#!/bin/sh
#
#  bitrate is 2500 by default for SVCD      (lower is worse)
#  quality factor is 8 by default for SVCD  (higher is worse)
#  The peak bit-rate and average bit-rate should differ by 20-25%
#  Suggested -b2300 -q10 / -b2400 -q9 / -b2500 -q8
#
#  .mov files from mobo are top interlaced first
#  .dv files are bottom interlaced first
#
def_interlace=0
def_ratio=1
def_signal=1
def_quality=2

help(){
    cat <<END
Usage: $0 [options] <filename.[flv]>
Options:
    -i n      n=0 progressive, n=1 top, n=2 bottom  ($def_interlace)
    -q n      quality, n=1 highest ... n=4 lowest   ($def_quality)
    -r n      aspect ratio, n=1 4:3, n=2 letterbox  ($def_ratio)
    -v n      norm, n=1 ntsc n=2 pal                ($def_signal)
    -h        Print this help message
END
    exit 0
}

interlace=$def_interlace
ratio=$def_ratio
signal=$def_signal
quality=$def_quality

while getopts i:q:r:v:h name "$@"
do
    case $name in
i)
    interlace=$OPTARG ;;
q)
    quality=$OPTARG ;;
r)
    ratio=$OPTARG ;;
v)
    signal=$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$//"` ;;
*)
    help ;;
esac

case $quality in
1)
    abitrate=224
    bitrate=2500
    quant_f=4 ;;
3)
    abitrate=192
    bitrate=2200
    quant_f=5 ;;
4)
    abitrate=96
    bitrate=2000
    quant_f=6 ;;
*)
    abitrate=192
    bitrate=2400
    quant_f=4 ;;
esac
case $signal in
2)
    nflag_f="-r pal" ;;
*)
    nflag_f="-r ntsc" ;;
esac
case $interlace in
0)
    iflag_f="-interlace 0" ;;
1)
    iflag_f="-interlace 1 -ildct -ilme -top 1" ;;
*)
    iflag_f="-interlace 1 -ildct -ilme -top 0" ;;
esac
case $ratio in
2)
    case $interlace in
0)
        iflag_f="-interlace 0" ;;
*)
        iflag_f="-deinterlace" ;;
esac
    aflag_f="-s480x360 -padtop 60 -padbottom 60 -aspect 4:3" ;;
*)
    aflag_f="-aspect 4:3" ;;
esac

echo "Encoding $input to $base.mpg..."
echo "    video bitrate $bitrate"
echo "    audio bitrate $abitrate"
sleep 5

#ffmpeg -i $input -acodec copy -vn -y $base-audio.flv
#ffmpeg -i $input -vcodec copy -an -y $base-video.flv
#nellynomore -l /usr/lib/mozilla/plugins/libflashplayer.so \
#	-i $base-audio.flv -o $base-audio.wav
#ffmpeg -i $base-audio.wav -y $base.wav

echo ffmpeg -i $input $nflag_f \
	-target svcd -s 480x480 $aflag_f $iflag_f \
    -flags scan_offset \
    -qmin $quant_f -b $bitrate -ab $abitrate -y $base.mpg

ffmpeg -i $input $nflag_f \
	-target svcd -s 480x480 $aflag_f $iflag_f \
    -flags scan_offset \
    -qmin $quant_f -b $bitrate -ab $abitrate -y $base.mpg
