Imported Upstream version 4.1.0 into tizen
[platform/upstream/tiff.git] / libtiff / tif_ojpeg.c
1 /* WARNING: The type of JPEG encapsulation defined by the TIFF Version 6.0
2    specification is now totally obsolete and deprecated for new applications and
3    images. This file was was created solely in order to read unconverted images
4    still present on some users' computer systems. It will never be extended
5    to write such files. Writing new-style JPEG compressed TIFFs is implemented
6    in tif_jpeg.c.
7
8    The code is carefully crafted to robustly read all gathered JPEG-in-TIFF
9    testfiles, and anticipate as much as possible all other... But still, it may
10    fail on some. If you encounter problems, please report them on the TIFF
11    mailing list and/or to Joris Van Damme <info@awaresystems.be>.
12
13    Please read the file called "TIFF Technical Note #2" if you need to be
14    convinced this compression scheme is bad and breaks TIFF. That document
15    is linked to from the LibTiff site <http://www.remotesensing.org/libtiff/>
16    and from AWare Systems' TIFF section
17    <http://www.awaresystems.be/imaging/tiff.html>. It is also absorbed
18    in Adobe's specification supplements, marked "draft" up to this day, but
19    supported by the TIFF community.
20
21    This file interfaces with Release 6B of the JPEG Library written by the
22    Independent JPEG Group. Previous versions of this file required a hack inside
23    the LibJpeg library. This version no longer requires that. Remember to
24    remove the hack if you update from the old version.
25
26    Copyright (c) Joris Van Damme <info@awaresystems.be>
27    Copyright (c) AWare Systems <http://www.awaresystems.be/>
28
29    The licence agreement for this file is the same as the rest of the LibTiff
30    library.
31
32    IN NO EVENT SHALL JORIS VAN DAMME OR AWARE SYSTEMS BE LIABLE FOR
33    ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
34    OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
35    WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
36    LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
37    OF THIS SOFTWARE.
38
39    Joris Van Damme and/or AWare Systems may be available for custom
40    development. If you like what you see, and need anything similar or related,
41    contact <info@awaresystems.be>.
42 */
43
44 /* What is what, and what is not?
45
46    This decoder starts with an input stream, that is essentially the JpegInterchangeFormat
47    stream, if any, followed by the strile data, if any. This stream is read in
48    OJPEGReadByte and related functions.
49
50    It analyzes the start of this stream, until it encounters non-marker data, i.e.
51    compressed image data. Some of the header markers it sees have no actual content,
52    like the SOI marker, and APP/COM markers that really shouldn't even be there. Some
53    other markers do have content, and the valuable bits and pieces of information
54    in these markers are saved, checking all to verify that the stream is more or
55    less within expected bounds. This happens inside the OJPEGReadHeaderInfoSecStreamXxx
56    functions.
57
58    Some OJPEG imagery contains no valid JPEG header markers. This situation is picked
59    up on if we've seen no SOF marker when we're at the start of the compressed image
60    data. In this case, the tables are read from JpegXxxTables tags, and the other
61    bits and pieces of information is initialized to its most basic value. This is
62    implemented in the OJPEGReadHeaderInfoSecTablesXxx functions.
63
64    When this is complete, a good and valid JPEG header can be assembled, and this is
65    passed through to LibJpeg. When that's done, the remainder of the input stream, i.e.
66    the compressed image data, can be passed through unchanged. This is done in
67    OJPEGWriteStream functions.
68
69    LibTiff rightly expects to know the subsampling values before decompression. Just like
70    in new-style JPEG-in-TIFF, though, or even more so, actually, the YCbCrsubsampling
71    tag is notoriously unreliable. To correct these tag values with the ones inside
72    the JPEG stream, the first part of the input stream is pre-scanned in
73    OJPEGSubsamplingCorrect, making no note of any other data, reporting no warnings
74    or errors, up to the point where either these values are read, or it's clear they
75    aren't there. This means that some of the data is read twice, but we feel speed
76    in correcting these values is important enough to warrant this sacrifice. Although
77    there is currently no define or other configuration mechanism to disable this behaviour,
78    the actual header scanning is build to robustly respond with error report if it
79    should encounter an uncorrected mismatch of subsampling values. See
80    OJPEGReadHeaderInfoSecStreamSof.
81
82    The restart interval and restart markers are the most tricky part... The restart
83    interval can be specified in a tag. It can also be set inside the input JPEG stream.
84    It can be used inside the input JPEG stream. If reading from strile data, we've
85    consistently discovered the need to insert restart markers in between the different
86    striles, as is also probably the most likely interpretation of the original TIFF 6.0
87    specification. With all this setting of interval, and actual use of markers that is not
88    predictable at the time of valid JPEG header assembly, the restart thing may turn
89    out the Achilles heel of this implementation. Fortunately, most OJPEG writer vendors
90    succeed in reading back what they write, which may be the reason why we've been able
91    to discover ways that seem to work.
92
93    Some special provision is made for planarconfig separate OJPEG files. These seem
94    to consistently contain header info, a SOS marker, a plane, SOS marker, plane, SOS,
95    and plane. This may or may not be a valid JPEG configuration, we don't know and don't
96    care. We want LibTiff to be able to access the planes individually, without huge
97    buffering inside LibJpeg, anyway. So we compose headers to feed to LibJpeg, in this
98    case, that allow us to pass a single plane such that LibJpeg sees a valid
99    single-channel JPEG stream. Locating subsequent SOS markers, and thus subsequent
100    planes, is done inside OJPEGReadSecondarySos.
101
102    The benefit of the scheme is... that it works, basically. We know of no other that
103    does. It works without checking software tag, or otherwise going about things in an
104    OJPEG flavor specific manner. Instead, it is a single scheme, that covers the cases
105    with and without JpegInterchangeFormat, with and without striles, with part of
106    the header in JpegInterchangeFormat and remainder in first strile, etc. It is forgiving
107    and robust, may likely work with OJPEG flavors we've not seen yet, and makes most out
108    of the data.
109
110    Another nice side-effect is that a complete JPEG single valid stream is build if
111    planarconfig is not separate (vast majority). We may one day use that to build
112    converters to JPEG, and/or to new-style JPEG compression inside TIFF.
113
114    A disadvantage is the lack of random access to the individual striles. This is the
115    reason for much of the complicated restart-and-position stuff inside OJPEGPreDecode.
116    Applications would do well accessing all striles in order, as this will result in
117    a single sequential scan of the input stream, and no restarting of LibJpeg decoding
118    session.
119 */
120
121 #define WIN32_LEAN_AND_MEAN
122 #define VC_EXTRALEAN
123
124 #include "tiffiop.h"
125 #ifdef OJPEG_SUPPORT
126
127 /* Configuration defines here are:
128  * JPEG_ENCAP_EXTERNAL: The normal way to call libjpeg, uses longjump. In some environments,
129  *      like eg LibTiffDelphi, this is not possible. For this reason, the actual calls to
130  *      libjpeg, with longjump stuff, are encapsulated in dedicated functions. When
131  *      JPEG_ENCAP_EXTERNAL is defined, these encapsulating functions are declared external
132  *      to this unit, and can be defined elsewhere to use stuff other then longjump.
133  *      The default mode, without JPEG_ENCAP_EXTERNAL, implements the call encapsulators
134  *      here, internally, with normal longjump.
135  * SETJMP, LONGJMP, JMP_BUF: On some machines/environments a longjump equivalent is
136  *      conveniently available, but still it may be worthwhile to use _setjmp or sigsetjmp
137  *      in place of plain setjmp. These macros will make it easier. It is useless
138  *      to fiddle with these if you define JPEG_ENCAP_EXTERNAL.
139  * OJPEG_BUFFER: Define the size of the desired buffer here. Should be small enough so as to guarantee
140  *      instant processing, optimal streaming and optimal use of processor cache, but also big
141  *      enough so as to not result in significant call overhead. It should be at least a few
142  *      bytes to accommodate some structures (this is verified in asserts), but it would not be
143  *      sensible to make it this small anyway, and it should be at most 64K since it is indexed
144  *      with uint16. We recommend 2K.
145  * EGYPTIANWALK: You could also define EGYPTIANWALK here, but it is not used anywhere and has
146  *      absolutely no effect. That is why most people insist the EGYPTIANWALK is a bit silly.
147  */
148
149 /* define LIBJPEG_ENCAP_EXTERNAL */
150 #define SETJMP(jbuf) setjmp(jbuf)
151 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
152 #define JMP_BUF jmp_buf
153 #define OJPEG_BUFFER 2048
154 /* define EGYPTIANWALK */
155
156 #define JPEG_MARKER_SOF0 0xC0
157 #define JPEG_MARKER_SOF1 0xC1
158 #define JPEG_MARKER_SOF3 0xC3
159 #define JPEG_MARKER_DHT 0xC4
160 #define JPEG_MARKER_RST0 0XD0
161 #define JPEG_MARKER_SOI 0xD8
162 #define JPEG_MARKER_EOI 0xD9
163 #define JPEG_MARKER_SOS 0xDA
164 #define JPEG_MARKER_DQT 0xDB
165 #define JPEG_MARKER_DRI 0xDD
166 #define JPEG_MARKER_APP0 0xE0
167 #define JPEG_MARKER_COM 0xFE
168
169 #define FIELD_OJPEG_JPEGINTERCHANGEFORMAT (FIELD_CODEC+0)
170 #define FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH (FIELD_CODEC+1)
171 #define FIELD_OJPEG_JPEGQTABLES (FIELD_CODEC+2)
172 #define FIELD_OJPEG_JPEGDCTABLES (FIELD_CODEC+3)
173 #define FIELD_OJPEG_JPEGACTABLES (FIELD_CODEC+4)
174 #define FIELD_OJPEG_JPEGPROC (FIELD_CODEC+5)
175 #define FIELD_OJPEG_JPEGRESTARTINTERVAL (FIELD_CODEC+6)
176
177 static const TIFFField ojpegFields[] = {
178         {TIFFTAG_JPEGIFOFFSET,1,1,TIFF_LONG8,0,TIFF_SETGET_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGINTERCHANGEFORMAT,TRUE,FALSE,"JpegInterchangeFormat",NULL},
179         {TIFFTAG_JPEGIFBYTECOUNT,1,1,TIFF_LONG8,0,TIFF_SETGET_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH,TRUE,FALSE,"JpegInterchangeFormatLength",NULL},
180         {TIFFTAG_JPEGQTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGQTABLES,FALSE,TRUE,"JpegQTables",NULL},
181         {TIFFTAG_JPEGDCTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGDCTABLES,FALSE,TRUE,"JpegDcTables",NULL},
182         {TIFFTAG_JPEGACTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGACTABLES,FALSE,TRUE,"JpegAcTables",NULL},
183         {TIFFTAG_JPEGPROC,1,1,TIFF_SHORT,0,TIFF_SETGET_UINT16,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGPROC,FALSE,FALSE,"JpegProc",NULL},
184         {TIFFTAG_JPEGRESTARTINTERVAL,1,1,TIFF_SHORT,0,TIFF_SETGET_UINT16,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGRESTARTINTERVAL,FALSE,FALSE,"JpegRestartInterval",NULL},
185 };
186
187 #ifndef LIBJPEG_ENCAP_EXTERNAL
188 #include <setjmp.h>
189 #endif
190
191 /* We undefine FAR to avoid conflict with JPEG definition */
192
193 #ifdef FAR
194 #undef FAR
195 #endif
196
197 /*
198   Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
199   not defined.  Unfortunately, the MinGW and Borland compilers include
200   a typedef for INT32, which causes a conflict.  MSVC does not include
201   a conflicting typedef given the headers which are included.
202 */
203 #if defined(__BORLANDC__) || defined(__MINGW32__)
204 # define XMD_H 1
205 #endif
206
207 /* Define "boolean" as unsigned char, not int, per Windows custom. */
208 #if defined(__WIN32__) && !defined(__MINGW32__)
209 # ifndef __RPCNDR_H__            /* don't conflict if rpcndr.h already read */
210    typedef unsigned char boolean;
211 # endif
212 # define HAVE_BOOLEAN            /* prevent jmorecfg.h from redefining it */
213 #endif
214
215 #include "jpeglib.h"
216 #include "jerror.h"
217
218 typedef struct jpeg_error_mgr jpeg_error_mgr;
219 typedef struct jpeg_common_struct jpeg_common_struct;
220 typedef struct jpeg_decompress_struct jpeg_decompress_struct;
221 typedef struct jpeg_source_mgr jpeg_source_mgr;
222
223 typedef enum {
224         osibsNotSetYet,
225         osibsJpegInterchangeFormat,
226         osibsStrile,
227         osibsEof
228 } OJPEGStateInBufferSource;
229
230 typedef enum {
231         ososSoi,
232         ososQTable0,ososQTable1,ososQTable2,ososQTable3,
233         ososDcTable0,ososDcTable1,ososDcTable2,ososDcTable3,
234         ososAcTable0,ososAcTable1,ososAcTable2,ososAcTable3,
235         ososDri,
236         ososSof,
237         ososSos,
238         ososCompressed,
239         ososRst,
240         ososEoi
241 } OJPEGStateOutState;
242
243 typedef struct {
244         TIFF* tif;
245         int decoder_ok;
246         int error_in_raw_data_decoding;
247         #ifndef LIBJPEG_ENCAP_EXTERNAL
248         JMP_BUF exit_jmpbuf;
249         #endif
250         TIFFVGetMethod vgetparent;
251         TIFFVSetMethod vsetparent;
252         TIFFPrintMethod printdir;
253         uint64 file_size;
254         uint32 image_width;
255         uint32 image_length;
256         uint32 strile_width;
257         uint32 strile_length;
258         uint32 strile_length_total;
259         uint8 samples_per_pixel;
260         uint8 plane_sample_offset;
261         uint8 samples_per_pixel_per_plane;
262         uint64 jpeg_interchange_format;
263         uint64 jpeg_interchange_format_length;
264         uint8 jpeg_proc;
265         uint8 subsamplingcorrect;
266         uint8 subsamplingcorrect_done;
267         uint8 subsampling_tag;
268         uint8 subsampling_hor;
269         uint8 subsampling_ver;
270         uint8 subsampling_force_desubsampling_inside_decompression;
271         uint8 qtable_offset_count;
272         uint8 dctable_offset_count;
273         uint8 actable_offset_count;
274         uint64 qtable_offset[3];
275         uint64 dctable_offset[3];
276         uint64 actable_offset[3];
277         uint8* qtable[4];
278         uint8* dctable[4];
279         uint8* actable[4];
280         uint16 restart_interval;
281         uint8 restart_index;
282         uint8 sof_log;
283         uint8 sof_marker_id;
284         uint32 sof_x;
285         uint32 sof_y;
286         uint8 sof_c[3];
287         uint8 sof_hv[3];
288         uint8 sof_tq[3];
289         uint8 sos_cs[3];
290         uint8 sos_tda[3];
291         struct {
292                 uint8 log;
293                 OJPEGStateInBufferSource in_buffer_source;
294                 uint32 in_buffer_next_strile;
295                 uint64 in_buffer_file_pos;
296                 uint64 in_buffer_file_togo;
297         } sos_end[3];
298         uint8 readheader_done;
299         uint8 writeheader_done;
300         uint16 write_cursample;
301         uint32 write_curstrile;
302         uint8 libjpeg_session_active;
303         uint8 libjpeg_jpeg_query_style;
304         jpeg_error_mgr libjpeg_jpeg_error_mgr;
305         jpeg_decompress_struct libjpeg_jpeg_decompress_struct;
306         jpeg_source_mgr libjpeg_jpeg_source_mgr;
307         uint8 subsampling_convert_log;
308         uint32 subsampling_convert_ylinelen;
309         uint32 subsampling_convert_ylines;
310         uint32 subsampling_convert_clinelen;
311         uint32 subsampling_convert_clines;
312         uint32 subsampling_convert_ybuflen;
313         uint32 subsampling_convert_cbuflen;
314         uint32 subsampling_convert_ycbcrbuflen;
315         uint8* subsampling_convert_ycbcrbuf;
316         uint8* subsampling_convert_ybuf;
317         uint8* subsampling_convert_cbbuf;
318         uint8* subsampling_convert_crbuf;
319         uint32 subsampling_convert_ycbcrimagelen;
320         uint8** subsampling_convert_ycbcrimage;
321         uint32 subsampling_convert_clinelenout;
322         uint32 subsampling_convert_state;
323         uint32 bytes_per_line;   /* if the codec outputs subsampled data, a 'line' in bytes_per_line */
324         uint32 lines_per_strile; /* and lines_per_strile means subsampling_ver desubsampled rows     */
325         OJPEGStateInBufferSource in_buffer_source;
326         uint32 in_buffer_next_strile;
327         uint32 in_buffer_strile_count;
328         uint64 in_buffer_file_pos;
329         uint8 in_buffer_file_pos_log;
330         uint64 in_buffer_file_togo;
331         uint16 in_buffer_togo;
332         uint8* in_buffer_cur;
333         uint8 in_buffer[OJPEG_BUFFER];
334         OJPEGStateOutState out_state;
335         uint8 out_buffer[OJPEG_BUFFER];
336         uint8* skip_buffer;
337 } OJPEGState;
338
339 static int OJPEGVGetField(TIFF* tif, uint32 tag, va_list ap);
340 static int OJPEGVSetField(TIFF* tif, uint32 tag, va_list ap);
341 static void OJPEGPrintDir(TIFF* tif, FILE* fd, long flags);
342
343 static int OJPEGFixupTags(TIFF* tif);
344 static int OJPEGSetupDecode(TIFF* tif);
345 static int OJPEGPreDecode(TIFF* tif, uint16 s);
346 static int OJPEGPreDecodeSkipRaw(TIFF* tif);
347 static int OJPEGPreDecodeSkipScanlines(TIFF* tif);
348 static int OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
349 static int OJPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc);
350 static int OJPEGDecodeScanlines(TIFF* tif, uint8* buf, tmsize_t cc);
351 static void OJPEGPostDecode(TIFF* tif, uint8* buf, tmsize_t cc);
352 static int OJPEGSetupEncode(TIFF* tif);
353 static int OJPEGPreEncode(TIFF* tif, uint16 s);
354 static int OJPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
355 static int OJPEGPostEncode(TIFF* tif);
356 static void OJPEGCleanup(TIFF* tif);
357
358 static void OJPEGSubsamplingCorrect(TIFF* tif);
359 static int OJPEGReadHeaderInfo(TIFF* tif);
360 static int OJPEGReadSecondarySos(TIFF* tif, uint16 s);
361 static int OJPEGWriteHeaderInfo(TIFF* tif);
362 static void OJPEGLibjpegSessionAbort(TIFF* tif);
363
364 static int OJPEGReadHeaderInfoSec(TIFF* tif);
365 static int OJPEGReadHeaderInfoSecStreamDri(TIFF* tif);
366 static int OJPEGReadHeaderInfoSecStreamDqt(TIFF* tif);
367 static int OJPEGReadHeaderInfoSecStreamDht(TIFF* tif);
368 static int OJPEGReadHeaderInfoSecStreamSof(TIFF* tif, uint8 marker_id);
369 static int OJPEGReadHeaderInfoSecStreamSos(TIFF* tif);
370 static int OJPEGReadHeaderInfoSecTablesQTable(TIFF* tif);
371 static int OJPEGReadHeaderInfoSecTablesDcTable(TIFF* tif);
372 static int OJPEGReadHeaderInfoSecTablesAcTable(TIFF* tif);
373
374 static int OJPEGReadBufferFill(OJPEGState* sp);
375 static int OJPEGReadByte(OJPEGState* sp, uint8* byte);
376 static int OJPEGReadBytePeek(OJPEGState* sp, uint8* byte);
377 static void OJPEGReadByteAdvance(OJPEGState* sp);
378 static int OJPEGReadWord(OJPEGState* sp, uint16* word);
379 static int OJPEGReadBlock(OJPEGState* sp, uint16 len, void* mem);
380 static void OJPEGReadSkip(OJPEGState* sp, uint16 len);
381
382 static int OJPEGWriteStream(TIFF* tif, void** mem, uint32* len);
383 static void OJPEGWriteStreamSoi(TIFF* tif, void** mem, uint32* len);
384 static void OJPEGWriteStreamQTable(TIFF* tif, uint8 table_index, void** mem, uint32* len);
385 static void OJPEGWriteStreamDcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len);
386 static void OJPEGWriteStreamAcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len);
387 static void OJPEGWriteStreamDri(TIFF* tif, void** mem, uint32* len);
388 static void OJPEGWriteStreamSof(TIFF* tif, void** mem, uint32* len);
389 static void OJPEGWriteStreamSos(TIFF* tif, void** mem, uint32* len);
390 static int OJPEGWriteStreamCompressed(TIFF* tif, void** mem, uint32* len);
391 static void OJPEGWriteStreamRst(TIFF* tif, void** mem, uint32* len);
392 static void OJPEGWriteStreamEoi(TIFF* tif, void** mem, uint32* len);
393
394 #ifdef LIBJPEG_ENCAP_EXTERNAL
395 extern int jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo);
396 extern int jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image);
397 extern int jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo);
398 extern int jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines);
399 extern int jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines);
400 extern void jpeg_encap_unwind(TIFF* tif);
401 #else
402 static int jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* j);
403 static int jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image);
404 static int jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo);
405 static int jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines);
406 static int jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines);
407 static void jpeg_encap_unwind(TIFF* tif);
408 #endif
409
410 static void OJPEGLibjpegJpegErrorMgrOutputMessage(jpeg_common_struct* cinfo);
411 static void OJPEGLibjpegJpegErrorMgrErrorExit(jpeg_common_struct* cinfo);
412 static void OJPEGLibjpegJpegSourceMgrInitSource(jpeg_decompress_struct* cinfo);
413 static boolean OJPEGLibjpegJpegSourceMgrFillInputBuffer(jpeg_decompress_struct* cinfo);
414 static void OJPEGLibjpegJpegSourceMgrSkipInputData(jpeg_decompress_struct* cinfo, long num_bytes);
415 static boolean OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct* cinfo, int desired);
416 static void OJPEGLibjpegJpegSourceMgrTermSource(jpeg_decompress_struct* cinfo);
417
418 int
419 TIFFInitOJPEG(TIFF* tif, int scheme)
420 {
421         static const char module[]="TIFFInitOJPEG";
422         OJPEGState* sp;
423
424         assert(scheme==COMPRESSION_OJPEG);
425
426         /*
427          * Merge codec-specific tag information.
428          */
429         if (!_TIFFMergeFields(tif, ojpegFields, TIFFArrayCount(ojpegFields))) {
430                 TIFFErrorExt(tif->tif_clientdata, module,
431                     "Merging Old JPEG codec-specific tags failed");
432                 return 0;
433         }
434
435         /* state block */
436         sp=_TIFFmalloc(sizeof(OJPEGState));
437         if (sp==NULL)
438         {
439                 TIFFErrorExt(tif->tif_clientdata,module,"No space for OJPEG state block");
440                 return(0);
441         }
442         _TIFFmemset(sp,0,sizeof(OJPEGState));
443         sp->tif=tif;
444         sp->jpeg_proc=1;
445         sp->subsampling_hor=2;
446         sp->subsampling_ver=2;
447         TIFFSetField(tif,TIFFTAG_YCBCRSUBSAMPLING,2,2);
448         /* tif codec methods */
449         tif->tif_fixuptags=OJPEGFixupTags;  
450         tif->tif_setupdecode=OJPEGSetupDecode;
451         tif->tif_predecode=OJPEGPreDecode;
452         tif->tif_postdecode=OJPEGPostDecode;  
453         tif->tif_decoderow=OJPEGDecode;  
454         tif->tif_decodestrip=OJPEGDecode;  
455         tif->tif_decodetile=OJPEGDecode;  
456         tif->tif_setupencode=OJPEGSetupEncode;
457         tif->tif_preencode=OJPEGPreEncode;
458         tif->tif_postencode=OJPEGPostEncode;
459         tif->tif_encoderow=OJPEGEncode;  
460         tif->tif_encodestrip=OJPEGEncode;  
461         tif->tif_encodetile=OJPEGEncode;  
462         tif->tif_cleanup=OJPEGCleanup;
463         tif->tif_data=(uint8*)sp;
464         /* tif tag methods */
465         sp->vgetparent=tif->tif_tagmethods.vgetfield;
466         tif->tif_tagmethods.vgetfield=OJPEGVGetField;
467         sp->vsetparent=tif->tif_tagmethods.vsetfield;
468         tif->tif_tagmethods.vsetfield=OJPEGVSetField;
469         sp->printdir=tif->tif_tagmethods.printdir;
470         tif->tif_tagmethods.printdir=OJPEGPrintDir;
471         /* Some OJPEG files don't have strip or tile offsets or bytecounts tags.
472            Some others do, but have totally meaningless or corrupt values
473            in these tags. In these cases, the JpegInterchangeFormat stream is
474            reliable. In any case, this decoder reads the compressed data itself,
475            from the most reliable locations, and we need to notify encapsulating
476            LibTiff not to read raw strips or tiles for us. */
477         tif->tif_flags|=TIFF_NOREADRAW;
478         return(1);
479 }
480
481 static int
482 OJPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
483 {
484         OJPEGState* sp=(OJPEGState*)tif->tif_data;
485         switch(tag)
486         {
487                 case TIFFTAG_JPEGIFOFFSET:
488                         *va_arg(ap,uint64*)=(uint64)sp->jpeg_interchange_format;
489                         break;
490                 case TIFFTAG_JPEGIFBYTECOUNT:
491                         *va_arg(ap,uint64*)=(uint64)sp->jpeg_interchange_format_length;
492                         break;
493                 case TIFFTAG_YCBCRSUBSAMPLING:
494                         if (sp->subsamplingcorrect_done==0)
495                                 OJPEGSubsamplingCorrect(tif);
496                         *va_arg(ap,uint16*)=(uint16)sp->subsampling_hor;
497                         *va_arg(ap,uint16*)=(uint16)sp->subsampling_ver;
498                         break;
499                 case TIFFTAG_JPEGQTABLES:
500                         *va_arg(ap,uint32*)=(uint32)sp->qtable_offset_count;
501                         *va_arg(ap,void**)=(void*)sp->qtable_offset; 
502                         break;
503                 case TIFFTAG_JPEGDCTABLES:
504                         *va_arg(ap,uint32*)=(uint32)sp->dctable_offset_count;
505                         *va_arg(ap,void**)=(void*)sp->dctable_offset;  
506                         break;
507                 case TIFFTAG_JPEGACTABLES:
508                         *va_arg(ap,uint32*)=(uint32)sp->actable_offset_count;
509                         *va_arg(ap,void**)=(void*)sp->actable_offset;
510                         break;
511                 case TIFFTAG_JPEGPROC:
512                         *va_arg(ap,uint16*)=(uint16)sp->jpeg_proc;
513                         break;
514                 case TIFFTAG_JPEGRESTARTINTERVAL:
515                         *va_arg(ap,uint16*)=sp->restart_interval;
516                         break;
517                 default:
518                         return (*sp->vgetparent)(tif,tag,ap);
519         }
520         return (1);
521 }
522
523 static int
524 OJPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
525 {
526         static const char module[]="OJPEGVSetField";
527         OJPEGState* sp=(OJPEGState*)tif->tif_data;
528         uint32 ma;
529         uint64* mb;
530         uint32 n;
531         const TIFFField* fip;
532
533         switch(tag)
534         {
535                 case TIFFTAG_JPEGIFOFFSET:
536                         sp->jpeg_interchange_format=(uint64)va_arg(ap,uint64);
537                         break;
538                 case TIFFTAG_JPEGIFBYTECOUNT:
539                         sp->jpeg_interchange_format_length=(uint64)va_arg(ap,uint64);
540                         break;
541                 case TIFFTAG_YCBCRSUBSAMPLING:
542                         sp->subsampling_tag=1;
543                         sp->subsampling_hor=(uint8)va_arg(ap,uint16_vap);
544                         sp->subsampling_ver=(uint8)va_arg(ap,uint16_vap);
545                         tif->tif_dir.td_ycbcrsubsampling[0]=sp->subsampling_hor;
546                         tif->tif_dir.td_ycbcrsubsampling[1]=sp->subsampling_ver;
547                         break;
548                 case TIFFTAG_JPEGQTABLES:
549                         ma=(uint32)va_arg(ap,uint32);
550                         if (ma!=0)
551                         {
552                                 if (ma>3)
553                                 {
554                                         TIFFErrorExt(tif->tif_clientdata,module,"JpegQTables tag has incorrect count");
555                                         return(0);
556                                 }
557                                 sp->qtable_offset_count=(uint8)ma;
558                                 mb=(uint64*)va_arg(ap,uint64*);
559                                 for (n=0; n<ma; n++)
560                                         sp->qtable_offset[n]=mb[n];
561                         }
562                         break;
563                 case TIFFTAG_JPEGDCTABLES:
564                         ma=(uint32)va_arg(ap,uint32);
565                         if (ma!=0)
566                         {
567                                 if (ma>3)
568                                 {
569                                         TIFFErrorExt(tif->tif_clientdata,module,"JpegDcTables tag has incorrect count");
570                                         return(0);
571                                 }
572                                 sp->dctable_offset_count=(uint8)ma;
573                                 mb=(uint64*)va_arg(ap,uint64*);
574                                 for (n=0; n<ma; n++)
575                                         sp->dctable_offset[n]=mb[n];
576                         }
577                         break;
578                 case TIFFTAG_JPEGACTABLES:
579                         ma=(uint32)va_arg(ap,uint32);
580                         if (ma!=0)
581                         {
582                                 if (ma>3)
583                                 {
584                                         TIFFErrorExt(tif->tif_clientdata,module,"JpegAcTables tag has incorrect count");
585                                         return(0);
586                                 }
587                                 sp->actable_offset_count=(uint8)ma;
588                                 mb=(uint64*)va_arg(ap,uint64*);
589                                 for (n=0; n<ma; n++)
590                                         sp->actable_offset[n]=mb[n];
591                         }
592                         break;
593                 case TIFFTAG_JPEGPROC:
594                         sp->jpeg_proc=(uint8)va_arg(ap,uint16_vap);
595                         break;
596                 case TIFFTAG_JPEGRESTARTINTERVAL:
597                         sp->restart_interval=(uint16)va_arg(ap,uint16_vap);
598                         break;
599                 default:
600                         return (*sp->vsetparent)(tif,tag,ap);
601         }
602         fip = TIFFFieldWithTag(tif,tag);
603         if( fip == NULL ) /* shouldn't happen */
604             return(0);
605         TIFFSetFieldBit(tif,fip->field_bit);
606         tif->tif_flags|=TIFF_DIRTYDIRECT;
607         return(1);
608 }
609
610 static void
611 OJPEGPrintDir(TIFF* tif, FILE* fd, long flags)
612 {
613         OJPEGState* sp=(OJPEGState*)tif->tif_data;
614         uint8 m;
615         (void)flags;
616         assert(sp!=NULL);
617         if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGINTERCHANGEFORMAT))
618                 fprintf(fd,"  JpegInterchangeFormat: " TIFF_UINT64_FORMAT "\n",(TIFF_UINT64_T)sp->jpeg_interchange_format);  
619         if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH))
620                 fprintf(fd,"  JpegInterchangeFormatLength: " TIFF_UINT64_FORMAT "\n",(TIFF_UINT64_T)sp->jpeg_interchange_format_length);  
621         if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGQTABLES))
622         {
623                 fprintf(fd,"  JpegQTables:");
624                 for (m=0; m<sp->qtable_offset_count; m++)
625                         fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->qtable_offset[m]);
626                 fprintf(fd,"\n");
627         }
628         if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGDCTABLES))
629         {
630                 fprintf(fd,"  JpegDcTables:");
631                 for (m=0; m<sp->dctable_offset_count; m++)
632                         fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->dctable_offset[m]);
633                 fprintf(fd,"\n");
634         }
635         if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGACTABLES))
636         {
637                 fprintf(fd,"  JpegAcTables:");
638                 for (m=0; m<sp->actable_offset_count; m++)
639                         fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->actable_offset[m]);
640                 fprintf(fd,"\n");
641         }
642         if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGPROC))
643                 fprintf(fd,"  JpegProc: %u\n",(unsigned int)sp->jpeg_proc);
644         if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGRESTARTINTERVAL))
645                 fprintf(fd,"  JpegRestartInterval: %u\n",(unsigned int)sp->restart_interval);
646         if (sp->printdir)
647                 (*sp->printdir)(tif, fd, flags);
648 }
649
650 static int
651 OJPEGFixupTags(TIFF* tif)
652 {
653         (void) tif;
654         return(1);
655 }
656
657 static int
658 OJPEGSetupDecode(TIFF* tif)
659 {
660         static const char module[]="OJPEGSetupDecode";
661         TIFFWarningExt(tif->tif_clientdata,module,"Depreciated and troublesome old-style JPEG compression mode, please convert to new-style JPEG compression and notify vendor of writing software");
662         return(1);
663 }
664
665 static int
666 OJPEGPreDecode(TIFF* tif, uint16 s)
667 {
668         OJPEGState* sp=(OJPEGState*)tif->tif_data;
669         uint32 m;
670         if (sp->subsamplingcorrect_done==0)
671                 OJPEGSubsamplingCorrect(tif);
672         if (sp->readheader_done==0)
673         {
674                 if (OJPEGReadHeaderInfo(tif)==0)
675                         return(0);
676         }
677         if (sp->sos_end[s].log==0)
678         {
679                 if (OJPEGReadSecondarySos(tif,s)==0)
680                         return(0);
681         }
682         if (isTiled(tif))
683                 m=tif->tif_curtile;
684         else
685                 m=tif->tif_curstrip;
686         if ((sp->writeheader_done!=0) && ((sp->write_cursample!=s) || (sp->write_curstrile>m)))
687         {
688                 if (sp->libjpeg_session_active!=0)
689                         OJPEGLibjpegSessionAbort(tif);
690                 sp->writeheader_done=0;
691         }
692         if (sp->writeheader_done==0)
693         {
694                 sp->plane_sample_offset=(uint8)s;
695                 sp->write_cursample=s;
696                 sp->write_curstrile=s*tif->tif_dir.td_stripsperimage;
697                 if ((sp->in_buffer_file_pos_log==0) ||
698                     (sp->in_buffer_file_pos-sp->in_buffer_togo!=sp->sos_end[s].in_buffer_file_pos))
699                 {
700                         sp->in_buffer_source=sp->sos_end[s].in_buffer_source;
701                         sp->in_buffer_next_strile=sp->sos_end[s].in_buffer_next_strile;
702                         sp->in_buffer_file_pos=sp->sos_end[s].in_buffer_file_pos;
703                         sp->in_buffer_file_pos_log=0;
704                         sp->in_buffer_file_togo=sp->sos_end[s].in_buffer_file_togo;
705                         sp->in_buffer_togo=0;
706                         sp->in_buffer_cur=0;
707                 }
708                 if (OJPEGWriteHeaderInfo(tif)==0)
709                         return(0);
710         }
711         while (sp->write_curstrile<m)          
712         {
713                 if (sp->libjpeg_jpeg_query_style==0)
714                 {
715                         if (OJPEGPreDecodeSkipRaw(tif)==0)
716                                 return(0);
717                 }
718                 else
719                 {
720                         if (OJPEGPreDecodeSkipScanlines(tif)==0)
721                                 return(0);
722                 }
723                 sp->write_curstrile++;
724         }
725         sp->decoder_ok = 1;
726         return(1);
727 }
728
729 static int
730 OJPEGPreDecodeSkipRaw(TIFF* tif)
731 {
732         OJPEGState* sp=(OJPEGState*)tif->tif_data;
733         uint32 m;
734         m=sp->lines_per_strile;
735         if (sp->subsampling_convert_state!=0)
736         {
737                 if (sp->subsampling_convert_clines-sp->subsampling_convert_state>=m)
738                 {
739                         sp->subsampling_convert_state+=m;
740                         if (sp->subsampling_convert_state==sp->subsampling_convert_clines)
741                                 sp->subsampling_convert_state=0;
742                         return(1);
743                 }
744                 m-=sp->subsampling_convert_clines-sp->subsampling_convert_state;
745                 sp->subsampling_convert_state=0;
746                 sp->error_in_raw_data_decoding=0;
747         }
748         while (m>=sp->subsampling_convert_clines)
749         {
750                 if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0)
751                         return(0);
752                 m-=sp->subsampling_convert_clines;
753         }
754         if (m>0)
755         {
756                 if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0)
757                         return(0);
758                 sp->subsampling_convert_state=m;
759         }
760         return(1);
761 }
762
763 static int
764 OJPEGPreDecodeSkipScanlines(TIFF* tif)
765 {
766         static const char module[]="OJPEGPreDecodeSkipScanlines";
767         OJPEGState* sp=(OJPEGState*)tif->tif_data;
768         uint32 m;
769         if (sp->skip_buffer==NULL)
770         {
771                 sp->skip_buffer=_TIFFmalloc(sp->bytes_per_line);
772                 if (sp->skip_buffer==NULL)
773                 {
774                         TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
775                         return(0);
776                 }
777         }
778         for (m=0; m<sp->lines_per_strile; m++)
779         {
780                 if (jpeg_read_scanlines_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),&sp->skip_buffer,1)==0)
781                         return(0);
782         }
783         return(1);
784 }
785
786 static int
787 OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
788 {
789         static const char module[]="OJPEGDecode";
790         OJPEGState* sp=(OJPEGState*)tif->tif_data;
791         (void)s;
792         if( !sp->decoder_ok )
793         {
794             TIFFErrorExt(tif->tif_clientdata,module,"Cannot decode: decoder not correctly initialized");
795             return 0;
796         }
797         if( sp->error_in_raw_data_decoding )
798         {
799             return 0;
800         }
801         if (sp->libjpeg_jpeg_query_style==0)
802         {
803                 if (OJPEGDecodeRaw(tif,buf,cc)==0)
804                         return(0);
805         }
806         else
807         {
808                 if (OJPEGDecodeScanlines(tif,buf,cc)==0)
809                         return(0);
810         }
811         return(1);
812 }
813
814 static int
815 OJPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc)
816 {
817         static const char module[]="OJPEGDecodeRaw";
818         OJPEGState* sp=(OJPEGState*)tif->tif_data;
819         uint8* m;
820         tmsize_t n;
821         uint8* oy;
822         uint8* ocb;
823         uint8* ocr;
824         uint8* p;
825         uint32 q;
826         uint8* r;
827         uint8 sx,sy;
828         if (cc%sp->bytes_per_line!=0)
829         {
830                 TIFFErrorExt(tif->tif_clientdata,module,"Fractional scanline not read");
831                 return(0);
832         }
833         assert(cc>0);
834         m=buf;
835         n=cc;
836         do
837         {
838                 if (sp->subsampling_convert_state==0)
839                 {
840                         const jpeg_decompress_struct* cinfo = &sp->libjpeg_jpeg_decompress_struct;
841                         int width = 0;
842                         int last_col_width = 0;
843                         int jpeg_bytes;
844                         int expected_bytes;
845                         int i;
846                         if (cinfo->MCUs_per_row == 0)
847                         {
848                                 sp->error_in_raw_data_decoding = 1;
849                                 return 0;
850                         }
851                         for (i = 0; i < cinfo->comps_in_scan; ++i)
852                         {
853                                 const jpeg_component_info* info = cinfo->cur_comp_info[i];
854 #if JPEG_LIB_VERSION >= 70
855                                 width += info->MCU_width * info->DCT_h_scaled_size;
856                                 last_col_width += info->last_col_width * info->DCT_h_scaled_size;
857 #else
858                                 width += info->MCU_width * info->DCT_scaled_size;
859                                 last_col_width += info->last_col_width * info->DCT_scaled_size;
860 #endif
861                         }
862                         jpeg_bytes = (cinfo->MCUs_per_row - 1) * width + last_col_width;
863                         expected_bytes = sp->subsampling_convert_clinelenout * sp->subsampling_ver * sp->subsampling_hor;
864                         if (jpeg_bytes != expected_bytes)
865                         {
866                                 TIFFErrorExt(tif->tif_clientdata,module,"Inconsistent number of MCU in codestream");
867                                 sp->error_in_raw_data_decoding = 1;
868                                 return(0);
869                         }
870                         if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0)
871                         {
872                                 sp->error_in_raw_data_decoding = 1;
873                                 return(0);
874                         }
875                 }
876                 oy=sp->subsampling_convert_ybuf+sp->subsampling_convert_state*sp->subsampling_ver*sp->subsampling_convert_ylinelen;
877                 ocb=sp->subsampling_convert_cbbuf+sp->subsampling_convert_state*sp->subsampling_convert_clinelen;
878                 ocr=sp->subsampling_convert_crbuf+sp->subsampling_convert_state*sp->subsampling_convert_clinelen;
879                 p=m;
880                 for (q=0; q<sp->subsampling_convert_clinelenout; q++)
881                 {
882                         r=oy;
883                         for (sy=0; sy<sp->subsampling_ver; sy++)
884                         {
885                                 for (sx=0; sx<sp->subsampling_hor; sx++)
886                                         *p++=*r++;
887                                 r+=sp->subsampling_convert_ylinelen-sp->subsampling_hor;
888                         }
889                         oy+=sp->subsampling_hor;
890                         *p++=*ocb++;
891                         *p++=*ocr++;
892                 }
893                 sp->subsampling_convert_state++;
894                 if (sp->subsampling_convert_state==sp->subsampling_convert_clines)
895                         sp->subsampling_convert_state=0;
896                 m+=sp->bytes_per_line;
897                 n-=sp->bytes_per_line;
898         } while(n>0);
899         return(1);
900 }
901
902 static int
903 OJPEGDecodeScanlines(TIFF* tif, uint8* buf, tmsize_t cc)
904 {
905         static const char module[]="OJPEGDecodeScanlines";
906         OJPEGState* sp=(OJPEGState*)tif->tif_data;
907         uint8* m;
908         tmsize_t n;
909         if (cc%sp->bytes_per_line!=0)
910         {
911                 TIFFErrorExt(tif->tif_clientdata,module,"Fractional scanline not read");
912                 return(0);
913         }
914         assert(cc>0);
915         m=buf;
916         n=cc;
917         do
918         {
919                 if (jpeg_read_scanlines_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),&m,1)==0)
920                         return(0);
921                 m+=sp->bytes_per_line;
922                 n-=sp->bytes_per_line;
923         } while(n>0);
924         return(1);
925 }
926
927 static void
928 OJPEGPostDecode(TIFF* tif, uint8* buf, tmsize_t cc)
929 {
930         OJPEGState* sp=(OJPEGState*)tif->tif_data;
931         (void)buf;
932         (void)cc;
933         sp->write_curstrile++;
934         if (sp->write_curstrile%tif->tif_dir.td_stripsperimage==0)  
935         {
936                 assert(sp->libjpeg_session_active!=0);
937                 OJPEGLibjpegSessionAbort(tif);
938                 sp->writeheader_done=0;
939         }
940 }
941
942 static int
943 OJPEGSetupEncode(TIFF* tif)
944 {
945         static const char module[]="OJPEGSetupEncode";
946         TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
947         return(0);
948 }
949
950 static int
951 OJPEGPreEncode(TIFF* tif, uint16 s)
952 {
953         static const char module[]="OJPEGPreEncode";
954         (void)s;
955         TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
956         return(0);
957 }
958
959 static int
960 OJPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
961 {
962         static const char module[]="OJPEGEncode";
963         (void)buf;
964         (void)cc;
965         (void)s;
966         TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
967         return(0);
968 }
969
970 static int
971 OJPEGPostEncode(TIFF* tif)
972 {
973         static const char module[]="OJPEGPostEncode";
974         TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
975         return(0);
976 }
977
978 static void
979 OJPEGCleanup(TIFF* tif)
980 {
981         OJPEGState* sp=(OJPEGState*)tif->tif_data;
982         if (sp!=0)
983         {
984                 tif->tif_tagmethods.vgetfield=sp->vgetparent;
985                 tif->tif_tagmethods.vsetfield=sp->vsetparent;
986                 tif->tif_tagmethods.printdir=sp->printdir;
987                 if (sp->qtable[0]!=0)
988                         _TIFFfree(sp->qtable[0]);
989                 if (sp->qtable[1]!=0)
990                         _TIFFfree(sp->qtable[1]);
991                 if (sp->qtable[2]!=0)
992                         _TIFFfree(sp->qtable[2]);
993                 if (sp->qtable[3]!=0)
994                         _TIFFfree(sp->qtable[3]);
995                 if (sp->dctable[0]!=0)
996                         _TIFFfree(sp->dctable[0]);
997                 if (sp->dctable[1]!=0)
998                         _TIFFfree(sp->dctable[1]);
999                 if (sp->dctable[2]!=0)
1000                         _TIFFfree(sp->dctable[2]);
1001                 if (sp->dctable[3]!=0)
1002                         _TIFFfree(sp->dctable[3]);
1003                 if (sp->actable[0]!=0)
1004                         _TIFFfree(sp->actable[0]);
1005                 if (sp->actable[1]!=0)
1006                         _TIFFfree(sp->actable[1]);
1007                 if (sp->actable[2]!=0)
1008                         _TIFFfree(sp->actable[2]);
1009                 if (sp->actable[3]!=0)
1010                         _TIFFfree(sp->actable[3]);
1011                 if (sp->libjpeg_session_active!=0)
1012                         OJPEGLibjpegSessionAbort(tif);
1013                 if (sp->subsampling_convert_ycbcrbuf!=0)
1014                         _TIFFfree(sp->subsampling_convert_ycbcrbuf);
1015                 if (sp->subsampling_convert_ycbcrimage!=0)
1016                         _TIFFfree(sp->subsampling_convert_ycbcrimage);
1017                 if (sp->skip_buffer!=0)
1018                         _TIFFfree(sp->skip_buffer);
1019                 _TIFFfree(sp);
1020                 tif->tif_data=NULL;
1021                 _TIFFSetDefaultCompressionState(tif);
1022         }
1023 }
1024
1025 static void
1026 OJPEGSubsamplingCorrect(TIFF* tif)
1027 {
1028         static const char module[]="OJPEGSubsamplingCorrect";
1029         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1030         uint8 mh;
1031         uint8 mv;
1032         
1033         assert(sp->subsamplingcorrect_done==0);
1034         if ((tif->tif_dir.td_samplesperpixel!=3) || ((tif->tif_dir.td_photometric!=PHOTOMETRIC_YCBCR) &&
1035             (tif->tif_dir.td_photometric!=PHOTOMETRIC_ITULAB)))
1036         {
1037                 if (sp->subsampling_tag!=0)
1038                         TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag not appropriate for this Photometric and/or SamplesPerPixel");
1039                 sp->subsampling_hor=1;
1040                 sp->subsampling_ver=1;
1041                 sp->subsampling_force_desubsampling_inside_decompression=0;
1042         }
1043         else
1044         {
1045                 sp->subsamplingcorrect_done=1;
1046                 mh=sp->subsampling_hor;
1047                 mv=sp->subsampling_ver;
1048                 sp->subsamplingcorrect=1;
1049                 OJPEGReadHeaderInfoSec(tif);
1050                 if (sp->subsampling_force_desubsampling_inside_decompression!=0)
1051                 {
1052                         sp->subsampling_hor=1;
1053                         sp->subsampling_ver=1;
1054                 }
1055                 sp->subsamplingcorrect=0;
1056                 if (((sp->subsampling_hor!=mh) || (sp->subsampling_ver!=mv)) && (sp->subsampling_force_desubsampling_inside_decompression==0))
1057                 {
1058                         if (sp->subsampling_tag==0)
1059                                 TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag is not set, yet subsampling inside JPEG data [%d,%d] does not match default values [2,2]; assuming subsampling inside JPEG data is correct",sp->subsampling_hor,sp->subsampling_ver);
1060                         else
1061                                 TIFFWarningExt(tif->tif_clientdata,module,"Subsampling inside JPEG data [%d,%d] does not match subsampling tag values [%d,%d]; assuming subsampling inside JPEG data is correct",sp->subsampling_hor,sp->subsampling_ver,mh,mv);
1062                 }
1063                 if (sp->subsampling_force_desubsampling_inside_decompression!=0)
1064                 {
1065                         if (sp->subsampling_tag==0)
1066                                 TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag is not set, yet subsampling inside JPEG data does not match default values [2,2] (nor any other values allowed in TIFF); assuming subsampling inside JPEG data is correct and desubsampling inside JPEG decompression");
1067                         else
1068                                 TIFFWarningExt(tif->tif_clientdata,module,"Subsampling inside JPEG data does not match subsampling tag values [%d,%d] (nor any other values allowed in TIFF); assuming subsampling inside JPEG data is correct and desubsampling inside JPEG decompression",mh,mv);
1069                 }
1070                 if (sp->subsampling_force_desubsampling_inside_decompression==0)
1071                 {
1072                         if (sp->subsampling_hor<sp->subsampling_ver)
1073                                 TIFFWarningExt(tif->tif_clientdata,module,"Subsampling values [%d,%d] are not allowed in TIFF",sp->subsampling_hor,sp->subsampling_ver);
1074                 }
1075         }
1076         sp->subsamplingcorrect_done=1;
1077 }
1078
1079 static int
1080 OJPEGReadHeaderInfo(TIFF* tif)
1081 {
1082         static const char module[]="OJPEGReadHeaderInfo";
1083         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1084         assert(sp->readheader_done==0);
1085         sp->image_width=tif->tif_dir.td_imagewidth;
1086         sp->image_length=tif->tif_dir.td_imagelength;
1087         if (isTiled(tif))
1088         {
1089                 sp->strile_width=tif->tif_dir.td_tilewidth;
1090                 sp->strile_length=tif->tif_dir.td_tilelength;
1091                 sp->strile_length_total=((sp->image_length+sp->strile_length-1)/sp->strile_length)*sp->strile_length;
1092         }
1093         else
1094         {
1095                 sp->strile_width=sp->image_width;
1096                 sp->strile_length=tif->tif_dir.td_rowsperstrip;
1097                 sp->strile_length_total=sp->image_length;
1098         }
1099         if (tif->tif_dir.td_samplesperpixel==1)
1100         {
1101                 sp->samples_per_pixel=1;
1102                 sp->plane_sample_offset=0;
1103                 sp->samples_per_pixel_per_plane=sp->samples_per_pixel;
1104                 sp->subsampling_hor=1;
1105                 sp->subsampling_ver=1;
1106         }
1107         else
1108         {
1109                 if (tif->tif_dir.td_samplesperpixel!=3)
1110                 {
1111                         TIFFErrorExt(tif->tif_clientdata,module,"SamplesPerPixel %d not supported for this compression scheme",sp->samples_per_pixel);
1112                         return(0);
1113                 }
1114                 sp->samples_per_pixel=3;
1115                 sp->plane_sample_offset=0;
1116                 if (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)
1117                         sp->samples_per_pixel_per_plane=3;
1118                 else
1119                         sp->samples_per_pixel_per_plane=1;
1120         }
1121         if (sp->strile_length<sp->image_length)
1122         {
1123                 if (((sp->subsampling_hor!=1) && (sp->subsampling_hor!=2) && (sp->subsampling_hor!=4)) ||
1124                     ((sp->subsampling_ver!=1) && (sp->subsampling_ver!=2) && (sp->subsampling_ver!=4)))
1125                 {
1126                         TIFFErrorExt(tif->tif_clientdata,module,"Invalid subsampling values");
1127                         return(0);
1128                 }
1129                 if (sp->strile_length%(sp->subsampling_ver*8)!=0)
1130                 {
1131                         TIFFErrorExt(tif->tif_clientdata,module,"Incompatible vertical subsampling and image strip/tile length");
1132                         return(0);
1133                 }
1134                 sp->restart_interval=(uint16)(((sp->strile_width+sp->subsampling_hor*8-1)/(sp->subsampling_hor*8))*(sp->strile_length/(sp->subsampling_ver*8)));
1135         }
1136         if (OJPEGReadHeaderInfoSec(tif)==0)
1137                 return(0);
1138         sp->sos_end[0].log=1;
1139         sp->sos_end[0].in_buffer_source=sp->in_buffer_source;
1140         sp->sos_end[0].in_buffer_next_strile=sp->in_buffer_next_strile;
1141         sp->sos_end[0].in_buffer_file_pos=sp->in_buffer_file_pos-sp->in_buffer_togo;
1142         sp->sos_end[0].in_buffer_file_togo=sp->in_buffer_file_togo+sp->in_buffer_togo; 
1143         sp->readheader_done=1;
1144         return(1);
1145 }
1146
1147 static int
1148 OJPEGReadSecondarySos(TIFF* tif, uint16 s)
1149 {
1150         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1151         uint8 m;
1152         assert(s>0);
1153         assert(s<3);
1154         assert(sp->sos_end[0].log!=0);
1155         assert(sp->sos_end[s].log==0);
1156         sp->plane_sample_offset=(uint8)(s-1);
1157         while(sp->sos_end[sp->plane_sample_offset].log==0)
1158                 sp->plane_sample_offset--;
1159         sp->in_buffer_source=sp->sos_end[sp->plane_sample_offset].in_buffer_source;
1160         sp->in_buffer_next_strile=sp->sos_end[sp->plane_sample_offset].in_buffer_next_strile;
1161         sp->in_buffer_file_pos=sp->sos_end[sp->plane_sample_offset].in_buffer_file_pos;
1162         sp->in_buffer_file_pos_log=0;
1163         sp->in_buffer_file_togo=sp->sos_end[sp->plane_sample_offset].in_buffer_file_togo;
1164         sp->in_buffer_togo=0;
1165         sp->in_buffer_cur=0;
1166         while(sp->plane_sample_offset<s)
1167         {
1168                 do
1169                 {
1170                         if (OJPEGReadByte(sp,&m)==0)
1171                                 return(0);
1172                         if (m==255)
1173                         {
1174                                 do
1175                                 {
1176                                         if (OJPEGReadByte(sp,&m)==0)
1177                                                 return(0);
1178                                         if (m!=255)
1179                                                 break;
1180                                 } while(1);
1181                                 if (m==JPEG_MARKER_SOS)
1182                                         break;
1183                         }
1184                 } while(1);
1185                 sp->plane_sample_offset++;
1186                 if (OJPEGReadHeaderInfoSecStreamSos(tif)==0)
1187                         return(0);
1188                 sp->sos_end[sp->plane_sample_offset].log=1;
1189                 sp->sos_end[sp->plane_sample_offset].in_buffer_source=sp->in_buffer_source;
1190                 sp->sos_end[sp->plane_sample_offset].in_buffer_next_strile=sp->in_buffer_next_strile;
1191                 sp->sos_end[sp->plane_sample_offset].in_buffer_file_pos=sp->in_buffer_file_pos-sp->in_buffer_togo;
1192                 sp->sos_end[sp->plane_sample_offset].in_buffer_file_togo=sp->in_buffer_file_togo+sp->in_buffer_togo;
1193         }
1194         return(1);
1195 }
1196
1197 static int
1198 OJPEGWriteHeaderInfo(TIFF* tif)
1199 {
1200         static const char module[]="OJPEGWriteHeaderInfo";
1201         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1202         uint8** m;
1203         uint32 n;
1204         /* if a previous attempt failed, don't try again */
1205         if (sp->libjpeg_session_active != 0) 
1206                 return 0;
1207         sp->out_state=ososSoi;
1208         sp->restart_index=0;
1209         jpeg_std_error(&(sp->libjpeg_jpeg_error_mgr));
1210         sp->libjpeg_jpeg_error_mgr.output_message=OJPEGLibjpegJpegErrorMgrOutputMessage;
1211         sp->libjpeg_jpeg_error_mgr.error_exit=OJPEGLibjpegJpegErrorMgrErrorExit;
1212         sp->libjpeg_jpeg_decompress_struct.err=&(sp->libjpeg_jpeg_error_mgr);
1213         sp->libjpeg_jpeg_decompress_struct.client_data=(void*)tif;
1214         if (jpeg_create_decompress_encap(sp,&(sp->libjpeg_jpeg_decompress_struct))==0)
1215                 return(0);
1216         sp->libjpeg_session_active=1;
1217         sp->libjpeg_jpeg_source_mgr.bytes_in_buffer=0;
1218         sp->libjpeg_jpeg_source_mgr.init_source=OJPEGLibjpegJpegSourceMgrInitSource;
1219         sp->libjpeg_jpeg_source_mgr.fill_input_buffer=OJPEGLibjpegJpegSourceMgrFillInputBuffer;
1220         sp->libjpeg_jpeg_source_mgr.skip_input_data=OJPEGLibjpegJpegSourceMgrSkipInputData;
1221         sp->libjpeg_jpeg_source_mgr.resync_to_restart=OJPEGLibjpegJpegSourceMgrResyncToRestart;
1222         sp->libjpeg_jpeg_source_mgr.term_source=OJPEGLibjpegJpegSourceMgrTermSource;
1223         sp->libjpeg_jpeg_decompress_struct.src=&(sp->libjpeg_jpeg_source_mgr);
1224         if (jpeg_read_header_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),1)==0)
1225                 return(0);
1226         if ((sp->subsampling_force_desubsampling_inside_decompression==0) && (sp->samples_per_pixel_per_plane>1))
1227         {
1228                 sp->libjpeg_jpeg_decompress_struct.raw_data_out=1;
1229 #if JPEG_LIB_VERSION >= 70
1230                 sp->libjpeg_jpeg_decompress_struct.do_fancy_upsampling=FALSE;
1231 #endif
1232                 sp->libjpeg_jpeg_query_style=0;
1233                 if (sp->subsampling_convert_log==0)
1234                 {
1235                         assert(sp->subsampling_convert_ycbcrbuf==0);
1236                         assert(sp->subsampling_convert_ycbcrimage==0);
1237                         sp->subsampling_convert_ylinelen=((sp->strile_width+sp->subsampling_hor*8-1)/(sp->subsampling_hor*8)*sp->subsampling_hor*8);
1238                         sp->subsampling_convert_ylines=sp->subsampling_ver*8;
1239                         sp->subsampling_convert_clinelen=sp->subsampling_convert_ylinelen/sp->subsampling_hor;
1240                         sp->subsampling_convert_clines=8;
1241                         sp->subsampling_convert_ybuflen=sp->subsampling_convert_ylinelen*sp->subsampling_convert_ylines;
1242                         sp->subsampling_convert_cbuflen=sp->subsampling_convert_clinelen*sp->subsampling_convert_clines;
1243                         sp->subsampling_convert_ycbcrbuflen=sp->subsampling_convert_ybuflen+2*sp->subsampling_convert_cbuflen;
1244                         /* The calloc is not normally necessary, except in some edge/broken cases */
1245                         /* for example for a tiled image of height 1 with a tile height of 1 and subsampling_hor=subsampling_ver=2 */
1246                         /* In that case, libjpeg will only fill the 8 first lines of the 16 lines */
1247                         /* See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=16844 */
1248                         /* Even if this case is allowed (?), its handling is broken because OJPEGPreDecode() should also likely */
1249                         /* reset subsampling_convert_state to 0 when changing tile. */
1250                         sp->subsampling_convert_ycbcrbuf=_TIFFcalloc(1, sp->subsampling_convert_ycbcrbuflen);
1251                         if (sp->subsampling_convert_ycbcrbuf==0)
1252                         {
1253                                 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1254                                 return(0);
1255                         }
1256                         sp->subsampling_convert_ybuf=sp->subsampling_convert_ycbcrbuf;
1257                         sp->subsampling_convert_cbbuf=sp->subsampling_convert_ybuf+sp->subsampling_convert_ybuflen;
1258                         sp->subsampling_convert_crbuf=sp->subsampling_convert_cbbuf+sp->subsampling_convert_cbuflen;
1259                         sp->subsampling_convert_ycbcrimagelen=3+sp->subsampling_convert_ylines+2*sp->subsampling_convert_clines;
1260                         sp->subsampling_convert_ycbcrimage=_TIFFmalloc(sp->subsampling_convert_ycbcrimagelen*sizeof(uint8*));
1261                         if (sp->subsampling_convert_ycbcrimage==0)
1262                         {
1263                                 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1264                                 return(0);
1265                         }
1266                         m=sp->subsampling_convert_ycbcrimage;
1267                         *m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3);
1268                         *m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3+sp->subsampling_convert_ylines);
1269                         *m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3+sp->subsampling_convert_ylines+sp->subsampling_convert_clines);
1270                         for (n=0; n<sp->subsampling_convert_ylines; n++)
1271                                 *m++=sp->subsampling_convert_ybuf+n*sp->subsampling_convert_ylinelen;
1272                         for (n=0; n<sp->subsampling_convert_clines; n++)
1273                                 *m++=sp->subsampling_convert_cbbuf+n*sp->subsampling_convert_clinelen;
1274                         for (n=0; n<sp->subsampling_convert_clines; n++)
1275                                 *m++=sp->subsampling_convert_crbuf+n*sp->subsampling_convert_clinelen;
1276                         sp->subsampling_convert_clinelenout=sp->strile_width/sp->subsampling_hor + ((sp->strile_width % sp->subsampling_hor) != 0 ? 1 : 0);
1277                         sp->subsampling_convert_state=0;
1278                         sp->error_in_raw_data_decoding=0;
1279                         sp->bytes_per_line=sp->subsampling_convert_clinelenout*(sp->subsampling_ver*sp->subsampling_hor+2);
1280                         sp->lines_per_strile=sp->strile_length/sp->subsampling_ver + ((sp->strile_length % sp->subsampling_ver) != 0 ? 1 : 0);
1281                         sp->subsampling_convert_log=1;
1282                 }
1283         }
1284         else
1285         {
1286                 sp->libjpeg_jpeg_decompress_struct.jpeg_color_space=JCS_UNKNOWN;
1287                 sp->libjpeg_jpeg_decompress_struct.out_color_space=JCS_UNKNOWN;
1288                 sp->libjpeg_jpeg_query_style=1;
1289                 sp->bytes_per_line=sp->samples_per_pixel_per_plane*sp->strile_width;
1290                 sp->lines_per_strile=sp->strile_length;
1291         }
1292         if (jpeg_start_decompress_encap(sp,&(sp->libjpeg_jpeg_decompress_struct))==0)
1293                 return(0);
1294         sp->writeheader_done=1;
1295         return(1);
1296 }
1297
1298 static void
1299 OJPEGLibjpegSessionAbort(TIFF* tif)
1300 {
1301         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1302         assert(sp->libjpeg_session_active!=0);
1303         jpeg_destroy((jpeg_common_struct*)(&(sp->libjpeg_jpeg_decompress_struct)));
1304         sp->libjpeg_session_active=0;
1305 }
1306
1307 static int
1308 OJPEGReadHeaderInfoSec(TIFF* tif)
1309 {
1310         static const char module[]="OJPEGReadHeaderInfoSec";
1311         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1312         uint8 m;
1313         uint16 n;
1314         uint8 o;
1315         if (sp->file_size==0)
1316                 sp->file_size=TIFFGetFileSize(tif);
1317         if (sp->jpeg_interchange_format!=0)
1318         {
1319                 if (sp->jpeg_interchange_format>=sp->file_size)
1320                 {
1321                         sp->jpeg_interchange_format=0;
1322                         sp->jpeg_interchange_format_length=0;
1323                 }
1324                 else
1325                 {
1326                         if ((sp->jpeg_interchange_format_length==0) ||
1327                             (sp->jpeg_interchange_format > TIFF_UINT64_MAX - sp->jpeg_interchange_format_length) ||
1328                             (sp->jpeg_interchange_format+sp->jpeg_interchange_format_length>sp->file_size))
1329                                 sp->jpeg_interchange_format_length=sp->file_size-sp->jpeg_interchange_format;
1330                 }
1331         }
1332         sp->in_buffer_source=osibsNotSetYet;
1333         sp->in_buffer_next_strile=0;
1334         sp->in_buffer_strile_count=tif->tif_dir.td_nstrips;
1335         sp->in_buffer_file_togo=0;
1336         sp->in_buffer_togo=0;
1337         do
1338         {
1339                 if (OJPEGReadBytePeek(sp,&m)==0)
1340                         return(0);
1341                 if (m!=255)
1342                         break;
1343                 OJPEGReadByteAdvance(sp);
1344                 do
1345                 {
1346                         if (OJPEGReadByte(sp,&m)==0)
1347                                 return(0);
1348                 } while(m==255);
1349                 switch(m)
1350                 {
1351                         case JPEG_MARKER_SOI:
1352                                 /* this type of marker has no data, and should be skipped */
1353                                 break;
1354                         case JPEG_MARKER_COM:
1355                         case JPEG_MARKER_APP0:
1356                         case JPEG_MARKER_APP0+1:
1357                         case JPEG_MARKER_APP0+2:
1358                         case JPEG_MARKER_APP0+3:
1359                         case JPEG_MARKER_APP0+4:
1360                         case JPEG_MARKER_APP0+5:
1361                         case JPEG_MARKER_APP0+6:
1362                         case JPEG_MARKER_APP0+7:
1363                         case JPEG_MARKER_APP0+8:
1364                         case JPEG_MARKER_APP0+9:
1365                         case JPEG_MARKER_APP0+10:
1366                         case JPEG_MARKER_APP0+11:
1367                         case JPEG_MARKER_APP0+12:
1368                         case JPEG_MARKER_APP0+13:
1369                         case JPEG_MARKER_APP0+14:
1370                         case JPEG_MARKER_APP0+15:
1371                                 /* this type of marker has data, but it has no use to us (and no place here) and should be skipped */
1372                                 if (OJPEGReadWord(sp,&n)==0)
1373                                         return(0);
1374                                 if (n<2)
1375                                 {
1376                                         if (sp->subsamplingcorrect==0)
1377                                                 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JPEG data");
1378                                         return(0);
1379                                 }
1380                                 if (n>2)
1381                                         OJPEGReadSkip(sp,n-2);
1382                                 break;
1383                         case JPEG_MARKER_DRI:
1384                                 if (OJPEGReadHeaderInfoSecStreamDri(tif)==0)
1385                                         return(0);
1386                                 break;
1387                         case JPEG_MARKER_DQT:
1388                                 if (OJPEGReadHeaderInfoSecStreamDqt(tif)==0)
1389                                         return(0);
1390                                 break;
1391                         case JPEG_MARKER_DHT:
1392                                 if (OJPEGReadHeaderInfoSecStreamDht(tif)==0)
1393                                         return(0);
1394                                 break;
1395                         case JPEG_MARKER_SOF0:
1396                         case JPEG_MARKER_SOF1:
1397                         case JPEG_MARKER_SOF3:
1398                                 if (OJPEGReadHeaderInfoSecStreamSof(tif,m)==0)
1399                                         return(0);
1400                                 if (sp->subsamplingcorrect!=0)
1401                                         return(1);
1402                                 break;
1403                         case JPEG_MARKER_SOS:
1404                                 if (sp->subsamplingcorrect!=0)
1405                                         return(1);
1406                                 assert(sp->plane_sample_offset==0);
1407                                 if (OJPEGReadHeaderInfoSecStreamSos(tif)==0)
1408                                         return(0);
1409                                 break;
1410                         default:
1411                                 TIFFErrorExt(tif->tif_clientdata,module,"Unknown marker type %d in JPEG data",m);
1412                                 return(0);
1413                 }
1414         } while(m!=JPEG_MARKER_SOS);
1415         if (sp->subsamplingcorrect)
1416                 return(1);
1417         if (sp->sof_log==0)
1418         {
1419                 if (OJPEGReadHeaderInfoSecTablesQTable(tif)==0)
1420                         return(0);
1421                 sp->sof_marker_id=JPEG_MARKER_SOF0;
1422                 for (o=0; o<sp->samples_per_pixel; o++)
1423                         sp->sof_c[o]=o;
1424                 sp->sof_hv[0]=((sp->subsampling_hor<<4)|sp->subsampling_ver);
1425                 for (o=1; o<sp->samples_per_pixel; o++)
1426                         sp->sof_hv[o]=17;
1427                 sp->sof_x=sp->strile_width;
1428                 sp->sof_y=sp->strile_length_total;
1429                 sp->sof_log=1;
1430                 if (OJPEGReadHeaderInfoSecTablesDcTable(tif)==0)
1431                         return(0);
1432                 if (OJPEGReadHeaderInfoSecTablesAcTable(tif)==0)
1433                         return(0);
1434                 for (o=1; o<sp->samples_per_pixel; o++)
1435                         sp->sos_cs[o]=o;
1436         }
1437         return(1);
1438 }
1439
1440 static int
1441 OJPEGReadHeaderInfoSecStreamDri(TIFF* tif)
1442 {
1443         /* This could easily cause trouble in some cases... but no such cases have
1444            occurred so far */
1445         static const char module[]="OJPEGReadHeaderInfoSecStreamDri";
1446         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1447         uint16 m;
1448         if (OJPEGReadWord(sp,&m)==0)
1449                 return(0);
1450         if (m!=4)
1451         {
1452                 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DRI marker in JPEG data");
1453                 return(0);
1454         }
1455         if (OJPEGReadWord(sp,&m)==0)
1456                 return(0);
1457         sp->restart_interval=m;
1458         return(1);
1459 }
1460
1461 static int
1462 OJPEGReadHeaderInfoSecStreamDqt(TIFF* tif)
1463 {
1464         /* this is a table marker, and it is to be saved as a whole for exact pushing on the jpeg stream later on */
1465         static const char module[]="OJPEGReadHeaderInfoSecStreamDqt";
1466         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1467         uint16 m;
1468         uint32 na;
1469         uint8* nb;
1470         uint8 o;
1471         if (OJPEGReadWord(sp,&m)==0)
1472                 return(0);
1473         if (m<=2)
1474         {
1475                 if (sp->subsamplingcorrect==0)
1476                         TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data");
1477                 return(0);
1478         }
1479         if (sp->subsamplingcorrect!=0)
1480                 OJPEGReadSkip(sp,m-2);
1481         else
1482         {
1483                 m-=2;
1484                 do
1485                 {
1486                         if (m<65)
1487                         {
1488                                 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data");
1489                                 return(0);
1490                         }
1491                         na=sizeof(uint32)+69;
1492                         nb=_TIFFmalloc(na);
1493                         if (nb==0)
1494                         {
1495                                 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1496                                 return(0);
1497                         }
1498                         *(uint32*)nb=na;
1499                         nb[sizeof(uint32)]=255;
1500                         nb[sizeof(uint32)+1]=JPEG_MARKER_DQT;
1501                         nb[sizeof(uint32)+2]=0;
1502                         nb[sizeof(uint32)+3]=67;
1503                         if (OJPEGReadBlock(sp,65,&nb[sizeof(uint32)+4])==0) {
1504                                 _TIFFfree(nb);
1505                                 return(0);
1506                         }
1507                         o=nb[sizeof(uint32)+4]&15;
1508                         if (3<o)
1509                         {
1510                                 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data");
1511                                 _TIFFfree(nb);
1512                                 return(0);
1513                         }
1514                         if (sp->qtable[o]!=0)
1515                                 _TIFFfree(sp->qtable[o]);
1516                         sp->qtable[o]=nb;
1517                         m-=65;
1518                 } while(m>0);
1519         }
1520         return(1);
1521 }
1522
1523 static int
1524 OJPEGReadHeaderInfoSecStreamDht(TIFF* tif)
1525 {
1526         /* this is a table marker, and it is to be saved as a whole for exact pushing on the jpeg stream later on */
1527         /* TODO: the following assumes there is only one table in this marker... but i'm not quite sure that assumption is guaranteed correct */
1528         static const char module[]="OJPEGReadHeaderInfoSecStreamDht";
1529         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1530         uint16 m;
1531         uint32 na;
1532         uint8* nb;
1533         uint8 o;
1534         if (OJPEGReadWord(sp,&m)==0)
1535                 return(0);
1536         if (m<=2)
1537         {
1538                 if (sp->subsamplingcorrect==0)
1539                         TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
1540                 return(0);
1541         }
1542         if (sp->subsamplingcorrect!=0)
1543         {
1544                 OJPEGReadSkip(sp,m-2);
1545         }
1546         else
1547         {
1548                 na=sizeof(uint32)+2+m;
1549                 nb=_TIFFmalloc(na);
1550                 if (nb==0)
1551                 {
1552                         TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1553                         return(0);
1554                 }
1555                 *(uint32*)nb=na;
1556                 nb[sizeof(uint32)]=255;
1557                 nb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
1558                 nb[sizeof(uint32)+2]=(m>>8);
1559                 nb[sizeof(uint32)+3]=(m&255);
1560                 if (OJPEGReadBlock(sp,m-2,&nb[sizeof(uint32)+4])==0) {
1561                         _TIFFfree(nb);
1562                         return(0);
1563                 }
1564                 o=nb[sizeof(uint32)+4];
1565                 if ((o&240)==0)
1566                 {
1567                         if (3<o)
1568                         {
1569                                 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
1570                                 _TIFFfree(nb);
1571                                 return(0);
1572                         }
1573                         if (sp->dctable[o]!=0)
1574                                 _TIFFfree(sp->dctable[o]);
1575                         sp->dctable[o]=nb;
1576                 }
1577                 else
1578                 {
1579                         if ((o&240)!=16)
1580                         {
1581                                 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
1582                                 _TIFFfree(nb);
1583                                 return(0);
1584                         }
1585                         o&=15;
1586                         if (3<o)
1587                         {
1588                                 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
1589                                 _TIFFfree(nb);
1590                                 return(0);
1591                         }
1592                         if (sp->actable[o]!=0)
1593                                 _TIFFfree(sp->actable[o]);
1594                         sp->actable[o]=nb;
1595                 }
1596         }
1597         return(1);
1598 }
1599
1600 static int
1601 OJPEGReadHeaderInfoSecStreamSof(TIFF* tif, uint8 marker_id)
1602 {
1603         /* this marker needs to be checked, and part of its data needs to be saved for regeneration later on */
1604         static const char module[]="OJPEGReadHeaderInfoSecStreamSof";
1605         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1606         uint16 m;
1607         uint16 n;
1608         uint8 o;
1609         uint16 p;
1610         uint16 q;
1611         if (sp->sof_log!=0)
1612         {
1613                 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JPEG data");
1614                 return(0);
1615         }
1616         if (sp->subsamplingcorrect==0)
1617                 sp->sof_marker_id=marker_id;
1618         /* Lf: data length */
1619         if (OJPEGReadWord(sp,&m)==0)
1620                 return(0);
1621         if (m<11)
1622         {
1623                 if (sp->subsamplingcorrect==0)
1624                         TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data");
1625                 return(0);
1626         }
1627         m-=8;
1628         if (m%3!=0)
1629         {
1630                 if (sp->subsamplingcorrect==0)
1631                         TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data");
1632                 return(0);
1633         }
1634         n=m/3;
1635         if (sp->subsamplingcorrect==0)
1636         {
1637                 if (n!=sp->samples_per_pixel)
1638                 {
1639                         TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected number of samples");
1640                         return(0);
1641                 }
1642         }
1643         /* P: Sample precision */
1644         if (OJPEGReadByte(sp,&o)==0)
1645                 return(0);
1646         if (o!=8)
1647         {
1648                 if (sp->subsamplingcorrect==0)
1649                         TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected number of bits per sample");
1650                 return(0);
1651         }
1652         /* Y: Number of lines, X: Number of samples per line */
1653         if (sp->subsamplingcorrect)
1654                 OJPEGReadSkip(sp,4);
1655         else
1656         {
1657                 /* Y: Number of lines */
1658                 if (OJPEGReadWord(sp,&p)==0)
1659                         return(0);
1660                 if (((uint32)p<sp->image_length) && ((uint32)p<sp->strile_length_total))
1661                 {
1662                         TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected height");
1663                         return(0);
1664                 }
1665                 sp->sof_y=p;
1666                 /* X: Number of samples per line */
1667                 if (OJPEGReadWord(sp,&p)==0)
1668                         return(0);
1669                 if (((uint32)p<sp->image_width) && ((uint32)p<sp->strile_width))
1670                 {
1671                         TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected width");
1672                         return(0);
1673                 }
1674                 if ((uint32)p>sp->strile_width)
1675                 {
1676                         TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data image width exceeds expected image width");
1677                         return(0);
1678                 }
1679                 sp->sof_x=p;
1680         }
1681         /* Nf: Number of image components in frame */
1682         if (OJPEGReadByte(sp,&o)==0)
1683                 return(0);
1684         if (o!=n)
1685         {
1686                 if (sp->subsamplingcorrect==0)
1687                         TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data");
1688                 return(0);
1689         }
1690         /* per component stuff */
1691         /* TODO: double-check that flow implies that n cannot be as big as to make us overflow sof_c, sof_hv and sof_tq arrays */
1692         for (q=0; q<n; q++)
1693         {
1694                 /* C: Component identifier */
1695                 if (OJPEGReadByte(sp,&o)==0)
1696                         return(0);
1697                 if (sp->subsamplingcorrect==0)
1698                         sp->sof_c[q]=o;
1699                 /* H: Horizontal sampling factor, and V: Vertical sampling factor */
1700                 if (OJPEGReadByte(sp,&o)==0)
1701                         return(0);
1702                 if (sp->subsamplingcorrect!=0)
1703                 {
1704                         if (q==0)
1705                         {
1706                                 sp->subsampling_hor=(o>>4);
1707                                 sp->subsampling_ver=(o&15);
1708                                 if (((sp->subsampling_hor!=1) && (sp->subsampling_hor!=2) && (sp->subsampling_hor!=4)) ||
1709                                         ((sp->subsampling_ver!=1) && (sp->subsampling_ver!=2) && (sp->subsampling_ver!=4)))
1710                                         sp->subsampling_force_desubsampling_inside_decompression=1;
1711                         }
1712                         else
1713                         {
1714                                 if (o!=17)
1715                                         sp->subsampling_force_desubsampling_inside_decompression=1;
1716                         }
1717                 }
1718                 else
1719                 {
1720                         sp->sof_hv[q]=o;
1721                         if (sp->subsampling_force_desubsampling_inside_decompression==0)
1722                         {
1723                                 if (q==0)
1724                                 {
1725                                         if (o!=((sp->subsampling_hor<<4)|sp->subsampling_ver))
1726                                         {
1727                                                 TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected subsampling values");
1728                                                 return(0);
1729                                         }
1730                                 }
1731                                 else
1732                                 {
1733                                         if (o!=17)
1734                                         {
1735                                                 TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected subsampling values");
1736                                                 return(0);
1737                                         }
1738                                 }
1739                         }
1740                 }
1741                 /* Tq: Quantization table destination selector */
1742                 if (OJPEGReadByte(sp,&o)==0)
1743                         return(0);
1744                 if (sp->subsamplingcorrect==0)
1745                         sp->sof_tq[q]=o;
1746         }
1747         if (sp->subsamplingcorrect==0)
1748                 sp->sof_log=1;
1749         return(1);
1750 }
1751
1752 static int
1753 OJPEGReadHeaderInfoSecStreamSos(TIFF* tif)
1754 {
1755         /* this marker needs to be checked, and part of its data needs to be saved for regeneration later on */
1756         static const char module[]="OJPEGReadHeaderInfoSecStreamSos";
1757         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1758         uint16 m;
1759         uint8 n;
1760         uint8 o;
1761         assert(sp->subsamplingcorrect==0);
1762         if (sp->sof_log==0)
1763         {
1764                 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data");
1765                 return(0);
1766         }
1767         /* Ls */
1768         if (OJPEGReadWord(sp,&m)==0)
1769                 return(0);
1770         if (m!=6+sp->samples_per_pixel_per_plane*2)
1771         {
1772                 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data");
1773                 return(0);
1774         }
1775         /* Ns */
1776         if (OJPEGReadByte(sp,&n)==0)
1777                 return(0);
1778         if (n!=sp->samples_per_pixel_per_plane)
1779         {
1780                 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data");
1781                 return(0);
1782         }
1783         /* Cs, Td, and Ta */
1784         for (o=0; o<sp->samples_per_pixel_per_plane; o++)
1785         {
1786                 /* Cs */
1787                 if (OJPEGReadByte(sp,&n)==0)
1788                         return(0);
1789                 sp->sos_cs[sp->plane_sample_offset+o]=n;
1790                 /* Td and Ta */
1791                 if (OJPEGReadByte(sp,&n)==0)
1792                         return(0);
1793                 sp->sos_tda[sp->plane_sample_offset+o]=n;
1794         }
1795         /* skip Ss, Se, Ah, en Al -> no check, as per Tom Lane recommendation, as per LibJpeg source */
1796         OJPEGReadSkip(sp,3);
1797         return(1);
1798 }
1799
1800 static int
1801 OJPEGReadHeaderInfoSecTablesQTable(TIFF* tif)
1802 {
1803         static const char module[]="OJPEGReadHeaderInfoSecTablesQTable";
1804         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1805         uint8 m;
1806         uint8 n;
1807         uint32 oa;
1808         uint8* ob;
1809         uint32 p;
1810         if (sp->qtable_offset[0]==0)
1811         {
1812                 TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables");
1813                 return(0);
1814         }
1815         sp->in_buffer_file_pos_log=0;
1816         for (m=0; m<sp->samples_per_pixel; m++)
1817         {
1818                 if ((sp->qtable_offset[m]!=0) && ((m==0) || (sp->qtable_offset[m]!=sp->qtable_offset[m-1])))
1819                 {
1820                         for (n=0; n<m-1; n++)
1821                         {
1822                                 if (sp->qtable_offset[m]==sp->qtable_offset[n])
1823                                 {
1824                                         TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegQTables tag value");
1825                                         return(0);
1826                                 }
1827                         }
1828                         oa=sizeof(uint32)+69;
1829                         ob=_TIFFmalloc(oa);
1830                         if (ob==0)
1831                         {
1832                                 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1833                                 return(0);
1834                         }
1835                         *(uint32*)ob=oa;
1836                         ob[sizeof(uint32)]=255;
1837                         ob[sizeof(uint32)+1]=JPEG_MARKER_DQT;
1838                         ob[sizeof(uint32)+2]=0;
1839                         ob[sizeof(uint32)+3]=67;
1840                         ob[sizeof(uint32)+4]=m;
1841                         TIFFSeekFile(tif,sp->qtable_offset[m],SEEK_SET); 
1842                         p=(uint32)TIFFReadFile(tif,&ob[sizeof(uint32)+5],64);
1843                         if (p!=64)
1844                         {
1845                                 _TIFFfree(ob);
1846                                 return(0);
1847                         }
1848                         if (sp->qtable[m]!=0)
1849                                 _TIFFfree(sp->qtable[m]);
1850                         sp->qtable[m]=ob;
1851                         sp->sof_tq[m]=m;
1852                 }
1853                 else
1854                         sp->sof_tq[m]=sp->sof_tq[m-1];
1855         }
1856         return(1);
1857 }
1858
1859 static int
1860 OJPEGReadHeaderInfoSecTablesDcTable(TIFF* tif)
1861 {
1862         static const char module[]="OJPEGReadHeaderInfoSecTablesDcTable";
1863         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1864         uint8 m;
1865         uint8 n;
1866         uint8 o[16];
1867         uint32 p;
1868         uint32 q;
1869         uint32 ra;
1870         uint8* rb;
1871         if (sp->dctable_offset[0]==0)
1872         {
1873                 TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables");
1874                 return(0);
1875         }
1876         sp->in_buffer_file_pos_log=0;
1877         for (m=0; m<sp->samples_per_pixel; m++)
1878         {
1879                 if ((sp->dctable_offset[m]!=0) && ((m==0) || (sp->dctable_offset[m]!=sp->dctable_offset[m-1])))
1880                 {
1881                         for (n=0; n<m-1; n++)
1882                         {
1883                                 if (sp->dctable_offset[m]==sp->dctable_offset[n])
1884                                 {
1885                                         TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegDcTables tag value");
1886                                         return(0);
1887                                 }
1888                         }
1889                         TIFFSeekFile(tif,sp->dctable_offset[m],SEEK_SET);
1890                         p=(uint32)TIFFReadFile(tif,o,16);
1891                         if (p!=16)
1892                                 return(0);
1893                         q=0;
1894                         for (n=0; n<16; n++)
1895                                 q+=o[n];
1896                         ra=sizeof(uint32)+21+q;
1897                         rb=_TIFFmalloc(ra);
1898                         if (rb==0)
1899                         {
1900                                 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1901                                 return(0);
1902                         }
1903                         *(uint32*)rb=ra;
1904                         rb[sizeof(uint32)]=255;
1905                         rb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
1906                         rb[sizeof(uint32)+2]=(uint8)((19+q)>>8);
1907                         rb[sizeof(uint32)+3]=((19+q)&255);
1908                         rb[sizeof(uint32)+4]=m;
1909                         for (n=0; n<16; n++)
1910                                 rb[sizeof(uint32)+5+n]=o[n];
1911                         p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
1912                         if (p!=q)
1913                         {
1914                                 _TIFFfree(rb);
1915                                 return(0);
1916                         }
1917                         if (sp->dctable[m]!=0)
1918                                 _TIFFfree(sp->dctable[m]);
1919                         sp->dctable[m]=rb;
1920                         sp->sos_tda[m]=(m<<4);
1921                 }
1922                 else
1923                         sp->sos_tda[m]=sp->sos_tda[m-1];
1924         }
1925         return(1);
1926 }
1927
1928 static int
1929 OJPEGReadHeaderInfoSecTablesAcTable(TIFF* tif)
1930 {
1931         static const char module[]="OJPEGReadHeaderInfoSecTablesAcTable";
1932         OJPEGState* sp=(OJPEGState*)tif->tif_data;
1933         uint8 m;
1934         uint8 n;
1935         uint8 o[16];
1936         uint32 p;
1937         uint32 q;
1938         uint32 ra;
1939         uint8* rb;
1940         if (sp->actable_offset[0]==0)
1941         {
1942                 TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables");
1943                 return(0);
1944         }
1945         sp->in_buffer_file_pos_log=0;
1946         for (m=0; m<sp->samples_per_pixel; m++)
1947         {
1948                 if ((sp->actable_offset[m]!=0) && ((m==0) || (sp->actable_offset[m]!=sp->actable_offset[m-1])))
1949                 {
1950                         for (n=0; n<m-1; n++)
1951                         {
1952                                 if (sp->actable_offset[m]==sp->actable_offset[n])
1953                                 {
1954                                         TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegAcTables tag value");
1955                                         return(0);
1956                                 }
1957                         }
1958                         TIFFSeekFile(tif,sp->actable_offset[m],SEEK_SET);  
1959                         p=(uint32)TIFFReadFile(tif,o,16);
1960                         if (p!=16)
1961                                 return(0);
1962                         q=0;
1963                         for (n=0; n<16; n++)
1964                                 q+=o[n];
1965                         ra=sizeof(uint32)+21+q;
1966                         rb=_TIFFmalloc(ra);
1967                         if (rb==0)
1968                         {
1969                                 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1970                                 return(0);
1971                         }
1972                         *(uint32*)rb=ra;
1973                         rb[sizeof(uint32)]=255;
1974                         rb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
1975                         rb[sizeof(uint32)+2]=(uint8)((19+q)>>8);
1976                         rb[sizeof(uint32)+3]=((19+q)&255);
1977                         rb[sizeof(uint32)+4]=(16|m);
1978                         for (n=0; n<16; n++)
1979                                 rb[sizeof(uint32)+5+n]=o[n];
1980                         p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
1981                         if (p!=q)
1982                         {
1983                                 _TIFFfree(rb);
1984                                 return(0);
1985                         }
1986                         if (sp->actable[m]!=0)
1987                                 _TIFFfree(sp->actable[m]);
1988                         sp->actable[m]=rb;
1989                         sp->sos_tda[m]=(sp->sos_tda[m]|m);
1990                 }
1991                 else
1992                         sp->sos_tda[m]=(sp->sos_tda[m]|(sp->sos_tda[m-1]&15));
1993         }
1994         return(1);
1995 }
1996
1997 static int
1998 OJPEGReadBufferFill(OJPEGState* sp)
1999 {
2000         uint16 m;
2001         tmsize_t n;
2002         /* TODO: double-check: when subsamplingcorrect is set, no call to TIFFErrorExt or TIFFWarningExt should be made
2003          * in any other case, seek or read errors should be passed through */
2004         do
2005         {
2006                 if (sp->in_buffer_file_togo!=0)
2007                 {
2008                         if (sp->in_buffer_file_pos_log==0)
2009                         {
2010                                 TIFFSeekFile(sp->tif,sp->in_buffer_file_pos,SEEK_SET);
2011                                 sp->in_buffer_file_pos_log=1;
2012                         }
2013                         m=OJPEG_BUFFER;
2014                         if ((uint64)m>sp->in_buffer_file_togo)
2015                                 m=(uint16)sp->in_buffer_file_togo;
2016                         n=TIFFReadFile(sp->tif,sp->in_buffer,(tmsize_t)m);
2017                         if (n==0)
2018                                 return(0);
2019                         assert(n>0);
2020                         assert(n<=OJPEG_BUFFER);
2021                         assert(n<65536);
2022                         assert((uint64)n<=sp->in_buffer_file_togo);
2023                         m=(uint16)n;
2024                         sp->in_buffer_togo=m;
2025                         sp->in_buffer_cur=sp->in_buffer;
2026                         sp->in_buffer_file_togo-=m;
2027                         sp->in_buffer_file_pos+=m;
2028                         break;
2029                 }
2030                 sp->in_buffer_file_pos_log=0;
2031                 switch(sp->in_buffer_source)
2032                 {
2033                         case osibsNotSetYet:
2034                                 if (sp->jpeg_interchange_format!=0)
2035                                 {
2036                                         sp->in_buffer_file_pos=sp->jpeg_interchange_format;
2037                                         sp->in_buffer_file_togo=sp->jpeg_interchange_format_length;
2038                                 }
2039                                 sp->in_buffer_source=osibsJpegInterchangeFormat;
2040                                 break;
2041                         case osibsJpegInterchangeFormat:
2042                                 sp->in_buffer_source=osibsStrile;
2043                                 break;
2044                         case osibsStrile:
2045                                 if (sp->in_buffer_next_strile==sp->in_buffer_strile_count)
2046                                         sp->in_buffer_source=osibsEof;
2047                                 else
2048                                 {
2049                                         int err = 0;
2050                                         sp->in_buffer_file_pos=TIFFGetStrileOffsetWithErr(sp->tif, sp->in_buffer_next_strile, &err);
2051                                         if( err )
2052                                                 return 0;
2053                                         if (sp->in_buffer_file_pos!=0)
2054                                         {
2055                                                 uint64 bytecount = TIFFGetStrileByteCountWithErr(sp->tif, sp->in_buffer_next_strile, &err);
2056                                                 if( err )
2057                                                         return 0;
2058                                                 if (sp->in_buffer_file_pos>=sp->file_size)
2059                                                         sp->in_buffer_file_pos=0;
2060                                                 else if (bytecount==0)
2061                                                         sp->in_buffer_file_togo=sp->file_size-sp->in_buffer_file_pos;
2062                                                 else
2063                                                 {
2064                                                         sp->in_buffer_file_togo=bytecount;
2065                                                         if (sp->in_buffer_file_togo==0)
2066                                                                 sp->in_buffer_file_pos=0;
2067                                                         else if (sp->in_buffer_file_pos > TIFF_UINT64_MAX - sp->in_buffer_file_togo || 
2068                                                                 sp->in_buffer_file_pos+sp->in_buffer_file_togo>sp->file_size)
2069                                                                 sp->in_buffer_file_togo=sp->file_size-sp->in_buffer_file_pos;
2070                                                 }
2071                                         }
2072                                         sp->in_buffer_next_strile++;
2073                                 }
2074                                 break;
2075                         default:
2076                                 return(0);
2077                 }
2078         } while (1);
2079         return(1);
2080 }
2081
2082 static int
2083 OJPEGReadByte(OJPEGState* sp, uint8* byte)
2084 {
2085         if (sp->in_buffer_togo==0)
2086         {
2087                 if (OJPEGReadBufferFill(sp)==0)
2088                         return(0);
2089                 assert(sp->in_buffer_togo>0);
2090         }
2091         *byte=*(sp->in_buffer_cur);
2092         sp->in_buffer_cur++;
2093         sp->in_buffer_togo--;
2094         return(1);
2095 }
2096
2097 static int
2098 OJPEGReadBytePeek(OJPEGState* sp, uint8* byte)
2099 {
2100         if (sp->in_buffer_togo==0)
2101         {
2102                 if (OJPEGReadBufferFill(sp)==0)
2103                         return(0);
2104                 assert(sp->in_buffer_togo>0);
2105         }
2106         *byte=*(sp->in_buffer_cur);
2107         return(1);
2108 }
2109
2110 static void
2111 OJPEGReadByteAdvance(OJPEGState* sp)
2112 {
2113         assert(sp->in_buffer_togo>0);
2114         sp->in_buffer_cur++;
2115         sp->in_buffer_togo--;
2116 }
2117
2118 static int
2119 OJPEGReadWord(OJPEGState* sp, uint16* word)
2120 {
2121         uint8 m;
2122         if (OJPEGReadByte(sp,&m)==0)
2123                 return(0);
2124         *word=(m<<8);
2125         if (OJPEGReadByte(sp,&m)==0)
2126                 return(0);
2127         *word|=m;
2128         return(1);
2129 }
2130
2131 static int
2132 OJPEGReadBlock(OJPEGState* sp, uint16 len, void* mem)
2133 {
2134         uint16 mlen;
2135         uint8* mmem;
2136         uint16 n;
2137         assert(len>0);
2138         mlen=len;
2139         mmem=mem;
2140         do
2141         {
2142                 if (sp->in_buffer_togo==0)
2143                 {
2144                         if (OJPEGReadBufferFill(sp)==0)
2145                                 return(0);
2146                         assert(sp->in_buffer_togo>0);
2147                 }
2148                 n=mlen;
2149                 if (n>sp->in_buffer_togo)
2150                         n=sp->in_buffer_togo;
2151                 _TIFFmemcpy(mmem,sp->in_buffer_cur,n);
2152                 sp->in_buffer_cur+=n;
2153                 sp->in_buffer_togo-=n;
2154                 mlen-=n;
2155                 mmem+=n;
2156         } while(mlen>0);
2157         return(1);
2158 }
2159
2160 static void
2161 OJPEGReadSkip(OJPEGState* sp, uint16 len)
2162 {
2163         uint16 m;
2164         uint16 n;
2165         m=len;
2166         n=m;
2167         if (n>sp->in_buffer_togo)
2168                 n=sp->in_buffer_togo;
2169         sp->in_buffer_cur+=n;
2170         sp->in_buffer_togo-=n;
2171         m-=n;
2172         if (m>0)
2173         {
2174                 assert(sp->in_buffer_togo==0);
2175                 n=m;
2176                 if ((uint64)n>sp->in_buffer_file_togo)
2177                         n=(uint16)sp->in_buffer_file_togo;
2178                 sp->in_buffer_file_pos+=n;
2179                 sp->in_buffer_file_togo-=n;
2180                 sp->in_buffer_file_pos_log=0;
2181                 /* we don't skip past jpeginterchangeformat/strile block...
2182                  * if that is asked from us, we're dealing with totally bazurk
2183                  * data anyway, and we've not seen this happening on any
2184                  * testfile, so we might as well likely cause some other
2185                  * meaningless error to be passed at some later time
2186                  */
2187         }
2188 }
2189
2190 static int
2191 OJPEGWriteStream(TIFF* tif, void** mem, uint32* len)
2192 {
2193         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2194         *len=0;
2195         do
2196         {
2197                 assert(sp->out_state<=ososEoi);
2198                 switch(sp->out_state)
2199                 {
2200                         case ososSoi:
2201                                 OJPEGWriteStreamSoi(tif,mem,len);
2202                                 break;
2203                         case ososQTable0:
2204                                 OJPEGWriteStreamQTable(tif,0,mem,len);
2205                                 break;
2206                         case ososQTable1:
2207                                 OJPEGWriteStreamQTable(tif,1,mem,len);
2208                                 break;
2209                         case ososQTable2:
2210                                 OJPEGWriteStreamQTable(tif,2,mem,len);
2211                                 break;
2212                         case ososQTable3:
2213                                 OJPEGWriteStreamQTable(tif,3,mem,len);
2214                                 break;
2215                         case ososDcTable0:
2216                                 OJPEGWriteStreamDcTable(tif,0,mem,len);
2217                                 break;
2218                         case ososDcTable1:
2219                                 OJPEGWriteStreamDcTable(tif,1,mem,len);
2220                                 break;
2221                         case ososDcTable2:
2222                                 OJPEGWriteStreamDcTable(tif,2,mem,len);
2223                                 break;
2224                         case ososDcTable3:
2225                                 OJPEGWriteStreamDcTable(tif,3,mem,len);
2226                                 break;
2227                         case ososAcTable0:
2228                                 OJPEGWriteStreamAcTable(tif,0,mem,len);
2229                                 break;
2230                         case ososAcTable1:
2231                                 OJPEGWriteStreamAcTable(tif,1,mem,len);
2232                                 break;
2233                         case ososAcTable2:
2234                                 OJPEGWriteStreamAcTable(tif,2,mem,len);
2235                                 break;
2236                         case ososAcTable3:
2237                                 OJPEGWriteStreamAcTable(tif,3,mem,len);
2238                                 break;
2239                         case ososDri:
2240                                 OJPEGWriteStreamDri(tif,mem,len);
2241                                 break;
2242                         case ososSof:
2243                                 OJPEGWriteStreamSof(tif,mem,len);
2244                                 break;
2245                         case ososSos:
2246                                 OJPEGWriteStreamSos(tif,mem,len);
2247                                 break;
2248                         case ososCompressed:
2249                                 if (OJPEGWriteStreamCompressed(tif,mem,len)==0)
2250                                         return(0);
2251                                 break;
2252                         case ososRst:
2253                                 OJPEGWriteStreamRst(tif,mem,len);
2254                                 break;
2255                         case ososEoi:
2256                                 OJPEGWriteStreamEoi(tif,mem,len);
2257                                 break;
2258                 }
2259         } while (*len==0);
2260         return(1);
2261 }
2262
2263 static void
2264 OJPEGWriteStreamSoi(TIFF* tif, void** mem, uint32* len)
2265 {
2266         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2267         assert(OJPEG_BUFFER>=2);
2268         sp->out_buffer[0]=255;
2269         sp->out_buffer[1]=JPEG_MARKER_SOI;
2270         *len=2;
2271         *mem=(void*)sp->out_buffer;
2272         sp->out_state++;
2273 }
2274
2275 static void
2276 OJPEGWriteStreamQTable(TIFF* tif, uint8 table_index, void** mem, uint32* len)
2277 {
2278         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2279         if (sp->qtable[table_index]!=0)
2280         {
2281                 *mem=(void*)(sp->qtable[table_index]+sizeof(uint32));
2282                 *len=*((uint32*)sp->qtable[table_index])-sizeof(uint32);
2283         }
2284         sp->out_state++;
2285 }
2286
2287 static void
2288 OJPEGWriteStreamDcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len)
2289 {
2290         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2291         if (sp->dctable[table_index]!=0)
2292         {
2293                 *mem=(void*)(sp->dctable[table_index]+sizeof(uint32));
2294                 *len=*((uint32*)sp->dctable[table_index])-sizeof(uint32);
2295         }
2296         sp->out_state++;
2297 }
2298
2299 static void
2300 OJPEGWriteStreamAcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len)
2301 {
2302         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2303         if (sp->actable[table_index]!=0)
2304         {
2305                 *mem=(void*)(sp->actable[table_index]+sizeof(uint32));
2306                 *len=*((uint32*)sp->actable[table_index])-sizeof(uint32);
2307         }
2308         sp->out_state++;
2309 }
2310
2311 static void
2312 OJPEGWriteStreamDri(TIFF* tif, void** mem, uint32* len)
2313 {
2314         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2315         assert(OJPEG_BUFFER>=6);
2316         if (sp->restart_interval!=0)
2317         {
2318                 sp->out_buffer[0]=255;
2319                 sp->out_buffer[1]=JPEG_MARKER_DRI;
2320                 sp->out_buffer[2]=0;
2321                 sp->out_buffer[3]=4;
2322                 sp->out_buffer[4]=(sp->restart_interval>>8);
2323                 sp->out_buffer[5]=(sp->restart_interval&255);
2324                 *len=6;
2325                 *mem=(void*)sp->out_buffer;
2326         }
2327         sp->out_state++;
2328 }
2329
2330 static void
2331 OJPEGWriteStreamSof(TIFF* tif, void** mem, uint32* len)
2332 {
2333         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2334         uint8 m;
2335         assert(OJPEG_BUFFER>=2+8+sp->samples_per_pixel_per_plane*3);
2336         assert(255>=8+sp->samples_per_pixel_per_plane*3);
2337         sp->out_buffer[0]=255;
2338         sp->out_buffer[1]=sp->sof_marker_id;
2339         /* Lf */
2340         sp->out_buffer[2]=0;
2341         sp->out_buffer[3]=8+sp->samples_per_pixel_per_plane*3;
2342         /* P */
2343         sp->out_buffer[4]=8;
2344         /* Y */
2345         sp->out_buffer[5]=(uint8)(sp->sof_y>>8);
2346         sp->out_buffer[6]=(sp->sof_y&255);
2347         /* X */
2348         sp->out_buffer[7]=(uint8)(sp->sof_x>>8);
2349         sp->out_buffer[8]=(sp->sof_x&255);
2350         /* Nf */
2351         sp->out_buffer[9]=sp->samples_per_pixel_per_plane;
2352         for (m=0; m<sp->samples_per_pixel_per_plane; m++)
2353         {
2354                 /* C */
2355                 sp->out_buffer[10+m*3]=sp->sof_c[sp->plane_sample_offset+m];
2356                 /* H and V */
2357                 sp->out_buffer[10+m*3+1]=sp->sof_hv[sp->plane_sample_offset+m];
2358                 /* Tq */
2359                 sp->out_buffer[10+m*3+2]=sp->sof_tq[sp->plane_sample_offset+m];
2360         }
2361         *len=10+sp->samples_per_pixel_per_plane*3;
2362         *mem=(void*)sp->out_buffer;
2363         sp->out_state++;
2364 }
2365
2366 static void
2367 OJPEGWriteStreamSos(TIFF* tif, void** mem, uint32* len)
2368 {
2369         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2370         uint8 m;
2371         assert(OJPEG_BUFFER>=2+6+sp->samples_per_pixel_per_plane*2);
2372         assert(255>=6+sp->samples_per_pixel_per_plane*2);
2373         sp->out_buffer[0]=255;
2374         sp->out_buffer[1]=JPEG_MARKER_SOS;
2375         /* Ls */
2376         sp->out_buffer[2]=0;
2377         sp->out_buffer[3]=6+sp->samples_per_pixel_per_plane*2;
2378         /* Ns */
2379         sp->out_buffer[4]=sp->samples_per_pixel_per_plane;
2380         for (m=0; m<sp->samples_per_pixel_per_plane; m++)
2381         {
2382                 /* Cs */
2383                 sp->out_buffer[5+m*2]=sp->sos_cs[sp->plane_sample_offset+m];
2384                 /* Td and Ta */
2385                 sp->out_buffer[5+m*2+1]=sp->sos_tda[sp->plane_sample_offset+m];
2386         }
2387         /* Ss */
2388         sp->out_buffer[5+sp->samples_per_pixel_per_plane*2]=0;
2389         /* Se */
2390         sp->out_buffer[5+sp->samples_per_pixel_per_plane*2+1]=63;
2391         /* Ah and Al */
2392         sp->out_buffer[5+sp->samples_per_pixel_per_plane*2+2]=0;
2393         *len=8+sp->samples_per_pixel_per_plane*2;
2394         *mem=(void*)sp->out_buffer;
2395         sp->out_state++;
2396 }
2397
2398 static int
2399 OJPEGWriteStreamCompressed(TIFF* tif, void** mem, uint32* len)
2400 {
2401         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2402         if (sp->in_buffer_togo==0)
2403         {
2404                 if (OJPEGReadBufferFill(sp)==0)
2405                         return(0);
2406                 assert(sp->in_buffer_togo>0);
2407         }
2408         *len=sp->in_buffer_togo;
2409         *mem=(void*)sp->in_buffer_cur;
2410         sp->in_buffer_togo=0;
2411         if (sp->in_buffer_file_togo==0)
2412         {
2413                 switch(sp->in_buffer_source)
2414                 {
2415                         case osibsStrile:
2416                                 if (sp->in_buffer_next_strile<sp->in_buffer_strile_count)
2417                                         sp->out_state=ososRst;
2418                                 else
2419                                         sp->out_state=ososEoi;
2420                                 break;
2421                         case osibsEof:
2422                                 sp->out_state=ososEoi;
2423                                 break;
2424                         default:
2425                                 break;
2426                 }
2427         }
2428         return(1);
2429 }
2430
2431 static void
2432 OJPEGWriteStreamRst(TIFF* tif, void** mem, uint32* len)
2433 {
2434         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2435         assert(OJPEG_BUFFER>=2);
2436         sp->out_buffer[0]=255;
2437         sp->out_buffer[1]=JPEG_MARKER_RST0+sp->restart_index;
2438         sp->restart_index++;
2439         if (sp->restart_index==8)
2440                 sp->restart_index=0;
2441         *len=2;
2442         *mem=(void*)sp->out_buffer;
2443         sp->out_state=ososCompressed;
2444 }
2445
2446 static void
2447 OJPEGWriteStreamEoi(TIFF* tif, void** mem, uint32* len)
2448 {
2449         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2450         assert(OJPEG_BUFFER>=2);
2451         sp->out_buffer[0]=255;
2452         sp->out_buffer[1]=JPEG_MARKER_EOI;
2453         *len=2;
2454         *mem=(void*)sp->out_buffer;
2455 }
2456
2457 #ifndef LIBJPEG_ENCAP_EXTERNAL
2458 static int
2459 jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo)
2460 {
2461         if( SETJMP(sp->exit_jmpbuf) )
2462                 return 0;
2463         else {
2464                 jpeg_create_decompress(cinfo);
2465                 return 1;
2466         }
2467 }
2468 #endif
2469
2470 #ifndef LIBJPEG_ENCAP_EXTERNAL
2471 static int
2472 jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image)
2473 {
2474         if( SETJMP(sp->exit_jmpbuf) )
2475                 return 0;
2476         else {
2477                 jpeg_read_header(cinfo,require_image);
2478                 return 1;
2479         }
2480 }
2481 #endif
2482
2483 #ifndef LIBJPEG_ENCAP_EXTERNAL
2484 static int
2485 jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo)
2486 {
2487         if( SETJMP(sp->exit_jmpbuf) )
2488                 return 0;
2489         else {
2490                 jpeg_start_decompress(cinfo);
2491                 return 1;
2492         }
2493 }
2494 #endif
2495
2496 #ifndef LIBJPEG_ENCAP_EXTERNAL
2497 static int
2498 jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines)
2499 {
2500         if( SETJMP(sp->exit_jmpbuf) )
2501                 return 0;
2502         else {
2503                 jpeg_read_scanlines(cinfo,scanlines,max_lines);
2504                 return 1;
2505         }
2506 }
2507 #endif
2508
2509 #ifndef LIBJPEG_ENCAP_EXTERNAL
2510 static int
2511 jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines)
2512 {
2513         if( SETJMP(sp->exit_jmpbuf) )
2514                 return 0;
2515         else {
2516                 jpeg_read_raw_data(cinfo,data,max_lines);
2517                 return 1;
2518         }
2519 }
2520 #endif
2521
2522 #ifndef LIBJPEG_ENCAP_EXTERNAL
2523 static void
2524 jpeg_encap_unwind(TIFF* tif)
2525 {
2526         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2527         LONGJMP(sp->exit_jmpbuf,1);
2528 }
2529 #endif
2530
2531 static void
2532 OJPEGLibjpegJpegErrorMgrOutputMessage(jpeg_common_struct* cinfo)
2533 {
2534         char buffer[JMSG_LENGTH_MAX];
2535         (*cinfo->err->format_message)(cinfo,buffer);
2536         TIFFWarningExt(((TIFF*)(cinfo->client_data))->tif_clientdata,"LibJpeg","%s",buffer);
2537 }
2538
2539 static void
2540 OJPEGLibjpegJpegErrorMgrErrorExit(jpeg_common_struct* cinfo)
2541 {
2542         char buffer[JMSG_LENGTH_MAX];
2543         (*cinfo->err->format_message)(cinfo,buffer);
2544         TIFFErrorExt(((TIFF*)(cinfo->client_data))->tif_clientdata,"LibJpeg","%s",buffer);
2545         jpeg_encap_unwind((TIFF*)(cinfo->client_data));
2546 }
2547
2548 static void
2549 OJPEGLibjpegJpegSourceMgrInitSource(jpeg_decompress_struct* cinfo)
2550 {
2551         (void)cinfo;
2552 }
2553
2554 static boolean
2555 OJPEGLibjpegJpegSourceMgrFillInputBuffer(jpeg_decompress_struct* cinfo)
2556 {
2557         TIFF* tif=(TIFF*)cinfo->client_data;
2558         OJPEGState* sp=(OJPEGState*)tif->tif_data;
2559         void* mem=0;
2560         uint32 len=0U;
2561         if (OJPEGWriteStream(tif,&mem,&len)==0)
2562         {
2563                 TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Premature end of JPEG data");
2564                 jpeg_encap_unwind(tif);
2565         }
2566         sp->libjpeg_jpeg_source_mgr.bytes_in_buffer=len;
2567         sp->libjpeg_jpeg_source_mgr.next_input_byte=mem;
2568         return(1);
2569 }
2570
2571 static void
2572 OJPEGLibjpegJpegSourceMgrSkipInputData(jpeg_decompress_struct* cinfo, long num_bytes)
2573 {
2574         TIFF* tif=(TIFF*)cinfo->client_data;
2575         (void)num_bytes;
2576         TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Unexpected error");
2577         jpeg_encap_unwind(tif);
2578 }
2579
2580 #ifdef _MSC_VER
2581 #pragma warning( push )
2582 #pragma warning( disable : 4702 ) /* unreachable code */
2583 #endif
2584 static boolean
2585 OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct* cinfo, int desired)
2586 {
2587         TIFF* tif=(TIFF*)cinfo->client_data;
2588         (void)desired;
2589         TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Unexpected error");
2590         jpeg_encap_unwind(tif);
2591         return(0);
2592 }
2593 #ifdef _MSC_VER
2594 #pragma warning( pop ) 
2595 #endif
2596
2597 static void
2598 OJPEGLibjpegJpegSourceMgrTermSource(jpeg_decompress_struct* cinfo)
2599 {
2600         (void)cinfo;
2601 }
2602
2603 #endif
2604
2605
2606 /*
2607  * Local Variables:
2608  * mode: c
2609  * c-basic-offset: 8
2610  * fill-column: 78
2611  * End:
2612  */