4a58f0fce3d398c5561402f573ff18c7e4f11ab8
[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("qzkh: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 [-tvrhz] -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 input videos to decrease output video size (requires HandBrakeCLI)\n";
33     print "   -z                    Recompress input videos to decrease output video size (requires HandBrakeCLI)\n";
34     return 1;
35 }
36 if(defined $opt_h) { usage(); exit 1; }
37
38 # Sanity checks
39 if((defined $opt_q || defined $opt_z) && !$use_compute_host && ! -x "$handbrake") { die "-E- Unable to find required program: handbrake\n"; }
40 if(! -d $srcpathname) { &usage; print "-E- Can't find srcpath: $srcpathname\n"; exit 1; }
41 if(defined $opt_h) { $compute_host = $opt_h; }
42
43 my %monthname2month = (
44                        "Jan" => "01",
45                        "Feb" => "02",
46                        "Mar" => "03",
47                        "Apr" => "04",
48                        "May" => "05",
49                        "Jun" => "06",
50                        "Jul" => "07",
51                        "Aug" => "08",
52                        "Sep" => "09",
53                        "Oct" => "10",
54                        "Nov" => "11",
55                        "Dec" => "12"
56                        );
57
58 my %month2monthname = (
59                        "01" => "Jan",
60                        "02" => "Feb",
61                        "03" => "Mar",
62                        "04" => "Apr",
63                        "05" => "May",
64                        "06" => "Jun",
65                        "07" => "Jul",
66                        "08" => "Aug",
67                        "09" => "Sep",
68                        "10" => "Oct",
69                        "11" => "Nov",
70                        "12" => "Dec"
71                        );
72
73 # Change directories to the srcpath to search for videos to merge
74 print "-> Finding all videos under '$srcpathname' to merge by day\n";
75 my %videos;
76 chdir "$srcpathname";
77 print "$find_cmd\n" if($opt_v);
78 foreach $file (sort `$find_cmd`) {
79
80     chomp($file);
81     $srcdir = dirname($file);
82     $file = basename($file);
83     $srcfile = $file;
84     $srcext = "";
85     if($srcfile =~ /\.(\w+)$/) { $srcext = $1; }
86     $ext = "mkv";
87     
88     print "Found movie: srcdir: $srcdir srcfile: $srcfile srcext: $srcext dstext: $ext\n" if($opt_v);
89
90     # Throw out files not in the current srcpath
91     if((! -f "$srcfile") && (! -f "$srcdir/$srcfile")) { next; }
92             
93     # Make a note of the month, year, and day this video was taken (from the modification time of the file)
94     $date_taken = ctime(stat("$srcdir/$srcfile")->mtime);
95     
96     # Get the date taken from the filename
97     if(!$merge_by_modification_date && $srcfile =~ /^(\d+)-(\d+)-(\d+)/) {
98         $year = $1;
99         $month = $2;
100         $day = sprintf("%02d",$3);
101         $monthnum = $month;
102         $monthname = lc($month2monthname{$month});
103     }
104     elsif(!$merge_by_modification_date && $srcfile =~ /^(\d\d\d\d)(\d\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 srcdir
112     elsif(!$merge_by_modification_date && $srcdir =~ /(\d+)-(\d+)-(\d+)/) {
113         $year = $1;
114         $month = $2;
115         $day = sprintf("%02d",$3);
116         $monthnum = $month;
117         $monthname = lc($month2monthname{$month});
118     }
119     # Get the date taken from the modification time
120     elsif($date_taken =~ /\S+\s+(\S+)\s+(\d+)\s+\S+\s+(\d+)/) {
121         $year = $3;
122         $month = $1;
123         $day = sprintf("%02d",$2);
124         $monthnum = $monthname2month{$month};
125         $monthname = lc($month2monthname{$month});
126     } else {
127         print "-E- Unable to parse year and month from this file: $srcdir/$srcfile\n";
128         next;
129     }
130
131     # We are ready to pick a destination folder to put the merged video in
132     $dstdir = $srcdir;
133     $dstfile = $dstdir . "/" . $year . "-" . $monthnum . "-" . $day;
134
135     # Check for duplicate filenames at the destination
136     $newfile = $dstfile . "." . $video_suffix;
137     if(-e "$newfile.$ext") {
138         foreach $i ($video_suffix+1 .. '999') {
139             $newfile = $dstfile . "." . sprintf("%03d",$i);
140             if(! -e "$newfile.$ext") { last; }
141         }
142         $dstfile = $newfile;
143     }
144
145     # Set the name of our unique destination file
146     $dstfile = "$newfile.$ext";
147
148     # You can only merge videos into a single destination that have the same extension/type
149     push(@{$videos{"$srcext"}{"$dstfile"}}, "\"$srcdir/$srcfile\"");
150 }
151
152 # Check for duplicate filenames in the dstfiles being created for other exts
153 foreach $ext (sort keys %videos) {
154     foreach $video (sort keys %{$videos{$ext}}) {       
155         # Make sure this video name is not in use as a destination for any other ext
156         foreach $checkext (sort keys %videos) {
157             if($checkext eq $ext) { next; }
158             foreach $checkvideo (sort keys %{$videos{$checkext}}) {
159                 if("$video" eq "$checkvideo") {
160                     if($video =~ /(.*?)\.(\d+)\.(\w+)$/) {
161                         $dstfile = $1;
162                         $dstnum = $2;
163                         $dstext = $3;
164                     }
165                     foreach $i ($dstnum .. '999') {
166                         $newfile = $dstfile . "." . sprintf("%03d",$i);
167                         if("$video" ne "$newfile.$dstext") { last; }
168                     }
169                     $videos{$ext}{"$newfile.$dstext"} = $videos{$ext}{$video};
170                     delete $videos{$ext}{$video};
171                 }
172             }
173         }
174     }
175 }
176
177 # Tell the user which videos we are going to merge
178 foreach $ext (sort keys %videos) {
179     foreach $video (sort keys %{$videos{$ext}}) {
180         foreach $srcfile (@{$videos{$ext}{$video}}) { 
181             print "   merging $srcfile into \"$video\"\n";
182         }
183     }
184 }
185
186 # Now actually do the merging
187 print "\n";
188 foreach $ext (sort keys %videos) {
189     foreach $video (sort keys %{$videos{$ext}}) {
190
191         my $videos = join(',', @{$videos{$ext}{$video}});
192         
193         if($video =~ /(\d+)-(\d+)-(\d+)/) {
194             $year = $1;
195             $month = $2;
196             $day = sprintf("%02d",$3);
197         }
198         
199         my $pwd = `pwd`; chomp($pwd);
200         my $cmd = "";
201         if($use_compute_host) { $cmd .= "ssh $compute_host 'cd \"$pwd\";"; }
202         $cmd .= "$make_mkv -t \"$video_title_prefix $year-$month-$day\" -o \"$video\" -i $videos";
203         if($requantize_input_video) { $cmd .= ' -q'; }
204         if($recompress_input_video) { $cmd .= ' -z'; }
205         if($use_compute_host) { $cmd .= "'"; }
206         if(defined $opt_t) {
207             # Print what will be done, but don't actually do it
208             print "\n-> Creating \"$video\"\n";
209             print "$cmd\n";
210             if(!defined $opt_k) { 
211                 foreach $video (@{$videos{$ext}{$video}}) {
212                     if(($save_originals) && ($video =~ /\.$originals_file_ext/)) {
213                         print "-> Saving the original video $video\n";
214                         print("mv $video \"$origpathname/".basename(dirname($video))."_".basename($video)."\n");
215                     } else {
216                         print "-> Removing the original video $video\n";
217                         print("/bin/bash -c '[[ -e $video ]] && rm -f $video'\n");
218                     }
219                 }
220             }
221         } else {
222             # Create the merged video
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             # Fix the permissions
228             system("chown $owner \"$video\"");
229             system("chgrp $group \"$video\"");
230             system("chmod $mode \"$video\"");
231             # Remove the individual video files
232             if(!defined $opt_k) { 
233                 foreach $srcvideo (@{$videos{$ext}{$video}}) {
234                     if(($save_originals) && ($srcvideo =~ /\.$originals_file_ext/)) {
235                         print "-> Saving the original video $srcvideo to $origpathname\n";
236                         system("mv $srcvideo \"$origpathname/".basename(dirname($srcvideo))."_".basename($srcvideo));
237                     } else {
238                         print "-> Removing the original video $srcvideo\n";
239                         system("/bin/bash -c '[[ -e $srcvideo ]] && rm -f $srcvideo'");
240                     }
241                 }
242             }
243         }
244     }
245 }