1 /* $Id: tif_jpeg.c,v 1.105 2012-02-01 01:51:00 fwarmerdam Exp $ */
4 * Copyright (c) 1994-1997 Sam Leffler
5 * Copyright (c) 1994-1997 Silicon Graphics, Inc.
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.
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.
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
27 #define WIN32_LEAN_AND_MEAN
36 * JPEG Compression support per TIFF Technical Note #2
37 * (*not* per the original TIFF 6.0 spec).
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/.
43 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
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 );
51 /* We undefine FAR to avoid conflict with JPEG definition */
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.
63 #if defined(__BORLANDC__) || defined(__MINGW32__)
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:
73 "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
76 For such users we wil fix the problem here. See install.doc file from
77 the JPEG library distribution for details.
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;
85 # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
92 * Do we want to do special processing suitable for when JSAMPLE is a
96 #if defined(JPEG_LIB_MK1)
97 # define JPEG_LIB_MK1_OR_12BIT 1
98 #elif BITS_IN_JSAMPLE == 12
99 # define JPEG_LIB_MK1_OR_12BIT 1
103 * We are using width_in_blocks which is supposed to be private to
104 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
105 * renamed this member to width_in_data_units. Since the header has
106 * also renamed a define, use that unique define name in order to
107 * detect the problem header and adjust to suit.
109 #if defined(D_MAX_DATA_UNITS_IN_MCU)
110 #define width_in_blocks width_in_data_units
114 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
115 * in place of plain setjmp. These macros will make it easier.
117 #define SETJMP(jbuf) setjmp(jbuf)
118 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
119 #define JMP_BUF jmp_buf
121 typedef struct jpeg_destination_mgr jpeg_destination_mgr;
122 typedef struct jpeg_source_mgr jpeg_source_mgr;
123 typedef struct jpeg_error_mgr jpeg_error_mgr;
126 * State block for each open TIFF file using
127 * libjpeg to do JPEG compression/decompression.
129 * libjpeg's visible state is either a jpeg_compress_struct
130 * or jpeg_decompress_struct depending on which way we
131 * are going. comm can be used to refer to the fields
132 * which are common to both.
134 * NB: cinfo is required to be the first member of JPEGState,
135 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
140 struct jpeg_compress_struct c;
141 struct jpeg_decompress_struct d;
142 struct jpeg_common_struct comm;
143 } cinfo; /* NB: must be first */
144 int cinfo_initialized;
146 jpeg_error_mgr err; /* libjpeg error manager */
147 JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
149 * The following two members could be a union, but
150 * they're small enough that it's not worth the effort.
152 jpeg_destination_mgr dest; /* data dest for compression */
153 jpeg_source_mgr src; /* data source for decompression */
155 TIFF* tif; /* back link needed by some code */
156 uint16 photometric; /* copy of PhotometricInterpretation */
157 uint16 h_sampling; /* luminance sampling factors */
159 tmsize_t bytesperline; /* decompressed bytes per scanline */
160 /* pointers to intermediate buffers when processing downsampled data */
161 JSAMPARRAY ds_buffer[MAX_COMPONENTS];
162 int scancount; /* number of "scanlines" accumulated */
165 TIFFVGetMethod vgetparent; /* super-class method */
166 TIFFVSetMethod vsetparent; /* super-class method */
167 TIFFPrintMethod printdir; /* super-class method */
168 TIFFStripMethod defsparent; /* super-class method */
169 TIFFTileMethod deftparent; /* super-class method */
170 /* pseudo-tag fields */
171 void* jpegtables; /* JPEGTables tag value, or NULL */
172 uint32 jpegtables_length; /* number of bytes in same */
173 int jpegquality; /* Compression quality level */
174 int jpegcolormode; /* Auto RGB<=>YCbCr convert? */
175 int jpegtablesmode; /* What to put in JPEGTables */
177 int ycbcrsampling_fetched;
180 #define JState(tif) ((JPEGState*)(tif)->tif_data)
182 static int JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
183 static int JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
184 static int JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
185 static int JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
186 static int JPEGInitializeLibJPEG(TIFF * tif, int decode );
187 static int DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
189 #define FIELD_JPEGTABLES (FIELD_CODEC+0)
191 static const TIFFField jpegFields[] = {
192 { TIFFTAG_JPEGTABLES, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_C32_UINT8, FIELD_JPEGTABLES, FALSE, TRUE, "JPEGTables", NULL },
193 { TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "", NULL },
194 { TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL },
195 { TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL }
199 * libjpeg interface layer.
201 * We use setjmp/longjmp to return control to libtiff
202 * when a fatal error is encountered within the JPEG
203 * library. We also direct libjpeg error and warning
204 * messages through the appropriate libtiff handlers.
208 * Error handling routines (these replace corresponding
209 * IJG routines from jerror.c). These are used for both
210 * compression and decompression.
213 TIFFjpeg_error_exit(j_common_ptr cinfo)
215 JPEGState *sp = (JPEGState *) cinfo; /* NB: cinfo assumed first */
216 char buffer[JMSG_LENGTH_MAX];
218 (*cinfo->err->format_message) (cinfo, buffer);
219 TIFFErrorExt(sp->tif->tif_clientdata, "JPEGLib", "%s", buffer); /* display the error message */
220 jpeg_abort(cinfo); /* clean up libjpeg state */
221 LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
225 * This routine is invoked only for warning messages,
226 * since error_exit does its own thing and trace_level
230 TIFFjpeg_output_message(j_common_ptr cinfo)
232 char buffer[JMSG_LENGTH_MAX];
234 (*cinfo->err->format_message) (cinfo, buffer);
235 TIFFWarningExt(((JPEGState *) cinfo)->tif->tif_clientdata, "JPEGLib", "%s", buffer);
239 * Interface routines. This layer of routines exists
240 * primarily to limit side-effects from using setjmp.
241 * Also, normal/error returns are converted into return
242 * values per libtiff practice.
244 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
245 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
248 TIFFjpeg_create_compress(JPEGState* sp)
250 /* initialize JPEG error handling */
251 sp->cinfo.c.err = jpeg_std_error(&sp->err);
252 sp->err.error_exit = TIFFjpeg_error_exit;
253 sp->err.output_message = TIFFjpeg_output_message;
255 return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
259 TIFFjpeg_create_decompress(JPEGState* sp)
261 /* initialize JPEG error handling */
262 sp->cinfo.d.err = jpeg_std_error(&sp->err);
263 sp->err.error_exit = TIFFjpeg_error_exit;
264 sp->err.output_message = TIFFjpeg_output_message;
266 return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
270 TIFFjpeg_set_defaults(JPEGState* sp)
272 return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
276 TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
278 return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
282 TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
285 jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
289 TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
291 return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
295 TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
298 jpeg_start_compress(&sp->cinfo.c, write_all_tables));
302 TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
304 return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
305 scanlines, (JDIMENSION) num_lines));
309 TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
311 return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
312 data, (JDIMENSION) num_lines));
316 TIFFjpeg_finish_compress(JPEGState* sp)
318 return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
322 TIFFjpeg_write_tables(JPEGState* sp)
324 return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
328 TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
330 return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
334 TIFFjpeg_start_decompress(JPEGState* sp)
336 return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
340 TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
342 return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
343 scanlines, (JDIMENSION) max_lines));
347 TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
349 return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
350 data, (JDIMENSION) max_lines));
354 TIFFjpeg_finish_decompress(JPEGState* sp)
356 return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
360 TIFFjpeg_abort(JPEGState* sp)
362 return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
366 TIFFjpeg_destroy(JPEGState* sp)
368 return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
372 TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
373 JDIMENSION samplesperrow, JDIMENSION numrows)
375 return CALLJPEG(sp, (JSAMPARRAY) NULL,
376 (*sp->cinfo.comm.mem->alloc_sarray)
377 (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
381 * JPEG library destination data manager.
382 * These routines direct compressed data from libjpeg into the
383 * libtiff output buffer.
387 std_init_destination(j_compress_ptr cinfo)
389 JPEGState* sp = (JPEGState*) cinfo;
392 sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
393 sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
397 std_empty_output_buffer(j_compress_ptr cinfo)
399 JPEGState* sp = (JPEGState*) cinfo;
402 /* the entire buffer has been filled */
403 tif->tif_rawcc = tif->tif_rawdatasize;
407 * The Intel IPP performance library does not necessarily fill up
408 * the whole output buffer on each pass, so only dump out the parts
409 * that have been filled.
410 * http://trac.osgeo.org/gdal/wiki/JpegIPP
412 if ( sp->dest.free_in_buffer >= 0 ) {
413 tif->tif_rawcc = tif->tif_rawdatasize - sp->dest.free_in_buffer;
418 sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
419 sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
425 std_term_destination(j_compress_ptr cinfo)
427 JPEGState* sp = (JPEGState*) cinfo;
430 tif->tif_rawcp = (uint8*) sp->dest.next_output_byte;
432 tif->tif_rawdatasize - (tmsize_t) sp->dest.free_in_buffer;
433 /* NB: libtiff does the final buffer flush */
437 TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
440 sp->cinfo.c.dest = &sp->dest;
441 sp->dest.init_destination = std_init_destination;
442 sp->dest.empty_output_buffer = std_empty_output_buffer;
443 sp->dest.term_destination = std_term_destination;
447 * Alternate destination manager for outputting to JPEGTables field.
451 tables_init_destination(j_compress_ptr cinfo)
453 JPEGState* sp = (JPEGState*) cinfo;
455 /* while building, jpegtables_length is allocated buffer size */
456 sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
457 sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
461 tables_empty_output_buffer(j_compress_ptr cinfo)
463 JPEGState* sp = (JPEGState*) cinfo;
466 /* the entire buffer has been filled; enlarge it by 1000 bytes */
467 newbuf = _TIFFrealloc((void*) sp->jpegtables,
468 (tmsize_t) (sp->jpegtables_length + 1000));
470 ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
471 sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
472 sp->dest.free_in_buffer = (size_t) 1000;
473 sp->jpegtables = newbuf;
474 sp->jpegtables_length += 1000;
479 tables_term_destination(j_compress_ptr cinfo)
481 JPEGState* sp = (JPEGState*) cinfo;
483 /* set tables length to number of bytes actually emitted */
484 sp->jpegtables_length -= (uint32) sp->dest.free_in_buffer;
488 TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
492 * Allocate a working buffer for building tables.
493 * Initial size is 1000 bytes, which is usually adequate.
496 _TIFFfree(sp->jpegtables);
497 sp->jpegtables_length = 1000;
498 sp->jpegtables = (void*) _TIFFmalloc((tmsize_t) sp->jpegtables_length);
499 if (sp->jpegtables == NULL) {
500 sp->jpegtables_length = 0;
501 TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
504 sp->cinfo.c.dest = &sp->dest;
505 sp->dest.init_destination = tables_init_destination;
506 sp->dest.empty_output_buffer = tables_empty_output_buffer;
507 sp->dest.term_destination = tables_term_destination;
512 * JPEG library source data manager.
513 * These routines supply compressed data to libjpeg.
517 std_init_source(j_decompress_ptr cinfo)
519 JPEGState* sp = (JPEGState*) cinfo;
522 sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
523 sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
527 std_fill_input_buffer(j_decompress_ptr cinfo)
529 JPEGState* sp = (JPEGState* ) cinfo;
530 static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
534 * The Intel IPP performance library does not necessarily read the whole
535 * input buffer in one pass, so it is possible to get here with data
538 * We just return without doing anything, until the entire buffer has
540 * http://trac.osgeo.org/gdal/wiki/JpegIPP
542 if( sp->src.bytes_in_buffer > 0 ) {
548 * Normally the whole strip/tile is read and so we don't need to do
549 * a fill. In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
550 * all the data, but the rawdata is refreshed between scanlines and
551 * we push this into the io machinery in JPEGDecode().
552 * http://trac.osgeo.org/gdal/ticket/3894
555 WARNMS(cinfo, JWRN_JPEG_EOF);
556 /* insert a fake EOI marker */
557 sp->src.next_input_byte = dummy_EOI;
558 sp->src.bytes_in_buffer = 2;
563 std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
565 JPEGState* sp = (JPEGState*) cinfo;
568 if ((size_t)num_bytes > sp->src.bytes_in_buffer) {
569 /* oops, buffer overrun */
570 (void) std_fill_input_buffer(cinfo);
572 sp->src.next_input_byte += (size_t) num_bytes;
573 sp->src.bytes_in_buffer -= (size_t) num_bytes;
579 std_term_source(j_decompress_ptr cinfo)
581 /* No work necessary here */
586 TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
589 sp->cinfo.d.src = &sp->src;
590 sp->src.init_source = std_init_source;
591 sp->src.fill_input_buffer = std_fill_input_buffer;
592 sp->src.skip_input_data = std_skip_input_data;
593 sp->src.resync_to_restart = jpeg_resync_to_restart;
594 sp->src.term_source = std_term_source;
595 sp->src.bytes_in_buffer = 0; /* for safety */
596 sp->src.next_input_byte = NULL;
600 * Alternate source manager for reading from JPEGTables.
601 * We can share all the code except for the init routine.
605 tables_init_source(j_decompress_ptr cinfo)
607 JPEGState* sp = (JPEGState*) cinfo;
609 sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
610 sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
614 TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
616 TIFFjpeg_data_src(sp, tif);
617 sp->src.init_source = tables_init_source;
621 * Allocate downsampled-data buffers needed for downsampled I/O.
622 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
623 * We use libjpeg's allocator so that buffers will be released automatically
624 * when done with strip/tile.
625 * This is also a handy place to compute samplesperclump, bytesperline.
628 alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
631 JPEGState* sp = JState(tif);
633 jpeg_component_info* compptr;
635 int samples_per_clump = 0;
637 for (ci = 0, compptr = comp_info; ci < num_components;
639 samples_per_clump += compptr->h_samp_factor *
640 compptr->v_samp_factor;
641 buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
642 compptr->width_in_blocks * DCTSIZE,
643 (JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
646 sp->ds_buffer[ci] = buf;
648 sp->samplesperclump = samples_per_clump;
657 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
659 #define JPEG_MARKER_SOF0 0xC0
660 #define JPEG_MARKER_SOF1 0xC1
661 #define JPEG_MARKER_SOF3 0xC3
662 #define JPEG_MARKER_DHT 0xC4
663 #define JPEG_MARKER_SOI 0xD8
664 #define JPEG_MARKER_SOS 0xDA
665 #define JPEG_MARKER_DQT 0xDB
666 #define JPEG_MARKER_DRI 0xDD
667 #define JPEG_MARKER_APP0 0xE0
668 #define JPEG_MARKER_COM 0xFE
669 struct JPEGFixupTagsSubsamplingData
674 uint8* buffercurrentbyte;
675 uint32 bufferbytesleft;
677 uint64 filebytesleft;
678 uint8 filepositioned;
680 static void JPEGFixupTagsSubsampling(TIFF* tif);
681 static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data);
682 static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result);
683 static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result);
684 static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength);
689 JPEGFixupTags(TIFF* tif)
691 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
692 if ((tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR)&&
693 (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&&
694 (tif->tif_dir.td_samplesperpixel==3))
695 JPEGFixupTagsSubsampling(tif);
701 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
704 JPEGFixupTagsSubsampling(TIFF* tif)
707 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
708 * the TIFF tags, but still use non-default (2,2) values within the jpeg
709 * data stream itself. In order for TIFF applications to work properly
710 * - for instance to get the strip buffer size right - it is imperative
711 * that the subsampling be available before we start reading the image
712 * data normally. This function will attempt to analyze the first strip in
713 * order to get the sampling values from the jpeg data stream.
715 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
716 * discovered sampling does not match the default sampling (2,2) or whatever
717 * was actually in the tiff tags.
719 * See the bug in bugzilla for details:
721 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
723 * Frank Warmerdam, July 2002
724 * Joris Van Damme, May 2007
726 static const char module[] = "JPEGFixupTagsSubsampling";
727 struct JPEGFixupTagsSubsamplingData m;
729 _TIFFFillStriles( tif );
731 if( tif->tif_dir.td_stripbytecount == NULL
732 || tif->tif_dir.td_stripbytecount[0] == 0 )
734 /* Do not even try to check if the first strip/tile does not
735 yet exist, as occurs when GDAL has created a new NULL file
742 m.buffer=_TIFFmalloc(m.buffersize);
745 TIFFWarningExt(tif->tif_clientdata,module,
746 "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
749 m.buffercurrentbyte=NULL;
751 m.fileoffset=tif->tif_dir.td_stripoffset[0];
753 m.filebytesleft=tif->tif_dir.td_stripbytecount[0];
754 if (!JPEGFixupTagsSubsamplingSec(&m))
755 TIFFWarningExt(tif->tif_clientdata,module,
756 "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
761 JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
763 static const char module[] = "JPEGFixupTagsSubsamplingSec";
769 if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
776 if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
783 case JPEG_MARKER_SOI:
784 /* this type of marker has no data and should be skipped */
786 case JPEG_MARKER_COM:
787 case JPEG_MARKER_APP0:
788 case JPEG_MARKER_APP0+1:
789 case JPEG_MARKER_APP0+2:
790 case JPEG_MARKER_APP0+3:
791 case JPEG_MARKER_APP0+4:
792 case JPEG_MARKER_APP0+5:
793 case JPEG_MARKER_APP0+6:
794 case JPEG_MARKER_APP0+7:
795 case JPEG_MARKER_APP0+8:
796 case JPEG_MARKER_APP0+9:
797 case JPEG_MARKER_APP0+10:
798 case JPEG_MARKER_APP0+11:
799 case JPEG_MARKER_APP0+12:
800 case JPEG_MARKER_APP0+13:
801 case JPEG_MARKER_APP0+14:
802 case JPEG_MARKER_APP0+15:
803 case JPEG_MARKER_DQT:
804 case JPEG_MARKER_SOS:
805 case JPEG_MARKER_DHT:
806 case JPEG_MARKER_DRI:
807 /* this type of marker has data, but it has no use to us and should be skipped */
810 if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
816 JPEGFixupTagsSubsamplingSkip(data,n);
819 case JPEG_MARKER_SOF0:
820 case JPEG_MARKER_SOF1:
821 /* this marker contains the subsampling factors we're scanning for */
827 if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
829 if (n!=8+data->tif->tif_dir.td_samplesperpixel*3)
831 JPEGFixupTagsSubsamplingSkip(data,7);
832 if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
836 JPEGFixupTagsSubsamplingSkip(data,1);
837 for (o=1; o<data->tif->tif_dir.td_samplesperpixel; o++)
839 JPEGFixupTagsSubsamplingSkip(data,1);
840 if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
844 TIFFWarningExt(data->tif->tif_clientdata,module,
845 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
848 JPEGFixupTagsSubsamplingSkip(data,1);
850 if (((ph!=1)&&(ph!=2)&&(ph!=4))||((pv!=1)&&(pv!=2)&&(pv!=4)))
852 TIFFWarningExt(data->tif->tif_clientdata,module,
853 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
856 if ((ph!=data->tif->tif_dir.td_ycbcrsubsampling[0])||(pv!=data->tif->tif_dir.td_ycbcrsubsampling[1]))
858 TIFFWarningExt(data->tif->tif_clientdata,module,
859 "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
860 (int)data->tif->tif_dir.td_ycbcrsubsampling[0],
861 (int)data->tif->tif_dir.td_ycbcrsubsampling[1],
863 data->tif->tif_dir.td_ycbcrsubsampling[0]=ph;
864 data->tif->tif_dir.td_ycbcrsubsampling[1]=pv;
875 JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result)
877 if (data->bufferbytesleft==0)
880 if (data->filebytesleft==0)
882 if (!data->filepositioned)
884 TIFFSeekFile(data->tif,data->fileoffset,SEEK_SET);
885 data->filepositioned=1;
888 if ((uint64)m>data->filebytesleft)
889 m=(uint32)data->filebytesleft;
890 assert(m<0x80000000UL);
891 if (TIFFReadFile(data->tif,data->buffer,(tmsize_t)m)!=(tmsize_t)m)
893 data->buffercurrentbyte=data->buffer;
894 data->bufferbytesleft=m;
896 data->filebytesleft-=m;
898 *result=*data->buffercurrentbyte;
899 data->buffercurrentbyte++;
900 data->bufferbytesleft--;
905 JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result)
909 if (!JPEGFixupTagsSubsamplingReadByte(data,&ma))
911 if (!JPEGFixupTagsSubsamplingReadByte(data,&mb))
918 JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength)
920 if ((uint32)skiplength<=data->bufferbytesleft)
922 data->buffercurrentbyte+=skiplength;
923 data->bufferbytesleft-=skiplength;
928 m=skiplength-data->bufferbytesleft;
929 if (m<=data->filebytesleft)
931 data->bufferbytesleft=0;
933 data->filebytesleft-=m;
934 data->filepositioned=0;
938 data->bufferbytesleft=0;
939 data->filebytesleft=0;
948 JPEGSetupDecode(TIFF* tif)
950 JPEGState* sp = JState(tif);
951 TIFFDirectory *td = &tif->tif_dir;
953 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
954 if( tif->tif_dir.td_bitspersample == 12 )
955 return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 0 );
958 JPEGInitializeLibJPEG( tif, TRUE );
961 assert(sp->cinfo.comm.is_decompressor);
963 /* Read JPEGTables if it is present */
964 if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
965 TIFFjpeg_tables_src(sp, tif);
966 if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
967 TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
972 /* Grab parameters that are same for all strips/tiles */
973 sp->photometric = td->td_photometric;
974 switch (sp->photometric) {
975 case PHOTOMETRIC_YCBCR:
976 sp->h_sampling = td->td_ycbcrsubsampling[0];
977 sp->v_sampling = td->td_ycbcrsubsampling[1];
980 /* TIFF 6.0 forbids subsampling of all other color spaces */
986 /* Set up for reading normal data */
987 TIFFjpeg_data_src(sp, tif);
988 tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
993 * Set up for decoding a strip or tile.
996 JPEGPreDecode(TIFF* tif, uint16 s)
998 JPEGState *sp = JState(tif);
999 TIFFDirectory *td = &tif->tif_dir;
1000 static const char module[] = "JPEGPreDecode";
1001 uint32 segment_width, segment_height;
1002 int downsampled_output;
1007 if (sp->cinfo.comm.is_decompressor == 0)
1009 tif->tif_setupdecode( tif );
1012 assert(sp->cinfo.comm.is_decompressor);
1014 * Reset decoder state from any previous strip/tile,
1015 * in case application didn't read the whole strip.
1017 if (!TIFFjpeg_abort(sp))
1020 * Read the header for this strip/tile.
1023 if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
1026 tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
1027 tif->tif_rawcc = sp->src.bytes_in_buffer;
1030 * Check image parameters and set decompression parameters.
1032 segment_width = td->td_imagewidth;
1033 segment_height = td->td_imagelength - tif->tif_row;
1035 segment_width = td->td_tilewidth;
1036 segment_height = td->td_tilelength;
1037 sp->bytesperline = TIFFTileRowSize(tif);
1039 if (segment_height > td->td_rowsperstrip)
1040 segment_height = td->td_rowsperstrip;
1041 sp->bytesperline = TIFFScanlineSize(tif);
1043 if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1045 * For PC 2, scale down the expected strip/tile size
1046 * to match a downsampled component
1048 segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
1049 segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1051 if (sp->cinfo.d.image_width < segment_width ||
1052 sp->cinfo.d.image_height < segment_height) {
1053 TIFFWarningExt(tif->tif_clientdata, module,
1054 "Improper JPEG strip/tile size, "
1055 "expected %dx%d, got %dx%d",
1056 segment_width, segment_height,
1057 sp->cinfo.d.image_width,
1058 sp->cinfo.d.image_height);
1060 if (sp->cinfo.d.image_width > segment_width ||
1061 sp->cinfo.d.image_height > segment_height) {
1063 * This case could be dangerous, if the strip or tile size has
1064 * been reported as less than the amount of data jpeg will
1065 * return, some potential security issues arise. Catch this
1066 * case and error out.
1068 TIFFErrorExt(tif->tif_clientdata, module,
1069 "JPEG strip/tile size exceeds expected dimensions,"
1070 " expected %dx%d, got %dx%d",
1071 segment_width, segment_height,
1072 sp->cinfo.d.image_width, sp->cinfo.d.image_height);
1075 if (sp->cinfo.d.num_components !=
1076 (td->td_planarconfig == PLANARCONFIG_CONTIG ?
1077 td->td_samplesperpixel : 1)) {
1078 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG component count");
1082 if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
1083 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
1086 sp->cinfo.d.data_precision = td->td_bitspersample;
1087 sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
1089 if (sp->cinfo.d.data_precision != td->td_bitspersample) {
1090 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
1094 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1095 /* Component 0 should have expected sampling factors */
1096 if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
1097 sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
1098 TIFFWarningExt(tif->tif_clientdata, module,
1099 "Improper JPEG sampling factors %d,%d\n"
1100 "Apparently should be %d,%d.",
1101 sp->cinfo.d.comp_info[0].h_samp_factor,
1102 sp->cinfo.d.comp_info[0].v_samp_factor,
1103 sp->h_sampling, sp->v_sampling);
1106 * There are potential security issues here
1107 * for decoders that have already allocated
1108 * buffers based on the expected sampling
1109 * factors. Lets check the sampling factors
1110 * dont exceed what we were expecting.
1112 if (sp->cinfo.d.comp_info[0].h_samp_factor
1114 || sp->cinfo.d.comp_info[0].v_samp_factor
1116 TIFFErrorExt(tif->tif_clientdata,
1118 "Cannot honour JPEG sampling factors"
1119 " that exceed those specified.");
1124 * XXX: Files written by the Intergraph software
1125 * has different sampling factors stored in the
1126 * TIFF tags and in the JPEG structures. We will
1127 * try to deduce Intergraph files by the presense
1130 if (!TIFFFindField(tif, 33918, TIFF_ANY)) {
1131 TIFFWarningExt(tif->tif_clientdata, module,
1132 "Decompressor will try reading with "
1134 sp->cinfo.d.comp_info[0].h_samp_factor,
1135 sp->cinfo.d.comp_info[0].v_samp_factor);
1137 sp->h_sampling = (uint16)
1138 sp->cinfo.d.comp_info[0].h_samp_factor;
1139 sp->v_sampling = (uint16)
1140 sp->cinfo.d.comp_info[0].v_samp_factor;
1143 /* Rest should have sampling factors 1,1 */
1144 for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
1145 if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
1146 sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
1147 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
1152 /* PC 2's single component should have sampling factors 1,1 */
1153 if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
1154 sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
1155 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
1159 downsampled_output = FALSE;
1160 if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1161 sp->photometric == PHOTOMETRIC_YCBCR &&
1162 sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1163 /* Convert YCbCr to RGB */
1164 sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
1165 sp->cinfo.d.out_color_space = JCS_RGB;
1167 /* Suppress colorspace handling */
1168 sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
1169 sp->cinfo.d.out_color_space = JCS_UNKNOWN;
1170 if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1171 (sp->h_sampling != 1 || sp->v_sampling != 1))
1172 downsampled_output = TRUE;
1173 /* XXX what about up-sampling? */
1175 if (downsampled_output) {
1176 /* Need to use raw-data interface to libjpeg */
1177 sp->cinfo.d.raw_data_out = TRUE;
1178 tif->tif_decoderow = DecodeRowError;
1179 tif->tif_decodestrip = JPEGDecodeRaw;
1180 tif->tif_decodetile = JPEGDecodeRaw;
1182 /* Use normal interface to libjpeg */
1183 sp->cinfo.d.raw_data_out = FALSE;
1184 tif->tif_decoderow = JPEGDecode;
1185 tif->tif_decodestrip = JPEGDecode;
1186 tif->tif_decodetile = JPEGDecode;
1188 /* Start JPEG decompressor */
1189 if (!TIFFjpeg_start_decompress(sp))
1191 /* Allocate downsampled-data buffers if needed */
1192 if (downsampled_output) {
1193 if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
1194 sp->cinfo.d.num_components))
1196 sp->scancount = DCTSIZE; /* mark buffer empty */
1202 * Decode a chunk of pixels.
1203 * "Standard" case: returned data is not downsampled.
1205 /*ARGSUSED*/ static int
1206 JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1208 JPEGState *sp = JState(tif);
1213 ** Update available information, buffer may have been refilled
1214 ** between decode requests
1216 sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
1217 sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
1219 if( sp->bytesperline == 0 )
1222 nrows = cc / sp->bytesperline;
1223 if (cc % sp->bytesperline)
1224 TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
1226 if( nrows > (tmsize_t) sp->cinfo.d.image_height )
1227 nrows = sp->cinfo.d.image_height;
1229 /* data is expected to be read in multiples of a scanline */
1232 JSAMPROW line_work_buf = NULL;
1235 * For 6B, only use temporary buffer for 12 bit imagery.
1236 * For Mk1 always use it.
1238 #if !defined(JPEG_LIB_MK1)
1239 if( sp->cinfo.d.data_precision == 12 )
1242 line_work_buf = (JSAMPROW)
1243 _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
1244 * sp->cinfo.d.num_components );
1248 if( line_work_buf != NULL )
1251 * In the MK1 case, we aways read into a 16bit buffer, and then
1252 * pack down to 12bit or 8bit. In 6B case we only read into 16
1253 * bit buffer for 12bit data, which we need to repack.
1255 if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
1258 if( sp->cinfo.d.data_precision == 12 )
1260 int value_pairs = (sp->cinfo.d.output_width
1261 * sp->cinfo.d.num_components) / 2;
1264 for( iPair = 0; iPair < value_pairs; iPair++ )
1266 unsigned char *out_ptr =
1267 ((unsigned char *) buf) + iPair * 3;
1268 JSAMPLE *in_ptr = line_work_buf + iPair * 2;
1270 out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
1271 out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
1272 | ((in_ptr[1] & 0xf00) >> 8);
1273 out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
1276 else if( sp->cinfo.d.data_precision == 8 )
1278 int value_count = (sp->cinfo.d.output_width
1279 * sp->cinfo.d.num_components);
1282 for( iValue = 0; iValue < value_count; iValue++ )
1284 ((unsigned char *) buf)[iValue] =
1285 line_work_buf[iValue] & 0xff;
1292 * In the libjpeg6b 8bit case. We read directly into the
1295 JSAMPROW bufptr = (JSAMPROW)buf;
1297 if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
1302 buf += sp->bytesperline;
1303 cc -= sp->bytesperline;
1304 } while (--nrows > 0);
1306 if( line_work_buf != NULL )
1307 _TIFFfree( line_work_buf );
1310 /* Update information on consumed data */
1311 tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
1312 tif->tif_rawcc = sp->src.bytes_in_buffer;
1314 /* Close down the decompressor if we've finished the strip or tile. */
1315 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1316 || TIFFjpeg_finish_decompress(sp);
1319 /*ARGSUSED*/ static int
1320 DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1327 TIFFErrorExt(tif->tif_clientdata, "TIFFReadScanline",
1328 "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
1333 * Decode a chunk of pixels.
1334 * Returned data is downsampled per sampling factors.
1336 /*ARGSUSED*/ static int
1337 JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1339 JPEGState *sp = JState(tif);
1343 /* data is expected to be read in multiples of a scanline */
1344 if ( (nrows = sp->cinfo.d.image_height) ) {
1346 /* Cb,Cr both have sampling factors 1, so this is correct */
1347 JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
1348 int samples_per_clump = sp->samplesperclump;
1350 #if defined(JPEG_LIB_MK1_OR_12BIT)
1351 unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
1352 sp->cinfo.d.output_width *
1353 sp->cinfo.d.num_components);
1355 TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1362 jpeg_component_info *compptr;
1363 int ci, clumpoffset;
1365 if( cc < sp->bytesperline * sp->v_sampling ) {
1366 TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1367 "application buffer not large enough for all data.");
1371 /* Reload downsampled-data buffer if needed */
1372 if (sp->scancount >= DCTSIZE) {
1373 int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
1374 if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
1379 * Fastest way to unseparate data is to make one pass
1380 * over the scanline for each row of each component.
1382 clumpoffset = 0; /* first sample in clump */
1383 for (ci = 0, compptr = sp->cinfo.d.comp_info;
1384 ci < sp->cinfo.d.num_components;
1386 int hsamp = compptr->h_samp_factor;
1387 int vsamp = compptr->v_samp_factor;
1390 for (ypos = 0; ypos < vsamp; ypos++) {
1391 JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1392 #if defined(JPEG_LIB_MK1_OR_12BIT)
1393 JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
1395 JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
1400 /* fast path for at least Cb and Cr */
1401 for (nclump = clumps_per_line; nclump-- > 0; ) {
1402 outptr[0] = *inptr++;
1403 outptr += samples_per_clump;
1409 for (nclump = clumps_per_line; nclump-- > 0; ) {
1410 for (xpos = 0; xpos < hsamp; xpos++)
1411 outptr[xpos] = *inptr++;
1412 outptr += samples_per_clump;
1415 clumpoffset += hsamp;
1419 #if defined(JPEG_LIB_MK1_OR_12BIT)
1421 if (sp->cinfo.d.data_precision == 8)
1424 int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
1425 for (i=0; i<len; i++)
1427 ((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
1432 int value_pairs = (sp->cinfo.d.output_width
1433 * sp->cinfo.d.num_components) / 2;
1435 for( iPair = 0; iPair < value_pairs; iPair++ )
1437 unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
1438 JSAMPLE *in_ptr = (JSAMPLE *) (tmpbuf + iPair * 2);
1439 out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
1440 out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
1441 | ((in_ptr[1] & 0xf00) >> 8);
1442 out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
1449 tif->tif_row += sp->v_sampling;
1451 buf += clumps_per_line*samples_per_clump;
1452 cc -= clumps_per_line*samples_per_clump;
1454 buf += sp->bytesperline * sp->v_sampling;
1455 cc -= sp->bytesperline * sp->v_sampling;
1457 nrows -= sp->v_sampling;
1458 } while (nrows > 0);
1460 #if defined(JPEG_LIB_MK1_OR_12BIT)
1466 /* Close down the decompressor if done. */
1467 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1468 || TIFFjpeg_finish_decompress(sp);
1477 unsuppress_quant_table (JPEGState* sp, int tblno)
1481 if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1482 qtbl->sent_table = FALSE;
1486 unsuppress_huff_table (JPEGState* sp, int tblno)
1490 if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1491 htbl->sent_table = FALSE;
1492 if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1493 htbl->sent_table = FALSE;
1497 prepare_JPEGTables(TIFF* tif)
1499 JPEGState* sp = JState(tif);
1501 /* Initialize quant tables for current quality setting */
1502 if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1504 /* Mark only the tables we want for output */
1505 /* NB: chrominance tables are currently used only with YCbCr */
1506 if (!TIFFjpeg_suppress_tables(sp, TRUE))
1508 if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
1509 unsuppress_quant_table(sp, 0);
1510 if (sp->photometric == PHOTOMETRIC_YCBCR)
1511 unsuppress_quant_table(sp, 1);
1513 if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
1514 unsuppress_huff_table(sp, 0);
1515 if (sp->photometric == PHOTOMETRIC_YCBCR)
1516 unsuppress_huff_table(sp, 1);
1518 /* Direct libjpeg output into jpegtables */
1519 if (!TIFFjpeg_tables_dest(sp, tif))
1521 /* Emit tables-only datastream */
1522 if (!TIFFjpeg_write_tables(sp))
1529 JPEGSetupEncode(TIFF* tif)
1531 JPEGState* sp = JState(tif);
1532 TIFFDirectory *td = &tif->tif_dir;
1533 static const char module[] = "JPEGSetupEncode";
1535 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
1536 if( tif->tif_dir.td_bitspersample == 12 )
1537 return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 1 );
1540 JPEGInitializeLibJPEG( tif, FALSE );
1543 assert(!sp->cinfo.comm.is_decompressor);
1546 * Initialize all JPEG parameters to default values.
1547 * Note that jpeg_set_defaults needs legal values for
1548 * in_color_space and input_components.
1550 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1551 sp->cinfo.c.input_components = 1;
1552 if (!TIFFjpeg_set_defaults(sp))
1554 /* Set per-file parameters */
1555 sp->photometric = td->td_photometric;
1556 switch (sp->photometric) {
1557 case PHOTOMETRIC_YCBCR:
1558 sp->h_sampling = td->td_ycbcrsubsampling[0];
1559 sp->v_sampling = td->td_ycbcrsubsampling[1];
1561 * A ReferenceBlackWhite field *must* be present since the
1562 * default value is inappropriate for YCbCr. Fill in the
1563 * proper value if application didn't set it.
1567 if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1570 long top = 1L << td->td_bitspersample;
1572 refbw[1] = (float)(top-1L);
1573 refbw[2] = (float)(top>>1);
1574 refbw[3] = refbw[1];
1575 refbw[4] = refbw[2];
1576 refbw[5] = refbw[1];
1577 TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1582 case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */
1583 case PHOTOMETRIC_MASK:
1584 TIFFErrorExt(tif->tif_clientdata, module,
1585 "PhotometricInterpretation %d not allowed for JPEG",
1586 (int) sp->photometric);
1589 /* TIFF 6.0 forbids subsampling of all other color spaces */
1595 /* Verify miscellaneous parameters */
1598 * This would need work if libtiff ever supports different
1599 * depths for different components, or if libjpeg ever supports
1600 * run-time selection of depth. Neither is imminent.
1603 /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1604 if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
1606 if (td->td_bitspersample != BITS_IN_JSAMPLE )
1609 TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
1610 (int) td->td_bitspersample);
1613 sp->cinfo.c.data_precision = td->td_bitspersample;
1615 sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
1618 if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
1619 TIFFErrorExt(tif->tif_clientdata, module,
1620 "JPEG tile height must be multiple of %d",
1621 sp->v_sampling * DCTSIZE);
1624 if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
1625 TIFFErrorExt(tif->tif_clientdata, module,
1626 "JPEG tile width must be multiple of %d",
1627 sp->h_sampling * DCTSIZE);
1631 if (td->td_rowsperstrip < td->td_imagelength &&
1632 (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
1633 TIFFErrorExt(tif->tif_clientdata, module,
1634 "RowsPerStrip must be multiple of %d for JPEG",
1635 sp->v_sampling * DCTSIZE);
1640 /* Create a JPEGTables field if appropriate */
1641 if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
1642 if( sp->jpegtables == NULL
1643 || memcmp(sp->jpegtables,"\0\0\0\0\0\0\0\0\0",8) == 0 )
1645 if (!prepare_JPEGTables(tif))
1647 /* Mark the field present */
1648 /* Can't use TIFFSetField since BEENWRITING is already set! */
1649 tif->tif_flags |= TIFF_DIRTYDIRECT;
1650 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1653 /* We do not support application-supplied JPEGTables, */
1654 /* so mark the field not present */
1655 TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
1658 /* Direct libjpeg output to libtiff's output buffer */
1659 TIFFjpeg_data_dest(sp, tif);
1665 * Set encoding state at the start of a strip or tile.
1668 JPEGPreEncode(TIFF* tif, uint16 s)
1670 JPEGState *sp = JState(tif);
1671 TIFFDirectory *td = &tif->tif_dir;
1672 static const char module[] = "JPEGPreEncode";
1673 uint32 segment_width, segment_height;
1674 int downsampled_input;
1678 if (sp->cinfo.comm.is_decompressor == 1)
1680 tif->tif_setupencode( tif );
1683 assert(!sp->cinfo.comm.is_decompressor);
1685 * Set encoding parameters for this strip/tile.
1688 segment_width = td->td_tilewidth;
1689 segment_height = td->td_tilelength;
1690 sp->bytesperline = TIFFTileRowSize(tif);
1692 segment_width = td->td_imagewidth;
1693 segment_height = td->td_imagelength - tif->tif_row;
1694 if (segment_height > td->td_rowsperstrip)
1695 segment_height = td->td_rowsperstrip;
1696 sp->bytesperline = TIFFScanlineSize(tif);
1698 if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1699 /* for PC 2, scale down the strip/tile size
1700 * to match a downsampled component
1702 segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
1703 segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1705 if (segment_width > 65535 || segment_height > 65535) {
1706 TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
1709 sp->cinfo.c.image_width = segment_width;
1710 sp->cinfo.c.image_height = segment_height;
1711 downsampled_input = FALSE;
1712 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1713 sp->cinfo.c.input_components = td->td_samplesperpixel;
1714 if (sp->photometric == PHOTOMETRIC_YCBCR) {
1715 if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1716 sp->cinfo.c.in_color_space = JCS_RGB;
1718 sp->cinfo.c.in_color_space = JCS_YCbCr;
1719 if (sp->h_sampling != 1 || sp->v_sampling != 1)
1720 downsampled_input = TRUE;
1722 if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
1725 * Set Y sampling factors;
1726 * we assume jpeg_set_colorspace() set the rest to 1
1728 sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
1729 sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
1731 if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
1732 sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
1733 else if (td->td_photometric == PHOTOMETRIC_RGB)
1734 sp->cinfo.c.in_color_space = JCS_RGB;
1735 else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
1736 sp->cinfo.c.in_color_space = JCS_CMYK;
1738 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1739 if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
1741 /* jpeg_set_colorspace set all sampling factors to 1 */
1744 sp->cinfo.c.input_components = 1;
1745 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1746 if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1748 sp->cinfo.c.comp_info[0].component_id = s;
1749 /* jpeg_set_colorspace() set sampling factors to 1 */
1750 if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
1751 sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
1752 sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
1753 sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
1756 /* ensure libjpeg won't write any extraneous markers */
1757 sp->cinfo.c.write_JFIF_header = FALSE;
1758 sp->cinfo.c.write_Adobe_marker = FALSE;
1759 /* set up table handling correctly */
1760 if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1762 if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
1763 unsuppress_quant_table(sp, 0);
1764 unsuppress_quant_table(sp, 1);
1766 if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
1767 sp->cinfo.c.optimize_coding = FALSE;
1769 sp->cinfo.c.optimize_coding = TRUE;
1770 if (downsampled_input) {
1771 /* Need to use raw-data interface to libjpeg */
1772 sp->cinfo.c.raw_data_in = TRUE;
1773 tif->tif_encoderow = JPEGEncodeRaw;
1774 tif->tif_encodestrip = JPEGEncodeRaw;
1775 tif->tif_encodetile = JPEGEncodeRaw;
1777 /* Use normal interface to libjpeg */
1778 sp->cinfo.c.raw_data_in = FALSE;
1779 tif->tif_encoderow = JPEGEncode;
1780 tif->tif_encodestrip = JPEGEncode;
1781 tif->tif_encodetile = JPEGEncode;
1783 /* Start JPEG compressor */
1784 if (!TIFFjpeg_start_compress(sp, FALSE))
1786 /* Allocate downsampled-data buffers if needed */
1787 if (downsampled_input) {
1788 if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
1789 sp->cinfo.c.num_components))
1798 * Encode a chunk of pixels.
1799 * "Standard" case: incoming data is not downsampled.
1802 JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1804 JPEGState *sp = JState(tif);
1807 short *line16 = NULL;
1808 int line16_count = 0;
1812 /* data is expected to be supplied in multiples of a scanline */
1813 nrows = cc / sp->bytesperline;
1814 if (cc % sp->bytesperline)
1815 TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
1816 "fractional scanline discarded");
1818 /* The last strip will be limited to image size */
1819 if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
1820 nrows = tif->tif_dir.td_imagelength - tif->tif_row;
1822 if( sp->cinfo.c.data_precision == 12 )
1824 line16_count = (sp->bytesperline * 2) / 3;
1825 line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
1826 // FIXME: undiagnosed malloc failure
1829 while (nrows-- > 0) {
1831 if( sp->cinfo.c.data_precision == 12 )
1834 int value_pairs = line16_count / 2;
1837 bufptr[0] = (JSAMPROW) line16;
1839 for( iPair = 0; iPair < value_pairs; iPair++ )
1841 unsigned char *in_ptr =
1842 ((unsigned char *) buf) + iPair * 3;
1843 JSAMPLE *out_ptr = (JSAMPLE *) (line16 + iPair * 2);
1845 out_ptr[0] = (in_ptr[0] << 4) | ((in_ptr[1] & 0xf0) >> 4);
1846 out_ptr[1] = ((in_ptr[1] & 0x0f) << 8) | in_ptr[2];
1851 bufptr[0] = (JSAMPROW) buf;
1853 if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
1857 buf += sp->bytesperline;
1860 if( sp->cinfo.c.data_precision == 12 )
1862 _TIFFfree( line16 );
1869 * Encode a chunk of pixels.
1870 * Incoming data is expected to be downsampled per sampling factors.
1873 JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1875 JPEGState *sp = JState(tif);
1879 JDIMENSION clumps_per_line, nclump;
1880 int clumpoffset, ci, xpos, ypos;
1881 jpeg_component_info* compptr;
1882 int samples_per_clump = sp->samplesperclump;
1883 tmsize_t bytesperclumpline;
1887 /* data is expected to be supplied in multiples of a clumpline */
1888 /* a clumpline is equivalent to v_sampling desubsampled scanlines */
1889 /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
1890 bytesperclumpline = (((sp->cinfo.c.image_width+sp->h_sampling-1)/sp->h_sampling)
1891 *(sp->h_sampling*sp->v_sampling+2)*sp->cinfo.c.data_precision+7)
1894 nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
1895 if (cc % bytesperclumpline)
1896 TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
1898 /* Cb,Cr both have sampling factors 1, so this is correct */
1899 clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
1903 * Fastest way to separate the data is to make one pass
1904 * over the scanline for each row of each component.
1906 clumpoffset = 0; /* first sample in clump */
1907 for (ci = 0, compptr = sp->cinfo.c.comp_info;
1908 ci < sp->cinfo.c.num_components;
1910 int hsamp = compptr->h_samp_factor;
1911 int vsamp = compptr->v_samp_factor;
1912 int padding = (int) (compptr->width_in_blocks * DCTSIZE -
1913 clumps_per_line * hsamp);
1914 for (ypos = 0; ypos < vsamp; ypos++) {
1915 inptr = ((JSAMPLE*) buf) + clumpoffset;
1916 outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1918 /* fast path for at least Cb and Cr */
1919 for (nclump = clumps_per_line; nclump-- > 0; ) {
1920 *outptr++ = inptr[0];
1921 inptr += samples_per_clump;
1925 for (nclump = clumps_per_line; nclump-- > 0; ) {
1926 for (xpos = 0; xpos < hsamp; xpos++)
1927 *outptr++ = inptr[xpos];
1928 inptr += samples_per_clump;
1931 /* pad each scanline as needed */
1932 for (xpos = 0; xpos < padding; xpos++) {
1933 *outptr = outptr[-1];
1936 clumpoffset += hsamp;
1940 if (sp->scancount >= DCTSIZE) {
1941 int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1942 if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1946 tif->tif_row += sp->v_sampling;
1947 buf += bytesperclumpline;
1948 nrows -= sp->v_sampling;
1954 * Finish up at the end of a strip or tile.
1957 JPEGPostEncode(TIFF* tif)
1959 JPEGState *sp = JState(tif);
1961 if (sp->scancount > 0) {
1963 * Need to emit a partial bufferload of downsampled data.
1964 * Pad the data vertically.
1967 jpeg_component_info* compptr;
1969 for (ci = 0, compptr = sp->cinfo.c.comp_info;
1970 ci < sp->cinfo.c.num_components;
1972 int vsamp = compptr->v_samp_factor;
1973 tmsize_t row_width = compptr->width_in_blocks * DCTSIZE
1975 for (ypos = sp->scancount * vsamp;
1976 ypos < DCTSIZE * vsamp; ypos++) {
1977 _TIFFmemcpy((void*)sp->ds_buffer[ci][ypos],
1978 (void*)sp->ds_buffer[ci][ypos-1],
1983 n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1984 if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1988 return (TIFFjpeg_finish_compress(JState(tif)));
1992 JPEGCleanup(TIFF* tif)
1994 JPEGState *sp = JState(tif);
1998 tif->tif_tagmethods.vgetfield = sp->vgetparent;
1999 tif->tif_tagmethods.vsetfield = sp->vsetparent;
2000 tif->tif_tagmethods.printdir = sp->printdir;
2003 if( sp->cinfo_initialized )
2004 TIFFjpeg_destroy(sp); /* release libjpeg resources */
2005 if (sp->jpegtables) /* tag value */
2006 _TIFFfree(sp->jpegtables);
2008 _TIFFfree(tif->tif_data); /* release local state */
2009 tif->tif_data = NULL;
2011 _TIFFSetDefaultCompressionState(tif);
2015 JPEGResetUpsampled( TIFF* tif )
2017 JPEGState* sp = JState(tif);
2018 TIFFDirectory* td = &tif->tif_dir;
2021 * Mark whether returned data is up-sampled or not so TIFFStripSize
2022 * and TIFFTileSize return values that reflect the true amount of
2025 tif->tif_flags &= ~TIFF_UPSAMPLED;
2026 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
2027 if (td->td_photometric == PHOTOMETRIC_YCBCR &&
2028 sp->jpegcolormode == JPEGCOLORMODE_RGB) {
2029 tif->tif_flags |= TIFF_UPSAMPLED;
2032 if (td->td_ycbcrsubsampling[0] != 1 ||
2033 td->td_ycbcrsubsampling[1] != 1)
2034 ; /* XXX what about up-sampling? */
2040 * Must recalculate cached tile size in case sampling state changed.
2041 * Should we really be doing this now if image size isn't set?
2043 if( tif->tif_tilesize > 0 )
2044 tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
2045 if( tif->tif_scanlinesize > 0 )
2046 tif->tif_scanlinesize = TIFFScanlineSize(tif);
2050 JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
2052 JPEGState* sp = JState(tif);
2053 const TIFFField* fip;
2059 case TIFFTAG_JPEGTABLES:
2060 v32 = (uint32) va_arg(ap, uint32);
2065 _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
2067 sp->jpegtables_length = v32;
2068 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2070 case TIFFTAG_JPEGQUALITY:
2071 sp->jpegquality = (int) va_arg(ap, int);
2072 return (1); /* pseudo tag */
2073 case TIFFTAG_JPEGCOLORMODE:
2074 sp->jpegcolormode = (int) va_arg(ap, int);
2075 JPEGResetUpsampled( tif );
2076 return (1); /* pseudo tag */
2077 case TIFFTAG_PHOTOMETRIC:
2079 int ret_value = (*sp->vsetparent)(tif, tag, ap);
2080 JPEGResetUpsampled( tif );
2083 case TIFFTAG_JPEGTABLESMODE:
2084 sp->jpegtablesmode = (int) va_arg(ap, int);
2085 return (1); /* pseudo tag */
2086 case TIFFTAG_YCBCRSUBSAMPLING:
2087 /* mark the fact that we have a real ycbcrsubsampling! */
2088 sp->ycbcrsampling_fetched = 1;
2089 /* should we be recomputing upsampling info here? */
2090 return (*sp->vsetparent)(tif, tag, ap);
2092 return (*sp->vsetparent)(tif, tag, ap);
2095 if ((fip = TIFFFieldWithTag(tif, tag))) {
2096 TIFFSetFieldBit(tif, fip->field_bit);
2101 tif->tif_flags |= TIFF_DIRTYDIRECT;
2106 JPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
2108 JPEGState* sp = JState(tif);
2113 case TIFFTAG_JPEGTABLES:
2114 *va_arg(ap, uint32*) = sp->jpegtables_length;
2115 *va_arg(ap, void**) = sp->jpegtables;
2117 case TIFFTAG_JPEGQUALITY:
2118 *va_arg(ap, int*) = sp->jpegquality;
2120 case TIFFTAG_JPEGCOLORMODE:
2121 *va_arg(ap, int*) = sp->jpegcolormode;
2123 case TIFFTAG_JPEGTABLESMODE:
2124 *va_arg(ap, int*) = sp->jpegtablesmode;
2127 return (*sp->vgetparent)(tif, tag, ap);
2133 JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
2135 JPEGState* sp = JState(tif);
2141 if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
2142 fprintf(fd, " JPEG Tables: (%lu bytes)\n",
2143 (unsigned long) sp->jpegtables_length);
2145 (*sp->printdir)(tif, fd, flags);
2150 JPEGDefaultStripSize(TIFF* tif, uint32 s)
2152 JPEGState* sp = JState(tif);
2153 TIFFDirectory *td = &tif->tif_dir;
2155 s = (*sp->defsparent)(tif, s);
2156 if (s < td->td_imagelength)
2157 s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
2162 JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
2164 JPEGState* sp = JState(tif);
2165 TIFFDirectory *td = &tif->tif_dir;
2167 (*sp->deftparent)(tif, tw, th);
2168 *tw = TIFFroundup_32(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
2169 *th = TIFFroundup_32(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
2173 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
2174 * now that we allow a TIFF file to be opened in update mode it is necessary
2175 * to have some way of deciding whether compression or decompression is
2176 * desired other than looking at tif->tif_mode. We accomplish this by
2177 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
2178 * If so, we assume decompression is desired.
2180 * This is tricky, because TIFFInitJPEG() is called while the directory is
2181 * being read, and generally speaking the BYTECOUNTS tag won't have been read
2182 * at that point. So we try to defer jpeg library initialization till we
2183 * do have that tag ... basically any access that might require the compressor
2184 * or decompressor that occurs after the reading of the directory.
2186 * In an ideal world compressors or decompressors would be setup
2187 * at the point where a single tile or strip was accessed (for read or write)
2188 * so that stuff like update of missing tiles, or replacement of tiles could
2189 * be done. However, we aren't trying to crack that nut just yet ...
2191 * NFW, Feb 3rd, 2003.
2194 static int JPEGInitializeLibJPEG( TIFF * tif, int decompress )
2196 JPEGState* sp = JState(tif);
2198 if(sp->cinfo_initialized)
2200 if( !decompress && sp->cinfo.comm.is_decompressor )
2201 TIFFjpeg_destroy( sp );
2202 else if( decompress && !sp->cinfo.comm.is_decompressor )
2203 TIFFjpeg_destroy( sp );
2207 sp->cinfo_initialized = 0;
2211 * Initialize libjpeg.
2214 if (!TIFFjpeg_create_decompress(sp))
2217 if (!TIFFjpeg_create_compress(sp))
2221 sp->cinfo_initialized = TRUE;
2227 TIFFInitJPEG(TIFF* tif, int scheme)
2231 assert(scheme == COMPRESSION_JPEG);
2234 * Merge codec-specific tag information.
2236 if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields))) {
2237 TIFFErrorExt(tif->tif_clientdata,
2239 "Merging JPEG codec-specific tags failed");
2244 * Allocate state block so tag methods have storage to record values.
2246 tif->tif_data = (uint8*) _TIFFmalloc(sizeof (JPEGState));
2248 if (tif->tif_data == NULL) {
2249 TIFFErrorExt(tif->tif_clientdata,
2250 "TIFFInitJPEG", "No space for JPEG state block");
2253 _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
2256 sp->tif = tif; /* back link */
2259 * Override parent get/set field methods.
2261 sp->vgetparent = tif->tif_tagmethods.vgetfield;
2262 tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
2263 sp->vsetparent = tif->tif_tagmethods.vsetfield;
2264 tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
2265 sp->printdir = tif->tif_tagmethods.printdir;
2266 tif->tif_tagmethods.printdir = JPEGPrintDir; /* hook for codec tags */
2268 /* Default values for codec-specific fields */
2269 sp->jpegtables = NULL;
2270 sp->jpegtables_length = 0;
2271 sp->jpegquality = 75; /* Default IJG quality */
2272 sp->jpegcolormode = JPEGCOLORMODE_RAW;
2273 sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
2274 sp->ycbcrsampling_fetched = 0;
2277 * Install codec methods.
2279 tif->tif_fixuptags = JPEGFixupTags;
2280 tif->tif_setupdecode = JPEGSetupDecode;
2281 tif->tif_predecode = JPEGPreDecode;
2282 tif->tif_decoderow = JPEGDecode;
2283 tif->tif_decodestrip = JPEGDecode;
2284 tif->tif_decodetile = JPEGDecode;
2285 tif->tif_setupencode = JPEGSetupEncode;
2286 tif->tif_preencode = JPEGPreEncode;
2287 tif->tif_postencode = JPEGPostEncode;
2288 tif->tif_encoderow = JPEGEncode;
2289 tif->tif_encodestrip = JPEGEncode;
2290 tif->tif_encodetile = JPEGEncode;
2291 tif->tif_cleanup = JPEGCleanup;
2292 sp->defsparent = tif->tif_defstripsize;
2293 tif->tif_defstripsize = JPEGDefaultStripSize;
2294 sp->deftparent = tif->tif_deftilesize;
2295 tif->tif_deftilesize = JPEGDefaultTileSize;
2296 tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
2298 sp->cinfo_initialized = FALSE;
2301 ** Create a JPEGTables field if no directory has yet been created.
2302 ** We do this just to ensure that sufficient space is reserved for
2303 ** the JPEGTables field. It will be properly created the right
2306 if( tif->tif_diroff == 0 )
2308 #define SIZE_OF_JPEGTABLES 2000
2310 The following line assumes incorrectly that all JPEG-in-TIFF files will have
2311 a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
2312 when the JPEG data is placed with TIFFWriteRawStrip. The field bit should be
2313 set, anyway, later when actual JPEGTABLES header is generated, so removing it
2314 here hopefully is harmless.
2315 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2317 sp->jpegtables_length = SIZE_OF_JPEGTABLES;
2318 sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
2319 // FIXME: NULL-deref after malloc failure
2320 _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
2321 #undef SIZE_OF_JPEGTABLES
2326 #endif /* JPEG_SUPPORT */
2328 /* vim: set ts=8 sts=8 sw=8 noet: */