1 : /* $Id: tif_jpeg.c,v 1.111 2012-07-06 18:48:04 bfriesen Exp $ */
2 :
3 : /*
4 : * Copyright (c) 1994-1997 Sam Leffler
5 : * Copyright (c) 1994-1997 Silicon Graphics, Inc.
6 : *
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.
14 : *
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.
18 : *
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
24 : * OF THIS SOFTWARE.
25 : */
26 :
27 : #define WIN32_LEAN_AND_MEAN
28 : #define VC_EXTRALEAN
29 :
30 : #include "tiffiop.h"
31 : #ifdef JPEG_SUPPORT
32 :
33 : /*
34 : * TIFF Library
35 : *
36 : * JPEG Compression support per TIFF Technical Note #2
37 : * (*not* per the original TIFF 6.0 spec).
38 : *
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/.
42 : *
43 : * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
44 : */
45 : #include <setjmp.h>
46 :
47 : int TIFFFillStrip(TIFF* tif, uint32 strip);
48 : int TIFFFillTile(TIFF* tif, uint32 tile);
49 : int TIFFReInitJPEG_12( TIFF *tif, int scheme, int is_encode );
50 :
51 : /* We undefine FAR to avoid conflict with JPEG definition */
52 :
53 : #ifdef FAR
54 : #undef FAR
55 : #endif
56 :
57 : /*
58 : Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
59 : not defined. Unfortunately, the MinGW and Borland compilers include
60 : a typedef for INT32, which causes a conflict. MSVC does not include
61 : a conficting typedef given the headers which are included.
62 : */
63 : #if defined(__BORLANDC__) || defined(__MINGW32__)
64 : # define XMD_H 1
65 : #endif
66 :
67 : /*
68 : The windows RPCNDR.H file defines boolean, but defines it with the
69 : unsigned char size. You should compile JPEG library using appropriate
70 : definitions in jconfig.h header, but many users compile library in wrong
71 : way. That causes errors of the following type:
72 :
73 : "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
74 : caller expects 464"
75 :
76 : For such users we wil fix the problem here. See install.doc file from
77 : the JPEG library distribution for details.
78 : */
79 :
80 : /* Define "boolean" as unsigned char, not int, per Windows custom. */
81 : #if defined(__WIN32__) && !defined(__MINGW32__)
82 : # ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
83 : typedef unsigned char boolean;
84 : # endif
85 : # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
86 : #endif
87 :
88 : #include "jpeglib.h"
89 : #include "jerror.h"
90 :
91 : /*
92 : * Do we want to do special processing suitable for when JSAMPLE is a
93 : * 16bit value?
94 : */
95 :
96 : #if defined(JPEG_LIB_MK1)
97 : # define JPEG_LIB_MK1_OR_12BIT 1
98 : #elif BITS_IN_JSAMPLE == 12
99 : # define JPEG_LIB_MK1_OR_12BIT 1
100 : #endif
101 :
102 : /*
103 : * We are using width_in_blocks which is supposed to be private to
104 : * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
105 : * renamed this member to width_in_data_units. Since the header has
106 : * also renamed a define, use that unique define name in order to
107 : * detect the problem header and adjust to suit.
108 : */
109 : #if defined(D_MAX_DATA_UNITS_IN_MCU)
110 : #define width_in_blocks width_in_data_units
111 : #endif
112 :
113 : /*
114 : * On some machines it may be worthwhile to use _setjmp or sigsetjmp
115 : * in place of plain setjmp. These macros will make it easier.
116 : */
117 : #define SETJMP(jbuf) setjmp(jbuf)
118 : #define LONGJMP(jbuf,code) longjmp(jbuf,code)
119 : #define JMP_BUF jmp_buf
120 :
121 : typedef struct jpeg_destination_mgr jpeg_destination_mgr;
122 : typedef struct jpeg_source_mgr jpeg_source_mgr;
123 : typedef struct jpeg_error_mgr jpeg_error_mgr;
124 :
125 : /*
126 : * State block for each open TIFF file using
127 : * libjpeg to do JPEG compression/decompression.
128 : *
129 : * libjpeg's visible state is either a jpeg_compress_struct
130 : * or jpeg_decompress_struct depending on which way we
131 : * are going. comm can be used to refer to the fields
132 : * which are common to both.
133 : *
134 : * NB: cinfo is required to be the first member of JPEGState,
135 : * so we can safely cast JPEGState* -> jpeg_xxx_struct*
136 : * and vice versa!
137 : */
138 : typedef struct {
139 : union {
140 : struct jpeg_compress_struct c;
141 : struct jpeg_decompress_struct d;
142 : struct jpeg_common_struct comm;
143 : } cinfo; /* NB: must be first */
144 : int cinfo_initialized;
145 :
146 : jpeg_error_mgr err; /* libjpeg error manager */
147 : JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
148 : /*
149 : * The following two members could be a union, but
150 : * they're small enough that it's not worth the effort.
151 : */
152 : jpeg_destination_mgr dest; /* data dest for compression */
153 : jpeg_source_mgr src; /* data source for decompression */
154 : /* private state */
155 : TIFF* tif; /* back link needed by some code */
156 : uint16 photometric; /* copy of PhotometricInterpretation */
157 : uint16 h_sampling; /* luminance sampling factors */
158 : uint16 v_sampling;
159 : tmsize_t bytesperline; /* decompressed bytes per scanline */
160 : /* pointers to intermediate buffers when processing downsampled data */
161 : JSAMPARRAY ds_buffer[MAX_COMPONENTS];
162 : int scancount; /* number of "scanlines" accumulated */
163 : int samplesperclump;
164 :
165 : TIFFVGetMethod vgetparent; /* super-class method */
166 : TIFFVSetMethod vsetparent; /* super-class method */
167 : TIFFPrintMethod printdir; /* super-class method */
168 : TIFFStripMethod defsparent; /* super-class method */
169 : TIFFTileMethod deftparent; /* super-class method */
170 : /* pseudo-tag fields */
171 : void* jpegtables; /* JPEGTables tag value, or NULL */
172 : uint32 jpegtables_length; /* number of bytes in same */
173 : int jpegquality; /* Compression quality level */
174 : int jpegcolormode; /* Auto RGB<=>YCbCr convert? */
175 : int jpegtablesmode; /* What to put in JPEGTables */
176 :
177 : int ycbcrsampling_fetched;
178 : } JPEGState;
179 :
180 : #define JState(tif) ((JPEGState*)(tif)->tif_data)
181 :
182 : static int JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
183 : static int JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
184 : static int JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
185 : static int JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
186 : static int JPEGInitializeLibJPEG(TIFF * tif, int decode );
187 : static int DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
188 :
189 : #define FIELD_JPEGTABLES (FIELD_CODEC+0)
190 :
191 : static const TIFFField jpegFields[] = {
192 : { TIFFTAG_JPEGTABLES, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_C32_UINT8, FIELD_JPEGTABLES, FALSE, TRUE, "JPEGTables", NULL },
193 : { TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "", NULL },
194 : { TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL },
195 : { TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL }
196 : };
197 :
198 : /*
199 : * libjpeg interface layer.
200 : *
201 : * We use setjmp/longjmp to return control to libtiff
202 : * when a fatal error is encountered within the JPEG
203 : * library. We also direct libjpeg error and warning
204 : * messages through the appropriate libtiff handlers.
205 : */
206 :
207 : /*
208 : * Error handling routines (these replace corresponding
209 : * IJG routines from jerror.c). These are used for both
210 : * compression and decompression.
211 : */
212 : static void
213 0 : TIFFjpeg_error_exit(j_common_ptr cinfo)
214 : {
215 0 : JPEGState *sp = (JPEGState *) cinfo; /* NB: cinfo assumed first */
216 : char buffer[JMSG_LENGTH_MAX];
217 :
218 0 : (*cinfo->err->format_message) (cinfo, buffer);
219 0 : TIFFErrorExt(sp->tif->tif_clientdata, "JPEGLib", "%s", buffer); /* display the error message */
220 0 : jpeg_abort(cinfo); /* clean up libjpeg state */
221 0 : LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
222 : }
223 :
224 : /*
225 : * This routine is invoked only for warning messages,
226 : * since error_exit does its own thing and trace_level
227 : * is never set > 0.
228 : */
229 : static void
230 0 : TIFFjpeg_output_message(j_common_ptr cinfo)
231 : {
232 : char buffer[JMSG_LENGTH_MAX];
233 :
234 0 : (*cinfo->err->format_message) (cinfo, buffer);
235 0 : TIFFWarningExt(((JPEGState *) cinfo)->tif->tif_clientdata, "JPEGLib", "%s", buffer);
236 0 : }
237 :
238 : /*
239 : * Interface routines. This layer of routines exists
240 : * primarily to limit side-effects from using setjmp.
241 : * Also, normal/error returns are converted into return
242 : * values per libtiff practice.
243 : */
244 : #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
245 : #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
246 :
247 : static int
248 3 : TIFFjpeg_create_compress(JPEGState* sp)
249 : {
250 : /* initialize JPEG error handling */
251 3 : sp->cinfo.c.err = jpeg_std_error(&sp->err);
252 3 : sp->err.error_exit = TIFFjpeg_error_exit;
253 3 : sp->err.output_message = TIFFjpeg_output_message;
254 :
255 3 : return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
256 : }
257 :
258 : static int
259 7 : TIFFjpeg_create_decompress(JPEGState* sp)
260 : {
261 : /* initialize JPEG error handling */
262 7 : sp->cinfo.d.err = jpeg_std_error(&sp->err);
263 7 : sp->err.error_exit = TIFFjpeg_error_exit;
264 7 : sp->err.output_message = TIFFjpeg_output_message;
265 :
266 7 : return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
267 : }
268 :
269 : static int
270 3 : TIFFjpeg_set_defaults(JPEGState* sp)
271 : {
272 3 : return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
273 : }
274 :
275 : static int
276 3 : TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
277 : {
278 3 : return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
279 : }
280 :
281 : static int
282 6 : TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
283 : {
284 6 : return CALLVJPEG(sp,
285 : jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
286 : }
287 :
288 : static int
289 3 : TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
290 : {
291 3 : return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
292 : }
293 :
294 : static int
295 3 : TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
296 : {
297 3 : return CALLVJPEG(sp,
298 : jpeg_start_compress(&sp->cinfo.c, write_all_tables));
299 : }
300 :
301 : static int
302 320 : TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
303 : {
304 320 : return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
305 : scanlines, (JDIMENSION) num_lines));
306 : }
307 :
308 : static int
309 0 : TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
310 : {
311 0 : return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
312 : data, (JDIMENSION) num_lines));
313 : }
314 :
315 : static int
316 3 : TIFFjpeg_finish_compress(JPEGState* sp)
317 : {
318 3 : return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
319 : }
320 :
321 : static int
322 3 : TIFFjpeg_write_tables(JPEGState* sp)
323 : {
324 3 : return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
325 : }
326 :
327 : static int
328 14 : TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
329 : {
330 14 : return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
331 : }
332 :
333 : static int
334 7 : TIFFjpeg_start_decompress(JPEGState* sp)
335 : {
336 7 : return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
337 : }
338 :
339 : static int
340 576 : TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
341 : {
342 576 : return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
343 : scanlines, (JDIMENSION) max_lines));
344 : }
345 :
346 : static int
347 0 : TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
348 : {
349 0 : return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
350 : data, (JDIMENSION) max_lines));
351 : }
352 :
353 : static int
354 7 : TIFFjpeg_finish_decompress(JPEGState* sp)
355 : {
356 7 : return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
357 : }
358 :
359 : static int
360 7 : TIFFjpeg_abort(JPEGState* sp)
361 : {
362 7 : return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
363 : }
364 :
365 : static int
366 10 : TIFFjpeg_destroy(JPEGState* sp)
367 : {
368 10 : return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
369 : }
370 :
371 : static JSAMPARRAY
372 0 : TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
373 : JDIMENSION samplesperrow, JDIMENSION numrows)
374 : {
375 0 : return CALLJPEG(sp, (JSAMPARRAY) NULL,
376 : (*sp->cinfo.comm.mem->alloc_sarray)
377 : (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
378 : }
379 :
380 : /*
381 : * JPEG library destination data manager.
382 : * These routines direct compressed data from libjpeg into the
383 : * libtiff output buffer.
384 : */
385 :
386 : static void
387 3 : std_init_destination(j_compress_ptr cinfo)
388 : {
389 3 : JPEGState* sp = (JPEGState*) cinfo;
390 3 : TIFF* tif = sp->tif;
391 :
392 3 : sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
393 3 : sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
394 3 : }
395 :
396 : static boolean
397 0 : std_empty_output_buffer(j_compress_ptr cinfo)
398 : {
399 0 : JPEGState* sp = (JPEGState*) cinfo;
400 0 : TIFF* tif = sp->tif;
401 :
402 : /* the entire buffer has been filled */
403 0 : tif->tif_rawcc = tif->tif_rawdatasize;
404 :
405 : #ifdef IPPJ_HUFF
406 : /*
407 : * The Intel IPP performance library does not necessarily fill up
408 : * the whole output buffer on each pass, so only dump out the parts
409 : * that have been filled.
410 : * http://trac.osgeo.org/gdal/wiki/JpegIPP
411 : */
412 : if ( sp->dest.free_in_buffer >= 0 ) {
413 : tif->tif_rawcc = tif->tif_rawdatasize - sp->dest.free_in_buffer;
414 : }
415 : #endif
416 :
417 0 : TIFFFlushData1(tif);
418 0 : sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
419 0 : sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
420 :
421 0 : return (TRUE);
422 : }
423 :
424 : static void
425 3 : std_term_destination(j_compress_ptr cinfo)
426 : {
427 3 : JPEGState* sp = (JPEGState*) cinfo;
428 3 : TIFF* tif = sp->tif;
429 :
430 3 : tif->tif_rawcp = (uint8*) sp->dest.next_output_byte;
431 3 : tif->tif_rawcc =
432 3 : tif->tif_rawdatasize - (tmsize_t) sp->dest.free_in_buffer;
433 : /* NB: libtiff does the final buffer flush */
434 3 : }
435 :
436 : static void
437 3 : TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
438 : {
439 : (void) tif;
440 3 : sp->cinfo.c.dest = &sp->dest;
441 3 : sp->dest.init_destination = std_init_destination;
442 3 : sp->dest.empty_output_buffer = std_empty_output_buffer;
443 3 : sp->dest.term_destination = std_term_destination;
444 3 : }
445 :
446 : /*
447 : * Alternate destination manager for outputting to JPEGTables field.
448 : */
449 :
450 : static void
451 3 : tables_init_destination(j_compress_ptr cinfo)
452 : {
453 3 : JPEGState* sp = (JPEGState*) cinfo;
454 :
455 : /* while building, jpegtables_length is allocated buffer size */
456 3 : sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
457 3 : sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
458 3 : }
459 :
460 : static boolean
461 0 : tables_empty_output_buffer(j_compress_ptr cinfo)
462 : {
463 0 : JPEGState* sp = (JPEGState*) cinfo;
464 : void* newbuf;
465 :
466 : /* the entire buffer has been filled; enlarge it by 1000 bytes */
467 0 : newbuf = _TIFFrealloc((void*) sp->jpegtables,
468 0 : (tmsize_t) (sp->jpegtables_length + 1000));
469 0 : if (newbuf == NULL)
470 0 : ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
471 0 : sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
472 0 : sp->dest.free_in_buffer = (size_t) 1000;
473 0 : sp->jpegtables = newbuf;
474 0 : sp->jpegtables_length += 1000;
475 0 : return (TRUE);
476 : }
477 :
478 : static void
479 3 : tables_term_destination(j_compress_ptr cinfo)
480 : {
481 3 : JPEGState* sp = (JPEGState*) cinfo;
482 :
483 : /* set tables length to number of bytes actually emitted */
484 3 : sp->jpegtables_length -= (uint32) sp->dest.free_in_buffer;
485 3 : }
486 :
487 : static int
488 3 : TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
489 : {
490 : (void) tif;
491 : /*
492 : * Allocate a working buffer for building tables.
493 : * Initial size is 1000 bytes, which is usually adequate.
494 : */
495 3 : if (sp->jpegtables)
496 0 : _TIFFfree(sp->jpegtables);
497 3 : sp->jpegtables_length = 1000;
498 3 : sp->jpegtables = (void*) _TIFFmalloc((tmsize_t) sp->jpegtables_length);
499 3 : if (sp->jpegtables == NULL) {
500 0 : sp->jpegtables_length = 0;
501 0 : TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
502 0 : return (0);
503 : }
504 3 : sp->cinfo.c.dest = &sp->dest;
505 3 : sp->dest.init_destination = tables_init_destination;
506 3 : sp->dest.empty_output_buffer = tables_empty_output_buffer;
507 3 : sp->dest.term_destination = tables_term_destination;
508 3 : return (1);
509 : }
510 :
511 : /*
512 : * JPEG library source data manager.
513 : * These routines supply compressed data to libjpeg.
514 : */
515 :
516 : static void
517 7 : std_init_source(j_decompress_ptr cinfo)
518 : {
519 7 : JPEGState* sp = (JPEGState*) cinfo;
520 7 : TIFF* tif = sp->tif;
521 :
522 7 : sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
523 7 : sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
524 7 : }
525 :
526 : static boolean
527 0 : std_fill_input_buffer(j_decompress_ptr cinfo)
528 : {
529 0 : JPEGState* sp = (JPEGState* ) cinfo;
530 : static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
531 :
532 : #ifdef IPPJ_HUFF
533 : /*
534 : * The Intel IPP performance library does not necessarily read the whole
535 : * input buffer in one pass, so it is possible to get here with data
536 : * yet to read.
537 : *
538 : * We just return without doing anything, until the entire buffer has
539 : * been read.
540 : * http://trac.osgeo.org/gdal/wiki/JpegIPP
541 : */
542 : if( sp->src.bytes_in_buffer > 0 ) {
543 : return (TRUE);
544 : }
545 : #endif
546 :
547 : /*
548 : * Normally the whole strip/tile is read and so we don't need to do
549 : * a fill. In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
550 : * all the data, but the rawdata is refreshed between scanlines and
551 : * we push this into the io machinery in JPEGDecode().
552 : * http://trac.osgeo.org/gdal/ticket/3894
553 : */
554 :
555 0 : WARNMS(cinfo, JWRN_JPEG_EOF);
556 : /* insert a fake EOI marker */
557 0 : sp->src.next_input_byte = dummy_EOI;
558 0 : sp->src.bytes_in_buffer = 2;
559 0 : return (TRUE);
560 : }
561 :
562 : static void
563 0 : std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
564 : {
565 0 : JPEGState* sp = (JPEGState*) cinfo;
566 :
567 0 : if (num_bytes > 0) {
568 0 : if ((size_t)num_bytes > sp->src.bytes_in_buffer) {
569 : /* oops, buffer overrun */
570 0 : (void) std_fill_input_buffer(cinfo);
571 : } else {
572 0 : sp->src.next_input_byte += (size_t) num_bytes;
573 0 : sp->src.bytes_in_buffer -= (size_t) num_bytes;
574 : }
575 : }
576 0 : }
577 :
578 : static void
579 7 : std_term_source(j_decompress_ptr cinfo)
580 : {
581 : /* No work necessary here */
582 : (void) cinfo;
583 7 : }
584 :
585 : static void
586 14 : TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
587 : {
588 : (void) tif;
589 14 : sp->cinfo.d.src = &sp->src;
590 14 : sp->src.init_source = std_init_source;
591 14 : sp->src.fill_input_buffer = std_fill_input_buffer;
592 14 : sp->src.skip_input_data = std_skip_input_data;
593 14 : sp->src.resync_to_restart = jpeg_resync_to_restart;
594 14 : sp->src.term_source = std_term_source;
595 14 : sp->src.bytes_in_buffer = 0; /* for safety */
596 14 : sp->src.next_input_byte = NULL;
597 14 : }
598 :
599 : /*
600 : * Alternate source manager for reading from JPEGTables.
601 : * We can share all the code except for the init routine.
602 : */
603 :
604 : static void
605 7 : tables_init_source(j_decompress_ptr cinfo)
606 : {
607 7 : JPEGState* sp = (JPEGState*) cinfo;
608 :
609 7 : sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
610 7 : sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
611 7 : }
612 :
613 : static void
614 7 : TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
615 : {
616 7 : TIFFjpeg_data_src(sp, tif);
617 7 : sp->src.init_source = tables_init_source;
618 7 : }
619 :
620 : /*
621 : * Allocate downsampled-data buffers needed for downsampled I/O.
622 : * We use values computed in jpeg_start_compress or jpeg_start_decompress.
623 : * We use libjpeg's allocator so that buffers will be released automatically
624 : * when done with strip/tile.
625 : * This is also a handy place to compute samplesperclump, bytesperline.
626 : */
627 : static int
628 0 : alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
629 : int num_components)
630 : {
631 0 : JPEGState* sp = JState(tif);
632 : int ci;
633 : jpeg_component_info* compptr;
634 : JSAMPARRAY buf;
635 0 : int samples_per_clump = 0;
636 :
637 0 : for (ci = 0, compptr = comp_info; ci < num_components;
638 0 : ci++, compptr++) {
639 0 : samples_per_clump += compptr->h_samp_factor *
640 : compptr->v_samp_factor;
641 0 : buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
642 : compptr->width_in_blocks * DCTSIZE,
643 0 : (JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
644 0 : if (buf == NULL)
645 0 : return (0);
646 0 : sp->ds_buffer[ci] = buf;
647 : }
648 0 : sp->samplesperclump = samples_per_clump;
649 0 : return (1);
650 : }
651 :
652 :
653 : /*
654 : * JPEG Decoding.
655 : */
656 :
657 : #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
658 :
659 : #define JPEG_MARKER_SOF0 0xC0
660 : #define JPEG_MARKER_SOF1 0xC1
661 : #define JPEG_MARKER_SOF3 0xC3
662 : #define JPEG_MARKER_DHT 0xC4
663 : #define JPEG_MARKER_SOI 0xD8
664 : #define JPEG_MARKER_SOS 0xDA
665 : #define JPEG_MARKER_DQT 0xDB
666 : #define JPEG_MARKER_DRI 0xDD
667 : #define JPEG_MARKER_APP0 0xE0
668 : #define JPEG_MARKER_COM 0xFE
669 : struct JPEGFixupTagsSubsamplingData
670 : {
671 : TIFF* tif;
672 : void* buffer;
673 : uint32 buffersize;
674 : uint8* buffercurrentbyte;
675 : uint32 bufferbytesleft;
676 : uint64 fileoffset;
677 : uint64 filebytesleft;
678 : uint8 filepositioned;
679 : };
680 : static void JPEGFixupTagsSubsampling(TIFF* tif);
681 : static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data);
682 : static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result);
683 : static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result);
684 : static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength);
685 :
686 : #endif
687 :
688 : static int
689 0 : JPEGFixupTags(TIFF* tif)
690 : {
691 : #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
692 0 : if ((tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR)&&
693 0 : (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&&
694 0 : (tif->tif_dir.td_samplesperpixel==3))
695 0 : JPEGFixupTagsSubsampling(tif);
696 : #endif
697 :
698 0 : return(1);
699 : }
700 :
701 : #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
702 :
703 : static void
704 0 : JPEGFixupTagsSubsampling(TIFF* tif)
705 : {
706 : /*
707 : * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
708 : * the TIFF tags, but still use non-default (2,2) values within the jpeg
709 : * data stream itself. In order for TIFF applications to work properly
710 : * - for instance to get the strip buffer size right - it is imperative
711 : * that the subsampling be available before we start reading the image
712 : * data normally. This function will attempt to analyze the first strip in
713 : * order to get the sampling values from the jpeg data stream.
714 : *
715 : * Note that JPEGPreDeocode() will produce a fairly loud warning when the
716 : * discovered sampling does not match the default sampling (2,2) or whatever
717 : * was actually in the tiff tags.
718 : *
719 : * See the bug in bugzilla for details:
720 : *
721 : * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
722 : *
723 : * Frank Warmerdam, July 2002
724 : * Joris Van Damme, May 2007
725 : */
726 : static const char module[] = "JPEGFixupTagsSubsampling";
727 : struct JPEGFixupTagsSubsamplingData m;
728 :
729 0 : _TIFFFillStriles( tif );
730 :
731 0 : if( tif->tif_dir.td_stripbytecount == NULL
732 0 : || tif->tif_dir.td_stripbytecount[0] == 0 )
733 : {
734 : /* Do not even try to check if the first strip/tile does not
735 : yet exist, as occurs when GDAL has created a new NULL file
736 : for instance. */
737 0 : return;
738 : }
739 :
740 0 : m.tif=tif;
741 0 : m.buffersize=2048;
742 0 : m.buffer=_TIFFmalloc(m.buffersize);
743 0 : if (m.buffer==NULL)
744 : {
745 0 : TIFFWarningExt(tif->tif_clientdata,module,
746 : "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
747 0 : return;
748 : }
749 0 : m.buffercurrentbyte=NULL;
750 0 : m.bufferbytesleft=0;
751 0 : m.fileoffset=tif->tif_dir.td_stripoffset[0];
752 0 : m.filepositioned=0;
753 0 : m.filebytesleft=tif->tif_dir.td_stripbytecount[0];
754 0 : if (!JPEGFixupTagsSubsamplingSec(&m))
755 0 : TIFFWarningExt(tif->tif_clientdata,module,
756 : "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
757 0 : _TIFFfree(m.buffer);
758 : }
759 :
760 : static int
761 0 : JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
762 : {
763 : static const char module[] = "JPEGFixupTagsSubsamplingSec";
764 : uint8 m;
765 : while (1)
766 : {
767 : while (1)
768 : {
769 0 : if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
770 0 : return(0);
771 0 : if (m==255)
772 0 : break;
773 0 : }
774 : while (1)
775 : {
776 0 : if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
777 0 : return(0);
778 0 : if (m!=255)
779 : break;
780 0 : }
781 0 : switch (m)
782 : {
783 : case JPEG_MARKER_SOI:
784 : /* this type of marker has no data and should be skipped */
785 0 : break;
786 : case JPEG_MARKER_COM:
787 : case JPEG_MARKER_APP0:
788 : case JPEG_MARKER_APP0+1:
789 : case JPEG_MARKER_APP0+2:
790 : case JPEG_MARKER_APP0+3:
791 : case JPEG_MARKER_APP0+4:
792 : case JPEG_MARKER_APP0+5:
793 : case JPEG_MARKER_APP0+6:
794 : case JPEG_MARKER_APP0+7:
795 : case JPEG_MARKER_APP0+8:
796 : case JPEG_MARKER_APP0+9:
797 : case JPEG_MARKER_APP0+10:
798 : case JPEG_MARKER_APP0+11:
799 : case JPEG_MARKER_APP0+12:
800 : case JPEG_MARKER_APP0+13:
801 : case JPEG_MARKER_APP0+14:
802 : case JPEG_MARKER_APP0+15:
803 : case JPEG_MARKER_DQT:
804 : case JPEG_MARKER_SOS:
805 : case JPEG_MARKER_DHT:
806 : case JPEG_MARKER_DRI:
807 : /* this type of marker has data, but it has no use to us and should be skipped */
808 : {
809 : uint16 n;
810 0 : if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
811 0 : return(0);
812 0 : if (n<2)
813 0 : return(0);
814 0 : n-=2;
815 0 : if (n>0)
816 0 : JPEGFixupTagsSubsamplingSkip(data,n);
817 : }
818 0 : break;
819 : case JPEG_MARKER_SOF0:
820 : case JPEG_MARKER_SOF1:
821 : /* this marker contains the subsampling factors we're scanning for */
822 : {
823 : uint16 n;
824 : uint16 o;
825 : uint8 p;
826 : uint8 ph,pv;
827 0 : if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
828 0 : return(0);
829 0 : if (n!=8+data->tif->tif_dir.td_samplesperpixel*3)
830 0 : return(0);
831 0 : JPEGFixupTagsSubsamplingSkip(data,7);
832 0 : if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
833 0 : return(0);
834 0 : ph=(p>>4);
835 0 : pv=(p&15);
836 0 : JPEGFixupTagsSubsamplingSkip(data,1);
837 0 : for (o=1; o<data->tif->tif_dir.td_samplesperpixel; o++)
838 : {
839 0 : JPEGFixupTagsSubsamplingSkip(data,1);
840 0 : if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
841 0 : return(0);
842 0 : if (p!=0x11)
843 : {
844 0 : TIFFWarningExt(data->tif->tif_clientdata,module,
845 : "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
846 0 : return(1);
847 : }
848 0 : JPEGFixupTagsSubsamplingSkip(data,1);
849 : }
850 0 : if (((ph!=1)&&(ph!=2)&&(ph!=4))||((pv!=1)&&(pv!=2)&&(pv!=4)))
851 : {
852 0 : TIFFWarningExt(data->tif->tif_clientdata,module,
853 : "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
854 0 : return(1);
855 : }
856 0 : if ((ph!=data->tif->tif_dir.td_ycbcrsubsampling[0])||(pv!=data->tif->tif_dir.td_ycbcrsubsampling[1]))
857 : {
858 0 : TIFFWarningExt(data->tif->tif_clientdata,module,
859 : "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
860 0 : (int)data->tif->tif_dir.td_ycbcrsubsampling[0],
861 0 : (int)data->tif->tif_dir.td_ycbcrsubsampling[1],
862 : (int)ph,(int)pv);
863 0 : data->tif->tif_dir.td_ycbcrsubsampling[0]=ph;
864 0 : data->tif->tif_dir.td_ycbcrsubsampling[1]=pv;
865 : }
866 : }
867 0 : return(1);
868 : default:
869 0 : return(0);
870 : }
871 0 : }
872 : }
873 :
874 : static int
875 0 : JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result)
876 : {
877 0 : if (data->bufferbytesleft==0)
878 : {
879 : uint32 m;
880 0 : if (data->filebytesleft==0)
881 0 : return(0);
882 0 : if (!data->filepositioned)
883 : {
884 0 : TIFFSeekFile(data->tif,data->fileoffset,SEEK_SET);
885 0 : data->filepositioned=1;
886 : }
887 0 : m=data->buffersize;
888 0 : if ((uint64)m>data->filebytesleft)
889 0 : m=(uint32)data->filebytesleft;
890 0 : assert(m<0x80000000UL);
891 0 : if (TIFFReadFile(data->tif,data->buffer,(tmsize_t)m)!=(tmsize_t)m)
892 0 : return(0);
893 0 : data->buffercurrentbyte=data->buffer;
894 0 : data->bufferbytesleft=m;
895 0 : data->fileoffset+=m;
896 0 : data->filebytesleft-=m;
897 : }
898 0 : *result=*data->buffercurrentbyte;
899 0 : data->buffercurrentbyte++;
900 0 : data->bufferbytesleft--;
901 0 : return(1);
902 : }
903 :
904 : static int
905 0 : JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result)
906 : {
907 : uint8 ma;
908 : uint8 mb;
909 0 : if (!JPEGFixupTagsSubsamplingReadByte(data,&ma))
910 0 : return(0);
911 0 : if (!JPEGFixupTagsSubsamplingReadByte(data,&mb))
912 0 : return(0);
913 0 : *result=(ma<<8)|mb;
914 0 : return(1);
915 : }
916 :
917 : static void
918 0 : JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength)
919 : {
920 0 : if ((uint32)skiplength<=data->bufferbytesleft)
921 : {
922 0 : data->buffercurrentbyte+=skiplength;
923 0 : data->bufferbytesleft-=skiplength;
924 : }
925 : else
926 : {
927 : uint16 m;
928 0 : m=skiplength-data->bufferbytesleft;
929 0 : if (m<=data->filebytesleft)
930 : {
931 0 : data->bufferbytesleft=0;
932 0 : data->fileoffset+=m;
933 0 : data->filebytesleft-=m;
934 0 : data->filepositioned=0;
935 : }
936 : else
937 : {
938 0 : data->bufferbytesleft=0;
939 0 : data->filebytesleft=0;
940 : }
941 : }
942 0 : }
943 :
944 : #endif
945 :
946 :
947 : static int
948 7 : JPEGSetupDecode(TIFF* tif)
949 : {
950 7 : JPEGState* sp = JState(tif);
951 7 : TIFFDirectory *td = &tif->tif_dir;
952 :
953 : #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
954 : if( tif->tif_dir.td_bitspersample == 12 )
955 : return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 0 );
956 : #endif
957 :
958 7 : JPEGInitializeLibJPEG( tif, TRUE );
959 :
960 7 : assert(sp != NULL);
961 7 : assert(sp->cinfo.comm.is_decompressor);
962 :
963 : /* Read JPEGTables if it is present */
964 7 : if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
965 7 : TIFFjpeg_tables_src(sp, tif);
966 7 : if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
967 0 : TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
968 0 : return (0);
969 : }
970 : }
971 :
972 : /* Grab parameters that are same for all strips/tiles */
973 7 : sp->photometric = td->td_photometric;
974 7 : switch (sp->photometric) {
975 : case PHOTOMETRIC_YCBCR:
976 5 : sp->h_sampling = td->td_ycbcrsubsampling[0];
977 5 : sp->v_sampling = td->td_ycbcrsubsampling[1];
978 5 : break;
979 : default:
980 : /* TIFF 6.0 forbids subsampling of all other color spaces */
981 2 : sp->h_sampling = 1;
982 2 : sp->v_sampling = 1;
983 : break;
984 : }
985 :
986 : /* Set up for reading normal data */
987 7 : TIFFjpeg_data_src(sp, tif);
988 7 : tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
989 7 : return (1);
990 : }
991 :
992 : /*
993 : * Set up for decoding a strip or tile.
994 : */
995 : static int
996 7 : JPEGPreDecode(TIFF* tif, uint16 s)
997 : {
998 7 : JPEGState *sp = JState(tif);
999 7 : TIFFDirectory *td = &tif->tif_dir;
1000 : static const char module[] = "JPEGPreDecode";
1001 : uint32 segment_width, segment_height;
1002 : int downsampled_output;
1003 : int ci;
1004 :
1005 7 : assert(sp != NULL);
1006 :
1007 7 : if (sp->cinfo.comm.is_decompressor == 0)
1008 : {
1009 0 : tif->tif_setupdecode( tif );
1010 : }
1011 :
1012 7 : assert(sp->cinfo.comm.is_decompressor);
1013 : /*
1014 : * Reset decoder state from any previous strip/tile,
1015 : * in case application didn't read the whole strip.
1016 : */
1017 7 : if (!TIFFjpeg_abort(sp))
1018 0 : return (0);
1019 : /*
1020 : * Read the header for this strip/tile.
1021 : */
1022 :
1023 7 : if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
1024 0 : return (0);
1025 :
1026 7 : tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
1027 7 : tif->tif_rawcc = sp->src.bytes_in_buffer;
1028 :
1029 : /*
1030 : * Check image parameters and set decompression parameters.
1031 : */
1032 7 : segment_width = td->td_imagewidth;
1033 7 : segment_height = td->td_imagelength - tif->tif_row;
1034 7 : if (isTiled(tif)) {
1035 2 : segment_width = td->td_tilewidth;
1036 2 : segment_height = td->td_tilelength;
1037 2 : sp->bytesperline = TIFFTileRowSize(tif);
1038 : } else {
1039 5 : if (segment_height > td->td_rowsperstrip)
1040 0 : segment_height = td->td_rowsperstrip;
1041 5 : sp->bytesperline = TIFFScanlineSize(tif);
1042 : }
1043 7 : if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1044 : /*
1045 : * For PC 2, scale down the expected strip/tile size
1046 : * to match a downsampled component
1047 : */
1048 0 : segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
1049 0 : segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1050 : }
1051 14 : if (sp->cinfo.d.image_width < segment_width ||
1052 7 : sp->cinfo.d.image_height < segment_height) {
1053 0 : TIFFWarningExt(tif->tif_clientdata, module,
1054 : "Improper JPEG strip/tile size, "
1055 : "expected %dx%d, got %dx%d",
1056 : segment_width, segment_height,
1057 : sp->cinfo.d.image_width,
1058 : sp->cinfo.d.image_height);
1059 : }
1060 14 : if (sp->cinfo.d.image_width > segment_width ||
1061 7 : sp->cinfo.d.image_height > segment_height) {
1062 : /*
1063 : * This case could be dangerous, if the strip or tile size has
1064 : * been reported as less than the amount of data jpeg will
1065 : * return, some potential security issues arise. Catch this
1066 : * case and error out.
1067 : */
1068 0 : TIFFErrorExt(tif->tif_clientdata, module,
1069 : "JPEG strip/tile size exceeds expected dimensions,"
1070 : " expected %dx%d, got %dx%d",
1071 : segment_width, segment_height,
1072 : sp->cinfo.d.image_width, sp->cinfo.d.image_height);
1073 0 : return (0);
1074 : }
1075 21 : if (sp->cinfo.d.num_components !=
1076 7 : (td->td_planarconfig == PLANARCONFIG_CONTIG ?
1077 7 : td->td_samplesperpixel : 1)) {
1078 0 : TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG component count");
1079 0 : return (0);
1080 : }
1081 : #ifdef JPEG_LIB_MK1
1082 : if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
1083 : TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
1084 : return (0);
1085 : }
1086 : sp->cinfo.d.data_precision = td->td_bitspersample;
1087 : sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
1088 : #else
1089 7 : if (sp->cinfo.d.data_precision != td->td_bitspersample) {
1090 0 : TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
1091 0 : return (0);
1092 : }
1093 : #endif
1094 7 : if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1095 : /* Component 0 should have expected sampling factors */
1096 14 : if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
1097 7 : sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
1098 0 : TIFFErrorExt(tif->tif_clientdata, module,
1099 : "Improper JPEG sampling factors %d,%d\n"
1100 : "Apparently should be %d,%d.",
1101 0 : sp->cinfo.d.comp_info[0].h_samp_factor,
1102 0 : sp->cinfo.d.comp_info[0].v_samp_factor,
1103 0 : sp->h_sampling, sp->v_sampling);
1104 0 : return (0);
1105 : }
1106 : /* Rest should have sampling factors 1,1 */
1107 17 : for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
1108 20 : if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
1109 10 : sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
1110 0 : TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
1111 0 : return (0);
1112 : }
1113 : }
1114 : } else {
1115 : /* PC 2's single component should have sampling factors 1,1 */
1116 0 : if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
1117 0 : sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
1118 0 : TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
1119 0 : return (0);
1120 : }
1121 : }
1122 7 : downsampled_output = FALSE;
1123 24 : if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1124 7 : sp->photometric == PHOTOMETRIC_YCBCR &&
1125 5 : sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1126 : /* Convert YCbCr to RGB */
1127 5 : sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
1128 5 : sp->cinfo.d.out_color_space = JCS_RGB;
1129 : } else {
1130 : /* Suppress colorspace handling */
1131 2 : sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
1132 2 : sp->cinfo.d.out_color_space = JCS_UNKNOWN;
1133 6 : if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1134 4 : (sp->h_sampling != 1 || sp->v_sampling != 1))
1135 0 : downsampled_output = TRUE;
1136 : /* XXX what about up-sampling? */
1137 : }
1138 7 : if (downsampled_output) {
1139 : /* Need to use raw-data interface to libjpeg */
1140 0 : sp->cinfo.d.raw_data_out = TRUE;
1141 : #if JPEG_LIB_VERSION >= 70
1142 : sp->cinfo.d.do_fancy_upsampling = FALSE;
1143 : #endif /* JPEG_LIB_VERSION >= 70 */
1144 0 : tif->tif_decoderow = DecodeRowError;
1145 0 : tif->tif_decodestrip = JPEGDecodeRaw;
1146 0 : tif->tif_decodetile = JPEGDecodeRaw;
1147 : } else {
1148 : /* Use normal interface to libjpeg */
1149 7 : sp->cinfo.d.raw_data_out = FALSE;
1150 7 : tif->tif_decoderow = JPEGDecode;
1151 7 : tif->tif_decodestrip = JPEGDecode;
1152 7 : tif->tif_decodetile = JPEGDecode;
1153 : }
1154 : /* Start JPEG decompressor */
1155 7 : if (!TIFFjpeg_start_decompress(sp))
1156 0 : return (0);
1157 : /* Allocate downsampled-data buffers if needed */
1158 7 : if (downsampled_output) {
1159 0 : if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
1160 : sp->cinfo.d.num_components))
1161 0 : return (0);
1162 0 : sp->scancount = DCTSIZE; /* mark buffer empty */
1163 : }
1164 7 : return (1);
1165 : }
1166 :
1167 : /*
1168 : * Decode a chunk of pixels.
1169 : * "Standard" case: returned data is not downsampled.
1170 : */
1171 : /*ARGSUSED*/ static int
1172 7 : JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1173 : {
1174 7 : JPEGState *sp = JState(tif);
1175 : tmsize_t nrows;
1176 : (void) s;
1177 :
1178 : /*
1179 : ** Update available information, buffer may have been refilled
1180 : ** between decode requests
1181 : */
1182 7 : sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
1183 7 : sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
1184 :
1185 7 : if( sp->bytesperline == 0 )
1186 0 : return 0;
1187 :
1188 7 : nrows = cc / sp->bytesperline;
1189 7 : if (cc % sp->bytesperline)
1190 0 : TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
1191 :
1192 7 : if( nrows > (tmsize_t) sp->cinfo.d.image_height )
1193 0 : nrows = sp->cinfo.d.image_height;
1194 :
1195 : /* data is expected to be read in multiples of a scanline */
1196 7 : if (nrows)
1197 : {
1198 7 : JSAMPROW line_work_buf = NULL;
1199 :
1200 : /*
1201 : * For 6B, only use temporary buffer for 12 bit imagery.
1202 : * For Mk1 always use it.
1203 : */
1204 : #if !defined(JPEG_LIB_MK1)
1205 7 : if( sp->cinfo.d.data_precision == 12 )
1206 : #endif
1207 : {
1208 7 : line_work_buf = (JSAMPROW)
1209 7 : _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
1210 : * sp->cinfo.d.num_components );
1211 : }
1212 :
1213 : do {
1214 576 : if( line_work_buf != NULL )
1215 : {
1216 : /*
1217 : * In the MK1 case, we aways read into a 16bit buffer, and then
1218 : * pack down to 12bit or 8bit. In 6B case we only read into 16
1219 : * bit buffer for 12bit data, which we need to repack.
1220 : */
1221 576 : if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
1222 0 : return (0);
1223 :
1224 576 : if( sp->cinfo.d.data_precision == 12 )
1225 : {
1226 576 : int value_pairs = (sp->cinfo.d.output_width
1227 576 : * sp->cinfo.d.num_components) / 2;
1228 : int iPair;
1229 :
1230 47680 : for( iPair = 0; iPair < value_pairs; iPair++ )
1231 : {
1232 : unsigned char *out_ptr =
1233 47104 : ((unsigned char *) buf) + iPair * 3;
1234 47104 : JSAMPLE *in_ptr = line_work_buf + iPair * 2;
1235 :
1236 47104 : out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
1237 94208 : out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
1238 47104 : | ((in_ptr[1] & 0xf00) >> 8);
1239 47104 : out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
1240 : }
1241 : }
1242 0 : else if( sp->cinfo.d.data_precision == 8 )
1243 : {
1244 0 : int value_count = (sp->cinfo.d.output_width
1245 0 : * sp->cinfo.d.num_components);
1246 : int iValue;
1247 :
1248 0 : for( iValue = 0; iValue < value_count; iValue++ )
1249 : {
1250 0 : ((unsigned char *) buf)[iValue] =
1251 0 : line_work_buf[iValue] & 0xff;
1252 : }
1253 : }
1254 : }
1255 : else
1256 : {
1257 : /*
1258 : * In the libjpeg6b 8bit case. We read directly into the
1259 : * TIFF buffer.
1260 : */
1261 0 : JSAMPROW bufptr = (JSAMPROW)buf;
1262 :
1263 0 : if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
1264 0 : return (0);
1265 : }
1266 :
1267 576 : ++tif->tif_row;
1268 576 : buf += sp->bytesperline;
1269 576 : cc -= sp->bytesperline;
1270 576 : } while (--nrows > 0);
1271 :
1272 7 : if( line_work_buf != NULL )
1273 7 : _TIFFfree( line_work_buf );
1274 : }
1275 :
1276 : /* Update information on consumed data */
1277 7 : tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
1278 7 : tif->tif_rawcc = sp->src.bytes_in_buffer;
1279 :
1280 : /* Close down the decompressor if we've finished the strip or tile. */
1281 14 : return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1282 14 : || TIFFjpeg_finish_decompress(sp);
1283 : }
1284 :
1285 : /*ARGSUSED*/ static int
1286 0 : DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1287 :
1288 : {
1289 : (void) buf;
1290 : (void) cc;
1291 : (void) s;
1292 :
1293 0 : TIFFErrorExt(tif->tif_clientdata, "TIFFReadScanline",
1294 : "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
1295 0 : return 0;
1296 : }
1297 :
1298 : /*
1299 : * Decode a chunk of pixels.
1300 : * Returned data is downsampled per sampling factors.
1301 : */
1302 : /*ARGSUSED*/ static int
1303 0 : JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1304 : {
1305 0 : JPEGState *sp = JState(tif);
1306 : tmsize_t nrows;
1307 : (void) s;
1308 :
1309 : /* data is expected to be read in multiples of a scanline */
1310 0 : if ( (nrows = sp->cinfo.d.image_height) ) {
1311 :
1312 : /* Cb,Cr both have sampling factors 1, so this is correct */
1313 0 : JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
1314 0 : int samples_per_clump = sp->samplesperclump;
1315 :
1316 : #if defined(JPEG_LIB_MK1_OR_12BIT)
1317 0 : unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
1318 : sp->cinfo.d.output_width *
1319 0 : sp->cinfo.d.num_components);
1320 0 : if(tmpbuf==NULL) {
1321 0 : TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1322 : "Out of memory");
1323 0 : return 0;
1324 : }
1325 : #endif
1326 :
1327 : do {
1328 : jpeg_component_info *compptr;
1329 : int ci, clumpoffset;
1330 :
1331 0 : if( cc < sp->bytesperline ) {
1332 0 : TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1333 : "application buffer not large enough for all data.");
1334 0 : return 0;
1335 : }
1336 :
1337 : /* Reload downsampled-data buffer if needed */
1338 0 : if (sp->scancount >= DCTSIZE) {
1339 0 : int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
1340 0 : if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n) != n)
1341 0 : return (0);
1342 0 : sp->scancount = 0;
1343 : }
1344 : /*
1345 : * Fastest way to unseparate data is to make one pass
1346 : * over the scanline for each row of each component.
1347 : */
1348 0 : clumpoffset = 0; /* first sample in clump */
1349 0 : for (ci = 0, compptr = sp->cinfo.d.comp_info;
1350 0 : ci < sp->cinfo.d.num_components;
1351 0 : ci++, compptr++) {
1352 0 : int hsamp = compptr->h_samp_factor;
1353 0 : int vsamp = compptr->v_samp_factor;
1354 : int ypos;
1355 :
1356 0 : for (ypos = 0; ypos < vsamp; ypos++) {
1357 0 : JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1358 : JDIMENSION nclump;
1359 : #if defined(JPEG_LIB_MK1_OR_12BIT)
1360 0 : JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
1361 : #else
1362 : JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
1363 : if (cc < (tmsize_t) (clumpoffset + samples_per_clump*(clumps_per_line-1) + hsamp)) {
1364 : TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1365 : "application buffer not large enough for all data, possible subsampling issue");
1366 : return 0;
1367 : }
1368 : #endif
1369 :
1370 0 : if (hsamp == 1) {
1371 : /* fast path for at least Cb and Cr */
1372 0 : for (nclump = clumps_per_line; nclump-- > 0; ) {
1373 0 : outptr[0] = *inptr++;
1374 0 : outptr += samples_per_clump;
1375 : }
1376 : } else {
1377 : int xpos;
1378 :
1379 : /* general case */
1380 0 : for (nclump = clumps_per_line; nclump-- > 0; ) {
1381 0 : for (xpos = 0; xpos < hsamp; xpos++)
1382 0 : outptr[xpos] = *inptr++;
1383 0 : outptr += samples_per_clump;
1384 : }
1385 : }
1386 0 : clumpoffset += hsamp;
1387 : }
1388 : }
1389 :
1390 : #if defined(JPEG_LIB_MK1_OR_12BIT)
1391 : {
1392 0 : if (sp->cinfo.d.data_precision == 8)
1393 : {
1394 0 : int i=0;
1395 0 : int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
1396 0 : for (i=0; i<len; i++)
1397 : {
1398 0 : ((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
1399 : }
1400 : }
1401 : else
1402 : { /* 12-bit */
1403 0 : int value_pairs = (sp->cinfo.d.output_width
1404 0 : * sp->cinfo.d.num_components) / 2;
1405 : int iPair;
1406 0 : for( iPair = 0; iPair < value_pairs; iPair++ )
1407 : {
1408 0 : unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
1409 0 : JSAMPLE *in_ptr = (JSAMPLE *) (tmpbuf + iPair * 2);
1410 0 : out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
1411 0 : out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
1412 0 : | ((in_ptr[1] & 0xf00) >> 8);
1413 0 : out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
1414 : }
1415 : }
1416 : }
1417 : #endif
1418 :
1419 0 : sp->scancount ++;
1420 0 : tif->tif_row += sp->v_sampling;
1421 :
1422 0 : buf += sp->bytesperline;
1423 0 : cc -= sp->bytesperline;
1424 :
1425 0 : nrows -= sp->v_sampling;
1426 0 : } while (nrows > 0);
1427 :
1428 : #if defined(JPEG_LIB_MK1_OR_12BIT)
1429 0 : _TIFFfree(tmpbuf);
1430 : #endif
1431 :
1432 : }
1433 :
1434 : /* Close down the decompressor if done. */
1435 0 : return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1436 0 : || TIFFjpeg_finish_decompress(sp);
1437 : }
1438 :
1439 :
1440 : /*
1441 : * JPEG Encoding.
1442 : */
1443 :
1444 : static void
1445 4 : unsuppress_quant_table (JPEGState* sp, int tblno)
1446 : {
1447 : JQUANT_TBL* qtbl;
1448 :
1449 4 : if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1450 4 : qtbl->sent_table = FALSE;
1451 4 : }
1452 :
1453 : static void
1454 4 : unsuppress_huff_table (JPEGState* sp, int tblno)
1455 : {
1456 : JHUFF_TBL* htbl;
1457 :
1458 4 : if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1459 4 : htbl->sent_table = FALSE;
1460 4 : if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1461 4 : htbl->sent_table = FALSE;
1462 4 : }
1463 :
1464 : static int
1465 3 : prepare_JPEGTables(TIFF* tif)
1466 : {
1467 3 : JPEGState* sp = JState(tif);
1468 :
1469 : /* Initialize quant tables for current quality setting */
1470 3 : if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1471 0 : return (0);
1472 : /* Mark only the tables we want for output */
1473 : /* NB: chrominance tables are currently used only with YCbCr */
1474 3 : if (!TIFFjpeg_suppress_tables(sp, TRUE))
1475 0 : return (0);
1476 3 : if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
1477 3 : unsuppress_quant_table(sp, 0);
1478 3 : if (sp->photometric == PHOTOMETRIC_YCBCR)
1479 1 : unsuppress_quant_table(sp, 1);
1480 : }
1481 3 : if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
1482 3 : unsuppress_huff_table(sp, 0);
1483 3 : if (sp->photometric == PHOTOMETRIC_YCBCR)
1484 1 : unsuppress_huff_table(sp, 1);
1485 : }
1486 : /* Direct libjpeg output into jpegtables */
1487 3 : if (!TIFFjpeg_tables_dest(sp, tif))
1488 0 : return (0);
1489 : /* Emit tables-only datastream */
1490 3 : if (!TIFFjpeg_write_tables(sp))
1491 0 : return (0);
1492 :
1493 3 : return (1);
1494 : }
1495 :
1496 : static int
1497 3 : JPEGSetupEncode(TIFF* tif)
1498 : {
1499 3 : JPEGState* sp = JState(tif);
1500 3 : TIFFDirectory *td = &tif->tif_dir;
1501 : static const char module[] = "JPEGSetupEncode";
1502 :
1503 : #if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
1504 : if( tif->tif_dir.td_bitspersample == 12 )
1505 : return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 1 );
1506 : #endif
1507 :
1508 3 : JPEGInitializeLibJPEG( tif, FALSE );
1509 :
1510 3 : assert(sp != NULL);
1511 3 : assert(!sp->cinfo.comm.is_decompressor);
1512 :
1513 : /*
1514 : * Initialize all JPEG parameters to default values.
1515 : * Note that jpeg_set_defaults needs legal values for
1516 : * in_color_space and input_components.
1517 : */
1518 3 : sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1519 3 : sp->cinfo.c.input_components = 1;
1520 3 : if (!TIFFjpeg_set_defaults(sp))
1521 0 : return (0);
1522 : /* Set per-file parameters */
1523 3 : sp->photometric = td->td_photometric;
1524 3 : switch (sp->photometric) {
1525 : case PHOTOMETRIC_YCBCR:
1526 1 : sp->h_sampling = td->td_ycbcrsubsampling[0];
1527 1 : sp->v_sampling = td->td_ycbcrsubsampling[1];
1528 : /*
1529 : * A ReferenceBlackWhite field *must* be present since the
1530 : * default value is inappropriate for YCbCr. Fill in the
1531 : * proper value if application didn't set it.
1532 : */
1533 : {
1534 : float *ref;
1535 1 : if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1536 : &ref)) {
1537 : float refbw[6];
1538 1 : long top = 1L << td->td_bitspersample;
1539 1 : refbw[0] = 0;
1540 1 : refbw[1] = (float)(top-1L);
1541 1 : refbw[2] = (float)(top>>1);
1542 1 : refbw[3] = refbw[1];
1543 1 : refbw[4] = refbw[2];
1544 1 : refbw[5] = refbw[1];
1545 1 : TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1546 : refbw);
1547 : }
1548 : }
1549 1 : break;
1550 : case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */
1551 : case PHOTOMETRIC_MASK:
1552 0 : TIFFErrorExt(tif->tif_clientdata, module,
1553 : "PhotometricInterpretation %d not allowed for JPEG",
1554 : (int) sp->photometric);
1555 0 : return (0);
1556 : default:
1557 : /* TIFF 6.0 forbids subsampling of all other color spaces */
1558 2 : sp->h_sampling = 1;
1559 2 : sp->v_sampling = 1;
1560 : break;
1561 : }
1562 :
1563 : /* Verify miscellaneous parameters */
1564 :
1565 : /*
1566 : * This would need work if libtiff ever supports different
1567 : * depths for different components, or if libjpeg ever supports
1568 : * run-time selection of depth. Neither is imminent.
1569 : */
1570 : #ifdef JPEG_LIB_MK1
1571 : /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1572 : if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
1573 : #else
1574 3 : if (td->td_bitspersample != BITS_IN_JSAMPLE )
1575 : #endif
1576 : {
1577 0 : TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
1578 : (int) td->td_bitspersample);
1579 0 : return (0);
1580 : }
1581 3 : sp->cinfo.c.data_precision = td->td_bitspersample;
1582 : #ifdef JPEG_LIB_MK1
1583 : sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
1584 : #endif
1585 3 : if (isTiled(tif)) {
1586 2 : if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
1587 0 : TIFFErrorExt(tif->tif_clientdata, module,
1588 : "JPEG tile height must be multiple of %d",
1589 : sp->v_sampling * DCTSIZE);
1590 0 : return (0);
1591 : }
1592 2 : if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
1593 0 : TIFFErrorExt(tif->tif_clientdata, module,
1594 : "JPEG tile width must be multiple of %d",
1595 : sp->h_sampling * DCTSIZE);
1596 0 : return (0);
1597 : }
1598 : } else {
1599 1 : if (td->td_rowsperstrip < td->td_imagelength &&
1600 0 : (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
1601 0 : TIFFErrorExt(tif->tif_clientdata, module,
1602 : "RowsPerStrip must be multiple of %d for JPEG",
1603 : sp->v_sampling * DCTSIZE);
1604 0 : return (0);
1605 : }
1606 : }
1607 :
1608 : /* Create a JPEGTables field if appropriate */
1609 3 : if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
1610 3 : if( sp->jpegtables == NULL
1611 3 : || memcmp(sp->jpegtables,"\0\0\0\0\0\0\0\0\0",8) == 0 )
1612 : {
1613 3 : if (!prepare_JPEGTables(tif))
1614 0 : return (0);
1615 : /* Mark the field present */
1616 : /* Can't use TIFFSetField since BEENWRITING is already set! */
1617 3 : tif->tif_flags |= TIFF_DIRTYDIRECT;
1618 3 : TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1619 : }
1620 : } else {
1621 : /* We do not support application-supplied JPEGTables, */
1622 : /* so mark the field not present */
1623 0 : TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
1624 : }
1625 :
1626 : /* Direct libjpeg output to libtiff's output buffer */
1627 3 : TIFFjpeg_data_dest(sp, tif);
1628 :
1629 3 : return (1);
1630 : }
1631 :
1632 : /*
1633 : * Set encoding state at the start of a strip or tile.
1634 : */
1635 : static int
1636 3 : JPEGPreEncode(TIFF* tif, uint16 s)
1637 : {
1638 3 : JPEGState *sp = JState(tif);
1639 3 : TIFFDirectory *td = &tif->tif_dir;
1640 : static const char module[] = "JPEGPreEncode";
1641 : uint32 segment_width, segment_height;
1642 : int downsampled_input;
1643 :
1644 3 : assert(sp != NULL);
1645 :
1646 3 : if (sp->cinfo.comm.is_decompressor == 1)
1647 : {
1648 0 : tif->tif_setupencode( tif );
1649 : }
1650 :
1651 3 : assert(!sp->cinfo.comm.is_decompressor);
1652 : /*
1653 : * Set encoding parameters for this strip/tile.
1654 : */
1655 3 : if (isTiled(tif)) {
1656 2 : segment_width = td->td_tilewidth;
1657 2 : segment_height = td->td_tilelength;
1658 2 : sp->bytesperline = TIFFTileRowSize(tif);
1659 : } else {
1660 1 : segment_width = td->td_imagewidth;
1661 1 : segment_height = td->td_imagelength - tif->tif_row;
1662 1 : if (segment_height > td->td_rowsperstrip)
1663 0 : segment_height = td->td_rowsperstrip;
1664 1 : sp->bytesperline = TIFFScanlineSize(tif);
1665 : }
1666 3 : if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1667 : /* for PC 2, scale down the strip/tile size
1668 : * to match a downsampled component
1669 : */
1670 0 : segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
1671 0 : segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1672 : }
1673 3 : if (segment_width > 65535 || segment_height > 65535) {
1674 0 : TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
1675 0 : return (0);
1676 : }
1677 3 : sp->cinfo.c.image_width = segment_width;
1678 3 : sp->cinfo.c.image_height = segment_height;
1679 3 : downsampled_input = FALSE;
1680 3 : if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1681 3 : sp->cinfo.c.input_components = td->td_samplesperpixel;
1682 3 : if (sp->photometric == PHOTOMETRIC_YCBCR) {
1683 1 : if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1684 1 : sp->cinfo.c.in_color_space = JCS_RGB;
1685 : } else {
1686 0 : sp->cinfo.c.in_color_space = JCS_YCbCr;
1687 0 : if (sp->h_sampling != 1 || sp->v_sampling != 1)
1688 0 : downsampled_input = TRUE;
1689 : }
1690 1 : if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
1691 0 : return (0);
1692 : /*
1693 : * Set Y sampling factors;
1694 : * we assume jpeg_set_colorspace() set the rest to 1
1695 : */
1696 1 : sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
1697 1 : sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
1698 : } else {
1699 4 : if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
1700 2 : sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
1701 0 : else if (td->td_photometric == PHOTOMETRIC_RGB && td->td_samplesperpixel == 3)
1702 0 : sp->cinfo.c.in_color_space = JCS_RGB;
1703 0 : else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
1704 0 : sp->cinfo.c.in_color_space = JCS_CMYK;
1705 : else
1706 0 : sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1707 2 : if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
1708 0 : return (0);
1709 : /* jpeg_set_colorspace set all sampling factors to 1 */
1710 : }
1711 : } else {
1712 0 : sp->cinfo.c.input_components = 1;
1713 0 : sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1714 0 : if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1715 0 : return (0);
1716 0 : sp->cinfo.c.comp_info[0].component_id = s;
1717 : /* jpeg_set_colorspace() set sampling factors to 1 */
1718 0 : if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
1719 0 : sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
1720 0 : sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
1721 0 : sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
1722 : }
1723 : }
1724 : /* ensure libjpeg won't write any extraneous markers */
1725 3 : sp->cinfo.c.write_JFIF_header = FALSE;
1726 3 : sp->cinfo.c.write_Adobe_marker = FALSE;
1727 : /* set up table handling correctly */
1728 3 : if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1729 0 : return (0);
1730 3 : if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
1731 0 : unsuppress_quant_table(sp, 0);
1732 0 : unsuppress_quant_table(sp, 1);
1733 : }
1734 3 : if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
1735 3 : sp->cinfo.c.optimize_coding = FALSE;
1736 : else
1737 0 : sp->cinfo.c.optimize_coding = TRUE;
1738 3 : if (downsampled_input) {
1739 : /* Need to use raw-data interface to libjpeg */
1740 0 : sp->cinfo.c.raw_data_in = TRUE;
1741 0 : tif->tif_encoderow = JPEGEncodeRaw;
1742 0 : tif->tif_encodestrip = JPEGEncodeRaw;
1743 0 : tif->tif_encodetile = JPEGEncodeRaw;
1744 : } else {
1745 : /* Use normal interface to libjpeg */
1746 3 : sp->cinfo.c.raw_data_in = FALSE;
1747 3 : tif->tif_encoderow = JPEGEncode;
1748 3 : tif->tif_encodestrip = JPEGEncode;
1749 3 : tif->tif_encodetile = JPEGEncode;
1750 : }
1751 : /* Start JPEG compressor */
1752 3 : if (!TIFFjpeg_start_compress(sp, FALSE))
1753 0 : return (0);
1754 : /* Allocate downsampled-data buffers if needed */
1755 3 : if (downsampled_input) {
1756 0 : if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
1757 : sp->cinfo.c.num_components))
1758 0 : return (0);
1759 : }
1760 3 : sp->scancount = 0;
1761 :
1762 3 : return (1);
1763 : }
1764 :
1765 : /*
1766 : * Encode a chunk of pixels.
1767 : * "Standard" case: incoming data is not downsampled.
1768 : */
1769 : static int
1770 3 : JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1771 : {
1772 3 : JPEGState *sp = JState(tif);
1773 : tmsize_t nrows;
1774 : JSAMPROW bufptr[1];
1775 3 : short *line16 = NULL;
1776 3 : int line16_count = 0;
1777 :
1778 : (void) s;
1779 3 : assert(sp != NULL);
1780 : /* data is expected to be supplied in multiples of a scanline */
1781 3 : nrows = cc / sp->bytesperline;
1782 3 : if (cc % sp->bytesperline)
1783 0 : TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
1784 : "fractional scanline discarded");
1785 :
1786 : /* The last strip will be limited to image size */
1787 3 : if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
1788 0 : nrows = tif->tif_dir.td_imagelength - tif->tif_row;
1789 :
1790 3 : if( sp->cinfo.c.data_precision == 12 )
1791 : {
1792 3 : line16_count = (sp->bytesperline * 2) / 3;
1793 3 : line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
1794 : // FIXME: undiagnosed malloc failure
1795 : }
1796 :
1797 326 : while (nrows-- > 0) {
1798 :
1799 320 : if( sp->cinfo.c.data_precision == 12 )
1800 : {
1801 :
1802 320 : int value_pairs = line16_count / 2;
1803 : int iPair;
1804 :
1805 320 : bufptr[0] = (JSAMPROW) line16;
1806 :
1807 22848 : for( iPair = 0; iPair < value_pairs; iPair++ )
1808 : {
1809 : unsigned char *in_ptr =
1810 22528 : ((unsigned char *) buf) + iPair * 3;
1811 22528 : JSAMPLE *out_ptr = (JSAMPLE *) (line16 + iPair * 2);
1812 :
1813 22528 : out_ptr[0] = (in_ptr[0] << 4) | ((in_ptr[1] & 0xf0) >> 4);
1814 22528 : out_ptr[1] = ((in_ptr[1] & 0x0f) << 8) | in_ptr[2];
1815 : }
1816 : }
1817 : else
1818 : {
1819 0 : bufptr[0] = (JSAMPROW) buf;
1820 : }
1821 320 : if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
1822 0 : return (0);
1823 320 : if (nrows > 0)
1824 317 : tif->tif_row++;
1825 320 : buf += sp->bytesperline;
1826 : }
1827 :
1828 3 : if( sp->cinfo.c.data_precision == 12 )
1829 : {
1830 3 : _TIFFfree( line16 );
1831 : }
1832 :
1833 3 : return (1);
1834 : }
1835 :
1836 : /*
1837 : * Encode a chunk of pixels.
1838 : * Incoming data is expected to be downsampled per sampling factors.
1839 : */
1840 : static int
1841 0 : JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1842 : {
1843 0 : JPEGState *sp = JState(tif);
1844 : JSAMPLE* inptr;
1845 : JSAMPLE* outptr;
1846 : tmsize_t nrows;
1847 : JDIMENSION clumps_per_line, nclump;
1848 : int clumpoffset, ci, xpos, ypos;
1849 : jpeg_component_info* compptr;
1850 0 : int samples_per_clump = sp->samplesperclump;
1851 : tmsize_t bytesperclumpline;
1852 :
1853 : (void) s;
1854 0 : assert(sp != NULL);
1855 : /* data is expected to be supplied in multiples of a clumpline */
1856 : /* a clumpline is equivalent to v_sampling desubsampled scanlines */
1857 : /* TODO: the following calculation of bytesperclumpline, should substitute calculation of sp->bytesperline, except that it is per v_sampling lines */
1858 0 : bytesperclumpline = (((sp->cinfo.c.image_width+sp->h_sampling-1)/sp->h_sampling)
1859 0 : *(sp->h_sampling*sp->v_sampling+2)*sp->cinfo.c.data_precision+7)
1860 : /8;
1861 :
1862 0 : nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
1863 0 : if (cc % bytesperclumpline)
1864 0 : TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
1865 :
1866 : /* Cb,Cr both have sampling factors 1, so this is correct */
1867 0 : clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
1868 :
1869 0 : while (nrows > 0) {
1870 : /*
1871 : * Fastest way to separate the data is to make one pass
1872 : * over the scanline for each row of each component.
1873 : */
1874 0 : clumpoffset = 0; /* first sample in clump */
1875 0 : for (ci = 0, compptr = sp->cinfo.c.comp_info;
1876 0 : ci < sp->cinfo.c.num_components;
1877 0 : ci++, compptr++) {
1878 0 : int hsamp = compptr->h_samp_factor;
1879 0 : int vsamp = compptr->v_samp_factor;
1880 0 : int padding = (int) (compptr->width_in_blocks * DCTSIZE -
1881 0 : clumps_per_line * hsamp);
1882 0 : for (ypos = 0; ypos < vsamp; ypos++) {
1883 0 : inptr = ((JSAMPLE*) buf) + clumpoffset;
1884 0 : outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1885 0 : if (hsamp == 1) {
1886 : /* fast path for at least Cb and Cr */
1887 0 : for (nclump = clumps_per_line; nclump-- > 0; ) {
1888 0 : *outptr++ = inptr[0];
1889 0 : inptr += samples_per_clump;
1890 : }
1891 : } else {
1892 : /* general case */
1893 0 : for (nclump = clumps_per_line; nclump-- > 0; ) {
1894 0 : for (xpos = 0; xpos < hsamp; xpos++)
1895 0 : *outptr++ = inptr[xpos];
1896 0 : inptr += samples_per_clump;
1897 : }
1898 : }
1899 : /* pad each scanline as needed */
1900 0 : for (xpos = 0; xpos < padding; xpos++) {
1901 0 : *outptr = outptr[-1];
1902 0 : outptr++;
1903 : }
1904 0 : clumpoffset += hsamp;
1905 : }
1906 : }
1907 0 : sp->scancount++;
1908 0 : if (sp->scancount >= DCTSIZE) {
1909 0 : int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1910 0 : if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1911 0 : return (0);
1912 0 : sp->scancount = 0;
1913 : }
1914 0 : tif->tif_row += sp->v_sampling;
1915 0 : buf += bytesperclumpline;
1916 0 : nrows -= sp->v_sampling;
1917 : }
1918 0 : return (1);
1919 : }
1920 :
1921 : /*
1922 : * Finish up at the end of a strip or tile.
1923 : */
1924 : static int
1925 3 : JPEGPostEncode(TIFF* tif)
1926 : {
1927 3 : JPEGState *sp = JState(tif);
1928 :
1929 3 : if (sp->scancount > 0) {
1930 : /*
1931 : * Need to emit a partial bufferload of downsampled data.
1932 : * Pad the data vertically.
1933 : */
1934 : int ci, ypos, n;
1935 : jpeg_component_info* compptr;
1936 :
1937 0 : for (ci = 0, compptr = sp->cinfo.c.comp_info;
1938 0 : ci < sp->cinfo.c.num_components;
1939 0 : ci++, compptr++) {
1940 0 : int vsamp = compptr->v_samp_factor;
1941 0 : tmsize_t row_width = compptr->width_in_blocks * DCTSIZE
1942 0 : * sizeof(JSAMPLE);
1943 0 : for (ypos = sp->scancount * vsamp;
1944 0 : ypos < DCTSIZE * vsamp; ypos++) {
1945 0 : _TIFFmemcpy((void*)sp->ds_buffer[ci][ypos],
1946 0 : (void*)sp->ds_buffer[ci][ypos-1],
1947 : row_width);
1948 :
1949 : }
1950 : }
1951 0 : n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1952 0 : if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1953 0 : return (0);
1954 : }
1955 :
1956 3 : return (TIFFjpeg_finish_compress(JState(tif)));
1957 : }
1958 :
1959 : static void
1960 10 : JPEGCleanup(TIFF* tif)
1961 : {
1962 10 : JPEGState *sp = JState(tif);
1963 :
1964 10 : assert(sp != 0);
1965 :
1966 10 : tif->tif_tagmethods.vgetfield = sp->vgetparent;
1967 10 : tif->tif_tagmethods.vsetfield = sp->vsetparent;
1968 10 : tif->tif_tagmethods.printdir = sp->printdir;
1969 :
1970 10 : if( sp != NULL ) {
1971 10 : if( sp->cinfo_initialized )
1972 10 : TIFFjpeg_destroy(sp); /* release libjpeg resources */
1973 10 : if (sp->jpegtables) /* tag value */
1974 10 : _TIFFfree(sp->jpegtables);
1975 : }
1976 10 : _TIFFfree(tif->tif_data); /* release local state */
1977 10 : tif->tif_data = NULL;
1978 :
1979 10 : _TIFFSetDefaultCompressionState(tif);
1980 10 : }
1981 :
1982 : static void
1983 0 : JPEGResetUpsampled( TIFF* tif )
1984 : {
1985 0 : JPEGState* sp = JState(tif);
1986 0 : TIFFDirectory* td = &tif->tif_dir;
1987 :
1988 : /*
1989 : * Mark whether returned data is up-sampled or not so TIFFStripSize
1990 : * and TIFFTileSize return values that reflect the true amount of
1991 : * data.
1992 : */
1993 0 : tif->tif_flags &= ~TIFF_UPSAMPLED;
1994 0 : if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1995 0 : if (td->td_photometric == PHOTOMETRIC_YCBCR &&
1996 0 : sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1997 0 : tif->tif_flags |= TIFF_UPSAMPLED;
1998 : } else {
1999 : #ifdef notdef
2000 : if (td->td_ycbcrsubsampling[0] != 1 ||
2001 : td->td_ycbcrsubsampling[1] != 1)
2002 : ; /* XXX what about up-sampling? */
2003 : #endif
2004 : }
2005 : }
2006 :
2007 : /*
2008 : * Must recalculate cached tile size in case sampling state changed.
2009 : * Should we really be doing this now if image size isn't set?
2010 : */
2011 0 : if( tif->tif_tilesize > 0 )
2012 0 : tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);
2013 0 : if( tif->tif_scanlinesize > 0 )
2014 0 : tif->tif_scanlinesize = TIFFScanlineSize(tif);
2015 0 : }
2016 :
2017 : static int
2018 1 : JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
2019 : {
2020 1 : JPEGState* sp = JState(tif);
2021 : const TIFFField* fip;
2022 : uint32 v32;
2023 :
2024 1 : assert(sp != NULL);
2025 :
2026 1 : switch (tag) {
2027 : case TIFFTAG_JPEGTABLES:
2028 0 : v32 = (uint32) va_arg(ap, uint32);
2029 0 : if (v32 == 0) {
2030 : /* XXX */
2031 0 : return (0);
2032 : }
2033 0 : _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
2034 : (long) v32);
2035 0 : sp->jpegtables_length = v32;
2036 0 : TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2037 : break;
2038 : case TIFFTAG_JPEGQUALITY:
2039 0 : sp->jpegquality = (int) va_arg(ap, int);
2040 0 : return (1); /* pseudo tag */
2041 : case TIFFTAG_JPEGCOLORMODE:
2042 0 : sp->jpegcolormode = (int) va_arg(ap, int);
2043 0 : JPEGResetUpsampled( tif );
2044 0 : return (1); /* pseudo tag */
2045 : case TIFFTAG_PHOTOMETRIC:
2046 : {
2047 0 : int ret_value = (*sp->vsetparent)(tif, tag, ap);
2048 0 : JPEGResetUpsampled( tif );
2049 0 : return ret_value;
2050 : }
2051 : case TIFFTAG_JPEGTABLESMODE:
2052 0 : sp->jpegtablesmode = (int) va_arg(ap, int);
2053 0 : return (1); /* pseudo tag */
2054 : case TIFFTAG_YCBCRSUBSAMPLING:
2055 : /* mark the fact that we have a real ycbcrsubsampling! */
2056 0 : sp->ycbcrsampling_fetched = 1;
2057 : /* should we be recomputing upsampling info here? */
2058 0 : return (*sp->vsetparent)(tif, tag, ap);
2059 : default:
2060 1 : return (*sp->vsetparent)(tif, tag, ap);
2061 : }
2062 :
2063 0 : if ((fip = TIFFFieldWithTag(tif, tag))) {
2064 0 : TIFFSetFieldBit(tif, fip->field_bit);
2065 : } else {
2066 0 : return (0);
2067 : }
2068 :
2069 0 : tif->tif_flags |= TIFF_DIRTYDIRECT;
2070 0 : return (1);
2071 : }
2072 :
2073 : static int
2074 8 : JPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
2075 : {
2076 8 : JPEGState* sp = JState(tif);
2077 :
2078 8 : assert(sp != NULL);
2079 :
2080 8 : switch (tag) {
2081 : case TIFFTAG_JPEGTABLES:
2082 6 : *va_arg(ap, uint32*) = sp->jpegtables_length;
2083 6 : *va_arg(ap, void**) = sp->jpegtables;
2084 6 : break;
2085 : case TIFFTAG_JPEGQUALITY:
2086 0 : *va_arg(ap, int*) = sp->jpegquality;
2087 0 : break;
2088 : case TIFFTAG_JPEGCOLORMODE:
2089 0 : *va_arg(ap, int*) = sp->jpegcolormode;
2090 0 : break;
2091 : case TIFFTAG_JPEGTABLESMODE:
2092 0 : *va_arg(ap, int*) = sp->jpegtablesmode;
2093 0 : break;
2094 : default:
2095 2 : return (*sp->vgetparent)(tif, tag, ap);
2096 : }
2097 6 : return (1);
2098 : }
2099 :
2100 : static void
2101 0 : JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
2102 : {
2103 0 : JPEGState* sp = JState(tif);
2104 :
2105 0 : assert(sp != NULL);
2106 : (void) flags;
2107 :
2108 0 : if( sp != NULL ) {
2109 0 : if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
2110 0 : fprintf(fd, " JPEG Tables: (%lu bytes)\n",
2111 : (unsigned long) sp->jpegtables_length);
2112 0 : if (sp->printdir)
2113 0 : (*sp->printdir)(tif, fd, flags);
2114 : }
2115 0 : }
2116 :
2117 : static uint32
2118 0 : JPEGDefaultStripSize(TIFF* tif, uint32 s)
2119 : {
2120 0 : JPEGState* sp = JState(tif);
2121 0 : TIFFDirectory *td = &tif->tif_dir;
2122 :
2123 0 : s = (*sp->defsparent)(tif, s);
2124 0 : if (s < td->td_imagelength)
2125 0 : s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
2126 0 : return (s);
2127 : }
2128 :
2129 : static void
2130 0 : JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
2131 : {
2132 0 : JPEGState* sp = JState(tif);
2133 0 : TIFFDirectory *td = &tif->tif_dir;
2134 :
2135 0 : (*sp->deftparent)(tif, tw, th);
2136 0 : *tw = TIFFroundup_32(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
2137 0 : *th = TIFFroundup_32(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
2138 0 : }
2139 :
2140 : /*
2141 : * The JPEG library initialized used to be done in TIFFInitJPEG(), but
2142 : * now that we allow a TIFF file to be opened in update mode it is necessary
2143 : * to have some way of deciding whether compression or decompression is
2144 : * desired other than looking at tif->tif_mode. We accomplish this by
2145 : * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
2146 : * If so, we assume decompression is desired.
2147 : *
2148 : * This is tricky, because TIFFInitJPEG() is called while the directory is
2149 : * being read, and generally speaking the BYTECOUNTS tag won't have been read
2150 : * at that point. So we try to defer jpeg library initialization till we
2151 : * do have that tag ... basically any access that might require the compressor
2152 : * or decompressor that occurs after the reading of the directory.
2153 : *
2154 : * In an ideal world compressors or decompressors would be setup
2155 : * at the point where a single tile or strip was accessed (for read or write)
2156 : * so that stuff like update of missing tiles, or replacement of tiles could
2157 : * be done. However, we aren't trying to crack that nut just yet ...
2158 : *
2159 : * NFW, Feb 3rd, 2003.
2160 : */
2161 :
2162 10 : static int JPEGInitializeLibJPEG( TIFF * tif, int decompress )
2163 : {
2164 10 : JPEGState* sp = JState(tif);
2165 :
2166 10 : if(sp->cinfo_initialized)
2167 : {
2168 0 : if( !decompress && sp->cinfo.comm.is_decompressor )
2169 0 : TIFFjpeg_destroy( sp );
2170 0 : else if( decompress && !sp->cinfo.comm.is_decompressor )
2171 0 : TIFFjpeg_destroy( sp );
2172 : else
2173 0 : return 1;
2174 :
2175 0 : sp->cinfo_initialized = 0;
2176 : }
2177 :
2178 : /*
2179 : * Initialize libjpeg.
2180 : */
2181 10 : if ( decompress ) {
2182 7 : if (!TIFFjpeg_create_decompress(sp))
2183 0 : return (0);
2184 : } else {
2185 3 : if (!TIFFjpeg_create_compress(sp))
2186 0 : return (0);
2187 : }
2188 :
2189 10 : sp->cinfo_initialized = TRUE;
2190 :
2191 10 : return 1;
2192 : }
2193 :
2194 : int
2195 0 : TIFFInitJPEG(TIFF* tif, int scheme)
2196 : {
2197 : JPEGState* sp;
2198 :
2199 0 : assert(scheme == COMPRESSION_JPEG);
2200 :
2201 : /*
2202 : * Merge codec-specific tag information.
2203 : */
2204 0 : if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields))) {
2205 0 : TIFFErrorExt(tif->tif_clientdata,
2206 : "TIFFInitJPEG",
2207 : "Merging JPEG codec-specific tags failed");
2208 0 : return 0;
2209 : }
2210 :
2211 : /*
2212 : * Allocate state block so tag methods have storage to record values.
2213 : */
2214 0 : tif->tif_data = (uint8*) _TIFFmalloc(sizeof (JPEGState));
2215 :
2216 0 : if (tif->tif_data == NULL) {
2217 0 : TIFFErrorExt(tif->tif_clientdata,
2218 : "TIFFInitJPEG", "No space for JPEG state block");
2219 0 : return 0;
2220 : }
2221 0 : _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
2222 :
2223 0 : sp = JState(tif);
2224 0 : sp->tif = tif; /* back link */
2225 :
2226 : /*
2227 : * Override parent get/set field methods.
2228 : */
2229 0 : sp->vgetparent = tif->tif_tagmethods.vgetfield;
2230 0 : tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
2231 0 : sp->vsetparent = tif->tif_tagmethods.vsetfield;
2232 0 : tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
2233 0 : sp->printdir = tif->tif_tagmethods.printdir;
2234 0 : tif->tif_tagmethods.printdir = JPEGPrintDir; /* hook for codec tags */
2235 :
2236 : /* Default values for codec-specific fields */
2237 0 : sp->jpegtables = NULL;
2238 0 : sp->jpegtables_length = 0;
2239 0 : sp->jpegquality = 75; /* Default IJG quality */
2240 0 : sp->jpegcolormode = JPEGCOLORMODE_RAW;
2241 0 : sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
2242 0 : sp->ycbcrsampling_fetched = 0;
2243 :
2244 : /*
2245 : * Install codec methods.
2246 : */
2247 0 : tif->tif_fixuptags = JPEGFixupTags;
2248 0 : tif->tif_setupdecode = JPEGSetupDecode;
2249 0 : tif->tif_predecode = JPEGPreDecode;
2250 0 : tif->tif_decoderow = JPEGDecode;
2251 0 : tif->tif_decodestrip = JPEGDecode;
2252 0 : tif->tif_decodetile = JPEGDecode;
2253 0 : tif->tif_setupencode = JPEGSetupEncode;
2254 0 : tif->tif_preencode = JPEGPreEncode;
2255 0 : tif->tif_postencode = JPEGPostEncode;
2256 0 : tif->tif_encoderow = JPEGEncode;
2257 0 : tif->tif_encodestrip = JPEGEncode;
2258 0 : tif->tif_encodetile = JPEGEncode;
2259 0 : tif->tif_cleanup = JPEGCleanup;
2260 0 : sp->defsparent = tif->tif_defstripsize;
2261 0 : tif->tif_defstripsize = JPEGDefaultStripSize;
2262 0 : sp->deftparent = tif->tif_deftilesize;
2263 0 : tif->tif_deftilesize = JPEGDefaultTileSize;
2264 0 : tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
2265 :
2266 0 : sp->cinfo_initialized = FALSE;
2267 :
2268 : /*
2269 : ** Create a JPEGTables field if no directory has yet been created.
2270 : ** We do this just to ensure that sufficient space is reserved for
2271 : ** the JPEGTables field. It will be properly created the right
2272 : ** size later.
2273 : */
2274 0 : if( tif->tif_diroff == 0 )
2275 : {
2276 : #define SIZE_OF_JPEGTABLES 2000
2277 : /*
2278 : The following line assumes incorrectly that all JPEG-in-TIFF files will have
2279 : a JPEGTABLES tag generated and causes null-filled JPEGTABLES tags to be written
2280 : when the JPEG data is placed with TIFFWriteRawStrip. The field bit should be
2281 : set, anyway, later when actual JPEGTABLES header is generated, so removing it
2282 : here hopefully is harmless.
2283 : TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2284 : */
2285 0 : sp->jpegtables_length = SIZE_OF_JPEGTABLES;
2286 0 : sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
2287 : // FIXME: NULL-deref after malloc failure
2288 0 : _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
2289 : #undef SIZE_OF_JPEGTABLES
2290 : }
2291 :
2292 0 : return 1;
2293 : }
2294 : #endif /* JPEG_SUPPORT */
2295 :
2296 : /* vim: set ts=8 sts=8 sw=8 noet: */
2297 :
2298 : /*
2299 : * Local Variables:
2300 : * mode: c
2301 : * c-basic-offset: 8
2302 : * fill-column: 78
2303 : * End:
2304 : */
|