#!/bin/sh
#
#  Multipass Xvid encoding
#
#  -i2 for dv
#
#  high bitrate -a224 -b7500 if it underruns
#  medium bitrate -a224 -b7000 if it underruns
#  low bitrate -a192 -b6000 if it underruns
#  very low bitrate -a96 -b5000 if it underruns
#
def_abitrate=224
def_bitrate=7000
def_WxH=720x480
def_docrop=false
def_interlace=2
def_ratio=2

help(){
    cat <<END
Usage: $0 [options] <filename.[avi|mov|qt|dv|mpg]>
Options:
    -a n      Set the audio bitrate                 ($def_abitrate)
    -b n      Set the bitrate                       ($def_bitrate)
    -g WxH    Width and height of the output stream ($def_WxH)
    -c        Crop the bottom by 3.333333%          ($def_docrop)
    -i n      n=0 progressive, n=1 top, n=2 bottom  ($def_interlace)
    -r n      aspect ratio, n=1 4:3, n=2 16:9       ($def_ratio)
    -h        Print this help message
END
    exit 0
}

abitrate=$def_abitrate
bitrate=$def_bitrate
WxH=$def_WxH
docrop=$def_docrop
interlace=$def_interlace
ratio=$def_ratio

while getopts a:b:cg:i:r:h name "$@"
do
    case $name in
a)  
    abitrate=$OPTARG ;;
b)  
    bitrate=$OPTARG ;;
c)
    docrop=true ;;
g)
    WxH=$OPTARG ;;
i)
    interlace=$OPTARG ;;
r)
    ratio=$OPTARG ;;
*)
    help ;;
    esac
done
let shiftind=$OPTIND-1
shift $shiftind

if test "$#" != "1"
then
	help
	exit
fi
case $1 in
*.qt)
	type=mov
    input="$1"
    base=`echo $input | sed "s/\.qt$//"` ;;
*.mov)
	type=mov
    input="$1"
    base=`echo $input | sed "s/\.mov$//"` ;;
*.dv)
	type=dv
    input="$1"
    base=`echo $input | sed "s/\.dv$//"` ;;
*.mpg)
	type=mpeg2,mp3
    input="$1"
    base=`echo $input | sed "s/\.mpg$//"`-dvd ;;
*.avi)
	type=ffmpeg
    input="$1"
    base=`echo $input | sed "s/\.avi$//"` ;;
*)
    help ;;
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 Encoding $input to $base.mpg....

case $interlace in
0)
    fields=p
    dnmode=0 ;;
1)
    fields=t
    dnmode=1 ;;
*)
    fields=b
    dnmode=1 ;;
esac
case $ratio in
2)
    aflag="--export_asr 3 --export_par 5" ;;
*)
    aflag="--export_asr 2 --export_par 3" ;;
esac
echo transcode -i $input -x $type -Z $WxH \
	$aflag --encode_fields $fields \
	-Jyuvdenoise=mode=$dnmode:sharpen=0:border=0x0-$crop \
	-y mpeg2enc,toolame -E 48000,16,2 \
	-F 8 -w $bitrate -b $abitrate -o $base

sleep 5
transcode -i $input -x $type -Z $WxH \
	$aflag --encode_fields $fields \
	-Jyuvdenoise=mode=$dnmode:sharpen=0:border=0x0-$crop \
	-y mpeg2enc,toolame -E 48000,16,2 \
	-F 8 -w $bitrate -b $abitrate -o $base

mplex -f 8 $base.m2v $base.mp2 -o $base.mpg
