1
/* $Id: tif_jpeg.c,v 1.50.2.9 2010-06-14 02:47:16 fwarmerdam 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
27
#define WIN32_LEAN_AND_MEAN
36
* JPEG Compression support per TIFF Technical Note #2
37
* (*not* per the original TIFF 6.0 spec).
39
* This file is simply an interface to the libjpeg library written by
40
* the Independent JPEG Group. You need release 5 or later of the IJG
41
* code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
43
* Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
47
int TIFFFillStrip(TIFF*, tstrip_t);
48
int TIFFFillTile(TIFF*, ttile_t);
50
/* We undefine FAR to avoid conflict with JPEG definition */
57
Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
58
not defined. Unfortunately, the MinGW and Borland compilers include
59
a typedef for INT32, which causes a conflict. MSVC does not include
60
a conficting typedef given the headers which are included.
62
#if defined(__BORLANDC__) || defined(__MINGW32__)
67
The windows RPCNDR.H file defines boolean, but defines it with the
68
unsigned char size. You should compile JPEG library using appropriate
69
definitions in jconfig.h header, but many users compile library in wrong
70
way. That causes errors of the following type:
72
"JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
75
For such users we wil fix the problem here. See install.doc file from
76
the JPEG library distribution for details.
79
/* Define "boolean" as unsigned char, not int, per Windows custom. */
80
#if defined(WIN32) && !defined(__MINGW32__)
81
# ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
82
typedef unsigned char boolean;
84
# define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
91
* We are using width_in_blocks which is supposed to be private to
92
* libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
93
* renamed this member to width_in_data_units. Since the header has
94
* also renamed a define, use that unique define name in order to
95
* detect the problem header and adjust to suit.
97
#if defined(D_MAX_DATA_UNITS_IN_MCU)
98
#define width_in_blocks width_in_data_units
102
* On some machines it may be worthwhile to use _setjmp or sigsetjmp
103
* in place of plain setjmp. These macros will make it easier.
105
#define SETJMP(jbuf) setjmp(jbuf)
106
#define LONGJMP(jbuf,code) longjmp(jbuf,code)
107
#define JMP_BUF jmp_buf
109
typedef struct jpeg_destination_mgr jpeg_destination_mgr;
110
typedef struct jpeg_source_mgr jpeg_source_mgr;
111
typedef struct jpeg_error_mgr jpeg_error_mgr;
114
* State block for each open TIFF file using
115
* libjpeg to do JPEG compression/decompression.
117
* libjpeg's visible state is either a jpeg_compress_struct
118
* or jpeg_decompress_struct depending on which way we
119
* are going. comm can be used to refer to the fields
120
* which are common to both.
122
* NB: cinfo is required to be the first member of JPEGState,
123
* so we can safely cast JPEGState* -> jpeg_xxx_struct*
128
struct jpeg_compress_struct c;
129
struct jpeg_decompress_struct d;
130
struct jpeg_common_struct comm;
131
} cinfo; /* NB: must be first */
132
int cinfo_initialized;
134
jpeg_error_mgr err; /* libjpeg error manager */
135
JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
137
* The following two members could be a union, but
138
* they're small enough that it's not worth the effort.
140
jpeg_destination_mgr dest; /* data dest for compression */
141
jpeg_source_mgr src; /* data source for decompression */
143
TIFF* tif; /* back link needed by some code */
144
uint16 photometric; /* copy of PhotometricInterpretation */
145
uint16 h_sampling; /* luminance sampling factors */
147
tsize_t bytesperline; /* decompressed bytes per scanline */
148
/* pointers to intermediate buffers when processing downsampled data */
149
JSAMPARRAY ds_buffer[MAX_COMPONENTS];
150
int scancount; /* number of "scanlines" accumulated */
153
TIFFVGetMethod vgetparent; /* super-class method */
154
TIFFVSetMethod vsetparent; /* super-class method */
155
TIFFPrintMethod printdir; /* super-class method */
156
TIFFStripMethod defsparent; /* super-class method */
157
TIFFTileMethod deftparent; /* super-class method */
158
/* pseudo-tag fields */
159
void* jpegtables; /* JPEGTables tag value, or NULL */
160
uint32 jpegtables_length; /* number of bytes in same */
161
int jpegquality; /* Compression quality level */
162
int jpegcolormode; /* Auto RGB<=>YCbCr convert? */
163
int jpegtablesmode; /* What to put in JPEGTables */
165
int ycbcrsampling_fetched;
166
uint32 recvparams; /* encoded Class 2 session params */
167
char* subaddress; /* subaddress string */
168
uint32 recvtime; /* time spent receiving (secs) */
169
char* faxdcs; /* encoded fax parameters (DCS, Table 2/T.30) */
172
#define JState(tif) ((JPEGState*)(tif)->tif_data)
174
static int JPEGDecode(TIFF*, tidata_t, tsize_t, tsample_t);
175
static int JPEGDecodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
176
static int JPEGEncode(TIFF*, tidata_t, tsize_t, tsample_t);
177
static int JPEGEncodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
178
static int JPEGInitializeLibJPEG( TIFF * tif,
179
int force_encode, int force_decode );
181
#define FIELD_JPEGTABLES (FIELD_CODEC+0)
182
#define FIELD_RECVPARAMS (FIELD_CODEC+1)
183
#define FIELD_SUBADDRESS (FIELD_CODEC+2)
184
#define FIELD_RECVTIME (FIELD_CODEC+3)
185
#define FIELD_FAXDCS (FIELD_CODEC+4)
187
static const TIFFFieldInfo jpegFieldInfo[] = {
188
{ TIFFTAG_JPEGTABLES, -3,-3, TIFF_UNDEFINED, FIELD_JPEGTABLES,
189
FALSE, TRUE, "JPEGTables" },
190
{ TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, FIELD_PSEUDO,
192
{ TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
194
{ TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
196
/* Specific for JPEG in faxes */
197
{ TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, FIELD_RECVPARAMS,
198
TRUE, FALSE, "FaxRecvParams" },
199
{ TIFFTAG_FAXSUBADDRESS, -1,-1, TIFF_ASCII, FIELD_SUBADDRESS,
200
TRUE, FALSE, "FaxSubAddress" },
201
{ TIFFTAG_FAXRECVTIME, 1, 1, TIFF_LONG, FIELD_RECVTIME,
202
TRUE, FALSE, "FaxRecvTime" },
203
{ TIFFTAG_FAXDCS, -1, -1, TIFF_ASCII, FIELD_FAXDCS,
204
TRUE, FALSE, "FaxDcs" },
206
#define N(a) (sizeof (a) / sizeof (a[0]))
209
* libjpeg interface layer.
211
* We use setjmp/longjmp to return control to libtiff
212
* when a fatal error is encountered within the JPEG
213
* library. We also direct libjpeg error and warning
214
* messages through the appropriate libtiff handlers.
218
* Error handling routines (these replace corresponding
219
* IJG routines from jerror.c). These are used for both
220
* compression and decompression.
223
TIFFjpeg_error_exit(j_common_ptr cinfo)
225
JPEGState *sp = (JPEGState *) cinfo; /* NB: cinfo assumed first */
226
char buffer[JMSG_LENGTH_MAX];
228
(*cinfo->err->format_message) (cinfo, buffer);
229
TIFFErrorExt(sp->tif->tif_clientdata, "JPEGLib", "%s", buffer); /* display the error message */
230
jpeg_abort(cinfo); /* clean up libjpeg state */
231
LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
235
* This routine is invoked only for warning messages,
236
* since error_exit does its own thing and trace_level
240
TIFFjpeg_output_message(j_common_ptr cinfo)
242
char buffer[JMSG_LENGTH_MAX];
244
(*cinfo->err->format_message) (cinfo, buffer);
245
TIFFWarningExt(((JPEGState *) cinfo)->tif->tif_clientdata, "JPEGLib", "%s", buffer);
249
* Interface routines. This layer of routines exists
250
* primarily to limit side-effects from using setjmp.
251
* Also, normal/error returns are converted into return
252
* values per libtiff practice.
254
#define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
255
#define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
258
TIFFjpeg_create_compress(JPEGState* sp)
260
/* initialize JPEG error handling */
261
sp->cinfo.c.err = jpeg_std_error(&sp->err);
262
sp->err.error_exit = TIFFjpeg_error_exit;
263
sp->err.output_message = TIFFjpeg_output_message;
265
return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
269
TIFFjpeg_create_decompress(JPEGState* sp)
271
/* initialize JPEG error handling */
272
sp->cinfo.d.err = jpeg_std_error(&sp->err);
273
sp->err.error_exit = TIFFjpeg_error_exit;
274
sp->err.output_message = TIFFjpeg_output_message;
276
return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
280
TIFFjpeg_set_defaults(JPEGState* sp)
282
return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
286
TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
288
return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
292
TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
295
jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
299
TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
301
return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
305
TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
308
jpeg_start_compress(&sp->cinfo.c, write_all_tables));
312
TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
314
return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
315
scanlines, (JDIMENSION) num_lines));
319
TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
321
return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
322
data, (JDIMENSION) num_lines));
326
TIFFjpeg_finish_compress(JPEGState* sp)
328
return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
332
TIFFjpeg_write_tables(JPEGState* sp)
334
return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
338
TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
340
return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
344
TIFFjpeg_start_decompress(JPEGState* sp)
346
return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
350
TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
352
return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
353
scanlines, (JDIMENSION) max_lines));
357
TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
359
return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
360
data, (JDIMENSION) max_lines));
364
TIFFjpeg_finish_decompress(JPEGState* sp)
366
return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
370
TIFFjpeg_abort(JPEGState* sp)
372
return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
376
TIFFjpeg_destroy(JPEGState* sp)
378
return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
382
TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
383
JDIMENSION samplesperrow, JDIMENSION numrows)
385
return CALLJPEG(sp, (JSAMPARRAY) NULL,
386
(*sp->cinfo.comm.mem->alloc_sarray)
387
(&sp->cinfo.comm, pool_id, samplesperrow, numrows));
391
* JPEG library destination data manager.
392
* These routines direct compressed data from libjpeg into the
393
* libtiff output buffer.
397
std_init_destination(j_compress_ptr cinfo)
399
JPEGState* sp = (JPEGState*) cinfo;
402
sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
403
sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
407
std_empty_output_buffer(j_compress_ptr cinfo)
409
JPEGState* sp = (JPEGState*) cinfo;
412
/* the entire buffer has been filled */
413
tif->tif_rawcc = tif->tif_rawdatasize;
415
sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
416
sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
422
std_term_destination(j_compress_ptr cinfo)
424
JPEGState* sp = (JPEGState*) cinfo;
427
tif->tif_rawcp = (tidata_t) sp->dest.next_output_byte;
429
tif->tif_rawdatasize - (tsize_t) sp->dest.free_in_buffer;
430
/* NB: libtiff does the final buffer flush */
434
TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
437
sp->cinfo.c.dest = &sp->dest;
438
sp->dest.init_destination = std_init_destination;
439
sp->dest.empty_output_buffer = std_empty_output_buffer;
440
sp->dest.term_destination = std_term_destination;
444
* Alternate destination manager for outputting to JPEGTables field.
448
tables_init_destination(j_compress_ptr cinfo)
450
JPEGState* sp = (JPEGState*) cinfo;
452
/* while building, jpegtables_length is allocated buffer size */
453
sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
454
sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
458
tables_empty_output_buffer(j_compress_ptr cinfo)
460
JPEGState* sp = (JPEGState*) cinfo;
463
/* the entire buffer has been filled; enlarge it by 1000 bytes */
464
newbuf = _TIFFrealloc((tdata_t) sp->jpegtables,
465
(tsize_t) (sp->jpegtables_length + 1000));
467
ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
468
sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
469
sp->dest.free_in_buffer = (size_t) 1000;
470
sp->jpegtables = newbuf;
471
sp->jpegtables_length += 1000;
476
tables_term_destination(j_compress_ptr cinfo)
478
JPEGState* sp = (JPEGState*) cinfo;
480
/* set tables length to number of bytes actually emitted */
481
sp->jpegtables_length -= sp->dest.free_in_buffer;
485
TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
489
* Allocate a working buffer for building tables.
490
* Initial size is 1000 bytes, which is usually adequate.
493
_TIFFfree(sp->jpegtables);
494
sp->jpegtables_length = 1000;
495
sp->jpegtables = (void*) _TIFFmalloc((tsize_t) sp->jpegtables_length);
496
if (sp->jpegtables == NULL) {
497
sp->jpegtables_length = 0;
498
TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
501
sp->cinfo.c.dest = &sp->dest;
502
sp->dest.init_destination = tables_init_destination;
503
sp->dest.empty_output_buffer = tables_empty_output_buffer;
504
sp->dest.term_destination = tables_term_destination;
509
* JPEG library source data manager.
510
* These routines supply compressed data to libjpeg.
514
std_init_source(j_decompress_ptr cinfo)
516
JPEGState* sp = (JPEGState*) cinfo;
519
sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
520
sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
524
std_fill_input_buffer(j_decompress_ptr cinfo)
526
JPEGState* sp = (JPEGState* ) cinfo;
527
static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
530
* Should never get here since entire strip/tile is
531
* read into memory before the decompressor is called,
532
* and thus was supplied by init_source.
534
WARNMS(cinfo, JWRN_JPEG_EOF);
535
/* insert a fake EOI marker */
536
sp->src.next_input_byte = dummy_EOI;
537
sp->src.bytes_in_buffer = 2;
542
std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
544
JPEGState* sp = (JPEGState*) cinfo;
547
if (num_bytes > (long) sp->src.bytes_in_buffer) {
548
/* oops, buffer overrun */
549
(void) std_fill_input_buffer(cinfo);
551
sp->src.next_input_byte += (size_t) num_bytes;
552
sp->src.bytes_in_buffer -= (size_t) num_bytes;
558
std_term_source(j_decompress_ptr cinfo)
560
/* No work necessary here */
561
/* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
562
/* (if so, need empty tables_term_source!) */
567
TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
570
sp->cinfo.d.src = &sp->src;
571
sp->src.init_source = std_init_source;
572
sp->src.fill_input_buffer = std_fill_input_buffer;
573
sp->src.skip_input_data = std_skip_input_data;
574
sp->src.resync_to_restart = jpeg_resync_to_restart;
575
sp->src.term_source = std_term_source;
576
sp->src.bytes_in_buffer = 0; /* for safety */
577
sp->src.next_input_byte = NULL;
581
* Alternate source manager for reading from JPEGTables.
582
* We can share all the code except for the init routine.
586
tables_init_source(j_decompress_ptr cinfo)
588
JPEGState* sp = (JPEGState*) cinfo;
590
sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
591
sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
595
TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
597
TIFFjpeg_data_src(sp, tif);
598
sp->src.init_source = tables_init_source;
602
* Allocate downsampled-data buffers needed for downsampled I/O.
603
* We use values computed in jpeg_start_compress or jpeg_start_decompress.
604
* We use libjpeg's allocator so that buffers will be released automatically
605
* when done with strip/tile.
606
* This is also a handy place to compute samplesperclump, bytesperline.
609
alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
612
JPEGState* sp = JState(tif);
614
jpeg_component_info* compptr;
616
int samples_per_clump = 0;
618
for (ci = 0, compptr = comp_info; ci < num_components;
620
samples_per_clump += compptr->h_samp_factor *
621
compptr->v_samp_factor;
622
buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
623
compptr->width_in_blocks * DCTSIZE,
624
(JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
627
sp->ds_buffer[ci] = buf;
629
sp->samplesperclump = samples_per_clump;
639
JPEGSetupDecode(TIFF* tif)
641
JPEGState* sp = JState(tif);
642
TIFFDirectory *td = &tif->tif_dir;
644
JPEGInitializeLibJPEG( tif, 0, 1 );
647
assert(sp->cinfo.comm.is_decompressor);
649
/* Read JPEGTables if it is present */
650
if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
651
TIFFjpeg_tables_src(sp, tif);
652
if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
653
TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
658
/* Grab parameters that are same for all strips/tiles */
659
sp->photometric = td->td_photometric;
660
switch (sp->photometric) {
661
case PHOTOMETRIC_YCBCR:
662
sp->h_sampling = td->td_ycbcrsubsampling[0];
663
sp->v_sampling = td->td_ycbcrsubsampling[1];
666
/* TIFF 6.0 forbids subsampling of all other color spaces */
672
/* Set up for reading normal data */
673
TIFFjpeg_data_src(sp, tif);
674
tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
679
* Set up for decoding a strip or tile.
682
JPEGPreDecode(TIFF* tif, tsample_t s)
684
JPEGState *sp = JState(tif);
685
TIFFDirectory *td = &tif->tif_dir;
686
static const char module[] = "JPEGPreDecode";
687
uint32 segment_width, segment_height;
688
int downsampled_output;
692
assert(sp->cinfo.comm.is_decompressor);
694
* Reset decoder state from any previous strip/tile,
695
* in case application didn't read the whole strip.
697
if (!TIFFjpeg_abort(sp))
700
* Read the header for this strip/tile.
702
if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
705
* Check image parameters and set decompression parameters.
707
segment_width = td->td_imagewidth;
708
segment_height = td->td_imagelength - tif->tif_row;
710
segment_width = td->td_tilewidth;
711
segment_height = td->td_tilelength;
712
sp->bytesperline = TIFFTileRowSize(tif);
714
if (segment_height > td->td_rowsperstrip)
715
segment_height = td->td_rowsperstrip;
716
sp->bytesperline = TIFFOldScanlineSize(tif);
718
if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
720
* For PC 2, scale down the expected strip/tile size
721
* to match a downsampled component
723
segment_width = TIFFhowmany(segment_width, sp->h_sampling);
724
segment_height = TIFFhowmany(segment_height, sp->v_sampling);
726
if (sp->cinfo.d.image_width < segment_width ||
727
sp->cinfo.d.image_height < segment_height) {
728
TIFFWarningExt(tif->tif_clientdata, module,
729
"Improper JPEG strip/tile size, "
730
"expected %dx%d, got %dx%d",
731
segment_width, segment_height,
732
sp->cinfo.d.image_width,
733
sp->cinfo.d.image_height);
735
if (sp->cinfo.d.image_width > segment_width ||
736
sp->cinfo.d.image_height > segment_height) {
738
* This case could be dangerous, if the strip or tile size has
739
* been reported as less than the amount of data jpeg will
740
* return, some potential security issues arise. Catch this
741
* case and error out.
743
TIFFErrorExt(tif->tif_clientdata, module,
744
"JPEG strip/tile size exceeds expected dimensions,"
745
" expected %dx%d, got %dx%d",
746
segment_width, segment_height,
747
sp->cinfo.d.image_width, sp->cinfo.d.image_height);
750
if (sp->cinfo.d.num_components !=
751
(td->td_planarconfig == PLANARCONFIG_CONTIG ?
752
td->td_samplesperpixel : 1)) {
753
TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG component count");
757
if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
758
TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
761
sp->cinfo.d.data_precision = td->td_bitspersample;
762
sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
764
if (sp->cinfo.d.data_precision != td->td_bitspersample) {
765
TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
769
if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
770
/* Component 0 should have expected sampling factors */
771
if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
772
sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
773
TIFFWarningExt(tif->tif_clientdata, module,
774
"Improper JPEG sampling factors %d,%d\n"
775
"Apparently should be %d,%d.",
776
sp->cinfo.d.comp_info[0].h_samp_factor,
777
sp->cinfo.d.comp_info[0].v_samp_factor,
778
sp->h_sampling, sp->v_sampling);
781
* There are potential security issues here
782
* for decoders that have already allocated
783
* buffers based on the expected sampling
784
* factors. Lets check the sampling factors
785
* dont exceed what we were expecting.
787
if (sp->cinfo.d.comp_info[0].h_samp_factor
789
|| sp->cinfo.d.comp_info[0].v_samp_factor
791
TIFFErrorExt(tif->tif_clientdata,
793
"Cannot honour JPEG sampling factors"
794
" that exceed those specified.");
799
* XXX: Files written by the Intergraph software
800
* has different sampling factors stored in the
801
* TIFF tags and in the JPEG structures. We will
802
* try to deduce Intergraph files by the presense
805
if (!_TIFFFindFieldInfo(tif, 33918, TIFF_ANY)) {
806
TIFFWarningExt(tif->tif_clientdata, module,
807
"Decompressor will try reading with "
809
sp->cinfo.d.comp_info[0].h_samp_factor,
810
sp->cinfo.d.comp_info[0].v_samp_factor);
812
sp->h_sampling = (uint16)
813
sp->cinfo.d.comp_info[0].h_samp_factor;
814
sp->v_sampling = (uint16)
815
sp->cinfo.d.comp_info[0].v_samp_factor;
818
/* Rest should have sampling factors 1,1 */
819
for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
820
if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
821
sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
822
TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
827
/* PC 2's single component should have sampling factors 1,1 */
828
if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
829
sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
830
TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
834
downsampled_output = FALSE;
835
if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
836
sp->photometric == PHOTOMETRIC_YCBCR &&
837
sp->jpegcolormode == JPEGCOLORMODE_RGB) {
838
/* Convert YCbCr to RGB */
839
sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
840
sp->cinfo.d.out_color_space = JCS_RGB;
842
/* Suppress colorspace handling */
843
sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
844
sp->cinfo.d.out_color_space = JCS_UNKNOWN;
845
if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
846
(sp->h_sampling != 1 || sp->v_sampling != 1))
847
downsampled_output = TRUE;
848
/* XXX what about up-sampling? */
850
if (downsampled_output) {
851
/* Need to use raw-data interface to libjpeg */
852
sp->cinfo.d.raw_data_out = TRUE;
853
tif->tif_decoderow = JPEGDecodeRaw;
854
tif->tif_decodestrip = JPEGDecodeRaw;
855
tif->tif_decodetile = JPEGDecodeRaw;
857
/* Use normal interface to libjpeg */
858
sp->cinfo.d.raw_data_out = FALSE;
859
tif->tif_decoderow = JPEGDecode;
860
tif->tif_decodestrip = JPEGDecode;
861
tif->tif_decodetile = JPEGDecode;
863
/* Start JPEG decompressor */
864
if (!TIFFjpeg_start_decompress(sp))
866
/* Allocate downsampled-data buffers if needed */
867
if (downsampled_output) {
868
if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
869
sp->cinfo.d.num_components))
871
sp->scancount = DCTSIZE; /* mark buffer empty */
877
* Decode a chunk of pixels.
878
* "Standard" case: returned data is not downsampled.
880
/*ARGSUSED*/ static int
881
JPEGDecode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
883
JPEGState *sp = JState(tif);
887
nrows = cc / sp->bytesperline;
888
if (cc % sp->bytesperline)
889
TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
891
if( nrows > (int) sp->cinfo.d.image_height )
892
nrows = sp->cinfo.d.image_height;
894
/* data is expected to be read in multiples of a scanline */
897
JSAMPROW line_work_buf = NULL;
900
** For 6B, only use temporary buffer for 12 bit imagery.
901
** For Mk1 always use it.
903
#if !defined(JPEG_LIB_MK1)
904
if( sp->cinfo.d.data_precision == 12 )
907
line_work_buf = (JSAMPROW)
908
_TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
909
* sp->cinfo.d.num_components );
913
if( line_work_buf != NULL )
916
** In the MK1 case, we aways read into a 16bit buffer, and then
917
** pack down to 12bit or 8bit. In 6B case we only read into 16
918
** bit buffer for 12bit data, which we need to repack.
920
if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
923
if( sp->cinfo.d.data_precision == 12 )
925
int value_pairs = (sp->cinfo.d.output_width
926
* sp->cinfo.d.num_components) / 2;
929
for( iPair = 0; iPair < value_pairs; iPair++ )
931
unsigned char *out_ptr =
932
((unsigned char *) buf) + iPair * 3;
933
JSAMPLE *in_ptr = line_work_buf + iPair * 2;
935
out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
936
out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
937
| ((in_ptr[1] & 0xf00) >> 8);
938
out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
941
else if( sp->cinfo.d.data_precision == 8 )
943
int value_count = (sp->cinfo.d.output_width
944
* sp->cinfo.d.num_components);
947
for( iValue = 0; iValue < value_count; iValue++ )
949
((unsigned char *) buf)[iValue] =
950
line_work_buf[iValue] & 0xff;
957
** In the libjpeg6b 8bit case. We read directly into the
960
JSAMPROW bufptr = (JSAMPROW)buf;
962
if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
967
buf += sp->bytesperline;
968
cc -= sp->bytesperline;
969
} while (--nrows > 0);
971
if( line_work_buf != NULL )
972
_TIFFfree( line_work_buf );
975
/* Close down the decompressor if we've finished the strip or tile. */
976
return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
977
|| TIFFjpeg_finish_decompress(sp);
981
* Decode a chunk of pixels.
982
* Returned data is downsampled per sampling factors.
984
/*ARGSUSED*/ static int
985
JPEGDecodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
987
JPEGState *sp = JState(tif);
991
/* data is expected to be read in multiples of a scanline */
992
if ( (nrows = sp->cinfo.d.image_height) ) {
993
/* Cb,Cr both have sampling factors 1, so this is correct */
994
JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
995
int samples_per_clump = sp->samplesperclump;
998
unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
999
sp->cinfo.d.output_width *
1000
sp->cinfo.d.num_components);
1004
jpeg_component_info *compptr;
1005
int ci, clumpoffset;
1007
/* Reload downsampled-data buffer if needed */
1008
if (sp->scancount >= DCTSIZE) {
1009
int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
1010
if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
1015
* Fastest way to unseparate data is to make one pass
1016
* over the scanline for each row of each component.
1018
clumpoffset = 0; /* first sample in clump */
1019
for (ci = 0, compptr = sp->cinfo.d.comp_info;
1020
ci < sp->cinfo.d.num_components;
1022
int hsamp = compptr->h_samp_factor;
1023
int vsamp = compptr->v_samp_factor;
1026
for (ypos = 0; ypos < vsamp; ypos++) {
1027
JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1029
JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
1031
JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
1036
/* fast path for at least Cb and Cr */
1037
for (nclump = clumps_per_line; nclump-- > 0; ) {
1038
outptr[0] = *inptr++;
1039
outptr += samples_per_clump;
1045
for (nclump = clumps_per_line; nclump-- > 0; ) {
1046
for (xpos = 0; xpos < hsamp; xpos++)
1047
outptr[xpos] = *inptr++;
1048
outptr += samples_per_clump;
1051
clumpoffset += hsamp;
1057
if (sp->cinfo.d.data_precision == 8)
1060
int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
1061
for (i=0; i<len; i++)
1063
((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
1068
int value_pairs = (sp->cinfo.d.output_width
1069
* sp->cinfo.d.num_components) / 2;
1071
for( iPair = 0; iPair < value_pairs; iPair++ )
1073
unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
1074
JSAMPLE *in_ptr = tmpbuf + iPair * 2;
1075
out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
1076
out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
1077
| ((in_ptr[1] & 0xf00) >> 8);
1078
out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
1085
tif->tif_row += sp->v_sampling;
1086
/* increment/decrement of buf and cc is still incorrect, but should not matter
1087
* TODO: resolve this */
1088
buf += sp->bytesperline;
1089
cc -= sp->bytesperline;
1090
nrows -= sp->v_sampling;
1091
} while (nrows > 0);
1099
/* Close down the decompressor if done. */
1100
return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1101
|| TIFFjpeg_finish_decompress(sp);
1110
unsuppress_quant_table (JPEGState* sp, int tblno)
1114
if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1115
qtbl->sent_table = FALSE;
1119
unsuppress_huff_table (JPEGState* sp, int tblno)
1123
if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1124
htbl->sent_table = FALSE;
1125
if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1126
htbl->sent_table = FALSE;
1130
prepare_JPEGTables(TIFF* tif)
1132
JPEGState* sp = JState(tif);
1134
JPEGInitializeLibJPEG( tif, 0, 0 );
1136
/* Initialize quant tables for current quality setting */
1137
if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1139
/* Mark only the tables we want for output */
1140
/* NB: chrominance tables are currently used only with YCbCr */
1141
if (!TIFFjpeg_suppress_tables(sp, TRUE))
1143
if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
1144
unsuppress_quant_table(sp, 0);
1145
if (sp->photometric == PHOTOMETRIC_YCBCR)
1146
unsuppress_quant_table(sp, 1);
1148
if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
1149
unsuppress_huff_table(sp, 0);
1150
if (sp->photometric == PHOTOMETRIC_YCBCR)
1151
unsuppress_huff_table(sp, 1);
1153
/* Direct libjpeg output into jpegtables */
1154
if (!TIFFjpeg_tables_dest(sp, tif))
1156
/* Emit tables-only datastream */
1157
if (!TIFFjpeg_write_tables(sp))
1164
JPEGSetupEncode(TIFF* tif)
1166
JPEGState* sp = JState(tif);
1167
TIFFDirectory *td = &tif->tif_dir;
1168
static const char module[] = "JPEGSetupEncode";
1170
JPEGInitializeLibJPEG( tif, 1, 0 );
1173
assert(!sp->cinfo.comm.is_decompressor);
1176
* Initialize all JPEG parameters to default values.
1177
* Note that jpeg_set_defaults needs legal values for
1178
* in_color_space and input_components.
1180
sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1181
sp->cinfo.c.input_components = 1;
1182
if (!TIFFjpeg_set_defaults(sp))
1184
/* Set per-file parameters */
1185
sp->photometric = td->td_photometric;
1186
switch (sp->photometric) {
1187
case PHOTOMETRIC_YCBCR:
1188
sp->h_sampling = td->td_ycbcrsubsampling[0];
1189
sp->v_sampling = td->td_ycbcrsubsampling[1];
1191
* A ReferenceBlackWhite field *must* be present since the
1192
* default value is inappropriate for YCbCr. Fill in the
1193
* proper value if application didn't set it.
1197
if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1200
long top = 1L << td->td_bitspersample;
1202
refbw[1] = (float)(top-1L);
1203
refbw[2] = (float)(top>>1);
1204
refbw[3] = refbw[1];
1205
refbw[4] = refbw[2];
1206
refbw[5] = refbw[1];
1207
TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1212
case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */
1213
case PHOTOMETRIC_MASK:
1214
TIFFErrorExt(tif->tif_clientdata, module,
1215
"PhotometricInterpretation %d not allowed for JPEG",
1216
(int) sp->photometric);
1219
/* TIFF 6.0 forbids subsampling of all other color spaces */
1225
/* Verify miscellaneous parameters */
1228
* This would need work if libtiff ever supports different
1229
* depths for different components, or if libjpeg ever supports
1230
* run-time selection of depth. Neither is imminent.
1233
/* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1234
if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
1236
if (td->td_bitspersample != BITS_IN_JSAMPLE )
1239
TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
1240
(int) td->td_bitspersample);
1243
sp->cinfo.c.data_precision = td->td_bitspersample;
1245
sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
1248
if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
1249
TIFFErrorExt(tif->tif_clientdata, module,
1250
"JPEG tile height must be multiple of %d",
1251
sp->v_sampling * DCTSIZE);
1254
if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
1255
TIFFErrorExt(tif->tif_clientdata, module,
1256
"JPEG tile width must be multiple of %d",
1257
sp->h_sampling * DCTSIZE);
1261
if (td->td_rowsperstrip < td->td_imagelength &&
1262
(td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
1263
TIFFErrorExt(tif->tif_clientdata, module,
1264
"RowsPerStrip must be multiple of %d for JPEG",
1265
sp->v_sampling * DCTSIZE);
1270
/* Create a JPEGTables field if appropriate */
1271
if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
1272
if( sp->jpegtables == NULL
1273
|| memcmp(sp->jpegtables,"\0\0\0\0\0\0\0\0\0",8) == 0 )
1275
if (!prepare_JPEGTables(tif))
1277
/* Mark the field present */
1278
/* Can't use TIFFSetField since BEENWRITING is already set! */
1279
tif->tif_flags |= TIFF_DIRTYDIRECT;
1280
TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1283
/* We do not support application-supplied JPEGTables, */
1284
/* so mark the field not present */
1285
TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
1288
/* Direct libjpeg output to libtiff's output buffer */
1289
TIFFjpeg_data_dest(sp, tif);
1295
* Set encoding state at the start of a strip or tile.
1298
JPEGPreEncode(TIFF* tif, tsample_t s)
1300
JPEGState *sp = JState(tif);
1301
TIFFDirectory *td = &tif->tif_dir;
1302
static const char module[] = "JPEGPreEncode";
1303
uint32 segment_width, segment_height;
1304
int downsampled_input;
1307
assert(!sp->cinfo.comm.is_decompressor);
1309
* Set encoding parameters for this strip/tile.
1312
segment_width = td->td_tilewidth;
1313
segment_height = td->td_tilelength;
1314
sp->bytesperline = TIFFTileRowSize(tif);
1316
segment_width = td->td_imagewidth;
1317
segment_height = td->td_imagelength - tif->tif_row;
1318
if (segment_height > td->td_rowsperstrip)
1319
segment_height = td->td_rowsperstrip;
1320
sp->bytesperline = TIFFOldScanlineSize(tif);
1322
if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1323
/* for PC 2, scale down the strip/tile size
1324
* to match a downsampled component
1326
segment_width = TIFFhowmany(segment_width, sp->h_sampling);
1327
segment_height = TIFFhowmany(segment_height, sp->v_sampling);
1329
if (segment_width > 65535 || segment_height > 65535) {
1330
TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
1333
sp->cinfo.c.image_width = segment_width;
1334
sp->cinfo.c.image_height = segment_height;
1335
downsampled_input = FALSE;
1336
if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1337
sp->cinfo.c.input_components = td->td_samplesperpixel;
1338
if (sp->photometric == PHOTOMETRIC_YCBCR) {
1339
if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1340
sp->cinfo.c.in_color_space = JCS_RGB;
1342
sp->cinfo.c.in_color_space = JCS_YCbCr;
1343
if (sp->h_sampling != 1 || sp->v_sampling != 1)
1344
downsampled_input = TRUE;
1346
if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
1349
* Set Y sampling factors;
1350
* we assume jpeg_set_colorspace() set the rest to 1
1352
sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
1353
sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
1355
sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1356
if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1358
/* jpeg_set_colorspace set all sampling factors to 1 */
1361
sp->cinfo.c.input_components = 1;
1362
sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1363
if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1365
sp->cinfo.c.comp_info[0].component_id = s;
1366
/* jpeg_set_colorspace() set sampling factors to 1 */
1367
if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
1368
sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
1369
sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
1370
sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
1373
/* ensure libjpeg won't write any extraneous markers */
1374
sp->cinfo.c.write_JFIF_header = FALSE;
1375
sp->cinfo.c.write_Adobe_marker = FALSE;
1376
/* set up table handling correctly */
1377
if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1379
if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
1380
unsuppress_quant_table(sp, 0);
1381
unsuppress_quant_table(sp, 1);
1383
if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
1384
sp->cinfo.c.optimize_coding = FALSE;
1386
sp->cinfo.c.optimize_coding = TRUE;
1387
if (downsampled_input) {
1388
/* Need to use raw-data interface to libjpeg */
1389
sp->cinfo.c.raw_data_in = TRUE;
1390
tif->tif_encoderow = JPEGEncodeRaw;
1391
tif->tif_encodestrip = JPEGEncodeRaw;
1392
tif->tif_encodetile = JPEGEncodeRaw;
1394
/* Use normal interface to libjpeg */
1395
sp->cinfo.c.raw_data_in = FALSE;
1396
tif->tif_encoderow = JPEGEncode;
1397
tif->tif_encodestrip = JPEGEncode;
1398
tif->tif_encodetile = JPEGEncode;
1400
/* Start JPEG compressor */
1401
if (!TIFFjpeg_start_compress(sp, FALSE))
1403
/* Allocate downsampled-data buffers if needed */
1404
if (downsampled_input) {
1405
if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
1406
sp->cinfo.c.num_components))
1415
* Encode a chunk of pixels.
1416
* "Standard" case: incoming data is not downsampled.
1419
JPEGEncode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
1421
JPEGState *sp = JState(tif);
1427
/* data is expected to be supplied in multiples of a scanline */
1428
nrows = cc / sp->bytesperline;
1429
if (cc % sp->bytesperline)
1430
TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
1432
/* The last strip will be limited to image size */
1433
if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
1434
nrows = tif->tif_dir.td_imagelength - tif->tif_row;
1436
while (nrows-- > 0) {
1437
bufptr[0] = (JSAMPROW) buf;
1438
if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
1442
buf += sp->bytesperline;
1448
* Encode a chunk of pixels.
1449
* Incoming data is expected to be downsampled per sampling factors.
1452
JPEGEncodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
1454
JPEGState *sp = JState(tif);
1458
JDIMENSION clumps_per_line, nclump;
1459
int clumpoffset, ci, xpos, ypos;
1460
jpeg_component_info* compptr;
1461
int samples_per_clump = sp->samplesperclump;
1462
tsize_t bytesperclumpline;
1466
/* data is expected to be supplied in multiples of a clumpline */
1467
/* a clumpline is equivalent to v_sampling desubsampled scanlines */
1468
/* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
1469
bytesperclumpline = (((sp->cinfo.c.image_width+sp->h_sampling-1)/sp->h_sampling)
1470
*(sp->h_sampling*sp->v_sampling+2)*sp->cinfo.c.data_precision+7)
1473
nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
1474
if (cc % bytesperclumpline)
1475
TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
1477
/* Cb,Cr both have sampling factors 1, so this is correct */
1478
clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
1482
* Fastest way to separate the data is to make one pass
1483
* over the scanline for each row of each component.
1485
clumpoffset = 0; /* first sample in clump */
1486
for (ci = 0, compptr = sp->cinfo.c.comp_info;
1487
ci < sp->cinfo.c.num_components;
1489
int hsamp = compptr->h_samp_factor;
1490
int vsamp = compptr->v_samp_factor;
1491
int padding = (int) (compptr->width_in_blocks * DCTSIZE -
1492
clumps_per_line * hsamp);
1493
for (ypos = 0; ypos < vsamp; ypos++) {
1494
inptr = ((JSAMPLE*) buf) + clumpoffset;
1495
outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1497
/* fast path for at least Cb and Cr */
1498
for (nclump = clumps_per_line; nclump-- > 0; ) {
1499
*outptr++ = inptr[0];
1500
inptr += samples_per_clump;
1504
for (nclump = clumps_per_line; nclump-- > 0; ) {
1505
for (xpos = 0; xpos < hsamp; xpos++)
1506
*outptr++ = inptr[xpos];
1507
inptr += samples_per_clump;
1510
/* pad each scanline as needed */
1511
for (xpos = 0; xpos < padding; xpos++) {
1512
*outptr = outptr[-1];
1515
clumpoffset += hsamp;
1519
if (sp->scancount >= DCTSIZE) {
1520
int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1521
if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1525
tif->tif_row += sp->v_sampling;
1526
buf += sp->bytesperline;
1527
nrows -= sp->v_sampling;
1533
* Finish up at the end of a strip or tile.
1536
JPEGPostEncode(TIFF* tif)
1538
JPEGState *sp = JState(tif);
1540
if (sp->scancount > 0) {
1542
* Need to emit a partial bufferload of downsampled data.
1543
* Pad the data vertically.
1546
jpeg_component_info* compptr;
1548
for (ci = 0, compptr = sp->cinfo.c.comp_info;
1549
ci < sp->cinfo.c.num_components;
1551
int vsamp = compptr->v_samp_factor;
1552
tsize_t row_width = compptr->width_in_blocks * DCTSIZE
1554
for (ypos = sp->scancount * vsamp;
1555
ypos < DCTSIZE * vsamp; ypos++) {
1556
_TIFFmemcpy((tdata_t)sp->ds_buffer[ci][ypos],
1557
(tdata_t)sp->ds_buffer[ci][ypos-1],
1562
n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1563
if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1567
return (TIFFjpeg_finish_compress(JState(tif)));
1571
JPEGCleanup(TIFF* tif)
1573
JPEGState *sp = JState(tif);
1577
tif->tif_tagmethods.vgetfield = sp->vgetparent;
1578
tif->tif_tagmethods.vsetfield = sp->vsetparent;
1579
tif->tif_tagmethods.printdir = sp->printdir;
1581
if( sp->cinfo_initialized )
1582
TIFFjpeg_destroy(sp); /* release libjpeg resources */
1583
if (sp->jpegtables) /* tag value */
1584
_TIFFfree(sp->jpegtables);
1585
_TIFFfree(tif->tif_data); /* release local state */
1586
tif->tif_data = NULL;
1588
_TIFFSetDefaultCompressionState(tif);
1592
JPEGResetUpsampled( TIFF* tif )
1594
JPEGState* sp = JState(tif);
1595
TIFFDirectory* td = &tif->tif_dir;
1598
* Mark whether returned data is up-sampled or not so TIFFStripSize
1599
* and TIFFTileSize return values that reflect the true amount of
1602
tif->tif_flags &= ~TIFF_UPSAMPLED;
1603
if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1604
if (td->td_photometric == PHOTOMETRIC_YCBCR &&
1605
sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1606
tif->tif_flags |= TIFF_UPSAMPLED;
1609
if (td->td_ycbcrsubsampling[0] != 1 ||
1610
td->td_ycbcrsubsampling[1] != 1)
1611
; /* XXX what about up-sampling? */
1617
* Must recalculate cached tile size in case sampling state changed.
1618
* Should we really be doing this now if image size isn't set?
1620
if( tif->tif_tilesize > 0 )
1621
tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tsize_t) -1;
1623
if(tif->tif_scanlinesize > 0 )
1624
tif->tif_scanlinesize = TIFFScanlineSize(tif);
1628
JPEGVSetField(TIFF* tif, ttag_t tag, va_list ap)
1630
JPEGState* sp = JState(tif);
1631
const TIFFFieldInfo* fip;
1637
case TIFFTAG_JPEGTABLES:
1638
v32 = va_arg(ap, uint32);
1643
_TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
1645
sp->jpegtables_length = v32;
1646
TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1648
case TIFFTAG_JPEGQUALITY:
1649
sp->jpegquality = va_arg(ap, int);
1650
return (1); /* pseudo tag */
1651
case TIFFTAG_JPEGCOLORMODE:
1652
sp->jpegcolormode = va_arg(ap, int);
1653
JPEGResetUpsampled( tif );
1654
return (1); /* pseudo tag */
1655
case TIFFTAG_PHOTOMETRIC:
1657
int ret_value = (*sp->vsetparent)(tif, tag, ap);
1658
JPEGResetUpsampled( tif );
1661
case TIFFTAG_JPEGTABLESMODE:
1662
sp->jpegtablesmode = va_arg(ap, int);
1663
return (1); /* pseudo tag */
1664
case TIFFTAG_YCBCRSUBSAMPLING:
1665
/* mark the fact that we have a real ycbcrsubsampling! */
1666
sp->ycbcrsampling_fetched = 1;
1667
/* should we be recomputing upsampling info here? */
1668
return (*sp->vsetparent)(tif, tag, ap);
1669
case TIFFTAG_FAXRECVPARAMS:
1670
sp->recvparams = va_arg(ap, uint32);
1672
case TIFFTAG_FAXSUBADDRESS:
1673
_TIFFsetString(&sp->subaddress, va_arg(ap, char*));
1675
case TIFFTAG_FAXRECVTIME:
1676
sp->recvtime = va_arg(ap, uint32);
1678
case TIFFTAG_FAXDCS:
1679
_TIFFsetString(&sp->faxdcs, va_arg(ap, char*));
1682
return (*sp->vsetparent)(tif, tag, ap);
1685
if ((fip = _TIFFFieldWithTag(tif, tag))) {
1686
TIFFSetFieldBit(tif, fip->field_bit);
1691
tif->tif_flags |= TIFF_DIRTYDIRECT;
1696
* Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
1697
* the TIFF tags, but still use non-default (2,2) values within the jpeg
1698
* data stream itself. In order for TIFF applications to work properly
1699
* - for instance to get the strip buffer size right - it is imperative
1700
* that the subsampling be available before we start reading the image
1701
* data normally. This function will attempt to load the first strip in
1702
* order to get the sampling values from the jpeg data stream. Various
1703
* hacks are various places are done to ensure this function gets called
1704
* before the td_ycbcrsubsampling values are used from the directory structure,
1705
* including calling TIFFGetField() for the YCBCRSUBSAMPLING field from
1706
* TIFFStripSize(), and the printing code in tif_print.c.
1708
* Note that JPEGPreDeocode() will produce a fairly loud warning when the
1709
* discovered sampling does not match the default sampling (2,2) or whatever
1710
* was actually in the tiff tags.
1713
* o This code will cause one whole strip/tile of compressed data to be
1714
* loaded just to get the tags right, even if the imagery is never read.
1715
* It would be more efficient to just load a bit of the header, and
1716
* initialize things from that.
1718
* See the bug in bugzilla for details:
1720
* http://bugzilla.remotesensing.org/show_bug.cgi?id=168
1722
* Frank Warmerdam, July 2002
1726
JPEGFixupTestSubsampling( TIFF * tif )
1728
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
1729
JPEGState *sp = JState(tif);
1730
TIFFDirectory *td = &tif->tif_dir;
1732
JPEGInitializeLibJPEG( tif, 0, 0 );
1735
* Some JPEG-in-TIFF files don't provide the ycbcrsampling tags,
1736
* and use a sampling schema other than the default 2,2. To handle
1737
* this we actually have to scan the header of a strip or tile of
1738
* jpeg data to get the sampling.
1740
if( !sp->cinfo.comm.is_decompressor
1741
|| sp->ycbcrsampling_fetched
1742
|| td->td_photometric != PHOTOMETRIC_YCBCR )
1745
sp->ycbcrsampling_fetched = 1;
1746
if( TIFFIsTiled( tif ) )
1748
if( !TIFFFillTile( tif, 0 ) )
1753
if( !TIFFFillStrip( tif, 0 ) )
1757
TIFFSetField( tif, TIFFTAG_YCBCRSUBSAMPLING,
1758
(uint16) sp->h_sampling, (uint16) sp->v_sampling );
1761
** We want to clear the loaded strip so the application has time
1762
** to set JPEGCOLORMODE or other behavior modifiers. This essentially
1763
** undoes the JPEGPreDecode triggers by TIFFFileStrip(). (#1936)
1765
tif->tif_curstrip = -1;
1767
#endif /* CHECK_JPEG_YCBCR_SUBSAMPLING */
1771
JPEGVGetField(TIFF* tif, ttag_t tag, va_list ap)
1773
JPEGState* sp = JState(tif);
1778
case TIFFTAG_JPEGTABLES:
1779
*va_arg(ap, uint32*) = sp->jpegtables_length;
1780
*va_arg(ap, void**) = sp->jpegtables;
1782
case TIFFTAG_JPEGQUALITY:
1783
*va_arg(ap, int*) = sp->jpegquality;
1785
case TIFFTAG_JPEGCOLORMODE:
1786
*va_arg(ap, int*) = sp->jpegcolormode;
1788
case TIFFTAG_JPEGTABLESMODE:
1789
*va_arg(ap, int*) = sp->jpegtablesmode;
1791
case TIFFTAG_YCBCRSUBSAMPLING:
1792
JPEGFixupTestSubsampling( tif );
1793
return (*sp->vgetparent)(tif, tag, ap);
1794
case TIFFTAG_FAXRECVPARAMS:
1795
*va_arg(ap, uint32*) = sp->recvparams;
1797
case TIFFTAG_FAXSUBADDRESS:
1798
*va_arg(ap, char**) = sp->subaddress;
1800
case TIFFTAG_FAXRECVTIME:
1801
*va_arg(ap, uint32*) = sp->recvtime;
1803
case TIFFTAG_FAXDCS:
1804
*va_arg(ap, char**) = sp->faxdcs;
1807
return (*sp->vgetparent)(tif, tag, ap);
1813
JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
1815
JPEGState* sp = JState(tif);
1820
if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
1821
fprintf(fd, " JPEG Tables: (%lu bytes)\n",
1822
(unsigned long) sp->jpegtables_length);
1823
if (TIFFFieldSet(tif,FIELD_RECVPARAMS))
1824
fprintf(fd, " Fax Receive Parameters: %08lx\n",
1825
(unsigned long) sp->recvparams);
1826
if (TIFFFieldSet(tif,FIELD_SUBADDRESS))
1827
fprintf(fd, " Fax SubAddress: %s\n", sp->subaddress);
1828
if (TIFFFieldSet(tif,FIELD_RECVTIME))
1829
fprintf(fd, " Fax Receive Time: %lu secs\n",
1830
(unsigned long) sp->recvtime);
1831
if (TIFFFieldSet(tif,FIELD_FAXDCS))
1832
fprintf(fd, " Fax DCS: %s\n", sp->faxdcs);
1836
JPEGDefaultStripSize(TIFF* tif, uint32 s)
1838
JPEGState* sp = JState(tif);
1839
TIFFDirectory *td = &tif->tif_dir;
1841
s = (*sp->defsparent)(tif, s);
1842
if (s < td->td_imagelength)
1843
s = TIFFroundup(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
1848
JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
1850
JPEGState* sp = JState(tif);
1851
TIFFDirectory *td = &tif->tif_dir;
1853
(*sp->deftparent)(tif, tw, th);
1854
*tw = TIFFroundup(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
1855
*th = TIFFroundup(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
1859
* The JPEG library initialized used to be done in TIFFInitJPEG(), but
1860
* now that we allow a TIFF file to be opened in update mode it is necessary
1861
* to have some way of deciding whether compression or decompression is
1862
* desired other than looking at tif->tif_mode. We accomplish this by
1863
* examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
1864
* If so, we assume decompression is desired.
1866
* This is tricky, because TIFFInitJPEG() is called while the directory is
1867
* being read, and generally speaking the BYTECOUNTS tag won't have been read
1868
* at that point. So we try to defer jpeg library initialization till we
1869
* do have that tag ... basically any access that might require the compressor
1870
* or decompressor that occurs after the reading of the directory.
1872
* In an ideal world compressors or decompressors would be setup
1873
* at the point where a single tile or strip was accessed (for read or write)
1874
* so that stuff like update of missing tiles, or replacement of tiles could
1875
* be done. However, we aren't trying to crack that nut just yet ...
1877
* NFW, Feb 3rd, 2003.
1880
static int JPEGInitializeLibJPEG( TIFF * tif, int force_encode, int force_decode )
1882
JPEGState* sp = JState(tif);
1883
uint32 *byte_counts = NULL;
1884
int data_is_empty = TRUE;
1888
if(sp->cinfo_initialized)
1890
if( force_encode && sp->cinfo.comm.is_decompressor )
1891
TIFFjpeg_destroy( sp );
1892
else if( force_decode && !sp->cinfo.comm.is_decompressor )
1893
TIFFjpeg_destroy( sp );
1897
sp->cinfo_initialized = 0;
1901
* Do we have tile data already? Make sure we initialize the
1902
* the state in decompressor mode if we have tile data, even if we
1903
* are not in read-only file access mode.
1905
if( TIFFIsTiled( tif )
1906
&& TIFFGetField( tif, TIFFTAG_TILEBYTECOUNTS, &byte_counts )
1907
&& byte_counts != NULL )
1909
data_is_empty = byte_counts[0] == 0;
1911
if( !TIFFIsTiled( tif )
1912
&& TIFFGetField( tif, TIFFTAG_STRIPBYTECOUNTS, &byte_counts)
1913
&& byte_counts != NULL )
1915
data_is_empty = byte_counts[0] == 0;
1920
else if( force_encode )
1922
else if( tif->tif_mode == O_RDONLY )
1924
else if( data_is_empty )
1930
* Initialize libjpeg.
1933
if (!TIFFjpeg_create_decompress(sp))
1937
if (!TIFFjpeg_create_compress(sp))
1941
sp->cinfo_initialized = TRUE;
1947
TIFFInitJPEG(TIFF* tif, int scheme)
1951
assert(scheme == COMPRESSION_JPEG);
1954
* Merge codec-specific tag information.
1956
if (!_TIFFMergeFieldInfo(tif, jpegFieldInfo, N(jpegFieldInfo))) {
1957
TIFFErrorExt(tif->tif_clientdata,
1959
"Merging JPEG codec-specific tags failed");
1964
* Allocate state block so tag methods have storage to record values.
1966
tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (JPEGState));
1968
if (tif->tif_data == NULL) {
1969
TIFFErrorExt(tif->tif_clientdata,
1970
"TIFFInitJPEG", "No space for JPEG state block");
1973
_TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
1976
sp->tif = tif; /* back link */
1979
* Override parent get/set field methods.
1981
sp->vgetparent = tif->tif_tagmethods.vgetfield;
1982
tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
1983
sp->vsetparent = tif->tif_tagmethods.vsetfield;
1984
tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
1985
sp->printdir = tif->tif_tagmethods.printdir;
1986
tif->tif_tagmethods.printdir = JPEGPrintDir; /* hook for codec tags */
1988
/* Default values for codec-specific fields */
1989
sp->jpegtables = NULL;
1990
sp->jpegtables_length = 0;
1991
sp->jpegquality = 75; /* Default IJG quality */
1992
sp->jpegcolormode = JPEGCOLORMODE_RAW;
1993
sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
1996
sp->subaddress = NULL;
1999
sp->ycbcrsampling_fetched = 0;
2002
* Install codec methods.
2004
tif->tif_setupdecode = JPEGSetupDecode;
2005
tif->tif_predecode = JPEGPreDecode;
2006
tif->tif_decoderow = JPEGDecode;
2007
tif->tif_decodestrip = JPEGDecode;
2008
tif->tif_decodetile = JPEGDecode;
2009
tif->tif_setupencode = JPEGSetupEncode;
2010
tif->tif_preencode = JPEGPreEncode;
2011
tif->tif_postencode = JPEGPostEncode;
2012
tif->tif_encoderow = JPEGEncode;
2013
tif->tif_encodestrip = JPEGEncode;
2014
tif->tif_encodetile = JPEGEncode;
2015
tif->tif_cleanup = JPEGCleanup;
2016
sp->defsparent = tif->tif_defstripsize;
2017
tif->tif_defstripsize = JPEGDefaultStripSize;
2018
sp->deftparent = tif->tif_deftilesize;
2019
tif->tif_deftilesize = JPEGDefaultTileSize;
2020
tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
2022
sp->cinfo_initialized = FALSE;
2025
** Create a JPEGTables field if no directory has yet been created.
2026
** We do this just to ensure that sufficient space is reserved for
2027
** the JPEGTables field. It will be properly created the right
2030
if( tif->tif_diroff == 0 )
2032
#define SIZE_OF_JPEGTABLES 2000
2034
The following line assumes incorrectly that all JPEG-in-TIFF files will have
2035
a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
2036
when the JPEG data is placed with TIFFWriteRawStrip. The field bit should be
2037
set, anyway, later when actual JPEGTABLES header is generated, so removing it
2038
here hopefully is harmless.
2039
TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2041
sp->jpegtables_length = SIZE_OF_JPEGTABLES;
2042
sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
2043
_TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
2044
#undef SIZE_OF_JPEGTABLES
2048
* Mark the TIFFTAG_YCBCRSAMPLES as present even if it is not
2049
* see: JPEGFixupTestSubsampling().
2051
TIFFSetFieldBit( tif, FIELD_YCBCRSUBSAMPLING );
2055
#endif /* JPEG_SUPPORT */
2057
/* vim: set ts=8 sts=8 sw=8 noet: */