1
/* $Header: /cvsroot/osrs/libtiff/libtiff/tif_jpeg.c,v 1.16 2003/12/20 13:47:28 dron Exp $ */
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
62
#if defined(__RPCNDR_H__)
64
#define boolean unsigned int
71
* On some machines it may be worthwhile to use _setjmp or sigsetjmp
72
* in place of plain setjmp. These macros will make it easier.
74
#define SETJMP(jbuf) setjmp(jbuf)
75
#define LONGJMP(jbuf,code) longjmp(jbuf,code)
76
#define JMP_BUF jmp_buf
78
typedef struct jpeg_destination_mgr jpeg_destination_mgr;
79
typedef struct jpeg_source_mgr jpeg_source_mgr;
80
typedef struct jpeg_error_mgr jpeg_error_mgr;
83
* State block for each open TIFF file using
84
* libjpeg to do JPEG compression/decompression.
86
* libjpeg's visible state is either a jpeg_compress_struct
87
* or jpeg_decompress_struct depending on which way we
88
* are going. comm can be used to refer to the fields
89
* which are common to both.
91
* NB: cinfo is required to be the first member of JPEGState,
92
* so we can safely cast JPEGState* -> jpeg_xxx_struct*
97
struct jpeg_compress_struct c;
98
struct jpeg_decompress_struct d;
99
struct jpeg_common_struct comm;
100
} cinfo; /* NB: must be first */
101
int cinfo_initialized;
103
jpeg_error_mgr err; /* libjpeg error manager */
104
JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
106
* The following two members could be a union, but
107
* they're small enough that it's not worth the effort.
109
jpeg_destination_mgr dest; /* data dest for compression */
110
jpeg_source_mgr src; /* data source for decompression */
112
TIFF* tif; /* back link needed by some code */
113
uint16 photometric; /* copy of PhotometricInterpretation */
114
uint16 h_sampling; /* luminance sampling factors */
116
tsize_t bytesperline; /* decompressed bytes per scanline */
117
/* pointers to intermediate buffers when processing downsampled data */
118
JSAMPARRAY ds_buffer[MAX_COMPONENTS];
119
int scancount; /* number of "scanlines" accumulated */
122
TIFFVGetMethod vgetparent; /* super-class method */
123
TIFFVSetMethod vsetparent; /* super-class method */
124
TIFFStripMethod defsparent; /* super-class method */
125
TIFFTileMethod deftparent; /* super-class method */
126
/* pseudo-tag fields */
127
void* jpegtables; /* JPEGTables tag value, or NULL */
128
uint32 jpegtables_length; /* number of bytes in same */
129
int jpegquality; /* Compression quality level */
130
int jpegcolormode; /* Auto RGB<=>YCbCr convert? */
131
int jpegtablesmode; /* What to put in JPEGTables */
133
int ycbcrsampling_fetched;
136
#define JState(tif) ((JPEGState*)(tif)->tif_data)
138
static int JPEGDecode(TIFF*, tidata_t, tsize_t, tsample_t);
139
static int JPEGDecodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
140
static int JPEGEncode(TIFF*, tidata_t, tsize_t, tsample_t);
141
static int JPEGEncodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
142
static int JPEGInitializeLibJPEG( TIFF * tif );
144
#define FIELD_JPEGTABLES (FIELD_CODEC+0)
146
static const TIFFFieldInfo jpegFieldInfo[] = {
147
{ TIFFTAG_JPEGTABLES, -1,-1, TIFF_UNDEFINED, FIELD_JPEGTABLES,
148
FALSE, TRUE, "JPEGTables" },
149
{ TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, FIELD_PSEUDO,
151
{ TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
153
{ TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
156
#define N(a) (sizeof (a) / sizeof (a[0]))
159
* libjpeg interface layer.
161
* We use setjmp/longjmp to return control to libtiff
162
* when a fatal error is encountered within the JPEG
163
* library. We also direct libjpeg error and warning
164
* messages through the appropriate libtiff handlers.
168
* Error handling routines (these replace corresponding
169
* IJG routines from jerror.c). These are used for both
170
* compression and decompression.
173
TIFFjpeg_error_exit(j_common_ptr cinfo)
175
JPEGState *sp = (JPEGState *) cinfo; /* NB: cinfo assumed first */
176
char buffer[JMSG_LENGTH_MAX];
178
(*cinfo->err->format_message) (cinfo, buffer);
179
TIFFError("JPEGLib", buffer); /* display the error message */
180
jpeg_abort(cinfo); /* clean up libjpeg state */
181
LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
185
* This routine is invoked only for warning messages,
186
* since error_exit does its own thing and trace_level
190
TIFFjpeg_output_message(j_common_ptr cinfo)
192
char buffer[JMSG_LENGTH_MAX];
194
(*cinfo->err->format_message) (cinfo, buffer);
195
TIFFWarning("JPEGLib", buffer);
199
* Interface routines. This layer of routines exists
200
* primarily to limit side-effects from using setjmp.
201
* Also, normal/error returns are converted into return
202
* values per libtiff practice.
204
#define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
205
#define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
208
TIFFjpeg_create_compress(JPEGState* sp)
210
/* initialize JPEG error handling */
211
sp->cinfo.c.err = jpeg_std_error(&sp->err);
212
sp->err.error_exit = TIFFjpeg_error_exit;
213
sp->err.output_message = TIFFjpeg_output_message;
215
return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
219
TIFFjpeg_create_decompress(JPEGState* sp)
221
/* initialize JPEG error handling */
222
sp->cinfo.d.err = jpeg_std_error(&sp->err);
223
sp->err.error_exit = TIFFjpeg_error_exit;
224
sp->err.output_message = TIFFjpeg_output_message;
226
return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
230
TIFFjpeg_set_defaults(JPEGState* sp)
232
return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
236
TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
238
return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
242
TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
245
jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
249
TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
251
return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
255
TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
258
jpeg_start_compress(&sp->cinfo.c, write_all_tables));
262
TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
264
return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
265
scanlines, (JDIMENSION) num_lines));
269
TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
271
return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
272
data, (JDIMENSION) num_lines));
276
TIFFjpeg_finish_compress(JPEGState* sp)
278
return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
282
TIFFjpeg_write_tables(JPEGState* sp)
284
return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
288
TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
290
return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
294
TIFFjpeg_start_decompress(JPEGState* sp)
296
return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
300
TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
302
return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
303
scanlines, (JDIMENSION) max_lines));
307
TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
309
return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
310
data, (JDIMENSION) max_lines));
314
TIFFjpeg_finish_decompress(JPEGState* sp)
316
return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
320
TIFFjpeg_abort(JPEGState* sp)
322
return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
326
TIFFjpeg_destroy(JPEGState* sp)
328
return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
332
TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
333
JDIMENSION samplesperrow, JDIMENSION numrows)
335
return CALLJPEG(sp, (JSAMPARRAY) NULL,
336
(*sp->cinfo.comm.mem->alloc_sarray)
337
(&sp->cinfo.comm, pool_id, samplesperrow, numrows));
341
* JPEG library destination data manager.
342
* These routines direct compressed data from libjpeg into the
343
* libtiff output buffer.
347
std_init_destination(j_compress_ptr cinfo)
349
JPEGState* sp = (JPEGState*) cinfo;
352
sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
353
sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
357
std_empty_output_buffer(j_compress_ptr cinfo)
359
JPEGState* sp = (JPEGState*) cinfo;
362
/* the entire buffer has been filled */
363
tif->tif_rawcc = tif->tif_rawdatasize;
365
sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
366
sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
372
std_term_destination(j_compress_ptr cinfo)
374
JPEGState* sp = (JPEGState*) cinfo;
377
tif->tif_rawcp = (tidata_t) sp->dest.next_output_byte;
379
tif->tif_rawdatasize - (tsize_t) sp->dest.free_in_buffer;
380
/* NB: libtiff does the final buffer flush */
384
TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
387
sp->cinfo.c.dest = &sp->dest;
388
sp->dest.init_destination = std_init_destination;
389
sp->dest.empty_output_buffer = std_empty_output_buffer;
390
sp->dest.term_destination = std_term_destination;
394
* Alternate destination manager for outputting to JPEGTables field.
398
tables_init_destination(j_compress_ptr cinfo)
400
JPEGState* sp = (JPEGState*) cinfo;
402
/* while building, jpegtables_length is allocated buffer size */
403
sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
404
sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
408
tables_empty_output_buffer(j_compress_ptr cinfo)
410
JPEGState* sp = (JPEGState*) cinfo;
413
/* the entire buffer has been filled; enlarge it by 1000 bytes */
414
newbuf = _TIFFrealloc((tdata_t) sp->jpegtables,
415
(tsize_t) (sp->jpegtables_length + 1000));
417
ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
418
sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
419
sp->dest.free_in_buffer = (size_t) 1000;
420
sp->jpegtables = newbuf;
421
sp->jpegtables_length += 1000;
426
tables_term_destination(j_compress_ptr cinfo)
428
JPEGState* sp = (JPEGState*) cinfo;
430
/* set tables length to number of bytes actually emitted */
431
sp->jpegtables_length -= sp->dest.free_in_buffer;
435
TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
439
* Allocate a working buffer for building tables.
440
* Initial size is 1000 bytes, which is usually adequate.
443
_TIFFfree(sp->jpegtables);
444
sp->jpegtables_length = 1000;
445
sp->jpegtables = (void*) _TIFFmalloc((tsize_t) sp->jpegtables_length);
446
if (sp->jpegtables == NULL) {
447
sp->jpegtables_length = 0;
448
TIFFError("TIFFjpeg_tables_dest", "No space for JPEGTables");
451
sp->cinfo.c.dest = &sp->dest;
452
sp->dest.init_destination = tables_init_destination;
453
sp->dest.empty_output_buffer = tables_empty_output_buffer;
454
sp->dest.term_destination = tables_term_destination;
459
* JPEG library source data manager.
460
* These routines supply compressed data to libjpeg.
464
std_init_source(j_decompress_ptr cinfo)
466
JPEGState* sp = (JPEGState*) cinfo;
469
sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
470
sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
474
std_fill_input_buffer(j_decompress_ptr cinfo)
476
JPEGState* sp = (JPEGState* ) cinfo;
477
static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
480
* Should never get here since entire strip/tile is
481
* read into memory before the decompressor is called,
482
* and thus was supplied by init_source.
484
WARNMS(cinfo, JWRN_JPEG_EOF);
485
/* insert a fake EOI marker */
486
sp->src.next_input_byte = dummy_EOI;
487
sp->src.bytes_in_buffer = 2;
492
std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
494
JPEGState* sp = (JPEGState*) cinfo;
497
if (num_bytes > (long) sp->src.bytes_in_buffer) {
498
/* oops, buffer overrun */
499
(void) std_fill_input_buffer(cinfo);
501
sp->src.next_input_byte += (size_t) num_bytes;
502
sp->src.bytes_in_buffer -= (size_t) num_bytes;
508
std_term_source(j_decompress_ptr cinfo)
510
/* No work necessary here */
511
/* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
512
/* (if so, need empty tables_term_source!) */
517
TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
520
sp->cinfo.d.src = &sp->src;
521
sp->src.init_source = std_init_source;
522
sp->src.fill_input_buffer = std_fill_input_buffer;
523
sp->src.skip_input_data = std_skip_input_data;
524
sp->src.resync_to_restart = jpeg_resync_to_restart;
525
sp->src.term_source = std_term_source;
526
sp->src.bytes_in_buffer = 0; /* for safety */
527
sp->src.next_input_byte = NULL;
531
* Alternate source manager for reading from JPEGTables.
532
* We can share all the code except for the init routine.
536
tables_init_source(j_decompress_ptr cinfo)
538
JPEGState* sp = (JPEGState*) cinfo;
540
sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
541
sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
545
TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
547
TIFFjpeg_data_src(sp, tif);
548
sp->src.init_source = tables_init_source;
552
* Allocate downsampled-data buffers needed for downsampled I/O.
553
* We use values computed in jpeg_start_compress or jpeg_start_decompress.
554
* We use libjpeg's allocator so that buffers will be released automatically
555
* when done with strip/tile.
556
* This is also a handy place to compute samplesperclump, bytesperline.
559
alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
562
JPEGState* sp = JState(tif);
564
jpeg_component_info* compptr;
566
int samples_per_clump = 0;
568
for (ci = 0, compptr = comp_info; ci < num_components;
570
samples_per_clump += compptr->h_samp_factor *
571
compptr->v_samp_factor;
572
buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
573
compptr->width_in_blocks * DCTSIZE,
574
(JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
577
sp->ds_buffer[ci] = buf;
579
sp->samplesperclump = samples_per_clump;
589
JPEGSetupDecode(TIFF* tif)
591
JPEGState* sp = JState(tif);
592
TIFFDirectory *td = &tif->tif_dir;
594
JPEGInitializeLibJPEG( tif );
597
assert(sp->cinfo.comm.is_decompressor);
599
/* Read JPEGTables if it is present */
600
if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
601
TIFFjpeg_tables_src(sp, tif);
602
if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
603
TIFFError("JPEGSetupDecode", "Bogus JPEGTables field");
608
/* Grab parameters that are same for all strips/tiles */
609
sp->photometric = td->td_photometric;
610
switch (sp->photometric) {
611
case PHOTOMETRIC_YCBCR:
612
sp->h_sampling = td->td_ycbcrsubsampling[0];
613
sp->v_sampling = td->td_ycbcrsubsampling[1];
616
/* TIFF 6.0 forbids subsampling of all other color spaces */
622
/* Set up for reading normal data */
623
TIFFjpeg_data_src(sp, tif);
624
tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
629
* Set up for decoding a strip or tile.
632
JPEGPreDecode(TIFF* tif, tsample_t s)
634
JPEGState *sp = JState(tif);
635
TIFFDirectory *td = &tif->tif_dir;
636
static const char module[] = "JPEGPreDecode";
637
uint32 segment_width, segment_height;
638
int downsampled_output;
642
assert(sp->cinfo.comm.is_decompressor);
644
* Reset decoder state from any previous strip/tile,
645
* in case application didn't read the whole strip.
647
if (!TIFFjpeg_abort(sp))
650
* Read the header for this strip/tile.
652
if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
655
* Check image parameters and set decompression parameters.
657
segment_width = td->td_imagewidth;
658
segment_height = td->td_imagelength - tif->tif_row;
660
segment_width = td->td_tilewidth;
661
segment_height = td->td_tilelength;
662
sp->bytesperline = TIFFTileRowSize(tif);
664
if (segment_height > td->td_rowsperstrip)
665
segment_height = td->td_rowsperstrip;
666
sp->bytesperline = TIFFScanlineSize(tif);
668
if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
670
* For PC 2, scale down the expected strip/tile size
671
* to match a downsampled component
673
segment_width = TIFFhowmany(segment_width, sp->h_sampling);
674
segment_height = TIFFhowmany(segment_height, sp->v_sampling);
676
if (sp->cinfo.d.image_width != segment_width ||
677
sp->cinfo.d.image_height != segment_height) {
679
"Improper JPEG strip/tile size, expected %dx%d, got %dx%d",
682
sp->cinfo.d.image_width,
683
sp->cinfo.d.image_height);
685
if (sp->cinfo.d.num_components !=
686
(td->td_planarconfig == PLANARCONFIG_CONTIG ?
687
td->td_samplesperpixel : 1)) {
688
TIFFError(module, "Improper JPEG component count");
691
if (sp->cinfo.d.data_precision != td->td_bitspersample) {
692
TIFFError(module, "Improper JPEG data precision");
695
if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
696
/* Component 0 should have expected sampling factors */
697
if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
698
sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
700
"Improper JPEG sampling factors %d,%d\n"
701
"Apparently should be %d,%d, "
702
"decompressor will try reading with "
704
sp->cinfo.d.comp_info[0].h_samp_factor,
705
sp->cinfo.d.comp_info[0].v_samp_factor,
708
sp->cinfo.d.comp_info[0].h_samp_factor,
709
sp->cinfo.d.comp_info[0].v_samp_factor );
711
sp->h_sampling = (uint16)
712
sp->cinfo.d.comp_info[0].h_samp_factor;
713
sp->v_sampling = (uint16)
714
sp->cinfo.d.comp_info[0].v_samp_factor;
716
/* Rest should have sampling factors 1,1 */
717
for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
718
if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
719
sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
720
TIFFError(module, "Improper JPEG sampling factors");
725
/* PC 2's single component should have sampling factors 1,1 */
726
if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
727
sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
728
TIFFError(module, "Improper JPEG sampling factors");
732
downsampled_output = FALSE;
733
if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
734
sp->photometric == PHOTOMETRIC_YCBCR &&
735
sp->jpegcolormode == JPEGCOLORMODE_RGB) {
736
/* Convert YCbCr to RGB */
737
sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
738
sp->cinfo.d.out_color_space = JCS_RGB;
740
/* Suppress colorspace handling */
741
sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
742
sp->cinfo.d.out_color_space = JCS_UNKNOWN;
743
if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
744
(sp->h_sampling != 1 || sp->v_sampling != 1))
745
downsampled_output = TRUE;
746
/* XXX what about up-sampling? */
748
if (downsampled_output) {
749
/* Need to use raw-data interface to libjpeg */
750
sp->cinfo.d.raw_data_out = TRUE;
751
tif->tif_decoderow = JPEGDecodeRaw;
752
tif->tif_decodestrip = JPEGDecodeRaw;
753
tif->tif_decodetile = JPEGDecodeRaw;
755
/* Use normal interface to libjpeg */
756
sp->cinfo.d.raw_data_out = FALSE;
757
tif->tif_decoderow = JPEGDecode;
758
tif->tif_decodestrip = JPEGDecode;
759
tif->tif_decodetile = JPEGDecode;
761
/* Start JPEG decompressor */
762
if (!TIFFjpeg_start_decompress(sp))
764
/* Allocate downsampled-data buffers if needed */
765
if (downsampled_output) {
766
if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
767
sp->cinfo.d.num_components))
769
sp->scancount = DCTSIZE; /* mark buffer empty */
775
* Decode a chunk of pixels.
776
* "Standard" case: returned data is not downsampled.
778
/*ARGSUSED*/ static int
779
JPEGDecode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
781
JPEGState *sp = JState(tif);
784
nrows = cc / sp->bytesperline;
785
if (cc % sp->bytesperline)
786
TIFFWarning(tif->tif_name, "fractional scanline not read");
788
if( nrows > (int) sp->cinfo.d.image_height )
789
nrows = sp->cinfo.d.image_height;
791
/* data is expected to be read in multiples of a scanline */
795
JSAMPROW bufptr = (JSAMPROW)buf;
797
if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
800
buf += sp->bytesperline;
801
cc -= sp->bytesperline;
802
} while (--nrows > 0);
804
/* Close down the decompressor if we've finished the strip or tile. */
805
return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
806
|| TIFFjpeg_finish_decompress(sp);
810
* Decode a chunk of pixels.
811
* Returned data is downsampled per sampling factors.
813
/*ARGSUSED*/ static int
814
JPEGDecodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
816
JPEGState *sp = JState(tif);
819
/* data is expected to be read in multiples of a scanline */
820
if ( (nrows = sp->cinfo.d.image_height) ) {
821
/* Cb,Cr both have sampling factors 1, so this is correct */
822
JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
823
int samples_per_clump = sp->samplesperclump;
826
jpeg_component_info *compptr;
829
/* Reload downsampled-data buffer if needed */
830
if (sp->scancount >= DCTSIZE) {
831
int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
833
if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n)
839
* Fastest way to unseparate data is to make one pass
840
* over the scanline for each row of each component.
842
clumpoffset = 0; /* first sample in clump */
843
for (ci = 0, compptr = sp->cinfo.d.comp_info;
844
ci < sp->cinfo.d.num_components;
846
int hsamp = compptr->h_samp_factor;
847
int vsamp = compptr->v_samp_factor;
850
for (ypos = 0; ypos < vsamp; ypos++) {
851
JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
852
JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
856
/* fast path for at least Cb and Cr */
857
for (nclump = clumps_per_line; nclump-- > 0; ) {
858
outptr[0] = *inptr++;
859
outptr += samples_per_clump;
865
for (nclump = clumps_per_line; nclump-- > 0; ) {
866
for (xpos = 0; xpos < hsamp; xpos++)
867
outptr[xpos] = *inptr++;
868
outptr += samples_per_clump;
871
clumpoffset += hsamp;
876
buf += sp->bytesperline;
877
cc -= sp->bytesperline;
878
} while (--nrows > 0);
881
/* Close down the decompressor if done. */
882
return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
883
|| TIFFjpeg_finish_decompress(sp);
892
unsuppress_quant_table (JPEGState* sp, int tblno)
896
if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
897
qtbl->sent_table = FALSE;
901
unsuppress_huff_table (JPEGState* sp, int tblno)
905
if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
906
htbl->sent_table = FALSE;
907
if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
908
htbl->sent_table = FALSE;
912
prepare_JPEGTables(TIFF* tif)
914
JPEGState* sp = JState(tif);
916
JPEGInitializeLibJPEG( tif );
918
/* Initialize quant tables for current quality setting */
919
if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
921
/* Mark only the tables we want for output */
922
/* NB: chrominance tables are currently used only with YCbCr */
923
if (!TIFFjpeg_suppress_tables(sp, TRUE))
925
if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
926
unsuppress_quant_table(sp, 0);
927
if (sp->photometric == PHOTOMETRIC_YCBCR)
928
unsuppress_quant_table(sp, 1);
930
if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
931
unsuppress_huff_table(sp, 0);
932
if (sp->photometric == PHOTOMETRIC_YCBCR)
933
unsuppress_huff_table(sp, 1);
935
/* Direct libjpeg output into jpegtables */
936
if (!TIFFjpeg_tables_dest(sp, tif))
938
/* Emit tables-only datastream */
939
if (!TIFFjpeg_write_tables(sp))
946
JPEGSetupEncode(TIFF* tif)
948
JPEGState* sp = JState(tif);
949
TIFFDirectory *td = &tif->tif_dir;
950
static const char module[] = "JPEGSetupEncode";
952
JPEGInitializeLibJPEG( tif );
955
assert(!sp->cinfo.comm.is_decompressor);
958
* Initialize all JPEG parameters to default values.
959
* Note that jpeg_set_defaults needs legal values for
960
* in_color_space and input_components.
962
sp->cinfo.c.in_color_space = JCS_UNKNOWN;
963
sp->cinfo.c.input_components = 1;
964
if (!TIFFjpeg_set_defaults(sp))
966
/* Set per-file parameters */
967
sp->photometric = td->td_photometric;
968
switch (sp->photometric) {
969
case PHOTOMETRIC_YCBCR:
970
sp->h_sampling = td->td_ycbcrsubsampling[0];
971
sp->v_sampling = td->td_ycbcrsubsampling[1];
973
* A ReferenceBlackWhite field *must* be present since the
974
* default value is inappropriate for YCbCr. Fill in the
975
* proper value if application didn't set it.
977
if (!TIFFFieldSet(tif, FIELD_REFBLACKWHITE)) {
979
long top = 1L << td->td_bitspersample;
981
refbw[1] = (float)(top-1L);
982
refbw[2] = (float)(top>>1);
986
TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE, refbw);
989
case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */
990
case PHOTOMETRIC_MASK:
992
"PhotometricInterpretation %d not allowed for JPEG",
993
(int) sp->photometric);
996
/* TIFF 6.0 forbids subsampling of all other color spaces */
1002
/* Verify miscellaneous parameters */
1005
* This would need work if libtiff ever supports different
1006
* depths for different components, or if libjpeg ever supports
1007
* run-time selection of depth. Neither is imminent.
1009
if (td->td_bitspersample != BITS_IN_JSAMPLE) {
1010
TIFFError(module, "BitsPerSample %d not allowed for JPEG",
1011
(int) td->td_bitspersample);
1014
sp->cinfo.c.data_precision = td->td_bitspersample;
1016
if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
1018
"JPEG tile height must be multiple of %d",
1019
sp->v_sampling * DCTSIZE);
1022
if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
1024
"JPEG tile width must be multiple of %d",
1025
sp->h_sampling * DCTSIZE);
1029
if (td->td_rowsperstrip < td->td_imagelength &&
1030
(td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
1032
"RowsPerStrip must be multiple of %d for JPEG",
1033
sp->v_sampling * DCTSIZE);
1038
/* Create a JPEGTables field if appropriate */
1039
if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
1040
if (!prepare_JPEGTables(tif))
1042
/* Mark the field present */
1043
/* Can't use TIFFSetField since BEENWRITING is already set! */
1044
TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1045
tif->tif_flags |= TIFF_DIRTYDIRECT;
1047
/* We do not support application-supplied JPEGTables, */
1048
/* so mark the field not present */
1049
TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
1052
/* Direct libjpeg output to libtiff's output buffer */
1053
TIFFjpeg_data_dest(sp, tif);
1059
* Set encoding state at the start of a strip or tile.
1062
JPEGPreEncode(TIFF* tif, tsample_t s)
1064
JPEGState *sp = JState(tif);
1065
TIFFDirectory *td = &tif->tif_dir;
1066
static const char module[] = "JPEGPreEncode";
1067
uint32 segment_width, segment_height;
1068
int downsampled_input;
1071
assert(!sp->cinfo.comm.is_decompressor);
1073
* Set encoding parameters for this strip/tile.
1076
segment_width = td->td_tilewidth;
1077
segment_height = td->td_tilelength;
1078
sp->bytesperline = TIFFTileRowSize(tif);
1080
segment_width = td->td_imagewidth;
1081
segment_height = td->td_imagelength - tif->tif_row;
1082
if (segment_height > td->td_rowsperstrip)
1083
segment_height = td->td_rowsperstrip;
1084
sp->bytesperline = TIFFScanlineSize(tif);
1086
if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1087
/* for PC 2, scale down the strip/tile size
1088
* to match a downsampled component
1090
segment_width = TIFFhowmany(segment_width, sp->h_sampling);
1091
segment_height = TIFFhowmany(segment_height, sp->v_sampling);
1093
if (segment_width > 65535 || segment_height > 65535) {
1094
TIFFError(module, "Strip/tile too large for JPEG");
1097
sp->cinfo.c.image_width = segment_width;
1098
sp->cinfo.c.image_height = segment_height;
1099
downsampled_input = FALSE;
1100
if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1101
sp->cinfo.c.input_components = td->td_samplesperpixel;
1102
if (sp->photometric == PHOTOMETRIC_YCBCR) {
1103
if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1104
sp->cinfo.c.in_color_space = JCS_RGB;
1106
sp->cinfo.c.in_color_space = JCS_YCbCr;
1107
if (sp->h_sampling != 1 || sp->v_sampling != 1)
1108
downsampled_input = TRUE;
1110
if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
1113
* Set Y sampling factors;
1114
* we assume jpeg_set_colorspace() set the rest to 1
1116
sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
1117
sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
1119
sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1120
if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1122
/* jpeg_set_colorspace set all sampling factors to 1 */
1125
sp->cinfo.c.input_components = 1;
1126
sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1127
if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1129
sp->cinfo.c.comp_info[0].component_id = s;
1130
/* jpeg_set_colorspace() set sampling factors to 1 */
1131
if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
1132
sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
1133
sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
1134
sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
1137
/* ensure libjpeg won't write any extraneous markers */
1138
sp->cinfo.c.write_JFIF_header = FALSE;
1139
sp->cinfo.c.write_Adobe_marker = FALSE;
1140
/* set up table handling correctly */
1141
if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
1142
if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1144
unsuppress_quant_table(sp, 0);
1145
unsuppress_quant_table(sp, 1);
1147
if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
1148
sp->cinfo.c.optimize_coding = FALSE;
1150
sp->cinfo.c.optimize_coding = TRUE;
1151
if (downsampled_input) {
1152
/* Need to use raw-data interface to libjpeg */
1153
sp->cinfo.c.raw_data_in = TRUE;
1154
tif->tif_encoderow = JPEGEncodeRaw;
1155
tif->tif_encodestrip = JPEGEncodeRaw;
1156
tif->tif_encodetile = JPEGEncodeRaw;
1158
/* Use normal interface to libjpeg */
1159
sp->cinfo.c.raw_data_in = FALSE;
1160
tif->tif_encoderow = JPEGEncode;
1161
tif->tif_encodestrip = JPEGEncode;
1162
tif->tif_encodetile = JPEGEncode;
1164
/* Start JPEG compressor */
1165
if (!TIFFjpeg_start_compress(sp, FALSE))
1167
/* Allocate downsampled-data buffers if needed */
1168
if (downsampled_input) {
1169
if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
1170
sp->cinfo.c.num_components))
1179
* Encode a chunk of pixels.
1180
* "Standard" case: incoming data is not downsampled.
1183
JPEGEncode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
1185
JPEGState *sp = JState(tif);
1191
/* data is expected to be supplied in multiples of a scanline */
1192
nrows = cc / sp->bytesperline;
1193
if (cc % sp->bytesperline)
1194
TIFFWarning(tif->tif_name, "fractional scanline discarded");
1196
while (nrows-- > 0) {
1197
bufptr[0] = (JSAMPROW) buf;
1198
if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
1202
buf += sp->bytesperline;
1208
* Encode a chunk of pixels.
1209
* Incoming data is expected to be downsampled per sampling factors.
1212
JPEGEncodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
1214
JPEGState *sp = JState(tif);
1218
JDIMENSION clumps_per_line, nclump;
1219
int clumpoffset, ci, xpos, ypos;
1220
jpeg_component_info* compptr;
1221
int samples_per_clump = sp->samplesperclump;
1225
/* data is expected to be supplied in multiples of a scanline */
1226
nrows = cc / sp->bytesperline;
1227
if (cc % sp->bytesperline)
1228
TIFFWarning(tif->tif_name, "fractional scanline discarded");
1230
/* Cb,Cr both have sampling factors 1, so this is correct */
1231
clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
1233
while (nrows-- > 0) {
1235
* Fastest way to separate the data is to make one pass
1236
* over the scanline for each row of each component.
1238
clumpoffset = 0; /* first sample in clump */
1239
for (ci = 0, compptr = sp->cinfo.c.comp_info;
1240
ci < sp->cinfo.c.num_components;
1242
int hsamp = compptr->h_samp_factor;
1243
int vsamp = compptr->v_samp_factor;
1244
int padding = (int) (compptr->width_in_blocks * DCTSIZE -
1245
clumps_per_line * hsamp);
1246
for (ypos = 0; ypos < vsamp; ypos++) {
1247
inptr = ((JSAMPLE*) buf) + clumpoffset;
1248
outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1250
/* fast path for at least Cb and Cr */
1251
for (nclump = clumps_per_line; nclump-- > 0; ) {
1252
*outptr++ = inptr[0];
1253
inptr += samples_per_clump;
1257
for (nclump = clumps_per_line; nclump-- > 0; ) {
1258
for (xpos = 0; xpos < hsamp; xpos++)
1259
*outptr++ = inptr[xpos];
1260
inptr += samples_per_clump;
1263
/* pad each scanline as needed */
1264
for (xpos = 0; xpos < padding; xpos++) {
1265
*outptr = outptr[-1];
1268
clumpoffset += hsamp;
1272
if (sp->scancount >= DCTSIZE) {
1273
int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1274
if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1280
buf += sp->bytesperline;
1286
* Finish up at the end of a strip or tile.
1289
JPEGPostEncode(TIFF* tif)
1291
JPEGState *sp = JState(tif);
1293
if (sp->scancount > 0) {
1295
* Need to emit a partial bufferload of downsampled data.
1296
* Pad the data vertically.
1299
jpeg_component_info* compptr;
1301
for (ci = 0, compptr = sp->cinfo.c.comp_info;
1302
ci < sp->cinfo.c.num_components;
1304
int vsamp = compptr->v_samp_factor;
1305
tsize_t row_width = compptr->width_in_blocks * DCTSIZE
1307
for (ypos = sp->scancount * vsamp;
1308
ypos < DCTSIZE * vsamp; ypos++) {
1309
_TIFFmemcpy((tdata_t)sp->ds_buffer[ci][ypos],
1310
(tdata_t)sp->ds_buffer[ci][ypos-1],
1315
n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1316
if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1320
return (TIFFjpeg_finish_compress(JState(tif)));
1324
JPEGCleanup(TIFF* tif)
1326
if (tif->tif_data) {
1327
JPEGState *sp = JState(tif);
1328
if( sp->cinfo_initialized )
1329
TIFFjpeg_destroy(sp); /* release libjpeg resources */
1330
if (sp->jpegtables) /* tag value */
1331
_TIFFfree(sp->jpegtables);
1332
_TIFFfree(tif->tif_data); /* release local state */
1333
tif->tif_data = NULL;
1338
JPEGVSetField(TIFF* tif, ttag_t tag, va_list ap)
1340
JPEGState* sp = JState(tif);
1341
TIFFDirectory* td = &tif->tif_dir;
1345
case TIFFTAG_JPEGTABLES:
1346
v32 = va_arg(ap, uint32);
1351
_TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
1353
sp->jpegtables_length = v32;
1354
TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1356
case TIFFTAG_JPEGQUALITY:
1357
sp->jpegquality = va_arg(ap, int);
1358
return (1); /* pseudo tag */
1359
case TIFFTAG_JPEGCOLORMODE:
1360
sp->jpegcolormode = va_arg(ap, int);
1362
* Mark whether returned data is up-sampled or not
1363
* so TIFFStripSize and TIFFTileSize return values
1364
* that reflect the true amount of data.
1366
tif->tif_flags &= ~TIFF_UPSAMPLED;
1367
if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1368
if (td->td_photometric == PHOTOMETRIC_YCBCR &&
1369
sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1370
tif->tif_flags |= TIFF_UPSAMPLED;
1372
if (td->td_ycbcrsubsampling[0] != 1 ||
1373
td->td_ycbcrsubsampling[1] != 1)
1374
; /* XXX what about up-sampling? */
1378
* Must recalculate cached tile size
1379
* in case sampling state changed.
1381
tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tsize_t) -1;
1382
return (1); /* pseudo tag */
1383
case TIFFTAG_JPEGTABLESMODE:
1384
sp->jpegtablesmode = va_arg(ap, int);
1385
return (1); /* pseudo tag */
1386
case TIFFTAG_YCBCRSUBSAMPLING:
1387
/* mark the fact that we have a real ycbcrsubsampling! */
1388
sp->ycbcrsampling_fetched = 1;
1389
return (*sp->vsetparent)(tif, tag, ap);
1391
return (*sp->vsetparent)(tif, tag, ap);
1393
tif->tif_flags |= TIFF_DIRTYDIRECT;
1398
* Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
1399
* the TIFF tags, but still use non-default (2,2) values within the jpeg
1400
* data stream itself. In order for TIFF applications to work properly
1401
* - for instance to get the strip buffer size right - it is imperative
1402
* that the subsampling be available before we start reading the image
1403
* data normally. This function will attempt to load the first strip in
1404
* order to get the sampling values from the jpeg data stream. Various
1405
* hacks are various places are done to ensure this function gets called
1406
* before the td_ycbcrsubsampling values are used from the directory structure,
1407
* including calling TIFFGetField() for the YCBCRSUBSAMPLING field from
1408
* TIFFStripSize(), and the printing code in tif_print.c.
1410
* Note that JPEGPreDeocode() will produce a fairly loud warning when the
1411
* discovered sampling does not match the default sampling (2,2) or whatever
1412
* was actually in the tiff tags.
1415
* o This code will cause one whole strip/tile of compressed data to be
1416
* loaded just to get the tags right, even if the imagery is never read.
1417
* It would be more efficient to just load a bit of the header, and
1418
* initialize things from that.
1420
* See the bug in bugzilla for details:
1422
* http://bugzilla.remotesensing.org/show_bug.cgi?id=168
1424
* Frank Warmerdam, July 2002
1428
JPEGFixupTestSubsampling( TIFF * tif )
1430
#if CHECK_JPEG_YCBCR_SUBSAMPLING == 1
1431
JPEGState *sp = JState(tif);
1432
TIFFDirectory *td = &tif->tif_dir;
1434
JPEGInitializeLibJPEG( tif );
1437
* Some JPEG-in-TIFF files don't provide the ycbcrsampling tags,
1438
* and use a sampling schema other than the default 2,2. To handle
1439
* this we actually have to scan the header of a strip or tile of
1440
* jpeg data to get the sampling.
1442
if( !sp->cinfo.comm.is_decompressor
1443
|| sp->ycbcrsampling_fetched
1444
|| td->td_photometric != PHOTOMETRIC_YCBCR )
1447
sp->ycbcrsampling_fetched = 1;
1448
if( TIFFIsTiled( tif ) )
1450
if( !TIFFFillTile( tif, 0 ) )
1455
if( !TIFFFillStrip( tif, 0 ) )
1459
TIFFSetField( tif, TIFFTAG_YCBCRSUBSAMPLING,
1460
(uint16) sp->h_sampling, (uint16) sp->v_sampling );
1461
#endif /* CHECK_JPEG_YCBCR_SUBSAMPLING == 1 */
1465
JPEGVGetField(TIFF* tif, ttag_t tag, va_list ap)
1467
JPEGState* sp = JState(tif);
1470
case TIFFTAG_JPEGTABLES:
1471
/* u_short is bogus --- should be uint32 ??? */
1472
/* TIFFWriteNormalTag needs fixed XXX */
1473
*va_arg(ap, u_short*) = (u_short) sp->jpegtables_length;
1474
*va_arg(ap, void**) = sp->jpegtables;
1476
case TIFFTAG_JPEGQUALITY:
1477
*va_arg(ap, int*) = sp->jpegquality;
1479
case TIFFTAG_JPEGCOLORMODE:
1480
*va_arg(ap, int*) = sp->jpegcolormode;
1482
case TIFFTAG_JPEGTABLESMODE:
1483
*va_arg(ap, int*) = sp->jpegtablesmode;
1485
case TIFFTAG_YCBCRSUBSAMPLING:
1486
JPEGFixupTestSubsampling( tif );
1487
return (*sp->vgetparent)(tif, tag, ap);
1490
return (*sp->vgetparent)(tif, tag, ap);
1496
JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
1498
JPEGState* sp = JState(tif);
1501
if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
1502
fprintf(fd, " JPEG Tables: (%lu bytes)\n",
1503
(u_long) sp->jpegtables_length);
1507
JPEGDefaultStripSize(TIFF* tif, uint32 s)
1509
JPEGState* sp = JState(tif);
1510
TIFFDirectory *td = &tif->tif_dir;
1512
s = (*sp->defsparent)(tif, s);
1513
if (s < td->td_imagelength)
1514
s = TIFFroundup(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
1519
JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
1521
JPEGState* sp = JState(tif);
1522
TIFFDirectory *td = &tif->tif_dir;
1524
(*sp->deftparent)(tif, tw, th);
1525
*tw = TIFFroundup(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
1526
*th = TIFFroundup(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
1530
* The JPEG library initialized used to be done in TIFFInitJPEG(), but
1531
* now that we allow a TIFF file to be opened in update mode it is necessary
1532
* to have some way of deciding whether compression or decompression is
1533
* desired other than looking at tif->tif_mode. We accomplish this by
1534
* examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
1535
* If so, we assume decompression is desired.
1537
* This is tricky, because TIFFInitJPEG() is called while the directory is
1538
* being read, and generally speaking the BYTECOUNTS tag won't have been read
1539
* at that point. So we try to defer jpeg library initialization till we
1540
* do have that tag ... basically any access that might require the compressor
1541
* or decompressor that occurs after the reading of the directory.
1543
* In an ideal world compressors or decompressors would be setup
1544
* at the point where a single tile or strip was accessed (for read or write)
1545
* so that stuff like update of missing tiles, or replacement of tiles could
1546
* be done. However, we aren't trying to crack that nut just yet ...
1548
* NFW, Feb 3rd, 2003.
1551
static int JPEGInitializeLibJPEG( TIFF * tif )
1553
JPEGState* sp = JState(tif);
1554
uint32 *byte_counts = NULL;
1555
int data_is_empty = TRUE;
1557
if( sp->cinfo_initialized )
1561
* Do we have tile data already? Make sure we initialize the
1562
* the state in decompressor mode if we have tile data, even if we
1563
* are not in read-only file access mode.
1565
if( TIFFIsTiled( tif )
1566
&& TIFFGetField( tif, TIFFTAG_TILEBYTECOUNTS, &byte_counts )
1567
&& byte_counts != NULL )
1569
data_is_empty = byte_counts[0] == 0;
1571
if( !TIFFIsTiled( tif )
1572
&& TIFFGetField( tif, TIFFTAG_STRIPBYTECOUNTS, &byte_counts)
1573
&& byte_counts != NULL )
1575
data_is_empty = byte_counts[0] == 0;
1579
* Initialize libjpeg.
1581
if (tif->tif_mode == O_RDONLY || !data_is_empty ) {
1582
if (!TIFFjpeg_create_decompress(sp))
1586
if (!TIFFjpeg_create_compress(sp))
1590
sp->cinfo_initialized = TRUE;
1596
TIFFInitJPEG(TIFF* tif, int scheme)
1600
assert(scheme == COMPRESSION_JPEG);
1603
* Allocate state block so tag methods have storage to record values.
1605
tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (JPEGState));
1607
if (tif->tif_data == NULL) {
1608
TIFFError("TIFFInitJPEG", "No space for JPEG state block");
1611
memset( tif->tif_data, 0, sizeof(JPEGState));
1614
sp->tif = tif; /* back link */
1617
* Merge codec-specific tag information and
1618
* override parent get/set field methods.
1620
_TIFFMergeFieldInfo(tif, jpegFieldInfo, N(jpegFieldInfo));
1621
sp->vgetparent = tif->tif_tagmethods.vgetfield;
1622
tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
1623
sp->vsetparent = tif->tif_tagmethods.vsetfield;
1624
tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
1625
tif->tif_tagmethods.printdir = JPEGPrintDir; /* hook for codec tags */
1627
/* Default values for codec-specific fields */
1628
sp->jpegtables = NULL;
1629
sp->jpegtables_length = 0;
1630
sp->jpegquality = 75; /* Default IJG quality */
1631
sp->jpegcolormode = JPEGCOLORMODE_RAW;
1632
sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
1634
sp->ycbcrsampling_fetched = 0;
1637
* Install codec methods.
1639
tif->tif_setupdecode = JPEGSetupDecode;
1640
tif->tif_predecode = JPEGPreDecode;
1641
tif->tif_decoderow = JPEGDecode;
1642
tif->tif_decodestrip = JPEGDecode;
1643
tif->tif_decodetile = JPEGDecode;
1644
tif->tif_setupencode = JPEGSetupEncode;
1645
tif->tif_preencode = JPEGPreEncode;
1646
tif->tif_postencode = JPEGPostEncode;
1647
tif->tif_encoderow = JPEGEncode;
1648
tif->tif_encodestrip = JPEGEncode;
1649
tif->tif_encodetile = JPEGEncode;
1650
tif->tif_cleanup = JPEGCleanup;
1651
sp->defsparent = tif->tif_defstripsize;
1652
tif->tif_defstripsize = JPEGDefaultStripSize;
1653
sp->deftparent = tif->tif_deftilesize;
1654
tif->tif_deftilesize = JPEGDefaultTileSize;
1655
tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
1657
sp->cinfo_initialized = FALSE;
1660
* Mark the TIFFTAG_YCBCRSAMPLES as present even if it is not
1661
* see: JPEGFixupTestSubsampling().
1663
TIFFSetFieldBit( tif, FIELD_YCBCRSUBSAMPLING );
1667
#endif /* JPEG_SUPPORT */