#! /bin/sh
#

USAGE="`basename $0` [-h] -f fps -b bitrate file.ts..."

abort () {
  echo $1 >&2
  exit ${2-1}
}

trap "rm -f video.h264 audio.aac" 0 1 2 3 15

fps=
bt=

# parse command line
set -- `getopt b:f:h $*`

if [ $? != 0 ]
then
  abort "$USAGE" 1
fi

while [ $1 != -- ]
do
  case $1 in
    -h)
	abort "$USAGE" 0
	;;
    -f)
	fps="$2"
	shift
	;;
    -b)
	bt="$2"
	shift
	;;
  esac
  shift	# next flag
done

if [ -z "$fps" -o -z "$bt" ]
then
  abort "$USAGE" 1
fi

shift	# skip --

if [ $# = 0 ]
then
  abort "$USAGE" 1
fi

for f in $*
do
	ext=`echo -n $f | sed 's/.*\.//'`
	if [ ! -f $f -o "$ext" != "ts" ]
	then
  		abort "$f?"
	fi
	
	file=`basename $f .ts`

	ffmpeg -i $f -an -vcodec copy -bt $bt video.h264
	ffmpeg -i $f -acodec copy -vn audio.aac

	MP4Box -add video.h264 -add audio.aac $file.mp4

	if [ $? -ne 0 ]
	then
  		abort "$f?"
	fi
done

