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