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