1/* $Header$ */
2
3/*
4 * Copyright (c) 1994-1996 Sam Leffler
5 * Copyright (c) 1994-1996 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#include "tkimg.h"
28#include "tiffInt.h"
29#include "jpegtcl.h"
30#include <assert.h>
31#include <setjmp.h>
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
46/*
47 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
48 * in place of plain setjmp.  These macros will make it easier.
49 */
50#define SETJMP(jbuf)		setjmp(jbuf)
51#define LONGJMP(jbuf,code)	longjmp(jbuf,code)
52#define JMP_BUF			jmp_buf
53
54typedef struct jpeg_destination_mgr jpeg_destination_mgr;
55typedef struct jpeg_source_mgr jpeg_source_mgr;
56typedef	struct jpeg_error_mgr jpeg_error_mgr;
57
58/*
59 * State block for each open TIFF file using
60 * libjpeg to do JPEG compression/decompression.
61 *
62 * libjpeg's visible state is either a jpeg_compress_struct
63 * or jpeg_decompress_struct depending on which way we
64 * are going.  comm can be used to refer to the fields
65 * which are common to both.
66 *
67 * NB: cinfo is required to be the first member of JPEGState,
68 *     so we can safely cast JPEGState* -> jpeg_xxx_struct*
69 *     and vice versa!
70 */
71typedef	struct {
72  union {
73    struct jpeg_compress_struct c;
74    struct jpeg_decompress_struct d;
75    struct jpeg_common_struct comm;
76  } cinfo;			/* NB: must be first */
77  jpeg_error_mgr	err;		/* libjpeg error manager */
78  JMP_BUF		exit_jmpbuf;	/* for catching libjpeg failures */
79  /*
80   * The following two members could be a union, but
81   * they're small enough that it's not worth the effort.
82   */
83  jpeg_destination_mgr dest;	/* data dest for compression */
84  jpeg_source_mgr	src;		/* data source for decompression */
85					/* private state */
86  TIFF*		tif;		/* back link needed by some code */
87  uint16		photometric;	/* copy of PhotometricInterpretation */
88  uint16		h_sampling;	/* luminance sampling factors */
89  uint16		v_sampling;
90  tsize_t		bytesperline;	/* decompressed bytes per scanline */
91  /* pointers to intermediate buffers when processing downsampled data */
92  JSAMPARRAY	ds_buffer[MAX_COMPONENTS];
93  int		scancount;	/* number of "scanlines" accumulated */
94  int		samplesperclump;
95
96  TIFFVGetMethod	vgetparent;	/* super-class method */
97  TIFFVSetMethod	vsetparent;	/* super-class method */
98  TIFFStripMethod	defsparent;	/* super-class method */
99  TIFFTileMethod	deftparent;	/* super-class method */
100					/* pseudo-tag fields */
101  void*		jpegtables;	/* JPEGTables tag value, or NULL */
102  uint32	jpegtables_length; /* number of bytes in same */
103  int		jpegquality;	/* Compression quality level */
104  int		jpegcolormode;	/* Auto RGB<=>YCbCr convert? */
105  int		jpegtablesmode;	/* What to put in JPEGTables */
106} JPEGState;
107
108#define	JState(tif)	((JPEGState*)(tif)->tif_data)
109
110static int JPEGDecode(TIFF*, tidata_t, tsize_t, tsample_t);
111static int JPEGDecodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
112static int JPEGEncode(TIFF*, tidata_t, tsize_t, tsample_t);
113static int JPEGEncodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
114
115#define	FIELD_JPEGTABLES	(FIELD_CODEC+0)
116
117static const TIFFFieldInfo jpegFieldInfo[] = {
118    { TIFFTAG_JPEGTABLES,	 -1,-1,	TIFF_UNDEFINED,	FIELD_JPEGTABLES,
119      FALSE,	TRUE,	"JPEGTables" },
120    { TIFFTAG_JPEGQUALITY,	 0, 0,	TIFF_ANY,	FIELD_PSEUDO,
121      TRUE,	FALSE,	"" },
122    { TIFFTAG_JPEGCOLORMODE,	 0, 0,	TIFF_ANY,	FIELD_PSEUDO,
123      FALSE,	FALSE,	"" },
124    { TIFFTAG_JPEGTABLESMODE,	 0, 0,	TIFF_ANY,	FIELD_PSEUDO,
125      FALSE,	FALSE,	"" },
126};
127#define	N(a)	(sizeof (a) / sizeof (a[0]))
128
129/*
130 * libjpeg interface layer.
131 *
132 * We use setjmp/longjmp to return control to libtiff
133 * when a fatal error is encountered within the JPEG
134 * library.  We also direct libjpeg error and warning
135 * messages through the appropriate libtiff handlers.
136 */
137
138/*
139 * Error handling routines (these replace corresponding
140 * IJG routines from jerror.c).  These are used for both
141 * compression and decompression.
142 */
143
144static void TIFFjpeg_error_exit(j_common_ptr);
145static void TIFFjpeg_output_message(j_common_ptr);
146static int TIFFjpeg_create_compress(JPEGState*);
147static int TIFFjpeg_create_decompress(JPEGState*);
148static int TIFFjpeg_set_defaults(JPEGState*);
149static int TIFFjpeg_set_colorspace(JPEGState*, J_COLOR_SPACE);
150static int TIFFjpeg_set_quality(JPEGState*, int, boolean);
151static int TIFFjpeg_suppress_tables(JPEGState*, boolean);
152static int TIFFjpeg_start_compress(JPEGState*, boolean);
153static int TIFFjpeg_write_scanlines(JPEGState*, JSAMPARRAY, int);
154static int TIFFjpeg_write_raw_data(JPEGState*, JSAMPIMAGE, int);
155static int TIFFjpeg_finish_compress(JPEGState* sp);
156static int TIFFjpeg_write_tables(JPEGState*);
157static int TIFFjpeg_read_header(JPEGState*, boolean);
158static int TIFFjpeg_start_decompress(JPEGState*);
159static int TIFFjpeg_read_scanlines(JPEGState*, JSAMPARRAY, int);
160static int  TIFFjpeg_read_raw_data(JPEGState*, JSAMPIMAGE, int);
161static int TIFFjpeg_finish_decompress(JPEGState*);
162static int TIFFjpeg_abort(JPEGState*);
163static int TIFFjpeg_destroy(JPEGState*);
164static JSAMPARRAY TIFFjpeg_alloc_sarray(JPEGState*,
165	int, JDIMENSION, JDIMENSION);
166static void TIFFjpeg_data_dest(JPEGState*, TIFF*);
167static int TIFFjpeg_tables_dest(JPEGState*, TIFF*);
168static void TIFFjpeg_data_src(JPEGState*, TIFF*);
169static void TIFFjpeg_tables_src(JPEGState*, TIFF*);
170
171static void std_init_destination(j_compress_ptr);
172static boolean std_empty_output_buffer(j_compress_ptr);
173static void std_term_destination(j_compress_ptr);
174static void tables_init_destination(j_compress_ptr);
175static boolean tables_empty_output_buffer(j_compress_ptr);
176static void tables_term_destination(j_compress_ptr);
177static void std_init_source(j_decompress_ptr);
178static boolean std_fill_input_buffer(j_decompress_ptr);
179static void std_skip_input_data(j_decompress_ptr, long);
180static void std_term_source(j_decompress_ptr);
181static void tables_init_source(j_decompress_ptr);
182static int alloc_downsampled_buffers(TIFF*,
183	jpeg_component_info*, int);
184
185static int JPEGSetupDecode(TIFF* tif);
186static int JPEGSetupEncode(TIFF* tif);
187static int JPEGEncode(TIFF*, tidata_t, tsize_t, tsample_t);
188static int JPEGEncodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
189static int JPEGPostEncode(TIFF* tif);
190static void JPEGCleanup(TIFF*);
191static int JPEGVSetField(TIFF* tif, ttag_t tag, va_list ap);
192static int JPEGVGetField(TIFF* tif, ttag_t tag, va_list ap);
193static uint32 JPEGDefaultStripSize(TIFF*, uint32);
194static void JPEGDefaultTileSize(TIFF*, uint32*, uint32*);
195
196
197static void
198TIFFjpeg_error_exit(cinfo)
199    j_common_ptr cinfo;
200{
201    JPEGState *sp = (JPEGState *) cinfo;	/* NB: cinfo assumed first */
202    char buffer[JMSG_LENGTH_MAX];
203
204    (*cinfo->err->format_message) (cinfo, buffer);
205    TIFFError("JPEGLib", buffer);		/* display the error message */
206    jpeg_abort(cinfo);			/* clean up libjpeg state */
207    LONGJMP(sp->exit_jmpbuf, 1);		/* return to libtiff caller */
208}
209
210/*
211 * This routine is invoked only for warning messages,
212 * since error_exit does its own thing and trace_level
213 * is never set > 0.
214 */
215
216static void
217TIFFjpeg_output_message(cinfo)
218    j_common_ptr cinfo;
219{
220}
221
222/*
223 * Interface routines.  This layer of routines exists
224 * primarily to limit side-effects from using setjmp.
225 * Also, normal/error returns are converted into return
226 * values per libtiff practice.
227 */
228#define	CALLJPEG(sp, fail, op)	(SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
229
230#define	CALLVJPEG(sp, op)	CALLJPEG(sp, 0, ((op),1))
231#undef  CALLVJPEG
232#define CALLVJPEG(sp, op)       (SETJMP((sp)->exit_jmpbuf) ? (0) : ((op),1))
233
234static int
235TIFFjpeg_create_compress(sp)
236    JPEGState* sp;
237{
238    /* initialize JPEG error handling */
239    sp->cinfo.c.err = jpeg_std_error(&sp->err);
240    sp->err.error_exit = TIFFjpeg_error_exit;
241    sp->err.output_message = TIFFjpeg_output_message;
242
243    return CALLVJPEG(sp, jpeg_CreateCompress(&sp->cinfo.c, JPEG_LIB_VERSION,
244			(size_t) sizeof(struct jpeg_compress_struct)));
245}
246
247
248static int
249TIFFjpeg_create_decompress(sp)
250    JPEGState* sp;
251{
252	/* initialize JPEG error handling */
253	sp->cinfo.d.err = jpeg_std_error(&sp->err);
254	sp->err.error_exit = TIFFjpeg_error_exit;
255	sp->err.output_message = TIFFjpeg_output_message;
256
257	return CALLVJPEG(sp, jpeg_CreateDecompress(&sp->cinfo.d, JPEG_LIB_VERSION,
258		(size_t) sizeof(struct jpeg_decompress_struct)));
259}
260
261
262static int
263TIFFjpeg_set_defaults(sp)
264    JPEGState* sp;
265{
266    return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
267}
268
269
270static int
271TIFFjpeg_set_colorspace(sp, colorspace)
272    JPEGState* sp;
273    J_COLOR_SPACE colorspace;
274{
275    return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
276}
277
278
279static int
280TIFFjpeg_set_quality(sp, quality, force_baseline)
281    JPEGState* sp;
282    int quality;
283    boolean force_baseline;
284{
285    return CALLVJPEG(sp,
286     jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
287}
288
289
290static int
291TIFFjpeg_suppress_tables(sp, suppress)
292    JPEGState* sp;
293    boolean suppress;
294{
295    return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
296}
297
298static int
299TIFFjpeg_start_compress(sp, write_all_tables)
300    JPEGState* sp;
301    boolean write_all_tables;
302{
303    return CALLVJPEG(sp,
304     jpeg_start_compress(&sp->cinfo.c, write_all_tables));
305}
306
307static int
308TIFFjpeg_write_scanlines(sp, scanlines, num_lines)
309    JPEGState* sp;
310    JSAMPARRAY scanlines;
311    int num_lines;
312{
313    return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
314	  scanlines, (JDIMENSION) num_lines));
315}
316
317
318static int
319TIFFjpeg_write_raw_data(sp, data, num_lines)
320    JPEGState* sp;
321    JSAMPIMAGE data;
322    int num_lines;
323{
324	return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
325	    data, (JDIMENSION) num_lines));
326}
327
328
329static int
330TIFFjpeg_finish_compress(sp)
331    JPEGState* sp;
332{
333    return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
334}
335
336
337static int
338TIFFjpeg_write_tables(sp)
339    JPEGState* sp;
340{
341    return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
342}
343
344
345static int
346TIFFjpeg_read_header(sp, require_image)
347    JPEGState* sp;
348    boolean require_image;
349{
350    return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
351}
352
353static int
354TIFFjpeg_start_decompress(sp)
355    JPEGState* sp;
356{
357    return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
358}
359
360
361static int
362TIFFjpeg_read_scanlines(sp, scanlines, max_lines)
363    JPEGState* sp;
364    JSAMPARRAY scanlines;
365    int max_lines;
366{
367    return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
368	    scanlines, (JDIMENSION) max_lines));
369}
370
371static int
372TIFFjpeg_read_raw_data(sp, data, max_lines)
373    JPEGState* sp;
374    JSAMPIMAGE data;
375    int max_lines;
376{
377    return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
378	    data, (JDIMENSION) max_lines));
379}
380
381static int
382TIFFjpeg_finish_decompress(sp)
383    JPEGState* sp;
384{
385    return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
386}
387
388static int
389TIFFjpeg_abort(sp)
390    JPEGState* sp;
391{
392    return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
393}
394
395static int
396TIFFjpeg_destroy(sp)
397    JPEGState* sp;
398{
399    return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
400}
401
402static JSAMPARRAY
403TIFFjpeg_alloc_sarray(sp, pool_id, samplesperrow, numrows)
404    JPEGState* sp;
405    int pool_id;
406    JDIMENSION samplesperrow;
407    JDIMENSION numrows;
408{
409	return CALLJPEG(sp, (JSAMPARRAY) NULL,
410	    (*sp->cinfo.comm.mem->alloc_sarray)
411		(&sp->cinfo.comm, pool_id, samplesperrow, numrows));
412}
413
414/*
415 * JPEG library destination data manager.
416 * These routines direct compressed data from libjpeg into the
417 * libtiff output buffer.
418 */
419
420static void
421std_init_destination(cinfo)
422    j_compress_ptr cinfo;
423{
424    JPEGState* sp = (JPEGState*) cinfo;
425    TIFF* tif = sp->tif;
426
427    sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
428    sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
429}
430
431static boolean
432std_empty_output_buffer(cinfo)
433    j_compress_ptr cinfo;
434{
435    JPEGState* sp = (JPEGState*) cinfo;
436    TIFF* tif = sp->tif;
437
438    /* the entire buffer has been filled */
439    tif->tif_rawcc = tif->tif_rawdatasize;
440    TIFFFlushData1(tif);
441    sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
442    sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
443
444    return (TRUE);
445}
446
447static void
448std_term_destination(cinfo)
449    j_compress_ptr cinfo;
450{
451    JPEGState* sp = (JPEGState*) cinfo;
452    TIFF* tif = sp->tif;
453
454    tif->tif_rawcp = (tidata_t) sp->dest.next_output_byte;
455    tif->tif_rawcc =
456      tif->tif_rawdatasize - (tsize_t) sp->dest.free_in_buffer;
457    /* NB: libtiff does the final buffer flush */
458}
459
460static void
461TIFFjpeg_data_dest(sp, tif)
462    JPEGState* sp;
463    TIFF* tif;
464{
465    (void) tif;
466    sp->cinfo.c.dest = &sp->dest;
467    sp->dest.init_destination = std_init_destination;
468    sp->dest.empty_output_buffer = std_empty_output_buffer;
469    sp->dest.term_destination = std_term_destination;
470}
471
472/*
473 * Alternate destination manager for outputting to JPEGTables field.
474 */
475
476static void
477tables_init_destination(cinfo)
478    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
487static boolean
488tables_empty_output_buffer(cinfo)
489    j_compress_ptr cinfo;
490{
491    JPEGState* sp = (JPEGState*) cinfo;
492    void* newbuf;
493
494    /* the entire buffer has been filled; enlarge it by 1000 bytes */
495    newbuf = TkimgTIFFrealloc((tdata_t) sp->jpegtables,
496			      (tsize_t) (sp->jpegtables_length + 1000));
497    if (newbuf == NULL)
498      ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
499    sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
500    sp->dest.free_in_buffer = (size_t) 1000;
501    sp->jpegtables = newbuf;
502    sp->jpegtables_length += 1000;
503    return (TRUE);
504}
505
506static void
507tables_term_destination(cinfo)
508    j_compress_ptr cinfo;
509{
510    JPEGState* sp = (JPEGState*) cinfo;
511
512    /* set tables length to number of bytes actually emitted */
513    sp->jpegtables_length -= sp->dest.free_in_buffer;
514}
515
516static int
517TIFFjpeg_tables_dest(sp, tif)
518    JPEGState* sp;
519    TIFF* tif;
520{
521    (void) tif;
522    /*
523     * Allocate a working buffer for building tables.
524     * Initial size is 1000 bytes, which is usually adequate.
525     */
526    if (sp->jpegtables) {
527        TkimgTIFFfree(sp->jpegtables);
528    }
529    sp->jpegtables_length = 1000;
530    sp->jpegtables = (void*) TkimgTIFFmalloc((tsize_t) sp->jpegtables_length);
531    if (sp->jpegtables == NULL) {
532        sp->jpegtables_length = 0;
533	TIFFError("TIFFjpeg_tables_dest", "No space for JPEGTables");
534      return (0);
535    }
536    sp->cinfo.c.dest = &sp->dest;
537    sp->dest.init_destination = tables_init_destination;
538    sp->dest.empty_output_buffer = tables_empty_output_buffer;
539    sp->dest.term_destination = tables_term_destination;
540    return (1);
541}
542
543/*
544 * JPEG library source data manager.
545 * These routines supply compressed data to libjpeg.
546 */
547
548static void
549std_init_source(cinfo)
550    j_decompress_ptr cinfo;
551{
552    JPEGState* sp = (JPEGState*) cinfo;
553    TIFF* tif = sp->tif;
554
555    sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
556    sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
557}
558
559static boolean
560std_fill_input_buffer(cinfo)
561    j_decompress_ptr cinfo;
562{
563    JPEGState* sp = (JPEGState* ) cinfo;
564    static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
565
566    /*
567     * Should never get here since entire strip/tile is
568     * read into memory before the decompressor is called,
569     * and thus was supplied by init_source.
570     */
571    WARNMS(cinfo, JWRN_JPEG_EOF);
572    /* insert a fake EOI marker */
573    sp->src.next_input_byte = dummy_EOI;
574    sp->src.bytes_in_buffer = 2;
575    return (TRUE);
576}
577
578static void
579std_skip_input_data(cinfo, num_bytes)
580    j_decompress_ptr cinfo;
581    long num_bytes;
582{
583    JPEGState* sp = (JPEGState*) cinfo;
584
585    if (num_bytes > 0) {
586      if (num_bytes > (long) sp->src.bytes_in_buffer) {
587	/* oops, buffer overrun */
588	(void) std_fill_input_buffer(cinfo);
589      } else {
590	sp->src.next_input_byte += (size_t) num_bytes;
591	sp->src.bytes_in_buffer -= (size_t) num_bytes;
592      }
593    }
594}
595
596static void
597std_term_source(cinfo)
598    j_decompress_ptr cinfo;
599{
600    /* No work necessary here */
601    /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
602    /* (if so, need empty tables_term_source!) */
603    (void) cinfo;
604}
605
606static void
607TIFFjpeg_data_src(sp, tif)
608    JPEGState* sp;
609    TIFF* tif;
610{
611    (void) tif;
612    sp->cinfo.d.src = &sp->src;
613    sp->src.init_source = std_init_source;
614    sp->src.fill_input_buffer = std_fill_input_buffer;
615    sp->src.skip_input_data = std_skip_input_data;
616    sp->src.resync_to_restart = jpeg_resync_to_restart;
617    sp->src.term_source = std_term_source;
618    sp->src.bytes_in_buffer = 0;		/* for safety */
619    sp->src.next_input_byte = NULL;
620}
621
622/*
623 * Alternate source manager for reading from JPEGTables.
624 * We can share all the code except for the init routine.
625 */
626
627static void
628tables_init_source(cinfo)
629    j_decompress_ptr cinfo;
630{
631    JPEGState* sp = (JPEGState*) cinfo;
632
633    sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
634    sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
635}
636
637static void
638TIFFjpeg_tables_src(sp, tif)
639    JPEGState* sp;
640    TIFF* tif;
641{
642    TIFFjpeg_data_src(sp, tif);
643    sp->src.init_source = tables_init_source;
644}
645
646/*
647 * Allocate downsampled-data buffers needed for downsampled I/O.
648 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
649 * We use libjpeg's allocator so that buffers will be released automatically
650 * when done with strip/tile.
651 * This is also a handy place to compute samplesperclump, bytesperline.
652 */
653
654static int
655alloc_downsampled_buffers(tif, comp_info, num_components)
656    TIFF* tif;
657    jpeg_component_info* comp_info;
658    int num_components;
659{
660	JPEGState* sp = JState(tif);
661	int ci;
662	jpeg_component_info* compptr;
663	JSAMPARRAY buf;
664	int samples_per_clump = 0;
665
666	for (ci = 0, compptr = comp_info; ci < num_components;
667	     ci++, compptr++) {
668		samples_per_clump += compptr->h_samp_factor *
669			compptr->v_samp_factor;
670		buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
671				compptr->width_in_blocks * DCTSIZE,
672				(JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
673		if (buf == NULL)
674			return (0);
675		sp->ds_buffer[ci] = buf;
676	}
677	sp->samplesperclump = samples_per_clump;
678	/* Cb,Cr both have sampling factors 1 */
679	/* so downsampled width of Cb is # of clumps per line */
680	sp->bytesperline = sizeof(JSAMPLE) * samples_per_clump *
681		comp_info[1].downsampled_width;
682	return (1);
683}
684
685
686/*
687 * JPEG Decoding.
688 */
689
690static int
691JPEGSetupDecode(tif)
692    TIFF* tif;
693{
694	JPEGState* sp = JState(tif);
695	TIFFDirectory *td = &tif->tif_dir;
696
697	assert(sp != NULL);
698	assert(sp->cinfo.comm.is_decompressor);
699
700	/* Read JPEGTables if it is present */
701	if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
702		TIFFjpeg_tables_src(sp, tif);
703		if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
704			TIFFError("JPEGSetupDecode", "Bogus JPEGTables field");
705			return (0);
706		}
707	}
708
709	/* Grab parameters that are same for all strips/tiles */
710	sp->photometric = td->td_photometric;
711	switch (sp->photometric) {
712	case PHOTOMETRIC_YCBCR:
713		sp->h_sampling = td->td_ycbcrsubsampling[0];
714		sp->v_sampling = td->td_ycbcrsubsampling[1];
715		break;
716	default:
717		/* TIFF 6.0 forbids subsampling of all other color spaces */
718		sp->h_sampling = 1;
719		sp->v_sampling = 1;
720		break;
721	}
722
723	/* Set up for reading normal data */
724	TIFFjpeg_data_src(sp, tif);
725	tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
726	return (1);
727}
728
729/*
730 * Set up for decoding a strip or tile.
731 */
732
733static int
734JPEGPreDecode (
735    TIFF* tif,
736    tsample_t s)
737{
738	JPEGState *sp = JState(tif);
739	TIFFDirectory *td = &tif->tif_dir;
740	static char module[] = "JPEGPreDecode";
741	uint32 segment_width, segment_height;
742	int downsampled_output;
743	int ci;
744
745	assert(sp != NULL);
746	assert(sp->cinfo.comm.is_decompressor);
747	/*
748	 * Reset decoder state from any previous strip/tile,
749	 * in case application didn't read the whole strip.
750	 */
751	if (!TIFFjpeg_abort(sp))
752		return (0);
753	/*
754	 * Read the header for this strip/tile.
755	 */
756	if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
757		return (0);
758	/*
759	 * Check image parameters and set decompression parameters.
760	 */
761	if (isTiled(tif)) {
762		segment_width = td->td_tilewidth;
763		segment_height = td->td_tilelength;
764		sp->bytesperline = TIFFTileRowSize(tif);
765	} else {
766		segment_width = td->td_imagewidth;
767		segment_height = td->td_imagelength - tif->tif_row;
768		if (segment_height > td->td_rowsperstrip)
769			segment_height = td->td_rowsperstrip;
770		sp->bytesperline = TIFFScanlineSize(tif);
771	}
772	if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
773		/*
774		 * For PC 2, scale down the expected strip/tile size
775		 * to match a downsampled component
776		 */
777		segment_width = TIFFhowmany(segment_width, sp->h_sampling);
778		segment_height = TIFFhowmany(segment_height, sp->v_sampling);
779	}
780	if (sp->cinfo.d.image_width != segment_width ||
781	    sp->cinfo.d.image_height != segment_height) {
782		TIFFError(module, "Improper JPEG strip/tile size");
783		return (0);
784	}
785	if (sp->cinfo.d.num_components !=
786	    (td->td_planarconfig == PLANARCONFIG_CONTIG ?
787	     td->td_samplesperpixel : 1)) {
788		TIFFError(module, "Improper JPEG component count");
789		return (0);
790	}
791	if (sp->cinfo.d.data_precision != td->td_bitspersample) {
792		TIFFError(module, "Improper JPEG data precision");
793		return (0);
794	}
795	if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
796		/* Component 0 should have expected sampling factors */
797		if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
798		    sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
799			TIFFError(module, "Improper JPEG sampling factors");
800			return (0);
801		}
802		/* Rest should have sampling factors 1,1 */
803		for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
804			if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
805			    sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
806				TIFFError(module, "Improper JPEG sampling factors");
807				return (0);
808			}
809		}
810	} else {
811		/* PC 2's single component should have sampling factors 1,1 */
812		if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
813		    sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
814			TIFFError(module, "Improper JPEG sampling factors");
815			return (0);
816		}
817	}
818	downsampled_output = FALSE;
819	if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
820	    sp->photometric == PHOTOMETRIC_YCBCR &&
821	    sp->jpegcolormode == JPEGCOLORMODE_RGB) {
822		/* Convert YCbCr to RGB */
823		sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
824		sp->cinfo.d.out_color_space = JCS_RGB;
825	} else {
826		/* Suppress colorspace handling */
827		sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
828		sp->cinfo.d.out_color_space = JCS_UNKNOWN;
829		if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
830		    (sp->h_sampling != 1 || sp->v_sampling != 1))
831			downsampled_output = TRUE;
832		/* XXX what about up-sampling? */
833	}
834	if (downsampled_output) {
835		/* Need to use raw-data interface to libjpeg */
836		sp->cinfo.d.raw_data_out = TRUE;
837		tif->tif_decoderow = JPEGDecodeRaw;
838		tif->tif_decodestrip = JPEGDecodeRaw;
839		tif->tif_decodetile = JPEGDecodeRaw;
840	} else {
841		/* Use normal interface to libjpeg */
842		sp->cinfo.d.raw_data_out = FALSE;
843		tif->tif_decoderow = JPEGDecode;
844		tif->tif_decodestrip = JPEGDecode;
845		tif->tif_decodetile = JPEGDecode;
846	}
847	/* Start JPEG decompressor */
848	if (!TIFFjpeg_start_decompress(sp))
849		return (0);
850	/* Allocate downsampled-data buffers if needed */
851	if (downsampled_output) {
852		if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
853					       sp->cinfo.d.num_components))
854			return (0);
855		sp->scancount = DCTSIZE;	/* mark buffer empty */
856	}
857	return (1);
858}
859
860/*
861 * Decode a chunk of pixels.
862 * "Standard" case: returned data is not downsampled.
863 */
864
865static int
866JPEGDecode (
867    TIFF* tif,
868    tidata_t buf,
869    tsize_t cc,
870    tsample_t s)
871{
872	JPEGState *sp = JState(tif);
873	tsize_t nrows;
874	JSAMPROW bufptr[1];
875
876	(void) s;
877	assert(sp != NULL);
878	/* data is expected to be read in multiples of a scanline */
879	nrows = cc / sp->bytesperline;
880
881	while (nrows-- > 0) {
882		bufptr[0] = (JSAMPROW) buf;
883		if (TIFFjpeg_read_scanlines(sp, bufptr, 1) != 1)
884			return (0);
885		if (nrows > 0)
886			tif->tif_row++;
887		buf += sp->bytesperline;
888	}
889	/* Close down the decompressor if we've finished the strip or tile. */
890	if (sp->cinfo.d.output_scanline == sp->cinfo.d.output_height) {
891		if (TIFFjpeg_finish_decompress(sp) != TRUE)
892			return (0);
893	}
894	return (1);
895}
896
897/*
898 * Decode a chunk of pixels.
899 * Returned data is downsampled per sampling factors.
900 */
901
902static int
903JPEGDecodeRaw (
904    TIFF* tif,
905    tidata_t buf,
906    tsize_t cc,
907    tsample_t s)
908{
909	JPEGState *sp = JState(tif);
910	JSAMPLE* inptr;
911	JSAMPLE* outptr;
912	tsize_t nrows;
913	JDIMENSION clumps_per_line, nclump;
914	int clumpoffset, ci, xpos, ypos;
915	jpeg_component_info* compptr;
916	int samples_per_clump = sp->samplesperclump;
917
918	(void) s;
919	assert(sp != NULL);
920	/* data is expected to be read in multiples of a scanline */
921	nrows = cc / sp->bytesperline;
922
923	/* Cb,Cr both have sampling factors 1, so this is correct */
924	clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
925
926	while (nrows-- > 0) {
927		/* Reload downsampled-data buffer if needed */
928		if (sp->scancount >= DCTSIZE) {
929			int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
930			if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
931				return (0);
932			sp->scancount = 0;
933			/* Close down the decompressor if done. */
934			if (sp->cinfo.d.output_scanline >=
935			    sp->cinfo.d.output_height) {
936				if (TIFFjpeg_finish_decompress(sp) != TRUE)
937					return (0);
938			}
939		}
940		/*
941		 * Fastest way to unseparate the data is to make one pass
942		 * over the scanline for each row of each component.
943		 */
944		clumpoffset = 0;		/* first sample in clump */
945		for (ci = 0, compptr = sp->cinfo.d.comp_info;
946		     ci < sp->cinfo.d.num_components;
947		     ci++, compptr++) {
948		    int hsamp = compptr->h_samp_factor;
949		    int vsamp = compptr->v_samp_factor;
950		    for (ypos = 0; ypos < vsamp; ypos++) {
951			inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
952			outptr = ((JSAMPLE*) buf) + clumpoffset;
953			if (hsamp == 1) {
954			    /* fast path for at least Cb and Cr */
955			    for (nclump = clumps_per_line; nclump-- > 0; ) {
956				outptr[0] = *inptr++;
957				outptr += samples_per_clump;
958			    }
959			} else {
960			    /* general case */
961			    for (nclump = clumps_per_line; nclump-- > 0; ) {
962				for (xpos = 0; xpos < hsamp; xpos++)
963				    outptr[xpos] = *inptr++;
964				outptr += samples_per_clump;
965			    }
966			}
967			clumpoffset += hsamp;
968		    }
969		}
970		sp->scancount++;
971		if (nrows > 0)
972			tif->tif_row++;
973		buf += sp->bytesperline;
974	}
975	return (1);
976}
977
978
979/*
980 * JPEG Encoding.
981 */
982
983static void unsuppress_quant_table(JPEGState*, int);
984static void
985unsuppress_quant_table(sp, tblno)
986    JPEGState* sp;
987    int tblno;
988{
989	JQUANT_TBL* qtbl;
990
991	if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
992		qtbl->sent_table = FALSE;
993}
994
995static void unsuppress_huff_table(JPEGState*, int);
996static void
997unsuppress_huff_table(sp, tblno)
998    JPEGState* sp;
999    int tblno;
1000{
1001	JHUFF_TBL* htbl;
1002
1003	if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1004		htbl->sent_table = FALSE;
1005	if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1006		htbl->sent_table = FALSE;
1007}
1008
1009static int prepare_JPEGTables(TIFF*);
1010static int
1011prepare_JPEGTables(tif)
1012    TIFF* tif;
1013{
1014	JPEGState* sp = JState(tif);
1015
1016	/* Initialize quant tables for current quality setting */
1017	if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1018		return (0);
1019	/* Mark only the tables we want for output */
1020	/* NB: chrominance tables are currently used only with YCbCr */
1021	if (!TIFFjpeg_suppress_tables(sp, TRUE))
1022		return (0);
1023	if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
1024		unsuppress_quant_table(sp, 0);
1025		if (sp->photometric == PHOTOMETRIC_YCBCR)
1026			unsuppress_quant_table(sp, 1);
1027	}
1028	if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
1029		unsuppress_huff_table(sp, 0);
1030		if (sp->photometric == PHOTOMETRIC_YCBCR)
1031			unsuppress_huff_table(sp, 1);
1032	}
1033	/* Direct libjpeg output into jpegtables */
1034	if (!TIFFjpeg_tables_dest(sp, tif))
1035		return (0);
1036	/* Emit tables-only datastream */
1037	if (!TIFFjpeg_write_tables(sp))
1038		return (0);
1039
1040	return (1);
1041}
1042
1043static int
1044JPEGSetupEncode(tif)
1045    TIFF* tif;
1046{
1047	JPEGState* sp = JState(tif);
1048	TIFFDirectory *td = &tif->tif_dir;
1049	static char module[] = "JPEGSetupEncode";
1050
1051	assert(sp != NULL);
1052	assert(!sp->cinfo.comm.is_decompressor);
1053
1054	/*
1055	 * Initialize all JPEG parameters to default values.
1056	 * Note that jpeg_set_defaults needs legal values for
1057	 * in_color_space and input_components.
1058	 */
1059	sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1060	sp->cinfo.c.input_components = 1;
1061	if (!TIFFjpeg_set_defaults(sp))
1062		return (0);
1063	/* Set per-file parameters */
1064	sp->photometric = td->td_photometric;
1065	switch (sp->photometric) {
1066	case PHOTOMETRIC_YCBCR:
1067		sp->h_sampling = td->td_ycbcrsubsampling[0];
1068		sp->v_sampling = td->td_ycbcrsubsampling[1];
1069		/*
1070		 * A ReferenceBlackWhite field *must* be present since the
1071		 * default value is inappropriate for YCbCr.  Fill in the
1072		 * proper value if application didn't set it.
1073		 */
1074		{
1075			float *ref;
1076			if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1077					  &ref)) {
1078				float refbw[6];
1079				long top = 1L << td->td_bitspersample;
1080				refbw[0] = 0;
1081				refbw[1] = (float)(top-1L);
1082				refbw[2] = (float)(top>>1);
1083				refbw[3] = refbw[1];
1084				refbw[4] = refbw[2];
1085				refbw[5] = refbw[1];
1086				TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1087					     refbw);
1088			}
1089		}
1090		break;
1091	case PHOTOMETRIC_PALETTE:		/* disallowed by Tech Note */
1092	case PHOTOMETRIC_MASK:
1093		TIFFError(module,
1094			  "PhotometricInterpretation %d not allowed for JPEG",
1095			  (int) sp->photometric);
1096		return (0);
1097	default:
1098		/* TIFF 6.0 forbids subsampling of all other color spaces */
1099		sp->h_sampling = 1;
1100		sp->v_sampling = 1;
1101		break;
1102	}
1103
1104	/* Verify miscellaneous parameters */
1105
1106	/*
1107	 * This would need work if libtiff ever supports different
1108	 * depths for different components, or if libjpeg ever supports
1109	 * run-time selection of depth.  Neither is imminent.
1110	 */
1111	if (td->td_bitspersample != BITS_IN_JSAMPLE) {
1112		TIFFError(module, "BitsPerSample %d not allowed for JPEG",
1113			  (int) td->td_bitspersample);
1114		return (0);
1115	}
1116	sp->cinfo.c.data_precision = td->td_bitspersample;
1117	if (isTiled(tif)) {
1118		if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
1119			TIFFError(module,
1120				  "JPEG tile height must be multiple of %d",
1121				  sp->v_sampling * DCTSIZE);
1122			return (0);
1123		}
1124		if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
1125			TIFFError(module,
1126				  "JPEG tile width must be multiple of %d",
1127				  sp->h_sampling * DCTSIZE);
1128			return (0);
1129		}
1130	} else {
1131		if (td->td_rowsperstrip < td->td_imagelength &&
1132		    (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
1133			TIFFError(module,
1134				  "RowsPerStrip must be multiple of %d for JPEG",
1135				  sp->v_sampling * DCTSIZE);
1136			return (0);
1137		}
1138	}
1139
1140	/* Create a JPEGTables field if appropriate */
1141	if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
1142		if (!prepare_JPEGTables(tif))
1143			return (0);
1144		/* Mark the field present */
1145		/* Can't use TIFFSetField since BEENWRITING is already set! */
1146		TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1147		tif->tif_flags |= TIFF_DIRTYDIRECT;
1148	} else {
1149		/* We do not support application-supplied JPEGTables, */
1150		/* so mark the field not present */
1151		TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
1152	}
1153
1154	/* Direct libjpeg output to libtiff's output buffer */
1155	TIFFjpeg_data_dest(sp, tif);
1156
1157	return (1);
1158}
1159
1160/*
1161 * Set encoding state at the start of a strip or tile.
1162 */
1163
1164static int
1165JPEGPreEncode (
1166    TIFF* tif,
1167    tsample_t s)
1168{
1169	JPEGState *sp = JState(tif);
1170	TIFFDirectory *td = &tif->tif_dir;
1171	static char module[] = "JPEGPreEncode";
1172	uint32 segment_width, segment_height;
1173	int downsampled_input;
1174
1175	assert(sp != NULL);
1176	assert(!sp->cinfo.comm.is_decompressor);
1177	/*
1178	 * Set encoding parameters for this strip/tile.
1179	 */
1180	if (isTiled(tif)) {
1181		segment_width = td->td_tilewidth;
1182		segment_height = td->td_tilelength;
1183		sp->bytesperline = TIFFTileRowSize(tif);
1184	} else {
1185		segment_width = td->td_imagewidth;
1186		segment_height = td->td_imagelength - tif->tif_row;
1187		if (segment_height > td->td_rowsperstrip)
1188			segment_height = td->td_rowsperstrip;
1189		sp->bytesperline = TIFFScanlineSize(tif);
1190	}
1191	if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1192		/* for PC 2, scale down the strip/tile size
1193		 * to match a downsampled component
1194		 */
1195		segment_width = TIFFhowmany(segment_width, sp->h_sampling);
1196		segment_height = TIFFhowmany(segment_height, sp->v_sampling);
1197	}
1198	if (segment_width > 65535 || segment_height > 65535) {
1199		TIFFError(module, "Strip/tile too large for JPEG");
1200		return (0);
1201	}
1202	sp->cinfo.c.image_width = segment_width;
1203	sp->cinfo.c.image_height = segment_height;
1204	downsampled_input = FALSE;
1205	if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1206		sp->cinfo.c.input_components = td->td_samplesperpixel;
1207		if (sp->photometric == PHOTOMETRIC_YCBCR) {
1208			if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1209				sp->cinfo.c.in_color_space = JCS_RGB;
1210			} else {
1211				sp->cinfo.c.in_color_space = JCS_YCbCr;
1212				if (sp->h_sampling != 1 || sp->v_sampling != 1)
1213					downsampled_input = TRUE;
1214			}
1215			if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
1216				return (0);
1217			/*
1218			 * Set Y sampling factors;
1219			 * we assume jpeg_set_colorspace() set the rest to 1
1220			 */
1221			sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
1222			sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
1223		} else {
1224			sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1225			if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1226				return (0);
1227			/* jpeg_set_colorspace set all sampling factors to 1 */
1228		}
1229	} else {
1230		sp->cinfo.c.input_components = 1;
1231		sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1232		if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1233			return (0);
1234		sp->cinfo.c.comp_info[0].component_id = s;
1235		/* jpeg_set_colorspace() set sampling factors to 1 */
1236		if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
1237			sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
1238			sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
1239			sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
1240		}
1241	}
1242	/* ensure libjpeg won't write any extraneous markers */
1243	sp->cinfo.c.write_JFIF_header = FALSE;
1244	sp->cinfo.c.write_Adobe_marker = FALSE;
1245	/* set up table handling correctly */
1246	if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
1247		if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1248			return (0);
1249		unsuppress_quant_table(sp, 0);
1250		unsuppress_quant_table(sp, 1);
1251	}
1252	if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
1253		sp->cinfo.c.optimize_coding = FALSE;
1254	else
1255		sp->cinfo.c.optimize_coding = TRUE;
1256	if (downsampled_input) {
1257		/* Need to use raw-data interface to libjpeg */
1258		sp->cinfo.c.raw_data_in = TRUE;
1259		tif->tif_encoderow = JPEGEncodeRaw;
1260		tif->tif_encodestrip = JPEGEncodeRaw;
1261		tif->tif_encodetile = JPEGEncodeRaw;
1262	} else {
1263		/* Use normal interface to libjpeg */
1264		sp->cinfo.c.raw_data_in = FALSE;
1265		tif->tif_encoderow = JPEGEncode;
1266		tif->tif_encodestrip = JPEGEncode;
1267		tif->tif_encodetile = JPEGEncode;
1268	}
1269	/* Start JPEG compressor */
1270	if (!TIFFjpeg_start_compress(sp, FALSE))
1271		return (0);
1272	/* Allocate downsampled-data buffers if needed */
1273	if (downsampled_input) {
1274		if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
1275					       sp->cinfo.c.num_components))
1276			return (0);
1277	}
1278	sp->scancount = 0;
1279
1280	return (1);
1281}
1282
1283/*
1284 * Encode a chunk of pixels.
1285 * "Standard" case: incoming data is not downsampled.
1286 */
1287
1288static int
1289JPEGEncode(tif, buf, cc, s)
1290    TIFF* tif;
1291    tidata_t buf;
1292    tsize_t cc;
1293    tsample_t s;
1294{
1295	JPEGState *sp = JState(tif);
1296	tsize_t nrows;
1297	JSAMPROW bufptr[1];
1298
1299	(void) s;
1300	assert(sp != NULL);
1301	/* data is expected to be supplied in multiples of a scanline */
1302	nrows = cc / sp->bytesperline;
1303
1304	while (nrows-- > 0) {
1305		bufptr[0] = (JSAMPROW) buf;
1306		if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
1307			return (0);
1308		if (nrows > 0)
1309			tif->tif_row++;
1310		buf += sp->bytesperline;
1311	}
1312	return (1);
1313}
1314
1315/*
1316 * Encode a chunk of pixels.
1317 * Incoming data is expected to be downsampled per sampling factors.
1318 */
1319
1320static int
1321JPEGEncodeRaw(tif, buf, cc, s)
1322    TIFF* tif;
1323    tidata_t buf;
1324    tsize_t cc;
1325    tsample_t s;
1326{
1327	JPEGState *sp = JState(tif);
1328	JSAMPLE* inptr;
1329	JSAMPLE* outptr;
1330	tsize_t nrows;
1331	JDIMENSION clumps_per_line, nclump;
1332	int clumpoffset, ci, xpos, ypos;
1333	jpeg_component_info* compptr;
1334	int samples_per_clump = sp->samplesperclump;
1335
1336	(void) s;
1337	assert(sp != NULL);
1338	/* data is expected to be supplied in multiples of a scanline */
1339	nrows = cc / sp->bytesperline;
1340
1341	/* Cb,Cr both have sampling factors 1, so this is correct */
1342	clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
1343
1344	while (nrows-- > 0) {
1345		/*
1346		 * Fastest way to separate the data is to make one pass
1347		 * over the scanline for each row of each component.
1348		 */
1349		clumpoffset = 0;		/* first sample in clump */
1350		for (ci = 0, compptr = sp->cinfo.c.comp_info;
1351		     ci < sp->cinfo.c.num_components;
1352		     ci++, compptr++) {
1353		    int hsamp = compptr->h_samp_factor;
1354		    int vsamp = compptr->v_samp_factor;
1355		    int padding = (int) (compptr->width_in_blocks * DCTSIZE -
1356					 clumps_per_line * hsamp);
1357		    for (ypos = 0; ypos < vsamp; ypos++) {
1358			inptr = ((JSAMPLE*) buf) + clumpoffset;
1359			outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1360			if (hsamp == 1) {
1361			    /* fast path for at least Cb and Cr */
1362			    for (nclump = clumps_per_line; nclump-- > 0; ) {
1363				*outptr++ = inptr[0];
1364				inptr += samples_per_clump;
1365			    }
1366			} else {
1367			    /* general case */
1368			    for (nclump = clumps_per_line; nclump-- > 0; ) {
1369				for (xpos = 0; xpos < hsamp; xpos++)
1370				    *outptr++ = inptr[xpos];
1371				inptr += samples_per_clump;
1372			    }
1373			}
1374			/* pad each scanline as needed */
1375			for (xpos = 0; xpos < padding; xpos++) {
1376			    *outptr = outptr[-1];
1377			    outptr++;
1378			}
1379			clumpoffset += hsamp;
1380		    }
1381		}
1382		sp->scancount++;
1383		if (sp->scancount >= DCTSIZE) {
1384			int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1385			if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1386				return (0);
1387			sp->scancount = 0;
1388		}
1389		if (nrows > 0)
1390			tif->tif_row++;
1391		buf += sp->bytesperline;
1392	}
1393	return (1);
1394}
1395
1396/*
1397 * Finish up at the end of a strip or tile.
1398 */
1399
1400static int
1401JPEGPostEncode(tif)
1402    TIFF* tif;
1403{
1404	JPEGState *sp = JState(tif);
1405
1406	if (sp->scancount > 0) {
1407		/*
1408		 * Need to emit a partial bufferload of downsampled data.
1409		 * Pad the data vertically.
1410		 */
1411		int ci, ypos, n;
1412		jpeg_component_info* compptr;
1413
1414		for (ci = 0, compptr = sp->cinfo.c.comp_info;
1415		     ci < sp->cinfo.c.num_components;
1416		     ci++, compptr++) {
1417			int vsamp = compptr->v_samp_factor;
1418			tsize_t row_width = compptr->width_in_blocks * DCTSIZE
1419				* sizeof(JSAMPLE);
1420			for (ypos = sp->scancount * vsamp;
1421			     ypos < DCTSIZE * vsamp; ypos++) {
1422				_TIFFmemcpy((tdata_t)sp->ds_buffer[ci][ypos],
1423					    (tdata_t)sp->ds_buffer[ci][ypos-1],
1424					    row_width);
1425
1426			}
1427		}
1428		n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1429		if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1430			return (0);
1431	}
1432
1433	return (TIFFjpeg_finish_compress(JState(tif)));
1434}
1435
1436static void
1437JPEGCleanup(tif)
1438    TIFF* tif;
1439{
1440	if (tif->tif_data) {
1441		JPEGState *sp = JState(tif);
1442		TIFFjpeg_destroy(sp);		/* release libjpeg resources */
1443		if (sp->jpegtables) {		/* tag value */
1444			TkimgTIFFfree(sp->jpegtables);
1445		}
1446		TkimgTIFFfree(tif->tif_data);	/* release local state */
1447		tif->tif_data = NULL;
1448	}
1449}
1450
1451
1452static int
1453JPEGVSetField(tif, tag, ap)
1454    TIFF* tif;
1455    ttag_t tag;
1456    va_list ap;
1457{
1458	JPEGState* sp = JState(tif);
1459	TIFFDirectory* td = &tif->tif_dir;
1460	uint32 v32;
1461
1462	switch (tag) {
1463	case TIFFTAG_JPEGTABLES:
1464		v32 = va_arg(ap, uint32);
1465		if (v32 == 0) {
1466			/* XXX */
1467			return (0);
1468		}
1469		_TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
1470		    (long) v32);
1471		sp->jpegtables_length = v32;
1472		TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1473		break;
1474	case TIFFTAG_JPEGQUALITY:
1475		sp->jpegquality = va_arg(ap, int);
1476		return (1);			/* pseudo tag */
1477	case TIFFTAG_JPEGCOLORMODE:
1478		sp->jpegcolormode = va_arg(ap, int);
1479		/*
1480		 * Mark whether returned data is up-sampled or not
1481		 * so TIFFStripSize and TIFFTileSize return values
1482		 * that reflect the true amount of data.
1483		 */
1484		tif->tif_flags &= ~TIFF_UPSAMPLED;
1485		if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1486		    if (td->td_photometric == PHOTOMETRIC_YCBCR &&
1487		      sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1488			tif->tif_flags |= TIFF_UPSAMPLED;
1489		    } else {
1490			if (td->td_ycbcrsubsampling[0] != 1 ||
1491			    td->td_ycbcrsubsampling[1] != 1)
1492			    ; /* XXX what about up-sampling? */
1493		    }
1494		}
1495		/*
1496		 * Must recalculate cached tile size
1497		 * in case sampling state changed.
1498		 */
1499		tif->tif_tilesize = TIFFTileSize(tif);
1500		return (1);			/* pseudo tag */
1501	case TIFFTAG_JPEGTABLESMODE:
1502		sp->jpegtablesmode = va_arg(ap, int);
1503		return (1);			/* pseudo tag */
1504	default:
1505		return (*sp->vsetparent)(tif, tag, ap);
1506	}
1507	tif->tif_flags |= TIFF_DIRTYDIRECT;
1508	return (1);
1509}
1510
1511
1512static int
1513JPEGVGetField(tif, tag, ap)
1514    TIFF* tif;
1515    ttag_t tag;
1516    va_list ap;
1517{
1518	JPEGState* sp = JState(tif);
1519
1520	switch (tag) {
1521	case TIFFTAG_JPEGTABLES:
1522		*va_arg(ap, uint32*) = (uint32) sp->jpegtables_length;
1523		*va_arg(ap, void**) = sp->jpegtables;
1524		break;
1525	case TIFFTAG_JPEGQUALITY:
1526		*va_arg(ap, int*) = sp->jpegquality;
1527		break;
1528	case TIFFTAG_JPEGCOLORMODE:
1529		*va_arg(ap, int*) = sp->jpegcolormode;
1530		break;
1531	case TIFFTAG_JPEGTABLESMODE:
1532		*va_arg(ap, int*) = sp->jpegtablesmode;
1533		break;
1534	default:
1535		return (*sp->vgetparent)(tif, tag, ap);
1536	}
1537	return (1);
1538}
1539
1540static uint32
1541JPEGDefaultStripSize(tif, s)
1542    TIFF* tif;
1543    uint32 s;
1544{
1545	JPEGState* sp = JState(tif);
1546	TIFFDirectory *td = &tif->tif_dir;
1547
1548	s = (*sp->defsparent)(tif, s);
1549	if (s < td->td_imagelength)
1550		s = TIFFroundup(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
1551	return (s);
1552}
1553
1554static void
1555JPEGDefaultTileSize(tif, tw, th)
1556    TIFF* tif;
1557    uint32* tw;
1558    uint32* th;
1559{
1560	JPEGState* sp = JState(tif);
1561	TIFFDirectory *td = &tif->tif_dir;
1562
1563	(*sp->deftparent)(tif, tw, th);
1564	*tw = TIFFroundup(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
1565	*th = TIFFroundup(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
1566}
1567
1568int
1569TkimgTIFFInitJpeg(handle, scheme)
1570    TIFF* handle;
1571    int scheme;
1572{
1573    TIFF *tif = (TIFF *) handle;
1574    JPEGState* sp;
1575
1576    assert(scheme == COMPRESSION_JPEG);
1577
1578    /*
1579     * We assume here that package jpegtcl is loaded and its stub
1580     * table initialized. This happens in tiff.c, just before the
1581     * codec is registered.
1582     */
1583
1584    /*
1585     * Allocate state block so tag methods have storage to record values.
1586     */
1587    tif->tif_data = (tidata_t) TkimgTIFFmalloc(sizeof (JPEGState));
1588    if (tif->tif_data == NULL) {
1589      TIFFError("TIFFInitJPEG", "No space for JPEG state block");
1590      return (0);
1591    }
1592    sp = JState(tif);
1593    sp->tif = tif;				/* back link */
1594
1595    /*
1596     * Merge codec-specific tag information and
1597     * override parent get/set field methods.
1598     */
1599    _TIFFMergeFieldInfo(tif, jpegFieldInfo, N(jpegFieldInfo));
1600    sp->vgetparent = tif->tif_tagmethods.vgetfield;
1601    tif->tif_tagmethods.vgetfield = JPEGVGetField;	/* hook for codec tags */
1602    sp->vsetparent = tif->tif_tagmethods.vsetfield;
1603    tif->tif_tagmethods.vsetfield = JPEGVSetField;	/* hook for codec tags */
1604
1605    /* Default values for codec-specific fields */
1606    sp->jpegtables = NULL;
1607    sp->jpegtables_length = 0;
1608    sp->jpegquality = 75;			/* Default IJG quality */
1609    sp->jpegcolormode = JPEGCOLORMODE_RAW;
1610    sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
1611
1612    /*
1613     * Install codec methods.
1614     */
1615    tif->tif_setupdecode = JPEGSetupDecode;
1616    tif->tif_predecode = JPEGPreDecode;
1617    tif->tif_decoderow = JPEGDecode;
1618    tif->tif_decodestrip = JPEGDecode;
1619    tif->tif_decodetile = JPEGDecode;
1620    tif->tif_setupencode = JPEGSetupEncode;
1621    tif->tif_preencode = JPEGPreEncode;
1622    tif->tif_postencode = JPEGPostEncode;
1623    tif->tif_encoderow = JPEGEncode;
1624    tif->tif_encodestrip = JPEGEncode;
1625    tif->tif_encodetile = JPEGEncode;
1626    tif->tif_cleanup = JPEGCleanup;
1627    sp->defsparent = tif->tif_defstripsize;
1628    tif->tif_defstripsize = JPEGDefaultStripSize;
1629    sp->deftparent = tif->tif_deftilesize;
1630    tif->tif_deftilesize = JPEGDefaultTileSize;
1631    tif->tif_flags |= TIFF_NOBITREV;	/* no bit reversal, please */
1632
1633    /*
1634     * Initialize libjpeg.
1635     */
1636    if (tif->tif_mode == O_RDONLY) {
1637      if (!TIFFjpeg_create_decompress(sp))
1638	return (0);
1639    } else {
1640      if (!TIFFjpeg_create_compress(sp))
1641	return (0);
1642    }
1643
1644    return (1);
1645}
1646