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