Repository navigation
Expand file tree
/
Copy pathmetadata_xmp.cpp
More file actions
1629 lines (1353 loc) · 49.9 KB
/
Copy pathmetadata_xmp.cpp
File metadata and controls
1629 lines (1353 loc) · 49.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of the Diffractor photo and video organizer
// Copyright 2026 Zac Walker
//
// This program is free software; you can redistribute it and / or modify it
// under the terms of the LGPL License either version 2.1 or later.
// License details are available at https://www.gnu.org/licenses/lgpl-2.1.html
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY
// Purpose: XMP (Extensible Metadata Platform) support. Maps Diffractor's properties to and from XMP
// packets, whose data model is libfiles', and reads and writes the packets in files with libfiles.
#include "pch.h"
#include "model_property.h"
#include "model_location.h"
#include "metadata_xmp.h"
#include "files.h"
#include "libfiles/write.h"
#include "libfiles/xmp.h"
namespace xmp_ns = libfiles::xmp::ns;
// ReSharper disable CppUnusedIncludeDirective
#include "metadata_exif.h"
static df::file_path s_test_raw_source_xmp_path;
static df::blob s_test_raw_source_xmp;
static std::vector<int> s_test_update_failure_sequence;
void metadata_xmp::set_test_raw_source_xmp(const df::file_path path, const df::cspan xmp)
{
s_test_raw_source_xmp_path = path;
s_test_raw_source_xmp.assign(xmp.begin(), xmp.end());
}
void metadata_xmp::set_test_update_failure_sequence(std::vector<int> actions)
{
s_test_update_failure_sequence = std::move(actions);
}
// A malformed sidecar or a bad batch of files repeats the same failure for every scanned item, so
// each distinct message is written once and the total is capped; the session total lands in the
// exit perf summary.
static void record_xmp_error(const std::string_view context, const std::string_view message)
{
df::bump(df::file_perf.metadata_errors);
df::log_once(context, message);
}
static df::date_t xmp_parse_date(const std::string_view str)
{
if (!str.empty())
{
df::date_t ft;
ft.parse_xml_date(str);
if (ft.is_valid())
{
return ft;
}
}
return {};
}
// parse_xml_date reads the digits and drops the zone, so the caller has to recover it. Without
// this an XMP date ending in Z is filed as a local reading and lands an hour or more away from the
// container date it is meant to agree with, which then reads as two dates instead of one.
static int16_t xmp_date_offset(const std::string_view str)
{
return prop::parse_utc_offset(str);
}
static bool xmp_parse_coordinate_part(const std::string_view text, double& result)
{
if (text.empty()) return false;
const auto* const begin = text.data();
const auto* const end = begin + text.size();
const auto parsed = std::from_chars(begin, end, result);
return parsed.ec == std::errc{} && parsed.ptr == end && result >= 0.0;
}
static bool xmp_decode_gps_coordinate(const std::string_view str, const bool is_latitude, double& result)
{
const auto text = str::trim(str);
const auto len = text.size();
if (len < 4) return false;
// DDD,MM,SSk
// DDD,MM.mmk
// Key:
// DDD = number of degrees
// MM = number of minutes
// SS = number of seconds
// mm = fraction of minutes
// k = {N/S/E/W}
const auto hemisphere = text[len - 1];
const auto north = hemisphere == 'N' || hemisphere == 'n';
const auto south = hemisphere == 'S' || hemisphere == 's';
const auto east = hemisphere == 'E' || hemisphere == 'e';
const auto west = hemisphere == 'W' || hemisphere == 'w';
if (is_latitude ? !(north || south) : !(east || west)) return false;
const auto body = text.substr(0, len - 1);
const auto first_comma = body.find(',');
if (first_comma == std::string_view::npos) return false;
const auto second_comma = body.find(',', first_comma + 1);
if (second_comma != std::string_view::npos && body.find(',', second_comma + 1) != std::string_view::npos)
return false;
double degrees = 0.0;
double minutes = 0.0;
double seconds = 0.0;
if (!xmp_parse_coordinate_part(body.substr(0, first_comma), degrees)) return false;
if (second_comma == std::string_view::npos)
{
if (!xmp_parse_coordinate_part(body.substr(first_comma + 1), minutes)) return false;
}
else
{
if (!xmp_parse_coordinate_part(body.substr(first_comma + 1, second_comma - first_comma - 1), minutes))
return false;
if (!xmp_parse_coordinate_part(body.substr(second_comma + 1), seconds)) return false;
}
if (minutes >= 60.0 || seconds >= 60.0) return false;
const auto coordinate = gps_coordinate::dms_to_decimal(degrees, minutes, seconds);
const auto signed_coordinate = (south || west) ? -coordinate : coordinate;
const auto candidate = is_latitude ? gps_coordinate(signed_coordinate, 0.0) : gps_coordinate(0.0, signed_coordinate);
if (!candidate.is_valid()) return false;
result = signed_coordinate;
return true;
}
static bool xmp_decode_rational(const std::string_view text, metadata_exif::urational32_t& result)
{
const auto len = text.size();
unsigned long locNum = 0, locDenom = 0;
char nextChar = 0; // Used to make sure sscanf consumes all of the string.
const auto* const sz = std::bit_cast<const char*>(text.data());
const int items = _snscanf_s(sz, len, "%lu/%lu%c", &locNum, &locDenom, &nextChar, 1);
// AUDIT: This is safe, check the calls.
if (items != 2)
{
if (items != 1) return false;
locDenom = 1; // The XMP was just an integer, assume a denominator of 1.
}
// Protect against division by zero
if (locDenom == 0)
{
return false;
}
result.numerator = locNum;
result.denominator = locDenom;
return true;
}
std::string microsoft_photo_prefix;
// xmp:Rating is -1 (rejected) through 5. Anything else came from a broken writer.
static int xmp_safe_rating(const int r)
{
return std::clamp(r, -1, 5);
}
static str::cached xmp_load_array(const libfiles::xmp::meta& xmp, const std::string_view schema_ns,
const std::string_view array_name)
{
str::cached result = {};
const auto count = xmp.count_array_items(schema_ns, array_name);
if (count > 0)
{
std::vector<std::string> parts;
parts.reserve(count);
for (auto i = 0; i < count; i++)
{
std::string str;
if (xmp.get_array_item(schema_ns, array_name, i + 1, &str))
{
parts.emplace_back(str::utf8_cast(str));
}
}
if (!parts.empty())
{
result = str::cache(str::combine(parts));
}
}
return result;
}
// Google's photo sphere namespace, which is what a phone panorama mode and most stitchers write.
// It is not one the toolkit knows, so it is registered at startup before any file is parsed.
constexpr auto ns_gpano = "http://ns.google.com/photos/1.0/panorama/";
// Records what the file itself declares, never what its shape suggests. `UsePanoramaViewer` and the
// cropped-area properties are read only to answer "is this a panorama" for a writer that omitted
// ProjectionType; a file carrying none of them is not one.
static void read_panorama_projection(const libfiles::xmp::meta& xmp, prop::item_metadata& md)
{
std::string utf8;
if (xmp.get_property(ns_gpano, "ProjectionType", &utf8))
{
const auto text = str::trim(str::utf8_cast(utf8));
if (str::icmp(text, "equirectangular") == 0)
{
md.panorama = prop::panorama_projection::equirectangular;
return;
}
if (str::icmp(text, "cylindrical") == 0)
{
md.panorama = prop::panorama_projection::cylindrical;
return;
}
if (!text.empty())
{
md.panorama = prop::panorama_projection::unspecified;
return;
}
}
for (const auto* const declares_panorama : {
"UsePanoramaViewer", "FullPanoWidthPixels", "CroppedAreaImageWidthPixels"
})
{
if (xmp.get_property(ns_gpano, declares_panorama, &utf8))
{
md.panorama = prop::panorama_projection::unspecified;
return;
}
}
}
static void parse_xmp(const libfiles::xmp::meta& xmp, prop::item_metadata& md)
{
std::string utf8;
if (xmp.get_property(xmp_ns::photoshop, "DateCreated", &utf8))
{
const auto text = str::utf8_cast(utf8);
const auto d = xmp_parse_date(text);
if (d.is_valid()) md.dates.add(prop::date_source::photoshop_created, d, xmp_date_offset(text));
}
if (xmp.get_property(xmp_ns::xmp, "CreateDate", &utf8))
{
const auto text = str::utf8_cast(utf8);
const auto d = xmp_parse_date(text);
if (d.is_valid())
{
md.dates.add(prop::date_source::xmp_create, d, xmp_date_offset(text));
}
else if (str::is_num(text))
{
md.year = str::to_int(text);
}
}
if (xmp.get_property(xmp_ns::xmp, "ModifyDate", &utf8))
{
const auto text = str::utf8_cast(utf8);
const auto d = xmp_parse_date(text);
if (d.is_valid()) md.dates.add(prop::date_source::xmp_modify, d, xmp_date_offset(text));
}
if (xmp.get_property(xmp_ns::exif, "DateTimeDigitized", &utf8))
{
const auto text = str::utf8_cast(utf8);
const auto d = xmp_parse_date(text);
if (d.is_valid()) md.dates.add(prop::date_source::xmp_exif_digitized, d, xmp_date_offset(text));
}
if (xmp.get_property(xmp_ns::exif, "DateTimeOriginal", &utf8))
{
const auto text = str::utf8_cast(utf8);
const auto d = xmp_parse_date(text);
if (d.is_valid()) md.dates.add(prop::date_source::xmp_exif_original, d, xmp_date_offset(text));
}
// A coordinate that failed to decode must not be applied - a zeroed half pins the item to the
// Gulf of Guinea instead of leaving the location unknown. Applied as a pair for the same reason:
// a file carrying only one XMP component would otherwise keep the other from EXIF, pinning the
// item to a coordinate neither source states.
{
double latitude = 0;
double longitude = 0;
const auto has_latitude = xmp.get_property(xmp_ns::exif, "GPSLatitude", &utf8) &&
xmp_decode_gps_coordinate(str::utf8_cast(utf8), true, latitude);
const auto has_longitude = xmp.get_property(xmp_ns::exif, "GPSLongitude", &utf8) &&
xmp_decode_gps_coordinate(str::utf8_cast(utf8), false, longitude);
if (has_latitude && has_longitude)
{
const gps_coordinate candidate(latitude, longitude);
if (candidate.is_valid()) md.coordinate = candidate;
}
}
if (xmp.get_property(xmp_ns::photoshop, "City", &utf8))
{
md.location_place = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::photoshop, "State", &utf8))
{
md.location_state = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::photoshop, "Country", &utf8))
{
md.location_country = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::photoshop, "Credit", &utf8))
{
md.copyright_credit = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::xmp_rights, "WebStatement", &utf8))
{
md.copyright_url = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::photoshop, "Source", &utf8))
{
md.copyright_source = str::strip_and_cache(utf8);
}
// Xmp is parsed last, so an absent array must not erase what Exif or Iptc supplied.
if (const auto creator = xmp_load_array(xmp, xmp_ns::dc, "creator"); !str::is_empty(creator))
{
md.copyright_creator = creator;
}
if (xmp.get_localized_text(xmp_ns::dc, "rights", "", "x-default", nullptr, &utf8))
{
md.copyright_notice = str::strip_and_cache(utf8);
}
if (xmp.get_localized_text(xmp_ns::dc, "title", "", "x-default", nullptr, &utf8))
{
md.title = str::strip_and_cache(utf8);
}
if (xmp.get_localized_text(xmp_ns::exif, "UserComment", "", "x-default", nullptr, &utf8))
{
md.comment = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::dm, "logComment", &utf8))
{
md.comment = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::dm, "synopsis", &utf8))
{
md.synopsis = str::strip_and_cache(utf8);
}
if (xmp.get_localized_text(xmp_ns::dc, "description", "", "x-default", nullptr, &utf8))
{
md.description = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::xmp, "Rating", &utf8))
{
md.rating = xmp_safe_rating(str::to_int(str::utf8_cast(utf8)));
}
else if (xmp.get_property(xmp_ns::microsoft_photo, "Rating", &utf8))
{
//MicrosoftPhoto:Rating
md.rating = xmp_safe_rating(df::round_up(str::to_int(str::utf8_cast(utf8)), 20));
}
if (xmp.get_property(xmp_ns::xmp, "Label", &utf8))
{
md.label = str::strip_and_cache(utf8);
}
// Xmp is parsed last, so an array that is simply absent must not erase what Exif or Iptc
// supplied. An array that is present and empty is different: that is the file stating it has no
// tags, and the writer above emits exactly that for cleared tags rather than deleting the
// property. Reading only the non-empty case threw that statement away, so clearing every tag
// and rescanning brought the legacy Iptc keywords straight back.
if (xmp.exists(xmp_ns::dc, "subject"))
{
md.tags = xmp_load_array(xmp, xmp_ns::dc, "subject");
}
if (xmp.get_property(xmp_ns::tiff, "Make", &utf8))
{
md.camera_manufacturer = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::tiff, "Model", &utf8))
{
md.camera_model = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::dm, "album", &utf8))
{
md.album = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::dm, "albumArtist", &utf8))
{
md.album_artist = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::dm, "artist", &utf8))
{
md.artist = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::dm, "genre", &utf8))
{
md.genre = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::dm, "show", &utf8))
{
md.show = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::dm, "trackNumber", &utf8))
{
md.track = df::xy8::parse(str::utf8_cast(utf8));
}
if (xmp.get_property(xmp_ns::dm, "discNumber", &utf8))
{
md.disk = df::xy8::parse(str::utf8_cast(utf8));
}
if (xmp.get_property(xmp_ns::dm, "episode", &utf8))
{
md.episode = df::xy8::parse(str::utf8_cast(utf8));
}
if (xmp.get_property(xmp_ns::dm, "season", &utf8))
{
md.season = str::to_int(str::utf8_cast(utf8));
}
// <exif:FNumber>33/10</exif:FNumber>
// <exif:FocalLength>600/10</exif:FocalLength>
// <exif:ExposureTime>10/100</exif:ExposureTime>
if (xmp.get_property(xmp_ns::exif, "FocalLengthIn35mmFilm", &utf8))
{
metadata_exif::urational32_t r;
if (xmp_decode_rational(str::utf8_cast(utf8), r))
{
md.focal_length_35mm_equivalent = r.round();
}
}
if (xmp.get_property(xmp_ns::exif, "FNumber", &utf8))
{
metadata_exif::urational32_t r;
if (xmp_decode_rational(str::utf8_cast(utf8), r))
{
md.f_number = static_cast<float>(r.to_real());
}
}
if (xmp.get_property(xmp_ns::exif, "FocalLength", &utf8))
{
metadata_exif::urational32_t r;
if (xmp_decode_rational(str::utf8_cast(utf8), r))
{
md.focal_length = static_cast<float>(r.to_real());
}
}
if (xmp.get_property(xmp_ns::exif, "ExposureTime", &utf8))
{
metadata_exif::urational32_t r;
if (xmp_decode_rational(str::utf8_cast(utf8), r))
{
md.exposure_time = static_cast<float>(r.to_real());
}
}
if (xmp.get_property(xmp_ns::tiff, "Orientation", &utf8))
{
// An out of range value would index the rotation tables with an undefined enumerator.
const auto o = str::to_int(str::utf8_cast(utf8));
if (o >= 1 && o <= 8) md.orientation = static_cast<ui::orientation>(o);
}
if (xmp.get_property(xmp_ns::exif_aux, "Lens", &utf8))
{
md.lens = str::strip_and_cache(utf8);
}
if (xmp.get_property(xmp_ns::camera_raw, "RawFileName", &utf8))
{
md.raw_file_name = str::strip_and_cache(utf8);
}
read_panorama_projection(xmp, md);
}
void metadata_xmp::initialise()
{
libfiles::xmp::register_namespace(ns_gpano, "GPano");
}
void metadata_edits::apply(libfiles::xmp::meta& meta) const
{
if (location_coordinate.has_value())
{
const auto position = location_coordinate.value();
meta.set_property(xmp_ns::exif, "GPSLatitude",
str::utf8_cast2(gps_coordinate::decimal_to_dms_str(position.latitude(), true)));
meta.set_property(xmp_ns::exif, "GPSLongitude",
str::utf8_cast2(gps_coordinate::decimal_to_dms_str(position.longitude(), false)));
}
if (location_place.has_value())
{
if (!str::is_empty(location_place.value()))
{
meta.set_property(xmp_ns::photoshop, "City", str::utf8_cast2(location_place.value()));
}
else
{
meta.delete_property(xmp_ns::photoshop, "City");
}
}
if (location_state.has_value())
{
if (!str::is_empty(location_state.value()))
{
meta.set_property(xmp_ns::photoshop, "State", str::utf8_cast2(location_state.value()));
}
else
{
meta.delete_property(xmp_ns::photoshop, "State");
}
}
if (location_country.has_value())
{
if (!str::is_empty(location_country.value()))
{
meta.set_property(xmp_ns::photoshop, "Country", str::utf8_cast2(location_country.value()));
}
else
{
meta.delete_property(xmp_ns::photoshop, "Country");
}
}
if (copyright_credit.has_value())
{
meta.set_property(xmp_ns::photoshop, "Credit", str::utf8_cast2(copyright_credit.value()));
}
if (copyright_url.has_value())
{
meta.set_property(xmp_ns::xmp_rights, "WebStatement", str::utf8_cast2(copyright_url.value()));
}
if (copyright_source.has_value())
{
meta.set_property(xmp_ns::photoshop, "Source", str::utf8_cast2(copyright_source.value()));
}
if (copyright_notice.has_value())
{
meta.set_localized_text(xmp_ns::dc, "rights", "", "x-default", str::utf8_cast2(copyright_notice.value()));
}
if (copyright_creator.has_value())
{
// dc:creator is an ordered array of names, and that is how it is read back. Writing it as
// alt-lang text produces a packet Adobe tools will not show.
meta.delete_property(xmp_ns::dc, "creator");
if (str::is_empty(copyright_creator.value()))
{
meta.set_composite(xmp_ns::dc, "creator", libfiles::xmp::array_is_ordered);
}
else
{
// Names are separated by punctuation, never by the space inside "Jane Doe".
for (const auto& part : str::split(copyright_creator.value(), true, str::is_artist_separator))
{
const auto name = str::trim(part);
if (!name.empty())
{
meta.append_array_item(xmp_ns::dc, "creator", libfiles::xmp::array_is_ordered, str::utf8_cast2(name));
}
}
}
}
if (title.has_value())
{
meta.set_localized_text(xmp_ns::dc, "title", "", "x-default", str::utf8_cast2(title.value()));
}
if (description.has_value())
{
meta.set_localized_text(xmp_ns::dc, "description", "", "x-default", str::utf8_cast2(description.value()));
}
if (comment.has_value())
{
meta.set_property(xmp_ns::dm, "logComment", str::utf8_cast2(comment.value()));
}
if (synopsis.has_value())
{
meta.set_property(xmp_ns::dm, "synopsis", str::utf8_cast2(synopsis.value()));
}
if (rating.has_value())
{
const int r = std::clamp(rating.value(), -1, 5);
meta.set_property_int(xmp_ns::xmp, "Rating", r);
meta.set_property_int(xmp_ns::microsoft_photo, "Rating", rating_to_percent(r));
}
if (label.has_value())
{
if (!str::is_empty(label.value()))
{
meta.set_property(xmp_ns::xmp, "Label", str::utf8_cast2(label.value()));
}
else
{
meta.delete_property(xmp_ns::xmp, "Label");
}
}
if (album.has_value())
{
meta.set_property(xmp_ns::dm, "album", str::utf8_cast2(album.value()));
}
if (album_artist.has_value())
{
meta.set_property(xmp_ns::dm, "albumArtist", str::utf8_cast2(album_artist.value()));
}
if (genre.has_value())
{
meta.set_property(xmp_ns::dm, "genre", str::utf8_cast2(genre.value()));
}
if (show.has_value())
{
meta.set_property(xmp_ns::dm, "show", str::utf8_cast2(show.value()));
}
if (year.has_value() && !date_created.has_value())
{
// A bare year and a Created date are the same XMP property, told apart on read by whether it
// parses as a date. Writing both would leave whichever went last, so the date wins: it is the
// more specific answer and it still carries the year.
meta.set_property(xmp_ns::xmp, "CreateDate", str::utf8_cast2(str::to_string(year.value())));
}
if (date_created.has_value())
{
const auto text = str::utf8_cast2(date_created.value().to_xmp_date());
// Both, as Original writes both below: xmp:CreateDate is the fourth-ranked Created source, so
// wherever the file's own DateTimeDigitized survives the write it would outrank the edit and
// the correction would appear to do nothing.
meta.set_property(xmp_ns::xmp, "CreateDate", text);
meta.set_property(xmp_ns::exif, "DateTimeDigitized", text);
}
if (date_original.has_value())
{
const auto text = str::utf8_cast2(date_original.value().to_xmp_date());
// Both, because photoshop:DateCreated alone is the lowest-authority capture source and would
// be outranked by the file's own DateTimeOriginal - the edit would appear to do nothing. The
// toolkit reconciles exif:DateTimeOriginal back into the embedded EXIF on save.
meta.set_property(xmp_ns::photoshop, "DateCreated", text);
meta.set_property(xmp_ns::exif, "DateTimeOriginal", text);
}
if (episode.has_value())
{
meta.set_property(xmp_ns::dm, "episode", str::utf8_cast2(episode.value().str()));
}
if (season.has_value())
{
meta.set_property(xmp_ns::dm, "season", str::utf8_cast2(str::to_string(season.value())));
}
if (track_num.has_value())
{
meta.set_property(xmp_ns::dm, "trackNumber", str::utf8_cast2(track_num.value().str()));
}
if (disk_num.has_value())
{
meta.set_property(xmp_ns::dm, "discNumber", str::utf8_cast2(disk_num.value().str()));
}
if (artist.has_value())
{
meta.set_property(xmp_ns::dm, "artist", str::utf8_cast2(artist.value()));
}
if (orientation.has_value())
{
meta.set_property(xmp_ns::tiff, "Orientation",
str::utf8_cast2(str::to_string(static_cast<int>(orientation.value()))), libfiles::xmp::delete_existing);
}
if (!remove_tags.is_empty() || !add_tags.is_empty())
{
tag_set tags;
const auto count = meta.count_array_items(xmp_ns::dc, "subject");
for (auto i = 0; i < count; i++)
{
std::string str;
if (meta.get_array_item(xmp_ns::dc, "subject", i + 1, &str))
{
tags.add_one(str::cache(str));
}
}
tags.remove(remove_tags);
tags.add(add_tags);
tags.make_unique();
meta.delete_property(xmp_ns::dc, "subject");
if (tags.is_empty())
{
meta.set_composite(xmp_ns::dc, "subject", libfiles::xmp::value_is_array);
}
else
for (auto i = 0u; i < tags.size(); i++)
{
meta.append_array_item(xmp_ns::dc, "subject", libfiles::xmp::value_is_array, str::utf8_cast2(tags[i]));
}
// Sync exif:XPKeywords (Windows Explorer tag) with dc:subject. Cleared tags are written
// as an empty value rather than a deleted property: the TIFF export leaves tags that are
// simply absent from XMP alone, so deleting here would leave the old keywords in place.
meta.set_property(xmp_ns::exif, "XPKeywords",
tags.is_empty() ? std::string() : str::utf8_cast2(tags.to_string(";", false)));
}
if (remove_rating)
{
meta.set_property_int(xmp_ns::xmp, "Rating", 0);
meta.set_property_int(xmp_ns::microsoft_photo, "Rating", 0);
}
}
// A packet from a JPEG APP1 segment still starts with its signature, which already ends in the NUL
// that terminates the segment header.
static std::string_view packet_text(const df::cspan xmp)
{
std::string_view text(std::bit_cast<const char*>(xmp.data), xmp.size);
if (text.size() > xmp_signature.size() && text.starts_with(xmp_signature)) text.remove_prefix(xmp_signature.size());
return text;
}
metadata_xmp::property_presence metadata_xmp::properties(const df::cspan xmp)
{
property_presence result;
try
{
if (xmp.size == 0) return result;
libfiles::xmp::meta meta;
meta.parse(packet_text(xmp));
result.tags = meta.exists(xmp_ns::dc, "subject");
result.rating = meta.exists(xmp_ns::xmp, "Rating") ||
meta.exists(xmp_ns::microsoft_photo, "Rating");
}
catch (const std::exception& e)
{
record_xmp_error(__FUNCTION__, e.what());
}
return result;
}
void metadata_xmp::parse(prop::item_metadata& pd, const df::cspan xmp)
{
try
{
if (xmp.size > 0)
{
libfiles::xmp::meta meta;
meta.parse(packet_text(xmp));
parse_xmp(meta, pd);
}
}
catch (const std::exception& e)
{
record_xmp_error(__FUNCTION__, e.what());
}
}
void metadata_xmp::parse(prop::item_metadata& pd, const df::file_path path)
{
try
{
libfiles::xmp::meta xmp;
auto f = blob_from_file(path);
if (!f.empty())
{
xmp.parse(std::string_view(std::bit_cast<const char*>(f.data()), f.size()));
parse_xmp(xmp, pd);
}
}
catch (const std::exception& e)
{
record_xmp_error(__FUNCTION__, e.what());
}
}
df::file_path probe_xmp_path(const df::file_path src_path, const std::string_view xmp_name)
{
if (!xmp_name.empty())
{
return src_path.folder().combine_file(xmp_name);
}
return src_path.extension(".xmp");
}
static std::optional<libfiles::packet_reading> read_file_packet(df::file_path path);
// GPano writes these as plain integers. A property the file omits leaves its member zero, which
// prop::panorama_geometry reads as an incomplete declaration and resolves against the pixels.
static void read_panorama_geometry(const libfiles::xmp::meta& xmp, prop::panorama_geometry& g)
{
const auto read = [&xmp](const char* const name, int& out)
{
std::int32_t value = 0;
if (xmp.get_property_int(ns_gpano, name, &value)) out = value;
};
read("FullPanoWidthPixels", g.full_width);
read("FullPanoHeightPixels", g.full_height);
read("CroppedAreaLeftPixels", g.cropped_left);
read("CroppedAreaTopPixels", g.cropped_top);
read("CroppedAreaImageWidthPixels", g.cropped_width);
read("CroppedAreaImageHeightPixels", g.cropped_height);
}
prop::panorama_geometry metadata_xmp::panorama(const df::file_path path)
{
prop::panorama_geometry result;
try
{
const auto* const ft = files::file_type_from_name(path);
if (ft->has_trait(file_traits::embedded_xmp))
{
libfiles::xmp::meta xmp;
if (const auto packet = read_file_packet(path))
{
if (!packet->packet.empty()) xmp.parse(packet->packet);
}
else
{
// HEIF and JPEG XL are read-only here. The scan also supplies Brotli for compressed
// JPEG XL boxes, just as read_embedded_source does when converting either format.
files ff;
const auto scanned = ff.scan_file(path, false, ft);
if (!scanned.success) record_xmp_error(__FUNCTION__, "the panorama metadata could not be read");
if (!scanned.metadata.xmp.empty()) xmp.parse(packet_text(scanned.metadata.xmp));
}
read_panorama_geometry(xmp, result);
if (result.is_valid()) return result;
}
// A stitcher that wrote a sidecar rather than an embedded packet still declared the sphere. The
// embedded reading is discarded first: read_panorama_geometry fills only what a packet declares,
// so joining an incomplete embedded declaration to the sidecar's would describe neither file.
result = {};
const auto sidecar = blob_from_file(probe_xmp_path(path, {}));
if (!sidecar.empty())
{
libfiles::xmp::meta xmp;
xmp.parse(std::string_view(std::bit_cast<const char*>(sidecar.data()), sidecar.size()));
read_panorama_geometry(xmp, result);
}
}
catch (const std::exception& e)
{
record_xmp_error(__FUNCTION__, e.what());
}
return result;
}
// The formats libfiles reads and writes: every one diffractor embeds metadata in.
static libfiles::file_format libfiles_update_format(const df::file_path path)
{
const auto f = open_file(path, platform::file_open_mode::read);
uint8_t head[16] = {};
if (!f || f->read(head, sizeof(head)) != sizeof(head)) return libfiles::file_format::unknown;
return libfiles::detect_file_format(head);
}
// The packet a file holds, where libfiles reads and writes it. Nothing when libfiles does not read the
// format or the file cannot be opened.
static std::optional<libfiles::packet_reading> read_file_packet(const df::file_path path)
{
const auto f = open_file(path, platform::file_open_mode::read);
if (!f) return {};
platform_file_stream stream(f);
libfiles::reader r(stream);
if (r.size() < 16) return {};
uint8_t head[16];
r.read(0, head, sizeof(head));
if (!libfiles::can_update(libfiles::detect_file_format(head))) return {};
return libfiles::read_packet(r);
}
// What the item shows, written into the packet wherever the packet lacks it.
static void seed_from_shown(const prop::item_metadata& shown, libfiles::xmp::meta& xmp)
{
metadata_edits seed;
const auto missing = [&xmp](const std::string_view ns, const std::string_view name)
{
return !xmp.get_property(ns, name);
};
const auto text = [](const str::cached value) -> std::optional<std::string>
{
if (str::is_empty(value)) return {};
return std::string(value.sv());
};
if (missing(xmp_ns::dc, "title")) seed.title = text(shown.title);
if (missing(xmp_ns::dc, "description")) seed.description = text(shown.description);
if (missing(xmp_ns::dc, "rights")) seed.copyright_notice = text(shown.copyright_notice);
if (missing(xmp_ns::dc, "creator")) seed.copyright_creator = text(shown.copyright_creator);
if (missing(xmp_ns::photoshop, "Credit")) seed.copyright_credit = text(shown.copyright_credit);
if (missing(xmp_ns::photoshop, "Source")) seed.copyright_source = text(shown.copyright_source);
if (missing(xmp_ns::photoshop, "City")) seed.location_place = text(shown.location_place);
if (missing(xmp_ns::photoshop, "State")) seed.location_state = text(shown.location_state);
if (missing(xmp_ns::photoshop, "Country")) seed.location_country = text(shown.location_country);
if (missing(xmp_ns::dc, "subject") && !str::is_empty(shown.tags)) seed.add_tags = tag_set(shown.tags);
seed.apply(xmp);