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