#!/bin/sh

# A script to convert any readable file for the Blackberry Storm
if [ $# -lt 2 ]; then
  echo "Converts any (supported) media file in H.264/AAC for use on the BlackBerry Storm"
  echo "Usage: $0 infile outfile"
  exit 1
fi

PWD=`pwd`
STATSFILE=`mktemp --tmpdir=$PWD`
QTMUXFILE=`mktemp --tmpdir=$PWD`

cleanup()
{
  # x264enc seems to append .temp to the filename we give it. Go figure
  rm -f $STATSFILE.temp $STATSFILE $QTMUXFILE > /dev/null
}

trap cleanup EXIT

VENC="x264enc bitrate=512 bframes=0 cabac=false threads=0 stats-file=$STATSFILE"
# pass 1
echo "1st pass encode"
gst-launch-0.10 filesrc location="$1" ! decodebin2 name=decode \
decode. ! video/x-raw-rgb\;video/x-raw-yuv ! videorate ! queue max-size-buffers=1 ! \
videoscale ! video/x-raw-yuv,width=480,height=360 ! ffmpegcolorspace ! \
$VENC pass=pass1 ! progressreport ! fakesink | grep "progressreport"

if [ "$?" -ne 0 ];  then
  echo "First pass failed. Exiting"
  exit 1
fi

# pass 2
echo "2nd pass encode"
gst-launch-0.10 filesrc location="$1" ! decodebin2 name=decode \
decode. ! video/x-raw-rgb\;video/x-raw-yuv ! videorate ! queue max-size-buffers=1 ! \
videoscale ! video/x-raw-yuv,width=480,height=360 ! ffmpegcolorspace ! \
$VENC pass=pass2 ! progressreport ! mux. \
\
decode. ! audio/x-raw-int\;audio/x-raw-float ! \
audioconvert ! audioresample ! audio/x-raw-int,rate=44100,channels=2 ! faac profile=2 bitrate=96000 ! \
mux. \
\
mp4mux name=mux movie-timescale=1000 faststart=true faststart-file="$QTMUXFILE" ! filesink location="$2" | grep "progressreport"
