#!/bin/sh
# Re-encode existing media files, suitable for viewing on a N95 (or
#  similar S60 device)
# Uses ffmpeg to do the re-encoding to MP4, and mplayer to query the
#  resolution, so we can figure out how to scale it to 320x???
# Details on how the bitrates were selected can be found at
#  http://gagravarr.livejournal.com/129314.html
#
# v0.02 - 2007/08/21

RATE=350000
ARATE=96000

IN=$1
OUT=$2

if [[ "$OUT" == "" ]]; then
	echo "Use:"
	echo "  $0 <in> <out.mp4> [size] [framerate]"
	echo ""
	echo "Where the size should be something like 320x180"
	echo " (if not given, will scale to fit 320 pixels wide)"
	echo "And the framerate should be something like 23.98"
	echo " (if not given, ffmpeg will try to use the current one)"
	echo ""
	exit 1
fi

SIZE=$3
if [[ "$SIZE" == "" ]]; then	
	# Query it, via mplayer
	echo "Detecting the size of $IN..."
	RAWSIZE=`mplayer -ao none -vo none "$IN" 2>&1 | grep 'VIDEO' | awk '{print $3}'`
	echo "Detected a size of $RAWSIZE"

	# Scale to 320x???
	RAW_W=`echo $RAWSIZE | awk -F 'x' '{print $1}'`
	RAW_H=`echo $RAWSIZE | awk -F 'x' '{print $2}'`

	# Scale it to a multiple of 2, rounding up if needed
	SIZE_W=320
	SIZE_H=`perl -e "print int((${RAW_H} / ${RAW_W} * ${SIZE_W}) + 0.5)"`
	SIZE_H=`perl -e "print int( int(${SIZE_H}/2) * 2 )"`
	
	SIZE=${SIZE_W}x${SIZE_H}
	echo "Picked a scaled size of $SIZE"
else
	echo "Using specified size of $SIZE"
fi

FRATE=$4
if [[ "$FRATE" == "" ]]; then
	# Do nothing
	FOO=1
else
	FRATE="-r $FRATE"
	echo "Using specified framerate of $FRATE"
fi

echo "Video bitrate will be $RATE"
echo "Audio bitrate will be $ARATE"
echo ""
sleep 4

# Off we go!
ffmpeg -i "$IN" \
	-f mp4 -vcodec mpeg4 -b $RATE -s $SIZE \
	-acodec aac -ar 48000 -ab $ARATE -ac 2 \
	$FRATE   $OUT
