#!/usr/bin/perl -w

$|++;

$def{tracklen} = 0;
$def{filesize} = 700;
$def{audiorate} = 192;

open(D, "<$ENV{HOME}/.calc_bitrate") && do {
	while(<D>) {
		chomp;
		s/#.*//;
		my ($k, $v) = split;
		$v ||= "";
		$def{$k} = $v if $k;
	}
	close D;
};

print "Length of input (seconds or hh:mm:ss, \"d\" to scan DVD) [$def{tracklen}]: ";
chomp ($length = <>);

$length = $def{tracklen} if $length eq "";

if($length =~ /^[\d:]+$/) {
	if($length =~ /(?:(\d?\d):)?(\d\d):(\d\d)/) {
		my $newlength = $3 + 60 * $2 + 3600 * $1;
		print "$length == $newlength seconds\n";
		$length = $newlength;
	}
} elsif($length =~ /^d/i) {
	open L, "lsdvd|" or die "Can't find lsdvd in PATH\n";
	while(<L>) {
		chomp;
		next unless $_;
		print $_, "\n";
#Title: 01, Length: 02:56:48.066 Chapters: 19, Cells: 20, Audio streams: 01, Subpictures: 03
		if(/^Title:\s*(\d+),\s*Length:\s*(\d?\d):(\d\d):(\d\d)(?:\.\d+)?\s*Chapters:\s*(\d+)/)
		{
			my $track = $1;
			my $len = $4 + 60 * $3 + 3600 * $2;
			my $chaps = $5;
			$tracklens{$track+0} = $len;
#			$trackchaps{$track+0} = $chaps;
		}
		$dtrack = $1 if /^Longest track: (\d+)/;
	}

	print "Select track [$dtrack]: ";
	chomp ($track = <>);
	$track = $dtrack unless $track;
	$track += 0;
	$length = $tracklens{$track};
} else {
	die "Invalid length\n";
}

print "Desired AVI size in megabytes [$def{filesize}]: ";
chomp ($s = <>);
$size = $s ? $s : $def{filesize};

print "Audio bitrate [$def{audiorate}]: ";
chomp ($b = <>);
$abit = $b ? $b : $def{audiorate};

open(D, ">$ENV{HOME}/.calc_bitrate") && do {
	print D "audiorate $abit\n" if $abit;
	print D "tracklen $length\n" if $length;
	print D "filesize $size\n" if $size;
};

close D;

# calculate total bitrate:
$totalbits = $size * 1024 * 1024 * 8;
$bits_sec = $totalbits / $length;
$kbits_sec = $bits_sec / 1000;
$vbit = $kbits_sec - $abit;

# fudge factor:
#$vbit *= 0.985;
$vbit *= 0.992;

print "Video bitrate for $length seconds \@ $size MB: $vbit\n";
