1 /* WARNING: The type of JPEG encapsulation defined by the TIFF Version 6.0
2 specification is now totally obsolete and deprecated for new applications and
3 images. This file was was created solely in order to read unconverted images
4 still present on some users' computer systems. It will never be extended
5 to write such files. Writing new-style JPEG compressed TIFFs is implemented
8 The code is carefully crafted to robustly read all gathered JPEG-in-TIFF
9 testfiles, and anticipate as much as possible all other... But still, it may
10 fail on some. If you encounter problems, please report them on the TIFF
11 mailing list and/or to Joris Van Damme <info@awaresystems.be>.
13 Please read the file called "TIFF Technical Note #2" if you need to be
14 convinced this compression scheme is bad and breaks TIFF. That document
15 is linked to from the LibTiff site <http://www.remotesensing.org/libtiff/>
16 and from AWare Systems' TIFF section
17 <http://www.awaresystems.be/imaging/tiff.html>. It is also absorbed
18 in Adobe's specification supplements, marked "draft" up to this day, but
19 supported by the TIFF community.
21 This file interfaces with Release 6B of the JPEG Library written by the
22 Independent JPEG Group. Previous versions of this file required a hack inside
23 the LibJpeg library. This version no longer requires that. Remember to
24 remove the hack if you update from the old version.
26 Copyright (c) Joris Van Damme <info@awaresystems.be>
27 Copyright (c) AWare Systems <http://www.awaresystems.be/>
29 The licence agreement for this file is the same as the rest of the LibTiff
32 IN NO EVENT SHALL JORIS VAN DAMME OR AWARE SYSTEMS BE LIABLE FOR
33 ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
34 OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
35 WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
36 LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
39 Joris Van Damme and/or AWare Systems may be available for custom
40 development. If you like what you see, and need anything similar or related,
41 contact <info@awaresystems.be>.
44 /* What is what, and what is not?
46 This decoder starts with an input stream, that is essentially the JpegInterchangeFormat
47 stream, if any, followed by the strile data, if any. This stream is read in
48 OJPEGReadByte and related functions.
50 It analyzes the start of this stream, until it encounters non-marker data, i.e.
51 compressed image data. Some of the header markers it sees have no actual content,
52 like the SOI marker, and APP/COM markers that really shouldn't even be there. Some
53 other markers do have content, and the valuable bits and pieces of information
54 in these markers are saved, checking all to verify that the stream is more or
55 less within expected bounds. This happens inside the OJPEGReadHeaderInfoSecStreamXxx
58 Some OJPEG imagery contains no valid JPEG header markers. This situation is picked
59 up on if we've seen no SOF marker when we're at the start of the compressed image
60 data. In this case, the tables are read from JpegXxxTables tags, and the other
61 bits and pieces of information is initialized to its most basic value. This is
62 implemented in the OJPEGReadHeaderInfoSecTablesXxx functions.
64 When this is complete, a good and valid JPEG header can be assembled, and this is
65 passed through to LibJpeg. When that's done, the remainder of the input stream, i.e.
66 the compressed image data, can be passed through unchanged. This is done in
67 OJPEGWriteStream functions.
69 LibTiff rightly expects to know the subsampling values before decompression. Just like
70 in new-style JPEG-in-TIFF, though, or even more so, actually, the YCbCrsubsampling
71 tag is notoriously unreliable. To correct these tag values with the ones inside
72 the JPEG stream, the first part of the input stream is pre-scanned in
73 OJPEGSubsamplingCorrect, making no note of any other data, reporting no warnings
74 or errors, up to the point where either these values are read, or it's clear they
75 aren't there. This means that some of the data is read twice, but we feel speed
76 in correcting these values is important enough to warrant this sacrifice. Although
77 there is currently no define or other configuration mechanism to disable this behaviour,
78 the actual header scanning is build to robustly respond with error report if it
79 should encounter an uncorrected mismatch of subsampling values. See
80 OJPEGReadHeaderInfoSecStreamSof.
82 The restart interval and restart markers are the most tricky part... The restart
83 interval can be specified in a tag. It can also be set inside the input JPEG stream.
84 It can be used inside the input JPEG stream. If reading from strile data, we've
85 consistently discovered the need to insert restart markers in between the different
86 striles, as is also probably the most likely interpretation of the original TIFF 6.0
87 specification. With all this setting of interval, and actual use of markers that is not
88 predictable at the time of valid JPEG header assembly, the restart thing may turn
89 out the Achilles heel of this implementation. Fortunately, most OJPEG writer vendors
90 succeed in reading back what they write, which may be the reason why we've been able
91 to discover ways that seem to work.
93 Some special provision is made for planarconfig separate OJPEG files. These seem
94 to consistently contain header info, a SOS marker, a plane, SOS marker, plane, SOS,
95 and plane. This may or may not be a valid JPEG configuration, we don't know and don't
96 care. We want LibTiff to be able to access the planes individually, without huge
97 buffering inside LibJpeg, anyway. So we compose headers to feed to LibJpeg, in this
98 case, that allow us to pass a single plane such that LibJpeg sees a valid
99 single-channel JPEG stream. Locating subsequent SOS markers, and thus subsequent
100 planes, is done inside OJPEGReadSecondarySos.
102 The benefit of the scheme is... that it works, basically. We know of no other that
103 does. It works without checking software tag, or otherwise going about things in an
104 OJPEG flavor specific manner. Instead, it is a single scheme, that covers the cases
105 with and without JpegInterchangeFormat, with and without striles, with part of
106 the header in JpegInterchangeFormat and remainder in first strile, etc. It is forgiving
107 and robust, may likely work with OJPEG flavors we've not seen yet, and makes most out
110 Another nice side-effect is that a complete JPEG single valid stream is build if
111 planarconfig is not separate (vast majority). We may one day use that to build
112 converters to JPEG, and/or to new-style JPEG compression inside TIFF.
114 A disadvantage is the lack of random access to the individual striles. This is the
115 reason for much of the complicated restart-and-position stuff inside OJPEGPreDecode.
116 Applications would do well accessing all striles in order, as this will result in
117 a single sequential scan of the input stream, and no restarting of LibJpeg decoding
121 #define WIN32_LEAN_AND_MEAN
127 /* Configuration defines here are:
128 * JPEG_ENCAP_EXTERNAL: The normal way to call libjpeg, uses longjump. In some environments,
129 * like eg LibTiffDelphi, this is not possible. For this reason, the actual calls to
130 * libjpeg, with longjump stuff, are encapsulated in dedicated functions. When
131 * JPEG_ENCAP_EXTERNAL is defined, these encapsulating functions are declared external
132 * to this unit, and can be defined elsewhere to use stuff other then longjump.
133 * The default mode, without JPEG_ENCAP_EXTERNAL, implements the call encapsulators
134 * here, internally, with normal longjump.
135 * SETJMP, LONGJMP, JMP_BUF: On some machines/environments a longjump equivalent is
136 * conveniently available, but still it may be worthwhile to use _setjmp or sigsetjmp
137 * in place of plain setjmp. These macros will make it easier. It is useless
138 * to fiddle with these if you define JPEG_ENCAP_EXTERNAL.
139 * OJPEG_BUFFER: Define the size of the desired buffer here. Should be small enough so as to guarantee
140 * instant processing, optimal streaming and optimal use of processor cache, but also big
141 * enough so as to not result in significant call overhead. It should be at least a few
142 * bytes to accommodate some structures (this is verified in asserts), but it would not be
143 * sensible to make it this small anyway, and it should be at most 64K since it is indexed
144 * with uint16. We recommend 2K.
145 * EGYPTIANWALK: You could also define EGYPTIANWALK here, but it is not used anywhere and has
146 * absolutely no effect. That is why most people insist the EGYPTIANWALK is a bit silly.
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 */
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
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)
177 static const TIFFField ojpegFields[] = {
178 {TIFFTAG_JPEGIFOFFSET,1,1,TIFF_LONG8,0,TIFF_SETGET_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGINTERCHANGEFORMAT,TRUE,FALSE,"JpegInterchangeFormat",NULL},
179 {TIFFTAG_JPEGIFBYTECOUNT,1,1,TIFF_LONG8,0,TIFF_SETGET_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH,TRUE,FALSE,"JpegInterchangeFormatLength",NULL},
180 {TIFFTAG_JPEGQTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGQTABLES,FALSE,TRUE,"JpegQTables",NULL},
181 {TIFFTAG_JPEGDCTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGDCTABLES,FALSE,TRUE,"JpegDcTables",NULL},
182 {TIFFTAG_JPEGACTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGACTABLES,FALSE,TRUE,"JpegAcTables",NULL},
183 {TIFFTAG_JPEGPROC,1,1,TIFF_SHORT,0,TIFF_SETGET_UINT16,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGPROC,FALSE,FALSE,"JpegProc",NULL},
184 {TIFFTAG_JPEGRESTARTINTERVAL,1,1,TIFF_SHORT,0,TIFF_SETGET_UINT16,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGRESTARTINTERVAL,FALSE,FALSE,"JpegRestartInterval",NULL},
187 #ifndef LIBJPEG_ENCAP_EXTERNAL
191 /* We undefine FAR to avoid conflict with JPEG definition */
198 Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
199 not defined. Unfortunately, the MinGW and Borland compilers include
200 a typedef for INT32, which causes a conflict. MSVC does not include
201 a conflicting typedef given the headers which are included.
203 #if defined(__BORLANDC__) || defined(__MINGW32__)
207 /* Define "boolean" as unsigned char, not int, per Windows custom. */
208 #if defined(__WIN32__) && !defined(__MINGW32__)
209 # ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
210 typedef unsigned char boolean;
212 # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
218 typedef struct jpeg_error_mgr jpeg_error_mgr;
219 typedef struct jpeg_common_struct jpeg_common_struct;
220 typedef struct jpeg_decompress_struct jpeg_decompress_struct;
221 typedef struct jpeg_source_mgr jpeg_source_mgr;
225 osibsJpegInterchangeFormat,
228 } OJPEGStateInBufferSource;
232 ososQTable0,ososQTable1,ososQTable2,ososQTable3,
233 ososDcTable0,ososDcTable1,ososDcTable2,ososDcTable3,
234 ososAcTable0,ososAcTable1,ososAcTable2,ososAcTable3,
241 } OJPEGStateOutState;
246 int error_in_raw_data_decoding;
247 #ifndef LIBJPEG_ENCAP_EXTERNAL
250 TIFFVGetMethod vgetparent;
251 TIFFVSetMethod vsetparent;
252 TIFFPrintMethod printdir;
257 uint32 strile_length;
258 uint32 strile_length_total;
259 uint8 samples_per_pixel;
260 uint8 plane_sample_offset;
261 uint8 samples_per_pixel_per_plane;
262 uint64 jpeg_interchange_format;
263 uint64 jpeg_interchange_format_length;
265 uint8 subsamplingcorrect;
266 uint8 subsamplingcorrect_done;
267 uint8 subsampling_tag;
268 uint8 subsampling_hor;
269 uint8 subsampling_ver;
270 uint8 subsampling_force_desubsampling_inside_decompression;
271 uint8 qtable_offset_count;
272 uint8 dctable_offset_count;
273 uint8 actable_offset_count;
274 uint64 qtable_offset[3];
275 uint64 dctable_offset[3];
276 uint64 actable_offset[3];
280 uint16 restart_interval;
293 OJPEGStateInBufferSource in_buffer_source;
294 uint32 in_buffer_next_strile;
295 uint64 in_buffer_file_pos;
296 uint64 in_buffer_file_togo;
298 uint8 readheader_done;
299 uint8 writeheader_done;
300 uint16 write_cursample;
301 uint32 write_curstrile;
302 uint8 libjpeg_session_active;
303 uint8 libjpeg_jpeg_query_style;
304 jpeg_error_mgr libjpeg_jpeg_error_mgr;
305 jpeg_decompress_struct libjpeg_jpeg_decompress_struct;
306 jpeg_source_mgr libjpeg_jpeg_source_mgr;
307 uint8 subsampling_convert_log;
308 uint32 subsampling_convert_ylinelen;
309 uint32 subsampling_convert_ylines;
310 uint32 subsampling_convert_clinelen;
311 uint32 subsampling_convert_clines;
312 uint32 subsampling_convert_ybuflen;
313 uint32 subsampling_convert_cbuflen;
314 uint32 subsampling_convert_ycbcrbuflen;
315 uint8* subsampling_convert_ycbcrbuf;
316 uint8* subsampling_convert_ybuf;
317 uint8* subsampling_convert_cbbuf;
318 uint8* subsampling_convert_crbuf;
319 uint32 subsampling_convert_ycbcrimagelen;
320 uint8** subsampling_convert_ycbcrimage;
321 uint32 subsampling_convert_clinelenout;
322 uint32 subsampling_convert_state;
323 uint32 bytes_per_line; /* if the codec outputs subsampled data, a 'line' in bytes_per_line */
324 uint32 lines_per_strile; /* and lines_per_strile means subsampling_ver desubsampled rows */
325 OJPEGStateInBufferSource in_buffer_source;
326 uint32 in_buffer_next_strile;
327 uint32 in_buffer_strile_count;
328 uint64 in_buffer_file_pos;
329 uint8 in_buffer_file_pos_log;
330 uint64 in_buffer_file_togo;
331 uint16 in_buffer_togo;
332 uint8* in_buffer_cur;
333 uint8 in_buffer[OJPEG_BUFFER];
334 OJPEGStateOutState out_state;
335 uint8 out_buffer[OJPEG_BUFFER];
339 static int OJPEGVGetField(TIFF* tif, uint32 tag, va_list ap);
340 static int OJPEGVSetField(TIFF* tif, uint32 tag, va_list ap);
341 static void OJPEGPrintDir(TIFF* tif, FILE* fd, long flags);
343 static int OJPEGFixupTags(TIFF* tif);
344 static int OJPEGSetupDecode(TIFF* tif);
345 static int OJPEGPreDecode(TIFF* tif, uint16 s);
346 static int OJPEGPreDecodeSkipRaw(TIFF* tif);
347 static int OJPEGPreDecodeSkipScanlines(TIFF* tif);
348 static int OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
349 static int OJPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc);
350 static int OJPEGDecodeScanlines(TIFF* tif, uint8* buf, tmsize_t cc);
351 static void OJPEGPostDecode(TIFF* tif, uint8* buf, tmsize_t cc);
352 static int OJPEGSetupEncode(TIFF* tif);
353 static int OJPEGPreEncode(TIFF* tif, uint16 s);
354 static int OJPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
355 static int OJPEGPostEncode(TIFF* tif);
356 static void OJPEGCleanup(TIFF* tif);
358 static void OJPEGSubsamplingCorrect(TIFF* tif);
359 static int OJPEGReadHeaderInfo(TIFF* tif);
360 static int OJPEGReadSecondarySos(TIFF* tif, uint16 s);
361 static int OJPEGWriteHeaderInfo(TIFF* tif);
362 static void OJPEGLibjpegSessionAbort(TIFF* tif);
364 static int OJPEGReadHeaderInfoSec(TIFF* tif);
365 static int OJPEGReadHeaderInfoSecStreamDri(TIFF* tif);
366 static int OJPEGReadHeaderInfoSecStreamDqt(TIFF* tif);
367 static int OJPEGReadHeaderInfoSecStreamDht(TIFF* tif);
368 static int OJPEGReadHeaderInfoSecStreamSof(TIFF* tif, uint8 marker_id);
369 static int OJPEGReadHeaderInfoSecStreamSos(TIFF* tif);
370 static int OJPEGReadHeaderInfoSecTablesQTable(TIFF* tif);
371 static int OJPEGReadHeaderInfoSecTablesDcTable(TIFF* tif);
372 static int OJPEGReadHeaderInfoSecTablesAcTable(TIFF* tif);
374 static int OJPEGReadBufferFill(OJPEGState* sp);
375 static int OJPEGReadByte(OJPEGState* sp, uint8* byte);
376 static int OJPEGReadBytePeek(OJPEGState* sp, uint8* byte);
377 static void OJPEGReadByteAdvance(OJPEGState* sp);
378 static int OJPEGReadWord(OJPEGState* sp, uint16* word);
379 static int OJPEGReadBlock(OJPEGState* sp, uint16 len, void* mem);
380 static void OJPEGReadSkip(OJPEGState* sp, uint16 len);
382 static int OJPEGWriteStream(TIFF* tif, void** mem, uint32* len);
383 static void OJPEGWriteStreamSoi(TIFF* tif, void** mem, uint32* len);
384 static void OJPEGWriteStreamQTable(TIFF* tif, uint8 table_index, void** mem, uint32* len);
385 static void OJPEGWriteStreamDcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len);
386 static void OJPEGWriteStreamAcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len);
387 static void OJPEGWriteStreamDri(TIFF* tif, void** mem, uint32* len);
388 static void OJPEGWriteStreamSof(TIFF* tif, void** mem, uint32* len);
389 static void OJPEGWriteStreamSos(TIFF* tif, void** mem, uint32* len);
390 static int OJPEGWriteStreamCompressed(TIFF* tif, void** mem, uint32* len);
391 static void OJPEGWriteStreamRst(TIFF* tif, void** mem, uint32* len);
392 static void OJPEGWriteStreamEoi(TIFF* tif, void** mem, uint32* len);
394 #ifdef LIBJPEG_ENCAP_EXTERNAL
395 extern int jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo);
396 extern int jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image);
397 extern int jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo);
398 extern int jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines);
399 extern int jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines);
400 extern void jpeg_encap_unwind(TIFF* tif);
402 static int jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* j);
403 static int jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image);
404 static int jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo);
405 static int jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines);
406 static int jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines);
407 static void jpeg_encap_unwind(TIFF* tif);
410 static void OJPEGLibjpegJpegErrorMgrOutputMessage(jpeg_common_struct* cinfo);
411 static void OJPEGLibjpegJpegErrorMgrErrorExit(jpeg_common_struct* cinfo);
412 static void OJPEGLibjpegJpegSourceMgrInitSource(jpeg_decompress_struct* cinfo);
413 static boolean OJPEGLibjpegJpegSourceMgrFillInputBuffer(jpeg_decompress_struct* cinfo);
414 static void OJPEGLibjpegJpegSourceMgrSkipInputData(jpeg_decompress_struct* cinfo, long num_bytes);
415 static boolean OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct* cinfo, int desired);
416 static void OJPEGLibjpegJpegSourceMgrTermSource(jpeg_decompress_struct* cinfo);
419 TIFFInitOJPEG(TIFF* tif, int scheme)
421 static const char module[]="TIFFInitOJPEG";
424 assert(scheme==COMPRESSION_OJPEG);
427 * Merge codec-specific tag information.
429 if (!_TIFFMergeFields(tif, ojpegFields, TIFFArrayCount(ojpegFields))) {
430 TIFFErrorExt(tif->tif_clientdata, module,
431 "Merging Old JPEG codec-specific tags failed");
436 sp=_TIFFmalloc(sizeof(OJPEGState));
439 TIFFErrorExt(tif->tif_clientdata,module,"No space for OJPEG state block");
442 _TIFFmemset(sp,0,sizeof(OJPEGState));
445 sp->subsampling_hor=2;
446 sp->subsampling_ver=2;
447 TIFFSetField(tif,TIFFTAG_YCBCRSUBSAMPLING,2,2);
448 /* tif codec methods */
449 tif->tif_fixuptags=OJPEGFixupTags;
450 tif->tif_setupdecode=OJPEGSetupDecode;
451 tif->tif_predecode=OJPEGPreDecode;
452 tif->tif_postdecode=OJPEGPostDecode;
453 tif->tif_decoderow=OJPEGDecode;
454 tif->tif_decodestrip=OJPEGDecode;
455 tif->tif_decodetile=OJPEGDecode;
456 tif->tif_setupencode=OJPEGSetupEncode;
457 tif->tif_preencode=OJPEGPreEncode;
458 tif->tif_postencode=OJPEGPostEncode;
459 tif->tif_encoderow=OJPEGEncode;
460 tif->tif_encodestrip=OJPEGEncode;
461 tif->tif_encodetile=OJPEGEncode;
462 tif->tif_cleanup=OJPEGCleanup;
463 tif->tif_data=(uint8*)sp;
464 /* tif tag methods */
465 sp->vgetparent=tif->tif_tagmethods.vgetfield;
466 tif->tif_tagmethods.vgetfield=OJPEGVGetField;
467 sp->vsetparent=tif->tif_tagmethods.vsetfield;
468 tif->tif_tagmethods.vsetfield=OJPEGVSetField;
469 sp->printdir=tif->tif_tagmethods.printdir;
470 tif->tif_tagmethods.printdir=OJPEGPrintDir;
471 /* Some OJPEG files don't have strip or tile offsets or bytecounts tags.
472 Some others do, but have totally meaningless or corrupt values
473 in these tags. In these cases, the JpegInterchangeFormat stream is
474 reliable. In any case, this decoder reads the compressed data itself,
475 from the most reliable locations, and we need to notify encapsulating
476 LibTiff not to read raw strips or tiles for us. */
477 tif->tif_flags|=TIFF_NOREADRAW;
482 OJPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
484 OJPEGState* sp=(OJPEGState*)tif->tif_data;
487 case TIFFTAG_JPEGIFOFFSET:
488 *va_arg(ap,uint64*)=(uint64)sp->jpeg_interchange_format;
490 case TIFFTAG_JPEGIFBYTECOUNT:
491 *va_arg(ap,uint64*)=(uint64)sp->jpeg_interchange_format_length;
493 case TIFFTAG_YCBCRSUBSAMPLING:
494 if (sp->subsamplingcorrect_done==0)
495 OJPEGSubsamplingCorrect(tif);
496 *va_arg(ap,uint16*)=(uint16)sp->subsampling_hor;
497 *va_arg(ap,uint16*)=(uint16)sp->subsampling_ver;
499 case TIFFTAG_JPEGQTABLES:
500 *va_arg(ap,uint32*)=(uint32)sp->qtable_offset_count;
501 *va_arg(ap,void**)=(void*)sp->qtable_offset;
503 case TIFFTAG_JPEGDCTABLES:
504 *va_arg(ap,uint32*)=(uint32)sp->dctable_offset_count;
505 *va_arg(ap,void**)=(void*)sp->dctable_offset;
507 case TIFFTAG_JPEGACTABLES:
508 *va_arg(ap,uint32*)=(uint32)sp->actable_offset_count;
509 *va_arg(ap,void**)=(void*)sp->actable_offset;
511 case TIFFTAG_JPEGPROC:
512 *va_arg(ap,uint16*)=(uint16)sp->jpeg_proc;
514 case TIFFTAG_JPEGRESTARTINTERVAL:
515 *va_arg(ap,uint16*)=sp->restart_interval;
518 return (*sp->vgetparent)(tif,tag,ap);
524 OJPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
526 static const char module[]="OJPEGVSetField";
527 OJPEGState* sp=(OJPEGState*)tif->tif_data;
531 const TIFFField* fip;
535 case TIFFTAG_JPEGIFOFFSET:
536 sp->jpeg_interchange_format=(uint64)va_arg(ap,uint64);
538 case TIFFTAG_JPEGIFBYTECOUNT:
539 sp->jpeg_interchange_format_length=(uint64)va_arg(ap,uint64);
541 case TIFFTAG_YCBCRSUBSAMPLING:
542 sp->subsampling_tag=1;
543 sp->subsampling_hor=(uint8)va_arg(ap,uint16_vap);
544 sp->subsampling_ver=(uint8)va_arg(ap,uint16_vap);
545 tif->tif_dir.td_ycbcrsubsampling[0]=sp->subsampling_hor;
546 tif->tif_dir.td_ycbcrsubsampling[1]=sp->subsampling_ver;
548 case TIFFTAG_JPEGQTABLES:
549 ma=(uint32)va_arg(ap,uint32);
554 TIFFErrorExt(tif->tif_clientdata,module,"JpegQTables tag has incorrect count");
557 sp->qtable_offset_count=(uint8)ma;
558 mb=(uint64*)va_arg(ap,uint64*);
560 sp->qtable_offset[n]=mb[n];
563 case TIFFTAG_JPEGDCTABLES:
564 ma=(uint32)va_arg(ap,uint32);
569 TIFFErrorExt(tif->tif_clientdata,module,"JpegDcTables tag has incorrect count");
572 sp->dctable_offset_count=(uint8)ma;
573 mb=(uint64*)va_arg(ap,uint64*);
575 sp->dctable_offset[n]=mb[n];
578 case TIFFTAG_JPEGACTABLES:
579 ma=(uint32)va_arg(ap,uint32);
584 TIFFErrorExt(tif->tif_clientdata,module,"JpegAcTables tag has incorrect count");
587 sp->actable_offset_count=(uint8)ma;
588 mb=(uint64*)va_arg(ap,uint64*);
590 sp->actable_offset[n]=mb[n];
593 case TIFFTAG_JPEGPROC:
594 sp->jpeg_proc=(uint8)va_arg(ap,uint16_vap);
596 case TIFFTAG_JPEGRESTARTINTERVAL:
597 sp->restart_interval=(uint16)va_arg(ap,uint16_vap);
600 return (*sp->vsetparent)(tif,tag,ap);
602 fip = TIFFFieldWithTag(tif,tag);
603 if( fip == NULL ) /* shouldn't happen */
605 TIFFSetFieldBit(tif,fip->field_bit);
606 tif->tif_flags|=TIFF_DIRTYDIRECT;
611 OJPEGPrintDir(TIFF* tif, FILE* fd, long flags)
613 OJPEGState* sp=(OJPEGState*)tif->tif_data;
617 if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGINTERCHANGEFORMAT))
618 fprintf(fd," JpegInterchangeFormat: " TIFF_UINT64_FORMAT "\n",(TIFF_UINT64_T)sp->jpeg_interchange_format);
619 if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH))
620 fprintf(fd," JpegInterchangeFormatLength: " TIFF_UINT64_FORMAT "\n",(TIFF_UINT64_T)sp->jpeg_interchange_format_length);
621 if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGQTABLES))
623 fprintf(fd," JpegQTables:");
624 for (m=0; m<sp->qtable_offset_count; m++)
625 fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->qtable_offset[m]);
628 if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGDCTABLES))
630 fprintf(fd," JpegDcTables:");
631 for (m=0; m<sp->dctable_offset_count; m++)
632 fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->dctable_offset[m]);
635 if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGACTABLES))
637 fprintf(fd," JpegAcTables:");
638 for (m=0; m<sp->actable_offset_count; m++)
639 fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->actable_offset[m]);
642 if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGPROC))
643 fprintf(fd," JpegProc: %u\n",(unsigned int)sp->jpeg_proc);
644 if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGRESTARTINTERVAL))
645 fprintf(fd," JpegRestartInterval: %u\n",(unsigned int)sp->restart_interval);
647 (*sp->printdir)(tif, fd, flags);
651 OJPEGFixupTags(TIFF* tif)
658 OJPEGSetupDecode(TIFF* tif)
660 static const char module[]="OJPEGSetupDecode";
661 TIFFWarningExt(tif->tif_clientdata,module,"Depreciated and troublesome old-style JPEG compression mode, please convert to new-style JPEG compression and notify vendor of writing software");
666 OJPEGPreDecode(TIFF* tif, uint16 s)
668 OJPEGState* sp=(OJPEGState*)tif->tif_data;
670 if (sp->subsamplingcorrect_done==0)
671 OJPEGSubsamplingCorrect(tif);
672 if (sp->readheader_done==0)
674 if (OJPEGReadHeaderInfo(tif)==0)
677 if (sp->sos_end[s].log==0)
679 if (OJPEGReadSecondarySos(tif,s)==0)
686 if ((sp->writeheader_done!=0) && ((sp->write_cursample!=s) || (sp->write_curstrile>m)))
688 if (sp->libjpeg_session_active!=0)
689 OJPEGLibjpegSessionAbort(tif);
690 sp->writeheader_done=0;
692 if (sp->writeheader_done==0)
694 sp->plane_sample_offset=(uint8)s;
695 sp->write_cursample=s;
696 sp->write_curstrile=s*tif->tif_dir.td_stripsperimage;
697 if ((sp->in_buffer_file_pos_log==0) ||
698 (sp->in_buffer_file_pos-sp->in_buffer_togo!=sp->sos_end[s].in_buffer_file_pos))
700 sp->in_buffer_source=sp->sos_end[s].in_buffer_source;
701 sp->in_buffer_next_strile=sp->sos_end[s].in_buffer_next_strile;
702 sp->in_buffer_file_pos=sp->sos_end[s].in_buffer_file_pos;
703 sp->in_buffer_file_pos_log=0;
704 sp->in_buffer_file_togo=sp->sos_end[s].in_buffer_file_togo;
705 sp->in_buffer_togo=0;
708 if (OJPEGWriteHeaderInfo(tif)==0)
711 while (sp->write_curstrile<m)
713 if (sp->libjpeg_jpeg_query_style==0)
715 if (OJPEGPreDecodeSkipRaw(tif)==0)
720 if (OJPEGPreDecodeSkipScanlines(tif)==0)
723 sp->write_curstrile++;
730 OJPEGPreDecodeSkipRaw(TIFF* tif)
732 OJPEGState* sp=(OJPEGState*)tif->tif_data;
734 m=sp->lines_per_strile;
735 if (sp->subsampling_convert_state!=0)
737 if (sp->subsampling_convert_clines-sp->subsampling_convert_state>=m)
739 sp->subsampling_convert_state+=m;
740 if (sp->subsampling_convert_state==sp->subsampling_convert_clines)
741 sp->subsampling_convert_state=0;
744 m-=sp->subsampling_convert_clines-sp->subsampling_convert_state;
745 sp->subsampling_convert_state=0;
746 sp->error_in_raw_data_decoding=0;
748 while (m>=sp->subsampling_convert_clines)
750 if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0)
752 m-=sp->subsampling_convert_clines;
756 if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0)
758 sp->subsampling_convert_state=m;
764 OJPEGPreDecodeSkipScanlines(TIFF* tif)
766 static const char module[]="OJPEGPreDecodeSkipScanlines";
767 OJPEGState* sp=(OJPEGState*)tif->tif_data;
769 if (sp->skip_buffer==NULL)
771 sp->skip_buffer=_TIFFmalloc(sp->bytes_per_line);
772 if (sp->skip_buffer==NULL)
774 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
778 for (m=0; m<sp->lines_per_strile; m++)
780 if (jpeg_read_scanlines_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),&sp->skip_buffer,1)==0)
787 OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
789 static const char module[]="OJPEGDecode";
790 OJPEGState* sp=(OJPEGState*)tif->tif_data;
792 if( !sp->decoder_ok )
794 TIFFErrorExt(tif->tif_clientdata,module,"Cannot decode: decoder not correctly initialized");
797 if( sp->error_in_raw_data_decoding )
801 if (sp->libjpeg_jpeg_query_style==0)
803 if (OJPEGDecodeRaw(tif,buf,cc)==0)
808 if (OJPEGDecodeScanlines(tif,buf,cc)==0)
815 OJPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc)
817 static const char module[]="OJPEGDecodeRaw";
818 OJPEGState* sp=(OJPEGState*)tif->tif_data;
828 if (cc%sp->bytes_per_line!=0)
830 TIFFErrorExt(tif->tif_clientdata,module,"Fractional scanline not read");
838 if (sp->subsampling_convert_state==0)
840 const jpeg_decompress_struct* cinfo = &sp->libjpeg_jpeg_decompress_struct;
842 int last_col_width = 0;
846 if (cinfo->MCUs_per_row == 0)
848 sp->error_in_raw_data_decoding = 1;
851 for (i = 0; i < cinfo->comps_in_scan; ++i)
853 const jpeg_component_info* info = cinfo->cur_comp_info[i];
854 #if JPEG_LIB_VERSION >= 70
855 width += info->MCU_width * info->DCT_h_scaled_size;
856 last_col_width += info->last_col_width * info->DCT_h_scaled_size;
858 width += info->MCU_width * info->DCT_scaled_size;
859 last_col_width += info->last_col_width * info->DCT_scaled_size;
862 jpeg_bytes = (cinfo->MCUs_per_row - 1) * width + last_col_width;
863 expected_bytes = sp->subsampling_convert_clinelenout * sp->subsampling_ver * sp->subsampling_hor;
864 if (jpeg_bytes != expected_bytes)
866 TIFFErrorExt(tif->tif_clientdata,module,"Inconsistent number of MCU in codestream");
867 sp->error_in_raw_data_decoding = 1;
870 if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0)
872 sp->error_in_raw_data_decoding = 1;
876 oy=sp->subsampling_convert_ybuf+sp->subsampling_convert_state*sp->subsampling_ver*sp->subsampling_convert_ylinelen;
877 ocb=sp->subsampling_convert_cbbuf+sp->subsampling_convert_state*sp->subsampling_convert_clinelen;
878 ocr=sp->subsampling_convert_crbuf+sp->subsampling_convert_state*sp->subsampling_convert_clinelen;
880 for (q=0; q<sp->subsampling_convert_clinelenout; q++)
883 for (sy=0; sy<sp->subsampling_ver; sy++)
885 for (sx=0; sx<sp->subsampling_hor; sx++)
887 r+=sp->subsampling_convert_ylinelen-sp->subsampling_hor;
889 oy+=sp->subsampling_hor;
893 sp->subsampling_convert_state++;
894 if (sp->subsampling_convert_state==sp->subsampling_convert_clines)
895 sp->subsampling_convert_state=0;
896 m+=sp->bytes_per_line;
897 n-=sp->bytes_per_line;
903 OJPEGDecodeScanlines(TIFF* tif, uint8* buf, tmsize_t cc)
905 static const char module[]="OJPEGDecodeScanlines";
906 OJPEGState* sp=(OJPEGState*)tif->tif_data;
909 if (cc%sp->bytes_per_line!=0)
911 TIFFErrorExt(tif->tif_clientdata,module,"Fractional scanline not read");
919 if (jpeg_read_scanlines_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),&m,1)==0)
921 m+=sp->bytes_per_line;
922 n-=sp->bytes_per_line;
928 OJPEGPostDecode(TIFF* tif, uint8* buf, tmsize_t cc)
930 OJPEGState* sp=(OJPEGState*)tif->tif_data;
933 sp->write_curstrile++;
934 if (sp->write_curstrile%tif->tif_dir.td_stripsperimage==0)
936 assert(sp->libjpeg_session_active!=0);
937 OJPEGLibjpegSessionAbort(tif);
938 sp->writeheader_done=0;
943 OJPEGSetupEncode(TIFF* tif)
945 static const char module[]="OJPEGSetupEncode";
946 TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
951 OJPEGPreEncode(TIFF* tif, uint16 s)
953 static const char module[]="OJPEGPreEncode";
955 TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
960 OJPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
962 static const char module[]="OJPEGEncode";
966 TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
971 OJPEGPostEncode(TIFF* tif)
973 static const char module[]="OJPEGPostEncode";
974 TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
979 OJPEGCleanup(TIFF* tif)
981 OJPEGState* sp=(OJPEGState*)tif->tif_data;
984 tif->tif_tagmethods.vgetfield=sp->vgetparent;
985 tif->tif_tagmethods.vsetfield=sp->vsetparent;
986 tif->tif_tagmethods.printdir=sp->printdir;
987 if (sp->qtable[0]!=0)
988 _TIFFfree(sp->qtable[0]);
989 if (sp->qtable[1]!=0)
990 _TIFFfree(sp->qtable[1]);
991 if (sp->qtable[2]!=0)
992 _TIFFfree(sp->qtable[2]);
993 if (sp->qtable[3]!=0)
994 _TIFFfree(sp->qtable[3]);
995 if (sp->dctable[0]!=0)
996 _TIFFfree(sp->dctable[0]);
997 if (sp->dctable[1]!=0)
998 _TIFFfree(sp->dctable[1]);
999 if (sp->dctable[2]!=0)
1000 _TIFFfree(sp->dctable[2]);
1001 if (sp->dctable[3]!=0)
1002 _TIFFfree(sp->dctable[3]);
1003 if (sp->actable[0]!=0)
1004 _TIFFfree(sp->actable[0]);
1005 if (sp->actable[1]!=0)
1006 _TIFFfree(sp->actable[1]);
1007 if (sp->actable[2]!=0)
1008 _TIFFfree(sp->actable[2]);
1009 if (sp->actable[3]!=0)
1010 _TIFFfree(sp->actable[3]);
1011 if (sp->libjpeg_session_active!=0)
1012 OJPEGLibjpegSessionAbort(tif);
1013 if (sp->subsampling_convert_ycbcrbuf!=0)
1014 _TIFFfree(sp->subsampling_convert_ycbcrbuf);
1015 if (sp->subsampling_convert_ycbcrimage!=0)
1016 _TIFFfree(sp->subsampling_convert_ycbcrimage);
1017 if (sp->skip_buffer!=0)
1018 _TIFFfree(sp->skip_buffer);
1021 _TIFFSetDefaultCompressionState(tif);
1026 OJPEGSubsamplingCorrect(TIFF* tif)
1028 static const char module[]="OJPEGSubsamplingCorrect";
1029 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1033 assert(sp->subsamplingcorrect_done==0);
1034 if ((tif->tif_dir.td_samplesperpixel!=3) || ((tif->tif_dir.td_photometric!=PHOTOMETRIC_YCBCR) &&
1035 (tif->tif_dir.td_photometric!=PHOTOMETRIC_ITULAB)))
1037 if (sp->subsampling_tag!=0)
1038 TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag not appropriate for this Photometric and/or SamplesPerPixel");
1039 sp->subsampling_hor=1;
1040 sp->subsampling_ver=1;
1041 sp->subsampling_force_desubsampling_inside_decompression=0;
1045 sp->subsamplingcorrect_done=1;
1046 mh=sp->subsampling_hor;
1047 mv=sp->subsampling_ver;
1048 sp->subsamplingcorrect=1;
1049 OJPEGReadHeaderInfoSec(tif);
1050 if (sp->subsampling_force_desubsampling_inside_decompression!=0)
1052 sp->subsampling_hor=1;
1053 sp->subsampling_ver=1;
1055 sp->subsamplingcorrect=0;
1056 if (((sp->subsampling_hor!=mh) || (sp->subsampling_ver!=mv)) && (sp->subsampling_force_desubsampling_inside_decompression==0))
1058 if (sp->subsampling_tag==0)
1059 TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag is not set, yet subsampling inside JPEG data [%d,%d] does not match default values [2,2]; assuming subsampling inside JPEG data is correct",sp->subsampling_hor,sp->subsampling_ver);
1061 TIFFWarningExt(tif->tif_clientdata,module,"Subsampling inside JPEG data [%d,%d] does not match subsampling tag values [%d,%d]; assuming subsampling inside JPEG data is correct",sp->subsampling_hor,sp->subsampling_ver,mh,mv);
1063 if (sp->subsampling_force_desubsampling_inside_decompression!=0)
1065 if (sp->subsampling_tag==0)
1066 TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag is not set, yet subsampling inside JPEG data does not match default values [2,2] (nor any other values allowed in TIFF); assuming subsampling inside JPEG data is correct and desubsampling inside JPEG decompression");
1068 TIFFWarningExt(tif->tif_clientdata,module,"Subsampling inside JPEG data does not match subsampling tag values [%d,%d] (nor any other values allowed in TIFF); assuming subsampling inside JPEG data is correct and desubsampling inside JPEG decompression",mh,mv);
1070 if (sp->subsampling_force_desubsampling_inside_decompression==0)
1072 if (sp->subsampling_hor<sp->subsampling_ver)
1073 TIFFWarningExt(tif->tif_clientdata,module,"Subsampling values [%d,%d] are not allowed in TIFF",sp->subsampling_hor,sp->subsampling_ver);
1076 sp->subsamplingcorrect_done=1;
1080 OJPEGReadHeaderInfo(TIFF* tif)
1082 static const char module[]="OJPEGReadHeaderInfo";
1083 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1084 assert(sp->readheader_done==0);
1085 sp->image_width=tif->tif_dir.td_imagewidth;
1086 sp->image_length=tif->tif_dir.td_imagelength;
1089 sp->strile_width=tif->tif_dir.td_tilewidth;
1090 sp->strile_length=tif->tif_dir.td_tilelength;
1091 sp->strile_length_total=((sp->image_length+sp->strile_length-1)/sp->strile_length)*sp->strile_length;
1095 sp->strile_width=sp->image_width;
1096 sp->strile_length=tif->tif_dir.td_rowsperstrip;
1097 sp->strile_length_total=sp->image_length;
1099 if (tif->tif_dir.td_samplesperpixel==1)
1101 sp->samples_per_pixel=1;
1102 sp->plane_sample_offset=0;
1103 sp->samples_per_pixel_per_plane=sp->samples_per_pixel;
1104 sp->subsampling_hor=1;
1105 sp->subsampling_ver=1;
1109 if (tif->tif_dir.td_samplesperpixel!=3)
1111 TIFFErrorExt(tif->tif_clientdata,module,"SamplesPerPixel %d not supported for this compression scheme",sp->samples_per_pixel);
1114 sp->samples_per_pixel=3;
1115 sp->plane_sample_offset=0;
1116 if (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)
1117 sp->samples_per_pixel_per_plane=3;
1119 sp->samples_per_pixel_per_plane=1;
1121 if (sp->strile_length<sp->image_length)
1123 if (((sp->subsampling_hor!=1) && (sp->subsampling_hor!=2) && (sp->subsampling_hor!=4)) ||
1124 ((sp->subsampling_ver!=1) && (sp->subsampling_ver!=2) && (sp->subsampling_ver!=4)))
1126 TIFFErrorExt(tif->tif_clientdata,module,"Invalid subsampling values");
1129 if (sp->strile_length%(sp->subsampling_ver*8)!=0)
1131 TIFFErrorExt(tif->tif_clientdata,module,"Incompatible vertical subsampling and image strip/tile length");
1134 sp->restart_interval=(uint16)(((sp->strile_width+sp->subsampling_hor*8-1)/(sp->subsampling_hor*8))*(sp->strile_length/(sp->subsampling_ver*8)));
1136 if (OJPEGReadHeaderInfoSec(tif)==0)
1138 sp->sos_end[0].log=1;
1139 sp->sos_end[0].in_buffer_source=sp->in_buffer_source;
1140 sp->sos_end[0].in_buffer_next_strile=sp->in_buffer_next_strile;
1141 sp->sos_end[0].in_buffer_file_pos=sp->in_buffer_file_pos-sp->in_buffer_togo;
1142 sp->sos_end[0].in_buffer_file_togo=sp->in_buffer_file_togo+sp->in_buffer_togo;
1143 sp->readheader_done=1;
1148 OJPEGReadSecondarySos(TIFF* tif, uint16 s)
1150 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1154 assert(sp->sos_end[0].log!=0);
1155 assert(sp->sos_end[s].log==0);
1156 sp->plane_sample_offset=(uint8)(s-1);
1157 while(sp->sos_end[sp->plane_sample_offset].log==0)
1158 sp->plane_sample_offset--;
1159 sp->in_buffer_source=sp->sos_end[sp->plane_sample_offset].in_buffer_source;
1160 sp->in_buffer_next_strile=sp->sos_end[sp->plane_sample_offset].in_buffer_next_strile;
1161 sp->in_buffer_file_pos=sp->sos_end[sp->plane_sample_offset].in_buffer_file_pos;
1162 sp->in_buffer_file_pos_log=0;
1163 sp->in_buffer_file_togo=sp->sos_end[sp->plane_sample_offset].in_buffer_file_togo;
1164 sp->in_buffer_togo=0;
1165 sp->in_buffer_cur=0;
1166 while(sp->plane_sample_offset<s)
1170 if (OJPEGReadByte(sp,&m)==0)
1176 if (OJPEGReadByte(sp,&m)==0)
1181 if (m==JPEG_MARKER_SOS)
1185 sp->plane_sample_offset++;
1186 if (OJPEGReadHeaderInfoSecStreamSos(tif)==0)
1188 sp->sos_end[sp->plane_sample_offset].log=1;
1189 sp->sos_end[sp->plane_sample_offset].in_buffer_source=sp->in_buffer_source;
1190 sp->sos_end[sp->plane_sample_offset].in_buffer_next_strile=sp->in_buffer_next_strile;
1191 sp->sos_end[sp->plane_sample_offset].in_buffer_file_pos=sp->in_buffer_file_pos-sp->in_buffer_togo;
1192 sp->sos_end[sp->plane_sample_offset].in_buffer_file_togo=sp->in_buffer_file_togo+sp->in_buffer_togo;
1198 OJPEGWriteHeaderInfo(TIFF* tif)
1200 static const char module[]="OJPEGWriteHeaderInfo";
1201 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1204 /* if a previous attempt failed, don't try again */
1205 if (sp->libjpeg_session_active != 0)
1207 sp->out_state=ososSoi;
1208 sp->restart_index=0;
1209 jpeg_std_error(&(sp->libjpeg_jpeg_error_mgr));
1210 sp->libjpeg_jpeg_error_mgr.output_message=OJPEGLibjpegJpegErrorMgrOutputMessage;
1211 sp->libjpeg_jpeg_error_mgr.error_exit=OJPEGLibjpegJpegErrorMgrErrorExit;
1212 sp->libjpeg_jpeg_decompress_struct.err=&(sp->libjpeg_jpeg_error_mgr);
1213 sp->libjpeg_jpeg_decompress_struct.client_data=(void*)tif;
1214 if (jpeg_create_decompress_encap(sp,&(sp->libjpeg_jpeg_decompress_struct))==0)
1216 sp->libjpeg_session_active=1;
1217 sp->libjpeg_jpeg_source_mgr.bytes_in_buffer=0;
1218 sp->libjpeg_jpeg_source_mgr.init_source=OJPEGLibjpegJpegSourceMgrInitSource;
1219 sp->libjpeg_jpeg_source_mgr.fill_input_buffer=OJPEGLibjpegJpegSourceMgrFillInputBuffer;
1220 sp->libjpeg_jpeg_source_mgr.skip_input_data=OJPEGLibjpegJpegSourceMgrSkipInputData;
1221 sp->libjpeg_jpeg_source_mgr.resync_to_restart=OJPEGLibjpegJpegSourceMgrResyncToRestart;
1222 sp->libjpeg_jpeg_source_mgr.term_source=OJPEGLibjpegJpegSourceMgrTermSource;
1223 sp->libjpeg_jpeg_decompress_struct.src=&(sp->libjpeg_jpeg_source_mgr);
1224 if (jpeg_read_header_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),1)==0)
1226 if ((sp->subsampling_force_desubsampling_inside_decompression==0) && (sp->samples_per_pixel_per_plane>1))
1228 sp->libjpeg_jpeg_decompress_struct.raw_data_out=1;
1229 #if JPEG_LIB_VERSION >= 70
1230 sp->libjpeg_jpeg_decompress_struct.do_fancy_upsampling=FALSE;
1232 sp->libjpeg_jpeg_query_style=0;
1233 if (sp->subsampling_convert_log==0)
1235 assert(sp->subsampling_convert_ycbcrbuf==0);
1236 assert(sp->subsampling_convert_ycbcrimage==0);
1237 sp->subsampling_convert_ylinelen=((sp->strile_width+sp->subsampling_hor*8-1)/(sp->subsampling_hor*8)*sp->subsampling_hor*8);
1238 sp->subsampling_convert_ylines=sp->subsampling_ver*8;
1239 sp->subsampling_convert_clinelen=sp->subsampling_convert_ylinelen/sp->subsampling_hor;
1240 sp->subsampling_convert_clines=8;
1241 sp->subsampling_convert_ybuflen=sp->subsampling_convert_ylinelen*sp->subsampling_convert_ylines;
1242 sp->subsampling_convert_cbuflen=sp->subsampling_convert_clinelen*sp->subsampling_convert_clines;
1243 sp->subsampling_convert_ycbcrbuflen=sp->subsampling_convert_ybuflen+2*sp->subsampling_convert_cbuflen;
1244 /* The calloc is not normally necessary, except in some edge/broken cases */
1245 /* for example for a tiled image of height 1 with a tile height of 1 and subsampling_hor=subsampling_ver=2 */
1246 /* In that case, libjpeg will only fill the 8 first lines of the 16 lines */
1247 /* See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=16844 */
1248 /* Even if this case is allowed (?), its handling is broken because OJPEGPreDecode() should also likely */
1249 /* reset subsampling_convert_state to 0 when changing tile. */
1250 sp->subsampling_convert_ycbcrbuf=_TIFFcalloc(1, sp->subsampling_convert_ycbcrbuflen);
1251 if (sp->subsampling_convert_ycbcrbuf==0)
1253 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1256 sp->subsampling_convert_ybuf=sp->subsampling_convert_ycbcrbuf;
1257 sp->subsampling_convert_cbbuf=sp->subsampling_convert_ybuf+sp->subsampling_convert_ybuflen;
1258 sp->subsampling_convert_crbuf=sp->subsampling_convert_cbbuf+sp->subsampling_convert_cbuflen;
1259 sp->subsampling_convert_ycbcrimagelen=3+sp->subsampling_convert_ylines+2*sp->subsampling_convert_clines;
1260 sp->subsampling_convert_ycbcrimage=_TIFFmalloc(sp->subsampling_convert_ycbcrimagelen*sizeof(uint8*));
1261 if (sp->subsampling_convert_ycbcrimage==0)
1263 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1266 m=sp->subsampling_convert_ycbcrimage;
1267 *m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3);
1268 *m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3+sp->subsampling_convert_ylines);
1269 *m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3+sp->subsampling_convert_ylines+sp->subsampling_convert_clines);
1270 for (n=0; n<sp->subsampling_convert_ylines; n++)
1271 *m++=sp->subsampling_convert_ybuf+n*sp->subsampling_convert_ylinelen;
1272 for (n=0; n<sp->subsampling_convert_clines; n++)
1273 *m++=sp->subsampling_convert_cbbuf+n*sp->subsampling_convert_clinelen;
1274 for (n=0; n<sp->subsampling_convert_clines; n++)
1275 *m++=sp->subsampling_convert_crbuf+n*sp->subsampling_convert_clinelen;
1276 sp->subsampling_convert_clinelenout=sp->strile_width/sp->subsampling_hor + ((sp->strile_width % sp->subsampling_hor) != 0 ? 1 : 0);
1277 sp->subsampling_convert_state=0;
1278 sp->error_in_raw_data_decoding=0;
1279 sp->bytes_per_line=sp->subsampling_convert_clinelenout*(sp->subsampling_ver*sp->subsampling_hor+2);
1280 sp->lines_per_strile=sp->strile_length/sp->subsampling_ver + ((sp->strile_length % sp->subsampling_ver) != 0 ? 1 : 0);
1281 sp->subsampling_convert_log=1;
1286 sp->libjpeg_jpeg_decompress_struct.jpeg_color_space=JCS_UNKNOWN;
1287 sp->libjpeg_jpeg_decompress_struct.out_color_space=JCS_UNKNOWN;
1288 sp->libjpeg_jpeg_query_style=1;
1289 sp->bytes_per_line=sp->samples_per_pixel_per_plane*sp->strile_width;
1290 sp->lines_per_strile=sp->strile_length;
1292 if (jpeg_start_decompress_encap(sp,&(sp->libjpeg_jpeg_decompress_struct))==0)
1294 sp->writeheader_done=1;
1299 OJPEGLibjpegSessionAbort(TIFF* tif)
1301 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1302 assert(sp->libjpeg_session_active!=0);
1303 jpeg_destroy((jpeg_common_struct*)(&(sp->libjpeg_jpeg_decompress_struct)));
1304 sp->libjpeg_session_active=0;
1308 OJPEGReadHeaderInfoSec(TIFF* tif)
1310 static const char module[]="OJPEGReadHeaderInfoSec";
1311 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1315 if (sp->file_size==0)
1316 sp->file_size=TIFFGetFileSize(tif);
1317 if (sp->jpeg_interchange_format!=0)
1319 if (sp->jpeg_interchange_format>=sp->file_size)
1321 sp->jpeg_interchange_format=0;
1322 sp->jpeg_interchange_format_length=0;
1326 if ((sp->jpeg_interchange_format_length==0) ||
1327 (sp->jpeg_interchange_format > TIFF_UINT64_MAX - sp->jpeg_interchange_format_length) ||
1328 (sp->jpeg_interchange_format+sp->jpeg_interchange_format_length>sp->file_size))
1329 sp->jpeg_interchange_format_length=sp->file_size-sp->jpeg_interchange_format;
1332 sp->in_buffer_source=osibsNotSetYet;
1333 sp->in_buffer_next_strile=0;
1334 sp->in_buffer_strile_count=tif->tif_dir.td_nstrips;
1335 sp->in_buffer_file_togo=0;
1336 sp->in_buffer_togo=0;
1339 if (OJPEGReadBytePeek(sp,&m)==0)
1343 OJPEGReadByteAdvance(sp);
1346 if (OJPEGReadByte(sp,&m)==0)
1351 case JPEG_MARKER_SOI:
1352 /* this type of marker has no data, and should be skipped */
1354 case JPEG_MARKER_COM:
1355 case JPEG_MARKER_APP0:
1356 case JPEG_MARKER_APP0+1:
1357 case JPEG_MARKER_APP0+2:
1358 case JPEG_MARKER_APP0+3:
1359 case JPEG_MARKER_APP0+4:
1360 case JPEG_MARKER_APP0+5:
1361 case JPEG_MARKER_APP0+6:
1362 case JPEG_MARKER_APP0+7:
1363 case JPEG_MARKER_APP0+8:
1364 case JPEG_MARKER_APP0+9:
1365 case JPEG_MARKER_APP0+10:
1366 case JPEG_MARKER_APP0+11:
1367 case JPEG_MARKER_APP0+12:
1368 case JPEG_MARKER_APP0+13:
1369 case JPEG_MARKER_APP0+14:
1370 case JPEG_MARKER_APP0+15:
1371 /* this type of marker has data, but it has no use to us (and no place here) and should be skipped */
1372 if (OJPEGReadWord(sp,&n)==0)
1376 if (sp->subsamplingcorrect==0)
1377 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JPEG data");
1381 OJPEGReadSkip(sp,n-2);
1383 case JPEG_MARKER_DRI:
1384 if (OJPEGReadHeaderInfoSecStreamDri(tif)==0)
1387 case JPEG_MARKER_DQT:
1388 if (OJPEGReadHeaderInfoSecStreamDqt(tif)==0)
1391 case JPEG_MARKER_DHT:
1392 if (OJPEGReadHeaderInfoSecStreamDht(tif)==0)
1395 case JPEG_MARKER_SOF0:
1396 case JPEG_MARKER_SOF1:
1397 case JPEG_MARKER_SOF3:
1398 if (OJPEGReadHeaderInfoSecStreamSof(tif,m)==0)
1400 if (sp->subsamplingcorrect!=0)
1403 case JPEG_MARKER_SOS:
1404 if (sp->subsamplingcorrect!=0)
1406 assert(sp->plane_sample_offset==0);
1407 if (OJPEGReadHeaderInfoSecStreamSos(tif)==0)
1411 TIFFErrorExt(tif->tif_clientdata,module,"Unknown marker type %d in JPEG data",m);
1414 } while(m!=JPEG_MARKER_SOS);
1415 if (sp->subsamplingcorrect)
1419 if (OJPEGReadHeaderInfoSecTablesQTable(tif)==0)
1421 sp->sof_marker_id=JPEG_MARKER_SOF0;
1422 for (o=0; o<sp->samples_per_pixel; o++)
1424 sp->sof_hv[0]=((sp->subsampling_hor<<4)|sp->subsampling_ver);
1425 for (o=1; o<sp->samples_per_pixel; o++)
1427 sp->sof_x=sp->strile_width;
1428 sp->sof_y=sp->strile_length_total;
1430 if (OJPEGReadHeaderInfoSecTablesDcTable(tif)==0)
1432 if (OJPEGReadHeaderInfoSecTablesAcTable(tif)==0)
1434 for (o=1; o<sp->samples_per_pixel; o++)
1441 OJPEGReadHeaderInfoSecStreamDri(TIFF* tif)
1443 /* This could easily cause trouble in some cases... but no such cases have
1445 static const char module[]="OJPEGReadHeaderInfoSecStreamDri";
1446 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1448 if (OJPEGReadWord(sp,&m)==0)
1452 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DRI marker in JPEG data");
1455 if (OJPEGReadWord(sp,&m)==0)
1457 sp->restart_interval=m;
1462 OJPEGReadHeaderInfoSecStreamDqt(TIFF* tif)
1464 /* this is a table marker, and it is to be saved as a whole for exact pushing on the jpeg stream later on */
1465 static const char module[]="OJPEGReadHeaderInfoSecStreamDqt";
1466 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1471 if (OJPEGReadWord(sp,&m)==0)
1475 if (sp->subsamplingcorrect==0)
1476 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data");
1479 if (sp->subsamplingcorrect!=0)
1480 OJPEGReadSkip(sp,m-2);
1488 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data");
1491 na=sizeof(uint32)+69;
1495 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1499 nb[sizeof(uint32)]=255;
1500 nb[sizeof(uint32)+1]=JPEG_MARKER_DQT;
1501 nb[sizeof(uint32)+2]=0;
1502 nb[sizeof(uint32)+3]=67;
1503 if (OJPEGReadBlock(sp,65,&nb[sizeof(uint32)+4])==0) {
1507 o=nb[sizeof(uint32)+4]&15;
1510 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data");
1514 if (sp->qtable[o]!=0)
1515 _TIFFfree(sp->qtable[o]);
1524 OJPEGReadHeaderInfoSecStreamDht(TIFF* tif)
1526 /* this is a table marker, and it is to be saved as a whole for exact pushing on the jpeg stream later on */
1527 /* TODO: the following assumes there is only one table in this marker... but i'm not quite sure that assumption is guaranteed correct */
1528 static const char module[]="OJPEGReadHeaderInfoSecStreamDht";
1529 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1534 if (OJPEGReadWord(sp,&m)==0)
1538 if (sp->subsamplingcorrect==0)
1539 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
1542 if (sp->subsamplingcorrect!=0)
1544 OJPEGReadSkip(sp,m-2);
1548 na=sizeof(uint32)+2+m;
1552 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1556 nb[sizeof(uint32)]=255;
1557 nb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
1558 nb[sizeof(uint32)+2]=(m>>8);
1559 nb[sizeof(uint32)+3]=(m&255);
1560 if (OJPEGReadBlock(sp,m-2,&nb[sizeof(uint32)+4])==0) {
1564 o=nb[sizeof(uint32)+4];
1569 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
1573 if (sp->dctable[o]!=0)
1574 _TIFFfree(sp->dctable[o]);
1581 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
1588 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
1592 if (sp->actable[o]!=0)
1593 _TIFFfree(sp->actable[o]);
1601 OJPEGReadHeaderInfoSecStreamSof(TIFF* tif, uint8 marker_id)
1603 /* this marker needs to be checked, and part of its data needs to be saved for regeneration later on */
1604 static const char module[]="OJPEGReadHeaderInfoSecStreamSof";
1605 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1613 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JPEG data");
1616 if (sp->subsamplingcorrect==0)
1617 sp->sof_marker_id=marker_id;
1618 /* Lf: data length */
1619 if (OJPEGReadWord(sp,&m)==0)
1623 if (sp->subsamplingcorrect==0)
1624 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data");
1630 if (sp->subsamplingcorrect==0)
1631 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data");
1635 if (sp->subsamplingcorrect==0)
1637 if (n!=sp->samples_per_pixel)
1639 TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected number of samples");
1643 /* P: Sample precision */
1644 if (OJPEGReadByte(sp,&o)==0)
1648 if (sp->subsamplingcorrect==0)
1649 TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected number of bits per sample");
1652 /* Y: Number of lines, X: Number of samples per line */
1653 if (sp->subsamplingcorrect)
1654 OJPEGReadSkip(sp,4);
1657 /* Y: Number of lines */
1658 if (OJPEGReadWord(sp,&p)==0)
1660 if (((uint32)p<sp->image_length) && ((uint32)p<sp->strile_length_total))
1662 TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected height");
1666 /* X: Number of samples per line */
1667 if (OJPEGReadWord(sp,&p)==0)
1669 if (((uint32)p<sp->image_width) && ((uint32)p<sp->strile_width))
1671 TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected width");
1674 if ((uint32)p>sp->strile_width)
1676 TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data image width exceeds expected image width");
1681 /* Nf: Number of image components in frame */
1682 if (OJPEGReadByte(sp,&o)==0)
1686 if (sp->subsamplingcorrect==0)
1687 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data");
1690 /* per component stuff */
1691 /* TODO: double-check that flow implies that n cannot be as big as to make us overflow sof_c, sof_hv and sof_tq arrays */
1694 /* C: Component identifier */
1695 if (OJPEGReadByte(sp,&o)==0)
1697 if (sp->subsamplingcorrect==0)
1699 /* H: Horizontal sampling factor, and V: Vertical sampling factor */
1700 if (OJPEGReadByte(sp,&o)==0)
1702 if (sp->subsamplingcorrect!=0)
1706 sp->subsampling_hor=(o>>4);
1707 sp->subsampling_ver=(o&15);
1708 if (((sp->subsampling_hor!=1) && (sp->subsampling_hor!=2) && (sp->subsampling_hor!=4)) ||
1709 ((sp->subsampling_ver!=1) && (sp->subsampling_ver!=2) && (sp->subsampling_ver!=4)))
1710 sp->subsampling_force_desubsampling_inside_decompression=1;
1715 sp->subsampling_force_desubsampling_inside_decompression=1;
1721 if (sp->subsampling_force_desubsampling_inside_decompression==0)
1725 if (o!=((sp->subsampling_hor<<4)|sp->subsampling_ver))
1727 TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected subsampling values");
1735 TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected subsampling values");
1741 /* Tq: Quantization table destination selector */
1742 if (OJPEGReadByte(sp,&o)==0)
1744 if (sp->subsamplingcorrect==0)
1747 if (sp->subsamplingcorrect==0)
1753 OJPEGReadHeaderInfoSecStreamSos(TIFF* tif)
1755 /* this marker needs to be checked, and part of its data needs to be saved for regeneration later on */
1756 static const char module[]="OJPEGReadHeaderInfoSecStreamSos";
1757 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1761 assert(sp->subsamplingcorrect==0);
1764 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data");
1768 if (OJPEGReadWord(sp,&m)==0)
1770 if (m!=6+sp->samples_per_pixel_per_plane*2)
1772 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data");
1776 if (OJPEGReadByte(sp,&n)==0)
1778 if (n!=sp->samples_per_pixel_per_plane)
1780 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data");
1783 /* Cs, Td, and Ta */
1784 for (o=0; o<sp->samples_per_pixel_per_plane; o++)
1787 if (OJPEGReadByte(sp,&n)==0)
1789 sp->sos_cs[sp->plane_sample_offset+o]=n;
1791 if (OJPEGReadByte(sp,&n)==0)
1793 sp->sos_tda[sp->plane_sample_offset+o]=n;
1795 /* skip Ss, Se, Ah, en Al -> no check, as per Tom Lane recommendation, as per LibJpeg source */
1796 OJPEGReadSkip(sp,3);
1801 OJPEGReadHeaderInfoSecTablesQTable(TIFF* tif)
1803 static const char module[]="OJPEGReadHeaderInfoSecTablesQTable";
1804 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1810 if (sp->qtable_offset[0]==0)
1812 TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables");
1815 sp->in_buffer_file_pos_log=0;
1816 for (m=0; m<sp->samples_per_pixel; m++)
1818 if ((sp->qtable_offset[m]!=0) && ((m==0) || (sp->qtable_offset[m]!=sp->qtable_offset[m-1])))
1820 for (n=0; n<m-1; n++)
1822 if (sp->qtable_offset[m]==sp->qtable_offset[n])
1824 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegQTables tag value");
1828 oa=sizeof(uint32)+69;
1832 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1836 ob[sizeof(uint32)]=255;
1837 ob[sizeof(uint32)+1]=JPEG_MARKER_DQT;
1838 ob[sizeof(uint32)+2]=0;
1839 ob[sizeof(uint32)+3]=67;
1840 ob[sizeof(uint32)+4]=m;
1841 TIFFSeekFile(tif,sp->qtable_offset[m],SEEK_SET);
1842 p=(uint32)TIFFReadFile(tif,&ob[sizeof(uint32)+5],64);
1848 if (sp->qtable[m]!=0)
1849 _TIFFfree(sp->qtable[m]);
1854 sp->sof_tq[m]=sp->sof_tq[m-1];
1860 OJPEGReadHeaderInfoSecTablesDcTable(TIFF* tif)
1862 static const char module[]="OJPEGReadHeaderInfoSecTablesDcTable";
1863 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1871 if (sp->dctable_offset[0]==0)
1873 TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables");
1876 sp->in_buffer_file_pos_log=0;
1877 for (m=0; m<sp->samples_per_pixel; m++)
1879 if ((sp->dctable_offset[m]!=0) && ((m==0) || (sp->dctable_offset[m]!=sp->dctable_offset[m-1])))
1881 for (n=0; n<m-1; n++)
1883 if (sp->dctable_offset[m]==sp->dctable_offset[n])
1885 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegDcTables tag value");
1889 TIFFSeekFile(tif,sp->dctable_offset[m],SEEK_SET);
1890 p=(uint32)TIFFReadFile(tif,o,16);
1894 for (n=0; n<16; n++)
1896 ra=sizeof(uint32)+21+q;
1900 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1904 rb[sizeof(uint32)]=255;
1905 rb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
1906 rb[sizeof(uint32)+2]=(uint8)((19+q)>>8);
1907 rb[sizeof(uint32)+3]=((19+q)&255);
1908 rb[sizeof(uint32)+4]=m;
1909 for (n=0; n<16; n++)
1910 rb[sizeof(uint32)+5+n]=o[n];
1911 p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
1917 if (sp->dctable[m]!=0)
1918 _TIFFfree(sp->dctable[m]);
1920 sp->sos_tda[m]=(m<<4);
1923 sp->sos_tda[m]=sp->sos_tda[m-1];
1929 OJPEGReadHeaderInfoSecTablesAcTable(TIFF* tif)
1931 static const char module[]="OJPEGReadHeaderInfoSecTablesAcTable";
1932 OJPEGState* sp=(OJPEGState*)tif->tif_data;
1940 if (sp->actable_offset[0]==0)
1942 TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables");
1945 sp->in_buffer_file_pos_log=0;
1946 for (m=0; m<sp->samples_per_pixel; m++)
1948 if ((sp->actable_offset[m]!=0) && ((m==0) || (sp->actable_offset[m]!=sp->actable_offset[m-1])))
1950 for (n=0; n<m-1; n++)
1952 if (sp->actable_offset[m]==sp->actable_offset[n])
1954 TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegAcTables tag value");
1958 TIFFSeekFile(tif,sp->actable_offset[m],SEEK_SET);
1959 p=(uint32)TIFFReadFile(tif,o,16);
1963 for (n=0; n<16; n++)
1965 ra=sizeof(uint32)+21+q;
1969 TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
1973 rb[sizeof(uint32)]=255;
1974 rb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
1975 rb[sizeof(uint32)+2]=(uint8)((19+q)>>8);
1976 rb[sizeof(uint32)+3]=((19+q)&255);
1977 rb[sizeof(uint32)+4]=(16|m);
1978 for (n=0; n<16; n++)
1979 rb[sizeof(uint32)+5+n]=o[n];
1980 p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
1986 if (sp->actable[m]!=0)
1987 _TIFFfree(sp->actable[m]);
1989 sp->sos_tda[m]=(sp->sos_tda[m]|m);
1992 sp->sos_tda[m]=(sp->sos_tda[m]|(sp->sos_tda[m-1]&15));
1998 OJPEGReadBufferFill(OJPEGState* sp)
2002 /* TODO: double-check: when subsamplingcorrect is set, no call to TIFFErrorExt or TIFFWarningExt should be made
2003 * in any other case, seek or read errors should be passed through */
2006 if (sp->in_buffer_file_togo!=0)
2008 if (sp->in_buffer_file_pos_log==0)
2010 TIFFSeekFile(sp->tif,sp->in_buffer_file_pos,SEEK_SET);
2011 sp->in_buffer_file_pos_log=1;
2014 if ((uint64)m>sp->in_buffer_file_togo)
2015 m=(uint16)sp->in_buffer_file_togo;
2016 n=TIFFReadFile(sp->tif,sp->in_buffer,(tmsize_t)m);
2020 assert(n<=OJPEG_BUFFER);
2022 assert((uint64)n<=sp->in_buffer_file_togo);
2024 sp->in_buffer_togo=m;
2025 sp->in_buffer_cur=sp->in_buffer;
2026 sp->in_buffer_file_togo-=m;
2027 sp->in_buffer_file_pos+=m;
2030 sp->in_buffer_file_pos_log=0;
2031 switch(sp->in_buffer_source)
2033 case osibsNotSetYet:
2034 if (sp->jpeg_interchange_format!=0)
2036 sp->in_buffer_file_pos=sp->jpeg_interchange_format;
2037 sp->in_buffer_file_togo=sp->jpeg_interchange_format_length;
2039 sp->in_buffer_source=osibsJpegInterchangeFormat;
2041 case osibsJpegInterchangeFormat:
2042 sp->in_buffer_source=osibsStrile;
2045 if (sp->in_buffer_next_strile==sp->in_buffer_strile_count)
2046 sp->in_buffer_source=osibsEof;
2050 sp->in_buffer_file_pos=TIFFGetStrileOffsetWithErr(sp->tif, sp->in_buffer_next_strile, &err);
2053 if (sp->in_buffer_file_pos!=0)
2055 uint64 bytecount = TIFFGetStrileByteCountWithErr(sp->tif, sp->in_buffer_next_strile, &err);
2058 if (sp->in_buffer_file_pos>=sp->file_size)
2059 sp->in_buffer_file_pos=0;
2060 else if (bytecount==0)
2061 sp->in_buffer_file_togo=sp->file_size-sp->in_buffer_file_pos;
2064 sp->in_buffer_file_togo=bytecount;
2065 if (sp->in_buffer_file_togo==0)
2066 sp->in_buffer_file_pos=0;
2067 else if (sp->in_buffer_file_pos > TIFF_UINT64_MAX - sp->in_buffer_file_togo ||
2068 sp->in_buffer_file_pos+sp->in_buffer_file_togo>sp->file_size)
2069 sp->in_buffer_file_togo=sp->file_size-sp->in_buffer_file_pos;
2072 sp->in_buffer_next_strile++;
2083 OJPEGReadByte(OJPEGState* sp, uint8* byte)
2085 if (sp->in_buffer_togo==0)
2087 if (OJPEGReadBufferFill(sp)==0)
2089 assert(sp->in_buffer_togo>0);
2091 *byte=*(sp->in_buffer_cur);
2092 sp->in_buffer_cur++;
2093 sp->in_buffer_togo--;
2098 OJPEGReadBytePeek(OJPEGState* sp, uint8* byte)
2100 if (sp->in_buffer_togo==0)
2102 if (OJPEGReadBufferFill(sp)==0)
2104 assert(sp->in_buffer_togo>0);
2106 *byte=*(sp->in_buffer_cur);
2111 OJPEGReadByteAdvance(OJPEGState* sp)
2113 assert(sp->in_buffer_togo>0);
2114 sp->in_buffer_cur++;
2115 sp->in_buffer_togo--;
2119 OJPEGReadWord(OJPEGState* sp, uint16* word)
2122 if (OJPEGReadByte(sp,&m)==0)
2125 if (OJPEGReadByte(sp,&m)==0)
2132 OJPEGReadBlock(OJPEGState* sp, uint16 len, void* mem)
2142 if (sp->in_buffer_togo==0)
2144 if (OJPEGReadBufferFill(sp)==0)
2146 assert(sp->in_buffer_togo>0);
2149 if (n>sp->in_buffer_togo)
2150 n=sp->in_buffer_togo;
2151 _TIFFmemcpy(mmem,sp->in_buffer_cur,n);
2152 sp->in_buffer_cur+=n;
2153 sp->in_buffer_togo-=n;
2161 OJPEGReadSkip(OJPEGState* sp, uint16 len)
2167 if (n>sp->in_buffer_togo)
2168 n=sp->in_buffer_togo;
2169 sp->in_buffer_cur+=n;
2170 sp->in_buffer_togo-=n;
2174 assert(sp->in_buffer_togo==0);
2176 if ((uint64)n>sp->in_buffer_file_togo)
2177 n=(uint16)sp->in_buffer_file_togo;
2178 sp->in_buffer_file_pos+=n;
2179 sp->in_buffer_file_togo-=n;
2180 sp->in_buffer_file_pos_log=0;
2181 /* we don't skip past jpeginterchangeformat/strile block...
2182 * if that is asked from us, we're dealing with totally bazurk
2183 * data anyway, and we've not seen this happening on any
2184 * testfile, so we might as well likely cause some other
2185 * meaningless error to be passed at some later time
2191 OJPEGWriteStream(TIFF* tif, void** mem, uint32* len)
2193 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2197 assert(sp->out_state<=ososEoi);
2198 switch(sp->out_state)
2201 OJPEGWriteStreamSoi(tif,mem,len);
2204 OJPEGWriteStreamQTable(tif,0,mem,len);
2207 OJPEGWriteStreamQTable(tif,1,mem,len);
2210 OJPEGWriteStreamQTable(tif,2,mem,len);
2213 OJPEGWriteStreamQTable(tif,3,mem,len);
2216 OJPEGWriteStreamDcTable(tif,0,mem,len);
2219 OJPEGWriteStreamDcTable(tif,1,mem,len);
2222 OJPEGWriteStreamDcTable(tif,2,mem,len);
2225 OJPEGWriteStreamDcTable(tif,3,mem,len);
2228 OJPEGWriteStreamAcTable(tif,0,mem,len);
2231 OJPEGWriteStreamAcTable(tif,1,mem,len);
2234 OJPEGWriteStreamAcTable(tif,2,mem,len);
2237 OJPEGWriteStreamAcTable(tif,3,mem,len);
2240 OJPEGWriteStreamDri(tif,mem,len);
2243 OJPEGWriteStreamSof(tif,mem,len);
2246 OJPEGWriteStreamSos(tif,mem,len);
2248 case ososCompressed:
2249 if (OJPEGWriteStreamCompressed(tif,mem,len)==0)
2253 OJPEGWriteStreamRst(tif,mem,len);
2256 OJPEGWriteStreamEoi(tif,mem,len);
2264 OJPEGWriteStreamSoi(TIFF* tif, void** mem, uint32* len)
2266 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2267 assert(OJPEG_BUFFER>=2);
2268 sp->out_buffer[0]=255;
2269 sp->out_buffer[1]=JPEG_MARKER_SOI;
2271 *mem=(void*)sp->out_buffer;
2276 OJPEGWriteStreamQTable(TIFF* tif, uint8 table_index, void** mem, uint32* len)
2278 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2279 if (sp->qtable[table_index]!=0)
2281 *mem=(void*)(sp->qtable[table_index]+sizeof(uint32));
2282 *len=*((uint32*)sp->qtable[table_index])-sizeof(uint32);
2288 OJPEGWriteStreamDcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len)
2290 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2291 if (sp->dctable[table_index]!=0)
2293 *mem=(void*)(sp->dctable[table_index]+sizeof(uint32));
2294 *len=*((uint32*)sp->dctable[table_index])-sizeof(uint32);
2300 OJPEGWriteStreamAcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len)
2302 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2303 if (sp->actable[table_index]!=0)
2305 *mem=(void*)(sp->actable[table_index]+sizeof(uint32));
2306 *len=*((uint32*)sp->actable[table_index])-sizeof(uint32);
2312 OJPEGWriteStreamDri(TIFF* tif, void** mem, uint32* len)
2314 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2315 assert(OJPEG_BUFFER>=6);
2316 if (sp->restart_interval!=0)
2318 sp->out_buffer[0]=255;
2319 sp->out_buffer[1]=JPEG_MARKER_DRI;
2320 sp->out_buffer[2]=0;
2321 sp->out_buffer[3]=4;
2322 sp->out_buffer[4]=(sp->restart_interval>>8);
2323 sp->out_buffer[5]=(sp->restart_interval&255);
2325 *mem=(void*)sp->out_buffer;
2331 OJPEGWriteStreamSof(TIFF* tif, void** mem, uint32* len)
2333 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2335 assert(OJPEG_BUFFER>=2+8+sp->samples_per_pixel_per_plane*3);
2336 assert(255>=8+sp->samples_per_pixel_per_plane*3);
2337 sp->out_buffer[0]=255;
2338 sp->out_buffer[1]=sp->sof_marker_id;
2340 sp->out_buffer[2]=0;
2341 sp->out_buffer[3]=8+sp->samples_per_pixel_per_plane*3;
2343 sp->out_buffer[4]=8;
2345 sp->out_buffer[5]=(uint8)(sp->sof_y>>8);
2346 sp->out_buffer[6]=(sp->sof_y&255);
2348 sp->out_buffer[7]=(uint8)(sp->sof_x>>8);
2349 sp->out_buffer[8]=(sp->sof_x&255);
2351 sp->out_buffer[9]=sp->samples_per_pixel_per_plane;
2352 for (m=0; m<sp->samples_per_pixel_per_plane; m++)
2355 sp->out_buffer[10+m*3]=sp->sof_c[sp->plane_sample_offset+m];
2357 sp->out_buffer[10+m*3+1]=sp->sof_hv[sp->plane_sample_offset+m];
2359 sp->out_buffer[10+m*3+2]=sp->sof_tq[sp->plane_sample_offset+m];
2361 *len=10+sp->samples_per_pixel_per_plane*3;
2362 *mem=(void*)sp->out_buffer;
2367 OJPEGWriteStreamSos(TIFF* tif, void** mem, uint32* len)
2369 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2371 assert(OJPEG_BUFFER>=2+6+sp->samples_per_pixel_per_plane*2);
2372 assert(255>=6+sp->samples_per_pixel_per_plane*2);
2373 sp->out_buffer[0]=255;
2374 sp->out_buffer[1]=JPEG_MARKER_SOS;
2376 sp->out_buffer[2]=0;
2377 sp->out_buffer[3]=6+sp->samples_per_pixel_per_plane*2;
2379 sp->out_buffer[4]=sp->samples_per_pixel_per_plane;
2380 for (m=0; m<sp->samples_per_pixel_per_plane; m++)
2383 sp->out_buffer[5+m*2]=sp->sos_cs[sp->plane_sample_offset+m];
2385 sp->out_buffer[5+m*2+1]=sp->sos_tda[sp->plane_sample_offset+m];
2388 sp->out_buffer[5+sp->samples_per_pixel_per_plane*2]=0;
2390 sp->out_buffer[5+sp->samples_per_pixel_per_plane*2+1]=63;
2392 sp->out_buffer[5+sp->samples_per_pixel_per_plane*2+2]=0;
2393 *len=8+sp->samples_per_pixel_per_plane*2;
2394 *mem=(void*)sp->out_buffer;
2399 OJPEGWriteStreamCompressed(TIFF* tif, void** mem, uint32* len)
2401 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2402 if (sp->in_buffer_togo==0)
2404 if (OJPEGReadBufferFill(sp)==0)
2406 assert(sp->in_buffer_togo>0);
2408 *len=sp->in_buffer_togo;
2409 *mem=(void*)sp->in_buffer_cur;
2410 sp->in_buffer_togo=0;
2411 if (sp->in_buffer_file_togo==0)
2413 switch(sp->in_buffer_source)
2416 if (sp->in_buffer_next_strile<sp->in_buffer_strile_count)
2417 sp->out_state=ososRst;
2419 sp->out_state=ososEoi;
2422 sp->out_state=ososEoi;
2432 OJPEGWriteStreamRst(TIFF* tif, void** mem, uint32* len)
2434 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2435 assert(OJPEG_BUFFER>=2);
2436 sp->out_buffer[0]=255;
2437 sp->out_buffer[1]=JPEG_MARKER_RST0+sp->restart_index;
2438 sp->restart_index++;
2439 if (sp->restart_index==8)
2440 sp->restart_index=0;
2442 *mem=(void*)sp->out_buffer;
2443 sp->out_state=ososCompressed;
2447 OJPEGWriteStreamEoi(TIFF* tif, void** mem, uint32* len)
2449 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2450 assert(OJPEG_BUFFER>=2);
2451 sp->out_buffer[0]=255;
2452 sp->out_buffer[1]=JPEG_MARKER_EOI;
2454 *mem=(void*)sp->out_buffer;
2457 #ifndef LIBJPEG_ENCAP_EXTERNAL
2459 jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo)
2461 if( SETJMP(sp->exit_jmpbuf) )
2464 jpeg_create_decompress(cinfo);
2470 #ifndef LIBJPEG_ENCAP_EXTERNAL
2472 jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image)
2474 if( SETJMP(sp->exit_jmpbuf) )
2477 jpeg_read_header(cinfo,require_image);
2483 #ifndef LIBJPEG_ENCAP_EXTERNAL
2485 jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo)
2487 if( SETJMP(sp->exit_jmpbuf) )
2490 jpeg_start_decompress(cinfo);
2496 #ifndef LIBJPEG_ENCAP_EXTERNAL
2498 jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines)
2500 if( SETJMP(sp->exit_jmpbuf) )
2503 jpeg_read_scanlines(cinfo,scanlines,max_lines);
2509 #ifndef LIBJPEG_ENCAP_EXTERNAL
2511 jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines)
2513 if( SETJMP(sp->exit_jmpbuf) )
2516 jpeg_read_raw_data(cinfo,data,max_lines);
2522 #ifndef LIBJPEG_ENCAP_EXTERNAL
2524 jpeg_encap_unwind(TIFF* tif)
2526 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2527 LONGJMP(sp->exit_jmpbuf,1);
2532 OJPEGLibjpegJpegErrorMgrOutputMessage(jpeg_common_struct* cinfo)
2534 char buffer[JMSG_LENGTH_MAX];
2535 (*cinfo->err->format_message)(cinfo,buffer);
2536 TIFFWarningExt(((TIFF*)(cinfo->client_data))->tif_clientdata,"LibJpeg","%s",buffer);
2540 OJPEGLibjpegJpegErrorMgrErrorExit(jpeg_common_struct* cinfo)
2542 char buffer[JMSG_LENGTH_MAX];
2543 (*cinfo->err->format_message)(cinfo,buffer);
2544 TIFFErrorExt(((TIFF*)(cinfo->client_data))->tif_clientdata,"LibJpeg","%s",buffer);
2545 jpeg_encap_unwind((TIFF*)(cinfo->client_data));
2549 OJPEGLibjpegJpegSourceMgrInitSource(jpeg_decompress_struct* cinfo)
2555 OJPEGLibjpegJpegSourceMgrFillInputBuffer(jpeg_decompress_struct* cinfo)
2557 TIFF* tif=(TIFF*)cinfo->client_data;
2558 OJPEGState* sp=(OJPEGState*)tif->tif_data;
2561 if (OJPEGWriteStream(tif,&mem,&len)==0)
2563 TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Premature end of JPEG data");
2564 jpeg_encap_unwind(tif);
2566 sp->libjpeg_jpeg_source_mgr.bytes_in_buffer=len;
2567 sp->libjpeg_jpeg_source_mgr.next_input_byte=mem;
2572 OJPEGLibjpegJpegSourceMgrSkipInputData(jpeg_decompress_struct* cinfo, long num_bytes)
2574 TIFF* tif=(TIFF*)cinfo->client_data;
2576 TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Unexpected error");
2577 jpeg_encap_unwind(tif);
2581 #pragma warning( push )
2582 #pragma warning( disable : 4702 ) /* unreachable code */
2585 OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct* cinfo, int desired)
2587 TIFF* tif=(TIFF*)cinfo->client_data;
2589 TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Unexpected error");
2590 jpeg_encap_unwind(tif);
2594 #pragma warning( pop )
2598 OJPEGLibjpegJpegSourceMgrTermSource(jpeg_decompress_struct* cinfo)