#!/usr/local/bin/perl

# DVB MPEG2 -> RISC OS MPEG1 conversion script
# © Jeffrey Lee, 2006
# See http://www.iconbar.com/forums/viewthread.php?newsid=1096 for more info

# Input and output folders
$src_folder = 'E:/v';
$dest_folder = 'E:/v-mini';

# Processing tools
$mpgtx = 'E:/mpgtx.exe';
$ffmpeg = 'E:/ffmpeg.exe';
$toolame = 'E:/toolame.exe';

# Temp files
$tempwav = 'E:/tempwav.wav';
$tempmp2 = 'E:/tempmp2.mp2';
$tempmpg = 'E:/tempmpg.mpg';

# Array of problem files. name -> output resolution
$problem_files{'apocalypse_now.mpg'} = '480x270';
$problem_files{'azumi.mpg'} = '480x270';
$problem_files{'kagemusha.mpg'} = '480x270';
$problem_files{'minority_report.mpg'} = '480x270';
$problem_files{'princess_mononoke.mpg'} = '480x270';

# Scan the input folder
opendir DH,$src_folder;
while ($current = readdir DH) {
	if($current =~ m/\.mpg$/i) {
		# Is this file already processed?
		if(open(FH,$dest_folder . '/' . $current)) {
			close FH;
		} else {
			process($current);
		}
		# Now check if we need to fix the audio
		# Done as post-process to try and ensure AV sync in resulting file
		if(open(FH,$dest_folder . '/' . $current)) {
			close FH;
			process2($current);
		}
	}
}

sub process {
	my ($file) = @_;
	print "Processing $file\n";
	# Run mpgtx to get info about the file
	$info = qx($mpgtx -i $src_folder/$file);
	# ... then decide on output resolution
	if($info =~ m/Aspect Ratio 16\/9/i) {
		$res = '480x270';
	} elsif($info =~ m/Aspect Ratio 4\/3/i) {
		$res = '416x312';
	} elsif(exists $problem_files{$file}) {
		$res = $problem_files{$file};
	} else {
		print "Unknown aspect ratio! Skipping\n";
		return;
	}
	# ... then run ffmpeg
	system "$ffmpeg -i \"$src_folder/$file\" -vcodec mpeg1video -r 25 -s $res -b 850k -acodec copy \"$dest_folder/$file\""; 
}

sub process2 {
	my ($file) = @_;
	# Run mpgtx to get info about the file
	$info = qx($mpgtx -i $dest_folder/$file);
	# Is the audio already downsampled?
	if($info =~ m/ 128 kbps/i) {
		return;
	}
	print "Resampling audio for $file\n";
	# Extract the audio
	system "$ffmpeg -i \"$dest_folder/$file\" -ar 48000 $tempwav";
	# Run it through toolame
	system "$toolame -s 48 -b 128 $tempwav $tempmp2";
	# Put it back into the mpeg
	system "$ffmpeg -i \"$dest_folder/$file\" -i $tempmp2 -vcodec copy -acodec copy -map 0:0 -map 1:0 $tempmpg";
	# Check it worked!
	open(FH,$tempmpg) or die "ffmpeg failed multiplexing new audio?\n";
	close FH; 
	# Get rid of the original and temp files
	unlink $tempwav, $tempmp2, "$dest_folder/$file";
	# Rename temp file
	rename $tempmpg, "$dest_folder/$file" or die "Can't rename temp file!\n";
}


