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