#!/usr/bin/perl

# USAGE:
#     On dvd::rip > Transcode:
#     Type 'theora' in  Video options > Video codec
#     Select  Video options > 2-pass encoding > No
#     Optionally enter video bitrate. Theora quality will be 
#     calculated as kbps/100 (0-1000 kbps).
#
# BACKGROUND
#     I like using dvd::rip for encoding my DVDs. And I like the ideas
#     behind Theora, so I would like to encode my DVDs to Theora using
#     dvd::rip.
#     
#     Dvd::rip uses transcode for transcoding. But transcode seems not
#     to support Theora yet. So I have here created a hack that does
#     the transcoding.
#     
#     It would be nice if the hack was included in dvd::rip until
#     transcode supports Theora natively.
#
# BUGS
#     Does not respect vorbis quality setting
#
# LICENSE
#     Same license as dvd::rip
#
# AUTHOR
#     2004-01-09 Ole Tange http://ole.tange.dk
#

use strict;

my $theora=0;
for my $a (@ARGV) {
    my ($vcodec,$acodec) =  split /,/, $a;
    if($vcodec =~ /theora/) {
	# Magic
	$theora=1;
    }
}

if(not $theora) {
    print STDERR "DVDRIP_JOB_PID=$$\n";
    exec @ARGV;
} else {
    print STDERR "DVDRIP_JOB_PID=$$\n";
    my ($video_quality,$theora,$outputfile,$yuv_file,$wav_file);
    my (@yuv_argv, @wav_argv);
    while(@ARGV) {
	my $a = shift (@ARGV);
	if(in($a,"transcode","--a52_drc_off","-k","-V")) {
	    # single arg
	    push @yuv_argv, $a;
	    push @wav_argv, $a;
	} elsif(in($a,"--print_status", "-B", "-H", "-R", "-Y", "-Z", "-a",
		   "-b", "-c", "-f", "-i", "-s", "-x", )) {
	    # arg with parameter
	    my $arg = shift @ARGV;
	    push @yuv_argv, $a, $arg;
	    push @wav_argv, $a, $arg;
	} elsif(in($a,"-m")) {
	    # secondary output - ignored
	    shift @ARGV;
	} elsif(in($a,"-w")) {
	    my $video_kbps =  shift @ARGV;
	    push @yuv_argv, $a, $video_kbps;
	    push @wav_argv, $a, $video_kbps;
	    $video_quality = $video_kbps < 1000 ? $video_kbps/100 : 10;
	} elsif(in($a,"-o")) {
	    $outputfile =  shift @ARGV;
	    $yuv_file = $outputfile."yuv";
	    $wav_file = $outputfile."wav";
	    push @yuv_argv, $a, $yuv_file;
	    push @wav_argv, $a, $wav_file;
	} elsif(in($a,"-y")) {
	    shift @ARGV;
	    push @yuv_argv, "-k", "-y", "yuv4mpeg,null";
	    push @wav_argv, "-k", "-y", "null,wav";
	} else {
	    warn("Unknown option '$a' - ignored");
	}
    }
    my @encode_argv = ("encoder_example","-a", 4, ### Vorbis quality - hardcoded ###
		    "-v", $video_quality, "-o", $outputfile.".ogm",
		    $wav_file, $yuv_file);
    open STDERR, ">$outputfile-stderr";
    print STDERR "@yuv_argv\n";
    print STDERR "@wav_argv\n";
    print STDERR "@encode_argv\n";
    unlink $yuv_file;
    unlink $wav_file;
    system("mkfifo",$yuv_file);
    system("mkfifo",$wav_file);
    if(! fork()) { exec(@yuv_argv); }
    if(! fork()) { exec(@wav_argv); }
    exec(@encode_argv);
}

sub in {
    my($test,@set)=@_;
    for my $t (@set) {
	if($t eq $test) {
	    return 1;
	}
    }
    return 0;
}
