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;
20 use DateTime::Format::Strptime qw( );
22 # Set our ffmpeg creation_time format
23 $ffmpeg_time_format_utc = DateTime::Format::Strptime->new(pattern=>'%Y-%m-%dT%H:%M:%S', time_zone => 'UTC', on_error => 'croak');
24 $ffmpeg_time_format_local = DateTime::Format::Strptime->new(pattern=>'%Y-%m-%dT%H:%M:%S', time_zone => 'local', on_error => 'croak');
26 ####################################################################################################
27 # Configuration parameters
28 $mydir = `cd \$(dirname $0) 2>/dev/null; pwd`; chomp($mydir); unshift @INC,("$mydir");
29 # Default configuration values
30 require "organize_videos.conf";
31 # Override defaults with local customizations
32 if( -f "$mydir/organize_videos.conf.local") { require "organize_videos.conf.local"; }
34 ####################################################################################################
35 # Command Line Options
36 getopts("svqzt:o:i:h");
38 if(! defined $opt_t) { &usage(); die "-E- Missing required title: -t <title>\n"; }
39 if(! defined $opt_o) { &usage(); die "-E- Missing required argument output video names: -o <output.mkv>\n"; }
40 if(! defined $opt_i) { &usage(); die "-E- Missing required argument input video names: -i <input,input,...>\n"; }
41 if(! -x $ffmpeg) { die "-E- Missing required executable for ffmpeg: $ffmpeg\n"; }
42 if(! -x $avconv) { die "-E- Missing required executable for avconv: $avconv\n"; }
45 print "usage: $0 -t <title> -o <output.mkv> -i <input,input,...>\n";
46 print " -t <title> Sets the general title for the output video file\n";
47 print " -o <output> Sets the basename of the output mkv file\n";
48 print " -i <input,input,...> Sets the names of the input files to combine into a new mkv file\n";
49 print " -q Requantize input videos to decrease output video size (requires HandBrakeCLI)\n";
50 print " -z Recompress input videos to decrease output video size (requires HandBrakeCLI)\n";
51 print " -s Simulate mode. Don't actually make the video, but tell us what you will do\n";
52 print " -v Increase verbosity for debug\n";
57 $SIG{'INT'} = sub {die "-E- Killed by CTRL-C\n"};
58 ####################################################################################################
62 my $mtime = DateTime->from_epoch(epoch => $epoch);
63 $mtime->set_time_zone($timezone);
64 return sprintf("%4d",$mtime->year)."-".sprintf("%02d",$mtime->month)."-".sprintf("%02d",$mtime->day)." ".$mtime->hms;
67 ####################################################################################################
70 # Turn the list of input videos into a hash with a value equal to the modification time in epoch seconds
72 foreach $video (split(/,/, $opt_i)) {
73 if(! -r "$video") { die "-E- Unable to read input video file: $video\n"; }
75 my $creation_time = `$ffmpeg -i "$video" 2>&1 | grep "creation_time" | head -n 1 | awk '{print \$3}'`;
76 my $brands = `$ffmpeg -i "$video" 2>&1 | grep "compatible_brands" | tail -n 1`; chomp($brands);
78 my $date_taken = $ffmpeg_time_format_utc->parse_datetime($creation_time);
79 if ($brands && $brands =~ /$local_tz_brands/) {
80 $date_taken = $ffmpeg_time_format_local->parse_datetime($creation_time);
82 $date_taken->set_time_zone('local');
83 $mtime_epoch = $date_taken->epoch;
85 $mtime_epoch = stat("$video")->mtime;
87 my $mdate = epoch_to_date($mtime_epoch);
88 $videos{$video} = $mtime_epoch;
91 ####################################################################################################
92 # 1) Create the mkv video
93 print "-> Creating MKV video files with basename '$opt_o'\n";
95 # Make our input file command line options for all the videos
98 foreach my $video (sort{$videos{$a} <=> $videos{$b}} keys %videos) {
99 # Make a note of the video extension
100 my $video_ext = $video;
101 $video_ext =~ s/.*\.(\S+)$/$1/;
103 # Detect if the input file is interlaced or not.
104 # 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.
105 # 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.
106 # We will then merge this temporarily created mkv container into the final mkv container instead of the original interlaced video.
107 # http://ubuntuforums.org/showthread.php?t=1627194
108 # http://forum.doom9.org/showthread.php?t=155732&page=31
110 # This is the best way to detect if content is interlaced or progressive:
111 # http://www.aktau.be/2013/09/22/detecting-interlaced-video-with-ffmpeg/
113 my $detect_cmd = "$ffmpeg -filter:v idet -frames:v 100 -an -f rawvideo -y /dev/null -i \"$video\" 2>&1 | grep Parsed_idet";
114 if($opt_v) { print " $detect_cmd\n"; }
115 my $detect_output = `$detect_cmd`;
116 if($detect_output !~ /Progressive:0/) { $progressive = 1; }
118 my $video_mkv = $video;
119 print " Detected interlaced video content: $video\n";
120 # We don't need to do this anymore since it is not an issue with the new mkvmerge
121 if($video_ext !~ /mkv/i) {
122 $video_mkv =~ s/\.[^.]*$//; $video_mkv .= ".ffmpeg.mkv";
123 if(-f $video_mkv) { next; }
124 print " Re-muxing the interlaced video content as an mkv file: $video_mkv\n";
125 my $make_mkv_cmd = "$avconv -y -i \"$video\" -scodec copy -acodec copy -vcodec copy -f matroska \"$video_mkv\" >> \"$tmpfile\" 2>&1";
127 if($opt_v) { print " $make_mkv_cmd\n"; }
128 if(! defined $opt_s) {
129 my $errno = system("$make_mkv_cmd");
130 $errno = $errno >> 8;
133 print "-W- avconv encountered some errors with exit code $errno\n";
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 # Copy the modification date from the src video to the dst video
141 system("touch \"$video_mkv\" -r \"$video\"");
142 # Update the name of our video file to equal the name of our new intermediate video file name
147 print " Detected progressive video content: $video\n";
150 # Re-quantize or re-compress the input video to reduce the resulting output filesize
151 # This also gives us a chance to deinterlace the video as well
152 # Only re-quantize for .MTS videos
153 # We can re-compress any input video
154 my $rotated = "none";
155 if(((defined $opt_q) && ($video_ext =~ /mts/i)) || (defined $opt_z)) {
157 my $handbrake_options = "";
159 # Set our output video filename
160 my $video_mp4 = $video; $video_mp4 =~ s/\.[^.]*$//; $video_mp4 .= ".hb.mp4";
162 # Don't recompress certain file extensions
163 # Unless the video is not progressive or is rotated, then we do need to recompress it to deinterlace or unrotate it
164 my $no_recompress = 0;
165 if($no_recompress_file_ext && $progressive && ($video =~ $no_recompress_file_ext)) { $no_recompress = 1; }
167 # Set our rotate option accordingly to rotate videos taken in portrait mode to landscape
168 my $rotate = `$ffprobe "$video" 2>&1 | grep -e rotate | awk '{print \$3}'`; chomp($rotate);
170 print " Detected rotated input video ($rotate). Rotating video to: $video_mp4\n";
171 if($rotate eq "90") { $handbrake_options .= " --rotate=4"; $rotated = "90"; }
172 if($rotate eq "180") { $handbrake_options .= " --rotate=3"; $rotated = "none"; }
173 $no_recompress = 0; # We have to recompress this video to unrotate it
176 # Set our requantize factor accordingly
177 if(defined $opt_q and ! -f $video_mp4) {
178 print " Re-quantizing input video content to: $video_mp4\n";
179 $handbrake_options = $handbrake_requantize_options;
180 if(!$progressive) { $handbrake_options = "-q $interlaced_requantize_quality"; }
181 else { $handbrake_options = "-q $progressive_requantize_quality"; }
184 # Set our recompress options accordingly
185 if(defined $opt_z and ! -f $video_mp4 and ! $no_recompress) {
186 print " Re-compressing input video content to: $video_mp4\n";
187 $handbrake_options = $handbrake_recompress_options;
188 # 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
189 if($opt_v) { print " $ffmpeg -i \"$video\" 2>&1 | grep \"Audio\" | sed -r -e 's/.*?Audio: (\\S+).*?/\\1/' | tail -n 1\n"; }
190 $AUDIO_CODEC=`$ffmpeg -i "$video" 2>&1 | grep "Audio" | sed -r -e 's/.*?Audio: (\\S+).*?/\\1/' | tail -n 1`; chomp($AUDIO_CODEC);
191 $AUDIO_CODEC =~ s/,$//g;
192 if($AUDIO_CODEC eq "") { print "-W- Unable to extract audio track encoding from input video file: $video\n"; $handbrake_options .= " -E copy"; }
193 else { $handbrake_options .= " -E copy:$AUDIO_CODEC"; }
196 # Set our de-interlace option accordingly
197 my $deinterlace_option = "";
198 if(!$progressive) { $deinterlace_option = "-d"; }
200 # Use HandBrake to requantize/recompress/deinterlace the input video
201 if(! $no_recompress and ! -f $video_mp4) {
202 my $handbrake_cmd = "$handbrake $deinterlace_option $handbrake_options -i \"$video\" -o \"$video_mp4\" >> \"$tmpfile\" 2>&1";
203 if($opt_v) { print " $handbrake_cmd\n"; }
204 if(! defined $opt_s and ! -f $video_mp4) {
205 my $errno = system("$handbrake_cmd");
206 $errno = $errno >> 8;
209 die "-E- handbrake encountered some errors with exit code $errno\n";
211 # Restore the metadata from the original video to the intermediate video to preserve the creation_time of the original video metadata in it
212 `$ffmpeg -i \"$video\" -i \"$video_mp4\" -map 1 -map_metadata 0 -c copy -movflags use_metadata_tags \"$video_mp4.fixed.mp4\" >> \"$tmpfile\" 2>&1`;
213 $errno=system("mv \"$video_mp4.fixed.mp4\" \"$video_mp4\" 2>/dev/null");
214 if($errno) { print "-E- Error moving fixed metadata video back to dstfile: $video_mp4.fixed.mp4 -> $video_mp4\n"; }
218 print " Copying input video content to: $video_mp4\n";
219 system("cp \"$video\" \"$video_mp4\"") if(!$opt_s);
223 # Push the name of our intermediate video file onto a list of files to delete on exit
224 push(@video_tmp_files, "$video_mp4");
225 # Copy the modification date from the src video to the dst video
226 system("touch \"$video_mp4\" -r \"$video\"");
227 # Update the name of our video file to equal the name of our new intermediate video file name
232 ####################################################################################################
233 # 2) Group the encoded videos together by their parameters
234 # We can merge videos that have the same parameters together in a destination video file.
237 my $video_stream_info = `$ffprobe "$video" 2>&1 | grep -e "Stream.*Video"`; chomp($video_stream_info);
238 my $dimensions = "unknown";
239 if($video_stream_info =~ / (\d+x\d+)[,| ]/) { $dimensions = "$1"; }
240 else { print "-W- ffprobe was unable to find dimensions for video: $video\n"; }
243 my $video_stream_info = `$ffprobe "$video" 2>&1 | grep -e "Stream.*Video"`; chomp($video_stream_info);
244 my $video_codec = "unknown";
245 if($video_stream_info =~ / Video: (\S+) /) { $video_codec = "$1"; }
246 else { print "-W- ffprobe was unable to find video codec for video: $video\n"; }
249 my $color_space = "unknown";
250 if($video_stream_info =~ /, (\S+)\(.*?\)/) { $color_space = "$1"; }
251 else { print "-W- ffprobe was unable to find color space for video: $video\n"; }
254 my $audio_stream_info = `$ffprobe "$video" 2>&1 | grep -e "Stream.*Audio"`; chomp($video_stream_info);
255 my $audio_handler = "unknown";
256 if($audio_stream_info =~ / Hz, ([^,]+), /) { $audio_handler = "$1"; }
257 else { print "-W- ffprobe was unable to find audio handler for video: $video\n"; }
260 my $audio_codec = "unknown";
261 if($audio_stream_info =~ /Audio: (\S+) /) { $audio_codec = "$1"; }
262 else { print "-W- ffprobe was unable to find audio codec for video: $video\n"; }
264 # Now create our parameters string
265 my $parameters = "$dimensions.$video_codec.$color_space.$audio_handler.$audio_codec";
267 print " Adding video $video to be merged into output video file: $opt_o.$parameters.mkv\n" if($opt_v);
268 push @{$merge_videos{"$parameters"}}, $video;
272 print "\n-> Merge videos hash:\n";
273 print Dumper(\%merge_videos);
277 ####################################################################################################
278 # 3) Create a chapter file for each destination video file
280 # 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
281 my $chapter_file = `tempfile`; chomp($chapter_file); unlink "$chapter_file";
283 foreach my $key (keys %merge_videos) {
284 # Create the chapters file for each output mkv file.
285 # Make each video file it's own chapter in the MKV file.
286 # Name the chapter with the date and time the video clip was taken (modified date).
287 print "-> Creating $opt_o.$key.mkv with title '$opt_t' from the following video files in last modified date order:\n";
288 open(CHAPTERS,">$chapter_file.$key") || die "-E- Unable to create chapter file: $chapter_file.$key\n";
290 my $chapter_timecode = DateTime::Duration->new(years => 2000, hours => 0, minutes => 0, seconds => 0);
291 my $timecode_format = DateTime::Format::Duration->new(pattern => '%H:%M:%S.%3N', normalize => 1);
292 foreach my $video (@{$merge_videos{$key}}) {
298 my $creation_time = `$ffmpeg -i "$video" 2>&1 | grep "creation_time" | head -n 1 | awk '{print \$3}'`;
299 my $brands = `$ffmpeg -i "$video" 2>&1 | grep "compatible_brands" | tail -n 1`; chomp($brands);
301 my $date_taken = $ffmpeg_time_format_utc->parse_datetime($creation_time);
302 if ($brands && $brands =~ /$local_tz_brands/) {
303 $date_taken = $ffmpeg_time_format_local->parse_datetime($creation_time);
305 $date_taken->set_time_zone('local');
306 $mtime_epoch = $date_taken->epoch;
308 $mtime_epoch = stat("$video")->mtime;
310 my $mdate = epoch_to_date($mtime_epoch);
311 my $duration = `$ffmpeg -i "$video" 2>&1 | grep Duration`;
312 if($duration =~ /Duration: (\d+):(\d+):(\d+)\.(\d+)/) {
317 my $timecode = $timecode_format->format_duration($chapter_timecode);
318 print "$mdate $hour:$min:$sec -> $video \n";
319 print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."=".$timecode."\n";
320 print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."NAME=".$mdate."\n";
321 my $dt = DateTime::Duration->new(years => 2000, hours => $hour, minutes => $min, seconds => $sec);
322 $chapter_timecode = $chapter_timecode + $dt;
325 print "\n-> Creating the following chapter file $chapter_file.$key for this video:\n";
326 $chapter_file_contents = `cat $chapter_file.$key`;
327 print "$chapter_file_contents\n";
330 ####################################################################################################
331 # 4) Run mkvmerge to merge all of the videos together of the same parameters
332 foreach my $key (keys %merge_videos) {
333 my $merge_cmd = "$mkvmerge --title \"$opt_t\" $output_file_options --chapters $chapter_file.$key -o \"$opt_o.$key.mkv\"";
335 foreach my $video (@{$merge_videos{$key}}) {
337 $merge_cmd .= " $input_file_options \"$video\"";
339 $merge_cmd .= " $input_file_options + \"$video\"";
343 print "\n$merge_cmd\n";
344 if(! defined $opt_s) {
345 #if(-f "$opt_o.$key.mkv") { die "-E- Output video file $opt_o already exists. This is unexpected for key $key!"; }
346 my $errno = system("$merge_cmd");
347 $errno = $errno >> 8;
349 unlink "$opt_o.$key.mkv";
350 die "-E- mkvmerge encountered some errors with exit code $errno\n";
355 ####################################################################################################
356 # 5) Remove all temporary files
358 # Remove the temporary file used for ffmpeg and handbrake output
359 if(-e "$tmpfile") { unlink "$tmpfile"; }
361 # Remove the temporary file used for the chapter generation
362 foreach my $key (keys %merge_videos) {
363 if(-e "$chapter_file.$key") { unlink "$chapter_file.$key"; }
366 # Remove any temporary video files created during the merge process
367 foreach my $video (@video_tmp_files) {
368 if(-e "$video") { unlink "$video"; }
372 ####################################################################################################