LCOV - code coverage report
Current view: top level - frmts/gtiff/libtiff - tif_jpeg.c (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 744 1148 64.8 %
Date: 2026-05-04 15:01:57 Functions: 57 74 77.0 %

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

Generated by: LCOV version 1.14