forked from openjdk/jdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TIFFIFD.java
1325 lines (1194 loc) · 51.1 KB
/
TIFFIFD.java
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
/*
* Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.imageio.plugins.tiff;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.imageio.IIOException;
import javax.imageio.plugins.tiff.BaselineTIFFTagSet;
import javax.imageio.plugins.tiff.TIFFDirectory;
import javax.imageio.plugins.tiff.TIFFField;
import javax.imageio.plugins.tiff.TIFFTag;
import javax.imageio.plugins.tiff.TIFFTagSet;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import static java.nio.charset.StandardCharsets.US_ASCII;
public class TIFFIFD extends TIFFDirectory {
private static final long MAX_SAMPLES_PER_PIXEL = 0xffff;
private static final long MAX_ASCII_SIZE = 0xffff;
private long stripOrTileByteCountsPosition = -1;
private long stripOrTileOffsetsPosition = -1;
private long lastPosition = -1;
//
// A set of tag numbers corresponding to tags essential to decoding
// the image and metadata required to interpret its samples.
//
private static volatile Set<Integer> essentialTags;
private static void initializeEssentialTags() {
Set<Integer> tags = essentialTags;
if (tags == null) {
essentialTags = Set.of(
BaselineTIFFTagSet.TAG_BITS_PER_SAMPLE,
BaselineTIFFTagSet.TAG_COLOR_MAP,
BaselineTIFFTagSet.TAG_COMPRESSION,
BaselineTIFFTagSet.TAG_EXTRA_SAMPLES,
BaselineTIFFTagSet.TAG_FILL_ORDER,
BaselineTIFFTagSet.TAG_ICC_PROFILE,
BaselineTIFFTagSet.TAG_IMAGE_LENGTH,
BaselineTIFFTagSet.TAG_IMAGE_WIDTH,
BaselineTIFFTagSet.TAG_JPEG_AC_TABLES,
BaselineTIFFTagSet.TAG_JPEG_DC_TABLES,
BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT,
BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH,
BaselineTIFFTagSet.TAG_JPEG_PROC,
BaselineTIFFTagSet.TAG_JPEG_Q_TABLES,
BaselineTIFFTagSet.TAG_JPEG_RESTART_INTERVAL,
BaselineTIFFTagSet.TAG_JPEG_TABLES,
BaselineTIFFTagSet.TAG_PHOTOMETRIC_INTERPRETATION,
BaselineTIFFTagSet.TAG_PLANAR_CONFIGURATION,
BaselineTIFFTagSet.TAG_PREDICTOR,
BaselineTIFFTagSet.TAG_REFERENCE_BLACK_WHITE,
BaselineTIFFTagSet.TAG_ROWS_PER_STRIP,
BaselineTIFFTagSet.TAG_SAMPLES_PER_PIXEL,
BaselineTIFFTagSet.TAG_SAMPLE_FORMAT,
BaselineTIFFTagSet.TAG_STRIP_BYTE_COUNTS,
BaselineTIFFTagSet.TAG_STRIP_OFFSETS,
BaselineTIFFTagSet.TAG_T4_OPTIONS,
BaselineTIFFTagSet.TAG_T6_OPTIONS,
BaselineTIFFTagSet.TAG_TILE_BYTE_COUNTS,
BaselineTIFFTagSet.TAG_TILE_LENGTH,
BaselineTIFFTagSet.TAG_TILE_OFFSETS,
BaselineTIFFTagSet.TAG_TILE_WIDTH,
BaselineTIFFTagSet.TAG_Y_CB_CR_COEFFICIENTS,
BaselineTIFFTagSet.TAG_Y_CB_CR_SUBSAMPLING
);
}
}
/**
* Converts a {@code TIFFDirectory} to a {@code TIFFIFD}.
*/
public static TIFFIFD getDirectoryAsIFD(TIFFDirectory dir) {
if(dir instanceof TIFFIFD) {
return (TIFFIFD)dir;
}
TIFFIFD ifd = new TIFFIFD(Arrays.asList(dir.getTagSets()),
dir.getParentTag());
TIFFField[] fields = dir.getTIFFFields();
int numFields = fields.length;
for(int i = 0; i < numFields; i++) {
TIFFField f = fields[i];
TIFFTag tag = f.getTag();
if(tag.isIFDPointer()) {
TIFFDirectory subDir = null;
if (f.hasDirectory()) {
subDir = f.getDirectory();
} else if (f.getData() instanceof TIFFDirectory) {
subDir = (TIFFDirectory)f.getData();
}
if (subDir != null) {
TIFFDirectory subIFD = getDirectoryAsIFD(subDir);
f = new TIFFField(tag, f.getType(), (long)f.getCount(),
subIFD);
} else {
f = null;
}
}
if (f != null) {
ifd.addTIFFField(f);
}
}
return ifd;
}
public static TIFFTag getTag(int tagNumber, List<TIFFTagSet> tagSets) {
for (TIFFTagSet tagSet : tagSets) {
TIFFTag tag = tagSet.getTag(tagNumber);
if (tag != null) {
return tag;
}
}
return null;
}
public static TIFFTag getTag(String tagName, List<TIFFTagSet> tagSets) {
for (TIFFTagSet tagSet : tagSets) {
TIFFTag tag = tagSet.getTag(tagName);
if (tag != null) {
return tag;
}
}
return null;
}
private static void writeTIFFFieldToStream(TIFFField field,
ImageOutputStream stream)
throws IOException {
int count = field.getCount();
Object data = field.getData();
switch (field.getType()) {
case TIFFTag.TIFF_ASCII:
for (int i = 0; i < count; i++) {
String s = ((String[])data)[i];
int length = s.length();
for (int j = 0; j < length; j++) {
stream.writeByte(s.charAt(j) & 0xff);
}
stream.writeByte(0);
}
break;
case TIFFTag.TIFF_UNDEFINED:
case TIFFTag.TIFF_BYTE:
case TIFFTag.TIFF_SBYTE:
stream.write((byte[])data);
break;
case TIFFTag.TIFF_SHORT:
stream.writeChars((char[])data, 0, ((char[])data).length);
break;
case TIFFTag.TIFF_SSHORT:
stream.writeShorts((short[])data, 0, ((short[])data).length);
break;
case TIFFTag.TIFF_SLONG:
stream.writeInts((int[])data, 0, ((int[])data).length);
break;
case TIFFTag.TIFF_LONG:
for (int i = 0; i < count; i++) {
stream.writeInt((int)(((long[])data)[i]));
}
break;
case TIFFTag.TIFF_IFD_POINTER:
stream.writeInt(0); // will need to be backpatched
break;
case TIFFTag.TIFF_FLOAT:
stream.writeFloats((float[])data, 0, ((float[])data).length);
break;
case TIFFTag.TIFF_DOUBLE:
stream.writeDoubles((double[])data, 0, ((double[])data).length);
break;
case TIFFTag.TIFF_SRATIONAL:
for (int i = 0; i < count; i++) {
stream.writeInt(((int[][])data)[i][0]);
stream.writeInt(((int[][])data)[i][1]);
}
break;
case TIFFTag.TIFF_RATIONAL:
for (int i = 0; i < count; i++) {
long num = ((long[][])data)[i][0];
long den = ((long[][])data)[i][1];
stream.writeInt((int)num);
stream.writeInt((int)den);
}
break;
default:
// error
}
}
public TIFFIFD(List<TIFFTagSet> tagSets, TIFFTag parentTag) {
super(tagSets.toArray(new TIFFTagSet[tagSets.size()]),
parentTag);
}
public TIFFIFD(List<TIFFTagSet> tagSets) {
this(tagSets, null);
}
public List<TIFFTagSet> getTagSetList() {
return Arrays.asList(getTagSets());
}
/**
* Returns an {@code Iterator} over the TIFF fields. The
* traversal is in the order of increasing tag number.
*/
// Note: the sort is guaranteed for low fields by the use of an
// array wherein the index corresponds to the tag number and for
// the high fields by the use of a TreeMap with tag number keys.
public Iterator<TIFFField> iterator() {
return Arrays.asList(getTIFFFields()).iterator();
}
/**
* Read the value of a field. The {@code data} parameter should be
* an array of length 1 of Object.
*
* @param stream the input stream
* @param type the type as read from the stream
* @param count the count read from the stream
* @param data a container for the data
* @return the updated count
* @throws IOException
*/
private static int readFieldValue(ImageInputStream stream,
int type, int count, Object[] data) throws IOException {
Object obj;
final int UNIT_SIZE = 1024000;
switch (type) {
case TIFFTag.TIFF_BYTE:
case TIFFTag.TIFF_SBYTE:
case TIFFTag.TIFF_UNDEFINED:
case TIFFTag.TIFF_ASCII:
if (type == TIFFTag.TIFF_ASCII) {
byte[] bvalues = new byte[count];
stream.readFully(bvalues, 0, count);
// Can be multiple strings
ArrayList<String> v = new ArrayList<>();
boolean inString = false;
int prevIndex = 0;
for (int index = 0; index <= count; index++) {
if (index < count && bvalues[index] != 0) {
if (!inString) {
// start of string
prevIndex = index;
inString = true;
}
} else { // null or special case at end of string
if (inString) {
// end of string
String s = new String(bvalues, prevIndex,
index - prevIndex, US_ASCII);
v.add(s);
inString = false;
}
}
}
count = v.size();
String[] strings;
if (count != 0) {
strings = new String[count];
for (int c = 0; c < count; c++) {
strings[c] = v.get(c);
}
} else {
// This case has been observed when the value of
// 'count' recorded in the field is non-zero but
// the value portion contains all nulls.
count = 1;
strings = new String[]{""};
}
obj = strings;
} else {
if (count < UNIT_SIZE) {
byte[] bvalues = new byte[count];
stream.readFully(bvalues, 0, count);
obj = bvalues;
} else {
int bytesToRead = count;
int bytesRead = 0;
List<byte[]> bufs = new ArrayList<>();
while (bytesToRead != 0) {
int sz = Math.min(bytesToRead, UNIT_SIZE);
byte[] unit = new byte[sz];
stream.readFully(unit, 0, sz);
bufs.add(unit);
bytesRead += sz;
bytesToRead -= sz;
}
byte[] tagData = new byte[bytesRead];
int copiedBytes = 0;
for (byte[] ba : bufs) {
System.arraycopy(ba, 0, tagData, copiedBytes, ba.length);
copiedBytes += ba.length;
}
obj = tagData;
}
}
break;
case TIFFTag.TIFF_SHORT:
final int SHORT_TILE_SIZE =
UNIT_SIZE / TIFFTag.getSizeOfType(TIFFTag.TIFF_SHORT);
if (count < SHORT_TILE_SIZE) {
char[] cvalues = new char[count];
for (int j = 0; j < count; j++) {
cvalues[j] = (char) (stream.readUnsignedShort());
}
obj = cvalues;
} else {
int charsToRead = count;
int charsRead = 0;
List<char[]> bufs = new ArrayList<>();
while (charsToRead != 0) {
int sz = Math.min(charsToRead, SHORT_TILE_SIZE);
char[] unit = new char[sz];
for (int i = 0; i < sz ; i++) {
unit[i] = (char) (stream.readUnsignedShort());
}
bufs.add(unit);
charsRead += sz;
charsToRead -= sz;
}
char[] tagData = new char[charsRead];
int copiedChars = 0;
for (char[] ca : bufs) {
System.arraycopy(ca, 0, tagData, copiedChars, ca.length);
copiedChars += ca.length;
}
obj = tagData;
}
break;
case TIFFTag.TIFF_LONG:
case TIFFTag.TIFF_IFD_POINTER:
final int LONG_TILE_SIZE =
UNIT_SIZE / TIFFTag.getSizeOfType(TIFFTag.TIFF_LONG);
if (count < LONG_TILE_SIZE) {
long[] lvalues = new long[count];
for (int j = 0; j < count; j++) {
lvalues[j] = stream.readUnsignedInt();
}
obj = lvalues;
} else {
int longsToRead = count;
int longsRead = 0;
List<long[]> bufs = new ArrayList<>();
while (longsToRead != 0) {
int sz = Math.min(longsToRead, LONG_TILE_SIZE);
long[] unit = new long[sz];
for (int i = 0; i < sz ; i++) {
unit[i] = stream.readUnsignedInt();
}
bufs.add(unit);
longsRead += sz;
longsToRead -= sz;
}
long[] tagData = new long[longsRead];
int copiedLongs = 0;
for (long[] la : bufs) {
System.arraycopy(la, 0, tagData, copiedLongs, la.length);
copiedLongs += la.length;
}
obj = tagData;
}
break;
case TIFFTag.TIFF_RATIONAL:
final int RATIONAL_TILE_SIZE =
UNIT_SIZE / TIFFTag.getSizeOfType(TIFFTag.TIFF_RATIONAL);
if (count < RATIONAL_TILE_SIZE) {
long[][] llvalues = new long[count][2];
for (int j = 0; j < count; j++) {
llvalues[j][0] = stream.readUnsignedInt();
llvalues[j][1] = stream.readUnsignedInt();
}
obj = llvalues;
} else {
int rationalsToRead = count;
int rationalsRead = 0;
List<long[]> bufs = new ArrayList<>();
while (rationalsToRead != 0) {
int sz = Math.min(rationalsToRead, RATIONAL_TILE_SIZE);
long[] unit = new long[sz * 2];
for (int i = 0; i < (sz * 2) ; i++) {
unit[i] = stream.readUnsignedInt();
}
bufs.add(unit);
rationalsRead += sz;
rationalsToRead -= sz;
}
long[][] tagData = new long[rationalsRead][2];
int copiedRationals = 0;
for (long[] la : bufs) {
for (int i = 0; i < la.length; i = i + 2) {
tagData[copiedRationals + i][0] = la[i];
tagData[copiedRationals + i][1] = la[i + 1];
}
copiedRationals += (la.length / 2);
}
obj = tagData;
}
break;
case TIFFTag.TIFF_SSHORT:
final int SSHORT_TILE_SIZE =
UNIT_SIZE / TIFFTag.getSizeOfType(TIFFTag.TIFF_SSHORT);
if (count < SSHORT_TILE_SIZE) {
short[] svalues = new short[count];
for (int j = 0; j < count; j++) {
svalues[j] = stream.readShort();
}
obj = svalues;
} else {
int shortsToRead = count;
int shortsRead = 0;
List<short[]> bufs = new ArrayList<>();
while (shortsToRead != 0) {
int sz = Math.min(shortsToRead, SSHORT_TILE_SIZE);
short[] unit = new short[sz];
stream.readFully(unit, 0, sz);
bufs.add(unit);
shortsRead += sz;
shortsToRead -= sz;
}
short[] tagData = new short[shortsRead];
int copiedShorts = 0;
for (short[] sa : bufs) {
System.arraycopy(sa, 0, tagData, copiedShorts, sa.length);
copiedShorts += sa.length;
}
obj = tagData;
}
break;
case TIFFTag.TIFF_SLONG:
final int INT_TILE_SIZE =
UNIT_SIZE / TIFFTag.getSizeOfType(TIFFTag.TIFF_SLONG);
if (count < INT_TILE_SIZE) {
int[] ivalues = new int[count];
for (int j = 0; j < count; j++) {
ivalues[j] = stream.readInt();
}
obj = ivalues;
} else {
int intsToRead = count;
int intsRead = 0;
List<int[]> bufs = new ArrayList<>();
while (intsToRead != 0) {
int sz = Math.min(intsToRead, INT_TILE_SIZE);
int[] unit = new int[sz];
stream.readFully(unit, 0, sz);
bufs.add(unit);
intsRead += sz;
intsToRead -= sz;
}
int[] tagData = new int[intsRead];
int copiedInts = 0;
for (int[] ia : bufs) {
System.arraycopy(ia, 0, tagData, copiedInts, ia.length);
copiedInts += ia.length;
}
obj = tagData;
}
break;
case TIFFTag.TIFF_SRATIONAL:
final int SRATIONAL_TILE_SIZE =
UNIT_SIZE / TIFFTag.getSizeOfType(TIFFTag.TIFF_SRATIONAL);
if (count < SRATIONAL_TILE_SIZE) {
int[][] iivalues = new int[count][2];
for (int j = 0; j < count; j++) {
iivalues[j][0] = stream.readInt();
iivalues[j][1] = stream.readInt();
}
obj = iivalues;
} else {
int srationalsToRead = count;
int srationalsRead = 0;
List<int[]> bufs = new ArrayList<>();
while (srationalsToRead != 0) {
int sz = Math.min(srationalsToRead, SRATIONAL_TILE_SIZE);
int[] unit = new int[sz * 2];
stream.readFully(unit, 0, (sz * 2));
bufs.add(unit);
srationalsRead += sz;
srationalsToRead -= sz;
}
int[][] tagData = new int[srationalsRead][2];
int copiedSrationals = 0;
for (int[] ia : bufs) {
for (int i = 0; i < ia.length; i = i + 2) {
tagData[copiedSrationals + i][0] = ia[i];
tagData[copiedSrationals + i][1] = ia[i + 1];
}
copiedSrationals += (ia.length / 2);
}
obj = tagData;
}
break;
case TIFFTag.TIFF_FLOAT:
final int FLOAT_TILE_SIZE =
UNIT_SIZE / TIFFTag.getSizeOfType(TIFFTag.TIFF_FLOAT);
if (count < FLOAT_TILE_SIZE) {
float[] fvalues = new float[count];
for (int j = 0; j < count; j++) {
fvalues[j] = stream.readFloat();
}
obj = fvalues;
} else {
int floatsToRead = count;
int floatsRead = 0;
List<float[]> bufs = new ArrayList<>();
while (floatsToRead != 0) {
int sz = Math.min(floatsToRead, FLOAT_TILE_SIZE);
float[] unit = new float[sz];
stream.readFully(unit, 0, sz);
bufs.add(unit);
floatsRead += sz;
floatsToRead -= sz;
}
float[] tagData = new float[floatsRead];
int copiedFloats = 0;
for (float[] fa : bufs) {
System.arraycopy(fa, 0, tagData, copiedFloats, fa.length);
copiedFloats += fa.length;
}
obj = tagData;
}
break;
case TIFFTag.TIFF_DOUBLE:
final int DOUBLE_TILE_SIZE =
UNIT_SIZE / TIFFTag.getSizeOfType(TIFFTag.TIFF_DOUBLE);
if (count < DOUBLE_TILE_SIZE) {
double[] dvalues = new double[count];
for (int j = 0; j < count; j++) {
dvalues[j] = stream.readDouble();
}
obj = dvalues;
} else {
int doublesToRead = count;
int doublesRead = 0;
List<double[]> bufs = new ArrayList<>();
while (doublesToRead != 0) {
int sz = Math.min(doublesToRead, DOUBLE_TILE_SIZE);
double[] unit = new double[sz];
stream.readFully(unit, 0, sz);
bufs.add(unit);
doublesRead += sz;
doublesToRead -= sz;
}
double[] tagData = new double[doublesRead];
int copiedDoubles = 0;
for (double[] da : bufs) {
System.arraycopy(da, 0, tagData, copiedDoubles, da.length);
copiedDoubles += da.length;
}
obj = tagData;
}
break;
default:
obj = null;
break;
}
data[0] = obj;
return count;
}
//
// Class to represent an IFD entry where the actual content is at an offset
// in the stream somewhere outside the IFD itself. This occurs when the
// value cannot be contained within four bytes. Seeking is required to read
// such field values.
//
private static class TIFFIFDEntry {
public final TIFFTag tag;
public final int type;
public final int count;
public final long offset;
TIFFIFDEntry(TIFFTag tag, int type, int count, long offset) {
this.tag = tag;
this.type = type;
this.count = count;
this.offset = offset;
}
}
//
// Retrieve the value of a baseline field as a long.
//
private long getFieldAsLong(int tagNumber) {
TIFFField f = getTIFFField(tagNumber);
return f == null ? -1 : f.getAsLong(0);
}
//
// Retrieve the value of a baseline field as an int.
//
private int getFieldAsInt(int tagNumber) {
TIFFField f = getTIFFField(tagNumber);
return f == null ? -1 : f.getAsInt(0);
}
//
// Calculate the number of bytes in each strip or tile. This method
// is to be used if and only if no fields exist which provide this
// information. The parameter must be empty and if the method succeeds
// will contain a single element.
//
private boolean calculateByteCounts(int expectedSize,
List<TIFFField> byteCounts) {
if (!byteCounts.isEmpty()) {
throw new IllegalArgumentException("byteCounts is not empty");
}
// must be interleaved
if (getFieldAsInt(BaselineTIFFTagSet.TAG_PLANAR_CONFIGURATION) ==
BaselineTIFFTagSet.PLANAR_CONFIGURATION_PLANAR) {
return false;
}
// must be uncompressed
if (getFieldAsInt(BaselineTIFFTagSet.TAG_COMPRESSION) !=
BaselineTIFFTagSet.COMPRESSION_NONE) {
return false;
}
// must have image dimensions
long w = getFieldAsLong(BaselineTIFFTagSet.TAG_IMAGE_WIDTH);
if (w < 0) {
return false;
}
long h = getFieldAsLong(BaselineTIFFTagSet.TAG_IMAGE_LENGTH);
if (h < 0) {
return false;
}
long tw = getFieldAsLong(BaselineTIFFTagSet.TAG_TILE_WIDTH);
if (tw < 0) {
tw = w;
}
long th = getFieldAsLong(BaselineTIFFTagSet.TAG_TILE_LENGTH);
if (th < 0) {
th = getFieldAsLong(BaselineTIFFTagSet.TAG_ROWS_PER_STRIP);
if (th < 0) {
th = h;
}
}
int[] bitsPerSample = null;
TIFFField f = getTIFFField(BaselineTIFFTagSet.TAG_BITS_PER_SAMPLE);
if (f != null) {
bitsPerSample = f.getAsInts();
} else {
int samplesPerPixel =
getFieldAsInt(BaselineTIFFTagSet.TAG_SAMPLES_PER_PIXEL);
if (samplesPerPixel < 0) {
samplesPerPixel = 1;
}
bitsPerSample = new int[samplesPerPixel];
Arrays.fill(bitsPerSample, 8);
}
int bitsPerPixel = 0;
for (int bps : bitsPerSample) {
bitsPerPixel += bps;
}
int bytesPerRow = (int)(tw*bitsPerPixel + 7)/8;
int bytesPerPacket = (int)th*bytesPerRow;
long nx = (w + tw - 1)/tw;
long ny = (h + th - 1)/th;
if (nx*ny != expectedSize) {
return false;
}
boolean isTiled =
getTIFFField(BaselineTIFFTagSet.TAG_TILE_BYTE_COUNTS) != null;
int tagNumber;
if (isTiled) {
tagNumber = BaselineTIFFTagSet.TAG_TILE_BYTE_COUNTS;
} else {
tagNumber = BaselineTIFFTagSet.TAG_STRIP_BYTE_COUNTS;
}
TIFFTag t = BaselineTIFFTagSet.getInstance().getTag(tagNumber);
f = getTIFFField(tagNumber);
if (f != null) {
removeTIFFField(tagNumber);
}
int numPackets = (int)(nx*ny);
long[] packetByteCounts = new long[numPackets];
Arrays.fill(packetByteCounts, bytesPerPacket);
// if the strip or tile width does not exceed the image width and the
// image height is not a multiple of the strip or tile height, then
// truncate the estimate of the byte count of the last strip to avoid
// reading past the end of the data
if (tw <= w && h % th != 0) {
int numRowsInLastStrip = (int)(h - (ny - 1)*th);
packetByteCounts[numPackets - 1] = numRowsInLastStrip*bytesPerRow;
}
f = new TIFFField(t, TIFFTag.TIFF_LONG, numPackets, packetByteCounts);
addTIFFField(f);
byteCounts.add(f);
return true;
}
//
// Verify that data pointed to outside of the IFD itself are within the
// stream. To be called after all fields have been read and populated.
//
private void checkFieldOffsets(long streamLength) throws IIOException {
if (streamLength < 0) {
return;
}
// StripOffsets
List<TIFFField> offsets = new ArrayList<>();
TIFFField f = getTIFFField(BaselineTIFFTagSet.TAG_STRIP_OFFSETS);
int count = 0;
if (f != null) {
count = f.getCount();
offsets.add(f);
}
// TileOffsets
f = getTIFFField(BaselineTIFFTagSet.TAG_TILE_OFFSETS);
if (f != null) {
int sz = offsets.size();
int newCount = f.getCount();
if (sz > 0 && newCount != count) {
throw new IIOException
("StripOffsets count != TileOffsets count");
}
if (sz == 0) {
count = newCount;
}
offsets.add(f);
}
List<TIFFField> byteCounts = new ArrayList<>();
if (offsets.size() > 0) {
// StripByteCounts
f = getTIFFField(BaselineTIFFTagSet.TAG_STRIP_BYTE_COUNTS);
if (f != null) {
if (f.getCount() != count) {
throw new IIOException
("StripByteCounts count != number of offsets");
}
byteCounts.add(f);
}
// TileByteCounts
f = getTIFFField(BaselineTIFFTagSet.TAG_TILE_BYTE_COUNTS);
if (f != null) {
if (f.getCount() != count) {
throw new IIOException
("TileByteCounts count != number of offsets");
}
byteCounts.add(f);
}
if (byteCounts.size() > 0) {
for (TIFFField offset : offsets) {
for (TIFFField byteCount : byteCounts) {
for (int i = 0; i < count; i++) {
long dataOffset = offset.getAsLong(i);
long dataByteCount = byteCount.getAsLong(i);
if (dataOffset + dataByteCount > streamLength) {
throw new IIOException
("Data segment out of stream");
}
}
}
}
}
}
// JPEGInterchangeFormat and JPEGInterchangeFormatLength
TIFFField jpegOffset =
getTIFFField(BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT);
if (jpegOffset != null) {
TIFFField jpegLength =
getTIFFField(BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH);
if (jpegLength != null) {
if (jpegOffset.getAsLong(0) + jpegLength.getAsLong(0)
> streamLength) {
throw new IIOException
("JPEGInterchangeFormat data out of stream");
}
}
}
// Ensure there is at least a data pointer for JPEG interchange format or
// both data offsets and byte counts for other compression types.
if (jpegOffset == null
&& (offsets.size() == 0 || byteCounts.size() == 0)) {
boolean throwException = true;
if (offsets.size() != 0 && byteCounts.size() == 0) {
// Attempt to calculate missing byte counts
int expectedSize = offsets.get(0).getCount();
throwException =
!calculateByteCounts(expectedSize, byteCounts);
}
if (throwException) {
throw new IIOException
("Insufficient data offsets or byte counts");
}
}
// JPEGQTables - one 64-byte table for each offset.
f = getTIFFField(BaselineTIFFTagSet.TAG_JPEG_Q_TABLES);
if (f != null) {
long[] tableOffsets = f.getAsLongs();
for (long off : tableOffsets) {
if (off + 64 > streamLength) {
throw new IIOException("JPEGQTables data out of stream");
}
}
}
// JPEGDCTables
f = getTIFFField(BaselineTIFFTagSet.TAG_JPEG_DC_TABLES);
if (f != null) {
long[] tableOffsets = f.getAsLongs();
for (long off : tableOffsets) {
if (off + 16 > streamLength) {
throw new IIOException("JPEGDCTables data out of stream");
}
}
}
// JPEGACTables
f = getTIFFField(BaselineTIFFTagSet.TAG_JPEG_AC_TABLES);
if (f != null) {
long[] tableOffsets = f.getAsLongs();
for (long off : tableOffsets) {
if (off + 16 > streamLength) {
throw new IIOException("JPEGACTables data out of stream");
}
}
}
}
// Stream position initially at beginning, left at end
// if readUnknownTags is false, do not load fields for which
// a tag cannot be found in an allowed TagSet.
public void initialize(ImageInputStream stream, boolean isPrimaryIFD,
boolean ignoreMetadata, boolean readUnknownTags) throws IOException {
removeTIFFFields();
long streamLength = stream.length();
boolean haveStreamLength = streamLength != -1;
List<TIFFTagSet> tagSetList = getTagSetList();
// Configure essential tag variables if this is the primary IFD and
// either all metadata are being ignored, or metadata are not being
// ignored but both unknown tags are being ignored and the tag set
// list does not contain the baseline tags.
boolean ensureEssentialTags = false;
TIFFTagSet baselineTagSet = null;
if (isPrimaryIFD &&
(ignoreMetadata ||
(!readUnknownTags &&
!tagSetList.contains(BaselineTIFFTagSet.getInstance())))) {
ensureEssentialTags = true;
initializeEssentialTags();
baselineTagSet = BaselineTIFFTagSet.getInstance();
}
List<Object> entries = new ArrayList<>();
Object[] entryData = new Object[1]; // allocate once for later reuse.
// Read the IFD entries, loading the field values which are no more than
// four bytes long, and storing the 4-byte offsets for the others.
int numEntries = stream.readUnsignedShort();
for (int i = 0; i < numEntries; i++) {
// Read tag number, value type, and value count.
int tagNumber = stream.readUnsignedShort();
int type = stream.readUnsignedShort();
int sizeOfType;
try {
sizeOfType = TIFFTag.getSizeOfType(type);
} catch (IllegalArgumentException ignored) {
// Continue with the next IFD entry.
stream.skipBytes(4);
continue;
}
long longCount = stream.readUnsignedInt();
// Get the associated TIFFTag.
TIFFTag tag = getTag(tagNumber, tagSetList);
if (tag == null && ensureEssentialTags
&& essentialTags.contains(tagNumber)) {
tag = baselineTagSet.getTag(tagNumber);
}
// Ignore non-essential fields, unknown fields unless forcibly
// being read, fields with unknown type, and fields
// with count out of int range.
if((ignoreMetadata &&
(!ensureEssentialTags || !essentialTags.contains(tagNumber)))
|| (tag == null && !readUnknownTags)
|| (tag != null && !tag.isDataTypeOK(type))
|| longCount > Integer.MAX_VALUE) {
// Skip the value/offset so as to leave the stream
// position at the start of the next IFD entry.
stream.skipBytes(4);
// Continue with the next IFD entry.
continue;
}
int count = (int)longCount;
if (tag == null) {
tag = new TIFFTag(TIFFTag.UNKNOWN_TAG_NAME, tagNumber,
1 << type, count);
} else {
int expectedCount = tag.getCount();
if (expectedCount > 0) {
// If the tag count is positive then the tag defines a
// specific, fixed count that the field must match.
if (count != expectedCount) {
throw new IIOException("Unexpected count "
+ count + " for " + tag.getName() + " field");
}
} else if (type == TIFFTag.TIFF_ASCII) {
// Clamp the size of ASCII fields of unspecified length
// to a maximum value.
int asciiSize = TIFFTag.getSizeOfType(TIFFTag.TIFF_ASCII);
if (count*asciiSize > MAX_ASCII_SIZE) {
count = (int)(MAX_ASCII_SIZE/asciiSize);
}
}
}
long longSize = longCount*sizeOfType;
if (longSize > Integer.MAX_VALUE) {
// Continue with the next IFD entry.
stream.skipBytes(4);
continue;
}
int size = (int)longSize;