Fixed interlace/progressive detection check in make_mkv
[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("htvnkpd:");
58
59 sub usage {
60     print "usage: $0 [-v] [-t] [-r] [-p] [-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 "   -n        do not copy to dest; do not copy the resultant video files to the destination dir\n";
64     print "   -k        keep the individual video files that are merged. By default, after a merge, individual video files that were merged are removed\n";
65     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";
66     print "   -d <dir>  directory to recreate the playlists in. Only needed if -p option is given\n";
67     return 1;
68 }
69
70 sub is_folder_empty {
71     my $dirname = shift;
72     opendir(my $dh, $dirname) or die "Not a directory";
73     return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0;
74 }
75
76 sub create_playlists {
77     my ($dstdirs) = @_;
78     
79     foreach $dstdir (keys %{$dstdirs}) {
80         print "-> Recreating playlists in: $dstdir\n";
81         print "-> Creating playlists for each month & year of clips from this directory: $video_directory\n";
82         opendir(VIDEODIR, "$dstdir") or die "-E- could not open: $dstdir\n";
83         chdir "$dstdir" || die "-E- Unable to change directory to the dstdir: $dstdir\n";
84         
85         my @all_files = readdir VIDEODIR;
86         closedir(VIDEODIR);
87         @all_files = sort @all_files;
88
89         print "   Removing all existing playlists from the directory\n";
90         if(! defined $opt_t) { system("rm *.$playlist_extension > /dev/null 2>&1"); }
91     
92         foreach $file (@all_files) {
93             next if -d $file;
94             next if ($file !~ /\.avi$/i && $file !~ /\.mpg$/i && $file !~ /\.mkv$/i && $file !~ /\.3gp$/i && $file !~ /\.mov$/i && $file !~ /\.mts$/i);
95             if($file =~ /(\d\d\d\d)-(\d\d)-(\d\d)/) {
96                 $year = $1; $month = $2;
97                 print "   Adding $file to $year.$playlist_extension & $year-$month.$playlist_extension\n";
98                 if(! defined $opt_t) { system("echo \"$file\" >> $year.$playlist_extension"); }
99                 if(! defined $opt_t) { system("echo \"$file\" >> $year-$month.$playlist_extension"); }
100             } else {
101                 print "   Skipping $file since we can't extract the year and month from it\n"; 
102             }
103         }
104
105         # Fix the permissions
106         system("chown $owner \"$dstdir/\"*.$playlist_extension");
107         system("chgrp $group \"$dstdir/\"*.$playlist_extension");
108         system("chmod $mode \"$dstdir/\"*.$playlist_extension");
109    } 
110 }
111
112 # Sanity checks / Option processing
113 if(defined $opt_h) { usage(); exit 1; }
114 if(defined $opt_p) {
115     if(defined $opt_d) {
116         my %dstdirs = ("$opt_d",1); 
117         create_playlists(\%dstdirs);
118     } else {
119         die "-E- You must specify the -d <dir> option when using the -p option\n"; 
120     }
121     exit 0;
122 }
123
124 # Only proceed if there are video files to organize
125 $video_files_found=`$find_cmd_with_mkv`;
126 if(!$video_files_found) { exit 0; }
127
128 # Only proceed if no files have changed in the past $cmin minutes
129 $changed_files_found=`$find_changed_cmd`;
130 if($changed_files_found) { exit 0; }
131
132 # Only one instance of this script running at a time
133 my $pidfile = File::Pid->new({file => "$pid_file", pid => "$$"});
134 exit if $pidfile->running();
135 $pidfile->write();
136
137 # Print the date
138 system("date");
139
140 # Merge videos prior to copying them over to the destination path
141 my $errno = 0;
142 my $merge_opts = "";
143 if(defined $opt_t) { $merge_opts .= "-t "; }
144 if(defined $opt_k) { $merge_opts .= "-k "; }
145 if($requantize_input_video) { $merge_opts .= ' -q'; }
146 if($recompress_input_video) { $merge_opts .= ' -z'; }
147 $errno=system("$merge_videos_by_day -s \"$srcpathname\" $merge_opts");
148 $errno = $errno >> 8;
149 if($errno) { die "-E- $merge_videos_by_day encountered some errors with exit code $errno\n"; }
150
151 # Exit now if we are not supposed to copy the resultant video files to the destination path
152 if(defined $opt_n) {
153     $pidfile->remove();
154     print "\n\n";
155     exit 0;
156 }
157
158 # Copy the videos over to the destination path
159 my %dstdirs;
160 chdir "$srcpathname";
161 print "$find_cmd_with_mkv\n" if($opt_v);
162 foreach $file (`$find_cmd_with_mkv`) {
163
164     chomp($file);
165     $srcdir = dirname($file);
166     $file = basename($file);
167     $srcfile = $file;
168     $ext = $file; $ext =~ s/.*\.(\S+)$/$1/; $ext = lc($ext);
169     
170     print "Found movie: srcdir: $srcdir srcfile: $srcfile ext: $ext\n" if($opt_v);
171
172     # Throw out files not in the current srcpath
173     if((! -f "$srcfile") && (! -f "$srcdir/$srcfile")) { next; }
174         
175     # Make a note of the month, year, and day this video was taken (from the modification time of the file)
176     $date_taken = ctime(stat("$srcdir/$srcfile")->mtime);
177
178     # Get the date taken from the filename
179     if($srcfile =~ /^(\d+)-(\d+)-(\d+)/) {
180         $year = $1;
181         $month = $2;
182         $day = sprintf("%02d",$3);
183         $monthnum = $month;
184         $monthname = lc($month2monthname{$month});
185     }
186     elsif($srcfile =~ /^(\d\d\d\d)(\d\d)(\d\d)/) {
187         $year = $1;
188         $month = $2;
189         $day = sprintf("%02d",$3);
190         $monthnum = $month;
191         $monthname = lc($month2monthname{$month});
192     }
193     # Get the date taken from the modification time
194     elsif($date_taken =~ /\S+\s+(\S+)\s+(\d+)\s+\S+\s+(\d+)/) {
195         $year = $3;
196         $month = $1;
197         $day = sprintf("%02d",$2);
198         $monthnum = $monthname2month{$month};
199         $monthname = lc($month2monthname{$month});
200     } else {
201         print "-E- Unable to parse year and month from this file: $srcdir/$srcfile\n";
202         next;
203     }
204
205     # We are ready to pick a destination folder to put the video in
206     $dstdir = $dstpathname . "/" . $year;
207     $dstdirs{$dstdir} = 1;
208     $dstfile = $dstdir . "/" . $year . "-" . $monthnum . "-" . $day;
209
210     # Check for duplicate filenames at the destination
211     $newfile = $dstfile . "." . $video_suffix;
212     if(-e "$newfile.$ext") {
213         foreach $i ($video_suffix+1 .. '999') {
214             $newfile = $dstfile . "." . sprintf("%03d",$i);;
215             if(! -e "$newfile.$ext") { last; }
216         }
217         $dstfile = $newfile;
218     }
219     $dstfile = "$newfile.$ext";
220
221
222     if(defined $opt_t) {
223         print "-> Moving \"$srcdir/$srcfile\" to \"$dstfile\"\n";
224     } else {
225         # Make sure the destination directories exist
226         $errno=system("mkdir -p -m $dirmode \"$dstdir\"");
227         if($errno) { print "-E- Error creating dstdir: $dstdir\n"; next; }
228         # Perform the move operation from $srcdir/$srcfile -> $dstfile
229         print "-> Moving \"$srcdir/$srcfile\" to \"$dstfile\"\n";
230         # Make sure the dstfile doesn't exist, if it does, don't do the move
231         if(! -f "$dstfile") {
232             $errno=system("mv \"$srcdir/$srcfile\" \"$dstfile\" 2>/dev/null");
233             if($errno) { print "-E- Error moving srcfile to dstfile: $srcdir/$srcfile -> $dstfile\n"; next; }
234         } else {
235             print "-> Skipping \"$srcdir/$srcfile\". Destfile \"$dstfile\" already exists.\n";
236         }
237         # Fix the permissions
238         system("chown $owner \"$dstfile\"");
239         system("chgrp $group \"$dstfile\"");
240         system("chmod $mode \"$dstfile\"");
241     }
242     
243     # Check to see if there is an empty sub directory to remove
244     if(($srcdir ne $srcpathname) && ($srcpathname ne ".")) { 
245         if(is_folder_empty($srcdir)) { 
246             print "-> Subdir detected for videos ($srcdir != $srcpathname)\n" if($opt_v);
247             if(! defined $opt_t) { 
248                 $tmpdir=`tempfile`;
249                 system("rm $tmpdir");
250                 system("cp -R \"$srcdir\" $tmpdir > /dev/null 2>/dev/null");
251                 system("rm -rf \"$srcdir\"");
252                 print "-> Moved empty subdir $srcdir to $tmpdir\n" if($opt_v);
253             }
254         }
255     }
256 }
257
258 # For each destination dir we copied new content into, recreate the playlists
259 create_playlists(\%dstdirs);
260
261 $pidfile->remove();
262
263 print "\n\n";