#!/bin/sh
#
#  high bitrate -a224 -b6500 if it underruns
#  medium bitrate -a224 -b6000 if it underruns
#  low bitrate -a192 -b5500 if it underruns
#  very low bitrate -a96 -b5000 if it underruns
#
# quantizer values are essentially half that of mjpegtools
#
def_abitrate=224
def_bitrate=6000
def_interlace=2
def_ratio=2

help(){
    cat <<END
Usage: $0 [options] <filename.[mov|qt|dv|mpg|avi]>
Options:
    -a n      Set the audio bitrate                 ($def_abitrate)
    -b n      Set the bitrate                       ($def_bitrate)
    -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
interlace=$def_interlace
ratio=$def_ratio

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

if test "$#" != "1"
then
	help
fi
case $1 in
*.qt)
    input="$1"
    base=`echo $input | sed "s/\.qt$//"` ;;
*.mov)
    input="$1"
    base=`echo $input | sed "s/\.mov$//"` ;;
*.avi)
    input="$1"
    base=`echo $input | sed "s/\.avi$//"` ;;
*.dv)
    input="$1"
    base=`echo $input | sed "s/\.dv$//"` ;;
*.mpg)
    input="$1"
    base=`echo $input | sed "s/\.mpg$//"`-dvd ;;
*)
    help ;;
esac

echo Encoding $input to $base.mpg....

case $interlace in
0)
	flags=""
    ;;
1)
	flags="-ildct -ilme -top 1"
    ;;
*)
	flags="-ildct -ilme -top 0"
    ;;
esac
case $ratio in
2)
    aflag="-aspect 16:9" ;;
*)
    aflag="-aspect 4:3" ;;
esac

echo ffmpeg -threads 2 -i $input $aflag $flags \
	-target dvd -qmin 4 -b $bitrate -ab $abitrate -y $base.mpg

sleep 5

ffmpeg -threads 2 -i $input $aflag $flags \
	-target dvd -qmin 4 -b $bitrate -ab $abitrate -y $base.mpg
