1 /* $Id: tif_jpeg.c,v 1.127 2017-01-31 13:02:27 erouault Exp $ */
4 * Copyright (c) 1994-1997 Sam Leffler
5 * Copyright (c) 1994-1997 Silicon Graphics, Inc.
7 * Permission to use, copy, modify, distribute, and sell this software and
8 * its documentation for any purpose is hereby granted without fee, provided
9 * that (i) the above copyright notices and this permission notice appear in
10 * all copies of the software and related documentation, and (ii) the names of
11 * Sam Leffler and Silicon Graphics may not be used in any advertising or
12 * publicity relating to the software without the specific, prior written
13 * permission of Sam Leffler and Silicon Graphics.
15 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
19 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
27 #define WIN32_LEAN_AND_MEAN
37 * JPEG Compression support per TIFF Technical Note #2
38 * (*not* per the original TIFF 6.0 spec).
40 * This file is simply an interface to the libjpeg library written by
41 * the Independent JPEG Group. You need release 5 or later of the IJG
42 * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
44 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
48 int TIFFFillStrip(TIFF
* tif
, uint32 strip
);
49 int TIFFFillTile(TIFF
* tif
, uint32 tile
);
50 int TIFFReInitJPEG_12( TIFF
*tif
, int scheme
, int is_encode
);
52 /* We undefine FAR to avoid conflict with JPEG definition */
59 Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
60 not defined. Unfortunately, the MinGW and Borland compilers include
61 a typedef for INT32, which causes a conflict. MSVC does not include
62 a conflicting typedef given the headers which are included.
64 #if defined(__BORLANDC__) || defined(__MINGW32__)
69 The windows RPCNDR.H file defines boolean, but defines it with the
70 unsigned char size. You should compile JPEG library using appropriate
71 definitions in jconfig.h header, but many users compile library in wrong
72 way. That causes errors of the following type:
74 "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
77 For such users we wil fix the problem here. See install.doc file from
78 the JPEG library distribution for details.
81 /* Define "boolean" as unsigned char, not int, per Windows custom. */
82 #if defined(__WIN32__) && !defined(__MINGW32__)
83 # ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
84 typedef unsigned char boolean
;
86 # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
93 * Do we want to do special processing suitable for when JSAMPLE is a
97 #if defined(JPEG_LIB_MK1)
98 # define JPEG_LIB_MK1_OR_12BIT 1
99 #elif BITS_IN_JSAMPLE == 12
100 # define JPEG_LIB_MK1_OR_12BIT 1
104 * We are using width_in_blocks which is supposed to be private to
105 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
106 * renamed this member to width_in_data_units. Since the header has
107 * also renamed a define, use that unique define name in order to
108 * detect the problem header and adjust to suit.
110 #if defined(D_MAX_DATA_UNITS_IN_MCU)
111 #define width_in_blocks width_in_data_units
115 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
116 * in place of plain setjmp. These macros will make it easier.
118 #define SETJMP(jbuf) setjmp(jbuf)
119 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
120 #define JMP_BUF jmp_buf
122 typedef struct jpeg_destination_mgr jpeg_destination_mgr
;
123 typedef struct jpeg_source_mgr jpeg_source_mgr
;
124 typedef struct jpeg_error_mgr jpeg_error_mgr
;
127 * State block for each open TIFF file using
128 * libjpeg to do JPEG compression/decompression.
130 * libjpeg's visible state is either a jpeg_compress_struct
131 * or jpeg_decompress_struct depending on which way we
132 * are going. comm can be used to refer to the fields
133 * which are common to both.
135 * NB: cinfo is required to be the first member of JPEGState,
136 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
141 struct jpeg_compress_struct c
;
142 struct jpeg_decompress_struct d
;
143 struct jpeg_common_struct comm
;
144 } cinfo
; /* NB: must be first */
145 int cinfo_initialized
;
147 jpeg_error_mgr err
; /* libjpeg error manager */
148 JMP_BUF exit_jmpbuf
; /* for catching libjpeg failures */
150 * The following two members could be a union, but
151 * they're small enough that it's not worth the effort.
153 jpeg_destination_mgr dest
; /* data dest for compression */
154 jpeg_source_mgr src
; /* data source for decompression */
156 TIFF
* tif
; /* back link needed by some code */
157 uint16 photometric
; /* copy of PhotometricInterpretation */
158 uint16 h_sampling
; /* luminance sampling factors */
160 tmsize_t bytesperline
; /* decompressed bytes per scanline */
161 /* pointers to intermediate buffers when processing downsampled data */
162 JSAMPARRAY ds_buffer
[MAX_COMPONENTS
];
163 int scancount
; /* number of "scanlines" accumulated */
166 TIFFVGetMethod vgetparent
; /* super-class method */
167 TIFFVSetMethod vsetparent
; /* super-class method */
168 TIFFPrintMethod printdir
; /* super-class method */
169 TIFFStripMethod defsparent
; /* super-class method */
170 TIFFTileMethod deftparent
; /* super-class method */
171 /* pseudo-tag fields */
172 void* jpegtables
; /* JPEGTables tag value, or NULL */
173 uint32 jpegtables_length
; /* number of bytes in same */
174 int jpegquality
; /* Compression quality level */
175 int jpegcolormode
; /* Auto RGB<=>YCbCr convert? */
176 int jpegtablesmode
; /* What to put in JPEGTables */
178 int ycbcrsampling_fetched
;
181 #define JState(tif) ((JPEGState*)(tif)->tif_data)
183 static int JPEGDecode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
184 static int JPEGDecodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
185 static int JPEGEncode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
186 static int JPEGEncodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
187 static int JPEGInitializeLibJPEG(TIFF
* tif
, int decode
);
188 static int DecodeRowError(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
);
190 #define FIELD_JPEGTABLES (FIELD_CODEC+0)
192 static const TIFFField jpegFields
[] = {
193 { TIFFTAG_JPEGTABLES
, -3, -3, TIFF_UNDEFINED
, 0, TIFF_SETGET_C32_UINT8
, TIFF_SETGET_C32_UINT8
, FIELD_JPEGTABLES
, FALSE
, TRUE
, "JPEGTables", NULL
},
194 { TIFFTAG_JPEGQUALITY
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, TRUE
, FALSE
, "", NULL
},
195 { TIFFTAG_JPEGCOLORMODE
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, FALSE
, FALSE
, "", NULL
},
196 { TIFFTAG_JPEGTABLESMODE
, 0, 0, TIFF_ANY
, 0, TIFF_SETGET_INT
, TIFF_SETGET_UNDEFINED
, FIELD_PSEUDO
, FALSE
, FALSE
, "", NULL
}
200 * libjpeg interface layer.
202 * We use setjmp/longjmp to return control to libtiff
203 * when a fatal error is encountered within the JPEG
204 * library. We also direct libjpeg error and warning
205 * messages through the appropriate libtiff handlers.
209 * Error handling routines (these replace corresponding
210 * IJG routines from jerror.c). These are used for both
211 * compression and decompression.
214 TIFFjpeg_error_exit(j_common_ptr cinfo
)
216 JPEGState
*sp
= (JPEGState
*) cinfo
; /* NB: cinfo assumed first */
217 char buffer
[JMSG_LENGTH_MAX
];
219 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
220 TIFFErrorExt(sp
->tif
->tif_clientdata
, "JPEGLib", "%s", buffer
); /* display the error message */
221 jpeg_abort(cinfo
); /* clean up libjpeg state */
222 LONGJMP(sp
->exit_jmpbuf
, 1); /* return to libtiff caller */
226 * This routine is invoked only for warning messages,
227 * since error_exit does its own thing and trace_level
231 TIFFjpeg_output_message(j_common_ptr cinfo
)
233 char buffer
[JMSG_LENGTH_MAX
];
235 (*cinfo
->err
->format_message
) (cinfo
, buffer
);
236 TIFFWarningExt(((JPEGState
*) cinfo
)->tif
->tif_clientdata
, "JPEGLib", "%s", buffer
);
240 * Interface routines. This layer of routines exists
241 * primarily to limit side-effects from using setjmp.
242 * Also, normal/error returns are converted into return
243 * values per libtiff practice.
245 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
246 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
249 TIFFjpeg_create_compress(JPEGState
* sp
)
251 /* initialize JPEG error handling */
252 sp
->cinfo
.c
.err
= jpeg_std_error(&sp
->err
);
253 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
254 sp
->err
.output_message
= TIFFjpeg_output_message
;
256 /* set client_data to avoid UMR warning from tools like Purify */
257 sp
->cinfo
.c
.client_data
= NULL
;
259 return CALLVJPEG(sp
, jpeg_create_compress(&sp
->cinfo
.c
));
263 TIFFjpeg_create_decompress(JPEGState
* sp
)
265 /* initialize JPEG error handling */
266 sp
->cinfo
.d
.err
= jpeg_std_error(&sp
->err
);
267 sp
->err
.error_exit
= TIFFjpeg_error_exit
;
268 sp
->err
.output_message
= TIFFjpeg_output_message
;
270 /* set client_data to avoid UMR warning from tools like Purify */
271 sp
->cinfo
.d
.client_data
= NULL
;
273 return CALLVJPEG(sp
, jpeg_create_decompress(&sp
->cinfo
.d
));
277 TIFFjpeg_set_defaults(JPEGState
* sp
)
279 return CALLVJPEG(sp
, jpeg_set_defaults(&sp
->cinfo
.c
));
283 TIFFjpeg_set_colorspace(JPEGState
* sp
, J_COLOR_SPACE colorspace
)
285 return CALLVJPEG(sp
, jpeg_set_colorspace(&sp
->cinfo
.c
, colorspace
));
289 TIFFjpeg_set_quality(JPEGState
* sp
, int quality
, boolean force_baseline
)
292 jpeg_set_quality(&sp
->cinfo
.c
, quality
, force_baseline
));
296 TIFFjpeg_suppress_tables(JPEGState
* sp
, boolean suppress
)
298 return CALLVJPEG(sp
, jpeg_suppress_tables(&sp
->cinfo
.c
, suppress
));
302 TIFFjpeg_start_compress(JPEGState
* sp
, boolean write_all_tables
)
305 jpeg_start_compress(&sp
->cinfo
.c
, write_all_tables
));
309 TIFFjpeg_write_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int num_lines
)
311 return CALLJPEG(sp
, -1, (int) jpeg_write_scanlines(&sp
->cinfo
.c
,
312 scanlines
, (JDIMENSION
) num_lines
));
316 TIFFjpeg_write_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int num_lines
)
318 return CALLJPEG(sp
, -1, (int) jpeg_write_raw_data(&sp
->cinfo
.c
,
319 data
, (JDIMENSION
) num_lines
));
323 TIFFjpeg_finish_compress(JPEGState
* sp
)
325 return CALLVJPEG(sp
, jpeg_finish_compress(&sp
->cinfo
.c
));
329 TIFFjpeg_write_tables(JPEGState
* sp
)
331 return CALLVJPEG(sp
, jpeg_write_tables(&sp
->cinfo
.c
));
335 TIFFjpeg_read_header(JPEGState
* sp
, boolean require_image
)
337 return CALLJPEG(sp
, -1, jpeg_read_header(&sp
->cinfo
.d
, require_image
));
341 TIFFjpeg_start_decompress(JPEGState
* sp
)
343 return CALLVJPEG(sp
, jpeg_start_decompress(&sp
->cinfo
.d
));
347 TIFFjpeg_read_scanlines(JPEGState
* sp
, JSAMPARRAY scanlines
, int max_lines
)
349 return CALLJPEG(sp
, -1, (int) jpeg_read_scanlines(&sp
->cinfo
.d
,
350 scanlines
, (JDIMENSION
) max_lines
));
354 TIFFjpeg_read_raw_data(JPEGState
* sp
, JSAMPIMAGE data
, int max_lines
)
356 return CALLJPEG(sp
, -1, (int) jpeg_read_raw_data(&sp
->cinfo
.d
,
357 data
, (JDIMENSION
) max_lines
));
361 TIFFjpeg_finish_decompress(JPEGState
* sp
)
363 return CALLJPEG(sp
, -1, (int) jpeg_finish_decompress(&sp
->cinfo
.d
));
367 TIFFjpeg_abort(JPEGState
* sp
)
369 return CALLVJPEG(sp
, jpeg_abort(&sp
->cinfo
.comm
));
373 TIFFjpeg_destroy(JPEGState
* sp
)
375 return CALLVJPEG(sp
, jpeg_destroy(&sp
->cinfo
.comm
));
379 TIFFjpeg_alloc_sarray(JPEGState
* sp
, int pool_id
,
380 JDIMENSION samplesperrow
, JDIMENSION numrows
)
382 return CALLJPEG(sp
, (JSAMPARRAY
) NULL
,
383 (*sp
->cinfo
.comm
.mem
->alloc_sarray
)
384 (&sp
->cinfo
.comm
, pool_id
, samplesperrow
, numrows
));
388 * JPEG library destination data manager.
389 * These routines direct compressed data from libjpeg into the
390 * libtiff output buffer.
394 std_init_destination(j_compress_ptr cinfo
)
396 JPEGState
* sp
= (JPEGState
*) cinfo
;
399 sp
->dest
.next_output_byte
= (JOCTET
*) tif
->tif_rawdata
;
400 sp
->dest
.free_in_buffer
= (size_t) tif
->tif_rawdatasize
;
404 std_empty_output_buffer(j_compress_ptr cinfo
)
406 JPEGState
* sp
= (JPEGState
*) cinfo
;
409 /* the entire buffer has been filled */
410 tif
->tif_rawcc
= tif
->tif_rawdatasize
;
414 * The Intel IPP performance library does not necessarily fill up
415 * the whole output buffer on each pass, so only dump out the parts
416 * that have been filled.
417 * http://trac.osgeo.org/gdal/wiki/JpegIPP
419 if ( sp
->dest
.free_in_buffer
>= 0 ) {
420 tif
->tif_rawcc
= tif
->tif_rawdatasize
- sp
->dest
.free_in_buffer
;
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
= (uint8
*) sp
->dest
.next_output_byte
;
439 tif
->tif_rawdatasize
- (tmsize_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
;
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((void*) sp
->jpegtables
,
475 (tmsize_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
-= (uint32
) 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((tmsize_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
;
534 std_fill_input_buffer(j_decompress_ptr cinfo
)
536 JPEGState
* sp
= (JPEGState
* ) cinfo
;
537 static const JOCTET dummy_EOI
[2] = { 0xFF, JPEG_EOI
};
541 * The Intel IPP performance library does not necessarily read the whole
542 * input buffer in one pass, so it is possible to get here with data
545 * We just return without doing anything, until the entire buffer has
547 * http://trac.osgeo.org/gdal/wiki/JpegIPP
549 if( sp
->src
.bytes_in_buffer
> 0 ) {
555 * Normally the whole strip/tile is read and so we don't need to do
556 * a fill. In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
557 * all the data, but the rawdata is refreshed between scanlines and
558 * we push this into the io machinery in JPEGDecode().
559 * http://trac.osgeo.org/gdal/ticket/3894
562 WARNMS(cinfo
, JWRN_JPEG_EOF
);
563 /* insert a fake EOI marker */
564 sp
->src
.next_input_byte
= dummy_EOI
;
565 sp
->src
.bytes_in_buffer
= 2;
570 std_skip_input_data(j_decompress_ptr cinfo
, long num_bytes
)
572 JPEGState
* sp
= (JPEGState
*) cinfo
;
575 if ((size_t)num_bytes
> sp
->src
.bytes_in_buffer
) {
576 /* oops, buffer overrun */
577 (void) std_fill_input_buffer(cinfo
);
579 sp
->src
.next_input_byte
+= (size_t) num_bytes
;
580 sp
->src
.bytes_in_buffer
-= (size_t) num_bytes
;
586 std_term_source(j_decompress_ptr cinfo
)
588 /* No work necessary here */
593 TIFFjpeg_data_src(JPEGState
* sp
, TIFF
* tif
)
596 sp
->cinfo
.d
.src
= &sp
->src
;
597 sp
->src
.init_source
= std_init_source
;
598 sp
->src
.fill_input_buffer
= std_fill_input_buffer
;
599 sp
->src
.skip_input_data
= std_skip_input_data
;
600 sp
->src
.resync_to_restart
= jpeg_resync_to_restart
;
601 sp
->src
.term_source
= std_term_source
;
602 sp
->src
.bytes_in_buffer
= 0; /* for safety */
603 sp
->src
.next_input_byte
= NULL
;
607 * Alternate source manager for reading from JPEGTables.
608 * We can share all the code except for the init routine.
612 tables_init_source(j_decompress_ptr cinfo
)
614 JPEGState
* sp
= (JPEGState
*) cinfo
;
616 sp
->src
.next_input_byte
= (const JOCTET
*) sp
->jpegtables
;
617 sp
->src
.bytes_in_buffer
= (size_t) sp
->jpegtables_length
;
621 TIFFjpeg_tables_src(JPEGState
* sp
, TIFF
* tif
)
623 TIFFjpeg_data_src(sp
, tif
);
624 sp
->src
.init_source
= tables_init_source
;
628 * Allocate downsampled-data buffers needed for downsampled I/O.
629 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
630 * We use libjpeg's allocator so that buffers will be released automatically
631 * when done with strip/tile.
632 * This is also a handy place to compute samplesperclump, bytesperline.
635 alloc_downsampled_buffers(TIFF
* tif
, jpeg_component_info
* comp_info
,
638 JPEGState
* sp
= JState(tif
);
640 jpeg_component_info
* compptr
;
642 int samples_per_clump
= 0;
644 for (ci
= 0, compptr
= comp_info
; ci
< num_components
;
646 samples_per_clump
+= compptr
->h_samp_factor
*
647 compptr
->v_samp_factor
;
648 buf
= TIFFjpeg_alloc_sarray(sp
, JPOOL_IMAGE
,
649 compptr
->width_in_blocks
* DCTSIZE
,
650 (JDIMENSION
) (compptr
->v_samp_factor
*DCTSIZE
));
653 sp
->ds_buffer
[ci
] = buf
;
655 sp
->samplesperclump
= samples_per_clump
;
664 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
666 #define JPEG_MARKER_SOF0 0xC0
667 #define JPEG_MARKER_SOF1 0xC1
668 #define JPEG_MARKER_SOF2 0xC2
669 #define JPEG_MARKER_SOF9 0xC9
670 #define JPEG_MARKER_SOF10 0xCA
671 #define JPEG_MARKER_DHT 0xC4
672 #define JPEG_MARKER_SOI 0xD8
673 #define JPEG_MARKER_SOS 0xDA
674 #define JPEG_MARKER_DQT 0xDB
675 #define JPEG_MARKER_DRI 0xDD
676 #define JPEG_MARKER_APP0 0xE0
677 #define JPEG_MARKER_COM 0xFE
678 struct JPEGFixupTagsSubsamplingData
683 uint8
* buffercurrentbyte
;
684 uint32 bufferbytesleft
;
686 uint64 filebytesleft
;
687 uint8 filepositioned
;
689 static void JPEGFixupTagsSubsampling(TIFF
* tif
);
690 static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData
* data
);
691 static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData
* data
, uint8
* result
);
692 static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData
* data
, uint16
* result
);
693 static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData
* data
, uint16 skiplength
);
698 JPEGFixupTags(TIFF
* tif
)
700 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
701 JPEGState
* sp
= JState(tif
);
702 if ((tif
->tif_dir
.td_photometric
==PHOTOMETRIC_YCBCR
)&&
703 (tif
->tif_dir
.td_planarconfig
==PLANARCONFIG_CONTIG
)&&
704 (tif
->tif_dir
.td_samplesperpixel
==3) &&
705 !sp
->ycbcrsampling_fetched
)
706 JPEGFixupTagsSubsampling(tif
);
712 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
715 JPEGFixupTagsSubsampling(TIFF
* tif
)
718 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
719 * the TIFF tags, but still use non-default (2,2) values within the jpeg
720 * data stream itself. In order for TIFF applications to work properly
721 * - for instance to get the strip buffer size right - it is imperative
722 * that the subsampling be available before we start reading the image
723 * data normally. This function will attempt to analyze the first strip in
724 * order to get the sampling values from the jpeg data stream.
726 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
727 * discovered sampling does not match the default sampling (2,2) or whatever
728 * was actually in the tiff tags.
730 * See the bug in bugzilla for details:
732 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
734 * Frank Warmerdam, July 2002
735 * Joris Van Damme, May 2007
737 static const char module
[] = "JPEGFixupTagsSubsampling";
738 struct JPEGFixupTagsSubsamplingData m
;
740 _TIFFFillStriles( tif
);
742 if( tif
->tif_dir
.td_stripbytecount
== NULL
743 || tif
->tif_dir
.td_stripoffset
== NULL
744 || tif
->tif_dir
.td_stripbytecount
[0] == 0 )
746 /* Do not even try to check if the first strip/tile does not
747 yet exist, as occurs when GDAL has created a new NULL file
754 m
.buffer
=_TIFFmalloc(m
.buffersize
);
757 TIFFWarningExt(tif
->tif_clientdata
,module
,
758 "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
761 m
.buffercurrentbyte
=NULL
;
763 m
.fileoffset
=tif
->tif_dir
.td_stripoffset
[0];
765 m
.filebytesleft
=tif
->tif_dir
.td_stripbytecount
[0];
766 if (!JPEGFixupTagsSubsamplingSec(&m
))
767 TIFFWarningExt(tif
->tif_clientdata
,module
,
768 "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
773 JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData
* data
)
775 static const char module
[] = "JPEGFixupTagsSubsamplingSec";
781 if (!JPEGFixupTagsSubsamplingReadByte(data
,&m
))
788 if (!JPEGFixupTagsSubsamplingReadByte(data
,&m
))
795 case JPEG_MARKER_SOI
:
796 /* this type of marker has no data and should be skipped */
798 case JPEG_MARKER_COM
:
799 case JPEG_MARKER_APP0
:
800 case JPEG_MARKER_APP0
+1:
801 case JPEG_MARKER_APP0
+2:
802 case JPEG_MARKER_APP0
+3:
803 case JPEG_MARKER_APP0
+4:
804 case JPEG_MARKER_APP0
+5:
805 case JPEG_MARKER_APP0
+6:
806 case JPEG_MARKER_APP0
+7:
807 case JPEG_MARKER_APP0
+8:
808 case JPEG_MARKER_APP0
+9:
809 case JPEG_MARKER_APP0
+10:
810 case JPEG_MARKER_APP0
+11:
811 case JPEG_MARKER_APP0
+12:
812 case JPEG_MARKER_APP0
+13:
813 case JPEG_MARKER_APP0
+14:
814 case JPEG_MARKER_APP0
+15:
815 case JPEG_MARKER_DQT
:
816 case JPEG_MARKER_SOS
:
817 case JPEG_MARKER_DHT
:
818 case JPEG_MARKER_DRI
:
819 /* this type of marker has data, but it has no use to us and should be skipped */
822 if (!JPEGFixupTagsSubsamplingReadWord(data
,&n
))
828 JPEGFixupTagsSubsamplingSkip(data
,n
);
831 case JPEG_MARKER_SOF0
: /* Baseline sequential Huffman */
832 case JPEG_MARKER_SOF1
: /* Extended sequential Huffman */
833 case JPEG_MARKER_SOF2
: /* Progressive Huffman: normally not allowed by TechNote, but that doesn't hurt supporting it */
834 case JPEG_MARKER_SOF9
: /* Extended sequential arithmetic */
835 case JPEG_MARKER_SOF10
: /* Progressive arithmetic: normally not allowed by TechNote, but that doesn't hurt supporting it */
836 /* this marker contains the subsampling factors we're scanning for */
842 if (!JPEGFixupTagsSubsamplingReadWord(data
,&n
))
844 if (n
!=8+data
->tif
->tif_dir
.td_samplesperpixel
*3)
846 JPEGFixupTagsSubsamplingSkip(data
,7);
847 if (!JPEGFixupTagsSubsamplingReadByte(data
,&p
))
851 JPEGFixupTagsSubsamplingSkip(data
,1);
852 for (o
=1; o
<data
->tif
->tif_dir
.td_samplesperpixel
; o
++)
854 JPEGFixupTagsSubsamplingSkip(data
,1);
855 if (!JPEGFixupTagsSubsamplingReadByte(data
,&p
))
859 TIFFWarningExt(data
->tif
->tif_clientdata
,module
,
860 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
863 JPEGFixupTagsSubsamplingSkip(data
,1);
865 if (((ph
!=1)&&(ph
!=2)&&(ph
!=4))||((pv
!=1)&&(pv
!=2)&&(pv
!=4)))
867 TIFFWarningExt(data
->tif
->tif_clientdata
,module
,
868 "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
871 if ((ph
!=data
->tif
->tif_dir
.td_ycbcrsubsampling
[0])||(pv
!=data
->tif
->tif_dir
.td_ycbcrsubsampling
[1]))
873 TIFFWarningExt(data
->tif
->tif_clientdata
,module
,
874 "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
875 (int)data
->tif
->tif_dir
.td_ycbcrsubsampling
[0],
876 (int)data
->tif
->tif_dir
.td_ycbcrsubsampling
[1],
878 data
->tif
->tif_dir
.td_ycbcrsubsampling
[0]=ph
;
879 data
->tif
->tif_dir
.td_ycbcrsubsampling
[1]=pv
;
890 JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData
* data
, uint8
* result
)
892 if (data
->bufferbytesleft
==0)
895 if (data
->filebytesleft
==0)
897 if (!data
->filepositioned
)
899 TIFFSeekFile(data
->tif
,data
->fileoffset
,SEEK_SET
);
900 data
->filepositioned
=1;
903 if ((uint64
)m
>data
->filebytesleft
)
904 m
=(uint32
)data
->filebytesleft
;
905 assert(m
<0x80000000UL
);
906 if (TIFFReadFile(data
->tif
,data
->buffer
,(tmsize_t
)m
)!=(tmsize_t
)m
)
908 data
->buffercurrentbyte
=data
->buffer
;
909 data
->bufferbytesleft
=m
;
911 data
->filebytesleft
-=m
;
913 *result
=*data
->buffercurrentbyte
;
914 data
->buffercurrentbyte
++;
915 data
->bufferbytesleft
--;
920 JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData
* data
, uint16
* result
)
924 if (!JPEGFixupTagsSubsamplingReadByte(data
,&ma
))
926 if (!JPEGFixupTagsSubsamplingReadByte(data
,&mb
))
933 JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData
* data
, uint16 skiplength
)
935 if ((uint32
)skiplength
<=data
->bufferbytesleft
)
937 data
->buffercurrentbyte
+=skiplength
;
938 data
->bufferbytesleft
-=skiplength
;
943 m
=(uint16
)(skiplength
-data
->bufferbytesleft
);
944 if (m
<=data
->filebytesleft
)
946 data
->bufferbytesleft
=0;
948 data
->filebytesleft
-=m
;
949 data
->filepositioned
=0;
953 data
->bufferbytesleft
=0;
954 data
->filebytesleft
=0;
963 JPEGSetupDecode(TIFF
* tif
)
965 JPEGState
* sp
= JState(tif
);
966 TIFFDirectory
*td
= &tif
->tif_dir
;
968 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
969 if( tif
->tif_dir
.td_bitspersample
== 12 )
970 return TIFFReInitJPEG_12( tif
, COMPRESSION_JPEG
, 0 );
973 JPEGInitializeLibJPEG( tif
, TRUE
);
976 assert(sp
->cinfo
.comm
.is_decompressor
);
978 /* Read JPEGTables if it is present */
979 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
)) {
980 TIFFjpeg_tables_src(sp
, tif
);
981 if(TIFFjpeg_read_header(sp
,FALSE
) != JPEG_HEADER_TABLES_ONLY
) {
982 TIFFErrorExt(tif
->tif_clientdata
, "JPEGSetupDecode", "Bogus JPEGTables field");
987 /* Grab parameters that are same for all strips/tiles */
988 sp
->photometric
= td
->td_photometric
;
989 switch (sp
->photometric
) {
990 case PHOTOMETRIC_YCBCR
:
991 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
992 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
995 /* TIFF 6.0 forbids subsampling of all other color spaces */
1001 /* Set up for reading normal data */
1002 TIFFjpeg_data_src(sp
, tif
);
1003 tif
->tif_postdecode
= _TIFFNoPostDecode
; /* override byte swapping */
1008 * Set up for decoding a strip or tile.
1010 /*ARGSUSED*/ static int
1011 JPEGPreDecode(TIFF
* tif
, uint16 s
)
1013 JPEGState
*sp
= JState(tif
);
1014 TIFFDirectory
*td
= &tif
->tif_dir
;
1015 static const char module
[] = "JPEGPreDecode";
1016 uint32 segment_width
, segment_height
;
1017 int downsampled_output
;
1022 if (sp
->cinfo
.comm
.is_decompressor
== 0)
1024 tif
->tif_setupdecode( tif
);
1027 assert(sp
->cinfo
.comm
.is_decompressor
);
1029 * Reset decoder state from any previous strip/tile,
1030 * in case application didn't read the whole strip.
1032 if (!TIFFjpeg_abort(sp
))
1035 * Read the header for this strip/tile.
1038 if (TIFFjpeg_read_header(sp
, TRUE
) != JPEG_HEADER_OK
)
1041 tif
->tif_rawcp
= (uint8
*) sp
->src
.next_input_byte
;
1042 tif
->tif_rawcc
= sp
->src
.bytes_in_buffer
;
1045 * Check image parameters and set decompression parameters.
1047 segment_width
= td
->td_imagewidth
;
1048 segment_height
= td
->td_imagelength
- tif
->tif_row
;
1050 segment_width
= td
->td_tilewidth
;
1051 segment_height
= td
->td_tilelength
;
1052 sp
->bytesperline
= TIFFTileRowSize(tif
);
1054 if (segment_height
> td
->td_rowsperstrip
)
1055 segment_height
= td
->td_rowsperstrip
;
1056 sp
->bytesperline
= TIFFScanlineSize(tif
);
1058 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
1060 * For PC 2, scale down the expected strip/tile size
1061 * to match a downsampled component
1063 segment_width
= TIFFhowmany_32(segment_width
, sp
->h_sampling
);
1064 segment_height
= TIFFhowmany_32(segment_height
, sp
->v_sampling
);
1066 if (sp
->cinfo
.d
.image_width
< segment_width
||
1067 sp
->cinfo
.d
.image_height
< segment_height
) {
1068 TIFFWarningExt(tif
->tif_clientdata
, module
,
1069 "Improper JPEG strip/tile size, "
1070 "expected %dx%d, got %dx%d",
1071 segment_width
, segment_height
,
1072 sp
->cinfo
.d
.image_width
,
1073 sp
->cinfo
.d
.image_height
);
1075 if (sp
->cinfo
.d
.image_width
> segment_width
||
1076 sp
->cinfo
.d
.image_height
> segment_height
) {
1078 * This case could be dangerous, if the strip or tile size has
1079 * been reported as less than the amount of data jpeg will
1080 * return, some potential security issues arise. Catch this
1081 * case and error out.
1083 TIFFErrorExt(tif
->tif_clientdata
, module
,
1084 "JPEG strip/tile size exceeds expected dimensions,"
1085 " expected %dx%d, got %dx%d",
1086 segment_width
, segment_height
,
1087 sp
->cinfo
.d
.image_width
, sp
->cinfo
.d
.image_height
);
1090 if (sp
->cinfo
.d
.num_components
!=
1091 (td
->td_planarconfig
== PLANARCONFIG_CONTIG
?
1092 td
->td_samplesperpixel
: 1)) {
1093 TIFFErrorExt(tif
->tif_clientdata
, module
, "Improper JPEG component count");
1097 if (12 != td
->td_bitspersample
&& 8 != td
->td_bitspersample
) {
1098 TIFFErrorExt(tif
->tif_clientdata
, module
, "Improper JPEG data precision");
1101 sp
->cinfo
.d
.data_precision
= td
->td_bitspersample
;
1102 sp
->cinfo
.d
.bits_in_jsample
= td
->td_bitspersample
;
1104 if (sp
->cinfo
.d
.data_precision
!= td
->td_bitspersample
) {
1105 TIFFErrorExt(tif
->tif_clientdata
, module
, "Improper JPEG data precision");
1109 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1110 /* Component 0 should have expected sampling factors */
1111 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= sp
->h_sampling
||
1112 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= sp
->v_sampling
) {
1113 TIFFErrorExt(tif
->tif_clientdata
, module
,
1114 "Improper JPEG sampling factors %d,%d\n"
1115 "Apparently should be %d,%d.",
1116 sp
->cinfo
.d
.comp_info
[0].h_samp_factor
,
1117 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
,
1118 sp
->h_sampling
, sp
->v_sampling
);
1121 /* Rest should have sampling factors 1,1 */
1122 for (ci
= 1; ci
< sp
->cinfo
.d
.num_components
; ci
++) {
1123 if (sp
->cinfo
.d
.comp_info
[ci
].h_samp_factor
!= 1 ||
1124 sp
->cinfo
.d
.comp_info
[ci
].v_samp_factor
!= 1) {
1125 TIFFErrorExt(tif
->tif_clientdata
, module
, "Improper JPEG sampling factors");
1130 /* PC 2's single component should have sampling factors 1,1 */
1131 if (sp
->cinfo
.d
.comp_info
[0].h_samp_factor
!= 1 ||
1132 sp
->cinfo
.d
.comp_info
[0].v_samp_factor
!= 1) {
1133 TIFFErrorExt(tif
->tif_clientdata
, module
, "Improper JPEG sampling factors");
1137 downsampled_output
= FALSE
;
1138 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
1139 sp
->photometric
== PHOTOMETRIC_YCBCR
&&
1140 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1141 /* Convert YCbCr to RGB */
1142 sp
->cinfo
.d
.jpeg_color_space
= JCS_YCbCr
;
1143 sp
->cinfo
.d
.out_color_space
= JCS_RGB
;
1145 /* Suppress colorspace handling */
1146 sp
->cinfo
.d
.jpeg_color_space
= JCS_UNKNOWN
;
1147 sp
->cinfo
.d
.out_color_space
= JCS_UNKNOWN
;
1148 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
&&
1149 (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1))
1150 downsampled_output
= TRUE
;
1151 /* XXX what about up-sampling? */
1153 if (downsampled_output
) {
1154 /* Need to use raw-data interface to libjpeg */
1155 sp
->cinfo
.d
.raw_data_out
= TRUE
;
1156 #if JPEG_LIB_VERSION >= 70
1157 sp
->cinfo
.d
.do_fancy_upsampling
= FALSE
;
1158 #endif /* JPEG_LIB_VERSION >= 70 */
1159 tif
->tif_decoderow
= DecodeRowError
;
1160 tif
->tif_decodestrip
= JPEGDecodeRaw
;
1161 tif
->tif_decodetile
= JPEGDecodeRaw
;
1163 /* Use normal interface to libjpeg */
1164 sp
->cinfo
.d
.raw_data_out
= FALSE
;
1165 tif
->tif_decoderow
= JPEGDecode
;
1166 tif
->tif_decodestrip
= JPEGDecode
;
1167 tif
->tif_decodetile
= JPEGDecode
;
1169 /* Start JPEG decompressor */
1170 if (!TIFFjpeg_start_decompress(sp
))
1172 /* Allocate downsampled-data buffers if needed */
1173 if (downsampled_output
) {
1174 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.d
.comp_info
,
1175 sp
->cinfo
.d
.num_components
))
1177 sp
->scancount
= DCTSIZE
; /* mark buffer empty */
1183 * Decode a chunk of pixels.
1184 * "Standard" case: returned data is not downsampled.
1186 #if !JPEG_LIB_MK1_OR_12BIT
1188 JPEGDecode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1190 JPEGState
*sp
= JState(tif
);
1195 ** Update available information, buffer may have been refilled
1196 ** between decode requests
1198 sp
->src
.next_input_byte
= (const JOCTET
*) tif
->tif_rawcp
;
1199 sp
->src
.bytes_in_buffer
= (size_t) tif
->tif_rawcc
;
1201 if( sp
->bytesperline
== 0 )
1204 nrows
= cc
/ sp
->bytesperline
;
1205 if (cc
% sp
->bytesperline
)
1206 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
,
1207 "fractional scanline not read");
1209 if( nrows
> (tmsize_t
) sp
->cinfo
.d
.image_height
)
1210 nrows
= sp
->cinfo
.d
.image_height
;
1212 /* data is expected to be read in multiples of a scanline */
1218 * In the libjpeg6b-9a 8bit case. We read directly into
1221 JSAMPROW bufptr
= (JSAMPROW
)buf
;
1223 if (TIFFjpeg_read_scanlines(sp
, &bufptr
, 1) != 1)
1227 buf
+= sp
->bytesperline
;
1228 cc
-= sp
->bytesperline
;
1229 } while (--nrows
> 0);
1232 /* Update information on consumed data */
1233 tif
->tif_rawcp
= (uint8
*) sp
->src
.next_input_byte
;
1234 tif
->tif_rawcc
= sp
->src
.bytes_in_buffer
;
1236 /* Close down the decompressor if we've finished the strip or tile. */
1237 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
1238 || TIFFjpeg_finish_decompress(sp
);
1240 #endif /* !JPEG_LIB_MK1_OR_12BIT */
1242 #if JPEG_LIB_MK1_OR_12BIT
1243 /*ARGSUSED*/ static int
1244 JPEGDecode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1246 JPEGState
*sp
= JState(tif
);
1251 ** Update available information, buffer may have been refilled
1252 ** between decode requests
1254 sp
->src
.next_input_byte
= (const JOCTET
*) tif
->tif_rawcp
;
1255 sp
->src
.bytes_in_buffer
= (size_t) tif
->tif_rawcc
;
1257 if( sp
->bytesperline
== 0 )
1260 nrows
= cc
/ sp
->bytesperline
;
1261 if (cc
% sp
->bytesperline
)
1262 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
,
1263 "fractional scanline not read");
1265 if( nrows
> (tmsize_t
) sp
->cinfo
.d
.image_height
)
1266 nrows
= sp
->cinfo
.d
.image_height
;
1268 /* data is expected to be read in multiples of a scanline */
1271 JSAMPROW line_work_buf
= NULL
;
1274 * For 6B, only use temporary buffer for 12 bit imagery.
1275 * For Mk1 always use it.
1277 if( sp
->cinfo
.d
.data_precision
== 12 )
1279 line_work_buf
= (JSAMPROW
)
1280 _TIFFmalloc(sizeof(short) * sp
->cinfo
.d
.output_width
1281 * sp
->cinfo
.d
.num_components
);
1286 if( line_work_buf
!= NULL
)
1289 * In the MK1 case, we always read into a 16bit
1290 * buffer, and then pack down to 12bit or 8bit.
1291 * In 6B case we only read into 16 bit buffer
1292 * for 12bit data, which we need to repack.
1294 if (TIFFjpeg_read_scanlines(sp
, &line_work_buf
, 1) != 1)
1297 if( sp
->cinfo
.d
.data_precision
== 12 )
1299 int value_pairs
= (sp
->cinfo
.d
.output_width
1300 * sp
->cinfo
.d
.num_components
) / 2;
1303 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1305 unsigned char *out_ptr
=
1306 ((unsigned char *) buf
) + iPair
* 3;
1307 JSAMPLE
*in_ptr
= line_work_buf
+ iPair
* 2;
1309 out_ptr
[0] = (unsigned char)((in_ptr
[0] & 0xff0) >> 4);
1310 out_ptr
[1] = (unsigned char)(((in_ptr
[0] & 0xf) << 4)
1311 | ((in_ptr
[1] & 0xf00) >> 8));
1312 out_ptr
[2] = (unsigned char)(((in_ptr
[1] & 0xff) >> 0));
1315 else if( sp
->cinfo
.d
.data_precision
== 8 )
1317 int value_count
= (sp
->cinfo
.d
.output_width
1318 * sp
->cinfo
.d
.num_components
);
1321 for( iValue
= 0; iValue
< value_count
; iValue
++ )
1323 ((unsigned char *) buf
)[iValue
] =
1324 line_work_buf
[iValue
] & 0xff;
1330 buf
+= sp
->bytesperline
;
1331 cc
-= sp
->bytesperline
;
1332 } while (--nrows
> 0);
1334 if( line_work_buf
!= NULL
)
1335 _TIFFfree( line_work_buf
);
1338 /* Update information on consumed data */
1339 tif
->tif_rawcp
= (uint8
*) sp
->src
.next_input_byte
;
1340 tif
->tif_rawcc
= sp
->src
.bytes_in_buffer
;
1342 /* Close down the decompressor if we've finished the strip or tile. */
1343 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
1344 || TIFFjpeg_finish_decompress(sp
);
1346 #endif /* JPEG_LIB_MK1_OR_12BIT */
1348 /*ARGSUSED*/ static int
1349 DecodeRowError(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1356 TIFFErrorExt(tif
->tif_clientdata
, "TIFFReadScanline",
1357 "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
1362 * Decode a chunk of pixels.
1363 * Returned data is downsampled per sampling factors.
1365 /*ARGSUSED*/ static int
1366 JPEGDecodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1368 JPEGState
*sp
= JState(tif
);
1372 /* data is expected to be read in multiples of a scanline */
1373 if ( (nrows
= sp
->cinfo
.d
.image_height
) != 0 ) {
1375 /* Cb,Cr both have sampling factors 1, so this is correct */
1376 JDIMENSION clumps_per_line
= sp
->cinfo
.d
.comp_info
[1].downsampled_width
;
1377 int samples_per_clump
= sp
->samplesperclump
;
1379 #if defined(JPEG_LIB_MK1_OR_12BIT)
1380 unsigned short* tmpbuf
= _TIFFmalloc(sizeof(unsigned short) *
1381 sp
->cinfo
.d
.output_width
*
1382 sp
->cinfo
.d
.num_components
);
1384 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1391 jpeg_component_info
*compptr
;
1392 int ci
, clumpoffset
;
1394 if( cc
< sp
->bytesperline
) {
1395 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1396 "application buffer not large enough for all data.");
1400 /* Reload downsampled-data buffer if needed */
1401 if (sp
->scancount
>= DCTSIZE
) {
1402 int n
= sp
->cinfo
.d
.max_v_samp_factor
* DCTSIZE
;
1403 if (TIFFjpeg_read_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
1408 * Fastest way to unseparate data is to make one pass
1409 * over the scanline for each row of each component.
1411 clumpoffset
= 0; /* first sample in clump */
1412 for (ci
= 0, compptr
= sp
->cinfo
.d
.comp_info
;
1413 ci
< sp
->cinfo
.d
.num_components
;
1415 int hsamp
= compptr
->h_samp_factor
;
1416 int vsamp
= compptr
->v_samp_factor
;
1419 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
1420 JSAMPLE
*inptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
1422 #if defined(JPEG_LIB_MK1_OR_12BIT)
1423 JSAMPLE
*outptr
= (JSAMPLE
*)tmpbuf
+ clumpoffset
;
1425 JSAMPLE
*outptr
= (JSAMPLE
*)buf
+ clumpoffset
;
1426 if (cc
< (tmsize_t
) (clumpoffset
+ samples_per_clump
*(clumps_per_line
-1) + hsamp
)) {
1427 TIFFErrorExt(tif
->tif_clientdata
, "JPEGDecodeRaw",
1428 "application buffer not large enough for all data, possible subsampling issue");
1434 /* fast path for at least Cb and Cr */
1435 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1436 outptr
[0] = *inptr
++;
1437 outptr
+= samples_per_clump
;
1443 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
1444 for (xpos
= 0; xpos
< hsamp
; xpos
++)
1445 outptr
[xpos
] = *inptr
++;
1446 outptr
+= samples_per_clump
;
1449 clumpoffset
+= hsamp
;
1453 #if defined(JPEG_LIB_MK1_OR_12BIT)
1455 if (sp
->cinfo
.d
.data_precision
== 8)
1458 int len
= sp
->cinfo
.d
.output_width
* sp
->cinfo
.d
.num_components
;
1459 for (i
=0; i
<len
; i
++)
1461 ((unsigned char*)buf
)[i
] = tmpbuf
[i
] & 0xff;
1466 int value_pairs
= (sp
->cinfo
.d
.output_width
1467 * sp
->cinfo
.d
.num_components
) / 2;
1469 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1471 unsigned char *out_ptr
= ((unsigned char *) buf
) + iPair
* 3;
1472 JSAMPLE
*in_ptr
= (JSAMPLE
*) (tmpbuf
+ iPair
* 2);
1473 out_ptr
[0] = (unsigned char)((in_ptr
[0] & 0xff0) >> 4);
1474 out_ptr
[1] = (unsigned char)(((in_ptr
[0] & 0xf) << 4)
1475 | ((in_ptr
[1] & 0xf00) >> 8));
1476 out_ptr
[2] = (unsigned char)(((in_ptr
[1] & 0xff) >> 0));
1483 tif
->tif_row
+= sp
->v_sampling
;
1485 buf
+= sp
->bytesperline
;
1486 cc
-= sp
->bytesperline
;
1488 nrows
-= sp
->v_sampling
;
1489 } while (nrows
> 0);
1491 #if defined(JPEG_LIB_MK1_OR_12BIT)
1497 /* Close down the decompressor if done. */
1498 return sp
->cinfo
.d
.output_scanline
< sp
->cinfo
.d
.output_height
1499 || TIFFjpeg_finish_decompress(sp
);
1508 unsuppress_quant_table (JPEGState
* sp
, int tblno
)
1512 if ((qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[tblno
]) != NULL
)
1513 qtbl
->sent_table
= FALSE
;
1517 suppress_quant_table (JPEGState
* sp
, int tblno
)
1521 if ((qtbl
= sp
->cinfo
.c
.quant_tbl_ptrs
[tblno
]) != NULL
)
1522 qtbl
->sent_table
= TRUE
;
1526 unsuppress_huff_table (JPEGState
* sp
, int tblno
)
1530 if ((htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[tblno
]) != NULL
)
1531 htbl
->sent_table
= FALSE
;
1532 if ((htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[tblno
]) != NULL
)
1533 htbl
->sent_table
= FALSE
;
1537 suppress_huff_table (JPEGState
* sp
, int tblno
)
1541 if ((htbl
= sp
->cinfo
.c
.dc_huff_tbl_ptrs
[tblno
]) != NULL
)
1542 htbl
->sent_table
= TRUE
;
1543 if ((htbl
= sp
->cinfo
.c
.ac_huff_tbl_ptrs
[tblno
]) != NULL
)
1544 htbl
->sent_table
= TRUE
;
1548 prepare_JPEGTables(TIFF
* tif
)
1550 JPEGState
* sp
= JState(tif
);
1552 /* Initialize quant tables for current quality setting */
1553 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1555 /* Mark only the tables we want for output */
1556 /* NB: chrominance tables are currently used only with YCbCr */
1557 if (!TIFFjpeg_suppress_tables(sp
, TRUE
))
1559 if (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
) {
1560 unsuppress_quant_table(sp
, 0);
1561 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1562 unsuppress_quant_table(sp
, 1);
1564 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
) {
1565 unsuppress_huff_table(sp
, 0);
1566 if (sp
->photometric
== PHOTOMETRIC_YCBCR
)
1567 unsuppress_huff_table(sp
, 1);
1569 /* Direct libjpeg output into jpegtables */
1570 if (!TIFFjpeg_tables_dest(sp
, tif
))
1572 /* Emit tables-only datastream */
1573 if (!TIFFjpeg_write_tables(sp
))
1580 JPEGSetupEncode(TIFF
* tif
)
1582 JPEGState
* sp
= JState(tif
);
1583 TIFFDirectory
*td
= &tif
->tif_dir
;
1584 static const char module
[] = "JPEGSetupEncode";
1586 #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
1587 if( tif
->tif_dir
.td_bitspersample
== 12 )
1588 return TIFFReInitJPEG_12( tif
, COMPRESSION_JPEG
, 1 );
1591 JPEGInitializeLibJPEG( tif
, FALSE
);
1594 assert(!sp
->cinfo
.comm
.is_decompressor
);
1596 sp
->photometric
= td
->td_photometric
;
1599 * Initialize all JPEG parameters to default values.
1600 * Note that jpeg_set_defaults needs legal values for
1601 * in_color_space and input_components.
1603 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1604 sp
->cinfo
.c
.input_components
= td
->td_samplesperpixel
;
1605 if (sp
->photometric
== PHOTOMETRIC_YCBCR
) {
1606 if (sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
1607 sp
->cinfo
.c
.in_color_space
= JCS_RGB
;
1609 sp
->cinfo
.c
.in_color_space
= JCS_YCbCr
;
1612 if ((td
->td_photometric
== PHOTOMETRIC_MINISWHITE
|| td
->td_photometric
== PHOTOMETRIC_MINISBLACK
) && td
->td_samplesperpixel
== 1)
1613 sp
->cinfo
.c
.in_color_space
= JCS_GRAYSCALE
;
1614 else if (td
->td_photometric
== PHOTOMETRIC_RGB
&& td
->td_samplesperpixel
== 3)
1615 sp
->cinfo
.c
.in_color_space
= JCS_RGB
;
1616 else if (td
->td_photometric
== PHOTOMETRIC_SEPARATED
&& td
->td_samplesperpixel
== 4)
1617 sp
->cinfo
.c
.in_color_space
= JCS_CMYK
;
1619 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1622 sp
->cinfo
.c
.input_components
= 1;
1623 sp
->cinfo
.c
.in_color_space
= JCS_UNKNOWN
;
1625 if (!TIFFjpeg_set_defaults(sp
))
1627 /* Set per-file parameters */
1628 switch (sp
->photometric
) {
1629 case PHOTOMETRIC_YCBCR
:
1630 sp
->h_sampling
= td
->td_ycbcrsubsampling
[0];
1631 sp
->v_sampling
= td
->td_ycbcrsubsampling
[1];
1632 if( sp
->h_sampling
== 0 || sp
->v_sampling
== 0 )
1634 TIFFErrorExt(tif
->tif_clientdata
, module
,
1635 "Invalig horizontal/vertical sampling value");
1638 if( td
->td_bitspersample
> 16 )
1640 TIFFErrorExt(tif
->tif_clientdata
, module
,
1641 "BitsPerSample %d not allowed for JPEG",
1642 td
->td_bitspersample
);
1647 * A ReferenceBlackWhite field *must* be present since the
1648 * default value is inappropriate for YCbCr. Fill in the
1649 * proper value if application didn't set it.
1653 if (!TIFFGetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1656 long top
= 1L << td
->td_bitspersample
;
1658 refbw
[1] = (float)(top
-1L);
1659 refbw
[2] = (float)(top
>>1);
1660 refbw
[3] = refbw
[1];
1661 refbw
[4] = refbw
[2];
1662 refbw
[5] = refbw
[1];
1663 TIFFSetField(tif
, TIFFTAG_REFERENCEBLACKWHITE
,
1668 case PHOTOMETRIC_PALETTE
: /* disallowed by Tech Note */
1669 case PHOTOMETRIC_MASK
:
1670 TIFFErrorExt(tif
->tif_clientdata
, module
,
1671 "PhotometricInterpretation %d not allowed for JPEG",
1672 (int) sp
->photometric
);
1675 /* TIFF 6.0 forbids subsampling of all other color spaces */
1681 /* Verify miscellaneous parameters */
1684 * This would need work if libtiff ever supports different
1685 * depths for different components, or if libjpeg ever supports
1686 * run-time selection of depth. Neither is imminent.
1689 /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1690 if (td
->td_bitspersample
!= 8 && td
->td_bitspersample
!= 12)
1692 if (td
->td_bitspersample
!= BITS_IN_JSAMPLE
)
1695 TIFFErrorExt(tif
->tif_clientdata
, module
, "BitsPerSample %d not allowed for JPEG",
1696 (int) td
->td_bitspersample
);
1699 sp
->cinfo
.c
.data_precision
= td
->td_bitspersample
;
1701 sp
->cinfo
.c
.bits_in_jsample
= td
->td_bitspersample
;
1704 if ((td
->td_tilelength
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1705 TIFFErrorExt(tif
->tif_clientdata
, module
,
1706 "JPEG tile height must be multiple of %d",
1707 sp
->v_sampling
* DCTSIZE
);
1710 if ((td
->td_tilewidth
% (sp
->h_sampling
* DCTSIZE
)) != 0) {
1711 TIFFErrorExt(tif
->tif_clientdata
, module
,
1712 "JPEG tile width must be multiple of %d",
1713 sp
->h_sampling
* DCTSIZE
);
1717 if (td
->td_rowsperstrip
< td
->td_imagelength
&&
1718 (td
->td_rowsperstrip
% (sp
->v_sampling
* DCTSIZE
)) != 0) {
1719 TIFFErrorExt(tif
->tif_clientdata
, module
,
1720 "RowsPerStrip must be multiple of %d for JPEG",
1721 sp
->v_sampling
* DCTSIZE
);
1726 /* Create a JPEGTables field if appropriate */
1727 if (sp
->jpegtablesmode
& (JPEGTABLESMODE_QUANT
|JPEGTABLESMODE_HUFF
)) {
1728 if( sp
->jpegtables
== NULL
1729 || memcmp(sp
->jpegtables
,"\0\0\0\0\0\0\0\0\0",8) == 0 )
1731 if (!prepare_JPEGTables(tif
))
1733 /* Mark the field present */
1734 /* Can't use TIFFSetField since BEENWRITING is already set! */
1735 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
1736 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
1739 /* We do not support application-supplied JPEGTables, */
1740 /* so mark the field not present */
1741 TIFFClrFieldBit(tif
, FIELD_JPEGTABLES
);
1744 /* Direct libjpeg output to libtiff's output buffer */
1745 TIFFjpeg_data_dest(sp
, tif
);
1751 * Set encoding state at the start of a strip or tile.
1754 JPEGPreEncode(TIFF
* tif
, uint16 s
)
1756 JPEGState
*sp
= JState(tif
);
1757 TIFFDirectory
*td
= &tif
->tif_dir
;
1758 static const char module
[] = "JPEGPreEncode";
1759 uint32 segment_width
, segment_height
;
1760 int downsampled_input
;
1764 if (sp
->cinfo
.comm
.is_decompressor
== 1)
1766 tif
->tif_setupencode( tif
);
1769 assert(!sp
->cinfo
.comm
.is_decompressor
);
1771 * Set encoding parameters for this strip/tile.
1774 segment_width
= td
->td_tilewidth
;
1775 segment_height
= td
->td_tilelength
;
1776 sp
->bytesperline
= TIFFTileRowSize(tif
);
1778 segment_width
= td
->td_imagewidth
;
1779 segment_height
= td
->td_imagelength
- tif
->tif_row
;
1780 if (segment_height
> td
->td_rowsperstrip
)
1781 segment_height
= td
->td_rowsperstrip
;
1782 sp
->bytesperline
= TIFFScanlineSize(tif
);
1784 if (td
->td_planarconfig
== PLANARCONFIG_SEPARATE
&& s
> 0) {
1785 /* for PC 2, scale down the strip/tile size
1786 * to match a downsampled component
1788 segment_width
= TIFFhowmany_32(segment_width
, sp
->h_sampling
);
1789 segment_height
= TIFFhowmany_32(segment_height
, sp
->v_sampling
);
1791 if (segment_width
> 65535 || segment_height
> 65535) {
1792 TIFFErrorExt(tif
->tif_clientdata
, module
, "Strip/tile too large for JPEG");
1795 sp
->cinfo
.c
.image_width
= segment_width
;
1796 sp
->cinfo
.c
.image_height
= segment_height
;
1797 downsampled_input
= FALSE
;
1798 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
1799 sp
->cinfo
.c
.input_components
= td
->td_samplesperpixel
;
1800 if (sp
->photometric
== PHOTOMETRIC_YCBCR
) {
1801 if (sp
->jpegcolormode
!= JPEGCOLORMODE_RGB
) {
1802 if (sp
->h_sampling
!= 1 || sp
->v_sampling
!= 1)
1803 downsampled_input
= TRUE
;
1805 if (!TIFFjpeg_set_colorspace(sp
, JCS_YCbCr
))
1808 * Set Y sampling factors;
1809 * we assume jpeg_set_colorspace() set the rest to 1
1811 sp
->cinfo
.c
.comp_info
[0].h_samp_factor
= sp
->h_sampling
;
1812 sp
->cinfo
.c
.comp_info
[0].v_samp_factor
= sp
->v_sampling
;
1814 if (!TIFFjpeg_set_colorspace(sp
, sp
->cinfo
.c
.in_color_space
))
1816 /* jpeg_set_colorspace set all sampling factors to 1 */
1819 if (!TIFFjpeg_set_colorspace(sp
, JCS_UNKNOWN
))
1821 sp
->cinfo
.c
.comp_info
[0].component_id
= s
;
1822 /* jpeg_set_colorspace() set sampling factors to 1 */
1823 if (sp
->photometric
== PHOTOMETRIC_YCBCR
&& s
> 0) {
1824 sp
->cinfo
.c
.comp_info
[0].quant_tbl_no
= 1;
1825 sp
->cinfo
.c
.comp_info
[0].dc_tbl_no
= 1;
1826 sp
->cinfo
.c
.comp_info
[0].ac_tbl_no
= 1;
1829 /* ensure libjpeg won't write any extraneous markers */
1830 sp
->cinfo
.c
.write_JFIF_header
= FALSE
;
1831 sp
->cinfo
.c
.write_Adobe_marker
= FALSE
;
1832 /* set up table handling correctly */
1833 /* calling TIFFjpeg_set_quality() causes quantization tables to be flagged */
1834 /* as being to be emitted, which we don't want in the JPEGTABLESMODE_QUANT */
1835 /* mode, so we must manually suppress them. However TIFFjpeg_set_quality() */
1836 /* should really be called when dealing with files with directories with */
1837 /* mixed qualities. see http://trac.osgeo.org/gdal/ticket/3539 */
1838 if (!TIFFjpeg_set_quality(sp
, sp
->jpegquality
, FALSE
))
1840 if (sp
->jpegtablesmode
& JPEGTABLESMODE_QUANT
) {
1841 suppress_quant_table(sp
, 0);
1842 suppress_quant_table(sp
, 1);
1845 unsuppress_quant_table(sp
, 0);
1846 unsuppress_quant_table(sp
, 1);
1848 if (sp
->jpegtablesmode
& JPEGTABLESMODE_HUFF
)
1850 /* Explicit suppression is only needed if we did not go through the */
1851 /* prepare_JPEGTables() code path, which may be the case if updating */
1852 /* an existing file */
1853 suppress_huff_table(sp
, 0);
1854 suppress_huff_table(sp
, 1);
1855 sp
->cinfo
.c
.optimize_coding
= FALSE
;
1858 sp
->cinfo
.c
.optimize_coding
= TRUE
;
1859 if (downsampled_input
) {
1860 /* Need to use raw-data interface to libjpeg */
1861 sp
->cinfo
.c
.raw_data_in
= TRUE
;
1862 tif
->tif_encoderow
= JPEGEncodeRaw
;
1863 tif
->tif_encodestrip
= JPEGEncodeRaw
;
1864 tif
->tif_encodetile
= JPEGEncodeRaw
;
1866 /* Use normal interface to libjpeg */
1867 sp
->cinfo
.c
.raw_data_in
= FALSE
;
1868 tif
->tif_encoderow
= JPEGEncode
;
1869 tif
->tif_encodestrip
= JPEGEncode
;
1870 tif
->tif_encodetile
= JPEGEncode
;
1872 /* Start JPEG compressor */
1873 if (!TIFFjpeg_start_compress(sp
, FALSE
))
1875 /* Allocate downsampled-data buffers if needed */
1876 if (downsampled_input
) {
1877 if (!alloc_downsampled_buffers(tif
, sp
->cinfo
.c
.comp_info
,
1878 sp
->cinfo
.c
.num_components
))
1887 * Encode a chunk of pixels.
1888 * "Standard" case: incoming data is not downsampled.
1891 JPEGEncode(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1893 JPEGState
*sp
= JState(tif
);
1896 short *line16
= NULL
;
1897 int line16_count
= 0;
1901 /* data is expected to be supplied in multiples of a scanline */
1902 nrows
= cc
/ sp
->bytesperline
;
1903 if (cc
% sp
->bytesperline
)
1904 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
,
1905 "fractional scanline discarded");
1907 /* The last strip will be limited to image size */
1908 if( !isTiled(tif
) && tif
->tif_row
+nrows
> tif
->tif_dir
.td_imagelength
)
1909 nrows
= tif
->tif_dir
.td_imagelength
- tif
->tif_row
;
1911 if( sp
->cinfo
.c
.data_precision
== 12 )
1913 line16_count
= (int)((sp
->bytesperline
* 2) / 3);
1914 line16
= (short *) _TIFFmalloc(sizeof(short) * line16_count
);
1917 TIFFErrorExt(tif
->tif_clientdata
,
1919 "Failed to allocate memory");
1925 while (nrows
-- > 0) {
1927 if( sp
->cinfo
.c
.data_precision
== 12 )
1930 int value_pairs
= line16_count
/ 2;
1933 bufptr
[0] = (JSAMPROW
) line16
;
1935 for( iPair
= 0; iPair
< value_pairs
; iPair
++ )
1937 unsigned char *in_ptr
=
1938 ((unsigned char *) buf
) + iPair
* 3;
1939 JSAMPLE
*out_ptr
= (JSAMPLE
*) (line16
+ iPair
* 2);
1941 out_ptr
[0] = (in_ptr
[0] << 4) | ((in_ptr
[1] & 0xf0) >> 4);
1942 out_ptr
[1] = ((in_ptr
[1] & 0x0f) << 8) | in_ptr
[2];
1947 bufptr
[0] = (JSAMPROW
) buf
;
1949 if (TIFFjpeg_write_scanlines(sp
, bufptr
, 1) != 1)
1953 buf
+= sp
->bytesperline
;
1956 if( sp
->cinfo
.c
.data_precision
== 12 )
1958 _TIFFfree( line16
);
1965 * Encode a chunk of pixels.
1966 * Incoming data is expected to be downsampled per sampling factors.
1969 JPEGEncodeRaw(TIFF
* tif
, uint8
* buf
, tmsize_t cc
, uint16 s
)
1971 JPEGState
*sp
= JState(tif
);
1975 JDIMENSION clumps_per_line
, nclump
;
1976 int clumpoffset
, ci
, xpos
, ypos
;
1977 jpeg_component_info
* compptr
;
1978 int samples_per_clump
= sp
->samplesperclump
;
1979 tmsize_t bytesperclumpline
;
1983 /* data is expected to be supplied in multiples of a clumpline */
1984 /* a clumpline is equivalent to v_sampling desubsampled scanlines */
1985 /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
1986 bytesperclumpline
= (((sp
->cinfo
.c
.image_width
+sp
->h_sampling
-1)/sp
->h_sampling
)
1987 *(sp
->h_sampling
*sp
->v_sampling
+2)*sp
->cinfo
.c
.data_precision
+7)
1990 nrows
= ( cc
/ bytesperclumpline
) * sp
->v_sampling
;
1991 if (cc
% bytesperclumpline
)
1992 TIFFWarningExt(tif
->tif_clientdata
, tif
->tif_name
, "fractional scanline discarded");
1994 /* Cb,Cr both have sampling factors 1, so this is correct */
1995 clumps_per_line
= sp
->cinfo
.c
.comp_info
[1].downsampled_width
;
1999 * Fastest way to separate the data is to make one pass
2000 * over the scanline for each row of each component.
2002 clumpoffset
= 0; /* first sample in clump */
2003 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
2004 ci
< sp
->cinfo
.c
.num_components
;
2006 int hsamp
= compptr
->h_samp_factor
;
2007 int vsamp
= compptr
->v_samp_factor
;
2008 int padding
= (int) (compptr
->width_in_blocks
* DCTSIZE
-
2009 clumps_per_line
* hsamp
);
2010 for (ypos
= 0; ypos
< vsamp
; ypos
++) {
2011 inptr
= ((JSAMPLE
*) buf
) + clumpoffset
;
2012 outptr
= sp
->ds_buffer
[ci
][sp
->scancount
*vsamp
+ ypos
];
2014 /* fast path for at least Cb and Cr */
2015 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
2016 *outptr
++ = inptr
[0];
2017 inptr
+= samples_per_clump
;
2021 for (nclump
= clumps_per_line
; nclump
-- > 0; ) {
2022 for (xpos
= 0; xpos
< hsamp
; xpos
++)
2023 *outptr
++ = inptr
[xpos
];
2024 inptr
+= samples_per_clump
;
2027 /* pad each scanline as needed */
2028 for (xpos
= 0; xpos
< padding
; xpos
++) {
2029 *outptr
= outptr
[-1];
2032 clumpoffset
+= hsamp
;
2036 if (sp
->scancount
>= DCTSIZE
) {
2037 int n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
2038 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
2042 tif
->tif_row
+= sp
->v_sampling
;
2043 buf
+= bytesperclumpline
;
2044 nrows
-= sp
->v_sampling
;
2050 * Finish up at the end of a strip or tile.
2053 JPEGPostEncode(TIFF
* tif
)
2055 JPEGState
*sp
= JState(tif
);
2057 if (sp
->scancount
> 0) {
2059 * Need to emit a partial bufferload of downsampled data.
2060 * Pad the data vertically.
2063 jpeg_component_info
* compptr
;
2065 for (ci
= 0, compptr
= sp
->cinfo
.c
.comp_info
;
2066 ci
< sp
->cinfo
.c
.num_components
;
2068 int vsamp
= compptr
->v_samp_factor
;
2069 tmsize_t row_width
= compptr
->width_in_blocks
* DCTSIZE
2071 for (ypos
= sp
->scancount
* vsamp
;
2072 ypos
< DCTSIZE
* vsamp
; ypos
++) {
2073 _TIFFmemcpy((void*)sp
->ds_buffer
[ci
][ypos
],
2074 (void*)sp
->ds_buffer
[ci
][ypos
-1],
2079 n
= sp
->cinfo
.c
.max_v_samp_factor
* DCTSIZE
;
2080 if (TIFFjpeg_write_raw_data(sp
, sp
->ds_buffer
, n
) != n
)
2084 return (TIFFjpeg_finish_compress(JState(tif
)));
2088 JPEGCleanup(TIFF
* tif
)
2090 JPEGState
*sp
= JState(tif
);
2094 tif
->tif_tagmethods
.vgetfield
= sp
->vgetparent
;
2095 tif
->tif_tagmethods
.vsetfield
= sp
->vsetparent
;
2096 tif
->tif_tagmethods
.printdir
= sp
->printdir
;
2097 if( sp
->cinfo_initialized
)
2098 TIFFjpeg_destroy(sp
); /* release libjpeg resources */
2099 if (sp
->jpegtables
) /* tag value */
2100 _TIFFfree(sp
->jpegtables
);
2101 _TIFFfree(tif
->tif_data
); /* release local state */
2102 tif
->tif_data
= NULL
;
2104 _TIFFSetDefaultCompressionState(tif
);
2108 JPEGResetUpsampled( TIFF
* tif
)
2110 JPEGState
* sp
= JState(tif
);
2111 TIFFDirectory
* td
= &tif
->tif_dir
;
2114 * Mark whether returned data is up-sampled or not so TIFFStripSize
2115 * and TIFFTileSize return values that reflect the true amount of
2118 tif
->tif_flags
&= ~TIFF_UPSAMPLED
;
2119 if (td
->td_planarconfig
== PLANARCONFIG_CONTIG
) {
2120 if (td
->td_photometric
== PHOTOMETRIC_YCBCR
&&
2121 sp
->jpegcolormode
== JPEGCOLORMODE_RGB
) {
2122 tif
->tif_flags
|= TIFF_UPSAMPLED
;
2125 if (td
->td_ycbcrsubsampling
[0] != 1 ||
2126 td
->td_ycbcrsubsampling
[1] != 1)
2127 ; /* XXX what about up-sampling? */
2133 * Must recalculate cached tile size in case sampling state changed.
2134 * Should we really be doing this now if image size isn't set?
2136 if( tif
->tif_tilesize
> 0 )
2137 tif
->tif_tilesize
= isTiled(tif
) ? TIFFTileSize(tif
) : (tmsize_t
)(-1);
2138 if( tif
->tif_scanlinesize
> 0 )
2139 tif
->tif_scanlinesize
= TIFFScanlineSize(tif
);
2143 JPEGVSetField(TIFF
* tif
, uint32 tag
, va_list ap
)
2145 JPEGState
* sp
= JState(tif
);
2146 const TIFFField
* fip
;
2152 case TIFFTAG_JPEGTABLES
:
2153 v32
= (uint32
) va_arg(ap
, uint32
);
2158 _TIFFsetByteArray(&sp
->jpegtables
, va_arg(ap
, void*), v32
);
2159 sp
->jpegtables_length
= v32
;
2160 TIFFSetFieldBit(tif
, FIELD_JPEGTABLES
);
2162 case TIFFTAG_JPEGQUALITY
:
2163 sp
->jpegquality
= (int) va_arg(ap
, int);
2164 return (1); /* pseudo tag */
2165 case TIFFTAG_JPEGCOLORMODE
:
2166 sp
->jpegcolormode
= (int) va_arg(ap
, int);
2167 JPEGResetUpsampled( tif
);
2168 return (1); /* pseudo tag */
2169 case TIFFTAG_PHOTOMETRIC
:
2171 int ret_value
= (*sp
->vsetparent
)(tif
, tag
, ap
);
2172 JPEGResetUpsampled( tif
);
2175 case TIFFTAG_JPEGTABLESMODE
:
2176 sp
->jpegtablesmode
= (int) va_arg(ap
, int);
2177 return (1); /* pseudo tag */
2178 case TIFFTAG_YCBCRSUBSAMPLING
:
2179 /* mark the fact that we have a real ycbcrsubsampling! */
2180 sp
->ycbcrsampling_fetched
= 1;
2181 /* should we be recomputing upsampling info here? */
2182 return (*sp
->vsetparent
)(tif
, tag
, ap
);
2184 return (*sp
->vsetparent
)(tif
, tag
, ap
);
2187 if ((fip
= TIFFFieldWithTag(tif
, tag
)) != NULL
) {
2188 TIFFSetFieldBit(tif
, fip
->field_bit
);
2193 tif
->tif_flags
|= TIFF_DIRTYDIRECT
;
2198 JPEGVGetField(TIFF
* tif
, uint32 tag
, va_list ap
)
2200 JPEGState
* sp
= JState(tif
);
2205 case TIFFTAG_JPEGTABLES
:
2206 *va_arg(ap
, uint32
*) = sp
->jpegtables_length
;
2207 *va_arg(ap
, void**) = sp
->jpegtables
;
2209 case TIFFTAG_JPEGQUALITY
:
2210 *va_arg(ap
, int*) = sp
->jpegquality
;
2212 case TIFFTAG_JPEGCOLORMODE
:
2213 *va_arg(ap
, int*) = sp
->jpegcolormode
;
2215 case TIFFTAG_JPEGTABLESMODE
:
2216 *va_arg(ap
, int*) = sp
->jpegtablesmode
;
2219 return (*sp
->vgetparent
)(tif
, tag
, ap
);
2225 JPEGPrintDir(TIFF
* tif
, FILE* fd
, long flags
)
2227 JPEGState
* sp
= JState(tif
);
2233 if (TIFFFieldSet(tif
,FIELD_JPEGTABLES
))
2234 fprintf(fd
, " JPEG Tables: (%lu bytes)\n",
2235 (unsigned long) sp
->jpegtables_length
);
2237 (*sp
->printdir
)(tif
, fd
, flags
);
2242 JPEGDefaultStripSize(TIFF
* tif
, uint32 s
)
2244 JPEGState
* sp
= JState(tif
);
2245 TIFFDirectory
*td
= &tif
->tif_dir
;
2247 s
= (*sp
->defsparent
)(tif
, s
);
2248 if (s
< td
->td_imagelength
)
2249 s
= TIFFroundup_32(s
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
2254 JPEGDefaultTileSize(TIFF
* tif
, uint32
* tw
, uint32
* th
)
2256 JPEGState
* sp
= JState(tif
);
2257 TIFFDirectory
*td
= &tif
->tif_dir
;
2259 (*sp
->deftparent
)(tif
, tw
, th
);
2260 *tw
= TIFFroundup_32(*tw
, td
->td_ycbcrsubsampling
[0] * DCTSIZE
);
2261 *th
= TIFFroundup_32(*th
, td
->td_ycbcrsubsampling
[1] * DCTSIZE
);
2265 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
2266 * now that we allow a TIFF file to be opened in update mode it is necessary
2267 * to have some way of deciding whether compression or decompression is
2268 * desired other than looking at tif->tif_mode. We accomplish this by
2269 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
2270 * If so, we assume decompression is desired.
2272 * This is tricky, because TIFFInitJPEG() is called while the directory is
2273 * being read, and generally speaking the BYTECOUNTS tag won't have been read
2274 * at that point. So we try to defer jpeg library initialization till we
2275 * do have that tag ... basically any access that might require the compressor
2276 * or decompressor that occurs after the reading of the directory.
2278 * In an ideal world compressors or decompressors would be setup
2279 * at the point where a single tile or strip was accessed (for read or write)
2280 * so that stuff like update of missing tiles, or replacement of tiles could
2281 * be done. However, we aren't trying to crack that nut just yet ...
2283 * NFW, Feb 3rd, 2003.
2286 static int JPEGInitializeLibJPEG( TIFF
* tif
, int decompress
)
2288 JPEGState
* sp
= JState(tif
);
2290 if(sp
->cinfo_initialized
)
2292 if( !decompress
&& sp
->cinfo
.comm
.is_decompressor
)
2293 TIFFjpeg_destroy( sp
);
2294 else if( decompress
&& !sp
->cinfo
.comm
.is_decompressor
)
2295 TIFFjpeg_destroy( sp
);
2299 sp
->cinfo_initialized
= 0;
2303 * Initialize libjpeg.
2306 if (!TIFFjpeg_create_decompress(sp
))
2309 if (!TIFFjpeg_create_compress(sp
))
2311 #ifndef TIFF_JPEG_MAX_MEMORY_TO_USE
2312 #define TIFF_JPEG_MAX_MEMORY_TO_USE (10 * 1024 * 1024)
2314 /* Increase the max memory usable. This helps when creating files */
2315 /* with "big" tile, without using libjpeg temporary files. */
2316 /* For example a 512x512 tile with 3 bands */
2317 /* requires 1.5 MB which is above libjpeg 1MB default */
2318 if( sp
->cinfo
.c
.mem
->max_memory_to_use
< TIFF_JPEG_MAX_MEMORY_TO_USE
)
2319 sp
->cinfo
.c
.mem
->max_memory_to_use
= TIFF_JPEG_MAX_MEMORY_TO_USE
;
2322 sp
->cinfo_initialized
= TRUE
;
2328 TIFFInitJPEG(TIFF
* tif
, int scheme
)
2332 assert(scheme
== COMPRESSION_JPEG
);
2335 * Merge codec-specific tag information.
2337 if (!_TIFFMergeFields(tif
, jpegFields
, TIFFArrayCount(jpegFields
))) {
2338 TIFFErrorExt(tif
->tif_clientdata
,
2340 "Merging JPEG codec-specific tags failed");
2345 * Allocate state block so tag methods have storage to record values.
2347 tif
->tif_data
= (uint8
*) _TIFFmalloc(sizeof (JPEGState
));
2349 if (tif
->tif_data
== NULL
) {
2350 TIFFErrorExt(tif
->tif_clientdata
,
2351 "TIFFInitJPEG", "No space for JPEG state block");
2354 _TIFFmemset(tif
->tif_data
, 0, sizeof(JPEGState
));
2357 sp
->tif
= tif
; /* back link */
2360 * Override parent get/set field methods.
2362 sp
->vgetparent
= tif
->tif_tagmethods
.vgetfield
;
2363 tif
->tif_tagmethods
.vgetfield
= JPEGVGetField
; /* hook for codec tags */
2364 sp
->vsetparent
= tif
->tif_tagmethods
.vsetfield
;
2365 tif
->tif_tagmethods
.vsetfield
= JPEGVSetField
; /* hook for codec tags */
2366 sp
->printdir
= tif
->tif_tagmethods
.printdir
;
2367 tif
->tif_tagmethods
.printdir
= JPEGPrintDir
; /* hook for codec tags */
2369 /* Default values for codec-specific fields */
2370 sp
->jpegtables
= NULL
;
2371 sp
->jpegtables_length
= 0;
2372 sp
->jpegquality
= 75; /* Default IJG quality */
2373 sp
->jpegcolormode
= JPEGCOLORMODE_RAW
;
2374 sp
->jpegtablesmode
= JPEGTABLESMODE_QUANT
| JPEGTABLESMODE_HUFF
;
2375 sp
->ycbcrsampling_fetched
= 0;
2378 * Install codec methods.
2380 tif
->tif_fixuptags
= JPEGFixupTags
;
2381 tif
->tif_setupdecode
= JPEGSetupDecode
;
2382 tif
->tif_predecode
= JPEGPreDecode
;
2383 tif
->tif_decoderow
= JPEGDecode
;
2384 tif
->tif_decodestrip
= JPEGDecode
;
2385 tif
->tif_decodetile
= JPEGDecode
;
2386 tif
->tif_setupencode
= JPEGSetupEncode
;
2387 tif
->tif_preencode
= JPEGPreEncode
;
2388 tif
->tif_postencode
= JPEGPostEncode
;
2389 tif
->tif_encoderow
= JPEGEncode
;
2390 tif
->tif_encodestrip
= JPEGEncode
;
2391 tif
->tif_encodetile
= JPEGEncode
;
2392 tif
->tif_cleanup
= JPEGCleanup
;
2393 sp
->defsparent
= tif
->tif_defstripsize
;
2394 tif
->tif_defstripsize
= JPEGDefaultStripSize
;
2395 sp
->deftparent
= tif
->tif_deftilesize
;
2396 tif
->tif_deftilesize
= JPEGDefaultTileSize
;
2397 tif
->tif_flags
|= TIFF_NOBITREV
; /* no bit reversal, please */
2399 sp
->cinfo_initialized
= FALSE
;
2402 ** Create a JPEGTables field if no directory has yet been created.
2403 ** We do this just to ensure that sufficient space is reserved for
2404 ** the JPEGTables field. It will be properly created the right
2407 if( tif
->tif_diroff
== 0 )
2409 #define SIZE_OF_JPEGTABLES 2000
2411 The following line assumes incorrectly that all JPEG-in-TIFF files will have
2412 a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
2413 when the JPEG data is placed with TIFFWriteRawStrip. The field bit should be
2414 set, anyway, later when actual JPEGTABLES header is generated, so removing it
2415 here hopefully is harmless.
2416 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2418 sp
->jpegtables_length
= SIZE_OF_JPEGTABLES
;
2419 sp
->jpegtables
= (void *) _TIFFmalloc(sp
->jpegtables_length
);
2422 _TIFFmemset(sp
->jpegtables
, 0, SIZE_OF_JPEGTABLES
);
2426 TIFFErrorExt(tif
->tif_clientdata
,
2428 "Failed to allocate memory for JPEG tables");
2431 #undef SIZE_OF_JPEGTABLES
2436 #endif /* JPEG_SUPPORT */
2438 /* vim: set ts=8 sts=8 sw=8 noet: */