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