Update to 2.0.0 tree from current Fremantle build
[opencv] / 3rdparty / libtiff / tif_ojpeg.c
1 /* $Id: tif_ojpeg.c,v 1.1 2005-06-17 13:54:52 vp153 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 */
144 extern 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
170 typedef struct jpeg_destination_mgr jpeg_destination_mgr;
171 typedef struct jpeg_source_mgr jpeg_source_mgr;
172 typedef struct jpeg_error_mgr jpeg_error_mgr;
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 */
183 typedef 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
240 static 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   };
313 static const char JPEGLib_name[]={"JPEG Library"},
314                   bad_bps[]={"%u BitsPerSample not allowed for JPEG"},
315                   bad_photometry[]={"PhotometricInterpretation %u not allowed for JPEG"},
316                   bad_subsampling[]={"invalid YCbCr subsampling factor(s)"},
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 */
329 static void
330 TIFFojpeg_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
346 static void
347 TIFFojpeg_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
366 static int
367 TIFFojpeg_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 */
379 static void
380 std_init_destination(register j_compress_ptr cinfo){} /* "Dummy" stub */
381
382 static boolean
383 std_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
396 static void
397 std_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
410 static void
411 tables_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
420 static boolean
421 tables_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
439 static void
440 tables_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
449 TIFFojpeg_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
473 static 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 */
486 static void
487 std_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
500 static boolean
501 std_fill_input_buffer(register j_decompress_ptr cinfo)
502   { static const JOCTET dummy_EOI[2]={0xFF,JPEG_EOI};
503 #   define sp ((OJPEGState *)cinfo)
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
516 static void
517 std_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
535 std_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 */
542 static int
543 alloc_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
585 OJPEGEncode(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s)
586   { tsize_t rows;                          /* No. of unprocessed rows in file */
587     register OJPEGState *sp = OJState(tif);
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
608 OJPEGEncodeRaw(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s)
609   { tsize_t rows;                          /* No. of unprocessed rows in file */
610     JDIMENSION lines_per_MCU, size;
611     register OJPEGState *sp = OJState(tif);
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
686 static int
687 OJPEGSetupEncode(register TIFF *tif)
688   { static const char module[]={"OJPEGSetupEncode"};
689     uint32 segment_height, segment_width;
690     int status = 1;                              /* Assume success by default */
691     register OJPEGState *sp = OJState(tif);
692 #   define td (&tif->tif_dir)
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
908 static int
909 OJPEGPreEncode(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
944 static int
945 OJPEGPostEncode(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
996 OJPEGDecode(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s)
997   { tsize_t bytesperline = isTiled(tif)
998                          ? TIFFTileRowSize(tif)
999                          : tif->tif_scanlinesize,
1000             rows;                          /* No. of unprocessed rows in file */
1001     register OJPEGState *sp = OJState(tif);
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
1046 OJPEGDecodeRawContig(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s)
1047   { tsize_t rows;                          /* No. of unprocessed rows in file */
1048     JDIMENSION lines_per_MCU, size;
1049     register OJPEGState *sp = OJState(tif);
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
1140 OJPEGDecodeRawSeparate(TIFF *tif,register tidata_t buf,tsize_t cc,tsample_t s)
1141   { tsize_t rows;                          /* No. of unprocessed rows in file */
1142     JDIMENSION lines_per_MCU,
1143                size,                                             /* ...of MCU */
1144                v;                   /* Component's vertical up-sampling ratio */
1145     register OJPEGState *sp = OJState(tif);
1146     register jpeg_component_info *compptr = sp->cinfo.d.comp_info + s;
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)
1192 fake_SOS_marker(j_decompress_ptr cinfo){return JPEG_REACHED_SOS;}
1193
1194 /*ARGSUSED*/ METHODDEF(int)
1195 suspend(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 */
1204 METHODDEF(void)
1205 ycc_rgb_convert(register j_decompress_ptr cinfo,JSAMPIMAGE in,JDIMENSION row,
1206                 register JSAMPARRAY out,register int nrows)
1207   { typedef struct                /* "jdcolor.c" color-space conversion state */
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
1276 METHODDEF(void)
1277 null_convert(register j_decompress_ptr cinfo,JSAMPIMAGE in,JDIMENSION row,
1278              register JSAMPARRAY out,register int nrows)
1279   { register JSAMPARRAY irowp = in[cinfo->output_scan_number - 1] + row;
1280
1281     while (--nrows >= 0) _TIFFmemcpy(*out++,*irowp++,cinfo->output_width);
1282   }
1283
1284 static int
1285 OJPEGSetupDecode(register TIFF *tif)
1286   { static char module[]={"OJPEGSetupDecode"};
1287     J_COLOR_SPACE jpeg_color_space,   /* Color space of JPEG-compressed image */
1288                   out_color_space;       /* Color space of decompressed image */
1289     uint32 segment_width;
1290     int status = 1;                              /* Assume success by default */
1291     boolean downsampled_output=FALSE, /* <=> Want JPEG Library's "raw" image? */
1292             is_JFIF;                                       /* <=> JFIF image? */
1293     register OJPEGState *sp = OJState(tif);
1294 #   define td (&tif->tif_dir)
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
1813 static int
1814 OJPEGPreDecode(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
1846 OJPEGPostDecode(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
1866 static int
1867 OJPEGVSetField(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
1881      /* If a "ReferenceBlackWhite" TIFF tag appears in the file explicitly, undo
1882         any modified default definition that we might have installed below, then
1883         install the real one.
1884      */
1885         case TIFFTAG_REFERENCEBLACKWHITE   : if (td->td_refblackwhite)
1886                                                {
1887                                                  _TIFFfree(td->td_refblackwhite);
1888                                                  td->td_refblackwhite = 0;
1889                                                };
1890         default                            : return
1891                                                (*sp->vsetparent)(tif,tag,ap);
1892
1893      /* BEWARE OF KLUDGE:  Some old-format JPEG-in-TIFF files, including those
1894                            produced by the Wang Imaging application for Micro-
1895         soft Windows, illegally omit a "ReferenceBlackWhite" TIFF tag, even
1896         though the TIFF specification's default is intended for the RGB color
1897         space and is inappropriate for the YCbCr color space ordinarily used for
1898         JPEG images.  Since many TIFF client applications request the value of
1899         this tag immediately after a TIFF image directory is parsed, and before
1900         any other code in this module receives control, we are forced to fix
1901         this problem very early in image-file processing.  Fortunately, legal
1902         TIFF files are supposed to store their tags in numeric order, so a
1903         mandatory "PhotometricInterpretation" tag should always appear before
1904         an optional "ReferenceBlackWhite" tag.  Hence, we slyly peek ahead when
1905         we discover the desired photometry, by installing modified black and
1906         white reference levels.
1907      */
1908         case TIFFTAG_PHOTOMETRIC           :
1909           if (   (v32 = (*sp->vsetparent)(tif,tag,ap))
1910               && td->td_photometric == PHOTOMETRIC_YCBCR
1911              )
1912           {
1913             if ( (td->td_refblackwhite = _TIFFmalloc(6*sizeof(float))) )
1914               { register long top = 1 << td->td_bitspersample;
1915
1916                 td->td_refblackwhite[0] = 0;
1917                 td->td_refblackwhite[1] = td->td_refblackwhite[3] =
1918                 td->td_refblackwhite[5] = top - 1;
1919                 td->td_refblackwhite[2] = td->td_refblackwhite[4] = top >> 1;
1920               }
1921             else
1922               {
1923                 TIFFError(tif->tif_name,
1924                   "Cannot set default reference black and white levels");
1925                 v32 = 0;
1926               };
1927           }
1928           return v32;
1929
1930      /* BEWARE OF KLUDGE:  According to Charles Auer <Bumble731@msn.com>, if our
1931                            input is a multi-image (multi-directory) JPEG-in-TIFF
1932         file is produced by the Wang Imaging application on Microsoft Windows,
1933         for some reason the first directory excludes the vendor-specific "WANG
1934         PageControl" tag (32934) that we check below, so the only other way to
1935         identify these directories is apparently to look for a software-
1936         identification tag with the substring, "Wang Labs".  Single-image files
1937         can apparently pass both tests, which causes no harm here, but what a
1938         mess this is!
1939      */
1940         case TIFFTAG_SOFTWARE              :
1941         {
1942             char *software;
1943
1944             v32 = (*sp->vsetparent)(tif,tag,ap);
1945             if( TIFFGetField( tif, TIFFTAG_SOFTWARE, &software )
1946                 && strstr( software, "Wang Labs" ) )
1947                 sp->is_WANG = 1;
1948             return v32;
1949         }
1950
1951         case TIFFTAG_JPEGPROC              :
1952         case TIFFTAG_JPEGIFOFFSET          :
1953         case TIFFTAG_JPEGIFBYTECOUNT       :
1954         case TIFFTAG_JPEGRESTARTINTERVAL   :
1955         case TIFFTAG_JPEGLOSSLESSPREDICTORS:
1956         case TIFFTAG_JPEGPOINTTRANSFORM    :
1957         case TIFFTAG_JPEGQTABLES           :
1958         case TIFFTAG_JPEGDCTABLES          :
1959         case TIFFTAG_JPEGACTABLES          :
1960         case TIFFTAG_WANG_PAGECONTROL      :
1961         case TIFFTAG_JPEGCOLORMODE         : ;
1962       };
1963     v32 = va_arg(ap,uint32); /* No. of values in this TIFF record */
1964
1965     /* This switch statement is added for OJPEGVSetField */
1966     if(v32 !=0){
1967         switch(tag){
1968             case TIFFTAG_JPEGPROC:
1969                 sp->jpegproc=v32;
1970                 break;
1971             case TIFFTAG_JPEGIFOFFSET:
1972                 sp->jpegifoffset=v32;
1973                 break;
1974             case TIFFTAG_JPEGIFBYTECOUNT:
1975                 sp->jpegifbytecount=v32;
1976                 break;
1977             case TIFFTAG_JPEGRESTARTINTERVAL:
1978                 sp->jpegrestartinterval=v32;
1979                 break;
1980             case TIFFTAG_JPEGLOSSLESSPREDICTORS:
1981                 sp->jpeglosslesspredictors_length=v32;
1982                 break;
1983             case TIFFTAG_JPEGPOINTTRANSFORM:
1984                 sp->jpegpointtransform_length=v32;
1985                 break;
1986             case TIFFTAG_JPEGQTABLES:
1987                 sp->jpegqtables_length=v32;
1988                 break;
1989             case TIFFTAG_JPEGACTABLES:
1990                 sp->jpegactables_length=v32;
1991                 break;
1992             case TIFFTAG_JPEGDCTABLES:
1993                 sp->jpegdctables_length=v32;
1994                 break;
1995             default:
1996                 break;
1997         }
1998     }
1999
2000  /* BEWARE:  The following actions apply only if we are reading a "source" TIFF
2001              image to be decompressed for a client application program.  If we
2002     ever enhance this file's CODEC to write "destination" JPEG-in-TIFF images,
2003     we'll need an "if"- and another "switch"-statement below, because we'll
2004     probably want to store these records' values in some different places.  Most
2005     of these need not be parsed here in order to decode JPEG bit stream, so we
2006     set boolean flags to note that they have been seen, but we otherwise ignore
2007     them.
2008  */
2009     switch (tag)
2010       { JHUFF_TBL **h;
2011
2012      /* Validate the JPEG-process code. */
2013
2014         case TIFFTAG_JPEGPROC              :
2015           switch (v32)
2016             {
2017               default               : TIFFError(tif->tif_name,
2018                                         "Unknown JPEG process");
2019                                       return 0;
2020 #             ifdef C_LOSSLESS_SUPPORTED
2021
2022            /* Image uses (lossy) baseline sequential coding. */
2023
2024               case JPEGPROC_BASELINE: sp->cinfo.d.process = JPROC_SEQUENTIAL;
2025                                       sp->cinfo.d.data_unit = DCTSIZE;
2026                                       break;
2027
2028            /* Image uses (lossless) Huffman coding. */
2029
2030               case JPEGPROC_LOSSLESS: sp->cinfo.d.process = JPROC_LOSSLESS;
2031                                       sp->cinfo.d.data_unit = 1;
2032 #             else /* not C_LOSSLESS_SUPPORTED */
2033               case JPEGPROC_LOSSLESS: TIFFError(JPEGLib_name,
2034                                         "Does not support lossless Huffman coding");
2035                                       return 0;
2036               case JPEGPROC_BASELINE: ;
2037 #             endif /* C_LOSSLESS_SUPPORTED */
2038             };
2039           break;
2040
2041      /* The TIFF Version 6.0 specification says that if the value of a TIFF
2042         "JPEGInterchangeFormat" record is 0, then we are to behave as if this
2043         record were absent; i.e., the data does *not* represent a JPEG Inter-
2044         change Format File (JFIF), so don't even set the boolean "I've been
2045         here" flag below.  Otherwise, the field's value represents the file
2046         offset of the JPEG SOI marker.
2047      */
2048         case TIFFTAG_JPEGIFOFFSET          :
2049           if (v32)
2050             {
2051               sp->src.next_input_byte = tif->tif_base + v32;
2052               break;
2053             };
2054           return 1;
2055         case TIFFTAG_JPEGIFBYTECOUNT       :
2056           sp->src.bytes_in_buffer = v32;
2057           break;
2058
2059      /* The TIFF Version 6.0 specification says that if the JPEG "Restart"
2060         marker interval is 0, then the data has no "Restart" markers; i.e., we
2061         must behave as if this TIFF record were absent.  So, don't even set the
2062         boolean "I've been here" flag below.
2063      */
2064      /*
2065       * Instead, set the field bit so TIFFGetField can get whether or not
2066       * it was set.
2067       */
2068         case TIFFTAG_JPEGRESTARTINTERVAL   :
2069           if (v32)
2070               sp->cinfo.d.restart_interval = v32;
2071               break;
2072      /* The TIFF Version 6.0 specification says that this tag is supposed to be
2073         a vector containing a value for each image component, but for lossless
2074         Huffman coding (the only JPEG process defined by the specification for
2075         which this tag should be needed), ISO IS 10918-1 uses only a single
2076         value, equivalent to the "Ss" field in a JPEG bit-stream's "Start of
2077         Scan" (SOS) marker.  So, we extract the first vector element and ignore
2078         the rest.  (I hope this is correct!)
2079      */
2080         case TIFFTAG_JPEGLOSSLESSPREDICTORS:
2081            if (v32)
2082              {
2083                sp->cinfo.d.Ss = *va_arg(ap,uint16 *);
2084                sp->jpeglosslesspredictors = 
2085                     _TIFFmalloc(sp->jpeglosslesspredictors_length
2086                                 * sizeof(uint16));
2087                if(sp->jpeglosslesspredictors==NULL){return(0);}
2088                for(i2=0;i2<sp->jpeglosslesspredictors_length;i2++){
2089                 ((uint16*)sp->jpeglosslesspredictors)[i2] =
2090                         ((uint16*)sp->cinfo.d.Ss)[i2];
2091                }
2092                sp->jpeglosslesspredictors_length*=sizeof(uint16);
2093                break;
2094              };
2095            return v32;
2096
2097      /* The TIFF Version 6.0 specification says that this tag is supposed to be
2098         a vector containing a value for each image component, but for lossless
2099         Huffman coding (the only JPEG process defined by the specification for
2100         which this tag should be needed), ISO IS 10918-1 uses only a single
2101         value, equivalent to the "Al" field in a JPEG bit-stream's "Start of
2102         Scan" (SOS) marker.  So, we extract the first vector element and ignore
2103         the rest.  (I hope this is correct!)
2104      */
2105         case TIFFTAG_JPEGPOINTTRANSFORM    :
2106            if (v32)
2107              {
2108                sp->cinfo.d.Al = *va_arg(ap,uint16 *);
2109                sp->jpegpointtransform =
2110                     _TIFFmalloc(sp->jpegpointtransform_length*sizeof(uint16));
2111                if(sp->jpegpointtransform==NULL){return(0);}
2112                for(i2=0;i2<sp->jpegpointtransform_length;i2++) {
2113                 ((uint16*)sp->jpegpointtransform)[i2] =
2114                         ((uint16*)sp->cinfo.d.Al)[i2];
2115                }
2116                sp->jpegpointtransform_length*=sizeof(uint16);
2117                break;
2118              }
2119            return v32;
2120
2121      /* We have a vector of offsets to quantization tables, so load 'em! */
2122
2123         case TIFFTAG_JPEGQTABLES           :
2124           if (v32)
2125             { uint32 *v;
2126               int i;
2127               if (v32 > NUM_QUANT_TBLS)
2128                 {
2129                   TIFFError(tif->tif_name,"Too many quantization tables");
2130                   return 0;
2131                 };
2132               i = 0;
2133               v = va_arg(ap,uint32 *);
2134                 sp->jpegqtables=_TIFFmalloc(64*sp->jpegqtables_length);
2135                 if(sp->jpegqtables==NULL){return(0);}
2136                 tiffoff = TIFFSeekFile(tif, 0, SEEK_CUR);
2137                 bufoff=0;
2138                 for(i2=0;i2<sp->jpegqtables_length;i2++){
2139                     TIFFSeekFile(tif, v[i2], SEEK_SET);
2140                     TIFFReadFile(tif, &(((unsigned char*)(sp->jpegqtables))[bufoff]),
2141                                  64);
2142                     bufoff+=64;
2143                 }
2144                 sp->jpegqtables_length=bufoff;
2145                 TIFFSeekFile(tif, tiffoff, SEEK_SET);
2146
2147               do /* read quantization table */
2148                 { register UINT8 *from = tif->tif_base + *v++;
2149                   register UINT16 *to;
2150                   register int j = DCTSIZE2;
2151
2152                   if (!( sp->cinfo.d.quant_tbl_ptrs[i]
2153                        = CALLJPEG(sp,0,jpeg_alloc_quant_table(&sp->cinfo.comm))
2154                        )
2155                      )
2156                     {
2157                       TIFFError(JPEGLib_name,"No space for quantization table");
2158                       return 0;
2159                     };
2160                   to = sp->cinfo.d.quant_tbl_ptrs[i]->quantval;
2161                   do *to++ = *from++; while (--j > 0);
2162                 }
2163               while (++i < v32);
2164               sp->jpegtablesmode |= JPEGTABLESMODE_QUANT;
2165             };
2166           break;
2167
2168      /* We have a vector of offsets to DC Huffman tables, so load 'em! */
2169
2170         case TIFFTAG_JPEGDCTABLES          :
2171           h = sp->cinfo.d.dc_huff_tbl_ptrs;
2172           goto L;
2173
2174      /* We have a vector of offsets to AC Huffman tables, so load 'em! */
2175
2176         case TIFFTAG_JPEGACTABLES          :
2177           h = sp->cinfo.d.ac_huff_tbl_ptrs;
2178        L: if (v32)
2179             { uint32 *v;
2180               int i;
2181               if (v32 > NUM_HUFF_TBLS)
2182                 {
2183                   TIFFError(tif->tif_name,"Too many Huffman tables");
2184                   return 0;
2185                 };
2186               v = va_arg(ap,uint32 *);
2187                 if(tag == TIFFTAG_JPEGDCTABLES) {
2188                     sp->jpegdctables=_TIFFmalloc(272*sp->jpegdctables_length);
2189                     if(sp->jpegdctables==NULL){return(0);}
2190                     tiffoff = TIFFSeekFile(tif, 0, SEEK_CUR);
2191                     bufoff=0;
2192                     code_count=0;                
2193                     for(i2=0;i2<sp->jpegdctables_length;i2++){
2194                         TIFFSeekFile(tif, v[i2], SEEK_SET);
2195                         TIFFReadFile(tif,
2196                                      &(((unsigned char*)(sp->jpegdctables))[bufoff]),
2197                                      16);
2198                         code_count=0;
2199                         for(k2=0;k2<16;k2++){
2200                             code_count+=((unsigned char*)(sp->jpegdctables))[k2+bufoff];
2201                         }
2202                         TIFFReadFile(tif,
2203                                      &(((unsigned char*)(sp->jpegdctables))[bufoff+16]),
2204                                      code_count);
2205                         bufoff+=16;
2206                         bufoff+=code_count;
2207                     }
2208                     sp->jpegdctables_length=bufoff;
2209                     TIFFSeekFile(tif, tiffoff, SEEK_SET);
2210                 }
2211                 if(tag==TIFFTAG_JPEGACTABLES){
2212                     sp->jpegactables=_TIFFmalloc(272*sp->jpegactables_length);
2213                     if(sp->jpegactables==NULL){return(0);}
2214                     tiffoff = TIFFSeekFile(tif, 0, SEEK_CUR);
2215                     bufoff=0;
2216                     code_count=0;                
2217                     for(i2=0;i2<sp->jpegactables_length;i2++){
2218                         TIFFSeekFile(tif, v[i2], SEEK_SET);
2219                         TIFFReadFile(tif, &(((unsigned char*)(sp->jpegactables))[bufoff]), 16);
2220                         code_count=0;
2221                         for(k2=0;k2<16;k2++){
2222                             code_count+=((unsigned char*)(sp->jpegactables))[k2+bufoff];
2223                         }
2224                         TIFFReadFile(tif, &(((unsigned char*)(sp->jpegactables))[bufoff+16]), code_count);
2225                         bufoff+=16;
2226                         bufoff+=code_count;
2227                     }
2228                     sp->jpegactables_length=bufoff;
2229                     TIFFSeekFile(tif, tiffoff, SEEK_SET);
2230                 }
2231               i = 0;
2232               do /* copy each Huffman table */
2233                 { int size = 0;
2234                   register UINT8 *from = tif->tif_base + *v++, *to;
2235                   register int j = sizeof (*h)->bits;
2236
2237                /* WARNING:  This code relies on the fact that an image file not
2238                             "memory mapped" was read entirely into a single
2239                   buffer by "TIFFInitOJPEG()", so we can do a fast memory-to-
2240                   memory copy here.  Each table consists of 16 Bytes, which are
2241                   suffixed to a 0 Byte when copied, followed by a variable
2242                   number of Bytes whose length is the sum of the first 16.
2243                */
2244                   if (!( *h
2245                        = CALLJPEG(sp,0,jpeg_alloc_huff_table(&sp->cinfo.comm))
2246                        )
2247                      )
2248                     {
2249                       TIFFError(JPEGLib_name,"No space for Huffman table");
2250                       return 0;
2251                     };
2252                   to = (*h++)->bits;
2253                   *to++ = 0;
2254                   while (--j > 0) size += *to++ = *from++; /* Copy 16 Bytes */
2255                   if (size > sizeof (*h)->huffval/sizeof *(*h)->huffval)
2256                     {
2257                       TIFFError(tif->tif_name,"Huffman table too big");
2258                       return 0;
2259                     };
2260                   if ((j = size) > 0) do *to++ = *from++; while (--j > 0);
2261                   while (++size <= sizeof (*h)->huffval/sizeof *(*h)->huffval)
2262                     *to++ = 0; /* Zero the rest of the table for cleanliness */
2263                 }
2264               while (++i < v32);
2265               sp->jpegtablesmode |= JPEGTABLESMODE_HUFF;
2266             };
2267           break;
2268
2269      /* The following vendor-specific TIFF tag occurs in (highly illegal) files
2270         produced by the Wang Imaging application for Microsoft Windows.  These
2271         can apparently have several "pages", in which case this tag specifies
2272         the offset of a "page control" structure, which we don't currently know
2273         how to handle.  0 indicates a 1-page image with no "page control", which
2274         we make a feeble effort to handle.
2275      */
2276         case TIFFTAG_WANG_PAGECONTROL      :
2277           if (v32 == 0) v32 = -1;
2278           sp->is_WANG = v32;
2279           tag = TIFFTAG_JPEGPROC+FIELD_WANG_PAGECONTROL-FIELD_JPEGPROC;
2280           break;
2281
2282      /* This pseudo tag indicates whether our caller is expected to do YCbCr <->
2283         RGB color-space conversion (JPEGCOLORMODE_RAW <=> 0) or whether we must
2284         ask the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1).
2285      */
2286         case TIFFTAG_JPEGCOLORMODE         :
2287           sp->jpegcolormode = v32;
2288
2289        /* Mark the image to indicate whether returned data is up-sampled, so
2290           that "TIFF{Strip,Tile}Size()" reflect the true amount of data present.
2291        */
2292           v32 = tif->tif_flags; /* Save flags temporarily */
2293           tif->tif_flags &= ~TIFF_UPSAMPLED;
2294           if (   td->td_photometric == PHOTOMETRIC_YCBCR
2295               &&    (td->td_ycbcrsubsampling[0]<<3 | td->td_ycbcrsubsampling[1])
2296                  != 011
2297               && sp->jpegcolormode == JPEGCOLORMODE_RGB
2298              ) tif->tif_flags |= TIFF_UPSAMPLED;
2299
2300        /* If the up-sampling state changed, re-calculate tile size. */
2301
2302           if ((tif->tif_flags ^ v32) & TIFF_UPSAMPLED)
2303             {
2304               tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tsize_t) -1;
2305               tif->tif_flags |= TIFF_DIRTYDIRECT;
2306             };
2307           return 1;
2308       };
2309     TIFFSetFieldBit(tif,tag-TIFFTAG_JPEGPROC+FIELD_JPEGPROC);
2310     return 1;
2311 #   undef td
2312   }
2313
2314 static int
2315 OJPEGVGetField(register TIFF *tif,ttag_t tag,va_list ap)
2316   { register OJPEGState *sp = OJState(tif);
2317
2318     switch (tag)
2319       {
2320
2321      /* If this file has managed to synthesize a set of consolidated "metadata"
2322         tables for the current (post-TIFF Version 6.0 specification) JPEG-in-
2323         TIFF encapsulation strategy, then tell our caller about them; otherwise,
2324         keep mum.
2325      */
2326         case TIFFTAG_JPEGTABLES            :
2327           if (sp->jpegtables_length) /* we have "new"-style JPEG tables */
2328             {
2329               *va_arg(ap,uint32 *) = sp->jpegtables_length;
2330               *va_arg(ap,char **) = sp->jpegtables;
2331               return 1;
2332             };
2333
2334      /* This pseudo tag indicates whether our caller is expected to do YCbCr <->
2335         RGB color-space conversion (JPEGCOLORMODE_RAW <=> 0) or whether we must
2336         ask the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1).
2337      */
2338         case TIFFTAG_JPEGCOLORMODE         :
2339           *va_arg(ap,uint32 *) = sp->jpegcolormode;
2340           return 1;
2341
2342      /* The following tags are defined by the TIFF Version 6.0 specification
2343         and are obsolete.  If our caller asks for information about them, do not
2344         return anything, even if we parsed them in an old-format "source" image.
2345      */
2346         case TIFFTAG_JPEGPROC              :
2347                 *va_arg(ap, uint16*)=sp->jpegproc;
2348                 return(1);
2349                 break;
2350         case TIFFTAG_JPEGIFOFFSET          :
2351                 *va_arg(ap, uint32*)=sp->jpegifoffset;
2352                 return(1);
2353                 break;
2354         case TIFFTAG_JPEGIFBYTECOUNT       :
2355                 *va_arg(ap, uint32*)=sp->jpegifbytecount;
2356                 return(1);
2357                 break;
2358         case TIFFTAG_JPEGRESTARTINTERVAL   :
2359                 *va_arg(ap, uint32*)=sp->jpegrestartinterval;
2360                 return(1);
2361                 break;
2362         case TIFFTAG_JPEGLOSSLESSPREDICTORS:
2363                 *va_arg(ap, uint32*)=sp->jpeglosslesspredictors_length;
2364                 *va_arg(ap, void**)=sp->jpeglosslesspredictors;
2365                 return(1);
2366                 break;
2367         case TIFFTAG_JPEGPOINTTRANSFORM    :
2368                 *va_arg(ap, uint32*)=sp->jpegpointtransform_length;
2369                 *va_arg(ap, void**)=sp->jpegpointtransform;
2370                 return(1);
2371                 break;
2372         case TIFFTAG_JPEGQTABLES           :
2373                 *va_arg(ap, uint32*)=sp->jpegqtables_length;
2374                 *va_arg(ap, void**)=sp->jpegqtables;
2375                 return(1);
2376                 break;
2377         case TIFFTAG_JPEGDCTABLES          :
2378                 *va_arg(ap, uint32*)=sp->jpegdctables_length;
2379                 *va_arg(ap, void**)=sp->jpegdctables;
2380                 return(1);
2381                 break;
2382         case TIFFTAG_JPEGACTABLES          : 
2383                 *va_arg(ap, uint32*)=sp->jpegactables_length;
2384                 *va_arg(ap, void**)=sp->jpegactables;
2385                 return(1);
2386                 break;
2387       };
2388     return (*sp->vgetparent)(tif,tag,ap);
2389   }
2390
2391 static void
2392 OJPEGPrintDir(register TIFF *tif,FILE *fd,long flags)
2393   { register OJPEGState *sp = OJState(tif);
2394
2395     if (   ( flags
2396            & (TIFFPRINT_JPEGQTABLES|TIFFPRINT_JPEGDCTABLES|TIFFPRINT_JPEGACTABLES)
2397            )
2398         && sp->jpegtables_length
2399        )
2400       fprintf(fd,"  JPEG Table Data: <present>, %lu bytes\n",
2401         sp->jpegtables_length);
2402   }
2403
2404 static uint32
2405 OJPEGDefaultStripSize(register TIFF *tif,register uint32 s)
2406   { register OJPEGState *sp = OJState(tif);
2407 #   define td (&tif->tif_dir)
2408
2409     if ((s = (*sp->defsparent)(tif,s)) < td->td_imagelength)
2410       { register tsize_t size = sp->cinfo.comm.is_decompressor
2411 #                             ifdef D_LOSSLESS_SUPPORTED
2412                               ? sp->cinfo.d.min_codec_data_unit
2413 #                             else
2414                               ? DCTSIZE
2415 #                             endif
2416 #                             ifdef C_LOSSLESS_SUPPORTED
2417                               : sp->cinfo.c.data_unit;
2418 #                             else
2419                               : DCTSIZE;
2420 #                             endif
2421
2422         size = TIFFroundup(size,16);
2423         s = TIFFroundup(s,td->td_ycbcrsubsampling[1]*size);
2424       };
2425     return s;
2426 #   undef td
2427   }
2428
2429 static void
2430 OJPEGDefaultTileSize(register TIFF *tif,register uint32 *tw,register uint32 *th)
2431   { register OJPEGState *sp = OJState(tif);
2432     register tsize_t size;
2433 #   define td (&tif->tif_dir)
2434
2435     size = sp->cinfo.comm.is_decompressor
2436 #        ifdef D_LOSSLESS_SUPPORTED
2437          ? sp->cinfo.d.min_codec_data_unit
2438 #        else
2439          ? DCTSIZE
2440 #        endif
2441 #        ifdef C_LOSSLESS_SUPPORTED
2442          : sp->cinfo.c.data_unit;
2443 #        else
2444          : DCTSIZE;
2445 #        endif
2446     size = TIFFroundup(size,16);
2447     (*sp->deftparent)(tif,tw,th);
2448     *tw = TIFFroundup(*tw,td->td_ycbcrsubsampling[0]*size);
2449     *th = TIFFroundup(*th,td->td_ycbcrsubsampling[1]*size);
2450 #   undef td
2451   }
2452
2453 static void
2454 OJPEGCleanUp(register TIFF *tif)
2455   { register OJPEGState *sp;
2456
2457     if ( (sp = OJState(tif)) )
2458       {
2459         CALLVJPEG(sp,jpeg_destroy(&sp->cinfo.comm)); /* Free JPEG Lib. vars. */
2460         if (sp->jpegtables) {_TIFFfree(sp->jpegtables);sp->jpegtables=0;}
2461         if (sp->jpeglosslesspredictors) {
2462                 _TIFFfree(sp->jpeglosslesspredictors);
2463                 sp->jpeglosslesspredictors = 0;
2464         }
2465         if (sp->jpegpointtransform) {
2466                 _TIFFfree(sp->jpegpointtransform);
2467                 sp->jpegpointtransform=0;
2468         }
2469         if (sp->jpegqtables) {_TIFFfree(sp->jpegqtables);sp->jpegqtables=0;}
2470         if (sp->jpegactables) {_TIFFfree(sp->jpegactables);sp->jpegactables=0;}
2471         if (sp->jpegdctables) {_TIFFfree(sp->jpegdctables);sp->jpegdctables=0;}
2472      /* If the image file isn't "memory mapped" and we read it all into a
2473         single, large memory buffer, free the buffer now.
2474      */
2475         if (!isMapped(tif) && tif->tif_base) /* free whole-file buffer */
2476           {
2477             _TIFFfree(tif->tif_base);
2478             tif->tif_base = 0;
2479             tif->tif_size = 0;
2480           };
2481         _TIFFfree(sp); /* Release local variables */
2482         tif->tif_data = 0;
2483       }
2484   }
2485
2486 int
2487 TIFFInitOJPEG(register TIFF *tif,int scheme)
2488   { register OJPEGState *sp;
2489 #   define td (&tif->tif_dir)
2490 #   ifndef never
2491
2492  /* This module supports a decompression-only CODEC, which is intended strictly
2493     for viewing old image files using the obsolete JPEG-in-TIFF encapsulation
2494     specified by the TIFF Version 6.0 specification.  It does not, and never
2495     should, support compression for new images.  If a client application asks us
2496     to, refuse and complain loudly!
2497  */
2498     if (tif->tif_mode != O_RDONLY) return _notSupported(tif);
2499 #   endif /* never */
2500     if (!isMapped(tif))
2501       {
2502
2503      /* BEWARE OF KLUDGE:  If our host operating-system doesn't let an image
2504                            file be "memory mapped", then we want to read the
2505         entire file into a single (possibly large) memory buffer as if it had
2506         been "memory mapped".  Although this is likely to waste space, because
2507         analysis of the file's content might cause parts of it to be read into
2508         smaller buffers duplicatively, it appears to be the lesser of several
2509         evils.  Very old JPEG-in-TIFF encapsulations aren't guaranteed to be
2510         JFIF bit streams, or to have a TIFF "JPEGTables" record or much other
2511         "metadata" to help us locate the decoding tables and entropy-coded data,
2512         so we're likely do a lot of random-access grokking around, and we must
2513         ultimately tell the JPEG Library to sequentially scan much of the file
2514         anyway.  This is all likely to be easier if we use "brute force" to
2515         read the entire file, once, and don't use incremental disc I/O.  If our
2516         client application tries to process a file so big that we can't buffer
2517         it entirely, then tough shit: we'll give up and exit!
2518      */
2519         if (!(tif->tif_base = _TIFFmalloc(tif->tif_size=TIFFGetFileSize(tif))))
2520           {
2521             TIFFError(tif->tif_name,"Cannot allocate file buffer");
2522             return 0;
2523           };
2524         if (!SeekOK(tif,0) || !ReadOK(tif,tif->tif_base,tif->tif_size))
2525           {
2526             TIFFError(tif->tif_name,"Cannot read file");
2527             return 0;
2528           }
2529       };
2530
2531  /* Allocate storage for this module's per-file variables. */
2532
2533     if (!(tif->tif_data = (tidata_t)_TIFFmalloc(sizeof *sp)))
2534       {
2535         TIFFError("TIFFInitOJPEG","No space for JPEG state block");
2536         return 0;
2537       };
2538     (sp = OJState(tif))->tif = tif; /* Initialize reverse pointer */
2539     sp->cinfo.d.err = jpeg_std_error(&sp->err); /* Initialize error handling */
2540     sp->err.error_exit = TIFFojpeg_error_exit;
2541     sp->err.output_message = TIFFojpeg_output_message;
2542     if (!CALLVJPEG(sp,jpeg_create_decompress(&sp->cinfo.d))) return 0;
2543
2544  /* Install CODEC-specific tag information and override default TIFF Library
2545     "method" subroutines with our own, CODEC-specific methods.  Like all good
2546     members of an object-class, we save some of these subroutine pointers for
2547     "fall back" in case our own methods fail.
2548  */
2549     _TIFFMergeFieldInfo(tif,ojpegFieldInfo,
2550       sizeof ojpegFieldInfo/sizeof *ojpegFieldInfo);
2551     sp->defsparent = tif->tif_defstripsize;
2552     sp->deftparent = tif->tif_deftilesize;
2553     sp->vgetparent = tif->tif_tagmethods.vgetfield;
2554     sp->vsetparent = tif->tif_tagmethods.vsetfield;
2555     tif->tif_defstripsize = OJPEGDefaultStripSize;
2556     tif->tif_deftilesize = OJPEGDefaultTileSize;
2557     tif->tif_tagmethods.vgetfield = OJPEGVGetField;
2558     tif->tif_tagmethods.vsetfield = OJPEGVSetField;
2559     tif->tif_tagmethods.printdir = OJPEGPrintDir;
2560 #   ifdef never
2561     tif->tif_setupencode = OJPEGSetupEncode;
2562     tif->tif_preencode = OJPEGPreEncode;
2563     tif->tif_postencode = OJPEGPostEncode;
2564 #   else /* well, hardly ever */
2565     tif->tif_setupencode = tif->tif_postencode = _notSupported;
2566     tif->tif_preencode = (TIFFPreMethod)_notSupported;
2567 #   endif /* never */
2568     tif->tif_setupdecode = OJPEGSetupDecode;
2569     tif->tif_predecode = OJPEGPreDecode;
2570     tif->tif_postdecode = OJPEGPostDecode;
2571     tif->tif_cleanup = OJPEGCleanUp;
2572
2573  /* If the image file doesn't have "JPEGInterchangeFormat[Length]" TIFF records
2574     to guide us, we have few clues about where its encapsulated JPEG bit stream
2575     is located, so establish intelligent defaults:  If the Image File Directory
2576     doesn't immediately follow the TIFF header, assume that the JPEG data lies
2577     in between; otherwise, assume that it follows the Image File Directory.
2578  */
2579     if (tif->tif_header.tiff_diroff > sizeof tif->tif_header)
2580       {
2581         sp->src.next_input_byte = tif->tif_base + sizeof tif->tif_header;
2582         sp->src.bytes_in_buffer = tif->tif_header.tiff_diroff
2583                                 - sizeof tif->tif_header;
2584       }
2585     else /* this case is ugly! */
2586       { uint32 maxoffset = tif->tif_size;
2587         uint16 dircount;
2588
2589      /* Calculate the offset to the next Image File Directory, if there is one,
2590         or to the end of the file, if not.  Then arrange to read the file from
2591         the end of the Image File Directory to that offset.
2592      */
2593         if (tif->tif_nextdiroff) maxoffset = tif->tif_nextdiroff; /* Not EOF */
2594         _TIFFmemcpy(&dircount,(const tdata_t)
2595           (sp->src.next_input_byte = tif->tif_base+tif->tif_header.tiff_diroff),
2596           sizeof dircount);
2597         if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount);
2598         sp->src.next_input_byte += dircount*sizeof(TIFFDirEntry)
2599                                 + sizeof maxoffset + sizeof dircount;
2600         sp->src.bytes_in_buffer = tif->tif_base - sp->src.next_input_byte
2601                                 + maxoffset;
2602       };
2603
2604  /* IJG JPEG Library Version 6B can be configured for either 8- or 12-bit sample
2605     precision, but we assume that "old JPEG" TIFF clients only need 8 bits.
2606  */
2607     sp->cinfo.d.data_precision = 8;
2608 #   ifdef C_LOSSLESS_SUPPORTED
2609
2610  /* If the "JPEGProc" TIFF tag is missing from the Image File Dictionary, the
2611     JPEG Library will use its (lossy) baseline sequential process by default.
2612  */
2613     sp->cinfo.d.data_unit = DCTSIZE;
2614 #   endif /* C_LOSSLESS_SUPPORTED */
2615
2616  /* Initialize other CODEC-specific variables requiring default values. */
2617
2618     tif->tif_flags |= TIFF_NOBITREV; /* No bit-reversal within data bytes */
2619     sp->h_sampling = sp->v_sampling = 1; /* No subsampling by default */
2620     sp->is_WANG = 0; /* Assume not a MS Windows Wang Imaging file by default */
2621     sp->jpegtables = 0; /* No "new"-style JPEG tables synthesized yet */
2622     sp->jpegtables_length = 0;
2623     sp->jpegquality = 75; /* Default IJG quality */
2624     sp->jpegcolormode = JPEGCOLORMODE_RAW;
2625     sp->jpegtablesmode = 0; /* No tables found yet */
2626     sp->jpeglosslesspredictors=0;
2627     sp->jpeglosslesspredictors_length=0;
2628     sp->jpegpointtransform=0;
2629     sp->jpegpointtransform_length=0;
2630     sp->jpegqtables=0;
2631     sp->jpegqtables_length=0;
2632     sp->jpegdctables=0;
2633     sp->jpegdctables_length=0;
2634     sp->jpegactables=0;
2635     sp->jpegactables_length=0;
2636     return 1;
2637 #   undef td
2638   }
2639 #endif /* OJPEG_SUPPORT */
2640
2641 /* vim: set ts=8 sts=8 sw=8 noet: */