#!/bin/sh

usage()
{
	# Title
	echo "Title: H.264 MP4 Dual Pass (FFMPEG)"

	# Usable?
	aac=`ffmpeg -formats 2> /dev/null | egrep "(Encoders:)|(.*E.*h264)" | grep h264 | wc -l`
	[ "$aac" -gt 0 ] && echo Status: Active || echo Status: Inactive

	# Type
	echo Flags: double-pass file-producer

	# Profiles
	echo "Profile: High Quality (640x480, 2168 kb/s)"
	echo "Profile: Medium Quality (320x240, 1088 kb/s)"
	echo "Profile: Broadband Quality (320x240, 364 kb/s)"
	echo "Profile: 3G Mobile Quality (176x144, 12fps, 128 kb/s)"
}

execute()
{
	# Arguments
	normalisation="$1"
	length="$2"
	profile="$3"
	file="$4"
	project="$5"
	pass="$6"

	source "`dirname $0`/ffmpeg_utils.sh"

	# generate filename if missing
	[ "x$file" = "x" ] && file="kino_export_"`date +%Y-%m-%d_%H.%M.%S`
	
	# Variable parameters
	hq=""
	[ $pass -eq "2" ] && ffmpeg_generate_hq

	# Create metadata options
	title=`awk '/title="/ {split($0, x, "\""); z = 0; for (y in x) if (x[y] ~ /title=/) z = y + 1; print x[z]; exit}' "$project"`
	author=`awk '/author="/ {split($0, x, "\""); z = 0; for (y in x) if (x[y] ~ /author=/) z = y + 1; print x[z]; exit}' "$project"`
	comment=`awk '/abstract="/ {split($0, x, "\""); z = 0; for (y in x) if (x[y] ~ /abstract=/) z = y + 1; print x[z]; exit}' "$project"`
	copyright=`awk '/copyright="/ {split($0, x, "\""); z = 0; for (y in x) if (x[y] ~ /copyright=/) z = y + 1; print x[z]; exit}' "$project"`
	
	# Run the command
	case "$profile" in 
		"0" ) ffmpeg -f dv -i pipe: -pass $pass -passlogfile "$file" \
			-vcodec h264 $hq -s 640x480 -aspect 4:3 -b 2048 -ab 120 \
			-title "$title" -author "$author" -comment "$comment" -copyright "$copyright" \
			-y "$file".mp4 ;;
		"1" ) ffmpeg -f dv -i pipe: -pass $pass -passlogfile "$file" \
			-vcodec h264 $hq -s 320x240 -aspect 4:3 -b 1024 -ab 64 -ar 44100 \
			-title "$title" -author "$author" -comment "$comment" -copyright "$copyright" \
			-y "$file".mp4 ;;
		"2" ) ffmpeg -f dv -i pipe: -pass $pass -passlogfile "$file" \
			-vcodec h264 $hq -s 320x240 -aspect 4:3 -b 300 -g 60 -ab 32 -ar 22050 \
			-title "$title" -author "$author" -comment "$comment" -copyright "$copyright" \
			-y "$file".mp4 ;;
		"3" ) ffmpeg -f dv -i pipe: -pass $pass -passlogfile "$file" \
			-vcodec h264 $hq -r 12 -g 36 -s qcif -aspect 4:3 -b 100 -ac 1 -ab 28 -ar 16000 \
			-title "$title" -author "$author" -comment "$comment" -copyright "$copyright" \
			-y "$file".mp4 ;;
	esac
	[ $pass -eq "2" ] && rm -f "$file-0.log"
}

[ "$1" = "--usage" ] || [ -z "$1" ] && usage "$@" || execute "$@"
