#!/bin/sh
#
def_interlace=1
def_subq=6

help(){
    cat <<END
Usage: $0 [options] <filename.[mov|qt|dv|mpg|avi|flv|m2t]>
Options:
    -i n      n=0 prog, n=1 top, n=2 bot            ($def_interlace)
    -q n      subpixed refinement quality
              n=0 lowest, ..., n=7 highets          ($def_subq)
    -h        Print this help message
END
    exit 0
}

interlace=$def_interlace
subq=$def_subq

while getopts i:q:h name "$@"
do
    case $name in
i)
	interlace=$OPTARG ;;
q)
	subq=$OPTARG ;;
*)
    help ;;
    esac
done
let shiftind=$OPTIND-1
shift $shiftind

if test "$#" != "1"
then
	help
fi
case $1 in
*.flv)
    input="$1"
    base=`echo $input | sed "s/\.flv$//"` ;;
*.qt)
    input="$1"
    base=`echo $input | sed "s/\.qt$//"` ;;
*.mov)
    input="$1"
    base=`echo $input | sed "s/\.mov$//"` ;;
*.m2t)
    input="$1"
    base=`echo $input | sed "s/\.m2t$//"` ;;
*.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 $interlace in
0)
    xint_f="nointerlaced"
    int_f="" ;;
1)
    xint_f="interlaced"
    int_f="-field-dominance 0" ;;
*)
    xint_f="interlaced"
    int_f="-field-dominance 1" ;;
esac

#echo mencoder $input $int_f \
#	-ovc x264 -oac lavc \
#	-lavcopts acodec=ac3:abitrate=192 \
#	-x264encopts bitrate=12000:$xint_f:threads=2 \
#	-o $base.avi
#echo ffmpeg -i $base.avi -acodec copy -vcodec copy -f vob -y $base.vob

encopts="bitrate=10000:$xint_f:threads=2:level_idc=41:bframes=2"
encopts=$encopts":frameref=3:nob_pyramid:8x8dct:mixed_refs:bime:brdo"
encopts=$encopts":subq=$subq:trellis=2:aq_mode=1:cqm=flat"

#encopts="bitrate=10000:$xint_f:threads=2:level_idc=41:nob_pyramid:aq_mode=1"

echo mencoder $input -nosound $int_f -aspect 16:9 \
	-ovc x264 -x264encopts $encopts \
	-of rawvideo -o $base.264
echo mencoder $input -ovc copy -oac lavc \
    -lavcopts acodec=ac3:abitrate=192 \
    -of rawaudio -o $base.ac3
echo mkvmerge --default-duration 0:29.97002997002997002997fps $base.264 --default-duration 0:29.97002997002997002997fps $base.ac3 -o $base.mkv

sleep 5

mencoder $input -nosound $int_f -aspect 16:9 \
	-ovc x264 -x264encopts $encopts \
	-of rawvideo -o $base.264
mencoder $input -ovc copy -oac lavc \
    -lavcopts acodec=ac3:abitrate=192 \
    -of rawaudio -o $base.ac3
mkvmerge --default-duration 0:29.97002997002997002997fps $base.264 --default-duration 0:29.97002997002997002997fps $base.ac3 -o $base.mkv
