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