]> git.saurik.com Git - wxWidgets.git/blob - src/tiff/libtiff/tif_jpeg.c
fixing warning about missing virt destructor
[wxWidgets.git] / src / tiff / libtiff / tif_jpeg.c
1 /* $Id$ */
2
3 /*
4 * Copyright (c) 1994-1997 Sam Leffler
5 * Copyright (c) 1994-1997 Silicon Graphics, Inc.
6 *
7 * Permission to use, copy, modify, distribute, and sell this software and
8 * its documentation for any purpose is hereby granted without fee, provided
9 * that (i) the above copyright notices and this permission notice appear in
10 * all copies of the software and related documentation, and (ii) the names of
11 * Sam Leffler and Silicon Graphics may not be used in any advertising or
12 * publicity relating to the software without the specific, prior written
13 * permission of Sam Leffler and Silicon Graphics.
14 *
15 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
18 *
19 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24 * OF THIS SOFTWARE.
25 */
26
27 #define WIN32_LEAN_AND_MEAN
28 #define VC_EXTRALEAN
29
30 #include "tiffiop.h"
31 #ifdef JPEG_SUPPORT
32
33 /*
34 * TIFF Library
35 *
36 * JPEG Compression support per TIFF Technical Note #2
37 * (*not* per the original TIFF 6.0 spec).
38 *
39 * This file is simply an interface to the libjpeg library written by
40 * the Independent JPEG Group. You need release 5 or later of the IJG
41 * code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
42 *
43 * Contributed by Tom Lane <tgl@sss.pgh.pa.us>.
44 */
45 #include <setjmp.h>
46
47 int TIFFFillStrip(TIFF*, tstrip_t);
48 int TIFFFillTile(TIFF*, ttile_t);
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 #ifdef wxHACK_BOOLEAN
88 #include "wx/defs.h"
89 #define XMD_H 1
90 #define HAVE_BOOLEAN
91 #define boolean wxHACK_BOOLEAN
92 #endif
93
94 #include "jpeglib.h"
95 #include "jerror.h"
96
97 #ifndef HAVE_WXJPEG_BOOLEAN
98 typedef boolean wxjpeg_boolean;
99 #endif
100
101 /*
102 * We are using width_in_blocks which is supposed to be private to
103 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
104 * renamed this member to width_in_data_units. Since the header has
105 * also renamed a define, use that unique define name in order to
106 * detect the problem header and adjust to suit.
107 */
108 #if defined(D_MAX_DATA_UNITS_IN_MCU)
109 #define width_in_blocks width_in_data_units
110 #endif
111
112 /*
113 * On some machines it may be worthwhile to use _setjmp or sigsetjmp
114 * in place of plain setjmp. These macros will make it easier.
115 */
116 #define SETJMP(jbuf) setjmp(jbuf)
117 #define LONGJMP(jbuf,code) longjmp(jbuf,code)
118 #define JMP_BUF jmp_buf
119
120 typedef struct jpeg_destination_mgr jpeg_destination_mgr;
121 typedef struct jpeg_source_mgr jpeg_source_mgr;
122 typedef struct jpeg_error_mgr jpeg_error_mgr;
123
124 /*
125 * State block for each open TIFF file using
126 * libjpeg to do JPEG compression/decompression.
127 *
128 * libjpeg's visible state is either a jpeg_compress_struct
129 * or jpeg_decompress_struct depending on which way we
130 * are going. comm can be used to refer to the fields
131 * which are common to both.
132 *
133 * NB: cinfo is required to be the first member of JPEGState,
134 * so we can safely cast JPEGState* -> jpeg_xxx_struct*
135 * and vice versa!
136 */
137 typedef struct {
138 union {
139 struct jpeg_compress_struct c;
140 struct jpeg_decompress_struct d;
141 struct jpeg_common_struct comm;
142 } cinfo; /* NB: must be first */
143 int cinfo_initialized;
144
145 jpeg_error_mgr err; /* libjpeg error manager */
146 JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
147 /*
148 * The following two members could be a union, but
149 * they're small enough that it's not worth the effort.
150 */
151 jpeg_destination_mgr dest; /* data dest for compression */
152 jpeg_source_mgr src; /* data source for decompression */
153 /* private state */
154 TIFF* tif; /* back link needed by some code */
155 uint16 photometric; /* copy of PhotometricInterpretation */
156 uint16 h_sampling; /* luminance sampling factors */
157 uint16 v_sampling;
158 tsize_t bytesperline; /* decompressed bytes per scanline */
159 /* pointers to intermediate buffers when processing downsampled data */
160 JSAMPARRAY ds_buffer[MAX_COMPONENTS];
161 int scancount; /* number of "scanlines" accumulated */
162 int samplesperclump;
163
164 TIFFVGetMethod vgetparent; /* super-class method */
165 TIFFVSetMethod vsetparent; /* super-class method */
166 TIFFStripMethod defsparent; /* super-class method */
167 TIFFTileMethod deftparent; /* super-class method */
168 /* pseudo-tag fields */
169 void* jpegtables; /* JPEGTables tag value, or NULL */
170 uint32 jpegtables_length; /* number of bytes in same */
171 int jpegquality; /* Compression quality level */
172 int jpegcolormode; /* Auto RGB<=>YCbCr convert? */
173 int jpegtablesmode; /* What to put in JPEGTables */
174
175 int ycbcrsampling_fetched;
176 uint32 recvparams; /* encoded Class 2 session params */
177 char* subaddress; /* subaddress string */
178 uint32 recvtime; /* time spent receiving (secs) */
179 char* faxdcs; /* encoded fax parameters (DCS, Table 2/T.30) */
180 } JPEGState;
181
182 #define JState(tif) ((JPEGState*)(tif)->tif_data)
183
184 static int JPEGDecode(TIFF*, tidata_t, tsize_t, tsample_t);
185 static int JPEGDecodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
186 static int JPEGEncode(TIFF*, tidata_t, tsize_t, tsample_t);
187 static int JPEGEncodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
188 static int JPEGInitializeLibJPEG( TIFF * tif,
189 int force_encode, int force_decode );
190
191 #define FIELD_JPEGTABLES (FIELD_CODEC+0)
192 #define FIELD_RECVPARAMS (FIELD_CODEC+1)
193 #define FIELD_SUBADDRESS (FIELD_CODEC+2)
194 #define FIELD_RECVTIME (FIELD_CODEC+3)
195 #define FIELD_FAXDCS (FIELD_CODEC+4)
196
197 static const TIFFFieldInfo jpegFieldInfo[] = {
198 { TIFFTAG_JPEGTABLES, -3,-3, TIFF_UNDEFINED, FIELD_JPEGTABLES,
199 FALSE, TRUE, "JPEGTables" },
200 { TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, FIELD_PSEUDO,
201 TRUE, FALSE, "" },
202 { TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
203 FALSE, FALSE, "" },
204 { TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, FIELD_PSEUDO,
205 FALSE, FALSE, "" },
206 /* Specific for JPEG in faxes */
207 { TIFFTAG_FAXRECVPARAMS, 1, 1, TIFF_LONG, FIELD_RECVPARAMS,
208 TRUE, FALSE, "FaxRecvParams" },
209 { TIFFTAG_FAXSUBADDRESS, -1,-1, TIFF_ASCII, FIELD_SUBADDRESS,
210 TRUE, FALSE, "FaxSubAddress" },
211 { TIFFTAG_FAXRECVTIME, 1, 1, TIFF_LONG, FIELD_RECVTIME,
212 TRUE, FALSE, "FaxRecvTime" },
213 { TIFFTAG_FAXDCS, -1, -1, TIFF_ASCII, FIELD_FAXDCS,
214 TRUE, FALSE, "FaxDcs" },
215 };
216 #define N(a) (sizeof (a) / sizeof (a[0]))
217
218 /*
219 * libjpeg interface layer.
220 *
221 * We use setjmp/longjmp to return control to libtiff
222 * when a fatal error is encountered within the JPEG
223 * library. We also direct libjpeg error and warning
224 * messages through the appropriate libtiff handlers.
225 */
226
227 /*
228 * Error handling routines (these replace corresponding
229 * IJG routines from jerror.c). These are used for both
230 * compression and decompression.
231 */
232 static void
233 TIFFjpeg_error_exit(j_common_ptr cinfo)
234 {
235 JPEGState *sp = (JPEGState *) cinfo; /* NB: cinfo assumed first */
236 char buffer[JMSG_LENGTH_MAX];
237
238 (*cinfo->err->format_message) (cinfo, buffer);
239 TIFFErrorExt(sp->tif->tif_clientdata, "JPEGLib", buffer); /* display the error message */
240 jpeg_abort(cinfo); /* clean up libjpeg state */
241 LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
242 }
243
244 /*
245 * This routine is invoked only for warning messages,
246 * since error_exit does its own thing and trace_level
247 * is never set > 0.
248 */
249 static void
250 TIFFjpeg_output_message(j_common_ptr cinfo)
251 {
252 char buffer[JMSG_LENGTH_MAX];
253
254 (*cinfo->err->format_message) (cinfo, buffer);
255 TIFFWarningExt(((JPEGState *) cinfo)->tif->tif_clientdata, "JPEGLib", buffer);
256 }
257
258 /*
259 * Interface routines. This layer of routines exists
260 * primarily to limit side-effects from using setjmp.
261 * Also, normal/error returns are converted into return
262 * values per libtiff practice.
263 */
264 #define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
265 #define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
266
267 static int
268 TIFFjpeg_create_compress(JPEGState* sp)
269 {
270 /* initialize JPEG error handling */
271 sp->cinfo.c.err = jpeg_std_error(&sp->err);
272 sp->err.error_exit = TIFFjpeg_error_exit;
273 sp->err.output_message = TIFFjpeg_output_message;
274
275 return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
276 }
277
278 static int
279 TIFFjpeg_create_decompress(JPEGState* sp)
280 {
281 /* initialize JPEG error handling */
282 sp->cinfo.d.err = jpeg_std_error(&sp->err);
283 sp->err.error_exit = TIFFjpeg_error_exit;
284 sp->err.output_message = TIFFjpeg_output_message;
285
286 return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
287 }
288
289 static int
290 TIFFjpeg_set_defaults(JPEGState* sp)
291 {
292 return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
293 }
294
295 static int
296 TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
297 {
298 return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
299 }
300
301 static int
302 TIFFjpeg_set_quality(JPEGState* sp, int quality, wxjpeg_boolean force_baseline)
303 {
304 return CALLVJPEG(sp,
305 jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
306 }
307
308 static int
309 TIFFjpeg_suppress_tables(JPEGState* sp, wxjpeg_boolean suppress)
310 {
311 return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
312 }
313
314 static int
315 TIFFjpeg_start_compress(JPEGState* sp, wxjpeg_boolean write_all_tables)
316 {
317 return CALLVJPEG(sp,
318 jpeg_start_compress(&sp->cinfo.c, write_all_tables));
319 }
320
321 static int
322 TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
323 {
324 return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
325 scanlines, (JDIMENSION) num_lines));
326 }
327
328 static int
329 TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
330 {
331 return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
332 data, (JDIMENSION) num_lines));
333 }
334
335 static int
336 TIFFjpeg_finish_compress(JPEGState* sp)
337 {
338 return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
339 }
340
341 static int
342 TIFFjpeg_write_tables(JPEGState* sp)
343 {
344 return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
345 }
346
347 static int
348 TIFFjpeg_read_header(JPEGState* sp, wxjpeg_boolean require_image)
349 {
350 return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
351 }
352
353 static int
354 TIFFjpeg_start_decompress(JPEGState* sp)
355 {
356 return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
357 }
358
359 static int
360 TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
361 {
362 return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
363 scanlines, (JDIMENSION) max_lines));
364 }
365
366 static int
367 TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
368 {
369 return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
370 data, (JDIMENSION) max_lines));
371 }
372
373 static int
374 TIFFjpeg_finish_decompress(JPEGState* sp)
375 {
376 return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
377 }
378
379 static int
380 TIFFjpeg_abort(JPEGState* sp)
381 {
382 return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
383 }
384
385 static int
386 TIFFjpeg_destroy(JPEGState* sp)
387 {
388 return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
389 }
390
391 static JSAMPARRAY
392 TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
393 JDIMENSION samplesperrow, JDIMENSION numrows)
394 {
395 return CALLJPEG(sp, (JSAMPARRAY) NULL,
396 (*sp->cinfo.comm.mem->alloc_sarray)
397 (&sp->cinfo.comm, pool_id, samplesperrow, numrows));
398 }
399
400 /*
401 * JPEG library destination data manager.
402 * These routines direct compressed data from libjpeg into the
403 * libtiff output buffer.
404 */
405
406 static void
407 std_init_destination(j_compress_ptr cinfo)
408 {
409 JPEGState* sp = (JPEGState*) cinfo;
410 TIFF* tif = sp->tif;
411
412 sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
413 sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
414 }
415
416 static wxjpeg_boolean
417 std_empty_output_buffer(j_compress_ptr cinfo)
418 {
419 JPEGState* sp = (JPEGState*) cinfo;
420 TIFF* tif = sp->tif;
421
422 /* the entire buffer has been filled */
423 tif->tif_rawcc = tif->tif_rawdatasize;
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 = (tidata_t) sp->dest.next_output_byte;
438 tif->tif_rawcc =
439 tif->tif_rawdatasize - (tsize_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 wxjpeg_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((tdata_t) sp->jpegtables,
475 (tsize_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 -= 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((tsize_t) sp->jpegtables_length);
506 if (sp->jpegtables == NULL) {
507 sp->jpegtables_length = 0;
508 TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
509 return (0);
510 }
511 sp->cinfo.c.dest = &sp->dest;
512 sp->dest.init_destination = tables_init_destination;
513 sp->dest.empty_output_buffer = tables_empty_output_buffer;
514 sp->dest.term_destination = tables_term_destination;
515 return (1);
516 }
517
518 /*
519 * JPEG library source data manager.
520 * These routines supply compressed data to libjpeg.
521 */
522
523 static void
524 std_init_source(j_decompress_ptr cinfo)
525 {
526 JPEGState* sp = (JPEGState*) cinfo;
527 TIFF* tif = sp->tif;
528
529 sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
530 sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
531 }
532
533 static wxjpeg_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 /*
540 * Should never get here since entire strip/tile is
541 * read into memory before the decompressor is called,
542 * and thus was supplied by init_source.
543 */
544 WARNMS(cinfo, JWRN_JPEG_EOF);
545 /* insert a fake EOI marker */
546 sp->src.next_input_byte = dummy_EOI;
547 sp->src.bytes_in_buffer = 2;
548 return (TRUE);
549 }
550
551 static void
552 std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
553 {
554 JPEGState* sp = (JPEGState*) cinfo;
555
556 if (num_bytes > 0) {
557 if (num_bytes > (long) sp->src.bytes_in_buffer) {
558 /* oops, buffer overrun */
559 (void) std_fill_input_buffer(cinfo);
560 } else {
561 sp->src.next_input_byte += (size_t) num_bytes;
562 sp->src.bytes_in_buffer -= (size_t) num_bytes;
563 }
564 }
565 }
566
567 static void
568 std_term_source(j_decompress_ptr cinfo)
569 {
570 /* No work necessary here */
571 /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
572 /* (if so, need empty tables_term_source!) */
573 (void) cinfo;
574 }
575
576 static void
577 TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
578 {
579 (void) tif;
580 sp->cinfo.d.src = &sp->src;
581 sp->src.init_source = std_init_source;
582 sp->src.fill_input_buffer = std_fill_input_buffer;
583 sp->src.skip_input_data = std_skip_input_data;
584 sp->src.resync_to_restart = jpeg_resync_to_restart;
585 sp->src.term_source = std_term_source;
586 sp->src.bytes_in_buffer = 0; /* for safety */
587 sp->src.next_input_byte = NULL;
588 }
589
590 /*
591 * Alternate source manager for reading from JPEGTables.
592 * We can share all the code except for the init routine.
593 */
594
595 static void
596 tables_init_source(j_decompress_ptr cinfo)
597 {
598 JPEGState* sp = (JPEGState*) cinfo;
599
600 sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
601 sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
602 }
603
604 static void
605 TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
606 {
607 TIFFjpeg_data_src(sp, tif);
608 sp->src.init_source = tables_init_source;
609 }
610
611 /*
612 * Allocate downsampled-data buffers needed for downsampled I/O.
613 * We use values computed in jpeg_start_compress or jpeg_start_decompress.
614 * We use libjpeg's allocator so that buffers will be released automatically
615 * when done with strip/tile.
616 * This is also a handy place to compute samplesperclump, bytesperline.
617 */
618 static int
619 alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
620 int num_components)
621 {
622 JPEGState* sp = JState(tif);
623 int ci;
624 jpeg_component_info* compptr;
625 JSAMPARRAY buf;
626 int samples_per_clump = 0;
627
628 for (ci = 0, compptr = comp_info; ci < num_components;
629 ci++, compptr++) {
630 samples_per_clump += compptr->h_samp_factor *
631 compptr->v_samp_factor;
632 buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
633 compptr->width_in_blocks * DCTSIZE,
634 (JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
635 if (buf == NULL)
636 return (0);
637 sp->ds_buffer[ci] = buf;
638 }
639 sp->samplesperclump = samples_per_clump;
640 return (1);
641 }
642
643
644 /*
645 * JPEG Decoding.
646 */
647
648 static int
649 JPEGSetupDecode(TIFF* tif)
650 {
651 JPEGState* sp = JState(tif);
652 TIFFDirectory *td = &tif->tif_dir;
653
654 JPEGInitializeLibJPEG( tif, 0, 1 );
655
656 assert(sp != NULL);
657 assert(sp->cinfo.comm.is_decompressor);
658
659 /* Read JPEGTables if it is present */
660 if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
661 TIFFjpeg_tables_src(sp, tif);
662 if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
663 TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
664 return (0);
665 }
666 }
667
668 /* Grab parameters that are same for all strips/tiles */
669 sp->photometric = td->td_photometric;
670 switch (sp->photometric) {
671 case PHOTOMETRIC_YCBCR:
672 sp->h_sampling = td->td_ycbcrsubsampling[0];
673 sp->v_sampling = td->td_ycbcrsubsampling[1];
674 break;
675 default:
676 /* TIFF 6.0 forbids subsampling of all other color spaces */
677 sp->h_sampling = 1;
678 sp->v_sampling = 1;
679 break;
680 }
681
682 /* Set up for reading normal data */
683 TIFFjpeg_data_src(sp, tif);
684 tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
685 return (1);
686 }
687
688 /*
689 * Set up for decoding a strip or tile.
690 */
691 static int
692 JPEGPreDecode(TIFF* tif, tsample_t s)
693 {
694 JPEGState *sp = JState(tif);
695 TIFFDirectory *td = &tif->tif_dir;
696 static const char module[] = "JPEGPreDecode";
697 uint32 segment_width, segment_height;
698 int downsampled_output;
699 int ci;
700
701 assert(sp != NULL);
702 assert(sp->cinfo.comm.is_decompressor);
703 /*
704 * Reset decoder state from any previous strip/tile,
705 * in case application didn't read the whole strip.
706 */
707 if (!TIFFjpeg_abort(sp))
708 return (0);
709 /*
710 * Read the header for this strip/tile.
711 */
712 if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
713 return (0);
714 /*
715 * Check image parameters and set decompression parameters.
716 */
717 segment_width = td->td_imagewidth;
718 segment_height = td->td_imagelength - tif->tif_row;
719 if (isTiled(tif)) {
720 segment_width = td->td_tilewidth;
721 segment_height = td->td_tilelength;
722 sp->bytesperline = TIFFTileRowSize(tif);
723 } else {
724 if (segment_height > td->td_rowsperstrip)
725 segment_height = td->td_rowsperstrip;
726 sp->bytesperline = TIFFScanlineSize(tif);
727 }
728 if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
729 /*
730 * For PC 2, scale down the expected strip/tile size
731 * to match a downsampled component
732 */
733 segment_width = TIFFhowmany(segment_width, sp->h_sampling);
734 segment_height = TIFFhowmany(segment_height, sp->v_sampling);
735 }
736 if (sp->cinfo.d.image_width != segment_width ||
737 sp->cinfo.d.image_height != segment_height) {
738 TIFFWarningExt(tif->tif_clientdata, module,
739 "Improper JPEG strip/tile size, expected %dx%d, got %dx%d",
740 segment_width,
741 segment_height,
742 sp->cinfo.d.image_width,
743 sp->cinfo.d.image_height);
744 }
745 if (sp->cinfo.d.num_components !=
746 (td->td_planarconfig == PLANARCONFIG_CONTIG ?
747 td->td_samplesperpixel : 1)) {
748 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG component count");
749 return (0);
750 }
751 #ifdef JPEG_LIB_MK1
752 if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
753 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
754 return (0);
755 }
756 sp->cinfo.d.data_precision = td->td_bitspersample;
757 sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
758 #else
759 if (sp->cinfo.d.data_precision != td->td_bitspersample) {
760 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
761 return (0);
762 }
763 #endif
764 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
765 /* Component 0 should have expected sampling factors */
766 if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
767 sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
768 TIFFWarningExt(tif->tif_clientdata, module,
769 "Improper JPEG sampling factors %d,%d\n"
770 "Apparently should be %d,%d.",
771 sp->cinfo.d.comp_info[0].h_samp_factor,
772 sp->cinfo.d.comp_info[0].v_samp_factor,
773 sp->h_sampling, sp->v_sampling);
774
775 /*
776 * XXX: Files written by the Intergraph software
777 * has different sampling factors stored in the
778 * TIFF tags and in the JPEG structures. We will
779 * try to deduce Intergraph files by the presense
780 * of the tag 33918.
781 */
782 if (!_TIFFFindFieldInfo(tif, 33918, TIFF_ANY)) {
783 TIFFWarningExt(tif->tif_clientdata, module,
784 "Decompressor will try reading with "
785 "sampling %d,%d.",
786 sp->cinfo.d.comp_info[0].h_samp_factor,
787 sp->cinfo.d.comp_info[0].v_samp_factor);
788
789 sp->h_sampling = (uint16)
790 sp->cinfo.d.comp_info[0].h_samp_factor;
791 sp->v_sampling = (uint16)
792 sp->cinfo.d.comp_info[0].v_samp_factor;
793 }
794 }
795 /* Rest should have sampling factors 1,1 */
796 for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
797 if (sp->cinfo.d.comp_info[ci].h_samp_factor != 1 ||
798 sp->cinfo.d.comp_info[ci].v_samp_factor != 1) {
799 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
800 return (0);
801 }
802 }
803 } else {
804 /* PC 2's single component should have sampling factors 1,1 */
805 if (sp->cinfo.d.comp_info[0].h_samp_factor != 1 ||
806 sp->cinfo.d.comp_info[0].v_samp_factor != 1) {
807 TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG sampling factors");
808 return (0);
809 }
810 }
811 downsampled_output = FALSE;
812 if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
813 sp->photometric == PHOTOMETRIC_YCBCR &&
814 sp->jpegcolormode == JPEGCOLORMODE_RGB) {
815 /* Convert YCbCr to RGB */
816 sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
817 sp->cinfo.d.out_color_space = JCS_RGB;
818 } else {
819 /* Suppress colorspace handling */
820 sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
821 sp->cinfo.d.out_color_space = JCS_UNKNOWN;
822 if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
823 (sp->h_sampling != 1 || sp->v_sampling != 1))
824 downsampled_output = TRUE;
825 /* XXX what about up-sampling? */
826 }
827 if (downsampled_output) {
828 /* Need to use raw-data interface to libjpeg */
829 sp->cinfo.d.raw_data_out = TRUE;
830 tif->tif_decoderow = JPEGDecodeRaw;
831 tif->tif_decodestrip = JPEGDecodeRaw;
832 tif->tif_decodetile = JPEGDecodeRaw;
833 } else {
834 /* Use normal interface to libjpeg */
835 sp->cinfo.d.raw_data_out = FALSE;
836 tif->tif_decoderow = JPEGDecode;
837 tif->tif_decodestrip = JPEGDecode;
838 tif->tif_decodetile = JPEGDecode;
839 }
840 /* Start JPEG decompressor */
841 if (!TIFFjpeg_start_decompress(sp))
842 return (0);
843 /* Allocate downsampled-data buffers if needed */
844 if (downsampled_output) {
845 if (!alloc_downsampled_buffers(tif, sp->cinfo.d.comp_info,
846 sp->cinfo.d.num_components))
847 return (0);
848 sp->scancount = DCTSIZE; /* mark buffer empty */
849 }
850 return (1);
851 }
852
853 /*
854 * Decode a chunk of pixels.
855 * "Standard" case: returned data is not downsampled.
856 */
857 /*ARGSUSED*/ static int
858 JPEGDecode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
859 {
860 JPEGState *sp = JState(tif);
861 tsize_t nrows;
862 (void) s;
863
864 nrows = cc / sp->bytesperline;
865 if (cc % sp->bytesperline)
866 TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
867
868 if( nrows > (int) sp->cinfo.d.image_height )
869 nrows = sp->cinfo.d.image_height;
870
871 /* data is expected to be read in multiples of a scanline */
872 if (nrows)
873 {
874 JSAMPROW line_work_buf = NULL;
875
876 /*
877 ** For 6B, only use temporary buffer for 12 bit imagery.
878 ** For Mk1 always use it.
879 */
880 #if !defined(JPEG_LIB_MK1)
881 if( sp->cinfo.d.data_precision == 12 )
882 #endif
883 {
884 line_work_buf = (JSAMPROW)
885 _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
886 * sp->cinfo.d.num_components );
887 }
888
889 do {
890 if( line_work_buf != NULL )
891 {
892 /*
893 ** In the MK1 case, we aways read into a 16bit buffer, and then
894 ** pack down to 12bit or 8bit. In 6B case we only read into 16
895 ** bit buffer for 12bit data, which we need to repack.
896 */
897 if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
898 return (0);
899
900 if( sp->cinfo.d.data_precision == 12 )
901 {
902 int value_pairs = (sp->cinfo.d.output_width
903 * sp->cinfo.d.num_components) / 2;
904 int iPair;
905
906 for( iPair = 0; iPair < value_pairs; iPair++ )
907 {
908 unsigned char *out_ptr =
909 ((unsigned char *) buf) + iPair * 3;
910 JSAMPLE *in_ptr = line_work_buf + iPair * 2;
911
912 out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
913 out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
914 | ((in_ptr[1] & 0xf00) >> 8);
915 out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
916 }
917 }
918 else if( sp->cinfo.d.data_precision == 8 )
919 {
920 int value_count = (sp->cinfo.d.output_width
921 * sp->cinfo.d.num_components);
922 int iValue;
923
924 for( iValue = 0; iValue < value_count; iValue++ )
925 {
926 ((unsigned char *) buf)[iValue] =
927 line_work_buf[iValue] & 0xff;
928 }
929 }
930 }
931 else
932 {
933 /*
934 ** In the libjpeg6b 8bit case. We read directly into the
935 ** TIFF buffer.
936 */
937 JSAMPROW bufptr = (JSAMPROW)buf;
938
939 if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
940 return (0);
941 }
942
943 ++tif->tif_row;
944 buf += sp->bytesperline;
945 cc -= sp->bytesperline;
946 } while (--nrows > 0);
947
948 if( line_work_buf != NULL )
949 _TIFFfree( line_work_buf );
950 }
951
952 /* Close down the decompressor if we've finished the strip or tile. */
953 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
954 || TIFFjpeg_finish_decompress(sp);
955 }
956
957 /*
958 * Decode a chunk of pixels.
959 * Returned data is downsampled per sampling factors.
960 */
961 /*ARGSUSED*/ static int
962 JPEGDecodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
963 {
964 JPEGState *sp = JState(tif);
965 tsize_t nrows;
966 (void) s;
967
968 /* data is expected to be read in multiples of a scanline */
969 if ( (nrows = sp->cinfo.d.image_height) ) {
970 /* Cb,Cr both have sampling factors 1, so this is correct */
971 JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;
972 int samples_per_clump = sp->samplesperclump;
973
974 #ifdef JPEG_LIB_MK1
975 unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
976 sp->cinfo.d.output_width *
977 sp->cinfo.d.num_components);
978 #endif
979
980 do {
981 jpeg_component_info *compptr;
982 int ci, clumpoffset;
983
984 /* Reload downsampled-data buffer if needed */
985 if (sp->scancount >= DCTSIZE) {
986 int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
987 if (TIFFjpeg_read_raw_data(sp, sp->ds_buffer, n)
988 != n)
989 return (0);
990 sp->scancount = 0;
991 }
992 /*
993 * Fastest way to unseparate data is to make one pass
994 * over the scanline for each row of each component.
995 */
996 clumpoffset = 0; /* first sample in clump */
997 for (ci = 0, compptr = sp->cinfo.d.comp_info;
998 ci < sp->cinfo.d.num_components;
999 ci++, compptr++) {
1000 int hsamp = compptr->h_samp_factor;
1001 int vsamp = compptr->v_samp_factor;
1002 int ypos;
1003
1004 for (ypos = 0; ypos < vsamp; ypos++) {
1005 JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1006 #ifdef JPEG_LIB_MK1
1007 JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
1008 #else
1009 JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
1010 #endif
1011 JDIMENSION nclump;
1012
1013 if (hsamp == 1) {
1014 /* fast path for at least Cb and Cr */
1015 for (nclump = clumps_per_line; nclump-- > 0; ) {
1016 outptr[0] = *inptr++;
1017 outptr += samples_per_clump;
1018 }
1019 } else {
1020 int xpos;
1021
1022 /* general case */
1023 for (nclump = clumps_per_line; nclump-- > 0; ) {
1024 for (xpos = 0; xpos < hsamp; xpos++)
1025 outptr[xpos] = *inptr++;
1026 outptr += samples_per_clump;
1027 }
1028 }
1029 clumpoffset += hsamp;
1030 }
1031 }
1032
1033 #ifdef JPEG_LIB_MK1
1034 {
1035 if (sp->cinfo.d.data_precision == 8)
1036 {
1037 int i=0;
1038 int len = sp->cinfo.d.output_width * sp->cinfo.d.num_components;
1039 for (i=0; i<len; i++)
1040 {
1041 ((unsigned char*)buf)[i] = tmpbuf[i] & 0xff;
1042 }
1043 }
1044 else
1045 { // 12-bit
1046 int value_pairs = (sp->cinfo.d.output_width
1047 * sp->cinfo.d.num_components) / 2;
1048 int iPair;
1049 for( iPair = 0; iPair < value_pairs; iPair++ )
1050 {
1051 unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
1052 JSAMPLE *in_ptr = tmpbuf + iPair * 2;
1053 out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
1054 out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
1055 | ((in_ptr[1] & 0xf00) >> 8);
1056 out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
1057 }
1058 }
1059 }
1060 #endif
1061
1062 ++sp->scancount;
1063 ++tif->tif_row;
1064 buf += sp->bytesperline;
1065 cc -= sp->bytesperline;
1066 } while (--nrows > 0);
1067
1068 #ifdef JPEG_LIB_MK1
1069 _TIFFfree(tmpbuf);
1070 #endif
1071
1072 }
1073
1074 /* Close down the decompressor if done. */
1075 return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1076 || TIFFjpeg_finish_decompress(sp);
1077 }
1078
1079
1080 /*
1081 * JPEG Encoding.
1082 */
1083
1084 static void
1085 unsuppress_quant_table (JPEGState* sp, int tblno)
1086 {
1087 JQUANT_TBL* qtbl;
1088
1089 if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
1090 qtbl->sent_table = FALSE;
1091 }
1092
1093 static void
1094 unsuppress_huff_table (JPEGState* sp, int tblno)
1095 {
1096 JHUFF_TBL* htbl;
1097
1098 if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
1099 htbl->sent_table = FALSE;
1100 if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
1101 htbl->sent_table = FALSE;
1102 }
1103
1104 static int
1105 prepare_JPEGTables(TIFF* tif)
1106 {
1107 JPEGState* sp = JState(tif);
1108
1109 JPEGInitializeLibJPEG( tif, 0, 0 );
1110
1111 /* Initialize quant tables for current quality setting */
1112 if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1113 return (0);
1114 /* Mark only the tables we want for output */
1115 /* NB: chrominance tables are currently used only with YCbCr */
1116 if (!TIFFjpeg_suppress_tables(sp, TRUE))
1117 return (0);
1118 if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
1119 unsuppress_quant_table(sp, 0);
1120 if (sp->photometric == PHOTOMETRIC_YCBCR)
1121 unsuppress_quant_table(sp, 1);
1122 }
1123 if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF) {
1124 unsuppress_huff_table(sp, 0);
1125 if (sp->photometric == PHOTOMETRIC_YCBCR)
1126 unsuppress_huff_table(sp, 1);
1127 }
1128 /* Direct libjpeg output into jpegtables */
1129 if (!TIFFjpeg_tables_dest(sp, tif))
1130 return (0);
1131 /* Emit tables-only datastream */
1132 if (!TIFFjpeg_write_tables(sp))
1133 return (0);
1134
1135 return (1);
1136 }
1137
1138 static int
1139 JPEGSetupEncode(TIFF* tif)
1140 {
1141 JPEGState* sp = JState(tif);
1142 TIFFDirectory *td = &tif->tif_dir;
1143 static const char module[] = "JPEGSetupEncode";
1144
1145 JPEGInitializeLibJPEG( tif, 1, 0 );
1146
1147 assert(sp != NULL);
1148 assert(!sp->cinfo.comm.is_decompressor);
1149
1150 /*
1151 * Initialize all JPEG parameters to default values.
1152 * Note that jpeg_set_defaults needs legal values for
1153 * in_color_space and input_components.
1154 */
1155 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1156 sp->cinfo.c.input_components = 1;
1157 if (!TIFFjpeg_set_defaults(sp))
1158 return (0);
1159 /* Set per-file parameters */
1160 sp->photometric = td->td_photometric;
1161 switch (sp->photometric) {
1162 case PHOTOMETRIC_YCBCR:
1163 sp->h_sampling = td->td_ycbcrsubsampling[0];
1164 sp->v_sampling = td->td_ycbcrsubsampling[1];
1165 /*
1166 * A ReferenceBlackWhite field *must* be present since the
1167 * default value is inappropriate for YCbCr. Fill in the
1168 * proper value if application didn't set it.
1169 */
1170 {
1171 float *ref;
1172 if (!TIFFGetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1173 &ref)) {
1174 float refbw[6];
1175 long top = 1L << td->td_bitspersample;
1176 refbw[0] = 0;
1177 refbw[1] = (float)(top-1L);
1178 refbw[2] = (float)(top>>1);
1179 refbw[3] = refbw[1];
1180 refbw[4] = refbw[2];
1181 refbw[5] = refbw[1];
1182 TIFFSetField(tif, TIFFTAG_REFERENCEBLACKWHITE,
1183 refbw);
1184 }
1185 }
1186 break;
1187 case PHOTOMETRIC_PALETTE: /* disallowed by Tech Note */
1188 case PHOTOMETRIC_MASK:
1189 TIFFErrorExt(tif->tif_clientdata, module,
1190 "PhotometricInterpretation %d not allowed for JPEG",
1191 (int) sp->photometric);
1192 return (0);
1193 default:
1194 /* TIFF 6.0 forbids subsampling of all other color spaces */
1195 sp->h_sampling = 1;
1196 sp->v_sampling = 1;
1197 break;
1198 }
1199
1200 /* Verify miscellaneous parameters */
1201
1202 /*
1203 * This would need work if libtiff ever supports different
1204 * depths for different components, or if libjpeg ever supports
1205 * run-time selection of depth. Neither is imminent.
1206 */
1207 #ifdef JPEG_LIB_MK1
1208 /* BITS_IN_JSAMPLE now permits 8 and 12 --- dgilbert */
1209 if (td->td_bitspersample != 8 && td->td_bitspersample != 12)
1210 #else
1211 if (td->td_bitspersample != BITS_IN_JSAMPLE )
1212 #endif
1213 {
1214 TIFFErrorExt(tif->tif_clientdata, module, "BitsPerSample %d not allowed for JPEG",
1215 (int) td->td_bitspersample);
1216 return (0);
1217 }
1218 sp->cinfo.c.data_precision = td->td_bitspersample;
1219 #ifdef JPEG_LIB_MK1
1220 sp->cinfo.c.bits_in_jsample = td->td_bitspersample;
1221 #endif
1222 if (isTiled(tif)) {
1223 if ((td->td_tilelength % (sp->v_sampling * DCTSIZE)) != 0) {
1224 TIFFErrorExt(tif->tif_clientdata, module,
1225 "JPEG tile height must be multiple of %d",
1226 sp->v_sampling * DCTSIZE);
1227 return (0);
1228 }
1229 if ((td->td_tilewidth % (sp->h_sampling * DCTSIZE)) != 0) {
1230 TIFFErrorExt(tif->tif_clientdata, module,
1231 "JPEG tile width must be multiple of %d",
1232 sp->h_sampling * DCTSIZE);
1233 return (0);
1234 }
1235 } else {
1236 if (td->td_rowsperstrip < td->td_imagelength &&
1237 (td->td_rowsperstrip % (sp->v_sampling * DCTSIZE)) != 0) {
1238 TIFFErrorExt(tif->tif_clientdata, module,
1239 "RowsPerStrip must be multiple of %d for JPEG",
1240 sp->v_sampling * DCTSIZE);
1241 return (0);
1242 }
1243 }
1244
1245 /* Create a JPEGTables field if appropriate */
1246 if (sp->jpegtablesmode & (JPEGTABLESMODE_QUANT|JPEGTABLESMODE_HUFF)) {
1247 if (!prepare_JPEGTables(tif))
1248 return (0);
1249 /* Mark the field present */
1250 /* Can't use TIFFSetField since BEENWRITING is already set! */
1251 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1252 tif->tif_flags |= TIFF_DIRTYDIRECT;
1253 } else {
1254 /* We do not support application-supplied JPEGTables, */
1255 /* so mark the field not present */
1256 TIFFClrFieldBit(tif, FIELD_JPEGTABLES);
1257 }
1258
1259 /* Direct libjpeg output to libtiff's output buffer */
1260 TIFFjpeg_data_dest(sp, tif);
1261
1262 return (1);
1263 }
1264
1265 /*
1266 * Set encoding state at the start of a strip or tile.
1267 */
1268 static int
1269 JPEGPreEncode(TIFF* tif, tsample_t s)
1270 {
1271 JPEGState *sp = JState(tif);
1272 TIFFDirectory *td = &tif->tif_dir;
1273 static const char module[] = "JPEGPreEncode";
1274 uint32 segment_width, segment_height;
1275 int downsampled_input;
1276
1277 assert(sp != NULL);
1278 assert(!sp->cinfo.comm.is_decompressor);
1279 /*
1280 * Set encoding parameters for this strip/tile.
1281 */
1282 if (isTiled(tif)) {
1283 segment_width = td->td_tilewidth;
1284 segment_height = td->td_tilelength;
1285 sp->bytesperline = TIFFTileRowSize(tif);
1286 } else {
1287 segment_width = td->td_imagewidth;
1288 segment_height = td->td_imagelength - tif->tif_row;
1289 if (segment_height > td->td_rowsperstrip)
1290 segment_height = td->td_rowsperstrip;
1291 sp->bytesperline = TIFFScanlineSize(tif);
1292 }
1293 if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1294 /* for PC 2, scale down the strip/tile size
1295 * to match a downsampled component
1296 */
1297 segment_width = TIFFhowmany(segment_width, sp->h_sampling);
1298 segment_height = TIFFhowmany(segment_height, sp->v_sampling);
1299 }
1300 if (segment_width > 65535 || segment_height > 65535) {
1301 TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
1302 return (0);
1303 }
1304 sp->cinfo.c.image_width = segment_width;
1305 sp->cinfo.c.image_height = segment_height;
1306 downsampled_input = FALSE;
1307 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1308 sp->cinfo.c.input_components = td->td_samplesperpixel;
1309 if (sp->photometric == PHOTOMETRIC_YCBCR) {
1310 if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1311 sp->cinfo.c.in_color_space = JCS_RGB;
1312 } else {
1313 sp->cinfo.c.in_color_space = JCS_YCbCr;
1314 if (sp->h_sampling != 1 || sp->v_sampling != 1)
1315 downsampled_input = TRUE;
1316 }
1317 if (!TIFFjpeg_set_colorspace(sp, JCS_YCbCr))
1318 return (0);
1319 /*
1320 * Set Y sampling factors;
1321 * we assume jpeg_set_colorspace() set the rest to 1
1322 */
1323 sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
1324 sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
1325 } else {
1326 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1327 if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1328 return (0);
1329 /* jpeg_set_colorspace set all sampling factors to 1 */
1330 }
1331 } else {
1332 sp->cinfo.c.input_components = 1;
1333 sp->cinfo.c.in_color_space = JCS_UNKNOWN;
1334 if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
1335 return (0);
1336 sp->cinfo.c.comp_info[0].component_id = s;
1337 /* jpeg_set_colorspace() set sampling factors to 1 */
1338 if (sp->photometric == PHOTOMETRIC_YCBCR && s > 0) {
1339 sp->cinfo.c.comp_info[0].quant_tbl_no = 1;
1340 sp->cinfo.c.comp_info[0].dc_tbl_no = 1;
1341 sp->cinfo.c.comp_info[0].ac_tbl_no = 1;
1342 }
1343 }
1344 /* ensure libjpeg won't write any extraneous markers */
1345 sp->cinfo.c.write_JFIF_header = FALSE;
1346 sp->cinfo.c.write_Adobe_marker = FALSE;
1347 /* set up table handling correctly */
1348 if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
1349 if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1350 return (0);
1351 unsuppress_quant_table(sp, 0);
1352 unsuppress_quant_table(sp, 1);
1353 }
1354 if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
1355 sp->cinfo.c.optimize_coding = FALSE;
1356 else
1357 sp->cinfo.c.optimize_coding = TRUE;
1358 if (downsampled_input) {
1359 /* Need to use raw-data interface to libjpeg */
1360 sp->cinfo.c.raw_data_in = TRUE;
1361 tif->tif_encoderow = JPEGEncodeRaw;
1362 tif->tif_encodestrip = JPEGEncodeRaw;
1363 tif->tif_encodetile = JPEGEncodeRaw;
1364 } else {
1365 /* Use normal interface to libjpeg */
1366 sp->cinfo.c.raw_data_in = FALSE;
1367 tif->tif_encoderow = JPEGEncode;
1368 tif->tif_encodestrip = JPEGEncode;
1369 tif->tif_encodetile = JPEGEncode;
1370 }
1371 /* Start JPEG compressor */
1372 if (!TIFFjpeg_start_compress(sp, FALSE))
1373 return (0);
1374 /* Allocate downsampled-data buffers if needed */
1375 if (downsampled_input) {
1376 if (!alloc_downsampled_buffers(tif, sp->cinfo.c.comp_info,
1377 sp->cinfo.c.num_components))
1378 return (0);
1379 }
1380 sp->scancount = 0;
1381
1382 return (1);
1383 }
1384
1385 /*
1386 * Encode a chunk of pixels.
1387 * "Standard" case: incoming data is not downsampled.
1388 */
1389 static int
1390 JPEGEncode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
1391 {
1392 JPEGState *sp = JState(tif);
1393 tsize_t nrows;
1394 JSAMPROW bufptr[1];
1395
1396 (void) s;
1397 assert(sp != NULL);
1398 /* data is expected to be supplied in multiples of a scanline */
1399 nrows = cc / sp->bytesperline;
1400 if (cc % sp->bytesperline)
1401 TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
1402
1403 while (nrows-- > 0) {
1404 bufptr[0] = (JSAMPROW) buf;
1405 if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
1406 return (0);
1407 if (nrows > 0)
1408 tif->tif_row++;
1409 buf += sp->bytesperline;
1410 }
1411 return (1);
1412 }
1413
1414 /*
1415 * Encode a chunk of pixels.
1416 * Incoming data is expected to be downsampled per sampling factors.
1417 */
1418 static int
1419 JPEGEncodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
1420 {
1421 JPEGState *sp = JState(tif);
1422 JSAMPLE* inptr;
1423 JSAMPLE* outptr;
1424 tsize_t nrows;
1425 JDIMENSION clumps_per_line, nclump;
1426 int clumpoffset, ci, xpos, ypos;
1427 jpeg_component_info* compptr;
1428 int samples_per_clump = sp->samplesperclump;
1429
1430 (void) s;
1431 assert(sp != NULL);
1432 /* data is expected to be supplied in multiples of a scanline */
1433 nrows = cc / sp->bytesperline;
1434 if (cc % sp->bytesperline)
1435 TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
1436
1437 /* Cb,Cr both have sampling factors 1, so this is correct */
1438 clumps_per_line = sp->cinfo.c.comp_info[1].downsampled_width;
1439
1440 while (nrows-- > 0) {
1441 /*
1442 * Fastest way to separate the data is to make one pass
1443 * over the scanline for each row of each component.
1444 */
1445 clumpoffset = 0; /* first sample in clump */
1446 for (ci = 0, compptr = sp->cinfo.c.comp_info;
1447 ci < sp->cinfo.c.num_components;
1448 ci++, compptr++) {
1449 int hsamp = compptr->h_samp_factor;
1450 int vsamp = compptr->v_samp_factor;
1451 int padding = (int) (compptr->width_in_blocks * DCTSIZE -
1452 clumps_per_line * hsamp);
1453 for (ypos = 0; ypos < vsamp; ypos++) {
1454 inptr = ((JSAMPLE*) buf) + clumpoffset;
1455 outptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1456 if (hsamp == 1) {
1457 /* fast path for at least Cb and Cr */
1458 for (nclump = clumps_per_line; nclump-- > 0; ) {
1459 *outptr++ = inptr[0];
1460 inptr += samples_per_clump;
1461 }
1462 } else {
1463 /* general case */
1464 for (nclump = clumps_per_line; nclump-- > 0; ) {
1465 for (xpos = 0; xpos < hsamp; xpos++)
1466 *outptr++ = inptr[xpos];
1467 inptr += samples_per_clump;
1468 }
1469 }
1470 /* pad each scanline as needed */
1471 for (xpos = 0; xpos < padding; xpos++) {
1472 *outptr = outptr[-1];
1473 outptr++;
1474 }
1475 clumpoffset += hsamp;
1476 }
1477 }
1478 sp->scancount++;
1479 if (sp->scancount >= DCTSIZE) {
1480 int n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1481 if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1482 return (0);
1483 sp->scancount = 0;
1484 }
1485 if (nrows > 0)
1486 tif->tif_row++;
1487 buf += sp->bytesperline;
1488 }
1489 return (1);
1490 }
1491
1492 /*
1493 * Finish up at the end of a strip or tile.
1494 */
1495 static int
1496 JPEGPostEncode(TIFF* tif)
1497 {
1498 JPEGState *sp = JState(tif);
1499
1500 if (sp->scancount > 0) {
1501 /*
1502 * Need to emit a partial bufferload of downsampled data.
1503 * Pad the data vertically.
1504 */
1505 int ci, ypos, n;
1506 jpeg_component_info* compptr;
1507
1508 for (ci = 0, compptr = sp->cinfo.c.comp_info;
1509 ci < sp->cinfo.c.num_components;
1510 ci++, compptr++) {
1511 int vsamp = compptr->v_samp_factor;
1512 tsize_t row_width = compptr->width_in_blocks * DCTSIZE
1513 * sizeof(JSAMPLE);
1514 for (ypos = sp->scancount * vsamp;
1515 ypos < DCTSIZE * vsamp; ypos++) {
1516 _TIFFmemcpy((tdata_t)sp->ds_buffer[ci][ypos],
1517 (tdata_t)sp->ds_buffer[ci][ypos-1],
1518 row_width);
1519
1520 }
1521 }
1522 n = sp->cinfo.c.max_v_samp_factor * DCTSIZE;
1523 if (TIFFjpeg_write_raw_data(sp, sp->ds_buffer, n) != n)
1524 return (0);
1525 }
1526
1527 return (TIFFjpeg_finish_compress(JState(tif)));
1528 }
1529
1530 static void
1531 JPEGCleanup(TIFF* tif)
1532 {
1533 JPEGState *sp = JState(tif);
1534
1535 assert(sp != 0);
1536
1537 tif->tif_tagmethods.vgetfield = sp->vgetparent;
1538 tif->tif_tagmethods.vsetfield = sp->vsetparent;
1539
1540 if( sp->cinfo_initialized )
1541 TIFFjpeg_destroy(sp); /* release libjpeg resources */
1542 if (sp->jpegtables) /* tag value */
1543 _TIFFfree(sp->jpegtables);
1544 _TIFFfree(tif->tif_data); /* release local state */
1545 tif->tif_data = NULL;
1546
1547 _TIFFSetDefaultCompressionState(tif);
1548 }
1549
1550 static int
1551 JPEGVSetField(TIFF* tif, ttag_t tag, va_list ap)
1552 {
1553 JPEGState* sp = JState(tif);
1554 TIFFDirectory* td = &tif->tif_dir;
1555 uint32 v32;
1556
1557 assert(sp != NULL);
1558
1559 switch (tag) {
1560 case TIFFTAG_JPEGTABLES:
1561 v32 = va_arg(ap, uint32);
1562 if (v32 == 0) {
1563 /* XXX */
1564 return (0);
1565 }
1566 _TIFFsetByteArray(&sp->jpegtables, va_arg(ap, void*),
1567 (long) v32);
1568 sp->jpegtables_length = v32;
1569 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1570 break;
1571 case TIFFTAG_JPEGQUALITY:
1572 sp->jpegquality = va_arg(ap, int);
1573 return (1); /* pseudo tag */
1574 case TIFFTAG_JPEGCOLORMODE:
1575 sp->jpegcolormode = va_arg(ap, int);
1576 /*
1577 * Mark whether returned data is up-sampled or not
1578 * so TIFFStripSize and TIFFTileSize return values
1579 * that reflect the true amount of data.
1580 */
1581 tif->tif_flags &= ~TIFF_UPSAMPLED;
1582 if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
1583 if (td->td_photometric == PHOTOMETRIC_YCBCR &&
1584 sp->jpegcolormode == JPEGCOLORMODE_RGB) {
1585 tif->tif_flags |= TIFF_UPSAMPLED;
1586 } else {
1587 if (td->td_ycbcrsubsampling[0] != 1 ||
1588 td->td_ycbcrsubsampling[1] != 1)
1589 ; /* XXX what about up-sampling? */
1590 }
1591 }
1592 /*
1593 * Must recalculate cached tile size
1594 * in case sampling state changed.
1595 */
1596 tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tsize_t) -1;
1597 return (1); /* pseudo tag */
1598 case TIFFTAG_JPEGTABLESMODE:
1599 sp->jpegtablesmode = va_arg(ap, int);
1600 return (1); /* pseudo tag */
1601 case TIFFTAG_YCBCRSUBSAMPLING:
1602 /* mark the fact that we have a real ycbcrsubsampling! */
1603 sp->ycbcrsampling_fetched = 1;
1604 return (*sp->vsetparent)(tif, tag, ap);
1605 case TIFFTAG_FAXRECVPARAMS:
1606 sp->recvparams = va_arg(ap, uint32);
1607 break;
1608 case TIFFTAG_FAXSUBADDRESS:
1609 _TIFFsetString(&sp->subaddress, va_arg(ap, char*));
1610 break;
1611 case TIFFTAG_FAXRECVTIME:
1612 sp->recvtime = va_arg(ap, uint32);
1613 break;
1614 case TIFFTAG_FAXDCS:
1615 _TIFFsetString(&sp->faxdcs, va_arg(ap, char*));
1616 break;
1617 default:
1618 return (*sp->vsetparent)(tif, tag, ap);
1619 }
1620 TIFFSetFieldBit(tif, _TIFFFieldWithTag(tif, tag)->field_bit);
1621 tif->tif_flags |= TIFF_DIRTYDIRECT;
1622 return (1);
1623 }
1624
1625 /*
1626 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
1627 * the TIFF tags, but still use non-default (2,2) values within the jpeg
1628 * data stream itself. In order for TIFF applications to work properly
1629 * - for instance to get the strip buffer size right - it is imperative
1630 * that the subsampling be available before we start reading the image
1631 * data normally. This function will attempt to load the first strip in
1632 * order to get the sampling values from the jpeg data stream. Various
1633 * hacks are various places are done to ensure this function gets called
1634 * before the td_ycbcrsubsampling values are used from the directory structure,
1635 * including calling TIFFGetField() for the YCBCRSUBSAMPLING field from
1636 * TIFFStripSize(), and the printing code in tif_print.c.
1637 *
1638 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
1639 * discovered sampling does not match the default sampling (2,2) or whatever
1640 * was actually in the tiff tags.
1641 *
1642 * Problems:
1643 * o This code will cause one whole strip/tile of compressed data to be
1644 * loaded just to get the tags right, even if the imagery is never read.
1645 * It would be more efficient to just load a bit of the header, and
1646 * initialize things from that.
1647 *
1648 * See the bug in bugzilla for details:
1649 *
1650 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
1651 *
1652 * Frank Warmerdam, July 2002
1653 */
1654
1655 static void
1656 JPEGFixupTestSubsampling( TIFF * tif )
1657 {
1658 #ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
1659 JPEGState *sp = JState(tif);
1660 TIFFDirectory *td = &tif->tif_dir;
1661
1662 JPEGInitializeLibJPEG( tif, 0, 0 );
1663
1664 /*
1665 * Some JPEG-in-TIFF files don't provide the ycbcrsampling tags,
1666 * and use a sampling schema other than the default 2,2. To handle
1667 * this we actually have to scan the header of a strip or tile of
1668 * jpeg data to get the sampling.
1669 */
1670 if( !sp->cinfo.comm.is_decompressor
1671 || sp->ycbcrsampling_fetched
1672 || td->td_photometric != PHOTOMETRIC_YCBCR )
1673 return;
1674
1675 sp->ycbcrsampling_fetched = 1;
1676 if( TIFFIsTiled( tif ) )
1677 {
1678 if( !TIFFFillTile( tif, 0 ) )
1679 return;
1680 }
1681 else
1682 {
1683 if( !TIFFFillStrip( tif, 0 ) )
1684 return;
1685 }
1686
1687 TIFFSetField( tif, TIFFTAG_YCBCRSUBSAMPLING,
1688 (uint16) sp->h_sampling, (uint16) sp->v_sampling );
1689 #endif /* CHECK_JPEG_YCBCR_SUBSAMPLING */
1690 }
1691
1692 static int
1693 JPEGVGetField(TIFF* tif, ttag_t tag, va_list ap)
1694 {
1695 JPEGState* sp = JState(tif);
1696
1697 assert(sp != NULL);
1698
1699 switch (tag) {
1700 case TIFFTAG_JPEGTABLES:
1701 *va_arg(ap, uint32*) = sp->jpegtables_length;
1702 *va_arg(ap, void**) = sp->jpegtables;
1703 break;
1704 case TIFFTAG_JPEGQUALITY:
1705 *va_arg(ap, int*) = sp->jpegquality;
1706 break;
1707 case TIFFTAG_JPEGCOLORMODE:
1708 *va_arg(ap, int*) = sp->jpegcolormode;
1709 break;
1710 case TIFFTAG_JPEGTABLESMODE:
1711 *va_arg(ap, int*) = sp->jpegtablesmode;
1712 break;
1713 case TIFFTAG_YCBCRSUBSAMPLING:
1714 JPEGFixupTestSubsampling( tif );
1715 return (*sp->vgetparent)(tif, tag, ap);
1716 break;
1717 case TIFFTAG_FAXRECVPARAMS:
1718 *va_arg(ap, uint32*) = sp->recvparams;
1719 break;
1720 case TIFFTAG_FAXSUBADDRESS:
1721 *va_arg(ap, char**) = sp->subaddress;
1722 break;
1723 case TIFFTAG_FAXRECVTIME:
1724 *va_arg(ap, uint32*) = sp->recvtime;
1725 break;
1726 case TIFFTAG_FAXDCS:
1727 *va_arg(ap, char**) = sp->faxdcs;
1728 break;
1729 default:
1730 return (*sp->vgetparent)(tif, tag, ap);
1731 }
1732 return (1);
1733 }
1734
1735 static void
1736 JPEGPrintDir(TIFF* tif, FILE* fd, long flags)
1737 {
1738 JPEGState* sp = JState(tif);
1739
1740 assert(sp != NULL);
1741
1742 (void) flags;
1743 if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
1744 fprintf(fd, " JPEG Tables: (%lu bytes)\n",
1745 (unsigned long) sp->jpegtables_length);
1746 if (TIFFFieldSet(tif,FIELD_RECVPARAMS))
1747 fprintf(fd, " Fax Receive Parameters: %08lx\n",
1748 (unsigned long) sp->recvparams);
1749 if (TIFFFieldSet(tif,FIELD_SUBADDRESS))
1750 fprintf(fd, " Fax SubAddress: %s\n", sp->subaddress);
1751 if (TIFFFieldSet(tif,FIELD_RECVTIME))
1752 fprintf(fd, " Fax Receive Time: %lu secs\n",
1753 (unsigned long) sp->recvtime);
1754 if (TIFFFieldSet(tif,FIELD_FAXDCS))
1755 fprintf(fd, " Fax DCS: %s\n", sp->faxdcs);
1756 }
1757
1758 static uint32
1759 JPEGDefaultStripSize(TIFF* tif, uint32 s)
1760 {
1761 JPEGState* sp = JState(tif);
1762 TIFFDirectory *td = &tif->tif_dir;
1763
1764 s = (*sp->defsparent)(tif, s);
1765 if (s < td->td_imagelength)
1766 s = TIFFroundup(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
1767 return (s);
1768 }
1769
1770 static void
1771 JPEGDefaultTileSize(TIFF* tif, uint32* tw, uint32* th)
1772 {
1773 JPEGState* sp = JState(tif);
1774 TIFFDirectory *td = &tif->tif_dir;
1775
1776 (*sp->deftparent)(tif, tw, th);
1777 *tw = TIFFroundup(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
1778 *th = TIFFroundup(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
1779 }
1780
1781 /*
1782 * The JPEG library initialized used to be done in TIFFInitJPEG(), but
1783 * now that we allow a TIFF file to be opened in update mode it is necessary
1784 * to have some way of deciding whether compression or decompression is
1785 * desired other than looking at tif->tif_mode. We accomplish this by
1786 * examining {TILE/STRIP}BYTECOUNTS to see if there is a non-zero entry.
1787 * If so, we assume decompression is desired.
1788 *
1789 * This is tricky, because TIFFInitJPEG() is called while the directory is
1790 * being read, and generally speaking the BYTECOUNTS tag won't have been read
1791 * at that point. So we try to defer jpeg library initialization till we
1792 * do have that tag ... basically any access that might require the compressor
1793 * or decompressor that occurs after the reading of the directory.
1794 *
1795 * In an ideal world compressors or decompressors would be setup
1796 * at the point where a single tile or strip was accessed (for read or write)
1797 * so that stuff like update of missing tiles, or replacement of tiles could
1798 * be done. However, we aren't trying to crack that nut just yet ...
1799 *
1800 * NFW, Feb 3rd, 2003.
1801 */
1802
1803 static int JPEGInitializeLibJPEG( TIFF * tif, int force_encode, int force_decode )
1804 {
1805 JPEGState* sp = JState(tif);
1806 uint32 *byte_counts = NULL;
1807 int data_is_empty = TRUE;
1808 int decompress;
1809
1810 if( sp->cinfo_initialized )
1811 return 1;
1812
1813 /*
1814 * Do we have tile data already? Make sure we initialize the
1815 * the state in decompressor mode if we have tile data, even if we
1816 * are not in read-only file access mode.
1817 */
1818 if( TIFFIsTiled( tif )
1819 && TIFFGetField( tif, TIFFTAG_TILEBYTECOUNTS, &byte_counts )
1820 && byte_counts != NULL )
1821 {
1822 data_is_empty = byte_counts[0] == 0;
1823 }
1824 if( !TIFFIsTiled( tif )
1825 && TIFFGetField( tif, TIFFTAG_STRIPBYTECOUNTS, &byte_counts)
1826 && byte_counts != NULL )
1827 {
1828 data_is_empty = byte_counts[0] == 0;
1829 }
1830
1831 if( force_decode )
1832 decompress = 1;
1833 else if( force_encode )
1834 decompress = 0;
1835 else if( tif->tif_mode == O_RDONLY )
1836 decompress = 1;
1837 else if( data_is_empty )
1838 decompress = 0;
1839 else
1840 decompress = 1;
1841
1842 /*
1843 * Initialize libjpeg.
1844 */
1845 if ( decompress ) {
1846 if (!TIFFjpeg_create_decompress(sp))
1847 return (0);
1848
1849 } else {
1850 if (!TIFFjpeg_create_compress(sp))
1851 return (0);
1852 }
1853
1854 sp->cinfo_initialized = TRUE;
1855
1856 return 1;
1857 }
1858
1859 int
1860 TIFFInitJPEG(TIFF* tif, int scheme)
1861 {
1862 JPEGState* sp;
1863
1864 assert(scheme == COMPRESSION_JPEG);
1865
1866 /*
1867 * Allocate state block so tag methods have storage to record values.
1868 */
1869 tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (JPEGState));
1870
1871 if (tif->tif_data == NULL) {
1872 TIFFErrorExt(tif->tif_clientdata, "TIFFInitJPEG", "No space for JPEG state block");
1873 return (0);
1874 }
1875 _TIFFmemset( tif->tif_data, 0, sizeof(JPEGState));
1876
1877 sp = JState(tif);
1878 sp->tif = tif; /* back link */
1879
1880 /*
1881 * Merge codec-specific tag information and override parent get/set
1882 * field methods.
1883 */
1884 _TIFFMergeFieldInfo(tif, jpegFieldInfo, N(jpegFieldInfo));
1885 sp->vgetparent = tif->tif_tagmethods.vgetfield;
1886 tif->tif_tagmethods.vgetfield = JPEGVGetField; /* hook for codec tags */
1887 sp->vsetparent = tif->tif_tagmethods.vsetfield;
1888 tif->tif_tagmethods.vsetfield = JPEGVSetField; /* hook for codec tags */
1889 tif->tif_tagmethods.printdir = JPEGPrintDir; /* hook for codec tags */
1890
1891 /* Default values for codec-specific fields */
1892 sp->jpegtables = NULL;
1893 sp->jpegtables_length = 0;
1894 sp->jpegquality = 75; /* Default IJG quality */
1895 sp->jpegcolormode = JPEGCOLORMODE_RAW;
1896 sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
1897
1898 sp->recvparams = 0;
1899 sp->subaddress = NULL;
1900 sp->faxdcs = NULL;
1901
1902 sp->ycbcrsampling_fetched = 0;
1903
1904 /*
1905 * Install codec methods.
1906 */
1907 tif->tif_setupdecode = JPEGSetupDecode;
1908 tif->tif_predecode = JPEGPreDecode;
1909 tif->tif_decoderow = JPEGDecode;
1910 tif->tif_decodestrip = JPEGDecode;
1911 tif->tif_decodetile = JPEGDecode;
1912 tif->tif_setupencode = JPEGSetupEncode;
1913 tif->tif_preencode = JPEGPreEncode;
1914 tif->tif_postencode = JPEGPostEncode;
1915 tif->tif_encoderow = JPEGEncode;
1916 tif->tif_encodestrip = JPEGEncode;
1917 tif->tif_encodetile = JPEGEncode;
1918 tif->tif_cleanup = JPEGCleanup;
1919 sp->defsparent = tif->tif_defstripsize;
1920 tif->tif_defstripsize = JPEGDefaultStripSize;
1921 sp->deftparent = tif->tif_deftilesize;
1922 tif->tif_deftilesize = JPEGDefaultTileSize;
1923 tif->tif_flags |= TIFF_NOBITREV; /* no bit reversal, please */
1924
1925 sp->cinfo_initialized = FALSE;
1926
1927 /*
1928 ** Create a JPEGTables field if no directory has yet been created.
1929 ** We do this just to ensure that sufficient space is reserved for
1930 ** the JPEGTables field. It will be properly created the right
1931 ** size later.
1932 */
1933 if( tif->tif_diroff == 0 )
1934 {
1935 #define SIZE_OF_JPEGTABLES 2000
1936 TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1937 sp->jpegtables_length = SIZE_OF_JPEGTABLES;
1938 sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
1939 _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
1940 #undef SIZE_OF_JPEGTABLES
1941 }
1942
1943 /*
1944 * Mark the TIFFTAG_YCBCRSAMPLES as present even if it is not
1945 * see: JPEGFixupTestSubsampling().
1946 */
1947 TIFFSetFieldBit( tif, FIELD_YCBCRSUBSAMPLING );
1948
1949 return 1;
1950 }
1951 #endif /* JPEG_SUPPORT */
1952
1953 /* vim: set ts=8 sts=8 sw=8 noet: */