bed9ddd206706b1d257a9cb35d5bfc2231f7d0ee
[reactos.git] / dll / 3rdparty / libtiff / tif_jpeg.c
1 /* $Id: tif_jpeg.c,v 1.127 2017-01-31 13:02:27 erouault 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 <precomp.h>
31
32 #ifdef JPEG_SUPPORT
33
34 /*
35 * TIFF Library
36 *
37 * JPEG Compression support per TIFF Technical Note #2
38 * (*not* per the original TIFF 6.0 spec).
39 *
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/.
43 *
44 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
45 */
46 #include <setjmp.h>
47
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 );
51
52 /* We undefine FAR to avoid conflict with JPEG definition */
53
54 #ifdef FAR
55 #undef FAR
56 #endif
57
58 /*
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.
63 */
64 #if defined(__BORLANDC__) || defined(__MINGW32__)
65 # define XMD_H 1
66 #endif
67
68 /*
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:
73
74 "JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
75 caller expects 464"
76
77 For such users we wil fix the problem here. See install.doc file from
78 the JPEG library distribution for details.
79 */
80
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;
85 # endif
86 # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
87 #endif
88
89 #include "jpeglib.h"
90 #include "jerror.h"
91
92 /*
93 * Do we want to do special processing suitable for when JSAMPLE is a
94 * 16bit value?
95 */
96
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
101 #endif
102
103 /*
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.
109 */
110 #if defined(D_MAX_DATA_UNITS_IN_MCU)
111 #define width_in_blocks width_in_data_units
112 #endif
113
114 /*
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.
117 */
118 #define SETJMP(jbuf) setjmp(jbuf)
119 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
120 #define JMP_BUF jmp_buf
121
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;
125
126 /*
127 * State block for each open TIFF file using
128 * libjpeg to do JPEG compression/decompression.
129 *
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.
134 *
135 * NB: cinfo is required to be the first member of JPEGState,
136 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
137 * and vice versa!
138 */
139 typedef struct {
140 union {
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;
146
147 jpeg_error_mgr err; /* libjpeg error manager */
148 JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
149 /*
150 * The following two members could be a union, but
151 * they're small enough that it's not worth the effort.
152 */
153 jpeg_destination_mgr dest; /* data dest for compression */
154 jpeg_source_mgr src; /* data source for decompression */
155 /* private state */
156 TIFF* tif; /* back link needed by some code */
157 uint16 photometric; /* copy of PhotometricInterpretation */
158 uint16 h_sampling; /* luminance sampling factors */
159 uint16 v_sampling;
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 */
164 int samplesperclump;
165
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 */
177
178 int ycbcrsampling_fetched;
179 } JPEGState;
180
181 #define JState(tif) ((JPEGState*)(tif)->tif_data)
182
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);
189
190 #define FIELD_JPEGTABLES (FIELD_CODEC+0)
191
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 }
197 };
198
199 /*
200 * libjpeg interface layer.
201 *
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.
206 */
207
208 /*
209 * Error handling routines (these replace corresponding
210 * IJG routines from jerror.c). These are used for both
211 * compression and decompression.
212 */
213 static void
214 TIFFjpeg_error_exit(j_common_ptr cinfo)
215 {
216 JPEGState *sp = (JPEGState *) cinfo; /* NB: cinfo assumed first */
217 char buffer[JMSG_LENGTH_MAX];
218
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 */
223 }
224
225 /*
226 * This routine is invoked only for warning messages,
227 * since error_exit does its own thing and trace_level
228 * is never set > 0.
229 */
230 static void
231 TIFFjpeg_output_message(j_common_ptr cinfo)
232 {
233 char buffer[JMSG_LENGTH_MAX];
234
235 (*cinfo->err->format_message) (cinfo, buffer);
236 TIFFWarningExt(((JPEGState *) cinfo)->tif->tif_clientdata, "JPEGLib", "%s", buffer);
237 }
238
239 /*
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.
244 */
245 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
246 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
247
248 static int
249 TIFFjpeg_create_compress(JPEGState* sp)
250 {
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;
255
256 /* set client_data to avoid UMR warning from tools like Purify */
257 sp->cinfo.c.client_data = NULL;
258
259 return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
260 }
261
262 static int
263 TIFFjpeg_create_decompress(JPEGState* sp)
264 {
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;
269
270 /* set client_data to avoid UMR warning from tools like Purify */
271 sp->cinfo.d.client_data = NULL;
272
273 return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
274 }
275
276 static int
277 TIFFjpeg_set_defaults(JPEGState* sp)
278 {
279 return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
280 }
281
282 static int
283 TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
284 {
285 return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
286 }
287
288 static int
289 TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
290 {
291 return CALLVJPEG(sp,
292 jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
293 }
294
295 static int
296 TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
297 {
298 return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
299 }
300
301 static int
302 TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
303 {
304 return CALLVJPEG(sp,
305 jpeg_start_compress(&sp->cinfo.c, write_all_tables));
306 }
307
308 static int
309 TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
310 {
311 return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
312 scanlines, (JDIMENSION) num_lines));
313 }
314
315 static int
316 TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
317 {
318 return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
319 data, (JDIMENSION) num_lines));
320 }
321
322 static int
323 TIFFjpeg_finish_compress(JPEGState* sp)
324 {
325 return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
326 }
327
328 static int
329 TIFFjpeg_write_tables(JPEGState* sp)
330 {
331 return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
332 }
333
334 static int
335 TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
336 {
337 return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
338 }
339
340 static int
341 TIFFjpeg_start_decompress(JPEGState* sp)
342 {
343 return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
344 }
345
346 static int
347 TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
348 {
349 return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
350 scanlines, (JDIMENSION) max_lines));
351 }
352
353 static int
354 TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
355 {
356 return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
357 data, (JDIMENSION) max_lines));
358 }
359
360 static int
361 TIFFjpeg_finish_decompress(JPEGState* sp)
362 {
363 return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
364 }
365
366 static int
367 TIFFjpeg_abort(JPEGState* sp)
368 {
369 return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
370 }
371
372 static int
373 TIFFjpeg_destroy(JPEGState* sp)
374 {
375 return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
376 }
377
378 static JSAMPARRAY
379 TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
380 JDIMENSION samplesperrow, JDIMENSION numrows)
381 {
382 return CALLJPEG(sp, (JSAMPARRAY) NULL,
383 (*sp->cinfo.comm.mem->alloc_sarray)
384 (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
385 }
386
387 /*
388 * JPEG library destination data manager.
389 * These routines direct compressed data from libjpeg into the
390 * libtiff output buffer.
391 */
392
393 static void
394 std_init_destination(j_compress_ptr cinfo)
395 {
396 JPEGState* sp = (JPEGState*) cinfo;
397 TIFF* tif = sp->tif;
398
399 sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
400 sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
401 }
402
403 static boolean
404 std_empty_output_buffer(j_compress_ptr cinfo)
405 {
406 JPEGState* sp = (JPEGState*) cinfo;
407 TIFF* tif = sp->tif;
408
409 /* the entire buffer has been filled */
410 tif->tif_rawcc = tif->tif_rawdatasize;
411
412 #ifdef IPPJ_HUFF
413 /*
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
418 */
419 if ( sp->dest.free_in_buffer >= 0 ) {
420 tif->tif_rawcc = tif->tif_rawdatasize - sp->dest.free_in_buffer;
421 }
422 #endif
423
424 TIFFFlushData1(tif);
425 sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
426 sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
427
428 return (TRUE);
429 }
430
431 static void
432 std_term_destination(j_compress_ptr cinfo)
433 {
434 JPEGState* sp = (JPEGState*) cinfo;
435 TIFF* tif = sp->tif;
436
437 tif->tif_rawcp = (uint8*) sp->dest.next_output_byte;
438 tif->tif_rawcc =
439 tif->tif_rawdatasize - (tmsize_t) sp->dest.free_in_buffer;
440 /* NB: libtiff does the final buffer flush */
441 }
442
443 static void
444 TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
445 {
446 (void) 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;
451 }
452
453 /*
454 * Alternate destination manager for outputting to JPEGTables field.
455 */
456
457 static void
458 tables_init_destination(j_compress_ptr cinfo)
459 {
460 JPEGState* sp = (JPEGState*) cinfo;
461
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;
465 }
466
467 static boolean
468 tables_empty_output_buffer(j_compress_ptr cinfo)
469 {
470 JPEGState* sp = (JPEGState*) cinfo;
471 void* newbuf;
472
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));
476 if (newbuf == NULL)
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;
482 return (TRUE);
483 }
484
485 static void
486 tables_term_destination(j_compress_ptr cinfo)
487 {
488 JPEGState* sp = (JPEGState*) cinfo;
489
490 /* set tables length to number of bytes actually emitted */
491 sp->jpegtables_length -= (uint32) sp->dest.free_in_buffer;
492 }
493
494 static int
495 TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
496 {
497 (void) tif;
498 /*
499 * Allocate a working buffer for building tables.
500 * Initial size is 1000 bytes, which is usually adequate.
501 */
502 if (sp->jpegtables)
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");
509 return (0);
510 }
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;
515 return (1);
516 }
517
518 /*
519 * JPEG library source data manager.
520 * These routines supply compressed data to libjpeg.
521 */
522
523 static void
524 std_init_source(j_decompress_ptr cinfo)
525 {
526 JPEGState* sp = (JPEGState*) cinfo;
527 TIFF* tif = sp->tif;
528
529 sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
530 sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
531 }
532
533 static boolean
534 std_fill_input_buffer(j_decompress_ptr cinfo)
535 {
536 JPEGState* sp = (JPEGState* ) cinfo;
537 static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
538
539 #ifdef IPPJ_HUFF
540 /*
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
543 * yet to read.
544 *
545 * We just return without doing anything, until the entire buffer has
546 * been read.
547 * http://trac.osgeo.org/gdal/wiki/JpegIPP
548 */
549 if( sp->src.bytes_in_buffer > 0 ) {
550 return (TRUE);
551 }
552 #endif
553
554 /*
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
560 */
561
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;
566 return (TRUE);
567 }
568
569 static void
570 std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
571 {
572 JPEGState* sp = (JPEGState*) cinfo;
573
574 if (num_bytes > 0) {
575 if ((size_t)num_bytes > sp->src.bytes_in_buffer) {
576 /* oops, buffer overrun */
577 (void) std_fill_input_buffer(cinfo);
578 } else {
579 sp->src.next_input_byte += (size_t) num_bytes;
580 sp->src.bytes_in_buffer -= (size_t) num_bytes;
581 }
582 }
583 }
584
585 static void
586 std_term_source(j_decompress_ptr cinfo)
587 {
588 /* No work necessary here */
589 (void) cinfo;
590 }
591
592 static void
593 TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
594 {
595 (void) 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;
604 }
605
606 /*
607 * Alternate source manager for reading from JPEGTables.
608 * We can share all the code except for the init routine.
609 */
610
611 static void
612 tables_init_source(j_decompress_ptr cinfo)
613 {
614 JPEGState* sp = (JPEGState*) cinfo;
615
616 sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
617 sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
618 }
619
620 static void
621 TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
622 {
623 TIFFjpeg_data_src(sp, tif);
624 sp->src.init_source = tables_init_source;
625 }
626
627 /*
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.
633 */
634 static int
635 alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
636 int num_components)
637 {
638 JPEGState* sp = JState(tif);
639 int ci;
640 jpeg_component_info* compptr;
641 JSAMPARRAY buf;
642 int samples_per_clump = 0;
643
644 for (ci = 0, compptr = comp_info; ci < num_components;
645 ci++, compptr++) {
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));
651 if (buf == NULL)
652 return (0);
653 sp->ds_buffer[ci] = buf;
654 }
655 sp->samplesperclump = samples_per_clump;
656 return (1);
657 }
658
659
660 /*
661 * JPEG Decoding.
662 */
663
664 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
665
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
679 {
680 TIFF* tif;
681 void* buffer;
682 uint32 buffersize;
683 uint8* buffercurrentbyte;
684 uint32 bufferbytesleft;
685 uint64 fileoffset;
686 uint64 filebytesleft;
687 uint8 filepositioned;
688 };
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);
694
695 #endif
696
697 static int
698 JPEGFixupTags(TIFF* tif)
699 {
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);
707 #endif
708
709 return(1);
710 }
711
712 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
713
714 static void
715 JPEGFixupTagsSubsampling(TIFF* tif)
716 {
717 /*
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.
725 *
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.
729 *
730 * See the bug in bugzilla for details:
731 *
732 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
733 *
734 * Frank Warmerdam, July 2002
735 * Joris Van Damme, May 2007
736 */
737 static const char module[] = "JPEGFixupTagsSubsampling";
738 struct JPEGFixupTagsSubsamplingData m;
739
740 _TIFFFillStriles( tif );
741
742 if( tif->tif_dir.td_stripbytecount == NULL
743 || tif->tif_dir.td_stripoffset == NULL
744 || tif->tif_dir.td_stripbytecount[0] == 0 )
745 {
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
748 for instance. */
749 return;
750 }
751
752 m.tif=tif;
753 m.buffersize=2048;
754 m.buffer=_TIFFmalloc(m.buffersize);
755 if (m.buffer==NULL)
756 {
757 TIFFWarningExt(tif->tif_clientdata,module,
758 "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
759 return;
760 }
761 m.buffercurrentbyte=NULL;
762 m.bufferbytesleft=0;
763 m.fileoffset=tif->tif_dir.td_stripoffset[0];
764 m.filepositioned=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");
769 _TIFFfree(m.buffer);
770 }
771
772 static int
773 JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
774 {
775 static const char module[] = "JPEGFixupTagsSubsamplingSec";
776 uint8 m;
777 while (1)
778 {
779 while (1)
780 {
781 if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
782 return(0);
783 if (m==255)
784 break;
785 }
786 while (1)
787 {
788 if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
789 return(0);
790 if (m!=255)
791 break;
792 }
793 switch (m)
794 {
795 case JPEG_MARKER_SOI:
796 /* this type of marker has no data and should be skipped */
797 break;
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 */
820 {
821 uint16 n;
822 if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
823 return(0);
824 if (n<2)
825 return(0);
826 n-=2;
827 if (n>0)
828 JPEGFixupTagsSubsamplingSkip(data,n);
829 }
830 break;
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 */
837 {
838 uint16 n;
839 uint16 o;
840 uint8 p;
841 uint8 ph,pv;
842 if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
843 return(0);
844 if (n!=8+data->tif->tif_dir.td_samplesperpixel*3)
845 return(0);
846 JPEGFixupTagsSubsamplingSkip(data,7);
847 if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
848 return(0);
849 ph=(p>>4);
850 pv=(p&15);
851 JPEGFixupTagsSubsamplingSkip(data,1);
852 for (o=1; o<data->tif->tif_dir.td_samplesperpixel; o++)
853 {
854 JPEGFixupTagsSubsamplingSkip(data,1);
855 if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
856 return(0);
857 if (p!=0x11)
858 {
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");
861 return(1);
862 }
863 JPEGFixupTagsSubsamplingSkip(data,1);
864 }
865 if (((ph!=1)&&(ph!=2)&&(ph!=4))||((pv!=1)&&(pv!=2)&&(pv!=4)))
866 {
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");
869 return(1);
870 }
871 if ((ph!=data->tif->tif_dir.td_ycbcrsubsampling[0])||(pv!=data->tif->tif_dir.td_ycbcrsubsampling[1]))
872 {
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],
877 (int)ph,(int)pv);
878 data->tif->tif_dir.td_ycbcrsubsampling[0]=ph;
879 data->tif->tif_dir.td_ycbcrsubsampling[1]=pv;
880 }
881 }
882 return(1);
883 default:
884 return(0);
885 }
886 }
887 }
888
889 static int
890 JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result)
891 {
892 if (data->bufferbytesleft==0)
893 {
894 uint32 m;
895 if (data->filebytesleft==0)
896 return(0);
897 if (!data->filepositioned)
898 {
899 TIFFSeekFile(data->tif,data->fileoffset,SEEK_SET);
900 data->filepositioned=1;
901 }
902 m=data->buffersize;
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)
907 return(0);
908 data->buffercurrentbyte=data->buffer;
909 data->bufferbytesleft=m;
910 data->fileoffset+=m;
911 data->filebytesleft-=m;
912 }
913 *result=*data->buffercurrentbyte;
914 data->buffercurrentbyte++;
915 data->bufferbytesleft--;
916 return(1);
917 }
918
919 static int
920 JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result)
921 {
922 uint8 ma;
923 uint8 mb;
924 if (!JPEGFixupTagsSubsamplingReadByte(data,&ma))
925 return(0);
926 if (!JPEGFixupTagsSubsamplingReadByte(data,&mb))
927 return(0);
928 *result=(ma<<8)|mb;
929 return(1);
930 }
931
932 static void
933 JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength)
934 {
935 if ((uint32)skiplength<=data->bufferbytesleft)
936 {
937 data->buffercurrentbyte+=skiplength;
938 data->bufferbytesleft-=skiplength;
939 }
940 else
941 {
942 uint16 m;
943 m=(uint16)(skiplength-data->bufferbytesleft);
944 if (m<=data->filebytesleft)
945 {
946 data->bufferbytesleft=0;
947 data->fileoffset+=m;
948 data->filebytesleft-=m;
949 data->filepositioned=0;
950 }
951 else
952 {
953 data->bufferbytesleft=0;
954 data->filebytesleft=0;
955 }
956 }
957 }
958
959 #endif
960
961
962 static int
963 JPEGSetupDecode(TIFF* tif)
964 {
965 JPEGState* sp = JState(tif);
966 TIFFDirectory *td = &tif->tif_dir;
967
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 );
971 #endif
972
973 JPEGInitializeLibJPEG( tif, TRUE );
974
975 assert(sp != NULL);
976 assert(sp->cinfo.comm.is_decompressor);
977
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");
983 return (0);
984 }
985 }
986
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];
993 break;
994 default:
995 /* TIFF 6.0 forbids subsampling of all other color spaces */
996 sp->h_sampling = 1;
997 sp->v_sampling = 1;
998 break;
999 }
1000
1001 /* Set up for reading normal data */
1002 TIFFjpeg_data_src(sp, tif);
1003 tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
1004 return (1);
1005 }
1006
1007 /*
1008 * Set up for decoding a strip or tile.
1009 */
1010 /*ARGSUSED*/ static int
1011 JPEGPreDecode(TIFF* tif, uint16 s)
1012 {
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;
1018 int ci;
1019
1020 assert(sp != NULL);
1021
1022 if (sp->cinfo.comm.is_decompressor == 0)
1023 {
1024 tif->tif_setupdecode( tif );
1025 }
1026
1027 assert(sp->cinfo.comm.is_decompressor);
1028 /*
1029 * Reset decoder state from any previous strip/tile,
1030 * in case application didn't read the whole strip.
1031 */
1032 if (!TIFFjpeg_abort(sp))
1033 return (0);
1034 /*
1035 * Read the header for this strip/tile.
1036 */
1037
1038 if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
1039 return (0);
1040
1041 tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
1042 tif->tif_rawcc = sp->src.bytes_in_buffer;
1043
1044 /*
1045 * Check image parameters and set decompression parameters.
1046 */
1047 segment_width = td->td_imagewidth;
1048 segment_height = td->td_imagelength - tif->tif_row;
1049 if (isTiled(tif)) {
1050 segment_width = td->td_tilewidth;
1051 segment_height = td->td_tilelength;
1052 sp->bytesperline = TIFFTileRowSize(tif);
1053 } else {
1054 if (segment_height > td->td_rowsperstrip)
1055 segment_height = td->td_rowsperstrip;
1056 sp->bytesperline = TIFFScanlineSize(tif);
1057 }
1058 if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1059 /*
1060 * For PC 2, scale down the expected strip/tile size
1061 * to match a downsampled component
1062 */
1063 segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
1064 segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1065 }
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);
1074 }
1075 if (sp->cinfo.d.image_width > segment_width ||
1076 sp->cinfo.d.image_height > segment_height) {
1077 /*
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.
1082 */
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);
1088 return (0);
1089 }
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");
1094 return (0);
1095 }
1096 #ifdef JPEG_LIB_MK1
1097 if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
1098 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
1099 return (0);
1100 }
1101 sp->cinfo.d.data_precision = td->td_bitspersample;
1102 sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
1103 #else
1104 if (sp->cinfo.d.data_precision != td->td_bitspersample) {
1105 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
1106 return (0);
1107 }
1108 #endif
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);
1119 return (0);
1120 }
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");
1126 return (0);
1127 }
1128 }
1129 } else {
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");
1134 return (0);
1135 }
1136 }
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;
1144 } else {
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? */
1152 }
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;
1162 } else {
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;
1168 }
1169 /* Start JPEG decompressor */
1170 if (!TIFFjpeg_start_decompress(sp))
1171 return (0);
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))
1176 return (0);
1177 sp->scancount = DCTSIZE; /* mark buffer empty */
1178 }
1179 return (1);
1180 }
1181
1182 /*
1183 * Decode a chunk of pixels.
1184 * "Standard" case: returned data is not downsampled.
1185 */
1186 #if !JPEG_LIB_MK1_OR_12BIT
1187 static int
1188 JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1189 {
1190 JPEGState *sp = JState(tif);
1191 tmsize_t nrows;
1192 (void) s;
1193
1194 /*
1195 ** Update available information, buffer may have been refilled
1196 ** between decode requests
1197 */
1198 sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
1199 sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
1200
1201 if( sp->bytesperline == 0 )
1202 return 0;
1203
1204 nrows = cc / sp->bytesperline;
1205 if (cc % sp->bytesperline)
1206 TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
1207 "fractional scanline not read");
1208
1209 if( nrows > (tmsize_t) sp->cinfo.d.image_height )
1210 nrows = sp->cinfo.d.image_height;
1211
1212 /* data is expected to be read in multiples of a scanline */
1213 if (nrows)
1214 {
1215 do
1216 {
1217 /*
1218 * In the libjpeg6b-9a 8bit case. We read directly into
1219 * the TIFF buffer.
1220 */
1221 JSAMPROW bufptr = (JSAMPROW)buf;
1222
1223 if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
1224 return (0);
1225
1226 ++tif->tif_row;
1227 buf += sp->bytesperline;
1228 cc -= sp->bytesperline;
1229 } while (--nrows > 0);
1230 }
1231
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;
1235
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);
1239 }
1240 #endif /* !JPEG_LIB_MK1_OR_12BIT */
1241
1242 #if JPEG_LIB_MK1_OR_12BIT
1243 /*ARGSUSED*/ static int
1244 JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1245 {
1246 JPEGState *sp = JState(tif);
1247 tmsize_t nrows;
1248 (void) s;
1249
1250 /*
1251 ** Update available information, buffer may have been refilled
1252 ** between decode requests
1253 */
1254 sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
1255 sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
1256
1257 if( sp->bytesperline == 0 )
1258 return 0;
1259
1260 nrows = cc / sp->bytesperline;
1261 if (cc % sp->bytesperline)
1262 TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
1263 "fractional scanline not read");
1264
1265 if( nrows > (tmsize_t) sp->cinfo.d.image_height )
1266 nrows = sp->cinfo.d.image_height;
1267
1268 /* data is expected to be read in multiples of a scanline */
1269 if (nrows)
1270 {
1271 JSAMPROW line_work_buf = NULL;
1272
1273 /*
1274 * For 6B, only use temporary buffer for 12 bit imagery.
1275 * For Mk1 always use it.
1276 */
1277 if( sp->cinfo.d.data_precision == 12 )
1278 {
1279 line_work_buf = (JSAMPROW)
1280 _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
1281 * sp->cinfo.d.num_components );
1282 }
1283
1284 do
1285 {
1286 if( line_work_buf != NULL )
1287 {
1288 /*
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.
1293 */
1294 if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
1295 return (0);
1296
1297 if( sp->cinfo.d.data_precision == 12 )
1298 {
1299 int value_pairs = (sp->cinfo.d.output_width
1300 * sp->cinfo.d.num_components) / 2;
1301 int iPair;
1302
1303 for( iPair = 0; iPair < value_pairs; iPair++ )
1304 {
1305 unsigned char *out_ptr =
1306 ((unsigned char *) buf) + iPair * 3;
1307 JSAMPLE *in_ptr = line_work_buf + iPair * 2;
1308
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));
1313 }
1314 }
1315 else if( sp->cinfo.d.data_precision == 8 )
1316 {
1317 int value_count = (sp->cinfo.d.output_width
1318 * sp->cinfo.d.num_components);
1319 int iValue;
1320
1321 for( iValue = 0; iValue < value_count; iValue++ )
1322 {
1323 ((unsigned char *) buf)[iValue] =
1324 line_work_buf[iValue] & 0xff;
1325 }
1326 }
1327 }
1328
1329 ++tif->tif_row;
1330 buf += sp->bytesperline;
1331 cc -= sp->bytesperline;
1332 } while (--nrows > 0);
1333
1334 if( line_work_buf != NULL )
1335 _TIFFfree( line_work_buf );
1336 }
1337
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;
1341
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);
1345 }
1346 #endif /* JPEG_LIB_MK1_OR_12BIT */
1347
1348 /*ARGSUSED*/ static int
1349 DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1350
1351 {
1352 (void) buf;
1353 (void) cc;
1354 (void) s;
1355
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." );
1358 return 0;
1359 }
1360
1361 /*
1362 * Decode a chunk of pixels.
1363 * Returned data is downsampled per sampling factors.
1364 */
1365 /*ARGSUSED*/ static int
1366 JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1367 {
1368 JPEGState *sp = JState(tif);
1369 tmsize_t nrows;
1370 (void) s;
1371
1372 /* data is expected to be read in multiples of a scanline */
1373 if ( (nrows = sp->cinfo.d.image_height) != 0 ) {
1374
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;
1378
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);
1383 if(tmpbuf==NULL) {
1384 TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1385 "Out of memory");
1386 return 0;
1387 }
1388 #endif
1389
1390 do {
1391 jpeg_component_info *compptr;
1392 int ci, clumpoffset;
1393
1394 if( cc < sp->bytesperline ) {
1395 TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
1396 "application buffer not large enough for all data.");
1397 return 0;
1398 }
1399
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)
1404 return (0);
1405 sp->scancount = 0;
1406 }
1407 /*
1408 * Fastest way to unseparate data is to make one pass
1409 * over the scanline for each row of each component.
1410 */
1411 clumpoffset = 0; /* first sample in clump */
1412 for (ci = 0, compptr = sp->cinfo.d.comp_info;
1413 ci < sp->cinfo.d.num_components;
1414 ci++, compptr++) {
1415 int hsamp = compptr->h_samp_factor;
1416 int vsamp = compptr->v_samp_factor;
1417 int ypos;
1418
1419 for (ypos = 0; ypos < vsamp; ypos++) {
1420 JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1421 JDIMENSION nclump;
1422 #if defined(JPEG_LIB_MK1_OR_12BIT)
1423 JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
1424 #else
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");
1429 return 0;
1430 }
1431 #endif
1432
1433 if (hsamp == 1) {
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;
1438 }
1439 } else {
1440 int xpos;
1441
1442 /* general case */
1443 for (nclump = clumps_per_line; nclump-- > 0; ) {
1444 for (xpos = 0; xpos < hsamp; xpos++)
1445 outptr[xpos] = *inptr++;
1446 outptr += samples_per_clump;
1447 }
1448 }
1449 clumpoffset += hsamp;
1450 }
1451 }
1452
1453 #if defined(JPEG_LIB_MK1_OR_12BIT)
1454 {
1455 if (sp->cinfo.d.data_precision == 8)
1456 {
1457 int i=0;
1458 int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
1459 for (i=0; i<len; i++)
1460 {
1461 ((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
1462 }
1463 }
1464 else
1465 { /* 12-bit */
1466 int value_pairs = (sp->cinfo.d.output_width
1467 * sp->cinfo.d.num_components) / 2;
1468 int iPair;
1469 for( iPair = 0; iPair < value_pairs; iPair++ )
1470 {
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));
1477 }
1478 }
1479 }
1480 #endif
1481
1482 sp->scancount ++;
1483 tif->tif_row += sp->v_sampling;
1484
1485 buf += sp->bytesperline;
1486 cc -= sp->bytesperline;
1487
1488 nrows -= sp->v_sampling;
1489 } while (nrows > 0);
1490
1491 #if defined(JPEG_LIB_MK1_OR_12BIT)
1492 _TIFFfree(tmpbuf);
1493 #endif
1494
1495 }
1496
1497 /* Close down the decompressor if done. */
1498 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1499 || TIFFjpeg_finish_decompress(sp);
1500 }
1501
1502
1503 /*
1504 * JPEG Encoding.
1505 */
1506
1507 static void
1508 unsuppress_quant_table (JPEGState* sp, int tblno)
1509 {
1510 JQUANT_TBL* qtbl;
1511
1512 if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1513 qtbl->sent_table = FALSE;
1514 }
1515
1516 static void
1517 suppress_quant_table (JPEGState* sp, int tblno)
1518 {
1519 JQUANT_TBL* qtbl;
1520
1521 if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1522 qtbl->sent_table = TRUE;
1523 }
1524
1525 static void
1526 unsuppress_huff_table (JPEGState* sp, int tblno)
1527 {
1528 JHUFF_TBL* htbl;
1529
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;
1534 }
1535
1536 static void
1537 suppress_huff_table (JPEGState* sp, int tblno)
1538 {
1539 JHUFF_TBL* htbl;
1540
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;
1545 }
1546
1547 static int
1548 prepare_JPEGTables(TIFF* tif)
1549 {
1550 JPEGState* sp = JState(tif);
1551
1552 /* Initialize quant tables for current quality setting */
1553 if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1554 return (0);
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))
1558 return (0);
1559 if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
1560 unsuppress_quant_table(sp, 0);
1561 if (sp->photometric == PHOTOMETRIC_YCBCR)
1562 unsuppress_quant_table(sp, 1);
1563 }
1564 if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
1565 unsuppress_huff_table(sp, 0);
1566 if (sp->photometric == PHOTOMETRIC_YCBCR)
1567 unsuppress_huff_table(sp, 1);
1568 }
1569 /* Direct libjpeg output into jpegtables */
1570 if (!TIFFjpeg_tables_dest(sp, tif))
1571 return (0);
1572 /* Emit tables-only datastream */
1573 if (!TIFFjpeg_write_tables(sp))
1574 return (0);
1575
1576 return (1);
1577 }
1578
1579 static int
1580 JPEGSetupEncode(TIFF* tif)
1581 {
1582 JPEGState* sp = JState(tif);
1583 TIFFDirectory *td = &tif->tif_dir;
1584 static const char module[] = "JPEGSetupEncode";
1585
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 );
1589 #endif
1590
1591 JPEGInitializeLibJPEG( tif, FALSE );
1592
1593 assert(sp != NULL);
1594 assert(!sp->cinfo.comm.is_decompressor);
1595
1596 sp->photometric = td->td_photometric;
1597
1598 /*
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.
1602 */
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;
1608 } else {
1609 sp->cinfo.c.in_color_space = JCS_YCbCr;
1610 }
1611 } else {
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;
1618 else
1619 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1620 }
1621 } else {
1622 sp->cinfo.c.input_components = 1;
1623 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1624 }
1625 if (!TIFFjpeg_set_defaults(sp))
1626 return (0);
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 )
1633 {
1634 TIFFErrorExt(tif->tif_clientdata, module,
1635 "Invalig horizontal/vertical sampling value");
1636 return (0);
1637 }
1638 if( td->td_bitspersample > 16 )
1639 {
1640 TIFFErrorExt(tif->tif_clientdata, module,
1641 "BitsPerSample %d not allowed for JPEG",
1642 td->td_bitspersample);
1643 return (0);
1644 }
1645
1646 /*
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.
1650 */
1651 {
1652 float *ref;
1653 if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1654 &ref)) {
1655 float refbw[6];
1656 long top = 1L << td->td_bitspersample;
1657 refbw[0] = 0;
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,
1664 refbw);
1665 }
1666 }
1667 break;
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);
1673 return (0);
1674 default:
1675 /* TIFF 6.0 forbids subsampling of all other color spaces */
1676 sp->h_sampling = 1;
1677 sp->v_sampling = 1;
1678 break;
1679 }
1680
1681 /* Verify miscellaneous parameters */
1682
1683 /*
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.
1687 */
1688 #ifdef JPEG_LIB_MK1
1689 /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1690 if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
1691 #else
1692 if (td->td_bitspersample != BITS_IN_JSAMPLE )
1693 #endif
1694 {
1695 TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
1696 (int) td->td_bitspersample);
1697 return (0);
1698 }
1699 sp->cinfo.c.data_precision = td->td_bitspersample;
1700 #ifdef JPEG_LIB_MK1
1701 sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
1702 #endif
1703 if (isTiled(tif)) {
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);
1708 return (0);
1709 }
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);
1714 return (0);
1715 }
1716 } else {
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);
1722 return (0);
1723 }
1724 }
1725
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 )
1730 {
1731 if (!prepare_JPEGTables(tif))
1732 return (0);
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);
1737 }
1738 } else {
1739 /* We do not support application-supplied JPEGTables, */
1740 /* so mark the field not present */
1741 TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
1742 }
1743
1744 /* Direct libjpeg output to libtiff's output buffer */
1745 TIFFjpeg_data_dest(sp, tif);
1746
1747 return (1);
1748 }
1749
1750 /*
1751 * Set encoding state at the start of a strip or tile.
1752 */
1753 static int
1754 JPEGPreEncode(TIFF* tif, uint16 s)
1755 {
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;
1761
1762 assert(sp != NULL);
1763
1764 if (sp->cinfo.comm.is_decompressor == 1)
1765 {
1766 tif->tif_setupencode( tif );
1767 }
1768
1769 assert(!sp->cinfo.comm.is_decompressor);
1770 /*
1771 * Set encoding parameters for this strip/tile.
1772 */
1773 if (isTiled(tif)) {
1774 segment_width = td->td_tilewidth;
1775 segment_height = td->td_tilelength;
1776 sp->bytesperline = TIFFTileRowSize(tif);
1777 } else {
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);
1783 }
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
1787 */
1788 segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
1789 segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1790 }
1791 if (segment_width > 65535 || segment_height > 65535) {
1792 TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
1793 return (0);
1794 }
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;
1804 }
1805 if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
1806 return (0);
1807 /*
1808 * Set Y sampling factors;
1809 * we assume jpeg_set_colorspace() set the rest to 1
1810 */
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;
1813 } else {
1814 if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
1815 return (0);
1816 /* jpeg_set_colorspace set all sampling factors to 1 */
1817 }
1818 } else {
1819 if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1820 return (0);
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;
1827 }
1828 }
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))
1839 return (0);
1840 if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
1841 suppress_quant_table(sp, 0);
1842 suppress_quant_table(sp, 1);
1843 }
1844 else {
1845 unsuppress_quant_table(sp, 0);
1846 unsuppress_quant_table(sp, 1);
1847 }
1848 if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
1849 {
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;
1856 }
1857 else
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;
1865 } else {
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;
1871 }
1872 /* Start JPEG compressor */
1873 if (!TIFFjpeg_start_compress(sp, FALSE))
1874 return (0);
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))
1879 return (0);
1880 }
1881 sp->scancount = 0;
1882
1883 return (1);
1884 }
1885
1886 /*
1887 * Encode a chunk of pixels.
1888 * "Standard" case: incoming data is not downsampled.
1889 */
1890 static int
1891 JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1892 {
1893 JPEGState *sp = JState(tif);
1894 tmsize_t nrows;
1895 JSAMPROW bufptr[1];
1896 short *line16 = NULL;
1897 int line16_count = 0;
1898
1899 (void) s;
1900 assert(sp != NULL);
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");
1906
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;
1910
1911 if( sp->cinfo.c.data_precision == 12 )
1912 {
1913 line16_count = (int)((sp->bytesperline * 2) / 3);
1914 line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
1915 if (!line16)
1916 {
1917 TIFFErrorExt(tif->tif_clientdata,
1918 "JPEGEncode",
1919 "Failed to allocate memory");
1920
1921 return 0;
1922 }
1923 }
1924
1925 while (nrows-- > 0) {
1926
1927 if( sp->cinfo.c.data_precision == 12 )
1928 {
1929
1930 int value_pairs = line16_count / 2;
1931 int iPair;
1932
1933 bufptr[0] = (JSAMPROW) line16;
1934
1935 for( iPair = 0; iPair < value_pairs; iPair++ )
1936 {
1937 unsigned char *in_ptr =
1938 ((unsigned char *) buf) + iPair * 3;
1939 JSAMPLE *out_ptr = (JSAMPLE *) (line16 + iPair * 2);
1940
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];
1943 }
1944 }
1945 else
1946 {
1947 bufptr[0] = (JSAMPROW) buf;
1948 }
1949 if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
1950 return (0);
1951 if (nrows > 0)
1952 tif->tif_row++;
1953 buf += sp->bytesperline;
1954 }
1955
1956 if( sp->cinfo.c.data_precision == 12 )
1957 {
1958 _TIFFfree( line16 );
1959 }
1960
1961 return (1);
1962 }
1963
1964 /*
1965 * Encode a chunk of pixels.
1966 * Incoming data is expected to be downsampled per sampling factors.
1967 */
1968 static int
1969 JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1970 {
1971 JPEGState *sp = JState(tif);
1972 JSAMPLE* inptr;
1973 JSAMPLE* outptr;
1974 tmsize_t nrows;
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;
1980
1981 (void) s;
1982 assert(sp != NULL);
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)
1988 /8;
1989
1990 nrows = ( cc / bytesperclumpline ) * sp->v_sampling;
1991 if (cc % bytesperclumpline)
1992 TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
1993
1994 /* Cb,Cr both have sampling factors 1, so this is correct */
1995 clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
1996
1997 while (nrows > 0) {
1998 /*
1999 * Fastest way to separate the data is to make one pass
2000 * over the scanline for each row of each component.
2001 */
2002 clumpoffset = 0; /* first sample in clump */
2003 for (ci = 0, compptr = sp->cinfo.c.comp_info;
2004 ci < sp->cinfo.c.num_components;
2005 ci++, compptr++) {
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];
2013 if (hsamp == 1) {
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;
2018 }
2019 } else {
2020 /* general case */
2021 for (nclump = clumps_per_line; nclump-- > 0; ) {
2022 for (xpos = 0; xpos < hsamp; xpos++)
2023 *outptr++ = inptr[xpos];
2024 inptr += samples_per_clump;
2025 }
2026 }
2027 /* pad each scanline as needed */
2028 for (xpos = 0; xpos < padding; xpos++) {
2029 *outptr = outptr[-1];
2030 outptr++;
2031 }
2032 clumpoffset += hsamp;
2033 }
2034 }
2035 sp->scancount++;
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)
2039 return (0);
2040 sp->scancount = 0;
2041 }
2042 tif->tif_row += sp->v_sampling;
2043 buf += bytesperclumpline;
2044 nrows -= sp->v_sampling;
2045 }
2046 return (1);
2047 }
2048
2049 /*
2050 * Finish up at the end of a strip or tile.
2051 */
2052 static int
2053 JPEGPostEncode(TIFF* tif)
2054 {
2055 JPEGState *sp = JState(tif);
2056
2057 if (sp->scancount > 0) {
2058 /*
2059 * Need to emit a partial bufferload of downsampled data.
2060 * Pad the data vertically.
2061 */
2062 int ci, ypos, n;
2063 jpeg_component_info* compptr;
2064
2065 for (ci = 0, compptr = sp->cinfo.c.comp_info;
2066 ci < sp->cinfo.c.num_components;
2067 ci++, compptr++) {
2068 int vsamp = compptr->v_samp_factor;
2069 tmsize_t row_width = compptr->width_in_blocks * DCTSIZE
2070 * sizeof(JSAMPLE);
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],
2075 row_width);
2076
2077 }
2078 }
2079 n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
2080 if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
2081 return (0);
2082 }
2083
2084 return (TIFFjpeg_finish_compress(JState(tif)));
2085 }
2086
2087 static void
2088 JPEGCleanup(TIFF* tif)
2089 {
2090 JPEGState *sp = JState(tif);
2091
2092 assert(sp != 0);
2093
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;
2103
2104 _TIFFSetDefaultCompressionState(tif);
2105 }
2106
2107 static void
2108 JPEGResetUpsampled( TIFF* tif )
2109 {
2110 JPEGState* sp = JState(tif);
2111 TIFFDirectory* td = &tif->tif_dir;
2112
2113 /*
2114 * Mark whether returned data is up-sampled or not so TIFFStripSize
2115 * and TIFFTileSize return values that reflect the true amount of
2116 * data.
2117 */
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;
2123 } else {
2124 #ifdef notdef
2125 if (td->td_ycbcrsubsampling[0] != 1 ||
2126 td->td_ycbcrsubsampling[1] != 1)
2127 ; /* XXX what about up-sampling? */
2128 #endif
2129 }
2130 }
2131
2132 /*
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?
2135 */
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);
2140 }
2141
2142 static int
2143 JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
2144 {
2145 JPEGState* sp = JState(tif);
2146 const TIFFField* fip;
2147 uint32 v32;
2148
2149 assert(sp != NULL);
2150
2151 switch (tag) {
2152 case TIFFTAG_JPEGTABLES:
2153 v32 = (uint32) va_arg(ap, uint32);
2154 if (v32 == 0) {
2155 /* XXX */
2156 return (0);
2157 }
2158 _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*), v32);
2159 sp->jpegtables_length = v32;
2160 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
2161 break;
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:
2170 {
2171 int ret_value = (*sp->vsetparent)(tif, tag, ap);
2172 JPEGResetUpsampled( tif );
2173 return ret_value;
2174 }
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);
2183 default:
2184 return (*sp->vsetparent)(tif, tag, ap);
2185 }
2186
2187 if ((fip = TIFFFieldWithTag(tif, tag)) != NULL) {
2188 TIFFSetFieldBit(tif, fip->field_bit);
2189 } else {
2190 return (0);
2191 }
2192
2193 tif->tif_flags |= TIFF_DIRTYDIRECT;
2194 return (1);
2195 }
2196
2197 static int
2198 JPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
2199 {
2200 JPEGState* sp = JState(tif);
2201
2202 assert(sp != NULL);
2203
2204 switch (tag) {
2205 case TIFFTAG_JPEGTABLES:
2206 *va_arg(ap, uint32*) = sp->jpegtables_length;
2207 *va_arg(ap, void**) = sp->jpegtables;
2208 break;
2209 case TIFFTAG_JPEGQUALITY:
2210 *va_arg(ap, int*) = sp->jpegquality;
2211 break;
2212 case TIFFTAG_JPEGCOLORMODE:
2213 *va_arg(ap, int*) = sp->jpegcolormode;
2214 break;
2215 case TIFFTAG_JPEGTABLESMODE:
2216 *va_arg(ap, int*) = sp->jpegtablesmode;
2217 break;
2218 default:
2219 return (*sp->vgetparent)(tif, tag, ap);
2220 }
2221 return (1);
2222 }
2223
2224 static void
2225 JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
2226 {
2227 JPEGState* sp = JState(tif);
2228
2229 assert(sp != NULL);
2230 (void) flags;
2231
2232 if( sp != NULL ) {
2233 if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
2234 fprintf(fd, " JPEG Tables: (%lu bytes)\n",
2235 (unsigned long) sp->jpegtables_length);
2236 if (sp->printdir)
2237 (*sp->printdir)(tif, fd, flags);
2238 }
2239 }
2240
2241 static uint32
2242 JPEGDefaultStripSize(TIFF* tif, uint32 s)
2243 {
2244 JPEGState* sp = JState(tif);
2245 TIFFDirectory *td = &tif->tif_dir;
2246
2247 s = (*sp->defsparent)(tif, s);
2248 if (s < td->td_imagelength)
2249 s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
2250 return (s);
2251 }
2252
2253 static void
2254 JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
2255 {
2256 JPEGState* sp = JState(tif);
2257 TIFFDirectory *td = &tif->tif_dir;
2258
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);
2262 }
2263
2264 /*
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.
2271 *
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.
2277 *
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 ...
2282 *
2283 * NFW, Feb 3rd, 2003.
2284 */
2285
2286 static int JPEGInitializeLibJPEG( TIFF * tif, int decompress )
2287 {
2288 JPEGState* sp = JState(tif);
2289
2290 if(sp->cinfo_initialized)
2291 {
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 );
2296 else
2297 return 1;
2298
2299 sp->cinfo_initialized = 0;
2300 }
2301
2302 /*
2303 * Initialize libjpeg.
2304 */
2305 if ( decompress ) {
2306 if (!TIFFjpeg_create_decompress(sp))
2307 return (0);
2308 } else {
2309 if (!TIFFjpeg_create_compress(sp))
2310 return (0);
2311 #ifndef TIFF_JPEG_MAX_MEMORY_TO_USE
2312 #define TIFF_JPEG_MAX_MEMORY_TO_USE (10 * 1024 * 1024)
2313 #endif
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;
2320 }
2321
2322 sp->cinfo_initialized = TRUE;
2323
2324 return 1;
2325 }
2326
2327 int
2328 TIFFInitJPEG(TIFF* tif, int scheme)
2329 {
2330 JPEGState* sp;
2331
2332 assert(scheme == COMPRESSION_JPEG);
2333
2334 /*
2335 * Merge codec-specific tag information.
2336 */
2337 if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields))) {
2338 TIFFErrorExt(tif->tif_clientdata,
2339 "TIFFInitJPEG",
2340 "Merging JPEG codec-specific tags failed");
2341 return 0;
2342 }
2343
2344 /*
2345 * Allocate state block so tag methods have storage to record values.
2346 */
2347 tif->tif_data = (uint8*) _TIFFmalloc(sizeof (JPEGState));
2348
2349 if (tif->tif_data == NULL) {
2350 TIFFErrorExt(tif->tif_clientdata,
2351 "TIFFInitJPEG", "No space for JPEG state block");
2352 return 0;
2353 }
2354 _TIFFmemset(tif->tif_data, 0, sizeof(JPEGState));
2355
2356 sp = JState(tif);
2357 sp->tif = tif; /* back link */
2358
2359 /*
2360 * Override parent get/set field methods.
2361 */
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 */
2368
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;
2376
2377 /*
2378 * Install codec methods.
2379 */
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 */
2398
2399 sp->cinfo_initialized = FALSE;
2400
2401 /*
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
2405 ** size later.
2406 */
2407 if( tif->tif_diroff == 0 )
2408 {
2409 #define SIZE_OF_JPEGTABLES 2000
2410 /*
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);
2417 */
2418 sp->jpegtables_length = SIZE_OF_JPEGTABLES;
2419 sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
2420 if (sp->jpegtables)
2421 {
2422 _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
2423 }
2424 else
2425 {
2426 TIFFErrorExt(tif->tif_clientdata,
2427 "TIFFInitJPEG",
2428 "Failed to allocate memory for JPEG tables");
2429 return 0;
2430 }
2431 #undef SIZE_OF_JPEGTABLES
2432 }
2433
2434 return 1;
2435 }
2436 #endif /* JPEG_SUPPORT */
2437
2438 /* vim: set ts=8 sts=8 sw=8 noet: */
2439
2440 /*
2441 * Local Variables:
2442 * mode: c
2443 * c-basic-offset: 8
2444 * fill-column: 78
2445 * End:
2446 */