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