-
Notifications
You must be signed in to change notification settings - Fork 331
Expand file tree
/
Copy pathIFDReader.cs
More file actions
1027 lines (856 loc) · 31.6 KB
/
IFDReader.cs
File metadata and controls
1027 lines (856 loc) · 31.6 KB
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
//
// IFDReader.cs: Parses TIFF IFDs and populates an IFD structure.
//
// Author:
// Ruben Vermeersch (ruben@savanne.be)
// Mike Gemuende (mike@gemuende.de)
//
// Copyright (C) 2009 Ruben Vermeersch
// Copyright (C) 2009 Mike Gemuende
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
using System.Collections.Generic;
using System.IO;
using TagLib.IFD.Entries;
using TagLib.IFD.Makernotes;
using TagLib.IFD.Tags;
namespace TagLib.IFD
{
/// <summary>
/// This class contains all the IFD reading and parsing code.
/// </summary>
public class IFDReader
{
#region Private Constants
static readonly string PANASONIC_HEADER = "Panasonic\0\0\0";
static readonly string PENTAX_HEADER = "AOC\0";
static readonly string NIKON_HEADER = "Nikon\0";
static readonly string OLYMPUS1_HEADER = "OLYMP\0";
static readonly string OLYMPUS2_HEADER = "OLYMPUS\0";
static readonly string SONY_HEADER = "SONY DSC \0\0\0";
static readonly string LEICA_HEADER = "LEICA\0\0\0";
#endregion
#region Protected Fields
/// <summary>
/// The <see cref="File" /> where this IFD is found in.
/// </summary>
protected readonly File file;
/// <summary>
/// If IFD is encoded in BigEndian or not
/// </summary>
protected readonly bool is_bigendian;
/// <summary>
/// The IFD structure that will be populated
/// </summary>
protected readonly IFDStructure structure;
/// <summary>
/// A <see cref="System.Int64"/> value describing the base were the IFD offsets
/// refer to. E.g. in Jpegs the IFD are located in an Segment and the offsets
/// inside the IFD refer from the beginning of this segment. So base_offset must
/// contain the beginning of the segment.
/// </summary>
protected readonly long base_offset;
/// <summary>
/// A <see cref="System.UInt32"/> value with the beginning of the IFD relative to
/// base_offset.
/// </summary>
protected readonly uint ifd_offset;
/// <summary>
/// A <see cref="System.UInt32"/> with the maximal offset, which should occur in the
/// IFD. Greater offsets, would reference beyond the considered data.
/// </summary>
protected readonly uint max_offset;
/// <summary>
/// Whether or not the makernote should be parsed.
/// </summary>
protected bool parse_makernote = true;
#endregion
/// <summary>
/// Whether or not the makernote should be parsed.
/// </summary>
internal bool ShouldParseMakernote {
get { return parse_makernote; }
set { parse_makernote = value; }
}
#region Constructors
/// <summary>
/// Constructor. Reads an IFD from given file, using the given endianness.
/// </summary>
/// <param name="file">
/// A <see cref="File"/> to read from.
/// </param>
/// <param name="is_bigendian">
/// A <see cref="System.Boolean"/>, it must be true, if the data of the IFD should be
/// read as bigendian, otherwise false.
/// </param>
/// <param name="structure">
/// A <see cref="IFDStructure"/> that will be populated.
/// </param>
/// <param name="base_offset">
/// A <see cref="System.Int64"/> value describing the base were the IFD offsets
/// refer to. E.g. in Jpegs the IFD are located in an Segment and the offsets
/// inside the IFD refer from the beginning of this segment. So <paramref
/// name="base_offset"/> must contain the beginning of the segment.
/// </param>
/// <param name="ifd_offset">
/// A <see cref="System.UInt32"/> value with the beginning of the IFD relative to
/// <paramref name="base_offset"/>.
/// </param>
/// <param name="max_offset">
/// A <see cref="System.UInt32"/> value with maximal possible offset. This is to limit
/// the size of the possible data;
/// </param>
public IFDReader (File file, bool is_bigendian, IFDStructure structure, long base_offset, uint ifd_offset, uint max_offset)
{
this.file = file;
this.is_bigendian = is_bigendian;
this.structure = structure;
this.base_offset = base_offset;
this.ifd_offset = ifd_offset;
this.max_offset = max_offset;
}
#endregion
#region Public Methods
/// <summary>
/// Read all IFD segments from the file.
/// </summary>
public void Read ()
{
Read (-1);
}
/// <summary>
/// Read IFD segments from the file.
/// </summary>
/// <para>
/// The number of IFDs that may be read can be restricted using the count
/// parameter. This might be needed for fiels that have invalid next-ifd
/// pointers (such as some IFDs in the Nikon Makernote). This condition is
/// tested in the Nikon2 unit test, which contains such a file.
/// </para>
/// <param name="count">
/// A <see cref="System.Int32"/> with the maximal number of IFDs to read.
/// Passing -1 means unlimited.
/// </param>
public void Read (int count)
{
if (count == 0)
return;
uint next_offset = ifd_offset;
int i = 0;
lock (file) {
StartIFDLoopDetect ();
do {
if (DetectIFDLoop (base_offset + next_offset)) {
file.MarkAsCorrupt ("IFD loop detected");
break;
}
next_offset = ReadIFD (base_offset, next_offset, max_offset);
} while (next_offset > 0 && (count == -1 || ++i < count));
StopIFDLoopDetect ();
}
}
#endregion
#region Private Methods
/// <summary>
/// Add to the reference count for the IFD loop detection.
/// </summary>
void StartIFDLoopDetect ()
{
lock (ifd_sync_object) {
if (!ifd_offsets.ContainsKey (file)) {
ifd_offsets[file] = new List<long> ();
ifd_loopdetect_refs[file] = 1;
} else {
ifd_loopdetect_refs[file]++;
}
}
}
/// <summary>
/// Attempts to detect whether or not this file has an endless IFD loop.
/// </summary>
/// <param name="offset">
/// A <see cref="System.UInt32"/> with the offset at which the next IFD
/// can be found.
/// </param>
/// <returns>
/// True if we have gone into a loop, false otherwise.
/// </returns>
bool DetectIFDLoop (long offset)
{
if (offset == 0)
return false;
lock (ifd_sync_object) {
if (ifd_offsets[file].Contains (offset))
return true;
ifd_offsets[file].Add (offset);
}
return false;
}
/// <summary>
/// End the IFD loop detection, cleanup if we're the last.
/// </summary>
void StopIFDLoopDetect ()
{
lock (ifd_sync_object) {
ifd_loopdetect_refs[file]--;
if (ifd_loopdetect_refs[file] == 0) {
ifd_offsets.Remove (file);
ifd_loopdetect_refs.Remove (file);
}
}
}
static object ifd_sync_object = new object ();
static readonly Dictionary<File, List<long>> ifd_offsets = new Dictionary<File, List<long>> ();
static readonly Dictionary<File, int> ifd_loopdetect_refs = new Dictionary<File, int> ();
/// <summary>
/// Reads an IFD from file at position <paramref name="offset"/> relative
/// to <paramref name="baseOffset"/>.
/// </summary>
/// <param name="baseOffset">
/// A <see cref="System.Int64"/> with the base offset which every offset
/// in IFD is relative to.
/// </param>
/// <param name="offset">
/// A <see cref="System.UInt32"/> with the offset of the IFD relative to
/// <paramref name="baseOffset"/>
/// </param>
/// <param name="maxOffset">
/// A <see cref="System.UInt32"/> with the maximal offset to consider for
/// the IFD.
/// </param>
/// <returns>
/// A <see cref="System.UInt32"/> with the offset of the next IFD, the
/// offset is also relative to <paramref name="baseOffset"/>
/// </returns>
uint ReadIFD (long baseOffset, uint offset, uint maxOffset)
{
long length = 0;
try {
length = file.Length;
} catch (Exception) {
// Use a safety-value of 4 gigabyte.
length = 1073741824L * 4;
}
if (baseOffset + offset > length) {
file.MarkAsCorrupt ("Invalid IFD offset");
return 0;
}
var directory = new IFDDirectory ();
file.Seek (baseOffset + offset, SeekOrigin.Begin);
ushort entry_count = ReadUShort ();
if (file.Tell + 12 * entry_count > baseOffset + maxOffset) {
file.MarkAsCorrupt ("Size of entries exceeds possible data size");
return 0;
}
ByteVector entry_datas = file.ReadBlock (12 * entry_count);
uint next_offset = ReadUInt ();
for (int i = 0; i < entry_count; i++) {
ByteVector entry_data = entry_datas.Mid (i * 12, 12);
ushort entry_tag = entry_data.Mid (0, 2).ToUShort (is_bigendian);
ushort type = entry_data.Mid (2, 2).ToUShort (is_bigendian);
uint value_count = entry_data.Mid (4, 4).ToUInt (is_bigendian);
ByteVector offset_data = entry_data.Mid (8, 4);
IFDEntry entry;
try {
entry = CreateIFDEntry (entry_tag, type, value_count, baseOffset, offset_data, maxOffset);
} catch (OverflowException) {
// This exception occurs when the image does not have data in the expected format at the
// requested location. This has been observed in images taken with an Olympus camera.
file.MarkAsCorrupt ("Invalid IFD entry");
continue;
}
if (entry == null)
continue;
if (directory.ContainsKey (entry.Tag))
directory.Remove (entry.Tag);
directory.Add (entry.Tag, entry);
}
FixupDirectory (baseOffset, directory);
structure.directories.Add (directory);
return next_offset;
}
/// <summary>
/// Creates an IFDEntry from the given values. This method is used for
/// every entry. Custom parsing can be hooked in by overriding the
/// <see cref="ParseIFDEntry(ushort,ushort,uint,long,uint)"/> method.
/// </summary>
/// <param name="tag">
/// A <see cref="System.UInt16"/> with the tag of the entry.
/// </param>
/// <param name="type">
/// A <see cref="System.UInt16"/> with the type of the entry.
/// </param>
/// <param name="count">
/// A <see cref="System.UInt32"/> with the data count of the entry.
/// </param>
/// <param name="baseOffset">
/// A <see cref="System.Int64"/> with the base offset which every
/// offsets in the IFD are relative to.
/// </param>
/// <param name="offsetData">
/// A <see cref="ByteVector"/> containing exactly 4 byte with the data
/// of the offset of the entry. Since this field isn't interpreted as
/// an offset if the data can be directly stored in the 4 byte, we
/// pass the <see cref="ByteVector"/> to easier interpret it.
/// </param>
/// <param name="maxOffset">
/// A <see cref="System.UInt32"/> with the maximal offset to consider for
/// the IFD.
/// </param>
/// <returns>
/// A <see cref="IFDEntry"/> with the given parameter.
/// </returns>
IFDEntry CreateIFDEntry (ushort tag, ushort type, uint count, long baseOffset, ByteVector offsetData, uint maxOffset)
{
uint offset = offsetData.ToUInt (is_bigendian);
// Fix the type for the IPTC tag.
// From http://www.awaresystems.be/imaging/tiff/tifftags/iptc.html
// "Often times, the datatype is incorrectly specified as LONG. "
if (tag == (ushort)IFDEntryTag.IPTC && type == (ushort)IFDEntryType.Long) {
type = (ushort)IFDEntryType.Byte;
}
var ifd_entry = ParseIFDEntry (tag, type, count, baseOffset, offset);
if (ifd_entry != null)
return ifd_entry;
if (count > 0x10000000) {
// Some Nikon files are known to exhibit this corruption (or "feature").
file.MarkAsCorrupt ("Impossibly large item count");
return null;
}
// then handle the values stored in the offset data itself
if (count == 1) {
if (type == (ushort)IFDEntryType.Byte)
return new ByteIFDEntry (tag, offsetData[0]);
if (type == (ushort)IFDEntryType.SByte)
return new SByteIFDEntry (tag, (sbyte)offsetData[0]);
if (type == (ushort)IFDEntryType.Short)
return new ShortIFDEntry (tag, offsetData.Mid (0, 2).ToUShort (is_bigendian));
if (type == (ushort)IFDEntryType.SShort)
return new SShortIFDEntry (tag, offsetData.Mid (0, 2).ToUShort (is_bigendian));
if (type == (ushort)IFDEntryType.Long)
return new LongIFDEntry (tag, offsetData.ToUInt (is_bigendian));
if (type == (ushort)IFDEntryType.SLong)
return new SLongIFDEntry (tag, offsetData.ToInt (is_bigendian));
}
if (count == 2) {
if (type == (ushort)IFDEntryType.Short) {
ushort[] data = new[] {
offsetData.Mid (0, 2).ToUShort (is_bigendian),
offsetData.Mid (2, 2).ToUShort (is_bigendian)
};
return new ShortArrayIFDEntry (tag, data);
}
if (type == (ushort)IFDEntryType.SShort) {
short[] data = new[] {
(short) offsetData.Mid (0, 2).ToUShort (is_bigendian),
(short) offsetData.Mid (2, 2).ToUShort (is_bigendian)
};
return new SShortArrayIFDEntry (tag, data);
}
}
if (count <= 4) {
if (type == (ushort)IFDEntryType.Undefined)
return new UndefinedIFDEntry (tag, offsetData.Mid (0, (int)count));
if (type == (ushort)IFDEntryType.Ascii) {
string data = offsetData.Mid (0, (int)count).ToString ();
int term = data.IndexOf ('\0');
if (term > -1)
data = data.Substring (0, term);
return new StringIFDEntry (tag, data);
}
if (type == (ushort)IFDEntryType.Byte)
return new ByteVectorIFDEntry (tag, offsetData.Mid (0, (int)count));
}
// FIXME: create correct type.
if (offset > maxOffset)
return new UndefinedIFDEntry (tag, new ByteVector ());
// then handle data referenced by the offset
file.Seek (baseOffset + offset, SeekOrigin.Begin);
if (count == 1) {
if (type == (ushort)IFDEntryType.Rational)
return new RationalIFDEntry (tag, ReadRational ());
if (type == (ushort)IFDEntryType.SRational)
return new SRationalIFDEntry (tag, ReadSRational ());
}
if (count > 1) {
if (type == (ushort)IFDEntryType.Long) {
uint[] data = ReadUIntArray (count);
return new LongArrayIFDEntry (tag, data);
}
if (type == (ushort)IFDEntryType.SLong) {
int[] data = ReadIntArray (count);
return new SLongArrayIFDEntry (tag, data);
}
if (type == (ushort)IFDEntryType.Rational) {
var entries = new Rational[count];
for (int i = 0; i < count; i++)
entries[i] = ReadRational ();
return new RationalArrayIFDEntry (tag, entries);
}
if (type == (ushort)IFDEntryType.SRational) {
var entries = new SRational[count];
for (int i = 0; i < count; i++)
entries[i] = ReadSRational ();
return new SRationalArrayIFDEntry (tag, entries);
}
}
if (count > 2) {
if (type == (ushort)IFDEntryType.Short) {
ushort[] data = ReadUShortArray (count);
return new ShortArrayIFDEntry (tag, data);
}
if (type == (ushort)IFDEntryType.SShort) {
short[] data = ReadShortArray (count);
return new SShortArrayIFDEntry (tag, data);
}
}
if (count > 4) {
if (type == (ushort)IFDEntryType.Long) {
uint[] data = ReadUIntArray (count);
return new LongArrayIFDEntry (tag, data);
}
if (type == (ushort)IFDEntryType.Byte) {
ByteVector data = file.ReadBlock ((int)count);
return new ByteVectorIFDEntry (tag, data);
}
if (type == (ushort)IFDEntryType.Ascii) {
string data = ReadAsciiString ((int)count);
return new StringIFDEntry (tag, data);
}
if (tag == (ushort)ExifEntryTag.UserComment) {
ByteVector data = file.ReadBlock ((int)count);
return new UserCommentIFDEntry (tag, data, file);
}
if (type == (ushort)IFDEntryType.Undefined) {
ByteVector data = file.ReadBlock ((int)count);
return new UndefinedIFDEntry (tag, data);
}
}
if (type == (ushort)IFDEntryType.Float)
return null;
if (type == 0 || type > 12) {
// Invalid type
file.MarkAsCorrupt ("Invalid item type");
return null;
}
return null;
// TODO: We should ignore unreadable values, erroring for now until we have sufficient coverage.
throw new NotImplementedException ($"Unknown type/count {type}/{count} ({offset})");
}
/// <summary>
/// Reads a 2-byte signed short from the current file.
/// </summary>
/// <returns>
/// A <see cref="short" /> value containing the short read
/// from the current instance.
/// </returns>
short ReadShort ()
{
return file.ReadBlock (2).ToShort (is_bigendian);
}
/// <summary>
/// Reads a 2-byte unsigned short from the current file.
/// </summary>
/// <returns>
/// A <see cref="ushort" /> value containing the short read
/// from the current instance.
/// </returns>
ushort ReadUShort ()
{
return file.ReadBlock (2).ToUShort (is_bigendian);
}
/// <summary>
/// Reads a 4-byte int from the current file.
/// </summary>
/// <returns>
/// A <see cref="uint" /> value containing the int read
/// from the current instance.
/// </returns>
int ReadInt ()
{
return file.ReadBlock (4).ToInt (is_bigendian);
}
/// <summary>
/// Reads a 4-byte unsigned int from the current file.
/// </summary>
/// <returns>
/// A <see cref="uint" /> value containing the int read
/// from the current instance.
/// </returns>
uint ReadUInt ()
{
return file.ReadBlock (4).ToUInt (is_bigendian);
}
/// <summary>
/// Reads a <see cref="Rational"/> by two following unsigned
/// int from the current file.
/// </summary>
/// <returns>
/// A <see cref="Rational"/> value created by the read values.
/// </returns>
Rational ReadRational ()
{
uint numerator = ReadUInt ();
uint denominator = ReadUInt ();
// correct illegal value
if (denominator == 0) {
numerator = 0;
denominator = 1;
}
return new Rational (numerator, denominator);
}
/// <summary>
/// Reads a <see cref="SRational"/> by two following unsigned
/// int from the current file.
/// </summary>
/// <returns>
/// A <see cref="SRational"/> value created by the read values.
/// </returns>
SRational ReadSRational ()
{
int numerator = ReadInt ();
int denominator = ReadInt ();
// correct illegal value
if (denominator == 0) {
numerator = 0;
denominator = 1;
}
return new SRational (numerator, denominator);
}
/// <summary>
/// Reads an array of 2-byte shorts from the current file.
/// </summary>
/// <returns>
/// An array of <see cref="ushort" /> values containing the
/// shorts read from the current instance.
/// </returns>
ushort[] ReadUShortArray (uint count)
{
ushort[] data = new ushort[count];
for (int i = 0; i < count; i++)
data[i] = ReadUShort ();
return data;
}
/// <summary>
/// Reads an array of 2-byte signed shorts from the current file.
/// </summary>
/// <returns>
/// An array of <see cref="short" /> values containing the
/// shorts read from the current instance.
/// </returns>
short[] ReadShortArray (uint count)
{
short[] data = new short[count];
for (int i = 0; i < count; i++)
data[i] = ReadShort ();
return data;
}
/// <summary>
/// Reads an array of 4-byte int from the current file.
/// </summary>
/// <returns>
/// An array of <see cref="int" /> values containing the
/// shorts read from the current instance.
/// </returns>
int[] ReadIntArray (uint count)
{
int[] data = new int[count];
for (int i = 0; i < count; i++)
data[i] = ReadInt ();
return data;
}
/// <summary>
/// Reads an array of 4-byte unsigned int from the current file.
/// </summary>
/// <returns>
/// An array of <see cref="uint" /> values containing the
/// shorts read from the current instance.
/// </returns>
uint[] ReadUIntArray (uint count)
{
uint[] data = new uint[count];
for (int i = 0; i < count; i++)
data[i] = ReadUInt ();
return data;
}
/// <summary>
/// Reads an ASCII string from the current file.
/// </summary>
/// <returns>
/// A <see cref="string" /> read from the current instance.
/// </returns>
/// <remarks>
/// The exif standard allows to store multiple string separated
/// by '\0' in one ASCII-field. On the other hand some programs
/// (e.g. CanonZoomBrowser) fill some ASCII fields by trailing
/// '\0's.
/// We follow the Adobe practice as described in XMP Specification
/// Part 3 (Storeage in Files), and process the ASCII string only
/// to the first '\0'.
/// </remarks>
string ReadAsciiString (int count)
{
string str = file.ReadBlock (count).ToString ();
int term = str.IndexOf ('\0');
if (term > -1)
str = str.Substring (0, term);
return str;
}
/// <summary>
/// Performs some fixups to a read <see cref="IFDDirectory"/>. For some
/// special cases multiple <see cref="IFDEntry"/> instances contained
/// in the directory are needed. Therfore, we do the fixups after reading the
/// whole directory to be sure, all entries are present.
/// </summary>
/// <param name="baseOffset">
/// A <see cref="System.Int64"/> value with the base offset, all offsets in the
/// directory refers to.
/// </param>
/// <param name="directory">
/// A <see cref="IFDDirectory"/> instance which was read and needs fixes.
/// </param>
void FixupDirectory (long baseOffset, IFDDirectory directory)
{
// The following two entries refer to thumbnail data, where one is the offset
// to the data and the other is the length. Unnaturally both are used to describe
// the data. So it is needed to keep both entries in sync and keep the thumbnail data
// for writing it back.
// We determine the position of the data, read it and store it in an ThumbnailDataIFDEntry
// which replaces the offset-entry to thumbnail data.
ushort offset_tag = (ushort)IFDEntryTag.JPEGInterchangeFormat;
ushort length_tag = (ushort)IFDEntryTag.JPEGInterchangeFormatLength;
if (directory.ContainsKey (offset_tag) && directory.ContainsKey (length_tag)) {
if (directory[offset_tag] is LongIFDEntry offset_entry && directory[length_tag] is LongIFDEntry length_entry) {
uint offset = offset_entry.Value;
uint length = length_entry.Value;
file.Seek (baseOffset + offset, SeekOrigin.Begin);
var data = file.ReadBlock ((int)length);
directory.Remove (offset_tag);
directory.Add (offset_tag, new ThumbnailDataIFDEntry (offset_tag, data));
}
}
// create a StripOffsetIFDEntry if necessary
ushort strip_offsets_tag = (ushort)IFDEntryTag.StripOffsets;
ushort strip_byte_counts_tag = (ushort)IFDEntryTag.StripByteCounts;
if (directory.ContainsKey (strip_offsets_tag) && directory.ContainsKey (strip_byte_counts_tag)) {
uint[] strip_offsets = null;
uint[] strip_byte_counts = null;
var strip_offsets_entry = directory[strip_offsets_tag];
var strip_byte_counts_entry = directory[strip_byte_counts_tag];
if (strip_offsets_entry is LongIFDEntry)
strip_offsets = new[] { (strip_offsets_entry as LongIFDEntry).Value };
else if (strip_offsets_entry is LongArrayIFDEntry)
strip_offsets = (strip_offsets_entry as LongArrayIFDEntry).Values;
if (strip_offsets == null)
return;
if (strip_byte_counts_entry is LongIFDEntry)
strip_byte_counts = new[] { (strip_byte_counts_entry as LongIFDEntry).Value };
else if (strip_byte_counts_entry is LongArrayIFDEntry)
strip_byte_counts = (strip_byte_counts_entry as LongArrayIFDEntry).Values;
if (strip_byte_counts == null)
return;
directory.Remove (strip_offsets_tag);
directory.Add (strip_offsets_tag, new StripOffsetsIFDEntry (strip_offsets_tag, strip_offsets, strip_byte_counts, file));
}
}
IFDEntry ParseMakernote (ushort tag, ushort type, uint count, long baseOffset, uint offset)
{
long makernote_offset = baseOffset + offset;
var ifd_structure = new IFDStructure ();
// This is the minimum size a makernote should have
// The shortest header is PENTAX_HEADER (4)
// + IFD entry count (2)
// + at least one IFD etry (12)
// + next IFD pointer (4)
// = 22 ....
// we use this number to read a header which is big used
// to identify the makernote types
int header_size = 18;
long length = 0;
try {
length = file.Length;
} catch (Exception) {
// Use a safety-value of 4 gigabyte.
length = 1073741824L * 4;
}
if (makernote_offset > length) {
file.MarkAsCorrupt ("offset to makernote is beyond file size");
return null;
}
if (makernote_offset + header_size > length) {
file.MarkAsCorrupt ("data is to short to contain a maker note ifd");
return null;
}
// read header
file.Seek (makernote_offset, SeekOrigin.Begin);
ByteVector header = file.ReadBlock (header_size);
if (header.StartsWith (PANASONIC_HEADER)) {
var reader = new IFDReader (file, is_bigendian, ifd_structure, baseOffset, offset + 12, max_offset);
reader.ReadIFD (baseOffset, offset + 12, max_offset);
return new MakernoteIFDEntry (tag, ifd_structure, MakernoteType.Panasonic, PANASONIC_HEADER, 12, true, null);
}
if (header.StartsWith (PENTAX_HEADER)) {
var reader = new IFDReader (file, is_bigendian, ifd_structure, baseOffset, offset + 6, max_offset);
reader.ReadIFD (baseOffset, offset + 6, max_offset);
return new MakernoteIFDEntry (tag, ifd_structure, MakernoteType.Pentax, header.Mid (0, 6), 6, true, null);
}
if (header.StartsWith (OLYMPUS1_HEADER)) {
var reader = new IFDReader (file, is_bigendian, ifd_structure, baseOffset, offset + 8, max_offset);
reader.Read ();
return new MakernoteIFDEntry (tag, ifd_structure, MakernoteType.Olympus1, header.Mid (0, 8), 8, true, null);
}
if (header.StartsWith (OLYMPUS2_HEADER)) {
var reader = new IFDReader (file, is_bigendian, ifd_structure, makernote_offset, 12, count);
reader.Read ();
return new MakernoteIFDEntry (tag, ifd_structure, MakernoteType.Olympus2, header.Mid (0, 12), 12, false, null);
}
if (header.StartsWith (SONY_HEADER)) {
var reader = new IFDReader (file, is_bigendian, ifd_structure, baseOffset, offset + 12, max_offset);
reader.ReadIFD (baseOffset, offset + 12, max_offset);
return new MakernoteIFDEntry (tag, ifd_structure, MakernoteType.Sony, SONY_HEADER, 12, true, null);
}
if (header.StartsWith (NIKON_HEADER)) {
ByteVector endian_bytes = header.Mid (10, 2);
if (endian_bytes.ToString () == "II" || endian_bytes.ToString () == "MM") {
bool makernote_endian = endian_bytes.ToString ().Equals ("MM");
ushort magic = header.Mid (12, 2).ToUShort (is_bigendian);
if (magic == 42) {
// TODO: the max_offset value is not correct here. However, some nikon files have offsets to a sub-ifd
// (preview image) which are not stored with the other makernote data. Therfore, we keep the max_offset
// for now. (It is just an upper bound for some checks. So if it is too big, it doesn't matter)
var reader = new Nikon3MakernoteReader (file, makernote_endian, ifd_structure, makernote_offset + 10, 8, max_offset - offset - 10);
reader.Read ();
return new MakernoteIFDEntry (tag, ifd_structure, MakernoteType.Nikon3, header.Mid (0, 18), 8, false, makernote_endian);
}
}
}
if (header.StartsWith (LEICA_HEADER)) {
var reader = new IFDReader (file, is_bigendian, ifd_structure, makernote_offset, 8, count);
reader.Read ();
return new MakernoteIFDEntry (tag, ifd_structure, MakernoteType.Leica, header.Mid (0, 8), 10, false, null);
}
try {
var reader = new IFDReader (file, is_bigendian, ifd_structure, baseOffset, offset, max_offset);
reader.Read ();
return new MakernoteIFDEntry (tag, ifd_structure, MakernoteType.Canon);
} catch {
return null;
}
}
#endregion
#region Protected Methods
/// <summary>
/// Try to parse the given IFD entry, used to discover format-specific entries.
/// </summary>
/// <param name="tag">
/// A <see cref="System.UInt16"/> with the tag of the entry.
/// </param>
/// <param name="type">
/// A <see cref="System.UInt16"/> with the type of the entry.
/// </param>
/// <param name="count">
/// A <see cref="System.UInt32"/> with the data count of the entry.
/// </param>
/// <param name="baseOffset">
/// A <see cref="System.Int64"/> with the base offset which every offsets in the
/// IFD are relative to.
/// </param>
/// <param name="offset">
/// A <see cref="System.UInt32"/> with the offset of the entry.
/// </param>
/// <returns>
/// A <see cref="IFDEntry"/> with the given parameters, or null if none was parsed, after
/// which the normal TIFF parsing is used.
/// </returns>
protected virtual IFDEntry ParseIFDEntry (ushort tag, ushort type, uint count, long baseOffset, uint offset)
{
if (tag == (ushort)ExifEntryTag.MakerNote && parse_makernote)
return ParseMakernote (tag, type, count, baseOffset, offset);
if (tag == (ushort)IFDEntryTag.SubIFDs) {
var entries = new List<IFDStructure> ();
uint[] data;
if (count >= 2) {
// This is impossible right?
if (baseOffset + offset > file.Length) {
file.MarkAsCorrupt ("Length of SubIFD is too long");
return null;
}
file.Seek (baseOffset + offset, SeekOrigin.Begin);
data = ReadUIntArray (count);
} else {
data = new[] { offset };
}
foreach (var sub_offset in data) {
var sub_structure = new IFDStructure ();
var sub_reader = CreateSubIFDReader (file, is_bigendian, sub_structure, baseOffset, sub_offset, max_offset);
sub_reader.Read ();
entries.Add (sub_structure);
}
return new SubIFDArrayEntry (tag, entries);
}
var ifd_structure = new IFDStructure ();
IFDReader reader = CreateSubIFDReader (file, is_bigendian, ifd_structure, baseOffset, offset, max_offset);
// Sub IFDs are either identified by the IFD-type ...
if (type == (ushort)IFDEntryType.IFD) {
reader.Read ();
return new SubIFDEntry (tag, type, (uint)ifd_structure.Directories.Length, ifd_structure);
}
// ... or by one of the following tags
switch (tag) {
case (ushort)IFDEntryTag.ExifIFD:
case (ushort)IFDEntryTag.InteroperabilityIFD:
case (ushort)IFDEntryTag.GPSIFD:
reader.Read ();
return new SubIFDEntry (tag, (ushort)IFDEntryType.Long, 1, ifd_structure);
default:
return null;
}
}
/// <summary>
/// Create a reader for Sub IFD entries.
/// </summary>
/// <param name="file">
/// A <see cref="File"/> to read from.
/// </param>
/// <param name="isBigendian">
/// A <see cref="System.Boolean"/>, it must be true, if the data of the IFD should be