#!/bin/sh
#
#  Single pass ffmpeg mpeg4 encoding
#
#  high bitrate -a224 -b2000 if it underruns
#  medium bitrate -a224 -b1800 if it underruns
#  low bitrate -a192 -b1600 if it underruns
#  very low bitrate -a96 -b1200 if it underruns
#
#  quantizer values are essentially half that of mjpegtools
#
def_ratio=1
def_size=1

help(){
    cat <<END
Usage: $0 [options] <filename.[mov|qt|dv|mpg|avi]>
Options:
    -r n      n=1 4:3, n=2 16:9 to panscan          ($def_ratio)
	-s n      n=1 320x240, n=2 160x120, n=3 96x72   ($def_size)
    -h        Print this help message
END
    exit 0
}

ratio=$def_ratio
size=$def_size

while getopts r:s:h name "$@"
do
    case $name in
r)
    ratio=$OPTARG ;;
s)
	size=$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$//"` ;;
*)
    help ;;
esac

echo Encoding $input to $base.avi....

case $ratio in
2)
    aflag="-cropleft 90 -cropright 90 -aspect 4:3" ;;
*)
    aflag="-aspect 4:3" ;;
esac
case $size in
3)
	sflag="-s 96x72 -qmin 1" ;;
2)
	sflag="-s 160x120 -qmin 2" ;;
*)
	sflag="-s 320x240 -qmin 3" ;;
esac


echo ffmpeg -i $input $aflag \
	-deinterlace -interlace 0 -r ntsc $sflag \
	-vcodec mpeg4 -acodec ac3 -ar 44100 \
	-b 360 -ab 96 -y $base.mp4

sleep 5

ffmpeg -i $input $aflag \
	-deinterlace -interlace 0 -r ntsc $sflag \
	-vcodec mpeg4 -acodec ac3 -ar 44100 \
	-b 360 -ab 96 -y $base.mp4
