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