~ubuntu-branches/ubuntu/raring/wxwidgets2.8/raring

« back to all changes in this revision

Viewing changes to src/tiff/tif_ojpeg.c

  • Committer: Package Import Robot
  • Author(s): Stéphane Graber
  • Date: 2012-01-07 13:59:25 UTC
  • mfrom: (1.1.9) (5.1.10 sid)
  • Revision ID: package-import@ubuntu.com-20120107135925-2601miy9ullcon9j
Tags: 2.8.12.1-6ubuntu1
* Resync from Debian, changes that were kept:
  - debian/rules: re-enable mediactrl. This allows libwx_gtk2u_media-2.8 to be
    built, as this is required by some applications (LP: #632984)
  - debian/control: Build-dep on libxt-dev for mediactrl.
  - Patches
    + fix-bashism-in-example
* Add conflict on python-wxgtk2.8 (<< 2.8.12.1-6ubuntu1~) to python-wxversion
  to guarantee upgrade ordering when moving from pycentral to dh_python2.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#include "tiffiop.h"
2
 
#ifdef OJPEG_SUPPORT
3
 
 
4
 
/* JPEG Compression support, as per the original TIFF 6.0 specification.
5
 
 
6
 
   WARNING: KLUDGE ALERT!  The type of JPEG encapsulation defined by the TIFF
7
 
                           Version 6.0 specification is now totally obsolete and
8
 
   deprecated for new applications and images.  This file is an unsupported hack
9
 
   that was created solely in order to read (but NOT write!) a few old,
10
 
   unconverted images still present on some users' computer systems.  The code
11
 
   isn't pretty or robust, and it won't read every "old format" JPEG-in-TIFF
12
 
   file (see Samuel Leffler's draft "TIFF Technical Note No. 2" for a long and
13
 
   incomplete list of known problems), but it seems to work well enough in the
14
 
   few cases of practical interest to the author; so, "caveat emptor"!  This
15
 
   file should NEVER be enhanced to write new images using anything other than
16
 
   the latest approved JPEG-in-TIFF encapsulation method, implemented by the
17
 
   "tif_jpeg.c" file elsewhere in this library.
18
 
 
19
 
   This file interfaces with Release 6B of the JPEG Library written by theu
20
 
   Independent JPEG Group, which you can find on the Internet at:
21
 
   ftp://ftp.uu.net:/graphics/jpeg/.
22
 
 
23
 
   The "C" Preprocessor macros, "[CD]_LOSSLESS_SUPPORTED", are defined by your
24
 
   JPEG Library Version 6B only if you have applied a (massive!) patch by Ken
25
 
   Murchison of Oceana Matrix Ltd. <ken@oceana.com> to support lossless Huffman
26
 
   encoding (TIFF "JPEGProc" tag value = 14).  This patch can be found on the
27
 
   Internet at: ftp://ftp.oceana.com/pub/ljpeg-6b.tar.gz.
28
 
 
29
 
   Some old files produced by the Wang Imaging application for Microsoft Windows
30
 
   apparently can be decoded only with a special patch to the JPEG Library,
31
 
   which defines a subroutine named "jpeg_reset_huff_decode()" in its "jdhuff.c"
32
 
   module (the "jdshuff.c" module, if Ken Murchison's patch has been applied).
33
 
   Unfortunately the patch differs slightly in each case, and some TIFF Library
34
 
   have reported problems finding the code, so both versions appear below; you
35
 
   should carefully extract and apply only the version that applies to your JPEG
36
 
   Library!
37
 
 
38
 
   Contributed by Scott Marovich <marovich@hpl.hp.com> with considerable help
39
 
   from Charles Auer <Bumble731@msn.com> to unravel the mysteries of image files
40
 
   created by the Wang Imaging application for Microsoft Windows.
41
 
*/
42
 
#if 0  /* Patch for JPEG Library WITHOUT lossless Huffman coding */
43
 
*** jdhuff.c.orig       Mon Oct 20 17:51:10 1997
44
 
--- jdhuff.c    Sun Nov 11 17:33:58 2001
45
 
***************
46
 
*** 648,651 ****
47
 
--- 648,683 ----
48
 
    for (i = 0; i < NUM_HUFF_TBLS; i++) {
49
 
      entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
50
 
    }
51
 
  }
52
 
53
 
+ /*
54
 
+  * BEWARE OF KLUDGE:  This subroutine is a hack for decoding illegal JPEG-in-
55
 
+  *                    TIFF encapsulations produced by Microsoft's Wang Imaging
56
 
+  * for Windows application with the public-domain TIFF Library.  Based upon an
57
 
+  * examination of selected output files, this program apparently divides a JPEG
58
 
+  * bit-stream into consecutive horizontal TIFF "strips", such that the JPEG
59
 
+  * encoder's/decoder's DC coefficients for each image component are reset before
60
 
+  * each "strip".  Moreover, a "strip" is not necessarily encoded in a multiple
61
 
+  * of 8 bits, so one must sometimes discard 1-7 bits at the end of each "strip"
62
 
+  * for alignment to the next input-Byte storage boundary.  IJG JPEG Library
63
 
+  * decoder state is not normally exposed to client applications, so this sub-
64
 
+  * routine provides the TIFF Library with a "hook" to make these corrections.
65
 
+  * It should be called after "jpeg_start_decompress()" and before
66
 
+  * "jpeg_finish_decompress()", just before decoding each "strip" using
67
 
+  * "jpeg_read_raw_data()" or "jpeg_read_scanlines()".
68
 
+  *
69
 
+  * This kludge is not sanctioned or supported by the Independent JPEG Group, and
70
 
+  * future changes to the IJG JPEG Library might invalidate it.  Do not send bug
71
 
+  * reports about this code to IJG developers.  Instead, contact the author for
72
 
+  * advice: Scott B. Marovich <marovich@hpl.hp.com>, Hewlett-Packard Labs, 6/01.
73
 
+  */
74
 
+ GLOBAL(void)
75
 
+ jpeg_reset_huff_decode (register j_decompress_ptr cinfo)
76
 
+ { register huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
77
 
+   register int ci = 0;
78
 
79
 
+   /* Discard encoded input bits, up to the next Byte boundary */
80
 
+   entropy->bitstate.bits_left &= ~7;
81
 
+   /* Re-initialize DC predictions to 0 */
82
 
+   do entropy->saved.last_dc_val[ci] = 0; while (++ci < cinfo->comps_in_scan);
83
 
+ }
84
 
#endif /* Patch for JPEG Library WITHOUT lossless Huffman coding */
85
 
#if 0  /* Patch for JPEG Library WITH lossless Huffman coding */
86
 
*** jdshuff.c.orig      Mon Mar 11 16:44:54 2002
87
 
--- jdshuff.c   Mon Mar 11 16:44:54 2002
88
 
***************
89
 
*** 357,360 ****
90
 
--- 357,393 ----
91
 
    for (i = 0; i < NUM_HUFF_TBLS; i++) {
92
 
      entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
93
 
    }
94
 
  }
95
 
96
 
+ /*
97
 
+  * BEWARE OF KLUDGE:  This subroutine is a hack for decoding illegal JPEG-in-
98
 
+  *                    TIFF encapsulations produced by Microsoft's Wang Imaging
99
 
+  * for Windows application with the public-domain TIFF Library.  Based upon an
100
 
+  * examination of selected output files, this program apparently divides a JPEG
101
 
+  * bit-stream into consecutive horizontal TIFF "strips", such that the JPEG
102
 
+  * encoder's/decoder's DC coefficients for each image component are reset before
103
 
+  * each "strip".  Moreover, a "strip" is not necessarily encoded in a multiple
104
 
+  * of 8 bits, so one must sometimes discard 1-7 bits at the end of each "strip"
105
 
+  * for alignment to the next input-Byte storage boundary.  IJG JPEG Library
106
 
+  * decoder state is not normally exposed to client applications, so this sub-
107
 
+  * routine provides the TIFF Library with a "hook" to make these corrections.
108
 
+  * It should be called after "jpeg_start_decompress()" and before
109
 
+  * "jpeg_finish_decompress()", just before decoding each "strip" using
110
 
+  * "jpeg_read_raw_data()" or "jpeg_read_scanlines()".
111
 
+  *
112
 
+  * This kludge is not sanctioned or supported by the Independent JPEG Group, and
113
 
+  * future changes to the IJG JPEG Library might invalidate it.  Do not send bug
114
 
+  * reports about this code to IJG developers.  Instead, contact the author for
115
 
+  * advice: Scott B. Marovich <marovich@hpl.hp.com>, Hewlett-Packard Labs, 6/01.
116
 
+  */
117
 
+ GLOBAL(void)
118
 
+ jpeg_reset_huff_decode (register j_decompress_ptr cinfo)
119
 
+ { register shuff_entropy_ptr entropy = (shuff_entropy_ptr)
120
 
+                                        ((j_lossy_d_ptr)cinfo->codec)->entropy_private;
121
 
+   register int ci = 0;
122
 
123
 
+   /* Discard encoded input bits, up to the next Byte boundary */
124
 
+   entropy->bitstate.bits_left &= ~7;
125
 
+   /* Re-initialize DC predictions to 0 */
126
 
+   do entropy->saved.last_dc_val[ci] = 0; while (++ci < cinfo->comps_in_scan);
127
 
+ }
128
 
#endif /* Patch for JPEG Library WITH lossless Huffman coding */
129
 
#include <setjmp.h>
130
 
#include <stdio.h>
131
 
#ifdef FAR
132
 
#undef FAR /* Undefine FAR to avoid conflict with JPEG definition */
133
 
#endif
134
 
#define JPEG_INTERNALS /* Include "jpegint.h" for "DSTATE_*" symbols */
135
 
#define JPEG_CJPEG_DJPEG /* Include all Version 6B+ "jconfig.h" options */
136
 
#undef INLINE
137
 
#include "jpeglib.h"
138
 
#undef JPEG_CJPEG_DJPEG
139
 
#undef JPEG_INTERNALS
140
 
 
141
 
/* Hack for files produced by Wang Imaging application on Microsoft Windows */
142
 
extern void jpeg_reset_huff_decode(j_decompress_ptr);
143
 
 
144
 
/* On some machines, it may be worthwhile to use "_setjmp()" or "sigsetjmp()"
145
 
   instead of "setjmp()".  These macros make it easier:
146
 
*/
147
 
#define SETJMP(jbuf)setjmp(jbuf)
148
 
#define LONGJMP(jbuf,code)longjmp(jbuf,code)
149
 
#define JMP_BUF jmp_buf
150
 
 
151
 
#define TIFFTAG_WANG_PAGECONTROL 32934
152
 
 
153
 
/* Bit-vector offsets for keeping track of TIFF records that we've parsed. */
154
 
 
155
 
#define FIELD_JPEGPROC FIELD_CODEC
156
 
#define FIELD_JPEGIFOFFSET (FIELD_CODEC+1)
157
 
#define FIELD_JPEGIFBYTECOUNT (FIELD_CODEC+2)
158
 
#define FIELD_JPEGRESTARTINTERVAL (FIELD_CODEC+3)
159
 
#define FIELD_JPEGTABLES (FIELD_CODEC+4) /* New, post-6.0 JPEG-in-TIFF tag! */
160
 
#define FIELD_JPEGLOSSLESSPREDICTORS (FIELD_CODEC+5)
161
 
#define FIELD_JPEGPOINTTRANSFORM (FIELD_CODEC+6)
162
 
#define FIELD_JPEGQTABLES (FIELD_CODEC+7)
163
 
#define FIELD_JPEGDCTABLES (FIELD_CODEC+8)
164
 
#define FIELD_JPEGACTABLES (FIELD_CODEC+9)
165
 
#define FIELD_WANG_PAGECONTROL (FIELD_CODEC+10)
166
 
#define FIELD_JPEGCOLORMODE (FIELD_CODEC+11)
167
 
 
168
 
typedef struct jpeg_destination_mgr jpeg_destination_mgr;
169
 
typedef struct jpeg_source_mgr jpeg_source_mgr;
170
 
typedef struct jpeg_error_mgr jpeg_error_mgr;
171
 
 
172
 
/* State variable for each open TIFF file that uses "libjpeg" for JPEG
173
 
   decompression.  (Note:  This file should NEVER perform JPEG compression
174
 
   except in the manner implemented by the "tif_jpeg.c" file, elsewhere in this
175
 
   library; see comments above.)  JPEG Library internal state is recorded in a
176
 
   "jpeg_{de}compress_struct", while a "jpeg_common_struct" records a few items
177
 
   common to both compression and expansion.  The "cinfo" field containing JPEG
178
 
   Library state MUST be the 1st member of our own state variable, so that we
179
 
   can safely "cast" pointers back and forth.
180
 
*/
181
 
typedef struct             /* This module's private, per-image state variable */
182
 
  {
183
 
    union         /* JPEG Library state variable; this MUST be our 1st field! */
184
 
      {
185
 
        struct jpeg_compress_struct c;
186
 
        struct jpeg_decompress_struct d;
187
 
        struct jpeg_common_struct comm;
188
 
      } cinfo;
189
 
    jpeg_error_mgr err;                         /* JPEG Library error manager */
190
 
    JMP_BUF exit_jmpbuf;             /* ...for catching JPEG Library failures */
191
 
#   ifdef never
192
 
 
193
 
 /* (The following two fields could be a "union", but they're small enough that
194
 
    it's not worth the effort.)
195
 
 */
196
 
    jpeg_destination_mgr dest;             /* Destination for compressed data */
197
 
#   endif
198
 
    jpeg_source_mgr src;                           /* Source of expanded data */
199
 
    JSAMPARRAY ds_buffer[MAX_COMPONENTS]; /* ->Temporary downsampling buffers */
200
 
    TIFF *tif;                        /* Reverse pointer, needed by some code */
201
 
    TIFFVGetMethod vgetparent;                    /* "Super class" methods... */
202
 
    TIFFVSetMethod vsetparent;
203
 
    TIFFStripMethod defsparent;
204
 
    TIFFTileMethod deftparent;
205
 
    void *jpegtables;           /* ->"New" JPEG tables, if we synthesized any */
206
 
    uint32 is_WANG,    /* <=> Wang Imaging for Microsoft Windows output file? */
207
 
           jpegtables_length;   /* Length of "new" JPEG tables, if they exist */
208
 
    tsize_t bytesperline;          /* No. of decompressed Bytes per scan line */
209
 
    int jpegquality,                             /* Compression quality level */
210
 
        jpegtablesmode,                          /* What to put in JPEGTables */
211
 
        samplesperclump,
212
 
        scancount;                           /* No. of scan lines accumulated */
213
 
    J_COLOR_SPACE photometric;          /* IJG JPEG Library's photometry code */
214
 
    u_char h_sampling,                          /* Luminance sampling factors */
215
 
           v_sampling,
216
 
           jpegcolormode;           /* Who performs RGB <-> YCbCr conversion? */
217
 
                        /* JPEGCOLORMODE_RAW <=> TIFF Library or its client */
218
 
                        /* JPEGCOLORMODE_RGB <=> JPEG Library               */
219
 
    /* These fields are added to support TIFFGetField */
220
 
    uint16 jpegproc;
221
 
    uint32 jpegifoffset;
222
 
    uint32 jpegifbytecount;
223
 
    uint32 jpegrestartinterval;
224
 
    void* jpeglosslesspredictors;
225
 
    uint16 jpeglosslesspredictors_length;
226
 
    void* jpegpointtransform;
227
 
    uint32 jpegpointtransform_length;
228
 
    void* jpegqtables;
229
 
    uint32 jpegqtables_length;
230
 
    void* jpegdctables;
231
 
    uint32 jpegdctables_length;
232
 
    void* jpegactables;
233
 
    uint32 jpegactables_length;
234
 
 
235
 
  } OJPEGState;
236
 
#define OJState(tif)((OJPEGState*)(tif)->tif_data)
237
 
 
238
 
static const TIFFFieldInfo ojpegFieldInfo[]=/* JPEG-specific TIFF-record tags */
239
 
  {
240
 
 
241
 
 /* This is the current JPEG-in-TIFF metadata-encapsulation tag, and its
242
 
    treatment in this file is idiosyncratic.  It should never appear in a
243
 
    "source" image conforming to the TIFF Version 6.0 specification, so we
244
 
    arrange to report an error if it appears.  But in order to support possible
245
 
    future conversion of "old" JPEG-in-TIFF encapsulations to "new" ones, we
246
 
    might wish to synthesize an equivalent value to be returned by the TIFF
247
 
    Library's "getfield" method.  So, this table tells the TIFF Library to pass
248
 
    these records to us in order to filter them below.
249
 
 */
250
 
    {
251
 
      TIFFTAG_JPEGTABLES            ,TIFF_VARIABLE,TIFF_VARIABLE,
252
 
      TIFF_UNDEFINED,FIELD_JPEGTABLES            ,FALSE,TRUE ,"JPEGTables"
253
 
    },
254
 
 
255
 
 /* These tags are defined by the TIFF Version 6.0 specification and are now
256
 
    obsolete.  This module reads them from an old "source" image, but it never
257
 
    writes them to a new "destination" image.
258
 
 */
259
 
    {
260
 
      TIFFTAG_JPEGPROC              ,1            ,1            ,
261
 
      TIFF_SHORT    ,FIELD_JPEGPROC              ,FALSE,FALSE,"JPEGProc"
262
 
    },
263
 
    {
264
 
      TIFFTAG_JPEGIFOFFSET          ,1            ,1            ,
265
 
      TIFF_LONG     ,FIELD_JPEGIFOFFSET          ,FALSE,FALSE,"JPEGInterchangeFormat"
266
 
    },
267
 
    {
268
 
      TIFFTAG_JPEGIFBYTECOUNT       ,1            ,1            ,
269
 
      TIFF_LONG     ,FIELD_JPEGIFBYTECOUNT       ,FALSE,FALSE,"JPEGInterchangeFormatLength"
270
 
    },
271
 
    {
272
 
      TIFFTAG_JPEGRESTARTINTERVAL   ,1            ,1            ,
273
 
      TIFF_SHORT    ,FIELD_JPEGRESTARTINTERVAL   ,FALSE,FALSE,"JPEGRestartInterval"
274
 
    },
275
 
    {
276
 
      TIFFTAG_JPEGLOSSLESSPREDICTORS,TIFF_VARIABLE,TIFF_VARIABLE,
277
 
      TIFF_SHORT    ,FIELD_JPEGLOSSLESSPREDICTORS,FALSE,TRUE ,"JPEGLosslessPredictors"
278
 
    },
279
 
    {
280
 
      TIFFTAG_JPEGPOINTTRANSFORM    ,TIFF_VARIABLE,TIFF_VARIABLE,
281
 
      TIFF_SHORT    ,FIELD_JPEGPOINTTRANSFORM    ,FALSE,TRUE ,"JPEGPointTransforms"
282
 
    },
283
 
    {
284
 
      TIFFTAG_JPEGQTABLES           ,TIFF_VARIABLE,TIFF_VARIABLE,
285
 
      TIFF_LONG     ,FIELD_JPEGQTABLES           ,FALSE,TRUE ,"JPEGQTables"
286
 
    },
287
 
    {
288
 
      TIFFTAG_JPEGDCTABLES          ,TIFF_VARIABLE,TIFF_VARIABLE,
289
 
      TIFF_LONG     ,FIELD_JPEGDCTABLES          ,FALSE,TRUE ,"JPEGDCTables"
290
 
    },
291
 
    {
292
 
      TIFFTAG_JPEGACTABLES          ,TIFF_VARIABLE,TIFF_VARIABLE,
293
 
      TIFF_LONG     ,FIELD_JPEGACTABLES          ,FALSE,TRUE ,"JPEGACTables"
294
 
    },
295
 
    {
296
 
      TIFFTAG_WANG_PAGECONTROL      ,TIFF_VARIABLE,1            ,
297
 
      TIFF_LONG     ,FIELD_WANG_PAGECONTROL      ,FALSE,FALSE,"WANG PageControl"
298
 
    },
299
 
 
300
 
 /* This is a pseudo tag intended for internal use only by the TIFF Library and
301
 
    its clients, which should never appear in an input/output image file.  It
302
 
    specifies whether the TIFF Library (or its client) should do YCbCr <-> RGB
303
 
    color-space conversion (JPEGCOLORMODE_RAW <=> 0) or whether we should ask
304
 
    the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1).
305
 
 */
306
 
    {
307
 
      TIFFTAG_JPEGCOLORMODE         ,0            ,0            ,
308
 
      TIFF_ANY      ,FIELD_PSEUDO                ,FALSE,FALSE,"JPEGColorMode"
309
 
    }
310
 
  };
311
 
static const char JPEGLib_name[]={"JPEG Library"},
312
 
                  bad_bps[]={"%u BitsPerSample not allowed for JPEG"},
313
 
                  bad_photometry[]={"PhotometricInterpretation %u not allowed for JPEG"},
314
 
                  bad_subsampling[]={"invalid YCbCr subsampling factor(s)"},
315
 
#                 ifdef never
316
 
                  no_write_frac[]={"fractional scan line discarded"},
317
 
#                 endif
318
 
                  no_read_frac[]={"fractional scan line not read"},
319
 
                  no_jtable_space[]={"No space for JPEGTables"};
320
 
 
321
 
/* The following diagnostic subroutines interface with and replace default
322
 
   subroutines in the JPEG Library.  Our basic strategy is to use "setjmp()"/
323
 
   "longjmp()" in order to return control to the TIFF Library when the JPEG
324
 
   library detects an error, and to use TIFF Library subroutines for displaying
325
 
   diagnostic messages to a client application.
326
 
*/
327
 
static void
328
 
TIFFojpeg_error_exit(register j_common_ptr cinfo)
329
 
  { char buffer[JMSG_LENGTH_MAX];
330
 
 
331
 
    (*cinfo->err->format_message)(cinfo,buffer);
332
 
    TIFFError(JPEGLib_name,buffer); /* Display error message */
333
 
    jpeg_abort(cinfo); /* Clean up JPEG Library state */
334
 
    LONGJMP(((OJPEGState *)cinfo)->exit_jmpbuf,1); /* Return to TIFF client */
335
 
  }
336
 
 
337
 
static void
338
 
TIFFojpeg_output_message(register j_common_ptr cinfo)
339
 
  { char buffer[JMSG_LENGTH_MAX];
340
 
 
341
 
 /* This subroutine is invoked only for warning messages, since the JPEG
342
 
    Library's "error_exit" method does its own thing and "trace_level" is never
343
 
    set > 0.
344
 
 */
345
 
    (*cinfo->err->format_message)(cinfo,buffer);
346
 
    TIFFWarning(JPEGLib_name,buffer);
347
 
  }
348
 
 
349
 
/* The following subroutines, which also interface with the JPEG Library, exist
350
 
   mainly in limit the side effects of "setjmp()" and convert JPEG normal/error
351
 
   conditions into TIFF Library return codes.
352
 
*/
353
 
#define CALLJPEG(sp,fail,op)(SETJMP((sp)->exit_jmpbuf)?(fail):(op))
354
 
#define CALLVJPEG(sp,op)CALLJPEG(sp,0,((op),1))
355
 
#ifdef never
356
 
 
357
 
static int
358
 
TIFFojpeg_create_compress(register OJPEGState *sp)
359
 
  {
360
 
    sp->cinfo.c.err = jpeg_std_error(&sp->err); /* Initialize error handling */
361
 
    sp->err.error_exit = TIFFojpeg_error_exit;
362
 
    sp->err.output_message = TIFFojpeg_output_message;
363
 
    return CALLVJPEG(sp,jpeg_create_compress(&sp->cinfo.c));
364
 
  }
365
 
 
366
 
/* The following subroutines comprise a JPEG Library "destination" data manager
367
 
   by directing compressed data from the JPEG Library to a TIFF Library output
368
 
   buffer.
369
 
*/
370
 
static void
371
 
std_init_destination(register j_compress_ptr cinfo){} /* "Dummy" stub */
372
 
 
373
 
static boolean
374
 
std_empty_output_buffer(register j_compress_ptr cinfo)
375
 
  {
376
 
#   define sp ((OJPEGState *)cinfo)
377
 
    register TIFF *tif = sp->tif;
378
 
 
379
 
    tif->tif_rawcc = tif->tif_rawdatasize; /* Entire buffer has been filled */
380
 
    TIFFFlushData1(tif);
381
 
    sp->dest.next_output_byte = (JOCTET *)tif->tif_rawdata;
382
 
    sp->dest.free_in_buffer = (size_t)tif->tif_rawdatasize;
383
 
    return TRUE;
384
 
#   undef sp
385
 
  }
386
 
 
387
 
static void
388
 
std_term_destination(register j_compress_ptr cinfo)
389
 
  {
390
 
#   define sp ((OJPEGState *)cinfo)
391
 
    register TIFF *tif = sp->tif;
392
 
 
393
 
 /* NB: The TIFF Library does the final buffer flush. */
394
 
    tif->tif_rawcp = (tidata_t)sp->dest.next_output_byte;
395
 
    tif->tif_rawcc = tif->tif_rawdatasize - (tsize_t)sp->dest.free_in_buffer;
396
 
#   undef sp
397
 
  }
398
 
 
399
 
/* Alternate destination manager to output JPEGTables field: */
400
 
 
401
 
static void
402
 
tables_init_destination(register j_compress_ptr cinfo)
403
 
  {
404
 
#   define sp ((OJPEGState *)cinfo)
405
 
 /* The "jpegtables_length" field is the allocated buffer size while building */
406
 
    sp->dest.next_output_byte = (JOCTET *)sp->jpegtables;
407
 
    sp->dest.free_in_buffer = (size_t)sp->jpegtables_length;
408
 
#   undef sp
409
 
  }
410
 
 
411
 
static boolean
412
 
tables_empty_output_buffer(register j_compress_ptr cinfo)
413
 
  { void *newbuf;
414
 
#   define sp ((OJPEGState *)cinfo)
415
 
 
416
 
 /* The entire buffer has been filled, so enlarge it by 1000 bytes. */
417
 
    if (!( newbuf = _TIFFrealloc( (tdata_t)sp->jpegtables
418
 
                                , (tsize_t)(sp->jpegtables_length + 1000)
419
 
                                )
420
 
         )
421
 
       ) ERREXIT1(cinfo,JERR_OUT_OF_MEMORY,100);
422
 
    sp->dest.next_output_byte = (JOCTET *)newbuf + sp->jpegtables_length;
423
 
    sp->dest.free_in_buffer = (size_t)1000;
424
 
    sp->jpegtables = newbuf;
425
 
    sp->jpegtables_length += 1000;
426
 
    return TRUE;
427
 
#   undef sp
428
 
  }
429
 
 
430
 
static void
431
 
tables_term_destination(register j_compress_ptr cinfo)
432
 
  {
433
 
#   define sp ((OJPEGState *)cinfo)
434
 
 /* Set tables length to no. of Bytes actually emitted. */
435
 
    sp->jpegtables_length -= sp->dest.free_in_buffer;
436
 
#   undef sp
437
 
  }
438
 
 
439
 
/*ARGSUSED*/ static int
440
 
TIFFojpeg_tables_dest(register OJPEGState *sp, TIFF *tif)
441
 
  {
442
 
 
443
 
 /* Allocate a working buffer for building tables.  The initial size is 1000
444
 
    Bytes, which is usually adequate.
445
 
 */
446
 
    if (sp->jpegtables) _TIFFfree(sp->jpegtables);
447
 
    if (!(sp->jpegtables = (void*)
448
 
                           _TIFFmalloc((tsize_t)(sp->jpegtables_length = 1000))
449
 
         )
450
 
       )
451
 
      {
452
 
        sp->jpegtables_length = 0;
453
 
        TIFFError("TIFFojpeg_tables_dest",no_jtable_space);
454
 
        return 0;
455
 
      };
456
 
    sp->cinfo.c.dest = &sp->dest;
457
 
    sp->dest.init_destination = tables_init_destination;
458
 
    sp->dest.empty_output_buffer = tables_empty_output_buffer;
459
 
    sp->dest.term_destination = tables_term_destination;
460
 
    return 1;
461
 
  }
462
 
#else /* well, hardly ever */
463
 
 
464
 
static int
465
 
_notSupported(register TIFF *tif)
466
 
  { const TIFFCodec *c = TIFFFindCODEC(tif->tif_dir.td_compression);
467
 
 
468
 
    TIFFError(tif->tif_name,"%s compression not supported",c->name);
469
 
    return 0;
470
 
  }
471
 
#endif /* never */
472
 
 
473
 
/* The following subroutines comprise a JPEG Library "source" data manager by
474
 
   by directing compressed data to the JPEG Library from a TIFF Library input
475
 
   buffer.
476
 
*/
477
 
static void
478
 
std_init_source(register j_decompress_ptr cinfo)
479
 
  {
480
 
#   define sp ((OJPEGState *)cinfo)
481
 
    register TIFF *tif = sp->tif;
482
 
 
483
 
    if (sp->src.bytes_in_buffer == 0)
484
 
      {
485
 
        sp->src.next_input_byte = (const JOCTET *)tif->tif_rawdata;
486
 
        sp->src.bytes_in_buffer = (size_t)tif->tif_rawcc;
487
 
      };
488
 
#   undef sp
489
 
  }
490
 
 
491
 
static boolean
492
 
std_fill_input_buffer(register j_decompress_ptr cinfo)
493
 
  { static const JOCTET dummy_EOI[2]={0xFF,JPEG_EOI};
494
 
#   define sp ((OJPEGState *)cinfo)
495
 
 
496
 
 /* Control should never get here, since an entire strip/tile is read into
497
 
    memory before the decompressor is called; thus, data should have been
498
 
    supplied by the "init_source" method.  ...But, sometimes things fail.
499
 
 */
500
 
    WARNMS(cinfo,JWRN_JPEG_EOF);
501
 
    sp->src.next_input_byte = dummy_EOI; /* Insert a fake EOI marker */
502
 
    sp->src.bytes_in_buffer = sizeof dummy_EOI;
503
 
    return TRUE;
504
 
#   undef sp
505
 
  }
506
 
 
507
 
static void
508
 
std_skip_input_data(register j_decompress_ptr cinfo, long num_bytes)
509
 
  {
510
 
#   define sp ((OJPEGState *)cinfo)
511
 
 
512
 
    if (num_bytes > 0)
513
 
    {
514
 
      if (num_bytes > (long)sp->src.bytes_in_buffer) /* oops: buffer overrun */
515
 
        (void)std_fill_input_buffer(cinfo);
516
 
      else
517
 
        {
518
 
          sp->src.next_input_byte += (size_t)num_bytes;
519
 
          sp->src.bytes_in_buffer -= (size_t)num_bytes;
520
 
        }
521
 
    }
522
 
#   undef sp
523
 
  }
524
 
 
525
 
/*ARGSUSED*/ static void
526
 
std_term_source(register j_decompress_ptr cinfo){} /* "Dummy" stub */
527
 
 
528
 
/* Allocate temporary I/O buffers for downsampled data, using values computed in
529
 
   "jpeg_start_{de}compress()".  We use the JPEG Library's allocator so that
530
 
   buffers will be released automatically when done with a strip/tile.  This is
531
 
   also a handy place to compute samplesperclump, bytesperline, etc.
532
 
*/
533
 
static int
534
 
alloc_downsampled_buffers(TIFF *tif,jpeg_component_info *comp_info,
535
 
                          int num_components)
536
 
  { register OJPEGState *sp = OJState(tif);
537
 
 
538
 
    sp->samplesperclump = 0;
539
 
    if (num_components > 0)
540
 
      { tsize_t size = sp->cinfo.comm.is_decompressor
541
 
#                    ifdef D_LOSSLESS_SUPPORTED
542
 
                     ? sp->cinfo.d.min_codec_data_unit
543
 
#                    else
544
 
                     ? DCTSIZE
545
 
#                    endif
546
 
#                    ifdef C_LOSSLESS_SUPPORTED
547
 
                     : sp->cinfo.c.data_unit;
548
 
#                    else
549
 
                     : DCTSIZE;
550
 
#                    endif
551
 
        int ci = 0;
552
 
        register jpeg_component_info *compptr = comp_info;
553
 
 
554
 
        do
555
 
          { JSAMPARRAY buf;
556
 
 
557
 
            sp->samplesperclump +=
558
 
              compptr->h_samp_factor * compptr->v_samp_factor;
559
 
#           if defined(C_LOSSLESS_SUPPORTED) || defined(D_LOSSLESS_SUPPORTED)
560
 
            if (!(buf = CALLJPEG(sp,0,(*sp->cinfo.comm.mem->alloc_sarray)(&sp->cinfo.comm,JPOOL_IMAGE,compptr->width_in_data_units*size,compptr->v_samp_factor*size))))
561
 
#           else
562
 
            if (!(buf = CALLJPEG(sp,0,(*sp->cinfo.comm.mem->alloc_sarray)(&sp->cinfo.comm,JPOOL_IMAGE,compptr->width_in_blocks*size,compptr->v_samp_factor*size))))
563
 
#           endif
564
 
              return 0;
565
 
            sp->ds_buffer[ci] = buf;
566
 
          }
567
 
        while (++compptr,++ci < num_components);
568
 
      };
569
 
    return 1;
570
 
  }
571
 
#ifdef never
572
 
 
573
 
/* JPEG Encoding begins here. */
574
 
 
575
 
/*ARGSUSED*/ static int
576
 
OJPEGEncode(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s)
577
 
  { tsize_t rows;                          /* No. of unprocessed rows in file */
578
 
    register OJPEGState *sp = OJState(tif);
579
 
 
580
 
 /* Encode a chunk of pixels, where returned data is NOT down-sampled (the
581
 
    standard case).  The data is expected to be written in scan-line multiples.
582
 
 */
583
 
    if (cc % sp->bytesperline) TIFFWarning(tif->tif_name,no_write_frac);
584
 
    if ( (cc /= bytesperline)      /* No. of complete rows in caller's buffer */
585
 
       > (rows = sp->cinfo.c.image_height - sp->cinfo.c.next_scanline)
586
 
       ) cc = rows;
587
 
    while (--cc >= 0)
588
 
      {
589
 
        if (   CALLJPEG(sp,-1,jpeg_write_scanlines(&sp->cinfo.c,(JSAMPARRAY)&buf,1))
590
 
            != 1
591
 
           ) return 0;
592
 
        ++tif->tif_row;
593
 
        buf += sp->bytesperline;
594
 
      };
595
 
    return 1;
596
 
  }
597
 
 
598
 
/*ARGSUSED*/ static int
599
 
OJPEGEncodeRaw(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s)
600
 
  { tsize_t rows;                          /* No. of unprocessed rows in file */
601
 
    JDIMENSION lines_per_MCU, size;
602
 
    register OJPEGState *sp = OJState(tif);
603
 
 
604
 
 /* Encode a chunk of pixels, where returned data is down-sampled as per the
605
 
    sampling factors.  The data is expected to be written in scan-line
606
 
    multiples.
607
 
 */
608
 
    cc /= sp->bytesperline;
609
 
    if (cc % sp->bytesperline) TIFFWarning(tif->tif_name,no_write_frac);
610
 
    if ( (cc /= bytesperline)      /* No. of complete rows in caller's buffer */
611
 
       > (rows = sp->cinfo.c.image_height - sp->cinfo.c.next_scanline)
612
 
       ) cc = rows;
613
 
#   ifdef C_LOSSLESS_SUPPORTED
614
 
    lines_per_MCU = sp->cinfo.c.max_samp_factor*(size = sp->cinfo.d.data_unit);
615
 
#   else
616
 
    lines_per_MCU = sp->cinfo.c.max_samp_factor*(size = DCTSIZE);
617
 
#   endif
618
 
    while (--cc >= 0)
619
 
      { int ci = 0, clumpoffset = 0;
620
 
        register jpeg_component_info *compptr = sp->cinfo.c.comp_info;
621
 
 
622
 
     /* The fastest way to separate the data is to make 1 pass over the scan
623
 
        line for each row of each component.
624
 
     */
625
 
        do
626
 
          { int ypos = 0;
627
 
 
628
 
            do
629
 
              { int padding;
630
 
                register JSAMPLE *inptr = (JSAMPLE*)buf + clumpoffset,
631
 
                                 *outptr =
632
 
                  sp->ds_buffer[ci][sp->scancount*compptr->v_samp_factor+ypos];
633
 
             /* Cb,Cr both have sampling factors 1, so this is correct */
634
 
                register int clumps_per_line =
635
 
                  sp->cinfo.c.comp_info[1].downsampled_width,
636
 
                             xpos;
637
 
 
638
 
                padding = (int)
639
 
#                         ifdef C_LOSSLESS_SUPPORTED
640
 
                          ( compptr->width_in_data_units * size
641
 
#                         else
642
 
                          ( compptr->width_in_blocks * size
643
 
#                         endif
644
 
                          - clumps_per_line * compptr->h_samp_factor
645
 
                          );
646
 
                if (compptr->h_samp_factor == 1) /* Cb & Cr fast path */
647
 
                  do *outptr++ = *inptr;
648
 
                  while ((inptr += sp->samplesperclump),--clumps_per_line > 0);
649
 
                else /* general case */
650
 
                  do
651
 
                    {
652
 
                      xpos = 0;
653
 
                      do *outptr++ = inptr[xpos];
654
 
                      while (++xpos < compptr->h_samp_factor);
655
 
                    }
656
 
                  while ((inptr += sp->samplesperclump),--clumps_per_line > 0);
657
 
                xpos = 0; /* Pad each scan line as needed */
658
 
                do outptr[0] = outptr[-1]; while (++outptr,++xpos < padding);
659
 
                clumpoffset += compptr->h_samp_factor;
660
 
              }
661
 
            while (++ypos < compptr->v_samp_factor);
662
 
          }
663
 
        while (++compptr,++ci < sp->cinfo.c.num_components);
664
 
        if (++sp->scancount >= size)
665
 
          {
666
 
            if (   CALLJPEG(sp,-1,jpeg_write_raw_data(&sp->cinfo.c,sp->ds_buffer,lines_per_MCU))
667
 
                != lines_per_MCU
668
 
               ) return 0;
669
 
            sp->scancount = 0;
670
 
          };
671
 
        ++tif->tif_row++
672
 
        buf += sp->bytesperline;
673
 
      };
674
 
    return 1;
675
 
  }
676
 
 
677
 
static int
678
 
OJPEGSetupEncode(register TIFF *tif)
679
 
  { static const char module[]={"OJPEGSetupEncode"};
680
 
    uint32 segment_height, segment_width;
681
 
    int status = 1;                              /* Assume success by default */
682
 
    register OJPEGState *sp = OJState(tif);
683
 
#   define td (&tif->tif_dir)
684
 
 
685
 
 /* Verify miscellaneous parameters.  This will need work if the TIFF Library
686
 
    ever supports different depths for different components, or if the JPEG
687
 
    Library ever supports run-time depth selection.  Neither seems imminent.
688
 
 */
689
 
    if (td->td_bitspersample != 8)
690
 
      {
691
 
        TIFFError(module,bad_bps,td->td_bitspersample);
692
 
        status = 0;
693
 
      };
694
 
 
695
 
 /* The TIFF Version 6.0 specification and IJG JPEG Library accept different
696
 
    sets of color spaces, so verify that our image belongs to the common subset
697
 
    and map its photometry code, then initialize to handle subsampling and
698
 
    optional JPEG Library YCbCr <-> RGB color-space conversion.
699
 
 */
700
 
    switch (td->td_photometric)
701
 
      {
702
 
        case PHOTOMETRIC_YCBCR     :
703
 
 
704
 
       /* ISO IS 10918-1 requires that JPEG subsampling factors be 1-4, but
705
 
          TIFF Version 6.0 is more restrictive: only 1, 2, and 4 are allowed.
706
 
       */
707
 
          if (   (   td->td_ycbcrsubsampling[0] == 1
708
 
                  || td->td_ycbcrsubsampling[0] == 2
709
 
                  || td->td_ycbcrsubsampling[0] == 4
710
 
                 )
711
 
              && (   td->td_ycbcrsubsampling[1] == 1
712
 
                  || td->td_ycbcrsubsampling[1] == 2
713
 
                  || td->td_ycbcrsubsampling[1] == 4
714
 
                 )
715
 
             )
716
 
            sp->cinfo.c.raw_data_in =
717
 
              ( (sp->h_sampling = td->td_ycbcrsubsampling[0]) << 3
718
 
              | (sp->v_sampling = td->td_ycbcrsubsampling[1])
719
 
              ) != 011;
720
 
          else
721
 
            {
722
 
              TIFFError(module,bad_subsampling);
723
 
              status = 0;
724
 
            };
725
 
 
726
 
       /* A ReferenceBlackWhite field MUST be present, since the default value
727
 
          is inapproriate for YCbCr.  Fill in the proper value if the
728
 
          application didn't set it.
729
 
       */
730
 
          if (!TIFFFieldSet(tif,FIELD_REFBLACKWHITE))
731
 
            { float refbw[6];
732
 
              long top = 1L << td->td_bitspersample;
733
 
 
734
 
              refbw[0] = 0;
735
 
              refbw[1] = (float)(top-1L);
736
 
              refbw[2] = (float)(top>>1);
737
 
              refbw[3] = refbw[1];
738
 
              refbw[4] = refbw[2];
739
 
              refbw[5] = refbw[1];
740
 
              TIFFSetField(tif,TIFFTAG_REFERENCEBLACKWHITE,refbw);
741
 
            };
742
 
          sp->cinfo.c.jpeg_color_space = JCS_YCbCr;
743
 
          if (sp->jpegcolormode == JPEGCOLORMODE_RGB)
744
 
            {
745
 
              sp->cinfo.c.raw_data_in = FALSE;
746
 
              sp->in_color_space = JCS_RGB;
747
 
              break;
748
 
            };
749
 
          goto L2;
750
 
        case PHOTOMETRIC_MINISBLACK:
751
 
          sp->cinfo.c.jpeg_color_space = JCS_GRAYSCALE;
752
 
          goto L1;
753
 
        case PHOTOMETRIC_RGB       :
754
 
          sp->cinfo.c.jpeg_color_space = JCS_RGB;
755
 
          goto L1;
756
 
        case PHOTOMETRIC_SEPARATED :
757
 
          sp->cinfo.c.jpeg_color_space = JCS_CMYK;
758
 
      L1: sp->jpegcolormode = JPEGCOLORMODE_RAW; /* No JPEG Lib. conversion */
759
 
      L2: sp->cinfo.d.in_color_space = sp->cinfo.d.jpeg_color-space;
760
 
          break;
761
 
        default                    :
762
 
          TIFFError(module,bad_photometry,td->td_photometric);
763
 
          status = 0;
764
 
      };
765
 
    tif->tif_encoderow = tif->tif_encodestrip = tif->tif_encodetile =
766
 
      sp->cinfo.c.raw_data_in ? OJPEGEncodeRaw : OJPEGEncode;
767
 
    if (isTiled(tif))
768
 
      { tsize_t size;
769
 
 
770
 
#       ifdef C_LOSSLESS_SUPPORTED
771
 
        if ((size = sp->v_sampling*sp->cinfo.c.data_unit) < 16) size = 16;
772
 
#       else
773
 
        if ((size = sp->v_sampling*DCTSIZE) < 16) size = 16;
774
 
#       endif
775
 
        if ((segment_height = td->td_tilelength) % size)
776
 
          {
777
 
            TIFFError(module,"JPEG tile height must be multiple of %d",size);
778
 
            status = 0;
779
 
          };
780
 
#       ifdef C_LOSSLESS_SUPPORTED
781
 
        if ((size = sp->h_sampling*sp->cinfo.c.data_unit) < 16) size = 16;
782
 
#       else
783
 
        if ((size = sp->h_sampling*DCTSIZE) < 16) size = 16;
784
 
#       endif
785
 
        if ((segment_width = td->td_tilewidth) % size)
786
 
          {
787
 
            TIFFError(module,"JPEG tile width must be multiple of %d",size);
788
 
            status = 0;
789
 
          };
790
 
        sp->bytesperline = TIFFTileRowSize(tif);
791
 
      }
792
 
    else
793
 
      { tsize_t size;
794
 
 
795
 
#       ifdef C_LOSSLESS_SUPPORTED
796
 
        if ((size = sp->v_sampling*sp->cinfo.c.data_unit) < 16) size = 16;
797
 
#       else
798
 
        if ((size = sp->v_sampling*DCTSIZE) < 16) size = 16;
799
 
#       endif
800
 
        if (td->td_rowsperstrip < (segment_height = td->td_imagelength))
801
 
          {
802
 
            if (td->td_rowsperstrip % size)
803
 
              {
804
 
                TIFFError(module,"JPEG RowsPerStrip must be multiple of %d",size);
805
 
                status = 0;
806
 
              };
807
 
            segment_height = td->td_rowsperstrip;
808
 
          };
809
 
        segment_width = td->td_imagewidth;
810
 
        sp->bytesperline = tif->tif_scanlinesize;
811
 
      };
812
 
    if (segment_width > 65535 || segment_height > 65535)
813
 
      {
814
 
        TIFFError(module,"Strip/tile too large for JPEG");
815
 
        status = 0;
816
 
      };
817
 
 
818
 
 /* Initialize all JPEG parameters to default values.  Note that the JPEG
819
 
    Library's "jpeg_set_defaults()" method needs legal values for the
820
 
    "in_color_space" and "input_components" fields.
821
 
 */
822
 
    sp->cinfo.c.input_components = 1; /* Default for JCS_UNKNOWN */
823
 
    if (!CALLVJPEG(sp,jpeg_set_defaults(&sp->cinfo.c))) status = 0;
824
 
    switch (sp->jpegtablesmode & (JPEGTABLESMODE_HUFF|JPEGTABLESMODE_QUANT))
825
 
      { register JHUFF_TBL *htbl;
826
 
        register JQUANT_TBL *qtbl;
827
 
 
828
 
        case 0                                       :
829
 
          sp->cinfo.c.optimize_coding = TRUE;
830
 
        case JPEGTABLESMODE_HUFF                     :
831
 
          if (!CALLVJPEG(sp,jpeg_set_quality(&sp->cinfo.c,sp->jpegquality,FALSE)))
832
 
            return 0;
833
 
          if (qtbl = sp->cinfo.c.quant_tbl_ptrs[0]) qtbl->sent_table = FALSE;
834
 
          if (qtbl = sp->cinfo.c.quant_tbl_ptrs[1]) qtbl->sent_table = FALSE;
835
 
          goto L3;
836
 
        case JPEGTABLESMODE_QUANT                    :
837
 
          sp->cinfo.c.optimize_coding = TRUE;
838
 
 
839
 
       /* We do not support application-supplied JPEG tables, so mark the field
840
 
          "not present".
841
 
       */
842
 
      L3: TIFFClrFieldBit(tif,FIELD_JPEGTABLES);
843
 
          break;
844
 
        case JPEGTABLESMODE_HUFF|JPEGTABLESMODE_QUANT:
845
 
          if (   !CALLVJPEG(sp,jpeg_set_quality(&sp->cinfo.c,sp->jpegquality,FALSE))
846
 
              || !CALLVJPEG(sp,jpeg_suppress_tables(&sp->cinfo.c,TRUE))
847
 
             )
848
 
            {
849
 
              status = 0;
850
 
              break;
851
 
            };
852
 
          if (qtbl = sp->cinfo.c.quant_tbl_ptrs[0]) qtbl->sent_table = FALSE;
853
 
          if (htbl = sp->cinfo.c.dc_huff_tbl_ptrs[0]) htbl->sent_table = FALSE;
854
 
          if (htbl = sp->cinfo.c.ac_huff_tbl_ptrs[0]) htbl->sent_table = FALSE;
855
 
          if (sp->cinfo.c.jpeg_color_space == JCS_YCbCr)
856
 
            {
857
 
              if (qtbl = sp->cinfo.c.quant_tbl_ptrs[1])
858
 
                qtbl->sent_table = FALSE;
859
 
              if (htbl = sp->cinfo.c.dc_huff_tbl_ptrs[1])
860
 
                htbl->sent_table = FALSE;
861
 
              if (htbl = sp->cinfo.c.ac_huff_tbl_ptrs[1])
862
 
                htbl->sent_table = FALSE;
863
 
            };
864
 
          if (   TIFFojpeg_tables_dest(sp,tif)
865
 
              && CALLVJPEG(sp,jpeg_write_tables(&sp->cinfo.c))
866
 
             )
867
 
            {
868
 
    
869
 
           /* Mark the field "present".  We can't use "TIFFSetField()" because
870
 
              "BEENWRITING" is already set!
871
 
           */
872
 
              TIFFSetFieldBit(tif,FIELD_JPEGTABLES);
873
 
              tif->tif_flags |= TIFF_DIRTYDIRECT;
874
 
            }
875
 
          else status = 0;
876
 
      };
877
 
    if (   sp->cinfo.c.raw_data_in
878
 
        && !alloc_downsampled_buffers(tif,sp->cinfo.c.comp_info,
879
 
                                      sp->cinfo.c.num_components)
880
 
       ) status = 0;
881
 
    if (status == 0) return 0; /* If TIFF errors, don't bother to continue */
882
 
 /* Grab parameters that are same for all strips/tiles. */
883
 
 
884
 
    sp->dest.init_destination = std_init_destination;
885
 
    sp->dest.empty_output_buffer = std_empty_output_buffer;
886
 
    sp->dest.term_destination = std_term_destination;
887
 
    sp->cinfo.c.dest = &sp->dest;
888
 
    sp->cinfo.c.data_precision = td->td_bitspersample;
889
 
    sp->cinfo.c.write_JFIF_header = /* Don't write extraneous markers */
890
 
    sp->cinfo.c.write_Adobe_marker = FALSE;
891
 
    sp->cinfo.c.image_width = segment_width;
892
 
    sp->cinfo.c.image_height = segment_height;
893
 
    sp->cinfo.c.comp_info[0].h_samp_factor =
894
 
    sp->cinfo.c.comp_info[0].v_samp_factor = 1;
895
 
    return CALLVJPEG(sp,jpeg_start_compress(&sp->cinfo.c,FALSE));
896
 
#   undef td
897
 
  }
898
 
 
899
 
static int
900
 
OJPEGPreEncode(register TIFF *tif,tsample_t s)
901
 
  { register OJPEGState *sp = OJState(tif);
902
 
#   define td (&tif->tif_dir)
903
 
 
904
 
 /* If we are about to write the first row of an image plane, which should
905
 
    coincide with a JPEG "scan", reset the JPEG Library's compressor.  Otherwise
906
 
    let the compressor run "as is" and return a "success" status without further
907
 
    ado.
908
 
 */
909
 
    if (     (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip)
910
 
           % td->td_stripsperimage
911
 
        == 0
912
 
       )
913
 
      {
914
 
        if (   (sp->cinfo.c.comp_info[0].component_id = s) == 1)
915
 
            && sp->cinfo.c.jpeg_color_space == JCS_YCbCr
916
 
           )
917
 
          {
918
 
            sp->cinfo.c.comp_info[0].quant_tbl_no =
919
 
            sp->cinfo.c.comp_info[0].dc_tbl_no =
920
 
            sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
921
 
            sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
922
 
            sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
923
 
    
924
 
         /* Scale expected strip/tile size to match a downsampled component. */
925
 
    
926
 
            sp->cinfo.c.image_width = TIFFhowmany(segment_width,sp->h_sampling);
927
 
            sp->cinfo.c.image_height=TIFFhowmany(segment_height,sp->v_sampling);
928
 
          };
929
 
        sp->scancount = 0; /* Mark subsampling buffer(s) empty */
930
 
      };
931
 
    return 1;
932
 
#   undef td
933
 
  }
934
 
 
935
 
static int
936
 
OJPEGPostEncode(register TIFF *tif)
937
 
  { register OJPEGState *sp = OJState(tif);
938
 
 
939
 
 /* Finish up at the end of a strip or tile. */
940
 
 
941
 
    if (sp->scancount > 0) /* emit partial buffer of down-sampled data */
942
 
      { JDIMENSION n;
943
 
 
944
 
#       ifdef C_LOSSLESS_SUPPORTED
945
 
        if (   sp->scancount < sp->cinfo.c.data_unit
946
 
            && sp->cinfo.c.num_components > 0
947
 
           )
948
 
#       else
949
 
        if (sp->scancount < DCTSIZE && sp->cinfo.c.num_components > 0)
950
 
#       endif
951
 
          { int ci = 0,                            /* Pad the data vertically */
952
 
#           ifdef C_LOSSLESS_SUPPORTED
953
 
                size = sp->cinfo.c.data_unit;
954
 
#           else
955
 
                size = DCTSIZE;
956
 
#           endif
957
 
            register jpeg_component_info *compptr = sp->cinfo.c.comp_info;
958
 
 
959
 
            do
960
 
#              ifdef C_LOSSLESS_SUPPORTED
961
 
               { tsize_t row_width = compptr->width_in_data_units
962
 
#              else
963
 
                 tsize_t row_width = compptr->width_in_blocks
964
 
#              endif
965
 
                   *size*sizeof(JSAMPLE);
966
 
                 int ypos = sp->scancount*compptr->v_samp_factor;
967
 
 
968
 
                 do _TIFFmemcpy( (tdata_t)sp->ds_buffer[ci][ypos]
969
 
                               , (tdata_t)sp->ds_buffer[ci][ypos-1]
970
 
                               , row_width
971
 
                               );
972
 
                 while (++ypos < compptr->v_samp_factor*size);
973
 
               }
974
 
            while (++compptr,++ci < sp->cinfo.c.num_components);
975
 
          };
976
 
        n = sp->cinfo.c.max_v_samp_factor*size;
977
 
        if (CALLJPEG(sp,-1,jpeg_write_raw_data(&sp->cinfo.c,sp->ds_buffer,n)) != n)
978
 
          return 0;
979
 
      };
980
 
    return CALLVJPEG(sp,jpeg_finish_compress(&sp->cinfo.c));
981
 
  }
982
 
#endif /* never */
983
 
 
984
 
/* JPEG Decoding begins here. */
985
 
 
986
 
/*ARGSUSED*/ static int
987
 
OJPEGDecode(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s)
988
 
  { tsize_t bytesperline = isTiled(tif)
989
 
                         ? TIFFTileRowSize(tif)
990
 
                         : tif->tif_scanlinesize,
991
 
            rows;                          /* No. of unprocessed rows in file */
992
 
    register OJPEGState *sp = OJState(tif);
993
 
 
994
 
 /* Decode a chunk of pixels, where the input data has not NOT been down-
995
 
    sampled, or else the TIFF Library's client has used the "JPEGColorMode" TIFF
996
 
    pseudo-tag to request that the JPEG Library do color-space conversion; this
997
 
    is the normal case.  The data is expected to be read in scan-line multiples,
998
 
    and this subroutine is called for both pixel-interleaved and separate color
999
 
    planes.
1000
 
 
1001
 
    WARNING:  Unlike "OJPEGDecodeRawContig()", below, the no. of Bytes in each
1002
 
              decoded row is calculated here as "bytesperline" instead of
1003
 
    using "sp->bytesperline", which might be a little smaller.  This can
1004
 
    occur for an old tiled image whose width isn't a multiple of 8 pixels.
1005
 
    That's illegal according to the TIFF Version 6 specification, but some
1006
 
    test files, like "zackthecat.tif", were built that way.  In those cases,
1007
 
    we want to embed the image's true width in our caller's buffer (which is
1008
 
    presumably allocated according to the expected tile width) by
1009
 
    effectively "padding" it with unused Bytes at the end of each row.
1010
 
 */
1011
 
    if ( (cc /= bytesperline)      /* No. of complete rows in caller's buffer */
1012
 
       > (rows = sp->cinfo.d.output_height - sp->cinfo.d.output_scanline)
1013
 
       ) cc = rows;
1014
 
    while (--cc >= 0)
1015
 
      {
1016
 
        if (   CALLJPEG(sp,-1,jpeg_read_scanlines(&sp->cinfo.d,(JSAMPARRAY)&buf,1))
1017
 
            != 1
1018
 
           ) return 0;
1019
 
        buf += bytesperline;
1020
 
        ++tif->tif_row;
1021
 
      };
1022
 
 
1023
 
 /* BEWARE OF KLUDGE:  If our input file was produced by Microsoft's Wang
1024
 
                       Imaging for Windows application, the DC coefficients of
1025
 
    each JPEG image component (Y,Cb,Cr) must be reset at the end of each TIFF
1026
 
    "strip", and any JPEG data bits remaining in the current Byte of the
1027
 
    decoder's input buffer must be discarded.  To do so, we create an "ad hoc"
1028
 
    interface in the "jdhuff.c" module of IJG JPEG Library Version 6 (module
1029
 
    "jdshuff.c", if Ken Murchison's lossless-Huffman patch is applied), and we
1030
 
    invoke that interface here after decoding each "strip".
1031
 
 */
1032
 
    if (sp->is_WANG) jpeg_reset_huff_decode(&sp->cinfo.d);
1033
 
    return 1;
1034
 
  }
1035
 
 
1036
 
/*ARGSUSED*/ static int
1037
 
OJPEGDecodeRawContig(register TIFF *tif,tidata_t buf,tsize_t cc,tsample_t s)
1038
 
  { tsize_t rows;                          /* No. of unprocessed rows in file */
1039
 
    JDIMENSION lines_per_MCU, size;
1040
 
    register OJPEGState *sp = OJState(tif);
1041
 
 
1042
 
 /* Decode a chunk of pixels, where the input data has pixel-interleaved color
1043
 
    planes, some of which have been down-sampled, but the TIFF Library's client
1044
 
    has NOT used the "JPEGColorMode" TIFF pseudo-tag to request that the JPEG
1045
 
    Library do color-space conversion.  In other words, we must up-sample/
1046
 
    expand/duplicate image components according to the image's sampling factors,
1047
 
    without changing its color space.  The data is expected to be read in scan-
1048
 
    line multiples.
1049
 
 */
1050
 
    if ( (cc /= sp->bytesperline)  /* No. of complete rows in caller's buffer */
1051
 
       > (rows = sp->cinfo.d.output_height - sp->cinfo.d.output_scanline)
1052
 
       ) cc = rows;
1053
 
    lines_per_MCU = sp->cinfo.d.max_v_samp_factor
1054
 
#   ifdef D_LOSSLESS_SUPPORTED
1055
 
                  * (size = sp->cinfo.d.min_codec_data_unit);
1056
 
#   else
1057
 
                  * (size = DCTSIZE);
1058
 
#   endif
1059
 
    while (--cc >= 0)
1060
 
      { int clumpoffset, ci;
1061
 
        register jpeg_component_info *compptr;
1062
 
 
1063
 
        if (sp->scancount >= size) /* reload downsampled-data buffers */
1064
 
          {
1065
 
            if (   CALLJPEG(sp,-1,jpeg_read_raw_data(&sp->cinfo.d,sp->ds_buffer,lines_per_MCU))
1066
 
                != lines_per_MCU
1067
 
               ) return 0;
1068
 
            sp->scancount = 0;
1069
 
          };
1070
 
 
1071
 
     /* The fastest way to separate the data is: make 1 pass over the scan
1072
 
        line for each row of each component.
1073
 
     */
1074
 
        clumpoffset = ci = 0;
1075
 
        compptr = sp->cinfo.d.comp_info;
1076
 
        do
1077
 
          { int ypos = 0;
1078
 
 
1079
 
            if (compptr->h_samp_factor == 1) /* fast path */
1080
 
              do
1081
 
                { register JSAMPLE *inptr =
1082
 
                    sp->ds_buffer[ci][sp->scancount*compptr->v_samp_factor+ypos],
1083
 
                                   *outptr = (JSAMPLE *)buf + clumpoffset;
1084
 
                  register int clumps_per_line = compptr->downsampled_width;
1085
 
 
1086
 
                  do *outptr = *inptr++;
1087
 
                  while ((outptr += sp->samplesperclump),--clumps_per_line > 0);
1088
 
                }
1089
 
              while ( (clumpoffset += compptr->h_samp_factor)
1090
 
                    , ++ypos < compptr->v_samp_factor
1091
 
                    );
1092
 
            else /* general case */
1093
 
              do
1094
 
                { register JSAMPLE *inptr =
1095
 
                    sp->ds_buffer[ci][sp->scancount*compptr->v_samp_factor+ypos],
1096
 
                                   *outptr = (JSAMPLE *)buf + clumpoffset;
1097
 
                  register int clumps_per_line = compptr->downsampled_width;
1098
 
 
1099
 
                  do
1100
 
                    { register int xpos = 0;
1101
 
 
1102
 
                      do outptr[xpos] = *inptr++;
1103
 
                      while (++xpos < compptr->h_samp_factor);
1104
 
                    }
1105
 
                  while ((outptr += sp->samplesperclump),--clumps_per_line > 0);
1106
 
                }
1107
 
              while ( (clumpoffset += compptr->h_samp_factor)
1108
 
                    , ++ypos < compptr->v_samp_factor
1109
 
                    );
1110
 
          }
1111
 
        while (++compptr,++ci < sp->cinfo.d.num_components);
1112
 
        ++sp->scancount;
1113
 
        buf += sp->bytesperline;
1114
 
        ++tif->tif_row;
1115
 
      };
1116
 
 
1117
 
 /* BEWARE OF KLUDGE:  If our input file was produced by Microsoft's Wang
1118
 
                       Imaging for Windows application, the DC coefficients of
1119
 
    each JPEG image component (Y,Cb,Cr) must be reset at the end of each TIFF
1120
 
    "strip", and any JPEG data bits remaining in the current Byte of the
1121
 
    decoder's input buffer must be discarded.  To do so, we create an "ad hoc"
1122
 
    interface in the "jdhuff.c" module of IJG JPEG Library Version 6 (module
1123
 
    "jdshuff.c", if Ken Murchison's lossless-Huffman patch is applied), and we
1124
 
    invoke that interface here after decoding each "strip".
1125
 
 */
1126
 
    if (sp->is_WANG) jpeg_reset_huff_decode(&sp->cinfo.d);
1127
 
    return 1;
1128
 
  }
1129
 
 
1130
 
/*ARGSUSED*/ static int
1131
 
OJPEGDecodeRawSeparate(TIFF *tif,register tidata_t buf,tsize_t cc,tsample_t s)
1132
 
  { tsize_t rows;                          /* No. of unprocessed rows in file */
1133
 
    JDIMENSION lines_per_MCU,
1134
 
               size,                                             /* ...of MCU */
1135
 
               v;                   /* Component's vertical up-sampling ratio */
1136
 
    register OJPEGState *sp = OJState(tif);
1137
 
    register jpeg_component_info *compptr = sp->cinfo.d.comp_info + s;
1138
 
 
1139
 
 /* Decode a chunk of pixels, where the input data has separate color planes,
1140
 
    some of which have been down-sampled, but the TIFF Library's client has NOT
1141
 
    used the "JPEGColorMode" TIFF pseudo-tag to request that the JPEG Library
1142
 
    do color-space conversion.  The data is expected to be read in scan-line
1143
 
    multiples.
1144
 
 */
1145
 
    v = sp->cinfo.d.max_v_samp_factor/compptr->v_samp_factor;
1146
 
    if ( (cc /= compptr->downsampled_width) /* No. of rows in caller's buffer */
1147
 
       > (rows = (sp->cinfo.d.output_height-sp->cinfo.d.output_scanline+v-1)/v)
1148
 
       ) cc = rows; /* No. of rows of "clumps" to read */
1149
 
    lines_per_MCU = sp->cinfo.d.max_v_samp_factor
1150
 
#   ifdef D_LOSSLESS_SUPPORTED
1151
 
                  * (size = sp->cinfo.d.min_codec_data_unit);
1152
 
#   else
1153
 
                  * (size = DCTSIZE);
1154
 
#   endif
1155
 
 L: if (sp->scancount >= size) /* reload downsampled-data buffers */
1156
 
      {
1157
 
        if (   CALLJPEG(sp,-1,jpeg_read_raw_data(&sp->cinfo.d,sp->ds_buffer,lines_per_MCU))
1158
 
            != lines_per_MCU
1159
 
           ) return 0;
1160
 
        sp->scancount = 0;
1161
 
      };
1162
 
    rows = 0;
1163
 
    do
1164
 
      { register JSAMPLE *inptr =
1165
 
          sp->ds_buffer[s][sp->scancount*compptr->v_samp_factor + rows];
1166
 
        register int clumps_per_line = compptr->downsampled_width;
1167
 
 
1168
 
        do *buf++ = *inptr++; while (--clumps_per_line > 0); /* Copy scanline */
1169
 
        tif->tif_row += v;
1170
 
        if (--cc <= 0) return 1; /* End of caller's buffer? */
1171
 
      }
1172
 
    while (++rows < compptr->v_samp_factor);
1173
 
    ++sp->scancount;
1174
 
    goto L;
1175
 
  }
1176
 
 
1177
 
/* "OJPEGSetupDecode()" temporarily forces the JPEG Library to use the following
1178
 
   subroutine as a "dummy" input reader in order to fool the library into
1179
 
   thinking that it has read the image's first "Start of Scan" (SOS) marker, so
1180
 
   that it initializes accordingly.
1181
 
*/
1182
 
/*ARGSUSED*/ METHODDEF(int)
1183
 
fake_SOS_marker(j_decompress_ptr cinfo){return JPEG_REACHED_SOS;}
1184
 
 
1185
 
/*ARGSUSED*/ METHODDEF(int)
1186
 
suspend(j_decompress_ptr cinfo){return JPEG_SUSPENDED;}
1187
 
 
1188
 
/* The JPEG Library's "null" color-space converter actually re-packs separate
1189
 
   color planes (it's native image representation) into a pixel-interleaved,
1190
 
   contiguous plane.  But if our TIFF Library client is tryng to process a
1191
 
   PLANARCONFIG_SEPARATE image, we don't want that; so here are modifications of
1192
 
   code in the JPEG Library's "jdcolor.c" file, which simply copy Bytes to a
1193
 
   color plane specified by the current JPEG "scan".
1194
 
*/
1195
 
METHODDEF(void)
1196
 
ycc_rgb_convert(register j_decompress_ptr cinfo,JSAMPIMAGE in,JDIMENSION row,
1197
 
                register JSAMPARRAY out,register int nrows)
1198
 
  { typedef struct                /* "jdcolor.c" color-space conversion state */
1199
 
      {
1200
 
 
1201
 
     /* WARNING:  This declaration is ugly and dangerous!  It's supposed to be
1202
 
                  private to the JPEG Library's "jdcolor.c" module, but we also
1203
 
        need it here.  Since the library's copy might change without notice, be
1204
 
        sure to keep this one synchronized or the following code will break!
1205
 
     */
1206
 
        struct jpeg_color_deconverter pub; /* Public fields */
1207
 
     /* Private state for YCC->RGB conversion */
1208
 
        int *Cr_r_tab,   /* ->Cr to R conversion table */
1209
 
            *Cb_b_tab;   /* ->Cb to B conversion table */
1210
 
        INT32 *Cr_g_tab, /* ->Cr to G conversion table */
1211
 
              *Cb_g_tab; /* ->Cb to G conversion table */
1212
 
      } *my_cconvert_ptr;
1213
 
    my_cconvert_ptr cconvert = (my_cconvert_ptr)cinfo->cconvert;
1214
 
    JSAMPARRAY irow0p = in[0] + row;
1215
 
    register JSAMPLE *range_limit = cinfo->sample_range_limit;
1216
 
    register JSAMPROW outp, Y;
1217
 
 
1218
 
    switch (cinfo->output_scan_number - 1)
1219
 
      { JSAMPARRAY irow1p, irow2p;
1220
 
        register INT32 *table0, *table1;
1221
 
        SHIFT_TEMPS
1222
 
 
1223
 
        case RGB_RED  : irow2p = in[2] + row;
1224
 
                        table0 = (INT32 *)cconvert->Cr_r_tab;
1225
 
                        while (--nrows >= 0)
1226
 
                          { register JSAMPROW Cr = *irow2p++;
1227
 
                             register int i = cinfo->output_width;
1228
 
 
1229
 
                             Y = *irow0p++;
1230
 
                             outp = *out++;
1231
 
                             while (--i >= 0)
1232
 
                               *outp++ = range_limit[*Y++ + table0[*Cr++]];
1233
 
                          };
1234
 
                        return;
1235
 
        case RGB_GREEN: irow1p = in[1] + row;
1236
 
                        irow2p = in[2] + row;
1237
 
                        table0 = cconvert->Cb_g_tab;
1238
 
                        table1 = cconvert->Cr_g_tab;
1239
 
                        while (--nrows >= 0)
1240
 
                          { register JSAMPROW Cb = *irow1p++,
1241
 
                                              Cr = *irow2p++;
1242
 
                             register int i = cinfo->output_width;
1243
 
 
1244
 
                             Y = *irow0p++;
1245
 
                             outp = *out++;
1246
 
                             while (--i >= 0)
1247
 
                               *outp++ =
1248
 
                                 range_limit[ *Y++
1249
 
                                            + RIGHT_SHIFT(table0[*Cb++]+table1[*Cr++],16)
1250
 
                                            ];
1251
 
                          };
1252
 
                        return;
1253
 
        case RGB_BLUE : irow1p = in[1] + row;
1254
 
                        table0 = (INT32 *)cconvert->Cb_b_tab;
1255
 
                        while (--nrows >= 0)
1256
 
                          { register JSAMPROW Cb = *irow1p++;
1257
 
                             register int i = cinfo->output_width;
1258
 
 
1259
 
                             Y = *irow0p++;
1260
 
                             outp = *out++;
1261
 
                             while (--i >= 0)
1262
 
                               *outp++ = range_limit[*Y++ + table0[*Cb++]];
1263
 
                          }
1264
 
      }
1265
 
  }
1266
 
 
1267
 
METHODDEF(void)
1268
 
null_convert(register j_decompress_ptr cinfo,JSAMPIMAGE in,JDIMENSION row,
1269
 
             register JSAMPARRAY out,register int nrows)
1270
 
  { register JSAMPARRAY irowp = in[cinfo->output_scan_number - 1] + row;
1271
 
 
1272
 
    while (--nrows >= 0) _TIFFmemcpy(*out++,*irowp++,cinfo->output_width);
1273
 
  }
1274
 
 
1275
 
static int
1276
 
OJPEGSetupDecode(register TIFF *tif)
1277
 
  { static char module[]={"OJPEGSetupDecode"};
1278
 
    J_COLOR_SPACE jpeg_color_space,   /* Color space of JPEG-compressed image */
1279
 
                  out_color_space;       /* Color space of decompressed image */
1280
 
    uint32 segment_width;
1281
 
    int status = 1;                              /* Assume success by default */
1282
 
    boolean downsampled_output=FALSE, /* <=> Want JPEG Library's "raw" image? */
1283
 
            is_JFIF;                                       /* <=> JFIF image? */
1284
 
    register OJPEGState *sp = OJState(tif);
1285
 
#   define td (&tif->tif_dir)
1286
 
 
1287
 
 /* Verify miscellaneous parameters.  This will need work if the TIFF Library
1288
 
    ever supports different depths for different components, or if the JPEG
1289
 
    Library ever supports run-time depth selection.  Neither seems imminent.
1290
 
 */
1291
 
    if (td->td_bitspersample != sp->cinfo.d.data_precision)
1292
 
      {
1293
 
        TIFFError(module,bad_bps,td->td_bitspersample);
1294
 
        status = 0;
1295
 
      };
1296
 
 
1297
 
 /* The TIFF Version 6.0 specification and IJG JPEG Library accept different
1298
 
    sets of color spaces, so verify that our image belongs to the common subset
1299
 
    and map its photometry code, then initialize to handle subsampling and
1300
 
    optional JPEG Library YCbCr <-> RGB color-space conversion.
1301
 
 */
1302
 
    switch (td->td_photometric)
1303
 
      {
1304
 
        case PHOTOMETRIC_YCBCR     :
1305
 
 
1306
 
       /* ISO IS 10918-1 requires that JPEG subsampling factors be 1-4, but
1307
 
          TIFF Version 6.0 is more restrictive: only 1, 2, and 4 are allowed.
1308
 
       */
1309
 
          if (   (   td->td_ycbcrsubsampling[0] == 1
1310
 
                  || td->td_ycbcrsubsampling[0] == 2
1311
 
                  || td->td_ycbcrsubsampling[0] == 4
1312
 
                 )
1313
 
              && (   td->td_ycbcrsubsampling[1] == 1
1314
 
                  || td->td_ycbcrsubsampling[1] == 2
1315
 
                  || td->td_ycbcrsubsampling[1] == 4
1316
 
                 )
1317
 
             )
1318
 
            downsampled_output =
1319
 
              (
1320
 
                (sp->h_sampling = td->td_ycbcrsubsampling[0]) << 3
1321
 
              | (sp->v_sampling = td->td_ycbcrsubsampling[1])
1322
 
              ) != 011;
1323
 
          else
1324
 
            {
1325
 
              TIFFError(module,bad_subsampling);
1326
 
              status = 0;
1327
 
            };
1328
 
          jpeg_color_space = JCS_YCbCr;
1329
 
          if (sp->jpegcolormode == JPEGCOLORMODE_RGB)
1330
 
            {
1331
 
              downsampled_output = FALSE;
1332
 
              out_color_space = JCS_RGB;
1333
 
              break;
1334
 
            };
1335
 
          goto L2;
1336
 
        case PHOTOMETRIC_MINISBLACK:
1337
 
          jpeg_color_space = JCS_GRAYSCALE;
1338
 
          goto L1;
1339
 
        case PHOTOMETRIC_RGB       :
1340
 
          jpeg_color_space = JCS_RGB;
1341
 
          goto L1;
1342
 
        case PHOTOMETRIC_SEPARATED :
1343
 
          jpeg_color_space = JCS_CMYK;
1344
 
      L1: sp->jpegcolormode = JPEGCOLORMODE_RAW; /* No JPEG Lib. conversion */
1345
 
      L2: out_color_space = jpeg_color_space;
1346
 
          break;
1347
 
        default                    :
1348
 
          TIFFError(module,bad_photometry,td->td_photometric);
1349
 
          status = 0;
1350
 
      };
1351
 
    if (status == 0) return 0; /* If TIFF errors, don't bother to continue */
1352
 
 
1353
 
 /* Set parameters that are same for all strips/tiles. */
1354
 
 
1355
 
    sp->cinfo.d.src = &sp->src;
1356
 
    sp->src.init_source = std_init_source;
1357
 
    sp->src.fill_input_buffer = std_fill_input_buffer;
1358
 
    sp->src.skip_input_data = std_skip_input_data;
1359
 
    sp->src.resync_to_restart = jpeg_resync_to_restart;
1360
 
    sp->src.term_source = std_term_source;
1361
 
 
1362
 
 /* BOGOSITY ALERT!  The Wang Imaging application for Microsoft Windows produces
1363
 
                     images containing "JPEGInterchangeFormat[Length]" TIFF
1364
 
    records that resemble JFIF-in-TIFF encapsulations but, in fact, violate the
1365
 
    TIFF Version 6 specification in several ways; nevertheless, we try to handle
1366
 
    them gracefully because there are apparently a lot of them around.  The
1367
 
    purported "JFIF" data stream in one of these files vaguely resembles a JPEG
1368
 
    "tables only" data stream, except that there's no trailing EOI marker.  The
1369
 
    rest of the JPEG data stream lies in a discontiguous file region, identified
1370
 
    by the 0th Strip offset (which is *also* illegal!), where it begins with an
1371
 
    SOS marker and apparently continues to the end of the file.  There is no
1372
 
    trailing EOI marker here, either.
1373
 
 */
1374
 
    is_JFIF = !sp->is_WANG && TIFFFieldSet(tif,FIELD_JPEGIFOFFSET);
1375
 
 
1376
 
 /* Initialize decompression parameters that won't be overridden by JPEG Library
1377
 
    defaults set during the "jpeg_read_header()" call, below.
1378
 
 */
1379
 
    segment_width = td->td_imagewidth;
1380
 
    if (isTiled(tif))
1381
 
      {
1382
 
        if (sp->is_WANG) /* we don't know how to handle it */
1383
 
          {
1384
 
            TIFFError(module,"Tiled Wang image not supported");
1385
 
            return 0;
1386
 
          };
1387
 
 
1388
 
     /* BOGOSITY ALERT!  "TIFFTileRowSize()" seems to work fine for modern JPEG-
1389
 
                         in-TIFF encapsulations where the image width--like the
1390
 
        tile width--is a multiple of 8 or 16 pixels.  But image widths and
1391
 
        heights are aren't restricted to 8- or 16-bit multiples, and we need
1392
 
        the exact Byte count of decompressed scan lines when we call the JPEG
1393
 
        Library.  At least one old file ("zackthecat.tif") in the TIFF Library
1394
 
        test suite has widths and heights slightly less than the tile sizes, and
1395
 
        it apparently used the bogus computation below to determine the number
1396
 
        of Bytes per scan line (was this due to an old, broken version of
1397
 
        "TIFFhowmany()"?).  Before we get here, "OJPEGSetupDecode()" verified
1398
 
        that our image uses 8-bit samples, so the following check appears to
1399
 
        return the correct answer in all known cases tested to date.
1400
 
     */
1401
 
        if (is_JFIF || (segment_width & 7) == 0)
1402
 
          sp->bytesperline = TIFFTileRowSize(tif); /* Normal case */
1403
 
        else
1404
 
          {
1405
 
            /* Was the file-encoder's segment-width calculation bogus? */
1406
 
            segment_width = (segment_width/sp->h_sampling + 1) * sp->h_sampling;
1407
 
            sp->bytesperline = segment_width * td->td_samplesperpixel;
1408
 
          }
1409
 
      }
1410
 
    else sp->bytesperline = TIFFVStripSize(tif,1);
1411
 
 
1412
 
 /* BEWARE OF KLUDGE:  If we have JPEG Interchange File Format (JFIF) image,
1413
 
                       then we want to read "metadata" in the bit-stream's
1414
 
    header and validate it against corresponding information in TIFF records.
1415
 
    But if we have a *really old* JPEG file that's not JFIF, then we simply
1416
 
    assign TIFF-record values to JPEG Library variables without checking.
1417
 
 */
1418
 
    if (is_JFIF) /* JFIF image */
1419
 
      { unsigned char *end_of_data;
1420
 
        int subsampling_factors;
1421
 
        register unsigned char *p;
1422
 
        register int i;
1423
 
 
1424
 
     /* WARNING:  Although the image file contains a JFIF bit stream, it might
1425
 
                  also contain some old TIFF records causing "OJPEGVSetField()"
1426
 
        to have allocated quantization or Huffman decoding tables.  But when the
1427
 
        JPEG Library reads and parses the JFIF header below, it reallocate these
1428
 
        tables anew without checking for "dangling" pointers, thereby causing a
1429
 
        memory "leak".  We have enough information to potentially deallocate the
1430
 
        old tables here, but unfortunately JPEG Library Version 6B uses a "pool"
1431
 
        allocator for small objects, with no deallocation procedure; instead, it
1432
 
        reclaims a whole pool when an image is closed/destroyed, so well-behaved
1433
 
        TIFF client applications (i.e., those which close their JPEG images as
1434
 
        soon as they're no longer needed) will waste memory for a short time but
1435
 
        recover it eventually.  But ill-behaved TIFF clients (i.e., those which
1436
 
        keep many JPEG images open gratuitously) can exhaust memory prematurely.
1437
 
        If the JPEG Library ever implements a deallocation procedure, insert
1438
 
        this clean-up code:
1439
 
     */
1440
 
#       ifdef someday
1441
 
        if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) /* free quant. tables */
1442
 
          { register int i = 0;
1443
 
 
1444
 
            do
1445
 
              { register JQUANT_TBL *q;
1446
 
 
1447
 
                if (q = sp->cinfo.d.quant_tbl_ptrs[i])
1448
 
                  {
1449
 
                    jpeg_free_small(&sp->cinfo.comm,q,sizeof *q);
1450
 
                    sp->cinfo.d.quant_tbl_ptrs[i] = 0;
1451
 
                  }
1452
 
              }
1453
 
            while (++i < NUM_QUANT_TBLS);
1454
 
          };
1455
 
        if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) /* free Huffman tables */
1456
 
          { register int i = 0;
1457
 
 
1458
 
            do
1459
 
              { register JHUFF_TBL *h;
1460
 
 
1461
 
                if (h = sp->cinfo.d.dc_huff_tbl_ptrs[i])
1462
 
                  {
1463
 
                    jpeg_free_small(&sp->cinfo.comm,h,sizeof *h);
1464
 
                    sp->cinfo.d.dc_huff_tbl_ptrs[i] = 0;
1465
 
                  };
1466
 
                if (h = sp->cinfo.d.ac_huff_tbl_ptrs[i])
1467
 
                  {
1468
 
                    jpeg_free_small(&sp->cinfo.comm,h,sizeof *h);
1469
 
                    sp->cinfo.d.ac_huff_tbl_ptrs[i] = 0;
1470
 
                  }
1471
 
              }
1472
 
            while (++i < NUM_HUFF_TBLS);
1473
 
          };
1474
 
#       endif /* someday */
1475
 
 
1476
 
     /* Since we might someday wish to try rewriting "old format" JPEG-in-TIFF
1477
 
        encapsulations in "new format" files, try to synthesize the value of a
1478
 
        modern "JPEGTables" TIFF record by scanning the JPEG data from just past
1479
 
        the "Start of Information" (SOI) marker until something other than a
1480
 
        legitimate "table" marker is found, as defined in ISO IS 10918-1
1481
 
        Appending B.2.4; namely:
1482
 
 
1483
 
        -- Define Quantization Table (DQT)
1484
 
        -- Define Huffman Table (DHT)
1485
 
        -- Define Arithmetic Coding table (DAC)
1486
 
        -- Define Restart Interval (DRI)
1487
 
        -- Comment (COM)
1488
 
        -- Application data (APPn)
1489
 
 
1490
 
        For convenience, we also accept "Expansion" (EXP) markers, although they
1491
 
        are apparently not a part of normal "table" data.
1492
 
     */
1493
 
        sp->jpegtables = p = (unsigned char *)sp->src.next_input_byte;
1494
 
        end_of_data = p + sp->src.bytes_in_buffer;
1495
 
        p += 2;
1496
 
        while (p < end_of_data && p[0] == 0xFF)
1497
 
          switch (p[1])
1498
 
            {
1499
 
              default  : goto L;
1500
 
              case 0xC0: /* SOF0  */
1501
 
              case 0xC1: /* SOF1  */
1502
 
              case 0xC2: /* SOF2  */
1503
 
              case 0xC3: /* SOF3  */
1504
 
              case 0xC4: /* DHT   */
1505
 
              case 0xC5: /* SOF5  */
1506
 
              case 0xC6: /* SOF6  */
1507
 
              case 0xC7: /* SOF7  */
1508
 
              case 0xC9: /* SOF9  */
1509
 
              case 0xCA: /* SOF10 */
1510
 
              case 0xCB: /* SOF11 */
1511
 
              case 0xCC: /* DAC   */
1512
 
              case 0xCD: /* SOF13 */
1513
 
              case 0xCE: /* SOF14 */
1514
 
              case 0xCF: /* SOF15 */
1515
 
              case 0xDB: /* DQT   */
1516
 
              case 0xDD: /* DRI   */
1517
 
              case 0xDF: /* EXP   */
1518
 
              case 0xE0: /* APP0  */
1519
 
              case 0xE1: /* APP1  */
1520
 
              case 0xE2: /* APP2  */
1521
 
              case 0xE3: /* APP3  */
1522
 
              case 0xE4: /* APP4  */
1523
 
              case 0xE5: /* APP5  */
1524
 
              case 0xE6: /* APP6  */
1525
 
              case 0xE7: /* APP7  */
1526
 
              case 0xE8: /* APP8  */
1527
 
              case 0xE9: /* APP9  */
1528
 
              case 0xEA: /* APP10 */
1529
 
              case 0xEB: /* APP11 */
1530
 
              case 0xEC: /* APP12 */
1531
 
              case 0xED: /* APP13 */
1532
 
              case 0xEE: /* APP14 */
1533
 
              case 0xEF: /* APP15 */
1534
 
              case 0xFE: /* COM   */
1535
 
                         p += (p[2] << 8 | p[3]) + 2;
1536
 
            };
1537
 
     L: if (p - (unsigned char *)sp->jpegtables > 2) /* fake "JPEGTables" */
1538
 
          {
1539
 
 
1540
 
         /* In case our client application asks, pretend that this image file
1541
 
            contains a modern "JPEGTables" TIFF record by copying to a buffer
1542
 
            the initial part of the JFIF bit-stream that we just scanned, from
1543
 
            the SOI marker through the "metadata" tables, then append an EOI
1544
 
            marker and flag the "JPEGTables" TIFF record as "present".
1545
 
         */
1546
 
            sp->jpegtables_length = p - (unsigned char*)sp->jpegtables + 2;
1547
 
            p = sp->jpegtables;
1548
 
            if (!(sp->jpegtables = _TIFFmalloc(sp->jpegtables_length)))
1549
 
              {
1550
 
                TIFFError(module,no_jtable_space);
1551
 
                return 0;
1552
 
              };
1553
 
            _TIFFmemcpy(sp->jpegtables,p,sp->jpegtables_length-2);
1554
 
            p = (unsigned char *)sp->jpegtables + sp->jpegtables_length;
1555
 
            p[-2] = 0xFF; p[-1] = JPEG_EOI; /* Append EOI marker */
1556
 
            TIFFSetFieldBit(tif,FIELD_JPEGTABLES);
1557
 
            tif->tif_flags |= TIFF_DIRTYDIRECT;
1558
 
          }
1559
 
        else sp->jpegtables = 0; /* Don't simulate "JPEGTables" */
1560
 
        if (   CALLJPEG(sp,-1,jpeg_read_header(&sp->cinfo.d,TRUE))
1561
 
            != JPEG_HEADER_OK
1562
 
           ) return 0;
1563
 
        if (   sp->cinfo.d.image_width  != segment_width
1564
 
            || sp->cinfo.d.image_height != td->td_imagelength 
1565
 
           )
1566
 
          {
1567
 
            TIFFError(module,"Improper JPEG strip/tile size");
1568
 
            return 0;
1569
 
          };
1570
 
        if (sp->cinfo.d.num_components != td->td_samplesperpixel)
1571
 
          {
1572
 
            TIFFError(module,"Improper JPEG component count");
1573
 
            return 0;
1574
 
          };
1575
 
        if (sp->cinfo.d.data_precision != td->td_bitspersample)
1576
 
          {
1577
 
            TIFFError(module,"Improper JPEG data precision");
1578
 
            return 0;
1579
 
          };
1580
 
 
1581
 
     /* Check that JPEG image components all have the same subsampling factors
1582
 
        declared (or defaulted) in the TIFF file, since TIFF Version 6.0 is more
1583
 
        restrictive than JPEG:  Only the 0th component may have horizontal and
1584
 
        vertical subsampling factors other than <1,1>.
1585
 
     */
1586
 
        subsampling_factors = sp->h_sampling << 3 | sp->v_sampling;
1587
 
        i = 0;
1588
 
        do
1589
 
          {
1590
 
            if (   ( sp->cinfo.d.comp_info[i].h_samp_factor << 3
1591
 
                   | sp->cinfo.d.comp_info[i].v_samp_factor
1592
 
                   )
1593
 
                != subsampling_factors
1594
 
               )
1595
 
              {
1596
 
                TIFFError(module,"Improper JPEG subsampling factors");
1597
 
                return 0;
1598
 
              };
1599
 
            subsampling_factors = 011; /* Required for image components > 0 */
1600
 
          }
1601
 
        while (++i < sp->cinfo.d.num_components);
1602
 
      }
1603
 
    else /* not JFIF image */
1604
 
      { int (*save)(j_decompress_ptr cinfo) = sp->cinfo.d.marker->read_markers;
1605
 
        register int i;
1606
 
 
1607
 
     /* We're not assuming that this file's JPEG bit stream has any header
1608
 
        "metadata", so fool the JPEG Library into thinking that we read a
1609
 
        "Start of Input" (SOI) marker and a "Start of Frame" (SOFx) marker, then
1610
 
        force it to read a simulated "Start of Scan" (SOS) marker when we call
1611
 
        "jpeg_read_header()" below.  This should cause the JPEG Library to
1612
 
        establish reasonable defaults.
1613
 
     */
1614
 
        sp->cinfo.d.marker->saw_SOI =       /* Pretend we saw SOI marker */
1615
 
        sp->cinfo.d.marker->saw_SOF = TRUE; /* Pretend we saw SOF marker */
1616
 
        sp->cinfo.d.marker->read_markers =
1617
 
          sp->is_WANG ? suspend : fake_SOS_marker;
1618
 
        sp->cinfo.d.global_state = DSTATE_INHEADER;
1619
 
        sp->cinfo.d.Se = DCTSIZE2-1; /* Suppress JPEG Library warning */
1620
 
        sp->cinfo.d.image_width  = segment_width;
1621
 
        sp->cinfo.d.image_height = td->td_imagelength;
1622
 
 
1623
 
     /* The following color-space initialization, including the complicated
1624
 
        "switch"-statement below, essentially duplicates the logic used by the
1625
 
        JPEG Library's "jpeg_init_colorspace()" subroutine during compression.
1626
 
     */
1627
 
        sp->cinfo.d.num_components = td->td_samplesperpixel;
1628
 
        sp->cinfo.d.comp_info = (jpeg_component_info *)
1629
 
          (*sp->cinfo.d.mem->alloc_small)
1630
 
            ( &sp->cinfo.comm
1631
 
            , JPOOL_IMAGE
1632
 
            , sp->cinfo.d.num_components * sizeof *sp->cinfo.d.comp_info
1633
 
            );
1634
 
        i = 0;
1635
 
        do
1636
 
          {
1637
 
            sp->cinfo.d.comp_info[i].component_index = i;
1638
 
            sp->cinfo.d.comp_info[i].component_needed = TRUE;
1639
 
            sp->cinfo.d.cur_comp_info[i] = &sp->cinfo.d.comp_info[i];
1640
 
          }
1641
 
        while (++i < sp->cinfo.d.num_components);
1642
 
        switch (jpeg_color_space)
1643
 
          {
1644
 
            case JCS_UNKNOWN  :
1645
 
              i = 0;
1646
 
              do
1647
 
                {
1648
 
                  sp->cinfo.d.comp_info[i].component_id = i;
1649
 
                  sp->cinfo.d.comp_info[i].h_samp_factor =
1650
 
                  sp->cinfo.d.comp_info[i].v_samp_factor = 1;
1651
 
                }
1652
 
              while (++i < sp->cinfo.d.num_components);
1653
 
              break;
1654
 
            case JCS_GRAYSCALE:
1655
 
              sp->cinfo.d.comp_info[0].component_id =
1656
 
              sp->cinfo.d.comp_info[0].h_samp_factor =
1657
 
              sp->cinfo.d.comp_info[0].v_samp_factor = 1;
1658
 
              break;
1659
 
            case JCS_RGB      :
1660
 
              sp->cinfo.d.comp_info[0].component_id = 'R';
1661
 
              sp->cinfo.d.comp_info[1].component_id = 'G';
1662
 
              sp->cinfo.d.comp_info[2].component_id = 'B';
1663
 
              i = 0;
1664
 
              do sp->cinfo.d.comp_info[i].h_samp_factor =
1665
 
                 sp->cinfo.d.comp_info[i].v_samp_factor = 1;
1666
 
              while (++i < sp->cinfo.d.num_components);
1667
 
              break;
1668
 
            case JCS_CMYK     :
1669
 
              sp->cinfo.d.comp_info[0].component_id = 'C';
1670
 
              sp->cinfo.d.comp_info[1].component_id = 'M';
1671
 
              sp->cinfo.d.comp_info[2].component_id = 'Y';
1672
 
              sp->cinfo.d.comp_info[3].component_id = 'K';
1673
 
              i = 0;
1674
 
              do sp->cinfo.d.comp_info[i].h_samp_factor =
1675
 
                 sp->cinfo.d.comp_info[i].v_samp_factor = 1;
1676
 
              while (++i < sp->cinfo.d.num_components);
1677
 
              break;
1678
 
            case JCS_YCbCr    :
1679
 
              i = 0;
1680
 
              do
1681
 
                {
1682
 
                  sp->cinfo.d.comp_info[i].component_id = i+1;
1683
 
                  sp->cinfo.d.comp_info[i].h_samp_factor =
1684
 
                  sp->cinfo.d.comp_info[i].v_samp_factor = 1;
1685
 
                  sp->cinfo.d.comp_info[i].quant_tbl_no =
1686
 
                  sp->cinfo.d.comp_info[i].dc_tbl_no =
1687
 
                  sp->cinfo.d.comp_info[i].ac_tbl_no = i > 0;
1688
 
                }
1689
 
              while (++i < sp->cinfo.d.num_components);
1690
 
              sp->cinfo.d.comp_info[0].h_samp_factor = sp->h_sampling;
1691
 
              sp->cinfo.d.comp_info[0].v_samp_factor = sp->v_sampling;
1692
 
          };
1693
 
        sp->cinfo.d.comps_in_scan = td->td_planarconfig == PLANARCONFIG_CONTIG
1694
 
                                  ? sp->cinfo.d.num_components
1695
 
                                  : 1;
1696
 
        i = CALLJPEG(sp,-1,jpeg_read_header(&sp->cinfo.d,!sp->is_WANG));
1697
 
        sp->cinfo.d.marker->read_markers = save; /* Restore input method */
1698
 
        if (sp->is_WANG) /* produced by Wang Imaging on Microsoft Windows */
1699
 
          {
1700
 
            if (i != JPEG_SUSPENDED) return 0;
1701
 
 
1702
 
         /* BOGOSITY ALERT!  Files prooduced by the Wang Imaging application for
1703
 
                             Microsoft Windows are a special--and, technically
1704
 
            illegal--case.  A JPEG SOS marker and rest of the data stream should
1705
 
            be located at the end of the file, in a position identified by the
1706
 
            0th Strip offset.
1707
 
         */
1708
 
            i = td->td_nstrips - 1;
1709
 
            sp->src.next_input_byte = tif->tif_base + td->td_stripoffset[0];
1710
 
            sp->src.bytes_in_buffer = td->td_stripoffset[i] -
1711
 
              td->td_stripoffset[0] + td->td_stripbytecount[i];
1712
 
            i = CALLJPEG(sp,-1,jpeg_read_header(&sp->cinfo.d,TRUE));
1713
 
          };
1714
 
        if (i != JPEG_HEADER_OK) return 0;
1715
 
      };
1716
 
 
1717
 
 /* Some of our initialization must wait until the JPEG Library is initialized
1718
 
    above, in order to override its defaults.
1719
 
 */
1720
 
    if (   (sp->cinfo.d.raw_data_out = downsampled_output)
1721
 
        && !alloc_downsampled_buffers(tif,sp->cinfo.d.comp_info,
1722
 
                                      sp->cinfo.d.num_components)
1723
 
       ) return 0;
1724
 
    sp->cinfo.d.jpeg_color_space = jpeg_color_space;
1725
 
    sp->cinfo.d.out_color_space = out_color_space;
1726
 
    sp->cinfo.d.dither_mode = JDITHER_NONE; /* Reduce image "noise" */
1727
 
    sp->cinfo.d.two_pass_quantize = FALSE;
1728
 
 
1729
 
 /* If the image consists of separate, discontiguous TIFF "samples" (= color
1730
 
    planes, hopefully = JPEG "scans"), then we must use the JPEG Library's
1731
 
    "buffered image" mode to decompress the entire image into temporary buffers,
1732
 
    because the JPEG Library must parse the entire JPEG bit-stream in order to
1733
 
    be satsified that it has a complete set of color components for each pixel,
1734
 
    but the TIFF Library must allow our client to extract 1 component at a time.
1735
 
    Initializing the JPEG Library's "buffered image" mode is tricky:  First, we
1736
 
    start its decompressor, then we tell the decompressor to "consume" (i.e.,
1737
 
    buffer) the entire bit-stream.
1738
 
 
1739
 
    WARNING:  Disabling "fancy" up-sampling seems to slightly reduce "noise" for
1740
 
              certain old Wang Imaging files, but it absolutely *must* be
1741
 
    enabled if the image has separate color planes, since in that case, the JPEG
1742
 
    Library doesn't use an "sp->cinfo.d.cconvert" structure (so de-referencing
1743
 
    this pointer below will cause a fatal crash) but writing our own code to up-
1744
 
    sample separate color planes is too much work for right now.  Maybe someday?
1745
 
 */
1746
 
    sp->cinfo.d.do_fancy_upsampling = /* Always let this default (to TRUE)? */
1747
 
    sp->cinfo.d.buffered_image = td->td_planarconfig == PLANARCONFIG_SEPARATE;
1748
 
    if (!CALLJPEG(sp,0,jpeg_start_decompress(&sp->cinfo.d))) return 0;
1749
 
    if (sp->cinfo.d.buffered_image) /* separate color planes */
1750
 
      {
1751
 
        if (sp->cinfo.d.raw_data_out)
1752
 
          tif->tif_decoderow = tif->tif_decodestrip = tif->tif_decodetile =
1753
 
            OJPEGDecodeRawSeparate;
1754
 
        else
1755
 
          {
1756
 
            tif->tif_decoderow = tif->tif_decodestrip = tif->tif_decodetile =
1757
 
              OJPEGDecode;
1758
 
 
1759
 
         /* In JPEG Library Version 6B, color-space conversion isn't implemented
1760
 
            for separate color planes, so we must do it ourself if our TIFF
1761
 
            client doesn't want to:
1762
 
         */
1763
 
            sp->cinfo.d.cconvert->color_convert =
1764
 
              sp->cinfo.d.jpeg_color_space == sp->cinfo.d.out_color_space
1765
 
              ? null_convert : ycc_rgb_convert;
1766
 
          };
1767
 
    L3: switch (CALLJPEG(sp,0,jpeg_consume_input(&sp->cinfo.d)))
1768
 
          {
1769
 
            default              : goto L3;
1770
 
 
1771
 
         /* If no JPEG "End of Information" (EOI) marker is found when bit-
1772
 
            stream parsing ends, check whether we have enough data to proceed
1773
 
            before reporting an error.
1774
 
         */
1775
 
            case JPEG_SUSPENDED  : if (  sp->cinfo.d.input_scan_number
1776
 
                                        *sp->cinfo.d.image_height
1777
 
                                       + sp->cinfo.d.input_iMCU_row
1778
 
                                        *sp->cinfo.d.max_v_samp_factor
1779
 
#                                       ifdef D_LOSSLESS_SUPPORTED
1780
 
                                        *sp->cinfo.d.data_units_in_MCU
1781
 
                                        *sp->cinfo.d.min_codec_data_unit
1782
 
#                                       else
1783
 
                                        *sp->cinfo.d.blocks_in_MCU
1784
 
                                        *DCTSIZE
1785
 
#                                       endif
1786
 
                                      < td->td_samplesperpixel
1787
 
                                       *sp->cinfo.d.image_height
1788
 
                                      )
1789
 
                                     {
1790
 
                                       TIFFError(tif->tif_name,
1791
 
                                         "Premature end of JPEG bit-stream");
1792
 
                                       return 0;
1793
 
                                     }
1794
 
            case JPEG_REACHED_EOI: ;
1795
 
          }
1796
 
      }
1797
 
    else /* pixel-interleaved color planes */
1798
 
      tif->tif_decoderow = tif->tif_decodestrip = tif->tif_decodetile =
1799
 
        downsampled_output ? OJPEGDecodeRawContig : OJPEGDecode;
1800
 
    return 1;
1801
 
#   undef td
1802
 
  }
1803
 
 
1804
 
static int
1805
 
OJPEGPreDecode(register TIFF *tif,tsample_t s)
1806
 
  { register OJPEGState *sp = OJState(tif);
1807
 
#   define td (&tif->tif_dir)
1808
 
 
1809
 
 /* If we are about to read the first row of an image plane (hopefully, these
1810
 
    are coincident with JPEG "scans"!), reset the JPEG Library's decompressor
1811
 
    appropriately.  Otherwise, let the decompressor run "as is" and return a
1812
 
    "success" status without further ado.
1813
 
 */
1814
 
    if (     (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip)
1815
 
           % td->td_stripsperimage
1816
 
        == 0
1817
 
       )
1818
 
      {
1819
 
        if (   sp->cinfo.d.buffered_image
1820
 
            && !CALLJPEG(sp,0,jpeg_start_output(&sp->cinfo.d,s+1))
1821
 
           ) return 0;
1822
 
        sp->cinfo.d.output_scanline = 0;
1823
 
 
1824
 
     /* Mark subsampling buffers "empty". */
1825
 
 
1826
 
#       ifdef D_LOSSLESS_SUPPORTED
1827
 
        sp->scancount = sp->cinfo.d.min_codec_data_unit;
1828
 
#       else
1829
 
        sp->scancount = DCTSIZE;
1830
 
#       endif
1831
 
      };
1832
 
    return 1;
1833
 
#   undef td
1834
 
  }
1835
 
 
1836
 
/*ARGSUSED*/ static void
1837
 
OJPEGPostDecode(register TIFF *tif,tidata_t buf,tsize_t cc)
1838
 
  { register OJPEGState *sp = OJState(tif);
1839
 
#   define td (&tif->tif_dir)
1840
 
 
1841
 
 /* The JPEG Library decompressor has reached the end of a strip/tile.  If this
1842
 
    is the end of a TIFF image "sample" (= JPEG "scan") in a file with separate
1843
 
    components (color planes), then end the "scan".  If it ends the image's last
1844
 
    sample/scan, then also stop the JPEG Library's decompressor.
1845
 
 */
1846
 
    if (sp->cinfo.d.output_scanline >= sp->cinfo.d.output_height)
1847
 
      {
1848
 
        if (sp->cinfo.d.buffered_image)
1849
 
          CALLJPEG(sp,-1,jpeg_finish_output(&sp->cinfo.d)); /* End JPEG scan */
1850
 
        if (   (isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip)
1851
 
            >= td->td_nstrips-1
1852
 
           ) CALLJPEG(sp,0,jpeg_finish_decompress(&sp->cinfo.d));
1853
 
      }
1854
 
#   undef td
1855
 
  }
1856
 
 
1857
 
static int
1858
 
OJPEGVSetField(register TIFF *tif,ttag_t tag,va_list ap)
1859
 
{
1860
 
    uint32 v32;
1861
 
    register OJPEGState *sp = OJState(tif);
1862
 
#   define td (&tif->tif_dir)
1863
 
    toff_t tiffoff=0;
1864
 
    uint32 bufoff=0;
1865
 
    uint32 code_count=0;
1866
 
    int i2=0;
1867
 
    int k2=0;
1868
 
 
1869
 
    switch (tag)
1870
 
      {
1871
 
 
1872
 
     /* If a "ReferenceBlackWhite" TIFF tag appears in the file explicitly, undo
1873
 
        any modified default definition that we might have installed below, then
1874
 
        install the real one.
1875
 
     */
1876
 
        case TIFFTAG_REFERENCEBLACKWHITE   : if (td->td_refblackwhite)
1877
 
                                               {
1878
 
                                                 _TIFFfree(td->td_refblackwhite);
1879
 
                                                 td->td_refblackwhite = 0;
1880
 
                                               };
1881
 
        default                            : return
1882
 
                                               (*sp->vsetparent)(tif,tag,ap);
1883
 
 
1884
 
     /* BEWARE OF KLUDGE:  Some old-format JPEG-in-TIFF files, including those
1885
 
                           produced by the Wang Imaging application for Micro-
1886
 
        soft Windows, illegally omit a "ReferenceBlackWhite" TIFF tag, even
1887
 
        though the TIFF specification's default is intended for the RGB color
1888
 
        space and is inappropriate for the YCbCr color space ordinarily used for
1889
 
        JPEG images.  Since many TIFF client applications request the value of
1890
 
        this tag immediately after a TIFF image directory is parsed, and before
1891
 
        any other code in this module receives control, we are forced to fix
1892
 
        this problem very early in image-file processing.  Fortunately, legal
1893
 
        TIFF files are supposed to store their tags in numeric order, so a
1894
 
        mandatory "PhotometricInterpretation" tag should always appear before
1895
 
        an optional "ReferenceBlackWhite" tag.  Hence, we slyly peek ahead when
1896
 
        we discover the desired photometry, by installing modified black and
1897
 
        white reference levels.
1898
 
     */
1899
 
        case TIFFTAG_PHOTOMETRIC           :
1900
 
          if (   (v32 = (*sp->vsetparent)(tif,tag,ap))
1901
 
              && td->td_photometric == PHOTOMETRIC_YCBCR
1902
 
             )
1903
 
          {
1904
 
            if ( (td->td_refblackwhite = _TIFFmalloc(6*sizeof(float))) )
1905
 
              { register long top = 1 << td->td_bitspersample;
1906
 
 
1907
 
                td->td_refblackwhite[0] = 0;
1908
 
                td->td_refblackwhite[1] = td->td_refblackwhite[3] =
1909
 
                td->td_refblackwhite[5] = top - 1;
1910
 
                td->td_refblackwhite[2] = td->td_refblackwhite[4] = top >> 1;
1911
 
              }
1912
 
            else
1913
 
              {
1914
 
                TIFFError(tif->tif_name,
1915
 
                  "Cannot set default reference black and white levels");
1916
 
                v32 = 0;
1917
 
              };
1918
 
          }
1919
 
          return v32;
1920
 
 
1921
 
     /* BEWARE OF KLUDGE:  According to Charles Auer <Bumble731@msn.com>, if our
1922
 
                           input is a multi-image (multi-directory) JPEG-in-TIFF
1923
 
        file is produced by the Wang Imaging application on Microsoft Windows,
1924
 
        for some reason the first directory excludes the vendor-specific "WANG
1925
 
        PageControl" tag (32934) that we check below, so the only other way to
1926
 
        identify these directories is apparently to look for a software-
1927
 
        identification tag with the substring, "Wang Labs".  Single-image files
1928
 
        can apparently pass both tests, which causes no harm here, but what a
1929
 
        mess this is!
1930
 
     */
1931
 
        case TIFFTAG_SOFTWARE              :
1932
 
        {
1933
 
            char *software;
1934
 
 
1935
 
            v32 = (*sp->vsetparent)(tif,tag,ap);
1936
 
            if( TIFFGetField( tif, TIFFTAG_SOFTWARE, &software )
1937
 
                && strstr( software, "Wang Labs" ) )
1938
 
                sp->is_WANG = 1;
1939
 
            return v32;
1940
 
        }
1941
 
 
1942
 
        case TIFFTAG_JPEGPROC              :
1943
 
        case TIFFTAG_JPEGIFOFFSET          :
1944
 
        case TIFFTAG_JPEGIFBYTECOUNT       :
1945
 
        case TIFFTAG_JPEGRESTARTINTERVAL   :
1946
 
        case TIFFTAG_JPEGLOSSLESSPREDICTORS:
1947
 
        case TIFFTAG_JPEGPOINTTRANSFORM    :
1948
 
        case TIFFTAG_JPEGQTABLES           :
1949
 
        case TIFFTAG_JPEGDCTABLES          :
1950
 
        case TIFFTAG_JPEGACTABLES          :
1951
 
        case TIFFTAG_WANG_PAGECONTROL      :
1952
 
        case TIFFTAG_JPEGCOLORMODE         : ;
1953
 
      };
1954
 
    v32 = va_arg(ap,uint32); /* No. of values in this TIFF record */
1955
 
 
1956
 
    /* This switch statement is added for OJPEGVSetField */
1957
 
    if(v32 !=0){
1958
 
        switch(tag){
1959
 
            case TIFFTAG_JPEGPROC:
1960
 
                sp->jpegproc=v32;
1961
 
                break;
1962
 
            case TIFFTAG_JPEGIFOFFSET:
1963
 
                sp->jpegifoffset=v32;
1964
 
                break;
1965
 
            case TIFFTAG_JPEGIFBYTECOUNT:
1966
 
                sp->jpegifbytecount=v32;
1967
 
                break;
1968
 
            case TIFFTAG_JPEGRESTARTINTERVAL:
1969
 
                sp->jpegrestartinterval=v32;
1970
 
                break;
1971
 
            case TIFFTAG_JPEGLOSSLESSPREDICTORS:
1972
 
                sp->jpeglosslesspredictors_length=v32;
1973
 
                break;
1974
 
            case TIFFTAG_JPEGPOINTTRANSFORM:
1975
 
                sp->jpegpointtransform_length=v32;
1976
 
                break;
1977
 
            case TIFFTAG_JPEGQTABLES:
1978
 
                sp->jpegqtables_length=v32;
1979
 
                break;
1980
 
            case TIFFTAG_JPEGACTABLES:
1981
 
                sp->jpegactables_length=v32;
1982
 
                break;
1983
 
            case TIFFTAG_JPEGDCTABLES:
1984
 
                sp->jpegdctables_length=v32;
1985
 
                break;
1986
 
            default:
1987
 
                break;
1988
 
        }
1989
 
    }
1990
 
 
1991
 
 /* BEWARE:  The following actions apply only if we are reading a "source" TIFF
1992
 
             image to be decompressed for a client application program.  If we
1993
 
    ever enhance this file's CODEC to write "destination" JPEG-in-TIFF images,
1994
 
    we'll need an "if"- and another "switch"-statement below, because we'll
1995
 
    probably want to store these records' values in some different places.  Most
1996
 
    of these need not be parsed here in order to decode JPEG bit stream, so we
1997
 
    set boolean flags to note that they have been seen, but we otherwise ignore
1998
 
    them.
1999
 
 */
2000
 
    switch (tag)
2001
 
      { JHUFF_TBL **h;
2002
 
 
2003
 
     /* Validate the JPEG-process code. */
2004
 
 
2005
 
        case TIFFTAG_JPEGPROC              :
2006
 
          switch (v32)
2007
 
            {
2008
 
              default               : TIFFError(tif->tif_name,
2009
 
                                        "Unknown JPEG process");
2010
 
                                      return 0;
2011
 
#             ifdef C_LOSSLESS_SUPPORTED
2012
 
 
2013
 
           /* Image uses (lossy) baseline sequential coding. */
2014
 
 
2015
 
              case JPEGPROC_BASELINE: sp->cinfo.d.process = JPROC_SEQUENTIAL;
2016
 
                                      sp->cinfo.d.data_unit = DCTSIZE;
2017
 
                                      break;
2018
 
 
2019
 
           /* Image uses (lossless) Huffman coding. */
2020
 
 
2021
 
              case JPEGPROC_LOSSLESS: sp->cinfo.d.process = JPROC_LOSSLESS;
2022
 
                                      sp->cinfo.d.data_unit = 1;
2023
 
#             else /* not C_LOSSLESS_SUPPORTED */
2024
 
              case JPEGPROC_LOSSLESS: TIFFError(JPEGLib_name,
2025
 
                                        "Does not support lossless Huffman coding");
2026
 
                                      return 0;
2027
 
              case JPEGPROC_BASELINE: ;
2028
 
#             endif /* C_LOSSLESS_SUPPORTED */
2029
 
            };
2030
 
          break;
2031
 
 
2032
 
     /* The TIFF Version 6.0 specification says that if the value of a TIFF
2033
 
        "JPEGInterchangeFormat" record is 0, then we are to behave as if this
2034
 
        record were absent; i.e., the data does *not* represent a JPEG Inter-
2035
 
        change Format File (JFIF), so don't even set the boolean "I've been
2036
 
        here" flag below.  Otherwise, the field's value represents the file
2037
 
        offset of the JPEG SOI marker.
2038
 
     */
2039
 
        case TIFFTAG_JPEGIFOFFSET          :
2040
 
          if (v32)
2041
 
            {
2042
 
              sp->src.next_input_byte = tif->tif_base + v32;
2043
 
              break;
2044
 
            };
2045
 
          return 1;
2046
 
        case TIFFTAG_JPEGIFBYTECOUNT       :
2047
 
          sp->src.bytes_in_buffer = v32;
2048
 
          break;
2049
 
 
2050
 
     /* The TIFF Version 6.0 specification says that if the JPEG "Restart"
2051
 
        marker interval is 0, then the data has no "Restart" markers; i.e., we
2052
 
        must behave as if this TIFF record were absent.  So, don't even set the
2053
 
        boolean "I've been here" flag below.
2054
 
     */
2055
 
     /*
2056
 
      * Instead, set the field bit so TIFFGetField can get whether or not
2057
 
      * it was set.
2058
 
      */
2059
 
        case TIFFTAG_JPEGRESTARTINTERVAL   :
2060
 
          if (v32)
2061
 
              sp->cinfo.d.restart_interval = v32;
2062
 
              break;
2063
 
     /* The TIFF Version 6.0 specification says that this tag is supposed to be
2064
 
        a vector containing a value for each image component, but for lossless
2065
 
        Huffman coding (the only JPEG process defined by the specification for
2066
 
        which this tag should be needed), ISO IS 10918-1 uses only a single
2067
 
        value, equivalent to the "Ss" field in a JPEG bit-stream's "Start of
2068
 
        Scan" (SOS) marker.  So, we extract the first vector element and ignore
2069
 
        the rest.  (I hope this is correct!)
2070
 
     */
2071
 
        case TIFFTAG_JPEGLOSSLESSPREDICTORS:
2072
 
           if (v32)
2073
 
             {
2074
 
               sp->cinfo.d.Ss = *va_arg(ap,uint16 *);
2075
 
               sp->jpeglosslesspredictors = 
2076
 
                    _TIFFmalloc(sp->jpeglosslesspredictors_length
2077
 
                                * sizeof(uint16));
2078
 
               if(sp->jpeglosslesspredictors==NULL){return(0);}
2079
 
               for(i2=0;i2<sp->jpeglosslesspredictors_length;i2++){
2080
 
                ((uint16*)sp->jpeglosslesspredictors)[i2] =
2081
 
                        ((uint16*)sp->cinfo.d.Ss)[i2];
2082
 
               }
2083
 
               sp->jpeglosslesspredictors_length*=sizeof(uint16);
2084
 
               break;
2085
 
             };
2086
 
           return v32;
2087
 
 
2088
 
     /* The TIFF Version 6.0 specification says that this tag is supposed to be
2089
 
        a vector containing a value for each image component, but for lossless
2090
 
        Huffman coding (the only JPEG process defined by the specification for
2091
 
        which this tag should be needed), ISO IS 10918-1 uses only a single
2092
 
        value, equivalent to the "Al" field in a JPEG bit-stream's "Start of
2093
 
        Scan" (SOS) marker.  So, we extract the first vector element and ignore
2094
 
        the rest.  (I hope this is correct!)
2095
 
     */
2096
 
        case TIFFTAG_JPEGPOINTTRANSFORM    :
2097
 
           if (v32)
2098
 
             {
2099
 
               sp->cinfo.d.Al = *va_arg(ap,uint16 *);
2100
 
               sp->jpegpointtransform =
2101
 
                    _TIFFmalloc(sp->jpegpointtransform_length*sizeof(uint16));
2102
 
               if(sp->jpegpointtransform==NULL){return(0);}
2103
 
               for(i2=0;i2<sp->jpegpointtransform_length;i2++) {
2104
 
                ((uint16*)sp->jpegpointtransform)[i2] =
2105
 
                        ((uint16*)sp->cinfo.d.Al)[i2];
2106
 
               }
2107
 
               sp->jpegpointtransform_length*=sizeof(uint16);
2108
 
               break;
2109
 
             }
2110
 
           return v32;
2111
 
 
2112
 
     /* We have a vector of offsets to quantization tables, so load 'em! */
2113
 
 
2114
 
        case TIFFTAG_JPEGQTABLES           :
2115
 
          if (v32)
2116
 
            { uint32 *v;
2117
 
              int i;
2118
 
              if (v32 > NUM_QUANT_TBLS)
2119
 
                {
2120
 
                  TIFFError(tif->tif_name,"Too many quantization tables");
2121
 
                  return 0;
2122
 
                };
2123
 
              i = 0;
2124
 
              v = va_arg(ap,uint32 *);
2125
 
                sp->jpegqtables=_TIFFmalloc(64*sp->jpegqtables_length);
2126
 
                if(sp->jpegqtables==NULL){return(0);}
2127
 
                tiffoff = TIFFSeekFile(tif, 0, SEEK_CUR);
2128
 
                bufoff=0;
2129
 
                for(i2=0;i2<sp->jpegqtables_length;i2++){
2130
 
                    TIFFSeekFile(tif, v[i2], SEEK_SET);
2131
 
                    TIFFReadFile(tif, &(((u_char*)(sp->jpegqtables))[bufoff]),
2132
 
                                 64);
2133
 
                    bufoff+=64;
2134
 
                }
2135
 
                sp->jpegqtables_length=bufoff;
2136
 
                TIFFSeekFile(tif, tiffoff, SEEK_SET);
2137
 
 
2138
 
              do /* read quantization table */
2139
 
                { register UINT8 *from = tif->tif_base + *v++;
2140
 
                  register UINT16 *to;
2141
 
                  register int j = DCTSIZE2;
2142
 
 
2143
 
                  if (!( sp->cinfo.d.quant_tbl_ptrs[i]
2144
 
                       = CALLJPEG(sp,0,jpeg_alloc_quant_table(&sp->cinfo.comm))
2145
 
                       )
2146
 
                     )
2147
 
                    {
2148
 
                      TIFFError(JPEGLib_name,"No space for quantization table");
2149
 
                      return 0;
2150
 
                    };
2151
 
                  to = sp->cinfo.d.quant_tbl_ptrs[i]->quantval;
2152
 
                  do *to++ = *from++; while (--j > 0);
2153
 
                }
2154
 
              while (++i < v32);
2155
 
              sp->jpegtablesmode |= JPEGTABLESMODE_QUANT;
2156
 
            };
2157
 
          break;
2158
 
 
2159
 
     /* We have a vector of offsets to DC Huffman tables, so load 'em! */
2160
 
 
2161
 
        case TIFFTAG_JPEGDCTABLES          :
2162
 
          h = sp->cinfo.d.dc_huff_tbl_ptrs;
2163
 
          goto L;
2164
 
 
2165
 
     /* We have a vector of offsets to AC Huffman tables, so load 'em! */
2166
 
 
2167
 
        case TIFFTAG_JPEGACTABLES          :
2168
 
          h = sp->cinfo.d.ac_huff_tbl_ptrs;
2169
 
       L: if (v32)
2170
 
            { uint32 *v;
2171
 
              int i;
2172
 
              if (v32 > NUM_HUFF_TBLS)
2173
 
                {
2174
 
                  TIFFError(tif->tif_name,"Too many Huffman tables");
2175
 
                  return 0;
2176
 
                };
2177
 
              v = va_arg(ap,uint32 *);
2178
 
                if(tag == TIFFTAG_JPEGDCTABLES) {
2179
 
                    sp->jpegdctables=_TIFFmalloc(272*sp->jpegdctables_length);
2180
 
                    if(sp->jpegdctables==NULL){return(0);}
2181
 
                    tiffoff = TIFFSeekFile(tif, 0, SEEK_CUR);
2182
 
                    bufoff=0;
2183
 
                    code_count=0;                
2184
 
                    for(i2=0;i2<sp->jpegdctables_length;i2++){
2185
 
                        TIFFSeekFile(tif, v[i2], SEEK_SET);
2186
 
                        TIFFReadFile(tif,
2187
 
                                     &(((u_char*)(sp->jpegdctables))[bufoff]),
2188
 
                                     16);
2189
 
                        code_count=0;
2190
 
                        for(k2=0;k2<16;k2++){
2191
 
                            code_count+=((u_char*)(sp->jpegdctables))[k2+bufoff];
2192
 
                        }
2193
 
                        TIFFReadFile(tif,
2194
 
                                     &(((u_char*)(sp->jpegdctables))[bufoff+16]),
2195
 
                                     code_count);
2196
 
                        bufoff+=16;
2197
 
                        bufoff+=code_count;
2198
 
                    }
2199
 
                    sp->jpegdctables_length=bufoff;
2200
 
                    TIFFSeekFile(tif, tiffoff, SEEK_SET);
2201
 
                }
2202
 
                if(tag==TIFFTAG_JPEGACTABLES){
2203
 
                    sp->jpegactables=_TIFFmalloc(272*sp->jpegactables_length);
2204
 
                    if(sp->jpegactables==NULL){return(0);}
2205
 
                    tiffoff = TIFFSeekFile(tif, 0, SEEK_CUR);
2206
 
                    bufoff=0;
2207
 
                    code_count=0;                
2208
 
                    for(i2=0;i2<sp->jpegactables_length;i2++){
2209
 
                        TIFFSeekFile(tif, v[i2], SEEK_SET);
2210
 
                        TIFFReadFile(tif, &(((unsigned char*)(sp->jpegactables))[bufoff]), 16);
2211
 
                        code_count=0;
2212
 
                        for(k2=0;k2<16;k2++){
2213
 
                            code_count+=((unsigned char*)(sp->jpegactables))[k2+bufoff];
2214
 
                        }
2215
 
                        TIFFReadFile(tif, &(((unsigned char*)(sp->jpegactables))[bufoff+16]), code_count);
2216
 
                        bufoff+=16;
2217
 
                        bufoff+=code_count;
2218
 
                    }
2219
 
                    sp->jpegactables_length=bufoff;
2220
 
                    TIFFSeekFile(tif, tiffoff, SEEK_SET);
2221
 
                }
2222
 
              i = 0;
2223
 
              do /* copy each Huffman table */
2224
 
                { int size = 0;
2225
 
                  register UINT8 *from = tif->tif_base + *v++, *to;
2226
 
                  register int j = sizeof (*h)->bits;
2227
 
 
2228
 
               /* WARNING:  This code relies on the fact that an image file not
2229
 
                            "memory mapped" was read entirely into a single
2230
 
                  buffer by "TIFFInitOJPEG()", so we can do a fast memory-to-
2231
 
                  memory copy here.  Each table consists of 16 Bytes, which are
2232
 
                  suffixed to a 0 Byte when copied, followed by a variable
2233
 
                  number of Bytes whose length is the sum of the first 16.
2234
 
               */
2235
 
                  if (!( *h
2236
 
                       = CALLJPEG(sp,0,jpeg_alloc_huff_table(&sp->cinfo.comm))
2237
 
                       )
2238
 
                     )
2239
 
                    {
2240
 
                      TIFFError(JPEGLib_name,"No space for Huffman table");
2241
 
                      return 0;
2242
 
                    };
2243
 
                  to = (*h++)->bits;
2244
 
                  *to++ = 0;
2245
 
                  while (--j > 0) size += *to++ = *from++; /* Copy 16 Bytes */
2246
 
                  if (size > sizeof (*h)->huffval/sizeof *(*h)->huffval)
2247
 
                    {
2248
 
                      TIFFError(tif->tif_name,"Huffman table too big");
2249
 
                      return 0;
2250
 
                    };
2251
 
                  if ((j = size) > 0) do *to++ = *from++; while (--j > 0);
2252
 
                  while (++size <= sizeof (*h)->huffval/sizeof *(*h)->huffval)
2253
 
                    *to++ = 0; /* Zero the rest of the table for cleanliness */
2254
 
                }
2255
 
              while (++i < v32);
2256
 
              sp->jpegtablesmode |= JPEGTABLESMODE_HUFF;
2257
 
            };
2258
 
          break;
2259
 
 
2260
 
     /* The following vendor-specific TIFF tag occurs in (highly illegal) files
2261
 
        produced by the Wang Imaging application for Microsoft Windows.  These
2262
 
        can apparently have several "pages", in which case this tag specifies
2263
 
        the offset of a "page control" structure, which we don't currently know
2264
 
        how to handle.  0 indicates a 1-page image with no "page control", which
2265
 
        we make a feeble effort to handle.
2266
 
     */
2267
 
        case TIFFTAG_WANG_PAGECONTROL      :
2268
 
          if (v32 == 0) v32 = -1;
2269
 
          sp->is_WANG = v32;
2270
 
          tag = TIFFTAG_JPEGPROC+FIELD_WANG_PAGECONTROL-FIELD_JPEGPROC;
2271
 
          break;
2272
 
 
2273
 
     /* This pseudo tag indicates whether our caller is expected to do YCbCr <->
2274
 
        RGB color-space conversion (JPEGCOLORMODE_RAW <=> 0) or whether we must
2275
 
        ask the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1).
2276
 
     */
2277
 
        case TIFFTAG_JPEGCOLORMODE         :
2278
 
          sp->jpegcolormode = v32;
2279
 
 
2280
 
       /* Mark the image to indicate whether returned data is up-sampled, so
2281
 
          that "TIFF{Strip,Tile}Size()" reflect the true amount of data present.
2282
 
       */
2283
 
          v32 = tif->tif_flags; /* Save flags temporarily */
2284
 
          tif->tif_flags &= ~TIFF_UPSAMPLED;
2285
 
          if (   td->td_photometric == PHOTOMETRIC_YCBCR
2286
 
              &&    (td->td_ycbcrsubsampling[0]<<3 | td->td_ycbcrsubsampling[1])
2287
 
                 != 011
2288
 
              && sp->jpegcolormode == JPEGCOLORMODE_RGB
2289
 
             ) tif->tif_flags |= TIFF_UPSAMPLED;
2290
 
 
2291
 
       /* If the up-sampling state changed, re-calculate tile size. */
2292
 
 
2293
 
          if ((tif->tif_flags ^ v32) & TIFF_UPSAMPLED)
2294
 
            {
2295
 
              tif->tif_tilesize = TIFFTileSize(tif);
2296
 
              tif->tif_flags |= TIFF_DIRTYDIRECT;
2297
 
            };
2298
 
          return 1;
2299
 
      };
2300
 
    TIFFSetFieldBit(tif,tag-TIFFTAG_JPEGPROC+FIELD_JPEGPROC);
2301
 
    return 1;
2302
 
#   undef td
2303
 
  }
2304
 
 
2305
 
static int
2306
 
OJPEGVGetField(register TIFF *tif,ttag_t tag,va_list ap)
2307
 
  { register OJPEGState *sp = OJState(tif);
2308
 
 
2309
 
    switch (tag)
2310
 
      {
2311
 
 
2312
 
     /* If this file has managed to synthesize a set of consolidated "metadata"
2313
 
        tables for the current (post-TIFF Version 6.0 specification) JPEG-in-
2314
 
        TIFF encapsulation strategy, then tell our caller about them; otherwise,
2315
 
        keep mum.
2316
 
     */
2317
 
        case TIFFTAG_JPEGTABLES            :
2318
 
          if (sp->jpegtables_length) /* we have "new"-style JPEG tables */
2319
 
            {
2320
 
              *va_arg(ap,uint32 *) = sp->jpegtables_length;
2321
 
              *va_arg(ap,char **) = sp->jpegtables;
2322
 
              return 1;
2323
 
            };
2324
 
 
2325
 
     /* This pseudo tag indicates whether our caller is expected to do YCbCr <->
2326
 
        RGB color-space conversion (JPEGCOLORMODE_RAW <=> 0) or whether we must
2327
 
        ask the JPEG Library to do it (JPEGCOLORMODE_RGB <=> 1).
2328
 
     */
2329
 
        case TIFFTAG_JPEGCOLORMODE         :
2330
 
          *va_arg(ap,uint32 *) = sp->jpegcolormode;
2331
 
          return 1;
2332
 
 
2333
 
     /* The following tags are defined by the TIFF Version 6.0 specification
2334
 
        and are obsolete.  If our caller asks for information about them, do not
2335
 
        return anything, even if we parsed them in an old-format "source" image.
2336
 
     */
2337
 
        case TIFFTAG_JPEGPROC              :
2338
 
                *va_arg(ap, uint16*)=sp->jpegproc;
2339
 
                return(1);
2340
 
                break;
2341
 
        case TIFFTAG_JPEGIFOFFSET          :
2342
 
                *va_arg(ap, uint32*)=sp->jpegifoffset;
2343
 
                return(1);
2344
 
                break;
2345
 
        case TIFFTAG_JPEGIFBYTECOUNT       :
2346
 
                *va_arg(ap, uint32*)=sp->jpegifbytecount;
2347
 
                return(1);
2348
 
                break;
2349
 
        case TIFFTAG_JPEGRESTARTINTERVAL   :
2350
 
                *va_arg(ap, uint32*)=sp->jpegrestartinterval;
2351
 
                return(1);
2352
 
                break;
2353
 
        case TIFFTAG_JPEGLOSSLESSPREDICTORS:
2354
 
                *va_arg(ap, uint32*)=sp->jpeglosslesspredictors_length;
2355
 
                *va_arg(ap, void**)=sp->jpeglosslesspredictors;
2356
 
                return(1);
2357
 
                break;
2358
 
        case TIFFTAG_JPEGPOINTTRANSFORM    :
2359
 
                *va_arg(ap, uint32*)=sp->jpegpointtransform_length;
2360
 
                *va_arg(ap, void**)=sp->jpegpointtransform;
2361
 
                return(1);
2362
 
                break;
2363
 
        case TIFFTAG_JPEGQTABLES           :
2364
 
                *va_arg(ap, uint32*)=sp->jpegqtables_length;
2365
 
                *va_arg(ap, void**)=sp->jpegqtables;
2366
 
                return(1);
2367
 
                break;
2368
 
        case TIFFTAG_JPEGDCTABLES          :
2369
 
                *va_arg(ap, uint32*)=sp->jpegdctables_length;
2370
 
                *va_arg(ap, void**)=sp->jpegdctables;
2371
 
                return(1);
2372
 
                break;
2373
 
        case TIFFTAG_JPEGACTABLES          : 
2374
 
                *va_arg(ap, uint32*)=sp->jpegactables_length;
2375
 
                *va_arg(ap, void**)=sp->jpegactables;
2376
 
                return(1);
2377
 
                break;
2378
 
      };
2379
 
    return (*sp->vgetparent)(tif,tag,ap);
2380
 
  }
2381
 
 
2382
 
static void
2383
 
OJPEGPrintDir(register TIFF *tif,FILE *fd,long flags)
2384
 
  { register OJPEGState *sp = OJState(tif);
2385
 
 
2386
 
    if (   ( flags
2387
 
           & (TIFFPRINT_JPEGQTABLES|TIFFPRINT_JPEGDCTABLES|TIFFPRINT_JPEGACTABLES)
2388
 
           )
2389
 
        && sp->jpegtables_length
2390
 
       )
2391
 
      fprintf(fd,"  JPEG Table Data: <present>, %lu bytes\n",
2392
 
        sp->jpegtables_length);
2393
 
  }
2394
 
 
2395
 
static uint32
2396
 
OJPEGDefaultStripSize(register TIFF *tif,register uint32 s)
2397
 
  { register OJPEGState *sp = OJState(tif);
2398
 
#   define td (&tif->tif_dir)
2399
 
 
2400
 
    if ((s = (*sp->defsparent)(tif,s)) < td->td_imagelength)
2401
 
      { register tsize_t size = sp->cinfo.comm.is_decompressor
2402
 
#                             ifdef D_LOSSLESS_SUPPORTED
2403
 
                              ? sp->cinfo.d.min_codec_data_unit
2404
 
#                             else
2405
 
                              ? DCTSIZE
2406
 
#                             endif
2407
 
#                             ifdef C_LOSSLESS_SUPPORTED
2408
 
                              : sp->cinfo.c.data_unit;
2409
 
#                             else
2410
 
                              : DCTSIZE;
2411
 
#                             endif
2412
 
 
2413
 
        size = TIFFroundup(size,16);
2414
 
        s = TIFFroundup(s,td->td_ycbcrsubsampling[1]*size);
2415
 
      };
2416
 
    return s;
2417
 
#   undef td
2418
 
  }
2419
 
 
2420
 
static void
2421
 
OJPEGDefaultTileSize(register TIFF *tif,register uint32 *tw,register uint32 *th)
2422
 
  { register OJPEGState *sp = OJState(tif);
2423
 
    register tsize_t size;
2424
 
#   define td (&tif->tif_dir)
2425
 
 
2426
 
    size = sp->cinfo.comm.is_decompressor
2427
 
#        ifdef D_LOSSLESS_SUPPORTED
2428
 
         ? sp->cinfo.d.min_codec_data_unit
2429
 
#        else
2430
 
         ? DCTSIZE
2431
 
#        endif
2432
 
#        ifdef C_LOSSLESS_SUPPORTED
2433
 
         : sp->cinfo.c.data_unit;
2434
 
#        else
2435
 
         : DCTSIZE;
2436
 
#        endif
2437
 
    size = TIFFroundup(size,16);
2438
 
    (*sp->deftparent)(tif,tw,th);
2439
 
    *tw = TIFFroundup(*tw,td->td_ycbcrsubsampling[0]*size);
2440
 
    *th = TIFFroundup(*th,td->td_ycbcrsubsampling[1]*size);
2441
 
#   undef td
2442
 
  }
2443
 
 
2444
 
static void
2445
 
OJPEGCleanUp(register TIFF *tif)
2446
 
  { register OJPEGState *sp;
2447
 
 
2448
 
    if ( (sp = OJState(tif)) )
2449
 
      {
2450
 
        CALLVJPEG(sp,jpeg_destroy(&sp->cinfo.comm)); /* Free JPEG Lib. vars. */
2451
 
        if (sp->jpegtables) {_TIFFfree(sp->jpegtables);sp->jpegtables=0;}
2452
 
        if (sp->jpeglosslesspredictors) {
2453
 
                _TIFFfree(sp->jpeglosslesspredictors);
2454
 
                sp->jpeglosslesspredictors = 0;
2455
 
        }
2456
 
        if (sp->jpegpointtransform) {
2457
 
                _TIFFfree(sp->jpegpointtransform);
2458
 
                sp->jpegpointtransform=0;
2459
 
        }
2460
 
        if (sp->jpegqtables) {_TIFFfree(sp->jpegqtables);sp->jpegqtables=0;}
2461
 
        if (sp->jpegactables) {_TIFFfree(sp->jpegactables);sp->jpegactables=0;}
2462
 
        if (sp->jpegdctables) {_TIFFfree(sp->jpegdctables);sp->jpegdctables=0;}
2463
 
     /* If the image file isn't "memory mapped" and we read it all into a
2464
 
        single, large memory buffer, free the buffer now.
2465
 
     */
2466
 
        if (!isMapped(tif) && tif->tif_base) /* free whole-file buffer */
2467
 
          {
2468
 
            _TIFFfree(tif->tif_base);
2469
 
            tif->tif_base = 0;
2470
 
            tif->tif_size = 0;
2471
 
          };
2472
 
        _TIFFfree(sp); /* Release local variables */
2473
 
        tif->tif_data = 0;
2474
 
      }
2475
 
  }
2476
 
 
2477
 
int
2478
 
TIFFInitOJPEG(register TIFF *tif,int scheme)
2479
 
  { register OJPEGState *sp;
2480
 
#   define td (&tif->tif_dir)
2481
 
#   ifndef never
2482
 
 
2483
 
 /* This module supports a decompression-only CODEC, which is intended strictly
2484
 
    for viewing old image files using the obsolete JPEG-in-TIFF encapsulation
2485
 
    specified by the TIFF Version 6.0 specification.  It does not, and never
2486
 
    should, support compression for new images.  If a client application asks us
2487
 
    to, refuse and complain loudly!
2488
 
 */
2489
 
    if (tif->tif_mode != O_RDONLY) return _notSupported(tif);
2490
 
#   endif /* never */
2491
 
    if (!isMapped(tif))
2492
 
      {
2493
 
 
2494
 
     /* BEWARE OF KLUDGE:  If our host operating-system doesn't let an image
2495
 
                           file be "memory mapped", then we want to read the
2496
 
        entire file into a single (possibly large) memory buffer as if it had
2497
 
        been "memory mapped".  Although this is likely to waste space, because
2498
 
        analysis of the file's content might cause parts of it to be read into
2499
 
        smaller buffers duplicatively, it appears to be the lesser of several
2500
 
        evils.  Very old JPEG-in-TIFF encapsulations aren't guaranteed to be
2501
 
        JFIF bit streams, or to have a TIFF "JPEGTables" record or much other
2502
 
        "metadata" to help us locate the decoding tables and entropy-coded data,
2503
 
        so we're likely do a lot of random-access grokking around, and we must
2504
 
        ultimately tell the JPEG Library to sequentially scan much of the file
2505
 
        anyway.  This is all likely to be easier if we use "brute force" to
2506
 
        read the entire file, once, and don't use incremental disc I/O.  If our
2507
 
        client application tries to process a file so big that we can't buffer
2508
 
        it entirely, then tough shit: we'll give up and exit!
2509
 
     */
2510
 
        if (!(tif->tif_base = _TIFFmalloc(tif->tif_size=TIFFGetFileSize(tif))))
2511
 
          {
2512
 
            TIFFError(tif->tif_name,"Cannot allocate file buffer");
2513
 
            return 0;
2514
 
          };
2515
 
        if (!SeekOK(tif,0) || !ReadOK(tif,tif->tif_base,tif->tif_size))
2516
 
          {
2517
 
            TIFFError(tif->tif_name,"Cannot read file");
2518
 
            return 0;
2519
 
          }
2520
 
      };
2521
 
 
2522
 
 /* Allocate storage for this module's per-file variables. */
2523
 
 
2524
 
    if (!(tif->tif_data = (tidata_t)_TIFFmalloc(sizeof *sp)))
2525
 
      {
2526
 
        TIFFError("TIFFInitOJPEG","No space for JPEG state block");
2527
 
        return 0;
2528
 
      };
2529
 
    (sp = OJState(tif))->tif = tif; /* Initialize reverse pointer */
2530
 
    sp->cinfo.d.err = jpeg_std_error(&sp->err); /* Initialize error handling */
2531
 
    sp->err.error_exit = TIFFojpeg_error_exit;
2532
 
    sp->err.output_message = TIFFojpeg_output_message;
2533
 
    if (!CALLVJPEG(sp,jpeg_create_decompress(&sp->cinfo.d))) return 0;
2534
 
 
2535
 
 /* Install CODEC-specific tag information and override default TIFF Library
2536
 
    "method" subroutines with our own, CODEC-specific methods.  Like all good
2537
 
    members of an object-class, we save some of these subroutine pointers for
2538
 
    "fall back" in case our own methods fail.
2539
 
 */
2540
 
    _TIFFMergeFieldInfo(tif,ojpegFieldInfo,
2541
 
      sizeof ojpegFieldInfo/sizeof *ojpegFieldInfo);
2542
 
    sp->defsparent = tif->tif_defstripsize;
2543
 
    sp->deftparent = tif->tif_deftilesize;
2544
 
    sp->vgetparent = tif->tif_tagmethods.vgetfield;
2545
 
    sp->vsetparent = tif->tif_tagmethods.vsetfield;
2546
 
    tif->tif_defstripsize = OJPEGDefaultStripSize;
2547
 
    tif->tif_deftilesize = OJPEGDefaultTileSize;
2548
 
    tif->tif_tagmethods.vgetfield = OJPEGVGetField;
2549
 
    tif->tif_tagmethods.vsetfield = OJPEGVSetField;
2550
 
    tif->tif_tagmethods.printdir = OJPEGPrintDir;
2551
 
#   ifdef never
2552
 
    tif->tif_setupencode = OJPEGSetupEncode;
2553
 
    tif->tif_preencode = OJPEGPreEncode;
2554
 
    tif->tif_postencode = OJPEGPostEncode;
2555
 
#   else /* well, hardly ever */
2556
 
    tif->tif_setupencode = tif->tif_postencode = _notSupported;
2557
 
    tif->tif_preencode = (TIFFPreMethod)_notSupported;
2558
 
#   endif /* never */
2559
 
    tif->tif_setupdecode = OJPEGSetupDecode;
2560
 
    tif->tif_predecode = OJPEGPreDecode;
2561
 
    tif->tif_postdecode = OJPEGPostDecode;
2562
 
    tif->tif_cleanup = OJPEGCleanUp;
2563
 
 
2564
 
 /* If the image file doesn't have "JPEGInterchangeFormat[Length]" TIFF records
2565
 
    to guide us, we have few clues about where its encapsulated JPEG bit stream
2566
 
    is located, so establish intelligent defaults:  If the Image File Directory
2567
 
    doesn't immediately follow the TIFF header, assume that the JPEG data lies
2568
 
    in between; otherwise, assume that it follows the Image File Directory.
2569
 
 */
2570
 
    if (tif->tif_header.tiff_diroff > sizeof tif->tif_header)
2571
 
      {
2572
 
        sp->src.next_input_byte = tif->tif_base + sizeof tif->tif_header;
2573
 
        sp->src.bytes_in_buffer = tif->tif_header.tiff_diroff
2574
 
                                - sizeof tif->tif_header;
2575
 
      }
2576
 
    else /* this case is ugly! */
2577
 
      { uint32 maxoffset = tif->tif_size;
2578
 
        uint16 dircount;
2579
 
 
2580
 
     /* Calculate the offset to the next Image File Directory, if there is one,
2581
 
        or to the end of the file, if not.  Then arrange to read the file from
2582
 
        the end of the Image File Directory to that offset.
2583
 
     */
2584
 
        if (tif->tif_nextdiroff) maxoffset = tif->tif_nextdiroff; /* Not EOF */
2585
 
        _TIFFmemcpy(&dircount,(const tdata_t)
2586
 
          (sp->src.next_input_byte = tif->tif_base+tif->tif_header.tiff_diroff),
2587
 
          sizeof dircount);
2588
 
        if (tif->tif_flags & TIFF_SWAB) TIFFSwabShort(&dircount);
2589
 
        sp->src.next_input_byte += dircount*sizeof(TIFFDirEntry)
2590
 
                                + sizeof maxoffset + sizeof dircount;
2591
 
        sp->src.bytes_in_buffer = tif->tif_base - sp->src.next_input_byte
2592
 
                                + maxoffset;
2593
 
      };
2594
 
 
2595
 
 /* IJG JPEG Library Version 6B can be configured for either 8- or 12-bit sample
2596
 
    precision, but we assume that "old JPEG" TIFF clients only need 8 bits.
2597
 
 */
2598
 
    sp->cinfo.d.data_precision = 8;
2599
 
#   ifdef C_LOSSLESS_SUPPORTED
2600
 
 
2601
 
 /* If the "JPEGProc" TIFF tag is missing from the Image File Dictionary, the
2602
 
    JPEG Library will use its (lossy) baseline sequential process by default.
2603
 
 */
2604
 
    sp->cinfo.d.data_unit = DCTSIZE;
2605
 
#   endif /* C_LOSSLESS_SUPPORTED */
2606
 
 
2607
 
 /* Initialize other CODEC-specific variables requiring default values. */
2608
 
 
2609
 
    tif->tif_flags |= TIFF_NOBITREV; /* No bit-reversal within data bytes */
2610
 
    sp->h_sampling = sp->v_sampling = 1; /* No subsampling by default */
2611
 
    sp->is_WANG = 0; /* Assume not a MS Windows Wang Imaging file by default */
2612
 
    sp->jpegtables = 0; /* No "new"-style JPEG tables synthesized yet */
2613
 
    sp->jpegtables_length = 0;
2614
 
    sp->jpegquality = 75; /* Default IJG quality */
2615
 
    sp->jpegcolormode = JPEGCOLORMODE_RAW;
2616
 
    sp->jpegtablesmode = 0; /* No tables found yet */
2617
 
    sp->jpeglosslesspredictors=0;
2618
 
    sp->jpeglosslesspredictors_length=0;
2619
 
    sp->jpegpointtransform=0;
2620
 
    sp->jpegpointtransform_length=0;
2621
 
    sp->jpegqtables=0;
2622
 
    sp->jpegqtables_length=0;
2623
 
    sp->jpegdctables=0;
2624
 
    sp->jpegdctables_length=0;
2625
 
    sp->jpegactables=0;
2626
 
    sp->jpegactables_length=0;
2627
 
    return 1;
2628
 
#   undef td
2629
 
  }
2630
 
#endif /* OJPEG_SUPPORT */