Home | History | Annotate | Download | only in libtiff
      1 /* $Id: tif_jpeg.c,v 1.119 2015-08-15 20:13:07 bfriesen 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 conficting typedef given the headers which are included.
     62 */
     63 #if defined(__BORLANDC__) || defined(__MINGW32__)
     64 # define XMD_H 1
     65 #endif
     66 
     67 /*
     68    The windows RPCNDR.H file defines boolean, but defines it with the
     69    unsigned char size.  You should compile JPEG library using appropriate
     70    definitions in jconfig.h header, but many users compile library in wrong
     71    way. That causes errors of the following type:
     72 
     73    "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
     74    caller expects 464"
     75 
     76    For such users we wil fix the problem here. See install.doc file from
     77    the JPEG library distribution for details.
     78 */
     79 
     80 /* Define "boolean" as unsigned char, not int, per Windows custom. */
     81 #if defined(__WIN32__) && !defined(__MINGW32__)
     82 # ifndef __RPCNDR_H__            /* don't conflict if rpcndr.h already read */
     83    typedef unsigned char boolean;
     84 # endif
     85 # define HAVE_BOOLEAN            /* prevent jmorecfg.h from redefining it */
     86 #endif
     87 
     88 #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 	if ((tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR)&&
    709 	    (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&&
    710 	    (tif->tif_dir.td_samplesperpixel==3))
    711 		JPEGFixupTagsSubsampling(tif);
    712 #endif
    713 
    714 	return(1);
    715 }
    716 
    717 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
    718 
    719 static void
    720 JPEGFixupTagsSubsampling(TIFF* tif)
    721 {
    722 	/*
    723 	 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
    724 	 * the TIFF tags, but still use non-default (2,2) values within the jpeg
    725 	 * data stream itself.  In order for TIFF applications to work properly
    726 	 * - for instance to get the strip buffer size right - it is imperative
    727 	 * that the subsampling be available before we start reading the image
    728 	 * data normally.  This function will attempt to analyze the first strip in
    729 	 * order to get the sampling values from the jpeg data stream.
    730 	 *
    731 	 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
    732 	 * discovered sampling does not match the default sampling (2,2) or whatever
    733 	 * was actually in the tiff tags.
    734 	 *
    735 	 * See the bug in bugzilla for details:
    736 	 *
    737 	 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
    738 	 *
    739 	 * Frank Warmerdam, July 2002
    740 	 * Joris Van Damme, May 2007
    741 	 */
    742 	static const char module[] = "JPEGFixupTagsSubsampling";
    743 	struct JPEGFixupTagsSubsamplingData m;
    744 
    745         _TIFFFillStriles( tif );
    746 
    747         if( tif->tif_dir.td_stripbytecount == NULL
    748             || tif->tif_dir.td_stripoffset == NULL
    749             || tif->tif_dir.td_stripbytecount[0] == 0 )
    750         {
    751             /* Do not even try to check if the first strip/tile does not
    752                yet exist, as occurs when GDAL has created a new NULL file
    753                for instance. */
    754             return;
    755         }
    756 
    757 	m.tif=tif;
    758 	m.buffersize=2048;
    759 	m.buffer=_TIFFmalloc(m.buffersize);
    760 	if (m.buffer==NULL)
    761 	{
    762 		TIFFWarningExt(tif->tif_clientdata,module,
    763 		    "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
    764 		return;
    765 	}
    766 	m.buffercurrentbyte=NULL;
    767 	m.bufferbytesleft=0;
    768 	m.fileoffset=tif->tif_dir.td_stripoffset[0];
    769 	m.filepositioned=0;
    770 	m.filebytesleft=tif->tif_dir.td_stripbytecount[0];
    771 	if (!JPEGFixupTagsSubsamplingSec(&m))
    772 		TIFFWarningExt(tif->tif_clientdata,module,
    773 		    "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
    774 	_TIFFfree(m.buffer);
    775 }
    776 
    777 static int
    778 JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
    779 {
    780 	static const char module[] = "JPEGFixupTagsSubsamplingSec";
    781 	uint8 m;
    782 	while (1)
    783 	{
    784 		while (1)
    785 		{
    786 			if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
    787 				return(0);
    788 			if (m==255)
    789 				break;
    790 		}
    791 		while (1)
    792 		{
    793 			if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
    794 				return(0);
    795 			if (m!=255)
    796 				break;
    797 		}
    798 		switch (m)
    799 		{
    800 			case JPEG_MARKER_SOI:
    801 				/* this type of marker has no data and should be skipped */
    802 				break;
    803 			case JPEG_MARKER_COM:
    804 			case JPEG_MARKER_APP0:
    805 			case JPEG_MARKER_APP0+1:
    806 			case JPEG_MARKER_APP0+2:
    807 			case JPEG_MARKER_APP0+3:
    808 			case JPEG_MARKER_APP0+4:
    809 			case JPEG_MARKER_APP0+5:
    810 			case JPEG_MARKER_APP0+6:
    811 			case JPEG_MARKER_APP0+7:
    812 			case JPEG_MARKER_APP0+8:
    813 			case JPEG_MARKER_APP0+9:
    814 			case JPEG_MARKER_APP0+10:
    815 			case JPEG_MARKER_APP0+11:
    816 			case JPEG_MARKER_APP0+12:
    817 			case JPEG_MARKER_APP0+13:
    818 			case JPEG_MARKER_APP0+14:
    819 			case JPEG_MARKER_APP0+15:
    820 			case JPEG_MARKER_DQT:
    821 			case JPEG_MARKER_SOS:
    822 			case JPEG_MARKER_DHT:
    823 			case JPEG_MARKER_DRI:
    824 				/* this type of marker has data, but it has no use to us and should be skipped */
    825 				{
    826 					uint16 n;
    827 					if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
    828 						return(0);
    829 					if (n<2)
    830 						return(0);
    831 					n-=2;
    832 					if (n>0)
    833 						JPEGFixupTagsSubsamplingSkip(data,n);
    834 				}
    835 				break;
    836 			case JPEG_MARKER_SOF0: /* Baseline sequential Huffman */
    837 			case JPEG_MARKER_SOF1: /* Extended sequential Huffman */
    838 			case JPEG_MARKER_SOF2: /* Progressive Huffman: normally not allowed by TechNote, but that doesn't hurt supporting it */
    839 			case JPEG_MARKER_SOF9: /* Extended sequential arithmetic */
    840 			case JPEG_MARKER_SOF10: /* Progressive arithmetic: normally not allowed by TechNote, but that doesn't hurt supporting it */
    841 				/* this marker contains the subsampling factors we're scanning for */
    842 				{
    843 					uint16 n;
    844 					uint16 o;
    845 					uint8 p;
    846 					uint8 ph,pv;
    847 					if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
    848 						return(0);
    849 					if (n!=8+data->tif->tif_dir.td_samplesperpixel*3)
    850 						return(0);
    851 					JPEGFixupTagsSubsamplingSkip(data,7);
    852 					if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
    853 						return(0);
    854 					ph=(p>>4);
    855 					pv=(p&15);
    856 					JPEGFixupTagsSubsamplingSkip(data,1);
    857 					for (o=1; o<data->tif->tif_dir.td_samplesperpixel; o++)
    858 					{
    859 						JPEGFixupTagsSubsamplingSkip(data,1);
    860 						if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
    861 							return(0);
    862 						if (p!=0x11)
    863 						{
    864 							TIFFWarningExt(data->tif->tif_clientdata,module,
    865 							    "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
    866 							return(1);
    867 						}
    868 						JPEGFixupTagsSubsamplingSkip(data,1);
    869 					}
    870 					if (((ph!=1)&&(ph!=2)&&(ph!=4))||((pv!=1)&&(pv!=2)&&(pv!=4)))
    871 					{
    872 						TIFFWarningExt(data->tif->tif_clientdata,module,
    873 						    "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
    874 						return(1);
    875 					}
    876 					if ((ph!=data->tif->tif_dir.td_ycbcrsubsampling[0])||(pv!=data->tif->tif_dir.td_ycbcrsubsampling[1]))
    877 					{
    878 						TIFFWarningExt(data->tif->tif_clientdata,module,
    879 						    "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
    880 						    (int)data->tif->tif_dir.td_ycbcrsubsampling[0],
    881 						    (int)data->tif->tif_dir.td_ycbcrsubsampling[1],
    882 						    (int)ph,(int)pv);
    883 						data->tif->tif_dir.td_ycbcrsubsampling[0]=ph;
    884 						data->tif->tif_dir.td_ycbcrsubsampling[1]=pv;
    885 					}
    886 				}
    887 				return(1);
    888 			default:
    889 				return(0);
    890 		}
    891 	}
    892 }
    893 
    894 static int
    895 JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result)
    896 {
    897 	if (data->bufferbytesleft==0)
    898 	{
    899 		uint32 m;
    900 		if (data->filebytesleft==0)
    901 			return(0);
    902 		if (!data->filepositioned)
    903 		{
    904 			TIFFSeekFile(data->tif,data->fileoffset,SEEK_SET);
    905 			data->filepositioned=1;
    906 		}
    907 		m=data->buffersize;
    908 		if ((uint64)m>data->filebytesleft)
    909 			m=(uint32)data->filebytesleft;
    910 		assert(m<0x80000000UL);
    911 		if (TIFFReadFile(data->tif,data->buffer,(tmsize_t)m)!=(tmsize_t)m)
    912 			return(0);
    913 		data->buffercurrentbyte=data->buffer;
    914 		data->bufferbytesleft=m;
    915 		data->fileoffset+=m;
    916 		data->filebytesleft-=m;
    917 	}
    918 	*result=*data->buffercurrentbyte;
    919 	data->buffercurrentbyte++;
    920 	data->bufferbytesleft--;
    921 	return(1);
    922 }
    923 
    924 static int
    925 JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result)
    926 {
    927 	uint8 ma;
    928 	uint8 mb;
    929 	if (!JPEGFixupTagsSubsamplingReadByte(data,&ma))
    930 		return(0);
    931 	if (!JPEGFixupTagsSubsamplingReadByte(data,&mb))
    932 		return(0);
    933 	*result=(ma<<8)|mb;
    934 	return(1);
    935 }
    936 
    937 static void
    938 JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength)
    939 {
    940 	if ((uint32)skiplength<=data->bufferbytesleft)
    941 	{
    942 		data->buffercurrentbyte+=skiplength;
    943 		data->bufferbytesleft-=skiplength;
    944 	}
    945 	else
    946 	{
    947 		uint16 m;
    948 		m=skiplength-data->bufferbytesleft;
    949 		if (m<=data->filebytesleft)
    950 		{
    951 			data->bufferbytesleft=0;
    952 			data->fileoffset+=m;
    953 			data->filebytesleft-=m;
    954 			data->filepositioned=0;
    955 		}
    956 		else
    957 		{
    958 			data->bufferbytesleft=0;
    959 			data->filebytesleft=0;
    960 		}
    961 	}
    962 }
    963 
    964 #endif
    965 
    966 
    967 static int
    968 JPEGSetupDecode(TIFF* tif)
    969 {
    970 	JPEGState* sp = JState(tif);
    971 	TIFFDirectory *td = &tif->tif_dir;
    972 
    973 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
    974         if( tif->tif_dir.td_bitspersample == 12 )
    975             return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 0 );
    976 #endif
    977 
    978 	JPEGInitializeLibJPEG( tif, TRUE );
    979 
    980 	assert(sp != NULL);
    981 	assert(sp->cinfo.comm.is_decompressor);
    982 
    983 	/* Read JPEGTables if it is present */
    984 	if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
    985 		TIFFjpeg_tables_src(sp, tif);
    986 		if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
    987 			TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
    988 			return (0);
    989 		}
    990 	}
    991 
    992 	/* Grab parameters that are same for all strips/tiles */
    993 	sp->photometric = td->td_photometric;
    994 	switch (sp->photometric) {
    995 	case PHOTOMETRIC_YCBCR:
    996 		sp->h_sampling = td->td_ycbcrsubsampling[0];
    997 		sp->v_sampling = td->td_ycbcrsubsampling[1];
    998 		break;
    999 	default:
   1000 		/* TIFF 6.0 forbids subsampling of all other color spaces */
   1001 		sp->h_sampling = 1;
   1002 		sp->v_sampling = 1;
   1003 		break;
   1004 	}
   1005 
   1006 	/* Set up for reading normal data */
   1007 	TIFFjpeg_data_src(sp, tif);
   1008 	tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
   1009 	return (1);
   1010 }
   1011 
   1012 /*
   1013  * Set up for decoding a strip or tile.
   1014  */
   1015 /*ARGSUSED*/ static int
   1016 JPEGPreDecode(TIFF* tif, uint16 s)
   1017 {
   1018 	JPEGState *sp = JState(tif);
   1019 	TIFFDirectory *td = &tif->tif_dir;
   1020 	static const char module[] = "JPEGPreDecode";
   1021 	uint32 segment_width, segment_height;
   1022 	int downsampled_output;
   1023 	int ci;
   1024 
   1025 	assert(sp != NULL);
   1026 
   1027 	if (sp->cinfo.comm.is_decompressor == 0)
   1028 	{
   1029 		tif->tif_setupdecode( tif );
   1030 	}
   1031 
   1032 	assert(sp->cinfo.comm.is_decompressor);
   1033 	/*
   1034 	 * Reset decoder state from any previous strip/tile,
   1035 	 * in case application didn't read the whole strip.
   1036 	 */
   1037 	if (!TIFFjpeg_abort(sp))
   1038 		return (0);
   1039 	/*
   1040 	 * Read the header for this strip/tile.
   1041 	 */
   1042 
   1043 	if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
   1044 		return (0);
   1045 
   1046         tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
   1047         tif->tif_rawcc = sp->src.bytes_in_buffer;
   1048 
   1049 	/*
   1050 	 * Check image parameters and set decompression parameters.
   1051 	 */
   1052 	segment_width = td->td_imagewidth;
   1053 	segment_height = td->td_imagelength - tif->tif_row;
   1054 	if (isTiled(tif)) {
   1055                 segment_width = td->td_tilewidth;
   1056                 segment_height = td->td_tilelength;
   1057 		sp->bytesperline = TIFFTileRowSize(tif);
   1058 	} else {
   1059 		if (segment_height > td->td_rowsperstrip)
   1060 			segment_height = td->td_rowsperstrip;
   1061 		sp->bytesperline = TIFFScanlineSize(tif);
   1062 	}
   1063 	if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
   1064 		/*
   1065 		 * For PC 2, scale down the expected strip/tile size
   1066 		 * to match a downsampled component
   1067 		 */
   1068 		segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
   1069 		segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
   1070 	}
   1071 	if (sp->cinfo.d.image_width < segment_width ||
   1072 	    sp->cinfo.d.image_height < segment_height) {
   1073 		TIFFWarningExt(tif->tif_clientdata, module,
   1074 			       "Improper JPEG strip/tile size, "
   1075 			       "expected %dx%d, got %dx%d",
   1076 			       segment_width, segment_height,
   1077 			       sp->cinfo.d.image_width,
   1078 			       sp->cinfo.d.image_height);
   1079 	}
   1080 	if (sp->cinfo.d.image_width > segment_width ||
   1081 	    sp->cinfo.d.image_height > segment_height) {
   1082 		/*
   1083 		 * This case could be dangerous, if the strip or tile size has
   1084 		 * been reported as less than the amount of data jpeg will
   1085 		 * return, some potential security issues arise. Catch this
   1086 		 * case and error out.
   1087 		 */
   1088 		TIFFErrorExt(tif->tif_clientdata, module,
   1089 			     "JPEG strip/tile size exceeds expected dimensions,"
   1090 			     " expected %dx%d, got %dx%d",
   1091 			     segment_width, segment_height,
   1092 			     sp->cinfo.d.image_width, sp->cinfo.d.image_height);
   1093 		return (0);
   1094 	}
   1095 	if (sp->cinfo.d.num_components !=
   1096 	    (td->td_planarconfig == PLANARCONFIG_CONTIG ?
   1097 	     td->td_samplesperpixel : 1)) {
   1098 		TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG component count");
   1099 		return (0);
   1100 	}
   1101 #ifdef JPEG_LIB_MK1
   1102 	if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
   1103 		TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
   1104 		return (0);
   1105 	}
   1106 	sp->cinfo.d.data_precision = td->td_bitspersample;
   1107 	sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
   1108 #else
   1109 	if (sp->cinfo.d.data_precision != td->td_bitspersample) {
   1110 		TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
   1111 		return (0);
   1112 	}
   1113 #endif
   1114 	if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
   1115 		/* Component 0 should have expected sampling factors */
   1116 		if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
   1117 		    sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
   1118 			TIFFErrorExt(tif->tif_clientdata, module,
   1119 				       "Improper JPEG sampling factors %d,%d\n"
   1120 				       "Apparently should be %d,%d.",
   1121 				       sp->cinfo.d.comp_info[0].h_samp_factor,
   1122 				       sp->cinfo.d.comp_info[0].v_samp_factor,
   1123 				       sp->h_sampling, sp->v_sampling);
   1124 			return (0);
   1125 		}
   1126 		/* Rest should have sampling factors 1,1 */
   1127 		for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
   1128 			if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
   1129 			    sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
   1130 				TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
   1131 				return (0);
   1132 			}
   1133 		}
   1134 	} else {
   1135 		/* PC 2's single component should have sampling factors 1,1 */
   1136 		if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
   1137 		    sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
   1138 			TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
   1139 			return (0);
   1140 		}
   1141 	}
   1142 	downsampled_output = FALSE;
   1143 	if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
   1144 	    sp->photometric == PHOTOMETRIC_YCBCR &&
   1145 	    sp->jpegcolormode == JPEGCOLORMODE_RGB) {
   1146 		/* Convert YCbCr to RGB */
   1147 		sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
   1148 		sp->cinfo.d.out_color_space = JCS_RGB;
   1149 	} else {
   1150 		/* Suppress colorspace handling */
   1151 		sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
   1152 		sp->cinfo.d.out_color_space = JCS_UNKNOWN;
   1153 		if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
   1154 		    (sp->h_sampling != 1 || sp->v_sampling != 1))
   1155 			downsampled_output = TRUE;
   1156 		/* XXX what about up-sampling? */
   1157 	}
   1158 	if (downsampled_output) {
   1159 		/* Need to use raw-data interface to libjpeg */
   1160 		sp->cinfo.d.raw_data_out = TRUE;
   1161 #if JPEG_LIB_VERSION >= 70
   1162 		sp->cinfo.d.do_fancy_upsampling = FALSE;
   1163 #endif /* JPEG_LIB_VERSION >= 70 */
   1164 		tif->tif_decoderow = DecodeRowError;
   1165 		tif->tif_decodestrip = JPEGDecodeRaw;
   1166 		tif->tif_decodetile = JPEGDecodeRaw;
   1167 	} else {
   1168 		/* Use normal interface to libjpeg */
   1169 		sp->cinfo.d.raw_data_out = FALSE;
   1170 		tif->tif_decoderow = JPEGDecode;
   1171 		tif->tif_decodestrip = JPEGDecode;
   1172 		tif->tif_decodetile = JPEGDecode;
   1173 	}
   1174 	/* Start JPEG decompressor */
   1175 	if (!TIFFjpeg_start_decompress(sp))
   1176 		return (0);
   1177 	/* Allocate downsampled-data buffers if needed */
   1178 	if (downsampled_output) {
   1179 		if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
   1180 					       sp->cinfo.d.num_components))
   1181 			return (0);
   1182 		sp->scancount = DCTSIZE;	/* mark buffer empty */
   1183 	}
   1184 	return (1);
   1185 }
   1186 
   1187 /*
   1188  * Decode a chunk of pixels.
   1189  * "Standard" case: returned data is not downsampled.
   1190  */
   1191 #if !JPEG_LIB_MK1_OR_12BIT
   1192 static int
   1193 JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
   1194 {
   1195 	JPEGState *sp = JState(tif);
   1196 	tmsize_t nrows;
   1197 	(void) s;
   1198 
   1199         /*
   1200         ** Update available information, buffer may have been refilled
   1201         ** between decode requests
   1202         */
   1203 	sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
   1204 	sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
   1205 
   1206         if( sp->bytesperline == 0 )
   1207                 return 0;
   1208 
   1209 	nrows = cc / sp->bytesperline;
   1210 	if (cc % sp->bytesperline)
   1211 		TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
   1212                                "fractional scanline not read");
   1213 
   1214 	if( nrows > (tmsize_t) sp->cinfo.d.image_height )
   1215 		nrows = sp->cinfo.d.image_height;
   1216 
   1217 	/* data is expected to be read in multiples of a scanline */
   1218 	if (nrows)
   1219         {
   1220                 do
   1221                 {
   1222                         /*
   1223                          * In the libjpeg6b-9a 8bit case.  We read directly into
   1224                          * the TIFF buffer.
   1225                          */
   1226                         JSAMPROW bufptr = (JSAMPROW)buf;
   1227 
   1228                         if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
   1229                                 return (0);
   1230 
   1231                         ++tif->tif_row;
   1232                         buf += sp->bytesperline;
   1233                         cc -= sp->bytesperline;
   1234                 } while (--nrows > 0);
   1235         }
   1236 
   1237         /* Update information on consumed data */
   1238         tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
   1239         tif->tif_rawcc = sp->src.bytes_in_buffer;
   1240 
   1241 	/* Close down the decompressor if we've finished the strip or tile. */
   1242 	return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
   1243                 || TIFFjpeg_finish_decompress(sp);
   1244 }
   1245 #endif /* !JPEG_LIB_MK1_OR_12BIT */
   1246 
   1247 #if JPEG_LIB_MK1_OR_12BIT
   1248 /*ARGSUSED*/ static int
   1249 JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
   1250 {
   1251 	JPEGState *sp = JState(tif);
   1252 	tmsize_t nrows;
   1253 	(void) s;
   1254 
   1255         /*
   1256         ** Update available information, buffer may have been refilled
   1257         ** between decode requests
   1258         */
   1259 	sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
   1260 	sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
   1261 
   1262         if( sp->bytesperline == 0 )
   1263                 return 0;
   1264 
   1265 	nrows = cc / sp->bytesperline;
   1266 	if (cc % sp->bytesperline)
   1267 		TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
   1268                                "fractional scanline not read");
   1269 
   1270 	if( nrows > (tmsize_t) sp->cinfo.d.image_height )
   1271 		nrows = sp->cinfo.d.image_height;
   1272 
   1273 	/* data is expected to be read in multiples of a scanline */
   1274 	if (nrows)
   1275         {
   1276                 JSAMPROW line_work_buf = NULL;
   1277 
   1278                 /*
   1279                  * For 6B, only use temporary buffer for 12 bit imagery.
   1280                  * For Mk1 always use it.
   1281                  */
   1282                 if( sp->cinfo.d.data_precision == 12 )
   1283                 {
   1284                         line_work_buf = (JSAMPROW)
   1285                                 _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
   1286                                             * sp->cinfo.d.num_components );
   1287                 }
   1288 
   1289                do
   1290                {
   1291                        if( line_work_buf != NULL )
   1292                        {
   1293                                /*
   1294                                 * In the MK1 case, we aways read into a 16bit
   1295                                 * buffer, and then pack down to 12bit or 8bit.
   1296                                 * In 6B case we only read into 16 bit buffer
   1297                                 * for 12bit data, which we need to repack.
   1298                                 */
   1299                                if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
   1300                                        return (0);
   1301 
   1302                                if( sp->cinfo.d.data_precision == 12 )
   1303                                {
   1304                                        int value_pairs = (sp->cinfo.d.output_width
   1305                                                           * sp->cinfo.d.num_components) / 2;
   1306                                        int iPair;
   1307 
   1308                                        for( iPair = 0; iPair < value_pairs; iPair++ )
   1309                                        {
   1310                                                unsigned char *out_ptr =
   1311                                                        ((unsigned char *) buf) + iPair * 3;
   1312                                                JSAMPLE *in_ptr = line_work_buf + iPair * 2;
   1313 
   1314                                                out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
   1315                                                out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
   1316                                                        | ((in_ptr[1] & 0xf00) >> 8);
   1317                                                out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
   1318                                        }
   1319                                }
   1320                                else if( sp->cinfo.d.data_precision == 8 )
   1321                                {
   1322                                        int value_count = (sp->cinfo.d.output_width
   1323                                                           * sp->cinfo.d.num_components);
   1324                                        int iValue;
   1325 
   1326                                        for( iValue = 0; iValue < value_count; iValue++ )
   1327                                        {
   1328                                                ((unsigned char *) buf)[iValue] =
   1329                                                        line_work_buf[iValue] & 0xff;
   1330                                        }
   1331                                }
   1332                        }
   1333 
   1334                        ++tif->tif_row;
   1335                        buf += sp->bytesperline;
   1336                        cc -= sp->bytesperline;
   1337                } while (--nrows > 0);
   1338 
   1339                if( line_work_buf != NULL )
   1340                        _TIFFfree( line_work_buf );
   1341         }
   1342 
   1343         /* Update information on consumed data */
   1344         tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
   1345         tif->tif_rawcc = sp->src.bytes_in_buffer;
   1346 
   1347 	/* Close down the decompressor if we've finished the strip or tile. */
   1348 	return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
   1349                 || TIFFjpeg_finish_decompress(sp);
   1350 }
   1351 #endif /* JPEG_LIB_MK1_OR_12BIT */
   1352 
   1353 /*ARGSUSED*/ static int
   1354 DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
   1355 
   1356 {
   1357     (void) buf;
   1358     (void) cc;
   1359     (void) s;
   1360 
   1361     TIFFErrorExt(tif->tif_clientdata, "TIFFReadScanline",
   1362                  "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
   1363     return 0;
   1364 }
   1365 
   1366 /*
   1367  * Decode a chunk of pixels.
   1368  * Returned data is downsampled per sampling factors.
   1369  */
   1370 /*ARGSUSED*/ static int
   1371 JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
   1372 {
   1373 	JPEGState *sp = JState(tif);
   1374 	tmsize_t nrows;
   1375 	(void) s;
   1376 
   1377 	/* data is expected to be read in multiples of a scanline */
   1378 	if ( (nrows = sp->cinfo.d.image_height) ) {
   1379 
   1380 		/* Cb,Cr both have sampling factors 1, so this is correct */
   1381 		JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
   1382 		int samples_per_clump = sp->samplesperclump;
   1383 
   1384 #if defined(JPEG_LIB_MK1_OR_12BIT)
   1385 		unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
   1386 						     sp->cinfo.d.output_width *
   1387 						     sp->cinfo.d.num_components);
   1388 		if(tmpbuf==NULL) {
   1389                         TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
   1390 				     "Out of memory");
   1391 			return 0;
   1392                 }
   1393 #endif
   1394 
   1395 		do {
   1396 			jpeg_component_info *compptr;
   1397 			int ci, clumpoffset;
   1398 
   1399                         if( cc < sp->bytesperline ) {
   1400 				TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
   1401 					     "application buffer not large enough for all data.");
   1402 				return 0;
   1403                         }
   1404 
   1405 			/* Reload downsampled-data buffer if needed */
   1406 			if (sp->scancount >= DCTSIZE) {
   1407 				int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
   1408 				if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
   1409 					return (0);
   1410 				sp->scancount = 0;
   1411 			}
   1412 			/*
   1413 			 * Fastest way to unseparate data is to make one pass
   1414 			 * over the scanline for each row of each component.
   1415 			 */
   1416 			clumpoffset = 0;    /* first sample in clump */
   1417 			for (ci = 0, compptr = sp->cinfo.d.comp_info;
   1418 			     ci < sp->cinfo.d.num_components;
   1419 			     ci++, compptr++) {
   1420 				int hsamp = compptr->h_samp_factor;
   1421 				int vsamp = compptr->v_samp_factor;
   1422 				int ypos;
   1423 
   1424 				for (ypos = 0; ypos < vsamp; ypos++) {
   1425 					JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
   1426 					JDIMENSION nclump;
   1427 #if defined(JPEG_LIB_MK1_OR_12BIT)
   1428 					JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
   1429 #else
   1430 					JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
   1431 					if (cc < (tmsize_t) (clumpoffset + samples_per_clump*(clumps_per_line-1) + hsamp)) {
   1432 						TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
   1433 							     "application buffer not large enough for all data, possible subsampling issue");
   1434 						return 0;
   1435 					}
   1436 #endif
   1437 
   1438 					if (hsamp == 1) {
   1439 						/* fast path for at least Cb and Cr */
   1440 						for (nclump = clumps_per_line; nclump-- > 0; ) {
   1441 							outptr[0] = *inptr++;
   1442 							outptr += samples_per_clump;
   1443 						}
   1444 					} else {
   1445 						int xpos;
   1446 
   1447 						/* general case */
   1448 						for (nclump = clumps_per_line; nclump-- > 0; ) {
   1449 							for (xpos = 0; xpos < hsamp; xpos++)
   1450 								outptr[xpos] = *inptr++;
   1451 							outptr += samples_per_clump;
   1452 						}
   1453 					}
   1454 					clumpoffset += hsamp;
   1455 				}
   1456 			}
   1457 
   1458 #if defined(JPEG_LIB_MK1_OR_12BIT)
   1459 			{
   1460 				if (sp->cinfo.d.data_precision == 8)
   1461 				{
   1462 					int i=0;
   1463 					int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
   1464 					for (i=0; i<len; i++)
   1465 					{
   1466 						((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
   1467 					}
   1468 				}
   1469 				else
   1470 				{         /* 12-bit */
   1471 					int value_pairs = (sp->cinfo.d.output_width
   1472 							   * sp->cinfo.d.num_components) / 2;
   1473 					int iPair;
   1474 					for( iPair = 0; iPair < value_pairs; iPair++ )
   1475 					{
   1476 						unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
   1477 						JSAMPLE *in_ptr = (JSAMPLE *) (tmpbuf + iPair * 2);
   1478 						out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
   1479 						out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
   1480 							| ((in_ptr[1] & 0xf00) >> 8);
   1481 						out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
   1482 					}
   1483 				}
   1484 			}
   1485 #endif
   1486 
   1487 			sp->scancount ++;
   1488 			tif->tif_row += sp->v_sampling;
   1489 
   1490 			buf += sp->bytesperline;
   1491 			cc -= sp->bytesperline;
   1492 
   1493 			nrows -= sp->v_sampling;
   1494 		} while (nrows > 0);
   1495 
   1496 #if defined(JPEG_LIB_MK1_OR_12BIT)
   1497 		_TIFFfree(tmpbuf);
   1498 #endif
   1499 
   1500 	}
   1501 
   1502 	/* Close down the decompressor if done. */
   1503 	return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
   1504 		|| TIFFjpeg_finish_decompress(sp);
   1505 }
   1506 
   1507 
   1508 /*
   1509  * JPEG Encoding.
   1510  */
   1511 
   1512 static void
   1513 unsuppress_quant_table (JPEGState* sp, int tblno)
   1514 {
   1515 	JQUANT_TBL* qtbl;
   1516 
   1517 	if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
   1518 		qtbl->sent_table = FALSE;
   1519 }
   1520 
   1521 static void
   1522 suppress_quant_table (JPEGState* sp, int tblno)
   1523 {
   1524 	JQUANT_TBL* qtbl;
   1525 
   1526 	if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
   1527 		qtbl->sent_table = TRUE;
   1528 }
   1529 
   1530 static void
   1531 unsuppress_huff_table (JPEGState* sp, int tblno)
   1532 {
   1533 	JHUFF_TBL* htbl;
   1534 
   1535 	if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
   1536 		htbl->sent_table = FALSE;
   1537 	if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
   1538 		htbl->sent_table = FALSE;
   1539 }
   1540 
   1541 static void
   1542 suppress_huff_table (JPEGState* sp, int tblno)
   1543 {
   1544 	JHUFF_TBL* htbl;
   1545 
   1546 	if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
   1547 		htbl->sent_table = TRUE;
   1548 	if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
   1549 		htbl->sent_table = TRUE;
   1550 }
   1551 
   1552 static int
   1553 prepare_JPEGTables(TIFF* tif)
   1554 {
   1555 	JPEGState* sp = JState(tif);
   1556 
   1557 	/* Initialize quant tables for current quality setting */
   1558 	if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
   1559 		return (0);
   1560 	/* Mark only the tables we want for output */
   1561 	/* NB: chrominance tables are currently used only with YCbCr */
   1562 	if (!TIFFjpeg_suppress_tables(sp, TRUE))
   1563 		return (0);
   1564 	if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
   1565 		unsuppress_quant_table(sp, 0);
   1566 		if (sp->photometric == PHOTOMETRIC_YCBCR)
   1567 			unsuppress_quant_table(sp, 1);
   1568 	}
   1569 	if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
   1570 		unsuppress_huff_table(sp, 0);
   1571 		if (sp->photometric == PHOTOMETRIC_YCBCR)
   1572 			unsuppress_huff_table(sp, 1);
   1573 	}
   1574 	/* Direct libjpeg output into jpegtables */
   1575 	if (!TIFFjpeg_tables_dest(sp, tif))
   1576 		return (0);
   1577 	/* Emit tables-only datastream */
   1578 	if (!TIFFjpeg_write_tables(sp))
   1579 		return (0);
   1580 
   1581 	return (1);
   1582 }
   1583 
   1584 static int
   1585 JPEGSetupEncode(TIFF* tif)
   1586 {
   1587 	JPEGState* sp = JState(tif);
   1588 	TIFFDirectory *td = &tif->tif_dir;
   1589 	static const char module[] = "JPEGSetupEncode";
   1590 
   1591 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
   1592         if( tif->tif_dir.td_bitspersample == 12 )
   1593             return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 1 );
   1594 #endif
   1595 
   1596         JPEGInitializeLibJPEG( tif, FALSE );
   1597 
   1598 	assert(sp != NULL);
   1599 	assert(!sp->cinfo.comm.is_decompressor);
   1600 
   1601 	sp->photometric = td->td_photometric;
   1602 
   1603 	/*
   1604 	 * Initialize all JPEG parameters to default values.
   1605 	 * Note that jpeg_set_defaults needs legal values for
   1606 	 * in_color_space and input_components.
   1607 	 */
   1608 	if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
   1609 		sp->cinfo.c.input_components = td->td_samplesperpixel;
   1610 		if (sp->photometric == PHOTOMETRIC_YCBCR) {
   1611 			if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
   1612 				sp->cinfo.c.in_color_space = JCS_RGB;
   1613 			} else {
   1614 				sp->cinfo.c.in_color_space = JCS_YCbCr;
   1615 			}
   1616 		} else {
   1617 			if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
   1618 				sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
   1619 			else if (td->td_photometric == PHOTOMETRIC_RGB && td->td_samplesperpixel == 3)
   1620 				sp->cinfo.c.in_color_space = JCS_RGB;
   1621 			else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
   1622 				sp->cinfo.c.in_color_space = JCS_CMYK;
   1623 			else
   1624 				sp->cinfo.c.in_color_space = JCS_UNKNOWN;
   1625 		}
   1626 	} else {
   1627 		sp->cinfo.c.input_components = 1;
   1628 		sp->cinfo.c.in_color_space = JCS_UNKNOWN;
   1629 	}
   1630 	if (!TIFFjpeg_set_defaults(sp))
   1631 		return (0);
   1632 	/* Set per-file parameters */
   1633 	switch (sp->photometric) {
   1634 	case PHOTOMETRIC_YCBCR:
   1635 		sp->h_sampling = td->td_ycbcrsubsampling[0];
   1636 		sp->v_sampling = td->td_ycbcrsubsampling[1];
   1637 		/*
   1638 		 * A ReferenceBlackWhite field *must* be present since the
   1639 		 * default value is inappropriate for YCbCr.  Fill in the
   1640 		 * proper value if application didn't set it.
   1641 		 */
   1642 		{
   1643 			float *ref;
   1644 			if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
   1645 					  &ref)) {
   1646 				float refbw[6];
   1647 				long top = 1L << td->td_bitspersample;
   1648 				refbw[0] = 0;
   1649 				refbw[1] = (float)(top-1L);
   1650 				refbw[2] = (float)(top>>1);
   1651 				refbw[3] = refbw[1];
   1652 				refbw[4] = refbw[2];
   1653 				refbw[5] = refbw[1];
   1654 				TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
   1655 					     refbw);
   1656 			}
   1657 		}
   1658 		break;
   1659 	case PHOTOMETRIC_PALETTE:		/* disallowed by Tech Note */
   1660 	case PHOTOMETRIC_MASK:
   1661 		TIFFErrorExt(tif->tif_clientdata, module,
   1662 			  "PhotometricInterpretation %d not allowed for JPEG",
   1663 			  (int) sp->photometric);
   1664 		return (0);
   1665 	default:
   1666 		/* TIFF 6.0 forbids subsampling of all other color spaces */
   1667 		sp->h_sampling = 1;
   1668 		sp->v_sampling = 1;
   1669 		break;
   1670 	}
   1671 
   1672 	/* Verify miscellaneous parameters */
   1673 
   1674 	/*
   1675 	 * This would need work if libtiff ever supports different
   1676 	 * depths for different components, or if libjpeg ever supports
   1677 	 * run-time selection of depth.  Neither is imminent.
   1678 	 */
   1679 #ifdef JPEG_LIB_MK1
   1680         /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
   1681 	if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
   1682 #else
   1683 	if (td->td_bitspersample != BITS_IN_JSAMPLE )
   1684 #endif
   1685 	{
   1686 		TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
   1687 			  (int) td->td_bitspersample);
   1688 		return (0);
   1689 	}
   1690 	sp->cinfo.c.data_precision = td->td_bitspersample;
   1691 #ifdef JPEG_LIB_MK1
   1692         sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
   1693 #endif
   1694 	if (isTiled(tif)) {
   1695 		if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
   1696 			TIFFErrorExt(tif->tif_clientdata, module,
   1697 				  "JPEG tile height must be multiple of %d",
   1698 				  sp->v_sampling * DCTSIZE);
   1699 			return (0);
   1700 		}
   1701 		if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
   1702 			TIFFErrorExt(tif->tif_clientdata, module,
   1703 				  "JPEG tile width must be multiple of %d",
   1704 				  sp->h_sampling * DCTSIZE);
   1705 			return (0);
   1706 		}
   1707 	} else {
   1708 		if (td->td_rowsperstrip < td->td_imagelength &&
   1709 		    (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
   1710 			TIFFErrorExt(tif->tif_clientdata, module,
   1711 				  "RowsPerStrip must be multiple of %d for JPEG",
   1712 				  sp->v_sampling * DCTSIZE);
   1713 			return (0);
   1714 		}
   1715 	}
   1716 
   1717 	/* Create a JPEGTables field if appropriate */
   1718 	if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
   1719                 if( sp->jpegtables == NULL
   1720                     || memcmp(sp->jpegtables,"\0\0\0\0\0\0\0\0\0",8) == 0 )
   1721                 {
   1722                         if (!prepare_JPEGTables(tif))
   1723                                 return (0);
   1724                         /* Mark the field present */
   1725                         /* Can't use TIFFSetField since BEENWRITING is already set! */
   1726                         tif->tif_flags |= TIFF_DIRTYDIRECT;
   1727                         TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
   1728                 }
   1729 	} else {
   1730 		/* We do not support application-supplied JPEGTables, */
   1731 		/* so mark the field not present */
   1732 		TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
   1733 	}
   1734 
   1735 	/* Direct libjpeg output to libtiff's output buffer */
   1736 	TIFFjpeg_data_dest(sp, tif);
   1737 
   1738 	return (1);
   1739 }
   1740 
   1741 /*
   1742  * Set encoding state at the start of a strip or tile.
   1743  */
   1744 static int
   1745 JPEGPreEncode(TIFF* tif, uint16 s)
   1746 {
   1747 	JPEGState *sp = JState(tif);
   1748 	TIFFDirectory *td = &tif->tif_dir;
   1749 	static const char module[] = "JPEGPreEncode";
   1750 	uint32 segment_width, segment_height;
   1751 	int downsampled_input;
   1752 
   1753 	assert(sp != NULL);
   1754 
   1755 	if (sp->cinfo.comm.is_decompressor == 1)
   1756 	{
   1757 		tif->tif_setupencode( tif );
   1758 	}
   1759 
   1760 	assert(!sp->cinfo.comm.is_decompressor);
   1761 	/*
   1762 	 * Set encoding parameters for this strip/tile.
   1763 	 */
   1764 	if (isTiled(tif)) {
   1765 		segment_width = td->td_tilewidth;
   1766 		segment_height = td->td_tilelength;
   1767 		sp->bytesperline = TIFFTileRowSize(tif);
   1768 	} else {
   1769 		segment_width = td->td_imagewidth;
   1770 		segment_height = td->td_imagelength - tif->tif_row;
   1771 		if (segment_height > td->td_rowsperstrip)
   1772 			segment_height = td->td_rowsperstrip;
   1773 		sp->bytesperline = TIFFScanlineSize(tif);
   1774 	}
   1775 	if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
   1776 		/* for PC 2, scale down the strip/tile size
   1777 		 * to match a downsampled component
   1778 		 */
   1779 		segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
   1780 		segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
   1781 	}
   1782 	if (segment_width > 65535 || segment_height > 65535) {
   1783 		TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
   1784 		return (0);
   1785 	}
   1786 	sp->cinfo.c.image_width = segment_width;
   1787 	sp->cinfo.c.image_height = segment_height;
   1788 	downsampled_input = FALSE;
   1789 	if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
   1790 		sp->cinfo.c.input_components = td->td_samplesperpixel;
   1791 		if (sp->photometric == PHOTOMETRIC_YCBCR) {
   1792 			if (sp->jpegcolormode != JPEGCOLORMODE_RGB) {
   1793 				if (sp->h_sampling != 1 || sp->v_sampling != 1)
   1794 					downsampled_input = TRUE;
   1795 			}
   1796 			if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
   1797 				return (0);
   1798 			/*
   1799 			 * Set Y sampling factors;
   1800 			 * we assume jpeg_set_colorspace() set the rest to 1
   1801 			 */
   1802 			sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
   1803 			sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
   1804 		} else {
   1805 			if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
   1806 				return (0);
   1807 			/* jpeg_set_colorspace set all sampling factors to 1 */
   1808 		}
   1809 	} else {
   1810 		if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
   1811 			return (0);
   1812 		sp->cinfo.c.comp_info[0].component_id = s;
   1813 		/* jpeg_set_colorspace() set sampling factors to 1 */
   1814 		if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
   1815 			sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
   1816 			sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
   1817 			sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
   1818 		}
   1819 	}
   1820 	/* ensure libjpeg won't write any extraneous markers */
   1821 	sp->cinfo.c.write_JFIF_header = FALSE;
   1822 	sp->cinfo.c.write_Adobe_marker = FALSE;
   1823 	/* set up table handling correctly */
   1824 	/* calling TIFFjpeg_set_quality() causes quantization tables to be flagged */
   1825 	/* as being to be emitted, which we don't want in the JPEGTABLESMODE_QUANT */
   1826 	/* mode, so we must manually suppress them. However TIFFjpeg_set_quality() */
   1827 	/* should really be called when dealing with files with directories with */
   1828 	/* mixed qualities. see http://trac.osgeo.org/gdal/ticket/3539 */
   1829 	if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
   1830 		return (0);
   1831 	if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
   1832 		suppress_quant_table(sp, 0);
   1833 		suppress_quant_table(sp, 1);
   1834 	}
   1835 	else {
   1836 		unsuppress_quant_table(sp, 0);
   1837 		unsuppress_quant_table(sp, 1);
   1838 	}
   1839 	if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
   1840 	{
   1841 		/* Explicit suppression is only needed if we did not go through the */
   1842 		/* prepare_JPEGTables() code path, which may be the case if updating */
   1843 		/* an existing file */
   1844 		suppress_huff_table(sp, 0);
   1845 		suppress_huff_table(sp, 1);
   1846 		sp->cinfo.c.optimize_coding = FALSE;
   1847 	}
   1848 	else
   1849 		sp->cinfo.c.optimize_coding = TRUE;
   1850 	if (downsampled_input) {
   1851 		/* Need to use raw-data interface to libjpeg */
   1852 		sp->cinfo.c.raw_data_in = TRUE;
   1853 		tif->tif_encoderow = JPEGEncodeRaw;
   1854 		tif->tif_encodestrip = JPEGEncodeRaw;
   1855 		tif->tif_encodetile = JPEGEncodeRaw;
   1856 	} else {
   1857 		/* Use normal interface to libjpeg */
   1858 		sp->cinfo.c.raw_data_in = FALSE;
   1859 		tif->tif_encoderow = JPEGEncode;
   1860 		tif->tif_encodestrip = JPEGEncode;
   1861 		tif->tif_encodetile = JPEGEncode;
   1862 	}
   1863 	/* Start JPEG compressor */
   1864 	if (!TIFFjpeg_start_compress(sp, FALSE))
   1865 		return (0);
   1866 	/* Allocate downsampled-data buffers if needed */
   1867 	if (downsampled_input) {
   1868 		if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
   1869 					       sp->cinfo.c.num_components))
   1870 			return (0);
   1871 	}
   1872 	sp->scancount = 0;
   1873 
   1874 	return (1);
   1875 }
   1876 
   1877 /*
   1878  * Encode a chunk of pixels.
   1879  * "Standard" case: incoming data is not downsampled.
   1880  */
   1881 static int
   1882 JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
   1883 {
   1884 	JPEGState *sp = JState(tif);
   1885 	tmsize_t nrows;
   1886 	JSAMPROW bufptr[1];
   1887         short *line16 = NULL;
   1888         int    line16_count = 0;
   1889 
   1890 	(void) s;
   1891 	assert(sp != NULL);
   1892 	/* data is expected to be supplied in multiples of a scanline */
   1893 	nrows = cc / sp->bytesperline;
   1894 	if (cc % sp->bytesperline)
   1895             TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
   1896                            "fractional scanline discarded");
   1897 
   1898         /* The last strip will be limited to image size */
   1899         if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
   1900             nrows = tif->tif_dir.td_imagelength - tif->tif_row;
   1901 
   1902         if( sp->cinfo.c.data_precision == 12 )
   1903         {
   1904             line16_count = (sp->bytesperline * 2) / 3;
   1905             line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
   1906             if (!line16)
   1907             {
   1908                 TIFFErrorExt(tif->tif_clientdata,
   1909 			     "JPEGEncode",
   1910                              "Failed to allocate memory");
   1911 
   1912                 return 0;
   1913             }
   1914         }
   1915 
   1916 	while (nrows-- > 0) {
   1917 
   1918             if( sp->cinfo.c.data_precision == 12 )
   1919             {
   1920 
   1921                 int value_pairs = line16_count / 2;
   1922                 int iPair;
   1923 
   1924 		bufptr[0] = (JSAMPROW) line16;
   1925 
   1926                 for( iPair = 0; iPair < value_pairs; iPair++ )
   1927                 {
   1928                     unsigned char *in_ptr =
   1929                         ((unsigned char *) buf) + iPair * 3;
   1930                     JSAMPLE *out_ptr = (JSAMPLE *) (line16 + iPair * 2);
   1931 
   1932                     out_ptr[0] = (in_ptr[0] << 4) | ((in_ptr[1] & 0xf0) >> 4);
   1933                     out_ptr[1] = ((in_ptr[1] & 0x0f) << 8) | in_ptr[2];
   1934                 }
   1935             }
   1936             else
   1937             {
   1938 		bufptr[0] = (JSAMPROW) buf;
   1939             }
   1940             if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
   1941                 return (0);
   1942             if (nrows > 0)
   1943                 tif->tif_row++;
   1944             buf += sp->bytesperline;
   1945 	}
   1946 
   1947         if( sp->cinfo.c.data_precision == 12 )
   1948         {
   1949             _TIFFfree( line16 );
   1950         }
   1951 
   1952 	return (1);
   1953 }
   1954 
   1955 /*
   1956  * Encode a chunk of pixels.
   1957  * Incoming data is expected to be downsampled per sampling factors.
   1958  */
   1959 static int
   1960 JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
   1961 {
   1962 	JPEGState *sp = JState(tif);
   1963 	JSAMPLE* inptr;
   1964 	JSAMPLE* outptr;
   1965 	tmsize_t nrows;
   1966 	JDIMENSION clumps_per_line, nclump;
   1967 	int clumpoffset, ci, xpos, ypos;
   1968 	jpeg_component_info* compptr;
   1969 	int samples_per_clump = sp->samplesperclump;
   1970 	tmsize_t bytesperclumpline;
   1971 
   1972 	(void) s;
   1973 	assert(sp != NULL);
   1974 	/* data is expected to be supplied in multiples of a clumpline */
   1975 	/* a clumpline is equivalent to v_sampling desubsampled scanlines */
   1976 	/* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
   1977 	bytesperclumpline = (((sp->cinfo.c.image_width+sp->h_sampling-1)/sp->h_sampling)
   1978 			     *(sp->h_sampling*sp->v_sampling+2)*sp->cinfo.c.data_precision+7)
   1979 			    /8;
   1980 
   1981 	nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
   1982 	if (cc % bytesperclumpline)
   1983 		TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
   1984 
   1985 	/* Cb,Cr both have sampling factors 1, so this is correct */
   1986 	clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
   1987 
   1988 	while (nrows > 0) {
   1989 		/*
   1990 		 * Fastest way to separate the data is to make one pass
   1991 		 * over the scanline for each row of each component.
   1992 		 */
   1993 		clumpoffset = 0;		/* first sample in clump */
   1994 		for (ci = 0, compptr = sp->cinfo.c.comp_info;
   1995 		     ci < sp->cinfo.c.num_components;
   1996 		     ci++, compptr++) {
   1997 		    int hsamp = compptr->h_samp_factor;
   1998 		    int vsamp = compptr->v_samp_factor;
   1999 		    int padding = (int) (compptr->width_in_blocks * DCTSIZE -
   2000 					 clumps_per_line * hsamp);
   2001 		    for (ypos = 0; ypos < vsamp; ypos++) {
   2002 			inptr = ((JSAMPLE*) buf) + clumpoffset;
   2003 			outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
   2004 			if (hsamp == 1) {
   2005 			    /* fast path for at least Cb and Cr */
   2006 			    for (nclump = clumps_per_line; nclump-- > 0; ) {
   2007 				*outptr++ = inptr[0];
   2008 				inptr += samples_per_clump;
   2009 			    }
   2010 			} else {
   2011 			    /* general case */
   2012 			    for (nclump = clumps_per_line; nclump-- > 0; ) {
   2013 				for (xpos = 0; xpos < hsamp; xpos++)
   2014 				    *outptr++ = inptr[xpos];
   2015 				inptr += samples_per_clump;
   2016 			    }
   2017 			}
   2018 			/* pad each scanline as needed */
   2019 			for (xpos = 0; xpos < padding; xpos++) {
   2020 			    *outptr = outptr[-1];
   2021 			    outptr++;
   2022 			}
   2023 			clumpoffset += hsamp;
   2024 		    }
   2025 		}
   2026 		sp->scancount++;
   2027 		if (sp->scancount >= DCTSIZE) {
   2028 			int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
   2029 			if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
   2030 				return (0);
   2031 			sp->scancount = 0;
   2032 		}
   2033 		tif->tif_row += sp->v_sampling;
   2034 		buf += bytesperclumpline;
   2035 		nrows -= sp->v_sampling;
   2036 	}
   2037 	return (1);
   2038 }
   2039 
   2040 /*
   2041  * Finish up at the end of a strip or tile.
   2042  */
   2043 static int
   2044 JPEGPostEncode(TIFF* tif)
   2045 {
   2046 	JPEGState *sp = JState(tif);
   2047 
   2048 	if (sp->scancount > 0) {
   2049 		/*
   2050 		 * Need to emit a partial bufferload of downsampled data.
   2051 		 * Pad the data vertically.
   2052 		 */
   2053 		int ci, ypos, n;
   2054 		jpeg_component_info* compptr;
   2055 
   2056 		for (ci = 0, compptr = sp->cinfo.c.comp_info;
   2057 		     ci < sp->cinfo.c.num_components;
   2058 		     ci++, compptr++) {
   2059 			int vsamp = compptr->v_samp_factor;
   2060 			tmsize_t row_width = compptr->width_in_blocks * DCTSIZE
   2061 				* sizeof(JSAMPLE);
   2062 			for (ypos = sp->scancount * vsamp;
   2063 			     ypos < DCTSIZE * vsamp; ypos++) {
   2064 				_TIFFmemcpy((void*)sp->ds_buffer[ci][ypos],
   2065 					    (void*)sp->ds_buffer[ci][ypos-1],
   2066 					    row_width);
   2067 
   2068 			}
   2069 		}
   2070 		n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
   2071 		if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
   2072 			return (0);
   2073 	}
   2074 
   2075 	return (TIFFjpeg_finish_compress(JState(tif)));
   2076 }
   2077 
   2078 static void
   2079 JPEGCleanup(TIFF* tif)
   2080 {
   2081 	JPEGState *sp = JState(tif);
   2082 
   2083 	assert(sp != 0);
   2084 
   2085 	tif->tif_tagmethods.vgetfield = sp->vgetparent;
   2086 	tif->tif_tagmethods.vsetfield = sp->vsetparent;
   2087 	tif->tif_tagmethods.printdir = sp->printdir;
   2088         if( sp->cinfo_initialized )
   2089                 TIFFjpeg_destroy(sp);	/* release libjpeg resources */
   2090         if (sp->jpegtables)		/* tag value */
   2091                 _TIFFfree(sp->jpegtables);
   2092 	_TIFFfree(tif->tif_data);	/* release local state */
   2093 	tif->tif_data = NULL;
   2094 
   2095 	_TIFFSetDefaultCompressionState(tif);
   2096 }
   2097 
   2098 static void
   2099 JPEGResetUpsampled( TIFF* tif )
   2100 {
   2101 	JPEGState* sp = JState(tif);
   2102 	TIFFDirectory* td = &tif->tif_dir;
   2103 
   2104 	/*
   2105 	 * Mark whether returned data is up-sampled or not so TIFFStripSize
   2106 	 * and TIFFTileSize return values that reflect the true amount of
   2107 	 * data.
   2108 	 */
   2109 	tif->tif_flags &= ~TIFF_UPSAMPLED;
   2110 	if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
   2111 		if (td->td_photometric == PHOTOMETRIC_YCBCR &&
   2112 		    sp->jpegcolormode == JPEGCOLORMODE_RGB) {
   2113 			tif->tif_flags |= TIFF_UPSAMPLED;
   2114 		} else {
   2115 #ifdef notdef
   2116 			if (td->td_ycbcrsubsampling[0] != 1 ||
   2117 			    td->td_ycbcrsubsampling[1] != 1)
   2118 				; /* XXX what about up-sampling? */
   2119 #endif
   2120 		}
   2121 	}
   2122 
   2123 	/*
   2124 	 * Must recalculate cached tile size in case sampling state changed.
   2125 	 * Should we really be doing this now if image size isn't set?
   2126 	 */
   2127         if( tif->tif_tilesize > 0 )
   2128             tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
   2129         if( tif->tif_scanlinesize > 0 )
   2130             tif->tif_scanlinesize = TIFFScanlineSize(tif);
   2131 }
   2132 
   2133 static int
   2134 JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
   2135 {
   2136 	JPEGState* sp = JState(tif);
   2137 	const TIFFField* fip;
   2138 	uint32 v32;
   2139 
   2140 	assert(sp != NULL);
   2141 
   2142 	switch (tag) {
   2143 	case TIFFTAG_JPEGTABLES:
   2144 		v32 = (uint32) va_arg(ap, uint32);
   2145 		if (v32 == 0) {
   2146 			/* XXX */
   2147 			return (0);
   2148 		}
   2149 		_TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
   2150 		    (long) v32);
   2151 		sp->jpegtables_length = v32;
   2152 		TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
   2153 		break;
   2154 	case TIFFTAG_JPEGQUALITY:
   2155 		sp->jpegquality = (int) va_arg(ap, int);
   2156 		return (1);			/* pseudo tag */
   2157 	case TIFFTAG_JPEGCOLORMODE:
   2158 		sp->jpegcolormode = (int) va_arg(ap, int);
   2159 		JPEGResetUpsampled( tif );
   2160 		return (1);			/* pseudo tag */
   2161 	case TIFFTAG_PHOTOMETRIC:
   2162 	{
   2163 		int ret_value = (*sp->vsetparent)(tif, tag, ap);
   2164 		JPEGResetUpsampled( tif );
   2165 		return ret_value;
   2166 	}
   2167 	case TIFFTAG_JPEGTABLESMODE:
   2168 		sp->jpegtablesmode = (int) va_arg(ap, int);
   2169 		return (1);			/* pseudo tag */
   2170 	case TIFFTAG_YCBCRSUBSAMPLING:
   2171 		/* mark the fact that we have a real ycbcrsubsampling! */
   2172 		sp->ycbcrsampling_fetched = 1;
   2173 		/* should we be recomputing upsampling info here? */
   2174 		return (*sp->vsetparent)(tif, tag, ap);
   2175 	default:
   2176 		return (*sp->vsetparent)(tif, tag, ap);
   2177 	}
   2178 
   2179 	if ((fip = TIFFFieldWithTag(tif, tag))) {
   2180 		TIFFSetFieldBit(tif, fip->field_bit);
   2181 	} else {
   2182 		return (0);
   2183 	}
   2184 
   2185 	tif->tif_flags |= TIFF_DIRTYDIRECT;
   2186 	return (1);
   2187 }
   2188 
   2189 static int
   2190 JPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
   2191 {
   2192 	JPEGState* sp = JState(tif);
   2193 
   2194 	assert(sp != NULL);
   2195 
   2196 	switch (tag) {
   2197 		case TIFFTAG_JPEGTABLES:
   2198 			*va_arg(ap, uint32*) = sp->jpegtables_length;
   2199 			*va_arg(ap, void**) = sp->jpegtables;
   2200 			break;
   2201 		case TIFFTAG_JPEGQUALITY:
   2202 			*va_arg(ap, int*) = sp->jpegquality;
   2203 			break;
   2204 		case TIFFTAG_JPEGCOLORMODE:
   2205 			*va_arg(ap, int*) = sp->jpegcolormode;
   2206 			break;
   2207 		case TIFFTAG_JPEGTABLESMODE:
   2208 			*va_arg(ap, int*) = sp->jpegtablesmode;
   2209 			break;
   2210 		default:
   2211 			return (*sp->vgetparent)(tif, tag, ap);
   2212 	}
   2213 	return (1);
   2214 }
   2215 
   2216 static void
   2217 JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
   2218 {
   2219 	JPEGState* sp = JState(tif);
   2220 
   2221 	assert(sp != NULL);
   2222 	(void) flags;
   2223 
   2224         if( sp != NULL ) {
   2225 		if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
   2226 			fprintf(fd, "  JPEG Tables: (%lu bytes)\n",
   2227 				(unsigned long) sp->jpegtables_length);
   2228 		if (sp->printdir)
   2229 			(*sp->printdir)(tif, fd, flags);
   2230 	}
   2231 }
   2232 
   2233 static uint32
   2234 JPEGDefaultStripSize(TIFF* tif, uint32 s)
   2235 {
   2236 	JPEGState* sp = JState(tif);
   2237 	TIFFDirectory *td = &tif->tif_dir;
   2238 
   2239 	s = (*sp->defsparent)(tif, s);
   2240 	if (s < td->td_imagelength)
   2241 		s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
   2242 	return (s);
   2243 }
   2244 
   2245 static void
   2246 JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
   2247 {
   2248 	JPEGState* sp = JState(tif);
   2249 	TIFFDirectory *td = &tif->tif_dir;
   2250 
   2251 	(*sp->deftparent)(tif, tw, th);
   2252 	*tw = TIFFroundup_32(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
   2253 	*th = TIFFroundup_32(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
   2254 }
   2255 
   2256 /*
   2257  * The JPEG library initialized used to be done in TIFFInitJPEG(), but
   2258  * now that we allow a TIFF file to be opened in update mode it is necessary
   2259  * to have some way of deciding whether compression or decompression is
   2260  * desired other than looking at tif->tif_mode.  We accomplish this by
   2261  * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
   2262  * If so, we assume decompression is desired.
   2263  *
   2264  * This is tricky, because TIFFInitJPEG() is called while the directory is
   2265  * being read, and generally speaking the BYTECOUNTS tag won't have been read
   2266  * at that point.  So we try to defer jpeg library initialization till we
   2267  * do have that tag ... basically any access that might require the compressor
   2268  * or decompressor that occurs after the reading of the directory.
   2269  *
   2270  * In an ideal world compressors or decompressors would be setup
   2271  * at the point where a single tile or strip was accessed (for read or write)
   2272  * so that stuff like update of missing tiles, or replacement of tiles could
   2273  * be done. However, we aren't trying to crack that nut just yet ...
   2274  *
   2275  * NFW, Feb 3rd, 2003.
   2276  */
   2277 
   2278 static int JPEGInitializeLibJPEG( TIFF * tif, int decompress )
   2279 {
   2280     JPEGState* sp = JState(tif);
   2281 
   2282     if(sp->cinfo_initialized)
   2283     {
   2284         if( !decompress && sp->cinfo.comm.is_decompressor )
   2285             TIFFjpeg_destroy( sp );
   2286         else if( decompress && !sp->cinfo.comm.is_decompressor )
   2287             TIFFjpeg_destroy( sp );
   2288         else
   2289             return 1;
   2290 
   2291         sp->cinfo_initialized = 0;
   2292     }
   2293 
   2294     /*
   2295      * Initialize libjpeg.
   2296      */
   2297     if ( decompress ) {
   2298         if (!TIFFjpeg_create_decompress(sp))
   2299             return (0);
   2300     } else {
   2301         if (!TIFFjpeg_create_compress(sp))
   2302             return (0);
   2303     }
   2304 
   2305     sp->cinfo_initialized = TRUE;
   2306 
   2307     return 1;
   2308 }
   2309 
   2310 int
   2311 TIFFInitJPEG(TIFF* tif, int scheme)
   2312 {
   2313 	JPEGState* sp;
   2314 
   2315 	assert(scheme == COMPRESSION_JPEG);
   2316 
   2317 	/*
   2318 	 * Merge codec-specific tag information.
   2319 	 */
   2320 	if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields))) {
   2321 		TIFFErrorExt(tif->tif_clientdata,
   2322 			     "TIFFInitJPEG",
   2323 			     "Merging JPEG codec-specific tags failed");
   2324 		return 0;
   2325 	}
   2326 
   2327 	/*
   2328 	 * Allocate state block so tag methods have storage to record values.
   2329 	 */
   2330 	tif->tif_data = (uint8*) _TIFFmalloc(sizeof (JPEGState));
   2331 
   2332 	if (tif->tif_data == NULL) {
   2333 		TIFFErrorExt(tif->tif_clientdata,
   2334 			     "TIFFInitJPEG", "No space for JPEG state block");
   2335 		return 0;
   2336 	}
   2337         _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
   2338 
   2339 	sp = JState(tif);
   2340 	sp->tif = tif;				/* back link */
   2341 
   2342 	/*
   2343 	 * Override parent get/set field methods.
   2344 	 */
   2345 	sp->vgetparent = tif->tif_tagmethods.vgetfield;
   2346 	tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
   2347 	sp->vsetparent = tif->tif_tagmethods.vsetfield;
   2348 	tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
   2349 	sp->printdir = tif->tif_tagmethods.printdir;
   2350 	tif->tif_tagmethods.printdir = JPEGPrintDir;   /* hook for codec tags */
   2351 
   2352 	/* Default values for codec-specific fields */
   2353 	sp->jpegtables = NULL;
   2354 	sp->jpegtables_length = 0;
   2355 	sp->jpegquality = 75;			/* Default IJG quality */
   2356 	sp->jpegcolormode = JPEGCOLORMODE_RAW;
   2357 	sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
   2358         sp->ycbcrsampling_fetched = 0;
   2359 
   2360 	/*
   2361 	 * Install codec methods.
   2362 	 */
   2363 	tif->tif_fixuptags = JPEGFixupTags;
   2364 	tif->tif_setupdecode = JPEGSetupDecode;
   2365 	tif->tif_predecode = JPEGPreDecode;
   2366 	tif->tif_decoderow = JPEGDecode;
   2367 	tif->tif_decodestrip = JPEGDecode;
   2368 	tif->tif_decodetile = JPEGDecode;
   2369 	tif->tif_setupencode = JPEGSetupEncode;
   2370 	tif->tif_preencode = JPEGPreEncode;
   2371 	tif->tif_postencode = JPEGPostEncode;
   2372 	tif->tif_encoderow = JPEGEncode;
   2373 	tif->tif_encodestrip = JPEGEncode;
   2374 	tif->tif_encodetile = JPEGEncode;
   2375 	tif->tif_cleanup = JPEGCleanup;
   2376 	sp->defsparent = tif->tif_defstripsize;
   2377 	tif->tif_defstripsize = JPEGDefaultStripSize;
   2378 	sp->deftparent = tif->tif_deftilesize;
   2379 	tif->tif_deftilesize = JPEGDefaultTileSize;
   2380 	tif->tif_flags |= TIFF_NOBITREV;	/* no bit reversal, please */
   2381 
   2382         sp->cinfo_initialized = FALSE;
   2383 
   2384 	/*
   2385         ** Create a JPEGTables field if no directory has yet been created.
   2386         ** We do this just to ensure that sufficient space is reserved for
   2387         ** the JPEGTables field.  It will be properly created the right
   2388         ** size later.
   2389         */
   2390         if( tif->tif_diroff == 0 )
   2391         {
   2392 #define SIZE_OF_JPEGTABLES 2000
   2393 /*
   2394 The following line assumes incorrectly that all JPEG-in-TIFF files will have
   2395 a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
   2396 when the JPEG data is placed with TIFFWriteRawStrip.  The field bit should be
   2397 set, anyway, later when actual JPEGTABLES header is generated, so removing it
   2398 here hopefully is harmless.
   2399             TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
   2400 */
   2401             sp->jpegtables_length = SIZE_OF_JPEGTABLES;
   2402             sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
   2403             if (sp->jpegtables)
   2404             {
   2405                 _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
   2406             }
   2407             else
   2408             {
   2409                 TIFFErrorExt(tif->tif_clientdata,
   2410 			     "TIFFInitJPEG",
   2411                              "Failed to allocate memory for JPEG tables");
   2412                 return 0;
   2413             }
   2414 #undef SIZE_OF_JPEGTABLES
   2415         }
   2416 
   2417 	return 1;
   2418 }
   2419 #endif /* JPEG_SUPPORT */
   2420 
   2421 /* vim: set ts=8 sts=8 sw=8 noet: */
   2422 
   2423 /*
   2424  * Local Variables:
   2425  * mode: c
   2426  * c-basic-offset: 8
   2427  * fill-column: 78
   2428  * End:
   2429  */
   2430