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/
10 ####################################################################################################
18 use DateTime::Duration;
19 use DateTime::Format::Duration;
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"; }
29 ####################################################################################################
30 # Command Line Options
31 getopts("svqzt:o:i:h");
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"; }
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";
52 $SIG{'INT'} = sub {die "-E- Killed by CTRL-C\n"};
53 ####################################################################################################
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;
62 ####################################################################################################
65 # Turn the list of input videos into a hash with a value equal to the modification time in epoch seconds
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;
74 ####################################################################################################
75 # 1) Create the mkv video
76 print "-> Creating MKV video files with basename '$opt_o'\n";
78 # Make our input file command line options for all the 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/;
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
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/
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; }
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";
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;
116 print "-W- avconv encountered some errors with exit code $errno\n";
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
130 print " Detected progressive video content: $video\n";
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)) {
140 my $handbrake_options = "";
142 # Set our output video filename
143 my $video_mp4 = $video; $video_mp4 =~ s/\.[^.]*$//; $video_mp4 .= ".hb.mp4";
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; }
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);
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
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"; }
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"; }
179 # Set our de-interlace option accordingly
180 my $deinterlace_option = "";
181 if(!$progressive) { $deinterlace_option = "-d"; }
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;
192 die "-E- handbrake encountered some errors with exit code $errno\n";
197 print " Copying input video content to: $video_mp4\n";
198 system("cp \"$video\" \"$video_mp4\"") if(!$opt_s);
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
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.
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"; }
222 my $audio_stream_info = `$ffprobe "$video" 2>&1 | grep -e "Stream.*Audio"`; chomp($video_stream_info);
223 my $audio_handler = "unknown";
224 if($audio_stream_info =~ / Hz, ([^,]+), /) { $audio_handler = "$1"; }
225 else { print "-W- ffprobe was unable to find audio handler for video: $video\n"; }
228 my $audio_codec = "unknown";
229 if($audio_stream_info =~ /Audio: (\S+) /) { $audio_codec = "$1"; }
230 else { print "-W- ffprobe was unable to find audio codec for video: $video\n"; }
232 # Now create our parameters string
233 my $parameters = "$dimensions.$audio_handler.$audio_codec";
235 print " Adding video $video to be merged into output video file: $opt_o.$parameters.mkv\n" if($opt_v);
236 push @{$merge_videos{"$parameters"}}, $video;
240 print "\n-> Merge videos hash:\n";
241 print Dumper(\%merge_videos);
245 ####################################################################################################
246 # 3) Create a chapter file for each destination video file
248 # 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
249 my $chapter_file = `tempfile`; chomp($chapter_file); unlink "$chapter_file";
251 foreach my $key (keys %merge_videos) {
252 # Create the chapters file for each output mkv file.
253 # Make each video file it's own chapter in the MKV file.
254 # Name the chapter with the date and time the video clip was taken (modified date).
255 print "-> Creating $opt_o.$key.mkv with title '$opt_t' from the following video files in last modified date order:\n";
256 open(CHAPTERS,">$chapter_file.$key") || die "-E- Unable to create chapter file: $chapter_file.$key\n";
258 my $chapter_timecode = DateTime::Duration->new(years => 2000, hours => 0, minutes => 0, seconds => 0);
259 my $timecode_format = DateTime::Format::Duration->new(pattern => '%H:%M:%S.%3N', normalize => 1);
260 foreach my $video (@{$merge_videos{$key}}) {
265 my $mtime_epoch = stat("$video")->mtime;
266 my $mdate = epoch_to_date($mtime_epoch);
267 my $duration = `$ffmpeg -i "$video" 2>&1 | grep Duration`;
268 if($duration =~ /Duration: (\d+):(\d+):(\d+)\.(\d+)/) {
273 my $timecode = $timecode_format->format_duration($chapter_timecode);
274 print "$mdate $hour:$min:$sec -> $video \n";
275 print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."=".$timecode."\n";
276 print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."NAME=".$mdate."\n";
277 my $dt = DateTime::Duration->new(years => 2000, hours => $hour, minutes => $min, seconds => $sec);
278 $chapter_timecode = $chapter_timecode + $dt;
281 print "\n-> Creating the following chapter file $chapter_file.$key for this video:\n";
282 $chapter_file_contents = `cat $chapter_file.$key`;
283 print "$chapter_file_contents\n";
286 ####################################################################################################
287 # 4) Run mkvmerge to merge all of the videos together of the same parameters
288 foreach my $key (keys %merge_videos) {
289 my $merge_cmd = "$mkvmerge --title \"$opt_t\" $output_file_options --chapters $chapter_file.$key -o \"$opt_o.$key.mkv\"";
291 foreach my $video (@{$merge_videos{$key}}) {
293 $merge_cmd .= " $input_file_options \"$video\"";
295 $merge_cmd .= " $input_file_options + \"$video\"";
299 print "\n$merge_cmd\n";
300 if(! defined $opt_s) {
301 if(-f "$opt_o.$key.mkv") { die "-E- Output video file $opt_o already exists. This is unexpected for key $key!"; }
302 my $errno = system("$merge_cmd");
303 $errno = $errno >> 8;
305 unlink "$opt_o.$key.mkv";
306 die "-E- mkvmerge encountered some errors with exit code $errno\n";
311 ####################################################################################################
312 # 5) Remove all temporary files
314 # Remove the temporary file used for ffmpeg and handbrake output
315 if(-e "$tmpfile") { unlink "$tmpfile"; }
317 # Remove the temporary file used for the chapter generation
318 foreach my $key (keys %merge_videos) {
319 if(-e "$chapter_file.$key") { unlink "$chapter_file.$key"; }
322 # Remove any temporary video files created during the merge process
323 foreach my $video (@video_tmp_files) {
324 if(-e "$video") { unlink "$video"; }
328 ####################################################################################################