Coverage Report

Created: 2025-06-24 07:02

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