Fixed some bugs found in re-testing
[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
11 # Early command line options processing
12 getopts("qkh:tvs:");
13 my $srcpathname = $opt_s;
14
15 ####################################################################################################
16 # Configuration parameters
17 $mydir = `cd \$(dirname $0) 2>/dev/null; pwd`; chomp($mydir); unshift @INC,("$mydir");
18 # Default configuration values
19 require "organize_videos.conf";
20 # Override defaults with local customizations
21 if( -f "$mydir/organize_videos.conf.local") { require "organize_videos.conf.local"; }
22
23 ####################################################################################################
24
25 sub usage {
26     print "usage: $0 [-tvrh] -s <srcpath>\n";
27     print "   -s <srcpath>          specify the path to search for videos to merge under\n";
28     print "   -h <compute host>     specify the remote compute host to submit the mkvmerge job to\n";
29     print "   -v                    verbose mode; print extra information about what is being found/merged\n";
30     print "   -t                    test mode; print what will happen, but don't do anything\n";
31     print "   -k                    keep the individual video files that are merged. By default, after a merge, individual video files that were merged are removed\n";
32     print "   -q                    Requantize MTS input videos to decrease output video size (requires HandBrakeCLI)\n";
33     return 1;
34 }
35 if(defined $opt_h) { usage(); exit 1; }
36
37 # Sanity checks
38 if(defined $opt_q && !$use_compute_host) { die "-E- Unable to find required program: handbrake\n"; }
39 if(! -d $srcpathname) { &usage; print "-E- Can't find srcpath: $srcpathname\n"; exit 1; }
40 if(defined $opt_h) { $compute_host = $opt_h; }
41
42 my %monthname2month = (
43                        "Jan" => "01",
44                        "Feb" => "02",
45                        "Mar" => "03",
46                        "Apr" => "04",
47                        "May" => "05",
48                        "Jun" => "06",
49                        "Jul" => "07",
50                        "Aug" => "08",
51                        "Sep" => "09",
52                        "Oct" => "10",
53                        "Nov" => "11",
54                        "Dec" => "12"
55                        );
56
57 my %month2monthname = (
58                        "01" => "Jan",
59                        "02" => "Feb",
60                        "03" => "Mar",
61                        "04" => "Apr",
62                        "05" => "May",
63                        "06" => "Jun",
64                        "07" => "Jul",
65                        "08" => "Aug",
66                        "09" => "Sep",
67                        "10" => "Oct",
68                        "11" => "Nov",
69                        "12" => "Dec"
70                        );
71
72 # Change directories to the srcpath to search for videos to merge
73 print "-> Finding all videos under '$srcpathname' to merge by day\n";
74 my %videos;
75 chdir "$srcpathname";
76 print "$find_cmd\n" if($opt_v);
77 foreach $file (sort `$find_cmd`) {
78
79     chomp($file);
80     $srcdir = dirname($file);
81     $file = basename($file);
82     $srcfile = $file;
83     $srcext = "";
84     if($srcfile =~ /\.(\w+)$/) { $srcext = $1; }
85     $ext = "mkv";
86     
87     print "Found movie: srcdir: $srcdir srcfile: $srcfile srcext: $srcext dstext: $ext\n" if($opt_v);
88
89     # Throw out files not in the current srcpath
90     if((! -f "$srcfile") && (! -f "$srcdir/$srcfile")) { next; }
91             
92     # Make a note of the month, year, and day this video was taken (from the modification time of the file)
93     $date_taken = ctime(stat("$srcdir/$srcfile")->mtime);
94
95     # Get the date taken from the filename
96     if($srcfile =~ /^(\d+)-(\d+)-(\d+)/) {
97         $year = $1;
98         $month = $2;
99         $day = sprintf("%02d",$3);
100         $monthnum = $month;
101         $monthname = lc($month2monthname{$month});
102     }
103     # Get the date taken from the modification time
104     elsif($date_taken =~ /\S+\s+(\S+)\s+(\d+)\s+\S+\s+(\d+)/) {
105         $year = $3;
106         $month = $1;
107         $day = sprintf("%02d",$2);
108         $monthnum = $monthname2month{$month};
109         $monthname = lc($month2monthname{$month});
110     } else {
111         print "-E- Unable to parse year and month from this file: $srcdir/$srcfile\n";
112         next;
113     }
114
115     # We are ready to pick a destination folder to put the merged video in
116     $dstdir = $srcdir;
117     $dstfile = $dstdir . "/" . $year . "-" . $monthnum . "-" . $day;
118
119     # Check for duplicate filenames at the destination
120     $newfile = $dstfile . "." . $video_suffix;
121     if(-e "$newfile.$ext") {
122         foreach $i ($video_suffix+1 .. '999') {
123             $newfile = $dstfile . "." . sprintf("%03d",$i);
124             if(! -e "$newfile.$ext") { last; }
125         }
126         $dstfile = $newfile;
127     }
128
129     # Set the name of our unique destination file
130     $dstfile = "$newfile.$ext";
131
132     # You can only merge videos into a single destination that have the same extension/type
133     push(@{$videos{"$srcext"}{"$dstfile"}}, "\"$srcdir/$srcfile\"");
134 }
135
136 # For single videos, with the re-quantize option given, rename the destination file to mp4
137 foreach $ext (sort keys %videos) {
138     foreach $video (sort keys %{$videos{$ext}}) {       
139         # Get a count of the number of videos for this date
140         # If we only have a single video, its extension will actually be mp4 if opt_q is specified
141         my $num_videos = $#{$videos{$ext}{$video}} + 1;
142         if((defined $opt_q) && ($num_videos <= 1)) {
143             if($video =~ /(.*?)\.(\d+)\.(\w+)$/) {
144                 $dstfile = $1;
145                 $dstnum = $2;
146                 $new_dstvideo = "$1.$2.mp4";
147                 $videos{$ext}{$new_dstvideo} = $videos{$ext}{$video}; # make a new dst video entry with the src video being the same
148                 delete $videos{$ext}{$video}; # delete the old destination video from the hash
149             }
150         }
151     }
152 }
153
154 # Check for duplicate filenames in the dstfiles being created for other exts
155 foreach $ext (sort keys %videos) {
156     foreach $video (sort keys %{$videos{$ext}}) {       
157         # Make sure this video name is not in use as a destination for any other ext
158         foreach $checkext (sort keys %videos) {
159             if($checkext eq $ext) { next; }
160             foreach $checkvideo (sort keys %{$videos{$checkext}}) {
161                 if("$video" eq "$checkvideo") {
162                     if($video =~ /(.*?)\.(\d+)\.(\w+)$/) {
163                         $dstfile = $1;
164                         $dstnum = $2;
165                         $dstext = $3;
166                     }
167                     foreach $i ($dstnum .. '999') {
168                         $newfile = $dstfile . "." . sprintf("%03d",$i);
169                         if("$video" ne "$newfile.$dstext") { last; }
170                     }
171                     $videos{$ext}{"$newfile.$dstext"} = $videos{$ext}{$video};
172                     delete $videos{$ext}{$video};
173                 }
174             }
175         }
176     }
177 }
178
179 # Only merge the videos if there is more than 1 video to merge on a given day for a given ext
180 # If there is only 1 video for a given day for a given ext, re-quantize it here if that option was given
181 foreach $ext (sort keys %videos) {
182     foreach $video (sort keys %{$videos{$ext}}) {
183         
184         # Get a count of the number of videos for this date
185         my $num_videos = $#{$videos{$ext}{$video}} + 1;
186
187         # Process any single videos now
188         if($num_videos <= 1) {
189
190             # Store the srcvideo name
191             my $srcvideo = $videos{$ext}{$video}[0];
192             my $pwd = `pwd`; chomp($pwd);
193
194             # Make a note if this video is interlaced or not
195             my $ffmpeg_cmd = "";
196             if($use_compute_host) { $ffmpeg_cmd .= "ssh $compute_host 'cd \"$pwd\";"; }
197             $ffmpeg_cmd .= "$ffmpeg -i $srcvideo 2>&1 | grep -q \"frame rate differs\"";
198             if($use_compute_host) { $ffmpeg_cmd .= "'"; }
199             my $progressive = system('$ffmpeg_cmd');
200             if(!$progressive) { print "   Detected interlaced video content: $srcvideo\n"; }
201             
202             # Re-quantize the input video to reduce the resulting output filesize
203             # This also gives us a chance to deinterlace the video as well
204             # Only do this for .MTS videos
205             if((defined $opt_q) && ($ext =~ /mts/i)) {
206                 
207                 # Set our requantize factor accordingly
208                 my $requantize_option = "";
209                 if(!$progressive) { $requantize_option = "-q $interlaced_requantize_quality"; }
210                 else { $requantize_option = "-q $progressive_requantize_quality"; }
211                 
212                 # Set our de-interlace option accordingly
213                 my $deinterlace_option = "";
214                 if(!$progressive) { $deinterlace_option = "-d"; }
215                 
216                 # Use HandBrake to requantize/deinterlace the input video
217                 print "   Re-quantizing input video content: $video\n";
218                 my $handbrake_cmd = "";
219                 if($use_compute_host) { $handbrake_cmd .= "ssh $compute_host 'cd \"$pwd\";"; }
220                 $handbrake_cmd .= "$handbrake $deinterlace_option $requantize_option $handbrake_options -i $srcvideo -o \"$video\" > /dev/null 2>&1";
221                 if($use_compute_host) { $handbrake_cmd .= "'"; }
222                 if(! defined $opt_t) { 
223                     my $errno = system("$handbrake_cmd");
224                     $errno = $errno >> 8;
225                     if($errno > 1) {
226                         unlink "$video";
227                         die "-E- handbrake encountered some errors with exit code $errno\n";
228                     } else {
229                         # Remove the original srcvideo since we created a new version of it that we are going to keep instead
230                         if(!defined $opt_k) { 
231                             system("rm -f $srcvideo\n");
232                         }
233                     }
234                 }
235             }
236
237             # Remove the video from the array since we already processed it above
238             delete $videos{$ext}{$video};
239             next;
240         }
241     }
242 }
243
244 # Tell the user which videos we are going to merge
245 foreach $ext (sort keys %videos) {
246     foreach $video (sort keys %{$videos{$ext}}) {
247         foreach $srcfile (@{$videos{$ext}{$video}}) { 
248             print "   merging \"$srcfile\" into \"$video\"\n";
249         }
250     }
251 }
252
253 # Now actually do the merging
254 print "\n";
255 foreach $ext (sort keys %videos) {
256     foreach $video (sort keys %{$videos{$ext}}) {
257
258         my $videos = join(',', @{$videos{$ext}{$video}});
259         
260         if($video =~ /(\d+)-(\d+)-(\d+)/) {
261             $year = $1;
262             $month = $2;
263             $day = sprintf("%02d",$3);
264         }
265         
266         my $pwd = `pwd`; chomp($pwd);
267         my $cmd = "";
268         if($use_compute_host) { $cmd .= "ssh $compute_host 'cd \"$pwd\";"; }
269         $cmd .= "$make_mkv -t \"$video_title_prefix $year-$month-$day\" -o \"$video\" -i $videos";
270         if($requantize_input_video) { $cmd .= ' -q'; }
271         if($use_compute_host) { $cmd .= "'"; }
272         if(defined $opt_t) {
273             print "\n-> Creating \"$video\"\n";
274             print "$cmd\n";
275             if(!defined $opt_k) { 
276                 foreach $video (@{$videos{$ext}{$video}}) {
277                     print("rm -f $video\n");
278                 }
279             }
280         } else {
281             # Create the merged video
282             my $errno = system("$cmd");
283             $errno = $errno >> 8;
284             if($errno) { die "-E- make_mkv encountered some errors with exit code $errno\n"; }
285             system("ls -l \"$srcpathname/\" > /dev/null"); # Make sure the video file is there
286             # Fix the permissions
287             system("chown $owner \"$video\"");
288             system("chgrp $group \"$video\"");
289             system("chmod $mode \"$video\"");
290             # Remove the individual video files
291             if(!defined $opt_k) { 
292                 foreach $srcvideo (@{$videos{$ext}{$video}}) {
293                     system("rm -f $srcvideo");
294                 }
295             }
296         }
297     }
298 }