1 /* $Id: tif_jpeg.c,v 1.1 2005-06-17 13:54:52 vp153 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>.
43 int TIFFFillStrip(TIFF*, tstrip_t);
44 int TIFFFillTile(TIFF*, ttile_t);
46 /* We undefine FAR to avoid conflict with JPEG definition */
54 The windows RPCNDR.H file defines boolean, but defines it with the
55 unsigned char size. You should compile JPEG library using appropriate
56 definitions in jconfig.h header, but many users compile library in wrong
57 way. That causes errors of the following type:
59 "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
62 For such users we wil fix the problem here. See install.doc file from
63 the JPEG library distribution for details.
66 /* Define "boolean" as unsigned char, not int, per Windows custom. */
68 # ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
69 typedef unsigned char boolean;
71 # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
78 * We are using width_in_blocks which is supposed to be private to
79 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
80 * renamed this member to width_in_data_units. Since the header has
81 * also renamed a define, use that unique define name in order to
82 * detect the problem header and adjust to suit.
84 #if defined(D_MAX_DATA_UNITS_IN_MCU)
85 #define width_in_blocks width_in_data_units
89 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
90 * in place of plain setjmp. These macros will make it easier.
92 #define SETJMP(jbuf) setjmp(jbuf)
93 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
94 #define JMP_BUF jmp_buf
96 typedef struct jpeg_destination_mgr jpeg_destination_mgr;
97 typedef struct jpeg_source_mgr jpeg_source_mgr;
98 typedef struct jpeg_error_mgr jpeg_error_mgr;
101 * State block for each open TIFF file using
102 * libjpeg to do JPEG compression/decompression.
104 * libjpeg's visible state is either a jpeg_compress_struct
105 * or jpeg_decompress_struct depending on which way we
106 * are going. comm can be used to refer to the fields
107 * which are common to both.
109 * NB: cinfo is required to be the first member of JPEGState,
110 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
115 struct jpeg_compress_struct c;
116 struct jpeg_decompress_struct d;
117 struct jpeg_common_struct comm;
118 } cinfo; /* NB: must be first */
119 int cinfo_initialized;
121 jpeg_error_mgr err; /* libjpeg error manager */
122 JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
124 * The following two members could be a union, but
125 * they're small enough that it's not worth the effort.
127 jpeg_destination_mgr dest; /* data dest for compression */
128 jpeg_source_mgr src; /* data source for decompression */
130 TIFF* tif; /* back link needed by some code */
131 uint16 photometric; /* copy of PhotometricInterpretation */
132 uint16 h_sampling; /* luminance sampling factors */
134 tsize_t bytesperline; /* decompressed bytes per scanline */
135 /* pointers to intermediate buffers when processing downsampled data */
136 JSAMPARRAY ds_buffer[MAX_COMPONENTS];
137 int scancount; /* number of "scanlines" accumulated */
140 TIFFVGetMethod vgetparent; /* super-class method */
141 TIFFVSetMethod vsetparent; /* super-class method */
142 TIFFStripMethod defsparent; /* super-class method */
143 TIFFTileMethod deftparent; /* super-class method */
144 /* pseudo-tag fields */
145 void* jpegtables; /* JPEGTables tag value, or NULL */
146 uint32 jpegtables_length; /* number of bytes in same */
147 int jpegquality; /* Compression quality level */
148 int jpegcolormode; /* Auto RGB<=>YCbCr convert? */
149 int jpegtablesmode; /* What to put in JPEGTables */
151 int ycbcrsampling_fetched;
152 uint32 recvparams; /* encoded Class 2 session params */
153 char* subaddress; /* subaddress string */
154 uint32 recvtime; /* time spent receiving (secs) */
155 char* faxdcs; /* encoded fax parameters (DCS, Table 2/T.30) */
158 #define JState(tif) ((JPEGState*)(tif)->tif_data)
160 static int JPEGDecode(TIFF*, tidata_t, tsize_t, tsample_t);
161 static int JPEGDecodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
162 static int JPEGEncode(TIFF*, tidata_t, tsize_t, tsample_t);
163 static int JPEGEncodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
164 static int JPEGInitializeLibJPEG( TIFF * tif );
166 #define FIELD_JPEGTABLES (FIELD_CODEC+0)
167 #define FIELD_RECVPARAMS (FIELD_CODEC+1)
168 #define FIELD_SUBADDRESS (FIELD_CODEC+2)
169 #define FIELD_RECVTIME (FIELD_CODEC+3)
170 #define FIELD_FAXDCS (FIELD_CODEC+4)
172 static const TIFFFieldInfo jpegFieldInfo[] = {
173 { TIFFTAG_JPEGTABLES, -3,-3, TIFF_UNDEFINED, FIELD_JPEGTABLES,
174 FALSE, TRUE, "JPEGTables" },
175 { TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, FIELD_PSEUDO,
177 { TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
179 { TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
181 /* Specific for JPEG in faxes */
182 { TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, FIELD_RECVPARAMS,
183 TRUE, FALSE, "FaxRecvParams" },
184 { TIFFTAG_FAXSUBADDRESS, -1,-1, TIFF_ASCII, FIELD_SUBADDRESS,
185 TRUE, FALSE, "FaxSubAddress" },
186 { TIFFTAG_FAXRECVTIME, 1, 1, TIFF_LONG, FIELD_RECVTIME,
187 TRUE, FALSE, "FaxRecvTime" },
188 { TIFFTAG_FAXDCS, -1, -1, TIFF_ASCII, FIELD_FAXDCS,
189 TRUE, FALSE, "FaxDcs" },
191 #define N(a) (sizeof (a) / sizeof (a[0]))
194 * libjpeg interface layer.
196 * We use setjmp/longjmp to return control to libtiff
197 * when a fatal error is encountered within the JPEG
198 * library. We also direct libjpeg error and warning
199 * messages through the appropriate libtiff handlers.
203 * Error handling routines (these replace corresponding
204 * IJG routines from jerror.c). These are used for both
205 * compression and decompression.
208 TIFFjpeg_error_exit(j_common_ptr cinfo)
210 JPEGState *sp = (JPEGState *) cinfo; /* NB: cinfo assumed first */
211 char buffer[JMSG_LENGTH_MAX];
213 (*cinfo->err->format_message) (cinfo, buffer);
214 TIFFError("JPEGLib", buffer); /* display the error message */
215 jpeg_abort(cinfo); /* clean up libjpeg state */
216 LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
220 * This routine is invoked only for warning messages,
221 * since error_exit does its own thing and trace_level
225 TIFFjpeg_output_message(j_common_ptr cinfo)
227 char buffer[JMSG_LENGTH_MAX];
229 (*cinfo->err->format_message) (cinfo, buffer);
230 TIFFWarning("JPEGLib", buffer);
234 * Interface routines. This layer of routines exists
235 * primarily to limit side-effects from using setjmp.
236 * Also, normal/error returns are converted into return
237 * values per libtiff practice.
239 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
240 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
243 TIFFjpeg_create_compress(JPEGState* sp)
245 /* initialize JPEG error handling */
246 sp->cinfo.c.err = jpeg_std_error(&sp->err);
247 sp->err.error_exit = TIFFjpeg_error_exit;
248 sp->err.output_message = TIFFjpeg_output_message;
250 return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
254 TIFFjpeg_create_decompress(JPEGState* sp)
256 /* initialize JPEG error handling */
257 sp->cinfo.d.err = jpeg_std_error(&sp->err);
258 sp->err.error_exit = TIFFjpeg_error_exit;
259 sp->err.output_message = TIFFjpeg_output_message;
261 return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
265 TIFFjpeg_set_defaults(JPEGState* sp)
267 return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
271 TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
273 return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
277 TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
280 jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
284 TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
286 return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
290 TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
293 jpeg_start_compress(&sp->cinfo.c, write_all_tables));
297 TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
299 return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
300 scanlines, (JDIMENSION) num_lines));
304 TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
306 return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
307 data, (JDIMENSION) num_lines));
311 TIFFjpeg_finish_compress(JPEGState* sp)
313 return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
317 TIFFjpeg_write_tables(JPEGState* sp)
319 return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
323 TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
325 return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
329 TIFFjpeg_start_decompress(JPEGState* sp)
331 return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
335 TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
337 return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
338 scanlines, (JDIMENSION) max_lines));
342 TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
344 return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
345 data, (JDIMENSION) max_lines));
349 TIFFjpeg_finish_decompress(JPEGState* sp)
351 return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
355 TIFFjpeg_abort(JPEGState* sp)
357 return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
361 TIFFjpeg_destroy(JPEGState* sp)
363 return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
367 TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
368 JDIMENSION samplesperrow, JDIMENSION numrows)
370 return CALLJPEG(sp, (JSAMPARRAY) NULL,
371 (*sp->cinfo.comm.mem->alloc_sarray)
372 (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
376 * JPEG library destination data manager.
377 * These routines direct compressed data from libjpeg into the
378 * libtiff output buffer.
382 std_init_destination(j_compress_ptr cinfo)
384 JPEGState* sp = (JPEGState*) cinfo;
387 sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
388 sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
392 std_empty_output_buffer(j_compress_ptr cinfo)
394 JPEGState* sp = (JPEGState*) cinfo;
397 /* the entire buffer has been filled */
398 tif->tif_rawcc = tif->tif_rawdatasize;
400 sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
401 sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
407 std_term_destination(j_compress_ptr cinfo)
409 JPEGState* sp = (JPEGState*) cinfo;
412 tif->tif_rawcp = (tidata_t) sp->dest.next_output_byte;
414 tif->tif_rawdatasize - (tsize_t) sp->dest.free_in_buffer;
415 /* NB: libtiff does the final buffer flush */
419 TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
422 sp->cinfo.c.dest = &sp->dest;
423 sp->dest.init_destination = std_init_destination;
424 sp->dest.empty_output_buffer = std_empty_output_buffer;
425 sp->dest.term_destination = std_term_destination;
429 * Alternate destination manager for outputting to JPEGTables field.
433 tables_init_destination(j_compress_ptr cinfo)
435 JPEGState* sp = (JPEGState*) cinfo;
437 /* while building, jpegtables_length is allocated buffer size */
438 sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
439 sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
443 tables_empty_output_buffer(j_compress_ptr cinfo)
445 JPEGState* sp = (JPEGState*) cinfo;
448 /* the entire buffer has been filled; enlarge it by 1000 bytes */
449 newbuf = _TIFFrealloc((tdata_t) sp->jpegtables,
450 (tsize_t) (sp->jpegtables_length + 1000));
452 ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
453 sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
454 sp->dest.free_in_buffer = (size_t) 1000;
455 sp->jpegtables = newbuf;
456 sp->jpegtables_length += 1000;
461 tables_term_destination(j_compress_ptr cinfo)
463 JPEGState* sp = (JPEGState*) cinfo;
465 /* set tables length to number of bytes actually emitted */
466 sp->jpegtables_length -= sp->dest.free_in_buffer;
470 TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
474 * Allocate a working buffer for building tables.
475 * Initial size is 1000 bytes, which is usually adequate.
478 _TIFFfree(sp->jpegtables);
479 sp->jpegtables_length = 1000;
480 sp->jpegtables = (void*) _TIFFmalloc((tsize_t) sp->jpegtables_length);
481 if (sp->jpegtables == NULL) {
482 sp->jpegtables_length = 0;
483 TIFFError("TIFFjpeg_tables_dest", "No space for JPEGTables");
486 sp->cinfo.c.dest = &sp->dest;
487 sp->dest.init_destination = tables_init_destination;
488 sp->dest.empty_output_buffer = tables_empty_output_buffer;
489 sp->dest.term_destination = tables_term_destination;
494 * JPEG library source data manager.
495 * These routines supply compressed data to libjpeg.
499 std_init_source(j_decompress_ptr cinfo)
501 JPEGState* sp = (JPEGState*) cinfo;
504 sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
505 sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
509 std_fill_input_buffer(j_decompress_ptr cinfo)
511 JPEGState* sp = (JPEGState* ) cinfo;
512 static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
515 * Should never get here since entire strip/tile is
516 * read into memory before the decompressor is called,
517 * and thus was supplied by init_source.
519 WARNMS(cinfo, JWRN_JPEG_EOF);
520 /* insert a fake EOI marker */
521 sp->src.next_input_byte = dummy_EOI;
522 sp->src.bytes_in_buffer = 2;
527 std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
529 JPEGState* sp = (JPEGState*) cinfo;
532 if (num_bytes > (long) sp->src.bytes_in_buffer) {
533 /* oops, buffer overrun */
534 (void) std_fill_input_buffer(cinfo);
536 sp->src.next_input_byte += (size_t) num_bytes;
537 sp->src.bytes_in_buffer -= (size_t) num_bytes;
543 std_term_source(j_decompress_ptr cinfo)
545 /* No work necessary here */
546 /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
547 /* (if so, need empty tables_term_source!) */
552 TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
555 sp->cinfo.d.src = &sp->src;
556 sp->src.init_source = std_init_source;
557 sp->src.fill_input_buffer = std_fill_input_buffer;
558 sp->src.skip_input_data = std_skip_input_data;
559 sp->src.resync_to_restart = jpeg_resync_to_restart;
560 sp->src.term_source = std_term_source;
561 sp->src.bytes_in_buffer = 0; /* for safety */
562 sp->src.next_input_byte = NULL;
566 * Alternate source manager for reading from JPEGTables.
567 * We can share all the code except for the init routine.
571 tables_init_source(j_decompress_ptr cinfo)
573 JPEGState* sp = (JPEGState*) cinfo;
575 sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
576 sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
580 TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
582 TIFFjpeg_data_src(sp, tif);
583 sp->src.init_source = tables_init_source;
587 * Allocate downsampled-data buffers needed for downsampled I/O.
588 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
589 * We use libjpeg's allocator so that buffers will be released automatically
590 * when done with strip/tile.
591 * This is also a handy place to compute samplesperclump, bytesperline.
594 alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
597 JPEGState* sp = JState(tif);
599 jpeg_component_info* compptr;
601 int samples_per_clump = 0;
603 for (ci = 0, compptr = comp_info; ci < num_components;
605 samples_per_clump += compptr->h_samp_factor *
606 compptr->v_samp_factor;
607 buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
608 compptr->width_in_blocks * DCTSIZE,
609 (JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
612 sp->ds_buffer[ci] = buf;
614 sp->samplesperclump = samples_per_clump;
624 JPEGSetupDecode(TIFF* tif)
626 JPEGState* sp = JState(tif);
627 TIFFDirectory *td = &tif->tif_dir;
629 JPEGInitializeLibJPEG( tif );
632 assert(sp->cinfo.comm.is_decompressor);
634 /* Read JPEGTables if it is present */
635 if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
636 TIFFjpeg_tables_src(sp, tif);
637 if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
638 TIFFError("JPEGSetupDecode", "Bogus JPEGTables field");
643 /* Grab parameters that are same for all strips/tiles */
644 sp->photometric = td->td_photometric;
645 switch (sp->photometric) {
646 case PHOTOMETRIC_YCBCR:
647 sp->h_sampling = td->td_ycbcrsubsampling[0];
648 sp->v_sampling = td->td_ycbcrsubsampling[1];
651 /* TIFF 6.0 forbids subsampling of all other color spaces */
657 /* Set up for reading normal data */
658 TIFFjpeg_data_src(sp, tif);
659 tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
664 * Set up for decoding a strip or tile.
667 JPEGPreDecode(TIFF* tif, tsample_t s)
669 JPEGState *sp = JState(tif);
670 TIFFDirectory *td = &tif->tif_dir;
671 static const char module[] = "JPEGPreDecode";
672 uint32 segment_width, segment_height;
673 int downsampled_output;
677 assert(sp->cinfo.comm.is_decompressor);
679 * Reset decoder state from any previous strip/tile,
680 * in case application didn't read the whole strip.
682 if (!TIFFjpeg_abort(sp))
685 * Read the header for this strip/tile.
687 if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
690 * Check image parameters and set decompression parameters.
692 segment_width = td->td_imagewidth;
693 segment_height = td->td_imagelength - tif->tif_row;
695 segment_width = td->td_tilewidth;
696 segment_height = td->td_tilelength;
697 sp->bytesperline = TIFFTileRowSize(tif);
699 if (segment_height > td->td_rowsperstrip)
700 segment_height = td->td_rowsperstrip;
701 sp->bytesperline = TIFFScanlineSize(tif);
703 if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
705 * For PC 2, scale down the expected strip/tile size
706 * to match a downsampled component
708 segment_width = TIFFhowmany(segment_width, sp->h_sampling);
709 segment_height = TIFFhowmany(segment_height, sp->v_sampling);
711 if (sp->cinfo.d.image_width != segment_width ||
712 sp->cinfo.d.image_height != segment_height) {
714 "Improper JPEG strip/tile size, expected %dx%d, got %dx%d",
717 sp->cinfo.d.image_width,
718 sp->cinfo.d.image_height);
720 if (sp->cinfo.d.num_components !=
721 (td->td_planarconfig == PLANARCONFIG_CONTIG ?
722 td->td_samplesperpixel : 1)) {
723 TIFFError(module, "Improper JPEG component count");
726 if (sp->cinfo.d.data_precision != td->td_bitspersample) {
727 TIFFError(module, "Improper JPEG data precision");
730 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
731 /* Component 0 should have expected sampling factors */
732 if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
733 sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
735 "Improper JPEG sampling factors %d,%d\n"
736 "Apparently should be %d,%d.",
737 sp->cinfo.d.comp_info[0].h_samp_factor,
738 sp->cinfo.d.comp_info[0].v_samp_factor,
739 sp->h_sampling, sp->v_sampling);
742 * XXX: Files written by the Intergraph software
743 * has different sampling factors stored in the
744 * TIFF tags and in the JPEG structures. We will
745 * try to deduce Intergraph files by the presense
748 if (!_TIFFFindFieldInfo(tif, 33918, TIFF_ANY)) {
750 "Decompressor will try reading with "
752 sp->cinfo.d.comp_info[0].h_samp_factor,
753 sp->cinfo.d.comp_info[0].v_samp_factor);
755 sp->h_sampling = (uint16)
756 sp->cinfo.d.comp_info[0].h_samp_factor;
757 sp->v_sampling = (uint16)
758 sp->cinfo.d.comp_info[0].v_samp_factor;
761 /* Rest should have sampling factors 1,1 */
762 for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
763 if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
764 sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
765 TIFFError(module, "Improper JPEG sampling factors");
770 /* PC 2's single component should have sampling factors 1,1 */
771 if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
772 sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
773 TIFFError(module, "Improper JPEG sampling factors");
777 downsampled_output = FALSE;
778 if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
779 sp->photometric == PHOTOMETRIC_YCBCR &&
780 sp->jpegcolormode == JPEGCOLORMODE_RGB) {
781 /* Convert YCbCr to RGB */
782 sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
783 sp->cinfo.d.out_color_space = JCS_RGB;
785 /* Suppress colorspace handling */
786 sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
787 sp->cinfo.d.out_color_space = JCS_UNKNOWN;
788 if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
789 (sp->h_sampling != 1 || sp->v_sampling != 1))
790 downsampled_output = TRUE;
791 /* XXX what about up-sampling? */
793 if (downsampled_output) {
794 /* Need to use raw-data interface to libjpeg */
795 sp->cinfo.d.raw_data_out = TRUE;
796 tif->tif_decoderow = JPEGDecodeRaw;
797 tif->tif_decodestrip = JPEGDecodeRaw;
798 tif->tif_decodetile = JPEGDecodeRaw;
800 /* Use normal interface to libjpeg */
801 sp->cinfo.d.raw_data_out = FALSE;
802 tif->tif_decoderow = JPEGDecode;
803 tif->tif_decodestrip = JPEGDecode;
804 tif->tif_decodetile = JPEGDecode;
806 /* Start JPEG decompressor */
807 if (!TIFFjpeg_start_decompress(sp))
809 /* Allocate downsampled-data buffers if needed */
810 if (downsampled_output) {
811 if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
812 sp->cinfo.d.num_components))
814 sp->scancount = DCTSIZE; /* mark buffer empty */
820 * Decode a chunk of pixels.
821 * "Standard" case: returned data is not downsampled.
823 /*ARGSUSED*/ static int
824 JPEGDecode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
826 JPEGState *sp = JState(tif);
829 nrows = cc / sp->bytesperline;
830 if (cc % sp->bytesperline)
831 TIFFWarning(tif->tif_name, "fractional scanline not read");
833 if( nrows > (int) sp->cinfo.d.image_height )
834 nrows = sp->cinfo.d.image_height;
836 /* data is expected to be read in multiples of a scanline */
840 JSAMPROW bufptr = (JSAMPROW)buf;
842 if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
845 buf += sp->bytesperline;
846 cc -= sp->bytesperline;
847 } while (--nrows > 0);
849 /* Close down the decompressor if we've finished the strip or tile. */
850 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
851 || TIFFjpeg_finish_decompress(sp);
855 * Decode a chunk of pixels.
856 * Returned data is downsampled per sampling factors.
858 /*ARGSUSED*/ static int
859 JPEGDecodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
861 JPEGState *sp = JState(tif);
864 /* data is expected to be read in multiples of a scanline */
865 if ( (nrows = sp->cinfo.d.image_height) ) {
866 /* Cb,Cr both have sampling factors 1, so this is correct */
867 JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
868 int samples_per_clump = sp->samplesperclump;
871 jpeg_component_info *compptr;
874 /* Reload downsampled-data buffer if needed */
875 if (sp->scancount >= DCTSIZE) {
876 int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
878 if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n)
884 * Fastest way to unseparate data is to make one pass
885 * over the scanline for each row of each component.
887 clumpoffset = 0; /* first sample in clump */
888 for (ci = 0, compptr = sp->cinfo.d.comp_info;
889 ci < sp->cinfo.d.num_components;
891 int hsamp = compptr->h_samp_factor;
892 int vsamp = compptr->v_samp_factor;
895 for (ypos = 0; ypos < vsamp; ypos++) {
896 JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
897 JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
901 /* fast path for at least Cb and Cr */
902 for (nclump = clumps_per_line; nclump-- > 0; ) {
903 outptr[0] = *inptr++;
904 outptr += samples_per_clump;
910 for (nclump = clumps_per_line; nclump-- > 0; ) {
911 for (xpos = 0; xpos < hsamp; xpos++)
912 outptr[xpos] = *inptr++;
913 outptr += samples_per_clump;
916 clumpoffset += hsamp;
921 buf += sp->bytesperline;
922 cc -= sp->bytesperline;
923 } while (--nrows > 0);
926 /* Close down the decompressor if done. */
927 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
928 || TIFFjpeg_finish_decompress(sp);
937 unsuppress_quant_table (JPEGState* sp, int tblno)
941 if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
942 qtbl->sent_table = FALSE;
946 unsuppress_huff_table (JPEGState* sp, int tblno)
950 if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
951 htbl->sent_table = FALSE;
952 if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
953 htbl->sent_table = FALSE;
957 prepare_JPEGTables(TIFF* tif)
959 JPEGState* sp = JState(tif);
961 JPEGInitializeLibJPEG( tif );
963 /* Initialize quant tables for current quality setting */
964 if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
966 /* Mark only the tables we want for output */
967 /* NB: chrominance tables are currently used only with YCbCr */
968 if (!TIFFjpeg_suppress_tables(sp, TRUE))
970 if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
971 unsuppress_quant_table(sp, 0);
972 if (sp->photometric == PHOTOMETRIC_YCBCR)
973 unsuppress_quant_table(sp, 1);
975 if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
976 unsuppress_huff_table(sp, 0);
977 if (sp->photometric == PHOTOMETRIC_YCBCR)
978 unsuppress_huff_table(sp, 1);
980 /* Direct libjpeg output into jpegtables */
981 if (!TIFFjpeg_tables_dest(sp, tif))
983 /* Emit tables-only datastream */
984 if (!TIFFjpeg_write_tables(sp))
991 JPEGSetupEncode(TIFF* tif)
993 JPEGState* sp = JState(tif);
994 TIFFDirectory *td = &tif->tif_dir;
995 static const char module[] = "JPEGSetupEncode";
997 JPEGInitializeLibJPEG( tif );
1000 assert(!sp->cinfo.comm.is_decompressor);
1003 * Initialize all JPEG parameters to default values.
1004 * Note that jpeg_set_defaults needs legal values for
1005 * in_color_space and input_components.
1007 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1008 sp->cinfo.c.input_components = 1;
1009 if (!TIFFjpeg_set_defaults(sp))
1011 /* Set per-file parameters */
1012 sp->photometric = td->td_photometric;
1013 switch (sp->photometric) {
1014 case PHOTOMETRIC_YCBCR:
1015 sp->h_sampling = td->td_ycbcrsubsampling[0];
1016 sp->v_sampling = td->td_ycbcrsubsampling[1];
1018 * A ReferenceBlackWhite field *must* be present since the
1019 * default value is inappropriate for YCbCr. Fill in the
1020 * proper value if application didn't set it.
1022 if (!TIFFFieldSet(tif, FIELD_REFBLACKWHITE)) {
1024 long top = 1L << td->td_bitspersample;
1026 refbw[1] = (float)(top-1L);
1027 refbw[2] = (float)(top>>1);
1028 refbw[3] = refbw[1];
1029 refbw[4] = refbw[2];
1030 refbw[5] = refbw[1];
1031 TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE, refbw);
1034 case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */
1035 case PHOTOMETRIC_MASK:
1037 "PhotometricInterpretation %d not allowed for JPEG",
1038 (int) sp->photometric);
1041 /* TIFF 6.0 forbids subsampling of all other color spaces */
1047 /* Verify miscellaneous parameters */
1050 * This would need work if libtiff ever supports different
1051 * depths for different components, or if libjpeg ever supports
1052 * run-time selection of depth. Neither is imminent.
1054 if (td->td_bitspersample != BITS_IN_JSAMPLE) {
1055 TIFFError(module, "BitsPerSample %d not allowed for JPEG",
1056 (int) td->td_bitspersample);
1059 sp->cinfo.c.data_precision = td->td_bitspersample;
1061 if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
1063 "JPEG tile height must be multiple of %d",
1064 sp->v_sampling * DCTSIZE);
1067 if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
1069 "JPEG tile width must be multiple of %d",
1070 sp->h_sampling * DCTSIZE);
1074 if (td->td_rowsperstrip < td->td_imagelength &&
1075 (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
1077 "RowsPerStrip must be multiple of %d for JPEG",
1078 sp->v_sampling * DCTSIZE);
1083 /* Create a JPEGTables field if appropriate */
1084 if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
1085 if (!prepare_JPEGTables(tif))
1087 /* Mark the field present */
1088 /* Can't use TIFFSetField since BEENWRITING is already set! */
1089 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1090 tif->tif_flags |= TIFF_DIRTYDIRECT;
1092 /* We do not support application-supplied JPEGTables, */
1093 /* so mark the field not present */
1094 TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
1097 /* Direct libjpeg output to libtiff's output buffer */
1098 TIFFjpeg_data_dest(sp, tif);
1104 * Set encoding state at the start of a strip or tile.
1107 JPEGPreEncode(TIFF* tif, tsample_t s)
1109 JPEGState *sp = JState(tif);
1110 TIFFDirectory *td = &tif->tif_dir;
1111 static const char module[] = "JPEGPreEncode";
1112 uint32 segment_width, segment_height;
1113 int downsampled_input;
1116 assert(!sp->cinfo.comm.is_decompressor);
1118 * Set encoding parameters for this strip/tile.
1121 segment_width = td->td_tilewidth;
1122 segment_height = td->td_tilelength;
1123 sp->bytesperline = TIFFTileRowSize(tif);
1125 segment_width = td->td_imagewidth;
1126 segment_height = td->td_imagelength - tif->tif_row;
1127 if (segment_height > td->td_rowsperstrip)
1128 segment_height = td->td_rowsperstrip;
1129 sp->bytesperline = TIFFScanlineSize(tif);
1131 if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1132 /* for PC 2, scale down the strip/tile size
1133 * to match a downsampled component
1135 segment_width = TIFFhowmany(segment_width, sp->h_sampling);
1136 segment_height = TIFFhowmany(segment_height, sp->v_sampling);
1138 if (segment_width > 65535 || segment_height > 65535) {
1139 TIFFError(module, "Strip/tile too large for JPEG");
1142 sp->cinfo.c.image_width = segment_width;
1143 sp->cinfo.c.image_height = segment_height;
1144 downsampled_input = FALSE;
1145 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1146 sp->cinfo.c.input_components = td->td_samplesperpixel;
1147 if (sp->photometric == PHOTOMETRIC_YCBCR) {
1148 if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1149 sp->cinfo.c.in_color_space = JCS_RGB;
1151 sp->cinfo.c.in_color_space = JCS_YCbCr;
1152 if (sp->h_sampling != 1 || sp->v_sampling != 1)
1153 downsampled_input = TRUE;
1155 if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
1158 * Set Y sampling factors;
1159 * we assume jpeg_set_colorspace() set the rest to 1
1161 sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
1162 sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
1164 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1165 if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1167 /* jpeg_set_colorspace set all sampling factors to 1 */
1170 sp->cinfo.c.input_components = 1;
1171 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1172 if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1174 sp->cinfo.c.comp_info[0].component_id = s;
1175 /* jpeg_set_colorspace() set sampling factors to 1 */
1176 if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
1177 sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
1178 sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
1179 sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
1182 /* ensure libjpeg won't write any extraneous markers */
1183 sp->cinfo.c.write_JFIF_header = FALSE;
1184 sp->cinfo.c.write_Adobe_marker = FALSE;
1185 /* set up table handling correctly */
1186 if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
1187 if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1189 unsuppress_quant_table(sp, 0);
1190 unsuppress_quant_table(sp, 1);
1192 if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
1193 sp->cinfo.c.optimize_coding = FALSE;
1195 sp->cinfo.c.optimize_coding = TRUE;
1196 if (downsampled_input) {
1197 /* Need to use raw-data interface to libjpeg */
1198 sp->cinfo.c.raw_data_in = TRUE;
1199 tif->tif_encoderow = JPEGEncodeRaw;
1200 tif->tif_encodestrip = JPEGEncodeRaw;
1201 tif->tif_encodetile = JPEGEncodeRaw;
1203 /* Use normal interface to libjpeg */
1204 sp->cinfo.c.raw_data_in = FALSE;
1205 tif->tif_encoderow = JPEGEncode;
1206 tif->tif_encodestrip = JPEGEncode;
1207 tif->tif_encodetile = JPEGEncode;
1209 /* Start JPEG compressor */
1210 if (!TIFFjpeg_start_compress(sp, FALSE))
1212 /* Allocate downsampled-data buffers if needed */
1213 if (downsampled_input) {
1214 if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
1215 sp->cinfo.c.num_components))
1224 * Encode a chunk of pixels.
1225 * "Standard" case: incoming data is not downsampled.
1228 JPEGEncode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
1230 JPEGState *sp = JState(tif);
1236 /* data is expected to be supplied in multiples of a scanline */
1237 nrows = cc / sp->bytesperline;
1238 if (cc % sp->bytesperline)
1239 TIFFWarning(tif->tif_name, "fractional scanline discarded");
1241 while (nrows-- > 0) {
1242 bufptr[0] = (JSAMPROW) buf;
1243 if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
1247 buf += sp->bytesperline;
1253 * Encode a chunk of pixels.
1254 * Incoming data is expected to be downsampled per sampling factors.
1257 JPEGEncodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
1259 JPEGState *sp = JState(tif);
1263 JDIMENSION clumps_per_line, nclump;
1264 int clumpoffset, ci, xpos, ypos;
1265 jpeg_component_info* compptr;
1266 int samples_per_clump = sp->samplesperclump;
1270 /* data is expected to be supplied in multiples of a scanline */
1271 nrows = cc / sp->bytesperline;
1272 if (cc % sp->bytesperline)
1273 TIFFWarning(tif->tif_name, "fractional scanline discarded");
1275 /* Cb,Cr both have sampling factors 1, so this is correct */
1276 clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
1278 while (nrows-- > 0) {
1280 * Fastest way to separate the data is to make one pass
1281 * over the scanline for each row of each component.
1283 clumpoffset = 0; /* first sample in clump */
1284 for (ci = 0, compptr = sp->cinfo.c.comp_info;
1285 ci < sp->cinfo.c.num_components;
1287 int hsamp = compptr->h_samp_factor;
1288 int vsamp = compptr->v_samp_factor;
1289 int padding = (int) (compptr->width_in_blocks * DCTSIZE -
1290 clumps_per_line * hsamp);
1291 for (ypos = 0; ypos < vsamp; ypos++) {
1292 inptr = ((JSAMPLE*) buf) + clumpoffset;
1293 outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1295 /* fast path for at least Cb and Cr */
1296 for (nclump = clumps_per_line; nclump-- > 0; ) {
1297 *outptr++ = inptr[0];
1298 inptr += samples_per_clump;
1302 for (nclump = clumps_per_line; nclump-- > 0; ) {
1303 for (xpos = 0; xpos < hsamp; xpos++)
1304 *outptr++ = inptr[xpos];
1305 inptr += samples_per_clump;
1308 /* pad each scanline as needed */
1309 for (xpos = 0; xpos < padding; xpos++) {
1310 *outptr = outptr[-1];
1313 clumpoffset += hsamp;
1317 if (sp->scancount >= DCTSIZE) {
1318 int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1319 if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1325 buf += sp->bytesperline;
1331 * Finish up at the end of a strip or tile.
1334 JPEGPostEncode(TIFF* tif)
1336 JPEGState *sp = JState(tif);
1338 if (sp->scancount > 0) {
1340 * Need to emit a partial bufferload of downsampled data.
1341 * Pad the data vertically.
1344 jpeg_component_info* compptr;
1346 for (ci = 0, compptr = sp->cinfo.c.comp_info;
1347 ci < sp->cinfo.c.num_components;
1349 int vsamp = compptr->v_samp_factor;
1350 tsize_t row_width = compptr->width_in_blocks * DCTSIZE
1352 for (ypos = sp->scancount * vsamp;
1353 ypos < DCTSIZE * vsamp; ypos++) {
1354 _TIFFmemcpy((tdata_t)sp->ds_buffer[ci][ypos],
1355 (tdata_t)sp->ds_buffer[ci][ypos-1],
1360 n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1361 if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1365 return (TIFFjpeg_finish_compress(JState(tif)));
1369 JPEGCleanup(TIFF* tif)
1371 if (tif->tif_data) {
1372 JPEGState *sp = JState(tif);
1373 if( sp->cinfo_initialized )
1374 TIFFjpeg_destroy(sp); /* release libjpeg resources */
1375 if (sp->jpegtables) /* tag value */
1376 _TIFFfree(sp->jpegtables);
1377 _TIFFfree(tif->tif_data); /* release local state */
1378 tif->tif_data = NULL;
1383 JPEGVSetField(TIFF* tif, ttag_t tag, va_list ap)
1385 JPEGState* sp = JState(tif);
1386 TIFFDirectory* td = &tif->tif_dir;
1390 case TIFFTAG_JPEGTABLES:
1391 v32 = va_arg(ap, uint32);
1396 _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
1398 sp->jpegtables_length = v32;
1399 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1401 case TIFFTAG_JPEGQUALITY:
1402 sp->jpegquality = va_arg(ap, int);
1403 return (1); /* pseudo tag */
1404 case TIFFTAG_JPEGCOLORMODE:
1405 sp->jpegcolormode = va_arg(ap, int);
1407 * Mark whether returned data is up-sampled or not
1408 * so TIFFStripSize and TIFFTileSize return values
1409 * that reflect the true amount of data.
1411 tif->tif_flags &= ~TIFF_UPSAMPLED;
1412 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1413 if (td->td_photometric == PHOTOMETRIC_YCBCR &&
1414 sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1415 tif->tif_flags |= TIFF_UPSAMPLED;
1417 if (td->td_ycbcrsubsampling[0] != 1 ||
1418 td->td_ycbcrsubsampling[1] != 1)
1419 ; /* XXX what about up-sampling? */
1423 * Must recalculate cached tile size
1424 * in case sampling state changed.
1426 tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tsize_t) -1;
1427 return (1); /* pseudo tag */
1428 case TIFFTAG_JPEGTABLESMODE:
1429 sp->jpegtablesmode = va_arg(ap, int);
1430 return (1); /* pseudo tag */
1431 case TIFFTAG_YCBCRSUBSAMPLING:
1432 /* mark the fact that we have a real ycbcrsubsampling! */
1433 sp->ycbcrsampling_fetched = 1;
1434 return (*sp->vsetparent)(tif, tag, ap);
1435 case TIFFTAG_FAXRECVPARAMS:
1436 sp->recvparams = va_arg(ap, uint32);
1438 case TIFFTAG_FAXSUBADDRESS:
1439 _TIFFsetString(&sp->subaddress, va_arg(ap, char*));
1441 case TIFFTAG_FAXRECVTIME:
1442 sp->recvtime = va_arg(ap, uint32);
1444 case TIFFTAG_FAXDCS:
1445 _TIFFsetString(&sp->faxdcs, va_arg(ap, char*));
1448 return (*sp->vsetparent)(tif, tag, ap);
1450 TIFFSetFieldBit(tif, _TIFFFieldWithTag(tif, tag)->field_bit);
1451 tif->tif_flags |= TIFF_DIRTYDIRECT;
1456 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
1457 * the TIFF tags, but still use non-default (2,2) values within the jpeg
1458 * data stream itself. In order for TIFF applications to work properly
1459 * - for instance to get the strip buffer size right - it is imperative
1460 * that the subsampling be available before we start reading the image
1461 * data normally. This function will attempt to load the first strip in
1462 * order to get the sampling values from the jpeg data stream. Various
1463 * hacks are various places are done to ensure this function gets called
1464 * before the td_ycbcrsubsampling values are used from the directory structure,
1465 * including calling TIFFGetField() for the YCBCRSUBSAMPLING field from
1466 * TIFFStripSize(), and the printing code in tif_print.c.
1468 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
1469 * discovered sampling does not match the default sampling (2,2) or whatever
1470 * was actually in the tiff tags.
1473 * o This code will cause one whole strip/tile of compressed data to be
1474 * loaded just to get the tags right, even if the imagery is never read.
1475 * It would be more efficient to just load a bit of the header, and
1476 * initialize things from that.
1478 * See the bug in bugzilla for details:
1480 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
1482 * Frank Warmerdam, July 2002
1486 JPEGFixupTestSubsampling( TIFF * tif )
1488 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
1489 JPEGState *sp = JState(tif);
1490 TIFFDirectory *td = &tif->tif_dir;
1492 JPEGInitializeLibJPEG( tif );
1495 * Some JPEG-in-TIFF files don't provide the ycbcrsampling tags,
1496 * and use a sampling schema other than the default 2,2. To handle
1497 * this we actually have to scan the header of a strip or tile of
1498 * jpeg data to get the sampling.
1500 if( !sp->cinfo.comm.is_decompressor
1501 || sp->ycbcrsampling_fetched
1502 || td->td_photometric != PHOTOMETRIC_YCBCR )
1505 sp->ycbcrsampling_fetched = 1;
1506 if( TIFFIsTiled( tif ) )
1508 if( !TIFFFillTile( tif, 0 ) )
1513 if( !TIFFFillStrip( tif, 0 ) )
1517 TIFFSetField( tif, TIFFTAG_YCBCRSUBSAMPLING,
1518 (uint16) sp->h_sampling, (uint16) sp->v_sampling );
1519 #endif /* CHECK_JPEG_YCBCR_SUBSAMPLING */
1523 JPEGVGetField(TIFF* tif, ttag_t tag, va_list ap)
1525 JPEGState* sp = JState(tif);
1528 case TIFFTAG_JPEGTABLES:
1529 *va_arg(ap, uint32*) = sp->jpegtables_length;
1530 *va_arg(ap, void**) = sp->jpegtables;
1532 case TIFFTAG_JPEGQUALITY:
1533 *va_arg(ap, int*) = sp->jpegquality;
1535 case TIFFTAG_JPEGCOLORMODE:
1536 *va_arg(ap, int*) = sp->jpegcolormode;
1538 case TIFFTAG_JPEGTABLESMODE:
1539 *va_arg(ap, int*) = sp->jpegtablesmode;
1541 case TIFFTAG_YCBCRSUBSAMPLING:
1542 JPEGFixupTestSubsampling( tif );
1543 return (*sp->vgetparent)(tif, tag, ap);
1545 case TIFFTAG_FAXRECVPARAMS:
1546 *va_arg(ap, uint32*) = sp->recvparams;
1548 case TIFFTAG_FAXSUBADDRESS:
1549 *va_arg(ap, char**) = sp->subaddress;
1551 case TIFFTAG_FAXRECVTIME:
1552 *va_arg(ap, uint32*) = sp->recvtime;
1554 case TIFFTAG_FAXDCS:
1555 *va_arg(ap, char**) = sp->faxdcs;
1558 return (*sp->vgetparent)(tif, tag, ap);
1564 JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
1566 JPEGState* sp = JState(tif);
1569 if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
1570 fprintf(fd, " JPEG Tables: (%lu bytes)\n",
1571 (unsigned long) sp->jpegtables_length);
1572 if (TIFFFieldSet(tif,FIELD_RECVPARAMS))
1573 fprintf(fd, " Fax Receive Parameters: %08lx\n",
1574 (unsigned long) sp->recvparams);
1575 if (TIFFFieldSet(tif,FIELD_SUBADDRESS))
1576 fprintf(fd, " Fax SubAddress: %s\n", sp->subaddress);
1577 if (TIFFFieldSet(tif,FIELD_RECVTIME))
1578 fprintf(fd, " Fax Receive Time: %lu secs\n",
1579 (unsigned long) sp->recvtime);
1580 if (TIFFFieldSet(tif,FIELD_FAXDCS))
1581 fprintf(fd, " Fax DCS: %s\n", sp->faxdcs);
1585 JPEGDefaultStripSize(TIFF* tif, uint32 s)
1587 JPEGState* sp = JState(tif);
1588 TIFFDirectory *td = &tif->tif_dir;
1590 s = (*sp->defsparent)(tif, s);
1591 if (s < td->td_imagelength)
1592 s = TIFFroundup(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
1597 JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
1599 JPEGState* sp = JState(tif);
1600 TIFFDirectory *td = &tif->tif_dir;
1602 (*sp->deftparent)(tif, tw, th);
1603 *tw = TIFFroundup(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
1604 *th = TIFFroundup(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
1608 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
1609 * now that we allow a TIFF file to be opened in update mode it is necessary
1610 * to have some way of deciding whether compression or decompression is
1611 * desired other than looking at tif->tif_mode. We accomplish this by
1612 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
1613 * If so, we assume decompression is desired.
1615 * This is tricky, because TIFFInitJPEG() is called while the directory is
1616 * being read, and generally speaking the BYTECOUNTS tag won't have been read
1617 * at that point. So we try to defer jpeg library initialization till we
1618 * do have that tag ... basically any access that might require the compressor
1619 * or decompressor that occurs after the reading of the directory.
1621 * In an ideal world compressors or decompressors would be setup
1622 * at the point where a single tile or strip was accessed (for read or write)
1623 * so that stuff like update of missing tiles, or replacement of tiles could
1624 * be done. However, we aren't trying to crack that nut just yet ...
1626 * NFW, Feb 3rd, 2003.
1629 static int JPEGInitializeLibJPEG( TIFF * tif )
1631 JPEGState* sp = JState(tif);
1632 uint32 *byte_counts = NULL;
1633 int data_is_empty = TRUE;
1635 if( sp->cinfo_initialized )
1639 * Do we have tile data already? Make sure we initialize the
1640 * the state in decompressor mode if we have tile data, even if we
1641 * are not in read-only file access mode.
1643 if( TIFFIsTiled( tif )
1644 && TIFFGetField( tif, TIFFTAG_TILEBYTECOUNTS, &byte_counts )
1645 && byte_counts != NULL )
1647 data_is_empty = byte_counts[0] == 0;
1649 if( !TIFFIsTiled( tif )
1650 && TIFFGetField( tif, TIFFTAG_STRIPBYTECOUNTS, &byte_counts)
1651 && byte_counts != NULL )
1653 data_is_empty = byte_counts[0] == 0;
1657 * Initialize libjpeg.
1659 if (tif->tif_mode == O_RDONLY || !data_is_empty ) {
1660 if (!TIFFjpeg_create_decompress(sp))
1664 if (!TIFFjpeg_create_compress(sp))
1668 sp->cinfo_initialized = TRUE;
1674 TIFFInitJPEG(TIFF* tif, int scheme)
1678 assert(scheme == COMPRESSION_JPEG);
1681 * Allocate state block so tag methods have storage to record values.
1683 tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (JPEGState));
1685 if (tif->tif_data == NULL) {
1686 TIFFError("TIFFInitJPEG", "No space for JPEG state block");
1689 _TIFFmemset( tif->tif_data, 0, sizeof(JPEGState));
1692 sp->tif = tif; /* back link */
1695 * Merge codec-specific tag information and
1696 * override parent get/set field methods.
1698 _TIFFMergeFieldInfo(tif, jpegFieldInfo, N(jpegFieldInfo));
1699 sp->vgetparent = tif->tif_tagmethods.vgetfield;
1700 tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
1701 sp->vsetparent = tif->tif_tagmethods.vsetfield;
1702 tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
1703 tif->tif_tagmethods.printdir = JPEGPrintDir; /* hook for codec tags */
1705 /* Default values for codec-specific fields */
1706 sp->jpegtables = NULL;
1707 sp->jpegtables_length = 0;
1708 sp->jpegquality = 75; /* Default IJG quality */
1709 sp->jpegcolormode = JPEGCOLORMODE_RAW;
1710 sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
1713 sp->subaddress = NULL;
1716 sp->ycbcrsampling_fetched = 0;
1719 * Install codec methods.
1721 tif->tif_setupdecode = JPEGSetupDecode;
1722 tif->tif_predecode = JPEGPreDecode;
1723 tif->tif_decoderow = JPEGDecode;
1724 tif->tif_decodestrip = JPEGDecode;
1725 tif->tif_decodetile = JPEGDecode;
1726 tif->tif_setupencode = JPEGSetupEncode;
1727 tif->tif_preencode = JPEGPreEncode;
1728 tif->tif_postencode = JPEGPostEncode;
1729 tif->tif_encoderow = JPEGEncode;
1730 tif->tif_encodestrip = JPEGEncode;
1731 tif->tif_encodetile = JPEGEncode;
1732 tif->tif_cleanup = JPEGCleanup;
1733 sp->defsparent = tif->tif_defstripsize;
1734 tif->tif_defstripsize = JPEGDefaultStripSize;
1735 sp->deftparent = tif->tif_deftilesize;
1736 tif->tif_deftilesize = JPEGDefaultTileSize;
1737 tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
1739 sp->cinfo_initialized = FALSE;
1742 * Mark the TIFFTAG_YCBCRSAMPLES as present even if it is not
1743 * see: JPEGFixupTestSubsampling().
1745 TIFFSetFieldBit( tif, FIELD_YCBCRSUBSAMPLING );
1749 #endif /* JPEG_SUPPORT */
1751 /* vim: set ts=8 sts=8 sw=8 noet: */