Coverage Report

Created: 2026-06-30 08:33

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