LCOV - code coverage report
Current view: top level - frmts/gtiff/libtiff - tif_ojpeg.c (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 724 1453 49.8 %
Date: 2026-03-20 01:44:29 Functions: 35 63 55.6 %

          Line data    Source code
       1             : /* WARNING: The type of JPEG encapsulation defined by the TIFF Version 6.0
       2             :    specification is now totally obsolete and deprecated for new applications and
       3             :    images. This file was was created solely in order to read unconverted images
       4             :    still present on some users' computer systems. It will never be extended
       5             :    to write such files. Writing new-style JPEG compressed TIFFs is implemented
       6             :    in tif_jpeg.c.
       7             : 
       8             :    The code is carefully crafted to robustly read all gathered JPEG-in-TIFF
       9             :    testfiles, and anticipate as much as possible all other... But still, it may
      10             :    fail on some. If you encounter problems, please report them on the TIFF
      11             :    mailing list and/or to Joris Van Damme <info@awaresystems.be>.
      12             : 
      13             :    Please read the file called "TIFF Technical Note #2" if you need to be
      14             :    convinced this compression scheme is bad and breaks TIFF. That document
      15             :    is linked to from the LibTiff site <http://www.remotesensing.org/libtiff/>
      16             :    and from AWare Systems' TIFF section
      17             :    <http://www.awaresystems.be/imaging/tiff.html>. It is also absorbed
      18             :    in Adobe's specification supplements, marked "draft" up to this day, but
      19             :    supported by the TIFF community.
      20             : 
      21             :    This file interfaces with Release 6B of the JPEG Library written by the
      22             :    Independent JPEG Group. Previous versions of this file required a hack inside
      23             :    the LibJpeg library. This version no longer requires that. Remember to
      24             :    remove the hack if you update from the old version.
      25             : 
      26             :    Copyright (c) Joris Van Damme <info@awaresystems.be>
      27             :    Copyright (c) AWare Systems <http://www.awaresystems.be/>
      28             : 
      29             :    The licence agreement for this file is the same as the rest of the LibTiff
      30             :    library.
      31             : 
      32             :    IN NO EVENT SHALL JORIS VAN DAMME OR AWARE SYSTEMS BE LIABLE FOR
      33             :    ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
      34             :    OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
      35             :    WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
      36             :    LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
      37             :    OF THIS SOFTWARE.
      38             : 
      39             :    Joris Van Damme and/or AWare Systems may be available for custom
      40             :    development. If you like what you see, and need anything similar or related,
      41             :    contact <info@awaresystems.be>.
      42             : */
      43             : 
      44             : /* What is what, and what is not?
      45             : 
      46             :    This decoder starts with an input stream, that is essentially the
      47             :    JpegInterchangeFormat stream, if any, followed by the strile data, if any.
      48             :    This stream is read in OJPEGReadByte and related functions.
      49             : 
      50             :    It analyzes the start of this stream, until it encounters non-marker data,
      51             :    i.e. compressed image data. Some of the header markers it sees have no actual
      52             :    content, like the SOI marker, and APP/COM markers that really shouldn't even
      53             :    be there. Some other markers do have content, and the valuable bits and
      54             :    pieces of information in these markers are saved, checking all to verify that
      55             :    the stream is more or less within expected bounds. This happens inside the
      56             :    OJPEGReadHeaderInfoSecStreamXxx functions.
      57             : 
      58             :    Some OJPEG imagery contains no valid JPEG header markers. This situation is
      59             :    picked up on if we've seen no SOF marker when we're at the start of the
      60             :    compressed image data. In this case, the tables are read from JpegXxxTables
      61             :    tags, and the other bits and pieces of information is initialized to its most
      62             :    basic value. This is implemented in the OJPEGReadHeaderInfoSecTablesXxx
      63             :    functions.
      64             : 
      65             :    When this is complete, a good and valid JPEG header can be assembled, and
      66             :    this is passed through to LibJpeg. When that's done, the remainder of the
      67             :    input stream, i.e. the compressed image data, can be passed through
      68             :    unchanged. This is done in OJPEGWriteStream functions.
      69             : 
      70             :    LibTiff rightly expects to know the subsampling values before decompression.
      71             :    Just like in new-style JPEG-in-TIFF, though, or even more so, actually, the
      72             :    YCbCrsubsampling tag is notoriously unreliable. To correct these tag values
      73             :    with the ones inside the JPEG stream, the first part of the input stream is
      74             :    pre-scanned in OJPEGSubsamplingCorrect, making no note of any other data,
      75             :    reporting no warnings or errors, up to the point where either these values
      76             :    are read, or it's clear they aren't there. This means that some of the data
      77             :    is read twice, but we feel speed in correcting these values is important
      78             :    enough to warrant this sacrifice. Although there is currently no define or
      79             :    other configuration mechanism to disable this behavior, the actual header
      80             :    scanning is build to robustly respond with error report if it should
      81             :    encounter an uncorrected mismatch of subsampling values. See
      82             :    OJPEGReadHeaderInfoSecStreamSof.
      83             : 
      84             :    The restart interval and restart markers are the most tricky part... The
      85             :    restart interval can be specified in a tag. It can also be set inside the
      86             :    input JPEG stream. It can be used inside the input JPEG stream. If reading
      87             :    from strile data, we've consistently discovered the need to insert restart
      88             :    markers in between the different striles, as is also probably the most likely
      89             :    interpretation of the original TIFF 6.0 specification. With all this setting
      90             :    of interval, and actual use of markers that is not predictable at the time of
      91             :    valid JPEG header assembly, the restart thing may turn out the Achilles heel
      92             :    of this implementation. Fortunately, most OJPEG writer vendors succeed in
      93             :    reading back what they write, which may be the reason why we've been able to
      94             :    discover ways that seem to work.
      95             : 
      96             :    Some special provision is made for planarconfig separate OJPEG files. These
      97             :    seem to consistently contain header info, a SOS marker, a plane, SOS marker,
      98             :    plane, SOS, and plane. This may or may not be a valid JPEG configuration, we
      99             :    don't know and don't care. We want LibTiff to be able to access the planes
     100             :    individually, without huge buffering inside LibJpeg, anyway. So we compose
     101             :    headers to feed to LibJpeg, in this case, that allow us to pass a single
     102             :    plane such that LibJpeg sees a valid single-channel JPEG stream. Locating
     103             :    subsequent SOS markers, and thus subsequent planes, is done inside
     104             :    OJPEGReadSecondarySos.
     105             : 
     106             :    The benefit of the scheme is... that it works, basically. We know of no other
     107             :    that does. It works without checking software tag, or otherwise going about
     108             :    things in an OJPEG flavor specific manner. Instead, it is a single scheme,
     109             :    that covers the cases with and without JpegInterchangeFormat, with and
     110             :    without striles, with part of the header in JpegInterchangeFormat and
     111             :    remainder in first strile, etc. It is forgiving and robust, may likely work
     112             :    with OJPEG flavors we've not seen yet, and makes most out of the data.
     113             : 
     114             :    Another nice side-effect is that a complete JPEG single valid stream is build
     115             :    if planarconfig is not separate (vast majority). We may one day use that to
     116             :    build converters to JPEG, and/or to new-style JPEG compression inside TIFF.
     117             : 
     118             :    A disadvantage is the lack of random access to the individual striles. This
     119             :    is the reason for much of the complicated restart-and-position stuff inside
     120             :    OJPEGPreDecode. Applications would do well accessing all striles in order, as
     121             :    this will result in a single sequential scan of the input stream, and no
     122             :    restarting of LibJpeg decoding session.
     123             : */
     124             : 
     125             : #define WIN32_LEAN_AND_MEAN
     126             : #define VC_EXTRALEAN
     127             : 
     128             : #include "tiffiop.h"
     129             : #ifdef OJPEG_SUPPORT
     130             : 
     131             : /* Configuration defines here are:
     132             :  * JPEG_ENCAP_EXTERNAL: The normal way to call libjpeg, uses longjump. In some
     133             :  * environments, like eg LibTiffDelphi, this is not possible. For this reason,
     134             :  * the actual calls to libjpeg, with longjump stuff, are encapsulated in
     135             :  * dedicated functions. When JPEG_ENCAP_EXTERNAL is defined, these encapsulating
     136             :  * functions are declared external to this unit, and can be defined elsewhere to
     137             :  * use stuff other then longjump. The default mode, without JPEG_ENCAP_EXTERNAL,
     138             :  * implements the call encapsulators here, internally, with normal longjump.
     139             :  * SETJMP, LONGJMP, JMP_BUF: On some machines/environments a longjump equivalent
     140             :  * is conveniently available, but still it may be worthwhile to use _setjmp or
     141             :  * sigsetjmp in place of plain setjmp. These macros will make it easier. It is
     142             :  * useless to fiddle with these if you define JPEG_ENCAP_EXTERNAL. OJPEG_BUFFER:
     143             :  * Define the size of the desired buffer here. Should be small enough so as to
     144             :  * guarantee instant processing, optimal streaming and optimal use of processor
     145             :  * cache, but also big enough so as to not result in significant call overhead.
     146             :  * It should be at least a few bytes to accommodate some structures (this is
     147             :  * verified in asserts), but it would not be sensible to make it this small
     148             :  * anyway, and it should be at most 64K since it is indexed with uint16_t. We
     149             :  * recommend 2K. EGYPTIANWALK: You could also define EGYPTIANWALK here, but it
     150             :  * is not used anywhere and has absolutely no effect. That is why most people
     151             :  * insist the EGYPTIANWALK is a bit silly.
     152             :  */
     153             : 
     154             : /* define LIBJPEG_ENCAP_EXTERNAL */
     155             : #define SETJMP(jbuf) setjmp(jbuf)
     156             : #define LONGJMP(jbuf, code) longjmp(jbuf, code)
     157             : #define JMP_BUF jmp_buf
     158             : #define OJPEG_BUFFER 2048
     159             : /* define EGYPTIANWALK */
     160             : 
     161             : #define JPEG_MARKER_SOF0 0xC0
     162             : #define JPEG_MARKER_SOF1 0xC1
     163             : #define JPEG_MARKER_SOF3 0xC3
     164             : #define JPEG_MARKER_DHT 0xC4
     165             : #define JPEG_MARKER_RST0 0XD0
     166             : #define JPEG_MARKER_SOI 0xD8
     167             : #define JPEG_MARKER_EOI 0xD9
     168             : #define JPEG_MARKER_SOS 0xDA
     169             : #define JPEG_MARKER_DQT 0xDB
     170             : #define JPEG_MARKER_DRI 0xDD
     171             : #define JPEG_MARKER_APP0 0xE0
     172             : #define JPEG_MARKER_COM 0xFE
     173             : 
     174             : #define FIELD_OJPEG_JPEGINTERCHANGEFORMAT (FIELD_CODEC + 0)
     175             : #define FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH (FIELD_CODEC + 1)
     176             : #define FIELD_OJPEG_JPEGQTABLES (FIELD_CODEC + 2)
     177             : #define FIELD_OJPEG_JPEGDCTABLES (FIELD_CODEC + 3)
     178             : #define FIELD_OJPEG_JPEGACTABLES (FIELD_CODEC + 4)
     179             : #define FIELD_OJPEG_JPEGPROC (FIELD_CODEC + 5)
     180             : #define FIELD_OJPEG_JPEGRESTARTINTERVAL (FIELD_CODEC + 6)
     181             : 
     182             : static const TIFFField ojpegFields[] = {
     183             :     {TIFFTAG_JPEGIFOFFSET, 1, 1, TIFF_LONG8, 0, TIFF_SETGET_UINT64,
     184             :      FIELD_OJPEG_JPEGINTERCHANGEFORMAT, TRUE, FALSE, "JpegInterchangeFormat",
     185             :      NULL},
     186             :     {TIFFTAG_JPEGIFBYTECOUNT, 1, 1, TIFF_LONG8, 0, TIFF_SETGET_UINT64,
     187             :      FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH, TRUE, FALSE,
     188             :      "JpegInterchangeFormatLength", NULL},
     189             :     {TIFFTAG_JPEGQTABLES, TIFF_VARIABLE2, TIFF_VARIABLE2, TIFF_LONG8, 0,
     190             :      TIFF_SETGET_C32_UINT64, FIELD_OJPEG_JPEGQTABLES, FALSE, TRUE,
     191             :      "JpegQTables", NULL},
     192             :     {TIFFTAG_JPEGDCTABLES, TIFF_VARIABLE2, TIFF_VARIABLE2, TIFF_LONG8, 0,
     193             :      TIFF_SETGET_C32_UINT64, FIELD_OJPEG_JPEGDCTABLES, FALSE, TRUE,
     194             :      "JpegDcTables", NULL},
     195             :     {TIFFTAG_JPEGACTABLES, TIFF_VARIABLE2, TIFF_VARIABLE2, TIFF_LONG8, 0,
     196             :      TIFF_SETGET_C32_UINT64, FIELD_OJPEG_JPEGACTABLES, FALSE, TRUE,
     197             :      "JpegAcTables", NULL},
     198             :     {TIFFTAG_JPEGPROC, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16,
     199             :      FIELD_OJPEG_JPEGPROC, FALSE, FALSE, "JpegProc", NULL},
     200             :     {TIFFTAG_JPEGRESTARTINTERVAL, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16,
     201             :      FIELD_OJPEG_JPEGRESTARTINTERVAL, FALSE, FALSE, "JpegRestartInterval",
     202             :      NULL},
     203             : };
     204             : 
     205             : #ifndef LIBJPEG_ENCAP_EXTERNAL
     206             : #include <setjmp.h>
     207             : #endif
     208             : 
     209             : #include "jerror.h"
     210             : #include "jpeglib.h"
     211             : 
     212             : #ifndef TIFF_jpeg_source_mgr_defined
     213             : #define TIFF_jpeg_source_mgr_defined
     214             : typedef struct jpeg_source_mgr jpeg_source_mgr;
     215             : #endif
     216             : 
     217             : #ifndef TIFF_jpeg_error_mgr_defined
     218             : #define TIFF_jpeg_error_mgr_defined
     219             : typedef struct jpeg_error_mgr jpeg_error_mgr;
     220             : #endif
     221             : 
     222             : typedef struct jpeg_common_struct jpeg_common_struct;
     223             : typedef struct jpeg_decompress_struct jpeg_decompress_struct;
     224             : 
     225             : typedef enum
     226             : {
     227             :     osibsNotSetYet,
     228             :     osibsJpegInterchangeFormat,
     229             :     osibsStrile,
     230             :     osibsEof
     231             : } OJPEGStateInBufferSource;
     232             : 
     233             : typedef enum
     234             : {
     235             :     ososSoi,
     236             :     ososQTable0,
     237             :     ososQTable1,
     238             :     ososQTable2,
     239             :     ososQTable3,
     240             :     ososDcTable0,
     241             :     ososDcTable1,
     242             :     ososDcTable2,
     243             :     ososDcTable3,
     244             :     ososAcTable0,
     245             :     ososAcTable1,
     246             :     ososAcTable2,
     247             :     ososAcTable3,
     248             :     ososDri,
     249             :     ososSof,
     250             :     ososSos,
     251             :     ososCompressed,
     252             :     ososRst,
     253             :     ososEoi
     254             : } OJPEGStateOutState;
     255             : 
     256             : typedef struct
     257             : {
     258             :     TIFF *tif;
     259             :     int decoder_ok;
     260             :     int error_in_raw_data_decoding;
     261             : #ifndef LIBJPEG_ENCAP_EXTERNAL
     262             :     JMP_BUF exit_jmpbuf;
     263             : #endif
     264             :     TIFFVGetMethod vgetparent;
     265             :     TIFFVSetMethod vsetparent;
     266             :     TIFFPrintMethod printdir;
     267             :     uint64_t file_size;
     268             :     uint32_t image_width;
     269             :     uint32_t image_length;
     270             :     uint32_t strile_width;
     271             :     uint32_t strile_length;
     272             :     uint32_t strile_length_total;
     273             :     uint8_t samples_per_pixel;
     274             :     uint8_t plane_sample_offset;
     275             :     uint8_t samples_per_pixel_per_plane;
     276             :     uint64_t jpeg_interchange_format;
     277             :     uint64_t jpeg_interchange_format_length;
     278             :     uint8_t jpeg_proc;
     279             :     uint8_t subsamplingcorrect;
     280             :     uint8_t subsamplingcorrect_done;
     281             :     uint8_t subsampling_tag;
     282             :     uint8_t subsampling_hor;
     283             :     uint8_t subsampling_ver;
     284             :     uint8_t subsampling_force_desubsampling_inside_decompression;
     285             :     uint8_t qtable_offset_count;
     286             :     uint8_t dctable_offset_count;
     287             :     uint8_t actable_offset_count;
     288             :     uint64_t qtable_offset[3];
     289             :     uint64_t dctable_offset[3];
     290             :     uint64_t actable_offset[3];
     291             :     uint8_t *qtable[4];
     292             :     uint8_t *dctable[4];
     293             :     uint8_t *actable[4];
     294             :     uint16_t restart_interval;
     295             :     uint8_t restart_index;
     296             :     uint8_t sof_log;
     297             :     uint8_t sof_marker_id;
     298             :     uint32_t sof_x;
     299             :     uint32_t sof_y;
     300             :     uint8_t sof_c[3];
     301             :     uint8_t sof_hv[3];
     302             :     uint8_t sof_tq[3];
     303             :     uint8_t sos_cs[3];
     304             :     uint8_t sos_tda[3];
     305             :     struct
     306             :     {
     307             :         uint8_t log;
     308             :         OJPEGStateInBufferSource in_buffer_source;
     309             :         uint32_t in_buffer_next_strile;
     310             :         uint64_t in_buffer_file_pos;
     311             :         uint64_t in_buffer_file_togo;
     312             :     } sos_end[3];
     313             :     uint8_t readheader_done;
     314             :     uint8_t writeheader_done;
     315             :     uint16_t write_cursample;
     316             :     uint32_t write_curstrile;
     317             :     uint8_t libjpeg_session_active;
     318             :     uint8_t libjpeg_jpeg_query_style;
     319             :     jpeg_error_mgr libjpeg_jpeg_error_mgr;
     320             :     jpeg_decompress_struct libjpeg_jpeg_decompress_struct;
     321             :     jpeg_source_mgr libjpeg_jpeg_source_mgr;
     322             :     uint8_t subsampling_convert_log;
     323             :     uint32_t subsampling_convert_ylinelen;
     324             :     uint32_t subsampling_convert_ylines;
     325             :     uint32_t subsampling_convert_clinelen;
     326             :     uint32_t subsampling_convert_clines;
     327             :     uint32_t subsampling_convert_ybuflen;
     328             :     uint32_t subsampling_convert_cbuflen;
     329             :     uint32_t subsampling_convert_ycbcrbuflen;
     330             :     uint8_t *subsampling_convert_ycbcrbuf;
     331             :     uint8_t *subsampling_convert_ybuf;
     332             :     uint8_t *subsampling_convert_cbbuf;
     333             :     uint8_t *subsampling_convert_crbuf;
     334             :     uint32_t subsampling_convert_ycbcrimagelen;
     335             :     uint8_t **subsampling_convert_ycbcrimage;
     336             :     uint32_t subsampling_convert_clinelenout;
     337             :     uint32_t subsampling_convert_state;
     338             :     uint32_t bytes_per_line;   /* if the codec outputs subsampled data, a 'line'
     339             :                                   in bytes_per_line */
     340             :     uint32_t lines_per_strile; /* and lines_per_strile means subsampling_ver
     341             :                                   desubsampled rows     */
     342             :     OJPEGStateInBufferSource in_buffer_source;
     343             :     uint32_t in_buffer_next_strile;
     344             :     uint32_t in_buffer_strile_count;
     345             :     uint64_t in_buffer_file_pos;
     346             :     uint8_t in_buffer_file_pos_log;
     347             :     uint64_t in_buffer_file_togo;
     348             :     uint16_t in_buffer_togo;
     349             :     uint8_t *in_buffer_cur;
     350             :     uint8_t in_buffer[OJPEG_BUFFER];
     351             :     OJPEGStateOutState out_state;
     352             :     uint8_t out_buffer[OJPEG_BUFFER];
     353             :     uint8_t *skip_buffer;
     354             : } OJPEGState;
     355             : 
     356             : static int OJPEGVGetField(TIFF *tif, uint32_t tag, va_list ap);
     357             : static int OJPEGVSetField(TIFF *tif, uint32_t tag, va_list ap);
     358             : static void OJPEGPrintDir(TIFF *tif, FILE *fd, long flags);
     359             : 
     360             : static int OJPEGFixupTags(TIFF *tif);
     361             : static int OJPEGSetupDecode(TIFF *tif);
     362             : static int OJPEGPreDecode(TIFF *tif, uint16_t s);
     363             : static int OJPEGPreDecodeSkipRaw(TIFF *tif);
     364             : static int OJPEGPreDecodeSkipScanlines(TIFF *tif);
     365             : static int OJPEGDecode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
     366             : static int OJPEGDecodeRaw(TIFF *tif, uint8_t *buf, tmsize_t cc);
     367             : static int OJPEGDecodeScanlines(TIFF *tif, uint8_t *buf, tmsize_t cc);
     368             : static void OJPEGPostDecode(TIFF *tif, uint8_t *buf, tmsize_t cc);
     369             : static int OJPEGSetupEncode(TIFF *tif);
     370             : static int OJPEGPreEncode(TIFF *tif, uint16_t s);
     371             : static int OJPEGEncode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s);
     372             : static int OJPEGPostEncode(TIFF *tif);
     373             : static void OJPEGCleanup(TIFF *tif);
     374             : 
     375             : static void OJPEGSubsamplingCorrect(TIFF *tif);
     376             : static int OJPEGReadHeaderInfo(TIFF *tif);
     377             : static int OJPEGReadSecondarySos(TIFF *tif, uint16_t s);
     378             : static int OJPEGWriteHeaderInfo(TIFF *tif);
     379             : static void OJPEGLibjpegSessionAbort(TIFF *tif);
     380             : 
     381             : static int OJPEGReadHeaderInfoSec(TIFF *tif);
     382             : static int OJPEGReadHeaderInfoSecStreamDri(TIFF *tif);
     383             : static int OJPEGReadHeaderInfoSecStreamDqt(TIFF *tif);
     384             : static int OJPEGReadHeaderInfoSecStreamDht(TIFF *tif);
     385             : static int OJPEGReadHeaderInfoSecStreamSof(TIFF *tif, uint8_t marker_id);
     386             : static int OJPEGReadHeaderInfoSecStreamSos(TIFF *tif);
     387             : static int OJPEGReadHeaderInfoSecTablesQTable(TIFF *tif);
     388             : static int OJPEGReadHeaderInfoSecTablesDcTable(TIFF *tif);
     389             : static int OJPEGReadHeaderInfoSecTablesAcTable(TIFF *tif);
     390             : 
     391             : static int OJPEGReadBufferFill(OJPEGState *sp);
     392             : static int OJPEGReadByte(OJPEGState *sp, uint8_t *byte);
     393             : static int OJPEGReadBytePeek(OJPEGState *sp, uint8_t *byte);
     394             : static void OJPEGReadByteAdvance(OJPEGState *sp);
     395             : static int OJPEGReadWord(OJPEGState *sp, uint16_t *word);
     396             : static int OJPEGReadBlock(OJPEGState *sp, uint16_t len, void *mem);
     397             : static void OJPEGReadSkip(OJPEGState *sp, uint16_t len);
     398             : 
     399             : static int OJPEGWriteStream(TIFF *tif, void **mem, uint32_t *len);
     400             : static void OJPEGWriteStreamSoi(TIFF *tif, void **mem, uint32_t *len);
     401             : static void OJPEGWriteStreamQTable(TIFF *tif, uint8_t table_index, void **mem,
     402             :                                    uint32_t *len);
     403             : static void OJPEGWriteStreamDcTable(TIFF *tif, uint8_t table_index, void **mem,
     404             :                                     uint32_t *len);
     405             : static void OJPEGWriteStreamAcTable(TIFF *tif, uint8_t table_index, void **mem,
     406             :                                     uint32_t *len);
     407             : static void OJPEGWriteStreamDri(TIFF *tif, void **mem, uint32_t *len);
     408             : static void OJPEGWriteStreamSof(TIFF *tif, void **mem, uint32_t *len);
     409             : static void OJPEGWriteStreamSos(TIFF *tif, void **mem, uint32_t *len);
     410             : static int OJPEGWriteStreamCompressed(TIFF *tif, void **mem, uint32_t *len);
     411             : static void OJPEGWriteStreamRst(TIFF *tif, void **mem, uint32_t *len);
     412             : static void OJPEGWriteStreamEoi(TIFF *tif, void **mem, uint32_t *len);
     413             : 
     414             : #ifdef LIBJPEG_ENCAP_EXTERNAL
     415             : extern int jpeg_create_decompress_encap(OJPEGState *sp,
     416             :                                         jpeg_decompress_struct *cinfo);
     417             : extern int jpeg_read_header_encap(OJPEGState *sp, jpeg_decompress_struct *cinfo,
     418             :                                   uint8_t require_image);
     419             : extern int jpeg_start_decompress_encap(OJPEGState *sp,
     420             :                                        jpeg_decompress_struct *cinfo);
     421             : extern int jpeg_read_scanlines_encap(OJPEGState *sp,
     422             :                                      jpeg_decompress_struct *cinfo,
     423             :                                      void *scanlines, uint32_t max_lines);
     424             : extern int jpeg_read_raw_data_encap(OJPEGState *sp,
     425             :                                     jpeg_decompress_struct *cinfo, void *data,
     426             :                                     uint32_t max_lines);
     427             : extern void jpeg_encap_unwind(TIFF *tif);
     428             : #else
     429             : static int jpeg_create_decompress_encap(OJPEGState *sp,
     430             :                                         jpeg_decompress_struct *j);
     431             : static int jpeg_read_header_encap(OJPEGState *sp, jpeg_decompress_struct *cinfo,
     432             :                                   uint8_t require_image);
     433             : static int jpeg_start_decompress_encap(OJPEGState *sp,
     434             :                                        jpeg_decompress_struct *cinfo);
     435             : static int jpeg_read_scanlines_encap(OJPEGState *sp,
     436             :                                      jpeg_decompress_struct *cinfo,
     437             :                                      void *scanlines, uint32_t max_lines);
     438             : static int jpeg_read_raw_data_encap(OJPEGState *sp,
     439             :                                     jpeg_decompress_struct *cinfo, void *data,
     440             :                                     uint32_t max_lines);
     441             : static void jpeg_encap_unwind(TIFF *tif);
     442             : #endif
     443             : 
     444             : static void OJPEGLibjpegJpegErrorMgrOutputMessage(jpeg_common_struct *cinfo);
     445             : static void OJPEGLibjpegJpegErrorMgrErrorExit(jpeg_common_struct *cinfo);
     446             : static void OJPEGLibjpegJpegSourceMgrInitSource(jpeg_decompress_struct *cinfo);
     447             : static boolean
     448             : OJPEGLibjpegJpegSourceMgrFillInputBuffer(jpeg_decompress_struct *cinfo);
     449             : static void
     450             : OJPEGLibjpegJpegSourceMgrSkipInputData(jpeg_decompress_struct *cinfo,
     451             :                                        long num_bytes);
     452             : static boolean
     453             : OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct *cinfo,
     454             :                                          int desired);
     455             : static void OJPEGLibjpegJpegSourceMgrTermSource(jpeg_decompress_struct *cinfo);
     456             : 
     457           2 : int TIFFInitOJPEG(TIFF *tif, int scheme)
     458             : {
     459             :     static const char module[] = "TIFFInitOJPEG";
     460             :     OJPEGState *sp;
     461             : 
     462             :     (void)scheme;
     463           2 :     assert(scheme == COMPRESSION_OJPEG);
     464             : 
     465             :     /*
     466             :      * Merge codec-specific tag information.
     467             :      */
     468           2 :     if (!_TIFFMergeFields(tif, ojpegFields, TIFFArrayCount(ojpegFields)))
     469             :     {
     470           0 :         TIFFErrorExtR(tif, module,
     471             :                       "Merging Old JPEG codec-specific tags failed");
     472           0 :         return 0;
     473             :     }
     474             : 
     475             :     /* state block */
     476           2 :     sp = (OJPEGState *)_TIFFmallocExt(tif, sizeof(OJPEGState));
     477           2 :     if (sp == NULL)
     478             :     {
     479           0 :         TIFFErrorExtR(tif, module, "No space for OJPEG state block");
     480           0 :         return (0);
     481             :     }
     482           2 :     _TIFFmemset(sp, 0, sizeof(OJPEGState));
     483           2 :     sp->tif = tif;
     484           2 :     sp->jpeg_proc = 1;
     485           2 :     sp->subsampling_hor = 2;
     486           2 :     sp->subsampling_ver = 2;
     487           2 :     TIFFSetField(tif, TIFFTAG_YCBCRSUBSAMPLING, 2, 2);
     488             :     /* tif codec methods */
     489           2 :     tif->tif_fixuptags = OJPEGFixupTags;
     490           2 :     tif->tif_setupdecode = OJPEGSetupDecode;
     491           2 :     tif->tif_predecode = OJPEGPreDecode;
     492           2 :     tif->tif_postdecode = OJPEGPostDecode;
     493           2 :     tif->tif_decoderow = OJPEGDecode;
     494           2 :     tif->tif_decodestrip = OJPEGDecode;
     495           2 :     tif->tif_decodetile = OJPEGDecode;
     496           2 :     tif->tif_setupencode = OJPEGSetupEncode;
     497           2 :     tif->tif_preencode = OJPEGPreEncode;
     498           2 :     tif->tif_postencode = OJPEGPostEncode;
     499           2 :     tif->tif_encoderow = OJPEGEncode;
     500           2 :     tif->tif_encodestrip = OJPEGEncode;
     501           2 :     tif->tif_encodetile = OJPEGEncode;
     502           2 :     tif->tif_cleanup = OJPEGCleanup;
     503           2 :     tif->tif_data = (uint8_t *)sp;
     504             :     /* tif tag methods */
     505           2 :     sp->vgetparent = tif->tif_tagmethods.vgetfield;
     506           2 :     tif->tif_tagmethods.vgetfield = OJPEGVGetField;
     507           2 :     sp->vsetparent = tif->tif_tagmethods.vsetfield;
     508           2 :     tif->tif_tagmethods.vsetfield = OJPEGVSetField;
     509           2 :     sp->printdir = tif->tif_tagmethods.printdir;
     510           2 :     tif->tif_tagmethods.printdir = OJPEGPrintDir;
     511             :     /* Some OJPEG files don't have strip or tile offsets or bytecounts tags.
     512             :        Some others do, but have totally meaningless or corrupt values
     513             :        in these tags. In these cases, the JpegInterchangeFormat stream is
     514             :        reliable. In any case, this decoder reads the compressed data itself,
     515             :        from the most reliable locations, and we need to notify encapsulating
     516             :        LibTiff not to read raw strips or tiles for us. */
     517           2 :     tif->tif_flags |= TIFF_NOREADRAW;
     518           2 :     return (1);
     519             : }
     520             : 
     521          94 : static int OJPEGVGetField(TIFF *tif, uint32_t tag, va_list ap)
     522             : {
     523          94 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
     524          94 :     switch (tag)
     525             :     {
     526           0 :         case TIFFTAG_JPEGIFOFFSET:
     527           0 :             *va_arg(ap, uint64_t *) = (uint64_t)sp->jpeg_interchange_format;
     528           0 :             break;
     529           0 :         case TIFFTAG_JPEGIFBYTECOUNT:
     530           0 :             *va_arg(ap, uint64_t *) =
     531           0 :                 (uint64_t)sp->jpeg_interchange_format_length;
     532           0 :             break;
     533           8 :         case TIFFTAG_YCBCRSUBSAMPLING:
     534           8 :             if (sp->subsamplingcorrect_done == 0)
     535           2 :                 OJPEGSubsamplingCorrect(tif);
     536           8 :             *va_arg(ap, uint16_t *) = (uint16_t)sp->subsampling_hor;
     537           8 :             *va_arg(ap, uint16_t *) = (uint16_t)sp->subsampling_ver;
     538           8 :             break;
     539           0 :         case TIFFTAG_JPEGQTABLES:
     540           0 :             *va_arg(ap, uint32_t *) = (uint32_t)sp->qtable_offset_count;
     541           0 :             *va_arg(ap, const void **) = (const void *)sp->qtable_offset;
     542           0 :             break;
     543           0 :         case TIFFTAG_JPEGDCTABLES:
     544           0 :             *va_arg(ap, uint32_t *) = (uint32_t)sp->dctable_offset_count;
     545           0 :             *va_arg(ap, const void **) = (const void *)sp->dctable_offset;
     546           0 :             break;
     547           0 :         case TIFFTAG_JPEGACTABLES:
     548           0 :             *va_arg(ap, uint32_t *) = (uint32_t)sp->actable_offset_count;
     549           0 :             *va_arg(ap, const void **) = (const void *)sp->actable_offset;
     550           0 :             break;
     551           0 :         case TIFFTAG_JPEGPROC:
     552           0 :             *va_arg(ap, uint16_t *) = (uint16_t)sp->jpeg_proc;
     553           0 :             break;
     554           0 :         case TIFFTAG_JPEGRESTARTINTERVAL:
     555           0 :             *va_arg(ap, uint16_t *) = sp->restart_interval;
     556           0 :             break;
     557          86 :         default:
     558          86 :             return (*sp->vgetparent)(tif, tag, ap);
     559             :     }
     560           8 :     return (1);
     561             : }
     562             : 
     563          34 : static int OJPEGVSetField(TIFF *tif, uint32_t tag, va_list ap)
     564             : {
     565             :     static const char module[] = "OJPEGVSetField";
     566          34 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
     567             :     uint32_t ma;
     568             :     uint64_t *mb;
     569             :     uint32_t n;
     570             :     const TIFFField *fip;
     571             : 
     572          34 :     switch (tag)
     573             :     {
     574           0 :         case TIFFTAG_JPEGIFOFFSET:
     575           0 :             sp->jpeg_interchange_format = (uint64_t)va_arg(ap, uint64_t);
     576           0 :             break;
     577           0 :         case TIFFTAG_JPEGIFBYTECOUNT:
     578           0 :             sp->jpeg_interchange_format_length = (uint64_t)va_arg(ap, uint64_t);
     579           0 :             break;
     580           2 :         case TIFFTAG_YCBCRSUBSAMPLING:
     581           2 :             sp->subsampling_tag = 1;
     582           2 :             sp->subsampling_hor = (uint8_t)va_arg(ap, uint16_vap);
     583           2 :             sp->subsampling_ver = (uint8_t)va_arg(ap, uint16_vap);
     584           2 :             tif->tif_dir.td_ycbcrsubsampling[0] = sp->subsampling_hor;
     585           2 :             tif->tif_dir.td_ycbcrsubsampling[1] = sp->subsampling_ver;
     586           2 :             break;
     587           2 :         case TIFFTAG_JPEGQTABLES:
     588           2 :             ma = (uint32_t)va_arg(ap, uint32_t);
     589           2 :             if (ma != 0)
     590             :             {
     591           2 :                 if (ma > 3)
     592             :                 {
     593           0 :                     TIFFErrorExtR(tif, module,
     594             :                                   "JpegQTables tag has incorrect count");
     595           0 :                     return (0);
     596             :                 }
     597           2 :                 sp->qtable_offset_count = (uint8_t)ma;
     598           2 :                 mb = (uint64_t *)va_arg(ap, uint64_t *);
     599           8 :                 for (n = 0; n < ma; n++)
     600           6 :                     sp->qtable_offset[n] = mb[n];
     601             :             }
     602           2 :             break;
     603           2 :         case TIFFTAG_JPEGDCTABLES:
     604           2 :             ma = (uint32_t)va_arg(ap, uint32_t);
     605           2 :             if (ma != 0)
     606             :             {
     607           2 :                 if (ma > 3)
     608             :                 {
     609           0 :                     TIFFErrorExtR(tif, module,
     610             :                                   "JpegDcTables tag has incorrect count");
     611           0 :                     return (0);
     612             :                 }
     613           2 :                 sp->dctable_offset_count = (uint8_t)ma;
     614           2 :                 mb = (uint64_t *)va_arg(ap, uint64_t *);
     615           8 :                 for (n = 0; n < ma; n++)
     616           6 :                     sp->dctable_offset[n] = mb[n];
     617             :             }
     618           2 :             break;
     619           2 :         case TIFFTAG_JPEGACTABLES:
     620           2 :             ma = (uint32_t)va_arg(ap, uint32_t);
     621           2 :             if (ma != 0)
     622             :             {
     623           2 :                 if (ma > 3)
     624             :                 {
     625           0 :                     TIFFErrorExtR(tif, module,
     626             :                                   "JpegAcTables tag has incorrect count");
     627           0 :                     return (0);
     628             :                 }
     629           2 :                 sp->actable_offset_count = (uint8_t)ma;
     630           2 :                 mb = (uint64_t *)va_arg(ap, uint64_t *);
     631           8 :                 for (n = 0; n < ma; n++)
     632           6 :                     sp->actable_offset[n] = mb[n];
     633             :             }
     634           2 :             break;
     635           2 :         case TIFFTAG_JPEGPROC:
     636           2 :             sp->jpeg_proc = (uint8_t)va_arg(ap, uint16_vap);
     637           2 :             break;
     638           0 :         case TIFFTAG_JPEGRESTARTINTERVAL:
     639           0 :             sp->restart_interval = (uint16_t)va_arg(ap, uint16_vap);
     640           0 :             break;
     641          24 :         default:
     642          24 :             return (*sp->vsetparent)(tif, tag, ap);
     643             :     }
     644          10 :     fip = TIFFFieldWithTag(tif, tag);
     645          10 :     if (fip == NULL) /* shouldn't happen */
     646           0 :         return (0);
     647          10 :     TIFFSetFieldBit(tif, fip->field_bit);
     648          10 :     tif->tif_flags |= TIFF_DIRTYDIRECT;
     649          10 :     return (1);
     650             : }
     651             : 
     652           0 : static void OJPEGPrintDir(TIFF *tif, FILE *fd, long flags)
     653             : {
     654           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
     655             :     uint8_t m;
     656             :     (void)flags;
     657           0 :     assert(sp != NULL);
     658           0 :     if (TIFFFieldSet(tif, FIELD_OJPEG_JPEGINTERCHANGEFORMAT))
     659           0 :         fprintf(fd, "  JpegInterchangeFormat: %" PRIu64 "\n",
     660           0 :                 (uint64_t)sp->jpeg_interchange_format);
     661           0 :     if (TIFFFieldSet(tif, FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH))
     662           0 :         fprintf(fd, "  JpegInterchangeFormatLength: %" PRIu64 "\n",
     663           0 :                 (uint64_t)sp->jpeg_interchange_format_length);
     664           0 :     if (TIFFFieldSet(tif, FIELD_OJPEG_JPEGQTABLES))
     665             :     {
     666           0 :         fprintf(fd, "  JpegQTables:");
     667           0 :         for (m = 0; m < sp->qtable_offset_count; m++)
     668           0 :             fprintf(fd, " %" PRIu64, (uint64_t)sp->qtable_offset[m]);
     669           0 :         fprintf(fd, "\n");
     670             :     }
     671           0 :     if (TIFFFieldSet(tif, FIELD_OJPEG_JPEGDCTABLES))
     672             :     {
     673           0 :         fprintf(fd, "  JpegDcTables:");
     674           0 :         for (m = 0; m < sp->dctable_offset_count; m++)
     675           0 :             fprintf(fd, " %" PRIu64, (uint64_t)sp->dctable_offset[m]);
     676           0 :         fprintf(fd, "\n");
     677             :     }
     678           0 :     if (TIFFFieldSet(tif, FIELD_OJPEG_JPEGACTABLES))
     679             :     {
     680           0 :         fprintf(fd, "  JpegAcTables:");
     681           0 :         for (m = 0; m < sp->actable_offset_count; m++)
     682           0 :             fprintf(fd, " %" PRIu64, (uint64_t)sp->actable_offset[m]);
     683           0 :         fprintf(fd, "\n");
     684             :     }
     685           0 :     if (TIFFFieldSet(tif, FIELD_OJPEG_JPEGPROC))
     686           0 :         fprintf(fd, "  JpegProc: %" PRIu8 "\n", sp->jpeg_proc);
     687           0 :     if (TIFFFieldSet(tif, FIELD_OJPEG_JPEGRESTARTINTERVAL))
     688           0 :         fprintf(fd, "  JpegRestartInterval: %" PRIu16 "\n",
     689           0 :                 sp->restart_interval);
     690           0 :     if (sp->printdir)
     691           0 :         (*sp->printdir)(tif, fd, flags);
     692           0 : }
     693             : 
     694           2 : static int OJPEGFixupTags(TIFF *tif)
     695             : {
     696             :     (void)tif;
     697           2 :     return (1);
     698             : }
     699             : 
     700           2 : static int OJPEGSetupDecode(TIFF *tif)
     701             : {
     702             :     static const char module[] = "OJPEGSetupDecode";
     703           2 :     TIFFWarningExtR(tif, module,
     704             :                     "Deprecated and troublesome old-style JPEG compression "
     705             :                     "mode, please convert to new-style JPEG compression and "
     706             :                     "notify vendor of writing software");
     707           2 :     return (1);
     708             : }
     709             : 
     710           2 : static int OJPEGPreDecode(TIFF *tif, uint16_t s)
     711             : {
     712           2 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
     713             :     uint32_t m;
     714           2 :     if (sp->subsamplingcorrect_done == 0)
     715           0 :         OJPEGSubsamplingCorrect(tif);
     716           2 :     if (sp->readheader_done == 0)
     717             :     {
     718           2 :         if (OJPEGReadHeaderInfo(tif) == 0)
     719           1 :             return (0);
     720             :     }
     721           1 :     if (sp->sos_end[s].log == 0)
     722             :     {
     723           0 :         if (OJPEGReadSecondarySos(tif, s) == 0)
     724           0 :             return (0);
     725             :     }
     726           1 :     if (isTiled(tif))
     727           1 :         m = tif->tif_curtile;
     728             :     else
     729           0 :         m = tif->tif_curstrip;
     730           1 :     if ((sp->writeheader_done != 0) &&
     731           0 :         ((sp->write_cursample != s) || (sp->write_curstrile > m)))
     732             :     {
     733           0 :         if (sp->libjpeg_session_active != 0)
     734           0 :             OJPEGLibjpegSessionAbort(tif);
     735           0 :         sp->writeheader_done = 0;
     736             :     }
     737           1 :     if (sp->writeheader_done == 0)
     738             :     {
     739           1 :         sp->plane_sample_offset = (uint8_t)s;
     740           1 :         sp->write_cursample = s;
     741           1 :         sp->write_curstrile = s * tif->tif_dir.td_stripsperimage;
     742           1 :         if ((sp->in_buffer_file_pos_log == 0) ||
     743           0 :             (sp->in_buffer_file_pos - sp->in_buffer_togo !=
     744           0 :              sp->sos_end[s].in_buffer_file_pos))
     745             :         {
     746           1 :             sp->in_buffer_source = sp->sos_end[s].in_buffer_source;
     747           1 :             sp->in_buffer_next_strile = sp->sos_end[s].in_buffer_next_strile;
     748           1 :             sp->in_buffer_file_pos = sp->sos_end[s].in_buffer_file_pos;
     749           1 :             sp->in_buffer_file_pos_log = 0;
     750           1 :             sp->in_buffer_file_togo = sp->sos_end[s].in_buffer_file_togo;
     751           1 :             sp->in_buffer_togo = 0;
     752           1 :             sp->in_buffer_cur = 0;
     753             :         }
     754           1 :         if (OJPEGWriteHeaderInfo(tif) == 0)
     755           0 :             return (0);
     756             :     }
     757             : 
     758           1 :     sp->subsampling_convert_state = 0;
     759             : 
     760           1 :     while (sp->write_curstrile < m)
     761             :     {
     762           0 :         if (sp->libjpeg_jpeg_query_style == 0)
     763             :         {
     764           0 :             if (OJPEGPreDecodeSkipRaw(tif) == 0)
     765           0 :                 return (0);
     766             :         }
     767             :         else
     768             :         {
     769           0 :             if (OJPEGPreDecodeSkipScanlines(tif) == 0)
     770           0 :                 return (0);
     771             :         }
     772           0 :         sp->write_curstrile++;
     773             :     }
     774           1 :     sp->decoder_ok = 1;
     775           1 :     return (1);
     776             : }
     777             : 
     778           0 : static int OJPEGPreDecodeSkipRaw(TIFF *tif)
     779             : {
     780           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
     781             :     uint32_t m;
     782           0 :     m = sp->lines_per_strile;
     783           0 :     if (sp->subsampling_convert_state != 0)
     784             :     {
     785           0 :         if (sp->subsampling_convert_clines - sp->subsampling_convert_state >= m)
     786             :         {
     787           0 :             sp->subsampling_convert_state += m;
     788           0 :             if (sp->subsampling_convert_state == sp->subsampling_convert_clines)
     789           0 :                 sp->subsampling_convert_state = 0;
     790           0 :             return (1);
     791             :         }
     792           0 :         m -= sp->subsampling_convert_clines - sp->subsampling_convert_state;
     793           0 :         sp->subsampling_convert_state = 0;
     794           0 :         sp->error_in_raw_data_decoding = 0;
     795             :     }
     796           0 :     while (m >= sp->subsampling_convert_clines)
     797             :     {
     798           0 :         if (jpeg_read_raw_data_encap(sp, &(sp->libjpeg_jpeg_decompress_struct),
     799           0 :                                      sp->subsampling_convert_ycbcrimage,
     800           0 :                                      sp->subsampling_ver * 8) == 0)
     801           0 :             return (0);
     802           0 :         m -= sp->subsampling_convert_clines;
     803             :     }
     804           0 :     if (m > 0)
     805             :     {
     806           0 :         if (jpeg_read_raw_data_encap(sp, &(sp->libjpeg_jpeg_decompress_struct),
     807           0 :                                      sp->subsampling_convert_ycbcrimage,
     808           0 :                                      sp->subsampling_ver * 8) == 0)
     809           0 :             return (0);
     810           0 :         sp->subsampling_convert_state = m;
     811             :     }
     812           0 :     return (1);
     813             : }
     814             : 
     815           0 : static int OJPEGPreDecodeSkipScanlines(TIFF *tif)
     816             : {
     817             :     static const char module[] = "OJPEGPreDecodeSkipScanlines";
     818           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
     819             :     uint32_t m;
     820           0 :     if (sp->skip_buffer == NULL)
     821             :     {
     822           0 :         sp->skip_buffer = (uint8_t *)_TIFFmallocExt(tif, sp->bytes_per_line);
     823           0 :         if (sp->skip_buffer == NULL)
     824             :         {
     825           0 :             TIFFErrorExtR(tif, module, "Out of memory");
     826           0 :             return (0);
     827             :         }
     828             :     }
     829           0 :     for (m = 0; m < sp->lines_per_strile; m++)
     830             :     {
     831           0 :         if (jpeg_read_scanlines_encap(sp, &(sp->libjpeg_jpeg_decompress_struct),
     832           0 :                                       &sp->skip_buffer, 1) == 0)
     833           0 :             return (0);
     834             :     }
     835           0 :     return (1);
     836             : }
     837             : 
     838           1 : static int OJPEGDecode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s)
     839             : {
     840             :     static const char module[] = "OJPEGDecode";
     841           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
     842             :     (void)s;
     843           1 :     if (!sp->decoder_ok)
     844             :     {
     845           0 :         memset(buf, 0, (size_t)cc);
     846           0 :         TIFFErrorExtR(tif, module,
     847             :                       "Cannot decode: decoder not correctly initialized");
     848           0 :         return 0;
     849             :     }
     850           1 :     if (sp->libjpeg_session_active == 0)
     851             :     {
     852           0 :         memset(buf, 0, (size_t)cc);
     853             :         /* This should normally not happen, except that it does when */
     854             :         /* using TIFFReadScanline() which calls OJPEGPostDecode() for */
     855             :         /* each scanline, which assumes that a whole strile was read */
     856             :         /* and may thus incorrectly consider it has read the whole image,
     857             :          * causing */
     858             :         /* OJPEGLibjpegSessionAbort() to be called prematurely. */
     859             :         /* Triggered by https://gitlab.com/libtiff/libtiff/-/issues/337 */
     860           0 :         TIFFErrorExtR(tif, module,
     861             :                       "Cannot decode: libjpeg_session_active == 0");
     862           0 :         return 0;
     863             :     }
     864           1 :     if (sp->error_in_raw_data_decoding)
     865             :     {
     866           0 :         memset(buf, 0, (size_t)cc);
     867           0 :         return 0;
     868             :     }
     869           1 :     if (sp->libjpeg_jpeg_query_style == 0)
     870             :     {
     871           1 :         if (OJPEGDecodeRaw(tif, buf, cc) == 0)
     872             :         {
     873           0 :             memset(buf, 0, (size_t)cc);
     874           0 :             return (0);
     875             :         }
     876             :     }
     877             :     else
     878             :     {
     879           0 :         if (OJPEGDecodeScanlines(tif, buf, cc) == 0)
     880             :         {
     881           0 :             memset(buf, 0, (size_t)cc);
     882           0 :             return (0);
     883             :         }
     884             :     }
     885           1 :     return (1);
     886             : }
     887             : 
     888           1 : static int OJPEGDecodeRaw(TIFF *tif, uint8_t *buf, tmsize_t cc)
     889             : {
     890             :     static const char module[] = "OJPEGDecodeRaw";
     891           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
     892             :     uint8_t *m;
     893             :     tmsize_t n;
     894             :     uint8_t *oy;
     895             :     uint8_t *ocb;
     896             :     uint8_t *ocr;
     897             :     uint8_t *p;
     898             :     uint32_t q;
     899             :     uint8_t *r;
     900             :     uint8_t sx, sy;
     901           1 :     if (cc % sp->bytes_per_line != 0)
     902             :     {
     903           0 :         TIFFErrorExtR(tif, module, "Fractional scanline not read");
     904           0 :         return (0);
     905             :     }
     906           1 :     assert(cc > 0);
     907           1 :     m = buf;
     908           1 :     n = cc;
     909             :     do
     910             :     {
     911         112 :         if (sp->subsampling_convert_state == 0)
     912             :         {
     913          14 :             if (jpeg_read_raw_data_encap(sp,
     914             :                                          &(sp->libjpeg_jpeg_decompress_struct),
     915          14 :                                          sp->subsampling_convert_ycbcrimage,
     916          14 :                                          sp->subsampling_ver * 8) == 0)
     917             :             {
     918           0 :                 sp->error_in_raw_data_decoding = 1;
     919           0 :                 return (0);
     920             :             }
     921             :         }
     922         112 :         oy = sp->subsampling_convert_ybuf +
     923         112 :              sp->subsampling_convert_state * sp->subsampling_ver *
     924         112 :                  sp->subsampling_convert_ylinelen;
     925         112 :         ocb = sp->subsampling_convert_cbbuf +
     926         112 :               sp->subsampling_convert_state * sp->subsampling_convert_clinelen;
     927         112 :         ocr = sp->subsampling_convert_crbuf +
     928         112 :               sp->subsampling_convert_state * sp->subsampling_convert_clinelen;
     929         112 :         p = m;
     930       13552 :         for (q = 0; q < sp->subsampling_convert_clinelenout; q++)
     931             :         {
     932       13440 :             r = oy;
     933       40320 :             for (sy = 0; sy < sp->subsampling_ver; sy++)
     934             :             {
     935       80640 :                 for (sx = 0; sx < sp->subsampling_hor; sx++)
     936       53760 :                     *p++ = *r++;
     937       26880 :                 r += sp->subsampling_convert_ylinelen - sp->subsampling_hor;
     938             :             }
     939       13440 :             oy += sp->subsampling_hor;
     940       13440 :             *p++ = *ocb++;
     941       13440 :             *p++ = *ocr++;
     942             :         }
     943         112 :         sp->subsampling_convert_state++;
     944         112 :         if (sp->subsampling_convert_state == sp->subsampling_convert_clines)
     945          14 :             sp->subsampling_convert_state = 0;
     946         112 :         m += sp->bytes_per_line;
     947         112 :         n -= sp->bytes_per_line;
     948         112 :     } while (n > 0);
     949           1 :     return (1);
     950             : }
     951             : 
     952           0 : static int OJPEGDecodeScanlines(TIFF *tif, uint8_t *buf, tmsize_t cc)
     953             : {
     954             :     static const char module[] = "OJPEGDecodeScanlines";
     955           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
     956             :     uint8_t *m;
     957             :     tmsize_t n;
     958           0 :     if (cc % sp->bytes_per_line != 0)
     959             :     {
     960           0 :         TIFFErrorExtR(tif, module, "Fractional scanline not read");
     961           0 :         return (0);
     962             :     }
     963           0 :     assert(cc > 0);
     964           0 :     m = buf;
     965           0 :     n = cc;
     966             :     do
     967             :     {
     968           0 :         if (jpeg_read_scanlines_encap(sp, &(sp->libjpeg_jpeg_decompress_struct),
     969             :                                       &m, 1) == 0)
     970           0 :             return (0);
     971           0 :         m += sp->bytes_per_line;
     972           0 :         n -= sp->bytes_per_line;
     973           0 :     } while (n > 0);
     974           0 :     return (1);
     975             : }
     976             : 
     977           0 : static void OJPEGPostDecode(TIFF *tif, uint8_t *buf, tmsize_t cc)
     978             : {
     979           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
     980             :     (void)buf;
     981             :     (void)cc;
     982             :     /* This function somehow incorrectly assumes that a whole strile was read,
     983             :      */
     984             :     /* which is not true when TIFFReadScanline() is called, */
     985             :     /* and may thus incorrectly consider it has read the whole image, causing */
     986             :     /* OJPEGLibjpegSessionAbort() to be called prematurely. */
     987             :     /* So this logic should be fixed to take into account cc, or disable */
     988             :     /* the scan line reading interface. */
     989             :     /* Triggered by https://gitlab.com/libtiff/libtiff/-/issues/337 */
     990           0 :     sp->write_curstrile++;
     991           0 :     if (sp->write_curstrile % tif->tif_dir.td_stripsperimage == 0)
     992             :     {
     993           0 :         assert(sp->libjpeg_session_active != 0);
     994           0 :         OJPEGLibjpegSessionAbort(tif);
     995           0 :         sp->writeheader_done = 0;
     996             :     }
     997           0 : }
     998             : 
     999           0 : static int OJPEGSetupEncode(TIFF *tif)
    1000             : {
    1001             :     static const char module[] = "OJPEGSetupEncode";
    1002           0 :     TIFFErrorExtR(
    1003             :         tif, module,
    1004             :         "OJPEG encoding not supported; use new-style JPEG compression instead");
    1005           0 :     return (0);
    1006             : }
    1007             : 
    1008           0 : static int OJPEGPreEncode(TIFF *tif, uint16_t s)
    1009             : {
    1010             :     static const char module[] = "OJPEGPreEncode";
    1011             :     (void)s;
    1012           0 :     TIFFErrorExtR(
    1013             :         tif, module,
    1014             :         "OJPEG encoding not supported; use new-style JPEG compression instead");
    1015           0 :     return (0);
    1016             : }
    1017             : 
    1018           0 : static int OJPEGEncode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s)
    1019             : {
    1020             :     static const char module[] = "OJPEGEncode";
    1021             :     (void)buf;
    1022             :     (void)cc;
    1023             :     (void)s;
    1024           0 :     TIFFErrorExtR(
    1025             :         tif, module,
    1026             :         "OJPEG encoding not supported; use new-style JPEG compression instead");
    1027           0 :     return (0);
    1028             : }
    1029             : 
    1030           0 : static int OJPEGPostEncode(TIFF *tif)
    1031             : {
    1032             :     static const char module[] = "OJPEGPostEncode";
    1033           0 :     TIFFErrorExtR(
    1034             :         tif, module,
    1035             :         "OJPEG encoding not supported; use new-style JPEG compression instead");
    1036           0 :     return (0);
    1037             : }
    1038             : 
    1039           2 : static void OJPEGCleanup(TIFF *tif)
    1040             : {
    1041           2 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1042           2 :     if (sp != 0)
    1043             :     {
    1044           2 :         tif->tif_tagmethods.vgetfield = sp->vgetparent;
    1045           2 :         tif->tif_tagmethods.vsetfield = sp->vsetparent;
    1046           2 :         tif->tif_tagmethods.printdir = sp->printdir;
    1047           2 :         if (sp->qtable[0] != 0)
    1048           1 :             _TIFFfreeExt(tif, sp->qtable[0]);
    1049           2 :         if (sp->qtable[1] != 0)
    1050           1 :             _TIFFfreeExt(tif, sp->qtable[1]);
    1051           2 :         if (sp->qtable[2] != 0)
    1052           1 :             _TIFFfreeExt(tif, sp->qtable[2]);
    1053           2 :         if (sp->qtable[3] != 0)
    1054           0 :             _TIFFfreeExt(tif, sp->qtable[3]);
    1055           2 :         if (sp->dctable[0] != 0)
    1056           1 :             _TIFFfreeExt(tif, sp->dctable[0]);
    1057           2 :         if (sp->dctable[1] != 0)
    1058           1 :             _TIFFfreeExt(tif, sp->dctable[1]);
    1059           2 :         if (sp->dctable[2] != 0)
    1060           1 :             _TIFFfreeExt(tif, sp->dctable[2]);
    1061           2 :         if (sp->dctable[3] != 0)
    1062           0 :             _TIFFfreeExt(tif, sp->dctable[3]);
    1063           2 :         if (sp->actable[0] != 0)
    1064           1 :             _TIFFfreeExt(tif, sp->actable[0]);
    1065           2 :         if (sp->actable[1] != 0)
    1066           1 :             _TIFFfreeExt(tif, sp->actable[1]);
    1067           2 :         if (sp->actable[2] != 0)
    1068           1 :             _TIFFfreeExt(tif, sp->actable[2]);
    1069           2 :         if (sp->actable[3] != 0)
    1070           0 :             _TIFFfreeExt(tif, sp->actable[3]);
    1071           2 :         if (sp->libjpeg_session_active != 0)
    1072           1 :             OJPEGLibjpegSessionAbort(tif);
    1073           2 :         if (sp->subsampling_convert_ycbcrbuf != 0)
    1074           1 :             _TIFFfreeExt(tif, sp->subsampling_convert_ycbcrbuf);
    1075           2 :         if (sp->subsampling_convert_ycbcrimage != 0)
    1076           1 :             _TIFFfreeExt(tif, sp->subsampling_convert_ycbcrimage);
    1077           2 :         if (sp->skip_buffer != 0)
    1078           0 :             _TIFFfreeExt(tif, sp->skip_buffer);
    1079           2 :         _TIFFfreeExt(tif, sp);
    1080           2 :         tif->tif_data = NULL;
    1081           2 :         _TIFFSetDefaultCompressionState(tif);
    1082             :     }
    1083           2 : }
    1084             : 
    1085           2 : static void OJPEGSubsamplingCorrect(TIFF *tif)
    1086             : {
    1087             :     static const char module[] = "OJPEGSubsamplingCorrect";
    1088           2 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1089             :     uint8_t mh;
    1090             :     uint8_t mv;
    1091             : 
    1092           2 :     assert(sp->subsamplingcorrect_done == 0);
    1093           2 :     if ((tif->tif_dir.td_samplesperpixel != 3) ||
    1094           2 :         ((tif->tif_dir.td_photometric != PHOTOMETRIC_YCBCR) &&
    1095           0 :          (tif->tif_dir.td_photometric != PHOTOMETRIC_ITULAB)))
    1096             :     {
    1097           0 :         if (sp->subsampling_tag != 0)
    1098           0 :             TIFFWarningExtR(tif, module,
    1099             :                             "Subsampling tag not appropriate for this "
    1100             :                             "Photometric and/or SamplesPerPixel");
    1101           0 :         sp->subsampling_hor = 1;
    1102           0 :         sp->subsampling_ver = 1;
    1103           0 :         sp->subsampling_force_desubsampling_inside_decompression = 0;
    1104             :     }
    1105             :     else
    1106             :     {
    1107           2 :         sp->subsamplingcorrect_done = 1;
    1108           2 :         mh = sp->subsampling_hor;
    1109           2 :         mv = sp->subsampling_ver;
    1110           2 :         sp->subsamplingcorrect = 1;
    1111           2 :         OJPEGReadHeaderInfoSec(tif);
    1112           2 :         if (sp->subsampling_force_desubsampling_inside_decompression != 0)
    1113             :         {
    1114           0 :             sp->subsampling_hor = 1;
    1115           0 :             sp->subsampling_ver = 1;
    1116             :         }
    1117           2 :         sp->subsamplingcorrect = 0;
    1118           2 :         if (((sp->subsampling_hor != mh) || (sp->subsampling_ver != mv)) &&
    1119           0 :             (sp->subsampling_force_desubsampling_inside_decompression == 0))
    1120             :         {
    1121           0 :             if (sp->subsampling_tag == 0)
    1122           0 :                 TIFFWarningExtR(
    1123             :                     tif, module,
    1124             :                     "Subsampling tag is not set, yet subsampling inside JPEG "
    1125             :                     "data [%" PRIu8 ",%" PRIu8
    1126             :                     "] does not match default values [2,2]; assuming "
    1127             :                     "subsampling inside JPEG data is correct",
    1128           0 :                     sp->subsampling_hor, sp->subsampling_ver);
    1129             :             else
    1130           0 :                 TIFFWarningExtR(
    1131             :                     tif, module,
    1132             :                     "Subsampling inside JPEG data [%" PRIu8 ",%" PRIu8
    1133             :                     "] does not match subsampling tag values [%" PRIu8
    1134             :                     ",%" PRIu8
    1135             :                     "]; assuming subsampling inside JPEG data is correct",
    1136           0 :                     sp->subsampling_hor, sp->subsampling_ver, mh, mv);
    1137             :         }
    1138           2 :         if (sp->subsampling_force_desubsampling_inside_decompression != 0)
    1139             :         {
    1140           0 :             if (sp->subsampling_tag == 0)
    1141           0 :                 TIFFWarningExtR(
    1142             :                     tif, module,
    1143             :                     "Subsampling tag is not set, yet subsampling inside JPEG "
    1144             :                     "data does not match default values [2,2] (nor any other "
    1145             :                     "values allowed in TIFF); assuming subsampling inside JPEG "
    1146             :                     "data is correct and desubsampling inside JPEG "
    1147             :                     "decompression");
    1148             :             else
    1149           0 :                 TIFFWarningExtR(
    1150             :                     tif, module,
    1151             :                     "Subsampling inside JPEG data does not match subsampling "
    1152             :                     "tag values [%" PRIu8 ",%" PRIu8
    1153             :                     "] (nor any other values allowed in TIFF); assuming "
    1154             :                     "subsampling inside JPEG data is correct and desubsampling "
    1155             :                     "inside JPEG decompression",
    1156             :                     mh, mv);
    1157             :         }
    1158           2 :         if (sp->subsampling_force_desubsampling_inside_decompression == 0)
    1159             :         {
    1160           2 :             if (sp->subsampling_hor < sp->subsampling_ver)
    1161           0 :                 TIFFWarningExtR(tif, module,
    1162             :                                 "Subsampling values [%" PRIu8 ",%" PRIu8
    1163             :                                 "] are not allowed in TIFF",
    1164           0 :                                 sp->subsampling_hor, sp->subsampling_ver);
    1165             :         }
    1166             :     }
    1167           2 :     sp->subsamplingcorrect_done = 1;
    1168           2 : }
    1169             : 
    1170           2 : static int OJPEGReadHeaderInfo(TIFF *tif)
    1171             : {
    1172             :     static const char module[] = "OJPEGReadHeaderInfo";
    1173           2 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1174           2 :     assert(sp->readheader_done == 0);
    1175           2 :     sp->image_width = tif->tif_dir.td_imagewidth;
    1176           2 :     sp->image_length = tif->tif_dir.td_imagelength;
    1177           2 :     if (isTiled(tif))
    1178             :     {
    1179           2 :         sp->strile_width = tif->tif_dir.td_tilewidth;
    1180           2 :         sp->strile_length = tif->tif_dir.td_tilelength;
    1181           2 :         sp->strile_length_total =
    1182           2 :             ((sp->image_length + sp->strile_length - 1) / sp->strile_length) *
    1183           2 :             sp->strile_length;
    1184             :     }
    1185             :     else
    1186             :     {
    1187           0 :         sp->strile_width = sp->image_width;
    1188           0 :         sp->strile_length = tif->tif_dir.td_rowsperstrip;
    1189           0 :         if (sp->strile_length == (uint32_t)-1)
    1190           0 :             sp->strile_length = sp->image_length;
    1191           0 :         sp->strile_length_total = sp->image_length;
    1192             :     }
    1193           2 :     if (tif->tif_dir.td_samplesperpixel == 1)
    1194             :     {
    1195           0 :         sp->samples_per_pixel = 1;
    1196           0 :         sp->plane_sample_offset = 0;
    1197           0 :         sp->samples_per_pixel_per_plane = sp->samples_per_pixel;
    1198           0 :         sp->subsampling_hor = 1;
    1199           0 :         sp->subsampling_ver = 1;
    1200             :     }
    1201             :     else
    1202             :     {
    1203           2 :         if (tif->tif_dir.td_samplesperpixel != 3)
    1204             :         {
    1205           0 :             TIFFErrorExtR(tif, module,
    1206             :                           "SamplesPerPixel %" PRIu8
    1207             :                           " not supported for this compression scheme",
    1208           0 :                           sp->samples_per_pixel);
    1209           0 :             return (0);
    1210             :         }
    1211           2 :         sp->samples_per_pixel = 3;
    1212           2 :         sp->plane_sample_offset = 0;
    1213           2 :         if (tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG)
    1214           2 :             sp->samples_per_pixel_per_plane = 3;
    1215             :         else
    1216           0 :             sp->samples_per_pixel_per_plane = 1;
    1217             :     }
    1218           2 :     if (sp->strile_length < sp->image_length)
    1219             :     {
    1220           0 :         if (((sp->subsampling_hor != 1) && (sp->subsampling_hor != 2) &&
    1221           0 :              (sp->subsampling_hor != 4)) ||
    1222           0 :             ((sp->subsampling_ver != 1) && (sp->subsampling_ver != 2) &&
    1223           0 :              (sp->subsampling_ver != 4)))
    1224             :         {
    1225           0 :             TIFFErrorExtR(tif, module, "Invalid subsampling values");
    1226           0 :             return (0);
    1227             :         }
    1228           0 :         if (sp->strile_length % (sp->subsampling_ver * 8) != 0)
    1229             :         {
    1230           0 :             TIFFErrorExtR(tif, module,
    1231             :                           "Incompatible vertical subsampling and image "
    1232             :                           "strip/tile length");
    1233           0 :             return (0);
    1234             :         }
    1235           0 :         sp->restart_interval =
    1236           0 :             (uint16_t)(((sp->strile_width + sp->subsampling_hor * 8 - 1) /
    1237           0 :                         (sp->subsampling_hor * 8)) *
    1238           0 :                        (sp->strile_length / (sp->subsampling_ver * 8)));
    1239             :     }
    1240           2 :     if (OJPEGReadHeaderInfoSec(tif) == 0)
    1241           1 :         return (0);
    1242           1 :     sp->sos_end[0].log = 1;
    1243           1 :     sp->sos_end[0].in_buffer_source = sp->in_buffer_source;
    1244           1 :     sp->sos_end[0].in_buffer_next_strile = sp->in_buffer_next_strile;
    1245           1 :     sp->sos_end[0].in_buffer_file_pos =
    1246           1 :         sp->in_buffer_file_pos - sp->in_buffer_togo;
    1247           1 :     sp->sos_end[0].in_buffer_file_togo =
    1248           1 :         sp->in_buffer_file_togo + sp->in_buffer_togo;
    1249           1 :     sp->readheader_done = 1;
    1250           1 :     return (1);
    1251             : }
    1252             : 
    1253           0 : static int OJPEGReadSecondarySos(TIFF *tif, uint16_t s)
    1254             : {
    1255           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1256             :     uint8_t m;
    1257           0 :     assert(s > 0);
    1258           0 :     assert(s < 3);
    1259           0 :     assert(sp->sos_end[0].log != 0);
    1260           0 :     assert(sp->sos_end[s].log == 0);
    1261           0 :     sp->plane_sample_offset = (uint8_t)(s - 1);
    1262           0 :     while (sp->sos_end[sp->plane_sample_offset].log == 0)
    1263           0 :         sp->plane_sample_offset--;
    1264           0 :     sp->in_buffer_source =
    1265           0 :         sp->sos_end[sp->plane_sample_offset].in_buffer_source;
    1266           0 :     sp->in_buffer_next_strile =
    1267           0 :         sp->sos_end[sp->plane_sample_offset].in_buffer_next_strile;
    1268           0 :     sp->in_buffer_file_pos =
    1269           0 :         sp->sos_end[sp->plane_sample_offset].in_buffer_file_pos;
    1270           0 :     sp->in_buffer_file_pos_log = 0;
    1271           0 :     sp->in_buffer_file_togo =
    1272           0 :         sp->sos_end[sp->plane_sample_offset].in_buffer_file_togo;
    1273           0 :     sp->in_buffer_togo = 0;
    1274           0 :     sp->in_buffer_cur = 0;
    1275           0 :     while (sp->plane_sample_offset < s)
    1276             :     {
    1277             :         do
    1278             :         {
    1279           0 :             if (OJPEGReadByte(sp, &m) == 0)
    1280           0 :                 return (0);
    1281           0 :             if (m == 255)
    1282             :             {
    1283             :                 do
    1284             :                 {
    1285           0 :                     if (OJPEGReadByte(sp, &m) == 0)
    1286           0 :                         return (0);
    1287           0 :                     if (m != 255)
    1288           0 :                         break;
    1289             :                 } while (1);
    1290           0 :                 if (m == JPEG_MARKER_SOS)
    1291           0 :                     break;
    1292             :             }
    1293             :         } while (1);
    1294           0 :         sp->plane_sample_offset++;
    1295           0 :         if (OJPEGReadHeaderInfoSecStreamSos(tif) == 0)
    1296           0 :             return (0);
    1297           0 :         sp->sos_end[sp->plane_sample_offset].log = 1;
    1298           0 :         sp->sos_end[sp->plane_sample_offset].in_buffer_source =
    1299           0 :             sp->in_buffer_source;
    1300           0 :         sp->sos_end[sp->plane_sample_offset].in_buffer_next_strile =
    1301           0 :             sp->in_buffer_next_strile;
    1302           0 :         sp->sos_end[sp->plane_sample_offset].in_buffer_file_pos =
    1303           0 :             sp->in_buffer_file_pos - sp->in_buffer_togo;
    1304           0 :         sp->sos_end[sp->plane_sample_offset].in_buffer_file_togo =
    1305           0 :             sp->in_buffer_file_togo + sp->in_buffer_togo;
    1306             :     }
    1307           0 :     return (1);
    1308             : }
    1309             : 
    1310           1 : static int OJPEGWriteHeaderInfo(TIFF *tif)
    1311             : {
    1312             :     static const char module[] = "OJPEGWriteHeaderInfo";
    1313           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1314             :     uint8_t **m;
    1315             :     uint32_t n;
    1316             :     /* if a previous attempt failed, don't try again */
    1317           1 :     if (sp->libjpeg_session_active != 0)
    1318           0 :         return 0;
    1319           1 :     sp->out_state = ososSoi;
    1320           1 :     sp->restart_index = 0;
    1321           1 :     jpeg_std_error(&(sp->libjpeg_jpeg_error_mgr));
    1322           1 :     sp->libjpeg_jpeg_error_mgr.output_message =
    1323             :         OJPEGLibjpegJpegErrorMgrOutputMessage;
    1324           1 :     sp->libjpeg_jpeg_error_mgr.error_exit = OJPEGLibjpegJpegErrorMgrErrorExit;
    1325           1 :     sp->libjpeg_jpeg_decompress_struct.err = &(sp->libjpeg_jpeg_error_mgr);
    1326           1 :     sp->libjpeg_jpeg_decompress_struct.client_data = (void *)tif;
    1327           1 :     if (jpeg_create_decompress_encap(
    1328             :             sp, &(sp->libjpeg_jpeg_decompress_struct)) == 0)
    1329           0 :         return (0);
    1330           1 :     sp->libjpeg_session_active = 1;
    1331           1 :     sp->libjpeg_jpeg_source_mgr.bytes_in_buffer = 0;
    1332           1 :     sp->libjpeg_jpeg_source_mgr.init_source =
    1333             :         OJPEGLibjpegJpegSourceMgrInitSource;
    1334           1 :     sp->libjpeg_jpeg_source_mgr.fill_input_buffer =
    1335             :         OJPEGLibjpegJpegSourceMgrFillInputBuffer;
    1336           1 :     sp->libjpeg_jpeg_source_mgr.skip_input_data =
    1337             :         OJPEGLibjpegJpegSourceMgrSkipInputData;
    1338           1 :     sp->libjpeg_jpeg_source_mgr.resync_to_restart =
    1339             :         OJPEGLibjpegJpegSourceMgrResyncToRestart;
    1340           1 :     sp->libjpeg_jpeg_source_mgr.term_source =
    1341             :         OJPEGLibjpegJpegSourceMgrTermSource;
    1342           1 :     sp->libjpeg_jpeg_decompress_struct.src = &(sp->libjpeg_jpeg_source_mgr);
    1343           1 :     if (jpeg_read_header_encap(sp, &(sp->libjpeg_jpeg_decompress_struct), 1) ==
    1344             :         0)
    1345           0 :         return (0);
    1346           1 :     if ((sp->subsampling_force_desubsampling_inside_decompression == 0) &&
    1347           1 :         (sp->samples_per_pixel_per_plane > 1))
    1348             :     {
    1349           1 :         sp->libjpeg_jpeg_decompress_struct.raw_data_out = 1;
    1350             : #if JPEG_LIB_VERSION >= 70
    1351           1 :         sp->libjpeg_jpeg_decompress_struct.do_fancy_upsampling = FALSE;
    1352             : #endif
    1353           1 :         sp->libjpeg_jpeg_query_style = 0;
    1354           1 :         if (sp->subsampling_convert_log == 0)
    1355             :         {
    1356           1 :             assert(sp->subsampling_convert_ycbcrbuf == 0);
    1357           1 :             assert(sp->subsampling_convert_ycbcrimage == 0);
    1358             :             /* Check for division by zero. */
    1359           1 :             if (sp->subsampling_hor == 0 || sp->subsampling_ver == 0)
    1360           0 :                 return (0);
    1361             :             /* Check for potential overflow in subsampling_convert_ylinelen
    1362             :              * computation.
    1363             :              */
    1364           1 :             if (sp->strile_width > UINT32_MAX - (sp->subsampling_hor * 8 - 1))
    1365           0 :                 return (0);
    1366           1 :             sp->subsampling_convert_ylinelen =
    1367           1 :                 ((sp->strile_width + sp->subsampling_hor * 8 - 1) /
    1368           1 :                  (sp->subsampling_hor * 8) * sp->subsampling_hor * 8);
    1369           1 :             sp->subsampling_convert_ylines = sp->subsampling_ver * 8;
    1370           1 :             sp->subsampling_convert_clinelen =
    1371           1 :                 sp->subsampling_convert_ylinelen / sp->subsampling_hor;
    1372           1 :             sp->subsampling_convert_clines = 8;
    1373           1 :             sp->subsampling_convert_ybuflen = sp->subsampling_convert_ylinelen *
    1374           1 :                                               sp->subsampling_convert_ylines;
    1375           1 :             sp->subsampling_convert_cbuflen = sp->subsampling_convert_clinelen *
    1376           1 :                                               sp->subsampling_convert_clines;
    1377           1 :             sp->subsampling_convert_ycbcrbuflen =
    1378           1 :                 sp->subsampling_convert_ybuflen +
    1379           1 :                 2 * sp->subsampling_convert_cbuflen;
    1380             :             /* The calloc is not normally necessary, except in some edge/broken
    1381             :              * cases */
    1382             :             /* for example for a tiled image of height 1 with a tile height of 1
    1383             :              * and subsampling_hor=subsampling_ver=2 */
    1384             :             /* In that case, libjpeg will only fill the 8 first lines of the 16
    1385             :              * lines */
    1386             :             /* See https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=16844
    1387             :              */
    1388             :             /* Even if this case is allowed (?), its handling is broken because
    1389             :              * OJPEGPreDecode() should also likely */
    1390             :             /* reset subsampling_convert_state to 0 when changing tile. */
    1391           2 :             sp->subsampling_convert_ycbcrbuf = (uint8_t *)_TIFFcallocExt(
    1392           1 :                 tif, 1, sp->subsampling_convert_ycbcrbuflen);
    1393           1 :             if (sp->subsampling_convert_ycbcrbuf == 0)
    1394             :             {
    1395           0 :                 TIFFErrorExtR(tif, module, "Out of memory");
    1396           0 :                 return (0);
    1397             :             }
    1398           1 :             sp->subsampling_convert_ybuf = sp->subsampling_convert_ycbcrbuf;
    1399           1 :             sp->subsampling_convert_cbbuf =
    1400           1 :                 sp->subsampling_convert_ybuf + sp->subsampling_convert_ybuflen;
    1401           1 :             sp->subsampling_convert_crbuf =
    1402           1 :                 sp->subsampling_convert_cbbuf + sp->subsampling_convert_cbuflen;
    1403           1 :             sp->subsampling_convert_ycbcrimagelen =
    1404           1 :                 3 + sp->subsampling_convert_ylines +
    1405           1 :                 2 * sp->subsampling_convert_clines;
    1406           2 :             sp->subsampling_convert_ycbcrimage = (uint8_t **)_TIFFmallocExt(
    1407           1 :                 tif, sp->subsampling_convert_ycbcrimagelen * sizeof(uint8_t *));
    1408           1 :             if (sp->subsampling_convert_ycbcrimage == 0)
    1409             :             {
    1410           0 :                 TIFFErrorExtR(tif, module, "Out of memory");
    1411           0 :                 return (0);
    1412             :             }
    1413           1 :             m = sp->subsampling_convert_ycbcrimage;
    1414           1 :             *m++ = (uint8_t *)(sp->subsampling_convert_ycbcrimage + 3);
    1415           1 :             *m++ = (uint8_t *)(sp->subsampling_convert_ycbcrimage + 3 +
    1416           1 :                                sp->subsampling_convert_ylines);
    1417           1 :             *m++ = (uint8_t *)(sp->subsampling_convert_ycbcrimage + 3 +
    1418           1 :                                sp->subsampling_convert_ylines +
    1419           1 :                                sp->subsampling_convert_clines);
    1420          17 :             for (n = 0; n < sp->subsampling_convert_ylines; n++)
    1421          16 :                 *m++ = sp->subsampling_convert_ybuf +
    1422          16 :                        n * sp->subsampling_convert_ylinelen;
    1423           9 :             for (n = 0; n < sp->subsampling_convert_clines; n++)
    1424           8 :                 *m++ = sp->subsampling_convert_cbbuf +
    1425           8 :                        n * sp->subsampling_convert_clinelen;
    1426           9 :             for (n = 0; n < sp->subsampling_convert_clines; n++)
    1427           8 :                 *m++ = sp->subsampling_convert_crbuf +
    1428           8 :                        n * sp->subsampling_convert_clinelen;
    1429           1 :             sp->subsampling_convert_clinelenout =
    1430           2 :                 sp->strile_width / sp->subsampling_hor +
    1431           1 :                 ((sp->strile_width % sp->subsampling_hor) != 0 ? 1 : 0);
    1432           1 :             sp->subsampling_convert_state = 0;
    1433           1 :             sp->error_in_raw_data_decoding = 0;
    1434             : 
    1435           1 :             const uint64_t bpl =
    1436           1 :                 (uint64_t)sp->subsampling_convert_clinelenout *
    1437           1 :                 (sp->subsampling_ver * sp->subsampling_hor + 2);
    1438           1 :             if (bpl > UINT32_MAX)
    1439           0 :                 return (0);
    1440           1 :             sp->bytes_per_line = (uint32_t)bpl;
    1441             : 
    1442           1 :             sp->lines_per_strile =
    1443           2 :                 sp->strile_length / sp->subsampling_ver +
    1444           1 :                 ((sp->strile_length % sp->subsampling_ver) != 0 ? 1 : 0);
    1445           1 :             sp->subsampling_convert_log = 1;
    1446             :         }
    1447             :     }
    1448             :     else
    1449             :     {
    1450           0 :         sp->libjpeg_jpeg_decompress_struct.jpeg_color_space = JCS_UNKNOWN;
    1451           0 :         sp->libjpeg_jpeg_decompress_struct.out_color_space = JCS_UNKNOWN;
    1452           0 :         sp->libjpeg_jpeg_query_style = 1;
    1453           0 :         sp->bytes_per_line = sp->samples_per_pixel_per_plane * sp->strile_width;
    1454           0 :         sp->lines_per_strile = sp->strile_length;
    1455             :     }
    1456           1 :     if (jpeg_start_decompress_encap(sp,
    1457             :                                     &(sp->libjpeg_jpeg_decompress_struct)) == 0)
    1458           0 :         return (0);
    1459           1 :     if (sp->libjpeg_jpeg_decompress_struct.image_width != sp->strile_width)
    1460             :     {
    1461           0 :         TIFFErrorExtR(tif, module,
    1462             :                       "jpeg_start_decompress() returned image_width = %u, "
    1463             :                       "expected %" PRIu32,
    1464             :                       sp->libjpeg_jpeg_decompress_struct.image_width,
    1465             :                       sp->strile_width);
    1466           0 :         return 0;
    1467             :     }
    1468           1 :     if (sp->libjpeg_jpeg_decompress_struct.max_h_samp_factor !=
    1469           1 :             sp->subsampling_hor ||
    1470           1 :         sp->libjpeg_jpeg_decompress_struct.max_v_samp_factor !=
    1471           1 :             sp->subsampling_ver)
    1472             :     {
    1473           0 :         TIFFErrorExtR(tif, module,
    1474             :                       "jpeg_start_decompress() returned max_h_samp_factor = %d "
    1475             :                       "and max_v_samp_factor = %d, expected %" PRIu8
    1476             :                       " and %" PRIu8,
    1477             :                       sp->libjpeg_jpeg_decompress_struct.max_h_samp_factor,
    1478             :                       sp->libjpeg_jpeg_decompress_struct.max_v_samp_factor,
    1479           0 :                       sp->subsampling_hor, sp->subsampling_ver);
    1480           0 :         return 0;
    1481             :     }
    1482             : 
    1483           1 :     sp->writeheader_done = 1;
    1484           1 :     return (1);
    1485             : }
    1486             : 
    1487           1 : static void OJPEGLibjpegSessionAbort(TIFF *tif)
    1488             : {
    1489           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1490           1 :     assert(sp->libjpeg_session_active != 0);
    1491           1 :     jpeg_destroy((jpeg_common_struct *)(&(sp->libjpeg_jpeg_decompress_struct)));
    1492           1 :     sp->libjpeg_session_active = 0;
    1493           1 : }
    1494             : 
    1495           4 : static int OJPEGReadHeaderInfoSec(TIFF *tif)
    1496             : {
    1497             :     static const char module[] = "OJPEGReadHeaderInfoSec";
    1498           4 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1499             :     uint8_t m;
    1500             :     uint16_t n;
    1501             :     uint8_t o;
    1502           4 :     if (sp->file_size == 0)
    1503           2 :         sp->file_size = TIFFGetFileSize(tif);
    1504           4 :     if (sp->jpeg_interchange_format != 0)
    1505             :     {
    1506           0 :         if (sp->jpeg_interchange_format >= sp->file_size)
    1507             :         {
    1508           0 :             sp->jpeg_interchange_format = 0;
    1509           0 :             sp->jpeg_interchange_format_length = 0;
    1510             :         }
    1511             :         else
    1512             :         {
    1513           0 :             if ((sp->jpeg_interchange_format_length == 0) ||
    1514           0 :                 (sp->jpeg_interchange_format >
    1515           0 :                  UINT64_MAX - sp->jpeg_interchange_format_length) ||
    1516           0 :                 (sp->jpeg_interchange_format +
    1517           0 :                      sp->jpeg_interchange_format_length >
    1518           0 :                  sp->file_size))
    1519           0 :                 sp->jpeg_interchange_format_length =
    1520           0 :                     sp->file_size - sp->jpeg_interchange_format;
    1521             :         }
    1522             :     }
    1523           4 :     sp->in_buffer_source = osibsNotSetYet;
    1524           4 :     sp->in_buffer_next_strile = 0;
    1525           4 :     sp->in_buffer_strile_count = tif->tif_dir.td_nstrips;
    1526           4 :     sp->in_buffer_file_togo = 0;
    1527           4 :     sp->in_buffer_togo = 0;
    1528             :     do
    1529             :     {
    1530           4 :         if (OJPEGReadBytePeek(sp, &m) == 0)
    1531           2 :             return (0);
    1532           2 :         if (m != 255)
    1533           2 :             break;
    1534           0 :         OJPEGReadByteAdvance(sp);
    1535             :         do
    1536             :         {
    1537           0 :             if (OJPEGReadByte(sp, &m) == 0)
    1538           0 :                 return (0);
    1539           0 :         } while (m == 255);
    1540           0 :         switch (m)
    1541             :         {
    1542           0 :             case JPEG_MARKER_SOI:
    1543             :                 /* this type of marker has no data, and should be skipped */
    1544           0 :                 break;
    1545           0 :             case JPEG_MARKER_COM:
    1546             :             case JPEG_MARKER_APP0:
    1547             :             case JPEG_MARKER_APP0 + 1:
    1548             :             case JPEG_MARKER_APP0 + 2:
    1549             :             case JPEG_MARKER_APP0 + 3:
    1550             :             case JPEG_MARKER_APP0 + 4:
    1551             :             case JPEG_MARKER_APP0 + 5:
    1552             :             case JPEG_MARKER_APP0 + 6:
    1553             :             case JPEG_MARKER_APP0 + 7:
    1554             :             case JPEG_MARKER_APP0 + 8:
    1555             :             case JPEG_MARKER_APP0 + 9:
    1556             :             case JPEG_MARKER_APP0 + 10:
    1557             :             case JPEG_MARKER_APP0 + 11:
    1558             :             case JPEG_MARKER_APP0 + 12:
    1559             :             case JPEG_MARKER_APP0 + 13:
    1560             :             case JPEG_MARKER_APP0 + 14:
    1561             :             case JPEG_MARKER_APP0 + 15:
    1562             :                 /* this type of marker has data, but it has no use to us (and no
    1563             :                  * place here) and should be skipped */
    1564           0 :                 if (OJPEGReadWord(sp, &n) == 0)
    1565           0 :                     return (0);
    1566           0 :                 if (n < 2)
    1567             :                 {
    1568           0 :                     if (sp->subsamplingcorrect == 0)
    1569           0 :                         TIFFErrorExtR(tif, module, "Corrupt JPEG data");
    1570           0 :                     return (0);
    1571             :                 }
    1572           0 :                 if (n > 2)
    1573           0 :                     OJPEGReadSkip(sp, n - 2);
    1574           0 :                 break;
    1575           0 :             case JPEG_MARKER_DRI:
    1576           0 :                 if (OJPEGReadHeaderInfoSecStreamDri(tif) == 0)
    1577           0 :                     return (0);
    1578           0 :                 break;
    1579           0 :             case JPEG_MARKER_DQT:
    1580           0 :                 if (OJPEGReadHeaderInfoSecStreamDqt(tif) == 0)
    1581           0 :                     return (0);
    1582           0 :                 break;
    1583           0 :             case JPEG_MARKER_DHT:
    1584           0 :                 if (OJPEGReadHeaderInfoSecStreamDht(tif) == 0)
    1585           0 :                     return (0);
    1586           0 :                 break;
    1587           0 :             case JPEG_MARKER_SOF0:
    1588             :             case JPEG_MARKER_SOF1:
    1589             :             case JPEG_MARKER_SOF3:
    1590           0 :                 if (OJPEGReadHeaderInfoSecStreamSof(tif, m) == 0)
    1591           0 :                     return (0);
    1592           0 :                 if (sp->subsamplingcorrect != 0)
    1593           0 :                     return (1);
    1594           0 :                 break;
    1595           0 :             case JPEG_MARKER_SOS:
    1596           0 :                 if (sp->subsamplingcorrect != 0)
    1597           0 :                     return (1);
    1598           0 :                 assert(sp->plane_sample_offset == 0);
    1599           0 :                 if (OJPEGReadHeaderInfoSecStreamSos(tif) == 0)
    1600           0 :                     return (0);
    1601           0 :                 break;
    1602           0 :             default:
    1603           0 :                 TIFFErrorExtR(tif, module,
    1604             :                               "Unknown marker type %" PRIu8 " in JPEG data", m);
    1605           0 :                 return (0);
    1606             :         }
    1607           0 :     } while (m != JPEG_MARKER_SOS);
    1608           2 :     if (sp->subsamplingcorrect)
    1609           1 :         return (1);
    1610           1 :     if (sp->sof_log == 0)
    1611             :     {
    1612           1 :         if (OJPEGReadHeaderInfoSecTablesQTable(tif) == 0)
    1613           0 :             return (0);
    1614           1 :         sp->sof_marker_id = JPEG_MARKER_SOF0;
    1615           4 :         for (o = 0; o < sp->samples_per_pixel; o++)
    1616           3 :             sp->sof_c[o] = o;
    1617           1 :         sp->sof_hv[0] = ((sp->subsampling_hor << 4) | sp->subsampling_ver);
    1618           3 :         for (o = 1; o < sp->samples_per_pixel; o++)
    1619           2 :             sp->sof_hv[o] = 17;
    1620           1 :         sp->sof_x = sp->strile_width;
    1621           1 :         sp->sof_y = sp->strile_length_total;
    1622           1 :         sp->sof_log = 1;
    1623           1 :         if (OJPEGReadHeaderInfoSecTablesDcTable(tif) == 0)
    1624           0 :             return (0);
    1625           1 :         if (OJPEGReadHeaderInfoSecTablesAcTable(tif) == 0)
    1626           0 :             return (0);
    1627           3 :         for (o = 1; o < sp->samples_per_pixel; o++)
    1628           2 :             sp->sos_cs[o] = o;
    1629             :     }
    1630           1 :     return (1);
    1631             : }
    1632             : 
    1633           0 : static int OJPEGReadHeaderInfoSecStreamDri(TIFF *tif)
    1634             : {
    1635             :     /* This could easily cause trouble in some cases... but no such cases have
    1636             :        occurred so far */
    1637             :     static const char module[] = "OJPEGReadHeaderInfoSecStreamDri";
    1638           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1639             :     uint16_t m;
    1640           0 :     if (OJPEGReadWord(sp, &m) == 0)
    1641           0 :         return (0);
    1642           0 :     if (m != 4)
    1643             :     {
    1644           0 :         TIFFErrorExtR(tif, module, "Corrupt DRI marker in JPEG data");
    1645           0 :         return (0);
    1646             :     }
    1647           0 :     if (OJPEGReadWord(sp, &m) == 0)
    1648           0 :         return (0);
    1649           0 :     sp->restart_interval = m;
    1650           0 :     return (1);
    1651             : }
    1652             : 
    1653           0 : static int OJPEGReadHeaderInfoSecStreamDqt(TIFF *tif)
    1654             : {
    1655             :     /* this is a table marker, and it is to be saved as a whole for exact
    1656             :      * pushing on the jpeg stream later on */
    1657             :     static const char module[] = "OJPEGReadHeaderInfoSecStreamDqt";
    1658           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1659             :     uint16_t m;
    1660             :     uint32_t na;
    1661             :     uint8_t *nb;
    1662             :     uint8_t o;
    1663           0 :     if (OJPEGReadWord(sp, &m) == 0)
    1664           0 :         return (0);
    1665           0 :     if (m <= 2)
    1666             :     {
    1667           0 :         if (sp->subsamplingcorrect == 0)
    1668           0 :             TIFFErrorExtR(tif, module, "Corrupt DQT marker in JPEG data");
    1669           0 :         return (0);
    1670             :     }
    1671           0 :     if (sp->subsamplingcorrect != 0)
    1672           0 :         OJPEGReadSkip(sp, m - 2);
    1673             :     else
    1674             :     {
    1675           0 :         m -= 2;
    1676             :         do
    1677             :         {
    1678           0 :             if (m < 65)
    1679             :             {
    1680           0 :                 TIFFErrorExtR(tif, module, "Corrupt DQT marker in JPEG data");
    1681           0 :                 return (0);
    1682             :             }
    1683           0 :             na = sizeof(uint32_t) + 69;
    1684           0 :             nb = (uint8_t *)_TIFFmallocExt(tif, na);
    1685           0 :             if (nb == 0)
    1686             :             {
    1687           0 :                 TIFFErrorExtR(tif, module, "Out of memory");
    1688           0 :                 return (0);
    1689             :             }
    1690           0 :             *(uint32_t *)nb = na;
    1691           0 :             nb[sizeof(uint32_t)] = 255;
    1692           0 :             nb[sizeof(uint32_t) + 1] = JPEG_MARKER_DQT;
    1693           0 :             nb[sizeof(uint32_t) + 2] = 0;
    1694           0 :             nb[sizeof(uint32_t) + 3] = 67;
    1695           0 :             if (OJPEGReadBlock(sp, 65, &nb[sizeof(uint32_t) + 4]) == 0)
    1696             :             {
    1697           0 :                 _TIFFfreeExt(tif, nb);
    1698           0 :                 return (0);
    1699             :             }
    1700           0 :             o = nb[sizeof(uint32_t) + 4] & 15;
    1701           0 :             if (3 < o)
    1702             :             {
    1703           0 :                 TIFFErrorExtR(tif, module, "Corrupt DQT marker in JPEG data");
    1704           0 :                 _TIFFfreeExt(tif, nb);
    1705           0 :                 return (0);
    1706             :             }
    1707           0 :             if (sp->qtable[o] != 0)
    1708           0 :                 _TIFFfreeExt(tif, sp->qtable[o]);
    1709           0 :             sp->qtable[o] = nb;
    1710           0 :             m -= 65;
    1711           0 :         } while (m > 0);
    1712             :     }
    1713           0 :     return (1);
    1714             : }
    1715             : 
    1716           0 : static int OJPEGReadHeaderInfoSecStreamDht(TIFF *tif)
    1717             : {
    1718             :     /* this is a table marker, and it is to be saved as a whole for exact
    1719             :      * pushing on the jpeg stream later on */
    1720             :     /* TODO: the following assumes there is only one table in this marker... but
    1721             :      * i'm not quite sure that assumption is guaranteed correct */
    1722             :     static const char module[] = "OJPEGReadHeaderInfoSecStreamDht";
    1723           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1724             :     uint16_t m;
    1725             :     uint32_t na;
    1726             :     uint8_t *nb;
    1727             :     uint8_t o;
    1728           0 :     if (OJPEGReadWord(sp, &m) == 0)
    1729           0 :         return (0);
    1730           0 :     if (m <= 2)
    1731             :     {
    1732           0 :         if (sp->subsamplingcorrect == 0)
    1733           0 :             TIFFErrorExtR(tif, module, "Corrupt DHT marker in JPEG data");
    1734           0 :         return (0);
    1735             :     }
    1736           0 :     if (sp->subsamplingcorrect != 0)
    1737             :     {
    1738           0 :         OJPEGReadSkip(sp, m - 2);
    1739             :     }
    1740             :     else
    1741             :     {
    1742           0 :         na = sizeof(uint32_t) + 2 + m;
    1743           0 :         nb = (uint8_t *)_TIFFmallocExt(tif, na);
    1744           0 :         if (nb == 0)
    1745             :         {
    1746           0 :             TIFFErrorExtR(tif, module, "Out of memory");
    1747           0 :             return (0);
    1748             :         }
    1749           0 :         *(uint32_t *)nb = na;
    1750           0 :         nb[sizeof(uint32_t)] = 255;
    1751           0 :         nb[sizeof(uint32_t) + 1] = JPEG_MARKER_DHT;
    1752           0 :         nb[sizeof(uint32_t) + 2] = (m >> 8);
    1753           0 :         nb[sizeof(uint32_t) + 3] = (m & 255);
    1754           0 :         if (OJPEGReadBlock(sp, m - 2, &nb[sizeof(uint32_t) + 4]) == 0)
    1755             :         {
    1756           0 :             _TIFFfreeExt(tif, nb);
    1757           0 :             return (0);
    1758             :         }
    1759           0 :         o = nb[sizeof(uint32_t) + 4];
    1760           0 :         if ((o & 240) == 0)
    1761             :         {
    1762           0 :             if (3 < o)
    1763             :             {
    1764           0 :                 TIFFErrorExtR(tif, module, "Corrupt DHT marker in JPEG data");
    1765           0 :                 _TIFFfreeExt(tif, nb);
    1766           0 :                 return (0);
    1767             :             }
    1768           0 :             if (sp->dctable[o] != 0)
    1769           0 :                 _TIFFfreeExt(tif, sp->dctable[o]);
    1770           0 :             sp->dctable[o] = nb;
    1771             :         }
    1772             :         else
    1773             :         {
    1774           0 :             if ((o & 240) != 16)
    1775             :             {
    1776           0 :                 TIFFErrorExtR(tif, module, "Corrupt DHT marker in JPEG data");
    1777           0 :                 _TIFFfreeExt(tif, nb);
    1778           0 :                 return (0);
    1779             :             }
    1780           0 :             o &= 15;
    1781           0 :             if (3 < o)
    1782             :             {
    1783           0 :                 TIFFErrorExtR(tif, module, "Corrupt DHT marker in JPEG data");
    1784           0 :                 _TIFFfreeExt(tif, nb);
    1785           0 :                 return (0);
    1786             :             }
    1787           0 :             if (sp->actable[o] != 0)
    1788           0 :                 _TIFFfreeExt(tif, sp->actable[o]);
    1789           0 :             sp->actable[o] = nb;
    1790             :         }
    1791             :     }
    1792           0 :     return (1);
    1793             : }
    1794             : 
    1795           0 : static int OJPEGReadHeaderInfoSecStreamSof(TIFF *tif, uint8_t marker_id)
    1796             : {
    1797             :     /* this marker needs to be checked, and part of its data needs to be saved
    1798             :      * for regeneration later on */
    1799             :     static const char module[] = "OJPEGReadHeaderInfoSecStreamSof";
    1800           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1801             :     uint16_t m;
    1802             :     uint16_t n;
    1803             :     uint8_t o;
    1804             :     uint16_t p;
    1805             :     uint16_t q;
    1806           0 :     if (sp->sof_log != 0)
    1807             :     {
    1808           0 :         TIFFErrorExtR(tif, module, "Corrupt JPEG data");
    1809           0 :         return (0);
    1810             :     }
    1811           0 :     if (sp->subsamplingcorrect == 0)
    1812           0 :         sp->sof_marker_id = marker_id;
    1813             :     /* Lf: data length */
    1814           0 :     if (OJPEGReadWord(sp, &m) == 0)
    1815           0 :         return (0);
    1816           0 :     if (m < 11)
    1817             :     {
    1818           0 :         if (sp->subsamplingcorrect == 0)
    1819           0 :             TIFFErrorExtR(tif, module, "Corrupt SOF marker in JPEG data");
    1820           0 :         return (0);
    1821             :     }
    1822           0 :     m -= 8;
    1823           0 :     if (m % 3 != 0)
    1824             :     {
    1825           0 :         if (sp->subsamplingcorrect == 0)
    1826           0 :             TIFFErrorExtR(tif, module, "Corrupt SOF marker in JPEG data");
    1827           0 :         return (0);
    1828             :     }
    1829           0 :     n = m / 3;
    1830           0 :     if (sp->subsamplingcorrect == 0)
    1831             :     {
    1832           0 :         if (n != sp->samples_per_pixel)
    1833             :         {
    1834           0 :             TIFFErrorExtR(
    1835             :                 tif, module,
    1836             :                 "JPEG compressed data indicates unexpected number of samples");
    1837           0 :             return (0);
    1838             :         }
    1839             :     }
    1840             :     /* P: Sample precision */
    1841           0 :     if (OJPEGReadByte(sp, &o) == 0)
    1842           0 :         return (0);
    1843           0 :     if (o != 8)
    1844             :     {
    1845           0 :         if (sp->subsamplingcorrect == 0)
    1846           0 :             TIFFErrorExtR(tif, module,
    1847             :                           "JPEG compressed data indicates unexpected number of "
    1848             :                           "bits per sample");
    1849           0 :         return (0);
    1850             :     }
    1851             :     /* Y: Number of lines, X: Number of samples per line */
    1852           0 :     if (sp->subsamplingcorrect)
    1853           0 :         OJPEGReadSkip(sp, 4);
    1854             :     else
    1855             :     {
    1856             :         /* Y: Number of lines */
    1857           0 :         if (OJPEGReadWord(sp, &p) == 0)
    1858           0 :             return (0);
    1859           0 :         if (((uint32_t)p < sp->image_length) &&
    1860           0 :             ((uint32_t)p < sp->strile_length_total))
    1861             :         {
    1862           0 :             TIFFErrorExtR(tif, module,
    1863             :                           "JPEG compressed data indicates unexpected height");
    1864           0 :             return (0);
    1865             :         }
    1866           0 :         sp->sof_y = p;
    1867             :         /* X: Number of samples per line */
    1868           0 :         if (OJPEGReadWord(sp, &p) == 0)
    1869           0 :             return (0);
    1870           0 :         if (((uint32_t)p < sp->image_width) && ((uint32_t)p < sp->strile_width))
    1871             :         {
    1872           0 :             TIFFErrorExtR(tif, module,
    1873             :                           "JPEG compressed data indicates unexpected width");
    1874           0 :             return (0);
    1875             :         }
    1876           0 :         if ((uint32_t)p > sp->strile_width)
    1877             :         {
    1878           0 :             TIFFErrorExtR(tif, module,
    1879             :                           "JPEG compressed data image width exceeds expected "
    1880             :                           "image width");
    1881           0 :             return (0);
    1882             :         }
    1883           0 :         sp->sof_x = p;
    1884             :     }
    1885             :     /* Nf: Number of image components in frame */
    1886           0 :     if (OJPEGReadByte(sp, &o) == 0)
    1887           0 :         return (0);
    1888           0 :     if (o != n)
    1889             :     {
    1890           0 :         if (sp->subsamplingcorrect == 0)
    1891           0 :             TIFFErrorExtR(tif, module, "Corrupt SOF marker in JPEG data");
    1892           0 :         return (0);
    1893             :     }
    1894             :     /* per component stuff */
    1895             :     /* TODO: double-check that flow implies that n cannot be as big as to make
    1896             :      * us overflow sof_c, sof_hv and sof_tq arrays */
    1897           0 :     for (q = 0; q < n; q++)
    1898             :     {
    1899             :         /* C: Component identifier */
    1900           0 :         if (OJPEGReadByte(sp, &o) == 0)
    1901           0 :             return (0);
    1902           0 :         if (sp->subsamplingcorrect == 0)
    1903           0 :             sp->sof_c[q] = o;
    1904             :         /* H: Horizontal sampling factor, and V: Vertical sampling factor */
    1905           0 :         if (OJPEGReadByte(sp, &o) == 0)
    1906           0 :             return (0);
    1907           0 :         if (sp->subsamplingcorrect != 0)
    1908             :         {
    1909           0 :             if (q == 0)
    1910             :             {
    1911           0 :                 sp->subsampling_hor = (o >> 4);
    1912           0 :                 sp->subsampling_ver = (o & 15);
    1913           0 :                 if (((sp->subsampling_hor != 1) && (sp->subsampling_hor != 2) &&
    1914           0 :                      (sp->subsampling_hor != 4)) ||
    1915           0 :                     ((sp->subsampling_ver != 1) && (sp->subsampling_ver != 2) &&
    1916           0 :                      (sp->subsampling_ver != 4)))
    1917           0 :                     sp->subsampling_force_desubsampling_inside_decompression =
    1918             :                         1;
    1919             :             }
    1920             :             else
    1921             :             {
    1922           0 :                 if (o != 17)
    1923           0 :                     sp->subsampling_force_desubsampling_inside_decompression =
    1924             :                         1;
    1925             :             }
    1926             :         }
    1927             :         else
    1928             :         {
    1929           0 :             sp->sof_hv[q] = o;
    1930           0 :             if (sp->subsampling_force_desubsampling_inside_decompression == 0)
    1931             :             {
    1932           0 :                 if (q == 0)
    1933             :                 {
    1934           0 :                     if (o != ((sp->subsampling_hor << 4) | sp->subsampling_ver))
    1935             :                     {
    1936           0 :                         TIFFErrorExtR(tif, module,
    1937             :                                       "JPEG compressed data indicates "
    1938             :                                       "unexpected subsampling values");
    1939           0 :                         return (0);
    1940             :                     }
    1941             :                 }
    1942             :                 else
    1943             :                 {
    1944           0 :                     if (o != 17)
    1945             :                     {
    1946           0 :                         TIFFErrorExtR(tif, module,
    1947             :                                       "JPEG compressed data indicates "
    1948             :                                       "unexpected subsampling values");
    1949           0 :                         return (0);
    1950             :                     }
    1951             :                 }
    1952             :             }
    1953             :         }
    1954             :         /* Tq: Quantization table destination selector */
    1955           0 :         if (OJPEGReadByte(sp, &o) == 0)
    1956           0 :             return (0);
    1957           0 :         if (sp->subsamplingcorrect == 0)
    1958           0 :             sp->sof_tq[q] = o;
    1959             :     }
    1960           0 :     if (sp->subsamplingcorrect == 0)
    1961           0 :         sp->sof_log = 1;
    1962           0 :     return (1);
    1963             : }
    1964             : 
    1965           0 : static int OJPEGReadHeaderInfoSecStreamSos(TIFF *tif)
    1966             : {
    1967             :     /* this marker needs to be checked, and part of its data needs to be saved
    1968             :      * for regeneration later on */
    1969             :     static const char module[] = "OJPEGReadHeaderInfoSecStreamSos";
    1970           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    1971             :     uint16_t m;
    1972             :     uint8_t n;
    1973             :     uint8_t o;
    1974           0 :     assert(sp->subsamplingcorrect == 0);
    1975           0 :     if (sp->sof_log == 0)
    1976             :     {
    1977           0 :         TIFFErrorExtR(tif, module, "Corrupt SOS marker in JPEG data");
    1978           0 :         return (0);
    1979             :     }
    1980             :     /* Ls */
    1981           0 :     if (OJPEGReadWord(sp, &m) == 0)
    1982           0 :         return (0);
    1983           0 :     if (m != 6 + sp->samples_per_pixel_per_plane * 2)
    1984             :     {
    1985           0 :         TIFFErrorExtR(tif, module, "Corrupt SOS marker in JPEG data");
    1986           0 :         return (0);
    1987             :     }
    1988             :     /* Ns */
    1989           0 :     if (OJPEGReadByte(sp, &n) == 0)
    1990           0 :         return (0);
    1991           0 :     if (n != sp->samples_per_pixel_per_plane)
    1992             :     {
    1993           0 :         TIFFErrorExtR(tif, module, "Corrupt SOS marker in JPEG data");
    1994           0 :         return (0);
    1995             :     }
    1996             :     /* Cs, Td, and Ta */
    1997           0 :     for (o = 0; o < sp->samples_per_pixel_per_plane; o++)
    1998             :     {
    1999             :         /* Cs */
    2000           0 :         if (OJPEGReadByte(sp, &n) == 0)
    2001           0 :             return (0);
    2002           0 :         sp->sos_cs[sp->plane_sample_offset + o] = n;
    2003             :         /* Td and Ta */
    2004           0 :         if (OJPEGReadByte(sp, &n) == 0)
    2005           0 :             return (0);
    2006           0 :         sp->sos_tda[sp->plane_sample_offset + o] = n;
    2007             :     }
    2008             :     /* skip Ss, Se, Ah, en Al -> no check, as per Tom Lane recommendation, as
    2009             :      * per LibJpeg source */
    2010           0 :     OJPEGReadSkip(sp, 3);
    2011           0 :     return (1);
    2012             : }
    2013             : 
    2014           1 : static int OJPEGReadHeaderInfoSecTablesQTable(TIFF *tif)
    2015             : {
    2016             :     static const char module[] = "OJPEGReadHeaderInfoSecTablesQTable";
    2017           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2018             :     uint8_t m;
    2019             :     uint8_t n;
    2020             :     uint32_t oa;
    2021             :     uint8_t *ob;
    2022             :     uint32_t p;
    2023           1 :     if (sp->qtable_offset[0] == 0)
    2024             :     {
    2025           0 :         TIFFErrorExtR(tif, module, "Missing JPEG tables");
    2026           0 :         return (0);
    2027             :     }
    2028           1 :     sp->in_buffer_file_pos_log = 0;
    2029           4 :     for (m = 0; m < sp->samples_per_pixel; m++)
    2030             :     {
    2031           3 :         if ((sp->qtable_offset[m] != 0) &&
    2032           2 :             ((m == 0) || (sp->qtable_offset[m] != sp->qtable_offset[m - 1])))
    2033             :         {
    2034           4 :             for (n = 0; n < m - 1; n++)
    2035             :             {
    2036           1 :                 if (sp->qtable_offset[m] == sp->qtable_offset[n])
    2037             :                 {
    2038           0 :                     TIFFErrorExtR(tif, module, "Corrupt JpegQTables tag value");
    2039           0 :                     return (0);
    2040             :                 }
    2041             :             }
    2042           3 :             oa = sizeof(uint32_t) + 69;
    2043           3 :             ob = (uint8_t *)_TIFFmallocExt(tif, oa);
    2044           3 :             if (ob == 0)
    2045             :             {
    2046           0 :                 TIFFErrorExtR(tif, module, "Out of memory");
    2047           0 :                 return (0);
    2048             :             }
    2049           3 :             *(uint32_t *)ob = oa;
    2050           3 :             ob[sizeof(uint32_t)] = 255;
    2051           3 :             ob[sizeof(uint32_t) + 1] = JPEG_MARKER_DQT;
    2052           3 :             ob[sizeof(uint32_t) + 2] = 0;
    2053           3 :             ob[sizeof(uint32_t) + 3] = 67;
    2054           3 :             ob[sizeof(uint32_t) + 4] = m;
    2055           3 :             TIFFSeekFile(tif, sp->qtable_offset[m], SEEK_SET);
    2056           3 :             p = (uint32_t)TIFFReadFile(tif, &ob[sizeof(uint32_t) + 5], 64);
    2057           3 :             if (p != 64)
    2058             :             {
    2059           0 :                 _TIFFfreeExt(tif, ob);
    2060           0 :                 return (0);
    2061             :             }
    2062           3 :             if (sp->qtable[m] != 0)
    2063           0 :                 _TIFFfreeExt(tif, sp->qtable[m]);
    2064           3 :             sp->qtable[m] = ob;
    2065           3 :             sp->sof_tq[m] = m;
    2066             :         }
    2067             :         else
    2068           0 :             sp->sof_tq[m] = sp->sof_tq[m - 1];
    2069             :     }
    2070           1 :     return (1);
    2071             : }
    2072             : 
    2073           1 : static int OJPEGReadHeaderInfoSecTablesDcTable(TIFF *tif)
    2074             : {
    2075             :     static const char module[] = "OJPEGReadHeaderInfoSecTablesDcTable";
    2076           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2077             :     uint8_t m;
    2078             :     uint8_t n;
    2079             :     uint8_t o[16];
    2080             :     uint32_t p;
    2081             :     uint32_t q;
    2082             :     uint32_t ra;
    2083             :     uint8_t *rb;
    2084           1 :     if (sp->dctable_offset[0] == 0)
    2085             :     {
    2086           0 :         TIFFErrorExtR(tif, module, "Missing JPEG tables");
    2087           0 :         return (0);
    2088             :     }
    2089           1 :     sp->in_buffer_file_pos_log = 0;
    2090           4 :     for (m = 0; m < sp->samples_per_pixel; m++)
    2091             :     {
    2092           3 :         if ((sp->dctable_offset[m] != 0) &&
    2093           2 :             ((m == 0) || (sp->dctable_offset[m] != sp->dctable_offset[m - 1])))
    2094             :         {
    2095           4 :             for (n = 0; n < m - 1; n++)
    2096             :             {
    2097           1 :                 if (sp->dctable_offset[m] == sp->dctable_offset[n])
    2098             :                 {
    2099           0 :                     TIFFErrorExtR(tif, module,
    2100             :                                   "Corrupt JpegDcTables tag value");
    2101           0 :                     return (0);
    2102             :                 }
    2103             :             }
    2104           3 :             TIFFSeekFile(tif, sp->dctable_offset[m], SEEK_SET);
    2105           3 :             p = (uint32_t)TIFFReadFile(tif, o, 16);
    2106           3 :             if (p != 16)
    2107           0 :                 return (0);
    2108           3 :             q = 0;
    2109          51 :             for (n = 0; n < 16; n++)
    2110          48 :                 q += o[n];
    2111           3 :             ra = sizeof(uint32_t) + 21 + q;
    2112           3 :             rb = (uint8_t *)_TIFFmallocExt(tif, ra);
    2113           3 :             if (rb == 0)
    2114             :             {
    2115           0 :                 TIFFErrorExtR(tif, module, "Out of memory");
    2116           0 :                 return (0);
    2117             :             }
    2118           3 :             *(uint32_t *)rb = ra;
    2119           3 :             rb[sizeof(uint32_t)] = 255;
    2120           3 :             rb[sizeof(uint32_t) + 1] = JPEG_MARKER_DHT;
    2121           3 :             rb[sizeof(uint32_t) + 2] = (uint8_t)((19 + q) >> 8);
    2122           3 :             rb[sizeof(uint32_t) + 3] = ((19 + q) & 255);
    2123           3 :             rb[sizeof(uint32_t) + 4] = m;
    2124          51 :             for (n = 0; n < 16; n++)
    2125          48 :                 rb[sizeof(uint32_t) + 5 + n] = o[n];
    2126           3 :             p = (uint32_t)TIFFReadFile(tif, &(rb[sizeof(uint32_t) + 21]), q);
    2127           3 :             if (p != q)
    2128             :             {
    2129           0 :                 _TIFFfreeExt(tif, rb);
    2130           0 :                 return (0);
    2131             :             }
    2132           3 :             if (sp->dctable[m] != 0)
    2133           0 :                 _TIFFfreeExt(tif, sp->dctable[m]);
    2134           3 :             sp->dctable[m] = rb;
    2135           3 :             sp->sos_tda[m] = (m << 4);
    2136             :         }
    2137             :         else
    2138           0 :             sp->sos_tda[m] = sp->sos_tda[m - 1];
    2139             :     }
    2140           1 :     return (1);
    2141             : }
    2142             : 
    2143           1 : static int OJPEGReadHeaderInfoSecTablesAcTable(TIFF *tif)
    2144             : {
    2145             :     static const char module[] = "OJPEGReadHeaderInfoSecTablesAcTable";
    2146           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2147             :     uint8_t m;
    2148             :     uint8_t n;
    2149             :     uint8_t o[16];
    2150             :     uint32_t p;
    2151             :     uint32_t q;
    2152             :     uint32_t ra;
    2153             :     uint8_t *rb;
    2154           1 :     if (sp->actable_offset[0] == 0)
    2155             :     {
    2156           0 :         TIFFErrorExtR(tif, module, "Missing JPEG tables");
    2157           0 :         return (0);
    2158             :     }
    2159           1 :     sp->in_buffer_file_pos_log = 0;
    2160           4 :     for (m = 0; m < sp->samples_per_pixel; m++)
    2161             :     {
    2162           3 :         if ((sp->actable_offset[m] != 0) &&
    2163           2 :             ((m == 0) || (sp->actable_offset[m] != sp->actable_offset[m - 1])))
    2164             :         {
    2165           4 :             for (n = 0; n < m - 1; n++)
    2166             :             {
    2167           1 :                 if (sp->actable_offset[m] == sp->actable_offset[n])
    2168             :                 {
    2169           0 :                     TIFFErrorExtR(tif, module,
    2170             :                                   "Corrupt JpegAcTables tag value");
    2171           0 :                     return (0);
    2172             :                 }
    2173             :             }
    2174           3 :             TIFFSeekFile(tif, sp->actable_offset[m], SEEK_SET);
    2175           3 :             p = (uint32_t)TIFFReadFile(tif, o, 16);
    2176           3 :             if (p != 16)
    2177           0 :                 return (0);
    2178           3 :             q = 0;
    2179          51 :             for (n = 0; n < 16; n++)
    2180          48 :                 q += o[n];
    2181           3 :             ra = sizeof(uint32_t) + 21 + q;
    2182           3 :             rb = (uint8_t *)_TIFFmallocExt(tif, ra);
    2183           3 :             if (rb == 0)
    2184             :             {
    2185           0 :                 TIFFErrorExtR(tif, module, "Out of memory");
    2186           0 :                 return (0);
    2187             :             }
    2188           3 :             *(uint32_t *)rb = ra;
    2189           3 :             rb[sizeof(uint32_t)] = 255;
    2190           3 :             rb[sizeof(uint32_t) + 1] = JPEG_MARKER_DHT;
    2191           3 :             rb[sizeof(uint32_t) + 2] = (uint8_t)((19 + q) >> 8);
    2192           3 :             rb[sizeof(uint32_t) + 3] = ((19 + q) & 255);
    2193           3 :             rb[sizeof(uint32_t) + 4] = (16 | m);
    2194          51 :             for (n = 0; n < 16; n++)
    2195          48 :                 rb[sizeof(uint32_t) + 5 + n] = o[n];
    2196           3 :             p = (uint32_t)TIFFReadFile(tif, &(rb[sizeof(uint32_t) + 21]), q);
    2197           3 :             if (p != q)
    2198             :             {
    2199           0 :                 _TIFFfreeExt(tif, rb);
    2200           0 :                 return (0);
    2201             :             }
    2202           3 :             if (sp->actable[m] != 0)
    2203           0 :                 _TIFFfreeExt(tif, sp->actable[m]);
    2204           3 :             sp->actable[m] = rb;
    2205           3 :             sp->sos_tda[m] = (sp->sos_tda[m] | m);
    2206             :         }
    2207             :         else
    2208           0 :             sp->sos_tda[m] = (sp->sos_tda[m] | (sp->sos_tda[m - 1] & 15));
    2209             :     }
    2210           1 :     return (1);
    2211             : }
    2212             : 
    2213          22 : static int OJPEGReadBufferFill(OJPEGState *sp)
    2214             : {
    2215             :     uint16_t m;
    2216             :     tmsize_t n;
    2217             :     /* TODO: double-check: when subsamplingcorrect is set, no call to
    2218             :      * TIFFErrorExt or TIFFWarningExt should be made in any other case, seek or
    2219             :      * read errors should be passed through */
    2220             :     do
    2221             :     {
    2222          22 :         if (sp->in_buffer_file_togo != 0)
    2223             :         {
    2224           6 :             if (sp->in_buffer_file_pos_log == 0)
    2225             :             {
    2226           3 :                 TIFFSeekFile(sp->tif, sp->in_buffer_file_pos, SEEK_SET);
    2227           3 :                 sp->in_buffer_file_pos_log = 1;
    2228             :             }
    2229           6 :             m = OJPEG_BUFFER;
    2230           6 :             if ((uint64_t)m > sp->in_buffer_file_togo)
    2231           1 :                 m = (uint16_t)sp->in_buffer_file_togo;
    2232           6 :             n = TIFFReadFile(sp->tif, sp->in_buffer, (tmsize_t)m);
    2233           6 :             if (n == 0)
    2234           0 :                 return (0);
    2235           6 :             assert(n > 0);
    2236           6 :             assert(n <= OJPEG_BUFFER);
    2237           6 :             assert(n < 65536);
    2238           6 :             assert((uint64_t)n <= sp->in_buffer_file_togo);
    2239           6 :             m = (uint16_t)n;
    2240           6 :             sp->in_buffer_togo = m;
    2241           6 :             sp->in_buffer_cur = sp->in_buffer;
    2242           6 :             sp->in_buffer_file_togo -= m;
    2243           6 :             sp->in_buffer_file_pos += m;
    2244           6 :             break;
    2245             :         }
    2246          16 :         sp->in_buffer_file_pos_log = 0;
    2247          16 :         switch (sp->in_buffer_source)
    2248             :         {
    2249           4 :             case osibsNotSetYet:
    2250           4 :                 if (sp->jpeg_interchange_format != 0)
    2251             :                 {
    2252           0 :                     sp->in_buffer_file_pos = sp->jpeg_interchange_format;
    2253           0 :                     sp->in_buffer_file_togo =
    2254           0 :                         sp->jpeg_interchange_format_length;
    2255             :                 }
    2256           4 :                 sp->in_buffer_source = osibsJpegInterchangeFormat;
    2257           4 :                 break;
    2258           4 :             case osibsJpegInterchangeFormat:
    2259           4 :                 sp->in_buffer_source = osibsStrile;
    2260           4 :                 break;
    2261           6 :             case osibsStrile:
    2262           6 :                 if (sp->in_buffer_next_strile == sp->in_buffer_strile_count)
    2263           2 :                     sp->in_buffer_source = osibsEof;
    2264             :                 else
    2265             :                 {
    2266           4 :                     int err = 0;
    2267           4 :                     sp->in_buffer_file_pos = TIFFGetStrileOffsetWithErr(
    2268             :                         sp->tif, sp->in_buffer_next_strile, &err);
    2269           4 :                     if (err)
    2270           0 :                         return 0;
    2271           4 :                     if (sp->in_buffer_file_pos != 0)
    2272             :                     {
    2273           4 :                         uint64_t bytecount = TIFFGetStrileByteCountWithErr(
    2274             :                             sp->tif, sp->in_buffer_next_strile, &err);
    2275           4 :                         if (err)
    2276           0 :                             return 0;
    2277           4 :                         if (sp->in_buffer_file_pos >= sp->file_size)
    2278           2 :                             sp->in_buffer_file_pos = 0;
    2279           2 :                         else if (bytecount == 0)
    2280           0 :                             sp->in_buffer_file_togo =
    2281           0 :                                 sp->file_size - sp->in_buffer_file_pos;
    2282             :                         else
    2283             :                         {
    2284           2 :                             sp->in_buffer_file_togo = bytecount;
    2285           2 :                             if (sp->in_buffer_file_togo == 0)
    2286           0 :                                 sp->in_buffer_file_pos = 0;
    2287           2 :                             else if (sp->in_buffer_file_pos >
    2288           2 :                                          UINT64_MAX - sp->in_buffer_file_togo ||
    2289           2 :                                      sp->in_buffer_file_pos +
    2290           2 :                                              sp->in_buffer_file_togo >
    2291           2 :                                          sp->file_size)
    2292           0 :                                 sp->in_buffer_file_togo =
    2293           0 :                                     sp->file_size - sp->in_buffer_file_pos;
    2294             :                         }
    2295             :                     }
    2296           4 :                     sp->in_buffer_next_strile++;
    2297             :                 }
    2298           6 :                 break;
    2299           2 :             case osibsEof:
    2300             :             default:
    2301           2 :                 return (0);
    2302             :         }
    2303             :     } while (1);
    2304           6 :     return (1);
    2305             : }
    2306             : 
    2307           0 : static int OJPEGReadByte(OJPEGState *sp, uint8_t *byte)
    2308             : {
    2309           0 :     if (sp->in_buffer_togo == 0)
    2310             :     {
    2311           0 :         if (OJPEGReadBufferFill(sp) == 0)
    2312           0 :             return (0);
    2313           0 :         assert(sp->in_buffer_togo > 0);
    2314             :     }
    2315           0 :     *byte = *(sp->in_buffer_cur);
    2316           0 :     sp->in_buffer_cur++;
    2317           0 :     sp->in_buffer_togo--;
    2318           0 :     return (1);
    2319             : }
    2320             : 
    2321           4 : static int OJPEGReadBytePeek(OJPEGState *sp, uint8_t *byte)
    2322             : {
    2323           4 :     if (sp->in_buffer_togo == 0)
    2324             :     {
    2325           4 :         if (OJPEGReadBufferFill(sp) == 0)
    2326           2 :             return (0);
    2327           2 :         assert(sp->in_buffer_togo > 0);
    2328             :     }
    2329           2 :     *byte = *(sp->in_buffer_cur);
    2330           2 :     return (1);
    2331             : }
    2332             : 
    2333           0 : static void OJPEGReadByteAdvance(OJPEGState *sp)
    2334             : {
    2335           0 :     assert(sp->in_buffer_togo > 0);
    2336           0 :     sp->in_buffer_cur++;
    2337           0 :     sp->in_buffer_togo--;
    2338           0 : }
    2339             : 
    2340           0 : static int OJPEGReadWord(OJPEGState *sp, uint16_t *word)
    2341             : {
    2342             :     uint8_t m;
    2343           0 :     if (OJPEGReadByte(sp, &m) == 0)
    2344           0 :         return (0);
    2345           0 :     *word = (m << 8);
    2346           0 :     if (OJPEGReadByte(sp, &m) == 0)
    2347           0 :         return (0);
    2348           0 :     *word |= m;
    2349           0 :     return (1);
    2350             : }
    2351             : 
    2352           0 : static int OJPEGReadBlock(OJPEGState *sp, uint16_t len, void *mem)
    2353             : {
    2354             :     uint16_t mlen;
    2355             :     uint8_t *mmem;
    2356             :     uint16_t n;
    2357           0 :     assert(len > 0);
    2358           0 :     mlen = len;
    2359           0 :     mmem = (uint8_t *)mem;
    2360             :     do
    2361             :     {
    2362           0 :         if (sp->in_buffer_togo == 0)
    2363             :         {
    2364           0 :             if (OJPEGReadBufferFill(sp) == 0)
    2365           0 :                 return (0);
    2366           0 :             assert(sp->in_buffer_togo > 0);
    2367             :         }
    2368           0 :         n = mlen;
    2369           0 :         if (n > sp->in_buffer_togo)
    2370           0 :             n = sp->in_buffer_togo;
    2371           0 :         _TIFFmemcpy(mmem, sp->in_buffer_cur, n);
    2372           0 :         sp->in_buffer_cur += n;
    2373           0 :         sp->in_buffer_togo -= n;
    2374           0 :         mlen -= n;
    2375           0 :         mmem += n;
    2376           0 :     } while (mlen > 0);
    2377           0 :     return (1);
    2378             : }
    2379             : 
    2380           0 : static void OJPEGReadSkip(OJPEGState *sp, uint16_t len)
    2381             : {
    2382             :     uint16_t m;
    2383             :     uint16_t n;
    2384           0 :     m = len;
    2385           0 :     n = m;
    2386           0 :     if (n > sp->in_buffer_togo)
    2387           0 :         n = sp->in_buffer_togo;
    2388           0 :     sp->in_buffer_cur += n;
    2389           0 :     sp->in_buffer_togo -= n;
    2390           0 :     m -= n;
    2391           0 :     if (m > 0)
    2392             :     {
    2393           0 :         assert(sp->in_buffer_togo == 0);
    2394           0 :         n = m;
    2395           0 :         if ((uint64_t)n > sp->in_buffer_file_togo)
    2396           0 :             n = (uint16_t)sp->in_buffer_file_togo;
    2397           0 :         sp->in_buffer_file_pos += n;
    2398           0 :         sp->in_buffer_file_togo -= n;
    2399           0 :         sp->in_buffer_file_pos_log = 0;
    2400             :         /* we don't skip past jpeginterchangeformat/strile block...
    2401             :          * if that is asked from us, we're dealing with totally bazurk
    2402             :          * data anyway, and we've not seen this happening on any
    2403             :          * testfile, so we might as well likely cause some other
    2404             :          * meaningless error to be passed at some later time
    2405             :          */
    2406             :     }
    2407           0 : }
    2408             : 
    2409          17 : static int OJPEGWriteStream(TIFF *tif, void **mem, uint32_t *len)
    2410             : {
    2411          17 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2412          17 :     *len = 0;
    2413             :     do
    2414             :     {
    2415          21 :         assert(sp->out_state <= ososEoi);
    2416          21 :         switch (sp->out_state)
    2417             :         {
    2418           1 :             case ososSoi:
    2419           1 :                 OJPEGWriteStreamSoi(tif, mem, len);
    2420           1 :                 break;
    2421           1 :             case ososQTable0:
    2422           1 :                 OJPEGWriteStreamQTable(tif, 0, mem, len);
    2423           1 :                 break;
    2424           1 :             case ososQTable1:
    2425           1 :                 OJPEGWriteStreamQTable(tif, 1, mem, len);
    2426           1 :                 break;
    2427           1 :             case ososQTable2:
    2428           1 :                 OJPEGWriteStreamQTable(tif, 2, mem, len);
    2429           1 :                 break;
    2430           1 :             case ososQTable3:
    2431           1 :                 OJPEGWriteStreamQTable(tif, 3, mem, len);
    2432           1 :                 break;
    2433           1 :             case ososDcTable0:
    2434           1 :                 OJPEGWriteStreamDcTable(tif, 0, mem, len);
    2435           1 :                 break;
    2436           1 :             case ososDcTable1:
    2437           1 :                 OJPEGWriteStreamDcTable(tif, 1, mem, len);
    2438           1 :                 break;
    2439           1 :             case ososDcTable2:
    2440           1 :                 OJPEGWriteStreamDcTable(tif, 2, mem, len);
    2441           1 :                 break;
    2442           1 :             case ososDcTable3:
    2443           1 :                 OJPEGWriteStreamDcTable(tif, 3, mem, len);
    2444           1 :                 break;
    2445           1 :             case ososAcTable0:
    2446           1 :                 OJPEGWriteStreamAcTable(tif, 0, mem, len);
    2447           1 :                 break;
    2448           1 :             case ososAcTable1:
    2449           1 :                 OJPEGWriteStreamAcTable(tif, 1, mem, len);
    2450           1 :                 break;
    2451           1 :             case ososAcTable2:
    2452           1 :                 OJPEGWriteStreamAcTable(tif, 2, mem, len);
    2453           1 :                 break;
    2454           1 :             case ososAcTable3:
    2455           1 :                 OJPEGWriteStreamAcTable(tif, 3, mem, len);
    2456           1 :                 break;
    2457           1 :             case ososDri:
    2458           1 :                 OJPEGWriteStreamDri(tif, mem, len);
    2459           1 :                 break;
    2460           1 :             case ososSof:
    2461           1 :                 OJPEGWriteStreamSof(tif, mem, len);
    2462           1 :                 break;
    2463           1 :             case ososSos:
    2464           1 :                 OJPEGWriteStreamSos(tif, mem, len);
    2465           1 :                 break;
    2466           4 :             case ososCompressed:
    2467           4 :                 if (OJPEGWriteStreamCompressed(tif, mem, len) == 0)
    2468           0 :                     return (0);
    2469           4 :                 break;
    2470           0 :             case ososRst:
    2471           0 :                 OJPEGWriteStreamRst(tif, mem, len);
    2472           0 :                 break;
    2473           1 :             case ososEoi:
    2474           1 :                 OJPEGWriteStreamEoi(tif, mem, len);
    2475           1 :                 break;
    2476           0 :             default:
    2477           0 :                 break;
    2478             :         }
    2479          21 :     } while (*len == 0);
    2480          17 :     return (1);
    2481             : }
    2482             : 
    2483           1 : static void OJPEGWriteStreamSoi(TIFF *tif, void **mem, uint32_t *len)
    2484             : {
    2485           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2486             :     assert(OJPEG_BUFFER >= 2);
    2487           1 :     sp->out_buffer[0] = 255;
    2488           1 :     sp->out_buffer[1] = JPEG_MARKER_SOI;
    2489           1 :     *len = 2;
    2490           1 :     *mem = (void *)sp->out_buffer;
    2491           1 :     sp->out_state = (OJPEGStateOutState)(sp->out_state + 1);
    2492           1 : }
    2493             : 
    2494           4 : static void OJPEGWriteStreamQTable(TIFF *tif, uint8_t table_index, void **mem,
    2495             :                                    uint32_t *len)
    2496             : {
    2497           4 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2498           4 :     if (sp->qtable[table_index] != 0)
    2499             :     {
    2500           3 :         *mem = (void *)(sp->qtable[table_index] + sizeof(uint32_t));
    2501           3 :         *len = *((uint32_t *)sp->qtable[table_index]) - sizeof(uint32_t);
    2502             :     }
    2503           4 :     sp->out_state = (OJPEGStateOutState)(sp->out_state + 1);
    2504           4 : }
    2505             : 
    2506           4 : static void OJPEGWriteStreamDcTable(TIFF *tif, uint8_t table_index, void **mem,
    2507             :                                     uint32_t *len)
    2508             : {
    2509           4 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2510           4 :     if (sp->dctable[table_index] != 0)
    2511             :     {
    2512           3 :         *mem = (void *)(sp->dctable[table_index] + sizeof(uint32_t));
    2513           3 :         *len = *((uint32_t *)sp->dctable[table_index]) - sizeof(uint32_t);
    2514             :     }
    2515           4 :     sp->out_state = (OJPEGStateOutState)(sp->out_state + 1);
    2516           4 : }
    2517             : 
    2518           4 : static void OJPEGWriteStreamAcTable(TIFF *tif, uint8_t table_index, void **mem,
    2519             :                                     uint32_t *len)
    2520             : {
    2521           4 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2522           4 :     if (sp->actable[table_index] != 0)
    2523             :     {
    2524           3 :         *mem = (void *)(sp->actable[table_index] + sizeof(uint32_t));
    2525           3 :         *len = *((uint32_t *)sp->actable[table_index]) - sizeof(uint32_t);
    2526             :     }
    2527           4 :     sp->out_state = (OJPEGStateOutState)(sp->out_state + 1);
    2528           4 : }
    2529             : 
    2530           1 : static void OJPEGWriteStreamDri(TIFF *tif, void **mem, uint32_t *len)
    2531             : {
    2532           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2533             :     assert(OJPEG_BUFFER >= 6);
    2534           1 :     if (sp->restart_interval != 0)
    2535             :     {
    2536           0 :         sp->out_buffer[0] = 255;
    2537           0 :         sp->out_buffer[1] = JPEG_MARKER_DRI;
    2538           0 :         sp->out_buffer[2] = 0;
    2539           0 :         sp->out_buffer[3] = 4;
    2540           0 :         sp->out_buffer[4] = (sp->restart_interval >> 8);
    2541           0 :         sp->out_buffer[5] = (sp->restart_interval & 255);
    2542           0 :         *len = 6;
    2543           0 :         *mem = (void *)sp->out_buffer;
    2544             :     }
    2545           1 :     sp->out_state = (OJPEGStateOutState)(sp->out_state + 1);
    2546           1 : }
    2547             : 
    2548           1 : static void OJPEGWriteStreamSof(TIFF *tif, void **mem, uint32_t *len)
    2549             : {
    2550           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2551             :     uint8_t m;
    2552           1 :     assert(OJPEG_BUFFER >= 2 + 8 + sp->samples_per_pixel_per_plane * 3);
    2553           1 :     assert(255 >= 8 + sp->samples_per_pixel_per_plane * 3);
    2554           1 :     sp->out_buffer[0] = 255;
    2555           1 :     sp->out_buffer[1] = sp->sof_marker_id;
    2556             :     /* Lf */
    2557           1 :     sp->out_buffer[2] = 0;
    2558           1 :     sp->out_buffer[3] = 8 + sp->samples_per_pixel_per_plane * 3;
    2559             :     /* P */
    2560           1 :     sp->out_buffer[4] = 8;
    2561             :     /* Y */
    2562           1 :     sp->out_buffer[5] = (uint8_t)(sp->sof_y >> 8);
    2563           1 :     sp->out_buffer[6] = (sp->sof_y & 255);
    2564             :     /* X */
    2565           1 :     sp->out_buffer[7] = (uint8_t)(sp->sof_x >> 8);
    2566           1 :     sp->out_buffer[8] = (sp->sof_x & 255);
    2567             :     /* Nf */
    2568           1 :     sp->out_buffer[9] = sp->samples_per_pixel_per_plane;
    2569           4 :     for (m = 0; m < sp->samples_per_pixel_per_plane; m++)
    2570             :     {
    2571             :         /* C */
    2572           3 :         sp->out_buffer[10 + m * 3] = sp->sof_c[sp->plane_sample_offset + m];
    2573             :         /* H and V */
    2574           3 :         sp->out_buffer[10 + m * 3 + 1] =
    2575           3 :             sp->sof_hv[sp->plane_sample_offset + m];
    2576             :         /* Tq */
    2577           3 :         sp->out_buffer[10 + m * 3 + 2] =
    2578           3 :             sp->sof_tq[sp->plane_sample_offset + m];
    2579             :     }
    2580           1 :     *len = 10 + sp->samples_per_pixel_per_plane * 3;
    2581           1 :     *mem = (void *)sp->out_buffer;
    2582           1 :     sp->out_state = (OJPEGStateOutState)(sp->out_state + 1);
    2583           1 : }
    2584             : 
    2585           1 : static void OJPEGWriteStreamSos(TIFF *tif, void **mem, uint32_t *len)
    2586             : {
    2587           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2588             :     uint8_t m;
    2589           1 :     assert(OJPEG_BUFFER >= 2 + 6 + sp->samples_per_pixel_per_plane * 2);
    2590           1 :     assert(255 >= 6 + sp->samples_per_pixel_per_plane * 2);
    2591           1 :     sp->out_buffer[0] = 255;
    2592           1 :     sp->out_buffer[1] = JPEG_MARKER_SOS;
    2593             :     /* Ls */
    2594           1 :     sp->out_buffer[2] = 0;
    2595           1 :     sp->out_buffer[3] = 6 + sp->samples_per_pixel_per_plane * 2;
    2596             :     /* Ns */
    2597           1 :     sp->out_buffer[4] = sp->samples_per_pixel_per_plane;
    2598           4 :     for (m = 0; m < sp->samples_per_pixel_per_plane; m++)
    2599             :     {
    2600             :         /* Cs */
    2601           3 :         sp->out_buffer[5 + m * 2] = sp->sos_cs[sp->plane_sample_offset + m];
    2602             :         /* Td and Ta */
    2603           3 :         sp->out_buffer[5 + m * 2 + 1] =
    2604           3 :             sp->sos_tda[sp->plane_sample_offset + m];
    2605             :     }
    2606             :     /* Ss */
    2607           1 :     sp->out_buffer[5 + sp->samples_per_pixel_per_plane * 2] = 0;
    2608             :     /* Se */
    2609           1 :     sp->out_buffer[5 + sp->samples_per_pixel_per_plane * 2 + 1] = 63;
    2610             :     /* Ah and Al */
    2611           1 :     sp->out_buffer[5 + sp->samples_per_pixel_per_plane * 2 + 2] = 0;
    2612           1 :     *len = 8 + sp->samples_per_pixel_per_plane * 2;
    2613           1 :     *mem = (void *)sp->out_buffer;
    2614           1 :     sp->out_state = (OJPEGStateOutState)(sp->out_state + 1);
    2615           1 : }
    2616             : 
    2617           4 : static int OJPEGWriteStreamCompressed(TIFF *tif, void **mem, uint32_t *len)
    2618             : {
    2619           4 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2620           4 :     if (sp->in_buffer_togo == 0)
    2621             :     {
    2622           4 :         if (OJPEGReadBufferFill(sp) == 0)
    2623           0 :             return (0);
    2624           4 :         assert(sp->in_buffer_togo > 0);
    2625             :     }
    2626           4 :     *len = sp->in_buffer_togo;
    2627           4 :     *mem = (void *)sp->in_buffer_cur;
    2628           4 :     sp->in_buffer_togo = 0;
    2629           4 :     if (sp->in_buffer_file_togo == 0)
    2630             :     {
    2631           1 :         switch (sp->in_buffer_source)
    2632             :         {
    2633           1 :             case osibsStrile:
    2634           1 :                 if (sp->in_buffer_next_strile < sp->in_buffer_strile_count)
    2635           0 :                     sp->out_state = ososRst;
    2636             :                 else
    2637           1 :                     sp->out_state = ososEoi;
    2638           1 :                 break;
    2639           0 :             case osibsEof:
    2640           0 :                 sp->out_state = ososEoi;
    2641           0 :                 break;
    2642           0 :             case osibsNotSetYet:
    2643             :             case osibsJpegInterchangeFormat:
    2644             :             default:
    2645           0 :                 break;
    2646             :         }
    2647           3 :     }
    2648           4 :     return (1);
    2649             : }
    2650             : 
    2651           0 : static void OJPEGWriteStreamRst(TIFF *tif, void **mem, uint32_t *len)
    2652             : {
    2653           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2654             :     assert(OJPEG_BUFFER >= 2);
    2655           0 :     sp->out_buffer[0] = 255;
    2656           0 :     sp->out_buffer[1] = JPEG_MARKER_RST0 + sp->restart_index;
    2657           0 :     sp->restart_index++;
    2658           0 :     if (sp->restart_index == 8)
    2659           0 :         sp->restart_index = 0;
    2660           0 :     *len = 2;
    2661           0 :     *mem = (void *)sp->out_buffer;
    2662           0 :     sp->out_state = ososCompressed;
    2663           0 : }
    2664             : 
    2665           1 : static void OJPEGWriteStreamEoi(TIFF *tif, void **mem, uint32_t *len)
    2666             : {
    2667           1 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2668             :     assert(OJPEG_BUFFER >= 2);
    2669           1 :     sp->out_buffer[0] = 255;
    2670           1 :     sp->out_buffer[1] = JPEG_MARKER_EOI;
    2671           1 :     *len = 2;
    2672           1 :     *mem = (void *)sp->out_buffer;
    2673           1 : }
    2674             : 
    2675             : #ifndef LIBJPEG_ENCAP_EXTERNAL
    2676           1 : static int jpeg_create_decompress_encap(OJPEGState *sp,
    2677             :                                         jpeg_decompress_struct *cinfo)
    2678             : {
    2679           1 :     if (SETJMP(sp->exit_jmpbuf))
    2680           0 :         return 0;
    2681             :     else
    2682             :     {
    2683           1 :         jpeg_create_decompress(cinfo);
    2684           1 :         return 1;
    2685             :     }
    2686             : }
    2687             : #endif
    2688             : 
    2689             : #ifndef LIBJPEG_ENCAP_EXTERNAL
    2690           1 : static int jpeg_read_header_encap(OJPEGState *sp, jpeg_decompress_struct *cinfo,
    2691             :                                   uint8_t require_image)
    2692             : {
    2693           1 :     if (SETJMP(sp->exit_jmpbuf))
    2694           0 :         return 0;
    2695             :     else
    2696             :     {
    2697           1 :         jpeg_read_header(cinfo, require_image);
    2698           1 :         return 1;
    2699             :     }
    2700             : }
    2701             : #endif
    2702             : 
    2703             : #ifndef LIBJPEG_ENCAP_EXTERNAL
    2704           1 : static int jpeg_start_decompress_encap(OJPEGState *sp,
    2705             :                                        jpeg_decompress_struct *cinfo)
    2706             : {
    2707           1 :     if (SETJMP(sp->exit_jmpbuf))
    2708           0 :         return 0;
    2709             :     else
    2710             :     {
    2711           1 :         jpeg_start_decompress(cinfo);
    2712           1 :         return 1;
    2713             :     }
    2714             : }
    2715             : #endif
    2716             : 
    2717             : #ifndef LIBJPEG_ENCAP_EXTERNAL
    2718           0 : static int jpeg_read_scanlines_encap(OJPEGState *sp,
    2719             :                                      jpeg_decompress_struct *cinfo,
    2720             :                                      void *scanlines, uint32_t max_lines)
    2721             : {
    2722           0 :     if (SETJMP(sp->exit_jmpbuf))
    2723           0 :         return 0;
    2724             :     else
    2725             :     {
    2726           0 :         jpeg_read_scanlines(cinfo, (JSAMPARRAY)scanlines, max_lines);
    2727           0 :         return 1;
    2728             :     }
    2729             : }
    2730             : #endif
    2731             : 
    2732             : #ifndef LIBJPEG_ENCAP_EXTERNAL
    2733          14 : static int jpeg_read_raw_data_encap(OJPEGState *sp,
    2734             :                                     jpeg_decompress_struct *cinfo, void *data,
    2735             :                                     uint32_t max_lines)
    2736             : {
    2737          14 :     if (SETJMP(sp->exit_jmpbuf))
    2738           0 :         return 0;
    2739             :     else
    2740             :     {
    2741          14 :         jpeg_read_raw_data(cinfo, (JSAMPIMAGE)data, max_lines);
    2742          14 :         return 1;
    2743             :     }
    2744             : }
    2745             : #endif
    2746             : 
    2747             : #ifndef LIBJPEG_ENCAP_EXTERNAL
    2748           0 : static void jpeg_encap_unwind(TIFF *tif)
    2749             : {
    2750           0 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2751           0 :     LONGJMP(sp->exit_jmpbuf, 1);
    2752             : }
    2753             : #endif
    2754             : 
    2755           0 : static void OJPEGLibjpegJpegErrorMgrOutputMessage(jpeg_common_struct *cinfo)
    2756             : {
    2757             :     char buffer[JMSG_LENGTH_MAX];
    2758           0 :     (*cinfo->err->format_message)(cinfo, buffer);
    2759           0 :     TIFFWarningExtR(((TIFF *)(cinfo->client_data)), "LibJpeg", "%s", buffer);
    2760           0 : }
    2761             : 
    2762           0 : static void OJPEGLibjpegJpegErrorMgrErrorExit(jpeg_common_struct *cinfo)
    2763             : {
    2764             :     char buffer[JMSG_LENGTH_MAX];
    2765           0 :     (*cinfo->err->format_message)(cinfo, buffer);
    2766           0 :     TIFFErrorExtR(((TIFF *)(cinfo->client_data)), "LibJpeg", "%s", buffer);
    2767           0 :     jpeg_encap_unwind((TIFF *)(cinfo->client_data));
    2768           0 : }
    2769             : 
    2770           1 : static void OJPEGLibjpegJpegSourceMgrInitSource(jpeg_decompress_struct *cinfo)
    2771             : {
    2772             :     (void)cinfo;
    2773           1 : }
    2774             : 
    2775             : static boolean
    2776          17 : OJPEGLibjpegJpegSourceMgrFillInputBuffer(jpeg_decompress_struct *cinfo)
    2777             : {
    2778          17 :     TIFF *tif = (TIFF *)cinfo->client_data;
    2779          17 :     OJPEGState *sp = (OJPEGState *)tif->tif_data;
    2780          17 :     void *mem = 0;
    2781          17 :     uint32_t len = 0U;
    2782          17 :     if (OJPEGWriteStream(tif, &mem, &len) == 0)
    2783             :     {
    2784           0 :         TIFFErrorExtR(tif, "LibJpeg", "Premature end of JPEG data");
    2785           0 :         jpeg_encap_unwind(tif);
    2786             :     }
    2787          17 :     sp->libjpeg_jpeg_source_mgr.bytes_in_buffer = len;
    2788          17 :     sp->libjpeg_jpeg_source_mgr.next_input_byte = (const JOCTET *)mem;
    2789          17 :     return (1);
    2790             : }
    2791             : 
    2792             : static void
    2793           0 : OJPEGLibjpegJpegSourceMgrSkipInputData(jpeg_decompress_struct *cinfo,
    2794             :                                        long num_bytes)
    2795             : {
    2796           0 :     TIFF *tif = (TIFF *)cinfo->client_data;
    2797             :     (void)num_bytes;
    2798           0 :     TIFFErrorExtR(tif, "LibJpeg", "Unexpected error");
    2799           0 :     jpeg_encap_unwind(tif);
    2800           0 : }
    2801             : 
    2802             : #ifdef _MSC_VER
    2803             : #pragma warning(push)
    2804             : #pragma warning(disable : 4702) /* unreachable code */
    2805             : #endif
    2806             : static boolean
    2807           0 : OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct *cinfo,
    2808             :                                          int desired)
    2809             : {
    2810           0 :     TIFF *tif = (TIFF *)cinfo->client_data;
    2811             :     (void)desired;
    2812           0 :     TIFFErrorExtR(tif, "LibJpeg", "Unexpected error");
    2813           0 :     jpeg_encap_unwind(tif);
    2814           0 :     return (0);
    2815             : }
    2816             : #ifdef _MSC_VER
    2817             : #pragma warning(pop)
    2818             : #endif
    2819             : 
    2820           0 : static void OJPEGLibjpegJpegSourceMgrTermSource(jpeg_decompress_struct *cinfo)
    2821             : {
    2822             :     (void)cinfo;
    2823           0 : }
    2824             : 
    2825             : #endif

Generated by: LCOV version 1.14