home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / hensa / graphics / libtiff_1 / c / tif_jpeg < prev    next >
Text File  |  1995-10-12  |  42KB  |  1,481 lines

  1. /* $Header: /usr/people/sam/tiff/libtiff/RCS/tif_jpeg.c,v 1.23 1995/06/30 15:29:02 sam Exp $ */
  2.  
  3. /*
  4.  * Copyright (c) 1994-1995 Sam Leffler
  5.  * Copyright (c) 1994-1995 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. #include "tiffiop.h"
  28. #ifdef JPEG_SUPPORT
  29. /*
  30.  * TIFF Library
  31.  *
  32.  * JPEG Compression support per TIFF Technical Note #2
  33.  * (*not* per the original TIFF 6.0 spec).
  34.  *
  35.  * This file is simply an interface to the libjpeg library written by
  36.  * the Independent JPEG Group.  You need release 5 or later of the IJG
  37.  * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
  38.  *
  39.  * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
  40.  */
  41. #include <assert.h>
  42. #include <stdio.h>
  43. #include <setjmp.h>
  44. #include "jpeglib.h"
  45. #include "jerror.h"
  46.  
  47. /*
  48.  * On some machines it may be worthwhile to use _setjmp or sigsetjmp
  49.  * in place of plain setjmp.  These macros will make it easier.
  50.  */
  51. #define SETJMP(jbuf)        setjmp(jbuf)
  52. #define LONGJMP(jbuf,code)    longjmp(jbuf,code)
  53. #define JMP_BUF            jmp_buf
  54.  
  55. typedef struct jpeg_destination_mgr jpeg_destination_mgr;
  56. typedef struct jpeg_source_mgr jpeg_source_mgr;
  57. typedef    struct jpeg_error_mgr jpeg_error_mgr;
  58.  
  59. /*
  60.  * State block for each open TIFF file using
  61.  * libjpeg to do JPEG compression/decompression.
  62.  *
  63.  * libjpeg's visible state is either a jpeg_compress_struct
  64.  * or jpeg_decompress_struct depending on which way we
  65.  * are going.  comm can be used to refer to the fields
  66.  * which are common to both.
  67.  *
  68.  * NB: cinfo is required to be the first member of JPEGState,
  69.  *     so we can safely cast JPEGState* -> jpeg_xxx_struct*
  70.  *     and vice versa!
  71.  */
  72. typedef    struct {
  73.     union {
  74.         struct jpeg_compress_struct c;
  75.         struct jpeg_decompress_struct d;
  76.         struct jpeg_common_struct comm;
  77.     } cinfo;            /* NB: must be first */
  78.     jpeg_error_mgr    err;        /* libjpeg error manager */
  79.     JMP_BUF        exit_jmpbuf;    /* for catching libjpeg failures */
  80.     /*
  81.      * The following two members could be a union, but
  82.      * they're small enough that it's not worth the effort.
  83.      */
  84.     jpeg_destination_mgr dest;    /* data dest for compression */
  85.     jpeg_source_mgr    src;        /* data source for decompression */
  86.                     /* private state */
  87.     TIFF*        tif;        /* back link needed by some code */
  88.     uint16        photometric;    /* copy of PhotometricInterpretation */
  89.     uint16        h_sampling;    /* luminance sampling factors */
  90.     uint16        v_sampling;
  91.     tsize_t        bytesperline;    /* decompressed bytes per scanline */
  92.     /* pointers to intermediate buffers when processing downsampled data */
  93.     JSAMPARRAY    ds_buffer[MAX_COMPONENTS];
  94.     int        scancount;    /* number of "scanlines" accumulated */
  95.     int        samplesperclump;
  96.  
  97.     TIFFVGetMethod    vgetparent;    /* super-class method */
  98.     TIFFVSetMethod    vsetparent;    /* super-class method */
  99.     TIFFStripMethod    defsparent;    /* super-class method */
  100.     TIFFTileMethod    deftparent;    /* super-class method */
  101.                     /* pseudo-tag fields */
  102.     void*        jpegtables;    /* JPEGTables tag value, or NULL */
  103.     uint32        jpegtables_length; /* number of bytes in same */
  104.     int        jpegquality;    /* Compression quality level */
  105.     int        jpegcolormode;    /* Auto RGB<=>YCbCr convert? */
  106.     int        jpegtablesmode;    /* What to put in JPEGTables */
  107. } JPEGState;
  108.  
  109. #define    JState(tif)    ((JPEGState*)(tif)->tif_data)
  110.  
  111. static    int JPEGDecode(TIFF*, tidata_t, tsize_t, tsample_t);
  112. static    int JPEGDecodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
  113. static    int JPEGEncode(TIFF*, tidata_t, tsize_t, tsample_t);
  114. static    int JPEGEncodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
  115.  
  116. #define    FIELD_JPEGTABLES    (FIELD_CODEC+0)
  117. #define    FIELD_JPEGQUALITY    (FIELD_CODEC+1)
  118. #define    FIELD_JPEGCOLORMODE    (FIELD_CODEC+2)
  119. #define    FIELD_JPEGTABLESMODE    (FIELD_CODEC+3)
  120.  
  121. static const TIFFFieldInfo jpegFieldInfo[] = {
  122.     { TIFFTAG_JPEGTABLES,     -1,-1,    TIFF_UNDEFINED,    FIELD_JPEGTABLES,
  123.       FALSE,    TRUE,    "JPEGTables" },
  124.     { TIFFTAG_JPEGQUALITY,     0, 0,    TIFF_ANY,    FIELD_JPEGQUALITY,
  125.       TRUE,    FALSE,    "" },
  126.     { TIFFTAG_JPEGCOLORMODE,     0, 0,    TIFF_ANY,    FIELD_JPEGCOLORMODE,
  127.       FALSE,    FALSE,    "" },
  128.     { TIFFTAG_JPEGTABLESMODE,     0, 0,    TIFF_ANY,    FIELD_JPEGTABLESMODE,
  129.       FALSE,    FALSE,    "" },
  130. };
  131. #define    N(a)    (sizeof (a) / sizeof (a[0]))
  132.  
  133. /*
  134.  * libjpeg interface layer.
  135.  *
  136.  * We use setjmp/longjmp to return control to libtiff
  137.  * when a fatal error is encountered within the JPEG
  138.  * library.  We also direct libjpeg error and warning
  139.  * messages through the appropriate libtiff handlers.
  140.  */
  141.  
  142. /*
  143.  * Error handling routines (these replace corresponding
  144.  * IJG routines from jerror.c).  These are used for both
  145.  * compression and decompression.
  146.  */
  147. static void
  148. TIFFjpeg_error_exit(j_common_ptr cinfo)
  149. {
  150.     JPEGState *sp = (JPEGState *) cinfo;    /* NB: cinfo assumed first */
  151.     char buffer[JMSG_LENGTH_MAX];
  152.  
  153.     (*cinfo->err->format_message) (cinfo, buffer);
  154.     TIFFError("JPEGLib", buffer);        /* display the error message */
  155.     jpeg_abort(cinfo);            /* clean up libjpeg state */
  156.     LONGJMP(sp->exit_jmpbuf, 1);        /* return to libtiff caller */
  157. }
  158.  
  159. /*
  160.  * This routine is invoked only for warning messages,
  161.  * since error_exit does its own thing and trace_level
  162.  * is never set > 0.
  163.  */
  164. static void
  165. TIFFjpeg_output_message(j_common_ptr cinfo)
  166. {
  167.     char buffer[JMSG_LENGTH_MAX];
  168.  
  169.     (*cinfo->err->format_message) (cinfo, buffer);
  170.     TIFFWarning("JPEGLib", buffer);
  171. }
  172.  
  173. /*
  174.  * Interface routines.  This layer of routines exists
  175.  * primarily to limit side-effects from using setjmp.
  176.  * Also, normal/error returns are converted into return
  177.  * values per libtiff practice.
  178.  */
  179. #define    CALLJPEG(sp, fail, op)    (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
  180. #define    CALLVJPEG(sp, op)    CALLJPEG(sp, 0, ((op),1))
  181.  
  182. static int
  183. TIFFjpeg_create_compress(JPEGState* sp)
  184. {
  185.     /* initialize JPEG error handling */
  186.     sp->cinfo.c.err = jpeg_std_error(&sp->err);
  187.     sp->err.error_exit = TIFFjpeg_error_exit;
  188.     sp->err.output_message = TIFFjpeg_output_message;
  189.  
  190.     return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
  191. }
  192.  
  193. static int
  194. TIFFjpeg_create_decompress(JPEGState* sp)
  195. {
  196.     /* initialize JPEG error handling */
  197.     sp->cinfo.d.err = jpeg_std_error(&sp->err);
  198.     sp->err.error_exit = TIFFjpeg_error_exit;
  199.     sp->err.output_message = TIFFjpeg_output_message;
  200.  
  201.     return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
  202. }
  203.  
  204. static int
  205. TIFFjpeg_set_defaults(JPEGState* sp)
  206. {
  207.     return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
  208. }
  209.  
  210. static int
  211. TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
  212. {
  213.     return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
  214. }
  215.  
  216. static int
  217. TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
  218. {
  219.     return CALLVJPEG(sp,
  220.         jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
  221. }
  222.  
  223. static int
  224. TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
  225. {
  226.     return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
  227. }
  228.  
  229. static int
  230. TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
  231. {
  232.     return CALLVJPEG(sp,
  233.         jpeg_start_compress(&sp->cinfo.c, write_all_tables));
  234. }
  235.  
  236. static int
  237. TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
  238. {
  239.     return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
  240.         scanlines, (JDIMENSION) num_lines));
  241. }
  242.  
  243. static int
  244. TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
  245. {
  246.     return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
  247.         data, (JDIMENSION) num_lines));
  248. }
  249.  
  250. static int
  251. TIFFjpeg_finish_compress(JPEGState* sp)
  252. {
  253.     return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
  254. }
  255.  
  256. static int
  257. TIFFjpeg_write_tables(JPEGState* sp)
  258. {
  259.     return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
  260. }
  261.  
  262. static int
  263. TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
  264. {
  265.     return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
  266. }
  267.  
  268. static int
  269. TIFFjpeg_start_decompress(JPEGState* sp)
  270. {
  271.     return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
  272. }
  273.  
  274. static int
  275. TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
  276. {
  277.     return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
  278.         scanlines, (JDIMENSION) max_lines));
  279. }
  280.  
  281. static int
  282. TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
  283. {
  284.     return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
  285.         data, (JDIMENSION) max_lines));
  286. }
  287.  
  288. static int
  289. TIFFjpeg_finish_decompress(JPEGState* sp)
  290. {
  291.     return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
  292. }
  293.  
  294. static int
  295. TIFFjpeg_abort(JPEGState* sp)
  296. {
  297.     return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
  298. }
  299.  
  300. static int
  301. TIFFjpeg_destroy(JPEGState* sp)
  302. {
  303.     return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
  304. }
  305.  
  306. static JSAMPARRAY
  307. TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
  308.               JDIMENSION samplesperrow, JDIMENSION numrows)
  309. {
  310.     return CALLJPEG(sp, (JSAMPARRAY) NULL,
  311.         (*sp->cinfo.comm.mem->alloc_sarray)
  312.         (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
  313. }
  314.  
  315. /*
  316.  * JPEG library destination data manager.
  317.  * These routines direct compressed data from libjpeg into the
  318.  * libtiff output buffer.
  319.  */
  320.  
  321. static void
  322. std_init_destination(j_compress_ptr cinfo)
  323. {
  324.     JPEGState* sp = (JPEGState*) cinfo;
  325.     TIFF* tif = sp->tif;
  326.  
  327.     sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
  328.     sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
  329. }
  330.  
  331. static boolean
  332. std_empty_output_buffer(j_compress_ptr cinfo)
  333. {
  334.     JPEGState* sp = (JPEGState*) cinfo;
  335.     TIFF* tif = sp->tif;
  336.  
  337.     /* the entire buffer has been filled */
  338.     tif->tif_rawcc = tif->tif_rawdatasize;
  339.     TIFFFlushData1(tif);
  340.     sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
  341.     sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
  342.  
  343.     return (TRUE);
  344. }
  345.  
  346. static void
  347. std_term_destination(j_compress_ptr cinfo)
  348. {
  349.     JPEGState* sp = (JPEGState*) cinfo;
  350.     TIFF* tif = sp->tif;
  351.  
  352.     tif->tif_rawcp = (tidata_t) sp->dest.next_output_byte;
  353.     tif->tif_rawcc =
  354.         tif->tif_rawdatasize - (tsize_t) sp->dest.free_in_buffer;
  355.     /* NB: libtiff does the final buffer flush */
  356. }
  357.  
  358. static void
  359. TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
  360. {
  361.     (void) tif;
  362.     sp->cinfo.c.dest = &sp->dest;
  363.     sp->dest.init_destination = std_init_destination;
  364.     sp->dest.empty_output_buffer = std_empty_output_buffer;
  365.     sp->dest.term_destination = std_term_destination;
  366. }
  367.  
  368. /*
  369.  * Alternate destination manager for outputting to JPEGTables field.
  370.  */
  371.  
  372. static void
  373. tables_init_destination(j_compress_ptr cinfo)
  374. {
  375.     JPEGState* sp = (JPEGState*) cinfo;
  376.  
  377.     /* while building, jpegtables_length is allocated buffer size */
  378.     sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
  379.     sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
  380. }
  381.  
  382. static boolean
  383. tables_empty_output_buffer(j_compress_ptr cinfo)
  384. {
  385.     JPEGState* sp = (JPEGState*) cinfo;
  386.     void* newbuf;
  387.  
  388.     /* the entire buffer has been filled; enlarge it by 1000 bytes */
  389.     newbuf = _TIFFrealloc((tdata_t) sp->jpegtables,
  390.                   (tsize_t) (sp->jpegtables_length + 1000));
  391.     if (newbuf == NULL)
  392.         ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
  393.     sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
  394.     sp->dest.free_in_buffer = (size_t) 1000;
  395.     sp->jpegtables = newbuf;
  396.     sp->jpegtables_length += 1000;
  397.     return (TRUE);
  398. }
  399.  
  400. static void
  401. tables_term_destination(j_compress_ptr cinfo)
  402. {
  403.     JPEGState* sp = (JPEGState*) cinfo;
  404.  
  405.     /* set tables length to number of bytes actually emitted */
  406.     sp->jpegtables_length -= sp->dest.free_in_buffer;
  407. }
  408.  
  409. static int
  410. TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
  411. {
  412.     (void) tif;
  413.     /*
  414.      * Allocate a working buffer for building tables.
  415.      * Initial size is 1000 bytes, which is usually adequate.
  416.      */
  417.     if (sp->jpegtables)
  418.         _TIFFfree(sp->jpegtables);
  419.     sp->jpegtables_length = 1000;
  420.     sp->jpegtables = (void*) _TIFFmalloc((tsize_t) sp->jpegtables_length);
  421.     if (sp->jpegtables == NULL) {
  422.         sp->jpegtables_length = 0;
  423.         TIFFError("TIFFjpeg_tables_dest", "No space for JPEGTables");
  424.         return (0);
  425.     }
  426.     sp->cinfo.c.dest = &sp->dest;
  427.     sp->dest.init_destination = tables_init_destination;
  428.     sp->dest.empty_output_buffer = tables_empty_output_buffer;
  429.     sp->dest.term_destination = tables_term_destination;
  430.     return (1);
  431. }
  432.  
  433. /*
  434.  * JPEG library source data manager.
  435.  * These routines supply compressed data to libjpeg.
  436.  */
  437.  
  438. static void
  439. std_init_source(j_decompress_ptr cinfo)
  440. {
  441.     JPEGState* sp = (JPEGState*) cinfo;
  442.     TIFF* tif = sp->tif;
  443.  
  444.     sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
  445.     sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
  446. }
  447.  
  448. static boolean
  449. std_fill_input_buffer(j_decompress_ptr cinfo)
  450. {
  451.     JPEGState* sp = (JPEGState* ) cinfo;
  452.     static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
  453.  
  454.     /*
  455.      * Should never get here since entire strip/tile is
  456.      * read into memory before the decompressor is called,
  457.      * and thus was supplied by init_source.
  458.      */
  459.     WARNMS(cinfo, JWRN_JPEG_EOF);
  460.     /* insert a fake EOI marker */
  461.     sp->src.next_input_byte = dummy_EOI;
  462.     sp->src.bytes_in_buffer = 2;
  463.     return (TRUE);
  464. }
  465.  
  466. static void
  467. std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
  468. {
  469.     JPEGState* sp = (JPEGState*) cinfo;
  470.  
  471.     if (num_bytes > 0) {
  472.         if (num_bytes > (long) sp->src.bytes_in_buffer) {
  473.             /* oops, buffer overrun */
  474.             (void) std_fill_input_buffer(cinfo);
  475.         } else {
  476.             sp->src.next_input_byte += (size_t) num_bytes;
  477.             sp->src.bytes_in_buffer -= (size_t) num_bytes;
  478.         }
  479.     }
  480. }
  481.  
  482. static void
  483. std_term_source(j_decompress_ptr cinfo)
  484. {
  485.     /* No work necessary here */
  486.     /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
  487.     /* (if so, need empty tables_term_source!) */
  488.     (void) cinfo;
  489. }
  490.  
  491. static void
  492. TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
  493. {
  494.     (void) tif;
  495.     sp->cinfo.d.src = &sp->src;
  496.     sp->src.init_source = std_init_source;
  497.     sp->src.fill_input_buffer = std_fill_input_buffer;
  498.     sp->src.skip_input_data = std_skip_input_data;
  499.     sp->src.resync_to_restart = jpeg_resync_to_restart;
  500.     sp->src.term_source = std_term_source;
  501.     sp->src.bytes_in_buffer = 0;        /* for safety */
  502.     sp->src.next_input_byte = NULL;
  503. }
  504.  
  505. /*
  506.  * Alternate source manager for reading from JPEGTables.
  507.  * We can share all the code except for the init routine.
  508.  */
  509.  
  510. static void
  511. tables_init_source(j_decompress_ptr cinfo)
  512. {
  513.     JPEGState* sp = (JPEGState*) cinfo;
  514.  
  515.     sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
  516.     sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
  517. }
  518.  
  519. static void
  520. TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
  521. {
  522.     TIFFjpeg_data_src(sp, tif);
  523.     sp->src.init_source = tables_init_source;
  524. }
  525.  
  526. /*
  527.  * Allocate downsampled-data buffers needed for downsampled I/O.
  528.  * We use values computed in jpeg_start_compress or jpeg_start_decompress.
  529.  * We use libjpeg's allocator so that buffers will be released automatically
  530.  * when done with strip/tile.
  531.  * This is also a handy place to compute samplesperclump, bytesperline.
  532.  */
  533. static int
  534. alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
  535.               int num_components)
  536. {
  537.     JPEGState* sp = JState(tif);
  538.     int ci;
  539.     jpeg_component_info* compptr;
  540.     JSAMPARRAY buf;
  541.     int samples_per_clump = 0;
  542.  
  543.     for (ci = 0, compptr = comp_info; ci < num_components;
  544.          ci++, compptr++) {
  545.         samples_per_clump += compptr->h_samp_factor *
  546.             compptr->v_samp_factor;
  547.         buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
  548.                 compptr->width_in_blocks * DCTSIZE,
  549.                 (JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
  550.         if (buf == NULL)
  551.             return (0);
  552.         sp->ds_buffer[ci] = buf;
  553.     }
  554.     sp->samplesperclump = samples_per_clump;
  555.     /* Cb,Cr both have sampling factors 1 */
  556.     /* so downsampled width of Cb is # of clumps per line */
  557.     sp->bytesperline = sizeof(JSAMPLE) * samples_per_clump *
  558.         comp_info[1].downsampled_width;
  559.     return (1);
  560. }
  561.  
  562.  
  563. /*
  564.  * JPEG Decoding.
  565.  */
  566.  
  567. static int
  568. JPEGSetupDecode(TIFF* tif)
  569. {
  570.     JPEGState* sp = JState(tif);
  571.     TIFFDirectory *td = &tif->tif_dir;
  572.  
  573.     assert(sp != NULL);
  574.     assert(sp->cinfo.comm.is_decompressor);
  575.  
  576.     /* Read JPEGTables if it is present */
  577.     if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
  578.         TIFFjpeg_tables_src(sp, tif);
  579.         if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
  580.             TIFFError("JPEGSetupDecode", "Bogus JPEGTables field");
  581.             return (0);
  582.         }
  583.     }
  584.  
  585.     /* Grab parameters that are same for all strips/tiles */
  586.     sp->photometric = td->td_photometric;
  587.     switch (sp->photometric) {
  588.     case PHOTOMETRIC_YCBCR:
  589.         sp->h_sampling = td->td_ycbcrsubsampling[0];
  590.         sp->v_sampling = td->td_ycbcrsubsampling[1];
  591.         break;
  592.     default:
  593.         /* TIFF 6.0 forbids subsampling of all other color spaces */
  594.         sp->h_sampling = 1;
  595.         sp->v_sampling = 1;
  596.         break;
  597.     }
  598.  
  599.     /* Set up for reading normal data */
  600.     TIFFjpeg_data_src(sp, tif);
  601.     tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
  602.     return (1);
  603. }
  604.  
  605. /*
  606.  * Set up for decoding a strip or tile.
  607.  */
  608. static int
  609. JPEGPreDecode(TIFF* tif, tsample_t s)
  610. {
  611.     JPEGState *sp = JState(tif);
  612.     TIFFDirectory *td = &tif->tif_dir;
  613.     static char module[] = "JPEGPreDecode";
  614.     uint32 segment_width, segment_height;
  615.     int downsampled_output;
  616.     int ci;
  617.  
  618.     assert(sp != NULL);
  619.     assert(sp->cinfo.comm.is_decompressor);
  620.     /*
  621.      * Reset decoder state from any previous strip/tile,
  622.      * in case application didn't read the whole strip.
  623.      */
  624.     if (!TIFFjpeg_abort(sp))
  625.         return (0);
  626.     /*
  627.      * Read the header for this strip/tile.
  628.      */
  629.     if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
  630.         return (0);
  631.     /*
  632.      * Check image parameters and set decompression parameters.
  633.      */
  634.     if (isTiled(tif)) {
  635.         segment_width = td->td_tilewidth;
  636.         segment_height = td->td_tilelength;
  637.         sp->bytesperline = TIFFTileRowSize(tif);
  638.     } else {
  639.         segment_width = td->td_imagewidth;
  640.         segment_height = td->td_imagelength - tif->tif_row;
  641.         if (segment_height > td->td_rowsperstrip)
  642.             segment_height = td->td_rowsperstrip;
  643.         sp->bytesperline = TIFFScanlineSize(tif);
  644.     }
  645.     if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
  646.         /*
  647.          * For PC 2, scale down the expected strip/tile size
  648.          * to match a downsampled component
  649.          */
  650.         segment_width = TIFFhowmany(segment_width, sp->h_sampling);
  651.         segment_height = TIFFhowmany(segment_height, sp->v_sampling);
  652.     }
  653.     if (sp->cinfo.d.image_width != segment_width ||
  654.         sp->cinfo.d.image_height != segment_height) {
  655.         TIFFError(module, "Improper JPEG strip/tile size");
  656.         return (0);
  657.     }
  658.     if (sp->cinfo.d.num_components !=
  659.         (td->td_planarconfig == PLANARCONFIG_CONTIG ?
  660.          td->td_samplesperpixel : 1)) {
  661.         TIFFError(module, "Improper JPEG component count");
  662.         return (0);
  663.     }
  664.     if (sp->cinfo.d.data_precision != td->td_bitspersample) {
  665.         TIFFError(module, "Improper JPEG data precision");
  666.         return (0);
  667.     }
  668.     if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
  669.         /* Component 0 should have expected sampling factors */
  670.         if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
  671.             sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
  672.             TIFFError(module, "Improper JPEG sampling factors");
  673.             return (0);
  674.         }
  675.         /* Rest should have sampling factors 1,1 */
  676.         for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
  677.             if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
  678.                 sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
  679.                 TIFFError(module, "Improper JPEG sampling factors");
  680.                 return (0);
  681.             }
  682.         }
  683.     } else {
  684.         /* PC 2's single component should have sampling factors 1,1 */
  685.         if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
  686.             sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
  687.             TIFFError(module, "Improper JPEG sampling factors");
  688.             return (0);
  689.         }
  690.     }
  691.     downsampled_output = FALSE;
  692.     if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
  693.         sp->photometric == PHOTOMETRIC_YCBCR &&
  694.         sp->jpegcolormode == JPEGCOLORMODE_RGB) {
  695.         /* Convert YCbCr to RGB */
  696.         sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
  697.         sp->cinfo.d.out_color_space = JCS_RGB;
  698.     } else {
  699.         /* Suppress colorspace handling */
  700.         sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
  701.         sp->cinfo.d.out_color_space = JCS_UNKNOWN;
  702.         if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
  703.             (sp->h_sampling != 1 || sp->v_sampling != 1))
  704.             downsampled_output = TRUE;
  705.         /* XXX what about up-sampling? */
  706.     }
  707.     if (downsampled_output) {
  708.         /* Need to use raw-data interface to libjpeg */
  709.         sp->cinfo.d.raw_data_out = TRUE;
  710.         tif->tif_decoderow = JPEGDecodeRaw;
  711.         tif->tif_decodestrip = JPEGDecodeRaw;
  712.         tif->tif_decodetile = JPEGDecodeRaw;
  713.     } else {
  714.         /* Use normal interface to libjpeg */
  715.         sp->cinfo.d.raw_data_out = FALSE;
  716.         tif->tif_decoderow = JPEGDecode;
  717.         tif->tif_decodestrip = JPEGDecode;
  718.         tif->tif_decodetile = JPEGDecode;
  719.     }
  720.     /* Start JPEG decompressor */
  721.     if (!TIFFjpeg_start_decompress(sp))
  722.         return (0);
  723.     /* Allocate downsampled-data buffers if needed */
  724.     if (downsampled_output) {
  725.         if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
  726.                            sp->cinfo.d.num_components))
  727.             return (0);
  728.         sp->scancount = DCTSIZE;    /* mark buffer empty */
  729.     }
  730.     return (1);
  731. }
  732.  
  733. /*
  734.  * Decode a chunk of pixels.
  735.  * "Standard" case: returned data is not downsampled.
  736.  */
  737. static int
  738. JPEGDecode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
  739. {
  740.     JPEGState *sp = JState(tif);
  741.     tsize_t nrows;
  742.     JSAMPROW bufptr[1];
  743.  
  744.     (void) s;
  745.     assert(sp != NULL);
  746.     /* data is expected to be read in multiples of a scanline */
  747.     nrows = cc / sp->bytesperline;
  748.     if (cc % sp->bytesperline)
  749.         TIFFWarning(tif->tif_name, "fractional scanline not read");
  750.  
  751.     while (nrows-- > 0) {
  752.         bufptr[0] = (JSAMPROW) buf;
  753.         if (TIFFjpeg_read_scanlines(sp, bufptr, 1) != 1)
  754.             return (0);
  755.         if (nrows > 0)
  756.             tif->tif_row++;
  757.         buf += sp->bytesperline;
  758.     }
  759.     /* Close down the decompressor if we've finished the strip or tile. */
  760.     if (sp->cinfo.d.output_scanline == sp->cinfo.d.output_height) {
  761.         if (TIFFjpeg_finish_decompress(sp) != TRUE)
  762.             return (0);
  763.     }
  764.     return (1);
  765. }
  766.  
  767. /*
  768.  * Decode a chunk of pixels.
  769.  * Returned data is downsampled per sampling factors.
  770.  */
  771. static int
  772. JPEGDecodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
  773. {
  774.     JPEGState *sp = JState(tif);
  775.     JSAMPLE* inptr;
  776.     JSAMPLE* outptr;
  777.     tsize_t nrows;
  778.     JDIMENSION clumps_per_line, nclump;
  779.     int clumpoffset, ci, xpos, ypos;
  780.     jpeg_component_info* compptr;
  781.     int samples_per_clump = sp->samplesperclump;
  782.  
  783.     (void) s;
  784.     assert(sp != NULL);
  785.     /* data is expected to be read in multiples of a scanline */
  786.     nrows = cc / sp->bytesperline;
  787.     if (cc % sp->bytesperline)
  788.         TIFFWarning(tif->tif_name, "fractional scanline not read");
  789.  
  790.     /* Cb,Cr both have sampling factors 1, so this is correct */
  791.     clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
  792.  
  793.     while (nrows-- > 0) {
  794.         /* Reload downsampled-data buffer if needed */
  795.         if (sp->scancount >= DCTSIZE) {
  796.             int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
  797.             if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
  798.                 return (0);
  799.             sp->scancount = 0;
  800.             /* Close down the decompressor if done. */
  801.             if (sp->cinfo.d.output_scanline >=
  802.                 sp->cinfo.d.output_height) {
  803.                 if (TIFFjpeg_finish_decompress(sp) != TRUE)
  804.                     return (0);
  805.             }
  806.         }
  807.         /*
  808.          * Fastest way to unseparate the data is to make one pass
  809.          * over the scanline for each row of each component.
  810.          */
  811.         clumpoffset = 0;        /* first sample in clump */
  812.         for (ci = 0, compptr = sp->cinfo.d.comp_info;
  813.              ci < sp->cinfo.d.num_components;
  814.              ci++, compptr++) {
  815.             int hsamp = compptr->h_samp_factor;
  816.             int vsamp = compptr->v_samp_factor;
  817.             for (ypos = 0; ypos < vsamp; ypos++) {
  818.             inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
  819.             outptr = ((JSAMPLE*) buf) + clumpoffset;
  820.             if (hsamp == 1) {
  821.                 /* fast path for at least Cb and Cr */
  822.                 for (nclump = clumps_per_line; nclump-- > 0; ) {
  823.                 outptr[0] = *inptr++;
  824.                 outptr += samples_per_clump;
  825.                 }
  826.             } else {
  827.                 /* general case */
  828.                 for (nclump = clumps_per_line; nclump-- > 0; ) {
  829.                 for (xpos = 0; xpos < hsamp; xpos++)
  830.                     outptr[xpos] = *inptr++;
  831.                 outptr += samples_per_clump;
  832.                 }
  833.             }
  834.             clumpoffset += hsamp;
  835.             }
  836.         }
  837.         sp->scancount++;
  838.         if (nrows > 0)
  839.             tif->tif_row++;
  840.         buf += sp->bytesperline;
  841.     }
  842.     return (1);
  843. }
  844.  
  845.  
  846. /*
  847.  * JPEG Encoding.
  848.  */
  849.  
  850. static void
  851. unsuppress_quant_table (JPEGState* sp, int tblno)
  852. {
  853.     JQUANT_TBL* qtbl;
  854.  
  855.     if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
  856.         qtbl->sent_table = FALSE;
  857. }
  858.  
  859. static void
  860. unsuppress_huff_table (JPEGState* sp, int tblno)
  861. {
  862.     JHUFF_TBL* htbl;
  863.  
  864.     if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
  865.         htbl->sent_table = FALSE;
  866.     if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
  867.         htbl->sent_table = FALSE;
  868. }
  869.  
  870. static int
  871. prepare_JPEGTables(TIFF* tif)
  872. {
  873.     JPEGState* sp = JState(tif);
  874.  
  875.     /* Initialize quant tables for current quality setting */
  876.     if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
  877.         return (0);
  878.     /* Mark only the tables we want for output */
  879.     /* NB: chrominance tables are currently used only with YCbCr */
  880.     if (!TIFFjpeg_suppress_tables(sp, TRUE))
  881.         return (0);
  882.     if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
  883.         unsuppress_quant_table(sp, 0);
  884.         if (sp->photometric == PHOTOMETRIC_YCBCR)
  885.             unsuppress_quant_table(sp, 1);
  886.     }
  887.     if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
  888.         unsuppress_huff_table(sp, 0);
  889.         if (sp->photometric == PHOTOMETRIC_YCBCR)
  890.             unsuppress_huff_table(sp, 1);
  891.     }
  892.     /* Direct libjpeg output into jpegtables */
  893.     if (!TIFFjpeg_tables_dest(sp, tif))
  894.         return (0);
  895.     /* Emit tables-only datastream */
  896.     if (!TIFFjpeg_write_tables(sp))
  897.         return (0);
  898.  
  899.     return (1);
  900. }
  901.  
  902. static int
  903. JPEGSetupEncode(TIFF* tif)
  904. {
  905.     JPEGState* sp = JState(tif);
  906.     TIFFDirectory *td = &tif->tif_dir;
  907.     static char module[] = "JPEGSetupEncode";
  908.  
  909.     assert(sp != NULL);
  910.     assert(!sp->cinfo.comm.is_decompressor);
  911.  
  912.     /*
  913.      * Initialize all JPEG parameters to default values.
  914.      * Note that jpeg_set_defaults needs legal values for
  915.      * in_color_space and input_components.
  916.      */
  917.     sp->cinfo.c.in_color_space = JCS_UNKNOWN;
  918.     sp->cinfo.c.input_components = 1;
  919.     if (!TIFFjpeg_set_defaults(sp))
  920.         return (0);
  921.     /* Set per-file parameters */
  922.     sp->photometric = td->td_photometric;
  923.     switch (sp->photometric) {
  924.     case PHOTOMETRIC_YCBCR:
  925.         sp->h_sampling = td->td_ycbcrsubsampling[0];
  926.         sp->v_sampling = td->td_ycbcrsubsampling[1];
  927.         /*
  928.          * A ReferenceBlackWhite field *must* be present since the
  929.          * default value is inappropriate for YCbCr.  Fill in the
  930.          * proper value if application didn't set it.
  931.          */
  932. #ifdef COLORIMETRY_SUPPORT
  933.         if (!TIFFFieldSet(tif, FIELD_REFBLACKWHITE)) {
  934.             float refbw[6];
  935.             long top = 1L << td->td_bitspersample;
  936.             refbw[0] = 0;
  937.             refbw[1] = (float)(top-1L);
  938.             refbw[2] = (float)(top>>1);
  939.             refbw[3] = refbw[1];
  940.             refbw[4] = refbw[2];
  941.             refbw[5] = refbw[1];
  942.             TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE, refbw);
  943.         }
  944. #endif
  945.         break;
  946.     case PHOTOMETRIC_PALETTE:        /* disallowed by Tech Note */
  947.     case PHOTOMETRIC_MASK:
  948.         TIFFError(module,
  949.               "PhotometricInterpretation %d not allowed for JPEG",
  950.               (int) sp->photometric);
  951.         return (0);
  952.     default:
  953.         /* TIFF 6.0 forbids subsampling of all other color spaces */
  954.         sp->h_sampling = 1;
  955.         sp->v_sampling = 1;
  956.         break;
  957.     }
  958.     
  959.     /* Verify miscellaneous parameters */
  960.  
  961.     /*
  962.      * This would need work if libtiff ever supports different
  963.      * depths for different components, or if libjpeg ever supports
  964.      * run-time selection of depth.  Neither is imminent.
  965.      */
  966.     if (td->td_bitspersample != BITS_IN_JSAMPLE) {
  967.         TIFFError(module, "BitsPerSample %d not allowed for JPEG",
  968.               (int) td->td_bitspersample);
  969.         return (0);
  970.     }
  971.     sp->cinfo.c.data_precision = td->td_bitspersample;
  972.     if (isTiled(tif)) {
  973.         if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
  974.             TIFFError(module,
  975.                   "JPEG tile height must be multiple of %d",
  976.                   sp->v_sampling * DCTSIZE);
  977.             return (0);
  978.         }
  979.         if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
  980.             TIFFError(module,
  981.                   "JPEG tile width must be multiple of %d",
  982.                   sp->h_sampling * DCTSIZE);
  983.             return (0);
  984.         }
  985.     } else {
  986.         if (td->td_rowsperstrip < td->td_imagelength &&
  987.             (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
  988.             TIFFError(module,
  989.                   "RowsPerStrip must be multiple of %d for JPEG",
  990.                   sp->v_sampling * DCTSIZE);
  991.             return (0);
  992.         }
  993.     }
  994.  
  995.     /* Create a JPEGTables field if appropriate */
  996.     if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
  997.         if (!prepare_JPEGTables(tif))
  998.             return (0);
  999.         /* Mark the field present */
  1000.         /* Can't use TIFFSetField since BEENWRITING is already set! */
  1001.         TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
  1002.         tif->tif_flags |= TIFF_DIRTYDIRECT;
  1003.     } else {
  1004.         /* We do not support application-supplied JPEGTables, */
  1005.         /* so mark the field not present */
  1006.         TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
  1007.     }
  1008.  
  1009.     /* Direct libjpeg output to libtiff's output buffer */
  1010.     TIFFjpeg_data_dest(sp, tif);
  1011.  
  1012.     return (1);
  1013. }
  1014.  
  1015. /*
  1016.  * Set encoding state at the start of a strip or tile.
  1017.  */
  1018. static int
  1019. JPEGPreEncode(TIFF* tif, tsample_t s)
  1020. {
  1021.     JPEGState *sp = JState(tif);
  1022.     TIFFDirectory *td = &tif->tif_dir;
  1023.     static char module[] = "JPEGPreEncode";
  1024.     uint32 segment_width, segment_height;
  1025.     int downsampled_input;
  1026.  
  1027.     assert(sp != NULL);
  1028.     assert(!sp->cinfo.comm.is_decompressor);
  1029.     /*
  1030.      * Set encoding parameters for this strip/tile.
  1031.      */
  1032.     if (isTiled(tif)) {
  1033.         segment_width = td->td_tilewidth;
  1034.         segment_height = td->td_tilelength;
  1035.         sp->bytesperline = TIFFTileRowSize(tif);
  1036.     } else {
  1037.         segment_width = td->td_imagewidth;
  1038.         segment_height = td->td_imagelength - tif->tif_row;
  1039.         if (segment_height > td->td_rowsperstrip)
  1040.             segment_height = td->td_rowsperstrip;
  1041.         sp->bytesperline = TIFFScanlineSize(tif);
  1042.     }
  1043.     if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
  1044.         /* for PC 2, scale down the strip/tile size
  1045.          * to match a downsampled component
  1046.          */
  1047.         segment_width = TIFFhowmany(segment_width, sp->h_sampling);
  1048.         segment_height = TIFFhowmany(segment_height, sp->v_sampling);
  1049.     }
  1050.     if (segment_width > 65535 || segment_height > 65535) {
  1051.         TIFFError(module, "Strip/tile too large for JPEG");
  1052.         return (0);
  1053.     }
  1054.     sp->cinfo.c.image_width = segment_width;
  1055.     sp->cinfo.c.image_height = segment_height;
  1056.     downsampled_input = FALSE;
  1057.     if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
  1058.         sp->cinfo.c.input_components = td->td_samplesperpixel;
  1059.         if (sp->photometric == PHOTOMETRIC_YCBCR) {
  1060.             if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
  1061.                 sp->cinfo.c.in_color_space = JCS_RGB;
  1062.             } else {
  1063.                 sp->cinfo.c.in_color_space = JCS_YCbCr;
  1064.                 if (sp->h_sampling != 1 || sp->v_sampling != 1)
  1065.                     downsampled_input = TRUE;
  1066.             }
  1067.             if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
  1068.                 return (0);
  1069.             /*
  1070.              * Set Y sampling factors;
  1071.              * we assume jpeg_set_colorspace() set the rest to 1
  1072.              */
  1073.             sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
  1074.             sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
  1075.         } else {
  1076.             sp->cinfo.c.in_color_space = JCS_UNKNOWN;
  1077.             if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
  1078.                 return (0);
  1079.             /* jpeg_set_colorspace set all sampling factors to 1 */
  1080.         }
  1081.     } else {
  1082.         sp->cinfo.c.input_components = 1;
  1083.         sp->cinfo.c.in_color_space = JCS_UNKNOWN;
  1084.         if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
  1085.             return (0);
  1086.         sp->cinfo.c.comp_info[0].component_id = s;
  1087.         /* jpeg_set_colorspace() set sampling factors to 1 */
  1088.         if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
  1089.             sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
  1090.             sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
  1091.             sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
  1092.         }
  1093.     }
  1094.     /* ensure libjpeg won't write any extraneous markers */
  1095.     sp->cinfo.c.write_JFIF_header = FALSE;
  1096.     sp->cinfo.c.write_Adobe_marker = FALSE;
  1097.     /* set up table handling correctly */
  1098.     if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
  1099.         if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
  1100.             return (0);
  1101.         unsuppress_quant_table(sp, 0);
  1102.         unsuppress_quant_table(sp, 1);
  1103.     }
  1104.     if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
  1105.         sp->cinfo.c.optimize_coding = FALSE;
  1106.     else
  1107.         sp->cinfo.c.optimize_coding = TRUE;
  1108.     if (downsampled_input) {
  1109.         /* Need to use raw-data interface to libjpeg */
  1110.         sp->cinfo.c.raw_data_in = TRUE;
  1111.         tif->tif_encoderow = JPEGEncodeRaw;
  1112.         tif->tif_encodestrip = JPEGEncodeRaw;
  1113.         tif->tif_encodetile = JPEGEncodeRaw;
  1114.     } else {
  1115.         /* Use normal interface to libjpeg */
  1116.         sp->cinfo.c.raw_data_in = FALSE;
  1117.         tif->tif_encoderow = JPEGEncode;
  1118.         tif->tif_encodestrip = JPEGEncode;
  1119.         tif->tif_encodetile = JPEGEncode;
  1120.     }
  1121.     /* Start JPEG compressor */
  1122.     if (!TIFFjpeg_start_compress(sp, FALSE))
  1123.         return (0);
  1124.     /* Allocate downsampled-data buffers if needed */
  1125.     if (downsampled_input) {
  1126.         if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
  1127.                            sp->cinfo.c.num_components))
  1128.             return (0);
  1129.     }
  1130.     sp->scancount = 0;
  1131.  
  1132.     return (1);
  1133. }
  1134.  
  1135. /*
  1136.  * Encode a chunk of pixels.
  1137.  * "Standard" case: incoming data is not downsampled.
  1138.  */
  1139. static int
  1140. JPEGEncode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
  1141. {
  1142.     JPEGState *sp = JState(tif);
  1143.     tsize_t nrows;
  1144.     JSAMPROW bufptr[1];
  1145.  
  1146.     (void) s;
  1147.     assert(sp != NULL);
  1148.     /* data is expected to be supplied in multiples of a scanline */
  1149.     nrows = cc / sp->bytesperline;
  1150.     if (cc % sp->bytesperline)
  1151.         TIFFWarning(tif->tif_name, "fractional scanline discarded");
  1152.  
  1153.     while (nrows-- > 0) {
  1154.         bufptr[0] = (JSAMPROW) buf;
  1155.         if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
  1156.             return (0);
  1157.         if (nrows > 0)
  1158.             tif->tif_row++;
  1159.         buf += sp->bytesperline;
  1160.     }
  1161.     return (1);
  1162. }
  1163.  
  1164. /*
  1165.  * Encode a chunk of pixels.
  1166.  * Incoming data is expected to be downsampled per sampling factors.
  1167.  */
  1168. static int
  1169. JPEGEncodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
  1170. {
  1171.     JPEGState *sp = JState(tif);
  1172.     JSAMPLE* inptr;
  1173.     JSAMPLE* outptr;
  1174.     tsize_t nrows;
  1175.     JDIMENSION clumps_per_line, nclump;
  1176.     int clumpoffset, ci, xpos, ypos;
  1177.     jpeg_component_info* compptr;
  1178.     int samples_per_clump = sp->samplesperclump;
  1179.  
  1180.     (void) s;
  1181.     assert(sp != NULL);
  1182.     /* data is expected to be supplied in multiples of a scanline */
  1183.     nrows = cc / sp->bytesperline;
  1184.     if (cc % sp->bytesperline)
  1185.         TIFFWarning(tif->tif_name, "fractional scanline discarded");
  1186.  
  1187.     /* Cb,Cr both have sampling factors 1, so this is correct */
  1188.     clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
  1189.  
  1190.     while (nrows-- > 0) {
  1191.         /*
  1192.          * Fastest way to separate the data is to make one pass
  1193.          * over the scanline for each row of each component.
  1194.          */
  1195.         clumpoffset = 0;        /* first sample in clump */
  1196.         for (ci = 0, compptr = sp->cinfo.c.comp_info;
  1197.              ci < sp->cinfo.c.num_components;
  1198.              ci++, compptr++) {
  1199.             int hsamp = compptr->h_samp_factor;
  1200.             int vsamp = compptr->v_samp_factor;
  1201.             int padding = (int) (compptr->width_in_blocks * DCTSIZE -
  1202.                      clumps_per_line * hsamp);
  1203.             for (ypos = 0; ypos < vsamp; ypos++) {
  1204.             inptr = ((JSAMPLE*) buf) + clumpoffset;
  1205.             outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
  1206.             if (hsamp == 1) {
  1207.                 /* fast path for at least Cb and Cr */
  1208.                 for (nclump = clumps_per_line; nclump-- > 0; ) {
  1209.                 *outptr++ = inptr[0];
  1210.                 inptr += samples_per_clump;
  1211.                 }
  1212.             } else {
  1213.                 /* general case */
  1214.                 for (nclump = clumps_per_line; nclump-- > 0; ) {
  1215.                 for (xpos = 0; xpos < hsamp; xpos++)
  1216.                     *outptr++ = inptr[xpos];
  1217.                 inptr += samples_per_clump;
  1218.                 }
  1219.             }
  1220.             /* pad each scanline as needed */
  1221.             for (xpos = 0; xpos < padding; xpos++) {
  1222.                 *outptr = outptr[-1];
  1223.                 outptr++;
  1224.             }
  1225.             clumpoffset += hsamp;
  1226.             }
  1227.         }
  1228.         sp->scancount++;
  1229.         if (sp->scancount >= DCTSIZE) {
  1230.             int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
  1231.             if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
  1232.                 return (0);
  1233.             sp->scancount = 0;
  1234.         }
  1235.         if (nrows > 0)
  1236.             tif->tif_row++;
  1237.         buf += sp->bytesperline;
  1238.     }
  1239.     return (1);
  1240. }
  1241.  
  1242. /*
  1243.  * Finish up at the end of a strip or tile.
  1244.  */
  1245. static int
  1246. JPEGPostEncode(TIFF* tif)
  1247. {
  1248.     JPEGState *sp = JState(tif);
  1249.  
  1250.     if (sp->scancount > 0) {
  1251.         /*
  1252.          * Need to emit a partial bufferload of downsampled data.
  1253.          * Pad the data vertically.
  1254.          */
  1255.         int ci, ypos, n;
  1256.         jpeg_component_info* compptr;
  1257.  
  1258.         for (ci = 0, compptr = sp->cinfo.c.comp_info;
  1259.              ci < sp->cinfo.c.num_components;
  1260.              ci++, compptr++) {
  1261.             int vsamp = compptr->v_samp_factor;
  1262.             tsize_t row_width = compptr->width_in_blocks * DCTSIZE
  1263.                 * sizeof(JSAMPLE);
  1264.             for (ypos = sp->scancount * vsamp;
  1265.                  ypos < DCTSIZE * vsamp; ypos++) {
  1266.                 _TIFFmemcpy((tdata_t)sp->ds_buffer[ci][ypos],
  1267.                         (tdata_t)sp->ds_buffer[ci][ypos-1],
  1268.                         row_width);
  1269.  
  1270.             }
  1271.         }
  1272.         n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
  1273.         if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
  1274.             return (0);
  1275.     }
  1276.  
  1277.     return (TIFFjpeg_finish_compress(JState(tif)));
  1278. }
  1279.  
  1280. static void
  1281. JPEGCleanup(TIFF* tif)
  1282. {
  1283.     if (tif->tif_data) {
  1284.         JPEGState *sp = JState(tif);
  1285.         TIFFjpeg_destroy(sp);        /* release libjpeg resources */
  1286.         if (sp->jpegtables)        /* tag value */
  1287.             _TIFFfree(sp->jpegtables);
  1288.         _TIFFfree(tif->tif_data);    /* release local state */
  1289.         tif->tif_data = NULL;
  1290.     }
  1291. }
  1292.  
  1293. static int
  1294. JPEGVSetField(TIFF* tif, ttag_t tag, va_list ap)
  1295. {
  1296.     JPEGState* sp = JState(tif);
  1297.     TIFFDirectory* td = &tif->tif_dir;
  1298.     uint32 v32;
  1299.  
  1300.     switch (tag) {
  1301.     case TIFFTAG_JPEGTABLES:
  1302.         v32 = va_arg(ap, uint32);
  1303.         if (v32 == 0) {
  1304.             /* XXX */
  1305.             return (0);
  1306.         }
  1307.         _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
  1308.             (long) v32);
  1309.         sp->jpegtables_length = v32;
  1310.         TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
  1311.         break;
  1312.     case TIFFTAG_JPEGQUALITY:
  1313.         sp->jpegquality = va_arg(ap, int);
  1314.         return (1);            /* pseudo tag */
  1315.     case TIFFTAG_JPEGCOLORMODE:
  1316.         sp->jpegcolormode = va_arg(ap, int);
  1317.         /*
  1318.          * Mark whether returned data is up-sampled or not
  1319.          * so TIFFStripSize and TIFFTileSize return values
  1320.          * that reflect the true amount of data.
  1321.          */
  1322.         tif->tif_flags &= ~TIFF_UPSAMPLED;
  1323.         if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
  1324.             if (td->td_photometric == PHOTOMETRIC_YCBCR &&
  1325.               sp->jpegcolormode == JPEGCOLORMODE_RGB) {
  1326.             tif->tif_flags |= TIFF_UPSAMPLED;
  1327.             } else {
  1328.             if (td->td_ycbcrsubsampling[0] != 1 ||
  1329.                 td->td_ycbcrsubsampling[1] != 1)
  1330.                 ; /* XXX what about up-sampling? */
  1331.             }
  1332.         }
  1333.         /*
  1334.          * Must recalculate cached tile size
  1335.          * in case sampling state changed.
  1336.          */
  1337.         tif->tif_tilesize = TIFFTileSize(tif);
  1338.         return (1);            /* pseudo tag */
  1339.     case TIFFTAG_JPEGTABLESMODE:
  1340.         sp->jpegtablesmode = va_arg(ap, int);
  1341.         return (1);            /* pseudo tag */
  1342.     default:
  1343.         return (*sp->vsetparent)(tif, tag, ap);
  1344.     }
  1345.     tif->tif_flags |= TIFF_DIRTYDIRECT;
  1346.     return (1);
  1347. }
  1348.  
  1349. static int
  1350. JPEGVGetField(TIFF* tif, ttag_t tag, va_list ap)
  1351. {
  1352.     JPEGState* sp = JState(tif);
  1353.  
  1354.     switch (tag) {
  1355.     case TIFFTAG_JPEGTABLES:
  1356.         /* u_short is bogus --- should be uint32 ??? */
  1357.         /* TIFFWriteNormalTag needs fixed  XXX */
  1358.         *va_arg(ap, u_short*) = (u_short) sp->jpegtables_length;
  1359.         *va_arg(ap, void**) = sp->jpegtables;
  1360.         break;
  1361.     case TIFFTAG_JPEGQUALITY:
  1362.         *va_arg(ap, int*) = sp->jpegquality;
  1363.         break;
  1364.     case TIFFTAG_JPEGCOLORMODE:
  1365.         *va_arg(ap, int*) = sp->jpegcolormode;
  1366.         break;
  1367.     case TIFFTAG_JPEGTABLESMODE:
  1368.         *va_arg(ap, int*) = sp->jpegtablesmode;
  1369.         break;
  1370.     default:
  1371.         return (*sp->vgetparent)(tif, tag, ap);
  1372.     }
  1373.     return (1);
  1374. }
  1375.  
  1376. static void
  1377. JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
  1378. {
  1379.     JPEGState* sp = JState(tif);
  1380.  
  1381.     (void) flags;
  1382.     if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
  1383.         fprintf(fd, "  JPEG Tables: (%lu bytes)\n",
  1384.             (u_long) sp->jpegtables_length);
  1385. }
  1386.  
  1387. static uint32
  1388. JPEGDefaultStripSize(TIFF* tif, uint32 s)
  1389. {
  1390.     JPEGState* sp = JState(tif);
  1391.     TIFFDirectory *td = &tif->tif_dir;
  1392.  
  1393.     s = (*sp->defsparent)(tif, s);
  1394.     if (s < td->td_imagelength)
  1395.         s = TIFFroundup(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
  1396.     return (s);
  1397. }
  1398.  
  1399. static void
  1400. JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
  1401. {
  1402.     JPEGState* sp = JState(tif);
  1403.     TIFFDirectory *td = &tif->tif_dir;
  1404.  
  1405.     (*sp->deftparent)(tif, tw, th);
  1406.     *tw = TIFFroundup(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
  1407.     *th = TIFFroundup(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
  1408. }
  1409.  
  1410. int
  1411. TIFFInitJPEG(TIFF* tif, int scheme)
  1412. {
  1413.     JPEGState* sp;
  1414.  
  1415.     assert(scheme == COMPRESSION_JPEG);
  1416.  
  1417.     /*
  1418.      * Allocate state block so tag methods have storage to record values.
  1419.      */
  1420.     tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (JPEGState));
  1421.     if (tif->tif_data == NULL) {
  1422.         TIFFError("TIFFInitJPEG", "No space for JPEG state block");
  1423.         return (0);
  1424.     }
  1425.     sp = JState(tif);
  1426.     sp->tif = tif;                /* back link */
  1427.  
  1428.     /*
  1429.      * Merge codec-specific tag information and
  1430.      * override parent get/set field methods.
  1431.      */
  1432.     _TIFFMergeFieldInfo(tif, jpegFieldInfo, N(jpegFieldInfo));
  1433.     sp->vgetparent = tif->tif_vgetfield;
  1434.     tif->tif_vgetfield = JPEGVGetField;    /* hook for codec tags */
  1435.     sp->vsetparent = tif->tif_vsetfield;
  1436.     tif->tif_vsetfield = JPEGVSetField;    /* hook for codec tags */
  1437.     tif->tif_printdir = JPEGPrintDir;    /* hook for codec tags */
  1438.  
  1439.     /* Default values for codec-specific fields */
  1440.     sp->jpegtables = NULL;
  1441.     sp->jpegtables_length = 0;
  1442.     sp->jpegquality = 75;            /* Default IJG quality */
  1443.     sp->jpegcolormode = JPEGCOLORMODE_RAW;
  1444.     sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
  1445.  
  1446.     /*
  1447.      * Install codec methods.
  1448.      */
  1449.     tif->tif_setupdecode = JPEGSetupDecode;
  1450.     tif->tif_predecode = JPEGPreDecode;
  1451.     tif->tif_decoderow = JPEGDecode;
  1452.     tif->tif_decodestrip = JPEGDecode;
  1453.     tif->tif_decodetile = JPEGDecode;
  1454.     tif->tif_setupencode = JPEGSetupEncode;
  1455.     tif->tif_preencode = JPEGPreEncode;
  1456.     tif->tif_postencode = JPEGPostEncode;
  1457.     tif->tif_encoderow = JPEGEncode;
  1458.     tif->tif_encodestrip = JPEGEncode;
  1459.     tif->tif_encodetile = JPEGEncode;
  1460.     tif->tif_cleanup = JPEGCleanup;
  1461.     sp->defsparent = tif->tif_defstripsize;
  1462.     tif->tif_defstripsize = JPEGDefaultStripSize;
  1463.     sp->deftparent = tif->tif_deftilesize;
  1464.     tif->tif_deftilesize = JPEGDefaultTileSize;
  1465.     tif->tif_flags |= TIFF_NOBITREV;    /* no bit reversal, please */
  1466.  
  1467.     /*
  1468.      * Initialize libjpeg.
  1469.      */
  1470.     if (tif->tif_mode == O_RDONLY) {
  1471.         if (!TIFFjpeg_create_decompress(sp))
  1472.             return (0);
  1473.     } else {
  1474.         if (!TIFFjpeg_create_compress(sp))
  1475.             return (0);
  1476.     }
  1477.  
  1478.     return (1);
  1479. }
  1480. #endif /* JPEG_SUPPORT */
  1481.