#!/bin/ksh

if [ -z "$1" ]
then
    echo "Usage: $0 video1 video2 video3 ..."
    exit 1
fi

function get_aspect {
( echo scale=4
  mplayer -quiet -vo null -ao null -frames 0 -identify "$1" 2>&1 | grep ^VIDEO: | awk '{print $3}' | sed 's/x/\//' ) | bc
}

#target=/home/inittab/public_html
target="/fs/files/backups/TiVo"
#target="/usr/local/media/video/pspmovies/MP_ROOT/100MNV01"
#target="/usr/local/media/video/pspmovies"
format=psp
#format=ps3
aspect=1.7
mkdir -p "$target"
for m in "$@"
do
    echo "-------------------"
    echo "Start converting $m"
    echo "-------------------"
    output="10001"
    while [ -f "$target/m4v${output}.mp4" ]
    do
        let "output += 1"
    done

    filename=$(basename "$m")
    #aspect=$(get_aspect "$m")
    case "$aspect" in
    1.2*|1.3*|1.4*|1.5*)
        ratio=4:3
        pspres=320x240
	ps3res=640x480
        ;;
    1.7*|1.8*)
        ratio=16:9
        pspres=368x208
	ps3res=1920x1080
        ;;
    *)
        ratio=4:3
        pspres=320x240
	ps3res=640x480
        ;;
    esac

    CMD="cat"
    echo "$m" | egrep -q -i '\.tivo$'
    if [ "$?" = "0" ]; then
        CMD="tivodecode -"
    fi
    
    #generate video
    #If "-r 29.97" does NOT work try "-r 14.985"
    case "$format" in
    psp)
        # Playstation Portable & Playstation 3
        $CMD < "$m" | ffmpeg -i - -f psp -r 29.97 -b 768k -ar 24000 -ab 64k -aspect "$ratio" -s "$pspres" -title "${filename}" "${target}/m4v${output}.mp4"
        ;;
    ps3)
        # Playstation 3 only
        $CMD < "$m" | ffmpeg -i - -f mp4 -r 29.97 -aspect "$ratio" -s "$ps3res" -title "${filename}" -y -vcodec h264 -acodec aac -mbd rd -flags 4mv+trell+aic+qprd+mv0 -flags2 dct8x8+skiprd -ab 128k -bf 3 -ac 2 -level 41 "${target}/m4v${output}.mp4"
        ;;
    esac

    #generate thumbnail
    ffmpeg -y -i "${target}/m4v${output}.mp4" -f image2 -ss 6 -vframes 1 -s 160x120 -an "${target}/m4v${output}.thm"

    #list the files that were just generated
    ls -l "${target}/m4v${output}.mp4" "${target}/m4v${output}.thm"
done

echo
echo "---------------------------------------------------------------------------"
echo "You will find any newly generated PSP/PS3 videos in:"
echo "     ${target}"
echo
echo "Please copy them to your PSP's 'MP_ROOT/100MNV01/' folder."
echo
echo "Note: if that folder doesn't already exist, just create the folders first."
echo "---------------------------------------------------------------------------"


