forked from opencv/opencv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtif_jpeg.c
2301 lines (2053 loc) · 74.3 KB
/
tif_jpeg.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $Id: tif_jpeg.c,v 1.108 2012-06-05 03:24:30 fwarmerdam Exp $ */
/*
* Copyright (c) 1994-1997 Sam Leffler
* Copyright (c) 1994-1997 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include "tiffiop.h"
#ifdef JPEG_SUPPORT
/*
* TIFF Library
*
* JPEG Compression support per TIFF Technical Note #2
* (*not* per the original TIFF 6.0 spec).
*
* This file is simply an interface to the libjpeg library written by
* the Independent JPEG Group. You need release 5 or later of the IJG
* code, which you can find on the Internet at ftp.uu.net:/graphics/jpeg/.
*
* Contributed by Tom Lane <[email protected]>.
*/
#include <setjmp.h>
int TIFFFillStrip(TIFF* tif, uint32 strip);
int TIFFFillTile(TIFF* tif, uint32 tile);
int TIFFReInitJPEG_12( TIFF *tif, int scheme, int is_encode );
/* We undefine FAR to avoid conflict with JPEG definition */
#ifdef FAR
#undef FAR
#endif
/*
Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
not defined. Unfortunately, the MinGW and Borland compilers include
a typedef for INT32, which causes a conflict. MSVC does not include
a conficting typedef given the headers which are included.
*/
#if defined(__BORLANDC__) || defined(__MINGW32__)
# define XMD_H 1
#endif
/*
The windows RPCNDR.H file defines boolean, but defines it with the
unsigned char size. You should compile JPEG library using appropriate
definitions in jconfig.h header, but many users compile library in wrong
way. That causes errors of the following type:
"JPEGLib: JPEG parameter struct mismatch: library thinks size is 432,
caller expects 464"
For such users we wil fix the problem here. See install.doc file from
the JPEG library distribution for details.
*/
/* Define "boolean" as unsigned char, not int, per Windows custom. */
#if defined(__WIN32__) && !defined(__MINGW32__)
# ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
typedef unsigned char boolean;
# endif
# define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
#endif
#include "jpeglib.h"
#include "jerror.h"
/*
* Do we want to do special processing suitable for when JSAMPLE is a
* 16bit value?
*/
#if defined(JPEG_LIB_MK1)
# define JPEG_LIB_MK1_OR_12BIT 1
#elif BITS_IN_JSAMPLE == 12
# define JPEG_LIB_MK1_OR_12BIT 1
#endif
/*
* We are using width_in_blocks which is supposed to be private to
* libjpeg. Unfortunately, the libjpeg delivered with Cygwin has
* renamed this member to width_in_data_units. Since the header has
* also renamed a define, use that unique define name in order to
* detect the problem header and adjust to suit.
*/
#if defined(D_MAX_DATA_UNITS_IN_MCU)
#define width_in_blocks width_in_data_units
#endif
/*
* On some machines it may be worthwhile to use _setjmp or sigsetjmp
* in place of plain setjmp. These macros will make it easier.
*/
#define SETJMP(jbuf) setjmp(jbuf)
#define LONGJMP(jbuf,code) longjmp(jbuf,code)
#define JMP_BUF jmp_buf
typedef struct jpeg_destination_mgr jpeg_destination_mgr;
typedef struct jpeg_source_mgr jpeg_source_mgr;
typedef struct jpeg_error_mgr jpeg_error_mgr;
/*
* State block for each open TIFF file using
* libjpeg to do JPEG compression/decompression.
*
* libjpeg's visible state is either a jpeg_compress_struct
* or jpeg_decompress_struct depending on which way we
* are going. comm can be used to refer to the fields
* which are common to both.
*
* NB: cinfo is required to be the first member of JPEGState,
* so we can safely cast JPEGState* -> jpeg_xxx_struct*
* and vice versa!
*/
typedef struct {
union {
struct jpeg_compress_struct c;
struct jpeg_decompress_struct d;
struct jpeg_common_struct comm;
} cinfo; /* NB: must be first */
int cinfo_initialized;
jpeg_error_mgr err; /* libjpeg error manager */
JMP_BUF exit_jmpbuf; /* for catching libjpeg failures */
/*
* The following two members could be a union, but
* they're small enough that it's not worth the effort.
*/
jpeg_destination_mgr dest; /* data dest for compression */
jpeg_source_mgr src; /* data source for decompression */
/* private state */
TIFF* tif; /* back link needed by some code */
uint16 photometric; /* copy of PhotometricInterpretation */
uint16 h_sampling; /* luminance sampling factors */
uint16 v_sampling;
tmsize_t bytesperline; /* decompressed bytes per scanline */
/* pointers to intermediate buffers when processing downsampled data */
JSAMPARRAY ds_buffer[MAX_COMPONENTS];
int scancount; /* number of "scanlines" accumulated */
int samplesperclump;
TIFFVGetMethod vgetparent; /* super-class method */
TIFFVSetMethod vsetparent; /* super-class method */
TIFFPrintMethod printdir; /* super-class method */
TIFFStripMethod defsparent; /* super-class method */
TIFFTileMethod deftparent; /* super-class method */
/* pseudo-tag fields */
void* jpegtables; /* JPEGTables tag value, or NULL */
uint32 jpegtables_length; /* number of bytes in same */
int jpegquality; /* Compression quality level */
int jpegcolormode; /* Auto RGB<=>YCbCr convert? */
int jpegtablesmode; /* What to put in JPEGTables */
int ycbcrsampling_fetched;
} JPEGState;
#define JState(tif) ((JPEGState*)(tif)->tif_data)
static int JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
static int JPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
static int JPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
static int JPEGEncodeRaw(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
static int JPEGInitializeLibJPEG(TIFF * tif, int decode );
static int DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
#define FIELD_JPEGTABLES (FIELD_CODEC+0)
static const TIFFField jpegFields[] = {
{ TIFFTAG_JPEGTABLES, -3, -3, TIFF_UNDEFINED, 0, TIFF_SETGET_C32_UINT8, TIFF_SETGET_C32_UINT8, FIELD_JPEGTABLES, FALSE, TRUE, "JPEGTables", NULL },
{ TIFFTAG_JPEGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "", NULL },
{ TIFFTAG_JPEGCOLORMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL },
{ TIFFTAG_JPEGTABLESMODE, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL }
};
/*
* libjpeg interface layer.
*
* We use setjmp/longjmp to return control to libtiff
* when a fatal error is encountered within the JPEG
* library. We also direct libjpeg error and warning
* messages through the appropriate libtiff handlers.
*/
/*
* Error handling routines (these replace corresponding
* IJG routines from jerror.c). These are used for both
* compression and decompression.
*/
static void
TIFFjpeg_error_exit(j_common_ptr cinfo)
{
JPEGState *sp = (JPEGState *) cinfo; /* NB: cinfo assumed first */
char buffer[JMSG_LENGTH_MAX];
(*cinfo->err->format_message) (cinfo, buffer);
TIFFErrorExt(sp->tif->tif_clientdata, "JPEGLib", "%s", buffer); /* display the error message */
jpeg_abort(cinfo); /* clean up libjpeg state */
LONGJMP(sp->exit_jmpbuf, 1); /* return to libtiff caller */
}
/*
* This routine is invoked only for warning messages,
* since error_exit does its own thing and trace_level
* is never set > 0.
*/
static void
TIFFjpeg_output_message(j_common_ptr cinfo)
{
char buffer[JMSG_LENGTH_MAX];
(*cinfo->err->format_message) (cinfo, buffer);
TIFFWarningExt(((JPEGState *) cinfo)->tif->tif_clientdata, "JPEGLib", "%s", buffer);
}
/*
* Interface routines. This layer of routines exists
* primarily to limit side-effects from using setjmp.
* Also, normal/error returns are converted into return
* values per libtiff practice.
*/
#define CALLJPEG(sp, fail, op) (SETJMP((sp)->exit_jmpbuf) ? (fail) : (op))
#define CALLVJPEG(sp, op) CALLJPEG(sp, 0, ((op),1))
static int
TIFFjpeg_create_compress(JPEGState* sp)
{
/* initialize JPEG error handling */
sp->cinfo.c.err = jpeg_std_error(&sp->err);
sp->err.error_exit = TIFFjpeg_error_exit;
sp->err.output_message = TIFFjpeg_output_message;
return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
}
static int
TIFFjpeg_create_decompress(JPEGState* sp)
{
/* initialize JPEG error handling */
sp->cinfo.d.err = jpeg_std_error(&sp->err);
sp->err.error_exit = TIFFjpeg_error_exit;
sp->err.output_message = TIFFjpeg_output_message;
return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
}
static int
TIFFjpeg_set_defaults(JPEGState* sp)
{
return CALLVJPEG(sp, jpeg_set_defaults(&sp->cinfo.c));
}
static int
TIFFjpeg_set_colorspace(JPEGState* sp, J_COLOR_SPACE colorspace)
{
return CALLVJPEG(sp, jpeg_set_colorspace(&sp->cinfo.c, colorspace));
}
static int
TIFFjpeg_set_quality(JPEGState* sp, int quality, boolean force_baseline)
{
return CALLVJPEG(sp,
jpeg_set_quality(&sp->cinfo.c, quality, force_baseline));
}
static int
TIFFjpeg_suppress_tables(JPEGState* sp, boolean suppress)
{
return CALLVJPEG(sp, jpeg_suppress_tables(&sp->cinfo.c, suppress));
}
static int
TIFFjpeg_start_compress(JPEGState* sp, boolean write_all_tables)
{
return CALLVJPEG(sp,
jpeg_start_compress(&sp->cinfo.c, write_all_tables));
}
static int
TIFFjpeg_write_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int num_lines)
{
return CALLJPEG(sp, -1, (int) jpeg_write_scanlines(&sp->cinfo.c,
scanlines, (JDIMENSION) num_lines));
}
static int
TIFFjpeg_write_raw_data(JPEGState* sp, JSAMPIMAGE data, int num_lines)
{
return CALLJPEG(sp, -1, (int) jpeg_write_raw_data(&sp->cinfo.c,
data, (JDIMENSION) num_lines));
}
static int
TIFFjpeg_finish_compress(JPEGState* sp)
{
return CALLVJPEG(sp, jpeg_finish_compress(&sp->cinfo.c));
}
static int
TIFFjpeg_write_tables(JPEGState* sp)
{
return CALLVJPEG(sp, jpeg_write_tables(&sp->cinfo.c));
}
static int
TIFFjpeg_read_header(JPEGState* sp, boolean require_image)
{
return CALLJPEG(sp, -1, jpeg_read_header(&sp->cinfo.d, require_image));
}
static int
TIFFjpeg_start_decompress(JPEGState* sp)
{
return CALLVJPEG(sp, jpeg_start_decompress(&sp->cinfo.d));
}
static int
TIFFjpeg_read_scanlines(JPEGState* sp, JSAMPARRAY scanlines, int max_lines)
{
return CALLJPEG(sp, -1, (int) jpeg_read_scanlines(&sp->cinfo.d,
scanlines, (JDIMENSION) max_lines));
}
static int
TIFFjpeg_read_raw_data(JPEGState* sp, JSAMPIMAGE data, int max_lines)
{
return CALLJPEG(sp, -1, (int) jpeg_read_raw_data(&sp->cinfo.d,
data, (JDIMENSION) max_lines));
}
static int
TIFFjpeg_finish_decompress(JPEGState* sp)
{
return CALLJPEG(sp, -1, (int) jpeg_finish_decompress(&sp->cinfo.d));
}
static int
TIFFjpeg_abort(JPEGState* sp)
{
return CALLVJPEG(sp, jpeg_abort(&sp->cinfo.comm));
}
static int
TIFFjpeg_destroy(JPEGState* sp)
{
return CALLVJPEG(sp, jpeg_destroy(&sp->cinfo.comm));
}
static JSAMPARRAY
TIFFjpeg_alloc_sarray(JPEGState* sp, int pool_id,
JDIMENSION samplesperrow, JDIMENSION numrows)
{
return CALLJPEG(sp, (JSAMPARRAY) NULL,
(*sp->cinfo.comm.mem->alloc_sarray)
(&sp->cinfo.comm, pool_id, samplesperrow, numrows));
}
/*
* JPEG library destination data manager.
* These routines direct compressed data from libjpeg into the
* libtiff output buffer.
*/
static void
std_init_destination(j_compress_ptr cinfo)
{
JPEGState* sp = (JPEGState*) cinfo;
TIFF* tif = sp->tif;
sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
}
static boolean
std_empty_output_buffer(j_compress_ptr cinfo)
{
JPEGState* sp = (JPEGState*) cinfo;
TIFF* tif = sp->tif;
/* the entire buffer has been filled */
tif->tif_rawcc = tif->tif_rawdatasize;
#ifdef IPPJ_HUFF
/*
* The Intel IPP performance library does not necessarily fill up
* the whole output buffer on each pass, so only dump out the parts
* that have been filled.
* http://trac.osgeo.org/gdal/wiki/JpegIPP
*/
if ( sp->dest.free_in_buffer >= 0 ) {
tif->tif_rawcc = tif->tif_rawdatasize - sp->dest.free_in_buffer;
}
#endif
TIFFFlushData1(tif);
sp->dest.next_output_byte = (JOCTET*) tif->tif_rawdata;
sp->dest.free_in_buffer = (size_t) tif->tif_rawdatasize;
return (TRUE);
}
static void
std_term_destination(j_compress_ptr cinfo)
{
JPEGState* sp = (JPEGState*) cinfo;
TIFF* tif = sp->tif;
tif->tif_rawcp = (uint8*) sp->dest.next_output_byte;
tif->tif_rawcc =
tif->tif_rawdatasize - (tmsize_t) sp->dest.free_in_buffer;
/* NB: libtiff does the final buffer flush */
}
static void
TIFFjpeg_data_dest(JPEGState* sp, TIFF* tif)
{
(void) tif;
sp->cinfo.c.dest = &sp->dest;
sp->dest.init_destination = std_init_destination;
sp->dest.empty_output_buffer = std_empty_output_buffer;
sp->dest.term_destination = std_term_destination;
}
/*
* Alternate destination manager for outputting to JPEGTables field.
*/
static void
tables_init_destination(j_compress_ptr cinfo)
{
JPEGState* sp = (JPEGState*) cinfo;
/* while building, jpegtables_length is allocated buffer size */
sp->dest.next_output_byte = (JOCTET*) sp->jpegtables;
sp->dest.free_in_buffer = (size_t) sp->jpegtables_length;
}
static boolean
tables_empty_output_buffer(j_compress_ptr cinfo)
{
JPEGState* sp = (JPEGState*) cinfo;
void* newbuf;
/* the entire buffer has been filled; enlarge it by 1000 bytes */
newbuf = _TIFFrealloc((void*) sp->jpegtables,
(tmsize_t) (sp->jpegtables_length + 1000));
if (newbuf == NULL)
ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 100);
sp->dest.next_output_byte = (JOCTET*) newbuf + sp->jpegtables_length;
sp->dest.free_in_buffer = (size_t) 1000;
sp->jpegtables = newbuf;
sp->jpegtables_length += 1000;
return (TRUE);
}
static void
tables_term_destination(j_compress_ptr cinfo)
{
JPEGState* sp = (JPEGState*) cinfo;
/* set tables length to number of bytes actually emitted */
sp->jpegtables_length -= (uint32) sp->dest.free_in_buffer;
}
static int
TIFFjpeg_tables_dest(JPEGState* sp, TIFF* tif)
{
(void) tif;
/*
* Allocate a working buffer for building tables.
* Initial size is 1000 bytes, which is usually adequate.
*/
if (sp->jpegtables)
_TIFFfree(sp->jpegtables);
sp->jpegtables_length = 1000;
sp->jpegtables = (void*) _TIFFmalloc((tmsize_t) sp->jpegtables_length);
if (sp->jpegtables == NULL) {
sp->jpegtables_length = 0;
TIFFErrorExt(sp->tif->tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
return (0);
}
sp->cinfo.c.dest = &sp->dest;
sp->dest.init_destination = tables_init_destination;
sp->dest.empty_output_buffer = tables_empty_output_buffer;
sp->dest.term_destination = tables_term_destination;
return (1);
}
/*
* JPEG library source data manager.
* These routines supply compressed data to libjpeg.
*/
static void
std_init_source(j_decompress_ptr cinfo)
{
JPEGState* sp = (JPEGState*) cinfo;
TIFF* tif = sp->tif;
sp->src.next_input_byte = (const JOCTET*) tif->tif_rawdata;
sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
}
static boolean
std_fill_input_buffer(j_decompress_ptr cinfo)
{
JPEGState* sp = (JPEGState* ) cinfo;
static const JOCTET dummy_EOI[2] = { 0xFF, JPEG_EOI };
#ifdef IPPJ_HUFF
/*
* The Intel IPP performance library does not necessarily read the whole
* input buffer in one pass, so it is possible to get here with data
* yet to read.
*
* We just return without doing anything, until the entire buffer has
* been read.
* http://trac.osgeo.org/gdal/wiki/JpegIPP
*/
if( sp->src.bytes_in_buffer > 0 ) {
return (TRUE);
}
#endif
/*
* Normally the whole strip/tile is read and so we don't need to do
* a fill. In the case of CHUNKY_STRIP_READ_SUPPORT we might not have
* all the data, but the rawdata is refreshed between scanlines and
* we push this into the io machinery in JPEGDecode().
* http://trac.osgeo.org/gdal/ticket/3894
*/
WARNMS(cinfo, JWRN_JPEG_EOF);
/* insert a fake EOI marker */
sp->src.next_input_byte = dummy_EOI;
sp->src.bytes_in_buffer = 2;
return (TRUE);
}
static void
std_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
{
JPEGState* sp = (JPEGState*) cinfo;
if (num_bytes > 0) {
if ((size_t)num_bytes > sp->src.bytes_in_buffer) {
/* oops, buffer overrun */
(void) std_fill_input_buffer(cinfo);
} else {
sp->src.next_input_byte += (size_t) num_bytes;
sp->src.bytes_in_buffer -= (size_t) num_bytes;
}
}
}
static void
std_term_source(j_decompress_ptr cinfo)
{
/* No work necessary here */
(void) cinfo;
}
static void
TIFFjpeg_data_src(JPEGState* sp, TIFF* tif)
{
(void) tif;
sp->cinfo.d.src = &sp->src;
sp->src.init_source = std_init_source;
sp->src.fill_input_buffer = std_fill_input_buffer;
sp->src.skip_input_data = std_skip_input_data;
sp->src.resync_to_restart = jpeg_resync_to_restart;
sp->src.term_source = std_term_source;
sp->src.bytes_in_buffer = 0; /* for safety */
sp->src.next_input_byte = NULL;
}
/*
* Alternate source manager for reading from JPEGTables.
* We can share all the code except for the init routine.
*/
static void
tables_init_source(j_decompress_ptr cinfo)
{
JPEGState* sp = (JPEGState*) cinfo;
sp->src.next_input_byte = (const JOCTET*) sp->jpegtables;
sp->src.bytes_in_buffer = (size_t) sp->jpegtables_length;
}
static void
TIFFjpeg_tables_src(JPEGState* sp, TIFF* tif)
{
TIFFjpeg_data_src(sp, tif);
sp->src.init_source = tables_init_source;
}
/*
* Allocate downsampled-data buffers needed for downsampled I/O.
* We use values computed in jpeg_start_compress or jpeg_start_decompress.
* We use libjpeg's allocator so that buffers will be released automatically
* when done with strip/tile.
* This is also a handy place to compute samplesperclump, bytesperline.
*/
static int
alloc_downsampled_buffers(TIFF* tif, jpeg_component_info* comp_info,
int num_components)
{
JPEGState* sp = JState(tif);
int ci;
jpeg_component_info* compptr;
JSAMPARRAY buf;
int samples_per_clump = 0;
for (ci = 0, compptr = comp_info; ci < num_components;
ci++, compptr++) {
samples_per_clump += compptr->h_samp_factor *
compptr->v_samp_factor;
buf = TIFFjpeg_alloc_sarray(sp, JPOOL_IMAGE,
compptr->width_in_blocks * DCTSIZE,
(JDIMENSION) (compptr->v_samp_factor*DCTSIZE));
if (buf == NULL)
return (0);
sp->ds_buffer[ci] = buf;
}
sp->samplesperclump = samples_per_clump;
return (1);
}
/*
* JPEG Decoding.
*/
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
#define JPEG_MARKER_SOF0 0xC0
#define JPEG_MARKER_SOF1 0xC1
#define JPEG_MARKER_SOF3 0xC3
#define JPEG_MARKER_DHT 0xC4
#define JPEG_MARKER_SOI 0xD8
#define JPEG_MARKER_SOS 0xDA
#define JPEG_MARKER_DQT 0xDB
#define JPEG_MARKER_DRI 0xDD
#define JPEG_MARKER_APP0 0xE0
#define JPEG_MARKER_COM 0xFE
struct JPEGFixupTagsSubsamplingData
{
TIFF* tif;
void* buffer;
uint32 buffersize;
uint8* buffercurrentbyte;
uint32 bufferbytesleft;
uint64 fileoffset;
uint64 filebytesleft;
uint8 filepositioned;
};
static void JPEGFixupTagsSubsampling(TIFF* tif);
static int JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data);
static int JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result);
static int JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result);
static void JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength);
#endif
static int
JPEGFixupTags(TIFF* tif)
{
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
if ((tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR)&&
(tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&&
(tif->tif_dir.td_samplesperpixel==3))
JPEGFixupTagsSubsampling(tif);
#endif
return(1);
}
#ifdef CHECK_JPEG_YCBCR_SUBSAMPLING
static void
JPEGFixupTagsSubsampling(TIFF* tif)
{
/*
* Some JPEG-in-TIFF produces do not emit the YCBCRSUBSAMPLING values in
* the TIFF tags, but still use non-default (2,2) values within the jpeg
* data stream itself. In order for TIFF applications to work properly
* - for instance to get the strip buffer size right - it is imperative
* that the subsampling be available before we start reading the image
* data normally. This function will attempt to analyze the first strip in
* order to get the sampling values from the jpeg data stream.
*
* Note that JPEGPreDeocode() will produce a fairly loud warning when the
* discovered sampling does not match the default sampling (2,2) or whatever
* was actually in the tiff tags.
*
* See the bug in bugzilla for details:
*
* http://bugzilla.remotesensing.org/show_bug.cgi?id=168
*
* Frank Warmerdam, July 2002
* Joris Van Damme, May 2007
*/
static const char module[] = "JPEGFixupTagsSubsampling";
struct JPEGFixupTagsSubsamplingData m;
_TIFFFillStriles( tif );
if( tif->tif_dir.td_stripbytecount == NULL
|| tif->tif_dir.td_stripbytecount[0] == 0 )
{
/* Do not even try to check if the first strip/tile does not
yet exist, as occurs when GDAL has created a new NULL file
for instance. */
return;
}
m.tif=tif;
m.buffersize=2048;
m.buffer=_TIFFmalloc(m.buffersize);
if (m.buffer==NULL)
{
TIFFWarningExt(tif->tif_clientdata,module,
"Unable to allocate memory for auto-correcting of subsampling values; auto-correcting skipped");
return;
}
m.buffercurrentbyte=NULL;
m.bufferbytesleft=0;
m.fileoffset=tif->tif_dir.td_stripoffset[0];
m.filepositioned=0;
m.filebytesleft=tif->tif_dir.td_stripbytecount[0];
if (!JPEGFixupTagsSubsamplingSec(&m))
TIFFWarningExt(tif->tif_clientdata,module,
"Unable to auto-correct subsampling values, likely corrupt JPEG compressed data in first strip/tile; auto-correcting skipped");
_TIFFfree(m.buffer);
}
static int
JPEGFixupTagsSubsamplingSec(struct JPEGFixupTagsSubsamplingData* data)
{
static const char module[] = "JPEGFixupTagsSubsamplingSec";
uint8 m;
while (1)
{
while (1)
{
if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
return(0);
if (m==255)
break;
}
while (1)
{
if (!JPEGFixupTagsSubsamplingReadByte(data,&m))
return(0);
if (m!=255)
break;
}
switch (m)
{
case JPEG_MARKER_SOI:
/* this type of marker has no data and should be skipped */
break;
case JPEG_MARKER_COM:
case JPEG_MARKER_APP0:
case JPEG_MARKER_APP0+1:
case JPEG_MARKER_APP0+2:
case JPEG_MARKER_APP0+3:
case JPEG_MARKER_APP0+4:
case JPEG_MARKER_APP0+5:
case JPEG_MARKER_APP0+6:
case JPEG_MARKER_APP0+7:
case JPEG_MARKER_APP0+8:
case JPEG_MARKER_APP0+9:
case JPEG_MARKER_APP0+10:
case JPEG_MARKER_APP0+11:
case JPEG_MARKER_APP0+12:
case JPEG_MARKER_APP0+13:
case JPEG_MARKER_APP0+14:
case JPEG_MARKER_APP0+15:
case JPEG_MARKER_DQT:
case JPEG_MARKER_SOS:
case JPEG_MARKER_DHT:
case JPEG_MARKER_DRI:
/* this type of marker has data, but it has no use to us and should be skipped */
{
uint16 n;
if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
return(0);
if (n<2)
return(0);
n-=2;
if (n>0)
JPEGFixupTagsSubsamplingSkip(data,n);
}
break;
case JPEG_MARKER_SOF0:
case JPEG_MARKER_SOF1:
/* this marker contains the subsampling factors we're scanning for */
{
uint16 n;
uint16 o;
uint8 p;
uint8 ph,pv;
if (!JPEGFixupTagsSubsamplingReadWord(data,&n))
return(0);
if (n!=8+data->tif->tif_dir.td_samplesperpixel*3)
return(0);
JPEGFixupTagsSubsamplingSkip(data,7);
if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
return(0);
ph=(p>>4);
pv=(p&15);
JPEGFixupTagsSubsamplingSkip(data,1);
for (o=1; o<data->tif->tif_dir.td_samplesperpixel; o++)
{
JPEGFixupTagsSubsamplingSkip(data,1);
if (!JPEGFixupTagsSubsamplingReadByte(data,&p))
return(0);
if (p!=0x11)
{
TIFFWarningExt(data->tif->tif_clientdata,module,
"Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
return(1);
}
JPEGFixupTagsSubsamplingSkip(data,1);
}
if (((ph!=1)&&(ph!=2)&&(ph!=4))||((pv!=1)&&(pv!=2)&&(pv!=4)))
{
TIFFWarningExt(data->tif->tif_clientdata,module,
"Subsampling values inside JPEG compressed data have no TIFF equivalent, auto-correction of TIFF subsampling values failed");
return(1);
}
if ((ph!=data->tif->tif_dir.td_ycbcrsubsampling[0])||(pv!=data->tif->tif_dir.td_ycbcrsubsampling[1]))
{
TIFFWarningExt(data->tif->tif_clientdata,module,
"Auto-corrected former TIFF subsampling values [%d,%d] to match subsampling values inside JPEG compressed data [%d,%d]",
(int)data->tif->tif_dir.td_ycbcrsubsampling[0],
(int)data->tif->tif_dir.td_ycbcrsubsampling[1],
(int)ph,(int)pv);
data->tif->tif_dir.td_ycbcrsubsampling[0]=ph;
data->tif->tif_dir.td_ycbcrsubsampling[1]=pv;
}
}
return(1);
default:
return(0);
}
}
}
static int
JPEGFixupTagsSubsamplingReadByte(struct JPEGFixupTagsSubsamplingData* data, uint8* result)
{
if (data->bufferbytesleft==0)
{
uint32 m;
if (data->filebytesleft==0)
return(0);
if (!data->filepositioned)
{
TIFFSeekFile(data->tif,data->fileoffset,SEEK_SET);
data->filepositioned=1;
}
m=data->buffersize;
if ((uint64)m>data->filebytesleft)
m=(uint32)data->filebytesleft;
assert(m<0x80000000UL);
if (TIFFReadFile(data->tif,data->buffer,(tmsize_t)m)!=(tmsize_t)m)
return(0);
data->buffercurrentbyte=data->buffer;
data->bufferbytesleft=m;
data->fileoffset+=m;
data->filebytesleft-=m;
}
*result=*data->buffercurrentbyte;
data->buffercurrentbyte++;
data->bufferbytesleft--;
return(1);
}
static int
JPEGFixupTagsSubsamplingReadWord(struct JPEGFixupTagsSubsamplingData* data, uint16* result)
{
uint8 ma;
uint8 mb;
if (!JPEGFixupTagsSubsamplingReadByte(data,&ma))
return(0);
if (!JPEGFixupTagsSubsamplingReadByte(data,&mb))
return(0);
*result=(ma<<8)|mb;
return(1);
}
static void
JPEGFixupTagsSubsamplingSkip(struct JPEGFixupTagsSubsamplingData* data, uint16 skiplength)
{
if ((uint32)skiplength<=data->bufferbytesleft)
{
data->buffercurrentbyte+=skiplength;
data->bufferbytesleft-=skiplength;
}
else
{
uint16 m;
m=skiplength-data->bufferbytesleft;
if (m<=data->filebytesleft)
{
data->bufferbytesleft=0;
data->fileoffset+=m;
data->filebytesleft-=m;
data->filepositioned=0;
}
else
{
data->bufferbytesleft=0;
data->filebytesleft=0;
}
}
}
#endif
static int
JPEGSetupDecode(TIFF* tif)
{
JPEGState* sp = JState(tif);
TIFFDirectory *td = &tif->tif_dir;
#if defined(JPEG_DUAL_MODE_8_12) && !defined(TIFFInitJPEG)
if( tif->tif_dir.td_bitspersample == 12 )
return TIFFReInitJPEG_12( tif, COMPRESSION_JPEG, 0 );
#endif
JPEGInitializeLibJPEG( tif, TRUE );
assert(sp != NULL);
assert(sp->cinfo.comm.is_decompressor);
/* Read JPEGTables if it is present */
if (TIFFFieldSet(tif,FIELD_JPEGTABLES)) {
TIFFjpeg_tables_src(sp, tif);
if(TIFFjpeg_read_header(sp,FALSE) != JPEG_HEADER_TABLES_ONLY) {
TIFFErrorExt(tif->tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
return (0);
}
}
/* Grab parameters that are same for all strips/tiles */
sp->photometric = td->td_photometric;
switch (sp->photometric) {
case PHOTOMETRIC_YCBCR:
sp->h_sampling = td->td_ycbcrsubsampling[0];
sp->v_sampling = td->td_ycbcrsubsampling[1];
break;
default:
/* TIFF 6.0 forbids subsampling of all other color spaces */
sp->h_sampling = 1;
sp->v_sampling = 1;
break;
}
/* Set up for reading normal data */
TIFFjpeg_data_src(sp, tif);
tif->tif_postdecode = _TIFFNoPostDecode; /* override byte swapping */
return (1);
}
/*
* Set up for decoding a strip or tile.
*/
static int
JPEGPreDecode(TIFF* tif, uint16 s)
{
JPEGState *sp = JState(tif);
TIFFDirectory *td = &tif->tif_dir;
static const char module[] = "JPEGPreDecode";