Synchronize.pm

filter: Statementstmt 96.4% 55 / 57 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 19 / 19 Podpod n/a totaltotal 97.3% 74 / 76 CC 1 SCAR 0.2
CC
1
Cov
96%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Synchronize/Timestamp.pm ↑ Summary
1 package Image::Synchronize;
2
3 1 ▶use Modern::Perl;
Subroutine BEGIN: called CC=1 SCAR=0.0
4
5 =head1 NAME
6
7 Image::Synchronize - a module for synchronizing filesystem
8 modification timestamps of images, movies, and related files.
9
10 =head1 SYNOPSIS
11
12 use Image::Synchronize;
13
14 $ims = Image::Synchronize->new(%options);
15 $ims->process(@pathpatterns);
16
17 =head1 DESCRIPTION
18
19 This module is the backend of L<imsync> and was not designed to be
20 used outside of that context.
21
22 =head1 SEE ALSO
23
24 See the documentation of L<imsync> for more details.
25
26 =head1 AUTHOR
27
28 Louis Strous, E<lt>imsync@quae.nl<gt>
29
30 =head1 COPYRIGHT AND LICENSE
31
32 Copyright (C) 2018-2023 by Louis Strous
33
34 This library is free software; you can redistribute it and/or modify
35 it under the same terms as Perl itself, either Perl version 5.26.2 or,
36 at your option, any later version of Perl 5 you may have available.
37
38 =cut
39
40 1 ▶use parent 'Exporter';
Subroutine BEGIN: called CC=1 SCAR=0.0
41 our @EXPORT_OK = qw(normalize_options);
42
43 1 ▶use feature 'state';
Subroutine BEGIN: called CC=1 SCAR=0.0
44
45 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
46 1 ▶use Clone qw(clone);
Subroutine BEGIN: called CC=1 SCAR=0.0
47 1 use File::Copy qw(
48 copy
49 move
50 1 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
51 1 use File::Spec qw(
52 case_tolerant
53 1 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
54 1 ▶use Image::ExifTool 10.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
55 1 ▶use Image::Synchronize::CameraOffsets;
Subroutine BEGIN: called CC=1 SCAR=0.0
56 1 ▶use Image::Synchronize::GpsPositionCollection;
Subroutine BEGIN: called CC=1 SCAR=0.0
57 1 ▶use Image::Synchronize::GroupedInfo;
Subroutine BEGIN: called CC=1 SCAR=0.0
58 1 use Image::Synchronize::Logger qw(
59 default_logger
60 log_error
61 log_message
62 log_warn
63 1 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
64 1 ▶use Image::Synchronize::ProgressBar;
Subroutine BEGIN: called CC=1 SCAR=0.0
65 1 use Path::Class qw(
66 dir
67 file
68 1 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
69 1 ▶use Path::Iterator::Rule;
Subroutine BEGIN: called CC=1 SCAR=0.0
70 1 use POSIX qw(
71 floor
72 1 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
73 1 use Scalar::Util qw(
74 blessed
75 looks_like_number
76 1 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
77 1 ▶use Text::Glob qw(match_glob);
Subroutine BEGIN: called CC=1 SCAR=0.0
78 1 ▶use XML::Twig;
Subroutine BEGIN: called CC=1 SCAR=2.6
79 use YAML::Any qw(
80 Dump
81 DumpFile
82 LoadFile
83 );
84
85 BEGIN {
86 if ($^O eq 'MSWin32'
87 and (!$^V or $^V lt v5.33.5)
88 and eval 'require Win32::UTCFileTime')
89 {
90 import Win32::UTCFileTime;
91 }
92 }
93
94 # always use x.yyy version numbering, so that string comparison and
95 # numeric comparison give the same ordering, to avoid trouble due to
96 # different ways of interpreting version numbers.
97 our $VERSION = '2.011';
98
99 # TODO: check each folder for an .imsync-cameraoffsets.yaml file
100 # TODO: allow timezone specification on --time
101
102 my $CASE_TOLERANT;
103 my $PIRname; # for 'name' or 'iname' as appropriate for
104 # case-sensitiveness of the operating system
105 my $PIRnotname; # likewise for 'not_name' or 'not_iname'
106
107 # capture and log warnings and errors, so they end up in the log file
108 # as well as being printed to standard output
109 BEGIN {
110 $SIG{__WARN__} = sub {
111 log_warn( $_[0] );
112 };
113 $SIG{__DIE__} = sub {
114 log_error( Carp::longmess( $_[0] ) ) unless $^S;
115 };
116 $CASE_TOLERANT = File::Spec->case_tolerant();
117 $PIRname = $CASE_TOLERANT? 'iname': 'name';
118 $PIRnotname = 'not_' . $PIRname;
119 }
120
121 my @gps_location_tags = qw(GPSLatitude GPSLongitude GPSAltitude);
122 my %gps_location_tags = map { $_ => 1 } @gps_location_tags;
123
124 # The ExiftimeVersion is here temporarily. It is associated with a
125 # predecessor of the current application that was not released to the
126 # general public but was extensively used by the author. He wants to
127 # know if he's processing files using the current application that
128 # already contain tags embedded by the predecessor.
129 my @own_xmp_tags = qw(
130 CameraID
131 ImsyncVersion
132 TimeSource
133 ExiftimeVersion
134 );
135
136 my @all_tags;
137 {
138 my %tags = map { $_ => 1 }
139 (
140 'CreateDate',
141 'DateTimeOriginal',
142 'Duration',
143 'FileModifyDate',
144 'GPSAltitude',
145 'GPSAltitudeRef',
146 'GPSDateTime',
147 'GPSLatitude',
148 'GPSLatitudeRef',
149 'GPSLongitude',
150 'GPSLongitudeRef',
151 'ImageWidth',
152 'Make',
153 'MIMEType',
154 'Model',
155 'QuickTime:CreationDate',
156 'QuickTime:AndroidManufacturer',
157 'QuickTime:AndroidModel',
158 'SerialNumber',
159 map { "XMP:$_" } @own_xmp_tags,
160 );
161 @all_tags = sort keys %tags;
162 }
163
164 my %all_tags = map { $_ => 1 } @all_tags;
165
166 my %time_tags;
167
168 # non-UTC time tags
169 $time_tags{$_} = 1 foreach qw(FileModifyDate CreateDate DateTimeOriginal);
170
171 # UTC time tags
172 $time_tags{$_} = 0 foreach qw(GPSDateTime QuickTime:CreationDate);
173
174 =head1 METHODS
175
176 =head2 new
177
178 $ims = Image::Synchronize->new(%options);
179
180 Construct and return a new instance of the class. The following
181 C<%options> keys are recognized:
182
183 =over
184
185 =item logfile
186
187 Specifies the file to write the log messages to (in addition to
188 printing them to standard output). If not set, then I<imsync.log>
189 in the current working directory is used.
190
191 =back
192
193 =cut
194
195 sub new {
196 my ( $class, %options ) = @_;
197
198 my $self = bless {
199 backend => Image::ExifTool->new,
200 gps_offsets => Image::Synchronize::CameraOffsets->new(
201 log_callback => sub { log_message( 16, @_ ) }
202 ),
203 gps_positions => Image::Synchronize::GpsPositionCollection->new,
204 options => \%options,
205 }, $class;
206
207 # write XMP tags without padding.
208 $self->{backend}->Options( Compact => 1, );
209
210 return $self;
211 }
212
213 =head2 process
214
215 $ims->process(@arguments);
216
217 Processes the specified C<@arguments>, of which the elements are
218 interpreted as path name patterns matching files and/or directories.
219
220 Returns C<$ims>.
221
222 =cut
223
224 sub process {
225 my ( $self, @arguments ) = @_;
226 $self->set_working_directory->initialize_logging->report_program_and_options;
227
228 my $done = 0;
229 my $result;
230
231 if ( $self->option('restoreoriginals') ) {
232 $result = $self->restore_original_files(@arguments);
233 $done = 1;
234 }
235
236 if ( $self->option('removebackups') ) {
237 $result = $self->delete_backups(@arguments);
238 $done = 1;
239 }
240
241 my @files;
242 if ( not($done) or $self->option('removeourtags') ) {
243 log_message("Seeking files.\n");
244 @files = resolve_files( { recurse => $self->option('recurse') },
245 Path::Iterator::Rule->new->$PIRnotname('*_original')->file, @arguments );
246 log_message( 'Found ' . scalar(@files) . ' file(s).' . "\n" );
247
248 $self->process_follow(@files) # must happen before the first
249 # file-specific message gets printed
250 ->initialize_own_xmp_namespace; # must happen before using any
251 # Image::Exiftool functionality
252
253 if ( $self->option('removeourtags') ) {
254 $result = $self->remove_our_tags(@files);
255 $done = 1;
256 }
257 }
258
259 if ( not $done ) {
260 $self->inspect_files(@files);
261
262 # must happen before determining new values
263
264 $self->import_camera_offsets->process_user_camera_ids->process_user_times
265 ->process_user_locations->process_summer_wintertime->read_gpx_tracks;
266
267 $self->determine_new_values_for_all_files->modify_files->report->exportgpx(
268 $self->option('exportgpx') );
269
270 $self->export_camera_offsets if $self->option('modify');
271 }
272
273 log_message( "\nResults logged to file '"
274 . file( $self->{logfile} )->absolute
275 . "'.\n" );
276
277 # clean up the logging to file
278 default_logger()->clear_printer('file');
279 close $self->{logfh};
280
281 if ( ( $self->option('removebackups') and $self->option('clearlog') )
282 or $self->option('unsafe') )
283 {
284 print "Removing logfile.\n";
285 unlink( $self->{logfile} );
286 }
287
288 return 0;
289 }
290
291 # below here, specify subs in alphabetical order
292
293 # output a key-value pair only if the value is defined.
294 sub add_maybe {
295 if ( @_ == 2 ) {
296 my ( $key, $value ) = @_;
297 return ( $key => $value ) if defined $value;
298 }
299 elsif ( @_ == 1 ) {
300 my ($key) = @_;
301 return defined($key) ? $key : ();
302 }
303 return ();
304 }
305
306 # ($quotient, $remainder) = split_number($value, $divisor);
307 # $quotient = split_number($value, $divisor);
308 #
309 # Divides two numbers and returns their quotient and (in list mode)
310 # non-negative remainder.
311 sub split_number {
312 my ($value, $period) = @_;
313 $period = abs($period);
314 my $q = sprintf('%d', $value/$period)*$period;
315 my $r = $value - $q;
316 if ($r < 0) {
317 $r += $period;
318 $q -= $period;;
319 } elsif ($r >= $period) {
320 $r -= $period;
321 $q += $period;
322 }
323 return wantarray? ($q, $r): $q;
324 }
325
326 # $corrected_time = apply_camera_offset($time, $offset);
327 #
328 # Applies camera offset C<$offset> (in seconds) to a clone of
329 # C<$time>, which must be a Synchronize::Timestamp. Returns the
330 # clone.
331 sub apply_camera_offset {
332 my ( $t, $offset ) = @_;
333 $t = $t->clone; # don't modify object that argument refers to
334
335 # In v2.0.0, we processed as follows:
336 # - remove the timezone (if any) from $t
337 # - set the timezone offset of $t to $offset, which was a plain number
338 # - move $t to the local timezone
339
340 if (Image::Synchronize::Timestamp->istypeof($offset)) {
341 # the timezone offset has a time part and perhaps a timezone part
342 $offset = $offset->clone; # don't modify object that argument
343 # refers to
344 } else {
345 # deprecated: offset is a number; support for backward
346 # compatibility
347 $t->set_timezone_offset($offset)
348 ->adjust_to_local_timezone;
349 }
350
351 # If $offset has no timezone offset, then split its time part into
352 # two parts: (1) the whole number of hours nearest its value, which
353 # becomes the timezone part of $offset; (2) the remainder, which
354 # becomes the new time part of $offset.
355 #
356 # For example, if $offset is +02:11:03 then it gets changed to
357 # +0:11:03+02:00.
358 if (not $offset->has_timezone_offset) {
359 my ($q, $r) = split_number($offset->time_local, 3600);
360 if ($r >= 1800) { # the offset is nearer the next higher hour than
361 # the current hour
362 $r -= 3600;
363 $q += 3600;
364 }
365 $offset = Image::Synchronize::Timestamp
366 ->new($r)
367 ->adjust_timezone_offset($q)
368 ->adjust_nodate;
369 }
370
371 # Add the time part of $offset to $t and then adjust the timezone
372 # of $t to the timezone of $offset. For example, if $t is
373 # 12:40:00+02:00 and $offset is +00:05+03:00, then the result is
374 # 13:45:00+03:00.
375 $t += $offset->time_local;
376 $t->adjust_timezone_offset($offset->timezone_offset);
377
378 return $t;
379 }
380
381 # $backend = $ims->backend;
382 #
383 # Returns the L<Image::ExifTool> backend that is used to interact with
384 # the image files.
385 sub backend {
386 my ($self) = @_;
387 return $self->{backend};
388 }
389
390 # $base_camera_id = base_camera_id($camera_id)
391 #
392 # Returns the camera ID without the "always UTC" suffix "|U", if any.
393 sub base_camera_id {
394 my ($camera_id) = @_;
395
396 # Camera IDs that we construct are like Make|Model|SerialNumber or,
397 # if the file's CreateDate is always in UTC,
398 # Make|Model|SerialNumber|U. However, camera IDs that the user
399 # supplies through --cameraid can have any format, and perhaps we
400 # appended the "|U" suffix.
401 return $1 if defined($camera_id) and $camera_id =~ /^(.*?)\|U$/;
402 return $camera_id;
403 }
404
405 # $pattern = basename_pattern($path);
406 #
407 # Returns text identifying the structure of the base name of the
408 # C<$path>, suitable for use as a camera ID if no explicit camera ID is
409 # known for the file.
410 #
411 # The returned text consists of the base name of the C<$path>, omitting
412 # the last period and any following text, and replacing any sequence of
413 # digits with the length of that sequence.
414 sub basename_pattern {
415 my ($path) = @_;
416 my $name = file($path)->basename;
417 $name =~ s/\.[^.]+$//; # remove file extension
418 $name =~ s/(\d+)/length($1)/eg;
419 return $name;
420 }
421
422 my %camera_id_tags
423 = (
424 Make => [qw(Make QuickTime:AndroidManufacturer)],
425 Model => [qw(Model QuickTime:AndroidModel)],
426 SerialNumber => [qw(SerialNumber)],
427 );
428
429 # $camera_id = camera_id($info);
430 #
431 # returns the ID of the camera, based on information extracted from an
432 # image file through Image::ExifTool::ImageInfo. For some but not all
433 # types of camera, the camera ID includes a serial number that is
434 # unique to the camera.
435 sub camera_id {
436 my ( $info ) = @_;
437 my @values;
438 foreach my $maintag (qw(Make Model SerialNumber)) {
439 my $value;
440 foreach my $tagtry (@{$camera_id_tags{$maintag}}) {
441 my $v = $info->get(split /:/, $tagtry);
442 if (defined $v) {
443 $value = $v;
444 last;
445 }
446 }
447 push @values, $value // '';
448 }
449 my $id = join( '|', @values );
450 if ($id =~ /^\|+$/) {
451 $id = undef;
452 } elsif ($info->get('supposedly_utc')) {
453 $id .= '|U';
454 }
455 return $id;
456 }
457
458 # $camera_id = $ims->camera_id_from_fallback($fallback_camera_id);
459 #
460 # Returns the regular camera ID of a camera that has a fallback camera
461 # ID equal to C<$fallback_camera_id>, or C<$fallback_camera_id> if
462 # there is no such camera.
463 sub camera_id_from_fallback {
464 my ( $self, $fallback_camera_id ) = @_;
465 my $r = $self->{fallback_to_camera_id}->{$fallback_camera_id};
466 if ( defined $r ) {
467 my @candidates =
468 sort { ( $r->{$b} <=> $r->{$a} ) or ( $a cmp $b ) } keys %{$r};
469 return $candidates[0];
470 } else {
471 return $fallback_camera_id;
472 }
473 }
474
475 # $camera_offsets_path = $ims->camera_offsets_path
476 #
477 # Returns the camera offsets path, which is taken from the
478 # C<offsetspath> option if defined. If C<offsetspath> is not defined,
479 # then uses C<'.imsync-cameraoffsets.yaml'> if that file exists in the
480 # current working directory or if the C<HOME> environment variable
481 # isn't set, and otherwise uses that file name in the directory
482 # defined by the C<HOME> environment variable.
483 sub camera_offsets_path {
484 my ( $self ) = @_;
485 my $path = $self->option('offsetspath');
486 if ( not defined $path ) {
487 $path = '.imsync-cameraoffsets.yaml';
488 if ( not(-e $path) and exists $ENV{HOME}) {
489 $path = file( $ENV{HOME}, $path );
490 }
491 }
492 return $path;
493 }
494
495 # $ims->cleanup_progressbar($progressbar);
496 #
497 # Cleans up and removes the specified $progressbar.
498 sub cleanup_progressbar {
499 my ( $self, $progressbar ) = @_;
500 $progressbar->done;
501
502 # Restore the original logger for logging to the screen, now that
503 # the progress bar has disappeared.
504 default_logger()->set_printer(
505 {
506 bitflags => ( $self->option('verbose') // 1 ),
507 action => sub { print @_; }
508 }
509 );
510 return $self;
511 }
512
513 # $prefix = common_prefix($separator, @values);
514 #
515 # Determines the common prefix of a collection of text values. The
516 # returned common prefix ends with the specified separator, unless the
517 # common prefix is empty (or the separator is empty).
518 #
519 # For example, if (':', 'foo:bar:fie', 'foo:bar:zoo') are passed as
520 # arguments, then 'foo:bar:' is returned.
521 sub common_prefix {
522 my ( $separator, @values ) = @_;
523 return '' unless @values;
524 my $value = shift @values;
525 my @prefix = split /($separator)/, $value;
526 my $shorter;
527 foreach $value (@values) {
528 my @next = split /($separator)/, $value;
529 for my $i ( 0 .. $#prefix ) {
530 if ( not( defined( $next[$i] ) ) or $next[$i] ne $prefix[$i] ) {
531 @prefix = @prefix[ 0 .. $i - 1 ];
532 $shorter = 1;
533 last;
534 }
535 }
536 }
537 pop @prefix if not($shorter) and $separator;
538 return '' unless @prefix;
539 my $result = join( '', @prefix );
540 return $result;
541 }
542
543 # $prefix = common_prefix_path(@paths);
544 #
545 # Determines the common prefix of a collection of file paths. The
546 # returned common prefix ends with a path name separator, unless the
547 # common prefix is empty. The returned path is in Unix style, with
548 # forward slashes as path separators.
549 #
550 # For example, if 'foo/bar/fie' and 'foo/bar/zoo' are passed as
551 # arguments, then 'foo/bar/' is returned.
552 sub common_prefix_path {
553 my @args = map { file($_)->as_foreign('Unix')->stringify } @_;
554 return common_prefix( '/', @_ );
555 }
556
557 # This is a callback function
558 sub convert_to_xmp {
559 my ( $tag, $in, $out ) = @_;
560 $out->{ 'XMP:' . $tag } = $in;
561 }
562
563 # $offset = deduce_camera_offset($camera_time, $target_time);
564 #
565 # deduce the camera offset from the C<$camera_time> and the
566 # C<$target_time>. The $target_time must have a timezone offset. The
567 # $camera_time may or may not have a timezone offset.
568 #
569 # The deduced camera offset has a time part and a timezone part. The
570 # time part says how much to add to the instant expressed by the
571 # camera time to get the instant expressed by the target time (if both
572 # are converted to the same timezone). The timezone part says how
573 # much to add to UTC to get the nominal timezone offset of the camera.
574 # The nominal timezone is the timezone that the camera's clock was
575 # intended to follow. The time part of the offset says how much the
576 # "true" camera timezone differed from the nominal one, perhaps due to
577 # misconfiguration or clock drift.
578 #
579 # If the camera time is 2020-07-30T08:22:30+02:00 and the target time
580 # is 2020-07-30T09:23:05+03:00 then the deduced camera offset is
581 # +00:00:35+02:00.
582 #
583 # TODO: what timezone should we assume for the target time if it has
584 # none, to get backward compatibility with versions of imsync
585 # predating the introduction of the timezone part of the camera
586 # offset?
587 #
588 # In the past the camera offset did not have a timezone part yet.
589 # Then the camera offset was added to the camera time (which was
590 # assumed to have no timezone offset) and the resulting timestamp was
591 # assumed to be given relative to the system's timezone for that
592 # instant.
593 #
594 # If the camera time was 2020-07-30T08:22:30 and the target time was
595 # 2020-07-30T09:23:05+03:00 (with the system's timezone offset
596 # UTC+03:00) then the deduced camera offset was +01:00:35.
597 sub deduce_camera_offset {
598 my ( $camera_time, $target_time ) = @_;
599
600 croak "Target time must have a timezone offset\n"
601 unless $target_time->has_timezone_offset;
602
603 my $d = Image::Synchronize::Timestamp->new($target_time - $camera_time)
604 ->adjust_nodate;
605
606 $d->adjust_timezone_offset($target_time->timezone_offset);
607 return $d;
608 }
609
610 # $ims->delete_backups(@file_patterns);
611 #
612 # Deletes any backup files matching the C<@file_patterns>. Backup
613 # files have a name that ends in '_original'.
614 sub delete_backups {
615 my ( $self, @arguments ) = @_;
616 my @files = resolve_files( { recurse => $self->option('recurse') },
617 Path::Iterator::Rule->new->$PIRname('*_original')->file, @arguments );
618
619 log_message( "Removing " . scalar(@files) . " backup file(s).\n" );
620 my $progressbar;
621 if ( scalar(@files) ) {
622 $progressbar = $self->setup_progressbar( scalar(@files), 'delete' );
623 foreach my $file (@files) {
624 unlink($file);
625 $progressbar->add;
626 }
627 $self->cleanup_progressbar($progressbar);
628 }
629 log_message("Done removing backup file(s).\n");
630 $self;
631 }
632
633 # @best_scorers = best_scorers(sub { ... }, @targets)
634 #
635 # Return the best-scoring items. The code reference, when called for
636 # a target, should return a numerical score. The highest score among
637 # the @targets is determined, and all elements of @targets that have
638 # that highest score are returned.
639 sub best_scorers {
640 my ($code, @targets) = @_;
641 my %score = map { $code->($_) } @targets;
642 my @order = sort { $score{$b} <=> $score{$a} } @targets;
643 my $bestscore = $score{ $order[0] };
644 return grep { $score{$_} == $bestscore } keys %score;
645 }
646
647 sub potential_donors {
648 my ($self, $file, $info) = @_;
649 my $number = $info->get('image_number');
650 my @targets;
651 if ( defined($number)
652 && defined( $self->{files_for_image_numbers}->{$number} ) ) {
653 my $target;
654 @targets = grep { $_ ne $file }
655 @{ $self->{files_for_image_numbers}->{$number} };
656 if (@targets > 1) {
657 # multiple files with the same number. Arrange them in
658 # descending order of priority; metadata that is missing from
659 # the current file will be copied from the first target file
660 # that has it.
661
662 # descending priority order:
663 # 1. current file name with '.yaml' appended
664 # 2. greatest directory prefix in common with current file
665 # 3. metadata file
666 # 4. greatest basename pattern prefix in common with current file
667 # 5. lexicographic order
668 my $t1 = "${file}.yaml";
669 my $t3 = basename_pattern($file);
670 @targets = map { $_->[0] }
671 sort {
672 $b->[1] <=> $a->[1] # with .yaml suffix
673 or $b->[2] <=> $a->[2] # common directory prefix
674 or $b->[3] <=> $a->[3] # metadata file
675 or $b->[4] <=> $a->[4] # common base name pattern
676 or $a->[0] cmp $b->[0] # fallback: lexicographic order
677 }
678 map { [
679 $_,
680 ($_ eq $t1)? 1: 0,
681 length_of_common_directory_prefix($_, $file),
682 ($self->{original_info}->{$_}->get('is_metadata') // 0),
683 length_of_common_prefix(basename_pattern($_), $t3)
684 ] } @targets;
685 }
686 }
687 return @targets;
688 }
689
690 # $ims->determine_new_values_for_all_files;
691 #
692 # Determines the proposed final values (target timestamp, location, and
693 # so on) for the files, as far as possible.
694 #
695 # Returns C<$ims>.
696 sub determine_new_values_for_all_files {
697 my ($self) = @_;
698
699 my @files = sort keys %{ $self->{original_info} };
700
701 my $progressbar = $self->setup_progressbar( scalar(@files), 'Determine' );
702
703 # Process the files
704 my @files_handle_by_number;
705 my $count_modified = 0;
706 my %count_needs_force;
707 foreach my $file (@files) {
708 my $info = $self->{original_info}->{$file};
709
710 if ( $self->has_useful_timestamp($file, $info) ) {
711
712 # remember which files with embedded timestamps have which image
713 # number
714 push @{ $self->{files_for_image_numbers}->{ $info->get('image_number') } }, $file
715 if defined $info->get('image_number');
716
717 my @potential_donors = $self->potential_donors($file, $info);
718 my $modification_type = $self->determine_new_values_for_file($file, \@potential_donors);
719
720 ++$count_modified if $modification_type == 1;
721
722 my $extra_info = $self->{extra_info}->{$file};
723 if (defined($extra_info)) {
724 my $f = $extra_info->get('min_force_for_change');
725 ++$count_needs_force{$f} if $f;
726 }
727 }
728 elsif ( defined $info->get('image_number') ) {
729
730 # mark but otherwise skip files that aren't image or movie files
731 # but that have a potential image number; we can hopefully copy
732 # the target time from another image or movie file with the same
733 # number later, so we must make sure to process those
734 push @files_handle_by_number, $file;
735 next;
736 }
737 else {
738 log_message(
739 8,
740 { name => $file },
741 sub {
742 <<EOD; } );
743
744 Processing '$file'.
745 No relevant embedded timestamps or image number found -- skipped.
746 EOD
747 }
748 $progressbar->add;
749 }
750
751 # now process files with a file number but no embedded timestamp;
752 # maybe we can copy the target timestamp from a file processed
753 # earlier that has the same image number
754 foreach my $file (@files_handle_by_number) {
755 my $info = $self->{original_info}->{$file};
756 my $number = $info->get('image_number');
757 if ( defined( $self->{files_for_image_numbers}->{$number} ) ) {
758 my @potential_donors = $self->potential_donors($file, $info);
759 $count_modified +=
760 ($self->determine_new_values_for_file( $file, \@potential_donors ) == 1);
761 my $extra_info = $self->{extra_info}->{$file};
762 if (defined($extra_info)) {
763 my $f = $extra_info->get('min_force_for_change');
764 ++$count_needs_force{$f} if $f;
765 }
766 }
767 else {
768 log_message(
769 8,
770 { name => $file },
771 sub {
772 <<EOD; } );
773
774 Processing '$file'.
775 No file from which to copy a target timestamp -- skipped.
776 EOD
777 }
778
779 $progressbar->add;
780 }
781
782 $self->cleanup_progressbar($progressbar);
783
784 log_message("$count_modified file(s) need modification.\n");
785 log_message($count_needs_force{1} . " file(s) need --force for modification.\n")
786 if $count_needs_force{1} && $self->option('force', 0) < 1;
787 log_message($count_needs_force{2} . " file(s) need --force --force for modification.\n")
788 if $count_needs_force{2} && $self->option('force', 0) < 2;
789 return $self;
790 }
791
792 sub get_from_targets {
793 my ($self, $tag, $target_files) = @_;
794 foreach my $tf (@{$target_files}) {
795 my $v = $self->{new_info}->{$tf}->get($tag);
796 if (defined $v) {
797 return wantarray? ($v, $tf): $v;
798 }
799 }
800 return;
801 }
802
803 # Compares $info and $new_info (which must be of type
804 # Image::Synchronize::GroupedInfo) to determine which tags need to be
805 # changed.
806 #
807 # $messages, if defined, is a reference to an array to which relevant
808 # progress messages are appended.
809 #
810 # $changes, if defined, is a reference to a hash to which key-value
811 # pairs are added in which the keys are the tags for which a change is
812 # needed and the values are the amount of force that is needed for the
813 # change.
814 #
815 # Returns 0 if no changes are needed. If changes are needed, then
816 # returns 1 plus the minimum amount of force that is needed for any of
817 # the changes.
818 sub get_changes {
819 my ($self, $file, $info, $new_info, $extra_info, $messages, $changes) = @_;
820
821 $messages //= [];
822 $changes //= {};
823
824 my $can_change = is_image_or_movie($info);
825
826 # In general, the file needs modification if FileModifyDate has
827 # changed or if the GPS location and timestamp are newly added
828 # or if the GPS location or timestamp have changed and
829 # TimeSource was set but not equal to 'GPS'.
830 #
831 # If the user specified --force or --force 1, then the file also
832 # needs modification if CameraID, DateTimeOriginal, or
833 # TimeSource have changed or are newly added.
834 #
835 # If the user specified --force 2, then the file also needs
836 # modification if the GPS location or timestamp have changed and
837 # TimeSource was not set or was equal to 'GPS'.
838
839 my $gps_location_tags_count;
840 my $min_force_for_change = 99;
841 if ($can_change) {
842 # not a metadata file
843 foreach my $tag (
844 qw(
845 CameraID
846 DateTimeOriginal
847 ImsyncVersion
848 FileModifyDate
849 GPSAltitude
850 GPSLatitude
851 GPSLongitude
852 TimeSource
853 )
854 ) {
855 my $new = $new_info->get($tag);
856 my $old = $info->get($tag);
857 my $change = 1;
858
859 if ( (defined($gps_location_tags{$tag}))
860 and (defined($old) or defined($new)) ) {
861 ++$gps_location_tags_count;
862 next; # handle these separately
863 }
864
865 if ( defined $old ) {
866 if ( defined $new ) {
867 if ( $new ne $old ) {
868 push @{$messages}, " $tag has changed.";
869 } else {
870 $change = 0;
871 }
872 } else { # old but not new
873 push @{$messages}, " $tag has disappeared,";
874 }
875 } elsif ( defined $new ) { # new but not old
876 push @{$messages}, " $tag is new.";
877 } else { # neither new nor old
878 $change = 0;
879 }
880 if ($change) {
881 state $force_1_tags = {
882 map { $_ => 1 }
883 qw(
884 CameraID
885 DateTimeOriginal
886 ImsyncVersion
887 TimeSource
888 )
889 };
890 if ( $tag eq 'FileModifyDate' ) {
891 $min_force_for_change = 0
892 if $min_force_for_change > 0;
893 $changes->{$tag} = 0;
894 } elsif ( exists $force_1_tags->{$tag} ) {
895 $min_force_for_change = 1
896 if $min_force_for_change > 1;
897 $changes->{$tag} = 1;
898 }
899 }
900 }
901 } else {
902 # a non-image file; cannot change any embedded tags, only file
903 # modification timestamp
904 my $tag = 'FileModifyDate';
905 my $new = $new_info->get($tag);
906 my $old = $info->get($tag);
907 my $change = 1;
908
909 if ( defined $old ) {
910 if ( defined $new ) {
911 if ( $new ne $old ) {
912 push @{$messages}, " $tag has changed.";
913 } else {
914 $change = 0;
915 }
916 } else { # old but not new
917 push @{$messages}, " $tag has disappeared,";
918 }
919 } elsif ( defined $new ) { # new but not old
920 push @{$messages}, " $tag is new.";
921 } else { # neither new nor old
922 $change = 0;
923 }
924 if ($change) {
925 $min_force_for_change = 0
926 if $min_force_for_change > 0;
927 $changes->{$tag} = 0;
928 }
929 }
930
931 if ($gps_location_tags_count) {
932 # Some cameras, for example the LG-H870, can record a GPS altitude
933 # by itself, without a GPS latitude and longitude, when the camera
934 # doesn't know its location. We treat those cases as if the GPS
935 # altitude wasn't there, but if the file gets modified anyway and
936 # get no new GPS position then we remove the troublesome and
937 # to us useless GPS altitude.
938 my $change = 1;
939 my $old_pos_count = 0;
940 my @old_pos = map {
941 my $v = $info->get($_);
942 ++$old_pos_count
943 if defined $v
944 and $_ ne 'GPSAltitude';
945 $v
946 } @gps_location_tags;
947 my $new_pos_count = 0;
948 my @new_pos = map {
949 my $v = $new_info->get($_);
950 ++$new_pos_count
951 if defined $v
952 and $_ ne 'GPSAltitude';
953 $v
954 } @gps_location_tags;
955 my $distance = geo_distance( \@old_pos, \@new_pos );
956 if ( defined $distance ) { # the GPS location was complete in old
957 # and new
958
959 # The precision of the updated or new coordinates as written in
960 # the image file may differ from the precision provided by the
961 # source of the coordinates. Then later runs of this
962 # application with the same inputs and configuration may report
963 # a non-zero distance. To avoid this problem we ignore
964 # distances less than 1 cm.
965 if ( $distance >= 0.01 ) {
966 my ( $value, $prefix ) = si_prefix($distance);
967 push @{$messages}, " GPS position has changed by $value ${prefix}m.";
968 $extra_info->set( 'position_change', $distance );
969 if ( $distance > ( $self->{max_gps_distance} // 0 ) ) {
970 $self->{max_gps_distance} = $distance;
971 $self->{max_gps_file} = $file;
972 }
973 }
974 else {
975 $change = 0;
976 }
977 }
978 elsif ( $old_pos_count == 2 ) {
979 push @{$messages}, " GPS position has disappeared,";
980 $new_info->delete($_) foreach ( @gps_location_tags, 'GPSDateTime' );
981 }
982 elsif ( $new_pos_count ) {
983 push @{$messages}, " GPS position is new.";
984 } elsif ($old_pos_count == 0) {
985 # no old location and no new location and yet we got here. Must
986 # be the case where the file contains a solitary GPS altitude.
987 push @{$messages}, ' Solitary GPS altitude.';
988 $new_info->delete('GPSAltitude');
989 } else {
990 push @{$messages}, ' GPS position is incomplete.';
991 $new_info->delete($_) foreach ( @gps_location_tags, 'GPSDateTime' );
992 }
993 if ($change) {
994
995 # if the GPS position already existed and the TimeSource is
996 # absent or equal to GPS, then we assume the GPS information was
997 # embedded by a GPS device and should only be modified if the
998 # --force level is at least 2. Otherwise we assume that the old
999 # GPS position (if any) was added by us in an earlier run; then
1000 # we can already modify it even if no --force is specified.
1001 if ( ( $info->get('TimeSource') // 'GPS' ) eq 'GPS' )
1002 {
1003 $min_force_for_change = 2
1004 if $min_force_for_change > 2;
1005 foreach my $tag (@gps_location_tags, 'GPSDateTime') {
1006 $changes->{$tag} = 2
1007 if stringify($info->get($tag)) ne stringify($new_info->get($tag));
1008 }
1009 }
1010 else {
1011 $min_force_for_change = 0
1012 if $min_force_for_change > 0;
1013 foreach my $tag (@gps_location_tags, 'GPSDateTime') {
1014 $changes->{$tag} = 0
1015 if stringify($info->get($tag)) ne stringify($new_info->get($tag));
1016 }
1017 }
1018 }
1019 }
1020
1021 push @{$messages}, $new_info->stringify(' ');
1022
1023 if (scalar(keys %{$changes}) == 1
1024 and exists $changes->{ImsyncVersion}
1025 and defined $info->get('ImsyncVersion')) {
1026 # The only thing that changed is the ImsyncVersion value: the file
1027 # already has that tag but the current version of imsync is newer
1028 # than the one that modified the file last. This is not a good
1029 # reason to change the file, so we suppress that change.
1030 %{$changes} = ();
1031 $min_force_for_change = 99;
1032 $new_info->set('ImsyncVersion', $info->get('ImsyncVersion'));
1033 push @{$messages}, ' Only ImsyncVersion has changed -- suppressing.';
1034 }
1035
1036 $extra_info->set( 'min_force_for_change', $min_force_for_change );
1037
1038 my $result = 0;
1039 if ( $min_force_for_change < 99 ) { # some changes
1040 if ( ( $extra_info->get('explicit_change') // 0 ) > 0
1041 or $self->option( 'force', 0 ) >= $min_force_for_change )
1042 {
1043 $extra_info->set( 'needs_modification', 1 );
1044 push @{$messages}, ' Modification of this file is indicated.';
1045 $extra_info->set( 'changes', [ sort keys %{$changes} ] )
1046 if keys %{$changes};
1047 $result = 1;
1048 }
1049 else {
1050 push @{$messages}, ' Modification of this file is suppressed, needs --force'
1051 . ( $min_force_for_change > 1 ? ' --force' : '' ) . '.';
1052 $result = $min_force_for_change + 1;
1053 }
1054 }
1055 else {
1056 push @{$messages}, ' No changes.';
1057 }
1058
1059 return $result;
1060 }
1061
1062 # returns 0 if the file needs no modification, 1 if the file needs
1063 # modification (for the current level of force), or 1 + minimum needed
1064 # force if the file needs more force if it is to be modified.
1065 sub determine_new_values_for_file {
1066 my ( $self, $file, $donator_files ) = @_;
1067
1068 # The user may have chosen to get progress messages printed only
1069 # when the file needs modification, but we can't tell yet if that is
1070 # the case. Save up the messages until we can tell if we need them.
1071 my @messages;
1072 push @messages, "\nProcessing '$file'";
1073
1074 my $info = $self->{original_info}->{$file};
1075 my $new_info = $self->{new_info}->{$file} =
1076 new Image::Synchronize::GroupedInfo;
1077 my $extra_info = $self->{extra_info}->{$file} =
1078 new Image::Synchronize::GroupedInfo;
1079
1080 # copy preferred tags to final list
1081 my @tagstoget = qw(
1082 CameraID
1083 CreateDate
1084 DateTimeOriginal
1085 FileModifyDate
1086 GPSAltitude
1087 GPSDateTime
1088 GPSLatitude
1089 GPSLongitude
1090 TimeSource
1091 );
1092
1093 foreach my $tag (@tagstoget)
1094 {
1095 my $v = $info->get($tag);
1096 if (blessed $v) {
1097 # create a clone; we don't want to accidentally adjust the $info
1098 # member by adjusting the $new_info member
1099 $v = clone($v);
1100 }
1101 $new_info->set( $tag, $v ) if defined $v;
1102 }
1103
1104 # TODO: only report donators when sufficiently verbose
1105 if (defined($donator_files) and @{$donator_files})
1106 {
1107 push @messages, " Possible donators in order of descending priority:";
1108 push @messages, " $_" foreach @{$donator_files};
1109 }
1110
1111 # for files that aren't image or movie files, we suppress changes of
1112 # any tags except FileModifyDate.
1113 my $can_change = is_image_or_movie($info);
1114
1115 # For image and movie files, if there is at least one donator file
1116 # and if the first of them is a metadata file then we prefer the
1117 # metadata from the donator file.
1118 if ($can_change
1119 and defined($donator_files)
1120 and @{$donator_files}) {
1121 my $first_donator_info = $self->{original_info}->{$donator_files->[0]};
1122 if ($first_donator_info->get('is_metadata')) {
1123 foreach my $tag (@tagstoget) {
1124 my $v = $first_donator_info->get($tag);
1125 if (blessed $v) {
1126 # create a clone; we don't want to accidentally adjust the $info
1127 # member by adjusting the $new_info member
1128 $v = clone($v);
1129 }
1130 my $current = $new_info->get($tag);
1131 if (defined $current
1132 and (not(defined $v)
1133 or $v ne $current)) {
1134 $new_info->set( $tag, $v );
1135 }
1136 }
1137 }
1138 }
1139
1140 # determine final camera ID.
1141
1142 # user-specified camera ID?
1143 my $camera_id = $self->user_camera_id($file);
1144 if ( defined $camera_id ) {
1145 push @messages, ' Camera ID set by user (--cameraid).';
1146 $extra_info->set( 'explicit_change', 1 ) if $can_change;
1147 } else {
1148 $camera_id = $info->get('camera_id');
1149
1150 if ( not( defined $camera_id ) ) {
1151 ($camera_id, my $donator) =
1152 $self->get_from_targets('CameraID', $donator_files);
1153 if ( defined($camera_id) ) {
1154 push @messages, " Camera ID copied from '$donator'.";
1155 } else {
1156 my $fallback_camera_id = $info->get('fallback_camera_id')
1157 // fallback_camera_id($file);
1158 $camera_id = $self->camera_id_from_fallback($fallback_camera_id);
1159 if ( defined $camera_id ) {
1160 push @messages, ' Got camera ID via fallback.';
1161 }
1162 }
1163 }
1164 }
1165 $new_info->set( 'CameraID', $camera_id );
1166
1167 # get creation timestamp if available
1168
1169 my $timesource; # value for TimeSource tag
1170 my $timesource_letter; # letter to identify time source in report
1171
1172 my $create_time = $new_info->get('CreateDate');
1173 if (defined $create_time) {
1174 if (not $create_time->has_timezone_offset
1175 and $info->get('supposedly_utc')) {
1176 $create_time->set_timezone_offset(0); # assume UTC
1177 }
1178 } else {
1179 ($create_time, my $donator) =
1180 $self->get_from_targets('CreateDate', $donator_files);
1181 if (defined $create_time) {
1182 push @messages, " Creation timestamp copied from '$donator'.";
1183 $timesource_letter = 'n';
1184 $timesource = 'Other';
1185 }
1186 }
1187
1188 # determine the target time
1189
1190 my $target_time = $self->repository('user_times')->{$file};
1191 if (defined $target_time) {
1192 push @messages, " Target time is set by user.";
1193 $extra_info->set( 'explicit_change', 1 ) if $can_change;
1194 $timesource_letter //= 't'; # source is user's --time
1195 $timesource //= 'User';
1196 } elsif (defined($camera_id) and defined($create_time)) {
1197 # An image file may or may not have a timezone offset specified
1198 # for its CreateDate. How do we handle both kinds of timestamps
1199 # when applying a camera offset?
1200 #
1201 # A CreateDate timestamp is schematically T+Z (e.g.,
1202 # 2020-11-23T14:23+02:00) where T is the timestamp
1203 # (2020-11-23T14:23) and Z is the timezone offset (+02:00), in
1204 # such a way that T − Z = U aims for UTC (2020-11-23T12:23Z) -- if
1205 # a timezone offset is known. If no timezone offset is known,
1206 # then the timestamp is just T.
1207 #
1208 # The camera offset is schematically t+z where t is the timestamp
1209 # part and z is the timezone part, similar to T and Z.
1210 #
1211 # Camera offsets written by versions < 2.001 don't have a timezone
1212 # part z. They get treated as if the specified value were t + z
1213 # where z is the timezone offset that the current system would
1214 # have had on the indicated date in the current location.
1215 #
1216 # The target timestamp is schematically τ+ζ where τ is the
1217 # timestamp part and ζ is the timezone part, similar to T and Z.
1218 # The corresponding UTC time is τ − ζ = υ.
1219 #
1220 # If we don't know Z, then we want the target timestamp to be
1221 # calculated as
1222 #
1223 # τ = T + t
1224 # ζ = z
1225 #
1226 # i.e., t is how much to add to T, and z is the timezone to assume
1227 # for the result.
1228 #
1229 # If we do know Z, then we still want t to indicate how far off
1230 # the CreateDate was, so
1231 #
1232 # υ = U + t ⇔ τ − ζ = T − Z + t ⇔ τ = t + ζ + T − Z
1233 #
1234 # And we still want to end up in timezone z, so
1235 #
1236 # ζ = z
1237 # τ = t + z + T − Z
1238 #
1239 # If we compare the with-Z result with the no-Z result then we see
1240 # that they are equivalent if z = Z, i.e., equivalent to the
1241 # assumption that the CreateDate timezone is equal to the camera
1242 # offset timezone.
1243
1244 my $cto = $self->gps_offsets->get($camera_id, $create_time);
1245 if ( defined $cto) {
1246 push @messages, " Target time is based on camera timezone offsets.";
1247 $timesource_letter //= 's'; # source is CreateDate plus other images
1248 $timesource //= 'Other';
1249
1250 unless ($cto->has_timezone_offset) {
1251 # timezone offset for local system at given instant
1252 my $tz = $cto->local_timezone_offset;
1253 # $cto_before->time_local
1254 # == $cto_after->time_local + $cto_after->timezone_offset
1255 # and $cto_after->timezone_offset = $tz
1256 # so $cto_after->time_local = $cto_before->time_local - $tz
1257 $cto = ($cto - $tz)->set_timezone_offset($tz);
1258 }
1259
1260 $target_time = apply_camera_offset( $create_time, $cto );
1261 }
1262 }
1263 if (not defined $target_time) {
1264 $target_time = $new_info->get('DateTimeOriginal');
1265 if (defined $target_time) {
1266 push @messages,
1267 " Target time is embedded original time (DateTimeOriginal).";
1268 $timesource_letter //= 'o'; # source is DateTimeOriginal
1269 } else {
1270 ($target_time, my $donator) =
1271 $self->get_from_targets('DateTimeOriginal', $donator_files);
1272 if (defined $target_time) {
1273 push @messages, " Target timestamp copied from '$donator' (DateTimeOriginal).";
1274 $timesource_letter //= 'n'; # source is other file
1275 }
1276 }
1277 if (not defined $target_time) {
1278 $target_time = $new_info->get('CreateDate');
1279 if (defined $target_time) {
1280 push @messages, " Target time is embedded creation time (CreateDate).";
1281 $timesource_letter //= 'c'; # source is CreateDate
1282 }
1283 }
1284 }
1285 if (not defined $target_time) {
1286 ($target_time, my $donator) =
1287 $self->get_from_targets('FileModifyDate', $donator_files);
1288 if (defined $target_time) {
1289 push @messages, " Target timestamp copied from '$donator' (FileModifyDate).";
1290 $timesource_letter //= 'n'; # source is other file
1291 }
1292 }
1293
1294 if (defined($target_time)) {
1295 $timesource //= 'Other';
1296
1297 # the timezone part of the camera offset is the target timezone of
1298 # the target time
1299 my $cto = $self->gps_offsets->get($camera_id, $create_time // $target_time);
1300
1301 if (defined $cto) {
1302 unless ($cto->has_timezone_offset) {
1303 # timezone offset for local system at given instant
1304 my $tz = $cto->local_timezone_offset;
1305 # $cto_before->time_local
1306 # == $cto_after->time_local + $cto_after->timezone_offset
1307 # and $cto_after->timezone_offset = $tz
1308 # so $cto_after->time_local = $cto_before->time_local - $tz
1309 $cto = ($cto - $tz)->set_timezone_offset($tz);
1310 }
1311 $target_time->adjust_timezone_offset($cto->timezone_offset);
1312 } else {
1313 $target_time->adjust_to_local_timezone;
1314 }
1315
1316 if ( defined( my $j = $self->repository('jump')->{$file} ) ) {
1317 $target_time += $j * 3600;
1318 push @messages, " Clock time of camera jumped by $j hours.";
1319 }
1320 }
1321
1322 if ($can_change) {
1323 $new_info->set('DateTimeOriginal', $target_time);
1324 $new_info->set( 'TimeSource', $timesource );
1325 }
1326 $extra_info->set( 'timesource_letter', $timesource_letter );
1327
1328 # the File Modification Time may be in a different timezone than the
1329 # target time, because of --relativetime
1330 # TODO: suppress if target time is donated FileModifyDate?
1331 $new_info->set('FileModifyDate', $self->file_from_dto($target_time));
1332
1333 push @messages, " Target time is $target_time.";
1334
1335 # determine the camera offset
1336
1337 if ($timesource_letter ne 'n'
1338 and defined($create_time)
1339 and defined($target_time)
1340 and defined ($camera_id)) {
1341 my $camera_timezone_offset =
1342 deduce_camera_offset( $create_time, $target_time );
1343
1344 push @messages, ' Timezone offset for camera is '
1345 . $camera_timezone_offset->display_time . '.';
1346
1347 # record the offset so it can be used for later files
1348 $self->gps_offsets->set($camera_id, $create_time, $camera_timezone_offset);
1349 }
1350
1351 # determine position
1352
1353 if ( defined($target_time) and $can_change) {
1354 my $position = $self->repository('user_locations')->{$file};
1355 if ( defined $position ) {
1356 $extra_info->set( 'explicit_change', 1 );
1357 } elsif (
1358 not( $info->get('GPSDateTime') ) # none yet
1359 or (
1360 ( $info->get('TimeSource') // 'GPS' ) ne 'GPS' # not original
1361 or $self->option( 'force', 0 ) >= 2 # or force is at least 2
1362 )
1363 ) {
1364 # presumably able to store a GPS position; deduce one if
1365 # possible.
1366 #
1367 # Do we have a target file with GPS information?
1368 (undef, my $donator) = $self->get_from_targets('GPSDateTime', $donator_files);
1369 if (defined $donator) {
1370 my $donator_info = $self->{new_info}->{$donator};
1371 # TODO: store in $positions
1372 # push @messages, " GPS information copied from '$donator'.";
1373 # foreach my $tag (@gps_location_tags, 'GPSDateTime') {
1374 # $new_info->set($tag, $donator_info->get($tag));
1375 # }
1376 }
1377 #
1378 # If the file already had a GPS position, then should we
1379 # update it? If TimeSource was absent or equal to 'GPS', then
1380 # the existing GPS position was embedded in the file when the
1381 # file was created, presumably directly from an attached GPS
1382 # device.
1383 #
1384 # In that case we should be very reluctant to update that
1385 # position, only updating the GPS position if --force has at
1386 # least a value of 2. If --force is less than 2, then we
1387 # should propose to update the TimeSource to 'GPS' if it was
1388 # empty.
1389 #
1390 # If a GPS position and TimeSource were already present but
1391 # TimeSource is not equal to 'GPS', then the GPS position is
1392 # assumed to have been added by an earlier run of an
1393 # application like this one, and then it is OK to update it.
1394 my @gps_positions =
1395 $self->gps_positions->position_for_time( $target_time,
1396 scope => scope_for_file($file) );
1397 if (@gps_positions) {
1398 my $l = length( $gps_positions[0]->{scope} );
1399
1400 # ignore positions from other than the first (longest) scope
1401 @gps_positions = grep { length( $_->{scope} ) == $l } @gps_positions;
1402
1403 if ( @gps_positions > 1 ) {
1404
1405 # sort by track ID
1406 @gps_positions =
1407 sort { $a->{track} cmp $b->{track} } @gps_positions;
1408 @gps_positions = ( $gps_positions[0] );
1409 }
1410 $position = $gps_positions[0]->{position};
1411 }
1412 }
1413 if ( defined $position ) {
1414 if (@{$position}) {
1415 foreach my $ix (0..$#gps_location_tags) {
1416 my $v = $info->get($gps_location_tags[$ix]);
1417 $new_info->set( $gps_location_tags[$ix], $position->[$ix] )
1418 if defined($position->[$ix]) and (not(defined $v) or $position->[$ix] != $v);
1419 }
1420 my $v = $info->get('GPSDateTime');
1421 $new_info->set( 'GPSDateTime', $target_time )
1422 if not(defined $v) or $target_time != $v;
1423 croak "Expected new TimeSource to have been set already\n"
1424 unless defined $new_info->get('TimeSource');
1425 } else { # remove position
1426 foreach my $ix (0..$#gps_location_tags) {
1427 $new_info->delete( $gps_location_tags[$ix] );
1428 }
1429 $new_info->delete( 'GPSDateTime' );
1430 }
1431 }
1432 }
1433
1434 # If the current image is acquiring an embedded GPSDateTime,
1435 # then it is vital that it also ends up with an embedded
1436 # TimeSource, because imsync interprets a GPSDateTime without
1437 # a TimeSource as having been embedded in the image by the
1438 # original recording device (such as a smartphone), for which
1439 # the GPS fix may differ a few seconds from the image recording
1440 # time (with the difference not necessarily being the same from
1441 # one image to the next), which may cause imsync to round the
1442 # camera offset.
1443 #
1444 # However, if the new GPSDateTime is embedded by imsync
1445 # (together with a location), then the camera offset is deemed
1446 # to be exact and must not be rounded. So, such a new
1447 # GPSDateTime must be accompanied by a suitable TimeSource, to
1448 # avoid it being interpreted later as an original GPSDateTime
1449 # for which the camera offset may get rounded, thus differing
1450 # from the previous camera offset and leading to the target time
1451 # being modified again (and erroneously).
1452 #
1453 # A TimeSource may be deduced during the Inspect phase even if
1454 # the image has no embedded TimeSource, so if the final
1455 # TimeSource (deduced during this Determine phase) is equal to
1456 # the TimeSource from the Inspect phase, then the above
1457 # $register call for XMP:TimeSource won't have registered a new
1458 # value for XMP:TimeSource, but if a GPSDateTime is being added
1459 # then we must also have a TimeSource.
1460
1461 if ( $can_change ) {
1462 $new_info->set( 'DateTimeOriginal', $new_info->get('FileModifyDate') )
1463 unless defined $new_info->get('DateTimeOriginal');
1464 $new_info->set( 'ImsyncVersion', $VERSION );
1465
1466 # our XMP tags must go in the XMP namespace
1467 foreach my $tag (@own_xmp_tags) {
1468 my $value = $new_info->get($tag);
1469 if ( defined $value ) {
1470 $new_info->delete($tag); # clear old value (not in a group)
1471 $new_info->set( 'XMP', $tag, $value );
1472 }
1473 }
1474
1475 # We want to store DateTimeOriginal with a timezone, which means
1476 # we must put it in the XMP group, because DateTimeOriginal in the
1477 # default Exif group likely has no room for a timezone.
1478 {
1479 my $dto = $new_info->get('DateTimeOriginal');
1480 if (defined $dto) {
1481 $new_info->set( 'XMP', 'DateTimeOriginal', $dto );
1482 my $o = $info->get('DateTimeOriginal');
1483 if (defined($o) && not($o->has_timezone_offset)) {
1484 # original DateTimeOriginal has no timezone offset, so the
1485 # new one (for the Exif group) can't have one
1486 $new_info->set('DateTimeOriginal', $dto->clone->remove_timezone);
1487 }
1488 }
1489 }
1490 }
1491
1492 my %changes;
1493
1494 my $result = $self->get_changes($file, $info, $new_info, $extra_info,
1495 \@messages, \%changes);
1496
1497 {
1498 my $camera_id = $new_info->get('CameraID');
1499 $self->{camera_ids}->{$camera_id} = 1 if defined $camera_id;
1500 }
1501
1502 # if verbose & 4 then only print if needs_modification
1503 # if verbose & 8 then print even if not needs_modification
1504 # otherwise don't print
1505 my $bitflag = 8;
1506 $bitflag |= 4 if $extra_info->get('needs_modification');
1507 log_message( $bitflag, { name => $file }, join( "\n", @messages ) . "\n" );
1508
1509 return $result;
1510 }
1511
1512 # $text = display_offset($offset, $maxlength);
1513 #
1514 # Returns a text representation of the time $offset measured in
1515 # seconds, that is at most $maxlength characters wide. The text
1516 # representation uses 'y' for years, 'd' for days, 'h' for hours, 'm'
1517 # for minutes, and 's' for seconds. If the allowed width is too
1518 # narrow to fit the entire representation, then only as many of the
1519 # largest components are returned as will fit, and a period '.' is
1520 # appended to indicate the truncation. If $maxlength is undefined
1521 # then the length is unrestricted.
1522 sub display_offset {
1523 use integer;
1524 my ( $offset, $maxlength ) = @_;
1525 $maxlength //= 80;
1526 return '0' unless $offset;
1527 my $a = abs($offset);
1528 my @steps = ( 60, 60, 24, 365 );
1529 my @symbols = ( 's', 'm', 'h', 'd', 'y' );
1530 my @values;
1531
1532 foreach my $step (@steps) {
1533 push @values, $a % $step;
1534 $a /= $step;
1535 last unless $a;
1536 }
1537 push @values, $a if $a;
1538 my @result;
1539 for my $i ( 0 .. $#values ) {
1540 push @result, $values[$i] . $symbols[$i] if $values[$i];
1541 }
1542 my $result = ( $offset > 0 ) ? '+' : '-';
1543 while ( my $value = pop @result ) {
1544 my $new_result = $result . $value;
1545 if ( length($new_result) > $maxlength ) {
1546 $result = $result . '.';
1547 last;
1548 }
1549 if ( length($new_result) == $maxlength
1550 and @result )
1551 {
1552 $result = $result . '.';
1553 last;
1554 }
1555 $result = $new_result;
1556 }
1557 return $result;
1558 }
1559
1560 # $regex = end_glob_to_regex($pattern);
1561 #
1562 # return a regular expression corresponding to glob C<$pattern>.
1563 sub end_glob_to_regex {
1564 my ($pattern) = @_;
1565 $pattern = perlish_path($pattern);
1566 $pattern =~ s/([.+()])/\\$1/g; # lose special meaning
1567 $pattern =~ s|\*|[^/]*|g; # match zero or more characters not equal to /
1568 $pattern =~ s|\?|[^/]|g; # match one character not equal to /
1569 my $case = $CASE_TOLERANT ? '(?i)' : '';
1570 return qr/${case}${pattern}$/;
1571 }
1572
1573 # $success = $ims->ensure_backup($file);
1574 #
1575 # Ensures that there is a backup of the $file. The name of the backup
1576 # is equal to $file with '_original' appended. If such a file does
1577 # not yet exist, then a copy of $file is made with that name.
1578 #
1579 # Returns a true value upon success, and otherwise a false value.
1580 sub ensure_backup {
1581 my ( $self, $file ) = @_;
1582 my $copy = "${file}_original";
1583 my $short = file($copy)->basename;
1584 if ( -e $copy ) {
1585 log_message(
1586 4,
1587 { name => $file },
1588 sub { "Backup '$short' of '$file' already exists.\n" }
1589 );
1590 return 1;
1591 }
1592 if ( copy( $file, $copy ) ) {
1593 log_message(
1594 4,
1595 { name => $file },
1596 sub { "Created backup '$short' of '$file'.\n" }
1597 );
1598 return 1;
1599 }
1600 else {
1601 log_error("Creating backup '$short' of '$file' failed; reason: $!\n");
1602 return;
1603 }
1604 }
1605
1606 # $ims->export_camera_offsets;
1607 #
1608 # Export the camera offsets. Returns C<$ims>.
1609 sub export_camera_offsets {
1610 my ($self) = @_;
1611 my $path = $self->camera_offsets_path;
1612 if ($path) {
1613 my $data = $self->gps_offsets->export_data;
1614 log_message("Exporting camera offsets to '$path'.\n");
1615 DumpFile( $path, $data );
1616 } else {
1617 log_message("Not exporting camera offsets because --offsetspath value was empty.\n");
1618 }
1619 $self;
1620 }
1621
1622 # $ims->exportgpx($exportfile);
1623 #
1624 # Exports the positions to GPX file C<$exportfile>. Returns C<$ims>.
1625 sub exportgpx {
1626 my ( $self, $exportfile ) = @_;
1627
1628 return $self unless defined $exportfile;
1629
1630 $exportfile = 'export.gpx' unless $exportfile;
1631
1632 my ( $xmlroot, $minlat, $maxlat, $minlon, $maxlon, $count );
1633 foreach my $file ( sort keys %{ $self->{new_info} } ) {
1634 my $new_info = $self->{new_info}->{$file};
1635 next unless defined( my $longitude = $new_info->get('GPSLongitude') );
1636 # get GPSDateTime, not FileModifyDate, because of GPS fix lag
1637 next unless defined( my $time = $new_info->get('GPSDateTime') );
1638
1639 ++$count;
1640
1641 my $latitude = $new_info->get('GPSLatitude');
1642 my $altitude = $new_info->get('GPSAltitude');
1643 $time = $time->display_utc;
1644
1645 $minlat = $latitude
1646 if not( defined $minlat )
1647 or $latitude < $minlat;
1648 $maxlat = $latitude
1649 if not( defined $maxlat )
1650 or $latitude > $minlat;
1651 $minlon = $longitude
1652 if not( defined $minlon )
1653 or $longitude < $minlon;
1654 $maxlon = $longitude
1655 if not( defined $maxlon )
1656 or $longitude > $minlon;
1657
1658 $xmlroot //= XML::Twig::Elt->new(
1659 'gpx',
1660 {
1661 'xmlns' => 'http://www.topografix.com/GPX/1/1',
1662 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
1663 version => '1.1',
1664 'xsi:schemaLocation' =>
1665 'http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd',
1666 creator => 'Exiftime',
1667 }
1668 );
1669
1670 # latitude must be between -90 and +90, inclusive
1671 # longitude must be between -180 and +180, inclusive
1672 my $wpt = $xmlroot->insert_new_elt(
1673 'last_child',
1674 wpt => {
1675 lat => $latitude,
1676 lon => $longitude
1677 }
1678 );
1679 $wpt->insert_new_elt( 'name', file($file)->basename );
1680 $wpt->insert_new_elt( 'time', $time ) if defined $time;
1681 $wpt->insert_new_elt( 'ele', $altitude ) if defined $altitude;
1682 }
1683
1684 if ( defined $xmlroot ) {
1685 my $metadata = $xmlroot->insert_new_elt('metadata');
1686 $metadata->insert_new_elt(
1687 bounds => {
1688 maxlat => $maxlat,
1689 maxlon => $maxlon,
1690 minlat => $minlat,
1691 minlon => $minlon
1692 }
1693 );
1694
1695 $xmlroot->set_pretty_print('indented');
1696 $xmlroot->set_empty_tag_style('html');
1697 $xmlroot->print_to_file($exportfile);
1698 log_message(
1699 sub {
1700 "\nExported "
1701 . ( $self->option('modify') ? '' : '(intended) ' )
1702 . "GPS tags of "
1703 . ( $count // 0 )
1704 . " images to '$exportfile'.\n";
1705 }
1706 );
1707 }
1708 else {
1709 log_message( sub { "\nNo GPS tags to export to '$exportfile'.\n" } );
1710 }
1711 return $self;
1712 }
1713
1714 # $fallback_camera_id = fallback_camera_id($path);
1715 #
1716 # Returns the fall-back camera ID, to be used in case the usual
1717 # information from which to deduce a camera ID is not available.
1718 sub fallback_camera_id {
1719 my ( $path ) = @_;
1720 return '?' . basename_pattern($path);
1721 }
1722
1723 # @targets = $ims->find_info_targets($t);
1724 #
1725 # Returns the files that match C<$t>, which must be a
1726 # Synchronize::Timestamp or a Synchronize::Timerange.
1727 sub find_info_targets {
1728 my ( $self, $t ) = @_;
1729 my @targets;
1730 foreach my $file ( keys %{ $self->{original_info} } ) {
1731 my $create_date = $self->{original_info}->{$file}->get('CreateDate');
1732 next unless defined $create_date;
1733 push @targets, $file
1734 if $t->contains_local($create_date);
1735 }
1736 return @targets;
1737 }
1738
1739 # $r = geo_distance([$latitude1, $longitude1, $altitude1],
1740 # [$latitude2, $longitude2, $altitude2]);
1741 #
1742 # Calculate the approximate distance in meters between the two
1743 # positions. The latitude and longitude are measured in degrees and
1744 # the optional altitudes in meters.
1745 sub geo_distance {
1746 my ( $pos1, $pos2 ) = @_;
1747 return unless ref $pos1 eq 'ARRAY' and ref $pos2 eq 'ARRAY';
1748 return unless scalar( @{$pos1} ) >= 2 and scalar( @{$pos2} ) >= 2;
1749 foreach my $p ( $pos1, $pos2 ) {
1750 foreach my $i ( 0 .. 1 ) {
1751 return unless defined $p->[$i];
1752 }
1753 }
1754
1755 # Image::Exiftool stores longitude and latitude with a resolution of
1756 # 0.01 seconds of arc, and altitude with a resolution of 0.01 m, so
1757 # it is not useful to report a difference that is smaller than that
1758 # resolution.
1759
1760 my @pos1_r = @{$pos1};
1761 @pos1_r[ 0 .. 1 ] = map { floor( $_ * 360000 + 0.5 ) } @pos1_r[ 0 .. 1 ];
1762 $pos1_r[2] = floor( $pos1_r[2] * 100 + 0.5 ) if defined $pos1_r[2];
1763 my @pos2_r = @{$pos2};
1764 @pos2_r[ 0 .. 1 ] = map { floor( $_ * 360000 + 0.5 ) } @pos2_r[ 0 .. 1 ];
1765 $pos2_r[2] = floor( $pos2_r[2] * 100 + 0.5 ) if defined $pos2_r[2];
1766
1767 return 0
1768 if $pos1_r[0] == $pos2_r[0]
1769 && $pos1_r[1] == $pos2_r[1]
1770 && ( $pos1_r[2] // 'X' ) eq ( $pos2_r[2] // 'X' );
1771
1772 use constant DEG => 45 / atan2( 1, 1 );
1773 use constant R => 6378000;
1774
1775 my ( $lat1, $lon1, $alt1 ) =
1776 ( $pos1->[0] / DEG, $pos1->[1] / DEG, ( $pos1->[2] // 0 ) );
1777 my ( $lat2, $lon2, $alt2 ) =
1778 ( $pos2->[0] / DEG, $pos2->[1] / DEG, ( $pos2->[2] // 0 ) );
1779 my $x1 = ( R + $alt1 ) * cos($lon1) * cos($lat1);
1780 my $y1 = ( R + $alt1 ) * sin($lon1) * cos($lat1);
1781 my $z1 = ( R + $alt1 ) * sin($lat1);
1782 my $x2 = ( R + $alt2 ) * cos($lon2) * cos($lat2);
1783 my $y2 = ( R + $alt2 ) * sin($lon2) * cos($lat2);
1784 my $z2 = ( R + $alt2 ) * sin($lat2);
1785 my $dx = $x1 - $x2;
1786 my $dy = $y1 - $y2;
1787 my $dz = $z1 - $z2;
1788 my $rr = $dx * $dx + $dy * $dy + $dz * $dz;
1789 return sqrt($rr);
1790 }
1791
1792 =head2 get_image_info
1793
1794 $et->get_image_info($file);
1795
1796 Extract relevant information from the C<$file>, using
1797 L<Image::ExifTool>, and returns a reference to a hash map containing
1798 the extracted information. The extracted tags are:
1799
1800 =over
1801
1802 =item CreateDate
1803
1804 =item DateTimeOriginal
1805
1806 =item Duration
1807
1808 =item FileModifyDate
1809
1810 =item GPSAltitude
1811
1812 =item GPSAltitudeRef
1813
1814 =item GPSDateTime
1815
1816 =item GPSLatitude
1817
1818 =item GPSLatitudeRef
1819
1820 =item GPSLongitude
1821
1822 =item GPSLongitudeRef
1823
1824 =item ImageWidth
1825
1826 =item Make
1827
1828 =item MIMEType
1829
1830 =item Model
1831
1832 =item QuickTime:CreationDate
1833
1834 =item SerialNumber
1835
1836 =item XMP:CameraID
1837
1838 =item XMP:ImsyncVersion
1839
1840 =item XMP:TimeSource
1841
1842 =item XMP:ExiftimeVersion
1843
1844 =back
1845
1846 Some of the requested tags may occur in the embedded information
1847 multiple times (for example, once as an EXIF tag and once as an XMP
1848 tag). We store all occurrences in the returned map, with keys that
1849 consist of the requested tag name with the tag group (= source) name
1850 prefixed, separated by a colon (e.g., C<"Exif:DateTimeOriginal">).
1851 Additionally, the preferred occurrence is stored in the map with a key
1852 that has only the tag name without the group name (e.g.,
1853 C<"DateTimeOriginal">).
1854
1855 If the ImageWidth tag is present, then the file is considered to be an
1856 image, and then the returned hash map also includes the effective
1857 camera ID, as the value for key C<effective_camera_id>. The
1858 ImageWidth tag is omitted from the hash map.
1859
1860 QuickTime images/movies (recognized by there being a
1861 C<QuickTime:CreateDate> tag) get '|U' appended to their effective
1862 camera ID, and the C<QuickTime::CreateDate> tag is omitted from the
1863 hash map.
1864
1865 Each value is stored for the Image::ExifTool tag including the group
1866 name, and also for the tag without the group name. If a value occurs
1867 in multiple groups (for example EXIF and XMP), then the preferred
1868 value is stored for the tag without the group name.
1869
1870 =cut
1871
1872 sub get_image_info {
1873 my ( $self, $file ) = @_;
1874
1875 my $info = new Image::Synchronize::GroupedInfo;
1876
1877 {
1878 my $image_info = $self->backend->ImageInfo
1879 (
1880 $file,
1881 @all_tags,
1882 {
1883 PrintConv => 0,
1884 defined( $self->option('fastscan') )
1885 ? ( FastScan => $self->option('fastscan') )
1886 : (),
1887 }
1888 );
1889
1890 if ( ( $image_info->{MIMEType} // '' ) =~ m|^image/| ) {
1891 $info->set( 'file_type', 'image' );
1892 }
1893 elsif ( ( $image_info->{MIMEType} // '' ) =~ m|^video/| ) {
1894 $info->set( 'file_type', 'video' );
1895 }
1896 elsif ( $image_info->{ImageWidth} ) {
1897 $info->set( 'file_type', $image_info->{Duration} ? 'video' : 'image' );
1898 }
1899 remove_tag( $image_info, 'ImageWidth', 'Duration' ); # no longer needed
1900
1901 # There are some problems with the hash map returned by
1902 # Image::ExifTool::ImageInfo:
1903 #
1904 # The keys in the hash map may be different from the requested tag
1905 # names -- even if only a single instance of the requested
1906 # information occurs in the file. The letter case of the keys may
1907 # be different from that of the requested tags. The keys do not
1908 # include a tag group, even if the requested tag did include a tag
1909 # group. If there are multiple values for a requested tag, then
1910 # each key gets a parenthesized 1-based index number appended to
1911 # it (e.g., "DateTimeOriginal (1)" and "DateTimeOriginal (2)". In
1912 # such a case we want to know what the source (e.g., Exif, XMP) of
1913 # each of the values is, otherwise we cannot pick the preferred
1914 # value if the values are not identical.
1915 #
1916 # In the case of timestamps, some of them include timezone
1917 # information, but others do not.
1918
1919 my $t = $self->backend->GetInfo("File:FileModifyDate");
1920 if ( $t and scalar keys %{$t} ) {
1921
1922 # $t is a hash reference with one element. We cannot predict
1923 # its tag name exactly; It lacks the 'File:' group name prefix
1924 # but might have a parenthesized instance number affixed.
1925 # Image::ExifTool::GetTagName merely removes the instance
1926 # number, if any, so is no help here.
1927 my $ts =
1928 Image::Synchronize::Timestamp->new( ( values %{$t} )[0] );
1929 if ($ts) {
1930 $info->set( 'File', 'FileModifyDate', $ts );
1931 remove_tag( $image_info, 'FileModifyDate' );
1932 }
1933 }
1934
1935 # now treat the other tags
1936 foreach my $tag ( sort keys %{$image_info} ) {
1937 my $group = $self->backend->GetGroup($tag);
1938 my $bare_tag = $tag =~ s/ \(\d+\)$//r; # omit index number if any
1939
1940 my $value = $image_info->{$tag};
1941
1942 if ( exists $time_tags{$bare_tag}
1943 or exists $time_tags{"$group:$bare_tag"} )
1944 { # it expresses a time
1945 $value = Image::Synchronize::Timestamp->new($value);
1946 }
1947
1948 if (defined $value) {
1949 $info->set( $group, $bare_tag, $value );
1950 } # otherwise $value was undefined, for example because a
1951 # timestamp tag's value wasn't valid.
1952 }
1953
1954 # The GPS tags need special treatment. The sign of the
1955 # longitude/latitude/altitude is generally stored separately from
1956 # the value, and we need to combine them. Exiftool may provide
1957 # already combined values in the 'Composite' and 'XMP' groups,
1958 # except that XMP:GPSAltitude appears not to include a sign yet.
1959 foreach my $tag (@gps_location_tags) {
1960 foreach my $composite_group (qw(Composite XMP)) {
1961 my $composite = $info->get($composite_group, $tag);
1962 if (defined($composite)
1963 && ($tag ne 'GPSAltitude'
1964 || $composite_group ne 'XMP')) {
1965 # We have a composite value, store in the group with the
1966 # empty name ('') so it is the preferred value
1967 $info->set('', $tag, $composite);
1968 last;
1969 }
1970 }
1971 if (not defined $info->get('', $tag)) {
1972 # no composite value yet, so try to construct one from the
1973 # separate parts
1974 foreach my $group ($info->groups($tag)) {
1975 my $value = $info->get($group, $tag);
1976 my $ref = $info->get($group, $tag . 'Ref');
1977 if (defined($value) and defined($ref)) {
1978 if (( $tag eq 'GPSLongitude' and $ref eq 'W')
1979 || ($tag eq 'GPSLatitude' and $ref eq 'S')
1980 || ($tag eq 'GPSAltitude' and $ref eq '1')) {
1981 $value = -$value;
1982 }
1983 $info->set('', $tag, $value);
1984 last;
1985 }
1986 }
1987 }
1988 }
1989 }
1990
1991 if ( is_supposedly_utc($info) ) {
1992
1993 if ( defined $info->get( 'QuickTime', 'CreationDate' )
1994 and $info->get( 'QuickTime', 'CreationDate' )->has_timezone_offset )
1995 {
1996 # We expect that this tag represents absolute time, and allows
1997 # UTC to be deduced. We rename the tag from CreationDate to
1998 # CreateDate so it has the same name as for the other sources.
1999 $info->set( 'QuickTime', 'CreateDate',
2000 $info->get( 'QuickTime', 'CreationDate' ) );
2001 $info->delete( 'QuickTime', 'CreationDate' );
2002 }
2003
2004 if ( defined $info->get('GPSLongitude')
2005 and not( defined $info->get('GPSDateTime') ) )
2006 {
2007 # Some QuickTime files with a GPS position embedded in the
2008 # QuickTime section have no explicit GPSDateTime defined,
2009 # because some other timestamp serves the same purpose.
2010 # (E.g., for Apple iPod Touch.) The remainder of this program
2011 # assumes that if GPS information is present then it includes
2012 # at least longitude, latitude, and time, so copy a suitable
2013 # timestamp to GPSDateTime
2014 $info->set( 'GPSDateTime', $info->get( 'QuickTime', 'CreateDate' ) );
2015 $info->get('GPSDateTime')->adjust_to_utc; # just in case
2016 }
2017 }
2018
2019 if (not(defined $info->get('CreateDate'))) {
2020 # can we get a CreateDate from another tag?
2021 my $ct = $info->get('RIFF', 'DateTimeOriginal');
2022 if (defined $ct) {
2023 $info->set('CreateDate', $ct);
2024 }
2025 }
2026
2027 # for synchronizing the times of non-image files with those of
2028 # related image files, we determine the "image number" of each file.
2029 {
2030 my $number = get_image_number($file);
2031 $info->set( 'image_number', $number ) if defined $number;
2032 }
2033
2034 return $info;
2035 }
2036
2037 # read image/movie metadata from a text file. The metadata is assumed
2038 # to be in JSON or YAML format and to contain tags as produced by
2039 # "exiftool -n -j", optionally (and preferably) also with the "-G"
2040 # option.
2041 sub get_image_info_from_metadata_file {
2042 my ($file) = @_;
2043
2044 my $info;
2045
2046 my $metadata = LoadFile($file);
2047
2048 if (ref($metadata) eq 'ARRAY' && scalar(@{$metadata}) == 1) {
2049 # single-element array, uncover the single element
2050 $metadata = $metadata->[0];
2051 }
2052 if (ref($metadata) eq 'HASH') {
2053 $info = new Image::Synchronize::GroupedInfo;
2054
2055 foreach my $k (keys %{$metadata}) {
2056 my ($group, $tag) = $k =~ /^(?:([^:]+):)?(.*)$/;
2057 if (defined $tag) {
2058 if (exists($all_tags{$k}) || exists($all_tags{$tag})) {
2059 # a tag that interests us
2060 $info->set($group, $tag, $metadata->{$k});
2061 }
2062 }
2063 }
2064 if ($info->tags_count > 0) {
2065 # mark that this information is metadata about another file
2066 $info->set('is_metadata', 1);
2067 }
2068 }
2069 return $info;
2070 }
2071
2072 # extract the image number from the C<$file> name. The image number
2073 # is found as follows: (1) remove the directory part and the file name
2074 # extension from the file name, where the file name extension begins
2075 # at the last period '.'; (2) remove the part after the last digit;
2076 # (3) remove the part up to and including the last letter; (4)
2077 # concatenate the digits that remain. Some examples that yield image
2078 # number 1234: IMG_1234.JPG IMG_1234-extra.txt foo6x1.2_3.4-y.mov
2079 sub get_image_number {
2080 my ($file) = @_;
2081 my $file2 = file($file)->basename; # remove directory part, if any
2082 $file2 =~ s/\.([^.]*)$//; # remove file extension, if any
2083 $file2 =~ s/(\d)\D*$/$1/; # (2)
2084 $file2 =~ s/^.*?[[:alpha:]]([^[:alpha:]]*)$/$1/; # (3)
2085 my $number = join('', split /\D+/, $file2);
2086 return unless defined $number;
2087 return if $number eq '';
2088 return $number + 0;
2089 }
2090
2091 # $gps_offsets = $ims->gps_offsets;
2092 #
2093 # Returns a reference to the offsets of GPS times relative to file
2094 # creation times.
2095 sub gps_offsets {
2096 my ($self) = @_;
2097 return $self->{gps_offsets};
2098 }
2099
2100 # $gpc = $ims->gps_positions;
2101 #
2102 # Returns an C<Image::Synchronize::GpsPositionCollection> object
2103 # representing GPS positions as a function of time, obtained from GPX
2104 # files.
2105 sub gps_positions {
2106 my ($self) = @_;
2107 return $self->{gps_positions};
2108 }
2109
2110 sub has_embedded_timestamp {
2111 my ($image_info) = @_;
2112 foreach my $tag (qw(CreateDate DateTimeOriginal GPSDateTime)) {
2113 my ( $group, $value ) = $image_info->get_context($tag);
2114 return 1 if defined($value) and $group ne 'File' and $group ne '';
2115 }
2116 return 0;
2117 }
2118
2119 sub has_useful_timestamp {
2120 my ($self, $file, $image_info) = @_;
2121 return ( has_embedded_timestamp($image_info)
2122 || defined($self->repository('user_times')->{$file}) );
2123 }
2124
2125 # identify @files that match the $pattern. The match is case
2126 # sensitive, except on case-insensitive operating systems.
2127 sub identify_files {
2128 my ( $pattern, @files ) = @_;
2129 my %original;
2130 my @tfiles;
2131 if ($CASE_TOLERANT) {
2132 # lowercase the file names and pattern if the operating system
2133 # uses case insensitive path names so the match becomes case
2134 # insensitive. Remember the original path names so we can return
2135 # those (the matching ones) instead of the lowercased versions.
2136 $pattern = lc $pattern;
2137 @tfiles = map { lc =~ s|^\./||r } @files;
2138 } else {
2139 @tfiles = map { s|^\./||r } @files;
2140 }
2141 foreach my $i (0..$#files) {
2142 $original{$tfiles[$i]} = $files[$i];
2143 }
2144 $pattern = '*' . $pattern unless $pattern =~ /^\*/;
2145 return map { $original{$_} } match_glob($pattern, @tfiles);
2146 }
2147
2148 # $ims->import_camera_offsets;
2149 #
2150 # Imports camera offsets from the camera offsets file. Returns
2151 # C<$ims>.
2152 sub import_camera_offsets {
2153 my ($self) = @_;
2154 my $path = $self->camera_offsets_path;
2155 if ($path) {
2156 if ( -e $path ) {
2157 log_message("Importing camera offsets from '$path'.\n");
2158 my $data = LoadFile($path);
2159 $self->gps_offsets->parse($data)
2160 or croak "Imported camera offsets are invalid: $@\n";
2161 log_message(
2162 16,
2163 sub {
2164 "Camera Offsets:\n", Dump( $self->gps_offsets->export_data ), "\n";
2165 }
2166 );
2167 } else {
2168 log_message("No camera offsets file found to import from.\n");
2169 }
2170 } else {
2171 log_message("Not importing camera offsets because --offsetspath has an empty value.\n");
2172 }
2173 $self;
2174 }
2175
2176 # initialize_logging
2177 #
2178 # $ims->initialize_logging
2179 #
2180 # Set up logging to a file. Returns <$ims>.
2181 sub initialize_logging {
2182 my ($self) = @_;
2183
2184 # configure logging to standard output
2185 Image::Synchronize::Logger->new(
2186 {
2187 bitflags => $self->option( 'verbose', 1 ),
2188 action => sub { print @_; }
2189 }
2190 )->set_as_default;
2191
2192 # configure logging to the log file
2193 my $logfile = $self->option( 'logfile', 'imsync.log' );
2194 my $ofh;
2195 if ( $self->option('clearlog') ) {
2196 open $ofh, '>', $logfile
2197 or croak "Cannot open '$logfile' for writing: $^E\n";
2198 }
2199 else {
2200 open $ofh, '>>', $logfile
2201 or croak "Cannot open '$logfile' for appending: $^E\n";
2202 }
2203 $ofh->autoflush; # we may be watching the file
2204 $self->{logfh} = $ofh;
2205 $self->{logfile} = $logfile;
2206
2207 default_logger()->set_printer(
2208 {
2209 name => 'file',
2210 bitflags => $self->option( 'verbose', 1 ),
2211 action => sub { print $ofh @_; }
2212 }
2213 );
2214
2215 $self;
2216 }
2217
2218 # initialize_own_xmp_namespace
2219 #
2220 # $ims = $ims->initialize_own_xmp_namespace;
2221 #
2222 # Initialize our own XMP namespace for embedding our own tags into
2223 # image files through Image::ExifTool. Returns C<$ims>.
2224 sub initialize_own_xmp_namespace {
2225 my ($self) = @_;
2226
2227 # to delete all XMP tags using exiftool, use exiftool -XMP:all=
2228 # <files>
2229
2230 {
2231 no warnings; # suppress warning about ..::imsync being used only once
2232
2233 %Image::ExifTool::UserDefined::imsync = (
2234 GROUPS => { 0 => 'XMP', 1 => 'XMP', 2 => 'Image' },
2235 NAMESPACE => { 'imsync' => 'http://imsync.quae.nl/' },
2236 WRITABLE => 'string',
2237 map { $_ => {} } @own_xmp_tags
2238 );
2239
2240 %Image::ExifTool::UserDefined = (
2241
2242 # add new XMP namespace to the Main XMP table
2243 'Image::ExifTool::XMP::Main' => {
2244 imsync => {
2245 SubDirectory => {
2246 TagTable => 'Image::ExifTool::UserDefined::imsync'
2247 },
2248 },
2249 }
2250 );
2251 }
2252
2253 $self;
2254 }
2255
2256 sub enhance_image_info {
2257 my ($self, $file, $info) = @_;
2258
2259 # TODO: remove this when the author no longer needs it to transition
2260 # from exiftime to imsync
2261 if ( defined $info->get('ExiftimeVersion') ) {
2262 log_warn("ExiftimeVersion found in $file.\n");
2263 }
2264
2265 my $count_essential_gps_tags = 0;
2266 foreach (qw(GPSDateTime GPSLongitude GPSLatitude)) {
2267 ++$count_essential_gps_tags if defined $info->get($_);
2268 }
2269 if ( $count_essential_gps_tags
2270 and $count_essential_gps_tags < 3 ) {
2271 log_warn(<<EOD);
2272 File '$file' has some but not all of GPSDateTime,
2273 GPSLongitude, GPSLatitude. Ignoring its GPS information.
2274 EOD
2275 $info->delete($_)
2276 foreach qw(GPSLatitude GPSLongitude GPSAltitude GPSDateTime);
2277 }
2278
2279 $info->set( 'supposedly_utc', 1 ) if is_supposedly_utc($info);
2280
2281 # determine the camera ID.
2282
2283 my $camera_id;
2284 {
2285 my $embedded_camera_id = $info->get('CameraID');
2286
2287 if (defined $embedded_camera_id
2288 and not $self->option('force', 0)) {
2289 # no --force was applied, so just reuse the embedded
2290 # camera ID
2291 $camera_id = $embedded_camera_id;
2292 } else {
2293 # construct a camera ID from the embedded information
2294 $camera_id = camera_id($info);
2295 }
2296 }
2297
2298 # there may not be sufficient information to deduce a camera
2299 # ID in the preferred way; also deduce a fallback camera ID
2300 # that is always available
2301 my $fallback_camera_id = fallback_camera_id( $file );
2302
2303 if (defined $camera_id
2304 and $camera_id eq $fallback_camera_id) {
2305 $camera_id = undef;
2306 }
2307
2308 if ( defined $camera_id ) {
2309 $info->set( 'camera_id', $camera_id );
2310
2311 # remember for later, so we can hopefully substitute real
2312 # camera IDs for some fallback ones.
2313 ++$self->{fallback_to_camera_id}->{$fallback_camera_id}->{$camera_id};
2314 }
2315 $info->set( 'fallback_camera_id', $fallback_camera_id );
2316 }
2317
2318 # $ims->inspect_files(@files);
2319 #
2320 # Inspects the @files. The files are inspected but not modified,
2321 # because we may be able to use information from a later image to
2322 # synchronize the time of an earlier image, but we can't tell until
2323 # we've inspected all files.
2324 #
2325 # Relevant properties are remembered, and files that provide too
2326 # little information (or are found to not be image or movie files) are
2327 # omitted from further consideration.
2328 #
2329 # Returns the object.
2330 sub inspect_files {
2331 my ( $self, @files ) = @_;
2332
2333 my $count_image_files = 0;
2334 my $count_gps_times = 0;
2335 my $count_gps_track_files = 0;
2336
2337 # We display a progress bar to show how far we are in processing all
2338 # files.
2339 my $progressbar = $self->setup_progressbar( scalar(@files), 'Inspect' );
2340
2341 my %gpx_files;
2342
2343 $self->{fallback_to_camera_id} = {};
2344
2345 # Now process the files.
2346 foreach my $file (@files) {
2347
2348 log_message( 2, { name => $file }, sub { "\nInspecting '$file'\n" } );
2349
2350 if ( is_gpx_track($file) ) { # a GPX track
2351 ++$count_gps_track_files;
2352 push @{ $self->{gpx_tracks} }, $file;
2353 $self->{gpx_total_size} += -s $file;
2354 log_message( 2, { name => $file }, " Is a GPX file.\n" );
2355 }
2356 else {
2357 my $info =
2358 $self->get_image_info( $file );
2359
2360 # if we have the creation timestamp only from the file system
2361 # and not from an embedded tag, then we cannot deduce the target
2362 # timestamp from the creation timestamp (because the file
2363 # apparently wasn't created by a camera). We need to be able to
2364 # detect this.
2365 my ( $group, $createdate ) = $info->get_context('CreateDate');
2366 $info->set( 'createdate_was_embedded', 1 )
2367 if defined($createdate)
2368 and $group ne 'File';
2369
2370 if (is_image_or_movie($info)) {
2371 $self->enhance_image_info($file, $info);
2372 ++$count_image_files;
2373 ++$count_gps_times if defined $info->{GPSDateTime};
2374 } else {
2375 my $type;
2376 if (($info->get('MIMEType') // '') =~ m'application/(json|yaml)') {
2377 # the MIMEType is detected based on the file's contents,
2378 # regardless of its file name extension
2379 $type = uc($1);
2380 } elsif ($file =~ /\.ya?ml$/i) {
2381 # but at the time of writing this there is no YAML-specific
2382 # MIMEType yet, so we can also detect YAML files based on
2383 # the file name extension
2384 $type = 'YAML';
2385 }
2386 if ($type) {
2387 my $metainfo = get_image_info_from_metadata_file($file);
2388 if (defined $metainfo) {
2389 $self->enhance_image_info($file, $metainfo);
2390 my @tags = $metainfo->tags;
2391 if (@tags) {
2392 log_message(2, { name => $file }, " Is a $type metadata file.\n" );
2393 # $info->set('is_metadata', 1);
2394 foreach my $tag ($metainfo->tags) {
2395 my ($group, $value) = $metainfo->get_context($tag);
2396 if (not defined($info->get($group, $tag))) {
2397 # this group/tag is not in $info yet
2398 if (exists $time_tags{$tag}) {
2399 $value = Image::Synchronize::Timestamp->new($value);
2400 }
2401 $info->set($group, $tag, $value);
2402 }
2403 }
2404 ++$count_gps_times if defined $info->{GPSDateTime};
2405 }
2406 }
2407 }
2408 }
2409
2410 $self->{original_info}->{$file} = $info;
2411 log_message( 2, { name => $file }, $info->stringify(' Found ') . "\n" );
2412 }
2413
2414 $progressbar->add;
2415 }
2416 $self->cleanup_progressbar($progressbar);
2417
2418 log_message("\n");
2419 log_message("Found $count_gps_track_files GPS track file(s).\n")
2420 if $count_gps_track_files;
2421 log_message("Found $count_image_files image file(s).\n");
2422 log_message("$count_gps_times file(s) have a GPS timestamp.\n");
2423 return $self;
2424 }
2425
2426 # $ok = is_gpx_track($file);
2427 #
2428 # determines whether the named file is a GPX file, by looking for
2429 # "<gpx " in its first line. This is much faster than trying to parse
2430 # the entire file using an XML parser.
2431 sub is_gpx_track {
2432 my ($file) = @_;
2433 if ( open my $ifh, '<', $file ) {
2434 my $line;
2435 do {
2436 $line = <$ifh>;
2437 } until eof($ifh) or $line =~ /<[^?]/;
2438 close $ifh;
2439 return 1 if defined($line) and $line =~ /<gpx /;
2440 }
2441 else {
2442 log_message( { name => $file },
2443 sub { "Cannot open file '$file' for reading: $^E\n" } );
2444 }
2445 return 0;
2446 }
2447
2448 # $ok = is_image_or_movie($image_info);
2449 #
2450 # Queries whether the C<$image_info> indicates that the source was an
2451 # image or movie file. Returns a true value if yes, a false value if
2452 # no.
2453 sub is_image_or_movie {
2454 my ($image_info) = @_;
2455 return ( $image_info->get('file_type') // '' ) =~ /^image|video$/;
2456 }
2457
2458 # $ok = is_supposedly_utc($image_info);
2459 #
2460 # Queries whether the C<$image_info> indicates an image source whose
2461 # CreateDate is supposedly in UTC instead of in the local timezone.
2462 # Returns a true value if yes, a false value if no.
2463 #
2464 # Such timestamps that are supposed to be in UTC sometimes are not,
2465 # for instance when the image source doesn't know what timezone it is
2466 # in.
2467 sub is_supposedly_utc {
2468 my ($image_info) = @_;
2469
2470 # For a QuickTime file, QuickTime:CreateDate does not include an
2471 # explicit timezone. It is supposed to be in UTC, but sometimes
2472 # isn't. (For example, if the camera doesn't know what timezone it
2473 # is in.) Sometimes QuickTime:CreateDate is in neither UTC nor the
2474 # camera's local timezone.
2475
2476 return defined( $image_info->get( 'QuickTime', 'CreateDate' ) );
2477 }
2478
2479 sub length_of_common_prefix {
2480 my ( $a, $b ) = @_;
2481 my @a = split //, $a;
2482 my @b = split //, $b;
2483 splice @a, scalar(@b);
2484 foreach my $i (0..$#a) {
2485 return $i if $a[$i] ne $b[$i];
2486 }
2487 return scalar(@a);
2488 }
2489
2490 sub length_of_common_directory_prefix {
2491 my ($a, $b) = @_;
2492 my $a2 = file($a)->parent->stringify;
2493 my $b2 = file($b)->parent->stringify;
2494 return length_of_common_prefix($a2, $b2);
2495 }
2496
2497 my %convert_for_writing = (
2498 GPSLatitude => sub {
2499 my ( $tag, $in, $out ) = @_;
2500
2501 # don't set coordinates to abs($in). If the coordinate is
2502 # writting to XMP rather than EXIF, then there is no GPSxRef so
2503 # then the sign on GPSx is needed.
2504 $out->{"${tag}#"} = $in;
2505 $out->{"${tag}Ref#"} = ( $in > 0 ) ? 'N' : 'S';
2506 },
2507 GPSLongitude => sub {
2508 my ( $tag, $in, $out ) = @_;
2509 $out->{"${tag}#"} = $in;
2510 $out->{"${tag}Ref#"} = ( $in > 0 ) ? 'E' : 'W';
2511 },
2512 GPSAltitude => sub {
2513 my ( $tag, $in, $out ) = @_;
2514 $out->{"${tag}#"} = $in;
2515 $out->{"${tag}Ref#"} = ( $in > 0 ) ? 0 : 1;
2516 },
2517 GPSDateTime => sub {
2518 my ( $tag, $in, $out ) = @_;
2519 my $t = Image::Synchronize::Timestamp->new($in)->adjust_to_utc;
2520
2521 # GPSDateStamp and GPSTimeStamp are needed for EXIF.
2522 $out->{GPSDateStamp} = $t->date;
2523 $out->{GPSTimeStamp} = $t->time;
2524
2525 # GPSDateTime is for XMP, in case the GPS coordinates ended up in
2526 # XMP.
2527 $out->{$tag} = "$t";
2528 },
2529 DateTimeOriginal => sub {
2530 my ( $tag, $in, $out ) = @_;
2531
2532 # make sure to also write in XMP
2533 $out->{$tag} = $in;
2534 $out->{ 'XMP:' . $tag } = $in;
2535 },
2536 ImsyncVersion => \&convert_to_xmp,
2537 CameraID => \&convert_to_xmp,
2538 TimeSource => \&convert_to_xmp,
2539 );
2540
2541 sub set_file_modification_time {
2542 my ($self, $file, $time_utc) = @_;
2543 utime undef, $time_utc, $file;
2544 # return $self->backend->SetFileTime($file, undef, $time_utc);
2545 }
2546
2547 # $et->modify_file($file);
2548 #
2549 # Modify the $file as indicated in the information gathered in
2550 # C<$self>. Ensures that there is a backup of the file before
2551 # modifying the original -- and refuses to modify the original
2552 # otherwise.
2553 #
2554 # Returns 1 if the file was modified OK, 2 if the file was written but
2555 # no changes were made, 3 if the file was not modified because no
2556 # backup could be created for it, 4 if there was an error writing the
2557 # file but the metadata could be written to a separate file, 5 if
2558 # there were errors writing the file and writing the separate metadata
2559 # file, and 0 if there were no changes to make.
2560 sub modify_file {
2561 my ( $self, $file ) = @_;
2562
2563 my $new_info = $self->{new_info}->{$file};
2564 my $extra_info = $self->{extra_info}->{$file};
2565 my $changes = $extra_info->get('changes');
2566 return 0 unless defined($changes) and scalar( @{$changes} );
2567
2568 my $status;
2569 my $b = $self->backend;
2570
2571 {
2572 my $size = -s $file;
2573 log_message(
2574 2,
2575 { name => $file },
2576 sub { "Modifying '$file' ($size bytes)\n" }
2577 );
2578 }
2579 if ( $self->option('unsafe') || $self->ensure_backup($file) ) {
2580
2581 $b->SaveNewValues(); # so we can return to a clean slate
2582
2583 # then we treat all requested tags
2584 $b->ExtractInfo($file);
2585
2586 my $changed;
2587 my $found_filemodifydate_tag;
2588 foreach my $tag ( @{$changes} ) {
2589 $found_filemodifydate_tag = 1, next
2590 if $tag eq 'FileModifyDate'; # done separately
2591 my $value = $new_info->get($tag);
2592 my %values;
2593 if ( defined $value ) {
2594 $value = "$value"; # stringify
2595 if ( $convert_for_writing{$tag} ) {
2596 $convert_for_writing{$tag}->( $tag, $value, \%values );
2597 }
2598 else {
2599 $values{$tag} = $value;
2600 }
2601 }
2602 else {
2603 # delete this tag
2604 if ( $convert_for_writing{$tag} ) {
2605
2606 # figure out which tags we need to adjust
2607 # use "dummy" value 0
2608 $convert_for_writing{$tag}->( $tag, 0, \%values );
2609
2610 # set value to undef so tag will get deleted by
2611 # SetNewValue
2612 $values{$_} = undef foreach keys %values;
2613 }
2614 else {
2615 $values{$tag} = undef;
2616 }
2617 }
2618 foreach my $t ( sort keys %values ) {
2619 my ( $success, $error ) = $b->SetNewValue( $t, $values{$t} );
2620 if ($success) {
2621 log_message(
2622 4,
2623 {
2624 name => $file
2625 },
2626 sub {
2627 defined( $values{$t} )
2628 ? " Set $t of '$file' to '" . $values{$t} . "'\n"
2629 : " Removed $t from '$file'\n";
2630 }
2631 );
2632 $changed += $success;
2633 }
2634 else {
2635 log_warn(
2636 defined( $values{$t} )
2637 ? " ExifTool error setting $t of '$file' to '" . $values{$t} . "': $error\n"
2638 : " ExifTool error removing $t from '$file': $error\n"
2639 );
2640 }
2641 }
2642 }
2643
2644 if ( $changed ) {
2645
2646 $status = $b->WriteInfo($file); # write to file
2647 if ( $status == 2 ) {
2648 log_warn(" '$file' written but no changes made.\n");
2649 }
2650 if ( $status == 1 ) {
2651 my $warning = $b->GetValue('Warning');
2652 if ($warning) {
2653
2654 # We suppress warnings about the FileName encoding not being
2655 # specified. We don't invent or modify the byte values of the
2656 # file name, so the encoding should be unimportant as long as
2657 # Image::ExifTool doesn't modify any file name byte values,
2658 # either.
2659 my @warnings = split /\n/, $warning;
2660 @warnings = grep { !/
2661 FileName[ ]encoding[ ]not[ ]specified
2662 |Maker[ ]notes[ ]could[ ]not[ ]be[ ]parsed
2663 /x } @warnings;
2664 if (@warnings) {
2665 $warning = join( "\n", @warnings );
2666 log_warn(" Writing '$file' succeeded with ExifTool warning: $warning\n");
2667 }
2668 }
2669 }
2670 else {
2671 # Writing via Image::ExifTool failed. We write the tags to a
2672 # corresponding metadata file instead. If the writing failed
2673 # because Image::ExifTool does not support the file type
2674 # (yet), then we report that problem only for the first file
2675 # of that type -- to avoid numerous otherwise unavoidable
2676 # warnings.
2677
2678 my @messages;
2679 my $error = $b->GetValue('Error');
2680 if ($error =~ /(Writing of (?:.*?) files is not yet supported)/) {
2681 state %suppress;
2682 if (not $suppress{$1}) {
2683 push @messages,
2684 " Writing '$file' failed, ExifTool reports:\n $error\n",
2685 " This message is suppressed for similar following files.\n";
2686 # mark that we reported this problem already
2687 $suppress{$1} = 1;
2688 }
2689 } else {
2690 push @messages,
2691 join( ', ',
2692 " Writing '$file' failed",
2693 ( $error ? "ExifTool reports:\n $error" : () ))
2694 . "\n"
2695 ;
2696 }
2697
2698 # write the tags to a metadata file instead, if any of the
2699 # tags have changed relative to what is in the metadata file
2700 # already
2701 my $metafile = "${file}.yaml";
2702 my $old_metainfo;
2703 if (-r $metafile) {
2704 $old_metainfo = get_image_info_from_metadata_file($metafile);
2705 } else {
2706 $old_metainfo = new Image::Synchronize::GroupedInfo;
2707 }
2708 my %changes;
2709 $changed = $self->get_changes($file, $old_metainfo, $new_info, $extra_info,
2710 undef, \%changes);
2711 if ($changed) {
2712 if (exists $changes{FileModifyDate}
2713 and scalar keys %changes == 1) {
2714 # only FileModifyDate needs to be changed
2715 $self->set_file_modification_time($metafile,
2716 $new_info->get('FileModifyDate')->time_utc);
2717 $status = 4;
2718 } else {
2719 # the contents of the metadata file needs changes
2720 my %values_for_export;
2721 foreach my $tag ($new_info->tags) {
2722 foreach my $group ($new_info->groups($tag)) {
2723 my $v = $new_info->get($group, $tag);
2724 $values_for_export{$group? "$group:$tag": $tag} = "$v";
2725 }
2726 }
2727 if (DumpFile($metafile, \%values_for_export)) {
2728 push @messages, " Wrote metadata to '$metafile'.\n";
2729 $self->set_file_modification_time($metafile,
2730 $new_info->get('FileModifyDate')->time_utc);
2731 $status = 4;
2732 } else {
2733 push @messages, " Writing metadata to '${file}.yaml' failed: $@\n";
2734 $status = 5;
2735 }
2736 }
2737 } else {
2738 $changed = 0; # no changes (perhaps excluding FileModifyDate) after all
2739 }
2740 if (@messages) {
2741 log_message(join("\n", @messages) . "\n");
2742 }
2743 }
2744 }
2745
2746 if ( $changed or $found_filemodifydate_tag ) {
2747 # Updating the FileModifyDate (the file system modification
2748 # timestamp) via WriteInfo doesn't always work; for example,
2749 # ExifTool 10.63 does not support modifying AVI files.
2750 #
2751 # Unfortunately, on Microsoft Windows setting the file
2752 # modification time via utime() is problematic, because the zero
2753 # point depends on the timzone settings (at least it depends on
2754 # whether Daylight Savings Time is in effect when this code is
2755 # executed).
2756 #
2757 # The author of Image::ExifTool faced and overcame the same
2758 # problem, and using the resulting Image::ExifTool functionality
2759 # worked for me on Windows 10 but no longer on Windows 11.
2760 #
2761 # Then I found Win32::UTCFileTime, which allows overriding utime
2762 # with a version that hopefully works on Windows 11.
2763
2764 my $cur_mt = -M $file;
2765 my $fmt = $new_info->get('FileModifyDate');
2766 my $success = $self->set_file_modification_time($file, $fmt->time_utc);
2767
2768 if ($success) {
2769 my $new_mt = -M $file;
2770 if ($new_mt == $cur_mt) {
2771 log_message( 4, { name => $file },
2772 sub { " Setting FileModifyDate of '$file' to '$fmt' FAILED\n" } );
2773 $success = 0;
2774 }
2775 }
2776 if ($success) {
2777 log_message( 4, { name => $file },
2778 sub { " Set FileModifyDate of '$file' to '$fmt'\n" } );
2779 $changed += $success;
2780 } else {
2781 log_warn( " Error setting FileModifyDate of '$file' to '$fmt'\n");
2782 }
2783 } else {
2784 # TODO: don't report any changes for this file, either
2785 }
2786 $b->RestoreNewValues(); # return to clean slate
2787 }
2788 else {
2789 log_error(" Could not create backup file for '$file': not modified.\n");
2790 $status = 3;
2791 }
2792 return $status;
2793 }
2794
2795 # $et->modify_files;
2796 #
2797 # Makes another pass over all of the files of interest left over from
2798 # the previous pass. During this pass, the target timestamp for each
2799 # file is applied to that file, if the 'modify' option is true.
2800 sub modify_files {
2801 my ($self) = @_;
2802 return $self unless $self->option('modify'); # nothing to do
2803 my $totalsize = 0;
2804 my @files = grep {
2805 my $n = $self->{extra_info}->{$_}->get('needs_modification');
2806 $totalsize += -s $_ if $n;
2807 $n;
2808 } keys %{ $self->{extra_info} };
2809 return $self unless @files;
2810
2811 @files = sort @files;
2812
2813 if (@files) {
2814 my $count_modified = 0;
2815
2816 my $progressbar = $self->setup_progressbar( $totalsize, 'Modify' );
2817
2818 foreach my $file (@files) {
2819 my $ok = $self->modify_file($file);
2820 $progressbar->add( -s $file );
2821 ++$count_modified if $ok;
2822 }
2823 $self->cleanup_progressbar($progressbar);
2824 if ($count_modified) {
2825 log_message("$count_modified file(s) changed.\n");
2826 }
2827 $self->cleanup_progressbar($progressbar);
2828 }
2829 return $self;
2830 }
2831
2832 # $value = $ims->option($name);
2833 # $value = $ims->option($name, $default);
2834 #
2835 # Retrieves the value of the option with the specified C<$name>.
2836 # Accesses the options specified in the constructor and through
2837 # L</set_option>. If the option is not defined, then returns
2838 # C<$default> if specified, and C<undef> otherwise.
2839 sub option {
2840 my ( $self, $option, $default ) = @_;
2841 return $self->{options}->{$option} // $default;
2842 }
2843
2844 sub parse_coordinate {
2845 my ($value) = @_;
2846 return unless defined $value;
2847 my $result;
2848 if ( looks_like_number($value) ) {
2849 $result = $value;
2850 }
2851 else {
2852 my @components;
2853 my $rest = $value;
2854
2855 # may be signed
2856 my $sign = +1;
2857 if ( $rest =~ /^([-+])(.*)$/ ) {
2858 $sign = -1 if $1 eq '-';
2859 $rest = $2;
2860 }
2861
2862 # a possibly fractional number at the end
2863 if ( $rest =~ /^(.*?)(\d+(?:\.\d+)?)\D*$/ ) {
2864 unshift @components, $2;
2865 $rest = $1;
2866 }
2867 else { # not valid input
2868 return undef;
2869 }
2870 if ($rest) {
2871 unshift @components, split /\D+/, $rest;
2872 }
2873 $result = 0;
2874 while (@components) {
2875 my $next_component = pop(@components);
2876 next unless defined $next_component;
2877 $result = $result / 60 + $next_component;
2878 }
2879 $result *= $sign;
2880 }
2881 return $result;
2882 }
2883
2884 # convert the path to Perl style
2885 sub perlish_path {
2886 my ($path) = @_;
2887 return file($path)->as_foreign('Unix')->stringify;
2888 }
2889
2890 # %display_cameras = $ims->prepare_display_cameras;
2891 #
2892 # Determines a two-letter abbreviation for all of the camera IDs seen.
2893 # The abbreviation consists of the first two characters of the camera
2894 # ID, unless that conflicts with an abbreviation assigned earlier.
2895 # Progressively more distant abbreviations are tried until one is
2896 # found that isn't used yet. If all else fails, then '**' is used, so
2897 # that is the only abbreviation that might be assigned to multiple
2898 # cameras.
2899
2900 sub prepare_display_cameras {
2901 my ($self) = @_;
2902 my %display_cameras;
2903 my %used;
2904 foreach my $camera ( sort keys %{ $self->{camera_ids} } ) {
2905 my $candidate = uc( substr( $camera, 0, 2 ) );
2906 $candidate .= ' ' x ( 2 - length($candidate) ) if length($candidate) < 2;
2907 if ( $used{$candidate} ) { # try first letter with digit suffix
2908 my $prefix = uc( substr( $camera, 0, 1 ) );
2909 for my $i ( 0 .. 9 ) {
2910 $candidate = $prefix . $i;
2911 last unless $used{$candidate};
2912 }
2913 }
2914 if ( $used{$candidate} ) { # try first letter with lowercase letter suffix
2915 my $prefix = uc( substr( $camera, 0, 1 ) );
2916 for my $a ( 'a' .. 'z' ) {
2917 $candidate = $prefix . $a;
2918 last unless $used{$candidate};
2919 }
2920 }
2921 if ( $used{$candidate} ) { # try first letter with uppercase letter suffix
2922 my $prefix = uc( substr( $camera, 0, 1 ) );
2923 for my $a ( 'A' .. 'Z' ) {
2924 $candidate = $prefix . $a;
2925 last unless $used{$candidate};
2926 }
2927 }
2928 if ( $used{$candidate} ) { # try any two lowercase letters
2929 $candidate = 'aa';
2930 do {
2931 last unless $used{$candidate};
2932 ++$candidate;
2933 } while length($candidate) == 2;
2934 }
2935 if ( $used{$candidate} ) { # give up
2936 $candidate = '**';
2937 }
2938 $display_cameras{$camera} = $candidate;
2939 $used{$candidate} = 1;
2940 }
2941 return %display_cameras;
2942 }
2943
2944 sub process_gpx_track {
2945 my ( $self, $file ) = @_;
2946 my $gps_point_count;
2947 my $time_parse_problem_count;
2948 my $gpc = $self->gps_positions;
2949 my ( $mintime, $maxtime );
2950 my $track_count = 0;
2951 my $twig = XML::Twig->new(
2952 twig_handlers => {
2953 trkseg => sub {
2954 my ( $twig, $section ) = @_;
2955 ++$track_count;
2956 my $id = "$file-$track_count";
2957 foreach my $point ( $section->children('trkpt') ) {
2958 my $lat = $point->att('lat');
2959 my $lon = $point->att('lon');
2960 my $time = $point->first_child_text('time');
2961 next unless $time;
2962 $time = Image::Synchronize::Timestamp->new($time);
2963 unless ( defined $time ) {
2964 ++$time_parse_problem_count;
2965 next;
2966 }
2967 $mintime = $time
2968 if not( defined $mintime )
2969 or $time < $mintime;
2970 $maxtime = $time
2971 if not( defined $maxtime )
2972 or $time > $maxtime;
2973 my $ele = $point->first_child_text('ele');
2974 ++$gps_point_count;
2975 $gpc->add( $time->time_utc, $lat, $lon, $ele, $id,
2976 scope_for_file($file) )
2977 if $time;
2978 }
2979 }
2980 }
2981 );
2982 log_message( 2, { name => $file }, "Reading '$file'.\n" );
2983 if ( $twig->safe_parsefile($file) ) {
2984 if ( defined $gps_point_count ) {
2985 log_message(
2986 2,
2987 { name => $file },
2988 sub {
2989 my $min = $mintime->display_utc;
2990 my $max = $maxtime->display_utc;
2991 my $common_prefix = common_prefix( '[-T]', $min, $max );
2992 $max =~ s/^\Q$common_prefix\E//;
2993 " Read $gps_point_count positions ($min/$max).\n";
2994 }
2995 );
2996 }
2997 log_message(
2998 "Could not parse $time_parse_problem_count times from GPX file '$file'\n"
2999 ) if defined $time_parse_problem_count;
3000 return 1;
3001 }
3002 else {
3003 # some error
3004 log_message("Problem parsing GPX tracks from $file: $@\n");
3005 return 0;
3006 }
3007 }
3008
3009 sub process_summer_wintertime {
3010 my ($self) = @_;
3011 my %jumps = ( summertime => +1, wintertime => -1 );
3012 my @files = keys %{ $self->{original_info} };
3013 foreach my $jump ( keys %jumps ) {
3014 my $target = $self->option($jump);
3015 my $match;
3016 if ($target) {
3017 my @matches = identify_files( $target, @files );
3018 if (@matches) {
3019 $self->repository('jump')->{ $matches[0] } = $jumps{$jump};
3020 }
3021 else {
3022 croak "--$jump pattern matches no files.\n";
3023 }
3024 }
3025 }
3026 return $self;
3027 }
3028
3029 # (FILE_END|TIMESTAMP(/TIMESTAMP)?)=CAMERAID
3030 sub process_user_camera_ids {
3031 my ( $self, @files ) = @_;
3032 my $action_cref = sub {
3033 my ($rhs) = @_;
3034
3035 # strip surrounding whitespace
3036 $rhs = $1 if $rhs =~ /^\s*(.*?)\s*$/;
3037 if ($rhs) {
3038 return $rhs;
3039 }
3040 else {
3041 log_warn("None or an empty camera ID was specified; ignored.\n");
3042 return;
3043 }
3044 };
3045 return $self->process_user_items( 'cameraid', 'user_camera_ids', $action_cref,
3046 @files );
3047 }
3048
3049 # t a r g e t = s o u r c e
3050 # (FILE_END|TIMESTAMP(/TIMESTAMP)?)=(LOCATION|FILE_END)
3051 sub process_user_locations {
3052 my ($self) = @_;
3053 my $action_cref = sub {
3054 my ( $rhs, $file ) = @_;
3055 my @sources;
3056 if ($rhs) {
3057 @sources = identify_files( $rhs, keys %{ $self->{original_info} } );
3058 if ( @sources > 1 ) {
3059 log_warn("--location RHS '$rhs' matches more than one file; ignored.\n");
3060 return;
3061 }
3062 elsif ( @sources == 0 ) { # is it a location?
3063 my ( $latitude, $longitude, $altitude ) = split /,/, $rhs;
3064 $latitude = parse_coordinate($latitude);
3065 $longitude = parse_coordinate($longitude);
3066 if ( defined($latitude) and defined($longitude) ) {
3067 return [ $latitude, $longitude, add_maybe($altitude) ];
3068 }
3069 }
3070 if ( @sources == 1 ) {
3071 my $source_info = $self->{original_info}->{ $sources[0] };
3072 if ( defined $source_info ) {
3073 return [
3074 $source_info->get('GPSLatitude'),
3075 $source_info->get('GPSLongitude'),
3076 add_maybe( $source_info->get('GPSAltitude') )
3077 ];
3078 }
3079 }
3080 } else { # empty rhs -- reset position
3081 return [];
3082 }
3083 log_warn("Could not resolve --location RHS '$rhs'.\n");
3084 return;
3085 };
3086 return $self->process_user_items( 'location', 'user_locations',
3087 $action_cref );
3088 }
3089
3090 # (FILE_END|TIMESTAMP(/TIMESTAMP)?)=(TIME|OFFSET|FILE_END)
3091 sub process_user_times {
3092 my ($self) = @_;
3093 my $action_cref = sub {
3094 my ( $rhs, $file, $info ) = @_;
3095 my $value;
3096 if ( looks_like_number($rhs) ) { # offset in seconds
3097 my $createdate = $info->get('CreateDate');
3098 if ( defined $createdate ) {
3099 $value = $createdate->clone->adjust_to_local_timezone + $rhs;
3100 }
3101 else {
3102 # no CreateDate; cannot apply offset
3103 log_warn(
3104 "Cannot apply --time offset for $file because it lacks an embedded CreateDate.\n"
3105 );
3106 }
3107 }
3108 elsif (
3109 $rhs
3110 and $rhs =~ /^
3111 (?<sign>[-+])?
3112 (?:(?<year>\d+)y)?
3113 (?:(?<day>\d+)d)?
3114 (?:(?<hour>\d+)h)?
3115 (?:(?<minute>\d+)m)?
3116 (?:(?<second>[\d.]+)s)?
3117 $/x
3118 )
3119 { # multi-unit offset
3120 # TODO: support timezone offset
3121 $value = ( $+{year} // 0 ) * 365;
3122 $value = ( $value + ( $+{day} // 0 ) ) * 24;
3123 $value = ( $value + ( $+{hour} // 0 ) ) * 60;
3124 $value = ( $value + ( $+{minute} // 0 ) ) * 60;
3125 $value += ( $+{second} // 0 );
3126 $value = -$value if ( $+{sign} // '+' ) eq '-';
3127 my $createdate = $info->get('CreateDate');
3128 if ( defined $createdate ) {
3129 $value = $createdate->clone->adjust_to_local_timezone + $value;
3130 }
3131 else {
3132 # no CreateDate; cannot apply offset
3133 log_warn(
3134 "Cannot apply --time offset for $file because it lacks an embedded CreateDate.\n"
3135 );
3136 }
3137 }
3138 elsif ( $rhs =~ /^(\d+:\d+(?::\d+)?)$/ ) { # clock time
3139 # TODO: support timezone offset
3140 my $createdate = $info->get('CreateDate');
3141 if ( defined $createdate ) {
3142 $value = Image::Synchronize::Timestamp->new( $rhs, $createdate );
3143 }
3144 else {
3145 # no CreateDate; cannot apply offset
3146 log_warn(
3147 "Cannot apply --time clock time for $file because it lacks an embedded CreateDate.\n"
3148 );
3149 }
3150 }
3151 elsif ( $rhs =~ /^(\d+-\d+-\d+\D\d+:\d+(?::\d+)?)$/
3152 && defined($value = Image::Synchronize::Timestamp->new( $rhs )) ) {
3153 # clock date/time
3154 }
3155 else { # path end
3156 my @files = keys %{ $self->{original_info} };
3157 @files = identify_files( $rhs, @files );
3158 if (@files) {
3159 if ( @files > 1 ) {
3160 croak "--time RHS value matched by multiple files: "
3161 . join( ', ', sort @files ) . "\n";
3162 }
3163 else {
3164 $value = $files[0];
3165 $value = $self->{original_info}->{$value}->get('DateTimeOriginal');
3166 croak "--time RHS file '$value' had no DateTimeOriginal.\n"
3167 unless defined $value;
3168 }
3169 }
3170 else { # timestamp
3171 $value = Image::Synchronize::Timestamp->new($rhs);
3172 if ( defined $value ) {
3173 $value->adjust_to_local_timezone
3174 unless $value->has_timezone_offset;
3175 }
3176 else {
3177 log_error(
3178 "--time value $rhs does not have a valid format (for $file).\n");
3179 }
3180 }
3181 }
3182 return $value;
3183 };
3184 return $self->process_user_items( 'time', 'user_times', $action_cref );
3185 }
3186
3187 # process the 'follow' option.
3188 #
3189 # Returns the object.
3190 sub process_follow {
3191 my ( $self, @files ) = @_;
3192 my $count = 0;
3193 my $action_cref = sub {
3194 my ($item) = @_;
3195 $self->{follow}->{$item} = 1;
3196 ++$count;
3197 return undef; # don't need to remember anything else
3198 };
3199 $self->process_user_items( 'follow', undef, $action_cref, @files );
3200 if ($count) {
3201 default_logger()
3202 ->set_printer_condition( '', 'follow',
3203 sub { $_ && $self->{follow}->{ $_->{name} } } );
3204 }
3205 return $self;
3206 }
3207
3208 # $self->process_user_items($option, $repository, $action);
3209 #
3210 # Processes the structured value of a command-line option.
3211 #
3212 # C<$option> names the command-line option whose value to process. The
3213 # value identifies files and the data to associate with them.
3214 #
3215 # C<$repository> names the repository to which to append the results of
3216 # processing the command-line option value. The repository must be a
3217 # hash, and is created if it does not yet exist.
3218 #
3219 # C<$action> is a CODE reference through which the command-line option
3220 # value is processed.
3221 #
3222 # The value of command-line option C<$option> may be a HASH or an ARRAY
3223 # reference. The hash keys or array elements are scalars that identify
3224 # the files with which to associate the results.
3225 #
3226 # The files to search through are those for which information has been
3227 # gathered through L</inspect_files>.
3228 #
3229 # If any of those files have a path that ends with the hash key or array
3230 # element, then those files are the targets for that hash key or array
3231 # element.
3232 #
3233 # Otherwise, if the hash key or array element can be parsed as a
3234 # timestamp (L<Image::Synchronize::Timestamp>) or time range
3235 # (L<ImsyncTimerange>), then the files whose C<CreateDate> is equal to
3236 # the timestamp or falls within the time range are the targets.
3237 #
3238 # If the value of the command-line option is a HASH reference, then
3239 # the results are obtained through
3240 #
3241 # $result = $action->($value, $file, $info);
3242 #
3243 # for each target C<$file>, with C<$value> the hash value and C<$info>
3244 # the image information of the target file.
3245 #
3246 # If the value of the command-line option is an ARRAY reference, then
3247 # the results are obtained through
3248 #
3249 # $result = $action->($file, $info);
3250 #
3251 # for each target C<$file>.
3252 #
3253 # In both cases, if the C<$result> is defined, then it is stored in the
3254 # repository hash as the value for the key equal to C<$file>.
3255 #
3256 # Returns C<$self>.
3257 sub process_user_items {
3258 my ( $self, $option, $repository, $action, @files ) = @_;
3259 my $in_spec = $self->option($option);
3260 my $out_repository = $self->repository($repository) if defined $repository;
3261 if ($in_spec) {
3262 my @keys;
3263 if ( ref $in_spec eq 'HASH' ) {
3264 @keys = keys %{$in_spec};
3265 }
3266 elsif ( ref $in_spec eq 'ARRAY' ) {
3267 @keys = @{$in_spec};
3268 }
3269 else {
3270 croak "Argument should be array ref or hash ref but is '" . ref($in_spec)
3271 . "\n";
3272 }
3273 unless (@files) {
3274 @files = sort keys %{ $self->{original_info} };
3275 }
3276 foreach my $key (@keys) {
3277
3278 # $key is FILE_END or TIMESTAMP or TIMESTAMP/TIMESTAMP. First
3279 # see if the end of the path name of any file matches the key.
3280 my @targets = identify_files( $key, @files );
3281 unless (@targets) {
3282
3283 # then check if the key is a timestamp or time range
3284 my $t;
3285 if ( $key =~ m|/| ) {
3286 $t = Image::Synchronize::Timerange->new($key);
3287 }
3288 else {
3289 $t = Image::Synchronize::Timestamp->new($key);
3290 }
3291 if ( defined $t ) {
3292 @targets = $self->find_info_targets($t);
3293 }
3294 }
3295 unless (@targets) {
3296 log_warn(
3297 "Target '$key' does not match any of the specified files and does not look like a time instant or range; ignored.\n"
3298 );
3299 next;
3300 }
3301 foreach my $target (@targets) {
3302 my $rhs;
3303 if ( ref $in_spec eq 'HASH' ) {
3304 $rhs = $action->(
3305 $in_spec->{$key}, $target, $self->{original_info}->{$target}
3306 );
3307 }
3308 else {
3309 $rhs = $action->( $target, $self->{original_info}->{$target} );
3310 }
3311 if ( defined($out_repository) && defined($rhs) ) {
3312 $out_repository->{$target} = $rhs;
3313 } # end if defined($out_repository) && defined($rhs)
3314 } # end foreach my $target
3315 } # end foreach my $key
3316 } # end if $in_spec
3317 return $self;
3318 }
3319
3320 sub read_gpx_tracks {
3321 my ($self) = @_;
3322 if ( $self->{gpx_total_size} ) {
3323 my $progressbar =
3324 $self->setup_progressbar( $self->{gpx_total_size}, 'GPX' );
3325 foreach my $file ( @{ $self->{gpx_tracks} } ) {
3326 $self->process_gpx_track($file);
3327 $progressbar->add( -s $file );
3328 }
3329 $self->cleanup_progressbar($progressbar);
3330 }
3331 return $self;
3332 }
3333
3334 # remove the tags that this application added
3335 sub remove_our_tags {
3336 my ( $self, @files ) = @_;
3337
3338 my $b = $self->backend;
3339 my $progressbar =
3340 $self->setup_progressbar( scalar(@files), 'Remove Own Tags' );
3341 my $count = 0;
3342 foreach my $file (@files) {
3343 my $image_info = $self->get_image_info($file);
3344 if ( has_embedded_timestamp($image_info) ) {
3345 $b->ExtractInfo($file);
3346 $b->SaveNewValues(); # so we can return to a clean slate
3347
3348 # We don't include XMP:DateTimeOriginal even though the current
3349 # application may have written it, because it might also have been
3350 # written by some other application. We invented the following
3351 # tags, but not DateTimeOriginal.
3352 my @tags_to_remove = map { "XMP:$_" } @own_xmp_tags;
3353
3354 # if TimeSource is not equal to GPS, then we can remove the GPS tags
3355 my $timesource = $image_info->get('TimeSource');
3356 if ( not( defined $timesource ) or $timesource ne 'GPS' ) {
3357 # GPSDateTime is in this list because Image::ExifTool writes
3358 # it in the XMP namespace when it writes GPSDateStamp and
3359 # GPSTimeStamp in the EXIF namespace
3360 push @tags_to_remove, qw(
3361 GPSAltitude
3362 GPSAltitudeRef
3363 GPSDateStamp
3364 GPSDateTime
3365 GPSLatitude
3366 GPSLatitudeRef
3367 GPSLongitude
3368 GPSLongitudeRef
3369 GPSTimeStamp
3370 );
3371 }
3372
3373 my $changed = 0;
3374 foreach my $tag (@tags_to_remove) {
3375 {
3376 my $v = $b->GetValue($tag);
3377 next if not defined $v;
3378 next if ref($v) eq 'HASH' and not( scalar keys %{$v} );
3379 next if ref($v) eq 'ARRAY' and not( scalar @{$v} );
3380 }
3381 my ( $success, $error ) = $b->SetNewValue( $tag, undef );
3382 if ($success) {
3383 log_message(
3384 4,
3385 {
3386 name => $file
3387 },
3388 sub { "Removed $tag from '$file'\n"; }
3389 );
3390 $changed += $success;
3391 }
3392 else {
3393 log_warn(" Error removing $tag from '$file': $error\n");
3394 }
3395 }
3396 if ($changed) {
3397
3398 # Also update the FileModifyDate (the file system modification
3399 # timestamp), because updating any embedded information changes
3400 # that timestamp to the current time.
3401 my $value = $image_info->get('FileModifyDate');
3402 $value = "$value"; # stringify
3403 my ( $success, $error ) =
3404 $b->SetNewValue( 'FileModifyDate', $value, Protected => 1 );
3405 if ($success) {
3406 log_message(
3407 4,
3408 {
3409 name => $file
3410 },
3411 sub { " Set FileModifyDate of '$file' to '$value'\n" }
3412 );
3413 $changed += $success;
3414 }
3415 else {
3416 log_warn(
3417 " Error setting FileModifyDate of '$file' to '$value': $error\n");
3418 }
3419
3420 my $status = $b->WriteInfo($file);
3421 log_warn(" '$file' written but no changes made.\n") if $status == 2;
3422 if ( $status == 1 ) {
3423 my $warning = $b->GetValue('Warning');
3424 if ($warning) {
3425
3426 # We suppress warnings about the FileName encoding not being
3427 # specified. We don't invent or modify the byte values of the
3428 # file name, so the encoding should be unimportant as long as
3429 # Image::ExifTool doesn't modify any file name byte values,
3430 # either.
3431 my @warnings = split /\n/, $warning;
3432 @warnings = grep { !/FileName encoding not specified/ } @warnings;
3433 if (@warnings) {
3434 $warning = join( "\n", @warnings );
3435 log_warn(" Writing '$file' succeeded with warning: $warning\n");
3436 }
3437 }
3438 ++$count;
3439 }
3440 else {
3441 my $error = $b->GetValue('Error');
3442 log_warn(
3443 join( ', ',
3444 " Writing '$file' failed",
3445 ( $error ? "Error: $error" : () ) )
3446 . "\n"
3447 );
3448 $status = 4;
3449 }
3450 }
3451 $b->RestoreNewValues(); # return to clean slate
3452 }
3453 $progressbar->add;
3454 }
3455 log_message("Removed our own tags from $count file(s).\n");
3456 $self->cleanup_progressbar($progressbar);
3457 return $self;
3458 }
3459
3460 # removes tags related to C<@tags> from C<$image_info>.
3461 #
3462 # Image::ExifTool::ImageInfo returns a hash map that may contain
3463 # multiple keys for a requested tag, depending on how many instances
3464 # of the requested information were included in the target file. If
3465 # there are multiple keys, then some or all of them end with a
3466 # parenthesized index number. This sub removes keys equal to the
3467 # specified @tags, and also keys equal to the tag followed by a
3468 # parenthesized index number.
3469 sub remove_tag {
3470 my ( $image_info, @tags ) = @_;
3471 foreach my $tag (@tags) {
3472 delete $image_info->{$_}
3473 foreach grep /^\Q$tag\E(?: \(\d+\))?$/, keys %{$image_info};
3474 }
3475 return $image_info;
3476 }
3477
3478 # $ims->report;
3479 #
3480 # Prints a report about the processed files. Returns C<$ims>.
3481 sub report {
3482 my ($self) = @_;
3483
3484 my $reportlevel = $self->option( 'reportlevel', 1 );
3485 return $self unless $reportlevel;
3486
3487 my @report_these = keys %{ $self->{extra_info} };
3488 @report_these =
3489 grep { $self->{extra_info}->{$_}->get('needs_modification') } @report_these
3490 if $reportlevel == 1;
3491 return $self unless @report_these;
3492
3493 my %display_cameras = $self->prepare_display_cameras;
3494
3495 my $common_prefix_path;
3496 $common_prefix_path = common_prefix_path(@report_these);
3497
3498 my $modify = $self->option('modify');
3499 my $modality = $modify ? '' : 'would be ';
3500 log_message(<<EOD);
3501
3502 REPORT:
3503 G: embedded GPS timestamp (UTC)
3504 E: embedded original timestamp
3505 O: other embedded tags
3506 M: file modification time
3507 P: embedded GPS position
3508 F: minimum --force for modification
3509 =: ${modality}unchanged
3510 *: ${modality}modified
3511 +: ${modality}added
3512 !: ${modality}removed
3513 -: absent
3514
3515 Cm: camera code from following table
3516 Cm Camera ID
3517 --|-------------------------
3518 EOD
3519 my %cameras = reverse %display_cameras;
3520 foreach my $id ( sort keys %cameras ) {
3521 my $name = $cameras{$id} eq '?' ? 'UNKNOWN' : $cameras{$id};
3522 log_message(" $id $name\n");
3523 }
3524 log_message("\n");
3525 log_message( <<EOD );
3526 M Offset source:
3527 g: embedded GPS timestamp
3528 s: embedded creation timestamp & other images
3529 o: embedded original timestamp
3530 c: embedded creation timestamp
3531 t: --time
3532 n: other file with same number
3533
3534 EOD
3535
3536 log_message(
3537 sprintf(
3538 "GEOMPF Cm %-25s %-10s %-8s %s\n",
3539 'Target Time', 'M Offset', 'c Offset', 'File'
3540 )
3541 );
3542 log_message( '------|--|'
3543 . ( '-' x 25 ) . '|'
3544 . ( '-' x 10 ) . '|'
3545 . ( '-' x 8 ) . '|'
3546 . ( '-' x 8 )
3547 . "\n" );
3548
3549 my $min_offset;
3550 my $max_offset;
3551 my $count_nonzero_offset = 0;
3552 foreach my $file (
3553 sort {
3554 timestamp_for_sorting( $self->{original_info}->{$a},
3555 $self->{new_info}->{$a} )
3556 <=> timestamp_for_sorting( $self->{original_info}->{$a},
3557 $self->{new_info}->{$b} )
3558 or ( $self->{original_info}->{$a}->get('image_number') // -1 )
3559 <=> ( $self->{original_info}->{$b}->get('image_number') // -1 )
3560 } @report_these
3561 )
3562 {
3563 my $info = $self->{original_info}->{$file};
3564 my $new_info = $self->{new_info}->{$file};
3565 my $extra_info = $self->{extra_info}->{$file};
3566 my $short;
3567 ( $short = $file ) =~ s/^(\Q$common_prefix_path\E)//o;
3568 $short =~ s{^\./}{};
3569
3570 my $is_metainfo_file = $info->get('is_metadata');
3571
3572 # G
3573 log_message( report_letter( 'GPSDateTime', $info, $new_info ) );
3574
3575 # E
3576 log_message( report_letter( 'DateTimeOriginal', $info, $new_info ) );
3577
3578 # O
3579 if ($is_metainfo_file) {
3580 log_message('=');
3581 } else {
3582 my @letters = map { report_letter( $_, $info, $new_info ) }
3583 ( 'XMP:DateTimeOriginal', map { "XMP:$_" } @own_xmp_tags );
3584 my $combined = $letters[0];
3585 foreach my $i ( 1 .. $#letters ) {
3586 if ( $letters[$i] ne $combined ) {
3587 if ( $combined eq '=' ) {
3588 $combined = $letters[$i];
3589 }
3590 else {
3591 $combined = '*';
3592 }
3593 }
3594 }
3595 log_message($combined);
3596 }
3597
3598 # M
3599 log_message( report_letter( 'FileModifyDate', $info, $new_info ) );
3600
3601 # P
3602 {
3603 my $letter;
3604 if ($extra_info->get('position_change')) {
3605 # position was present in old and new, and the new position is
3606 # sufficiently different that the difference shows up in the
3607 # EXIF tags
3608 $letter = '*';
3609 } else {
3610 # a position wasn't present in old or new, or it was present
3611 # in both and hasn't changed significantly. The same then
3612 # goes for any one of the components.
3613 $letter = report_letter( 'GPSLatitude', $info, $new_info );
3614 if ($letter eq '*') {
3615 # the latitude is different but not by enough to show up in
3616 # the EXIF tag after writing. Mark as the same.
3617 $letter = '=';
3618 }
3619 }
3620 log_message($letter);
3621 }
3622
3623 {
3624 my $m = $extra_info->get('min_force_for_change');
3625 log_message( {}, $m < 99 ? $m : ' ' );
3626 }
3627
3628 my $timestamp = timestamp_for_sorting( $info, $new_info );
3629 my $new_fmd = $new_info->get('FileModifyDate');
3630 my $time_change = $new_fmd - $info->get('FileModifyDate');
3631 if ( defined $timestamp ) {
3632 my $create_date = $new_info->get('CreateDate');
3633 my $camera_id = $new_info->get('CameraID');
3634 $camera_id = $display_cameras{$camera_id} if defined $camera_id;
3635 log_message(
3636 sprintf(
3637 " %2s %-25.25s %1s %8s %8s %s\n",
3638 ( $camera_id // '' ),
3639 $timestamp->display_iso,
3640 $extra_info->get('timesource_letter') // ' ',
3641 display_offset( $time_change, 8 ),
3642 (
3643 defined($create_date)
3644 ? display_offset( $new_fmd - $create_date, 8 )
3645 : ' ' x 8
3646 ),
3647 $short
3648 )
3649 );
3650 }
3651 else {
3652 log_message(
3653 sprintf(
3654 " %2s %-25.25s %1s %8s %8s %s\n",
3655 display_camera( $new_info->get('CameraID') ),
3656 'unknown', '?', 'unknown', 'unknown', $short
3657 )
3658 );
3659 }
3660 if ($time_change) {
3661 ++$count_nonzero_offset;
3662 $min_offset = $time_change
3663 if not( defined $min_offset )
3664 or $time_change < $min_offset;
3665 $max_offset = $time_change
3666 if not( defined $max_offset )
3667 or $time_change > $max_offset;
3668 }
3669 }
3670 log_message("\n");
3671 $min_offset //= 0;
3672 $max_offset //= 0;
3673 if ( $min_offset == $max_offset ) {
3674 if ($min_offset) { # not equal to zero
3675 log_message( "All $count_nonzero_offset non-zero offsets are equal to ",
3676 display_offset($min_offset), ".\n\n" );
3677 }
3678 else {
3679 log_message("All offsets are equal to 0 seconds.\n");
3680 }
3681 }
3682 else {
3683 log_message(
3684 "$count_nonzero_offset non-zero offsets are between ",
3685 display_offset($min_offset),
3686 " and ", display_offset($max_offset), ".\n"
3687 );
3688 }
3689
3690 if ( $self->{max_gps_distance} ) {
3691 log_message(
3692 sub {
3693 my ( $value, $prefix ) = si_prefix( $self->{max_gps_distance} );
3694 "Maximum shift of GPS position is $value ${prefix}m for $self->{max_gps_file}\n";
3695 }
3696 );
3697 }
3698
3699 if ( $self->gps_offsets->camera_count ) {
3700 if ( $self->option( 'verbose', 1 ) & 16 ) {
3701 log_message(
3702 sub {
3703 "\nCamera Offsets:\n", Dump( $self->gps_offsets->to_display ), "\n";
3704 }
3705 );
3706 }
3707 else {
3708 log_message(
3709 sub {
3710 "\nCamera offsets for the time range:\n",
3711 Dump( $self->gps_offsets->relevant_part ),
3712 "\n";
3713 }
3714 );
3715 }
3716 }
3717 else {
3718 log_message("\nNo camera offsets are known.\n");
3719 }
3720
3721 return $self;
3722 }
3723
3724 sub report_letter {
3725 my ( $tag, $info, $new_info ) = @_;
3726 ( my $group, $tag ) = $tag =~ /^(?:(\w+):)?(\w+)$/;
3727 $group //= '';
3728 my $old = $info->get($tag);
3729 my $new = $new_info->get( $group, $tag );
3730 if ( defined $new ) {
3731 if ( defined $old ) {
3732 if ( $new ne $old ) {
3733 return '*'; # modified
3734 }
3735 else {
3736 return '='; # unchanged
3737 }
3738 }
3739 else { # new but not old
3740 return '+'; # added
3741 }
3742 }
3743 else { # not new
3744 if ( defined $old ) {
3745 return '!'; # removed
3746 }
3747 else {
3748 return '-'; # absent
3749 }
3750 }
3751 }
3752
3753 # report program and options
3754 sub report_program_and_options {
3755 my ($self) = @_;
3756 my $program_name = file($0)->basename;
3757 my %defaults = (
3758 fastscan => 1,
3759 recurse => 1,
3760 );
3761 my %no = map { $_ => 1 } qw(modify recurse);
3762 log_message(
3763 "Running $program_name " . join(
3764 ' ',
3765 grep { defined($_) } map( {
3766 my $key = $_;
3767 my $value = $self->option($key);
3768 my $text;
3769 if ( ref $value eq 'HASH' ) {
3770 $text = "--$key "
3771 . join( " --$key ",
3772 map { "\"$_\"=\"$value->{$_}\"" } sort keys %{$value} );
3773 }
3774 elsif ( ref $value eq 'ARRAY' ) {
3775 $text = "--$key " . join( " --$key ", @{$value} );
3776 }
3777 elsif ( not( defined $defaults{$key} )
3778 || $value ne $defaults{$key} )
3779 {
3780 if ( $no{$key} ) {
3781 $text = '--' . ( $value ? '' : 'no-' ) . $key;
3782 }
3783 else {
3784 $text = "--$key";
3785 if ( looks_like_number($value) ) {
3786 if ( $value != 1 ) {
3787 $text .= " $value";
3788 }
3789 }
3790 else {
3791 $text .=
3792 ' ' . ( $value =~ /\s/ ? q(") . $value . q(") : $value );
3793 }
3794 }
3795 }
3796 $text;
3797 } grep !/^working-directory$/,
3798 sort keys %{ $self->{options} } ),
3799 map { /\s/ ? q(") . $_ . q(") : $_ } @ARGV
3800 )
3801 . "\n version $VERSION"
3802 . "\n in "
3803 . dir()->absolute . ".\n\n"
3804 );
3805 $self;
3806 }
3807
3808 # returns a reference to the named repository, which gets created if
3809 # it did not exist yet
3810 sub repository {
3811 my ( $self, $name ) = @_;
3812 $self->{repository}->{$name} //= {};
3813 return $self->{repository}->{$name};
3814 }
3815
3816 # @files = resolve_files($rule, @items);
3817 # @files = resolve_files({ recurse => 0 }, $rule, @items); # don't recurse
3818 #
3819 # Resolves a list of path name patterns to a list of files. C<$rule> is
3820 # expected to be a L<Path::Iterator::Rule> that identifies files of
3821 # interest. C<@items> is a list of path name patterns or references to
3822 # lists of path name patterns. If the first argument is a hash
3823 # reference, then it provides additional options. The C<recurse> option
3824 # says whether or not to recurse into subdirectories. It defaults to 1,
3825 # and can be set to 0 through this option.
3826 #
3827 # If an item is an existing directory, then the rule is applied to all
3828 # of its elements, and the matching elements are appended to the list to
3829 # be returned.
3830 #
3831 # If an item is an existing file, then it is appended to the list to be
3832 # returned.
3833 #
3834 # Otherwise, the item is interpreted as a path name pattern, and files
3835 # that match that pattern and also the rule are appended to the list to
3836 # be returned.
3837 sub resolve_files {
3838 my ( $options, $rule, @items );
3839 if ( ref $_[0] eq 'HASH' ) {
3840 ( $options, $rule, @items ) = @_;
3841 }
3842 else {
3843 ( $rule, @items ) = @_;
3844 }
3845 @items = map { ref($_) eq 'ARRAY' ? @{$_} : $_ } @items;
3846 return () unless @items;
3847 $options //= {};
3848 if ( not( $options->{recurse} ) ) {
3849 $rule = Path::Iterator::Rule->new
3850 ->max_depth(1) # no recursion
3851 ->and($rule);
3852 }
3853 my @files;
3854 foreach my $item (@items) {
3855 my @extra;
3856 if ( -d $item ) {
3857 @extra = $rule->all($item);
3858 log_message("No matches for $item.\n") unless @extra;
3859 }
3860 elsif ( -f $item ) {
3861 my $f = file($item);
3862 @extra = ($f);
3863 }
3864 else {
3865 # the item was not found as a literal name; maybe it is a file
3866 # name pattern
3867
3868 my $f = file($item);
3869
3870 # seek directories matching the pattern
3871 my @subdirs =
3872 Path::Iterator::Rule->new
3873 ->max_depth(1)
3874 ->$PIRname( $f->basename )
3875 ->directory
3876 ->all( $f->parent );
3877 @extra = $rule->all(@subdirs) if @subdirs;
3878
3879 # seek files matching the pattern
3880 push @extra,
3881 Path::Iterator::Rule->new
3882 ->max_depth(1)
3883 ->$PIRname( $f->basename )
3884 ->and( $rule )
3885 ->all( $f->parent );
3886
3887 log_message("No matches for $item.\n") unless @extra;
3888
3889 # remove initial './' because it makes later pattern matching
3890 # more difficult
3891 @extra = map { s|^./||; $_ } @extra;
3892 }
3893 push @files, @extra;
3894 }
3895
3896 # remove duplicates, and convert to Perl-style paths
3897 my %files;
3898 $files{ perlish_path($_) } = 1 foreach @files;
3899 return sort keys %files;
3900 }
3901
3902 # restore original files from backup files
3903 sub restore_original_files {
3904 my ( $self, @arguments ) = @_;
3905
3906 # restore original files
3907 my @files = resolve_files( { recurse => $self->option('recurse') },
3908 Path::Iterator::Rule->new->file->$PIRname('*_original'), @arguments );
3909 my $progressbar = $self->setup_progressbar( scalar(@files), 'restore' );
3910 my $count = 0;
3911 my $exit_status = 0;
3912 foreach my $file (@files) {
3913 my $original;
3914 my $backup;
3915 if ( $file =~ /^(.*?)_original$/ ) {
3916 $original = $1;
3917 $backup = $file;
3918 }
3919 else {
3920 $original = $file;
3921 $backup = "${file}_original";
3922 }
3923 if ( -e $backup ) {
3924 if ( -e $original ) {
3925 log_message( 4, { name => $file }, "Removing '$original'.\n" );
3926 unlink($original);
3927 }
3928 else {
3929 log_message(
3930 4,
3931 { name => $file },
3932 "'$original' does not exist; no need to delete.\n"
3933 );
3934 }
3935 log_message( 4, { name => $file },
3936 "Renaming '$backup' to '$original'\n" );
3937 move( $backup, $original )
3938 or $self->log_message("Failed to restore '$original': $!\n");
3939 }
3940 else {
3941 log_message( 4,
3942 "Backup '$backup' does not exist; not restoring '$original'.\n" );
3943 }
3944 ++$count;
3945 $progressbar->add;
3946 }
3947 log_message("Done restoring $count original file(s).\n");
3948 $self->cleanup_progressbar($progressbar);
3949 $self;
3950 }
3951
3952 sub scope_for_file {
3953 my ($file) = @_;
3954 my $scope = file($file)->dir->as_foreign('Unix')->stringify;
3955 $scope = '' if $scope eq '.';
3956 return $scope;
3957 }
3958
3959 # $ims->set_option($name, $value);
3960 # $ims->set_option($name); # undefine
3961 #
3962 # Assigns the C<$value> to the option with the given C<$name>. If the
3963 # C<$value> is not defined or equal to C<undef>, then the option is
3964 # removed.
3965 #
3966 # Returns C<$ims>.
3967 sub set_option {
3968 my ( $self, $option, $value ) = @_;
3969 if ( defined $value ) {
3970 $self->{options}->{$option} = $value;
3971 }
3972 else {
3973 delete $self->{options}->{$option};
3974 }
3975 return $self;
3976 }
3977
3978 # set_working_directory
3979 #
3980 # $ims->set_working_directory;
3981 #
3982 # Sets the working directory based on the C<working-directory> option.
3983 # Must be done before calling L</initialize_logging> because the log
3984 # file by default is in the working directory. So cannot make use of
3985 # the logging.
3986 #
3987 # Returns C<$ims>.
3988 sub set_working_directory {
3989 my ($self) = @_;
3990 my $wd = $self->option( 'workingdirectory', '.' );
3991 if ( $wd ne '.' ) {
3992 chdir($wd)
3993 or croak "Couldn't change to working directory '$wd': $@\n";
3994 }
3995 $self;
3996 }
3997
3998 # $progressbar = $ims->setup_progressbar($count, $title);
3999 #
4000 # Displays an Image::Synchronize::ProgressBar with the specified
4001 # $title that shows progress toward the goal equal to $count.
4002 # Progress messages are passed through the default
4003 # Image::Synchronize::Logger.
4004 sub setup_progressbar {
4005 my ( $self, $count, $title ) = @_;
4006
4007 # We display a progress bar to show how far we are in processing all
4008 # files.
4009 my $progressbar = Image::Synchronize::ProgressBar->new(
4010 {
4011 count => $count,
4012 name => $title,
4013 }
4014 );
4015
4016 # Arrange for the progress bar to handle output of log messages to
4017 # screen, so those messages and the progress bar don't mess up each
4018 # other.
4019 default_logger()->set_printer(
4020 {
4021 bitflags => ( $self->option('verbose') // 1 ),
4022 action => sub { $progressbar->message( join( '', @_ ) ); }
4023 }
4024 );
4025 log_message("Starting phase '$title'.\n");
4026 return $progressbar;
4027 }
4028
4029 sub si_prefix {
4030 my ( $value, $significant ) = @_;
4031 $significant //= 3;
4032 my $sign;
4033 if ( $value < 0 ) {
4034 $sign = -1;
4035 $value = -$value;
4036 }
4037 elsif ( $value > 0 ) {
4038 $sign = 1;
4039 }
4040 else {
4041 return wantarray ? ( 0, '' ) : 0;
4042 }
4043 my @prefixes = ( 'μ', 'm', '', 'k', 'M' );
4044 my $l = POSIX::floor( log($value) / log(1000) + 1 / 3 + 2 );
4045 $l = 0 if $l < 0;
4046 $l = $#prefixes if $l > $#prefixes;
4047 my $prefix = $prefixes[$l];
4048 my $factor = 10**( 3 * ( 2 - $l ) );
4049 my $numeral = sprintf( '%.*g', $significant, $sign * $value * $factor );
4050 return wantarray
4051 ? ( $numeral, $prefix )
4052 : $numeral . ( $prefix ? " $prefix" : '' );
4053 }
4054
4055 sub stringify {
4056 my ($thing) = @_;
4057 return "$thing" if defined $thing;
4058 return '';
4059 }
4060
4061 # $timestamp = timestamp_for_sorting($info, $new_info);
4062 #
4063 # Returns the "best available" timestamp for sorting, based on
4064 # information contained in $info and $new_info, which must have the
4065 # expected format. The order of preference is: (1) new
4066 # FileModifyDate, (2) new DateTimeOriginal, (3) new GPSDateTime, (4)
4067 # old FileModifyDate, (5) old DateTimeOriginal, (6) old GPSDateTime
4068 sub timestamp_for_sorting {
4069 my ( $info, $new_info ) = @_;
4070 my @tags = qw(FileModifyDate DateTimeOriginal GPSDateTime);
4071 my $value;
4072 foreach my $tag (@tags) {
4073 $value = $new_info->get($tag);
4074 return $value if defined $value;
4075 }
4076 foreach my $tag (@tags) {
4077 $value = $info->get($tag);
4078 return $value if defined $value;
4079 }
4080 return;
4081 }
4082
4083 # $user_camera_id = $ims->user_camera_id($path);
4084 #
4085 # Returns the user-defined (through option C<camera>) camera ID for
4086 # the file with the given C<$path>, or C<undef> if there isn't one.
4087 sub user_camera_id {
4088 my ( $self, $path ) = @_;
4089 return $self->repository('user_camera_ids')->{$path};
4090 }
4091
4092 # Calculates a file modification timestamp from a DateTimeOriginal.
4093 #
4094 # The file modification timestamp is expressed in the local timezone.
4095 # If 'relativefiletime' is set, then the file modification timestamp
4096 # has the same clock time as the DateTimeOriginal. Otherwise, the
4097 # file modification timestamp represents the same instant of universal
4098 # time as the DateTimeOriginal.
4099 sub file_from_dto {
4100 my ($self, $dto_timestamp) = @_;
4101 if ($self->option('relativefiletime')) {
4102 my $ltzo = $dto_timestamp->local_timezone_offset;
4103 return $dto_timestamp->clone->set_timezone_offset($ltzo);
4104 } else {
4105 return $dto_timestamp;
4106 }
4107 }
4108
4109 sub normalize_options {
4110 my @args;
4111 foreach (@_) {
4112 if (my ($prefix, $opt, $suffix) = /^(-+)([-_\w]+)(.*)/) {
4113 $opt =~ tr/-_//d;
4114 push @args, "$prefix$opt$suffix";
4115 } else {
4116 push @args, $_;
4117 }
4118 }
4119 return @args;
4120 }
4121
4122 1;
4123
4124 __END__
« Synchronize/Timestamp.pm ↑ Summary