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