~ubuntu-branches/ubuntu/trusty/tiff/trusty

« back to all changes in this revision

Viewing changes to libtiff/tif_jpeg.c

  • Committer: Package Import Robot
  • Author(s): Jay Berkenbilt
  • Date: 2012-06-24 13:45:42 UTC
  • mfrom: (15.1.14 sid)
  • Revision ID: package-import@ubuntu.com-20120624134542-u7dltcqwnb6orprf
Tags: 4.0.2-1
New upstream release

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* $Id: tif_jpeg.c,v 1.50.2.17 2011-01-04 02:51:17 faxguy Exp $ */
 
1
/* $Id: tif_jpeg.c,v 1.108 2012-06-05 03:24:30 fwarmerdam Exp $ */
2
2
 
3
3
/*
4
4
 * Copyright (c) 1994-1997 Sam Leffler
44
44
 */
45
45
#include <setjmp.h>
46
46
 
47
 
int TIFFFillStrip(TIFF*, tstrip_t);
48
 
int TIFFFillTile(TIFF*, ttile_t);
 
47
int TIFFFillStrip(TIFF* tif, uint32 strip);
 
48
int TIFFFillTile(TIFF* tif, uint32 tile);
 
49
int TIFFReInitJPEG_12( TIFF *tif, int scheme, int is_encode );
49
50
 
50
51
/* We undefine FAR to avoid conflict with JPEG definition */
51
52
 
77
78
*/
78
79
 
79
80
/* Define "boolean" as unsigned char, not int, per Windows custom. */
80
 
#if defined(WIN32) && !defined(__MINGW32__)
 
81
#if defined(__WIN32__) && !defined(__MINGW32__)
81
82
# ifndef __RPCNDR_H__            /* don't conflict if rpcndr.h already read */
82
83
   typedef unsigned char boolean;
83
84
# endif
87
88
#include "jpeglib.h"
88
89
#include "jerror.h"
89
90
 
 
91
/* 
 
92
 * Do we want to do special processing suitable for when JSAMPLE is a
 
93
 * 16bit value?  
 
94
 */
 
95
 
 
96
#if defined(JPEG_LIB_MK1)
 
97
#  define JPEG_LIB_MK1_OR_12BIT 1
 
98
#elif BITS_IN_JSAMPLE == 12
 
99
#  define JPEG_LIB_MK1_OR_12BIT 1
 
100
#endif
 
101
 
90
102
/*
91
103
 * We are using width_in_blocks which is supposed to be private to
92
104
 * libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
108
120
 
109
121
typedef struct jpeg_destination_mgr jpeg_destination_mgr;
110
122
typedef struct jpeg_source_mgr jpeg_source_mgr;
111
 
typedef struct jpeg_error_mgr jpeg_error_mgr;
 
123
typedef struct jpeg_error_mgr jpeg_error_mgr;
112
124
 
113
125
/*
114
126
 * State block for each open TIFF file using
123
135
 *     so we can safely cast JPEGState* -> jpeg_xxx_struct*
124
136
 *     and vice versa!
125
137
 */
126
 
typedef struct {
 
138
typedef struct {
127
139
        union {
128
140
                struct jpeg_compress_struct c;
129
141
                struct jpeg_decompress_struct d;
130
142
                struct jpeg_common_struct comm;
131
143
        } cinfo;                        /* NB: must be first */
132
 
        int             cinfo_initialized;
 
144
        int             cinfo_initialized;
133
145
 
134
146
        jpeg_error_mgr  err;            /* libjpeg error manager */
135
147
        JMP_BUF         exit_jmpbuf;    /* for catching libjpeg failures */
144
156
        uint16          photometric;    /* copy of PhotometricInterpretation */
145
157
        uint16          h_sampling;     /* luminance sampling factors */
146
158
        uint16          v_sampling;
147
 
        tsize_t         bytesperline;   /* decompressed bytes per scanline */
 
159
        tmsize_t        bytesperline;   /* decompressed bytes per scanline */
148
160
        /* pointers to intermediate buffers when processing downsampled data */
149
161
        JSAMPARRAY      ds_buffer[MAX_COMPONENTS];
150
162
        int             scancount;      /* number of "scanlines" accumulated */
163
175
        int             jpegtablesmode; /* What to put in JPEGTables */
164
176
 
165
177
        int             ycbcrsampling_fetched;
166
 
        uint32          recvparams;     /* encoded Class 2 session params */
167
 
        char*           subaddress;     /* subaddress string */
168
 
        uint32          recvtime;       /* time spent receiving (secs) */
169
 
        char*           faxdcs;         /* encoded fax parameters (DCS, Table 2/T.30) */
170
178
} JPEGState;
171
179
 
172
180
#define JState(tif)     ((JPEGState*)(tif)->tif_data)
173
181
 
174
 
static  int JPEGDecode(TIFF*, tidata_t, tsize_t, tsample_t);
175
 
static  int JPEGDecodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
176
 
static  int JPEGEncode(TIFF*, tidata_t, tsize_t, tsample_t);
177
 
static  int JPEGEncodeRaw(TIFF*, tidata_t, tsize_t, tsample_t);
178
 
static  int JPEGInitializeLibJPEG( TIFF * tif,
179
 
                                                                   int force_encode, int force_decode );
 
182
static int JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
 
183
static int JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
 
184
static int JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
 
185
static int JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
 
186
static int JPEGInitializeLibJPEG(TIFF * tif, int decode );
 
187
static int DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
180
188
 
181
189
#define FIELD_JPEGTABLES        (FIELD_CODEC+0)
182
 
#define FIELD_RECVPARAMS        (FIELD_CODEC+1)
183
 
#define FIELD_SUBADDRESS        (FIELD_CODEC+2)
184
 
#define FIELD_RECVTIME          (FIELD_CODEC+3)
185
 
#define FIELD_FAXDCS            (FIELD_CODEC+4)
186
190
 
187
 
static const TIFFFieldInfo jpegFieldInfo[] = {
188
 
    { TIFFTAG_JPEGTABLES,        -3,-3, TIFF_UNDEFINED, FIELD_JPEGTABLES,
189
 
      FALSE,    TRUE,   "JPEGTables" },
190
 
    { TIFFTAG_JPEGQUALITY,       0, 0,  TIFF_ANY,       FIELD_PSEUDO,
191
 
      TRUE,     FALSE,  "" },
192
 
    { TIFFTAG_JPEGCOLORMODE,     0, 0,  TIFF_ANY,       FIELD_PSEUDO,
193
 
      FALSE,    FALSE,  "" },
194
 
    { TIFFTAG_JPEGTABLESMODE,    0, 0,  TIFF_ANY,       FIELD_PSEUDO,
195
 
      FALSE,    FALSE,  "" },
196
 
    /* Specific for JPEG in faxes */
197
 
    { TIFFTAG_FAXRECVPARAMS,     1, 1, TIFF_LONG,       FIELD_RECVPARAMS,
198
 
      TRUE,     FALSE,  "FaxRecvParams" },
199
 
    { TIFFTAG_FAXSUBADDRESS,    -1,-1, TIFF_ASCII,      FIELD_SUBADDRESS,
200
 
      TRUE,     FALSE,  "FaxSubAddress" },
201
 
    { TIFFTAG_FAXRECVTIME,       1, 1, TIFF_LONG,       FIELD_RECVTIME,
202
 
      TRUE,     FALSE,  "FaxRecvTime" },
203
 
    { TIFFTAG_FAXDCS,           -1, -1, TIFF_ASCII,     FIELD_FAXDCS,
204
 
          TRUE, FALSE,  "FaxDcs" },
 
191
static const TIFFField jpegFields[] = {
 
192
    { TIFFTAG_JPEGTABLES, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_C32_UINT8, FIELD_JPEGTABLES, FALSE, TRUE, "JPEGTables", NULL },
 
193
    { TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "", NULL },
 
194
    { TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL },
 
195
    { TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL }
205
196
};
206
 
#define N(a)    (sizeof (a) / sizeof (a[0]))
207
197
 
208
198
/*
209
199
 * libjpeg interface layer.
411
401
 
412
402
        /* the entire buffer has been filled */
413
403
        tif->tif_rawcc = tif->tif_rawdatasize;
 
404
 
 
405
#ifdef IPPJ_HUFF
 
406
       /*
 
407
        * The Intel IPP performance library does not necessarily fill up
 
408
        * the whole output buffer on each pass, so only dump out the parts
 
409
        * that have been filled.
 
410
        *   http://trac.osgeo.org/gdal/wiki/JpegIPP
 
411
        */
 
412
       if ( sp->dest.free_in_buffer >= 0 ) {
 
413
               tif->tif_rawcc = tif->tif_rawdatasize - sp->dest.free_in_buffer;
 
414
       }
 
415
#endif
 
416
 
414
417
        TIFFFlushData1(tif);
415
418
        sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
416
419
        sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
424
427
        JPEGState* sp = (JPEGState*) cinfo;
425
428
        TIFF* tif = sp->tif;
426
429
 
427
 
        tif->tif_rawcp = (tidata_t) sp->dest.next_output_byte;
 
430
        tif->tif_rawcp = (uint8*) sp->dest.next_output_byte;
428
431
        tif->tif_rawcc =
429
 
            tif->tif_rawdatasize - (tsize_t) sp->dest.free_in_buffer;
 
432
            tif->tif_rawdatasize - (tmsize_t) sp->dest.free_in_buffer;
430
433
        /* NB: libtiff does the final buffer flush */
431
434
}
432
435
 
461
464
        void* newbuf;
462
465
 
463
466
        /* the entire buffer has been filled; enlarge it by 1000 bytes */
464
 
        newbuf = _TIFFrealloc((tdata_t) sp->jpegtables,
465
 
                              (tsize_t) (sp->jpegtables_length + 1000));
 
467
        newbuf = _TIFFrealloc((void*) sp->jpegtables,
 
468
                              (tmsize_t) (sp->jpegtables_length + 1000));
466
469
        if (newbuf == NULL)
467
470
                ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
468
471
        sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
478
481
        JPEGState* sp = (JPEGState*) cinfo;
479
482
 
480
483
        /* set tables length to number of bytes actually emitted */
481
 
        sp->jpegtables_length -= sp->dest.free_in_buffer;
 
484
        sp->jpegtables_length -= (uint32) sp->dest.free_in_buffer;
482
485
}
483
486
 
484
487
static int
492
495
        if (sp->jpegtables)
493
496
                _TIFFfree(sp->jpegtables);
494
497
        sp->jpegtables_length = 1000;
495
 
        sp->jpegtables = (void*) _TIFFmalloc((tsize_t) sp->jpegtables_length);
 
498
        sp->jpegtables = (void*) _TIFFmalloc((tmsize_t) sp->jpegtables_length);
496
499
        if (sp->jpegtables == NULL) {
497
500
                sp->jpegtables_length = 0;
498
501
                TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
526
529
        JPEGState* sp = (JPEGState* ) cinfo;
527
530
        static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
528
531
 
 
532
#ifdef IPPJ_HUFF
 
533
        /*
 
534
         * The Intel IPP performance library does not necessarily read the whole
 
535
         * input buffer in one pass, so it is possible to get here with data
 
536
         * yet to read. 
 
537
         * 
 
538
         * We just return without doing anything, until the entire buffer has
 
539
         * been read.  
 
540
         * http://trac.osgeo.org/gdal/wiki/JpegIPP
 
541
         */
 
542
        if( sp->src.bytes_in_buffer > 0 ) {
 
543
            return (TRUE);
 
544
        }
 
545
#endif
 
546
 
529
547
        /*
530
 
         * Should never get here since entire strip/tile is
531
 
         * read into memory before the decompressor is called,
532
 
         * and thus was supplied by init_source.
 
548
         * Normally the whole strip/tile is read and so we don't need to do
 
549
         * a fill.  In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
 
550
         * all the data, but the rawdata is refreshed between scanlines and
 
551
         * we push this into the io machinery in JPEGDecode().   
 
552
         * http://trac.osgeo.org/gdal/ticket/3894
533
553
         */
 
554
        
534
555
        WARNMS(cinfo, JWRN_JPEG_EOF);
535
556
        /* insert a fake EOI marker */
536
557
        sp->src.next_input_byte = dummy_EOI;
544
565
        JPEGState* sp = (JPEGState*) cinfo;
545
566
 
546
567
        if (num_bytes > 0) {
547
 
                if (num_bytes > (long) sp->src.bytes_in_buffer) {
 
568
                if ((size_t)num_bytes > sp->src.bytes_in_buffer) {
548
569
                        /* oops, buffer overrun */
549
570
                        (void) std_fill_input_buffer(cinfo);
550
571
                } else {
558
579
std_term_source(j_decompress_ptr cinfo)
559
580
{
560
581
        /* No work necessary here */
561
 
        /* Or must we update tif->tif_rawcp, tif->tif_rawcc ??? */
562
 
        /* (if so, need empty tables_term_source!) */
563
582
        (void) cinfo;
564
583
}
565
584
 
635
654
 * JPEG Decoding.
636
655
 */
637
656
 
 
657
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
 
658
 
 
659
#define JPEG_MARKER_SOF0 0xC0
 
660
#define JPEG_MARKER_SOF1 0xC1
 
661
#define JPEG_MARKER_SOF3 0xC3
 
662
#define JPEG_MARKER_DHT 0xC4
 
663
#define JPEG_MARKER_SOI 0xD8
 
664
#define JPEG_MARKER_SOS 0xDA
 
665
#define JPEG_MARKER_DQT 0xDB
 
666
#define JPEG_MARKER_DRI 0xDD
 
667
#define JPEG_MARKER_APP0 0xE0
 
668
#define JPEG_MARKER_COM 0xFE
 
669
struct JPEGFixupTagsSubsamplingData
 
670
{
 
671
        TIFF* tif;
 
672
        void* buffer;
 
673
        uint32 buffersize;
 
674
        uint8* buffercurrentbyte;
 
675
        uint32 bufferbytesleft;
 
676
        uint64 fileoffset;
 
677
        uint64 filebytesleft;
 
678
        uint8 filepositioned;
 
679
};
 
680
static void JPEGFixupTagsSubsampling(TIFF* tif);
 
681
static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data);
 
682
static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result);
 
683
static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result);
 
684
static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength);
 
685
 
 
686
#endif
 
687
 
 
688
static int
 
689
JPEGFixupTags(TIFF* tif)
 
690
{
 
691
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
 
692
        if ((tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR)&&
 
693
            (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&&
 
694
            (tif->tif_dir.td_samplesperpixel==3))
 
695
                JPEGFixupTagsSubsampling(tif);
 
696
#endif
 
697
        
 
698
        return(1);
 
699
}
 
700
 
 
701
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
 
702
 
 
703
static void
 
704
JPEGFixupTagsSubsampling(TIFF* tif)
 
705
{
 
706
        /*
 
707
         * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
 
708
         * the TIFF tags, but still use non-default (2,2) values within the jpeg
 
709
         * data stream itself.  In order for TIFF applications to work properly
 
710
         * - for instance to get the strip buffer size right - it is imperative
 
711
         * that the subsampling be available before we start reading the image
 
712
         * data normally.  This function will attempt to analyze the first strip in
 
713
         * order to get the sampling values from the jpeg data stream.
 
714
         *
 
715
         * Note that JPEGPreDeocode() will produce a fairly loud warning when the
 
716
         * discovered sampling does not match the default sampling (2,2) or whatever
 
717
         * was actually in the tiff tags.
 
718
         *
 
719
         * See the bug in bugzilla for details:
 
720
         *
 
721
         * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
 
722
         *
 
723
         * Frank Warmerdam, July 2002
 
724
         * Joris Van Damme, May 2007
 
725
         */
 
726
        static const char module[] = "JPEGFixupTagsSubsampling";
 
727
        struct JPEGFixupTagsSubsamplingData m;
 
728
 
 
729
        _TIFFFillStriles( tif );
 
730
        
 
731
        if( tif->tif_dir.td_stripbytecount == NULL
 
732
            || tif->tif_dir.td_stripbytecount[0] == 0 )
 
733
        {
 
734
            /* Do not even try to check if the first strip/tile does not
 
735
               yet exist, as occurs when GDAL has created a new NULL file
 
736
               for instance. */
 
737
            return;
 
738
        }
 
739
 
 
740
        m.tif=tif;
 
741
        m.buffersize=2048;
 
742
        m.buffer=_TIFFmalloc(m.buffersize);
 
743
        if (m.buffer==NULL)
 
744
        {
 
745
                TIFFWarningExt(tif->tif_clientdata,module,
 
746
                    "Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
 
747
                return;
 
748
        }
 
749
        m.buffercurrentbyte=NULL;
 
750
        m.bufferbytesleft=0;
 
751
        m.fileoffset=tif->tif_dir.td_stripoffset[0];
 
752
        m.filepositioned=0;
 
753
        m.filebytesleft=tif->tif_dir.td_stripbytecount[0];
 
754
        if (!JPEGFixupTagsSubsamplingSec(&m))
 
755
                TIFFWarningExt(tif->tif_clientdata,module,
 
756
                    "Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
 
757
        _TIFFfree(m.buffer);
 
758
}
 
759
 
 
760
static int
 
761
JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
 
762
{
 
763
        static const char module[] = "JPEGFixupTagsSubsamplingSec";
 
764
        uint8 m;
 
765
        while (1)
 
766
        {
 
767
                while (1)
 
768
                {
 
769
                        if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
 
770
                                return(0);
 
771
                        if (m==255)
 
772
                                break;
 
773
                }
 
774
                while (1)
 
775
                {
 
776
                        if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
 
777
                                return(0);
 
778
                        if (m!=255)
 
779
                                break;
 
780
                }
 
781
                switch (m)
 
782
                {
 
783
                        case JPEG_MARKER_SOI:
 
784
                                /* this type of marker has no data and should be skipped */
 
785
                                break;
 
786
                        case JPEG_MARKER_COM:
 
787
                        case JPEG_MARKER_APP0:
 
788
                        case JPEG_MARKER_APP0+1:
 
789
                        case JPEG_MARKER_APP0+2:
 
790
                        case JPEG_MARKER_APP0+3:
 
791
                        case JPEG_MARKER_APP0+4:
 
792
                        case JPEG_MARKER_APP0+5:
 
793
                        case JPEG_MARKER_APP0+6:
 
794
                        case JPEG_MARKER_APP0+7:
 
795
                        case JPEG_MARKER_APP0+8:
 
796
                        case JPEG_MARKER_APP0+9:
 
797
                        case JPEG_MARKER_APP0+10:
 
798
                        case JPEG_MARKER_APP0+11:
 
799
                        case JPEG_MARKER_APP0+12:
 
800
                        case JPEG_MARKER_APP0+13:
 
801
                        case JPEG_MARKER_APP0+14:
 
802
                        case JPEG_MARKER_APP0+15:
 
803
                        case JPEG_MARKER_DQT:
 
804
                        case JPEG_MARKER_SOS:
 
805
                        case JPEG_MARKER_DHT:
 
806
                        case JPEG_MARKER_DRI:
 
807
                                /* this type of marker has data, but it has no use to us and should be skipped */
 
808
                                {
 
809
                                        uint16 n;
 
810
                                        if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
 
811
                                                return(0);
 
812
                                        if (n<2)
 
813
                                                return(0);
 
814
                                        n-=2;
 
815
                                        if (n>0)
 
816
                                                JPEGFixupTagsSubsamplingSkip(data,n);
 
817
                                }
 
818
                                break;
 
819
                        case JPEG_MARKER_SOF0:
 
820
                        case JPEG_MARKER_SOF1:
 
821
                                /* this marker contains the subsampling factors we're scanning for */
 
822
                                {
 
823
                                        uint16 n;
 
824
                                        uint16 o;
 
825
                                        uint8 p;
 
826
                                        uint8 ph,pv;
 
827
                                        if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
 
828
                                                return(0);
 
829
                                        if (n!=8+data->tif->tif_dir.td_samplesperpixel*3)
 
830
                                                return(0);
 
831
                                        JPEGFixupTagsSubsamplingSkip(data,7);
 
832
                                        if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
 
833
                                                return(0);
 
834
                                        ph=(p>>4);
 
835
                                        pv=(p&15);
 
836
                                        JPEGFixupTagsSubsamplingSkip(data,1);
 
837
                                        for (o=1; o<data->tif->tif_dir.td_samplesperpixel; o++)
 
838
                                        {
 
839
                                                JPEGFixupTagsSubsamplingSkip(data,1);
 
840
                                                if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
 
841
                                                        return(0);
 
842
                                                if (p!=0x11)
 
843
                                                {
 
844
                                                        TIFFWarningExt(data->tif->tif_clientdata,module,
 
845
                                                            "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
 
846
                                                        return(1);
 
847
                                                }
 
848
                                                JPEGFixupTagsSubsamplingSkip(data,1);
 
849
                                        }
 
850
                                        if (((ph!=1)&&(ph!=2)&&(ph!=4))||((pv!=1)&&(pv!=2)&&(pv!=4)))
 
851
                                        {
 
852
                                                TIFFWarningExt(data->tif->tif_clientdata,module,
 
853
                                                    "Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
 
854
                                                return(1);
 
855
                                        }
 
856
                                        if ((ph!=data->tif->tif_dir.td_ycbcrsubsampling[0])||(pv!=data->tif->tif_dir.td_ycbcrsubsampling[1]))
 
857
                                        {
 
858
                                                TIFFWarningExt(data->tif->tif_clientdata,module,
 
859
                                                    "Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
 
860
                                                    (int)data->tif->tif_dir.td_ycbcrsubsampling[0],
 
861
                                                    (int)data->tif->tif_dir.td_ycbcrsubsampling[1],
 
862
                                                    (int)ph,(int)pv);
 
863
                                                data->tif->tif_dir.td_ycbcrsubsampling[0]=ph;
 
864
                                                data->tif->tif_dir.td_ycbcrsubsampling[1]=pv;
 
865
                                        }
 
866
                                }
 
867
                                return(1);
 
868
                        default:
 
869
                                return(0);
 
870
                }
 
871
        }
 
872
}
 
873
 
 
874
static int
 
875
JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result)
 
876
{
 
877
        if (data->bufferbytesleft==0)
 
878
        {
 
879
                uint32 m;
 
880
                if (data->filebytesleft==0)
 
881
                        return(0);
 
882
                if (!data->filepositioned)
 
883
                {
 
884
                        TIFFSeekFile(data->tif,data->fileoffset,SEEK_SET);
 
885
                        data->filepositioned=1;
 
886
                }
 
887
                m=data->buffersize;
 
888
                if ((uint64)m>data->filebytesleft)
 
889
                        m=(uint32)data->filebytesleft;
 
890
                assert(m<0x80000000UL);
 
891
                if (TIFFReadFile(data->tif,data->buffer,(tmsize_t)m)!=(tmsize_t)m)
 
892
                        return(0);
 
893
                data->buffercurrentbyte=data->buffer;
 
894
                data->bufferbytesleft=m;
 
895
                data->fileoffset+=m;
 
896
                data->filebytesleft-=m;
 
897
        }
 
898
        *result=*data->buffercurrentbyte;
 
899
        data->buffercurrentbyte++;
 
900
        data->bufferbytesleft--;
 
901
        return(1);
 
902
}
 
903
 
 
904
static int
 
905
JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result)
 
906
{
 
907
        uint8 ma;
 
908
        uint8 mb;
 
909
        if (!JPEGFixupTagsSubsamplingReadByte(data,&ma))
 
910
                return(0);
 
911
        if (!JPEGFixupTagsSubsamplingReadByte(data,&mb))
 
912
                return(0);
 
913
        *result=(ma<<8)|mb;
 
914
        return(1);
 
915
}
 
916
 
 
917
static void
 
918
JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength)
 
919
{
 
920
        if ((uint32)skiplength<=data->bufferbytesleft)
 
921
        {
 
922
                data->buffercurrentbyte+=skiplength;
 
923
                data->bufferbytesleft-=skiplength;
 
924
        }
 
925
        else
 
926
        {
 
927
                uint16 m;
 
928
                m=skiplength-data->bufferbytesleft;
 
929
                if (m<=data->filebytesleft)
 
930
                {
 
931
                        data->bufferbytesleft=0;
 
932
                        data->fileoffset+=m;
 
933
                        data->filebytesleft-=m;
 
934
                        data->filepositioned=0;
 
935
                }
 
936
                else
 
937
                {
 
938
                        data->bufferbytesleft=0;
 
939
                        data->filebytesleft=0;
 
940
                }
 
941
        }
 
942
}
 
943
 
 
944
#endif
 
945
 
 
946
 
638
947
static int
639
948
JPEGSetupDecode(TIFF* tif)
640
949
{
641
950
        JPEGState* sp = JState(tif);
642
951
        TIFFDirectory *td = &tif->tif_dir;
643
952
 
644
 
        JPEGInitializeLibJPEG( tif, 0, 1 );
 
953
#if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
 
954
        if( tif->tif_dir.td_bitspersample == 12 )
 
955
            return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 0 );
 
956
#endif
 
957
 
 
958
        JPEGInitializeLibJPEG( tif, TRUE );
645
959
 
646
960
        assert(sp != NULL);
647
961
        assert(sp->cinfo.comm.is_decompressor);
679
993
 * Set up for decoding a strip or tile.
680
994
 */
681
995
static int
682
 
JPEGPreDecode(TIFF* tif, tsample_t s)
 
996
JPEGPreDecode(TIFF* tif, uint16 s)
683
997
{
684
998
        JPEGState *sp = JState(tif);
685
999
        TIFFDirectory *td = &tif->tif_dir;
689
1003
        int ci;
690
1004
 
691
1005
        assert(sp != NULL);
 
1006
  
 
1007
        if (sp->cinfo.comm.is_decompressor == 0)
 
1008
        {
 
1009
                tif->tif_setupdecode( tif );
 
1010
        }
 
1011
  
692
1012
        assert(sp->cinfo.comm.is_decompressor);
693
1013
        /*
694
1014
         * Reset decoder state from any previous strip/tile,
699
1019
        /*
700
1020
         * Read the header for this strip/tile.
701
1021
         */
 
1022
        
702
1023
        if (TIFFjpeg_read_header(sp, TRUE) != JPEG_HEADER_OK)
703
1024
                return (0);
 
1025
 
 
1026
        tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
 
1027
        tif->tif_rawcc = sp->src.bytes_in_buffer;
 
1028
 
704
1029
        /*
705
1030
         * Check image parameters and set decompression parameters.
706
1031
         */
713
1038
        } else {
714
1039
                if (segment_height > td->td_rowsperstrip)
715
1040
                        segment_height = td->td_rowsperstrip;
716
 
                sp->bytesperline = TIFFOldScanlineSize(tif);
 
1041
                sp->bytesperline = TIFFScanlineSize(tif);
717
1042
        }
718
1043
        if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
719
1044
                /*
720
1045
                 * For PC 2, scale down the expected strip/tile size
721
1046
                 * to match a downsampled component
722
1047
                 */
723
 
                segment_width = TIFFhowmany(segment_width, sp->h_sampling);
724
 
                segment_height = TIFFhowmany(segment_height, sp->v_sampling);
 
1048
                segment_width = TIFFhowmany_32(segment_width, sp->h_sampling);
 
1049
                segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
725
1050
        }
726
1051
        if (sp->cinfo.d.image_width < segment_width ||
727
1052
            sp->cinfo.d.image_height < segment_height) {
755
1080
        }
756
1081
#ifdef JPEG_LIB_MK1
757
1082
        if (12 != td->td_bitspersample && 8 != td->td_bitspersample) {
758
 
                        TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
759
 
            return (0);
 
1083
                TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
 
1084
                return (0);
760
1085
        }
761
 
        sp->cinfo.d.data_precision = td->td_bitspersample;
762
 
        sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
 
1086
        sp->cinfo.d.data_precision = td->td_bitspersample;
 
1087
        sp->cinfo.d.bits_in_jsample = td->td_bitspersample;
763
1088
#else
764
1089
        if (sp->cinfo.d.data_precision != td->td_bitspersample) {
765
 
                        TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
766
 
            return (0);
 
1090
                TIFFErrorExt(tif->tif_clientdata, module, "Improper JPEG data precision");
 
1091
                return (0);
767
1092
        }
768
1093
#endif
769
1094
        if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
770
1095
                /* Component 0 should have expected sampling factors */
771
1096
                if (sp->cinfo.d.comp_info[0].h_samp_factor != sp->h_sampling ||
772
1097
                    sp->cinfo.d.comp_info[0].v_samp_factor != sp->v_sampling) {
773
 
                                TIFFWarningExt(tif->tif_clientdata, module,
774
 
                                    "Improper JPEG sampling factors %d,%d\n"
775
 
                                    "Apparently should be %d,%d.",
776
 
                                    sp->cinfo.d.comp_info[0].h_samp_factor,
777
 
                                    sp->cinfo.d.comp_info[0].v_samp_factor,
778
 
                                    sp->h_sampling, sp->v_sampling);
779
 
 
780
 
                                /*
781
 
                                 * There are potential security issues here
782
 
                                 * for decoders that have already allocated
783
 
                                 * buffers based on the expected sampling
784
 
                                 * factors. Lets check the sampling factors
785
 
                                 * dont exceed what we were expecting.
786
 
                                 */
787
 
                                if (sp->cinfo.d.comp_info[0].h_samp_factor
788
 
                                        > sp->h_sampling
789
 
                                    || sp->cinfo.d.comp_info[0].v_samp_factor
790
 
                                        > sp->v_sampling) {
791
 
                                        TIFFErrorExt(tif->tif_clientdata,
792
 
                                                     module,
793
 
                                        "Cannot honour JPEG sampling factors"
794
 
                                        " that exceed those specified.");
795
 
                                        return (0);
796
 
                                }
797
 
 
798
 
                            /*
799
 
                             * XXX: Files written by the Intergraph software
800
 
                             * has different sampling factors stored in the
801
 
                             * TIFF tags and in the JPEG structures. We will
802
 
                             * try to deduce Intergraph files by the presense
803
 
                             * of the tag 33918.
804
 
                             */
805
 
                            if (!_TIFFFindFieldInfo(tif, 33918, TIFF_ANY)) {
806
 
                                        TIFFWarningExt(tif->tif_clientdata, module,
807
 
                                        "Decompressor will try reading with "
808
 
                                        "sampling %d,%d.",
809
 
                                        sp->cinfo.d.comp_info[0].h_samp_factor,
810
 
                                        sp->cinfo.d.comp_info[0].v_samp_factor);
811
 
 
812
 
                                    sp->h_sampling = (uint16)
813
 
                                        sp->cinfo.d.comp_info[0].h_samp_factor;
814
 
                                    sp->v_sampling = (uint16)
815
 
                                        sp->cinfo.d.comp_info[0].v_samp_factor;
816
 
                            }
 
1098
                        TIFFErrorExt(tif->tif_clientdata, module,
 
1099
                                       "Improper JPEG sampling factors %d,%d\n"
 
1100
                                       "Apparently should be %d,%d.",
 
1101
                                       sp->cinfo.d.comp_info[0].h_samp_factor,
 
1102
                                       sp->cinfo.d.comp_info[0].v_samp_factor,
 
1103
                                       sp->h_sampling, sp->v_sampling);
 
1104
                        return (0);
817
1105
                }
818
1106
                /* Rest should have sampling factors 1,1 */
819
1107
                for (ci = 1; ci < sp->cinfo.d.num_components; ci++) {
835
1123
        if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
836
1124
            sp->photometric == PHOTOMETRIC_YCBCR &&
837
1125
            sp->jpegcolormode == JPEGCOLORMODE_RGB) {
838
 
        /* Convert YCbCr to RGB */
 
1126
                /* Convert YCbCr to RGB */
839
1127
                sp->cinfo.d.jpeg_color_space = JCS_YCbCr;
840
1128
                sp->cinfo.d.out_color_space = JCS_RGB;
841
1129
        } else {
842
 
                        /* Suppress colorspace handling */
 
1130
                /* Suppress colorspace handling */
843
1131
                sp->cinfo.d.jpeg_color_space = JCS_UNKNOWN;
844
1132
                sp->cinfo.d.out_color_space = JCS_UNKNOWN;
845
1133
                if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
850
1138
        if (downsampled_output) {
851
1139
                /* Need to use raw-data interface to libjpeg */
852
1140
                sp->cinfo.d.raw_data_out = TRUE;
853
 
                tif->tif_decoderow = JPEGDecodeRaw;
 
1141
                tif->tif_decoderow = DecodeRowError;
854
1142
                tif->tif_decodestrip = JPEGDecodeRaw;
855
1143
                tif->tif_decodetile = JPEGDecodeRaw;
856
1144
        } else {
858
1146
                sp->cinfo.d.raw_data_out = FALSE;
859
1147
                tif->tif_decoderow = JPEGDecode;
860
1148
                tif->tif_decodestrip = JPEGDecode;
861
 
                tif->tif_decodetile = JPEGDecode;
 
1149
                tif->tif_decodetile = JPEGDecode;  
862
1150
        }
863
1151
        /* Start JPEG decompressor */
864
1152
        if (!TIFFjpeg_start_decompress(sp))
878
1166
 * "Standard" case: returned data is not downsampled.
879
1167
 */
880
1168
/*ARGSUSED*/ static int
881
 
JPEGDecode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
882
 
{
883
 
    JPEGState *sp = JState(tif);
884
 
    tsize_t nrows;
 
1169
JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
 
1170
{
 
1171
        JPEGState *sp = JState(tif);
 
1172
        tmsize_t nrows;
 
1173
        (void) s;
 
1174
 
 
1175
        /*
 
1176
        ** Update available information, buffer may have been refilled
 
1177
        ** between decode requests
 
1178
        */
 
1179
        sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
 
1180
        sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
 
1181
 
 
1182
        if( sp->bytesperline == 0 )
 
1183
                return 0;
 
1184
        
 
1185
        nrows = cc / sp->bytesperline;
 
1186
        if (cc % sp->bytesperline)
 
1187
                TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
 
1188
 
 
1189
        if( nrows > (tmsize_t) sp->cinfo.d.image_height )
 
1190
                nrows = sp->cinfo.d.image_height;
 
1191
 
 
1192
        /* data is expected to be read in multiples of a scanline */
 
1193
        if (nrows)
 
1194
        {
 
1195
                JSAMPROW line_work_buf = NULL;
 
1196
 
 
1197
                /*
 
1198
                 * For 6B, only use temporary buffer for 12 bit imagery.
 
1199
                 * For Mk1 always use it.
 
1200
                 */
 
1201
#if !defined(JPEG_LIB_MK1)
 
1202
                if( sp->cinfo.d.data_precision == 12 )
 
1203
#endif
 
1204
                {
 
1205
                        line_work_buf = (JSAMPROW)
 
1206
                            _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
 
1207
                            * sp->cinfo.d.num_components );
 
1208
                }
 
1209
 
 
1210
                do {
 
1211
                        if( line_work_buf != NULL )
 
1212
                        {
 
1213
                                /*
 
1214
                                 * In the MK1 case, we aways read into a 16bit buffer, and then
 
1215
                                 * pack down to 12bit or 8bit.  In 6B case we only read into 16
 
1216
                                 * bit buffer for 12bit data, which we need to repack.
 
1217
                                */
 
1218
                                if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
 
1219
                                        return (0);
 
1220
 
 
1221
                                if( sp->cinfo.d.data_precision == 12 )
 
1222
                                {
 
1223
                                        int value_pairs = (sp->cinfo.d.output_width
 
1224
                                            * sp->cinfo.d.num_components) / 2;
 
1225
                                        int iPair;
 
1226
 
 
1227
                                        for( iPair = 0; iPair < value_pairs; iPair++ )
 
1228
                                        {
 
1229
                                                unsigned char *out_ptr =
 
1230
                                                    ((unsigned char *) buf) + iPair * 3;
 
1231
                                                JSAMPLE *in_ptr = line_work_buf + iPair * 2;
 
1232
 
 
1233
                                                out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
 
1234
                                                out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
 
1235
                                                    | ((in_ptr[1] & 0xf00) >> 8);
 
1236
                                                out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
 
1237
                                        }
 
1238
                                }
 
1239
                                else if( sp->cinfo.d.data_precision == 8 )
 
1240
                                {
 
1241
                                        int value_count = (sp->cinfo.d.output_width
 
1242
                                            * sp->cinfo.d.num_components);
 
1243
                                        int iValue;
 
1244
 
 
1245
                                        for( iValue = 0; iValue < value_count; iValue++ )
 
1246
                                        {
 
1247
                                                ((unsigned char *) buf)[iValue] =
 
1248
                                                    line_work_buf[iValue] & 0xff;
 
1249
                                        }
 
1250
                                }
 
1251
                        }
 
1252
                        else
 
1253
                        {
 
1254
                                /*
 
1255
                                 * In the libjpeg6b 8bit case.  We read directly into the
 
1256
                                 * TIFF buffer.
 
1257
                                */
 
1258
                                JSAMPROW bufptr = (JSAMPROW)buf;
 
1259
 
 
1260
                                if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
 
1261
                                        return (0);
 
1262
                        }
 
1263
 
 
1264
                        ++tif->tif_row;
 
1265
                        buf += sp->bytesperline;
 
1266
                        cc -= sp->bytesperline;
 
1267
                } while (--nrows > 0);
 
1268
 
 
1269
                if( line_work_buf != NULL )
 
1270
                        _TIFFfree( line_work_buf );
 
1271
        }
 
1272
 
 
1273
        /* Update information on consumed data */
 
1274
        tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
 
1275
        tif->tif_rawcc = sp->src.bytes_in_buffer;
 
1276
                
 
1277
        /* Close down the decompressor if we've finished the strip or tile. */
 
1278
        return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
 
1279
            || TIFFjpeg_finish_decompress(sp);
 
1280
}
 
1281
 
 
1282
/*ARGSUSED*/ static int
 
1283
DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
 
1284
 
 
1285
{
 
1286
    (void) buf;
 
1287
    (void) cc;
885
1288
    (void) s;
886
1289
 
887
 
    nrows = cc / sp->bytesperline;
888
 
    if (cc % sp->bytesperline)
889
 
                TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
890
 
 
891
 
    if( nrows > (int) sp->cinfo.d.image_height )
892
 
        nrows = sp->cinfo.d.image_height;
893
 
 
894
 
    /* data is expected to be read in multiples of a scanline */
895
 
    if (nrows)
896
 
    {
897
 
        JSAMPROW line_work_buf = NULL;
898
 
 
899
 
        /*
900
 
        ** For 6B, only use temporary buffer for 12 bit imagery. 
901
 
        ** For Mk1 always use it. 
902
 
        */
903
 
#if !defined(JPEG_LIB_MK1)        
904
 
        if( sp->cinfo.d.data_precision == 12 )
905
 
#endif
906
 
        {
907
 
            line_work_buf = (JSAMPROW) 
908
 
                _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width 
909
 
                            * sp->cinfo.d.num_components );
910
 
        }
911
 
 
912
 
        do {
913
 
            if( line_work_buf != NULL )
914
 
            {
915
 
                /* 
916
 
                ** In the MK1 case, we aways read into a 16bit buffer, and then
917
 
                ** pack down to 12bit or 8bit.  In 6B case we only read into 16
918
 
                ** bit buffer for 12bit data, which we need to repack. 
919
 
                */
920
 
                if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
921
 
                    return (0);
922
 
 
923
 
                if( sp->cinfo.d.data_precision == 12 )
924
 
                {
925
 
                    int value_pairs = (sp->cinfo.d.output_width 
926
 
                                       * sp->cinfo.d.num_components) / 2;
927
 
                    int iPair;
928
 
 
929
 
                    for( iPair = 0; iPair < value_pairs; iPair++ )
930
 
                    {
931
 
                        unsigned char *out_ptr = 
932
 
                            ((unsigned char *) buf) + iPair * 3;
933
 
                        JSAMPLE *in_ptr = line_work_buf + iPair * 2;
934
 
 
935
 
                        out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
936
 
                        out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
937
 
                            | ((in_ptr[1] & 0xf00) >> 8);
938
 
                        out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
939
 
                    }
940
 
                }
941
 
                else if( sp->cinfo.d.data_precision == 8 )
942
 
                {
943
 
                    int value_count = (sp->cinfo.d.output_width 
944
 
                                       * sp->cinfo.d.num_components);
945
 
                    int iValue;
946
 
 
947
 
                    for( iValue = 0; iValue < value_count; iValue++ )
948
 
                    {
949
 
                        ((unsigned char *) buf)[iValue] = 
950
 
                            line_work_buf[iValue] & 0xff;
951
 
                    }
952
 
                }
953
 
            }
954
 
            else
955
 
            {
956
 
                /*
957
 
                ** In the libjpeg6b 8bit case.  We read directly into the 
958
 
                ** TIFF buffer.
959
 
                */
960
 
                JSAMPROW bufptr = (JSAMPROW)buf;
961
 
  
962
 
                if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
963
 
                    return (0);
964
 
            }
965
 
 
966
 
            ++tif->tif_row;
967
 
            buf += sp->bytesperline;
968
 
            cc -= sp->bytesperline;
969
 
        } while (--nrows > 0);
970
 
 
971
 
        if( line_work_buf != NULL )
972
 
            _TIFFfree( line_work_buf );
973
 
    }
974
 
 
975
 
    /* Close down the decompressor if we've finished the strip or tile. */
976
 
    return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
977
 
        || TIFFjpeg_finish_decompress(sp);
 
1290
    TIFFErrorExt(tif->tif_clientdata, "TIFFReadScanline",
 
1291
                 "scanline oriented access is not supported for downsampled JPEG compressed images, consider enabling TIFF_JPEGCOLORMODE as JPEGCOLORMODE_RGB." );
 
1292
    return 0;
978
1293
}
979
1294
 
980
1295
/*
982
1297
 * Returned data is downsampled per sampling factors.
983
1298
 */
984
1299
/*ARGSUSED*/ static int
985
 
JPEGDecodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
 
1300
JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
986
1301
{
987
1302
        JPEGState *sp = JState(tif);
988
 
        tsize_t nrows;
 
1303
        tmsize_t nrows;
989
1304
        (void) s;
990
1305
 
991
 
    nrows = cc / sp->bytesperline;
992
 
    if (cc % sp->bytesperline)
993
 
                TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
994
 
 
995
 
    if( nrows > (int) sp->cinfo.d.image_height )
996
 
        nrows = sp->cinfo.d.image_height;
997
 
 
998
 
    /* data is expected to be read in multiples of a scanline */
999
 
    if (nrows) {
 
1306
        /* data is expected to be read in multiples of a scanline */
 
1307
        if ( (nrows = sp->cinfo.d.image_height) ) {
 
1308
 
1000
1309
                /* Cb,Cr both have sampling factors 1, so this is correct */
1001
1310
                JDIMENSION clumps_per_line = sp->cinfo.d.comp_info[1].downsampled_width;            
1002
1311
                int samples_per_clump = sp->samplesperclump;
1003
1312
 
1004
 
#ifdef JPEG_LIB_MK1
 
1313
#if defined(JPEG_LIB_MK1_OR_12BIT)
1005
1314
                unsigned short* tmpbuf = _TIFFmalloc(sizeof(unsigned short) *
1006
 
                    sp->cinfo.d.output_width *
1007
 
                    sp->cinfo.d.num_components);
 
1315
                                                     sp->cinfo.d.output_width *
 
1316
                                                     sp->cinfo.d.num_components);
 
1317
                if(tmpbuf==NULL) {
 
1318
                        TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
 
1319
                                     "Out of memory");
 
1320
                        return 0;
 
1321
                }
1008
1322
#endif
1009
1323
 
1010
1324
                do {
1011
1325
                        jpeg_component_info *compptr;
1012
1326
                        int ci, clumpoffset;
1013
1327
 
 
1328
                        if( cc < sp->bytesperline ) {
 
1329
                                TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
 
1330
                                             "application buffer not large enough for all data.");
 
1331
                                return 0;
 
1332
                        }
 
1333
 
1014
1334
                        /* Reload downsampled-data buffer if needed */
1015
1335
                        if (sp->scancount >= DCTSIZE) {
1016
1336
                                int n = sp->cinfo.d.max_v_samp_factor * DCTSIZE;
1024
1344
                         */
1025
1345
                        clumpoffset = 0;    /* first sample in clump */
1026
1346
                        for (ci = 0, compptr = sp->cinfo.d.comp_info;
1027
 
                            ci < sp->cinfo.d.num_components;
1028
 
                            ci++, compptr++) {
 
1347
                             ci < sp->cinfo.d.num_components;
 
1348
                             ci++, compptr++) {
1029
1349
                                int hsamp = compptr->h_samp_factor;
1030
1350
                                int vsamp = compptr->v_samp_factor;
1031
1351
                                int ypos;
1032
1352
 
1033
1353
                                for (ypos = 0; ypos < vsamp; ypos++) {
1034
1354
                                        JSAMPLE *inptr = sp->ds_buffer[ci][sp->scancount*vsamp + ypos];
1035
 
#ifdef JPEG_LIB_MK1
 
1355
                                        JDIMENSION nclump;
 
1356
#if defined(JPEG_LIB_MK1_OR_12BIT)
1036
1357
                                        JSAMPLE *outptr = (JSAMPLE*)tmpbuf + clumpoffset;
1037
1358
#else
1038
1359
                                        JSAMPLE *outptr = (JSAMPLE*)buf + clumpoffset;
 
1360
                                        if (cc < clumpoffset + samples_per_clump*(clumps_per_line-1) + hsamp) {
 
1361
                                                TIFFErrorExt(tif->tif_clientdata, "JPEGDecodeRaw",
 
1362
                                                             "application buffer not large enough for all data, possible subsampling issue");
 
1363
                                                return 0;
 
1364
                                        }
1039
1365
#endif
1040
 
                                        JDIMENSION nclump;
1041
1366
 
1042
1367
                                        if (hsamp == 1) {
1043
1368
                                                /* fast path for at least Cb and Cr */
1048
1373
                                        } else {
1049
1374
                                                int xpos;
1050
1375
 
1051
 
                        /* general case */
 
1376
                                                /* general case */
1052
1377
                                                for (nclump = clumps_per_line; nclump-- > 0; ) {
1053
1378
                                                        for (xpos = 0; xpos < hsamp; xpos++)
1054
1379
                                                                outptr[xpos] = *inptr++;
1059
1384
                                }
1060
1385
                        }
1061
1386
 
1062
 
#ifdef JPEG_LIB_MK1
 
1387
#if defined(JPEG_LIB_MK1_OR_12BIT)
1063
1388
                        {
1064
1389
                                if (sp->cinfo.d.data_precision == 8)
1065
1390
                                {
1071
1396
                                        }
1072
1397
                                }
1073
1398
                                else
1074
 
                                {         /* 12-bit  */
 
1399
                                {         /* 12-bit */
1075
1400
                                        int value_pairs = (sp->cinfo.d.output_width
1076
 
                                            * sp->cinfo.d.num_components) / 2;
 
1401
                                                           * sp->cinfo.d.num_components) / 2;
1077
1402
                                        int iPair;
1078
1403
                                        for( iPair = 0; iPair < value_pairs; iPair++ )
1079
1404
                                        {
1080
1405
                                                unsigned char *out_ptr = ((unsigned char *) buf) + iPair * 3;
1081
 
                                                JSAMPLE *in_ptr = tmpbuf + iPair * 2;
 
1406
                                                JSAMPLE *in_ptr = (JSAMPLE *) (tmpbuf + iPair * 2);
1082
1407
                                                out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
1083
1408
                                                out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
1084
 
                                                    | ((in_ptr[1] & 0xf00) >> 8);
 
1409
                                                        | ((in_ptr[1] & 0xf00) >> 8);
1085
1410
                                                out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
1086
1411
                                        }
1087
1412
                                }
1090
1415
 
1091
1416
                        sp->scancount ++;
1092
1417
                        tif->tif_row += sp->v_sampling;
1093
 
                        /* increment/decrement of buf and cc is still incorrect, but should not matter
1094
 
                         * TODO: resolve this */
 
1418
 
1095
1419
                        buf += sp->bytesperline;
1096
1420
                        cc -= sp->bytesperline;
1097
 
                } while (--nrows > 0);
1098
 
 
1099
 
#ifdef JPEG_LIB_MK1
 
1421
 
 
1422
                        nrows -= sp->v_sampling;
 
1423
                } while (nrows > 0);
 
1424
 
 
1425
#if defined(JPEG_LIB_MK1_OR_12BIT)
1100
1426
                _TIFFfree(tmpbuf);
1101
1427
#endif
1102
1428
 
1104
1430
 
1105
1431
        /* Close down the decompressor if done. */
1106
1432
        return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
1107
 
            || TIFFjpeg_finish_decompress(sp);
 
1433
                || TIFFjpeg_finish_decompress(sp);
1108
1434
}
1109
1435
 
1110
1436
 
1137
1463
{
1138
1464
        JPEGState* sp = JState(tif);
1139
1465
 
1140
 
        JPEGInitializeLibJPEG( tif, 0, 0 );
1141
 
 
1142
1466
        /* Initialize quant tables for current quality setting */
1143
1467
        if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1144
1468
                return (0);
1173
1497
        TIFFDirectory *td = &tif->tif_dir;
1174
1498
        static const char module[] = "JPEGSetupEncode";
1175
1499
 
1176
 
        JPEGInitializeLibJPEG( tif, 1, 0 );
 
1500
#if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
 
1501
        if( tif->tif_dir.td_bitspersample == 12 )
 
1502
            return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 1 );
 
1503
#endif
 
1504
 
 
1505
        JPEGInitializeLibJPEG( tif, FALSE );
1177
1506
 
1178
1507
        assert(sp != NULL);
1179
1508
        assert(!sp->cinfo.comm.is_decompressor);
1301
1630
 * Set encoding state at the start of a strip or tile.
1302
1631
 */
1303
1632
static int
1304
 
JPEGPreEncode(TIFF* tif, tsample_t s)
 
1633
JPEGPreEncode(TIFF* tif, uint16 s)
1305
1634
{
1306
1635
        JPEGState *sp = JState(tif);
1307
1636
        TIFFDirectory *td = &tif->tif_dir;
1310
1639
        int downsampled_input;
1311
1640
 
1312
1641
        assert(sp != NULL);
 
1642
  
 
1643
        if (sp->cinfo.comm.is_decompressor == 1)
 
1644
        {
 
1645
                tif->tif_setupencode( tif );
 
1646
        }
 
1647
  
1313
1648
        assert(!sp->cinfo.comm.is_decompressor);
1314
1649
        /*
1315
1650
         * Set encoding parameters for this strip/tile.
1323
1658
                segment_height = td->td_imagelength - tif->tif_row;
1324
1659
                if (segment_height > td->td_rowsperstrip)
1325
1660
                        segment_height = td->td_rowsperstrip;
1326
 
                sp->bytesperline = TIFFOldScanlineSize(tif);
 
1661
                sp->bytesperline = TIFFScanlineSize(tif);
1327
1662
        }
1328
1663
        if (td->td_planarconfig == PLANARCONFIG_SEPARATE && s > 0) {
1329
1664
                /* for PC 2, scale down the strip/tile size
1330
1665
                 * to match a downsampled component
1331
1666
                 */
1332
 
                segment_width = TIFFhowmany(segment_width, sp->h_sampling);
1333
 
                segment_height = TIFFhowmany(segment_height, sp->v_sampling);
 
1667
                segment_width = TIFFhowmany_32(segment_width, sp->h_sampling); 
 
1668
                segment_height = TIFFhowmany_32(segment_height, sp->v_sampling);
1334
1669
        }
1335
1670
        if (segment_width > 65535 || segment_height > 65535) {
1336
1671
                TIFFErrorExt(tif->tif_clientdata, module, "Strip/tile too large for JPEG");
1388
1723
        sp->cinfo.c.write_Adobe_marker = FALSE;
1389
1724
        /* set up table handling correctly */
1390
1725
        if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
1391
 
                return (0);
 
1726
                return (0);
1392
1727
        if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
1393
1728
                unsuppress_quant_table(sp, 0);
1394
1729
                unsuppress_quant_table(sp, 1);
1429
1764
 * "Standard" case: incoming data is not downsampled.
1430
1765
 */
1431
1766
static int
1432
 
JPEGEncode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
 
1767
JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1433
1768
{
1434
1769
        JPEGState *sp = JState(tif);
1435
 
        tsize_t nrows;
 
1770
        tmsize_t nrows;
1436
1771
        JSAMPROW bufptr[1];
 
1772
        short *line16 = NULL;
 
1773
        int    line16_count = 0;
1437
1774
 
1438
1775
        (void) s;
1439
1776
        assert(sp != NULL);
1440
1777
        /* data is expected to be supplied in multiples of a scanline */
1441
1778
        nrows = cc / sp->bytesperline;
1442
1779
        if (cc % sp->bytesperline)
1443
 
                TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline discarded");
 
1780
            TIFFWarningExt(tif->tif_clientdata, tif->tif_name, 
 
1781
                           "fractional scanline discarded");
1444
1782
 
1445
1783
        /* The last strip will be limited to image size */
1446
1784
        if( !isTiled(tif) && tif->tif_row+nrows > tif->tif_dir.td_imagelength )
1447
1785
            nrows = tif->tif_dir.td_imagelength - tif->tif_row;
1448
1786
 
 
1787
        if( sp->cinfo.c.data_precision == 12 )
 
1788
        {
 
1789
            line16_count = (sp->bytesperline * 2) / 3;
 
1790
            line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
 
1791
            // FIXME: undiagnosed malloc failure
 
1792
        }
 
1793
            
1449
1794
        while (nrows-- > 0) {
 
1795
 
 
1796
            if( sp->cinfo.c.data_precision == 12 )
 
1797
            {
 
1798
 
 
1799
                int value_pairs = line16_count / 2;
 
1800
                int iPair;
 
1801
 
 
1802
                bufptr[0] = (JSAMPROW) line16;
 
1803
 
 
1804
                for( iPair = 0; iPair < value_pairs; iPair++ )
 
1805
                {
 
1806
                    unsigned char *in_ptr =
 
1807
                        ((unsigned char *) buf) + iPair * 3;
 
1808
                    JSAMPLE *out_ptr = (JSAMPLE *) (line16 + iPair * 2);
 
1809
 
 
1810
                    out_ptr[0] = (in_ptr[0] << 4) | ((in_ptr[1] & 0xf0) >> 4);
 
1811
                    out_ptr[1] = ((in_ptr[1] & 0x0f) << 8) | in_ptr[2];
 
1812
                }
 
1813
            }
 
1814
            else
 
1815
            {
1450
1816
                bufptr[0] = (JSAMPROW) buf;
1451
 
                if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
1452
 
                        return (0);
1453
 
                if (nrows > 0)
1454
 
                        tif->tif_row++;
1455
 
                buf += sp->bytesperline;
 
1817
            }
 
1818
            if (TIFFjpeg_write_scanlines(sp, bufptr, 1) != 1)
 
1819
                return (0);
 
1820
            if (nrows > 0)
 
1821
                tif->tif_row++;
 
1822
            buf += sp->bytesperline;
1456
1823
        }
 
1824
 
 
1825
        if( sp->cinfo.c.data_precision == 12 )
 
1826
        {
 
1827
            _TIFFfree( line16 );
 
1828
        }
 
1829
            
1457
1830
        return (1);
1458
1831
}
1459
1832
 
1462
1835
 * Incoming data is expected to be downsampled per sampling factors.
1463
1836
 */
1464
1837
static int
1465
 
JPEGEncodeRaw(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
 
1838
JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
1466
1839
{
1467
1840
        JPEGState *sp = JState(tif);
1468
1841
        JSAMPLE* inptr;
1469
1842
        JSAMPLE* outptr;
1470
 
        tsize_t nrows;
 
1843
        tmsize_t nrows;
1471
1844
        JDIMENSION clumps_per_line, nclump;
1472
1845
        int clumpoffset, ci, xpos, ypos;
1473
1846
        jpeg_component_info* compptr;
1474
1847
        int samples_per_clump = sp->samplesperclump;
1475
 
        tsize_t bytesperclumpline;
 
1848
        tmsize_t bytesperclumpline;
1476
1849
 
1477
1850
        (void) s;
1478
1851
        assert(sp != NULL);
1562
1935
                     ci < sp->cinfo.c.num_components;
1563
1936
                     ci++, compptr++) {
1564
1937
                        int vsamp = compptr->v_samp_factor;
1565
 
                        tsize_t row_width = compptr->width_in_blocks * DCTSIZE
 
1938
                        tmsize_t row_width = compptr->width_in_blocks * DCTSIZE
1566
1939
                                * sizeof(JSAMPLE);
1567
1940
                        for (ypos = sp->scancount * vsamp;
1568
1941
                             ypos < DCTSIZE * vsamp; ypos++) {
1569
 
                                _TIFFmemcpy((tdata_t)sp->ds_buffer[ci][ypos],
1570
 
                                            (tdata_t)sp->ds_buffer[ci][ypos-1],
 
1942
                                _TIFFmemcpy((void*)sp->ds_buffer[ci][ypos],
 
1943
                                            (void*)sp->ds_buffer[ci][ypos-1],
1571
1944
                                            row_width);
1572
1945
 
1573
1946
                        }
1591
1964
        tif->tif_tagmethods.vsetfield = sp->vsetparent;
1592
1965
        tif->tif_tagmethods.printdir = sp->printdir;
1593
1966
 
1594
 
        if( sp->cinfo_initialized )
1595
 
            TIFFjpeg_destroy(sp);       /* release libjpeg resources */
1596
 
        if (sp->jpegtables)             /* tag value */
1597
 
                _TIFFfree(sp->jpegtables);
 
1967
        if( sp != NULL ) {
 
1968
                if( sp->cinfo_initialized )
 
1969
                    TIFFjpeg_destroy(sp);       /* release libjpeg resources */
 
1970
                if (sp->jpegtables)             /* tag value */
 
1971
                        _TIFFfree(sp->jpegtables);
 
1972
        }
1598
1973
        _TIFFfree(tif->tif_data);       /* release local state */
1599
1974
        tif->tif_data = NULL;
1600
1975
 
1631
2006
         * Should we really be doing this now if image size isn't set? 
1632
2007
         */
1633
2008
        if( tif->tif_tilesize > 0 )
1634
 
            tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tsize_t) -1;
1635
 
 
1636
 
        if(tif->tif_scanlinesize > 0 )
 
2009
            tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1);   
 
2010
        if( tif->tif_scanlinesize > 0 )
1637
2011
            tif->tif_scanlinesize = TIFFScanlineSize(tif); 
1638
2012
}
1639
2013
 
1640
2014
static int
1641
 
JPEGVSetField(TIFF* tif, ttag_t tag, va_list ap)
 
2015
JPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
1642
2016
{
1643
2017
        JPEGState* sp = JState(tif);
1644
 
        const TIFFFieldInfo* fip;
 
2018
        const TIFFField* fip;
1645
2019
        uint32 v32;
1646
2020
 
1647
2021
        assert(sp != NULL);
1648
2022
 
1649
2023
        switch (tag) {
1650
2024
        case TIFFTAG_JPEGTABLES:
1651
 
                v32 = va_arg(ap, uint32);
 
2025
                v32 = (uint32) va_arg(ap, uint32);
1652
2026
                if (v32 == 0) {
1653
2027
                        /* XXX */
1654
2028
                        return (0);
1659
2033
                TIFFSetFieldBit(tif, FIELD_JPEGTABLES);
1660
2034
                break;
1661
2035
        case TIFFTAG_JPEGQUALITY:
1662
 
                sp->jpegquality = va_arg(ap, int);
 
2036
                sp->jpegquality = (int) va_arg(ap, int);
1663
2037
                return (1);                     /* pseudo tag */
1664
2038
        case TIFFTAG_JPEGCOLORMODE:
1665
 
                sp->jpegcolormode = va_arg(ap, int);
1666
 
                JPEGResetUpsampled( tif );
 
2039
                sp->jpegcolormode = (int) va_arg(ap, int);
 
2040
                JPEGResetUpsampled( tif );
1667
2041
                return (1);                     /* pseudo tag */
1668
2042
        case TIFFTAG_PHOTOMETRIC:
1669
 
        {
1670
 
                int ret_value = (*sp->vsetparent)(tif, tag, ap);
1671
 
                JPEGResetUpsampled( tif );
1672
 
                return ret_value;
1673
 
        }
 
2043
        {
 
2044
                int ret_value = (*sp->vsetparent)(tif, tag, ap);
 
2045
                JPEGResetUpsampled( tif );
 
2046
                return ret_value;
 
2047
        }
1674
2048
        case TIFFTAG_JPEGTABLESMODE:
1675
 
                sp->jpegtablesmode = va_arg(ap, int);
 
2049
                sp->jpegtablesmode = (int) va_arg(ap, int);
1676
2050
                return (1);                     /* pseudo tag */
1677
2051
        case TIFFTAG_YCBCRSUBSAMPLING:
1678
 
                /* mark the fact that we have a real ycbcrsubsampling! */
 
2052
                /* mark the fact that we have a real ycbcrsubsampling! */
1679
2053
                sp->ycbcrsampling_fetched = 1;
1680
 
                /* should we be recomputing upsampling info here? */
 
2054
                /* should we be recomputing upsampling info here? */
1681
2055
                return (*sp->vsetparent)(tif, tag, ap);
1682
 
        case TIFFTAG_FAXRECVPARAMS:
1683
 
                sp->recvparams = va_arg(ap, uint32);
1684
 
                break;
1685
 
        case TIFFTAG_FAXSUBADDRESS:
1686
 
                _TIFFsetString(&sp->subaddress, va_arg(ap, char*));
1687
 
                break;
1688
 
        case TIFFTAG_FAXRECVTIME:
1689
 
                sp->recvtime = va_arg(ap, uint32);
1690
 
                break;
1691
 
        case TIFFTAG_FAXDCS:
1692
 
                _TIFFsetString(&sp->faxdcs, va_arg(ap, char*));
1693
 
                break;
1694
2056
        default:
1695
2057
                return (*sp->vsetparent)(tif, tag, ap);
1696
2058
        }
1697
2059
 
1698
 
        if ((fip = _TIFFFieldWithTag(tif, tag))) {
 
2060
        if ((fip = TIFFFieldWithTag(tif, tag))) {
1699
2061
                TIFFSetFieldBit(tif, fip->field_bit);
1700
2062
        } else {
1701
2063
                return (0);
1705
2067
        return (1);
1706
2068
}
1707
2069
 
1708
 
/*
1709
 
 * Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
1710
 
 * the TIFF tags, but still use non-default (2,2) values within the jpeg
1711
 
 * data stream itself.  In order for TIFF applications to work properly
1712
 
 * - for instance to get the strip buffer size right - it is imperative
1713
 
 * that the subsampling be available before we start reading the image
1714
 
 * data normally.  This function will attempt to load the first strip in
1715
 
 * order to get the sampling values from the jpeg data stream.  Various
1716
 
 * hacks are various places are done to ensure this function gets called
1717
 
 * before the td_ycbcrsubsampling values are used from the directory structure,
1718
 
 * including calling TIFFGetField() for the YCBCRSUBSAMPLING field from 
1719
 
 * TIFFStripSize(), and the printing code in tif_print.c. 
1720
 
 *
1721
 
 * Note that JPEGPreDeocode() will produce a fairly loud warning when the
1722
 
 * discovered sampling does not match the default sampling (2,2) or whatever
1723
 
 * was actually in the tiff tags. 
1724
 
 *
1725
 
 * Problems:
1726
 
 *  o This code will cause one whole strip/tile of compressed data to be
1727
 
 *    loaded just to get the tags right, even if the imagery is never read.
1728
 
 *    It would be more efficient to just load a bit of the header, and
1729
 
 *    initialize things from that. 
1730
 
 *
1731
 
 * See the bug in bugzilla for details:
1732
 
 *
1733
 
 * http://bugzilla.remotesensing.org/show_bug.cgi?id=168
1734
 
 *
1735
 
 * Frank Warmerdam, July 2002
1736
 
 */
1737
 
 
1738
 
static void 
1739
 
JPEGFixupTestSubsampling( TIFF * tif )
1740
 
{
1741
 
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
1742
 
    JPEGState *sp = JState(tif);
1743
 
    TIFFDirectory *td = &tif->tif_dir;
1744
 
 
1745
 
    JPEGInitializeLibJPEG( tif, 0, 0 );
1746
 
 
1747
 
    /*
1748
 
     * Some JPEG-in-TIFF files don't provide the ycbcrsampling tags, 
1749
 
     * and use a sampling schema other than the default 2,2.  To handle
1750
 
     * this we actually have to scan the header of a strip or tile of
1751
 
     * jpeg data to get the sampling.  
1752
 
     */
1753
 
    if( !sp->cinfo.comm.is_decompressor 
1754
 
        || sp->ycbcrsampling_fetched  
1755
 
        || td->td_photometric != PHOTOMETRIC_YCBCR )
1756
 
        return;
1757
 
 
1758
 
    sp->ycbcrsampling_fetched = 1;
1759
 
    if( TIFFIsTiled( tif ) )
1760
 
    {
1761
 
        if( !TIFFFillTile( tif, 0 ) )
1762
 
                        return;
1763
 
    }
1764
 
    else
1765
 
    {
1766
 
        if( !TIFFFillStrip( tif, 0 ) )
1767
 
            return;
1768
 
    }
1769
 
 
1770
 
    TIFFSetField( tif, TIFFTAG_YCBCRSUBSAMPLING, 
1771
 
                  (uint16) sp->h_sampling, (uint16) sp->v_sampling );
1772
 
 
1773
 
    /*
1774
 
    ** We want to clear the loaded strip so the application has time
1775
 
    ** to set JPEGCOLORMODE or other behavior modifiers.  This essentially
1776
 
    ** undoes the JPEGPreDecode triggers by TIFFFileStrip().  (#1936)
1777
 
    */
1778
 
    tif->tif_curstrip = -1;
1779
 
 
1780
 
#endif /* CHECK_JPEG_YCBCR_SUBSAMPLING */
1781
 
}
1782
 
 
1783
2070
static int
1784
 
JPEGVGetField(TIFF* tif, ttag_t tag, va_list ap)
 
2071
JPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
1785
2072
{
1786
2073
        JPEGState* sp = JState(tif);
1787
2074
 
1801
2088
                case TIFFTAG_JPEGTABLESMODE:
1802
2089
                        *va_arg(ap, int*) = sp->jpegtablesmode;
1803
2090
                        break;
1804
 
                case TIFFTAG_YCBCRSUBSAMPLING:
1805
 
                        JPEGFixupTestSubsampling( tif );
1806
 
                        return (*sp->vgetparent)(tif, tag, ap);
1807
 
                case TIFFTAG_FAXRECVPARAMS:
1808
 
                        *va_arg(ap, uint32*) = sp->recvparams;
1809
 
                        break;
1810
 
                case TIFFTAG_FAXSUBADDRESS:
1811
 
                        *va_arg(ap, char**) = sp->subaddress;
1812
 
                        break;
1813
 
                case TIFFTAG_FAXRECVTIME:
1814
 
                        *va_arg(ap, uint32*) = sp->recvtime;
1815
 
                        break;
1816
 
                case TIFFTAG_FAXDCS:
1817
 
                        *va_arg(ap, char**) = sp->faxdcs;
1818
 
                        break;
1819
2091
                default:
1820
2092
                        return (*sp->vgetparent)(tif, tag, ap);
1821
2093
        }
1828
2100
        JPEGState* sp = JState(tif);
1829
2101
 
1830
2102
        assert(sp != NULL);
1831
 
 
1832
2103
        (void) flags;
1833
 
        if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
1834
 
                fprintf(fd, "  JPEG Tables: (%lu bytes)\n",
1835
 
                        (unsigned long) sp->jpegtables_length);
1836
 
        if (TIFFFieldSet(tif,FIELD_RECVPARAMS))
1837
 
                fprintf(fd, "  Fax Receive Parameters: %08lx\n",
1838
 
                   (unsigned long) sp->recvparams);
1839
 
        if (TIFFFieldSet(tif,FIELD_SUBADDRESS))
1840
 
                fprintf(fd, "  Fax SubAddress: %s\n", sp->subaddress);
1841
 
        if (TIFFFieldSet(tif,FIELD_RECVTIME))
1842
 
                fprintf(fd, "  Fax Receive Time: %lu secs\n",
1843
 
                    (unsigned long) sp->recvtime);
1844
 
        if (TIFFFieldSet(tif,FIELD_FAXDCS))
1845
 
                fprintf(fd, "  Fax DCS: %s\n", sp->faxdcs);
 
2104
 
 
2105
        if( sp != NULL ) {
 
2106
                if (TIFFFieldSet(tif,FIELD_JPEGTABLES))
 
2107
                        fprintf(fd, "  JPEG Tables: (%lu bytes)\n",
 
2108
                                (unsigned long) sp->jpegtables_length);
 
2109
                if (sp->printdir)
 
2110
                        (*sp->printdir)(tif, fd, flags);
 
2111
        }
1846
2112
}
1847
2113
 
1848
2114
static uint32
1853
2119
 
1854
2120
        s = (*sp->defsparent)(tif, s);
1855
2121
        if (s < td->td_imagelength)
1856
 
                s = TIFFroundup(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
 
2122
                s = TIFFroundup_32(s, td->td_ycbcrsubsampling[1] * DCTSIZE);
1857
2123
        return (s);
1858
2124
}
1859
2125
 
1864
2130
        TIFFDirectory *td = &tif->tif_dir;
1865
2131
 
1866
2132
        (*sp->deftparent)(tif, tw, th);
1867
 
        *tw = TIFFroundup(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
1868
 
        *th = TIFFroundup(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
 
2133
        *tw = TIFFroundup_32(*tw, td->td_ycbcrsubsampling[0] * DCTSIZE);
 
2134
        *th = TIFFroundup_32(*th, td->td_ycbcrsubsampling[1] * DCTSIZE);
1869
2135
}
1870
2136
 
1871
2137
/*
1890
2156
 * NFW, Feb 3rd, 2003.
1891
2157
 */
1892
2158
 
1893
 
static int JPEGInitializeLibJPEG( TIFF * tif, int force_encode, int force_decode )
 
2159
static int JPEGInitializeLibJPEG( TIFF * tif, int decompress )
1894
2160
{
1895
2161
    JPEGState* sp = JState(tif);
1896
 
    uint32 *byte_counts = NULL;
1897
 
    int     data_is_empty = TRUE;
1898
 
    int     decompress;
1899
 
 
1900
2162
 
1901
2163
    if(sp->cinfo_initialized)
1902
2164
    {
1903
 
        if( force_encode && sp->cinfo.comm.is_decompressor )
 
2165
        if( !decompress && sp->cinfo.comm.is_decompressor )
1904
2166
            TIFFjpeg_destroy( sp );
1905
 
        else if( force_decode && !sp->cinfo.comm.is_decompressor )
 
2167
        else if( decompress && !sp->cinfo.comm.is_decompressor )
1906
2168
            TIFFjpeg_destroy( sp );
1907
2169
        else
1908
2170
            return 1;
1911
2173
    }
1912
2174
 
1913
2175
    /*
1914
 
     * Do we have tile data already?  Make sure we initialize the
1915
 
     * the state in decompressor mode if we have tile data, even if we
1916
 
     * are not in read-only file access mode. 
1917
 
     */
1918
 
    if( TIFFIsTiled( tif ) 
1919
 
        && TIFFGetField( tif, TIFFTAG_TILEBYTECOUNTS, &byte_counts ) 
1920
 
        && byte_counts != NULL )
1921
 
    {
1922
 
        data_is_empty = byte_counts[0] == 0;
1923
 
    }
1924
 
    if( !TIFFIsTiled( tif ) 
1925
 
        && TIFFGetField( tif, TIFFTAG_STRIPBYTECOUNTS, &byte_counts) 
1926
 
        && byte_counts != NULL )
1927
 
    {
1928
 
        data_is_empty = byte_counts[0] == 0;
1929
 
    }
1930
 
 
1931
 
    if( force_decode )
1932
 
        decompress = 1;
1933
 
    else if( force_encode )
1934
 
        decompress = 0;
1935
 
    else if( tif->tif_mode == O_RDONLY )
1936
 
        decompress = 1;
1937
 
    else if( data_is_empty )
1938
 
        decompress = 0;
1939
 
    else
1940
 
        decompress = 1;
1941
 
 
1942
 
    /*
1943
2176
     * Initialize libjpeg.
1944
2177
     */
1945
2178
    if ( decompress ) {
1946
2179
        if (!TIFFjpeg_create_decompress(sp))
1947
2180
            return (0);
1948
 
 
1949
2181
    } else {
1950
2182
        if (!TIFFjpeg_create_compress(sp))
1951
2183
            return (0);
1966
2198
        /*
1967
2199
         * Merge codec-specific tag information.
1968
2200
         */
1969
 
        if (!_TIFFMergeFieldInfo(tif, jpegFieldInfo, N(jpegFieldInfo))) {
 
2201
        if (!_TIFFMergeFields(tif, jpegFields, TIFFArrayCount(jpegFields))) {
1970
2202
                TIFFErrorExt(tif->tif_clientdata,
1971
2203
                             "TIFFInitJPEG",
1972
2204
                             "Merging JPEG codec-specific tags failed");
1976
2208
        /*
1977
2209
         * Allocate state block so tag methods have storage to record values.
1978
2210
         */
1979
 
        tif->tif_data = (tidata_t) _TIFFmalloc(sizeof (JPEGState));
 
2211
        tif->tif_data = (uint8*) _TIFFmalloc(sizeof (JPEGState));
1980
2212
 
1981
2213
        if (tif->tif_data == NULL) {
1982
2214
                TIFFErrorExt(tif->tif_clientdata,
2004
2236
        sp->jpegquality = 75;                   /* Default IJG quality */
2005
2237
        sp->jpegcolormode = JPEGCOLORMODE_RAW;
2006
2238
        sp->jpegtablesmode = JPEGTABLESMODE_QUANT | JPEGTABLESMODE_HUFF;
2007
 
 
2008
 
        sp->recvparams = 0;
2009
 
        sp->subaddress = NULL;
2010
 
        sp->faxdcs = NULL;
2011
 
 
2012
2239
        sp->ycbcrsampling_fetched = 0;
2013
2240
 
2014
2241
        /*
2015
2242
         * Install codec methods.
2016
2243
         */
 
2244
        tif->tif_fixuptags = JPEGFixupTags;
2017
2245
        tif->tif_setupdecode = JPEGSetupDecode;
2018
2246
        tif->tif_predecode = JPEGPreDecode;
2019
2247
        tif->tif_decoderow = JPEGDecode;
2024
2252
        tif->tif_postencode = JPEGPostEncode;
2025
2253
        tif->tif_encoderow = JPEGEncode;
2026
2254
        tif->tif_encodestrip = JPEGEncode;
2027
 
        tif->tif_encodetile = JPEGEncode;
 
2255
        tif->tif_encodetile = JPEGEncode;  
2028
2256
        tif->tif_cleanup = JPEGCleanup;
2029
2257
        sp->defsparent = tif->tif_defstripsize;
2030
2258
        tif->tif_defstripsize = JPEGDefaultStripSize;
2053
2281
*/
2054
2282
            sp->jpegtables_length = SIZE_OF_JPEGTABLES;
2055
2283
            sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
 
2284
            // FIXME: NULL-deref after malloc failure
2056
2285
            _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
2057
2286
#undef SIZE_OF_JPEGTABLES
2058
2287
        }
2059
2288
 
2060
 
        /*
2061
 
         * Mark the TIFFTAG_YCBCRSAMPLES as present even if it is not
2062
 
         * see: JPEGFixupTestSubsampling().
2063
 
         */
2064
 
        TIFFSetFieldBit( tif, FIELD_YCBCRSUBSAMPLING );
2065
 
 
2066
2289
        return 1;
2067
2290
}
2068
2291
#endif /* JPEG_SUPPORT */