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