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