Coverage Report

Created: 2023-06-07 06:50

/src/opencv/3rdparty/libtiff/tif_jpeg.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 1994-1997 Sam Leffler
3
 * Copyright (c) 1994-1997 Silicon Graphics, Inc.
4
 *
5
 * Permission to use, copy, modify, distribute, and sell this software and 
6
 * its documentation for any purpose is hereby granted without fee, provided
7
 * that (i) the above copyright notices and this permission notice appear in
8
 * all copies of the software and related documentation, and (ii) the names of
9
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
10
 * publicity relating to the software without the specific, prior written
11
 * permission of Sam Leffler and Silicon Graphics.
12
 * 
13
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
14
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
15
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
16
 * 
17
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
21
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
22
 * OF THIS SOFTWARE.
23
 */
24
25
#define WIN32_LEAN_AND_MEAN
26
#define VC_EXTRALEAN
27
28
#include "tiffiop.h"
29
#include <stdlib.h>
30
31
#ifdef JPEG_SUPPORT
32
33
/*
34
 * TIFF Library
35
 *
36
 * JPEG Compression support per TIFF Technical Note #2
37
 * (*not* per the original TIFF 6.0 spec).
38
 *
39
 * This file is simply an interface to the libjpeg library written by
40
 * the Independent JPEG Group.  You need release 5 or later of the IJG
41
 * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
42
 *
43
 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
44
 */
45
#include <setjmp.h>
46
47
int TIFFFillStrip(TIFF* tif, uint32 strip);
48
int TIFFFillTile(TIFF* tif, uint32 tile);
49
int TIFFReInitJPEG_12( TIFF *tif, int scheme, int is_encode );
50
int TIFFJPEGIsFullStripRequired_12(TIFF* tif);
51
52
/* We undefine FAR to avoid conflict with JPEG definition */
53
54
#ifdef FAR
55
#undef FAR
56
#endif
57
58
/*
59
  Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
60
  not defined.  Unfortunately, the MinGW and Borland compilers include
61
  a typedef for INT32, which causes a conflict.  MSVC does not include
62
  a conflicting typedef given the headers which are included.
63
*/
64
#if defined(__BORLANDC__) || defined(__MINGW32__)
65
# define XMD_H 1
66
#endif
67
68
/*
69
   The windows RPCNDR.H file defines boolean, but defines it with the
70
   unsigned char size.  You should compile JPEG library using appropriate
71
   definitions in jconfig.h header, but many users compile library in wrong
72
   way. That causes errors of the following type:
73
74
   "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
75
   caller expects 464"
76
77
   For such users we will fix the problem here. See install.doc file from
78
   the JPEG library distribution for details.
79
*/
80
81
/* Define "boolean" as unsigned char, not int, per Windows custom. */
82
#if defined(__WIN32__) && !defined(__MINGW32__)
83
# ifndef __RPCNDR_H__            /* don't conflict if rpcndr.h already read */
84
   typedef unsigned char boolean;
85
# endif
86
# define HAVE_BOOLEAN            /* prevent jmorecfg.h from redefining it */
87
#endif
88
89
#include "jpeglib.h"
90
#include "jerror.h"
91
92
/* 
93
 * Do we want to do special processing suitable for when JSAMPLE is a
94
 * 16bit value?  
95
 */
96
97
#if defined(JPEG_LIB_MK1)
98
#  define JPEG_LIB_MK1_OR_12BIT 1
99
#elif BITS_IN_JSAMPLE == 12
100
#  define JPEG_LIB_MK1_OR_12BIT 1
101
#endif
102
103
/*
104
 * We are using width_in_blocks which is supposed to be private to
105
 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
106
 * renamed this member to width_in_data_units.  Since the header has
107
 * also renamed a define, use that unique define name in order to
108
 * detect the problem header and adjust to suit.
109
 */
110
#if defined(D_MAX_DATA_UNITS_IN_MCU)
111
#define width_in_blocks width_in_data_units
112
#endif
113
114
/*
115
 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
116
 * in place of plain setjmp.  These macros will make it easier.
117
 */
118
0
#define SETJMP(jbuf)    setjmp(jbuf)
119
0
#define LONGJMP(jbuf,code)  longjmp(jbuf,code)
120
#define JMP_BUF     jmp_buf
121
122
typedef struct jpeg_destination_mgr jpeg_destination_mgr;
123
typedef struct jpeg_source_mgr jpeg_source_mgr;
124
typedef struct jpeg_error_mgr jpeg_error_mgr;
125
126
/*
127
 * State block for each open TIFF file using
128
 * libjpeg to do JPEG compression/decompression.
129
 *
130
 * libjpeg's visible state is either a jpeg_compress_struct
131
 * or jpeg_decompress_struct depending on which way we
132
 * are going.  comm can be used to refer to the fields
133
 * which are common to both.
134
 *
135
 * NB: cinfo is required to be the first member of JPEGState,
136
 *     so we can safely cast JPEGState* -> jpeg_xxx_struct*
137
 *     and vice versa!
138
 */
139
typedef struct {
140
  union {
141
    struct jpeg_compress_struct c;
142
    struct jpeg_decompress_struct d;
143
    struct jpeg_common_struct comm;
144
  } cinfo;      /* NB: must be first */
145
  int             cinfo_initialized;
146
147
  jpeg_error_mgr  err;    /* libjpeg error manager */
148
  JMP_BUF   exit_jmpbuf;  /* for catching libjpeg failures */
149
  
150
  struct jpeg_progress_mgr progress;
151
  /*
152
   * The following two members could be a union, but
153
   * they're small enough that it's not worth the effort.
154
   */
155
  jpeg_destination_mgr dest;  /* data dest for compression */
156
  jpeg_source_mgr src;    /* data source for decompression */
157
          /* private state */
158
  TIFF*   tif;    /* back link needed by some code */
159
  uint16    photometric;  /* copy of PhotometricInterpretation */
160
  uint16    h_sampling; /* luminance sampling factors */
161
  uint16    v_sampling;
162
  tmsize_t    bytesperline; /* decompressed bytes per scanline */
163
  /* pointers to intermediate buffers when processing downsampled data */
164
  JSAMPARRAY  ds_buffer[MAX_COMPONENTS];
165
  int   scancount;  /* number of "scanlines" accumulated */
166
  int   samplesperclump;
167
168
  TIFFVGetMethod  vgetparent; /* super-class method */
169
  TIFFVSetMethod  vsetparent; /* super-class method */
170
  TIFFPrintMethod printdir; /* super-class method */
171
  TIFFStripMethod defsparent; /* super-class method */
172
  TIFFTileMethod  deftparent; /* super-class method */
173
          /* pseudo-tag fields */
174
  void*   jpegtables; /* JPEGTables tag value, or NULL */
175
  uint32    jpegtables_length; /* number of bytes in same */
176
  int   jpegquality;  /* Compression quality level */
177
  int   jpegcolormode;  /* Auto RGB<=>YCbCr convert? */
178
  int   jpegtablesmode; /* What to put in JPEGTables */
179
180
        int             ycbcrsampling_fetched;
181
        int             max_allowed_scan_number;
182
} JPEGState;
183
184
0
#define JState(tif) ((JPEGState*)(tif)->tif_data)
185
186
static int JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
187
static int JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
188
static int JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
189
static int JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
190
static int JPEGInitializeLibJPEG(TIFF * tif, int decode );
191
static int DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
192
193
#define FIELD_JPEGTABLES  (FIELD_CODEC+0)
194
195
static const TIFFField jpegFields[] = {
196
    { TIFFTAG_JPEGTABLES, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_C32_UINT8, FIELD_JPEGTABLES, FALSE, TRUE, "JPEGTables", NULL },
197
    { TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "", NULL },
198
    { TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL },
199
    { TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL }
200
};
201
202
/*
203
 * libjpeg interface layer.
204
 *
205
 * We use setjmp/longjmp to return control to libtiff
206
 * when a fatal error is encountered within the JPEG
207
 * library.  We also direct libjpeg error and warning
208
 * messages through the appropriate libtiff handlers.
209
 */
210
211
/*
212
 * Error handling routines (these replace corresponding
213
 * IJG routines from jerror.c).  These are used for both
214
 * compression and decompression.
215
 */
216
static void
217
TIFFjpeg_error_exit(j_common_ptr cinfo)
218
0
{
219
0
  JPEGState *sp = (JPEGState *) cinfo;  /* NB: cinfo assumed first */
220
0
  char buffer[JMSG_LENGTH_MAX];
221
222
0
  (*cinfo->err->format_message) (cinfo, buffer);
223
0
  TIFFErrorExt(sp->tif->tif_clientdata, "JPEGLib", "%s", buffer);   /* display the error message */
224
0
  jpeg_abort(cinfo);      /* clean up libjpeg state */
225
0
  LONGJMP(sp->exit_jmpbuf, 1);   /* return to libtiff caller */
226
0
}
227
228
/*
229
 * This routine is invoked only for warning messages,
230
 * since error_exit does its own thing and trace_level
231
 * is never set > 0.
232
 */
233
static void
234
TIFFjpeg_output_message(j_common_ptr cinfo)
235
0
{
236
0
  char buffer[JMSG_LENGTH_MAX];
237
238
0
  (*cinfo->err->format_message) (cinfo, buffer);
239
0
  TIFFWarningExt(((JPEGState *) cinfo)->tif->tif_clientdata, "JPEGLib", "%s", buffer);
240
0
}
241
242
/* Avoid the risk of denial-of-service on crafted JPEGs with an insane */
243
/* number of scans. */
244
/* See http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf */
245
static void
246
TIFFjpeg_progress_monitor(j_common_ptr cinfo)
247
0
{
248
0
    JPEGState *sp = (JPEGState *) cinfo;  /* NB: cinfo assumed first */
249
0
    if (cinfo->is_decompressor)
250
0
    {
251
0
        const int scan_no =
252
0
            ((j_decompress_ptr)cinfo)->input_scan_number;
253
0
        if (scan_no >= sp->max_allowed_scan_number)
254
0
        {
255
0
            TIFFErrorExt(((JPEGState *) cinfo)->tif->tif_clientdata, 
256
0
                     "TIFFjpeg_progress_monitor",
257
0
                     "Scan number %d exceeds maximum scans (%d). This limit "
258
0
                     "can be raised through the LIBTIFF_JPEG_MAX_ALLOWED_SCAN_NUMBER "
259
0
                     "environment variable.",
260
0
                     scan_no, sp->max_allowed_scan_number);
261
262
0
            jpeg_abort(cinfo);      /* clean up libjpeg state */
263
0
            LONGJMP(sp->exit_jmpbuf, 1);   /* return to libtiff caller */
264
0
        }
265
0
    }
266
0
}
267
268
269
/*
270
 * Interface routines.  This layer of routines exists
271
 * primarily to limit side-effects from using setjmp.
272
 * Also, normal/error returns are converted into return
273
 * values per libtiff practice.
274
 */
275
0
#define CALLJPEG(sp, fail, op)  (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
276
0
#define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
277
278
static int
279
TIFFjpeg_create_compress(JPEGState* sp)
280
0
{
281
  /* initialize JPEG error handling */
282
0
  sp->cinfo.c.err = jpeg_std_error(&sp->err);
283
0
  sp->err.error_exit = TIFFjpeg_error_exit;
284
0
  sp->err.output_message = TIFFjpeg_output_message;
285
286
  /* set client_data to avoid UMR warning from tools like Purify */
287
0
  sp->cinfo.c.client_data = NULL;
288
289
0
  return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
290
0
}
291
292
static int
293
TIFFjpeg_create_decompress(JPEGState* sp)
294
0
{
295
  /* initialize JPEG error handling */
296
0
  sp->cinfo.d.err = jpeg_std_error(&sp->err);
297
0
  sp->err.error_exit = TIFFjpeg_error_exit;
298
0
  sp->err.output_message = TIFFjpeg_output_message;
299
300
  /* set client_data to avoid UMR warning from tools like Purify */
301
0
  sp->cinfo.d.client_data = NULL;
302
303
0
  return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
304
0
}
305
306
static int
307
TIFFjpeg_set_defaults(JPEGState* sp)
308
0
{
309
0
  return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
310
0
}
311
312
static int
313
TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
314
0
{
315
0
  return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
316
0
}
317
318
static int
319
TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
320
0
{
321
0
  return CALLVJPEG(sp,
322
0
      jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
323
0
}
324
325
static int
326
TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
327
0
{
328
0
  return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
329
0
}
330
331
static int
332
TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
333
0
{
334
0
  return CALLVJPEG(sp,
335
0
      jpeg_start_compress(&sp->cinfo.c, write_all_tables));
336
0
}
337
338
static int
339
TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
340
0
{
341
0
  return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
342
0
      scanlines, (JDIMENSION) num_lines));
343
0
}
344
345
static int
346
TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
347
0
{
348
0
  return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
349
0
      data, (JDIMENSION) num_lines));
350
0
}
351
352
static int
353
TIFFjpeg_finish_compress(JPEGState* sp)
354
0
{
355
0
  return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
356
0
}
357
358
static int
359
TIFFjpeg_write_tables(JPEGState* sp)
360
0
{
361
0
  return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
362
0
}
363
364
static int
365
TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
366
0
{
367
0
  return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
368
0
}
369
370
static int
371
TIFFjpeg_has_multiple_scans(JPEGState* sp)
372
0
{
373
0
  return CALLJPEG(sp, 0, jpeg_has_multiple_scans(&sp->cinfo.d));
374
0
}
375
376
static int
377
TIFFjpeg_start_decompress(JPEGState* sp)
378
0
{
379
0
        const char* sz_max_allowed_scan_number;
380
        /* progress monitor */
381
0
        sp->cinfo.d.progress = &sp->progress;
382
0
        sp->progress.progress_monitor = TIFFjpeg_progress_monitor;
383
0
        sp->max_allowed_scan_number = 100;
384
0
        sz_max_allowed_scan_number = getenv("LIBTIFF_JPEG_MAX_ALLOWED_SCAN_NUMBER");
385
0
        if( sz_max_allowed_scan_number )
386
0
            sp->max_allowed_scan_number = atoi(sz_max_allowed_scan_number);
387
388
0
  return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
389
0
}
390
391
static int
392
TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
393
0
{
394
0
  return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
395
0
      scanlines, (JDIMENSION) max_lines));
396
0
}
397
398
static int
399
TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
400
0
{
401
0
  return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
402
0
      data, (JDIMENSION) max_lines));
403
0
}
404
405
static int
406
TIFFjpeg_finish_decompress(JPEGState* sp)
407
0
{
408
0
  return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
409
0
}
410
411
static int
412
TIFFjpeg_abort(JPEGState* sp)
413
0
{
414
0
  return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
415
0
}
416
417
static int
418
TIFFjpeg_destroy(JPEGState* sp)
419
0
{
420
0
  return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
421
0
}
422
423
static JSAMPARRAY
424
TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
425
          JDIMENSION samplesperrow, JDIMENSION numrows)
426
0
{
427
0
  return CALLJPEG(sp, (JSAMPARRAY) NULL,
428
0
      (*sp->cinfo.comm.mem->alloc_sarray)
429
0
    (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
430
0
}
431
432
/*
433
 * JPEG library destination data manager.
434
 * These routines direct compressed data from libjpeg into the
435
 * libtiff output buffer.
436
 */
437
438
static void
439
std_init_destination(j_compress_ptr cinfo)
440
0
{
441
0
  JPEGState* sp = (JPEGState*) cinfo;
442
0
  TIFF* tif = sp->tif;
443
444
0
  sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
445
0
  sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
446
0
}
447
448
static boolean
449
std_empty_output_buffer(j_compress_ptr cinfo)
450
0
{
451
0
  JPEGState* sp = (JPEGState*) cinfo;
452
0
  TIFF* tif = sp->tif;
453
454
  /* the entire buffer has been filled */
455
0
  tif->tif_rawcc = tif->tif_rawdatasize;
456
457
#ifdef IPPJ_HUFF
458
       /*
459
        * The Intel IPP performance library does not necessarily fill up
460
        * the whole output buffer on each pass, so only dump out the parts
461
        * that have been filled.
462
        *   http://trac.osgeo.org/gdal/wiki/JpegIPP
463
        */
464
       if ( sp->dest.free_in_buffer >= 0 ) {
465
               tif->tif_rawcc = tif->tif_rawdatasize - sp->dest.free_in_buffer;
466
       }
467
#endif
468
469
0
  if( !TIFFFlushData1(tif) )
470
0
            return FALSE;
471
0
  sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
472
0
  sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
473
474
0
  return (TRUE);
475
0
}
476
477
static void
478
std_term_destination(j_compress_ptr cinfo)
479
0
{
480
0
  JPEGState* sp = (JPEGState*) cinfo;
481
0
  TIFF* tif = sp->tif;
482
483
0
  tif->tif_rawcp = (uint8*) sp->dest.next_output_byte;
484
0
  tif->tif_rawcc =
485
0
      tif->tif_rawdatasize - (tmsize_t) sp->dest.free_in_buffer;
486
  /* NB: libtiff does the final buffer flush */
487
0
}
488
489
static void
490
TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
491
0
{
492
0
  (void) tif;
493
0
  sp->cinfo.c.dest = &sp->dest;
494
0
  sp->dest.init_destination = std_init_destination;
495
0
  sp->dest.empty_output_buffer = std_empty_output_buffer;
496
0
  sp->dest.term_destination = std_term_destination;
497
0
}
498
499
/*
500
 * Alternate destination manager for outputting to JPEGTables field.
501
 */
502
503
static void
504
tables_init_destination(j_compress_ptr cinfo)
505
0
{
506
0
  JPEGState* sp = (JPEGState*) cinfo;
507
508
  /* while building, jpegtables_length is allocated buffer size */
509
0
  sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
510
0
  sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
511
0
}
512
513
static boolean
514
tables_empty_output_buffer(j_compress_ptr cinfo)
515
0
{
516
0
  JPEGState* sp = (JPEGState*) cinfo;
517
0
  void* newbuf;
518
519
  /* the entire buffer has been filled; enlarge it by 1000 bytes */
520
0
  newbuf = _TIFFrealloc((void*) sp->jpegtables,
521
0
            (tmsize_t) (sp->jpegtables_length + 1000));
522
0
  if (newbuf == NULL)
523
0
    ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
524
0
  sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
525
0
  sp->dest.free_in_buffer = (size_t) 1000;
526
0
  sp->jpegtables = newbuf;
527
0
  sp->jpegtables_length += 1000;
528
0
  return (TRUE);
529
0
}
530
531
static void
532
tables_term_destination(j_compress_ptr cinfo)
533
0
{
534
0
  JPEGState* sp = (JPEGState*) cinfo;
535
536
  /* set tables length to number of bytes actually emitted */
537
0
  sp->jpegtables_length -= (uint32) sp->dest.free_in_buffer;
538
0
}
539
540
static int
541
TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
542
0
{
543
0
  (void) tif;
544
  /*
545
   * Allocate a working buffer for building tables.
546
   * Initial size is 1000 bytes, which is usually adequate.
547
   */
548
0
  if (sp->jpegtables)
549
0
    _TIFFfree(sp->jpegtables);
550
0
  sp->jpegtables_length = 1000;
551
0
  sp->jpegtables = (void*) _TIFFmalloc((tmsize_t) sp->jpegtables_length);
552
0
  if (sp->jpegtables == NULL) {
553
0
    sp->jpegtables_length = 0;
554
0
    TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
555
0
    return (0);
556
0
  }
557
0
  sp->cinfo.c.dest = &sp->dest;
558
0
  sp->dest.init_destination = tables_init_destination;
559
0
  sp->dest.empty_output_buffer = tables_empty_output_buffer;
560
0
  sp->dest.term_destination = tables_term_destination;
561
0
  return (1);
562
0
}
563
564
/*
565
 * JPEG library source data manager.
566
 * These routines supply compressed data to libjpeg.
567
 */
568
569
static void
570
std_init_source(j_decompress_ptr cinfo)
571
0
{
572
0
  JPEGState* sp = (JPEGState*) cinfo;
573
0
  TIFF* tif = sp->tif;
574
575
0
  sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
576
0
  sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
577
0
}
578
579
static boolean
580
std_fill_input_buffer(j_decompress_ptr cinfo)
581
0
{
582
0
  JPEGState* sp = (JPEGState* ) cinfo;
583
0
  static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
584
585
#ifdef IPPJ_HUFF
586
        /*
587
         * The Intel IPP performance library does not necessarily read the whole
588
         * input buffer in one pass, so it is possible to get here with data
589
         * yet to read. 
590
         * 
591
         * We just return without doing anything, until the entire buffer has
592
         * been read.  
593
         * http://trac.osgeo.org/gdal/wiki/JpegIPP
594
         */
595
        if( sp->src.bytes_in_buffer > 0 ) {
596
            return (TRUE);
597
        }
598
#endif
599
600
  /*
601
         * Normally the whole strip/tile is read and so we don't need to do
602
         * a fill.  In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
603
         * all the data, but the rawdata is refreshed between scanlines and
604
         * we push this into the io machinery in JPEGDecode().   
605
         * http://trac.osgeo.org/gdal/ticket/3894
606
   */
607
        
608
0
  WARNMS(cinfo, JWRN_JPEG_EOF);
609
  /* insert a fake EOI marker */
610
0
  sp->src.next_input_byte = dummy_EOI;
611
0
  sp->src.bytes_in_buffer = 2;
612
0
  return (TRUE);
613
0
}
614
615
static void
616
std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
617
0
{
618
0
  JPEGState* sp = (JPEGState*) cinfo;
619
620
0
  if (num_bytes > 0) {
621
0
    if ((size_t)num_bytes > sp->src.bytes_in_buffer) {
622
      /* oops, buffer overrun */
623
0
      (void) std_fill_input_buffer(cinfo);
624
0
    } else {
625
0
      sp->src.next_input_byte += (size_t) num_bytes;
626
0
      sp->src.bytes_in_buffer -= (size_t) num_bytes;
627
0
    }
628
0
  }
629
0
}
630
631
static void
632
std_term_source(j_decompress_ptr cinfo)
633
0
{
634
  /* No work necessary here */
635
0
  (void) cinfo;
636
0
}
637
638
static void
639
TIFFjpeg_data_src(JPEGState* sp)
640
0
{
641
0
  sp->cinfo.d.src = &sp->src;
642
0
  sp->src.init_source = std_init_source;
643
0
  sp->src.fill_input_buffer = std_fill_input_buffer;
644
0
  sp->src.skip_input_data = std_skip_input_data;
645
0
  sp->src.resync_to_restart = jpeg_resync_to_restart;
646
0
  sp->src.term_source = std_term_source;
647
0
  sp->src.bytes_in_buffer = 0;    /* for safety */
648
0
  sp->src.next_input_byte = NULL;
649
0
}
650
651
/*
652
 * Alternate source manager for reading from JPEGTables.
653
 * We can share all the code except for the init routine.
654
 */
655
656
static void
657
tables_init_source(j_decompress_ptr cinfo)
658
0
{
659
0
  JPEGState* sp = (JPEGState*) cinfo;
660
661
0
  sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
662
0
  sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
663
0
}
664
665
static void
666
TIFFjpeg_tables_src(JPEGState* sp)
667
0
{
668
0
  TIFFjpeg_data_src(sp);
669
0
  sp->src.init_source = tables_init_source;
670
0
}
671
672
/*
673
 * Allocate downsampled-data buffers needed for downsampled I/O.
674
 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
675
 * We use libjpeg's allocator so that buffers will be released automatically
676
 * when done with strip/tile.
677
 * This is also a handy place to compute samplesperclump, bytesperline.
678
 */
679
static int
680
alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
681
        int num_components)
682
0
{
683
0
  JPEGState* sp = JState(tif);
684
0
  int ci;
685
0
  jpeg_component_info* compptr;
686
0
  JSAMPARRAY buf;
687
0
  int samples_per_clump = 0;
688
689
0
  for (ci = 0, compptr = comp_info; ci < num_components;
690
0
       ci++, compptr++) {
691
0
    samples_per_clump += compptr->h_samp_factor *
692
0
      compptr->v_samp_factor;
693
0
    buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
694
0
        compptr->width_in_blocks * DCTSIZE,
695
0
        (JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
696
0
    if (buf == NULL)
697
0
      return (0);
698
0
    sp->ds_buffer[ci] = buf;
699
0
  }
700
0
  sp->samplesperclump = samples_per_clump;
701
0
  return (1);
702
0
}
703
704
705
/*
706
 * JPEG Decoding.
707
 */
708
709
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
710
711
0
#define JPEG_MARKER_SOF0 0xC0
712
0
#define JPEG_MARKER_SOF1 0xC1
713
0
#define JPEG_MARKER_SOF2 0xC2
714
0
#define JPEG_MARKER_SOF9 0xC9
715
0
#define JPEG_MARKER_SOF10 0xCA
716
0
#define JPEG_MARKER_DHT 0xC4
717
0
#define JPEG_MARKER_SOI 0xD8
718
0
#define JPEG_MARKER_SOS 0xDA
719
0
#define JPEG_MARKER_DQT 0xDB
720
0
#define JPEG_MARKER_DRI 0xDD
721
0
#define JPEG_MARKER_APP0 0xE0
722
0
#define JPEG_MARKER_COM 0xFE
723
struct JPEGFixupTagsSubsamplingData
724
{
725
  TIFF* tif;
726
  void* buffer;
727
  uint32 buffersize;
728
  uint8* buffercurrentbyte;
729
  uint32 bufferbytesleft;
730
  uint64 fileoffset;
731
  uint64 filebytesleft;
732
  uint8 filepositioned;
733
};
734
static void JPEGFixupTagsSubsampling(TIFF* tif);
735
static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data);
736
static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result);
737
static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result);
738
static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength);
739
740
#endif
741
742
static int
743
JPEGFixupTags(TIFF* tif)
744
0
{
745
0
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
746
0
        JPEGState* sp = JState(tif);
747
0
  if ((tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR)&&
748
0
      (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&&
749
0
      (tif->tif_dir.td_samplesperpixel==3) &&
750
0
            !sp->ycbcrsampling_fetched)
751
0
    JPEGFixupTagsSubsampling(tif);
752
0
#endif
753
        
754
0
  return(1);
755
0
}
756
757
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
758
759
static void
760
JPEGFixupTagsSubsampling(TIFF* tif)
761
0
{
762
  /*
763
   * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
764
   * the TIFF tags, but still use non-default (2,2) values within the jpeg
765
   * data stream itself.  In order for TIFF applications to work properly
766
   * - for instance to get the strip buffer size right - it is imperative
767
   * that the subsampling be available before we start reading the image
768
   * data normally.  This function will attempt to analyze the first strip in
769
   * order to get the sampling values from the jpeg data stream.
770
   *
771
   * Note that JPEGPreDeocode() will produce a fairly loud warning when the
772
   * discovered sampling does not match the default sampling (2,2) or whatever
773
   * was actually in the tiff tags.
774
   *
775
   * See the bug in bugzilla for details:
776
   *
777
   * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
778
   *
779
   * Frank Warmerdam, July 2002
780
   * Joris Van Damme, May 2007
781
   */
782
0
  static const char module[] = "JPEGFixupTagsSubsampling";
783
0
  struct JPEGFixupTagsSubsamplingData m;
784
0
        uint64 fileoffset = TIFFGetStrileOffset(tif, 0);
785
786
0
        if( fileoffset == 0 )
787
0
        {
788
            /* Do not even try to check if the first strip/tile does not
789
               yet exist, as occurs when GDAL has created a new NULL file
790
               for instance. */
791
0
            return;
792
0
        }
793
794
0
  m.tif=tif;
795
0
  m.buffersize=2048;
796
0
  m.buffer=_TIFFmalloc(m.buffersize);
797
0
  if (m.buffer==NULL)
798
0
  {
799
0
    TIFFWarningExt(tif->tif_clientdata,module,
800
0
        "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
801
0
    return;
802
0
  }
803
0
  m.buffercurrentbyte=NULL;
804
0
  m.bufferbytesleft=0;
805
0
  m.fileoffset=fileoffset;
806
0
  m.filepositioned=0;
807
0
  m.filebytesleft=TIFFGetStrileByteCount(tif, 0);
808
0
  if (!JPEGFixupTagsSubsamplingSec(&m))
809
0
    TIFFWarningExt(tif->tif_clientdata,module,
810
0
        "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
811
0
  _TIFFfree(m.buffer);
812
0
}
813
814
static int
815
JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
816
0
{
817
0
  static const char module[] = "JPEGFixupTagsSubsamplingSec";
818
0
  uint8 m;
819
0
  while (1)
820
0
  {
821
0
    while (1)
822
0
    {
823
0
      if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
824
0
        return(0);
825
0
      if (m==255)
826
0
        break;
827
0
    }
828
0
    while (1)
829
0
    {
830
0
      if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
831
0
        return(0);
832
0
      if (m!=255)
833
0
        break;
834
0
    }
835
0
    switch (m)
836
0
    {
837
0
      case JPEG_MARKER_SOI:
838
        /* this type of marker has no data and should be skipped */
839
0
        break;
840
0
      case JPEG_MARKER_COM:
841
0
      case JPEG_MARKER_APP0:
842
0
      case JPEG_MARKER_APP0+1:
843
0
      case JPEG_MARKER_APP0+2:
844
0
      case JPEG_MARKER_APP0+3:
845
0
      case JPEG_MARKER_APP0+4:
846
0
      case JPEG_MARKER_APP0+5:
847
0
      case JPEG_MARKER_APP0+6:
848
0
      case JPEG_MARKER_APP0+7:
849
0
      case JPEG_MARKER_APP0+8:
850
0
      case JPEG_MARKER_APP0+9:
851
0
      case JPEG_MARKER_APP0+10:
852
0
      case JPEG_MARKER_APP0+11:
853
0
      case JPEG_MARKER_APP0+12:
854
0
      case JPEG_MARKER_APP0+13:
855
0
      case JPEG_MARKER_APP0+14:
856
0
      case JPEG_MARKER_APP0+15:
857
0
      case JPEG_MARKER_DQT:
858
0
      case JPEG_MARKER_SOS:
859
0
      case JPEG_MARKER_DHT:
860
0
      case JPEG_MARKER_DRI:
861
        /* this type of marker has data, but it has no use to us and should be skipped */
862
0
        {
863
0
          uint16 n;
864
0
          if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
865
0
            return(0);
866
0
          if (n<2)
867
0
            return(0);
868
0
          n-=2;
869
0
          if (n>0)
870
0
            JPEGFixupTagsSubsamplingSkip(data,n);
871
0
        }
872
0
        break;
873
0
      case JPEG_MARKER_SOF0: /* Baseline sequential Huffman */
874
0
      case JPEG_MARKER_SOF1: /* Extended sequential Huffman */
875
0
      case JPEG_MARKER_SOF2: /* Progressive Huffman: normally not allowed by TechNote, but that doesn't hurt supporting it */
876
0
      case JPEG_MARKER_SOF9: /* Extended sequential arithmetic */
877
0
      case JPEG_MARKER_SOF10: /* Progressive arithmetic: normally not allowed by TechNote, but that doesn't hurt supporting it */
878
        /* this marker contains the subsampling factors we're scanning for */
879
0
        {
880
0
          uint16 n;
881
0
          uint16 o;
882
0
          uint8 p;
883
0
          uint8 ph,pv;
884
0
          if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
885
0
            return(0);
886
0
          if (n!=8+data->tif->tif_dir.td_samplesperpixel*3)
887
0
            return(0);
888
0
          JPEGFixupTagsSubsamplingSkip(data,7);
889
0
          if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
890
0
            return(0);
891
0
          ph=(p>>4);
892
0
          pv=(p&15);
893
0
          JPEGFixupTagsSubsamplingSkip(data,1);
894
0
          for (o=1; o<data->tif->tif_dir.td_samplesperpixel; o++)
895
0
          {
896
0
            JPEGFixupTagsSubsamplingSkip(data,1);
897
0
            if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
898
0
              return(0);
899
0
            if (p!=0x11)
900
0
            {
901
0
              TIFFWarningExt(data->tif->tif_clientdata,module,
902
0
                  "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
903
0
              return(1);
904
0
            }
905
0
            JPEGFixupTagsSubsamplingSkip(data,1);
906
0
          }
907
0
          if (((ph!=1)&&(ph!=2)&&(ph!=4))||((pv!=1)&&(pv!=2)&&(pv!=4)))
908
0
          {
909
0
            TIFFWarningExt(data->tif->tif_clientdata,module,
910
0
                "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
911
0
            return(1);
912
0
          }
913
0
          if ((ph!=data->tif->tif_dir.td_ycbcrsubsampling[0])||(pv!=data->tif->tif_dir.td_ycbcrsubsampling[1]))
914
0
          {
915
0
            TIFFWarningExt(data->tif->tif_clientdata,module,
916
0
                "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
917
0
                (int)data->tif->tif_dir.td_ycbcrsubsampling[0],
918
0
                (int)data->tif->tif_dir.td_ycbcrsubsampling[1],
919
0
                (int)ph,(int)pv);
920
0
            data->tif->tif_dir.td_ycbcrsubsampling[0]=ph;
921
0
            data->tif->tif_dir.td_ycbcrsubsampling[1]=pv;
922
0
          }
923
0
        }
924
0
        return(1);
925
0
      default:
926
0
        return(0);
927
0
    }
928
0
  }
929
0
}
930
931
static int
932
JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result)
933
0
{
934
0
  if (data->bufferbytesleft==0)
935
0
  {
936
0
    uint32 m;
937
0
    if (data->filebytesleft==0)
938
0
      return(0);
939
0
    if (!data->filepositioned)
940
0
    {
941
0
      if (TIFFSeekFile(data->tif,data->fileoffset,SEEK_SET) == (toff_t)-1)
942
0
      {
943
0
          return 0;
944
0
      }
945
0
      data->filepositioned=1;
946
0
    }
947
0
    m=data->buffersize;
948
0
    if ((uint64)m>data->filebytesleft)
949
0
      m=(uint32)data->filebytesleft;
950
0
    assert(m<0x80000000UL);
951
0
    if (TIFFReadFile(data->tif,data->buffer,(tmsize_t)m)!=(tmsize_t)m)
952
0
      return(0);
953
0
    data->buffercurrentbyte=data->buffer;
954
0
    data->bufferbytesleft=m;
955
0
    data->fileoffset+=m;
956
0
    data->filebytesleft-=m;
957
0
  }
958
0
  *result=*data->buffercurrentbyte;
959
0
  data->buffercurrentbyte++;
960
0
  data->bufferbytesleft--;
961
0
  return(1);
962
0
}
963
964
static int
965
JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result)
966
0
{
967
0
  uint8 ma;
968
0
  uint8 mb;
969
0
  if (!JPEGFixupTagsSubsamplingReadByte(data,&ma))
970
0
    return(0);
971
0
  if (!JPEGFixupTagsSubsamplingReadByte(data,&mb))
972
0
    return(0);
973
0
  *result=(ma<<8)|mb;
974
0
  return(1);
975
0
}
976
977
static void
978
JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength)
979
0
{
980
0
  if ((uint32)skiplength<=data->bufferbytesleft)
981
0
  {
982
0
    data->buffercurrentbyte+=skiplength;
983
0
    data->bufferbytesleft-=skiplength;
984
0
  }
985
0
  else
986
0
  {
987
0
    uint16 m;
988
0
    m=(uint16)(skiplength-data->bufferbytesleft);
989
0
    if (m<=data->filebytesleft)
990
0
    {
991
0
      data->bufferbytesleft=0;
992
0
      data->fileoffset+=m;
993
0
      data->filebytesleft-=m;
994
0
      data->filepositioned=0;
995
0
    }
996
0
    else
997
0
    {
998
0
      data->bufferbytesleft=0;
999
0
      data->filebytesleft=0;
1000
0
    }
1001
0
  }
1002
0
}
1003
1004
#endif
1005
1006
1007
static int
1008
JPEGSetupDecode(TIFF* tif)
1009
0
{
1010
0
  JPEGState* sp = JState(tif);
1011
0
  TIFFDirectory *td = &tif->tif_dir;
1012
1013
#if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
1014
        if( tif->tif_dir.td_bitspersample == 12 )
1015
            return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 0 );
1016
#endif
1017
1018
0
  JPEGInitializeLibJPEG( tif, TRUE );
1019
1020
0
  assert(sp != NULL);
1021
0
  assert(sp->cinfo.comm.is_decompressor);
1022
1023
  /* Read JPEGTables if it is present */
1024
0
  if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
1025
0
    TIFFjpeg_tables_src(sp);
1026
0
    if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
1027
0
      TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
1028
0
      return (0);
1029
0
    }
1030
0
  }
1031
1032
  /* Grab parameters that are same for all strips/tiles */
1033
0
  sp->photometric = td->td_photometric;
1034
0
  switch (sp->photometric) {
1035
0
  case PHOTOMETRIC_YCBCR:
1036
0
    sp->h_sampling = td->td_ycbcrsubsampling[0];
1037
0
    sp->v_sampling = td->td_ycbcrsubsampling[1];
1038
0
    break;
1039
0
  default:
1040
    /* TIFF 6.0 forbids subsampling of all other color spaces */
1041
0
    sp->h_sampling = 1;
1042
0
    sp->v_sampling = 1;
1043
0
    break;
1044
0
  }
1045
1046
  /* Set up for reading normal data */
1047
0
  TIFFjpeg_data_src(sp);
1048
0
  tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
1049
0
  return (1);
1050
0
}
1051
1052
/* Returns 1 if the full strip should be read, even when doing scanline per */
1053
/* scanline decoding. This happens when the JPEG stream uses multiple scans. */
1054
/* Currently only called in CHUNKY_STRIP_READ_SUPPORT mode through */
1055
/* scanline interface. */
1056
/* Only reads tif->tif_dir.td_bitspersample, tif->tif_rawdata and */
1057
/* tif->tif_rawcc members. */
1058
/* Can be called independently of the usual setup/predecode/decode states */
1059
int TIFFJPEGIsFullStripRequired(TIFF* tif)
1060
0
{
1061
0
    int ret;
1062
0
    JPEGState state;
1063
1064
#if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFJPEGIsFullStripRequired)
1065
    if( tif->tif_dir.td_bitspersample == 12 )
1066
        return TIFFJPEGIsFullStripRequired_12( tif );
1067
#endif
1068
1069
0
    memset(&state, 0, sizeof(JPEGState));
1070
0
    state.tif = tif;
1071
1072
0
    TIFFjpeg_create_decompress(&state);
1073
1074
0
    TIFFjpeg_data_src(&state);
1075
1076
0
    if (TIFFjpeg_read_header(&state, TRUE) != JPEG_HEADER_OK)
1077
0
    {
1078
0
        TIFFjpeg_destroy(&state);
1079
0
        return (0);
1080
0
    }
1081
0
    ret = TIFFjpeg_has_multiple_scans(&state);
1082
1083
0
    TIFFjpeg_destroy(&state);
1084
1085
0
    return ret;
1086
0
}
1087
1088
/*
1089
 * Set up for decoding a strip or tile.
1090
 */
1091
/*ARGSUSED*/ static int
1092
JPEGPreDecode(TIFF* tif, uint16 s)
1093
0
{
1094
0
  JPEGState *sp = JState(tif);
1095
0
  TIFFDirectory *td = &tif->tif_dir;
1096
0
  static const char module[] = "JPEGPreDecode";
1097
0
  uint32 segment_width, segment_height;
1098
0
  int downsampled_output;
1099
0
  int ci;
1100
1101
0
  assert(sp != NULL);
1102
  
1103
0
  if (sp->cinfo.comm.is_decompressor == 0)
1104
0
  {
1105
0
    tif->tif_setupdecode( tif );
1106
0
  }
1107
  
1108
0
  assert(sp->cinfo.comm.is_decompressor);
1109
  /*
1110
   * Reset decoder state from any previous strip/tile,
1111
   * in case application didn't read the whole strip.
1112
   */
1113
0
  if (!TIFFjpeg_abort(sp))
1114
0
    return (0);
1115
  /*
1116
   * Read the header for this strip/tile.
1117
   */
1118
        
1119
0
  if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
1120
0
    return (0);
1121
1122
0
        tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
1123
0
        tif->tif_rawcc = sp->src.bytes_in_buffer;
1124
1125
  /*
1126
   * Check image parameters and set decompression parameters.
1127
   */
1128
0
  if (isTiled(tif)) {
1129
0
                segment_width = td->td_tilewidth;
1130
0
                segment_height = td->td_tilelength;
1131
0
    sp->bytesperline = TIFFTileRowSize(tif);
1132
0
  } else {
1133
0
    segment_width = td->td_imagewidth;
1134
0
    segment_height = td->td_imagelength - tif->tif_row;
1135
0
    if (segment_height > td->td_rowsperstrip)
1136
0
      segment_height = td->td_rowsperstrip;
1137
0
    sp->bytesperline = TIFFScanlineSize(tif);
1138
0
  }
1139
0
  if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1140
    /*
1141
     * For PC 2, scale down the expected strip/tile size
1142
     * to match a downsampled component
1143
     */
1144
0
    segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
1145
0
    segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1146
0
  }
1147
0
  if (sp->cinfo.d.image_width < segment_width ||
1148
0
      sp->cinfo.d.image_height < segment_height) {
1149
0
    TIFFWarningExt(tif->tif_clientdata, module,
1150
0
             "Improper JPEG strip/tile size, "
1151
0
             "expected %dx%d, got %dx%d",
1152
0
             segment_width, segment_height,
1153
0
             sp->cinfo.d.image_width,
1154
0
             sp->cinfo.d.image_height);
1155
0
  }
1156
0
  if( sp->cinfo.d.image_width == segment_width &&
1157
0
      sp->cinfo.d.image_height > segment_height &&
1158
0
      tif->tif_row + segment_height == td->td_imagelength &&
1159
0
      !isTiled(tif) ) {
1160
    /* Some files have a last strip, that should be truncated, */
1161
    /* but their JPEG codestream has still the maximum strip */
1162
    /* height. Warn about this as this is non compliant, but */
1163
    /* we can safely recover from that. */
1164
0
    TIFFWarningExt(tif->tif_clientdata, module,
1165
0
           "JPEG strip size exceeds expected dimensions,"
1166
0
           " expected %dx%d, got %dx%d",
1167
0
           segment_width, segment_height,
1168
0
           sp->cinfo.d.image_width, sp->cinfo.d.image_height);
1169
0
  }
1170
0
  else if (sp->cinfo.d.image_width > segment_width ||
1171
0
     sp->cinfo.d.image_height > segment_height) {
1172
    /*
1173
     * This case could be dangerous, if the strip or tile size has
1174
     * been reported as less than the amount of data jpeg will
1175
     * return, some potential security issues arise. Catch this
1176
     * case and error out.
1177
     */
1178
0
    TIFFErrorExt(tif->tif_clientdata, module,
1179
0
           "JPEG strip/tile size exceeds expected dimensions,"
1180
0
           " expected %dx%d, got %dx%d",
1181
0
           segment_width, segment_height,
1182
0
           sp->cinfo.d.image_width, sp->cinfo.d.image_height);
1183
0
    return (0);
1184
0
  }
1185
0
  if (sp->cinfo.d.num_components !=
1186
0
      (td->td_planarconfig == PLANARCONFIG_CONTIG ?
1187
0
       td->td_samplesperpixel : 1)) {
1188
0
    TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG component count");
1189
0
    return (0);
1190
0
  }
1191
#ifdef JPEG_LIB_MK1
1192
  if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
1193
    TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
1194
    return (0);
1195
  }
1196
  sp->cinfo.d.data_precision = td->td_bitspersample;
1197
  sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
1198
#else
1199
0
  if (sp->cinfo.d.data_precision != td->td_bitspersample) {
1200
0
    TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
1201
0
    return (0);
1202
0
  }
1203
0
#endif
1204
1205
        /* In some cases, libjpeg needs to allocate a lot of memory */
1206
        /* http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf */
1207
0
        if( TIFFjpeg_has_multiple_scans(sp) )
1208
0
        {
1209
            /* In this case libjpeg will need to allocate memory or backing */
1210
            /* store for all coefficients */
1211
            /* See call to jinit_d_coef_controller() from master_selection() */
1212
            /* in libjpeg */
1213
1214
            /* 1 MB for regular libjpeg usage */
1215
0
            toff_t nRequiredMemory = 1024 * 1024;
1216
1217
0
            for (ci = 0; ci < sp->cinfo.d.num_components; ci++) {
1218
0
                const jpeg_component_info *compptr = &(sp->cinfo.d.comp_info[ci]);
1219
0
                if( compptr->h_samp_factor > 0 && compptr->v_samp_factor > 0 )
1220
0
                {
1221
0
                    nRequiredMemory += (toff_t)(
1222
0
                        ((compptr->width_in_blocks + compptr->h_samp_factor - 1) / compptr->h_samp_factor)) *
1223
0
                        ((compptr->height_in_blocks + compptr->v_samp_factor - 1) / compptr->v_samp_factor) *
1224
0
                        sizeof(JBLOCK);
1225
0
                }
1226
0
            }
1227
1228
0
            if( sp->cinfo.d.mem->max_memory_to_use > 0 &&
1229
0
                nRequiredMemory > (toff_t)(sp->cinfo.d.mem->max_memory_to_use) &&
1230
0
                getenv("LIBTIFF_ALLOW_LARGE_LIBJPEG_MEM_ALLOC") == NULL )
1231
0
            {
1232
0
                TIFFErrorExt(tif->tif_clientdata, module,
1233
0
                    "Reading this image would require libjpeg to allocate "
1234
0
                    "at least %u bytes. "
1235
0
                    "This is disabled since above the %u threshold. "
1236
0
                    "You may override this restriction by defining the "
1237
0
                    "LIBTIFF_ALLOW_LARGE_LIBJPEG_MEM_ALLOC environment variable, "
1238
0
                    "or setting the JPEGMEM environment variable to a value greater "
1239
0
                    "or equal to '%uM'",
1240
0
                    (unsigned)(nRequiredMemory),
1241
0
                    (unsigned)(sp->cinfo.d.mem->max_memory_to_use),
1242
0
                    (unsigned)((nRequiredMemory + 1000000 - 1) / 1000000));
1243
0
                return 0;
1244
0
            }
1245
0
        }
1246
1247
0
  if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1248
    /* Component 0 should have expected sampling factors */
1249
0
    if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
1250
0
        sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
1251
0
      TIFFErrorExt(tif->tif_clientdata, module,
1252
0
               "Improper JPEG sampling factors %d,%d\n"
1253
0
               "Apparently should be %d,%d.",
1254
0
               sp->cinfo.d.comp_info[0].h_samp_factor,
1255
0
               sp->cinfo.d.comp_info[0].v_samp_factor,
1256
0
               sp->h_sampling, sp->v_sampling);
1257
0
      return (0);
1258
0
    }
1259
    /* Rest should have sampling factors 1,1 */
1260
0
    for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
1261
0
      if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
1262
0
          sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
1263
0
        TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
1264
0
        return (0);
1265
0
      }
1266
0
    }
1267
0
  } else {
1268
    /* PC 2's single component should have sampling factors 1,1 */
1269
0
    if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
1270
0
        sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
1271
0
      TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
1272
0
      return (0);
1273
0
    }
1274
0
  }
1275
0
  downsampled_output = FALSE;
1276
0
  if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1277
0
      sp->photometric == PHOTOMETRIC_YCBCR &&
1278
0
      sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1279
    /* Convert YCbCr to RGB */
1280
0
    sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
1281
0
    sp->cinfo.d.out_color_space = JCS_RGB;
1282
0
  } else {
1283
    /* Suppress colorspace handling */
1284
0
    sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
1285
0
    sp->cinfo.d.out_color_space = JCS_UNKNOWN;
1286
0
    if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1287
0
        (sp->h_sampling != 1 || sp->v_sampling != 1))
1288
0
      downsampled_output = TRUE;
1289
    /* XXX what about up-sampling? */
1290
0
  }
1291
0
  if (downsampled_output) {
1292
    /* Need to use raw-data interface to libjpeg */
1293
0
    sp->cinfo.d.raw_data_out = TRUE;
1294
#if JPEG_LIB_VERSION >= 70
1295
    sp->cinfo.d.do_fancy_upsampling = FALSE;
1296
#endif /* JPEG_LIB_VERSION >= 70 */
1297
0
    tif->tif_decoderow = DecodeRowError;
1298
0
    tif->tif_decodestrip = JPEGDecodeRaw;
1299
0
    tif->tif_decodetile = JPEGDecodeRaw;
1300
0
  } else {
1301
    /* Use normal interface to libjpeg */
1302
0
    sp->cinfo.d.raw_data_out = FALSE;
1303
0
    tif->tif_decoderow = JPEGDecode;
1304
0
    tif->tif_decodestrip = JPEGDecode;
1305
0
    tif->tif_decodetile = JPEGDecode;  
1306
0
  }
1307
  /* Start JPEG decompressor */
1308
0
  if (!TIFFjpeg_start_decompress(sp))
1309
0
    return (0);
1310
  /* Allocate downsampled-data buffers if needed */
1311
0
  if (downsampled_output) {
1312
0
    if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
1313
0
                 sp->cinfo.d.num_components))
1314
0
      return (0);
1315
0
    sp->scancount = DCTSIZE; /* mark buffer empty */
1316
0
  }
1317
0
  return (1);
1318
0
}
1319
1320
/*
1321
 * Decode a chunk of pixels.
1322
 * "Standard" case: returned data is not downsampled.
1323
 */
1324
#if !JPEG_LIB_MK1_OR_12BIT
1325
static int
1326
JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1327
0
{
1328
0
  JPEGState *sp = JState(tif);
1329
0
  tmsize_t nrows;
1330
0
  (void) s;
1331
1332
        /*
1333
        ** Update available information, buffer may have been refilled
1334
        ** between decode requests
1335
        */
1336
0
  sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
1337
0
  sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
1338
1339
0
        if( sp->bytesperline == 0 )
1340
0
                return 0;
1341
        
1342
0
  nrows = cc / sp->bytesperline;
1343
0
  if (cc % sp->bytesperline)
1344
0
    TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
1345
0
                               "fractional scanline not read");
1346
1347
0
  if( nrows > (tmsize_t) sp->cinfo.d.image_height )
1348
0
    nrows = sp->cinfo.d.image_height;
1349
1350
  /* data is expected to be read in multiples of a scanline */
1351
0
  if (nrows)
1352
0
        {
1353
0
                do
1354
0
                {
1355
                        /*
1356
                         * In the libjpeg6b-9a 8bit case.  We read directly into
1357
                         * the TIFF buffer.
1358
                         */
1359
0
                        JSAMPROW bufptr = (JSAMPROW)buf;
1360
1361
0
                        if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
1362
0
                                return (0);
1363
1364
0
                        ++tif->tif_row;
1365
0
                        buf += sp->bytesperline;
1366
0
                        cc -= sp->bytesperline;
1367
0
                } while (--nrows > 0);
1368
0
        }
1369
1370
        /* Update information on consumed data */
1371
0
        tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
1372
0
        tif->tif_rawcc = sp->src.bytes_in_buffer;
1373
                
1374
  /* Close down the decompressor if we've finished the strip or tile. */
1375
0
  return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1376
0
                || TIFFjpeg_finish_decompress(sp);
1377
0
}
1378
#endif /* !JPEG_LIB_MK1_OR_12BIT */
1379
1380
#if JPEG_LIB_MK1_OR_12BIT
1381
/*ARGSUSED*/ static int
1382
JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1383
{
1384
  JPEGState *sp = JState(tif);
1385
  tmsize_t nrows;
1386
  (void) s;
1387
1388
        /*
1389
        ** Update available information, buffer may have been refilled
1390
        ** between decode requests
1391
        */
1392
  sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
1393
  sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
1394
1395
        if( sp->bytesperline == 0 )
1396
                return 0;
1397
        
1398
  nrows = cc / sp->bytesperline;
1399
  if (cc % sp->bytesperline)
1400
    TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
1401
                               "fractional scanline not read");
1402
1403
  if( nrows > (tmsize_t) sp->cinfo.d.image_height )
1404
    nrows = sp->cinfo.d.image_height;
1405
1406
  /* data is expected to be read in multiples of a scanline */
1407
  if (nrows)
1408
        {
1409
                JSAMPROW line_work_buf = NULL;
1410
1411
                /*
1412
                 * For 6B, only use temporary buffer for 12 bit imagery.
1413
                 * For Mk1 always use it.
1414
                 */
1415
                if( sp->cinfo.d.data_precision == 12 )
1416
                {
1417
                        line_work_buf = (JSAMPROW)
1418
                                _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
1419
                                            * sp->cinfo.d.num_components );
1420
                }
1421
1422
               do
1423
               {
1424
                       if( line_work_buf != NULL )
1425
                       {
1426
                               /*
1427
                                * In the MK1 case, we always read into a 16bit
1428
                                * buffer, and then pack down to 12bit or 8bit.
1429
                                * In 6B case we only read into 16 bit buffer
1430
                                * for 12bit data, which we need to repack.
1431
                                */
1432
                               if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
1433
                                       return (0);
1434
1435
                               if( sp->cinfo.d.data_precision == 12 )
1436
                               {
1437
                                       int value_pairs = (sp->cinfo.d.output_width
1438
                                                          * sp->cinfo.d.num_components) / 2;
1439
                                       int iPair;
1440
1441
                                       for( iPair = 0; iPair < value_pairs; iPair++ )
1442
                                       {
1443
                                               unsigned char *out_ptr =
1444
                                                       ((unsigned char *) buf) + iPair * 3;
1445
                                               JSAMPLE *in_ptr = line_work_buf + iPair * 2;
1446
1447
                                               out_ptr[0] = (unsigned char)((in_ptr[0] & 0xff0) >> 4);
1448
                                               out_ptr[1] = (unsigned char)(((in_ptr[0] & 0xf) << 4)
1449
                                                       | ((in_ptr[1] & 0xf00) >> 8));
1450
                                               out_ptr[2] = (unsigned char)(((in_ptr[1] & 0xff) >> 0));
1451
                                       }
1452
                               }
1453
                               else if( sp->cinfo.d.data_precision == 8 )
1454
                               {
1455
                                       int value_count = (sp->cinfo.d.output_width
1456
                                                          * sp->cinfo.d.num_components);
1457
                                       int iValue;
1458
1459
                                       for( iValue = 0; iValue < value_count; iValue++ )
1460
                                       {
1461
                                               ((unsigned char *) buf)[iValue] =
1462
                                                       line_work_buf[iValue] & 0xff;
1463
                                       }
1464
                               }
1465
                       }
1466
1467
                       ++tif->tif_row;
1468
                       buf += sp->bytesperline;
1469
                       cc -= sp->bytesperline;
1470
               } while (--nrows > 0);
1471
1472
               if( line_work_buf != NULL )
1473
                       _TIFFfree( line_work_buf );
1474
        }
1475
1476
        /* Update information on consumed data */
1477
        tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
1478
        tif->tif_rawcc = sp->src.bytes_in_buffer;
1479
                
1480
  /* Close down the decompressor if we've finished the strip or tile. */
1481
  return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1482
                || TIFFjpeg_finish_decompress(sp);
1483
}
1484
#endif /* JPEG_LIB_MK1_OR_12BIT */
1485
1486
/*ARGSUSED*/ static int
1487
DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1488
1489
0
{
1490
0
    (void) buf;
1491
0
    (void) cc;
1492
0
    (void) s;
1493
1494
0
    TIFFErrorExt(tif->tif_clientdata, "TIFFReadScanline",
1495
0
                 "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
1496
0
    return 0;
1497
0
}
1498
1499
/*
1500
 * Decode a chunk of pixels.
1501
 * Returned data is downsampled per sampling factors.
1502
 */
1503
/*ARGSUSED*/ static int
1504
JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1505
0
{
1506
0
  JPEGState *sp = JState(tif);
1507
0
  tmsize_t nrows;
1508
0
        TIFFDirectory *td = &tif->tif_dir;
1509
0
  (void) s;
1510
1511
0
        nrows = sp->cinfo.d.image_height;
1512
        /* For last strip, limit number of rows to its truncated height */
1513
        /* even if the codestream height is larger (which is not compliant, */
1514
        /* but that we tolerate) */
1515
0
        if( (uint32)nrows > td->td_imagelength - tif->tif_row && !isTiled(tif) )
1516
0
            nrows = td->td_imagelength - tif->tif_row;
1517
1518
  /* data is expected to be read in multiples of a scanline */
1519
0
  if ( nrows != 0 ) {
1520
1521
    /* Cb,Cr both have sampling factors 1, so this is correct */
1522
0
    JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;            
1523
0
    int samples_per_clump = sp->samplesperclump;
1524
1525
#if defined(JPEG_LIB_MK1_OR_12BIT)
1526
    unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
1527
                 sp->cinfo.d.output_width *
1528
                 sp->cinfo.d.num_components);
1529
    if(tmpbuf==NULL) {
1530
                        TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1531
             "Out of memory");
1532
      return 0;
1533
                }
1534
#endif
1535
1536
0
    do {
1537
0
      jpeg_component_info *compptr;
1538
0
      int ci, clumpoffset;
1539
1540
0
                        if( cc < sp->bytesperline ) {
1541
0
        TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1542
0
               "application buffer not large enough for all data.");
1543
0
        return 0;
1544
0
                        }
1545
1546
      /* Reload downsampled-data buffer if needed */
1547
0
      if (sp->scancount >= DCTSIZE) {
1548
0
        int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
1549
0
        if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
1550
0
          return (0);
1551
0
        sp->scancount = 0;
1552
0
      }
1553
      /*
1554
       * Fastest way to unseparate data is to make one pass
1555
       * over the scanline for each row of each component.
1556
       */
1557
0
      clumpoffset = 0;    /* first sample in clump */
1558
0
      for (ci = 0, compptr = sp->cinfo.d.comp_info;
1559
0
           ci < sp->cinfo.d.num_components;
1560
0
           ci++, compptr++) {
1561
0
        int hsamp = compptr->h_samp_factor;
1562
0
        int vsamp = compptr->v_samp_factor;
1563
0
        int ypos;
1564
1565
0
        for (ypos = 0; ypos < vsamp; ypos++) {
1566
0
          JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1567
0
          JDIMENSION nclump;
1568
#if defined(JPEG_LIB_MK1_OR_12BIT)
1569
          JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
1570
#else
1571
0
          JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
1572
0
          if (cc < (tmsize_t)(clumpoffset + (tmsize_t)samples_per_clump*(clumps_per_line-1) + hsamp)) {
1573
0
            TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1574
0
                   "application buffer not large enough for all data, possible subsampling issue");
1575
0
            return 0;
1576
0
          }
1577
0
#endif
1578
1579
0
          if (hsamp == 1) {
1580
            /* fast path for at least Cb and Cr */
1581
0
            for (nclump = clumps_per_line; nclump-- > 0; ) {
1582
0
              outptr[0] = *inptr++;
1583
0
              outptr += samples_per_clump;
1584
0
            }
1585
0
          } else {
1586
0
            int xpos;
1587
1588
            /* general case */
1589
0
            for (nclump = clumps_per_line; nclump-- > 0; ) {
1590
0
              for (xpos = 0; xpos < hsamp; xpos++)
1591
0
                outptr[xpos] = *inptr++;
1592
0
              outptr += samples_per_clump;
1593
0
            }
1594
0
          }
1595
0
          clumpoffset += hsamp;
1596
0
        }
1597
0
      }
1598
1599
#if defined(JPEG_LIB_MK1_OR_12BIT)
1600
      {
1601
        if (sp->cinfo.d.data_precision == 8)
1602
        {
1603
          int i=0;
1604
          int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
1605
          for (i=0; i<len; i++)
1606
          {
1607
            ((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
1608
          }
1609
        }
1610
        else
1611
        {         /* 12-bit */
1612
          int value_pairs = (sp->cinfo.d.output_width
1613
                 * sp->cinfo.d.num_components) / 2;
1614
          int iPair;
1615
          for( iPair = 0; iPair < value_pairs; iPair++ )
1616
          {
1617
            unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
1618
            JSAMPLE *in_ptr = (JSAMPLE *) (tmpbuf + iPair * 2);
1619
            out_ptr[0] = (unsigned char)((in_ptr[0] & 0xff0) >> 4);
1620
            out_ptr[1] = (unsigned char)(((in_ptr[0] & 0xf) << 4)
1621
              | ((in_ptr[1] & 0xf00) >> 8));
1622
            out_ptr[2] = (unsigned char)(((in_ptr[1] & 0xff) >> 0));
1623
          }
1624
        }
1625
      }
1626
#endif
1627
1628
0
      sp->scancount ++;
1629
0
      tif->tif_row += sp->v_sampling;
1630
1631
0
      buf += sp->bytesperline;
1632
0
      cc -= sp->bytesperline;
1633
1634
0
      nrows -= sp->v_sampling;
1635
0
    } while (nrows > 0);
1636
1637
#if defined(JPEG_LIB_MK1_OR_12BIT)
1638
    _TIFFfree(tmpbuf);
1639
#endif
1640
1641
0
  }
1642
1643
  /* Close down the decompressor if done. */
1644
0
  return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1645
0
    || TIFFjpeg_finish_decompress(sp);
1646
0
}
1647
1648
1649
/*
1650
 * JPEG Encoding.
1651
 */
1652
1653
static void
1654
unsuppress_quant_table (JPEGState* sp, int tblno)
1655
0
{
1656
0
  JQUANT_TBL* qtbl;
1657
1658
0
  if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1659
0
    qtbl->sent_table = FALSE;
1660
0
}
1661
1662
static void
1663
suppress_quant_table (JPEGState* sp, int tblno)
1664
0
{
1665
0
  JQUANT_TBL* qtbl;
1666
1667
0
  if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1668
0
    qtbl->sent_table = TRUE;
1669
0
}
1670
1671
static void
1672
unsuppress_huff_table (JPEGState* sp, int tblno)
1673
0
{
1674
0
  JHUFF_TBL* htbl;
1675
1676
0
  if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1677
0
    htbl->sent_table = FALSE;
1678
0
  if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1679
0
    htbl->sent_table = FALSE;
1680
0
}
1681
1682
static void
1683
suppress_huff_table (JPEGState* sp, int tblno)
1684
0
{
1685
0
  JHUFF_TBL* htbl;
1686
1687
0
  if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1688
0
    htbl->sent_table = TRUE;
1689
0
  if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1690
0
    htbl->sent_table = TRUE;
1691
0
}
1692
1693
static int
1694
prepare_JPEGTables(TIFF* tif)
1695
0
{
1696
0
  JPEGState* sp = JState(tif);
1697
1698
  /* Initialize quant tables for current quality setting */
1699
0
  if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1700
0
    return (0);
1701
  /* Mark only the tables we want for output */
1702
  /* NB: chrominance tables are currently used only with YCbCr */
1703
0
  if (!TIFFjpeg_suppress_tables(sp, TRUE))
1704
0
    return (0);
1705
0
  if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
1706
0
    unsuppress_quant_table(sp, 0);
1707
0
    if (sp->photometric == PHOTOMETRIC_YCBCR)
1708
0
      unsuppress_quant_table(sp, 1);
1709
0
  }
1710
0
  if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
1711
0
    unsuppress_huff_table(sp, 0);
1712
0
    if (sp->photometric == PHOTOMETRIC_YCBCR)
1713
0
      unsuppress_huff_table(sp, 1);
1714
0
  }
1715
  /* Direct libjpeg output into jpegtables */
1716
0
  if (!TIFFjpeg_tables_dest(sp, tif))
1717
0
    return (0);
1718
  /* Emit tables-only datastream */
1719
0
  if (!TIFFjpeg_write_tables(sp))
1720
0
    return (0);
1721
1722
0
  return (1);
1723
0
}
1724
1725
static int
1726
JPEGSetupEncode(TIFF* tif)
1727
0
{
1728
0
  JPEGState* sp = JState(tif);
1729
0
  TIFFDirectory *td = &tif->tif_dir;
1730
0
  static const char module[] = "JPEGSetupEncode";
1731
1732
#if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
1733
        if( tif->tif_dir.td_bitspersample == 12 )
1734
            return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 1 );
1735
#endif
1736
1737
0
        JPEGInitializeLibJPEG( tif, FALSE );
1738
1739
0
  assert(sp != NULL);
1740
0
  assert(!sp->cinfo.comm.is_decompressor);
1741
1742
0
  sp->photometric = td->td_photometric;
1743
1744
  /*
1745
   * Initialize all JPEG parameters to default values.
1746
   * Note that jpeg_set_defaults needs legal values for
1747
   * in_color_space and input_components.
1748
   */
1749
0
  if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1750
0
    sp->cinfo.c.input_components = td->td_samplesperpixel;
1751
0
    if (sp->photometric == PHOTOMETRIC_YCBCR) {
1752
0
      if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1753
0
        sp->cinfo.c.in_color_space = JCS_RGB;
1754
0
      } else {
1755
0
        sp->cinfo.c.in_color_space = JCS_YCbCr;
1756
0
      }
1757
0
    } else {
1758
0
      if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
1759
0
        sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
1760
0
      else if (td->td_photometric == PHOTOMETRIC_RGB && td->td_samplesperpixel == 3)
1761
0
        sp->cinfo.c.in_color_space = JCS_RGB;
1762
0
      else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
1763
0
        sp->cinfo.c.in_color_space = JCS_CMYK;
1764
0
      else
1765
0
        sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1766
0
    }
1767
0
  } else {
1768
0
    sp->cinfo.c.input_components = 1;
1769
0
    sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1770
0
  }
1771
0
  if (!TIFFjpeg_set_defaults(sp))
1772
0
    return (0);
1773
  /* Set per-file parameters */
1774
0
  switch (sp->photometric) {
1775
0
  case PHOTOMETRIC_YCBCR:
1776
0
    sp->h_sampling = td->td_ycbcrsubsampling[0];
1777
0
    sp->v_sampling = td->td_ycbcrsubsampling[1];
1778
0
                if( sp->h_sampling == 0 || sp->v_sampling == 0 )
1779
0
                {
1780
0
                    TIFFErrorExt(tif->tif_clientdata, module,
1781
0
                            "Invalig horizontal/vertical sampling value");
1782
0
                    return (0);
1783
0
                }
1784
0
                if( td->td_bitspersample > 16 )
1785
0
                {
1786
0
                    TIFFErrorExt(tif->tif_clientdata, module,
1787
0
                                 "BitsPerSample %d not allowed for JPEG",
1788
0
                                 td->td_bitspersample);
1789
0
                    return (0);
1790
0
                }
1791
1792
    /*
1793
     * A ReferenceBlackWhite field *must* be present since the
1794
     * default value is inappropriate for YCbCr.  Fill in the
1795
     * proper value if application didn't set it.
1796
     */
1797
0
    {
1798
0
      float *ref;
1799
0
      if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1800
0
            &ref)) {
1801
0
        float refbw[6];
1802
0
        long top = 1L << td->td_bitspersample;
1803
0
        refbw[0] = 0;
1804
0
        refbw[1] = (float)(top-1L);
1805
0
        refbw[2] = (float)(top>>1);
1806
0
        refbw[3] = refbw[1];
1807
0
        refbw[4] = refbw[2];
1808
0
        refbw[5] = refbw[1];
1809
0
        TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1810
0
               refbw);
1811
0
      }
1812
0
    }
1813
0
    break;
1814
0
  case PHOTOMETRIC_PALETTE:   /* disallowed by Tech Note */
1815
0
  case PHOTOMETRIC_MASK:
1816
0
    TIFFErrorExt(tif->tif_clientdata, module,
1817
0
        "PhotometricInterpretation %d not allowed for JPEG",
1818
0
        (int) sp->photometric);
1819
0
    return (0);
1820
0
  default:
1821
    /* TIFF 6.0 forbids subsampling of all other color spaces */
1822
0
    sp->h_sampling = 1;
1823
0
    sp->v_sampling = 1;
1824
0
    break;
1825
0
  }
1826
1827
  /* Verify miscellaneous parameters */
1828
1829
  /*
1830
   * This would need work if libtiff ever supports different
1831
   * depths for different components, or if libjpeg ever supports
1832
   * run-time selection of depth.  Neither is imminent.
1833
   */
1834
#ifdef JPEG_LIB_MK1
1835
        /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1836
  if (td->td_bitspersample != 8 && td->td_bitspersample != 12) 
1837
#else
1838
0
  if (td->td_bitspersample != BITS_IN_JSAMPLE )
1839
0
#endif
1840
0
  {
1841
0
    TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
1842
0
        (int) td->td_bitspersample);
1843
0
    return (0);
1844
0
  }
1845
0
  sp->cinfo.c.data_precision = td->td_bitspersample;
1846
#ifdef JPEG_LIB_MK1
1847
        sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
1848
#endif
1849
0
  if (isTiled(tif)) {
1850
0
    if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
1851
0
      TIFFErrorExt(tif->tif_clientdata, module,
1852
0
          "JPEG tile height must be multiple of %d",
1853
0
          sp->v_sampling * DCTSIZE);
1854
0
      return (0);
1855
0
    }
1856
0
    if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
1857
0
      TIFFErrorExt(tif->tif_clientdata, module,
1858
0
          "JPEG tile width must be multiple of %d",
1859
0
          sp->h_sampling * DCTSIZE);
1860
0
      return (0);
1861
0
    }
1862
0
  } else {
1863
0
    if (td->td_rowsperstrip < td->td_imagelength &&
1864
0
        (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
1865
0
      TIFFErrorExt(tif->tif_clientdata, module,
1866
0
          "RowsPerStrip must be multiple of %d for JPEG",
1867
0
          sp->v_sampling * DCTSIZE);
1868
0
      return (0);
1869
0
    }
1870
0
  }
1871
1872
  /* Create a JPEGTables field if appropriate */
1873
0
  if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
1874
0
                if( sp->jpegtables == NULL
1875
0
                    || memcmp(sp->jpegtables,"\0\0\0\0\0\0\0\0\0",8) == 0 )
1876
0
                {
1877
0
                        if (!prepare_JPEGTables(tif))
1878
0
                                return (0);
1879
                        /* Mark the field present */
1880
                        /* Can't use TIFFSetField since BEENWRITING is already set! */
1881
0
                        tif->tif_flags |= TIFF_DIRTYDIRECT;
1882
0
                        TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1883
0
                }
1884
0
  } else {
1885
    /* We do not support application-supplied JPEGTables, */
1886
    /* so mark the field not present */
1887
0
    TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
1888
0
  }
1889
1890
  /* Direct libjpeg output to libtiff's output buffer */
1891
0
  TIFFjpeg_data_dest(sp, tif);
1892
1893
0
  return (1);
1894
0
}
1895
1896
/*
1897
 * Set encoding state at the start of a strip or tile.
1898
 */
1899
static int
1900
JPEGPreEncode(TIFF* tif, uint16 s)
1901
0
{
1902
0
  JPEGState *sp = JState(tif);
1903
0
  TIFFDirectory *td = &tif->tif_dir;
1904
0
  static const char module[] = "JPEGPreEncode";
1905
0
  uint32 segment_width, segment_height;
1906
0
  int downsampled_input;
1907
1908
0
  assert(sp != NULL);
1909
  
1910
0
  if (sp->cinfo.comm.is_decompressor == 1)
1911
0
  {
1912
0
    tif->tif_setupencode( tif );
1913
0
  }
1914
  
1915
0
  assert(!sp->cinfo.comm.is_decompressor);
1916
  /*
1917
   * Set encoding parameters for this strip/tile.
1918
   */
1919
0
  if (isTiled(tif)) {
1920
0
    segment_width = td->td_tilewidth;
1921
0
    segment_height = td->td_tilelength;
1922
0
    sp->bytesperline = TIFFTileRowSize(tif);
1923
0
  } else {
1924
0
    segment_width = td->td_imagewidth;
1925
0
    segment_height = td->td_imagelength - tif->tif_row;
1926
0
    if (segment_height > td->td_rowsperstrip)
1927
0
      segment_height = td->td_rowsperstrip;
1928
0
    sp->bytesperline = TIFFScanlineSize(tif);
1929
0
  }
1930
0
  if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1931
    /* for PC 2, scale down the strip/tile size
1932
     * to match a downsampled component
1933
     */
1934
0
    segment_width = TIFFhowmany_32(segment_width, sp->h_sampling); 
1935
0
    segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1936
0
  }
1937
0
  if (segment_width > 65535 || segment_height > 65535) {
1938
0
    TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
1939
0
    return (0);
1940
0
  }
1941
0
  sp->cinfo.c.image_width = segment_width;
1942
0
  sp->cinfo.c.image_height = segment_height;
1943
0
  downsampled_input = FALSE;
1944
0
  if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1945
0
    sp->cinfo.c.input_components = td->td_samplesperpixel;
1946
0
    if (sp->photometric == PHOTOMETRIC_YCBCR) {
1947
0
      if (sp->jpegcolormode != JPEGCOLORMODE_RGB) {
1948
0
        if (sp->h_sampling != 1 || sp->v_sampling != 1)
1949
0
          downsampled_input = TRUE;
1950
0
      }
1951
0
      if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
1952
0
        return (0);
1953
      /*
1954
       * Set Y sampling factors;
1955
       * we assume jpeg_set_colorspace() set the rest to 1
1956
       */
1957
0
      sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
1958
0
      sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
1959
0
    } else {
1960
0
      if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
1961
0
        return (0);
1962
      /* jpeg_set_colorspace set all sampling factors to 1 */
1963
0
    }
1964
0
  } else {
1965
0
    if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1966
0
      return (0);
1967
0
    sp->cinfo.c.comp_info[0].component_id = s;
1968
    /* jpeg_set_colorspace() set sampling factors to 1 */
1969
0
    if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
1970
0
      sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
1971
0
      sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
1972
0
      sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
1973
0
    }
1974
0
  }
1975
  /* ensure libjpeg won't write any extraneous markers */
1976
0
  sp->cinfo.c.write_JFIF_header = FALSE;
1977
0
  sp->cinfo.c.write_Adobe_marker = FALSE;
1978
  /* set up table handling correctly */
1979
  /* calling TIFFjpeg_set_quality() causes quantization tables to be flagged */
1980
  /* as being to be emitted, which we don't want in the JPEGTABLESMODE_QUANT */
1981
  /* mode, so we must manually suppress them. However TIFFjpeg_set_quality() */
1982
  /* should really be called when dealing with files with directories with */
1983
  /* mixed qualities. see http://trac.osgeo.org/gdal/ticket/3539 */
1984
0
  if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1985
0
    return (0);
1986
0
  if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
1987
0
    suppress_quant_table(sp, 0);
1988
0
    suppress_quant_table(sp, 1);
1989
0
  }
1990
0
  else {
1991
0
    unsuppress_quant_table(sp, 0);
1992
0
    unsuppress_quant_table(sp, 1);
1993
0
  }
1994
0
  if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
1995
0
  {
1996
    /* Explicit suppression is only needed if we did not go through the */
1997
    /* prepare_JPEGTables() code path, which may be the case if updating */
1998
    /* an existing file */
1999
0
    suppress_huff_table(sp, 0);
2000
0
    suppress_huff_table(sp, 1);
2001
0
    sp->cinfo.c.optimize_coding = FALSE;
2002
0
  }
2003
0
  else
2004
0
    sp->cinfo.c.optimize_coding = TRUE;
2005
0
  if (downsampled_input) {
2006
    /* Need to use raw-data interface to libjpeg */
2007
0
    sp->cinfo.c.raw_data_in = TRUE;
2008
0
    tif->tif_encoderow = JPEGEncodeRaw;
2009
0
    tif->tif_encodestrip = JPEGEncodeRaw;
2010
0
    tif->tif_encodetile = JPEGEncodeRaw;
2011
0
  } else {
2012
    /* Use normal interface to libjpeg */
2013
0
    sp->cinfo.c.raw_data_in = FALSE;
2014
0
    tif->tif_encoderow = JPEGEncode;
2015
0
    tif->tif_encodestrip = JPEGEncode;
2016
0
    tif->tif_encodetile = JPEGEncode;
2017
0
  }
2018
  /* Start JPEG compressor */
2019
0
  if (!TIFFjpeg_start_compress(sp, FALSE))
2020
0
    return (0);
2021
  /* Allocate downsampled-data buffers if needed */
2022
0
  if (downsampled_input) {
2023
0
    if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
2024
0
                 sp->cinfo.c.num_components))
2025
0
      return (0);
2026
0
  }
2027
0
  sp->scancount = 0;
2028
2029
0
  return (1);
2030
0
}
2031
2032
/*
2033
 * Encode a chunk of pixels.
2034
 * "Standard" case: incoming data is not downsampled.
2035
 */
2036
static int
2037
JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
2038
0
{
2039
0
  JPEGState *sp = JState(tif);
2040
0
  tmsize_t nrows;
2041
0
  JSAMPROW bufptr[1];
2042
0
        short *line16 = NULL;
2043
0
        int    line16_count = 0;
2044
2045
0
  (void) s;
2046
0
  assert(sp != NULL);
2047
  /* data is expected to be supplied in multiples of a scanline */
2048
0
  nrows = cc / sp->bytesperline;
2049
0
  if (cc % sp->bytesperline)
2050
0
            TIFFWarningExt(tif->tif_clientdata, tif->tif_name, 
2051
0
                           "fractional scanline discarded");
2052
2053
        /* The last strip will be limited to image size */
2054
0
        if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
2055
0
            nrows = tif->tif_dir.td_imagelength - tif->tif_row;
2056
2057
0
        if( sp->cinfo.c.data_precision == 12 )
2058
0
        {
2059
0
            line16_count = (int)((sp->bytesperline * 2) / 3);
2060
0
            line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
2061
0
            if (!line16)
2062
0
            {
2063
0
                TIFFErrorExt(tif->tif_clientdata,
2064
0
           "JPEGEncode",
2065
0
                             "Failed to allocate memory");
2066
2067
0
                return 0;
2068
0
            }
2069
0
        }
2070
            
2071
0
  while (nrows-- > 0) {
2072
2073
0
            if( sp->cinfo.c.data_precision == 12 )
2074
0
            {
2075
2076
0
                int value_pairs = line16_count / 2;
2077
0
                int iPair;
2078
2079
0
    bufptr[0] = (JSAMPROW) line16;
2080
2081
0
                for( iPair = 0; iPair < value_pairs; iPair++ )
2082
0
                {
2083
0
                    unsigned char *in_ptr =
2084
0
                        ((unsigned char *) buf) + iPair * 3;
2085
0
                    JSAMPLE *out_ptr = (JSAMPLE *) (line16 + iPair * 2);
2086
2087
0
                    out_ptr[0] = (in_ptr[0] << 4) | ((in_ptr[1] & 0xf0) >> 4);
2088
0
                    out_ptr[1] = ((in_ptr[1] & 0x0f) << 8) | in_ptr[2];
2089
0
                }
2090
0
            }
2091
0
            else
2092
0
            {
2093
0
    bufptr[0] = (JSAMPROW) buf;
2094
0
            }
2095
0
            if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
2096
0
                return (0);
2097
0
            if (nrows > 0)
2098
0
                tif->tif_row++;
2099
0
            buf += sp->bytesperline;
2100
0
  }
2101
2102
0
        if( sp->cinfo.c.data_precision == 12 )
2103
0
        {
2104
0
            _TIFFfree( line16 );
2105
0
        }
2106
            
2107
0
  return (1);
2108
0
}
2109
2110
/*
2111
 * Encode a chunk of pixels.
2112
 * Incoming data is expected to be downsampled per sampling factors.
2113
 */
2114
static int
2115
JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
2116
0
{
2117
0
  JPEGState *sp = JState(tif);
2118
0
  JSAMPLE* inptr;
2119
0
  JSAMPLE* outptr;
2120
0
  tmsize_t nrows;
2121
0
  JDIMENSION clumps_per_line, nclump;
2122
0
  int clumpoffset, ci, xpos, ypos;
2123
0
  jpeg_component_info* compptr;
2124
0
  int samples_per_clump = sp->samplesperclump;
2125
0
  tmsize_t bytesperclumpline;
2126
2127
0
  (void) s;
2128
0
  assert(sp != NULL);
2129
  /* data is expected to be supplied in multiples of a clumpline */
2130
  /* a clumpline is equivalent to v_sampling desubsampled scanlines */
2131
  /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
2132
0
  bytesperclumpline = ((((tmsize_t)sp->cinfo.c.image_width+sp->h_sampling-1)/sp->h_sampling)
2133
0
           *((tmsize_t)sp->h_sampling*sp->v_sampling+2)*sp->cinfo.c.data_precision+7)
2134
0
          /8;
2135
2136
0
  nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
2137
0
  if (cc % bytesperclumpline)
2138
0
    TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
2139
2140
  /* Cb,Cr both have sampling factors 1, so this is correct */
2141
0
  clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
2142
2143
0
  while (nrows > 0) {
2144
    /*
2145
     * Fastest way to separate the data is to make one pass
2146
     * over the scanline for each row of each component.
2147
     */
2148
0
    clumpoffset = 0;    /* first sample in clump */
2149
0
    for (ci = 0, compptr = sp->cinfo.c.comp_info;
2150
0
         ci < sp->cinfo.c.num_components;
2151
0
         ci++, compptr++) {
2152
0
        int hsamp = compptr->h_samp_factor;
2153
0
        int vsamp = compptr->v_samp_factor;
2154
0
        int padding = (int) (compptr->width_in_blocks * DCTSIZE -
2155
0
           clumps_per_line * hsamp);
2156
0
        for (ypos = 0; ypos < vsamp; ypos++) {
2157
0
      inptr = ((JSAMPLE*) buf) + clumpoffset;
2158
0
      outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
2159
0
      if (hsamp == 1) {
2160
          /* fast path for at least Cb and Cr */
2161
0
          for (nclump = clumps_per_line; nclump-- > 0; ) {
2162
0
        *outptr++ = inptr[0];
2163
0
        inptr += samples_per_clump;
2164
0
          }
2165
0
      } else {
2166
          /* general case */
2167
0
          for (nclump = clumps_per_line; nclump-- > 0; ) {
2168
0
        for (xpos = 0; xpos < hsamp; xpos++)
2169
0
            *outptr++ = inptr[xpos];
2170
0
        inptr += samples_per_clump;
2171
0
          }
2172
0
      }
2173
      /* pad each scanline as needed */
2174
0
      for (xpos = 0; xpos < padding; xpos++) {
2175
0
          *outptr = outptr[-1];
2176
0
          outptr++;
2177
0
      }
2178
0
      clumpoffset += hsamp;
2179
0
        }
2180
0
    }
2181
0
    sp->scancount++;
2182
0
    if (sp->scancount >= DCTSIZE) {
2183
0
      int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
2184
0
      if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
2185
0
        return (0);
2186
0
      sp->scancount = 0;
2187
0
    }
2188
0
    tif->tif_row += sp->v_sampling;
2189
0
    buf += bytesperclumpline;
2190
0
    nrows -= sp->v_sampling;
2191
0
  }
2192
0
  return (1);
2193
0
}
2194
2195
/*
2196
 * Finish up at the end of a strip or tile.
2197
 */
2198
static int
2199
JPEGPostEncode(TIFF* tif)
2200
0
{
2201
0
  JPEGState *sp = JState(tif);
2202
2203
0
  if (sp->scancount > 0) {
2204
    /*
2205
     * Need to emit a partial bufferload of downsampled data.
2206
     * Pad the data vertically.
2207
     */
2208
0
    int ci, ypos, n;
2209
0
    jpeg_component_info* compptr;
2210
2211
0
    for (ci = 0, compptr = sp->cinfo.c.comp_info;
2212
0
         ci < sp->cinfo.c.num_components;
2213
0
         ci++, compptr++) {
2214
0
      int vsamp = compptr->v_samp_factor;
2215
0
      tmsize_t row_width = compptr->width_in_blocks * DCTSIZE
2216
0
        * sizeof(JSAMPLE);
2217
0
      for (ypos = sp->scancount * vsamp;
2218
0
           ypos < DCTSIZE * vsamp; ypos++) {
2219
0
        _TIFFmemcpy((void*)sp->ds_buffer[ci][ypos],
2220
0
              (void*)sp->ds_buffer[ci][ypos-1],
2221
0
              row_width);
2222
2223
0
      }
2224
0
    }
2225
0
    n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
2226
0
    if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
2227
0
      return (0);
2228
0
  }
2229
2230
0
  return (TIFFjpeg_finish_compress(JState(tif)));
2231
0
}
2232
2233
static void
2234
JPEGCleanup(TIFF* tif)
2235
0
{
2236
0
  JPEGState *sp = JState(tif);
2237
  
2238
0
  assert(sp != 0);
2239
2240
0
  tif->tif_tagmethods.vgetfield = sp->vgetparent;
2241
0
  tif->tif_tagmethods.vsetfield = sp->vsetparent;
2242
0
  tif->tif_tagmethods.printdir = sp->printdir;
2243
0
        if( sp->cinfo_initialized )
2244
0
                TIFFjpeg_destroy(sp); /* release libjpeg resources */
2245
0
        if (sp->jpegtables)   /* tag value */
2246
0
                _TIFFfree(sp->jpegtables);
2247
0
  _TIFFfree(tif->tif_data); /* release local state */
2248
0
  tif->tif_data = NULL;
2249
2250
0
  _TIFFSetDefaultCompressionState(tif);
2251
0
}
2252
2253
static void 
2254
JPEGResetUpsampled( TIFF* tif )
2255
0
{
2256
0
  JPEGState* sp = JState(tif);
2257
0
  TIFFDirectory* td = &tif->tif_dir;
2258
2259
  /*
2260
   * Mark whether returned data is up-sampled or not so TIFFStripSize
2261
   * and TIFFTileSize return values that reflect the true amount of
2262
   * data.
2263
   */
2264
0
  tif->tif_flags &= ~TIFF_UPSAMPLED;
2265
0
  if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
2266
0
    if (td->td_photometric == PHOTOMETRIC_YCBCR &&
2267
0
        sp->jpegcolormode == JPEGCOLORMODE_RGB) {
2268
0
      tif->tif_flags |= TIFF_UPSAMPLED;
2269
0
    } else {
2270
#ifdef notdef
2271
      if (td->td_ycbcrsubsampling[0] != 1 ||
2272
          td->td_ycbcrsubsampling[1] != 1)
2273
        ; /* XXX what about up-sampling? */
2274
#endif
2275
0
    }
2276
0
  }
2277
2278
  /*
2279
   * Must recalculate cached tile size in case sampling state changed.
2280
   * Should we really be doing this now if image size isn't set? 
2281
   */
2282
0
        if( tif->tif_tilesize > 0 )
2283
0
            tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);   
2284
0
        if( tif->tif_scanlinesize > 0 )
2285
0
            tif->tif_scanlinesize = TIFFScanlineSize(tif); 
2286
0
}
2287
2288
static int
2289
JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
2290
0
{
2291
0
  JPEGState* sp = JState(tif);
2292
0
  const TIFFField* fip;
2293
0
  uint32 v32;
2294
2295
0
  assert(sp != NULL);
2296
2297
0
  switch (tag) {
2298
0
  case TIFFTAG_JPEGTABLES:
2299
0
    v32 = (uint32) va_arg(ap, uint32);
2300
0
    if (v32 == 0) {
2301
      /* XXX */
2302
0
      return (0);
2303
0
    }
2304
0
    _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*), v32);
2305
0
    sp->jpegtables_length = v32;
2306
0
    TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2307
0
    break;
2308
0
  case TIFFTAG_JPEGQUALITY:
2309
0
    sp->jpegquality = (int) va_arg(ap, int);
2310
0
    return (1);     /* pseudo tag */
2311
0
  case TIFFTAG_JPEGCOLORMODE:
2312
0
    sp->jpegcolormode = (int) va_arg(ap, int);
2313
0
    JPEGResetUpsampled( tif );
2314
0
    return (1);     /* pseudo tag */
2315
0
  case TIFFTAG_PHOTOMETRIC:
2316
0
  {
2317
0
    int ret_value = (*sp->vsetparent)(tif, tag, ap);
2318
0
    JPEGResetUpsampled( tif );
2319
0
    return ret_value;
2320
0
  }
2321
0
  case TIFFTAG_JPEGTABLESMODE:
2322
0
    sp->jpegtablesmode = (int) va_arg(ap, int);
2323
0
    return (1);     /* pseudo tag */
2324
0
  case TIFFTAG_YCBCRSUBSAMPLING:
2325
    /* mark the fact that we have a real ycbcrsubsampling! */
2326
0
    sp->ycbcrsampling_fetched = 1;
2327
    /* should we be recomputing upsampling info here? */
2328
0
    return (*sp->vsetparent)(tif, tag, ap);
2329
0
  default:
2330
0
    return (*sp->vsetparent)(tif, tag, ap);
2331
0
  }
2332
2333
0
  if ((fip = TIFFFieldWithTag(tif, tag)) != NULL) {
2334
0
    TIFFSetFieldBit(tif, fip->field_bit);
2335
0
  } else {
2336
0
    return (0);
2337
0
  }
2338
2339
0
  tif->tif_flags |= TIFF_DIRTYDIRECT;
2340
0
  return (1);
2341
0
}
2342
2343
static int
2344
JPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
2345
0
{
2346
0
  JPEGState* sp = JState(tif);
2347
2348
0
  assert(sp != NULL);
2349
2350
0
  switch (tag) {
2351
0
    case TIFFTAG_JPEGTABLES:
2352
0
      *va_arg(ap, uint32*) = sp->jpegtables_length;
2353
0
      *va_arg(ap, const void**) = sp->jpegtables;
2354
0
      break;
2355
0
    case TIFFTAG_JPEGQUALITY:
2356
0
      *va_arg(ap, int*) = sp->jpegquality;
2357
0
      break;
2358
0
    case TIFFTAG_JPEGCOLORMODE:
2359
0
      *va_arg(ap, int*) = sp->jpegcolormode;
2360
0
      break;
2361
0
    case TIFFTAG_JPEGTABLESMODE:
2362
0
      *va_arg(ap, int*) = sp->jpegtablesmode;
2363
0
      break;
2364
0
    default:
2365
0
      return (*sp->vgetparent)(tif, tag, ap);
2366
0
  }
2367
0
  return (1);
2368
0
}
2369
2370
static void
2371
JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
2372
0
{
2373
0
  JPEGState* sp = JState(tif);
2374
2375
0
  assert(sp != NULL);
2376
0
  (void) flags;
2377
2378
0
        if( sp != NULL ) {
2379
0
    if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
2380
0
      fprintf(fd, "  JPEG Tables: (%lu bytes)\n",
2381
0
        (unsigned long) sp->jpegtables_length);
2382
0
    if (sp->printdir)
2383
0
      (*sp->printdir)(tif, fd, flags);
2384
0
  }
2385
0
}
2386
2387
static uint32
2388
JPEGDefaultStripSize(TIFF* tif, uint32 s)
2389
0
{
2390
0
  JPEGState* sp = JState(tif);
2391
0
  TIFFDirectory *td = &tif->tif_dir;
2392
2393
0
  s = (*sp->defsparent)(tif, s);
2394
0
  if (s < td->td_imagelength)
2395
0
    s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
2396
0
  return (s);
2397
0
}
2398
2399
static void
2400
JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
2401
0
{
2402
0
  JPEGState* sp = JState(tif);
2403
0
  TIFFDirectory *td = &tif->tif_dir;
2404
2405
0
  (*sp->deftparent)(tif, tw, th);
2406
0
  *tw = TIFFroundup_32(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
2407
0
  *th = TIFFroundup_32(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
2408
0
}
2409
2410
/*
2411
 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
2412
 * now that we allow a TIFF file to be opened in update mode it is necessary
2413
 * to have some way of deciding whether compression or decompression is
2414
 * desired other than looking at tif->tif_mode.  We accomplish this by 
2415
 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
2416
 * If so, we assume decompression is desired. 
2417
 *
2418
 * This is tricky, because TIFFInitJPEG() is called while the directory is
2419
 * being read, and generally speaking the BYTECOUNTS tag won't have been read
2420
 * at that point.  So we try to defer jpeg library initialization till we
2421
 * do have that tag ... basically any access that might require the compressor
2422
 * or decompressor that occurs after the reading of the directory. 
2423
 *
2424
 * In an ideal world compressors or decompressors would be setup
2425
 * at the point where a single tile or strip was accessed (for read or write)
2426
 * so that stuff like update of missing tiles, or replacement of tiles could
2427
 * be done. However, we aren't trying to crack that nut just yet ...
2428
 *
2429
 * NFW, Feb 3rd, 2003.
2430
 */
2431
2432
static int JPEGInitializeLibJPEG( TIFF * tif, int decompress )
2433
0
{
2434
0
    JPEGState* sp = JState(tif);
2435
2436
0
    if(sp->cinfo_initialized)
2437
0
    {
2438
0
        if( !decompress && sp->cinfo.comm.is_decompressor )
2439
0
            TIFFjpeg_destroy( sp );
2440
0
        else if( decompress && !sp->cinfo.comm.is_decompressor )
2441
0
            TIFFjpeg_destroy( sp );
2442
0
        else
2443
0
            return 1;
2444
2445
0
        sp->cinfo_initialized = 0;
2446
0
    }
2447
2448
    /*
2449
     * Initialize libjpeg.
2450
     */
2451
0
    if ( decompress ) {
2452
0
        if (!TIFFjpeg_create_decompress(sp))
2453
0
            return (0);
2454
0
    } else {
2455
0
        if (!TIFFjpeg_create_compress(sp))
2456
0
            return (0);
2457
0
#ifndef TIFF_JPEG_MAX_MEMORY_TO_USE
2458
0
#define TIFF_JPEG_MAX_MEMORY_TO_USE (10 * 1024 * 1024)
2459
0
#endif
2460
        /* libjpeg turbo 1.5.2 honours max_memory_to_use, but has no backing */
2461
        /* store implementation, so better not set max_memory_to_use ourselves. */
2462
        /* See https://github.com/libjpeg-turbo/libjpeg-turbo/issues/162 */
2463
0
        if( sp->cinfo.c.mem->max_memory_to_use > 0 )
2464
0
        {
2465
            /* This is to address bug related in ticket GDAL #1795. */
2466
0
            if (getenv("JPEGMEM") == NULL)
2467
0
            {
2468
                /* Increase the max memory usable. This helps when creating files */
2469
                /* with "big" tile, without using libjpeg temporary files. */
2470
                /* For example a 512x512 tile with 3 bands */
2471
                /* requires 1.5 MB which is above libjpeg 1MB default */
2472
0
                if( sp->cinfo.c.mem->max_memory_to_use < TIFF_JPEG_MAX_MEMORY_TO_USE )
2473
0
                    sp->cinfo.c.mem->max_memory_to_use = TIFF_JPEG_MAX_MEMORY_TO_USE;
2474
0
            }
2475
0
        }
2476
0
    }
2477
2478
0
    sp->cinfo_initialized = TRUE;
2479
2480
0
    return 1;
2481
0
}
2482
2483
int
2484
TIFFInitJPEG(TIFF* tif, int scheme)
2485
0
{
2486
0
  JPEGState* sp;
2487
2488
0
        (void)scheme;
2489
0
  assert(scheme == COMPRESSION_JPEG);
2490
2491
  /*
2492
   * Merge codec-specific tag information.
2493
   */
2494
0
  if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields))) {
2495
0
    TIFFErrorExt(tif->tif_clientdata,
2496
0
           "TIFFInitJPEG",
2497
0
           "Merging JPEG codec-specific tags failed");
2498
0
    return 0;
2499
0
  }
2500
2501
  /*
2502
   * Allocate state block so tag methods have storage to record values.
2503
   */
2504
0
  tif->tif_data = (uint8*) _TIFFmalloc(sizeof (JPEGState));
2505
2506
0
  if (tif->tif_data == NULL) {
2507
0
    TIFFErrorExt(tif->tif_clientdata,
2508
0
           "TIFFInitJPEG", "No space for JPEG state block");
2509
0
    return 0;
2510
0
  }
2511
0
        _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
2512
2513
0
  sp = JState(tif);
2514
0
  sp->tif = tif;        /* back link */
2515
2516
  /*
2517
   * Override parent get/set field methods.
2518
   */
2519
0
  sp->vgetparent = tif->tif_tagmethods.vgetfield;
2520
0
  tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
2521
0
  sp->vsetparent = tif->tif_tagmethods.vsetfield;
2522
0
  tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
2523
0
  sp->printdir = tif->tif_tagmethods.printdir;
2524
0
  tif->tif_tagmethods.printdir = JPEGPrintDir;   /* hook for codec tags */
2525
2526
  /* Default values for codec-specific fields */
2527
0
  sp->jpegtables = NULL;
2528
0
  sp->jpegtables_length = 0;
2529
0
  sp->jpegquality = 75;     /* Default IJG quality */
2530
0
  sp->jpegcolormode = JPEGCOLORMODE_RAW;
2531
0
  sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
2532
0
        sp->ycbcrsampling_fetched = 0;
2533
2534
  /*
2535
   * Install codec methods.
2536
   */
2537
0
  tif->tif_fixuptags = JPEGFixupTags;
2538
0
  tif->tif_setupdecode = JPEGSetupDecode;
2539
0
  tif->tif_predecode = JPEGPreDecode;
2540
0
  tif->tif_decoderow = JPEGDecode;
2541
0
  tif->tif_decodestrip = JPEGDecode;
2542
0
  tif->tif_decodetile = JPEGDecode;
2543
0
  tif->tif_setupencode = JPEGSetupEncode;
2544
0
  tif->tif_preencode = JPEGPreEncode;
2545
0
  tif->tif_postencode = JPEGPostEncode;
2546
0
  tif->tif_encoderow = JPEGEncode;
2547
0
  tif->tif_encodestrip = JPEGEncode;
2548
0
  tif->tif_encodetile = JPEGEncode;  
2549
0
  tif->tif_cleanup = JPEGCleanup;
2550
0
  sp->defsparent = tif->tif_defstripsize;
2551
0
  tif->tif_defstripsize = JPEGDefaultStripSize;
2552
0
  sp->deftparent = tif->tif_deftilesize;
2553
0
  tif->tif_deftilesize = JPEGDefaultTileSize;
2554
0
  tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
2555
2556
0
        sp->cinfo_initialized = FALSE;
2557
2558
  /*
2559
        ** Create a JPEGTables field if no directory has yet been created. 
2560
        ** We do this just to ensure that sufficient space is reserved for
2561
        ** the JPEGTables field.  It will be properly created the right
2562
        ** size later. 
2563
        */
2564
0
        if( tif->tif_diroff == 0 )
2565
0
        {
2566
0
#define SIZE_OF_JPEGTABLES 2000
2567
/*
2568
The following line assumes incorrectly that all JPEG-in-TIFF files will have
2569
a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
2570
when the JPEG data is placed with TIFFWriteRawStrip.  The field bit should be 
2571
set, anyway, later when actual JPEGTABLES header is generated, so removing it 
2572
here hopefully is harmless.
2573
            TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2574
*/
2575
0
            sp->jpegtables_length = SIZE_OF_JPEGTABLES;
2576
0
            sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
2577
0
            if (sp->jpegtables)
2578
0
            {
2579
0
                _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
2580
0
            }
2581
0
            else
2582
0
            {
2583
0
                TIFFErrorExt(tif->tif_clientdata,
2584
0
           "TIFFInitJPEG",
2585
0
                             "Failed to allocate memory for JPEG tables");
2586
0
                return 0;
2587
0
            }
2588
0
#undef SIZE_OF_JPEGTABLES
2589
0
        }
2590
2591
0
  return 1;
2592
0
}
2593
#endif /* JPEG_SUPPORT */
2594
2595
/* vim: set ts=8 sts=8 sw=8 noet: */
2596
2597
/*
2598
 * Local Variables:
2599
 * mode: c
2600
 * c-basic-offset: 8
2601
 * fill-column: 78
2602
 * End:
2603
 */