-
Notifications
You must be signed in to change notification settings - Fork 70
/
ifd_enumerate.go
1356 lines (1047 loc) · 34.6 KB
/
ifd_enumerate.go
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
package exif
import (
"bytes"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"encoding/binary"
"github.com/dsoprea/go-logging"
)
var (
ifdEnumerateLogger = log.NewLogger("exifjpeg.ifd")
)
var (
ErrNoThumbnail = errors.New("no thumbnail")
ErrNoGpsTags = errors.New("no gps tags")
ErrTagTypeNotValid = errors.New("tag type invalid")
)
var (
ValidGpsVersions = [][4]byte{
{2, 2, 0, 0},
// Suddenly appeared at the default in 2.31: https://home.jeita.or.jp/tsc/std-pdf/CP-3451D.pdf
//
// Note that the presence of 2.3.0.0 doesn't seem to guarantee
// coordinates. In some cases, we seen just the following:
//
// GPS Tag Version |2.3.0.0
// GPS Receiver Status |V
// Geodetic Survey Data|WGS-84
// GPS Differential Cor|0
//
{2, 3, 0, 0},
}
)
// IfdTagEnumerator knows how to decode an IFD and all of the tags it
// describes.
//
// The IFDs and the actual values can float throughout the EXIF block, but the
// IFD itself is just a minor header followed by a set of repeating,
// statically-sized records. So, the tags (though notnecessarily their values)
// are fairly simple to enumerate.
type IfdTagEnumerator struct {
byteOrder binary.ByteOrder
addressableData []byte
ifdOffset uint32
buffer *bytes.Buffer
}
func NewIfdTagEnumerator(addressableData []byte, byteOrder binary.ByteOrder, ifdOffset uint32) (ite *IfdTagEnumerator) {
ite = &IfdTagEnumerator{
addressableData: addressableData,
byteOrder: byteOrder,
buffer: bytes.NewBuffer(addressableData[ifdOffset:]),
}
return ite
}
// getUint16 reads a uint16 and advances both our current and our current
// accumulator (which allows us to know how far to seek to the beginning of the
// next IFD when it's time to jump).
func (ife *IfdTagEnumerator) getUint16() (value uint16, raw []byte, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
needBytes := 2
offset := 0
raw = make([]byte, needBytes)
for offset < needBytes {
n, err := ife.buffer.Read(raw[offset:])
log.PanicIf(err)
offset += n
}
value = ife.byteOrder.Uint16(raw)
return value, raw, nil
}
// getUint32 reads a uint32 and advances both our current and our current
// accumulator (which allows us to know how far to seek to the beginning of the
// next IFD when it's time to jump).
func (ife *IfdTagEnumerator) getUint32() (value uint32, raw []byte, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
needBytes := 4
offset := 0
raw = make([]byte, needBytes)
for offset < needBytes {
n, err := ife.buffer.Read(raw[offset:])
log.PanicIf(err)
offset += n
}
value = ife.byteOrder.Uint32(raw)
return value, raw, nil
}
type IfdEnumerate struct {
exifData []byte
buffer *bytes.Buffer
byteOrder binary.ByteOrder
currentOffset uint32
tagIndex *TagIndex
ifdMapping *IfdMapping
}
func NewIfdEnumerate(ifdMapping *IfdMapping, tagIndex *TagIndex, exifData []byte, byteOrder binary.ByteOrder) *IfdEnumerate {
return &IfdEnumerate{
exifData: exifData,
buffer: bytes.NewBuffer(exifData),
byteOrder: byteOrder,
ifdMapping: ifdMapping,
tagIndex: tagIndex,
}
}
func (ie *IfdEnumerate) getTagEnumerator(ifdOffset uint32) (ite *IfdTagEnumerator) {
ite = NewIfdTagEnumerator(
ie.exifData[ExifAddressableAreaStart:],
ie.byteOrder,
ifdOffset)
return ite
}
func (ie *IfdEnumerate) parseTag(fqIfdPath string, tagPosition int, ite *IfdTagEnumerator, resolveValue bool) (tag *IfdTagEntry, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
tagId, _, err := ite.getUint16()
log.PanicIf(err)
tagTypeRaw, _, err := ite.getUint16()
log.PanicIf(err)
tagType := TagTypePrimitive(tagTypeRaw)
unitCount, _, err := ite.getUint32()
log.PanicIf(err)
valueOffset, rawValueOffset, err := ite.getUint32()
log.PanicIf(err)
if _, found := TypeNames[tagType]; found == false {
log.Panic(ErrTagTypeNotValid)
}
ifdPath, err := ie.ifdMapping.StripPathPhraseIndices(fqIfdPath)
log.PanicIf(err)
tag = &IfdTagEntry{
IfdPath: ifdPath,
TagId: tagId,
TagIndex: tagPosition,
TagType: tagType,
UnitCount: unitCount,
ValueOffset: valueOffset,
RawValueOffset: rawValueOffset,
}
if resolveValue == true {
value, isUnhandledUnknown, err := ie.resolveTagValue(tag)
log.PanicIf(err)
tag.value = value
tag.isUnhandledUnknown = isUnhandledUnknown
}
// If it's an IFD but not a standard one, it'll just be seen as a LONG
// (the standard IFD tag type), later, unless we skip it because it's
// [likely] not even in the standard list of known tags.
mi, err := ie.ifdMapping.GetChild(ifdPath, tagId)
if err == nil {
tag.ChildIfdName = mi.Name
tag.ChildIfdPath = mi.PathPhrase()
tag.ChildFqIfdPath = fmt.Sprintf("%s/%s", fqIfdPath, mi.Name)
// We also need to set `tag.ChildFqIfdPath` but can't do it here
// because we don't have the IFD index.
} else if log.Is(err, ErrChildIfdNotMapped) == false {
log.Panic(err)
}
return tag, nil
}
func (ie *IfdEnumerate) GetValueContext(ite *IfdTagEntry) *ValueContext {
// TODO(dustin): Add test
addressableData := ie.exifData[ExifAddressableAreaStart:]
return newValueContextFromTag(
ite,
addressableData,
ie.byteOrder)
}
func (ie *IfdEnumerate) resolveTagValue(ite *IfdTagEntry) (valueBytes []byte, isUnhandledUnknown bool, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
addressableData := ie.exifData[ExifAddressableAreaStart:]
// Return the exact bytes of the unknown-type value. Returning a string
// (`ValueString`) is easy because we can just pass everything to
// `Sprintf()`. Returning the raw, typed value (`Value`) is easy
// (obviously). However, here, in order to produce the list of bytes, we
// need to coerce whatever `Undefined()` returns.
if ite.TagType == TypeUndefined {
valueContext := ie.GetValueContext(ite)
value, err := valueContext.Undefined()
if err != nil {
if err == ErrUnhandledUnknownTypedTag {
valueBytes = []byte(UnparseableUnknownTagValuePlaceholder)
return valueBytes, true, nil
}
log.Panic(err)
} else {
switch value.(type) {
case []byte:
return value.([]byte), false, nil
case TagUnknownType_UnknownValue:
b := []byte(value.(TagUnknownType_UnknownValue))
return b, false, nil
case string:
return []byte(value.(string)), false, nil
case UnknownTagValue:
valueBytes, err := value.(UnknownTagValue).ValueBytes()
log.PanicIf(err)
return valueBytes, false, nil
default:
// TODO(dustin): !! Finish translating the rest of the types (make reusable and replace into other similar implementations?)
log.Panicf("can not produce bytes for unknown-type tag (0x%04x) (1): [%s]", ite.TagId, reflect.TypeOf(value))
}
}
} else {
originalType := NewTagType(ite.TagType, ie.byteOrder)
byteCount := uint32(originalType.Type().Size()) * ite.UnitCount
tt := NewTagType(TypeByte, ie.byteOrder)
if tt.valueIsEmbedded(byteCount) == true {
iteLogger.Debugf(nil, "Reading BYTE value (ITE; embedded).")
// In this case, the bytes normally used for the offset are actually
// data.
valueBytes, err = tt.ParseBytes(ite.RawValueOffset, byteCount)
log.PanicIf(err)
} else {
iteLogger.Debugf(nil, "Reading BYTE value (ITE; at offset).")
valueBytes, err = tt.ParseBytes(addressableData[ite.ValueOffset:], byteCount)
log.PanicIf(err)
}
}
return valueBytes, false, nil
}
// RawTagVisitorPtr is an optional callback that can get hit for every tag we parse
// through. `addressableData` is the byte array startign after the EXIF header
// (where the offsets of all IFDs and values are calculated from).
//
// This was reimplemented as an interface to allow for simpler change management
// in the future.
type RawTagWalk interface {
Visit(fqIfdPath string, ifdIndex int, tagId uint16, tagType TagType, valueContext *ValueContext) (err error)
}
type RawTagWalkLegacyWrapper struct {
legacyVisitor RawTagVisitor
}
func (rtwlw RawTagWalkLegacyWrapper) Visit(fqIfdPath string, ifdIndex int, tagId uint16, tagType TagType, valueContext *ValueContext) (err error) {
return rtwlw.legacyVisitor(fqIfdPath, ifdIndex, tagId, tagType, *valueContext)
}
// RawTagVisitor is an optional callback that can get hit for every tag we parse
// through. `addressableData` is the byte array startign after the EXIF header
// (where the offsets of all IFDs and values are calculated from).
//
// DEPRECATED(dustin): Use a RawTagWalk instead.
type RawTagVisitor func(fqIfdPath string, ifdIndex int, tagId uint16, tagType TagType, valueContext ValueContext) (err error)
// ParseIfd decodes the IFD block that we're currently sitting on the first
// byte of.
func (ie *IfdEnumerate) ParseIfd(fqIfdPath string, ifdIndex int, ite *IfdTagEnumerator, visitor interface{}, doDescend bool, resolveValues bool) (nextIfdOffset uint32, entries []*IfdTagEntry, thumbnailData []byte, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
var visitorWrapper RawTagWalk
if visitor != nil {
var ok bool
visitorWrapper, ok = visitor.(RawTagWalk)
if ok == false {
// Legacy usage.
// `ok` can be `true` but `legacyVisitor` can still be `nil` (when
// passed as nil).
if legacyVisitor, ok := visitor.(RawTagVisitor); ok == true && legacyVisitor != nil {
visitorWrapper = RawTagWalkLegacyWrapper{
legacyVisitor: legacyVisitor,
}
}
}
}
tagCount, _, err := ite.getUint16()
log.PanicIf(err)
ifdEnumerateLogger.Debugf(nil, "Current IFD tag-count: (%d)", tagCount)
entries = make([]*IfdTagEntry, 0)
var iteThumbnailOffset *IfdTagEntry
var iteThumbnailSize *IfdTagEntry
for i := 0; i < int(tagCount); i++ {
tag, err := ie.parseTag(fqIfdPath, i, ite, resolveValues)
if err != nil {
if log.Is(err, ErrTagTypeNotValid) == true {
ifdEnumerateLogger.Warningf(nil, "Tag in IFD [%s] at position (%d) has invalid type and will be skipped.", fqIfdPath, i)
continue
}
log.Panic(err)
}
if tag.TagId == ThumbnailOffsetTagId {
iteThumbnailOffset = tag
continue
} else if tag.TagId == ThumbnailSizeTagId {
iteThumbnailSize = tag
continue
}
if visitorWrapper != nil {
tt := NewTagType(tag.TagType, ie.byteOrder)
valueContext := ie.GetValueContext(tag)
err := visitorWrapper.Visit(fqIfdPath, ifdIndex, tag.TagId, tt, valueContext)
log.PanicIf(err)
}
// If it's an IFD but not a standard one, it'll just be seen as a LONG
// (the standard IFD tag type), later, unless we skip it because it's
// [likely] not even in the standard list of known tags.
if tag.ChildIfdPath != "" {
if doDescend == true {
ifdEnumerateLogger.Debugf(nil, "Descending to IFD [%s].", tag.ChildIfdPath)
err := ie.scan(tag.ChildFqIfdPath, tag.ValueOffset, visitor, resolveValues)
log.PanicIf(err)
}
}
entries = append(entries, tag)
}
if iteThumbnailOffset != nil && iteThumbnailSize != nil {
thumbnailData, err = ie.parseThumbnail(iteThumbnailOffset, iteThumbnailSize)
log.PanicIf(err)
}
nextIfdOffset, _, err = ite.getUint32()
log.PanicIf(err)
ifdEnumerateLogger.Debugf(nil, "Next IFD at offset: (%08x)", nextIfdOffset)
return nextIfdOffset, entries, thumbnailData, nil
}
func (ie *IfdEnumerate) parseThumbnail(offsetIte, lengthIte *IfdTagEntry) (thumbnailData []byte, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
addressableData := ie.exifData[ExifAddressableAreaStart:]
vRaw, err := lengthIte.Value(addressableData, ie.byteOrder)
log.PanicIf(err)
vList := vRaw.([]uint32)
if len(vList) != 1 {
log.Panicf("not exactly one long: (%d)", len(vList))
}
length := vList[0]
// The tag is official a LONG type, but it's actually an offset to a blob of bytes.
offsetIte.TagType = TypeByte
offsetIte.UnitCount = length
thumbnailData, err = offsetIte.ValueBytes(addressableData, ie.byteOrder)
log.PanicIf(err)
return thumbnailData, nil
}
// Scan enumerates the different EXIF's IFD blocks.
func (ie *IfdEnumerate) scan(fqIfdName string, ifdOffset uint32, visitor interface{}, resolveValues bool) (err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
for ifdIndex := 0; ; ifdIndex++ {
ifdEnumerateLogger.Debugf(nil, "Parsing IFD [%s] (%d) at offset (%04x).", fqIfdName, ifdIndex, ifdOffset)
ite := ie.getTagEnumerator(ifdOffset)
nextIfdOffset, _, _, err := ie.ParseIfd(fqIfdName, ifdIndex, ite, visitor, true, resolveValues)
log.PanicIf(err)
if nextIfdOffset == 0 {
break
}
ifdOffset = nextIfdOffset
}
return nil
}
// Scan enumerates the different EXIF blocks (called IFDs). `rootIfdName` will
// be "IFD" in the TIFF standard.
func (ie *IfdEnumerate) Scan(rootIfdName string, ifdOffset uint32, visitor RawTagVisitor, resolveValue bool) (err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
err = ie.scan(rootIfdName, ifdOffset, visitor, resolveValue)
log.PanicIf(err)
return nil
}
// Ifd represents a single parsed IFD.
type Ifd struct {
// TODO(dustin): !! Why are all of these public? Privatize them and then add NextIfd().
// This is just for convenience, just so that we can easily get the values
// and not involve other projects in semantics that they won't otherwise
// need to know.
addressableData []byte
ByteOrder binary.ByteOrder
// Name is the name of the IFD (the rightmost name in the path, sans any
// indices).
Name string
// IfdPath is a simple IFD path (e.g. IFD/GPSInfo). No indices.
IfdPath string
// FqIfdPath is a fully-qualified IFD path (e.g. IFD0/GPSInfo0). With
// indices.
FqIfdPath string
TagId uint16
Id int
ParentIfd *Ifd
// ParentTagIndex is our tag position in the parent IFD, if we had a parent
// (if `ParentIfd` is not nil and we weren't an IFD referenced as a sibling
// instead of as a child).
ParentTagIndex int
// Name string
Index int
Offset uint32
Entries []*IfdTagEntry
EntriesByTagId map[uint16][]*IfdTagEntry
Children []*Ifd
ChildIfdIndex map[string]*Ifd
NextIfdOffset uint32
NextIfd *Ifd
thumbnailData []byte
ifdMapping *IfdMapping
tagIndex *TagIndex
}
func (ifd *Ifd) ChildWithIfdPath(ifdPath string) (childIfd *Ifd, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
for _, childIfd := range ifd.Children {
if childIfd.IfdPath == ifdPath {
return childIfd, nil
}
}
log.Panic(ErrTagNotFound)
return nil, nil
}
func (ifd *Ifd) TagValue(ite *IfdTagEntry) (value interface{}, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
value, err = ite.Value(ifd.addressableData, ifd.ByteOrder)
log.PanicIf(err)
return value, nil
}
func (ifd *Ifd) TagValueBytes(ite *IfdTagEntry) (value []byte, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
value, err = ite.ValueBytes(ifd.addressableData, ifd.ByteOrder)
log.PanicIf(err)
return value, nil
}
// FindTagWithId returns a list of tags (usually just zero or one) that match
// the given tag ID. This is efficient.
func (ifd *Ifd) FindTagWithId(tagId uint16) (results []*IfdTagEntry, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
results, found := ifd.EntriesByTagId[tagId]
if found != true {
log.Panic(ErrTagNotFound)
}
return results, nil
}
// FindTagWithName returns a list of tags (usually just zero or one) that match
// the given tag name. This is not efficient (though the labor is trivial).
func (ifd *Ifd) FindTagWithName(tagName string) (results []*IfdTagEntry, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
it, err := ifd.tagIndex.GetWithName(ifd.IfdPath, tagName)
if log.Is(err, ErrTagNotFound) == true {
log.Panic(ErrTagNotStandard)
} else if err != nil {
log.Panic(err)
}
results = make([]*IfdTagEntry, 0)
for _, ite := range ifd.Entries {
if ite.TagId == it.Id {
results = append(results, ite)
}
}
if len(results) == 0 {
log.Panic(ErrTagNotFound)
}
return results, nil
}
func (ifd Ifd) String() string {
parentOffset := uint32(0)
if ifd.ParentIfd != nil {
parentOffset = ifd.ParentIfd.Offset
}
return fmt.Sprintf("Ifd<ID=(%d) IFD-PATH=[%s] INDEX=(%d) COUNT=(%d) OFF=(0x%04x) CHILDREN=(%d) PARENT=(0x%04x) NEXT-IFD=(0x%04x)>", ifd.Id, ifd.IfdPath, ifd.Index, len(ifd.Entries), ifd.Offset, len(ifd.Children), parentOffset, ifd.NextIfdOffset)
}
func (ifd *Ifd) Thumbnail() (data []byte, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
if ifd.thumbnailData == nil {
log.Panic(ErrNoThumbnail)
}
return ifd.thumbnailData, nil
}
func (ifd *Ifd) dumpTags(tags []*IfdTagEntry) []*IfdTagEntry {
if tags == nil {
tags = make([]*IfdTagEntry, 0)
}
// Now, print the tags while also descending to child-IFDS as we encounter them.
ifdsFoundCount := 0
for _, tag := range ifd.Entries {
tags = append(tags, tag)
if tag.ChildIfdPath != "" {
ifdsFoundCount++
childIfd, found := ifd.ChildIfdIndex[tag.ChildIfdPath]
if found != true {
log.Panicf("alien child IFD referenced by a tag: [%s]", tag.ChildIfdPath)
}
tags = childIfd.dumpTags(tags)
}
}
if len(ifd.Children) != ifdsFoundCount {
log.Panicf("have one or more dangling child IFDs: (%d) != (%d)", len(ifd.Children), ifdsFoundCount)
}
if ifd.NextIfd != nil {
tags = ifd.NextIfd.dumpTags(tags)
}
return tags
}
// DumpTags prints the IFD hierarchy.
func (ifd *Ifd) DumpTags() []*IfdTagEntry {
return ifd.dumpTags(nil)
}
func (ifd *Ifd) printTagTree(populateValues bool, index, level int, nextLink bool) {
indent := strings.Repeat(" ", level*2)
prefix := " "
if nextLink {
prefix = ">"
}
fmt.Printf("%s%sIFD: %s\n", indent, prefix, ifd)
// Now, print the tags while also descending to child-IFDS as we encounter them.
ifdsFoundCount := 0
for _, tag := range ifd.Entries {
if tag.ChildIfdPath != "" {
fmt.Printf("%s - TAG: %s\n", indent, tag)
} else {
it, err := ifd.tagIndex.Get(ifd.IfdPath, tag.TagId)
tagName := ""
if err == nil {
tagName = it.Name
}
var value interface{}
if populateValues == true {
var err error
value, err = ifd.TagValue(tag)
if err != nil {
if err == ErrUnhandledUnknownTypedTag {
value = UnparseableUnknownTagValuePlaceholder
} else {
log.Panic(err)
}
}
}
fmt.Printf("%s - TAG: %s NAME=[%s] VALUE=[%v]\n", indent, tag, tagName, value)
}
if tag.ChildIfdPath != "" {
ifdsFoundCount++
childIfd, found := ifd.ChildIfdIndex[tag.ChildIfdPath]
if found != true {
log.Panicf("alien child IFD referenced by a tag: [%s]", tag.ChildIfdPath)
}
childIfd.printTagTree(populateValues, 0, level+1, false)
}
}
if len(ifd.Children) != ifdsFoundCount {
log.Panicf("have one or more dangling child IFDs: (%d) != (%d)", len(ifd.Children), ifdsFoundCount)
}
if ifd.NextIfd != nil {
ifd.NextIfd.printTagTree(populateValues, index+1, level, true)
}
}
// PrintTagTree prints the IFD hierarchy.
func (ifd *Ifd) PrintTagTree(populateValues bool) {
ifd.printTagTree(populateValues, 0, 0, false)
}
func (ifd *Ifd) printIfdTree(level int, nextLink bool) {
indent := strings.Repeat(" ", level*2)
prefix := " "
if nextLink {
prefix = ">"
}
fmt.Printf("%s%s%s\n", indent, prefix, ifd)
// Now, print the tags while also descending to child-IFDS as we encounter them.
ifdsFoundCount := 0
for _, tag := range ifd.Entries {
if tag.ChildIfdPath != "" {
ifdsFoundCount++
childIfd, found := ifd.ChildIfdIndex[tag.ChildIfdPath]
if found != true {
log.Panicf("alien child IFD referenced by a tag: [%s]", tag.ChildIfdPath)
}
childIfd.printIfdTree(level+1, false)
}
}
if len(ifd.Children) != ifdsFoundCount {
log.Panicf("have one or more dangling child IFDs: (%d) != (%d)", len(ifd.Children), ifdsFoundCount)
}
if ifd.NextIfd != nil {
ifd.NextIfd.printIfdTree(level, true)
}
}
// PrintIfdTree prints the IFD hierarchy.
func (ifd *Ifd) PrintIfdTree() {
ifd.printIfdTree(0, false)
}
func (ifd *Ifd) dumpTree(tagsDump []string, level int) []string {
if tagsDump == nil {
tagsDump = make([]string, 0)
}
indent := strings.Repeat(" ", level*2)
var ifdPhrase string
if ifd.ParentIfd != nil {
ifdPhrase = fmt.Sprintf("[%s]->[%s]:(%d)", ifd.ParentIfd.IfdPath, ifd.IfdPath, ifd.Index)
} else {
ifdPhrase = fmt.Sprintf("[ROOT]->[%s]:(%d)", ifd.IfdPath, ifd.Index)
}
startBlurb := fmt.Sprintf("%s> IFD %s TOP", indent, ifdPhrase)
tagsDump = append(tagsDump, startBlurb)
ifdsFoundCount := 0
for _, tag := range ifd.Entries {
tagsDump = append(tagsDump, fmt.Sprintf("%s - (0x%04x)", indent, tag.TagId))
if tag.ChildIfdPath != "" {
ifdsFoundCount++
childIfd, found := ifd.ChildIfdIndex[tag.ChildIfdPath]
if found != true {
log.Panicf("alien child IFD referenced by a tag: [%s]", tag.ChildIfdPath)
}
tagsDump = childIfd.dumpTree(tagsDump, level+1)
}
}
if len(ifd.Children) != ifdsFoundCount {
log.Panicf("have one or more dangling child IFDs: (%d) != (%d)", len(ifd.Children), ifdsFoundCount)
}
finishBlurb := fmt.Sprintf("%s< IFD %s BOTTOM", indent, ifdPhrase)
tagsDump = append(tagsDump, finishBlurb)
if ifd.NextIfd != nil {
siblingBlurb := fmt.Sprintf("%s* LINKING TO SIBLING IFD [%s]:(%d)", indent, ifd.NextIfd.IfdPath, ifd.NextIfd.Index)
tagsDump = append(tagsDump, siblingBlurb)
tagsDump = ifd.NextIfd.dumpTree(tagsDump, level)
}
return tagsDump
}
// DumpTree returns a list of strings describing the IFD hierarchy.
func (ifd *Ifd) DumpTree() []string {
return ifd.dumpTree(nil, 0)
}
// GpsInfo parses and consolidates the GPS info. This can only be called on the
// GPS IFD.
func (ifd *Ifd) GpsInfo() (gi *GpsInfo, err error) {
defer func() {
if state := recover(); state != nil {
err = log.Wrap(state.(error))
}
}()
// TODO(dustin): !! Also add functionality to update the GPS info.
gi = new(GpsInfo)
if ifd.IfdPath != IfdPathStandardGps {
log.Panicf("GPS can only be read on GPS IFD: [%s] != [%s]", ifd.IfdPath, IfdPathStandardGps)
}
if tags, found := ifd.EntriesByTagId[TagVersionId]; found == false {
// We've seen this. We'll just have to default to assuming we're in a
// 2.2.0.0 format.
ifdEnumerateLogger.Warningf(nil, "No GPS version tag (0x%04x) found.", TagVersionId)
} else {
hit := false
for _, acceptedGpsVersion := range ValidGpsVersions {
if bytes.Compare(tags[0].value, acceptedGpsVersion[:]) == 0 {
hit = true
break
}
}
if hit != true {
ifdEnumerateLogger.Warningf(nil, "GPS version not supported: %v", tags[0].value)
log.Panic(ErrNoGpsTags)
}
}
tags, found := ifd.EntriesByTagId[TagLatitudeId]
if found == false {
ifdEnumerateLogger.Warningf(nil, "latitude not found")
log.Panic(ErrNoGpsTags)
}
latitudeValue, err := ifd.TagValue(tags[0])
log.PanicIf(err)
// Look for whether North or South.
tags, found = ifd.EntriesByTagId[TagLatitudeRefId]
if found == false {
ifdEnumerateLogger.Warningf(nil, "latitude-ref not found")
log.Panic(ErrNoGpsTags)
}
latitudeRefValue, err := ifd.TagValue(tags[0])
log.PanicIf(err)
tags, found = ifd.EntriesByTagId[TagLongitudeId]
if found == false {
ifdEnumerateLogger.Warningf(nil, "longitude not found")
log.Panic(ErrNoGpsTags)
}
longitudeValue, err := ifd.TagValue(tags[0])
log.PanicIf(err)
// Look for whether West or East.
tags, found = ifd.EntriesByTagId[TagLongitudeRefId]
if found == false {
ifdEnumerateLogger.Warningf(nil, "longitude-ref not found")
log.Panic(ErrNoGpsTags)
}
longitudeRefValue, err := ifd.TagValue(tags[0])
log.PanicIf(err)
// Parse location.
latitudeRaw := latitudeValue.([]Rational)
gi.Latitude = GpsDegrees{
Orientation: latitudeRefValue.(string)[0],
Degrees: float64(latitudeRaw[0].Numerator) / float64(latitudeRaw[0].Denominator),
Minutes: float64(latitudeRaw[1].Numerator) / float64(latitudeRaw[1].Denominator),
Seconds: float64(latitudeRaw[2].Numerator) / float64(latitudeRaw[2].Denominator),
}
longitudeRaw := longitudeValue.([]Rational)
gi.Longitude = GpsDegrees{
Orientation: longitudeRefValue.(string)[0],
Degrees: float64(longitudeRaw[0].Numerator) / float64(longitudeRaw[0].Denominator),
Minutes: float64(longitudeRaw[1].Numerator) / float64(longitudeRaw[1].Denominator),
Seconds: float64(longitudeRaw[2].Numerator) / float64(longitudeRaw[2].Denominator),
}
// Parse altitude.
altitudeTags, foundAltitude := ifd.EntriesByTagId[TagAltitudeId]
altitudeRefTags, foundAltitudeRef := ifd.EntriesByTagId[TagAltitudeRefId]
if foundAltitude == true && foundAltitudeRef == true {
altitudeValue, err := ifd.TagValue(altitudeTags[0])
log.PanicIf(err)
altitudeRefValue, err := ifd.TagValue(altitudeRefTags[0])
log.PanicIf(err)
altitudeRaw := altitudeValue.([]Rational)
altitude := int(altitudeRaw[0].Numerator / altitudeRaw[0].Denominator)
if altitudeRefValue.([]byte)[0] == 1 {
altitude *= -1
}
gi.Altitude = altitude
}
// Parse time.
timestampTags, foundTimestamp := ifd.EntriesByTagId[TagTimestampId]
datestampTags, foundDatestamp := ifd.EntriesByTagId[TagDatestampId]
if foundTimestamp == true && foundDatestamp == true {
datestampValue, err := ifd.TagValue(datestampTags[0])
log.PanicIf(err)
dateParts := strings.Split(datestampValue.(string), ":")
year, err1 := strconv.ParseUint(dateParts[0], 10, 16)
month, err2 := strconv.ParseUint(dateParts[1], 10, 8)
day, err3 := strconv.ParseUint(dateParts[2], 10, 8)
if err1 == nil && err2 == nil && err3 == nil {
timestampValue, err := ifd.TagValue(timestampTags[0])
log.PanicIf(err)
timestampRaw := timestampValue.([]Rational)
hour := int(timestampRaw[0].Numerator / timestampRaw[0].Denominator)
minute := int(timestampRaw[1].Numerator / timestampRaw[1].Denominator)
second := int(timestampRaw[2].Numerator / timestampRaw[2].Denominator)
gi.Timestamp = time.Date(int(year), time.Month(month), int(day), hour, minute, second, 0, time.UTC)
}
}
return gi, nil
}
type ParsedTagVisitor func(*Ifd, *IfdTagEntry) error