#!/bin/sh
def_abitrate=192
def_bitrate=2000
def_interlace=2
def_ratio=2   

help(){
    cat <<END 
Usage: $0 [options] <filename.[qt|avi|dv|mov|vob]>
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      n=1 4:3, n=2 16:9, n=3 letterbox      ($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$//"` ;;
*.avi)
    input="$1"
    base=`echo $input | sed "s/\.avi$//"` ;;
*.dv)
    input="$1"
    base=`echo $input | sed "s/\.dv$//"` ;;
*.mov)
    input="$1"
    base=`echo $input | sed "s/\.mov$//"` ;;
*.vob)
    input="$1"
    base=`echo $input | sed "s/\.vob$//"` ;;
*)
    help ;;
esac

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

case $interlace in
0)
    flags="-qmin 4" ;;
1)
    flags="-ildct -ilme -top 1 -qmin 4" ;;
*)
    flags="-ildct -ilme -top 0 -qmin 4" ;;
esac
case $ratio in
2)
    aflag="-aspect 16:9" ;;
3)
    aflag="-s 480x360 -padtop 60 -padbottom 60 -aspect 4:3"
    case $interlace in
0)
        flags="-qmin 3" ;;
*)
        flags="-deinterlace -qmin 3" ;;
    esac ;;
*)
    aflag="-aspect 4:3" ;;
esac

echo ffmpeg -i $input -target svcd $aflag $flags -scan_offset \
        -b $bitrate -ab $abitrate -y $base.mpg

sleep 5

ffmpeg -i $input -target svcd $aflag $flags -scan_offset \
        -b $bitrate -ab $abitrate -y $base.mpg
