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