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