~ubuntu-branches/ubuntu/karmic/tiff/karmic-security

« back to all changes in this revision

Viewing changes to libtiff/tif_jpeg.c

  • Committer: Bazaar Package Importer
  • Author(s): Jay Berkenbilt
  • Date: 2008-08-17 11:56:01 UTC
  • mfrom: (2.1.6 gutsy)
  • Revision ID: james.westby@ubuntu.com-20080817115601-z9wls4z4dzk3nizw
Tags: 3.8.2-7+etch1
Apply patches from Drew Yao of Apple Product Security to fix
CVE-2008-2327, a potential buffer underflow in the LZW decoder
(tif_lzw.c).

Show diffs side-by-side

added added

removed removed

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