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