ReactOS Fundraising Campaign 2012
 
€ 4,410 / € 30,000

Information | Donate

Home | Info | Community | Development | myReactOS | Contact Us

  1. Home
  2. Community
  3. Development
  4. myReactOS
  5. Fundraiser 2012

  1. Main Page
  2. Alphabetical List
  3. Data Structures
  4. Directories
  5. File List
  6. Data Fields
  7. Globals
  8. Related Pages

ReactOS Development > Doxygen

tif_jpeg.c
Go to the documentation of this file.
00001 /* $Id: tif_jpeg.c,v 1.50.2.9 2010-06-14 02:47:16 fwarmerdam Exp $ */
00002 
00003 /*
00004  * Copyright (c) 1994-1997 Sam Leffler
00005  * Copyright (c) 1994-1997 Silicon Graphics, Inc.
00006  *
00007  * Permission to use, copy, modify, distribute, and sell this software and 
00008  * its documentation for any purpose is hereby granted without fee, provided
00009  * that (i) the above copyright notices and this permission notice appear in
00010  * all copies of the software and related documentation, and (ii) the names of
00011  * Sam Leffler and Silicon Graphics may not be used in any advertising or
00012  * publicity relating to the software without the specific, prior written
00013  * permission of Sam Leffler and Silicon Graphics.
00014  * 
00015  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
00016  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
00017  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
00018  * 
00019  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
00020  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
00021  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
00022  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
00023  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
00024  * OF THIS SOFTWARE.
00025  */
00026 
00027 #define WIN32_LEAN_AND_MEAN
00028 #define VC_EXTRALEAN
00029 
00030 #include "tiffiop.h"
00031 #ifdef JPEG_SUPPORT
00032 
00033 /*
00034  * TIFF Library
00035  *
00036  * JPEG Compression support per TIFF Technical Note #2
00037  * (*not* per the original TIFF 6.0 spec).
00038  *
00039  * This file is simply an interface to the libjpeg library written by
00040  * the Independent JPEG Group.  You need release 5 or later of the IJG
00041  * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
00042  *
00043  * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
00044  */
00045 #include <setjmp.h>
00046 
00047 int TIFFFillStrip(TIFF*, tstrip_t);
00048 int TIFFFillTile(TIFF*, ttile_t);
00049 
00050 /* We undefine FAR to avoid conflict with JPEG definition */
00051 
00052 #ifdef FAR
00053 #undef FAR
00054 #endif
00055 
00056 /*
00057   Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
00058   not defined.  Unfortunately, the MinGW and Borland compilers include
00059   a typedef for INT32, which causes a conflict.  MSVC does not include
00060   a conficting typedef given the headers which are included.
00061 */
00062 #if defined(__BORLANDC__) || defined(__MINGW32__)
00063 # define XMD_H 1
00064 #endif
00065 
00066 /*
00067    The windows RPCNDR.H file defines boolean, but defines it with the
00068    unsigned char size.  You should compile JPEG library using appropriate
00069    definitions in jconfig.h header, but many users compile library in wrong
00070    way. That causes errors of the following type:
00071 
00072    "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
00073    caller expects 464"
00074 
00075    For such users we wil fix the problem here. See install.doc file from
00076    the JPEG library distribution for details.
00077 */
00078 
00079 /* Define "boolean" as unsigned char, not int, per Windows custom. */
00080 #if defined(WIN32) && !defined(__MINGW32__)
00081 # ifndef __RPCNDR_H__            /* don't conflict if rpcndr.h already read */
00082    typedef unsigned char boolean;
00083 # endif
00084 # define HAVE_BOOLEAN            /* prevent jmorecfg.h from redefining it */
00085 #endif
00086 
00087 #include "jpeglib.h"
00088 #include "jerror.h"
00089 
00090 /*
00091  * We are using width_in_blocks which is supposed to be private to
00092  * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
00093  * renamed this member to width_in_data_units.  Since the header has
00094  * also renamed a define, use that unique define name in order to
00095  * detect the problem header and adjust to suit.
00096  */
00097 #if defined(D_MAX_DATA_UNITS_IN_MCU)
00098 #define width_in_blocks width_in_data_units
00099 #endif
00100 
00101 /*
00102  * On some machines it may be worthwhile to use _setjmp or sigsetjmp
00103  * in place of plain setjmp.  These macros will make it easier.
00104  */
00105 #define SETJMP(jbuf)        setjmp(jbuf)
00106 #define LONGJMP(jbuf,code)  longjmp(jbuf,code)
00107 #define JMP_BUF         jmp_buf
00108 
00109 typedef struct jpeg_destination_mgr jpeg_destination_mgr;
00110 typedef struct jpeg_source_mgr jpeg_source_mgr;
00111 typedef struct jpeg_error_mgr jpeg_error_mgr;
00112 
00113 /*
00114  * State block for each open TIFF file using
00115  * libjpeg to do JPEG compression/decompression.
00116  *
00117  * libjpeg's visible state is either a jpeg_compress_struct
00118  * or jpeg_decompress_struct depending on which way we
00119  * are going.  comm can be used to refer to the fields
00120  * which are common to both.
00121  *
00122  * NB: cinfo is required to be the first member of JPEGState,
00123  *     so we can safely cast JPEGState* -> jpeg_xxx_struct*
00124  *     and vice versa!
00125  */
00126 typedef struct {
00127     union {
00128         struct jpeg_compress_struct c;
00129         struct jpeg_decompress_struct d;
00130         struct jpeg_common_struct comm;
00131     } cinfo;            /* NB: must be first */
00132         int             cinfo_initialized;
00133 
00134     jpeg_error_mgr  err;        /* libjpeg error manager */
00135     JMP_BUF     exit_jmpbuf;    /* for catching libjpeg failures */
00136     /*
00137      * The following two members could be a union, but
00138      * they're small enough that it's not worth the effort.
00139      */
00140     jpeg_destination_mgr dest;  /* data dest for compression */
00141     jpeg_source_mgr src;        /* data source for decompression */
00142                     /* private state */
00143     TIFF*       tif;        /* back link needed by some code */
00144     uint16      photometric;    /* copy of PhotometricInterpretation */
00145     uint16      h_sampling; /* luminance sampling factors */
00146     uint16      v_sampling;
00147     tsize_t     bytesperline;   /* decompressed bytes per scanline */
00148     /* pointers to intermediate buffers when processing downsampled data */
00149     JSAMPARRAY  ds_buffer[MAX_COMPONENTS];
00150     int     scancount;  /* number of "scanlines" accumulated */
00151     int     samplesperclump;
00152 
00153     TIFFVGetMethod  vgetparent; /* super-class method */
00154     TIFFVSetMethod  vsetparent; /* super-class method */
00155     TIFFPrintMethod printdir;   /* super-class method */
00156     TIFFStripMethod defsparent; /* super-class method */
00157     TIFFTileMethod  deftparent; /* super-class method */
00158                     /* pseudo-tag fields */
00159     void*       jpegtables; /* JPEGTables tag value, or NULL */
00160     uint32      jpegtables_length; /* number of bytes in same */
00161     int     jpegquality;    /* Compression quality level */
00162     int     jpegcolormode;  /* Auto RGB<=>YCbCr convert? */
00163     int     jpegtablesmode; /* What to put in JPEGTables */
00164 
00165         int             ycbcrsampling_fetched;
00166     uint32      recvparams; /* encoded Class 2 session params */
00167     char*       subaddress; /* subaddress string */
00168     uint32      recvtime;   /* time spent receiving (secs) */
00169     char*       faxdcs;     /* encoded fax parameters (DCS, Table 2/T.30) */
00170 } JPEGState;
00171 
00172 #define JState(tif) ((JPEGState*)(tif)->tif_data)
00173 
00174 static  int JPEGDecode(TIFF*, tidata_t, tsize_t, tsample_t);
00175 static  int JPEGDecodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
00176 static  int JPEGEncode(TIFF*, tidata_t, tsize_t, tsample_t);
00177 static  int JPEGEncodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
00178 static  int JPEGInitializeLibJPEG( TIFF * tif,
00179                                    int force_encode, int force_decode );
00180 
00181 #define FIELD_JPEGTABLES    (FIELD_CODEC+0)
00182 #define FIELD_RECVPARAMS    (FIELD_CODEC+1)
00183 #define FIELD_SUBADDRESS    (FIELD_CODEC+2)
00184 #define FIELD_RECVTIME      (FIELD_CODEC+3)
00185 #define FIELD_FAXDCS        (FIELD_CODEC+4)
00186 
00187 static const TIFFFieldInfo jpegFieldInfo[] = {
00188     { TIFFTAG_JPEGTABLES,    -3,-3, TIFF_UNDEFINED, FIELD_JPEGTABLES,
00189       FALSE,    TRUE,   "JPEGTables" },
00190     { TIFFTAG_JPEGQUALITY,   0, 0,  TIFF_ANY,   FIELD_PSEUDO,
00191       TRUE, FALSE,  "" },
00192     { TIFFTAG_JPEGCOLORMODE,     0, 0,  TIFF_ANY,   FIELD_PSEUDO,
00193       FALSE,    FALSE,  "" },
00194     { TIFFTAG_JPEGTABLESMODE,    0, 0,  TIFF_ANY,   FIELD_PSEUDO,
00195       FALSE,    FALSE,  "" },
00196     /* Specific for JPEG in faxes */
00197     { TIFFTAG_FAXRECVPARAMS,     1, 1, TIFF_LONG,   FIELD_RECVPARAMS,
00198       TRUE, FALSE,  "FaxRecvParams" },
00199     { TIFFTAG_FAXSUBADDRESS,    -1,-1, TIFF_ASCII,  FIELD_SUBADDRESS,
00200       TRUE, FALSE,  "FaxSubAddress" },
00201     { TIFFTAG_FAXRECVTIME,   1, 1, TIFF_LONG,   FIELD_RECVTIME,
00202       TRUE, FALSE,  "FaxRecvTime" },
00203     { TIFFTAG_FAXDCS,       -1, -1, TIFF_ASCII, FIELD_FAXDCS,
00204       TRUE, FALSE,  "FaxDcs" },
00205 };
00206 #define N(a)    (sizeof (a) / sizeof (a[0]))
00207 
00208 /*
00209  * libjpeg interface layer.
00210  *
00211  * We use setjmp/longjmp to return control to libtiff
00212  * when a fatal error is encountered within the JPEG
00213  * library.  We also direct libjpeg error and warning
00214  * messages through the appropriate libtiff handlers.
00215  */
00216 
00217 /*
00218  * Error handling routines (these replace corresponding
00219  * IJG routines from jerror.c).  These are used for both
00220  * compression and decompression.
00221  */
00222 static void
00223 TIFFjpeg_error_exit(j_common_ptr cinfo)
00224 {
00225     JPEGState *sp = (JPEGState *) cinfo;    /* NB: cinfo assumed first */
00226     char buffer[JMSG_LENGTH_MAX];
00227 
00228     (*cinfo->err->format_message) (cinfo, buffer);
00229     TIFFErrorExt(sp->tif->tif_clientdata, "JPEGLib", "%s", buffer);     /* display the error message */
00230     jpeg_abort(cinfo);          /* clean up libjpeg state */
00231     LONGJMP(sp->exit_jmpbuf, 1);        /* return to libtiff caller */
00232 }
00233 
00234 /*
00235  * This routine is invoked only for warning messages,
00236  * since error_exit does its own thing and trace_level
00237  * is never set > 0.
00238  */
00239 static void
00240 TIFFjpeg_output_message(j_common_ptr cinfo)
00241 {
00242     char buffer[JMSG_LENGTH_MAX];
00243 
00244     (*cinfo->err->format_message) (cinfo, buffer);
00245     TIFFWarningExt(((JPEGState *) cinfo)->tif->tif_clientdata, "JPEGLib", "%s", buffer);
00246 }
00247 
00248 /*
00249  * Interface routines.  This layer of routines exists
00250  * primarily to limit side-effects from using setjmp.
00251  * Also, normal/error returns are converted into return
00252  * values per libtiff practice.
00253  */
00254 #define CALLJPEG(sp, fail, op)  (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
00255 #define CALLVJPEG(sp, op)   CALLJPEG(sp, 0, ((op),1))
00256 
00257 static int
00258 TIFFjpeg_create_compress(JPEGState* sp)
00259 {
00260     /* initialize JPEG error handling */
00261     sp->cinfo.c.err = jpeg_std_error(&sp->err);
00262     sp->err.error_exit = TIFFjpeg_error_exit;
00263     sp->err.output_message = TIFFjpeg_output_message;
00264 
00265     return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
00266 }
00267 
00268 static int
00269 TIFFjpeg_create_decompress(JPEGState* sp)
00270 {
00271     /* initialize JPEG error handling */
00272     sp->cinfo.d.err = jpeg_std_error(&sp->err);
00273     sp->err.error_exit = TIFFjpeg_error_exit;
00274     sp->err.output_message = TIFFjpeg_output_message;
00275 
00276     return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
00277 }
00278 
00279 static int
00280 TIFFjpeg_set_defaults(JPEGState* sp)
00281 {
00282     return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
00283 }
00284 
00285 static int
00286 TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
00287 {
00288     return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
00289 }
00290 
00291 static int
00292 TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
00293 {
00294     return CALLVJPEG(sp,
00295         jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
00296 }
00297 
00298 static int
00299 TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
00300 {
00301     return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
00302 }
00303 
00304 static int
00305 TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
00306 {
00307     return CALLVJPEG(sp,
00308         jpeg_start_compress(&sp->cinfo.c, write_all_tables));
00309 }
00310 
00311 static int
00312 TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
00313 {
00314     return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
00315         scanlines, (JDIMENSION) num_lines));
00316 }
00317 
00318 static int
00319 TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
00320 {
00321     return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
00322         data, (JDIMENSION) num_lines));
00323 }
00324 
00325 static int
00326 TIFFjpeg_finish_compress(JPEGState* sp)
00327 {
00328     return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
00329 }
00330 
00331 static int
00332 TIFFjpeg_write_tables(JPEGState* sp)
00333 {
00334     return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
00335 }
00336 
00337 static int
00338 TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
00339 {
00340     return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
00341 }
00342 
00343 static int
00344 TIFFjpeg_start_decompress(JPEGState* sp)
00345 {
00346     return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
00347 }
00348 
00349 static int
00350 TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
00351 {
00352     return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
00353         scanlines, (JDIMENSION) max_lines));
00354 }
00355 
00356 static int
00357 TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
00358 {
00359     return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
00360         data, (JDIMENSION) max_lines));
00361 }
00362 
00363 static int
00364 TIFFjpeg_finish_decompress(JPEGState* sp)
00365 {
00366     return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
00367 }
00368 
00369 static int
00370 TIFFjpeg_abort(JPEGState* sp)
00371 {
00372     return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
00373 }
00374 
00375 static int
00376 TIFFjpeg_destroy(JPEGState* sp)
00377 {
00378     return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
00379 }
00380 
00381 static JSAMPARRAY
00382 TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
00383               JDIMENSION samplesperrow, JDIMENSION numrows)
00384 {
00385     return CALLJPEG(sp, (JSAMPARRAY) NULL,
00386         (*sp->cinfo.comm.mem->alloc_sarray)
00387         (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
00388 }
00389 
00390 /*
00391  * JPEG library destination data manager.
00392  * These routines direct compressed data from libjpeg into the
00393  * libtiff output buffer.
00394  */
00395 
00396 static void
00397 std_init_destination(j_compress_ptr cinfo)
00398 {
00399     JPEGState* sp = (JPEGState*) cinfo;
00400     TIFF* tif = sp->tif;
00401 
00402     sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
00403     sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
00404 }
00405 
00406 static boolean
00407 std_empty_output_buffer(j_compress_ptr cinfo)
00408 {
00409     JPEGState* sp = (JPEGState*) cinfo;
00410     TIFF* tif = sp->tif;
00411 
00412     /* the entire buffer has been filled */
00413     tif->tif_rawcc = tif->tif_rawdatasize;
00414     TIFFFlushData1(tif);
00415     sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
00416     sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
00417 
00418     return (TRUE);
00419 }
00420 
00421 static void
00422 std_term_destination(j_compress_ptr cinfo)
00423 {
00424     JPEGState* sp = (JPEGState*) cinfo;
00425     TIFF* tif = sp->tif;
00426 
00427     tif->tif_rawcp = (tidata_t) sp->dest.next_output_byte;
00428     tif->tif_rawcc =
00429         tif->tif_rawdatasize - (tsize_t) sp->dest.free_in_buffer;
00430     /* NB: libtiff does the final buffer flush */
00431 }
00432 
00433 static void
00434 TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
00435 {
00436     (void) tif;
00437     sp->cinfo.c.dest = &sp->dest;
00438     sp->dest.init_destination = std_init_destination;
00439     sp->dest.empty_output_buffer = std_empty_output_buffer;
00440     sp->dest.term_destination = std_term_destination;
00441 }
00442 
00443 /*
00444  * Alternate destination manager for outputting to JPEGTables field.
00445  */
00446 
00447 static void
00448 tables_init_destination(j_compress_ptr cinfo)
00449 {
00450     JPEGState* sp = (JPEGState*) cinfo;
00451 
00452     /* while building, jpegtables_length is allocated buffer size */
00453     sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
00454     sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
00455 }
00456 
00457 static boolean
00458 tables_empty_output_buffer(j_compress_ptr cinfo)
00459 {
00460     JPEGState* sp = (JPEGState*) cinfo;
00461     void* newbuf;
00462 
00463     /* the entire buffer has been filled; enlarge it by 1000 bytes */
00464     newbuf = _TIFFrealloc((tdata_t) sp->jpegtables,
00465                   (tsize_t) (sp->jpegtables_length + 1000));
00466     if (newbuf == NULL)
00467         ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
00468     sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
00469     sp->dest.free_in_buffer = (size_t) 1000;
00470     sp->jpegtables = newbuf;
00471     sp->jpegtables_length += 1000;
00472     return (TRUE);
00473 }
00474 
00475 static void
00476 tables_term_destination(j_compress_ptr cinfo)
00477 {
00478     JPEGState* sp = (JPEGState*) cinfo;
00479 
00480     /* set tables length to number of bytes actually emitted */
00481     sp->jpegtables_length -= sp->dest.free_in_buffer;
00482 }
00483 
00484 static int
00485 TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
00486 {
00487     (void) tif;
00488     /*
00489      * Allocate a working buffer for building tables.
00490      * Initial size is 1000 bytes, which is usually adequate.
00491      */
00492     if (sp->jpegtables)
00493         _TIFFfree(sp->jpegtables);
00494     sp->jpegtables_length = 1000;
00495     sp->jpegtables = (void*) _TIFFmalloc((tsize_t) sp->jpegtables_length);
00496     if (sp->jpegtables == NULL) {
00497         sp->jpegtables_length = 0;
00498         TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
00499         return (0);
00500     }
00501     sp->cinfo.c.dest = &sp->dest;
00502     sp->dest.init_destination = tables_init_destination;
00503     sp->dest.empty_output_buffer = tables_empty_output_buffer;
00504     sp->dest.term_destination = tables_term_destination;
00505     return (1);
00506 }
00507 
00508 /*
00509  * JPEG library source data manager.
00510  * These routines supply compressed data to libjpeg.
00511  */
00512 
00513 static void
00514 std_init_source(j_decompress_ptr cinfo)
00515 {
00516     JPEGState* sp = (JPEGState*) cinfo;
00517     TIFF* tif = sp->tif;
00518 
00519     sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
00520     sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
00521 }
00522 
00523 static boolean
00524 std_fill_input_buffer(j_decompress_ptr cinfo)
00525 {
00526     JPEGState* sp = (JPEGState* ) cinfo;
00527     static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
00528 
00529     /*
00530      * Should never get here since entire strip/tile is
00531      * read into memory before the decompressor is called,
00532      * and thus was supplied by init_source.
00533      */
00534     WARNMS(cinfo, JWRN_JPEG_EOF);
00535     /* insert a fake EOI marker */
00536     sp->src.next_input_byte = dummy_EOI;
00537     sp->src.bytes_in_buffer = 2;
00538     return (TRUE);
00539 }
00540 
00541 static void
00542 std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
00543 {
00544     JPEGState* sp = (JPEGState*) cinfo;
00545 
00546     if (num_bytes > 0) {
00547         if (num_bytes > (long) sp->src.bytes_in_buffer) {
00548             /* oops, buffer overrun */
00549             (void) std_fill_input_buffer(cinfo);
00550         } else {
00551             sp->src.next_input_byte += (size_t) num_bytes;
00552             sp->src.bytes_in_buffer -= (size_t) num_bytes;
00553         }
00554     }
00555 }
00556 
00557 static void
00558 std_term_source(j_decompress_ptr cinfo)
00559 {
00560     /* No work necessary here */
00561     /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
00562     /* (if so, need empty tables_term_source!) */
00563     (void) cinfo;
00564 }
00565 
00566 static void
00567 TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
00568 {
00569     (void) tif;
00570     sp->cinfo.d.src = &sp->src;
00571     sp->src.init_source = std_init_source;
00572     sp->src.fill_input_buffer = std_fill_input_buffer;
00573     sp->src.skip_input_data = std_skip_input_data;
00574     sp->src.resync_to_restart = jpeg_resync_to_restart;
00575     sp->src.term_source = std_term_source;
00576     sp->src.bytes_in_buffer = 0;        /* for safety */
00577     sp->src.next_input_byte = NULL;
00578 }
00579 
00580 /*
00581  * Alternate source manager for reading from JPEGTables.
00582  * We can share all the code except for the init routine.
00583  */
00584 
00585 static void
00586 tables_init_source(j_decompress_ptr cinfo)
00587 {
00588     JPEGState* sp = (JPEGState*) cinfo;
00589 
00590     sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
00591     sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
00592 }
00593 
00594 static void
00595 TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
00596 {
00597     TIFFjpeg_data_src(sp, tif);
00598     sp->src.init_source = tables_init_source;
00599 }
00600 
00601 /*
00602  * Allocate downsampled-data buffers needed for downsampled I/O.
00603  * We use values computed in jpeg_start_compress or jpeg_start_decompress.
00604  * We use libjpeg's allocator so that buffers will be released automatically
00605  * when done with strip/tile.
00606  * This is also a handy place to compute samplesperclump, bytesperline.
00607  */
00608 static int
00609 alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
00610               int num_components)
00611 {
00612     JPEGState* sp = JState(tif);
00613     int ci;
00614     jpeg_component_info* compptr;
00615     JSAMPARRAY buf;
00616     int samples_per_clump = 0;
00617 
00618     for (ci = 0, compptr = comp_info; ci < num_components;
00619          ci++, compptr++) {
00620         samples_per_clump += compptr->h_samp_factor *
00621             compptr->v_samp_factor;
00622         buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
00623                 compptr->width_in_blocks * DCTSIZE,
00624                 (JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
00625         if (buf == NULL)
00626             return (0);
00627         sp->ds_buffer[ci] = buf;
00628     }
00629     sp->samplesperclump = samples_per_clump;
00630     return (1);
00631 }
00632 
00633 
00634 /*
00635  * JPEG Decoding.
00636  */
00637 
00638 static int
00639 JPEGSetupDecode(TIFF* tif)
00640 {
00641     JPEGState* sp = JState(tif);
00642     TIFFDirectory *td = &tif->tif_dir;
00643 
00644         JPEGInitializeLibJPEG( tif, 0, 1 );
00645 
00646     assert(sp != NULL);
00647     assert(sp->cinfo.comm.is_decompressor);
00648 
00649     /* Read JPEGTables if it is present */
00650     if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
00651         TIFFjpeg_tables_src(sp, tif);
00652         if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
00653             TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
00654             return (0);
00655         }
00656     }
00657 
00658     /* Grab parameters that are same for all strips/tiles */
00659     sp->photometric = td->td_photometric;
00660     switch (sp->photometric) {
00661     case PHOTOMETRIC_YCBCR:
00662         sp->h_sampling = td->td_ycbcrsubsampling[0];
00663         sp->v_sampling = td->td_ycbcrsubsampling[1];
00664         break;
00665     default:
00666         /* TIFF 6.0 forbids subsampling of all other color spaces */
00667         sp->h_sampling = 1;
00668         sp->v_sampling = 1;
00669         break;
00670     }
00671 
00672     /* Set up for reading normal data */
00673     TIFFjpeg_data_src(sp, tif);
00674     tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
00675     return (1);
00676 }
00677 
00678 /*
00679  * Set up for decoding a strip or tile.
00680  */
00681 static int
00682 JPEGPreDecode(TIFF* tif, tsample_t s)
00683 {
00684     JPEGState *sp = JState(tif);
00685     TIFFDirectory *td = &tif->tif_dir;
00686     static const char module[] = "JPEGPreDecode";
00687     uint32 segment_width, segment_height;
00688     int downsampled_output;
00689     int ci;
00690 
00691     assert(sp != NULL);
00692     assert(sp->cinfo.comm.is_decompressor);
00693     /*
00694      * Reset decoder state from any previous strip/tile,
00695      * in case application didn't read the whole strip.
00696      */
00697     if (!TIFFjpeg_abort(sp))
00698         return (0);
00699     /*
00700      * Read the header for this strip/tile.
00701      */
00702     if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
00703         return (0);
00704     /*
00705      * Check image parameters and set decompression parameters.
00706      */
00707     segment_width = td->td_imagewidth;
00708     segment_height = td->td_imagelength - tif->tif_row;
00709     if (isTiled(tif)) {
00710                 segment_width = td->td_tilewidth;
00711                 segment_height = td->td_tilelength;
00712         sp->bytesperline = TIFFTileRowSize(tif);
00713     } else {
00714         if (segment_height > td->td_rowsperstrip)
00715             segment_height = td->td_rowsperstrip;
00716         sp->bytesperline = TIFFOldScanlineSize(tif);
00717     }
00718     if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
00719         /*
00720          * For PC 2, scale down the expected strip/tile size
00721          * to match a downsampled component
00722          */
00723         segment_width = TIFFhowmany(segment_width, sp->h_sampling);
00724         segment_height = TIFFhowmany(segment_height, sp->v_sampling);
00725     }
00726     if (sp->cinfo.d.image_width < segment_width ||
00727         sp->cinfo.d.image_height < segment_height) {
00728         TIFFWarningExt(tif->tif_clientdata, module,
00729                    "Improper JPEG strip/tile size, "
00730                    "expected %dx%d, got %dx%d",
00731                    segment_width, segment_height,
00732                    sp->cinfo.d.image_width,
00733                    sp->cinfo.d.image_height);
00734     } 
00735     if (sp->cinfo.d.image_width > segment_width ||
00736         sp->cinfo.d.image_height > segment_height) {
00737         /*
00738          * This case could be dangerous, if the strip or tile size has
00739          * been reported as less than the amount of data jpeg will
00740          * return, some potential security issues arise. Catch this
00741          * case and error out.
00742          */
00743         TIFFErrorExt(tif->tif_clientdata, module,
00744                  "JPEG strip/tile size exceeds expected dimensions,"
00745                  " expected %dx%d, got %dx%d",
00746                  segment_width, segment_height,
00747                  sp->cinfo.d.image_width, sp->cinfo.d.image_height);
00748         return (0);
00749     }
00750     if (sp->cinfo.d.num_components !=
00751         (td->td_planarconfig == PLANARCONFIG_CONTIG ?
00752          td->td_samplesperpixel : 1)) {
00753         TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG component count");
00754         return (0);
00755     }
00756 #ifdef JPEG_LIB_MK1
00757     if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
00758             TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
00759             return (0);
00760     }
00761         sp->cinfo.d.data_precision = td->td_bitspersample;
00762         sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
00763 #else
00764     if (sp->cinfo.d.data_precision != td->td_bitspersample) {
00765             TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
00766             return (0);
00767     }
00768 #endif
00769     if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
00770         /* Component 0 should have expected sampling factors */
00771         if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
00772             sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
00773                 TIFFWarningExt(tif->tif_clientdata, module,
00774                                     "Improper JPEG sampling factors %d,%d\n"
00775                                     "Apparently should be %d,%d.",
00776                                     sp->cinfo.d.comp_info[0].h_samp_factor,
00777                                     sp->cinfo.d.comp_info[0].v_samp_factor,
00778                                     sp->h_sampling, sp->v_sampling);
00779 
00780                 /*
00781                  * There are potential security issues here
00782                  * for decoders that have already allocated
00783                  * buffers based on the expected sampling
00784                  * factors. Lets check the sampling factors
00785                  * dont exceed what we were expecting.
00786                  */
00787                 if (sp->cinfo.d.comp_info[0].h_samp_factor
00788                     > sp->h_sampling
00789                     || sp->cinfo.d.comp_info[0].v_samp_factor
00790                     > sp->v_sampling) {
00791                     TIFFErrorExt(tif->tif_clientdata,
00792                              module,
00793                     "Cannot honour JPEG sampling factors"
00794                     " that exceed those specified.");
00795                     return (0);
00796                 }
00797 
00798                 /*
00799                  * XXX: Files written by the Intergraph software
00800                  * has different sampling factors stored in the
00801                  * TIFF tags and in the JPEG structures. We will
00802                  * try to deduce Intergraph files by the presense
00803                  * of the tag 33918.
00804                  */
00805                 if (!_TIFFFindFieldInfo(tif, 33918, TIFF_ANY)) {
00806                     TIFFWarningExt(tif->tif_clientdata, module,
00807                     "Decompressor will try reading with "
00808                     "sampling %d,%d.",
00809                     sp->cinfo.d.comp_info[0].h_samp_factor,
00810                     sp->cinfo.d.comp_info[0].v_samp_factor);
00811 
00812                     sp->h_sampling = (uint16)
00813                     sp->cinfo.d.comp_info[0].h_samp_factor;
00814                     sp->v_sampling = (uint16)
00815                     sp->cinfo.d.comp_info[0].v_samp_factor;
00816                 }
00817         }
00818         /* Rest should have sampling factors 1,1 */
00819         for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
00820             if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
00821                 sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
00822                 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
00823                 return (0);
00824             }
00825         }
00826     } else {
00827         /* PC 2's single component should have sampling factors 1,1 */
00828         if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
00829             sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
00830             TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
00831             return (0);
00832         }
00833     }
00834     downsampled_output = FALSE;
00835     if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
00836         sp->photometric == PHOTOMETRIC_YCBCR &&
00837         sp->jpegcolormode == JPEGCOLORMODE_RGB) {
00838     /* Convert YCbCr to RGB */
00839         sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
00840         sp->cinfo.d.out_color_space = JCS_RGB;
00841     } else {
00842             /* Suppress colorspace handling */
00843         sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
00844         sp->cinfo.d.out_color_space = JCS_UNKNOWN;
00845         if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
00846             (sp->h_sampling != 1 || sp->v_sampling != 1))
00847             downsampled_output = TRUE;
00848         /* XXX what about up-sampling? */
00849     }
00850     if (downsampled_output) {
00851         /* Need to use raw-data interface to libjpeg */
00852         sp->cinfo.d.raw_data_out = TRUE;
00853         tif->tif_decoderow = JPEGDecodeRaw;
00854         tif->tif_decodestrip = JPEGDecodeRaw;
00855         tif->tif_decodetile = JPEGDecodeRaw;
00856     } else {
00857         /* Use normal interface to libjpeg */
00858         sp->cinfo.d.raw_data_out = FALSE;
00859         tif->tif_decoderow = JPEGDecode;
00860         tif->tif_decodestrip = JPEGDecode;
00861         tif->tif_decodetile = JPEGDecode;
00862     }
00863     /* Start JPEG decompressor */
00864     if (!TIFFjpeg_start_decompress(sp))
00865         return (0);
00866     /* Allocate downsampled-data buffers if needed */
00867     if (downsampled_output) {
00868         if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
00869                            sp->cinfo.d.num_components))
00870             return (0);
00871         sp->scancount = DCTSIZE;    /* mark buffer empty */
00872     }
00873     return (1);
00874 }
00875 
00876 /*
00877  * Decode a chunk of pixels.
00878  * "Standard" case: returned data is not downsampled.
00879  */
00880 /*ARGSUSED*/ static int
00881 JPEGDecode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
00882 {
00883     JPEGState *sp = JState(tif);
00884     tsize_t nrows;
00885     (void) s;
00886 
00887     nrows = cc / sp->bytesperline;
00888     if (cc % sp->bytesperline)
00889         TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
00890 
00891     if( nrows > (int) sp->cinfo.d.image_height )
00892         nrows = sp->cinfo.d.image_height;
00893 
00894     /* data is expected to be read in multiples of a scanline */
00895     if (nrows)
00896     {
00897         JSAMPROW line_work_buf = NULL;
00898 
00899         /*
00900         ** For 6B, only use temporary buffer for 12 bit imagery. 
00901         ** For Mk1 always use it. 
00902         */
00903 #if !defined(JPEG_LIB_MK1)        
00904         if( sp->cinfo.d.data_precision == 12 )
00905 #endif
00906         {
00907             line_work_buf = (JSAMPROW) 
00908                 _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width 
00909                             * sp->cinfo.d.num_components );
00910         }
00911 
00912         do {
00913             if( line_work_buf != NULL )
00914             {
00915                 /* 
00916                 ** In the MK1 case, we aways read into a 16bit buffer, and then
00917                 ** pack down to 12bit or 8bit.  In 6B case we only read into 16
00918                 ** bit buffer for 12bit data, which we need to repack. 
00919                 */
00920                 if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
00921                     return (0);
00922 
00923                 if( sp->cinfo.d.data_precision == 12 )
00924                 {
00925                     int value_pairs = (sp->cinfo.d.output_width 
00926                                        * sp->cinfo.d.num_components) / 2;
00927                     int iPair;
00928 
00929                     for( iPair = 0; iPair < value_pairs; iPair++ )
00930                     {
00931                         unsigned char *out_ptr = 
00932                             ((unsigned char *) buf) + iPair * 3;
00933                         JSAMPLE *in_ptr = line_work_buf + iPair * 2;
00934 
00935                         out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
00936                         out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
00937                             | ((in_ptr[1] & 0xf00) >> 8);
00938                         out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
00939                     }
00940                 }
00941                 else if( sp->cinfo.d.data_precision == 8 )
00942                 {
00943                     int value_count = (sp->cinfo.d.output_width 
00944                                        * sp->cinfo.d.num_components);
00945                     int iValue;
00946 
00947                     for( iValue = 0; iValue < value_count; iValue++ )
00948                     {
00949                         ((unsigned char *) buf)[iValue] = 
00950                             line_work_buf[iValue] & 0xff;
00951                     }
00952                 }
00953             }
00954             else
00955             {
00956                 /*
00957                 ** In the libjpeg6b 8bit case.  We read directly into the 
00958                 ** TIFF buffer.
00959                 */
00960                 JSAMPROW bufptr = (JSAMPROW)buf;
00961   
00962                 if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
00963                     return (0);
00964             }
00965 
00966             ++tif->tif_row;
00967             buf += sp->bytesperline;
00968             cc -= sp->bytesperline;
00969         } while (--nrows > 0);
00970 
00971         if( line_work_buf != NULL )
00972             _TIFFfree( line_work_buf );
00973     }
00974 
00975     /* Close down the decompressor if we've finished the strip or tile. */
00976     return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
00977         || TIFFjpeg_finish_decompress(sp);
00978 }
00979 
00980 /*
00981  * Decode a chunk of pixels.
00982  * Returned data is downsampled per sampling factors.
00983  */
00984 /*ARGSUSED*/ static int
00985 JPEGDecodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
00986 {
00987     JPEGState *sp = JState(tif);
00988     tsize_t nrows;
00989     (void) s;
00990 
00991     /* data is expected to be read in multiples of a scanline */
00992     if ( (nrows = sp->cinfo.d.image_height) ) {
00993         /* Cb,Cr both have sampling factors 1, so this is correct */
00994         JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;            
00995         int samples_per_clump = sp->samplesperclump;
00996 
00997 #ifdef JPEG_LIB_MK1
00998         unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
00999             sp->cinfo.d.output_width *
01000             sp->cinfo.d.num_components);
01001 #endif
01002 
01003         do {
01004             jpeg_component_info *compptr;
01005             int ci, clumpoffset;
01006 
01007             /* Reload downsampled-data buffer if needed */
01008             if (sp->scancount >= DCTSIZE) {
01009                 int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
01010                 if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
01011                     return (0);
01012                 sp->scancount = 0;
01013             }
01014             /*
01015              * Fastest way to unseparate data is to make one pass
01016              * over the scanline for each row of each component.
01017              */
01018             clumpoffset = 0;    /* first sample in clump */
01019             for (ci = 0, compptr = sp->cinfo.d.comp_info;
01020                 ci < sp->cinfo.d.num_components;
01021                 ci++, compptr++) {
01022                 int hsamp = compptr->h_samp_factor;
01023                 int vsamp = compptr->v_samp_factor;
01024                 int ypos;
01025 
01026                 for (ypos = 0; ypos < vsamp; ypos++) {
01027                     JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
01028 #ifdef JPEG_LIB_MK1
01029                     JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
01030 #else
01031                     JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
01032 #endif
01033                     JDIMENSION nclump;
01034 
01035                     if (hsamp == 1) {
01036                         /* fast path for at least Cb and Cr */
01037                         for (nclump = clumps_per_line; nclump-- > 0; ) {
01038                             outptr[0] = *inptr++;
01039                             outptr += samples_per_clump;
01040                         }
01041                     } else {
01042                         int xpos;
01043 
01044             /* general case */
01045                         for (nclump = clumps_per_line; nclump-- > 0; ) {
01046                             for (xpos = 0; xpos < hsamp; xpos++)
01047                                 outptr[xpos] = *inptr++;
01048                             outptr += samples_per_clump;
01049                         }
01050                     }
01051                     clumpoffset += hsamp;
01052                 }
01053             }
01054 
01055 #ifdef JPEG_LIB_MK1
01056             {
01057                 if (sp->cinfo.d.data_precision == 8)
01058                 {
01059                     int i=0;
01060                     int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
01061                     for (i=0; i<len; i++)
01062                     {
01063                         ((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
01064                     }
01065                 }
01066                 else
01067                 {         // 12-bit
01068                     int value_pairs = (sp->cinfo.d.output_width
01069                         * sp->cinfo.d.num_components) / 2;
01070                     int iPair;
01071                     for( iPair = 0; iPair < value_pairs; iPair++ )
01072                     {
01073                         unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
01074                         JSAMPLE *in_ptr = tmpbuf + iPair * 2;
01075                         out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
01076                         out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
01077                             | ((in_ptr[1] & 0xf00) >> 8);
01078                         out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
01079                     }
01080                 }
01081             }
01082 #endif
01083 
01084             sp->scancount ++;
01085             tif->tif_row += sp->v_sampling;
01086             /* increment/decrement of buf and cc is still incorrect, but should not matter
01087              * TODO: resolve this */
01088             buf += sp->bytesperline;
01089             cc -= sp->bytesperline;
01090             nrows -= sp->v_sampling;
01091         } while (nrows > 0);
01092 
01093 #ifdef JPEG_LIB_MK1
01094         _TIFFfree(tmpbuf);
01095 #endif
01096 
01097     }
01098 
01099     /* Close down the decompressor if done. */
01100     return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
01101         || TIFFjpeg_finish_decompress(sp);
01102 }
01103 
01104 
01105 /*
01106  * JPEG Encoding.
01107  */
01108 
01109 static void
01110 unsuppress_quant_table (JPEGState* sp, int tblno)
01111 {
01112     JQUANT_TBL* qtbl;
01113 
01114     if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
01115         qtbl->sent_table = FALSE;
01116 }
01117 
01118 static void
01119 unsuppress_huff_table (JPEGState* sp, int tblno)
01120 {
01121     JHUFF_TBL* htbl;
01122 
01123     if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
01124         htbl->sent_table = FALSE;
01125     if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
01126         htbl->sent_table = FALSE;
01127 }
01128 
01129 static int
01130 prepare_JPEGTables(TIFF* tif)
01131 {
01132     JPEGState* sp = JState(tif);
01133 
01134         JPEGInitializeLibJPEG( tif, 0, 0 );
01135 
01136     /* Initialize quant tables for current quality setting */
01137     if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
01138         return (0);
01139     /* Mark only the tables we want for output */
01140     /* NB: chrominance tables are currently used only with YCbCr */
01141     if (!TIFFjpeg_suppress_tables(sp, TRUE))
01142         return (0);
01143     if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
01144         unsuppress_quant_table(sp, 0);
01145         if (sp->photometric == PHOTOMETRIC_YCBCR)
01146             unsuppress_quant_table(sp, 1);
01147     }
01148     if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
01149         unsuppress_huff_table(sp, 0);
01150         if (sp->photometric == PHOTOMETRIC_YCBCR)
01151             unsuppress_huff_table(sp, 1);
01152     }
01153     /* Direct libjpeg output into jpegtables */
01154     if (!TIFFjpeg_tables_dest(sp, tif))
01155         return (0);
01156     /* Emit tables-only datastream */
01157     if (!TIFFjpeg_write_tables(sp))
01158         return (0);
01159 
01160     return (1);
01161 }
01162 
01163 static int
01164 JPEGSetupEncode(TIFF* tif)
01165 {
01166     JPEGState* sp = JState(tif);
01167     TIFFDirectory *td = &tif->tif_dir;
01168     static const char module[] = "JPEGSetupEncode";
01169 
01170         JPEGInitializeLibJPEG( tif, 1, 0 );
01171 
01172     assert(sp != NULL);
01173     assert(!sp->cinfo.comm.is_decompressor);
01174 
01175     /*
01176      * Initialize all JPEG parameters to default values.
01177      * Note that jpeg_set_defaults needs legal values for
01178      * in_color_space and input_components.
01179      */
01180     sp->cinfo.c.in_color_space = JCS_UNKNOWN;
01181     sp->cinfo.c.input_components = 1;
01182     if (!TIFFjpeg_set_defaults(sp))
01183         return (0);
01184     /* Set per-file parameters */
01185     sp->photometric = td->td_photometric;
01186     switch (sp->photometric) {
01187     case PHOTOMETRIC_YCBCR:
01188         sp->h_sampling = td->td_ycbcrsubsampling[0];
01189         sp->v_sampling = td->td_ycbcrsubsampling[1];
01190         /*
01191          * A ReferenceBlackWhite field *must* be present since the
01192          * default value is inappropriate for YCbCr.  Fill in the
01193          * proper value if application didn't set it.
01194          */
01195         {
01196             float *ref;
01197             if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
01198                       &ref)) {
01199                 float refbw[6];
01200                 long top = 1L << td->td_bitspersample;
01201                 refbw[0] = 0;
01202                 refbw[1] = (float)(top-1L);
01203                 refbw[2] = (float)(top>>1);
01204                 refbw[3] = refbw[1];
01205                 refbw[4] = refbw[2];
01206                 refbw[5] = refbw[1];
01207                 TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
01208                          refbw);
01209             }
01210         }
01211         break;
01212     case PHOTOMETRIC_PALETTE:       /* disallowed by Tech Note */
01213     case PHOTOMETRIC_MASK:
01214         TIFFErrorExt(tif->tif_clientdata, module,
01215               "PhotometricInterpretation %d not allowed for JPEG",
01216               (int) sp->photometric);
01217         return (0);
01218     default:
01219         /* TIFF 6.0 forbids subsampling of all other color spaces */
01220         sp->h_sampling = 1;
01221         sp->v_sampling = 1;
01222         break;
01223     }
01224 
01225     /* Verify miscellaneous parameters */
01226 
01227     /*
01228      * This would need work if libtiff ever supports different
01229      * depths for different components, or if libjpeg ever supports
01230      * run-time selection of depth.  Neither is imminent.
01231      */
01232 #ifdef JPEG_LIB_MK1
01233         /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
01234     if (td->td_bitspersample != 8 && td->td_bitspersample != 12) 
01235 #else
01236     if (td->td_bitspersample != BITS_IN_JSAMPLE )
01237 #endif
01238     {
01239         TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
01240               (int) td->td_bitspersample);
01241         return (0);
01242     }
01243     sp->cinfo.c.data_precision = td->td_bitspersample;
01244 #ifdef JPEG_LIB_MK1
01245         sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
01246 #endif
01247     if (isTiled(tif)) {
01248         if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
01249             TIFFErrorExt(tif->tif_clientdata, module,
01250                   "JPEG tile height must be multiple of %d",
01251                   sp->v_sampling * DCTSIZE);
01252             return (0);
01253         }
01254         if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
01255             TIFFErrorExt(tif->tif_clientdata, module,
01256                   "JPEG tile width must be multiple of %d",
01257                   sp->h_sampling * DCTSIZE);
01258             return (0);
01259         }
01260     } else {
01261         if (td->td_rowsperstrip < td->td_imagelength &&
01262             (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
01263             TIFFErrorExt(tif->tif_clientdata, module,
01264                   "RowsPerStrip must be multiple of %d for JPEG",
01265                   sp->v_sampling * DCTSIZE);
01266             return (0);
01267         }
01268     }
01269 
01270     /* Create a JPEGTables field if appropriate */
01271     if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
01272                 if( sp->jpegtables == NULL
01273                     || memcmp(sp->jpegtables,"\0\0\0\0\0\0\0\0\0",8) == 0 )
01274                 {
01275                         if (!prepare_JPEGTables(tif))
01276                                 return (0);
01277                         /* Mark the field present */
01278                         /* Can't use TIFFSetField since BEENWRITING is already set! */
01279                         tif->tif_flags |= TIFF_DIRTYDIRECT;
01280                         TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
01281                 }
01282     } else {
01283         /* We do not support application-supplied JPEGTables, */
01284         /* so mark the field not present */
01285         TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
01286     }
01287 
01288     /* Direct libjpeg output to libtiff's output buffer */
01289     TIFFjpeg_data_dest(sp, tif);
01290 
01291     return (1);
01292 }
01293 
01294 /*
01295  * Set encoding state at the start of a strip or tile.
01296  */
01297 static int
01298 JPEGPreEncode(TIFF* tif, tsample_t s)
01299 {
01300     JPEGState *sp = JState(tif);
01301     TIFFDirectory *td = &tif->tif_dir;
01302     static const char module[] = "JPEGPreEncode";
01303     uint32 segment_width, segment_height;
01304     int downsampled_input;
01305 
01306     assert(sp != NULL);
01307     assert(!sp->cinfo.comm.is_decompressor);
01308     /*
01309      * Set encoding parameters for this strip/tile.
01310      */
01311     if (isTiled(tif)) {
01312         segment_width = td->td_tilewidth;
01313         segment_height = td->td_tilelength;
01314         sp->bytesperline = TIFFTileRowSize(tif);
01315     } else {
01316         segment_width = td->td_imagewidth;
01317         segment_height = td->td_imagelength - tif->tif_row;
01318         if (segment_height > td->td_rowsperstrip)
01319             segment_height = td->td_rowsperstrip;
01320         sp->bytesperline = TIFFOldScanlineSize(tif);
01321     }
01322     if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
01323         /* for PC 2, scale down the strip/tile size
01324          * to match a downsampled component
01325          */
01326         segment_width = TIFFhowmany(segment_width, sp->h_sampling);
01327         segment_height = TIFFhowmany(segment_height, sp->v_sampling);
01328     }
01329     if (segment_width > 65535 || segment_height > 65535) {
01330         TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
01331         return (0);
01332     }
01333     sp->cinfo.c.image_width = segment_width;
01334     sp->cinfo.c.image_height = segment_height;
01335     downsampled_input = FALSE;
01336     if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
01337         sp->cinfo.c.input_components = td->td_samplesperpixel;
01338         if (sp->photometric == PHOTOMETRIC_YCBCR) {
01339             if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
01340                 sp->cinfo.c.in_color_space = JCS_RGB;
01341             } else {
01342                 sp->cinfo.c.in_color_space = JCS_YCbCr;
01343                 if (sp->h_sampling != 1 || sp->v_sampling != 1)
01344                     downsampled_input = TRUE;
01345             }
01346             if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
01347                 return (0);
01348             /*
01349              * Set Y sampling factors;
01350              * we assume jpeg_set_colorspace() set the rest to 1
01351              */
01352             sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
01353             sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
01354         } else {
01355             sp->cinfo.c.in_color_space = JCS_UNKNOWN;
01356             if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
01357                 return (0);
01358             /* jpeg_set_colorspace set all sampling factors to 1 */
01359         }
01360     } else {
01361         sp->cinfo.c.input_components = 1;
01362         sp->cinfo.c.in_color_space = JCS_UNKNOWN;
01363         if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
01364             return (0);
01365         sp->cinfo.c.comp_info[0].component_id = s;
01366         /* jpeg_set_colorspace() set sampling factors to 1 */
01367         if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
01368             sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
01369             sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
01370             sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
01371         }
01372     }
01373     /* ensure libjpeg won't write any extraneous markers */
01374     sp->cinfo.c.write_JFIF_header = FALSE;
01375     sp->cinfo.c.write_Adobe_marker = FALSE;
01376     /* set up table handling correctly */
01377         if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
01378                 return (0);
01379     if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
01380         unsuppress_quant_table(sp, 0);
01381         unsuppress_quant_table(sp, 1);
01382     }
01383     if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
01384         sp->cinfo.c.optimize_coding = FALSE;
01385     else
01386         sp->cinfo.c.optimize_coding = TRUE;
01387     if (downsampled_input) {
01388         /* Need to use raw-data interface to libjpeg */
01389         sp->cinfo.c.raw_data_in = TRUE;
01390         tif->tif_encoderow = JPEGEncodeRaw;
01391         tif->tif_encodestrip = JPEGEncodeRaw;
01392         tif->tif_encodetile = JPEGEncodeRaw;
01393     } else {
01394         /* Use normal interface to libjpeg */
01395         sp->cinfo.c.raw_data_in = FALSE;
01396         tif->tif_encoderow = JPEGEncode;
01397         tif->tif_encodestrip = JPEGEncode;
01398         tif->tif_encodetile = JPEGEncode;
01399     }
01400     /* Start JPEG compressor */
01401     if (!TIFFjpeg_start_compress(sp, FALSE))
01402         return (0);
01403     /* Allocate downsampled-data buffers if needed */
01404     if (downsampled_input) {
01405         if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
01406                            sp->cinfo.c.num_components))
01407             return (0);
01408     }
01409     sp->scancount = 0;
01410 
01411     return (1);
01412 }
01413 
01414 /*
01415  * Encode a chunk of pixels.
01416  * "Standard" case: incoming data is not downsampled.
01417  */
01418 static int
01419 JPEGEncode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
01420 {
01421     JPEGState *sp = JState(tif);
01422     tsize_t nrows;
01423     JSAMPROW bufptr[1];
01424 
01425     (void) s;
01426     assert(sp != NULL);
01427     /* data is expected to be supplied in multiples of a scanline */
01428     nrows = cc / sp->bytesperline;
01429     if (cc % sp->bytesperline)
01430         TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
01431 
01432         /* The last strip will be limited to image size */
01433         if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
01434             nrows = tif->tif_dir.td_imagelength - tif->tif_row;
01435 
01436     while (nrows-- > 0) {
01437         bufptr[0] = (JSAMPROW) buf;
01438         if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
01439             return (0);
01440         if (nrows > 0)
01441             tif->tif_row++;
01442         buf += sp->bytesperline;
01443     }
01444     return (1);
01445 }
01446 
01447 /*
01448  * Encode a chunk of pixels.
01449  * Incoming data is expected to be downsampled per sampling factors.
01450  */
01451 static int
01452 JPEGEncodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
01453 {
01454     JPEGState *sp = JState(tif);
01455     JSAMPLE* inptr;
01456     JSAMPLE* outptr;
01457     tsize_t nrows;
01458     JDIMENSION clumps_per_line, nclump;
01459     int clumpoffset, ci, xpos, ypos;
01460     jpeg_component_info* compptr;
01461     int samples_per_clump = sp->samplesperclump;
01462     tsize_t bytesperclumpline;
01463 
01464     (void) s;
01465     assert(sp != NULL);
01466     /* data is expected to be supplied in multiples of a clumpline */
01467     /* a clumpline is equivalent to v_sampling desubsampled scanlines */
01468     /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
01469     bytesperclumpline = (((sp->cinfo.c.image_width+sp->h_sampling-1)/sp->h_sampling)
01470                  *(sp->h_sampling*sp->v_sampling+2)*sp->cinfo.c.data_precision+7)
01471                 /8;
01472 
01473     nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
01474     if (cc % bytesperclumpline)
01475         TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
01476 
01477     /* Cb,Cr both have sampling factors 1, so this is correct */
01478     clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
01479 
01480     while (nrows > 0) {
01481         /*
01482          * Fastest way to separate the data is to make one pass
01483          * over the scanline for each row of each component.
01484          */
01485         clumpoffset = 0;        /* first sample in clump */
01486         for (ci = 0, compptr = sp->cinfo.c.comp_info;
01487              ci < sp->cinfo.c.num_components;
01488              ci++, compptr++) {
01489             int hsamp = compptr->h_samp_factor;
01490             int vsamp = compptr->v_samp_factor;
01491             int padding = (int) (compptr->width_in_blocks * DCTSIZE -
01492                      clumps_per_line * hsamp);
01493             for (ypos = 0; ypos < vsamp; ypos++) {
01494             inptr = ((JSAMPLE*) buf) + clumpoffset;
01495             outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
01496             if (hsamp == 1) {
01497                 /* fast path for at least Cb and Cr */
01498                 for (nclump = clumps_per_line; nclump-- > 0; ) {
01499                 *outptr++ = inptr[0];
01500                 inptr += samples_per_clump;
01501                 }
01502             } else {
01503                 /* general case */
01504                 for (nclump = clumps_per_line; nclump-- > 0; ) {
01505                 for (xpos = 0; xpos < hsamp; xpos++)
01506                     *outptr++ = inptr[xpos];
01507                 inptr += samples_per_clump;
01508                 }
01509             }
01510             /* pad each scanline as needed */
01511             for (xpos = 0; xpos < padding; xpos++) {
01512                 *outptr = outptr[-1];
01513                 outptr++;
01514             }
01515             clumpoffset += hsamp;
01516             }
01517         }
01518         sp->scancount++;
01519         if (sp->scancount >= DCTSIZE) {
01520             int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
01521             if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
01522                 return (0);
01523             sp->scancount = 0;
01524         }
01525         tif->tif_row += sp->v_sampling;
01526         buf += sp->bytesperline;
01527         nrows -= sp->v_sampling;
01528     }
01529     return (1);
01530 }
01531 
01532 /*
01533  * Finish up at the end of a strip or tile.
01534  */
01535 static int
01536 JPEGPostEncode(TIFF* tif)
01537 {
01538     JPEGState *sp = JState(tif);
01539 
01540     if (sp->scancount > 0) {
01541         /*
01542          * Need to emit a partial bufferload of downsampled data.
01543          * Pad the data vertically.
01544          */
01545         int ci, ypos, n;
01546         jpeg_component_info* compptr;
01547 
01548         for (ci = 0, compptr = sp->cinfo.c.comp_info;
01549              ci < sp->cinfo.c.num_components;
01550              ci++, compptr++) {
01551             int vsamp = compptr->v_samp_factor;
01552             tsize_t row_width = compptr->width_in_blocks * DCTSIZE
01553                 * sizeof(JSAMPLE);
01554             for (ypos = sp->scancount * vsamp;
01555                  ypos < DCTSIZE * vsamp; ypos++) {
01556                 _TIFFmemcpy((tdata_t)sp->ds_buffer[ci][ypos],
01557                         (tdata_t)sp->ds_buffer[ci][ypos-1],
01558                         row_width);
01559 
01560             }
01561         }
01562         n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
01563         if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
01564             return (0);
01565     }
01566 
01567     return (TIFFjpeg_finish_compress(JState(tif)));
01568 }
01569 
01570 static void
01571 JPEGCleanup(TIFF* tif)
01572 {
01573     JPEGState *sp = JState(tif);
01574     
01575     assert(sp != 0);
01576 
01577     tif->tif_tagmethods.vgetfield = sp->vgetparent;
01578     tif->tif_tagmethods.vsetfield = sp->vsetparent;
01579     tif->tif_tagmethods.printdir = sp->printdir;
01580 
01581     if( sp->cinfo_initialized )
01582         TIFFjpeg_destroy(sp);   /* release libjpeg resources */
01583     if (sp->jpegtables)     /* tag value */
01584         _TIFFfree(sp->jpegtables);
01585     _TIFFfree(tif->tif_data);   /* release local state */
01586     tif->tif_data = NULL;
01587 
01588     _TIFFSetDefaultCompressionState(tif);
01589 }
01590 
01591 static void 
01592 JPEGResetUpsampled( TIFF* tif )
01593 {
01594     JPEGState* sp = JState(tif);
01595     TIFFDirectory* td = &tif->tif_dir;
01596 
01597     /*
01598      * Mark whether returned data is up-sampled or not so TIFFStripSize
01599      * and TIFFTileSize return values that reflect the true amount of
01600      * data.
01601      */
01602     tif->tif_flags &= ~TIFF_UPSAMPLED;
01603     if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
01604         if (td->td_photometric == PHOTOMETRIC_YCBCR &&
01605             sp->jpegcolormode == JPEGCOLORMODE_RGB) {
01606             tif->tif_flags |= TIFF_UPSAMPLED;
01607         } else {
01608 #ifdef notdef
01609             if (td->td_ycbcrsubsampling[0] != 1 ||
01610                 td->td_ycbcrsubsampling[1] != 1)
01611                 ; /* XXX what about up-sampling? */
01612 #endif
01613         }
01614     }
01615 
01616     /*
01617      * Must recalculate cached tile size in case sampling state changed.
01618      * Should we really be doing this now if image size isn't set? 
01619      */
01620         if( tif->tif_tilesize > 0 )
01621             tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tsize_t) -1;
01622 
01623         if(tif->tif_scanlinesize > 0 )
01624             tif->tif_scanlinesize = TIFFScanlineSize(tif); 
01625 }
01626 
01627 static int
01628 JPEGVSetField(TIFF* tif, ttag_t tag, va_list ap)
01629 {
01630     JPEGState* sp = JState(tif);
01631     const TIFFFieldInfo* fip;
01632     uint32 v32;
01633 
01634     assert(sp != NULL);
01635 
01636     switch (tag) {
01637     case TIFFTAG_JPEGTABLES:
01638         v32 = va_arg(ap, uint32);
01639         if (v32 == 0) {
01640             /* XXX */
01641             return (0);
01642         }
01643         _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
01644             (long) v32);
01645         sp->jpegtables_length = v32;
01646         TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
01647         break;
01648     case TIFFTAG_JPEGQUALITY:
01649         sp->jpegquality = va_arg(ap, int);
01650         return (1);         /* pseudo tag */
01651     case TIFFTAG_JPEGCOLORMODE:
01652         sp->jpegcolormode = va_arg(ap, int);
01653                 JPEGResetUpsampled( tif );
01654         return (1);         /* pseudo tag */
01655     case TIFFTAG_PHOTOMETRIC:
01656         {
01657                 int ret_value = (*sp->vsetparent)(tif, tag, ap);
01658                 JPEGResetUpsampled( tif );
01659                 return ret_value;
01660         }
01661     case TIFFTAG_JPEGTABLESMODE:
01662         sp->jpegtablesmode = va_arg(ap, int);
01663         return (1);         /* pseudo tag */
01664     case TIFFTAG_YCBCRSUBSAMPLING:
01665                 /* mark the fact that we have a real ycbcrsubsampling! */
01666         sp->ycbcrsampling_fetched = 1;
01667                 /* should we be recomputing upsampling info here? */
01668         return (*sp->vsetparent)(tif, tag, ap);
01669     case TIFFTAG_FAXRECVPARAMS:
01670         sp->recvparams = va_arg(ap, uint32);
01671         break;
01672     case TIFFTAG_FAXSUBADDRESS:
01673         _TIFFsetString(&sp->subaddress, va_arg(ap, char*));
01674         break;
01675     case TIFFTAG_FAXRECVTIME:
01676         sp->recvtime = va_arg(ap, uint32);
01677         break;
01678     case TIFFTAG_FAXDCS:
01679         _TIFFsetString(&sp->faxdcs, va_arg(ap, char*));
01680         break;
01681     default:
01682         return (*sp->vsetparent)(tif, tag, ap);
01683     }
01684 
01685     if ((fip = _TIFFFieldWithTag(tif, tag))) {
01686         TIFFSetFieldBit(tif, fip->field_bit);
01687     } else {
01688         return (0);
01689     }
01690 
01691     tif->tif_flags |= TIFF_DIRTYDIRECT;
01692     return (1);
01693 }
01694 
01695 /*
01696  * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
01697  * the TIFF tags, but still use non-default (2,2) values within the jpeg
01698  * data stream itself.  In order for TIFF applications to work properly
01699  * - for instance to get the strip buffer size right - it is imperative
01700  * that the subsampling be available before we start reading the image
01701  * data normally.  This function will attempt to load the first strip in
01702  * order to get the sampling values from the jpeg data stream.  Various
01703  * hacks are various places are done to ensure this function gets called
01704  * before the td_ycbcrsubsampling values are used from the directory structure,
01705  * including calling TIFFGetField() for the YCBCRSUBSAMPLING field from 
01706  * TIFFStripSize(), and the printing code in tif_print.c. 
01707  *
01708  * Note that JPEGPreDeocode() will produce a fairly loud warning when the
01709  * discovered sampling does not match the default sampling (2,2) or whatever
01710  * was actually in the tiff tags. 
01711  *
01712  * Problems:
01713  *  o This code will cause one whole strip/tile of compressed data to be
01714  *    loaded just to get the tags right, even if the imagery is never read.
01715  *    It would be more efficient to just load a bit of the header, and
01716  *    initialize things from that. 
01717  *
01718  * See the bug in bugzilla for details:
01719  *
01720  * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
01721  *
01722  * Frank Warmerdam, July 2002
01723  */
01724 
01725 static void 
01726 JPEGFixupTestSubsampling( TIFF * tif )
01727 {
01728 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
01729     JPEGState *sp = JState(tif);
01730     TIFFDirectory *td = &tif->tif_dir;
01731 
01732     JPEGInitializeLibJPEG( tif, 0, 0 );
01733 
01734     /*
01735      * Some JPEG-in-TIFF files don't provide the ycbcrsampling tags, 
01736      * and use a sampling schema other than the default 2,2.  To handle
01737      * this we actually have to scan the header of a strip or tile of
01738      * jpeg data to get the sampling.  
01739      */
01740     if( !sp->cinfo.comm.is_decompressor 
01741         || sp->ycbcrsampling_fetched  
01742         || td->td_photometric != PHOTOMETRIC_YCBCR )
01743         return;
01744 
01745     sp->ycbcrsampling_fetched = 1;
01746     if( TIFFIsTiled( tif ) )
01747     {
01748         if( !TIFFFillTile( tif, 0 ) )
01749             return;
01750     }
01751     else
01752     {
01753         if( !TIFFFillStrip( tif, 0 ) )
01754             return;
01755     }
01756 
01757     TIFFSetField( tif, TIFFTAG_YCBCRSUBSAMPLING, 
01758                   (uint16) sp->h_sampling, (uint16) sp->v_sampling );
01759 
01760     /*
01761     ** We want to clear the loaded strip so the application has time
01762     ** to set JPEGCOLORMODE or other behavior modifiers.  This essentially
01763     ** undoes the JPEGPreDecode triggers by TIFFFileStrip().  (#1936)
01764     */
01765     tif->tif_curstrip = -1;
01766 
01767 #endif /* CHECK_JPEG_YCBCR_SUBSAMPLING */
01768 }
01769 
01770 static int
01771 JPEGVGetField(TIFF* tif, ttag_t tag, va_list ap)
01772 {
01773     JPEGState* sp = JState(tif);
01774 
01775     assert(sp != NULL);
01776 
01777     switch (tag) {
01778         case TIFFTAG_JPEGTABLES:
01779             *va_arg(ap, uint32*) = sp->jpegtables_length;
01780             *va_arg(ap, void**) = sp->jpegtables;
01781             break;
01782         case TIFFTAG_JPEGQUALITY:
01783             *va_arg(ap, int*) = sp->jpegquality;
01784             break;
01785         case TIFFTAG_JPEGCOLORMODE:
01786             *va_arg(ap, int*) = sp->jpegcolormode;
01787             break;
01788         case TIFFTAG_JPEGTABLESMODE:
01789             *va_arg(ap, int*) = sp->jpegtablesmode;
01790             break;
01791         case TIFFTAG_YCBCRSUBSAMPLING:
01792             JPEGFixupTestSubsampling( tif );
01793             return (*sp->vgetparent)(tif, tag, ap);
01794         case TIFFTAG_FAXRECVPARAMS:
01795             *va_arg(ap, uint32*) = sp->recvparams;
01796             break;
01797         case TIFFTAG_FAXSUBADDRESS:
01798             *va_arg(ap, char**) = sp->subaddress;
01799             break;
01800         case TIFFTAG_FAXRECVTIME:
01801             *va_arg(ap, uint32*) = sp->recvtime;
01802             break;
01803         case TIFFTAG_FAXDCS:
01804             *va_arg(ap, char**) = sp->faxdcs;
01805             break;
01806         default:
01807             return (*sp->vgetparent)(tif, tag, ap);
01808     }
01809     return (1);
01810 }
01811 
01812 static void
01813 JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
01814 {
01815     JPEGState* sp = JState(tif);
01816 
01817     assert(sp != NULL);
01818 
01819     (void) flags;
01820     if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
01821         fprintf(fd, "  JPEG Tables: (%lu bytes)\n",
01822             (unsigned long) sp->jpegtables_length);
01823         if (TIFFFieldSet(tif,FIELD_RECVPARAMS))
01824                 fprintf(fd, "  Fax Receive Parameters: %08lx\n",
01825                    (unsigned long) sp->recvparams);
01826         if (TIFFFieldSet(tif,FIELD_SUBADDRESS))
01827                 fprintf(fd, "  Fax SubAddress: %s\n", sp->subaddress);
01828         if (TIFFFieldSet(tif,FIELD_RECVTIME))
01829                 fprintf(fd, "  Fax Receive Time: %lu secs\n",
01830                     (unsigned long) sp->recvtime);
01831         if (TIFFFieldSet(tif,FIELD_FAXDCS))
01832                 fprintf(fd, "  Fax DCS: %s\n", sp->faxdcs);
01833 }
01834 
01835 static uint32
01836 JPEGDefaultStripSize(TIFF* tif, uint32 s)
01837 {
01838     JPEGState* sp = JState(tif);
01839     TIFFDirectory *td = &tif->tif_dir;
01840 
01841     s = (*sp->defsparent)(tif, s);
01842     if (s < td->td_imagelength)
01843         s = TIFFroundup(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
01844     return (s);
01845 }
01846 
01847 static void
01848 JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
01849 {
01850     JPEGState* sp = JState(tif);
01851     TIFFDirectory *td = &tif->tif_dir;
01852 
01853     (*sp->deftparent)(tif, tw, th);
01854     *tw = TIFFroundup(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
01855     *th = TIFFroundup(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
01856 }
01857 
01858 /*
01859  * The JPEG library initialized used to be done in TIFFInitJPEG(), but
01860  * now that we allow a TIFF file to be opened in update mode it is necessary
01861  * to have some way of deciding whether compression or decompression is
01862  * desired other than looking at tif->tif_mode.  We accomplish this by 
01863  * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
01864  * If so, we assume decompression is desired. 
01865  *
01866  * This is tricky, because TIFFInitJPEG() is called while the directory is
01867  * being read, and generally speaking the BYTECOUNTS tag won't have been read
01868  * at that point.  So we try to defer jpeg library initialization till we
01869  * do have that tag ... basically any access that might require the compressor
01870  * or decompressor that occurs after the reading of the directory. 
01871  *
01872  * In an ideal world compressors or decompressors would be setup
01873  * at the point where a single tile or strip was accessed (for read or write)
01874  * so that stuff like update of missing tiles, or replacement of tiles could
01875  * be done. However, we aren't trying to crack that nut just yet ...
01876  *
01877  * NFW, Feb 3rd, 2003.
01878  */
01879 
01880 static int JPEGInitializeLibJPEG( TIFF * tif, int force_encode, int force_decode )
01881 {
01882     JPEGState* sp = JState(tif);
01883     uint32 *byte_counts = NULL;
01884     int     data_is_empty = TRUE;
01885     int     decompress;
01886 
01887 
01888     if(sp->cinfo_initialized)
01889     {
01890         if( force_encode && sp->cinfo.comm.is_decompressor )
01891             TIFFjpeg_destroy( sp );
01892         else if( force_decode && !sp->cinfo.comm.is_decompressor )
01893             TIFFjpeg_destroy( sp );
01894         else
01895             return 1;
01896 
01897         sp->cinfo_initialized = 0;
01898     }
01899 
01900     /*
01901      * Do we have tile data already?  Make sure we initialize the
01902      * the state in decompressor mode if we have tile data, even if we
01903      * are not in read-only file access mode. 
01904      */
01905     if( TIFFIsTiled( tif ) 
01906         && TIFFGetField( tif, TIFFTAG_TILEBYTECOUNTS, &byte_counts ) 
01907         && byte_counts != NULL )
01908     {
01909         data_is_empty = byte_counts[0] == 0;
01910     }
01911     if( !TIFFIsTiled( tif ) 
01912         && TIFFGetField( tif, TIFFTAG_STRIPBYTECOUNTS, &byte_counts) 
01913         && byte_counts != NULL )
01914     {
01915         data_is_empty = byte_counts[0] == 0;
01916     }
01917 
01918     if( force_decode )
01919         decompress = 1;
01920     else if( force_encode )
01921         decompress = 0;
01922     else if( tif->tif_mode == O_RDONLY )
01923         decompress = 1;
01924     else if( data_is_empty )
01925         decompress = 0;
01926     else
01927         decompress = 1;
01928 
01929     /*
01930      * Initialize libjpeg.
01931      */
01932     if ( decompress ) {
01933         if (!TIFFjpeg_create_decompress(sp))
01934             return (0);
01935 
01936     } else {
01937         if (!TIFFjpeg_create_compress(sp))
01938             return (0);
01939     }
01940 
01941     sp->cinfo_initialized = TRUE;
01942 
01943     return 1;
01944 }
01945 
01946 int
01947 TIFFInitJPEG(TIFF* tif, int scheme)
01948 {
01949     JPEGState* sp;
01950 
01951     assert(scheme == COMPRESSION_JPEG);
01952 
01953     /*
01954      * Merge codec-specific tag information.
01955      */
01956     if (!_TIFFMergeFieldInfo(tif, jpegFieldInfo, N(jpegFieldInfo))) {
01957         TIFFErrorExt(tif->tif_clientdata,
01958                  "TIFFInitJPEG",
01959                  "Merging JPEG codec-specific tags failed");
01960         return 0;
01961     }
01962 
01963     /*
01964      * Allocate state block so tag methods have storage to record values.
01965      */
01966     tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (JPEGState));
01967 
01968     if (tif->tif_data == NULL) {
01969         TIFFErrorExt(tif->tif_clientdata,
01970                  "TIFFInitJPEG", "No space for JPEG state block");
01971         return 0;
01972     }
01973         _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
01974 
01975     sp = JState(tif);
01976     sp->tif = tif;              /* back link */
01977 
01978     /*
01979      * Override parent get/set field methods.
01980      */
01981     sp->vgetparent = tif->tif_tagmethods.vgetfield;
01982     tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
01983     sp->vsetparent = tif->tif_tagmethods.vsetfield;
01984     tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
01985     sp->printdir = tif->tif_tagmethods.printdir;
01986     tif->tif_tagmethods.printdir = JPEGPrintDir;   /* hook for codec tags */
01987 
01988     /* Default values for codec-specific fields */
01989     sp->jpegtables = NULL;
01990     sp->jpegtables_length = 0;
01991     sp->jpegquality = 75;           /* Default IJG quality */
01992     sp->jpegcolormode = JPEGCOLORMODE_RAW;
01993     sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
01994 
01995         sp->recvparams = 0;
01996         sp->subaddress = NULL;
01997         sp->faxdcs = NULL;
01998 
01999         sp->ycbcrsampling_fetched = 0;
02000 
02001     /*
02002      * Install codec methods.
02003      */
02004     tif->tif_setupdecode = JPEGSetupDecode;
02005     tif->tif_predecode = JPEGPreDecode;
02006     tif->tif_decoderow = JPEGDecode;
02007     tif->tif_decodestrip = JPEGDecode;
02008     tif->tif_decodetile = JPEGDecode;
02009     tif->tif_setupencode = JPEGSetupEncode;
02010     tif->tif_preencode = JPEGPreEncode;
02011     tif->tif_postencode = JPEGPostEncode;
02012     tif->tif_encoderow = JPEGEncode;
02013     tif->tif_encodestrip = JPEGEncode;
02014     tif->tif_encodetile = JPEGEncode;
02015     tif->tif_cleanup = JPEGCleanup;
02016     sp->defsparent = tif->tif_defstripsize;
02017     tif->tif_defstripsize = JPEGDefaultStripSize;
02018     sp->deftparent = tif->tif_deftilesize;
02019     tif->tif_deftilesize = JPEGDefaultTileSize;
02020     tif->tif_flags |= TIFF_NOBITREV;    /* no bit reversal, please */
02021 
02022         sp->cinfo_initialized = FALSE;
02023 
02024     /*
02025         ** Create a JPEGTables field if no directory has yet been created. 
02026         ** We do this just to ensure that sufficient space is reserved for
02027         ** the JPEGTables field.  It will be properly created the right
02028         ** size later. 
02029         */
02030         if( tif->tif_diroff == 0 )
02031         {
02032 #define SIZE_OF_JPEGTABLES 2000
02033 /*
02034 The following line assumes incorrectly that all JPEG-in-TIFF files will have
02035 a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
02036 when the JPEG data is placed with TIFFWriteRawStrip.  The field bit should be 
02037 set, anyway, later when actual JPEGTABLES header is generated, so removing it 
02038 here hopefully is harmless.
02039             TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
02040 */
02041             sp->jpegtables_length = SIZE_OF_JPEGTABLES;
02042             sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
02043         _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
02044 #undef SIZE_OF_JPEGTABLES
02045         }
02046 
02047         /*
02048          * Mark the TIFFTAG_YCBCRSAMPLES as present even if it is not
02049          * see: JPEGFixupTestSubsampling().
02050          */
02051         TIFFSetFieldBit( tif, FIELD_YCBCRSUBSAMPLING );
02052 
02053     return 1;
02054 }
02055 #endif /* JPEG_SUPPORT */
02056 
02057 /* vim: set ts=8 sts=8 sw=8 noet: */
02058 
02059 /*
02060  * Local Variables:
02061  * mode: c
02062  * c-basic-offset: 8
02063  * fill-column: 78
02064  * End:
02065  */

Generated on Fri May 25 2012 04:17:42 for ReactOS by doxygen 1.7.6.1

ReactOS is a registered trademark or a trademark of ReactOS Foundation in the United States and other countries.