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