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