4 * Copyright (c) 1994-1997 Sam Leffler
5 * Copyright (c) 1994-1997 Silicon Graphics, Inc.
7 * Permission to use, copy, modify, distribute, and sell this software and
8 * its documentation for any purpose is hereby granted without fee, provided
9 * that (i) the above copyright notices and this permission notice appear in
10 * all copies of the software and related documentation, and (ii) the names of
11 * Sam Leffler and Silicon Graphics may not be used in any advertising or
12 * publicity relating to the software without the specific, prior written
13 * permission of Sam Leffler and Silicon Graphics.
15 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
19 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
27 #define WIN32_LEAN_AND_MEAN
36 * JPEG Compression support per TIFF Technical Note #2
37 * (*not* per the original TIFF 6.0 spec).
39 * This file is simply an interface to the libjpeg library written by
40 * the Independent JPEG Group. You need release 5 or later of the IJG
41 * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
43 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
47 int TIFFFillStrip(TIFF
* tif
, uint32 strip
);
48 int TIFFFillTile(TIFF
* tif
, uint32 tile
);
49 int TIFFReInitJPEG_12( TIFF
*tif
, int scheme
, int is_encode
);
51 /* We undefine FAR to avoid conflict with JPEG definition */
58 Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
59 not defined. Unfortunately, the MinGW and Borland compilers include
60 a typedef for INT32, which causes a conflict. MSVC does not include
61 a conficting typedef given the headers which are included.
63 #if defined(__BORLANDC__) || defined(__MINGW32__)
68 The windows RPCNDR.H file defines boolean, but defines it with the
69 unsigned char size. You should compile JPEG library using appropriate
70 definitions in jconfig.h header, but many users compile library in wrong
71 way. That causes errors of the following type:
73 "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
76 For such users we wil fix the problem here. See install.doc file from
77 the JPEG library distribution for details.
80 /* Define "boolean" as unsigned char, not int, per Windows custom. */
81 #if defined(__WIN32__) && !defined(__MINGW32__)
82 # ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
83 typedef unsigned char boolean
;
85 # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
92 #define boolean wxHACK_BOOLEAN
98 #ifndef HAVE_WXJPEG_BOOLEAN
99 typedef boolean wxjpeg_boolean
;
103 * Do we want to do special processing suitable for when JSAMPLE is a
107 #if defined(JPEG_LIB_MK1)
108 # define JPEG_LIB_MK1_OR_12BIT 1
109 #elif BITS_IN_JSAMPLE == 12
110 # define JPEG_LIB_MK1_OR_12BIT 1
114 * We are using width_in_blocks which is supposed to be private to
115 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
116 * renamed this member to width_in_data_units. Since the header has
117 * also renamed a define, use that unique define name in order to
118 * detect the problem header and adjust to suit.
120 #if defined(D_MAX_DATA_UNITS_IN_MCU)
121 #define width_in_blocks width_in_data_units
125 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
126 * in place of plain setjmp. These macros will make it easier.
128 #define SETJMP(jbuf) setjmp(jbuf)
129 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
130 #define JMP_BUF jmp_buf
132 typedef struct jpeg_destination_mgr jpeg_destination_mgr
;
133 typedef struct jpeg_source_mgr jpeg_source_mgr
;
134 typedef struct jpeg_error_mgr jpeg_error_mgr
;
137 * State block for each open TIFF file using
138 * libjpeg to do JPEG compression/decompression.
140 * libjpeg's visible state is either a jpeg_compress_struct
141 * or jpeg_decompress_struct depending on which way we
142 * are going. comm can be used to refer to the fields
143 * which are common to both.
145 * NB: cinfo is required to be the first member of JPEGState,
146 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
151 struct jpeg_compress_struct c
;
152 struct jpeg_decompress_struct d
;
153 struct jpeg_common_struct comm
;
154 } cinfo
; /* NB: must be first */
155 int cinfo_initialized
;
157 jpeg_error_mgr err
; /* libjpeg error manager */
158 JMP_BUF exit_jmpbuf
; /* for catching libjpeg failures */
160 * The following two members could be a union, but
161 * they're small enough that it's not worth the effort.
163 jpeg_destination_mgr dest
; /* data dest for compression */
164 jpeg_source_mgr src
; /* data source for decompression */
166 TIFF
* tif
; /* back link needed by some code */
167 uint16 photometric
; /* copy of PhotometricInterpretation */
168 uint16 h_sampling
; /* luminance sampling factors */
170 tmsize_t bytesperline
; /* decompressed bytes per scanline */
171 /* pointers to intermediate buffers when processing downsampled data */
172 JSAMPARRAY ds_buffer
[MAX_COMPONENTS
];
173 int scancount
; /* number of "scanlines" accumulated */
176 TIFFVGetMethod vgetparent
; /* super-class method */
177 TIFFVSetMethod vsetparent
; /* super-class method */
178 TIFFPrintMethod printdir
; /* super-class method */
179 TIFFStripMethod defsparent
; /* super-class method */
180 TIFFTileMethod deftparent
; /* super-class method */
181 /* pseudo-tag fields */
182 void* jpegtables
; /* JPEGTables tag value, or NULL */
183 uint32 jpegtables_length
; /* number of bytes in same */
184 int jpegquality
; /* Compression quality level */
185 int jpegcolormode
; /* Auto RGB<=>YCbCr convert? */
186 int jpegtablesmode
; /* What to put in JPEGTables */
188 int ycbcrsampling_fetched
;
191 #define JState(tif) ((JPEGState*)(tif)->tif_data)
193 static int JPEGDecode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
194 static int JPEGDecodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
195 static int JPEGEncode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
196 static int JPEGEncodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
197 static int JPEGInitializeLibJPEG(TIFF
* tif
, int decode
);
198 static int DecodeRowError(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
200 #define FIELD_JPEGTABLES (FIELD_CODEC+0)
202 static const TIFFField jpegFields
[] = {
203 { TIFFTAG_JPEGTABLES
, -3, -3, TIFF_UNDEFINED
, 0, TIFF_SETGET_C32_UINT8
, TIFF_SETGET_C32_UINT8
, FIELD_JPEGTABLES
, FALSE
, TRUE
, "JPEGTables", NULL
},
204 { TIFFTAG_JPEGQUALITY
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, TRUE
, FALSE
, "", NULL
},
205 { TIFFTAG_JPEGCOLORMODE
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, FALSE
, FALSE
, "", NULL
},
206 { TIFFTAG_JPEGTABLESMODE
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, FALSE
, FALSE
, "", NULL
}
210 * libjpeg interface layer.
212 * We use setjmp/longjmp to return control to libtiff
213 * when a fatal error is encountered within the JPEG
214 * library. We also direct libjpeg error and warning
215 * messages through the appropriate libtiff handlers.
219 * Error handling routines (these replace corresponding
220 * IJG routines from jerror.c). These are used for both
221 * compression and decompression.
224 TIFFjpeg_error_exit(j_common_ptr cinfo
)
226 JPEGState
*sp
= (JPEGState
*) cinfo
; /* NB: cinfo assumed first */
227 char buffer
[JMSG_LENGTH_MAX
];
229 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
230 TIFFErrorExt(sp
->tif
->tif_clientdata
, "JPEGLib", "%s", buffer
); /* display the error message */
231 jpeg_abort(cinfo
); /* clean up libjpeg state */
232 LONGJMP(sp
->exit_jmpbuf
, 1); /* return to libtiff caller */
236 * This routine is invoked only for warning messages,
237 * since error_exit does its own thing and trace_level
241 TIFFjpeg_output_message(j_common_ptr cinfo
)
243 char buffer
[JMSG_LENGTH_MAX
];
245 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
246 TIFFWarningExt(((JPEGState
*) cinfo
)->tif
->tif_clientdata
, "JPEGLib", "%s", buffer
);
250 * Interface routines. This layer of routines exists
251 * primarily to limit side-effects from using setjmp.
252 * Also, normal/error returns are converted into return
253 * values per libtiff practice.
255 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
256 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
259 TIFFjpeg_create_compress(JPEGState
* sp
)
261 /* initialize JPEG error handling */
262 sp
->cinfo
.c
.err
= jpeg_std_error(&sp
->err
);
263 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
264 sp
->err
.output_message
= TIFFjpeg_output_message
;
266 return CALLVJPEG(sp
, jpeg_create_compress(&sp
->cinfo
.c
));
270 TIFFjpeg_create_decompress(JPEGState
* sp
)
272 /* initialize JPEG error handling */
273 sp
->cinfo
.d
.err
= jpeg_std_error(&sp
->err
);
274 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
275 sp
->err
.output_message
= TIFFjpeg_output_message
;
277 return CALLVJPEG(sp
, jpeg_create_decompress(&sp
->cinfo
.d
));
281 TIFFjpeg_set_defaults(JPEGState
* sp
)
283 return CALLVJPEG(sp
, jpeg_set_defaults(&sp
->cinfo
.c
));
287 TIFFjpeg_set_colorspace(JPEGState
* sp
, J_COLOR_SPACE colorspace
)
289 return CALLVJPEG(sp
, jpeg_set_colorspace(&sp
->cinfo
.c
, colorspace
));
293 TIFFjpeg_set_quality(JPEGState
* sp
, int quality
, wxjpeg_boolean force_baseline
)
296 jpeg_set_quality(&sp
->cinfo
.c
, quality
, force_baseline
));
300 TIFFjpeg_suppress_tables(JPEGState
* sp
, wxjpeg_boolean suppress
)
302 return CALLVJPEG(sp
, jpeg_suppress_tables(&sp
->cinfo
.c
, suppress
));
306 TIFFjpeg_start_compress(JPEGState
* sp
, wxjpeg_boolean write_all_tables
)
309 jpeg_start_compress(&sp
->cinfo
.c
, write_all_tables
));
313 TIFFjpeg_write_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int num_lines
)
315 return CALLJPEG(sp
, -1, (int) jpeg_write_scanlines(&sp
->cinfo
.c
,
316 scanlines
, (JDIMENSION
) num_lines
));
320 TIFFjpeg_write_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int num_lines
)
322 return CALLJPEG(sp
, -1, (int) jpeg_write_raw_data(&sp
->cinfo
.c
,
323 data
, (JDIMENSION
) num_lines
));
327 TIFFjpeg_finish_compress(JPEGState
* sp
)
329 return CALLVJPEG(sp
, jpeg_finish_compress(&sp
->cinfo
.c
));
333 TIFFjpeg_write_tables(JPEGState
* sp
)
335 return CALLVJPEG(sp
, jpeg_write_tables(&sp
->cinfo
.c
));
339 TIFFjpeg_read_header(JPEGState
* sp
, wxjpeg_boolean require_image
)
341 return CALLJPEG(sp
, -1, jpeg_read_header(&sp
->cinfo
.d
, require_image
));
345 TIFFjpeg_start_decompress(JPEGState
* sp
)
347 return CALLVJPEG(sp
, jpeg_start_decompress(&sp
->cinfo
.d
));
351 TIFFjpeg_read_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int max_lines
)
353 return CALLJPEG(sp
, -1, (int) jpeg_read_scanlines(&sp
->cinfo
.d
,
354 scanlines
, (JDIMENSION
) max_lines
));
358 TIFFjpeg_read_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int max_lines
)
360 return CALLJPEG(sp
, -1, (int) jpeg_read_raw_data(&sp
->cinfo
.d
,
361 data
, (JDIMENSION
) max_lines
));
365 TIFFjpeg_finish_decompress(JPEGState
* sp
)
367 return CALLJPEG(sp
, -1, (int) jpeg_finish_decompress(&sp
->cinfo
.d
));
371 TIFFjpeg_abort(JPEGState
* sp
)
373 return CALLVJPEG(sp
, jpeg_abort(&sp
->cinfo
.comm
));
377 TIFFjpeg_destroy(JPEGState
* sp
)
379 return CALLVJPEG(sp
, jpeg_destroy(&sp
->cinfo
.comm
));
383 TIFFjpeg_alloc_sarray(JPEGState
* sp
, int pool_id
,
384 JDIMENSION samplesperrow
, JDIMENSION numrows
)
386 return CALLJPEG(sp
, (JSAMPARRAY
) NULL
,
387 (*sp
->cinfo
.comm
.mem
->alloc_sarray
)
388 (&sp
->cinfo
.comm
, pool_id
, samplesperrow
, numrows
));
392 * JPEG library destination data manager.
393 * These routines direct compressed data from libjpeg into the
394 * libtiff output buffer.
398 std_init_destination(j_compress_ptr cinfo
)
400 JPEGState
* sp
= (JPEGState
*) cinfo
;
403 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
404 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
407 static wxjpeg_boolean
408 std_empty_output_buffer(j_compress_ptr cinfo
)
410 JPEGState
* sp
= (JPEGState
*) cinfo
;
413 /* the entire buffer has been filled */
414 tif
->tif_rawcc
= tif
->tif_rawdatasize
;
418 * The Intel IPP performance library does not necessarily fill up
419 * the whole output buffer on each pass, so only dump out the parts
420 * that have been filled.
421 * http://trac.osgeo.org/gdal/wiki/JpegIPP
423 if ( sp
->dest
.free_in_buffer
>= 0 ) {
424 tif
->tif_rawcc
= tif
->tif_rawdatasize
- sp
->dest
.free_in_buffer
;
429 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
430 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
436 std_term_destination(j_compress_ptr cinfo
)
438 JPEGState
* sp
= (JPEGState
*) cinfo
;
441 tif
->tif_rawcp
= (uint8
*) sp
->dest
.next_output_byte
;
443 tif
->tif_rawdatasize
- (tmsize_t
) sp
->dest
.free_in_buffer
;
444 /* NB: libtiff does the final buffer flush */
448 TIFFjpeg_data_dest(JPEGState
* sp
, TIFF
* tif
)
451 sp
->cinfo
.c
.dest
= &sp
->dest
;
452 sp
->dest
.init_destination
= std_init_destination
;
453 sp
->dest
.empty_output_buffer
= std_empty_output_buffer
;
454 sp
->dest
.term_destination
= std_term_destination
;
458 * Alternate destination manager for outputting to JPEGTables field.
462 tables_init_destination(j_compress_ptr cinfo
)
464 JPEGState
* sp
= (JPEGState
*) cinfo
;
466 /* while building, jpegtables_length is allocated buffer size */
467 sp
->dest
.next_output_byte
= (JOCTET
*) sp
->jpegtables
;
468 sp
->dest
.free_in_buffer
= (size_t) sp
->jpegtables_length
;
471 static wxjpeg_boolean
472 tables_empty_output_buffer(j_compress_ptr cinfo
)
474 JPEGState
* sp
= (JPEGState
*) cinfo
;
477 /* the entire buffer has been filled; enlarge it by 1000 bytes */
478 newbuf
= _TIFFrealloc((void*) sp
->jpegtables
,
479 (tmsize_t
) (sp
->jpegtables_length
+ 1000));
481 ERREXIT1(cinfo
, JERR_OUT_OF_MEMORY
, 100);
482 sp
->dest
.next_output_byte
= (JOCTET
*) newbuf
+ sp
->jpegtables_length
;
483 sp
->dest
.free_in_buffer
= (size_t) 1000;
484 sp
->jpegtables
= newbuf
;
485 sp
->jpegtables_length
+= 1000;
490 tables_term_destination(j_compress_ptr cinfo
)
492 JPEGState
* sp
= (JPEGState
*) cinfo
;
494 /* set tables length to number of bytes actually emitted */
495 sp
->jpegtables_length
-= (uint32
) sp
->dest
.free_in_buffer
;
499 TIFFjpeg_tables_dest(JPEGState
* sp
, TIFF
* tif
)
503 * Allocate a working buffer for building tables.
504 * Initial size is 1000 bytes, which is usually adequate.
507 _TIFFfree(sp
->jpegtables
);
508 sp
->jpegtables_length
= 1000;
509 sp
->jpegtables
= (void*) _TIFFmalloc((tmsize_t
) sp
->jpegtables_length
);
510 if (sp
->jpegtables
== NULL
) {
511 sp
->jpegtables_length
= 0;
512 TIFFErrorExt(sp
->tif
->tif_clientdata
, "TIFFjpeg_tables_dest", "No space for JPEGTables");
515 sp
->cinfo
.c
.dest
= &sp
->dest
;
516 sp
->dest
.init_destination
= tables_init_destination
;
517 sp
->dest
.empty_output_buffer
= tables_empty_output_buffer
;
518 sp
->dest
.term_destination
= tables_term_destination
;
523 * JPEG library source data manager.
524 * These routines supply compressed data to libjpeg.
528 std_init_source(j_decompress_ptr cinfo
)
530 JPEGState
* sp
= (JPEGState
*) cinfo
;
533 sp
->src
.next_input_byte
= (const JOCTET
*) tif
->tif_rawdata
;
534 sp
->src
.bytes_in_buffer
= (size_t) tif
->tif_rawcc
;
537 static wxjpeg_boolean
538 std_fill_input_buffer(j_decompress_ptr cinfo
)
540 JPEGState
* sp
= (JPEGState
* ) cinfo
;
541 static const JOCTET dummy_EOI
[2] = { 0xFF, JPEG_EOI
};
545 * The Intel IPP performance library does not necessarily read the whole
546 * input buffer in one pass, so it is possible to get here with data
549 * We just return without doing anything, until the entire buffer has
551 * http://trac.osgeo.org/gdal/wiki/JpegIPP
553 if( sp
->src
.bytes_in_buffer
> 0 ) {
559 * Normally the whole strip/tile is read and so we don't need to do
560 * a fill. In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
561 * all the data, but the rawdata is refreshed between scanlines and
562 * we push this into the io machinery in JPEGDecode().
563 * http://trac.osgeo.org/gdal/ticket/3894
566 WARNMS(cinfo
, JWRN_JPEG_EOF
);
567 /* insert a fake EOI marker */
568 sp
->src
.next_input_byte
= dummy_EOI
;
569 sp
->src
.bytes_in_buffer
= 2;
574 std_skip_input_data(j_decompress_ptr cinfo
, long num_bytes
)
576 JPEGState
* sp
= (JPEGState
*) cinfo
;
579 if ((size_t)num_bytes
> sp
->src
.bytes_in_buffer
) {
580 /* oops, buffer overrun */
581 (void) std_fill_input_buffer(cinfo
);
583 sp
->src
.next_input_byte
+= (size_t) num_bytes
;
584 sp
->src
.bytes_in_buffer
-= (size_t) num_bytes
;
590 std_term_source(j_decompress_ptr cinfo
)
592 /* No work necessary here */
597 TIFFjpeg_data_src(JPEGState
* sp
, TIFF
* tif
)
600 sp
->cinfo
.d
.src
= &sp
->src
;
601 sp
->src
.init_source
= std_init_source
;
602 sp
->src
.fill_input_buffer
= std_fill_input_buffer
;
603 sp
->src
.skip_input_data
= std_skip_input_data
;
604 sp
->src
.resync_to_restart
= jpeg_resync_to_restart
;
605 sp
->src
.term_source
= std_term_source
;
606 sp
->src
.bytes_in_buffer
= 0; /* for safety */
607 sp
->src
.next_input_byte
= NULL
;
611 * Alternate source manager for reading from JPEGTables.
612 * We can share all the code except for the init routine.
616 tables_init_source(j_decompress_ptr cinfo
)
618 JPEGState
* sp
= (JPEGState
*) cinfo
;
620 sp
->src
.next_input_byte
= (const JOCTET
*) sp
->jpegtables
;
621 sp
->src
.bytes_in_buffer
= (size_t) sp
->jpegtables_length
;
625 TIFFjpeg_tables_src(JPEGState
* sp
, TIFF
* tif
)
627 TIFFjpeg_data_src(sp
, tif
);
628 sp
->src
.init_source
= tables_init_source
;
632 * Allocate downsampled-data buffers needed for downsampled I/O.
633 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
634 * We use libjpeg's allocator so that buffers will be released automatically
635 * when done with strip/tile.
636 * This is also a handy place to compute samplesperclump, bytesperline.
639 alloc_downsampled_buffers(TIFF
* tif
, jpeg_component_info
* comp_info
,
642 JPEGState
* sp
= JState(tif
);
644 jpeg_component_info
* compptr
;
646 int samples_per_clump
= 0;
648 for (ci
= 0, compptr
= comp_info
; ci
< num_components
;
650 samples_per_clump
+= compptr
->h_samp_factor
*
651 compptr
->v_samp_factor
;
652 buf
= TIFFjpeg_alloc_sarray(sp
, JPOOL_IMAGE
,
653 compptr
->width_in_blocks
* DCTSIZE
,
654 (JDIMENSION
) (compptr
->v_samp_factor
*DCTSIZE
));
657 sp
->ds_buffer
[ci
] = buf
;
659 sp
->samplesperclump
= samples_per_clump
;
668 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
670 #define JPEG_MARKER_SOF0 0xC0
671 #define JPEG_MARKER_SOF1 0xC1
672 #define JPEG_MARKER_SOF3 0xC3
673 #define JPEG_MARKER_DHT 0xC4
674 #define JPEG_MARKER_SOI 0xD8
675 #define JPEG_MARKER_SOS 0xDA
676 #define JPEG_MARKER_DQT 0xDB
677 #define JPEG_MARKER_DRI 0xDD
678 #define JPEG_MARKER_APP0 0xE0
679 #define JPEG_MARKER_COM 0xFE
680 struct JPEGFixupTagsSubsamplingData
685 uint8
* buffercurrentbyte
;
686 uint32 bufferbytesleft
;
688 uint64 filebytesleft
;
689 uint8 filepositioned
;
691 static void JPEGFixupTagsSubsampling(TIFF
* tif
);
692 static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData
* data
);
693 static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData
* data
, uint8
* result
);
694 static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData
* data
, uint16
* result
);
695 static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData
* data
, uint16 skiplength
);
700 JPEGFixupTags(TIFF
* tif
)
702 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
703 if ((tif
->tif_dir
.td_photometric
==PHOTOMETRIC_YCBCR
)&&
704 (tif
->tif_dir
.td_planarconfig
==PLANARCONFIG_CONTIG
)&&
705 (tif
->tif_dir
.td_samplesperpixel
==3))
706 JPEGFixupTagsSubsampling(tif
);
712 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
715 JPEGFixupTagsSubsampling(TIFF
* tif
)
718 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
719 * the TIFF tags, but still use non-default (2,2) values within the jpeg
720 * data stream itself. In order for TIFF applications to work properly
721 * - for instance to get the strip buffer size right - it is imperative
722 * that the subsampling be available before we start reading the image
723 * data normally. This function will attempt to analyze the first strip in
724 * order to get the sampling values from the jpeg data stream.
726 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
727 * discovered sampling does not match the default sampling (2,2) or whatever
728 * was actually in the tiff tags.
730 * See the bug in bugzilla for details:
732 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
734 * Frank Warmerdam, July 2002
735 * Joris Van Damme, May 2007
737 static const char module[] = "JPEGFixupTagsSubsampling";
738 struct JPEGFixupTagsSubsamplingData m
;
740 _TIFFFillStriles( tif
);
742 if( tif
->tif_dir
.td_stripbytecount
== NULL
743 || tif
->tif_dir
.td_stripbytecount
[0] == 0 )
745 /* Do not even try to check if the first strip/tile does not
746 yet exist, as occurs when GDAL has created a new NULL file
753 m
.buffer
=_TIFFmalloc(m
.buffersize
);
756 TIFFWarningExt(tif
->tif_clientdata
,module,
757 "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
760 m
.buffercurrentbyte
=NULL
;
762 m
.fileoffset
=tif
->tif_dir
.td_stripoffset
[0];
764 m
.filebytesleft
=tif
->tif_dir
.td_stripbytecount
[0];
765 if (!JPEGFixupTagsSubsamplingSec(&m
))
766 TIFFWarningExt(tif
->tif_clientdata
,module,
767 "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
772 JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData
* data
)
774 static const char module[] = "JPEGFixupTagsSubsamplingSec";
780 if (!JPEGFixupTagsSubsamplingReadByte(data
,&m
))
787 if (!JPEGFixupTagsSubsamplingReadByte(data
,&m
))
794 case JPEG_MARKER_SOI
:
795 /* this type of marker has no data and should be skipped */
797 case JPEG_MARKER_COM
:
798 case JPEG_MARKER_APP0
:
799 case JPEG_MARKER_APP0
+1:
800 case JPEG_MARKER_APP0
+2:
801 case JPEG_MARKER_APP0
+3:
802 case JPEG_MARKER_APP0
+4:
803 case JPEG_MARKER_APP0
+5:
804 case JPEG_MARKER_APP0
+6:
805 case JPEG_MARKER_APP0
+7:
806 case JPEG_MARKER_APP0
+8:
807 case JPEG_MARKER_APP0
+9:
808 case JPEG_MARKER_APP0
+10:
809 case JPEG_MARKER_APP0
+11:
810 case JPEG_MARKER_APP0
+12:
811 case JPEG_MARKER_APP0
+13:
812 case JPEG_MARKER_APP0
+14:
813 case JPEG_MARKER_APP0
+15:
814 case JPEG_MARKER_DQT
:
815 case JPEG_MARKER_SOS
:
816 case JPEG_MARKER_DHT
:
817 case JPEG_MARKER_DRI
:
818 /* this type of marker has data, but it has no use to us and should be skipped */
821 if (!JPEGFixupTagsSubsamplingReadWord(data
,&n
))
827 JPEGFixupTagsSubsamplingSkip(data
,n
);
830 case JPEG_MARKER_SOF0
:
831 case JPEG_MARKER_SOF1
:
832 /* this marker contains the subsampling factors we're scanning for */
838 if (!JPEGFixupTagsSubsamplingReadWord(data
,&n
))
840 if (n
!=8+data
->tif
->tif_dir
.td_samplesperpixel
*3)
842 JPEGFixupTagsSubsamplingSkip(data
,7);
843 if (!JPEGFixupTagsSubsamplingReadByte(data
,&p
))
847 JPEGFixupTagsSubsamplingSkip(data
,1);
848 for (o
=1; o
<data
->tif
->tif_dir
.td_samplesperpixel
; o
++)
850 JPEGFixupTagsSubsamplingSkip(data
,1);
851 if (!JPEGFixupTagsSubsamplingReadByte(data
,&p
))
855 TIFFWarningExt(data
->tif
->tif_clientdata
,module,
856 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
859 JPEGFixupTagsSubsamplingSkip(data
,1);
861 if (((ph
!=1)&&(ph
!=2)&&(ph
!=4))||((pv
!=1)&&(pv
!=2)&&(pv
!=4)))
863 TIFFWarningExt(data
->tif
->tif_clientdata
,module,
864 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
867 if ((ph
!=data
->tif
->tif_dir
.td_ycbcrsubsampling
[0])||(pv
!=data
->tif
->tif_dir
.td_ycbcrsubsampling
[1]))
869 TIFFWarningExt(data
->tif
->tif_clientdata
,module,
870 "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
871 (int)data
->tif
->tif_dir
.td_ycbcrsubsampling
[0],
872 (int)data
->tif
->tif_dir
.td_ycbcrsubsampling
[1],
874 data
->tif
->tif_dir
.td_ycbcrsubsampling
[0]=ph
;
875 data
->tif
->tif_dir
.td_ycbcrsubsampling
[1]=pv
;
886 JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData
* data
, uint8
* result
)
888 if (data
->bufferbytesleft
==0)
891 if (data
->filebytesleft
==0)
893 if (!data
->filepositioned
)
895 TIFFSeekFile(data
->tif
,data
->fileoffset
,SEEK_SET
);
896 data
->filepositioned
=1;
899 if ((uint64
)m
>data
->filebytesleft
)
900 m
=(uint32
)data
->filebytesleft
;
901 assert(m
<0x80000000UL
);
902 if (TIFFReadFile(data
->tif
,data
->buffer
,(tmsize_t
)m
)!=(tmsize_t
)m
)
904 data
->buffercurrentbyte
=data
->buffer
;
905 data
->bufferbytesleft
=m
;
907 data
->filebytesleft
-=m
;
909 *result
=*data
->buffercurrentbyte
;
910 data
->buffercurrentbyte
++;
911 data
->bufferbytesleft
--;
916 JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData
* data
, uint16
* result
)
920 if (!JPEGFixupTagsSubsamplingReadByte(data
,&ma
))
922 if (!JPEGFixupTagsSubsamplingReadByte(data
,&mb
))
929 JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData
* data
, uint16 skiplength
)
931 if ((uint32
)skiplength
<=data
->bufferbytesleft
)
933 data
->buffercurrentbyte
+=skiplength
;
934 data
->bufferbytesleft
-=skiplength
;
939 m
=skiplength
-data
->bufferbytesleft
;
940 if (m
<=data
->filebytesleft
)
942 data
->bufferbytesleft
=0;
944 data
->filebytesleft
-=m
;
945 data
->filepositioned
=0;
949 data
->bufferbytesleft
=0;
950 data
->filebytesleft
=0;
959 JPEGSetupDecode(TIFF
* tif
)
961 JPEGState
* sp
= JState(tif
);
962 TIFFDirectory
*td
= &tif
->tif_dir
;
964 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
965 if( tif
->tif_dir
.td_bitspersample
== 12 )
966 return TIFFReInitJPEG_12( tif
, COMPRESSION_JPEG
, 0 );
969 JPEGInitializeLibJPEG( tif
, TRUE
);
972 assert(sp
->cinfo
.comm
.is_decompressor
);
974 /* Read JPEGTables if it is present */
975 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
)) {
976 TIFFjpeg_tables_src(sp
, tif
);
977 if(TIFFjpeg_read_header(sp
,FALSE
) != JPEG_HEADER_TABLES_ONLY
) {
978 TIFFErrorExt(tif
->tif_clientdata
, "JPEGSetupDecode", "Bogus JPEGTables field");
983 /* Grab parameters that are same for all strips/tiles */
984 sp
->photometric
= td
->td_photometric
;
985 switch (sp
->photometric
) {
986 case PHOTOMETRIC_YCBCR
:
987 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
988 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
991 /* TIFF 6.0 forbids subsampling of all other color spaces */
997 /* Set up for reading normal data */
998 TIFFjpeg_data_src(sp
, tif
);
999 tif
->tif_postdecode
= _TIFFNoPostDecode
; /* override byte swapping */
1004 * Set up for decoding a strip or tile.
1007 JPEGPreDecode(TIFF
* tif
, uint16 s
)
1009 JPEGState
*sp
= JState(tif
);
1010 TIFFDirectory
*td
= &tif
->tif_dir
;
1011 static const char module[] = "JPEGPreDecode";
1012 uint32 segment_width
, segment_height
;
1013 int downsampled_output
;
1018 if (sp
->cinfo
.comm
.is_decompressor
== 0)
1020 tif
->tif_setupdecode( tif
);
1023 assert(sp
->cinfo
.comm
.is_decompressor
);
1025 * Reset decoder state from any previous strip/tile,
1026 * in case application didn't read the whole strip.
1028 if (!TIFFjpeg_abort(sp
))
1031 * Read the header for this strip/tile.
1034 if (TIFFjpeg_read_header(sp
, TRUE
) != JPEG_HEADER_OK
)
1037 tif
->tif_rawcp
= (uint8
*) sp
->src
.next_input_byte
;
1038 tif
->tif_rawcc
= sp
->src
.bytes_in_buffer
;
1041 * Check image parameters and set decompression parameters.
1043 segment_width
= td
->td_imagewidth
;
1044 segment_height
= td
->td_imagelength
- tif
->tif_row
;
1046 segment_width
= td
->td_tilewidth
;
1047 segment_height
= td
->td_tilelength
;
1048 sp
->bytesperline
= TIFFTileRowSize(tif
);
1050 if (segment_height
> td
->td_rowsperstrip
)
1051 segment_height
= td
->td_rowsperstrip
;
1052 sp
->bytesperline
= TIFFScanlineSize(tif
);
1054 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
1056 * For PC 2, scale down the expected strip/tile size
1057 * to match a downsampled component
1059 segment_width
= TIFFhowmany_32(segment_width
, sp
->h_sampling
);
1060 segment_height
= TIFFhowmany_32(segment_height
, sp
->v_sampling
);
1062 if (sp
->cinfo
.d
.image_width
< segment_width
||
1063 sp
->cinfo
.d
.image_height
< segment_height
) {
1064 TIFFWarningExt(tif
->tif_clientdata
, module,
1065 "Improper JPEG strip/tile size, "
1066 "expected %dx%d, got %dx%d",
1067 segment_width
, segment_height
,
1068 sp
->cinfo
.d
.image_width
,
1069 sp
->cinfo
.d
.image_height
);
1071 if (sp
->cinfo
.d
.image_width
> segment_width
||
1072 sp
->cinfo
.d
.image_height
> segment_height
) {
1074 * This case could be dangerous, if the strip or tile size has
1075 * been reported as less than the amount of data jpeg will
1076 * return, some potential security issues arise. Catch this
1077 * case and error out.
1079 TIFFErrorExt(tif
->tif_clientdata
, module,
1080 "JPEG strip/tile size exceeds expected dimensions,"
1081 " expected %dx%d, got %dx%d",
1082 segment_width
, segment_height
,
1083 sp
->cinfo
.d
.image_width
, sp
->cinfo
.d
.image_height
);
1086 if (sp
->cinfo
.d
.num_components
!=
1087 (td
->td_planarconfig
== PLANARCONFIG_CONTIG
?
1088 td
->td_samplesperpixel
: 1)) {
1089 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG component count");
1093 if (12 != td
->td_bitspersample
&& 8 != td
->td_bitspersample
) {
1094 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG data precision");
1097 sp
->cinfo
.d
.data_precision
= td
->td_bitspersample
;
1098 sp
->cinfo
.d
.bits_in_jsample
= td
->td_bitspersample
;
1100 if (sp
->cinfo
.d
.data_precision
!= td
->td_bitspersample
) {
1101 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG data precision");
1105 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1106 /* Component 0 should have expected sampling factors */
1107 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= sp
->h_sampling
||
1108 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= sp
->v_sampling
) {
1109 TIFFErrorExt(tif
->tif_clientdata
, module,
1110 "Improper JPEG sampling factors %d,%d\n"
1111 "Apparently should be %d,%d.",
1112 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
,
1113 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
,
1114 sp
->h_sampling
, sp
->v_sampling
);
1117 /* Rest should have sampling factors 1,1 */
1118 for (ci
= 1; ci
< sp
->cinfo
.d
.num_components
; ci
++) {
1119 if (sp
->cinfo
.d
.comp_info
[ci
].h_samp_factor
!= 1 ||
1120 sp
->cinfo
.d
.comp_info
[ci
].v_samp_factor
!= 1) {
1121 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG sampling factors");
1126 /* PC 2's single component should have sampling factors 1,1 */
1127 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= 1 ||
1128 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= 1) {
1129 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG sampling factors");
1133 downsampled_output
= FALSE
;
1134 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
1135 sp
->photometric
== PHOTOMETRIC_YCBCR
&&
1136 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1137 /* Convert YCbCr to RGB */
1138 sp
->cinfo
.d
.jpeg_color_space
= JCS_YCbCr
;
1139 sp
->cinfo
.d
.out_color_space
= JCS_RGB
;
1141 /* Suppress colorspace handling */
1142 sp
->cinfo
.d
.jpeg_color_space
= JCS_UNKNOWN
;
1143 sp
->cinfo
.d
.out_color_space
= JCS_UNKNOWN
;
1144 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
1145 (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1))
1146 downsampled_output
= TRUE
;
1147 /* XXX what about up-sampling? */
1149 if (downsampled_output
) {
1150 /* Need to use raw-data interface to libjpeg */
1151 sp
->cinfo
.d
.raw_data_out
= TRUE
;
1152 #if JPEG_LIB_VERSION >= 70
1153 sp
->cinfo
.d
.do_fancy_upsampling
= FALSE
;
1154 #endif /* JPEG_LIB_VERSION >= 70 */
1155 tif
->tif_decoderow
= DecodeRowError
;
1156 tif
->tif_decodestrip
= JPEGDecodeRaw
;
1157 tif
->tif_decodetile
= JPEGDecodeRaw
;
1159 /* Use normal interface to libjpeg */
1160 sp
->cinfo
.d
.raw_data_out
= FALSE
;
1161 tif
->tif_decoderow
= JPEGDecode
;
1162 tif
->tif_decodestrip
= JPEGDecode
;
1163 tif
->tif_decodetile
= JPEGDecode
;
1165 /* Start JPEG decompressor */
1166 if (!TIFFjpeg_start_decompress(sp
))
1168 /* Allocate downsampled-data buffers if needed */
1169 if (downsampled_output
) {
1170 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.d
.comp_info
,
1171 sp
->cinfo
.d
.num_components
))
1173 sp
->scancount
= DCTSIZE
; /* mark buffer empty */
1179 * Decode a chunk of pixels.
1180 * "Standard" case: returned data is not downsampled.
1182 /*ARGSUSED*/ static int
1183 JPEGDecode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1185 JPEGState
*sp
= JState(tif
);
1190 ** Update available information, buffer may have been refilled
1191 ** between decode requests
1193 sp
->src
.next_input_byte
= (const JOCTET
*) tif
->tif_rawcp
;
1194 sp
->src
.bytes_in_buffer
= (size_t) tif
->tif_rawcc
;
1196 if( sp
->bytesperline
== 0 )
1199 nrows
= cc
/ sp
->bytesperline
;
1200 if (cc
% sp
->bytesperline
)
1201 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline not read");
1203 if( nrows
> (tmsize_t
) sp
->cinfo
.d
.image_height
)
1204 nrows
= sp
->cinfo
.d
.image_height
;
1206 /* data is expected to be read in multiples of a scanline */
1209 JSAMPROW line_work_buf
= NULL
;
1212 * For 6B, only use temporary buffer for 12 bit imagery.
1213 * For Mk1 always use it.
1215 #if !defined(JPEG_LIB_MK1)
1216 if( sp
->cinfo
.d
.data_precision
== 12 )
1219 line_work_buf
= (JSAMPROW
)
1220 _TIFFmalloc(sizeof(short) * sp
->cinfo
.d
.output_width
1221 * sp
->cinfo
.d
.num_components
);
1225 if( line_work_buf
!= NULL
)
1228 * In the MK1 case, we aways read into a 16bit buffer, and then
1229 * pack down to 12bit or 8bit. In 6B case we only read into 16
1230 * bit buffer for 12bit data, which we need to repack.
1232 if (TIFFjpeg_read_scanlines(sp
, &line_work_buf
, 1) != 1)
1235 if( sp
->cinfo
.d
.data_precision
== 12 )
1237 int value_pairs
= (sp
->cinfo
.d
.output_width
1238 * sp
->cinfo
.d
.num_components
) / 2;
1241 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1243 unsigned char *out_ptr
=
1244 ((unsigned char *) buf
) + iPair
* 3;
1245 JSAMPLE
*in_ptr
= line_work_buf
+ iPair
* 2;
1247 out_ptr
[0] = (in_ptr
[0] & 0xff0) >> 4;
1248 out_ptr
[1] = ((in_ptr
[0] & 0xf) << 4)
1249 | ((in_ptr
[1] & 0xf00) >> 8);
1250 out_ptr
[2] = ((in_ptr
[1] & 0xff) >> 0);
1253 else if( sp
->cinfo
.d
.data_precision
== 8 )
1255 int value_count
= (sp
->cinfo
.d
.output_width
1256 * sp
->cinfo
.d
.num_components
);
1259 for( iValue
= 0; iValue
< value_count
; iValue
++ )
1261 ((unsigned char *) buf
)[iValue
] =
1262 line_work_buf
[iValue
] & 0xff;
1269 * In the libjpeg6b 8bit case. We read directly into the
1272 JSAMPROW bufptr
= (JSAMPROW
)buf
;
1274 if (TIFFjpeg_read_scanlines(sp
, &bufptr
, 1) != 1)
1279 buf
+= sp
->bytesperline
;
1280 cc
-= sp
->bytesperline
;
1281 } while (--nrows
> 0);
1283 if( line_work_buf
!= NULL
)
1284 _TIFFfree( line_work_buf
);
1287 /* Update information on consumed data */
1288 tif
->tif_rawcp
= (uint8
*) sp
->src
.next_input_byte
;
1289 tif
->tif_rawcc
= sp
->src
.bytes_in_buffer
;
1291 /* Close down the decompressor if we've finished the strip or tile. */
1292 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
1293 || TIFFjpeg_finish_decompress(sp
);
1296 /*ARGSUSED*/ static int
1297 DecodeRowError(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1304 TIFFErrorExt(tif
->tif_clientdata
, "TIFFReadScanline",
1305 "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
1310 * Decode a chunk of pixels.
1311 * Returned data is downsampled per sampling factors.
1313 /*ARGSUSED*/ static int
1314 JPEGDecodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1316 JPEGState
*sp
= JState(tif
);
1320 /* data is expected to be read in multiples of a scanline */
1321 if ( (nrows
= sp
->cinfo
.d
.image_height
) ) {
1323 /* Cb,Cr both have sampling factors 1, so this is correct */
1324 JDIMENSION clumps_per_line
= sp
->cinfo
.d
.comp_info
[1].downsampled_width
;
1325 int samples_per_clump
= sp
->samplesperclump
;
1327 #if defined(JPEG_LIB_MK1_OR_12BIT)
1328 unsigned short* tmpbuf
= _TIFFmalloc(sizeof(unsigned short) *
1329 sp
->cinfo
.d
.output_width
*
1330 sp
->cinfo
.d
.num_components
);
1332 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1339 jpeg_component_info
*compptr
;
1340 int ci
, clumpoffset
;
1342 if( cc
< sp
->bytesperline
) {
1343 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1344 "application buffer not large enough for all data.");
1348 /* Reload downsampled-data buffer if needed */
1349 if (sp
->scancount
>= DCTSIZE
) {
1350 int n
= sp
->cinfo
.d
.max_v_samp_factor
* DCTSIZE
;
1351 if (TIFFjpeg_read_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1356 * Fastest way to unseparate data is to make one pass
1357 * over the scanline for each row of each component.
1359 clumpoffset
= 0; /* first sample in clump */
1360 for (ci
= 0, compptr
= sp
->cinfo
.d
.comp_info
;
1361 ci
< sp
->cinfo
.d
.num_components
;
1363 int hsamp
= compptr
->h_samp_factor
;
1364 int vsamp
= compptr
->v_samp_factor
;
1367 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
1368 JSAMPLE
*inptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
1370 #if defined(JPEG_LIB_MK1_OR_12BIT)
1371 JSAMPLE
*outptr
= (JSAMPLE
*)tmpbuf
+ clumpoffset
;
1373 JSAMPLE
*outptr
= (JSAMPLE
*)buf
+ clumpoffset
;
1374 if (cc
< (tmsize_t
) (clumpoffset
+ samples_per_clump
*(clumps_per_line
-1) + hsamp
)) {
1375 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1376 "application buffer not large enough for all data, possible subsampling issue");
1382 /* fast path for at least Cb and Cr */
1383 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1384 outptr
[0] = *inptr
++;
1385 outptr
+= samples_per_clump
;
1391 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1392 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1393 outptr
[xpos
] = *inptr
++;
1394 outptr
+= samples_per_clump
;
1397 clumpoffset
+= hsamp
;
1401 #if defined(JPEG_LIB_MK1_OR_12BIT)
1403 if (sp
->cinfo
.d
.data_precision
== 8)
1406 int len
= sp
->cinfo
.d
.output_width
* sp
->cinfo
.d
.num_components
;
1407 for (i
=0; i
<len
; i
++)
1409 ((unsigned char*)buf
)[i
] = tmpbuf
[i
] & 0xff;
1414 int value_pairs
= (sp
->cinfo
.d
.output_width
1415 * sp
->cinfo
.d
.num_components
) / 2;
1417 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1419 unsigned char *out_ptr
= ((unsigned char *) buf
) + iPair
* 3;
1420 JSAMPLE
*in_ptr
= (JSAMPLE
*) (tmpbuf
+ iPair
* 2);
1421 out_ptr
[0] = (in_ptr
[0] & 0xff0) >> 4;
1422 out_ptr
[1] = ((in_ptr
[0] & 0xf) << 4)
1423 | ((in_ptr
[1] & 0xf00) >> 8);
1424 out_ptr
[2] = ((in_ptr
[1] & 0xff) >> 0);
1431 tif
->tif_row
+= sp
->v_sampling
;
1433 buf
+= sp
->bytesperline
;
1434 cc
-= sp
->bytesperline
;
1436 nrows
-= sp
->v_sampling
;
1437 } while (nrows
> 0);
1439 #if defined(JPEG_LIB_MK1_OR_12BIT)
1445 /* Close down the decompressor if done. */
1446 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
1447 || TIFFjpeg_finish_decompress(sp
);
1456 unsuppress_quant_table (JPEGState
* sp
, int tblno
)
1460 if ((qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[tblno
]) != NULL
)
1461 qtbl
->sent_table
= FALSE
;
1465 unsuppress_huff_table (JPEGState
* sp
, int tblno
)
1469 if ((htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[tblno
]) != NULL
)
1470 htbl
->sent_table
= FALSE
;
1471 if ((htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[tblno
]) != NULL
)
1472 htbl
->sent_table
= FALSE
;
1476 prepare_JPEGTables(TIFF
* tif
)
1478 JPEGState
* sp
= JState(tif
);
1480 /* Initialize quant tables for current quality setting */
1481 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1483 /* Mark only the tables we want for output */
1484 /* NB: chrominance tables are currently used only with YCbCr */
1485 if (!TIFFjpeg_suppress_tables(sp
, TRUE
))
1487 if (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
) {
1488 unsuppress_quant_table(sp
, 0);
1489 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1490 unsuppress_quant_table(sp
, 1);
1492 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
) {
1493 unsuppress_huff_table(sp
, 0);
1494 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1495 unsuppress_huff_table(sp
, 1);
1497 /* Direct libjpeg output into jpegtables */
1498 if (!TIFFjpeg_tables_dest(sp
, tif
))
1500 /* Emit tables-only datastream */
1501 if (!TIFFjpeg_write_tables(sp
))
1508 JPEGSetupEncode(TIFF
* tif
)
1510 JPEGState
* sp
= JState(tif
);
1511 TIFFDirectory
*td
= &tif
->tif_dir
;
1512 static const char module[] = "JPEGSetupEncode";
1514 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
1515 if( tif
->tif_dir
.td_bitspersample
== 12 )
1516 return TIFFReInitJPEG_12( tif
, COMPRESSION_JPEG
, 1 );
1519 JPEGInitializeLibJPEG( tif
, FALSE
);
1522 assert(!sp
->cinfo
.comm
.is_decompressor
);
1525 * Initialize all JPEG parameters to default values.
1526 * Note that jpeg_set_defaults needs legal values for
1527 * in_color_space and input_components.
1529 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1530 sp
->cinfo
.c
.input_components
= 1;
1531 if (!TIFFjpeg_set_defaults(sp
))
1533 /* Set per-file parameters */
1534 sp
->photometric
= td
->td_photometric
;
1535 switch (sp
->photometric
) {
1536 case PHOTOMETRIC_YCBCR
:
1537 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
1538 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
1540 * A ReferenceBlackWhite field *must* be present since the
1541 * default value is inappropriate for YCbCr. Fill in the
1542 * proper value if application didn't set it.
1546 if (!TIFFGetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1549 long top
= 1L << td
->td_bitspersample
;
1551 refbw
[1] = (float)(top
-1L);
1552 refbw
[2] = (float)(top
>>1);
1553 refbw
[3] = refbw
[1];
1554 refbw
[4] = refbw
[2];
1555 refbw
[5] = refbw
[1];
1556 TIFFSetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1561 case PHOTOMETRIC_PALETTE
: /* disallowed by Tech Note */
1562 case PHOTOMETRIC_MASK
:
1563 TIFFErrorExt(tif
->tif_clientdata
, module,
1564 "PhotometricInterpretation %d not allowed for JPEG",
1565 (int) sp
->photometric
);
1568 /* TIFF 6.0 forbids subsampling of all other color spaces */
1574 /* Verify miscellaneous parameters */
1577 * This would need work if libtiff ever supports different
1578 * depths for different components, or if libjpeg ever supports
1579 * run-time selection of depth. Neither is imminent.
1582 /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1583 if (td
->td_bitspersample
!= 8 && td
->td_bitspersample
!= 12)
1585 if (td
->td_bitspersample
!= BITS_IN_JSAMPLE
)
1588 TIFFErrorExt(tif
->tif_clientdata
, module, "BitsPerSample %d not allowed for JPEG",
1589 (int) td
->td_bitspersample
);
1592 sp
->cinfo
.c
.data_precision
= td
->td_bitspersample
;
1594 sp
->cinfo
.c
.bits_in_jsample
= td
->td_bitspersample
;
1597 if ((td
->td_tilelength
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1598 TIFFErrorExt(tif
->tif_clientdata
, module,
1599 "JPEG tile height must be multiple of %d",
1600 sp
->v_sampling
* DCTSIZE
);
1603 if ((td
->td_tilewidth
% (sp
->h_sampling
* DCTSIZE
)) != 0) {
1604 TIFFErrorExt(tif
->tif_clientdata
, module,
1605 "JPEG tile width must be multiple of %d",
1606 sp
->h_sampling
* DCTSIZE
);
1610 if (td
->td_rowsperstrip
< td
->td_imagelength
&&
1611 (td
->td_rowsperstrip
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1612 TIFFErrorExt(tif
->tif_clientdata
, module,
1613 "RowsPerStrip must be multiple of %d for JPEG",
1614 sp
->v_sampling
* DCTSIZE
);
1619 /* Create a JPEGTables field if appropriate */
1620 if (sp
->jpegtablesmode
& (JPEGTABLESMODE_QUANT
|JPEGTABLESMODE_HUFF
)) {
1621 if( sp
->jpegtables
== NULL
1622 || memcmp(sp
->jpegtables
,"\0\0\0\0\0\0\0\0\0",8) == 0 )
1624 if (!prepare_JPEGTables(tif
))
1626 /* Mark the field present */
1627 /* Can't use TIFFSetField since BEENWRITING is already set! */
1628 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1629 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1632 /* We do not support application-supplied JPEGTables, */
1633 /* so mark the field not present */
1634 TIFFClrFieldBit(tif
, FIELD_JPEGTABLES
);
1637 /* Direct libjpeg output to libtiff's output buffer */
1638 TIFFjpeg_data_dest(sp
, tif
);
1644 * Set encoding state at the start of a strip or tile.
1647 JPEGPreEncode(TIFF
* tif
, uint16 s
)
1649 JPEGState
*sp
= JState(tif
);
1650 TIFFDirectory
*td
= &tif
->tif_dir
;
1651 static const char module[] = "JPEGPreEncode";
1652 uint32 segment_width
, segment_height
;
1653 int downsampled_input
;
1657 if (sp
->cinfo
.comm
.is_decompressor
== 1)
1659 tif
->tif_setupencode( tif
);
1662 assert(!sp
->cinfo
.comm
.is_decompressor
);
1664 * Set encoding parameters for this strip/tile.
1667 segment_width
= td
->td_tilewidth
;
1668 segment_height
= td
->td_tilelength
;
1669 sp
->bytesperline
= TIFFTileRowSize(tif
);
1671 segment_width
= td
->td_imagewidth
;
1672 segment_height
= td
->td_imagelength
- tif
->tif_row
;
1673 if (segment_height
> td
->td_rowsperstrip
)
1674 segment_height
= td
->td_rowsperstrip
;
1675 sp
->bytesperline
= TIFFScanlineSize(tif
);
1677 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
1678 /* for PC 2, scale down the strip/tile size
1679 * to match a downsampled component
1681 segment_width
= TIFFhowmany_32(segment_width
, sp
->h_sampling
);
1682 segment_height
= TIFFhowmany_32(segment_height
, sp
->v_sampling
);
1684 if (segment_width
> 65535 || segment_height
> 65535) {
1685 TIFFErrorExt(tif
->tif_clientdata
, module, "Strip/tile too large for JPEG");
1688 sp
->cinfo
.c
.image_width
= segment_width
;
1689 sp
->cinfo
.c
.image_height
= segment_height
;
1690 downsampled_input
= FALSE
;
1691 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1692 sp
->cinfo
.c
.input_components
= td
->td_samplesperpixel
;
1693 if (sp
->photometric
== PHOTOMETRIC_YCBCR
) {
1694 if (sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1695 sp
->cinfo
.c
.in_color_space
= JCS_RGB
;
1697 sp
->cinfo
.c
.in_color_space
= JCS_YCbCr
;
1698 if (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1)
1699 downsampled_input
= TRUE
;
1701 if (!TIFFjpeg_set_colorspace(sp
, JCS_YCbCr
))
1704 * Set Y sampling factors;
1705 * we assume jpeg_set_colorspace() set the rest to 1
1707 sp
->cinfo
.c
.comp_info
[0].h_samp_factor
= sp
->h_sampling
;
1708 sp
->cinfo
.c
.comp_info
[0].v_samp_factor
= sp
->v_sampling
;
1710 if ((td
->td_photometric
== PHOTOMETRIC_MINISWHITE
|| td
->td_photometric
== PHOTOMETRIC_MINISBLACK
) && td
->td_samplesperpixel
== 1)
1711 sp
->cinfo
.c
.in_color_space
= JCS_GRAYSCALE
;
1712 else if (td
->td_photometric
== PHOTOMETRIC_RGB
&& td
->td_samplesperpixel
== 3)
1713 sp
->cinfo
.c
.in_color_space
= JCS_RGB
;
1714 else if (td
->td_photometric
== PHOTOMETRIC_SEPARATED
&& td
->td_samplesperpixel
== 4)
1715 sp
->cinfo
.c
.in_color_space
= JCS_CMYK
;
1717 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1718 if (!TIFFjpeg_set_colorspace(sp
, sp
->cinfo
.c
.in_color_space
))
1720 /* jpeg_set_colorspace set all sampling factors to 1 */
1723 sp
->cinfo
.c
.input_components
= 1;
1724 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1725 if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
))
1727 sp
->cinfo
.c
.comp_info
[0].component_id
= s
;
1728 /* jpeg_set_colorspace() set sampling factors to 1 */
1729 if (sp
->photometric
== PHOTOMETRIC_YCBCR
&& s
> 0) {
1730 sp
->cinfo
.c
.comp_info
[0].quant_tbl_no
= 1;
1731 sp
->cinfo
.c
.comp_info
[0].dc_tbl_no
= 1;
1732 sp
->cinfo
.c
.comp_info
[0].ac_tbl_no
= 1;
1735 /* ensure libjpeg won't write any extraneous markers */
1736 sp
->cinfo
.c
.write_JFIF_header
= FALSE
;
1737 sp
->cinfo
.c
.write_Adobe_marker
= FALSE
;
1738 /* set up table handling correctly */
1739 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1741 if (! (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
)) {
1742 unsuppress_quant_table(sp
, 0);
1743 unsuppress_quant_table(sp
, 1);
1745 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
)
1746 sp
->cinfo
.c
.optimize_coding
= FALSE
;
1748 sp
->cinfo
.c
.optimize_coding
= TRUE
;
1749 if (downsampled_input
) {
1750 /* Need to use raw-data interface to libjpeg */
1751 sp
->cinfo
.c
.raw_data_in
= TRUE
;
1752 tif
->tif_encoderow
= JPEGEncodeRaw
;
1753 tif
->tif_encodestrip
= JPEGEncodeRaw
;
1754 tif
->tif_encodetile
= JPEGEncodeRaw
;
1756 /* Use normal interface to libjpeg */
1757 sp
->cinfo
.c
.raw_data_in
= FALSE
;
1758 tif
->tif_encoderow
= JPEGEncode
;
1759 tif
->tif_encodestrip
= JPEGEncode
;
1760 tif
->tif_encodetile
= JPEGEncode
;
1762 /* Start JPEG compressor */
1763 if (!TIFFjpeg_start_compress(sp
, FALSE
))
1765 /* Allocate downsampled-data buffers if needed */
1766 if (downsampled_input
) {
1767 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.c
.comp_info
,
1768 sp
->cinfo
.c
.num_components
))
1777 * Encode a chunk of pixels.
1778 * "Standard" case: incoming data is not downsampled.
1781 JPEGEncode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1783 JPEGState
*sp
= JState(tif
);
1786 short *line16
= NULL
;
1787 int line16_count
= 0;
1791 /* data is expected to be supplied in multiples of a scanline */
1792 nrows
= cc
/ sp
->bytesperline
;
1793 if (cc
% sp
->bytesperline
)
1794 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
,
1795 "fractional scanline discarded");
1797 /* The last strip will be limited to image size */
1798 if( !isTiled(tif
) && tif
->tif_row
+nrows
> tif
->tif_dir
.td_imagelength
)
1799 nrows
= tif
->tif_dir
.td_imagelength
- tif
->tif_row
;
1801 if( sp
->cinfo
.c
.data_precision
== 12 )
1803 line16_count
= (sp
->bytesperline
* 2) / 3;
1804 line16
= (short *) _TIFFmalloc(sizeof(short) * line16_count
);
1805 // FIXME: undiagnosed malloc failure
1808 while (nrows
-- > 0) {
1810 if( sp
->cinfo
.c
.data_precision
== 12 )
1813 int value_pairs
= line16_count
/ 2;
1816 bufptr
[0] = (JSAMPROW
) line16
;
1818 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1820 unsigned char *in_ptr
=
1821 ((unsigned char *) buf
) + iPair
* 3;
1822 JSAMPLE
*out_ptr
= (JSAMPLE
*) (line16
+ iPair
* 2);
1824 out_ptr
[0] = (in_ptr
[0] << 4) | ((in_ptr
[1] & 0xf0) >> 4);
1825 out_ptr
[1] = ((in_ptr
[1] & 0x0f) << 8) | in_ptr
[2];
1830 bufptr
[0] = (JSAMPROW
) buf
;
1832 if (TIFFjpeg_write_scanlines(sp
, bufptr
, 1) != 1)
1836 buf
+= sp
->bytesperline
;
1839 if( sp
->cinfo
.c
.data_precision
== 12 )
1841 _TIFFfree( line16
);
1848 * Encode a chunk of pixels.
1849 * Incoming data is expected to be downsampled per sampling factors.
1852 JPEGEncodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1854 JPEGState
*sp
= JState(tif
);
1858 JDIMENSION clumps_per_line
, nclump
;
1859 int clumpoffset
, ci
, xpos
, ypos
;
1860 jpeg_component_info
* compptr
;
1861 int samples_per_clump
= sp
->samplesperclump
;
1862 tmsize_t bytesperclumpline
;
1866 /* data is expected to be supplied in multiples of a clumpline */
1867 /* a clumpline is equivalent to v_sampling desubsampled scanlines */
1868 /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
1869 bytesperclumpline
= (((sp
->cinfo
.c
.image_width
+sp
->h_sampling
-1)/sp
->h_sampling
)
1870 *(sp
->h_sampling
*sp
->v_sampling
+2)*sp
->cinfo
.c
.data_precision
+7)
1873 nrows
= ( cc
/ bytesperclumpline
) * sp
->v_sampling
;
1874 if (cc
% bytesperclumpline
)
1875 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline discarded");
1877 /* Cb,Cr both have sampling factors 1, so this is correct */
1878 clumps_per_line
= sp
->cinfo
.c
.comp_info
[1].downsampled_width
;
1882 * Fastest way to separate the data is to make one pass
1883 * over the scanline for each row of each component.
1885 clumpoffset
= 0; /* first sample in clump */
1886 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1887 ci
< sp
->cinfo
.c
.num_components
;
1889 int hsamp
= compptr
->h_samp_factor
;
1890 int vsamp
= compptr
->v_samp_factor
;
1891 int padding
= (int) (compptr
->width_in_blocks
* DCTSIZE
-
1892 clumps_per_line
* hsamp
);
1893 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
1894 inptr
= ((JSAMPLE
*) buf
) + clumpoffset
;
1895 outptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
1897 /* fast path for at least Cb and Cr */
1898 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1899 *outptr
++ = inptr
[0];
1900 inptr
+= samples_per_clump
;
1904 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1905 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1906 *outptr
++ = inptr
[xpos
];
1907 inptr
+= samples_per_clump
;
1910 /* pad each scanline as needed */
1911 for (xpos
= 0; xpos
< padding
; xpos
++) {
1912 *outptr
= outptr
[-1];
1915 clumpoffset
+= hsamp
;
1919 if (sp
->scancount
>= DCTSIZE
) {
1920 int n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1921 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1925 tif
->tif_row
+= sp
->v_sampling
;
1926 buf
+= bytesperclumpline
;
1927 nrows
-= sp
->v_sampling
;
1933 * Finish up at the end of a strip or tile.
1936 JPEGPostEncode(TIFF
* tif
)
1938 JPEGState
*sp
= JState(tif
);
1940 if (sp
->scancount
> 0) {
1942 * Need to emit a partial bufferload of downsampled data.
1943 * Pad the data vertically.
1946 jpeg_component_info
* compptr
;
1948 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1949 ci
< sp
->cinfo
.c
.num_components
;
1951 int vsamp
= compptr
->v_samp_factor
;
1952 tmsize_t row_width
= compptr
->width_in_blocks
* DCTSIZE
1954 for (ypos
= sp
->scancount
* vsamp
;
1955 ypos
< DCTSIZE
* vsamp
; ypos
++) {
1956 _TIFFmemcpy((void*)sp
->ds_buffer
[ci
][ypos
],
1957 (void*)sp
->ds_buffer
[ci
][ypos
-1],
1962 n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1963 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1967 return (TIFFjpeg_finish_compress(JState(tif
)));
1971 JPEGCleanup(TIFF
* tif
)
1973 JPEGState
*sp
= JState(tif
);
1977 tif
->tif_tagmethods
.vgetfield
= sp
->vgetparent
;
1978 tif
->tif_tagmethods
.vsetfield
= sp
->vsetparent
;
1979 tif
->tif_tagmethods
.printdir
= sp
->printdir
;
1982 if( sp
->cinfo_initialized
)
1983 TIFFjpeg_destroy(sp
); /* release libjpeg resources */
1984 if (sp
->jpegtables
) /* tag value */
1985 _TIFFfree(sp
->jpegtables
);
1987 _TIFFfree(tif
->tif_data
); /* release local state */
1988 tif
->tif_data
= NULL
;
1990 _TIFFSetDefaultCompressionState(tif
);
1994 JPEGResetUpsampled( TIFF
* tif
)
1996 JPEGState
* sp
= JState(tif
);
1997 TIFFDirectory
* td
= &tif
->tif_dir
;
2000 * Mark whether returned data is up-sampled or not so TIFFStripSize
2001 * and TIFFTileSize return values that reflect the true amount of
2004 tif
->tif_flags
&= ~TIFF_UPSAMPLED
;
2005 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
2006 if (td
->td_photometric
== PHOTOMETRIC_YCBCR
&&
2007 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
2008 tif
->tif_flags
|= TIFF_UPSAMPLED
;
2011 if (td
->td_ycbcrsubsampling
[0] != 1 ||
2012 td
->td_ycbcrsubsampling
[1] != 1)
2013 ; /* XXX what about up-sampling? */
2019 * Must recalculate cached tile size in case sampling state changed.
2020 * Should we really be doing this now if image size isn't set?
2022 if( tif
->tif_tilesize
> 0 )
2023 tif
->tif_tilesize
= isTiled(tif
) ? TIFFTileSize(tif
) : (tmsize_t
)(-1);
2024 if( tif
->tif_scanlinesize
> 0 )
2025 tif
->tif_scanlinesize
= TIFFScanlineSize(tif
);
2029 JPEGVSetField(TIFF
* tif
, uint32 tag
, va_list ap
)
2031 JPEGState
* sp
= JState(tif
);
2032 const TIFFField
* fip
;
2038 case TIFFTAG_JPEGTABLES
:
2039 v32
= (uint32
) va_arg(ap
, uint32
);
2044 _TIFFsetByteArray(&sp
->jpegtables
, va_arg(ap
, void*),
2046 sp
->jpegtables_length
= v32
;
2047 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
2049 case TIFFTAG_JPEGQUALITY
:
2050 sp
->jpegquality
= (int) va_arg(ap
, int);
2051 return (1); /* pseudo tag */
2052 case TIFFTAG_JPEGCOLORMODE
:
2053 sp
->jpegcolormode
= (int) va_arg(ap
, int);
2054 JPEGResetUpsampled( tif
);
2055 return (1); /* pseudo tag */
2056 case TIFFTAG_PHOTOMETRIC
:
2058 int ret_value
= (*sp
->vsetparent
)(tif
, tag
, ap
);
2059 JPEGResetUpsampled( tif
);
2062 case TIFFTAG_JPEGTABLESMODE
:
2063 sp
->jpegtablesmode
= (int) va_arg(ap
, int);
2064 return (1); /* pseudo tag */
2065 case TIFFTAG_YCBCRSUBSAMPLING
:
2066 /* mark the fact that we have a real ycbcrsubsampling! */
2067 sp
->ycbcrsampling_fetched
= 1;
2068 /* should we be recomputing upsampling info here? */
2069 return (*sp
->vsetparent
)(tif
, tag
, ap
);
2071 return (*sp
->vsetparent
)(tif
, tag
, ap
);
2074 if ((fip
= TIFFFieldWithTag(tif
, tag
))) {
2075 TIFFSetFieldBit(tif
, fip
->field_bit
);
2080 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
2085 JPEGVGetField(TIFF
* tif
, uint32 tag
, va_list ap
)
2087 JPEGState
* sp
= JState(tif
);
2092 case TIFFTAG_JPEGTABLES
:
2093 *va_arg(ap
, uint32
*) = sp
->jpegtables_length
;
2094 *va_arg(ap
, void**) = sp
->jpegtables
;
2096 case TIFFTAG_JPEGQUALITY
:
2097 *va_arg(ap
, int*) = sp
->jpegquality
;
2099 case TIFFTAG_JPEGCOLORMODE
:
2100 *va_arg(ap
, int*) = sp
->jpegcolormode
;
2102 case TIFFTAG_JPEGTABLESMODE
:
2103 *va_arg(ap
, int*) = sp
->jpegtablesmode
;
2106 return (*sp
->vgetparent
)(tif
, tag
, ap
);
2112 JPEGPrintDir(TIFF
* tif
, FILE* fd
, long flags
)
2114 JPEGState
* sp
= JState(tif
);
2120 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
))
2121 fprintf(fd
, " JPEG Tables: (%lu bytes)\n",
2122 (unsigned long) sp
->jpegtables_length
);
2124 (*sp
->printdir
)(tif
, fd
, flags
);
2129 JPEGDefaultStripSize(TIFF
* tif
, uint32 s
)
2131 JPEGState
* sp
= JState(tif
);
2132 TIFFDirectory
*td
= &tif
->tif_dir
;
2134 s
= (*sp
->defsparent
)(tif
, s
);
2135 if (s
< td
->td_imagelength
)
2136 s
= TIFFroundup_32(s
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
2141 JPEGDefaultTileSize(TIFF
* tif
, uint32
* tw
, uint32
* th
)
2143 JPEGState
* sp
= JState(tif
);
2144 TIFFDirectory
*td
= &tif
->tif_dir
;
2146 (*sp
->deftparent
)(tif
, tw
, th
);
2147 *tw
= TIFFroundup_32(*tw
, td
->td_ycbcrsubsampling
[0] * DCTSIZE
);
2148 *th
= TIFFroundup_32(*th
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
2152 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
2153 * now that we allow a TIFF file to be opened in update mode it is necessary
2154 * to have some way of deciding whether compression or decompression is
2155 * desired other than looking at tif->tif_mode. We accomplish this by
2156 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
2157 * If so, we assume decompression is desired.
2159 * This is tricky, because TIFFInitJPEG() is called while the directory is
2160 * being read, and generally speaking the BYTECOUNTS tag won't have been read
2161 * at that point. So we try to defer jpeg library initialization till we
2162 * do have that tag ... basically any access that might require the compressor
2163 * or decompressor that occurs after the reading of the directory.
2165 * In an ideal world compressors or decompressors would be setup
2166 * at the point where a single tile or strip was accessed (for read or write)
2167 * so that stuff like update of missing tiles, or replacement of tiles could
2168 * be done. However, we aren't trying to crack that nut just yet ...
2170 * NFW, Feb 3rd, 2003.
2173 static int JPEGInitializeLibJPEG( TIFF
* tif
, int decompress
)
2175 JPEGState
* sp
= JState(tif
);
2177 if(sp
->cinfo_initialized
)
2179 if( !decompress
&& sp
->cinfo
.comm
.is_decompressor
)
2180 TIFFjpeg_destroy( sp
);
2181 else if( decompress
&& !sp
->cinfo
.comm
.is_decompressor
)
2182 TIFFjpeg_destroy( sp
);
2186 sp
->cinfo_initialized
= 0;
2190 * Initialize libjpeg.
2193 if (!TIFFjpeg_create_decompress(sp
))
2196 if (!TIFFjpeg_create_compress(sp
))
2200 sp
->cinfo_initialized
= TRUE
;
2206 TIFFInitJPEG(TIFF
* tif
, int scheme
)
2210 assert(scheme
== COMPRESSION_JPEG
);
2213 * Merge codec-specific tag information.
2215 if (!_TIFFMergeFields(tif
, jpegFields
, TIFFArrayCount(jpegFields
))) {
2216 TIFFErrorExt(tif
->tif_clientdata
,
2218 "Merging JPEG codec-specific tags failed");
2223 * Allocate state block so tag methods have storage to record values.
2225 tif
->tif_data
= (uint8
*) _TIFFmalloc(sizeof (JPEGState
));
2227 if (tif
->tif_data
== NULL
) {
2228 TIFFErrorExt(tif
->tif_clientdata
,
2229 "TIFFInitJPEG", "No space for JPEG state block");
2232 _TIFFmemset(tif
->tif_data
, 0, sizeof(JPEGState
));
2235 sp
->tif
= tif
; /* back link */
2238 * Override parent get/set field methods.
2240 sp
->vgetparent
= tif
->tif_tagmethods
.vgetfield
;
2241 tif
->tif_tagmethods
.vgetfield
= JPEGVGetField
; /* hook for codec tags */
2242 sp
->vsetparent
= tif
->tif_tagmethods
.vsetfield
;
2243 tif
->tif_tagmethods
.vsetfield
= JPEGVSetField
; /* hook for codec tags */
2244 sp
->printdir
= tif
->tif_tagmethods
.printdir
;
2245 tif
->tif_tagmethods
.printdir
= JPEGPrintDir
; /* hook for codec tags */
2247 /* Default values for codec-specific fields */
2248 sp
->jpegtables
= NULL
;
2249 sp
->jpegtables_length
= 0;
2250 sp
->jpegquality
= 75; /* Default IJG quality */
2251 sp
->jpegcolormode
= JPEGCOLORMODE_RAW
;
2252 sp
->jpegtablesmode
= JPEGTABLESMODE_QUANT
| JPEGTABLESMODE_HUFF
;
2253 sp
->ycbcrsampling_fetched
= 0;
2256 * Install codec methods.
2258 tif
->tif_fixuptags
= JPEGFixupTags
;
2259 tif
->tif_setupdecode
= JPEGSetupDecode
;
2260 tif
->tif_predecode
= JPEGPreDecode
;
2261 tif
->tif_decoderow
= JPEGDecode
;
2262 tif
->tif_decodestrip
= JPEGDecode
;
2263 tif
->tif_decodetile
= JPEGDecode
;
2264 tif
->tif_setupencode
= JPEGSetupEncode
;
2265 tif
->tif_preencode
= JPEGPreEncode
;
2266 tif
->tif_postencode
= JPEGPostEncode
;
2267 tif
->tif_encoderow
= JPEGEncode
;
2268 tif
->tif_encodestrip
= JPEGEncode
;
2269 tif
->tif_encodetile
= JPEGEncode
;
2270 tif
->tif_cleanup
= JPEGCleanup
;
2271 sp
->defsparent
= tif
->tif_defstripsize
;
2272 tif
->tif_defstripsize
= JPEGDefaultStripSize
;
2273 sp
->deftparent
= tif
->tif_deftilesize
;
2274 tif
->tif_deftilesize
= JPEGDefaultTileSize
;
2275 tif
->tif_flags
|= TIFF_NOBITREV
; /* no bit reversal, please */
2277 sp
->cinfo_initialized
= FALSE
;
2280 ** Create a JPEGTables field if no directory has yet been created.
2281 ** We do this just to ensure that sufficient space is reserved for
2282 ** the JPEGTables field. It will be properly created the right
2285 if( tif
->tif_diroff
== 0 )
2287 #define SIZE_OF_JPEGTABLES 2000
2289 The following line assumes incorrectly that all JPEG-in-TIFF files will have
2290 a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
2291 when the JPEG data is placed with TIFFWriteRawStrip. The field bit should be
2292 set, anyway, later when actual JPEGTABLES header is generated, so removing it
2293 here hopefully is harmless.
2294 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2296 sp
->jpegtables_length
= SIZE_OF_JPEGTABLES
;
2297 sp
->jpegtables
= (void *) _TIFFmalloc(sp
->jpegtables_length
);
2298 // FIXME: NULL-deref after malloc failure
2299 _TIFFmemset(sp
->jpegtables
, 0, SIZE_OF_JPEGTABLES
);
2300 #undef SIZE_OF_JPEGTABLES
2305 #endif /* JPEG_SUPPORT */
2307 /* vim: set ts=8 sts=8 sw=8 noet: */