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