6 /* JPEG Compression support, as per the original TIFF 6.0 specification.
8 WARNING: KLUDGE ALERT! The type of JPEG encapsulation defined by the TIFF
9 Version 6.0 specification is now totally obsolete and
10 deprecated for new applications and images. This file is an unsupported hack
11 that was created solely in order to read (but NOT write!) a few old,
12 unconverted images still present on some users' computer systems. The code
13 isn't pretty or robust, and it won't read every "old format" JPEG-in-TIFF
14 file (see Samuel Leffler's draft "TIFF Technical Note No. 2" for a long and
15 incomplete list of known problems), but it seems to work well enough in the
16 few cases of practical interest to the author; so, "caveat emptor"! This
17 file should NEVER be enhanced to write new images using anything other than
18 the latest approved JPEG-in-TIFF encapsulation method, implemented by the
19 "tif_jpeg.c" file elsewhere in this library.
21 This file interfaces with Release 6B of the JPEG Library written by theu
22 Independent JPEG Group, which you can find on the Internet at:
23 ftp://ftp.uu.net:/graphics/jpeg/.
25 The "C" Preprocessor macros, "[CD]_LOSSLESS_SUPPORTED", are defined by your
26 JPEG Library Version 6B only if you have applied a (massive!) patch by Ken
27 Murchison of Oceana Matrix Ltd. <ken@oceana.com> to support lossless Huffman
28 encoding (TIFF "JPEGProc" tag value = 14). This patch can be found on the
29 Internet at: ftp://ftp.oceana.com/pub/ljpeg-6b.tar.gz.
31 Some old files produced by the Wang Imaging application for Microsoft Windows
32 apparently can be decoded only with a special patch to the JPEG Library,
33 which defines a subroutine named "jpeg_reset_huff_decode()" in its "jdhuff.c"
34 module (the "jdshuff.c" module, if Ken Murchison's patch has been applied).
35 Unfortunately the patch differs slightly in each case, and some TIFF Library
36 have reported problems finding the code, so both versions appear below; you
37 should carefully extract and apply only the version that applies to your JPEG
40 Contributed by Scott Marovich <marovich@hpl.hp.com> with considerable help
41 from Charles Auer <Bumble731@msn.com> to unravel the mysteries of image files
42 created by the Wang Imaging application for Microsoft Windows.
44 #if 0 /* Patch for JPEG Library WITHOUT lossless Huffman coding */
45 *** jdhuff
.c
.orig Mon Oct
20 17:51:10 1997
46 --- jdhuff
.c Sun Nov
11 17:33:58 2001
50 for (i
= 0; i
< NUM_HUFF_TBLS
; i
++) {
51 entropy
->dc_derived_tbls
[i
] = entropy
->ac_derived_tbls
[i
] = NULL
;
56 + * BEWARE OF KLUDGE: This subroutine is a hack for decoding illegal JPEG-in-
57 + * TIFF encapsulations produced by Microsoft's Wang Imaging
58 + * for Windows application with the public-domain TIFF Library. Based upon an
59 + * examination of selected output files, this program apparently divides a JPEG
60 + * bit-stream into consecutive horizontal TIFF "strips", such that the JPEG
61 + * encoder's/decoder's DC coefficients for each image component are reset before
62 + * each "strip". Moreover, a "strip" is not necessarily encoded in a multiple
63 + * of 8 bits, so one must sometimes discard 1-7 bits at the end of each "strip"
64 + * for alignment to the next input-Byte storage boundary. IJG JPEG Library
65 + * decoder state is not normally exposed to client applications, so this sub-
66 + * routine provides the TIFF Library with a "hook" to make these corrections.
67 + * It should be called after "jpeg_start_decompress()" and before
68 + * "jpeg_finish_decompress()", just before decoding each "strip" using
69 + * "jpeg_read_raw_data()" or "jpeg_read_scanlines()".
71 + * This kludge is not sanctioned or supported by the Independent JPEG Group, and
72 + * future changes to the IJG JPEG Library might invalidate it. Do not send bug
73 + * reports about this code to IJG developers. Instead, contact the author for
74 + * advice: Scott B. Marovich <marovich@hpl.hp.com>, Hewlett-Packard Labs, 6/01.
77 + jpeg_reset_huff_decode (register j_decompress_ptr cinfo
)
78 + { register huff_entropy_ptr entropy
= (huff_entropy_ptr
)cinfo
->entropy
;
79 + register int ci
= 0;
81 + /* Discard encoded input bits, up to the next Byte boundary */
82 + entropy
->bitstate
.bits_left
&= ~7;
83 + /* Re-initialize DC predictions to 0 */
84 + do entropy
->saved
.last_dc_val
[ci
] = 0; while (++ci
< cinfo
->comps_in_scan
);
86 #endif /* Patch for JPEG Library WITHOUT lossless Huffman coding */
87 #if 0 /* Patch for JPEG Library WITH lossless Huffman coding */
88 *** jdshuff
.c
.orig Mon Mar
11 16:44:54 2002
89 --- jdshuff
.c Mon Mar
11 16:44:54 2002
93 for (i
= 0; i
< NUM_HUFF_TBLS
; i
++) {
94 entropy
->dc_derived_tbls
[i
] = entropy
->ac_derived_tbls
[i
] = NULL
;
99 + * BEWARE OF KLUDGE: This subroutine is a hack for decoding illegal JPEG-in-
100 + * TIFF encapsulations produced by Microsoft's Wang Imaging
101 + * for Windows application with the public-domain TIFF Library. Based upon an
102 + * examination of selected output files, this program apparently divides a JPEG
103 + * bit-stream into consecutive horizontal TIFF "strips", such that the JPEG
104 + * encoder's/decoder's DC coefficients for each image component are reset before
105 + * each "strip". Moreover, a "strip" is not necessarily encoded in a multiple
106 + * of 8 bits, so one must sometimes discard 1-7 bits at the end of each "strip"
107 + * for alignment to the next input-Byte storage boundary. IJG JPEG Library
108 + * decoder state is not normally exposed to client applications, so this sub-
109 + * routine provides the TIFF Library with a "hook" to make these corrections.
110 + * It should be called after "jpeg_start_decompress()" and before
111 + * "jpeg_finish_decompress()", just before decoding each "strip" using
112 + * "jpeg_read_raw_data()" or "jpeg_read_scanlines()".
114 + * This kludge is not sanctioned or supported by the Independent JPEG Group, and
115 + * future changes to the IJG JPEG Library might invalidate it. Do not send bug
116 + * reports about this code to IJG developers. Instead, contact the author for
117 + * advice: Scott B. Marovich <marovich@hpl.hp.com>, Hewlett-Packard Labs, 6/01.
120 + jpeg_reset_huff_decode (register j_decompress_ptr cinfo
)
121 + { register shuff_entropy_ptr entropy
= (shuff_entropy_ptr
)
122 + ((j_lossy_d_ptr
)cinfo
->codec
)->entropy_private
;
123 + register int ci
= 0;
125 + /* Discard encoded input bits, up to the next Byte boundary */
126 + entropy
->bitstate
.bits_left
&= ~7;
127 + /* Re-initialize DC predictions to 0 */
128 + do entropy
->saved
.last_dc_val
[ci
] = 0; while (++ci
< cinfo
->comps_in_scan
);
130 #endif /* Patch for JPEG Library WITH lossless Huffman coding */
134 #undef FAR /* Undefine FAR to avoid conflict with JPEG definition */
136 #define JPEG_INTERNALS /* Include "jpegint.h" for "DSTATE_*" symbols */
137 #define JPEG_CJPEG_DJPEG /* Include all Version 6B+ "jconfig.h" options */
140 #undef JPEG_CJPEG_DJPEG
141 #undef JPEG_INTERNALS
143 /* Hack for files produced by Wang Imaging application on Microsoft Windows */
144 extern void jpeg_reset_huff_decode(j_decompress_ptr
);
146 /* On some machines, it may be worthwhile to use "_setjmp()" or "sigsetjmp()"
147 instead of "setjmp()". These macros make it easier:
149 #define SETJMP(jbuf)setjmp(jbuf)
150 #define LONGJMP(jbuf,code)longjmp(jbuf,code)
151 #define JMP_BUF jmp_buf
153 #define TIFFTAG_WANG_PAGECONTROL 32934
155 /* Bit-vector offsets for keeping track of TIFF records that we've parsed. */
157 #define FIELD_JPEGPROC FIELD_CODEC
158 #define FIELD_JPEGIFOFFSET (FIELD_CODEC+1)
159 #define FIELD_JPEGIFBYTECOUNT (FIELD_CODEC+2)
160 #define FIELD_JPEGRESTARTINTERVAL (FIELD_CODEC+3)
161 #define FIELD_JPEGTABLES (FIELD_CODEC+4) /* New, post-6.0 JPEG-in-TIFF tag! */
162 #define FIELD_JPEGLOSSLESSPREDICTORS (FIELD_CODEC+5)
163 #define FIELD_JPEGPOINTTRANSFORM (FIELD_CODEC+6)
164 #define FIELD_JPEGQTABLES (FIELD_CODEC+7)
165 #define FIELD_JPEGDCTABLES (FIELD_CODEC+8)
166 #define FIELD_JPEGACTABLES (FIELD_CODEC+9)
167 #define FIELD_WANG_PAGECONTROL (FIELD_CODEC+10)
168 #define FIELD_JPEGCOLORMODE (FIELD_CODEC+11)
170 typedef struct jpeg_destination_mgr jpeg_destination_mgr
;
171 typedef struct jpeg_source_mgr jpeg_source_mgr
;
172 typedef struct jpeg_error_mgr jpeg_error_mgr
;
174 /* State variable for each open TIFF file that uses "libjpeg" for JPEG
175 decompression. (Note: This file should NEVER perform JPEG compression
176 except in the manner implemented by the "tif_jpeg.c" file, elsewhere in this
177 library; see comments above.) JPEG Library internal state is recorded in a
178 "jpeg_{de}compress_struct", while a "jpeg_common_struct" records a few items
179 common to both compression and expansion. The "cinfo" field containing JPEG
180 Library state MUST be the 1st member of our own state variable, so that we
181 can safely "cast" pointers back and forth.
183 typedef struct /* This module's private, per-image state variable */
185 union /* JPEG Library state variable; this MUST be our 1st field! */
187 struct jpeg_compress_struct c
;
188 struct jpeg_decompress_struct d
;
189 struct jpeg_common_struct comm
;
191 jpeg_error_mgr err
; /* JPEG Library error manager */
192 JMP_BUF exit_jmpbuf
; /* ...for catching JPEG Library failures */
195 /* (The following two fields could be a "union", but they're small enough that
196 it's not worth the effort.)
198 jpeg_destination_mgr dest
; /* Destination for compressed data */
200 jpeg_source_mgr src
; /* Source of expanded data */
201 JSAMPARRAY ds_buffer
[MAX_COMPONENTS
]; /* ->Temporary downsampling buffers */
202 TIFF
*tif
; /* Reverse pointer, needed by some code */
203 TIFFVGetMethod vgetparent
; /* "Super class" methods... */
204 TIFFVSetMethod vsetparent
;
205 TIFFStripMethod defsparent
;
206 TIFFTileMethod deftparent
;
207 void *jpegtables
; /* ->"New" JPEG tables, if we synthesized any */
208 uint32 is_WANG
, /* <=> Wang Imaging for Microsoft Windows output file? */
209 jpegtables_length
; /* Length of "new" JPEG tables, if they exist */
210 tsize_t bytesperline
; /* No. of decompressed Bytes per scan line */
211 int jpegquality
, /* Compression quality level */
212 jpegtablesmode
, /* What to put in JPEGTables */
214 scancount
; /* No. of scan lines accumulated */
215 J_COLOR_SPACE photometric
; /* IJG JPEG Library's photometry code */
216 unsigned char h_sampling
, /* Luminance sampling factors */
218 jpegcolormode
; /* Who performs RGB <-> YCbCr conversion? */
219 /* JPEGCOLORMODE_RAW <=> TIFF Library or its client */
220 /* JPEGCOLORMODE_RGB <=> JPEG Library */
221 /* These fields are added to support TIFFGetField */
224 uint32 jpegifbytecount
;
225 uint32 jpegrestartinterval
;
226 void* jpeglosslesspredictors
;
227 uint16 jpeglosslesspredictors_length
;
228 void* jpegpointtransform
;
229 uint32 jpegpointtransform_length
;
231 uint32 jpegqtables_length
;
233 uint32 jpegdctables_length
;
235 uint32 jpegactables_length
;
238 #define OJState(tif)((OJPEGState*)(tif)->tif_data)
240 static const TIFFFieldInfo ojpegFieldInfo
[]=/* JPEG-specific TIFF-record tags */
243 /* This is the current JPEG-in-TIFF metadata-encapsulation tag, and its
244 treatment in this file is idiosyncratic. It should never appear in a
245 "source" image conforming to the TIFF Version 6.0 specification, so we
246 arrange to report an error if it appears. But in order to support possible
247 future conversion of "old" JPEG-in-TIFF encapsulations to "new" ones, we
248 might wish to synthesize an equivalent value to be returned by the TIFF
249 Library's "getfield" method. So, this table tells the TIFF Library to pass
250 these records to us in order to filter them below.
253 TIFFTAG_JPEGTABLES
,TIFF_VARIABLE2
,TIFF_VARIABLE2
,
254 TIFF_UNDEFINED
,FIELD_JPEGTABLES
,FALSE
,TRUE
,"JPEGTables"
257 /* These tags are defined by the TIFF Version 6.0 specification and are now
258 obsolete. This module reads them from an old "source" image, but it never
259 writes them to a new "destination" image.
262 TIFFTAG_JPEGPROC
,1 ,1 ,
263 TIFF_SHORT
,FIELD_JPEGPROC
,FALSE
,FALSE
,"JPEGProc"
266 TIFFTAG_JPEGIFOFFSET
,1 ,1 ,
267 TIFF_LONG
,FIELD_JPEGIFOFFSET
,FALSE
,FALSE
,"JPEGInterchangeFormat"
270 TIFFTAG_JPEGIFBYTECOUNT
,1 ,1 ,
271 TIFF_LONG
,FIELD_JPEGIFBYTECOUNT
,FALSE
,FALSE
,"JPEGInterchangeFormatLength"
274 TIFFTAG_JPEGRESTARTINTERVAL
,1 ,1 ,
275 TIFF_SHORT
,FIELD_JPEGRESTARTINTERVAL
,FALSE
,FALSE
,"JPEGRestartInterval"
278 TIFFTAG_JPEGLOSSLESSPREDICTORS
,TIFF_VARIABLE
,TIFF_VARIABLE
,
279 TIFF_SHORT
,FIELD_JPEGLOSSLESSPREDICTORS
,FALSE
,TRUE
,"JPEGLosslessPredictors"
282 TIFFTAG_JPEGPOINTTRANSFORM
,TIFF_VARIABLE
,TIFF_VARIABLE
,
283 TIFF_SHORT
,FIELD_JPEGPOINTTRANSFORM
,FALSE
,TRUE
,"JPEGPointTransforms"
286 TIFFTAG_JPEGQTABLES
,TIFF_VARIABLE
,TIFF_VARIABLE
,
287 TIFF_LONG
,FIELD_JPEGQTABLES
,FALSE
,TRUE
,"JPEGQTables"
290 TIFFTAG_JPEGDCTABLES
,TIFF_VARIABLE
,TIFF_VARIABLE
,
291 TIFF_LONG
,FIELD_JPEGDCTABLES
,FALSE
,TRUE
,"JPEGDCTables"
294 TIFFTAG_JPEGACTABLES
,TIFF_VARIABLE
,TIFF_VARIABLE
,
295 TIFF_LONG
,FIELD_JPEGACTABLES
,FALSE
,TRUE
,"JPEGACTables"
298 TIFFTAG_WANG_PAGECONTROL
,TIFF_VARIABLE
,1 ,
299 TIFF_LONG
,FIELD_WANG_PAGECONTROL
,FALSE
,FALSE
,"WANG PageControl"
302 /* This is a pseudo tag intended for internal use only by the TIFF Library and
303 its clients, which should never appear in an input/output image file. It
304 specifies whether the TIFF Library (or its client) should do YCbCr <-> RGB
305 color-space conversion (JPEGCOLORMODE_RAW <=> 0) or whether we should ask
306 the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1).
309 TIFFTAG_JPEGCOLORMODE
,0 ,0 ,
310 TIFF_ANY
,FIELD_PSEUDO
,FALSE
,FALSE
,"JPEGColorMode"
313 static const char JPEGLib_name
[]={"JPEG Library"},
314 bad_bps
[]={"%u BitsPerSample not allowed for JPEG"},
315 bad_photometry
[]={"PhotometricInterpretation %u not allowed for JPEG"},
316 bad_subsampling
[]={"invalid YCbCr subsampling factor(s)"},
318 no_write_frac
[]={"fractional scan line discarded"},
320 no_read_frac
[]={"fractional scan line not read"},
321 no_jtable_space
[]={"No space for JPEGTables"};
323 /* The following diagnostic subroutines interface with and replace default
324 subroutines in the JPEG Library. Our basic strategy is to use "setjmp()"/
325 "longjmp()" in order to return control to the TIFF Library when the JPEG
326 library detects an error, and to use TIFF Library subroutines for displaying
327 diagnostic messages to a client application.
330 TIFFojpeg_error_exit(register j_common_ptr cinfo
)
332 char buffer
[JMSG_LENGTH_MAX
];
333 int code
= cinfo
->err
->msg_code
;
335 if (((OJPEGState
*)cinfo
)->is_WANG
) {
336 if (code
== JERR_SOF_DUPLICATE
|| code
== JERR_SOI_DUPLICATE
)
337 return; /* ignore it */
340 (*cinfo
->err
->format_message
)(cinfo
,buffer
);
341 TIFFError(JPEGLib_name
,buffer
); /* Display error message */
342 jpeg_abort(cinfo
); /* Clean up JPEG Library state */
343 LONGJMP(((OJPEGState
*)cinfo
)->exit_jmpbuf
,1); /* Return to TIFF client */
347 TIFFojpeg_output_message(register j_common_ptr cinfo
)
348 { char buffer
[JMSG_LENGTH_MAX
];
350 /* This subroutine is invoked only for warning messages, since the JPEG
351 Library's "error_exit" method does its own thing and "trace_level" is never
354 (*cinfo
->err
->format_message
)(cinfo
,buffer
);
355 TIFFWarning(JPEGLib_name
,buffer
);
358 /* The following subroutines, which also interface with the JPEG Library, exist
359 mainly in limit the side effects of "setjmp()" and convert JPEG normal/error
360 conditions into TIFF Library return codes.
362 #define CALLJPEG(sp,fail,op)(SETJMP((sp)->exit_jmpbuf)?(fail):(op))
363 #define CALLVJPEG(sp,op)CALLJPEG(sp,0,((op),1))
367 TIFFojpeg_create_compress(register OJPEGState
*sp
)
369 sp
->cinfo
.c
.err
= jpeg_std_error(&sp
->err
); /* Initialize error handling */
370 sp
->err
.error_exit
= TIFFojpeg_error_exit
;
371 sp
->err
.output_message
= TIFFojpeg_output_message
;
372 return CALLVJPEG(sp
,jpeg_create_compress(&sp
->cinfo
.c
));
375 /* The following subroutines comprise a JPEG Library "destination" data manager
376 by directing compressed data from the JPEG Library to a TIFF Library output
380 std_init_destination(register j_compress_ptr cinfo
){} /* "Dummy" stub */
383 std_empty_output_buffer(register j_compress_ptr cinfo
)
385 # define sp ((OJPEGState *)cinfo)
386 register TIFF
*tif
= sp
->tif
;
388 tif
->tif_rawcc
= tif
->tif_rawdatasize
; /* Entire buffer has been filled */
390 sp
->dest
.next_output_byte
= (JOCTET
*)tif
->tif_rawdata
;
391 sp
->dest
.free_in_buffer
= (size_t)tif
->tif_rawdatasize
;
397 std_term_destination(register j_compress_ptr cinfo
)
399 # define sp ((OJPEGState *)cinfo)
400 register TIFF
*tif
= sp
->tif
;
402 /* NB: The TIFF Library does the final buffer flush. */
403 tif
->tif_rawcp
= (tidata_t
)sp
->dest
.next_output_byte
;
404 tif
->tif_rawcc
= tif
->tif_rawdatasize
- (tsize_t
)sp
->dest
.free_in_buffer
;
408 /* Alternate destination manager to output JPEGTables field: */
411 tables_init_destination(register j_compress_ptr cinfo
)
413 # define sp ((OJPEGState *)cinfo)
414 /* The "jpegtables_length" field is the allocated buffer size while building */
415 sp
->dest
.next_output_byte
= (JOCTET
*)sp
->jpegtables
;
416 sp
->dest
.free_in_buffer
= (size_t)sp
->jpegtables_length
;
421 tables_empty_output_buffer(register j_compress_ptr cinfo
)
423 # define sp ((OJPEGState *)cinfo)
425 /* The entire buffer has been filled, so enlarge it by 1000 bytes. */
426 if (!( newbuf
= _TIFFrealloc( (tdata_t
)sp
->jpegtables
427 , (tsize_t
)(sp
->jpegtables_length
+ 1000)
430 ) ERREXIT1(cinfo
,JERR_OUT_OF_MEMORY
,100);
431 sp
->dest
.next_output_byte
= (JOCTET
*)newbuf
+ sp
->jpegtables_length
;
432 sp
->dest
.free_in_buffer
= (size_t)1000;
433 sp
->jpegtables
= newbuf
;
434 sp
->jpegtables_length
+= 1000;
440 tables_term_destination(register j_compress_ptr cinfo
)
442 # define sp ((OJPEGState *)cinfo)
443 /* Set tables length to no. of Bytes actually emitted. */
444 sp
->jpegtables_length
-= sp
->dest
.free_in_buffer
;
448 /*ARGSUSED*/ static int
449 TIFFojpeg_tables_dest(register OJPEGState
*sp
, TIFF
*tif
)
452 /* Allocate a working buffer for building tables. The initial size is 1000
453 Bytes, which is usually adequate.
455 if (sp
->jpegtables
) _TIFFfree(sp
->jpegtables
);
456 if (!(sp
->jpegtables
= (void*)
457 _TIFFmalloc((tsize_t
)(sp
->jpegtables_length
= 1000))
461 sp
->jpegtables_length
= 0;
462 TIFFError("TIFFojpeg_tables_dest",no_jtable_space
);
465 sp
->cinfo
.c
.dest
= &sp
->dest
;
466 sp
->dest
.init_destination
= tables_init_destination
;
467 sp
->dest
.empty_output_buffer
= tables_empty_output_buffer
;
468 sp
->dest
.term_destination
= tables_term_destination
;
471 #else /* well, hardly ever */
474 _notSupported(register TIFF
*tif
)
475 { const TIFFCodec
*c
= TIFFFindCODEC(tif
->tif_dir
.td_compression
);
477 TIFFError(tif
->tif_name
,"%s compression not supported",c
->name
);
482 /* The following subroutines comprise a JPEG Library "source" data manager by
483 by directing compressed data to the JPEG Library from a TIFF Library input
487 std_init_source(register j_decompress_ptr cinfo
)
489 # define sp ((OJPEGState *)cinfo)
490 register TIFF
*tif
= sp
->tif
;
492 if (sp
->src
.bytes_in_buffer
== 0)
494 sp
->src
.next_input_byte
= (const JOCTET
*)tif
->tif_rawdata
;
495 sp
->src
.bytes_in_buffer
= (size_t)tif
->tif_rawcc
;
501 std_fill_input_buffer(register j_decompress_ptr cinfo
)
502 { static const JOCTET dummy_EOI
[2]={0xFF,JPEG_EOI
};
503 # define sp ((OJPEGState *)cinfo)
505 /* Control should never get here, since an entire strip/tile is read into
506 memory before the decompressor is called; thus, data should have been
507 supplied by the "init_source" method. ...But, sometimes things fail.
509 WARNMS(cinfo
,JWRN_JPEG_EOF
);
510 sp
->src
.next_input_byte
= dummy_EOI
; /* Insert a fake EOI marker */
511 sp
->src
.bytes_in_buffer
= sizeof dummy_EOI
;
517 std_skip_input_data(register j_decompress_ptr cinfo
, long num_bytes
)
519 # define sp ((OJPEGState *)cinfo)
523 if (num_bytes
> (long)sp
->src
.bytes_in_buffer
) /* oops: buffer overrun */
524 (void)std_fill_input_buffer(cinfo
);
527 sp
->src
.next_input_byte
+= (size_t)num_bytes
;
528 sp
->src
.bytes_in_buffer
-= (size_t)num_bytes
;
534 /*ARGSUSED*/ static void
535 std_term_source(register j_decompress_ptr cinfo
){} /* "Dummy" stub */
537 /* Allocate temporary I/O buffers for downsampled data, using values computed in
538 "jpeg_start_{de}compress()". We use the JPEG Library's allocator so that
539 buffers will be released automatically when done with a strip/tile. This is
540 also a handy place to compute samplesperclump, bytesperline, etc.
543 alloc_downsampled_buffers(TIFF
*tif
,jpeg_component_info
*comp_info
,
545 { register OJPEGState
*sp
= OJState(tif
);
547 sp
->samplesperclump
= 0;
548 if (num_components
> 0)
549 { tsize_t size
= sp
->cinfo
.comm
.is_decompressor
550 # ifdef D_LOSSLESS_SUPPORTED
551 ? sp
->cinfo
.d
.min_codec_data_unit
555 # ifdef C_LOSSLESS_SUPPORTED
556 : sp
->cinfo
.c
.data_unit
;
561 register jpeg_component_info
*compptr
= comp_info
;
566 sp
->samplesperclump
+=
567 compptr
->h_samp_factor
* compptr
->v_samp_factor
;
568 # if defined(C_LOSSLESS_SUPPORTED) || defined(D_LOSSLESS_SUPPORTED)
569 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
))))
571 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
))))
574 sp
->ds_buffer
[ci
] = buf
;
576 while (++compptr
,++ci
< num_components
);
582 /* JPEG Encoding begins here. */
584 /*ARGSUSED*/ static int
585 OJPEGEncode(register TIFF
*tif
,tidata_t buf
,tsize_t cc
,tsample_t s
)
586 { tsize_t rows
; /* No. of unprocessed rows in file */
587 register OJPEGState
*sp
= OJState(tif
);
589 /* Encode a chunk of pixels, where returned data is NOT down-sampled (the
590 standard case). The data is expected to be written in scan-line multiples.
592 if (cc
% sp
->bytesperline
) TIFFWarning(tif
->tif_name
,no_write_frac
);
593 if ( (cc
/= bytesperline
) /* No. of complete rows in caller's buffer */
594 > (rows
= sp
->cinfo
.c
.image_height
- sp
->cinfo
.c
.next_scanline
)
598 if ( CALLJPEG(sp
,-1,jpeg_write_scanlines(&sp
->cinfo
.c
,(JSAMPARRAY
)&buf
,1))
602 buf
+= sp
->bytesperline
;
607 /*ARGSUSED*/ static int
608 OJPEGEncodeRaw(register TIFF
*tif
,tidata_t buf
,tsize_t cc
,tsample_t s
)
609 { tsize_t rows
; /* No. of unprocessed rows in file */
610 JDIMENSION lines_per_MCU
, size
;
611 register OJPEGState
*sp
= OJState(tif
);
613 /* Encode a chunk of pixels, where returned data is down-sampled as per the
614 sampling factors. The data is expected to be written in scan-line
617 cc
/= sp
->bytesperline
;
618 if (cc
% sp
->bytesperline
) TIFFWarning(tif
->tif_name
,no_write_frac
);
619 if ( (cc
/= bytesperline
) /* No. of complete rows in caller's buffer */
620 > (rows
= sp
->cinfo
.c
.image_height
- sp
->cinfo
.c
.next_scanline
)
622 # ifdef C_LOSSLESS_SUPPORTED
623 lines_per_MCU
= sp
->cinfo
.c
.max_samp_factor
*(size
= sp
->cinfo
.d
.data_unit
);
625 lines_per_MCU
= sp
->cinfo
.c
.max_samp_factor
*(size
= DCTSIZE
);
628 { int ci
= 0, clumpoffset
= 0;
629 register jpeg_component_info
*compptr
= sp
->cinfo
.c
.comp_info
;
631 /* The fastest way to separate the data is to make 1 pass over the scan
632 line for each row of each component.
639 register JSAMPLE
*inptr
= (JSAMPLE
*)buf
+ clumpoffset
,
641 sp
->ds_buffer
[ci
][sp
->scancount
*compptr
->v_samp_factor
+ypos
];
642 /* Cb,Cr both have sampling factors 1, so this is correct */
643 register int clumps_per_line
=
644 sp
->cinfo
.c
.comp_info
[1].downsampled_width
,
648 # ifdef C_LOSSLESS_SUPPORTED
649 ( compptr
->width_in_data_units
* size
651 ( compptr
->width_in_blocks
* size
653 - clumps_per_line
* compptr
->h_samp_factor
655 if (compptr
->h_samp_factor
== 1) /* Cb & Cr fast path */
656 do *outptr
++ = *inptr
;
657 while ((inptr
+= sp
->samplesperclump
),--clumps_per_line
> 0);
658 else /* general case */
662 do *outptr
++ = inptr
[xpos
];
663 while (++xpos
< compptr
->h_samp_factor
);
665 while ((inptr
+= sp
->samplesperclump
),--clumps_per_line
> 0);
666 xpos
= 0; /* Pad each scan line as needed */
667 do outptr
[0] = outptr
[-1]; while (++outptr
,++xpos
< padding
);
668 clumpoffset
+= compptr
->h_samp_factor
;
670 while (++ypos
< compptr
->v_samp_factor
);
672 while (++compptr
,++ci
< sp
->cinfo
.c
.num_components
);
673 if (++sp
->scancount
>= size
)
675 if ( CALLJPEG(sp
,-1,jpeg_write_raw_data(&sp
->cinfo
.c
,sp
->ds_buffer
,lines_per_MCU
))
681 buf
+= sp
->bytesperline
;
687 OJPEGSetupEncode(register TIFF
*tif
)
688 { static const char module[]={"OJPEGSetupEncode"};
689 uint32 segment_height
, segment_width
;
690 int status
= 1; /* Assume success by default */
691 register OJPEGState
*sp
= OJState(tif
);
692 # define td (&tif->tif_dir)
694 /* Verify miscellaneous parameters. This will need work if the TIFF Library
695 ever supports different depths for different components, or if the JPEG
696 Library ever supports run-time depth selection. Neither seems imminent.
698 if (td
->td_bitspersample
!= 8)
700 TIFFError(module,bad_bps
,td
->td_bitspersample
);
704 /* The TIFF Version 6.0 specification and IJG JPEG Library accept different
705 sets of color spaces, so verify that our image belongs to the common subset
706 and map its photometry code, then initialize to handle subsampling and
707 optional JPEG Library YCbCr <-> RGB color-space conversion.
709 switch (td
->td_photometric
)
711 case PHOTOMETRIC_YCBCR
:
713 /* ISO IS 10918-1 requires that JPEG subsampling factors be 1-4, but
714 TIFF Version 6.0 is more restrictive: only 1, 2, and 4 are allowed.
716 if ( ( td
->td_ycbcrsubsampling
[0] == 1
717 || td
->td_ycbcrsubsampling
[0] == 2
718 || td
->td_ycbcrsubsampling
[0] == 4
720 && ( td
->td_ycbcrsubsampling
[1] == 1
721 || td
->td_ycbcrsubsampling
[1] == 2
722 || td
->td_ycbcrsubsampling
[1] == 4
725 sp
->cinfo
.c
.raw_data_in
=
726 ( (sp
->h_sampling
= td
->td_ycbcrsubsampling
[0]) << 3
727 | (sp
->v_sampling
= td
->td_ycbcrsubsampling
[1])
731 TIFFError(module,bad_subsampling
);
735 /* A ReferenceBlackWhite field MUST be present, since the default value
736 is inapproriate for YCbCr. Fill in the proper value if the
737 application didn't set it.
739 if (!TIFFFieldSet(tif
,FIELD_REFBLACKWHITE
))
741 long top
= 1L << td
->td_bitspersample
;
744 refbw
[1] = (float)(top
-1L);
745 refbw
[2] = (float)(top
>>1);
749 TIFFSetField(tif
,TIFFTAG_REFERENCEBLACKWHITE
,refbw
);
751 sp
->cinfo
.c
.jpeg_color_space
= JCS_YCbCr
;
752 if (sp
->jpegcolormode
== JPEGCOLORMODE_RGB
)
754 sp
->cinfo
.c
.raw_data_in
= FALSE
;
755 sp
->in_color_space
= JCS_RGB
;
759 case PHOTOMETRIC_MINISBLACK
:
760 sp
->cinfo
.c
.jpeg_color_space
= JCS_GRAYSCALE
;
762 case PHOTOMETRIC_RGB
:
763 sp
->cinfo
.c
.jpeg_color_space
= JCS_RGB
;
765 case PHOTOMETRIC_SEPARATED
:
766 sp
->cinfo
.c
.jpeg_color_space
= JCS_CMYK
;
767 L1
: sp
->jpegcolormode
= JPEGCOLORMODE_RAW
; /* No JPEG Lib. conversion */
768 L2
: sp
->cinfo
.d
.in_color_space
= sp
->cinfo
.d
.jpeg_color
-space
;
771 TIFFError(module,bad_photometry
,td
->td_photometric
);
774 tif
->tif_encoderow
= tif
->tif_encodestrip
= tif
->tif_encodetile
=
775 sp
->cinfo
.c
.raw_data_in
? OJPEGEncodeRaw
: OJPEGEncode
;
779 # ifdef C_LOSSLESS_SUPPORTED
780 if ((size
= sp
->v_sampling
*sp
->cinfo
.c
.data_unit
) < 16) size
= 16;
782 if ((size
= sp
->v_sampling
*DCTSIZE
) < 16) size
= 16;
784 if ((segment_height
= td
->td_tilelength
) % size
)
786 TIFFError(module,"JPEG tile height must be multiple of %d",size
);
789 # ifdef C_LOSSLESS_SUPPORTED
790 if ((size
= sp
->h_sampling
*sp
->cinfo
.c
.data_unit
) < 16) size
= 16;
792 if ((size
= sp
->h_sampling
*DCTSIZE
) < 16) size
= 16;
794 if ((segment_width
= td
->td_tilewidth
) % size
)
796 TIFFError(module,"JPEG tile width must be multiple of %d",size
);
799 sp
->bytesperline
= TIFFTileRowSize(tif
);
804 # ifdef C_LOSSLESS_SUPPORTED
805 if ((size
= sp
->v_sampling
*sp
->cinfo
.c
.data_unit
) < 16) size
= 16;
807 if ((size
= sp
->v_sampling
*DCTSIZE
) < 16) size
= 16;
809 if (td
->td_rowsperstrip
< (segment_height
= td
->td_imagelength
))
811 if (td
->td_rowsperstrip
% size
)
813 TIFFError(module,"JPEG RowsPerStrip must be multiple of %d",size
);
816 segment_height
= td
->td_rowsperstrip
;
818 segment_width
= td
->td_imagewidth
;
819 sp
->bytesperline
= tif
->tif_scanlinesize
;
821 if (segment_width
> 65535 || segment_height
> 65535)
823 TIFFError(module,"Strip/tile too large for JPEG");
827 /* Initialize all JPEG parameters to default values. Note that the JPEG
828 Library's "jpeg_set_defaults()" method needs legal values for the
829 "in_color_space" and "input_components" fields.
831 sp
->cinfo
.c
.input_components
= 1; /* Default for JCS_UNKNOWN */
832 if (!CALLVJPEG(sp
,jpeg_set_defaults(&sp
->cinfo
.c
))) status
= 0;
833 switch (sp
->jpegtablesmode
& (JPEGTABLESMODE_HUFF
|JPEGTABLESMODE_QUANT
))
834 { register JHUFF_TBL
*htbl
;
835 register JQUANT_TBL
*qtbl
;
838 sp
->cinfo
.c
.optimize_coding
= TRUE
;
839 case JPEGTABLESMODE_HUFF
:
840 if (!CALLVJPEG(sp
,jpeg_set_quality(&sp
->cinfo
.c
,sp
->jpegquality
,FALSE
)))
842 if (qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[0]) qtbl
->sent_table
= FALSE
;
843 if (qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[1]) qtbl
->sent_table
= FALSE
;
845 case JPEGTABLESMODE_QUANT
:
846 sp
->cinfo
.c
.optimize_coding
= TRUE
;
848 /* We do not support application-supplied JPEG tables, so mark the field
851 L3
: TIFFClrFieldBit(tif
,FIELD_JPEGTABLES
);
853 case JPEGTABLESMODE_HUFF
|JPEGTABLESMODE_QUANT
:
854 if ( !CALLVJPEG(sp
,jpeg_set_quality(&sp
->cinfo
.c
,sp
->jpegquality
,FALSE
))
855 || !CALLVJPEG(sp
,jpeg_suppress_tables(&sp
->cinfo
.c
,TRUE
))
861 if (qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[0]) qtbl
->sent_table
= FALSE
;
862 if (htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[0]) htbl
->sent_table
= FALSE
;
863 if (htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[0]) htbl
->sent_table
= FALSE
;
864 if (sp
->cinfo
.c
.jpeg_color_space
== JCS_YCbCr
)
866 if (qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[1])
867 qtbl
->sent_table
= FALSE
;
868 if (htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[1])
869 htbl
->sent_table
= FALSE
;
870 if (htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[1])
871 htbl
->sent_table
= FALSE
;
873 if ( TIFFojpeg_tables_dest(sp
,tif
)
874 && CALLVJPEG(sp
,jpeg_write_tables(&sp
->cinfo
.c
))
878 /* Mark the field "present". We can't use "TIFFSetField()" because
879 "BEENWRITING" is already set!
881 TIFFSetFieldBit(tif
,FIELD_JPEGTABLES
);
882 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
886 if ( sp
->cinfo
.c
.raw_data_in
887 && !alloc_downsampled_buffers(tif
,sp
->cinfo
.c
.comp_info
,
888 sp
->cinfo
.c
.num_components
)
890 if (status
== 0) return 0; /* If TIFF errors, don't bother to continue */
891 /* Grab parameters that are same for all strips/tiles. */
893 sp
->dest
.init_destination
= std_init_destination
;
894 sp
->dest
.empty_output_buffer
= std_empty_output_buffer
;
895 sp
->dest
.term_destination
= std_term_destination
;
896 sp
->cinfo
.c
.dest
= &sp
->dest
;
897 sp
->cinfo
.c
.data_precision
= td
->td_bitspersample
;
898 sp
->cinfo
.c
.write_JFIF_header
= /* Don't write extraneous markers */
899 sp
->cinfo
.c
.write_Adobe_marker
= FALSE
;
900 sp
->cinfo
.c
.image_width
= segment_width
;
901 sp
->cinfo
.c
.image_height
= segment_height
;
902 sp
->cinfo
.c
.comp_info
[0].h_samp_factor
=
903 sp
->cinfo
.c
.comp_info
[0].v_samp_factor
= 1;
904 return CALLVJPEG(sp
,jpeg_start_compress(&sp
->cinfo
.c
,FALSE
));
909 OJPEGPreEncode(register TIFF
*tif
,tsample_t s
)
910 { register OJPEGState
*sp
= OJState(tif
);
911 # define td (&tif->tif_dir)
913 /* If we are about to write the first row of an image plane, which should
914 coincide with a JPEG "scan", reset the JPEG Library's compressor. Otherwise
915 let the compressor run "as is" and return a "success" status without further
918 if ( (isTiled(tif
) ? tif
->tif_curtile
: tif
->tif_curstrip
)
919 % td
->td_stripsperimage
923 if ( (sp
->cinfo
.c
.comp_info
[0].component_id
= s
) == 1)
924 && sp
->cinfo
.c
.jpeg_color_space
== JCS_YCbCr
927 sp
->cinfo
.c
.comp_info
[0].quant_tbl_no
=
928 sp
->cinfo
.c
.comp_info
[0].dc_tbl_no
=
929 sp
->cinfo
.c
.comp_info
[0].ac_tbl_no
= 1;
930 sp
->cinfo
.c
.comp_info
[0].h_samp_factor
= sp
->h_sampling
;
931 sp
->cinfo
.c
.comp_info
[0].v_samp_factor
= sp
->v_sampling
;
933 /* Scale expected strip/tile size to match a downsampled component. */
935 sp
->cinfo
.c
.image_width
= TIFFhowmany(segment_width
,sp
->h_sampling
);
936 sp
->cinfo
.c
.image_height
=TIFFhowmany(segment_height
,sp
->v_sampling
);
938 sp
->scancount
= 0; /* Mark subsampling buffer(s) empty */
945 OJPEGPostEncode(register TIFF
*tif
)
946 { register OJPEGState
*sp
= OJState(tif
);
948 /* Finish up at the end of a strip or tile. */
950 if (sp
->scancount
> 0) /* emit partial buffer of down-sampled data */
953 # ifdef C_LOSSLESS_SUPPORTED
954 if ( sp
->scancount
< sp
->cinfo
.c
.data_unit
955 && sp
->cinfo
.c
.num_components
> 0
958 if (sp
->scancount
< DCTSIZE
&& sp
->cinfo
.c
.num_components
> 0)
960 { int ci
= 0, /* Pad the data vertically */
961 # ifdef C_LOSSLESS_SUPPORTED
962 size
= sp
->cinfo
.c
.data_unit
;
966 register jpeg_component_info
*compptr
= sp
->cinfo
.c
.comp_info
;
969 # ifdef C_LOSSLESS_SUPPORTED
970 { tsize_t row_width
= compptr
->width_in_data_units
972 tsize_t row_width
= compptr
->width_in_blocks
974 *size
*sizeof(JSAMPLE
);
975 int ypos
= sp
->scancount
*compptr
->v_samp_factor
;
977 do _TIFFmemcpy( (tdata_t
)sp
->ds_buffer
[ci
][ypos
]
978 , (tdata_t
)sp
->ds_buffer
[ci
][ypos
-1]
981 while (++ypos
< compptr
->v_samp_factor
*size
);
983 while (++compptr
,++ci
< sp
->cinfo
.c
.num_components
);
985 n
= sp
->cinfo
.c
.max_v_samp_factor
*size
;
986 if (CALLJPEG(sp
,-1,jpeg_write_raw_data(&sp
->cinfo
.c
,sp
->ds_buffer
,n
)) != n
)
989 return CALLVJPEG(sp
,jpeg_finish_compress(&sp
->cinfo
.c
));
993 /* JPEG Decoding begins here. */
995 /*ARGSUSED*/ static int
996 OJPEGDecode(register TIFF
*tif
,tidata_t buf
,tsize_t cc
,tsample_t s
)
997 { tsize_t bytesperline
= isTiled(tif
)
998 ? TIFFTileRowSize(tif
)
999 : tif
->tif_scanlinesize
,
1000 rows
; /* No. of unprocessed rows in file */
1001 register OJPEGState
*sp
= OJState(tif
);
1003 /* Decode a chunk of pixels, where the input data has not NOT been down-
1004 sampled, or else the TIFF Library's client has used the "JPEGColorMode" TIFF
1005 pseudo-tag to request that the JPEG Library do color-space conversion; this
1006 is the normal case. The data is expected to be read in scan-line multiples,
1007 and this subroutine is called for both pixel-interleaved and separate color
1010 WARNING: Unlike "OJPEGDecodeRawContig()", below, the no. of Bytes in each
1011 decoded row is calculated here as "bytesperline" instead of
1012 using "sp->bytesperline", which might be a little smaller. This can
1013 occur for an old tiled image whose width isn't a multiple of 8 pixels.
1014 That's illegal according to the TIFF Version 6 specification, but some
1015 test files, like "zackthecat.tif", were built that way. In those cases,
1016 we want to embed the image's true width in our caller's buffer (which is
1017 presumably allocated according to the expected tile width) by
1018 effectively "padding" it with unused Bytes at the end of each row.
1020 if ( (cc
/= bytesperline
) /* No. of complete rows in caller's buffer */
1021 > (rows
= sp
->cinfo
.d
.output_height
- sp
->cinfo
.d
.output_scanline
)
1025 if ( CALLJPEG(sp
,-1,jpeg_read_scanlines(&sp
->cinfo
.d
,(JSAMPARRAY
)&buf
,1))
1028 buf
+= bytesperline
;
1032 /* BEWARE OF KLUDGE: If our input file was produced by Microsoft's Wang
1033 Imaging for Windows application, the DC coefficients of
1034 each JPEG image component (Y,Cb,Cr) must be reset at the end of each TIFF
1035 "strip", and any JPEG data bits remaining in the current Byte of the
1036 decoder's input buffer must be discarded. To do so, we create an "ad hoc"
1037 interface in the "jdhuff.c" module of IJG JPEG Library Version 6 (module
1038 "jdshuff.c", if Ken Murchison's lossless-Huffman patch is applied), and we
1039 invoke that interface here after decoding each "strip".
1041 if (sp
->is_WANG
) jpeg_reset_huff_decode(&sp
->cinfo
.d
);
1045 /*ARGSUSED*/ static int
1046 OJPEGDecodeRawContig(register TIFF
*tif
,tidata_t buf
,tsize_t cc
,tsample_t s
)
1047 { tsize_t rows
; /* No. of unprocessed rows in file */
1048 JDIMENSION lines_per_MCU
, size
;
1049 register OJPEGState
*sp
= OJState(tif
);
1051 /* Decode a chunk of pixels, where the input data has pixel-interleaved color
1052 planes, some of which have been down-sampled, but the TIFF Library's client
1053 has NOT used the "JPEGColorMode" TIFF pseudo-tag to request that the JPEG
1054 Library do color-space conversion. In other words, we must up-sample/
1055 expand/duplicate image components according to the image's sampling factors,
1056 without changing its color space. The data is expected to be read in scan-
1059 if ( (cc
/= sp
->bytesperline
) /* No. of complete rows in caller's buffer */
1060 > (rows
= sp
->cinfo
.d
.output_height
- sp
->cinfo
.d
.output_scanline
)
1062 lines_per_MCU
= sp
->cinfo
.d
.max_v_samp_factor
1063 # ifdef D_LOSSLESS_SUPPORTED
1064 * (size
= sp
->cinfo
.d
.min_codec_data_unit
);
1069 { int clumpoffset
, ci
;
1070 register jpeg_component_info
*compptr
;
1072 if (sp
->scancount
>= size
) /* reload downsampled-data buffers */
1074 if ( CALLJPEG(sp
,-1,jpeg_read_raw_data(&sp
->cinfo
.d
,sp
->ds_buffer
,lines_per_MCU
))
1080 /* The fastest way to separate the data is: make 1 pass over the scan
1081 line for each row of each component.
1083 clumpoffset
= ci
= 0;
1084 compptr
= sp
->cinfo
.d
.comp_info
;
1088 if (compptr
->h_samp_factor
== 1) /* fast path */
1090 { register JSAMPLE
*inptr
=
1091 sp
->ds_buffer
[ci
][sp
->scancount
*compptr
->v_samp_factor
+ypos
],
1092 *outptr
= (JSAMPLE
*)buf
+ clumpoffset
;
1093 register int clumps_per_line
= compptr
->downsampled_width
;
1095 do *outptr
= *inptr
++;
1096 while ((outptr
+= sp
->samplesperclump
),--clumps_per_line
> 0);
1098 while ( (clumpoffset
+= compptr
->h_samp_factor
)
1099 , ++ypos
< compptr
->v_samp_factor
1101 else /* general case */
1103 { register JSAMPLE
*inptr
=
1104 sp
->ds_buffer
[ci
][sp
->scancount
*compptr
->v_samp_factor
+ypos
],
1105 *outptr
= (JSAMPLE
*)buf
+ clumpoffset
;
1106 register int clumps_per_line
= compptr
->downsampled_width
;
1109 { register int xpos
= 0;
1111 do outptr
[xpos
] = *inptr
++;
1112 while (++xpos
< compptr
->h_samp_factor
);
1114 while ((outptr
+= sp
->samplesperclump
),--clumps_per_line
> 0);
1116 while ( (clumpoffset
+= compptr
->h_samp_factor
)
1117 , ++ypos
< compptr
->v_samp_factor
1120 while (++compptr
,++ci
< sp
->cinfo
.d
.num_components
);
1122 buf
+= sp
->bytesperline
;
1126 /* BEWARE OF KLUDGE: If our input file was produced by Microsoft's Wang
1127 Imaging for Windows application, the DC coefficients of
1128 each JPEG image component (Y,Cb,Cr) must be reset at the end of each TIFF
1129 "strip", and any JPEG data bits remaining in the current Byte of the
1130 decoder's input buffer must be discarded. To do so, we create an "ad hoc"
1131 interface in the "jdhuff.c" module of IJG JPEG Library Version 6 (module
1132 "jdshuff.c", if Ken Murchison's lossless-Huffman patch is applied), and we
1133 invoke that interface here after decoding each "strip".
1135 if (sp
->is_WANG
) jpeg_reset_huff_decode(&sp
->cinfo
.d
);
1139 /*ARGSUSED*/ static int
1140 OJPEGDecodeRawSeparate(TIFF
*tif
,register tidata_t buf
,tsize_t cc
,tsample_t s
)
1141 { tsize_t rows
; /* No. of unprocessed rows in file */
1142 JDIMENSION lines_per_MCU
,
1143 size
, /* ...of MCU */
1144 v
; /* Component's vertical up-sampling ratio */
1145 register OJPEGState
*sp
= OJState(tif
);
1146 register jpeg_component_info
*compptr
= sp
->cinfo
.d
.comp_info
+ s
;
1148 /* Decode a chunk of pixels, where the input data has separate color planes,
1149 some of which have been down-sampled, but the TIFF Library's client has NOT
1150 used the "JPEGColorMode" TIFF pseudo-tag to request that the JPEG Library
1151 do color-space conversion. The data is expected to be read in scan-line
1154 v
= sp
->cinfo
.d
.max_v_samp_factor
/compptr
->v_samp_factor
;
1155 if ( (cc
/= compptr
->downsampled_width
) /* No. of rows in caller's buffer */
1156 > (rows
= (sp
->cinfo
.d
.output_height
-sp
->cinfo
.d
.output_scanline
+v
-1)/v
)
1157 ) cc
= rows
; /* No. of rows of "clumps" to read */
1158 lines_per_MCU
= sp
->cinfo
.d
.max_v_samp_factor
1159 # ifdef D_LOSSLESS_SUPPORTED
1160 * (size
= sp
->cinfo
.d
.min_codec_data_unit
);
1164 L
: if (sp
->scancount
>= size
) /* reload downsampled-data buffers */
1166 if ( CALLJPEG(sp
,-1,jpeg_read_raw_data(&sp
->cinfo
.d
,sp
->ds_buffer
,lines_per_MCU
))
1173 { register JSAMPLE
*inptr
=
1174 sp
->ds_buffer
[s
][sp
->scancount
*compptr
->v_samp_factor
+ rows
];
1175 register int clumps_per_line
= compptr
->downsampled_width
;
1177 do *buf
++ = *inptr
++; while (--clumps_per_line
> 0); /* Copy scanline */
1179 if (--cc
<= 0) return 1; /* End of caller's buffer? */
1181 while (++rows
< compptr
->v_samp_factor
);
1186 /* "OJPEGSetupDecode()" temporarily forces the JPEG Library to use the following
1187 subroutine as a "dummy" input reader in order to fool the library into
1188 thinking that it has read the image's first "Start of Scan" (SOS) marker, so
1189 that it initializes accordingly.
1191 /*ARGSUSED*/ METHODDEF(int)
1192 fake_SOS_marker(j_decompress_ptr cinfo
){return JPEG_REACHED_SOS
;}
1194 /*ARGSUSED*/ METHODDEF(int)
1195 suspend(j_decompress_ptr cinfo
){return JPEG_SUSPENDED
;}
1197 /* The JPEG Library's "null" color-space converter actually re-packs separate
1198 color planes (it's native image representation) into a pixel-interleaved,
1199 contiguous plane. But if our TIFF Library client is tryng to process a
1200 PLANARCONFIG_SEPARATE image, we don't want that; so here are modifications of
1201 code in the JPEG Library's "jdcolor.c" file, which simply copy Bytes to a
1202 color plane specified by the current JPEG "scan".
1205 ycc_rgb_convert(register j_decompress_ptr cinfo
,JSAMPIMAGE in
,JDIMENSION row
,
1206 register JSAMPARRAY out
,register int nrows
)
1207 { typedef struct /* "jdcolor.c" color-space conversion state */
1210 /* WARNING: This declaration is ugly and dangerous! It's supposed to be
1211 private to the JPEG Library's "jdcolor.c" module, but we also
1212 need it here. Since the library's copy might change without notice, be
1213 sure to keep this one synchronized or the following code will break!
1215 struct jpeg_color_deconverter pub
; /* Public fields */
1216 /* Private state for YCC->RGB conversion */
1217 int *Cr_r_tab
, /* ->Cr to R conversion table */
1218 *Cb_b_tab
; /* ->Cb to B conversion table */
1219 INT32
*Cr_g_tab
, /* ->Cr to G conversion table */
1220 *Cb_g_tab
; /* ->Cb to G conversion table */
1222 my_cconvert_ptr cconvert
= (my_cconvert_ptr
)cinfo
->cconvert
;
1223 JSAMPARRAY irow0p
= in
[0] + row
;
1224 register JSAMPLE
*range_limit
= cinfo
->sample_range_limit
;
1225 register JSAMPROW outp
, Y
;
1227 switch (cinfo
->output_scan_number
- 1)
1228 { JSAMPARRAY irow1p
, irow2p
;
1229 register INT32
*table0
, *table1
;
1232 case RGB_RED
: irow2p
= in
[2] + row
;
1233 table0
= (INT32
*)cconvert
->Cr_r_tab
;
1234 while (--nrows
>= 0)
1235 { register JSAMPROW Cr
= *irow2p
++;
1236 register int i
= cinfo
->output_width
;
1241 *outp
++ = range_limit
[*Y
++ + table0
[*Cr
++]];
1244 case RGB_GREEN
: irow1p
= in
[1] + row
;
1245 irow2p
= in
[2] + row
;
1246 table0
= cconvert
->Cb_g_tab
;
1247 table1
= cconvert
->Cr_g_tab
;
1248 while (--nrows
>= 0)
1249 { register JSAMPROW Cb
= *irow1p
++,
1251 register int i
= cinfo
->output_width
;
1258 + RIGHT_SHIFT(table0
[*Cb
++]+table1
[*Cr
++],16)
1262 case RGB_BLUE
: irow1p
= in
[1] + row
;
1263 table0
= (INT32
*)cconvert
->Cb_b_tab
;
1264 while (--nrows
>= 0)
1265 { register JSAMPROW Cb
= *irow1p
++;
1266 register int i
= cinfo
->output_width
;
1271 *outp
++ = range_limit
[*Y
++ + table0
[*Cb
++]];
1277 null_convert(register j_decompress_ptr cinfo
,JSAMPIMAGE in
,JDIMENSION row
,
1278 register JSAMPARRAY out
,register int nrows
)
1279 { register JSAMPARRAY irowp
= in
[cinfo
->output_scan_number
- 1] + row
;
1281 while (--nrows
>= 0) _TIFFmemcpy(*out
++,*irowp
++,cinfo
->output_width
);
1285 OJPEGSetupDecode(register TIFF
*tif
)
1286 { static char module[]={"OJPEGSetupDecode"};
1287 J_COLOR_SPACE jpeg_color_space
, /* Color space of JPEG-compressed image */
1288 out_color_space
; /* Color space of decompressed image */
1289 uint32 segment_width
;
1290 int status
= 1; /* Assume success by default */
1291 boolean downsampled_output
=FALSE
, /* <=> Want JPEG Library's "raw" image? */
1292 is_JFIF
; /* <=> JFIF image? */
1293 register OJPEGState
*sp
= OJState(tif
);
1294 # define td (&tif->tif_dir)
1296 /* Verify miscellaneous parameters. This will need work if the TIFF Library
1297 ever supports different depths for different components, or if the JPEG
1298 Library ever supports run-time depth selection. Neither seems imminent.
1300 if (td
->td_bitspersample
!= sp
->cinfo
.d
.data_precision
)
1302 TIFFError(module,bad_bps
,td
->td_bitspersample
);
1306 /* The TIFF Version 6.0 specification and IJG JPEG Library accept different
1307 sets of color spaces, so verify that our image belongs to the common subset
1308 and map its photometry code, then initialize to handle subsampling and
1309 optional JPEG Library YCbCr <-> RGB color-space conversion.
1311 switch (td
->td_photometric
)
1313 case PHOTOMETRIC_YCBCR
:
1315 /* ISO IS 10918-1 requires that JPEG subsampling factors be 1-4, but
1316 TIFF Version 6.0 is more restrictive: only 1, 2, and 4 are allowed.
1318 if ( ( td
->td_ycbcrsubsampling
[0] == 1
1319 || td
->td_ycbcrsubsampling
[0] == 2
1320 || td
->td_ycbcrsubsampling
[0] == 4
1322 && ( td
->td_ycbcrsubsampling
[1] == 1
1323 || td
->td_ycbcrsubsampling
[1] == 2
1324 || td
->td_ycbcrsubsampling
[1] == 4
1327 downsampled_output
=
1329 (sp
->h_sampling
= td
->td_ycbcrsubsampling
[0]) << 3
1330 | (sp
->v_sampling
= td
->td_ycbcrsubsampling
[1])
1334 TIFFError(module,bad_subsampling
);
1337 jpeg_color_space
= JCS_YCbCr
;
1338 if (sp
->jpegcolormode
== JPEGCOLORMODE_RGB
)
1340 downsampled_output
= FALSE
;
1341 out_color_space
= JCS_RGB
;
1345 case PHOTOMETRIC_MINISBLACK
:
1346 jpeg_color_space
= JCS_GRAYSCALE
;
1348 case PHOTOMETRIC_RGB
:
1349 jpeg_color_space
= JCS_RGB
;
1351 case PHOTOMETRIC_SEPARATED
:
1352 jpeg_color_space
= JCS_CMYK
;
1353 L1
: sp
->jpegcolormode
= JPEGCOLORMODE_RAW
; /* No JPEG Lib. conversion */
1354 L2
: out_color_space
= jpeg_color_space
;
1357 TIFFError(module,bad_photometry
,td
->td_photometric
);
1360 if (status
== 0) return 0; /* If TIFF errors, don't bother to continue */
1362 /* Set parameters that are same for all strips/tiles. */
1364 sp
->cinfo
.d
.src
= &sp
->src
;
1365 sp
->src
.init_source
= std_init_source
;
1366 sp
->src
.fill_input_buffer
= std_fill_input_buffer
;
1367 sp
->src
.skip_input_data
= std_skip_input_data
;
1368 sp
->src
.resync_to_restart
= jpeg_resync_to_restart
;
1369 sp
->src
.term_source
= std_term_source
;
1371 /* BOGOSITY ALERT! The Wang Imaging application for Microsoft Windows produces
1372 images containing "JPEGInterchangeFormat[Length]" TIFF
1373 records that resemble JFIF-in-TIFF encapsulations but, in fact, violate the
1374 TIFF Version 6 specification in several ways; nevertheless, we try to handle
1375 them gracefully because there are apparently a lot of them around. The
1376 purported "JFIF" data stream in one of these files vaguely resembles a JPEG
1377 "tables only" data stream, except that there's no trailing EOI marker. The
1378 rest of the JPEG data stream lies in a discontiguous file region, identified
1379 by the 0th Strip offset (which is *also* illegal!), where it begins with an
1380 SOS marker and apparently continues to the end of the file. There is no
1381 trailing EOI marker here, either.
1383 is_JFIF
= !sp
->is_WANG
&& TIFFFieldSet(tif
,FIELD_JPEGIFOFFSET
);
1385 /* Initialize decompression parameters that won't be overridden by JPEG Library
1386 defaults set during the "jpeg_read_header()" call, below.
1388 segment_width
= td
->td_imagewidth
;
1391 if (sp
->is_WANG
) /* we don't know how to handle it */
1393 TIFFError(module,"Tiled Wang image not supported");
1397 /* BOGOSITY ALERT! "TIFFTileRowSize()" seems to work fine for modern JPEG-
1398 in-TIFF encapsulations where the image width--like the
1399 tile width--is a multiple of 8 or 16 pixels. But image widths and
1400 heights are aren't restricted to 8- or 16-bit multiples, and we need
1401 the exact Byte count of decompressed scan lines when we call the JPEG
1402 Library. At least one old file ("zackthecat.tif") in the TIFF Library
1403 test suite has widths and heights slightly less than the tile sizes, and
1404 it apparently used the bogus computation below to determine the number
1405 of Bytes per scan line (was this due to an old, broken version of
1406 "TIFFhowmany()"?). Before we get here, "OJPEGSetupDecode()" verified
1407 that our image uses 8-bit samples, so the following check appears to
1408 return the correct answer in all known cases tested to date.
1410 if (is_JFIF
|| (segment_width
& 7) == 0)
1411 sp
->bytesperline
= TIFFTileRowSize(tif
); /* Normal case */
1414 /* Was the file-encoder's segment-width calculation bogus? */
1415 segment_width
= (segment_width
/sp
->h_sampling
+ 1) * sp
->h_sampling
;
1416 sp
->bytesperline
= segment_width
* td
->td_samplesperpixel
;
1419 else sp
->bytesperline
= TIFFVStripSize(tif
,1);
1421 /* BEWARE OF KLUDGE: If we have JPEG Interchange File Format (JFIF) image,
1422 then we want to read "metadata" in the bit-stream's
1423 header and validate it against corresponding information in TIFF records.
1424 But if we have a *really old* JPEG file that's not JFIF, then we simply
1425 assign TIFF-record values to JPEG Library variables without checking.
1427 if (is_JFIF
) /* JFIF image */
1428 { unsigned char *end_of_data
;
1429 int subsampling_factors
;
1430 register unsigned char *p
;
1433 /* WARNING: Although the image file contains a JFIF bit stream, it might
1434 also contain some old TIFF records causing "OJPEGVSetField()"
1435 to have allocated quantization or Huffman decoding tables. But when the
1436 JPEG Library reads and parses the JFIF header below, it reallocate these
1437 tables anew without checking for "dangling" pointers, thereby causing a
1438 memory "leak". We have enough information to potentially deallocate the
1439 old tables here, but unfortunately JPEG Library Version 6B uses a "pool"
1440 allocator for small objects, with no deallocation procedure; instead, it
1441 reclaims a whole pool when an image is closed/destroyed, so well-behaved
1442 TIFF client applications (i.e., those which close their JPEG images as
1443 soon as they're no longer needed) will waste memory for a short time but
1444 recover it eventually. But ill-behaved TIFF clients (i.e., those which
1445 keep many JPEG images open gratuitously) can exhaust memory prematurely.
1446 If the JPEG Library ever implements a deallocation procedure, insert
1450 if (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
) /* free quant. tables */
1451 { register int i
= 0;
1454 { register JQUANT_TBL
*q
;
1456 if (q
= sp
->cinfo
.d
.quant_tbl_ptrs
[i
])
1458 jpeg_free_small(&sp
->cinfo
.comm
,q
,sizeof *q
);
1459 sp
->cinfo
.d
.quant_tbl_ptrs
[i
] = 0;
1462 while (++i
< NUM_QUANT_TBLS
);
1464 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
) /* free Huffman tables */
1465 { register int i
= 0;
1468 { register JHUFF_TBL
*h
;
1470 if (h
= sp
->cinfo
.d
.dc_huff_tbl_ptrs
[i
])
1472 jpeg_free_small(&sp
->cinfo
.comm
,h
,sizeof *h
);
1473 sp
->cinfo
.d
.dc_huff_tbl_ptrs
[i
] = 0;
1475 if (h
= sp
->cinfo
.d
.ac_huff_tbl_ptrs
[i
])
1477 jpeg_free_small(&sp
->cinfo
.comm
,h
,sizeof *h
);
1478 sp
->cinfo
.d
.ac_huff_tbl_ptrs
[i
] = 0;
1481 while (++i
< NUM_HUFF_TBLS
);
1483 # endif /* someday */
1485 /* Since we might someday wish to try rewriting "old format" JPEG-in-TIFF
1486 encapsulations in "new format" files, try to synthesize the value of a
1487 modern "JPEGTables" TIFF record by scanning the JPEG data from just past
1488 the "Start of Information" (SOI) marker until something other than a
1489 legitimate "table" marker is found, as defined in ISO IS 10918-1
1490 Appending B.2.4; namely:
1492 -- Define Quantization Table (DQT)
1493 -- Define Huffman Table (DHT)
1494 -- Define Arithmetic Coding table (DAC)
1495 -- Define Restart Interval (DRI)
1497 -- Application data (APPn)
1499 For convenience, we also accept "Expansion" (EXP) markers, although they
1500 are apparently not a part of normal "table" data.
1502 sp
->jpegtables
= p
= (unsigned char *)sp
->src
.next_input_byte
;
1503 end_of_data
= p
+ sp
->src
.bytes_in_buffer
;
1505 while (p
< end_of_data
&& p
[0] == 0xFF)
1509 case 0xC0: /* SOF0 */
1510 case 0xC1: /* SOF1 */
1511 case 0xC2: /* SOF2 */
1512 case 0xC3: /* SOF3 */
1513 case 0xC4: /* DHT */
1514 case 0xC5: /* SOF5 */
1515 case 0xC6: /* SOF6 */
1516 case 0xC7: /* SOF7 */
1517 case 0xC9: /* SOF9 */
1518 case 0xCA: /* SOF10 */
1519 case 0xCB: /* SOF11 */
1520 case 0xCC: /* DAC */
1521 case 0xCD: /* SOF13 */
1522 case 0xCE: /* SOF14 */
1523 case 0xCF: /* SOF15 */
1524 case 0xDB: /* DQT */
1525 case 0xDD: /* DRI */
1526 case 0xDF: /* EXP */
1527 case 0xE0: /* APP0 */
1528 case 0xE1: /* APP1 */
1529 case 0xE2: /* APP2 */
1530 case 0xE3: /* APP3 */
1531 case 0xE4: /* APP4 */
1532 case 0xE5: /* APP5 */
1533 case 0xE6: /* APP6 */
1534 case 0xE7: /* APP7 */
1535 case 0xE8: /* APP8 */
1536 case 0xE9: /* APP9 */
1537 case 0xEA: /* APP10 */
1538 case 0xEB: /* APP11 */
1539 case 0xEC: /* APP12 */
1540 case 0xED: /* APP13 */
1541 case 0xEE: /* APP14 */
1542 case 0xEF: /* APP15 */
1543 case 0xFE: /* COM */
1544 p
+= (p
[2] << 8 | p
[3]) + 2;
1546 L
: if (p
- (unsigned char *)sp
->jpegtables
> 2) /* fake "JPEGTables" */
1549 /* In case our client application asks, pretend that this image file
1550 contains a modern "JPEGTables" TIFF record by copying to a buffer
1551 the initial part of the JFIF bit-stream that we just scanned, from
1552 the SOI marker through the "metadata" tables, then append an EOI
1553 marker and flag the "JPEGTables" TIFF record as "present".
1555 sp
->jpegtables_length
= p
- (unsigned char*)sp
->jpegtables
+ 2;
1557 if (!(sp
->jpegtables
= _TIFFmalloc(sp
->jpegtables_length
)))
1559 TIFFError(module,no_jtable_space
);
1562 _TIFFmemcpy(sp
->jpegtables
,p
,sp
->jpegtables_length
-2);
1563 p
= (unsigned char *)sp
->jpegtables
+ sp
->jpegtables_length
;
1564 p
[-2] = 0xFF; p
[-1] = JPEG_EOI
; /* Append EOI marker */
1565 TIFFSetFieldBit(tif
,FIELD_JPEGTABLES
);
1566 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1568 else sp
->jpegtables
= 0; /* Don't simulate "JPEGTables" */
1569 if ( CALLJPEG(sp
,-1,jpeg_read_header(&sp
->cinfo
.d
,TRUE
))
1572 if ( sp
->cinfo
.d
.image_width
!= segment_width
1573 || sp
->cinfo
.d
.image_height
!= td
->td_imagelength
1576 TIFFError(module,"Improper JPEG strip/tile size");
1579 if (sp
->cinfo
.d
.num_components
!= td
->td_samplesperpixel
)
1581 TIFFError(module,"Improper JPEG component count");
1584 if (sp
->cinfo
.d
.data_precision
!= td
->td_bitspersample
)
1586 TIFFError(module,"Improper JPEG data precision");
1590 /* Check that JPEG image components all have the same subsampling factors
1591 declared (or defaulted) in the TIFF file, since TIFF Version 6.0 is more
1592 restrictive than JPEG: Only the 0th component may have horizontal and
1593 vertical subsampling factors other than <1,1>.
1595 subsampling_factors
= sp
->h_sampling
<< 3 | sp
->v_sampling
;
1599 if ( ( sp
->cinfo
.d
.comp_info
[i
].h_samp_factor
<< 3
1600 | sp
->cinfo
.d
.comp_info
[i
].v_samp_factor
1602 != subsampling_factors
1605 TIFFError(module,"Improper JPEG subsampling factors");
1608 subsampling_factors
= 011; /* Required for image components > 0 */
1610 while (++i
< sp
->cinfo
.d
.num_components
);
1612 else /* not JFIF image */
1613 { int (*save
)(j_decompress_ptr cinfo
) = sp
->cinfo
.d
.marker
->read_markers
;
1616 /* We're not assuming that this file's JPEG bit stream has any header
1617 "metadata", so fool the JPEG Library into thinking that we read a
1618 "Start of Input" (SOI) marker and a "Start of Frame" (SOFx) marker, then
1619 force it to read a simulated "Start of Scan" (SOS) marker when we call
1620 "jpeg_read_header()" below. This should cause the JPEG Library to
1621 establish reasonable defaults.
1623 sp
->cinfo
.d
.marker
->saw_SOI
= /* Pretend we saw SOI marker */
1624 sp
->cinfo
.d
.marker
->saw_SOF
= TRUE
; /* Pretend we saw SOF marker */
1625 sp
->cinfo
.d
.marker
->read_markers
=
1626 sp
->is_WANG
? suspend
: fake_SOS_marker
;
1627 sp
->cinfo
.d
.global_state
= DSTATE_INHEADER
;
1628 sp
->cinfo
.d
.Se
= DCTSIZE2
-1; /* Suppress JPEG Library warning */
1629 sp
->cinfo
.d
.image_width
= segment_width
;
1630 sp
->cinfo
.d
.image_height
= td
->td_imagelength
;
1632 /* The following color-space initialization, including the complicated
1633 "switch"-statement below, essentially duplicates the logic used by the
1634 JPEG Library's "jpeg_init_colorspace()" subroutine during compression.
1636 sp
->cinfo
.d
.num_components
= td
->td_samplesperpixel
;
1637 sp
->cinfo
.d
.comp_info
= (jpeg_component_info
*)
1638 (*sp
->cinfo
.d
.mem
->alloc_small
)
1641 , sp
->cinfo
.d
.num_components
* sizeof *sp
->cinfo
.d
.comp_info
1646 sp
->cinfo
.d
.comp_info
[i
].component_index
= i
;
1647 sp
->cinfo
.d
.comp_info
[i
].component_needed
= TRUE
;
1648 sp
->cinfo
.d
.cur_comp_info
[i
] = &sp
->cinfo
.d
.comp_info
[i
];
1650 while (++i
< sp
->cinfo
.d
.num_components
);
1651 switch (jpeg_color_space
)
1657 sp
->cinfo
.d
.comp_info
[i
].component_id
= i
;
1658 sp
->cinfo
.d
.comp_info
[i
].h_samp_factor
=
1659 sp
->cinfo
.d
.comp_info
[i
].v_samp_factor
= 1;
1661 while (++i
< sp
->cinfo
.d
.num_components
);
1664 sp
->cinfo
.d
.comp_info
[0].component_id
=
1665 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
=
1666 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
= 1;
1669 sp
->cinfo
.d
.comp_info
[0].component_id
= 'R';
1670 sp
->cinfo
.d
.comp_info
[1].component_id
= 'G';
1671 sp
->cinfo
.d
.comp_info
[2].component_id
= 'B';
1673 do sp
->cinfo
.d
.comp_info
[i
].h_samp_factor
=
1674 sp
->cinfo
.d
.comp_info
[i
].v_samp_factor
= 1;
1675 while (++i
< sp
->cinfo
.d
.num_components
);
1678 sp
->cinfo
.d
.comp_info
[0].component_id
= 'C';
1679 sp
->cinfo
.d
.comp_info
[1].component_id
= 'M';
1680 sp
->cinfo
.d
.comp_info
[2].component_id
= 'Y';
1681 sp
->cinfo
.d
.comp_info
[3].component_id
= 'K';
1683 do sp
->cinfo
.d
.comp_info
[i
].h_samp_factor
=
1684 sp
->cinfo
.d
.comp_info
[i
].v_samp_factor
= 1;
1685 while (++i
< sp
->cinfo
.d
.num_components
);
1691 sp
->cinfo
.d
.comp_info
[i
].component_id
= i
+1;
1692 sp
->cinfo
.d
.comp_info
[i
].h_samp_factor
=
1693 sp
->cinfo
.d
.comp_info
[i
].v_samp_factor
= 1;
1694 sp
->cinfo
.d
.comp_info
[i
].quant_tbl_no
=
1695 sp
->cinfo
.d
.comp_info
[i
].dc_tbl_no
=
1696 sp
->cinfo
.d
.comp_info
[i
].ac_tbl_no
= i
> 0;
1698 while (++i
< sp
->cinfo
.d
.num_components
);
1699 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
= sp
->h_sampling
;
1700 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
= sp
->v_sampling
;
1702 sp
->cinfo
.d
.comps_in_scan
= td
->td_planarconfig
== PLANARCONFIG_CONTIG
1703 ? sp
->cinfo
.d
.num_components
1705 i
= CALLJPEG(sp
,-1,jpeg_read_header(&sp
->cinfo
.d
,!sp
->is_WANG
));
1706 sp
->cinfo
.d
.marker
->read_markers
= save
; /* Restore input method */
1707 if (sp
->is_WANG
) /* produced by Wang Imaging on Microsoft Windows */
1709 if (i
!= JPEG_SUSPENDED
) return 0;
1711 /* BOGOSITY ALERT! Files prooduced by the Wang Imaging application for
1712 Microsoft Windows are a special--and, technically
1713 illegal--case. A JPEG SOS marker and rest of the data stream should
1714 be located at the end of the file, in a position identified by the
1717 i
= td
->td_nstrips
- 1;
1718 sp
->src
.next_input_byte
= tif
->tif_base
+ td
->td_stripoffset
[0];
1719 sp
->src
.bytes_in_buffer
= td
->td_stripoffset
[i
] -
1720 td
->td_stripoffset
[0] + td
->td_stripbytecount
[i
];
1721 i
= CALLJPEG(sp
,-1,jpeg_read_header(&sp
->cinfo
.d
,TRUE
));
1723 if (i
!= JPEG_HEADER_OK
) return 0;
1726 /* Some of our initialization must wait until the JPEG Library is initialized
1727 above, in order to override its defaults.
1729 if ( (sp
->cinfo
.d
.raw_data_out
= downsampled_output
)
1730 && !alloc_downsampled_buffers(tif
,sp
->cinfo
.d
.comp_info
,
1731 sp
->cinfo
.d
.num_components
)
1733 sp
->cinfo
.d
.jpeg_color_space
= jpeg_color_space
;
1734 sp
->cinfo
.d
.out_color_space
= out_color_space
;
1735 sp
->cinfo
.d
.dither_mode
= JDITHER_NONE
; /* Reduce image "noise" */
1736 sp
->cinfo
.d
.two_pass_quantize
= FALSE
;
1738 /* If the image consists of separate, discontiguous TIFF "samples" (= color
1739 planes, hopefully = JPEG "scans"), then we must use the JPEG Library's
1740 "buffered image" mode to decompress the entire image into temporary buffers,
1741 because the JPEG Library must parse the entire JPEG bit-stream in order to
1742 be satsified that it has a complete set of color components for each pixel,
1743 but the TIFF Library must allow our client to extract 1 component at a time.
1744 Initializing the JPEG Library's "buffered image" mode is tricky: First, we
1745 start its decompressor, then we tell the decompressor to "consume" (i.e.,
1746 buffer) the entire bit-stream.
1748 WARNING: Disabling "fancy" up-sampling seems to slightly reduce "noise" for
1749 certain old Wang Imaging files, but it absolutely *must* be
1750 enabled if the image has separate color planes, since in that case, the JPEG
1751 Library doesn't use an "sp->cinfo.d.cconvert" structure (so de-referencing
1752 this pointer below will cause a fatal crash) but writing our own code to up-
1753 sample separate color planes is too much work for right now. Maybe someday?
1755 sp
->cinfo
.d
.do_fancy_upsampling
= /* Always let this default (to TRUE)? */
1756 sp
->cinfo
.d
.buffered_image
= td
->td_planarconfig
== PLANARCONFIG_SEPARATE
;
1757 if (!CALLJPEG(sp
,0,jpeg_start_decompress(&sp
->cinfo
.d
))) return 0;
1758 if (sp
->cinfo
.d
.buffered_image
) /* separate color planes */
1760 if (sp
->cinfo
.d
.raw_data_out
)
1761 tif
->tif_decoderow
= tif
->tif_decodestrip
= tif
->tif_decodetile
=
1762 OJPEGDecodeRawSeparate
;
1765 tif
->tif_decoderow
= tif
->tif_decodestrip
= tif
->tif_decodetile
=
1768 /* In JPEG Library Version 6B, color-space conversion isn't implemented
1769 for separate color planes, so we must do it ourself if our TIFF
1770 client doesn't want to:
1772 sp
->cinfo
.d
.cconvert
->color_convert
=
1773 sp
->cinfo
.d
.jpeg_color_space
== sp
->cinfo
.d
.out_color_space
1774 ? null_convert
: ycc_rgb_convert
;
1776 L3
: switch (CALLJPEG(sp
,0,jpeg_consume_input(&sp
->cinfo
.d
)))
1780 /* If no JPEG "End of Information" (EOI) marker is found when bit-
1781 stream parsing ends, check whether we have enough data to proceed
1782 before reporting an error.
1784 case JPEG_SUSPENDED
: if ( sp
->cinfo
.d
.input_scan_number
1785 *sp
->cinfo
.d
.image_height
1786 + sp
->cinfo
.d
.input_iMCU_row
1787 *sp
->cinfo
.d
.max_v_samp_factor
1788 # ifdef D_LOSSLESS_SUPPORTED
1789 *sp
->cinfo
.d
.data_units_in_MCU
1790 *sp
->cinfo
.d
.min_codec_data_unit
1792 *sp
->cinfo
.d
.blocks_in_MCU
1795 < td
->td_samplesperpixel
1796 *sp
->cinfo
.d
.image_height
1799 TIFFError(tif
->tif_name
,
1800 "Premature end of JPEG bit-stream");
1803 case JPEG_REACHED_EOI
: ;
1806 else /* pixel-interleaved color planes */
1807 tif
->tif_decoderow
= tif
->tif_decodestrip
= tif
->tif_decodetile
=
1808 downsampled_output
? OJPEGDecodeRawContig
: OJPEGDecode
;
1814 OJPEGPreDecode(register TIFF
*tif
,tsample_t s
)
1815 { register OJPEGState
*sp
= OJState(tif
);
1816 # define td (&tif->tif_dir)
1818 /* If we are about to read the first row of an image plane (hopefully, these
1819 are coincident with JPEG "scans"!), reset the JPEG Library's decompressor
1820 appropriately. Otherwise, let the decompressor run "as is" and return a
1821 "success" status without further ado.
1823 if ( (isTiled(tif
) ? tif
->tif_curtile
: tif
->tif_curstrip
)
1824 % td
->td_stripsperimage
1828 if ( sp
->cinfo
.d
.buffered_image
1829 && !CALLJPEG(sp
,0,jpeg_start_output(&sp
->cinfo
.d
,s
+1))
1831 sp
->cinfo
.d
.output_scanline
= 0;
1833 /* Mark subsampling buffers "empty". */
1835 # ifdef D_LOSSLESS_SUPPORTED
1836 sp
->scancount
= sp
->cinfo
.d
.min_codec_data_unit
;
1838 sp
->scancount
= DCTSIZE
;
1845 /*ARGSUSED*/ static void
1846 OJPEGPostDecode(register TIFF
*tif
,tidata_t buf
,tsize_t cc
)
1847 { register OJPEGState
*sp
= OJState(tif
);
1848 # define td (&tif->tif_dir)
1850 /* The JPEG Library decompressor has reached the end of a strip/tile. If this
1851 is the end of a TIFF image "sample" (= JPEG "scan") in a file with separate
1852 components (color planes), then end the "scan". If it ends the image's last
1853 sample/scan, then also stop the JPEG Library's decompressor.
1855 if (sp
->cinfo
.d
.output_scanline
>= sp
->cinfo
.d
.output_height
)
1857 if (sp
->cinfo
.d
.buffered_image
)
1858 CALLJPEG(sp
,-1,jpeg_finish_output(&sp
->cinfo
.d
)); /* End JPEG scan */
1859 if ( (isTiled(tif
) ? tif
->tif_curtile
: tif
->tif_curstrip
)
1861 ) CALLJPEG(sp
,0,jpeg_finish_decompress(&sp
->cinfo
.d
));
1867 OJPEGVSetField(register TIFF
*tif
,ttag_t tag
,va_list ap
)
1870 register OJPEGState
*sp
= OJState(tif
);
1871 # define td (&tif->tif_dir)
1874 uint32 code_count
=0;
1881 (*sp
->vsetparent
)(tif
,tag
,ap
);
1883 /* BEWARE OF KLUDGE: Some old-format JPEG-in-TIFF files, including those
1884 produced by the Wang Imaging application for Micro-
1885 soft Windows, illegally omit a "ReferenceBlackWhite" TIFF tag, even
1886 though the TIFF specification's default is intended for the RGB color
1887 space and is inappropriate for the YCbCr color space ordinarily used for
1888 JPEG images. Since many TIFF client applications request the value of
1889 this tag immediately after a TIFF image directory is parsed, and before
1890 any other code in this module receives control, we are forced to fix
1891 this problem very early in image-file processing. Fortunately, legal
1892 TIFF files are supposed to store their tags in numeric order, so a
1893 mandatory "PhotometricInterpretation" tag should always appear before
1894 an optional "ReferenceBlackWhite" tag. Hence, we slyly peek ahead when
1895 we discover the desired photometry, by installing modified black and
1896 white reference levels.
1898 case TIFFTAG_PHOTOMETRIC
:
1899 if ( (v32
= (*sp
->vsetparent
)(tif
,tag
,ap
))
1900 && td
->td_photometric
== PHOTOMETRIC_YCBCR
1904 if (!TIFFGetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
, &ref
)) {
1906 long top
= 1L << td
->td_bitspersample
;
1908 refbw
[1] = (float)(top
-1L);
1909 refbw
[2] = (float)(top
>>1);
1910 refbw
[3] = refbw
[1];
1911 refbw
[4] = refbw
[2];
1912 refbw
[5] = refbw
[1];
1913 TIFFSetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
, refbw
);
1918 /* BEWARE OF KLUDGE: According to Charles Auer <Bumble731@msn.com>, if our
1919 input is a multi-image (multi-directory) JPEG-in-TIFF
1920 file is produced by the Wang Imaging application on Microsoft Windows,
1921 for some reason the first directory excludes the vendor-specific "WANG
1922 PageControl" tag (32934) that we check below, so the only other way to
1923 identify these directories is apparently to look for a software-
1924 identification tag with the substring, "Wang Labs". Single-image files
1925 can apparently pass both tests, which causes no harm here, but what a
1928 case TIFFTAG_SOFTWARE
:
1932 v32
= (*sp
->vsetparent
)(tif
,tag
,ap
);
1933 if( TIFFGetField( tif
, TIFFTAG_SOFTWARE
, &software
)
1934 && strstr( software
, "Wang Labs" ) )
1939 case TIFFTAG_JPEGPROC
:
1940 case TIFFTAG_JPEGIFOFFSET
:
1941 case TIFFTAG_JPEGIFBYTECOUNT
:
1942 case TIFFTAG_JPEGRESTARTINTERVAL
:
1943 case TIFFTAG_JPEGLOSSLESSPREDICTORS
:
1944 case TIFFTAG_JPEGPOINTTRANSFORM
:
1945 case TIFFTAG_JPEGQTABLES
:
1946 case TIFFTAG_JPEGDCTABLES
:
1947 case TIFFTAG_JPEGACTABLES
:
1948 case TIFFTAG_WANG_PAGECONTROL
:
1949 case TIFFTAG_JPEGCOLORMODE
: ;
1951 v32
= va_arg(ap
,uint32
); /* No. of values in this TIFF record */
1953 /* This switch statement is added for OJPEGVSetField */
1956 case TIFFTAG_JPEGPROC
:
1959 case TIFFTAG_JPEGIFOFFSET
:
1960 sp
->jpegifoffset
=v32
;
1962 case TIFFTAG_JPEGIFBYTECOUNT
:
1963 sp
->jpegifbytecount
=v32
;
1965 case TIFFTAG_JPEGRESTARTINTERVAL
:
1966 sp
->jpegrestartinterval
=v32
;
1968 case TIFFTAG_JPEGLOSSLESSPREDICTORS
:
1969 sp
->jpeglosslesspredictors_length
=v32
;
1971 case TIFFTAG_JPEGPOINTTRANSFORM
:
1972 sp
->jpegpointtransform_length
=v32
;
1974 case TIFFTAG_JPEGQTABLES
:
1975 sp
->jpegqtables_length
=v32
;
1977 case TIFFTAG_JPEGACTABLES
:
1978 sp
->jpegactables_length
=v32
;
1980 case TIFFTAG_JPEGDCTABLES
:
1981 sp
->jpegdctables_length
=v32
;
1988 /* BEWARE: The following actions apply only if we are reading a "source" TIFF
1989 image to be decompressed for a client application program. If we
1990 ever enhance this file's CODEC to write "destination" JPEG-in-TIFF images,
1991 we'll need an "if"- and another "switch"-statement below, because we'll
1992 probably want to store these records' values in some different places. Most
1993 of these need not be parsed here in order to decode JPEG bit stream, so we
1994 set boolean flags to note that they have been seen, but we otherwise ignore
2000 /* Validate the JPEG-process code. */
2002 case TIFFTAG_JPEGPROC
:
2005 default : TIFFError(tif
->tif_name
,
2006 "Unknown JPEG process");
2008 # ifdef C_LOSSLESS_SUPPORTED
2010 /* Image uses (lossy) baseline sequential coding. */
2012 case JPEGPROC_BASELINE
: sp
->cinfo
.d
.process
= JPROC_SEQUENTIAL
;
2013 sp
->cinfo
.d
.data_unit
= DCTSIZE
;
2016 /* Image uses (lossless) Huffman coding. */
2018 case JPEGPROC_LOSSLESS
: sp
->cinfo
.d
.process
= JPROC_LOSSLESS
;
2019 sp
->cinfo
.d
.data_unit
= 1;
2020 # else /* not C_LOSSLESS_SUPPORTED */
2021 case JPEGPROC_LOSSLESS
: TIFFError(JPEGLib_name
,
2022 "Does not support lossless Huffman coding");
2024 case JPEGPROC_BASELINE
: ;
2025 # endif /* C_LOSSLESS_SUPPORTED */
2029 /* The TIFF Version 6.0 specification says that if the value of a TIFF
2030 "JPEGInterchangeFormat" record is 0, then we are to behave as if this
2031 record were absent; i.e., the data does *not* represent a JPEG Inter-
2032 change Format File (JFIF), so don't even set the boolean "I've been
2033 here" flag below. Otherwise, the field's value represents the file
2034 offset of the JPEG SOI marker.
2036 case TIFFTAG_JPEGIFOFFSET
:
2039 sp
->src
.next_input_byte
= tif
->tif_base
+ v32
;
2043 case TIFFTAG_JPEGIFBYTECOUNT
:
2044 sp
->src
.bytes_in_buffer
= v32
;
2047 /* The TIFF Version 6.0 specification says that if the JPEG "Restart"
2048 marker interval is 0, then the data has no "Restart" markers; i.e., we
2049 must behave as if this TIFF record were absent. So, don't even set the
2050 boolean "I've been here" flag below.
2053 * Instead, set the field bit so TIFFGetField can get whether or not
2056 case TIFFTAG_JPEGRESTARTINTERVAL
:
2058 sp
->cinfo
.d
.restart_interval
= v32
;
2060 /* The TIFF Version 6.0 specification says that this tag is supposed to be
2061 a vector containing a value for each image component, but for lossless
2062 Huffman coding (the only JPEG process defined by the specification for
2063 which this tag should be needed), ISO IS 10918-1 uses only a single
2064 value, equivalent to the "Ss" field in a JPEG bit-stream's "Start of
2065 Scan" (SOS) marker. So, we extract the first vector element and ignore
2066 the rest. (I hope this is correct!)
2068 case TIFFTAG_JPEGLOSSLESSPREDICTORS
:
2071 sp
->cinfo
.d
.Ss
= *va_arg(ap
,uint16
*);
2072 sp
->jpeglosslesspredictors
=
2073 _TIFFmalloc(sp
->jpeglosslesspredictors_length
2075 if(sp
->jpeglosslesspredictors
==NULL
){return(0);}
2076 for(i2
=0;i2
<sp
->jpeglosslesspredictors_length
;i2
++){
2077 ((uint16
*)sp
->jpeglosslesspredictors
)[i2
] =
2078 ((uint16
*)sp
->cinfo
.d
.Ss
)[i2
];
2080 sp
->jpeglosslesspredictors_length
*=sizeof(uint16
);
2085 /* The TIFF Version 6.0 specification says that this tag is supposed to be
2086 a vector containing a value for each image component, but for lossless
2087 Huffman coding (the only JPEG process defined by the specification for
2088 which this tag should be needed), ISO IS 10918-1 uses only a single
2089 value, equivalent to the "Al" field in a JPEG bit-stream's "Start of
2090 Scan" (SOS) marker. So, we extract the first vector element and ignore
2091 the rest. (I hope this is correct!)
2093 case TIFFTAG_JPEGPOINTTRANSFORM
:
2096 sp
->cinfo
.d
.Al
= *va_arg(ap
,uint16
*);
2097 sp
->jpegpointtransform
=
2098 _TIFFmalloc(sp
->jpegpointtransform_length
*sizeof(uint16
));
2099 if(sp
->jpegpointtransform
==NULL
){return(0);}
2100 for(i2
=0;i2
<sp
->jpegpointtransform_length
;i2
++) {
2101 ((uint16
*)sp
->jpegpointtransform
)[i2
] =
2102 ((uint16
*)sp
->cinfo
.d
.Al
)[i2
];
2104 sp
->jpegpointtransform_length
*=sizeof(uint16
);
2109 /* We have a vector of offsets to quantization tables, so load 'em! */
2111 case TIFFTAG_JPEGQTABLES
:
2115 if (v32
> NUM_QUANT_TBLS
)
2117 TIFFError(tif
->tif_name
,"Too many quantization tables");
2121 v
= va_arg(ap
,uint32
*);
2122 sp
->jpegqtables
=_TIFFmalloc(64*sp
->jpegqtables_length
);
2123 if(sp
->jpegqtables
==NULL
){return(0);}
2124 tiffoff
= TIFFSeekFile(tif
, 0, SEEK_CUR
);
2126 for(i2
=0;i2
<sp
->jpegqtables_length
;i2
++){
2127 TIFFSeekFile(tif
, v
[i2
], SEEK_SET
);
2128 TIFFReadFile(tif
, &(((unsigned char*)(sp
->jpegqtables
))[bufoff
]),
2132 sp
->jpegqtables_length
=bufoff
;
2133 TIFFSeekFile(tif
, tiffoff
, SEEK_SET
);
2135 do /* read quantization table */
2136 { register UINT8
*from
= tif
->tif_base
+ *v
++;
2137 register UINT16
*to
;
2138 register int j
= DCTSIZE2
;
2140 if (!( sp
->cinfo
.d
.quant_tbl_ptrs
[i
]
2141 = CALLJPEG(sp
,0,jpeg_alloc_quant_table(&sp
->cinfo
.comm
))
2145 TIFFError(JPEGLib_name
,"No space for quantization table");
2148 to
= sp
->cinfo
.d
.quant_tbl_ptrs
[i
]->quantval
;
2149 do *to
++ = *from
++; while (--j
> 0);
2152 sp
->jpegtablesmode
|= JPEGTABLESMODE_QUANT
;
2156 /* We have a vector of offsets to DC Huffman tables, so load 'em! */
2158 case TIFFTAG_JPEGDCTABLES
:
2159 h
= sp
->cinfo
.d
.dc_huff_tbl_ptrs
;
2162 /* We have a vector of offsets to AC Huffman tables, so load 'em! */
2164 case TIFFTAG_JPEGACTABLES
:
2165 h
= sp
->cinfo
.d
.ac_huff_tbl_ptrs
;
2169 if (v32
> NUM_HUFF_TBLS
)
2171 TIFFError(tif
->tif_name
,"Too many Huffman tables");
2174 v
= va_arg(ap
,uint32
*);
2175 if(tag
== TIFFTAG_JPEGDCTABLES
) {
2176 sp
->jpegdctables
=_TIFFmalloc(272*sp
->jpegdctables_length
);
2177 if(sp
->jpegdctables
==NULL
){return(0);}
2178 tiffoff
= TIFFSeekFile(tif
, 0, SEEK_CUR
);
2181 for(i2
=0;i2
<sp
->jpegdctables_length
;i2
++){
2182 TIFFSeekFile(tif
, v
[i2
], SEEK_SET
);
2184 &(((unsigned char*)(sp
->jpegdctables
))[bufoff
]),
2187 for(k2
=0;k2
<16;k2
++){
2188 code_count
+=((unsigned char*)(sp
->jpegdctables
))[k2
+bufoff
];
2191 &(((unsigned char*)(sp
->jpegdctables
))[bufoff
+16]),
2196 sp
->jpegdctables_length
=bufoff
;
2197 TIFFSeekFile(tif
, tiffoff
, SEEK_SET
);
2199 if(tag
==TIFFTAG_JPEGACTABLES
){
2200 sp
->jpegactables
=_TIFFmalloc(272*sp
->jpegactables_length
);
2201 if(sp
->jpegactables
==NULL
){return(0);}
2202 tiffoff
= TIFFSeekFile(tif
, 0, SEEK_CUR
);
2205 for(i2
=0;i2
<sp
->jpegactables_length
;i2
++){
2206 TIFFSeekFile(tif
, v
[i2
], SEEK_SET
);
2207 TIFFReadFile(tif
, &(((unsigned char*)(sp
->jpegactables
))[bufoff
]), 16);
2209 for(k2
=0;k2
<16;k2
++){
2210 code_count
+=((unsigned char*)(sp
->jpegactables
))[k2
+bufoff
];
2212 TIFFReadFile(tif
, &(((unsigned char*)(sp
->jpegactables
))[bufoff
+16]), code_count
);
2216 sp
->jpegactables_length
=bufoff
;
2217 TIFFSeekFile(tif
, tiffoff
, SEEK_SET
);
2220 do /* copy each Huffman table */
2222 register UINT8
*from
= tif
->tif_base
+ *v
++, *to
;
2223 register int j
= sizeof (*h
)->bits
;
2225 /* WARNING: This code relies on the fact that an image file not
2226 "memory mapped" was read entirely into a single
2227 buffer by "TIFFInitOJPEG()", so we can do a fast memory-to-
2228 memory copy here. Each table consists of 16 Bytes, which are
2229 suffixed to a 0 Byte when copied, followed by a variable
2230 number of Bytes whose length is the sum of the first 16.
2233 = CALLJPEG(sp
,0,jpeg_alloc_huff_table(&sp
->cinfo
.comm
))
2237 TIFFError(JPEGLib_name
,"No space for Huffman table");
2242 while (--j
> 0) size
+= *to
++ = *from
++; /* Copy 16 Bytes */
2243 if (size
> sizeof (*h
)->huffval
/sizeof *(*h
)->huffval
)
2245 TIFFError(tif
->tif_name
,"Huffman table too big");
2248 if ((j
= size
) > 0) do *to
++ = *from
++; while (--j
> 0);
2249 while (++size
<= sizeof (*h
)->huffval
/sizeof *(*h
)->huffval
)
2250 *to
++ = 0; /* Zero the rest of the table for cleanliness */
2253 sp
->jpegtablesmode
|= JPEGTABLESMODE_HUFF
;
2257 /* The following vendor-specific TIFF tag occurs in (highly illegal) files
2258 produced by the Wang Imaging application for Microsoft Windows. These
2259 can apparently have several "pages", in which case this tag specifies
2260 the offset of a "page control" structure, which we don't currently know
2261 how to handle. 0 indicates a 1-page image with no "page control", which
2262 we make a feeble effort to handle.
2264 case TIFFTAG_WANG_PAGECONTROL
:
2265 if (v32
== 0) v32
= -1;
2267 tag
= TIFFTAG_JPEGPROC
+FIELD_WANG_PAGECONTROL
-FIELD_JPEGPROC
;
2270 /* This pseudo tag indicates whether our caller is expected to do YCbCr <->
2271 RGB color-space conversion (JPEGCOLORMODE_RAW <=> 0) or whether we must
2272 ask the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1).
2274 case TIFFTAG_JPEGCOLORMODE
:
2275 sp
->jpegcolormode
= v32
;
2277 /* Mark the image to indicate whether returned data is up-sampled, so
2278 that "TIFF{Strip,Tile}Size()" reflect the true amount of data present.
2280 v32
= tif
->tif_flags
; /* Save flags temporarily */
2281 tif
->tif_flags
&= ~TIFF_UPSAMPLED
;
2282 if ( td
->td_photometric
== PHOTOMETRIC_YCBCR
2283 && (td
->td_ycbcrsubsampling
[0]<<3 | td
->td_ycbcrsubsampling
[1])
2285 && sp
->jpegcolormode
== JPEGCOLORMODE_RGB
2286 ) tif
->tif_flags
|= TIFF_UPSAMPLED
;
2288 /* If the up-sampling state changed, re-calculate tile size. */
2290 if ((tif
->tif_flags
^ v32
) & TIFF_UPSAMPLED
)
2292 tif
->tif_tilesize
= isTiled(tif
) ? TIFFTileSize(tif
) : (tsize_t
) -1;
2293 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
2297 TIFFSetFieldBit(tif
,tag
-TIFFTAG_JPEGPROC
+FIELD_JPEGPROC
);
2303 OJPEGVGetField(register TIFF
*tif
,ttag_t tag
,va_list ap
)
2304 { register OJPEGState
*sp
= OJState(tif
);
2309 /* If this file has managed to synthesize a set of consolidated "metadata"
2310 tables for the current (post-TIFF Version 6.0 specification) JPEG-in-
2311 TIFF encapsulation strategy, then tell our caller about them; otherwise,
2314 case TIFFTAG_JPEGTABLES
:
2315 if (sp
->jpegtables_length
) /* we have "new"-style JPEG tables */
2317 *va_arg(ap
,uint32
*) = sp
->jpegtables_length
;
2318 *va_arg(ap
,char **) = sp
->jpegtables
;
2322 /* This pseudo tag indicates whether our caller is expected to do YCbCr <->
2323 RGB color-space conversion (JPEGCOLORMODE_RAW <=> 0) or whether we must
2324 ask the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1).
2326 case TIFFTAG_JPEGCOLORMODE
:
2327 *va_arg(ap
,uint32
*) = sp
->jpegcolormode
;
2330 /* The following tags are defined by the TIFF Version 6.0 specification
2331 and are obsolete. If our caller asks for information about them, do not
2332 return anything, even if we parsed them in an old-format "source" image.
2334 case TIFFTAG_JPEGPROC
:
2335 *va_arg(ap
, uint16
*)=sp
->jpegproc
;
2338 case TIFFTAG_JPEGIFOFFSET
:
2339 *va_arg(ap
, uint32
*)=sp
->jpegifoffset
;
2342 case TIFFTAG_JPEGIFBYTECOUNT
:
2343 *va_arg(ap
, uint32
*)=sp
->jpegifbytecount
;
2346 case TIFFTAG_JPEGRESTARTINTERVAL
:
2347 *va_arg(ap
, uint32
*)=sp
->jpegrestartinterval
;
2350 case TIFFTAG_JPEGLOSSLESSPREDICTORS
:
2351 *va_arg(ap
, uint32
*)=sp
->jpeglosslesspredictors_length
;
2352 *va_arg(ap
, void**)=sp
->jpeglosslesspredictors
;
2355 case TIFFTAG_JPEGPOINTTRANSFORM
:
2356 *va_arg(ap
, uint32
*)=sp
->jpegpointtransform_length
;
2357 *va_arg(ap
, void**)=sp
->jpegpointtransform
;
2360 case TIFFTAG_JPEGQTABLES
:
2361 *va_arg(ap
, uint32
*)=sp
->jpegqtables_length
;
2362 *va_arg(ap
, void**)=sp
->jpegqtables
;
2365 case TIFFTAG_JPEGDCTABLES
:
2366 *va_arg(ap
, uint32
*)=sp
->jpegdctables_length
;
2367 *va_arg(ap
, void**)=sp
->jpegdctables
;
2370 case TIFFTAG_JPEGACTABLES
:
2371 *va_arg(ap
, uint32
*)=sp
->jpegactables_length
;
2372 *va_arg(ap
, void**)=sp
->jpegactables
;
2376 return (*sp
->vgetparent
)(tif
,tag
,ap
);
2380 OJPEGPrintDir(register TIFF
*tif
,FILE *fd
,long flags
)
2381 { register OJPEGState
*sp
= OJState(tif
);
2384 & (TIFFPRINT_JPEGQTABLES
|TIFFPRINT_JPEGDCTABLES
|TIFFPRINT_JPEGACTABLES
)
2386 && sp
->jpegtables_length
2388 fprintf(fd
," JPEG Table Data: <present>, %lu bytes\n",
2389 sp
->jpegtables_length
);
2393 OJPEGDefaultStripSize(register TIFF
*tif
,register uint32 s
)
2394 { register OJPEGState
*sp
= OJState(tif
);
2395 # define td (&tif->tif_dir)
2397 if ((s
= (*sp
->defsparent
)(tif
,s
)) < td
->td_imagelength
)
2398 { register tsize_t size
= sp
->cinfo
.comm
.is_decompressor
2399 # ifdef D_LOSSLESS_SUPPORTED
2400 ? sp
->cinfo
.d
.min_codec_data_unit
2404 # ifdef C_LOSSLESS_SUPPORTED
2405 : sp
->cinfo
.c
.data_unit
;
2410 size
= TIFFroundup(size
,16);
2411 s
= TIFFroundup(s
,td
->td_ycbcrsubsampling
[1]*size
);
2418 OJPEGDefaultTileSize(register TIFF
*tif
,register uint32
*tw
,register uint32
*th
)
2419 { register OJPEGState
*sp
= OJState(tif
);
2420 register tsize_t size
;
2421 # define td (&tif->tif_dir)
2423 size
= sp
->cinfo
.comm
.is_decompressor
2424 # ifdef D_LOSSLESS_SUPPORTED
2425 ? sp
->cinfo
.d
.min_codec_data_unit
2429 # ifdef C_LOSSLESS_SUPPORTED
2430 : sp
->cinfo
.c
.data_unit
;
2434 size
= TIFFroundup(size
,16);
2435 (*sp
->deftparent
)(tif
,tw
,th
);
2436 *tw
= TIFFroundup(*tw
,td
->td_ycbcrsubsampling
[0]*size
);
2437 *th
= TIFFroundup(*th
,td
->td_ycbcrsubsampling
[1]*size
);
2442 OJPEGCleanUp(register TIFF
*tif
)
2443 { register OJPEGState
*sp
;
2445 if ( (sp
= OJState(tif
)) )
2447 CALLVJPEG(sp
,jpeg_destroy(&sp
->cinfo
.comm
)); /* Free JPEG Lib. vars. */
2448 if (sp
->jpegtables
) {_TIFFfree(sp
->jpegtables
);sp
->jpegtables
=0;}
2449 if (sp
->jpeglosslesspredictors
) {
2450 _TIFFfree(sp
->jpeglosslesspredictors
);
2451 sp
->jpeglosslesspredictors
= 0;
2453 if (sp
->jpegpointtransform
) {
2454 _TIFFfree(sp
->jpegpointtransform
);
2455 sp
->jpegpointtransform
=0;
2457 if (sp
->jpegqtables
) {_TIFFfree(sp
->jpegqtables
);sp
->jpegqtables
=0;}
2458 if (sp
->jpegactables
) {_TIFFfree(sp
->jpegactables
);sp
->jpegactables
=0;}
2459 if (sp
->jpegdctables
) {_TIFFfree(sp
->jpegdctables
);sp
->jpegdctables
=0;}
2460 /* If the image file isn't "memory mapped" and we read it all into a
2461 single, large memory buffer, free the buffer now.
2463 if (!isMapped(tif
) && tif
->tif_base
) /* free whole-file buffer */
2465 _TIFFfree(tif
->tif_base
);
2469 _TIFFfree(sp
); /* Release local variables */
2475 TIFFInitOJPEG(register TIFF
*tif
,int scheme
)
2476 { register OJPEGState
*sp
;
2477 # define td (&tif->tif_dir)
2480 /* This module supports a decompression-only CODEC, which is intended strictly
2481 for viewing old image files using the obsolete JPEG-in-TIFF encapsulation
2482 specified by the TIFF Version 6.0 specification. It does not, and never
2483 should, support compression for new images. If a client application asks us
2484 to, refuse and complain loudly!
2486 if (tif
->tif_mode
!= O_RDONLY
) return _notSupported(tif
);
2491 /* BEWARE OF KLUDGE: If our host operating-system doesn't let an image
2492 file be "memory mapped", then we want to read the
2493 entire file into a single (possibly large) memory buffer as if it had
2494 been "memory mapped". Although this is likely to waste space, because
2495 analysis of the file's content might cause parts of it to be read into
2496 smaller buffers duplicatively, it appears to be the lesser of several
2497 evils. Very old JPEG-in-TIFF encapsulations aren't guaranteed to be
2498 JFIF bit streams, or to have a TIFF "JPEGTables" record or much other
2499 "metadata" to help us locate the decoding tables and entropy-coded data,
2500 so we're likely do a lot of random-access grokking around, and we must
2501 ultimately tell the JPEG Library to sequentially scan much of the file
2502 anyway. This is all likely to be easier if we use "brute force" to
2503 read the entire file, once, and don't use incremental disc I/O. If our
2504 client application tries to process a file so big that we can't buffer
2505 it entirely, then tough shit: we'll give up and exit!
2507 if (!(tif
->tif_base
= _TIFFmalloc(tif
->tif_size
=TIFFGetFileSize(tif
))))
2509 TIFFError(tif
->tif_name
,"Cannot allocate file buffer");
2512 if (!SeekOK(tif
,0) || !ReadOK(tif
,tif
->tif_base
,tif
->tif_size
))
2514 TIFFError(tif
->tif_name
,"Cannot read file");
2519 /* Allocate storage for this module's per-file variables. */
2521 if (!(tif
->tif_data
= (tidata_t
)_TIFFmalloc(sizeof *sp
)))
2523 TIFFError("TIFFInitOJPEG","No space for JPEG state block");
2526 (sp
= OJState(tif
))->tif
= tif
; /* Initialize reverse pointer */
2527 sp
->cinfo
.d
.err
= jpeg_std_error(&sp
->err
); /* Initialize error handling */
2528 sp
->err
.error_exit
= TIFFojpeg_error_exit
;
2529 sp
->err
.output_message
= TIFFojpeg_output_message
;
2530 if (!CALLVJPEG(sp
,jpeg_create_decompress(&sp
->cinfo
.d
))) return 0;
2532 /* Install CODEC-specific tag information and override default TIFF Library
2533 "method" subroutines with our own, CODEC-specific methods. Like all good
2534 members of an object-class, we save some of these subroutine pointers for
2535 "fall back" in case our own methods fail.
2537 _TIFFMergeFieldInfo(tif
,ojpegFieldInfo
,
2538 sizeof ojpegFieldInfo
/sizeof *ojpegFieldInfo
);
2539 sp
->defsparent
= tif
->tif_defstripsize
;
2540 sp
->deftparent
= tif
->tif_deftilesize
;
2541 sp
->vgetparent
= tif
->tif_tagmethods
.vgetfield
;
2542 sp
->vsetparent
= tif
->tif_tagmethods
.vsetfield
;
2543 tif
->tif_defstripsize
= OJPEGDefaultStripSize
;
2544 tif
->tif_deftilesize
= OJPEGDefaultTileSize
;
2545 tif
->tif_tagmethods
.vgetfield
= OJPEGVGetField
;
2546 tif
->tif_tagmethods
.vsetfield
= OJPEGVSetField
;
2547 tif
->tif_tagmethods
.printdir
= OJPEGPrintDir
;
2549 tif
->tif_setupencode
= OJPEGSetupEncode
;
2550 tif
->tif_preencode
= OJPEGPreEncode
;
2551 tif
->tif_postencode
= OJPEGPostEncode
;
2552 # else /* well, hardly ever */
2553 tif
->tif_setupencode
= tif
->tif_postencode
= _notSupported
;
2554 tif
->tif_preencode
= (TIFFPreMethod
)_notSupported
;
2556 tif
->tif_setupdecode
= OJPEGSetupDecode
;
2557 tif
->tif_predecode
= OJPEGPreDecode
;
2558 tif
->tif_postdecode
= OJPEGPostDecode
;
2559 tif
->tif_cleanup
= OJPEGCleanUp
;
2561 /* If the image file doesn't have "JPEGInterchangeFormat[Length]" TIFF records
2562 to guide us, we have few clues about where its encapsulated JPEG bit stream
2563 is located, so establish intelligent defaults: If the Image File Directory
2564 doesn't immediately follow the TIFF header, assume that the JPEG data lies
2565 in between; otherwise, assume that it follows the Image File Directory.
2567 if (tif
->tif_header
.tiff_diroff
> sizeof tif
->tif_header
)
2569 sp
->src
.next_input_byte
= tif
->tif_base
+ sizeof tif
->tif_header
;
2570 sp
->src
.bytes_in_buffer
= tif
->tif_header
.tiff_diroff
2571 - sizeof tif
->tif_header
;
2573 else /* this case is ugly! */
2574 { uint32 maxoffset
= tif
->tif_size
;
2577 /* Calculate the offset to the next Image File Directory, if there is one,
2578 or to the end of the file, if not. Then arrange to read the file from
2579 the end of the Image File Directory to that offset.
2581 if (tif
->tif_nextdiroff
) maxoffset
= tif
->tif_nextdiroff
; /* Not EOF */
2582 _TIFFmemcpy(&dircount
,(const tdata_t
)
2583 (sp
->src
.next_input_byte
= tif
->tif_base
+tif
->tif_header
.tiff_diroff
),
2585 if (tif
->tif_flags
& TIFF_SWAB
) TIFFSwabShort(&dircount
);
2586 sp
->src
.next_input_byte
+= dircount
*sizeof(TIFFDirEntry
)
2587 + sizeof maxoffset
+ sizeof dircount
;
2588 sp
->src
.bytes_in_buffer
= tif
->tif_base
- sp
->src
.next_input_byte
2592 /* IJG JPEG Library Version 6B can be configured for either 8- or 12-bit sample
2593 precision, but we assume that "old JPEG" TIFF clients only need 8 bits.
2595 sp
->cinfo
.d
.data_precision
= 8;
2596 # ifdef C_LOSSLESS_SUPPORTED
2598 /* If the "JPEGProc" TIFF tag is missing from the Image File Dictionary, the
2599 JPEG Library will use its (lossy) baseline sequential process by default.
2601 sp
->cinfo
.d
.data_unit
= DCTSIZE
;
2602 # endif /* C_LOSSLESS_SUPPORTED */
2604 /* Initialize other CODEC-specific variables requiring default values. */
2606 tif
->tif_flags
|= TIFF_NOBITREV
; /* No bit-reversal within data bytes */
2607 sp
->h_sampling
= sp
->v_sampling
= 1; /* No subsampling by default */
2608 sp
->is_WANG
= 0; /* Assume not a MS Windows Wang Imaging file by default */
2609 sp
->jpegtables
= 0; /* No "new"-style JPEG tables synthesized yet */
2610 sp
->jpegtables_length
= 0;
2611 sp
->jpegquality
= 75; /* Default IJG quality */
2612 sp
->jpegcolormode
= JPEGCOLORMODE_RAW
;
2613 sp
->jpegtablesmode
= 0; /* No tables found yet */
2614 sp
->jpeglosslesspredictors
=0;
2615 sp
->jpeglosslesspredictors_length
=0;
2616 sp
->jpegpointtransform
=0;
2617 sp
->jpegpointtransform_length
=0;
2619 sp
->jpegqtables_length
=0;
2621 sp
->jpegdctables_length
=0;
2623 sp
->jpegactables_length
=0;
2627 #endif /* OJPEG_SUPPORT */
2629 /* vim: set ts=8 sts=8 sw=8 noet: */