Updated for Ubuntu 22.04. Also fixed merge videos cmin check
[videoscripts/.git] / merge_videos_by_day
1 #!/usr/bin/perl
2 # Author: Alan J. Pippin
3 # Description: For the given srcpath, merge all the videos that were taken on the same day into a single mkv file
4
5 use File::Copy;
6 use File::Basename;
7 use Getopt::Std;
8 use File::stat;
9 use Time::localtime;
10 use DateTime::Format::Strptime qw( );
11
12 # Set our ffmpeg creation_time format
13 $ffmpeg_time_format_utc = DateTime::Format::Strptime->new(pattern=>'%Y-%m-%dT%H:%M:%S', time_zone => 'UTC', on_error => 'croak');
14 $ffmpeg_time_format_local = DateTime::Format::Strptime->new(pattern=>'%Y-%m-%dT%H:%M:%S', time_zone => 'local', on_error => 'croak');
15 $ctime_format = DateTime::Format::Strptime->new(pattern=>'%a %b %d %H:%M:%S %Y', time_zone => 'local', on_error => 'croak');
16
17 # Early command line options processing
18 getopts("qzkh:tvs:");
19 my $srcpathname = $opt_s;
20
21 ####################################################################################################
22 # Configuration parameters
23 $mydir = `cd \$(dirname $0) 2>/dev/null; pwd`; chomp($mydir); unshift @INC,("$mydir");
24 # Default configuration values
25 require "organize_videos.conf";
26 # Override defaults with local customizations
27 if( -f "$mydir/organize_videos.conf.local") { require "organize_videos.conf.local"; }
28
29 ####################################################################################################
30
31 sub usage {
32     print "usage: $0 [-tvrhz] -s <srcpath>\n";
33     print "   -s <srcpath>          specify the path to search for videos to merge under\n";
34     print "   -h <compute host>     specify the remote compute host to submit the mkvmerge job to\n";
35     print "   -v                    verbose mode; print extra information about what is being found/merged\n";
36     print "   -t                    test mode; print what will happen, but don't do anything\n";
37     print "   -k                    keep the individual video files that are merged. By default, after a merge, individual video files that were merged are removed\n";
38     print "   -q                    Requantize input videos to decrease output video size (requires HandBrakeCLI)\n";
39     print "   -z                    Recompress input videos to decrease output video size (requires HandBrakeCLI)\n";
40     return 1;
41 }
42 if(defined $opt_h) { usage(); exit 1; }
43 $SIG{'INT'} = sub {die "-E- Killed by CTRL-C\n"};
44
45 ####################################################################################################
46 # Sanity checks
47 if((defined $opt_q || defined $opt_z) && !$use_compute_host && ! -x "$handbrake") { die "-E- Unable to find required program: handbrake\n"; }
48 if(! -d $srcpathname) { &usage; print "-E- Can't find srcpath: $srcpathname\n"; exit 1; }
49 if(defined $opt_h) { $compute_host = $opt_h; }
50 if(! -x $ffmpeg) { die "-E- Missing required executable for ffmpeg: $ffmpeg\n"; }
51
52 my %monthname2month = (
53                        "Jan" => "01",
54                        "Feb" => "02",
55                        "Mar" => "03",
56                        "Apr" => "04",
57                        "May" => "05",
58                        "Jun" => "06",
59                        "Jul" => "07",
60                        "Aug" => "08",
61                        "Sep" => "09",
62                        "Oct" => "10",
63                        "Nov" => "11",
64                        "Dec" => "12"
65                        );
66
67 my %month2monthname = (
68                        "01" => "Jan",
69                        "02" => "Feb",
70                        "03" => "Mar",
71                        "04" => "Apr",
72                        "05" => "May",
73                        "06" => "Jun",
74                        "07" => "Jul",
75                        "08" => "Aug",
76                        "09" => "Sep",
77                        "10" => "Oct",
78                        "11" => "Nov",
79                        "12" => "Dec"
80                        );
81
82 # Change directories to the srcpath to search for videos to merge
83 print "-> Finding all videos under '$srcpathname' to merge by day\n";
84 my %videos;
85 chdir "$srcpathname";
86 print "$find_cmd\n" if($opt_v);
87 foreach $file (sort `$find_cmd`) {
88
89     chomp($file);
90     $srcdir = dirname($file);
91     $file = basename($file);
92     $srcfile = $file;
93     $srcext = "";
94     if($srcfile =~ /\.(\w+)$/) { $srcext = $1; }
95     $ext = "mkv";
96
97     # Throw out files not in the current srcpath
98     if((! -f "$srcfile") && (! -f "$srcdir/$srcfile")) { next; }
99
100     # Throw out encoded files left over from a previous run
101     #print "srcfile: $srcfile\n" if($opt_v);
102     if($srcfile =~ /.hb.mp4/) { next; }
103
104     print "Found video: srcdir: $srcdir srcfile: $srcfile srcext: $srcext dstext: $ext\n" if($opt_v);
105
106     # Make a note of the month, year, and day this video was taken
107     $creation_time = `$ffmpeg -i "$srcdir/$srcfile" 2>&1 | grep "creation_time" | head -n 1 | awk '{print \$3}'`;
108     $brands = `$ffmpeg -i "$srcdir/$srcfile" 2>&1 | grep "compatible_brands" | tail -n 1`; chomp($brands);
109     if($creation_time) {
110         $date_taken = $ffmpeg_time_format_utc->parse_datetime($creation_time);
111         if ($brands && $brands =~ /$local_tz_brands/) {
112             $date_taken = $ffmpeg_time_format_local->parse_datetime($creation_time);
113         }
114     } else {
115         # From the modification time of the file since we couldn't find it in the video file
116         $date_modified = ctime(stat("$srcdir/$srcfile")->mtime);
117     }
118
119     # Get the date taken from the ffmpeg creation_time
120     if(!$merge_by_modification_time && $date_taken) {
121         $date_taken->set_time_zone('local');
122         $year = $date_taken->year;
123         $month = sprintf("%02d",$date_taken->month);
124         $day = sprintf("%02d",$date_taken->day);
125         $monthnum = sprintf("%02d",$date_taken->month);
126         $monthname = lc($month2monthname{$month});
127         #print "date_taken: $year-$month-$day ".$date_taken->hour.":".$date_taken->minute.":".$date_taken->second." ".$date_taken->time_zone."\n";
128     }
129     # Get the date taken from the filename
130     elsif(!$merge_by_modification_date && $srcfile =~ /^(\d\d\d\d)-(\d\d)-(\d\d)/) {
131         $year = $1;
132         $month = $2;
133         $day = sprintf("%02d",$3);
134         $monthnum = $month;
135         $monthname = lc($month2monthname{$month});
136     }
137     elsif(!$merge_by_modification_date && $srcfile =~ /^(\d\d\d\d)(\d\d)(\d\d)/) {
138         $year = $1;
139         $month = $2;
140         $day = sprintf("%02d",$3);
141         $monthnum = $month;
142         $monthname = lc($month2monthname{$month});
143     }
144     # Get the date taken from the srcdir
145     elsif(!$merge_by_modification_date && $srcdir =~ /(\d\d\d\d)-(\d\d)-(\d\d)/) {
146         $year = $1;
147         $month = $2;
148         $day = sprintf("%02d",$3);
149         $monthnum = $month;
150         $monthname = lc($month2monthname{$month});
151     }
152     # Get the date taken from the modification time
153     elsif($date_modified =~ /\S+\s+(\S+)\s+(\d+)\s+\S+\s+(\d+)/) {
154         $year = $3;
155         $month = $1;
156         $day = sprintf("%02d",$2);
157         $monthnum = $monthname2month{$month};
158         $monthname = lc($month);
159     } else {
160         print "-E- Unable to parse year and month from this file: $srcdir/$srcfile\n";
161         next;
162     }
163
164     # We are ready to pick a destination folder to put the merged video in
165     $dstdir = $srcdir;
166     $dstfile = $dstdir . "/" . $year . "-" . $monthnum . "-" . $day;
167
168     # Make a note of this video and its merged destination
169     push(@{$videos{"$dstfile"}}, "\"$srcdir/$srcfile\"");
170 }
171
172 # Tell the user which videos we are going to merge
173 foreach $dstfile (sort keys %{$videos}) {
174     foreach $srcfile (@{$videos{$dstfile}}) { 
175         print "   merging $srcfile into \"$dstfile\"\n";
176     }
177 }
178
179 # Now actually do the merging
180 print "\n";
181 foreach $dstfile (sort keys %videos) {
182
183     my $videos = join(',', @{$videos{$dstfile}});
184     
185     if($dstfile =~ /(\d+)-(\d+)-(\d+)$/) {
186         $year = $1;
187         $month = $2;
188         $day = sprintf("%02d",$3);
189     }
190     
191     my $pwd = `pwd`; chomp($pwd);
192     my $cmd = "";
193     if($use_compute_host) { $cmd .= "ssh $compute_host 'cd \"$pwd\";"; }
194     $cmd .= "$make_mkv -t \"$video_title_prefix $year-$month-$day\" -o \"$dstfile\" -i $videos";
195     if($requantize_input_video) { $cmd .= ' -q'; }
196     if($recompress_input_video) { $cmd .= ' -z'; }
197     if($opt_v) { $cmd .= ' -v'; }
198     if($use_compute_host) { $cmd .= "'"; }
199     if(defined $opt_t) {
200         # Print what will be done, but don't actually do it
201         print "\n-> Creating \"$dstfile\"\n";
202         print "$cmd\n";
203         if(!defined $opt_k) { 
204             foreach $video (@{$videos{$dstfile}}) {
205                 if($opt_v) { print "   $ffmpeg -i $video 2>&1 | grep \"compatible_brands\" | tail -n 1\n"; }
206                 my $brands=`$ffmpeg -i $video 2>&1 | grep "compatible_brands" | tail -n 1`; chomp($brands);
207                 if(($save_originals) && ($video =~ /\.$originals_file_ext/) && (!$brands || $brands !~ /$originals_no_copy_brands/)) {
208                     print "-> Saving the original video $video\n";
209                     if(index($video, basename(dirname($video))) == -1) { 
210                         print("mv $video \"$origpathname/".basename(dirname($video))."_".basename($video)."\n");
211                     } else {
212                         print("mv $video \"$origpathname/".basename($video)."\n");
213                     }
214                 } else {
215                     print "-> Removing the original video $video\n";
216                     print("/bin/bash -c '[[ -e $video ]] && rm -f $video'\n");
217                 }
218             }
219         }
220     } else {
221         # Create the merged video
222         print "$cmd\n" if($opt_v);
223         my $errno = system("$cmd");
224         $errno = $errno >> 8;
225         if($errno) { die "-E- make_mkv encountered some errors with exit code $errno\n"; }
226         system("ls -l \"$srcpathname/\" > /dev/null"); # Make sure the video file is there
227
228         # Fix the permissions
229         system("chown $owner \"$dstfile\"*");
230         system("chgrp $group \"$dstfile\"*");
231         system("find \"$dstfile\"* -type f -exec chmod $mode -- {} +");
232
233         # Remove the individual video files
234         if(!defined $opt_k) { 
235             foreach $srcvideo (@{$videos{$dstfile}}) {
236                 if($opt_v) { print "   $ffmpeg -i $srcvideo 2>&1 | grep \"compatible_brands\" | tail -n 1\n"; }
237                 my $brands=`$ffmpeg -i $srcvideo 2>&1 | grep "compatible_brands" | tail -n 1`; chomp($brands);
238                 if(($save_originals) && ($srcvideo =~ /\.$originals_file_ext/) && (!$brands || $brands !~ /$originals_no_copy_brands/)) {               
239                     print "-> Saving the original video $srcvideo to $origpathname\n";
240                     if(index($srcvideo, basename(dirname($srcvideo))) == -1) { 
241                         system("mv $srcvideo \"$origpathname/".basename(dirname($srcvideo))."_".basename($srcvideo));
242                     } else {
243                         system("mv $srcvideo \"$origpathname/".basename($srcvideo));
244                     }
245                 } else {
246                     print "-> Removing the original video $srcvideo\n";
247                     system("/bin/bash -c '[[ -e $srcvideo ]] && rm -f $srcvideo'");
248                 }
249             }
250         }
251     }
252 }