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