Fixed a few bugs
[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 Data::Dumper;
17 use DateTime;
18 use DateTime::Duration;
19 use DateTime::Format::Duration;
20
21 ####################################################################################################
22 # Configuration parameters
23 $mydir = `cd \$(dirname $0) 2>/dev/null; pwd`; chomp($mydir); unshift @INC,("$mydir");
24 # Default configuration values
25 require "organize_videos.conf";
26 # Override defaults with local customizations
27 if( -f "$mydir/organize_videos.conf.local") { require "organize_videos.conf.local"; }
28
29 ####################################################################################################
30 # Command Line Options
31 getopts("svqzt:o:i:h");
32
33 if(! defined $opt_t) { &usage(); die "-E- Missing required title: -t <title>\n"; }
34 if(! defined $opt_o) { &usage(); die "-E- Missing required argument output video names: -o <output.mkv>\n"; }
35 if(! defined $opt_i) { &usage(); die "-E- Missing required argument input video names: -i <input,input,...>\n"; }
36 if(! -x $ffmpeg) { die "-E- Missing required executable for ffmpeg: $ffmpeg\n"; }
37 if(! -x $avconv) { die "-E- Missing required executable for avconv: $avconv\n"; }
38
39 sub usage {
40     print "usage: $0 -t <title> -o <output.mkv> -i <input,input,...>\n";
41     print "  -t <title>            Sets the general title for the output video file\n";
42     print "  -o <output>           Sets the basename of the output mkv file\n";
43     print "  -i <input,input,...>  Sets the names of the input files to combine into a new mkv file\n";
44     print "  -q                    Requantize input videos to decrease output video size (requires HandBrakeCLI)\n";
45     print "  -z                    Recompress input videos to decrease output video size (requires HandBrakeCLI)\n";
46     print "  -s                    Simulate mode. Don't actually make the video, but tell us what you will do\n";
47     print "  -v                    Increase verbosity for debug\n";
48     print "\n";
49     return 1;
50 }
51
52 $SIG{'INT'} = sub {die "-E- Killed by CTRL-C\n"};
53 ####################################################################################################
54 # Helper Subroutines
55 sub epoch_to_date {
56     my ($epoch) = @_;
57     my $mtime = DateTime->from_epoch(epoch => $epoch);
58     $mtime->set_time_zone($timezone);
59     return sprintf("%4d",$mtime->year)."-".sprintf("%02d",$mtime->month)."-".sprintf("%02d",$mtime->day)." ".$mtime->hms;
60 }
61
62 ####################################################################################################
63 # MAIN
64
65 # Turn the list of input videos into a hash with a value equal to the modification time in epoch seconds
66 my %videos;
67 foreach $video (split(/,/, $opt_i)) {
68     if(! -r "$video") { die "-E- Unable to read input video file: $video\n"; }
69     my $mtime_epoch = stat("$video")->mtime;
70     my $mdate = epoch_to_date($mtime_epoch);
71     $videos{$video} = $mtime_epoch;
72 }
73
74 ####################################################################################################
75 # 1) Create the mkv video
76 print "-> Creating MKV video files with basename '$opt_o'\n";
77
78 # Make our input file command line options for all the videos
79 my @video_tmp_files;
80 my %merge_videos;
81 foreach my $video (sort{$videos{$a} <=> $videos{$b}} keys %videos) {
82     # Make a note of the video extension
83     my $video_ext = $video;
84     $video_ext =~ s/.*\.(\S+)$/$1/;
85
86     # Detect if the input file is interlaced or not.
87     # 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.
88     # 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.
89     # We will then merge this temporarily created mkv container into the final mkv container instead of the original interlaced video.
90     # http://ubuntuforums.org/showthread.php?t=1627194
91     # http://forum.doom9.org/showthread.php?t=155732&page=31
92
93     # This is the best way to detect if content is interlaced or progressive:
94     # http://www.aktau.be/2013/09/22/detecting-interlaced-video-with-ffmpeg/
95     my $progressive = 0;
96     my $detect_cmd = "$ffmpeg -filter:v idet -frames:v 100 -an -f rawvideo -y /dev/null -i \"$video\" 2>&1 | grep Parsed_idet"; 
97     if($opt_v) { print "   $detect_cmd\n"; }
98     my $detect_output = `$detect_cmd`;
99     if($detect_output !~ /Progressive:0/) { $progressive = 1; }
100     if(!$progressive) {
101         my $video_mkv = $video;
102         print "   Detected interlaced video content: $video\n";
103         # We don't need to do this anymore since it is not an issue with the new mkvmerge
104         if($video_ext !~ /mkv/i) {
105             $video_mkv =~ s/\.[^.]*$//; $video_mkv .= ".ffmpeg.mkv";
106             if(-f $video_mkv) { next; }
107             print "   Re-muxing the interlaced video content as an mkv file: $video_mkv\n";
108             my $make_mkv_cmd = "$avconv -y -i \"$video\" -scodec copy -acodec copy -vcodec copy -f matroska \"$video_mkv\" >> \"$tmpfile\" 2>&1";
109             my $errors = 0;
110             if($opt_v) { print "   $make_mkv_cmd\n"; }
111             if(! defined $opt_s) {
112                 my $errno = system("$make_mkv_cmd");
113                 $errno = $errno >> 8;
114                 if($errno > 1) {
115                     unlink "$video_mkv";
116                     print "-W- avconv encountered some errors with exit code $errno\n";
117                     $errors = 1;
118                 }
119             }
120             if($errors == 0) { 
121                 # Push the name of our intermediate video file onto a list of files to delete on exit
122                 push(@video_tmp_files, "$video_mkv");
123                 # Copy the modification date from the src video to the dst video
124                 system("touch \"$video_mkv\" -r \"$video\"");
125                 # Update the name of our video file to equal the name of our new intermediate video file name
126                 $video = $video_mkv;
127             }
128         }
129     } else { 
130         print "   Detected progressive video content: $video\n";
131     }
132
133     # Re-quantize or re-compress the input video to reduce the resulting output filesize
134     # This also gives us a chance to deinterlace the video as well
135     # Only re-quantize for .MTS videos
136     # We can re-compress any input video
137     my $rotated = "none";
138     if(((defined $opt_q) && ($video_ext =~ /mts/i)) || (defined $opt_z)) {
139
140         my $handbrake_options = "";
141
142         # Set our output video filename
143         my $video_mp4 = $video; $video_mp4 =~ s/\.[^.]*$//; $video_mp4 .= ".hb.mp4";
144         
145         # Don't recompress certain file extensions
146         # Unless the video is not progressive or is rotated, then we do need to recompress it to deinterlace or unrotate it
147         my $no_recompress = 0;
148         if($no_recompress_file_ext && $progressive && ($video =~ $no_recompress_file_ext)) { $no_recompress = 1; } 
149         
150         # Set our rotate option accordingly to rotate videos taken in portrait mode to landscape
151         my $rotate = `$ffprobe "$video" 2>&1 | grep -e rotate | awk '{print \$3}'`; chomp($rotate);
152         if($rotate ne "") {
153             print "   Detected rotated input video ($rotate). Rotating video to: $video_mp4\n";
154             if($rotate eq "90")  { $handbrake_options .= " --rotate=4"; $rotated = "90"; }
155             if($rotate eq "180") { $handbrake_options .= " --rotate=3"; $rotated = "none"; }
156             $no_recompress = 0; # We have to recompress this video to unrotate it
157         }
158
159         # Set our requantize factor accordingly
160         if(defined $opt_q and ! -f $video_mp4) {
161             print "   Re-quantizing input video content to: $video_mp4\n";
162             $handbrake_options = $handbrake_requantize_options;
163             if(!$progressive) { $handbrake_options = "-q $interlaced_requantize_quality"; }
164             else { $handbrake_options = "-q $progressive_requantize_quality"; }
165         };
166
167         # Set our recompress options accordingly
168         if(defined $opt_z and ! -f $video_mp4 and ! $no_recompress) {
169             print "   Re-compressing input video content to: $video_mp4\n";
170             $handbrake_options = $handbrake_recompress_options;
171             # 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
172             if($opt_v) { print "   $ffmpeg -i \"$video\" 2>&1 | grep \"Audio\" | sed -r -e 's/.*?Audio: (\\S+).*?/\\1/' | tail -n 1\n"; }
173             $AUDIO_CODEC=`$ffmpeg -i "$video" 2>&1 | grep "Audio" | sed -r -e 's/.*?Audio: (\\S+).*?/\\1/' | tail -n 1`; chomp($AUDIO_CODEC);
174             $AUDIO_CODEC =~ s/,$//g;
175             if($AUDIO_CODEC eq "") { print "-W- Unable to extract audio track encoding from input video file: $video\n"; $handbrake_options .= " -E copy"; }
176             else { $handbrake_options .= " -E copy:$AUDIO_CODEC"; }
177         }
178         
179         # Set our de-interlace option accordingly
180         my $deinterlace_option = "";
181         if(!$progressive) { $deinterlace_option = "-d"; }
182
183         # Use HandBrake to requantize/recompress/deinterlace the input video
184         if(! $no_recompress and ! -f $video_mp4) { 
185             my $handbrake_cmd = "$handbrake $deinterlace_option $handbrake_options -i \"$video\" -o \"$video_mp4\" >> \"$tmpfile\" 2>&1";
186             if($opt_v) { print "   $handbrake_cmd\n"; }
187             if(! defined $opt_s and ! -f $video_mp4) { 
188                 my $errno = system("$handbrake_cmd");
189                 $errno = $errno >> 8;
190                 if($errno > 1) {
191                     unlink "$video_mp4";
192                     die "-E- handbrake encountered some errors with exit code $errno\n";
193                 }
194             }
195         } else {
196             if($no_recompress) { 
197                 print "   Copying input video content to: $video_mp4\n";
198                 system("cp \"$video\" \"$video_mp4\"") if(!$opt_s);
199             }
200         }
201         
202         # Push the name of our intermediate video file onto a list of files to delete on exit
203         push(@video_tmp_files, "$video_mp4");
204         # Copy the modification date from the src video to the dst video
205         system("touch \"$video_mp4\" -r \"$video\"");
206         # Update the name of our video file to equal the name of our new intermediate video file name
207         $video = $video_mp4;
208     }
209
210     
211     ####################################################################################################
212     # 2) Group the encoded videos together by their parameters
213     #    We can merge videos that have the same parameters together in a destination video file.
214
215     # Dimensions
216     my $video_stream_info = `$ffprobe "$video" 2>&1 | grep -e "Stream.*Video"`; chomp($video_stream_info);
217     my $dimensions = "unknown";
218     if($video_stream_info =~ / (\d+x\d+)[,| ]/) { $dimensions = "$1"; }
219     else { print "-W- ffprobe was unable to find dimensions for video: $video\n"; }
220
221     # Color space
222     my $color_space = "unknown";
223     if($video_stream_info =~ /, (\S+)\(.*?\)/) { $color_space = "$1"; }
224     else { print "-W- ffprobe was unable to find color space for video: $video\n"; }
225
226     # Audio Handler
227     my $audio_stream_info = `$ffprobe "$video" 2>&1 | grep -e "Stream.*Audio"`; chomp($video_stream_info);
228     my $audio_handler = "unknown";
229     if($audio_stream_info =~ / Hz, ([^,]+), /) { $audio_handler = "$1"; }
230     else { print "-W- ffprobe was unable to find audio handler for video: $video\n"; }
231
232     # Audio Codec
233     my $audio_codec = "unknown";
234     if($audio_stream_info =~ /Audio: (\S+) /) { $audio_codec = "$1"; }
235     else { print "-W- ffprobe was unable to find audio codec for video: $video\n"; }
236
237     # Now create our parameters string
238     my $parameters = "$dimensions.$color_space.$audio_handler.$audio_codec";
239     
240     print "   Adding video $video to be merged into output video file: $opt_o.$parameters.mkv\n" if($opt_v);
241     push @{$merge_videos{"$parameters"}}, $video;
242 }
243
244 if($opt_v) { 
245     print "\n-> Merge videos hash:\n";
246     print Dumper(\%merge_videos);
247     print "\n";
248 }
249
250 ####################################################################################################
251 # 3) Create a chapter file for each destination video file
252
253 # tmp chapter file used by handbrake when creating mkv, but remove the 0 byte file it creates, we'll create it if we need it
254 my $chapter_file = `tempfile`; chomp($chapter_file); unlink "$chapter_file";
255
256 foreach my $key (keys %merge_videos) {   
257     # Create the chapters file for each output mkv file.
258     # Make each video file it's own chapter in the MKV file.
259     # Name the chapter with the date and time the video clip was taken (modified date).
260     print "-> Creating $opt_o.$key.mkv with title '$opt_t' from the following video files in last modified date order:\n";
261     open(CHAPTERS,">$chapter_file.$key") || die "-E- Unable to create chapter file: $chapter_file.$key\n";
262     my $chapter_num = 0;
263     my $chapter_timecode = DateTime::Duration->new(years => 2000, hours => 0, minutes => 0, seconds => 0);
264     my $timecode_format = DateTime::Format::Duration->new(pattern => '%H:%M:%S.%3N', normalize => 1);
265     foreach my $video (@{$merge_videos{$key}}) {
266         $chapter_num++;
267         my $hour = 0;
268         my $min  = 5;
269         my $sec  = 0;
270         my $mtime_epoch = stat("$video")->mtime;
271         my $mdate = epoch_to_date($mtime_epoch);
272         my $duration = `$ffmpeg -i "$video" 2>&1 | grep Duration`;
273         if($duration =~ /Duration: (\d+):(\d+):(\d+)\.(\d+)/) {
274             $hour = $1;
275             $min = $2;
276             $sec = "$3.$4";
277         }
278         my $timecode = $timecode_format->format_duration($chapter_timecode);
279         print "$mdate $hour:$min:$sec  -> $video \n";
280         print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."=".$timecode."\n";
281         print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."NAME=".$mdate."\n";
282         my $dt = DateTime::Duration->new(years => 2000, hours => $hour, minutes => $min, seconds => $sec);
283         $chapter_timecode = $chapter_timecode + $dt;
284     }
285     close(CHAPTERS);
286     print "\n-> Creating the following chapter file $chapter_file.$key for this video:\n";
287     $chapter_file_contents = `cat $chapter_file.$key`;
288     print "$chapter_file_contents\n";
289 }
290     
291 ####################################################################################################
292 # 4) Run mkvmerge to merge all of the videos together of the same parameters
293 foreach my $key (keys %merge_videos) {
294     my $merge_cmd = "$mkvmerge --title \"$opt_t\" $output_file_options --chapters $chapter_file.$key -o \"$opt_o.$key.mkv\"";
295     my $i = 0;
296     foreach my $video (@{$merge_videos{$key}}) {
297         if($i == 0) { 
298             $merge_cmd .= " $input_file_options \"$video\"";
299         } else {
300             $merge_cmd .= " $input_file_options + \"$video\"";
301         }
302         $i++;
303     }
304     print "\n$merge_cmd\n";
305     if(! defined $opt_s) {
306         if(-f "$opt_o.$key.mkv") { die "-E- Output video file $opt_o already exists. This is unexpected for key $key!"; }
307         my $errno = system("$merge_cmd");
308         $errno = $errno >> 8;
309         if($errno > 1) {
310             unlink "$opt_o.$key.mkv";
311             die "-E- mkvmerge encountered some errors with exit code $errno\n";
312         }
313     }
314 }
315
316 ####################################################################################################
317 # 5) Remove all temporary files
318 if(!$opt_s) { 
319     # Remove the temporary file used for ffmpeg and handbrake output
320     if(-e "$tmpfile") { unlink "$tmpfile"; }
321
322     # Remove the temporary file used for the chapter generation
323     foreach my $key (keys %merge_videos) {   
324         if(-e "$chapter_file.$key") { unlink "$chapter_file.$key"; }
325     }
326
327     # Remove any temporary video files created during the merge process
328     foreach my $video (@video_tmp_files) {
329         if(-e "$video") { unlink "$video"; }
330     }
331 }
332
333 ####################################################################################################
334