#!/usr/bin/perl -w

# MPlayer DVD Stream dumper is a simple wrapper for MPlayer's dumpstream feature written in Perl.
# Copyright (C) 2007  Rune T. Sorensen
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# The GNU GPL can be found here: http://www.gnu.org/licenses/gpl.html#SEC1
# 
# Contact info: 
# Email: rune [at] areian [dot] net
# Homepage: http://www.areian.net

$name = "MPlayer DVD Stream dumper";
$version = "0.2.1";

#User options:
$dump_dir = "/path/to/dump/folder"; #Note that there's no trailing slash.
#User options end

$dump_dir =~ s/ /\\ /g; # Replaces all " "-chars with "\ " in order to process the blankspaces on the commandline
print "$name version $version, Copyright (C) 2007 Rune T. Sorensen\n";
print "$name comes with ABSOLUTELY NO WARRANTY.\n";
print "This is free software, and you are welcome\n";
print "to redistribute according to the GNU GPL.\n\n";

unless(-d $dump_dir) { # Check if $dump_dir exists, and if it doesn't:
	print "The directory $dump_dir doesn't exist. Create it? [y/n] ";
	if(<STDIN> =~ /^[yY]/) {
		system("mkdir -p $dump_dir");
	} else {
		exit;
	}
}

print "DVD titles: ";
@titlenumbers = split(/ /, <STDIN>);
chomp(@titlenumbers);

%dvd = ();
foreach (@titlenumbers) {
	print "Name of title #$_: ";
	chomp($dvd{$_} = <STDIN>);
	$dvd{$_} =~ s/ /\\ /g; # Replaces all " "-chars with "\ " in order to process the blankspaces on the commandline
}

while(($titlenumber, $titlename) = each(%dvd)) {
	if(-e "$dump_dir/$titlename.vob")  { # Checks if the dump file already exists
		print "The file $titlename.vob already exists in $dump_dir. Overwrite? [y/n] ";
		unless(<STDIN> =~ /^[yY]/) {
			exit;
		}
	}
	$dump_msg = "Dumping DVD title $titlenumber to \"$dump_dir\" as \"$titlename.vob\" ..... ";
	$dump_msg =~ s/\\ / /g;
	print $dump_msg;
	
	$procstart = time;
	open(MPLAYER, "mplayer dvd://$titlenumber -dumpstream -dumpfile $dump_dir/$titlename.vob|");
	while(<MPLAYER>) {
	}
	close(MPLAYER);
	($sec, $min, $hour) = gmtime(time - $procstart);
	print "Dump completed in: $hour hours, $min minutes and $sec seconds\n";
}
print "All done, exiting.\n";
