2 # Author: Alan J. Pippin
3 # Description: Take a list of video files and create a single mkv video file from them
6 # mkvtoolnix - http://www.bunkus.org/videotools/mkvtoolnix/
9 ####################################################################################################
16 use DateTime::Duration;
17 use DateTime::Format::Duration;
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"; }
27 ####################################################################################################
28 # Command Line Options
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"; }
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 MTS input videos to decrease output video size (requires HandBrakeCLI)\n";
41 print " -s Simulate mode. Don't actually make the video, but tell us what you will do\n";
46 ####################################################################################################
50 my $mtime = DateTime->from_epoch(epoch => $epoch);
51 $mtime->set_time_zone($timezone);
52 return sprintf("%4d",$mtime->year)."-".sprintf("%02d",$mtime->month)."-".sprintf("%02d",$mtime->day)." ".$mtime->hms;
55 ####################################################################################################
58 # Turn the list of input videos into a hash with a value equal to the modification time in epoch seconds
60 foreach $video (split(/,/, $opt_i)) {
61 if(! -r "$video") { die "-E- Unable to read input video file: $video\n"; }
62 my $mtime_epoch = stat("$video")->mtime;
63 my $mdate = epoch_to_date($mtime_epoch);
64 $videos{$video} = $mtime_epoch;
67 # Create the chapters file for the mkv file.
68 # Make each video file it's own chapter in the MKV file.
69 # Name the chapter with the date and time the video clip was taken (modified date).
70 print "-> Creating $opt_o with title '$opt_t' from the following video files in last modified date order:\n";
71 open(CHAPTERS,">$chapter_file") || die "-E- Unable to create chapter file: $chapter_file\n";
73 my $chapter_timecode = DateTime::Duration->new(years => 2000, hours => 0, minutes => 0, seconds => 0);
74 my $timecode_format = DateTime::Format::Duration->new(pattern => '%H:%M:%S.%3N', normalize => 1);
75 foreach my $video (sort{$videos{$a} <=> $videos{$b}} keys %videos) {
80 my $mtime_epoch = stat("$video")->mtime;
81 my $mdate = epoch_to_date($mtime_epoch);
82 my $duration = `$ffmpeg -i "$video" 2>&1 | grep Duration`;
83 if($duration =~ /Duration: (\d+):(\d+):(\d+)\.(\d+)/) {
88 my $timecode = $timecode_format->format_duration($chapter_timecode);
89 print "$mdate $hour:$min:$sec -> $video \n";
90 print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."=".$timecode."\n";
91 print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."NAME=".$mdate."\n";
92 my $dt = DateTime::Duration->new(years => 2000, hours => $hour, minutes => $min, seconds => $sec);
93 $chapter_timecode = $chapter_timecode + $dt;
96 print "\n-> Creating the following chapter file for this video:\n";
97 $chapter_file_contents = `cat $chapter_file`;
98 print "$chapter_file_contents\n";
100 # Create the mkv video
101 print "-> Creating the MKV video file '$opt_o'\n";
103 my $cmd = "$mkvmerge --title \"$opt_t\" $output_file_options -o \"$opt_o\"";
105 # Make our input file command line options for all the videos
108 foreach my $video (sort{$videos{$a} <=> $videos{$b}} keys %videos) {
109 # Make a note of the video extension
110 my $video_ext = $video;
111 $video_ext =~ s/.*\.(\S+)$/$1/;
113 # Detect if the input file is interlaced or not.
114 # 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.
115 # 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.
116 # We will then merge this temporarily created mkv container into the final mkv container instead of the original interlaced video.
117 # http://ubuntuforums.org/showthread.php?t=1627194
118 # http://forum.doom9.org/showthread.php?t=155732&page=31
119 my $progressive = system('$ffmpeg -i "$video" 2>&1 | grep -q "frame rate differs"');
121 my $video_mkv = $video;
122 print " Detected interlaced video content: $video\n";
123 if($video_ext !~ /mkv/i) {
124 $video_mkv =~ s/\.[^.]*$//; $video_mkv .= ".ffmpeg.mkv";
125 print " Re-muxing the interlaced video content as an mkv file: $video_mkv\n";
126 my $make_mkv_cmd = "$ffmpeg -y -i \"$video\" -scodec copy -acodec copy -vcodec copy -f matroska \"$video_mkv\" > /dev/null 2>&1";
127 if(! defined $opt_s) {
128 my $errno = system("$make_mkv_cmd");
129 $errno = $errno >> 8;
132 die "-E- ffmpeg encountered some errors with exit code $errno\n";
135 # Push the name of our intermediate video file onto a list of files to delete on exit
136 push(@video_tmp_files, "$video_mkv");
137 # Update the name of our video file to equal the name of our new intermediate video file name
141 print " Detected progressive video content: $video\n";
144 # Re-quantize the input video to reduce the resulting output filesize
145 # This also gives us a chance to deinterlace the video as well
146 # Only do this for .MTS videos
147 if((defined $opt_q) && ($video_ext =~ /mts/i)) {
149 # Set our requantize factor accordingly
150 my $requantize_option = "";
151 if(!$progressive) { $requantize_option = "-q $interlaced_requantize_quality"; }
152 else { $requantize_option = "-q $progressive_requantize_quality"; }
154 # Set our de-interlace option accordingly
155 my $deinterlace_option = "";
156 if(!$progressive) { $deinterlace_option = "-d"; }
158 # Use HandBrake to requantize/deinterlace the input video
159 my $video_mp4 = $video; $video_mp4 =~ s/\.[^.]*$//; $video_mp4 .= ".hb.mp4";
160 print " Re-quantizing input video content: $video_mp4\n";
161 my $handbrake_cmd = "$handbrake $deinterlace_option $requantize_option $handbrake_options -i \"$video\" -o \"$video_mp4\" > /dev/null 2>&1";
162 if(! defined $opt_s) {
163 my $errno = system("$handbrake_cmd");
164 $errno = $errno >> 8;
167 die "-E- handbrake encountered some errors with exit code $errno\n";
171 # Push the name of our intermediate video file onto a list of files to delete on exit
172 push(@video_tmp_files, "$video_mp4");
173 # Update the name of our video file to equal the name of our new intermediate video file name
177 # Create our input file command line options for this video
178 if($video_count == 0) {
179 $cmd .= " $input_file_options \"$video\"";
181 $cmd .= " $input_file_options + \"$video\"";
186 # Execute our command line
188 if(! defined $opt_s) {
189 my $errno = system("$cmd");
190 $errno = $errno >> 8;
193 die "-E- mkvmerge encountered some errors with exit code $errno\n";
197 # Remove the temporary file used for the chapter generation
198 if(-e "$tmpfile") { unlink "$tmpfile"; }
200 # Remove any temporary video files created during the merge process
201 foreach my $video (@video_tmp_files) {
202 if(-e "$video") { unlink "$video"; }
205 ####################################################################################################