#!/bin/sh
#
def_interlace=1
def_ratio=2
def_tools=1

help(){
    cat <<END
Usage: $0 [options] filename.anything
Options:
    -i n      n=0 prog, n=1 top, n=2 bot, n=3 deint ($def_interlace)
    -r n      aspect ratio, n=1 4:3, n=2 16:9       ($def_ratio)
    -t n      video, n=0 mjpegtools, n=1 ffmpeg     ($def_tools)
    -h        Print this help message
END
    exit 0
}

interlace=$def_interlace
ratio=$def_ratio
tools=$def_tools

while getopts i:r:t:h name "$@"
do
    case $name in
i)
    interlace=$OPTARG ;;
r)
    ratio=$OPTARG ;;
t)
    tools=$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_f="-interlace 0"
    iflag_m=NOT_INTERLACED ;;
1)
    iflag_f="-interlace 1 -ildct -ilme -top 1"
    iflag_m=INTERLACED_TOP_FIRST ;;
3)
    iflag_f="-deinterlace"
    iflag_m=NOT_INTERLACED ;;
*)
    iflag_f="-interlace 1 -ildct -ilme -top 0"
    iflag_m=INTERLACED_BOTTOM_FIRST ;;
esac

case $ratio in
2)
    aflag_f="-aspect 16:9"
    aflag_m="-a3" ;;
*)
    aflag_f="-aspect 4:3"
    aflag_m="-a2"  ;;
esac


echo "Encoding yuv4mpeg on /dev/stdin to $base.mpg"
sleep 5
#	yuvdenoise -g 0,0,0 -t 8,12,12 -M 0,0,0 |
case $tools in
1)
	yuvcorrect -T $iflag_m 2>/dev/null |
    yuvdeinterlace -d |
    yuvcorrect -T PROGRESSIVE |
    y4mscaler -O size=1280x720 |
    yuvfps -s 60000:1001 -r 60000:1001 |
	ffmpeg -f yuv4mpegpipe -i /dev/stdin -i $base.wav \
		$iflag_f -acodec ac3 -vcodec mpeg2video \
		-target dvd -muxrate 23000000 -bufsize 3997696
		-maxrate 20000000 $aflag_f -s 1280x720 \
		-qmin 2 -b 18000000 -ab 224000 \
		-f dvd -y $base.mpg ;;

*)
	yuvcorrect -T $iflag_m 2>/dev/null |
    yuvdeinterlace -d |
    yuvcorrect -T PROGRESSIVE |
    y4mscaler -O size=1280x720 |
    yuvfps -s 60000:1001 -r 60000:1001 |
	mpeg2enc --no-constraints -f3 -nn $aflag_m -Ktmpgenc -lh \
		-b18000 -V488 -r32 -G18 -q3 -s -o $base.m2v
	mp2enc -r48000 -b224 < $base.wav -o $base.m2a
	mplex -f8 -b488 -r23000 $base.m2v $base.m2a -o $base.mpg ;;

esac
