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