Added code to better detect video codecs
[videoscripts/.git] / organize_videos
1 #!/usr/bin/perl
2 # Author: Alan J. Pippin
3 # Description: Find videos from a temporary dropbox location and merge and move them into their final destination.
4
5 use File::Copy;
6 use File::Basename;
7 use Getopt::Std;
8 use File::stat;
9 use Time::localtime;
10 use File::Pid;
11
12 ####################################################################################################
13 # Configuration parameters
14 $mydir = `cd \$(dirname $0) 2>/dev/null; pwd`; chomp($mydir); unshift @INC,("$mydir");
15 # Default configuration values
16 require "organize_videos.conf";
17 # Override defaults with local customizations
18 if( -f "$mydir/organize_videos.conf.local") { require "organize_videos.conf.local"; }
19
20 ####################################################################################################
21
22 # Sanity check
23 if(! -d $srcpathname) { print "-E- Can't find srcpath: $srcpathname\n"; exit 1; }
24 if(! -d $dstpathname) { print "-E- Can't find dstpath: $dstpathname\n"; exit 1; }
25 if(! -x $merge_videos_by_day) { print "-E- Can't find required script: $merge_videos_by_day\n"; exit 1; }
26
27 my %monthname2month = (
28                        "Jan" => "01",
29                        "Feb" => "02",
30                        "Mar" => "03",
31                        "Apr" => "04",
32                        "May" => "05",
33                        "Jun" => "06",
34                        "Jul" => "07",
35                        "Aug" => "08",
36                        "Sep" => "09",
37                        "Oct" => "10",
38                        "Nov" => "11",
39                        "Dec" => "12"
40                        );
41
42 my %month2monthname = (
43                        "01" => "Jan",
44                        "02" => "Feb",
45                        "03" => "Mar",
46                        "04" => "Apr",
47                        "05" => "May",
48                        "06" => "Jun",
49                        "07" => "Jul",
50                        "08" => "Aug",
51                        "09" => "Sep",
52                        "10" => "Oct",
53                        "11" => "Nov",
54                        "12" => "Dec"
55                        );
56
57 getopts("htvnkpfd:");
58
59 sub usage {
60     print "usage: $0 [-v] [-t] [-r] [-p] [-f] [-d <dir>]\n";
61     print "   -v        verbose; print file being moved (to).\n";
62     print "   -t        test; print what will happen, but don't do anything\n";
63     print "   -f        force it to run by ignoring the \$minage setting in organize_videos.conf\n";
64     print "   -n        do not copy to dest; do not copy the resultant video files to the destination dir\n";
65     print "   -k        keep the individual video files that are merged. By default, after a merge, individual video files that were merged are removed\n";
66     print "   -p        only recreate video playlists, do not process any video files. Do this for each year & month of video clips in the directory specified by -d <dir>.\n";
67     print "   -d <dir>  directory to recreate the playlists in. Only needed if -p option is given\n";
68     return 1;
69 }
70 $SIG{'INT'} = sub {die "-E- Killed by CTRL-C\n"};
71
72 sub is_folder_empty {
73     my $dirname = shift;
74     opendir(my $dh, $dirname) or die "Not a directory";
75     return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0;
76 }
77
78 sub create_playlists {
79     my ($dstdirs) = @_;
80     
81     foreach $dstdir (keys %{$dstdirs}) {
82         print "-> Recreating playlists in: $dstdir\n";
83         print "-> Creating playlists for each month & year of clips from this directory: $video_directory\n";
84         opendir(VIDEODIR, "$dstdir") or die "-E- could not open: $dstdir\n";
85         chdir "$dstdir" || die "-E- Unable to change directory to the dstdir: $dstdir\n";
86         
87         my @all_files = readdir VIDEODIR;
88         closedir(VIDEODIR);
89         @all_files = sort @all_files;
90
91         print "   Removing all existing playlists from the directory\n";
92         if(! defined $opt_t) { system("rm *.$playlist_extension > /dev/null 2>&1"); }
93     
94         foreach $file (@all_files) {
95             next if -d $file;
96             next if ($file !~ /\.avi$/i && $file !~ /\.mpg$/i && $file !~ /\.mkv$/i && $file !~ /\.3gp$/i && $file !~ /\.mov$/i && $file !~ /\.mts$/i);
97             if($file =~ /(\d\d\d\d)-(\d\d)-(\d\d)/) {
98                 $year = $1; $month = $2;
99                 print "   Adding $file to $year.$playlist_extension & $year-$month.$playlist_extension\n";
100                 if(! defined $opt_t) { system("echo \"$file\" >> $year.$playlist_extension"); }
101                 if(! defined $opt_t) { system("echo \"$file\" >> $year-$month.$playlist_extension"); }
102             } else {
103                 print "   Skipping $file since we can't extract the year and month from it\n"; 
104             }
105         }
106
107         # Fix the permissions
108         system("chown $owner \"$dstdir/\"*.$playlist_extension");
109         system("chgrp $group \"$dstdir/\"*.$playlist_extension");
110         system("chmod $mode \"$dstdir/\"*.$playlist_extension");
111    } 
112 }
113
114 # Sanity checks / Option processing
115 if(defined $opt_h) { usage(); exit 1; }
116 if(defined $opt_p) {
117     if(defined $opt_d) {
118         my %dstdirs = ("$opt_d",1); 
119         create_playlists(\%dstdirs);
120     } else {
121         die "-E- You must specify the -d <dir> option when using the -p option\n"; 
122     }
123     exit 0;
124 }
125
126 # Only proceed if there are video files to organize
127 $video_files_found=`$find_cmd_with_mkv`;
128 if(!$video_files_found) { exit 0; }
129
130 # Only proceed if no files have changed in the past $cmin minutes
131 if(! $opt_f) { 
132   $changed_files_found=`$find_changed_cmd`;
133   if($changed_files_found) { exit 0; }
134 }
135
136 # Only one instance of this script running at a time
137 my $pidfile = File::Pid->new({file => "$pid_file", pid => "$$"});
138 exit if $pidfile->running();
139 $pidfile->write();
140
141 # Print the date
142 system("date");
143
144 # Merge videos prior to copying them over to the destination path
145 my $errno = 0;
146 my $merge_opts = "";
147 if(defined $opt_t) { $merge_opts .= "-t "; }
148 if(defined $opt_k) { $merge_opts .= "-k "; }
149 if(defined $opt_v) { $merge_opts .= "-v "; }
150 if($requantize_input_video) { $merge_opts .= ' -q'; }
151 if($recompress_input_video) { $merge_opts .= ' -z'; }
152 $errno=system("$merge_videos_by_day -s \"$srcpathname\" $merge_opts");
153 $errno = $errno >> 8;
154 if($errno) { die "-E- $merge_videos_by_day encountered some errors with exit code $errno\n"; }
155
156 # Exit now if we are not supposed to copy the resultant video files to the destination path
157 if(defined $opt_n) {
158     $pidfile->remove();
159     print "\n\n";
160     exit 0;
161 }
162
163 # Copy the videos over to the destination path
164 my %dstdirs;
165 chdir "$srcpathname";
166 print "$find_mkv\n" if($opt_v);
167 foreach $file (`$find_mkv`) {
168
169     chomp($file);
170     $srcdir = dirname($file);
171     $file = basename($file);
172     $srcfile = $file;
173     $ext = $file; $ext =~ s/.*\.(\S+)$/$1/; $ext = lc($ext);
174     
175     # Throw out files not in the current srcpath
176     if((! -f "$srcfile") && (! -f "$srcdir/$srcfile")) { next; }
177
178     # Throw out encoded files left over from a previous run
179     print "srcfile: $srcfile\n";
180     if($srcfile =~ /.hb.mp4/) { next; }
181     
182     print "Found movie: srcdir: $srcdir srcfile: $srcfile ext: $ext\n" if($opt_v);
183         
184     # Make a note of the month, year, and day this video was taken (from the modification time of the file)
185     $date_taken = ctime(stat("$srcdir/$srcfile")->mtime);
186
187     # Get the date taken from the filename
188     if($srcfile =~ /^(\d+)-(\d+)-(\d+)/) {
189         $year = $1;
190         $month = $2;
191         $day = sprintf("%02d",$3);
192         $monthnum = $month;
193         $monthname = lc($month2monthname{$month});
194     }
195     elsif($srcfile =~ /^(\d\d\d\d)(\d\d)(\d\d)/) {
196         $year = $1;
197         $month = $2;
198         $day = sprintf("%02d",$3);
199         $monthnum = $month;
200         $monthname = lc($month2monthname{$month});
201     }
202     # Get the date taken from the source directory
203     elsif($srcdir =~ /(\d+)-(\d+)-(\d+)/) {
204         $year = $1;
205         $month = $2;
206         $day = sprintf("%02d",$3);
207         $monthnum = $month;
208         $monthname = lc($month2monthname{$month});
209     }
210     # Get the date taken from the modification time
211     elsif($date_taken =~ /\S+\s+(\S+)\s+(\d+)\s+\S+\s+(\d+)/) {
212         $year = $3;
213         $month = $1;
214         $day = sprintf("%02d",$2);
215         $monthnum = $monthname2month{$month};
216         $monthname = lc($month);
217     } else {
218         print "-E- Unable to parse year and month from this file: $srcdir/$srcfile\n";
219         next;
220     }
221
222     # We are ready to pick a destination folder to put the video in
223     $dstdir = $dstpathname . "/" . $year;
224     $dstdirs{$dstdir} = 1;
225     $dstfile = $dstdir . "/" . $year . "-" . $monthnum . "-" . $day;
226
227     # Check for duplicate filenames at the destination
228     $newfile = $dstfile . "." . $video_suffix;
229     if(-e "$newfile.$ext") {
230         foreach $i ($video_suffix+1 .. '999') {
231             $newfile = $dstfile . "." . sprintf("%03d",$i);;
232             if(! -e "$newfile.$ext") { last; }
233         }
234         $dstfile = $newfile;
235     }
236     $dstfile = "$newfile.$ext";
237
238     if(defined $opt_t) {
239         print "-> Moving \"$srcdir/$srcfile\" to \"$dstfile\"\n";
240     } else {
241         # Make sure the destination directories exist
242         $errno=system("mkdir -p -m $dirmode \"$dstdir\"");
243         if($errno) { print "-E- Error creating dstdir: $dstdir\n"; next; }
244         # Perform the move operation from $srcdir/$srcfile -> $dstfile
245         print "-> Moving \"$srcdir/$srcfile\" to \"$dstfile\"\n";
246         # Make sure the dstfile doesn't exist, if it does, don't do the move
247         if(! -f "$dstfile") {
248             $errno=system("mv \"$srcdir/$srcfile\" \"$dstfile\" 2>/dev/null");
249             if($errno) { print "-E- Error moving srcfile to dstfile: $srcdir/$srcfile -> $dstfile\n"; next; }
250         } else {
251             print "-> Skipping \"$srcdir/$srcfile\". Destfile \"$dstfile\" already exists.\n";
252         }
253         # Fix the permissions
254         system("chown $owner \"$dstfile\"");
255         system("chgrp $group \"$dstfile\"");
256         system("chmod $mode \"$dstfile\"");
257     }
258     
259     # Check to see if there is an empty sub directory to remove
260     if(($srcdir ne $srcpathname) && ($srcpathname ne ".")) { 
261         if(is_folder_empty($srcdir)) { 
262             print "-> Subdir detected for videos ($srcdir != $srcpathname)\n" if($opt_v);
263             if(! defined $opt_t) { 
264                 $tmpdir=`tempfile`;
265                 system("rm $tmpdir");
266                 system("cp -R \"$srcdir\" $tmpdir > /dev/null 2>/dev/null");
267                 system("rm -rf \"$srcdir\"");
268                 print "-> Moved empty subdir $srcdir to $tmpdir\n" if($opt_v);
269             }
270         }
271     }
272 }
273
274 # For each destination dir we copied new content into, recreate the playlists
275 create_playlists(\%dstdirs);
276
277 $pidfile->remove();
278
279 print "\n\n";