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