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