#!/bin/sh
# A Kino export script that outputs PlayStation 3 compatible
# Best Quality H.264 MP4 using ffmpeg with x264

usage()
{
	# Title
	echo "Title: H.264 MP4 for PLAYSTATION 3 (FFMPEG)"

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

	# Type
	echo Flags: double-pass file-producer

	# Profile - only Best Quality
	echo "Profile: Best Quality (native size, interlace, 2240 kb/s)"
}

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

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

	# generate filename if missing
	[ "x$file" = "x" ] && file="kino_export_"`date +%Y-%m-%d_%H.%M.%S`
	
	# 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 "$pass" in
		"1" ) ffmpeg -threads $threads -f dv -i pipe: -pass 1 -passlogfile "$file" \
			-vcodec $x264 -vpre fastfirstpass -level 41 -g 300 $interlace -aspect $aspect -b 2048$kilo -bt 4096$kilo \
			-an -f rawvideo -y /dev/null
			;;
		"2" ) ffmpeg -threads $threads -f dv -i pipe: -pass 2 -passlogfile "$file" \
			-vcodec $x264 -vpre hq -level 41 -g 300  -flags +ildct+ilme -aspect $aspect -b 2048$kilo -bt 4096$kilo \
			-ab 448$audio_kilo -ar 48000 \
			${opt_title}"${title}" ${opt_author}"${author}" ${opt_comment}"${comment}" ${opt_copyright}"${copyright}" \
			-y "$file".mp4
			rm -f "$file-0.log"
			;;
	esac
}

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