Coverage Report

Created: 2025-12-31 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/frmts/gtiff/libtiff/tif_jpeg.c
Line
Count
Source
1
/*
2
 * Copyright (c) 1994-1997 Sam Leffler
3
 * Copyright (c) 1994-1997 Silicon Graphics, Inc.
4
 *
5
 * Permission to use, copy, modify, distribute, and sell this software and
6
 * its documentation for any purpose is hereby granted without fee, provided
7
 * that (i) the above copyright notices and this permission notice appear in
8
 * all copies of the software and related documentation, and (ii) the names of
9
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
10
 * publicity relating to the software without the specific, prior written
11
 * permission of Sam Leffler and Silicon Graphics.
12
 *
13
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
14
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
15
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
16
 *
17
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
21
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22
 * OF THIS SOFTWARE.
23
 */
24
25
#define WIN32_LEAN_AND_MEAN
26
#define VC_EXTRALEAN
27
28
#include "tiffiop.h"
29
#include <stdlib.h>
30
31
#ifdef JPEG_SUPPORT
32
33
/*
34
 * TIFF Library
35
 *
36
 * JPEG Compression support per TIFF Technical Note #2
37
 * (*not* per the original TIFF 6.0 spec).
38
 *
39
 * This file is simply an interface to the libjpeg library written by
40
 * the Independent JPEG Group.  You need release 5 or later of the IJG
41
 * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
42
 *
43
 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
44
 */
45
#include <setjmp.h>
46
47
/* Settings that are independent of libjpeg ABI. Used when reinitializing the */
48
/* JPEGState from libjpegs 8 bit to libjpeg 12 bits, which have potentially */
49
/* different ABI */
50
typedef struct
51
{
52
    TIFFVGetMethod vgetparent;  /* super-class method */
53
    TIFFVSetMethod vsetparent;  /* super-class method */
54
    TIFFPrintMethod printdir;   /* super-class method */
55
    TIFFStripMethod defsparent; /* super-class method */
56
    TIFFTileMethod deftparent;  /* super-class method */
57
58
    /* pseudo-tag fields */
59
    void *jpegtables;           /* JPEGTables tag value, or NULL */
60
    uint32_t jpegtables_length; /* number of bytes in same */
61
    int jpegquality;            /* Compression quality level */
62
    int jpegcolormode;          /* Auto RGB<=>YCbCr convert? */
63
    int jpegtablesmode;         /* What to put in JPEGTables */
64
65
    int ycbcrsampling_fetched;
66
    int max_allowed_scan_number;
67
    int has_warned_about_progressive_mode;
68
} JPEGOtherSettings;
69
70
int TIFFFillStrip(TIFF *tif, uint32_t strip);
71
int TIFFFillTile(TIFF *tif, uint32_t tile);
72
int TIFFReInitJPEG_12(TIFF *tif, const JPEGOtherSettings *otherSettings,
73
                      int scheme, int is_encode);
74
int TIFFJPEGIsFullStripRequired_12(TIFF *tif);
75
76
#include "jerror.h"
77
#include "jpeglib.h"
78
79
/* Do optional compile-time version check */
80
#if defined(EXPECTED_JPEG_LIB_VERSION) && !defined(LIBJPEG_12_PATH)
81
#if EXPECTED_JPEG_LIB_VERSION != JPEG_LIB_VERSION
82
#error EXPECTED_JPEG_LIB_VERSION != JPEG_LIB_VERSION
83
#endif
84
#endif
85
86
/*
87
 * Do we want to do special processing suitable for when JSAMPLE is a
88
 * 16bit value?
89
 */
90
91
/* HAVE_JPEGTURBO_DUAL_MODE_8_12 is defined for libjpeg-turbo >= 3.0 which
92
 * adds a dual-mode 8/12 bit API in the same library.
93
 * (note: libjpeg-turbo 2.2 was actually released as 3.0)
94
 */
95
96
#if defined(HAVE_JPEGTURBO_DUAL_MODE_8_12)
97
#define JPEG_DUAL_MODE_8_12
98
/* Start by undefining BITS_IN_JSAMPLE which is always set to 8 in libjpeg-turbo
99
 * >= 3.0 Cf
100
 * https://github.com/libjpeg-turbo/libjpeg-turbo/commit/8b9bc4b9635a2a047fb23ebe70c9acd728d3f99b
101
 */
102
#undef BITS_IN_JSAMPLE
103
/* libjpeg-turbo >= 3.0 adds J12xxxx datatypes for the 12-bit mode. */
104
#if defined(FROM_TIF_JPEG_12)
105
#define BITS_IN_JSAMPLE 12
106
#define TIFF_JSAMPLE J12SAMPLE
107
#define TIFF_JSAMPARRAY J12SAMPARRAY
108
#define TIFF_JSAMPIMAGE J12SAMPIMAGE
109
#define TIFF_JSAMPROW J12SAMPROW
110
#else
111
#define BITS_IN_JSAMPLE 8
112
#define TIFF_JSAMPLE JSAMPLE
113
#define TIFF_JSAMPARRAY JSAMPARRAY
114
#define TIFF_JSAMPIMAGE JSAMPIMAGE
115
#define TIFF_JSAMPROW JSAMPROW
116
#endif
117
#else
118
0
#define TIFF_JSAMPLE JSAMPLE
119
0
#define TIFF_JSAMPARRAY JSAMPARRAY
120
#define TIFF_JSAMPIMAGE JSAMPIMAGE
121
0
#define TIFF_JSAMPROW JSAMPROW
122
#endif
123
124
#if defined(JPEG_LIB_MK1)
125
#define JPEG_LIB_MK1_OR_12BIT 1
126
#elif BITS_IN_JSAMPLE == 12
127
#define JPEG_LIB_MK1_OR_12BIT 1
128
#endif
129
130
/*
131
 * We are using width_in_blocks which is supposed to be private to
132
 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
133
 * renamed this member to width_in_data_units.  Since the header has
134
 * also renamed a define, use that unique define name in order to
135
 * detect the problem header and adjust to suit.
136
 */
137
#if defined(D_MAX_DATA_UNITS_IN_MCU)
138
#define width_in_blocks width_in_data_units
139
#endif
140
141
/*
142
 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
143
 * in place of plain setjmp.  These macros will make it easier.
144
 */
145
0
#define SETJMP(jbuf) setjmp(jbuf)
146
0
#define LONGJMP(jbuf, code) longjmp(jbuf, code)
147
#define JMP_BUF jmp_buf
148
149
#ifndef TIFF_jpeg_destination_mgr_defined
150
#define TIFF_jpeg_destination_mgr_defined
151
typedef struct jpeg_destination_mgr jpeg_destination_mgr;
152
#endif
153
154
#ifndef TIFF_jpeg_source_mgr_defined
155
#define TIFF_jpeg_source_mgr_defined
156
typedef struct jpeg_source_mgr jpeg_source_mgr;
157
#endif
158
159
#ifndef TIFF_jpeg_error_mgr_defined
160
#define TIFF_jpeg_error_mgr_defined
161
typedef struct jpeg_error_mgr jpeg_error_mgr;
162
#endif
163
164
/*
165
 * State block for each open TIFF file using
166
 * libjpeg to do JPEG compression/decompression.
167
 *
168
 * libjpeg's visible state is either a jpeg_compress_struct
169
 * or jpeg_decompress_struct depending on which way we
170
 * are going.  comm can be used to refer to the fields
171
 * which are common to both.
172
 *
173
 * NB: cinfo is required to be the first member of JPEGState,
174
 *     so we can safely cast JPEGState* -> jpeg_xxx_struct*
175
 *     and vice versa!
176
 */
177
#ifdef _MSC_VER
178
#pragma warning(push)
179
#pragma warning(disable : 4324) /* structure padding due to alignment */
180
#endif
181
typedef struct
182
{
183
    union
184
    {
185
        struct jpeg_compress_struct c;
186
        struct jpeg_decompress_struct d;
187
        struct jpeg_common_struct comm;
188
    } cinfo; /* NB: must be first */
189
    int cinfo_initialized;
190
191
    jpeg_error_mgr err;  /* libjpeg error manager */
192
    JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
193
194
    struct jpeg_progress_mgr progress;
195
    /*
196
     * The following two members could be a union, but
197
     * they're small enough that it's not worth the effort.
198
     */
199
    jpeg_destination_mgr dest; /* data dest for compression */
200
    jpeg_source_mgr src;       /* data source for decompression */
201
                               /* private state */
202
    TIFF *tif;                 /* back link needed by some code */
203
    uint16_t photometric;      /* copy of PhotometricInterpretation */
204
    uint16_t h_sampling;       /* luminance sampling factors */
205
    uint16_t v_sampling;
206
    tmsize_t bytesperline; /* decompressed bytes per scanline */
207
    /* pointers to intermediate buffers when processing downsampled data */
208
    TIFF_JSAMPARRAY ds_buffer[MAX_COMPONENTS];
209
    int scancount; /* number of "scanlines" accumulated */
210
    int samplesperclump;
211
212
    JPEGOtherSettings otherSettings;
213
214
    int encode_raw_error;
215
} JPEGState;
216
#ifdef _MSC_VER
217
#pragma warning(pop)
218
#endif
219
220
0
#define JState(tif) ((JPEGState *)(tif)->tif_data)
221
222
static int JPEGDecode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
223
static int JPEGDecodeRaw(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
224
static int JPEGEncode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
225
static int JPEGEncodeRaw(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
226
static int JPEGInitializeLibJPEG(TIFF *tif, int decode);
227
static int DecodeRowError(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
228
229
#define FIELD_JPEGTABLES (FIELD_CODEC + 0)
230
231
static const TIFFField jpegFields[] = {
232
    {TIFFTAG_JPEGTABLES, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8,
233
     FIELD_JPEGTABLES, FALSE, TRUE, "JPEGTables", NULL},
234
    {TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, FIELD_PSEUDO,
235
     TRUE, FALSE, "", NULL},
236
    {TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, FIELD_PSEUDO,
237
     FALSE, FALSE, "", NULL},
238
    {TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, FIELD_PSEUDO,
239
     FALSE, FALSE, "", NULL}};
240
241
/*
242
 * libjpeg interface layer.
243
 *
244
 * We use setjmp/longjmp to return control to libtiff
245
 * when a fatal error is encountered within the JPEG
246
 * library.  We also direct libjpeg error and warning
247
 * messages through the appropriate libtiff handlers.
248
 */
249
250
/*
251
 * Error handling routines (these replace corresponding
252
 * IJG routines from jerror.c).  These are used for both
253
 * compression and decompression.
254
 */
255
static void TIFFjpeg_error_exit(j_common_ptr cinfo)
256
0
{
257
0
    JPEGState *sp = (JPEGState *)cinfo; /* NB: cinfo assumed first */
258
0
    char buffer[JMSG_LENGTH_MAX];
259
260
0
    (*cinfo->err->format_message)(cinfo, buffer);
261
0
    TIFFErrorExtR(sp->tif, "JPEGLib", "%s",
262
0
                  buffer);       /* display the error message */
263
0
    jpeg_abort(cinfo);           /* clean up libjpeg state */
264
0
    LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
265
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_error_exit
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_error_exit
266
267
/*
268
 * This routine is invoked only for warning messages,
269
 * since error_exit does its own thing and trace_level
270
 * is never set > 0.
271
 */
272
static void TIFFjpeg_output_message(j_common_ptr cinfo)
273
0
{
274
0
    char buffer[JMSG_LENGTH_MAX];
275
276
0
    (*cinfo->err->format_message)(cinfo, buffer);
277
0
    TIFFWarningExtR(((JPEGState *)cinfo)->tif, "JPEGLib", "%s", buffer);
278
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_output_message
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_output_message
279
280
/* Avoid the risk of denial-of-service on crafted JPEGs with an insane */
281
/* number of scans. */
282
/* See
283
 * http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf
284
 */
285
static void TIFFjpeg_progress_monitor(j_common_ptr cinfo)
286
0
{
287
0
    JPEGState *sp = (JPEGState *)cinfo; /* NB: cinfo assumed first */
288
0
    if (cinfo->is_decompressor)
289
0
    {
290
0
        const int scan_no = ((j_decompress_ptr)cinfo)->input_scan_number;
291
0
        if (scan_no >= sp->otherSettings.max_allowed_scan_number)
292
0
        {
293
0
            TIFFErrorExtR(
294
0
                ((JPEGState *)cinfo)->tif, "TIFFjpeg_progress_monitor",
295
0
                "Scan number %d exceeds maximum scans (%d). This limit "
296
0
                "can be raised through the "
297
0
                "LIBTIFF_JPEG_MAX_ALLOWED_SCAN_NUMBER "
298
0
                "environment variable.",
299
0
                scan_no, sp->otherSettings.max_allowed_scan_number);
300
301
0
            jpeg_abort(cinfo);           /* clean up libjpeg state */
302
0
            LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
303
0
        }
304
0
    }
305
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_progress_monitor
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_progress_monitor
306
307
/*
308
 * Interface routines.  This layer of routines exists
309
 * primarily to limit side-effects from using setjmp.
310
 * Also, normal/error returns are converted into return
311
 * values per libtiff practice.
312
 */
313
0
#define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
314
0
#define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op), 1))
315
316
static int TIFFjpeg_create_compress(JPEGState *sp)
317
0
{
318
    /* initialize JPEG error handling */
319
0
    sp->cinfo.c.err = jpeg_std_error(&sp->err);
320
0
    sp->err.error_exit = TIFFjpeg_error_exit;
321
0
    sp->err.output_message = TIFFjpeg_output_message;
322
323
    /* set client_data to avoid UMR warning from tools like Purify */
324
0
    sp->cinfo.c.client_data = NULL;
325
326
0
    return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
327
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_create_compress
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_create_compress
328
329
static int TIFFjpeg_create_decompress(JPEGState *sp)
330
0
{
331
    /* initialize JPEG error handling */
332
0
    sp->cinfo.d.err = jpeg_std_error(&sp->err);
333
0
    sp->err.error_exit = TIFFjpeg_error_exit;
334
0
    sp->err.output_message = TIFFjpeg_output_message;
335
336
    /* set client_data to avoid UMR warning from tools like Purify */
337
0
    sp->cinfo.d.client_data = NULL;
338
339
0
    return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
340
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_create_decompress
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_create_decompress
341
342
static int TIFFjpeg_set_defaults(JPEGState *sp)
343
0
{
344
0
    return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
345
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_set_defaults
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_set_defaults
346
347
static int TIFFjpeg_set_colorspace(JPEGState *sp, J_COLOR_SPACE colorspace)
348
0
{
349
0
    return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
350
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_set_colorspace
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_set_colorspace
351
352
static int TIFFjpeg_set_quality(JPEGState *sp, int quality,
353
                                boolean force_baseline)
354
0
{
355
0
    return CALLVJPEG(sp,
356
0
                     jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
357
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_set_quality
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_set_quality
358
359
static int TIFFjpeg_suppress_tables(JPEGState *sp, boolean suppress)
360
0
{
361
0
    return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
362
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_suppress_tables
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_suppress_tables
363
364
static int TIFFjpeg_start_compress(JPEGState *sp, boolean write_all_tables)
365
0
{
366
0
    return CALLVJPEG(sp, jpeg_start_compress(&sp->cinfo.c, write_all_tables));
367
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_start_compress
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_start_compress
368
369
static int TIFFjpeg_write_scanlines(JPEGState *sp, TIFF_JSAMPARRAY scanlines,
370
                                    int num_lines)
371
0
{
372
#if defined(HAVE_JPEGTURBO_DUAL_MODE_8_12) && BITS_IN_JSAMPLE == 12
373
    return CALLJPEG(sp, -1,
374
                    (int)jpeg12_write_scanlines(&sp->cinfo.c, scanlines,
375
                                                (JDIMENSION)num_lines));
376
#else
377
0
    return CALLJPEG(sp, -1,
378
0
                    (int)jpeg_write_scanlines(&sp->cinfo.c, scanlines,
379
0
                                              (JDIMENSION)num_lines));
380
0
#endif
381
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_write_scanlines
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_write_scanlines
382
383
static int TIFFjpeg_write_raw_data(JPEGState *sp, TIFF_JSAMPIMAGE data,
384
                                   int num_lines)
385
0
{
386
#if defined(HAVE_JPEGTURBO_DUAL_MODE_8_12) && BITS_IN_JSAMPLE == 12
387
    return CALLJPEG(
388
        sp, -1,
389
        (int)jpeg12_write_raw_data(&sp->cinfo.c, data, (JDIMENSION)num_lines));
390
#else
391
0
    return CALLJPEG(
392
0
        sp, -1,
393
0
        (int)jpeg_write_raw_data(&sp->cinfo.c, data, (JDIMENSION)num_lines));
394
0
#endif
395
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_write_raw_data
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_write_raw_data
396
397
static int TIFFjpeg_finish_compress(JPEGState *sp)
398
0
{
399
0
    return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
400
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_finish_compress
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_finish_compress
401
402
static int TIFFjpeg_write_tables(JPEGState *sp)
403
0
{
404
0
    return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
405
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_write_tables
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_write_tables
406
407
static int TIFFjpeg_read_header(JPEGState *sp, boolean require_image)
408
0
{
409
0
    return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
410
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_read_header
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_read_header
411
412
static int TIFFjpeg_has_multiple_scans(JPEGState *sp)
413
0
{
414
0
    return CALLJPEG(sp, 0, jpeg_has_multiple_scans(&sp->cinfo.d));
415
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_has_multiple_scans
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_has_multiple_scans
416
417
static int TIFFjpeg_start_decompress(JPEGState *sp)
418
0
{
419
0
    const char *sz_max_allowed_scan_number;
420
    /* progress monitor */
421
0
    sp->cinfo.d.progress = &sp->progress;
422
0
    sp->progress.progress_monitor = TIFFjpeg_progress_monitor;
423
0
    sp->otherSettings.max_allowed_scan_number = 100;
424
0
    sz_max_allowed_scan_number = getenv("LIBTIFF_JPEG_MAX_ALLOWED_SCAN_NUMBER");
425
0
    if (sz_max_allowed_scan_number)
426
0
        sp->otherSettings.max_allowed_scan_number =
427
0
            atoi(sz_max_allowed_scan_number);
428
429
0
    return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
430
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_start_decompress
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_start_decompress
431
432
static int TIFFjpeg_read_scanlines(JPEGState *sp, TIFF_JSAMPARRAY scanlines,
433
                                   int max_lines)
434
0
{
435
#if defined(HAVE_JPEGTURBO_DUAL_MODE_8_12) && BITS_IN_JSAMPLE == 12
436
    return CALLJPEG(sp, -1,
437
                    (int)jpeg12_read_scanlines(&sp->cinfo.d, scanlines,
438
                                               (JDIMENSION)max_lines));
439
#else
440
0
    return CALLJPEG(sp, -1,
441
0
                    (int)jpeg_read_scanlines(&sp->cinfo.d, scanlines,
442
0
                                             (JDIMENSION)max_lines));
443
0
#endif
444
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_read_scanlines
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_read_scanlines
445
446
static int TIFFjpeg_read_raw_data(JPEGState *sp, TIFF_JSAMPIMAGE data,
447
                                  int max_lines)
448
0
{
449
#if defined(HAVE_JPEGTURBO_DUAL_MODE_8_12) && BITS_IN_JSAMPLE == 12
450
    return CALLJPEG(
451
        sp, -1,
452
        (int)jpeg12_read_raw_data(&sp->cinfo.d, data, (JDIMENSION)max_lines));
453
#else
454
0
    return CALLJPEG(
455
0
        sp, -1,
456
0
        (int)jpeg_read_raw_data(&sp->cinfo.d, data, (JDIMENSION)max_lines));
457
0
#endif
458
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_read_raw_data
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_read_raw_data
459
460
static int TIFFjpeg_finish_decompress(JPEGState *sp)
461
0
{
462
0
    return CALLJPEG(sp, -1, (int)jpeg_finish_decompress(&sp->cinfo.d));
463
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_finish_decompress
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_finish_decompress
464
465
static int TIFFjpeg_abort(JPEGState *sp)
466
0
{
467
0
    return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
468
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_abort
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_abort
469
470
static int TIFFjpeg_destroy(JPEGState *sp)
471
0
{
472
0
    return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
473
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_destroy
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_destroy
474
475
static JSAMPARRAY TIFFjpeg_alloc_sarray(JPEGState *sp, int pool_id,
476
                                        JDIMENSION samplesperrow,
477
                                        JDIMENSION numrows)
478
0
{
479
0
    return CALLJPEG(sp, (JSAMPARRAY)NULL,
480
0
                    (*sp->cinfo.comm.mem->alloc_sarray)(
481
0
                        &sp->cinfo.comm, pool_id, samplesperrow, numrows));
482
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_alloc_sarray
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_alloc_sarray
483
484
/*
485
 * JPEG library destination data manager.
486
 * These routines direct compressed data from libjpeg into the
487
 * libtiff output buffer.
488
 */
489
490
static void std_init_destination(j_compress_ptr cinfo)
491
0
{
492
0
    JPEGState *sp = (JPEGState *)cinfo;
493
0
    TIFF *tif = sp->tif;
494
495
0
    sp->dest.next_output_byte = (JOCTET *)tif->tif_rawdata;
496
0
    sp->dest.free_in_buffer = (size_t)tif->tif_rawdatasize;
497
0
}
Unexecuted instantiation: tif_jpeg.c:std_init_destination
Unexecuted instantiation: tif_jpeg_12.c:std_init_destination
498
499
static boolean std_empty_output_buffer(j_compress_ptr cinfo)
500
0
{
501
0
    JPEGState *sp = (JPEGState *)cinfo;
502
0
    TIFF *tif = sp->tif;
503
504
    /* the entire buffer has been filled */
505
0
    tif->tif_rawcc = tif->tif_rawdatasize;
506
507
#ifdef IPPJ_HUFF
508
    /*
509
     * The Intel IPP performance library does not necessarily fill up
510
     * the whole output buffer on each pass, so only dump out the parts
511
     * that have been filled.
512
     *   http://trac.osgeo.org/gdal/wiki/JpegIPP
513
     */
514
    if (sp->dest.free_in_buffer >= 0)
515
    {
516
        tif->tif_rawcc = tif->tif_rawdatasize - sp->dest.free_in_buffer;
517
    }
518
#endif
519
520
0
    if (!TIFFFlushData1(tif))
521
0
        return FALSE;
522
0
    sp->dest.next_output_byte = (JOCTET *)tif->tif_rawdata;
523
0
    sp->dest.free_in_buffer = (size_t)tif->tif_rawdatasize;
524
525
0
    return (TRUE);
526
0
}
Unexecuted instantiation: tif_jpeg.c:std_empty_output_buffer
Unexecuted instantiation: tif_jpeg_12.c:std_empty_output_buffer
527
528
static void std_term_destination(j_compress_ptr cinfo)
529
0
{
530
0
    JPEGState *sp = (JPEGState *)cinfo;
531
0
    TIFF *tif = sp->tif;
532
533
0
    tif->tif_rawcp = (uint8_t *)sp->dest.next_output_byte;
534
0
    tif->tif_rawcc = tif->tif_rawdatasize - (tmsize_t)sp->dest.free_in_buffer;
535
    /* NB: libtiff does the final buffer flush */
536
0
}
Unexecuted instantiation: tif_jpeg.c:std_term_destination
Unexecuted instantiation: tif_jpeg_12.c:std_term_destination
537
538
static void TIFFjpeg_data_dest(JPEGState *sp, TIFF *tif)
539
0
{
540
0
    (void)tif;
541
0
    sp->cinfo.c.dest = &sp->dest;
542
0
    sp->dest.init_destination = std_init_destination;
543
0
    sp->dest.empty_output_buffer = std_empty_output_buffer;
544
0
    sp->dest.term_destination = std_term_destination;
545
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_data_dest
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_data_dest
546
547
/*
548
 * Alternate destination manager for outputting to JPEGTables field.
549
 */
550
551
static void tables_init_destination(j_compress_ptr cinfo)
552
0
{
553
0
    JPEGState *sp = (JPEGState *)cinfo;
554
555
    /* while building, otherSettings.jpegtables_length is allocated buffer size
556
     */
557
0
    sp->dest.next_output_byte = (JOCTET *)sp->otherSettings.jpegtables;
558
0
    sp->dest.free_in_buffer = (size_t)sp->otherSettings.jpegtables_length;
559
0
}
Unexecuted instantiation: tif_jpeg.c:tables_init_destination
Unexecuted instantiation: tif_jpeg_12.c:tables_init_destination
560
561
static boolean tables_empty_output_buffer(j_compress_ptr cinfo)
562
0
{
563
0
    JPEGState *sp = (JPEGState *)cinfo;
564
0
    void *newbuf;
565
566
    /* the entire buffer has been filled; enlarge it by 1000 bytes */
567
0
    newbuf =
568
0
        _TIFFreallocExt(sp->tif, (void *)sp->otherSettings.jpegtables,
569
0
                        (tmsize_t)(sp->otherSettings.jpegtables_length + 1000));
570
0
    if (newbuf == NULL)
571
0
        ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
572
0
    sp->dest.next_output_byte =
573
0
        (JOCTET *)newbuf + sp->otherSettings.jpegtables_length;
574
0
    sp->dest.free_in_buffer = (size_t)1000;
575
0
    sp->otherSettings.jpegtables = newbuf;
576
0
    sp->otherSettings.jpegtables_length += 1000;
577
0
    return (TRUE);
578
0
}
Unexecuted instantiation: tif_jpeg.c:tables_empty_output_buffer
Unexecuted instantiation: tif_jpeg_12.c:tables_empty_output_buffer
579
580
static void tables_term_destination(j_compress_ptr cinfo)
581
0
{
582
0
    JPEGState *sp = (JPEGState *)cinfo;
583
584
    /* set tables length to number of bytes actually emitted */
585
0
    sp->otherSettings.jpegtables_length -= (uint32_t)sp->dest.free_in_buffer;
586
0
}
Unexecuted instantiation: tif_jpeg.c:tables_term_destination
Unexecuted instantiation: tif_jpeg_12.c:tables_term_destination
587
588
static int TIFFjpeg_tables_dest(JPEGState *sp, TIFF *tif)
589
0
{
590
0
    (void)tif;
591
    /*
592
     * Allocate a working buffer for building tables.
593
     * Initial size is 1000 bytes, which is usually adequate.
594
     */
595
0
    if (sp->otherSettings.jpegtables)
596
0
        _TIFFfreeExt(tif, sp->otherSettings.jpegtables);
597
0
    sp->otherSettings.jpegtables_length = 1000;
598
0
    sp->otherSettings.jpegtables = (void *)_TIFFmallocExt(
599
0
        tif, (tmsize_t)sp->otherSettings.jpegtables_length);
600
0
    if (sp->otherSettings.jpegtables == NULL)
601
0
    {
602
0
        sp->otherSettings.jpegtables_length = 0;
603
0
        TIFFErrorExtR(sp->tif, "TIFFjpeg_tables_dest",
604
0
                      "No space for JPEGTables");
605
0
        return (0);
606
0
    }
607
0
    sp->cinfo.c.dest = &sp->dest;
608
0
    sp->dest.init_destination = tables_init_destination;
609
0
    sp->dest.empty_output_buffer = tables_empty_output_buffer;
610
0
    sp->dest.term_destination = tables_term_destination;
611
0
    return (1);
612
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_tables_dest
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_tables_dest
613
614
/*
615
 * JPEG library source data manager.
616
 * These routines supply compressed data to libjpeg.
617
 */
618
619
static void std_init_source(j_decompress_ptr cinfo)
620
0
{
621
0
    JPEGState *sp = (JPEGState *)cinfo;
622
0
    TIFF *tif = sp->tif;
623
624
0
    sp->src.next_input_byte = (const JOCTET *)tif->tif_rawdata;
625
0
    sp->src.bytes_in_buffer = (size_t)tif->tif_rawcc;
626
0
}
Unexecuted instantiation: tif_jpeg.c:std_init_source
Unexecuted instantiation: tif_jpeg_12.c:std_init_source
627
628
static boolean std_fill_input_buffer(j_decompress_ptr cinfo)
629
0
{
630
0
    JPEGState *sp = (JPEGState *)cinfo;
631
0
    static const JOCTET dummy_EOI[2] = {0xFF, JPEG_EOI};
632
633
#ifdef IPPJ_HUFF
634
    /*
635
     * The Intel IPP performance library does not necessarily read the whole
636
     * input buffer in one pass, so it is possible to get here with data
637
     * yet to read.
638
     *
639
     * We just return without doing anything, until the entire buffer has
640
     * been read.
641
     * http://trac.osgeo.org/gdal/wiki/JpegIPP
642
     */
643
    if (sp->src.bytes_in_buffer > 0)
644
    {
645
        return (TRUE);
646
    }
647
#endif
648
649
    /*
650
     * Normally the whole strip/tile is read and so we don't need to do
651
     * a fill.  In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
652
     * all the data, but the rawdata is refreshed between scanlines and
653
     * we push this into the io machinery in JPEGDecode().
654
     * http://trac.osgeo.org/gdal/ticket/3894
655
     */
656
657
0
    WARNMS(cinfo, JWRN_JPEG_EOF);
658
    /* insert a fake EOI marker */
659
0
    sp->src.next_input_byte = dummy_EOI;
660
0
    sp->src.bytes_in_buffer = 2;
661
0
    return (TRUE);
662
0
}
Unexecuted instantiation: tif_jpeg.c:std_fill_input_buffer
Unexecuted instantiation: tif_jpeg_12.c:std_fill_input_buffer
663
664
static void std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
665
0
{
666
0
    JPEGState *sp = (JPEGState *)cinfo;
667
668
0
    if (num_bytes > 0)
669
0
    {
670
0
        if ((size_t)num_bytes > sp->src.bytes_in_buffer)
671
0
        {
672
            /* oops, buffer overrun */
673
0
            (void)std_fill_input_buffer(cinfo);
674
0
        }
675
0
        else
676
0
        {
677
0
            sp->src.next_input_byte += (size_t)num_bytes;
678
0
            sp->src.bytes_in_buffer -= (size_t)num_bytes;
679
0
        }
680
0
    }
681
0
}
Unexecuted instantiation: tif_jpeg.c:std_skip_input_data
Unexecuted instantiation: tif_jpeg_12.c:std_skip_input_data
682
683
static void std_term_source(j_decompress_ptr cinfo)
684
0
{
685
    /* No work necessary here */
686
0
    (void)cinfo;
687
0
}
Unexecuted instantiation: tif_jpeg.c:std_term_source
Unexecuted instantiation: tif_jpeg_12.c:std_term_source
688
689
static void TIFFjpeg_data_src(JPEGState *sp)
690
0
{
691
0
    sp->cinfo.d.src = &sp->src;
692
0
    sp->src.init_source = std_init_source;
693
0
    sp->src.fill_input_buffer = std_fill_input_buffer;
694
0
    sp->src.skip_input_data = std_skip_input_data;
695
0
    sp->src.resync_to_restart = jpeg_resync_to_restart;
696
0
    sp->src.term_source = std_term_source;
697
0
    sp->src.bytes_in_buffer = 0; /* for safety */
698
0
    sp->src.next_input_byte = NULL;
699
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_data_src
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_data_src
700
701
/*
702
 * Alternate source manager for reading from JPEGTables.
703
 * We can share all the code except for the init routine.
704
 */
705
706
static void tables_init_source(j_decompress_ptr cinfo)
707
0
{
708
0
    JPEGState *sp = (JPEGState *)cinfo;
709
710
0
    sp->src.next_input_byte = (const JOCTET *)sp->otherSettings.jpegtables;
711
0
    sp->src.bytes_in_buffer = (size_t)sp->otherSettings.jpegtables_length;
712
0
}
Unexecuted instantiation: tif_jpeg.c:tables_init_source
Unexecuted instantiation: tif_jpeg_12.c:tables_init_source
713
714
static void TIFFjpeg_tables_src(JPEGState *sp)
715
0
{
716
0
    TIFFjpeg_data_src(sp);
717
0
    sp->src.init_source = tables_init_source;
718
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFjpeg_tables_src
Unexecuted instantiation: tif_jpeg_12.c:TIFFjpeg_tables_src
719
720
/*
721
 * Allocate downsampled-data buffers needed for downsampled I/O.
722
 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
723
 * We use libjpeg's allocator so that buffers will be released automatically
724
 * when done with strip/tile.
725
 * This is also a handy place to compute samplesperclump, bytesperline.
726
 */
727
static int alloc_downsampled_buffers(TIFF *tif, jpeg_component_info *comp_info,
728
                                     int num_components)
729
0
{
730
0
    JPEGState *sp = JState(tif);
731
0
    int ci;
732
0
    jpeg_component_info *compptr;
733
0
    TIFF_JSAMPARRAY buf;
734
0
    int samples_per_clump = 0;
735
736
0
    for (ci = 0, compptr = comp_info; ci < num_components; ci++, compptr++)
737
0
    {
738
0
        samples_per_clump += compptr->h_samp_factor * compptr->v_samp_factor;
739
0
        buf = (TIFF_JSAMPARRAY)TIFFjpeg_alloc_sarray(
740
0
            sp, JPOOL_IMAGE, compptr->width_in_blocks * DCTSIZE,
741
0
            (JDIMENSION)(compptr->v_samp_factor * DCTSIZE));
742
0
        if (buf == NULL)
743
0
            return (0);
744
0
        sp->ds_buffer[ci] = buf;
745
0
    }
746
0
    sp->samplesperclump = samples_per_clump;
747
0
    return (1);
748
0
}
Unexecuted instantiation: tif_jpeg.c:alloc_downsampled_buffers
Unexecuted instantiation: tif_jpeg_12.c:alloc_downsampled_buffers
749
750
/*
751
 * JPEG Decoding.
752
 */
753
754
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
755
756
0
#define JPEG_MARKER_SOF0 0xC0
757
0
#define JPEG_MARKER_SOF1 0xC1
758
0
#define JPEG_MARKER_SOF2 0xC2
759
0
#define JPEG_MARKER_SOF9 0xC9
760
0
#define JPEG_MARKER_SOF10 0xCA
761
0
#define JPEG_MARKER_DHT 0xC4
762
0
#define JPEG_MARKER_SOI 0xD8
763
0
#define JPEG_MARKER_SOS 0xDA
764
0
#define JPEG_MARKER_DQT 0xDB
765
0
#define JPEG_MARKER_DRI 0xDD
766
0
#define JPEG_MARKER_APP0 0xE0
767
0
#define JPEG_MARKER_COM 0xFE
768
struct JPEGFixupTagsSubsamplingData
769
{
770
    TIFF *tif;
771
    void *buffer;
772
    uint32_t buffersize;
773
    uint8_t *buffercurrentbyte;
774
    uint32_t bufferbytesleft;
775
    uint64_t fileoffset;
776
    uint64_t filebytesleft;
777
    uint8_t filepositioned;
778
};
779
static void JPEGFixupTagsSubsampling(TIFF *tif);
780
static int
781
JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData *data);
782
static int
783
JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData *data,
784
                                 uint8_t *result);
785
static int
786
JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData *data,
787
                                 uint16_t *result);
788
static void
789
JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData *data,
790
                             uint16_t skiplength);
791
792
#endif
793
794
static int JPEGFixupTags(TIFF *tif)
795
0
{
796
0
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
797
0
    JPEGState *sp = JState(tif);
798
0
    if ((tif->tif_dir.td_photometric == PHOTOMETRIC_YCBCR) &&
799
0
        (tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG) &&
800
0
        (tif->tif_dir.td_samplesperpixel == 3) &&
801
0
        !sp->otherSettings.ycbcrsampling_fetched)
802
0
        JPEGFixupTagsSubsampling(tif);
803
0
#endif
804
805
0
    return (1);
806
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGFixupTags
Unexecuted instantiation: tif_jpeg_12.c:JPEGFixupTags
807
808
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
809
810
static void JPEGFixupTagsSubsampling(TIFF *tif)
811
0
{
812
    /*
813
     * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
814
     * the TIFF tags, but still use non-default (2,2) values within the jpeg
815
     * data stream itself.  In order for TIFF applications to work properly
816
     * - for instance to get the strip buffer size right - it is imperative
817
     * that the subsampling be available before we start reading the image
818
     * data normally.  This function will attempt to analyze the first strip in
819
     * order to get the sampling values from the jpeg data stream.
820
     *
821
     * Note that JPEGPreDeocode() will produce a fairly loud warning when the
822
     * discovered sampling does not match the default sampling (2,2) or whatever
823
     * was actually in the tiff tags.
824
     *
825
     * See the bug in bugzilla for details:
826
     *
827
     * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
828
     *
829
     * Frank Warmerdam, July 2002
830
     * Joris Van Damme, May 2007
831
     */
832
0
    static const char module[] = "JPEGFixupTagsSubsampling";
833
0
    struct JPEGFixupTagsSubsamplingData m;
834
0
    uint64_t fileoffset = TIFFGetStrileOffset(tif, 0);
835
836
0
    if (fileoffset == 0)
837
0
    {
838
        /* Do not even try to check if the first strip/tile does not
839
           yet exist, as occurs when GDAL has created a new NULL file
840
           for instance. */
841
0
        return;
842
0
    }
843
844
0
    m.tif = tif;
845
0
    m.buffersize = 2048;
846
0
    m.buffer = _TIFFmallocExt(tif, m.buffersize);
847
0
    if (m.buffer == NULL)
848
0
    {
849
0
        TIFFWarningExtR(tif, module,
850
0
                        "Unable to allocate memory for auto-correcting of "
851
0
                        "subsampling values; auto-correcting skipped");
852
0
        return;
853
0
    }
854
0
    m.buffercurrentbyte = NULL;
855
0
    m.bufferbytesleft = 0;
856
0
    m.fileoffset = fileoffset;
857
0
    m.filepositioned = 0;
858
0
    m.filebytesleft = TIFFGetStrileByteCount(tif, 0);
859
0
    if (!JPEGFixupTagsSubsamplingSec(&m))
860
0
        TIFFWarningExtR(
861
0
            tif, module,
862
0
            "Unable to auto-correct subsampling values, likely corrupt JPEG "
863
0
            "compressed data in first strip/tile; auto-correcting skipped");
864
0
    _TIFFfreeExt(tif, m.buffer);
865
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGFixupTagsSubsampling
Unexecuted instantiation: tif_jpeg_12.c:JPEGFixupTagsSubsampling
866
867
static int
868
JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData *data)
869
0
{
870
0
    static const char module[] = "JPEGFixupTagsSubsamplingSec";
871
0
    uint8_t m;
872
0
    while (1)
873
0
    {
874
0
        while (1)
875
0
        {
876
0
            if (!JPEGFixupTagsSubsamplingReadByte(data, &m))
877
0
                return (0);
878
0
            if (m == 255)
879
0
                break;
880
0
        }
881
0
        while (1)
882
0
        {
883
0
            if (!JPEGFixupTagsSubsamplingReadByte(data, &m))
884
0
                return (0);
885
0
            if (m != 255)
886
0
                break;
887
0
        }
888
0
        switch (m)
889
0
        {
890
0
            case JPEG_MARKER_SOI:
891
                /* this type of marker has no data and should be skipped */
892
0
                break;
893
0
            case JPEG_MARKER_COM:
894
0
            case JPEG_MARKER_APP0:
895
0
            case JPEG_MARKER_APP0 + 1:
896
0
            case JPEG_MARKER_APP0 + 2:
897
0
            case JPEG_MARKER_APP0 + 3:
898
0
            case JPEG_MARKER_APP0 + 4:
899
0
            case JPEG_MARKER_APP0 + 5:
900
0
            case JPEG_MARKER_APP0 + 6:
901
0
            case JPEG_MARKER_APP0 + 7:
902
0
            case JPEG_MARKER_APP0 + 8:
903
0
            case JPEG_MARKER_APP0 + 9:
904
0
            case JPEG_MARKER_APP0 + 10:
905
0
            case JPEG_MARKER_APP0 + 11:
906
0
            case JPEG_MARKER_APP0 + 12:
907
0
            case JPEG_MARKER_APP0 + 13:
908
0
            case JPEG_MARKER_APP0 + 14:
909
0
            case JPEG_MARKER_APP0 + 15:
910
0
            case JPEG_MARKER_DQT:
911
0
            case JPEG_MARKER_SOS:
912
0
            case JPEG_MARKER_DHT:
913
0
            case JPEG_MARKER_DRI:
914
                /* this type of marker has data, but it has no use to us and
915
                 * should be skipped */
916
0
                {
917
0
                    uint16_t n;
918
0
                    if (!JPEGFixupTagsSubsamplingReadWord(data, &n))
919
0
                        return (0);
920
0
                    if (n < 2)
921
0
                        return (0);
922
0
                    n -= 2;
923
0
                    if (n > 0)
924
0
                        JPEGFixupTagsSubsamplingSkip(data, n);
925
0
                }
926
0
                break;
927
0
            case JPEG_MARKER_SOF0:  /* Baseline sequential Huffman */
928
0
            case JPEG_MARKER_SOF1:  /* Extended sequential Huffman */
929
0
            case JPEG_MARKER_SOF2:  /* Progressive Huffman: normally not allowed
930
                                       by  TechNote, but that doesn't hurt
931
                                       supporting it */
932
0
            case JPEG_MARKER_SOF9:  /* Extended sequential arithmetic */
933
0
            case JPEG_MARKER_SOF10: /* Progressive arithmetic: normally not
934
                                       allowed by TechNote, but that doesn't
935
                                       hurt supporting it */
936
                /* this marker contains the subsampling factors we're scanning
937
                 * for */
938
0
                {
939
0
                    uint16_t n;
940
0
                    uint16_t o;
941
0
                    uint8_t p;
942
0
                    uint8_t ph, pv;
943
0
                    if (!JPEGFixupTagsSubsamplingReadWord(data, &n))
944
0
                        return (0);
945
0
                    if (n != 8 + data->tif->tif_dir.td_samplesperpixel * 3)
946
0
                        return (0);
947
0
                    JPEGFixupTagsSubsamplingSkip(data, 7);
948
0
                    if (!JPEGFixupTagsSubsamplingReadByte(data, &p))
949
0
                        return (0);
950
0
                    ph = (p >> 4);
951
0
                    pv = (p & 15);
952
0
                    JPEGFixupTagsSubsamplingSkip(data, 1);
953
0
                    for (o = 1; o < data->tif->tif_dir.td_samplesperpixel; o++)
954
0
                    {
955
0
                        JPEGFixupTagsSubsamplingSkip(data, 1);
956
0
                        if (!JPEGFixupTagsSubsamplingReadByte(data, &p))
957
0
                            return (0);
958
0
                        if (p != 0x11)
959
0
                        {
960
0
                            TIFFWarningExtR(data->tif, module,
961
0
                                            "Subsampling values inside JPEG "
962
0
                                            "compressed data "
963
0
                                            "have no TIFF equivalent, "
964
0
                                            "auto-correction of TIFF "
965
0
                                            "subsampling values failed");
966
0
                            return (1);
967
0
                        }
968
0
                        JPEGFixupTagsSubsamplingSkip(data, 1);
969
0
                    }
970
0
                    if (((ph != 1) && (ph != 2) && (ph != 4)) ||
971
0
                        ((pv != 1) && (pv != 2) && (pv != 4)))
972
0
                    {
973
0
                        TIFFWarningExtR(data->tif, module,
974
0
                                        "Subsampling values inside JPEG "
975
0
                                        "compressed data have no TIFF "
976
0
                                        "equivalent, auto-correction of TIFF "
977
0
                                        "subsampling values failed");
978
0
                        return (1);
979
0
                    }
980
0
                    if ((ph != data->tif->tif_dir.td_ycbcrsubsampling[0]) ||
981
0
                        (pv != data->tif->tif_dir.td_ycbcrsubsampling[1]))
982
0
                    {
983
0
                        TIFFWarningExtR(
984
0
                            data->tif, module,
985
0
                            "Auto-corrected former TIFF subsampling values "
986
0
                            "[%" PRIu16 ",%" PRIu16
987
0
                            "] to match subsampling values inside JPEG "
988
0
                            "compressed data [%" PRIu8 ",%" PRIu8 "]",
989
0
                            data->tif->tif_dir.td_ycbcrsubsampling[0],
990
0
                            data->tif->tif_dir.td_ycbcrsubsampling[1], ph, pv);
991
0
                        data->tif->tif_dir.td_ycbcrsubsampling[0] = ph;
992
0
                        data->tif->tif_dir.td_ycbcrsubsampling[1] = pv;
993
0
                    }
994
0
                }
995
0
                return (1);
996
0
            default:
997
0
                return (0);
998
0
        }
999
0
    }
1000
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGFixupTagsSubsamplingSec
Unexecuted instantiation: tif_jpeg_12.c:JPEGFixupTagsSubsamplingSec
1001
1002
static int
1003
JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData *data,
1004
                                 uint8_t *result)
1005
0
{
1006
0
    if (data->bufferbytesleft == 0)
1007
0
    {
1008
0
        uint32_t m;
1009
0
        if (data->filebytesleft == 0)
1010
0
            return (0);
1011
0
        if (!data->filepositioned)
1012
0
        {
1013
0
            if (TIFFSeekFile(data->tif, data->fileoffset, SEEK_SET) ==
1014
0
                (toff_t)-1)
1015
0
            {
1016
0
                return 0;
1017
0
            }
1018
0
            data->filepositioned = 1;
1019
0
        }
1020
0
        m = data->buffersize;
1021
0
        if ((uint64_t)m > data->filebytesleft)
1022
0
            m = (uint32_t)data->filebytesleft;
1023
0
        assert(m < 0x80000000UL);
1024
0
        if (TIFFReadFile(data->tif, data->buffer, (tmsize_t)m) != (tmsize_t)m)
1025
0
            return (0);
1026
0
        data->buffercurrentbyte = (uint8_t *)data->buffer;
1027
0
        data->bufferbytesleft = m;
1028
0
        data->fileoffset += m;
1029
0
        data->filebytesleft -= m;
1030
0
    }
1031
0
    *result = *data->buffercurrentbyte;
1032
0
    data->buffercurrentbyte++;
1033
0
    data->bufferbytesleft--;
1034
0
    return (1);
1035
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGFixupTagsSubsamplingReadByte
Unexecuted instantiation: tif_jpeg_12.c:JPEGFixupTagsSubsamplingReadByte
1036
1037
static int
1038
JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData *data,
1039
                                 uint16_t *result)
1040
0
{
1041
0
    uint8_t ma;
1042
0
    uint8_t mb;
1043
0
    if (!JPEGFixupTagsSubsamplingReadByte(data, &ma))
1044
0
        return (0);
1045
0
    if (!JPEGFixupTagsSubsamplingReadByte(data, &mb))
1046
0
        return (0);
1047
0
    *result = (ma << 8) | mb;
1048
0
    return (1);
1049
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGFixupTagsSubsamplingReadWord
Unexecuted instantiation: tif_jpeg_12.c:JPEGFixupTagsSubsamplingReadWord
1050
1051
static void
1052
JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData *data,
1053
                             uint16_t skiplength)
1054
0
{
1055
0
    if ((uint32_t)skiplength <= data->bufferbytesleft)
1056
0
    {
1057
0
        data->buffercurrentbyte += skiplength;
1058
0
        data->bufferbytesleft -= skiplength;
1059
0
    }
1060
0
    else
1061
0
    {
1062
0
        uint16_t m;
1063
0
        m = (uint16_t)(skiplength - data->bufferbytesleft);
1064
0
        if (m <= data->filebytesleft)
1065
0
        {
1066
0
            data->bufferbytesleft = 0;
1067
0
            data->fileoffset += m;
1068
0
            data->filebytesleft -= m;
1069
0
            data->filepositioned = 0;
1070
0
        }
1071
0
        else
1072
0
        {
1073
0
            data->bufferbytesleft = 0;
1074
0
            data->filebytesleft = 0;
1075
0
        }
1076
0
    }
1077
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGFixupTagsSubsamplingSkip
Unexecuted instantiation: tif_jpeg_12.c:JPEGFixupTagsSubsamplingSkip
1078
1079
#endif
1080
1081
static int JPEGSetupDecode(TIFF *tif)
1082
0
{
1083
0
    JPEGState *sp = JState(tif);
1084
0
    TIFFDirectory *td = &tif->tif_dir;
1085
1086
#if defined(JPEG_DUAL_MODE_8_12) && !defined(FROM_TIF_JPEG_12)
1087
0
    if (tif->tif_dir.td_bitspersample == 12)
1088
0
    {
1089
        /* We pass a pointer to a copy of otherSettings, since */
1090
        /* TIFFReInitJPEG_12() will clear sp */
1091
0
        JPEGOtherSettings savedOtherSettings = sp->otherSettings;
1092
0
        return TIFFReInitJPEG_12(tif, &savedOtherSettings, COMPRESSION_JPEG, 0);
1093
0
    }
1094
0
#endif
1095
1096
0
    JPEGInitializeLibJPEG(tif, TRUE);
1097
1098
0
    assert(sp != NULL);
1099
0
    assert(sp->cinfo.comm.is_decompressor);
1100
1101
    /* Read JPEGTables if it is present */
1102
0
    if (TIFFFieldSet(tif, FIELD_JPEGTABLES))
1103
0
    {
1104
0
        TIFFjpeg_tables_src(sp);
1105
0
        if (TIFFjpeg_read_header(sp, FALSE) != JPEG_HEADER_TABLES_ONLY)
1106
0
        {
1107
0
            TIFFErrorExtR(tif, "JPEGSetupDecode", "Bogus JPEGTables field");
1108
0
            return (0);
1109
0
        }
1110
0
    }
1111
1112
    /* Grab parameters that are same for all strips/tiles */
1113
0
    sp->photometric = td->td_photometric;
1114
0
    switch (sp->photometric)
1115
0
    {
1116
0
        case PHOTOMETRIC_YCBCR:
1117
0
            sp->h_sampling = td->td_ycbcrsubsampling[0];
1118
0
            sp->v_sampling = td->td_ycbcrsubsampling[1];
1119
0
            break;
1120
0
        default:
1121
            /* TIFF 6.0 forbids subsampling of all other color spaces */
1122
0
            sp->h_sampling = 1;
1123
0
            sp->v_sampling = 1;
1124
0
            break;
1125
0
    }
1126
1127
    /* Set up for reading normal data */
1128
0
    TIFFjpeg_data_src(sp);
1129
0
    tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
1130
0
    return (1);
1131
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGSetupDecode
Unexecuted instantiation: tif_jpeg_12.c:JPEGSetupDecode
1132
1133
/* Returns 1 if the full strip should be read, even when doing scanline per */
1134
/* scanline decoding. This happens when the JPEG stream uses multiple scans. */
1135
/* Currently only called in CHUNKY_STRIP_READ_SUPPORT mode through */
1136
/* scanline interface. */
1137
/* Only reads tif->tif_dir.td_bitspersample, tif->tif_rawdata and */
1138
/* tif->tif_rawcc members. */
1139
/* Can be called independently of the usual setup/predecode/decode states */
1140
int TIFFJPEGIsFullStripRequired(TIFF *tif)
1141
0
{
1142
0
    int ret;
1143
0
    JPEGState state;
1144
1145
#if defined(JPEG_DUAL_MODE_8_12) && !defined(FROM_TIF_JPEG_12)
1146
0
    if (tif->tif_dir.td_bitspersample == 12)
1147
0
        return TIFFJPEGIsFullStripRequired_12(tif);
1148
0
#endif
1149
1150
0
    memset(&state, 0, sizeof(JPEGState));
1151
0
    state.tif = tif;
1152
1153
0
    TIFFjpeg_create_decompress(&state);
1154
1155
0
    TIFFjpeg_data_src(&state);
1156
1157
0
    if (TIFFjpeg_read_header(&state, TRUE) != JPEG_HEADER_OK)
1158
0
    {
1159
0
        TIFFjpeg_destroy(&state);
1160
0
        return (0);
1161
0
    }
1162
0
    ret = TIFFjpeg_has_multiple_scans(&state);
1163
1164
0
    TIFFjpeg_destroy(&state);
1165
1166
0
    return ret;
1167
0
}
Unexecuted instantiation: gdal_TIFFJPEGIsFullStripRequired
Unexecuted instantiation: gdal_TIFFJPEGIsFullStripRequired_12
1168
1169
/*
1170
 * Set up for decoding a strip or tile.
1171
 */
1172
/*ARGSUSED*/ static int JPEGPreDecode(TIFF *tif, uint16_t s)
1173
0
{
1174
0
    JPEGState *sp = JState(tif);
1175
0
    TIFFDirectory *td = &tif->tif_dir;
1176
0
    static const char module[] = "JPEGPreDecode";
1177
0
    uint32_t segment_width, segment_height;
1178
0
    int downsampled_output;
1179
0
    int ci;
1180
1181
0
    assert(sp != NULL);
1182
1183
0
    if (sp->cinfo.comm.is_decompressor == 0)
1184
0
    {
1185
0
        tif->tif_setupdecode(tif);
1186
0
    }
1187
1188
0
    assert(sp->cinfo.comm.is_decompressor);
1189
    /*
1190
     * Reset decoder state from any previous strip/tile,
1191
     * in case application didn't read the whole strip.
1192
     */
1193
0
    if (!TIFFjpeg_abort(sp))
1194
0
        return (0);
1195
    /*
1196
     * Read the header for this strip/tile.
1197
     */
1198
1199
0
    if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
1200
0
        return (0);
1201
1202
0
    tif->tif_rawcp = (uint8_t *)sp->src.next_input_byte;
1203
0
    tif->tif_rawcc = sp->src.bytes_in_buffer;
1204
1205
    /*
1206
     * Check image parameters and set decompression parameters.
1207
     */
1208
0
    if (isTiled(tif))
1209
0
    {
1210
0
        segment_width = td->td_tilewidth;
1211
0
        segment_height = td->td_tilelength;
1212
0
        sp->bytesperline = TIFFTileRowSize(tif);
1213
0
    }
1214
0
    else
1215
0
    {
1216
0
        segment_width = td->td_imagewidth;
1217
0
        segment_height = td->td_imagelength - tif->tif_row;
1218
0
        if (segment_height > td->td_rowsperstrip)
1219
0
            segment_height = td->td_rowsperstrip;
1220
0
        sp->bytesperline = TIFFScanlineSize(tif);
1221
0
    }
1222
0
    if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0)
1223
0
    {
1224
        /*
1225
         * For PC 2, scale down the expected strip/tile size
1226
         * to match a downsampled component
1227
         */
1228
0
        if (sp->h_sampling == 0 || sp->v_sampling == 0)
1229
0
        {
1230
0
            TIFFErrorExtR(tif, module,
1231
0
                          "JPEG horizontal or vertical sampling is zero");
1232
0
            return (0);
1233
0
        }
1234
0
        segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
1235
0
        segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1236
0
    }
1237
0
    if (sp->cinfo.d.image_width < segment_width ||
1238
0
        sp->cinfo.d.image_height < segment_height)
1239
0
    {
1240
0
        TIFFWarningExtR(tif, module,
1241
0
                        "Improper JPEG strip/tile size, "
1242
0
                        "expected %" PRIu32 "x%" PRIu32 ", got %ux%u",
1243
0
                        segment_width, segment_height, sp->cinfo.d.image_width,
1244
0
                        sp->cinfo.d.image_height);
1245
0
    }
1246
0
    if (sp->cinfo.d.image_width == segment_width &&
1247
0
        sp->cinfo.d.image_height > segment_height &&
1248
0
        tif->tif_row + segment_height == td->td_imagelength && !isTiled(tif))
1249
0
    {
1250
        /* Some files have a last strip, that should be truncated, */
1251
        /* but their JPEG codestream has still the maximum strip */
1252
        /* height. Warn about this as this is non compliant, but */
1253
        /* we can safely recover from that. */
1254
0
        TIFFWarningExtR(tif, module,
1255
0
                        "JPEG strip size exceeds expected dimensions,"
1256
0
                        " expected %" PRIu32 "x%" PRIu32 ", got %ux%u",
1257
0
                        segment_width, segment_height, sp->cinfo.d.image_width,
1258
0
                        sp->cinfo.d.image_height);
1259
0
    }
1260
0
    else if (sp->cinfo.d.image_width > segment_width ||
1261
0
             sp->cinfo.d.image_height > segment_height)
1262
0
    {
1263
        /*
1264
         * This case could be dangerous, if the strip or tile size has
1265
         * been reported as less than the amount of data jpeg will
1266
         * return, some potential security issues arise. Catch this
1267
         * case and error out.
1268
         */
1269
0
        TIFFErrorExtR(tif, module,
1270
0
                      "JPEG strip/tile size exceeds expected dimensions,"
1271
0
                      " expected %" PRIu32 "x%" PRIu32 ", got %ux%u",
1272
0
                      segment_width, segment_height, sp->cinfo.d.image_width,
1273
0
                      sp->cinfo.d.image_height);
1274
0
        return (0);
1275
0
    }
1276
0
    if (sp->cinfo.d.num_components !=
1277
0
        (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel
1278
0
                                                    : 1))
1279
0
    {
1280
0
        TIFFErrorExtR(tif, module, "Improper JPEG component count");
1281
0
        return (0);
1282
0
    }
1283
#ifdef JPEG_LIB_MK1
1284
    if (12 != td->td_bitspersample && 8 != td->td_bitspersample)
1285
    {
1286
        TIFFErrorExtR(tif, module, "Improper JPEG data precision");
1287
        return (0);
1288
    }
1289
    sp->cinfo.d.data_precision = td->td_bitspersample;
1290
    sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
1291
#else
1292
0
    if (td->td_bitspersample != BITS_IN_JSAMPLE ||
1293
0
        sp->cinfo.d.data_precision != td->td_bitspersample)
1294
0
    {
1295
0
        TIFFErrorExtR(tif, module, "Improper JPEG data precision");
1296
0
        return (0);
1297
0
    }
1298
0
#endif
1299
1300
0
    if (sp->cinfo.d.progressive_mode &&
1301
0
        !sp->otherSettings.has_warned_about_progressive_mode)
1302
0
    {
1303
0
        TIFFWarningExtR(tif, module,
1304
0
                        "The JPEG strip/tile is encoded with progressive mode, "
1305
0
                        "which is normally not legal for JPEG-in-TIFF.\n"
1306
0
                        "libtiff should be able to decode it, but it might "
1307
0
                        "cause compatibility issues with other readers");
1308
0
        sp->otherSettings.has_warned_about_progressive_mode = TRUE;
1309
0
    }
1310
1311
    /* In some cases, libjpeg needs to allocate a lot of memory */
1312
    /* http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf
1313
     */
1314
0
    if (TIFFjpeg_has_multiple_scans(sp))
1315
0
    {
1316
        /* In this case libjpeg will need to allocate memory or backing */
1317
        /* store for all coefficients */
1318
        /* See call to jinit_d_coef_controller() from master_selection() */
1319
        /* in libjpeg */
1320
1321
        /* 1 MB for regular libjpeg usage */
1322
0
        toff_t nRequiredMemory = 1024 * 1024;
1323
1324
0
        for (ci = 0; ci < sp->cinfo.d.num_components; ci++)
1325
0
        {
1326
0
            const jpeg_component_info *compptr = &(sp->cinfo.d.comp_info[ci]);
1327
0
            if (compptr->h_samp_factor > 0 && compptr->v_samp_factor > 0)
1328
0
            {
1329
0
                nRequiredMemory +=
1330
0
                    (toff_t)(((compptr->width_in_blocks +
1331
0
                               compptr->h_samp_factor - 1) /
1332
0
                              compptr->h_samp_factor)) *
1333
0
                    ((compptr->height_in_blocks + compptr->v_samp_factor - 1) /
1334
0
                     compptr->v_samp_factor) *
1335
0
                    sizeof(JBLOCK);
1336
0
            }
1337
0
        }
1338
1339
0
        if (sp->cinfo.d.mem->max_memory_to_use > 0 &&
1340
0
            nRequiredMemory > (toff_t)(sp->cinfo.d.mem->max_memory_to_use) &&
1341
0
            getenv("LIBTIFF_ALLOW_LARGE_LIBJPEG_MEM_ALLOC") == NULL)
1342
0
        {
1343
0
            TIFFErrorExtR(
1344
0
                tif, module,
1345
0
                "Reading this image would require libjpeg to allocate "
1346
0
                "at least %" PRIu64 " bytes. "
1347
0
                "This is disabled since above the %ld threshold. "
1348
0
                "You may override this restriction by defining the "
1349
0
                "LIBTIFF_ALLOW_LARGE_LIBJPEG_MEM_ALLOC environment variable, "
1350
0
                "or setting the JPEGMEM environment variable to a value "
1351
0
                "greater "
1352
0
                "or equal to '%" PRIu64 "M'",
1353
0
                nRequiredMemory, sp->cinfo.d.mem->max_memory_to_use,
1354
0
                (nRequiredMemory + 1000000u - 1u) / 1000000u);
1355
0
            return 0;
1356
0
        }
1357
0
    }
1358
1359
0
    if (td->td_planarconfig == PLANARCONFIG_CONTIG)
1360
0
    {
1361
        /* Component 0 should have expected sampling factors */
1362
0
        if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
1363
0
            sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling)
1364
0
        {
1365
0
            TIFFErrorExtR(tif, module,
1366
0
                          "Improper JPEG sampling factors %d,%d\n"
1367
0
                          "Apparently should be %" PRIu16 ",%" PRIu16 ".",
1368
0
                          sp->cinfo.d.comp_info[0].h_samp_factor,
1369
0
                          sp->cinfo.d.comp_info[0].v_samp_factor,
1370
0
                          sp->h_sampling, sp->v_sampling);
1371
0
            return (0);
1372
0
        }
1373
        /* Rest should have sampling factors 1,1 */
1374
0
        for (ci = 1; ci < sp->cinfo.d.num_components; ci++)
1375
0
        {
1376
0
            if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
1377
0
                sp->cinfo.d.comp_info[ci].v_samp_factor != 1)
1378
0
            {
1379
0
                TIFFErrorExtR(tif, module, "Improper JPEG sampling factors");
1380
0
                return (0);
1381
0
            }
1382
0
        }
1383
0
    }
1384
0
    else
1385
0
    {
1386
        /* PC 2's single component should have sampling factors 1,1 */
1387
0
        if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
1388
0
            sp->cinfo.d.comp_info[0].v_samp_factor != 1)
1389
0
        {
1390
0
            TIFFErrorExtR(tif, module, "Improper JPEG sampling factors");
1391
0
            return (0);
1392
0
        }
1393
0
    }
1394
0
    downsampled_output = FALSE;
1395
0
    if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1396
0
        sp->photometric == PHOTOMETRIC_YCBCR &&
1397
0
        sp->otherSettings.jpegcolormode == JPEGCOLORMODE_RGB)
1398
0
    {
1399
        /* Convert YCbCr to RGB */
1400
0
        sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
1401
0
        sp->cinfo.d.out_color_space = JCS_RGB;
1402
0
    }
1403
0
    else
1404
0
    {
1405
        /* Suppress colorspace handling */
1406
0
        sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
1407
0
        sp->cinfo.d.out_color_space = JCS_UNKNOWN;
1408
0
        if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1409
0
            (sp->h_sampling != 1 || sp->v_sampling != 1))
1410
0
            downsampled_output = TRUE;
1411
        /* XXX what about up-sampling? */
1412
0
    }
1413
0
    if (downsampled_output)
1414
0
    {
1415
        /* Need to use raw-data interface to libjpeg */
1416
0
        sp->cinfo.d.raw_data_out = TRUE;
1417
#if JPEG_LIB_VERSION >= 70
1418
0
        sp->cinfo.d.do_fancy_upsampling = FALSE;
1419
#endif /* JPEG_LIB_VERSION >= 70 */
1420
0
        tif->tif_decoderow = DecodeRowError;
1421
0
        tif->tif_decodestrip = JPEGDecodeRaw;
1422
0
        tif->tif_decodetile = JPEGDecodeRaw;
1423
0
    }
1424
0
    else
1425
0
    {
1426
        /* Use normal interface to libjpeg */
1427
0
        sp->cinfo.d.raw_data_out = FALSE;
1428
0
        tif->tif_decoderow = JPEGDecode;
1429
0
        tif->tif_decodestrip = JPEGDecode;
1430
0
        tif->tif_decodetile = JPEGDecode;
1431
0
    }
1432
    /* Start JPEG decompressor */
1433
0
    if (!TIFFjpeg_start_decompress(sp))
1434
0
        return (0);
1435
    /* Allocate downsampled-data buffers if needed */
1436
0
    if (downsampled_output)
1437
0
    {
1438
0
        if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
1439
0
                                       sp->cinfo.d.num_components))
1440
0
            return (0);
1441
0
        sp->scancount = DCTSIZE; /* mark buffer empty */
1442
0
    }
1443
0
    return (1);
1444
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGPreDecode
Unexecuted instantiation: tif_jpeg_12.c:JPEGPreDecode
1445
1446
/*
1447
 * Decode a chunk of pixels.
1448
 * "Standard" case: returned data is not downsampled.
1449
 */
1450
#if !JPEG_LIB_MK1_OR_12BIT
1451
static int JPEGDecode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s)
1452
0
{
1453
0
    JPEGState *sp = JState(tif);
1454
0
    tmsize_t nrows;
1455
0
    (void)s;
1456
1457
    /*
1458
    ** Update available information, buffer may have been refilled
1459
    ** between decode requests
1460
    */
1461
0
    sp->src.next_input_byte = (const JOCTET *)tif->tif_rawcp;
1462
0
    sp->src.bytes_in_buffer = (size_t)tif->tif_rawcc;
1463
1464
0
    if (sp->bytesperline == 0)
1465
0
    {
1466
0
        memset(buf, 0, (size_t)cc);
1467
0
        return 0;
1468
0
    }
1469
1470
0
    nrows = cc / sp->bytesperline;
1471
0
    if (cc % sp->bytesperline)
1472
0
        TIFFWarningExtR(tif, tif->tif_name, "fractional scanline not read");
1473
1474
0
    if (nrows > (tmsize_t)sp->cinfo.d.image_height)
1475
0
        nrows = sp->cinfo.d.image_height;
1476
1477
    /* data is expected to be read in multiples of a scanline */
1478
0
    if (nrows)
1479
0
    {
1480
0
        do
1481
0
        {
1482
            /*
1483
             * In the libjpeg6b-9a 8bit case.  We read directly into
1484
             * the TIFF buffer.
1485
             */
1486
0
            JSAMPROW bufptr = (JSAMPROW)buf;
1487
1488
0
            if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
1489
0
            {
1490
0
                memset(buf, 0, (size_t)cc);
1491
0
                return (0);
1492
0
            }
1493
1494
0
            ++tif->tif_row;
1495
0
            buf += sp->bytesperline;
1496
0
            cc -= sp->bytesperline;
1497
0
        } while (--nrows > 0);
1498
0
    }
1499
1500
    /* Update information on consumed data */
1501
0
    tif->tif_rawcp = (uint8_t *)sp->src.next_input_byte;
1502
0
    tif->tif_rawcc = sp->src.bytes_in_buffer;
1503
1504
    /* Close down the decompressor if we've finished the strip or tile. */
1505
0
    return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height ||
1506
0
           TIFFjpeg_finish_decompress(sp);
1507
0
}
1508
#endif /* !JPEG_LIB_MK1_OR_12BIT */
1509
1510
#if JPEG_LIB_MK1_OR_12BIT
1511
/*ARGSUSED*/ static int JPEGDecode(TIFF *tif, uint8_t *buf, tmsize_t cc,
1512
                                   uint16_t s)
1513
0
{
1514
0
    JPEGState *sp = JState(tif);
1515
0
    tmsize_t nrows;
1516
0
    (void)s;
1517
1518
    /*
1519
    ** Update available information, buffer may have been refilled
1520
    ** between decode requests
1521
    */
1522
0
    sp->src.next_input_byte = (const JOCTET *)tif->tif_rawcp;
1523
0
    sp->src.bytes_in_buffer = (size_t)tif->tif_rawcc;
1524
1525
0
    if (sp->bytesperline == 0)
1526
0
    {
1527
0
        memset(buf, 0, (size_t)cc);
1528
0
        return 0;
1529
0
    }
1530
1531
0
    nrows = cc / sp->bytesperline;
1532
0
    if (cc % sp->bytesperline)
1533
0
        TIFFWarningExtR(tif, tif->tif_name, "fractional scanline not read");
1534
1535
0
    if (nrows > (tmsize_t)sp->cinfo.d.image_height)
1536
0
        nrows = sp->cinfo.d.image_height;
1537
1538
    /* data is expected to be read in multiples of a scanline */
1539
0
    if (nrows)
1540
0
    {
1541
0
        TIFF_JSAMPROW line_work_buf = NULL;
1542
1543
        /*
1544
         * For 6B, only use temporary buffer for 12 bit imagery.
1545
         * For Mk1 always use it.
1546
         */
1547
0
        if (sp->cinfo.d.data_precision == 12)
1548
0
        {
1549
0
            line_work_buf = (TIFF_JSAMPROW)_TIFFmallocExt(
1550
0
                tif, sizeof(short) * sp->cinfo.d.output_width *
1551
0
                         sp->cinfo.d.num_components);
1552
0
        }
1553
1554
0
        do
1555
0
        {
1556
0
            if (line_work_buf != NULL)
1557
0
            {
1558
                /*
1559
                 * In the MK1 case, we always read into a 16bit
1560
                 * buffer, and then pack down to 12bit or 8bit.
1561
                 * In 6B case we only read into 16 bit buffer
1562
                 * for 12bit data, which we need to repack.
1563
                 */
1564
0
                if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
1565
0
                {
1566
0
                    memset(buf, 0, (size_t)cc);
1567
0
                    _TIFFfreeExt(tif, line_work_buf);
1568
0
                    return (0);
1569
0
                }
1570
1571
0
                if (sp->cinfo.d.data_precision == 12)
1572
0
                {
1573
0
                    int value_pairs = (sp->cinfo.d.output_width *
1574
0
                                       sp->cinfo.d.num_components) /
1575
0
                                      2;
1576
0
                    int iPair;
1577
1578
0
                    for (iPair = 0; iPair < value_pairs; iPair++)
1579
0
                    {
1580
0
                        unsigned char *out_ptr =
1581
0
                            ((unsigned char *)buf) + iPair * 3;
1582
0
                        TIFF_JSAMPLE *in_ptr = line_work_buf + iPair * 2;
1583
1584
0
                        out_ptr[0] = (unsigned char)((in_ptr[0] & 0xff0) >> 4);
1585
0
                        out_ptr[1] =
1586
0
                            (unsigned char)(((in_ptr[0] & 0xf) << 4) |
1587
0
                                            ((in_ptr[1] & 0xf00) >> 8));
1588
0
                        out_ptr[2] = (unsigned char)(((in_ptr[1] & 0xff) >> 0));
1589
0
                    }
1590
0
                }
1591
0
                else if (sp->cinfo.d.data_precision == 8)
1592
0
                {
1593
0
                    int value_count =
1594
0
                        (sp->cinfo.d.output_width * sp->cinfo.d.num_components);
1595
0
                    int iValue;
1596
1597
0
                    for (iValue = 0; iValue < value_count; iValue++)
1598
0
                    {
1599
0
                        ((unsigned char *)buf)[iValue] =
1600
0
                            line_work_buf[iValue] & 0xff;
1601
0
                    }
1602
0
                }
1603
0
            }
1604
1605
0
            ++tif->tif_row;
1606
0
            buf += sp->bytesperline;
1607
0
            cc -= sp->bytesperline;
1608
0
        } while (--nrows > 0);
1609
1610
0
        if (line_work_buf != NULL)
1611
0
            _TIFFfreeExt(tif, line_work_buf);
1612
0
    }
1613
1614
    /* Update information on consumed data */
1615
0
    tif->tif_rawcp = (uint8_t *)sp->src.next_input_byte;
1616
0
    tif->tif_rawcc = sp->src.bytes_in_buffer;
1617
1618
    /* Close down the decompressor if we've finished the strip or tile. */
1619
0
    return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height ||
1620
0
           TIFFjpeg_finish_decompress(sp);
1621
0
}
1622
#endif /* JPEG_LIB_MK1_OR_12BIT */
1623
1624
/*ARGSUSED*/ static int DecodeRowError(TIFF *tif, uint8_t *buf, tmsize_t cc,
1625
                                       uint16_t s)
1626
1627
0
{
1628
0
    (void)buf;
1629
0
    (void)cc;
1630
0
    (void)s;
1631
1632
0
    TIFFErrorExtR(
1633
0
        tif, "TIFFReadScanline",
1634
0
        "scanline oriented access is not supported for downsampled JPEG "
1635
0
        "compressed images, consider enabling TIFFTAG_JPEGCOLORMODE as "
1636
0
        "JPEGCOLORMODE_RGB.");
1637
0
    return 0;
1638
0
}
Unexecuted instantiation: tif_jpeg.c:DecodeRowError
Unexecuted instantiation: tif_jpeg_12.c:DecodeRowError
1639
1640
/*
1641
 * Decode a chunk of pixels.
1642
 * Returned data is downsampled per sampling factors.
1643
 */
1644
/*ARGSUSED*/ static int JPEGDecodeRaw(TIFF *tif, uint8_t *buf, tmsize_t cc,
1645
                                      uint16_t s)
1646
0
{
1647
0
    JPEGState *sp = JState(tif);
1648
0
    tmsize_t nrows;
1649
0
    TIFFDirectory *td = &tif->tif_dir;
1650
0
    (void)s;
1651
1652
0
    nrows = sp->cinfo.d.image_height;
1653
    /* For last strip, limit number of rows to its truncated height */
1654
    /* even if the codestream height is larger (which is not compliant, */
1655
    /* but that we tolerate) */
1656
0
    if ((uint32_t)nrows > td->td_imagelength - tif->tif_row && !isTiled(tif))
1657
0
        nrows = td->td_imagelength - tif->tif_row;
1658
1659
#if defined(JPEG_LIB_MK1_OR_12BIT)
1660
    unsigned short *tmpbuf = NULL;
1661
#endif
1662
1663
    /* data is expected to be read in multiples of a scanline */
1664
0
    if (nrows != 0)
1665
0
    {
1666
1667
        /* Cb,Cr both have sampling factors 1, so this is correct */
1668
0
        JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
1669
0
        int samples_per_clump = sp->samplesperclump;
1670
1671
#if defined(JPEG_LIB_MK1_OR_12BIT)
1672
0
        tmpbuf = (unsigned short *)_TIFFmallocExt(
1673
            tif, sizeof(unsigned short) * sp->cinfo.d.output_width *
1674
                     sp->cinfo.d.num_components);
1675
0
        if (tmpbuf == NULL)
1676
0
        {
1677
0
            TIFFErrorExtR(tif, "JPEGDecodeRaw", "Out of memory");
1678
0
            return 0;
1679
0
        }
1680
0
#endif
1681
1682
0
        do
1683
0
        {
1684
0
            jpeg_component_info *compptr;
1685
0
            int ci, clumpoffset;
1686
1687
0
            if (cc < sp->bytesperline)
1688
0
            {
1689
0
                TIFFErrorExtR(
1690
0
                    tif, "JPEGDecodeRaw",
1691
0
                    "application buffer not large enough for all data.");
1692
0
                goto error;
1693
0
            }
1694
1695
            /* Reload downsampled-data buffer if needed */
1696
0
            if (sp->scancount >= DCTSIZE)
1697
0
            {
1698
0
                int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
1699
0
                if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
1700
0
                    goto error;
1701
0
                sp->scancount = 0;
1702
0
            }
1703
            /*
1704
             * Fastest way to unseparate data is to make one pass
1705
             * over the scanline for each row of each component.
1706
             */
1707
0
            clumpoffset = 0; /* first sample in clump */
1708
0
            for (ci = 0, compptr = sp->cinfo.d.comp_info;
1709
0
                 ci < sp->cinfo.d.num_components; ci++, compptr++)
1710
0
            {
1711
0
                int hsamp = compptr->h_samp_factor;
1712
0
                int vsamp = compptr->v_samp_factor;
1713
0
                int ypos;
1714
1715
0
                for (ypos = 0; ypos < vsamp; ypos++)
1716
0
                {
1717
0
                    TIFF_JSAMPLE *inptr =
1718
0
                        sp->ds_buffer[ci][sp->scancount * vsamp + ypos];
1719
0
                    JDIMENSION nclump;
1720
#if defined(JPEG_LIB_MK1_OR_12BIT)
1721
0
                    TIFF_JSAMPLE *outptr = (TIFF_JSAMPLE *)tmpbuf + clumpoffset;
1722
#else
1723
0
                    TIFF_JSAMPLE *outptr = (TIFF_JSAMPLE *)buf + clumpoffset;
1724
0
                    if (cc < (tmsize_t)(clumpoffset +
1725
0
                                        (tmsize_t)samples_per_clump *
1726
0
                                            (clumps_per_line - 1) +
1727
0
                                        hsamp))
1728
0
                    {
1729
0
                        TIFFErrorExtR(
1730
0
                            tif, "JPEGDecodeRaw",
1731
0
                            "application buffer not large enough for all data, "
1732
0
                            "possible subsampling issue");
1733
0
                        goto error;
1734
0
                    }
1735
0
#endif
1736
1737
0
                    if (hsamp == 1)
1738
0
                    {
1739
                        /* fast path for at least Cb and Cr */
1740
0
                        for (nclump = clumps_per_line; nclump-- > 0;)
1741
0
                        {
1742
0
                            outptr[0] = *inptr++;
1743
0
                            outptr += samples_per_clump;
1744
0
                        }
1745
0
                    }
1746
0
                    else
1747
0
                    {
1748
0
                        int xpos;
1749
1750
                        /* general case */
1751
0
                        for (nclump = clumps_per_line; nclump-- > 0;)
1752
0
                        {
1753
0
                            for (xpos = 0; xpos < hsamp; xpos++)
1754
0
                                outptr[xpos] = *inptr++;
1755
0
                            outptr += samples_per_clump;
1756
0
                        }
1757
0
                    }
1758
0
                    clumpoffset += hsamp;
1759
0
                }
1760
0
            }
1761
1762
#if defined(JPEG_LIB_MK1_OR_12BIT)
1763
            {
1764
0
                if (sp->cinfo.d.data_precision == 8)
1765
0
                {
1766
0
                    int i = 0;
1767
0
                    int len =
1768
0
                        sp->cinfo.d.output_width * sp->cinfo.d.num_components;
1769
0
                    for (i = 0; i < len; i++)
1770
0
                    {
1771
0
                        ((unsigned char *)buf)[i] = tmpbuf[i] & 0xff;
1772
0
                    }
1773
0
                }
1774
0
                else
1775
0
                { /* 12-bit */
1776
0
                    int value_pairs = (sp->cinfo.d.output_width *
1777
0
                                       sp->cinfo.d.num_components) /
1778
0
                                      2;
1779
0
                    int iPair;
1780
0
                    for (iPair = 0; iPair < value_pairs; iPair++)
1781
0
                    {
1782
0
                        unsigned char *out_ptr =
1783
0
                            ((unsigned char *)buf) + iPair * 3;
1784
0
                        TIFF_JSAMPLE *in_ptr =
1785
0
                            (TIFF_JSAMPLE *)(tmpbuf + iPair * 2);
1786
0
                        out_ptr[0] = (unsigned char)((in_ptr[0] & 0xff0) >> 4);
1787
0
                        out_ptr[1] =
1788
0
                            (unsigned char)(((in_ptr[0] & 0xf) << 4) |
1789
0
                                            ((in_ptr[1] & 0xf00) >> 8));
1790
0
                        out_ptr[2] = (unsigned char)(((in_ptr[1] & 0xff) >> 0));
1791
0
                    }
1792
0
                }
1793
            }
1794
#endif
1795
1796
0
            sp->scancount++;
1797
0
            tif->tif_row += sp->v_sampling;
1798
1799
0
            buf += sp->bytesperline;
1800
0
            cc -= sp->bytesperline;
1801
1802
0
            nrows -= sp->v_sampling;
1803
0
        } while (nrows > 0);
1804
1805
#if defined(JPEG_LIB_MK1_OR_12BIT)
1806
0
        _TIFFfreeExt(tif, tmpbuf);
1807
0
#endif
1808
0
    }
1809
1810
    /* Close down the decompressor if done. */
1811
0
    return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height ||
1812
0
           TIFFjpeg_finish_decompress(sp);
1813
1814
0
error:
1815
#if defined(JPEG_LIB_MK1_OR_12BIT)
1816
0
    _TIFFfreeExt(tif, tmpbuf);
1817
#endif
1818
0
    return 0;
1819
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGDecodeRaw
Unexecuted instantiation: tif_jpeg_12.c:JPEGDecodeRaw
1820
1821
/*
1822
 * JPEG Encoding.
1823
 */
1824
1825
static void unsuppress_quant_table(JPEGState *sp, int tblno)
1826
0
{
1827
0
    JQUANT_TBL *qtbl;
1828
1829
0
    if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1830
0
        qtbl->sent_table = FALSE;
1831
0
}
Unexecuted instantiation: tif_jpeg.c:unsuppress_quant_table
Unexecuted instantiation: tif_jpeg_12.c:unsuppress_quant_table
1832
1833
static void suppress_quant_table(JPEGState *sp, int tblno)
1834
0
{
1835
0
    JQUANT_TBL *qtbl;
1836
1837
0
    if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1838
0
        qtbl->sent_table = TRUE;
1839
0
}
Unexecuted instantiation: tif_jpeg.c:suppress_quant_table
Unexecuted instantiation: tif_jpeg_12.c:suppress_quant_table
1840
1841
static void unsuppress_huff_table(JPEGState *sp, int tblno)
1842
0
{
1843
0
    JHUFF_TBL *htbl;
1844
1845
0
    if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1846
0
        htbl->sent_table = FALSE;
1847
0
    if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1848
0
        htbl->sent_table = FALSE;
1849
0
}
Unexecuted instantiation: tif_jpeg.c:unsuppress_huff_table
Unexecuted instantiation: tif_jpeg_12.c:unsuppress_huff_table
1850
1851
static void suppress_huff_table(JPEGState *sp, int tblno)
1852
0
{
1853
0
    JHUFF_TBL *htbl;
1854
1855
0
    if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1856
0
        htbl->sent_table = TRUE;
1857
0
    if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1858
0
        htbl->sent_table = TRUE;
1859
0
}
Unexecuted instantiation: tif_jpeg.c:suppress_huff_table
Unexecuted instantiation: tif_jpeg_12.c:suppress_huff_table
1860
1861
static int prepare_JPEGTables(TIFF *tif)
1862
0
{
1863
0
    JPEGState *sp = JState(tif);
1864
1865
    /* Initialize quant tables for current quality setting */
1866
0
    if (!TIFFjpeg_set_quality(sp, sp->otherSettings.jpegquality, FALSE))
1867
0
        return (0);
1868
    /* Mark only the tables we want for output */
1869
    /* NB: chrominance tables are currently used only with YCbCr */
1870
0
    if (!TIFFjpeg_suppress_tables(sp, TRUE))
1871
0
        return (0);
1872
0
    if (sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_QUANT)
1873
0
    {
1874
0
        unsuppress_quant_table(sp, 0);
1875
0
        if (sp->photometric == PHOTOMETRIC_YCBCR)
1876
0
            unsuppress_quant_table(sp, 1);
1877
0
    }
1878
0
    if (sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_HUFF)
1879
0
    {
1880
0
        unsuppress_huff_table(sp, 0);
1881
0
        if (sp->photometric == PHOTOMETRIC_YCBCR)
1882
0
            unsuppress_huff_table(sp, 1);
1883
0
    }
1884
    /* Direct libjpeg output into otherSettings.jpegtables */
1885
0
    if (!TIFFjpeg_tables_dest(sp, tif))
1886
0
        return (0);
1887
    /* Emit tables-only datastream */
1888
0
    if (!TIFFjpeg_write_tables(sp))
1889
0
        return (0);
1890
1891
0
    return (1);
1892
0
}
Unexecuted instantiation: tif_jpeg.c:prepare_JPEGTables
Unexecuted instantiation: tif_jpeg_12.c:prepare_JPEGTables
1893
1894
#if defined(JPEG_LIB_VERSION_MAJOR) &&                                         \
1895
    (JPEG_LIB_VERSION_MAJOR > 9 ||                                             \
1896
     (JPEG_LIB_VERSION_MAJOR == 9 && JPEG_LIB_VERSION_MINOR >= 4))
1897
/* This is a modified version of std_huff_tables() from jcparam.c
1898
 * in libjpeg-9d because it no longer initializes default Huffman
1899
 * tables in jpeg_set_defaults(). */
1900
static void TIFF_std_huff_tables(j_compress_ptr cinfo)
1901
{
1902
1903
    if (cinfo->dc_huff_tbl_ptrs[0] == NULL)
1904
    {
1905
        (void)jpeg_std_huff_table((j_common_ptr)cinfo, TRUE, 0);
1906
    }
1907
    if (cinfo->ac_huff_tbl_ptrs[0] == NULL)
1908
    {
1909
        (void)jpeg_std_huff_table((j_common_ptr)cinfo, FALSE, 0);
1910
    }
1911
    if (cinfo->dc_huff_tbl_ptrs[1] == NULL)
1912
    {
1913
        (void)jpeg_std_huff_table((j_common_ptr)cinfo, TRUE, 1);
1914
    }
1915
    if (cinfo->ac_huff_tbl_ptrs[1] == NULL)
1916
    {
1917
        (void)jpeg_std_huff_table((j_common_ptr)cinfo, FALSE, 1);
1918
    }
1919
}
1920
#endif
1921
1922
static int JPEGSetupEncode(TIFF *tif)
1923
0
{
1924
0
    JPEGState *sp = JState(tif);
1925
0
    TIFFDirectory *td = &tif->tif_dir;
1926
0
    static const char module[] = "JPEGSetupEncode";
1927
1928
#if defined(JPEG_DUAL_MODE_8_12) && !defined(FROM_TIF_JPEG_12)
1929
0
    if (tif->tif_dir.td_bitspersample == 12)
1930
0
    {
1931
        /* We pass a pointer to a copy of otherSettings, since */
1932
        /* TIFFReInitJPEG_12() will clear sp */
1933
0
        JPEGOtherSettings savedOtherSettings = sp->otherSettings;
1934
0
        return TIFFReInitJPEG_12(tif, &savedOtherSettings, COMPRESSION_JPEG, 1);
1935
0
    }
1936
0
#endif
1937
1938
0
    JPEGInitializeLibJPEG(tif, FALSE);
1939
1940
0
    assert(sp != NULL);
1941
0
    assert(!sp->cinfo.comm.is_decompressor);
1942
1943
0
    sp->photometric = td->td_photometric;
1944
1945
    /*
1946
     * Initialize all JPEG parameters to default values.
1947
     * Note that jpeg_set_defaults needs legal values for
1948
     * in_color_space and input_components.
1949
     */
1950
0
    if (td->td_planarconfig == PLANARCONFIG_CONTIG)
1951
0
    {
1952
0
        sp->cinfo.c.input_components = td->td_samplesperpixel;
1953
0
        if (sp->photometric == PHOTOMETRIC_YCBCR)
1954
0
        {
1955
0
            if (sp->otherSettings.jpegcolormode == JPEGCOLORMODE_RGB)
1956
0
            {
1957
0
                sp->cinfo.c.in_color_space = JCS_RGB;
1958
0
            }
1959
0
            else
1960
0
            {
1961
0
                sp->cinfo.c.in_color_space = JCS_YCbCr;
1962
0
            }
1963
0
        }
1964
0
        else
1965
0
        {
1966
0
            if ((td->td_photometric == PHOTOMETRIC_MINISWHITE ||
1967
0
                 td->td_photometric == PHOTOMETRIC_MINISBLACK) &&
1968
0
                td->td_samplesperpixel == 1)
1969
0
                sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
1970
0
            else if (td->td_photometric == PHOTOMETRIC_RGB &&
1971
0
                     td->td_samplesperpixel == 3)
1972
0
                sp->cinfo.c.in_color_space = JCS_RGB;
1973
0
            else if (td->td_photometric == PHOTOMETRIC_SEPARATED &&
1974
0
                     td->td_samplesperpixel == 4)
1975
0
                sp->cinfo.c.in_color_space = JCS_CMYK;
1976
0
            else
1977
0
                sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1978
0
        }
1979
0
    }
1980
0
    else
1981
0
    {
1982
0
        sp->cinfo.c.input_components = 1;
1983
0
        sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1984
0
    }
1985
0
    if (!TIFFjpeg_set_defaults(sp))
1986
0
        return (0);
1987
1988
    /* mozjpeg by default enables progressive JPEG, which is illegal in
1989
     * JPEG-in-TIFF */
1990
    /* So explicitly disable it. */
1991
0
    if (sp->cinfo.c.num_scans != 0 &&
1992
0
        (sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_HUFF) != 0)
1993
0
    {
1994
        /* it has been found that mozjpeg could create corrupt strips/tiles */
1995
        /* in non optimize_coding mode. */
1996
0
        TIFFWarningExtR(
1997
0
            tif, module,
1998
0
            "mozjpeg library likely detected. Disable emission of "
1999
0
            "Huffman tables in JpegTables tag, and use optimize_coding "
2000
0
            "to avoid potential issues");
2001
0
        sp->otherSettings.jpegtablesmode &= ~JPEGTABLESMODE_HUFF;
2002
0
    }
2003
0
    sp->cinfo.c.num_scans = 0;
2004
0
    sp->cinfo.c.scan_info = NULL;
2005
2006
    /* Set per-file parameters */
2007
0
    switch (sp->photometric)
2008
0
    {
2009
0
        case PHOTOMETRIC_YCBCR:
2010
0
            sp->h_sampling = td->td_ycbcrsubsampling[0];
2011
0
            sp->v_sampling = td->td_ycbcrsubsampling[1];
2012
0
            if (sp->h_sampling == 0 || sp->v_sampling == 0)
2013
0
            {
2014
0
                TIFFErrorExtR(tif, module,
2015
0
                              "Invalig horizontal/vertical sampling value");
2016
0
                return (0);
2017
0
            }
2018
0
            if (td->td_bitspersample > 16)
2019
0
            {
2020
0
                TIFFErrorExtR(tif, module,
2021
0
                              "BitsPerSample %" PRIu16 " not allowed for JPEG",
2022
0
                              td->td_bitspersample);
2023
0
                return (0);
2024
0
            }
2025
2026
            /*
2027
             * A ReferenceBlackWhite field *must* be present since the
2028
             * default value is inappropriate for YCbCr.  Fill in the
2029
             * proper value if application didn't set it.
2030
             */
2031
0
            {
2032
0
                float *ref;
2033
0
                if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE, &ref))
2034
0
                {
2035
0
                    float refbw[6];
2036
0
                    long top = 1L << td->td_bitspersample;
2037
0
                    refbw[0] = 0;
2038
0
                    refbw[1] = (float)(top - 1L);
2039
0
                    refbw[2] = (float)(top >> 1);
2040
0
                    refbw[3] = refbw[1];
2041
0
                    refbw[4] = refbw[2];
2042
0
                    refbw[5] = refbw[1];
2043
0
                    TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE, refbw);
2044
0
                }
2045
0
            }
2046
0
            break;
2047
0
        case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */
2048
0
        case PHOTOMETRIC_MASK:
2049
0
            TIFFErrorExtR(tif, module,
2050
0
                          "PhotometricInterpretation %" PRIu16
2051
0
                          " not allowed for JPEG",
2052
0
                          sp->photometric);
2053
0
            return (0);
2054
0
        default:
2055
            /* TIFF 6.0 forbids subsampling of all other color spaces */
2056
0
            sp->h_sampling = 1;
2057
0
            sp->v_sampling = 1;
2058
0
            break;
2059
0
    }
2060
2061
        /* Verify miscellaneous parameters */
2062
2063
        /*
2064
         * This would need work if libtiff ever supports different
2065
         * depths for different components, or if libjpeg ever supports
2066
         * run-time selection of depth.  Neither is imminent.
2067
         */
2068
#ifdef JPEG_LIB_MK1
2069
    /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
2070
    if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
2071
#else
2072
0
    if (td->td_bitspersample != BITS_IN_JSAMPLE)
2073
0
#endif
2074
0
    {
2075
0
        TIFFErrorExtR(tif, module,
2076
0
                      "BitsPerSample %" PRIu16 " not allowed for JPEG",
2077
0
                      td->td_bitspersample);
2078
0
        return (0);
2079
0
    }
2080
0
    sp->cinfo.c.data_precision = td->td_bitspersample;
2081
#ifdef JPEG_LIB_MK1
2082
    sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
2083
#endif
2084
0
    if (isTiled(tif))
2085
0
    {
2086
0
        if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0)
2087
0
        {
2088
0
            TIFFErrorExtR(tif, module,
2089
0
                          "JPEG tile height must be multiple of %" PRIu32,
2090
0
                          (uint32_t)(sp->v_sampling * DCTSIZE));
2091
0
            return (0);
2092
0
        }
2093
0
        if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0)
2094
0
        {
2095
0
            TIFFErrorExtR(tif, module,
2096
0
                          "JPEG tile width must be multiple of %" PRIu32,
2097
0
                          (uint32_t)(sp->h_sampling * DCTSIZE));
2098
0
            return (0);
2099
0
        }
2100
0
    }
2101
0
    else
2102
0
    {
2103
0
        if (td->td_rowsperstrip < td->td_imagelength &&
2104
0
            (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0)
2105
0
        {
2106
0
            TIFFErrorExtR(tif, module,
2107
0
                          "RowsPerStrip must be multiple of %" PRIu32
2108
0
                          " for JPEG",
2109
0
                          (uint32_t)(sp->v_sampling * DCTSIZE));
2110
0
            return (0);
2111
0
        }
2112
0
    }
2113
2114
    /* Create a JPEGTables field if appropriate */
2115
0
    if (sp->otherSettings.jpegtablesmode &
2116
0
        (JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF))
2117
0
    {
2118
0
        if (sp->otherSettings.jpegtables == NULL ||
2119
0
            memcmp(sp->otherSettings.jpegtables, "\0\0\0\0\0\0\0\0\0", 8) == 0)
2120
0
        {
2121
#if defined(JPEG_LIB_VERSION_MAJOR) &&                                         \
2122
    (JPEG_LIB_VERSION_MAJOR > 9 ||                                             \
2123
     (JPEG_LIB_VERSION_MAJOR == 9 && JPEG_LIB_VERSION_MINOR >= 4))
2124
            if ((sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_HUFF) != 0 &&
2125
                (sp->cinfo.c.dc_huff_tbl_ptrs[0] == NULL ||
2126
                 sp->cinfo.c.dc_huff_tbl_ptrs[1] == NULL ||
2127
                 sp->cinfo.c.ac_huff_tbl_ptrs[0] == NULL ||
2128
                 sp->cinfo.c.ac_huff_tbl_ptrs[1] == NULL))
2129
            {
2130
                /* libjpeg-9d no longer initializes default Huffman tables in */
2131
                /* jpeg_set_defaults() */
2132
                TIFF_std_huff_tables(&sp->cinfo.c);
2133
            }
2134
#endif
2135
2136
0
            if (!prepare_JPEGTables(tif))
2137
0
                return (0);
2138
            /* Mark the field present */
2139
            /* Can't use TIFFSetField since BEENWRITING is already set! */
2140
0
            tif->tif_flags |= TIFF_DIRTYDIRECT;
2141
0
            TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2142
0
        }
2143
0
    }
2144
0
    else
2145
0
    {
2146
        /* We do not support application-supplied JPEGTables, */
2147
        /* so mark the field not present */
2148
0
        TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
2149
0
    }
2150
2151
    /* Direct libjpeg output to libtiff's output buffer */
2152
0
    TIFFjpeg_data_dest(sp, tif);
2153
2154
0
    return (1);
2155
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGSetupEncode
Unexecuted instantiation: tif_jpeg_12.c:JPEGSetupEncode
2156
2157
/*
2158
 * Set encoding state at the start of a strip or tile.
2159
 */
2160
static int JPEGPreEncode(TIFF *tif, uint16_t s)
2161
0
{
2162
0
    JPEGState *sp = JState(tif);
2163
0
    TIFFDirectory *td = &tif->tif_dir;
2164
0
    static const char module[] = "JPEGPreEncode";
2165
0
    uint32_t segment_width, segment_height;
2166
0
    int downsampled_input;
2167
2168
0
    assert(sp != NULL);
2169
2170
0
    if (sp->cinfo.comm.is_decompressor == 1)
2171
0
    {
2172
0
        tif->tif_setupencode(tif);
2173
0
    }
2174
2175
0
    assert(!sp->cinfo.comm.is_decompressor);
2176
    /*
2177
     * Set encoding parameters for this strip/tile.
2178
     */
2179
0
    if (isTiled(tif))
2180
0
    {
2181
0
        segment_width = td->td_tilewidth;
2182
0
        segment_height = td->td_tilelength;
2183
0
        sp->bytesperline = TIFFTileRowSize(tif);
2184
0
    }
2185
0
    else
2186
0
    {
2187
0
        segment_width = td->td_imagewidth;
2188
0
        segment_height = td->td_imagelength - tif->tif_row;
2189
0
        if (segment_height > td->td_rowsperstrip)
2190
0
            segment_height = td->td_rowsperstrip;
2191
0
        sp->bytesperline = TIFFScanlineSize(tif);
2192
0
    }
2193
0
    if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0)
2194
0
    {
2195
        /* for PC 2, scale down the strip/tile size
2196
         * to match a downsampled component
2197
         */
2198
0
        if (sp->h_sampling == 0 || sp->v_sampling == 0)
2199
0
        {
2200
0
            TIFFErrorExtR(tif, module,
2201
0
                          "JPEG horizontal or vertical sampling is zero");
2202
0
            return (0);
2203
0
        }
2204
0
        segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
2205
0
        segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
2206
0
    }
2207
0
    if (segment_width > (uint32_t)JPEG_MAX_DIMENSION ||
2208
0
        segment_height > (uint32_t)JPEG_MAX_DIMENSION)
2209
0
    {
2210
0
        TIFFErrorExtR(tif, module,
2211
0
                      "Strip/tile too large for JPEG. Maximum dimension is %d",
2212
0
                      (int)JPEG_MAX_DIMENSION);
2213
0
        return (0);
2214
0
    }
2215
0
    sp->cinfo.c.image_width = segment_width;
2216
0
    sp->cinfo.c.image_height = segment_height;
2217
0
    downsampled_input = FALSE;
2218
0
    if (td->td_planarconfig == PLANARCONFIG_CONTIG)
2219
0
    {
2220
0
        sp->cinfo.c.input_components = td->td_samplesperpixel;
2221
0
        if (sp->photometric == PHOTOMETRIC_YCBCR)
2222
0
        {
2223
0
            if (sp->otherSettings.jpegcolormode != JPEGCOLORMODE_RGB)
2224
0
            {
2225
0
                if (sp->h_sampling != 1 || sp->v_sampling != 1)
2226
0
                    downsampled_input = TRUE;
2227
0
            }
2228
0
            if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
2229
0
                return (0);
2230
            /*
2231
             * Set Y sampling factors;
2232
             * we assume jpeg_set_colorspace() set the rest to 1
2233
             */
2234
0
            sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
2235
0
            sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
2236
0
        }
2237
0
        else
2238
0
        {
2239
0
            if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
2240
0
                return (0);
2241
            /* jpeg_set_colorspace set all sampling factors to 1 */
2242
0
        }
2243
0
    }
2244
0
    else
2245
0
    {
2246
0
        if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
2247
0
            return (0);
2248
0
        sp->cinfo.c.comp_info[0].component_id = s;
2249
        /* jpeg_set_colorspace() set sampling factors to 1 */
2250
0
        if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0)
2251
0
        {
2252
0
            sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
2253
0
            sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
2254
0
            sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
2255
0
        }
2256
0
    }
2257
    /* ensure libjpeg won't write any extraneous markers */
2258
0
    sp->cinfo.c.write_JFIF_header = FALSE;
2259
0
    sp->cinfo.c.write_Adobe_marker = FALSE;
2260
    /* set up table handling correctly */
2261
    /* calling TIFFjpeg_set_quality() causes quantization tables to be flagged
2262
     */
2263
    /* as being to be emitted, which we don't want in the JPEGTABLESMODE_QUANT
2264
     */
2265
    /* mode, so we must manually suppress them. However TIFFjpeg_set_quality()
2266
     */
2267
    /* should really be called when dealing with files with directories with */
2268
    /* mixed qualities. see http://trac.osgeo.org/gdal/ticket/3539 */
2269
0
    if (!TIFFjpeg_set_quality(sp, sp->otherSettings.jpegquality, FALSE))
2270
0
        return (0);
2271
0
    if (sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_QUANT)
2272
0
    {
2273
0
        suppress_quant_table(sp, 0);
2274
0
        suppress_quant_table(sp, 1);
2275
0
    }
2276
0
    else
2277
0
    {
2278
0
        unsuppress_quant_table(sp, 0);
2279
0
        unsuppress_quant_table(sp, 1);
2280
0
    }
2281
0
    if (sp->otherSettings.jpegtablesmode & JPEGTABLESMODE_HUFF)
2282
0
    {
2283
        /* Explicit suppression is only needed if we did not go through the */
2284
        /* prepare_JPEGTables() code path, which may be the case if updating */
2285
        /* an existing file */
2286
0
        suppress_huff_table(sp, 0);
2287
0
        suppress_huff_table(sp, 1);
2288
0
        sp->cinfo.c.optimize_coding = FALSE;
2289
0
    }
2290
0
    else
2291
0
        sp->cinfo.c.optimize_coding = TRUE;
2292
0
    if (downsampled_input)
2293
0
    {
2294
        /* Need to use raw-data interface to libjpeg */
2295
0
        sp->cinfo.c.raw_data_in = TRUE;
2296
0
        tif->tif_encoderow = JPEGEncodeRaw;
2297
0
        tif->tif_encodestrip = JPEGEncodeRaw;
2298
0
        tif->tif_encodetile = JPEGEncodeRaw;
2299
0
    }
2300
0
    else
2301
0
    {
2302
        /* Use normal interface to libjpeg */
2303
0
        sp->cinfo.c.raw_data_in = FALSE;
2304
0
        tif->tif_encoderow = JPEGEncode;
2305
0
        tif->tif_encodestrip = JPEGEncode;
2306
0
        tif->tif_encodetile = JPEGEncode;
2307
0
    }
2308
    /* Start JPEG compressor */
2309
0
    if (!TIFFjpeg_start_compress(sp, FALSE))
2310
0
        return (0);
2311
    /* Allocate downsampled-data buffers if needed */
2312
0
    if (downsampled_input)
2313
0
    {
2314
0
        if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
2315
0
                                       sp->cinfo.c.num_components))
2316
0
            return (0);
2317
0
    }
2318
0
    sp->scancount = 0;
2319
0
    sp->encode_raw_error = FALSE;
2320
2321
0
    return (1);
2322
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGPreEncode
Unexecuted instantiation: tif_jpeg_12.c:JPEGPreEncode
2323
2324
/*
2325
 * Encode a chunk of pixels.
2326
 * "Standard" case: incoming data is not downsampled.
2327
 */
2328
static int JPEGEncode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s)
2329
0
{
2330
0
    JPEGState *sp = JState(tif);
2331
0
    tmsize_t nrows;
2332
0
    TIFF_JSAMPROW bufptr[1];
2333
0
    short *line16 = NULL;
2334
0
    int line16_count = 0;
2335
2336
0
    (void)s;
2337
0
    assert(sp != NULL);
2338
    /* data is expected to be supplied in multiples of a scanline */
2339
0
    nrows = cc / sp->bytesperline;
2340
0
    if (cc % sp->bytesperline)
2341
0
        TIFFWarningExtR(tif, tif->tif_name, "fractional scanline discarded");
2342
2343
    /* The last strip will be limited to image size */
2344
0
    if (!isTiled(tif) && tif->tif_row + nrows > tif->tif_dir.td_imagelength)
2345
0
        nrows = tif->tif_dir.td_imagelength - tif->tif_row;
2346
2347
0
    if (sp->cinfo.c.data_precision == 12)
2348
0
    {
2349
0
        line16_count = (int)((sp->bytesperline * 2) / 3);
2350
0
        line16 = (short *)_TIFFmallocExt(tif, sizeof(short) * line16_count);
2351
0
        if (!line16)
2352
0
        {
2353
0
            TIFFErrorExtR(tif, "JPEGEncode", "Failed to allocate memory");
2354
2355
0
            return 0;
2356
0
        }
2357
0
    }
2358
2359
0
    while (nrows-- > 0)
2360
0
    {
2361
2362
0
        if (sp->cinfo.c.data_precision == 12)
2363
0
        {
2364
2365
0
            int value_pairs = line16_count / 2;
2366
0
            int iPair;
2367
2368
0
            bufptr[0] = (TIFF_JSAMPROW)line16;
2369
2370
0
            for (iPair = 0; iPair < value_pairs; iPair++)
2371
0
            {
2372
0
                unsigned char *in_ptr = ((unsigned char *)buf) + iPair * 3;
2373
0
                TIFF_JSAMPLE *out_ptr = (TIFF_JSAMPLE *)(line16 + iPair * 2);
2374
2375
0
                out_ptr[0] = (in_ptr[0] << 4) | ((in_ptr[1] & 0xf0) >> 4);
2376
0
                out_ptr[1] = ((in_ptr[1] & 0x0f) << 8) | in_ptr[2];
2377
0
            }
2378
0
        }
2379
0
        else
2380
0
        {
2381
0
            bufptr[0] = (TIFF_JSAMPROW)buf;
2382
0
        }
2383
0
        if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
2384
0
            return (0);
2385
0
        if (nrows > 0)
2386
0
            tif->tif_row++;
2387
0
        buf += sp->bytesperline;
2388
0
    }
2389
2390
0
    if (sp->cinfo.c.data_precision == 12)
2391
0
    {
2392
0
        _TIFFfreeExt(tif, line16);
2393
0
    }
2394
2395
0
    return (1);
2396
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGEncode
Unexecuted instantiation: tif_jpeg_12.c:JPEGEncode
2397
2398
/*
2399
 * Encode a chunk of pixels.
2400
 * Incoming data is expected to be downsampled per sampling factors.
2401
 */
2402
static int JPEGEncodeRaw(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s)
2403
0
{
2404
0
    JPEGState *sp = JState(tif);
2405
0
    TIFF_JSAMPLE *inptr;
2406
0
    TIFF_JSAMPLE *outptr;
2407
0
    tmsize_t nrows;
2408
0
    JDIMENSION clumps_per_line, nclump;
2409
0
    int clumpoffset, ci, xpos, ypos;
2410
0
    jpeg_component_info *compptr;
2411
0
    int samples_per_clump = sp->samplesperclump;
2412
0
    tmsize_t bytesperclumpline;
2413
2414
0
    (void)s;
2415
0
    assert(sp != NULL);
2416
2417
0
    if (sp->encode_raw_error)
2418
0
    {
2419
0
        TIFFErrorExtR(tif, tif->tif_name, "JPEGEncodeRaw() already failed");
2420
0
        return 0;
2421
0
    }
2422
2423
    /* data is expected to be supplied in multiples of a clumpline */
2424
    /* a clumpline is equivalent to v_sampling desubsampled scanlines */
2425
    /* TODO: the following calculation of bytesperclumpline, should substitute
2426
     * calculation of sp->bytesperline, except that it is per v_sampling lines
2427
     */
2428
0
    bytesperclumpline =
2429
0
        ((((tmsize_t)sp->cinfo.c.image_width + sp->h_sampling - 1) /
2430
0
          sp->h_sampling) *
2431
0
             ((tmsize_t)sp->h_sampling * sp->v_sampling + 2) *
2432
0
             sp->cinfo.c.data_precision +
2433
0
         7) /
2434
0
        8;
2435
2436
0
    nrows = (cc / bytesperclumpline) * sp->v_sampling;
2437
0
    if (cc % bytesperclumpline)
2438
0
        TIFFWarningExtR(tif, tif->tif_name, "fractional scanline discarded");
2439
2440
    /* Cb,Cr both have sampling factors 1, so this is correct */
2441
0
    clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
2442
2443
0
    while (nrows > 0)
2444
0
    {
2445
        /*
2446
         * Fastest way to separate the data is to make one pass
2447
         * over the scanline for each row of each component.
2448
         */
2449
0
        clumpoffset = 0; /* first sample in clump */
2450
0
        for (ci = 0, compptr = sp->cinfo.c.comp_info;
2451
0
             ci < sp->cinfo.c.num_components; ci++, compptr++)
2452
0
        {
2453
0
            int hsamp = compptr->h_samp_factor;
2454
0
            int vsamp = compptr->v_samp_factor;
2455
0
            int padding = (int)(compptr->width_in_blocks * DCTSIZE -
2456
0
                                clumps_per_line * hsamp);
2457
0
            for (ypos = 0; ypos < vsamp; ypos++)
2458
0
            {
2459
0
                inptr = ((TIFF_JSAMPLE *)buf) + clumpoffset;
2460
0
                outptr = sp->ds_buffer[ci][sp->scancount * vsamp + ypos];
2461
0
                if (hsamp == 1)
2462
0
                {
2463
                    /* fast path for at least Cb and Cr */
2464
0
                    for (nclump = clumps_per_line; nclump-- > 0;)
2465
0
                    {
2466
0
                        *outptr++ = inptr[0];
2467
0
                        inptr += samples_per_clump;
2468
0
                    }
2469
0
                }
2470
0
                else
2471
0
                {
2472
                    /* general case */
2473
0
                    for (nclump = clumps_per_line; nclump-- > 0;)
2474
0
                    {
2475
0
                        for (xpos = 0; xpos < hsamp; xpos++)
2476
0
                            *outptr++ = inptr[xpos];
2477
0
                        inptr += samples_per_clump;
2478
0
                    }
2479
0
                }
2480
                /* pad each scanline as needed */
2481
0
                for (xpos = 0; xpos < padding; xpos++)
2482
0
                {
2483
0
                    *outptr = outptr[-1];
2484
0
                    outptr++;
2485
0
                }
2486
0
                clumpoffset += hsamp;
2487
0
            }
2488
0
        }
2489
0
        sp->scancount++;
2490
0
        if (sp->scancount >= DCTSIZE)
2491
0
        {
2492
0
            int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
2493
0
            if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
2494
0
            {
2495
0
                sp->encode_raw_error = TRUE;
2496
0
                return (0);
2497
0
            }
2498
0
            sp->scancount = 0;
2499
0
        }
2500
0
        tif->tif_row += sp->v_sampling;
2501
0
        buf += bytesperclumpline;
2502
0
        nrows -= sp->v_sampling;
2503
0
    }
2504
0
    return (1);
2505
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGEncodeRaw
Unexecuted instantiation: tif_jpeg_12.c:JPEGEncodeRaw
2506
2507
/*
2508
 * Finish up at the end of a strip or tile.
2509
 */
2510
static int JPEGPostEncode(TIFF *tif)
2511
0
{
2512
0
    JPEGState *sp = JState(tif);
2513
2514
0
    if (sp->scancount > 0)
2515
0
    {
2516
        /*
2517
         * Need to emit a partial bufferload of downsampled data.
2518
         * Pad the data vertically.
2519
         */
2520
0
        int ci, ypos, n;
2521
0
        jpeg_component_info *compptr;
2522
2523
0
        for (ci = 0, compptr = sp->cinfo.c.comp_info;
2524
0
             ci < sp->cinfo.c.num_components; ci++, compptr++)
2525
0
        {
2526
0
            int vsamp = compptr->v_samp_factor;
2527
0
            tmsize_t row_width =
2528
0
                compptr->width_in_blocks * DCTSIZE * sizeof(JSAMPLE);
2529
0
            for (ypos = sp->scancount * vsamp; ypos < DCTSIZE * vsamp; ypos++)
2530
0
            {
2531
0
                _TIFFmemcpy((void *)sp->ds_buffer[ci][ypos],
2532
0
                            (void *)sp->ds_buffer[ci][ypos - 1], row_width);
2533
0
            }
2534
0
        }
2535
0
        n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
2536
0
        if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
2537
0
            return (0);
2538
0
    }
2539
2540
0
    return (TIFFjpeg_finish_compress(JState(tif)));
2541
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGPostEncode
Unexecuted instantiation: tif_jpeg_12.c:JPEGPostEncode
2542
2543
static void JPEGCleanup(TIFF *tif)
2544
0
{
2545
0
    JPEGState *sp = JState(tif);
2546
2547
0
    assert(sp != 0);
2548
2549
0
    tif->tif_tagmethods.vgetfield = sp->otherSettings.vgetparent;
2550
0
    tif->tif_tagmethods.vsetfield = sp->otherSettings.vsetparent;
2551
0
    tif->tif_tagmethods.printdir = sp->otherSettings.printdir;
2552
0
    if (sp->cinfo_initialized)
2553
0
        TIFFjpeg_destroy(sp);         /* release libjpeg resources */
2554
0
    if (sp->otherSettings.jpegtables) /* tag value */
2555
0
        _TIFFfreeExt(tif, sp->otherSettings.jpegtables);
2556
0
    _TIFFfreeExt(tif, tif->tif_data); /* release local state */
2557
0
    tif->tif_data = NULL;
2558
2559
0
    _TIFFSetDefaultCompressionState(tif);
2560
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGCleanup
Unexecuted instantiation: tif_jpeg_12.c:JPEGCleanup
2561
2562
static void JPEGResetUpsampled(TIFF *tif)
2563
0
{
2564
0
    JPEGState *sp = JState(tif);
2565
0
    TIFFDirectory *td = &tif->tif_dir;
2566
2567
    /*
2568
     * Mark whether returned data is up-sampled or not so TIFFStripSize
2569
     * and TIFFTileSize return values that reflect the true amount of
2570
     * data.
2571
     */
2572
0
    tif->tif_flags &= ~TIFF_UPSAMPLED;
2573
0
    if (td->td_planarconfig == PLANARCONFIG_CONTIG)
2574
0
    {
2575
0
        if (td->td_photometric == PHOTOMETRIC_YCBCR &&
2576
0
            sp->otherSettings.jpegcolormode == JPEGCOLORMODE_RGB)
2577
0
        {
2578
0
            tif->tif_flags |= TIFF_UPSAMPLED;
2579
0
        }
2580
0
        else
2581
0
        {
2582
#ifdef notdef
2583
            if (td->td_ycbcrsubsampling[0] != 1 ||
2584
                td->td_ycbcrsubsampling[1] != 1)
2585
                ; /* XXX what about up-sampling? */
2586
#endif
2587
0
        }
2588
0
    }
2589
2590
    /*
2591
     * Must recalculate cached tile size in case sampling state changed.
2592
     * Should we really be doing this now if image size isn't set?
2593
     */
2594
0
    if (tif->tif_tilesize > 0)
2595
0
        tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
2596
0
    if (tif->tif_scanlinesize > 0)
2597
0
        tif->tif_scanlinesize = TIFFScanlineSize(tif);
2598
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGResetUpsampled
Unexecuted instantiation: tif_jpeg_12.c:JPEGResetUpsampled
2599
2600
static int JPEGVSetField(TIFF *tif, uint32_t tag, va_list ap)
2601
0
{
2602
0
    JPEGState *sp = JState(tif);
2603
0
    const TIFFField *fip;
2604
0
    uint32_t v32;
2605
2606
0
    assert(sp != NULL);
2607
2608
0
    switch (tag)
2609
0
    {
2610
0
        case TIFFTAG_JPEGTABLES:
2611
0
            v32 = (uint32_t)va_arg(ap, uint32_t);
2612
0
            if (v32 == 0)
2613
0
            {
2614
                /* XXX */
2615
0
                return (0);
2616
0
            }
2617
0
            _TIFFsetByteArrayExt(tif, &sp->otherSettings.jpegtables,
2618
0
                                 va_arg(ap, void *), v32);
2619
0
            sp->otherSettings.jpegtables_length = v32;
2620
0
            TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2621
0
            break;
2622
0
        case TIFFTAG_JPEGQUALITY:
2623
0
            sp->otherSettings.jpegquality = (int)va_arg(ap, int);
2624
0
            return (1); /* pseudo tag */
2625
0
        case TIFFTAG_JPEGCOLORMODE:
2626
0
            sp->otherSettings.jpegcolormode = (int)va_arg(ap, int);
2627
0
            JPEGResetUpsampled(tif);
2628
0
            return (1); /* pseudo tag */
2629
0
        case TIFFTAG_PHOTOMETRIC:
2630
0
        {
2631
0
            int ret_value = (*sp->otherSettings.vsetparent)(tif, tag, ap);
2632
0
            JPEGResetUpsampled(tif);
2633
0
            return ret_value;
2634
0
        }
2635
0
        case TIFFTAG_JPEGTABLESMODE:
2636
0
            sp->otherSettings.jpegtablesmode = (int)va_arg(ap, int);
2637
0
            return (1); /* pseudo tag */
2638
0
        case TIFFTAG_YCBCRSUBSAMPLING:
2639
            /* mark the fact that we have a real ycbcrsubsampling! */
2640
0
            sp->otherSettings.ycbcrsampling_fetched = 1;
2641
            /* should we be recomputing upsampling info here? */
2642
0
            return (*sp->otherSettings.vsetparent)(tif, tag, ap);
2643
0
        default:
2644
0
            return (*sp->otherSettings.vsetparent)(tif, tag, ap);
2645
0
    }
2646
2647
0
    if ((fip = TIFFFieldWithTag(tif, tag)) != NULL)
2648
0
    {
2649
0
        TIFFSetFieldBit(tif, fip->field_bit);
2650
0
    }
2651
0
    else
2652
0
    {
2653
0
        return (0);
2654
0
    }
2655
2656
0
    tif->tif_flags |= TIFF_DIRTYDIRECT;
2657
0
    return (1);
2658
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGVSetField
Unexecuted instantiation: tif_jpeg_12.c:JPEGVSetField
2659
2660
static int JPEGVGetField(TIFF *tif, uint32_t tag, va_list ap)
2661
0
{
2662
0
    JPEGState *sp = JState(tif);
2663
2664
0
    assert(sp != NULL);
2665
2666
0
    switch (tag)
2667
0
    {
2668
0
        case TIFFTAG_JPEGTABLES:
2669
0
            *va_arg(ap, uint32_t *) = sp->otherSettings.jpegtables_length;
2670
0
            *va_arg(ap, const void **) = sp->otherSettings.jpegtables;
2671
0
            break;
2672
0
        case TIFFTAG_JPEGQUALITY:
2673
0
            *va_arg(ap, int *) = sp->otherSettings.jpegquality;
2674
0
            break;
2675
0
        case TIFFTAG_JPEGCOLORMODE:
2676
0
            *va_arg(ap, int *) = sp->otherSettings.jpegcolormode;
2677
0
            break;
2678
0
        case TIFFTAG_JPEGTABLESMODE:
2679
0
            *va_arg(ap, int *) = sp->otherSettings.jpegtablesmode;
2680
0
            break;
2681
0
        default:
2682
0
            return (*sp->otherSettings.vgetparent)(tif, tag, ap);
2683
0
    }
2684
0
    return (1);
2685
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGVGetField
Unexecuted instantiation: tif_jpeg_12.c:JPEGVGetField
2686
2687
static void JPEGPrintDir(TIFF *tif, FILE *fd, long flags)
2688
0
{
2689
0
    JPEGState *sp = JState(tif);
2690
2691
0
    assert(sp != NULL);
2692
0
    (void)flags;
2693
2694
0
    if (sp != NULL)
2695
0
    {
2696
0
        if (TIFFFieldSet(tif, FIELD_JPEGTABLES))
2697
0
            fprintf(fd, "  JPEG Tables: (%" PRIu32 " bytes)\n",
2698
0
                    sp->otherSettings.jpegtables_length);
2699
0
        if (sp->otherSettings.printdir)
2700
0
            (*sp->otherSettings.printdir)(tif, fd, flags);
2701
0
    }
2702
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGPrintDir
Unexecuted instantiation: tif_jpeg_12.c:JPEGPrintDir
2703
2704
static uint32_t JPEGDefaultStripSize(TIFF *tif, uint32_t s)
2705
0
{
2706
0
    JPEGState *sp = JState(tif);
2707
0
    TIFFDirectory *td = &tif->tif_dir;
2708
2709
0
    s = (*sp->otherSettings.defsparent)(tif, s);
2710
0
    if (s < td->td_imagelength)
2711
0
        s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
2712
0
    return (s);
2713
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGDefaultStripSize
Unexecuted instantiation: tif_jpeg_12.c:JPEGDefaultStripSize
2714
2715
static void JPEGDefaultTileSize(TIFF *tif, uint32_t *tw, uint32_t *th)
2716
0
{
2717
0
    JPEGState *sp = JState(tif);
2718
0
    TIFFDirectory *td = &tif->tif_dir;
2719
2720
0
    (*sp->otherSettings.deftparent)(tif, tw, th);
2721
0
    *tw = TIFFroundup_32(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
2722
0
    *th = TIFFroundup_32(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
2723
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGDefaultTileSize
Unexecuted instantiation: tif_jpeg_12.c:JPEGDefaultTileSize
2724
2725
/*
2726
 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
2727
 * now that we allow a TIFF file to be opened in update mode it is necessary
2728
 * to have some way of deciding whether compression or decompression is
2729
 * desired other than looking at tif->tif_mode.  We accomplish this by
2730
 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
2731
 * If so, we assume decompression is desired.
2732
 *
2733
 * This is tricky, because TIFFInitJPEG() is called while the directory is
2734
 * being read, and generally speaking the BYTECOUNTS tag won't have been read
2735
 * at that point.  So we try to defer jpeg library initialization till we
2736
 * do have that tag ... basically any access that might require the compressor
2737
 * or decompressor that occurs after the reading of the directory.
2738
 *
2739
 * In an ideal world compressors or decompressors would be setup
2740
 * at the point where a single tile or strip was accessed (for read or write)
2741
 * so that stuff like update of missing tiles, or replacement of tiles could
2742
 * be done. However, we aren't trying to crack that nut just yet ...
2743
 *
2744
 * NFW, Feb 3rd, 2003.
2745
 */
2746
2747
static int JPEGInitializeLibJPEG(TIFF *tif, int decompress)
2748
0
{
2749
0
    JPEGState *sp = JState(tif);
2750
2751
0
    if (sp->cinfo_initialized)
2752
0
    {
2753
0
        if (!decompress && sp->cinfo.comm.is_decompressor)
2754
0
            TIFFjpeg_destroy(sp);
2755
0
        else if (decompress && !sp->cinfo.comm.is_decompressor)
2756
0
            TIFFjpeg_destroy(sp);
2757
0
        else
2758
0
            return 1;
2759
2760
0
        sp->cinfo_initialized = 0;
2761
0
    }
2762
2763
    /*
2764
     * Initialize libjpeg.
2765
     */
2766
0
    if (decompress)
2767
0
    {
2768
0
        if (!TIFFjpeg_create_decompress(sp))
2769
0
            return (0);
2770
0
    }
2771
0
    else
2772
0
    {
2773
0
        if (!TIFFjpeg_create_compress(sp))
2774
0
            return (0);
2775
0
#ifndef TIFF_JPEG_MAX_MEMORY_TO_USE
2776
0
#define TIFF_JPEG_MAX_MEMORY_TO_USE (10 * 1024 * 1024)
2777
0
#endif
2778
        /* libjpeg turbo 1.5.2 honours max_memory_to_use, but has no backing */
2779
        /* store implementation, so better not set max_memory_to_use ourselves.
2780
         */
2781
        /* See https://github.com/libjpeg-turbo/libjpeg-turbo/issues/162 */
2782
0
        if (sp->cinfo.c.mem->max_memory_to_use > 0)
2783
0
        {
2784
            /* This is to address bug related in ticket GDAL #1795. */
2785
0
            if (getenv("JPEGMEM") == NULL)
2786
0
            {
2787
                /* Increase the max memory usable. This helps when creating
2788
                 * files */
2789
                /* with "big" tile, without using libjpeg temporary files. */
2790
                /* For example a 512x512 tile with 3 bands */
2791
                /* requires 1.5 MB which is above libjpeg 1MB default */
2792
0
                if (sp->cinfo.c.mem->max_memory_to_use <
2793
0
                    TIFF_JPEG_MAX_MEMORY_TO_USE)
2794
0
                    sp->cinfo.c.mem->max_memory_to_use =
2795
0
                        TIFF_JPEG_MAX_MEMORY_TO_USE;
2796
0
            }
2797
0
        }
2798
0
    }
2799
2800
0
    sp->cinfo_initialized = TRUE;
2801
2802
0
    return 1;
2803
0
}
Unexecuted instantiation: tif_jpeg.c:JPEGInitializeLibJPEG
Unexecuted instantiation: tif_jpeg_12.c:JPEGInitializeLibJPEG
2804
2805
/* Common to tif_jpeg.c and tif_jpeg_12.c */
2806
static void TIFFInitJPEGCommon(TIFF *tif)
2807
0
{
2808
0
    JPEGState *sp;
2809
2810
0
    sp = JState(tif);
2811
0
    sp->tif = tif; /* back link */
2812
2813
    /* Default values for codec-specific fields */
2814
0
    sp->otherSettings.jpegtables = NULL;
2815
0
    sp->otherSettings.jpegtables_length = 0;
2816
0
    sp->otherSettings.jpegquality = 75; /* Default IJG quality */
2817
0
    sp->otherSettings.jpegcolormode = JPEGCOLORMODE_RAW;
2818
0
    sp->otherSettings.jpegtablesmode =
2819
0
        JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
2820
0
    sp->otherSettings.ycbcrsampling_fetched = 0;
2821
2822
0
    tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
2823
0
    tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
2824
0
    tif->tif_tagmethods.printdir = JPEGPrintDir;   /* hook for codec tags */
2825
2826
    /*
2827
     * Install codec methods.
2828
     */
2829
0
    tif->tif_fixuptags = JPEGFixupTags;
2830
0
    tif->tif_setupdecode = JPEGSetupDecode;
2831
0
    tif->tif_predecode = JPEGPreDecode;
2832
0
    tif->tif_decoderow = JPEGDecode;
2833
0
    tif->tif_decodestrip = JPEGDecode;
2834
0
    tif->tif_decodetile = JPEGDecode;
2835
0
    tif->tif_setupencode = JPEGSetupEncode;
2836
0
    tif->tif_preencode = JPEGPreEncode;
2837
0
    tif->tif_postencode = JPEGPostEncode;
2838
0
    tif->tif_encoderow = JPEGEncode;
2839
0
    tif->tif_encodestrip = JPEGEncode;
2840
0
    tif->tif_encodetile = JPEGEncode;
2841
0
    tif->tif_cleanup = JPEGCleanup;
2842
2843
0
    tif->tif_defstripsize = JPEGDefaultStripSize;
2844
0
    tif->tif_deftilesize = JPEGDefaultTileSize;
2845
0
    tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
2846
0
    sp->cinfo_initialized = FALSE;
2847
0
}
Unexecuted instantiation: tif_jpeg.c:TIFFInitJPEGCommon
Unexecuted instantiation: tif_jpeg_12.c:TIFFInitJPEGCommon
2848
2849
int TIFFInitJPEG(TIFF *tif, int scheme)
2850
0
{
2851
0
    JPEGState *sp;
2852
2853
0
    (void)scheme;
2854
0
    assert(scheme == COMPRESSION_JPEG);
2855
2856
    /*
2857
     * Merge codec-specific tag information.
2858
     */
2859
0
    if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields)))
2860
0
    {
2861
0
        TIFFErrorExtR(tif, "TIFFInitJPEG",
2862
0
                      "Merging JPEG codec-specific tags failed");
2863
0
        return 0;
2864
0
    }
2865
2866
    /*
2867
     * Allocate state block so tag methods have storage to record values.
2868
     */
2869
0
    tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(JPEGState));
2870
2871
0
    if (tif->tif_data == NULL)
2872
0
    {
2873
0
        TIFFErrorExtR(tif, "TIFFInitJPEG", "No space for JPEG state block");
2874
0
        return 0;
2875
0
    }
2876
0
    _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
2877
2878
0
    sp = JState(tif);
2879
    /*
2880
     * Override parent get/set field methods.
2881
     */
2882
0
    sp->otherSettings.vgetparent = tif->tif_tagmethods.vgetfield;
2883
0
    sp->otherSettings.vsetparent = tif->tif_tagmethods.vsetfield;
2884
0
    sp->otherSettings.printdir = tif->tif_tagmethods.printdir;
2885
2886
0
    sp->otherSettings.defsparent = tif->tif_defstripsize;
2887
0
    sp->otherSettings.deftparent = tif->tif_deftilesize;
2888
2889
0
    TIFFInitJPEGCommon(tif);
2890
2891
    /*
2892
    ** Create a JPEGTables field if no directory has yet been created.
2893
    ** We do this just to ensure that sufficient space is reserved for
2894
    ** the JPEGTables field.  It will be properly created the right
2895
    ** size later.
2896
    */
2897
0
    if (tif->tif_diroff == 0)
2898
0
    {
2899
0
#define SIZE_OF_JPEGTABLES 2000
2900
        /*
2901
        The following line assumes incorrectly that all JPEG-in-TIFF files will
2902
        have a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags
2903
        to be written when the JPEG data is placed with TIFFWriteRawStrip.  The
2904
        field bit should be set, anyway, later when actual JPEGTABLES header is
2905
        generated, so removing it here hopefully is harmless.
2906
        TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2907
        */
2908
0
        sp->otherSettings.jpegtables_length = SIZE_OF_JPEGTABLES;
2909
0
        sp->otherSettings.jpegtables =
2910
0
            (void *)_TIFFmallocExt(tif, sp->otherSettings.jpegtables_length);
2911
0
        if (sp->otherSettings.jpegtables)
2912
0
        {
2913
0
            _TIFFmemset(sp->otherSettings.jpegtables, 0, SIZE_OF_JPEGTABLES);
2914
0
        }
2915
0
        else
2916
0
        {
2917
0
            TIFFErrorExtR(tif, "TIFFInitJPEG",
2918
0
                          "Failed to allocate memory for JPEG tables");
2919
0
            return 0;
2920
0
        }
2921
0
#undef SIZE_OF_JPEGTABLES
2922
0
    }
2923
0
    return 1;
2924
0
}
Unexecuted instantiation: gdal_TIFFInitJPEG
Unexecuted instantiation: gdal_TIFFInitJPEG_12
2925
#endif /* JPEG_SUPPORT */