4 * Copyright (c) 1994-1997 Sam Leffler
5 * Copyright (c) 1994-1997 Silicon Graphics, Inc.
7 * Permission to use, copy, modify, distribute, and sell this software and
8 * its documentation for any purpose is hereby granted without fee, provided
9 * that (i) the above copyright notices and this permission notice appear in
10 * all copies of the software and related documentation, and (ii) the names of
11 * Sam Leffler and Silicon Graphics may not be used in any advertising or
12 * publicity relating to the software without the specific, prior written
13 * permission of Sam Leffler and Silicon Graphics.
15 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
19 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
27 #define WIN32_LEAN_AND_MEAN
36 * JPEG Compression support per TIFF Technical Note #2
37 * (*not* per the original TIFF 6.0 spec).
39 * This file is simply an interface to the libjpeg library written by
40 * the Independent JPEG Group. You need release 5 or later of the IJG
41 * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
43 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
47 int TIFFFillStrip(TIFF
*, tstrip_t
);
48 int TIFFFillTile(TIFF
*, ttile_t
);
50 /* We undefine FAR to avoid conflict with JPEG definition */
57 Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
58 not defined. Unfortunately, the MinGW and Borland compilers include
59 a typedef for INT32, which causes a conflict. MSVC does not include
60 a conficting typedef given the headers which are included.
62 #if defined(__BORLANDC__) || defined(__MINGW32__)
67 The windows RPCNDR.H file defines boolean, but defines it with the
68 unsigned char size. You should compile JPEG library using appropriate
69 definitions in jconfig.h header, but many users compile library in wrong
70 way. That causes errors of the following type:
72 "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
75 For such users we wil fix the problem here. See install.doc file from
76 the JPEG library distribution for details.
79 /* Define "boolean" as unsigned char, not int, per Windows custom. */
80 #if defined(WIN32) && !defined(__MINGW32__)
81 # ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
82 typedef unsigned char boolean
;
84 # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
91 * We are using width_in_blocks which is supposed to be private to
92 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
93 * renamed this member to width_in_data_units. Since the header has
94 * also renamed a define, use that unique define name in order to
95 * detect the problem header and adjust to suit.
97 #if defined(D_MAX_DATA_UNITS_IN_MCU)
98 #define width_in_blocks width_in_data_units
102 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
103 * in place of plain setjmp. These macros will make it easier.
105 #define SETJMP(jbuf) setjmp(jbuf)
106 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
107 #define JMP_BUF jmp_buf
109 typedef struct jpeg_destination_mgr jpeg_destination_mgr
;
110 typedef struct jpeg_source_mgr jpeg_source_mgr
;
111 typedef struct jpeg_error_mgr jpeg_error_mgr
;
114 * State block for each open TIFF file using
115 * libjpeg to do JPEG compression/decompression.
117 * libjpeg's visible state is either a jpeg_compress_struct
118 * or jpeg_decompress_struct depending on which way we
119 * are going. comm can be used to refer to the fields
120 * which are common to both.
122 * NB: cinfo is required to be the first member of JPEGState,
123 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
128 struct jpeg_compress_struct c
;
129 struct jpeg_decompress_struct d
;
130 struct jpeg_common_struct comm
;
131 } cinfo
; /* NB: must be first */
132 int cinfo_initialized
;
134 jpeg_error_mgr err
; /* libjpeg error manager */
135 JMP_BUF exit_jmpbuf
; /* for catching libjpeg failures */
137 * The following two members could be a union, but
138 * they're small enough that it's not worth the effort.
140 jpeg_destination_mgr dest
; /* data dest for compression */
141 jpeg_source_mgr src
; /* data source for decompression */
143 TIFF
* tif
; /* back link needed by some code */
144 uint16 photometric
; /* copy of PhotometricInterpretation */
145 uint16 h_sampling
; /* luminance sampling factors */
147 tsize_t bytesperline
; /* decompressed bytes per scanline */
148 /* pointers to intermediate buffers when processing downsampled data */
149 JSAMPARRAY ds_buffer
[MAX_COMPONENTS
];
150 int scancount
; /* number of "scanlines" accumulated */
153 TIFFVGetMethod vgetparent
; /* super-class method */
154 TIFFVSetMethod vsetparent
; /* super-class method */
155 TIFFStripMethod defsparent
; /* super-class method */
156 TIFFTileMethod deftparent
; /* super-class method */
157 /* pseudo-tag fields */
158 void* jpegtables
; /* JPEGTables tag value, or NULL */
159 uint32 jpegtables_length
; /* number of bytes in same */
160 int jpegquality
; /* Compression quality level */
161 int jpegcolormode
; /* Auto RGB<=>YCbCr convert? */
162 int jpegtablesmode
; /* What to put in JPEGTables */
164 int ycbcrsampling_fetched
;
165 uint32 recvparams
; /* encoded Class 2 session params */
166 char* subaddress
; /* subaddress string */
167 uint32 recvtime
; /* time spent receiving (secs) */
168 char* faxdcs
; /* encoded fax parameters (DCS, Table 2/T.30) */
171 #define JState(tif) ((JPEGState*)(tif)->tif_data)
173 static int JPEGDecode(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
174 static int JPEGDecodeRaw(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
175 static int JPEGEncode(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
176 static int JPEGEncodeRaw(TIFF
*, tidata_t
, tsize_t
, tsample_t
);
177 static int JPEGInitializeLibJPEG( TIFF
* tif
,
178 int force_encode
, int force_decode
);
180 #define FIELD_JPEGTABLES (FIELD_CODEC+0)
181 #define FIELD_RECVPARAMS (FIELD_CODEC+1)
182 #define FIELD_SUBADDRESS (FIELD_CODEC+2)
183 #define FIELD_RECVTIME (FIELD_CODEC+3)
184 #define FIELD_FAXDCS (FIELD_CODEC+4)
186 static const TIFFFieldInfo jpegFieldInfo
[] = {
187 { TIFFTAG_JPEGTABLES
, -3,-3, TIFF_UNDEFINED
, FIELD_JPEGTABLES
,
188 FALSE
, TRUE
, "JPEGTables" },
189 { TIFFTAG_JPEGQUALITY
, 0, 0, TIFF_ANY
, FIELD_PSEUDO
,
191 { TIFFTAG_JPEGCOLORMODE
, 0, 0, TIFF_ANY
, FIELD_PSEUDO
,
193 { TIFFTAG_JPEGTABLESMODE
, 0, 0, TIFF_ANY
, FIELD_PSEUDO
,
195 /* Specific for JPEG in faxes */
196 { TIFFTAG_FAXRECVPARAMS
, 1, 1, TIFF_LONG
, FIELD_RECVPARAMS
,
197 TRUE
, FALSE
, "FaxRecvParams" },
198 { TIFFTAG_FAXSUBADDRESS
, -1,-1, TIFF_ASCII
, FIELD_SUBADDRESS
,
199 TRUE
, FALSE
, "FaxSubAddress" },
200 { TIFFTAG_FAXRECVTIME
, 1, 1, TIFF_LONG
, FIELD_RECVTIME
,
201 TRUE
, FALSE
, "FaxRecvTime" },
202 { TIFFTAG_FAXDCS
, -1, -1, TIFF_ASCII
, FIELD_FAXDCS
,
203 TRUE
, FALSE
, "FaxDcs" },
205 #define N(a) (sizeof (a) / sizeof (a[0]))
208 * libjpeg interface layer.
210 * We use setjmp/longjmp to return control to libtiff
211 * when a fatal error is encountered within the JPEG
212 * library. We also direct libjpeg error and warning
213 * messages through the appropriate libtiff handlers.
217 * Error handling routines (these replace corresponding
218 * IJG routines from jerror.c). These are used for both
219 * compression and decompression.
222 TIFFjpeg_error_exit(j_common_ptr cinfo
)
224 JPEGState
*sp
= (JPEGState
*) cinfo
; /* NB: cinfo assumed first */
225 char buffer
[JMSG_LENGTH_MAX
];
227 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
228 TIFFErrorExt(sp
->tif
->tif_clientdata
, "JPEGLib", buffer
); /* display the error message */
229 jpeg_abort(cinfo
); /* clean up libjpeg state */
230 LONGJMP(sp
->exit_jmpbuf
, 1); /* return to libtiff caller */
234 * This routine is invoked only for warning messages,
235 * since error_exit does its own thing and trace_level
239 TIFFjpeg_output_message(j_common_ptr cinfo
)
241 char buffer
[JMSG_LENGTH_MAX
];
243 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
244 TIFFWarningExt(((JPEGState
*) cinfo
)->tif
->tif_clientdata
, "JPEGLib", buffer
);
248 * Interface routines. This layer of routines exists
249 * primarily to limit side-effects from using setjmp.
250 * Also, normal/error returns are converted into return
251 * values per libtiff practice.
253 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
254 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
257 TIFFjpeg_create_compress(JPEGState
* sp
)
259 /* initialize JPEG error handling */
260 sp
->cinfo
.c
.err
= jpeg_std_error(&sp
->err
);
261 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
262 sp
->err
.output_message
= TIFFjpeg_output_message
;
264 return CALLVJPEG(sp
, jpeg_create_compress(&sp
->cinfo
.c
));
268 TIFFjpeg_create_decompress(JPEGState
* sp
)
270 /* initialize JPEG error handling */
271 sp
->cinfo
.d
.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_decompress(&sp
->cinfo
.d
));
279 TIFFjpeg_set_defaults(JPEGState
* sp
)
281 return CALLVJPEG(sp
, jpeg_set_defaults(&sp
->cinfo
.c
));
285 TIFFjpeg_set_colorspace(JPEGState
* sp
, J_COLOR_SPACE colorspace
)
287 return CALLVJPEG(sp
, jpeg_set_colorspace(&sp
->cinfo
.c
, colorspace
));
291 TIFFjpeg_set_quality(JPEGState
* sp
, int quality
, boolean force_baseline
)
294 jpeg_set_quality(&sp
->cinfo
.c
, quality
, force_baseline
));
298 TIFFjpeg_suppress_tables(JPEGState
* sp
, boolean suppress
)
300 return CALLVJPEG(sp
, jpeg_suppress_tables(&sp
->cinfo
.c
, suppress
));
304 TIFFjpeg_start_compress(JPEGState
* sp
, boolean write_all_tables
)
307 jpeg_start_compress(&sp
->cinfo
.c
, write_all_tables
));
311 TIFFjpeg_write_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int num_lines
)
313 return CALLJPEG(sp
, -1, (int) jpeg_write_scanlines(&sp
->cinfo
.c
,
314 scanlines
, (JDIMENSION
) num_lines
));
318 TIFFjpeg_write_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int num_lines
)
320 return CALLJPEG(sp
, -1, (int) jpeg_write_raw_data(&sp
->cinfo
.c
,
321 data
, (JDIMENSION
) num_lines
));
325 TIFFjpeg_finish_compress(JPEGState
* sp
)
327 return CALLVJPEG(sp
, jpeg_finish_compress(&sp
->cinfo
.c
));
331 TIFFjpeg_write_tables(JPEGState
* sp
)
333 return CALLVJPEG(sp
, jpeg_write_tables(&sp
->cinfo
.c
));
337 TIFFjpeg_read_header(JPEGState
* sp
, boolean require_image
)
339 return CALLJPEG(sp
, -1, jpeg_read_header(&sp
->cinfo
.d
, require_image
));
343 TIFFjpeg_start_decompress(JPEGState
* sp
)
345 return CALLVJPEG(sp
, jpeg_start_decompress(&sp
->cinfo
.d
));
349 TIFFjpeg_read_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int max_lines
)
351 return CALLJPEG(sp
, -1, (int) jpeg_read_scanlines(&sp
->cinfo
.d
,
352 scanlines
, (JDIMENSION
) max_lines
));
356 TIFFjpeg_read_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int max_lines
)
358 return CALLJPEG(sp
, -1, (int) jpeg_read_raw_data(&sp
->cinfo
.d
,
359 data
, (JDIMENSION
) max_lines
));
363 TIFFjpeg_finish_decompress(JPEGState
* sp
)
365 return CALLJPEG(sp
, -1, (int) jpeg_finish_decompress(&sp
->cinfo
.d
));
369 TIFFjpeg_abort(JPEGState
* sp
)
371 return CALLVJPEG(sp
, jpeg_abort(&sp
->cinfo
.comm
));
375 TIFFjpeg_destroy(JPEGState
* sp
)
377 return CALLVJPEG(sp
, jpeg_destroy(&sp
->cinfo
.comm
));
381 TIFFjpeg_alloc_sarray(JPEGState
* sp
, int pool_id
,
382 JDIMENSION samplesperrow
, JDIMENSION numrows
)
384 return CALLJPEG(sp
, (JSAMPARRAY
) NULL
,
385 (*sp
->cinfo
.comm
.mem
->alloc_sarray
)
386 (&sp
->cinfo
.comm
, pool_id
, samplesperrow
, numrows
));
390 * JPEG library destination data manager.
391 * These routines direct compressed data from libjpeg into the
392 * libtiff output buffer.
396 std_init_destination(j_compress_ptr cinfo
)
398 JPEGState
* sp
= (JPEGState
*) cinfo
;
401 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
402 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
406 std_empty_output_buffer(j_compress_ptr cinfo
)
408 JPEGState
* sp
= (JPEGState
*) cinfo
;
411 /* the entire buffer has been filled */
412 tif
->tif_rawcc
= tif
->tif_rawdatasize
;
414 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
415 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
421 std_term_destination(j_compress_ptr cinfo
)
423 JPEGState
* sp
= (JPEGState
*) cinfo
;
426 tif
->tif_rawcp
= (tidata_t
) sp
->dest
.next_output_byte
;
428 tif
->tif_rawdatasize
- (tsize_t
) sp
->dest
.free_in_buffer
;
429 /* NB: libtiff does the final buffer flush */
433 TIFFjpeg_data_dest(JPEGState
* sp
, TIFF
* tif
)
436 sp
->cinfo
.c
.dest
= &sp
->dest
;
437 sp
->dest
.init_destination
= std_init_destination
;
438 sp
->dest
.empty_output_buffer
= std_empty_output_buffer
;
439 sp
->dest
.term_destination
= std_term_destination
;
443 * Alternate destination manager for outputting to JPEGTables field.
447 tables_init_destination(j_compress_ptr cinfo
)
449 JPEGState
* sp
= (JPEGState
*) cinfo
;
451 /* while building, jpegtables_length is allocated buffer size */
452 sp
->dest
.next_output_byte
= (JOCTET
*) sp
->jpegtables
;
453 sp
->dest
.free_in_buffer
= (size_t) sp
->jpegtables_length
;
457 tables_empty_output_buffer(j_compress_ptr cinfo
)
459 JPEGState
* sp
= (JPEGState
*) cinfo
;
462 /* the entire buffer has been filled; enlarge it by 1000 bytes */
463 newbuf
= _TIFFrealloc((tdata_t
) sp
->jpegtables
,
464 (tsize_t
) (sp
->jpegtables_length
+ 1000));
466 ERREXIT1(cinfo
, JERR_OUT_OF_MEMORY
, 100);
467 sp
->dest
.next_output_byte
= (JOCTET
*) newbuf
+ sp
->jpegtables_length
;
468 sp
->dest
.free_in_buffer
= (size_t) 1000;
469 sp
->jpegtables
= newbuf
;
470 sp
->jpegtables_length
+= 1000;
475 tables_term_destination(j_compress_ptr cinfo
)
477 JPEGState
* sp
= (JPEGState
*) cinfo
;
479 /* set tables length to number of bytes actually emitted */
480 sp
->jpegtables_length
-= sp
->dest
.free_in_buffer
;
484 TIFFjpeg_tables_dest(JPEGState
* sp
, TIFF
* tif
)
488 * Allocate a working buffer for building tables.
489 * Initial size is 1000 bytes, which is usually adequate.
492 _TIFFfree(sp
->jpegtables
);
493 sp
->jpegtables_length
= 1000;
494 sp
->jpegtables
= (void*) _TIFFmalloc((tsize_t
) sp
->jpegtables_length
);
495 if (sp
->jpegtables
== NULL
) {
496 sp
->jpegtables_length
= 0;
497 TIFFErrorExt(sp
->tif
->tif_clientdata
, "TIFFjpeg_tables_dest", "No space for JPEGTables");
500 sp
->cinfo
.c
.dest
= &sp
->dest
;
501 sp
->dest
.init_destination
= tables_init_destination
;
502 sp
->dest
.empty_output_buffer
= tables_empty_output_buffer
;
503 sp
->dest
.term_destination
= tables_term_destination
;
508 * JPEG library source data manager.
509 * These routines supply compressed data to libjpeg.
513 std_init_source(j_decompress_ptr cinfo
)
515 JPEGState
* sp
= (JPEGState
*) cinfo
;
518 sp
->src
.next_input_byte
= (const JOCTET
*) tif
->tif_rawdata
;
519 sp
->src
.bytes_in_buffer
= (size_t) tif
->tif_rawcc
;
523 std_fill_input_buffer(j_decompress_ptr cinfo
)
525 JPEGState
* sp
= (JPEGState
* ) cinfo
;
526 static const JOCTET dummy_EOI
[2] = { 0xFF, JPEG_EOI
};
529 * Should never get here since entire strip/tile is
530 * read into memory before the decompressor is called,
531 * and thus was supplied by init_source.
533 WARNMS(cinfo
, JWRN_JPEG_EOF
);
534 /* insert a fake EOI marker */
535 sp
->src
.next_input_byte
= dummy_EOI
;
536 sp
->src
.bytes_in_buffer
= 2;
541 std_skip_input_data(j_decompress_ptr cinfo
, long num_bytes
)
543 JPEGState
* sp
= (JPEGState
*) cinfo
;
546 if (num_bytes
> (long) sp
->src
.bytes_in_buffer
) {
547 /* oops, buffer overrun */
548 (void) std_fill_input_buffer(cinfo
);
550 sp
->src
.next_input_byte
+= (size_t) num_bytes
;
551 sp
->src
.bytes_in_buffer
-= (size_t) num_bytes
;
557 std_term_source(j_decompress_ptr cinfo
)
559 /* No work necessary here */
560 /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
561 /* (if so, need empty tables_term_source!) */
566 TIFFjpeg_data_src(JPEGState
* sp
, TIFF
* tif
)
569 sp
->cinfo
.d
.src
= &sp
->src
;
570 sp
->src
.init_source
= std_init_source
;
571 sp
->src
.fill_input_buffer
= std_fill_input_buffer
;
572 sp
->src
.skip_input_data
= std_skip_input_data
;
573 sp
->src
.resync_to_restart
= jpeg_resync_to_restart
;
574 sp
->src
.term_source
= std_term_source
;
575 sp
->src
.bytes_in_buffer
= 0; /* for safety */
576 sp
->src
.next_input_byte
= NULL
;
580 * Alternate source manager for reading from JPEGTables.
581 * We can share all the code except for the init routine.
585 tables_init_source(j_decompress_ptr cinfo
)
587 JPEGState
* sp
= (JPEGState
*) cinfo
;
589 sp
->src
.next_input_byte
= (const JOCTET
*) sp
->jpegtables
;
590 sp
->src
.bytes_in_buffer
= (size_t) sp
->jpegtables_length
;
594 TIFFjpeg_tables_src(JPEGState
* sp
, TIFF
* tif
)
596 TIFFjpeg_data_src(sp
, tif
);
597 sp
->src
.init_source
= tables_init_source
;
601 * Allocate downsampled-data buffers needed for downsampled I/O.
602 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
603 * We use libjpeg's allocator so that buffers will be released automatically
604 * when done with strip/tile.
605 * This is also a handy place to compute samplesperclump, bytesperline.
608 alloc_downsampled_buffers(TIFF
* tif
, jpeg_component_info
* comp_info
,
611 JPEGState
* sp
= JState(tif
);
613 jpeg_component_info
* compptr
;
615 int samples_per_clump
= 0;
617 for (ci
= 0, compptr
= comp_info
; ci
< num_components
;
619 samples_per_clump
+= compptr
->h_samp_factor
*
620 compptr
->v_samp_factor
;
621 buf
= TIFFjpeg_alloc_sarray(sp
, JPOOL_IMAGE
,
622 compptr
->width_in_blocks
* DCTSIZE
,
623 (JDIMENSION
) (compptr
->v_samp_factor
*DCTSIZE
));
626 sp
->ds_buffer
[ci
] = buf
;
628 sp
->samplesperclump
= samples_per_clump
;
638 JPEGSetupDecode(TIFF
* tif
)
640 JPEGState
* sp
= JState(tif
);
641 TIFFDirectory
*td
= &tif
->tif_dir
;
643 JPEGInitializeLibJPEG( tif
, 0, 1 );
646 assert(sp
->cinfo
.comm
.is_decompressor
);
648 /* Read JPEGTables if it is present */
649 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
)) {
650 TIFFjpeg_tables_src(sp
, tif
);
651 if(TIFFjpeg_read_header(sp
,FALSE
) != JPEG_HEADER_TABLES_ONLY
) {
652 TIFFErrorExt(tif
->tif_clientdata
, "JPEGSetupDecode", "Bogus JPEGTables field");
657 /* Grab parameters that are same for all strips/tiles */
658 sp
->photometric
= td
->td_photometric
;
659 switch (sp
->photometric
) {
660 case PHOTOMETRIC_YCBCR
:
661 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
662 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
665 /* TIFF 6.0 forbids subsampling of all other color spaces */
671 /* Set up for reading normal data */
672 TIFFjpeg_data_src(sp
, tif
);
673 tif
->tif_postdecode
= _TIFFNoPostDecode
; /* override byte swapping */
678 * Set up for decoding a strip or tile.
681 JPEGPreDecode(TIFF
* tif
, tsample_t s
)
683 JPEGState
*sp
= JState(tif
);
684 TIFFDirectory
*td
= &tif
->tif_dir
;
685 static const char module[] = "JPEGPreDecode";
686 uint32 segment_width
, segment_height
;
687 int downsampled_output
;
691 assert(sp
->cinfo
.comm
.is_decompressor
);
693 * Reset decoder state from any previous strip/tile,
694 * in case application didn't read the whole strip.
696 if (!TIFFjpeg_abort(sp
))
699 * Read the header for this strip/tile.
701 if (TIFFjpeg_read_header(sp
, TRUE
) != JPEG_HEADER_OK
)
704 * Check image parameters and set decompression parameters.
706 segment_width
= td
->td_imagewidth
;
707 segment_height
= td
->td_imagelength
- tif
->tif_row
;
709 segment_width
= td
->td_tilewidth
;
710 segment_height
= td
->td_tilelength
;
711 sp
->bytesperline
= TIFFTileRowSize(tif
);
713 if (segment_height
> td
->td_rowsperstrip
)
714 segment_height
= td
->td_rowsperstrip
;
715 sp
->bytesperline
= TIFFScanlineSize(tif
);
717 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
719 * For PC 2, scale down the expected strip/tile size
720 * to match a downsampled component
722 segment_width
= TIFFhowmany(segment_width
, sp
->h_sampling
);
723 segment_height
= TIFFhowmany(segment_height
, sp
->v_sampling
);
725 if (sp
->cinfo
.d
.image_width
!= segment_width
||
726 sp
->cinfo
.d
.image_height
!= segment_height
) {
727 TIFFWarningExt(tif
->tif_clientdata
, module,
728 "Improper JPEG strip/tile size, expected %dx%d, got %dx%d",
731 sp
->cinfo
.d
.image_width
,
732 sp
->cinfo
.d
.image_height
);
734 if (sp
->cinfo
.d
.num_components
!=
735 (td
->td_planarconfig
== PLANARCONFIG_CONTIG
?
736 td
->td_samplesperpixel
: 1)) {
737 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG component count");
741 if (12 != td
->td_bitspersample
&& 8 != td
->td_bitspersample
) {
742 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG data precision");
745 sp
->cinfo
.d
.data_precision
= td
->td_bitspersample
;
746 sp
->cinfo
.d
.bits_in_jsample
= td
->td_bitspersample
;
748 if (sp
->cinfo
.d
.data_precision
!= td
->td_bitspersample
) {
749 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG data precision");
753 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
754 /* Component 0 should have expected sampling factors */
755 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= sp
->h_sampling
||
756 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= sp
->v_sampling
) {
757 TIFFWarningExt(tif
->tif_clientdata
, module,
758 "Improper JPEG sampling factors %d,%d\n"
759 "Apparently should be %d,%d.",
760 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
,
761 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
,
762 sp
->h_sampling
, sp
->v_sampling
);
765 * XXX: Files written by the Intergraph software
766 * has different sampling factors stored in the
767 * TIFF tags and in the JPEG structures. We will
768 * try to deduce Intergraph files by the presense
771 if (!_TIFFFindFieldInfo(tif
, 33918, TIFF_ANY
)) {
772 TIFFWarningExt(tif
->tif_clientdata
, module,
773 "Decompressor will try reading with "
775 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
,
776 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
);
778 sp
->h_sampling
= (uint16
)
779 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
;
780 sp
->v_sampling
= (uint16
)
781 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
;
784 /* Rest should have sampling factors 1,1 */
785 for (ci
= 1; ci
< sp
->cinfo
.d
.num_components
; ci
++) {
786 if (sp
->cinfo
.d
.comp_info
[ci
].h_samp_factor
!= 1 ||
787 sp
->cinfo
.d
.comp_info
[ci
].v_samp_factor
!= 1) {
788 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG sampling factors");
793 /* PC 2's single component should have sampling factors 1,1 */
794 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= 1 ||
795 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= 1) {
796 TIFFErrorExt(tif
->tif_clientdata
, module, "Improper JPEG sampling factors");
800 downsampled_output
= FALSE
;
801 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
802 sp
->photometric
== PHOTOMETRIC_YCBCR
&&
803 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
804 /* Convert YCbCr to RGB */
805 sp
->cinfo
.d
.jpeg_color_space
= JCS_YCbCr
;
806 sp
->cinfo
.d
.out_color_space
= JCS_RGB
;
808 /* Suppress colorspace handling */
809 sp
->cinfo
.d
.jpeg_color_space
= JCS_UNKNOWN
;
810 sp
->cinfo
.d
.out_color_space
= JCS_UNKNOWN
;
811 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
812 (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1))
813 downsampled_output
= TRUE
;
814 /* XXX what about up-sampling? */
816 if (downsampled_output
) {
817 /* Need to use raw-data interface to libjpeg */
818 sp
->cinfo
.d
.raw_data_out
= TRUE
;
819 tif
->tif_decoderow
= JPEGDecodeRaw
;
820 tif
->tif_decodestrip
= JPEGDecodeRaw
;
821 tif
->tif_decodetile
= JPEGDecodeRaw
;
823 /* Use normal interface to libjpeg */
824 sp
->cinfo
.d
.raw_data_out
= FALSE
;
825 tif
->tif_decoderow
= JPEGDecode
;
826 tif
->tif_decodestrip
= JPEGDecode
;
827 tif
->tif_decodetile
= JPEGDecode
;
829 /* Start JPEG decompressor */
830 if (!TIFFjpeg_start_decompress(sp
))
832 /* Allocate downsampled-data buffers if needed */
833 if (downsampled_output
) {
834 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.d
.comp_info
,
835 sp
->cinfo
.d
.num_components
))
837 sp
->scancount
= DCTSIZE
; /* mark buffer empty */
843 * Decode a chunk of pixels.
844 * "Standard" case: returned data is not downsampled.
846 /*ARGSUSED*/ static int
847 JPEGDecode(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
849 JPEGState
*sp
= JState(tif
);
853 nrows
= cc
/ sp
->bytesperline
;
854 if (cc
% sp
->bytesperline
)
855 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline not read");
857 if( nrows
> (int) sp
->cinfo
.d
.image_height
)
858 nrows
= sp
->cinfo
.d
.image_height
;
860 /* data is expected to be read in multiples of a scanline */
863 JSAMPROW line_work_buf
= NULL
;
866 ** For 6B, only use temporary buffer for 12 bit imagery.
867 ** For Mk1 always use it.
869 #if !defined(JPEG_LIB_MK1)
870 if( sp
->cinfo
.d
.data_precision
== 12 )
873 line_work_buf
= (JSAMPROW
)
874 _TIFFmalloc(sizeof(short) * sp
->cinfo
.d
.output_width
875 * sp
->cinfo
.d
.num_components
);
879 if( line_work_buf
!= NULL
)
882 ** In the MK1 case, we aways read into a 16bit buffer, and then
883 ** pack down to 12bit or 8bit. In 6B case we only read into 16
884 ** bit buffer for 12bit data, which we need to repack.
886 if (TIFFjpeg_read_scanlines(sp
, &line_work_buf
, 1) != 1)
889 if( sp
->cinfo
.d
.data_precision
== 12 )
891 int value_pairs
= (sp
->cinfo
.d
.output_width
892 * sp
->cinfo
.d
.num_components
) / 2;
895 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
897 unsigned char *out_ptr
=
898 ((unsigned char *) buf
) + iPair
* 3;
899 JSAMPLE
*in_ptr
= line_work_buf
+ iPair
* 2;
901 out_ptr
[0] = (in_ptr
[0] & 0xff0) >> 4;
902 out_ptr
[1] = ((in_ptr
[0] & 0xf) << 4)
903 | ((in_ptr
[1] & 0xf00) >> 8);
904 out_ptr
[2] = ((in_ptr
[1] & 0xff) >> 0);
907 else if( sp
->cinfo
.d
.data_precision
== 8 )
909 int value_count
= (sp
->cinfo
.d
.output_width
910 * sp
->cinfo
.d
.num_components
);
913 for( iValue
= 0; iValue
< value_count
; iValue
++ )
915 ((unsigned char *) buf
)[iValue
] =
916 line_work_buf
[iValue
] & 0xff;
923 ** In the libjpeg6b 8bit case. We read directly into the
926 JSAMPROW bufptr
= (JSAMPROW
)buf
;
928 if (TIFFjpeg_read_scanlines(sp
, &bufptr
, 1) != 1)
933 buf
+= sp
->bytesperline
;
934 cc
-= sp
->bytesperline
;
935 } while (--nrows
> 0);
937 if( line_work_buf
!= NULL
)
938 _TIFFfree( line_work_buf
);
941 /* Close down the decompressor if we've finished the strip or tile. */
942 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
943 || TIFFjpeg_finish_decompress(sp
);
947 * Decode a chunk of pixels.
948 * Returned data is downsampled per sampling factors.
950 /*ARGSUSED*/ static int
951 JPEGDecodeRaw(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
953 JPEGState
*sp
= JState(tif
);
957 /* data is expected to be read in multiples of a scanline */
958 if ( (nrows
= sp
->cinfo
.d
.image_height
) ) {
959 /* Cb,Cr both have sampling factors 1, so this is correct */
960 JDIMENSION clumps_per_line
= sp
->cinfo
.d
.comp_info
[1].downsampled_width
;
961 int samples_per_clump
= sp
->samplesperclump
;
964 unsigned short* tmpbuf
= _TIFFmalloc(sizeof(unsigned short) *
965 sp
->cinfo
.d
.output_width
*
966 sp
->cinfo
.d
.num_components
);
970 jpeg_component_info
*compptr
;
973 /* Reload downsampled-data buffer if needed */
974 if (sp
->scancount
>= DCTSIZE
) {
975 int n
= sp
->cinfo
.d
.max_v_samp_factor
* DCTSIZE
;
976 if (TIFFjpeg_read_raw_data(sp
, sp
->ds_buffer
, n
)
982 * Fastest way to unseparate data is to make one pass
983 * over the scanline for each row of each component.
985 clumpoffset
= 0; /* first sample in clump */
986 for (ci
= 0, compptr
= sp
->cinfo
.d
.comp_info
;
987 ci
< sp
->cinfo
.d
.num_components
;
989 int hsamp
= compptr
->h_samp_factor
;
990 int vsamp
= compptr
->v_samp_factor
;
993 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
994 JSAMPLE
*inptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
996 JSAMPLE
*outptr
= (JSAMPLE
*)tmpbuf
+ clumpoffset
;
998 JSAMPLE
*outptr
= (JSAMPLE
*)buf
+ clumpoffset
;
1003 /* fast path for at least Cb and Cr */
1004 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1005 outptr
[0] = *inptr
++;
1006 outptr
+= samples_per_clump
;
1012 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1013 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1014 outptr
[xpos
] = *inptr
++;
1015 outptr
+= samples_per_clump
;
1018 clumpoffset
+= hsamp
;
1024 if (sp
->cinfo
.d
.data_precision
== 8)
1027 int len
= sp
->cinfo
.d
.output_width
* sp
->cinfo
.d
.num_components
;
1028 for (i
=0; i
<len
; i
++)
1030 ((unsigned char*)buf
)[i
] = tmpbuf
[i
] & 0xff;
1035 int value_pairs
= (sp
->cinfo
.d
.output_width
1036 * sp
->cinfo
.d
.num_components
) / 2;
1038 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1040 unsigned char *out_ptr
= ((unsigned char *) buf
) + iPair
* 3;
1041 JSAMPLE
*in_ptr
= tmpbuf
+ iPair
* 2;
1042 out_ptr
[0] = (in_ptr
[0] & 0xff0) >> 4;
1043 out_ptr
[1] = ((in_ptr
[0] & 0xf) << 4)
1044 | ((in_ptr
[1] & 0xf00) >> 8);
1045 out_ptr
[2] = ((in_ptr
[1] & 0xff) >> 0);
1053 buf
+= sp
->bytesperline
;
1054 cc
-= sp
->bytesperline
;
1055 } while (--nrows
> 0);
1063 /* Close down the decompressor if done. */
1064 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
1065 || TIFFjpeg_finish_decompress(sp
);
1074 unsuppress_quant_table (JPEGState
* sp
, int tblno
)
1078 if ((qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[tblno
]) != NULL
)
1079 qtbl
->sent_table
= FALSE
;
1083 unsuppress_huff_table (JPEGState
* sp
, int tblno
)
1087 if ((htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[tblno
]) != NULL
)
1088 htbl
->sent_table
= FALSE
;
1089 if ((htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[tblno
]) != NULL
)
1090 htbl
->sent_table
= FALSE
;
1094 prepare_JPEGTables(TIFF
* tif
)
1096 JPEGState
* sp
= JState(tif
);
1098 JPEGInitializeLibJPEG( tif
, 0, 0 );
1100 /* Initialize quant tables for current quality setting */
1101 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1103 /* Mark only the tables we want for output */
1104 /* NB: chrominance tables are currently used only with YCbCr */
1105 if (!TIFFjpeg_suppress_tables(sp
, TRUE
))
1107 if (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
) {
1108 unsuppress_quant_table(sp
, 0);
1109 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1110 unsuppress_quant_table(sp
, 1);
1112 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
) {
1113 unsuppress_huff_table(sp
, 0);
1114 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1115 unsuppress_huff_table(sp
, 1);
1117 /* Direct libjpeg output into jpegtables */
1118 if (!TIFFjpeg_tables_dest(sp
, tif
))
1120 /* Emit tables-only datastream */
1121 if (!TIFFjpeg_write_tables(sp
))
1128 JPEGSetupEncode(TIFF
* tif
)
1130 JPEGState
* sp
= JState(tif
);
1131 TIFFDirectory
*td
= &tif
->tif_dir
;
1132 static const char module[] = "JPEGSetupEncode";
1134 JPEGInitializeLibJPEG( tif
, 1, 0 );
1137 assert(!sp
->cinfo
.comm
.is_decompressor
);
1140 * Initialize all JPEG parameters to default values.
1141 * Note that jpeg_set_defaults needs legal values for
1142 * in_color_space and input_components.
1144 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1145 sp
->cinfo
.c
.input_components
= 1;
1146 if (!TIFFjpeg_set_defaults(sp
))
1148 /* Set per-file parameters */
1149 sp
->photometric
= td
->td_photometric
;
1150 switch (sp
->photometric
) {
1151 case PHOTOMETRIC_YCBCR
:
1152 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
1153 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
1155 * A ReferenceBlackWhite field *must* be present since the
1156 * default value is inappropriate for YCbCr. Fill in the
1157 * proper value if application didn't set it.
1161 if (!TIFFGetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1164 long top
= 1L << td
->td_bitspersample
;
1166 refbw
[1] = (float)(top
-1L);
1167 refbw
[2] = (float)(top
>>1);
1168 refbw
[3] = refbw
[1];
1169 refbw
[4] = refbw
[2];
1170 refbw
[5] = refbw
[1];
1171 TIFFSetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1176 case PHOTOMETRIC_PALETTE
: /* disallowed by Tech Note */
1177 case PHOTOMETRIC_MASK
:
1178 TIFFErrorExt(tif
->tif_clientdata
, module,
1179 "PhotometricInterpretation %d not allowed for JPEG",
1180 (int) sp
->photometric
);
1183 /* TIFF 6.0 forbids subsampling of all other color spaces */
1189 /* Verify miscellaneous parameters */
1192 * This would need work if libtiff ever supports different
1193 * depths for different components, or if libjpeg ever supports
1194 * run-time selection of depth. Neither is imminent.
1197 /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1198 if (td
->td_bitspersample
!= 8 && td
->td_bitspersample
!= 12)
1200 if (td
->td_bitspersample
!= BITS_IN_JSAMPLE
)
1203 TIFFErrorExt(tif
->tif_clientdata
, module, "BitsPerSample %d not allowed for JPEG",
1204 (int) td
->td_bitspersample
);
1207 sp
->cinfo
.c
.data_precision
= td
->td_bitspersample
;
1209 sp
->cinfo
.c
.bits_in_jsample
= td
->td_bitspersample
;
1212 if ((td
->td_tilelength
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1213 TIFFErrorExt(tif
->tif_clientdata
, module,
1214 "JPEG tile height must be multiple of %d",
1215 sp
->v_sampling
* DCTSIZE
);
1218 if ((td
->td_tilewidth
% (sp
->h_sampling
* DCTSIZE
)) != 0) {
1219 TIFFErrorExt(tif
->tif_clientdata
, module,
1220 "JPEG tile width must be multiple of %d",
1221 sp
->h_sampling
* DCTSIZE
);
1225 if (td
->td_rowsperstrip
< td
->td_imagelength
&&
1226 (td
->td_rowsperstrip
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1227 TIFFErrorExt(tif
->tif_clientdata
, module,
1228 "RowsPerStrip must be multiple of %d for JPEG",
1229 sp
->v_sampling
* DCTSIZE
);
1234 /* Create a JPEGTables field if appropriate */
1235 if (sp
->jpegtablesmode
& (JPEGTABLESMODE_QUANT
|JPEGTABLESMODE_HUFF
)) {
1236 if (!prepare_JPEGTables(tif
))
1238 /* Mark the field present */
1239 /* Can't use TIFFSetField since BEENWRITING is already set! */
1240 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1241 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1243 /* We do not support application-supplied JPEGTables, */
1244 /* so mark the field not present */
1245 TIFFClrFieldBit(tif
, FIELD_JPEGTABLES
);
1248 /* Direct libjpeg output to libtiff's output buffer */
1249 TIFFjpeg_data_dest(sp
, tif
);
1255 * Set encoding state at the start of a strip or tile.
1258 JPEGPreEncode(TIFF
* tif
, tsample_t s
)
1260 JPEGState
*sp
= JState(tif
);
1261 TIFFDirectory
*td
= &tif
->tif_dir
;
1262 static const char module[] = "JPEGPreEncode";
1263 uint32 segment_width
, segment_height
;
1264 int downsampled_input
;
1267 assert(!sp
->cinfo
.comm
.is_decompressor
);
1269 * Set encoding parameters for this strip/tile.
1272 segment_width
= td
->td_tilewidth
;
1273 segment_height
= td
->td_tilelength
;
1274 sp
->bytesperline
= TIFFTileRowSize(tif
);
1276 segment_width
= td
->td_imagewidth
;
1277 segment_height
= td
->td_imagelength
- tif
->tif_row
;
1278 if (segment_height
> td
->td_rowsperstrip
)
1279 segment_height
= td
->td_rowsperstrip
;
1280 sp
->bytesperline
= TIFFScanlineSize(tif
);
1282 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
1283 /* for PC 2, scale down the strip/tile size
1284 * to match a downsampled component
1286 segment_width
= TIFFhowmany(segment_width
, sp
->h_sampling
);
1287 segment_height
= TIFFhowmany(segment_height
, sp
->v_sampling
);
1289 if (segment_width
> 65535 || segment_height
> 65535) {
1290 TIFFErrorExt(tif
->tif_clientdata
, module, "Strip/tile too large for JPEG");
1293 sp
->cinfo
.c
.image_width
= segment_width
;
1294 sp
->cinfo
.c
.image_height
= segment_height
;
1295 downsampled_input
= FALSE
;
1296 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1297 sp
->cinfo
.c
.input_components
= td
->td_samplesperpixel
;
1298 if (sp
->photometric
== PHOTOMETRIC_YCBCR
) {
1299 if (sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1300 sp
->cinfo
.c
.in_color_space
= JCS_RGB
;
1302 sp
->cinfo
.c
.in_color_space
= JCS_YCbCr
;
1303 if (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1)
1304 downsampled_input
= TRUE
;
1306 if (!TIFFjpeg_set_colorspace(sp
, JCS_YCbCr
))
1309 * Set Y sampling factors;
1310 * we assume jpeg_set_colorspace() set the rest to 1
1312 sp
->cinfo
.c
.comp_info
[0].h_samp_factor
= sp
->h_sampling
;
1313 sp
->cinfo
.c
.comp_info
[0].v_samp_factor
= sp
->v_sampling
;
1315 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1316 if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
))
1318 /* jpeg_set_colorspace set all sampling factors to 1 */
1321 sp
->cinfo
.c
.input_components
= 1;
1322 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1323 if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
))
1325 sp
->cinfo
.c
.comp_info
[0].component_id
= s
;
1326 /* jpeg_set_colorspace() set sampling factors to 1 */
1327 if (sp
->photometric
== PHOTOMETRIC_YCBCR
&& s
> 0) {
1328 sp
->cinfo
.c
.comp_info
[0].quant_tbl_no
= 1;
1329 sp
->cinfo
.c
.comp_info
[0].dc_tbl_no
= 1;
1330 sp
->cinfo
.c
.comp_info
[0].ac_tbl_no
= 1;
1333 /* ensure libjpeg won't write any extraneous markers */
1334 sp
->cinfo
.c
.write_JFIF_header
= FALSE
;
1335 sp
->cinfo
.c
.write_Adobe_marker
= FALSE
;
1336 /* set up table handling correctly */
1337 if (! (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
)) {
1338 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1340 unsuppress_quant_table(sp
, 0);
1341 unsuppress_quant_table(sp
, 1);
1343 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
)
1344 sp
->cinfo
.c
.optimize_coding
= FALSE
;
1346 sp
->cinfo
.c
.optimize_coding
= TRUE
;
1347 if (downsampled_input
) {
1348 /* Need to use raw-data interface to libjpeg */
1349 sp
->cinfo
.c
.raw_data_in
= TRUE
;
1350 tif
->tif_encoderow
= JPEGEncodeRaw
;
1351 tif
->tif_encodestrip
= JPEGEncodeRaw
;
1352 tif
->tif_encodetile
= JPEGEncodeRaw
;
1354 /* Use normal interface to libjpeg */
1355 sp
->cinfo
.c
.raw_data_in
= FALSE
;
1356 tif
->tif_encoderow
= JPEGEncode
;
1357 tif
->tif_encodestrip
= JPEGEncode
;
1358 tif
->tif_encodetile
= JPEGEncode
;
1360 /* Start JPEG compressor */
1361 if (!TIFFjpeg_start_compress(sp
, FALSE
))
1363 /* Allocate downsampled-data buffers if needed */
1364 if (downsampled_input
) {
1365 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.c
.comp_info
,
1366 sp
->cinfo
.c
.num_components
))
1375 * Encode a chunk of pixels.
1376 * "Standard" case: incoming data is not downsampled.
1379 JPEGEncode(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
1381 JPEGState
*sp
= JState(tif
);
1387 /* data is expected to be supplied in multiples of a scanline */
1388 nrows
= cc
/ sp
->bytesperline
;
1389 if (cc
% sp
->bytesperline
)
1390 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline discarded");
1392 while (nrows
-- > 0) {
1393 bufptr
[0] = (JSAMPROW
) buf
;
1394 if (TIFFjpeg_write_scanlines(sp
, bufptr
, 1) != 1)
1398 buf
+= sp
->bytesperline
;
1404 * Encode a chunk of pixels.
1405 * Incoming data is expected to be downsampled per sampling factors.
1408 JPEGEncodeRaw(TIFF
* tif
, tidata_t buf
, tsize_t cc
, tsample_t s
)
1410 JPEGState
*sp
= JState(tif
);
1414 JDIMENSION clumps_per_line
, nclump
;
1415 int clumpoffset
, ci
, xpos
, ypos
;
1416 jpeg_component_info
* compptr
;
1417 int samples_per_clump
= sp
->samplesperclump
;
1421 /* data is expected to be supplied in multiples of a scanline */
1422 nrows
= cc
/ sp
->bytesperline
;
1423 if (cc
% sp
->bytesperline
)
1424 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline discarded");
1426 /* Cb,Cr both have sampling factors 1, so this is correct */
1427 clumps_per_line
= sp
->cinfo
.c
.comp_info
[1].downsampled_width
;
1429 while (nrows
-- > 0) {
1431 * Fastest way to separate the data is to make one pass
1432 * over the scanline for each row of each component.
1434 clumpoffset
= 0; /* first sample in clump */
1435 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1436 ci
< sp
->cinfo
.c
.num_components
;
1438 int hsamp
= compptr
->h_samp_factor
;
1439 int vsamp
= compptr
->v_samp_factor
;
1440 int padding
= (int) (compptr
->width_in_blocks
* DCTSIZE
-
1441 clumps_per_line
* hsamp
);
1442 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
1443 inptr
= ((JSAMPLE
*) buf
) + clumpoffset
;
1444 outptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
1446 /* fast path for at least Cb and Cr */
1447 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1448 *outptr
++ = inptr
[0];
1449 inptr
+= samples_per_clump
;
1453 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1454 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1455 *outptr
++ = inptr
[xpos
];
1456 inptr
+= samples_per_clump
;
1459 /* pad each scanline as needed */
1460 for (xpos
= 0; xpos
< padding
; xpos
++) {
1461 *outptr
= outptr
[-1];
1464 clumpoffset
+= hsamp
;
1468 if (sp
->scancount
>= DCTSIZE
) {
1469 int n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1470 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1476 buf
+= sp
->bytesperline
;
1482 * Finish up at the end of a strip or tile.
1485 JPEGPostEncode(TIFF
* tif
)
1487 JPEGState
*sp
= JState(tif
);
1489 if (sp
->scancount
> 0) {
1491 * Need to emit a partial bufferload of downsampled data.
1492 * Pad the data vertically.
1495 jpeg_component_info
* compptr
;
1497 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
1498 ci
< sp
->cinfo
.c
.num_components
;
1500 int vsamp
= compptr
->v_samp_factor
;
1501 tsize_t row_width
= compptr
->width_in_blocks
* DCTSIZE
1503 for (ypos
= sp
->scancount
* vsamp
;
1504 ypos
< DCTSIZE
* vsamp
; ypos
++) {
1505 _TIFFmemcpy((tdata_t
)sp
->ds_buffer
[ci
][ypos
],
1506 (tdata_t
)sp
->ds_buffer
[ci
][ypos
-1],
1511 n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
1512 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1516 return (TIFFjpeg_finish_compress(JState(tif
)));
1520 JPEGCleanup(TIFF
* tif
)
1522 JPEGState
*sp
= JState(tif
);
1526 tif
->tif_tagmethods
.vgetfield
= sp
->vgetparent
;
1527 tif
->tif_tagmethods
.vsetfield
= sp
->vsetparent
;
1529 if( sp
->cinfo_initialized
)
1530 TIFFjpeg_destroy(sp
); /* release libjpeg resources */
1531 if (sp
->jpegtables
) /* tag value */
1532 _TIFFfree(sp
->jpegtables
);
1533 _TIFFfree(tif
->tif_data
); /* release local state */
1534 tif
->tif_data
= NULL
;
1536 _TIFFSetDefaultCompressionState(tif
);
1540 JPEGVSetField(TIFF
* tif
, ttag_t tag
, va_list ap
)
1542 JPEGState
* sp
= JState(tif
);
1543 TIFFDirectory
* td
= &tif
->tif_dir
;
1549 case TIFFTAG_JPEGTABLES
:
1550 v32
= va_arg(ap
, uint32
);
1555 _TIFFsetByteArray(&sp
->jpegtables
, va_arg(ap
, void*),
1557 sp
->jpegtables_length
= v32
;
1558 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1560 case TIFFTAG_JPEGQUALITY
:
1561 sp
->jpegquality
= va_arg(ap
, int);
1562 return (1); /* pseudo tag */
1563 case TIFFTAG_JPEGCOLORMODE
:
1564 sp
->jpegcolormode
= va_arg(ap
, int);
1566 * Mark whether returned data is up-sampled or not
1567 * so TIFFStripSize and TIFFTileSize return values
1568 * that reflect the true amount of data.
1570 tif
->tif_flags
&= ~TIFF_UPSAMPLED
;
1571 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1572 if (td
->td_photometric
== PHOTOMETRIC_YCBCR
&&
1573 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1574 tif
->tif_flags
|= TIFF_UPSAMPLED
;
1576 if (td
->td_ycbcrsubsampling
[0] != 1 ||
1577 td
->td_ycbcrsubsampling
[1] != 1)
1578 ; /* XXX what about up-sampling? */
1582 * Must recalculate cached tile size
1583 * in case sampling state changed.
1585 tif
->tif_tilesize
= isTiled(tif
) ? TIFFTileSize(tif
) : (tsize_t
) -1;
1586 return (1); /* pseudo tag */
1587 case TIFFTAG_JPEGTABLESMODE
:
1588 sp
->jpegtablesmode
= va_arg(ap
, int);
1589 return (1); /* pseudo tag */
1590 case TIFFTAG_YCBCRSUBSAMPLING
:
1591 /* mark the fact that we have a real ycbcrsubsampling! */
1592 sp
->ycbcrsampling_fetched
= 1;
1593 return (*sp
->vsetparent
)(tif
, tag
, ap
);
1594 case TIFFTAG_FAXRECVPARAMS
:
1595 sp
->recvparams
= va_arg(ap
, uint32
);
1597 case TIFFTAG_FAXSUBADDRESS
:
1598 _TIFFsetString(&sp
->subaddress
, va_arg(ap
, char*));
1600 case TIFFTAG_FAXRECVTIME
:
1601 sp
->recvtime
= va_arg(ap
, uint32
);
1603 case TIFFTAG_FAXDCS
:
1604 _TIFFsetString(&sp
->faxdcs
, va_arg(ap
, char*));
1607 return (*sp
->vsetparent
)(tif
, tag
, ap
);
1609 TIFFSetFieldBit(tif
, _TIFFFieldWithTag(tif
, tag
)->field_bit
);
1610 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1615 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
1616 * the TIFF tags, but still use non-default (2,2) values within the jpeg
1617 * data stream itself. In order for TIFF applications to work properly
1618 * - for instance to get the strip buffer size right - it is imperative
1619 * that the subsampling be available before we start reading the image
1620 * data normally. This function will attempt to load the first strip in
1621 * order to get the sampling values from the jpeg data stream. Various
1622 * hacks are various places are done to ensure this function gets called
1623 * before the td_ycbcrsubsampling values are used from the directory structure,
1624 * including calling TIFFGetField() for the YCBCRSUBSAMPLING field from
1625 * TIFFStripSize(), and the printing code in tif_print.c.
1627 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
1628 * discovered sampling does not match the default sampling (2,2) or whatever
1629 * was actually in the tiff tags.
1632 * o This code will cause one whole strip/tile of compressed data to be
1633 * loaded just to get the tags right, even if the imagery is never read.
1634 * It would be more efficient to just load a bit of the header, and
1635 * initialize things from that.
1637 * See the bug in bugzilla for details:
1639 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
1641 * Frank Warmerdam, July 2002
1645 JPEGFixupTestSubsampling( TIFF
* tif
)
1647 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
1648 JPEGState
*sp
= JState(tif
);
1649 TIFFDirectory
*td
= &tif
->tif_dir
;
1651 JPEGInitializeLibJPEG( tif
, 0, 0 );
1654 * Some JPEG-in-TIFF files don't provide the ycbcrsampling tags,
1655 * and use a sampling schema other than the default 2,2. To handle
1656 * this we actually have to scan the header of a strip or tile of
1657 * jpeg data to get the sampling.
1659 if( !sp
->cinfo
.comm
.is_decompressor
1660 || sp
->ycbcrsampling_fetched
1661 || td
->td_photometric
!= PHOTOMETRIC_YCBCR
)
1664 sp
->ycbcrsampling_fetched
= 1;
1665 if( TIFFIsTiled( tif
) )
1667 if( !TIFFFillTile( tif
, 0 ) )
1672 if( !TIFFFillStrip( tif
, 0 ) )
1676 TIFFSetField( tif
, TIFFTAG_YCBCRSUBSAMPLING
,
1677 (uint16
) sp
->h_sampling
, (uint16
) sp
->v_sampling
);
1678 #endif /* CHECK_JPEG_YCBCR_SUBSAMPLING */
1682 JPEGVGetField(TIFF
* tif
, ttag_t tag
, va_list ap
)
1684 JPEGState
* sp
= JState(tif
);
1689 case TIFFTAG_JPEGTABLES
:
1690 *va_arg(ap
, uint32
*) = sp
->jpegtables_length
;
1691 *va_arg(ap
, void**) = sp
->jpegtables
;
1693 case TIFFTAG_JPEGQUALITY
:
1694 *va_arg(ap
, int*) = sp
->jpegquality
;
1696 case TIFFTAG_JPEGCOLORMODE
:
1697 *va_arg(ap
, int*) = sp
->jpegcolormode
;
1699 case TIFFTAG_JPEGTABLESMODE
:
1700 *va_arg(ap
, int*) = sp
->jpegtablesmode
;
1702 case TIFFTAG_YCBCRSUBSAMPLING
:
1703 JPEGFixupTestSubsampling( tif
);
1704 return (*sp
->vgetparent
)(tif
, tag
, ap
);
1706 case TIFFTAG_FAXRECVPARAMS
:
1707 *va_arg(ap
, uint32
*) = sp
->recvparams
;
1709 case TIFFTAG_FAXSUBADDRESS
:
1710 *va_arg(ap
, char**) = sp
->subaddress
;
1712 case TIFFTAG_FAXRECVTIME
:
1713 *va_arg(ap
, uint32
*) = sp
->recvtime
;
1715 case TIFFTAG_FAXDCS
:
1716 *va_arg(ap
, char**) = sp
->faxdcs
;
1719 return (*sp
->vgetparent
)(tif
, tag
, ap
);
1725 JPEGPrintDir(TIFF
* tif
, FILE* fd
, long flags
)
1727 JPEGState
* sp
= JState(tif
);
1732 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
))
1733 fprintf(fd
, " JPEG Tables: (%lu bytes)\n",
1734 (unsigned long) sp
->jpegtables_length
);
1735 if (TIFFFieldSet(tif
,FIELD_RECVPARAMS
))
1736 fprintf(fd
, " Fax Receive Parameters: %08lx\n",
1737 (unsigned long) sp
->recvparams
);
1738 if (TIFFFieldSet(tif
,FIELD_SUBADDRESS
))
1739 fprintf(fd
, " Fax SubAddress: %s\n", sp
->subaddress
);
1740 if (TIFFFieldSet(tif
,FIELD_RECVTIME
))
1741 fprintf(fd
, " Fax Receive Time: %lu secs\n",
1742 (unsigned long) sp
->recvtime
);
1743 if (TIFFFieldSet(tif
,FIELD_FAXDCS
))
1744 fprintf(fd
, " Fax DCS: %s\n", sp
->faxdcs
);
1748 JPEGDefaultStripSize(TIFF
* tif
, uint32 s
)
1750 JPEGState
* sp
= JState(tif
);
1751 TIFFDirectory
*td
= &tif
->tif_dir
;
1753 s
= (*sp
->defsparent
)(tif
, s
);
1754 if (s
< td
->td_imagelength
)
1755 s
= TIFFroundup(s
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
1760 JPEGDefaultTileSize(TIFF
* tif
, uint32
* tw
, uint32
* th
)
1762 JPEGState
* sp
= JState(tif
);
1763 TIFFDirectory
*td
= &tif
->tif_dir
;
1765 (*sp
->deftparent
)(tif
, tw
, th
);
1766 *tw
= TIFFroundup(*tw
, td
->td_ycbcrsubsampling
[0] * DCTSIZE
);
1767 *th
= TIFFroundup(*th
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
1771 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
1772 * now that we allow a TIFF file to be opened in update mode it is necessary
1773 * to have some way of deciding whether compression or decompression is
1774 * desired other than looking at tif->tif_mode. We accomplish this by
1775 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
1776 * If so, we assume decompression is desired.
1778 * This is tricky, because TIFFInitJPEG() is called while the directory is
1779 * being read, and generally speaking the BYTECOUNTS tag won't have been read
1780 * at that point. So we try to defer jpeg library initialization till we
1781 * do have that tag ... basically any access that might require the compressor
1782 * or decompressor that occurs after the reading of the directory.
1784 * In an ideal world compressors or decompressors would be setup
1785 * at the point where a single tile or strip was accessed (for read or write)
1786 * so that stuff like update of missing tiles, or replacement of tiles could
1787 * be done. However, we aren't trying to crack that nut just yet ...
1789 * NFW, Feb 3rd, 2003.
1792 static int JPEGInitializeLibJPEG( TIFF
* tif
, int force_encode
, int force_decode
)
1794 JPEGState
* sp
= JState(tif
);
1795 uint32
*byte_counts
= NULL
;
1796 int data_is_empty
= TRUE
;
1799 if( sp
->cinfo_initialized
)
1803 * Do we have tile data already? Make sure we initialize the
1804 * the state in decompressor mode if we have tile data, even if we
1805 * are not in read-only file access mode.
1807 if( TIFFIsTiled( tif
)
1808 && TIFFGetField( tif
, TIFFTAG_TILEBYTECOUNTS
, &byte_counts
)
1809 && byte_counts
!= NULL
)
1811 data_is_empty
= byte_counts
[0] == 0;
1813 if( !TIFFIsTiled( tif
)
1814 && TIFFGetField( tif
, TIFFTAG_STRIPBYTECOUNTS
, &byte_counts
)
1815 && byte_counts
!= NULL
)
1817 data_is_empty
= byte_counts
[0] == 0;
1822 else if( force_encode
)
1824 else if( tif
->tif_mode
== O_RDONLY
)
1826 else if( data_is_empty
)
1832 * Initialize libjpeg.
1835 if (!TIFFjpeg_create_decompress(sp
))
1839 if (!TIFFjpeg_create_compress(sp
))
1843 sp
->cinfo_initialized
= TRUE
;
1849 TIFFInitJPEG(TIFF
* tif
, int scheme
)
1853 assert(scheme
== COMPRESSION_JPEG
);
1856 * Allocate state block so tag methods have storage to record values.
1858 tif
->tif_data
= (tidata_t
) _TIFFmalloc(sizeof (JPEGState
));
1860 if (tif
->tif_data
== NULL
) {
1861 TIFFErrorExt(tif
->tif_clientdata
, "TIFFInitJPEG", "No space for JPEG state block");
1864 _TIFFmemset( tif
->tif_data
, 0, sizeof(JPEGState
));
1867 sp
->tif
= tif
; /* back link */
1870 * Merge codec-specific tag information and override parent get/set
1873 _TIFFMergeFieldInfo(tif
, jpegFieldInfo
, N(jpegFieldInfo
));
1874 sp
->vgetparent
= tif
->tif_tagmethods
.vgetfield
;
1875 tif
->tif_tagmethods
.vgetfield
= JPEGVGetField
; /* hook for codec tags */
1876 sp
->vsetparent
= tif
->tif_tagmethods
.vsetfield
;
1877 tif
->tif_tagmethods
.vsetfield
= JPEGVSetField
; /* hook for codec tags */
1878 tif
->tif_tagmethods
.printdir
= JPEGPrintDir
; /* hook for codec tags */
1880 /* Default values for codec-specific fields */
1881 sp
->jpegtables
= NULL
;
1882 sp
->jpegtables_length
= 0;
1883 sp
->jpegquality
= 75; /* Default IJG quality */
1884 sp
->jpegcolormode
= JPEGCOLORMODE_RAW
;
1885 sp
->jpegtablesmode
= JPEGTABLESMODE_QUANT
| JPEGTABLESMODE_HUFF
;
1888 sp
->subaddress
= NULL
;
1891 sp
->ycbcrsampling_fetched
= 0;
1894 * Install codec methods.
1896 tif
->tif_setupdecode
= JPEGSetupDecode
;
1897 tif
->tif_predecode
= JPEGPreDecode
;
1898 tif
->tif_decoderow
= JPEGDecode
;
1899 tif
->tif_decodestrip
= JPEGDecode
;
1900 tif
->tif_decodetile
= JPEGDecode
;
1901 tif
->tif_setupencode
= JPEGSetupEncode
;
1902 tif
->tif_preencode
= JPEGPreEncode
;
1903 tif
->tif_postencode
= JPEGPostEncode
;
1904 tif
->tif_encoderow
= JPEGEncode
;
1905 tif
->tif_encodestrip
= JPEGEncode
;
1906 tif
->tif_encodetile
= JPEGEncode
;
1907 tif
->tif_cleanup
= JPEGCleanup
;
1908 sp
->defsparent
= tif
->tif_defstripsize
;
1909 tif
->tif_defstripsize
= JPEGDefaultStripSize
;
1910 sp
->deftparent
= tif
->tif_deftilesize
;
1911 tif
->tif_deftilesize
= JPEGDefaultTileSize
;
1912 tif
->tif_flags
|= TIFF_NOBITREV
; /* no bit reversal, please */
1914 sp
->cinfo_initialized
= FALSE
;
1917 ** Create a JPEGTables field if no directory has yet been created.
1918 ** We do this just to ensure that sufficient space is reserved for
1919 ** the JPEGTables field. It will be properly created the right
1922 if( tif
->tif_diroff
== 0 )
1924 #define SIZE_OF_JPEGTABLES 2000
1925 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1926 sp
->jpegtables_length
= SIZE_OF_JPEGTABLES
;
1927 sp
->jpegtables
= (void *) _TIFFmalloc(sp
->jpegtables_length
);
1928 _TIFFmemset(sp
->jpegtables
, 0, SIZE_OF_JPEGTABLES
);
1929 #undef SIZE_OF_JPEGTABLES
1933 * Mark the TIFFTAG_YCBCRSAMPLES as present even if it is not
1934 * see: JPEGFixupTestSubsampling().
1936 TIFFSetFieldBit( tif
, FIELD_YCBCRSUBSAMPLING
);
1940 #endif /* JPEG_SUPPORT */
1942 /* vim: set ts=8 sts=8 sw=8 noet: */