forked from GPSBabel/gpsbabel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exif.cc
1598 lines (1401 loc) · 47.8 KB
/
exif.cc
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
/*
Support for embedded (JPEG) Exif-GPS information.
Copyright (C) 2008 Olaf Klein, [email protected]
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* Exif specifications can be found at
* 2016, version 2.31: http://www.cipa.jp/std/documents/e/DC-008-Translation-2016-E.pdf
* 2012, version 2.3: http://www.cipa.jp/std/documents/e/DC-008-2012_E.pdf
* 2010, version 2.3: http://www.cipa.jp/std/documents/e/DC-008-2010_E.pdf
* 2002, version 2.2: http://www.exif.org/Exif2-2.PDF
* 1998, version 2.1: http://www.exif.org/Exif2-1.PDF
*
* TIFF specifications can be found at
* version 6.0: https://www.itu.int/itudoc/itu-t/com16/tiff-fx/docs/tiff6.pdf
* version 6.0: http://www.npes.org/pdf/TIFF-v6.pdf
* version 6.0: http://www.alternatiff.com/resources/TIFF6.pdf
*/
#include "exif.h"
#include <QByteArray> // for QByteArray
#include <QDate> // for QDate
#include <QDateTime> // for QDateTime
#include <QFile> // for QFile
#include <QFileInfo> // for QFileInfo
#include <QList> // for QList
#include <QPair> // for QPair
#include <QRegularExpression> // for QRegularExpressionMatch, QRegularExpression
#include <QString> // for QString
#include <QTextCodec> // for QTextCodec
#include <QTime> // for QTime
#include <QVariant> // for QVariant
#include <QVector> // for QVector
#include <Qt> // for UTC, ISODate
#include <QtGlobal> // for qAsConst, qPrintable, qint64
#include <algorithm> // for sort, min
#include <cassert> // for assert
#include <cctype> // for isprint, isspace
#include <cfloat> // for DBL_EPSILON
#include <cmath> // for fabs, modf, copysign, round, fmax
#include <cstdint> // for uint32_t, int32_t, uint16_t, int16_t, uint8_t, INT32_MAX
#include <cstdio> // for printf, SEEK_SET, snprintf, SEEK_CUR
#include <cstdlib> // for labs
#include <cstring> // for memcmp, strlen
#include <type_traits> // for add_const<>::type
#include "defs.h" // for Waypoint, fatal, warning, global_options, global_opts, unknown_alt, xfree, route_disp_all, track_disp_all, waypt_disp_all, wp_flags, KNOTS_TO_MPS, KPH_TO_MPS, MPH_TO_MPS, MPS_TO_KPH, WAYPT_HAS, case_ignore_strcmp, rtrim, waypt_add, xstrdup, xstrndup, fix_2d
#include "garmin_tables.h" // for gt_lookup_datum_index
#include "gbfile.h" // for gbfputuint32, gbfputuint16, gbfgetuint16, gbfgetuint32, gbfseek, gbftell, gbfile, gbfclose, gbfcopyfrom, gbfwrite, gbfopen_be, gbfread, gbfrewind, gbfgetflt, gbfgetint16, gbfopen, gbfputc, gbfputflt, gbsize_t, gbfeof, gbfgetdbl, gbfputdbl, gbfile::(anonymous)
#include "jeeps/gpsmath.h" // for GPS_Math_WGS84_To_Known_Datum_M
#include "src/core/datetime.h" // for DateTime
#define MYNAME "exif"
#define IFD0 0
#define IFD1 1
#define EXIF_IFD 2 /* dummy index */
#define GPS_IFD 3 /* dummy index */
#define INTER_IFD 4 /* dummy index */
#define EXIF_TYPE_BYTE 1
#define EXIF_TYPE_ASCII 2
#define EXIF_TYPE_SHORT 3
#define EXIF_TYPE_LONG 4
#define EXIF_TYPE_RAT 5
#define EXIF_TYPE_SBYTE 6 /* TIFF 6.0 */
#define EXIF_TYPE_UNK 7 /* TIFF 6.0 */
#define EXIF_TYPE_SSHORT 8 /* TIFF 6.0 */
#define EXIF_TYPE_SLONG 9 /* TIFF 6.0 */
#define EXIF_TYPE_SRAT 10 /* TIFF 6.0 */
#define EXIF_TYPE_FLOAT 11 /* TIFF 6.0 */
#define EXIF_TYPE_DOUBLE 12 /* TIFF 6.0 */
#define EXIF_TYPE_IFD 13
#define EXIF_TYPE_UNICODE 14
#define EXIF_TYPE_COMPLEX 15
#define EXIF_TYPE_LONG8 16 /* BigTIFF */
#define EXIF_TYPE_SLONG8 17 /* BigTIFF */
#define EXIF_TYPE_IFD8 18 /* BigTIFF */
#define BYTE_TYPE(a) ( (a==EXIF_TYPE_BYTE) || (a==EXIF_TYPE_ASCII) || (a==EXIF_TYPE_SBYTE) || (a==EXIF_TYPE_UNK) )
#define WORD_TYPE(a) ( (a==EXIF_TYPE_SHORT) || (a==EXIF_TYPE_SSHORT) )
#define LONG_TYPE(a) ( (a==EXIF_TYPE_LONG) || (a==EXIF_TYPE_SLONG) || (a==EXIF_TYPE_IFD) )
#define IFD0_TAG_EXIF_IFD_OFFS 0x8769
#define IFD0_TAG_GPS_IFD_OFFS 0x8825
#define IFD1_TAG_COMPRESSION 0x0103 // Compression, 1 => uncompressed, 6 => JPEG compression
#define IFD1_TAG_STRIP_OFFS 0x0111 // StripOffsets
#define IFD1_TAG_STRIP_BYTE_COUNTS 0x0117 // StripByteCounts
#define IFD1_TAG_JPEG_OFFS 0x0201 // JPEGInterchangeFormat
#define IFD1_TAG_JPEG_SIZE 0x0202 // JPEGInterchangeFormatLength
#define EXIF_IFD_TAG_USER_CMT 0x9286
#define EXIF_IFD_TAG_INTER_IFD_OFFS 0xA005
#define GPS_IFD_TAG_VERSION 0x0000
#define GPS_IFD_TAG_LATREF 0x0001
#define GPS_IFD_TAG_LAT 0x0002
#define GPS_IFD_TAG_LONREF 0x0003
#define GPS_IFD_TAG_LON 0x0004
#define GPS_IFD_TAG_ALTREF 0x0005
#define GPS_IFD_TAG_ALT 0x0006
#define GPS_IFD_TAG_TIMESTAMP 0x0007
#define GPS_IFD_TAG_SAT 0x0008
#define GPS_IFD_TAG_MODE 0x000A
#define GPS_IFD_TAG_DOP 0x000B
#define GPS_IFD_TAG_SPEEDREF 0x000C
#define GPS_IFD_TAG_SPEED 0x000D
#define GPS_IFD_TAG_DATUM 0x0012
#define GPS_IFD_TAG_DATESTAMP 0x001D
// for debug only
void
ExifFormat::print_buff(const char* buf, int sz, const char* cmt)
{
int i;
printf("%s: ", cmt);
for (i = 0; i < sz; i++) {
printf("%02x ", buf[i] & 0xFF);
}
for (i = 0; i < sz; i++) {
char c = buf[i];
if (isspace(c)) {
c = ' ';
} else if (! isprint(c)) {
c = '.';
}
printf("%c", c);
}
}
uint16_t
ExifFormat::exif_type_size(const uint16_t type)
{
uint16_t size;
switch (type) {
case EXIF_TYPE_BYTE:
case EXIF_TYPE_ASCII:
case EXIF_TYPE_SBYTE:
case EXIF_TYPE_UNK:
size = 1;
break;
case EXIF_TYPE_SHORT:
case EXIF_TYPE_SSHORT:
case EXIF_TYPE_UNICODE:
size = 2;
break;
case EXIF_TYPE_IFD:
case EXIF_TYPE_LONG:
case EXIF_TYPE_SLONG:
case EXIF_TYPE_FLOAT:
size = 4;
break;
case EXIF_TYPE_RAT:
case EXIF_TYPE_SRAT:
case EXIF_TYPE_DOUBLE:
case EXIF_TYPE_COMPLEX:
case EXIF_TYPE_LONG8:
case EXIF_TYPE_SLONG8:
case EXIF_TYPE_IFD8:
size = 8;
break;
default:
fatal(MYNAME ": Unknown data type %d! Please report.\n", type);
}
return size;
}
QString
ExifFormat::exif_time_str(const QDateTime& time)
{
QString str = time.toString(u"yyyy/MM/dd hh:mm:ss t");
if (time.timeSpec() != Qt::UTC) {
str.append(" (");
str.append(time.toUTC().toString(u"yyyy/MM/dd hh:mm:ss t"));
str.append(")");
}
return str;
}
char*
ExifFormat::exif_read_str(ExifTag* tag)
{
// Panasonic DMC-TZ10 stores datum with trailing spaces.
// Kodak stores zero count ASCII tags.
char* buf = (tag->count == 0) ? xstrdup("") : xstrndup(tag->data.at(0).toByteArray().constData(), tag->size);
rtrim(buf);
return buf;
}
double
ExifFormat::exif_read_double(const ExifTag* tag, const int index)
{
if (tag->type == EXIF_TYPE_RAT) {
auto num = tag->data.at(index * 2).value<uint32_t>();
auto den = tag->data.at((index * 2) + 1).value<uint32_t>();
return (double)num / (double)den;
} else { // EXIF_TYPE_SRAT
auto num = tag->data.at(index * 2).value<int32_t>();
auto den = tag->data.at((index * 2) + 1).value<int32_t>();
return (double)num / (double)den;
}
}
double
ExifFormat::exif_read_coord(const ExifTag* tag)
{
double res = exif_read_double(tag, 0);
if (tag->count == 1) {
return res;
}
double min = exif_read_double(tag, 1);
res += (min / 60);
if (tag->count == 2) {
return res;
}
double sec = exif_read_double(tag, 2);
res += (sec / 3600);
return res;
}
QTime
ExifFormat::exif_read_timestamp(const ExifTag* tag)
{
double hour = exif_read_double(tag, 0);
double min = exif_read_double(tag, 1);
double sec = exif_read_double(tag, 2);
return QTime(int(hour), int(min), int(sec));
}
QDate
ExifFormat::exif_read_datestamp(const ExifTag* tag)
{
return QDate::fromString(tag->data.at(0).toByteArray().constData(), "yyyy:MM:dd");
}
void
ExifFormat::exif_release_apps()
{
for (auto* app : qAsConst(*exif_apps)) {
if (app->fcache) {
gbfclose(app->fcache);
}
if (app->fexif) {
gbfclose(app->fexif);
}
delete app;
}
delete exif_apps;
exif_apps = nullptr;
}
uint32_t
ExifFormat::exif_ifd_size(ExifIfd* ifd)
{
uint32_t res = 6; /* nr of tags + next_ifd */
res += (ifd->count * 12);
for (auto& tag_instance : ifd->tags) {
ExifTag* tag = &tag_instance;
if (tag->size > 4) {
uint32_t size = tag->size;
if (size & 1u) {
size++;
}
res += size;
}
}
return res;
}
ExifFormat::ExifApp*
ExifFormat::exif_load_apps()
{
exif_app_ = nullptr;
while (! gbfeof(fin_)) {
exif_apps->append(new ExifApp);
ExifApp* app = exif_apps->last();
app->fcache = gbfopen(nullptr, "wb", MYNAME);
app->marker = gbfgetuint16(fin_);
app->len = gbfgetuint16(fin_);
if (global_opts.debug_level >= 3) {
printf(MYNAME ": api = %02X, len = %u (0x%04x), offs = 0x%08X\n", app->marker & 0xFF, app->len, app->len, gbftell(fin_));
}
if (exif_app_ || (app->marker == 0xFFDA)) { /* compressed data */
gbfcopyfrom(app->fcache, fin_, 0x7FFFFFFF);
if (global_opts.debug_level >= 3) {
printf(MYNAME ": compressed data size = %u\n", gbftell(app->fcache));
}
} else {
gbfcopyfrom(app->fcache, fin_, app->len - 2);
if (app->marker == 0xFFE1) {
exif_app_ = app;
}
}
}
return exif_app_;
}
#ifndef NDEBUG
void
ExifFormat::exif_validate_tag_structure(const ExifTag* tag)
{
// The count times the element size should match the saved size.
assert((tag->count * exif_type_size(tag->type)) == tag->size);
// for BYTE_TYPE we store a QByteArray as the only component of the QVector,
// and the count should match the size of the byte array.
assert((!BYTE_TYPE(tag->type)) ||
((tag->data.size() == 0) && (tag->count == 0)) ||
((tag->data.size() == 1) && (static_cast<unsigned>(tag->data.at(0).toByteArray().size()) == tag->count)));
// EXIF_TYPE_RAT and EXIF_TYPE_SRAT are stored as two values per item.
assert(((tag->type != EXIF_TYPE_RAT) && (tag->type != EXIF_TYPE_SRAT)) ||
(static_cast<unsigned>(tag->data.size()) == (2 * tag->count)));
// types other that BYTE_TYPE, RAT, SRAT are stored as one value per item.
assert(BYTE_TYPE(tag->type) || (tag->type == EXIF_TYPE_RAT) || (tag->type == EXIF_TYPE_SRAT) ||
(static_cast<unsigned>(tag->data.size()) == tag->count));
// For EXIF_TYPE_ASCII the last byte of the value must be NUL (binary 0).
assert((tag->type != EXIF_TYPE_ASCII) ||
((tag->data.size() == 0) && (tag->count == 0)) ||
((tag->data.size() == 1) && (tag->data.at(0).toByteArray().endsWith('\0'))));
}
#endif
ExifFormat::ExifIfd*
ExifFormat::exif_read_ifd(ExifApp* app, const uint16_t ifd_nr, const gbsize_t offs,
uint32_t* exif_ifd_ofs, uint32_t* gps_ifd_ofs, uint32_t* inter_ifd_ofs)
{
gbfile* fin = app->fexif;
app->ifds.append(ExifIfd());
ExifIfd* ifd = &app->ifds.last();
ifd->nr = ifd_nr;
gbfseek(fin, offs, SEEK_SET);
ifd->count = gbfgetuint16(fin);
if (global_opts.debug_level >= 3) {
const char* name;
switch (ifd_nr) {
case IFD0:
name = "IFD0";
break;
case IFD1:
name = "IFD1";
break;
case GPS_IFD:
name = "GPS";
break;
case EXIF_IFD:
name = "EXIF";
break;
case INTER_IFD:
name = "INTER";
break;
default:
name = "private";
break;
}
printf(MYNAME "-offs 0x%08X: Number of items in IFD%d \"%s\" = %d (0x%04x)\n",
offs, ifd_nr, name, ifd->count, ifd->count);
}
if (ifd->count == 0) {
return ifd;
}
for (uint16_t i = 0; i < ifd->count; i++) {
ifd->tags.append(ExifTag());
ExifTag* tag = &ifd->tags.last();
if (global_opts.debug_level >= 3) {
tag->tag_offset = gbftell(fin);
}
tag->id = gbfgetuint16(fin);
tag->type = gbfgetuint16(fin);
tag->count = gbfgetuint32(fin);
tag->size = exif_type_size(tag->type) * tag->count;
if (tag->size <= 4) { // data is in value offset field
if (BYTE_TYPE(tag->type)) {
assert(tag->count <= 4);
if (tag->count > 0) {
QByteArray qba(tag->count, 0);
gbfread(qba.data(), tag->count, 1, fin);
tag->data.append(qba);
}
} else if (WORD_TYPE(tag->type)) {
assert(tag->count <= 2);
for (unsigned idx=0; idx < tag->count; ++idx) {
tag->data.append(gbfgetuint16(fin));
}
} else if (LONG_TYPE(tag->type)) {
assert(tag->count <= 1);
if (tag->count == 1) {
tag->data.append(gbfgetuint32(fin));
}
} else if (tag->type == EXIF_TYPE_FLOAT) {
assert(tag->count <= 1);
if (tag->count == 1) {
tag->data.append(gbfgetflt(fin));
}
} else {
fatal(MYNAME "Unknown type %d has size <= 4! Please report.\n", tag->type);
}
int skip_bytes = 4 - tag->size;
if (skip_bytes > 0) {
gbfseek(fin, skip_bytes, SEEK_CUR);
}
if (global_opts.debug_level >= 3) {
gbfseek(fin, -4, SEEK_CUR);
gbfread(tag->raw, 4, 1, fin);
}
} else { // offset is in value offset field
tag->offset = gbfgetuint32(fin);
}
if (ifd_nr == IFD0) {
if (tag->id == IFD0_TAG_EXIF_IFD_OFFS) {
*exif_ifd_ofs = tag->toLong();
} else if (tag->id == IFD0_TAG_GPS_IFD_OFFS) {
*gps_ifd_ofs = tag->toLong();
}
} else if (ifd_nr == EXIF_IFD) {
if (tag->id == EXIF_IFD_TAG_INTER_IFD_OFFS) {
*inter_ifd_ofs = tag->toLong();
}
}
}
gbsize_t next_ifd_offs;
if (global_opts.debug_level >= 3) {
next_ifd_offs = gbftell(fin);
}
ifd->next_ifd = gbfgetuint32(fin);
for (auto& tag_instance : ifd->tags) {
ExifTag* tag = &tag_instance;
if ((tag->size > 4) && (tag->offset)) {
gbfseek(fin, tag->offset, SEEK_SET);
if (BYTE_TYPE(tag->type)) {
QByteArray qba(tag->count, 0);
gbfread(qba.data(), tag->count, 1, fin);
tag->data.append(qba);
} else for (unsigned i = 0; i < tag->count; i++) {
switch (tag->type) {
case EXIF_TYPE_SHORT:
case EXIF_TYPE_SSHORT:
tag->data.append(gbfgetuint16(fin));
break;
case EXIF_TYPE_IFD:
case EXIF_TYPE_LONG:
case EXIF_TYPE_SLONG:
tag->data.append(gbfgetuint32(fin));
break;
case EXIF_TYPE_RAT:
case EXIF_TYPE_SRAT:
tag->data.append(gbfgetuint32(fin));
tag->data.append(gbfgetuint32(fin));
break;
case EXIF_TYPE_FLOAT:
tag->data.append(gbfgetflt(fin));
break;
case EXIF_TYPE_DOUBLE:
tag->data.append(gbfgetdbl(fin));
break;
default: {
// We know the size for this tag type, but not the layout.
// Save it is a byte array we can echo on write.
QByteArray qba(tag->count, 0);
gbfread(qba.data(), exif_type_size(tag->type), 1, fin);
tag->data.append(qba);
}
break;
}
}
}
if (global_opts.debug_level >= 3) {
printf(MYNAME "-offs 0x%08X: ifd=%d id=0x%04X t=0x%04X c=%4u s=%4u",
tag->tag_offset, ifd->nr, tag->id, tag->type, tag->count, tag->size);
if (tag->size > 4) {
printf(" o=0x%08X", tag->offset);
} else {
printf(" v=0x%02X%02X%02X%02X", tag->raw[0], tag->raw[1], tag->raw[2], tag->raw[3]);
}
if (tag->type == EXIF_TYPE_ASCII) {
char* str = exif_read_str(tag);
printf(" \"%s\"", str);
xfree(str);
} else {
for (unsigned idx = 0; idx < std::min(tag->count, 4u); ++idx) {
if (tag->type == EXIF_TYPE_BYTE) {
printf(" %u", tag->data.at(0).toByteArray().at(idx));
} else if (tag->type == EXIF_TYPE_SBYTE) {
printf(" %d", tag->data.at(0).toByteArray().at(idx));
} else if (tag->type == EXIF_TYPE_UNK) {
printf(" 0x%02X", tag->data.at(0).toByteArray().at(idx));
} else if (tag->type == EXIF_TYPE_RAT) {
printf(" %+#g(%u/%u)", exif_read_double(tag, idx), tag->data.at(idx * 2).value<uint32_t>(), tag->data.at((idx * 2) + 1).value<uint32_t>());
} else if (tag->type == EXIF_TYPE_SRAT) {
printf(" %+#g(%d/%d)", exif_read_double(tag, idx), tag->data.at(idx * 2).value<int32_t>(), tag->data.at((idx * 2) + 1).value<int32_t>());
} else if (tag->type == EXIF_TYPE_SHORT) {
printf(" %u", tag->data.at(idx).value<uint16_t>());
} else if (tag->type == EXIF_TYPE_SSHORT) {
printf(" %d", tag->data.at(idx).value<int16_t>());
} else if (tag->type == EXIF_TYPE_LONG) {
printf(" %u", tag->data.at(idx).value<uint32_t>());
} else if (tag->type == EXIF_TYPE_SLONG) {
printf(" %d", tag->data.at(idx).value<int32_t>());
} else if (tag->type == EXIF_TYPE_FLOAT) {
printf(" %+#g", tag->data.at(idx).value<float>());
} else if (tag->type == EXIF_TYPE_DOUBLE) {
printf(" %+#g", tag->data.at(idx).value<double>());
} else {
printf(" 0x%0*X", 2 * exif_type_size(tag->type), tag->data.at(idx).value<uint32_t>());
}
}
if (tag->count > 4) {
printf(" ...");
}
}
printf("\n");
}
#ifndef NDEBUG
exif_validate_tag_structure(tag);
#endif
}
if (global_opts.debug_level >= 3) {
printf(MYNAME "-offs 0x%08X: Next IFD=0x%08X\n", next_ifd_offs, ifd->next_ifd);
}
return ifd;
}
void
ExifFormat::exif_read_app(ExifApp* app)
{
gbsize_t offs;
uint32_t exif_ifd_ofs, gps_ifd_ofs, inter_ifd_ofs;
ExifIfd* ifd;
gbfile* fin = app->fexif;
if (global_opts.debug_level >= 3) {
printf(MYNAME ": read_app...\n");
print_buff((const char*)fin->handle.mem, 8, MYNAME "-offs 0x00000000: Image File Header");
printf("\n");
}
exif_ifd_ofs = gps_ifd_ofs = inter_ifd_ofs = 0;
gbfseek(fin, 4, SEEK_SET);
offs = gbfgetuint32(fin); // Image File Header Bytes 4-7, the offset (in bytes) of the first IFD.
ifd = exif_read_ifd(app, IFD0, offs, &exif_ifd_ofs, &gps_ifd_ofs, &inter_ifd_ofs);
if (ifd == nullptr) {
return;
}
if (ifd->next_ifd) {
ifd = exif_read_ifd(app, IFD1, ifd->next_ifd, &exif_ifd_ofs, &gps_ifd_ofs, &inter_ifd_ofs);
}
if (exif_ifd_ofs) {
ifd = exif_read_ifd(app, EXIF_IFD, exif_ifd_ofs, nullptr, nullptr, &inter_ifd_ofs);
}
if (gps_ifd_ofs) {
ifd = exif_read_ifd(app, 3, gps_ifd_ofs, nullptr, nullptr, nullptr);
}
if (inter_ifd_ofs) {
ifd = exif_read_ifd(app, 4, inter_ifd_ofs, nullptr, nullptr, nullptr);
}
// The return values of exif_read_ifd above aren't actually used.
// Warning hush.
(void) ifd;
}
void
ExifFormat::exif_examine_app(ExifApp* app)
{
gbfile* ftmp = app->fcache;
gbfrewind(ftmp);
uint32_t ident = gbfgetuint32(ftmp);
if (ident != 0x66697845) {
fatal(MYNAME ": Invalid EXIF header magic.");
}
if (gbfgetint16(ftmp) != 0) {
fatal(MYNAME ": Error in EXIF header.");
}
uint16_t endianness = gbfgetint16(ftmp);
if (global_opts.debug_level >= 3) {
printf(MYNAME ": endianness = 0x%04X\n", endianness);
}
if (endianness == 0x4949) {
ftmp->big_endian = 0;
} else if (endianness == 0x4D4D) {
ftmp->big_endian = 1;
} else {
fatal(MYNAME ": Invalid endianness identifier 0x%04X!\n", endianness);
}
gbfseek(ftmp, 6, SEEK_SET);
app->fexif = gbfopen(nullptr, "wb", MYNAME);
app->fexif->big_endian = ftmp->big_endian;
gbfcopyfrom(app->fexif, ftmp, 0x7FFFFFFF);
exif_read_app(app);
}
ExifFormat::ExifIfd*
ExifFormat::exif_find_ifd(ExifApp* app, const uint16_t ifd_nr)
{
for (auto& ifd_instance : app->ifds) {
ExifIfd* ifd = &ifd_instance;
if (ifd->nr == ifd_nr) {
return ifd;
}
}
return nullptr;
}
ExifFormat::ExifTag*
ExifFormat::exif_find_tag(ExifApp* app, const uint16_t ifd_nr, const uint16_t tag_id)
{
ExifIfd* ifd = exif_find_ifd(app, ifd_nr);
if (ifd != nullptr) {
for (auto& tag_instance : ifd->tags) {
ExifTag* tag = &tag_instance;
if (tag->id == tag_id) {
return tag;
}
}
}
return nullptr;
}
QDateTime
ExifFormat::exif_get_exif_time(ExifApp* app)
{
QDateTime res;
ExifTag* tag = exif_find_tag(app, EXIF_IFD, 0x9003); /* DateTimeOriginal from EXIF */
if (! tag) {
tag = exif_find_tag(app, IFD0, 0x0132); /* DateTime from IFD0 */
}
if (! tag) {
tag = exif_find_tag(app, EXIF_IFD, 0x9004); /* DateTimeDigitized from EXIF */
}
if (tag) {
char* str = exif_read_str(tag);
// This assumes the Qt::TimeSpec is Qt::LocalTime, i.e. the current system time zone.
// Note the assumption of local time can be problematic if the data
// is processed in a different time zone than was used in recording
// the time in the image.
res = QDateTime::fromString(str, "yyyy:MM:dd hh:mm:ss");
xfree(str);
// Exif 2.31 added offset tags to record the offset to UTC.
// If these are present use them, otherwise assume local time.
ExifTag* offset_tag = nullptr;
switch (tag->id) {
case 0x9003:
offset_tag = exif_find_tag(app, EXIF_IFD, 0x9011); /* OffsetTimeOriginal from EXIF */
break;
case 0x0132:
offset_tag = exif_find_tag(app, EXIF_IFD, 0x9010); /* OffsetTime from EXIF */
break;
case 0x9004:
offset_tag = exif_find_tag(app, EXIF_IFD, 0x9012); /* OffsetTimeDigitized from EXIF */
break;
}
if (offset_tag) {
char* time_tag = exif_read_str(offset_tag);
// string should be +HH:MM or -HH:MM
static const QRegularExpression re(R"(^([+-])(\d{2}):(\d{2})$)");
assert(re.isValid());
QRegularExpressionMatch match = re.match(time_tag);
if (match.hasMatch()) {
// Correct the date time by supplying the offset from UTC.
int offset_hours = match.captured(1).append(match.captured(2)).toInt();
int offset_mins = match.captured(1).append(match.captured(3)).toInt();
res.setOffsetFromUtc(((offset_hours * 60) + offset_mins) * 60);
}
}
}
return res;
}
Waypoint*
ExifFormat::exif_waypt_from_exif_app(ExifApp* app) const
{
ExifTag* tag;
char lat_ref = '\0';
char lon_ref = '\0';
char alt_ref = 0;
char speed_ref = 'K';
char* datum = nullptr;
char mode = '\0';
double gpsdop = unknown_alt;
double alt = unknown_alt;
QTime timestamp;
QDate datestamp;
QDateTime gps_datetime;
ExifIfd* ifd = exif_find_ifd(app, GPS_IFD);
if (ifd == nullptr) {
return nullptr;
}
auto* wpt = new Waypoint;
wpt->latitude = unknown_alt;
wpt->longitude = unknown_alt;
for (auto& tag_instance : ifd->tags) {
tag = &tag_instance;
switch (tag->id) {
case GPS_IFD_TAG_VERSION:
break;
case GPS_IFD_TAG_LATREF:
lat_ref = tag->data.at(0).toByteArray().at(0);
break;
case GPS_IFD_TAG_LAT:
wpt->latitude = exif_read_coord(tag);
break;
case GPS_IFD_TAG_LONREF:
lon_ref = tag->data.at(0).toByteArray().at(0);
break;
case GPS_IFD_TAG_LON:
wpt->longitude = exif_read_coord(tag);
break;
case GPS_IFD_TAG_ALTREF:
alt_ref = tag->data.at(0).toByteArray().at(0);
break;
case GPS_IFD_TAG_ALT:
alt = exif_read_double(tag, 0);
break;
case GPS_IFD_TAG_TIMESTAMP:
timestamp = exif_read_timestamp(tag);
break;
case GPS_IFD_TAG_SAT:
wpt->sat = tag->data.at(0).toByteArray().toInt();
break;
case GPS_IFD_TAG_MODE:
mode = tag->data.at(0).toByteArray().at(0);
break;
case GPS_IFD_TAG_DOP:
gpsdop = exif_read_double(tag, 0);
break;
case GPS_IFD_TAG_SPEEDREF:
speed_ref = tag->data.at(0).toByteArray().at(0);
break;
case GPS_IFD_TAG_SPEED:
WAYPT_SET(wpt, speed, exif_read_double(tag, 0));
break;
case GPS_IFD_TAG_DATUM:
datum = exif_read_str(tag);
break;
case GPS_IFD_TAG_DATESTAMP:
datestamp = exif_read_datestamp(tag);
break;
}
}
if ((wpt->latitude == unknown_alt) || (wpt->longitude == unknown_alt)) {
fatal(MYNAME ": Missing GPSLatitude and/or GPSLongitude!\n");
}
if (lat_ref == 'S') {
wpt->latitude *= -1;
} else if (lat_ref != 'N') {
warning(MYNAME ": GPSLatitudeRef not set! Using N(orth).\n");
}
if (lon_ref == 'W') {
wpt->longitude *= -1;
} else if (lon_ref != 'E') {
warning(MYNAME ": GPSLongitudeRef not set! Using E(ast).\n");
}
if (global_opts.debug_level >= 3) {
printf(MYNAME "-GPSLatitude = %12.7f\n", wpt->latitude);
printf(MYNAME "-GPSLongitude = %12.7f\n", wpt->longitude);
}
if (datum) {
int idatum = gt_lookup_datum_index(datum, MYNAME);
if (idatum < 0) {
fatal(MYNAME ": Unknown GPSMapDatum \"%s\"!\n", datum);
}
if (idatum != DATUM_WGS84) {
GPS_Math_WGS84_To_Known_Datum_M(wpt->latitude, wpt->longitude, 0.0,
&wpt->latitude, &wpt->longitude, &alt, idatum);
}
xfree(datum);
}
if (alt != unknown_alt) {
double sign;
switch (alt_ref) {
case 0:
sign = 1.0;
break;
case 1:
sign = -1.0;
break;
default:
warning(MYNAME ": Invalid GPSAltitudeRef (%d)! Using default value 0 (= Sea level).\n", alt_ref);
sign = 1.0;
}
wpt->altitude = sign * alt;
if (global_opts.debug_level >= 3) {
printf(MYNAME "-GPSAltitude = %12.7f m\n", wpt->altitude);
}
}
if WAYPT_HAS(wpt, speed) {
switch (speed_ref) {
case 'K':
wpt->speed = KPH_TO_MPS(wpt->speed);
break;
case 'M':
wpt->speed = MPH_TO_MPS(wpt->speed);
break;
case 'N':
wpt->speed = KNOTS_TO_MPS(wpt->speed);
break;
default:
wpt->speed = 0;
WAYPT_UNSET(wpt, speed);
warning(MYNAME ": Unknown GPSSpeedRef unit %c (0x%02x)!\n", speed_ref, speed_ref);
}
if (global_opts.debug_level >= 3) {
if WAYPT_HAS(wpt, speed) {
printf(MYNAME "-GPSSpeed = %12.2f m/s\n", wpt->speed);
}
}
}
if (mode == '2') {
wpt->fix = fix_2d;
if (gpsdop != unknown_alt) {
wpt->hdop = gpsdop;
}
} else if (mode == '3') {
wpt->fix = fix_3d;
if (gpsdop != unknown_alt) {
wpt->pdop = gpsdop;
}
}
gps_datetime = QDateTime(datestamp, timestamp, Qt::UTC);
if (gps_datetime.isValid()) {
if (global_opts.debug_level >= 3) {
printf(MYNAME "-GPSTimeStamp = %s\n", qPrintable(gps_datetime.toString(Qt::ISODate)));
}
wpt->SetCreationTime(gps_datetime);
} else {
wpt->SetCreationTime(exif_get_exif_time(app));
}
tag = exif_find_tag(app, EXIF_IFD, EXIF_IFD_TAG_USER_CMT); /* UserComment */
if (tag && (tag->size > 8)) {
// TODO: User comments with JIS and Undefined Code Designations are ignored.
if (memcmp(tag->data.at(0).toByteArray().constData(), "ASCII\0\0\0", 8) == 0) {
wpt->notes = QString::fromLatin1(tag->data.at(0).toByteArray().constData() + 8, tag->size - 8);
} else if (memcmp(tag->data.at(0).toByteArray().constData(), "UNICODE\0", 8) == 0) {
QTextCodec* utf16_codec;
if (app->fcache->big_endian) {
utf16_codec = QTextCodec::codecForName("UTF-16BE");
} else {
utf16_codec = QTextCodec::codecForName("UTF-16LE");
}
wpt->notes = utf16_codec->toUnicode(tag->data.at(0).toByteArray().constData() + 8, tag->size - 8);
}
}
if (opt_filename) {
QFileInfo fi(fin_->name);
// No directory, no extension.
wpt->shortname = fi.baseName();
}
return wpt;
}
// TODO: we could achieve an increased domain and accuracy for TIFF RATIONAL
// types if we handled them separately (int32_t -> uint32_t, INT32_MAX -> UINT32_MAX).
ExifFormat::Rational<int32_t> ExifFormat::exif_dec2frac(double val, double tolerance = DBL_EPSILON)
{
constexpr double upper_limit = INT32_MAX;
constexpr double lower_limit = 1.0/upper_limit;
const double pval = fabs(val);
const double tol = fmax(tolerance, DBL_EPSILON);
if (pval < lower_limit) {
return Rational<int32_t>(0, upper_limit);
} else if (pval > upper_limit) {
fatal(MYNAME ": Value (%f) to big for a rational representation!\n", val);
return Rational<int32_t>(copysign(upper_limit, val), 1);
}
double b;
double remainder = modf(pval, &b);
Rational<double> prev_prev(1.0, 0.0);
Rational<double> prev(b, 1.0);
Rational<double> curr = prev;
// phi = (1.0+sqrt(5.0))/2.0 is badly approximable and the slowest to converge.
// This is a good test case to see the maximum number of iterations required.
for (int idx = 0; idx < 64; ++idx) {
// Calculate the next simple continued fraction coefficient (b), and remainder (remainder).
if (remainder < lower_limit) {
break; // remainder is nearly zero, use current estimate.
}
remainder = modf(1.0/remainder, &b);
// Convert the truncated simple continued fraction, a.k.a. a convergent, to an ordinary fraction (curr.num/curr.den).
Rational<double> candidate((b * prev.num) + prev_prev.num, (b * prev.den) + prev_prev.den);
if (candidate.num > upper_limit) {
break; // numerator too big, use current estimate.
}
if (candidate.den > upper_limit) {
break; // denominator too big, use current estimate.
}
curr = candidate;
if (fabs(pval- (curr.num/curr.den)) < (pval * tol)) {
break; // close enough, use current estimate.
}
prev_prev = prev;
prev = curr;
}
return Rational<int32_t>(round(copysign(curr.num, val)), round(curr.den));
}
ExifFormat::ExifTag*
ExifFormat::exif_put_value(const int ifd_nr, const uint16_t tag_id, const uint16_t type, const int count, const int index, const void* data) const
{
ExifTag* tag = nullptr;
uint16_t size;
ExifIfd* ifd = exif_find_ifd(exif_app_, ifd_nr);
if (ifd == nullptr) {
exif_app_->ifds.append(ExifIfd());
ifd = &exif_app_->ifds.last();
ifd->nr = ifd_nr;
} else {
tag = exif_find_tag(exif_app_, ifd_nr, tag_id);
}
uint16_t item_size = exif_type_size(type);
if ((data == nullptr) || (count < 1) || (index < 0)) {
size = 0;
} else {
size = (index + count) * item_size;
}