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