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