4 /* JPEG Compression support, as per the original TIFF 6.0 specification.
6 WARNING: KLUDGE ALERT! The type of JPEG encapsulation defined by the TIFF
7 Version 6.0 specification is now totally obsolete and
8 deprecated for new applications and images. This file is an unsupported hack
9 that was created solely in order to read (but NOT write!) a few old,
10 unconverted images still present on some users' computer systems. The code
11 isn't pretty or robust, and it won't read every "old format" JPEG-in-TIFF
12 file (see Samuel Leffler's draft "TIFF Technical Note No. 2" for a long and
13 incomplete list of known problems), but it seems to work well enough in the
14 few cases of practical interest to the author; so, "caveat emptor"! This
15 file should NEVER be enhanced to write new images using anything other than
16 the latest approved JPEG-in-TIFF encapsulation method, implemented by the
17 "tif_jpeg.c" file elsewhere in this library.
19 This file interfaces with Release 6B of the JPEG Library written by theu
20 Independent JPEG Group, which you can find on the Internet at:
21 ftp://ftp.uu.net:/graphics/jpeg/.
23 The "C" Preprocessor macros, "[CD]_LOSSLESS_SUPPORTED", are defined by your
24 JPEG Library Version 6B only if you have applied a (massive!) patch by Ken
25 Murchison of Oceana Matrix Ltd. <ken@oceana.com> to support lossless Huffman
26 encoding (TIFF "JPEGProc" tag value = 14). This patch can be found on the
27 Internet at: ftp://ftp.oceana.com/pub/ljpeg-6b.tar.gz.
29 Some old files produced by the Wang Imaging application for Microsoft Windows
30 apparently can be decoded only with a special patch to the JPEG Library,
31 which defines a subroutine named "jpeg_reset_huff_decode()" in its "jdhuff.c"
32 module (the "jdshuff.c" module, if Ken Murchison's patch has been applied).
33 Unfortunately the patch differs slightly in each case, and some TIFF Library
34 have reported problems finding the code, so both versions appear below; you
35 should carefully extract and apply only the version that applies to your JPEG
38 Contributed by Scott Marovich <marovich@hpl.hp.com> with considerable help
39 from Charles Auer <Bumble731@msn.com> to unravel the mysteries of image files
40 created by the Wang Imaging application for Microsoft Windows.
42 #if 0 /* Patch for JPEG Library WITHOUT lossless Huffman coding */
43 *** jdhuff
.c
.orig Mon Oct
20 17:51:10 1997
44 --- jdhuff
.c Sun Nov
11 17:33:58 2001
48 for (i
= 0; i
< NUM_HUFF_TBLS
; i
++) {
49 entropy
->dc_derived_tbls
[i
] = entropy
->ac_derived_tbls
[i
] = NULL
;
54 + * BEWARE OF KLUDGE: This subroutine is a hack for decoding illegal JPEG-in-
55 + * TIFF encapsulations produced by Microsoft's Wang Imaging
56 + * for Windows application with the public-domain TIFF Library. Based upon an
57 + * examination of selected output files, this program apparently divides a JPEG
58 + * bit-stream into consecutive horizontal TIFF "strips", such that the JPEG
59 + * encoder's/decoder's DC coefficients for each image component are reset before
60 + * each "strip". Moreover, a "strip" is not necessarily encoded in a multiple
61 + * of 8 bits, so one must sometimes discard 1-7 bits at the end of each "strip"
62 + * for alignment to the next input-Byte storage boundary. IJG JPEG Library
63 + * decoder state is not normally exposed to client applications, so this sub-
64 + * routine provides the TIFF Library with a "hook" to make these corrections.
65 + * It should be called after "jpeg_start_decompress()" and before
66 + * "jpeg_finish_decompress()", just before decoding each "strip" using
67 + * "jpeg_read_raw_data()" or "jpeg_read_scanlines()".
69 + * This kludge is not sanctioned or supported by the Independent JPEG Group, and
70 + * future changes to the IJG JPEG Library might invalidate it. Do not send bug
71 + * reports about this code to IJG developers. Instead, contact the author for
72 + * advice: Scott B. Marovich <marovich@hpl.hp.com>, Hewlett-Packard Labs, 6/01.
75 + jpeg_reset_huff_decode (register j_decompress_ptr cinfo
)
76 + { register huff_entropy_ptr entropy
= (huff_entropy_ptr
)cinfo
->entropy
;
77 + register int ci
= 0;
79 + /* Discard encoded input bits, up to the next Byte boundary */
80 + entropy
->bitstate
.bits_left
&= ~7;
81 + /* Re-initialize DC predictions to 0 */
82 + do entropy
->saved
.last_dc_val
[ci
] = 0; while (++ci
< cinfo
->comps_in_scan
);
84 #endif /* Patch for JPEG Library WITHOUT lossless Huffman coding */
85 #if 0 /* Patch for JPEG Library WITH lossless Huffman coding */
86 *** jdshuff
.c
.orig Mon Mar
11 16:44:54 2002
87 --- jdshuff
.c Mon Mar
11 16:44:54 2002
91 for (i
= 0; i
< NUM_HUFF_TBLS
; i
++) {
92 entropy
->dc_derived_tbls
[i
] = entropy
->ac_derived_tbls
[i
] = NULL
;
97 + * BEWARE OF KLUDGE: This subroutine is a hack for decoding illegal JPEG-in-
98 + * TIFF encapsulations produced by Microsoft's Wang Imaging
99 + * for Windows application with the public-domain TIFF Library. Based upon an
100 + * examination of selected output files, this program apparently divides a JPEG
101 + * bit-stream into consecutive horizontal TIFF "strips", such that the JPEG
102 + * encoder's/decoder's DC coefficients for each image component are reset before
103 + * each "strip". Moreover, a "strip" is not necessarily encoded in a multiple
104 + * of 8 bits, so one must sometimes discard 1-7 bits at the end of each "strip"
105 + * for alignment to the next input-Byte storage boundary. IJG JPEG Library
106 + * decoder state is not normally exposed to client applications, so this sub-
107 + * routine provides the TIFF Library with a "hook" to make these corrections.
108 + * It should be called after "jpeg_start_decompress()" and before
109 + * "jpeg_finish_decompress()", just before decoding each "strip" using
110 + * "jpeg_read_raw_data()" or "jpeg_read_scanlines()".
112 + * This kludge is not sanctioned or supported by the Independent JPEG Group, and
113 + * future changes to the IJG JPEG Library might invalidate it. Do not send bug
114 + * reports about this code to IJG developers. Instead, contact the author for
115 + * advice: Scott B. Marovich <marovich@hpl.hp.com>, Hewlett-Packard Labs, 6/01.
118 + jpeg_reset_huff_decode (register j_decompress_ptr cinfo
)
119 + { register shuff_entropy_ptr entropy
= (shuff_entropy_ptr
)
120 + ((j_lossy_d_ptr
)cinfo
->codec
)->entropy_private
;
121 + register int ci
= 0;
123 + /* Discard encoded input bits, up to the next Byte boundary */
124 + entropy
->bitstate
.bits_left
&= ~7;
125 + /* Re-initialize DC predictions to 0 */
126 + do entropy
->saved
.last_dc_val
[ci
] = 0; while (++ci
< cinfo
->comps_in_scan
);
128 #endif /* Patch for JPEG Library WITH lossless Huffman coding */
132 #undef FAR /* Undefine FAR to avoid conflict with JPEG definition */
134 #define JPEG_INTERNALS /* Include "jpegint.h" for "DSTATE_*" symbols */
135 #define JPEG_CJPEG_DJPEG /* Include all Version 6B+ "jconfig.h" options */
138 #undef JPEG_CJPEG_DJPEG
139 #undef JPEG_INTERNALS
141 /* Hack for files produced by Wang Imaging application on Microsoft Windows */
142 extern void jpeg_reset_huff_decode(j_decompress_ptr
);
144 /* On some machines, it may be worthwhile to use "_setjmp()" or "sigsetjmp()"
145 instead of "setjmp()". These macros make it easier:
147 #define SETJMP(jbuf)setjmp(jbuf)
148 #define LONGJMP(jbuf,code)longjmp(jbuf,code)
149 #define JMP_BUF jmp_buf
151 #define TIFFTAG_WANG_PAGECONTROL 32934
153 /* Bit-vector offsets for keeping track of TIFF records that we've parsed. */
155 #define FIELD_JPEGPROC FIELD_CODEC
156 #define FIELD_JPEGIFOFFSET (FIELD_CODEC+1)
157 #define FIELD_JPEGIFBYTECOUNT (FIELD_CODEC+2)
158 #define FIELD_JPEGRESTARTINTERVAL (FIELD_CODEC+3)
159 #define FIELD_JPEGTABLES (FIELD_CODEC+4) /* New, post-6.0 JPEG-in-TIFF tag! */
160 #define FIELD_JPEGLOSSLESSPREDICTORS (FIELD_CODEC+5)
161 #define FIELD_JPEGPOINTTRANSFORM (FIELD_CODEC+6)
162 #define FIELD_JPEGQTABLES (FIELD_CODEC+7)
163 #define FIELD_JPEGDCTABLES (FIELD_CODEC+8)
164 #define FIELD_JPEGACTABLES (FIELD_CODEC+9)
165 #define FIELD_WANG_PAGECONTROL (FIELD_CODEC+10)
166 #define FIELD_JPEGCOLORMODE (FIELD_CODEC+11)
168 typedef struct jpeg_destination_mgr jpeg_destination_mgr
;
169 typedef struct jpeg_source_mgr jpeg_source_mgr
;
170 typedef struct jpeg_error_mgr jpeg_error_mgr
;
172 /* State variable for each open TIFF file that uses "libjpeg" for JPEG
173 decompression. (Note: This file should NEVER perform JPEG compression
174 except in the manner implemented by the "tif_jpeg.c" file, elsewhere in this
175 library; see comments above.) JPEG Library internal state is recorded in a
176 "jpeg_{de}compress_struct", while a "jpeg_common_struct" records a few items
177 common to both compression and expansion. The "cinfo" field containing JPEG
178 Library state MUST be the 1st member of our own state variable, so that we
179 can safely "cast" pointers back and forth.
181 typedef struct /* This module's private, per-image state variable */
183 union /* JPEG Library state variable; this MUST be our 1st field! */
185 struct jpeg_compress_struct c
;
186 struct jpeg_decompress_struct d
;
187 struct jpeg_common_struct comm
;
189 jpeg_error_mgr err
; /* JPEG Library error manager */
190 JMP_BUF exit_jmpbuf
; /* ...for catching JPEG Library failures */
193 /* (The following two fields could be a "union", but they're small enough that
194 it's not worth the effort.)
196 jpeg_destination_mgr dest
; /* Destination for compressed data */
198 jpeg_source_mgr src
; /* Source of expanded data */
199 JSAMPARRAY ds_buffer
[MAX_COMPONENTS
]; /* ->Temporary downsampling buffers */
200 TIFF
*tif
; /* Reverse pointer, needed by some code */
201 TIFFVGetMethod vgetparent
; /* "Super class" methods... */
202 TIFFVSetMethod vsetparent
;
203 TIFFStripMethod defsparent
;
204 TIFFTileMethod deftparent
;
205 void *jpegtables
; /* ->"New" JPEG tables, if we synthesized any */
206 uint32 is_WANG
, /* <=> Wang Imaging for Microsoft Windows output file? */
207 jpegtables_length
; /* Length of "new" JPEG tables, if they exist */
208 tsize_t bytesperline
; /* No. of decompressed Bytes per scan line */
209 int jpegquality
, /* Compression quality level */
210 jpegtablesmode
, /* What to put in JPEGTables */
212 scancount
; /* No. of scan lines accumulated */
213 J_COLOR_SPACE photometric
; /* IJG JPEG Library's photometry code */
214 u_char h_sampling
, /* Luminance sampling factors */
216 jpegcolormode
; /* Who performs RGB <-> YCbCr conversion? */
217 /* JPEGCOLORMODE_RAW <=> TIFF Library or its client */
218 /* JPEGCOLORMODE_RGB <=> JPEG Library */
219 /* These fields are added to support TIFFGetField */
222 uint32 jpegifbytecount
;
223 uint32 jpegrestartinterval
;
224 void* jpeglosslesspredictors
;
225 uint16 jpeglosslesspredictors_length
;
226 void* jpegpointtransform
;
227 uint32 jpegpointtransform_length
;
229 uint32 jpegqtables_length
;
231 uint32 jpegdctables_length
;
233 uint32 jpegactables_length
;
236 #define OJState(tif)((OJPEGState*)(tif)->tif_data)
238 static const TIFFFieldInfo ojpegFieldInfo
[]=/* JPEG-specific TIFF-record tags */
241 /* This is the current JPEG-in-TIFF metadata-encapsulation tag, and its
242 treatment in this file is idiosyncratic. It should never appear in a
243 "source" image conforming to the TIFF Version 6.0 specification, so we
244 arrange to report an error if it appears. But in order to support possible
245 future conversion of "old" JPEG-in-TIFF encapsulations to "new" ones, we
246 might wish to synthesize an equivalent value to be returned by the TIFF
247 Library's "getfield" method. So, this table tells the TIFF Library to pass
248 these records to us in order to filter them below.
251 TIFFTAG_JPEGTABLES
,TIFF_VARIABLE
,TIFF_VARIABLE
,
252 TIFF_UNDEFINED
,FIELD_JPEGTABLES
,FALSE
,TRUE
,"JPEGTables"
255 /* These tags are defined by the TIFF Version 6.0 specification and are now
256 obsolete. This module reads them from an old "source" image, but it never
257 writes them to a new "destination" image.
260 TIFFTAG_JPEGPROC
,1 ,1 ,
261 TIFF_SHORT
,FIELD_JPEGPROC
,FALSE
,FALSE
,"JPEGProc"
264 TIFFTAG_JPEGIFOFFSET
,1 ,1 ,
265 TIFF_LONG
,FIELD_JPEGIFOFFSET
,FALSE
,FALSE
,"JPEGInterchangeFormat"
268 TIFFTAG_JPEGIFBYTECOUNT
,1 ,1 ,
269 TIFF_LONG
,FIELD_JPEGIFBYTECOUNT
,FALSE
,FALSE
,"JPEGInterchangeFormatLength"
272 TIFFTAG_JPEGRESTARTINTERVAL
,1 ,1 ,
273 TIFF_SHORT
,FIELD_JPEGRESTARTINTERVAL
,FALSE
,FALSE
,"JPEGRestartInterval"
276 TIFFTAG_JPEGLOSSLESSPREDICTORS
,TIFF_VARIABLE
,TIFF_VARIABLE
,
277 TIFF_SHORT
,FIELD_JPEGLOSSLESSPREDICTORS
,FALSE
,TRUE
,"JPEGLosslessPredictors"
280 TIFFTAG_JPEGPOINTTRANSFORM
,TIFF_VARIABLE
,TIFF_VARIABLE
,
281 TIFF_SHORT
,FIELD_JPEGPOINTTRANSFORM
,FALSE
,TRUE
,"JPEGPointTransforms"
284 TIFFTAG_JPEGQTABLES
,TIFF_VARIABLE
,TIFF_VARIABLE
,
285 TIFF_LONG
,FIELD_JPEGQTABLES
,FALSE
,TRUE
,"JPEGQTables"
288 TIFFTAG_JPEGDCTABLES
,TIFF_VARIABLE
,TIFF_VARIABLE
,
289 TIFF_LONG
,FIELD_JPEGDCTABLES
,FALSE
,TRUE
,"JPEGDCTables"
292 TIFFTAG_JPEGACTABLES
,TIFF_VARIABLE
,TIFF_VARIABLE
,
293 TIFF_LONG
,FIELD_JPEGACTABLES
,FALSE
,TRUE
,"JPEGACTables"
296 TIFFTAG_WANG_PAGECONTROL
,TIFF_VARIABLE
,1 ,
297 TIFF_LONG
,FIELD_WANG_PAGECONTROL
,FALSE
,FALSE
,"WANG PageControl"
300 /* This is a pseudo tag intended for internal use only by the TIFF Library and
301 its clients, which should never appear in an input/output image file. It
302 specifies whether the TIFF Library (or its client) should do YCbCr <-> RGB
303 color-space conversion (JPEGCOLORMODE_RAW <=> 0) or whether we should ask
304 the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1).
307 TIFFTAG_JPEGCOLORMODE
,0 ,0 ,
308 TIFF_ANY
,FIELD_PSEUDO
,FALSE
,FALSE
,"JPEGColorMode"
311 static const char JPEGLib_name
[]={"JPEG Library"},
312 bad_bps
[]={"%u BitsPerSample not allowed for JPEG"},
313 bad_photometry
[]={"PhotometricInterpretation %u not allowed for JPEG"},
314 bad_subsampling
[]={"invalid YCbCr subsampling factor(s)"},
316 no_write_frac
[]={"fractional scan line discarded"},
318 no_read_frac
[]={"fractional scan line not read"},
319 no_jtable_space
[]={"No space for JPEGTables"};
321 /* The following diagnostic subroutines interface with and replace default
322 subroutines in the JPEG Library. Our basic strategy is to use "setjmp()"/
323 "longjmp()" in order to return control to the TIFF Library when the JPEG
324 library detects an error, and to use TIFF Library subroutines for displaying
325 diagnostic messages to a client application.
328 TIFFojpeg_error_exit(register j_common_ptr cinfo
)
329 { char buffer
[JMSG_LENGTH_MAX
];
331 (*cinfo
->err
->format_message
)(cinfo
,buffer
);
332 TIFFError(JPEGLib_name
,buffer
); /* Display error message */
333 jpeg_abort(cinfo
); /* Clean up JPEG Library state */
334 LONGJMP(((OJPEGState
*)cinfo
)->exit_jmpbuf
,1); /* Return to TIFF client */
338 TIFFojpeg_output_message(register j_common_ptr cinfo
)
339 { char buffer
[JMSG_LENGTH_MAX
];
341 /* This subroutine is invoked only for warning messages, since the JPEG
342 Library's "error_exit" method does its own thing and "trace_level" is never
345 (*cinfo
->err
->format_message
)(cinfo
,buffer
);
346 TIFFWarning(JPEGLib_name
,buffer
);
349 /* The following subroutines, which also interface with the JPEG Library, exist
350 mainly in limit the side effects of "setjmp()" and convert JPEG normal/error
351 conditions into TIFF Library return codes.
353 #define CALLJPEG(sp,fail,op)(SETJMP((sp)->exit_jmpbuf)?(fail):(op))
354 #define CALLVJPEG(sp,op)CALLJPEG(sp,0,((op),1))
358 TIFFojpeg_create_compress(register OJPEGState
*sp
)
360 sp
->cinfo
.c
.err
= jpeg_std_error(&sp
->err
); /* Initialize error handling */
361 sp
->err
.error_exit
= TIFFojpeg_error_exit
;
362 sp
->err
.output_message
= TIFFojpeg_output_message
;
363 return CALLVJPEG(sp
,jpeg_create_compress(&sp
->cinfo
.c
));
366 /* The following subroutines comprise a JPEG Library "destination" data manager
367 by directing compressed data from the JPEG Library to a TIFF Library output
371 std_init_destination(register j_compress_ptr cinfo
){} /* "Dummy" stub */
374 std_empty_output_buffer(register j_compress_ptr cinfo
)
376 # define sp ((OJPEGState *)cinfo)
377 register TIFF
*tif
= sp
->tif
;
379 tif
->tif_rawcc
= tif
->tif_rawdatasize
; /* Entire buffer has been filled */
381 sp
->dest
.next_output_byte
= (JOCTET
*)tif
->tif_rawdata
;
382 sp
->dest
.free_in_buffer
= (size_t)tif
->tif_rawdatasize
;
388 std_term_destination(register j_compress_ptr cinfo
)
390 # define sp ((OJPEGState *)cinfo)
391 register TIFF
*tif
= sp
->tif
;
393 /* NB: The TIFF Library does the final buffer flush. */
394 tif
->tif_rawcp
= (tidata_t
)sp
->dest
.next_output_byte
;
395 tif
->tif_rawcc
= tif
->tif_rawdatasize
- (tsize_t
)sp
->dest
.free_in_buffer
;
399 /* Alternate destination manager to output JPEGTables field: */
402 tables_init_destination(register j_compress_ptr cinfo
)
404 # define sp ((OJPEGState *)cinfo)
405 /* The "jpegtables_length" field is the allocated buffer size while building */
406 sp
->dest
.next_output_byte
= (JOCTET
*)sp
->jpegtables
;
407 sp
->dest
.free_in_buffer
= (size_t)sp
->jpegtables_length
;
412 tables_empty_output_buffer(register j_compress_ptr cinfo
)
414 # define sp ((OJPEGState *)cinfo)
416 /* The entire buffer has been filled, so enlarge it by 1000 bytes. */
417 if (!( newbuf
= _TIFFrealloc( (tdata_t
)sp
->jpegtables
418 , (tsize_t
)(sp
->jpegtables_length
+ 1000)
421 ) ERREXIT1(cinfo
,JERR_OUT_OF_MEMORY
,100);
422 sp
->dest
.next_output_byte
= (JOCTET
*)newbuf
+ sp
->jpegtables_length
;
423 sp
->dest
.free_in_buffer
= (size_t)1000;
424 sp
->jpegtables
= newbuf
;
425 sp
->jpegtables_length
+= 1000;
431 tables_term_destination(register j_compress_ptr cinfo
)
433 # define sp ((OJPEGState *)cinfo)
434 /* Set tables length to no. of Bytes actually emitted. */
435 sp
->jpegtables_length
-= sp
->dest
.free_in_buffer
;
439 /*ARGSUSED*/ static int
440 TIFFojpeg_tables_dest(register OJPEGState
*sp
, TIFF
*tif
)
443 /* Allocate a working buffer for building tables. The initial size is 1000
444 Bytes, which is usually adequate.
446 if (sp
->jpegtables
) _TIFFfree(sp
->jpegtables
);
447 if (!(sp
->jpegtables
= (void*)
448 _TIFFmalloc((tsize_t
)(sp
->jpegtables_length
= 1000))
452 sp
->jpegtables_length
= 0;
453 TIFFError("TIFFojpeg_tables_dest",no_jtable_space
);
456 sp
->cinfo
.c
.dest
= &sp
->dest
;
457 sp
->dest
.init_destination
= tables_init_destination
;
458 sp
->dest
.empty_output_buffer
= tables_empty_output_buffer
;
459 sp
->dest
.term_destination
= tables_term_destination
;
462 #else /* well, hardly ever */
465 _notSupported(register TIFF
*tif
)
466 { const TIFFCodec
*c
= TIFFFindCODEC(tif
->tif_dir
.td_compression
);
468 TIFFError(tif
->tif_name
,"%s compression not supported",c
->name
);
473 /* The following subroutines comprise a JPEG Library "source" data manager by
474 by directing compressed data to the JPEG Library from a TIFF Library input
478 std_init_source(register j_decompress_ptr cinfo
)
480 # define sp ((OJPEGState *)cinfo)
481 register TIFF
*tif
= sp
->tif
;
483 if (sp
->src
.bytes_in_buffer
== 0)
485 sp
->src
.next_input_byte
= (const JOCTET
*)tif
->tif_rawdata
;
486 sp
->src
.bytes_in_buffer
= (size_t)tif
->tif_rawcc
;
492 std_fill_input_buffer(register j_decompress_ptr cinfo
)
493 { static const JOCTET dummy_EOI
[2]={0xFF,JPEG_EOI
};
494 # define sp ((OJPEGState *)cinfo)
496 /* Control should never get here, since an entire strip/tile is read into
497 memory before the decompressor is called; thus, data should have been
498 supplied by the "init_source" method. ...But, sometimes things fail.
500 WARNMS(cinfo
,JWRN_JPEG_EOF
);
501 sp
->src
.next_input_byte
= dummy_EOI
; /* Insert a fake EOI marker */
502 sp
->src
.bytes_in_buffer
= sizeof dummy_EOI
;
508 std_skip_input_data(register j_decompress_ptr cinfo
, long num_bytes
)
510 # define sp ((OJPEGState *)cinfo)
514 if (num_bytes
> (long)sp
->src
.bytes_in_buffer
) /* oops: buffer overrun */
515 (void)std_fill_input_buffer(cinfo
);
518 sp
->src
.next_input_byte
+= (size_t)num_bytes
;
519 sp
->src
.bytes_in_buffer
-= (size_t)num_bytes
;
525 /*ARGSUSED*/ static void
526 std_term_source(register j_decompress_ptr cinfo
){} /* "Dummy" stub */
528 /* Allocate temporary I/O buffers for downsampled data, using values computed in
529 "jpeg_start_{de}compress()". We use the JPEG Library's allocator so that
530 buffers will be released automatically when done with a strip/tile. This is
531 also a handy place to compute samplesperclump, bytesperline, etc.
534 alloc_downsampled_buffers(TIFF
*tif
,jpeg_component_info
*comp_info
,
536 { register OJPEGState
*sp
= OJState(tif
);
538 sp
->samplesperclump
= 0;
539 if (num_components
> 0)
540 { tsize_t size
= sp
->cinfo
.comm
.is_decompressor
541 # ifdef D_LOSSLESS_SUPPORTED
542 ? sp
->cinfo
.d
.min_codec_data_unit
546 # ifdef C_LOSSLESS_SUPPORTED
547 : sp
->cinfo
.c
.data_unit
;
552 register jpeg_component_info
*compptr
= comp_info
;
557 sp
->samplesperclump
+=
558 compptr
->h_samp_factor
* compptr
->v_samp_factor
;
559 # if defined(C_LOSSLESS_SUPPORTED) || defined(D_LOSSLESS_SUPPORTED)
560 if (!(buf
= CALLJPEG(sp
,0,(*sp
->cinfo
.comm
.mem
->alloc_sarray
)(&sp
->cinfo
.comm
,JPOOL_IMAGE
,compptr
->width_in_data_units
*size
,compptr
->v_samp_factor
*size
))))
562 if (!(buf
= CALLJPEG(sp
,0,(*sp
->cinfo
.comm
.mem
->alloc_sarray
)(&sp
->cinfo
.comm
,JPOOL_IMAGE
,compptr
->width_in_blocks
*size
,compptr
->v_samp_factor
*size
))))
565 sp
->ds_buffer
[ci
] = buf
;
567 while (++compptr
,++ci
< num_components
);
573 /* JPEG Encoding begins here. */
575 /*ARGSUSED*/ static int
576 OJPEGEncode(register TIFF
*tif
,tidata_t buf
,tsize_t cc
,tsample_t s
)
577 { tsize_t rows
; /* No. of unprocessed rows in file */
578 register OJPEGState
*sp
= OJState(tif
);
580 /* Encode a chunk of pixels, where returned data is NOT down-sampled (the
581 standard case). The data is expected to be written in scan-line multiples.
583 if (cc
% sp
->bytesperline
) TIFFWarning(tif
->tif_name
,no_write_frac
);
584 if ( (cc
/= bytesperline
) /* No. of complete rows in caller's buffer */
585 > (rows
= sp
->cinfo
.c
.image_height
- sp
->cinfo
.c
.next_scanline
)
589 if ( CALLJPEG(sp
,-1,jpeg_write_scanlines(&sp
->cinfo
.c
,(JSAMPARRAY
)&buf
,1))
593 buf
+= sp
->bytesperline
;
598 /*ARGSUSED*/ static int
599 OJPEGEncodeRaw(register TIFF
*tif
,tidata_t buf
,tsize_t cc
,tsample_t s
)
600 { tsize_t rows
; /* No. of unprocessed rows in file */
601 JDIMENSION lines_per_MCU
, size
;
602 register OJPEGState
*sp
= OJState(tif
);
604 /* Encode a chunk of pixels, where returned data is down-sampled as per the
605 sampling factors. The data is expected to be written in scan-line
608 cc
/= sp
->bytesperline
;
609 if (cc
% sp
->bytesperline
) TIFFWarning(tif
->tif_name
,no_write_frac
);
610 if ( (cc
/= bytesperline
) /* No. of complete rows in caller's buffer */
611 > (rows
= sp
->cinfo
.c
.image_height
- sp
->cinfo
.c
.next_scanline
)
613 # ifdef C_LOSSLESS_SUPPORTED
614 lines_per_MCU
= sp
->cinfo
.c
.max_samp_factor
*(size
= sp
->cinfo
.d
.data_unit
);
616 lines_per_MCU
= sp
->cinfo
.c
.max_samp_factor
*(size
= DCTSIZE
);
619 { int ci
= 0, clumpoffset
= 0;
620 register jpeg_component_info
*compptr
= sp
->cinfo
.c
.comp_info
;
622 /* The fastest way to separate the data is to make 1 pass over the scan
623 line for each row of each component.
630 register JSAMPLE
*inptr
= (JSAMPLE
*)buf
+ clumpoffset
,
632 sp
->ds_buffer
[ci
][sp
->scancount
*compptr
->v_samp_factor
+ypos
];
633 /* Cb,Cr both have sampling factors 1, so this is correct */
634 register int clumps_per_line
=
635 sp
->cinfo
.c
.comp_info
[1].downsampled_width
,
639 # ifdef C_LOSSLESS_SUPPORTED
640 ( compptr
->width_in_data_units
* size
642 ( compptr
->width_in_blocks
* size
644 - clumps_per_line
* compptr
->h_samp_factor
646 if (compptr
->h_samp_factor
== 1) /* Cb & Cr fast path */
647 do *outptr
++ = *inptr
;
648 while ((inptr
+= sp
->samplesperclump
),--clumps_per_line
> 0);
649 else /* general case */
653 do *outptr
++ = inptr
[xpos
];
654 while (++xpos
< compptr
->h_samp_factor
);
656 while ((inptr
+= sp
->samplesperclump
),--clumps_per_line
> 0);
657 xpos
= 0; /* Pad each scan line as needed */
658 do outptr
[0] = outptr
[-1]; while (++outptr
,++xpos
< padding
);
659 clumpoffset
+= compptr
->h_samp_factor
;
661 while (++ypos
< compptr
->v_samp_factor
);
663 while (++compptr
,++ci
< sp
->cinfo
.c
.num_components
);
664 if (++sp
->scancount
>= size
)
666 if ( CALLJPEG(sp
,-1,jpeg_write_raw_data(&sp
->cinfo
.c
,sp
->ds_buffer
,lines_per_MCU
))
672 buf
+= sp
->bytesperline
;
678 OJPEGSetupEncode(register TIFF
*tif
)
679 { static const char module[]={"OJPEGSetupEncode"};
680 uint32 segment_height
, segment_width
;
681 int status
= 1; /* Assume success by default */
682 register OJPEGState
*sp
= OJState(tif
);
683 # define td (&tif->tif_dir)
685 /* Verify miscellaneous parameters. This will need work if the TIFF Library
686 ever supports different depths for different components, or if the JPEG
687 Library ever supports run-time depth selection. Neither seems imminent.
689 if (td
->td_bitspersample
!= 8)
691 TIFFError(module,bad_bps
,td
->td_bitspersample
);
695 /* The TIFF Version 6.0 specification and IJG JPEG Library accept different
696 sets of color spaces, so verify that our image belongs to the common subset
697 and map its photometry code, then initialize to handle subsampling and
698 optional JPEG Library YCbCr <-> RGB color-space conversion.
700 switch (td
->td_photometric
)
702 case PHOTOMETRIC_YCBCR
:
704 /* ISO IS 10918-1 requires that JPEG subsampling factors be 1-4, but
705 TIFF Version 6.0 is more restrictive: only 1, 2, and 4 are allowed.
707 if ( ( td
->td_ycbcrsubsampling
[0] == 1
708 || td
->td_ycbcrsubsampling
[0] == 2
709 || td
->td_ycbcrsubsampling
[0] == 4
711 && ( td
->td_ycbcrsubsampling
[1] == 1
712 || td
->td_ycbcrsubsampling
[1] == 2
713 || td
->td_ycbcrsubsampling
[1] == 4
716 sp
->cinfo
.c
.raw_data_in
=
717 ( (sp
->h_sampling
= td
->td_ycbcrsubsampling
[0]) << 3
718 | (sp
->v_sampling
= td
->td_ycbcrsubsampling
[1])
722 TIFFError(module,bad_subsampling
);
726 /* A ReferenceBlackWhite field MUST be present, since the default value
727 is inapproriate for YCbCr. Fill in the proper value if the
728 application didn't set it.
730 if (!TIFFFieldSet(tif
,FIELD_REFBLACKWHITE
))
732 long top
= 1L << td
->td_bitspersample
;
735 refbw
[1] = (float)(top
-1L);
736 refbw
[2] = (float)(top
>>1);
740 TIFFSetField(tif
,TIFFTAG_REFERENCEBLACKWHITE
,refbw
);
742 sp
->cinfo
.c
.jpeg_color_space
= JCS_YCbCr
;
743 if (sp
->jpegcolormode
== JPEGCOLORMODE_RGB
)
745 sp
->cinfo
.c
.raw_data_in
= FALSE
;
746 sp
->in_color_space
= JCS_RGB
;
750 case PHOTOMETRIC_MINISBLACK
:
751 sp
->cinfo
.c
.jpeg_color_space
= JCS_GRAYSCALE
;
753 case PHOTOMETRIC_RGB
:
754 sp
->cinfo
.c
.jpeg_color_space
= JCS_RGB
;
756 case PHOTOMETRIC_SEPARATED
:
757 sp
->cinfo
.c
.jpeg_color_space
= JCS_CMYK
;
758 L1
: sp
->jpegcolormode
= JPEGCOLORMODE_RAW
; /* No JPEG Lib. conversion */
759 L2
: sp
->cinfo
.d
.in_color_space
= sp
->cinfo
.d
.jpeg_color
-space
;
762 TIFFError(module,bad_photometry
,td
->td_photometric
);
765 tif
->tif_encoderow
= tif
->tif_encodestrip
= tif
->tif_encodetile
=
766 sp
->cinfo
.c
.raw_data_in
? OJPEGEncodeRaw
: OJPEGEncode
;
770 # ifdef C_LOSSLESS_SUPPORTED
771 if ((size
= sp
->v_sampling
*sp
->cinfo
.c
.data_unit
) < 16) size
= 16;
773 if ((size
= sp
->v_sampling
*DCTSIZE
) < 16) size
= 16;
775 if ((segment_height
= td
->td_tilelength
) % size
)
777 TIFFError(module,"JPEG tile height must be multiple of %d",size
);
780 # ifdef C_LOSSLESS_SUPPORTED
781 if ((size
= sp
->h_sampling
*sp
->cinfo
.c
.data_unit
) < 16) size
= 16;
783 if ((size
= sp
->h_sampling
*DCTSIZE
) < 16) size
= 16;
785 if ((segment_width
= td
->td_tilewidth
) % size
)
787 TIFFError(module,"JPEG tile width must be multiple of %d",size
);
790 sp
->bytesperline
= TIFFTileRowSize(tif
);
795 # ifdef C_LOSSLESS_SUPPORTED
796 if ((size
= sp
->v_sampling
*sp
->cinfo
.c
.data_unit
) < 16) size
= 16;
798 if ((size
= sp
->v_sampling
*DCTSIZE
) < 16) size
= 16;
800 if (td
->td_rowsperstrip
< (segment_height
= td
->td_imagelength
))
802 if (td
->td_rowsperstrip
% size
)
804 TIFFError(module,"JPEG RowsPerStrip must be multiple of %d",size
);
807 segment_height
= td
->td_rowsperstrip
;
809 segment_width
= td
->td_imagewidth
;
810 sp
->bytesperline
= tif
->tif_scanlinesize
;
812 if (segment_width
> 65535 || segment_height
> 65535)
814 TIFFError(module,"Strip/tile too large for JPEG");
818 /* Initialize all JPEG parameters to default values. Note that the JPEG
819 Library's "jpeg_set_defaults()" method needs legal values for the
820 "in_color_space" and "input_components" fields.
822 sp
->cinfo
.c
.input_components
= 1; /* Default for JCS_UNKNOWN */
823 if (!CALLVJPEG(sp
,jpeg_set_defaults(&sp
->cinfo
.c
))) status
= 0;
824 switch (sp
->jpegtablesmode
& (JPEGTABLESMODE_HUFF
|JPEGTABLESMODE_QUANT
))
825 { register JHUFF_TBL
*htbl
;
826 register JQUANT_TBL
*qtbl
;
829 sp
->cinfo
.c
.optimize_coding
= TRUE
;
830 case JPEGTABLESMODE_HUFF
:
831 if (!CALLVJPEG(sp
,jpeg_set_quality(&sp
->cinfo
.c
,sp
->jpegquality
,FALSE
)))
833 if (qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[0]) qtbl
->sent_table
= FALSE
;
834 if (qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[1]) qtbl
->sent_table
= FALSE
;
836 case JPEGTABLESMODE_QUANT
:
837 sp
->cinfo
.c
.optimize_coding
= TRUE
;
839 /* We do not support application-supplied JPEG tables, so mark the field
842 L3
: TIFFClrFieldBit(tif
,FIELD_JPEGTABLES
);
844 case JPEGTABLESMODE_HUFF
|JPEGTABLESMODE_QUANT
:
845 if ( !CALLVJPEG(sp
,jpeg_set_quality(&sp
->cinfo
.c
,sp
->jpegquality
,FALSE
))
846 || !CALLVJPEG(sp
,jpeg_suppress_tables(&sp
->cinfo
.c
,TRUE
))
852 if (qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[0]) qtbl
->sent_table
= FALSE
;
853 if (htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[0]) htbl
->sent_table
= FALSE
;
854 if (htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[0]) htbl
->sent_table
= FALSE
;
855 if (sp
->cinfo
.c
.jpeg_color_space
== JCS_YCbCr
)
857 if (qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[1])
858 qtbl
->sent_table
= FALSE
;
859 if (htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[1])
860 htbl
->sent_table
= FALSE
;
861 if (htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[1])
862 htbl
->sent_table
= FALSE
;
864 if ( TIFFojpeg_tables_dest(sp
,tif
)
865 && CALLVJPEG(sp
,jpeg_write_tables(&sp
->cinfo
.c
))
869 /* Mark the field "present". We can't use "TIFFSetField()" because
870 "BEENWRITING" is already set!
872 TIFFSetFieldBit(tif
,FIELD_JPEGTABLES
);
873 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
877 if ( sp
->cinfo
.c
.raw_data_in
878 && !alloc_downsampled_buffers(tif
,sp
->cinfo
.c
.comp_info
,
879 sp
->cinfo
.c
.num_components
)
881 if (status
== 0) return 0; /* If TIFF errors, don't bother to continue */
882 /* Grab parameters that are same for all strips/tiles. */
884 sp
->dest
.init_destination
= std_init_destination
;
885 sp
->dest
.empty_output_buffer
= std_empty_output_buffer
;
886 sp
->dest
.term_destination
= std_term_destination
;
887 sp
->cinfo
.c
.dest
= &sp
->dest
;
888 sp
->cinfo
.c
.data_precision
= td
->td_bitspersample
;
889 sp
->cinfo
.c
.write_JFIF_header
= /* Don't write extraneous markers */
890 sp
->cinfo
.c
.write_Adobe_marker
= FALSE
;
891 sp
->cinfo
.c
.image_width
= segment_width
;
892 sp
->cinfo
.c
.image_height
= segment_height
;
893 sp
->cinfo
.c
.comp_info
[0].h_samp_factor
=
894 sp
->cinfo
.c
.comp_info
[0].v_samp_factor
= 1;
895 return CALLVJPEG(sp
,jpeg_start_compress(&sp
->cinfo
.c
,FALSE
));
900 OJPEGPreEncode(register TIFF
*tif
,tsample_t s
)
901 { register OJPEGState
*sp
= OJState(tif
);
902 # define td (&tif->tif_dir)
904 /* If we are about to write the first row of an image plane, which should
905 coincide with a JPEG "scan", reset the JPEG Library's compressor. Otherwise
906 let the compressor run "as is" and return a "success" status without further
909 if ( (isTiled(tif
) ? tif
->tif_curtile
: tif
->tif_curstrip
)
910 % td
->td_stripsperimage
914 if ( (sp
->cinfo
.c
.comp_info
[0].component_id
= s
) == 1)
915 && sp
->cinfo
.c
.jpeg_color_space
== JCS_YCbCr
918 sp
->cinfo
.c
.comp_info
[0].quant_tbl_no
=
919 sp
->cinfo
.c
.comp_info
[0].dc_tbl_no
=
920 sp
->cinfo
.c
.comp_info
[0].ac_tbl_no
= 1;
921 sp
->cinfo
.c
.comp_info
[0].h_samp_factor
= sp
->h_sampling
;
922 sp
->cinfo
.c
.comp_info
[0].v_samp_factor
= sp
->v_sampling
;
924 /* Scale expected strip/tile size to match a downsampled component. */
926 sp
->cinfo
.c
.image_width
= TIFFhowmany(segment_width
,sp
->h_sampling
);
927 sp
->cinfo
.c
.image_height
=TIFFhowmany(segment_height
,sp
->v_sampling
);
929 sp
->scancount
= 0; /* Mark subsampling buffer(s) empty */
936 OJPEGPostEncode(register TIFF
*tif
)
937 { register OJPEGState
*sp
= OJState(tif
);
939 /* Finish up at the end of a strip or tile. */
941 if (sp
->scancount
> 0) /* emit partial buffer of down-sampled data */
944 # ifdef C_LOSSLESS_SUPPORTED
945 if ( sp
->scancount
< sp
->cinfo
.c
.data_unit
946 && sp
->cinfo
.c
.num_components
> 0
949 if (sp
->scancount
< DCTSIZE
&& sp
->cinfo
.c
.num_components
> 0)
951 { int ci
= 0, /* Pad the data vertically */
952 # ifdef C_LOSSLESS_SUPPORTED
953 size
= sp
->cinfo
.c
.data_unit
;
957 register jpeg_component_info
*compptr
= sp
->cinfo
.c
.comp_info
;
960 # ifdef C_LOSSLESS_SUPPORTED
961 { tsize_t row_width
= compptr
->width_in_data_units
963 tsize_t row_width
= compptr
->width_in_blocks
965 *size
*sizeof(JSAMPLE
);
966 int ypos
= sp
->scancount
*compptr
->v_samp_factor
;
968 do _TIFFmemcpy( (tdata_t
)sp
->ds_buffer
[ci
][ypos
]
969 , (tdata_t
)sp
->ds_buffer
[ci
][ypos
-1]
972 while (++ypos
< compptr
->v_samp_factor
*size
);
974 while (++compptr
,++ci
< sp
->cinfo
.c
.num_components
);
976 n
= sp
->cinfo
.c
.max_v_samp_factor
*size
;
977 if (CALLJPEG(sp
,-1,jpeg_write_raw_data(&sp
->cinfo
.c
,sp
->ds_buffer
,n
)) != n
)
980 return CALLVJPEG(sp
,jpeg_finish_compress(&sp
->cinfo
.c
));
984 /* JPEG Decoding begins here. */
986 /*ARGSUSED*/ static int
987 OJPEGDecode(register TIFF
*tif
,tidata_t buf
,tsize_t cc
,tsample_t s
)
988 { tsize_t bytesperline
= isTiled(tif
)
989 ? TIFFTileRowSize(tif
)
990 : tif
->tif_scanlinesize
,
991 rows
; /* No. of unprocessed rows in file */
992 register OJPEGState
*sp
= OJState(tif
);
994 /* Decode a chunk of pixels, where the input data has not NOT been down-
995 sampled, or else the TIFF Library's client has used the "JPEGColorMode" TIFF
996 pseudo-tag to request that the JPEG Library do color-space conversion; this
997 is the normal case. The data is expected to be read in scan-line multiples,
998 and this subroutine is called for both pixel-interleaved and separate color
1001 WARNING: Unlike "OJPEGDecodeRawContig()", below, the no. of Bytes in each
1002 decoded row is calculated here as "bytesperline" instead of
1003 using "sp->bytesperline", which might be a little smaller. This can
1004 occur for an old tiled image whose width isn't a multiple of 8 pixels.
1005 That's illegal according to the TIFF Version 6 specification, but some
1006 test files, like "zackthecat.tif", were built that way. In those cases,
1007 we want to embed the image's true width in our caller's buffer (which is
1008 presumably allocated according to the expected tile width) by
1009 effectively "padding" it with unused Bytes at the end of each row.
1011 if ( (cc
/= bytesperline
) /* No. of complete rows in caller's buffer */
1012 > (rows
= sp
->cinfo
.d
.output_height
- sp
->cinfo
.d
.output_scanline
)
1016 if ( CALLJPEG(sp
,-1,jpeg_read_scanlines(&sp
->cinfo
.d
,(JSAMPARRAY
)&buf
,1))
1019 buf
+= bytesperline
;
1023 /* BEWARE OF KLUDGE: If our input file was produced by Microsoft's Wang
1024 Imaging for Windows application, the DC coefficients of
1025 each JPEG image component (Y,Cb,Cr) must be reset at the end of each TIFF
1026 "strip", and any JPEG data bits remaining in the current Byte of the
1027 decoder's input buffer must be discarded. To do so, we create an "ad hoc"
1028 interface in the "jdhuff.c" module of IJG JPEG Library Version 6 (module
1029 "jdshuff.c", if Ken Murchison's lossless-Huffman patch is applied), and we
1030 invoke that interface here after decoding each "strip".
1032 if (sp
->is_WANG
) jpeg_reset_huff_decode(&sp
->cinfo
.d
);
1036 /*ARGSUSED*/ static int
1037 OJPEGDecodeRawContig(register TIFF
*tif
,tidata_t buf
,tsize_t cc
,tsample_t s
)
1038 { tsize_t rows
; /* No. of unprocessed rows in file */
1039 JDIMENSION lines_per_MCU
, size
;
1040 register OJPEGState
*sp
= OJState(tif
);
1042 /* Decode a chunk of pixels, where the input data has pixel-interleaved color
1043 planes, some of which have been down-sampled, but the TIFF Library's client
1044 has NOT used the "JPEGColorMode" TIFF pseudo-tag to request that the JPEG
1045 Library do color-space conversion. In other words, we must up-sample/
1046 expand/duplicate image components according to the image's sampling factors,
1047 without changing its color space. The data is expected to be read in scan-
1050 if ( (cc
/= sp
->bytesperline
) /* No. of complete rows in caller's buffer */
1051 > (rows
= sp
->cinfo
.d
.output_height
- sp
->cinfo
.d
.output_scanline
)
1053 lines_per_MCU
= sp
->cinfo
.d
.max_v_samp_factor
1054 # ifdef D_LOSSLESS_SUPPORTED
1055 * (size
= sp
->cinfo
.d
.min_codec_data_unit
);
1060 { int clumpoffset
, ci
;
1061 register jpeg_component_info
*compptr
;
1063 if (sp
->scancount
>= size
) /* reload downsampled-data buffers */
1065 if ( CALLJPEG(sp
,-1,jpeg_read_raw_data(&sp
->cinfo
.d
,sp
->ds_buffer
,lines_per_MCU
))
1071 /* The fastest way to separate the data is: make 1 pass over the scan
1072 line for each row of each component.
1074 clumpoffset
= ci
= 0;
1075 compptr
= sp
->cinfo
.d
.comp_info
;
1079 if (compptr
->h_samp_factor
== 1) /* fast path */
1081 { register JSAMPLE
*inptr
=
1082 sp
->ds_buffer
[ci
][sp
->scancount
*compptr
->v_samp_factor
+ypos
],
1083 *outptr
= (JSAMPLE
*)buf
+ clumpoffset
;
1084 register int clumps_per_line
= compptr
->downsampled_width
;
1086 do *outptr
= *inptr
++;
1087 while ((outptr
+= sp
->samplesperclump
),--clumps_per_line
> 0);
1089 while ( (clumpoffset
+= compptr
->h_samp_factor
)
1090 , ++ypos
< compptr
->v_samp_factor
1092 else /* general case */
1094 { register JSAMPLE
*inptr
=
1095 sp
->ds_buffer
[ci
][sp
->scancount
*compptr
->v_samp_factor
+ypos
],
1096 *outptr
= (JSAMPLE
*)buf
+ clumpoffset
;
1097 register int clumps_per_line
= compptr
->downsampled_width
;
1100 { register int xpos
= 0;
1102 do outptr
[xpos
] = *inptr
++;
1103 while (++xpos
< compptr
->h_samp_factor
);
1105 while ((outptr
+= sp
->samplesperclump
),--clumps_per_line
> 0);
1107 while ( (clumpoffset
+= compptr
->h_samp_factor
)
1108 , ++ypos
< compptr
->v_samp_factor
1111 while (++compptr
,++ci
< sp
->cinfo
.d
.num_components
);
1113 buf
+= sp
->bytesperline
;
1117 /* BEWARE OF KLUDGE: If our input file was produced by Microsoft's Wang
1118 Imaging for Windows application, the DC coefficients of
1119 each JPEG image component (Y,Cb,Cr) must be reset at the end of each TIFF
1120 "strip", and any JPEG data bits remaining in the current Byte of the
1121 decoder's input buffer must be discarded. To do so, we create an "ad hoc"
1122 interface in the "jdhuff.c" module of IJG JPEG Library Version 6 (module
1123 "jdshuff.c", if Ken Murchison's lossless-Huffman patch is applied), and we
1124 invoke that interface here after decoding each "strip".
1126 if (sp
->is_WANG
) jpeg_reset_huff_decode(&sp
->cinfo
.d
);
1130 /*ARGSUSED*/ static int
1131 OJPEGDecodeRawSeparate(TIFF
*tif
,register tidata_t buf
,tsize_t cc
,tsample_t s
)
1132 { tsize_t rows
; /* No. of unprocessed rows in file */
1133 JDIMENSION lines_per_MCU
,
1134 size
, /* ...of MCU */
1135 v
; /* Component's vertical up-sampling ratio */
1136 register OJPEGState
*sp
= OJState(tif
);
1137 register jpeg_component_info
*compptr
= sp
->cinfo
.d
.comp_info
+ s
;
1139 /* Decode a chunk of pixels, where the input data has separate color planes,
1140 some of which have been down-sampled, but the TIFF Library's client has NOT
1141 used the "JPEGColorMode" TIFF pseudo-tag to request that the JPEG Library
1142 do color-space conversion. The data is expected to be read in scan-line
1145 v
= sp
->cinfo
.d
.max_v_samp_factor
/compptr
->v_samp_factor
;
1146 if ( (cc
/= compptr
->downsampled_width
) /* No. of rows in caller's buffer */
1147 > (rows
= (sp
->cinfo
.d
.output_height
-sp
->cinfo
.d
.output_scanline
+v
-1)/v
)
1148 ) cc
= rows
; /* No. of rows of "clumps" to read */
1149 lines_per_MCU
= sp
->cinfo
.d
.max_v_samp_factor
1150 # ifdef D_LOSSLESS_SUPPORTED
1151 * (size
= sp
->cinfo
.d
.min_codec_data_unit
);
1155 L
: if (sp
->scancount
>= size
) /* reload downsampled-data buffers */
1157 if ( CALLJPEG(sp
,-1,jpeg_read_raw_data(&sp
->cinfo
.d
,sp
->ds_buffer
,lines_per_MCU
))
1164 { register JSAMPLE
*inptr
=
1165 sp
->ds_buffer
[s
][sp
->scancount
*compptr
->v_samp_factor
+ rows
];
1166 register int clumps_per_line
= compptr
->downsampled_width
;
1168 do *buf
++ = *inptr
++; while (--clumps_per_line
> 0); /* Copy scanline */
1170 if (--cc
<= 0) return 1; /* End of caller's buffer? */
1172 while (++rows
< compptr
->v_samp_factor
);
1177 /* "OJPEGSetupDecode()" temporarily forces the JPEG Library to use the following
1178 subroutine as a "dummy" input reader in order to fool the library into
1179 thinking that it has read the image's first "Start of Scan" (SOS) marker, so
1180 that it initializes accordingly.
1182 /*ARGSUSED*/ METHODDEF(int)
1183 fake_SOS_marker(j_decompress_ptr cinfo
){return JPEG_REACHED_SOS
;}
1185 /*ARGSUSED*/ METHODDEF(int)
1186 suspend(j_decompress_ptr cinfo
){return JPEG_SUSPENDED
;}
1188 /* The JPEG Library's "null" color-space converter actually re-packs separate
1189 color planes (it's native image representation) into a pixel-interleaved,
1190 contiguous plane. But if our TIFF Library client is tryng to process a
1191 PLANARCONFIG_SEPARATE image, we don't want that; so here are modifications of
1192 code in the JPEG Library's "jdcolor.c" file, which simply copy Bytes to a
1193 color plane specified by the current JPEG "scan".
1196 ycc_rgb_convert(register j_decompress_ptr cinfo
,JSAMPIMAGE in
,JDIMENSION row
,
1197 register JSAMPARRAY out
,register int nrows
)
1198 { typedef struct /* "jdcolor.c" color-space conversion state */
1201 /* WARNING: This declaration is ugly and dangerous! It's supposed to be
1202 private to the JPEG Library's "jdcolor.c" module, but we also
1203 need it here. Since the library's copy might change without notice, be
1204 sure to keep this one synchronized or the following code will break!
1206 struct jpeg_color_deconverter pub
; /* Public fields */
1207 /* Private state for YCC->RGB conversion */
1208 int *Cr_r_tab
, /* ->Cr to R conversion table */
1209 *Cb_b_tab
; /* ->Cb to B conversion table */
1210 INT32
*Cr_g_tab
, /* ->Cr to G conversion table */
1211 *Cb_g_tab
; /* ->Cb to G conversion table */
1213 my_cconvert_ptr cconvert
= (my_cconvert_ptr
)cinfo
->cconvert
;
1214 JSAMPARRAY irow0p
= in
[0] + row
;
1215 register JSAMPLE
*range_limit
= cinfo
->sample_range_limit
;
1216 register JSAMPROW outp
, Y
;
1218 switch (cinfo
->output_scan_number
- 1)
1219 { JSAMPARRAY irow1p
, irow2p
;
1220 register INT32
*table0
, *table1
;
1223 case RGB_RED
: irow2p
= in
[2] + row
;
1224 table0
= (INT32
*)cconvert
->Cr_r_tab
;
1225 while (--nrows
>= 0)
1226 { register JSAMPROW Cr
= *irow2p
++;
1227 register int i
= cinfo
->output_width
;
1232 *outp
++ = range_limit
[*Y
++ + table0
[*Cr
++]];
1235 case RGB_GREEN
: irow1p
= in
[1] + row
;
1236 irow2p
= in
[2] + row
;
1237 table0
= cconvert
->Cb_g_tab
;
1238 table1
= cconvert
->Cr_g_tab
;
1239 while (--nrows
>= 0)
1240 { register JSAMPROW Cb
= *irow1p
++,
1242 register int i
= cinfo
->output_width
;
1249 + RIGHT_SHIFT(table0
[*Cb
++]+table1
[*Cr
++],16)
1253 case RGB_BLUE
: irow1p
= in
[1] + row
;
1254 table0
= (INT32
*)cconvert
->Cb_b_tab
;
1255 while (--nrows
>= 0)
1256 { register JSAMPROW Cb
= *irow1p
++;
1257 register int i
= cinfo
->output_width
;
1262 *outp
++ = range_limit
[*Y
++ + table0
[*Cb
++]];
1268 null_convert(register j_decompress_ptr cinfo
,JSAMPIMAGE in
,JDIMENSION row
,
1269 register JSAMPARRAY out
,register int nrows
)
1270 { register JSAMPARRAY irowp
= in
[cinfo
->output_scan_number
- 1] + row
;
1272 while (--nrows
>= 0) _TIFFmemcpy(*out
++,*irowp
++,cinfo
->output_width
);
1276 OJPEGSetupDecode(register TIFF
*tif
)
1277 { static char module[]={"OJPEGSetupDecode"};
1278 J_COLOR_SPACE jpeg_color_space
, /* Color space of JPEG-compressed image */
1279 out_color_space
; /* Color space of decompressed image */
1280 uint32 segment_width
;
1281 int status
= 1; /* Assume success by default */
1282 boolean downsampled_output
=FALSE
, /* <=> Want JPEG Library's "raw" image? */
1283 is_JFIF
; /* <=> JFIF image? */
1284 register OJPEGState
*sp
= OJState(tif
);
1285 # define td (&tif->tif_dir)
1287 /* Verify miscellaneous parameters. This will need work if the TIFF Library
1288 ever supports different depths for different components, or if the JPEG
1289 Library ever supports run-time depth selection. Neither seems imminent.
1291 if (td
->td_bitspersample
!= sp
->cinfo
.d
.data_precision
)
1293 TIFFError(module,bad_bps
,td
->td_bitspersample
);
1297 /* The TIFF Version 6.0 specification and IJG JPEG Library accept different
1298 sets of color spaces, so verify that our image belongs to the common subset
1299 and map its photometry code, then initialize to handle subsampling and
1300 optional JPEG Library YCbCr <-> RGB color-space conversion.
1302 switch (td
->td_photometric
)
1304 case PHOTOMETRIC_YCBCR
:
1306 /* ISO IS 10918-1 requires that JPEG subsampling factors be 1-4, but
1307 TIFF Version 6.0 is more restrictive: only 1, 2, and 4 are allowed.
1309 if ( ( td
->td_ycbcrsubsampling
[0] == 1
1310 || td
->td_ycbcrsubsampling
[0] == 2
1311 || td
->td_ycbcrsubsampling
[0] == 4
1313 && ( td
->td_ycbcrsubsampling
[1] == 1
1314 || td
->td_ycbcrsubsampling
[1] == 2
1315 || td
->td_ycbcrsubsampling
[1] == 4
1318 downsampled_output
=
1320 (sp
->h_sampling
= td
->td_ycbcrsubsampling
[0]) << 3
1321 | (sp
->v_sampling
= td
->td_ycbcrsubsampling
[1])
1325 TIFFError(module,bad_subsampling
);
1328 jpeg_color_space
= JCS_YCbCr
;
1329 if (sp
->jpegcolormode
== JPEGCOLORMODE_RGB
)
1331 downsampled_output
= FALSE
;
1332 out_color_space
= JCS_RGB
;
1336 case PHOTOMETRIC_MINISBLACK
:
1337 jpeg_color_space
= JCS_GRAYSCALE
;
1339 case PHOTOMETRIC_RGB
:
1340 jpeg_color_space
= JCS_RGB
;
1342 case PHOTOMETRIC_SEPARATED
:
1343 jpeg_color_space
= JCS_CMYK
;
1344 L1
: sp
->jpegcolormode
= JPEGCOLORMODE_RAW
; /* No JPEG Lib. conversion */
1345 L2
: out_color_space
= jpeg_color_space
;
1348 TIFFError(module,bad_photometry
,td
->td_photometric
);
1351 if (status
== 0) return 0; /* If TIFF errors, don't bother to continue */
1353 /* Set parameters that are same for all strips/tiles. */
1355 sp
->cinfo
.d
.src
= &sp
->src
;
1356 sp
->src
.init_source
= std_init_source
;
1357 sp
->src
.fill_input_buffer
= std_fill_input_buffer
;
1358 sp
->src
.skip_input_data
= std_skip_input_data
;
1359 sp
->src
.resync_to_restart
= jpeg_resync_to_restart
;
1360 sp
->src
.term_source
= std_term_source
;
1362 /* BOGOSITY ALERT! The Wang Imaging application for Microsoft Windows produces
1363 images containing "JPEGInterchangeFormat[Length]" TIFF
1364 records that resemble JFIF-in-TIFF encapsulations but, in fact, violate the
1365 TIFF Version 6 specification in several ways; nevertheless, we try to handle
1366 them gracefully because there are apparently a lot of them around. The
1367 purported "JFIF" data stream in one of these files vaguely resembles a JPEG
1368 "tables only" data stream, except that there's no trailing EOI marker. The
1369 rest of the JPEG data stream lies in a discontiguous file region, identified
1370 by the 0th Strip offset (which is *also* illegal!), where it begins with an
1371 SOS marker and apparently continues to the end of the file. There is no
1372 trailing EOI marker here, either.
1374 is_JFIF
= !sp
->is_WANG
&& TIFFFieldSet(tif
,FIELD_JPEGIFOFFSET
);
1376 /* Initialize decompression parameters that won't be overridden by JPEG Library
1377 defaults set during the "jpeg_read_header()" call, below.
1379 segment_width
= td
->td_imagewidth
;
1382 if (sp
->is_WANG
) /* we don't know how to handle it */
1384 TIFFError(module,"Tiled Wang image not supported");
1388 /* BOGOSITY ALERT! "TIFFTileRowSize()" seems to work fine for modern JPEG-
1389 in-TIFF encapsulations where the image width--like the
1390 tile width--is a multiple of 8 or 16 pixels. But image widths and
1391 heights are aren't restricted to 8- or 16-bit multiples, and we need
1392 the exact Byte count of decompressed scan lines when we call the JPEG
1393 Library. At least one old file ("zackthecat.tif") in the TIFF Library
1394 test suite has widths and heights slightly less than the tile sizes, and
1395 it apparently used the bogus computation below to determine the number
1396 of Bytes per scan line (was this due to an old, broken version of
1397 "TIFFhowmany()"?). Before we get here, "OJPEGSetupDecode()" verified
1398 that our image uses 8-bit samples, so the following check appears to
1399 return the correct answer in all known cases tested to date.
1401 if (is_JFIF
|| (segment_width
& 7) == 0)
1402 sp
->bytesperline
= TIFFTileRowSize(tif
); /* Normal case */
1405 /* Was the file-encoder's segment-width calculation bogus? */
1406 segment_width
= (segment_width
/sp
->h_sampling
+ 1) * sp
->h_sampling
;
1407 sp
->bytesperline
= segment_width
* td
->td_samplesperpixel
;
1410 else sp
->bytesperline
= TIFFVStripSize(tif
,1);
1412 /* BEWARE OF KLUDGE: If we have JPEG Interchange File Format (JFIF) image,
1413 then we want to read "metadata" in the bit-stream's
1414 header and validate it against corresponding information in TIFF records.
1415 But if we have a *really old* JPEG file that's not JFIF, then we simply
1416 assign TIFF-record values to JPEG Library variables without checking.
1418 if (is_JFIF
) /* JFIF image */
1419 { unsigned char *end_of_data
;
1420 int subsampling_factors
;
1421 register unsigned char *p
;
1424 /* WARNING: Although the image file contains a JFIF bit stream, it might
1425 also contain some old TIFF records causing "OJPEGVSetField()"
1426 to have allocated quantization or Huffman decoding tables. But when the
1427 JPEG Library reads and parses the JFIF header below, it reallocate these
1428 tables anew without checking for "dangling" pointers, thereby causing a
1429 memory "leak". We have enough information to potentially deallocate the
1430 old tables here, but unfortunately JPEG Library Version 6B uses a "pool"
1431 allocator for small objects, with no deallocation procedure; instead, it
1432 reclaims a whole pool when an image is closed/destroyed, so well-behaved
1433 TIFF client applications (i.e., those which close their JPEG images as
1434 soon as they're no longer needed) will waste memory for a short time but
1435 recover it eventually. But ill-behaved TIFF clients (i.e., those which
1436 keep many JPEG images open gratuitously) can exhaust memory prematurely.
1437 If the JPEG Library ever implements a deallocation procedure, insert
1441 if (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
) /* free quant. tables */
1442 { register int i
= 0;
1445 { register JQUANT_TBL
*q
;
1447 if (q
= sp
->cinfo
.d
.quant_tbl_ptrs
[i
])
1449 jpeg_free_small(&sp
->cinfo
.comm
,q
,sizeof *q
);
1450 sp
->cinfo
.d
.quant_tbl_ptrs
[i
] = 0;
1453 while (++i
< NUM_QUANT_TBLS
);
1455 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
) /* free Huffman tables */
1456 { register int i
= 0;
1459 { register JHUFF_TBL
*h
;
1461 if (h
= sp
->cinfo
.d
.dc_huff_tbl_ptrs
[i
])
1463 jpeg_free_small(&sp
->cinfo
.comm
,h
,sizeof *h
);
1464 sp
->cinfo
.d
.dc_huff_tbl_ptrs
[i
] = 0;
1466 if (h
= sp
->cinfo
.d
.ac_huff_tbl_ptrs
[i
])
1468 jpeg_free_small(&sp
->cinfo
.comm
,h
,sizeof *h
);
1469 sp
->cinfo
.d
.ac_huff_tbl_ptrs
[i
] = 0;
1472 while (++i
< NUM_HUFF_TBLS
);
1474 # endif /* someday */
1476 /* Since we might someday wish to try rewriting "old format" JPEG-in-TIFF
1477 encapsulations in "new format" files, try to synthesize the value of a
1478 modern "JPEGTables" TIFF record by scanning the JPEG data from just past
1479 the "Start of Information" (SOI) marker until something other than a
1480 legitimate "table" marker is found, as defined in ISO IS 10918-1
1481 Appending B.2.4; namely:
1483 -- Define Quantization Table (DQT)
1484 -- Define Huffman Table (DHT)
1485 -- Define Arithmetic Coding table (DAC)
1486 -- Define Restart Interval (DRI)
1488 -- Application data (APPn)
1490 For convenience, we also accept "Expansion" (EXP) markers, although they
1491 are apparently not a part of normal "table" data.
1493 sp
->jpegtables
= p
= (unsigned char *)sp
->src
.next_input_byte
;
1494 end_of_data
= p
+ sp
->src
.bytes_in_buffer
;
1496 while (p
< end_of_data
&& p
[0] == 0xFF)
1500 case 0xC0: /* SOF0 */
1501 case 0xC1: /* SOF1 */
1502 case 0xC2: /* SOF2 */
1503 case 0xC3: /* SOF3 */
1504 case 0xC4: /* DHT */
1505 case 0xC5: /* SOF5 */
1506 case 0xC6: /* SOF6 */
1507 case 0xC7: /* SOF7 */
1508 case 0xC9: /* SOF9 */
1509 case 0xCA: /* SOF10 */
1510 case 0xCB: /* SOF11 */
1511 case 0xCC: /* DAC */
1512 case 0xCD: /* SOF13 */
1513 case 0xCE: /* SOF14 */
1514 case 0xCF: /* SOF15 */
1515 case 0xDB: /* DQT */
1516 case 0xDD: /* DRI */
1517 case 0xDF: /* EXP */
1518 case 0xE0: /* APP0 */
1519 case 0xE1: /* APP1 */
1520 case 0xE2: /* APP2 */
1521 case 0xE3: /* APP3 */
1522 case 0xE4: /* APP4 */
1523 case 0xE5: /* APP5 */
1524 case 0xE6: /* APP6 */
1525 case 0xE7: /* APP7 */
1526 case 0xE8: /* APP8 */
1527 case 0xE9: /* APP9 */
1528 case 0xEA: /* APP10 */
1529 case 0xEB: /* APP11 */
1530 case 0xEC: /* APP12 */
1531 case 0xED: /* APP13 */
1532 case 0xEE: /* APP14 */
1533 case 0xEF: /* APP15 */
1534 case 0xFE: /* COM */
1535 p
+= (p
[2] << 8 | p
[3]) + 2;
1537 L
: if (p
- (unsigned char *)sp
->jpegtables
> 2) /* fake "JPEGTables" */
1540 /* In case our client application asks, pretend that this image file
1541 contains a modern "JPEGTables" TIFF record by copying to a buffer
1542 the initial part of the JFIF bit-stream that we just scanned, from
1543 the SOI marker through the "metadata" tables, then append an EOI
1544 marker and flag the "JPEGTables" TIFF record as "present".
1546 sp
->jpegtables_length
= p
- (unsigned char*)sp
->jpegtables
+ 2;
1548 if (!(sp
->jpegtables
= _TIFFmalloc(sp
->jpegtables_length
)))
1550 TIFFError(module,no_jtable_space
);
1553 _TIFFmemcpy(sp
->jpegtables
,p
,sp
->jpegtables_length
-2);
1554 p
= (unsigned char *)sp
->jpegtables
+ sp
->jpegtables_length
;
1555 p
[-2] = 0xFF; p
[-1] = JPEG_EOI
; /* Append EOI marker */
1556 TIFFSetFieldBit(tif
,FIELD_JPEGTABLES
);
1557 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1559 else sp
->jpegtables
= 0; /* Don't simulate "JPEGTables" */
1560 if ( CALLJPEG(sp
,-1,jpeg_read_header(&sp
->cinfo
.d
,TRUE
))
1563 if ( sp
->cinfo
.d
.image_width
!= segment_width
1564 || sp
->cinfo
.d
.image_height
!= td
->td_imagelength
1567 TIFFError(module,"Improper JPEG strip/tile size");
1570 if (sp
->cinfo
.d
.num_components
!= td
->td_samplesperpixel
)
1572 TIFFError(module,"Improper JPEG component count");
1575 if (sp
->cinfo
.d
.data_precision
!= td
->td_bitspersample
)
1577 TIFFError(module,"Improper JPEG data precision");
1581 /* Check that JPEG image components all have the same subsampling factors
1582 declared (or defaulted) in the TIFF file, since TIFF Version 6.0 is more
1583 restrictive than JPEG: Only the 0th component may have horizontal and
1584 vertical subsampling factors other than <1,1>.
1586 subsampling_factors
= sp
->h_sampling
<< 3 | sp
->v_sampling
;
1590 if ( ( sp
->cinfo
.d
.comp_info
[i
].h_samp_factor
<< 3
1591 | sp
->cinfo
.d
.comp_info
[i
].v_samp_factor
1593 != subsampling_factors
1596 TIFFError(module,"Improper JPEG subsampling factors");
1599 subsampling_factors
= 011; /* Required for image components > 0 */
1601 while (++i
< sp
->cinfo
.d
.num_components
);
1603 else /* not JFIF image */
1604 { int (*save
)(j_decompress_ptr cinfo
) = sp
->cinfo
.d
.marker
->read_markers
;
1607 /* We're not assuming that this file's JPEG bit stream has any header
1608 "metadata", so fool the JPEG Library into thinking that we read a
1609 "Start of Input" (SOI) marker and a "Start of Frame" (SOFx) marker, then
1610 force it to read a simulated "Start of Scan" (SOS) marker when we call
1611 "jpeg_read_header()" below. This should cause the JPEG Library to
1612 establish reasonable defaults.
1614 sp
->cinfo
.d
.marker
->saw_SOI
= /* Pretend we saw SOI marker */
1615 sp
->cinfo
.d
.marker
->saw_SOF
= TRUE
; /* Pretend we saw SOF marker */
1616 sp
->cinfo
.d
.marker
->read_markers
=
1617 sp
->is_WANG
? suspend
: fake_SOS_marker
;
1618 sp
->cinfo
.d
.global_state
= DSTATE_INHEADER
;
1619 sp
->cinfo
.d
.Se
= DCTSIZE2
-1; /* Suppress JPEG Library warning */
1620 sp
->cinfo
.d
.image_width
= segment_width
;
1621 sp
->cinfo
.d
.image_height
= td
->td_imagelength
;
1623 /* The following color-space initialization, including the complicated
1624 "switch"-statement below, essentially duplicates the logic used by the
1625 JPEG Library's "jpeg_init_colorspace()" subroutine during compression.
1627 sp
->cinfo
.d
.num_components
= td
->td_samplesperpixel
;
1628 sp
->cinfo
.d
.comp_info
= (jpeg_component_info
*)
1629 (*sp
->cinfo
.d
.mem
->alloc_small
)
1632 , sp
->cinfo
.d
.num_components
* sizeof *sp
->cinfo
.d
.comp_info
1637 sp
->cinfo
.d
.comp_info
[i
].component_index
= i
;
1638 sp
->cinfo
.d
.comp_info
[i
].component_needed
= TRUE
;
1639 sp
->cinfo
.d
.cur_comp_info
[i
] = &sp
->cinfo
.d
.comp_info
[i
];
1641 while (++i
< sp
->cinfo
.d
.num_components
);
1642 switch (jpeg_color_space
)
1648 sp
->cinfo
.d
.comp_info
[i
].component_id
= i
;
1649 sp
->cinfo
.d
.comp_info
[i
].h_samp_factor
=
1650 sp
->cinfo
.d
.comp_info
[i
].v_samp_factor
= 1;
1652 while (++i
< sp
->cinfo
.d
.num_components
);
1655 sp
->cinfo
.d
.comp_info
[0].component_id
=
1656 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
=
1657 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
= 1;
1660 sp
->cinfo
.d
.comp_info
[0].component_id
= 'R';
1661 sp
->cinfo
.d
.comp_info
[1].component_id
= 'G';
1662 sp
->cinfo
.d
.comp_info
[2].component_id
= 'B';
1664 do sp
->cinfo
.d
.comp_info
[i
].h_samp_factor
=
1665 sp
->cinfo
.d
.comp_info
[i
].v_samp_factor
= 1;
1666 while (++i
< sp
->cinfo
.d
.num_components
);
1669 sp
->cinfo
.d
.comp_info
[0].component_id
= 'C';
1670 sp
->cinfo
.d
.comp_info
[1].component_id
= 'M';
1671 sp
->cinfo
.d
.comp_info
[2].component_id
= 'Y';
1672 sp
->cinfo
.d
.comp_info
[3].component_id
= 'K';
1674 do sp
->cinfo
.d
.comp_info
[i
].h_samp_factor
=
1675 sp
->cinfo
.d
.comp_info
[i
].v_samp_factor
= 1;
1676 while (++i
< sp
->cinfo
.d
.num_components
);
1682 sp
->cinfo
.d
.comp_info
[i
].component_id
= i
+1;
1683 sp
->cinfo
.d
.comp_info
[i
].h_samp_factor
=
1684 sp
->cinfo
.d
.comp_info
[i
].v_samp_factor
= 1;
1685 sp
->cinfo
.d
.comp_info
[i
].quant_tbl_no
=
1686 sp
->cinfo
.d
.comp_info
[i
].dc_tbl_no
=
1687 sp
->cinfo
.d
.comp_info
[i
].ac_tbl_no
= i
> 0;
1689 while (++i
< sp
->cinfo
.d
.num_components
);
1690 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
= sp
->h_sampling
;
1691 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
= sp
->v_sampling
;
1693 sp
->cinfo
.d
.comps_in_scan
= td
->td_planarconfig
== PLANARCONFIG_CONTIG
1694 ? sp
->cinfo
.d
.num_components
1696 i
= CALLJPEG(sp
,-1,jpeg_read_header(&sp
->cinfo
.d
,!sp
->is_WANG
));
1697 sp
->cinfo
.d
.marker
->read_markers
= save
; /* Restore input method */
1698 if (sp
->is_WANG
) /* produced by Wang Imaging on Microsoft Windows */
1700 if (i
!= JPEG_SUSPENDED
) return 0;
1702 /* BOGOSITY ALERT! Files prooduced by the Wang Imaging application for
1703 Microsoft Windows are a special--and, technically
1704 illegal--case. A JPEG SOS marker and rest of the data stream should
1705 be located at the end of the file, in a position identified by the
1708 i
= td
->td_nstrips
- 1;
1709 sp
->src
.next_input_byte
= tif
->tif_base
+ td
->td_stripoffset
[0];
1710 sp
->src
.bytes_in_buffer
= td
->td_stripoffset
[i
] -
1711 td
->td_stripoffset
[0] + td
->td_stripbytecount
[i
];
1712 i
= CALLJPEG(sp
,-1,jpeg_read_header(&sp
->cinfo
.d
,TRUE
));
1714 if (i
!= JPEG_HEADER_OK
) return 0;
1717 /* Some of our initialization must wait until the JPEG Library is initialized
1718 above, in order to override its defaults.
1720 if ( (sp
->cinfo
.d
.raw_data_out
= downsampled_output
)
1721 && !alloc_downsampled_buffers(tif
,sp
->cinfo
.d
.comp_info
,
1722 sp
->cinfo
.d
.num_components
)
1724 sp
->cinfo
.d
.jpeg_color_space
= jpeg_color_space
;
1725 sp
->cinfo
.d
.out_color_space
= out_color_space
;
1726 sp
->cinfo
.d
.dither_mode
= JDITHER_NONE
; /* Reduce image "noise" */
1727 sp
->cinfo
.d
.two_pass_quantize
= FALSE
;
1729 /* If the image consists of separate, discontiguous TIFF "samples" (= color
1730 planes, hopefully = JPEG "scans"), then we must use the JPEG Library's
1731 "buffered image" mode to decompress the entire image into temporary buffers,
1732 because the JPEG Library must parse the entire JPEG bit-stream in order to
1733 be satsified that it has a complete set of color components for each pixel,
1734 but the TIFF Library must allow our client to extract 1 component at a time.
1735 Initializing the JPEG Library's "buffered image" mode is tricky: First, we
1736 start its decompressor, then we tell the decompressor to "consume" (i.e.,
1737 buffer) the entire bit-stream.
1739 WARNING: Disabling "fancy" up-sampling seems to slightly reduce "noise" for
1740 certain old Wang Imaging files, but it absolutely *must* be
1741 enabled if the image has separate color planes, since in that case, the JPEG
1742 Library doesn't use an "sp->cinfo.d.cconvert" structure (so de-referencing
1743 this pointer below will cause a fatal crash) but writing our own code to up-
1744 sample separate color planes is too much work for right now. Maybe someday?
1746 sp
->cinfo
.d
.do_fancy_upsampling
= /* Always let this default (to TRUE)? */
1747 sp
->cinfo
.d
.buffered_image
= td
->td_planarconfig
== PLANARCONFIG_SEPARATE
;
1748 if (!CALLJPEG(sp
,0,jpeg_start_decompress(&sp
->cinfo
.d
))) return 0;
1749 if (sp
->cinfo
.d
.buffered_image
) /* separate color planes */
1751 if (sp
->cinfo
.d
.raw_data_out
)
1752 tif
->tif_decoderow
= tif
->tif_decodestrip
= tif
->tif_decodetile
=
1753 OJPEGDecodeRawSeparate
;
1756 tif
->tif_decoderow
= tif
->tif_decodestrip
= tif
->tif_decodetile
=
1759 /* In JPEG Library Version 6B, color-space conversion isn't implemented
1760 for separate color planes, so we must do it ourself if our TIFF
1761 client doesn't want to:
1763 sp
->cinfo
.d
.cconvert
->color_convert
=
1764 sp
->cinfo
.d
.jpeg_color_space
== sp
->cinfo
.d
.out_color_space
1765 ? null_convert
: ycc_rgb_convert
;
1767 L3
: switch (CALLJPEG(sp
,0,jpeg_consume_input(&sp
->cinfo
.d
)))
1771 /* If no JPEG "End of Information" (EOI) marker is found when bit-
1772 stream parsing ends, check whether we have enough data to proceed
1773 before reporting an error.
1775 case JPEG_SUSPENDED
: if ( sp
->cinfo
.d
.input_scan_number
1776 *sp
->cinfo
.d
.image_height
1777 + sp
->cinfo
.d
.input_iMCU_row
1778 *sp
->cinfo
.d
.max_v_samp_factor
1779 # ifdef D_LOSSLESS_SUPPORTED
1780 *sp
->cinfo
.d
.data_units_in_MCU
1781 *sp
->cinfo
.d
.min_codec_data_unit
1783 *sp
->cinfo
.d
.blocks_in_MCU
1786 < td
->td_samplesperpixel
1787 *sp
->cinfo
.d
.image_height
1790 TIFFError(tif
->tif_name
,
1791 "Premature end of JPEG bit-stream");
1794 case JPEG_REACHED_EOI
: ;
1797 else /* pixel-interleaved color planes */
1798 tif
->tif_decoderow
= tif
->tif_decodestrip
= tif
->tif_decodetile
=
1799 downsampled_output
? OJPEGDecodeRawContig
: OJPEGDecode
;
1805 OJPEGPreDecode(register TIFF
*tif
,tsample_t s
)
1806 { register OJPEGState
*sp
= OJState(tif
);
1807 # define td (&tif->tif_dir)
1809 /* If we are about to read the first row of an image plane (hopefully, these
1810 are coincident with JPEG "scans"!), reset the JPEG Library's decompressor
1811 appropriately. Otherwise, let the decompressor run "as is" and return a
1812 "success" status without further ado.
1814 if ( (isTiled(tif
) ? tif
->tif_curtile
: tif
->tif_curstrip
)
1815 % td
->td_stripsperimage
1819 if ( sp
->cinfo
.d
.buffered_image
1820 && !CALLJPEG(sp
,0,jpeg_start_output(&sp
->cinfo
.d
,s
+1))
1822 sp
->cinfo
.d
.output_scanline
= 0;
1824 /* Mark subsampling buffers "empty". */
1826 # ifdef D_LOSSLESS_SUPPORTED
1827 sp
->scancount
= sp
->cinfo
.d
.min_codec_data_unit
;
1829 sp
->scancount
= DCTSIZE
;
1836 /*ARGSUSED*/ static void
1837 OJPEGPostDecode(register TIFF
*tif
,tidata_t buf
,tsize_t cc
)
1838 { register OJPEGState
*sp
= OJState(tif
);
1839 # define td (&tif->tif_dir)
1841 /* The JPEG Library decompressor has reached the end of a strip/tile. If this
1842 is the end of a TIFF image "sample" (= JPEG "scan") in a file with separate
1843 components (color planes), then end the "scan". If it ends the image's last
1844 sample/scan, then also stop the JPEG Library's decompressor.
1846 if (sp
->cinfo
.d
.output_scanline
>= sp
->cinfo
.d
.output_height
)
1848 if (sp
->cinfo
.d
.buffered_image
)
1849 CALLJPEG(sp
,-1,jpeg_finish_output(&sp
->cinfo
.d
)); /* End JPEG scan */
1850 if ( (isTiled(tif
) ? tif
->tif_curtile
: tif
->tif_curstrip
)
1852 ) CALLJPEG(sp
,0,jpeg_finish_decompress(&sp
->cinfo
.d
));
1858 OJPEGVSetField(register TIFF
*tif
,ttag_t tag
,va_list ap
)
1861 register OJPEGState
*sp
= OJState(tif
);
1862 # define td (&tif->tif_dir)
1865 uint32 code_count
=0;
1872 /* If a "ReferenceBlackWhite" TIFF tag appears in the file explicitly, undo
1873 any modified default definition that we might have installed below, then
1874 install the real one.
1876 case TIFFTAG_REFERENCEBLACKWHITE
: if (td
->td_refblackwhite
)
1878 _TIFFfree(td
->td_refblackwhite
);
1879 td
->td_refblackwhite
= 0;
1882 (*sp
->vsetparent
)(tif
,tag
,ap
);
1884 /* BEWARE OF KLUDGE: Some old-format JPEG-in-TIFF files, including those
1885 produced by the Wang Imaging application for Micro-
1886 soft Windows, illegally omit a "ReferenceBlackWhite" TIFF tag, even
1887 though the TIFF specification's default is intended for the RGB color
1888 space and is inappropriate for the YCbCr color space ordinarily used for
1889 JPEG images. Since many TIFF client applications request the value of
1890 this tag immediately after a TIFF image directory is parsed, and before
1891 any other code in this module receives control, we are forced to fix
1892 this problem very early in image-file processing. Fortunately, legal
1893 TIFF files are supposed to store their tags in numeric order, so a
1894 mandatory "PhotometricInterpretation" tag should always appear before
1895 an optional "ReferenceBlackWhite" tag. Hence, we slyly peek ahead when
1896 we discover the desired photometry, by installing modified black and
1897 white reference levels.
1899 case TIFFTAG_PHOTOMETRIC
:
1900 if ( (v32
= (*sp
->vsetparent
)(tif
,tag
,ap
))
1901 && td
->td_photometric
== PHOTOMETRIC_YCBCR
1904 if ( (td
->td_refblackwhite
= _TIFFmalloc(6*sizeof(float))) )
1905 { register long top
= 1 << td
->td_bitspersample
;
1907 td
->td_refblackwhite
[0] = 0;
1908 td
->td_refblackwhite
[1] = td
->td_refblackwhite
[3] =
1909 td
->td_refblackwhite
[5] = top
- 1;
1910 td
->td_refblackwhite
[2] = td
->td_refblackwhite
[4] = top
>> 1;
1914 TIFFError(tif
->tif_name
,
1915 "Cannot set default reference black and white levels");
1921 /* BEWARE OF KLUDGE: According to Charles Auer <Bumble731@msn.com>, if our
1922 input is a multi-image (multi-directory) JPEG-in-TIFF
1923 file is produced by the Wang Imaging application on Microsoft Windows,
1924 for some reason the first directory excludes the vendor-specific "WANG
1925 PageControl" tag (32934) that we check below, so the only other way to
1926 identify these directories is apparently to look for a software-
1927 identification tag with the substring, "Wang Labs". Single-image files
1928 can apparently pass both tests, which causes no harm here, but what a
1931 case TIFFTAG_SOFTWARE
:
1935 v32
= (*sp
->vsetparent
)(tif
,tag
,ap
);
1936 if( TIFFGetField( tif
, TIFFTAG_SOFTWARE
, &software
)
1937 && strstr( software
, "Wang Labs" ) )
1942 case TIFFTAG_JPEGPROC
:
1943 case TIFFTAG_JPEGIFOFFSET
:
1944 case TIFFTAG_JPEGIFBYTECOUNT
:
1945 case TIFFTAG_JPEGRESTARTINTERVAL
:
1946 case TIFFTAG_JPEGLOSSLESSPREDICTORS
:
1947 case TIFFTAG_JPEGPOINTTRANSFORM
:
1948 case TIFFTAG_JPEGQTABLES
:
1949 case TIFFTAG_JPEGDCTABLES
:
1950 case TIFFTAG_JPEGACTABLES
:
1951 case TIFFTAG_WANG_PAGECONTROL
:
1952 case TIFFTAG_JPEGCOLORMODE
: ;
1954 v32
= va_arg(ap
,uint32
); /* No. of values in this TIFF record */
1956 /* This switch statement is added for OJPEGVSetField */
1959 case TIFFTAG_JPEGPROC
:
1962 case TIFFTAG_JPEGIFOFFSET
:
1963 sp
->jpegifoffset
=v32
;
1965 case TIFFTAG_JPEGIFBYTECOUNT
:
1966 sp
->jpegifbytecount
=v32
;
1968 case TIFFTAG_JPEGRESTARTINTERVAL
:
1969 sp
->jpegrestartinterval
=v32
;
1971 case TIFFTAG_JPEGLOSSLESSPREDICTORS
:
1972 sp
->jpeglosslesspredictors_length
=v32
;
1974 case TIFFTAG_JPEGPOINTTRANSFORM
:
1975 sp
->jpegpointtransform_length
=v32
;
1977 case TIFFTAG_JPEGQTABLES
:
1978 sp
->jpegqtables_length
=v32
;
1980 case TIFFTAG_JPEGACTABLES
:
1981 sp
->jpegactables_length
=v32
;
1983 case TIFFTAG_JPEGDCTABLES
:
1984 sp
->jpegdctables_length
=v32
;
1991 /* BEWARE: The following actions apply only if we are reading a "source" TIFF
1992 image to be decompressed for a client application program. If we
1993 ever enhance this file's CODEC to write "destination" JPEG-in-TIFF images,
1994 we'll need an "if"- and another "switch"-statement below, because we'll
1995 probably want to store these records' values in some different places. Most
1996 of these need not be parsed here in order to decode JPEG bit stream, so we
1997 set boolean flags to note that they have been seen, but we otherwise ignore
2003 /* Validate the JPEG-process code. */
2005 case TIFFTAG_JPEGPROC
:
2008 default : TIFFError(tif
->tif_name
,
2009 "Unknown JPEG process");
2011 # ifdef C_LOSSLESS_SUPPORTED
2013 /* Image uses (lossy) baseline sequential coding. */
2015 case JPEGPROC_BASELINE
: sp
->cinfo
.d
.process
= JPROC_SEQUENTIAL
;
2016 sp
->cinfo
.d
.data_unit
= DCTSIZE
;
2019 /* Image uses (lossless) Huffman coding. */
2021 case JPEGPROC_LOSSLESS
: sp
->cinfo
.d
.process
= JPROC_LOSSLESS
;
2022 sp
->cinfo
.d
.data_unit
= 1;
2023 # else /* not C_LOSSLESS_SUPPORTED */
2024 case JPEGPROC_LOSSLESS
: TIFFError(JPEGLib_name
,
2025 "Does not support lossless Huffman coding");
2027 case JPEGPROC_BASELINE
: ;
2028 # endif /* C_LOSSLESS_SUPPORTED */
2032 /* The TIFF Version 6.0 specification says that if the value of a TIFF
2033 "JPEGInterchangeFormat" record is 0, then we are to behave as if this
2034 record were absent; i.e., the data does *not* represent a JPEG Inter-
2035 change Format File (JFIF), so don't even set the boolean "I've been
2036 here" flag below. Otherwise, the field's value represents the file
2037 offset of the JPEG SOI marker.
2039 case TIFFTAG_JPEGIFOFFSET
:
2042 sp
->src
.next_input_byte
= tif
->tif_base
+ v32
;
2046 case TIFFTAG_JPEGIFBYTECOUNT
:
2047 sp
->src
.bytes_in_buffer
= v32
;
2050 /* The TIFF Version 6.0 specification says that if the JPEG "Restart"
2051 marker interval is 0, then the data has no "Restart" markers; i.e., we
2052 must behave as if this TIFF record were absent. So, don't even set the
2053 boolean "I've been here" flag below.
2056 * Instead, set the field bit so TIFFGetField can get whether or not
2059 case TIFFTAG_JPEGRESTARTINTERVAL
:
2061 sp
->cinfo
.d
.restart_interval
= v32
;
2063 /* The TIFF Version 6.0 specification says that this tag is supposed to be
2064 a vector containing a value for each image component, but for lossless
2065 Huffman coding (the only JPEG process defined by the specification for
2066 which this tag should be needed), ISO IS 10918-1 uses only a single
2067 value, equivalent to the "Ss" field in a JPEG bit-stream's "Start of
2068 Scan" (SOS) marker. So, we extract the first vector element and ignore
2069 the rest. (I hope this is correct!)
2071 case TIFFTAG_JPEGLOSSLESSPREDICTORS
:
2074 sp
->cinfo
.d
.Ss
= *va_arg(ap
,uint16
*);
2075 sp
->jpeglosslesspredictors
=
2076 _TIFFmalloc(sp
->jpeglosslesspredictors_length
2078 if(sp
->jpeglosslesspredictors
==NULL
){return(0);}
2079 for(i2
=0;i2
<sp
->jpeglosslesspredictors_length
;i2
++){
2080 ((uint16
*)sp
->jpeglosslesspredictors
)[i2
] =
2081 ((uint16
*)sp
->cinfo
.d
.Ss
)[i2
];
2083 sp
->jpeglosslesspredictors_length
*=sizeof(uint16
);
2088 /* The TIFF Version 6.0 specification says that this tag is supposed to be
2089 a vector containing a value for each image component, but for lossless
2090 Huffman coding (the only JPEG process defined by the specification for
2091 which this tag should be needed), ISO IS 10918-1 uses only a single
2092 value, equivalent to the "Al" field in a JPEG bit-stream's "Start of
2093 Scan" (SOS) marker. So, we extract the first vector element and ignore
2094 the rest. (I hope this is correct!)
2096 case TIFFTAG_JPEGPOINTTRANSFORM
:
2099 sp
->cinfo
.d
.Al
= *va_arg(ap
,uint16
*);
2100 sp
->jpegpointtransform
=
2101 _TIFFmalloc(sp
->jpegpointtransform_length
*sizeof(uint16
));
2102 if(sp
->jpegpointtransform
==NULL
){return(0);}
2103 for(i2
=0;i2
<sp
->jpegpointtransform_length
;i2
++) {
2104 ((uint16
*)sp
->jpegpointtransform
)[i2
] =
2105 ((uint16
*)sp
->cinfo
.d
.Al
)[i2
];
2107 sp
->jpegpointtransform_length
*=sizeof(uint16
);
2112 /* We have a vector of offsets to quantization tables, so load 'em! */
2114 case TIFFTAG_JPEGQTABLES
:
2118 if (v32
> NUM_QUANT_TBLS
)
2120 TIFFError(tif
->tif_name
,"Too many quantization tables");
2124 v
= va_arg(ap
,uint32
*);
2125 sp
->jpegqtables
=_TIFFmalloc(64*sp
->jpegqtables_length
);
2126 if(sp
->jpegqtables
==NULL
){return(0);}
2127 tiffoff
= TIFFSeekFile(tif
, 0, SEEK_CUR
);
2129 for(i2
=0;i2
<sp
->jpegqtables_length
;i2
++){
2130 TIFFSeekFile(tif
, v
[i2
], SEEK_SET
);
2131 TIFFReadFile(tif
, &(((u_char
*)(sp
->jpegqtables
))[bufoff
]),
2135 sp
->jpegqtables_length
=bufoff
;
2136 TIFFSeekFile(tif
, tiffoff
, SEEK_SET
);
2138 do /* read quantization table */
2139 { register UINT8
*from
= tif
->tif_base
+ *v
++;
2140 register UINT16
*to
;
2141 register int j
= DCTSIZE2
;
2143 if (!( sp
->cinfo
.d
.quant_tbl_ptrs
[i
]
2144 = CALLJPEG(sp
,0,jpeg_alloc_quant_table(&sp
->cinfo
.comm
))
2148 TIFFError(JPEGLib_name
,"No space for quantization table");
2151 to
= sp
->cinfo
.d
.quant_tbl_ptrs
[i
]->quantval
;
2152 do *to
++ = *from
++; while (--j
> 0);
2155 sp
->jpegtablesmode
|= JPEGTABLESMODE_QUANT
;
2159 /* We have a vector of offsets to DC Huffman tables, so load 'em! */
2161 case TIFFTAG_JPEGDCTABLES
:
2162 h
= sp
->cinfo
.d
.dc_huff_tbl_ptrs
;
2165 /* We have a vector of offsets to AC Huffman tables, so load 'em! */
2167 case TIFFTAG_JPEGACTABLES
:
2168 h
= sp
->cinfo
.d
.ac_huff_tbl_ptrs
;
2172 if (v32
> NUM_HUFF_TBLS
)
2174 TIFFError(tif
->tif_name
,"Too many Huffman tables");
2177 v
= va_arg(ap
,uint32
*);
2178 if(tag
== TIFFTAG_JPEGDCTABLES
) {
2179 sp
->jpegdctables
=_TIFFmalloc(272*sp
->jpegdctables_length
);
2180 if(sp
->jpegdctables
==NULL
){return(0);}
2181 tiffoff
= TIFFSeekFile(tif
, 0, SEEK_CUR
);
2184 for(i2
=0;i2
<sp
->jpegdctables_length
;i2
++){
2185 TIFFSeekFile(tif
, v
[i2
], SEEK_SET
);
2187 &(((u_char
*)(sp
->jpegdctables
))[bufoff
]),
2190 for(k2
=0;k2
<16;k2
++){
2191 code_count
+=((u_char
*)(sp
->jpegdctables
))[k2
+bufoff
];
2194 &(((u_char
*)(sp
->jpegdctables
))[bufoff
+16]),
2199 sp
->jpegdctables_length
=bufoff
;
2200 TIFFSeekFile(tif
, tiffoff
, SEEK_SET
);
2202 if(tag
==TIFFTAG_JPEGACTABLES
){
2203 sp
->jpegactables
=_TIFFmalloc(272*sp
->jpegactables_length
);
2204 if(sp
->jpegactables
==NULL
){return(0);}
2205 tiffoff
= TIFFSeekFile(tif
, 0, SEEK_CUR
);
2208 for(i2
=0;i2
<sp
->jpegactables_length
;i2
++){
2209 TIFFSeekFile(tif
, v
[i2
], SEEK_SET
);
2210 TIFFReadFile(tif
, &(((unsigned char*)(sp
->jpegactables
))[bufoff
]), 16);
2212 for(k2
=0;k2
<16;k2
++){
2213 code_count
+=((unsigned char*)(sp
->jpegactables
))[k2
+bufoff
];
2215 TIFFReadFile(tif
, &(((unsigned char*)(sp
->jpegactables
))[bufoff
+16]), code_count
);
2219 sp
->jpegactables_length
=bufoff
;
2220 TIFFSeekFile(tif
, tiffoff
, SEEK_SET
);
2223 do /* copy each Huffman table */
2225 register UINT8
*from
= tif
->tif_base
+ *v
++, *to
;
2226 register int j
= sizeof (*h
)->bits
;
2228 /* WARNING: This code relies on the fact that an image file not
2229 "memory mapped" was read entirely into a single
2230 buffer by "TIFFInitOJPEG()", so we can do a fast memory-to-
2231 memory copy here. Each table consists of 16 Bytes, which are
2232 suffixed to a 0 Byte when copied, followed by a variable
2233 number of Bytes whose length is the sum of the first 16.
2236 = CALLJPEG(sp
,0,jpeg_alloc_huff_table(&sp
->cinfo
.comm
))
2240 TIFFError(JPEGLib_name
,"No space for Huffman table");
2245 while (--j
> 0) size
+= *to
++ = *from
++; /* Copy 16 Bytes */
2246 if (size
> sizeof (*h
)->huffval
/sizeof *(*h
)->huffval
)
2248 TIFFError(tif
->tif_name
,"Huffman table too big");
2251 if ((j
= size
) > 0) do *to
++ = *from
++; while (--j
> 0);
2252 while (++size
<= sizeof (*h
)->huffval
/sizeof *(*h
)->huffval
)
2253 *to
++ = 0; /* Zero the rest of the table for cleanliness */
2256 sp
->jpegtablesmode
|= JPEGTABLESMODE_HUFF
;
2260 /* The following vendor-specific TIFF tag occurs in (highly illegal) files
2261 produced by the Wang Imaging application for Microsoft Windows. These
2262 can apparently have several "pages", in which case this tag specifies
2263 the offset of a "page control" structure, which we don't currently know
2264 how to handle. 0 indicates a 1-page image with no "page control", which
2265 we make a feeble effort to handle.
2267 case TIFFTAG_WANG_PAGECONTROL
:
2268 if (v32
== 0) v32
= -1;
2270 tag
= TIFFTAG_JPEGPROC
+FIELD_WANG_PAGECONTROL
-FIELD_JPEGPROC
;
2273 /* This pseudo tag indicates whether our caller is expected to do YCbCr <->
2274 RGB color-space conversion (JPEGCOLORMODE_RAW <=> 0) or whether we must
2275 ask the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1).
2277 case TIFFTAG_JPEGCOLORMODE
:
2278 sp
->jpegcolormode
= v32
;
2280 /* Mark the image to indicate whether returned data is up-sampled, so
2281 that "TIFF{Strip,Tile}Size()" reflect the true amount of data present.
2283 v32
= tif
->tif_flags
; /* Save flags temporarily */
2284 tif
->tif_flags
&= ~TIFF_UPSAMPLED
;
2285 if ( td
->td_photometric
== PHOTOMETRIC_YCBCR
2286 && (td
->td_ycbcrsubsampling
[0]<<3 | td
->td_ycbcrsubsampling
[1])
2288 && sp
->jpegcolormode
== JPEGCOLORMODE_RGB
2289 ) tif
->tif_flags
|= TIFF_UPSAMPLED
;
2291 /* If the up-sampling state changed, re-calculate tile size. */
2293 if ((tif
->tif_flags
^ v32
) & TIFF_UPSAMPLED
)
2295 tif
->tif_tilesize
= TIFFTileSize(tif
);
2296 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
2300 TIFFSetFieldBit(tif
,tag
-TIFFTAG_JPEGPROC
+FIELD_JPEGPROC
);
2306 OJPEGVGetField(register TIFF
*tif
,ttag_t tag
,va_list ap
)
2307 { register OJPEGState
*sp
= OJState(tif
);
2312 /* If this file has managed to synthesize a set of consolidated "metadata"
2313 tables for the current (post-TIFF Version 6.0 specification) JPEG-in-
2314 TIFF encapsulation strategy, then tell our caller about them; otherwise,
2317 case TIFFTAG_JPEGTABLES
:
2318 if (sp
->jpegtables_length
) /* we have "new"-style JPEG tables */
2320 *va_arg(ap
,uint32
*) = sp
->jpegtables_length
;
2321 *va_arg(ap
,char **) = sp
->jpegtables
;
2325 /* This pseudo tag indicates whether our caller is expected to do YCbCr <->
2326 RGB color-space conversion (JPEGCOLORMODE_RAW <=> 0) or whether we must
2327 ask the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1).
2329 case TIFFTAG_JPEGCOLORMODE
:
2330 *va_arg(ap
,uint32
*) = sp
->jpegcolormode
;
2333 /* The following tags are defined by the TIFF Version 6.0 specification
2334 and are obsolete. If our caller asks for information about them, do not
2335 return anything, even if we parsed them in an old-format "source" image.
2337 case TIFFTAG_JPEGPROC
:
2338 *va_arg(ap
, uint16
*)=sp
->jpegproc
;
2341 case TIFFTAG_JPEGIFOFFSET
:
2342 *va_arg(ap
, uint32
*)=sp
->jpegifoffset
;
2345 case TIFFTAG_JPEGIFBYTECOUNT
:
2346 *va_arg(ap
, uint32
*)=sp
->jpegifbytecount
;
2349 case TIFFTAG_JPEGRESTARTINTERVAL
:
2350 *va_arg(ap
, uint32
*)=sp
->jpegrestartinterval
;
2353 case TIFFTAG_JPEGLOSSLESSPREDICTORS
:
2354 *va_arg(ap
, uint32
*)=sp
->jpeglosslesspredictors_length
;
2355 *va_arg(ap
, void**)=sp
->jpeglosslesspredictors
;
2358 case TIFFTAG_JPEGPOINTTRANSFORM
:
2359 *va_arg(ap
, uint32
*)=sp
->jpegpointtransform_length
;
2360 *va_arg(ap
, void**)=sp
->jpegpointtransform
;
2363 case TIFFTAG_JPEGQTABLES
:
2364 *va_arg(ap
, uint32
*)=sp
->jpegqtables_length
;
2365 *va_arg(ap
, void**)=sp
->jpegqtables
;
2368 case TIFFTAG_JPEGDCTABLES
:
2369 *va_arg(ap
, uint32
*)=sp
->jpegdctables_length
;
2370 *va_arg(ap
, void**)=sp
->jpegdctables
;
2373 case TIFFTAG_JPEGACTABLES
:
2374 *va_arg(ap
, uint32
*)=sp
->jpegactables_length
;
2375 *va_arg(ap
, void**)=sp
->jpegactables
;
2379 return (*sp
->vgetparent
)(tif
,tag
,ap
);
2383 OJPEGPrintDir(register TIFF
*tif
,FILE *fd
,long flags
)
2384 { register OJPEGState
*sp
= OJState(tif
);
2387 & (TIFFPRINT_JPEGQTABLES
|TIFFPRINT_JPEGDCTABLES
|TIFFPRINT_JPEGACTABLES
)
2389 && sp
->jpegtables_length
2391 fprintf(fd
," JPEG Table Data: <present>, %lu bytes\n",
2392 sp
->jpegtables_length
);
2396 OJPEGDefaultStripSize(register TIFF
*tif
,register uint32 s
)
2397 { register OJPEGState
*sp
= OJState(tif
);
2398 # define td (&tif->tif_dir)
2400 if ((s
= (*sp
->defsparent
)(tif
,s
)) < td
->td_imagelength
)
2401 { register tsize_t size
= sp
->cinfo
.comm
.is_decompressor
2402 # ifdef D_LOSSLESS_SUPPORTED
2403 ? sp
->cinfo
.d
.min_codec_data_unit
2407 # ifdef C_LOSSLESS_SUPPORTED
2408 : sp
->cinfo
.c
.data_unit
;
2413 size
= TIFFroundup(size
,16);
2414 s
= TIFFroundup(s
,td
->td_ycbcrsubsampling
[1]*size
);
2421 OJPEGDefaultTileSize(register TIFF
*tif
,register uint32
*tw
,register uint32
*th
)
2422 { register OJPEGState
*sp
= OJState(tif
);
2423 register tsize_t size
;
2424 # define td (&tif->tif_dir)
2426 size
= sp
->cinfo
.comm
.is_decompressor
2427 # ifdef D_LOSSLESS_SUPPORTED
2428 ? sp
->cinfo
.d
.min_codec_data_unit
2432 # ifdef C_LOSSLESS_SUPPORTED
2433 : sp
->cinfo
.c
.data_unit
;
2437 size
= TIFFroundup(size
,16);
2438 (*sp
->deftparent
)(tif
,tw
,th
);
2439 *tw
= TIFFroundup(*tw
,td
->td_ycbcrsubsampling
[0]*size
);
2440 *th
= TIFFroundup(*th
,td
->td_ycbcrsubsampling
[1]*size
);
2445 OJPEGCleanUp(register TIFF
*tif
)
2446 { register OJPEGState
*sp
;
2448 if ( (sp
= OJState(tif
)) )
2450 CALLVJPEG(sp
,jpeg_destroy(&sp
->cinfo
.comm
)); /* Free JPEG Lib. vars. */
2451 if (sp
->jpegtables
) {_TIFFfree(sp
->jpegtables
);sp
->jpegtables
=0;}
2452 if (sp
->jpeglosslesspredictors
) {
2453 _TIFFfree(sp
->jpeglosslesspredictors
);
2454 sp
->jpeglosslesspredictors
= 0;
2456 if (sp
->jpegpointtransform
) {
2457 _TIFFfree(sp
->jpegpointtransform
);
2458 sp
->jpegpointtransform
=0;
2460 if (sp
->jpegqtables
) {_TIFFfree(sp
->jpegqtables
);sp
->jpegqtables
=0;}
2461 if (sp
->jpegactables
) {_TIFFfree(sp
->jpegactables
);sp
->jpegactables
=0;}
2462 if (sp
->jpegdctables
) {_TIFFfree(sp
->jpegdctables
);sp
->jpegdctables
=0;}
2463 /* If the image file isn't "memory mapped" and we read it all into a
2464 single, large memory buffer, free the buffer now.
2466 if (!isMapped(tif
) && tif
->tif_base
) /* free whole-file buffer */
2468 _TIFFfree(tif
->tif_base
);
2472 _TIFFfree(sp
); /* Release local variables */
2478 TIFFInitOJPEG(register TIFF
*tif
,int scheme
)
2479 { register OJPEGState
*sp
;
2480 # define td (&tif->tif_dir)
2483 /* This module supports a decompression-only CODEC, which is intended strictly
2484 for viewing old image files using the obsolete JPEG-in-TIFF encapsulation
2485 specified by the TIFF Version 6.0 specification. It does not, and never
2486 should, support compression for new images. If a client application asks us
2487 to, refuse and complain loudly!
2489 if (tif
->tif_mode
!= O_RDONLY
) return _notSupported(tif
);
2494 /* BEWARE OF KLUDGE: If our host operating-system doesn't let an image
2495 file be "memory mapped", then we want to read the
2496 entire file into a single (possibly large) memory buffer as if it had
2497 been "memory mapped". Although this is likely to waste space, because
2498 analysis of the file's content might cause parts of it to be read into
2499 smaller buffers duplicatively, it appears to be the lesser of several
2500 evils. Very old JPEG-in-TIFF encapsulations aren't guaranteed to be
2501 JFIF bit streams, or to have a TIFF "JPEGTables" record or much other
2502 "metadata" to help us locate the decoding tables and entropy-coded data,
2503 so we're likely do a lot of random-access grokking around, and we must
2504 ultimately tell the JPEG Library to sequentially scan much of the file
2505 anyway. This is all likely to be easier if we use "brute force" to
2506 read the entire file, once, and don't use incremental disc I/O. If our
2507 client application tries to process a file so big that we can't buffer
2508 it entirely, then tough shit: we'll give up and exit!
2510 if (!(tif
->tif_base
= _TIFFmalloc(tif
->tif_size
=TIFFGetFileSize(tif
))))
2512 TIFFError(tif
->tif_name
,"Cannot allocate file buffer");
2515 if (!SeekOK(tif
,0) || !ReadOK(tif
,tif
->tif_base
,tif
->tif_size
))
2517 TIFFError(tif
->tif_name
,"Cannot read file");
2522 /* Allocate storage for this module's per-file variables. */
2524 if (!(tif
->tif_data
= (tidata_t
)_TIFFmalloc(sizeof *sp
)))
2526 TIFFError("TIFFInitOJPEG","No space for JPEG state block");
2529 (sp
= OJState(tif
))->tif
= tif
; /* Initialize reverse pointer */
2530 sp
->cinfo
.d
.err
= jpeg_std_error(&sp
->err
); /* Initialize error handling */
2531 sp
->err
.error_exit
= TIFFojpeg_error_exit
;
2532 sp
->err
.output_message
= TIFFojpeg_output_message
;
2533 if (!CALLVJPEG(sp
,jpeg_create_decompress(&sp
->cinfo
.d
))) return 0;
2535 /* Install CODEC-specific tag information and override default TIFF Library
2536 "method" subroutines with our own, CODEC-specific methods. Like all good
2537 members of an object-class, we save some of these subroutine pointers for
2538 "fall back" in case our own methods fail.
2540 _TIFFMergeFieldInfo(tif
,ojpegFieldInfo
,
2541 sizeof ojpegFieldInfo
/sizeof *ojpegFieldInfo
);
2542 sp
->defsparent
= tif
->tif_defstripsize
;
2543 sp
->deftparent
= tif
->tif_deftilesize
;
2544 sp
->vgetparent
= tif
->tif_tagmethods
.vgetfield
;
2545 sp
->vsetparent
= tif
->tif_tagmethods
.vsetfield
;
2546 tif
->tif_defstripsize
= OJPEGDefaultStripSize
;
2547 tif
->tif_deftilesize
= OJPEGDefaultTileSize
;
2548 tif
->tif_tagmethods
.vgetfield
= OJPEGVGetField
;
2549 tif
->tif_tagmethods
.vsetfield
= OJPEGVSetField
;
2550 tif
->tif_tagmethods
.printdir
= OJPEGPrintDir
;
2552 tif
->tif_setupencode
= OJPEGSetupEncode
;
2553 tif
->tif_preencode
= OJPEGPreEncode
;
2554 tif
->tif_postencode
= OJPEGPostEncode
;
2555 # else /* well, hardly ever */
2556 tif
->tif_setupencode
= tif
->tif_postencode
= _notSupported
;
2557 tif
->tif_preencode
= (TIFFPreMethod
)_notSupported
;
2559 tif
->tif_setupdecode
= OJPEGSetupDecode
;
2560 tif
->tif_predecode
= OJPEGPreDecode
;
2561 tif
->tif_postdecode
= OJPEGPostDecode
;
2562 tif
->tif_cleanup
= OJPEGCleanUp
;
2564 /* If the image file doesn't have "JPEGInterchangeFormat[Length]" TIFF records
2565 to guide us, we have few clues about where its encapsulated JPEG bit stream
2566 is located, so establish intelligent defaults: If the Image File Directory
2567 doesn't immediately follow the TIFF header, assume that the JPEG data lies
2568 in between; otherwise, assume that it follows the Image File Directory.
2570 if (tif
->tif_header
.tiff_diroff
> sizeof tif
->tif_header
)
2572 sp
->src
.next_input_byte
= tif
->tif_base
+ sizeof tif
->tif_header
;
2573 sp
->src
.bytes_in_buffer
= tif
->tif_header
.tiff_diroff
2574 - sizeof tif
->tif_header
;
2576 else /* this case is ugly! */
2577 { uint32 maxoffset
= tif
->tif_size
;
2580 /* Calculate the offset to the next Image File Directory, if there is one,
2581 or to the end of the file, if not. Then arrange to read the file from
2582 the end of the Image File Directory to that offset.
2584 if (tif
->tif_nextdiroff
) maxoffset
= tif
->tif_nextdiroff
; /* Not EOF */
2585 _TIFFmemcpy(&dircount
,(const tdata_t
)
2586 (sp
->src
.next_input_byte
= tif
->tif_base
+tif
->tif_header
.tiff_diroff
),
2588 if (tif
->tif_flags
& TIFF_SWAB
) TIFFSwabShort(&dircount
);
2589 sp
->src
.next_input_byte
+= dircount
*sizeof(TIFFDirEntry
)
2590 + sizeof maxoffset
+ sizeof dircount
;
2591 sp
->src
.bytes_in_buffer
= tif
->tif_base
- sp
->src
.next_input_byte
2595 /* IJG JPEG Library Version 6B can be configured for either 8- or 12-bit sample
2596 precision, but we assume that "old JPEG" TIFF clients only need 8 bits.
2598 sp
->cinfo
.d
.data_precision
= 8;
2599 # ifdef C_LOSSLESS_SUPPORTED
2601 /* If the "JPEGProc" TIFF tag is missing from the Image File Dictionary, the
2602 JPEG Library will use its (lossy) baseline sequential process by default.
2604 sp
->cinfo
.d
.data_unit
= DCTSIZE
;
2605 # endif /* C_LOSSLESS_SUPPORTED */
2607 /* Initialize other CODEC-specific variables requiring default values. */
2609 tif
->tif_flags
|= TIFF_NOBITREV
; /* No bit-reversal within data bytes */
2610 sp
->h_sampling
= sp
->v_sampling
= 1; /* No subsampling by default */
2611 sp
->is_WANG
= 0; /* Assume not a MS Windows Wang Imaging file by default */
2612 sp
->jpegtables
= 0; /* No "new"-style JPEG tables synthesized yet */
2613 sp
->jpegtables_length
= 0;
2614 sp
->jpegquality
= 75; /* Default IJG quality */
2615 sp
->jpegcolormode
= JPEGCOLORMODE_RAW
;
2616 sp
->jpegtablesmode
= 0; /* No tables found yet */
2617 sp
->jpeglosslesspredictors
=0;
2618 sp
->jpeglosslesspredictors_length
=0;
2619 sp
->jpegpointtransform
=0;
2620 sp
->jpegpointtransform_length
=0;
2622 sp
->jpegqtables_length
=0;
2624 sp
->jpegdctables_length
=0;
2626 sp
->jpegactables_length
=0;
2630 #endif /* OJPEG_SUPPORT */