Added a workaround for a bug in mkv tool's ability to handle 1080i (interlaced HD...
[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=`which mkvmerge`; chomp($mkvmerge);
22 my $ffmpeg=`which ffmpeg`; chomp($ffmpeg);
23 my $tmpfile = `tempfile`; chomp($tmpfile);
24 my $chapter_file = $tmpfile;
25 my $input_file_options = "-S";
26 my $output_file_options = "--chapters $chapter_file --compression -1:none";
27 my $timezone = `cat /etc/timezone`; chomp($timezone);
28 ####################################################################################################
29
30
31 ####################################################################################################
32 # Command Line Options
33 getopts("st:o:i:h");
34
35 if(! -x $mkvmerge) { die "-E- Unable to find required program: mkvmerge\n"; }
36 if(! -x $ffmpeg) { die "-E- Unable to find required program: ffmpeg\n"; }
37 if(! defined $opt_t) { &usage(); die "-E- Missing required title: -t <title>\n"; }
38 if(! defined $opt_o) { &usage(); die "-E- Missing required argument output video names: -o <output.mkv>\n"; }
39 if(! defined $opt_i) { &usage(); die "-E- Missing required argument input video names: -i <input,input,...>\n"; }
40
41 sub usage {
42     print "usage: $0 -t <title> -o <output.mkv> -i <input,input,...>\n";
43     print "  -t <title>            Sets the general title for the output video file\n";
44     print "  -o <output.mkv>       Sets the name of the output mkv file\n";
45     print "  -i <input,input,...>  Sets the name of the input files to make into an mkv file\n";
46     print "  -s                    Simulate mode. Don't actually make the video, but tell us what you will do\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_count = 0;
112 my @video_tmp_files;
113 foreach my $video (sort{$videos{$a} <=> $videos{$b}} keys %videos) {
114     # Detect if the input file is interlaced or not.
115     # 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.
116     # 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.
117     # We will then merge this temporarily created mkv container into the final mkv container instead of the original interlaced video.
118     # http://ubuntuforums.org/showthread.php?t=1627194
119     # http://forum.doom9.org/showthread.php?t=155732&page=31
120     my $interlaced = system('ffmpeg -i "$video" 2>&1 | grep -q "frame rate differs"');
121     if($interlaced != 0) {
122         my $video_mkv = $video;
123         my $video_ext = $video;
124         $video_ext =~ s/.*\.(\S+)$/$1/;
125         print "   Detected interlaced video content: $video\n";
126         if($video_ext !~ /mkv/i) {
127             $video_mkv =~ s/\.[^.]*$//; $video_mkv .= ".mkv";
128             print "   Re-muxing the interlaced video content as an mkv file: $video_mkv\n";
129             my $make_mkv_cmd = "ffmpeg -i \"$video\" -scodec copy -acodec copy -vcodec copy -f matroska \"$video_mkv\" > /dev/null 2>&1";
130             if(! defined $opt_s) { 
131                 my $errno = system("$make_mkv_cmd");
132                 $errno = $errno >> 8;
133                 if($errno > 1) {
134                     unlink "$video_mkv";
135                     die "-E- ffmpeg encountered some errors with exit code $errno\n";
136                 }
137             }
138             # Push the name of our intermediate video file onto a list of files to delete on exit
139             push(@video_tmp_files, "$video_mkv");
140             # Update the name of our video file to equal the name of our new intermediate video file name
141             $video = $video_mkv;
142         }
143     } else { 
144         print "   Detected progressive video content: $video\n";
145     }
146     # Create our intput file command line options for this video
147     if($video_count == 0) {
148         $cmd .= " $input_file_options \"$video\"";
149     } else {
150         $cmd .= " $input_file_options + \"$video\"";
151     }
152     $video_count++;
153 }
154
155 # Execute our command line
156 print "\n$cmd\n";
157 if(! defined $opt_s) { 
158     my $errno = system("$cmd");
159     $errno = $errno >> 8;
160     if($errno > 1) {
161         unlink "$opt_o";
162         die "-E- mkvmerge encountered some errors with exit code $errno\n";
163     }
164 }
165
166 # Remove the temporary file used for the chapter generation
167 if(-e "$tmpfile") { unlink "$tmpfile"; }
168
169 # Remove any temporary video files created during the merge process
170 foreach my $video (@video_tmp_files) {
171     if(-e "$video") { unlink "$video"; }
172 }
173
174 ####################################################################################################
175