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