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

help(){
    cat <<END
Usage: $0 [options] filename.anything
Options:
    -i n      n=0 prog, n=1 top, n=2 bot            ($def_interlace)
    -s n      n=0 no change, n=1 720p30             ($def_rescale)
    -q n      subpixed refinement quality
              n=1 lowest, ..., n=7 highest          ($def_subq)
    -h        Print this help message
END
    exit 0
}

interlace=$def_interlace
rescale=$def_rescale
subq=$def_subq

while getopts s:i:q:h name "$@"
do
    case $name in
i)
    interlace=$OPTARG ;;
s)
    rescale=$OPTARG ;;
q)
    subq=$OPTARG ;;
*)
    help ;;
    esac
done
let shiftind=$OPTIND-1
shift $shiftind
if test "$#" != "1"
then
    help
fi

outfile=$1
base=`echo $outfile | sed "s/\.[^.]*$//"`

case $interlace in
0)
    iflag_m=NOT_INTERLACED
	xint_f="nointerlaced"
	scale_f="-vf scale=1280:720"
	int_f="" ;;
1)
    iflag_m=INTERLACED_TOP_FIRST
	xint_f="interlaced"
	scale_f="-vf yadif=0:0,scale=1280:720"
	int_f="-field-dominance 0" ;;
*)
	iflag_m=INTERLACED_BOTTOM_FIRST
	xint_f="interlaced"
	scale_f="-vf yadif=0:1,scale=1280:720"
	int_f="-field-dominance 1" ;;
esac

case $rescale in
1)
	xint_f="nointerlaced" ;;
*)
	scale_f="" ;;
esac

echo "Encoding yuv4mpeg on /dev/stdin to $base.avi"
sleep 5

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"

yuvcorrect -T $iflag_m 2>/dev/null |
mencoder /dev/stdin -nosound $int_f \
	-aspect 16:9 $scale_f \
    -ovc x264 -x264encopts $encopts \
    -of rawvideo -o $base.264
