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