source: liacs/MIR2010/SourceCode/cximage/tiff/tif_ojpeg.c@ 253

Last change on this file since 253 was 95, checked in by Rick van der Zwet, 15 years ago

Bad boy, improper move of directory

File size: 107.2 KB
Line 
1/* $Id: tif_ojpeg.c,v 1.16 2006/03/01 11:09:13 dron Exp $ */
2
3#include "tiffiop.h"
4#ifdef OJPEG_SUPPORT
5
6/* JPEG Compression support, as per the original TIFF 6.0 specification.
7
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.
20
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/.
24
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.
30
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
38 Library!
39
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.
43*/
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
47***************
48*** 648,651 ****
49--- 648,683 ----
50 for (i = 0; i < NUM_HUFF_TBLS; i++) {
51 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
52 }
53 }
54+
55+ /*
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()".
70+ *
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.
75+ */
76+ GLOBAL(void)
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;
80+
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);
85+ }
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
90***************
91*** 357,360 ****
92--- 357,393 ----
93 for (i = 0; i < NUM_HUFF_TBLS; i++) {
94 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
95 }
96 }
97+
98+ /*
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()".
113+ *
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.
118+ */
119+ GLOBAL(void)
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;
124+
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);
129+ }
130#endif /* Patch for JPEG Library WITH lossless Huffman coding */
131#include <setjmp.h>
132#include <stdio.h>
133#ifdef FAR
134#undef FAR /* Undefine FAR to avoid conflict with JPEG definition */
135#endif
136#define JPEG_INTERNALS /* Include "jpegint.h" for "DSTATE_*" symbols */
137#define JPEG_CJPEG_DJPEG /* Include all Version 6B+ "jconfig.h" options */
138#undef INLINE
139#include "jpeglib.h"
140#undef JPEG_CJPEG_DJPEG
141#undef JPEG_INTERNALS
142
143/* Hack for files produced by Wang Imaging application on Microsoft Windows */
144extern void jpeg_reset_huff_decode(j_decompress_ptr);
145
146/* On some machines, it may be worthwhile to use "_setjmp()" or "sigsetjmp()"
147 instead of "setjmp()". These macros make it easier:
148*/
149#define SETJMP(jbuf)setjmp(jbuf)
150#define LONGJMP(jbuf,code)longjmp(jbuf,code)
151#define JMP_BUF jmp_buf
152
153#define TIFFTAG_WANG_PAGECONTROL 32934
154
155/* Bit-vector offsets for keeping track of TIFF records that we've parsed. */
156
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)
169
170typedef struct jpeg_destination_mgr jpeg_destination_mgr;
171typedef struct jpeg_source_mgr jpeg_source_mgr;
172typedef struct jpeg_error_mgr jpeg_error_mgr;
173
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.
182*/
183typedef struct /* This module's private, per-image state variable */
184 {
185 union /* JPEG Library state variable; this MUST be our 1st field! */
186 {
187 struct jpeg_compress_struct c;
188 struct jpeg_decompress_struct d;
189 struct jpeg_common_struct comm;
190 } cinfo;
191 jpeg_error_mgr err; /* JPEG Library error manager */
192 JMP_BUF exit_jmpbuf; /* ...for catching JPEG Library failures */
193# ifdef never
194
195 /* (The following two fields could be a "union", but they're small enough that
196 it's not worth the effort.)
197 */
198 jpeg_destination_mgr dest; /* Destination for compressed data */
199# endif
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 */
213 samplesperclump,
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 */
217 v_sampling,
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 */
222 uint16 jpegproc;
223 uint32 jpegifoffset;
224 uint32 jpegifbytecount;
225 uint32 jpegrestartinterval;
226 void* jpeglosslesspredictors;
227 uint16 jpeglosslesspredictors_length;
228 void* jpegpointtransform;
229 uint32 jpegpointtransform_length;
230 void* jpegqtables;
231 uint32 jpegqtables_length;
232 void* jpegdctables;
233 uint32 jpegdctables_length;
234 void* jpegactables;
235 uint32 jpegactables_length;
236
237 } OJPEGState;
238#define OJState(tif)((OJPEGState*)(tif)->tif_data)
239
240static const TIFFFieldInfo ojpegFieldInfo[]=/* JPEG-specific TIFF-record tags */
241 {
242
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.
251 */
252 {
253 TIFFTAG_JPEGTABLES ,TIFF_VARIABLE2,TIFF_VARIABLE2,
254 TIFF_UNDEFINED,FIELD_JPEGTABLES ,FALSE,TRUE ,"JPEGTables"
255 },
256
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.
260 */
261 {
262 TIFFTAG_JPEGPROC ,1 ,1 ,
263 TIFF_SHORT ,FIELD_JPEGPROC ,FALSE,FALSE,"JPEGProc"
264 },
265 {
266 TIFFTAG_JPEGIFOFFSET ,1 ,1 ,
267 TIFF_LONG ,FIELD_JPEGIFOFFSET ,FALSE,FALSE,"JPEGInterchangeFormat"
268 },
269 {
270 TIFFTAG_JPEGIFBYTECOUNT ,1 ,1 ,
271 TIFF_LONG ,FIELD_JPEGIFBYTECOUNT ,FALSE,FALSE,"JPEGInterchangeFormatLength"
272 },
273 {
274 TIFFTAG_JPEGRESTARTINTERVAL ,1 ,1 ,
275 TIFF_SHORT ,FIELD_JPEGRESTARTINTERVAL ,FALSE,FALSE,"JPEGRestartInterval"
276 },
277 {
278 TIFFTAG_JPEGLOSSLESSPREDICTORS,TIFF_VARIABLE,TIFF_VARIABLE,
279 TIFF_SHORT ,FIELD_JPEGLOSSLESSPREDICTORS,FALSE,TRUE ,"JPEGLosslessPredictors"
280 },
281 {
282 TIFFTAG_JPEGPOINTTRANSFORM ,TIFF_VARIABLE,TIFF_VARIABLE,
283 TIFF_SHORT ,FIELD_JPEGPOINTTRANSFORM ,FALSE,TRUE ,"JPEGPointTransforms"
284 },
285 {
286 TIFFTAG_JPEGQTABLES ,TIFF_VARIABLE,TIFF_VARIABLE,
287 TIFF_LONG ,FIELD_JPEGQTABLES ,FALSE,TRUE ,"JPEGQTables"
288 },
289 {
290 TIFFTAG_JPEGDCTABLES ,TIFF_VARIABLE,TIFF_VARIABLE,
291 TIFF_LONG ,FIELD_JPEGDCTABLES ,FALSE,TRUE ,"JPEGDCTables"
292 },
293 {
294 TIFFTAG_JPEGACTABLES ,TIFF_VARIABLE,TIFF_VARIABLE,
295 TIFF_LONG ,FIELD_JPEGACTABLES ,FALSE,TRUE ,"JPEGACTables"
296 },
297 {
298 TIFFTAG_WANG_PAGECONTROL ,TIFF_VARIABLE,1 ,
299 TIFF_LONG ,FIELD_WANG_PAGECONTROL ,FALSE,FALSE,"WANG PageControl"
300 },
301
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).
307 */
308 {
309 TIFFTAG_JPEGCOLORMODE ,0 ,0 ,
310 TIFF_ANY ,FIELD_PSEUDO ,FALSE,FALSE,"JPEGColorMode"
311 }
312 };
313static 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)"},
317# ifdef never
318 no_write_frac[]={"fractional scan line discarded"},
319# endif
320 no_read_frac[]={"fractional scan line not read"},
321 no_jtable_space[]={"No space for JPEGTables"};
322
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.
328*/
329static void
330TIFFojpeg_error_exit(register j_common_ptr cinfo)
331{
332 char buffer[JMSG_LENGTH_MAX];
333 int code = cinfo->err->msg_code;
334
335 if (((OJPEGState *)cinfo)->is_WANG) {
336 if (code == JERR_SOF_DUPLICATE || code == JERR_SOI_DUPLICATE)
337 return; /* ignore it */
338 }
339
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 */
344}
345
346static void
347TIFFojpeg_output_message(register j_common_ptr cinfo)
348 { char buffer[JMSG_LENGTH_MAX];
349
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
352 set > 0.
353 */
354 (*cinfo->err->format_message)(cinfo,buffer);
355 TIFFWarning(JPEGLib_name,buffer);
356 }
357
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.
361*/
362#define CALLJPEG(sp,fail,op)(SETJMP((sp)->exit_jmpbuf)?(fail):(op))
363#define CALLVJPEG(sp,op)CALLJPEG(sp,0,((op),1))
364#ifdef never
365
366static int
367TIFFojpeg_create_compress(register OJPEGState *sp)
368 {
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));
373 }
374
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
377 buffer.
378*/
379static void
380std_init_destination(register j_compress_ptr cinfo){} /* "Dummy" stub */
381
382static boolean
383std_empty_output_buffer(register j_compress_ptr cinfo)
384 {
385# define sp ((OJPEGState *)cinfo)
386 register TIFF *tif = sp->tif;
387
388 tif->tif_rawcc = tif->tif_rawdatasize; /* Entire buffer has been filled */
389 TIFFFlushData1(tif);
390 sp->dest.next_output_byte = (JOCTET *)tif->tif_rawdata;
391 sp->dest.free_in_buffer = (size_t)tif->tif_rawdatasize;
392 return TRUE;
393# undef sp
394 }
395
396static void
397std_term_destination(register j_compress_ptr cinfo)
398 {
399# define sp ((OJPEGState *)cinfo)
400 register TIFF *tif = sp->tif;
401
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;
405# undef sp
406 }
407
408/* Alternate destination manager to output JPEGTables field: */
409
410static void
411tables_init_destination(register j_compress_ptr cinfo)
412 {
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;
417# undef sp
418 }
419
420static boolean
421tables_empty_output_buffer(register j_compress_ptr cinfo)
422 { void *newbuf;
423# define sp ((OJPEGState *)cinfo)
424
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)
428 )
429 )
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;
435 return TRUE;
436# undef sp
437 }
438
439static void
440tables_term_destination(register j_compress_ptr cinfo)
441 {
442# define sp ((OJPEGState *)cinfo)
443 /* Set tables length to no. of Bytes actually emitted. */
444 sp->jpegtables_length -= sp->dest.free_in_buffer;
445# undef sp
446 }
447
448/*ARGSUSED*/ static int
449TIFFojpeg_tables_dest(register OJPEGState *sp, TIFF *tif)
450 {
451
452 /* Allocate a working buffer for building tables. The initial size is 1000
453 Bytes, which is usually adequate.
454 */
455 if (sp->jpegtables) _TIFFfree(sp->jpegtables);
456 if (!(sp->jpegtables = (void*)
457 _TIFFmalloc((tsize_t)(sp->jpegtables_length = 1000))
458 )
459 )
460 {
461 sp->jpegtables_length = 0;
462 TIFFError("TIFFojpeg_tables_dest",no_jtable_space);
463 return 0;
464 };
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;
469 return 1;
470 }
471#else /* well, hardly ever */
472
473static int
474_notSupported(register TIFF *tif)
475 { const TIFFCodec *c = TIFFFindCODEC(tif->tif_dir.td_compression);
476
477 TIFFError(tif->tif_name,"%s compression not supported",c->name);
478 return 0;
479 }
480#endif /* never */
481
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
484 buffer.
485*/
486static void
487std_init_source(register j_decompress_ptr cinfo)
488 {
489# define sp ((OJPEGState *)cinfo)
490 register TIFF *tif = sp->tif;
491
492 if (sp->src.bytes_in_buffer == 0)
493 {
494 sp->src.next_input_byte = (const JOCTET *)tif->tif_rawdata;
495 sp->src.bytes_in_buffer = (size_t)tif->tif_rawcc;
496 };
497# undef sp
498 }
499
500static boolean
501std_fill_input_buffer(register j_decompress_ptr cinfo)
502 { static const JOCTET dummy_EOI[2]={0xFF,JPEG_EOI};
503# define sp ((OJPEGState *)cinfo)
504
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.
508 */
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;
512 return TRUE;
513# undef sp
514 }
515
516static void
517std_skip_input_data(register j_decompress_ptr cinfo, long num_bytes)
518 {
519# define sp ((OJPEGState *)cinfo)
520
521 if (num_bytes > 0)
522 {
523 if (num_bytes > (long)sp->src.bytes_in_buffer) /* oops: buffer overrun */
524 (void)std_fill_input_buffer(cinfo);
525 else
526 {
527 sp->src.next_input_byte += (size_t)num_bytes;
528 sp->src.bytes_in_buffer -= (size_t)num_bytes;
529 }
530 }
531# undef sp
532 }
533
534/*ARGSUSED*/ static void
535std_term_source(register j_decompress_ptr cinfo){} /* "Dummy" stub */
536
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.
541*/
542static int
543alloc_downsampled_buffers(TIFF *tif,jpeg_component_info *comp_info,
544 int num_components)
545 { register OJPEGState *sp = OJState(tif);
546
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
552# else
553 ? DCTSIZE
554# endif
555# ifdef C_LOSSLESS_SUPPORTED
556 : sp->cinfo.c.data_unit;
557# else
558 : DCTSIZE;
559# endif
560 int ci = 0;
561 register jpeg_component_info *compptr = comp_info;
562
563 do
564 { JSAMPARRAY buf;
565
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))))
570# else
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))))
572# endif
573 return 0;
574 sp->ds_buffer[ci] = buf;
575 }
576 while (++compptr,++ci < num_components);
577 };
578 return 1;
579 }
580#ifdef never
581
582/* JPEG Encoding begins here. */
583
584/*ARGSUSED*/ static int
585OJPEGEncode(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);
588
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.
591 */
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)
595 ) cc = rows;
596 while (--cc >= 0)
597 {
598 if ( CALLJPEG(sp,-1,jpeg_write_scanlines(&sp->cinfo.c,(JSAMPARRAY)&buf,1))
599 != 1
600 ) return 0;
601 ++tif->tif_row;
602 buf += sp->bytesperline;
603 };
604 return 1;
605 }
606
607/*ARGSUSED*/ static int
608OJPEGEncodeRaw(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);
612
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
615 multiples.
616 */
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)
621 ) cc = rows;
622# ifdef C_LOSSLESS_SUPPORTED
623 lines_per_MCU = sp->cinfo.c.max_samp_factor*(size = sp->cinfo.d.data_unit);
624# else
625 lines_per_MCU = sp->cinfo.c.max_samp_factor*(size = DCTSIZE);
626# endif
627 while (--cc >= 0)
628 { int ci = 0, clumpoffset = 0;
629 register jpeg_component_info *compptr = sp->cinfo.c.comp_info;
630
631 /* The fastest way to separate the data is to make 1 pass over the scan
632 line for each row of each component.
633 */
634 do
635 { int ypos = 0;
636
637 do
638 { int padding;
639 register JSAMPLE *inptr = (JSAMPLE*)buf + clumpoffset,
640 *outptr =
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,
645 xpos;
646
647 padding = (int)
648# ifdef C_LOSSLESS_SUPPORTED
649 ( compptr->width_in_data_units * size
650# else
651 ( compptr->width_in_blocks * size
652# endif
653 - clumps_per_line * compptr->h_samp_factor
654 );
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 */
659 do
660 {
661 xpos = 0;
662 do *outptr++ = inptr[xpos];
663 while (++xpos < compptr->h_samp_factor);
664 }
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;
669 }
670 while (++ypos < compptr->v_samp_factor);
671 }
672 while (++compptr,++ci < sp->cinfo.c.num_components);
673 if (++sp->scancount >= size)
674 {
675 if ( CALLJPEG(sp,-1,jpeg_write_raw_data(&sp->cinfo.c,sp->ds_buffer,lines_per_MCU))
676 != lines_per_MCU
677 ) return 0;
678 sp->scancount = 0;
679 };
680 ++tif->tif_row++
681 buf += sp->bytesperline;
682 };
683 return 1;
684 }
685
686static int
687OJPEGSetupEncode(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)
693
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.
697 */
698 if (td->td_bitspersample != 8)
699 {
700 TIFFError(module,bad_bps,td->td_bitspersample);
701 status = 0;
702 };
703
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.
708 */
709 switch (td->td_photometric)
710 {
711 case PHOTOMETRIC_YCBCR :
712
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.
715 */
716 if ( ( td->td_ycbcrsubsampling[0] == 1
717 || td->td_ycbcrsubsampling[0] == 2
718 || td->td_ycbcrsubsampling[0] == 4
719 )
720 && ( td->td_ycbcrsubsampling[1] == 1
721 || td->td_ycbcrsubsampling[1] == 2
722 || td->td_ycbcrsubsampling[1] == 4
723 )
724 )
725 sp->cinfo.c.raw_data_in =
726 ( (sp->h_sampling = td->td_ycbcrsubsampling[0]) << 3
727 | (sp->v_sampling = td->td_ycbcrsubsampling[1])
728 ) != 011;
729 else
730 {
731 TIFFError(module,bad_subsampling);
732 status = 0;
733 };
734
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.
738 */
739 if (!TIFFFieldSet(tif,FIELD_REFBLACKWHITE))
740 { float refbw[6];
741 long top = 1L << td->td_bitspersample;
742
743 refbw[0] = 0;
744 refbw[1] = (float)(top-1L);
745 refbw[2] = (float)(top>>1);
746 refbw[3] = refbw[1];
747 refbw[4] = refbw[2];
748 refbw[5] = refbw[1];
749 TIFFSetField(tif,TIFFTAG_REFERENCEBLACKWHITE,refbw);
750 };
751 sp->cinfo.c.jpeg_color_space = JCS_YCbCr;
752 if (sp->jpegcolormode == JPEGCOLORMODE_RGB)
753 {
754 sp->cinfo.c.raw_data_in = FALSE;
755 sp->in_color_space = JCS_RGB;
756 break;
757 };
758 goto L2;
759 case PHOTOMETRIC_MINISBLACK:
760 sp->cinfo.c.jpeg_color_space = JCS_GRAYSCALE;
761 goto L1;
762 case PHOTOMETRIC_RGB :
763 sp->cinfo.c.jpeg_color_space = JCS_RGB;
764 goto L1;
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;
769 break;
770 default :
771 TIFFError(module,bad_photometry,td->td_photometric);
772 status = 0;
773 };
774 tif->tif_encoderow = tif->tif_encodestrip = tif->tif_encodetile =
775 sp->cinfo.c.raw_data_in ? OJPEGEncodeRaw : OJPEGEncode;
776 if (isTiled(tif))
777 { tsize_t size;
778
779# ifdef C_LOSSLESS_SUPPORTED
780 if ((size = sp->v_sampling*sp->cinfo.c.data_unit) < 16) size = 16;
781# else
782 if ((size = sp->v_sampling*DCTSIZE) < 16) size = 16;
783# endif
784 if ((segment_height = td->td_tilelength) % size)
785 {
786 TIFFError(module,"JPEG tile height must be multiple of %d",size);
787 status = 0;
788 };
789# ifdef C_LOSSLESS_SUPPORTED
790 if ((size = sp->h_sampling*sp->cinfo.c.data_unit) < 16) size = 16;
791# else
792 if ((size = sp->h_sampling*DCTSIZE) < 16) size = 16;
793# endif
794 if ((segment_width = td->td_tilewidth) % size)
795 {
796 TIFFError(module,"JPEG tile width must be multiple of %d",size);
797 status = 0;
798 };
799 sp->bytesperline = TIFFTileRowSize(tif);
800 }
801 else
802 { tsize_t size;
803
804# ifdef C_LOSSLESS_SUPPORTED
805 if ((size = sp->v_sampling*sp->cinfo.c.data_unit) < 16) size = 16;
806# else
807 if ((size = sp->v_sampling*DCTSIZE) < 16) size = 16;
808# endif
809 if (td->td_rowsperstrip < (segment_height = td->td_imagelength))
810 {
811 if (td->td_rowsperstrip % size)
812 {
813 TIFFError(module,"JPEG RowsPerStrip must be multiple of %d",size);
814 status = 0;
815 };
816 segment_height = td->td_rowsperstrip;
817 };
818 segment_width = td->td_imagewidth;
819 sp->bytesperline = tif->tif_scanlinesize;
820 };
821 if (segment_width > 65535 || segment_height > 65535)
822 {
823 TIFFError(module,"Strip/tile too large for JPEG");
824 status = 0;
825 };
826
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.
830 */
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;
836
837 case 0 :
838 sp->cinfo.c.optimize_coding = TRUE;
839 case JPEGTABLESMODE_HUFF :
840 if (!CALLVJPEG(sp,jpeg_set_quality(&sp->cinfo.c,sp->jpegquality,FALSE)))
841 return 0;
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;
844 goto L3;
845 case JPEGTABLESMODE_QUANT :
846 sp->cinfo.c.optimize_coding = TRUE;
847
848 /* We do not support application-supplied JPEG tables, so mark the field
849 "not present".
850 */
851 L3: TIFFClrFieldBit(tif,FIELD_JPEGTABLES);
852 break;
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))
856 )
857 {
858 status = 0;
859 break;
860 };
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)
865 {
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;
872 };
873 if ( TIFFojpeg_tables_dest(sp,tif)
874 && CALLVJPEG(sp,jpeg_write_tables(&sp->cinfo.c))
875 )
876 {
877
878 /* Mark the field "present". We can't use "TIFFSetField()" because
879 "BEENWRITING" is already set!
880 */
881 TIFFSetFieldBit(tif,FIELD_JPEGTABLES);
882 tif->tif_flags |= TIFF_DIRTYDIRECT;
883 }
884 else status = 0;
885 };
886 if ( sp->cinfo.c.raw_data_in
887 && !alloc_downsampled_buffers(tif,sp->cinfo.c.comp_info,
888 sp->cinfo.c.num_components)
889 ) status = 0;
890 if (status == 0) return 0; /* If TIFF errors, don't bother to continue */
891 /* Grab parameters that are same for all strips/tiles. */
892
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));
905# undef td
906 }
907
908static int
909OJPEGPreEncode(register TIFF *tif,tsample_t s)
910 { register OJPEGState *sp = OJState(tif);
911# define td (&tif->tif_dir)
912
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
916 ado.
917 */
918 if ( (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip)
919 % td->td_stripsperimage
920 == 0
921 )
922 {
923 if ( (sp->cinfo.c.comp_info[0].component_id = s) == 1)
924 && sp->cinfo.c.jpeg_color_space == JCS_YCbCr
925 )
926 {
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;
932
933 /* Scale expected strip/tile size to match a downsampled component. */
934
935 sp->cinfo.c.image_width = TIFFhowmany(segment_width,sp->h_sampling);
936 sp->cinfo.c.image_height=TIFFhowmany(segment_height,sp->v_sampling);
937 };
938 sp->scancount = 0; /* Mark subsampling buffer(s) empty */
939 };
940 return 1;
941# undef td
942 }
943
944static int
945OJPEGPostEncode(register TIFF *tif)
946 { register OJPEGState *sp = OJState(tif);
947
948 /* Finish up at the end of a strip or tile. */
949
950 if (sp->scancount > 0) /* emit partial buffer of down-sampled data */
951 { JDIMENSION n;
952
953# ifdef C_LOSSLESS_SUPPORTED
954 if ( sp->scancount < sp->cinfo.c.data_unit
955 && sp->cinfo.c.num_components > 0
956 )
957# else
958 if (sp->scancount < DCTSIZE && sp->cinfo.c.num_components > 0)
959# endif
960 { int ci = 0, /* Pad the data vertically */
961# ifdef C_LOSSLESS_SUPPORTED
962 size = sp->cinfo.c.data_unit;
963# else
964 size = DCTSIZE;
965# endif
966 register jpeg_component_info *compptr = sp->cinfo.c.comp_info;
967
968 do
969# ifdef C_LOSSLESS_SUPPORTED
970 { tsize_t row_width = compptr->width_in_data_units
971# else
972 tsize_t row_width = compptr->width_in_blocks
973# endif
974 *size*sizeof(JSAMPLE);
975 int ypos = sp->scancount*compptr->v_samp_factor;
976
977 do _TIFFmemcpy( (tdata_t)sp->ds_buffer[ci][ypos]
978 , (tdata_t)sp->ds_buffer[ci][ypos-1]
979 , row_width
980 );
981 while (++ypos < compptr->v_samp_factor*size);
982 }
983 while (++compptr,++ci < sp->cinfo.c.num_components);
984 };
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)
987 return 0;
988 };
989 return CALLVJPEG(sp,jpeg_finish_compress(&sp->cinfo.c));
990 }
991#endif /* never */
992
993/* JPEG Decoding begins here. */
994
995/*ARGSUSED*/ static int
996OJPEGDecode(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);
1002
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
1008 planes.
1009
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.
1019 */
1020 if ( (cc /= bytesperline) /* No. of complete rows in caller's buffer */
1021 > (rows = sp->cinfo.d.output_height - sp->cinfo.d.output_scanline)
1022 ) cc = rows;
1023 while (--cc >= 0)
1024 {
1025 if ( CALLJPEG(sp,-1,jpeg_read_scanlines(&sp->cinfo.d,(JSAMPARRAY)&buf,1))
1026 != 1
1027 ) return 0;
1028 buf += bytesperline;
1029 ++tif->tif_row;
1030 };
1031
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".
1040 */
1041 if (sp->is_WANG) jpeg_reset_huff_decode(&sp->cinfo.d);
1042 return 1;
1043 }
1044
1045/*ARGSUSED*/ static int
1046OJPEGDecodeRawContig(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);
1050
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-
1057 line multiples.
1058 */
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)
1061 ) cc = rows;
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);
1065# else
1066 * (size = DCTSIZE);
1067# endif
1068 while (--cc >= 0)
1069 { int clumpoffset, ci;
1070 register jpeg_component_info *compptr;
1071
1072 if (sp->scancount >= size) /* reload downsampled-data buffers */
1073 {
1074 if ( CALLJPEG(sp,-1,jpeg_read_raw_data(&sp->cinfo.d,sp->ds_buffer,lines_per_MCU))
1075 != lines_per_MCU
1076 ) return 0;
1077 sp->scancount = 0;
1078 };
1079
1080 /* The fastest way to separate the data is: make 1 pass over the scan
1081 line for each row of each component.
1082 */
1083 clumpoffset = ci = 0;
1084 compptr = sp->cinfo.d.comp_info;
1085 do
1086 { int ypos = 0;
1087
1088 if (compptr->h_samp_factor == 1) /* fast path */
1089 do
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;
1094
1095 do *outptr = *inptr++;
1096 while ((outptr += sp->samplesperclump),--clumps_per_line > 0);
1097 }
1098 while ( (clumpoffset += compptr->h_samp_factor)
1099 , ++ypos < compptr->v_samp_factor
1100 );
1101 else /* general case */
1102 do
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;
1107
1108 do
1109 { register int xpos = 0;
1110
1111 do outptr[xpos] = *inptr++;
1112 while (++xpos < compptr->h_samp_factor);
1113 }
1114 while ((outptr += sp->samplesperclump),--clumps_per_line > 0);
1115 }
1116 while ( (clumpoffset += compptr->h_samp_factor)
1117 , ++ypos < compptr->v_samp_factor
1118 );
1119 }
1120 while (++compptr,++ci < sp->cinfo.d.num_components);
1121 ++sp->scancount;
1122 buf += sp->bytesperline;
1123 ++tif->tif_row;
1124 };
1125
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".
1134 */
1135 if (sp->is_WANG) jpeg_reset_huff_decode(&sp->cinfo.d);
1136 return 1;
1137 }
1138
1139/*ARGSUSED*/ static int
1140OJPEGDecodeRawSeparate(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;
1147
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
1152 multiples.
1153 */
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);
1161# else
1162 * (size = DCTSIZE);
1163# endif
1164 L: if (sp->scancount >= size) /* reload downsampled-data buffers */
1165 {
1166 if ( CALLJPEG(sp,-1,jpeg_read_raw_data(&sp->cinfo.d,sp->ds_buffer,lines_per_MCU))
1167 != lines_per_MCU
1168 ) return 0;
1169 sp->scancount = 0;
1170 };
1171 rows = 0;
1172 do
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;
1176
1177 do *buf++ = *inptr++; while (--clumps_per_line > 0); /* Copy scanline */
1178 tif->tif_row += v;
1179 if (--cc <= 0) return 1; /* End of caller's buffer? */
1180 }
1181 while (++rows < compptr->v_samp_factor);
1182 ++sp->scancount;
1183 goto L;
1184 }
1185
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.
1190*/
1191/*ARGSUSED*/ METHODDEF(int)
1192fake_SOS_marker(j_decompress_ptr cinfo){return JPEG_REACHED_SOS;}
1193
1194/*ARGSUSED*/ METHODDEF(int)
1195suspend(j_decompress_ptr cinfo){return JPEG_SUSPENDED;}
1196
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".
1203*/
1204METHODDEF(void)
1205ycc_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 */
1208 {
1209
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!
1214 */
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 */
1221 } *my_cconvert_ptr;
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;
1226
1227 switch (cinfo->output_scan_number - 1)
1228 { JSAMPARRAY irow1p, irow2p;
1229 register INT32 *table0, *table1;
1230 SHIFT_TEMPS
1231
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;
1237
1238 Y = *irow0p++;
1239 outp = *out++;
1240 while (--i >= 0)
1241 *outp++ = range_limit[*Y++ + table0[*Cr++]];
1242 };
1243 return;
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++,
1250 Cr = *irow2p++;
1251 register int i = cinfo->output_width;
1252
1253 Y = *irow0p++;
1254 outp = *out++;
1255 while (--i >= 0)
1256 *outp++ =
1257 range_limit[ *Y++
1258 + RIGHT_SHIFT(table0[*Cb++]+table1[*Cr++],16)
1259 ];
1260 };
1261 return;
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;
1267
1268 Y = *irow0p++;
1269 outp = *out++;
1270 while (--i >= 0)
1271 *outp++ = range_limit[*Y++ + table0[*Cb++]];
1272 }
1273 }
1274 }
1275
1276METHODDEF(void)
1277null_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;
1280
1281 while (--nrows >= 0) _TIFFmemcpy(*out++,*irowp++,cinfo->output_width);
1282 }
1283
1284static int
1285OJPEGSetupDecode(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)
1295
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.
1299 */
1300 if (td->td_bitspersample != sp->cinfo.d.data_precision)
1301 {
1302 TIFFError(module,bad_bps,td->td_bitspersample);
1303 status = 0;
1304 };
1305
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.
1310 */
1311 switch (td->td_photometric)
1312 {
1313 case PHOTOMETRIC_YCBCR :
1314
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.
1317 */
1318 if ( ( td->td_ycbcrsubsampling[0] == 1
1319 || td->td_ycbcrsubsampling[0] == 2
1320 || td->td_ycbcrsubsampling[0] == 4
1321 )
1322 && ( td->td_ycbcrsubsampling[1] == 1
1323 || td->td_ycbcrsubsampling[1] == 2
1324 || td->td_ycbcrsubsampling[1] == 4
1325 )
1326 )
1327 downsampled_output =
1328 (
1329 (sp->h_sampling = td->td_ycbcrsubsampling[0]) << 3
1330 | (sp->v_sampling = td->td_ycbcrsubsampling[1])
1331 ) != 011;
1332 else
1333 {
1334 TIFFError(module,bad_subsampling);
1335 status = 0;
1336 };
1337 jpeg_color_space = JCS_YCbCr;
1338 if (sp->jpegcolormode == JPEGCOLORMODE_RGB)
1339 {
1340 downsampled_output = FALSE;
1341 out_color_space = JCS_RGB;
1342 break;
1343 };
1344 goto L2;
1345 case PHOTOMETRIC_MINISBLACK:
1346 jpeg_color_space = JCS_GRAYSCALE;
1347 goto L1;
1348 case PHOTOMETRIC_RGB :
1349 jpeg_color_space = JCS_RGB;
1350 goto L1;
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;
1355 break;
1356 default :
1357 TIFFError(module,bad_photometry,td->td_photometric);
1358 status = 0;
1359 };
1360 if (status == 0) return 0; /* If TIFF errors, don't bother to continue */
1361
1362 /* Set parameters that are same for all strips/tiles. */
1363
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;
1370
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.
1382 */
1383 is_JFIF = !sp->is_WANG && TIFFFieldSet(tif,FIELD_JPEGIFOFFSET);
1384
1385 /* Initialize decompression parameters that won't be overridden by JPEG Library
1386 defaults set during the "jpeg_read_header()" call, below.
1387 */
1388 segment_width = td->td_imagewidth;
1389 if (isTiled(tif))
1390 {
1391 if (sp->is_WANG) /* we don't know how to handle it */
1392 {
1393 TIFFError(module,"Tiled Wang image not supported");
1394 return 0;
1395 };
1396
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.
1409 */
1410 if (is_JFIF || (segment_width & 7) == 0)
1411 sp->bytesperline = TIFFTileRowSize(tif); /* Normal case */
1412 else
1413 {
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;
1417 }
1418 }
1419 else sp->bytesperline = TIFFVStripSize(tif,1);
1420
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.
1426 */
1427 if (is_JFIF) /* JFIF image */
1428 { unsigned char *end_of_data;
1429 int subsampling_factors;
1430 register unsigned char *p;
1431 register int i;
1432
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
1447 this clean-up code:
1448 */
1449# ifdef someday
1450 if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) /* free quant. tables */
1451 { register int i = 0;
1452
1453 do
1454 { register JQUANT_TBL *q;
1455
1456 if (q = sp->cinfo.d.quant_tbl_ptrs[i])
1457 {
1458 jpeg_free_small(&sp->cinfo.comm,q,sizeof *q);
1459 sp->cinfo.d.quant_tbl_ptrs[i] = 0;
1460 }
1461 }
1462 while (++i < NUM_QUANT_TBLS);
1463 };
1464 if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) /* free Huffman tables */
1465 { register int i = 0;
1466
1467 do
1468 { register JHUFF_TBL *h;
1469
1470 if (h = sp->cinfo.d.dc_huff_tbl_ptrs[i])
1471 {
1472 jpeg_free_small(&sp->cinfo.comm,h,sizeof *h);
1473 sp->cinfo.d.dc_huff_tbl_ptrs[i] = 0;
1474 };
1475 if (h = sp->cinfo.d.ac_huff_tbl_ptrs[i])
1476 {
1477 jpeg_free_small(&sp->cinfo.comm,h,sizeof *h);
1478 sp->cinfo.d.ac_huff_tbl_ptrs[i] = 0;
1479 }
1480 }
1481 while (++i < NUM_HUFF_TBLS);
1482 };
1483# endif /* someday */
1484
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:
1491
1492 -- Define Quantization Table (DQT)
1493 -- Define Huffman Table (DHT)
1494 -- Define Arithmetic Coding table (DAC)
1495 -- Define Restart Interval (DRI)
1496 -- Comment (COM)
1497 -- Application data (APPn)
1498
1499 For convenience, we also accept "Expansion" (EXP) markers, although they
1500 are apparently not a part of normal "table" data.
1501 */
1502 sp->jpegtables = p = (unsigned char *)sp->src.next_input_byte;
1503 end_of_data = p + sp->src.bytes_in_buffer;
1504 p += 2;
1505 while (p < end_of_data && p[0] == 0xFF)
1506 switch (p[1])
1507 {
1508 default : goto L;
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;
1545 };
1546 L: if (p - (unsigned char *)sp->jpegtables > 2) /* fake "JPEGTables" */
1547 {
1548
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".
1554 */
1555 sp->jpegtables_length = p - (unsigned char*)sp->jpegtables + 2;
1556 p = sp->jpegtables;
1557 if (!(sp->jpegtables = _TIFFmalloc(sp->jpegtables_length)))
1558 {
1559 TIFFError(module,no_jtable_space);
1560 return 0;
1561 };
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;
1567 }
1568 else sp->jpegtables = 0; /* Don't simulate "JPEGTables" */
1569 if ( CALLJPEG(sp,-1,jpeg_read_header(&sp->cinfo.d,TRUE))
1570 != JPEG_HEADER_OK
1571 ) return 0;
1572 if ( sp->cinfo.d.image_width != segment_width
1573 || sp->cinfo.d.image_height != td->td_imagelength
1574 )
1575 {
1576 TIFFError(module,"Improper JPEG strip/tile size");
1577 return 0;
1578 };
1579 if (sp->cinfo.d.num_components != td->td_samplesperpixel)
1580 {
1581 TIFFError(module,"Improper JPEG component count");
1582 return 0;
1583 };
1584 if (sp->cinfo.d.data_precision != td->td_bitspersample)
1585 {
1586 TIFFError(module,"Improper JPEG data precision");
1587 return 0;
1588 };
1589
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>.
1594 */
1595 subsampling_factors = sp->h_sampling << 3 | sp->v_sampling;
1596 i = 0;
1597 do
1598 {
1599 if ( ( sp->cinfo.d.comp_info[i].h_samp_factor << 3
1600 | sp->cinfo.d.comp_info[i].v_samp_factor
1601 )
1602 != subsampling_factors
1603 )
1604 {
1605 TIFFError(module,"Improper JPEG subsampling factors");
1606 return 0;
1607 };
1608 subsampling_factors = 011; /* Required for image components > 0 */
1609 }
1610 while (++i < sp->cinfo.d.num_components);
1611 }
1612 else /* not JFIF image */
1613 { int (*save)(j_decompress_ptr cinfo) = sp->cinfo.d.marker->read_markers;
1614 register int i;
1615
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.
1622 */
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;
1631
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.
1635 */
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)
1639 ( &sp->cinfo.comm
1640 , JPOOL_IMAGE
1641 , sp->cinfo.d.num_components * sizeof *sp->cinfo.d.comp_info
1642 );
1643 i = 0;
1644 do
1645 {
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];
1649 }
1650 while (++i < sp->cinfo.d.num_components);
1651 switch (jpeg_color_space)
1652 {
1653 case JCS_UNKNOWN :
1654 i = 0;
1655 do
1656 {
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;
1660 }
1661 while (++i < sp->cinfo.d.num_components);
1662 break;
1663 case JCS_GRAYSCALE:
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;
1667 break;
1668 case JCS_RGB :
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';
1672 i = 0;
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);
1676 break;
1677 case JCS_CMYK :
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';
1682 i = 0;
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);
1686 break;
1687 case JCS_YCbCr :
1688 i = 0;
1689 do
1690 {
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;
1697 }
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;
1701 };
1702 sp->cinfo.d.comps_in_scan = td->td_planarconfig == PLANARCONFIG_CONTIG
1703 ? sp->cinfo.d.num_components
1704 : 1;
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 */
1708 {
1709 if (i != JPEG_SUSPENDED) return 0;
1710
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
1715 0th Strip offset.
1716 */
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));
1722 };
1723 if (i != JPEG_HEADER_OK) return 0;
1724 };
1725
1726 /* Some of our initialization must wait until the JPEG Library is initialized
1727 above, in order to override its defaults.
1728 */
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)
1732 ) return 0;
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;
1737
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.
1747
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?
1754 */
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 */
1759 {
1760 if (sp->cinfo.d.raw_data_out)
1761 tif->tif_decoderow = tif->tif_decodestrip = tif->tif_decodetile =
1762 OJPEGDecodeRawSeparate;
1763 else
1764 {
1765 tif->tif_decoderow = tif->tif_decodestrip = tif->tif_decodetile =
1766 OJPEGDecode;
1767
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:
1771 */
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;
1775 };
1776 L3: switch (CALLJPEG(sp,0,jpeg_consume_input(&sp->cinfo.d)))
1777 {
1778 default : goto L3;
1779
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.
1783 */
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
1791# else
1792 *sp->cinfo.d.blocks_in_MCU
1793 *DCTSIZE
1794# endif
1795 < td->td_samplesperpixel
1796 *sp->cinfo.d.image_height
1797 )
1798 {
1799 TIFFError(tif->tif_name,
1800 "Premature end of JPEG bit-stream");
1801 return 0;
1802 }
1803 case JPEG_REACHED_EOI: ;
1804 }
1805 }
1806 else /* pixel-interleaved color planes */
1807 tif->tif_decoderow = tif->tif_decodestrip = tif->tif_decodetile =
1808 downsampled_output ? OJPEGDecodeRawContig : OJPEGDecode;
1809 return 1;
1810# undef td
1811 }
1812
1813static int
1814OJPEGPreDecode(register TIFF *tif,tsample_t s)
1815 { register OJPEGState *sp = OJState(tif);
1816# define td (&tif->tif_dir)
1817
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.
1822 */
1823 if ( (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip)
1824 % td->td_stripsperimage
1825 == 0
1826 )
1827 {
1828 if ( sp->cinfo.d.buffered_image
1829 && !CALLJPEG(sp,0,jpeg_start_output(&sp->cinfo.d,s+1))
1830 ) return 0;
1831 sp->cinfo.d.output_scanline = 0;
1832
1833 /* Mark subsampling buffers "empty". */
1834
1835# ifdef D_LOSSLESS_SUPPORTED
1836 sp->scancount = sp->cinfo.d.min_codec_data_unit;
1837# else
1838 sp->scancount = DCTSIZE;
1839# endif
1840 };
1841 return 1;
1842# undef td
1843 }
1844
1845/*ARGSUSED*/ static void
1846OJPEGPostDecode(register TIFF *tif,tidata_t buf,tsize_t cc)
1847 { register OJPEGState *sp = OJState(tif);
1848# define td (&tif->tif_dir)
1849
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.
1854 */
1855 if (sp->cinfo.d.output_scanline >= sp->cinfo.d.output_height)
1856 {
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)
1860 >= td->td_nstrips-1
1861 ) CALLJPEG(sp,0,jpeg_finish_decompress(&sp->cinfo.d));
1862 }
1863# undef td
1864 }
1865
1866static int
1867OJPEGVSetField(register TIFF *tif,ttag_t tag,va_list ap)
1868{
1869 uint32 v32;
1870 register OJPEGState *sp = OJState(tif);
1871# define td (&tif->tif_dir)
1872 toff_t tiffoff=0;
1873 uint32 bufoff=0;
1874 uint32 code_count=0;
1875 int i2=0;
1876 int k2=0;
1877
1878 switch (tag)
1879 {
1880 default : return
1881 (*sp->vsetparent)(tif,tag,ap);
1882
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.
1897 */
1898 case TIFFTAG_PHOTOMETRIC :
1899 if ( (v32 = (*sp->vsetparent)(tif,tag,ap))
1900 && td->td_photometric == PHOTOMETRIC_YCBCR
1901 )
1902 {
1903 float *ref;
1904 if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE, &ref)) {
1905 float refbw[6];
1906 long top = 1L << td->td_bitspersample;
1907 refbw[0] = 0;
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);
1914 }
1915 }
1916 return v32;
1917
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
1926 mess this is!
1927 */
1928 case TIFFTAG_SOFTWARE :
1929 {
1930 char *software;
1931
1932 v32 = (*sp->vsetparent)(tif,tag,ap);
1933 if( TIFFGetField( tif, TIFFTAG_SOFTWARE, &software )
1934 && strstr( software, "Wang Labs" ) )
1935 sp->is_WANG = 1;
1936 return v32;
1937 }
1938
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 : ;
1950 };
1951 v32 = va_arg(ap,uint32); /* No. of values in this TIFF record */
1952
1953 /* This switch statement is added for OJPEGVSetField */
1954 if(v32 !=0){
1955 switch(tag){
1956 case TIFFTAG_JPEGPROC:
1957 sp->jpegproc=v32;
1958 break;
1959 case TIFFTAG_JPEGIFOFFSET:
1960 sp->jpegifoffset=v32;
1961 break;
1962 case TIFFTAG_JPEGIFBYTECOUNT:
1963 sp->jpegifbytecount=v32;
1964 break;
1965 case TIFFTAG_JPEGRESTARTINTERVAL:
1966 sp->jpegrestartinterval=v32;
1967 break;
1968 case TIFFTAG_JPEGLOSSLESSPREDICTORS:
1969 sp->jpeglosslesspredictors_length=v32;
1970 break;
1971 case TIFFTAG_JPEGPOINTTRANSFORM:
1972 sp->jpegpointtransform_length=v32;
1973 break;
1974 case TIFFTAG_JPEGQTABLES:
1975 sp->jpegqtables_length=v32;
1976 break;
1977 case TIFFTAG_JPEGACTABLES:
1978 sp->jpegactables_length=v32;
1979 break;
1980 case TIFFTAG_JPEGDCTABLES:
1981 sp->jpegdctables_length=v32;
1982 break;
1983 default:
1984 break;
1985 }
1986 }
1987
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
1995 them.
1996 */
1997 switch (tag)
1998 { JHUFF_TBL **h;
1999
2000 /* Validate the JPEG-process code. */
2001
2002 case TIFFTAG_JPEGPROC :
2003 switch (v32)
2004 {
2005 default : TIFFError(tif->tif_name,
2006 "Unknown JPEG process");
2007 return 0;
2008# ifdef C_LOSSLESS_SUPPORTED
2009
2010 /* Image uses (lossy) baseline sequential coding. */
2011
2012 case JPEGPROC_BASELINE: sp->cinfo.d.process = JPROC_SEQUENTIAL;
2013 sp->cinfo.d.data_unit = DCTSIZE;
2014 break;
2015
2016 /* Image uses (lossless) Huffman coding. */
2017
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");
2023 return 0;
2024 case JPEGPROC_BASELINE: ;
2025# endif /* C_LOSSLESS_SUPPORTED */
2026 };
2027 break;
2028
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.
2035 */
2036 case TIFFTAG_JPEGIFOFFSET :
2037 if (v32)
2038 {
2039 sp->src.next_input_byte = tif->tif_base + v32;
2040 break;
2041 };
2042 return 1;
2043 case TIFFTAG_JPEGIFBYTECOUNT :
2044 sp->src.bytes_in_buffer = v32;
2045 break;
2046
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.
2051 */
2052 /*
2053 * Instead, set the field bit so TIFFGetField can get whether or not
2054 * it was set.
2055 */
2056 case TIFFTAG_JPEGRESTARTINTERVAL :
2057 if (v32)
2058 sp->cinfo.d.restart_interval = v32;
2059 break;
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!)
2067 */
2068 case TIFFTAG_JPEGLOSSLESSPREDICTORS:
2069 if (v32)
2070 {
2071 sp->cinfo.d.Ss = *va_arg(ap,uint16 *);
2072 sp->jpeglosslesspredictors =
2073 _TIFFmalloc(sp->jpeglosslesspredictors_length
2074 * sizeof(uint16));
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];
2079 }
2080 sp->jpeglosslesspredictors_length*=sizeof(uint16);
2081 break;
2082 };
2083 return v32;
2084
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!)
2092 */
2093 case TIFFTAG_JPEGPOINTTRANSFORM :
2094 if (v32)
2095 {
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];
2103 }
2104 sp->jpegpointtransform_length*=sizeof(uint16);
2105 break;
2106 }
2107 return v32;
2108
2109 /* We have a vector of offsets to quantization tables, so load 'em! */
2110
2111 case TIFFTAG_JPEGQTABLES :
2112 if (v32)
2113 { uint32 *v;
2114 int i;
2115 if (v32 > NUM_QUANT_TBLS)
2116 {
2117 TIFFError(tif->tif_name,"Too many quantization tables");
2118 return 0;
2119 };
2120 i = 0;
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);
2125 bufoff=0;
2126 for(i2=0;i2<sp->jpegqtables_length;i2++){
2127 TIFFSeekFile(tif, v[i2], SEEK_SET);
2128 TIFFReadFile(tif, &(((unsigned char*)(sp->jpegqtables))[bufoff]),
2129 64);
2130 bufoff+=64;
2131 }
2132 sp->jpegqtables_length=bufoff;
2133 TIFFSeekFile(tif, tiffoff, SEEK_SET);
2134
2135 do /* read quantization table */
2136 { register UINT8 *from = tif->tif_base + *v++;
2137 register UINT16 *to;
2138 register int j = DCTSIZE2;
2139
2140 if (!( sp->cinfo.d.quant_tbl_ptrs[i]
2141 = CALLJPEG(sp,0,jpeg_alloc_quant_table(&sp->cinfo.comm))
2142 )
2143 )
2144 {
2145 TIFFError(JPEGLib_name,"No space for quantization table");
2146 return 0;
2147 };
2148 to = sp->cinfo.d.quant_tbl_ptrs[i]->quantval;
2149 do *to++ = *from++; while (--j > 0);
2150 }
2151 while (++i < v32);
2152 sp->jpegtablesmode |= JPEGTABLESMODE_QUANT;
2153 };
2154 break;
2155
2156 /* We have a vector of offsets to DC Huffman tables, so load 'em! */
2157
2158 case TIFFTAG_JPEGDCTABLES :
2159 h = sp->cinfo.d.dc_huff_tbl_ptrs;
2160 goto L;
2161
2162 /* We have a vector of offsets to AC Huffman tables, so load 'em! */
2163
2164 case TIFFTAG_JPEGACTABLES :
2165 h = sp->cinfo.d.ac_huff_tbl_ptrs;
2166 L: if (v32)
2167 { uint32 *v;
2168 int i;
2169 if (v32 > NUM_HUFF_TBLS)
2170 {
2171 TIFFError(tif->tif_name,"Too many Huffman tables");
2172 return 0;
2173 };
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);
2179 bufoff=0;
2180 code_count=0;
2181 for(i2=0;i2<sp->jpegdctables_length;i2++){
2182 TIFFSeekFile(tif, v[i2], SEEK_SET);
2183 TIFFReadFile(tif,
2184 &(((unsigned char*)(sp->jpegdctables))[bufoff]),
2185 16);
2186 code_count=0;
2187 for(k2=0;k2<16;k2++){
2188 code_count+=((unsigned char*)(sp->jpegdctables))[k2+bufoff];
2189 }
2190 TIFFReadFile(tif,
2191 &(((unsigned char*)(sp->jpegdctables))[bufoff+16]),
2192 code_count);
2193 bufoff+=16;
2194 bufoff+=code_count;
2195 }
2196 sp->jpegdctables_length=bufoff;
2197 TIFFSeekFile(tif, tiffoff, SEEK_SET);
2198 }
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);
2203 bufoff=0;
2204 code_count=0;
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);
2208 code_count=0;
2209 for(k2=0;k2<16;k2++){
2210 code_count+=((unsigned char*)(sp->jpegactables))[k2+bufoff];
2211 }
2212 TIFFReadFile(tif, &(((unsigned char*)(sp->jpegactables))[bufoff+16]), code_count);
2213 bufoff+=16;
2214 bufoff+=code_count;
2215 }
2216 sp->jpegactables_length=bufoff;
2217 TIFFSeekFile(tif, tiffoff, SEEK_SET);
2218 }
2219 i = 0;
2220 do /* copy each Huffman table */
2221 { int size = 0;
2222 register UINT8 *from = tif->tif_base + *v++, *to;
2223 register int j = sizeof (*h)->bits;
2224
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.
2231 */
2232 if (!( *h
2233 = CALLJPEG(sp,0,jpeg_alloc_huff_table(&sp->cinfo.comm))
2234 )
2235 )
2236 {
2237 TIFFError(JPEGLib_name,"No space for Huffman table");
2238 return 0;
2239 };
2240 to = (*h++)->bits;
2241 *to++ = 0;
2242 while (--j > 0) size += *to++ = *from++; /* Copy 16 Bytes */
2243 if (size > sizeof (*h)->huffval/sizeof *(*h)->huffval)
2244 {
2245 TIFFError(tif->tif_name,"Huffman table too big");
2246 return 0;
2247 };
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 */
2251 }
2252 while (++i < v32);
2253 sp->jpegtablesmode |= JPEGTABLESMODE_HUFF;
2254 };
2255 break;
2256
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.
2263 */
2264 case TIFFTAG_WANG_PAGECONTROL :
2265 if (v32 == 0) v32 = -1;
2266 sp->is_WANG = v32;
2267 tag = TIFFTAG_JPEGPROC+FIELD_WANG_PAGECONTROL-FIELD_JPEGPROC;
2268 break;
2269
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).
2273 */
2274 case TIFFTAG_JPEGCOLORMODE :
2275 sp->jpegcolormode = v32;
2276
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.
2279 */
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])
2284 != 011
2285 && sp->jpegcolormode == JPEGCOLORMODE_RGB
2286 ) tif->tif_flags |= TIFF_UPSAMPLED;
2287
2288 /* If the up-sampling state changed, re-calculate tile size. */
2289
2290 if ((tif->tif_flags ^ v32) & TIFF_UPSAMPLED)
2291 {
2292 tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tsize_t) -1;
2293 tif->tif_flags |= TIFF_DIRTYDIRECT;
2294 };
2295 return 1;
2296 };
2297 TIFFSetFieldBit(tif,tag-TIFFTAG_JPEGPROC+FIELD_JPEGPROC);
2298 return 1;
2299# undef td
2300 }
2301
2302static int
2303OJPEGVGetField(register TIFF *tif,ttag_t tag,va_list ap)
2304 { register OJPEGState *sp = OJState(tif);
2305
2306 switch (tag)
2307 {
2308
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,
2312 keep mum.
2313 */
2314 case TIFFTAG_JPEGTABLES :
2315 if (sp->jpegtables_length) /* we have "new"-style JPEG tables */
2316 {
2317 *va_arg(ap,uint32 *) = sp->jpegtables_length;
2318 *va_arg(ap,char **) = sp->jpegtables;
2319 return 1;
2320 };
2321
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).
2325 */
2326 case TIFFTAG_JPEGCOLORMODE :
2327 *va_arg(ap,uint32 *) = sp->jpegcolormode;
2328 return 1;
2329
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.
2333 */
2334 case TIFFTAG_JPEGPROC :
2335 *va_arg(ap, uint16*)=sp->jpegproc;
2336 return(1);
2337 break;
2338 case TIFFTAG_JPEGIFOFFSET :
2339 *va_arg(ap, uint32*)=sp->jpegifoffset;
2340 return(1);
2341 break;
2342 case TIFFTAG_JPEGIFBYTECOUNT :
2343 *va_arg(ap, uint32*)=sp->jpegifbytecount;
2344 return(1);
2345 break;
2346 case TIFFTAG_JPEGRESTARTINTERVAL :
2347 *va_arg(ap, uint32*)=sp->jpegrestartinterval;
2348 return(1);
2349 break;
2350 case TIFFTAG_JPEGLOSSLESSPREDICTORS:
2351 *va_arg(ap, uint32*)=sp->jpeglosslesspredictors_length;
2352 *va_arg(ap, void**)=sp->jpeglosslesspredictors;
2353 return(1);
2354 break;
2355 case TIFFTAG_JPEGPOINTTRANSFORM :
2356 *va_arg(ap, uint32*)=sp->jpegpointtransform_length;
2357 *va_arg(ap, void**)=sp->jpegpointtransform;
2358 return(1);
2359 break;
2360 case TIFFTAG_JPEGQTABLES :
2361 *va_arg(ap, uint32*)=sp->jpegqtables_length;
2362 *va_arg(ap, void**)=sp->jpegqtables;
2363 return(1);
2364 break;
2365 case TIFFTAG_JPEGDCTABLES :
2366 *va_arg(ap, uint32*)=sp->jpegdctables_length;
2367 *va_arg(ap, void**)=sp->jpegdctables;
2368 return(1);
2369 break;
2370 case TIFFTAG_JPEGACTABLES :
2371 *va_arg(ap, uint32*)=sp->jpegactables_length;
2372 *va_arg(ap, void**)=sp->jpegactables;
2373 return(1);
2374 break;
2375 };
2376 return (*sp->vgetparent)(tif,tag,ap);
2377 }
2378
2379static void
2380OJPEGPrintDir(register TIFF *tif,FILE *fd,long flags)
2381 { register OJPEGState *sp = OJState(tif);
2382
2383 if ( ( flags
2384 & (TIFFPRINT_JPEGQTABLES|TIFFPRINT_JPEGDCTABLES|TIFFPRINT_JPEGACTABLES)
2385 )
2386 && sp->jpegtables_length
2387 )
2388 fprintf(fd," JPEG Table Data: <present>, %lu bytes\n",
2389 sp->jpegtables_length);
2390 }
2391
2392static uint32
2393OJPEGDefaultStripSize(register TIFF *tif,register uint32 s)
2394 { register OJPEGState *sp = OJState(tif);
2395# define td (&tif->tif_dir)
2396
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
2401# else
2402 ? DCTSIZE
2403# endif
2404# ifdef C_LOSSLESS_SUPPORTED
2405 : sp->cinfo.c.data_unit;
2406# else
2407 : DCTSIZE;
2408# endif
2409
2410 size = TIFFroundup(size,16);
2411 s = TIFFroundup(s,td->td_ycbcrsubsampling[1]*size);
2412 };
2413 return s;
2414# undef td
2415 }
2416
2417static void
2418OJPEGDefaultTileSize(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)
2422
2423 size = sp->cinfo.comm.is_decompressor
2424# ifdef D_LOSSLESS_SUPPORTED
2425 ? sp->cinfo.d.min_codec_data_unit
2426# else
2427 ? DCTSIZE
2428# endif
2429# ifdef C_LOSSLESS_SUPPORTED
2430 : sp->cinfo.c.data_unit;
2431# else
2432 : DCTSIZE;
2433# endif
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);
2438# undef td
2439 }
2440
2441static void
2442OJPEGCleanUp(register TIFF *tif)
2443 { register OJPEGState *sp;
2444
2445 if ( (sp = OJState(tif)) )
2446 {
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;
2452 }
2453 if (sp->jpegpointtransform) {
2454 _TIFFfree(sp->jpegpointtransform);
2455 sp->jpegpointtransform=0;
2456 }
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.
2462 */
2463 if (!isMapped(tif) && tif->tif_base) /* free whole-file buffer */
2464 {
2465 _TIFFfree(tif->tif_base);
2466 tif->tif_base = 0;
2467 tif->tif_size = 0;
2468 };
2469 _TIFFfree(sp); /* Release local variables */
2470 tif->tif_data = 0;
2471 }
2472 }
2473
2474int
2475TIFFInitOJPEG(register TIFF *tif,int scheme)
2476 { register OJPEGState *sp;
2477# define td (&tif->tif_dir)
2478# ifndef never
2479
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!
2485 */
2486 if (tif->tif_mode != O_RDONLY) return _notSupported(tif);
2487# endif /* never */
2488 if (!isMapped(tif))
2489 {
2490
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!
2506 */
2507 if (!(tif->tif_base = _TIFFmalloc(tif->tif_size=TIFFGetFileSize(tif))))
2508 {
2509 TIFFError(tif->tif_name,"Cannot allocate file buffer");
2510 return 0;
2511 };
2512 if (!SeekOK(tif,0) || !ReadOK(tif,tif->tif_base,tif->tif_size))
2513 {
2514 TIFFError(tif->tif_name,"Cannot read file");
2515 return 0;
2516 }
2517 };
2518
2519 /* Allocate storage for this module's per-file variables. */
2520
2521 if (!(tif->tif_data = (tidata_t)_TIFFmalloc(sizeof *sp)))
2522 {
2523 TIFFError("TIFFInitOJPEG","No space for JPEG state block");
2524 return 0;
2525 };
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;
2531
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.
2536 */
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;
2548# ifdef never
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;
2555# endif /* never */
2556 tif->tif_setupdecode = OJPEGSetupDecode;
2557 tif->tif_predecode = OJPEGPreDecode;
2558 tif->tif_postdecode = OJPEGPostDecode;
2559 tif->tif_cleanup = OJPEGCleanUp;
2560
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.
2566 */
2567 if (tif->tif_header.tiff_diroff > sizeof tif->tif_header)
2568 {
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;
2572 }
2573 else /* this case is ugly! */
2574 { uint32 maxoffset = tif->tif_size;
2575 uint16 dircount;
2576
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.
2580 */
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),
2584 sizeof dircount);
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
2589 + maxoffset;
2590 };
2591
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.
2594 */
2595 sp->cinfo.d.data_precision = 8;
2596# ifdef C_LOSSLESS_SUPPORTED
2597
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.
2600 */
2601 sp->cinfo.d.data_unit = DCTSIZE;
2602# endif /* C_LOSSLESS_SUPPORTED */
2603
2604 /* Initialize other CODEC-specific variables requiring default values. */
2605
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;
2618 sp->jpegqtables=0;
2619 sp->jpegqtables_length=0;
2620 sp->jpegdctables=0;
2621 sp->jpegdctables_length=0;
2622 sp->jpegactables=0;
2623 sp->jpegactables_length=0;
2624 return 1;
2625# undef td
2626 }
2627#endif /* OJPEG_SUPPORT */
2628
2629/* vim: set ts=8 sts=8 sw=8 noet: */
Note: See TracBrowser for help on using the repository browser.