#!/bin/bash
#
#  Single pass Xvid encoding
#
def_bitrate=1200
def_WxH=320x240
def_outfile=out.avi
def_wave=out.wav
def_docrop=false
def_interlace=0
def_passnum=0

help(){
	cat <<END
Usage: $0 [options]
Options:
	-b n      Set the bitrate                       ($def_bitrate)
	-g WxH    Width and height of the output stream ($def_WxH)
	-o s      Write the output to file with name    ($def_outfile)
	-p s      Wave file to multiplex with input     ($def_wave)
	-c        Crop the bottom by 3.333333%          ($def_docrop)
	-i n      n=0 progressive, n=1 top, n=2 bottom  ($def_interlace)
	-R n      n=0 single pass, n=1,2 multipass      ($def_passnum)
	-h        Print this help message
END
    exit 0
}

bitrate=$def_bitrate
WxH=$def_WxH
outfile=$def_outfile
docrop=$def_docrop
interlace=$def_interlace
wave=$def_wave
passnum=$def_passnum

while getopts b:cg:i:o:p:hR: name "$@"
do
	case $name in
b)
	bitrate=$OPTARG ;;
c)
	docrop=true ;;
g)
	WxH=$OPTARG ;;
i)
	interlace=$OPTARG ;;
o)
	outfile=$OPTARG ;;
p)
	wave=$OPTARG ;;
R)
	passnum=$OPTARG ;;
*)
	help ;;
	esac
done
let shiftind=$OPTIND-1
shift $shiftind

case $outfile in
*/*)
	newdir=`echo $outfile | sed "s/\/[^/]*$//"` 
	if cd $newdir
	then
		:
	else
		echo "Couldn't change to directory $newdir...."
		exit 1
	fi ;;
esac

case $docrop in
true)
	width=`echo $WxH | sed "s/x.*$//"`
	height=`echo $WxH | sed "s/^.*x//"`
	let height=$height-$height*10/300
	crop=${width}x${height} ;;
*)
	crop=$WxH ;;
esac

echo Multiplexing stdin with $wave to $outfile....

case $interlace in
0)
	fields=p
    dnmode=0
	sed "s/^interlaced.*$/interlaced = 0/;
		s/^topfieldfirst.*$/topfieldfirst = 0/" \
		< /usr/local/lib/transcode/xvid4.cfg \
		> xvid4.cfg ;;
1)
	fields=t
    dnmode=1
	sed "s/^interlaced.*$/interlaced = 1/;
        s/^topfieldfirst.*$/topfieldfirst = 1/" \
		< /usr/local/lib/transcode/xvid4.cfg \
		> xvid4.cfg ;;
*)
	fields=b
    dnmode=1
	sed "s/^interlaced.*$/interlaced = 1/;
        s/^topfieldfirst.*$/topfieldfirst = 0/" \
		< /usr/local/lib/transcode/xvid4.cfg \
		> xvid4.cfg ;;
esac

{
case $interlace in
0)
		yuvcorrect -T PROGRESSIVE 2>/dev/null ;;
1)
		yuvcorrect -T INTERLACED_TOP_FIRST 2>/dev/null ;;
*)
		yuvcorrect -T INTERLACED_BOTTOM_FIRST 2>/dev/null ;;
esac
} | yuvscaler -O SIZE_$WxH 2>/dev/null |
transcode -i /proc/self/fd/0 -p $wave -x yuv4mpeg \
	-g $WxH -f 29.970,4 -e 44100,16,2 \
	--export_asr 2 --export_par 1 --encode_fields $fields \
	-Jyuvdenoise=mode=$dnmode:sharpen=0:border=0x0-$crop \
	-R $passnum -y xvid4 -b 192 -w $bitrate -o $outfile

#rm xvid4.cfg
