Fixed up scripts to support importing videos from phones
[videoscripts/.git] / make_mkv
1 #!/usr/bin/perl
2 # Author: Alan J. Pippin
3 # Description: Take a list of video files and create a single mkv video file from them
4
5 # Pre-requisites:
6 # mkvtoolnix - http://www.bunkus.org/videotools/mkvtoolnix/
7 # ffmpeg
8 # avconv
9
10 ####################################################################################################
11 # Includes
12 use File::Copy;
13 use File::Basename;
14 use Getopt::Std;
15 use File::stat;
16 use DateTime;
17 use DateTime::Duration;
18 use DateTime::Format::Duration;
19
20 ####################################################################################################
21 # Configuration parameters
22 $mydir = `cd \$(dirname $0) 2>/dev/null; pwd`; chomp($mydir); unshift @INC,("$mydir");
23 # Default configuration values
24 require "organize_videos.conf";
25 # Override defaults with local customizations
26 if( -f "$mydir/organize_videos.conf.local") { require "organize_videos.conf.local"; }
27
28 ####################################################################################################
29 # Command Line Options
30 getopts("svqzt:o:i:h");
31
32 if(! defined $opt_t) { &usage(); die "-E- Missing required title: -t <title>\n"; }
33 if(! defined $opt_o) { &usage(); die "-E- Missing required argument output video names: -o <output.mkv>\n"; }
34 if(! defined $opt_i) { &usage(); die "-E- Missing required argument input video names: -i <input,input,...>\n"; }
35 if(! -x $ffmpeg) { die "-E- Missing required executable for ffmpeg: $ffmpeg\n"; }
36 if(! -x $avconv) { die "-E- Missing required executable for avconv: $avconv\n"; }
37
38 sub usage {
39     print "usage: $0 -t <title> -o <output.mkv> -i <input,input,...>\n";
40     print "  -t <title>            Sets the general title for the output video file\n";
41     print "  -o <output.mkv>       Sets the name of the output mkv file\n";
42     print "  -i <input,input,...>  Sets the name of the input files to make into an mkv file\n";
43     print "  -q                    Requantize input videos to decrease output video size (requires HandBrakeCLI)\n";
44     print "  -z                    Recompress input videos to decrease output video size (requires HandBrakeCLI)\n";
45     print "  -s                    Simulate mode. Don't actually make the video, but tell us what you will do\n";
46     print "  -v                    Increase verbosity for debug\n";
47     print "\n";
48     return 1;
49 }
50
51 ####################################################################################################
52 # Helper Subroutines
53 sub epoch_to_date {
54     my ($epoch) = @_;
55     my $mtime = DateTime->from_epoch(epoch => $epoch);
56     $mtime->set_time_zone($timezone);
57     return sprintf("%4d",$mtime->year)."-".sprintf("%02d",$mtime->month)."-".sprintf("%02d",$mtime->day)." ".$mtime->hms;
58 }
59
60 ####################################################################################################
61 # MAIN
62
63 # Turn the list of input videos into a hash with a value equal to the modification time in epoch seconds
64 my %videos;
65 foreach $video (split(/,/, $opt_i)) {
66     if(! -r "$video") { die "-E- Unable to read input video file: $video\n"; }
67     my $mtime_epoch = stat("$video")->mtime;
68     my $mdate = epoch_to_date($mtime_epoch);
69     $videos{$video} = $mtime_epoch;
70 }
71
72 # Create the chapters file for the mkv file.
73 # Make each video file it's own chapter in the MKV file.
74 # Name the chapter with the date and time the video clip was taken (modified date).
75 print "-> Creating $opt_o with title '$opt_t' from the following video files in last modified date order:\n";
76 open(CHAPTERS,">$chapter_file") || die "-E- Unable to create chapter file: $chapter_file\n";
77 my $chapter_num = 0;
78 my $chapter_timecode = DateTime::Duration->new(years => 2000, hours => 0, minutes => 0, seconds => 0);
79 my $timecode_format = DateTime::Format::Duration->new(pattern => '%H:%M:%S.%3N', normalize => 1);
80 foreach my $video (sort{$videos{$a} <=> $videos{$b}} keys %videos) {
81     $chapter_num++;
82     my $hour = 0;
83     my $min  = 5;
84     my $sec  = 0;
85     my $mtime_epoch = stat("$video")->mtime;
86     my $mdate = epoch_to_date($mtime_epoch);
87     my $duration = `$ffmpeg -i "$video" 2>&1 | grep Duration`;
88     if($duration =~ /Duration: (\d+):(\d+):(\d+)\.(\d+)/) {
89         $hour = $1;
90         $min = $2;
91         $sec = "$3.$4";
92     }
93     my $timecode = $timecode_format->format_duration($chapter_timecode);
94     print "$mdate $hour:$min:$sec  -> $video \n";
95     print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."=".$timecode."\n";
96     print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."NAME=".$mdate."\n";
97     my $dt = DateTime::Duration->new(years => 2000, hours => $hour, minutes => $min, seconds => $sec);
98     $chapter_timecode = $chapter_timecode + $dt;
99 }
100 close(CHAPTERS);
101 print "\n-> Creating the following chapter file for this video:\n";
102 $chapter_file_contents = `cat $chapter_file`;
103 print "$chapter_file_contents\n";
104
105 # Create the mkv video
106 print "-> Creating the MKV video file '$opt_o'\n";
107
108 my $cmd = "$mkvmerge --title \"$opt_t\" $output_file_options -o \"$opt_o\"";
109
110 # Make our input file command line options for all the videos
111 my @video_tmp_files;
112 my %merge_cmd;
113 foreach my $video (sort{$videos{$a} <=> $videos{$b}} keys %videos) {
114     # Make a note of the video extension
115     my $video_ext = $video;
116     $video_ext =~ s/.*\.(\S+)$/$1/;
117
118     # Detect if the input file is interlaced or not.
119     # There is a bug in mkvmerge 5.0.1 and earlier where if the video content is 1080i, it doesn't mux it properly, and it stutters.
120     # The quick solution to this issue is to run the interlaced video file through ffmpeg and tell it to copy the video/audio streams to a mkv container.
121     # We will then merge this temporarily created mkv container into the final mkv container instead of the original interlaced video.
122     # http://ubuntuforums.org/showthread.php?t=1627194
123     # http://forum.doom9.org/showthread.php?t=155732&page=31
124
125     # This is the best way to detect if content is interlaced or progressive:
126     # http://www.aktau.be/2013/09/22/detecting-interlaced-video-with-ffmpeg/
127     my $progressive = 0;
128     my $detect_cmd = "$ffmpeg -filter:v idet -frames:v 100 -an -f rawvideo -y /dev/null -i \"$video\" 2>&1 | grep Parsed_idet"; 
129     if($opt_v) { print "   $detect_cmd\n"; }
130     my $detect_output = `$detect_cmd`;
131     if($detect_output !~ /Progressive:0/) { $progressive = 1; }
132     if(!$progressive) {
133         my $video_mkv = $video;
134         print "   Detected interlaced video content: $video\n";
135         # We don't need to do this anymore since it is not an issue with the new mkvmerge
136         if($video_ext !~ /mkv/i) {
137             $video_mkv =~ s/\.[^.]*$//; $video_mkv .= ".ffmpeg.mkv";
138             if(-f $video_mkv) { next; }
139             print "   Re-muxing the interlaced video content as an mkv file: $video_mkv\n";
140             my $make_mkv_cmd = "$avconv -y -i \"$video\" -scodec copy -acodec copy -vcodec copy -f matroska \"$video_mkv\" >> \"$tmpfile\" 2>&1";
141             my $errors = 0;
142             if($opt_v) { print "   $make_mkv_cmd\n"; }
143             if(! defined $opt_s) {
144                 my $errno = system("$make_mkv_cmd");
145                 $errno = $errno >> 8;
146                 if($errno > 1) {
147                     unlink "$video_mkv";
148                     print "-W- avconv encountered some errors with exit code $errno\n";
149                     $errors = 1;
150                 }
151             }
152             if($errors == 0) { 
153                 # Push the name of our intermediate video file onto a list of files to delete on exit
154                 push(@video_tmp_files, "$video_mkv");
155                 # Update the name of our video file to equal the name of our new intermediate video file name
156                 $video = $video_mkv;
157             }
158         }
159     } else { 
160         print "   Detected progressive video content: $video\n";
161     }
162
163     # Re-quantize or re-compress the input video to reduce the resulting output filesize
164     # This also gives us a chance to deinterlace the video as well
165     # Only re-quantize for .MTS videos
166     # We can re-compress any input video
167     my $rotated = "none";
168     if(((defined $opt_q) && ($video_ext =~ /mts/i)) || (defined $opt_z)) {
169
170         my $handbrake_options = "";
171
172         # Set our output video filename
173         my $video_mp4 = $video; $video_mp4 =~ s/\.[^.]*$//; $video_mp4 .= ".hb.mp4";
174         
175         # Don't recompress certain file extensions
176         my $no_recompress = 0;
177         if($video =~ $no_recompress_file_ext) { $no_recompress = 1;} 
178
179         # Set our requantize factor accordingly
180         if(defined $opt_q and ! -f $video_mp4) {
181             print "   Re-quantizing input video content to: $video_mp4\n";
182             $handbrake_options = $handbrake_requantize_options;
183             if(!$progressive) { $handbrake_options = "-q $interlaced_requantize_quality"; }
184             else { $handbrake_options = "-q $progressive_requantize_quality"; }
185         };
186
187         # Set our recompress options accordingly
188         if(defined $opt_z and ! -f $video_mp4 and ! $no_recompress) {
189             print "   Re-compressing input video content to: $video_mp4\n";
190             $handbrake_options = $handbrake_recompress_options;
191             # We want our audio to be passed-through by default, so detect how the audio of the input is encoded, and tell handbrake to make the output match
192             if($opt_v) { print "   $ffmpeg -i \"$video\" 2>&1 | grep \"Audio\" | sed -r -e 's/.*?Audio: (\\S+).*?/\\1/' | tail -n 1\n"; }
193             $AUDIO_CODEC=`$ffmpeg -i "$video" 2>&1 | grep "Audio" | sed -r -e 's/.*?Audio: (\\S+).*?/\\1/' | tail -n 1`; chomp($AUDIO_CODEC);
194             $AUDIO_CODEC =~ s/,$//g;
195             if($AUDIO_CODEC eq "") { print "-W- Unable to extract audio track encoding from input video file: $video\n"; $handbrake_options .= " -E copy"; }
196             else { $handbrake_options .= " -E copy:$AUDIO_CODEC"; }
197         }
198
199         # Set our rotate option accordingly to rotate videos taken in portrait mode to landscape
200         my $rotate = `$ffprobe "$video" 2>&1 | grep -e rotate | awk '{print \$3}'`; chomp($rotate);
201         if($rotate ne "") {
202             print "   Detected rotated input video ($rotate). Rotating video to: $video_mp4\n";
203             if($rotate eq "90")  { $handbrake_options .= " --rotate=4"; $rotated = "90"; }
204             if($rotate eq "180") { $handbrake_options .= " --rotate=3"; $rotated = "none"; }
205         }
206         
207         # Set our de-interlace option accordingly
208         my $deinterlace_option = "";
209         if(!$progressive) { $deinterlace_option = "-d"; }
210
211         # Use HandBrake to requantize/recompress/deinterlace the input video
212         if(! $no_recompress and ! -f $video_mp4) { 
213             my $handbrake_cmd = "$handbrake $deinterlace_option $handbrake_options -i \"$video\" -o \"$video_mp4\" >> \"$tmpfile\" 2>&1";
214             if($opt_v) { print "   $handbrake_cmd\n"; }
215             if(! defined $opt_s and ! -f $video_mp4) { 
216                 my $errno = system("$handbrake_cmd");
217                 $errno = $errno >> 8;
218                 if($errno > 1) {
219                     unlink "$video_mp4";
220                     die "-E- handbrake encountered some errors with exit code $errno\n";
221                 }
222             }
223         } else {
224             if(! -f $video_mp4) { 
225                 print "   Copying input video content to: $video_mp4\n";
226                 system("cp \"$video\" \"$video_mp4\"") if(!$opt_s);
227             }
228         }
229         
230         # Push the name of our intermediate video file onto a list of files to delete on exit
231         push(@video_tmp_files, "$video_mp4");
232         # Update the name of our video file to equal the name of our new intermediate video file name
233         $video = $video_mp4;
234     }
235     
236     # Create our mkvmerge input file command line options for this video
237     if(not defined $merge_cmd{$rotated}) {
238         $merge_cmd{$rotated} = "$cmd $input_file_options \"$video\"";   
239     } else {
240         $merge_cmd{$rotated} .= " $input_file_options + \"$video\"";
241     }
242 }
243
244 # Execute our command line
245 foreach my $key (keys %merge_cmd) {
246     my $merge_cmd = $merge_cmd{$key};
247     # if the $key is not none, change the output filename to avoid naming conflicts since it will need to create a separate output file
248     if($key ne "none") {
249         $merge_cmd =~ s/-o "(.*?)\.(mkv)"/-o "$1\.$key\.$2"/g;
250     }
251     print "\n$merge_cmd\n";
252     if(! defined $opt_s) {
253         my $errno = system("$merge_cmd");
254         $errno = $errno >> 8;
255         if($errno > 1) {
256             unlink "$opt_o";
257             die "-E- mkvmerge encountered some errors with exit code $errno\n";
258         }
259     }
260 }
261
262 # Remove the temporary file used for ffmpeg and handbrake output
263 if(-e "$tmpfile") { unlink "$tmpfile"; }
264 # Remove the temporary file used for the chapter generation
265 if(-e "$chapter_file") { unlink "$chapter_file"; }
266
267 # Remove any temporary video files created during the merge process
268 foreach my $video (@video_tmp_files) {
269     if(-e "$video") { unlink "$video"; }
270 }
271
272 ####################################################################################################
273