#!/usr/bin/perl

#
# Simple script that scans the given directory for mkv-files and runs tsremux to create m2ts files from them.
# This to save me the pain of using tsMuxerGui to do one file at a time.. :)
#
# Torgeir <torgeir@sliter.nu>, November 2008.
#


#$useDir = "X:\\dvd_archive\\movies\\_incoming"; 
#$useDir = "F:\\"; 
$useDir = ".";
opendir (DH, $useDir) || die $!;
@files = readdir(DH);
closedir(DH);
@failed = ();
foreach $file (@files) {
	next if $file =~ /^\.$/;
	next if $file =~ /^\.\.$/;

	if ($file !~ /\.mkv$/) {
		print "Skipping non-mkv file '$file'\r\n";
		next;
	}

	print "FIL: $file\r\n";


	$cmd = "tsmuxer.exe \"$useDir". "/". $file; 
	$out = `$cmd`; 
	#print "<OUT>$out</OUT>\r\n";


	$meta = "MUXOPT --no-pcr-on-video-pid --new-audio-pes --vbr --vbr-len=500\n";
	@tracks = split("\n", $out);
	$id = "";
	$type = "";
	$delay = 0;

	$gotId = 0;
	foreach $track (@tracks) {

#		print "sjekker: $track\r\n";

		if (($track =~ /Track ID/) && ($gotId == 1)) {
			#print "PARTIALMATCH\r\n";
			if (($id ne "") && ($type ne "")) {
				#print "id($id) = type=$type delay=$delay\r\n";
				if ($delay != 0) {
					$delay = "timeshift=". $delay. "ms, ";
				} else {
					$delay = ""
				}
				$xtra = "$type, \"$useDir\\$file\", ". $delay. "track=$id\n";
				#print "META_ADD: $xtra";
				$meta = $meta . $xtra;
				$id = "";
				$type = "";
				$delay = 0;
			}	
			$gotId = 0;
		}

		if ($track =~ /Track ID/) {
			@t = split("    ", $track);
			$id = $t[1];
			$gotId = 1;
		}
		if ($track =~ /Stream ID/) {
			@t = split("   ", $track);
			$type = $t[1];
		}
		if ($track =~ /Stream delay/) {
			@t = split(": ", $track);
			$delay = $t[1];
		}
	
	}
	# pick up last track
	if ($gotId == 1) {
		if (($id ne "") && ($type ne "")) {
			#print "id($id) = type=$type delay=$delay\r\n";
			if ($delay != 0) {
				$delay = "timeshift=". $delay. "ms, ";
			} else {
				$delay = ""
			}
			$xtra = "$type, \"$useDir\\$file\", ". $delay. "track=$id\n";
			#print "META_ADD: $xtra";
			$meta = $meta . $xtra;
			$id = "";
			$type = "";
			$delay = 0;
		}	
		$gotId = 0;
	}


	open (OUT, ">$file.meta");
	print OUT $meta;
	close(OUT);

	$outfile = $file;
	$outfile =~ s/\.mkv/\.m2ts/gs;
	$cmd = "tsmuxer \"$file.meta\" \"$outfile\"";

	print "Processing $file...\r\n";
	print "Executing: $cmd\r\n";
	$res = `$cmd`;

	

	if ($res =~ /Mux successful complete/) {
		print "Success for $file! :)\r\n";
	} else {	
		print "Failed to process $file! :(\r\n";
		push(@failed, $file);
	}

}
print "Done processing files\r\n";
for $f (@failed) {
	print "File failed: $f\r\n";
}

$f = <STDIN>;
