LCOV - code coverage report
Current view: top level - frmts/gtiff/libtiff - tif_jpeg.c (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 733 1119 65.5 %
Date: 2025-12-13 23:48:27 Functions: 57 73 78.1 %

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

Generated by: LCOV version 1.14