forked from JoshDullen/libtiffN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tif_jpeg.cs
executable file
·1859 lines (1607 loc) · 56.7 KB
/
tif_jpeg.cs
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
#if JPEG_SUPPORT
// tif_jpeg.cs
//
// Based on LIBTIFF, Version 3.9.4 - 15-Jun-2010
// Copyright (c) 2006-2010 by the Authors
// Copyright (c) 1988-1997 Sam Leffler
// Copyright (c) 1991-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.
// 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 <tgl@sss.pgh.pa.us>.
using System;
using System.Collections.Generic;
using System.IO;
using Free.Ports.LibJpeg;
namespace Free.Ports.LibTiff
{
public static partial class libtiff
{
// 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.
class JPEGState : ICodecState
{
internal jpeg_common comm; // jpeg_compress or jpeg_decompress
internal bool cinfo_initialized;
internal jpeg_error_mgr err=new jpeg_error_mgr(); // libjpeg error manager
// The following two members could be a union, but
// they're small enough that it's not worth the effort.
internal jpeg_destination_mgr dest=new jpeg_destination_mgr(); // data dest for compression
internal jpeg_source_mgr src=new jpeg_source_mgr(); // data source for decompression
// private state
internal TIFF tif; // back link needed by some code
internal PHOTOMETRIC photometric; // copy of PhotometricInterpretation
internal ushort h_sampling; // luminance sampling factors
internal ushort v_sampling;
internal int bytesperline; // decompressed bytes per scanline
// pointers to intermediate buffers when processing downsampled data
internal byte[][][] ds_buffer=new byte[libjpeg.MAX_COMPONENTS][][];
internal int scancount; // number of "scanlines" accumulated
internal int samplesperclump;
internal TIFFVGetMethod vgetparent; // super-class method
internal TIFFVSetMethod vsetparent; // super-class method
internal TIFFPrintMethod printdir; // super-class method
internal TIFFStripMethod defsparent; // super-class method
internal TIFFTileMethod deftparent; // super-class method
// pseudo-tag fields
internal byte[] jpegtables; // JPEGTables tag value, or null
internal uint jpegtables_length; // number of bytes in same
internal int jpegquality; // Compression quality level
internal JPEGCOLORMODE jpegcolormode; // Auto RGB<=>YCbCr convert?
internal JPEGTABLESMODE jpegtablesmode; // What to put in JPEGTables
internal bool ycbcrsampling_fetched;
internal uint recvparams; // encoded Class 2 session params
internal string subaddress; // subaddress string
internal uint recvtime; // time spent receiving (secs)
internal string faxdcs; // encoded fax parameters (DCS, Table 2/T.30)
internal byte[][] scanlineBuffer=new byte[1][];
}
static readonly List<TIFFFieldInfo> jpegFieldInfo=MakeJpegFieldInfo();
static List<TIFFFieldInfo> MakeJpegFieldInfo()
{
List<TIFFFieldInfo> ret=new List<TIFFFieldInfo>();
ret.Add(new TIFFFieldInfo(TIFFTAG.JPEGTABLES, -1, -1, TIFFDataType.TIFF_UNDEFINED, FIELD.JPEG_JPEGTABLES, false, true, "JPEGTables"));
ret.Add(new TIFFFieldInfo(TIFFTAG.JPEGQUALITY, 0, 0, TIFFDataType.TIFF_ANY, FIELD.PSEUDO, true, false, ""));
ret.Add(new TIFFFieldInfo(TIFFTAG.JPEGCOLORMODE, 0, 0, TIFFDataType.TIFF_ANY, FIELD.PSEUDO, false, false, ""));
ret.Add(new TIFFFieldInfo(TIFFTAG.JPEGTABLESMODE, 0, 0, TIFFDataType.TIFF_ANY, FIELD.PSEUDO, false, false, ""));
// Specific for JPEG in faxes
ret.Add(new TIFFFieldInfo(TIFFTAG.FAXRECVPARAMS, 1, 1, TIFFDataType.TIFF_LONG, FIELD.JPEG_RECVPARAMS, true, false, "FaxRecvParams"));
ret.Add(new TIFFFieldInfo(TIFFTAG.FAXSUBADDRESS, -1, -1, TIFFDataType.TIFF_ASCII, FIELD.JPEG_SUBADDRESS, true, false, "FaxSubAddress"));
ret.Add(new TIFFFieldInfo(TIFFTAG.FAXRECVTIME, 1, 1, TIFFDataType.TIFF_LONG, FIELD.JPEG_RECVTIME, true, false, "FaxRecvTime"));
ret.Add(new TIFFFieldInfo(TIFFTAG.FAXDCS, -1, -1, TIFFDataType.TIFF_ASCII, FIELD.JPEG_FAXDCS, true, false, "FaxDcs"));
return ret;
}
// libjpeg interface layer.
//
// We use exceptions 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.cs). These are used for both
// compression and decompression.
static void TIFFjpeg_error_exit(jpeg_common cinfo)
{
JPEGState sp=(JPEGState)cinfo.client_data;
string buffer=cinfo.err.format_message(cinfo);
TIFFErrorExt(sp.tif.tif_clientdata, "JPEGLib", buffer); // display the error message
libjpeg.jpeg_abort(cinfo); // clean up libjpeg state
throw new Exception("jpeg_error_exit"); // 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(jpeg_common cinfo)
{
JPEGState sp=(JPEGState)cinfo.client_data;
string buffer=cinfo.err.format_message(cinfo);
TIFFWarningExt(sp.tif.tif_clientdata, "JPEGLib", buffer);
}
static bool TIFFjpeg_create_compress(JPEGState sp)
{
// initialize JPEG error handling
jpeg_compress c=new jpeg_compress();
sp.comm=c;
sp.comm.err=libjpeg.jpeg_std_error(sp.err);
sp.err.error_exit=TIFFjpeg_error_exit;
sp.err.output_message=TIFFjpeg_output_message;
c.client_data=sp;
try
{
libjpeg.jpeg_create_compress(c);
}
catch
{
return false;
}
return true;
}
static bool TIFFjpeg_create_decompress(JPEGState sp)
{
// initialize JPEG error handling
jpeg_decompress d=new jpeg_decompress();
sp.comm=d;
sp.comm.err=libjpeg.jpeg_std_error(sp.err);
sp.err.error_exit=TIFFjpeg_error_exit;
sp.err.output_message=TIFFjpeg_output_message;
d.client_data=sp;
try
{
libjpeg.jpeg_create_decompress(d);
}
catch
{
return false;
}
return true;
}
static bool TIFFjpeg_set_defaults(JPEGState sp)
{
try
{
libjpeg.jpeg_set_defaults((jpeg_compress)sp.comm);
}
catch
{
return false;
}
return true;
}
static bool TIFFjpeg_set_colorspace(JPEGState sp, J_COLOR_SPACE colorspace)
{
try
{
libjpeg.jpeg_set_colorspace((jpeg_compress)sp.comm, colorspace);
}
catch
{
return false;
}
return true;
}
static bool TIFFjpeg_set_quality(JPEGState sp, int quality, bool force_baseline)
{
try
{
libjpeg.jpeg_set_quality((jpeg_compress)sp.comm, quality, force_baseline);
}
catch
{
return false;
}
return true;
}
static bool TIFFjpeg_suppress_tables(JPEGState sp, bool suppress)
{
try
{
libjpeg.jpeg_suppress_tables((jpeg_compress)sp.comm, suppress);
}
catch
{
return false;
}
return true;
}
static bool TIFFjpeg_start_compress(JPEGState sp, bool write_all_tables)
{
try
{
libjpeg.jpeg_start_compress((jpeg_compress)sp.comm, write_all_tables);
}
catch
{
return false;
}
return true;
}
static int TIFFjpeg_write_scanlines(JPEGState sp, byte[][] scanlines, int num_lines)
{
try
{
return (int)libjpeg.jpeg_write_scanlines((jpeg_compress)sp.comm, scanlines, (uint)num_lines);
}
catch
{
return -1;
}
}
static int TIFFjpeg_write_raw_data(JPEGState sp, byte[][][] data, int num_lines)
{
try
{
return (int)libjpeg.jpeg_write_raw_data((jpeg_compress)sp.comm, data, (uint)num_lines);
}
catch
{
return -1;
}
}
static bool TIFFjpeg_finish_compress(JPEGState sp)
{
try
{
libjpeg.jpeg_finish_compress((jpeg_compress)sp.comm);
}
catch
{
return false;
}
return true;
}
static bool TIFFjpeg_write_tables(JPEGState sp)
{
try
{
libjpeg.jpeg_write_tables((jpeg_compress)sp.comm);
}
catch
{
return false;
}
return true;
}
static CONSUME_INPUT TIFFjpeg_read_header(JPEGState sp, bool require_image)
{
try
{
return libjpeg.jpeg_read_header((jpeg_decompress)sp.comm, require_image);
}
catch
{
return (CONSUME_INPUT)(-1);
}
}
static bool TIFFjpeg_start_decompress(JPEGState sp)
{
try
{
libjpeg.jpeg_start_decompress((jpeg_decompress)sp.comm);
}
catch
{
return false;
}
return true;
}
static int TIFFjpeg_read_scanlines(JPEGState sp, byte[][] scanlines, int max_lines)
{
try
{
return (int)libjpeg.jpeg_read_scanlines((jpeg_decompress)sp.comm, scanlines, (uint)max_lines);
}
catch
{
return -1;
}
}
static int TIFFjpeg_read_raw_data(JPEGState sp, byte[][][] data, int max_lines)
{
try
{
return (int)libjpeg.jpeg_read_raw_data((jpeg_decompress)sp.comm, data, (uint)max_lines);
}
catch
{
return -1;
}
}
static bool TIFFjpeg_finish_decompress(JPEGState sp)
{
try
{
return libjpeg.jpeg_finish_decompress((jpeg_decompress)sp.comm);
}
catch
{
return false;
}
}
static bool TIFFjpeg_abort(JPEGState sp)
{
try
{
libjpeg.jpeg_abort((jpeg_decompress)sp.comm);
}
catch
{
return false;
}
return true;
}
static bool TIFFjpeg_destroy(JPEGState sp)
{
try
{
var jd = sp.comm as jpeg_decompress;
if (jd != null) {
libjpeg.jpeg_destroy(jd);
}
}
catch
{
return false;
}
return true;
}
static byte[][] TIFFjpeg_alloc_sarray(JPEGState sp, uint samplesperrow, uint numrows)
{
try
{
return libjpeg.alloc_sarray(sp.comm, samplesperrow, numrows);
}
catch
{
return null;
}
}
// JPEG library destination data manager.
// These routines direct compressed data from libjpeg into the
// libtiff output buffer.
static void std_init_destination(jpeg_compress cinfo)
{
JPEGState sp=(JPEGState)cinfo.client_data;
TIFF tif=sp.tif;
sp.dest.output_bytes=tif.tif_rawdata;
sp.dest.next_output_byte=0;
sp.dest.free_in_buffer=tif.tif_rawdatasize;
}
static bool std_empty_output_buffer(jpeg_compress cinfo)
{
JPEGState sp=(JPEGState)cinfo.client_data;
TIFF tif=sp.tif;
// the entire buffer has been filled
tif.tif_rawcc=tif.tif_rawdatasize;
TIFFFlushData1(tif);
sp.dest.output_bytes=tif.tif_rawdata;
sp.dest.next_output_byte=0;
sp.dest.free_in_buffer=tif.tif_rawdatasize;
return true;
}
static void std_term_destination(jpeg_compress cinfo)
{
JPEGState sp=(JPEGState)cinfo.client_data;
TIFF tif=sp.tif;
tif.tif_rawcp=(uint)sp.dest.next_output_byte;
tif.tif_rawcc=tif.tif_rawdatasize-sp.dest.free_in_buffer;
// NB: libtiff does the final buffer flush
}
static void TIFFjpeg_data_dest(JPEGState sp, TIFF tif)
{
((jpeg_compress)sp.comm).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(jpeg_compress cinfo)
{
JPEGState sp=(JPEGState)cinfo.client_data;
// while building, jpegtables_length is allocated buffer size
sp.dest.output_bytes=sp.jpegtables;
sp.dest.next_output_byte=0;
sp.dest.free_in_buffer=sp.jpegtables_length;
}
static bool tables_empty_output_buffer(jpeg_compress cinfo)
{
JPEGState sp=(JPEGState)cinfo.client_data;
byte[] newbuf=null;
// the entire buffer has been filled; enlarge it by 1000 bytes
try
{
newbuf=new byte[sp.jpegtables_length+1000];
sp.jpegtables.CopyTo(newbuf, 0);
}
catch
{
libjpeg.ERREXIT1(cinfo, J_MESSAGE_CODE.JERR_OUT_OF_MEMORY, 100);
}
sp.dest.output_bytes=newbuf;
sp.dest.next_output_byte=(int)sp.jpegtables_length;
sp.dest.free_in_buffer=1000;
sp.jpegtables=newbuf;
sp.jpegtables_length+=1000;
return true;
}
static void tables_term_destination(jpeg_compress cinfo)
{
JPEGState sp=(JPEGState)cinfo.client_data;
// set tables length to number of bytes actually emitted
sp.jpegtables_length-=sp.dest.free_in_buffer;
}
static bool TIFFjpeg_tables_dest(JPEGState sp, TIFF tif)
{
// Allocate a working buffer for building tables.
// Initial size is 1000 bytes, which is usually adequate.
sp.jpegtables_length=1000;
try
{
sp.jpegtables=new byte[sp.jpegtables_length];
}
catch
{
sp.jpegtables_length=0;
TIFFErrorExt(sp.tif.tif_clientdata, "TIFFjpeg_tables_dest", "No space for JPEGTables");
return false;
}
((jpeg_compress)sp.comm).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 true;
}
// JPEG library source data manager.
// These routines supply compressed data to libjpeg.
static void std_init_source(jpeg_decompress cinfo)
{
JPEGState sp=(JPEGState)cinfo.client_data;
TIFF tif=sp.tif;
sp.src.input_bytes=tif.tif_rawdata;
sp.src.next_input_byte=0;
sp.src.bytes_in_buffer=tif.tif_rawcc;
}
static readonly byte[] dummy_EOI=new byte[2] { 0xFF, libjpeg.JPEG_EOI };
static bool std_fill_input_buffer(jpeg_decompress cinfo)
{
JPEGState sp=(JPEGState)cinfo.client_data;
// Should never get here since entire strip/tile is
// read into memory before the decompressor is called,
// and thus was supplied by init_source.
libjpeg.WARNMS(cinfo, J_MESSAGE_CODE.JWRN_JPEG_EOF);
// insert a fake EOI marker
sp.src.input_bytes=dummy_EOI;
sp.src.next_input_byte=0;
sp.src.bytes_in_buffer=2;
return true;
}
static void std_skip_input_data(jpeg_decompress cinfo, int num_bytes)
{
JPEGState sp=(JPEGState)cinfo.client_data;
if(num_bytes>0)
{
if(num_bytes>(int)sp.src.bytes_in_buffer)
{ // oops, buffer overrun
std_fill_input_buffer(cinfo);
}
else
{
sp.src.next_input_byte+=num_bytes;
sp.src.bytes_in_buffer-=(uint)num_bytes;
}
}
}
static void std_term_source(jpeg_decompress cinfo, bool readExtraBytes, out byte[] data)
{
// No work necessary here
// Or must we update tif.tif_rawcp, tif.tif_rawcc ???
// (if so, need empty tables_term_source!)
// Also ignore readExtraBytes
data=null;
}
static void TIFFjpeg_data_src(JPEGState sp, TIFF tif)
{
((jpeg_decompress)sp.comm).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=libjpeg.jpeg_resync_to_restart;
sp.src.term_source=std_term_source;
sp.src.bytes_in_buffer=0; // for safety
sp.src.input_bytes=null;
sp.src.next_input_byte=0;
}
// Alternate source manager for reading from JPEGTables.
// We can share all the code except for the init routine.
static void tables_init_source(jpeg_decompress cinfo)
{
JPEGState sp=(JPEGState)cinfo.client_data;
sp.src.input_bytes=sp.jpegtables;
sp.src.next_input_byte=0;
sp.src.bytes_in_buffer=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 bool alloc_downsampled_buffers(TIFF tif, jpeg_component_info[] comp_info, int num_components)
{
JPEGState sp=tif.tif_data as JPEGState;
byte[][] buf;
int samples_per_clump=0;
for(int ci=0; ci<num_components; ci++)
{
jpeg_component_info compptr=comp_info[ci];
samples_per_clump+=compptr.h_samp_factor*compptr.v_samp_factor;
try
{
buf=TIFFjpeg_alloc_sarray(sp, compptr.width_in_blocks*libjpeg.DCTSIZE, (uint)compptr.v_samp_factor*libjpeg.DCTSIZE);
}
catch
{
return false;
}
sp.ds_buffer[ci]=buf;
}
sp.samplesperclump=samples_per_clump;
return true;
}
// JPEG Decoding.
static bool JPEGSetupDecode(TIFF tif)
{
JPEGState sp=tif.tif_data as JPEGState;
TIFFDirectory td=tif.tif_dir;
JPEGInitializeLibJPEG(tif, false, true);
#if DEBUG
if(sp==null) throw new Exception("sp==null");
if(!sp.comm.is_decompressor) throw new Exception("!sp.comm.is_decompressor");
#endif
// Read JPEGTables if it is present
if(TIFFFieldSet(tif, FIELD.JPEG_JPEGTABLES))
{
TIFFjpeg_tables_src(sp, tif);
if(TIFFjpeg_read_header(sp, false)!=CONSUME_INPUT.JPEG_HEADER_TABLES_ONLY)
{
TIFFErrorExt(tif.tif_clientdata, "JPEGSetupDecode", "Bogus JPEGTables field");
return false;
}
}
// 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 true;
}
// Set up for decoding a strip or tile.
static bool JPEGPreDecode(TIFF tif, ushort sampleNumber)
{
JPEGState sp=tif.tif_data as JPEGState;
TIFFDirectory td=tif.tif_dir;
string module="JPEGPreDecode";
#if DEBUG
if(sp==null) throw new Exception("sp==null");
if(!sp.comm.is_decompressor) throw new Exception("!sp.comm.is_decompressor");
#endif
jpeg_decompress d=(jpeg_decompress)sp.comm;
// Reset decoder state from any previous strip/tile,
// in case application didn't read the whole strip.
if(!TIFFjpeg_abort(sp)) return false;
// Read the header for this strip/tile.
if(TIFFjpeg_read_header(sp, true)!=CONSUME_INPUT.JPEG_HEADER_OK) return false;
// Check image parameters and set decompression parameters.
uint segment_width=td.td_imagewidth;
uint segment_height=td.td_imagelength-tif.tif_row;
if(isTiled(tif))
{
segment_width=td.td_tilewidth;
segment_height=td.td_tilelength;
sp.bytesperline=TIFFTileRowSize(tif);
}
else
{
if(segment_height>td.td_rowsperstrip) segment_height=td.td_rowsperstrip;
sp.bytesperline=TIFFOldScanlineSize(tif);
}
if(td.td_planarconfig==PLANARCONFIG.SEPARATE&&sampleNumber>0)
{
// For PC 2, scale down the expected strip/tile size
// to match a downsampled component
segment_width=TIFFhowmany(segment_width, sp.h_sampling);
segment_height=TIFFhowmany(segment_height, sp.v_sampling);
}
if(d.image_width<segment_width||d.image_height<segment_height)
TIFFWarningExt(tif.tif_clientdata, module, "Improper JPEG strip/tile size, expected {0}x{1}, got {2}x{3}", segment_width, segment_height, d.image_width, d.image_height);
if(d.image_width>segment_width||d.image_height>segment_height)
{
// This case could be dangerous, if the strip or tile size has
// been reported as less than the amount of data jpeg will
// return, some potential security issues arise. Catch this
// case and error out.
TIFFErrorExt(tif.tif_clientdata, module, "JPEG strip/tile size exceeds expected dimensions, expected {0}x{1}, got {2}x{3}", segment_width, segment_height, d.image_width, d.image_height);
return false;
}
if(d.num_components!=(td.td_planarconfig==PLANARCONFIG.CONTIG?(int)td.td_samplesperpixel:1))
{
TIFFErrorExt(tif.tif_clientdata, module, "Improper JPEG component count");
return false;
}
if(d.data_precision!=td.td_bitspersample)
{
TIFFErrorExt(tif.tif_clientdata, module, "Improper JPEG data precision");
return false;
}
if(td.td_planarconfig==PLANARCONFIG.CONTIG)
{
// Component 0 should have expected sampling factors
if(d.comp_info[0].h_samp_factor!=sp.h_sampling||d.comp_info[0].v_samp_factor!=sp.v_sampling)
{
TIFFWarningExt(tif.tif_clientdata, module, "Improper JPEG sampling factors {0},{1}\nApparently should be {2},{3}.", d.comp_info[0].h_samp_factor, d.comp_info[0].v_samp_factor, sp.h_sampling, sp.v_sampling);
// There are potential security issues here
// for decoders that have already allocated
// buffers based on the expected sampling
// factors. Lets check the sampling factors
// dont exceed what we were expecting.
if(d.comp_info[0].h_samp_factor>sp.h_sampling||d.comp_info[0].v_samp_factor>sp.v_sampling)
{
TIFFErrorExt(tif.tif_clientdata, module, "Cannot honour JPEG sampling factors that exceed those specified.");
return false;
}
// XXX: Files written by the Intergraph software
// has different sampling factors stored in the
// TIFF tags and in the JPEG structures. We will
// try to deduce Intergraph files by the presense
// of the tag 33918.
if(TIFFFindFieldInfo(tif, TIFFTAG.INTERGRAPH_PACKET_DATA, TIFFDataType.TIFF_ANY)==null)
{
TIFFWarningExt(tif.tif_clientdata, module, "Decompressor will try reading with sampling {0},{1}.", d.comp_info[0].h_samp_factor, d.comp_info[0].v_samp_factor);
sp.h_sampling=(ushort)d.comp_info[0].h_samp_factor;
sp.v_sampling=(ushort)d.comp_info[0].v_samp_factor;
}
}
// Rest should have sampling factors 1,1
for(int ci=1; ci<d.num_components; ci++)
{
if(d.comp_info[ci].h_samp_factor!=1||d.comp_info[ci].v_samp_factor!=1)
{
TIFFErrorExt(tif.tif_clientdata, module, "Improper JPEG sampling factors");
return false;
}
}
}
else
{
// PC 2's single component should have sampling factors 1,1
if(d.comp_info[0].h_samp_factor!=1||d.comp_info[0].v_samp_factor!=1)
{
TIFFErrorExt(tif.tif_clientdata, module, "Improper JPEG sampling factors");
return false;
}
}
bool downsampled_output=false;
if(td.td_planarconfig==PLANARCONFIG.CONTIG&&sp.photometric==PHOTOMETRIC.YCBCR&&sp.jpegcolormode==JPEGCOLORMODE.RGB)
{
// Convert YCbCr to RGB
d.jpeg_color_space=J_COLOR_SPACE.JCS_YCbCr;
d.out_color_space=J_COLOR_SPACE.JCS_RGB;
}
else
{
// Suppress colorspace handling
d.jpeg_color_space=J_COLOR_SPACE.JCS_UNKNOWN;
d.out_color_space=J_COLOR_SPACE.JCS_UNKNOWN;
if(td.td_planarconfig==PLANARCONFIG.CONTIG&&(sp.h_sampling!=1||sp.v_sampling!=1)) downsampled_output=true;
// XXX what about up-sampling?
}
if(downsampled_output)
{
// Need to use raw-data interface to libjpeg
d.raw_data_out=true;
tif.tif_decoderow=JPEGDecodeRaw;
tif.tif_decodestrip=JPEGDecodeRaw;
tif.tif_decodetile=JPEGDecodeRaw;
}
else
{
// Use normal interface to libjpeg
d.raw_data_out=false;
tif.tif_decoderow=JPEGDecode;
tif.tif_decodestrip=JPEGDecode;
tif.tif_decodetile=JPEGDecode;
}
// Start JPEG decompressor
if(!TIFFjpeg_start_decompress(sp)) return false;
// Allocate downsampled-data buffers if needed
if(downsampled_output)
{
if(!alloc_downsampled_buffers(tif, d.comp_info, d.num_components)) return false;
sp.scancount=libjpeg.DCTSIZE; // mark buffer empty
}
return true;
}
// Decode a chunk of pixels.
// "Standard" case: returned data is not downsampled.
static bool JPEGDecode(TIFF tif, byte[] buf, int cc, ushort s)
{
JPEGState sp=tif.tif_data as JPEGState;
jpeg_decompress d=(jpeg_decompress)sp.comm;
int nrows=cc/sp.bytesperline;
if((cc%sp.bytesperline)!=0) TIFFWarningExt(tif.tif_clientdata, tif.tif_name, "fractional scanline not read");
if(nrows>(int)d.image_height) nrows=(int)d.image_height;
// data is expected to be read in multiples of a scanline
if(nrows!=0)
{
if(sp.scanlineBuffer[0]==null||sp.scanlineBuffer[0].Length<sp.bytesperline)
sp.scanlineBuffer[0]=new byte[sp.bytesperline];
int buf_ind=0;
do
{
// In the libjpeg6b 8bit case. We read directly into the TIFF buffer.
if(TIFFjpeg_read_scanlines(sp, sp.scanlineBuffer, 1)!=1) return false;
sp.scanlineBuffer[0].CopyTo(buf, buf_ind);
tif.tif_row++;
buf_ind+=sp.bytesperline;
cc-=sp.bytesperline;
nrows--;
} while(nrows>0);
}
// Close down the decompressor if we've finished the strip or tile.
return (d.output_scanline<d.output_height)||TIFFjpeg_finish_decompress(sp);
}
// Decode a chunk of pixels.
// Returned data is downsampled per sampling factors.
static bool JPEGDecodeRaw(TIFF tif, byte[] buf, int cc, ushort s)
{
JPEGState sp=tif.tif_data as JPEGState;
jpeg_decompress d=(jpeg_decompress)sp.comm;
int nrows=(int)d.image_height;
// data is expected to be read in multiples of a scanline
if(nrows!=0)
{
// Cb,Cr both have sampling factors 1, so this is correct
uint clumps_per_line=d.comp_info[1].downsampled_width;
int samples_per_clump=sp.samplesperclump;
do
{
// Reload downsampled-data buffer if needed
if(sp.scancount>=libjpeg.DCTSIZE)
{
int n=d.max_v_samp_factor*libjpeg.DCTSIZE;
if(TIFFjpeg_read_raw_data(sp, sp.ds_buffer, n)!=n) return false;
sp.scancount=0;
}
// Fastest way to unseparate data is to make one pass
// over the scanline for each row of each component.
int clumpoffset=0; // first sample in clump
int buf_offset=0;
for(int ci=0; ci<d.num_components; ci++)
{
jpeg_component_info compptr=d.comp_info[ci];
int hsamp=compptr.h_samp_factor;
int vsamp=compptr.v_samp_factor;
for(int ypos=0; ypos<vsamp; ypos++)
{
byte[] ds=sp.ds_buffer[ci][sp.scancount*vsamp+ypos];
uint inptr=0;
int outptr=buf_offset+clumpoffset;
uint nclump;
if(hsamp==1)
{ // fast path for at least Cb and Cr
for(nclump=clumps_per_line; nclump-->0; )
{
buf[outptr]=ds[inptr++];
outptr+=samples_per_clump;
}
}
else
{ // general case
for(nclump=clumps_per_line; nclump-->0; )
{
for(int xpos=0; xpos<hsamp; xpos++) buf[outptr+xpos]=ds[inptr++];
outptr+=samples_per_clump;
}
}
clumpoffset+=hsamp;
}
}
sp.scancount++;
tif.tif_row+=sp.v_sampling;
// increment/decrement of buf and cc is still incorrect, but should not matter
// TODO: resolve this
buf_offset+=sp.bytesperline;
cc-=sp.bytesperline;
nrows-=sp.v_sampling;
} while(nrows>0);
}
// Close down the decompressor if done.
return d.output_scanline<d.output_height||TIFFjpeg_finish_decompress(sp);
}
// JPEG Encoding.
static void unsuppress_quant_table(JPEGState sp, int tblno)
{
jpeg_compress c=(jpeg_compress)sp.comm;
JQUANT_TBL qtbl=c.quant_tbl_ptrs[tblno];
if(qtbl!=null) qtbl.sent_table=false;
}
static void unsuppress_huff_table(JPEGState sp, int tblno)
{
jpeg_compress c=(jpeg_compress)sp.comm;
JHUFF_TBL htbl=c.dc_huff_tbl_ptrs[tblno];
if(htbl!=null) htbl.sent_table=false;
htbl=c.ac_huff_tbl_ptrs[tblno];
if(htbl!=null) htbl.sent_table=false;
}
static bool prepare_JPEGTables(TIFF tif)
{
JPEGState sp=tif.tif_data as JPEGState;
JPEGInitializeLibJPEG(tif, false, false);
// Initialize quant tables for current quality setting
if(!TIFFjpeg_set_quality(sp, sp.jpegquality, false)) return false;