LCOV - code coverage report
Current view: directory - frmts/gtiff/libtiff - tif_jpeg.c (source / functions) Found Hit Coverage
Test: gdal_filtered.info Lines: 918 553 60.2 %
Date: 2010-01-09 Functions: 66 50 75.8 %

       1                 : /* $Id: tif_jpeg.c,v 1.86 2009-12-04 01:37:58 fwarmerdam Exp $ */
       2                 : 
       3                 : /*
       4                 :  * Copyright (c) 1994-1997 Sam Leffler
       5                 :  * Copyright (c) 1994-1997 Silicon Graphics, Inc.
       6                 :  *
       7                 :  * Permission to use, copy, modify, distribute, and sell this software and 
       8                 :  * its documentation for any purpose is hereby granted without fee, provided
       9                 :  * that (i) the above copyright notices and this permission notice appear in
      10                 :  * all copies of the software and related documentation, and (ii) the names of
      11                 :  * Sam Leffler and Silicon Graphics may not be used in any advertising or
      12                 :  * publicity relating to the software without the specific, prior written
      13                 :  * permission of Sam Leffler and Silicon Graphics.
      14                 :  * 
      15                 :  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
      16                 :  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
      17                 :  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
      18                 :  * 
      19                 :  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
      20                 :  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
      21                 :  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
      22                 :  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
      23                 :  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
      24                 :  * OF THIS SOFTWARE.
      25                 :  */
      26                 : 
      27                 : #define WIN32_LEAN_AND_MEAN
      28                 : #define VC_EXTRALEAN
      29                 : 
      30                 : #include "tiffiop.h"
      31                 : #ifdef JPEG_SUPPORT
      32                 : 
      33                 : /*
      34                 :  * TIFF Library
      35                 :  *
      36                 :  * JPEG Compression support per TIFF Technical Note #2
      37                 :  * (*not* per the original TIFF 6.0 spec).
      38                 :  *
      39                 :  * This file is simply an interface to the libjpeg library written by
      40                 :  * the Independent JPEG Group.  You need release 5 or later of the IJG
      41                 :  * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
      42                 :  *
      43                 :  * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
      44                 :  */
      45                 : #include <setjmp.h>
      46                 : 
      47                 : int TIFFFillStrip(TIFF* tif, uint32 strip);
      48                 : int TIFFFillTile(TIFF* tif, uint32 tile);
      49                 : int TIFFReInitJPEG_12( TIFF *tif, int scheme, int is_encode );
      50                 : 
      51                 : /* We undefine FAR to avoid conflict with JPEG definition */
      52                 : 
      53                 : #ifdef FAR
      54                 : #undef FAR
      55                 : #endif
      56                 : 
      57                 : /*
      58                 :   Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
      59                 :   not defined.  Unfortunately, the MinGW and Borland compilers include
      60                 :   a typedef for INT32, which causes a conflict.  MSVC does not include
      61                 :   a conficting typedef given the headers which are included.
      62                 : */
      63                 : #if defined(__BORLANDC__) || defined(__MINGW32__)
      64                 : # define XMD_H 1
      65                 : #endif
      66                 : 
      67                 : /*
      68                 :    The windows RPCNDR.H file defines boolean, but defines it with the
      69                 :    unsigned char size.  You should compile JPEG library using appropriate
      70                 :    definitions in jconfig.h header, but many users compile library in wrong
      71                 :    way. That causes errors of the following type:
      72                 : 
      73                 :    "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
      74                 :    caller expects 464"
      75                 : 
      76                 :    For such users we wil fix the problem here. See install.doc file from
      77                 :    the JPEG library distribution for details.
      78                 : */
      79                 : 
      80                 : /* Define "boolean" as unsigned char, not int, per Windows custom. */
      81                 : #if defined(__WIN32__) && !defined(__MINGW32__)
      82                 : # ifndef __RPCNDR_H__            /* don't conflict if rpcndr.h already read */
      83                 :    typedef unsigned char boolean;
      84                 : # endif
      85                 : # define HAVE_BOOLEAN            /* prevent jmorecfg.h from redefining it */
      86                 : #endif
      87                 : 
      88                 : #include "jpeglib.h"
      89                 : #include "jerror.h"
      90                 : 
      91                 : /* 
      92                 :  * Do we want to do special processing suitable for when JSAMPLE is a
      93                 :  * 16bit value?  
      94                 :  */
      95                 : 
      96                 : #if defined(JPEG_LIB_MK1)
      97                 : #  define JPEG_LIB_MK1_OR_12BIT 1
      98                 : #elif BITS_IN_JSAMPLE == 12
      99                 : #  define JPEG_LIB_MK1_OR_12BIT 1
     100                 : #endif
     101                 : 
     102                 : /*
     103                 :  * We are using width_in_blocks which is supposed to be private to
     104                 :  * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
     105                 :  * renamed this member to width_in_data_units.  Since the header has
     106                 :  * also renamed a define, use that unique define name in order to
     107                 :  * detect the problem header and adjust to suit.
     108                 :  */
     109                 : #if defined(D_MAX_DATA_UNITS_IN_MCU)
     110                 : #define width_in_blocks width_in_data_units
     111                 : #endif
     112                 : 
     113                 : /*
     114                 :  * On some machines it may be worthwhile to use _setjmp or sigsetjmp
     115                 :  * in place of plain setjmp.  These macros will make it easier.
     116                 :  */
     117                 : #define SETJMP(jbuf)    setjmp(jbuf)
     118                 : #define LONGJMP(jbuf,code)  longjmp(jbuf,code)
     119                 : #define JMP_BUF     jmp_buf
     120                 : 
     121                 : typedef struct jpeg_destination_mgr jpeg_destination_mgr;
     122                 : typedef struct jpeg_source_mgr jpeg_source_mgr;
     123                 : typedef struct jpeg_error_mgr jpeg_error_mgr;
     124                 : 
     125                 : /*
     126                 :  * State block for each open TIFF file using
     127                 :  * libjpeg to do JPEG compression/decompression.
     128                 :  *
     129                 :  * libjpeg's visible state is either a jpeg_compress_struct
     130                 :  * or jpeg_decompress_struct depending on which way we
     131                 :  * are going.  comm can be used to refer to the fields
     132                 :  * which are common to both.
     133                 :  *
     134                 :  * NB: cinfo is required to be the first member of JPEGState,
     135                 :  *     so we can safely cast JPEGState* -> jpeg_xxx_struct*
     136                 :  *     and vice versa!
     137                 :  */
     138                 : typedef struct {
     139                 :   union {
     140                 :     struct jpeg_compress_struct c;
     141                 :     struct jpeg_decompress_struct d;
     142                 :     struct jpeg_common_struct comm;
     143                 :   } cinfo;      /* NB: must be first */
     144                 :   int             cinfo_initialized;
     145                 : 
     146                 :   jpeg_error_mgr  err;    /* libjpeg error manager */
     147                 :   JMP_BUF   exit_jmpbuf;  /* for catching libjpeg failures */
     148                 :   /*
     149                 :    * The following two members could be a union, but
     150                 :    * they're small enough that it's not worth the effort.
     151                 :    */
     152                 :   jpeg_destination_mgr dest;  /* data dest for compression */
     153                 :   jpeg_source_mgr src;    /* data source for decompression */
     154                 :           /* private state */
     155                 :   TIFF*   tif;    /* back link needed by some code */
     156                 :   uint16    photometric;  /* copy of PhotometricInterpretation */
     157                 :   uint16    h_sampling; /* luminance sampling factors */
     158                 :   uint16    v_sampling;
     159                 :   tmsize_t    bytesperline; /* decompressed bytes per scanline */
     160                 :   /* pointers to intermediate buffers when processing downsampled data */
     161                 :   JSAMPARRAY  ds_buffer[MAX_COMPONENTS];
     162                 :   int   scancount;  /* number of "scanlines" accumulated */
     163                 :   int   samplesperclump;
     164                 : 
     165                 :   TIFFVGetMethod  vgetparent; /* super-class method */
     166                 :   TIFFVSetMethod  vsetparent; /* super-class method */
     167                 :   TIFFPrintMethod printdir; /* super-class method */
     168                 :   TIFFStripMethod defsparent; /* super-class method */
     169                 :   TIFFTileMethod  deftparent; /* super-class method */
     170                 :           /* pseudo-tag fields */
     171                 :   void*   jpegtables; /* JPEGTables tag value, or NULL */
     172                 :   uint32    jpegtables_length; /* number of bytes in same */
     173                 :   int   jpegquality;  /* Compression quality level */
     174                 :   int   jpegcolormode;  /* Auto RGB<=>YCbCr convert? */
     175                 :   int   jpegtablesmode; /* What to put in JPEGTables */
     176                 : 
     177                 :         int             ycbcrsampling_fetched;
     178                 : } JPEGState;
     179                 : 
     180                 : #define JState(tif) ((JPEGState*)(tif)->tif_data)
     181                 : 
     182                 : static int JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
     183                 : static int JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
     184                 : static int JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
     185                 : static int JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
     186                 : static int JPEGInitializeLibJPEG(TIFF * tif, int decode );
     187                 : static int DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
     188                 : 
     189                 : #define FIELD_JPEGTABLES  (FIELD_CODEC+0)
     190                 : 
     191                 : static const TIFFField jpegFields[] = {
     192                 :     { TIFFTAG_JPEGTABLES, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_C32_UINT8, FIELD_JPEGTABLES, FALSE, TRUE, "JPEGTables", NULL },
     193                 :     { TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "", NULL },
     194                 :     { TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL },
     195                 :     { TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL }
     196                 : };
     197                 : 
     198                 : /*
     199                 :  * libjpeg interface layer.
     200                 :  *
     201                 :  * We use setjmp/longjmp to return control to libtiff
     202                 :  * when a fatal error is encountered within the JPEG
     203                 :  * library.  We also direct libjpeg error and warning
     204                 :  * messages through the appropriate libtiff handlers.
     205                 :  */
     206                 : 
     207                 : /*
     208                 :  * Error handling routines (these replace corresponding
     209                 :  * IJG routines from jerror.c).  These are used for both
     210                 :  * compression and decompression.
     211                 :  */
     212                 : static void
     213               0 : TIFFjpeg_error_exit(j_common_ptr cinfo)
     214                 : {
     215               0 :   JPEGState *sp = (JPEGState *) cinfo;  /* NB: cinfo assumed first */
     216                 :   char buffer[JMSG_LENGTH_MAX];
     217                 : 
     218               0 :   (*cinfo->err->format_message) (cinfo, buffer);
     219               0 :   TIFFErrorExt(sp->tif->tif_clientdata, "JPEGLib", "%s", buffer);   /* display the error message */
     220               0 :   jpeg_abort(cinfo);      /* clean up libjpeg state */
     221               0 :   LONGJMP(sp->exit_jmpbuf, 1);   /* return to libtiff caller */
     222                 : }
     223                 : 
     224                 : /*
     225                 :  * This routine is invoked only for warning messages,
     226                 :  * since error_exit does its own thing and trace_level
     227                 :  * is never set > 0.
     228                 :  */
     229                 : static void
     230               0 : TIFFjpeg_output_message(j_common_ptr cinfo)
     231                 : {
     232                 :   char buffer[JMSG_LENGTH_MAX];
     233                 : 
     234               0 :   (*cinfo->err->format_message) (cinfo, buffer);
     235               0 :   TIFFWarningExt(((JPEGState *) cinfo)->tif->tif_clientdata, "JPEGLib", "%s", buffer);
     236               0 : }
     237                 : 
     238                 : /*
     239                 :  * Interface routines.  This layer of routines exists
     240                 :  * primarily to limit side-effects from using setjmp.
     241                 :  * Also, normal/error returns are converted into return
     242                 :  * values per libtiff practice.
     243                 :  */
     244                 : #define CALLJPEG(sp, fail, op)  (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
     245                 : #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
     246                 : 
     247                 : static int
     248              11 : TIFFjpeg_create_compress(JPEGState* sp)
     249                 : {
     250                 :   /* initialize JPEG error handling */
     251              11 :   sp->cinfo.c.err = jpeg_std_error(&sp->err);
     252              11 :   sp->err.error_exit = TIFFjpeg_error_exit;
     253              11 :   sp->err.output_message = TIFFjpeg_output_message;
     254                 : 
     255              11 :   return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
     256                 : }
     257                 : 
     258                 : static int
     259              19 : TIFFjpeg_create_decompress(JPEGState* sp)
     260                 : {
     261                 :   /* initialize JPEG error handling */
     262              19 :   sp->cinfo.d.err = jpeg_std_error(&sp->err);
     263              19 :   sp->err.error_exit = TIFFjpeg_error_exit;
     264              19 :   sp->err.output_message = TIFFjpeg_output_message;
     265                 : 
     266              19 :   return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
     267                 : }
     268                 : 
     269                 : static int
     270              11 : TIFFjpeg_set_defaults(JPEGState* sp)
     271                 : {
     272              11 :   return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
     273                 : }
     274                 : 
     275                 : static int
     276              17 : TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
     277                 : {
     278              17 :   return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
     279                 : }
     280                 : 
     281                 : static int
     282              11 : TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
     283                 : {
     284              11 :   return CALLVJPEG(sp,
     285                 :       jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
     286                 : }
     287                 : 
     288                 : static int
     289              11 : TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
     290                 : {
     291              11 :   return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
     292                 : }
     293                 : 
     294                 : static int
     295              17 : TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
     296                 : {
     297              17 :   return CALLVJPEG(sp,
     298                 :       jpeg_start_compress(&sp->cinfo.c, write_all_tables));
     299                 : }
     300                 : 
     301                 : static int
     302            8516 : TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
     303                 : {
     304            8516 :   return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
     305                 :       scanlines, (JDIMENSION) num_lines));
     306                 : }
     307                 : 
     308                 : static int
     309               0 : TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
     310                 : {
     311               0 :   return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
     312                 :       data, (JDIMENSION) num_lines));
     313                 : }
     314                 : 
     315                 : static int
     316              17 : TIFFjpeg_finish_compress(JPEGState* sp)
     317                 : {
     318              17 :   return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
     319                 : }
     320                 : 
     321                 : static int
     322              11 : TIFFjpeg_write_tables(JPEGState* sp)
     323                 : {
     324              11 :   return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
     325                 : }
     326                 : 
     327                 : static int
     328             131 : TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
     329                 : {
     330             131 :   return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
     331                 : }
     332                 : 
     333                 : static int
     334             112 : TIFFjpeg_start_decompress(JPEGState* sp)
     335                 : {
     336             112 :   return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
     337                 : }
     338                 : 
     339                 : static int
     340           19150 : TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
     341                 : {
     342           19150 :   return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
     343                 :       scanlines, (JDIMENSION) max_lines));
     344                 : }
     345                 : 
     346                 : static int
     347               0 : TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
     348                 : {
     349               0 :   return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
     350                 :       data, (JDIMENSION) max_lines));
     351                 : }
     352                 : 
     353                 : static int
     354              92 : TIFFjpeg_finish_decompress(JPEGState* sp)
     355                 : {
     356              92 :   return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
     357                 : }
     358                 : 
     359                 : static int
     360             112 : TIFFjpeg_abort(JPEGState* sp)
     361                 : {
     362             112 :   return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
     363                 : }
     364                 : 
     365                 : static int
     366              30 : TIFFjpeg_destroy(JPEGState* sp)
     367                 : {
     368              30 :   return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
     369                 : }
     370                 : 
     371                 : static JSAMPARRAY
     372               0 : TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
     373                 :           JDIMENSION samplesperrow, JDIMENSION numrows)
     374                 : {
     375               0 :   return CALLJPEG(sp, (JSAMPARRAY) NULL,
     376                 :       (*sp->cinfo.comm.mem->alloc_sarray)
     377                 :     (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
     378                 : }
     379                 : 
     380                 : /*
     381                 :  * JPEG library destination data manager.
     382                 :  * These routines direct compressed data from libjpeg into the
     383                 :  * libtiff output buffer.
     384                 :  */
     385                 : 
     386                 : static void
     387              17 : std_init_destination(j_compress_ptr cinfo)
     388                 : {
     389              17 :   JPEGState* sp = (JPEGState*) cinfo;
     390              17 :   TIFF* tif = sp->tif;
     391                 : 
     392              17 :   sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
     393              17 :   sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
     394              17 : }
     395                 : 
     396                 : static boolean
     397               0 : std_empty_output_buffer(j_compress_ptr cinfo)
     398                 : {
     399               0 :   JPEGState* sp = (JPEGState*) cinfo;
     400               0 :   TIFF* tif = sp->tif;
     401                 : 
     402                 :   /* the entire buffer has been filled */
     403               0 :   tif->tif_rawcc = tif->tif_rawdatasize;
     404                 : 
     405                 : #ifdef IPPJ_HUFF
     406                 :        /*
     407                 :         * The Intel IPP performance library does not necessarily fill up
     408                 :         * the whole output buffer on each pass, so only dump out the parts
     409                 :         * that have been filled.
     410                 :         *   http://trac.osgeo.org/gdal/wiki/JpegIPP
     411                 :         */
     412                 :        if ( sp->dest.free_in_buffer >= 0 ) {
     413                 :                tif->tif_rawcc = tif->tif_rawdatasize - sp->dest.free_in_buffer;
     414                 :        }
     415                 : #endif
     416                 : 
     417               0 :   TIFFFlushData1(tif);
     418               0 :   sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
     419               0 :   sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
     420                 : 
     421               0 :   return (TRUE);
     422                 : }
     423                 : 
     424                 : static void
     425              17 : std_term_destination(j_compress_ptr cinfo)
     426                 : {
     427              17 :   JPEGState* sp = (JPEGState*) cinfo;
     428              17 :   TIFF* tif = sp->tif;
     429                 : 
     430              17 :   tif->tif_rawcp = (uint8*) sp->dest.next_output_byte;
     431              17 :   tif->tif_rawcc =
     432              17 :       tif->tif_rawdatasize - (tmsize_t) sp->dest.free_in_buffer;
     433                 :   /* NB: libtiff does the final buffer flush */
     434              17 : }
     435                 : 
     436                 : static void
     437              11 : TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
     438                 : {
     439                 :   (void) tif;
     440              11 :   sp->cinfo.c.dest = &sp->dest;
     441              11 :   sp->dest.init_destination = std_init_destination;
     442              11 :   sp->dest.empty_output_buffer = std_empty_output_buffer;
     443              11 :   sp->dest.term_destination = std_term_destination;
     444              11 : }
     445                 : 
     446                 : /*
     447                 :  * Alternate destination manager for outputting to JPEGTables field.
     448                 :  */
     449                 : 
     450                 : static void
     451              11 : tables_init_destination(j_compress_ptr cinfo)
     452                 : {
     453              11 :   JPEGState* sp = (JPEGState*) cinfo;
     454                 : 
     455                 :   /* while building, jpegtables_length is allocated buffer size */
     456              11 :   sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
     457              11 :   sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
     458              11 : }
     459                 : 
     460                 : static boolean
     461               0 : tables_empty_output_buffer(j_compress_ptr cinfo)
     462                 : {
     463               0 :   JPEGState* sp = (JPEGState*) cinfo;
     464                 :   void* newbuf;
     465                 : 
     466                 :   /* the entire buffer has been filled; enlarge it by 1000 bytes */
     467               0 :   newbuf = _TIFFrealloc((void*) sp->jpegtables,
     468               0 :             (tmsize_t) (sp->jpegtables_length + 1000));
     469               0 :   if (newbuf == NULL)
     470               0 :     ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
     471               0 :   sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
     472               0 :   sp->dest.free_in_buffer = (size_t) 1000;
     473               0 :   sp->jpegtables = newbuf;
     474               0 :   sp->jpegtables_length += 1000;
     475               0 :   return (TRUE);
     476                 : }
     477                 : 
     478                 : static void
     479              11 : tables_term_destination(j_compress_ptr cinfo)
     480                 : {
     481              11 :   JPEGState* sp = (JPEGState*) cinfo;
     482                 : 
     483                 :   /* set tables length to number of bytes actually emitted */
     484              11 :   sp->jpegtables_length -= (uint32) sp->dest.free_in_buffer;
     485              11 : }
     486                 : 
     487                 : static int
     488              11 : TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
     489                 : {
     490                 :   (void) tif;
     491                 :   /*
     492                 :    * Allocate a working buffer for building tables.
     493                 :    * Initial size is 1000 bytes, which is usually adequate.
     494                 :    */
     495              11 :   if (sp->jpegtables)
     496              11 :     _TIFFfree(sp->jpegtables);
     497              11 :   sp->jpegtables_length = 1000;
     498              11 :   sp->jpegtables = (void*) _TIFFmalloc((tmsize_t) sp->jpegtables_length);
     499              11 :   if (sp->jpegtables == NULL) {
     500               0 :     sp->jpegtables_length = 0;
     501               0 :     TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
     502               0 :     return (0);
     503                 :   }
     504              11 :   sp->cinfo.c.dest = &sp->dest;
     505              11 :   sp->dest.init_destination = tables_init_destination;
     506              11 :   sp->dest.empty_output_buffer = tables_empty_output_buffer;
     507              11 :   sp->dest.term_destination = tables_term_destination;
     508              11 :   return (1);
     509                 : }
     510                 : 
     511                 : /*
     512                 :  * JPEG library source data manager.
     513                 :  * These routines supply compressed data to libjpeg.
     514                 :  */
     515                 : 
     516                 : static void
     517             112 : std_init_source(j_decompress_ptr cinfo)
     518                 : {
     519             112 :   JPEGState* sp = (JPEGState*) cinfo;
     520             112 :   TIFF* tif = sp->tif;
     521                 : 
     522             112 :   sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
     523             112 :   sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
     524             112 : }
     525                 : 
     526                 : static boolean
     527               0 : std_fill_input_buffer(j_decompress_ptr cinfo)
     528                 : {
     529               0 :   JPEGState* sp = (JPEGState* ) cinfo;
     530                 :   static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
     531                 : 
     532                 : #ifdef IPPJ_HUFF
     533                 :    /*
     534                 :     * The Intel IPP performance library does not necessarily read the whole
     535                 :     * input buffer in one pass, so it is possible to get here with data
     536                 :     * yet to read. 
     537                 :     * 
     538                 :     * We just return without doing anything, until the entire buffer has been
     539                 :     * read. Because the whole input tile is read into memory
     540                 :     * we never need to "fill" the buffer, as init_source does that.
     541                 :     * http://trac.osgeo.org/gdal/wiki/JpegIPP
     542                 :     */
     543                 :         if( sp->src.bytes_in_buffer > 0 ) {
     544                 :             return (TRUE);
     545                 :         }
     546                 : #endif
     547                 : 
     548                 :   /*
     549                 :    * Should never get here since entire strip/tile is
     550                 :    * read into memory before the decompressor is called,
     551                 :    * and thus was supplied by init_source.
     552                 :    */
     553               0 :   WARNMS(cinfo, JWRN_JPEG_EOF);
     554                 :   /* insert a fake EOI marker */
     555               0 :   sp->src.next_input_byte = dummy_EOI;
     556               0 :   sp->src.bytes_in_buffer = 2;
     557               0 :   return (TRUE);
     558                 : }
     559                 : 
     560                 : static void
     561               0 : std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
     562                 : {
     563               0 :   JPEGState* sp = (JPEGState*) cinfo;
     564                 : 
     565               0 :   if (num_bytes > 0) {
     566               0 :     if ((size_t)num_bytes > sp->src.bytes_in_buffer) {
     567                 :       /* oops, buffer overrun */
     568               0 :       (void) std_fill_input_buffer(cinfo);
     569                 :     } else {
     570               0 :       sp->src.next_input_byte += (size_t) num_bytes;
     571               0 :       sp->src.bytes_in_buffer -= (size_t) num_bytes;
     572                 :     }
     573                 :   }
     574               0 : }
     575                 : 
     576                 : static void
     577              92 : std_term_source(j_decompress_ptr cinfo)
     578                 : {
     579                 :   /* No work necessary here */
     580                 :   /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
     581                 :   /* (if so, need empty tables_term_source!) */
     582                 :   (void) cinfo;
     583              92 : }
     584                 : 
     585                 : static void
     586              38 : TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
     587                 : {
     588                 :   (void) tif;
     589              38 :   sp->cinfo.d.src = &sp->src;
     590              38 :   sp->src.init_source = std_init_source;
     591              38 :   sp->src.fill_input_buffer = std_fill_input_buffer;
     592              38 :   sp->src.skip_input_data = std_skip_input_data;
     593              38 :   sp->src.resync_to_restart = jpeg_resync_to_restart;
     594              38 :   sp->src.term_source = std_term_source;
     595              38 :   sp->src.bytes_in_buffer = 0;   /* for safety */
     596              38 :   sp->src.next_input_byte = NULL;
     597              38 : }
     598                 : 
     599                 : /*
     600                 :  * Alternate source manager for reading from JPEGTables.
     601                 :  * We can share all the code except for the init routine.
     602                 :  */
     603                 : 
     604                 : static void
     605              19 : tables_init_source(j_decompress_ptr cinfo)
     606                 : {
     607              19 :   JPEGState* sp = (JPEGState*) cinfo;
     608                 : 
     609              19 :   sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
     610              19 :   sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
     611              19 : }
     612                 : 
     613                 : static void
     614              19 : TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
     615                 : {
     616              19 :   TIFFjpeg_data_src(sp, tif);
     617              19 :   sp->src.init_source = tables_init_source;
     618              19 : }
     619                 : 
     620                 : /*
     621                 :  * Allocate downsampled-data buffers needed for downsampled I/O.
     622                 :  * We use values computed in jpeg_start_compress or jpeg_start_decompress.
     623                 :  * We use libjpeg's allocator so that buffers will be released automatically
     624                 :  * when done with strip/tile.
     625                 :  * This is also a handy place to compute samplesperclump, bytesperline.
     626                 :  */
     627                 : static int
     628               0 : alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
     629                 :         int num_components)
     630                 : {
     631               0 :   JPEGState* sp = JState(tif);
     632                 :   int ci;
     633                 :   jpeg_component_info* compptr;
     634                 :   JSAMPARRAY buf;
     635               0 :   int samples_per_clump = 0;
     636                 : 
     637               0 :   for (ci = 0, compptr = comp_info; ci < num_components;
     638               0 :        ci++, compptr++) {
     639               0 :     samples_per_clump += compptr->h_samp_factor *
     640                 :       compptr->v_samp_factor;
     641               0 :     buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
     642                 :         compptr->width_in_blocks * DCTSIZE,
     643               0 :         (JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
     644               0 :     if (buf == NULL)
     645               0 :       return (0);
     646               0 :     sp->ds_buffer[ci] = buf;
     647                 :   }
     648               0 :   sp->samplesperclump = samples_per_clump;
     649               0 :   return (1);
     650                 : }
     651                 : 
     652                 : 
     653                 : /*
     654                 :  * JPEG Decoding.
     655                 :  */
     656                 : 
     657                 : #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
     658                 : 
     659                 : #define JPEG_MARKER_SOF0 0xC0
     660                 : #define JPEG_MARKER_SOF1 0xC1
     661                 : #define JPEG_MARKER_SOF3 0xC3
     662                 : #define JPEG_MARKER_DHT 0xC4
     663                 : #define JPEG_MARKER_SOI 0xD8
     664                 : #define JPEG_MARKER_SOS 0xDA
     665                 : #define JPEG_MARKER_DQT 0xDB
     666                 : #define JPEG_MARKER_DRI 0xDD
     667                 : #define JPEG_MARKER_APP0 0xE0
     668                 : #define JPEG_MARKER_COM 0xFE
     669                 : struct JPEGFixupTagsSubsamplingData
     670                 : {
     671                 :   TIFF* tif;
     672                 :   void* buffer;
     673                 :   uint32 buffersize;
     674                 :   uint8* buffercurrentbyte;
     675                 :   uint32 bufferbytesleft;
     676                 :   uint64 fileoffset;
     677                 :   uint64 filebytesleft;
     678                 :   uint8 filepositioned;
     679                 : };
     680                 : static void JPEGFixupTagsSubsampling(TIFF* tif);
     681                 : static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data);
     682                 : static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result);
     683                 : static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result);
     684                 : static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength);
     685                 : 
     686                 : #endif
     687                 : 
     688                 : static int
     689              70 : JPEGFixupTags(TIFF* tif)
     690                 : {
     691                 :   #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
     692             204 :   if ((tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR)&&
     693              67 :       (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&&
     694              67 :       (tif->tif_dir.td_samplesperpixel==3))
     695              67 :     JPEGFixupTagsSubsampling(tif);
     696                 :   #endif
     697              70 :   return(1);
     698                 : }
     699                 : 
     700                 : #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
     701                 : 
     702                 : static void
     703              67 : JPEGFixupTagsSubsampling(TIFF* tif)
     704                 : {
     705                 :   /*
     706                 :    * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
     707                 :    * the TIFF tags, but still use non-default (2,2) values within the jpeg
     708                 :    * data stream itself.  In order for TIFF applications to work properly
     709                 :    * - for instance to get the strip buffer size right - it is imperative
     710                 :    * that the subsampling be available before we start reading the image
     711                 :    * data normally.  This function will attempt to analyze the first strip in
     712                 :    * order to get the sampling values from the jpeg data stream.
     713                 :    *
     714                 :    * Note that JPEGPreDeocode() will produce a fairly loud warning when the
     715                 :    * discovered sampling does not match the default sampling (2,2) or whatever
     716                 :    * was actually in the tiff tags.
     717                 :    *
     718                 :    * See the bug in bugzilla for details:
     719                 :    *
     720                 :    * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
     721                 :    *
     722                 :    * Frank Warmerdam, July 2002
     723                 :    * Joris Van Damme, May 2007
     724                 :    */
     725                 :   static const char module[] = "JPEGFixupTagsSubsampling";
     726                 :   struct JPEGFixupTagsSubsamplingData m;
     727                 : 
     728             134 :         if( tif->tif_dir.td_stripbytecount == NULL
     729             134 :             || tif->tif_dir.td_stripbytecount[0] == 0 )
     730                 :         {
     731                 :             /* Do not even try to check if the first strip/tile does not
     732                 :                yet exist, as occurs when GDAL has created a new NULL file
     733                 :                for instance. */
     734              20 :             return;
     735                 :         }
     736                 : 
     737              47 :   m.tif=tif;
     738              47 :   m.buffersize=2048;
     739              47 :   m.buffer=_TIFFmalloc(m.buffersize);
     740              47 :   if (m.buffer==NULL)
     741                 :   {
     742               0 :     TIFFWarningExt(tif->tif_clientdata,module,
     743                 :         "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
     744               0 :     return;
     745                 :   }
     746              47 :   m.buffercurrentbyte=NULL;
     747              47 :   m.bufferbytesleft=0;
     748              47 :   m.fileoffset=tif->tif_dir.td_stripoffset[0];
     749              47 :   m.filepositioned=0;
     750              47 :   m.filebytesleft=tif->tif_dir.td_stripbytecount[0];
     751              47 :   if (!JPEGFixupTagsSubsamplingSec(&m))
     752               0 :     TIFFWarningExt(tif->tif_clientdata,module,
     753                 :         "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
     754              47 :   _TIFFfree(m.buffer);
     755                 : }
     756                 : 
     757                 : static int
     758              94 : JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
     759                 : {
     760                 :   static const char module[] = "JPEGFixupTagsSubsamplingSec";
     761                 :   uint8 m;
     762                 :   while (1)
     763                 :   {
     764                 :     while (1)
     765                 :     {
     766              94 :       if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
     767               0 :         return(0);
     768              94 :       if (m==255)
     769              94 :         break;
     770               0 :     }
     771                 :     while (1)
     772                 :     {
     773              94 :       if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
     774               0 :         return(0);
     775              94 :       if (m!=255)
     776                 :         break;
     777               0 :     }
     778              94 :     switch (m)
     779                 :     {
     780                 :       case JPEG_MARKER_SOI:
     781                 :         /* this type of marker has no data and should be skipped */
     782              47 :         break;
     783                 :       case JPEG_MARKER_COM:
     784                 :       case JPEG_MARKER_APP0:
     785                 :       case JPEG_MARKER_APP0+1:
     786                 :       case JPEG_MARKER_APP0+2:
     787                 :       case JPEG_MARKER_APP0+3:
     788                 :       case JPEG_MARKER_APP0+4:
     789                 :       case JPEG_MARKER_APP0+5:
     790                 :       case JPEG_MARKER_APP0+6:
     791                 :       case JPEG_MARKER_APP0+7:
     792                 :       case JPEG_MARKER_APP0+8:
     793                 :       case JPEG_MARKER_APP0+9:
     794                 :       case JPEG_MARKER_APP0+10:
     795                 :       case JPEG_MARKER_APP0+11:
     796                 :       case JPEG_MARKER_APP0+12:
     797                 :       case JPEG_MARKER_APP0+13:
     798                 :       case JPEG_MARKER_APP0+14:
     799                 :       case JPEG_MARKER_APP0+15:
     800                 :       case JPEG_MARKER_DQT:
     801                 :       case JPEG_MARKER_SOS:
     802                 :       case JPEG_MARKER_DHT:
     803                 :       case JPEG_MARKER_DRI:
     804                 :         /* this type of marker has data, but it has no use to us and should be skipped */
     805                 :         {
     806                 :           uint16 n;
     807               0 :           if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
     808               0 :             return(0);
     809               0 :           if (n<2)
     810               0 :             return(0);
     811               0 :           n-=2;
     812               0 :           if (n>0)
     813               0 :             JPEGFixupTagsSubsamplingSkip(data,n);
     814                 :         }
     815               0 :         break;
     816                 :       case JPEG_MARKER_SOF0:
     817                 :       case JPEG_MARKER_SOF1:
     818                 :         /* this marker contains the subsampling factors we're scanning for */
     819                 :         {
     820                 :           uint16 n;
     821                 :           uint16 o;
     822                 :           uint8 p;
     823                 :           uint8 ph,pv;
     824              47 :           if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
     825               0 :             return(0);
     826              47 :           if (n!=8+data->tif->tif_dir.td_samplesperpixel*3)
     827               0 :             return(0);
     828              47 :           JPEGFixupTagsSubsamplingSkip(data,7);
     829              47 :           if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
     830               0 :             return(0);
     831              47 :           ph=(p>>4);
     832              47 :           pv=(p&15);
     833              47 :           JPEGFixupTagsSubsamplingSkip(data,1);
     834             141 :           for (o=1; o<data->tif->tif_dir.td_samplesperpixel; o++)
     835                 :           {
     836              94 :             JPEGFixupTagsSubsamplingSkip(data,1);
     837              94 :             if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
     838               0 :               return(0);
     839              94 :             if (p!=0x11)
     840                 :             {
     841               0 :               TIFFWarningExt(data->tif->tif_clientdata,module,
     842                 :                   "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
     843               0 :               return(1);
     844                 :             }
     845              94 :             JPEGFixupTagsSubsamplingSkip(data,1);
     846                 :           }
     847              47 :           if (((ph!=1)&&(ph!=2)&&(ph!=4))||((pv!=1)&&(pv!=2)&&(pv!=4)))
     848                 :           {
     849               0 :             TIFFWarningExt(data->tif->tif_clientdata,module,
     850                 :                 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
     851               0 :             return(1);
     852                 :           }
     853              47 :           if ((ph!=data->tif->tif_dir.td_ycbcrsubsampling[0])||(pv!=data->tif->tif_dir.td_ycbcrsubsampling[1]))
     854                 :           {
     855               0 :             TIFFWarningExt(data->tif->tif_clientdata,module,
     856                 :                 "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
     857               0 :                 (int)data->tif->tif_dir.td_ycbcrsubsampling[0],
     858               0 :                 (int)data->tif->tif_dir.td_ycbcrsubsampling[1],
     859                 :                 (int)ph,(int)pv);
     860               0 :             data->tif->tif_dir.td_ycbcrsubsampling[0]=ph;
     861               0 :             data->tif->tif_dir.td_ycbcrsubsampling[1]=pv;
     862                 :           }
     863                 :         }
     864              47 :         return(1);
     865                 :       default:
     866               0 :         return(0);
     867                 :     }
     868              47 :   }
     869                 : }
     870                 : 
     871                 : static int
     872             423 : JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result)
     873                 : {
     874             423 :   if (data->bufferbytesleft==0)
     875                 :   {
     876                 :     uint32 m;
     877              47 :     if (data->filebytesleft==0)
     878               0 :       return(0);
     879              47 :     if (!data->filepositioned)
     880                 :     {
     881              47 :       TIFFSeekFile(data->tif,data->fileoffset,SEEK_SET);
     882              47 :       data->filepositioned=1;
     883                 :     }
     884              47 :     m=data->buffersize;
     885              47 :     if ((uint64)m>data->filebytesleft)
     886              28 :       m=(uint32)data->filebytesleft;
     887              47 :     assert(m<0x80000000UL);
     888              47 :     if (TIFFReadFile(data->tif,data->buffer,(tmsize_t)m)!=(tmsize_t)m)
     889               0 :       return(0);
     890              47 :     data->buffercurrentbyte=data->buffer;
     891              47 :     data->bufferbytesleft=m;
     892              47 :     data->fileoffset+=m;
     893              47 :     data->filebytesleft-=m;
     894                 :   }
     895             423 :   *result=*data->buffercurrentbyte;
     896             423 :   data->buffercurrentbyte++;
     897             423 :   data->bufferbytesleft--;
     898             423 :   return(1);
     899                 : }
     900                 : 
     901                 : static int
     902              47 : JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result)
     903                 : {
     904                 :   uint8 ma;
     905                 :   uint8 mb;
     906              47 :   if (!JPEGFixupTagsSubsamplingReadByte(data,&ma))
     907               0 :     return(0);
     908              47 :   if (!JPEGFixupTagsSubsamplingReadByte(data,&mb))
     909               0 :     return(0);
     910              47 :   *result=(ma<<8)|mb;
     911              47 :   return(1);
     912                 : }
     913                 : 
     914                 : static void
     915             282 : JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength)
     916                 : {
     917             282 :   if ((uint32)skiplength<=data->bufferbytesleft)
     918                 :   {
     919             282 :     data->buffercurrentbyte+=skiplength;
     920             282 :     data->bufferbytesleft-=skiplength;
     921                 :   }
     922                 :   else
     923                 :   {
     924                 :     uint16 m;
     925               0 :     m=skiplength-data->bufferbytesleft;
     926               0 :     if (m<=data->filebytesleft)
     927                 :     {
     928               0 :       data->bufferbytesleft=0;
     929               0 :       data->fileoffset+=m;
     930               0 :       data->filebytesleft-=m;
     931               0 :       data->filepositioned=0;
     932                 :     }
     933                 :     else
     934                 :     {
     935               0 :       data->bufferbytesleft=0;
     936               0 :       data->filebytesleft=0;
     937                 :     }
     938                 :   }
     939             282 : }
     940                 : 
     941                 : #endif
     942                 : 
     943                 : 
     944                 : static int
     945              22 : JPEGSetupDecode(TIFF* tif)
     946                 : {
     947              22 :   JPEGState* sp = JState(tif);
     948              22 :   TIFFDirectory *td = &tif->tif_dir;
     949                 : 
     950                 : #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
     951              19 :         if( tif->tif_dir.td_bitspersample == 12 )
     952               3 :             return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 0 );
     953                 : #endif
     954                 : 
     955              19 :   JPEGInitializeLibJPEG( tif, TRUE );
     956                 : 
     957              19 :   assert(sp != NULL);
     958              19 :   assert(sp->cinfo.comm.is_decompressor);
     959                 : 
     960                 :   /* Read JPEGTables if it is present */
     961              19 :   if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
     962              19 :     TIFFjpeg_tables_src(sp, tif);
     963              19 :     if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
     964               0 :       TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
     965               0 :       return (0);
     966                 :     }
     967                 :   }
     968                 : 
     969                 :   /* Grab parameters that are same for all strips/tiles */
     970              19 :   sp->photometric = td->td_photometric;
     971              19 :   switch (sp->photometric) {
     972                 :   case PHOTOMETRIC_YCBCR:
     973              18 :     sp->h_sampling = td->td_ycbcrsubsampling[0];
     974              18 :     sp->v_sampling = td->td_ycbcrsubsampling[1];
     975              18 :     break;
     976                 :   default:
     977                 :     /* TIFF 6.0 forbids subsampling of all other color spaces */
     978               1 :     sp->h_sampling = 1;
     979               1 :     sp->v_sampling = 1;
     980                 :     break;
     981                 :   }
     982                 : 
     983                 :   /* Set up for reading normal data */
     984              19 :   TIFFjpeg_data_src(sp, tif);
     985              19 :   tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
     986              19 :   return (1);
     987                 : }
     988                 : 
     989                 : /*
     990                 :  * Set up for decoding a strip or tile.
     991                 :  */
     992                 : static int
     993             112 : JPEGPreDecode(TIFF* tif, uint16 s)
     994                 : {
     995             112 :   JPEGState *sp = JState(tif);
     996             112 :   TIFFDirectory *td = &tif->tif_dir;
     997                 :   static const char module[] = "JPEGPreDecode";
     998                 :   uint32 segment_width, segment_height;
     999                 :   int downsampled_output;
    1000                 :   int ci;
    1001                 : 
    1002             112 :   assert(sp != NULL);
    1003                 :   
    1004             112 :   if (sp->cinfo.comm.is_decompressor == 0)
    1005                 :   {
    1006               0 :     tif->tif_setupdecode( tif );
    1007                 :   }
    1008                 :   
    1009             112 :   assert(sp->cinfo.comm.is_decompressor);
    1010                 :   /*
    1011                 :    * Reset decoder state from any previous strip/tile,
    1012                 :    * in case application didn't read the whole strip.
    1013                 :    */
    1014             112 :   if (!TIFFjpeg_abort(sp))
    1015               0 :     return (0);
    1016                 :   /*
    1017                 :    * Read the header for this strip/tile.
    1018                 :    */
    1019             112 :   if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
    1020               0 :     return (0);
    1021                 :   /*
    1022                 :    * Check image parameters and set decompression parameters.
    1023                 :    */
    1024             112 :   segment_width = td->td_imagewidth;
    1025             112 :   segment_height = td->td_imagelength - tif->tif_row;
    1026             112 :   if (isTiled(tif)) {
    1027              24 :                 segment_width = td->td_tilewidth;
    1028              24 :                 segment_height = td->td_tilelength;
    1029              24 :     sp->bytesperline = TIFFTileRowSize(tif);
    1030                 :   } else {
    1031              88 :     if (segment_height > td->td_rowsperstrip)
    1032              74 :       segment_height = td->td_rowsperstrip;
    1033              88 :     sp->bytesperline = TIFFScanlineSize(tif);
    1034                 :   }
    1035             112 :   if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
    1036                 :     /*
    1037                 :      * For PC 2, scale down the expected strip/tile size
    1038                 :      * to match a downsampled component
    1039                 :      */
    1040               0 :     segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
    1041               0 :     segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
    1042                 :   }
    1043             224 :   if (sp->cinfo.d.image_width < segment_width ||
    1044             112 :       sp->cinfo.d.image_height < segment_height) {
    1045               0 :     TIFFWarningExt(tif->tif_clientdata, module,
    1046                 :              "Improper JPEG strip/tile size, "
    1047                 :              "expected %dx%d, got %dx%d",
    1048                 :              segment_width, segment_height,
    1049                 :              sp->cinfo.d.image_width,
    1050                 :              sp->cinfo.d.image_height);
    1051                 :   } 
    1052             224 :   if (sp->cinfo.d.image_width > segment_width ||
    1053             112 :       sp->cinfo.d.image_height > segment_height) {
    1054                 :     /*
    1055                 :      * This case could be dangerous, if the strip or tile size has
    1056                 :      * been reported as less than the amount of data jpeg will
    1057                 :      * return, some potential security issues arise. Catch this
    1058                 :      * case and error out.
    1059                 :      */
    1060               0 :     TIFFErrorExt(tif->tif_clientdata, module,
    1061                 :            "JPEG strip/tile size exceeds expected dimensions,"
    1062                 :            " expected %dx%d, got %dx%d",
    1063                 :            segment_width, segment_height,
    1064                 :            sp->cinfo.d.image_width, sp->cinfo.d.image_height);
    1065               0 :     return (0);
    1066                 :   }
    1067             336 :   if (sp->cinfo.d.num_components !=
    1068             112 :       (td->td_planarconfig == PLANARCONFIG_CONTIG ?
    1069             112 :        td->td_samplesperpixel : 1)) {
    1070               0 :     TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG component count");
    1071               0 :     return (0);
    1072                 :   }
    1073                 : #ifdef JPEG_LIB_MK1
    1074                 :   if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
    1075                 :     TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
    1076                 :     return (0);
    1077                 :   }
    1078                 :   sp->cinfo.d.data_precision = td->td_bitspersample;
    1079                 :   sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
    1080                 : #else
    1081             112 :   if (sp->cinfo.d.data_precision != td->td_bitspersample) {
    1082               0 :     TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
    1083               0 :     return (0);
    1084                 :   }
    1085                 : #endif
    1086             112 :   if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
    1087                 :     /* Component 0 should have expected sampling factors */
    1088             224 :     if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
    1089             112 :         sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
    1090               0 :         TIFFWarningExt(tif->tif_clientdata, module,
    1091                 :             "Improper JPEG sampling factors %d,%d\n"
    1092                 :             "Apparently should be %d,%d.",
    1093               0 :             sp->cinfo.d.comp_info[0].h_samp_factor,
    1094               0 :             sp->cinfo.d.comp_info[0].v_samp_factor,
    1095               0 :             sp->h_sampling, sp->v_sampling);
    1096                 : 
    1097                 :         /*
    1098                 :          * There are potential security issues here
    1099                 :          * for decoders that have already allocated
    1100                 :          * buffers based on the expected sampling
    1101                 :          * factors. Lets check the sampling factors
    1102                 :          * dont exceed what we were expecting.
    1103                 :          */
    1104               0 :         if (sp->cinfo.d.comp_info[0].h_samp_factor
    1105                 :           > sp->h_sampling
    1106               0 :             || sp->cinfo.d.comp_info[0].v_samp_factor
    1107               0 :           > sp->v_sampling) {
    1108               0 :           TIFFErrorExt(tif->tif_clientdata,
    1109                 :                  module,
    1110                 :           "Cannot honour JPEG sampling factors"
    1111                 :           " that exceed those specified.");
    1112               0 :           return (0);
    1113                 :         }
    1114                 : 
    1115                 :           /*
    1116                 :            * XXX: Files written by the Intergraph software
    1117                 :            * has different sampling factors stored in the
    1118                 :            * TIFF tags and in the JPEG structures. We will
    1119                 :            * try to deduce Intergraph files by the presense
    1120                 :            * of the tag 33918.
    1121                 :            */
    1122               0 :           if (!TIFFFindField(tif, 33918, TIFF_ANY)) {
    1123               0 :           TIFFWarningExt(tif->tif_clientdata, module,
    1124                 :           "Decompressor will try reading with "
    1125                 :           "sampling %d,%d.",
    1126               0 :           sp->cinfo.d.comp_info[0].h_samp_factor,
    1127               0 :           sp->cinfo.d.comp_info[0].v_samp_factor);
    1128                 : 
    1129               0 :             sp->h_sampling = (uint16)
    1130               0 :           sp->cinfo.d.comp_info[0].h_samp_factor;
    1131               0 :             sp->v_sampling = (uint16)
    1132               0 :           sp->cinfo.d.comp_info[0].v_samp_factor;
    1133                 :           }
    1134                 :     }
    1135                 :     /* Rest should have sampling factors 1,1 */
    1136             332 :     for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
    1137             440 :       if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
    1138             220 :           sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
    1139               0 :         TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
    1140               0 :         return (0);
    1141                 :       }
    1142                 :     }
    1143                 :   } else {
    1144                 :     /* PC 2's single component should have sampling factors 1,1 */
    1145               0 :     if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
    1146               0 :         sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
    1147               0 :       TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
    1148               0 :       return (0);
    1149                 :     }
    1150                 :   }
    1151             112 :   downsampled_output = FALSE;
    1152             444 :   if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
    1153             112 :       sp->photometric == PHOTOMETRIC_YCBCR &&
    1154             110 :       sp->jpegcolormode == JPEGCOLORMODE_RGB) {
    1155                 :   /* Convert YCbCr to RGB */
    1156             110 :     sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
    1157             110 :     sp->cinfo.d.out_color_space = JCS_RGB;
    1158                 :   } else {
    1159                 :       /* Suppress colorspace handling */
    1160               2 :     sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
    1161               2 :     sp->cinfo.d.out_color_space = JCS_UNKNOWN;
    1162               6 :     if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
    1163               4 :         (sp->h_sampling != 1 || sp->v_sampling != 1))
    1164               0 :       downsampled_output = TRUE;
    1165                 :     /* XXX what about up-sampling? */
    1166                 :   }
    1167             112 :   if (downsampled_output) {
    1168                 :     /* Need to use raw-data interface to libjpeg */
    1169               0 :     sp->cinfo.d.raw_data_out = TRUE;
    1170               0 :     tif->tif_decoderow = DecodeRowError;
    1171               0 :     tif->tif_decodestrip = JPEGDecodeRaw;
    1172               0 :     tif->tif_decodetile = JPEGDecodeRaw;
    1173                 :   } else {
    1174                 :     /* Use normal interface to libjpeg */
    1175             112 :     sp->cinfo.d.raw_data_out = FALSE;
    1176             112 :     tif->tif_decoderow = JPEGDecode;
    1177             112 :     tif->tif_decodestrip = JPEGDecode;
    1178             112 :     tif->tif_decodetile = JPEGDecode;  
    1179                 :   }
    1180                 :   /* Start JPEG decompressor */
    1181             112 :   if (!TIFFjpeg_start_decompress(sp))
    1182               0 :     return (0);
    1183                 :   /* Allocate downsampled-data buffers if needed */
    1184             112 :   if (downsampled_output) {
    1185               0 :     if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
    1186                 :                  sp->cinfo.d.num_components))
    1187               0 :       return (0);
    1188               0 :     sp->scancount = DCTSIZE; /* mark buffer empty */
    1189                 :   }
    1190             112 :   return (1);
    1191                 : }
    1192                 : 
    1193                 : /*
    1194                 :  * Decode a chunk of pixels.
    1195                 :  * "Standard" case: returned data is not downsampled.
    1196                 :  */
    1197                 : /*ARGSUSED*/ static int
    1198            9302 : JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
    1199                 : {
    1200            9302 :   JPEGState *sp = JState(tif);
    1201                 :   tmsize_t nrows;
    1202                 :   (void) s;
    1203                 : 
    1204            9302 :   nrows = cc / sp->bytesperline;
    1205            9302 :   if (cc % sp->bytesperline)
    1206               0 :     TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
    1207                 : 
    1208            9302 :   if( nrows > (tmsize_t) sp->cinfo.d.image_height )
    1209               0 :     nrows = sp->cinfo.d.image_height;
    1210                 : 
    1211                 :   /* data is expected to be read in multiples of a scanline */
    1212            9302 :   if (nrows)
    1213                 :   {
    1214            9302 :     JSAMPROW line_work_buf = NULL;
    1215                 : 
    1216                 :     /*
    1217                 :      * For 6B, only use temporary buffer for 12 bit imagery.
    1218                 :      * For Mk1 always use it.
    1219                 :      */
    1220                 : #if !defined(JPEG_LIB_MK1)
    1221            9302 :     if( sp->cinfo.d.data_precision == 12 )
    1222                 : #endif
    1223                 :     {
    1224               3 :       line_work_buf = (JSAMPROW)
    1225               3 :           _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
    1226                 :           * sp->cinfo.d.num_components );
    1227                 :     }
    1228                 : 
    1229                 :     do {
    1230           19150 :       if( line_work_buf != NULL )
    1231                 :       {
    1232                 :         /*
    1233                 :          * In the MK1 case, we aways read into a 16bit buffer, and then
    1234                 :          * pack down to 12bit or 8bit.  In 6B case we only read into 16
    1235                 :          * bit buffer for 12bit data, which we need to repack.
    1236                 :         */
    1237             192 :         if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
    1238               0 :           return (0);
    1239                 : 
    1240             192 :         if( sp->cinfo.d.data_precision == 12 )
    1241                 :         {
    1242             192 :           int value_pairs = (sp->cinfo.d.output_width
    1243             192 :               * sp->cinfo.d.num_components) / 2;
    1244                 :           int iPair;
    1245                 : 
    1246           18624 :           for( iPair = 0; iPair < value_pairs; iPair++ )
    1247                 :           {
    1248                 :             unsigned char *out_ptr =
    1249           18432 :                 ((unsigned char *) buf) + iPair * 3;
    1250           18432 :             JSAMPLE *in_ptr = line_work_buf + iPair * 2;
    1251                 : 
    1252           18432 :             out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
    1253           36864 :             out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
    1254           18432 :                 | ((in_ptr[1] & 0xf00) >> 8);
    1255           18432 :             out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
    1256                 :           }
    1257                 :         }
    1258               0 :         else if( sp->cinfo.d.data_precision == 8 )
    1259                 :         {
    1260               0 :           int value_count = (sp->cinfo.d.output_width
    1261               0 :               * sp->cinfo.d.num_components);
    1262                 :           int iValue;
    1263                 : 
    1264               0 :           for( iValue = 0; iValue < value_count; iValue++ )
    1265                 :           {
    1266               0 :             ((unsigned char *) buf)[iValue] =
    1267               0 :                 line_work_buf[iValue] & 0xff;
    1268                 :           }
    1269                 :         }
    1270                 :       }
    1271                 :       else
    1272                 :       {
    1273                 :         /*
    1274                 :          * In the libjpeg6b 8bit case.  We read directly into the
    1275                 :          * TIFF buffer.
    1276                 :         */
    1277           18958 :         JSAMPROW bufptr = (JSAMPROW)buf;
    1278                 : 
    1279           18958 :         if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
    1280               0 :           return (0);
    1281                 :       }
    1282                 : 
    1283           19150 :       ++tif->tif_row;
    1284           19150 :       buf += sp->bytesperline;
    1285           19150 :       cc -= sp->bytesperline;
    1286           19150 :     } while (--nrows > 0);
    1287                 : 
    1288            9302 :     if( line_work_buf != NULL )
    1289               3 :       _TIFFfree( line_work_buf );
    1290                 :   }
    1291                 : 
    1292                 :   /* Close down the decompressor if we've finished the strip or tile. */
    1293            9394 :   return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
    1294            9394 :       || TIFFjpeg_finish_decompress(sp);
    1295                 : }
    1296                 : 
    1297                 : /*ARGSUSED*/ static int
    1298               0 : DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
    1299                 : 
    1300                 : {
    1301                 :     (void) buf;
    1302                 :     (void) cc;
    1303                 :     (void) s;
    1304                 : 
    1305               0 :     TIFFErrorExt(tif->tif_clientdata, "TIFFReadScanline",
    1306                 :                  "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
    1307               0 :     return 0;
    1308                 : }
    1309                 : 
    1310                 : /*
    1311                 :  * Decode a chunk of pixels.
    1312                 :  * Returned data is downsampled per sampling factors.
    1313                 :  */
    1314                 : /*ARGSUSED*/ static int
    1315               0 : JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
    1316                 : {
    1317               0 :   JPEGState *sp = JState(tif);
    1318                 :   tmsize_t nrows;
    1319                 :   (void) s;
    1320                 : 
    1321                 :   /* data is expected to be read in multiples of a scanline */
    1322               0 :   if ( (nrows = sp->cinfo.d.image_height) ) {
    1323                 : 
    1324                 :     /* Cb,Cr both have sampling factors 1, so this is correct */
    1325               0 :     JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;            
    1326               0 :     int samples_per_clump = sp->samplesperclump;
    1327                 : 
    1328                 : #if defined(JPEG_LIB_MK1_OR_12BIT)
    1329               0 :     unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
    1330                 :         sp->cinfo.d.output_width *
    1331               0 :         sp->cinfo.d.num_components);
    1332                 : #endif
    1333                 : 
    1334                 :     do {
    1335                 :       jpeg_component_info *compptr;
    1336                 :       int ci, clumpoffset;
    1337                 : 
    1338               0 :                         if( cc < sp->bytesperline * sp->v_sampling ) {
    1339               0 :                             TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
    1340                 :                                          "application buffer not large enough for all data.");
    1341               0 :                             return 0;
    1342                 :                         }
    1343                 : 
    1344                 :       /* Reload downsampled-data buffer if needed */
    1345               0 :       if (sp->scancount >= DCTSIZE) {
    1346               0 :         int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
    1347               0 :         if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
    1348               0 :           return (0);
    1349               0 :         sp->scancount = 0;
    1350                 :       }
    1351                 :       /*
    1352                 :        * Fastest way to unseparate data is to make one pass
    1353                 :        * over the scanline for each row of each component.
    1354                 :        */
    1355               0 :       clumpoffset = 0;    /* first sample in clump */
    1356               0 :       for (ci = 0, compptr = sp->cinfo.d.comp_info;
    1357               0 :           ci < sp->cinfo.d.num_components;
    1358               0 :           ci++, compptr++) {
    1359               0 :         int hsamp = compptr->h_samp_factor;
    1360               0 :         int vsamp = compptr->v_samp_factor;
    1361                 :         int ypos;
    1362                 : 
    1363               0 :         for (ypos = 0; ypos < vsamp; ypos++) {
    1364               0 :           JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
    1365                 : #if defined(JPEG_LIB_MK1_OR_12BIT)
    1366               0 :           JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
    1367                 : #else
    1368               0 :           JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
    1369                 : #endif
    1370                 :           JDIMENSION nclump;
    1371                 : 
    1372               0 :           if (hsamp == 1) {
    1373                 :             /* fast path for at least Cb and Cr */
    1374               0 :             for (nclump = clumps_per_line; nclump-- > 0; ) {
    1375               0 :               outptr[0] = *inptr++;
    1376               0 :               outptr += samples_per_clump;
    1377                 :             }
    1378                 :           } else {
    1379                 :             int xpos;
    1380                 : 
    1381                 :       /* general case */
    1382               0 :             for (nclump = clumps_per_line; nclump-- > 0; ) {
    1383               0 :               for (xpos = 0; xpos < hsamp; xpos++)
    1384               0 :                 outptr[xpos] = *inptr++;
    1385               0 :               outptr += samples_per_clump;
    1386                 :             }
    1387                 :           }
    1388               0 :           clumpoffset += hsamp;
    1389                 :         }
    1390                 :       }
    1391                 : 
    1392                 : #if defined(JPEG_LIB_MK1_OR_12BIT)
    1393                 :       {
    1394               0 :         if (sp->cinfo.d.data_precision == 8)
    1395                 :         {
    1396               0 :           int i=0;
    1397               0 :           int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
    1398               0 :           for (i=0; i<len; i++)
    1399                 :           {
    1400               0 :             ((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
    1401                 :           }
    1402                 :         }
    1403                 :         else
    1404                 :         {         // 12-bit
    1405               0 :           int value_pairs = (sp->cinfo.d.output_width
    1406               0 :               * sp->cinfo.d.num_components) / 2;
    1407                 :           int iPair;
    1408               0 :           for( iPair = 0; iPair < value_pairs; iPair++ )
    1409                 :           {
    1410               0 :             unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
    1411               0 :             JSAMPLE *in_ptr = (JSAMPLE *) (tmpbuf + iPair * 2);
    1412               0 :             out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
    1413               0 :             out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
    1414               0 :                 | ((in_ptr[1] & 0xf00) >> 8);
    1415               0 :             out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
    1416                 :           }
    1417                 :         }
    1418                 :       }
    1419                 : #endif
    1420                 : 
    1421               0 :       sp->scancount ++;
    1422               0 :       tif->tif_row += sp->v_sampling;
    1423                 : /*
    1424                 :       buf += clumps_per_line*samples_per_clump;
    1425                 :       cc -= clumps_per_line*samples_per_clump;
    1426                 : */
    1427               0 :       buf += sp->bytesperline * sp->v_sampling;
    1428               0 :       cc -= sp->bytesperline * sp->v_sampling;
    1429                 : 
    1430               0 :       nrows -= sp->v_sampling;
    1431               0 :     } while (nrows > 0);
    1432                 : 
    1433                 : #if defined(JPEG_LIB_MK1_OR_12BIT)
    1434               0 :     _TIFFfree(tmpbuf);
    1435                 : #endif
    1436                 : 
    1437                 :   }
    1438                 : 
    1439                 :   /* Close down the decompressor if done. */
    1440               0 :   return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
    1441               0 :       || TIFFjpeg_finish_decompress(sp);
    1442                 : }
    1443                 : 
    1444                 : 
    1445                 : /*
    1446                 :  * JPEG Encoding.
    1447                 :  */
    1448                 : 
    1449                 : static void
    1450              21 : unsuppress_quant_table (JPEGState* sp, int tblno)
    1451                 : {
    1452                 :   JQUANT_TBL* qtbl;
    1453                 : 
    1454              21 :   if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
    1455              21 :     qtbl->sent_table = FALSE;
    1456              21 : }
    1457                 : 
    1458                 : static void
    1459              21 : unsuppress_huff_table (JPEGState* sp, int tblno)
    1460                 : {
    1461                 :   JHUFF_TBL* htbl;
    1462                 : 
    1463              21 :   if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
    1464              21 :     htbl->sent_table = FALSE;
    1465              21 :   if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
    1466              21 :     htbl->sent_table = FALSE;
    1467              21 : }
    1468                 : 
    1469                 : static int
    1470              11 : prepare_JPEGTables(TIFF* tif)
    1471                 : {
    1472              11 :   JPEGState* sp = JState(tif);
    1473                 : 
    1474                 :   /* Initialize quant tables for current quality setting */
    1475              11 :   if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
    1476               0 :     return (0);
    1477                 :   /* Mark only the tables we want for output */
    1478                 :   /* NB: chrominance tables are currently used only with YCbCr */
    1479              11 :   if (!TIFFjpeg_suppress_tables(sp, TRUE))
    1480               0 :     return (0);
    1481              11 :   if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
    1482              11 :     unsuppress_quant_table(sp, 0);
    1483              11 :     if (sp->photometric == PHOTOMETRIC_YCBCR)
    1484              10 :       unsuppress_quant_table(sp, 1);
    1485                 :   }
    1486              11 :   if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
    1487              11 :     unsuppress_huff_table(sp, 0);
    1488              11 :     if (sp->photometric == PHOTOMETRIC_YCBCR)
    1489              10 :       unsuppress_huff_table(sp, 1);
    1490                 :   }
    1491                 :   /* Direct libjpeg output into jpegtables */
    1492              11 :   if (!TIFFjpeg_tables_dest(sp, tif))
    1493               0 :     return (0);
    1494                 :   /* Emit tables-only datastream */
    1495              11 :   if (!TIFFjpeg_write_tables(sp))
    1496               0 :     return (0);
    1497                 : 
    1498              11 :   return (1);
    1499                 : }
    1500                 : 
    1501                 : static int
    1502              12 : JPEGSetupEncode(TIFF* tif)
    1503                 : {
    1504              12 :   JPEGState* sp = JState(tif);
    1505              12 :   TIFFDirectory *td = &tif->tif_dir;
    1506                 :   static const char module[] = "JPEGSetupEncode";
    1507                 : 
    1508                 : #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
    1509              11 :         if( tif->tif_dir.td_bitspersample == 12 )
    1510               1 :             return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 1 );
    1511                 : #endif
    1512                 : 
    1513              11 :         JPEGInitializeLibJPEG( tif, FALSE );
    1514                 : 
    1515              11 :   assert(sp != NULL);
    1516              11 :   assert(!sp->cinfo.comm.is_decompressor);
    1517                 : 
    1518                 :   /*
    1519                 :    * Initialize all JPEG parameters to default values.
    1520                 :    * Note that jpeg_set_defaults needs legal values for
    1521                 :    * in_color_space and input_components.
    1522                 :    */
    1523              11 :   sp->cinfo.c.in_color_space = JCS_UNKNOWN;
    1524              11 :   sp->cinfo.c.input_components = 1;
    1525              11 :   if (!TIFFjpeg_set_defaults(sp))
    1526               0 :     return (0);
    1527                 :   /* Set per-file parameters */
    1528              11 :   sp->photometric = td->td_photometric;
    1529              11 :   switch (sp->photometric) {
    1530                 :   case PHOTOMETRIC_YCBCR:
    1531              10 :     sp->h_sampling = td->td_ycbcrsubsampling[0];
    1532              10 :     sp->v_sampling = td->td_ycbcrsubsampling[1];
    1533                 :     /*
    1534                 :      * A ReferenceBlackWhite field *must* be present since the
    1535                 :      * default value is inappropriate for YCbCr.  Fill in the
    1536                 :      * proper value if application didn't set it.
    1537                 :      */
    1538                 :     {
    1539                 :       float *ref;
    1540              10 :       if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
    1541                 :             &ref)) {
    1542                 :         float refbw[6];
    1543              10 :         long top = 1L << td->td_bitspersample;
    1544              10 :         refbw[0] = 0;
    1545              10 :         refbw[1] = (float)(top-1L);
    1546              10 :         refbw[2] = (float)(top>>1);
    1547              10 :         refbw[3] = refbw[1];
    1548              10 :         refbw[4] = refbw[2];
    1549              10 :         refbw[5] = refbw[1];
    1550              10 :         TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
    1551                 :                refbw);
    1552                 :       }
    1553                 :     }
    1554              10 :     break;
    1555                 :   case PHOTOMETRIC_PALETTE:   /* disallowed by Tech Note */
    1556                 :   case PHOTOMETRIC_MASK:
    1557               0 :     TIFFErrorExt(tif->tif_clientdata, module,
    1558                 :         "PhotometricInterpretation %d not allowed for JPEG",
    1559                 :         (int) sp->photometric);
    1560               0 :     return (0);
    1561                 :   default:
    1562                 :     /* TIFF 6.0 forbids subsampling of all other color spaces */
    1563               1 :     sp->h_sampling = 1;
    1564               1 :     sp->v_sampling = 1;
    1565                 :     break;
    1566                 :   }
    1567                 : 
    1568                 :   /* Verify miscellaneous parameters */
    1569                 : 
    1570                 :   /*
    1571                 :    * This would need work if libtiff ever supports different
    1572                 :    * depths for different components, or if libjpeg ever supports
    1573                 :    * run-time selection of depth.  Neither is imminent.
    1574                 :    */
    1575                 : #ifdef JPEG_LIB_MK1
    1576                 :         /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
    1577                 :   if (td->td_bitspersample != 8 && td->td_bitspersample != 12) 
    1578                 : #else
    1579              11 :   if (td->td_bitspersample != BITS_IN_JSAMPLE )
    1580                 : #endif
    1581                 :   {
    1582               0 :     TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
    1583                 :         (int) td->td_bitspersample);
    1584               0 :     return (0);
    1585                 :   }
    1586              11 :   sp->cinfo.c.data_precision = td->td_bitspersample;
    1587                 : #ifdef JPEG_LIB_MK1
    1588                 :         sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
    1589                 : #endif
    1590              11 :   if (isTiled(tif)) {
    1591               6 :     if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
    1592               0 :       TIFFErrorExt(tif->tif_clientdata, module,
    1593                 :           "JPEG tile height must be multiple of %d",
    1594                 :           sp->v_sampling * DCTSIZE);
    1595               0 :       return (0);
    1596                 :     }
    1597               6 :     if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
    1598               0 :       TIFFErrorExt(tif->tif_clientdata, module,
    1599                 :           "JPEG tile width must be multiple of %d",
    1600                 :           sp->h_sampling * DCTSIZE);
    1601               0 :       return (0);
    1602                 :     }
    1603                 :   } else {
    1604               6 :     if (td->td_rowsperstrip < td->td_imagelength &&
    1605               1 :         (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
    1606               0 :       TIFFErrorExt(tif->tif_clientdata, module,
    1607                 :           "RowsPerStrip must be multiple of %d for JPEG",
    1608                 :           sp->v_sampling * DCTSIZE);
    1609               0 :       return (0);
    1610                 :     }
    1611                 :   }
    1612                 : 
    1613                 :   /* Create a JPEGTables field if appropriate */
    1614              11 :   if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
    1615              11 :     if (!prepare_JPEGTables(tif))
    1616               0 :       return (0);
    1617                 :     /* Mark the field present */
    1618                 :     /* Can't use TIFFSetField since BEENWRITING is already set! */
    1619              11 :     TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
    1620              11 :     tif->tif_flags |= TIFF_DIRTYDIRECT;
    1621                 :   } else {
    1622                 :     /* We do not support application-supplied JPEGTables, */
    1623                 :     /* so mark the field not present */
    1624               0 :     TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
    1625                 :   }
    1626                 : 
    1627                 :   /* Direct libjpeg output to libtiff's output buffer */
    1628              11 :   TIFFjpeg_data_dest(sp, tif);
    1629                 : 
    1630              11 :   return (1);
    1631                 : }
    1632                 : 
    1633                 : /*
    1634                 :  * Set encoding state at the start of a strip or tile.
    1635                 :  */
    1636                 : static int
    1637              17 : JPEGPreEncode(TIFF* tif, uint16 s)
    1638                 : {
    1639              17 :   JPEGState *sp = JState(tif);
    1640              17 :   TIFFDirectory *td = &tif->tif_dir;
    1641                 :   static const char module[] = "JPEGPreEncode";
    1642                 :   uint32 segment_width, segment_height;
    1643                 :   int downsampled_input;
    1644                 : 
    1645              17 :   assert(sp != NULL);
    1646                 :   
    1647              17 :   if (sp->cinfo.comm.is_decompressor == 1)
    1648                 :   {
    1649               0 :     tif->tif_setupencode( tif );
    1650                 :   }
    1651                 :   
    1652              17 :   assert(!sp->cinfo.comm.is_decompressor);
    1653                 :   /*
    1654                 :    * Set encoding parameters for this strip/tile.
    1655                 :    */
    1656              17 :   if (isTiled(tif)) {
    1657              11 :     segment_width = td->td_tilewidth;
    1658              11 :     segment_height = td->td_tilelength;
    1659              11 :     sp->bytesperline = TIFFTileRowSize(tif);
    1660                 :   } else {
    1661               6 :     segment_width = td->td_imagewidth;
    1662               6 :     segment_height = td->td_imagelength - tif->tif_row;
    1663               6 :     if (segment_height > td->td_rowsperstrip)
    1664               1 :       segment_height = td->td_rowsperstrip;
    1665               6 :     sp->bytesperline = TIFFScanlineSize(tif);
    1666                 :   }
    1667              17 :   if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
    1668                 :     /* for PC 2, scale down the strip/tile size
    1669                 :      * to match a downsampled component
    1670                 :      */
    1671               0 :     segment_width = TIFFhowmany_32(segment_width, sp->h_sampling); 
    1672               0 :     segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
    1673                 :   }
    1674              17 :   if (segment_width > 65535 || segment_height > 65535) {
    1675               0 :     TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
    1676               0 :     return (0);
    1677                 :   }
    1678              17 :   sp->cinfo.c.image_width = segment_width;
    1679              17 :   sp->cinfo.c.image_height = segment_height;
    1680              17 :   downsampled_input = FALSE;
    1681              17 :   if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
    1682              17 :     sp->cinfo.c.input_components = td->td_samplesperpixel;
    1683              17 :     if (sp->photometric == PHOTOMETRIC_YCBCR) {
    1684              15 :       if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
    1685              15 :         sp->cinfo.c.in_color_space = JCS_RGB;
    1686                 :       } else {
    1687               0 :         sp->cinfo.c.in_color_space = JCS_YCbCr;
    1688               0 :         if (sp->h_sampling != 1 || sp->v_sampling != 1)
    1689               0 :           downsampled_input = TRUE;
    1690                 :       }
    1691              15 :       if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
    1692               0 :         return (0);
    1693                 :       /*
    1694                 :        * Set Y sampling factors;
    1695                 :        * we assume jpeg_set_colorspace() set the rest to 1
    1696                 :        */
    1697              15 :       sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
    1698              15 :       sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
    1699                 :     } else {
    1700               2 :       sp->cinfo.c.in_color_space = JCS_UNKNOWN;
    1701               2 :       if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
    1702               0 :         return (0);
    1703                 :       /* jpeg_set_colorspace set all sampling factors to 1 */
    1704                 :     }
    1705                 :   } else {
    1706               0 :     sp->cinfo.c.input_components = 1;
    1707               0 :     sp->cinfo.c.in_color_space = JCS_UNKNOWN;
    1708               0 :     if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
    1709               0 :       return (0);
    1710               0 :     sp->cinfo.c.comp_info[0].component_id = s;
    1711                 :     /* jpeg_set_colorspace() set sampling factors to 1 */
    1712               0 :     if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
    1713               0 :       sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
    1714               0 :       sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
    1715               0 :       sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
    1716                 :     }
    1717                 :   }
    1718                 :   /* ensure libjpeg won't write any extraneous markers */
    1719              17 :   sp->cinfo.c.write_JFIF_header = FALSE;
    1720              17 :   sp->cinfo.c.write_Adobe_marker = FALSE;
    1721                 :   /* set up table handling correctly */
    1722              17 :   if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
    1723               0 :     if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
    1724               0 :       return (0);
    1725               0 :     unsuppress_quant_table(sp, 0);
    1726               0 :     unsuppress_quant_table(sp, 1);
    1727                 :   }
    1728              17 :   if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
    1729              17 :     sp->cinfo.c.optimize_coding = FALSE;
    1730                 :   else
    1731               0 :     sp->cinfo.c.optimize_coding = TRUE;
    1732              17 :   if (downsampled_input) {
    1733                 :     /* Need to use raw-data interface to libjpeg */
    1734               0 :     sp->cinfo.c.raw_data_in = TRUE;
    1735               0 :     tif->tif_encoderow = JPEGEncodeRaw;
    1736               0 :     tif->tif_encodestrip = JPEGEncodeRaw;
    1737               0 :     tif->tif_encodetile = JPEGEncodeRaw;
    1738                 :   } else {
    1739                 :     /* Use normal interface to libjpeg */
    1740              17 :     sp->cinfo.c.raw_data_in = FALSE;
    1741              17 :     tif->tif_encoderow = JPEGEncode;
    1742              17 :     tif->tif_encodestrip = JPEGEncode;
    1743              17 :     tif->tif_encodetile = JPEGEncode;
    1744                 :   }
    1745                 :   /* Start JPEG compressor */
    1746              17 :   if (!TIFFjpeg_start_compress(sp, FALSE))
    1747               0 :     return (0);
    1748                 :   /* Allocate downsampled-data buffers if needed */
    1749              17 :   if (downsampled_input) {
    1750               0 :     if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
    1751                 :                  sp->cinfo.c.num_components))
    1752               0 :       return (0);
    1753                 :   }
    1754              17 :   sp->scancount = 0;
    1755                 : 
    1756              17 :   return (1);
    1757                 : }
    1758                 : 
    1759                 : /*
    1760                 :  * Encode a chunk of pixels.
    1761                 :  * "Standard" case: incoming data is not downsampled.
    1762                 :  */
    1763                 : static int
    1764            2064 : JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
    1765                 : {
    1766            2064 :   JPEGState *sp = JState(tif);
    1767                 :   tmsize_t nrows;
    1768                 :   JSAMPROW bufptr[1];
    1769            2064 :         short *line16 = NULL;
    1770            2064 :         int    line16_count = 0;
    1771                 : 
    1772                 :   (void) s;
    1773            2064 :   assert(sp != NULL);
    1774                 :   /* data is expected to be supplied in multiples of a scanline */
    1775            2064 :   nrows = cc / sp->bytesperline;
    1776            2064 :   if (cc % sp->bytesperline)
    1777               0 :             TIFFWarningExt(tif->tif_clientdata, tif->tif_name, 
    1778                 :                            "fractional scanline discarded");
    1779                 : 
    1780                 :         /* The last strip will be limited to image size */
    1781            2064 :         if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
    1782               0 :             nrows = tif->tif_dir.td_imagelength - tif->tif_row;
    1783                 : 
    1784            2064 :         if( sp->cinfo.c.data_precision == 12 )
    1785                 :         {
    1786               1 :             line16_count = (sp->bytesperline * 2) / 3;
    1787               1 :             line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
    1788                 :         }
    1789                 :             
    1790           12644 :   while (nrows-- > 0) {
    1791                 : 
    1792            8516 :             if( sp->cinfo.c.data_precision == 12 )
    1793                 :             {
    1794                 : 
    1795              64 :                 int value_pairs = line16_count / 2;
    1796                 :                 int iPair;
    1797                 : 
    1798              64 :     bufptr[0] = (JSAMPROW) line16;
    1799                 : 
    1800            6208 :                 for( iPair = 0; iPair < value_pairs; iPair++ )
    1801                 :                 {
    1802                 :                     unsigned char *in_ptr =
    1803            6144 :                         ((unsigned char *) buf) + iPair * 3;
    1804            6144 :                     JSAMPLE *out_ptr = (JSAMPLE *) (line16 + iPair * 2);
    1805                 : 
    1806            6144 :                     out_ptr[0] = (in_ptr[0] << 4) | ((in_ptr[1] & 0xf0) >> 4);
    1807            6144 :                     out_ptr[1] = ((in_ptr[1] & 0x0f) << 8) | in_ptr[2];
    1808                 :                 }
    1809                 :             }
    1810                 :             else
    1811                 :             {
    1812            8452 :     bufptr[0] = (JSAMPROW) buf;
    1813                 :             }
    1814            8516 :             if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
    1815               0 :                 return (0);
    1816            8516 :             if (nrows > 0)
    1817            6452 :                 tif->tif_row++;
    1818            8516 :             buf += sp->bytesperline;
    1819                 :   }
    1820                 : 
    1821            2064 :         if( sp->cinfo.c.data_precision == 12 )
    1822                 :         {
    1823               1 :             _TIFFfree( line16 );
    1824                 :         }
    1825                 :             
    1826            2064 :   return (1);
    1827                 : }
    1828                 : 
    1829                 : /*
    1830                 :  * Encode a chunk of pixels.
    1831                 :  * Incoming data is expected to be downsampled per sampling factors.
    1832                 :  */
    1833                 : static int
    1834               0 : JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
    1835                 : {
    1836               0 :   JPEGState *sp = JState(tif);
    1837                 :   JSAMPLE* inptr;
    1838                 :   JSAMPLE* outptr;
    1839                 :   tmsize_t nrows;
    1840                 :   JDIMENSION clumps_per_line, nclump;
    1841                 :   int clumpoffset, ci, xpos, ypos;
    1842                 :   jpeg_component_info* compptr;
    1843               0 :   int samples_per_clump = sp->samplesperclump;
    1844                 :   tmsize_t bytesperclumpline;
    1845                 : 
    1846                 :   (void) s;
    1847               0 :   assert(sp != NULL);
    1848                 :   /* data is expected to be supplied in multiples of a clumpline */
    1849                 :   /* a clumpline is equivalent to v_sampling desubsampled scanlines */
    1850                 :   /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
    1851               0 :   bytesperclumpline = (((sp->cinfo.c.image_width+sp->h_sampling-1)/sp->h_sampling)
    1852               0 :            *(sp->h_sampling*sp->v_sampling+2)*sp->cinfo.c.data_precision+7)
    1853                 :           /8;
    1854                 : 
    1855               0 :   nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
    1856               0 :   if (cc % bytesperclumpline)
    1857               0 :     TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
    1858                 : 
    1859                 :   /* Cb,Cr both have sampling factors 1, so this is correct */
    1860               0 :   clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
    1861                 : 
    1862               0 :   while (nrows > 0) {
    1863                 :     /*
    1864                 :      * Fastest way to separate the data is to make one pass
    1865                 :      * over the scanline for each row of each component.
    1866                 :      */
    1867               0 :     clumpoffset = 0;    /* first sample in clump */
    1868               0 :     for (ci = 0, compptr = sp->cinfo.c.comp_info;
    1869               0 :          ci < sp->cinfo.c.num_components;
    1870               0 :          ci++, compptr++) {
    1871               0 :         int hsamp = compptr->h_samp_factor;
    1872               0 :         int vsamp = compptr->v_samp_factor;
    1873               0 :         int padding = (int) (compptr->width_in_blocks * DCTSIZE -
    1874               0 :            clumps_per_line * hsamp);
    1875               0 :         for (ypos = 0; ypos < vsamp; ypos++) {
    1876               0 :       inptr = ((JSAMPLE*) buf) + clumpoffset;
    1877               0 :       outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
    1878               0 :       if (hsamp == 1) {
    1879                 :           /* fast path for at least Cb and Cr */
    1880               0 :           for (nclump = clumps_per_line; nclump-- > 0; ) {
    1881               0 :         *outptr++ = inptr[0];
    1882               0 :         inptr += samples_per_clump;
    1883                 :           }
    1884                 :       } else {
    1885                 :           /* general case */
    1886               0 :           for (nclump = clumps_per_line; nclump-- > 0; ) {
    1887               0 :         for (xpos = 0; xpos < hsamp; xpos++)
    1888               0 :             *outptr++ = inptr[xpos];
    1889               0 :         inptr += samples_per_clump;
    1890                 :           }
    1891                 :       }
    1892                 :       /* pad each scanline as needed */
    1893               0 :       for (xpos = 0; xpos < padding; xpos++) {
    1894               0 :           *outptr = outptr[-1];
    1895               0 :           outptr++;
    1896                 :       }
    1897               0 :       clumpoffset += hsamp;
    1898                 :         }
    1899                 :     }
    1900               0 :     sp->scancount++;
    1901               0 :     if (sp->scancount >= DCTSIZE) {
    1902               0 :       int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
    1903               0 :       if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
    1904               0 :         return (0);
    1905               0 :       sp->scancount = 0;
    1906                 :     }
    1907               0 :     tif->tif_row += sp->v_sampling;
    1908               0 :     buf += sp->bytesperline;
    1909               0 :     nrows -= sp->v_sampling;
    1910                 :   }
    1911               0 :   return (1);
    1912                 : }
    1913                 : 
    1914                 : /*
    1915                 :  * Finish up at the end of a strip or tile.
    1916                 :  */
    1917                 : static int
    1918              17 : JPEGPostEncode(TIFF* tif)
    1919                 : {
    1920              17 :   JPEGState *sp = JState(tif);
    1921                 : 
    1922              17 :   if (sp->scancount > 0) {
    1923                 :     /*
    1924                 :      * Need to emit a partial bufferload of downsampled data.
    1925                 :      * Pad the data vertically.
    1926                 :      */
    1927                 :     int ci, ypos, n;
    1928                 :     jpeg_component_info* compptr;
    1929                 : 
    1930               0 :     for (ci = 0, compptr = sp->cinfo.c.comp_info;
    1931               0 :          ci < sp->cinfo.c.num_components;
    1932               0 :          ci++, compptr++) {
    1933               0 :       int vsamp = compptr->v_samp_factor;
    1934               0 :       tmsize_t row_width = compptr->width_in_blocks * DCTSIZE
    1935               0 :         * sizeof(JSAMPLE);
    1936               0 :       for (ypos = sp->scancount * vsamp;
    1937               0 :            ypos < DCTSIZE * vsamp; ypos++) {
    1938               0 :         _TIFFmemcpy((void*)sp->ds_buffer[ci][ypos],
    1939               0 :               (void*)sp->ds_buffer[ci][ypos-1],
    1940                 :               row_width);
    1941                 : 
    1942                 :       }
    1943                 :     }
    1944               0 :     n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
    1945               0 :     if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
    1946               0 :       return (0);
    1947                 :   }
    1948                 : 
    1949              17 :   return (TIFFjpeg_finish_compress(JState(tif)));
    1950                 : }
    1951                 : 
    1952                 : static void
    1953              79 : JPEGCleanup(TIFF* tif)
    1954                 : {
    1955              79 :   JPEGState *sp = JState(tif);
    1956                 :   
    1957              79 :   assert(sp != 0);
    1958                 : 
    1959              79 :   tif->tif_tagmethods.vgetfield = sp->vgetparent;
    1960              79 :   tif->tif_tagmethods.vsetfield = sp->vsetparent;
    1961              79 :   tif->tif_tagmethods.printdir = sp->printdir;
    1962                 : 
    1963              79 :   if( sp->cinfo_initialized )
    1964              30 :       TIFFjpeg_destroy(sp); /* release libjpeg resources */
    1965              79 :   if (sp->jpegtables)    /* tag value */
    1966              79 :     _TIFFfree(sp->jpegtables);
    1967              79 :   _TIFFfree(tif->tif_data);  /* release local state */
    1968              79 :   tif->tif_data = NULL;
    1969                 : 
    1970              79 :   _TIFFSetDefaultCompressionState(tif);
    1971              79 : }
    1972                 : 
    1973                 : static void 
    1974             142 : JPEGResetUpsampled( TIFF* tif )
    1975                 : {
    1976             142 :   JPEGState* sp = JState(tif);
    1977             142 :   TIFFDirectory* td = &tif->tif_dir;
    1978                 : 
    1979                 :   /*
    1980                 :    * Mark whether returned data is up-sampled or not so TIFFStripSize
    1981                 :    * and TIFFTileSize return values that reflect the true amount of
    1982                 :    * data.
    1983                 :    */
    1984             142 :   tif->tif_flags &= ~TIFF_UPSAMPLED;
    1985             142 :   if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
    1986             280 :     if (td->td_photometric == PHOTOMETRIC_YCBCR &&
    1987             138 :         sp->jpegcolormode == JPEGCOLORMODE_RGB) {
    1988              67 :       tif->tif_flags |= TIFF_UPSAMPLED;
    1989                 :     } else {
    1990                 : #ifdef notdef
    1991                 :       if (td->td_ycbcrsubsampling[0] != 1 ||
    1992                 :           td->td_ycbcrsubsampling[1] != 1)
    1993                 :         ; /* XXX what about up-sampling? */
    1994                 : #endif
    1995                 :     }
    1996                 :   }
    1997                 : 
    1998                 :   /*
    1999                 :    * Must recalculate cached tile size in case sampling state changed.
    2000                 :    * Should we really be doing this now if image size isn't set? 
    2001                 :    */
    2002             142 :         if( tif->tif_tilesize > 0 )
    2003              47 :             tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);   
    2004             142 :         if( tif->tif_scanlinesize > 0 )
    2005              94 :             tif->tif_scanlinesize = TIFFScanlineSize(tif); 
    2006             142 : }
    2007                 : 
    2008                 : static int
    2009             908 : JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
    2010                 : {
    2011             908 :   JPEGState* sp = JState(tif);
    2012                 :   const TIFFField* fip;
    2013                 :   uint32 v32;
    2014                 : 
    2015             908 :   assert(sp != NULL);
    2016                 : 
    2017             908 :   switch (tag) {
    2018                 :   case TIFFTAG_JPEGTABLES:
    2019              70 :     v32 = (uint32) va_arg(ap, uint32);
    2020              70 :     if (v32 == 0) {
    2021                 :       /* XXX */
    2022               0 :       return (0);
    2023                 :     }
    2024              70 :     _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
    2025                 :         (long) v32);
    2026              70 :     sp->jpegtables_length = v32;
    2027              70 :     TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
    2028                 :     break;
    2029                 :   case TIFFTAG_JPEGQUALITY:
    2030              10 :     sp->jpegquality = (int) va_arg(ap, int);
    2031              10 :     return (1);     /* pseudo tag */
    2032                 :   case TIFFTAG_JPEGCOLORMODE:
    2033              68 :     sp->jpegcolormode = (int) va_arg(ap, int);
    2034              68 :     JPEGResetUpsampled( tif );
    2035              68 :     return (1);     /* pseudo tag */
    2036                 :   case TIFFTAG_PHOTOMETRIC:
    2037                 :   {
    2038              74 :     int ret_value = (*sp->vsetparent)(tif, tag, ap);
    2039              74 :     JPEGResetUpsampled( tif );
    2040              74 :     return ret_value;
    2041                 :   }
    2042                 :   case TIFFTAG_JPEGTABLESMODE:
    2043               0 :     sp->jpegtablesmode = (int) va_arg(ap, int);
    2044               0 :     return (1);     /* pseudo tag */
    2045                 :   case TIFFTAG_YCBCRSUBSAMPLING:
    2046                 :     /* mark the fact that we have a real ycbcrsubsampling! */
    2047               0 :     sp->ycbcrsampling_fetched = 1;
    2048                 :     /* should we be recomputing upsampling info here? */
    2049               0 :     return (*sp->vsetparent)(tif, tag, ap);
    2050                 :   default:
    2051             686 :     return (*sp->vsetparent)(tif, tag, ap);
    2052                 :   }
    2053                 : 
    2054              70 :   if ((fip = TIFFFieldWithTag(tif, tag))) {
    2055              70 :     TIFFSetFieldBit(tif, fip->field_bit);
    2056                 :   } else {
    2057               0 :     return (0);
    2058                 :   }
    2059                 : 
    2060              70 :   tif->tif_flags |= TIFF_DIRTYDIRECT;
    2061              70 :   return (1);
    2062                 : }
    2063                 : 
    2064                 : static int
    2065            1460 : JPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
    2066                 : {
    2067            1460 :   JPEGState* sp = JState(tif);
    2068                 : 
    2069            1460 :   assert(sp != NULL);
    2070                 : 
    2071            1460 :   switch (tag) {
    2072                 :     case TIFFTAG_JPEGTABLES:
    2073              44 :       *va_arg(ap, uint32*) = sp->jpegtables_length;
    2074              44 :       *va_arg(ap, void**) = sp->jpegtables;
    2075              44 :       break;
    2076                 :     case TIFFTAG_JPEGQUALITY:
    2077               6 :       *va_arg(ap, int*) = sp->jpegquality;
    2078               6 :       break;
    2079                 :     case TIFFTAG_JPEGCOLORMODE:
    2080              65 :       *va_arg(ap, int*) = sp->jpegcolormode;
    2081              65 :       break;
    2082                 :     case TIFFTAG_JPEGTABLESMODE:
    2083               0 :       *va_arg(ap, int*) = sp->jpegtablesmode;
    2084               0 :       break;
    2085                 :     default:
    2086            1345 :       return (*sp->vgetparent)(tif, tag, ap);
    2087                 :   }
    2088             115 :   return (1);
    2089                 : }
    2090                 : 
    2091                 : static void
    2092               0 : JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
    2093                 : {
    2094               0 :   JPEGState* sp = JState(tif);
    2095                 : 
    2096               0 :   assert(sp != NULL);
    2097                 : 
    2098                 :   (void) flags;
    2099               0 :   if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
    2100               0 :     fprintf(fd, "  JPEG Tables: (%lu bytes)\n",
    2101                 :       (unsigned long) sp->jpegtables_length);
    2102               0 :   if (sp->printdir)
    2103               0 :     (*sp->printdir)(tif, fd, flags);
    2104               0 : }
    2105                 : 
    2106                 : static uint32
    2107               6 : JPEGDefaultStripSize(TIFF* tif, uint32 s)
    2108                 : {
    2109               6 :   JPEGState* sp = JState(tif);
    2110               6 :   TIFFDirectory *td = &tif->tif_dir;
    2111                 : 
    2112               6 :   s = (*sp->defsparent)(tif, s);
    2113               6 :   if (s < td->td_imagelength)
    2114               4 :     s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
    2115               6 :   return (s);
    2116                 : }
    2117                 : 
    2118                 : static void
    2119               0 : JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
    2120                 : {
    2121               0 :   JPEGState* sp = JState(tif);
    2122               0 :   TIFFDirectory *td = &tif->tif_dir;
    2123                 : 
    2124               0 :   (*sp->deftparent)(tif, tw, th);
    2125               0 :   *tw = TIFFroundup_32(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
    2126               0 :   *th = TIFFroundup_32(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
    2127               0 : }
    2128                 : 
    2129                 : /*
    2130                 :  * The JPEG library initialized used to be done in TIFFInitJPEG(), but
    2131                 :  * now that we allow a TIFF file to be opened in update mode it is necessary
    2132                 :  * to have some way of deciding whether compression or decompression is
    2133                 :  * desired other than looking at tif->tif_mode.  We accomplish this by 
    2134                 :  * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
    2135                 :  * If so, we assume decompression is desired. 
    2136                 :  *
    2137                 :  * This is tricky, because TIFFInitJPEG() is called while the directory is
    2138                 :  * being read, and generally speaking the BYTECOUNTS tag won't have been read
    2139                 :  * at that point.  So we try to defer jpeg library initialization till we
    2140                 :  * do have that tag ... basically any access that might require the compressor
    2141                 :  * or decompressor that occurs after the reading of the directory. 
    2142                 :  *
    2143                 :  * In an ideal world compressors or decompressors would be setup
    2144                 :  * at the point where a single tile or strip was accessed (for read or write)
    2145                 :  * so that stuff like update of missing tiles, or replacement of tiles could
    2146                 :  * be done. However, we aren't trying to crack that nut just yet ...
    2147                 :  *
    2148                 :  * NFW, Feb 3rd, 2003.
    2149                 :  */
    2150                 : 
    2151              30 : static int JPEGInitializeLibJPEG( TIFF * tif, int decompress )
    2152                 : {
    2153              30 :     JPEGState* sp = JState(tif);
    2154              30 :     uint64* byte_counts = NULL;
    2155              30 :     int     data_is_empty = TRUE;
    2156                 : 
    2157              30 :     if(sp->cinfo_initialized)
    2158                 :     {
    2159               0 :         if( !decompress && sp->cinfo.comm.is_decompressor )
    2160               0 :             TIFFjpeg_destroy( sp );
    2161               0 :         else if( decompress && !sp->cinfo.comm.is_decompressor )
    2162               0 :             TIFFjpeg_destroy( sp );
    2163                 :         else
    2164               0 :             return 1;
    2165                 : 
    2166               0 :         sp->cinfo_initialized = 0;
    2167                 :     }
    2168                 : 
    2169                 :     /*
    2170                 :      * Do we have tile data already?  Make sure we initialize the
    2171                 :      * the state in decompressor mode if we have tile data, even if we
    2172                 :      * are not in read-only file access mode. 
    2173                 :      */
    2174              60 :     if( TIFFIsTiled( tif ) 
    2175              30 :         && TIFFGetField( tif, TIFFTAG_TILEBYTECOUNTS, &byte_counts ) 
    2176              30 :         && byte_counts != NULL )
    2177                 :     {
    2178              15 :         data_is_empty = byte_counts[0] == 0;
    2179                 :     }
    2180              60 :     if( !TIFFIsTiled( tif ) 
    2181                 :         && TIFFGetField( tif, TIFFTAG_STRIPBYTECOUNTS, &byte_counts) 
    2182              30 :         && byte_counts != NULL )
    2183                 :     {
    2184              15 :         data_is_empty = byte_counts[0] == 0;
    2185                 :     }
    2186                 : 
    2187                 :     /*
    2188                 :      * Initialize libjpeg.
    2189                 :      */
    2190              30 :     if ( decompress ) {
    2191              19 :         if (!TIFFjpeg_create_decompress(sp))
    2192               0 :             return (0);
    2193                 :     } else {
    2194              11 :         if (!TIFFjpeg_create_compress(sp))
    2195               0 :             return (0);
    2196                 :     }
    2197                 : 
    2198              30 :     sp->cinfo_initialized = TRUE;
    2199                 : 
    2200              30 :     return 1;
    2201                 : }
    2202                 : 
    2203                 : int
    2204              81 : TIFFInitJPEG(TIFF* tif, int scheme)
    2205                 : {
    2206                 :   JPEGState* sp;
    2207                 : 
    2208              81 :   assert(scheme == COMPRESSION_JPEG);
    2209                 : 
    2210                 :   /*
    2211                 :    * Merge codec-specific tag information.
    2212                 :    */
    2213              81 :   if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields))) {
    2214               0 :     TIFFErrorExt(tif->tif_clientdata,
    2215                 :            "TIFFInitJPEG",
    2216                 :            "Merging JPEG codec-specific tags failed");
    2217               0 :     return 0;
    2218                 :   }
    2219                 : 
    2220                 :   /*
    2221                 :    * Allocate state block so tag methods have storage to record values.
    2222                 :    */
    2223              81 :   tif->tif_data = (uint8*) _TIFFmalloc(sizeof (JPEGState));
    2224                 : 
    2225              81 :   if (tif->tif_data == NULL) {
    2226               0 :     TIFFErrorExt(tif->tif_clientdata,
    2227                 :            "TIFFInitJPEG", "No space for JPEG state block");
    2228               0 :     return 0;
    2229                 :   }
    2230              81 :         _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
    2231                 : 
    2232              81 :   sp = JState(tif);
    2233              81 :   sp->tif = tif;       /* back link */
    2234                 : 
    2235                 :   /*
    2236                 :    * Override parent get/set field methods.
    2237                 :    */
    2238              81 :   sp->vgetparent = tif->tif_tagmethods.vgetfield;
    2239              81 :   tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
    2240              81 :   sp->vsetparent = tif->tif_tagmethods.vsetfield;
    2241              81 :   tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
    2242              81 :   sp->printdir = tif->tif_tagmethods.printdir;
    2243              81 :   tif->tif_tagmethods.printdir = JPEGPrintDir;   /* hook for codec tags */
    2244                 : 
    2245                 :   /* Default values for codec-specific fields */
    2246              81 :   sp->jpegtables = NULL;
    2247              81 :   sp->jpegtables_length = 0;
    2248              81 :   sp->jpegquality = 75;      /* Default IJG quality */
    2249              81 :   sp->jpegcolormode = JPEGCOLORMODE_RAW;
    2250              81 :   sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
    2251              81 :         sp->ycbcrsampling_fetched = 0;
    2252                 : 
    2253                 :   /*
    2254                 :    * Install codec methods.
    2255                 :    */
    2256              81 :   tif->tif_fixuptags = JPEGFixupTags;
    2257              81 :   tif->tif_setupdecode = JPEGSetupDecode;
    2258              81 :   tif->tif_predecode = JPEGPreDecode;
    2259              81 :   tif->tif_decoderow = JPEGDecode;
    2260              81 :   tif->tif_decodestrip = JPEGDecode;
    2261              81 :   tif->tif_decodetile = JPEGDecode;
    2262              81 :   tif->tif_setupencode = JPEGSetupEncode;
    2263              81 :   tif->tif_preencode = JPEGPreEncode;
    2264              81 :   tif->tif_postencode = JPEGPostEncode;
    2265              81 :   tif->tif_encoderow = JPEGEncode;
    2266              81 :   tif->tif_encodestrip = JPEGEncode;
    2267              81 :   tif->tif_encodetile = JPEGEncode;  
    2268              81 :   tif->tif_cleanup = JPEGCleanup;
    2269              81 :   sp->defsparent = tif->tif_defstripsize;
    2270              81 :   tif->tif_defstripsize = JPEGDefaultStripSize;
    2271              81 :   sp->deftparent = tif->tif_deftilesize;
    2272              81 :   tif->tif_deftilesize = JPEGDefaultTileSize;
    2273              81 :   tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
    2274                 : 
    2275              81 :         sp->cinfo_initialized = FALSE;
    2276                 : 
    2277                 :   /*
    2278                 :         ** Create a JPEGTables field if no directory has yet been created. 
    2279                 :         ** We do this just to ensure that sufficient space is reserved for
    2280                 :         ** the JPEGTables field.  It will be properly created the right
    2281                 :         ** size later. 
    2282                 :         */
    2283              81 :         if( tif->tif_diroff == 0 )
    2284                 :         {
    2285                 : #define SIZE_OF_JPEGTABLES 2000
    2286              11 :             TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
    2287              11 :             sp->jpegtables_length = SIZE_OF_JPEGTABLES;
    2288              11 :             sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
    2289              11 :       _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
    2290                 : #undef SIZE_OF_JPEGTABLES
    2291                 :         }
    2292                 : 
    2293              81 :   return 1;
    2294                 : }
    2295                 : #endif /* JPEG_SUPPORT */
    2296                 : 
    2297                 : /* vim: set ts=8 sts=8 sw=8 noet: */
    2298                 : 

Generated by: LCOV version 1.7