3 * Copyright (c) 1994-1997 Sam Leffler
4 * Copyright (c) 1994-1997 Silicon Graphics, Inc.
6 * Permission to use, copy, modify, distribute, and sell this software and
7 * its documentation for any purpose is hereby granted without fee, provided
8 * that (i) the above copyright notices and this permission notice appear in
9 * all copies of the software and related documentation, and (ii) the names of
10 * Sam Leffler and Silicon Graphics may not be used in any advertising or
11 * publicity relating to the software without the specific, prior written
12 * permission of Sam Leffler and Silicon Graphics.
14 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
16 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
18 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
19 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
20 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
21 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
22 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
26 #define WIN32_LEAN_AND_MEAN
35 * JPEG Compression support per TIFF Technical Note #2
36 * (*not* per the original TIFF 6.0 spec).
38 * This file is simply an interface to the libjpeg library written by
39 * the Independent JPEG Group. You need release 5 or later of the IJG
40 * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
42 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
46 int TIFFFillStrip(TIFF
* tif
, uint32 strip
);
47 int TIFFFillTile(TIFF
* tif
, uint32 tile
);
48 int TIFFReInitJPEG_12( TIFF
*tif
, int scheme
, int is_encode
);
50 /* We undefine FAR to avoid conflict with JPEG definition */
57 Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
58 not defined. Unfortunately, the MinGW and Borland compilers include
59 a typedef for INT32, which causes a conflict. MSVC does not include
60 a conficting typedef given the headers which are included.
62 #if defined(__BORLANDC__) || defined(__MINGW32__)
67 The windows RPCNDR.H file defines boolean, but defines it with the
68 unsigned char size. You should compile JPEG library using appropriate
69 definitions in jconfig.h header, but many users compile library in wrong
70 way. That causes errors of the following type:
72 "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
75 For such users we wil fix the problem here. See install.doc file from
76 the JPEG library distribution for details.
79 /* Define "boolean" as unsigned char, not int, per Windows custom. */
80 #if defined(__WIN32__) && !defined(__MINGW32__)
81 # ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
82 typedef unsigned char boolean
;
84 # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
91 #define boolean wxHACK_BOOLEAN
97 #ifndef HAVE_WXJPEG_BOOLEAN
98 typedef boolean wxjpeg_boolean
;
102 * Do we want to do special processing suitable for when JSAMPLE is a
106 #if defined(JPEG_LIB_MK1)
107 # define JPEG_LIB_MK1_OR_12BIT 1
108 #elif BITS_IN_JSAMPLE == 12
109 # define JPEG_LIB_MK1_OR_12BIT 1
113 * We are using width_in_blocks which is supposed to be private to
114 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
115 * renamed this member to width_in_data_units. Since the header has
116 * also renamed a define, use that unique define name in order to
117 * detect the problem header and adjust to suit.
119 #if defined(D_MAX_DATA_UNITS_IN_MCU)
120 #define width_in_blocks width_in_data_units
124 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
125 * in place of plain setjmp. These macros will make it easier.
127 #define SETJMP(jbuf) setjmp(jbuf)
128 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
129 #define JMP_BUF jmp_buf
131 typedef struct jpeg_destination_mgr jpeg_destination_mgr
;
132 typedef struct jpeg_source_mgr jpeg_source_mgr
;
133 typedef struct jpeg_error_mgr jpeg_error_mgr
;
136 * State block for each open TIFF file using
137 * libjpeg to do JPEG compression/decompression.
139 * libjpeg's visible state is either a jpeg_compress_struct
140 * or jpeg_decompress_struct depending on which way we
141 * are going. comm can be used to refer to the fields
142 * which are common to both.
144 * NB: cinfo is required to be the first member of JPEGState,
145 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
150 struct jpeg_compress_struct c
;
151 struct jpeg_decompress_struct d
;
152 struct jpeg_common_struct comm
;
153 } cinfo
; /* NB: must be first */
154 int cinfo_initialized
;
156 jpeg_error_mgr err
; /* libjpeg error manager */
157 JMP_BUF exit_jmpbuf
; /* for catching libjpeg failures */
159 * The following two members could be a union, but
160 * they're small enough that it's not worth the effort.
162 jpeg_destination_mgr dest
; /* data dest for compression */
163 jpeg_source_mgr src
; /* data source for decompression */
165 TIFF
* tif
; /* back link needed by some code */
166 uint16 photometric
; /* copy of PhotometricInterpretation */
167 uint16 h_sampling
; /* luminance sampling factors */
169 tmsize_t bytesperline
; /* decompressed bytes per scanline */
170 /* pointers to intermediate buffers when processing downsampled data */
171 JSAMPARRAY ds_buffer
[MAX_COMPONENTS
];
172 int scancount
; /* number of "scanlines" accumulated */
175 TIFFVGetMethod vgetparent
; /* super-class method */
176 TIFFVSetMethod vsetparent
; /* super-class method */
177 TIFFPrintMethod printdir
; /* super-class method */
178 TIFFStripMethod defsparent
; /* super-class method */
179 TIFFTileMethod deftparent
; /* super-class method */
180 /* pseudo-tag fields */
181 void* jpegtables
; /* JPEGTables tag value, or NULL */
182 uint32 jpegtables_length
; /* number of bytes in same */
183 int jpegquality
; /* Compression quality level */
184 int jpegcolormode
; /* Auto RGB<=>YCbCr convert? */
185 int jpegtablesmode
; /* What to put in JPEGTables */
187 int ycbcrsampling_fetched
;
190 #define JState(tif) ((JPEGState*)(tif)->tif_data)
192 static int JPEGDecode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
193 static int JPEGDecodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
194 static int JPEGEncode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
195 static int JPEGEncodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
196 static int JPEGInitializeLibJPEG(TIFF
* tif
, int decode
);
197 static int DecodeRowError(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
199 #define FIELD_JPEGTABLES (FIELD_CODEC+0)
201 static const TIFFField jpegFields
[] = {
202 { TIFFTAG_JPEGTABLES
, -3, -3, TIFF_UNDEFINED
, 0, TIFF_SETGET_C32_UINT8
, TIFF_SETGET_C32_UINT8
, FIELD_JPEGTABLES
, FALSE
, TRUE
, "JPEGTables", NULL
},
203 { TIFFTAG_JPEGQUALITY
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, TRUE
, FALSE
, "", NULL
},
204 { TIFFTAG_JPEGCOLORMODE
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, FALSE
, FALSE
, "", NULL
},
205 { TIFFTAG_JPEGTABLESMODE
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, FALSE
, FALSE
, "", NULL
}
209 * libjpeg interface layer.
211 * We use setjmp/longjmp to return control to libtiff
212 * when a fatal error is encountered within the JPEG
213 * library. We also direct libjpeg error and warning
214 * messages through the appropriate libtiff handlers.
218 * Error handling routines (these replace corresponding
219 * IJG routines from jerror.c). These are used for both
220 * compression and decompression.
223 TIFFjpeg_error_exit(j_common_ptr cinfo
)
225 JPEGState
*sp
= (JPEGState
*) cinfo
; /* NB: cinfo assumed first */
226 char buffer
[JMSG_LENGTH_MAX
];
228 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
229 TIFFErrorExt(sp
->tif
->tif_clientdata
, "JPEGLib", "%s", buffer
); /* display the error message */
230 jpeg_abort(cinfo
); /* clean up libjpeg state */
231 LONGJMP(sp
->exit_jmpbuf
, 1); /* return to libtiff caller */
235 * This routine is invoked only for warning messages,
236 * since error_exit does its own thing and trace_level
240 TIFFjpeg_output_message(j_common_ptr cinfo
)
242 char buffer
[JMSG_LENGTH_MAX
];
244 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
245 TIFFWarningExt(((JPEGState
*) cinfo
)->tif
->tif_clientdata
, "JPEGLib", "%s", buffer
);
249 * Interface routines. This layer of routines exists
250 * primarily to limit side-effects from using setjmp.
251 * Also, normal/error returns are converted into return
252 * values per libtiff practice.
254 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
255 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
258 TIFFjpeg_create_compress(JPEGState
* sp
)
260 /* initialize JPEG error handling */
261 sp
->cinfo
.c
.err
= jpeg_std_error(&sp
->err
);
262 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
263 sp
->err
.output_message
= TIFFjpeg_output_message
;
265 return CALLVJPEG(sp
, jpeg_create_compress(&sp
->cinfo
.c
));
269 TIFFjpeg_create_decompress(JPEGState
* sp
)
271 /* initialize JPEG error handling */
272 sp
->cinfo
.d
.err
= jpeg_std_error(&sp
->err
);
273 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
274 sp
->err
.output_message
= TIFFjpeg_output_message
;
276 return CALLVJPEG(sp
, jpeg_create_decompress(&sp
->cinfo
.d
));
280 TIFFjpeg_set_defaults(JPEGState
* sp
)
282 return CALLVJPEG(sp
, jpeg_set_defaults(&sp
->cinfo
.c
));
286 TIFFjpeg_set_colorspace(JPEGState
* sp
, J_COLOR_SPACE colorspace
)
288 return CALLVJPEG(sp
, jpeg_set_colorspace(&sp
->cinfo
.c
, colorspace
));
292 TIFFjpeg_set_quality(JPEGState
* sp
, int quality
, wxjpeg_boolean force_baseline
)
295 jpeg_set_quality(&sp
->cinfo
.c
, quality
, force_baseline
));
299 TIFFjpeg_suppress_tables(JPEGState
* sp
, wxjpeg_boolean suppress
)
301 return CALLVJPEG(sp
, jpeg_suppress_tables(&sp
->cinfo
.c
, suppress
));
305 TIFFjpeg_start_compress(JPEGState
* sp
, wxjpeg_boolean write_all_tables
)
308 jpeg_start_compress(&sp
->cinfo
.c
, write_all_tables
));
312 TIFFjpeg_write_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int num_lines
)
314 return CALLJPEG(sp
, -1, (int) jpeg_write_scanlines(&sp
->cinfo
.c
,
315 scanlines
, (JDIMENSION
) num_lines
));
319 TIFFjpeg_write_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int num_lines
)
321 return CALLJPEG(sp
, -1, (int) jpeg_write_raw_data(&sp
->cinfo
.c
,
322 data
, (JDIMENSION
) num_lines
));
326 TIFFjpeg_finish_compress(JPEGState
* sp
)
328 return CALLVJPEG(sp
, jpeg_finish_compress(&sp
->cinfo
.c
));
332 TIFFjpeg_write_tables(JPEGState
* sp
)
334 return CALLVJPEG(sp
, jpeg_write_tables(&sp
->cinfo
.c
));
338 TIFFjpeg_read_header(JPEGState
* sp
, wxjpeg_boolean require_image
)
340 return CALLJPEG(sp
, -1, jpeg_read_header(&sp
->cinfo
.d
, require_image
));
344 TIFFjpeg_start_decompress(JPEGState
* sp
)
346 return CALLVJPEG(sp
, jpeg_start_decompress(&sp
->cinfo
.d
));
350 TIFFjpeg_read_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int max_lines
)
352 return CALLJPEG(sp
, -1, (int) jpeg_read_scanlines(&sp
->cinfo
.d
,
353 scanlines
, (JDIMENSION
) max_lines
));
357 TIFFjpeg_read_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int max_lines
)
359 return CALLJPEG(sp
, -1, (int) jpeg_read_raw_data(&sp
->cinfo
.d
,
360 data
, (JDIMENSION
) max_lines
));
364 TIFFjpeg_finish_decompress(JPEGState
* sp
)
366 return CALLJPEG(sp
, -1, (int) jpeg_finish_decompress(&sp
->cinfo
.d
));
370 TIFFjpeg_abort(JPEGState
* sp
)
372 return CALLVJPEG(sp
, jpeg_abort(&sp
->cinfo
.comm
));
376 TIFFjpeg_destroy(JPEGState
* sp
)
378 return CALLVJPEG(sp
, jpeg_destroy(&sp
->cinfo
.comm
));
382 TIFFjpeg_alloc_sarray(JPEGState
* sp
, int pool_id
,
383 JDIMENSION samplesperrow
, JDIMENSION numrows
)
385 return CALLJPEG(sp
, (JSAMPARRAY
) NULL
,
386 (*sp
->cinfo
.comm
.mem
->alloc_sarray
)
387 (&sp
->cinfo
.comm
, pool_id
, samplesperrow
, numrows
));
391 * JPEG library destination data manager.
392 * These routines direct compressed data from libjpeg into the
393 * libtiff output buffer.
397 std_init_destination(j_compress_ptr cinfo
)
399 JPEGState
* sp
= (JPEGState
*) cinfo
;
402 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
403 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
406 static wxjpeg_boolean
407 std_empty_output_buffer(j_compress_ptr cinfo
)
409 JPEGState
* sp
= (JPEGState
*) cinfo
;
412 /* the entire buffer has been filled */
413 tif
->tif_rawcc
= tif
->tif_rawdatasize
;
417 * The Intel IPP performance library does not necessarily fill up
418 * the whole output buffer on each pass, so only dump out the parts
419 * that have been filled.
420 * http://trac.osgeo.org/gdal/wiki/JpegIPP
422 if ( sp
->dest
.free_in_buffer
>= 0 ) {
423 tif
->tif_rawcc
= tif
->tif_rawdatasize
- sp
->dest
.free_in_buffer
;
428 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
429 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
435 std_term_destination(j_compress_ptr cinfo
)
437 JPEGState
* sp
= (JPEGState
*) cinfo
;
440 tif
->tif_rawcp
= (uint8
*) sp
->dest
.next_output_byte
;
442 tif
->tif_rawdatasize
- (tmsize_t
) sp
->dest
.free_in_buffer
;
443 /* NB: libtiff does the final buffer flush */
447 TIFFjpeg_data_dest(JPEGState
* sp
, TIFF
* tif
)
450 sp
->cinfo
.c
.dest
= &sp
->dest
;
451 sp
->dest
.init_destination
= std_init_destination
;
452 sp
->dest
.empty_output_buffer
= std_empty_output_buffer
;
453 sp
->dest
.term_destination
= std_term_destination
;
457 * Alternate destination manager for outputting to JPEGTables field.
461 tables_init_destination(j_compress_ptr cinfo
)
463 JPEGState
* sp
= (JPEGState
*) cinfo
;
465 /* while building, jpegtables_length is allocated buffer size */
466 sp
->dest
.next_output_byte
= (JOCTET
*) sp
->jpegtables
;
467 sp
->dest
.free_in_buffer
= (size_t) sp
->jpegtables_length
;
470 static wxjpeg_boolean
471 tables_empty_output_buffer(j_compress_ptr cinfo
)
473 JPEGState
* sp
= (JPEGState
*) cinfo
;
476 /* the entire buffer has been filled; enlarge it by 1000 bytes */
477 newbuf
= _TIFFrealloc((void*) sp
->jpegtables
,
478 (tmsize_t
) (sp
->jpegtables_length
+ 1000));
480 ERREXIT1(cinfo
, JERR_OUT_OF_MEMORY
, 100);
481 sp
->dest
.next_output_byte
= (JOCTET
*) newbuf
+ sp
->jpegtables_length
;
482 sp
->dest
.free_in_buffer
= (size_t) 1000;
483 sp
->jpegtables
= newbuf
;
484 sp
->jpegtables_length
+= 1000;
489 tables_term_destination(j_compress_ptr cinfo
)
491 JPEGState
* sp
= (JPEGState
*) cinfo
;
493 /* set tables length to number of bytes actually emitted */
494 sp
->jpegtables_length
-= (uint32
) sp
->dest
.free_in_buffer
;
498 TIFFjpeg_tables_dest(JPEGState
* sp
, TIFF
* tif
)
502 * Allocate a working buffer for building tables.
503 * Initial size is 1000 bytes, which is usually adequate.
506 _TIFFfree(sp
->jpegtables
);
507 sp
->jpegtables_length
= 1000;
508 sp
->jpegtables
= (void*) _TIFFmalloc((tmsize_t
) sp
->jpegtables_length
);
509 if (sp
->jpegtables
== NULL
) {
510 sp
->jpegtables_length
= 0;
511 TIFFErrorExt(sp
->tif
->tif_clientdata
, "TIFFjpeg_tables_dest", "No space for JPEGTables");
514 sp
->cinfo
.c
.dest
= &sp
->dest
;
515 sp
->dest
.init_destination
= tables_init_destination
;
516 sp
->dest
.empty_output_buffer
= tables_empty_output_buffer
;
517 sp
->dest
.term_destination
= tables_term_destination
;
522 * JPEG library source data manager.
523 * These routines supply compressed data to libjpeg.
527 std_init_source(j_decompress_ptr cinfo
)
529 JPEGState
* sp
= (JPEGState
*) cinfo
;
532 sp
->src
.next_input_byte
= (const JOCTET
*) tif
->tif_rawdata
;
533 sp
->src
.bytes_in_buffer
= (size_t) tif
->tif_rawcc
;
536 static wxjpeg_boolean
537 std_fill_input_buffer(j_decompress_ptr cinfo
)
539 JPEGState
* sp
= (JPEGState
* ) cinfo
;
540 static const JOCTET dummy_EOI
[2] = { 0xFF, JPEG_EOI
};
544 * The Intel IPP performance library does not necessarily read the whole
545 * input buffer in one pass, so it is possible to get here with data
548 * We just return without doing anything, until the entire buffer has
550 * http://trac.osgeo.org/gdal/wiki/JpegIPP
552 if( sp
->src
.bytes_in_buffer
> 0 ) {
558 * Normally the whole strip/tile is read and so we don't need to do
559 * a fill. In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
560 * all the data, but the rawdata is refreshed between scanlines and
561 * we push this into the io machinery in JPEGDecode().
562 * http://trac.osgeo.org/gdal/ticket/3894
565 WARNMS(cinfo
, JWRN_JPEG_EOF
);
566 /* insert a fake EOI marker */
567 sp
->src
.next_input_byte
= dummy_EOI
;
568 sp
->src
.bytes_in_buffer
= 2;
573 std_skip_input_data(j_decompress_ptr cinfo
, long num_bytes
)
575 JPEGState
* sp
= (JPEGState
*) cinfo
;
578 if ((size_t)num_bytes
> sp
->src
.bytes_in_buffer
) {
579 /* oops, buffer overrun */
580 (void) std_fill_input_buffer(cinfo
);
582 sp
->src
.next_input_byte
+= (size_t) num_bytes
;
583 sp
->src
.bytes_in_buffer
-= (size_t) num_bytes
;
589 std_term_source(j_decompress_ptr cinfo
)
591 /* No work necessary here */
596 TIFFjpeg_data_src(JPEGState
* sp
, TIFF
* tif
)
599 sp
->cinfo
.d
.src
= &sp
->src
;
600 sp
->src
.init_source
= std_init_source
;
601 sp
->src
.fill_input_buffer
= std_fill_input_buffer
;
602 sp
->src
.skip_input_data
= std_skip_input_data
;
603 sp
->src
.resync_to_restart
= jpeg_resync_to_restart
;
604 sp
->src
.term_source
= std_term_source
;
605 sp
->src
.bytes_in_buffer
= 0; /* for safety */
606 sp
->src
.next_input_byte
= NULL
;
610 * Alternate source manager for reading from JPEGTables.
611 * We can share all the code except for the init routine.
615 tables_init_source(j_decompress_ptr cinfo
)
617 JPEGState
* sp
= (JPEGState
*) cinfo
;
619 sp
->src
.next_input_byte
= (const JOCTET
*) sp
->jpegtables
;
620 sp
->src
.bytes_in_buffer
= (size_t) sp
->jpegtables_length
;
624 TIFFjpeg_tables_src(JPEGState
* sp
, TIFF
* tif
)
626 TIFFjpeg_data_src(sp
, tif
);
627 sp
->src
.init_source
= tables_init_source
;
631 * Allocate downsampled-data buffers needed for downsampled I/O.
632 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
633 * We use libjpeg's allocator so that buffers will be released automatically
634 * when done with strip/tile.
635 * This is also a handy place to compute samplesperclump, bytesperline.
638 alloc_downsampled_buffers(TIFF
* tif
, jpeg_component_info
* comp_info
,
641 JPEGState
* sp
= JState(tif
);
643 jpeg_component_info
* compptr
;
645 int samples_per_clump
= 0;
647 for (ci
= 0, compptr
= comp_info
; ci
< num_components
;
649 samples_per_clump
+= compptr
->h_samp_factor
*
650 compptr
->v_samp_factor
;
651 buf
= TIFFjpeg_alloc_sarray(sp
, JPOOL_IMAGE
,
652 compptr
->width_in_blocks
* DCTSIZE
,
653 (JDIMENSION
) (compptr
->v_samp_factor
*DCTSIZE
));
656 sp
->ds_buffer
[ci
] = buf
;
658 sp
->samplesperclump
= samples_per_clump
;
667 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
669 #define JPEG_MARKER_SOF0 0xC0
670 #define JPEG_MARKER_SOF1 0xC1
671 #define JPEG_MARKER_SOF3 0xC3
672 #define JPEG_MARKER_DHT 0xC4
673 #define JPEG_MARKER_SOI 0xD8
674 #define JPEG_MARKER_SOS 0xDA
675 #define JPEG_MARKER_DQT 0xDB
676 #define JPEG_MARKER_DRI 0xDD
677 #define JPEG_MARKER_APP0 0xE0
678 #define JPEG_MARKER_COM 0xFE
679 struct JPEGFixupTagsSubsamplingData
684 uint8
* buffercurrentbyte
;
685 uint32 bufferbytesleft
;
687 uint64 filebytesleft
;
688 uint8 filepositioned
;
690 static void JPEGFixupTagsSubsampling(TIFF
* tif
);
691 static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData
* data
);
692 static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData
* data
, uint8
* result
);
693 static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData
* data
, uint16
* result
);
694 static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData
* data
, uint16 skiplength
);
699 JPEGFixupTags(TIFF
* tif
)
701 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
702 if ((tif
->tif_dir
.td_photometric
==PHOTOMETRIC_YCBCR
)&&
703 (tif
->tif_dir
.td_planarconfig
==PLANARCONFIG_CONTIG
)&&
704 (tif
->tif_dir
.td_samplesperpixel
==3))
705 JPEGFixupTagsSubsampling(tif
);
711 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
714 JPEGFixupTagsSubsampling(TIFF
* tif
)
717 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
718 * the TIFF tags, but still use non-default (2,2) values within the jpeg
719 * data stream itself. In order for TIFF applications to work properly
720 * - for instance to get the strip buffer size right - it is imperative
721 * that the subsampling be available before we start reading the image
722 * data normally. This function will attempt to analyze the first strip in
723 * order to get the sampling values from the jpeg data stream.
725 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
726 * discovered sampling does not match the default sampling (2,2) or whatever
727 * was actually in the tiff tags.
729 * See the bug in bugzilla for details:
731 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
733 * Frank Warmerdam, July 2002
734 * Joris Van Damme, May 2007
736 static const char module[] = "JPEGFixupTagsSubsampling";
737 struct JPEGFixupTagsSubsamplingData m
;
739 _TIFFFillStriles( tif
);
741 if( tif
->tif_dir
.td_stripbytecount
== NULL
742 || tif
->tif_dir
.td_stripbytecount
[0] == 0 )
744 /* Do not even try to check if the first strip/tile does not
745 yet exist, as occurs when GDAL has created a new NULL file
752 m
.buffer
=_TIFFmalloc(m
.buffersize
);
755 TIFFWarningExt(tif
->tif_clientdata
,module,
756 "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
759 m
.buffercurrentbyte
=NULL
;
761 m
.fileoffset
=tif
->tif_dir
.td_stripoffset
[0];
763 m
.filebytesleft
=tif
->tif_dir
.td_stripbytecount
[0];
764 if (!JPEGFixupTagsSubsamplingSec(&m
))
765 TIFFWarningExt(tif
->tif_clientdata
,module,
766 "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
771 JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData
* data
)
773 static const char module[] = "JPEGFixupTagsSubsamplingSec";
779 if (!JPEGFixupTagsSubsamplingReadByte(data
,&m
))
786 if (!JPEGFixupTagsSubsamplingReadByte(data
,&m
))
793 case JPEG_MARKER_SOI
:
794 /* this type of marker has no data and should be skipped */
796 case JPEG_MARKER_COM
:
797 case JPEG_MARKER_APP0
:
798 case JPEG_MARKER_APP0
+1:
799 case JPEG_MARKER_APP0
+2:
800 case JPEG_MARKER_APP0
+3:
801 case JPEG_MARKER_APP0
+4:
802 case JPEG_MARKER_APP0
+5:
803 case JPEG_MARKER_APP0
+6:
804 case JPEG_MARKER_APP0
+7:
805 case JPEG_MARKER_APP0
+8:
806 case JPEG_MARKER_APP0
+9:
807 case JPEG_MARKER_APP0
+10:
808 case JPEG_MARKER_APP0
+11:
809 case JPEG_MARKER_APP0
+12:
810 case JPEG_MARKER_APP0
+13:
811 case JPEG_MARKER_APP0
+14:
812 case JPEG_MARKER_APP0
+15:
813 case JPEG_MARKER_DQT
:
814 case JPEG_MARKER_SOS
:
815 case JPEG_MARKER_DHT
:
816 case JPEG_MARKER_DRI
:
817 /* this type of marker has data, but it has no use to us and should be skipped */
820 if (!JPEGFixupTagsSubsamplingReadWord(data
,&n
))
826 JPEGFixupTagsSubsamplingSkip(data
,n
);
829 case JPEG_MARKER_SOF0
:
830 case JPEG_MARKER_SOF1
:
831 /* this marker contains the subsampling factors we're scanning for */
837 if (!JPEGFixupTagsSubsamplingReadWord(data
,&n
))
839 if (n
!=8+data
->tif
->tif_dir
.td_samplesperpixel
*3)
841 JPEGFixupTagsSubsamplingSkip(data
,7);
842 if (!JPEGFixupTagsSubsamplingReadByte(data
,&p
))
846 JPEGFixupTagsSubsamplingSkip(data
,1);
847 for (o
=1; o
<data
->tif
->tif_dir
.td_samplesperpixel
; o
++)
849 JPEGFixupTagsSubsamplingSkip(data
,1);
850 if (!JPEGFixupTagsSubsamplingReadByte(data
,&p
))
854 TIFFWarningExt(data
->tif
->tif_clientdata
,module,
855 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
858 JPEGFixupTagsSubsamplingSkip(data
,1);
860 if (((ph
!=1)&&(ph
!=2)&&(ph
!=4))||((pv
!=1)&&(pv
!=2)&&(pv
!=4)))
862 TIFFWarningExt(data
->tif
->tif_clientdata
,module,
863 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
866 if ((ph
!=data
->tif
->tif_dir
.td_ycbcrsubsampling
[0])||(pv
!=data
->tif
->tif_dir
.td_ycbcrsubsampling
[1]))
868 TIFFWarningExt(data
->tif
->tif_clientdata
,module,
869 "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
870 (int)data
->tif
->tif_dir
.td_ycbcrsubsampling
[0],
871 (int)data
->tif
->tif_dir
.td_ycbcrsubsampling
[1],
873 data
->tif
->tif_dir
.td_ycbcrsubsampling
[0]=ph
;
874 data
->tif
->tif_dir
.td_ycbcrsubsampling
[1]=pv
;
885 JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData
* data
, uint8
* result
)
887 if (data
->bufferbytesleft
==0)
890 if (data
->filebytesleft
==0)
892 if (!data
->filepositioned
)
894 TIFFSeekFile(data
->tif
,data
->fileoffset
,SEEK_SET
);
895 data
->filepositioned
=1;
898 if ((uint64
)m
>data
->filebytesleft
)
899 m
=(uint32
)data
->filebytesleft
;
900 assert(m
<0x80000000UL
);
901 if (TIFFReadFile(data
->tif
,data
->buffer
,(tmsize_t
)m
)!=(tmsize_t
)m
)
903 data
->buffercurrentbyte
=data
->buffer
;
904 data
->bufferbytesleft
=m
;
906 data
->filebytesleft
-=m
;
908 *result
=*data
->buffercurrentbyte
;
909 data
->buffercurrentbyte
++;
910 data
->bufferbytesleft
--;
915 JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData
* data
, uint16
* result
)
919 if (!JPEGFixupTagsSubsamplingReadByte(data
,&ma
))
921 if (!JPEGFixupTagsSubsamplingReadByte(data
,&mb
))
928 JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData
* data
, uint16 skiplength
)
930 if ((uint32
)skiplength
<=data
->bufferbytesleft
)
932 data
->buffercurrentbyte
+=skiplength
;
933 data
->bufferbytesleft
-=skiplength
;
938 m
=skiplength
-data
->bufferbytesleft
;
939 if (m
<=data
->filebytesleft
)
941 data
->bufferbytesleft
=0;
943 data
->filebytesleft
-=m
;
944 data
->filepositioned
=0;
948 data
->bufferbytesleft
=0;
949 data
->filebytesleft
=0;
958 JPEGSetupDecode(TIFF
* tif
)
960 JPEGState
* sp
= JState(tif
);
961 TIFFDirectory
*td
= &tif
->tif_dir
;
963 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
964 if( tif
->tif_dir
.td_bitspersample
== 12 )
965 return TIFFReInitJPEG_12( tif
, COMPRESSION_JPEG
, 0 );
968 JPEGInitializeLibJPEG( tif
, TRUE
);
971 assert(sp
->cinfo
.comm
.is_decompressor
);
973 /* Read JPEGTables if it is present */
974 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
)) {
975 TIFFjpeg_tables_src(sp
, tif
);
976 if(TIFFjpeg_read_header(sp
,FALSE
) != JPEG_HEADER_TABLES_ONLY
) {
977 TIFFErrorExt(tif
->tif_clientdata
, "JPEGSetupDecode", "Bogus JPEGTables field");
982 /* Grab parameters that are same for all strips/tiles */
983 sp
->photometric
= td
->td_photometric
;
984 switch (sp
->photometric
) {
985 case PHOTOMETRIC_YCBCR
:
986 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
987 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
990 /* TIFF 6.0 forbids subsampling of all other color spaces */
996 /* Set up for reading normal data */
997 TIFFjpeg_data_src(sp
, tif
);
998 tif
->tif_postdecode
= _TIFFNoPostDecode
; /* override byte swapping */
1003 * Set up for decoding a strip or tile.
1006 JPEGPreDecode(TIFF
* tif
, uint16 s
)
1008 JPEGState
*sp
= JState(tif
);
1009 TIFFDirectory
*td
= &tif
->tif_dir
;
1010 static const char module[] = "JPEGPreDecode";
1011 uint32 segment_width
, segment_height
;
1012 int downsampled_output
;
1017 if (sp
->cinfo
.comm
.is_decompressor
== 0)
1019 tif
->tif_setupdecode( tif
);
1022 assert(sp
->cinfo
.comm
.is_decompressor
);
1024 * Reset decoder state from any previous strip/tile,
1025 * in case application didn't read the whole strip.
1027 if (!TIFFjpeg_abort(sp
))
1030 * Read the header for this strip/tile.
1033 if (TIFFjpeg_read_header(sp
, TRUE
) != JPEG_HEADER_OK
)
1036 tif
->tif_rawcp
= (uint8
*) sp
->src
.next_input_byte
;
1037 tif
->tif_rawcc
= sp
->src
.bytes_in_buffer
;
1040 * Check image parameters and set decompression parameters.
1042 segment_width
= td
->td_imagewidth
;
1043 segment_height
= td
->td_imagelength
- tif
->tif_row
;
1045 segment_width
= td
->td_tilewidth
;
1046 segment_height
= td
->td_tilelength
;
1047 sp
->bytesperline
= TIFFTileRowSize(tif
);
1049 if (segment_height
> td
->td_rowsperstrip
)
1050 segment_height
= td
->td_rowsperstrip
;
1051 sp
->bytesperline
= TIFFScanlineSize(tif
);
1053 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
1055 * For PC 2, scale down the expected strip/tile size
1056 * to match a downsampled component
1058 segment_width
= TIFFhowmany_32(segment_width
, sp
->h_sampling
);
1059 segment_height
= TIFFhowmany_32(segment_height
, sp
->v_sampling
);
1061 if (sp
->cinfo
.d
.image_width
< segment_width
||
1062 sp
->cinfo
.d
.image_height
< segment_height
) {
1063 TIFFWarningExt(tif
->tif_clientdata
, module,
1064 "Improper JPEG strip/tile size, "
1065 "expected %dx%d, got %dx%d",
1066 segment_width
, segment_height
,
1067 sp
->cinfo
.d
.image_width
,
1068 sp
->cinfo
.d
.image_height
);
1070 if (sp
->cinfo
.d
.image_width
> segment_width
||
1071 sp
->cinfo
.d
.image_height
> segment_height
) {
1073 * This case could be dangerous, if the strip or tile size has
1074 * been reported as less than the amount of data jpeg will
1075 * return, some potential security issues arise. Catch this
1076 * case and error out.
1078 TIFFErrorExt(tif
->tif_clientdata
, module,
1079 "JPEG strip/tile size exceeds expected dimensions,"
1080 " expected %dx%d, got %dx%d",
1081 segment_width
, segment_height
,
1082 sp
->cinfo
.d
.image_width
, sp
->cinfo
.d
.image_height
);
1085 if (sp
->cinfo
.d
.num_components
!=
1086 (td
->td_planarconfig
== PLANARCONFIG_CONTIG
?
1087 td
->td_samplesperpixel
: 1)) {
1088 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG component count");
1092 if (12 != td
->td_bitspersample
&& 8 != td
->td_bitspersample
) {
1093 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG data precision");
1096 sp
->cinfo
.d
.data_precision
= td
->td_bitspersample
;
1097 sp
->cinfo
.d
.bits_in_jsample
= td
->td_bitspersample
;
1099 if (sp
->cinfo
.d
.data_precision
!= td
->td_bitspersample
) {
1100 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG data precision");
1104 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1105 /* Component 0 should have expected sampling factors */
1106 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= sp
->h_sampling
||
1107 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= sp
->v_sampling
) {
1108 TIFFErrorExt(tif
->tif_clientdata
, module,
1109 "Improper JPEG sampling factors %d,%d\n"
1110 "Apparently should be %d,%d.",
1111 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
,
1112 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
,
1113 sp
->h_sampling
, sp
->v_sampling
);
1116 /* Rest should have sampling factors 1,1 */
1117 for (ci
= 1; ci
< sp
->cinfo
.d
.num_components
; ci
++) {
1118 if (sp
->cinfo
.d
.comp_info
[ci
].h_samp_factor
!= 1 ||
1119 sp
->cinfo
.d
.comp_info
[ci
].v_samp_factor
!= 1) {
1120 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG sampling factors");
1125 /* PC 2's single component should have sampling factors 1,1 */
1126 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= 1 ||
1127 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= 1) {
1128 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG sampling factors");
1132 downsampled_output
= FALSE
;
1133 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
1134 sp
->photometric
== PHOTOMETRIC_YCBCR
&&
1135 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1136 /* Convert YCbCr to RGB */
1137 sp
->cinfo
.d
.jpeg_color_space
= JCS_YCbCr
;
1138 sp
->cinfo
.d
.out_color_space
= JCS_RGB
;
1140 /* Suppress colorspace handling */
1141 sp
->cinfo
.d
.jpeg_color_space
= JCS_UNKNOWN
;
1142 sp
->cinfo
.d
.out_color_space
= JCS_UNKNOWN
;
1143 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
1144 (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1))
1145 downsampled_output
= TRUE
;
1146 /* XXX what about up-sampling? */
1148 if (downsampled_output
) {
1149 /* Need to use raw-data interface to libjpeg */
1150 sp
->cinfo
.d
.raw_data_out
= TRUE
;
1151 #if JPEG_LIB_VERSION >= 70
1152 sp
->cinfo
.d
.do_fancy_upsampling
= FALSE
;
1153 #endif /* JPEG_LIB_VERSION >= 70 */
1154 tif
->tif_decoderow
= DecodeRowError
;
1155 tif
->tif_decodestrip
= JPEGDecodeRaw
;
1156 tif
->tif_decodetile
= JPEGDecodeRaw
;
1158 /* Use normal interface to libjpeg */
1159 sp
->cinfo
.d
.raw_data_out
= FALSE
;
1160 tif
->tif_decoderow
= JPEGDecode
;
1161 tif
->tif_decodestrip
= JPEGDecode
;
1162 tif
->tif_decodetile
= JPEGDecode
;
1164 /* Start JPEG decompressor */
1165 if (!TIFFjpeg_start_decompress(sp
))
1167 /* Allocate downsampled-data buffers if needed */
1168 if (downsampled_output
) {
1169 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.d
.comp_info
,
1170 sp
->cinfo
.d
.num_components
))
1172 sp
->scancount
= DCTSIZE
; /* mark buffer empty */
1178 * Decode a chunk of pixels.
1179 * "Standard" case: returned data is not downsampled.
1181 /*ARGSUSED*/ static int
1182 JPEGDecode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1184 JPEGState
*sp
= JState(tif
);
1189 ** Update available information, buffer may have been refilled
1190 ** between decode requests
1192 sp
->src
.next_input_byte
= (const JOCTET
*) tif
->tif_rawcp
;
1193 sp
->src
.bytes_in_buffer
= (size_t) tif
->tif_rawcc
;
1195 if( sp
->bytesperline
== 0 )
1198 nrows
= cc
/ sp
->bytesperline
;
1199 if (cc
% sp
->bytesperline
)
1200 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline not read");
1202 if( nrows
> (tmsize_t
) sp
->cinfo
.d
.image_height
)
1203 nrows
= sp
->cinfo
.d
.image_height
;
1205 /* data is expected to be read in multiples of a scanline */
1208 JSAMPROW line_work_buf
= NULL
;
1211 * For 6B, only use temporary buffer for 12 bit imagery.
1212 * For Mk1 always use it.
1214 #if !defined(JPEG_LIB_MK1)
1215 if( sp
->cinfo
.d
.data_precision
== 12 )
1218 line_work_buf
= (JSAMPROW
)
1219 _TIFFmalloc(sizeof(short) * sp
->cinfo
.d
.output_width
1220 * sp
->cinfo
.d
.num_components
);
1224 if( line_work_buf
!= NULL
)
1227 * In the MK1 case, we aways read into a 16bit buffer, and then
1228 * pack down to 12bit or 8bit. In 6B case we only read into 16
1229 * bit buffer for 12bit data, which we need to repack.
1231 if (TIFFjpeg_read_scanlines(sp
, &line_work_buf
, 1) != 1)
1234 if( sp
->cinfo
.d
.data_precision
== 12 )
1236 int value_pairs
= (sp
->cinfo
.d
.output_width
1237 * sp
->cinfo
.d
.num_components
) / 2;
1240 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1242 unsigned char *out_ptr
=
1243 ((unsigned char *) buf
) + iPair
* 3;
1244 JSAMPLE
*in_ptr
= line_work_buf
+ iPair
* 2;
1246 out_ptr
[0] = (in_ptr
[0] & 0xff0) >> 4;
1247 out_ptr
[1] = ((in_ptr
[0] & 0xf) << 4)
1248 | ((in_ptr
[1] & 0xf00) >> 8);
1249 out_ptr
[2] = ((in_ptr
[1] & 0xff) >> 0);
1252 else if( sp
->cinfo
.d
.data_precision
== 8 )
1254 int value_count
= (sp
->cinfo
.d
.output_width
1255 * sp
->cinfo
.d
.num_components
);
1258 for( iValue
= 0; iValue
< value_count
; iValue
++ )
1260 ((unsigned char *) buf
)[iValue
] =
1261 line_work_buf
[iValue
] & 0xff;
1268 * In the libjpeg6b 8bit case. We read directly into the
1271 JSAMPROW bufptr
= (JSAMPROW
)buf
;
1273 if (TIFFjpeg_read_scanlines(sp
, &bufptr
, 1) != 1)
1278 buf
+= sp
->bytesperline
;
1279 cc
-= sp
->bytesperline
;
1280 } while (--nrows
> 0);
1282 if( line_work_buf
!= NULL
)
1283 _TIFFfree( line_work_buf
);
1286 /* Update information on consumed data */
1287 tif
->tif_rawcp
= (uint8
*) sp
->src
.next_input_byte
;
1288 tif
->tif_rawcc
= sp
->src
.bytes_in_buffer
;
1290 /* Close down the decompressor if we've finished the strip or tile. */
1291 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
1292 || TIFFjpeg_finish_decompress(sp
);
1295 /*ARGSUSED*/ static int
1296 DecodeRowError(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1303 TIFFErrorExt(tif
->tif_clientdata
, "TIFFReadScanline",
1304 "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
1309 * Decode a chunk of pixels.
1310 * Returned data is downsampled per sampling factors.
1312 /*ARGSUSED*/ static int
1313 JPEGDecodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1315 JPEGState
*sp
= JState(tif
);
1319 /* data is expected to be read in multiples of a scanline */
1320 if ( (nrows
= sp
->cinfo
.d
.image_height
) ) {
1322 /* Cb,Cr both have sampling factors 1, so this is correct */
1323 JDIMENSION clumps_per_line
= sp
->cinfo
.d
.comp_info
[1].downsampled_width
;
1324 int samples_per_clump
= sp
->samplesperclump
;
1326 #if defined(JPEG_LIB_MK1_OR_12BIT)
1327 unsigned short* tmpbuf
= _TIFFmalloc(sizeof(unsigned short) *
1328 sp
->cinfo
.d
.output_width
*
1329 sp
->cinfo
.d
.num_components
);
1331 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1338 jpeg_component_info
*compptr
;
1339 int ci
, clumpoffset
;
1341 if( cc
< sp
->bytesperline
) {
1342 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1343 "application buffer not large enough for all data.");
1347 /* Reload downsampled-data buffer if needed */
1348 if (sp
->scancount
>= DCTSIZE
) {
1349 int n
= sp
->cinfo
.d
.max_v_samp_factor
* DCTSIZE
;
1350 if (TIFFjpeg_read_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1355 * Fastest way to unseparate data is to make one pass
1356 * over the scanline for each row of each component.
1358 clumpoffset
= 0; /* first sample in clump */
1359 for (ci
= 0, compptr
= sp
->cinfo
.d
.comp_info
;
1360 ci
< sp
->cinfo
.d
.num_components
;
1362 int hsamp
= compptr
->h_samp_factor
;
1363 int vsamp
= compptr
->v_samp_factor
;
1366 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
1367 JSAMPLE
*inptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
1369 #if defined(JPEG_LIB_MK1_OR_12BIT)
1370 JSAMPLE
*outptr
= (JSAMPLE
*)tmpbuf
+ clumpoffset
;
1372 JSAMPLE
*outptr
= (JSAMPLE
*)buf
+ clumpoffset
;
1373 if (cc
< (tmsize_t
) (clumpoffset
+ samples_per_clump
*(clumps_per_line
-1) + hsamp
)) {
1374 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1375 "application buffer not large enough for all data, possible subsampling issue");
1381 /* fast path for at least Cb and Cr */
1382 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1383 outptr
[0] = *inptr
++;
1384 outptr
+= samples_per_clump
;
1390 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1391 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1392 outptr
[xpos
] = *inptr
++;
1393 outptr
+= samples_per_clump
;
1396 clumpoffset
+= hsamp
;
1400 #if defined(JPEG_LIB_MK1_OR_12BIT)
1402 if (sp
->cinfo
.d
.data_precision
== 8)
1405 int len
= sp
->cinfo
.d
.output_width
* sp
->cinfo
.d
.num_components
;
1406 for (i
=0; i
<len
; i
++)
1408 ((unsigned char*)buf
)[i
] = tmpbuf
[i
] & 0xff;
1413 int value_pairs
= (sp
->cinfo
.d
.output_width
1414 * sp
->cinfo
.d
.num_components
) / 2;
1416 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1418 unsigned char *out_ptr
= ((unsigned char *) buf
) + iPair
* 3;
1419 JSAMPLE
*in_ptr
= (JSAMPLE
*) (tmpbuf
+ iPair
* 2);
1420 out_ptr
[0] = (in_ptr
[0] & 0xff0) >> 4;
1421 out_ptr
[1] = ((in_ptr
[0] & 0xf) << 4)
1422 | ((in_ptr
[1] & 0xf00) >> 8);
1423 out_ptr
[2] = ((in_ptr
[1] & 0xff) >> 0);
1430 tif
->tif_row
+= sp
->v_sampling
;
1432 buf
+= sp
->bytesperline
;
1433 cc
-= sp
->bytesperline
;
1435 nrows
-= sp
->v_sampling
;
1436 } while (nrows
> 0);
1438 #if defined(JPEG_LIB_MK1_OR_12BIT)
1444 /* Close down the decompressor if done. */
1445 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
1446 || TIFFjpeg_finish_decompress(sp
);
1455 unsuppress_quant_table (JPEGState
* sp
, int tblno
)
1459 if ((qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[tblno
]) != NULL
)
1460 qtbl
->sent_table
= FALSE
;
1464 unsuppress_huff_table (JPEGState
* sp
, int tblno
)
1468 if ((htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[tblno
]) != NULL
)
1469 htbl
->sent_table
= FALSE
;
1470 if ((htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[tblno
]) != NULL
)
1471 htbl
->sent_table
= FALSE
;
1475 prepare_JPEGTables(TIFF
* tif
)
1477 JPEGState
* sp
= JState(tif
);
1479 /* Initialize quant tables for current quality setting */
1480 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1482 /* Mark only the tables we want for output */
1483 /* NB: chrominance tables are currently used only with YCbCr */
1484 if (!TIFFjpeg_suppress_tables(sp
, TRUE
))
1486 if (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
) {
1487 unsuppress_quant_table(sp
, 0);
1488 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1489 unsuppress_quant_table(sp
, 1);
1491 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
) {
1492 unsuppress_huff_table(sp
, 0);
1493 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1494 unsuppress_huff_table(sp
, 1);
1496 /* Direct libjpeg output into jpegtables */
1497 if (!TIFFjpeg_tables_dest(sp
, tif
))
1499 /* Emit tables-only datastream */
1500 if (!TIFFjpeg_write_tables(sp
))
1507 JPEGSetupEncode(TIFF
* tif
)
1509 JPEGState
* sp
= JState(tif
);
1510 TIFFDirectory
*td
= &tif
->tif_dir
;
1511 static const char module[] = "JPEGSetupEncode";
1513 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
1514 if( tif
->tif_dir
.td_bitspersample
== 12 )
1515 return TIFFReInitJPEG_12( tif
, COMPRESSION_JPEG
, 1 );
1518 JPEGInitializeLibJPEG( tif
, FALSE
);
1521 assert(!sp
->cinfo
.comm
.is_decompressor
);
1524 * Initialize all JPEG parameters to default values.
1525 * Note that jpeg_set_defaults needs legal values for
1526 * in_color_space and input_components.
1528 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1529 sp
->cinfo
.c
.input_components
= 1;
1530 if (!TIFFjpeg_set_defaults(sp
))
1532 /* Set per-file parameters */
1533 sp
->photometric
= td
->td_photometric
;
1534 switch (sp
->photometric
) {
1535 case PHOTOMETRIC_YCBCR
:
1536 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
1537 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
1539 * A ReferenceBlackWhite field *must* be present since the
1540 * default value is inappropriate for YCbCr. Fill in the
1541 * proper value if application didn't set it.
1545 if (!TIFFGetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1548 long top
= 1L << td
->td_bitspersample
;
1550 refbw
[1] = (float)(top
-1L);
1551 refbw
[2] = (float)(top
>>1);
1552 refbw
[3] = refbw
[1];
1553 refbw
[4] = refbw
[2];
1554 refbw
[5] = refbw
[1];
1555 TIFFSetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1560 case PHOTOMETRIC_PALETTE
: /* disallowed by Tech Note */
1561 case PHOTOMETRIC_MASK
:
1562 TIFFErrorExt(tif
->tif_clientdata
, module,
1563 "PhotometricInterpretation %d not allowed for JPEG",
1564 (int) sp
->photometric
);
1567 /* TIFF 6.0 forbids subsampling of all other color spaces */
1573 /* Verify miscellaneous parameters */
1576 * This would need work if libtiff ever supports different
1577 * depths for different components, or if libjpeg ever supports
1578 * run-time selection of depth. Neither is imminent.
1581 /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1582 if (td
->td_bitspersample
!= 8 && td
->td_bitspersample
!= 12)
1584 if (td
->td_bitspersample
!= BITS_IN_JSAMPLE
)
1587 TIFFErrorExt(tif
->tif_clientdata
, module, "BitsPerSample %d not allowed for JPEG",
1588 (int) td
->td_bitspersample
);
1591 sp
->cinfo
.c
.data_precision
= td
->td_bitspersample
;
1593 sp
->cinfo
.c
.bits_in_jsample
= td
->td_bitspersample
;
1596 if ((td
->td_tilelength
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1597 TIFFErrorExt(tif
->tif_clientdata
, module,
1598 "JPEG tile height must be multiple of %d",
1599 sp
->v_sampling
* DCTSIZE
);
1602 if ((td
->td_tilewidth
% (sp
->h_sampling
* DCTSIZE
)) != 0) {
1603 TIFFErrorExt(tif
->tif_clientdata
, module,
1604 "JPEG tile width must be multiple of %d",
1605 sp
->h_sampling
* DCTSIZE
);
1609 if (td
->td_rowsperstrip
< td
->td_imagelength
&&
1610 (td
->td_rowsperstrip
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1611 TIFFErrorExt(tif
->tif_clientdata
, module,
1612 "RowsPerStrip must be multiple of %d for JPEG",
1613 sp
->v_sampling
* DCTSIZE
);
1618 /* Create a JPEGTables field if appropriate */
1619 if (sp
->jpegtablesmode
& (JPEGTABLESMODE_QUANT
|JPEGTABLESMODE_HUFF
)) {
1620 if( sp
->jpegtables
== NULL
1621 || memcmp(sp
->jpegtables
,"\0\0\0\0\0\0\0\0\0",8) == 0 )
1623 if (!prepare_JPEGTables(tif
))
1625 /* Mark the field present */
1626 /* Can't use TIFFSetField since BEENWRITING is already set! */
1627 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1628 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1631 /* We do not support application-supplied JPEGTables, */
1632 /* so mark the field not present */
1633 TIFFClrFieldBit(tif
, FIELD_JPEGTABLES
);
1636 /* Direct libjpeg output to libtiff's output buffer */
1637 TIFFjpeg_data_dest(sp
, tif
);
1643 * Set encoding state at the start of a strip or tile.
1646 JPEGPreEncode(TIFF
* tif
, uint16 s
)
1648 JPEGState
*sp
= JState(tif
);
1649 TIFFDirectory
*td
= &tif
->tif_dir
;
1650 static const char module[] = "JPEGPreEncode";
1651 uint32 segment_width
, segment_height
;
1652 int downsampled_input
;
1656 if (sp
->cinfo
.comm
.is_decompressor
== 1)
1658 tif
->tif_setupencode( tif
);
1661 assert(!sp
->cinfo
.comm
.is_decompressor
);
1663 * Set encoding parameters for this strip/tile.
1666 segment_width
= td
->td_tilewidth
;
1667 segment_height
= td
->td_tilelength
;
1668 sp
->bytesperline
= TIFFTileRowSize(tif
);
1670 segment_width
= td
->td_imagewidth
;
1671 segment_height
= td
->td_imagelength
- tif
->tif_row
;
1672 if (segment_height
> td
->td_rowsperstrip
)
1673 segment_height
= td
->td_rowsperstrip
;
1674 sp
->bytesperline
= TIFFScanlineSize(tif
);
1676 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
1677 /* for PC 2, scale down the strip/tile size
1678 * to match a downsampled component
1680 segment_width
= TIFFhowmany_32(segment_width
, sp
->h_sampling
);
1681 segment_height
= TIFFhowmany_32(segment_height
, sp
->v_sampling
);
1683 if (segment_width
> 65535 || segment_height
> 65535) {
1684 TIFFErrorExt(tif
->tif_clientdata
, module, "Strip/tile too large for JPEG");
1687 sp
->cinfo
.c
.image_width
= segment_width
;
1688 sp
->cinfo
.c
.image_height
= segment_height
;
1689 downsampled_input
= FALSE
;
1690 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1691 sp
->cinfo
.c
.input_components
= td
->td_samplesperpixel
;
1692 if (sp
->photometric
== PHOTOMETRIC_YCBCR
) {
1693 if (sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1694 sp
->cinfo
.c
.in_color_space
= JCS_RGB
;
1696 sp
->cinfo
.c
.in_color_space
= JCS_YCbCr
;
1697 if (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1)
1698 downsampled_input
= TRUE
;
1700 if (!TIFFjpeg_set_colorspace(sp
, JCS_YCbCr
))
1703 * Set Y sampling factors;
1704 * we assume jpeg_set_colorspace() set the rest to 1
1706 sp
->cinfo
.c
.comp_info
[0].h_samp_factor
= sp
->h_sampling
;
1707 sp
->cinfo
.c
.comp_info
[0].v_samp_factor
= sp
->v_sampling
;
1709 if ((td
->td_photometric
== PHOTOMETRIC_MINISWHITE
|| td
->td_photometric
== PHOTOMETRIC_MINISBLACK
) && td
->td_samplesperpixel
== 1)
1710 sp
->cinfo
.c
.in_color_space
= JCS_GRAYSCALE
;
1711 else if (td
->td_photometric
== PHOTOMETRIC_RGB
&& td
->td_samplesperpixel
== 3)
1712 sp
->cinfo
.c
.in_color_space
= JCS_RGB
;
1713 else if (td
->td_photometric
== PHOTOMETRIC_SEPARATED
&& td
->td_samplesperpixel
== 4)
1714 sp
->cinfo
.c
.in_color_space
= JCS_CMYK
;
1716 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1717 if (!TIFFjpeg_set_colorspace(sp
, sp
->cinfo
.c
.in_color_space
))
1719 /* jpeg_set_colorspace set all sampling factors to 1 */
1722 sp
->cinfo
.c
.input_components
= 1;
1723 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1724 if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
))
1726 sp
->cinfo
.c
.comp_info
[0].component_id
= s
;
1727 /* jpeg_set_colorspace() set sampling factors to 1 */
1728 if (sp
->photometric
== PHOTOMETRIC_YCBCR
&& s
> 0) {
1729 sp
->cinfo
.c
.comp_info
[0].quant_tbl_no
= 1;
1730 sp
->cinfo
.c
.comp_info
[0].dc_tbl_no
= 1;
1731 sp
->cinfo
.c
.comp_info
[0].ac_tbl_no
= 1;
1734 /* ensure libjpeg won't write any extraneous markers */
1735 sp
->cinfo
.c
.write_JFIF_header
= FALSE
;
1736 sp
->cinfo
.c
.write_Adobe_marker
= FALSE
;
1737 /* set up table handling correctly */
1738 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1740 if (! (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
)) {
1741 unsuppress_quant_table(sp
, 0);
1742 unsuppress_quant_table(sp
, 1);
1744 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
)
1745 sp
->cinfo
.c
.optimize_coding
= FALSE
;
1747 sp
->cinfo
.c
.optimize_coding
= TRUE
;
1748 if (downsampled_input
) {
1749 /* Need to use raw-data interface to libjpeg */
1750 sp
->cinfo
.c
.raw_data_in
= TRUE
;
1751 tif
->tif_encoderow
= JPEGEncodeRaw
;
1752 tif
->tif_encodestrip
= JPEGEncodeRaw
;
1753 tif
->tif_encodetile
= JPEGEncodeRaw
;
1755 /* Use normal interface to libjpeg */
1756 sp
->cinfo
.c
.raw_data_in
= FALSE
;
1757 tif
->tif_encoderow
= JPEGEncode
;
1758 tif
->tif_encodestrip
= JPEGEncode
;
1759 tif
->tif_encodetile
= JPEGEncode
;
1761 /* Start JPEG compressor */
1762 if (!TIFFjpeg_start_compress(sp
, FALSE
))
1764 /* Allocate downsampled-data buffers if needed */
1765 if (downsampled_input
) {
1766 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.c
.comp_info
,
1767 sp
->cinfo
.c
.num_components
))
1776 * Encode a chunk of pixels.
1777 * "Standard" case: incoming data is not downsampled.
1780 JPEGEncode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1782 JPEGState
*sp
= JState(tif
);
1785 short *line16
= NULL
;
1786 int line16_count
= 0;
1790 /* data is expected to be supplied in multiples of a scanline */
1791 nrows
= cc
/ sp
->bytesperline
;
1792 if (cc
% sp
->bytesperline
)
1793 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
,
1794 "fractional scanline discarded");
1796 /* The last strip will be limited to image size */
1797 if( !isTiled(tif
) && tif
->tif_row
+nrows
> tif
->tif_dir
.td_imagelength
)
1798 nrows
= tif
->tif_dir
.td_imagelength
- tif
->tif_row
;
1800 if( sp
->cinfo
.c
.data_precision
== 12 )
1802 line16_count
= (sp
->bytesperline
* 2) / 3;
1803 line16
= (short *) _TIFFmalloc(sizeof(short) * line16_count
);
1804 // FIXME: undiagnosed malloc failure
1807 while (nrows
-- > 0) {
1809 if( sp
->cinfo
.c
.data_precision
== 12 )
1812 int value_pairs
= line16_count
/ 2;
1815 bufptr
[0] = (JSAMPROW
) line16
;
1817 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1819 unsigned char *in_ptr
=
1820 ((unsigned char *) buf
) + iPair
* 3;
1821 JSAMPLE
*out_ptr
= (JSAMPLE
*) (line16
+ iPair
* 2);
1823 out_ptr
[0] = (in_ptr
[0] << 4) | ((in_ptr
[1] & 0xf0) >> 4);
1824 out_ptr
[1] = ((in_ptr
[1] & 0x0f) << 8) | in_ptr
[2];
1829 bufptr
[0] = (JSAMPROW
) buf
;
1831 if (TIFFjpeg_write_scanlines(sp
, bufptr
, 1) != 1)
1835 buf
+= sp
->bytesperline
;
1838 if( sp
->cinfo
.c
.data_precision
== 12 )
1840 _TIFFfree( line16
);
1847 * Encode a chunk of pixels.
1848 * Incoming data is expected to be downsampled per sampling factors.
1851 JPEGEncodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1853 JPEGState
*sp
= JState(tif
);
1857 JDIMENSION clumps_per_line
, nclump
;
1858 int clumpoffset
, ci
, xpos
, ypos
;
1859 jpeg_component_info
* compptr
;
1860 int samples_per_clump
= sp
->samplesperclump
;
1861 tmsize_t bytesperclumpline
;
1865 /* data is expected to be supplied in multiples of a clumpline */
1866 /* a clumpline is equivalent to v_sampling desubsampled scanlines */
1867 /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
1868 bytesperclumpline
= (((sp
->cinfo
.c
.image_width
+sp
->h_sampling
-1)/sp
->h_sampling
)
1869 *(sp
->h_sampling
*sp
->v_sampling
+2)*sp
->cinfo
.c
.data_precision
+7)
1872 nrows
= ( cc
/ bytesperclumpline
) * sp
->v_sampling
;
1873 if (cc
% bytesperclumpline
)
1874 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline discarded");
1876 /* Cb,Cr both have sampling factors 1, so this is correct */
1877 clumps_per_line
= sp
->cinfo
.c
.comp_info
[1].downsampled_width
;
1881 * Fastest way to separate the data is to make one pass
1882 * over the scanline for each row of each component.
1884 clumpoffset
= 0; /* first sample in clump */
1885 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1886 ci
< sp
->cinfo
.c
.num_components
;
1888 int hsamp
= compptr
->h_samp_factor
;
1889 int vsamp
= compptr
->v_samp_factor
;
1890 int padding
= (int) (compptr
->width_in_blocks
* DCTSIZE
-
1891 clumps_per_line
* hsamp
);
1892 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
1893 inptr
= ((JSAMPLE
*) buf
) + clumpoffset
;
1894 outptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
1896 /* fast path for at least Cb and Cr */
1897 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1898 *outptr
++ = inptr
[0];
1899 inptr
+= samples_per_clump
;
1903 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1904 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1905 *outptr
++ = inptr
[xpos
];
1906 inptr
+= samples_per_clump
;
1909 /* pad each scanline as needed */
1910 for (xpos
= 0; xpos
< padding
; xpos
++) {
1911 *outptr
= outptr
[-1];
1914 clumpoffset
+= hsamp
;
1918 if (sp
->scancount
>= DCTSIZE
) {
1919 int n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1920 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1924 tif
->tif_row
+= sp
->v_sampling
;
1925 buf
+= bytesperclumpline
;
1926 nrows
-= sp
->v_sampling
;
1932 * Finish up at the end of a strip or tile.
1935 JPEGPostEncode(TIFF
* tif
)
1937 JPEGState
*sp
= JState(tif
);
1939 if (sp
->scancount
> 0) {
1941 * Need to emit a partial bufferload of downsampled data.
1942 * Pad the data vertically.
1945 jpeg_component_info
* compptr
;
1947 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1948 ci
< sp
->cinfo
.c
.num_components
;
1950 int vsamp
= compptr
->v_samp_factor
;
1951 tmsize_t row_width
= compptr
->width_in_blocks
* DCTSIZE
1953 for (ypos
= sp
->scancount
* vsamp
;
1954 ypos
< DCTSIZE
* vsamp
; ypos
++) {
1955 _TIFFmemcpy((void*)sp
->ds_buffer
[ci
][ypos
],
1956 (void*)sp
->ds_buffer
[ci
][ypos
-1],
1961 n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1962 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1966 return (TIFFjpeg_finish_compress(JState(tif
)));
1970 JPEGCleanup(TIFF
* tif
)
1972 JPEGState
*sp
= JState(tif
);
1976 tif
->tif_tagmethods
.vgetfield
= sp
->vgetparent
;
1977 tif
->tif_tagmethods
.vsetfield
= sp
->vsetparent
;
1978 tif
->tif_tagmethods
.printdir
= sp
->printdir
;
1981 if( sp
->cinfo_initialized
)
1982 TIFFjpeg_destroy(sp
); /* release libjpeg resources */
1983 if (sp
->jpegtables
) /* tag value */
1984 _TIFFfree(sp
->jpegtables
);
1986 _TIFFfree(tif
->tif_data
); /* release local state */
1987 tif
->tif_data
= NULL
;
1989 _TIFFSetDefaultCompressionState(tif
);
1993 JPEGResetUpsampled( TIFF
* tif
)
1995 JPEGState
* sp
= JState(tif
);
1996 TIFFDirectory
* td
= &tif
->tif_dir
;
1999 * Mark whether returned data is up-sampled or not so TIFFStripSize
2000 * and TIFFTileSize return values that reflect the true amount of
2003 tif
->tif_flags
&= ~TIFF_UPSAMPLED
;
2004 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
2005 if (td
->td_photometric
== PHOTOMETRIC_YCBCR
&&
2006 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
2007 tif
->tif_flags
|= TIFF_UPSAMPLED
;
2010 if (td
->td_ycbcrsubsampling
[0] != 1 ||
2011 td
->td_ycbcrsubsampling
[1] != 1)
2012 ; /* XXX what about up-sampling? */
2018 * Must recalculate cached tile size in case sampling state changed.
2019 * Should we really be doing this now if image size isn't set?
2021 if( tif
->tif_tilesize
> 0 )
2022 tif
->tif_tilesize
= isTiled(tif
) ? TIFFTileSize(tif
) : (tmsize_t
)(-1);
2023 if( tif
->tif_scanlinesize
> 0 )
2024 tif
->tif_scanlinesize
= TIFFScanlineSize(tif
);
2028 JPEGVSetField(TIFF
* tif
, uint32 tag
, va_list ap
)
2030 JPEGState
* sp
= JState(tif
);
2031 const TIFFField
* fip
;
2037 case TIFFTAG_JPEGTABLES
:
2038 v32
= (uint32
) va_arg(ap
, uint32
);
2043 _TIFFsetByteArray(&sp
->jpegtables
, va_arg(ap
, void*),
2045 sp
->jpegtables_length
= v32
;
2046 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
2048 case TIFFTAG_JPEGQUALITY
:
2049 sp
->jpegquality
= (int) va_arg(ap
, int);
2050 return (1); /* pseudo tag */
2051 case TIFFTAG_JPEGCOLORMODE
:
2052 sp
->jpegcolormode
= (int) va_arg(ap
, int);
2053 JPEGResetUpsampled( tif
);
2054 return (1); /* pseudo tag */
2055 case TIFFTAG_PHOTOMETRIC
:
2057 int ret_value
= (*sp
->vsetparent
)(tif
, tag
, ap
);
2058 JPEGResetUpsampled( tif
);
2061 case TIFFTAG_JPEGTABLESMODE
:
2062 sp
->jpegtablesmode
= (int) va_arg(ap
, int);
2063 return (1); /* pseudo tag */
2064 case TIFFTAG_YCBCRSUBSAMPLING
:
2065 /* mark the fact that we have a real ycbcrsubsampling! */
2066 sp
->ycbcrsampling_fetched
= 1;
2067 /* should we be recomputing upsampling info here? */
2068 return (*sp
->vsetparent
)(tif
, tag
, ap
);
2070 return (*sp
->vsetparent
)(tif
, tag
, ap
);
2073 if ((fip
= TIFFFieldWithTag(tif
, tag
))) {
2074 TIFFSetFieldBit(tif
, fip
->field_bit
);
2079 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
2084 JPEGVGetField(TIFF
* tif
, uint32 tag
, va_list ap
)
2086 JPEGState
* sp
= JState(tif
);
2091 case TIFFTAG_JPEGTABLES
:
2092 *va_arg(ap
, uint32
*) = sp
->jpegtables_length
;
2093 *va_arg(ap
, void**) = sp
->jpegtables
;
2095 case TIFFTAG_JPEGQUALITY
:
2096 *va_arg(ap
, int*) = sp
->jpegquality
;
2098 case TIFFTAG_JPEGCOLORMODE
:
2099 *va_arg(ap
, int*) = sp
->jpegcolormode
;
2101 case TIFFTAG_JPEGTABLESMODE
:
2102 *va_arg(ap
, int*) = sp
->jpegtablesmode
;
2105 return (*sp
->vgetparent
)(tif
, tag
, ap
);
2111 JPEGPrintDir(TIFF
* tif
, FILE* fd
, long flags
)
2113 JPEGState
* sp
= JState(tif
);
2119 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
))
2120 fprintf(fd
, " JPEG Tables: (%lu bytes)\n",
2121 (unsigned long) sp
->jpegtables_length
);
2123 (*sp
->printdir
)(tif
, fd
, flags
);
2128 JPEGDefaultStripSize(TIFF
* tif
, uint32 s
)
2130 JPEGState
* sp
= JState(tif
);
2131 TIFFDirectory
*td
= &tif
->tif_dir
;
2133 s
= (*sp
->defsparent
)(tif
, s
);
2134 if (s
< td
->td_imagelength
)
2135 s
= TIFFroundup_32(s
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
2140 JPEGDefaultTileSize(TIFF
* tif
, uint32
* tw
, uint32
* th
)
2142 JPEGState
* sp
= JState(tif
);
2143 TIFFDirectory
*td
= &tif
->tif_dir
;
2145 (*sp
->deftparent
)(tif
, tw
, th
);
2146 *tw
= TIFFroundup_32(*tw
, td
->td_ycbcrsubsampling
[0] * DCTSIZE
);
2147 *th
= TIFFroundup_32(*th
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
2151 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
2152 * now that we allow a TIFF file to be opened in update mode it is necessary
2153 * to have some way of deciding whether compression or decompression is
2154 * desired other than looking at tif->tif_mode. We accomplish this by
2155 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
2156 * If so, we assume decompression is desired.
2158 * This is tricky, because TIFFInitJPEG() is called while the directory is
2159 * being read, and generally speaking the BYTECOUNTS tag won't have been read
2160 * at that point. So we try to defer jpeg library initialization till we
2161 * do have that tag ... basically any access that might require the compressor
2162 * or decompressor that occurs after the reading of the directory.
2164 * In an ideal world compressors or decompressors would be setup
2165 * at the point where a single tile or strip was accessed (for read or write)
2166 * so that stuff like update of missing tiles, or replacement of tiles could
2167 * be done. However, we aren't trying to crack that nut just yet ...
2169 * NFW, Feb 3rd, 2003.
2172 static int JPEGInitializeLibJPEG( TIFF
* tif
, int decompress
)
2174 JPEGState
* sp
= JState(tif
);
2176 if(sp
->cinfo_initialized
)
2178 if( !decompress
&& sp
->cinfo
.comm
.is_decompressor
)
2179 TIFFjpeg_destroy( sp
);
2180 else if( decompress
&& !sp
->cinfo
.comm
.is_decompressor
)
2181 TIFFjpeg_destroy( sp
);
2185 sp
->cinfo_initialized
= 0;
2189 * Initialize libjpeg.
2192 if (!TIFFjpeg_create_decompress(sp
))
2195 if (!TIFFjpeg_create_compress(sp
))
2199 sp
->cinfo_initialized
= TRUE
;
2205 TIFFInitJPEG(TIFF
* tif
, int scheme
)
2209 assert(scheme
== COMPRESSION_JPEG
);
2212 * Merge codec-specific tag information.
2214 if (!_TIFFMergeFields(tif
, jpegFields
, TIFFArrayCount(jpegFields
))) {
2215 TIFFErrorExt(tif
->tif_clientdata
,
2217 "Merging JPEG codec-specific tags failed");
2222 * Allocate state block so tag methods have storage to record values.
2224 tif
->tif_data
= (uint8
*) _TIFFmalloc(sizeof (JPEGState
));
2226 if (tif
->tif_data
== NULL
) {
2227 TIFFErrorExt(tif
->tif_clientdata
,
2228 "TIFFInitJPEG", "No space for JPEG state block");
2231 _TIFFmemset(tif
->tif_data
, 0, sizeof(JPEGState
));
2234 sp
->tif
= tif
; /* back link */
2237 * Override parent get/set field methods.
2239 sp
->vgetparent
= tif
->tif_tagmethods
.vgetfield
;
2240 tif
->tif_tagmethods
.vgetfield
= JPEGVGetField
; /* hook for codec tags */
2241 sp
->vsetparent
= tif
->tif_tagmethods
.vsetfield
;
2242 tif
->tif_tagmethods
.vsetfield
= JPEGVSetField
; /* hook for codec tags */
2243 sp
->printdir
= tif
->tif_tagmethods
.printdir
;
2244 tif
->tif_tagmethods
.printdir
= JPEGPrintDir
; /* hook for codec tags */
2246 /* Default values for codec-specific fields */
2247 sp
->jpegtables
= NULL
;
2248 sp
->jpegtables_length
= 0;
2249 sp
->jpegquality
= 75; /* Default IJG quality */
2250 sp
->jpegcolormode
= JPEGCOLORMODE_RAW
;
2251 sp
->jpegtablesmode
= JPEGTABLESMODE_QUANT
| JPEGTABLESMODE_HUFF
;
2252 sp
->ycbcrsampling_fetched
= 0;
2255 * Install codec methods.
2257 tif
->tif_fixuptags
= JPEGFixupTags
;
2258 tif
->tif_setupdecode
= JPEGSetupDecode
;
2259 tif
->tif_predecode
= JPEGPreDecode
;
2260 tif
->tif_decoderow
= JPEGDecode
;
2261 tif
->tif_decodestrip
= JPEGDecode
;
2262 tif
->tif_decodetile
= JPEGDecode
;
2263 tif
->tif_setupencode
= JPEGSetupEncode
;
2264 tif
->tif_preencode
= JPEGPreEncode
;
2265 tif
->tif_postencode
= JPEGPostEncode
;
2266 tif
->tif_encoderow
= JPEGEncode
;
2267 tif
->tif_encodestrip
= JPEGEncode
;
2268 tif
->tif_encodetile
= JPEGEncode
;
2269 tif
->tif_cleanup
= JPEGCleanup
;
2270 sp
->defsparent
= tif
->tif_defstripsize
;
2271 tif
->tif_defstripsize
= JPEGDefaultStripSize
;
2272 sp
->deftparent
= tif
->tif_deftilesize
;
2273 tif
->tif_deftilesize
= JPEGDefaultTileSize
;
2274 tif
->tif_flags
|= TIFF_NOBITREV
; /* no bit reversal, please */
2276 sp
->cinfo_initialized
= FALSE
;
2279 ** Create a JPEGTables field if no directory has yet been created.
2280 ** We do this just to ensure that sufficient space is reserved for
2281 ** the JPEGTables field. It will be properly created the right
2284 if( tif
->tif_diroff
== 0 )
2286 #define SIZE_OF_JPEGTABLES 2000
2288 The following line assumes incorrectly that all JPEG-in-TIFF files will have
2289 a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
2290 when the JPEG data is placed with TIFFWriteRawStrip. The field bit should be
2291 set, anyway, later when actual JPEGTABLES header is generated, so removing it
2292 here hopefully is harmless.
2293 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2295 sp
->jpegtables_length
= SIZE_OF_JPEGTABLES
;
2296 sp
->jpegtables
= (void *) _TIFFmalloc(sp
->jpegtables_length
);
2297 // FIXME: NULL-deref after malloc failure
2298 _TIFFmemset(sp
->jpegtables
, 0, SIZE_OF_JPEGTABLES
);
2299 #undef SIZE_OF_JPEGTABLES
2304 #endif /* JPEG_SUPPORT */
2306 /* vim: set ts=8 sts=8 sw=8 noet: */