Coverage Report

Created: 2025-06-13 06:50

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