+####################################################################################################
+# 3) Create a chapter file for each destination video file
+
+# 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
+my $chapter_file = `tempfile`; chomp($chapter_file); unlink "$chapter_file";
+
+foreach my $key (keys %merge_videos) {
+ # Create the chapters file for each output mkv file.
+ # Make each video file it's own chapter in the MKV file.
+ # Name the chapter with the date and time the video clip was taken (modified date).
+ print "-> Creating $opt_o.$key.mkv with title '$opt_t' from the following video files in last modified date order:\n";
+ open(CHAPTERS,">$chapter_file.$key") || die "-E- Unable to create chapter file: $chapter_file.$key\n";
+ my $chapter_num = 0;
+ my $chapter_timecode = DateTime::Duration->new(years => 2000, hours => 0, minutes => 0, seconds => 0);
+ my $timecode_format = DateTime::Format::Duration->new(pattern => '%H:%M:%S.%3N', normalize => 1);
+ foreach my $video (@{$merge_videos{$key}}) {
+ $chapter_num++;
+ my $hour = 0;
+ my $min = 5;
+ my $sec = 0;
+ my $mtime_epoch = stat("$video")->mtime;
+ my $mdate = epoch_to_date($mtime_epoch);
+ my $duration = `$ffmpeg -i "$video" 2>&1 | grep Duration`;
+ if($duration =~ /Duration: (\d+):(\d+):(\d+)\.(\d+)/) {
+ $hour = $1;
+ $min = $2;
+ $sec = "$3.$4";
+ }
+ my $timecode = $timecode_format->format_duration($chapter_timecode);
+ print "$mdate $hour:$min:$sec -> $video \n";
+ print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."=".$timecode."\n";
+ print CHAPTERS "CHAPTER".sprintf("%02d",$chapter_num)."NAME=".$mdate."\n";
+ my $dt = DateTime::Duration->new(years => 2000, hours => $hour, minutes => $min, seconds => $sec);
+ $chapter_timecode = $chapter_timecode + $dt;
+ }
+ close(CHAPTERS);
+ print "\n-> Creating the following chapter file $chapter_file.$key for this video:\n";
+ $chapter_file_contents = `cat $chapter_file.$key`;
+ print "$chapter_file_contents\n";
+}
+
+####################################################################################################
+# 4) Run mkvmerge to merge all of the videos together of the same parameters
+foreach my $key (keys %merge_videos) {
+ my $merge_cmd = "$mkvmerge --title \"$opt_t\" $output_file_options --chapters $chapter_file.$key -o \"$opt_o.$key.mkv\"";
+ my $i = 0;
+ foreach my $video (@{$merge_videos{$key}}) {
+ if($i == 0) {
+ $merge_cmd .= " $input_file_options \"$video\"";
+ } else {
+ $merge_cmd .= " $input_file_options + \"$video\"";
+ }
+ $i++;