-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtif_dirread.cs
executable file
·1801 lines (1607 loc) · 57.9 KB
/
tif_dirread.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
// tif_dirread.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.
//
// Directory Read Support Routines.
using System;
using System.Collections.Generic;
using System.Text;
namespace Free.Ports.LibTiff
{
public static partial class libtiff
{
const int IGNORE=0; // tag placeholder used below
// Read the next TIFF directory from a file
// and convert it to the internal format.
// We read directories sequentially.
public static bool TIFFReadDirectory(TIFF tif)
{
string module="TIFFReadDirectory";
ushort iv;
uint v;
TIFFFieldInfo fip;
bool diroutoforderwarning=false;
bool haveunknowntags=false;
tif.tif_diroff=tif.tif_nextdiroff;
// Check whether we have the last offset or bad offset (IFD looping).
if(!TIFFCheckDirOffset(tif, tif.tif_nextdiroff)) return false;
// Cleanup any previous compression state.
tif.tif_cleanup(tif);
tif.tif_curdir++;
List<TIFFDirEntry> dir=null;
ushort dircount=TIFFFetchDirectory(tif, tif.tif_nextdiroff, ref dir, ref tif.tif_nextdiroff);
if(dircount==0)
{
TIFFErrorExt(tif.tif_clientdata, module, "{0}: Failed to read directory at offset{1}", tif.tif_name, tif.tif_nextdiroff);
return false;
}
tif.tif_flags&=~TIF_FLAGS.TIFF_BEENWRITING; // reset before new dir
// Setup default value and then make a pass over
// the fields to check type and tag information,
// and to extract info required to size data
// structures. A second pass is made afterwards
// to read in everthing not taken in the first pass.
TIFFDirectory td=tif.tif_dir;
// free any old stuff and reinit
TIFFFreeDirectory(tif);
TIFFDefaultDirectory(tif);
// Electronic Arts writes gray-scale TIFF files
// without a PlanarConfiguration directory entry.
// Thus we setup a default value here, even though
// the TIFF spec says there is no default value.
TIFFSetField(tif, TIFFTAG.PLANARCONFIG, PLANARCONFIG.CONTIG);
// Sigh, we must make a separate pass through the
// directory for the following reason:
//
// We must process the Compression tag in the first pass
// in order to merge in codec-private tag definitions (otherwise
// we may get complaints about unknown tags). However, the
// Compression tag may be dependent on the SamplesPerPixel
// tag value because older TIFF specs permited Compression
// to be written as a SamplesPerPixel-count tag entry.
// Thus if we don't first figure out the correct SamplesPerPixel
// tag value then we may end up ignoring the Compression tag
// value because it has an incorrect count value (if the
// true value of SamplesPerPixel is not 1).
//
// It sure would have been nice if Aldus had really thought
// this stuff through carefully.
foreach(TIFFDirEntry dp in dir)
{
if((tif.tif_flags&TIF_FLAGS.TIFF_SWAB)!=0)
{
TIFFSwab(ref dp.tdir_tag);
TIFFSwab(ref dp.tdir_type);
TIFFSwab(ref dp.tdir_count);
TIFFSwab(ref dp.tdir_offset);
}
if((TIFFTAG)dp.tdir_tag==TIFFTAG.SAMPLESPERPIXEL)
{
if(!TIFFFetchNormalTag(tif, dp)) return false;
dp.tdir_tag=IGNORE;
}
}
// First real pass over the directory.
int fix=0;
foreach(TIFFDirEntry dp in dir)
{
if(dp.tdir_tag==IGNORE) continue;
if(fix>=tif.tif_fieldinfo.Count) fix=0;
// Silicon Beach (at least) writes unordered
// directory tags (violating the spec). Handle
// it here, but be obnoxious (maybe they'll fix it?).
if(dp.tdir_tag<(ushort)tif.tif_fieldinfo[fix].field_tag)
{
if(!diroutoforderwarning)
{
TIFFWarningExt(tif.tif_clientdata, module, "{0}: invalid TIFF directory; tags are not sorted in ascending order", tif.tif_name);
diroutoforderwarning=true;
}
fix=0; // O(n^2)
}
while(fix<tif.tif_fieldinfo.Count&&(ushort)tif.tif_fieldinfo[fix].field_tag<dp.tdir_tag) fix++;
if(fix>=tif.tif_fieldinfo.Count||(ushort)tif.tif_fieldinfo[fix].field_tag!=dp.tdir_tag)
{
// Unknown tag ... we'll deal with it below
haveunknowntags=true;
continue;
}
// Null out old tags that we ignore.
if(tif.tif_fieldinfo[fix].field_bit==FIELD.IGNORE)
{
dp.tdir_tag=IGNORE;
continue;
}
// Check data type.
fip=tif.tif_fieldinfo[fix];
bool docontinue=false;
while(dp.tdir_type!=(ushort)fip.field_type&&fix<tif.tif_fieldinfo.Count)
{
if(fip.field_type==TIFFDataType.TIFF_ANY) break; // wildcard
fip=tif.tif_fieldinfo[++fix];
if(fix>=tif.tif_fieldinfo.Count||(ushort)fip.field_tag!=dp.tdir_tag)
{
TIFFWarningExt(tif.tif_clientdata, module, "{0}: wrong data type {1} for \"{2}\"; tag ignored", tif.tif_name, dp.tdir_type, tif.tif_fieldinfo[fix-1].field_name);
dp.tdir_tag=IGNORE;
docontinue=true;
break;
}
}
if(docontinue) continue;
// Check count if known in advance.
if(fip.field_readcount!=TIFF_VARIABLE)
{
uint expected=(fip.field_readcount==TIFF_SPP)?td.td_samplesperpixel:(uint)fip.field_readcount;
if(!CheckDirCount(tif, dp, expected))
{
dp.tdir_tag=IGNORE;
continue;
}
}
switch((TIFFTAG)dp.tdir_tag)
{
case TIFFTAG.COMPRESSION:
// The 5.0 spec says the Compression tag has
// one value, while earlier specs say it has
// one value per sample. Because of this, we
// accept the tag if one value is supplied.
if(dp.tdir_count==1)
{
//was v = TIFFExtractData(tif, dp.tdir_type, dp.tdir_offset);
v=(tif.tif_header.tiff_magic==TIFF_BIGENDIAN?(dp.tdir_offset>>tif_typeshift[dp.tdir_type])&tif_typemask[dp.tdir_type]:dp.tdir_offset&tif_typemask[dp.tdir_type]);
if(!TIFFSetField(tif, (TIFFTAG)dp.tdir_tag, (ushort)v)) return false;
break;
// XXX: workaround for broken TIFFs
}
if((TIFFDataType)dp.tdir_type==TIFFDataType.TIFF_LONG)
{
if(!TIFFFetchPerSampleLongs(tif, dp, out v)||!TIFFSetField(tif, (TIFFTAG)dp.tdir_tag, (ushort)v))
return false;
}
else
{
if(!TIFFFetchPerSampleShorts(tif, dp, out iv)||!TIFFSetField(tif, (TIFFTAG)dp.tdir_tag, iv))
return false;
}
dp.tdir_tag=IGNORE;
break;
case TIFFTAG.STRIPOFFSETS:
case TIFFTAG.STRIPBYTECOUNTS:
case TIFFTAG.TILEOFFSETS:
case TIFFTAG.TILEBYTECOUNTS:
TIFFSetFieldBit(tif, fip.field_bit);
break;
case TIFFTAG.IMAGEWIDTH:
case TIFFTAG.IMAGELENGTH:
case TIFFTAG.IMAGEDEPTH:
case TIFFTAG.TILELENGTH:
case TIFFTAG.TILEWIDTH:
case TIFFTAG.TILEDEPTH:
case TIFFTAG.PLANARCONFIG:
case TIFFTAG.ROWSPERSTRIP:
case TIFFTAG.EXTRASAMPLES:
if(!TIFFFetchNormalTag(tif, dp)) return false;
dp.tdir_tag=IGNORE;
break;
}
}
// If we saw any unknown tags, make an extra pass over the directory
// to deal with them. This must be done separately because the tags
// could have become known when we registered a codec after finding
// the Compression tag. In a correctly-sorted directory there's
// no problem because Compression will come before any codec-private
// tags, but if the sorting is wrong that might not hold.
if(haveunknowntags)
{
fix=0;
foreach(TIFFDirEntry dp in dir)
{
if(dp.tdir_tag==IGNORE) continue;
if(fix>=tif.tif_fieldinfo.Count||dp.tdir_tag<(ushort)tif.tif_fieldinfo[fix].field_tag) fix=0; // O(n^2)
while(fix<tif.tif_fieldinfo.Count&&(ushort)tif.tif_fieldinfo[fix].field_tag<dp.tdir_tag) fix++;
if(fix>=tif.tif_fieldinfo.Count||(ushort)tif.tif_fieldinfo[fix].field_tag!=dp.tdir_tag)
{
TIFFWarningExt(tif.tif_clientdata, module, "{0}: unknown field with tag %d (0x{1:X}) encountered", tif.tif_name, dp.tdir_tag, dp.tdir_tag);
if(!_TIFFMergeFieldInfo(tif, TIFFCreateAnonFieldInfo(tif, (TIFFTAG)dp.tdir_tag, (TIFFDataType)dp.tdir_type)))
{
TIFFWarningExt(tif.tif_clientdata, module, "Registering anonymous field with tag {0} (0x{1:X}) failed", dp.tdir_tag, dp.tdir_tag);
dp.tdir_tag=IGNORE;
continue;
}
fix=0;
while(fix<tif.tif_fieldinfo.Count&&(ushort)tif.tif_fieldinfo[fix].field_tag<dp.tdir_tag) fix++;
}
// Check data type.
fip=tif.tif_fieldinfo[fix];
while(dp.tdir_type!=(ushort)fip.field_type&&fix<tif.tif_fieldinfo.Count)
{
if(fip.field_type==TIFFDataType.TIFF_ANY) // wildcard
break;
fip=tif.tif_fieldinfo[++fix];
if(fix>=tif.tif_fieldinfo.Count||(ushort)fip.field_tag!=dp.tdir_tag)
{
TIFFWarningExt(tif.tif_clientdata, module, "{0}: wrong data type {1} for \"{2}\"; tag ignored", tif.tif_name, dp.tdir_type, tif.tif_fieldinfo[fix-1].field_name);
dp.tdir_tag=IGNORE;
break;
}
}
}
}
// Allocate directory structure and setup defaults.
if(!TIFFFieldSet(tif, FIELD.IMAGEDIMENSIONS))
{
MissingRequired(tif, "ImageLength");
return false;
}
// Setup appropriate structures (by strip or by tile)
if(!TIFFFieldSet(tif, FIELD.TILEDIMENSIONS))
{
td.td_nstrips=(uint)TIFFNumberOfStrips(tif);
td.td_tilewidth=td.td_imagewidth;
td.td_tilelength=td.td_rowsperstrip;
td.td_tiledepth=td.td_imagedepth;
tif.tif_flags&=~TIF_FLAGS.TIFF_ISTILED;
}
else
{
td.td_nstrips=(uint)TIFFNumberOfTiles(tif);
tif.tif_flags|=TIF_FLAGS.TIFF_ISTILED;
}
if(td.td_nstrips==0)
{
TIFFErrorExt(tif.tif_clientdata, module, "{0}: cannot handle zero number of {1}", tif.tif_name, isTiled(tif)?"tiles":"strips");
return false;
}
td.td_stripsperimage=td.td_nstrips;
if(td.td_planarconfig==PLANARCONFIG.SEPARATE) td.td_stripsperimage/=td.td_samplesperpixel;
if(!TIFFFieldSet(tif, FIELD.STRIPOFFSETS))
{
MissingRequired(tif, isTiled(tif)?"TileOffsets":"StripOffsets");
return false;
}
// Second pass: extract other information.
foreach(TIFFDirEntry dp in dir)
{
if(dp.tdir_tag==IGNORE) continue;
switch((TIFFTAG)dp.tdir_tag)
{
case TIFFTAG.MINSAMPLEVALUE:
case TIFFTAG.MAXSAMPLEVALUE:
case TIFFTAG.BITSPERSAMPLE:
case TIFFTAG.DATATYPE:
case TIFFTAG.SAMPLEFORMAT:
// The 5.0 spec says the Compression tag has
// one value, while earlier specs say it has
// one value per sample. Because of this, we
// accept the tag if one value is supplied.
//
// The MinSampleValue, MaxSampleValue, BitsPerSample
// DataType and SampleFormat tags are supposed to be
// written as one value/sample, but some vendors
// incorrectly write one value only -- so we accept
// that as well (yech). Other vendors write correct
// value for NumberOfSamples, but incorrect one for
// BitsPerSample and friends, and we will read this
// too.
if(dp.tdir_count==1)
{
//was v = TIFFExtractData(tif, dp.tdir_type, dp.tdir_offset);
v=(tif.tif_header.tiff_magic==TIFF_BIGENDIAN?(dp.tdir_offset>>tif_typeshift[dp.tdir_type])&tif_typemask[dp.tdir_type]:dp.tdir_offset&tif_typemask[dp.tdir_type]);
if(!TIFFSetField(tif, (TIFFTAG)dp.tdir_tag, (ushort)v)) return false;
// XXX: workaround for broken TIFFs
}
else if((TIFFTAG)dp.tdir_tag==TIFFTAG.BITSPERSAMPLE&&(TIFFDataType)dp.tdir_type==TIFFDataType.TIFF_LONG)
{
if(!TIFFFetchPerSampleLongs(tif, dp, out v)||!TIFFSetField(tif, (TIFFTAG)dp.tdir_tag, (ushort)v))
return false;
}
else
{
if(!TIFFFetchPerSampleShorts(tif, dp, out iv)||!TIFFSetField(tif, (TIFFTAG)dp.tdir_tag, iv))
return false;
}
break;
case TIFFTAG.SMINSAMPLEVALUE:
case TIFFTAG.SMAXSAMPLEVALUE:
{
double dv=0.0;
if(!TIFFFetchPerSampleAnys(tif, dp, out dv)||!TIFFSetField(tif, (TIFFTAG)dp.tdir_tag, dv))
return false;
}
break;
case TIFFTAG.STRIPOFFSETS:
case TIFFTAG.TILEOFFSETS:
if(!TIFFFetchStripThing(tif, dp, td.td_nstrips, ref td.td_stripoffset)) return false;
break;
case TIFFTAG.STRIPBYTECOUNTS:
case TIFFTAG.TILEBYTECOUNTS:
if(!TIFFFetchStripThing(tif, dp, td.td_nstrips, ref td.td_stripbytecount)) return false;
break;
case TIFFTAG.COLORMAP:
case TIFFTAG.TRANSFERFUNCTION:
{
// TransferFunction can have either 1x or 3x
// data values; Colormap can have only 3x
// items.
v=1u<<td.td_bitspersample;
if((TIFFTAG)dp.tdir_tag==TIFFTAG.COLORMAP||dp.tdir_count!=v)
{
if(!CheckDirCount(tif, dp, 3*v)) break;
}
//v*=sizeof(ushort);
ushort[] cp=null;
try
{
cp=new ushort[dp.tdir_count];
}
catch
{
TIFFErrorExt(tif.tif_clientdata, tif.tif_name, "No space to read \"TransferFunction\" tag");
}
if(cp==null) break;
if(TIFFFetchData(tif, dp, cp)==0) break;
// This deals with there being
// only one array to apply to
// all samples.
uint c=1u<<td.td_bitspersample;
if(dp.tdir_count==c) TIFFSetField(tif, (TIFFTAG)dp.tdir_tag, cp, cp, cp);
else
{
try
{
ushort[] cp1=new ushort[v];
ushort[] cp2=new ushort[v];
ushort[] cp3=new ushort[v];
Array.Copy(cp, 0*v, cp1, 0, v);
Array.Copy(cp, 1*v, cp2, 0, v);
Array.Copy(cp, 2*v, cp3, 0, v);
TIFFSetField(tif, (TIFFTAG)dp.tdir_tag, cp1, cp2, cp3);
}
catch
{
TIFFErrorExt(tif.tif_clientdata, tif.tif_name, "No space to read \"TransferFunction\" tag");
}
}
}
break;
case TIFFTAG.PAGENUMBER:
case TIFFTAG.HALFTONEHINTS:
case TIFFTAG.YCBCRSUBSAMPLING:
case TIFFTAG.DOTRANGE:
TIFFFetchShortPair(tif, dp);
break;
case TIFFTAG.REFERENCEBLACKWHITE:
TIFFFetchRefBlackWhite(tif, dp);
break;
// BEGIN REV 4.0 COMPATIBILITY
case TIFFTAG.OSUBFILETYPE:
v=0;
//was switch(TIFFExtractData(tif, dp.tdir_type, dp.tdir_offset))
switch((OFILETYPE)(tif.tif_header.tiff_magic==TIFF_BIGENDIAN?(dp.tdir_offset>>tif_typeshift[dp.tdir_type])&tif_typemask[dp.tdir_type]:dp.tdir_offset&tif_typemask[dp.tdir_type]))
{
case OFILETYPE.REDUCEDIMAGE: v=(uint)FILETYPE.REDUCEDIMAGE; break;
case OFILETYPE.PAGE: v=(uint)FILETYPE.PAGE; break;
}
if(v!=0) TIFFSetField(tif, TIFFTAG.SUBFILETYPE, v);
break;
// END REV 4.0 COMPATIBILITY
default:
TIFFFetchNormalTag(tif, dp);
break;
}
}
// Verify Palette image has a Colormap.
if(td.td_photometric==PHOTOMETRIC.PALETTE&&!TIFFFieldSet(tif, FIELD.COLORMAP))
{
MissingRequired(tif, "Colormap");
return false;
}
// Attempt to deal with a missing StripByteCounts tag.
if(!TIFFFieldSet(tif, FIELD.STRIPBYTECOUNTS))
{
// Some manufacturers violate the spec by not giving
// the size of the strips. In this case, assume there
// is one uncompressed strip of data.
if((td.td_planarconfig==PLANARCONFIG.CONTIG&&td.td_nstrips>1)||
(td.td_planarconfig==PLANARCONFIG.SEPARATE&&td.td_nstrips!=td.td_samplesperpixel))
{
MissingRequired(tif, "StripByteCounts");
return false;
}
TIFFWarningExt(tif.tif_clientdata, module, "{0}: TIFF directory is missing required \"{1}\" field, calculating from imagelength", tif.tif_name, TIFFFieldWithTag(tif, TIFFTAG.STRIPBYTECOUNTS).field_name);
if(EstimateStripByteCounts(tif, dir)<0) return false;
// Assume we have wrong StripByteCount value (in case of single strip) in
// following cases:
// - it is equal to zero along with StripOffset;
// - it is larger than file itself (in case of uncompressed image);
// - it is smaller than the size of the bytes per row multiplied on the
// number of rows. The last case should not be checked in the case of
// writing new image, because we may do not know the exact strip size
// until the whole image will be written and directory dumped out.
}
else if(td.td_nstrips==1&&td.td_stripoffset[0]!=0&&((td.td_stripbytecount[0]==0&&td.td_stripoffset[0]!=0)||
(td.td_compression==COMPRESSION.NONE&&td.td_stripbytecount[0]>TIFFGetFileSize(tif)-td.td_stripoffset[0])||
(tif.tif_mode==O.RDONLY&&td.td_compression==COMPRESSION.NONE&&td.td_stripbytecount[0]<TIFFScanlineSize(tif)*td.td_imagelength)))
{
// XXX: Plexus (and others) sometimes give a value of zero for
// a tag when they don't know what the correct value is! Try
// and handle the simple case of estimating the size of a one
// strip image.
TIFFWarningExt(tif.tif_clientdata, module, "{0}: Bogus \"{1}\" field, ignoring and calculating from imagelength", tif.tif_name, TIFFFieldWithTag(tif, TIFFTAG.STRIPBYTECOUNTS).field_name);
if(EstimateStripByteCounts(tif, dir)<0) return false;
}
else if(td.td_planarconfig==PLANARCONFIG.CONTIG&&td.td_nstrips>2&&td.td_compression==COMPRESSION.NONE&&td.td_stripbytecount[0]!=td.td_stripbytecount[1]&&td.td_stripbytecount[0]!=0&&td.td_stripbytecount[1]!=0)
{
// XXX: Some vendors fill StripByteCount array with absolutely
// wrong values (it can be equal to StripOffset array, for
// example). Catch this case here.
TIFFWarningExt(tif.tif_clientdata, module, "{0}: Wrong \"{1}\" field, ignoring and calculating from imagelength", tif.tif_name, TIFFFieldWithTag(tif, TIFFTAG.STRIPBYTECOUNTS).field_name);
if(EstimateStripByteCounts(tif, dir)<0) return false;
}
dir=null;
if(!TIFFFieldSet(tif, FIELD.MAXSAMPLEVALUE)) td.td_maxsamplevalue=(ushort)((1<<td.td_bitspersample)-1);
// Setup default compression scheme.
// XXX: We can optimize checking for the strip bounds using the sorted
// bytecounts array. See also comments for TIFFAppendToStrip()
// function in tif_write.cs.
if(td.td_nstrips>1)
{
td.td_stripbytecountsorted=1;
for(uint strip=1; strip<td.td_nstrips; strip++)
{
if(td.td_stripoffset[strip-1]>td.td_stripoffset[strip])
{
td.td_stripbytecountsorted=0;
break;
}
}
}
if(!TIFFFieldSet(tif, FIELD.COMPRESSION)) TIFFSetField(tif, TIFFTAG.COMPRESSION, COMPRESSION.NONE);
// Some manufacturers make life difficult by writing
// large amounts of uncompressed data as a single strip.
// This is contrary to the recommendations of the spec.
// The following makes an attempt at breaking such images
// into strips closer to the recommended 8k bytes. A
// side effect, however, is that the RowsPerStrip tag
// value may be changed.
if(td.td_nstrips==1&&td.td_compression==COMPRESSION.NONE&&(tif.tif_flags&(TIF_FLAGS.TIFF_STRIPCHOP|TIF_FLAGS.TIFF_ISTILED))==TIF_FLAGS.TIFF_STRIPCHOP)
ChopUpSingleUncompressedStrip(tif);
// Reinitialize i/o since we are starting on a new directory.
tif.tif_row=0xffffffff;
tif.tif_curstrip=0xffffffff;
tif.tif_col=0xffffffff;
tif.tif_curtile=0xffffffff;
tif.tif_tilesize=-1;
tif.tif_scanlinesize=(uint)TIFFScanlineSize(tif);
if(tif.tif_scanlinesize==0)
{
TIFFErrorExt(tif.tif_clientdata, module, "{0}: cannot handle zero scanline size", tif.tif_name);
return false;
}
if(isTiled(tif))
{
tif.tif_tilesize=TIFFTileSize(tif);
if(tif.tif_tilesize==0)
{
TIFFErrorExt(tif.tif_clientdata, module, "{0}: cannot handle zero tile size", tif.tif_name);
return false;
}
}
else
{
if(TIFFStripSize(tif)==0)
{
TIFFErrorExt(tif.tif_clientdata, module, "{0}: cannot handle zero strip size", tif.tif_name);
return false;
}
}
return true;
}
public static TIFFDirEntry TIFFReadDirectoryFind(List<TIFFDirEntry> dir, ushort dircount, ushort tagid)
{
foreach(TIFFDirEntry m in dir)
{
if(m.tdir_tag==tagid) return m;
}
return null;
}
// Read custom directory from the arbitarry offset.
// The code is very similar to TIFFReadDirectory().
public static bool TIFFReadCustomDirectory(TIFF tif, uint diroff, List<TIFFFieldInfo> info)
{
string module="TIFFReadCustomDirectory";
TIFFSetupFieldInfo(tif, info);
List<TIFFDirEntry> dir=null;
uint nextdiroff=0;
ushort dircount=TIFFFetchDirectory(tif, diroff, ref dir, ref nextdiroff);
if(dircount==0)
{
TIFFErrorExt(tif.tif_clientdata, module, "{0}: Failed to read custom directory at offset {1}", tif.tif_name, diroff);
return false;
}
TIFFFreeDirectory(tif);
TIFFDirectory td=tif.tif_dir;
td.Clear();
int fix=0;
foreach(TIFFDirEntry dp in dir)
{
if((tif.tif_flags&TIF_FLAGS.TIFF_SWAB)!=0)
{
TIFFSwab(ref dp.tdir_tag);
TIFFSwab(ref dp.tdir_type);
TIFFSwab(ref dp.tdir_count);
TIFFSwab(ref dp.tdir_offset);
}
if(fix>=tif.tif_fieldinfo.Count||dp.tdir_tag==IGNORE) continue;
while(fix<tif.tif_fieldinfo.Count&&tif.tif_fieldinfo[fix].field_tag<(TIFFTAG)dp.tdir_tag) fix++;
if(fix>=tif.tif_fieldinfo.Count||tif.tif_fieldinfo[fix].field_tag!=(TIFFTAG)dp.tdir_tag)
{
TIFFWarningExt(tif.tif_clientdata, module, "{0}: unknown field with tag {1} (0x{1:X}) encountered", tif.tif_name, dp.tdir_tag);
if(!_TIFFMergeFieldInfo(tif, TIFFCreateAnonFieldInfo(tif, (TIFFTAG)dp.tdir_tag, (TIFFDataType)dp.tdir_type)))
{
TIFFWarningExt(tif.tif_clientdata, module, "Registering anonymous field with tag {0} (0x{0:X}) failed", dp.tdir_tag);
dp.tdir_tag=IGNORE;
continue;
}
fix=0;
while(fix<tif.tif_fieldinfo.Count&&tif.tif_fieldinfo[fix].field_tag<(TIFFTAG)dp.tdir_tag) fix++;
}
// Null out old tags that we ignore.
if(tif.tif_fieldinfo[fix].field_bit==FIELD.IGNORE)
{
dp.tdir_tag=IGNORE;
continue;
}
// Check data type.
TIFFFieldInfo fip=tif.tif_fieldinfo[fix];
bool docontinue=false;
while(dp.tdir_type!=(ushort)fip.field_type&&fix<tif.tif_fieldinfo.Count)
{
if(fip.field_type==TIFFDataType.TIFF_ANY) break; // wildcard
fip=tif.tif_fieldinfo[++fix];
if(fix>=tif.tif_fieldinfo.Count||fip.field_tag!=(TIFFTAG)dp.tdir_tag)
{
TIFFWarningExt(tif.tif_clientdata, module, "{0}: wrong data type {1} for \"{2}\"; tag ignored", tif.tif_name, dp.tdir_type, tif.tif_fieldinfo[fix-1].field_name);
dp.tdir_tag=IGNORE;
docontinue=true;
break;
}
}
if(docontinue) continue;
// Check count if known in advance.
if(fip.field_readcount!=TIFF_VARIABLE)
{
uint expected=(fip.field_readcount==TIFF_SPP)?(uint)td.td_samplesperpixel:(uint)fip.field_readcount;
if(!CheckDirCount(tif, dp, expected))
{
dp.tdir_tag=IGNORE;
continue;
}
}
// EXIF tags which need to be specifically processed.
switch(dp.tdir_tag)
{
case (ushort)EXIFTAG.SUBJECTDISTANCE: TIFFFetchSubjectDistance(tif, dp);
break;
default:
TIFFFetchNormalTag(tif, dp);
break;
}
}
dir=null;
return true;
}
// EXIF is important special case of custom IFD, so we have a special
// function to read it.
public static bool TIFFReadEXIFDirectory(TIFF tif, uint diroff)
{
return TIFFReadCustomDirectory(tif, diroff, exifFieldInfo);
}
static int EstimateStripByteCounts(TIFF tif, List<TIFFDirEntry> dir)
{
string module="EstimateStripByteCounts";
TIFFDirectory td=tif.tif_dir;
uint strip;
try
{
td.td_stripbytecount=new uint[td.td_nstrips];
}
catch
{
TIFFErrorExt(tif.tif_clientdata, tif.tif_name, "No space for \"StripByteCounts\" array");
}
if(td.td_stripbytecount==null) return -1;
if(td.td_compression!=COMPRESSION.NONE)
{
//uint space=sizeof(TIFFHeader)+sizeof(ushort)+(dir.Count*sizeof(TIFFDirEntry))+sizeof(uint);
uint space=(uint)(8+2+(dir.Count*12)+4);
uint filesize=TIFFGetFileSize(tif);
// calculate amount of space used by indirect values
foreach(TIFFDirEntry dp in dir)
{
uint cc=(uint)TIFFDataWidth((TIFFDataType)dp.tdir_type);
if(cc==0)
{
TIFFErrorExt(tif.tif_clientdata, module, "{0}: Cannot determine size of unknown tag type {1}", tif.tif_name, dp.tdir_type);
return -1;
}
cc=cc*dp.tdir_count;
if(cc>4) space+=cc; // 4: sizeof(uint)
}
space=filesize-space;
if(td.td_planarconfig==PLANARCONFIG.SEPARATE) space/=td.td_samplesperpixel;
for(strip=0; strip<td.td_nstrips; strip++) td.td_stripbytecount[strip]=space;
// This gross hack handles the case were the offset to
// the last strip is past the place where we think the strip
// should begin. Since a strip of data must be contiguous,
// it's safe to assume that we've overestimated the amount
// of data in the strip and trim this number back accordingly.
strip--;
if(((uint)(td.td_stripoffset[strip]+td.td_stripbytecount[strip]))>filesize) td.td_stripbytecount[strip]=filesize-td.td_stripoffset[strip];
}
else if(isTiled(tif))
{
uint bytespertile=(uint)TIFFTileSize(tif);
for(strip=0; strip<td.td_nstrips; strip++) td.td_stripbytecount[strip]=bytespertile;
}
else
{
uint rowbytes=(uint)TIFFScanlineSize(tif);
uint rowsperstrip=td.td_imagelength/td.td_stripsperimage;
for(strip=0; strip<td.td_nstrips; strip++) td.td_stripbytecount[strip]=rowbytes*rowsperstrip;
}
TIFFSetFieldBit(tif, FIELD.STRIPBYTECOUNTS);
if(!TIFFFieldSet(tif, FIELD.ROWSPERSTRIP)) td.td_rowsperstrip=td.td_imagelength;
return 1;
}
static void MissingRequired(TIFF tif, string tagname)
{
string module="MissingRequired";
TIFFErrorExt(tif.tif_clientdata, module, "{0}: TIFF directory is missing required \"{1}\" field", tif.tif_name, tagname);
}
// Check the directory offset against the list of already seen directory
// offsets. This is a trick to prevent IFD looping. The one can create TIFF
// file with looped directory pointers. We will maintain a list of already
// seen directories and check every IFD offset against that list.
static bool TIFFCheckDirOffset(TIFF tif, uint diroff)
{
if(diroff==0) return false; // no more directories
for(int n=0; n<tif.tif_dirnumber; n++)
{
if(tif.tif_dirlist[n]==tif.tif_diroff) return false;
}
try
{
tif.tif_dirlist.Add(tif.tif_diroff);
tif.tif_dirnumber++;
}
catch
{
TIFFErrorExt(tif.tif_clientdata, "TIFFCheckDirOffset", "{0}: Failed to allocate space for IFD list", tif.tif_name);
return false;
}
return true;
}
// Check the count field of a directory
// entry against a known value. The caller
// is expected to skip/ignore the tag if
// there is a mismatch.
static bool CheckDirCount(TIFF tif, TIFFDirEntry dir, uint count)
{
if(count>dir.tdir_count)
{
TIFFWarningExt(tif.tif_clientdata, tif.tif_name, "incorrect count for field \"{0}\" ({1}, expecting {2}); tag ignored", TIFFFieldWithTag(tif, (TIFFTAG)dir.tdir_tag).field_name, dir.tdir_count, count);
return false;
}
if(count<dir.tdir_count)
{
TIFFWarningExt(tif.tif_clientdata, tif.tif_name, "incorrect count for field \"{0}\" ({1}, expecting {2}); tag trimmed", TIFFFieldWithTag(tif, (TIFFTAG)dir.tdir_tag).field_name, dir.tdir_count, count);
return true;
}
return true;
}
// Read IFD structure from the specified offset. If the pointer to
// nextdiroff variable has been specified, read it too. Function returns a
// number of fields in the directory or 0 if failed.
static ushort TIFFFetchDirectory(TIFF tif, uint diroff, ref List<TIFFDirEntry> pdir, ref uint nextdiroff)
{
string module="TIFFFetchDirectory";
tif.tif_diroff=diroff;
if(!SeekOK(tif, tif.tif_diroff))
{
TIFFErrorExt(tif.tif_clientdata, module, "{0}: Seek error accessing TIFF directory", tif.tif_name);
return 0;
}
ushort dircount;
if(!ReadOK(tif, out dircount))
{
TIFFErrorExt(tif.tif_clientdata, module, "{0}: Can not read TIFF directory count", tif.tif_name);
return 0;
}
if((tif.tif_flags&TIF_FLAGS.TIFF_SWAB)!=0) TIFFSwab(ref dircount);
List<TIFFDirEntry> dir=null;
try
{
dir=new List<TIFFDirEntry>();
}
catch
{
return 0;
}
if(!ReadOK(tif, dir, dircount))
{
TIFFErrorExt(tif.tif_clientdata, module, "{0}: Can not read TIFF directory", tif.tif_name);
return 0;
}
// Read offset to next directory for sequential scans.if needed.
if(nextdiroff!=0) ReadOK(tif, out nextdiroff);
if(nextdiroff!=0&&(tif.tif_flags&TIF_FLAGS.TIFF_SWAB)!=0) TIFFSwab(ref nextdiroff);
pdir=dir;
return dircount;
}
// Fetch a contiguous directory item.
static int TIFFFetchData(TIFF tif, TIFFDirEntry dir, byte[] cp)
{
uint w=(uint)TIFFDataWidth((TIFFDataType)dir.tdir_type);
// FIXME: butecount should have tsize_t type, but for now libtiff
// defines tsize_t as a signed 32-bit integer and we are losing
// ability to read arrays larger than 2^31 bytes. So we are using
// uint32 instead of tsize_t here.
uint cc=dir.tdir_count*w;
// Check for overflow.
if(dir.tdir_count==0||w==0||cc/w!=dir.tdir_count)
{
TIFFErrorExt(tif.tif_clientdata, tif.tif_name, "Error fetching data for field \"{0}\"", TIFFFieldWithTag(tif, (TIFFTAG)dir.tdir_tag).field_name);
return 0;
}
if(!SeekOK(tif, dir.tdir_offset))
{
TIFFErrorExt(tif.tif_clientdata, tif.tif_name, "Error fetching data for field \"{0}\"", TIFFFieldWithTag(tif, (TIFFTAG)dir.tdir_tag).field_name);
return 0;
}
if(!ReadOK(tif, cp, (int)cc))
{
TIFFErrorExt(tif.tif_clientdata, tif.tif_name, "Error fetching data for field \"{0}\"", TIFFFieldWithTag(tif, (TIFFTAG)dir.tdir_tag).field_name);
return 0;
}
if((tif.tif_flags&TIF_FLAGS.TIFF_SWAB)==0) return (int)cc;
switch((TIFFDataType)dir.tdir_type)
{
case TIFFDataType.TIFF_SHORT:
case TIFFDataType.TIFF_SSHORT:
TIFFSwabArrayOfShort(cp, dir.tdir_count);
break;
case TIFFDataType.TIFF_LONG:
case TIFFDataType.TIFF_SLONG:
case TIFFDataType.TIFF_FLOAT:
TIFFSwabArrayOfLong(cp, dir.tdir_count);
break;
case TIFFDataType.TIFF_RATIONAL:
case TIFFDataType.TIFF_SRATIONAL:
TIFFSwabArrayOfLong(cp, 2*dir.tdir_count);
break;
case TIFFDataType.TIFF_DOUBLE:
TIFFSwabArrayOfDouble(cp, dir.tdir_count);
break;
}
return (int)cc;
}
static int TIFFFetchData(TIFF tif, TIFFDirEntry dir, ushort[] cp)
{
byte[] buf=new byte[dir.tdir_count*2];
int ret=TIFFFetchData(tif, dir, buf);
if(ret==0) return 0;
for(int i=0; i<dir.tdir_count; i++) cp[i]=BitConverter.ToUInt16(buf, i*2);
return ret;
}
// Fetch an ASCII item from the file.
static int TIFFFetchString(TIFF tif, TIFFDirEntry dir, out string cp)
{
if(dir.tdir_count<=4)
{
uint l=dir.tdir_offset;
if((tif.tif_flags&TIF_FLAGS.TIFF_SWAB)!=0) TIFFSwab(ref l); // swab 'back' see in TIFFReadDirectory & TIFFReadCustomDirectory
cp=System.Text.Encoding.ASCII.GetString(BitConverter.GetBytes(l));
return 1;
}
cp=null;
byte[] buf=new byte[dir.tdir_count];
int ret=TIFFFetchData(tif, dir, buf);
if(ret==0) return 0;
cp=System.Text.Encoding.ASCII.GetString(buf);
return ret;
}
// Convert numerator+denominator to double.
static bool cvtRational(TIFF tif, TIFFDirEntry dir, uint num, uint denom, out double rv)
{
if(num==0&&denom==0)
{
rv=0;
return true;
}
if(denom==0)
{
TIFFErrorExt(tif.tif_clientdata, tif.tif_name, "{0}: Rational with zero denominator (num = {1})", TIFFFieldWithTag(tif, (TIFFTAG)dir.tdir_tag).field_name, num);
rv=double.NaN;
return false;
}
if((TIFFDataType)dir.tdir_type==TIFFDataType.TIFF_RATIONAL) rv=((double)num/(double)denom);
else rv=((double)(int)num/(double)(int)denom);
return true;
}
// Fetch a rational item from the file
// at offset off and return the value
// as a floating point number.
static double TIFFFetchRational(TIFF tif, TIFFDirEntry dir)
{
byte[] buf=new byte[8];
if(TIFFFetchData(tif, dir, buf)==0) return 1.0;
double v;
return !cvtRational(tif, dir, BitConverter.ToUInt32(buf, 0), BitConverter.ToUInt32(buf, 4), out v)?1.0:v;
}
// Fetch a single floating point value
// from the offset field and return it
// as a native float.
static float TIFFFetchFloat(TIFF tif, TIFFDirEntry dir)
{
return BitConverter.ToSingle(BitConverter.GetBytes(dir.tdir_offset), 0);
}
// Fetch a double item from the file
// at offset off and return the value.
static double TIFFFetchDouble(TIFF tif, TIFFDirEntry dir)
{