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