LCOV - code coverage report
Current view: top level - frmts/gtiff/libtiff - tif_jpeg.c (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 739 1148 64.4 %
Date: 2026-06-03 16:29:47 Functions: 58 75 77.3 %

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

Generated by: LCOV version 1.14