#!/bin/sh
# ipodconv: convert avi's to mp4's for iPod Touch playback
######################################################################

# we use cut, grep, mplayer & ffmpeg (linked w/ libfaac & libx264)
PATH=/usr/bin:/usr/local/bin

# Audio magic, use AAC compression, 2 channels, 44.1KHz and 128Kbit
AUDIO="-acodec libfaac -ac 2 -ar 44100 -ab 128k"

# Video magic, this is the real voodoo, LGTM, YMMV, RTFM, STFU
VIDEO="-vcodec libx264 -b 300k -flags +loop -cmp +chroma "
VIDEO=${VIDEO}"-partitions +parti4x4+partp8x8+partb8x8 -me umh "
VIDEO=${VIDEO}"-subq 5 -trellis 1 -refs 1 -coder 0 -me_range 16 "
VIDEO=${VIDEO}"-g 300 -keyint_min 25 -sc_threshold 40 "
VIDEO=${VIDEO}"-i_qfactor 0.71 -bt 300k -maxrate 300k -bufsize 300k "
VIDEO=${VIDEO}"-rc_eq blurCplx^(1-qComp) -qcomp 0.6 -qmin 15 "
VIDEO=${VIDEO}"-qmax 51 -qdiff 4 -level 30"

# Filenames should not have spaces.
for FILE in *.avi
do
	# use mplayer to determine the width (in pixels) of the video
	IDCMD="mplayer -vo null -nosound -frames 0 -identify ${FILE}"
	eval `${IDCMD} | grep '^ID_VIDEO_WIDTH=' | cut -f3 -d'_'`

	# Calculate the new height, based on the width of the original 
	# video. We scale orignal width to 480 and want the height to
	# be scaled appropriately but have it be a multiple of 16 (for
	# better performance of H.264).
	HEIGHT=$((16 * ((((480 * 320) / ${WIDTH}) + 15) / 16)))
	VIDOPTS="-s 480x${HEIGHT} ${VIDEO} -aspect 480:${HEIGHT}"

	# Now actually recode the file (takes a long time)
	ffmpeg -i ${FILE} ${AUDIO} ${VIDOPTS} ${FILE%avi}mp4
done
