#!/bin/bash

. mp4tools

[ "$#" -lt 1 ] && exec echo "usage: $0 <file> [outfile] [bitrate]"

X264OPTS='bframes=3:b-pyramid:merange=32:ref=3:qcomp=0.8:partitions=all:direct=auto:weightb:me=umh:subme=7:b-rdo:mixed-refs:bime:8x8dct:trellis=2'
VB=${3:-300}
OUTFILE="${1%.*}.mp4"
[ "$#" -gt 1 ] && OUTFILE="$2"

trap clean_tmp SIGINT
trap clean_tmp SIGQUIT
trap clean_tmp SIGKILL

analyse "$1"

if [ $HAS_AUDIO ]
then
	audiorip "$1" /tmp/audio.$$.wav lavcresample=44100 || clean_tmp

	normalize /tmp/audio.$$.wav || clean_tmp

	if [ -z $HAS_VIDEO ]
	then
		AQ='0.2'
		green "Audio only file, increasing quality a bit"
	fi
	aacplusencode /tmp/audio.$$.wav /tmp/audio.$$.aac $AQ || clean_tmp
	rm -f /tmp/audio.$$.wav
fi

if [ $HAS_VIDEO ]
then
	h264enc "$1" /tmp/video.$$.264 $X264OPTS $VB || clean_tmp
fi

avmux "$OUTFILE" || clean_tmp

clean_tmp 0
