Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(16)

Side by Side Diff: third_party/tiff_v403/tif_jpeg.c

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

Powered by Google App Engine
This is Rietveld 408576698