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