1 /* $Id: tif_jpeg.c,v 1.111 2012-07-06 18:48:04 bfriesen 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
37 * JPEG Compression support per TIFF Technical Note #2
38 * (*not* per the original TIFF 6.0 spec).
40 * This file is simply an interface to the libjpeg library written by
41 * the Independent JPEG Group. You need release 5 or later of the IJG
42 * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
44 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
48 int TIFFFillStrip(TIFF
* tif
, uint32 strip
);
49 int TIFFFillTile(TIFF
* tif
, uint32 tile
);
50 int TIFFReInitJPEG_12( TIFF
*tif
, int scheme
, int is_encode
);
52 /* We undefine FAR to avoid conflict with JPEG definition */
59 Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
60 not defined. Unfortunately, the MinGW and Borland compilers include
61 a typedef for INT32, which causes a conflict. MSVC does not include
62 a conficting typedef given the headers which are included.
64 #if defined(__BORLANDC__) || defined(__MINGW32__)
69 The windows RPCNDR.H file defines boolean, but defines it with the
70 unsigned char size. You should compile JPEG library using appropriate
71 definitions in jconfig.h header, but many users compile library in wrong
72 way. That causes errors of the following type:
74 "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
77 For such users we wil fix the problem here. See install.doc file from
78 the JPEG library distribution for details.
81 /* Define "boolean" as unsigned char, not int, per Windows custom. */
82 #if defined(__WIN32__) && !defined(__MINGW32__)
83 # ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
84 typedef unsigned char boolean
;
86 # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
93 * Do we want to do special processing suitable for when JSAMPLE is a
97 #if defined(JPEG_LIB_MK1)
98 # define JPEG_LIB_MK1_OR_12BIT 1
99 #elif BITS_IN_JSAMPLE == 12
100 # define JPEG_LIB_MK1_OR_12BIT 1
104 * We are using width_in_blocks which is supposed to be private to
105 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
106 * renamed this member to width_in_data_units. Since the header has
107 * also renamed a define, use that unique define name in order to
108 * detect the problem header and adjust to suit.
110 #if defined(D_MAX_DATA_UNITS_IN_MCU)
111 #define width_in_blocks width_in_data_units
115 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
116 * in place of plain setjmp. These macros will make it easier.
118 #define SETJMP(jbuf) setjmp(jbuf)
119 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
120 #define JMP_BUF jmp_buf
122 typedef struct jpeg_destination_mgr jpeg_destination_mgr
;
123 typedef struct jpeg_source_mgr jpeg_source_mgr
;
124 typedef struct jpeg_error_mgr jpeg_error_mgr
;
127 * State block for each open TIFF file using
128 * libjpeg to do JPEG compression/decompression.
130 * libjpeg's visible state is either a jpeg_compress_struct
131 * or jpeg_decompress_struct depending on which way we
132 * are going. comm can be used to refer to the fields
133 * which are common to both.
135 * NB: cinfo is required to be the first member of JPEGState,
136 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
141 struct jpeg_compress_struct c
;
142 struct jpeg_decompress_struct d
;
143 struct jpeg_common_struct comm
;
144 } cinfo
; /* NB: must be first */
145 int cinfo_initialized
;
147 jpeg_error_mgr err
; /* libjpeg error manager */
148 JMP_BUF exit_jmpbuf
; /* for catching libjpeg failures */
150 * The following two members could be a union, but
151 * they're small enough that it's not worth the effort.
153 jpeg_destination_mgr dest
; /* data dest for compression */
154 jpeg_source_mgr src
; /* data source for decompression */
156 TIFF
* tif
; /* back link needed by some code */
157 uint16 photometric
; /* copy of PhotometricInterpretation */
158 uint16 h_sampling
; /* luminance sampling factors */
160 tmsize_t bytesperline
; /* decompressed bytes per scanline */
161 /* pointers to intermediate buffers when processing downsampled data */
162 JSAMPARRAY ds_buffer
[MAX_COMPONENTS
];
163 int scancount
; /* number of "scanlines" accumulated */
166 TIFFVGetMethod vgetparent
; /* super-class method */
167 TIFFVSetMethod vsetparent
; /* super-class method */
168 TIFFPrintMethod printdir
; /* super-class method */
169 TIFFStripMethod defsparent
; /* super-class method */
170 TIFFTileMethod deftparent
; /* super-class method */
171 /* pseudo-tag fields */
172 void* jpegtables
; /* JPEGTables tag value, or NULL */
173 uint32 jpegtables_length
; /* number of bytes in same */
174 int jpegquality
; /* Compression quality level */
175 int jpegcolormode
; /* Auto RGB<=>YCbCr convert? */
176 int jpegtablesmode
; /* What to put in JPEGTables */
178 int ycbcrsampling_fetched
;
181 #define JState(tif) ((JPEGState*)(tif)->tif_data)
183 static int JPEGDecode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
184 static int JPEGDecodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
185 static int JPEGEncode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
186 static int JPEGEncodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
187 static int JPEGInitializeLibJPEG(TIFF
* tif
, int decode
);
188 static int DecodeRowError(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
190 #define FIELD_JPEGTABLES (FIELD_CODEC+0)
192 static const TIFFField jpegFields
[] = {
193 { TIFFTAG_JPEGTABLES
, -3, -3, TIFF_UNDEFINED
, 0, TIFF_SETGET_C32_UINT8
, TIFF_SETGET_C32_UINT8
, FIELD_JPEGTABLES
, FALSE
, TRUE
, "JPEGTables", NULL
},
194 { TIFFTAG_JPEGQUALITY
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, TRUE
, FALSE
, "", NULL
},
195 { TIFFTAG_JPEGCOLORMODE
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, FALSE
, FALSE
, "", NULL
},
196 { TIFFTAG_JPEGTABLESMODE
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, FALSE
, FALSE
, "", NULL
}
200 * libjpeg interface layer.
202 * We use setjmp/longjmp to return control to libtiff
203 * when a fatal error is encountered within the JPEG
204 * library. We also direct libjpeg error and warning
205 * messages through the appropriate libtiff handlers.
209 * Error handling routines (these replace corresponding
210 * IJG routines from jerror.c). These are used for both
211 * compression and decompression.
214 TIFFjpeg_error_exit(j_common_ptr cinfo
)
216 JPEGState
*sp
= (JPEGState
*) cinfo
; /* NB: cinfo assumed first */
217 char buffer
[JMSG_LENGTH_MAX
];
219 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
220 TIFFErrorExt(sp
->tif
->tif_clientdata
, "JPEGLib", "%s", buffer
); /* display the error message */
221 jpeg_abort(cinfo
); /* clean up libjpeg state */
222 LONGJMP(sp
->exit_jmpbuf
, 1); /* return to libtiff caller */
226 * This routine is invoked only for warning messages,
227 * since error_exit does its own thing and trace_level
231 TIFFjpeg_output_message(j_common_ptr cinfo
)
233 char buffer
[JMSG_LENGTH_MAX
];
235 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
236 TIFFWarningExt(((JPEGState
*) cinfo
)->tif
->tif_clientdata
, "JPEGLib", "%s", buffer
);
240 * Interface routines. This layer of routines exists
241 * primarily to limit side-effects from using setjmp.
242 * Also, normal/error returns are converted into return
243 * values per libtiff practice.
245 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
246 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
249 TIFFjpeg_create_compress(JPEGState
* sp
)
251 /* initialize JPEG error handling */
252 sp
->cinfo
.c
.err
= jpeg_std_error(&sp
->err
);
253 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
254 sp
->err
.output_message
= TIFFjpeg_output_message
;
256 return CALLVJPEG(sp
, jpeg_create_compress(&sp
->cinfo
.c
));
260 TIFFjpeg_create_decompress(JPEGState
* sp
)
262 /* initialize JPEG error handling */
263 sp
->cinfo
.d
.err
= jpeg_std_error(&sp
->err
);
264 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
265 sp
->err
.output_message
= TIFFjpeg_output_message
;
267 return CALLVJPEG(sp
, jpeg_create_decompress(&sp
->cinfo
.d
));
271 TIFFjpeg_set_defaults(JPEGState
* sp
)
273 return CALLVJPEG(sp
, jpeg_set_defaults(&sp
->cinfo
.c
));
277 TIFFjpeg_set_colorspace(JPEGState
* sp
, J_COLOR_SPACE colorspace
)
279 return CALLVJPEG(sp
, jpeg_set_colorspace(&sp
->cinfo
.c
, colorspace
));
283 TIFFjpeg_set_quality(JPEGState
* sp
, int quality
, boolean force_baseline
)
286 jpeg_set_quality(&sp
->cinfo
.c
, quality
, force_baseline
));
290 TIFFjpeg_suppress_tables(JPEGState
* sp
, boolean suppress
)
292 return CALLVJPEG(sp
, jpeg_suppress_tables(&sp
->cinfo
.c
, suppress
));
296 TIFFjpeg_start_compress(JPEGState
* sp
, boolean write_all_tables
)
299 jpeg_start_compress(&sp
->cinfo
.c
, write_all_tables
));
303 TIFFjpeg_write_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int num_lines
)
305 return CALLJPEG(sp
, -1, (int) jpeg_write_scanlines(&sp
->cinfo
.c
,
306 scanlines
, (JDIMENSION
) num_lines
));
310 TIFFjpeg_write_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int num_lines
)
312 return CALLJPEG(sp
, -1, (int) jpeg_write_raw_data(&sp
->cinfo
.c
,
313 data
, (JDIMENSION
) num_lines
));
317 TIFFjpeg_finish_compress(JPEGState
* sp
)
319 return CALLVJPEG(sp
, jpeg_finish_compress(&sp
->cinfo
.c
));
323 TIFFjpeg_write_tables(JPEGState
* sp
)
325 return CALLVJPEG(sp
, jpeg_write_tables(&sp
->cinfo
.c
));
329 TIFFjpeg_read_header(JPEGState
* sp
, boolean require_image
)
331 return CALLJPEG(sp
, -1, jpeg_read_header(&sp
->cinfo
.d
, require_image
));
335 TIFFjpeg_start_decompress(JPEGState
* sp
)
337 return CALLVJPEG(sp
, jpeg_start_decompress(&sp
->cinfo
.d
));
341 TIFFjpeg_read_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int max_lines
)
343 return CALLJPEG(sp
, -1, (int) jpeg_read_scanlines(&sp
->cinfo
.d
,
344 scanlines
, (JDIMENSION
) max_lines
));
348 TIFFjpeg_read_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int max_lines
)
350 return CALLJPEG(sp
, -1, (int) jpeg_read_raw_data(&sp
->cinfo
.d
,
351 data
, (JDIMENSION
) max_lines
));
355 TIFFjpeg_finish_decompress(JPEGState
* sp
)
357 return CALLJPEG(sp
, -1, (int) jpeg_finish_decompress(&sp
->cinfo
.d
));
361 TIFFjpeg_abort(JPEGState
* sp
)
363 return CALLVJPEG(sp
, jpeg_abort(&sp
->cinfo
.comm
));
367 TIFFjpeg_destroy(JPEGState
* sp
)
369 return CALLVJPEG(sp
, jpeg_destroy(&sp
->cinfo
.comm
));
373 TIFFjpeg_alloc_sarray(JPEGState
* sp
, int pool_id
,
374 JDIMENSION samplesperrow
, JDIMENSION numrows
)
376 return CALLJPEG(sp
, (JSAMPARRAY
) NULL
,
377 (*sp
->cinfo
.comm
.mem
->alloc_sarray
)
378 (&sp
->cinfo
.comm
, pool_id
, samplesperrow
, numrows
));
382 * JPEG library destination data manager.
383 * These routines direct compressed data from libjpeg into the
384 * libtiff output buffer.
388 std_init_destination(j_compress_ptr cinfo
)
390 JPEGState
* sp
= (JPEGState
*) cinfo
;
393 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
394 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
398 std_empty_output_buffer(j_compress_ptr cinfo
)
400 JPEGState
* sp
= (JPEGState
*) cinfo
;
403 /* the entire buffer has been filled */
404 tif
->tif_rawcc
= tif
->tif_rawdatasize
;
408 * The Intel IPP performance library does not necessarily fill up
409 * the whole output buffer on each pass, so only dump out the parts
410 * that have been filled.
411 * http://trac.osgeo.org/gdal/wiki/JpegIPP
413 if ( sp
->dest
.free_in_buffer
>= 0 ) {
414 tif
->tif_rawcc
= tif
->tif_rawdatasize
- sp
->dest
.free_in_buffer
;
419 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
420 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
426 std_term_destination(j_compress_ptr cinfo
)
428 JPEGState
* sp
= (JPEGState
*) cinfo
;
431 tif
->tif_rawcp
= (uint8
*) sp
->dest
.next_output_byte
;
433 tif
->tif_rawdatasize
- (tmsize_t
) sp
->dest
.free_in_buffer
;
434 /* NB: libtiff does the final buffer flush */
438 TIFFjpeg_data_dest(JPEGState
* sp
, TIFF
* tif
)
441 sp
->cinfo
.c
.dest
= &sp
->dest
;
442 sp
->dest
.init_destination
= std_init_destination
;
443 sp
->dest
.empty_output_buffer
= std_empty_output_buffer
;
444 sp
->dest
.term_destination
= std_term_destination
;
448 * Alternate destination manager for outputting to JPEGTables field.
452 tables_init_destination(j_compress_ptr cinfo
)
454 JPEGState
* sp
= (JPEGState
*) cinfo
;
456 /* while building, jpegtables_length is allocated buffer size */
457 sp
->dest
.next_output_byte
= (JOCTET
*) sp
->jpegtables
;
458 sp
->dest
.free_in_buffer
= (size_t) sp
->jpegtables_length
;
462 tables_empty_output_buffer(j_compress_ptr cinfo
)
464 JPEGState
* sp
= (JPEGState
*) cinfo
;
467 /* the entire buffer has been filled; enlarge it by 1000 bytes */
468 newbuf
= _TIFFrealloc((void*) sp
->jpegtables
,
469 (tmsize_t
) (sp
->jpegtables_length
+ 1000));
471 ERREXIT1(cinfo
, JERR_OUT_OF_MEMORY
, 100);
472 sp
->dest
.next_output_byte
= (JOCTET
*) newbuf
+ sp
->jpegtables_length
;
473 sp
->dest
.free_in_buffer
= (size_t) 1000;
474 sp
->jpegtables
= newbuf
;
475 sp
->jpegtables_length
+= 1000;
480 tables_term_destination(j_compress_ptr cinfo
)
482 JPEGState
* sp
= (JPEGState
*) cinfo
;
484 /* set tables length to number of bytes actually emitted */
485 sp
->jpegtables_length
-= (uint32
) sp
->dest
.free_in_buffer
;
489 TIFFjpeg_tables_dest(JPEGState
* sp
, TIFF
* tif
)
493 * Allocate a working buffer for building tables.
494 * Initial size is 1000 bytes, which is usually adequate.
497 _TIFFfree(sp
->jpegtables
);
498 sp
->jpegtables_length
= 1000;
499 sp
->jpegtables
= (void*) _TIFFmalloc((tmsize_t
) sp
->jpegtables_length
);
500 if (sp
->jpegtables
== NULL
) {
501 sp
->jpegtables_length
= 0;
502 TIFFErrorExt(sp
->tif
->tif_clientdata
, "TIFFjpeg_tables_dest", "No space for JPEGTables");
505 sp
->cinfo
.c
.dest
= &sp
->dest
;
506 sp
->dest
.init_destination
= tables_init_destination
;
507 sp
->dest
.empty_output_buffer
= tables_empty_output_buffer
;
508 sp
->dest
.term_destination
= tables_term_destination
;
513 * JPEG library source data manager.
514 * These routines supply compressed data to libjpeg.
518 std_init_source(j_decompress_ptr cinfo
)
520 JPEGState
* sp
= (JPEGState
*) cinfo
;
523 sp
->src
.next_input_byte
= (const JOCTET
*) tif
->tif_rawdata
;
524 sp
->src
.bytes_in_buffer
= (size_t) tif
->tif_rawcc
;
528 std_fill_input_buffer(j_decompress_ptr cinfo
)
530 JPEGState
* sp
= (JPEGState
* ) cinfo
;
531 static const JOCTET dummy_EOI
[2] = { 0xFF, JPEG_EOI
};
535 * The Intel IPP performance library does not necessarily read the whole
536 * input buffer in one pass, so it is possible to get here with data
539 * We just return without doing anything, until the entire buffer has
541 * http://trac.osgeo.org/gdal/wiki/JpegIPP
543 if( sp
->src
.bytes_in_buffer
> 0 ) {
549 * Normally the whole strip/tile is read and so we don't need to do
550 * a fill. In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
551 * all the data, but the rawdata is refreshed between scanlines and
552 * we push this into the io machinery in JPEGDecode().
553 * http://trac.osgeo.org/gdal/ticket/3894
556 WARNMS(cinfo
, JWRN_JPEG_EOF
);
557 /* insert a fake EOI marker */
558 sp
->src
.next_input_byte
= dummy_EOI
;
559 sp
->src
.bytes_in_buffer
= 2;
564 std_skip_input_data(j_decompress_ptr cinfo
, long num_bytes
)
566 JPEGState
* sp
= (JPEGState
*) cinfo
;
569 if ((size_t)num_bytes
> sp
->src
.bytes_in_buffer
) {
570 /* oops, buffer overrun */
571 (void) std_fill_input_buffer(cinfo
);
573 sp
->src
.next_input_byte
+= (size_t) num_bytes
;
574 sp
->src
.bytes_in_buffer
-= (size_t) num_bytes
;
580 std_term_source(j_decompress_ptr cinfo
)
582 /* No work necessary here */
587 TIFFjpeg_data_src(JPEGState
* sp
, TIFF
* tif
)
590 sp
->cinfo
.d
.src
= &sp
->src
;
591 sp
->src
.init_source
= std_init_source
;
592 sp
->src
.fill_input_buffer
= std_fill_input_buffer
;
593 sp
->src
.skip_input_data
= std_skip_input_data
;
594 sp
->src
.resync_to_restart
= jpeg_resync_to_restart
;
595 sp
->src
.term_source
= std_term_source
;
596 sp
->src
.bytes_in_buffer
= 0; /* for safety */
597 sp
->src
.next_input_byte
= NULL
;
601 * Alternate source manager for reading from JPEGTables.
602 * We can share all the code except for the init routine.
606 tables_init_source(j_decompress_ptr cinfo
)
608 JPEGState
* sp
= (JPEGState
*) cinfo
;
610 sp
->src
.next_input_byte
= (const JOCTET
*) sp
->jpegtables
;
611 sp
->src
.bytes_in_buffer
= (size_t) sp
->jpegtables_length
;
615 TIFFjpeg_tables_src(JPEGState
* sp
, TIFF
* tif
)
617 TIFFjpeg_data_src(sp
, tif
);
618 sp
->src
.init_source
= tables_init_source
;
622 * Allocate downsampled-data buffers needed for downsampled I/O.
623 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
624 * We use libjpeg's allocator so that buffers will be released automatically
625 * when done with strip/tile.
626 * This is also a handy place to compute samplesperclump, bytesperline.
629 alloc_downsampled_buffers(TIFF
* tif
, jpeg_component_info
* comp_info
,
632 JPEGState
* sp
= JState(tif
);
634 jpeg_component_info
* compptr
;
636 int samples_per_clump
= 0;
638 for (ci
= 0, compptr
= comp_info
; ci
< num_components
;
640 samples_per_clump
+= compptr
->h_samp_factor
*
641 compptr
->v_samp_factor
;
642 buf
= TIFFjpeg_alloc_sarray(sp
, JPOOL_IMAGE
,
643 compptr
->width_in_blocks
* DCTSIZE
,
644 (JDIMENSION
) (compptr
->v_samp_factor
*DCTSIZE
));
647 sp
->ds_buffer
[ci
] = buf
;
649 sp
->samplesperclump
= samples_per_clump
;
658 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
660 #define JPEG_MARKER_SOF0 0xC0
661 #define JPEG_MARKER_SOF1 0xC1
662 #define JPEG_MARKER_SOF3 0xC3
663 #define JPEG_MARKER_DHT 0xC4
664 #define JPEG_MARKER_SOI 0xD8
665 #define JPEG_MARKER_SOS 0xDA
666 #define JPEG_MARKER_DQT 0xDB
667 #define JPEG_MARKER_DRI 0xDD
668 #define JPEG_MARKER_APP0 0xE0
669 #define JPEG_MARKER_COM 0xFE
670 struct JPEGFixupTagsSubsamplingData
675 uint8
* buffercurrentbyte
;
676 uint32 bufferbytesleft
;
678 uint64 filebytesleft
;
679 uint8 filepositioned
;
681 static void JPEGFixupTagsSubsampling(TIFF
* tif
);
682 static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData
* data
);
683 static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData
* data
, uint8
* result
);
684 static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData
* data
, uint16
* result
);
685 static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData
* data
, uint16 skiplength
);
690 JPEGFixupTags(TIFF
* tif
)
692 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
693 if ((tif
->tif_dir
.td_photometric
==PHOTOMETRIC_YCBCR
)&&
694 (tif
->tif_dir
.td_planarconfig
==PLANARCONFIG_CONTIG
)&&
695 (tif
->tif_dir
.td_samplesperpixel
==3))
696 JPEGFixupTagsSubsampling(tif
);
702 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
705 JPEGFixupTagsSubsampling(TIFF
* tif
)
708 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
709 * the TIFF tags, but still use non-default (2,2) values within the jpeg
710 * data stream itself. In order for TIFF applications to work properly
711 * - for instance to get the strip buffer size right - it is imperative
712 * that the subsampling be available before we start reading the image
713 * data normally. This function will attempt to analyze the first strip in
714 * order to get the sampling values from the jpeg data stream.
716 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
717 * discovered sampling does not match the default sampling (2,2) or whatever
718 * was actually in the tiff tags.
720 * See the bug in bugzilla for details:
722 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
724 * Frank Warmerdam, July 2002
725 * Joris Van Damme, May 2007
727 static const char module
[] = "JPEGFixupTagsSubsampling";
728 struct JPEGFixupTagsSubsamplingData m
;
730 _TIFFFillStriles( tif
);
732 if( tif
->tif_dir
.td_stripbytecount
== NULL
733 || tif
->tif_dir
.td_stripbytecount
[0] == 0 )
735 /* Do not even try to check if the first strip/tile does not
736 yet exist, as occurs when GDAL has created a new NULL file
743 m
.buffer
=_TIFFmalloc(m
.buffersize
);
746 TIFFWarningExt(tif
->tif_clientdata
,module
,
747 "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
750 m
.buffercurrentbyte
=NULL
;
752 m
.fileoffset
=tif
->tif_dir
.td_stripoffset
[0];
754 m
.filebytesleft
=tif
->tif_dir
.td_stripbytecount
[0];
755 if (!JPEGFixupTagsSubsamplingSec(&m
))
756 TIFFWarningExt(tif
->tif_clientdata
,module
,
757 "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
762 JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData
* data
)
764 static const char module
[] = "JPEGFixupTagsSubsamplingSec";
770 if (!JPEGFixupTagsSubsamplingReadByte(data
,&m
))
777 if (!JPEGFixupTagsSubsamplingReadByte(data
,&m
))
784 case JPEG_MARKER_SOI
:
785 /* this type of marker has no data and should be skipped */
787 case JPEG_MARKER_COM
:
788 case JPEG_MARKER_APP0
:
789 case JPEG_MARKER_APP0
+1:
790 case JPEG_MARKER_APP0
+2:
791 case JPEG_MARKER_APP0
+3:
792 case JPEG_MARKER_APP0
+4:
793 case JPEG_MARKER_APP0
+5:
794 case JPEG_MARKER_APP0
+6:
795 case JPEG_MARKER_APP0
+7:
796 case JPEG_MARKER_APP0
+8:
797 case JPEG_MARKER_APP0
+9:
798 case JPEG_MARKER_APP0
+10:
799 case JPEG_MARKER_APP0
+11:
800 case JPEG_MARKER_APP0
+12:
801 case JPEG_MARKER_APP0
+13:
802 case JPEG_MARKER_APP0
+14:
803 case JPEG_MARKER_APP0
+15:
804 case JPEG_MARKER_DQT
:
805 case JPEG_MARKER_SOS
:
806 case JPEG_MARKER_DHT
:
807 case JPEG_MARKER_DRI
:
808 /* this type of marker has data, but it has no use to us and should be skipped */
811 if (!JPEGFixupTagsSubsamplingReadWord(data
,&n
))
817 JPEGFixupTagsSubsamplingSkip(data
,n
);
820 case JPEG_MARKER_SOF0
:
821 case JPEG_MARKER_SOF1
:
822 /* this marker contains the subsampling factors we're scanning for */
828 if (!JPEGFixupTagsSubsamplingReadWord(data
,&n
))
830 if (n
!=8+data
->tif
->tif_dir
.td_samplesperpixel
*3)
832 JPEGFixupTagsSubsamplingSkip(data
,7);
833 if (!JPEGFixupTagsSubsamplingReadByte(data
,&p
))
837 JPEGFixupTagsSubsamplingSkip(data
,1);
838 for (o
=1; o
<data
->tif
->tif_dir
.td_samplesperpixel
; o
++)
840 JPEGFixupTagsSubsamplingSkip(data
,1);
841 if (!JPEGFixupTagsSubsamplingReadByte(data
,&p
))
845 TIFFWarningExt(data
->tif
->tif_clientdata
,module
,
846 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
849 JPEGFixupTagsSubsamplingSkip(data
,1);
851 if (((ph
!=1)&&(ph
!=2)&&(ph
!=4))||((pv
!=1)&&(pv
!=2)&&(pv
!=4)))
853 TIFFWarningExt(data
->tif
->tif_clientdata
,module
,
854 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
857 if ((ph
!=data
->tif
->tif_dir
.td_ycbcrsubsampling
[0])||(pv
!=data
->tif
->tif_dir
.td_ycbcrsubsampling
[1]))
859 TIFFWarningExt(data
->tif
->tif_clientdata
,module
,
860 "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
861 (int)data
->tif
->tif_dir
.td_ycbcrsubsampling
[0],
862 (int)data
->tif
->tif_dir
.td_ycbcrsubsampling
[1],
864 data
->tif
->tif_dir
.td_ycbcrsubsampling
[0]=ph
;
865 data
->tif
->tif_dir
.td_ycbcrsubsampling
[1]=pv
;
876 JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData
* data
, uint8
* result
)
878 if (data
->bufferbytesleft
==0)
881 if (data
->filebytesleft
==0)
883 if (!data
->filepositioned
)
885 TIFFSeekFile(data
->tif
,data
->fileoffset
,SEEK_SET
);
886 data
->filepositioned
=1;
889 if ((uint64
)m
>data
->filebytesleft
)
890 m
=(uint32
)data
->filebytesleft
;
891 assert(m
<0x80000000UL
);
892 if (TIFFReadFile(data
->tif
,data
->buffer
,(tmsize_t
)m
)!=(tmsize_t
)m
)
894 data
->buffercurrentbyte
=data
->buffer
;
895 data
->bufferbytesleft
=m
;
897 data
->filebytesleft
-=m
;
899 *result
=*data
->buffercurrentbyte
;
900 data
->buffercurrentbyte
++;
901 data
->bufferbytesleft
--;
906 JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData
* data
, uint16
* result
)
910 if (!JPEGFixupTagsSubsamplingReadByte(data
,&ma
))
912 if (!JPEGFixupTagsSubsamplingReadByte(data
,&mb
))
919 JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData
* data
, uint16 skiplength
)
921 if ((uint32
)skiplength
<=data
->bufferbytesleft
)
923 data
->buffercurrentbyte
+=skiplength
;
924 data
->bufferbytesleft
-=skiplength
;
929 m
=skiplength
-data
->bufferbytesleft
;
930 if (m
<=data
->filebytesleft
)
932 data
->bufferbytesleft
=0;
934 data
->filebytesleft
-=m
;
935 data
->filepositioned
=0;
939 data
->bufferbytesleft
=0;
940 data
->filebytesleft
=0;
949 JPEGSetupDecode(TIFF
* tif
)
951 JPEGState
* sp
= JState(tif
);
952 TIFFDirectory
*td
= &tif
->tif_dir
;
954 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
955 if( tif
->tif_dir
.td_bitspersample
== 12 )
956 return TIFFReInitJPEG_12( tif
, COMPRESSION_JPEG
, 0 );
959 JPEGInitializeLibJPEG( tif
, TRUE
);
962 assert(sp
->cinfo
.comm
.is_decompressor
);
964 /* Read JPEGTables if it is present */
965 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
)) {
966 TIFFjpeg_tables_src(sp
, tif
);
967 if(TIFFjpeg_read_header(sp
,FALSE
) != JPEG_HEADER_TABLES_ONLY
) {
968 TIFFErrorExt(tif
->tif_clientdata
, "JPEGSetupDecode", "Bogus JPEGTables field");
973 /* Grab parameters that are same for all strips/tiles */
974 sp
->photometric
= td
->td_photometric
;
975 switch (sp
->photometric
) {
976 case PHOTOMETRIC_YCBCR
:
977 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
978 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
981 /* TIFF 6.0 forbids subsampling of all other color spaces */
987 /* Set up for reading normal data */
988 TIFFjpeg_data_src(sp
, tif
);
989 tif
->tif_postdecode
= _TIFFNoPostDecode
; /* override byte swapping */
994 * Set up for decoding a strip or tile.
997 JPEGPreDecode(TIFF
* tif
, uint16 s
)
999 JPEGState
*sp
= JState(tif
);
1000 TIFFDirectory
*td
= &tif
->tif_dir
;
1001 static const char module
[] = "JPEGPreDecode";
1002 uint32 segment_width
, segment_height
;
1003 int downsampled_output
;
1008 if (sp
->cinfo
.comm
.is_decompressor
== 0)
1010 tif
->tif_setupdecode( tif
);
1013 assert(sp
->cinfo
.comm
.is_decompressor
);
1015 * Reset decoder state from any previous strip/tile,
1016 * in case application didn't read the whole strip.
1018 if (!TIFFjpeg_abort(sp
))
1021 * Read the header for this strip/tile.
1024 if (TIFFjpeg_read_header(sp
, TRUE
) != JPEG_HEADER_OK
)
1027 tif
->tif_rawcp
= (uint8
*) sp
->src
.next_input_byte
;
1028 tif
->tif_rawcc
= sp
->src
.bytes_in_buffer
;
1031 * Check image parameters and set decompression parameters.
1033 segment_width
= td
->td_imagewidth
;
1034 segment_height
= td
->td_imagelength
- tif
->tif_row
;
1036 segment_width
= td
->td_tilewidth
;
1037 segment_height
= td
->td_tilelength
;
1038 sp
->bytesperline
= TIFFTileRowSize(tif
);
1040 if (segment_height
> td
->td_rowsperstrip
)
1041 segment_height
= td
->td_rowsperstrip
;
1042 sp
->bytesperline
= TIFFScanlineSize(tif
);
1044 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
1046 * For PC 2, scale down the expected strip/tile size
1047 * to match a downsampled component
1049 segment_width
= TIFFhowmany_32(segment_width
, sp
->h_sampling
);
1050 segment_height
= TIFFhowmany_32(segment_height
, sp
->v_sampling
);
1052 if (sp
->cinfo
.d
.image_width
< segment_width
||
1053 sp
->cinfo
.d
.image_height
< segment_height
) {
1054 TIFFWarningExt(tif
->tif_clientdata
, module
,
1055 "Improper JPEG strip/tile size, "
1056 "expected %dx%d, got %dx%d",
1057 segment_width
, segment_height
,
1058 sp
->cinfo
.d
.image_width
,
1059 sp
->cinfo
.d
.image_height
);
1061 if (sp
->cinfo
.d
.image_width
> segment_width
||
1062 sp
->cinfo
.d
.image_height
> segment_height
) {
1064 * This case could be dangerous, if the strip or tile size has
1065 * been reported as less than the amount of data jpeg will
1066 * return, some potential security issues arise. Catch this
1067 * case and error out.
1069 TIFFErrorExt(tif
->tif_clientdata
, module
,
1070 "JPEG strip/tile size exceeds expected dimensions,"
1071 " expected %dx%d, got %dx%d",
1072 segment_width
, segment_height
,
1073 sp
->cinfo
.d
.image_width
, sp
->cinfo
.d
.image_height
);
1076 if (sp
->cinfo
.d
.num_components
!=
1077 (td
->td_planarconfig
== PLANARCONFIG_CONTIG
?
1078 td
->td_samplesperpixel
: 1)) {
1079 TIFFErrorExt(tif
->tif_clientdata
, module
, "Improper JPEG component count");
1083 if (12 != td
->td_bitspersample
&& 8 != td
->td_bitspersample
) {
1084 TIFFErrorExt(tif
->tif_clientdata
, module
, "Improper JPEG data precision");
1087 sp
->cinfo
.d
.data_precision
= td
->td_bitspersample
;
1088 sp
->cinfo
.d
.bits_in_jsample
= td
->td_bitspersample
;
1090 if (sp
->cinfo
.d
.data_precision
!= td
->td_bitspersample
) {
1091 TIFFErrorExt(tif
->tif_clientdata
, module
, "Improper JPEG data precision");
1095 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1096 /* Component 0 should have expected sampling factors */
1097 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= sp
->h_sampling
||
1098 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= sp
->v_sampling
) {
1099 TIFFErrorExt(tif
->tif_clientdata
, module
,
1100 "Improper JPEG sampling factors %d,%d\n"
1101 "Apparently should be %d,%d.",
1102 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
,
1103 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
,
1104 sp
->h_sampling
, sp
->v_sampling
);
1107 /* Rest should have sampling factors 1,1 */
1108 for (ci
= 1; ci
< sp
->cinfo
.d
.num_components
; ci
++) {
1109 if (sp
->cinfo
.d
.comp_info
[ci
].h_samp_factor
!= 1 ||
1110 sp
->cinfo
.d
.comp_info
[ci
].v_samp_factor
!= 1) {
1111 TIFFErrorExt(tif
->tif_clientdata
, module
, "Improper JPEG sampling factors");
1116 /* PC 2's single component should have sampling factors 1,1 */
1117 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= 1 ||
1118 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= 1) {
1119 TIFFErrorExt(tif
->tif_clientdata
, module
, "Improper JPEG sampling factors");
1123 downsampled_output
= FALSE
;
1124 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
1125 sp
->photometric
== PHOTOMETRIC_YCBCR
&&
1126 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1127 /* Convert YCbCr to RGB */
1128 sp
->cinfo
.d
.jpeg_color_space
= JCS_YCbCr
;
1129 sp
->cinfo
.d
.out_color_space
= JCS_RGB
;
1131 /* Suppress colorspace handling */
1132 sp
->cinfo
.d
.jpeg_color_space
= JCS_UNKNOWN
;
1133 sp
->cinfo
.d
.out_color_space
= JCS_UNKNOWN
;
1134 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
1135 (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1))
1136 downsampled_output
= TRUE
;
1137 /* XXX what about up-sampling? */
1139 if (downsampled_output
) {
1140 /* Need to use raw-data interface to libjpeg */
1141 sp
->cinfo
.d
.raw_data_out
= TRUE
;
1142 #if JPEG_LIB_VERSION >= 70
1143 sp
->cinfo
.d
.do_fancy_upsampling
= FALSE
;
1144 #endif /* JPEG_LIB_VERSION >= 70 */
1145 tif
->tif_decoderow
= DecodeRowError
;
1146 tif
->tif_decodestrip
= JPEGDecodeRaw
;
1147 tif
->tif_decodetile
= JPEGDecodeRaw
;
1149 /* Use normal interface to libjpeg */
1150 sp
->cinfo
.d
.raw_data_out
= FALSE
;
1151 tif
->tif_decoderow
= JPEGDecode
;
1152 tif
->tif_decodestrip
= JPEGDecode
;
1153 tif
->tif_decodetile
= JPEGDecode
;
1155 /* Start JPEG decompressor */
1156 if (!TIFFjpeg_start_decompress(sp
))
1158 /* Allocate downsampled-data buffers if needed */
1159 if (downsampled_output
) {
1160 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.d
.comp_info
,
1161 sp
->cinfo
.d
.num_components
))
1163 sp
->scancount
= DCTSIZE
; /* mark buffer empty */
1169 * Decode a chunk of pixels.
1170 * "Standard" case: returned data is not downsampled.
1172 /*ARGSUSED*/ static int
1173 JPEGDecode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1175 JPEGState
*sp
= JState(tif
);
1180 ** Update available information, buffer may have been refilled
1181 ** between decode requests
1183 sp
->src
.next_input_byte
= (const JOCTET
*) tif
->tif_rawcp
;
1184 sp
->src
.bytes_in_buffer
= (size_t) tif
->tif_rawcc
;
1186 if( sp
->bytesperline
== 0 )
1189 nrows
= cc
/ sp
->bytesperline
;
1190 if (cc
% sp
->bytesperline
)
1191 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline not read");
1193 if( nrows
> (tmsize_t
) sp
->cinfo
.d
.image_height
)
1194 nrows
= sp
->cinfo
.d
.image_height
;
1196 /* data is expected to be read in multiples of a scanline */
1199 JSAMPROW line_work_buf
= NULL
;
1202 * For 6B, only use temporary buffer for 12 bit imagery.
1203 * For Mk1 always use it.
1205 #if !defined(JPEG_LIB_MK1)
1206 if( sp
->cinfo
.d
.data_precision
== 12 )
1209 line_work_buf
= (JSAMPROW
)
1210 _TIFFmalloc(sizeof(short) * sp
->cinfo
.d
.output_width
1211 * sp
->cinfo
.d
.num_components
);
1215 if( line_work_buf
!= NULL
)
1218 * In the MK1 case, we aways read into a 16bit buffer, and then
1219 * pack down to 12bit or 8bit. In 6B case we only read into 16
1220 * bit buffer for 12bit data, which we need to repack.
1222 if (TIFFjpeg_read_scanlines(sp
, &line_work_buf
, 1) != 1)
1225 if( sp
->cinfo
.d
.data_precision
== 12 )
1227 int value_pairs
= (sp
->cinfo
.d
.output_width
1228 * sp
->cinfo
.d
.num_components
) / 2;
1231 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1233 unsigned char *out_ptr
=
1234 ((unsigned char *) buf
) + iPair
* 3;
1235 JSAMPLE
*in_ptr
= line_work_buf
+ iPair
* 2;
1237 out_ptr
[0] = (in_ptr
[0] & 0xff0) >> 4;
1238 out_ptr
[1] = ((in_ptr
[0] & 0xf) << 4)
1239 | ((in_ptr
[1] & 0xf00) >> 8);
1240 out_ptr
[2] = ((in_ptr
[1] & 0xff) >> 0);
1243 else if( sp
->cinfo
.d
.data_precision
== 8 )
1245 int value_count
= (sp
->cinfo
.d
.output_width
1246 * sp
->cinfo
.d
.num_components
);
1249 for( iValue
= 0; iValue
< value_count
; iValue
++ )
1251 ((unsigned char *) buf
)[iValue
] =
1252 line_work_buf
[iValue
] & 0xff;
1259 * In the libjpeg6b 8bit case. We read directly into the
1262 JSAMPROW bufptr
= (JSAMPROW
)buf
;
1264 if (TIFFjpeg_read_scanlines(sp
, &bufptr
, 1) != 1)
1269 buf
+= sp
->bytesperline
;
1270 cc
-= sp
->bytesperline
;
1271 } while (--nrows
> 0);
1273 if( line_work_buf
!= NULL
)
1274 _TIFFfree( line_work_buf
);
1277 /* Update information on consumed data */
1278 tif
->tif_rawcp
= (uint8
*) sp
->src
.next_input_byte
;
1279 tif
->tif_rawcc
= sp
->src
.bytes_in_buffer
;
1281 /* Close down the decompressor if we've finished the strip or tile. */
1282 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
1283 || TIFFjpeg_finish_decompress(sp
);
1286 /*ARGSUSED*/ static int
1287 DecodeRowError(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1294 TIFFErrorExt(tif
->tif_clientdata
, "TIFFReadScanline",
1295 "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
1300 * Decode a chunk of pixels.
1301 * Returned data is downsampled per sampling factors.
1303 /*ARGSUSED*/ static int
1304 JPEGDecodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1306 JPEGState
*sp
= JState(tif
);
1310 /* data is expected to be read in multiples of a scanline */
1311 if ( (nrows
= sp
->cinfo
.d
.image_height
) ) {
1313 /* Cb,Cr both have sampling factors 1, so this is correct */
1314 JDIMENSION clumps_per_line
= sp
->cinfo
.d
.comp_info
[1].downsampled_width
;
1315 int samples_per_clump
= sp
->samplesperclump
;
1317 #if defined(JPEG_LIB_MK1_OR_12BIT)
1318 unsigned short* tmpbuf
= _TIFFmalloc(sizeof(unsigned short) *
1319 sp
->cinfo
.d
.output_width
*
1320 sp
->cinfo
.d
.num_components
);
1322 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1329 jpeg_component_info
*compptr
;
1330 int ci
, clumpoffset
;
1332 if( cc
< sp
->bytesperline
) {
1333 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1334 "application buffer not large enough for all data.");
1338 /* Reload downsampled-data buffer if needed */
1339 if (sp
->scancount
>= DCTSIZE
) {
1340 int n
= sp
->cinfo
.d
.max_v_samp_factor
* DCTSIZE
;
1341 if (TIFFjpeg_read_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1346 * Fastest way to unseparate data is to make one pass
1347 * over the scanline for each row of each component.
1349 clumpoffset
= 0; /* first sample in clump */
1350 for (ci
= 0, compptr
= sp
->cinfo
.d
.comp_info
;
1351 ci
< sp
->cinfo
.d
.num_components
;
1353 int hsamp
= compptr
->h_samp_factor
;
1354 int vsamp
= compptr
->v_samp_factor
;
1357 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
1358 JSAMPLE
*inptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
1360 #if defined(JPEG_LIB_MK1_OR_12BIT)
1361 JSAMPLE
*outptr
= (JSAMPLE
*)tmpbuf
+ clumpoffset
;
1363 JSAMPLE
*outptr
= (JSAMPLE
*)buf
+ clumpoffset
;
1364 if (cc
< (tmsize_t
) (clumpoffset
+ samples_per_clump
*(clumps_per_line
-1) + hsamp
)) {
1365 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1366 "application buffer not large enough for all data, possible subsampling issue");
1372 /* fast path for at least Cb and Cr */
1373 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1374 outptr
[0] = *inptr
++;
1375 outptr
+= samples_per_clump
;
1381 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1382 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1383 outptr
[xpos
] = *inptr
++;
1384 outptr
+= samples_per_clump
;
1387 clumpoffset
+= hsamp
;
1391 #if defined(JPEG_LIB_MK1_OR_12BIT)
1393 if (sp
->cinfo
.d
.data_precision
== 8)
1396 int len
= sp
->cinfo
.d
.output_width
* sp
->cinfo
.d
.num_components
;
1397 for (i
=0; i
<len
; i
++)
1399 ((unsigned char*)buf
)[i
] = tmpbuf
[i
] & 0xff;
1404 int value_pairs
= (sp
->cinfo
.d
.output_width
1405 * sp
->cinfo
.d
.num_components
) / 2;
1407 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1409 unsigned char *out_ptr
= ((unsigned char *) buf
) + iPair
* 3;
1410 JSAMPLE
*in_ptr
= (JSAMPLE
*) (tmpbuf
+ iPair
* 2);
1411 out_ptr
[0] = (in_ptr
[0] & 0xff0) >> 4;
1412 out_ptr
[1] = ((in_ptr
[0] & 0xf) << 4)
1413 | ((in_ptr
[1] & 0xf00) >> 8);
1414 out_ptr
[2] = ((in_ptr
[1] & 0xff) >> 0);
1421 tif
->tif_row
+= sp
->v_sampling
;
1423 buf
+= sp
->bytesperline
;
1424 cc
-= sp
->bytesperline
;
1426 nrows
-= sp
->v_sampling
;
1427 } while (nrows
> 0);
1429 #if defined(JPEG_LIB_MK1_OR_12BIT)
1435 /* Close down the decompressor if done. */
1436 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
1437 || TIFFjpeg_finish_decompress(sp
);
1446 unsuppress_quant_table (JPEGState
* sp
, int tblno
)
1450 if ((qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[tblno
]) != NULL
)
1451 qtbl
->sent_table
= FALSE
;
1455 unsuppress_huff_table (JPEGState
* sp
, int tblno
)
1459 if ((htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[tblno
]) != NULL
)
1460 htbl
->sent_table
= FALSE
;
1461 if ((htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[tblno
]) != NULL
)
1462 htbl
->sent_table
= FALSE
;
1466 prepare_JPEGTables(TIFF
* tif
)
1468 JPEGState
* sp
= JState(tif
);
1470 /* Initialize quant tables for current quality setting */
1471 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1473 /* Mark only the tables we want for output */
1474 /* NB: chrominance tables are currently used only with YCbCr */
1475 if (!TIFFjpeg_suppress_tables(sp
, TRUE
))
1477 if (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
) {
1478 unsuppress_quant_table(sp
, 0);
1479 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1480 unsuppress_quant_table(sp
, 1);
1482 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
) {
1483 unsuppress_huff_table(sp
, 0);
1484 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1485 unsuppress_huff_table(sp
, 1);
1487 /* Direct libjpeg output into jpegtables */
1488 if (!TIFFjpeg_tables_dest(sp
, tif
))
1490 /* Emit tables-only datastream */
1491 if (!TIFFjpeg_write_tables(sp
))
1498 JPEGSetupEncode(TIFF
* tif
)
1500 JPEGState
* sp
= JState(tif
);
1501 TIFFDirectory
*td
= &tif
->tif_dir
;
1502 static const char module
[] = "JPEGSetupEncode";
1504 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
1505 if( tif
->tif_dir
.td_bitspersample
== 12 )
1506 return TIFFReInitJPEG_12( tif
, COMPRESSION_JPEG
, 1 );
1509 JPEGInitializeLibJPEG( tif
, FALSE
);
1512 assert(!sp
->cinfo
.comm
.is_decompressor
);
1515 * Initialize all JPEG parameters to default values.
1516 * Note that jpeg_set_defaults needs legal values for
1517 * in_color_space and input_components.
1519 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1520 sp
->cinfo
.c
.input_components
= 1;
1521 if (!TIFFjpeg_set_defaults(sp
))
1523 /* Set per-file parameters */
1524 sp
->photometric
= td
->td_photometric
;
1525 switch (sp
->photometric
) {
1526 case PHOTOMETRIC_YCBCR
:
1527 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
1528 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
1530 * A ReferenceBlackWhite field *must* be present since the
1531 * default value is inappropriate for YCbCr. Fill in the
1532 * proper value if application didn't set it.
1536 if (!TIFFGetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1539 long top
= 1L << td
->td_bitspersample
;
1541 refbw
[1] = (float)(top
-1L);
1542 refbw
[2] = (float)(top
>>1);
1543 refbw
[3] = refbw
[1];
1544 refbw
[4] = refbw
[2];
1545 refbw
[5] = refbw
[1];
1546 TIFFSetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1551 case PHOTOMETRIC_PALETTE
: /* disallowed by Tech Note */
1552 case PHOTOMETRIC_MASK
:
1553 TIFFErrorExt(tif
->tif_clientdata
, module
,
1554 "PhotometricInterpretation %d not allowed for JPEG",
1555 (int) sp
->photometric
);
1558 /* TIFF 6.0 forbids subsampling of all other color spaces */
1564 /* Verify miscellaneous parameters */
1567 * This would need work if libtiff ever supports different
1568 * depths for different components, or if libjpeg ever supports
1569 * run-time selection of depth. Neither is imminent.
1572 /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1573 if (td
->td_bitspersample
!= 8 && td
->td_bitspersample
!= 12)
1575 if (td
->td_bitspersample
!= BITS_IN_JSAMPLE
)
1578 TIFFErrorExt(tif
->tif_clientdata
, module
, "BitsPerSample %d not allowed for JPEG",
1579 (int) td
->td_bitspersample
);
1582 sp
->cinfo
.c
.data_precision
= td
->td_bitspersample
;
1584 sp
->cinfo
.c
.bits_in_jsample
= td
->td_bitspersample
;
1587 if ((td
->td_tilelength
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1588 TIFFErrorExt(tif
->tif_clientdata
, module
,
1589 "JPEG tile height must be multiple of %d",
1590 sp
->v_sampling
* DCTSIZE
);
1593 if ((td
->td_tilewidth
% (sp
->h_sampling
* DCTSIZE
)) != 0) {
1594 TIFFErrorExt(tif
->tif_clientdata
, module
,
1595 "JPEG tile width must be multiple of %d",
1596 sp
->h_sampling
* DCTSIZE
);
1600 if (td
->td_rowsperstrip
< td
->td_imagelength
&&
1601 (td
->td_rowsperstrip
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1602 TIFFErrorExt(tif
->tif_clientdata
, module
,
1603 "RowsPerStrip must be multiple of %d for JPEG",
1604 sp
->v_sampling
* DCTSIZE
);
1609 /* Create a JPEGTables field if appropriate */
1610 if (sp
->jpegtablesmode
& (JPEGTABLESMODE_QUANT
|JPEGTABLESMODE_HUFF
)) {
1611 if( sp
->jpegtables
== NULL
1612 || memcmp(sp
->jpegtables
,"\0\0\0\0\0\0\0\0\0",8) == 0 )
1614 if (!prepare_JPEGTables(tif
))
1616 /* Mark the field present */
1617 /* Can't use TIFFSetField since BEENWRITING is already set! */
1618 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1619 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1622 /* We do not support application-supplied JPEGTables, */
1623 /* so mark the field not present */
1624 TIFFClrFieldBit(tif
, FIELD_JPEGTABLES
);
1627 /* Direct libjpeg output to libtiff's output buffer */
1628 TIFFjpeg_data_dest(sp
, tif
);
1634 * Set encoding state at the start of a strip or tile.
1637 JPEGPreEncode(TIFF
* tif
, uint16 s
)
1639 JPEGState
*sp
= JState(tif
);
1640 TIFFDirectory
*td
= &tif
->tif_dir
;
1641 static const char module
[] = "JPEGPreEncode";
1642 uint32 segment_width
, segment_height
;
1643 int downsampled_input
;
1647 if (sp
->cinfo
.comm
.is_decompressor
== 1)
1649 tif
->tif_setupencode( tif
);
1652 assert(!sp
->cinfo
.comm
.is_decompressor
);
1654 * Set encoding parameters for this strip/tile.
1657 segment_width
= td
->td_tilewidth
;
1658 segment_height
= td
->td_tilelength
;
1659 sp
->bytesperline
= TIFFTileRowSize(tif
);
1661 segment_width
= td
->td_imagewidth
;
1662 segment_height
= td
->td_imagelength
- tif
->tif_row
;
1663 if (segment_height
> td
->td_rowsperstrip
)
1664 segment_height
= td
->td_rowsperstrip
;
1665 sp
->bytesperline
= TIFFScanlineSize(tif
);
1667 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
1668 /* for PC 2, scale down the strip/tile size
1669 * to match a downsampled component
1671 segment_width
= TIFFhowmany_32(segment_width
, sp
->h_sampling
);
1672 segment_height
= TIFFhowmany_32(segment_height
, sp
->v_sampling
);
1674 if (segment_width
> 65535 || segment_height
> 65535) {
1675 TIFFErrorExt(tif
->tif_clientdata
, module
, "Strip/tile too large for JPEG");
1678 sp
->cinfo
.c
.image_width
= segment_width
;
1679 sp
->cinfo
.c
.image_height
= segment_height
;
1680 downsampled_input
= FALSE
;
1681 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1682 sp
->cinfo
.c
.input_components
= td
->td_samplesperpixel
;
1683 if (sp
->photometric
== PHOTOMETRIC_YCBCR
) {
1684 if (sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1685 sp
->cinfo
.c
.in_color_space
= JCS_RGB
;
1687 sp
->cinfo
.c
.in_color_space
= JCS_YCbCr
;
1688 if (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1)
1689 downsampled_input
= TRUE
;
1691 if (!TIFFjpeg_set_colorspace(sp
, JCS_YCbCr
))
1694 * Set Y sampling factors;
1695 * we assume jpeg_set_colorspace() set the rest to 1
1697 sp
->cinfo
.c
.comp_info
[0].h_samp_factor
= sp
->h_sampling
;
1698 sp
->cinfo
.c
.comp_info
[0].v_samp_factor
= sp
->v_sampling
;
1700 if ((td
->td_photometric
== PHOTOMETRIC_MINISWHITE
|| td
->td_photometric
== PHOTOMETRIC_MINISBLACK
) && td
->td_samplesperpixel
== 1)
1701 sp
->cinfo
.c
.in_color_space
= JCS_GRAYSCALE
;
1702 else if (td
->td_photometric
== PHOTOMETRIC_RGB
&& td
->td_samplesperpixel
== 3)
1703 sp
->cinfo
.c
.in_color_space
= JCS_RGB
;
1704 else if (td
->td_photometric
== PHOTOMETRIC_SEPARATED
&& td
->td_samplesperpixel
== 4)
1705 sp
->cinfo
.c
.in_color_space
= JCS_CMYK
;
1707 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1708 if (!TIFFjpeg_set_colorspace(sp
, sp
->cinfo
.c
.in_color_space
))
1710 /* jpeg_set_colorspace set all sampling factors to 1 */
1713 sp
->cinfo
.c
.input_components
= 1;
1714 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1715 if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
))
1717 sp
->cinfo
.c
.comp_info
[0].component_id
= s
;
1718 /* jpeg_set_colorspace() set sampling factors to 1 */
1719 if (sp
->photometric
== PHOTOMETRIC_YCBCR
&& s
> 0) {
1720 sp
->cinfo
.c
.comp_info
[0].quant_tbl_no
= 1;
1721 sp
->cinfo
.c
.comp_info
[0].dc_tbl_no
= 1;
1722 sp
->cinfo
.c
.comp_info
[0].ac_tbl_no
= 1;
1725 /* ensure libjpeg won't write any extraneous markers */
1726 sp
->cinfo
.c
.write_JFIF_header
= FALSE
;
1727 sp
->cinfo
.c
.write_Adobe_marker
= FALSE
;
1728 /* set up table handling correctly */
1729 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1731 if (! (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
)) {
1732 unsuppress_quant_table(sp
, 0);
1733 unsuppress_quant_table(sp
, 1);
1735 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
)
1736 sp
->cinfo
.c
.optimize_coding
= FALSE
;
1738 sp
->cinfo
.c
.optimize_coding
= TRUE
;
1739 if (downsampled_input
) {
1740 /* Need to use raw-data interface to libjpeg */
1741 sp
->cinfo
.c
.raw_data_in
= TRUE
;
1742 tif
->tif_encoderow
= JPEGEncodeRaw
;
1743 tif
->tif_encodestrip
= JPEGEncodeRaw
;
1744 tif
->tif_encodetile
= JPEGEncodeRaw
;
1746 /* Use normal interface to libjpeg */
1747 sp
->cinfo
.c
.raw_data_in
= FALSE
;
1748 tif
->tif_encoderow
= JPEGEncode
;
1749 tif
->tif_encodestrip
= JPEGEncode
;
1750 tif
->tif_encodetile
= JPEGEncode
;
1752 /* Start JPEG compressor */
1753 if (!TIFFjpeg_start_compress(sp
, FALSE
))
1755 /* Allocate downsampled-data buffers if needed */
1756 if (downsampled_input
) {
1757 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.c
.comp_info
,
1758 sp
->cinfo
.c
.num_components
))
1767 * Encode a chunk of pixels.
1768 * "Standard" case: incoming data is not downsampled.
1771 JPEGEncode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1773 JPEGState
*sp
= JState(tif
);
1776 short *line16
= NULL
;
1777 int line16_count
= 0;
1781 /* data is expected to be supplied in multiples of a scanline */
1782 nrows
= cc
/ sp
->bytesperline
;
1783 if (cc
% sp
->bytesperline
)
1784 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
,
1785 "fractional scanline discarded");
1787 /* The last strip will be limited to image size */
1788 if( !isTiled(tif
) && tif
->tif_row
+nrows
> tif
->tif_dir
.td_imagelength
)
1789 nrows
= tif
->tif_dir
.td_imagelength
- tif
->tif_row
;
1791 if( sp
->cinfo
.c
.data_precision
== 12 )
1793 line16_count
= (sp
->bytesperline
* 2) / 3;
1794 line16
= (short *) _TIFFmalloc(sizeof(short) * line16_count
);
1795 // FIXME: undiagnosed malloc failure
1798 while (nrows
-- > 0) {
1800 if( sp
->cinfo
.c
.data_precision
== 12 )
1803 int value_pairs
= line16_count
/ 2;
1806 bufptr
[0] = (JSAMPROW
) line16
;
1808 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1810 unsigned char *in_ptr
=
1811 ((unsigned char *) buf
) + iPair
* 3;
1812 JSAMPLE
*out_ptr
= (JSAMPLE
*) (line16
+ iPair
* 2);
1814 out_ptr
[0] = (in_ptr
[0] << 4) | ((in_ptr
[1] & 0xf0) >> 4);
1815 out_ptr
[1] = ((in_ptr
[1] & 0x0f) << 8) | in_ptr
[2];
1820 bufptr
[0] = (JSAMPROW
) buf
;
1822 if (TIFFjpeg_write_scanlines(sp
, bufptr
, 1) != 1)
1826 buf
+= sp
->bytesperline
;
1829 if( sp
->cinfo
.c
.data_precision
== 12 )
1831 _TIFFfree( line16
);
1838 * Encode a chunk of pixels.
1839 * Incoming data is expected to be downsampled per sampling factors.
1842 JPEGEncodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1844 JPEGState
*sp
= JState(tif
);
1848 JDIMENSION clumps_per_line
, nclump
;
1849 int clumpoffset
, ci
, xpos
, ypos
;
1850 jpeg_component_info
* compptr
;
1851 int samples_per_clump
= sp
->samplesperclump
;
1852 tmsize_t bytesperclumpline
;
1856 /* data is expected to be supplied in multiples of a clumpline */
1857 /* a clumpline is equivalent to v_sampling desubsampled scanlines */
1858 /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
1859 bytesperclumpline
= (((sp
->cinfo
.c
.image_width
+sp
->h_sampling
-1)/sp
->h_sampling
)
1860 *(sp
->h_sampling
*sp
->v_sampling
+2)*sp
->cinfo
.c
.data_precision
+7)
1863 nrows
= ( cc
/ bytesperclumpline
) * sp
->v_sampling
;
1864 if (cc
% bytesperclumpline
)
1865 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline discarded");
1867 /* Cb,Cr both have sampling factors 1, so this is correct */
1868 clumps_per_line
= sp
->cinfo
.c
.comp_info
[1].downsampled_width
;
1872 * Fastest way to separate the data is to make one pass
1873 * over the scanline for each row of each component.
1875 clumpoffset
= 0; /* first sample in clump */
1876 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1877 ci
< sp
->cinfo
.c
.num_components
;
1879 int hsamp
= compptr
->h_samp_factor
;
1880 int vsamp
= compptr
->v_samp_factor
;
1881 int padding
= (int) (compptr
->width_in_blocks
* DCTSIZE
-
1882 clumps_per_line
* hsamp
);
1883 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
1884 inptr
= ((JSAMPLE
*) buf
) + clumpoffset
;
1885 outptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
1887 /* fast path for at least Cb and Cr */
1888 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1889 *outptr
++ = inptr
[0];
1890 inptr
+= samples_per_clump
;
1894 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1895 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1896 *outptr
++ = inptr
[xpos
];
1897 inptr
+= samples_per_clump
;
1900 /* pad each scanline as needed */
1901 for (xpos
= 0; xpos
< padding
; xpos
++) {
1902 *outptr
= outptr
[-1];
1905 clumpoffset
+= hsamp
;
1909 if (sp
->scancount
>= DCTSIZE
) {
1910 int n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1911 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1915 tif
->tif_row
+= sp
->v_sampling
;
1916 buf
+= bytesperclumpline
;
1917 nrows
-= sp
->v_sampling
;
1923 * Finish up at the end of a strip or tile.
1926 JPEGPostEncode(TIFF
* tif
)
1928 JPEGState
*sp
= JState(tif
);
1930 if (sp
->scancount
> 0) {
1932 * Need to emit a partial bufferload of downsampled data.
1933 * Pad the data vertically.
1936 jpeg_component_info
* compptr
;
1938 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1939 ci
< sp
->cinfo
.c
.num_components
;
1941 int vsamp
= compptr
->v_samp_factor
;
1942 tmsize_t row_width
= compptr
->width_in_blocks
* DCTSIZE
1944 for (ypos
= sp
->scancount
* vsamp
;
1945 ypos
< DCTSIZE
* vsamp
; ypos
++) {
1946 _TIFFmemcpy((void*)sp
->ds_buffer
[ci
][ypos
],
1947 (void*)sp
->ds_buffer
[ci
][ypos
-1],
1952 n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1953 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1957 return (TIFFjpeg_finish_compress(JState(tif
)));
1961 JPEGCleanup(TIFF
* tif
)
1963 JPEGState
*sp
= JState(tif
);
1967 tif
->tif_tagmethods
.vgetfield
= sp
->vgetparent
;
1968 tif
->tif_tagmethods
.vsetfield
= sp
->vsetparent
;
1969 tif
->tif_tagmethods
.printdir
= sp
->printdir
;
1972 if( sp
->cinfo_initialized
)
1973 TIFFjpeg_destroy(sp
); /* release libjpeg resources */
1974 if (sp
->jpegtables
) /* tag value */
1975 _TIFFfree(sp
->jpegtables
);
1977 _TIFFfree(tif
->tif_data
); /* release local state */
1978 tif
->tif_data
= NULL
;
1980 _TIFFSetDefaultCompressionState(tif
);
1984 JPEGResetUpsampled( TIFF
* tif
)
1986 JPEGState
* sp
= JState(tif
);
1987 TIFFDirectory
* td
= &tif
->tif_dir
;
1990 * Mark whether returned data is up-sampled or not so TIFFStripSize
1991 * and TIFFTileSize return values that reflect the true amount of
1994 tif
->tif_flags
&= ~TIFF_UPSAMPLED
;
1995 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1996 if (td
->td_photometric
== PHOTOMETRIC_YCBCR
&&
1997 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1998 tif
->tif_flags
|= TIFF_UPSAMPLED
;
2001 if (td
->td_ycbcrsubsampling
[0] != 1 ||
2002 td
->td_ycbcrsubsampling
[1] != 1)
2003 ; /* XXX what about up-sampling? */
2009 * Must recalculate cached tile size in case sampling state changed.
2010 * Should we really be doing this now if image size isn't set?
2012 if( tif
->tif_tilesize
> 0 )
2013 tif
->tif_tilesize
= isTiled(tif
) ? TIFFTileSize(tif
) : (tmsize_t
)(-1);
2014 if( tif
->tif_scanlinesize
> 0 )
2015 tif
->tif_scanlinesize
= TIFFScanlineSize(tif
);
2019 JPEGVSetField(TIFF
* tif
, uint32 tag
, va_list ap
)
2021 JPEGState
* sp
= JState(tif
);
2022 const TIFFField
* fip
;
2028 case TIFFTAG_JPEGTABLES
:
2029 v32
= (uint32
) va_arg(ap
, uint32
);
2034 _TIFFsetByteArray(&sp
->jpegtables
, va_arg(ap
, void*),
2036 sp
->jpegtables_length
= v32
;
2037 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
2039 case TIFFTAG_JPEGQUALITY
:
2040 sp
->jpegquality
= (int) va_arg(ap
, int);
2041 return (1); /* pseudo tag */
2042 case TIFFTAG_JPEGCOLORMODE
:
2043 sp
->jpegcolormode
= (int) va_arg(ap
, int);
2044 JPEGResetUpsampled( tif
);
2045 return (1); /* pseudo tag */
2046 case TIFFTAG_PHOTOMETRIC
:
2048 int ret_value
= (*sp
->vsetparent
)(tif
, tag
, ap
);
2049 JPEGResetUpsampled( tif
);
2052 case TIFFTAG_JPEGTABLESMODE
:
2053 sp
->jpegtablesmode
= (int) va_arg(ap
, int);
2054 return (1); /* pseudo tag */
2055 case TIFFTAG_YCBCRSUBSAMPLING
:
2056 /* mark the fact that we have a real ycbcrsubsampling! */
2057 sp
->ycbcrsampling_fetched
= 1;
2058 /* should we be recomputing upsampling info here? */
2059 return (*sp
->vsetparent
)(tif
, tag
, ap
);
2061 return (*sp
->vsetparent
)(tif
, tag
, ap
);
2064 if ((fip
= TIFFFieldWithTag(tif
, tag
))) {
2065 TIFFSetFieldBit(tif
, fip
->field_bit
);
2070 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
2075 JPEGVGetField(TIFF
* tif
, uint32 tag
, va_list ap
)
2077 JPEGState
* sp
= JState(tif
);
2082 case TIFFTAG_JPEGTABLES
:
2083 *va_arg(ap
, uint32
*) = sp
->jpegtables_length
;
2084 *va_arg(ap
, void**) = sp
->jpegtables
;
2086 case TIFFTAG_JPEGQUALITY
:
2087 *va_arg(ap
, int*) = sp
->jpegquality
;
2089 case TIFFTAG_JPEGCOLORMODE
:
2090 *va_arg(ap
, int*) = sp
->jpegcolormode
;
2092 case TIFFTAG_JPEGTABLESMODE
:
2093 *va_arg(ap
, int*) = sp
->jpegtablesmode
;
2096 return (*sp
->vgetparent
)(tif
, tag
, ap
);
2102 JPEGPrintDir(TIFF
* tif
, FILE* fd
, long flags
)
2104 JPEGState
* sp
= JState(tif
);
2110 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
))
2111 fprintf(fd
, " JPEG Tables: (%lu bytes)\n",
2112 (unsigned long) sp
->jpegtables_length
);
2114 (*sp
->printdir
)(tif
, fd
, flags
);
2119 JPEGDefaultStripSize(TIFF
* tif
, uint32 s
)
2121 JPEGState
* sp
= JState(tif
);
2122 TIFFDirectory
*td
= &tif
->tif_dir
;
2124 s
= (*sp
->defsparent
)(tif
, s
);
2125 if (s
< td
->td_imagelength
)
2126 s
= TIFFroundup_32(s
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
2131 JPEGDefaultTileSize(TIFF
* tif
, uint32
* tw
, uint32
* th
)
2133 JPEGState
* sp
= JState(tif
);
2134 TIFFDirectory
*td
= &tif
->tif_dir
;
2136 (*sp
->deftparent
)(tif
, tw
, th
);
2137 *tw
= TIFFroundup_32(*tw
, td
->td_ycbcrsubsampling
[0] * DCTSIZE
);
2138 *th
= TIFFroundup_32(*th
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
2142 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
2143 * now that we allow a TIFF file to be opened in update mode it is necessary
2144 * to have some way of deciding whether compression or decompression is
2145 * desired other than looking at tif->tif_mode. We accomplish this by
2146 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
2147 * If so, we assume decompression is desired.
2149 * This is tricky, because TIFFInitJPEG() is called while the directory is
2150 * being read, and generally speaking the BYTECOUNTS tag won't have been read
2151 * at that point. So we try to defer jpeg library initialization till we
2152 * do have that tag ... basically any access that might require the compressor
2153 * or decompressor that occurs after the reading of the directory.
2155 * In an ideal world compressors or decompressors would be setup
2156 * at the point where a single tile or strip was accessed (for read or write)
2157 * so that stuff like update of missing tiles, or replacement of tiles could
2158 * be done. However, we aren't trying to crack that nut just yet ...
2160 * NFW, Feb 3rd, 2003.
2163 static int JPEGInitializeLibJPEG( TIFF
* tif
, int decompress
)
2165 JPEGState
* sp
= JState(tif
);
2167 if(sp
->cinfo_initialized
)
2169 if( !decompress
&& sp
->cinfo
.comm
.is_decompressor
)
2170 TIFFjpeg_destroy( sp
);
2171 else if( decompress
&& !sp
->cinfo
.comm
.is_decompressor
)
2172 TIFFjpeg_destroy( sp
);
2176 sp
->cinfo_initialized
= 0;
2180 * Initialize libjpeg.
2183 if (!TIFFjpeg_create_decompress(sp
))
2186 if (!TIFFjpeg_create_compress(sp
))
2190 sp
->cinfo_initialized
= TRUE
;
2196 TIFFInitJPEG(TIFF
* tif
, int scheme
)
2200 assert(scheme
== COMPRESSION_JPEG
);
2203 * Merge codec-specific tag information.
2205 if (!_TIFFMergeFields(tif
, jpegFields
, TIFFArrayCount(jpegFields
))) {
2206 TIFFErrorExt(tif
->tif_clientdata
,
2208 "Merging JPEG codec-specific tags failed");
2213 * Allocate state block so tag methods have storage to record values.
2215 tif
->tif_data
= (uint8
*) _TIFFmalloc(sizeof (JPEGState
));
2217 if (tif
->tif_data
== NULL
) {
2218 TIFFErrorExt(tif
->tif_clientdata
,
2219 "TIFFInitJPEG", "No space for JPEG state block");
2222 _TIFFmemset(tif
->tif_data
, 0, sizeof(JPEGState
));
2225 sp
->tif
= tif
; /* back link */
2228 * Override parent get/set field methods.
2230 sp
->vgetparent
= tif
->tif_tagmethods
.vgetfield
;
2231 tif
->tif_tagmethods
.vgetfield
= JPEGVGetField
; /* hook for codec tags */
2232 sp
->vsetparent
= tif
->tif_tagmethods
.vsetfield
;
2233 tif
->tif_tagmethods
.vsetfield
= JPEGVSetField
; /* hook for codec tags */
2234 sp
->printdir
= tif
->tif_tagmethods
.printdir
;
2235 tif
->tif_tagmethods
.printdir
= JPEGPrintDir
; /* hook for codec tags */
2237 /* Default values for codec-specific fields */
2238 sp
->jpegtables
= NULL
;
2239 sp
->jpegtables_length
= 0;
2240 sp
->jpegquality
= 75; /* Default IJG quality */
2241 sp
->jpegcolormode
= JPEGCOLORMODE_RAW
;
2242 sp
->jpegtablesmode
= JPEGTABLESMODE_QUANT
| JPEGTABLESMODE_HUFF
;
2243 sp
->ycbcrsampling_fetched
= 0;
2246 * Install codec methods.
2248 tif
->tif_fixuptags
= JPEGFixupTags
;
2249 tif
->tif_setupdecode
= JPEGSetupDecode
;
2250 tif
->tif_predecode
= JPEGPreDecode
;
2251 tif
->tif_decoderow
= JPEGDecode
;
2252 tif
->tif_decodestrip
= JPEGDecode
;
2253 tif
->tif_decodetile
= JPEGDecode
;
2254 tif
->tif_setupencode
= JPEGSetupEncode
;
2255 tif
->tif_preencode
= JPEGPreEncode
;
2256 tif
->tif_postencode
= JPEGPostEncode
;
2257 tif
->tif_encoderow
= JPEGEncode
;
2258 tif
->tif_encodestrip
= JPEGEncode
;
2259 tif
->tif_encodetile
= JPEGEncode
;
2260 tif
->tif_cleanup
= JPEGCleanup
;
2261 sp
->defsparent
= tif
->tif_defstripsize
;
2262 tif
->tif_defstripsize
= JPEGDefaultStripSize
;
2263 sp
->deftparent
= tif
->tif_deftilesize
;
2264 tif
->tif_deftilesize
= JPEGDefaultTileSize
;
2265 tif
->tif_flags
|= TIFF_NOBITREV
; /* no bit reversal, please */
2267 sp
->cinfo_initialized
= FALSE
;
2270 ** Create a JPEGTables field if no directory has yet been created.
2271 ** We do this just to ensure that sufficient space is reserved for
2272 ** the JPEGTables field. It will be properly created the right
2275 if( tif
->tif_diroff
== 0 )
2277 #define SIZE_OF_JPEGTABLES 2000
2279 The following line assumes incorrectly that all JPEG-in-TIFF files will have
2280 a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
2281 when the JPEG data is placed with TIFFWriteRawStrip. The field bit should be
2282 set, anyway, later when actual JPEGTABLES header is generated, so removing it
2283 here hopefully is harmless.
2284 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2286 sp
->jpegtables_length
= SIZE_OF_JPEGTABLES
;
2287 sp
->jpegtables
= (void *) _TIFFmalloc(sp
->jpegtables_length
);
2288 // FIXME: NULL-deref after malloc failure
2289 _TIFFmemset(sp
->jpegtables
, 0, SIZE_OF_JPEGTABLES
);
2290 #undef SIZE_OF_JPEGTABLES
2295 #endif /* JPEG_SUPPORT */
2297 /* vim: set ts=8 sts=8 sw=8 noet: */