Fixed missing strict-anamorphic mode for HandBrake.
[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
9 ####################################################################################################
10 # Includes
11 use File::Copy;
12 use File::Basename;
13 use Getopt::Std;
14 use File::stat;
15 use DateTime;
16 use DateTime::Duration;
17 use DateTime::Format::Duration;
18
19 ####################################################################################################
20 # Configuration parameters - CHANGE THESE TO SUITE YOUR NEEDS
21 my $mkvmerge='mkvmerge';
22 my $ffmpeg='ffmpeg';
23 my $handbrake='HandBrakeCLI';
24 my $handbrake_options='--strict-anamorphic --crop 0:0:0:0 -E ac3';
25 my $tmpfile = `tempfile`; chomp($tmpfile);
26 my $chapter_file = $tmpfile;
27 my $input_file_options = "-S";
28 my $output_file_options = "--chapters $chapter_file --compression -1:none";
29 my $timezone = `cat /etc/timezone`; chomp($timezone);
30 my $interlaced_requantize_quality=0.85;
31 my $progressive_requantize_quality=0.7;
32 ####################################################################################################
33
34
35 ####################################################################################################
36 # Command Line Options
37 getopts("sqt:o:i:h");
38
39 if(! defined $opt_t) { &usage(); die "-E- Missing required title: -t <title>\n"; }
40 if(! defined $opt_o) { &usage(); die "-E- Missing required argument output video names: -o <output.mkv>\n"; }
41 if(! defined $opt_i) { &usage(); die "-E- Missing required argument input video names: -i <input,input,...>\n"; }
42
43 sub usage {
44     print "usage: $0 -t <title> -o <output.mkv> -i <input,input,...>\n";
45     print "  -t <title>            Sets the general title for the output video file\n";
46     print "  -o <output.mkv>       Sets the name of the output mkv file\n";
47     print "  -i <input,input,...>  Sets the name of the input files to make into an mkv file\n";
48     print "  -q                    Requantize MTS input videos to decrease output video size (requires HandBrakeCLI)\n";
49     print "  -s                    Simulate mode. Don't actually make the video, but tell us what you will do\n";
50     print "\n";
51     return 1;
52 }
53
54 ####################################################################################################
55 # Helper Subroutines
56 sub epoch_to_date {
57     my ($epoch) = @_;
58     my $mtime = DateTime->from_epoch(epoch => $epoch);
59     $mtime->set_time_zone($timezone);
60     return sprintf("%4d",$mtime->year)."-".sprintf("%02d",$mtime->month)."-".sprintf("%02d",$mtime->day)." ".$mtime->hms;
61 }
62
63 ####################################################################################################
64 # MAIN
65
66 # Turn the list of input videos into a hash with a value equal to the modification time in epoch seconds
67 my %videos;
68 foreach $video (split(/,/, $opt_i)) {
69     if(! -r "$video") { die "-E- Unable to read input video file: $video\n"; }
70     my $mtime_epoch = stat("$video")->mtime;
71     my $mdate = epoch_to_date($mtime_epoch);
72     $videos{$video} = $mtime_epoch;
73 }
74
75 # Create the chapters file for the mkv file.
76 # Make each video file it's own chapter in the MKV file.
77 # Name the chapter with the date and time the video clip was taken (modified date).
78 print "-> Creating $opt_o with title '$opt_t' from the following video files in last modified date order:\n";
79 open(CHAPTERS,">$chapter_file") || die "-E- Unable to create chapter file: $chapter_file\n";
80 my $chapter_num = 0;
81 my $chapter_timecode = DateTime::Duration->new(years => 2000, hours => 0, minutes => 0, seconds => 0);
82 my $timecode_format = DateTime::Format::Duration->new(pattern => '%H:%M:%S.%3N', normalize => 1);
83 foreach my $video (sort{$videos{$a} <=> $videos{$b}} keys %videos) {
84     $chapter_num++;
85     my $hour = 0;
86     my $min  = 5;
87     my $sec  = 0;
88     my $mtime_epoch = stat("$video")->mtime;
89     my $mdate = epoch_to_date($mtime_epoch);
90     my $duration = `$ffmpeg -i "$video" 2>&1 | grep Duration`;
91     if($duration =~ /Duration: (\d+):(\d+):(\d+)\.(\d+)/) {
92         $hour = $1;
93         $min = $2;
94         $sec = "$3.$4";
95     }
96     my $timecode = $timecode_format->format_duration($chapter_timecode);
97     print "$mdate $hour:$min:$sec  -> $video \n";
98     print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."=".$timecode."\n";
99     print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."NAME=".$mdate."\n";
100     my $dt = DateTime::Duration->new(years => 2000, hours => $hour, minutes => $min, seconds => $sec);
101     $chapter_timecode = $chapter_timecode + $dt;
102 }
103 close(CHAPTERS);
104 print "\n-> Creating the following chapter file for this video:\n";
105 $chapter_file_contents = `cat $chapter_file`;
106 print "$chapter_file_contents\n";
107
108 # Create the mkv video
109 print "-> Creating the MKV video file '$opt_o'\n";
110
111 my $cmd = "$mkvmerge --title \"$opt_t\" $output_file_options -o \"$opt_o\"";
112
113 # Make our input file command line options for all the videos
114 my $video_count = 0;
115 my @video_tmp_files;
116 foreach my $video (sort{$videos{$a} <=> $videos{$b}} keys %videos) {
117     # Make a note of the video extension
118     my $video_ext = $video;
119     $video_ext =~ s/.*\.(\S+)$/$1/;
120
121     # Detect if the input file is interlaced or not.
122     # 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.
123     # 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.
124     # We will then merge this temporarily created mkv container into the final mkv container instead of the original interlaced video.
125     # http://ubuntuforums.org/showthread.php?t=1627194
126     # http://forum.doom9.org/showthread.php?t=155732&page=31
127     my $progressive = system('$ffmpeg -i "$video" 2>&1 | grep -q "frame rate differs"');
128     if(!$progressive) {
129         my $video_mkv = $video;
130         print "   Detected interlaced video content: $video\n";
131         if($video_ext !~ /mkv/i) {
132             $video_mkv =~ s/\.[^.]*$//; $video_mkv .= ".ffmpeg.mkv";
133             print "   Re-muxing the interlaced video content as an mkv file: $video_mkv\n";
134             my $make_mkv_cmd = "$ffmpeg -y -i \"$video\" -scodec copy -acodec copy -vcodec copy -f matroska \"$video_mkv\" > /dev/null 2>&1";
135             if(! defined $opt_s) { 
136                 my $errno = system("$make_mkv_cmd");
137                 $errno = $errno >> 8;
138                 if($errno > 1) {
139                     unlink "$video_mkv";
140                     die "-E- ffmpeg encountered some errors with exit code $errno\n";
141                 }
142             }
143             # Push the name of our intermediate video file onto a list of files to delete on exit
144             push(@video_tmp_files, "$video_mkv");
145             # Update the name of our video file to equal the name of our new intermediate video file name
146             $video = $video_mkv;
147         }
148     } else { 
149         print "   Detected progressive video content: $video\n";
150     }
151
152     # Re-quantize the input video to reduce the resulting output filesize
153     # This also gives us a chance to deinterlace the video as well
154     # Only do this for .MTS videos
155     if((defined $opt_q) && ($video_ext =~ /mts/i)) {
156
157         # Set our requantize factor accordingly
158         my $requantize_option = "";
159         if(!$progressive) { $requantize_option = "-q $interlaced_requantize_quality"; }
160         else { $requantize_option = "-q $progressive_requantize_quality"; }
161         
162         # Set our de-interlace option accordingly
163         my $deinterlace_option = "";
164         if(!$progressive) { $deinterlace_option = "-d"; }
165
166         # Use HandBrake to requantize/deinterlace the input video
167         my $video_mp4 = $video; $video_mp4 =~ s/\.[^.]*$//; $video_mp4 .= ".hb.mp4";
168         print "   Re-quantizing input video content: $video_mp4\n";
169         my $handbrake_cmd = "$handbrake $deinterlace_option $requantize_option $handbrake_options -i \"$video\" -o \"$video_mp4\" > /dev/null 2>&1";
170         if(! defined $opt_s) { 
171             my $errno = system("$handbrake_cmd");
172             $errno = $errno >> 8;
173             if($errno > 1) {
174                 unlink "$video_mp4";
175                 die "-E- handbrake encountered some errors with exit code $errno\n";
176             }
177         }
178         
179         # Push the name of our intermediate video file onto a list of files to delete on exit
180         push(@video_tmp_files, "$video_mp4");
181         # Update the name of our video file to equal the name of our new intermediate video file name
182         $video = $video_mp4;
183     }
184     
185     # Create our input file command line options for this video
186     if($video_count == 0) {
187         $cmd .= " $input_file_options \"$video\"";
188     } else {
189         $cmd .= " $input_file_options + \"$video\"";
190     }
191     $video_count++;
192 }
193
194 # Execute our command line
195 print "\n$cmd\n";
196 if(! defined $opt_s) { 
197     my $errno = system("$cmd");
198     $errno = $errno >> 8;
199     if($errno > 1) {
200         unlink "$opt_o";
201         die "-E- mkvmerge encountered some errors with exit code $errno\n";
202     }
203 }
204
205 # Remove the temporary file used for the chapter generation
206 if(-e "$tmpfile") { unlink "$tmpfile"; }
207
208 # Remove any temporary video files created during the merge process
209 foreach my $video (@video_tmp_files) {
210     if(-e "$video") { unlink "$video"; }
211 }
212
213 ####################################################################################################
214