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
32 * JPEG Compression support per TIFF Technical Note #2
33 * (*not* per the original TIFF 6.0 spec).
35 * This file is simply an interface to the libjpeg library written by
36 * the Independent JPEG Group. You need release 5 or later of the IJG
37 * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
39 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
45 int TIFFFillStrip(TIFF
*, tstrip_t
);
46 int TIFFFillTile(TIFF
*, ttile_t
);
48 /* We undefine FAR to avoid conflict with JPEG definition */
55 The windows RPCNDR.H file defines boolean, but defines it with the
56 wrong size. So we declare HAVE_BOOLEAN so that the jpeg include file
57 won't try to typedef boolean, but #define it to override the rpcndr.h
60 http://bugzilla.remotesensing.org/show_bug.cgi?id=188
62 #if defined wxHACK_BOOLEAN || defined __RPCNDR_H__ || defined __WINE_RPCNDR_H
66 #define boolean wxHACK_BOOLEAN
75 #ifndef HAVE_WXJPEG_BOOLEAN
76 typedef boolean wxjpeg_boolean
;
80 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
81 * in place of plain setjmp. These macros will make it easier.
83 #define SETJMP(jbuf) setjmp(jbuf)
84 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
85 #define JMP_BUF jmp_buf
87 typedef struct jpeg_destination_mgr jpeg_destination_mgr
;
88 typedef struct jpeg_source_mgr jpeg_source_mgr
;
89 typedef struct jpeg_error_mgr jpeg_error_mgr
;
92 * State block for each open TIFF file using
93 * libjpeg to do JPEG compression/decompression.
95 * libjpeg's visible state is either a jpeg_compress_struct
96 * or jpeg_decompress_struct depending on which way we
97 * are going. comm can be used to refer to the fields
98 * which are common to both.
100 * NB: cinfo is required to be the first member of JPEGState,
101 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
106 struct jpeg_compress_struct c
;
107 struct jpeg_decompress_struct d
;
108 struct jpeg_common_struct comm
;
109 } cinfo
; /* NB: must be first */
110 int cinfo_initialized
;
112 jpeg_error_mgr err
; /* libjpeg error manager */
113 JMP_BUF exit_jmpbuf
; /* for catching libjpeg failures */
115 * The following two members could be a union, but
116 * they're small enough that it's not worth the effort.
118 jpeg_destination_mgr dest
; /* data dest for compression */
119 jpeg_source_mgr src
; /* data source for decompression */
121 TIFF
* tif
; /* back link needed by some code */
122 uint16 photometric
; /* copy of PhotometricInterpretation */
123 uint16 h_sampling
; /* luminance sampling factors */
125 tsize_t bytesperline
; /* decompressed bytes per scanline */
126 /* pointers to intermediate buffers when processing downsampled data */
127 JSAMPARRAY ds_buffer
[MAX_COMPONENTS
];
128 int scancount
; /* number of "scanlines" accumulated */
131 TIFFVGetMethod vgetparent
; /* super-class method */
132 TIFFVSetMethod vsetparent
; /* super-class method */
133 TIFFStripMethod defsparent
; /* super-class method */
134 TIFFTileMethod deftparent
; /* super-class method */
135 /* pseudo-tag fields */
136 void* jpegtables
; /* JPEGTables tag value, or NULL */
137 uint32 jpegtables_length
; /* number of bytes in same */
138 int jpegquality
; /* Compression quality level */
139 int jpegcolormode
; /* Auto RGB<=>YCbCr convert? */
140 int jpegtablesmode
; /* What to put in JPEGTables */
142 int ycbcrsampling_fetched
;
145 #define JState(tif) ((JPEGState*)(tif)->tif_data)
147 static int JPEGDecode(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
148 static int JPEGDecodeRaw(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
149 static int JPEGEncode(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
150 static int JPEGEncodeRaw(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
151 static int JPEGInitializeLibJPEG( TIFF
* tif
);
153 #define FIELD_JPEGTABLES (FIELD_CODEC+0)
155 static const TIFFFieldInfo jpegFieldInfo
[] = {
156 { TIFFTAG_JPEGTABLES
, -1,-1, TIFF_UNDEFINED
, FIELD_JPEGTABLES
,
157 FALSE
, TRUE
, "JPEGTables" },
158 { TIFFTAG_JPEGQUALITY
, 0, 0, TIFF_ANY
, FIELD_PSEUDO
,
160 { TIFFTAG_JPEGCOLORMODE
, 0, 0, TIFF_ANY
, FIELD_PSEUDO
,
162 { TIFFTAG_JPEGTABLESMODE
, 0, 0, TIFF_ANY
, FIELD_PSEUDO
,
165 #define N(a) (sizeof (a) / sizeof (a[0]))
168 * libjpeg interface layer.
170 * We use setjmp/longjmp to return control to libtiff
171 * when a fatal error is encountered within the JPEG
172 * library. We also direct libjpeg error and warning
173 * messages through the appropriate libtiff handlers.
177 * Error handling routines (these replace corresponding
178 * IJG routines from jerror.c). These are used for both
179 * compression and decompression.
182 TIFFjpeg_error_exit(j_common_ptr cinfo
)
184 JPEGState
*sp
= (JPEGState
*) cinfo
; /* NB: cinfo assumed first */
185 char buffer
[JMSG_LENGTH_MAX
];
187 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
188 TIFFError("JPEGLib", buffer
); /* display the error message */
189 jpeg_abort(cinfo
); /* clean up libjpeg state */
190 LONGJMP(sp
->exit_jmpbuf
, 1); /* return to libtiff caller */
194 * This routine is invoked only for warning messages,
195 * since error_exit does its own thing and trace_level
199 TIFFjpeg_output_message(j_common_ptr cinfo
)
201 char buffer
[JMSG_LENGTH_MAX
];
203 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
204 TIFFWarning("JPEGLib", buffer
);
208 * Interface routines. This layer of routines exists
209 * primarily to limit side-effects from using setjmp.
210 * Also, normal/error returns are converted into return
211 * values per libtiff practice.
213 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
214 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
217 TIFFjpeg_create_compress(JPEGState
* sp
)
219 /* initialize JPEG error handling */
220 sp
->cinfo
.c
.err
= jpeg_std_error(&sp
->err
);
221 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
222 sp
->err
.output_message
= TIFFjpeg_output_message
;
224 return CALLVJPEG(sp
, jpeg_create_compress(&sp
->cinfo
.c
));
228 TIFFjpeg_create_decompress(JPEGState
* sp
)
230 /* initialize JPEG error handling */
231 sp
->cinfo
.d
.err
= jpeg_std_error(&sp
->err
);
232 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
233 sp
->err
.output_message
= TIFFjpeg_output_message
;
235 return CALLVJPEG(sp
, jpeg_create_decompress(&sp
->cinfo
.d
));
239 TIFFjpeg_set_defaults(JPEGState
* sp
)
241 return CALLVJPEG(sp
, jpeg_set_defaults(&sp
->cinfo
.c
));
245 TIFFjpeg_set_colorspace(JPEGState
* sp
, J_COLOR_SPACE colorspace
)
247 return CALLVJPEG(sp
, jpeg_set_colorspace(&sp
->cinfo
.c
, colorspace
));
251 TIFFjpeg_set_quality(JPEGState
* sp
, int quality
, wxjpeg_boolean force_baseline
)
254 jpeg_set_quality(&sp
->cinfo
.c
, quality
, force_baseline
));
258 TIFFjpeg_suppress_tables(JPEGState
* sp
, wxjpeg_boolean suppress
)
260 return CALLVJPEG(sp
, jpeg_suppress_tables(&sp
->cinfo
.c
, suppress
));
264 TIFFjpeg_start_compress(JPEGState
* sp
, wxjpeg_boolean write_all_tables
)
267 jpeg_start_compress(&sp
->cinfo
.c
, write_all_tables
));
271 TIFFjpeg_write_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int num_lines
)
273 return CALLJPEG(sp
, -1, (int) jpeg_write_scanlines(&sp
->cinfo
.c
,
274 scanlines
, (JDIMENSION
) num_lines
));
278 TIFFjpeg_write_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int num_lines
)
280 return CALLJPEG(sp
, -1, (int) jpeg_write_raw_data(&sp
->cinfo
.c
,
281 data
, (JDIMENSION
) num_lines
));
285 TIFFjpeg_finish_compress(JPEGState
* sp
)
287 return CALLVJPEG(sp
, jpeg_finish_compress(&sp
->cinfo
.c
));
291 TIFFjpeg_write_tables(JPEGState
* sp
)
293 return CALLVJPEG(sp
, jpeg_write_tables(&sp
->cinfo
.c
));
297 TIFFjpeg_read_header(JPEGState
* sp
, wxjpeg_boolean require_image
)
299 return CALLJPEG(sp
, -1, jpeg_read_header(&sp
->cinfo
.d
, require_image
));
303 TIFFjpeg_start_decompress(JPEGState
* sp
)
305 return CALLVJPEG(sp
, jpeg_start_decompress(&sp
->cinfo
.d
));
309 TIFFjpeg_read_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int max_lines
)
311 return CALLJPEG(sp
, -1, (int) jpeg_read_scanlines(&sp
->cinfo
.d
,
312 scanlines
, (JDIMENSION
) max_lines
));
316 TIFFjpeg_read_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int max_lines
)
318 return CALLJPEG(sp
, -1, (int) jpeg_read_raw_data(&sp
->cinfo
.d
,
319 data
, (JDIMENSION
) max_lines
));
323 TIFFjpeg_finish_decompress(JPEGState
* sp
)
325 return CALLJPEG(sp
, -1, (int) jpeg_finish_decompress(&sp
->cinfo
.d
));
329 TIFFjpeg_abort(JPEGState
* sp
)
331 return CALLVJPEG(sp
, jpeg_abort(&sp
->cinfo
.comm
));
335 TIFFjpeg_destroy(JPEGState
* sp
)
337 return CALLVJPEG(sp
, jpeg_destroy(&sp
->cinfo
.comm
));
341 TIFFjpeg_alloc_sarray(JPEGState
* sp
, int pool_id
,
342 JDIMENSION samplesperrow
, JDIMENSION numrows
)
344 return CALLJPEG(sp
, (JSAMPARRAY
) NULL
,
345 (*sp
->cinfo
.comm
.mem
->alloc_sarray
)
346 (&sp
->cinfo
.comm
, pool_id
, samplesperrow
, numrows
));
350 * JPEG library destination data manager.
351 * These routines direct compressed data from libjpeg into the
352 * libtiff output buffer.
356 std_init_destination(j_compress_ptr cinfo
)
358 JPEGState
* sp
= (JPEGState
*) cinfo
;
361 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
362 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
365 static wxjpeg_boolean
366 std_empty_output_buffer(j_compress_ptr cinfo
)
368 JPEGState
* sp
= (JPEGState
*) cinfo
;
371 /* the entire buffer has been filled */
372 tif
->tif_rawcc
= tif
->tif_rawdatasize
;
374 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
375 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
381 std_term_destination(j_compress_ptr cinfo
)
383 JPEGState
* sp
= (JPEGState
*) cinfo
;
386 tif
->tif_rawcp
= (tidata_t
) sp
->dest
.next_output_byte
;
388 tif
->tif_rawdatasize
- (tsize_t
) sp
->dest
.free_in_buffer
;
389 /* NB: libtiff does the final buffer flush */
393 TIFFjpeg_data_dest(JPEGState
* sp
, TIFF
* tif
)
396 sp
->cinfo
.c
.dest
= &sp
->dest
;
397 sp
->dest
.init_destination
= std_init_destination
;
398 sp
->dest
.empty_output_buffer
= std_empty_output_buffer
;
399 sp
->dest
.term_destination
= std_term_destination
;
403 * Alternate destination manager for outputting to JPEGTables field.
407 tables_init_destination(j_compress_ptr cinfo
)
409 JPEGState
* sp
= (JPEGState
*) cinfo
;
411 /* while building, jpegtables_length is allocated buffer size */
412 sp
->dest
.next_output_byte
= (JOCTET
*) sp
->jpegtables
;
413 sp
->dest
.free_in_buffer
= (size_t) sp
->jpegtables_length
;
416 static wxjpeg_boolean
417 tables_empty_output_buffer(j_compress_ptr cinfo
)
419 JPEGState
* sp
= (JPEGState
*) cinfo
;
422 /* the entire buffer has been filled; enlarge it by 1000 bytes */
423 newbuf
= _TIFFrealloc((tdata_t
) sp
->jpegtables
,
424 (tsize_t
) (sp
->jpegtables_length
+ 1000));
426 ERREXIT1(cinfo
, JERR_OUT_OF_MEMORY
, 100);
427 sp
->dest
.next_output_byte
= (JOCTET
*) newbuf
+ sp
->jpegtables_length
;
428 sp
->dest
.free_in_buffer
= (size_t) 1000;
429 sp
->jpegtables
= newbuf
;
430 sp
->jpegtables_length
+= 1000;
435 tables_term_destination(j_compress_ptr cinfo
)
437 JPEGState
* sp
= (JPEGState
*) cinfo
;
439 /* set tables length to number of bytes actually emitted */
440 sp
->jpegtables_length
-= sp
->dest
.free_in_buffer
;
444 TIFFjpeg_tables_dest(JPEGState
* sp
, TIFF
* tif
)
448 * Allocate a working buffer for building tables.
449 * Initial size is 1000 bytes, which is usually adequate.
452 _TIFFfree(sp
->jpegtables
);
453 sp
->jpegtables_length
= 1000;
454 sp
->jpegtables
= (void*) _TIFFmalloc((tsize_t
) sp
->jpegtables_length
);
455 if (sp
->jpegtables
== NULL
) {
456 sp
->jpegtables_length
= 0;
457 TIFFError("TIFFjpeg_tables_dest", "No space for JPEGTables");
460 sp
->cinfo
.c
.dest
= &sp
->dest
;
461 sp
->dest
.init_destination
= tables_init_destination
;
462 sp
->dest
.empty_output_buffer
= tables_empty_output_buffer
;
463 sp
->dest
.term_destination
= tables_term_destination
;
468 * JPEG library source data manager.
469 * These routines supply compressed data to libjpeg.
473 std_init_source(j_decompress_ptr cinfo
)
475 JPEGState
* sp
= (JPEGState
*) cinfo
;
478 sp
->src
.next_input_byte
= (const JOCTET
*) tif
->tif_rawdata
;
479 sp
->src
.bytes_in_buffer
= (size_t) tif
->tif_rawcc
;
482 static wxjpeg_boolean
483 std_fill_input_buffer(j_decompress_ptr cinfo
)
485 JPEGState
* sp
= (JPEGState
* ) cinfo
;
486 static const JOCTET dummy_EOI
[2] = { 0xFF, JPEG_EOI
};
489 * Should never get here since entire strip/tile is
490 * read into memory before the decompressor is called,
491 * and thus was supplied by init_source.
493 WARNMS(cinfo
, JWRN_JPEG_EOF
);
494 /* insert a fake EOI marker */
495 sp
->src
.next_input_byte
= dummy_EOI
;
496 sp
->src
.bytes_in_buffer
= 2;
501 std_skip_input_data(j_decompress_ptr cinfo
, long num_bytes
)
503 JPEGState
* sp
= (JPEGState
*) cinfo
;
506 if (num_bytes
> (long) sp
->src
.bytes_in_buffer
) {
507 /* oops, buffer overrun */
508 (void) std_fill_input_buffer(cinfo
);
510 sp
->src
.next_input_byte
+= (size_t) num_bytes
;
511 sp
->src
.bytes_in_buffer
-= (size_t) num_bytes
;
517 std_term_source(j_decompress_ptr cinfo
)
519 /* No work necessary here */
520 /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
521 /* (if so, need empty tables_term_source!) */
526 TIFFjpeg_data_src(JPEGState
* sp
, TIFF
* tif
)
529 sp
->cinfo
.d
.src
= &sp
->src
;
530 sp
->src
.init_source
= std_init_source
;
531 sp
->src
.fill_input_buffer
= std_fill_input_buffer
;
532 sp
->src
.skip_input_data
= std_skip_input_data
;
533 sp
->src
.resync_to_restart
= jpeg_resync_to_restart
;
534 sp
->src
.term_source
= std_term_source
;
535 sp
->src
.bytes_in_buffer
= 0; /* for safety */
536 sp
->src
.next_input_byte
= NULL
;
540 * Alternate source manager for reading from JPEGTables.
541 * We can share all the code except for the init routine.
545 tables_init_source(j_decompress_ptr cinfo
)
547 JPEGState
* sp
= (JPEGState
*) cinfo
;
549 sp
->src
.next_input_byte
= (const JOCTET
*) sp
->jpegtables
;
550 sp
->src
.bytes_in_buffer
= (size_t) sp
->jpegtables_length
;
554 TIFFjpeg_tables_src(JPEGState
* sp
, TIFF
* tif
)
556 TIFFjpeg_data_src(sp
, tif
);
557 sp
->src
.init_source
= tables_init_source
;
561 * Allocate downsampled-data buffers needed for downsampled I/O.
562 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
563 * We use libjpeg's allocator so that buffers will be released automatically
564 * when done with strip/tile.
565 * This is also a handy place to compute samplesperclump, bytesperline.
568 alloc_downsampled_buffers(TIFF
* tif
, jpeg_component_info
* comp_info
,
571 JPEGState
* sp
= JState(tif
);
573 jpeg_component_info
* compptr
;
575 int samples_per_clump
= 0;
577 for (ci
= 0, compptr
= comp_info
; ci
< num_components
;
579 samples_per_clump
+= compptr
->h_samp_factor
*
580 compptr
->v_samp_factor
;
581 buf
= TIFFjpeg_alloc_sarray(sp
, JPOOL_IMAGE
,
582 compptr
->width_in_blocks
* DCTSIZE
,
583 (JDIMENSION
) (compptr
->v_samp_factor
*DCTSIZE
));
586 sp
->ds_buffer
[ci
] = buf
;
588 sp
->samplesperclump
= samples_per_clump
;
598 JPEGSetupDecode(TIFF
* tif
)
600 JPEGState
* sp
= JState(tif
);
601 TIFFDirectory
*td
= &tif
->tif_dir
;
603 JPEGInitializeLibJPEG( tif
);
606 assert(sp
->cinfo
.comm
.is_decompressor
);
608 /* Read JPEGTables if it is present */
609 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
)) {
610 TIFFjpeg_tables_src(sp
, tif
);
611 if(TIFFjpeg_read_header(sp
,FALSE
) != JPEG_HEADER_TABLES_ONLY
) {
612 TIFFError("JPEGSetupDecode", "Bogus JPEGTables field");
617 /* Grab parameters that are same for all strips/tiles */
618 sp
->photometric
= td
->td_photometric
;
619 switch (sp
->photometric
) {
620 case PHOTOMETRIC_YCBCR
:
621 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
622 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
625 /* TIFF 6.0 forbids subsampling of all other color spaces */
631 /* Set up for reading normal data */
632 TIFFjpeg_data_src(sp
, tif
);
633 tif
->tif_postdecode
= _TIFFNoPostDecode
; /* override byte swapping */
638 * Set up for decoding a strip or tile.
641 JPEGPreDecode(TIFF
* tif
, tsample_t s
)
643 JPEGState
*sp
= JState(tif
);
644 TIFFDirectory
*td
= &tif
->tif_dir
;
645 static const char module[] = "JPEGPreDecode";
646 uint32 segment_width
, segment_height
;
647 int downsampled_output
;
651 assert(sp
->cinfo
.comm
.is_decompressor
);
653 * Reset decoder state from any previous strip/tile,
654 * in case application didn't read the whole strip.
656 if (!TIFFjpeg_abort(sp
))
659 * Read the header for this strip/tile.
661 if (TIFFjpeg_read_header(sp
, TRUE
) != JPEG_HEADER_OK
)
664 * Check image parameters and set decompression parameters.
666 segment_width
= td
->td_imagewidth
;
667 segment_height
= td
->td_imagelength
- tif
->tif_row
;
669 segment_width
= td
->td_tilewidth
;
670 segment_height
= td
->td_tilelength
;
671 sp
->bytesperline
= TIFFTileRowSize(tif
);
673 if (segment_height
> td
->td_rowsperstrip
)
674 segment_height
= td
->td_rowsperstrip
;
675 sp
->bytesperline
= TIFFScanlineSize(tif
);
677 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
679 * For PC 2, scale down the expected strip/tile size
680 * to match a downsampled component
682 segment_width
= TIFFhowmany(segment_width
, sp
->h_sampling
);
683 segment_height
= TIFFhowmany(segment_height
, sp
->v_sampling
);
685 if (sp
->cinfo
.d
.image_width
!= segment_width
||
686 sp
->cinfo
.d
.image_height
!= segment_height
) {
688 "Improper JPEG strip/tile size, expected %dx%d, got %dx%d",
691 sp
->cinfo
.d
.image_width
,
692 sp
->cinfo
.d
.image_height
);
694 if (sp
->cinfo
.d
.num_components
!=
695 (td
->td_planarconfig
== PLANARCONFIG_CONTIG
?
696 td
->td_samplesperpixel
: 1)) {
697 TIFFError(module, "Improper JPEG component count");
700 if (sp
->cinfo
.d
.data_precision
!= td
->td_bitspersample
) {
701 TIFFError(module, "Improper JPEG data precision");
704 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
705 /* Component 0 should have expected sampling factors */
706 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= sp
->h_sampling
||
707 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= sp
->v_sampling
) {
709 "Improper JPEG sampling factors %d,%d\n"
710 "Apparently should be %d,%d, "
711 "decompressor will try reading with "
713 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
,
714 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
,
717 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
,
718 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
);
720 sp
->h_sampling
= (uint16
)
721 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
;
722 sp
->v_sampling
= (uint16
)
723 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
;
725 /* Rest should have sampling factors 1,1 */
726 for (ci
= 1; ci
< sp
->cinfo
.d
.num_components
; ci
++) {
727 if (sp
->cinfo
.d
.comp_info
[ci
].h_samp_factor
!= 1 ||
728 sp
->cinfo
.d
.comp_info
[ci
].v_samp_factor
!= 1) {
729 TIFFError(module, "Improper JPEG sampling factors");
734 /* PC 2's single component should have sampling factors 1,1 */
735 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= 1 ||
736 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= 1) {
737 TIFFError(module, "Improper JPEG sampling factors");
741 downsampled_output
= FALSE
;
742 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
743 sp
->photometric
== PHOTOMETRIC_YCBCR
&&
744 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
745 /* Convert YCbCr to RGB */
746 sp
->cinfo
.d
.jpeg_color_space
= JCS_YCbCr
;
747 sp
->cinfo
.d
.out_color_space
= JCS_RGB
;
749 /* Suppress colorspace handling */
750 sp
->cinfo
.d
.jpeg_color_space
= JCS_UNKNOWN
;
751 sp
->cinfo
.d
.out_color_space
= JCS_UNKNOWN
;
752 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
753 (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1))
754 downsampled_output
= TRUE
;
755 /* XXX what about up-sampling? */
757 if (downsampled_output
) {
758 /* Need to use raw-data interface to libjpeg */
759 sp
->cinfo
.d
.raw_data_out
= TRUE
;
760 tif
->tif_decoderow
= JPEGDecodeRaw
;
761 tif
->tif_decodestrip
= JPEGDecodeRaw
;
762 tif
->tif_decodetile
= JPEGDecodeRaw
;
764 /* Use normal interface to libjpeg */
765 sp
->cinfo
.d
.raw_data_out
= FALSE
;
766 tif
->tif_decoderow
= JPEGDecode
;
767 tif
->tif_decodestrip
= JPEGDecode
;
768 tif
->tif_decodetile
= JPEGDecode
;
770 /* Start JPEG decompressor */
771 if (!TIFFjpeg_start_decompress(sp
))
773 /* Allocate downsampled-data buffers if needed */
774 if (downsampled_output
) {
775 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.d
.comp_info
,
776 sp
->cinfo
.d
.num_components
))
778 sp
->scancount
= DCTSIZE
; /* mark buffer empty */
784 * Decode a chunk of pixels.
785 * "Standard" case: returned data is not downsampled.
787 /*ARGSUSED*/ static int
788 JPEGDecode(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
790 JPEGState
*sp
= JState(tif
);
793 nrows
= cc
/ sp
->bytesperline
;
794 if (cc
% sp
->bytesperline
)
795 TIFFWarning(tif
->tif_name
, "fractional scanline not read");
797 if( nrows
> (int) sp
->cinfo
.d
.image_height
)
798 nrows
= sp
->cinfo
.d
.image_height
;
800 /* data is expected to be read in multiples of a scanline */
804 JSAMPROW bufptr
= (JSAMPROW
)buf
;
806 if (TIFFjpeg_read_scanlines(sp
, &bufptr
, 1) != 1)
809 buf
+= sp
->bytesperline
;
810 cc
-= sp
->bytesperline
;
811 } while (--nrows
> 0);
813 /* Close down the decompressor if we've finished the strip or tile. */
814 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
815 || TIFFjpeg_finish_decompress(sp
);
819 * Decode a chunk of pixels.
820 * Returned data is downsampled per sampling factors.
822 /*ARGSUSED*/ static int
823 JPEGDecodeRaw(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
825 JPEGState
*sp
= JState(tif
);
828 /* data is expected to be read in multiples of a scanline */
829 if ( (nrows
= sp
->cinfo
.d
.image_height
) ) {
830 /* Cb,Cr both have sampling factors 1, so this is correct */
831 JDIMENSION clumps_per_line
= sp
->cinfo
.d
.comp_info
[1].downsampled_width
;
832 int samples_per_clump
= sp
->samplesperclump
;
835 jpeg_component_info
*compptr
;
838 /* Reload downsampled-data buffer if needed */
839 if (sp
->scancount
>= DCTSIZE
) {
840 int n
= sp
->cinfo
.d
.max_v_samp_factor
* DCTSIZE
;
842 if (TIFFjpeg_read_raw_data(sp
, sp
->ds_buffer
, n
)
848 * Fastest way to unseparate data is to make one pass
849 * over the scanline for each row of each component.
851 clumpoffset
= 0; /* first sample in clump */
852 for (ci
= 0, compptr
= sp
->cinfo
.d
.comp_info
;
853 ci
< sp
->cinfo
.d
.num_components
;
855 int hsamp
= compptr
->h_samp_factor
;
856 int vsamp
= compptr
->v_samp_factor
;
859 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
860 JSAMPLE
*inptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
861 JSAMPLE
*outptr
= (JSAMPLE
*)buf
+ clumpoffset
;
865 /* fast path for at least Cb and Cr */
866 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
867 outptr
[0] = *inptr
++;
868 outptr
+= samples_per_clump
;
874 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
875 for (xpos
= 0; xpos
< hsamp
; xpos
++)
876 outptr
[xpos
] = *inptr
++;
877 outptr
+= samples_per_clump
;
880 clumpoffset
+= hsamp
;
885 buf
+= sp
->bytesperline
;
886 cc
-= sp
->bytesperline
;
887 } while (--nrows
> 0);
890 /* Close down the decompressor if done. */
891 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
892 || TIFFjpeg_finish_decompress(sp
);
901 unsuppress_quant_table (JPEGState
* sp
, int tblno
)
905 if ((qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[tblno
]) != NULL
)
906 qtbl
->sent_table
= FALSE
;
910 unsuppress_huff_table (JPEGState
* sp
, int tblno
)
914 if ((htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[tblno
]) != NULL
)
915 htbl
->sent_table
= FALSE
;
916 if ((htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[tblno
]) != NULL
)
917 htbl
->sent_table
= FALSE
;
921 prepare_JPEGTables(TIFF
* tif
)
923 JPEGState
* sp
= JState(tif
);
925 JPEGInitializeLibJPEG( tif
);
927 /* Initialize quant tables for current quality setting */
928 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
930 /* Mark only the tables we want for output */
931 /* NB: chrominance tables are currently used only with YCbCr */
932 if (!TIFFjpeg_suppress_tables(sp
, TRUE
))
934 if (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
) {
935 unsuppress_quant_table(sp
, 0);
936 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
937 unsuppress_quant_table(sp
, 1);
939 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
) {
940 unsuppress_huff_table(sp
, 0);
941 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
942 unsuppress_huff_table(sp
, 1);
944 /* Direct libjpeg output into jpegtables */
945 if (!TIFFjpeg_tables_dest(sp
, tif
))
947 /* Emit tables-only datastream */
948 if (!TIFFjpeg_write_tables(sp
))
955 JPEGSetupEncode(TIFF
* tif
)
957 JPEGState
* sp
= JState(tif
);
958 TIFFDirectory
*td
= &tif
->tif_dir
;
959 static const char module[] = "JPEGSetupEncode";
961 JPEGInitializeLibJPEG( tif
);
964 assert(!sp
->cinfo
.comm
.is_decompressor
);
967 * Initialize all JPEG parameters to default values.
968 * Note that jpeg_set_defaults needs legal values for
969 * in_color_space and input_components.
971 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
972 sp
->cinfo
.c
.input_components
= 1;
973 if (!TIFFjpeg_set_defaults(sp
))
975 /* Set per-file parameters */
976 sp
->photometric
= td
->td_photometric
;
977 switch (sp
->photometric
) {
978 case PHOTOMETRIC_YCBCR
:
979 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
980 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
982 * A ReferenceBlackWhite field *must* be present since the
983 * default value is inappropriate for YCbCr. Fill in the
984 * proper value if application didn't set it.
986 if (!TIFFFieldSet(tif
, FIELD_REFBLACKWHITE
)) {
988 long top
= 1L << td
->td_bitspersample
;
990 refbw
[1] = (float)(top
-1L);
991 refbw
[2] = (float)(top
>>1);
995 TIFFSetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
, refbw
);
998 case PHOTOMETRIC_PALETTE
: /* disallowed by Tech Note */
999 case PHOTOMETRIC_MASK
:
1001 "PhotometricInterpretation %d not allowed for JPEG",
1002 (int) sp
->photometric
);
1005 /* TIFF 6.0 forbids subsampling of all other color spaces */
1011 /* Verify miscellaneous parameters */
1014 * This would need work if libtiff ever supports different
1015 * depths for different components, or if libjpeg ever supports
1016 * run-time selection of depth. Neither is imminent.
1018 if (td
->td_bitspersample
!= BITS_IN_JSAMPLE
) {
1019 TIFFError(module, "BitsPerSample %d not allowed for JPEG",
1020 (int) td
->td_bitspersample
);
1023 sp
->cinfo
.c
.data_precision
= td
->td_bitspersample
;
1025 if ((td
->td_tilelength
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1027 "JPEG tile height must be multiple of %d",
1028 sp
->v_sampling
* DCTSIZE
);
1031 if ((td
->td_tilewidth
% (sp
->h_sampling
* DCTSIZE
)) != 0) {
1033 "JPEG tile width must be multiple of %d",
1034 sp
->h_sampling
* DCTSIZE
);
1038 if (td
->td_rowsperstrip
< td
->td_imagelength
&&
1039 (td
->td_rowsperstrip
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1041 "RowsPerStrip must be multiple of %d for JPEG",
1042 sp
->v_sampling
* DCTSIZE
);
1047 /* Create a JPEGTables field if appropriate */
1048 if (sp
->jpegtablesmode
& (JPEGTABLESMODE_QUANT
|JPEGTABLESMODE_HUFF
)) {
1049 if (!prepare_JPEGTables(tif
))
1051 /* Mark the field present */
1052 /* Can't use TIFFSetField since BEENWRITING is already set! */
1053 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1054 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1056 /* We do not support application-supplied JPEGTables, */
1057 /* so mark the field not present */
1058 TIFFClrFieldBit(tif
, FIELD_JPEGTABLES
);
1061 /* Direct libjpeg output to libtiff's output buffer */
1062 TIFFjpeg_data_dest(sp
, tif
);
1068 * Set encoding state at the start of a strip or tile.
1071 JPEGPreEncode(TIFF
* tif
, tsample_t s
)
1073 JPEGState
*sp
= JState(tif
);
1074 TIFFDirectory
*td
= &tif
->tif_dir
;
1075 static const char module[] = "JPEGPreEncode";
1076 uint32 segment_width
, segment_height
;
1077 int downsampled_input
;
1080 assert(!sp
->cinfo
.comm
.is_decompressor
);
1082 * Set encoding parameters for this strip/tile.
1085 segment_width
= td
->td_tilewidth
;
1086 segment_height
= td
->td_tilelength
;
1087 sp
->bytesperline
= TIFFTileRowSize(tif
);
1089 segment_width
= td
->td_imagewidth
;
1090 segment_height
= td
->td_imagelength
- tif
->tif_row
;
1091 if (segment_height
> td
->td_rowsperstrip
)
1092 segment_height
= td
->td_rowsperstrip
;
1093 sp
->bytesperline
= TIFFScanlineSize(tif
);
1095 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
1096 /* for PC 2, scale down the strip/tile size
1097 * to match a downsampled component
1099 segment_width
= TIFFhowmany(segment_width
, sp
->h_sampling
);
1100 segment_height
= TIFFhowmany(segment_height
, sp
->v_sampling
);
1102 if (segment_width
> 65535 || segment_height
> 65535) {
1103 TIFFError(module, "Strip/tile too large for JPEG");
1106 sp
->cinfo
.c
.image_width
= segment_width
;
1107 sp
->cinfo
.c
.image_height
= segment_height
;
1108 downsampled_input
= FALSE
;
1109 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1110 sp
->cinfo
.c
.input_components
= td
->td_samplesperpixel
;
1111 if (sp
->photometric
== PHOTOMETRIC_YCBCR
) {
1112 if (sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1113 sp
->cinfo
.c
.in_color_space
= JCS_RGB
;
1115 sp
->cinfo
.c
.in_color_space
= JCS_YCbCr
;
1116 if (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1)
1117 downsampled_input
= TRUE
;
1119 if (!TIFFjpeg_set_colorspace(sp
, JCS_YCbCr
))
1122 * Set Y sampling factors;
1123 * we assume jpeg_set_colorspace() set the rest to 1
1125 sp
->cinfo
.c
.comp_info
[0].h_samp_factor
= sp
->h_sampling
;
1126 sp
->cinfo
.c
.comp_info
[0].v_samp_factor
= sp
->v_sampling
;
1128 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1129 if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
))
1131 /* jpeg_set_colorspace set all sampling factors to 1 */
1134 sp
->cinfo
.c
.input_components
= 1;
1135 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1136 if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
))
1138 sp
->cinfo
.c
.comp_info
[0].component_id
= s
;
1139 /* jpeg_set_colorspace() set sampling factors to 1 */
1140 if (sp
->photometric
== PHOTOMETRIC_YCBCR
&& s
> 0) {
1141 sp
->cinfo
.c
.comp_info
[0].quant_tbl_no
= 1;
1142 sp
->cinfo
.c
.comp_info
[0].dc_tbl_no
= 1;
1143 sp
->cinfo
.c
.comp_info
[0].ac_tbl_no
= 1;
1146 /* ensure libjpeg won't write any extraneous markers */
1147 sp
->cinfo
.c
.write_JFIF_header
= FALSE
;
1148 sp
->cinfo
.c
.write_Adobe_marker
= FALSE
;
1149 /* set up table handling correctly */
1150 if (! (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
)) {
1151 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1153 unsuppress_quant_table(sp
, 0);
1154 unsuppress_quant_table(sp
, 1);
1156 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
)
1157 sp
->cinfo
.c
.optimize_coding
= FALSE
;
1159 sp
->cinfo
.c
.optimize_coding
= TRUE
;
1160 if (downsampled_input
) {
1161 /* Need to use raw-data interface to libjpeg */
1162 sp
->cinfo
.c
.raw_data_in
= TRUE
;
1163 tif
->tif_encoderow
= JPEGEncodeRaw
;
1164 tif
->tif_encodestrip
= JPEGEncodeRaw
;
1165 tif
->tif_encodetile
= JPEGEncodeRaw
;
1167 /* Use normal interface to libjpeg */
1168 sp
->cinfo
.c
.raw_data_in
= FALSE
;
1169 tif
->tif_encoderow
= JPEGEncode
;
1170 tif
->tif_encodestrip
= JPEGEncode
;
1171 tif
->tif_encodetile
= JPEGEncode
;
1173 /* Start JPEG compressor */
1174 if (!TIFFjpeg_start_compress(sp
, FALSE
))
1176 /* Allocate downsampled-data buffers if needed */
1177 if (downsampled_input
) {
1178 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.c
.comp_info
,
1179 sp
->cinfo
.c
.num_components
))
1188 * Encode a chunk of pixels.
1189 * "Standard" case: incoming data is not downsampled.
1192 JPEGEncode(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
1194 JPEGState
*sp
= JState(tif
);
1200 /* data is expected to be supplied in multiples of a scanline */
1201 nrows
= cc
/ sp
->bytesperline
;
1202 if (cc
% sp
->bytesperline
)
1203 TIFFWarning(tif
->tif_name
, "fractional scanline discarded");
1205 while (nrows
-- > 0) {
1206 bufptr
[0] = (JSAMPROW
) buf
;
1207 if (TIFFjpeg_write_scanlines(sp
, bufptr
, 1) != 1)
1211 buf
+= sp
->bytesperline
;
1217 * Encode a chunk of pixels.
1218 * Incoming data is expected to be downsampled per sampling factors.
1221 JPEGEncodeRaw(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
1223 JPEGState
*sp
= JState(tif
);
1227 JDIMENSION clumps_per_line
, nclump
;
1228 int clumpoffset
, ci
, xpos
, ypos
;
1229 jpeg_component_info
* compptr
;
1230 int samples_per_clump
= sp
->samplesperclump
;
1234 /* data is expected to be supplied in multiples of a scanline */
1235 nrows
= cc
/ sp
->bytesperline
;
1236 if (cc
% sp
->bytesperline
)
1237 TIFFWarning(tif
->tif_name
, "fractional scanline discarded");
1239 /* Cb,Cr both have sampling factors 1, so this is correct */
1240 clumps_per_line
= sp
->cinfo
.c
.comp_info
[1].downsampled_width
;
1242 while (nrows
-- > 0) {
1244 * Fastest way to separate the data is to make one pass
1245 * over the scanline for each row of each component.
1247 clumpoffset
= 0; /* first sample in clump */
1248 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1249 ci
< sp
->cinfo
.c
.num_components
;
1251 int hsamp
= compptr
->h_samp_factor
;
1252 int vsamp
= compptr
->v_samp_factor
;
1253 int padding
= (int) (compptr
->width_in_blocks
* DCTSIZE
-
1254 clumps_per_line
* hsamp
);
1255 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
1256 inptr
= ((JSAMPLE
*) buf
) + clumpoffset
;
1257 outptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
1259 /* fast path for at least Cb and Cr */
1260 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1261 *outptr
++ = inptr
[0];
1262 inptr
+= samples_per_clump
;
1266 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1267 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1268 *outptr
++ = inptr
[xpos
];
1269 inptr
+= samples_per_clump
;
1272 /* pad each scanline as needed */
1273 for (xpos
= 0; xpos
< padding
; xpos
++) {
1274 *outptr
= outptr
[-1];
1277 clumpoffset
+= hsamp
;
1281 if (sp
->scancount
>= DCTSIZE
) {
1282 int n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1283 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1289 buf
+= sp
->bytesperline
;
1295 * Finish up at the end of a strip or tile.
1298 JPEGPostEncode(TIFF
* tif
)
1300 JPEGState
*sp
= JState(tif
);
1302 if (sp
->scancount
> 0) {
1304 * Need to emit a partial bufferload of downsampled data.
1305 * Pad the data vertically.
1308 jpeg_component_info
* compptr
;
1310 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1311 ci
< sp
->cinfo
.c
.num_components
;
1313 int vsamp
= compptr
->v_samp_factor
;
1314 tsize_t row_width
= compptr
->width_in_blocks
* DCTSIZE
1316 for (ypos
= sp
->scancount
* vsamp
;
1317 ypos
< DCTSIZE
* vsamp
; ypos
++) {
1318 _TIFFmemcpy((tdata_t
)sp
->ds_buffer
[ci
][ypos
],
1319 (tdata_t
)sp
->ds_buffer
[ci
][ypos
-1],
1324 n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1325 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1329 return (TIFFjpeg_finish_compress(JState(tif
)));
1333 JPEGCleanup(TIFF
* tif
)
1335 if (tif
->tif_data
) {
1336 JPEGState
*sp
= JState(tif
);
1337 if( sp
->cinfo_initialized
)
1338 TIFFjpeg_destroy(sp
); /* release libjpeg resources */
1339 if (sp
->jpegtables
) /* tag value */
1340 _TIFFfree(sp
->jpegtables
);
1341 _TIFFfree(tif
->tif_data
); /* release local state */
1342 tif
->tif_data
= NULL
;
1347 JPEGVSetField(TIFF
* tif
, ttag_t tag
, va_list ap
)
1349 JPEGState
* sp
= JState(tif
);
1350 TIFFDirectory
* td
= &tif
->tif_dir
;
1354 case TIFFTAG_JPEGTABLES
:
1355 v32
= va_arg(ap
, uint32
);
1360 _TIFFsetByteArray(&sp
->jpegtables
, va_arg(ap
, void*),
1362 sp
->jpegtables_length
= v32
;
1363 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1365 case TIFFTAG_JPEGQUALITY
:
1366 sp
->jpegquality
= va_arg(ap
, int);
1367 return (1); /* pseudo tag */
1368 case TIFFTAG_JPEGCOLORMODE
:
1369 sp
->jpegcolormode
= va_arg(ap
, int);
1371 * Mark whether returned data is up-sampled or not
1372 * so TIFFStripSize and TIFFTileSize return values
1373 * that reflect the true amount of data.
1375 tif
->tif_flags
&= ~TIFF_UPSAMPLED
;
1376 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1377 if (td
->td_photometric
== PHOTOMETRIC_YCBCR
&&
1378 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1379 tif
->tif_flags
|= TIFF_UPSAMPLED
;
1381 if (td
->td_ycbcrsubsampling
[0] != 1 ||
1382 td
->td_ycbcrsubsampling
[1] != 1)
1383 ; /* XXX what about up-sampling? */
1387 * Must recalculate cached tile size
1388 * in case sampling state changed.
1390 tif
->tif_tilesize
= TIFFTileSize(tif
);
1391 return (1); /* pseudo tag */
1392 case TIFFTAG_JPEGTABLESMODE
:
1393 sp
->jpegtablesmode
= va_arg(ap
, int);
1394 return (1); /* pseudo tag */
1395 case TIFFTAG_YCBCRSUBSAMPLING
:
1396 /* mark the fact that we have a real ycbcrsubsampling! */
1397 sp
->ycbcrsampling_fetched
= 1;
1398 return (*sp
->vsetparent
)(tif
, tag
, ap
);
1400 return (*sp
->vsetparent
)(tif
, tag
, ap
);
1402 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1407 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
1408 * the TIFF tags, but still use non-default (2,2) values within the jpeg
1409 * data stream itself. In order for TIFF applications to work properly
1410 * - for instance to get the strip buffer size right - it is imperative
1411 * that the subsampling be available before we start reading the image
1412 * data normally. This function will attempt to load the first strip in
1413 * order to get the sampling values from the jpeg data stream. Various
1414 * hacks are various places are done to ensure this function gets called
1415 * before the td_ycbcrsubsampling values are used from the directory structure,
1416 * including calling TIFFGetField() for the YCBCRSUBSAMPLING field from
1417 * TIFFStripSize(), and the printing code in tif_print.c.
1419 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
1420 * discovered sampling does not match the default sampling (2,2) or whatever
1421 * was actually in the tiff tags.
1424 * o This code will cause one whole strip/tile of compressed data to be
1425 * loaded just to get the tags right, even if the imagery is never read.
1426 * It would be more efficient to just load a bit of the header, and
1427 * initialize things from that.
1429 * See the bug in bugzilla for details:
1431 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
1433 * Frank Warmerdam, July 2002
1437 JPEGFixupTestSubsampling( TIFF
* tif
)
1439 #if CHECK_JPEG_YCBCR_SUBSAMPLING == 1
1440 JPEGState
*sp
= JState(tif
);
1441 TIFFDirectory
*td
= &tif
->tif_dir
;
1443 JPEGInitializeLibJPEG( tif
);
1446 * Some JPEG-in-TIFF files don't provide the ycbcrsampling tags,
1447 * and use a sampling schema other than the default 2,2. To handle
1448 * this we actually have to scan the header of a strip or tile of
1449 * jpeg data to get the sampling.
1451 if( !sp
->cinfo
.comm
.is_decompressor
1452 || sp
->ycbcrsampling_fetched
1453 || td
->td_photometric
!= PHOTOMETRIC_YCBCR
)
1456 sp
->ycbcrsampling_fetched
= 1;
1457 if( TIFFIsTiled( tif
) )
1459 if( !TIFFFillTile( tif
, 0 ) )
1464 if( !TIFFFillStrip( tif
, 0 ) )
1468 TIFFSetField( tif
, TIFFTAG_YCBCRSUBSAMPLING
,
1469 (uint16
) sp
->h_sampling
, (uint16
) sp
->v_sampling
);
1470 #endif /* CHECK_JPEG_YCBCR_SUBSAMPLING == 1 */
1474 JPEGVGetField(TIFF
* tif
, ttag_t tag
, va_list ap
)
1476 JPEGState
* sp
= JState(tif
);
1479 case TIFFTAG_JPEGTABLES
:
1480 /* u_short is bogus --- should be uint32 ??? */
1481 /* TIFFWriteNormalTag needs fixed XXX */
1482 *va_arg(ap
, u_short
*) = (u_short
) sp
->jpegtables_length
;
1483 *va_arg(ap
, void**) = sp
->jpegtables
;
1485 case TIFFTAG_JPEGQUALITY
:
1486 *va_arg(ap
, int*) = sp
->jpegquality
;
1488 case TIFFTAG_JPEGCOLORMODE
:
1489 *va_arg(ap
, int*) = sp
->jpegcolormode
;
1491 case TIFFTAG_JPEGTABLESMODE
:
1492 *va_arg(ap
, int*) = sp
->jpegtablesmode
;
1494 case TIFFTAG_YCBCRSUBSAMPLING
:
1495 JPEGFixupTestSubsampling( tif
);
1496 return (*sp
->vgetparent
)(tif
, tag
, ap
);
1499 return (*sp
->vgetparent
)(tif
, tag
, ap
);
1505 JPEGPrintDir(TIFF
* tif
, FILE* fd
, long flags
)
1507 JPEGState
* sp
= JState(tif
);
1510 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
))
1511 fprintf(fd
, " JPEG Tables: (%lu bytes)\n",
1512 (u_long
) sp
->jpegtables_length
);
1516 JPEGDefaultStripSize(TIFF
* tif
, uint32 s
)
1518 JPEGState
* sp
= JState(tif
);
1519 TIFFDirectory
*td
= &tif
->tif_dir
;
1521 s
= (*sp
->defsparent
)(tif
, s
);
1522 if (s
< td
->td_imagelength
)
1523 s
= TIFFroundup(s
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
1528 JPEGDefaultTileSize(TIFF
* tif
, uint32
* tw
, uint32
* th
)
1530 JPEGState
* sp
= JState(tif
);
1531 TIFFDirectory
*td
= &tif
->tif_dir
;
1533 (*sp
->deftparent
)(tif
, tw
, th
);
1534 *tw
= TIFFroundup(*tw
, td
->td_ycbcrsubsampling
[0] * DCTSIZE
);
1535 *th
= TIFFroundup(*th
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
1539 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
1540 * now that we allow a TIFF file to be opened in update mode it is necessary
1541 * to have some way of deciding whether compression or decompression is
1542 * desired other than looking at tif->tif_mode. We accomplish this by
1543 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
1544 * If so, we assume decompression is desired.
1546 * This is tricky, because TIFFInitJPEG() is called while the directory is
1547 * being read, and generally speaking the BYTECOUNTS tag won't have been read
1548 * at that point. So we try to defer jpeg library initialization till we
1549 * do have that tag ... basically any access that might require the compressor
1550 * or decompressor that occurs after the reading of the directory.
1552 * In an ideal world compressors or decompressors would be setup
1553 * at the point where a single tile or strip was accessed (for read or write)
1554 * so that stuff like update of missing tiles, or replacement of tiles could
1555 * be done. However, we aren't trying to crack that nut just yet ...
1557 * NFW, Feb 3rd, 2003.
1560 static int JPEGInitializeLibJPEG( TIFF
* tif
)
1562 JPEGState
* sp
= JState(tif
);
1563 uint32
*byte_counts
= NULL
;
1564 int data_is_empty
= TRUE
;
1566 if( sp
->cinfo_initialized
)
1570 * Do we have tile data already? Make sure we initialize the
1571 * the state in decompressor mode if we have tile data, even if we
1572 * are not in read-only file access mode.
1574 if( TIFFIsTiled( tif
)
1575 && TIFFGetField( tif
, TIFFTAG_TILEBYTECOUNTS
, &byte_counts
)
1576 && byte_counts
!= NULL
)
1578 data_is_empty
= byte_counts
[0] == 0;
1580 if( !TIFFIsTiled( tif
)
1581 && TIFFGetField( tif
, TIFFTAG_STRIPBYTECOUNTS
, &byte_counts
)
1582 && byte_counts
!= NULL
)
1584 data_is_empty
= byte_counts
[0] == 0;
1588 * Initialize libjpeg.
1590 if (tif
->tif_mode
== O_RDONLY
|| !data_is_empty
) {
1591 if (!TIFFjpeg_create_decompress(sp
))
1595 if (!TIFFjpeg_create_compress(sp
))
1599 sp
->cinfo_initialized
= TRUE
;
1605 TIFFInitJPEG(TIFF
* tif
, int scheme
)
1609 assert(scheme
== COMPRESSION_JPEG
);
1612 * Allocate state block so tag methods have storage to record values.
1614 tif
->tif_data
= (tidata_t
) _TIFFmalloc(sizeof (JPEGState
));
1616 if (tif
->tif_data
== NULL
) {
1617 TIFFError("TIFFInitJPEG", "No space for JPEG state block");
1620 memset( tif
->tif_data
, 0, sizeof(JPEGState
));
1623 sp
->tif
= tif
; /* back link */
1626 * Merge codec-specific tag information and
1627 * override parent get/set field methods.
1629 _TIFFMergeFieldInfo(tif
, jpegFieldInfo
, N(jpegFieldInfo
));
1630 sp
->vgetparent
= tif
->tif_tagmethods
.vgetfield
;
1631 tif
->tif_tagmethods
.vgetfield
= JPEGVGetField
; /* hook for codec tags */
1632 sp
->vsetparent
= tif
->tif_tagmethods
.vsetfield
;
1633 tif
->tif_tagmethods
.vsetfield
= JPEGVSetField
; /* hook for codec tags */
1634 tif
->tif_tagmethods
.printdir
= JPEGPrintDir
; /* hook for codec tags */
1636 /* Default values for codec-specific fields */
1637 sp
->jpegtables
= NULL
;
1638 sp
->jpegtables_length
= 0;
1639 sp
->jpegquality
= 75; /* Default IJG quality */
1640 sp
->jpegcolormode
= JPEGCOLORMODE_RAW
;
1641 sp
->jpegtablesmode
= JPEGTABLESMODE_QUANT
| JPEGTABLESMODE_HUFF
;
1643 sp
->ycbcrsampling_fetched
= 0;
1646 * Install codec methods.
1648 tif
->tif_setupdecode
= JPEGSetupDecode
;
1649 tif
->tif_predecode
= JPEGPreDecode
;
1650 tif
->tif_decoderow
= JPEGDecode
;
1651 tif
->tif_decodestrip
= JPEGDecode
;
1652 tif
->tif_decodetile
= JPEGDecode
;
1653 tif
->tif_setupencode
= JPEGSetupEncode
;
1654 tif
->tif_preencode
= JPEGPreEncode
;
1655 tif
->tif_postencode
= JPEGPostEncode
;
1656 tif
->tif_encoderow
= JPEGEncode
;
1657 tif
->tif_encodestrip
= JPEGEncode
;
1658 tif
->tif_encodetile
= JPEGEncode
;
1659 tif
->tif_cleanup
= JPEGCleanup
;
1660 sp
->defsparent
= tif
->tif_defstripsize
;
1661 tif
->tif_defstripsize
= JPEGDefaultStripSize
;
1662 sp
->deftparent
= tif
->tif_deftilesize
;
1663 tif
->tif_deftilesize
= JPEGDefaultTileSize
;
1664 tif
->tif_flags
|= TIFF_NOBITREV
; /* no bit reversal, please */
1666 sp
->cinfo_initialized
= FALSE
;
1669 * Mark the TIFFTAG_YCBCRSAMPLES as present even if it is not
1670 * see: JPEGFixupTestSubsampling().
1672 TIFFSetFieldBit( tif
, FIELD_YCBCRSUBSAMPLING
);
1676 #endif /* JPEG_SUPPORT */