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