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