1 /* $Id: tif_jpeg.c,v 1.123 2016-01-23 21:20:34 erouault 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 conflicting 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 /* set client_data to avoid UMR warning from tools like Purify */
256 sp->cinfo.c.client_data = NULL;
258 return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
262 TIFFjpeg_create_decompress(JPEGState* sp)
264 /* initialize JPEG error handling */
265 sp->cinfo.d.err = jpeg_std_error(&sp->err);
266 sp->err.error_exit = TIFFjpeg_error_exit;
267 sp->err.output_message = TIFFjpeg_output_message;
269 /* set client_data to avoid UMR warning from tools like Purify */
270 sp->cinfo.d.client_data = NULL;
272 return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
276 TIFFjpeg_set_defaults(JPEGState* sp)
278 return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
282 TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
284 return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
288 TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
291 jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
295 TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
297 return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
301 TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
304 jpeg_start_compress(&sp->cinfo.c, write_all_tables));
308 TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
310 return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
311 scanlines, (JDIMENSION) num_lines));
315 TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
317 return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
318 data, (JDIMENSION) num_lines));
322 TIFFjpeg_finish_compress(JPEGState* sp)
324 return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
328 TIFFjpeg_write_tables(JPEGState* sp)
330 return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
334 TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
336 return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
340 TIFFjpeg_start_decompress(JPEGState* sp)
342 return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
346 TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
348 return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
349 scanlines, (JDIMENSION) max_lines));
353 TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
355 return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
356 data, (JDIMENSION) max_lines));
360 TIFFjpeg_finish_decompress(JPEGState* sp)
362 return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
366 TIFFjpeg_abort(JPEGState* sp)
368 return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
372 TIFFjpeg_destroy(JPEGState* sp)
374 return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
378 TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
379 JDIMENSION samplesperrow, JDIMENSION numrows)
381 return CALLJPEG(sp, (JSAMPARRAY) NULL,
382 (*sp->cinfo.comm.mem->alloc_sarray)
383 (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
387 * JPEG library destination data manager.
388 * These routines direct compressed data from libjpeg into the
389 * libtiff output buffer.
393 std_init_destination(j_compress_ptr cinfo)
395 JPEGState* sp = (JPEGState*) cinfo;
398 sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
399 sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
403 std_empty_output_buffer(j_compress_ptr cinfo)
405 JPEGState* sp = (JPEGState*) cinfo;
408 /* the entire buffer has been filled */
409 tif->tif_rawcc = tif->tif_rawdatasize;
413 * The Intel IPP performance library does not necessarily fill up
414 * the whole output buffer on each pass, so only dump out the parts
415 * that have been filled.
416 * http://trac.osgeo.org/gdal/wiki/JpegIPP
418 if ( sp->dest.free_in_buffer >= 0 ) {
419 tif->tif_rawcc = tif->tif_rawdatasize - sp->dest.free_in_buffer;
424 sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
425 sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
431 std_term_destination(j_compress_ptr cinfo)
433 JPEGState* sp = (JPEGState*) cinfo;
436 tif->tif_rawcp = (uint8*) sp->dest.next_output_byte;
438 tif->tif_rawdatasize - (tmsize_t) sp->dest.free_in_buffer;
439 /* NB: libtiff does the final buffer flush */
443 TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
446 sp->cinfo.c.dest = &sp->dest;
447 sp->dest.init_destination = std_init_destination;
448 sp->dest.empty_output_buffer = std_empty_output_buffer;
449 sp->dest.term_destination = std_term_destination;
453 * Alternate destination manager for outputting to JPEGTables field.
457 tables_init_destination(j_compress_ptr cinfo)
459 JPEGState* sp = (JPEGState*) cinfo;
461 /* while building, jpegtables_length is allocated buffer size */
462 sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
463 sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
467 tables_empty_output_buffer(j_compress_ptr cinfo)
469 JPEGState* sp = (JPEGState*) cinfo;
472 /* the entire buffer has been filled; enlarge it by 1000 bytes */
473 newbuf = _TIFFrealloc((void*) sp->jpegtables,
474 (tmsize_t) (sp->jpegtables_length + 1000));
476 ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
477 sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
478 sp->dest.free_in_buffer = (size_t) 1000;
479 sp->jpegtables = newbuf;
480 sp->jpegtables_length += 1000;
485 tables_term_destination(j_compress_ptr cinfo)
487 JPEGState* sp = (JPEGState*) cinfo;
489 /* set tables length to number of bytes actually emitted */
490 sp->jpegtables_length -= (uint32) sp->dest.free_in_buffer;
494 TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
498 * Allocate a working buffer for building tables.
499 * Initial size is 1000 bytes, which is usually adequate.
502 _TIFFfree(sp->jpegtables);
503 sp->jpegtables_length = 1000;
504 sp->jpegtables = (void*) _TIFFmalloc((tmsize_t) sp->jpegtables_length);
505 if (sp->jpegtables == NULL) {
506 sp->jpegtables_length = 0;
507 TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
510 sp->cinfo.c.dest = &sp->dest;
511 sp->dest.init_destination = tables_init_destination;
512 sp->dest.empty_output_buffer = tables_empty_output_buffer;
513 sp->dest.term_destination = tables_term_destination;
518 * JPEG library source data manager.
519 * These routines supply compressed data to libjpeg.
523 std_init_source(j_decompress_ptr cinfo)
525 JPEGState* sp = (JPEGState*) cinfo;
528 sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
529 sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
533 std_fill_input_buffer(j_decompress_ptr cinfo)
535 JPEGState* sp = (JPEGState* ) cinfo;
536 static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
540 * The Intel IPP performance library does not necessarily read the whole
541 * input buffer in one pass, so it is possible to get here with data
544 * We just return without doing anything, until the entire buffer has
546 * http://trac.osgeo.org/gdal/wiki/JpegIPP
548 if( sp->src.bytes_in_buffer > 0 ) {
554 * Normally the whole strip/tile is read and so we don't need to do
555 * a fill. In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
556 * all the data, but the rawdata is refreshed between scanlines and
557 * we push this into the io machinery in JPEGDecode().
558 * http://trac.osgeo.org/gdal/ticket/3894
561 WARNMS(cinfo, JWRN_JPEG_EOF);
562 /* insert a fake EOI marker */
563 sp->src.next_input_byte = dummy_EOI;
564 sp->src.bytes_in_buffer = 2;
569 std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
571 JPEGState* sp = (JPEGState*) cinfo;
574 if ((size_t)num_bytes > sp->src.bytes_in_buffer) {
575 /* oops, buffer overrun */
576 (void) std_fill_input_buffer(cinfo);
578 sp->src.next_input_byte += (size_t) num_bytes;
579 sp->src.bytes_in_buffer -= (size_t) num_bytes;
585 std_term_source(j_decompress_ptr cinfo)
587 /* No work necessary here */
592 TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
595 sp->cinfo.d.src = &sp->src;
596 sp->src.init_source = std_init_source;
597 sp->src.fill_input_buffer = std_fill_input_buffer;
598 sp->src.skip_input_data = std_skip_input_data;
599 sp->src.resync_to_restart = jpeg_resync_to_restart;
600 sp->src.term_source = std_term_source;
601 sp->src.bytes_in_buffer = 0; /* for safety */
602 sp->src.next_input_byte = NULL;
606 * Alternate source manager for reading from JPEGTables.
607 * We can share all the code except for the init routine.
611 tables_init_source(j_decompress_ptr cinfo)
613 JPEGState* sp = (JPEGState*) cinfo;
615 sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
616 sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
620 TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
622 TIFFjpeg_data_src(sp, tif);
623 sp->src.init_source = tables_init_source;
627 * Allocate downsampled-data buffers needed for downsampled I/O.
628 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
629 * We use libjpeg's allocator so that buffers will be released automatically
630 * when done with strip/tile.
631 * This is also a handy place to compute samplesperclump, bytesperline.
634 alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
637 JPEGState* sp = JState(tif);
639 jpeg_component_info* compptr;
641 int samples_per_clump = 0;
643 for (ci = 0, compptr = comp_info; ci < num_components;
645 samples_per_clump += compptr->h_samp_factor *
646 compptr->v_samp_factor;
647 buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
648 compptr->width_in_blocks * DCTSIZE,
649 (JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
652 sp->ds_buffer[ci] = buf;
654 sp->samplesperclump = samples_per_clump;
663 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
665 #define JPEG_MARKER_SOF0 0xC0
666 #define JPEG_MARKER_SOF1 0xC1
667 #define JPEG_MARKER_SOF2 0xC2
668 #define JPEG_MARKER_SOF9 0xC9
669 #define JPEG_MARKER_SOF10 0xCA
670 #define JPEG_MARKER_DHT 0xC4
671 #define JPEG_MARKER_SOI 0xD8
672 #define JPEG_MARKER_SOS 0xDA
673 #define JPEG_MARKER_DQT 0xDB
674 #define JPEG_MARKER_DRI 0xDD
675 #define JPEG_MARKER_APP0 0xE0
676 #define JPEG_MARKER_COM 0xFE
677 struct JPEGFixupTagsSubsamplingData
682 uint8* buffercurrentbyte;
683 uint32 bufferbytesleft;
685 uint64 filebytesleft;
686 uint8 filepositioned;
688 static void JPEGFixupTagsSubsampling(TIFF* tif);
689 static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data);
690 static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result);
691 static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result);
692 static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength);
697 JPEGFixupTags(TIFF* tif)
699 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
700 if ((tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR)&&
701 (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&&
702 (tif->tif_dir.td_samplesperpixel==3))
703 JPEGFixupTagsSubsampling(tif);
709 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
712 JPEGFixupTagsSubsampling(TIFF* tif)
715 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
716 * the TIFF tags, but still use non-default (2,2) values within the jpeg
717 * data stream itself. In order for TIFF applications to work properly
718 * - for instance to get the strip buffer size right - it is imperative
719 * that the subsampling be available before we start reading the image
720 * data normally. This function will attempt to analyze the first strip in
721 * order to get the sampling values from the jpeg data stream.
723 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
724 * discovered sampling does not match the default sampling (2,2) or whatever
725 * was actually in the tiff tags.
727 * See the bug in bugzilla for details:
729 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
731 * Frank Warmerdam, July 2002
732 * Joris Van Damme, May 2007
734 static const char module[] = "JPEGFixupTagsSubsampling";
735 struct JPEGFixupTagsSubsamplingData m;
737 _TIFFFillStriles( tif );
739 if( tif->tif_dir.td_stripbytecount == NULL
740 || tif->tif_dir.td_stripoffset == NULL
741 || tif->tif_dir.td_stripbytecount[0] == 0 )
743 /* Do not even try to check if the first strip/tile does not
744 yet exist, as occurs when GDAL has created a new NULL file
751 m.buffer=_TIFFmalloc(m.buffersize);
754 TIFFWarningExt(tif->tif_clientdata,module,
755 "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
758 m.buffercurrentbyte=NULL;
760 m.fileoffset=tif->tif_dir.td_stripoffset[0];
762 m.filebytesleft=tif->tif_dir.td_stripbytecount[0];
763 if (!JPEGFixupTagsSubsamplingSec(&m))
764 TIFFWarningExt(tif->tif_clientdata,module,
765 "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
770 JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
772 static const char module[] = "JPEGFixupTagsSubsamplingSec";
778 if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
785 if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
792 case JPEG_MARKER_SOI:
793 /* this type of marker has no data and should be skipped */
795 case JPEG_MARKER_COM:
796 case JPEG_MARKER_APP0:
797 case JPEG_MARKER_APP0+1:
798 case JPEG_MARKER_APP0+2:
799 case JPEG_MARKER_APP0+3:
800 case JPEG_MARKER_APP0+4:
801 case JPEG_MARKER_APP0+5:
802 case JPEG_MARKER_APP0+6:
803 case JPEG_MARKER_APP0+7:
804 case JPEG_MARKER_APP0+8:
805 case JPEG_MARKER_APP0+9:
806 case JPEG_MARKER_APP0+10:
807 case JPEG_MARKER_APP0+11:
808 case JPEG_MARKER_APP0+12:
809 case JPEG_MARKER_APP0+13:
810 case JPEG_MARKER_APP0+14:
811 case JPEG_MARKER_APP0+15:
812 case JPEG_MARKER_DQT:
813 case JPEG_MARKER_SOS:
814 case JPEG_MARKER_DHT:
815 case JPEG_MARKER_DRI:
816 /* this type of marker has data, but it has no use to us and should be skipped */
819 if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
825 JPEGFixupTagsSubsamplingSkip(data,n);
828 case JPEG_MARKER_SOF0: /* Baseline sequential Huffman */
829 case JPEG_MARKER_SOF1: /* Extended sequential Huffman */
830 case JPEG_MARKER_SOF2: /* Progressive Huffman: normally not allowed by TechNote, but that doesn't hurt supporting it */
831 case JPEG_MARKER_SOF9: /* Extended sequential arithmetic */
832 case JPEG_MARKER_SOF10: /* Progressive arithmetic: normally not allowed by TechNote, but that doesn't hurt supporting it */
833 /* this marker contains the subsampling factors we're scanning for */
839 if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
841 if (n!=8+data->tif->tif_dir.td_samplesperpixel*3)
843 JPEGFixupTagsSubsamplingSkip(data,7);
844 if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
848 JPEGFixupTagsSubsamplingSkip(data,1);
849 for (o=1; o<data->tif->tif_dir.td_samplesperpixel; o++)
851 JPEGFixupTagsSubsamplingSkip(data,1);
852 if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
856 TIFFWarningExt(data->tif->tif_clientdata,module,
857 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
860 JPEGFixupTagsSubsamplingSkip(data,1);
862 if (((ph!=1)&&(ph!=2)&&(ph!=4))||((pv!=1)&&(pv!=2)&&(pv!=4)))
864 TIFFWarningExt(data->tif->tif_clientdata,module,
865 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
868 if ((ph!=data->tif->tif_dir.td_ycbcrsubsampling[0])||(pv!=data->tif->tif_dir.td_ycbcrsubsampling[1]))
870 TIFFWarningExt(data->tif->tif_clientdata,module,
871 "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
872 (int)data->tif->tif_dir.td_ycbcrsubsampling[0],
873 (int)data->tif->tif_dir.td_ycbcrsubsampling[1],
875 data->tif->tif_dir.td_ycbcrsubsampling[0]=ph;
876 data->tif->tif_dir.td_ycbcrsubsampling[1]=pv;
887 JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result)
889 if (data->bufferbytesleft==0)
892 if (data->filebytesleft==0)
894 if (!data->filepositioned)
896 TIFFSeekFile(data->tif,data->fileoffset,SEEK_SET);
897 data->filepositioned=1;
900 if ((uint64)m>data->filebytesleft)
901 m=(uint32)data->filebytesleft;
902 assert(m<0x80000000UL);
903 if (TIFFReadFile(data->tif,data->buffer,(tmsize_t)m)!=(tmsize_t)m)
905 data->buffercurrentbyte=data->buffer;
906 data->bufferbytesleft=m;
908 data->filebytesleft-=m;
910 *result=*data->buffercurrentbyte;
911 data->buffercurrentbyte++;
912 data->bufferbytesleft--;
917 JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result)
921 if (!JPEGFixupTagsSubsamplingReadByte(data,&ma))
923 if (!JPEGFixupTagsSubsamplingReadByte(data,&mb))
930 JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength)
932 if ((uint32)skiplength<=data->bufferbytesleft)
934 data->buffercurrentbyte+=skiplength;
935 data->bufferbytesleft-=skiplength;
940 m=(uint16)(skiplength-data->bufferbytesleft);
941 if (m<=data->filebytesleft)
943 data->bufferbytesleft=0;
945 data->filebytesleft-=m;
946 data->filepositioned=0;
950 data->bufferbytesleft=0;
951 data->filebytesleft=0;
960 JPEGSetupDecode(TIFF* tif)
962 JPEGState* sp = JState(tif);
963 TIFFDirectory *td = &tif->tif_dir;
965 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
966 if( tif->tif_dir.td_bitspersample == 12 )
967 return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 0 );
970 JPEGInitializeLibJPEG( tif, TRUE );
973 assert(sp->cinfo.comm.is_decompressor);
975 /* Read JPEGTables if it is present */
976 if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
977 TIFFjpeg_tables_src(sp, tif);
978 if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
979 TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
984 /* Grab parameters that are same for all strips/tiles */
985 sp->photometric = td->td_photometric;
986 switch (sp->photometric) {
987 case PHOTOMETRIC_YCBCR:
988 sp->h_sampling = td->td_ycbcrsubsampling[0];
989 sp->v_sampling = td->td_ycbcrsubsampling[1];
992 /* TIFF 6.0 forbids subsampling of all other color spaces */
998 /* Set up for reading normal data */
999 TIFFjpeg_data_src(sp, tif);
1000 tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
1005 * Set up for decoding a strip or tile.
1007 /*ARGSUSED*/ static int
1008 JPEGPreDecode(TIFF* tif, uint16 s)
1010 JPEGState *sp = JState(tif);
1011 TIFFDirectory *td = &tif->tif_dir;
1012 static const char module[] = "JPEGPreDecode";
1013 uint32 segment_width, segment_height;
1014 int downsampled_output;
1019 if (sp->cinfo.comm.is_decompressor == 0)
1021 tif->tif_setupdecode( tif );
1024 assert(sp->cinfo.comm.is_decompressor);
1026 * Reset decoder state from any previous strip/tile,
1027 * in case application didn't read the whole strip.
1029 if (!TIFFjpeg_abort(sp))
1032 * Read the header for this strip/tile.
1035 if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
1038 tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
1039 tif->tif_rawcc = sp->src.bytes_in_buffer;
1042 * Check image parameters and set decompression parameters.
1044 segment_width = td->td_imagewidth;
1045 segment_height = td->td_imagelength - tif->tif_row;
1047 segment_width = td->td_tilewidth;
1048 segment_height = td->td_tilelength;
1049 sp->bytesperline = TIFFTileRowSize(tif);
1051 if (segment_height > td->td_rowsperstrip)
1052 segment_height = td->td_rowsperstrip;
1053 sp->bytesperline = TIFFScanlineSize(tif);
1055 if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1057 * For PC 2, scale down the expected strip/tile size
1058 * to match a downsampled component
1060 segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
1061 segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1063 if (sp->cinfo.d.image_width < segment_width ||
1064 sp->cinfo.d.image_height < segment_height) {
1065 TIFFWarningExt(tif->tif_clientdata, module,
1066 "Improper JPEG strip/tile size, "
1067 "expected %dx%d, got %dx%d",
1068 segment_width, segment_height,
1069 sp->cinfo.d.image_width,
1070 sp->cinfo.d.image_height);
1072 if (sp->cinfo.d.image_width > segment_width ||
1073 sp->cinfo.d.image_height > segment_height) {
1075 * This case could be dangerous, if the strip or tile size has
1076 * been reported as less than the amount of data jpeg will
1077 * return, some potential security issues arise. Catch this
1078 * case and error out.
1080 TIFFErrorExt(tif->tif_clientdata, module,
1081 "JPEG strip/tile size exceeds expected dimensions,"
1082 " expected %dx%d, got %dx%d",
1083 segment_width, segment_height,
1084 sp->cinfo.d.image_width, sp->cinfo.d.image_height);
1087 if (sp->cinfo.d.num_components !=
1088 (td->td_planarconfig == PLANARCONFIG_CONTIG ?
1089 td->td_samplesperpixel : 1)) {
1090 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG component count");
1094 if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
1095 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
1098 sp->cinfo.d.data_precision = td->td_bitspersample;
1099 sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
1101 if (sp->cinfo.d.data_precision != td->td_bitspersample) {
1102 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
1106 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1107 /* Component 0 should have expected sampling factors */
1108 if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
1109 sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
1110 TIFFErrorExt(tif->tif_clientdata, module,
1111 "Improper JPEG sampling factors %d,%d\n"
1112 "Apparently should be %d,%d.",
1113 sp->cinfo.d.comp_info[0].h_samp_factor,
1114 sp->cinfo.d.comp_info[0].v_samp_factor,
1115 sp->h_sampling, sp->v_sampling);
1118 /* Rest should have sampling factors 1,1 */
1119 for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
1120 if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
1121 sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
1122 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
1127 /* PC 2's single component should have sampling factors 1,1 */
1128 if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
1129 sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
1130 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
1134 downsampled_output = FALSE;
1135 if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1136 sp->photometric == PHOTOMETRIC_YCBCR &&
1137 sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1138 /* Convert YCbCr to RGB */
1139 sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
1140 sp->cinfo.d.out_color_space = JCS_RGB;
1142 /* Suppress colorspace handling */
1143 sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
1144 sp->cinfo.d.out_color_space = JCS_UNKNOWN;
1145 if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1146 (sp->h_sampling != 1 || sp->v_sampling != 1))
1147 downsampled_output = TRUE;
1148 /* XXX what about up-sampling? */
1150 if (downsampled_output) {
1151 /* Need to use raw-data interface to libjpeg */
1152 sp->cinfo.d.raw_data_out = TRUE;
1153 #if JPEG_LIB_VERSION >= 70
1154 sp->cinfo.d.do_fancy_upsampling = FALSE;
1155 #endif /* JPEG_LIB_VERSION >= 70 */
1156 tif->tif_decoderow = DecodeRowError;
1157 tif->tif_decodestrip = JPEGDecodeRaw;
1158 tif->tif_decodetile = JPEGDecodeRaw;
1160 /* Use normal interface to libjpeg */
1161 sp->cinfo.d.raw_data_out = FALSE;
1162 tif->tif_decoderow = JPEGDecode;
1163 tif->tif_decodestrip = JPEGDecode;
1164 tif->tif_decodetile = JPEGDecode;
1166 /* Start JPEG decompressor */
1167 if (!TIFFjpeg_start_decompress(sp))
1169 /* Allocate downsampled-data buffers if needed */
1170 if (downsampled_output) {
1171 if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
1172 sp->cinfo.d.num_components))
1174 sp->scancount = DCTSIZE; /* mark buffer empty */
1180 * Decode a chunk of pixels.
1181 * "Standard" case: returned data is not downsampled.
1183 #if !JPEG_LIB_MK1_OR_12BIT
1185 JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1187 JPEGState *sp = JState(tif);
1192 ** Update available information, buffer may have been refilled
1193 ** between decode requests
1195 sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
1196 sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
1198 if( sp->bytesperline == 0 )
1201 nrows = cc / sp->bytesperline;
1202 if (cc % sp->bytesperline)
1203 TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
1204 "fractional scanline not read");
1206 if( nrows > (tmsize_t) sp->cinfo.d.image_height )
1207 nrows = sp->cinfo.d.image_height;
1209 /* data is expected to be read in multiples of a scanline */
1215 * In the libjpeg6b-9a 8bit case. We read directly into
1218 JSAMPROW bufptr = (JSAMPROW)buf;
1220 if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
1224 buf += sp->bytesperline;
1225 cc -= sp->bytesperline;
1226 } while (--nrows > 0);
1229 /* Update information on consumed data */
1230 tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
1231 tif->tif_rawcc = sp->src.bytes_in_buffer;
1233 /* Close down the decompressor if we've finished the strip or tile. */
1234 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1235 || TIFFjpeg_finish_decompress(sp);
1237 #endif /* !JPEG_LIB_MK1_OR_12BIT */
1239 #if JPEG_LIB_MK1_OR_12BIT
1240 /*ARGSUSED*/ static int
1241 JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1243 JPEGState *sp = JState(tif);
1248 ** Update available information, buffer may have been refilled
1249 ** between decode requests
1251 sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
1252 sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
1254 if( sp->bytesperline == 0 )
1257 nrows = cc / sp->bytesperline;
1258 if (cc % sp->bytesperline)
1259 TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
1260 "fractional scanline not read");
1262 if( nrows > (tmsize_t) sp->cinfo.d.image_height )
1263 nrows = sp->cinfo.d.image_height;
1265 /* data is expected to be read in multiples of a scanline */
1268 JSAMPROW line_work_buf = NULL;
1271 * For 6B, only use temporary buffer for 12 bit imagery.
1272 * For Mk1 always use it.
1274 if( sp->cinfo.d.data_precision == 12 )
1276 line_work_buf = (JSAMPROW)
1277 _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
1278 * sp->cinfo.d.num_components );
1283 if( line_work_buf != NULL )
1286 * In the MK1 case, we always read into a 16bit
1287 * buffer, and then pack down to 12bit or 8bit.
1288 * In 6B case we only read into 16 bit buffer
1289 * for 12bit data, which we need to repack.
1291 if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
1294 if( sp->cinfo.d.data_precision == 12 )
1296 int value_pairs = (sp->cinfo.d.output_width
1297 * sp->cinfo.d.num_components) / 2;
1300 for( iPair = 0; iPair < value_pairs; iPair++ )
1302 unsigned char *out_ptr =
1303 ((unsigned char *) buf) + iPair * 3;
1304 JSAMPLE *in_ptr = line_work_buf + iPair * 2;
1306 out_ptr[0] = (unsigned char)((in_ptr[0] & 0xff0) >> 4);
1307 out_ptr[1] = (unsigned char)(((in_ptr[0] & 0xf) << 4)
1308 | ((in_ptr[1] & 0xf00) >> 8));
1309 out_ptr[2] = (unsigned char)(((in_ptr[1] & 0xff) >> 0));
1312 else if( sp->cinfo.d.data_precision == 8 )
1314 int value_count = (sp->cinfo.d.output_width
1315 * sp->cinfo.d.num_components);
1318 for( iValue = 0; iValue < value_count; iValue++ )
1320 ((unsigned char *) buf)[iValue] =
1321 line_work_buf[iValue] & 0xff;
1327 buf += sp->bytesperline;
1328 cc -= sp->bytesperline;
1329 } while (--nrows > 0);
1331 if( line_work_buf != NULL )
1332 _TIFFfree( line_work_buf );
1335 /* Update information on consumed data */
1336 tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
1337 tif->tif_rawcc = sp->src.bytes_in_buffer;
1339 /* Close down the decompressor if we've finished the strip or tile. */
1340 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1341 || TIFFjpeg_finish_decompress(sp);
1343 #endif /* JPEG_LIB_MK1_OR_12BIT */
1345 /*ARGSUSED*/ static int
1346 DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1353 TIFFErrorExt(tif->tif_clientdata, "TIFFReadScanline",
1354 "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
1359 * Decode a chunk of pixels.
1360 * Returned data is downsampled per sampling factors.
1362 /*ARGSUSED*/ static int
1363 JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1365 JPEGState *sp = JState(tif);
1369 /* data is expected to be read in multiples of a scanline */
1370 if ( (nrows = sp->cinfo.d.image_height) != 0 ) {
1372 /* Cb,Cr both have sampling factors 1, so this is correct */
1373 JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
1374 int samples_per_clump = sp->samplesperclump;
1376 #if defined(JPEG_LIB_MK1_OR_12BIT)
1377 unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
1378 sp->cinfo.d.output_width *
1379 sp->cinfo.d.num_components);
1381 TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1388 jpeg_component_info *compptr;
1389 int ci, clumpoffset;
1391 if( cc < sp->bytesperline ) {
1392 TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1393 "application buffer not large enough for all data.");
1397 /* Reload downsampled-data buffer if needed */
1398 if (sp->scancount >= DCTSIZE) {
1399 int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
1400 if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
1405 * Fastest way to unseparate data is to make one pass
1406 * over the scanline for each row of each component.
1408 clumpoffset = 0; /* first sample in clump */
1409 for (ci = 0, compptr = sp->cinfo.d.comp_info;
1410 ci < sp->cinfo.d.num_components;
1412 int hsamp = compptr->h_samp_factor;
1413 int vsamp = compptr->v_samp_factor;
1416 for (ypos = 0; ypos < vsamp; ypos++) {
1417 JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1419 #if defined(JPEG_LIB_MK1_OR_12BIT)
1420 JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
1422 JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
1423 if (cc < (tmsize_t) (clumpoffset + samples_per_clump*(clumps_per_line-1) + hsamp)) {
1424 TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1425 "application buffer not large enough for all data, possible subsampling issue");
1431 /* fast path for at least Cb and Cr */
1432 for (nclump = clumps_per_line; nclump-- > 0; ) {
1433 outptr[0] = *inptr++;
1434 outptr += samples_per_clump;
1440 for (nclump = clumps_per_line; nclump-- > 0; ) {
1441 for (xpos = 0; xpos < hsamp; xpos++)
1442 outptr[xpos] = *inptr++;
1443 outptr += samples_per_clump;
1446 clumpoffset += hsamp;
1450 #if defined(JPEG_LIB_MK1_OR_12BIT)
1452 if (sp->cinfo.d.data_precision == 8)
1455 int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
1456 for (i=0; i<len; i++)
1458 ((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
1463 int value_pairs = (sp->cinfo.d.output_width
1464 * sp->cinfo.d.num_components) / 2;
1466 for( iPair = 0; iPair < value_pairs; iPair++ )
1468 unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
1469 JSAMPLE *in_ptr = (JSAMPLE *) (tmpbuf + iPair * 2);
1470 out_ptr[0] = (unsigned char)((in_ptr[0] & 0xff0) >> 4);
1471 out_ptr[1] = (unsigned char)(((in_ptr[0] & 0xf) << 4)
1472 | ((in_ptr[1] & 0xf00) >> 8));
1473 out_ptr[2] = (unsigned char)(((in_ptr[1] & 0xff) >> 0));
1480 tif->tif_row += sp->v_sampling;
1482 buf += sp->bytesperline;
1483 cc -= sp->bytesperline;
1485 nrows -= sp->v_sampling;
1486 } while (nrows > 0);
1488 #if defined(JPEG_LIB_MK1_OR_12BIT)
1494 /* Close down the decompressor if done. */
1495 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1496 || TIFFjpeg_finish_decompress(sp);
1505 unsuppress_quant_table (JPEGState* sp, int tblno)
1509 if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1510 qtbl->sent_table = FALSE;
1514 suppress_quant_table (JPEGState* sp, int tblno)
1518 if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1519 qtbl->sent_table = TRUE;
1523 unsuppress_huff_table (JPEGState* sp, int tblno)
1527 if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1528 htbl->sent_table = FALSE;
1529 if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1530 htbl->sent_table = FALSE;
1534 suppress_huff_table (JPEGState* sp, int tblno)
1538 if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1539 htbl->sent_table = TRUE;
1540 if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1541 htbl->sent_table = TRUE;
1545 prepare_JPEGTables(TIFF* tif)
1547 JPEGState* sp = JState(tif);
1549 /* Initialize quant tables for current quality setting */
1550 if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1552 /* Mark only the tables we want for output */
1553 /* NB: chrominance tables are currently used only with YCbCr */
1554 if (!TIFFjpeg_suppress_tables(sp, TRUE))
1556 if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
1557 unsuppress_quant_table(sp, 0);
1558 if (sp->photometric == PHOTOMETRIC_YCBCR)
1559 unsuppress_quant_table(sp, 1);
1561 if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
1562 unsuppress_huff_table(sp, 0);
1563 if (sp->photometric == PHOTOMETRIC_YCBCR)
1564 unsuppress_huff_table(sp, 1);
1566 /* Direct libjpeg output into jpegtables */
1567 if (!TIFFjpeg_tables_dest(sp, tif))
1569 /* Emit tables-only datastream */
1570 if (!TIFFjpeg_write_tables(sp))
1577 JPEGSetupEncode(TIFF* tif)
1579 JPEGState* sp = JState(tif);
1580 TIFFDirectory *td = &tif->tif_dir;
1581 static const char module[] = "JPEGSetupEncode";
1583 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
1584 if( tif->tif_dir.td_bitspersample == 12 )
1585 return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 1 );
1588 JPEGInitializeLibJPEG( tif, FALSE );
1591 assert(!sp->cinfo.comm.is_decompressor);
1593 sp->photometric = td->td_photometric;
1596 * Initialize all JPEG parameters to default values.
1597 * Note that jpeg_set_defaults needs legal values for
1598 * in_color_space and input_components.
1600 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1601 sp->cinfo.c.input_components = td->td_samplesperpixel;
1602 if (sp->photometric == PHOTOMETRIC_YCBCR) {
1603 if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1604 sp->cinfo.c.in_color_space = JCS_RGB;
1606 sp->cinfo.c.in_color_space = JCS_YCbCr;
1609 if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
1610 sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
1611 else if (td->td_photometric == PHOTOMETRIC_RGB && td->td_samplesperpixel == 3)
1612 sp->cinfo.c.in_color_space = JCS_RGB;
1613 else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
1614 sp->cinfo.c.in_color_space = JCS_CMYK;
1616 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1619 sp->cinfo.c.input_components = 1;
1620 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1622 if (!TIFFjpeg_set_defaults(sp))
1624 /* Set per-file parameters */
1625 switch (sp->photometric) {
1626 case PHOTOMETRIC_YCBCR:
1627 sp->h_sampling = td->td_ycbcrsubsampling[0];
1628 sp->v_sampling = td->td_ycbcrsubsampling[1];
1630 * A ReferenceBlackWhite field *must* be present since the
1631 * default value is inappropriate for YCbCr. Fill in the
1632 * proper value if application didn't set it.
1636 if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1639 long top = 1L << td->td_bitspersample;
1641 refbw[1] = (float)(top-1L);
1642 refbw[2] = (float)(top>>1);
1643 refbw[3] = refbw[1];
1644 refbw[4] = refbw[2];
1645 refbw[5] = refbw[1];
1646 TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1651 case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */
1652 case PHOTOMETRIC_MASK:
1653 TIFFErrorExt(tif->tif_clientdata, module,
1654 "PhotometricInterpretation %d not allowed for JPEG",
1655 (int) sp->photometric);
1658 /* TIFF 6.0 forbids subsampling of all other color spaces */
1664 /* Verify miscellaneous parameters */
1667 * This would need work if libtiff ever supports different
1668 * depths for different components, or if libjpeg ever supports
1669 * run-time selection of depth. Neither is imminent.
1672 /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1673 if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
1675 if (td->td_bitspersample != BITS_IN_JSAMPLE )
1678 TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
1679 (int) td->td_bitspersample);
1682 sp->cinfo.c.data_precision = td->td_bitspersample;
1684 sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
1687 if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
1688 TIFFErrorExt(tif->tif_clientdata, module,
1689 "JPEG tile height must be multiple of %d",
1690 sp->v_sampling * DCTSIZE);
1693 if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
1694 TIFFErrorExt(tif->tif_clientdata, module,
1695 "JPEG tile width must be multiple of %d",
1696 sp->h_sampling * DCTSIZE);
1700 if (td->td_rowsperstrip < td->td_imagelength &&
1701 (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
1702 TIFFErrorExt(tif->tif_clientdata, module,
1703 "RowsPerStrip must be multiple of %d for JPEG",
1704 sp->v_sampling * DCTSIZE);
1709 /* Create a JPEGTables field if appropriate */
1710 if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
1711 if( sp->jpegtables == NULL
1712 || memcmp(sp->jpegtables,"\0\0\0\0\0\0\0\0\0",8) == 0 )
1714 if (!prepare_JPEGTables(tif))
1716 /* Mark the field present */
1717 /* Can't use TIFFSetField since BEENWRITING is already set! */
1718 tif->tif_flags |= TIFF_DIRTYDIRECT;
1719 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1722 /* We do not support application-supplied JPEGTables, */
1723 /* so mark the field not present */
1724 TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
1727 /* Direct libjpeg output to libtiff's output buffer */
1728 TIFFjpeg_data_dest(sp, tif);
1734 * Set encoding state at the start of a strip or tile.
1737 JPEGPreEncode(TIFF* tif, uint16 s)
1739 JPEGState *sp = JState(tif);
1740 TIFFDirectory *td = &tif->tif_dir;
1741 static const char module[] = "JPEGPreEncode";
1742 uint32 segment_width, segment_height;
1743 int downsampled_input;
1747 if (sp->cinfo.comm.is_decompressor == 1)
1749 tif->tif_setupencode( tif );
1752 assert(!sp->cinfo.comm.is_decompressor);
1754 * Set encoding parameters for this strip/tile.
1757 segment_width = td->td_tilewidth;
1758 segment_height = td->td_tilelength;
1759 sp->bytesperline = TIFFTileRowSize(tif);
1761 segment_width = td->td_imagewidth;
1762 segment_height = td->td_imagelength - tif->tif_row;
1763 if (segment_height > td->td_rowsperstrip)
1764 segment_height = td->td_rowsperstrip;
1765 sp->bytesperline = TIFFScanlineSize(tif);
1767 if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1768 /* for PC 2, scale down the strip/tile size
1769 * to match a downsampled component
1771 segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
1772 segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1774 if (segment_width > 65535 || segment_height > 65535) {
1775 TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
1778 sp->cinfo.c.image_width = segment_width;
1779 sp->cinfo.c.image_height = segment_height;
1780 downsampled_input = FALSE;
1781 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1782 sp->cinfo.c.input_components = td->td_samplesperpixel;
1783 if (sp->photometric == PHOTOMETRIC_YCBCR) {
1784 if (sp->jpegcolormode != JPEGCOLORMODE_RGB) {
1785 if (sp->h_sampling != 1 || sp->v_sampling != 1)
1786 downsampled_input = TRUE;
1788 if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
1791 * Set Y sampling factors;
1792 * we assume jpeg_set_colorspace() set the rest to 1
1794 sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
1795 sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
1797 if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
1799 /* jpeg_set_colorspace set all sampling factors to 1 */
1802 if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1804 sp->cinfo.c.comp_info[0].component_id = s;
1805 /* jpeg_set_colorspace() set sampling factors to 1 */
1806 if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
1807 sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
1808 sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
1809 sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
1812 /* ensure libjpeg won't write any extraneous markers */
1813 sp->cinfo.c.write_JFIF_header = FALSE;
1814 sp->cinfo.c.write_Adobe_marker = FALSE;
1815 /* set up table handling correctly */
1816 /* calling TIFFjpeg_set_quality() causes quantization tables to be flagged */
1817 /* as being to be emitted, which we don't want in the JPEGTABLESMODE_QUANT */
1818 /* mode, so we must manually suppress them. However TIFFjpeg_set_quality() */
1819 /* should really be called when dealing with files with directories with */
1820 /* mixed qualities. see http://trac.osgeo.org/gdal/ticket/3539 */
1821 if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1823 if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
1824 suppress_quant_table(sp, 0);
1825 suppress_quant_table(sp, 1);
1828 unsuppress_quant_table(sp, 0);
1829 unsuppress_quant_table(sp, 1);
1831 if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
1833 /* Explicit suppression is only needed if we did not go through the */
1834 /* prepare_JPEGTables() code path, which may be the case if updating */
1835 /* an existing file */
1836 suppress_huff_table(sp, 0);
1837 suppress_huff_table(sp, 1);
1838 sp->cinfo.c.optimize_coding = FALSE;
1841 sp->cinfo.c.optimize_coding = TRUE;
1842 if (downsampled_input) {
1843 /* Need to use raw-data interface to libjpeg */
1844 sp->cinfo.c.raw_data_in = TRUE;
1845 tif->tif_encoderow = JPEGEncodeRaw;
1846 tif->tif_encodestrip = JPEGEncodeRaw;
1847 tif->tif_encodetile = JPEGEncodeRaw;
1849 /* Use normal interface to libjpeg */
1850 sp->cinfo.c.raw_data_in = FALSE;
1851 tif->tif_encoderow = JPEGEncode;
1852 tif->tif_encodestrip = JPEGEncode;
1853 tif->tif_encodetile = JPEGEncode;
1855 /* Start JPEG compressor */
1856 if (!TIFFjpeg_start_compress(sp, FALSE))
1858 /* Allocate downsampled-data buffers if needed */
1859 if (downsampled_input) {
1860 if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
1861 sp->cinfo.c.num_components))
1870 * Encode a chunk of pixels.
1871 * "Standard" case: incoming data is not downsampled.
1874 JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1876 JPEGState *sp = JState(tif);
1879 short *line16 = NULL;
1880 int line16_count = 0;
1884 /* data is expected to be supplied in multiples of a scanline */
1885 nrows = cc / sp->bytesperline;
1886 if (cc % sp->bytesperline)
1887 TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
1888 "fractional scanline discarded");
1890 /* The last strip will be limited to image size */
1891 if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
1892 nrows = tif->tif_dir.td_imagelength - tif->tif_row;
1894 if( sp->cinfo.c.data_precision == 12 )
1896 line16_count = (int)((sp->bytesperline * 2) / 3);
1897 line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
1900 TIFFErrorExt(tif->tif_clientdata,
1902 "Failed to allocate memory");
1908 while (nrows-- > 0) {
1910 if( sp->cinfo.c.data_precision == 12 )
1913 int value_pairs = line16_count / 2;
1916 bufptr[0] = (JSAMPROW) line16;
1918 for( iPair = 0; iPair < value_pairs; iPair++ )
1920 unsigned char *in_ptr =
1921 ((unsigned char *) buf) + iPair * 3;
1922 JSAMPLE *out_ptr = (JSAMPLE *) (line16 + iPair * 2);
1924 out_ptr[0] = (in_ptr[0] << 4) | ((in_ptr[1] & 0xf0) >> 4);
1925 out_ptr[1] = ((in_ptr[1] & 0x0f) << 8) | in_ptr[2];
1930 bufptr[0] = (JSAMPROW) buf;
1932 if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
1936 buf += sp->bytesperline;
1939 if( sp->cinfo.c.data_precision == 12 )
1941 _TIFFfree( line16 );
1948 * Encode a chunk of pixels.
1949 * Incoming data is expected to be downsampled per sampling factors.
1952 JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1954 JPEGState *sp = JState(tif);
1958 JDIMENSION clumps_per_line, nclump;
1959 int clumpoffset, ci, xpos, ypos;
1960 jpeg_component_info* compptr;
1961 int samples_per_clump = sp->samplesperclump;
1962 tmsize_t bytesperclumpline;
1966 /* data is expected to be supplied in multiples of a clumpline */
1967 /* a clumpline is equivalent to v_sampling desubsampled scanlines */
1968 /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
1969 bytesperclumpline = (((sp->cinfo.c.image_width+sp->h_sampling-1)/sp->h_sampling)
1970 *(sp->h_sampling*sp->v_sampling+2)*sp->cinfo.c.data_precision+7)
1973 nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
1974 if (cc % bytesperclumpline)
1975 TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
1977 /* Cb,Cr both have sampling factors 1, so this is correct */
1978 clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
1982 * Fastest way to separate the data is to make one pass
1983 * over the scanline for each row of each component.
1985 clumpoffset = 0; /* first sample in clump */
1986 for (ci = 0, compptr = sp->cinfo.c.comp_info;
1987 ci < sp->cinfo.c.num_components;
1989 int hsamp = compptr->h_samp_factor;
1990 int vsamp = compptr->v_samp_factor;
1991 int padding = (int) (compptr->width_in_blocks * DCTSIZE -
1992 clumps_per_line * hsamp);
1993 for (ypos = 0; ypos < vsamp; ypos++) {
1994 inptr = ((JSAMPLE*) buf) + clumpoffset;
1995 outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1997 /* fast path for at least Cb and Cr */
1998 for (nclump = clumps_per_line; nclump-- > 0; ) {
1999 *outptr++ = inptr[0];
2000 inptr += samples_per_clump;
2004 for (nclump = clumps_per_line; nclump-- > 0; ) {
2005 for (xpos = 0; xpos < hsamp; xpos++)
2006 *outptr++ = inptr[xpos];
2007 inptr += samples_per_clump;
2010 /* pad each scanline as needed */
2011 for (xpos = 0; xpos < padding; xpos++) {
2012 *outptr = outptr[-1];
2015 clumpoffset += hsamp;
2019 if (sp->scancount >= DCTSIZE) {
2020 int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
2021 if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
2025 tif->tif_row += sp->v_sampling;
2026 buf += bytesperclumpline;
2027 nrows -= sp->v_sampling;
2033 * Finish up at the end of a strip or tile.
2036 JPEGPostEncode(TIFF* tif)
2038 JPEGState *sp = JState(tif);
2040 if (sp->scancount > 0) {
2042 * Need to emit a partial bufferload of downsampled data.
2043 * Pad the data vertically.
2046 jpeg_component_info* compptr;
2048 for (ci = 0, compptr = sp->cinfo.c.comp_info;
2049 ci < sp->cinfo.c.num_components;
2051 int vsamp = compptr->v_samp_factor;
2052 tmsize_t row_width = compptr->width_in_blocks * DCTSIZE
2054 for (ypos = sp->scancount * vsamp;
2055 ypos < DCTSIZE * vsamp; ypos++) {
2056 _TIFFmemcpy((void*)sp->ds_buffer[ci][ypos],
2057 (void*)sp->ds_buffer[ci][ypos-1],
2062 n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
2063 if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
2067 return (TIFFjpeg_finish_compress(JState(tif)));
2071 JPEGCleanup(TIFF* tif)
2073 JPEGState *sp = JState(tif);
2077 tif->tif_tagmethods.vgetfield = sp->vgetparent;
2078 tif->tif_tagmethods.vsetfield = sp->vsetparent;
2079 tif->tif_tagmethods.printdir = sp->printdir;
2080 if( sp->cinfo_initialized )
2081 TIFFjpeg_destroy(sp); /* release libjpeg resources */
2082 if (sp->jpegtables) /* tag value */
2083 _TIFFfree(sp->jpegtables);
2084 _TIFFfree(tif->tif_data); /* release local state */
2085 tif->tif_data = NULL;
2087 _TIFFSetDefaultCompressionState(tif);
2091 JPEGResetUpsampled( TIFF* tif )
2093 JPEGState* sp = JState(tif);
2094 TIFFDirectory* td = &tif->tif_dir;
2097 * Mark whether returned data is up-sampled or not so TIFFStripSize
2098 * and TIFFTileSize return values that reflect the true amount of
2101 tif->tif_flags &= ~TIFF_UPSAMPLED;
2102 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
2103 if (td->td_photometric == PHOTOMETRIC_YCBCR &&
2104 sp->jpegcolormode == JPEGCOLORMODE_RGB) {
2105 tif->tif_flags |= TIFF_UPSAMPLED;
2108 if (td->td_ycbcrsubsampling[0] != 1 ||
2109 td->td_ycbcrsubsampling[1] != 1)
2110 ; /* XXX what about up-sampling? */
2116 * Must recalculate cached tile size in case sampling state changed.
2117 * Should we really be doing this now if image size isn't set?
2119 if( tif->tif_tilesize > 0 )
2120 tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
2121 if( tif->tif_scanlinesize > 0 )
2122 tif->tif_scanlinesize = TIFFScanlineSize(tif);
2126 JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
2128 JPEGState* sp = JState(tif);
2129 const TIFFField* fip;
2135 case TIFFTAG_JPEGTABLES:
2136 v32 = (uint32) va_arg(ap, uint32);
2141 _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*), v32);
2142 sp->jpegtables_length = v32;
2143 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2145 case TIFFTAG_JPEGQUALITY:
2146 sp->jpegquality = (int) va_arg(ap, int);
2147 return (1); /* pseudo tag */
2148 case TIFFTAG_JPEGCOLORMODE:
2149 sp->jpegcolormode = (int) va_arg(ap, int);
2150 JPEGResetUpsampled( tif );
2151 return (1); /* pseudo tag */
2152 case TIFFTAG_PHOTOMETRIC:
2154 int ret_value = (*sp->vsetparent)(tif, tag, ap);
2155 JPEGResetUpsampled( tif );
2158 case TIFFTAG_JPEGTABLESMODE:
2159 sp->jpegtablesmode = (int) va_arg(ap, int);
2160 return (1); /* pseudo tag */
2161 case TIFFTAG_YCBCRSUBSAMPLING:
2162 /* mark the fact that we have a real ycbcrsubsampling! */
2163 sp->ycbcrsampling_fetched = 1;
2164 /* should we be recomputing upsampling info here? */
2165 return (*sp->vsetparent)(tif, tag, ap);
2167 return (*sp->vsetparent)(tif, tag, ap);
2170 if ((fip = TIFFFieldWithTag(tif, tag)) != NULL) {
2171 TIFFSetFieldBit(tif, fip->field_bit);
2176 tif->tif_flags |= TIFF_DIRTYDIRECT;
2181 JPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
2183 JPEGState* sp = JState(tif);
2188 case TIFFTAG_JPEGTABLES:
2189 *va_arg(ap, uint32*) = sp->jpegtables_length;
2190 *va_arg(ap, void**) = sp->jpegtables;
2192 case TIFFTAG_JPEGQUALITY:
2193 *va_arg(ap, int*) = sp->jpegquality;
2195 case TIFFTAG_JPEGCOLORMODE:
2196 *va_arg(ap, int*) = sp->jpegcolormode;
2198 case TIFFTAG_JPEGTABLESMODE:
2199 *va_arg(ap, int*) = sp->jpegtablesmode;
2202 return (*sp->vgetparent)(tif, tag, ap);
2208 JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
2210 JPEGState* sp = JState(tif);
2216 if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
2217 fprintf(fd, " JPEG Tables: (%lu bytes)\n",
2218 (unsigned long) sp->jpegtables_length);
2220 (*sp->printdir)(tif, fd, flags);
2225 JPEGDefaultStripSize(TIFF* tif, uint32 s)
2227 JPEGState* sp = JState(tif);
2228 TIFFDirectory *td = &tif->tif_dir;
2230 s = (*sp->defsparent)(tif, s);
2231 if (s < td->td_imagelength)
2232 s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
2237 JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
2239 JPEGState* sp = JState(tif);
2240 TIFFDirectory *td = &tif->tif_dir;
2242 (*sp->deftparent)(tif, tw, th);
2243 *tw = TIFFroundup_32(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
2244 *th = TIFFroundup_32(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
2248 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
2249 * now that we allow a TIFF file to be opened in update mode it is necessary
2250 * to have some way of deciding whether compression or decompression is
2251 * desired other than looking at tif->tif_mode. We accomplish this by
2252 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
2253 * If so, we assume decompression is desired.
2255 * This is tricky, because TIFFInitJPEG() is called while the directory is
2256 * being read, and generally speaking the BYTECOUNTS tag won't have been read
2257 * at that point. So we try to defer jpeg library initialization till we
2258 * do have that tag ... basically any access that might require the compressor
2259 * or decompressor that occurs after the reading of the directory.
2261 * In an ideal world compressors or decompressors would be setup
2262 * at the point where a single tile or strip was accessed (for read or write)
2263 * so that stuff like update of missing tiles, or replacement of tiles could
2264 * be done. However, we aren't trying to crack that nut just yet ...
2266 * NFW, Feb 3rd, 2003.
2269 static int JPEGInitializeLibJPEG( TIFF * tif, int decompress )
2271 JPEGState* sp = JState(tif);
2273 if(sp->cinfo_initialized)
2275 if( !decompress && sp->cinfo.comm.is_decompressor )
2276 TIFFjpeg_destroy( sp );
2277 else if( decompress && !sp->cinfo.comm.is_decompressor )
2278 TIFFjpeg_destroy( sp );
2282 sp->cinfo_initialized = 0;
2286 * Initialize libjpeg.
2289 if (!TIFFjpeg_create_decompress(sp))
2292 if (!TIFFjpeg_create_compress(sp))
2296 sp->cinfo_initialized = TRUE;
2302 TIFFInitJPEG(TIFF* tif, int scheme)
2306 assert(scheme == COMPRESSION_JPEG);
2309 * Merge codec-specific tag information.
2311 if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields))) {
2312 TIFFErrorExt(tif->tif_clientdata,
2314 "Merging JPEG codec-specific tags failed");
2319 * Allocate state block so tag methods have storage to record values.
2321 tif->tif_data = (uint8*) _TIFFmalloc(sizeof (JPEGState));
2323 if (tif->tif_data == NULL) {
2324 TIFFErrorExt(tif->tif_clientdata,
2325 "TIFFInitJPEG", "No space for JPEG state block");
2328 _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
2331 sp->tif = tif; /* back link */
2334 * Override parent get/set field methods.
2336 sp->vgetparent = tif->tif_tagmethods.vgetfield;
2337 tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
2338 sp->vsetparent = tif->tif_tagmethods.vsetfield;
2339 tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
2340 sp->printdir = tif->tif_tagmethods.printdir;
2341 tif->tif_tagmethods.printdir = JPEGPrintDir; /* hook for codec tags */
2343 /* Default values for codec-specific fields */
2344 sp->jpegtables = NULL;
2345 sp->jpegtables_length = 0;
2346 sp->jpegquality = 75; /* Default IJG quality */
2347 sp->jpegcolormode = JPEGCOLORMODE_RAW;
2348 sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
2349 sp->ycbcrsampling_fetched = 0;
2352 * Install codec methods.
2354 tif->tif_fixuptags = JPEGFixupTags;
2355 tif->tif_setupdecode = JPEGSetupDecode;
2356 tif->tif_predecode = JPEGPreDecode;
2357 tif->tif_decoderow = JPEGDecode;
2358 tif->tif_decodestrip = JPEGDecode;
2359 tif->tif_decodetile = JPEGDecode;
2360 tif->tif_setupencode = JPEGSetupEncode;
2361 tif->tif_preencode = JPEGPreEncode;
2362 tif->tif_postencode = JPEGPostEncode;
2363 tif->tif_encoderow = JPEGEncode;
2364 tif->tif_encodestrip = JPEGEncode;
2365 tif->tif_encodetile = JPEGEncode;
2366 tif->tif_cleanup = JPEGCleanup;
2367 sp->defsparent = tif->tif_defstripsize;
2368 tif->tif_defstripsize = JPEGDefaultStripSize;
2369 sp->deftparent = tif->tif_deftilesize;
2370 tif->tif_deftilesize = JPEGDefaultTileSize;
2371 tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
2373 sp->cinfo_initialized = FALSE;
2376 ** Create a JPEGTables field if no directory has yet been created.
2377 ** We do this just to ensure that sufficient space is reserved for
2378 ** the JPEGTables field. It will be properly created the right
2381 if( tif->tif_diroff == 0 )
2383 #define SIZE_OF_JPEGTABLES 2000
2385 The following line assumes incorrectly that all JPEG-in-TIFF files will have
2386 a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
2387 when the JPEG data is placed with TIFFWriteRawStrip. The field bit should be
2388 set, anyway, later when actual JPEGTABLES header is generated, so removing it
2389 here hopefully is harmless.
2390 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2392 sp->jpegtables_length = SIZE_OF_JPEGTABLES;
2393 sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
2396 _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
2400 TIFFErrorExt(tif->tif_clientdata,
2402 "Failed to allocate memory for JPEG tables");
2405 #undef SIZE_OF_JPEGTABLES
2410 #endif /* JPEG_SUPPORT */
2412 /* vim: set ts=8 sts=8 sw=8 noet: */