include/mscvpdb.h: Use flexible array members for the rest of structures.
[wine.git] / libs / tiff / libtiff / tif_jpeg.c
blob250144f21120207e5b1624c555f067a192ff7c61
1 /*
2 * Copyright (c) 1994-1997 Sam Leffler
3 * Copyright (c) 1994-1997 Silicon Graphics, Inc.
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.
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.
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.
25 #define WIN32_LEAN_AND_MEAN
26 #define VC_EXTRALEAN
28 #include "tiffiop.h"
29 #include <stdlib.h>
31 #ifdef JPEG_SUPPORT
34 * TIFF Library
36 * JPEG Compression support per TIFF Technical Note #2
37 * (*not* per the original TIFF 6.0 spec).
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/.
43 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
45 #include <setjmp.h>
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
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 */
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 */
65 int ycbcrsampling_fetched;
66 int max_allowed_scan_number;
67 int has_warned_about_progressive_mode;
68 } JPEGOtherSettings;
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);
76 /* We undefine FAR to avoid conflict with JPEG definition */
78 #ifdef FAR
79 #undef FAR
80 #endif
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.
88 #if defined(__BORLANDC__) || defined(__MINGW32__)
89 #define XMD_H 1
90 #endif
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:
98 "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
99 caller expects 464"
101 For such users we will fix the problem here. See install.doc file from
102 the JPEG library distribution for details.
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
113 #include "jerror.h"
114 #include "jpeglib.h"
116 /* Do optional compile-time version check */
117 #if defined(EXPECTED_JPEG_LIB_VERSION) && !defined(LIBJPEG_12_PATH)
118 #if EXPECTED_JPEG_LIB_VERSION != JPEG_LIB_VERSION
119 #error EXPECTED_JPEG_LIB_VERSION != JPEG_LIB_VERSION
120 #endif
121 #endif
124 * Do we want to do special processing suitable for when JSAMPLE is a
125 * 16bit value?
128 /* HAVE_JPEGTURBO_DUAL_MODE_8_12 is defined for libjpeg-turbo >= 2.2 which
129 * adds a dual-mode 8/12 bit API in the same library.
132 #if defined(HAVE_JPEGTURBO_DUAL_MODE_8_12)
133 #define JPEG_DUAL_MODE_8_12
134 /* Start by undefining BITS_IN_JSAMPLE which is always set to 8 in libjpeg-turbo
135 * >= 2.2 Cf
136 * https://github.com/libjpeg-turbo/libjpeg-turbo/commit/8b9bc4b9635a2a047fb23ebe70c9acd728d3f99b
138 #undef BITS_IN_JSAMPLE
139 /* libjpeg-turbo >= 2.2 adds J12xxxx datatypes for the 12-bit mode. */
140 #if defined(FROM_TIF_JPEG_12)
141 #define BITS_IN_JSAMPLE 12
142 #define TIFF_JSAMPLE J12SAMPLE
143 #define TIFF_JSAMPARRAY J12SAMPARRAY
144 #define TIFF_JSAMPIMAGE J12SAMPIMAGE
145 #define TIFF_JSAMPROW J12SAMPROW
146 #else
147 #define BITS_IN_JSAMPLE 8
148 #define TIFF_JSAMPLE JSAMPLE
149 #define TIFF_JSAMPARRAY JSAMPARRAY
150 #define TIFF_JSAMPIMAGE JSAMPIMAGE
151 #define TIFF_JSAMPROW JSAMPROW
152 #endif
153 #else
154 #define TIFF_JSAMPLE JSAMPLE
155 #define TIFF_JSAMPARRAY JSAMPARRAY
156 #define TIFF_JSAMPIMAGE JSAMPIMAGE
157 #define TIFF_JSAMPROW JSAMPROW
158 #endif
160 #if defined(JPEG_LIB_MK1)
161 #define JPEG_LIB_MK1_OR_12BIT 1
162 #elif BITS_IN_JSAMPLE == 12
163 #define JPEG_LIB_MK1_OR_12BIT 1
164 #endif
167 * We are using width_in_blocks which is supposed to be private to
168 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
169 * renamed this member to width_in_data_units. Since the header has
170 * also renamed a define, use that unique define name in order to
171 * detect the problem header and adjust to suit.
173 #if defined(D_MAX_DATA_UNITS_IN_MCU)
174 #define width_in_blocks width_in_data_units
175 #endif
178 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
179 * in place of plain setjmp. These macros will make it easier.
181 #define SETJMP(jbuf) setjmp(jbuf)
182 #define LONGJMP(jbuf, code) longjmp(jbuf, code)
183 #define JMP_BUF jmp_buf
185 typedef struct jpeg_destination_mgr jpeg_destination_mgr;
186 typedef struct jpeg_source_mgr jpeg_source_mgr;
187 typedef struct jpeg_error_mgr jpeg_error_mgr;
190 * State block for each open TIFF file using
191 * libjpeg to do JPEG compression/decompression.
193 * libjpeg's visible state is either a jpeg_compress_struct
194 * or jpeg_decompress_struct depending on which way we
195 * are going. comm can be used to refer to the fields
196 * which are common to both.
198 * NB: cinfo is required to be the first member of JPEGState,
199 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
200 * and vice versa!
202 typedef struct
204 union
206 struct jpeg_compress_struct c;
207 struct jpeg_decompress_struct d;
208 struct jpeg_common_struct comm;
209 } cinfo; /* NB: must be first */
210 int cinfo_initialized;
212 jpeg_error_mgr err; /* libjpeg error manager */
213 JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
215 struct jpeg_progress_mgr progress;
217 * The following two members could be a union, but
218 * they're small enough that it's not worth the effort.
220 jpeg_destination_mgr dest; /* data dest for compression */
221 jpeg_source_mgr src; /* data source for decompression */
222 /* private state */
223 TIFF *tif; /* back link needed by some code */
224 uint16_t photometric; /* copy of PhotometricInterpretation */
225 uint16_t h_sampling; /* luminance sampling factors */
226 uint16_t v_sampling;
227 tmsize_t bytesperline; /* decompressed bytes per scanline */
228 /* pointers to intermediate buffers when processing downsampled data */
229 TIFF_JSAMPARRAY ds_buffer[MAX_COMPONENTS];
230 int scancount; /* number of "scanlines" accumulated */
231 int samplesperclump;
233 JPEGOtherSettings otherSettings;
234 } JPEGState;
236 #define JState(tif) ((JPEGState *)(tif)->tif_data)
238 static int JPEGDecode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
239 static int JPEGDecodeRaw(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
240 static int JPEGEncode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
241 static int JPEGEncodeRaw(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
242 static int JPEGInitializeLibJPEG(TIFF *tif, int decode);
243 static int DecodeRowError(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
245 #define FIELD_JPEGTABLES (FIELD_CODEC + 0)
247 static const TIFFField jpegFields[] = {
248 {TIFFTAG_JPEGTABLES, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8,
249 TIFF_SETGET_C32_UINT8, FIELD_JPEGTABLES, FALSE, TRUE, "JPEGTables", NULL},
250 {TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT,
251 TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "", NULL},
252 {TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT,
253 TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL},
254 {TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT,
255 TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}};
258 * libjpeg interface layer.
260 * We use setjmp/longjmp to return control to libtiff
261 * when a fatal error is encountered within the JPEG
262 * library. We also direct libjpeg error and warning
263 * messages through the appropriate libtiff handlers.
267 * Error handling routines (these replace corresponding
268 * IJG routines from jerror.c). These are used for both
269 * compression and decompression.
271 static void TIFFjpeg_error_exit(j_common_ptr cinfo)
273 JPEGState *sp = (JPEGState *)cinfo; /* NB: cinfo assumed first */
274 char buffer[JMSG_LENGTH_MAX];
276 (*cinfo->err->format_message)(cinfo, buffer);
277 TIFFErrorExtR(sp->tif, "JPEGLib", "%s",
278 buffer); /* display the error message */
279 jpeg_abort(cinfo); /* clean up libjpeg state */
280 LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
284 * This routine is invoked only for warning messages,
285 * since error_exit does its own thing and trace_level
286 * is never set > 0.
288 static void TIFFjpeg_output_message(j_common_ptr cinfo)
290 char buffer[JMSG_LENGTH_MAX];
292 (*cinfo->err->format_message)(cinfo, buffer);
293 TIFFWarningExtR(((JPEGState *)cinfo)->tif, "JPEGLib", "%s", buffer);
296 /* Avoid the risk of denial-of-service on crafted JPEGs with an insane */
297 /* number of scans. */
298 /* See
299 * http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf
301 static void TIFFjpeg_progress_monitor(j_common_ptr cinfo)
303 JPEGState *sp = (JPEGState *)cinfo; /* NB: cinfo assumed first */
304 if (cinfo->is_decompressor)
306 const int scan_no = ((j_decompress_ptr)cinfo)->input_scan_number;
307 if (scan_no >= sp->otherSettings.max_allowed_scan_number)
309 TIFFErrorExtR(
310 ((JPEGState *)cinfo)->tif, "TIFFjpeg_progress_monitor",
311 "Scan number %d exceeds maximum scans (%d). This limit "
312 "can be raised through the "
313 "LIBTIFF_JPEG_MAX_ALLOWED_SCAN_NUMBER "
314 "environment variable.",
315 scan_no, sp->otherSettings.max_allowed_scan_number);
317 jpeg_abort(cinfo); /* clean up libjpeg state */
318 LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
324 * Interface routines. This layer of routines exists
325 * primarily to limit side-effects from using setjmp.
326 * Also, normal/error returns are converted into return
327 * values per libtiff practice.
329 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
330 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op), 1))
332 static int TIFFjpeg_create_compress(JPEGState *sp)
334 /* initialize JPEG error handling */
335 sp->cinfo.c.err = jpeg_std_error(&sp->err);
336 sp->err.error_exit = TIFFjpeg_error_exit;
337 sp->err.output_message = TIFFjpeg_output_message;
339 /* set client_data to avoid UMR warning from tools like Purify */
340 sp->cinfo.c.client_data = NULL;
342 return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
345 static int TIFFjpeg_create_decompress(JPEGState *sp)
347 /* initialize JPEG error handling */
348 sp->cinfo.d.err = jpeg_std_error(&sp->err);
349 sp->err.error_exit = TIFFjpeg_error_exit;
350 sp->err.output_message = TIFFjpeg_output_message;
352 /* set client_data to avoid UMR warning from tools like Purify */
353 sp->cinfo.d.client_data = NULL;
355 return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
358 static int TIFFjpeg_set_defaults(JPEGState *sp)
360 return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
363 static int TIFFjpeg_set_colorspace(JPEGState *sp, J_COLOR_SPACE colorspace)
365 return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
368 static int TIFFjpeg_set_quality(JPEGState *sp, int quality,
369 boolean force_baseline)
371 return CALLVJPEG(sp,
372 jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
375 static int TIFFjpeg_suppress_tables(JPEGState *sp, boolean suppress)
377 return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
380 static int TIFFjpeg_start_compress(JPEGState *sp, boolean write_all_tables)
382 return CALLVJPEG(sp, jpeg_start_compress(&sp->cinfo.c, write_all_tables));
385 static int TIFFjpeg_write_scanlines(JPEGState *sp, TIFF_JSAMPARRAY scanlines,
386 int num_lines)
388 #if defined(HAVE_JPEGTURBO_DUAL_MODE_8_12) && BITS_IN_JSAMPLE == 12
389 return CALLJPEG(sp, -1,
390 (int)jpeg12_write_scanlines(&sp->cinfo.c, scanlines,
391 (JDIMENSION)num_lines));
392 #else
393 return CALLJPEG(sp, -1,
394 (int)jpeg_write_scanlines(&sp->cinfo.c, scanlines,
395 (JDIMENSION)num_lines));
396 #endif
399 static int TIFFjpeg_write_raw_data(JPEGState *sp, TIFF_JSAMPIMAGE data,
400 int num_lines)
402 #if defined(HAVE_JPEGTURBO_DUAL_MODE_8_12) && BITS_IN_JSAMPLE == 12
403 return CALLJPEG(
404 sp, -1,
405 (int)jpeg12_write_raw_data(&sp->cinfo.c, data, (JDIMENSION)num_lines));
406 #else
407 return CALLJPEG(
408 sp, -1,
409 (int)jpeg_write_raw_data(&sp->cinfo.c, data, (JDIMENSION)num_lines));
410 #endif
413 static int TIFFjpeg_finish_compress(JPEGState *sp)
415 return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
418 static int TIFFjpeg_write_tables(JPEGState *sp)
420 return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
423 static int TIFFjpeg_read_header(JPEGState *sp, boolean require_image)
425 return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
428 static int TIFFjpeg_has_multiple_scans(JPEGState *sp)
430 return CALLJPEG(sp, 0, jpeg_has_multiple_scans(&sp->cinfo.d));
433 static int TIFFjpeg_start_decompress(JPEGState *sp)
435 const char *sz_max_allowed_scan_number;
436 /* progress monitor */
437 sp->cinfo.d.progress = &sp->progress;
438 sp->progress.progress_monitor = TIFFjpeg_progress_monitor;
439 sp->otherSettings.max_allowed_scan_number = 100;
440 sz_max_allowed_scan_number = getenv("LIBTIFF_JPEG_MAX_ALLOWED_SCAN_NUMBER");
441 if (sz_max_allowed_scan_number)
442 sp->otherSettings.max_allowed_scan_number =
443 atoi(sz_max_allowed_scan_number);
445 return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
448 static int TIFFjpeg_read_scanlines(JPEGState *sp, TIFF_JSAMPARRAY scanlines,
449 int max_lines)
451 #if defined(HAVE_JPEGTURBO_DUAL_MODE_8_12) && BITS_IN_JSAMPLE == 12
452 return CALLJPEG(sp, -1,
453 (int)jpeg12_read_scanlines(&sp->cinfo.d, scanlines,
454 (JDIMENSION)max_lines));
455 #else
456 return CALLJPEG(sp, -1,
457 (int)jpeg_read_scanlines(&sp->cinfo.d, scanlines,
458 (JDIMENSION)max_lines));
459 #endif
462 static int TIFFjpeg_read_raw_data(JPEGState *sp, TIFF_JSAMPIMAGE data,
463 int max_lines)
465 #if defined(HAVE_JPEGTURBO_DUAL_MODE_8_12) && BITS_IN_JSAMPLE == 12
466 return CALLJPEG(
467 sp, -1,
468 (int)jpeg12_read_raw_data(&sp->cinfo.d, data, (JDIMENSION)max_lines));
469 #else
470 return CALLJPEG(
471 sp, -1,
472 (int)jpeg_read_raw_data(&sp->cinfo.d, data, (JDIMENSION)max_lines));
473 #endif
476 static int TIFFjpeg_finish_decompress(JPEGState *sp)
478 return CALLJPEG(sp, -1, (int)jpeg_finish_decompress(&sp->cinfo.d));
481 static int TIFFjpeg_abort(JPEGState *sp)
483 return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
486 static int TIFFjpeg_destroy(JPEGState *sp)
488 return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
491 static JSAMPARRAY TIFFjpeg_alloc_sarray(JPEGState *sp, int pool_id,
492 JDIMENSION samplesperrow,
493 JDIMENSION numrows)
495 return CALLJPEG(sp, (JSAMPARRAY)NULL,
496 (*sp->cinfo.comm.mem->alloc_sarray)(
497 &sp->cinfo.comm, pool_id, samplesperrow, numrows));
501 * JPEG library destination data manager.
502 * These routines direct compressed data from libjpeg into the
503 * libtiff output buffer.
506 static void std_init_destination(j_compress_ptr cinfo)
508 JPEGState *sp = (JPEGState *)cinfo;
509 TIFF *tif = sp->tif;
511 sp->dest.next_output_byte = (JOCTET *)tif->tif_rawdata;
512 sp->dest.free_in_buffer = (size_t)tif->tif_rawdatasize;
515 static boolean std_empty_output_buffer(j_compress_ptr cinfo)
517 JPEGState *sp = (JPEGState *)cinfo;
518 TIFF *tif = sp->tif;
520 /* the entire buffer has been filled */
521 tif->tif_rawcc = tif->tif_rawdatasize;
523 #ifdef IPPJ_HUFF
525 * The Intel IPP performance library does not necessarily fill up
526 * the whole output buffer on each pass, so only dump out the parts
527 * that have been filled.
528 * http://trac.osgeo.org/gdal/wiki/JpegIPP
530 if (sp->dest.free_in_buffer >= 0)
532 tif->tif_rawcc = tif->tif_rawdatasize - sp->dest.free_in_buffer;
534 #endif
536 if (!TIFFFlushData1(tif))
537 return FALSE;
538 sp->dest.next_output_byte = (JOCTET *)tif->tif_rawdata;
539 sp->dest.free_in_buffer = (size_t)tif->tif_rawdatasize;
541 return (TRUE);
544 static void std_term_destination(j_compress_ptr cinfo)
546 JPEGState *sp = (JPEGState *)cinfo;
547 TIFF *tif = sp->tif;
549 tif->tif_rawcp = (uint8_t *)sp->dest.next_output_byte;
550 tif->tif_rawcc = tif->tif_rawdatasize - (tmsize_t)sp->dest.free_in_buffer;
551 /* NB: libtiff does the final buffer flush */
554 static void TIFFjpeg_data_dest(JPEGState *sp, TIFF *tif)
556 (void)tif;
557 sp->cinfo.c.dest = &sp->dest;
558 sp->dest.init_destination = std_init_destination;
559 sp->dest.empty_output_buffer = std_empty_output_buffer;
560 sp->dest.term_destination = std_term_destination;
564 * Alternate destination manager for outputting to JPEGTables field.
567 static void tables_init_destination(j_compress_ptr cinfo)
569 JPEGState *sp = (JPEGState *)cinfo;
571 /* while building, otherSettings.jpegtables_length is allocated buffer size
573 sp->dest.next_output_byte = (JOCTET *)sp->otherSettings.jpegtables;
574 sp->dest.free_in_buffer = (size_t)sp->otherSettings.jpegtables_length;
577 static boolean tables_empty_output_buffer(j_compress_ptr cinfo)
579 JPEGState *sp = (JPEGState *)cinfo;
580 void *newbuf;
582 /* the entire buffer has been filled; enlarge it by 1000 bytes */
583 newbuf =
584 _TIFFreallocExt(sp->tif, (void *)sp->otherSettings.jpegtables,
585 (tmsize_t)(sp->otherSettings.jpegtables_length + 1000));
586 if (newbuf == NULL)
587 ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
588 sp->dest.next_output_byte =
589 (JOCTET *)newbuf + sp->otherSettings.jpegtables_length;
590 sp->dest.free_in_buffer = (size_t)1000;
591 sp->otherSettings.jpegtables = newbuf;
592 sp->otherSettings.jpegtables_length += 1000;
593 return (TRUE);
596 static void tables_term_destination(j_compress_ptr cinfo)
598 JPEGState *sp = (JPEGState *)cinfo;
600 /* set tables length to number of bytes actually emitted */
601 sp->otherSettings.jpegtables_length -= (uint32_t)sp->dest.free_in_buffer;
604 static int TIFFjpeg_tables_dest(JPEGState *sp, TIFF *tif)
606 (void)tif;
608 * Allocate a working buffer for building tables.
609 * Initial size is 1000 bytes, which is usually adequate.
611 if (sp->otherSettings.jpegtables)
612 _TIFFfreeExt(tif, sp->otherSettings.jpegtables);
613 sp->otherSettings.jpegtables_length = 1000;
614 sp->otherSettings.jpegtables = (void *)_TIFFmallocExt(
615 tif, (tmsize_t)sp->otherSettings.jpegtables_length);
616 if (sp->otherSettings.jpegtables == NULL)
618 sp->otherSettings.jpegtables_length = 0;
619 TIFFErrorExtR(sp->tif, "TIFFjpeg_tables_dest",
620 "No space for JPEGTables");
621 return (0);
623 sp->cinfo.c.dest = &sp->dest;
624 sp->dest.init_destination = tables_init_destination;
625 sp->dest.empty_output_buffer = tables_empty_output_buffer;
626 sp->dest.term_destination = tables_term_destination;
627 return (1);
631 * JPEG library source data manager.
632 * These routines supply compressed data to libjpeg.
635 static void std_init_source(j_decompress_ptr cinfo)
637 JPEGState *sp = (JPEGState *)cinfo;
638 TIFF *tif = sp->tif;
640 sp->src.next_input_byte = (const JOCTET *)tif->tif_rawdata;
641 sp->src.bytes_in_buffer = (size_t)tif->tif_rawcc;
644 static boolean std_fill_input_buffer(j_decompress_ptr cinfo)
646 JPEGState *sp = (JPEGState *)cinfo;
647 static const JOCTET dummy_EOI[2] = {0xFF, JPEG_EOI};
649 #ifdef IPPJ_HUFF
651 * The Intel IPP performance library does not necessarily read the whole
652 * input buffer in one pass, so it is possible to get here with data
653 * yet to read.
655 * We just return without doing anything, until the entire buffer has
656 * been read.
657 * http://trac.osgeo.org/gdal/wiki/JpegIPP
659 if (sp->src.bytes_in_buffer > 0)
661 return (TRUE);
663 #endif
666 * Normally the whole strip/tile is read and so we don't need to do
667 * a fill. In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
668 * all the data, but the rawdata is refreshed between scanlines and
669 * we push this into the io machinery in JPEGDecode().
670 * http://trac.osgeo.org/gdal/ticket/3894
673 WARNMS(cinfo, JWRN_JPEG_EOF);
674 /* insert a fake EOI marker */
675 sp->src.next_input_byte = dummy_EOI;
676 sp->src.bytes_in_buffer = 2;
677 return (TRUE);
680 static void std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
682 JPEGState *sp = (JPEGState *)cinfo;
684 if (num_bytes > 0)
686 if ((size_t)num_bytes > sp->src.bytes_in_buffer)
688 /* oops, buffer overrun */
689 (void)std_fill_input_buffer(cinfo);
691 else
693 sp->src.next_input_byte += (size_t)num_bytes;
694 sp->src.bytes_in_buffer -= (size_t)num_bytes;
699 static void std_term_source(j_decompress_ptr cinfo)
701 /* No work necessary here */
702 (void)cinfo;
705 static void TIFFjpeg_data_src(JPEGState *sp)
707 sp->cinfo.d.src = &sp->src;
708 sp->src.init_source = std_init_source;
709 sp->src.fill_input_buffer = std_fill_input_buffer;
710 sp->src.skip_input_data = std_skip_input_data;
711 sp->src.resync_to_restart = jpeg_resync_to_restart;
712 sp->src.term_source = std_term_source;
713 sp->src.bytes_in_buffer = 0; /* for safety */
714 sp->src.next_input_byte = NULL;
718 * Alternate source manager for reading from JPEGTables.
719 * We can share all the code except for the init routine.
722 static void tables_init_source(j_decompress_ptr cinfo)
724 JPEGState *sp = (JPEGState *)cinfo;
726 sp->src.next_input_byte = (const JOCTET *)sp->otherSettings.jpegtables;
727 sp->src.bytes_in_buffer = (size_t)sp->otherSettings.jpegtables_length;
730 static void TIFFjpeg_tables_src(JPEGState *sp)
732 TIFFjpeg_data_src(sp);
733 sp->src.init_source = tables_init_source;
737 * Allocate downsampled-data buffers needed for downsampled I/O.
738 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
739 * We use libjpeg's allocator so that buffers will be released automatically
740 * when done with strip/tile.
741 * This is also a handy place to compute samplesperclump, bytesperline.
743 static int alloc_downsampled_buffers(TIFF *tif, jpeg_component_info *comp_info,
744 int num_components)
746 JPEGState *sp = JState(tif);
747 int ci;
748 jpeg_component_info *compptr;
749 TIFF_JSAMPARRAY buf;
750 int samples_per_clump = 0;
752 for (ci = 0, compptr = comp_info; ci < num_components; ci++, compptr++)
754 samples_per_clump += compptr->h_samp_factor * compptr->v_samp_factor;
755 buf = (TIFF_JSAMPARRAY)TIFFjpeg_alloc_sarray(
756 sp, JPOOL_IMAGE, compptr->width_in_blocks * DCTSIZE,
757 (JDIMENSION)(compptr->v_samp_factor * DCTSIZE));
758 if (buf == NULL)
759 return (0);
760 sp->ds_buffer[ci] = buf;
762 sp->samplesperclump = samples_per_clump;
763 return (1);
767 * JPEG Decoding.
770 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
772 #define JPEG_MARKER_SOF0 0xC0
773 #define JPEG_MARKER_SOF1 0xC1
774 #define JPEG_MARKER_SOF2 0xC2
775 #define JPEG_MARKER_SOF9 0xC9
776 #define JPEG_MARKER_SOF10 0xCA
777 #define JPEG_MARKER_DHT 0xC4
778 #define JPEG_MARKER_SOI 0xD8
779 #define JPEG_MARKER_SOS 0xDA
780 #define JPEG_MARKER_DQT 0xDB
781 #define JPEG_MARKER_DRI 0xDD
782 #define JPEG_MARKER_APP0 0xE0
783 #define JPEG_MARKER_COM 0xFE
784 struct JPEGFixupTagsSubsamplingData
786 TIFF *tif;
787 void *buffer;
788 uint32_t buffersize;
789 uint8_t *buffercurrentbyte;
790 uint32_t bufferbytesleft;
791 uint64_t fileoffset;
792 uint64_t filebytesleft;
793 uint8_t filepositioned;
795 static void JPEGFixupTagsSubsampling(TIFF *tif);
796 static int
797 JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData *data);
798 static int
799 JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData *data,
800 uint8_t *result);
801 static int
802 JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData *data,
803 uint16_t *result);
804 static void
805 JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData *data,
806 uint16_t skiplength);
808 #endif
810 static int JPEGFixupTags(TIFF *tif)
812 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
813 JPEGState *sp = JState(tif);
814 if ((tif->tif_dir.td_photometric == PHOTOMETRIC_YCBCR) &&
815 (tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG) &&
816 (tif->tif_dir.td_samplesperpixel == 3) &&
817 !sp->otherSettings.ycbcrsampling_fetched)
818 JPEGFixupTagsSubsampling(tif);
819 #endif
821 return (1);
824 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
826 static void JPEGFixupTagsSubsampling(TIFF *tif)
829 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
830 * the TIFF tags, but still use non-default (2,2) values within the jpeg
831 * data stream itself. In order for TIFF applications to work properly
832 * - for instance to get the strip buffer size right - it is imperative
833 * that the subsampling be available before we start reading the image
834 * data normally. This function will attempt to analyze the first strip in
835 * order to get the sampling values from the jpeg data stream.
837 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
838 * discovered sampling does not match the default sampling (2,2) or whatever
839 * was actually in the tiff tags.
841 * See the bug in bugzilla for details:
843 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
845 * Frank Warmerdam, July 2002
846 * Joris Van Damme, May 2007
848 static const char module[] = "JPEGFixupTagsSubsampling";
849 struct JPEGFixupTagsSubsamplingData m;
850 uint64_t fileoffset = TIFFGetStrileOffset(tif, 0);
852 if (fileoffset == 0)
854 /* Do not even try to check if the first strip/tile does not
855 yet exist, as occurs when GDAL has created a new NULL file
856 for instance. */
857 return;
860 m.tif = tif;
861 m.buffersize = 2048;
862 m.buffer = _TIFFmallocExt(tif, m.buffersize);
863 if (m.buffer == NULL)
865 TIFFWarningExtR(tif, module,
866 "Unable to allocate memory for auto-correcting of "
867 "subsampling values; auto-correcting skipped");
868 return;
870 m.buffercurrentbyte = NULL;
871 m.bufferbytesleft = 0;
872 m.fileoffset = fileoffset;
873 m.filepositioned = 0;
874 m.filebytesleft = TIFFGetStrileByteCount(tif, 0);
875 if (!JPEGFixupTagsSubsamplingSec(&m))
876 TIFFWarningExtR(
877 tif, module,
878 "Unable to auto-correct subsampling values, likely corrupt JPEG "
879 "compressed data in first strip/tile; auto-correcting skipped");
880 _TIFFfreeExt(tif, m.buffer);
883 static int
884 JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData *data)
886 static const char module[] = "JPEGFixupTagsSubsamplingSec";
887 uint8_t m;
888 while (1)
890 while (1)
892 if (!JPEGFixupTagsSubsamplingReadByte(data, &m))
893 return (0);
894 if (m == 255)
895 break;
897 while (1)
899 if (!JPEGFixupTagsSubsamplingReadByte(data, &m))
900 return (0);
901 if (m != 255)
902 break;
904 switch (m)
906 case JPEG_MARKER_SOI:
907 /* this type of marker has no data and should be skipped */
908 break;
909 case JPEG_MARKER_COM:
910 case JPEG_MARKER_APP0:
911 case JPEG_MARKER_APP0 + 1:
912 case JPEG_MARKER_APP0 + 2:
913 case JPEG_MARKER_APP0 + 3:
914 case JPEG_MARKER_APP0 + 4:
915 case JPEG_MARKER_APP0 + 5:
916 case JPEG_MARKER_APP0 + 6:
917 case JPEG_MARKER_APP0 + 7:
918 case JPEG_MARKER_APP0 + 8:
919 case JPEG_MARKER_APP0 + 9:
920 case JPEG_MARKER_APP0 + 10:
921 case JPEG_MARKER_APP0 + 11:
922 case JPEG_MARKER_APP0 + 12:
923 case JPEG_MARKER_APP0 + 13:
924 case JPEG_MARKER_APP0 + 14:
925 case JPEG_MARKER_APP0 + 15:
926 case JPEG_MARKER_DQT:
927 case JPEG_MARKER_SOS:
928 case JPEG_MARKER_DHT:
929 case JPEG_MARKER_DRI:
930 /* this type of marker has data, but it has no use to us and
931 * should be skipped */
933 uint16_t n;
934 if (!JPEGFixupTagsSubsamplingReadWord(data, &n))
935 return (0);
936 if (n < 2)
937 return (0);
938 n -= 2;
939 if (n > 0)
940 JPEGFixupTagsSubsamplingSkip(data, n);
942 break;
943 case JPEG_MARKER_SOF0: /* Baseline sequential Huffman */
944 case JPEG_MARKER_SOF1: /* Extended sequential Huffman */
945 case JPEG_MARKER_SOF2: /* Progressive Huffman: normally not allowed
946 by TechNote, but that doesn't hurt
947 supporting it */
948 case JPEG_MARKER_SOF9: /* Extended sequential arithmetic */
949 case JPEG_MARKER_SOF10: /* Progressive arithmetic: normally not
950 allowed by TechNote, but that doesn't
951 hurt supporting it */
952 /* this marker contains the subsampling factors we're scanning
953 * for */
955 uint16_t n;
956 uint16_t o;
957 uint8_t p;
958 uint8_t ph, pv;
959 if (!JPEGFixupTagsSubsamplingReadWord(data, &n))
960 return (0);
961 if (n != 8 + data->tif->tif_dir.td_samplesperpixel * 3)
962 return (0);
963 JPEGFixupTagsSubsamplingSkip(data, 7);
964 if (!JPEGFixupTagsSubsamplingReadByte(data, &p))
965 return (0);
966 ph = (p >> 4);
967 pv = (p & 15);
968 JPEGFixupTagsSubsamplingSkip(data, 1);
969 for (o = 1; o < data->tif->tif_dir.td_samplesperpixel; o++)
971 JPEGFixupTagsSubsamplingSkip(data, 1);
972 if (!JPEGFixupTagsSubsamplingReadByte(data, &p))
973 return (0);
974 if (p != 0x11)
976 TIFFWarningExtR(data->tif, module,
977 "Subsampling values inside JPEG "
978 "compressed data "
979 "have no TIFF equivalent, "
980 "auto-correction of TIFF "
981 "subsampling values failed");
982 return (1);
984 JPEGFixupTagsSubsamplingSkip(data, 1);
986 if (((ph != 1) && (ph != 2) && (ph != 4)) ||
987 ((pv != 1) && (pv != 2) && (pv != 4)))
989 TIFFWarningExtR(data->tif, module,
990 "Subsampling values inside JPEG "
991 "compressed data have no TIFF "
992 "equivalent, auto-correction of TIFF "
993 "subsampling values failed");
994 return (1);
996 if ((ph != data->tif->tif_dir.td_ycbcrsubsampling[0]) ||
997 (pv != data->tif->tif_dir.td_ycbcrsubsampling[1]))
999 TIFFWarningExtR(
1000 data->tif, module,
1001 "Auto-corrected former TIFF subsampling values "
1002 "[%" PRIu16 ",%" PRIu16
1003 "] to match subsampling values inside JPEG "
1004 "compressed data [%" PRIu8 ",%" PRIu8 "]",
1005 data->tif->tif_dir.td_ycbcrsubsampling[0],
1006 data->tif->tif_dir.td_ycbcrsubsampling[1], ph, pv);
1007 data->tif->tif_dir.td_ycbcrsubsampling[0] = ph;
1008 data->tif->tif_dir.td_ycbcrsubsampling[1] = pv;
1011 return (1);
1012 default:
1013 return (0);
1018 static int
1019 JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData *data,
1020 uint8_t *result)
1022 if (data->bufferbytesleft == 0)
1024 uint32_t m;
1025 if (data->filebytesleft == 0)
1026 return (0);
1027 if (!data->filepositioned)
1029 if (TIFFSeekFile(data->tif, data->fileoffset, SEEK_SET) ==
1030 (toff_t)-1)
1032 return 0;
1034 data->filepositioned = 1;
1036 m = data->buffersize;
1037 if ((uint64_t)m > data->filebytesleft)
1038 m = (uint32_t)data->filebytesleft;
1039 assert(m < 0x80000000UL);
1040 if (TIFFReadFile(data->tif, data->buffer, (tmsize_t)m) != (tmsize_t)m)
1041 return (0);
1042 data->buffercurrentbyte = data->buffer;
1043 data->bufferbytesleft = m;
1044 data->fileoffset += m;
1045 data->filebytesleft -= m;
1047 *result = *data->buffercurrentbyte;
1048 data->buffercurrentbyte++;
1049 data->bufferbytesleft--;
1050 return (1);
1053 static int
1054 JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData *data,
1055 uint16_t *result)
1057 uint8_t ma;
1058 uint8_t mb;
1059 if (!JPEGFixupTagsSubsamplingReadByte(data, &ma))
1060 return (0);
1061 if (!JPEGFixupTagsSubsamplingReadByte(data, &mb))
1062 return (0);
1063 *result = (ma << 8) | mb;
1064 return (1);
1067 static void
1068 JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData *data,
1069 uint16_t skiplength)
1071 if ((uint32_t)skiplength <= data->bufferbytesleft)
1073 data->buffercurrentbyte += skiplength;
1074 data->bufferbytesleft -= skiplength;
1076 else
1078 uint16_t m;
1079 m = (uint16_t)(skiplength - data->bufferbytesleft);
1080 if (m <= data->filebytesleft)
1082 data->bufferbytesleft = 0;
1083 data->fileoffset += m;
1084 data->filebytesleft -= m;
1085 data->filepositioned = 0;
1087 else
1089 data->bufferbytesleft = 0;
1090 data->filebytesleft = 0;
1095 #endif
1097 static int JPEGSetupDecode(TIFF *tif)
1099 JPEGState *sp = JState(tif);
1100 TIFFDirectory *td = &tif->tif_dir;
1102 #if defined(JPEG_DUAL_MODE_8_12) && !defined(FROM_TIF_JPEG_12)
1103 if (tif->tif_dir.td_bitspersample == 12)
1105 /* We pass a pointer to a copy of otherSettings, since */
1106 /* TIFFReInitJPEG_12() will clear sp */
1107 JPEGOtherSettings savedOtherSettings = sp->otherSettings;
1108 return TIFFReInitJPEG_12(tif, &savedOtherSettings, COMPRESSION_JPEG, 0);
1110 #endif
1112 JPEGInitializeLibJPEG(tif, TRUE);
1114 assert(sp != NULL);
1115 assert(sp->cinfo.comm.is_decompressor);
1117 /* Read JPEGTables if it is present */
1118 if (TIFFFieldSet(tif, FIELD_JPEGTABLES))
1120 TIFFjpeg_tables_src(sp);
1121 if (TIFFjpeg_read_header(sp, FALSE) != JPEG_HEADER_TABLES_ONLY)
1123 TIFFErrorExtR(tif, "JPEGSetupDecode", "Bogus JPEGTables field");
1124 return (0);
1128 /* Grab parameters that are same for all strips/tiles */
1129 sp->photometric = td->td_photometric;
1130 switch (sp->photometric)
1132 case PHOTOMETRIC_YCBCR:
1133 sp->h_sampling = td->td_ycbcrsubsampling[0];
1134 sp->v_sampling = td->td_ycbcrsubsampling[1];
1135 break;
1136 default:
1137 /* TIFF 6.0 forbids subsampling of all other color spaces */
1138 sp->h_sampling = 1;
1139 sp->v_sampling = 1;
1140 break;
1143 /* Set up for reading normal data */
1144 TIFFjpeg_data_src(sp);
1145 tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
1146 return (1);
1149 /* Returns 1 if the full strip should be read, even when doing scanline per */
1150 /* scanline decoding. This happens when the JPEG stream uses multiple scans. */
1151 /* Currently only called in CHUNKY_STRIP_READ_SUPPORT mode through */
1152 /* scanline interface. */
1153 /* Only reads tif->tif_dir.td_bitspersample, tif->tif_rawdata and */
1154 /* tif->tif_rawcc members. */
1155 /* Can be called independently of the usual setup/predecode/decode states */
1156 int TIFFJPEGIsFullStripRequired(TIFF *tif)
1158 int ret;
1159 JPEGState state;
1161 #if defined(JPEG_DUAL_MODE_8_12) && !defined(FROM_TIF_JPEG_12)
1162 if (tif->tif_dir.td_bitspersample == 12)
1163 return TIFFJPEGIsFullStripRequired_12(tif);
1164 #endif
1166 memset(&state, 0, sizeof(JPEGState));
1167 state.tif = tif;
1169 TIFFjpeg_create_decompress(&state);
1171 TIFFjpeg_data_src(&state);
1173 if (TIFFjpeg_read_header(&state, TRUE) != JPEG_HEADER_OK)
1175 TIFFjpeg_destroy(&state);
1176 return (0);
1178 ret = TIFFjpeg_has_multiple_scans(&state);
1180 TIFFjpeg_destroy(&state);
1182 return ret;
1186 * Set up for decoding a strip or tile.
1188 /*ARGSUSED*/ static int JPEGPreDecode(TIFF *tif, uint16_t s)
1190 JPEGState *sp = JState(tif);
1191 TIFFDirectory *td = &tif->tif_dir;
1192 static const char module[] = "JPEGPreDecode";
1193 uint32_t segment_width, segment_height;
1194 int downsampled_output;
1195 int ci;
1197 assert(sp != NULL);
1199 if (sp->cinfo.comm.is_decompressor == 0)
1201 tif->tif_setupdecode(tif);
1204 assert(sp->cinfo.comm.is_decompressor);
1206 * Reset decoder state from any previous strip/tile,
1207 * in case application didn't read the whole strip.
1209 if (!TIFFjpeg_abort(sp))
1210 return (0);
1212 * Read the header for this strip/tile.
1215 if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
1216 return (0);
1218 tif->tif_rawcp = (uint8_t *)sp->src.next_input_byte;
1219 tif->tif_rawcc = sp->src.bytes_in_buffer;
1222 * Check image parameters and set decompression parameters.
1224 if (isTiled(tif))
1226 segment_width = td->td_tilewidth;
1227 segment_height = td->td_tilelength;
1228 sp->bytesperline = TIFFTileRowSize(tif);
1230 else
1232 segment_width = td->td_imagewidth;
1233 segment_height = td->td_imagelength - tif->tif_row;
1234 if (segment_height > td->td_rowsperstrip)
1235 segment_height = td->td_rowsperstrip;
1236 sp->bytesperline = TIFFScanlineSize(tif);
1238 if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0)
1241 * For PC 2, scale down the expected strip/tile size
1242 * to match a downsampled component
1244 segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
1245 segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1247 if (sp->cinfo.d.image_width < segment_width ||
1248 sp->cinfo.d.image_height < segment_height)
1250 TIFFWarningExtR(tif, module,
1251 "Improper JPEG strip/tile size, "
1252 "expected %" PRIu32 "x%" PRIu32 ", got %ux%u",
1253 segment_width, segment_height, sp->cinfo.d.image_width,
1254 sp->cinfo.d.image_height);
1256 if (sp->cinfo.d.image_width == segment_width &&
1257 sp->cinfo.d.image_height > segment_height &&
1258 tif->tif_row + segment_height == td->td_imagelength && !isTiled(tif))
1260 /* Some files have a last strip, that should be truncated, */
1261 /* but their JPEG codestream has still the maximum strip */
1262 /* height. Warn about this as this is non compliant, but */
1263 /* we can safely recover from that. */
1264 TIFFWarningExtR(tif, module,
1265 "JPEG strip size exceeds expected dimensions,"
1266 " expected %" PRIu32 "x%" PRIu32 ", got %ux%u",
1267 segment_width, segment_height, sp->cinfo.d.image_width,
1268 sp->cinfo.d.image_height);
1270 else if (sp->cinfo.d.image_width > segment_width ||
1271 sp->cinfo.d.image_height > segment_height)
1274 * This case could be dangerous, if the strip or tile size has
1275 * been reported as less than the amount of data jpeg will
1276 * return, some potential security issues arise. Catch this
1277 * case and error out.
1279 TIFFErrorExtR(tif, module,
1280 "JPEG strip/tile size exceeds expected dimensions,"
1281 " expected %" PRIu32 "x%" PRIu32 ", got %ux%u",
1282 segment_width, segment_height, sp->cinfo.d.image_width,
1283 sp->cinfo.d.image_height);
1284 return (0);
1286 if (sp->cinfo.d.num_components !=
1287 (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel
1288 : 1))
1290 TIFFErrorExtR(tif, module, "Improper JPEG component count");
1291 return (0);
1293 #ifdef JPEG_LIB_MK1
1294 if (12 != td->td_bitspersample && 8 != td->td_bitspersample)
1296 TIFFErrorExtR(tif, module, "Improper JPEG data precision");
1297 return (0);
1299 sp->cinfo.d.data_precision = td->td_bitspersample;
1300 sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
1301 #else
1302 if (sp->cinfo.d.data_precision != td->td_bitspersample)
1304 TIFFErrorExtR(tif, module, "Improper JPEG data precision");
1305 return (0);
1307 #endif
1309 if (sp->cinfo.d.progressive_mode &&
1310 !sp->otherSettings.has_warned_about_progressive_mode)
1312 TIFFWarningExtR(tif, module,
1313 "The JPEG strip/tile is encoded with progressive mode, "
1314 "which is normally not legal for JPEG-in-TIFF.\n"
1315 "libtiff should be able to decode it, but it might "
1316 "cause compatibility issues with other readers");
1317 sp->otherSettings.has_warned_about_progressive_mode = TRUE;
1320 /* In some cases, libjpeg needs to allocate a lot of memory */
1321 /* http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf
1323 if (TIFFjpeg_has_multiple_scans(sp))
1325 /* In this case libjpeg will need to allocate memory or backing */
1326 /* store for all coefficients */
1327 /* See call to jinit_d_coef_controller() from master_selection() */
1328 /* in libjpeg */
1330 /* 1 MB for regular libjpeg usage */
1331 toff_t nRequiredMemory = 1024 * 1024;
1333 for (ci = 0; ci < sp->cinfo.d.num_components; ci++)
1335 const jpeg_component_info *compptr = &(sp->cinfo.d.comp_info[ci]);
1336 if (compptr->h_samp_factor > 0 && compptr->v_samp_factor > 0)
1338 nRequiredMemory +=
1339 (toff_t)(((compptr->width_in_blocks +
1340 compptr->h_samp_factor - 1) /
1341 compptr->h_samp_factor)) *
1342 ((compptr->height_in_blocks + compptr->v_samp_factor - 1) /
1343 compptr->v_samp_factor) *
1344 sizeof(JBLOCK);
1348 if (sp->cinfo.d.mem->max_memory_to_use > 0 &&
1349 nRequiredMemory > (toff_t)(sp->cinfo.d.mem->max_memory_to_use) &&
1350 getenv("LIBTIFF_ALLOW_LARGE_LIBJPEG_MEM_ALLOC") == NULL)
1352 TIFFErrorExtR(
1353 tif, module,
1354 "Reading this image would require libjpeg to allocate "
1355 "at least %" PRIu64 " bytes. "
1356 "This is disabled since above the %ld threshold. "
1357 "You may override this restriction by defining the "
1358 "LIBTIFF_ALLOW_LARGE_LIBJPEG_MEM_ALLOC environment variable, "
1359 "or setting the JPEGMEM environment variable to a value "
1360 "greater "
1361 "or equal to '%" PRIu64 "M'",
1362 nRequiredMemory, sp->cinfo.d.mem->max_memory_to_use,
1363 (nRequiredMemory + 1000000u - 1u) / 1000000u);
1364 return 0;
1368 if (td->td_planarconfig == PLANARCONFIG_CONTIG)
1370 /* Component 0 should have expected sampling factors */
1371 if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
1372 sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling)
1374 TIFFErrorExtR(tif, module,
1375 "Improper JPEG sampling factors %d,%d\n"
1376 "Apparently should be %" PRIu16 ",%" PRIu16 ".",
1377 sp->cinfo.d.comp_info[0].h_samp_factor,
1378 sp->cinfo.d.comp_info[0].v_samp_factor,
1379 sp->h_sampling, sp->v_sampling);
1380 return (0);
1382 /* Rest should have sampling factors 1,1 */
1383 for (ci = 1; ci < sp->cinfo.d.num_components; ci++)
1385 if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
1386 sp->cinfo.d.comp_info[ci].v_samp_factor != 1)
1388 TIFFErrorExtR(tif, module, "Improper JPEG sampling factors");
1389 return (0);
1393 else
1395 /* PC 2's single component should have sampling factors 1,1 */
1396 if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
1397 sp->cinfo.d.comp_info[0].v_samp_factor != 1)
1399 TIFFErrorExtR(tif, module, "Improper JPEG sampling factors");
1400 return (0);
1403 downsampled_output = FALSE;
1404 if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1405 sp->photometric == PHOTOMETRIC_YCBCR &&
1406 sp->otherSettings.jpegcolormode == JPEGCOLORMODE_RGB)
1408 /* Convert YCbCr to RGB */
1409 sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
1410 sp->cinfo.d.out_color_space = JCS_RGB;
1412 else
1414 /* Suppress colorspace handling */
1415 sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
1416 sp->cinfo.d.out_color_space = JCS_UNKNOWN;
1417 if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1418 (sp->h_sampling != 1 || sp->v_sampling != 1))
1419 downsampled_output = TRUE;
1420 /* XXX what about up-sampling? */
1422 if (downsampled_output)
1424 /* Need to use raw-data interface to libjpeg */
1425 sp->cinfo.d.raw_data_out = TRUE;
1426 #if JPEG_LIB_VERSION >= 70
1427 sp->cinfo.d.do_fancy_upsampling = FALSE;
1428 #endif /* JPEG_LIB_VERSION >= 70 */
1429 tif->tif_decoderow = DecodeRowError;
1430 tif->tif_decodestrip = JPEGDecodeRaw;
1431 tif->tif_decodetile = JPEGDecodeRaw;
1433 else
1435 /* Use normal interface to libjpeg */
1436 sp->cinfo.d.raw_data_out = FALSE;
1437 tif->tif_decoderow = JPEGDecode;
1438 tif->tif_decodestrip = JPEGDecode;
1439 tif->tif_decodetile = JPEGDecode;
1441 /* Start JPEG decompressor */
1442 if (!TIFFjpeg_start_decompress(sp))
1443 return (0);
1444 /* Allocate downsampled-data buffers if needed */
1445 if (downsampled_output)
1447 if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
1448 sp->cinfo.d.num_components))
1449 return (0);
1450 sp->scancount = DCTSIZE; /* mark buffer empty */
1452 return (1);
1456 * Decode a chunk of pixels.
1457 * "Standard" case: returned data is not downsampled.
1459 #if !JPEG_LIB_MK1_OR_12BIT
1460 static int JPEGDecode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s)
1462 JPEGState *sp = JState(tif);
1463 tmsize_t nrows;
1464 (void)s;
1467 ** Update available information, buffer may have been refilled
1468 ** between decode requests
1470 sp->src.next_input_byte = (const JOCTET *)tif->tif_rawcp;
1471 sp->src.bytes_in_buffer = (size_t)tif->tif_rawcc;
1473 if (sp->bytesperline == 0)
1474 return 0;
1476 nrows = cc / sp->bytesperline;
1477 if (cc % sp->bytesperline)
1478 TIFFWarningExtR(tif, tif->tif_name, "fractional scanline not read");
1480 if (nrows > (tmsize_t)sp->cinfo.d.image_height)
1481 nrows = sp->cinfo.d.image_height;
1483 /* data is expected to be read in multiples of a scanline */
1484 if (nrows)
1489 * In the libjpeg6b-9a 8bit case. We read directly into
1490 * the TIFF buffer.
1492 JSAMPROW bufptr = (JSAMPROW)buf;
1494 if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
1495 return (0);
1497 ++tif->tif_row;
1498 buf += sp->bytesperline;
1499 cc -= sp->bytesperline;
1500 } while (--nrows > 0);
1503 /* Update information on consumed data */
1504 tif->tif_rawcp = (uint8_t *)sp->src.next_input_byte;
1505 tif->tif_rawcc = sp->src.bytes_in_buffer;
1507 /* Close down the decompressor if we've finished the strip or tile. */
1508 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height ||
1509 TIFFjpeg_finish_decompress(sp);
1511 #endif /* !JPEG_LIB_MK1_OR_12BIT */
1513 #if JPEG_LIB_MK1_OR_12BIT
1514 /*ARGSUSED*/ static int JPEGDecode(TIFF *tif, uint8_t *buf, tmsize_t cc,
1515 uint16_t s)
1517 JPEGState *sp = JState(tif);
1518 tmsize_t nrows;
1519 (void)s;
1522 ** Update available information, buffer may have been refilled
1523 ** between decode requests
1525 sp->src.next_input_byte = (const JOCTET *)tif->tif_rawcp;
1526 sp->src.bytes_in_buffer = (size_t)tif->tif_rawcc;
1528 if (sp->bytesperline == 0)
1529 return 0;
1531 nrows = cc / sp->bytesperline;
1532 if (cc % sp->bytesperline)
1533 TIFFWarningExtR(tif, tif->tif_name, "fractional scanline not read");
1535 if (nrows > (tmsize_t)sp->cinfo.d.image_height)
1536 nrows = sp->cinfo.d.image_height;
1538 /* data is expected to be read in multiples of a scanline */
1539 if (nrows)
1541 TIFF_JSAMPROW line_work_buf = NULL;
1544 * For 6B, only use temporary buffer for 12 bit imagery.
1545 * For Mk1 always use it.
1547 if (sp->cinfo.d.data_precision == 12)
1549 line_work_buf = (TIFF_JSAMPROW)_TIFFmallocExt(
1550 tif, sizeof(short) * sp->cinfo.d.output_width *
1551 sp->cinfo.d.num_components);
1556 if (line_work_buf != NULL)
1559 * In the MK1 case, we always read into a 16bit
1560 * buffer, and then pack down to 12bit or 8bit.
1561 * In 6B case we only read into 16 bit buffer
1562 * for 12bit data, which we need to repack.
1564 if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
1565 return (0);
1567 if (sp->cinfo.d.data_precision == 12)
1569 int value_pairs = (sp->cinfo.d.output_width *
1570 sp->cinfo.d.num_components) /
1572 int iPair;
1574 for (iPair = 0; iPair < value_pairs; iPair++)
1576 unsigned char *out_ptr =
1577 ((unsigned char *)buf) + iPair * 3;
1578 TIFF_JSAMPLE *in_ptr = line_work_buf + iPair * 2;
1580 out_ptr[0] = (unsigned char)((in_ptr[0] & 0xff0) >> 4);
1581 out_ptr[1] =
1582 (unsigned char)(((in_ptr[0] & 0xf) << 4) |
1583 ((in_ptr[1] & 0xf00) >> 8));
1584 out_ptr[2] = (unsigned char)(((in_ptr[1] & 0xff) >> 0));
1587 else if (sp->cinfo.d.data_precision == 8)
1589 int value_count =
1590 (sp->cinfo.d.output_width * sp->cinfo.d.num_components);
1591 int iValue;
1593 for (iValue = 0; iValue < value_count; iValue++)
1595 ((unsigned char *)buf)[iValue] =
1596 line_work_buf[iValue] & 0xff;
1601 ++tif->tif_row;
1602 buf += sp->bytesperline;
1603 cc -= sp->bytesperline;
1604 } while (--nrows > 0);
1606 if (line_work_buf != NULL)
1607 _TIFFfreeExt(tif, line_work_buf);
1610 /* Update information on consumed data */
1611 tif->tif_rawcp = (uint8_t *)sp->src.next_input_byte;
1612 tif->tif_rawcc = sp->src.bytes_in_buffer;
1614 /* Close down the decompressor if we've finished the strip or tile. */
1615 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height ||
1616 TIFFjpeg_finish_decompress(sp);
1618 #endif /* JPEG_LIB_MK1_OR_12BIT */
1620 /*ARGSUSED*/ static int DecodeRowError(TIFF *tif, uint8_t *buf, tmsize_t cc,
1621 uint16_t s)
1624 (void)buf;
1625 (void)cc;
1626 (void)s;
1628 TIFFErrorExtR(
1629 tif, "TIFFReadScanline",
1630 "scanline oriented access is not supported for downsampled JPEG "
1631 "compressed images, consider enabling TIFFTAG_JPEGCOLORMODE as "
1632 "JPEGCOLORMODE_RGB.");
1633 return 0;
1637 * Decode a chunk of pixels.
1638 * Returned data is downsampled per sampling factors.
1640 /*ARGSUSED*/ static int JPEGDecodeRaw(TIFF *tif, uint8_t *buf, tmsize_t cc,
1641 uint16_t s)
1643 JPEGState *sp = JState(tif);
1644 tmsize_t nrows;
1645 TIFFDirectory *td = &tif->tif_dir;
1646 (void)s;
1648 nrows = sp->cinfo.d.image_height;
1649 /* For last strip, limit number of rows to its truncated height */
1650 /* even if the codestream height is larger (which is not compliant, */
1651 /* but that we tolerate) */
1652 if ((uint32_t)nrows > td->td_imagelength - tif->tif_row && !isTiled(tif))
1653 nrows = td->td_imagelength - tif->tif_row;
1655 #if defined(JPEG_LIB_MK1_OR_12BIT)
1656 unsigned short *tmpbuf = NULL;
1657 #endif
1659 /* data is expected to be read in multiples of a scanline */
1660 if (nrows != 0)
1663 /* Cb,Cr both have sampling factors 1, so this is correct */
1664 JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
1665 int samples_per_clump = sp->samplesperclump;
1667 #if defined(JPEG_LIB_MK1_OR_12BIT)
1668 tmpbuf = _TIFFmallocExt(tif, sizeof(unsigned short) *
1669 sp->cinfo.d.output_width *
1670 sp->cinfo.d.num_components);
1671 if (tmpbuf == NULL)
1673 TIFFErrorExtR(tif, "JPEGDecodeRaw", "Out of memory");
1674 return 0;
1676 #endif
1680 jpeg_component_info *compptr;
1681 int ci, clumpoffset;
1683 if (cc < sp->bytesperline)
1685 TIFFErrorExtR(
1686 tif, "JPEGDecodeRaw",
1687 "application buffer not large enough for all data.");
1688 goto error;
1691 /* Reload downsampled-data buffer if needed */
1692 if (sp->scancount >= DCTSIZE)
1694 int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
1695 if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
1696 goto error;
1697 sp->scancount = 0;
1700 * Fastest way to unseparate data is to make one pass
1701 * over the scanline for each row of each component.
1703 clumpoffset = 0; /* first sample in clump */
1704 for (ci = 0, compptr = sp->cinfo.d.comp_info;
1705 ci < sp->cinfo.d.num_components; ci++, compptr++)
1707 int hsamp = compptr->h_samp_factor;
1708 int vsamp = compptr->v_samp_factor;
1709 int ypos;
1711 for (ypos = 0; ypos < vsamp; ypos++)
1713 TIFF_JSAMPLE *inptr =
1714 sp->ds_buffer[ci][sp->scancount * vsamp + ypos];
1715 JDIMENSION nclump;
1716 #if defined(JPEG_LIB_MK1_OR_12BIT)
1717 TIFF_JSAMPLE *outptr = (TIFF_JSAMPLE *)tmpbuf + clumpoffset;
1718 #else
1719 TIFF_JSAMPLE *outptr = (TIFF_JSAMPLE *)buf + clumpoffset;
1720 if (cc < (tmsize_t)(clumpoffset +
1721 (tmsize_t)samples_per_clump *
1722 (clumps_per_line - 1) +
1723 hsamp))
1725 TIFFErrorExtR(
1726 tif, "JPEGDecodeRaw",
1727 "application buffer not large enough for all data, "
1728 "possible subsampling issue");
1729 goto error;
1731 #endif
1733 if (hsamp == 1)
1735 /* fast path for at least Cb and Cr */
1736 for (nclump = clumps_per_line; nclump-- > 0;)
1738 outptr[0] = *inptr++;
1739 outptr += samples_per_clump;
1742 else
1744 int xpos;
1746 /* general case */
1747 for (nclump = clumps_per_line; nclump-- > 0;)
1749 for (xpos = 0; xpos < hsamp; xpos++)
1750 outptr[xpos] = *inptr++;
1751 outptr += samples_per_clump;
1754 clumpoffset += hsamp;
1758 #if defined(JPEG_LIB_MK1_OR_12BIT)
1760 if (sp->cinfo.d.data_precision == 8)
1762 int i = 0;
1763 int len =
1764 sp->cinfo.d.output_width * sp->cinfo.d.num_components;
1765 for (i = 0; i < len; i++)
1767 ((unsigned char *)buf)[i] = tmpbuf[i] & 0xff;
1770 else
1771 { /* 12-bit */
1772 int value_pairs = (sp->cinfo.d.output_width *
1773 sp->cinfo.d.num_components) /
1775 int iPair;
1776 for (iPair = 0; iPair < value_pairs; iPair++)
1778 unsigned char *out_ptr =
1779 ((unsigned char *)buf) + iPair * 3;
1780 JSAMPLE *in_ptr = (JSAMPLE *)(tmpbuf + iPair * 2);
1781 out_ptr[0] = (unsigned char)((in_ptr[0] & 0xff0) >> 4);
1782 out_ptr[1] =
1783 (unsigned char)(((in_ptr[0] & 0xf) << 4) |
1784 ((in_ptr[1] & 0xf00) >> 8));
1785 out_ptr[2] = (unsigned char)(((in_ptr[1] & 0xff) >> 0));
1789 #endif
1791 sp->scancount++;
1792 tif->tif_row += sp->v_sampling;
1794 buf += sp->bytesperline;
1795 cc -= sp->bytesperline;
1797 nrows -= sp->v_sampling;
1798 } while (nrows > 0);
1800 #if defined(JPEG_LIB_MK1_OR_12BIT)
1801 _TIFFfreeExt(tif, tmpbuf);
1802 #endif
1805 /* Close down the decompressor if done. */
1806 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height ||
1807 TIFFjpeg_finish_decompress(sp);
1809 error:
1810 #if defined(JPEG_LIB_MK1_OR_12BIT)
1811 _TIFFfreeExt(tif, tmpbuf);
1812 #endif
1813 return 0;
1817 * JPEG Encoding.
1820 static void unsuppress_quant_table(JPEGState *sp, int tblno)
1822 JQUANT_TBL *qtbl;
1824 if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1825 qtbl->sent_table = FALSE;
1828 static void suppress_quant_table(JPEGState *sp, int tblno)
1830 JQUANT_TBL *qtbl;
1832 if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1833 qtbl->sent_table = TRUE;
1836 static void unsuppress_huff_table(JPEGState *sp, int tblno)
1838 JHUFF_TBL *htbl;
1840 if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1841 htbl->sent_table = FALSE;
1842 if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1843 htbl->sent_table = FALSE;
1846 static void suppress_huff_table(JPEGState *sp, int tblno)
1848 JHUFF_TBL *htbl;
1850 if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1851 htbl->sent_table = TRUE;
1852 if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1853 htbl->sent_table = TRUE;
1856 static int prepare_JPEGTables(TIFF *tif)
1858 JPEGState *sp = JState(tif);
1860 /* Initialize quant tables for current quality setting */
1861 if (!TIFFjpeg_set_quality(sp, sp->otherSettings.jpegquality, FALSE))
1862 return (0);
1863 /* Mark only the tables we want for output */
1864 /* NB: chrominance tables are currently used only with YCbCr */
1865 if (!TIFFjpeg_suppress_tables(sp, TRUE))
1866 return (0);
1867 if (sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_QUANT)
1869 unsuppress_quant_table(sp, 0);
1870 if (sp->photometric == PHOTOMETRIC_YCBCR)
1871 unsuppress_quant_table(sp, 1);
1873 if (sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_HUFF)
1875 unsuppress_huff_table(sp, 0);
1876 if (sp->photometric == PHOTOMETRIC_YCBCR)
1877 unsuppress_huff_table(sp, 1);
1879 /* Direct libjpeg output into otherSettings.jpegtables */
1880 if (!TIFFjpeg_tables_dest(sp, tif))
1881 return (0);
1882 /* Emit tables-only datastream */
1883 if (!TIFFjpeg_write_tables(sp))
1884 return (0);
1886 return (1);
1889 #if defined(JPEG_LIB_VERSION_MAJOR) && \
1890 (JPEG_LIB_VERSION_MAJOR > 9 || \
1891 (JPEG_LIB_VERSION_MAJOR == 9 && JPEG_LIB_VERSION_MINOR >= 4))
1892 /* This is a modified version of std_huff_tables() from jcparam.c
1893 * in libjpeg-9d because it no longer initializes default Huffman
1894 * tables in jpeg_set_defaults(). */
1895 static void TIFF_std_huff_tables(j_compress_ptr cinfo)
1898 if (cinfo->dc_huff_tbl_ptrs[0] == NULL)
1900 (void)jpeg_std_huff_table((j_common_ptr)cinfo, TRUE, 0);
1902 if (cinfo->ac_huff_tbl_ptrs[0] == NULL)
1904 (void)jpeg_std_huff_table((j_common_ptr)cinfo, FALSE, 0);
1906 if (cinfo->dc_huff_tbl_ptrs[1] == NULL)
1908 (void)jpeg_std_huff_table((j_common_ptr)cinfo, TRUE, 1);
1910 if (cinfo->ac_huff_tbl_ptrs[1] == NULL)
1912 (void)jpeg_std_huff_table((j_common_ptr)cinfo, FALSE, 1);
1915 #endif
1917 static int JPEGSetupEncode(TIFF *tif)
1919 JPEGState *sp = JState(tif);
1920 TIFFDirectory *td = &tif->tif_dir;
1921 static const char module[] = "JPEGSetupEncode";
1923 #if defined(JPEG_DUAL_MODE_8_12) && !defined(FROM_TIF_JPEG_12)
1924 if (tif->tif_dir.td_bitspersample == 12)
1926 /* We pass a pointer to a copy of otherSettings, since */
1927 /* TIFFReInitJPEG_12() will clear sp */
1928 JPEGOtherSettings savedOtherSettings = sp->otherSettings;
1929 return TIFFReInitJPEG_12(tif, &savedOtherSettings, COMPRESSION_JPEG, 1);
1931 #endif
1933 JPEGInitializeLibJPEG(tif, FALSE);
1935 assert(sp != NULL);
1936 assert(!sp->cinfo.comm.is_decompressor);
1938 sp->photometric = td->td_photometric;
1941 * Initialize all JPEG parameters to default values.
1942 * Note that jpeg_set_defaults needs legal values for
1943 * in_color_space and input_components.
1945 if (td->td_planarconfig == PLANARCONFIG_CONTIG)
1947 sp->cinfo.c.input_components = td->td_samplesperpixel;
1948 if (sp->photometric == PHOTOMETRIC_YCBCR)
1950 if (sp->otherSettings.jpegcolormode == JPEGCOLORMODE_RGB)
1952 sp->cinfo.c.in_color_space = JCS_RGB;
1954 else
1956 sp->cinfo.c.in_color_space = JCS_YCbCr;
1959 else
1961 if ((td->td_photometric == PHOTOMETRIC_MINISWHITE ||
1962 td->td_photometric == PHOTOMETRIC_MINISBLACK) &&
1963 td->td_samplesperpixel == 1)
1964 sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
1965 else if (td->td_photometric == PHOTOMETRIC_RGB &&
1966 td->td_samplesperpixel == 3)
1967 sp->cinfo.c.in_color_space = JCS_RGB;
1968 else if (td->td_photometric == PHOTOMETRIC_SEPARATED &&
1969 td->td_samplesperpixel == 4)
1970 sp->cinfo.c.in_color_space = JCS_CMYK;
1971 else
1972 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1975 else
1977 sp->cinfo.c.input_components = 1;
1978 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1980 if (!TIFFjpeg_set_defaults(sp))
1981 return (0);
1983 /* mozjpeg by default enables progressive JPEG, which is illegal in
1984 * JPEG-in-TIFF */
1985 /* So explicitly disable it. */
1986 if (sp->cinfo.c.num_scans != 0 &&
1987 (sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_HUFF) != 0)
1989 /* it has been found that mozjpeg could create corrupt strips/tiles */
1990 /* in non optimize_coding mode. */
1991 TIFFWarningExtR(
1992 tif, module,
1993 "mozjpeg library likely detected. Disable emission of "
1994 "Huffman tables in JpegTables tag, and use optimize_coding "
1995 "to avoid potential issues");
1996 sp->otherSettings.jpegtablesmode &= ~JPEGTABLESMODE_HUFF;
1998 sp->cinfo.c.num_scans = 0;
1999 sp->cinfo.c.scan_info = NULL;
2001 /* Set per-file parameters */
2002 switch (sp->photometric)
2004 case PHOTOMETRIC_YCBCR:
2005 sp->h_sampling = td->td_ycbcrsubsampling[0];
2006 sp->v_sampling = td->td_ycbcrsubsampling[1];
2007 if (sp->h_sampling == 0 || sp->v_sampling == 0)
2009 TIFFErrorExtR(tif, module,
2010 "Invalig horizontal/vertical sampling value");
2011 return (0);
2013 if (td->td_bitspersample > 16)
2015 TIFFErrorExtR(tif, module,
2016 "BitsPerSample %" PRIu16 " not allowed for JPEG",
2017 td->td_bitspersample);
2018 return (0);
2022 * A ReferenceBlackWhite field *must* be present since the
2023 * default value is inappropriate for YCbCr. Fill in the
2024 * proper value if application didn't set it.
2027 float *ref;
2028 if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE, &ref))
2030 float refbw[6];
2031 long top = 1L << td->td_bitspersample;
2032 refbw[0] = 0;
2033 refbw[1] = (float)(top - 1L);
2034 refbw[2] = (float)(top >> 1);
2035 refbw[3] = refbw[1];
2036 refbw[4] = refbw[2];
2037 refbw[5] = refbw[1];
2038 TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE, refbw);
2041 break;
2042 case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */
2043 case PHOTOMETRIC_MASK:
2044 TIFFErrorExtR(tif, module,
2045 "PhotometricInterpretation %" PRIu16
2046 " not allowed for JPEG",
2047 sp->photometric);
2048 return (0);
2049 default:
2050 /* TIFF 6.0 forbids subsampling of all other color spaces */
2051 sp->h_sampling = 1;
2052 sp->v_sampling = 1;
2053 break;
2056 /* Verify miscellaneous parameters */
2059 * This would need work if libtiff ever supports different
2060 * depths for different components, or if libjpeg ever supports
2061 * run-time selection of depth. Neither is imminent.
2063 #ifdef JPEG_LIB_MK1
2064 /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
2065 if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
2066 #else
2067 if (td->td_bitspersample != BITS_IN_JSAMPLE)
2068 #endif
2070 TIFFErrorExtR(tif, module,
2071 "BitsPerSample %" PRIu16 " not allowed for JPEG",
2072 td->td_bitspersample);
2073 return (0);
2075 sp->cinfo.c.data_precision = td->td_bitspersample;
2076 #ifdef JPEG_LIB_MK1
2077 sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
2078 #endif
2079 if (isTiled(tif))
2081 if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0)
2083 TIFFErrorExtR(tif, module,
2084 "JPEG tile height must be multiple of %" PRIu32,
2085 (uint32_t)(sp->v_sampling * DCTSIZE));
2086 return (0);
2088 if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0)
2090 TIFFErrorExtR(tif, module,
2091 "JPEG tile width must be multiple of %" PRIu32,
2092 (uint32_t)(sp->h_sampling * DCTSIZE));
2093 return (0);
2096 else
2098 if (td->td_rowsperstrip < td->td_imagelength &&
2099 (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0)
2101 TIFFErrorExtR(tif, module,
2102 "RowsPerStrip must be multiple of %" PRIu32
2103 " for JPEG",
2104 (uint32_t)(sp->v_sampling * DCTSIZE));
2105 return (0);
2109 /* Create a JPEGTables field if appropriate */
2110 if (sp->otherSettings.jpegtablesmode &
2111 (JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF))
2113 if (sp->otherSettings.jpegtables == NULL ||
2114 memcmp(sp->otherSettings.jpegtables, "\0\0\0\0\0\0\0\0\0", 8) == 0)
2116 #if defined(JPEG_LIB_VERSION_MAJOR) && \
2117 (JPEG_LIB_VERSION_MAJOR > 9 || \
2118 (JPEG_LIB_VERSION_MAJOR == 9 && JPEG_LIB_VERSION_MINOR >= 4))
2119 if ((sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_HUFF) != 0 &&
2120 (sp->cinfo.c.dc_huff_tbl_ptrs[0] == NULL ||
2121 sp->cinfo.c.dc_huff_tbl_ptrs[1] == NULL ||
2122 sp->cinfo.c.ac_huff_tbl_ptrs[0] == NULL ||
2123 sp->cinfo.c.ac_huff_tbl_ptrs[1] == NULL))
2125 /* libjpeg-9d no longer initializes default Huffman tables in */
2126 /* jpeg_set_defaults() */
2127 TIFF_std_huff_tables(&sp->cinfo.c);
2129 #endif
2131 if (!prepare_JPEGTables(tif))
2132 return (0);
2133 /* Mark the field present */
2134 /* Can't use TIFFSetField since BEENWRITING is already set! */
2135 tif->tif_flags |= TIFF_DIRTYDIRECT;
2136 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2139 else
2141 /* We do not support application-supplied JPEGTables, */
2142 /* so mark the field not present */
2143 TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
2146 /* Direct libjpeg output to libtiff's output buffer */
2147 TIFFjpeg_data_dest(sp, tif);
2149 return (1);
2153 * Set encoding state at the start of a strip or tile.
2155 static int JPEGPreEncode(TIFF *tif, uint16_t s)
2157 JPEGState *sp = JState(tif);
2158 TIFFDirectory *td = &tif->tif_dir;
2159 static const char module[] = "JPEGPreEncode";
2160 uint32_t segment_width, segment_height;
2161 int downsampled_input;
2163 assert(sp != NULL);
2165 if (sp->cinfo.comm.is_decompressor == 1)
2167 tif->tif_setupencode(tif);
2170 assert(!sp->cinfo.comm.is_decompressor);
2172 * Set encoding parameters for this strip/tile.
2174 if (isTiled(tif))
2176 segment_width = td->td_tilewidth;
2177 segment_height = td->td_tilelength;
2178 sp->bytesperline = TIFFTileRowSize(tif);
2180 else
2182 segment_width = td->td_imagewidth;
2183 segment_height = td->td_imagelength - tif->tif_row;
2184 if (segment_height > td->td_rowsperstrip)
2185 segment_height = td->td_rowsperstrip;
2186 sp->bytesperline = TIFFScanlineSize(tif);
2188 if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0)
2190 /* for PC 2, scale down the strip/tile size
2191 * to match a downsampled component
2193 segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
2194 segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
2196 if (segment_width > 65535 || segment_height > 65535)
2198 TIFFErrorExtR(tif, module, "Strip/tile too large for JPEG");
2199 return (0);
2201 sp->cinfo.c.image_width = segment_width;
2202 sp->cinfo.c.image_height = segment_height;
2203 downsampled_input = FALSE;
2204 if (td->td_planarconfig == PLANARCONFIG_CONTIG)
2206 sp->cinfo.c.input_components = td->td_samplesperpixel;
2207 if (sp->photometric == PHOTOMETRIC_YCBCR)
2209 if (sp->otherSettings.jpegcolormode != JPEGCOLORMODE_RGB)
2211 if (sp->h_sampling != 1 || sp->v_sampling != 1)
2212 downsampled_input = TRUE;
2214 if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
2215 return (0);
2217 * Set Y sampling factors;
2218 * we assume jpeg_set_colorspace() set the rest to 1
2220 sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
2221 sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
2223 else
2225 if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
2226 return (0);
2227 /* jpeg_set_colorspace set all sampling factors to 1 */
2230 else
2232 if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
2233 return (0);
2234 sp->cinfo.c.comp_info[0].component_id = s;
2235 /* jpeg_set_colorspace() set sampling factors to 1 */
2236 if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0)
2238 sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
2239 sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
2240 sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
2243 /* ensure libjpeg won't write any extraneous markers */
2244 sp->cinfo.c.write_JFIF_header = FALSE;
2245 sp->cinfo.c.write_Adobe_marker = FALSE;
2246 /* set up table handling correctly */
2247 /* calling TIFFjpeg_set_quality() causes quantization tables to be flagged
2249 /* as being to be emitted, which we don't want in the JPEGTABLESMODE_QUANT
2251 /* mode, so we must manually suppress them. However TIFFjpeg_set_quality()
2253 /* should really be called when dealing with files with directories with */
2254 /* mixed qualities. see http://trac.osgeo.org/gdal/ticket/3539 */
2255 if (!TIFFjpeg_set_quality(sp, sp->otherSettings.jpegquality, FALSE))
2256 return (0);
2257 if (sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_QUANT)
2259 suppress_quant_table(sp, 0);
2260 suppress_quant_table(sp, 1);
2262 else
2264 unsuppress_quant_table(sp, 0);
2265 unsuppress_quant_table(sp, 1);
2267 if (sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_HUFF)
2269 /* Explicit suppression is only needed if we did not go through the */
2270 /* prepare_JPEGTables() code path, which may be the case if updating */
2271 /* an existing file */
2272 suppress_huff_table(sp, 0);
2273 suppress_huff_table(sp, 1);
2274 sp->cinfo.c.optimize_coding = FALSE;
2276 else
2277 sp->cinfo.c.optimize_coding = TRUE;
2278 if (downsampled_input)
2280 /* Need to use raw-data interface to libjpeg */
2281 sp->cinfo.c.raw_data_in = TRUE;
2282 tif->tif_encoderow = JPEGEncodeRaw;
2283 tif->tif_encodestrip = JPEGEncodeRaw;
2284 tif->tif_encodetile = JPEGEncodeRaw;
2286 else
2288 /* Use normal interface to libjpeg */
2289 sp->cinfo.c.raw_data_in = FALSE;
2290 tif->tif_encoderow = JPEGEncode;
2291 tif->tif_encodestrip = JPEGEncode;
2292 tif->tif_encodetile = JPEGEncode;
2294 /* Start JPEG compressor */
2295 if (!TIFFjpeg_start_compress(sp, FALSE))
2296 return (0);
2297 /* Allocate downsampled-data buffers if needed */
2298 if (downsampled_input)
2300 if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
2301 sp->cinfo.c.num_components))
2302 return (0);
2304 sp->scancount = 0;
2306 return (1);
2310 * Encode a chunk of pixels.
2311 * "Standard" case: incoming data is not downsampled.
2313 static int JPEGEncode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s)
2315 JPEGState *sp = JState(tif);
2316 tmsize_t nrows;
2317 TIFF_JSAMPROW bufptr[1];
2318 short *line16 = NULL;
2319 int line16_count = 0;
2321 (void)s;
2322 assert(sp != NULL);
2323 /* data is expected to be supplied in multiples of a scanline */
2324 nrows = cc / sp->bytesperline;
2325 if (cc % sp->bytesperline)
2326 TIFFWarningExtR(tif, tif->tif_name, "fractional scanline discarded");
2328 /* The last strip will be limited to image size */
2329 if (!isTiled(tif) && tif->tif_row + nrows > tif->tif_dir.td_imagelength)
2330 nrows = tif->tif_dir.td_imagelength - tif->tif_row;
2332 if (sp->cinfo.c.data_precision == 12)
2334 line16_count = (int)((sp->bytesperline * 2) / 3);
2335 line16 = (short *)_TIFFmallocExt(tif, sizeof(short) * line16_count);
2336 if (!line16)
2338 TIFFErrorExtR(tif, "JPEGEncode", "Failed to allocate memory");
2340 return 0;
2344 while (nrows-- > 0)
2347 if (sp->cinfo.c.data_precision == 12)
2350 int value_pairs = line16_count / 2;
2351 int iPair;
2353 bufptr[0] = (TIFF_JSAMPROW)line16;
2355 for (iPair = 0; iPair < value_pairs; iPair++)
2357 unsigned char *in_ptr = ((unsigned char *)buf) + iPair * 3;
2358 TIFF_JSAMPLE *out_ptr = (TIFF_JSAMPLE *)(line16 + iPair * 2);
2360 out_ptr[0] = (in_ptr[0] << 4) | ((in_ptr[1] & 0xf0) >> 4);
2361 out_ptr[1] = ((in_ptr[1] & 0x0f) << 8) | in_ptr[2];
2364 else
2366 bufptr[0] = (TIFF_JSAMPROW)buf;
2368 if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
2369 return (0);
2370 if (nrows > 0)
2371 tif->tif_row++;
2372 buf += sp->bytesperline;
2375 if (sp->cinfo.c.data_precision == 12)
2377 _TIFFfreeExt(tif, line16);
2380 return (1);
2384 * Encode a chunk of pixels.
2385 * Incoming data is expected to be downsampled per sampling factors.
2387 static int JPEGEncodeRaw(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s)
2389 JPEGState *sp = JState(tif);
2390 TIFF_JSAMPLE *inptr;
2391 TIFF_JSAMPLE *outptr;
2392 tmsize_t nrows;
2393 JDIMENSION clumps_per_line, nclump;
2394 int clumpoffset, ci, xpos, ypos;
2395 jpeg_component_info *compptr;
2396 int samples_per_clump = sp->samplesperclump;
2397 tmsize_t bytesperclumpline;
2399 (void)s;
2400 assert(sp != NULL);
2401 /* data is expected to be supplied in multiples of a clumpline */
2402 /* a clumpline is equivalent to v_sampling desubsampled scanlines */
2403 /* TODO: the following calculation of bytesperclumpline, should substitute
2404 * calculation of sp->bytesperline, except that it is per v_sampling lines
2406 bytesperclumpline =
2407 ((((tmsize_t)sp->cinfo.c.image_width + sp->h_sampling - 1) /
2408 sp->h_sampling) *
2409 ((tmsize_t)sp->h_sampling * sp->v_sampling + 2) *
2410 sp->cinfo.c.data_precision +
2411 7) /
2414 nrows = (cc / bytesperclumpline) * sp->v_sampling;
2415 if (cc % bytesperclumpline)
2416 TIFFWarningExtR(tif, tif->tif_name, "fractional scanline discarded");
2418 /* Cb,Cr both have sampling factors 1, so this is correct */
2419 clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
2421 while (nrows > 0)
2424 * Fastest way to separate the data is to make one pass
2425 * over the scanline for each row of each component.
2427 clumpoffset = 0; /* first sample in clump */
2428 for (ci = 0, compptr = sp->cinfo.c.comp_info;
2429 ci < sp->cinfo.c.num_components; ci++, compptr++)
2431 int hsamp = compptr->h_samp_factor;
2432 int vsamp = compptr->v_samp_factor;
2433 int padding = (int)(compptr->width_in_blocks * DCTSIZE -
2434 clumps_per_line * hsamp);
2435 for (ypos = 0; ypos < vsamp; ypos++)
2437 inptr = ((TIFF_JSAMPLE *)buf) + clumpoffset;
2438 outptr = sp->ds_buffer[ci][sp->scancount * vsamp + ypos];
2439 if (hsamp == 1)
2441 /* fast path for at least Cb and Cr */
2442 for (nclump = clumps_per_line; nclump-- > 0;)
2444 *outptr++ = inptr[0];
2445 inptr += samples_per_clump;
2448 else
2450 /* general case */
2451 for (nclump = clumps_per_line; nclump-- > 0;)
2453 for (xpos = 0; xpos < hsamp; xpos++)
2454 *outptr++ = inptr[xpos];
2455 inptr += samples_per_clump;
2458 /* pad each scanline as needed */
2459 for (xpos = 0; xpos < padding; xpos++)
2461 *outptr = outptr[-1];
2462 outptr++;
2464 clumpoffset += hsamp;
2467 sp->scancount++;
2468 if (sp->scancount >= DCTSIZE)
2470 int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
2471 if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
2472 return (0);
2473 sp->scancount = 0;
2475 tif->tif_row += sp->v_sampling;
2476 buf += bytesperclumpline;
2477 nrows -= sp->v_sampling;
2479 return (1);
2483 * Finish up at the end of a strip or tile.
2485 static int JPEGPostEncode(TIFF *tif)
2487 JPEGState *sp = JState(tif);
2489 if (sp->scancount > 0)
2492 * Need to emit a partial bufferload of downsampled data.
2493 * Pad the data vertically.
2495 int ci, ypos, n;
2496 jpeg_component_info *compptr;
2498 for (ci = 0, compptr = sp->cinfo.c.comp_info;
2499 ci < sp->cinfo.c.num_components; ci++, compptr++)
2501 int vsamp = compptr->v_samp_factor;
2502 tmsize_t row_width =
2503 compptr->width_in_blocks * DCTSIZE * sizeof(JSAMPLE);
2504 for (ypos = sp->scancount * vsamp; ypos < DCTSIZE * vsamp; ypos++)
2506 _TIFFmemcpy((void *)sp->ds_buffer[ci][ypos],
2507 (void *)sp->ds_buffer[ci][ypos - 1], row_width);
2510 n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
2511 if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
2512 return (0);
2515 return (TIFFjpeg_finish_compress(JState(tif)));
2518 static void JPEGCleanup(TIFF *tif)
2520 JPEGState *sp = JState(tif);
2522 assert(sp != 0);
2524 tif->tif_tagmethods.vgetfield = sp->otherSettings.vgetparent;
2525 tif->tif_tagmethods.vsetfield = sp->otherSettings.vsetparent;
2526 tif->tif_tagmethods.printdir = sp->otherSettings.printdir;
2527 if (sp->cinfo_initialized)
2528 TIFFjpeg_destroy(sp); /* release libjpeg resources */
2529 if (sp->otherSettings.jpegtables) /* tag value */
2530 _TIFFfreeExt(tif, sp->otherSettings.jpegtables);
2531 _TIFFfreeExt(tif, tif->tif_data); /* release local state */
2532 tif->tif_data = NULL;
2534 _TIFFSetDefaultCompressionState(tif);
2537 static void JPEGResetUpsampled(TIFF *tif)
2539 JPEGState *sp = JState(tif);
2540 TIFFDirectory *td = &tif->tif_dir;
2543 * Mark whether returned data is up-sampled or not so TIFFStripSize
2544 * and TIFFTileSize return values that reflect the true amount of
2545 * data.
2547 tif->tif_flags &= ~TIFF_UPSAMPLED;
2548 if (td->td_planarconfig == PLANARCONFIG_CONTIG)
2550 if (td->td_photometric == PHOTOMETRIC_YCBCR &&
2551 sp->otherSettings.jpegcolormode == JPEGCOLORMODE_RGB)
2553 tif->tif_flags |= TIFF_UPSAMPLED;
2555 else
2557 #ifdef notdef
2558 if (td->td_ycbcrsubsampling[0] != 1 ||
2559 td->td_ycbcrsubsampling[1] != 1)
2560 ; /* XXX what about up-sampling? */
2561 #endif
2566 * Must recalculate cached tile size in case sampling state changed.
2567 * Should we really be doing this now if image size isn't set?
2569 if (tif->tif_tilesize > 0)
2570 tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
2571 if (tif->tif_scanlinesize > 0)
2572 tif->tif_scanlinesize = TIFFScanlineSize(tif);
2575 static int JPEGVSetField(TIFF *tif, uint32_t tag, va_list ap)
2577 JPEGState *sp = JState(tif);
2578 const TIFFField *fip;
2579 uint32_t v32;
2581 assert(sp != NULL);
2583 switch (tag)
2585 case TIFFTAG_JPEGTABLES:
2586 v32 = (uint32_t)va_arg(ap, uint32_t);
2587 if (v32 == 0)
2589 /* XXX */
2590 return (0);
2592 _TIFFsetByteArrayExt(tif, &sp->otherSettings.jpegtables,
2593 va_arg(ap, void *), v32);
2594 sp->otherSettings.jpegtables_length = v32;
2595 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2596 break;
2597 case TIFFTAG_JPEGQUALITY:
2598 sp->otherSettings.jpegquality = (int)va_arg(ap, int);
2599 return (1); /* pseudo tag */
2600 case TIFFTAG_JPEGCOLORMODE:
2601 sp->otherSettings.jpegcolormode = (int)va_arg(ap, int);
2602 JPEGResetUpsampled(tif);
2603 return (1); /* pseudo tag */
2604 case TIFFTAG_PHOTOMETRIC:
2606 int ret_value = (*sp->otherSettings.vsetparent)(tif, tag, ap);
2607 JPEGResetUpsampled(tif);
2608 return ret_value;
2610 case TIFFTAG_JPEGTABLESMODE:
2611 sp->otherSettings.jpegtablesmode = (int)va_arg(ap, int);
2612 return (1); /* pseudo tag */
2613 case TIFFTAG_YCBCRSUBSAMPLING:
2614 /* mark the fact that we have a real ycbcrsubsampling! */
2615 sp->otherSettings.ycbcrsampling_fetched = 1;
2616 /* should we be recomputing upsampling info here? */
2617 return (*sp->otherSettings.vsetparent)(tif, tag, ap);
2618 default:
2619 return (*sp->otherSettings.vsetparent)(tif, tag, ap);
2622 if ((fip = TIFFFieldWithTag(tif, tag)) != NULL)
2624 TIFFSetFieldBit(tif, fip->field_bit);
2626 else
2628 return (0);
2631 tif->tif_flags |= TIFF_DIRTYDIRECT;
2632 return (1);
2635 static int JPEGVGetField(TIFF *tif, uint32_t tag, va_list ap)
2637 JPEGState *sp = JState(tif);
2639 assert(sp != NULL);
2641 switch (tag)
2643 case TIFFTAG_JPEGTABLES:
2644 *va_arg(ap, uint32_t *) = sp->otherSettings.jpegtables_length;
2645 *va_arg(ap, const void **) = sp->otherSettings.jpegtables;
2646 break;
2647 case TIFFTAG_JPEGQUALITY:
2648 *va_arg(ap, int *) = sp->otherSettings.jpegquality;
2649 break;
2650 case TIFFTAG_JPEGCOLORMODE:
2651 *va_arg(ap, int *) = sp->otherSettings.jpegcolormode;
2652 break;
2653 case TIFFTAG_JPEGTABLESMODE:
2654 *va_arg(ap, int *) = sp->otherSettings.jpegtablesmode;
2655 break;
2656 default:
2657 return (*sp->otherSettings.vgetparent)(tif, tag, ap);
2659 return (1);
2662 static void JPEGPrintDir(TIFF *tif, FILE *fd, long flags)
2664 JPEGState *sp = JState(tif);
2666 assert(sp != NULL);
2667 (void)flags;
2669 if (sp != NULL)
2671 if (TIFFFieldSet(tif, FIELD_JPEGTABLES))
2672 fprintf(fd, " JPEG Tables: (%" PRIu32 " bytes)\n",
2673 sp->otherSettings.jpegtables_length);
2674 if (sp->otherSettings.printdir)
2675 (*sp->otherSettings.printdir)(tif, fd, flags);
2679 static uint32_t JPEGDefaultStripSize(TIFF *tif, uint32_t s)
2681 JPEGState *sp = JState(tif);
2682 TIFFDirectory *td = &tif->tif_dir;
2684 s = (*sp->otherSettings.defsparent)(tif, s);
2685 if (s < td->td_imagelength)
2686 s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
2687 return (s);
2690 static void JPEGDefaultTileSize(TIFF *tif, uint32_t *tw, uint32_t *th)
2692 JPEGState *sp = JState(tif);
2693 TIFFDirectory *td = &tif->tif_dir;
2695 (*sp->otherSettings.deftparent)(tif, tw, th);
2696 *tw = TIFFroundup_32(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
2697 *th = TIFFroundup_32(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
2701 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
2702 * now that we allow a TIFF file to be opened in update mode it is necessary
2703 * to have some way of deciding whether compression or decompression is
2704 * desired other than looking at tif->tif_mode. We accomplish this by
2705 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
2706 * If so, we assume decompression is desired.
2708 * This is tricky, because TIFFInitJPEG() is called while the directory is
2709 * being read, and generally speaking the BYTECOUNTS tag won't have been read
2710 * at that point. So we try to defer jpeg library initialization till we
2711 * do have that tag ... basically any access that might require the compressor
2712 * or decompressor that occurs after the reading of the directory.
2714 * In an ideal world compressors or decompressors would be setup
2715 * at the point where a single tile or strip was accessed (for read or write)
2716 * so that stuff like update of missing tiles, or replacement of tiles could
2717 * be done. However, we aren't trying to crack that nut just yet ...
2719 * NFW, Feb 3rd, 2003.
2722 static int JPEGInitializeLibJPEG(TIFF *tif, int decompress)
2724 JPEGState *sp = JState(tif);
2726 if (sp->cinfo_initialized)
2728 if (!decompress && sp->cinfo.comm.is_decompressor)
2729 TIFFjpeg_destroy(sp);
2730 else if (decompress && !sp->cinfo.comm.is_decompressor)
2731 TIFFjpeg_destroy(sp);
2732 else
2733 return 1;
2735 sp->cinfo_initialized = 0;
2739 * Initialize libjpeg.
2741 if (decompress)
2743 if (!TIFFjpeg_create_decompress(sp))
2744 return (0);
2746 else
2748 if (!TIFFjpeg_create_compress(sp))
2749 return (0);
2750 #ifndef TIFF_JPEG_MAX_MEMORY_TO_USE
2751 #define TIFF_JPEG_MAX_MEMORY_TO_USE (10 * 1024 * 1024)
2752 #endif
2753 /* libjpeg turbo 1.5.2 honours max_memory_to_use, but has no backing */
2754 /* store implementation, so better not set max_memory_to_use ourselves.
2756 /* See https://github.com/libjpeg-turbo/libjpeg-turbo/issues/162 */
2757 if (sp->cinfo.c.mem->max_memory_to_use > 0)
2759 /* This is to address bug related in ticket GDAL #1795. */
2760 if (getenv("JPEGMEM") == NULL)
2762 /* Increase the max memory usable. This helps when creating
2763 * files */
2764 /* with "big" tile, without using libjpeg temporary files. */
2765 /* For example a 512x512 tile with 3 bands */
2766 /* requires 1.5 MB which is above libjpeg 1MB default */
2767 if (sp->cinfo.c.mem->max_memory_to_use <
2768 TIFF_JPEG_MAX_MEMORY_TO_USE)
2769 sp->cinfo.c.mem->max_memory_to_use =
2770 TIFF_JPEG_MAX_MEMORY_TO_USE;
2775 sp->cinfo_initialized = TRUE;
2777 return 1;
2780 /* Common to tif_jpeg.c and tif_jpeg_12.c */
2781 static void TIFFInitJPEGCommon(TIFF *tif)
2783 JPEGState *sp;
2785 sp = JState(tif);
2786 sp->tif = tif; /* back link */
2788 /* Default values for codec-specific fields */
2789 sp->otherSettings.jpegtables = NULL;
2790 sp->otherSettings.jpegtables_length = 0;
2791 sp->otherSettings.jpegquality = 75; /* Default IJG quality */
2792 sp->otherSettings.jpegcolormode = JPEGCOLORMODE_RAW;
2793 sp->otherSettings.jpegtablesmode =
2794 JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
2795 sp->otherSettings.ycbcrsampling_fetched = 0;
2797 tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
2798 tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
2799 tif->tif_tagmethods.printdir = JPEGPrintDir; /* hook for codec tags */
2802 * Install codec methods.
2804 tif->tif_fixuptags = JPEGFixupTags;
2805 tif->tif_setupdecode = JPEGSetupDecode;
2806 tif->tif_predecode = JPEGPreDecode;
2807 tif->tif_decoderow = JPEGDecode;
2808 tif->tif_decodestrip = JPEGDecode;
2809 tif->tif_decodetile = JPEGDecode;
2810 tif->tif_setupencode = JPEGSetupEncode;
2811 tif->tif_preencode = JPEGPreEncode;
2812 tif->tif_postencode = JPEGPostEncode;
2813 tif->tif_encoderow = JPEGEncode;
2814 tif->tif_encodestrip = JPEGEncode;
2815 tif->tif_encodetile = JPEGEncode;
2816 tif->tif_cleanup = JPEGCleanup;
2818 tif->tif_defstripsize = JPEGDefaultStripSize;
2819 tif->tif_deftilesize = JPEGDefaultTileSize;
2820 tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
2821 sp->cinfo_initialized = FALSE;
2824 int TIFFInitJPEG(TIFF *tif, int scheme)
2826 JPEGState *sp;
2828 (void)scheme;
2829 assert(scheme == COMPRESSION_JPEG);
2832 * Merge codec-specific tag information.
2834 if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields)))
2836 TIFFErrorExtR(tif, "TIFFInitJPEG",
2837 "Merging JPEG codec-specific tags failed");
2838 return 0;
2842 * Allocate state block so tag methods have storage to record values.
2844 tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(JPEGState));
2846 if (tif->tif_data == NULL)
2848 TIFFErrorExtR(tif, "TIFFInitJPEG", "No space for JPEG state block");
2849 return 0;
2851 _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
2853 sp = JState(tif);
2855 * Override parent get/set field methods.
2857 sp->otherSettings.vgetparent = tif->tif_tagmethods.vgetfield;
2858 sp->otherSettings.vsetparent = tif->tif_tagmethods.vsetfield;
2859 sp->otherSettings.printdir = tif->tif_tagmethods.printdir;
2861 sp->otherSettings.defsparent = tif->tif_defstripsize;
2862 sp->otherSettings.deftparent = tif->tif_deftilesize;
2864 TIFFInitJPEGCommon(tif);
2867 ** Create a JPEGTables field if no directory has yet been created.
2868 ** We do this just to ensure that sufficient space is reserved for
2869 ** the JPEGTables field. It will be properly created the right
2870 ** size later.
2872 if (tif->tif_diroff == 0)
2874 #define SIZE_OF_JPEGTABLES 2000
2876 The following line assumes incorrectly that all JPEG-in-TIFF files will
2877 have a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags
2878 to be written when the JPEG data is placed with TIFFWriteRawStrip. The
2879 field bit should be set, anyway, later when actual JPEGTABLES header is
2880 generated, so removing it here hopefully is harmless.
2881 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2883 sp->otherSettings.jpegtables_length = SIZE_OF_JPEGTABLES;
2884 sp->otherSettings.jpegtables =
2885 (void *)_TIFFmallocExt(tif, sp->otherSettings.jpegtables_length);
2886 if (sp->otherSettings.jpegtables)
2888 _TIFFmemset(sp->otherSettings.jpegtables, 0, SIZE_OF_JPEGTABLES);
2890 else
2892 TIFFErrorExtR(tif, "TIFFInitJPEG",
2893 "Failed to allocate memory for JPEG tables");
2894 return 0;
2896 #undef SIZE_OF_JPEGTABLES
2898 return 1;
2900 #endif /* JPEG_SUPPORT */