LTP GCOV extension - code coverage report
Current view: directory - frmts/gtiff/libtiff - tif_jpeg.c
Test: gdal_filtered.info
Date: 2010-07-12 Instrumented lines: 873
Code covered: 63.6 % Executed lines: 555

       1                 : /* $Id: tif_jpeg.c,v 1.91 2010-05-07 18:38:46 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                 : TIFFjpeg_error_exit(j_common_ptr cinfo)
     214               0 : {
     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                 : TIFFjpeg_output_message(j_common_ptr cinfo)
     231               0 : {
     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                 : TIFFjpeg_create_compress(JPEGState* sp)
     249              32 : {
     250                 :   /* initialize JPEG error handling */
     251              32 :   sp->cinfo.c.err = jpeg_std_error(&sp->err);
     252              32 :   sp->err.error_exit = TIFFjpeg_error_exit;
     253              32 :   sp->err.output_message = TIFFjpeg_output_message;
     254                 : 
     255              32 :   return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
     256                 : }
     257                 : 
     258                 : static int
     259                 : TIFFjpeg_create_decompress(JPEGState* sp)
     260              45 : {
     261                 :   /* initialize JPEG error handling */
     262              45 :   sp->cinfo.d.err = jpeg_std_error(&sp->err);
     263              45 :   sp->err.error_exit = TIFFjpeg_error_exit;
     264              45 :   sp->err.output_message = TIFFjpeg_output_message;
     265                 : 
     266              45 :   return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
     267                 : }
     268                 : 
     269                 : static int
     270                 : TIFFjpeg_set_defaults(JPEGState* sp)
     271              32 : {
     272              32 :   return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
     273                 : }
     274                 : 
     275                 : static int
     276                 : TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
     277              40 : {
     278              40 :   return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
     279                 : }
     280                 : 
     281                 : static int
     282                 : TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
     283              54 : {
     284              54 :   return CALLVJPEG(sp,
     285                 :       jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
     286                 : }
     287                 : 
     288                 : static int
     289                 : TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
     290              14 : {
     291              14 :   return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
     292                 : }
     293                 : 
     294                 : static int
     295                 : TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
     296              40 : {
     297              40 :   return CALLVJPEG(sp,
     298                 :       jpeg_start_compress(&sp->cinfo.c, write_all_tables));
     299                 : }
     300                 : 
     301                 : static int
     302                 : TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
     303           11460 : {
     304           11460 :   return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
     305                 :       scanlines, (JDIMENSION) num_lines));
     306                 : }
     307                 : 
     308                 : static int
     309                 : TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
     310               0 : {
     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                 : TIFFjpeg_finish_compress(JPEGState* sp)
     317              40 : {
     318              40 :   return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
     319                 : }
     320                 : 
     321                 : static int
     322                 : TIFFjpeg_write_tables(JPEGState* sp)
     323              14 : {
     324              14 :   return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
     325                 : }
     326                 : 
     327                 : static int
     328                 : TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
     329             230 : {
     330             230 :   return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
     331                 : }
     332                 : 
     333                 : static int
     334                 : TIFFjpeg_start_decompress(JPEGState* sp)
     335             185 : {
     336             185 :   return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
     337                 : }
     338                 : 
     339                 : static int
     340                 : TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
     341           23006 : {
     342           23006 :   return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
     343                 :       scanlines, (JDIMENSION) max_lines));
     344                 : }
     345                 : 
     346                 : static int
     347                 : TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
     348               0 : {
     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                 : TIFFjpeg_finish_decompress(JPEGState* sp)
     355             165 : {
     356             165 :   return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
     357                 : }
     358                 : 
     359                 : static int
     360                 : TIFFjpeg_abort(JPEGState* sp)
     361             185 : {
     362             185 :   return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
     363                 : }
     364                 : 
     365                 : static int
     366                 : TIFFjpeg_destroy(JPEGState* sp)
     367              77 : {
     368              77 :   return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
     369                 : }
     370                 : 
     371                 : static JSAMPARRAY
     372                 : TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
     373                 :           JDIMENSION samplesperrow, JDIMENSION numrows)
     374               0 : {
     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                 : std_init_destination(j_compress_ptr cinfo)
     388              40 : {
     389              40 :   JPEGState* sp = (JPEGState*) cinfo;
     390              40 :   TIFF* tif = sp->tif;
     391                 : 
     392              40 :   sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
     393              40 :   sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
     394              40 : }
     395                 : 
     396                 : static boolean
     397                 : std_empty_output_buffer(j_compress_ptr cinfo)
     398               0 : {
     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                 : std_term_destination(j_compress_ptr cinfo)
     426              40 : {
     427              40 :   JPEGState* sp = (JPEGState*) cinfo;
     428              40 :   TIFF* tif = sp->tif;
     429                 : 
     430              40 :   tif->tif_rawcp = (uint8*) sp->dest.next_output_byte;
     431              40 :   tif->tif_rawcc =
     432                 :       tif->tif_rawdatasize - (tmsize_t) sp->dest.free_in_buffer;
     433                 :   /* NB: libtiff does the final buffer flush */
     434              40 : }
     435                 : 
     436                 : static void
     437                 : TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
     438              32 : {
     439                 :   (void) tif;
     440              32 :   sp->cinfo.c.dest = &sp->dest;
     441              32 :   sp->dest.init_destination = std_init_destination;
     442              32 :   sp->dest.empty_output_buffer = std_empty_output_buffer;
     443              32 :   sp->dest.term_destination = std_term_destination;
     444              32 : }
     445                 : 
     446                 : /*
     447                 :  * Alternate destination manager for outputting to JPEGTables field.
     448                 :  */
     449                 : 
     450                 : static void
     451                 : tables_init_destination(j_compress_ptr cinfo)
     452              14 : {
     453              14 :   JPEGState* sp = (JPEGState*) cinfo;
     454                 : 
     455                 :   /* while building, jpegtables_length is allocated buffer size */
     456              14 :   sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
     457              14 :   sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
     458              14 : }
     459                 : 
     460                 : static boolean
     461                 : tables_empty_output_buffer(j_compress_ptr cinfo)
     462               0 : {
     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                 :             (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                 : tables_term_destination(j_compress_ptr cinfo)
     480              14 : {
     481              14 :   JPEGState* sp = (JPEGState*) cinfo;
     482                 : 
     483                 :   /* set tables length to number of bytes actually emitted */
     484              14 :   sp->jpegtables_length -= (uint32) sp->dest.free_in_buffer;
     485              14 : }
     486                 : 
     487                 : static int
     488                 : TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
     489              14 : {
     490                 :   (void) tif;
     491                 :   /*
     492                 :    * Allocate a working buffer for building tables.
     493                 :    * Initial size is 1000 bytes, which is usually adequate.
     494                 :    */
     495              14 :   if (sp->jpegtables)
     496               0 :     _TIFFfree(sp->jpegtables);
     497              14 :   sp->jpegtables_length = 1000;
     498              14 :   sp->jpegtables = (void*) _TIFFmalloc((tmsize_t) sp->jpegtables_length);
     499              14 :   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              14 :   sp->cinfo.c.dest = &sp->dest;
     505              14 :   sp->dest.init_destination = tables_init_destination;
     506              14 :   sp->dest.empty_output_buffer = tables_empty_output_buffer;
     507              14 :   sp->dest.term_destination = tables_term_destination;
     508              14 :   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                 : std_init_source(j_decompress_ptr cinfo)
     518             185 : {
     519             185 :   JPEGState* sp = (JPEGState*) cinfo;
     520             185 :   TIFF* tif = sp->tif;
     521                 : 
     522             185 :   sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
     523             185 :   sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
     524             185 : }
     525                 : 
     526                 : static boolean
     527                 : std_fill_input_buffer(j_decompress_ptr cinfo)
     528               0 : {
     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                 : std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
     562               0 : {
     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                 : std_term_source(j_decompress_ptr cinfo)
     578             165 : {
     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             165 : }
     584                 : 
     585                 : static void
     586                 : TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
     587              90 : {
     588                 :   (void) tif;
     589              90 :   sp->cinfo.d.src = &sp->src;
     590              90 :   sp->src.init_source = std_init_source;
     591              90 :   sp->src.fill_input_buffer = std_fill_input_buffer;
     592              90 :   sp->src.skip_input_data = std_skip_input_data;
     593              90 :   sp->src.resync_to_restart = jpeg_resync_to_restart;
     594              90 :   sp->src.term_source = std_term_source;
     595              90 :   sp->src.bytes_in_buffer = 0;   /* for safety */
     596              90 :   sp->src.next_input_byte = NULL;
     597              90 : }
     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                 : tables_init_source(j_decompress_ptr cinfo)
     606              45 : {
     607              45 :   JPEGState* sp = (JPEGState*) cinfo;
     608                 : 
     609              45 :   sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
     610              45 :   sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
     611              45 : }
     612                 : 
     613                 : static void
     614                 : TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
     615              45 : {
     616              45 :   TIFFjpeg_data_src(sp, tif);
     617              45 :   sp->src.init_source = tables_init_source;
     618              45 : }
     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                 : alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
     629                 :         int num_components)
     630               0 : {
     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                 :         (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                 : JPEGFixupTags(TIFF* tif)
     690              94 : {
     691                 :   #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
     692              94 :   if ((tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR)&&
     693                 :       (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&&
     694                 :       (tif->tif_dir.td_samplesperpixel==3))
     695              74 :     JPEGFixupTagsSubsampling(tif);
     696                 :   #endif
     697              94 :   return(1);
     698                 : }
     699                 : 
     700                 : #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
     701                 : 
     702                 : static void
     703                 : JPEGFixupTagsSubsampling(TIFF* tif)
     704              74 : {
     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              74 :         if( tif->tif_dir.td_stripbytecount == NULL
     729                 :             || 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              54 :   m.tif=tif;
     738              54 :   m.buffersize=2048;
     739              54 :   m.buffer=_TIFFmalloc(m.buffersize);
     740              54 :   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              54 :   m.buffercurrentbyte=NULL;
     747              54 :   m.bufferbytesleft=0;
     748              54 :   m.fileoffset=tif->tif_dir.td_stripoffset[0];
     749              54 :   m.filepositioned=0;
     750              54 :   m.filebytesleft=tif->tif_dir.td_stripbytecount[0];
     751              54 :   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              54 :   _TIFFfree(m.buffer);
     755                 : }
     756                 : 
     757                 : static int
     758                 : JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
     759             174 : {
     760                 :   static const char module[] = "JPEGFixupTagsSubsamplingSec";
     761                 :   uint8 m;
     762                 :   while (1)
     763                 :   {
     764                 :     while (1)
     765                 :     {
     766             174 :       if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
     767               0 :         return(0);
     768             174 :       if (m==255)
     769             174 :         break;
     770               0 :     }
     771                 :     while (1)
     772                 :     {
     773             174 :       if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
     774               0 :         return(0);
     775             174 :       if (m!=255)
     776             174 :         break;
     777               0 :     }
     778             174 :     switch (m)
     779                 :     {
     780                 :       case JPEG_MARKER_SOI:
     781                 :         /* this type of marker has no data and should be skipped */
     782              54 :         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              66 :           if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
     808               0 :             return(0);
     809              66 :           if (n<2)
     810               0 :             return(0);
     811              66 :           n-=2;
     812              66 :           if (n>0)
     813              66 :             JPEGFixupTagsSubsamplingSkip(data,n);
     814                 :         }
     815              66 :         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              54 :           if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
     825               0 :             return(0);
     826              54 :           if (n!=8+data->tif->tif_dir.td_samplesperpixel*3)
     827               0 :             return(0);
     828              54 :           JPEGFixupTagsSubsamplingSkip(data,7);
     829              54 :           if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
     830               0 :             return(0);
     831              54 :           ph=(p>>4);
     832              54 :           pv=(p&15);
     833              54 :           JPEGFixupTagsSubsamplingSkip(data,1);
     834             162 :           for (o=1; o<data->tif->tif_dir.td_samplesperpixel; o++)
     835                 :           {
     836             108 :             JPEGFixupTagsSubsamplingSkip(data,1);
     837             108 :             if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
     838               0 :               return(0);
     839             108 :             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             108 :             JPEGFixupTagsSubsamplingSkip(data,1);
     846                 :           }
     847              54 :           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              54 :           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                 :                 (int)data->tif->tif_dir.td_ycbcrsubsampling[0],
     858                 :                 (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              54 :         return(1);
     865                 :       default:
     866               0 :         return(0);
     867                 :     }
     868             120 :   }
     869                 : }
     870                 : 
     871                 : static int
     872                 : JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result)
     873             750 : {
     874             750 :   if (data->bufferbytesleft==0)
     875                 :   {
     876                 :     uint32 m;
     877              54 :     if (data->filebytesleft==0)
     878               0 :       return(0);
     879              54 :     if (!data->filepositioned)
     880                 :     {
     881              54 :       TIFFSeekFile(data->tif,data->fileoffset,SEEK_SET);
     882              54 :       data->filepositioned=1;
     883                 :     }
     884              54 :     m=data->buffersize;
     885              54 :     if ((uint64)m>data->filebytesleft)
     886              29 :       m=(uint32)data->filebytesleft;
     887              54 :     assert(m<0x80000000UL);
     888              54 :     if (TIFFReadFile(data->tif,data->buffer,(tmsize_t)m)!=(tmsize_t)m)
     889               0 :       return(0);
     890              54 :     data->buffercurrentbyte=data->buffer;
     891              54 :     data->bufferbytesleft=m;
     892              54 :     data->fileoffset+=m;
     893              54 :     data->filebytesleft-=m;
     894                 :   }
     895             750 :   *result=*data->buffercurrentbyte;
     896             750 :   data->buffercurrentbyte++;
     897             750 :   data->bufferbytesleft--;
     898             750 :   return(1);
     899                 : }
     900                 : 
     901                 : static int
     902                 : JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result)
     903             120 : {
     904                 :   uint8 ma;
     905                 :   uint8 mb;
     906             120 :   if (!JPEGFixupTagsSubsamplingReadByte(data,&ma))
     907               0 :     return(0);
     908             120 :   if (!JPEGFixupTagsSubsamplingReadByte(data,&mb))
     909               0 :     return(0);
     910             120 :   *result=(ma<<8)|mb;
     911             120 :   return(1);
     912                 : }
     913                 : 
     914                 : static void
     915                 : JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength)
     916             390 : {
     917             390 :   if ((uint32)skiplength<=data->bufferbytesleft)
     918                 :   {
     919             390 :     data->buffercurrentbyte+=skiplength;
     920             390 :     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             390 : }
     940                 : 
     941                 : #endif
     942                 : 
     943                 : 
     944                 : static int
     945                 : JPEGSetupDecode(TIFF* tif)
     946              52 : {
     947              52 :   JPEGState* sp = JState(tif);
     948              52 :   TIFFDirectory *td = &tif->tif_dir;
     949                 : 
     950                 : #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
     951              45 :         if( tif->tif_dir.td_bitspersample == 12 )
     952               7 :             return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 0 );
     953                 : #endif
     954                 : 
     955              45 :   JPEGInitializeLibJPEG( tif, TRUE );
     956                 : 
     957              45 :   assert(sp != NULL);
     958              45 :   assert(sp->cinfo.comm.is_decompressor);
     959                 : 
     960                 :   /* Read JPEGTables if it is present */
     961              45 :   if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
     962              45 :     TIFFjpeg_tables_src(sp, tif);
     963              45 :     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              45 :   sp->photometric = td->td_photometric;
     971              45 :   switch (sp->photometric) {
     972                 :   case PHOTOMETRIC_YCBCR:
     973              23 :     sp->h_sampling = td->td_ycbcrsubsampling[0];
     974              23 :     sp->v_sampling = td->td_ycbcrsubsampling[1];
     975              23 :     break;
     976                 :   default:
     977                 :     /* TIFF 6.0 forbids subsampling of all other color spaces */
     978              22 :     sp->h_sampling = 1;
     979              22 :     sp->v_sampling = 1;
     980                 :     break;
     981                 :   }
     982                 : 
     983                 :   /* Set up for reading normal data */
     984              45 :   TIFFjpeg_data_src(sp, tif);
     985              45 :   tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
     986              45 :   return (1);
     987                 : }
     988                 : 
     989                 : /*
     990                 :  * Set up for decoding a strip or tile.
     991                 :  */
     992                 : static int
     993                 : JPEGPreDecode(TIFF* tif, uint16 s)
     994             185 : {
     995             185 :   JPEGState *sp = JState(tif);
     996             185 :   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             185 :   assert(sp != NULL);
    1003                 :   
    1004             185 :   if (sp->cinfo.comm.is_decompressor == 0)
    1005                 :   {
    1006              18 :     tif->tif_setupdecode( tif );
    1007                 :   }
    1008                 :   
    1009             185 :   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             185 :   if (!TIFFjpeg_abort(sp))
    1015               0 :     return (0);
    1016                 :   /*
    1017                 :    * Read the header for this strip/tile.
    1018                 :    */
    1019             185 :   if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
    1020               0 :     return (0);
    1021                 :   /*
    1022                 :    * Check image parameters and set decompression parameters.
    1023                 :    */
    1024             185 :   segment_width = td->td_imagewidth;
    1025             185 :   segment_height = td->td_imagelength - tif->tif_row;
    1026             185 :   if (isTiled(tif)) {
    1027              46 :                 segment_width = td->td_tilewidth;
    1028              46 :                 segment_height = td->td_tilelength;
    1029              46 :     sp->bytesperline = TIFFTileRowSize(tif);
    1030                 :   } else {
    1031             139 :     if (segment_height > td->td_rowsperstrip)
    1032             119 :       segment_height = td->td_rowsperstrip;
    1033             139 :     sp->bytesperline = TIFFScanlineSize(tif);
    1034                 :   }
    1035             185 :   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              13 :     segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
    1041              13 :     segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
    1042                 :   }
    1043             185 :   if (sp->cinfo.d.image_width < segment_width ||
    1044                 :       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             185 :   if (sp->cinfo.d.image_width > segment_width ||
    1053                 :       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             185 :   if (sp->cinfo.d.num_components !=
    1068                 :       (td->td_planarconfig == PLANARCONFIG_CONTIG ?
    1069                 :        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             185 :   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             185 :   if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
    1087                 :     /* Component 0 should have expected sampling factors */
    1088             166 :     if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
    1089                 :         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                 :             sp->cinfo.d.comp_info[0].h_samp_factor,
    1094                 :             sp->cinfo.d.comp_info[0].v_samp_factor,
    1095                 :             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                 :             || sp->cinfo.d.comp_info[0].v_samp_factor
    1107                 :           > 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                 :           sp->cinfo.d.comp_info[0].h_samp_factor,
    1127                 :           sp->cinfo.d.comp_info[0].v_samp_factor);
    1128                 : 
    1129               0 :             sp->h_sampling = (uint16)
    1130                 :           sp->cinfo.d.comp_info[0].h_samp_factor;
    1131               0 :             sp->v_sampling = (uint16)
    1132                 :           sp->cinfo.d.comp_info[0].v_samp_factor;
    1133                 :           }
    1134                 :     }
    1135                 :     /* Rest should have sampling factors 1,1 */
    1136             490 :     for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
    1137             324 :       if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
    1138                 :           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              19 :     if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
    1146                 :         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             185 :   downsampled_output = FALSE;
    1152             347 :   if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
    1153                 :       sp->photometric == PHOTOMETRIC_YCBCR &&
    1154                 :       sp->jpegcolormode == JPEGCOLORMODE_RGB) {
    1155                 :   /* Convert YCbCr to RGB */
    1156             162 :     sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
    1157             162 :     sp->cinfo.d.out_color_space = JCS_RGB;
    1158                 :   } else {
    1159                 :       /* Suppress colorspace handling */
    1160              23 :     sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
    1161              23 :     sp->cinfo.d.out_color_space = JCS_UNKNOWN;
    1162              23 :     if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
    1163                 :         (sp->h_sampling != 1 || sp->v_sampling != 1))
    1164               0 :       downsampled_output = TRUE;
    1165                 :     /* XXX what about up-sampling? */
    1166                 :   }
    1167             185 :   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             185 :     sp->cinfo.d.raw_data_out = FALSE;
    1176             185 :     tif->tif_decoderow = JPEGDecode;
    1177             185 :     tif->tif_decodestrip = JPEGDecode;
    1178             185 :     tif->tif_decodetile = JPEGDecode;  
    1179                 :   }
    1180                 :   /* Start JPEG decompressor */
    1181             185 :   if (!TIFFjpeg_start_decompress(sp))
    1182               0 :     return (0);
    1183                 :   /* Allocate downsampled-data buffers if needed */
    1184             185 :   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             185 :   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                 : JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
    1199            9375 : {
    1200            9375 :   JPEGState *sp = JState(tif);
    1201                 :   tmsize_t nrows;
    1202                 :   (void) s;
    1203                 : 
    1204            9375 :   nrows = cc / sp->bytesperline;
    1205            9375 :   if (cc % sp->bytesperline)
    1206               0 :     TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
    1207                 : 
    1208            9375 :   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            9375 :   if (nrows)
    1213                 :   {
    1214            9375 :     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            9375 :     if( sp->cinfo.d.data_precision == 12 )
    1222                 : #endif
    1223                 :     {
    1224               7 :       line_work_buf = (JSAMPROW)
    1225                 :           _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
    1226                 :           * sp->cinfo.d.num_components );
    1227                 :     }
    1228                 : 
    1229                 :     do {
    1230           23006 :       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             576 :         if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
    1238               0 :           return (0);
    1239                 : 
    1240             576 :         if( sp->cinfo.d.data_precision == 12 )
    1241                 :         {
    1242                 :           int value_pairs = (sp->cinfo.d.output_width
    1243             576 :               * sp->cinfo.d.num_components) / 2;
    1244                 :           int iPair;
    1245                 : 
    1246           47680 :           for( iPair = 0; iPair < value_pairs; iPair++ )
    1247                 :           {
    1248                 :             unsigned char *out_ptr =
    1249           47104 :                 ((unsigned char *) buf) + iPair * 3;
    1250           47104 :             JSAMPLE *in_ptr = line_work_buf + iPair * 2;
    1251                 : 
    1252           47104 :             out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
    1253           47104 :             out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
    1254                 :                 | ((in_ptr[1] & 0xf00) >> 8);
    1255           47104 :             out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
    1256                 :           }
    1257                 :         }
    1258               0 :         else if( sp->cinfo.d.data_precision == 8 )
    1259                 :         {
    1260                 :           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                 :                 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           22430 :         JSAMPROW bufptr = (JSAMPROW)buf;
    1278                 : 
    1279           22430 :         if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
    1280               0 :           return (0);
    1281                 :       }
    1282                 : 
    1283           23006 :       ++tif->tif_row;
    1284           23006 :       buf += sp->bytesperline;
    1285           23006 :       cc -= sp->bytesperline;
    1286           23006 :     } while (--nrows > 0);
    1287                 : 
    1288            9375 :     if( line_work_buf != NULL )
    1289               7 :       _TIFFfree( line_work_buf );
    1290                 :   }
    1291                 : 
    1292                 :   /* Close down the decompressor if we've finished the strip or tile. */
    1293            9375 :   return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
    1294                 :       || TIFFjpeg_finish_decompress(sp);
    1295                 : }
    1296                 : 
    1297                 : /*ARGSUSED*/ static int
    1298                 : DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
    1299                 : 
    1300               0 : {
    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                 : JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
    1316               0 : {
    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                 :     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                 :           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                 :                 | ((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                 :       || TIFFjpeg_finish_decompress(sp);
    1442                 : }
    1443                 : 
    1444                 : 
    1445                 : /*
    1446                 :  * JPEG Encoding.
    1447                 :  */
    1448                 : 
    1449                 : static void
    1450                 : unsuppress_quant_table (JPEGState* sp, int tblno)
    1451              24 : {
    1452                 :   JQUANT_TBL* qtbl;
    1453                 : 
    1454              24 :   if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
    1455              24 :     qtbl->sent_table = FALSE;
    1456              24 : }
    1457                 : 
    1458                 : static void
    1459                 : unsuppress_huff_table (JPEGState* sp, int tblno)
    1460              24 : {
    1461                 :   JHUFF_TBL* htbl;
    1462                 : 
    1463              24 :   if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
    1464              24 :     htbl->sent_table = FALSE;
    1465              24 :   if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
    1466              24 :     htbl->sent_table = FALSE;
    1467              24 : }
    1468                 : 
    1469                 : static int
    1470                 : prepare_JPEGTables(TIFF* tif)
    1471              14 : {
    1472              14 :   JPEGState* sp = JState(tif);
    1473                 : 
    1474                 :   /* Initialize quant tables for current quality setting */
    1475              14 :   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              14 :   if (!TIFFjpeg_suppress_tables(sp, TRUE))
    1480               0 :     return (0);
    1481              14 :   if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
    1482              14 :     unsuppress_quant_table(sp, 0);
    1483              14 :     if (sp->photometric == PHOTOMETRIC_YCBCR)
    1484              10 :       unsuppress_quant_table(sp, 1);
    1485                 :   }
    1486              14 :   if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
    1487              14 :     unsuppress_huff_table(sp, 0);
    1488              14 :     if (sp->photometric == PHOTOMETRIC_YCBCR)
    1489              10 :       unsuppress_huff_table(sp, 1);
    1490                 :   }
    1491                 :   /* Direct libjpeg output into jpegtables */
    1492              14 :   if (!TIFFjpeg_tables_dest(sp, tif))
    1493               0 :     return (0);
    1494                 :   /* Emit tables-only datastream */
    1495              14 :   if (!TIFFjpeg_write_tables(sp))
    1496               0 :     return (0);
    1497                 : 
    1498              14 :   return (1);
    1499                 : }
    1500                 : 
    1501                 : static int
    1502                 : JPEGSetupEncode(TIFF* tif)
    1503              35 : {
    1504              35 :   JPEGState* sp = JState(tif);
    1505              35 :   TIFFDirectory *td = &tif->tif_dir;
    1506                 :   static const char module[] = "JPEGSetupEncode";
    1507                 : 
    1508                 : #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
    1509              32 :         if( tif->tif_dir.td_bitspersample == 12 )
    1510               3 :             return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 1 );
    1511                 : #endif
    1512                 : 
    1513              32 :         JPEGInitializeLibJPEG( tif, FALSE );
    1514                 : 
    1515              32 :   assert(sp != NULL);
    1516              32 :   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              32 :   sp->cinfo.c.in_color_space = JCS_UNKNOWN;
    1524              32 :   sp->cinfo.c.input_components = 1;
    1525              32 :   if (!TIFFjpeg_set_defaults(sp))
    1526               0 :     return (0);
    1527                 :   /* Set per-file parameters */
    1528              32 :   sp->photometric = td->td_photometric;
    1529              32 :   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              22 :     sp->h_sampling = 1;
    1564              22 :     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              32 :   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              32 :   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              32 :   if (isTiled(tif)) {
    1591              27 :     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              27 :     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               5 :     if (td->td_rowsperstrip < td->td_imagelength &&
    1605                 :         (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              32 :   if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
    1615              32 :                 if( sp->jpegtables == NULL
    1616                 :                     || memcmp(sp->jpegtables,"\0\0\0\0\0\0\0\0\0",8) == 0 )
    1617                 :                 {
    1618              14 :                         if (!prepare_JPEGTables(tif))
    1619               0 :                                 return (0);
    1620                 :                         /* Mark the field present */
    1621                 :                         /* Can't use TIFFSetField since BEENWRITING is already set! */
    1622              14 :                         tif->tif_flags |= TIFF_DIRTYDIRECT;
    1623              14 :                         TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
    1624                 :                 }
    1625                 :   } else {
    1626                 :     /* We do not support application-supplied JPEGTables, */
    1627                 :     /* so mark the field not present */
    1628               0 :     TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
    1629                 :   }
    1630                 : 
    1631                 :   /* Direct libjpeg output to libtiff's output buffer */
    1632              32 :   TIFFjpeg_data_dest(sp, tif);
    1633                 : 
    1634              32 :   return (1);
    1635                 : }
    1636                 : 
    1637                 : /*
    1638                 :  * Set encoding state at the start of a strip or tile.
    1639                 :  */
    1640                 : static int
    1641                 : JPEGPreEncode(TIFF* tif, uint16 s)
    1642              40 : {
    1643              40 :   JPEGState *sp = JState(tif);
    1644              40 :   TIFFDirectory *td = &tif->tif_dir;
    1645                 :   static const char module[] = "JPEGPreEncode";
    1646                 :   uint32 segment_width, segment_height;
    1647                 :   int downsampled_input;
    1648                 : 
    1649              40 :   assert(sp != NULL);
    1650                 :   
    1651              40 :   if (sp->cinfo.comm.is_decompressor == 1)
    1652                 :   {
    1653              18 :     tif->tif_setupencode( tif );
    1654                 :   }
    1655                 :   
    1656              40 :   assert(!sp->cinfo.comm.is_decompressor);
    1657                 :   /*
    1658                 :    * Set encoding parameters for this strip/tile.
    1659                 :    */
    1660              40 :   if (isTiled(tif)) {
    1661              34 :     segment_width = td->td_tilewidth;
    1662              34 :     segment_height = td->td_tilelength;
    1663              34 :     sp->bytesperline = TIFFTileRowSize(tif);
    1664                 :   } else {
    1665               6 :     segment_width = td->td_imagewidth;
    1666               6 :     segment_height = td->td_imagelength - tif->tif_row;
    1667               6 :     if (segment_height > td->td_rowsperstrip)
    1668               1 :       segment_height = td->td_rowsperstrip;
    1669               6 :     sp->bytesperline = TIFFScanlineSize(tif);
    1670                 :   }
    1671              40 :   if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
    1672                 :     /* for PC 2, scale down the strip/tile size
    1673                 :      * to match a downsampled component
    1674                 :      */
    1675              14 :     segment_width = TIFFhowmany_32(segment_width, sp->h_sampling); 
    1676              14 :     segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
    1677                 :   }
    1678              40 :   if (segment_width > 65535 || segment_height > 65535) {
    1679               0 :     TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
    1680               0 :     return (0);
    1681                 :   }
    1682              40 :   sp->cinfo.c.image_width = segment_width;
    1683              40 :   sp->cinfo.c.image_height = segment_height;
    1684              40 :   downsampled_input = FALSE;
    1685              40 :   if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
    1686              19 :     sp->cinfo.c.input_components = td->td_samplesperpixel;
    1687              19 :     if (sp->photometric == PHOTOMETRIC_YCBCR) {
    1688              15 :       if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
    1689              15 :         sp->cinfo.c.in_color_space = JCS_RGB;
    1690                 :       } else {
    1691               0 :         sp->cinfo.c.in_color_space = JCS_YCbCr;
    1692               0 :         if (sp->h_sampling != 1 || sp->v_sampling != 1)
    1693               0 :           downsampled_input = TRUE;
    1694                 :       }
    1695              15 :       if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
    1696               0 :         return (0);
    1697                 :       /*
    1698                 :        * Set Y sampling factors;
    1699                 :        * we assume jpeg_set_colorspace() set the rest to 1
    1700                 :        */
    1701              15 :       sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
    1702              15 :       sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
    1703                 :     } else {
    1704               4 :       sp->cinfo.c.in_color_space = JCS_UNKNOWN;
    1705               4 :       if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
    1706               0 :         return (0);
    1707                 :       /* jpeg_set_colorspace set all sampling factors to 1 */
    1708                 :     }
    1709                 :   } else {
    1710              21 :     sp->cinfo.c.input_components = 1;
    1711              21 :     sp->cinfo.c.in_color_space = JCS_UNKNOWN;
    1712              21 :     if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
    1713               0 :       return (0);
    1714              21 :     sp->cinfo.c.comp_info[0].component_id = s;
    1715                 :     /* jpeg_set_colorspace() set sampling factors to 1 */
    1716              21 :     if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
    1717               0 :       sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
    1718               0 :       sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
    1719               0 :       sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
    1720                 :     }
    1721                 :   }
    1722                 :   /* ensure libjpeg won't write any extraneous markers */
    1723              40 :   sp->cinfo.c.write_JFIF_header = FALSE;
    1724              40 :   sp->cinfo.c.write_Adobe_marker = FALSE;
    1725                 :   /* set up table handling correctly */
    1726              40 :         if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
    1727               0 :     return (0);
    1728              40 :   if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
    1729               0 :     unsuppress_quant_table(sp, 0);
    1730               0 :     unsuppress_quant_table(sp, 1);
    1731                 :   }
    1732              40 :   if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
    1733              40 :     sp->cinfo.c.optimize_coding = FALSE;
    1734                 :   else
    1735               0 :     sp->cinfo.c.optimize_coding = TRUE;
    1736              40 :   if (downsampled_input) {
    1737                 :     /* Need to use raw-data interface to libjpeg */
    1738               0 :     sp->cinfo.c.raw_data_in = TRUE;
    1739               0 :     tif->tif_encoderow = JPEGEncodeRaw;
    1740               0 :     tif->tif_encodestrip = JPEGEncodeRaw;
    1741               0 :     tif->tif_encodetile = JPEGEncodeRaw;
    1742                 :   } else {
    1743                 :     /* Use normal interface to libjpeg */
    1744              40 :     sp->cinfo.c.raw_data_in = FALSE;
    1745              40 :     tif->tif_encoderow = JPEGEncode;
    1746              40 :     tif->tif_encodestrip = JPEGEncode;
    1747              40 :     tif->tif_encodetile = JPEGEncode;
    1748                 :   }
    1749                 :   /* Start JPEG compressor */
    1750              40 :   if (!TIFFjpeg_start_compress(sp, FALSE))
    1751               0 :     return (0);
    1752                 :   /* Allocate downsampled-data buffers if needed */
    1753              40 :   if (downsampled_input) {
    1754               0 :     if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
    1755                 :                  sp->cinfo.c.num_components))
    1756               0 :       return (0);
    1757                 :   }
    1758              40 :   sp->scancount = 0;
    1759                 : 
    1760              40 :   return (1);
    1761                 : }
    1762                 : 
    1763                 : /*
    1764                 :  * Encode a chunk of pixels.
    1765                 :  * "Standard" case: incoming data is not downsampled.
    1766                 :  */
    1767                 : static int
    1768                 : JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
    1769            2087 : {
    1770            2087 :   JPEGState *sp = JState(tif);
    1771                 :   tmsize_t nrows;
    1772                 :   JSAMPROW bufptr[1];
    1773            2087 :         short *line16 = NULL;
    1774            2087 :         int    line16_count = 0;
    1775                 : 
    1776                 :   (void) s;
    1777            2087 :   assert(sp != NULL);
    1778                 :   /* data is expected to be supplied in multiples of a scanline */
    1779            2087 :   nrows = cc / sp->bytesperline;
    1780            2087 :   if (cc % sp->bytesperline)
    1781               0 :             TIFFWarningExt(tif->tif_clientdata, tif->tif_name, 
    1782                 :                            "fractional scanline discarded");
    1783                 : 
    1784                 :         /* The last strip will be limited to image size */
    1785            2087 :         if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
    1786               0 :             nrows = tif->tif_dir.td_imagelength - tif->tif_row;
    1787                 : 
    1788            2087 :         if( sp->cinfo.c.data_precision == 12 )
    1789                 :         {
    1790               3 :             line16_count = (sp->bytesperline * 2) / 3;
    1791               3 :             line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
    1792                 :         }
    1793                 :             
    1794           15634 :   while (nrows-- > 0) {
    1795                 : 
    1796           11460 :             if( sp->cinfo.c.data_precision == 12 )
    1797                 :             {
    1798                 : 
    1799             320 :                 int value_pairs = line16_count / 2;
    1800                 :                 int iPair;
    1801                 : 
    1802             320 :     bufptr[0] = (JSAMPROW) line16;
    1803                 : 
    1804           22848 :                 for( iPair = 0; iPair < value_pairs; iPair++ )
    1805                 :                 {
    1806                 :                     unsigned char *in_ptr =
    1807           22528 :                         ((unsigned char *) buf) + iPair * 3;
    1808           22528 :                     JSAMPLE *out_ptr = (JSAMPLE *) (line16 + iPair * 2);
    1809                 : 
    1810           22528 :                     out_ptr[0] = (in_ptr[0] << 4) | ((in_ptr[1] & 0xf0) >> 4);
    1811           22528 :                     out_ptr[1] = ((in_ptr[1] & 0x0f) << 8) | in_ptr[2];
    1812                 :                 }
    1813                 :             }
    1814                 :             else
    1815                 :             {
    1816           11140 :     bufptr[0] = (JSAMPROW) buf;
    1817                 :             }
    1818           11460 :             if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
    1819               0 :                 return (0);
    1820           11460 :             if (nrows > 0)
    1821            9373 :                 tif->tif_row++;
    1822           11460 :             buf += sp->bytesperline;
    1823                 :   }
    1824                 : 
    1825            2087 :         if( sp->cinfo.c.data_precision == 12 )
    1826                 :         {
    1827               3 :             _TIFFfree( line16 );
    1828                 :         }
    1829                 :             
    1830            2087 :   return (1);
    1831                 : }
    1832                 : 
    1833                 : /*
    1834                 :  * Encode a chunk of pixels.
    1835                 :  * Incoming data is expected to be downsampled per sampling factors.
    1836                 :  */
    1837                 : static int
    1838                 : JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
    1839               0 : {
    1840               0 :   JPEGState *sp = JState(tif);
    1841                 :   JSAMPLE* inptr;
    1842                 :   JSAMPLE* outptr;
    1843                 :   tmsize_t nrows;
    1844                 :   JDIMENSION clumps_per_line, nclump;
    1845                 :   int clumpoffset, ci, xpos, ypos;
    1846                 :   jpeg_component_info* compptr;
    1847               0 :   int samples_per_clump = sp->samplesperclump;
    1848                 :   tmsize_t bytesperclumpline;
    1849                 : 
    1850                 :   (void) s;
    1851               0 :   assert(sp != NULL);
    1852                 :   /* data is expected to be supplied in multiples of a clumpline */
    1853                 :   /* a clumpline is equivalent to v_sampling desubsampled scanlines */
    1854                 :   /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
    1855               0 :   bytesperclumpline = (((sp->cinfo.c.image_width+sp->h_sampling-1)/sp->h_sampling)
    1856                 :            *(sp->h_sampling*sp->v_sampling+2)*sp->cinfo.c.data_precision+7)
    1857                 :           /8;
    1858                 : 
    1859               0 :   nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
    1860               0 :   if (cc % bytesperclumpline)
    1861               0 :     TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
    1862                 : 
    1863                 :   /* Cb,Cr both have sampling factors 1, so this is correct */
    1864               0 :   clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
    1865                 : 
    1866               0 :   while (nrows > 0) {
    1867                 :     /*
    1868                 :      * Fastest way to separate the data is to make one pass
    1869                 :      * over the scanline for each row of each component.
    1870                 :      */
    1871               0 :     clumpoffset = 0;    /* first sample in clump */
    1872               0 :     for (ci = 0, compptr = sp->cinfo.c.comp_info;
    1873               0 :          ci < sp->cinfo.c.num_components;
    1874               0 :          ci++, compptr++) {
    1875               0 :         int hsamp = compptr->h_samp_factor;
    1876               0 :         int vsamp = compptr->v_samp_factor;
    1877                 :         int padding = (int) (compptr->width_in_blocks * DCTSIZE -
    1878               0 :            clumps_per_line * hsamp);
    1879               0 :         for (ypos = 0; ypos < vsamp; ypos++) {
    1880               0 :       inptr = ((JSAMPLE*) buf) + clumpoffset;
    1881               0 :       outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
    1882               0 :       if (hsamp == 1) {
    1883                 :           /* fast path for at least Cb and Cr */
    1884               0 :           for (nclump = clumps_per_line; nclump-- > 0; ) {
    1885               0 :         *outptr++ = inptr[0];
    1886               0 :         inptr += samples_per_clump;
    1887                 :           }
    1888                 :       } else {
    1889                 :           /* general case */
    1890               0 :           for (nclump = clumps_per_line; nclump-- > 0; ) {
    1891               0 :         for (xpos = 0; xpos < hsamp; xpos++)
    1892               0 :             *outptr++ = inptr[xpos];
    1893               0 :         inptr += samples_per_clump;
    1894                 :           }
    1895                 :       }
    1896                 :       /* pad each scanline as needed */
    1897               0 :       for (xpos = 0; xpos < padding; xpos++) {
    1898               0 :           *outptr = outptr[-1];
    1899               0 :           outptr++;
    1900                 :       }
    1901               0 :       clumpoffset += hsamp;
    1902                 :         }
    1903                 :     }
    1904               0 :     sp->scancount++;
    1905               0 :     if (sp->scancount >= DCTSIZE) {
    1906               0 :       int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
    1907               0 :       if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
    1908               0 :         return (0);
    1909               0 :       sp->scancount = 0;
    1910                 :     }
    1911               0 :     tif->tif_row += sp->v_sampling;
    1912               0 :     buf += sp->bytesperline;
    1913               0 :     nrows -= sp->v_sampling;
    1914                 :   }
    1915               0 :   return (1);
    1916                 : }
    1917                 : 
    1918                 : /*
    1919                 :  * Finish up at the end of a strip or tile.
    1920                 :  */
    1921                 : static int
    1922                 : JPEGPostEncode(TIFF* tif)
    1923              40 : {
    1924              40 :   JPEGState *sp = JState(tif);
    1925                 : 
    1926              40 :   if (sp->scancount > 0) {
    1927                 :     /*
    1928                 :      * Need to emit a partial bufferload of downsampled data.
    1929                 :      * Pad the data vertically.
    1930                 :      */
    1931                 :     int ci, ypos, n;
    1932                 :     jpeg_component_info* compptr;
    1933                 : 
    1934               0 :     for (ci = 0, compptr = sp->cinfo.c.comp_info;
    1935               0 :          ci < sp->cinfo.c.num_components;
    1936               0 :          ci++, compptr++) {
    1937               0 :       int vsamp = compptr->v_samp_factor;
    1938                 :       tmsize_t row_width = compptr->width_in_blocks * DCTSIZE
    1939               0 :         * sizeof(JSAMPLE);
    1940               0 :       for (ypos = sp->scancount * vsamp;
    1941               0 :            ypos < DCTSIZE * vsamp; ypos++) {
    1942               0 :         _TIFFmemcpy((void*)sp->ds_buffer[ci][ypos],
    1943                 :               (void*)sp->ds_buffer[ci][ypos-1],
    1944                 :               row_width);
    1945                 : 
    1946                 :       }
    1947                 :     }
    1948               0 :     n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
    1949               0 :     if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
    1950               0 :       return (0);
    1951                 :   }
    1952                 : 
    1953              40 :   return (TIFFjpeg_finish_compress(JState(tif)));
    1954                 : }
    1955                 : 
    1956                 : static void
    1957                 : JPEGCleanup(TIFF* tif)
    1958             106 : {
    1959             106 :   JPEGState *sp = JState(tif);
    1960                 :   
    1961             106 :   assert(sp != 0);
    1962                 : 
    1963             106 :   tif->tif_tagmethods.vgetfield = sp->vgetparent;
    1964             106 :   tif->tif_tagmethods.vsetfield = sp->vsetparent;
    1965             106 :   tif->tif_tagmethods.printdir = sp->printdir;
    1966                 : 
    1967             106 :   if( sp->cinfo_initialized )
    1968              41 :       TIFFjpeg_destroy(sp); /* release libjpeg resources */
    1969             106 :   if (sp->jpegtables)    /* tag value */
    1970              95 :     _TIFFfree(sp->jpegtables);
    1971             106 :   _TIFFfree(tif->tif_data);  /* release local state */
    1972             106 :   tif->tif_data = NULL;
    1973                 : 
    1974             106 :   _TIFFSetDefaultCompressionState(tif);
    1975             106 : }
    1976                 : 
    1977                 : static void 
    1978                 : JPEGResetUpsampled( TIFF* tif )
    1979             176 : {
    1980             176 :   JPEGState* sp = JState(tif);
    1981             176 :   TIFFDirectory* td = &tif->tif_dir;
    1982                 : 
    1983                 :   /*
    1984                 :    * Mark whether returned data is up-sampled or not so TIFFStripSize
    1985                 :    * and TIFFTileSize return values that reflect the true amount of
    1986                 :    * data.
    1987                 :    */
    1988             176 :   tif->tif_flags &= ~TIFF_UPSAMPLED;
    1989             176 :   if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
    1990             170 :     if (td->td_photometric == PHOTOMETRIC_YCBCR &&
    1991                 :         sp->jpegcolormode == JPEGCOLORMODE_RGB) {
    1992              74 :       tif->tif_flags |= TIFF_UPSAMPLED;
    1993                 :     } else {
    1994                 : #ifdef notdef
    1995                 :       if (td->td_ycbcrsubsampling[0] != 1 ||
    1996                 :           td->td_ycbcrsubsampling[1] != 1)
    1997                 :         ; /* XXX what about up-sampling? */
    1998                 : #endif
    1999                 :     }
    2000                 :   }
    2001                 : 
    2002                 :   /*
    2003                 :    * Must recalculate cached tile size in case sampling state changed.
    2004                 :    * Should we really be doing this now if image size isn't set? 
    2005                 :    */
    2006             176 :         if( tif->tif_tilesize > 0 )
    2007              54 :             tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);   
    2008             176 :         if( tif->tif_scanlinesize > 0 )
    2009             107 :             tif->tif_scanlinesize = TIFFScanlineSize(tif); 
    2010             176 : }
    2011                 : 
    2012                 : static int
    2013                 : JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
    2014            1163 : {
    2015            1163 :   JPEGState* sp = JState(tif);
    2016                 :   const TIFFField* fip;
    2017                 :   uint32 v32;
    2018                 : 
    2019            1163 :   assert(sp != NULL);
    2020                 : 
    2021            1163 :   switch (tag) {
    2022                 :   case TIFFTAG_JPEGTABLES:
    2023              67 :     v32 = (uint32) va_arg(ap, uint32);
    2024              67 :     if (v32 == 0) {
    2025                 :       /* XXX */
    2026               0 :       return (0);
    2027                 :     }
    2028              67 :     _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
    2029                 :         (long) v32);
    2030              67 :     sp->jpegtables_length = v32;
    2031              67 :     TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
    2032                 :     break;
    2033                 :   case TIFFTAG_JPEGQUALITY:
    2034              11 :     sp->jpegquality = (int) va_arg(ap, int);
    2035              11 :     return (1);     /* pseudo tag */
    2036                 :   case TIFFTAG_JPEGCOLORMODE:
    2037              75 :     sp->jpegcolormode = (int) va_arg(ap, int);
    2038              75 :     JPEGResetUpsampled( tif );
    2039              75 :     return (1);     /* pseudo tag */
    2040                 :   case TIFFTAG_PHOTOMETRIC:
    2041                 :   {
    2042             101 :     int ret_value = (*sp->vsetparent)(tif, tag, ap);
    2043             101 :     JPEGResetUpsampled( tif );
    2044             101 :     return ret_value;
    2045                 :   }
    2046                 :   case TIFFTAG_JPEGTABLESMODE:
    2047               0 :     sp->jpegtablesmode = (int) va_arg(ap, int);
    2048               0 :     return (1);     /* pseudo tag */
    2049                 :   case TIFFTAG_YCBCRSUBSAMPLING:
    2050                 :     /* mark the fact that we have a real ycbcrsubsampling! */
    2051               0 :     sp->ycbcrsampling_fetched = 1;
    2052                 :     /* should we be recomputing upsampling info here? */
    2053               0 :     return (*sp->vsetparent)(tif, tag, ap);
    2054                 :   default:
    2055             909 :     return (*sp->vsetparent)(tif, tag, ap);
    2056                 :   }
    2057                 : 
    2058              67 :   if ((fip = TIFFFieldWithTag(tif, tag))) {
    2059              67 :     TIFFSetFieldBit(tif, fip->field_bit);
    2060                 :   } else {
    2061               0 :     return (0);
    2062                 :   }
    2063                 : 
    2064              67 :   tif->tif_flags |= TIFF_DIRTYDIRECT;
    2065              67 :   return (1);
    2066                 : }
    2067                 : 
    2068                 : static int
    2069                 : JPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
    2070            1980 : {
    2071            1980 :   JPEGState* sp = JState(tif);
    2072                 : 
    2073            1980 :   assert(sp != NULL);
    2074                 : 
    2075            1980 :   switch (tag) {
    2076                 :     case TIFFTAG_JPEGTABLES:
    2077              28 :       *va_arg(ap, uint32*) = sp->jpegtables_length;
    2078              28 :       *va_arg(ap, void**) = sp->jpegtables;
    2079              28 :       break;
    2080                 :     case TIFFTAG_JPEGQUALITY:
    2081               6 :       *va_arg(ap, int*) = sp->jpegquality;
    2082               6 :       break;
    2083                 :     case TIFFTAG_JPEGCOLORMODE:
    2084              72 :       *va_arg(ap, int*) = sp->jpegcolormode;
    2085              72 :       break;
    2086                 :     case TIFFTAG_JPEGTABLESMODE:
    2087               0 :       *va_arg(ap, int*) = sp->jpegtablesmode;
    2088               0 :       break;
    2089                 :     default:
    2090            1874 :       return (*sp->vgetparent)(tif, tag, ap);
    2091                 :   }
    2092             106 :   return (1);
    2093                 : }
    2094                 : 
    2095                 : static void
    2096                 : JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
    2097               0 : {
    2098               0 :   JPEGState* sp = JState(tif);
    2099                 : 
    2100               0 :   assert(sp != NULL);
    2101                 : 
    2102                 :   (void) flags;
    2103               0 :   if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
    2104               0 :     fprintf(fd, "  JPEG Tables: (%lu bytes)\n",
    2105                 :       (unsigned long) sp->jpegtables_length);
    2106               0 :   if (sp->printdir)
    2107               0 :     (*sp->printdir)(tif, fd, flags);
    2108               0 : }
    2109                 : 
    2110                 : static uint32
    2111                 : JPEGDefaultStripSize(TIFF* tif, uint32 s)
    2112               6 : {
    2113               6 :   JPEGState* sp = JState(tif);
    2114               6 :   TIFFDirectory *td = &tif->tif_dir;
    2115                 : 
    2116               6 :   s = (*sp->defsparent)(tif, s);
    2117               6 :   if (s < td->td_imagelength)
    2118               4 :     s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
    2119               6 :   return (s);
    2120                 : }
    2121                 : 
    2122                 : static void
    2123                 : JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
    2124               0 : {
    2125               0 :   JPEGState* sp = JState(tif);
    2126               0 :   TIFFDirectory *td = &tif->tif_dir;
    2127                 : 
    2128               0 :   (*sp->deftparent)(tif, tw, th);
    2129               0 :   *tw = TIFFroundup_32(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
    2130               0 :   *th = TIFFroundup_32(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
    2131               0 : }
    2132                 : 
    2133                 : /*
    2134                 :  * The JPEG library initialized used to be done in TIFFInitJPEG(), but
    2135                 :  * now that we allow a TIFF file to be opened in update mode it is necessary
    2136                 :  * to have some way of deciding whether compression or decompression is
    2137                 :  * desired other than looking at tif->tif_mode.  We accomplish this by 
    2138                 :  * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
    2139                 :  * If so, we assume decompression is desired. 
    2140                 :  *
    2141                 :  * This is tricky, because TIFFInitJPEG() is called while the directory is
    2142                 :  * being read, and generally speaking the BYTECOUNTS tag won't have been read
    2143                 :  * at that point.  So we try to defer jpeg library initialization till we
    2144                 :  * do have that tag ... basically any access that might require the compressor
    2145                 :  * or decompressor that occurs after the reading of the directory. 
    2146                 :  *
    2147                 :  * In an ideal world compressors or decompressors would be setup
    2148                 :  * at the point where a single tile or strip was accessed (for read or write)
    2149                 :  * so that stuff like update of missing tiles, or replacement of tiles could
    2150                 :  * be done. However, we aren't trying to crack that nut just yet ...
    2151                 :  *
    2152                 :  * NFW, Feb 3rd, 2003.
    2153                 :  */
    2154                 : 
    2155                 : static int JPEGInitializeLibJPEG( TIFF * tif, int decompress )
    2156              77 : {
    2157              77 :     JPEGState* sp = JState(tif);
    2158              77 :     uint64* byte_counts = NULL;
    2159              77 :     int     data_is_empty = TRUE;
    2160                 : 
    2161              77 :     if(sp->cinfo_initialized)
    2162                 :     {
    2163              54 :         if( !decompress && sp->cinfo.comm.is_decompressor )
    2164              18 :             TIFFjpeg_destroy( sp );
    2165              36 :         else if( decompress && !sp->cinfo.comm.is_decompressor )
    2166              18 :             TIFFjpeg_destroy( sp );
    2167                 :         else
    2168               0 :             return 1;
    2169                 : 
    2170              36 :         sp->cinfo_initialized = 0;
    2171                 :     }
    2172                 : 
    2173                 :     /*
    2174                 :      * Do we have tile data already?  Make sure we initialize the
    2175                 :      * the state in decompressor mode if we have tile data, even if we
    2176                 :      * are not in read-only file access mode. 
    2177                 :      */
    2178              77 :     if( TIFFIsTiled( tif ) 
    2179                 :         && TIFFGetField( tif, TIFFTAG_TILEBYTECOUNTS, &byte_counts ) 
    2180                 :         && byte_counts != NULL )
    2181                 :     {
    2182              58 :         data_is_empty = byte_counts[0] == 0;
    2183                 :     }
    2184              77 :     if( !TIFFIsTiled( tif ) 
    2185                 :         && TIFFGetField( tif, TIFFTAG_STRIPBYTECOUNTS, &byte_counts) 
    2186                 :         && byte_counts != NULL )
    2187                 :     {
    2188              19 :         data_is_empty = byte_counts[0] == 0;
    2189                 :     }
    2190                 : 
    2191                 :     /*
    2192                 :      * Initialize libjpeg.
    2193                 :      */
    2194              77 :     if ( decompress ) {
    2195              45 :         if (!TIFFjpeg_create_decompress(sp))
    2196               0 :             return (0);
    2197                 :     } else {
    2198              32 :         if (!TIFFjpeg_create_compress(sp))
    2199               0 :             return (0);
    2200                 :     }
    2201                 : 
    2202              77 :     sp->cinfo_initialized = TRUE;
    2203                 : 
    2204              77 :     return 1;
    2205                 : }
    2206                 : 
    2207                 : int
    2208                 : TIFFInitJPEG(TIFF* tif, int scheme)
    2209             108 : {
    2210                 :   JPEGState* sp;
    2211                 : 
    2212             108 :   assert(scheme == COMPRESSION_JPEG);
    2213                 : 
    2214                 :   /*
    2215                 :    * Merge codec-specific tag information.
    2216                 :    */
    2217             108 :   if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields))) {
    2218               0 :     TIFFErrorExt(tif->tif_clientdata,
    2219                 :            "TIFFInitJPEG",
    2220                 :            "Merging JPEG codec-specific tags failed");
    2221               0 :     return 0;
    2222                 :   }
    2223                 : 
    2224                 :   /*
    2225                 :    * Allocate state block so tag methods have storage to record values.
    2226                 :    */
    2227             108 :   tif->tif_data = (uint8*) _TIFFmalloc(sizeof (JPEGState));
    2228                 : 
    2229             108 :   if (tif->tif_data == NULL) {
    2230               0 :     TIFFErrorExt(tif->tif_clientdata,
    2231                 :            "TIFFInitJPEG", "No space for JPEG state block");
    2232               0 :     return 0;
    2233                 :   }
    2234             108 :         _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
    2235                 : 
    2236             108 :   sp = JState(tif);
    2237             108 :   sp->tif = tif;       /* back link */
    2238                 : 
    2239                 :   /*
    2240                 :    * Override parent get/set field methods.
    2241                 :    */
    2242             108 :   sp->vgetparent = tif->tif_tagmethods.vgetfield;
    2243             108 :   tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
    2244             108 :   sp->vsetparent = tif->tif_tagmethods.vsetfield;
    2245             108 :   tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
    2246             108 :   sp->printdir = tif->tif_tagmethods.printdir;
    2247             108 :   tif->tif_tagmethods.printdir = JPEGPrintDir;   /* hook for codec tags */
    2248                 : 
    2249                 :   /* Default values for codec-specific fields */
    2250             108 :   sp->jpegtables = NULL;
    2251             108 :   sp->jpegtables_length = 0;
    2252             108 :   sp->jpegquality = 75;      /* Default IJG quality */
    2253             108 :   sp->jpegcolormode = JPEGCOLORMODE_RAW;
    2254             108 :   sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
    2255             108 :         sp->ycbcrsampling_fetched = 0;
    2256                 : 
    2257                 :   /*
    2258                 :    * Install codec methods.
    2259                 :    */
    2260             108 :   tif->tif_fixuptags = JPEGFixupTags;
    2261             108 :   tif->tif_setupdecode = JPEGSetupDecode;
    2262             108 :   tif->tif_predecode = JPEGPreDecode;
    2263             108 :   tif->tif_decoderow = JPEGDecode;
    2264             108 :   tif->tif_decodestrip = JPEGDecode;
    2265             108 :   tif->tif_decodetile = JPEGDecode;
    2266             108 :   tif->tif_setupencode = JPEGSetupEncode;
    2267             108 :   tif->tif_preencode = JPEGPreEncode;
    2268             108 :   tif->tif_postencode = JPEGPostEncode;
    2269             108 :   tif->tif_encoderow = JPEGEncode;
    2270             108 :   tif->tif_encodestrip = JPEGEncode;
    2271             108 :   tif->tif_encodetile = JPEGEncode;  
    2272             108 :   tif->tif_cleanup = JPEGCleanup;
    2273             108 :   sp->defsparent = tif->tif_defstripsize;
    2274             108 :   tif->tif_defstripsize = JPEGDefaultStripSize;
    2275             108 :   sp->deftparent = tif->tif_deftilesize;
    2276             108 :   tif->tif_deftilesize = JPEGDefaultTileSize;
    2277             108 :   tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
    2278                 : 
    2279             108 :         sp->cinfo_initialized = FALSE;
    2280                 : 
    2281                 :   /*
    2282                 :         ** Create a JPEGTables field if no directory has yet been created. 
    2283                 :         ** We do this just to ensure that sufficient space is reserved for
    2284                 :         ** the JPEGTables field.  It will be properly created the right
    2285                 :         ** size later. 
    2286                 :         */
    2287             108 :         if( tif->tif_diroff == 0 )
    2288                 :         {
    2289                 : #define SIZE_OF_JPEGTABLES 2000
    2290                 : /*
    2291                 : The following line assumes incorrectly that all JPEG-in-TIFF files will have
    2292                 : a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
    2293                 : when the JPEG data is placed with TIFFWriteRawStrip.  The field bit should be 
    2294                 : set, anyway, later when actual JPEGTABLES header is generated, so removing it 
    2295                 : here hopefully is harmless.
    2296                 :             TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
    2297                 : */
    2298              14 :             sp->jpegtables_length = SIZE_OF_JPEGTABLES;
    2299              14 :             sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
    2300              14 :       _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
    2301                 : #undef SIZE_OF_JPEGTABLES
    2302                 :         }
    2303                 : 
    2304             108 :   return 1;
    2305                 : }
    2306                 : #endif /* JPEG_SUPPORT */
    2307                 : 
    2308                 : /* vim: set ts=8 sts=8 sw=8 noet: */
    2309                 : 
    2310                 : /*
    2311                 :  * Local Variables:
    2312                 :  * mode: c
    2313                 :  * c-basic-offset: 8
    2314                 :  * fill-column: 78
    2315                 :  * End:
    2316                 :  */

Generated by: LTP GCOV extension version 1.5