Coverage Report

Created: 2025-12-03 08:24

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