4  * Copyright (c) 1994-1997 Sam Leffler 
   5  * Copyright (c) 1994-1997 Silicon Graphics, Inc. 
   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. 
  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.   
  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  
  32  * JPEG Compression support per TIFF Technical Note #2 
  33  * (*not* per the original TIFF 6.0 spec). 
  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/. 
  39  * Contributed by Tom Lane <tgl@sss.pgh.pa.us>. 
  45 int TIFFFillStrip(TIFF
*, tstrip_t
); 
  46 int TIFFFillTile(TIFF
*, ttile_t
); 
  48 /* We undefine FAR to avoid conflict with JPEG definition */ 
  55    The windows RPCNDR.H file defines boolean, but defines it with the 
  56    wrong size.  So we declare HAVE_BOOLEAN so that the jpeg include file 
  57    won't try to typedef boolean, but #define it to override the rpcndr.h 
  60    http://bugzilla.remotesensing.org/show_bug.cgi?id=188 
  66     #define boolean wxHACK_BOOLEAN 
  72 #ifndef HAVE_WXJPEG_BOOLEAN 
  73 typedef boolean wxjpeg_boolean
; 
  77  * On some machines it may be worthwhile to use _setjmp or sigsetjmp 
  78  * in place of plain setjmp.  These macros will make it easier. 
  80 #define SETJMP(jbuf)            setjmp(jbuf) 
  81 #define LONGJMP(jbuf,code)      longjmp(jbuf,code) 
  82 #define JMP_BUF                 jmp_buf 
  84 typedef struct jpeg_destination_mgr jpeg_destination_mgr
; 
  85 typedef struct jpeg_source_mgr jpeg_source_mgr
; 
  86 typedef struct jpeg_error_mgr jpeg_error_mgr
; 
  89  * State block for each open TIFF file using 
  90  * libjpeg to do JPEG compression/decompression. 
  92  * libjpeg's visible state is either a jpeg_compress_struct 
  93  * or jpeg_decompress_struct depending on which way we 
  94  * are going.  comm can be used to refer to the fields 
  95  * which are common to both. 
  97  * NB: cinfo is required to be the first member of JPEGState, 
  98  *     so we can safely cast JPEGState* -> jpeg_xxx_struct* 
 103                 struct jpeg_compress_struct c
; 
 104                 struct jpeg_decompress_struct d
; 
 105                 struct jpeg_common_struct comm
; 
 106         } cinfo
;                        /* NB: must be first */ 
 107         int             cinfo_initialized
; 
 109         jpeg_error_mgr  err
;            /* libjpeg error manager */ 
 110         JMP_BUF         exit_jmpbuf
;    /* for catching libjpeg failures */ 
 112          * The following two members could be a union, but 
 113          * they're small enough that it's not worth the effort. 
 115         jpeg_destination_mgr dest
;      /* data dest for compression */ 
 116         jpeg_source_mgr src
;            /* data source for decompression */ 
 118         TIFF
*           tif
;            /* back link needed by some code */ 
 119         uint16          photometric
;    /* copy of PhotometricInterpretation */ 
 120         uint16          h_sampling
;     /* luminance sampling factors */ 
 122         tsize_t         bytesperline
;   /* decompressed bytes per scanline */ 
 123         /* pointers to intermediate buffers when processing downsampled data */ 
 124         JSAMPARRAY      ds_buffer
[MAX_COMPONENTS
]; 
 125         int             scancount
;      /* number of "scanlines" accumulated */ 
 128         TIFFVGetMethod  vgetparent
;     /* super-class method */ 
 129         TIFFVSetMethod  vsetparent
;     /* super-class method */ 
 130         TIFFStripMethod defsparent
;     /* super-class method */ 
 131         TIFFTileMethod  deftparent
;     /* super-class method */ 
 132                                         /* pseudo-tag fields */ 
 133         void*           jpegtables
;     /* JPEGTables tag value, or NULL */ 
 134         uint32          jpegtables_length
; /* number of bytes in same */ 
 135         int             jpegquality
;    /* Compression quality level */ 
 136         int             jpegcolormode
;  /* Auto RGB<=>YCbCr convert? */ 
 137         int             jpegtablesmode
; /* What to put in JPEGTables */ 
 139         int             ycbcrsampling_fetched
; 
 142 #define JState(tif)     ((JPEGState*)(tif)->tif_data) 
 144 static  int JPEGDecode(TIFF
*, tidata_t
, tsize_t
, tsample_t
); 
 145 static  int JPEGDecodeRaw(TIFF
*, tidata_t
, tsize_t
, tsample_t
); 
 146 static  int JPEGEncode(TIFF
*, tidata_t
, tsize_t
, tsample_t
); 
 147 static  int JPEGEncodeRaw(TIFF
*, tidata_t
, tsize_t
, tsample_t
); 
 148 static  int JPEGInitializeLibJPEG( TIFF 
* tif 
); 
 150 #define FIELD_JPEGTABLES        (FIELD_CODEC+0) 
 152 static const TIFFFieldInfo jpegFieldInfo
[] = { 
 153     { TIFFTAG_JPEGTABLES
,        -1,-1, TIFF_UNDEFINED
, FIELD_JPEGTABLES
, 
 154       FALSE
,    TRUE
,   "JPEGTables" }, 
 155     { TIFFTAG_JPEGQUALITY
,       0, 0,  TIFF_ANY
,       FIELD_PSEUDO
, 
 157     { TIFFTAG_JPEGCOLORMODE
,     0, 0,  TIFF_ANY
,       FIELD_PSEUDO
, 
 159     { TIFFTAG_JPEGTABLESMODE
,    0, 0,  TIFF_ANY
,       FIELD_PSEUDO
, 
 162 #define N(a)    (sizeof (a) / sizeof (a[0])) 
 165  * libjpeg interface layer. 
 167  * We use setjmp/longjmp to return control to libtiff 
 168  * when a fatal error is encountered within the JPEG 
 169  * library.  We also direct libjpeg error and warning 
 170  * messages through the appropriate libtiff handlers. 
 174  * Error handling routines (these replace corresponding 
 175  * IJG routines from jerror.c).  These are used for both 
 176  * compression and decompression. 
 179 TIFFjpeg_error_exit(j_common_ptr cinfo
) 
 181         JPEGState 
*sp 
= (JPEGState 
*) cinfo
;    /* NB: cinfo assumed first */ 
 182         char buffer
[JMSG_LENGTH_MAX
]; 
 184         (*cinfo
->err
->format_message
) (cinfo
, buffer
); 
 185         TIFFError("JPEGLib", buffer
);           /* display the error message */ 
 186         jpeg_abort(cinfo
);                      /* clean up libjpeg state */ 
 187         LONGJMP(sp
->exit_jmpbuf
, 1);            /* return to libtiff caller */ 
 191  * This routine is invoked only for warning messages, 
 192  * since error_exit does its own thing and trace_level 
 196 TIFFjpeg_output_message(j_common_ptr cinfo
) 
 198         char buffer
[JMSG_LENGTH_MAX
]; 
 200         (*cinfo
->err
->format_message
) (cinfo
, buffer
); 
 201         TIFFWarning("JPEGLib", buffer
); 
 205  * Interface routines.  This layer of routines exists 
 206  * primarily to limit side-effects from using setjmp. 
 207  * Also, normal/error returns are converted into return 
 208  * values per libtiff practice. 
 210 #define CALLJPEG(sp, fail, op)  (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op)) 
 211 #define CALLVJPEG(sp, op)       CALLJPEG(sp, 0, ((op),1)) 
 214 TIFFjpeg_create_compress(JPEGState
* sp
) 
 216         /* initialize JPEG error handling */ 
 217         sp
->cinfo
.c
.err 
= jpeg_std_error(&sp
->err
); 
 218         sp
->err
.error_exit 
= TIFFjpeg_error_exit
; 
 219         sp
->err
.output_message 
= TIFFjpeg_output_message
; 
 221         return CALLVJPEG(sp
, jpeg_create_compress(&sp
->cinfo
.c
)); 
 225 TIFFjpeg_create_decompress(JPEGState
* sp
) 
 227         /* initialize JPEG error handling */ 
 228         sp
->cinfo
.d
.err 
= jpeg_std_error(&sp
->err
); 
 229         sp
->err
.error_exit 
= TIFFjpeg_error_exit
; 
 230         sp
->err
.output_message 
= TIFFjpeg_output_message
; 
 232         return CALLVJPEG(sp
, jpeg_create_decompress(&sp
->cinfo
.d
)); 
 236 TIFFjpeg_set_defaults(JPEGState
* sp
) 
 238         return CALLVJPEG(sp
, jpeg_set_defaults(&sp
->cinfo
.c
)); 
 242 TIFFjpeg_set_colorspace(JPEGState
* sp
, J_COLOR_SPACE colorspace
) 
 244         return CALLVJPEG(sp
, jpeg_set_colorspace(&sp
->cinfo
.c
, colorspace
)); 
 248 TIFFjpeg_set_quality(JPEGState
* sp
, int quality
, wxjpeg_boolean force_baseline
) 
 251             jpeg_set_quality(&sp
->cinfo
.c
, quality
, force_baseline
)); 
 255 TIFFjpeg_suppress_tables(JPEGState
* sp
, wxjpeg_boolean suppress
) 
 257         return CALLVJPEG(sp
, jpeg_suppress_tables(&sp
->cinfo
.c
, suppress
)); 
 261 TIFFjpeg_start_compress(JPEGState
* sp
, wxjpeg_boolean write_all_tables
) 
 264             jpeg_start_compress(&sp
->cinfo
.c
, write_all_tables
)); 
 268 TIFFjpeg_write_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int num_lines
) 
 270         return CALLJPEG(sp
, -1, (int) jpeg_write_scanlines(&sp
->cinfo
.c
, 
 271             scanlines
, (JDIMENSION
) num_lines
)); 
 275 TIFFjpeg_write_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int num_lines
) 
 277         return CALLJPEG(sp
, -1, (int) jpeg_write_raw_data(&sp
->cinfo
.c
, 
 278             data
, (JDIMENSION
) num_lines
)); 
 282 TIFFjpeg_finish_compress(JPEGState
* sp
) 
 284         return CALLVJPEG(sp
, jpeg_finish_compress(&sp
->cinfo
.c
)); 
 288 TIFFjpeg_write_tables(JPEGState
* sp
) 
 290         return CALLVJPEG(sp
, jpeg_write_tables(&sp
->cinfo
.c
)); 
 294 TIFFjpeg_read_header(JPEGState
* sp
, wxjpeg_boolean require_image
) 
 296         return CALLJPEG(sp
, -1, jpeg_read_header(&sp
->cinfo
.d
, require_image
)); 
 300 TIFFjpeg_start_decompress(JPEGState
* sp
) 
 302         return CALLVJPEG(sp
, jpeg_start_decompress(&sp
->cinfo
.d
)); 
 306 TIFFjpeg_read_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int max_lines
) 
 308         return CALLJPEG(sp
, -1, (int) jpeg_read_scanlines(&sp
->cinfo
.d
, 
 309             scanlines
, (JDIMENSION
) max_lines
)); 
 313 TIFFjpeg_read_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int max_lines
) 
 315         return CALLJPEG(sp
, -1, (int) jpeg_read_raw_data(&sp
->cinfo
.d
, 
 316             data
, (JDIMENSION
) max_lines
)); 
 320 TIFFjpeg_finish_decompress(JPEGState
* sp
) 
 322         return CALLJPEG(sp
, -1, (int) jpeg_finish_decompress(&sp
->cinfo
.d
)); 
 326 TIFFjpeg_abort(JPEGState
* sp
) 
 328         return CALLVJPEG(sp
, jpeg_abort(&sp
->cinfo
.comm
)); 
 332 TIFFjpeg_destroy(JPEGState
* sp
) 
 334         return CALLVJPEG(sp
, jpeg_destroy(&sp
->cinfo
.comm
)); 
 338 TIFFjpeg_alloc_sarray(JPEGState
* sp
, int pool_id
, 
 339                       JDIMENSION samplesperrow
, JDIMENSION numrows
) 
 341         return CALLJPEG(sp
, (JSAMPARRAY
) NULL
, 
 342             (*sp
->cinfo
.comm
.mem
->alloc_sarray
) 
 343                 (&sp
->cinfo
.comm
, pool_id
, samplesperrow
, numrows
)); 
 347  * JPEG library destination data manager. 
 348  * These routines direct compressed data from libjpeg into the 
 349  * libtiff output buffer. 
 353 std_init_destination(j_compress_ptr cinfo
) 
 355         JPEGState
* sp 
= (JPEGState
*) cinfo
; 
 358         sp
->dest
.next_output_byte 
= (JOCTET
*) tif
->tif_rawdata
; 
 359         sp
->dest
.free_in_buffer 
= (size_t) tif
->tif_rawdatasize
; 
 362 static wxjpeg_boolean
 
 363 std_empty_output_buffer(j_compress_ptr cinfo
) 
 365         JPEGState
* sp 
= (JPEGState
*) cinfo
; 
 368         /* the entire buffer has been filled */ 
 369         tif
->tif_rawcc 
= tif
->tif_rawdatasize
; 
 371         sp
->dest
.next_output_byte 
= (JOCTET
*) tif
->tif_rawdata
; 
 372         sp
->dest
.free_in_buffer 
= (size_t) tif
->tif_rawdatasize
; 
 378 std_term_destination(j_compress_ptr cinfo
) 
 380         JPEGState
* sp 
= (JPEGState
*) cinfo
; 
 383         tif
->tif_rawcp 
= (tidata_t
) sp
->dest
.next_output_byte
; 
 385             tif
->tif_rawdatasize 
- (tsize_t
) sp
->dest
.free_in_buffer
; 
 386         /* NB: libtiff does the final buffer flush */ 
 390 TIFFjpeg_data_dest(JPEGState
* sp
, TIFF
* tif
) 
 393         sp
->cinfo
.c
.dest 
= &sp
->dest
; 
 394         sp
->dest
.init_destination 
= std_init_destination
; 
 395         sp
->dest
.empty_output_buffer 
= std_empty_output_buffer
; 
 396         sp
->dest
.term_destination 
= std_term_destination
; 
 400  * Alternate destination manager for outputting to JPEGTables field. 
 404 tables_init_destination(j_compress_ptr cinfo
) 
 406         JPEGState
* sp 
= (JPEGState
*) cinfo
; 
 408         /* while building, jpegtables_length is allocated buffer size */ 
 409         sp
->dest
.next_output_byte 
= (JOCTET
*) sp
->jpegtables
; 
 410         sp
->dest
.free_in_buffer 
= (size_t) sp
->jpegtables_length
; 
 413 static wxjpeg_boolean
 
 414 tables_empty_output_buffer(j_compress_ptr cinfo
) 
 416         JPEGState
* sp 
= (JPEGState
*) cinfo
; 
 419         /* the entire buffer has been filled; enlarge it by 1000 bytes */ 
 420         newbuf 
= _TIFFrealloc((tdata_t
) sp
->jpegtables
, 
 421                               (tsize_t
) (sp
->jpegtables_length 
+ 1000)); 
 423                 ERREXIT1(cinfo
, JERR_OUT_OF_MEMORY
, 100); 
 424         sp
->dest
.next_output_byte 
= (JOCTET
*) newbuf 
+ sp
->jpegtables_length
; 
 425         sp
->dest
.free_in_buffer 
= (size_t) 1000; 
 426         sp
->jpegtables 
= newbuf
; 
 427         sp
->jpegtables_length 
+= 1000; 
 432 tables_term_destination(j_compress_ptr cinfo
) 
 434         JPEGState
* sp 
= (JPEGState
*) cinfo
; 
 436         /* set tables length to number of bytes actually emitted */ 
 437         sp
->jpegtables_length 
-= sp
->dest
.free_in_buffer
; 
 441 TIFFjpeg_tables_dest(JPEGState
* sp
, TIFF
* tif
) 
 445          * Allocate a working buffer for building tables. 
 446          * Initial size is 1000 bytes, which is usually adequate. 
 449                 _TIFFfree(sp
->jpegtables
); 
 450         sp
->jpegtables_length 
= 1000; 
 451         sp
->jpegtables 
= (void*) _TIFFmalloc((tsize_t
) sp
->jpegtables_length
); 
 452         if (sp
->jpegtables 
== NULL
) { 
 453                 sp
->jpegtables_length 
= 0; 
 454                 TIFFError("TIFFjpeg_tables_dest", "No space for JPEGTables"); 
 457         sp
->cinfo
.c
.dest 
= &sp
->dest
; 
 458         sp
->dest
.init_destination 
= tables_init_destination
; 
 459         sp
->dest
.empty_output_buffer 
= tables_empty_output_buffer
; 
 460         sp
->dest
.term_destination 
= tables_term_destination
; 
 465  * JPEG library source data manager. 
 466  * These routines supply compressed data to libjpeg. 
 470 std_init_source(j_decompress_ptr cinfo
) 
 472         JPEGState
* sp 
= (JPEGState
*) cinfo
; 
 475         sp
->src
.next_input_byte 
= (const JOCTET
*) tif
->tif_rawdata
; 
 476         sp
->src
.bytes_in_buffer 
= (size_t) tif
->tif_rawcc
; 
 479 static wxjpeg_boolean
 
 480 std_fill_input_buffer(j_decompress_ptr cinfo
) 
 482         JPEGState
* sp 
= (JPEGState
* ) cinfo
; 
 483         static const JOCTET dummy_EOI
[2] = { 0xFF, JPEG_EOI 
}; 
 486          * Should never get here since entire strip/tile is 
 487          * read into memory before the decompressor is called, 
 488          * and thus was supplied by init_source. 
 490         WARNMS(cinfo
, JWRN_JPEG_EOF
); 
 491         /* insert a fake EOI marker */ 
 492         sp
->src
.next_input_byte 
= dummy_EOI
; 
 493         sp
->src
.bytes_in_buffer 
= 2; 
 498 std_skip_input_data(j_decompress_ptr cinfo
, long num_bytes
) 
 500         JPEGState
* sp 
= (JPEGState
*) cinfo
; 
 503                 if (num_bytes 
> (long) sp
->src
.bytes_in_buffer
) { 
 504                         /* oops, buffer overrun */ 
 505                         (void) std_fill_input_buffer(cinfo
); 
 507                         sp
->src
.next_input_byte 
+= (size_t) num_bytes
; 
 508                         sp
->src
.bytes_in_buffer 
-= (size_t) num_bytes
; 
 514 std_term_source(j_decompress_ptr cinfo
) 
 516         /* No work necessary here */ 
 517         /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */ 
 518         /* (if so, need empty tables_term_source!) */ 
 523 TIFFjpeg_data_src(JPEGState
* sp
, TIFF
* tif
) 
 526         sp
->cinfo
.d
.src 
= &sp
->src
; 
 527         sp
->src
.init_source 
= std_init_source
; 
 528         sp
->src
.fill_input_buffer 
= std_fill_input_buffer
; 
 529         sp
->src
.skip_input_data 
= std_skip_input_data
; 
 530         sp
->src
.resync_to_restart 
= jpeg_resync_to_restart
; 
 531         sp
->src
.term_source 
= std_term_source
; 
 532         sp
->src
.bytes_in_buffer 
= 0;            /* for safety */ 
 533         sp
->src
.next_input_byte 
= NULL
; 
 537  * Alternate source manager for reading from JPEGTables. 
 538  * We can share all the code except for the init routine. 
 542 tables_init_source(j_decompress_ptr cinfo
) 
 544         JPEGState
* sp 
= (JPEGState
*) cinfo
; 
 546         sp
->src
.next_input_byte 
= (const JOCTET
*) sp
->jpegtables
; 
 547         sp
->src
.bytes_in_buffer 
= (size_t) sp
->jpegtables_length
; 
 551 TIFFjpeg_tables_src(JPEGState
* sp
, TIFF
* tif
) 
 553         TIFFjpeg_data_src(sp
, tif
); 
 554         sp
->src
.init_source 
= tables_init_source
; 
 558  * Allocate downsampled-data buffers needed for downsampled I/O. 
 559  * We use values computed in jpeg_start_compress or jpeg_start_decompress. 
 560  * We use libjpeg's allocator so that buffers will be released automatically 
 561  * when done with strip/tile. 
 562  * This is also a handy place to compute samplesperclump, bytesperline. 
 565 alloc_downsampled_buffers(TIFF
* tif
, jpeg_component_info
* comp_info
, 
 568         JPEGState
* sp 
= JState(tif
); 
 570         jpeg_component_info
* compptr
; 
 572         int samples_per_clump 
= 0; 
 574         for (ci 
= 0, compptr 
= comp_info
; ci 
< num_components
; 
 576                 samples_per_clump 
+= compptr
->h_samp_factor 
* 
 577                         compptr
->v_samp_factor
; 
 578                 buf 
= TIFFjpeg_alloc_sarray(sp
, JPOOL_IMAGE
, 
 579                                 compptr
->width_in_blocks 
* DCTSIZE
, 
 580                                 (JDIMENSION
) (compptr
->v_samp_factor
*DCTSIZE
)); 
 583                 sp
->ds_buffer
[ci
] = buf
; 
 585         sp
->samplesperclump 
= samples_per_clump
; 
 595 JPEGSetupDecode(TIFF
* tif
) 
 597         JPEGState
* sp 
= JState(tif
); 
 598         TIFFDirectory 
*td 
= &tif
->tif_dir
; 
 600         JPEGInitializeLibJPEG( tif 
); 
 603         assert(sp
->cinfo
.comm
.is_decompressor
); 
 605         /* Read JPEGTables if it is present */ 
 606         if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
)) { 
 607                 TIFFjpeg_tables_src(sp
, tif
); 
 608                 if(TIFFjpeg_read_header(sp
,FALSE
) != JPEG_HEADER_TABLES_ONLY
) { 
 609                         TIFFError("JPEGSetupDecode", "Bogus JPEGTables field"); 
 614         /* Grab parameters that are same for all strips/tiles */ 
 615         sp
->photometric 
= td
->td_photometric
; 
 616         switch (sp
->photometric
) { 
 617         case PHOTOMETRIC_YCBCR
: 
 618                 sp
->h_sampling 
= td
->td_ycbcrsubsampling
[0]; 
 619                 sp
->v_sampling 
= td
->td_ycbcrsubsampling
[1]; 
 622                 /* TIFF 6.0 forbids subsampling of all other color spaces */ 
 628         /* Set up for reading normal data */ 
 629         TIFFjpeg_data_src(sp
, tif
); 
 630         tif
->tif_postdecode 
= _TIFFNoPostDecode
; /* override byte swapping */ 
 635  * Set up for decoding a strip or tile. 
 638 JPEGPreDecode(TIFF
* tif
, tsample_t s
) 
 640         JPEGState 
*sp 
= JState(tif
); 
 641         TIFFDirectory 
*td 
= &tif
->tif_dir
; 
 642         static const char module[] = "JPEGPreDecode"; 
 643         uint32 segment_width
, segment_height
; 
 644         int downsampled_output
; 
 648         assert(sp
->cinfo
.comm
.is_decompressor
); 
 650          * Reset decoder state from any previous strip/tile, 
 651          * in case application didn't read the whole strip. 
 653         if (!TIFFjpeg_abort(sp
)) 
 656          * Read the header for this strip/tile. 
 658         if (TIFFjpeg_read_header(sp
, TRUE
) != JPEG_HEADER_OK
) 
 661          * Check image parameters and set decompression parameters. 
 663         segment_width 
= td
->td_imagewidth
; 
 664         segment_height 
= td
->td_imagelength 
- tif
->tif_row
; 
 666                 segment_width 
= td
->td_tilewidth
; 
 667                 segment_height 
= td
->td_tilelength
; 
 668                 sp
->bytesperline 
= TIFFTileRowSize(tif
); 
 670                 if (segment_height 
> td
->td_rowsperstrip
) 
 671                         segment_height 
= td
->td_rowsperstrip
; 
 672                 sp
->bytesperline 
= TIFFScanlineSize(tif
); 
 674         if (td
->td_planarconfig 
== PLANARCONFIG_SEPARATE 
&& s 
> 0) { 
 676                  * For PC 2, scale down the expected strip/tile size 
 677                  * to match a downsampled component 
 679                 segment_width 
= TIFFhowmany(segment_width
, sp
->h_sampling
); 
 680                 segment_height 
= TIFFhowmany(segment_height
, sp
->v_sampling
); 
 682         if (sp
->cinfo
.d
.image_width 
!= segment_width 
|| 
 683             sp
->cinfo
.d
.image_height 
!= segment_height
) { 
 685                  "Improper JPEG strip/tile size, expected %dx%d, got %dx%d", 
 688                           sp
->cinfo
.d
.image_width
,  
 689                           sp
->cinfo
.d
.image_height
); 
 691         if (sp
->cinfo
.d
.num_components 
!= 
 692             (td
->td_planarconfig 
== PLANARCONFIG_CONTIG 
? 
 693              td
->td_samplesperpixel 
: 1)) { 
 694                 TIFFError(module, "Improper JPEG component count"); 
 697         if (sp
->cinfo
.d
.data_precision 
!= td
->td_bitspersample
) { 
 698                 TIFFError(module, "Improper JPEG data precision"); 
 701         if (td
->td_planarconfig 
== PLANARCONFIG_CONTIG
) { 
 702                 /* Component 0 should have expected sampling factors */ 
 703                 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor 
!= sp
->h_sampling 
|| 
 704                     sp
->cinfo
.d
.comp_info
[0].v_samp_factor 
!= sp
->v_sampling
) { 
 706                                     "Improper JPEG sampling factors %d,%d\n" 
 707                                     "Apparently should be %d,%d, " 
 708                                     "decompressor will try reading with " 
 710                                     sp
->cinfo
.d
.comp_info
[0].h_samp_factor
, 
 711                                     sp
->cinfo
.d
.comp_info
[0].v_samp_factor
, 
 714                                     sp
->cinfo
.d
.comp_info
[0].h_samp_factor
, 
 715                                     sp
->cinfo
.d
.comp_info
[0].v_samp_factor 
); 
 717                         sp
->h_sampling 
= (uint16
) 
 718                             sp
->cinfo
.d
.comp_info
[0].h_samp_factor
; 
 719                         sp
->v_sampling 
= (uint16
) 
 720                             sp
->cinfo
.d
.comp_info
[0].v_samp_factor
; 
 722                 /* Rest should have sampling factors 1,1 */ 
 723                 for (ci 
= 1; ci 
< sp
->cinfo
.d
.num_components
; ci
++) { 
 724                         if (sp
->cinfo
.d
.comp_info
[ci
].h_samp_factor 
!= 1 || 
 725                             sp
->cinfo
.d
.comp_info
[ci
].v_samp_factor 
!= 1) { 
 726                                 TIFFError(module, "Improper JPEG sampling factors"); 
 731                 /* PC 2's single component should have sampling factors 1,1 */ 
 732                 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor 
!= 1 || 
 733                     sp
->cinfo
.d
.comp_info
[0].v_samp_factor 
!= 1) { 
 734                         TIFFError(module, "Improper JPEG sampling factors"); 
 738         downsampled_output 
= FALSE
; 
 739         if (td
->td_planarconfig 
== PLANARCONFIG_CONTIG 
&& 
 740             sp
->photometric 
== PHOTOMETRIC_YCBCR 
&& 
 741             sp
->jpegcolormode 
== JPEGCOLORMODE_RGB
) { 
 742         /* Convert YCbCr to RGB */ 
 743                 sp
->cinfo
.d
.jpeg_color_space 
= JCS_YCbCr
; 
 744                 sp
->cinfo
.d
.out_color_space 
= JCS_RGB
; 
 746                         /* Suppress colorspace handling */ 
 747                 sp
->cinfo
.d
.jpeg_color_space 
= JCS_UNKNOWN
; 
 748                 sp
->cinfo
.d
.out_color_space 
= JCS_UNKNOWN
; 
 749                 if (td
->td_planarconfig 
== PLANARCONFIG_CONTIG 
&& 
 750                     (sp
->h_sampling 
!= 1 || sp
->v_sampling 
!= 1)) 
 751                         downsampled_output 
= TRUE
; 
 752                 /* XXX what about up-sampling? */ 
 754         if (downsampled_output
) { 
 755                 /* Need to use raw-data interface to libjpeg */ 
 756                 sp
->cinfo
.d
.raw_data_out 
= TRUE
; 
 757                 tif
->tif_decoderow 
= JPEGDecodeRaw
; 
 758                 tif
->tif_decodestrip 
= JPEGDecodeRaw
; 
 759                 tif
->tif_decodetile 
= JPEGDecodeRaw
; 
 761                 /* Use normal interface to libjpeg */ 
 762                 sp
->cinfo
.d
.raw_data_out 
= FALSE
; 
 763                 tif
->tif_decoderow 
= JPEGDecode
; 
 764                 tif
->tif_decodestrip 
= JPEGDecode
; 
 765                 tif
->tif_decodetile 
= JPEGDecode
; 
 767         /* Start JPEG decompressor */ 
 768         if (!TIFFjpeg_start_decompress(sp
)) 
 770         /* Allocate downsampled-data buffers if needed */ 
 771         if (downsampled_output
) { 
 772                 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.d
.comp_info
, 
 773                                                sp
->cinfo
.d
.num_components
)) 
 775                 sp
->scancount 
= DCTSIZE
;        /* mark buffer empty */ 
 781  * Decode a chunk of pixels. 
 782  * "Standard" case: returned data is not downsampled. 
 784 /*ARGSUSED*/ static int 
 785 JPEGDecode(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
) 
 787     JPEGState 
*sp 
= JState(tif
); 
 790     nrows 
= cc 
/ sp
->bytesperline
; 
 791     if (cc 
% sp
->bytesperline
) 
 792         TIFFWarning(tif
->tif_name
, "fractional scanline not read"); 
 794     if( nrows 
> (int) sp
->cinfo
.d
.image_height 
) 
 795         nrows 
= sp
->cinfo
.d
.image_height
; 
 797     /* data is expected to be read in multiples of a scanline */ 
 801             JSAMPROW bufptr 
= (JSAMPROW
)buf
; 
 803             if (TIFFjpeg_read_scanlines(sp
, &bufptr
, 1) != 1) 
 806             buf 
+= sp
->bytesperline
; 
 807             cc 
-= sp
->bytesperline
; 
 808         } while (--nrows 
> 0); 
 810     /* Close down the decompressor if we've finished the strip or tile. */ 
 811     return sp
->cinfo
.d
.output_scanline 
< sp
->cinfo
.d
.output_height
 
 812         || TIFFjpeg_finish_decompress(sp
); 
 816  * Decode a chunk of pixels. 
 817  * Returned data is downsampled per sampling factors. 
 819 /*ARGSUSED*/ static int 
 820 JPEGDecodeRaw(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
) 
 822         JPEGState 
*sp 
= JState(tif
); 
 825         /* data is expected to be read in multiples of a scanline */ 
 826         if ( (nrows 
= sp
->cinfo
.d
.image_height
) ) { 
 827                 /* Cb,Cr both have sampling factors 1, so this is correct */ 
 828                 JDIMENSION clumps_per_line 
= sp
->cinfo
.d
.comp_info
[1].downsampled_width
; 
 829                 int samples_per_clump 
= sp
->samplesperclump
; 
 832                         jpeg_component_info 
*compptr
; 
 835                         /* Reload downsampled-data buffer if needed */ 
 836                         if (sp
->scancount 
>= DCTSIZE
) { 
 837                                 int n 
= sp
->cinfo
.d
.max_v_samp_factor 
* DCTSIZE
; 
 839                                 if (TIFFjpeg_read_raw_data(sp
, sp
->ds_buffer
, n
) 
 845                          * Fastest way to unseparate data is to make one pass 
 846                          * over the scanline for each row of each component. 
 848                         clumpoffset 
= 0;        /* first sample in clump */ 
 849                         for (ci 
= 0, compptr 
= sp
->cinfo
.d
.comp_info
; 
 850                              ci 
< sp
->cinfo
.d
.num_components
; 
 852                             int hsamp 
= compptr
->h_samp_factor
; 
 853                             int vsamp 
= compptr
->v_samp_factor
; 
 856                             for (ypos 
= 0; ypos 
< vsamp
; ypos
++) { 
 857                                 JSAMPLE 
*inptr 
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp 
+ ypos
]; 
 858                                 JSAMPLE 
*outptr 
= (JSAMPLE
*)buf 
+ clumpoffset
; 
 862                                     /* fast path for at least Cb and Cr */ 
 863                                     for (nclump 
= clumps_per_line
; nclump
-- > 0; ) { 
 864                                         outptr
[0] = *inptr
++; 
 865                                         outptr 
+= samples_per_clump
; 
 871                                     for (nclump 
= clumps_per_line
; nclump
-- > 0; ) { 
 872                                         for (xpos 
= 0; xpos 
< hsamp
; xpos
++) 
 873                                             outptr
[xpos
] = *inptr
++; 
 874                                         outptr 
+= samples_per_clump
; 
 877                                 clumpoffset 
+= hsamp
; 
 882                         buf 
+= sp
->bytesperline
; 
 883                         cc 
-= sp
->bytesperline
; 
 884                 } while (--nrows 
> 0); 
 887         /* Close down the decompressor if done. */ 
 888         return sp
->cinfo
.d
.output_scanline 
< sp
->cinfo
.d
.output_height
 
 889             || TIFFjpeg_finish_decompress(sp
); 
 898 unsuppress_quant_table (JPEGState
* sp
, int tblno
) 
 902         if ((qtbl 
= sp
->cinfo
.c
.quant_tbl_ptrs
[tblno
]) != NULL
) 
 903                 qtbl
->sent_table 
= FALSE
; 
 907 unsuppress_huff_table (JPEGState
* sp
, int tblno
) 
 911         if ((htbl 
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[tblno
]) != NULL
) 
 912                 htbl
->sent_table 
= FALSE
; 
 913         if ((htbl 
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[tblno
]) != NULL
) 
 914                 htbl
->sent_table 
= FALSE
; 
 918 prepare_JPEGTables(TIFF
* tif
) 
 920         JPEGState
* sp 
= JState(tif
); 
 922         JPEGInitializeLibJPEG( tif 
); 
 924         /* Initialize quant tables for current quality setting */ 
 925         if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
)) 
 927         /* Mark only the tables we want for output */ 
 928         /* NB: chrominance tables are currently used only with YCbCr */ 
 929         if (!TIFFjpeg_suppress_tables(sp
, TRUE
)) 
 931         if (sp
->jpegtablesmode 
& JPEGTABLESMODE_QUANT
) { 
 932                 unsuppress_quant_table(sp
, 0); 
 933                 if (sp
->photometric 
== PHOTOMETRIC_YCBCR
) 
 934                         unsuppress_quant_table(sp
, 1); 
 936         if (sp
->jpegtablesmode 
& JPEGTABLESMODE_HUFF
) { 
 937                 unsuppress_huff_table(sp
, 0); 
 938                 if (sp
->photometric 
== PHOTOMETRIC_YCBCR
) 
 939                         unsuppress_huff_table(sp
, 1); 
 941         /* Direct libjpeg output into jpegtables */ 
 942         if (!TIFFjpeg_tables_dest(sp
, tif
)) 
 944         /* Emit tables-only datastream */ 
 945         if (!TIFFjpeg_write_tables(sp
)) 
 952 JPEGSetupEncode(TIFF
* tif
) 
 954         JPEGState
* sp 
= JState(tif
); 
 955         TIFFDirectory 
*td 
= &tif
->tif_dir
; 
 956         static const char module[] = "JPEGSetupEncode"; 
 958         JPEGInitializeLibJPEG( tif 
); 
 961         assert(!sp
->cinfo
.comm
.is_decompressor
); 
 964          * Initialize all JPEG parameters to default values. 
 965          * Note that jpeg_set_defaults needs legal values for 
 966          * in_color_space and input_components. 
 968         sp
->cinfo
.c
.in_color_space 
= JCS_UNKNOWN
; 
 969         sp
->cinfo
.c
.input_components 
= 1; 
 970         if (!TIFFjpeg_set_defaults(sp
)) 
 972         /* Set per-file parameters */ 
 973         sp
->photometric 
= td
->td_photometric
; 
 974         switch (sp
->photometric
) { 
 975         case PHOTOMETRIC_YCBCR
: 
 976                 sp
->h_sampling 
= td
->td_ycbcrsubsampling
[0]; 
 977                 sp
->v_sampling 
= td
->td_ycbcrsubsampling
[1]; 
 979                  * A ReferenceBlackWhite field *must* be present since the 
 980                  * default value is inappropriate for YCbCr.  Fill in the 
 981                  * proper value if application didn't set it. 
 983                 if (!TIFFFieldSet(tif
, FIELD_REFBLACKWHITE
)) { 
 985                         long top 
= 1L << td
->td_bitspersample
; 
 987                         refbw
[1] = (float)(top
-1L); 
 988                         refbw
[2] = (float)(top
>>1); 
 992                         TIFFSetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
, refbw
); 
 995         case PHOTOMETRIC_PALETTE
:               /* disallowed by Tech Note */ 
 996         case PHOTOMETRIC_MASK
: 
 998                           "PhotometricInterpretation %d not allowed for JPEG", 
 999                           (int) sp
->photometric
); 
1002                 /* TIFF 6.0 forbids subsampling of all other color spaces */ 
1008         /* Verify miscellaneous parameters */ 
1011          * This would need work if libtiff ever supports different 
1012          * depths for different components, or if libjpeg ever supports 
1013          * run-time selection of depth.  Neither is imminent. 
1015         if (td
->td_bitspersample 
!= BITS_IN_JSAMPLE
) { 
1016                 TIFFError(module, "BitsPerSample %d not allowed for JPEG", 
1017                           (int) td
->td_bitspersample
); 
1020         sp
->cinfo
.c
.data_precision 
= td
->td_bitspersample
; 
1022                 if ((td
->td_tilelength 
% (sp
->v_sampling 
* DCTSIZE
)) != 0) { 
1024                                   "JPEG tile height must be multiple of %d", 
1025                                   sp
->v_sampling 
* DCTSIZE
); 
1028                 if ((td
->td_tilewidth 
% (sp
->h_sampling 
* DCTSIZE
)) != 0) { 
1030                                   "JPEG tile width must be multiple of %d", 
1031                                   sp
->h_sampling 
* DCTSIZE
); 
1035                 if (td
->td_rowsperstrip 
< td
->td_imagelength 
&& 
1036                     (td
->td_rowsperstrip 
% (sp
->v_sampling 
* DCTSIZE
)) != 0) { 
1038                                   "RowsPerStrip must be multiple of %d for JPEG", 
1039                                   sp
->v_sampling 
* DCTSIZE
); 
1044         /* Create a JPEGTables field if appropriate */ 
1045         if (sp
->jpegtablesmode 
& (JPEGTABLESMODE_QUANT
|JPEGTABLESMODE_HUFF
)) { 
1046                 if (!prepare_JPEGTables(tif
)) 
1048                 /* Mark the field present */ 
1049                 /* Can't use TIFFSetField since BEENWRITING is already set! */ 
1050                 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
); 
1051                 tif
->tif_flags 
|= TIFF_DIRTYDIRECT
; 
1053                 /* We do not support application-supplied JPEGTables, */ 
1054                 /* so mark the field not present */ 
1055                 TIFFClrFieldBit(tif
, FIELD_JPEGTABLES
); 
1058         /* Direct libjpeg output to libtiff's output buffer */ 
1059         TIFFjpeg_data_dest(sp
, tif
); 
1065  * Set encoding state at the start of a strip or tile. 
1068 JPEGPreEncode(TIFF
* tif
, tsample_t s
) 
1070         JPEGState 
*sp 
= JState(tif
); 
1071         TIFFDirectory 
*td 
= &tif
->tif_dir
; 
1072         static const char module[] = "JPEGPreEncode"; 
1073         uint32 segment_width
, segment_height
; 
1074         int downsampled_input
; 
1077         assert(!sp
->cinfo
.comm
.is_decompressor
); 
1079          * Set encoding parameters for this strip/tile. 
1082                 segment_width 
= td
->td_tilewidth
; 
1083                 segment_height 
= td
->td_tilelength
; 
1084                 sp
->bytesperline 
= TIFFTileRowSize(tif
); 
1086                 segment_width 
= td
->td_imagewidth
; 
1087                 segment_height 
= td
->td_imagelength 
- tif
->tif_row
; 
1088                 if (segment_height 
> td
->td_rowsperstrip
) 
1089                         segment_height 
= td
->td_rowsperstrip
; 
1090                 sp
->bytesperline 
= TIFFScanlineSize(tif
); 
1092         if (td
->td_planarconfig 
== PLANARCONFIG_SEPARATE 
&& s 
> 0) { 
1093                 /* for PC 2, scale down the strip/tile size 
1094                  * to match a downsampled component 
1096                 segment_width 
= TIFFhowmany(segment_width
, sp
->h_sampling
); 
1097                 segment_height 
= TIFFhowmany(segment_height
, sp
->v_sampling
); 
1099         if (segment_width 
> 65535 || segment_height 
> 65535) { 
1100                 TIFFError(module, "Strip/tile too large for JPEG"); 
1103         sp
->cinfo
.c
.image_width 
= segment_width
; 
1104         sp
->cinfo
.c
.image_height 
= segment_height
; 
1105         downsampled_input 
= FALSE
; 
1106         if (td
->td_planarconfig 
== PLANARCONFIG_CONTIG
) { 
1107                 sp
->cinfo
.c
.input_components 
= td
->td_samplesperpixel
; 
1108                 if (sp
->photometric 
== PHOTOMETRIC_YCBCR
) { 
1109                         if (sp
->jpegcolormode 
== JPEGCOLORMODE_RGB
) { 
1110                                 sp
->cinfo
.c
.in_color_space 
= JCS_RGB
; 
1112                                 sp
->cinfo
.c
.in_color_space 
= JCS_YCbCr
; 
1113                                 if (sp
->h_sampling 
!= 1 || sp
->v_sampling 
!= 1) 
1114                                         downsampled_input 
= TRUE
; 
1116                         if (!TIFFjpeg_set_colorspace(sp
, JCS_YCbCr
)) 
1119                          * Set Y sampling factors; 
1120                          * we assume jpeg_set_colorspace() set the rest to 1 
1122                         sp
->cinfo
.c
.comp_info
[0].h_samp_factor 
= sp
->h_sampling
; 
1123                         sp
->cinfo
.c
.comp_info
[0].v_samp_factor 
= sp
->v_sampling
; 
1125                         sp
->cinfo
.c
.in_color_space 
= JCS_UNKNOWN
; 
1126                         if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
)) 
1128                         /* jpeg_set_colorspace set all sampling factors to 1 */ 
1131                 sp
->cinfo
.c
.input_components 
= 1; 
1132                 sp
->cinfo
.c
.in_color_space 
= JCS_UNKNOWN
; 
1133                 if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
)) 
1135                 sp
->cinfo
.c
.comp_info
[0].component_id 
= s
; 
1136                 /* jpeg_set_colorspace() set sampling factors to 1 */ 
1137                 if (sp
->photometric 
== PHOTOMETRIC_YCBCR 
&& s 
> 0) { 
1138                         sp
->cinfo
.c
.comp_info
[0].quant_tbl_no 
= 1; 
1139                         sp
->cinfo
.c
.comp_info
[0].dc_tbl_no 
= 1; 
1140                         sp
->cinfo
.c
.comp_info
[0].ac_tbl_no 
= 1; 
1143         /* ensure libjpeg won't write any extraneous markers */ 
1144         sp
->cinfo
.c
.write_JFIF_header 
= FALSE
; 
1145         sp
->cinfo
.c
.write_Adobe_marker 
= FALSE
; 
1146         /* set up table handling correctly */ 
1147         if (! (sp
->jpegtablesmode 
& JPEGTABLESMODE_QUANT
)) { 
1148                 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
)) 
1150                 unsuppress_quant_table(sp
, 0); 
1151                 unsuppress_quant_table(sp
, 1); 
1153         if (sp
->jpegtablesmode 
& JPEGTABLESMODE_HUFF
) 
1154                 sp
->cinfo
.c
.optimize_coding 
= FALSE
; 
1156                 sp
->cinfo
.c
.optimize_coding 
= TRUE
; 
1157         if (downsampled_input
) { 
1158                 /* Need to use raw-data interface to libjpeg */ 
1159                 sp
->cinfo
.c
.raw_data_in 
= TRUE
; 
1160                 tif
->tif_encoderow 
= JPEGEncodeRaw
; 
1161                 tif
->tif_encodestrip 
= JPEGEncodeRaw
; 
1162                 tif
->tif_encodetile 
= JPEGEncodeRaw
; 
1164                 /* Use normal interface to libjpeg */ 
1165                 sp
->cinfo
.c
.raw_data_in 
= FALSE
; 
1166                 tif
->tif_encoderow 
= JPEGEncode
; 
1167                 tif
->tif_encodestrip 
= JPEGEncode
; 
1168                 tif
->tif_encodetile 
= JPEGEncode
; 
1170         /* Start JPEG compressor */ 
1171         if (!TIFFjpeg_start_compress(sp
, FALSE
)) 
1173         /* Allocate downsampled-data buffers if needed */ 
1174         if (downsampled_input
) { 
1175                 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.c
.comp_info
, 
1176                                                sp
->cinfo
.c
.num_components
)) 
1185  * Encode a chunk of pixels. 
1186  * "Standard" case: incoming data is not downsampled. 
1189 JPEGEncode(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
) 
1191         JPEGState 
*sp 
= JState(tif
); 
1197         /* data is expected to be supplied in multiples of a scanline */ 
1198         nrows 
= cc 
/ sp
->bytesperline
; 
1199         if (cc 
% sp
->bytesperline
) 
1200                 TIFFWarning(tif
->tif_name
, "fractional scanline discarded"); 
1202         while (nrows
-- > 0) { 
1203                 bufptr
[0] = (JSAMPROW
) buf
; 
1204                 if (TIFFjpeg_write_scanlines(sp
, bufptr
, 1) != 1) 
1208                 buf 
+= sp
->bytesperline
; 
1214  * Encode a chunk of pixels. 
1215  * Incoming data is expected to be downsampled per sampling factors. 
1218 JPEGEncodeRaw(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
) 
1220         JPEGState 
*sp 
= JState(tif
); 
1224         JDIMENSION clumps_per_line
, nclump
; 
1225         int clumpoffset
, ci
, xpos
, ypos
; 
1226         jpeg_component_info
* compptr
; 
1227         int samples_per_clump 
= sp
->samplesperclump
; 
1231         /* data is expected to be supplied in multiples of a scanline */ 
1232         nrows 
= cc 
/ sp
->bytesperline
; 
1233         if (cc 
% sp
->bytesperline
) 
1234                 TIFFWarning(tif
->tif_name
, "fractional scanline discarded"); 
1236         /* Cb,Cr both have sampling factors 1, so this is correct */ 
1237         clumps_per_line 
= sp
->cinfo
.c
.comp_info
[1].downsampled_width
; 
1239         while (nrows
-- > 0) { 
1241                  * Fastest way to separate the data is to make one pass 
1242                  * over the scanline for each row of each component. 
1244                 clumpoffset 
= 0;                /* first sample in clump */ 
1245                 for (ci 
= 0, compptr 
= sp
->cinfo
.c
.comp_info
; 
1246                      ci 
< sp
->cinfo
.c
.num_components
; 
1248                     int hsamp 
= compptr
->h_samp_factor
; 
1249                     int vsamp 
= compptr
->v_samp_factor
; 
1250                     int padding 
= (int) (compptr
->width_in_blocks 
* DCTSIZE 
- 
1251                                          clumps_per_line 
* hsamp
); 
1252                     for (ypos 
= 0; ypos 
< vsamp
; ypos
++) { 
1253                         inptr 
= ((JSAMPLE
*) buf
) + clumpoffset
; 
1254                         outptr 
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp 
+ ypos
]; 
1256                             /* fast path for at least Cb and Cr */ 
1257                             for (nclump 
= clumps_per_line
; nclump
-- > 0; ) { 
1258                                 *outptr
++ = inptr
[0]; 
1259                                 inptr 
+= samples_per_clump
; 
1263                             for (nclump 
= clumps_per_line
; nclump
-- > 0; ) { 
1264                                 for (xpos 
= 0; xpos 
< hsamp
; xpos
++) 
1265                                     *outptr
++ = inptr
[xpos
]; 
1266                                 inptr 
+= samples_per_clump
; 
1269                         /* pad each scanline as needed */ 
1270                         for (xpos 
= 0; xpos 
< padding
; xpos
++) { 
1271                             *outptr 
= outptr
[-1]; 
1274                         clumpoffset 
+= hsamp
; 
1278                 if (sp
->scancount 
>= DCTSIZE
) { 
1279                         int n 
= sp
->cinfo
.c
.max_v_samp_factor 
* DCTSIZE
; 
1280                         if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
) 
1286                 buf 
+= sp
->bytesperline
; 
1292  * Finish up at the end of a strip or tile. 
1295 JPEGPostEncode(TIFF
* tif
) 
1297         JPEGState 
*sp 
= JState(tif
); 
1299         if (sp
->scancount 
> 0) { 
1301                  * Need to emit a partial bufferload of downsampled data. 
1302                  * Pad the data vertically. 
1305                 jpeg_component_info
* compptr
; 
1307                 for (ci 
= 0, compptr 
= sp
->cinfo
.c
.comp_info
; 
1308                      ci 
< sp
->cinfo
.c
.num_components
; 
1310                         int vsamp 
= compptr
->v_samp_factor
; 
1311                         tsize_t row_width 
= compptr
->width_in_blocks 
* DCTSIZE
 
1313                         for (ypos 
= sp
->scancount 
* vsamp
; 
1314                              ypos 
< DCTSIZE 
* vsamp
; ypos
++) { 
1315                                 _TIFFmemcpy((tdata_t
)sp
->ds_buffer
[ci
][ypos
], 
1316                                             (tdata_t
)sp
->ds_buffer
[ci
][ypos
-1], 
1321                 n 
= sp
->cinfo
.c
.max_v_samp_factor 
* DCTSIZE
; 
1322                 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
) 
1326         return (TIFFjpeg_finish_compress(JState(tif
))); 
1330 JPEGCleanup(TIFF
* tif
) 
1332         if (tif
->tif_data
) { 
1333                 JPEGState 
*sp 
= JState(tif
); 
1334                 if( sp
->cinfo_initialized 
) 
1335                     TIFFjpeg_destroy(sp
);       /* release libjpeg resources */ 
1336                 if (sp
->jpegtables
)             /* tag value */ 
1337                         _TIFFfree(sp
->jpegtables
); 
1338                 _TIFFfree(tif
->tif_data
);       /* release local state */ 
1339                 tif
->tif_data 
= NULL
; 
1344 JPEGVSetField(TIFF
* tif
, ttag_t tag
, va_list ap
) 
1346         JPEGState
* sp 
= JState(tif
); 
1347         TIFFDirectory
* td 
= &tif
->tif_dir
; 
1351         case TIFFTAG_JPEGTABLES
: 
1352                 v32 
= va_arg(ap
, uint32
); 
1357                 _TIFFsetByteArray(&sp
->jpegtables
, va_arg(ap
, void*), 
1359                 sp
->jpegtables_length 
= v32
; 
1360                 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
); 
1362         case TIFFTAG_JPEGQUALITY
: 
1363                 sp
->jpegquality 
= va_arg(ap
, int); 
1364                 return (1);                     /* pseudo tag */ 
1365         case TIFFTAG_JPEGCOLORMODE
: 
1366                 sp
->jpegcolormode 
= va_arg(ap
, int); 
1368                  * Mark whether returned data is up-sampled or not 
1369                  * so TIFFStripSize and TIFFTileSize return values 
1370                  * that reflect the true amount of data. 
1372                 tif
->tif_flags 
&= ~TIFF_UPSAMPLED
; 
1373                 if (td
->td_planarconfig 
== PLANARCONFIG_CONTIG
) { 
1374                     if (td
->td_photometric 
== PHOTOMETRIC_YCBCR 
&& 
1375                       sp
->jpegcolormode 
== JPEGCOLORMODE_RGB
) { 
1376                         tif
->tif_flags 
|= TIFF_UPSAMPLED
; 
1378                         if (td
->td_ycbcrsubsampling
[0] != 1 || 
1379                             td
->td_ycbcrsubsampling
[1] != 1) 
1380                             ; /* XXX what about up-sampling? */ 
1384                  * Must recalculate cached tile size 
1385                  * in case sampling state changed. 
1387                 tif
->tif_tilesize 
= TIFFTileSize(tif
); 
1388                 return (1);                     /* pseudo tag */ 
1389         case TIFFTAG_JPEGTABLESMODE
: 
1390                 sp
->jpegtablesmode 
= va_arg(ap
, int); 
1391                 return (1);                     /* pseudo tag */ 
1392         case TIFFTAG_YCBCRSUBSAMPLING
: 
1393                 /* mark the fact that we have a real ycbcrsubsampling! */ 
1394                 sp
->ycbcrsampling_fetched 
= 1; 
1395                 return (*sp
->vsetparent
)(tif
, tag
, ap
); 
1397                 return (*sp
->vsetparent
)(tif
, tag
, ap
); 
1399         tif
->tif_flags 
|= TIFF_DIRTYDIRECT
; 
1404  * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in 
1405  * the TIFF tags, but still use non-default (2,2) values within the jpeg 
1406  * data stream itself.  In order for TIFF applications to work properly 
1407  * - for instance to get the strip buffer size right - it is imperative 
1408  * that the subsampling be available before we start reading the image 
1409  * data normally.  This function will attempt to load the first strip in 
1410  * order to get the sampling values from the jpeg data stream.  Various 
1411  * hacks are various places are done to ensure this function gets called 
1412  * before the td_ycbcrsubsampling values are used from the directory structure, 
1413  * including calling TIFFGetField() for the YCBCRSUBSAMPLING field from  
1414  * TIFFStripSize(), and the printing code in tif_print.c.  
1416  * Note that JPEGPreDeocode() will produce a fairly loud warning when the 
1417  * discovered sampling does not match the default sampling (2,2) or whatever 
1418  * was actually in the tiff tags.  
1421  *  o This code will cause one whole strip/tile of compressed data to be 
1422  *    loaded just to get the tags right, even if the imagery is never read. 
1423  *    It would be more efficient to just load a bit of the header, and 
1424  *    initialize things from that.  
1426  * See the bug in bugzilla for details: 
1428  * http://bugzilla.remotesensing.org/show_bug.cgi?id=168 
1430  * Frank Warmerdam, July 2002 
1434 JPEGFixupTestSubsampling( TIFF 
* tif 
) 
1436 #if CHECK_JPEG_YCBCR_SUBSAMPLING == 1 
1437     JPEGState 
*sp 
= JState(tif
); 
1438     TIFFDirectory 
*td 
= &tif
->tif_dir
; 
1440     JPEGInitializeLibJPEG( tif 
); 
1443      * Some JPEG-in-TIFF files don't provide the ycbcrsampling tags,  
1444      * and use a sampling schema other than the default 2,2.  To handle 
1445      * this we actually have to scan the header of a strip or tile of 
1446      * jpeg data to get the sampling.   
1448     if( !sp
->cinfo
.comm
.is_decompressor 
 
1449         || sp
->ycbcrsampling_fetched  
 
1450         || td
->td_photometric 
!= PHOTOMETRIC_YCBCR 
) 
1453     sp
->ycbcrsampling_fetched 
= 1; 
1454     if( TIFFIsTiled( tif 
) ) 
1456         if( !TIFFFillTile( tif
, 0 ) ) 
1461         if( !TIFFFillStrip( tif
, 0 ) ) 
1465     TIFFSetField( tif
, TIFFTAG_YCBCRSUBSAMPLING
,  
1466                   (uint16
) sp
->h_sampling
, (uint16
) sp
->v_sampling 
); 
1467 #endif /* CHECK_JPEG_YCBCR_SUBSAMPLING == 1 */ 
1471 JPEGVGetField(TIFF
* tif
, ttag_t tag
, va_list ap
) 
1473         JPEGState
* sp 
= JState(tif
); 
1476         case TIFFTAG_JPEGTABLES
: 
1477                 /* u_short is bogus --- should be uint32 ??? */ 
1478                 /* TIFFWriteNormalTag needs fixed  XXX */ 
1479                 *va_arg(ap
, u_short
*) = (u_short
) sp
->jpegtables_length
; 
1480                 *va_arg(ap
, void**) = sp
->jpegtables
; 
1482         case TIFFTAG_JPEGQUALITY
: 
1483                 *va_arg(ap
, int*) = sp
->jpegquality
; 
1485         case TIFFTAG_JPEGCOLORMODE
: 
1486                 *va_arg(ap
, int*) = sp
->jpegcolormode
; 
1488         case TIFFTAG_JPEGTABLESMODE
: 
1489                 *va_arg(ap
, int*) = sp
->jpegtablesmode
; 
1491         case TIFFTAG_YCBCRSUBSAMPLING
: 
1492                 JPEGFixupTestSubsampling( tif 
); 
1493                 return (*sp
->vgetparent
)(tif
, tag
, ap
); 
1496                 return (*sp
->vgetparent
)(tif
, tag
, ap
); 
1502 JPEGPrintDir(TIFF
* tif
, FILE* fd
, long flags
) 
1504         JPEGState
* sp 
= JState(tif
); 
1507         if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
)) 
1508                 fprintf(fd
, "  JPEG Tables: (%lu bytes)\n", 
1509                         (u_long
) sp
->jpegtables_length
); 
1513 JPEGDefaultStripSize(TIFF
* tif
, uint32 s
) 
1515         JPEGState
* sp 
= JState(tif
); 
1516         TIFFDirectory 
*td 
= &tif
->tif_dir
; 
1518         s 
= (*sp
->defsparent
)(tif
, s
); 
1519         if (s 
< td
->td_imagelength
) 
1520                 s 
= TIFFroundup(s
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
); 
1525 JPEGDefaultTileSize(TIFF
* tif
, uint32
* tw
, uint32
* th
) 
1527         JPEGState
* sp 
= JState(tif
); 
1528         TIFFDirectory 
*td 
= &tif
->tif_dir
; 
1530         (*sp
->deftparent
)(tif
, tw
, th
); 
1531         *tw 
= TIFFroundup(*tw
, td
->td_ycbcrsubsampling
[0] * DCTSIZE
); 
1532         *th 
= TIFFroundup(*th
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
); 
1536  * The JPEG library initialized used to be done in TIFFInitJPEG(), but 
1537  * now that we allow a TIFF file to be opened in update mode it is necessary 
1538  * to have some way of deciding whether compression or decompression is 
1539  * desired other than looking at tif->tif_mode.  We accomplish this by  
1540  * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry. 
1541  * If so, we assume decompression is desired.  
1543  * This is tricky, because TIFFInitJPEG() is called while the directory is 
1544  * being read, and generally speaking the BYTECOUNTS tag won't have been read 
1545  * at that point.  So we try to defer jpeg library initialization till we 
1546  * do have that tag ... basically any access that might require the compressor 
1547  * or decompressor that occurs after the reading of the directory.  
1549  * In an ideal world compressors or decompressors would be setup 
1550  * at the point where a single tile or strip was accessed (for read or write) 
1551  * so that stuff like update of missing tiles, or replacement of tiles could 
1552  * be done. However, we aren't trying to crack that nut just yet ... 
1554  * NFW, Feb 3rd, 2003. 
1557 static int JPEGInitializeLibJPEG( TIFF 
* tif 
) 
1559     JPEGState
* sp 
= JState(tif
); 
1560     uint32 
*byte_counts 
= NULL
; 
1561     int     data_is_empty 
= TRUE
; 
1563     if( sp
->cinfo_initialized 
) 
1567      * Do we have tile data already?  Make sure we initialize the 
1568      * the state in decompressor mode if we have tile data, even if we 
1569      * are not in read-only file access mode.  
1571     if( TIFFIsTiled( tif 
)  
1572         && TIFFGetField( tif
, TIFFTAG_TILEBYTECOUNTS
, &byte_counts 
)  
1573         && byte_counts 
!= NULL 
) 
1575         data_is_empty 
= byte_counts
[0] == 0; 
1577     if( !TIFFIsTiled( tif 
)  
1578         && TIFFGetField( tif
, TIFFTAG_STRIPBYTECOUNTS
, &byte_counts
)  
1579         && byte_counts 
!= NULL 
) 
1581         data_is_empty 
= byte_counts
[0] == 0; 
1585      * Initialize libjpeg. 
1587     if (tif
->tif_mode 
== O_RDONLY 
|| !data_is_empty 
) { 
1588         if (!TIFFjpeg_create_decompress(sp
)) 
1592         if (!TIFFjpeg_create_compress(sp
)) 
1596     sp
->cinfo_initialized 
= TRUE
; 
1602 TIFFInitJPEG(TIFF
* tif
, int scheme
) 
1606         assert(scheme 
== COMPRESSION_JPEG
); 
1609          * Allocate state block so tag methods have storage to record values. 
1611         tif
->tif_data 
= (tidata_t
) _TIFFmalloc(sizeof (JPEGState
)); 
1613         if (tif
->tif_data 
== NULL
) { 
1614                 TIFFError("TIFFInitJPEG", "No space for JPEG state block"); 
1617         memset( tif
->tif_data
, 0, sizeof(JPEGState
)); 
1620         sp
->tif 
= tif
;                          /* back link */ 
1623          * Merge codec-specific tag information and 
1624          * override parent get/set field methods. 
1626         _TIFFMergeFieldInfo(tif
, jpegFieldInfo
, N(jpegFieldInfo
)); 
1627         sp
->vgetparent 
= tif
->tif_tagmethods
.vgetfield
; 
1628         tif
->tif_tagmethods
.vgetfield 
= JPEGVGetField
;  /* hook for codec tags */ 
1629         sp
->vsetparent 
= tif
->tif_tagmethods
.vsetfield
; 
1630         tif
->tif_tagmethods
.vsetfield 
= JPEGVSetField
;  /* hook for codec tags */ 
1631         tif
->tif_tagmethods
.printdir 
= JPEGPrintDir
;    /* hook for codec tags */ 
1633         /* Default values for codec-specific fields */ 
1634         sp
->jpegtables 
= NULL
; 
1635         sp
->jpegtables_length 
= 0; 
1636         sp
->jpegquality 
= 75;                   /* Default IJG quality */ 
1637         sp
->jpegcolormode 
= JPEGCOLORMODE_RAW
; 
1638         sp
->jpegtablesmode 
= JPEGTABLESMODE_QUANT 
| JPEGTABLESMODE_HUFF
; 
1640         sp
->ycbcrsampling_fetched 
= 0; 
1643          * Install codec methods. 
1645         tif
->tif_setupdecode 
= JPEGSetupDecode
; 
1646         tif
->tif_predecode 
= JPEGPreDecode
; 
1647         tif
->tif_decoderow 
= JPEGDecode
; 
1648         tif
->tif_decodestrip 
= JPEGDecode
; 
1649         tif
->tif_decodetile 
= JPEGDecode
; 
1650         tif
->tif_setupencode 
= JPEGSetupEncode
; 
1651         tif
->tif_preencode 
= JPEGPreEncode
; 
1652         tif
->tif_postencode 
= JPEGPostEncode
; 
1653         tif
->tif_encoderow 
= JPEGEncode
; 
1654         tif
->tif_encodestrip 
= JPEGEncode
; 
1655         tif
->tif_encodetile 
= JPEGEncode
; 
1656         tif
->tif_cleanup 
= JPEGCleanup
; 
1657         sp
->defsparent 
= tif
->tif_defstripsize
; 
1658         tif
->tif_defstripsize 
= JPEGDefaultStripSize
; 
1659         sp
->deftparent 
= tif
->tif_deftilesize
; 
1660         tif
->tif_deftilesize 
= JPEGDefaultTileSize
; 
1661         tif
->tif_flags 
|= TIFF_NOBITREV
;        /* no bit reversal, please */ 
1663         sp
->cinfo_initialized 
= FALSE
; 
1666          * Mark the TIFFTAG_YCBCRSAMPLES as present even if it is not 
1667          * see: JPEGFixupTestSubsampling(). 
1669         TIFFSetFieldBit( tif
, FIELD_YCBCRSUBSAMPLING 
); 
1673 #endif /* JPEG_SUPPORT */