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