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 #define boolean wxHACK_BOOLEAN
97 #ifndef HAVE_WXJPEG_BOOLEAN
98 typedef boolean wxjpeg_boolean
;
102 * We are using width_in_blocks which is supposed to be private to
103 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
104 * renamed this member to width_in_data_units. Since the header has
105 * also renamed a define, use that unique define name in order to
106 * detect the problem header and adjust to suit.
108 #if defined(D_MAX_DATA_UNITS_IN_MCU)
109 #define width_in_blocks width_in_data_units
113 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
114 * in place of plain setjmp. These macros will make it easier.
116 #define SETJMP(jbuf) setjmp(jbuf)
117 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
118 #define JMP_BUF jmp_buf
120 typedef struct jpeg_destination_mgr jpeg_destination_mgr
;
121 typedef struct jpeg_source_mgr jpeg_source_mgr
;
122 typedef struct jpeg_error_mgr jpeg_error_mgr
;
125 * State block for each open TIFF file using
126 * libjpeg to do JPEG compression/decompression.
128 * libjpeg's visible state is either a jpeg_compress_struct
129 * or jpeg_decompress_struct depending on which way we
130 * are going. comm can be used to refer to the fields
131 * which are common to both.
133 * NB: cinfo is required to be the first member of JPEGState,
134 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
139 struct jpeg_compress_struct c
;
140 struct jpeg_decompress_struct d
;
141 struct jpeg_common_struct comm
;
142 } cinfo
; /* NB: must be first */
143 int cinfo_initialized
;
145 jpeg_error_mgr err
; /* libjpeg error manager */
146 JMP_BUF exit_jmpbuf
; /* for catching libjpeg failures */
148 * The following two members could be a union, but
149 * they're small enough that it's not worth the effort.
151 jpeg_destination_mgr dest
; /* data dest for compression */
152 jpeg_source_mgr src
; /* data source for decompression */
154 TIFF
* tif
; /* back link needed by some code */
155 uint16 photometric
; /* copy of PhotometricInterpretation */
156 uint16 h_sampling
; /* luminance sampling factors */
158 tsize_t bytesperline
; /* decompressed bytes per scanline */
159 /* pointers to intermediate buffers when processing downsampled data */
160 JSAMPARRAY ds_buffer
[MAX_COMPONENTS
];
161 int scancount
; /* number of "scanlines" accumulated */
164 TIFFVGetMethod vgetparent
; /* super-class method */
165 TIFFVSetMethod vsetparent
; /* super-class method */
166 TIFFStripMethod defsparent
; /* super-class method */
167 TIFFTileMethod deftparent
; /* super-class method */
168 /* pseudo-tag fields */
169 void* jpegtables
; /* JPEGTables tag value, or NULL */
170 uint32 jpegtables_length
; /* number of bytes in same */
171 int jpegquality
; /* Compression quality level */
172 int jpegcolormode
; /* Auto RGB<=>YCbCr convert? */
173 int jpegtablesmode
; /* What to put in JPEGTables */
175 int ycbcrsampling_fetched
;
176 uint32 recvparams
; /* encoded Class 2 session params */
177 char* subaddress
; /* subaddress string */
178 uint32 recvtime
; /* time spent receiving (secs) */
179 char* faxdcs
; /* encoded fax parameters (DCS, Table 2/T.30) */
182 #define JState(tif) ((JPEGState*)(tif)->tif_data)
184 static int JPEGDecode(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
185 static int JPEGDecodeRaw(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
186 static int JPEGEncode(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
187 static int JPEGEncodeRaw(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
188 static int JPEGInitializeLibJPEG( TIFF
* tif
,
189 int force_encode
, int force_decode
);
191 #define FIELD_JPEGTABLES (FIELD_CODEC+0)
192 #define FIELD_RECVPARAMS (FIELD_CODEC+1)
193 #define FIELD_SUBADDRESS (FIELD_CODEC+2)
194 #define FIELD_RECVTIME (FIELD_CODEC+3)
195 #define FIELD_FAXDCS (FIELD_CODEC+4)
197 static const TIFFFieldInfo jpegFieldInfo
[] = {
198 { TIFFTAG_JPEGTABLES
, -3,-3, TIFF_UNDEFINED
, FIELD_JPEGTABLES
,
199 FALSE
, TRUE
, "JPEGTables" },
200 { TIFFTAG_JPEGQUALITY
, 0, 0, TIFF_ANY
, FIELD_PSEUDO
,
202 { TIFFTAG_JPEGCOLORMODE
, 0, 0, TIFF_ANY
, FIELD_PSEUDO
,
204 { TIFFTAG_JPEGTABLESMODE
, 0, 0, TIFF_ANY
, FIELD_PSEUDO
,
206 /* Specific for JPEG in faxes */
207 { TIFFTAG_FAXRECVPARAMS
, 1, 1, TIFF_LONG
, FIELD_RECVPARAMS
,
208 TRUE
, FALSE
, "FaxRecvParams" },
209 { TIFFTAG_FAXSUBADDRESS
, -1,-1, TIFF_ASCII
, FIELD_SUBADDRESS
,
210 TRUE
, FALSE
, "FaxSubAddress" },
211 { TIFFTAG_FAXRECVTIME
, 1, 1, TIFF_LONG
, FIELD_RECVTIME
,
212 TRUE
, FALSE
, "FaxRecvTime" },
213 { TIFFTAG_FAXDCS
, -1, -1, TIFF_ASCII
, FIELD_FAXDCS
,
214 TRUE
, FALSE
, "FaxDcs" },
216 #define N(a) (sizeof (a) / sizeof (a[0]))
219 * libjpeg interface layer.
221 * We use setjmp/longjmp to return control to libtiff
222 * when a fatal error is encountered within the JPEG
223 * library. We also direct libjpeg error and warning
224 * messages through the appropriate libtiff handlers.
228 * Error handling routines (these replace corresponding
229 * IJG routines from jerror.c). These are used for both
230 * compression and decompression.
233 TIFFjpeg_error_exit(j_common_ptr cinfo
)
235 JPEGState
*sp
= (JPEGState
*) cinfo
; /* NB: cinfo assumed first */
236 char buffer
[JMSG_LENGTH_MAX
];
238 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
239 TIFFErrorExt(sp
->tif
->tif_clientdata
, "JPEGLib", buffer
); /* display the error message */
240 jpeg_abort(cinfo
); /* clean up libjpeg state */
241 LONGJMP(sp
->exit_jmpbuf
, 1); /* return to libtiff caller */
245 * This routine is invoked only for warning messages,
246 * since error_exit does its own thing and trace_level
250 TIFFjpeg_output_message(j_common_ptr cinfo
)
252 char buffer
[JMSG_LENGTH_MAX
];
254 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
255 TIFFWarningExt(((JPEGState
*) cinfo
)->tif
->tif_clientdata
, "JPEGLib", buffer
);
259 * Interface routines. This layer of routines exists
260 * primarily to limit side-effects from using setjmp.
261 * Also, normal/error returns are converted into return
262 * values per libtiff practice.
264 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
265 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
268 TIFFjpeg_create_compress(JPEGState
* sp
)
270 /* initialize JPEG error handling */
271 sp
->cinfo
.c
.err
= jpeg_std_error(&sp
->err
);
272 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
273 sp
->err
.output_message
= TIFFjpeg_output_message
;
275 return CALLVJPEG(sp
, jpeg_create_compress(&sp
->cinfo
.c
));
279 TIFFjpeg_create_decompress(JPEGState
* sp
)
281 /* initialize JPEG error handling */
282 sp
->cinfo
.d
.err
= jpeg_std_error(&sp
->err
);
283 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
284 sp
->err
.output_message
= TIFFjpeg_output_message
;
286 return CALLVJPEG(sp
, jpeg_create_decompress(&sp
->cinfo
.d
));
290 TIFFjpeg_set_defaults(JPEGState
* sp
)
292 return CALLVJPEG(sp
, jpeg_set_defaults(&sp
->cinfo
.c
));
296 TIFFjpeg_set_colorspace(JPEGState
* sp
, J_COLOR_SPACE colorspace
)
298 return CALLVJPEG(sp
, jpeg_set_colorspace(&sp
->cinfo
.c
, colorspace
));
302 TIFFjpeg_set_quality(JPEGState
* sp
, int quality
, wxjpeg_boolean force_baseline
)
305 jpeg_set_quality(&sp
->cinfo
.c
, quality
, force_baseline
));
309 TIFFjpeg_suppress_tables(JPEGState
* sp
, wxjpeg_boolean suppress
)
311 return CALLVJPEG(sp
, jpeg_suppress_tables(&sp
->cinfo
.c
, suppress
));
315 TIFFjpeg_start_compress(JPEGState
* sp
, wxjpeg_boolean write_all_tables
)
318 jpeg_start_compress(&sp
->cinfo
.c
, write_all_tables
));
322 TIFFjpeg_write_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int num_lines
)
324 return CALLJPEG(sp
, -1, (int) jpeg_write_scanlines(&sp
->cinfo
.c
,
325 scanlines
, (JDIMENSION
) num_lines
));
329 TIFFjpeg_write_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int num_lines
)
331 return CALLJPEG(sp
, -1, (int) jpeg_write_raw_data(&sp
->cinfo
.c
,
332 data
, (JDIMENSION
) num_lines
));
336 TIFFjpeg_finish_compress(JPEGState
* sp
)
338 return CALLVJPEG(sp
, jpeg_finish_compress(&sp
->cinfo
.c
));
342 TIFFjpeg_write_tables(JPEGState
* sp
)
344 return CALLVJPEG(sp
, jpeg_write_tables(&sp
->cinfo
.c
));
348 TIFFjpeg_read_header(JPEGState
* sp
, wxjpeg_boolean require_image
)
350 return CALLJPEG(sp
, -1, jpeg_read_header(&sp
->cinfo
.d
, require_image
));
354 TIFFjpeg_start_decompress(JPEGState
* sp
)
356 return CALLVJPEG(sp
, jpeg_start_decompress(&sp
->cinfo
.d
));
360 TIFFjpeg_read_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int max_lines
)
362 return CALLJPEG(sp
, -1, (int) jpeg_read_scanlines(&sp
->cinfo
.d
,
363 scanlines
, (JDIMENSION
) max_lines
));
367 TIFFjpeg_read_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int max_lines
)
369 return CALLJPEG(sp
, -1, (int) jpeg_read_raw_data(&sp
->cinfo
.d
,
370 data
, (JDIMENSION
) max_lines
));
374 TIFFjpeg_finish_decompress(JPEGState
* sp
)
376 return CALLJPEG(sp
, -1, (int) jpeg_finish_decompress(&sp
->cinfo
.d
));
380 TIFFjpeg_abort(JPEGState
* sp
)
382 return CALLVJPEG(sp
, jpeg_abort(&sp
->cinfo
.comm
));
386 TIFFjpeg_destroy(JPEGState
* sp
)
388 return CALLVJPEG(sp
, jpeg_destroy(&sp
->cinfo
.comm
));
392 TIFFjpeg_alloc_sarray(JPEGState
* sp
, int pool_id
,
393 JDIMENSION samplesperrow
, JDIMENSION numrows
)
395 return CALLJPEG(sp
, (JSAMPARRAY
) NULL
,
396 (*sp
->cinfo
.comm
.mem
->alloc_sarray
)
397 (&sp
->cinfo
.comm
, pool_id
, samplesperrow
, numrows
));
401 * JPEG library destination data manager.
402 * These routines direct compressed data from libjpeg into the
403 * libtiff output buffer.
407 std_init_destination(j_compress_ptr cinfo
)
409 JPEGState
* sp
= (JPEGState
*) cinfo
;
412 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
413 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
416 static wxjpeg_boolean
417 std_empty_output_buffer(j_compress_ptr cinfo
)
419 JPEGState
* sp
= (JPEGState
*) cinfo
;
422 /* the entire buffer has been filled */
423 tif
->tif_rawcc
= tif
->tif_rawdatasize
;
425 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
426 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
432 std_term_destination(j_compress_ptr cinfo
)
434 JPEGState
* sp
= (JPEGState
*) cinfo
;
437 tif
->tif_rawcp
= (tidata_t
) sp
->dest
.next_output_byte
;
439 tif
->tif_rawdatasize
- (tsize_t
) sp
->dest
.free_in_buffer
;
440 /* NB: libtiff does the final buffer flush */
444 TIFFjpeg_data_dest(JPEGState
* sp
, TIFF
* tif
)
447 sp
->cinfo
.c
.dest
= &sp
->dest
;
448 sp
->dest
.init_destination
= std_init_destination
;
449 sp
->dest
.empty_output_buffer
= std_empty_output_buffer
;
450 sp
->dest
.term_destination
= std_term_destination
;
454 * Alternate destination manager for outputting to JPEGTables field.
458 tables_init_destination(j_compress_ptr cinfo
)
460 JPEGState
* sp
= (JPEGState
*) cinfo
;
462 /* while building, jpegtables_length is allocated buffer size */
463 sp
->dest
.next_output_byte
= (JOCTET
*) sp
->jpegtables
;
464 sp
->dest
.free_in_buffer
= (size_t) sp
->jpegtables_length
;
467 static wxjpeg_boolean
468 tables_empty_output_buffer(j_compress_ptr cinfo
)
470 JPEGState
* sp
= (JPEGState
*) cinfo
;
473 /* the entire buffer has been filled; enlarge it by 1000 bytes */
474 newbuf
= _TIFFrealloc((tdata_t
) sp
->jpegtables
,
475 (tsize_t
) (sp
->jpegtables_length
+ 1000));
477 ERREXIT1(cinfo
, JERR_OUT_OF_MEMORY
, 100);
478 sp
->dest
.next_output_byte
= (JOCTET
*) newbuf
+ sp
->jpegtables_length
;
479 sp
->dest
.free_in_buffer
= (size_t) 1000;
480 sp
->jpegtables
= newbuf
;
481 sp
->jpegtables_length
+= 1000;
486 tables_term_destination(j_compress_ptr cinfo
)
488 JPEGState
* sp
= (JPEGState
*) cinfo
;
490 /* set tables length to number of bytes actually emitted */
491 sp
->jpegtables_length
-= sp
->dest
.free_in_buffer
;
495 TIFFjpeg_tables_dest(JPEGState
* sp
, TIFF
* tif
)
499 * Allocate a working buffer for building tables.
500 * Initial size is 1000 bytes, which is usually adequate.
503 _TIFFfree(sp
->jpegtables
);
504 sp
->jpegtables_length
= 1000;
505 sp
->jpegtables
= (void*) _TIFFmalloc((tsize_t
) sp
->jpegtables_length
);
506 if (sp
->jpegtables
== NULL
) {
507 sp
->jpegtables_length
= 0;
508 TIFFErrorExt(sp
->tif
->tif_clientdata
, "TIFFjpeg_tables_dest", "No space for JPEGTables");
511 sp
->cinfo
.c
.dest
= &sp
->dest
;
512 sp
->dest
.init_destination
= tables_init_destination
;
513 sp
->dest
.empty_output_buffer
= tables_empty_output_buffer
;
514 sp
->dest
.term_destination
= tables_term_destination
;
519 * JPEG library source data manager.
520 * These routines supply compressed data to libjpeg.
524 std_init_source(j_decompress_ptr cinfo
)
526 JPEGState
* sp
= (JPEGState
*) cinfo
;
529 sp
->src
.next_input_byte
= (const JOCTET
*) tif
->tif_rawdata
;
530 sp
->src
.bytes_in_buffer
= (size_t) tif
->tif_rawcc
;
533 static wxjpeg_boolean
534 std_fill_input_buffer(j_decompress_ptr cinfo
)
536 JPEGState
* sp
= (JPEGState
* ) cinfo
;
537 static const JOCTET dummy_EOI
[2] = { 0xFF, JPEG_EOI
};
540 * Should never get here since entire strip/tile is
541 * read into memory before the decompressor is called,
542 * and thus was supplied by init_source.
544 WARNMS(cinfo
, JWRN_JPEG_EOF
);
545 /* insert a fake EOI marker */
546 sp
->src
.next_input_byte
= dummy_EOI
;
547 sp
->src
.bytes_in_buffer
= 2;
552 std_skip_input_data(j_decompress_ptr cinfo
, long num_bytes
)
554 JPEGState
* sp
= (JPEGState
*) cinfo
;
557 if (num_bytes
> (long) sp
->src
.bytes_in_buffer
) {
558 /* oops, buffer overrun */
559 (void) std_fill_input_buffer(cinfo
);
561 sp
->src
.next_input_byte
+= (size_t) num_bytes
;
562 sp
->src
.bytes_in_buffer
-= (size_t) num_bytes
;
568 std_term_source(j_decompress_ptr cinfo
)
570 /* No work necessary here */
571 /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
572 /* (if so, need empty tables_term_source!) */
577 TIFFjpeg_data_src(JPEGState
* sp
, TIFF
* tif
)
580 sp
->cinfo
.d
.src
= &sp
->src
;
581 sp
->src
.init_source
= std_init_source
;
582 sp
->src
.fill_input_buffer
= std_fill_input_buffer
;
583 sp
->src
.skip_input_data
= std_skip_input_data
;
584 sp
->src
.resync_to_restart
= jpeg_resync_to_restart
;
585 sp
->src
.term_source
= std_term_source
;
586 sp
->src
.bytes_in_buffer
= 0; /* for safety */
587 sp
->src
.next_input_byte
= NULL
;
591 * Alternate source manager for reading from JPEGTables.
592 * We can share all the code except for the init routine.
596 tables_init_source(j_decompress_ptr cinfo
)
598 JPEGState
* sp
= (JPEGState
*) cinfo
;
600 sp
->src
.next_input_byte
= (const JOCTET
*) sp
->jpegtables
;
601 sp
->src
.bytes_in_buffer
= (size_t) sp
->jpegtables_length
;
605 TIFFjpeg_tables_src(JPEGState
* sp
, TIFF
* tif
)
607 TIFFjpeg_data_src(sp
, tif
);
608 sp
->src
.init_source
= tables_init_source
;
612 * Allocate downsampled-data buffers needed for downsampled I/O.
613 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
614 * We use libjpeg's allocator so that buffers will be released automatically
615 * when done with strip/tile.
616 * This is also a handy place to compute samplesperclump, bytesperline.
619 alloc_downsampled_buffers(TIFF
* tif
, jpeg_component_info
* comp_info
,
622 JPEGState
* sp
= JState(tif
);
624 jpeg_component_info
* compptr
;
626 int samples_per_clump
= 0;
628 for (ci
= 0, compptr
= comp_info
; ci
< num_components
;
630 samples_per_clump
+= compptr
->h_samp_factor
*
631 compptr
->v_samp_factor
;
632 buf
= TIFFjpeg_alloc_sarray(sp
, JPOOL_IMAGE
,
633 compptr
->width_in_blocks
* DCTSIZE
,
634 (JDIMENSION
) (compptr
->v_samp_factor
*DCTSIZE
));
637 sp
->ds_buffer
[ci
] = buf
;
639 sp
->samplesperclump
= samples_per_clump
;
649 JPEGSetupDecode(TIFF
* tif
)
651 JPEGState
* sp
= JState(tif
);
652 TIFFDirectory
*td
= &tif
->tif_dir
;
654 JPEGInitializeLibJPEG( tif
, 0, 1 );
657 assert(sp
->cinfo
.comm
.is_decompressor
);
659 /* Read JPEGTables if it is present */
660 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
)) {
661 TIFFjpeg_tables_src(sp
, tif
);
662 if(TIFFjpeg_read_header(sp
,FALSE
) != JPEG_HEADER_TABLES_ONLY
) {
663 TIFFErrorExt(tif
->tif_clientdata
, "JPEGSetupDecode", "Bogus JPEGTables field");
668 /* Grab parameters that are same for all strips/tiles */
669 sp
->photometric
= td
->td_photometric
;
670 switch (sp
->photometric
) {
671 case PHOTOMETRIC_YCBCR
:
672 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
673 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
676 /* TIFF 6.0 forbids subsampling of all other color spaces */
682 /* Set up for reading normal data */
683 TIFFjpeg_data_src(sp
, tif
);
684 tif
->tif_postdecode
= _TIFFNoPostDecode
; /* override byte swapping */
689 * Set up for decoding a strip or tile.
692 JPEGPreDecode(TIFF
* tif
, tsample_t s
)
694 JPEGState
*sp
= JState(tif
);
695 TIFFDirectory
*td
= &tif
->tif_dir
;
696 static const char module[] = "JPEGPreDecode";
697 uint32 segment_width
, segment_height
;
698 int downsampled_output
;
702 assert(sp
->cinfo
.comm
.is_decompressor
);
704 * Reset decoder state from any previous strip/tile,
705 * in case application didn't read the whole strip.
707 if (!TIFFjpeg_abort(sp
))
710 * Read the header for this strip/tile.
712 if (TIFFjpeg_read_header(sp
, TRUE
) != JPEG_HEADER_OK
)
715 * Check image parameters and set decompression parameters.
717 segment_width
= td
->td_imagewidth
;
718 segment_height
= td
->td_imagelength
- tif
->tif_row
;
720 segment_width
= td
->td_tilewidth
;
721 segment_height
= td
->td_tilelength
;
722 sp
->bytesperline
= TIFFTileRowSize(tif
);
724 if (segment_height
> td
->td_rowsperstrip
)
725 segment_height
= td
->td_rowsperstrip
;
726 sp
->bytesperline
= TIFFScanlineSize(tif
);
728 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
730 * For PC 2, scale down the expected strip/tile size
731 * to match a downsampled component
733 segment_width
= TIFFhowmany(segment_width
, sp
->h_sampling
);
734 segment_height
= TIFFhowmany(segment_height
, sp
->v_sampling
);
736 if (sp
->cinfo
.d
.image_width
!= segment_width
||
737 sp
->cinfo
.d
.image_height
!= segment_height
) {
738 TIFFWarningExt(tif
->tif_clientdata
, module,
739 "Improper JPEG strip/tile size, expected %dx%d, got %dx%d",
742 sp
->cinfo
.d
.image_width
,
743 sp
->cinfo
.d
.image_height
);
745 if (sp
->cinfo
.d
.num_components
!=
746 (td
->td_planarconfig
== PLANARCONFIG_CONTIG
?
747 td
->td_samplesperpixel
: 1)) {
748 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG component count");
752 if (12 != td
->td_bitspersample
&& 8 != td
->td_bitspersample
) {
753 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG data precision");
756 sp
->cinfo
.d
.data_precision
= td
->td_bitspersample
;
757 sp
->cinfo
.d
.bits_in_jsample
= td
->td_bitspersample
;
759 if (sp
->cinfo
.d
.data_precision
!= td
->td_bitspersample
) {
760 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG data precision");
764 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
765 /* Component 0 should have expected sampling factors */
766 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= sp
->h_sampling
||
767 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= sp
->v_sampling
) {
768 TIFFWarningExt(tif
->tif_clientdata
, module,
769 "Improper JPEG sampling factors %d,%d\n"
770 "Apparently should be %d,%d.",
771 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
,
772 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
,
773 sp
->h_sampling
, sp
->v_sampling
);
776 * XXX: Files written by the Intergraph software
777 * has different sampling factors stored in the
778 * TIFF tags and in the JPEG structures. We will
779 * try to deduce Intergraph files by the presense
782 if (!_TIFFFindFieldInfo(tif
, 33918, TIFF_ANY
)) {
783 TIFFWarningExt(tif
->tif_clientdata
, module,
784 "Decompressor will try reading with "
786 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
,
787 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
);
789 sp
->h_sampling
= (uint16
)
790 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
;
791 sp
->v_sampling
= (uint16
)
792 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
;
795 /* Rest should have sampling factors 1,1 */
796 for (ci
= 1; ci
< sp
->cinfo
.d
.num_components
; ci
++) {
797 if (sp
->cinfo
.d
.comp_info
[ci
].h_samp_factor
!= 1 ||
798 sp
->cinfo
.d
.comp_info
[ci
].v_samp_factor
!= 1) {
799 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG sampling factors");
804 /* PC 2's single component should have sampling factors 1,1 */
805 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= 1 ||
806 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= 1) {
807 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG sampling factors");
811 downsampled_output
= FALSE
;
812 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
813 sp
->photometric
== PHOTOMETRIC_YCBCR
&&
814 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
815 /* Convert YCbCr to RGB */
816 sp
->cinfo
.d
.jpeg_color_space
= JCS_YCbCr
;
817 sp
->cinfo
.d
.out_color_space
= JCS_RGB
;
819 /* Suppress colorspace handling */
820 sp
->cinfo
.d
.jpeg_color_space
= JCS_UNKNOWN
;
821 sp
->cinfo
.d
.out_color_space
= JCS_UNKNOWN
;
822 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
823 (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1))
824 downsampled_output
= TRUE
;
825 /* XXX what about up-sampling? */
827 if (downsampled_output
) {
828 /* Need to use raw-data interface to libjpeg */
829 sp
->cinfo
.d
.raw_data_out
= TRUE
;
830 tif
->tif_decoderow
= JPEGDecodeRaw
;
831 tif
->tif_decodestrip
= JPEGDecodeRaw
;
832 tif
->tif_decodetile
= JPEGDecodeRaw
;
834 /* Use normal interface to libjpeg */
835 sp
->cinfo
.d
.raw_data_out
= FALSE
;
836 tif
->tif_decoderow
= JPEGDecode
;
837 tif
->tif_decodestrip
= JPEGDecode
;
838 tif
->tif_decodetile
= JPEGDecode
;
840 /* Start JPEG decompressor */
841 if (!TIFFjpeg_start_decompress(sp
))
843 /* Allocate downsampled-data buffers if needed */
844 if (downsampled_output
) {
845 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.d
.comp_info
,
846 sp
->cinfo
.d
.num_components
))
848 sp
->scancount
= DCTSIZE
; /* mark buffer empty */
854 * Decode a chunk of pixels.
855 * "Standard" case: returned data is not downsampled.
857 /*ARGSUSED*/ static int
858 JPEGDecode(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
860 JPEGState
*sp
= JState(tif
);
864 nrows
= cc
/ sp
->bytesperline
;
865 if (cc
% sp
->bytesperline
)
866 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline not read");
868 if( nrows
> (int) sp
->cinfo
.d
.image_height
)
869 nrows
= sp
->cinfo
.d
.image_height
;
871 /* data is expected to be read in multiples of a scanline */
874 JSAMPROW line_work_buf
= NULL
;
877 ** For 6B, only use temporary buffer for 12 bit imagery.
878 ** For Mk1 always use it.
880 #if !defined(JPEG_LIB_MK1)
881 if( sp
->cinfo
.d
.data_precision
== 12 )
884 line_work_buf
= (JSAMPROW
)
885 _TIFFmalloc(sizeof(short) * sp
->cinfo
.d
.output_width
886 * sp
->cinfo
.d
.num_components
);
890 if( line_work_buf
!= NULL
)
893 ** In the MK1 case, we aways read into a 16bit buffer, and then
894 ** pack down to 12bit or 8bit. In 6B case we only read into 16
895 ** bit buffer for 12bit data, which we need to repack.
897 if (TIFFjpeg_read_scanlines(sp
, &line_work_buf
, 1) != 1)
900 if( sp
->cinfo
.d
.data_precision
== 12 )
902 int value_pairs
= (sp
->cinfo
.d
.output_width
903 * sp
->cinfo
.d
.num_components
) / 2;
906 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
908 unsigned char *out_ptr
=
909 ((unsigned char *) buf
) + iPair
* 3;
910 JSAMPLE
*in_ptr
= line_work_buf
+ iPair
* 2;
912 out_ptr
[0] = (in_ptr
[0] & 0xff0) >> 4;
913 out_ptr
[1] = ((in_ptr
[0] & 0xf) << 4)
914 | ((in_ptr
[1] & 0xf00) >> 8);
915 out_ptr
[2] = ((in_ptr
[1] & 0xff) >> 0);
918 else if( sp
->cinfo
.d
.data_precision
== 8 )
920 int value_count
= (sp
->cinfo
.d
.output_width
921 * sp
->cinfo
.d
.num_components
);
924 for( iValue
= 0; iValue
< value_count
; iValue
++ )
926 ((unsigned char *) buf
)[iValue
] =
927 line_work_buf
[iValue
] & 0xff;
934 ** In the libjpeg6b 8bit case. We read directly into the
937 JSAMPROW bufptr
= (JSAMPROW
)buf
;
939 if (TIFFjpeg_read_scanlines(sp
, &bufptr
, 1) != 1)
944 buf
+= sp
->bytesperline
;
945 cc
-= sp
->bytesperline
;
946 } while (--nrows
> 0);
948 if( line_work_buf
!= NULL
)
949 _TIFFfree( line_work_buf
);
952 /* Close down the decompressor if we've finished the strip or tile. */
953 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
954 || TIFFjpeg_finish_decompress(sp
);
958 * Decode a chunk of pixels.
959 * Returned data is downsampled per sampling factors.
961 /*ARGSUSED*/ static int
962 JPEGDecodeRaw(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
964 JPEGState
*sp
= JState(tif
);
968 /* data is expected to be read in multiples of a scanline */
969 if ( (nrows
= sp
->cinfo
.d
.image_height
) ) {
970 /* Cb,Cr both have sampling factors 1, so this is correct */
971 JDIMENSION clumps_per_line
= sp
->cinfo
.d
.comp_info
[1].downsampled_width
;
972 int samples_per_clump
= sp
->samplesperclump
;
975 unsigned short* tmpbuf
= _TIFFmalloc(sizeof(unsigned short) *
976 sp
->cinfo
.d
.output_width
*
977 sp
->cinfo
.d
.num_components
);
981 jpeg_component_info
*compptr
;
984 /* Reload downsampled-data buffer if needed */
985 if (sp
->scancount
>= DCTSIZE
) {
986 int n
= sp
->cinfo
.d
.max_v_samp_factor
* DCTSIZE
;
987 if (TIFFjpeg_read_raw_data(sp
, sp
->ds_buffer
, n
)
993 * Fastest way to unseparate data is to make one pass
994 * over the scanline for each row of each component.
996 clumpoffset
= 0; /* first sample in clump */
997 for (ci
= 0, compptr
= sp
->cinfo
.d
.comp_info
;
998 ci
< sp
->cinfo
.d
.num_components
;
1000 int hsamp
= compptr
->h_samp_factor
;
1001 int vsamp
= compptr
->v_samp_factor
;
1004 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
1005 JSAMPLE
*inptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
1007 JSAMPLE
*outptr
= (JSAMPLE
*)tmpbuf
+ clumpoffset
;
1009 JSAMPLE
*outptr
= (JSAMPLE
*)buf
+ clumpoffset
;
1014 /* fast path for at least Cb and Cr */
1015 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1016 outptr
[0] = *inptr
++;
1017 outptr
+= samples_per_clump
;
1023 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1024 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1025 outptr
[xpos
] = *inptr
++;
1026 outptr
+= samples_per_clump
;
1029 clumpoffset
+= hsamp
;
1035 if (sp
->cinfo
.d
.data_precision
== 8)
1038 int len
= sp
->cinfo
.d
.output_width
* sp
->cinfo
.d
.num_components
;
1039 for (i
=0; i
<len
; i
++)
1041 ((unsigned char*)buf
)[i
] = tmpbuf
[i
] & 0xff;
1046 int value_pairs
= (sp
->cinfo
.d
.output_width
1047 * sp
->cinfo
.d
.num_components
) / 2;
1049 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1051 unsigned char *out_ptr
= ((unsigned char *) buf
) + iPair
* 3;
1052 JSAMPLE
*in_ptr
= tmpbuf
+ iPair
* 2;
1053 out_ptr
[0] = (in_ptr
[0] & 0xff0) >> 4;
1054 out_ptr
[1] = ((in_ptr
[0] & 0xf) << 4)
1055 | ((in_ptr
[1] & 0xf00) >> 8);
1056 out_ptr
[2] = ((in_ptr
[1] & 0xff) >> 0);
1064 buf
+= sp
->bytesperline
;
1065 cc
-= sp
->bytesperline
;
1066 } while (--nrows
> 0);
1074 /* Close down the decompressor if done. */
1075 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
1076 || TIFFjpeg_finish_decompress(sp
);
1085 unsuppress_quant_table (JPEGState
* sp
, int tblno
)
1089 if ((qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[tblno
]) != NULL
)
1090 qtbl
->sent_table
= FALSE
;
1094 unsuppress_huff_table (JPEGState
* sp
, int tblno
)
1098 if ((htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[tblno
]) != NULL
)
1099 htbl
->sent_table
= FALSE
;
1100 if ((htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[tblno
]) != NULL
)
1101 htbl
->sent_table
= FALSE
;
1105 prepare_JPEGTables(TIFF
* tif
)
1107 JPEGState
* sp
= JState(tif
);
1109 JPEGInitializeLibJPEG( tif
, 0, 0 );
1111 /* Initialize quant tables for current quality setting */
1112 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1114 /* Mark only the tables we want for output */
1115 /* NB: chrominance tables are currently used only with YCbCr */
1116 if (!TIFFjpeg_suppress_tables(sp
, TRUE
))
1118 if (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
) {
1119 unsuppress_quant_table(sp
, 0);
1120 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1121 unsuppress_quant_table(sp
, 1);
1123 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
) {
1124 unsuppress_huff_table(sp
, 0);
1125 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1126 unsuppress_huff_table(sp
, 1);
1128 /* Direct libjpeg output into jpegtables */
1129 if (!TIFFjpeg_tables_dest(sp
, tif
))
1131 /* Emit tables-only datastream */
1132 if (!TIFFjpeg_write_tables(sp
))
1139 JPEGSetupEncode(TIFF
* tif
)
1141 JPEGState
* sp
= JState(tif
);
1142 TIFFDirectory
*td
= &tif
->tif_dir
;
1143 static const char module[] = "JPEGSetupEncode";
1145 JPEGInitializeLibJPEG( tif
, 1, 0 );
1148 assert(!sp
->cinfo
.comm
.is_decompressor
);
1151 * Initialize all JPEG parameters to default values.
1152 * Note that jpeg_set_defaults needs legal values for
1153 * in_color_space and input_components.
1155 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1156 sp
->cinfo
.c
.input_components
= 1;
1157 if (!TIFFjpeg_set_defaults(sp
))
1159 /* Set per-file parameters */
1160 sp
->photometric
= td
->td_photometric
;
1161 switch (sp
->photometric
) {
1162 case PHOTOMETRIC_YCBCR
:
1163 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
1164 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
1166 * A ReferenceBlackWhite field *must* be present since the
1167 * default value is inappropriate for YCbCr. Fill in the
1168 * proper value if application didn't set it.
1172 if (!TIFFGetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1175 long top
= 1L << td
->td_bitspersample
;
1177 refbw
[1] = (float)(top
-1L);
1178 refbw
[2] = (float)(top
>>1);
1179 refbw
[3] = refbw
[1];
1180 refbw
[4] = refbw
[2];
1181 refbw
[5] = refbw
[1];
1182 TIFFSetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1187 case PHOTOMETRIC_PALETTE
: /* disallowed by Tech Note */
1188 case PHOTOMETRIC_MASK
:
1189 TIFFErrorExt(tif
->tif_clientdata
, module,
1190 "PhotometricInterpretation %d not allowed for JPEG",
1191 (int) sp
->photometric
);
1194 /* TIFF 6.0 forbids subsampling of all other color spaces */
1200 /* Verify miscellaneous parameters */
1203 * This would need work if libtiff ever supports different
1204 * depths for different components, or if libjpeg ever supports
1205 * run-time selection of depth. Neither is imminent.
1208 /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1209 if (td
->td_bitspersample
!= 8 && td
->td_bitspersample
!= 12)
1211 if (td
->td_bitspersample
!= BITS_IN_JSAMPLE
)
1214 TIFFErrorExt(tif
->tif_clientdata
, module, "BitsPerSample %d not allowed for JPEG",
1215 (int) td
->td_bitspersample
);
1218 sp
->cinfo
.c
.data_precision
= td
->td_bitspersample
;
1220 sp
->cinfo
.c
.bits_in_jsample
= td
->td_bitspersample
;
1223 if ((td
->td_tilelength
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1224 TIFFErrorExt(tif
->tif_clientdata
, module,
1225 "JPEG tile height must be multiple of %d",
1226 sp
->v_sampling
* DCTSIZE
);
1229 if ((td
->td_tilewidth
% (sp
->h_sampling
* DCTSIZE
)) != 0) {
1230 TIFFErrorExt(tif
->tif_clientdata
, module,
1231 "JPEG tile width must be multiple of %d",
1232 sp
->h_sampling
* DCTSIZE
);
1236 if (td
->td_rowsperstrip
< td
->td_imagelength
&&
1237 (td
->td_rowsperstrip
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1238 TIFFErrorExt(tif
->tif_clientdata
, module,
1239 "RowsPerStrip must be multiple of %d for JPEG",
1240 sp
->v_sampling
* DCTSIZE
);
1245 /* Create a JPEGTables field if appropriate */
1246 if (sp
->jpegtablesmode
& (JPEGTABLESMODE_QUANT
|JPEGTABLESMODE_HUFF
)) {
1247 if (!prepare_JPEGTables(tif
))
1249 /* Mark the field present */
1250 /* Can't use TIFFSetField since BEENWRITING is already set! */
1251 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1252 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1254 /* We do not support application-supplied JPEGTables, */
1255 /* so mark the field not present */
1256 TIFFClrFieldBit(tif
, FIELD_JPEGTABLES
);
1259 /* Direct libjpeg output to libtiff's output buffer */
1260 TIFFjpeg_data_dest(sp
, tif
);
1266 * Set encoding state at the start of a strip or tile.
1269 JPEGPreEncode(TIFF
* tif
, tsample_t s
)
1271 JPEGState
*sp
= JState(tif
);
1272 TIFFDirectory
*td
= &tif
->tif_dir
;
1273 static const char module[] = "JPEGPreEncode";
1274 uint32 segment_width
, segment_height
;
1275 int downsampled_input
;
1278 assert(!sp
->cinfo
.comm
.is_decompressor
);
1280 * Set encoding parameters for this strip/tile.
1283 segment_width
= td
->td_tilewidth
;
1284 segment_height
= td
->td_tilelength
;
1285 sp
->bytesperline
= TIFFTileRowSize(tif
);
1287 segment_width
= td
->td_imagewidth
;
1288 segment_height
= td
->td_imagelength
- tif
->tif_row
;
1289 if (segment_height
> td
->td_rowsperstrip
)
1290 segment_height
= td
->td_rowsperstrip
;
1291 sp
->bytesperline
= TIFFScanlineSize(tif
);
1293 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
1294 /* for PC 2, scale down the strip/tile size
1295 * to match a downsampled component
1297 segment_width
= TIFFhowmany(segment_width
, sp
->h_sampling
);
1298 segment_height
= TIFFhowmany(segment_height
, sp
->v_sampling
);
1300 if (segment_width
> 65535 || segment_height
> 65535) {
1301 TIFFErrorExt(tif
->tif_clientdata
, module, "Strip/tile too large for JPEG");
1304 sp
->cinfo
.c
.image_width
= segment_width
;
1305 sp
->cinfo
.c
.image_height
= segment_height
;
1306 downsampled_input
= FALSE
;
1307 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1308 sp
->cinfo
.c
.input_components
= td
->td_samplesperpixel
;
1309 if (sp
->photometric
== PHOTOMETRIC_YCBCR
) {
1310 if (sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1311 sp
->cinfo
.c
.in_color_space
= JCS_RGB
;
1313 sp
->cinfo
.c
.in_color_space
= JCS_YCbCr
;
1314 if (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1)
1315 downsampled_input
= TRUE
;
1317 if (!TIFFjpeg_set_colorspace(sp
, JCS_YCbCr
))
1320 * Set Y sampling factors;
1321 * we assume jpeg_set_colorspace() set the rest to 1
1323 sp
->cinfo
.c
.comp_info
[0].h_samp_factor
= sp
->h_sampling
;
1324 sp
->cinfo
.c
.comp_info
[0].v_samp_factor
= sp
->v_sampling
;
1326 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1327 if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
))
1329 /* jpeg_set_colorspace set all sampling factors to 1 */
1332 sp
->cinfo
.c
.input_components
= 1;
1333 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1334 if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
))
1336 sp
->cinfo
.c
.comp_info
[0].component_id
= s
;
1337 /* jpeg_set_colorspace() set sampling factors to 1 */
1338 if (sp
->photometric
== PHOTOMETRIC_YCBCR
&& s
> 0) {
1339 sp
->cinfo
.c
.comp_info
[0].quant_tbl_no
= 1;
1340 sp
->cinfo
.c
.comp_info
[0].dc_tbl_no
= 1;
1341 sp
->cinfo
.c
.comp_info
[0].ac_tbl_no
= 1;
1344 /* ensure libjpeg won't write any extraneous markers */
1345 sp
->cinfo
.c
.write_JFIF_header
= FALSE
;
1346 sp
->cinfo
.c
.write_Adobe_marker
= FALSE
;
1347 /* set up table handling correctly */
1348 if (! (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
)) {
1349 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1351 unsuppress_quant_table(sp
, 0);
1352 unsuppress_quant_table(sp
, 1);
1354 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
)
1355 sp
->cinfo
.c
.optimize_coding
= FALSE
;
1357 sp
->cinfo
.c
.optimize_coding
= TRUE
;
1358 if (downsampled_input
) {
1359 /* Need to use raw-data interface to libjpeg */
1360 sp
->cinfo
.c
.raw_data_in
= TRUE
;
1361 tif
->tif_encoderow
= JPEGEncodeRaw
;
1362 tif
->tif_encodestrip
= JPEGEncodeRaw
;
1363 tif
->tif_encodetile
= JPEGEncodeRaw
;
1365 /* Use normal interface to libjpeg */
1366 sp
->cinfo
.c
.raw_data_in
= FALSE
;
1367 tif
->tif_encoderow
= JPEGEncode
;
1368 tif
->tif_encodestrip
= JPEGEncode
;
1369 tif
->tif_encodetile
= JPEGEncode
;
1371 /* Start JPEG compressor */
1372 if (!TIFFjpeg_start_compress(sp
, FALSE
))
1374 /* Allocate downsampled-data buffers if needed */
1375 if (downsampled_input
) {
1376 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.c
.comp_info
,
1377 sp
->cinfo
.c
.num_components
))
1386 * Encode a chunk of pixels.
1387 * "Standard" case: incoming data is not downsampled.
1390 JPEGEncode(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
1392 JPEGState
*sp
= JState(tif
);
1398 /* data is expected to be supplied in multiples of a scanline */
1399 nrows
= cc
/ sp
->bytesperline
;
1400 if (cc
% sp
->bytesperline
)
1401 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline discarded");
1403 while (nrows
-- > 0) {
1404 bufptr
[0] = (JSAMPROW
) buf
;
1405 if (TIFFjpeg_write_scanlines(sp
, bufptr
, 1) != 1)
1409 buf
+= sp
->bytesperline
;
1415 * Encode a chunk of pixels.
1416 * Incoming data is expected to be downsampled per sampling factors.
1419 JPEGEncodeRaw(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
1421 JPEGState
*sp
= JState(tif
);
1425 JDIMENSION clumps_per_line
, nclump
;
1426 int clumpoffset
, ci
, xpos
, ypos
;
1427 jpeg_component_info
* compptr
;
1428 int samples_per_clump
= sp
->samplesperclump
;
1432 /* data is expected to be supplied in multiples of a scanline */
1433 nrows
= cc
/ sp
->bytesperline
;
1434 if (cc
% sp
->bytesperline
)
1435 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline discarded");
1437 /* Cb,Cr both have sampling factors 1, so this is correct */
1438 clumps_per_line
= sp
->cinfo
.c
.comp_info
[1].downsampled_width
;
1440 while (nrows
-- > 0) {
1442 * Fastest way to separate the data is to make one pass
1443 * over the scanline for each row of each component.
1445 clumpoffset
= 0; /* first sample in clump */
1446 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1447 ci
< sp
->cinfo
.c
.num_components
;
1449 int hsamp
= compptr
->h_samp_factor
;
1450 int vsamp
= compptr
->v_samp_factor
;
1451 int padding
= (int) (compptr
->width_in_blocks
* DCTSIZE
-
1452 clumps_per_line
* hsamp
);
1453 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
1454 inptr
= ((JSAMPLE
*) buf
) + clumpoffset
;
1455 outptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
1457 /* fast path for at least Cb and Cr */
1458 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1459 *outptr
++ = inptr
[0];
1460 inptr
+= samples_per_clump
;
1464 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1465 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1466 *outptr
++ = inptr
[xpos
];
1467 inptr
+= samples_per_clump
;
1470 /* pad each scanline as needed */
1471 for (xpos
= 0; xpos
< padding
; xpos
++) {
1472 *outptr
= outptr
[-1];
1475 clumpoffset
+= hsamp
;
1479 if (sp
->scancount
>= DCTSIZE
) {
1480 int n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1481 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1487 buf
+= sp
->bytesperline
;
1493 * Finish up at the end of a strip or tile.
1496 JPEGPostEncode(TIFF
* tif
)
1498 JPEGState
*sp
= JState(tif
);
1500 if (sp
->scancount
> 0) {
1502 * Need to emit a partial bufferload of downsampled data.
1503 * Pad the data vertically.
1506 jpeg_component_info
* compptr
;
1508 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1509 ci
< sp
->cinfo
.c
.num_components
;
1511 int vsamp
= compptr
->v_samp_factor
;
1512 tsize_t row_width
= compptr
->width_in_blocks
* DCTSIZE
1514 for (ypos
= sp
->scancount
* vsamp
;
1515 ypos
< DCTSIZE
* vsamp
; ypos
++) {
1516 _TIFFmemcpy((tdata_t
)sp
->ds_buffer
[ci
][ypos
],
1517 (tdata_t
)sp
->ds_buffer
[ci
][ypos
-1],
1522 n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1523 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1527 return (TIFFjpeg_finish_compress(JState(tif
)));
1531 JPEGCleanup(TIFF
* tif
)
1533 JPEGState
*sp
= JState(tif
);
1537 tif
->tif_tagmethods
.vgetfield
= sp
->vgetparent
;
1538 tif
->tif_tagmethods
.vsetfield
= sp
->vsetparent
;
1540 if( sp
->cinfo_initialized
)
1541 TIFFjpeg_destroy(sp
); /* release libjpeg resources */
1542 if (sp
->jpegtables
) /* tag value */
1543 _TIFFfree(sp
->jpegtables
);
1544 _TIFFfree(tif
->tif_data
); /* release local state */
1545 tif
->tif_data
= NULL
;
1547 _TIFFSetDefaultCompressionState(tif
);
1551 JPEGVSetField(TIFF
* tif
, ttag_t tag
, va_list ap
)
1553 JPEGState
* sp
= JState(tif
);
1554 TIFFDirectory
* td
= &tif
->tif_dir
;
1560 case TIFFTAG_JPEGTABLES
:
1561 v32
= va_arg(ap
, uint32
);
1566 _TIFFsetByteArray(&sp
->jpegtables
, va_arg(ap
, void*),
1568 sp
->jpegtables_length
= v32
;
1569 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1571 case TIFFTAG_JPEGQUALITY
:
1572 sp
->jpegquality
= va_arg(ap
, int);
1573 return (1); /* pseudo tag */
1574 case TIFFTAG_JPEGCOLORMODE
:
1575 sp
->jpegcolormode
= va_arg(ap
, int);
1577 * Mark whether returned data is up-sampled or not
1578 * so TIFFStripSize and TIFFTileSize return values
1579 * that reflect the true amount of data.
1581 tif
->tif_flags
&= ~TIFF_UPSAMPLED
;
1582 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1583 if (td
->td_photometric
== PHOTOMETRIC_YCBCR
&&
1584 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1585 tif
->tif_flags
|= TIFF_UPSAMPLED
;
1587 if (td
->td_ycbcrsubsampling
[0] != 1 ||
1588 td
->td_ycbcrsubsampling
[1] != 1)
1589 ; /* XXX what about up-sampling? */
1593 * Must recalculate cached tile size
1594 * in case sampling state changed.
1596 tif
->tif_tilesize
= isTiled(tif
) ? TIFFTileSize(tif
) : (tsize_t
) -1;
1597 return (1); /* pseudo tag */
1598 case TIFFTAG_JPEGTABLESMODE
:
1599 sp
->jpegtablesmode
= va_arg(ap
, int);
1600 return (1); /* pseudo tag */
1601 case TIFFTAG_YCBCRSUBSAMPLING
:
1602 /* mark the fact that we have a real ycbcrsubsampling! */
1603 sp
->ycbcrsampling_fetched
= 1;
1604 return (*sp
->vsetparent
)(tif
, tag
, ap
);
1605 case TIFFTAG_FAXRECVPARAMS
:
1606 sp
->recvparams
= va_arg(ap
, uint32
);
1608 case TIFFTAG_FAXSUBADDRESS
:
1609 _TIFFsetString(&sp
->subaddress
, va_arg(ap
, char*));
1611 case TIFFTAG_FAXRECVTIME
:
1612 sp
->recvtime
= va_arg(ap
, uint32
);
1614 case TIFFTAG_FAXDCS
:
1615 _TIFFsetString(&sp
->faxdcs
, va_arg(ap
, char*));
1618 return (*sp
->vsetparent
)(tif
, tag
, ap
);
1620 TIFFSetFieldBit(tif
, _TIFFFieldWithTag(tif
, tag
)->field_bit
);
1621 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1626 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
1627 * the TIFF tags, but still use non-default (2,2) values within the jpeg
1628 * data stream itself. In order for TIFF applications to work properly
1629 * - for instance to get the strip buffer size right - it is imperative
1630 * that the subsampling be available before we start reading the image
1631 * data normally. This function will attempt to load the first strip in
1632 * order to get the sampling values from the jpeg data stream. Various
1633 * hacks are various places are done to ensure this function gets called
1634 * before the td_ycbcrsubsampling values are used from the directory structure,
1635 * including calling TIFFGetField() for the YCBCRSUBSAMPLING field from
1636 * TIFFStripSize(), and the printing code in tif_print.c.
1638 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
1639 * discovered sampling does not match the default sampling (2,2) or whatever
1640 * was actually in the tiff tags.
1643 * o This code will cause one whole strip/tile of compressed data to be
1644 * loaded just to get the tags right, even if the imagery is never read.
1645 * It would be more efficient to just load a bit of the header, and
1646 * initialize things from that.
1648 * See the bug in bugzilla for details:
1650 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
1652 * Frank Warmerdam, July 2002
1656 JPEGFixupTestSubsampling( TIFF
* tif
)
1658 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
1659 JPEGState
*sp
= JState(tif
);
1660 TIFFDirectory
*td
= &tif
->tif_dir
;
1662 JPEGInitializeLibJPEG( tif
, 0, 0 );
1665 * Some JPEG-in-TIFF files don't provide the ycbcrsampling tags,
1666 * and use a sampling schema other than the default 2,2. To handle
1667 * this we actually have to scan the header of a strip or tile of
1668 * jpeg data to get the sampling.
1670 if( !sp
->cinfo
.comm
.is_decompressor
1671 || sp
->ycbcrsampling_fetched
1672 || td
->td_photometric
!= PHOTOMETRIC_YCBCR
)
1675 sp
->ycbcrsampling_fetched
= 1;
1676 if( TIFFIsTiled( tif
) )
1678 if( !TIFFFillTile( tif
, 0 ) )
1683 if( !TIFFFillStrip( tif
, 0 ) )
1687 TIFFSetField( tif
, TIFFTAG_YCBCRSUBSAMPLING
,
1688 (uint16
) sp
->h_sampling
, (uint16
) sp
->v_sampling
);
1689 #endif /* CHECK_JPEG_YCBCR_SUBSAMPLING */
1693 JPEGVGetField(TIFF
* tif
, ttag_t tag
, va_list ap
)
1695 JPEGState
* sp
= JState(tif
);
1700 case TIFFTAG_JPEGTABLES
:
1701 *va_arg(ap
, uint32
*) = sp
->jpegtables_length
;
1702 *va_arg(ap
, void**) = sp
->jpegtables
;
1704 case TIFFTAG_JPEGQUALITY
:
1705 *va_arg(ap
, int*) = sp
->jpegquality
;
1707 case TIFFTAG_JPEGCOLORMODE
:
1708 *va_arg(ap
, int*) = sp
->jpegcolormode
;
1710 case TIFFTAG_JPEGTABLESMODE
:
1711 *va_arg(ap
, int*) = sp
->jpegtablesmode
;
1713 case TIFFTAG_YCBCRSUBSAMPLING
:
1714 JPEGFixupTestSubsampling( tif
);
1715 return (*sp
->vgetparent
)(tif
, tag
, ap
);
1717 case TIFFTAG_FAXRECVPARAMS
:
1718 *va_arg(ap
, uint32
*) = sp
->recvparams
;
1720 case TIFFTAG_FAXSUBADDRESS
:
1721 *va_arg(ap
, char**) = sp
->subaddress
;
1723 case TIFFTAG_FAXRECVTIME
:
1724 *va_arg(ap
, uint32
*) = sp
->recvtime
;
1726 case TIFFTAG_FAXDCS
:
1727 *va_arg(ap
, char**) = sp
->faxdcs
;
1730 return (*sp
->vgetparent
)(tif
, tag
, ap
);
1736 JPEGPrintDir(TIFF
* tif
, FILE* fd
, long flags
)
1738 JPEGState
* sp
= JState(tif
);
1743 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
))
1744 fprintf(fd
, " JPEG Tables: (%lu bytes)\n",
1745 (unsigned long) sp
->jpegtables_length
);
1746 if (TIFFFieldSet(tif
,FIELD_RECVPARAMS
))
1747 fprintf(fd
, " Fax Receive Parameters: %08lx\n",
1748 (unsigned long) sp
->recvparams
);
1749 if (TIFFFieldSet(tif
,FIELD_SUBADDRESS
))
1750 fprintf(fd
, " Fax SubAddress: %s\n", sp
->subaddress
);
1751 if (TIFFFieldSet(tif
,FIELD_RECVTIME
))
1752 fprintf(fd
, " Fax Receive Time: %lu secs\n",
1753 (unsigned long) sp
->recvtime
);
1754 if (TIFFFieldSet(tif
,FIELD_FAXDCS
))
1755 fprintf(fd
, " Fax DCS: %s\n", sp
->faxdcs
);
1759 JPEGDefaultStripSize(TIFF
* tif
, uint32 s
)
1761 JPEGState
* sp
= JState(tif
);
1762 TIFFDirectory
*td
= &tif
->tif_dir
;
1764 s
= (*sp
->defsparent
)(tif
, s
);
1765 if (s
< td
->td_imagelength
)
1766 s
= TIFFroundup(s
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
1771 JPEGDefaultTileSize(TIFF
* tif
, uint32
* tw
, uint32
* th
)
1773 JPEGState
* sp
= JState(tif
);
1774 TIFFDirectory
*td
= &tif
->tif_dir
;
1776 (*sp
->deftparent
)(tif
, tw
, th
);
1777 *tw
= TIFFroundup(*tw
, td
->td_ycbcrsubsampling
[0] * DCTSIZE
);
1778 *th
= TIFFroundup(*th
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
1782 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
1783 * now that we allow a TIFF file to be opened in update mode it is necessary
1784 * to have some way of deciding whether compression or decompression is
1785 * desired other than looking at tif->tif_mode. We accomplish this by
1786 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
1787 * If so, we assume decompression is desired.
1789 * This is tricky, because TIFFInitJPEG() is called while the directory is
1790 * being read, and generally speaking the BYTECOUNTS tag won't have been read
1791 * at that point. So we try to defer jpeg library initialization till we
1792 * do have that tag ... basically any access that might require the compressor
1793 * or decompressor that occurs after the reading of the directory.
1795 * In an ideal world compressors or decompressors would be setup
1796 * at the point where a single tile or strip was accessed (for read or write)
1797 * so that stuff like update of missing tiles, or replacement of tiles could
1798 * be done. However, we aren't trying to crack that nut just yet ...
1800 * NFW, Feb 3rd, 2003.
1803 static int JPEGInitializeLibJPEG( TIFF
* tif
, int force_encode
, int force_decode
)
1805 JPEGState
* sp
= JState(tif
);
1806 uint32
*byte_counts
= NULL
;
1807 int data_is_empty
= TRUE
;
1810 if( sp
->cinfo_initialized
)
1814 * Do we have tile data already? Make sure we initialize the
1815 * the state in decompressor mode if we have tile data, even if we
1816 * are not in read-only file access mode.
1818 if( TIFFIsTiled( tif
)
1819 && TIFFGetField( tif
, TIFFTAG_TILEBYTECOUNTS
, &byte_counts
)
1820 && byte_counts
!= NULL
)
1822 data_is_empty
= byte_counts
[0] == 0;
1824 if( !TIFFIsTiled( tif
)
1825 && TIFFGetField( tif
, TIFFTAG_STRIPBYTECOUNTS
, &byte_counts
)
1826 && byte_counts
!= NULL
)
1828 data_is_empty
= byte_counts
[0] == 0;
1833 else if( force_encode
)
1835 else if( tif
->tif_mode
== O_RDONLY
)
1837 else if( data_is_empty
)
1843 * Initialize libjpeg.
1846 if (!TIFFjpeg_create_decompress(sp
))
1850 if (!TIFFjpeg_create_compress(sp
))
1854 sp
->cinfo_initialized
= TRUE
;
1860 TIFFInitJPEG(TIFF
* tif
, int scheme
)
1864 assert(scheme
== COMPRESSION_JPEG
);
1867 * Allocate state block so tag methods have storage to record values.
1869 tif
->tif_data
= (tidata_t
) _TIFFmalloc(sizeof (JPEGState
));
1871 if (tif
->tif_data
== NULL
) {
1872 TIFFErrorExt(tif
->tif_clientdata
, "TIFFInitJPEG", "No space for JPEG state block");
1875 _TIFFmemset( tif
->tif_data
, 0, sizeof(JPEGState
));
1878 sp
->tif
= tif
; /* back link */
1881 * Merge codec-specific tag information and override parent get/set
1884 _TIFFMergeFieldInfo(tif
, jpegFieldInfo
, N(jpegFieldInfo
));
1885 sp
->vgetparent
= tif
->tif_tagmethods
.vgetfield
;
1886 tif
->tif_tagmethods
.vgetfield
= JPEGVGetField
; /* hook for codec tags */
1887 sp
->vsetparent
= tif
->tif_tagmethods
.vsetfield
;
1888 tif
->tif_tagmethods
.vsetfield
= JPEGVSetField
; /* hook for codec tags */
1889 tif
->tif_tagmethods
.printdir
= JPEGPrintDir
; /* hook for codec tags */
1891 /* Default values for codec-specific fields */
1892 sp
->jpegtables
= NULL
;
1893 sp
->jpegtables_length
= 0;
1894 sp
->jpegquality
= 75; /* Default IJG quality */
1895 sp
->jpegcolormode
= JPEGCOLORMODE_RAW
;
1896 sp
->jpegtablesmode
= JPEGTABLESMODE_QUANT
| JPEGTABLESMODE_HUFF
;
1899 sp
->subaddress
= NULL
;
1902 sp
->ycbcrsampling_fetched
= 0;
1905 * Install codec methods.
1907 tif
->tif_setupdecode
= JPEGSetupDecode
;
1908 tif
->tif_predecode
= JPEGPreDecode
;
1909 tif
->tif_decoderow
= JPEGDecode
;
1910 tif
->tif_decodestrip
= JPEGDecode
;
1911 tif
->tif_decodetile
= JPEGDecode
;
1912 tif
->tif_setupencode
= JPEGSetupEncode
;
1913 tif
->tif_preencode
= JPEGPreEncode
;
1914 tif
->tif_postencode
= JPEGPostEncode
;
1915 tif
->tif_encoderow
= JPEGEncode
;
1916 tif
->tif_encodestrip
= JPEGEncode
;
1917 tif
->tif_encodetile
= JPEGEncode
;
1918 tif
->tif_cleanup
= JPEGCleanup
;
1919 sp
->defsparent
= tif
->tif_defstripsize
;
1920 tif
->tif_defstripsize
= JPEGDefaultStripSize
;
1921 sp
->deftparent
= tif
->tif_deftilesize
;
1922 tif
->tif_deftilesize
= JPEGDefaultTileSize
;
1923 tif
->tif_flags
|= TIFF_NOBITREV
; /* no bit reversal, please */
1925 sp
->cinfo_initialized
= FALSE
;
1928 ** Create a JPEGTables field if no directory has yet been created.
1929 ** We do this just to ensure that sufficient space is reserved for
1930 ** the JPEGTables field. It will be properly created the right
1933 if( tif
->tif_diroff
== 0 )
1935 #define SIZE_OF_JPEGTABLES 2000
1936 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1937 sp
->jpegtables_length
= SIZE_OF_JPEGTABLES
;
1938 sp
->jpegtables
= (void *) _TIFFmalloc(sp
->jpegtables_length
);
1939 _TIFFmemset(sp
->jpegtables
, 0, SIZE_OF_JPEGTABLES
);
1940 #undef SIZE_OF_JPEGTABLES
1944 * Mark the TIFFTAG_YCBCRSAMPLES as present even if it is not
1945 * see: JPEGFixupTestSubsampling().
1947 TIFFSetFieldBit( tif
, FIELD_YCBCRSUBSAMPLING
);
1951 #endif /* JPEG_SUPPORT */
1953 /* vim: set ts=8 sts=8 sw=8 noet: */