Repository navigation
Expand file tree
/
Copy pathTinyEXIF.cpp
More file actions
1976 lines (1815 loc) · 69.4 KB
/
Copy pathTinyEXIF.cpp
File metadata and controls
1976 lines (1815 loc) · 69.4 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
/*
TinyEXIF.cpp -- A simple ISO C++ library to parse basic EXIF and XMP
information from a JPEG file.
Copyright (c) 2015-2025 Seacave
cdc.seacave@gmail.com
MIT License
*/
#include "TinyEXIF.h"
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cerrno>
#include <cmath>
#include <cfloat>
#include <vector>
#include <algorithm>
#include <bitset>
#include <iostream>
#include <sstream>
#ifndef TINYEXIF_NO_XMP_SUPPORT
#include <tinyxml2.h>
#endif // TINYEXIF_NO_XMP_SUPPORT
#ifdef _MSC_VER
namespace {
int strcasecmp(const char* a, const char* b) {
return _stricmp(a, b);
}
}
#else
#include <string.h>
#endif
#ifndef TINYEXIF_NO_XMP_SUPPORT
// helpers used only by the XMP parser, so a build without it does not warn they are unused
namespace Tools {
// search string inside a string, case sensitive
static const char* strrnstr(const char* haystack, const char* needle, size_t len) {
const size_t needle_len(strlen(needle));
if (0 == needle_len)
return haystack;
if (len <= needle_len)
return NULL;
for (size_t i=len-needle_len; i-- > 0; ) {
if (haystack[0] == needle[0] &&
0 == strncmp(haystack, needle, needle_len))
return haystack;
haystack++;
}
return NULL;
}
// split an input string with a delimiter and fill a string vector
static void strSplit(const std::string& str, char delim, std::vector<std::string>& values) {
values.clear();
std::string::size_type start(0), end(0);
while (end != std::string::npos) {
end = str.find(delim, start);
values.emplace_back(str.substr(start, end-start));
start = end + 1;
}
}
// true if a number was parsed out of 'str' and only whitespace follows it, given the
// 'end' where strtod() or strtoull() stopped: they parse the longest prefix they can,
// so "12junk" would read as 12 and "1e/2" as 1/2 instead of being malformed
static bool isWholeNumber(const char* str, const char* end) {
if (end == str)
return false;
while (isspace((unsigned char)*end))
++end;
return *end == '\0';
}
// parse a decimal number out of untrusted XMP text; fails unless the whole text is
// one number, surrounding whitespace aside, on a value out of range, and on the "nan"
// and "inf" that strtod accepts as well, so that the result is always a finite number
static bool strToDouble(const char* str, double& value) {
char* end(NULL);
errno = 0;
const double parsed(strtod(str, &end));
if (!isWholeNumber(str, end) || errno == ERANGE || !std::isfinite(parsed))
return false;
value = parsed;
return true;
}
// make sure the given degrees value is between -180 and 180
static double NormD180(double d) {
return (d = fmod(d+180.0, 360.0)) < 0 ? d+180.0 : d-180.0;
}
} // namespace Tools
#endif // TINYEXIF_NO_XMP_SUPPORT
namespace TinyEXIF {
enum JPEG_MARKERS {
JM_START = 0xFF,
JM_SOF0 = 0xC0,
JM_SOF1 = 0xC1,
JM_SOF2 = 0xC2,
JM_SOF3 = 0xC3,
JM_DHT = 0xC4,
JM_SOF5 = 0xC5,
JM_SOF6 = 0xC6,
JM_SOF7 = 0xC7,
JM_JPG = 0xC8,
JM_SOF9 = 0xC9,
JM_SOF10 = 0xCA,
JM_SOF11 = 0xCB,
JM_DAC = 0xCC,
JM_SOF13 = 0xCD,
JM_SOF14 = 0xCE,
JM_SOF15 = 0xCF,
JM_RST0 = 0xD0,
JM_RST1 = 0xD1,
JM_RST2 = 0xD2,
JM_RST3 = 0xD3,
JM_RST4 = 0xD4,
JM_RST5 = 0xD5,
JM_RST6 = 0xD6,
JM_RST7 = 0xD7,
JM_SOI = 0xD8,
JM_EOI = 0xD9,
JM_SOS = 0xDA,
JM_DQT = 0xDB,
JM_DNL = 0xDC,
JM_DRI = 0xDD,
JM_DHP = 0xDE,
JM_EXP = 0xDF,
JM_APP0 = 0xE0,
JM_APP1 = 0xE1, // EXIF and XMP
JM_APP2 = 0xE2,
JM_APP3 = 0xE3,
JM_APP4 = 0xE4,
JM_APP5 = 0xE5,
JM_APP6 = 0xE6,
JM_APP7 = 0xE7,
JM_APP8 = 0xE8,
JM_APP9 = 0xE9,
JM_APP10 = 0xEA,
JM_APP11 = 0xEB,
JM_APP12 = 0xEC,
JM_APP13 = 0xED, // IPTC
JM_APP14 = 0xEE,
JM_APP15 = 0xEF,
JM_JPG0 = 0xF0,
JM_JPG1 = 0xF1,
JM_JPG2 = 0xF2,
JM_JPG3 = 0xF3,
JM_JPG4 = 0xF4,
JM_JPG5 = 0xF5,
JM_JPG6 = 0xF6,
JM_JPG7 = 0xF7,
JM_JPG8 = 0xF8,
JM_JPG9 = 0xF9,
JM_JPG10 = 0xFA,
JM_JPG11 = 0xFB,
JM_JPG12 = 0xFC,
JM_JPG13 = 0xFD,
JM_COM = 0xFE
};
// Store 'value' in 'field' only if it is finite. Every floating point field must hold
// a finite value or none: inf and NaN from a crafted file would otherwise read back as
// present, since they differ from the DBL_MAX "absent" sentinel, and NaN slips through
// any range check a caller applies, as every comparison with it is false.
static bool AssignFinite(double& field, double value) {
if (!std::isfinite(value))
return false;
field = value;
return true;
}
// Parser helper
class EntryParser {
private:
const uint8_t* buf;
const unsigned len;
const unsigned tiff_header_start;
const bool alignIntel; // byte order of the file (TIFF header), independent of the host
unsigned offs; // current offset into buffer
uint16_t tag, format;
uint32_t length;
std::bitset<65536> seenTags; // one bit per possible tag of the current IFD
public:
EntryParser(const uint8_t* _buf, unsigned _len, unsigned _tiff_header_start, bool _alignIntel)
: buf(_buf), len(_len), tiff_header_start(_tiff_header_start), alignIntel(_alignIntel), offs(0) {}
// Every read of buf must be validated by this: does the range [offset, offset+size)
// lie inside the buffer? Written as a subtraction so the check itself can not
// overflow, and taking a 64bit offset so that offsets the caller computes from
// attacker controlled data (base + idx*size) can not wrap around either.
bool InBounds(uint64_t offset, uint32_t size) const {
return offset <= len && (uint64_t)len - offset >= size;
}
void Init(unsigned _offs) {
// ParseTag() steps forward by one entry before reading, so start one entry
// earlier; the wrap-around for _offs < 12 is undone by that same step
offs = _offs - 12;
seenTags.reset();
}
// Step to the next 12-byte IFD entry and read it;
// returns false without touching the current entry if it does not fit the buffer
bool ParseTag() {
offs += 12;
if (!InBounds(offs, 12))
return false;
tag = parse16(buf + offs, alignIntel);
format = parse16(buf + offs + 2, alignIntel);
length = parse32(buf + offs + 4, alignIntel);
return true;
}
// Check if the current entry's tag was already seen in this IFD (first occurrence wins).
// Per TIFF 6.0: "No two entries in the same IFD may have the same Tag."
bool IsDuplicateTag() {
if (seenTags.test(tag))
return true;
seenTags.set(tag);
return false;
}
const uint8_t* GetBuffer() const { return buf; }
unsigned GetOffset() const { return offs; }
bool IsIntelAligned() const { return alignIntel; }
// a parser over the same buffer and TIFF header, reading in the given byte order
EntryParser WithByteOrder(bool intel) const {
return EntryParser(buf, len, tiff_header_start, intel);
}
uint16_t GetTag() const { return tag; }
uint32_t GetLength() const { return length; }
uint32_t GetData() const { return parse32(buf + offs + 8, alignIntel); }
// absolute offset of the data this entry points to; 64bit because the data offset
// is fully attacker controlled and would wrap when added to the header start
uint64_t GetSubIFD() const { return (uint64_t)tiff_header_start + GetData(); }
bool IsShort() const { return format == 3; }
bool IsLong() const { return format == 4; }
bool IsRational() const { return format == 5 || format == 10; }
bool IsSRational() const { return format == 10; }
bool IsFloat() const { return format == 11; }
bool IsUndefined() const { return format == 7; }
std::string FetchString() const {
return parseString(buf, length, GetData(), tiff_header_start, len, alignIntel);
}
bool Fetch(std::string& val) const {
if (format != 2 || length == 0)
return false;
val = FetchString();
return true;
}
bool Fetch(uint8_t& val) const {
if ((format != 1 && format != 2 && format != 6) || length == 0)
return false;
val = parse8(buf + offs + 8);
return true;
}
bool Fetch(uint16_t& val) const {
if (!IsShort() || length == 0)
return false;
val = parse16(buf + offs + 8, alignIntel);
return true;
}
bool Fetch(uint16_t& val, uint32_t idx) const {
if (!IsShort() || length <= idx)
return false;
const uint64_t offset = GetSubIFD() + (uint64_t)idx*2;
if (!InBounds(offset, 2))
return false;
val = parse16(buf + (size_t)offset, alignIntel);
return true;
}
bool Fetch(uint32_t& val) const {
if (!IsLong() || length == 0)
return false;
val = parse32(buf + offs + 8, alignIntel);
return true;
}
bool Fetch(float& val) const {
if (!IsFloat() || length == 0)
return false;
// a FLOAT is raw IEEE 754 bits, so the file can encode inf or NaN directly
const float value(parseFloat(buf + offs + 8, alignIntel));
if (!std::isfinite(value))
return false;
val = value;
return true;
}
bool Fetch(double& val) const {
if (!IsRational() || length == 0)
return false;
const uint64_t offset = GetSubIFD();
if (!InBounds(offset, 8))
return false;
val = parseRational(buf + (size_t)offset, alignIntel, IsSRational());
return true;
}
bool Fetch(double& val, uint32_t idx) const {
if (!IsRational() || length <= idx)
return false;
const uint64_t offset = GetSubIFD() + (uint64_t)idx*8;
if (!InBounds(offset, 8))
return false;
val = parseRational(buf + (size_t)offset, alignIntel, IsSRational());
return true;
}
// Fetch a value stored as type T into a member of a different type, e.g. an
// image width written as SHORT instead of LONG; like Fetch(), it leaves 'val'
// untouched when the entry is not a T. The temporary is initialized so that no
// compiler has to prove Fetch() wrote it before it is read (gcc 16 can not, #30).
template <typename T, typename V>
bool FetchAs(V& val) const {
T stored = T();
if (!Fetch(stored))
return false;
val = (V)stored;
return true;
}
public:
static uint8_t parse8(const uint8_t* buf) {
return buf[0];
}
static uint16_t parse16(const uint8_t* buf, bool intel) {
if (intel)
return ((uint16_t)buf[1]<<8) | buf[0];
return ((uint16_t)buf[0]<<8) | buf[1];
}
static uint32_t parse32(const uint8_t* buf, bool intel) {
if (intel)
return ((uint32_t)buf[3]<<24) |
((uint32_t)buf[2]<<16) |
((uint32_t)buf[1]<<8) |
buf[0];
return ((uint32_t)buf[0]<<24) |
((uint32_t)buf[1]<<16) |
((uint32_t)buf[2]<<8) |
buf[3];
}
static float parseFloat(const uint8_t* buf, bool intel) {
union {
uint32_t i;
float f;
} i2f;
i2f.i = parse32(buf, intel);
return i2f.f;
}
static double parseRational(const uint8_t* buf, bool intel, bool isSigned) {
const uint32_t denominator = parse32(buf+4, intel);
if (denominator == 0)
return 0.0;
const uint32_t numerator = parse32(buf, intel);
return isSigned ?
(double)(int32_t)numerator/(double)(int32_t)denominator :
(double)numerator/(double)denominator;
}
static std::string parseString(const uint8_t* buf,
unsigned num_components,
unsigned data,
unsigned base,
unsigned len,
bool intel)
{
std::string value;
// num_components is a raw attacker controlled count and FetchString() passes
// it through unchecked, so reject zero here rather than at the callers: below,
// num_components-1 is an unsigned expression that would wrap to 0xffffffff and
// index that far past value.data(), then resize() to 4GiB if the byte read is 0
if (num_components == 0)
return value;
if (num_components <= 4) {
value.resize(num_components);
char j = intel ? 0 : 24;
char j_m = intel ? -8 : 8;
for (unsigned i=0; i<num_components; ++i, j -= j_m)
value[i] = (data >> j) & 0xff;
if (value[num_components-1] == '\0')
value.resize(num_components-1);
} else
if ((uint64_t)base+data+num_components <= (uint64_t)len) {
const char* const sz((const char*)buf+base+data);
unsigned num(0);
while (num < num_components && sz[num] != '\0')
++num;
while (num && sz[num-1] == ' ')
--num;
value.assign(sz, num);
}
return value;
}
};
// Constructors
EXIFInfo::EXIFInfo() : Fields(FIELD_NA) {
}
EXIFInfo::EXIFInfo(EXIFStream& stream) {
parseFrom(stream);
}
EXIFInfo::EXIFInfo(std::istream& stream) {
parseFrom(stream);
}
EXIFInfo::EXIFInfo(const uint8_t* data, unsigned length) {
parseFrom(data, length);
}
// Number of 64bit words needed to store one presence bit per FieldID
static const size_t FIELD_ID_WORDS = ((size_t)FIELD_ID_COUNT + 63) / 64;
// Name of every field, in FieldID order: the path of the member it fills
static const char* const g_FieldNames[] = {
"ImageWidth",
"ImageHeight",
"RelatedImageWidth",
"RelatedImageHeight",
"ImageDescription",
"Make",
"Model",
"SerialNumber",
"Orientation",
"XResolution",
"YResolution",
"ResolutionUnit",
"BitsPerSample",
"Software",
"DateTime",
"DateTimeOriginal",
"DateTimeDigitized",
"SubSecTimeOriginal",
"Copyright",
"ExposureTime",
"FNumber",
"ExposureProgram",
"ISOSpeedRatings",
"ShutterSpeedValue",
"ApertureValue",
"BrightnessValue",
"ExposureBiasValue",
"SubjectDistance",
"FocalLength",
"Flash",
"MeteringMode",
"LightSource",
"ProjectionType",
"SubjectArea",
"Calibration.FocalLength",
"Calibration.OpticalCenterX",
"Calibration.OpticalCenterY",
"Distortion.DewarpFlag",
"Distortion.K1",
"Distortion.K2",
"Distortion.P1",
"Distortion.P2",
"Distortion.K3",
"LensInfo.FStopMin",
"LensInfo.FStopMax",
"LensInfo.FocalLengthMin",
"LensInfo.FocalLengthMax",
"LensInfo.DigitalZoomRatio",
"LensInfo.FocalLengthIn35mm",
"LensInfo.FocalPlaneXResolution",
"LensInfo.FocalPlaneYResolution",
"LensInfo.FocalPlaneResolutionUnit",
"LensInfo.Make",
"LensInfo.Model",
"GeoLocation.Latitude",
"GeoLocation.Longitude",
"GeoLocation.Altitude",
"GeoLocation.AltitudeRef",
"GeoLocation.RelativeAltitude",
"GeoLocation.RollDegree",
"GeoLocation.PitchDegree",
"GeoLocation.YawDegree",
"GeoLocation.SpeedX",
"GeoLocation.SpeedY",
"GeoLocation.SpeedZ",
"GeoLocation.AccuracyXY",
"GeoLocation.AccuracyZ",
"GeoLocation.GPSDOP",
"GeoLocation.GPSDifferential",
"GeoLocation.GPSMapDatum",
"GeoLocation.GPSTimeStamp",
"GeoLocation.GPSDateStamp",
"GeoLocation.LatComponents.direction",
"GeoLocation.LonComponents.direction",
"GPano.PosePitchDegrees",
"GPano.PoseRollDegrees",
"GPano.PoseHeadingDegrees",
"GPano.ProjectionType",
"GPano.CroppedAreaImageWidthPixels",
"GPano.CroppedAreaImageHeightPixels",
"GPano.FullPanoWidthPixels",
"GPano.FullPanoHeightPixels",
"GPano.CroppedAreaLeftPixels",
"GPano.CroppedAreaTopPixels",
"MicroVideo.HasMicroVideo",
"MicroVideo.MicroVideoVersion",
"MicroVideo.MicroVideoOffset",
"MicroVideo.HasMotionPhoto",
"MicroVideo.MotionPhotoLength",
"MicroVideo.MotionPhotoMime",
"MaxApertureValue",
"MPImages",
};
static_assert(sizeof(g_FieldNames)/sizeof(g_FieldNames[0]) == (size_t)FIELD_ID_COUNT,
"g_FieldNames must have exactly one entry per FieldID");
const char* FieldName(FieldID id) {
const unsigned pos((unsigned)id);
return pos < (unsigned)FIELD_ID_COUNT ? g_FieldNames[pos] : "";
}
bool EXIFInfo::HasField(FieldID id) const {
const unsigned pos((unsigned)id);
if (pos >= (unsigned)FIELD_ID_COUNT)
return false;
const size_t word(pos/64);
// the bitset is only allocated once something is stored in it, so a parse
// that found nothing at all (or no parse at all) leaves it empty
return word < FieldsPresent.size() &&
(FieldsPresent[word] & ((uint64_t)1 << (pos%64))) != 0;
}
std::vector<FieldID> EXIFInfo::GetFields() const {
std::vector<FieldID> fields;
for (unsigned pos=0; pos<(unsigned)FIELD_ID_COUNT; ++pos)
if (HasField((FieldID)pos))
fields.push_back((FieldID)pos);
return fields;
}
void EXIFInfo::SetField(FieldID id) {
const unsigned pos((unsigned)id);
if (pos >= (unsigned)FIELD_ID_COUNT)
return;
// parseFromEXIFSegment()/parseFromXMPSegment() may be called directly, without
// the clear() that parseFrom() does, so the storage is allocated on demand
if (FieldsPresent.size() < FIELD_ID_WORDS)
FieldsPresent.resize(FIELD_ID_WORDS, 0);
FieldsPresent[pos/64] |= (uint64_t)1 << (pos%64);
}
bool EXIFInfo::SetFieldIf(FieldID id, bool fetched) {
if (fetched)
SetField(id);
return fetched;
}
// Parse tag as Image IFD
void EXIFInfo::parseIFDImage(EntryParser& parser, uint64_t& exif_sub_ifd_offset, uint64_t& gps_sub_ifd_offset) {
switch (parser.GetTag()) {
case 0x0102:
// Bits per sample
SetFieldIf(FIELD_ID_BitsPerSample, parser.Fetch(BitsPerSample));
break;
case 0x010e:
// Image description
SetFieldIf(FIELD_ID_ImageDescription, parser.Fetch(ImageDescription));
break;
case 0x010f:
// Camera maker
SetFieldIf(FIELD_ID_Make, parser.Fetch(Make));
break;
case 0x0110:
// Camera model
SetFieldIf(FIELD_ID_Model, parser.Fetch(Model));
break;
case 0x0112:
// Orientation of image
SetFieldIf(FIELD_ID_Orientation, parser.Fetch(Orientation));
break;
case 0x011a:
// XResolution
SetFieldIf(FIELD_ID_XResolution, parser.Fetch(XResolution));
break;
case 0x011b:
// YResolution
SetFieldIf(FIELD_ID_YResolution, parser.Fetch(YResolution));
break;
case 0x0128:
// Resolution Unit
SetFieldIf(FIELD_ID_ResolutionUnit, parser.Fetch(ResolutionUnit));
break;
case 0x0131:
// Software used for image
SetFieldIf(FIELD_ID_Software, parser.Fetch(Software));
break;
case 0x0132:
// EXIF/TIFF date/time of image modification
SetFieldIf(FIELD_ID_DateTime, parser.Fetch(DateTime));
break;
case 0x1001:
// Original Image width (LONG or SHORT)
SetFieldIf(FIELD_ID_RelatedImageWidth, parser.Fetch(RelatedImageWidth) || parser.FetchAs<uint16_t>(RelatedImageWidth));
break;
case 0x1002:
// Original Image height (LONG or SHORT)
SetFieldIf(FIELD_ID_RelatedImageHeight, parser.Fetch(RelatedImageHeight) || parser.FetchAs<uint16_t>(RelatedImageHeight));
break;
case 0x8298:
// Copyright information
SetFieldIf(FIELD_ID_Copyright, parser.Fetch(Copyright));
break;
case 0x8769:
// EXIF SubIFD offset
exif_sub_ifd_offset = parser.GetSubIFD();
break;
case 0x8825:
// GPS IFS offset
gps_sub_ifd_offset = parser.GetSubIFD();
break;
default:
// Try to parse as EXIF tag, as some images store them in here
parseIFDExif(parser);
break;
}
}
// Parse tag as Exif IFD
void EXIFInfo::parseIFDExif(EntryParser& parser) {
switch (parser.GetTag()) {
case 0x02bc:
#ifndef TINYEXIF_NO_XMP_SUPPORT
// XMP Metadata (Adobe technote 9-14-02): IFD0 and the EXIF SubIFD are each read once
// per EXIF segment and repeated tags are skipped, so this runs at most twice per
// segment, and not at all once XMP was parsed from an earlier segment
if (parser.IsUndefined() && !(Fields & FIELD_XMP)) {
const std::string strXML(parser.FetchString());
if (parseFromXMPSegmentXML(strXML.c_str(), (unsigned)strXML.length()) == PARSE_SUCCESS)
Fields |= FIELD_XMP;
}
#endif // TINYEXIF_NO_XMP_SUPPORT
break;
case 0x829a:
// Exposure time in seconds
SetFieldIf(FIELD_ID_ExposureTime, parser.Fetch(ExposureTime));
break;
case 0x829d:
// FNumber
SetFieldIf(FIELD_ID_FNumber, parser.Fetch(FNumber));
break;
case 0x8822:
// Exposure Program
SetFieldIf(FIELD_ID_ExposureProgram, parser.Fetch(ExposureProgram));
break;
case 0x8827:
// ISO Speed Rating
SetFieldIf(FIELD_ID_ISOSpeedRatings, parser.Fetch(ISOSpeedRatings));
break;
case 0x9003:
// Original date and time
SetFieldIf(FIELD_ID_DateTimeOriginal, parser.Fetch(DateTimeOriginal));
break;
case 0x9004:
// Digitization date and time
SetFieldIf(FIELD_ID_DateTimeDigitized, parser.Fetch(DateTimeDigitized));
break;
case 0x9201: {
// Shutter speed value, converted from APEX to seconds
// the conversion only runs on a value that was really fetched: applied to the
// untouched 0 it would yield a plausible 1s; and its result is only kept when
// finite: an APEX value far outside any camera's range underflows exp() to 0
double apex(0);
SetFieldIf(FIELD_ID_ShutterSpeedValue, parser.Fetch(apex) && AssignFinite(ShutterSpeedValue, 1.0/exp(apex*log(2))));
break;
}
case 0x9202: {
// Aperture value, converted from APEX to an f-number
// as above: the untouched 0 would convert to a plausible f/1, and an APEX
// value far outside any lens's range overflows exp() to inf
double apex(0);
SetFieldIf(FIELD_ID_ApertureValue, parser.Fetch(apex) && AssignFinite(ApertureValue, exp(apex*log(2)*0.5)));
break;
}
case 0x9205: {
// Max aperture value, the widest aperture of the lens, converted from APEX
// to an f-number exactly like ApertureValue above
double apex(0);
SetFieldIf(FIELD_ID_MaxApertureValue, parser.Fetch(apex) && AssignFinite(MaxApertureValue, exp(apex*log(2)*0.5)));
break;
}
case 0x9203:
// Brightness value
SetFieldIf(FIELD_ID_BrightnessValue, parser.Fetch(BrightnessValue));
break;
case 0x9204:
// Exposure bias value
SetFieldIf(FIELD_ID_ExposureBiasValue, parser.Fetch(ExposureBiasValue));
break;
case 0x9206:
// Subject distance
SetFieldIf(FIELD_ID_SubjectDistance, parser.Fetch(SubjectDistance));
break;
case 0x9207:
// Metering mode
SetFieldIf(FIELD_ID_MeteringMode, parser.Fetch(MeteringMode));
break;
case 0x9208:
// Light source
SetFieldIf(FIELD_ID_LightSource, parser.Fetch(LightSource));
break;
case 0x9209:
// Flash info
SetFieldIf(FIELD_ID_Flash, parser.Fetch(Flash));
break;
case 0x920a:
// Focal length
SetFieldIf(FIELD_ID_FocalLength, parser.Fetch(FocalLength));
break;
case 0x9214:
// Subject area: 2, 3, or 4 coordinates per EXIF 2.32
if (parser.IsShort() && parser.GetLength() >= 2 && parser.GetLength() <= 4) {
// GetLength() is an attacker-controlled count; validate the whole array
// fits the buffer before sizing the vector to match it, rather than
// resizing first and relying on the per-element Fetch() bounds check
const uint64_t dataSize = (uint64_t)parser.GetLength()*2;
if (dataSize <= UINT32_MAX && parser.InBounds(parser.GetSubIFD(), (uint32_t)dataSize)) {
SubjectArea.resize(parser.GetLength());
for (uint32_t i=0; i<parser.GetLength(); ++i)
SetFieldIf(FIELD_ID_SubjectArea, parser.Fetch(SubjectArea[i], i));
}
}
break;
case 0x927c:
// MakerNote
parseIFDMakerNote(parser);
break;
case 0x9291:
// Fractions of seconds for DateTimeOriginal
SetFieldIf(FIELD_ID_SubSecTimeOriginal, parser.Fetch(SubSecTimeOriginal));
break;
case 0xa002:
// EXIF Image width (LONG or SHORT)
SetFieldIf(FIELD_ID_ImageWidth, parser.Fetch(ImageWidth) || parser.FetchAs<uint16_t>(ImageWidth));
break;
case 0xa003:
// EXIF Image height (LONG or SHORT)
SetFieldIf(FIELD_ID_ImageHeight, parser.Fetch(ImageHeight) || parser.FetchAs<uint16_t>(ImageHeight));
break;
case 0xa20e:
// Focal plane X resolution
SetFieldIf(FIELD_ID_LensInfo_FocalPlaneXResolution, parser.Fetch(LensInfo.FocalPlaneXResolution));
break;
case 0xa20f:
// Focal plane Y resolution
SetFieldIf(FIELD_ID_LensInfo_FocalPlaneYResolution, parser.Fetch(LensInfo.FocalPlaneYResolution));
break;
case 0xa210:
// Focal plane resolution unit
SetFieldIf(FIELD_ID_LensInfo_FocalPlaneResolutionUnit, parser.Fetch(LensInfo.FocalPlaneResolutionUnit));
break;
case 0xa215:
// Exposure Index and ISO Speed Rating are often used interchangeably;
// converting a double that uint16_t can not represent is undefined behavior,
// so a negative index is rejected and a large one clamped, as EXIF does for ISO
if (ISOSpeedRatings == 0) {
double ExposureIndex(0);
if (parser.Fetch(ExposureIndex) && ExposureIndex >= 0) {
ISOSpeedRatings = (uint16_t)std::min(ExposureIndex, (double)UINT16_MAX);
SetField(FIELD_ID_ISOSpeedRatings);
}
}
break;
case 0xa404:
// Digital Zoom Ratio
SetFieldIf(FIELD_ID_LensInfo_DigitalZoomRatio, parser.Fetch(LensInfo.DigitalZoomRatio));
break;
case 0xa405:
// Focal length in 35mm film (SHORT per EXIF, RATIONAL in some files)
SetFieldIf(FIELD_ID_LensInfo_FocalLengthIn35mm, parser.Fetch(LensInfo.FocalLengthIn35mm) || parser.FetchAs<uint16_t>(LensInfo.FocalLengthIn35mm));
break;
case 0xa431:
// Serial number of the camera
SetFieldIf(FIELD_ID_SerialNumber, parser.Fetch(SerialNumber));
break;
case 0xa432:
// Focal length and FStop.
if (SetFieldIf(FIELD_ID_LensInfo_FocalLengthMin, parser.Fetch(LensInfo.FocalLengthMin, 0)))
if (SetFieldIf(FIELD_ID_LensInfo_FocalLengthMax, parser.Fetch(LensInfo.FocalLengthMax, 1)))
if (SetFieldIf(FIELD_ID_LensInfo_FStopMin, parser.Fetch(LensInfo.FStopMin, 2)))
SetFieldIf(FIELD_ID_LensInfo_FStopMax, parser.Fetch(LensInfo.FStopMax, 3));
break;
case 0xa433:
// Lens make.
SetFieldIf(FIELD_ID_LensInfo_Make, parser.Fetch(LensInfo.Make));
break;
case 0xa434:
// Lens model.
SetFieldIf(FIELD_ID_LensInfo_Model, parser.Fetch(LensInfo.Model));
break;
}
}
// Parse tag as MakerNote IFD
void EXIFInfo::parseIFDMakerNote(EntryParser& exif) {
if (0 != strcasecmp(Make.c_str(), "DJI"))
return;
// the MakerNote is a full IFD of its own: entry count followed by 12-byte entries,
// none of which the tag's own length field is allowed to vouch for
const uint64_t off = exif.GetSubIFD();
if (!exif.InBounds(off, 4))
return;
// it is walked by a parser of its own, as its byte order can differ from the EXIF
// one: DJI writes it little-endian, and a tool rewriting the EXIF in Motorola order
// copies this opaque blob unchanged; the right order is the one in which the first
// entry reads as tag 1, the "DJI" make
const uint8_t* const note(exif.GetBuffer() + (size_t)off);
EntryParser parser(exif.WithByteOrder(EntryParser::parse16(note + 2, true) == 1));
int num_entries = EntryParser::parse16(note, parser.IsIntelAligned());
if (uint32_t(2 + 12 * num_entries) > exif.GetLength())
return;
if (!parser.InBounds(off+2, 12*(uint32_t)num_entries))
return;
parser.Init((unsigned)(off+2));
if (!parser.ParseTag())
return;
--num_entries;
std::string maker;
if (parser.GetTag() == 1 && parser.Fetch(maker)) {
if (0 == strcasecmp(maker.c_str(), "DJI")) {
while (--num_entries >= 0) {
if (!parser.ParseTag())
break;
if (parser.IsDuplicateTag())
continue;
switch (parser.GetTag()) {
case 3:
// SpeedX
SetFieldIf(FIELD_ID_GeoLocation_SpeedX, parser.FetchAs<float>(GeoLocation.SpeedX));
break;
case 4:
// SpeedY
SetFieldIf(FIELD_ID_GeoLocation_SpeedY, parser.FetchAs<float>(GeoLocation.SpeedY));
break;
case 5:
// SpeedZ
SetFieldIf(FIELD_ID_GeoLocation_SpeedZ, parser.FetchAs<float>(GeoLocation.SpeedZ));
break;
case 9:
// Camera Pitch
SetFieldIf(FIELD_ID_GeoLocation_PitchDegree, parser.FetchAs<float>(GeoLocation.PitchDegree));
break;
case 10:
// Camera Yaw
SetFieldIf(FIELD_ID_GeoLocation_YawDegree, parser.FetchAs<float>(GeoLocation.YawDegree));
break;
case 11:
// Camera Roll
SetFieldIf(FIELD_ID_GeoLocation_RollDegree, parser.FetchAs<float>(GeoLocation.RollDegree));
break;
}
}
}
}
}
// GPS IFD tags 1 to 6: latitude, longitude and altitude, each with its reference
static bool IsGPSPositionTag(uint16_t tag) {
return tag >= 1 && tag <= 6;
}
// True if the GPS IFD whose entries start at 'offs' has GPSStatus 'V': the receiver
// reports its measurement void, i.e. it had no fix. Cameras still write the position
// tags then, usually all zeros, which would place the image at 0N 0E; so the caller
// skips them, leaving the position absent instead of wrong.
static bool IsGPSMeasurementVoid(EntryParser& parser, unsigned offs, unsigned num_entries) {
std::string status;
parser.Init(offs);
while (num_entries-- > 0 && parser.ParseTag())
if (parser.GetTag() == 9 && parser.Fetch(status))
return status == "V";
return false;
}
// Parse tag as GPS IFD
void EXIFInfo::parseIFDGPS(EntryParser& parser) {
switch (parser.GetTag()) {
case 1:
// GPS north or south
SetFieldIf(FIELD_ID_GeoLocation_LatComponents_direction, parser.Fetch(GeoLocation.LatComponents.direction));
break;
case 2:
// GPS latitude
// the components are what parseCoords() turns into GeoLocation.Latitude,
// so they mark that field rather than one enumerator each
if (parser.IsRational() && parser.GetLength() == 3) {
SetFieldIf(FIELD_ID_GeoLocation_Latitude, parser.Fetch(GeoLocation.LatComponents.degrees, 0));
SetFieldIf(FIELD_ID_GeoLocation_Latitude, parser.Fetch(GeoLocation.LatComponents.minutes, 1));
SetFieldIf(FIELD_ID_GeoLocation_Latitude, parser.Fetch(GeoLocation.LatComponents.seconds, 2));
}
break;
case 3:
// GPS east or west
SetFieldIf(FIELD_ID_GeoLocation_LonComponents_direction, parser.Fetch(GeoLocation.LonComponents.direction));
break;
case 4:
// GPS longitude
if (parser.IsRational() && parser.GetLength() == 3) {
SetFieldIf(FIELD_ID_GeoLocation_Longitude, parser.Fetch(GeoLocation.LonComponents.degrees, 0));
SetFieldIf(FIELD_ID_GeoLocation_Longitude, parser.Fetch(GeoLocation.LonComponents.minutes, 1));
SetFieldIf(FIELD_ID_GeoLocation_Longitude, parser.Fetch(GeoLocation.LonComponents.seconds, 2));
}
break;
case 5:
// GPS altitude reference (below or above sea level)
SetFieldIf(FIELD_ID_GeoLocation_AltitudeRef, parser.FetchAs<uint8_t>(GeoLocation.AltitudeRef));
break;
case 6:
// GPS altitude
SetFieldIf(FIELD_ID_GeoLocation_Altitude, parser.Fetch(GeoLocation.Altitude));
break;
case 7:
// GPS timestamp
if (parser.IsRational() && parser.GetLength() == 3) {
// Fetch() leaves its out-parameter untouched when the bounds check
// rejects the offset, so the three are initialized and all three must
// succeed: hour, minute and second are one logical value and a partial
// timestamp is not a timestamp
double h(0), m(0), s(0);
if (parser.Fetch(h, 0) && parser.Fetch(m, 1) && parser.Fetch(s, 2)) {
char buffer[256];
snprintf(buffer, 256, "%g %g %g", h, m, s);
GeoLocation.GPSTimeStamp = buffer;
SetField(FIELD_ID_GeoLocation_GPSTimeStamp);