PageRenderTime 113ms CodeModel.GetById 4ms app.highlight 96ms RepoModel.GetById 1ms app.codeStats 0ms

/src/FreeImage/Source/LibTIFF/tif_jpeg.c

https://bitbucket.org/cabalistic/ogredeps/
C | 2078 lines | 1412 code | 219 blank | 447 comment | 300 complexity | 6eeffb4f0ce8ba5b5d9c37b7014cbbc4 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file