#!/usr/bin/perl

use strict;
use warnings;

print "\n===== Split up HD Video =====\n";
print "Splits any TS files found in the given directory into 600 second\n";
print "segments. Requires FFMPEG.\n\n";

if (!defined $ARGV[0] || !-d $ARGV[0])
{
  print "usage: video_splitter.pl <dir with ts files>\n";
  exit();
}

opendir(DH, $ARGV[0]) or die("Failed to open directory for reading: " . $ARGV[0]);
my @files = readdir(DH);
closedir(DH);
my $counter = 0;
foreach my $file (@files)
{
  if ($file =~ /^(.*)\.ts$/)
  {
    my $file_prefix = $1;
    print " * Processing: " . $file . "\n";
    my $path = $ARGV[0] . '/' . $file;
    my $mediainfo_command = 'mediainfo --Inform="Video;%Duration/String%" "' . $path . '"';
    my $raw_duration = `$mediainfo_command`;
    my $duration = 0;
    if ($raw_duration =~ /(\d+)h/)
    {
      $duration += $1 * 60;
    }
    if ($raw_duration =~ /(\d+)mn/)
    {
      $duration += $1;
    }
    print " - video is $duration minutes\n";
    if ($duration > 0)
    {
      my $offset = 0;
      my $step = 10;
      while (($offset < 60) && ($offset + $step < $duration))
      {
        $counter++;
        my $output_file = sprintf($file_prefix . '-%03d.ts', $counter);
        my $output_path = $ARGV[0] . '/' . $output_file;
        my $ffmpeg_command = sprintf('ffmpeg -ss 00:%02d:00 -t 600 -i "%s" -vcodec copy -acodec copy -scodec copy "%s" > /dev/null 2>&1', $offset, $path, $output_path);
        print " - cmd: $ffmpeg_command\n";
        print " - generating " . $output_file . "\n";
        `$ffmpeg_command`;
        #rint "DEBUG: $result\n\n";
        $offset += $step;
      }
    }
  }
}
print "Complete!\n\n";
exit;
1;
