Fixed a few bugs
[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 $SIG{'INT'} = sub {die "-E- Killed by CTRL-C\n"};
38
39 ####################################################################################################
40 # Sanity checks
41 if((defined $opt_q || defined $opt_z) && !$use_compute_host && ! -x "$handbrake") { die "-E- Unable to find required program: handbrake\n"; }
42 if(! -d $srcpathname) { &usage; print "-E- Can't find srcpath: $srcpathname\n"; exit 1; }
43 if(defined $opt_h) { $compute_host = $opt_h; }
44 if(! -x $ffmpeg) { die "-E- Missing required executable for ffmpeg: $ffmpeg\n"; }
45
46 my %monthname2month = (
47                        "Jan" => "01",
48                        "Feb" => "02",
49                        "Mar" => "03",
50                        "Apr" => "04",
51                        "May" => "05",
52                        "Jun" => "06",
53                        "Jul" => "07",
54                        "Aug" => "08",
55                        "Sep" => "09",
56                        "Oct" => "10",
57                        "Nov" => "11",
58                        "Dec" => "12"
59                        );
60
61 my %month2monthname = (
62                        "01" => "Jan",
63                        "02" => "Feb",
64                        "03" => "Mar",
65                        "04" => "Apr",
66                        "05" => "May",
67                        "06" => "Jun",
68                        "07" => "Jul",
69                        "08" => "Aug",
70                        "09" => "Sep",
71                        "10" => "Oct",
72                        "11" => "Nov",
73                        "12" => "Dec"
74                        );
75
76 # Change directories to the srcpath to search for videos to merge
77 print "-> Finding all videos under '$srcpathname' to merge by day\n";
78 my %videos;
79 chdir "$srcpathname";
80 print "$find_cmd\n" if($opt_v);
81 foreach $file (sort `$find_cmd`) {
82
83     chomp($file);
84     $srcdir = dirname($file);
85     $file = basename($file);
86     $srcfile = $file;
87     $srcext = "";
88     if($srcfile =~ /\.(\w+)$/) { $srcext = $1; }
89     $ext = "mkv";
90
91     # Throw out files not in the current srcpath
92     if((! -f "$srcfile") && (! -f "$srcdir/$srcfile")) { next; }
93
94     # Throw out encoded files left over from a previous run
95     #print "srcfile: $srcfile\n" if($opt_v);
96     if($srcfile =~ /.hb.mp4/) { next; }
97
98     print "Found video: srcdir: $srcdir srcfile: $srcfile srcext: $srcext dstext: $ext\n" if($opt_v);
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(!$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     elsif(!$merge_by_modification_date && $srcfile =~ /^(\d\d\d\d)(\d\d)(\d\d)/) {
112         $year = $1;
113         $month = $2;
114         $day = sprintf("%02d",$3);
115         $monthnum = $month;
116         $monthname = lc($month2monthname{$month});
117     }
118     # Get the date taken from the srcdir
119     elsif(!$merge_by_modification_date && $srcdir =~ /(\d\d\d\d)-(\d\d)-(\d\d)/) {
120         $year = $1;
121         $month = $2;
122         $day = sprintf("%02d",$3);
123         $monthnum = $month;
124         $monthname = lc($month2monthname{$month});
125     }
126     # Get the date taken from the modification time
127     elsif($date_taken =~ /\S+\s+(\S+)\s+(\d+)\s+\S+\s+(\d+)/) {
128         $year = $3;
129         $month = $1;
130         $day = sprintf("%02d",$2);
131         $monthnum = $monthname2month{$month};
132         $monthname = lc($month);
133     } else {
134         print "-E- Unable to parse year and month from this file: $srcdir/$srcfile\n";
135         next;
136     }
137
138     # We are ready to pick a destination folder to put the merged video in
139     $dstdir = $srcdir;
140     $dstfile = $dstdir . "/" . $year . "-" . $monthnum . "-" . $day;
141
142     # Make a note of this video and its merged destination
143     push(@{$videos{"$dstfile"}}, "\"$srcdir/$srcfile\"");
144 }
145
146 # Tell the user which videos we are going to merge
147 foreach $dstfile (sort keys %{$videos}) {
148     foreach $srcfile (@{$videos{$dstfile}}) { 
149         print "   merging $srcfile into \"$dstfile\"\n";
150     }
151 }
152
153 # Now actually do the merging
154 print "\n";
155 foreach $dstfile (sort keys %videos) {
156
157     my $videos = join(',', @{$videos{$dstfile}});
158     
159     if($dstfile =~ /(\d+)-(\d+)-(\d+)/) {
160         $year = $1;
161         $month = $2;
162         $day = sprintf("%02d",$3);
163     }
164     
165     my $pwd = `pwd`; chomp($pwd);
166     my $cmd = "";
167     if($use_compute_host) { $cmd .= "ssh $compute_host 'cd \"$pwd\";"; }
168     $cmd .= "$make_mkv -t \"$video_title_prefix $year-$month-$day\" -o \"$dstfile\" -i $videos";
169     if($requantize_input_video) { $cmd .= ' -q'; }
170     if($recompress_input_video) { $cmd .= ' -z'; }
171     if($opt_v) { $cmd .= ' -v'; }
172     if($use_compute_host) { $cmd .= "'"; }
173     if(defined $opt_t) {
174         # Print what will be done, but don't actually do it
175         print "\n-> Creating \"$dstfile\"\n";
176         print "$cmd\n";
177         if(!defined $opt_k) { 
178             foreach $video (@{$videos{$dstfile}}) {
179                 if($opt_v) { print "   $ffmpeg -i $video 2>&1 | grep \"compatible_brands\" | tail -n 1\n"; }
180                 my $brands=`$ffmpeg -i $video 2>&1 | grep "compatible_brands" | tail -n 1`; chomp($brands);
181                 if(($save_originals) && ($video =~ /\.$originals_file_ext/) && (!$brands || $brands !~ /$originals_no_copy_brands/)) {
182                     print "-> Saving the original video $video\n";
183                     if(index($video, basename(dirname($video))) == -1) { 
184                         print("mv $video \"$origpathname/".basename(dirname($video))."_".basename($video)."\n");
185                     } else {
186                         print("mv $video \"$origpathname/".basename($video)."\n");
187                     }
188                 } else {
189                     print "-> Removing the original video $video\n";
190                     print("/bin/bash -c '[[ -e $video ]] && rm -f $video'\n");
191                 }
192             }
193         }
194     } else {
195         # Create the merged video
196         print "$cmd\n" if($opt_v);
197         my $errno = system("$cmd");
198         $errno = $errno >> 8;
199         if($errno) { die "-E- make_mkv encountered some errors with exit code $errno\n"; }
200         system("ls -l \"$srcpathname/\" > /dev/null"); # Make sure the video file is there
201
202         # Fix the permissions
203         system("chown $owner \"$dstfile\"*");
204         system("chgrp $group \"$dstfile\"*");
205         system("find \"$dstfile\"* -type f -exec chmod $mode -- {} +");
206
207         # Remove the individual video files
208         if(!defined $opt_k) { 
209             foreach $srcvideo (@{$videos{$dstfile}}) {
210                 if($opt_v) { print "   $ffmpeg -i $srcvideo 2>&1 | grep \"compatible_brands\" | tail -n 1\n"; }
211                 my $brands=`$ffmpeg -i $srcvideo 2>&1 | grep "compatible_brands" | tail -n 1`; chomp($brands);
212                 if(($save_originals) && ($srcvideo =~ /\.$originals_file_ext/) && (!$brands || $brands !~ /$originals_no_copy_brands/)) {               
213                     print "-> Saving the original video $srcvideo to $origpathname\n";
214                     if(index($srcvideo, basename(dirname($srcvideo))) == -1) { 
215                         system("mv $srcvideo \"$origpathname/".basename(dirname($srcvideo))."_".basename($srcvideo));
216                     } else {
217                         system("mv $srcvideo \"$origpathname/".basename($srcvideo));
218                     }
219                 } else {
220                     print "-> Removing the original video $srcvideo\n";
221                     system("/bin/bash -c '[[ -e $srcvideo ]] && rm -f $srcvideo'");
222                 }
223             }
224         }
225     }
226 }