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