/
exif.cc
4540 lines (4082 loc) · 159 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
/*
This file is part of darktable,
Copyright (C) 2009-2021 darktable developers.
darktable 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 3 of the License, or
(at your option) any later version.
darktable 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 darktable. If not, see <http://www.gnu.org/licenses/>.
*/
#define __STDC_FORMAT_MACROS
extern "C" {
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <errno.h>
#include <glib.h>
#include <sqlite3.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <zlib.h>
#include "control/control.h"
}
#include <cassert>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <exiv2/exiv2.hpp>
#if defined(_WIN32) && defined(EXV_UNICODE_PATH)
#define WIDEN(s) pugi::as_wide(s)
#else
#define WIDEN(s) (s)
#endif
#include <pugixml.hpp>
using namespace std;
extern "C" {
#include "common/colorlabels.h"
#include "common/darktable.h"
#include "common/debug.h"
#include "common/dng_opcode.h"
#include "common/image_cache.h"
#include "common/imageio.h"
#include "common/exif.h"
#include "common/imageio_jpeg.h"
#include "common/metadata.h"
#include "common/ratings.h"
#include "common/tags.h"
#include "common/iop_order.h"
#include "common/variables.h"
#include "common/utility.h"
#include "common/history.h"
#include "common/datetime.h"
#include "control/conf.h"
#include "develop/imageop.h"
#include "develop/blend.h"
#include "develop/masks.h"
}
#define DT_XMP_EXIF_VERSION 5
// persistent list of exiv2 tags. set up in dt_init()
static GList *exiv2_taglist = NULL;
static const char *_get_exiv2_type(const int type)
{
switch(type)
{
case 1:
return "Byte";
case 2:
return "Ascii";
case 3:
return "Short";
case 4:
return "Long";
case 5:
return "Rational"; // two LONGs: numerator and denumerator of a fraction
case 6:
return "SByte";
case 7:
return "Undefined";
case 8:
return "SShort";
case 9:
return "SLong";
case 10:
return "SRational"; // two SLONGs: numerator and denumerator of a fraction.
case 11:
return "Float"; // single precision (4-byte) IEEE format
case 12:
return "Double"; // double precision (8-byte) IEEE format.
case 13:
return "Ifd"; // 32-bit (4-byte) unsigned integer
case 16:
return "LLong"; // 64-bit (8-byte) unsigned integer
case 17:
return "LLong"; // 64-bit (8-byte) signed integer
case 18:
return "Ifd8"; // 64-bit (8-byte) unsigned integer
case 0x10000:
return "String";
case 0x10001:
return "Date";
case 0x10002:
return "Time";
case 0x10003:
return "Comment";
case 0x10004:
return "Directory";
case 0x10005:
return "XmpText";
case 0x10006:
return "XmpAlt";
case 0x10007:
return "XmpBag";
case 0x10008:
return "XmpSeq";
case 0x10009:
return "LangAlt";
case 0x1fffe:
return "Invalid";
case 0x1ffff:
return "LastType";
default:
return "Invalid";
}
}
static void _get_xmp_tags(const char *prefix, GList **taglist)
{
const Exiv2::XmpPropertyInfo *pl = Exiv2::XmpProperties::propertyList(prefix);
if(pl)
{
for(int i = 0; pl[i].name_ != 0; ++i)
{
char *tag = dt_util_dstrcat(NULL, "Xmp.%s.%s,%s", prefix, pl[i].name_, _get_exiv2_type(pl[i].typeId_));
*taglist = g_list_prepend(*taglist, tag);
}
}
}
static int _illu_to_temp(dt_dng_illuminant_t illu)
{
switch(illu)
{
case DT_LS_StandardLightA:
case DT_LS_Tungsten:
return 2850;
case DT_LS_ISOStudioTungsten:
return 3200;
case DT_LS_StandardLightB:
return 4871;
case DT_LS_StandardLightC:
return 6774;
case DT_LS_D50:
return 5000;
case DT_LS_D55:
case DT_LS_Daylight:
case DT_LS_FineWeather:
case DT_LS_Flash:
return 5500;
case DT_LS_D65:
case DT_LS_CloudyWeather:
return 6500;
case DT_LS_D75:
case DT_LS_Shade:
return 7500;
case DT_LS_DaylightFluorescent:
return 6430;
case DT_LS_DayWhiteFluorescent:
return 5000;
case DT_LS_CoolWhiteFluorescent:
return 4150;
case DT_LS_Fluorescent:
return 4230;
case DT_LS_WhiteFluorescent:
return 3450;
case DT_LS_WarmWhiteFluorescent:
return 2940;
default:
return 0;
}
}
void dt_exif_set_exiv2_taglist()
{
if(exiv2_taglist) return;
try
{
const Exiv2::GroupInfo *groupList = Exiv2::ExifTags::groupList();
if(groupList)
{
while(groupList->tagList_)
{
const std::string groupName(groupList->groupName_);
if(groupName.substr(0, 3) != "Sub" &&
groupName != "Image2" &&
groupName != "Image3" &&
groupName != "Thumbnail"
)
{
const Exiv2::TagInfo *tagInfo = groupList->tagList_();
while(tagInfo->tag_ != 0xFFFF)
{
char *tag = dt_util_dstrcat(NULL, "Exif.%s.%s,%s", groupList->groupName_, tagInfo->name_, _get_exiv2_type(tagInfo->typeId_));
exiv2_taglist = g_list_prepend(exiv2_taglist, tag);
tagInfo++;
}
}
groupList++;
}
}
const Exiv2::DataSet *iptcEnvelopeList = Exiv2::IptcDataSets::envelopeRecordList();
while(iptcEnvelopeList->number_ != 0xFFFF)
{
char *tag = dt_util_dstrcat(NULL, "Iptc.Envelope.%s,%s%s", iptcEnvelopeList->name_,
_get_exiv2_type(iptcEnvelopeList->type_),
iptcEnvelopeList->repeatable_ ? "-R" : "");
exiv2_taglist = g_list_prepend(exiv2_taglist, tag);
iptcEnvelopeList++;
}
const Exiv2::DataSet *iptcApplication2List = Exiv2::IptcDataSets::application2RecordList();
while(iptcApplication2List->number_ != 0xFFFF)
{
char *tag = dt_util_dstrcat(NULL, "Iptc.Application2.%s,%s%s", iptcApplication2List->name_,
_get_exiv2_type(iptcApplication2List->type_),
iptcApplication2List->repeatable_ ? "-R" : "");
exiv2_taglist = g_list_prepend(exiv2_taglist, tag);
iptcApplication2List++;
}
_get_xmp_tags("dc", &exiv2_taglist);
_get_xmp_tags("xmp", &exiv2_taglist);
_get_xmp_tags("xmpRights", &exiv2_taglist);
_get_xmp_tags("xmpMM", &exiv2_taglist);
_get_xmp_tags("xmpBJ", &exiv2_taglist);
_get_xmp_tags("xmpTPg", &exiv2_taglist);
_get_xmp_tags("xmpDM", &exiv2_taglist);
_get_xmp_tags("pdf", &exiv2_taglist);
_get_xmp_tags("photoshop", &exiv2_taglist);
_get_xmp_tags("crs", &exiv2_taglist);
_get_xmp_tags("tiff", &exiv2_taglist);
_get_xmp_tags("exif", &exiv2_taglist);
_get_xmp_tags("exifEX", &exiv2_taglist);
_get_xmp_tags("aux", &exiv2_taglist);
_get_xmp_tags("iptc", &exiv2_taglist);
_get_xmp_tags("iptcExt", &exiv2_taglist);
_get_xmp_tags("plus", &exiv2_taglist);
_get_xmp_tags("mwg-rs", &exiv2_taglist);
_get_xmp_tags("mwg-kw", &exiv2_taglist);
_get_xmp_tags("dwc", &exiv2_taglist);
_get_xmp_tags("dcterms", &exiv2_taglist);
_get_xmp_tags("digiKam", &exiv2_taglist);
_get_xmp_tags("kipi", &exiv2_taglist);
_get_xmp_tags("GPano", &exiv2_taglist);
_get_xmp_tags("lr", &exiv2_taglist);
_get_xmp_tags("MP", &exiv2_taglist);
_get_xmp_tags("MPRI", &exiv2_taglist);
_get_xmp_tags("MPReg", &exiv2_taglist);
_get_xmp_tags("acdsee", &exiv2_taglist);
_get_xmp_tags("mediapro", &exiv2_taglist);
_get_xmp_tags("expressionmedia", &exiv2_taglist);
_get_xmp_tags("MicrosoftPhoto", &exiv2_taglist);
}
catch (Exiv2::AnyError& e)
{
std::string s(e.what());
std::cerr << "[exiv2 taglist] " << s << std::endl;
}
}
const GList* dt_exif_get_exiv2_taglist()
{
if(!exiv2_taglist)
dt_exif_set_exiv2_taglist();
return exiv2_taglist;
}
static const char *_exif_get_exiv2_tag_type(const char *tagname)
{
if(!tagname) return NULL;
for(GList *tag = exiv2_taglist; tag; tag = g_list_next(tag))
{
char *t = (char *)tag->data;
if(g_str_has_prefix(t, tagname) && t[strlen(tagname)] == ',')
if(t)
{
t += strlen(tagname) + 1;
return t;
}
}
return NULL;
}
// exiv2's readMetadata is not thread safe in 0.26. so we lock it. since readMetadata might throw an exception we
// wrap it into some c++ magic to make sure we unlock in all cases. well, actually not magic but basic raii.
// FIXME: check again once we rely on 0.27
class Lock
{
public:
Lock() { dt_pthread_mutex_lock(&darktable.exiv2_threadsafe); }
~Lock() { dt_pthread_mutex_unlock(&darktable.exiv2_threadsafe); }
};
#define read_metadata_threadsafe(image) \
{ \
Lock lock; \
image->readMetadata(); \
}
static void _exif_import_tags(dt_image_t *img, Exiv2::XmpData::iterator &pos);
static void read_xmp_timestamps(Exiv2::XmpData &xmpData, dt_image_t *img, const int xmp_version);
// this array should contain all XmpBag and XmpSeq keys used by dt
const char *dt_xmp_keys[]
= { "Xmp.dc.subject", "Xmp.lr.hierarchicalSubject", "Xmp.darktable.colorlabels", "Xmp.darktable.history",
"Xmp.darktable.history_modversion", "Xmp.darktable.history_enabled", "Xmp.darktable.history_end",
"Xmp.darktable.iop_order_version", "Xmp.darktable.iop_order_list",
"Xmp.darktable.history_operation", "Xmp.darktable.history_params", "Xmp.darktable.blendop_params",
"Xmp.darktable.blendop_version", "Xmp.darktable.multi_priority", "Xmp.darktable.multi_name",
"Xmp.darktable.iop_order",
"Xmp.darktable.xmp_version", "Xmp.darktable.raw_params", "Xmp.darktable.auto_presets_applied",
"Xmp.darktable.mask_id", "Xmp.darktable.mask_type", "Xmp.darktable.mask_name",
"Xmp.darktable.masks_history", "Xmp.darktable.mask_num", "Xmp.darktable.mask_points",
"Xmp.darktable.mask_version", "Xmp.darktable.mask", "Xmp.darktable.mask_nb", "Xmp.darktable.mask_src",
"Xmp.darktable.history_basic_hash", "Xmp.darktable.history_auto_hash", "Xmp.darktable.history_current_hash",
"Xmp.darktable.import_timestamp", "Xmp.darktable.change_timestamp",
"Xmp.darktable.export_timestamp", "Xmp.darktable.print_timestamp",
"Xmp.acdsee.notes", "Xmp.darktable.version_name",
"Xmp.dc.creator", "Xmp.dc.publisher", "Xmp.dc.title", "Xmp.dc.description", "Xmp.dc.rights",
"Xmp.xmpMM.DerivedFrom" };
static const guint dt_xmp_keys_n = G_N_ELEMENTS(dt_xmp_keys); // the number of XmpBag XmpSeq keys that dt uses
// inspired by ufraw_exiv2.cc:
static void dt_strlcpy_to_utf8(char *dest, size_t dest_max, Exiv2::ExifData::const_iterator &pos,
Exiv2::ExifData &exifData)
{
std::string str = pos->print(&exifData);
char *s = g_locale_to_utf8(str.c_str(), str.length(), NULL, NULL, NULL);
if(s != NULL)
{
g_strlcpy(dest, s, dest_max);
g_free(s);
}
else
{
g_strlcpy(dest, str.c_str(), dest_max);
}
}
// function to remove known dt keys and subtrees from xmpdata, so not to append them twice
// this should work because dt first reads all known keys
static void dt_remove_known_keys(Exiv2::XmpData &xmp)
{
xmp.sortByKey();
for(unsigned int i = 0; i < dt_xmp_keys_n; i++)
{
Exiv2::XmpData::iterator pos = xmp.findKey(Exiv2::XmpKey(dt_xmp_keys[i]));
while(pos != xmp.end())
{
std::string key = pos->key();
const char *ckey = key.c_str();
size_t len = key.size();
// stop iterating once the key no longer matches what we are trying to delete. this assumes sorted input
if(!(g_str_has_prefix(ckey, dt_xmp_keys[i]) && (ckey[len] == '[' || ckey[len] == '\0')))
break;
pos = xmp.erase(pos);
}
}
}
static void dt_remove_exif_keys(Exiv2::ExifData &exif, const char *keys[], unsigned int n_keys)
{
for(unsigned int i = 0; i < n_keys; i++)
{
try
{
Exiv2::ExifData::iterator pos;
while((pos = exif.findKey(Exiv2::ExifKey(keys[i]))) != exif.end())
exif.erase(pos);
}
catch(Exiv2::AnyError &e)
{
// the only exception we may get is "invalid" tag, which is not
// important enough to either stop the function, or even display
// a message (it's probably the tag is not implemented in the
// exiv2 version used)
}
}
}
static void dt_remove_xmp_keys(Exiv2::XmpData &xmp, const char *keys[], unsigned int n_keys)
{
for(unsigned int i = 0; i < n_keys; i++)
{
try
{
Exiv2::XmpData::iterator pos;
while((pos = xmp.findKey(Exiv2::XmpKey(keys[i]))) != xmp.end())
xmp.erase(pos);
}
catch(Exiv2::AnyError &e)
{
// the only exception we may get is "invalid" tag, which is not
// important enough to either stop the function, or even display
// a message (it's probably the tag is not implemented in the
// exiv2 version used)
}
}
}
static bool dt_exif_read_xmp_tag(Exiv2::XmpData &xmpData, Exiv2::XmpData::iterator *pos, string key)
{
try
{
return (*pos = xmpData.findKey(Exiv2::XmpKey(key))) != xmpData.end() && (*pos)->size();
}
catch(Exiv2::AnyError &e)
{
std::string s(e.what());
std::cerr << "[exiv2 read_xmp_tag] " << s << std::endl;
return false;
}
}
#define FIND_XMP_TAG(key) dt_exif_read_xmp_tag(xmpData, &pos, key)
// exiftool (but apparently not exiv2) convert
// e.g. "2017:10:23 12:34:56" to "2017-10-23T12:34:54" (ISO)
// and some vendors incorrectly use "2017/10/23"
// revert this to the format expected by exif and darktable
static void _sanitize_datetime(char *datetime)
{
// replace 'T' by ' ' (space)
char *c;
while((c = strchr(datetime, 'T')) != NULL)
{
*c = ' ';
}
// replace '-' and '/' by ':'
while((c = strchr(datetime, '-')) != NULL || (c = strchr(datetime, '/')) != NULL)
{
*c = ':';
}
}
// FIXME: according to http://www.exiv2.org/doc/classExiv2_1_1Metadatum.html#63c2b87249ba96679c29e01218169124
// there is no need to pass xmpData
// version = -1 -> version ignored
static bool _exif_decode_xmp_data(dt_image_t *img, Exiv2::XmpData &xmpData, int version,
bool exif_read)
{
// as this can be called several times during the image lifetime, clean up first
GList *imgs = NULL;
imgs = g_list_prepend(imgs, GINT_TO_POINTER(img->id));
try
{
Exiv2::XmpData::iterator pos;
// older darktable version did not write this data correctly:
// the reasoning behind strdup'ing all the strings before passing it to sqlite3 is, that
// they are somehow corrupt after the call to sqlite3_prepare_v2() -- don't ask me
// why for they don't get passed to that function.
if(version == -1 || version > 0)
{
if(!exif_read) dt_metadata_clear(imgs, FALSE);
for(unsigned int i = 0; i < DT_METADATA_NUMBER; i++)
{
const gchar *key = dt_metadata_get_key(i);
if(FIND_XMP_TAG(key))
{
char *value = strdup(pos->toString().c_str());
char *adr = value;
// skip any lang="" or charset=xxx
while(!strncmp(value, "lang=", 5) || !strncmp(value, "charset=", 8))
{
while(*value != ' ' && *value) value++;
while(*value == ' ') value++;
}
dt_metadata_set_import(img->id, key, value);
free(adr);
}
}
}
if(FIND_XMP_TAG("Xmp.xmp.Rating"))
{
const int stars = pos->toLong();
dt_image_set_xmp_rating(img, stars);
}
else
dt_image_set_xmp_rating(img, -2);
if(!exif_read) dt_colorlabels_remove_labels(img->id);
if(FIND_XMP_TAG("Xmp.xmp.Label"))
{
std::string label = pos->toString();
if(label == "Red") // Is it really called like that in XMP files?
dt_colorlabels_set_label(img->id, 0);
else if(label == "Yellow") // Is it really called like that in XMP files?
dt_colorlabels_set_label(img->id, 1);
else if(label == "Green")
dt_colorlabels_set_label(img->id, 2);
else if(label == "Blue") // Is it really called like that in XMP files?
dt_colorlabels_set_label(img->id, 3);
else if(label == "Purple") // Is it really called like that in XMP files?
dt_colorlabels_set_label(img->id, 4);
}
// if Xmp.xmp.Label not managed from an external app use dt colors
else if(FIND_XMP_TAG("Xmp.darktable.colorlabels"))
{
// color labels
const int cnt = pos->count();
for(int i = 0; i < cnt; i++)
{
dt_colorlabels_set_label(img->id, pos->toLong(i));
}
}
if((dt_image_get_xmp_mode() != DT_WRITE_XMP_NEVER) ||
dt_conf_get_bool("ui_last/import_last_tags_imported"))
{
GList *tags = NULL;
// preserve dt tags which are not saved in xmp file
if(!exif_read) dt_tag_set_tags(tags, imgs, TRUE, TRUE, FALSE);
if(FIND_XMP_TAG("Xmp.lr.hierarchicalSubject"))
_exif_import_tags(img, pos);
else if(FIND_XMP_TAG("Xmp.dc.subject"))
_exif_import_tags(img, pos);
}
/* read gps location */
if(FIND_XMP_TAG("Xmp.exif.GPSLatitude"))
{
img->geoloc.latitude = dt_util_gps_string_to_number(pos->toString().c_str());
}
if(FIND_XMP_TAG("Xmp.exif.GPSLongitude"))
{
img->geoloc.longitude = dt_util_gps_string_to_number(pos->toString().c_str());
}
if(FIND_XMP_TAG("Xmp.exif.GPSAltitude"))
{
Exiv2::XmpData::const_iterator ref = xmpData.findKey(Exiv2::XmpKey("Xmp.exif.GPSAltitudeRef"));
if(ref != xmpData.end() && ref->size())
{
std::string sign_str = ref->toString();
const char *sign = sign_str.c_str();
double elevation = 0.0;
if(dt_util_gps_elevation_to_number(pos->toRational(0).first, pos->toRational(0).second, sign[0], &elevation))
img->geoloc.elevation = elevation;
}
}
/* read lens type from Xmp.exifEX.LensModel */
if(FIND_XMP_TAG("Xmp.exifEX.LensModel"))
{
// lens model
char *lens = strdup(pos->toString().c_str());
char *adr = lens;
if(strncmp(lens, "lang=", 5) == 0)
{
lens = strchr(lens, ' ');
if(lens != NULL) lens++;
}
// no need to do any Unicode<->locale conversion, the field is specified as ASCII
g_strlcpy(img->exif_lens, lens, sizeof(img->exif_lens));
free(adr);
}
/* read timestamp from Xmp.exif.DateTimeOriginal */
if(FIND_XMP_TAG("Xmp.exif.DateTimeOriginal"))
{
char *datetime = strdup(pos->toString().c_str());
_sanitize_datetime(datetime);
dt_datetime_exif_to_img(img, datetime);
free(datetime);
}
if(imgs) g_list_free(imgs);
imgs = NULL;
return true;
}
catch(Exiv2::AnyError &e)
{
if(imgs) g_list_free(imgs);
imgs = NULL;
std::string s(e.what());
std::cerr << "[exiv2 _exif_decode_xmp_data] " << img->filename << ": " << s << std::endl;
return false;
}
}
static bool dt_exif_read_iptc_tag(Exiv2::IptcData &iptcData, Exiv2::IptcData::const_iterator *pos, string key)
{
try
{
return (*pos = iptcData.findKey(Exiv2::IptcKey(key))) != iptcData.end() && (*pos)->size();
}
catch(Exiv2::AnyError &e)
{
std::string s(e.what());
std::cerr << "[exiv2 read_iptc_tag] " << s << std::endl;
return false;
}
}
#define FIND_IPTC_TAG(key) dt_exif_read_iptc_tag(iptcData, &pos, key)
// FIXME: according to http://www.exiv2.org/doc/classExiv2_1_1Metadatum.html#63c2b87249ba96679c29e01218169124
// there is no need to pass iptcData
static bool _exif_decode_iptc_data(dt_image_t *img, Exiv2::IptcData &iptcData)
{
try
{
Exiv2::IptcData::const_iterator pos;
iptcData.sortByKey(); // this helps to quickly find all Iptc.Application2.Keywords
if((pos = iptcData.findKey(Exiv2::IptcKey("Iptc.Application2.Keywords"))) != iptcData.end())
{
while(pos != iptcData.end())
{
std::string key = pos->key();
if(g_strcmp0(key.c_str(), "Iptc.Application2.Keywords")) break;
std::string str = pos->print();
char *tag = dt_util_foo_to_utf8(str.c_str());
guint tagid = 0;
dt_tag_new(tag, &tagid);
dt_tag_attach(tagid, img->id, FALSE, FALSE);
g_free(tag);
++pos;
}
DT_DEBUG_CONTROL_SIGNAL_RAISE(darktable.signals, DT_SIGNAL_TAG_CHANGED);
}
if(FIND_IPTC_TAG("Iptc.Application2.Caption"))
{
std::string str = pos->print(/*&iptcData*/);
dt_metadata_set_import(img->id, "Xmp.dc.description", str.c_str());
}
if(FIND_IPTC_TAG("Iptc.Application2.Copyright"))
{
std::string str = pos->print(/*&iptcData*/);
dt_metadata_set_import(img->id, "Xmp.dc.rights", str.c_str());
}
if(FIND_IPTC_TAG("Iptc.Application2.Writer"))
{
std::string str = pos->print(/*&iptcData*/);
dt_metadata_set_import(img->id, "Xmp.dc.creator", str.c_str());
}
else if(FIND_IPTC_TAG("Iptc.Application2.Contact"))
{
std::string str = pos->print(/*&iptcData*/);
dt_metadata_set_import(img->id, "Xmp.dc.creator", str.c_str());
}
return true;
}
catch(Exiv2::AnyError &e)
{
std::string s(e.what());
std::cerr << "[exiv2 _exif_decode_iptc_data] " << img->filename << ": " << s << std::endl;
return false;
}
}
// Support DefaultUserCrop, what is the safe exif tag?
// Magic-nr taken from dng specs, the specs also say it has 4 floats (top,left,bottom,right
// We only take them if a) we find a value != the default *and* b) data are plausible
static bool dt_check_usercrop(Exiv2::ExifData &exifData, dt_image_t *img)
{
Exiv2::ExifData::const_iterator pos = exifData.findKey(Exiv2::ExifKey("Exif.SubImage1.0xc7b5"));
if(pos != exifData.end() && pos->count() == 4 && pos->size())
{
dt_boundingbox_t crop;
for(int i = 0; i < 4; i++) crop[i] = pos->toFloat(i);
if(((crop[0]>0)||(crop[1]>0)||(crop[2]<1)||(crop[3]<1))&&(crop[2]-crop[0]>0.05f)&&(crop[3]-crop[1]>0.05f))
{
for(int i=0; i<4; i++) img->usercrop[i] = crop[i];
return TRUE;
}
}
return FALSE;
}
static gboolean dt_check_dng_opcodes(Exiv2::ExifData &exifData, dt_image_t *img)
{
gboolean has_opcodes = FALSE;
Exiv2::ExifData::const_iterator pos = exifData.findKey(Exiv2::ExifKey("Exif.SubImage1.OpcodeList2"));
// DNGs without an embedded preview have the opcodes under Exif.Image instead of Exif.SubImage1
if(pos == exifData.end())
pos = exifData.findKey(Exiv2::ExifKey("Exif.Image.OpcodeList2"));
if(pos != exifData.end())
{
uint8_t *data = (uint8_t *)g_malloc(pos->size());
pos->copy(data, Exiv2::invalidByteOrder);
dt_dng_opcode_process_opcode_list_2(data, pos->size(), img);
g_free(data);
has_opcodes = TRUE;
}
else
{
dt_vprint(DT_DEBUG_IMAGEIO, "DNG OpcodeList2 tag not found\n");
}
return has_opcodes;
}
void dt_exif_img_check_additional_tags(dt_image_t *img, const char *filename)
{
try
{
std::unique_ptr<Exiv2::Image> image(Exiv2::ImageFactory::open(WIDEN(filename)));
assert(image.get() != 0);
read_metadata_threadsafe(image);
Exiv2::ExifData &exifData = image->exifData();
if(!exifData.empty())
{
dt_check_usercrop(exifData, img);
dt_check_dng_opcodes(exifData, img);
}
return;
}
catch(Exiv2::AnyError &e)
{
std::string s(e.what());
std::cerr << "[exiv2 reading DefaultUserCrop] " << filename << ": " << s << std::endl;
return;
}
}
static bool dt_exif_read_exif_tag(Exiv2::ExifData &exifData, Exiv2::ExifData::const_iterator *pos, string key)
{
try
{
return (*pos = exifData.findKey(Exiv2::ExifKey(key))) != exifData.end() && (*pos)->size();
}
catch(Exiv2::AnyError &e)
{
std::string s(e.what());
std::cerr << "[exiv2 read_exif_tag] " << s << std::endl;
return false;
}
}
#define FIND_EXIF_TAG(key) dt_exif_read_exif_tag(exifData, &pos, key)
static void _find_datetime_taken(Exiv2::ExifData &exifData, Exiv2::ExifData::const_iterator pos,
char *exif_datetime_taken)
{
if((FIND_EXIF_TAG("Exif.Image.DateTimeOriginal") || FIND_EXIF_TAG("Exif.Photo.DateTimeOriginal"))
&& pos->size() == DT_DATETIME_EXIF_LENGTH)
{
dt_strlcpy_to_utf8(exif_datetime_taken, DT_DATETIME_EXIF_LENGTH, pos, exifData);
_sanitize_datetime(exif_datetime_taken);
if(FIND_EXIF_TAG("Exif.Photo.SubSecTimeOriginal")
&& pos->size() > 1)
{
char msec[4];
dt_strlcpy_to_utf8(msec, sizeof(msec), pos, exifData);
dt_datetime_add_subsec_to_exif(exif_datetime_taken, DT_DATETIME_LENGTH, msec);
}
}
else
{
*exif_datetime_taken = '\0';
}
}
static void _find_exif_maker(Exiv2::ExifData &exifData, Exiv2::ExifData::const_iterator pos, char *maker, const size_t m_size)
{
// look for maker & model first so we can use that info later
if(FIND_EXIF_TAG("Exif.Image.Make"))
{
dt_strlcpy_to_utf8(maker, m_size, pos, exifData);
}
else if(FIND_EXIF_TAG("Exif.PanasonicRaw.Make"))
{
dt_strlcpy_to_utf8(maker, m_size, pos, exifData);
}
for(char *c = maker + m_size - 1; c > maker; c--)
if(*c != ' ' && *c != '\0')
{
*(c + 1) = '\0';
break;
}
}
static void _find_exif_model(Exiv2::ExifData &exifData, Exiv2::ExifData::const_iterator pos, char *model, const size_t m_size)
{
if(FIND_EXIF_TAG("Exif.Image.Model"))
{
dt_strlcpy_to_utf8(model, m_size, pos, exifData);
}
else if(FIND_EXIF_TAG("Exif.PanasonicRaw.Model"))
{
dt_strlcpy_to_utf8(model, m_size, pos, exifData);
}
for(char *c = model + m_size - 1; c > model; c--)
if(*c != ' ' && *c != '\0')
{
*(c + 1) = '\0';
break;
}
}
static void _find_exif_makermodel(Exiv2::ExifData &exifData, Exiv2::ExifData::const_iterator pos, dt_image_basic_exif_t *basic_exif)
{
char exif_maker[sizeof(basic_exif->maker)];
char exif_model[sizeof(basic_exif->model)];
char model[sizeof(basic_exif->model)];
exif_maker[0] = exif_model[0] = basic_exif->maker[0] = model[0] = basic_exif->model[0] = '\0';
// look for maker & model first so we can use that info later
_find_exif_maker(exifData, pos, exif_maker, sizeof(exif_maker));
_find_exif_model(exifData, pos, exif_model, sizeof(exif_model));
dt_imageio_lookup_makermodel(exif_maker, exif_model,
basic_exif->maker, sizeof(basic_exif->maker),
model, sizeof(model),
basic_exif->model, sizeof(basic_exif->model));
}
static bool _exif_decode_exif_data(dt_image_t *img, Exiv2::ExifData &exifData)
{
try
{
/* List of tag names taken from exiv2's printSummary() in actions.cpp */
Exiv2::ExifData::const_iterator pos;
_find_exif_maker(exifData, pos, img->exif_maker, sizeof(img->exif_maker));
_find_exif_model(exifData, pos, img->exif_model, sizeof(img->exif_model));
// Make sure we copy the exif make and model to the correct place if needed
dt_image_refresh_makermodel(img);
/* Read shutter time */
if((pos = Exiv2::exposureTime(exifData)) != exifData.end() && pos->size())
{
// dt_strlcpy_to_utf8(uf->conf->shutterText, max_name, pos, exifData);
img->exif_exposure = pos->toFloat();
}
else if(FIND_EXIF_TAG("Exif.Photo.ShutterSpeedValue") || FIND_EXIF_TAG("Exif.Image.ShutterSpeedValue"))
{
// uf_strlcpy_to_utf8(uf->conf->shutterText, max_name, pos, exifData);
img->exif_exposure = exp2f(-1.0f * pos->toFloat()); // convert from APEX value
}
// Read exposure bias
if(FIND_EXIF_TAG("Exif.Photo.ExposureBiasValue") || FIND_EXIF_TAG("Exif.Image.ExposureBiasValue"))
{
img->exif_exposure_bias = pos->toFloat();
}
/* Read aperture */
if((pos = Exiv2::fNumber(exifData)) != exifData.end() && pos->size())
{
img->exif_aperture = pos->toFloat();
}
else if(FIND_EXIF_TAG("Exif.Photo.ApertureValue") || FIND_EXIF_TAG("Exif.Image.ApertureValue"))
{
img->exif_aperture = exp2f(pos->toFloat() / 2.0f); // convert from APEX value
}
/* Read ISO speed - Nikon happens to return a pair for Lo and Hi modes */
if((pos = Exiv2::isoSpeed(exifData)) != exifData.end() && pos->size())
{
// if standard exif iso tag, use the old way of interpreting the return value to be more regression-save
if(strcmp(pos->key().c_str(), "Exif.Photo.ISOSpeedRatings") == 0)
{
int isofield = pos->count() > 1 ? 1 : 0;
img->exif_iso = pos->toFloat(isofield);
}
else
{
std::string str = pos->print();
img->exif_iso = (float)std::atof(str.c_str());
}
}
// some newer cameras support iso settings that exceed the 16 bit of exif's ISOSpeedRatings
if(img->exif_iso == 65535 || img->exif_iso == 0)
{
if(FIND_EXIF_TAG("Exif.PentaxDng.ISO") || FIND_EXIF_TAG("Exif.Pentax.ISO"))
{
std::string str = pos->print();
img->exif_iso = (float)std::atof(str.c_str());
}
else if((!g_strcmp0(img->exif_maker, "SONY") || !g_strcmp0(img->exif_maker, "Canon"))
&& FIND_EXIF_TAG("Exif.Photo.RecommendedExposureIndex"))
{
img->exif_iso = pos->toFloat();
}
}
/* Read focal length */
if((pos = Exiv2::focalLength(exifData)) != exifData.end() && pos->size())
{
// This works around a bug in exiv2 the developers refuse to fix
// For details see http://dev.exiv2.org/issues/1083
if(pos->key() == "Exif.Canon.FocalLength" && pos->count() == 4)
img->exif_focal_length = pos->toFloat(1);
else
img->exif_focal_length = pos->toFloat();
}
/* Read focal length in 35mm if available and try to calculate crop factor */
if(FIND_EXIF_TAG("Exif.Photo.FocalLengthIn35mmFilm"))
{
const float focal_length_35mm = pos->toFloat();
if(focal_length_35mm > 0.0f && img->exif_focal_length > 0.0f)
img->exif_crop = focal_length_35mm / img->exif_focal_length;
else
img->exif_crop = 1.0f;
}
if(dt_check_usercrop(exifData, img))
{
img->flags |= DT_IMAGE_HAS_ADDITIONAL_DNG_TAGS;
guint tagid = 0;
char tagname[64];
snprintf(tagname, sizeof(tagname), "darktable|mode|exif-crop");
dt_tag_new(tagname, &tagid);
dt_tag_attach(tagid, img->id, FALSE, FALSE);
}
if(dt_check_dng_opcodes(exifData, img))
{
img->flags |= DT_IMAGE_HAS_ADDITIONAL_DNG_TAGS;
}
/*
* Get the focus distance in meters.
*/
if(FIND_EXIF_TAG("Exif.NikonLd2.FocusDistance"))
{
float value = pos->toFloat();
img->exif_focus_distance = (0.01 * pow(10, value / 40));
}
else if(FIND_EXIF_TAG("Exif.NikonLd3.FocusDistance"))
{
float value = pos->toFloat();
img->exif_focus_distance = (0.01 * pow(10, value / 40));
}
else if(FIND_EXIF_TAG("Exif.OlympusFi.FocusDistance"))
{
/* the distance is stored as a rational (fraction). according to
* http://www.dpreview.com/forums/thread/1173960?page=4
* some Olympus cameras have a wrong denominator of 10 in there while the nominator is always in mm.
* thus we ignore the denominator
* and divide with 1000.
* "I've checked a number of E-1 and E-300 images, and I agree that the FocusDistance looks like it is
* in mm for the E-1. However,
* it looks more like cm for the E-300.
* For both cameras, this value is stored as a rational. With the E-1, the denominator is always 1,
* while for the E-300 it is 10.
* Therefore, it looks like the numerator in both cases is in mm (which makes a bit of sense, in an odd
* sort of way). So I think
* what I will do in ExifTool is to take the numerator and divide by 1000 to display the focus distance
* in meters."
* -- Boardhead, dpreview forums in 2005
*/
int nominator = pos->toRational(0).first;
img->exif_focus_distance = fmax(0.0, (0.001 * nominator));
}
else if(Exiv2::testVersion(0,25,0) && FIND_EXIF_TAG("Exif.CanonFi.FocusDistanceUpper"))
{
const float FocusDistanceUpper = pos->toFloat();
if(FocusDistanceUpper <= 0.0f || (int)FocusDistanceUpper >= 0xffff)
{
img->exif_focus_distance = 0.0f;
}
else
{