#!/bin/sh

#
# Copyright (c) 2011 Alexander Leidinger <Alexander@Leidinger.net>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#

calc_bitrate() {
	local width="$1" height="$2" fps="${3:-25}" time="$4" motion="$5"
	local fps_text="${3:-25 guessed}"

	bps=$(echo "${width} * ${height} * ${fps:-25} * ${motion} * 0.07" | bc)
	kbps=$(echo "${bps} / 1024" | bc)
	bits=$(echo "${time} * ${bps}" | bc)
	bytes_cbr=$(echo "${bits} / 8" | bc)
	bytes_vbr=$(echo "${bytes_cbr} * 3 / 4" | bc)	# *0.75 gives a float
	kbytes_cbr=$(echo "${bytes_cbr} / 1024" | bc)
	kbytes_vbr=$(echo "${bytes_vbr} / 1024" | bc)
	mbytes_cbr=$(echo "${kbytes_cbr} / 1024" | bc)
	mbytes_vbr=$(echo "${kbytes_vbr} / 1024" | bc)

	echo Width: ${width}, Height: ${height}, FPS: ${fps_text}, Time: ${time}, Motion: ${motion}
	echo "   Per second: ${bps} bps / ${kbps} Kibps"
	echo "   Total CBR: ${bytes_cbr} bytes / ${kbytes_cbr} KiB / ${mbytes_cbr} MiB"
	echo "   Total VBR: ${bytes_vbr} bytes / ${kbytes_vbr} KiB / ${mbytes_vbr} MiB"

}

for file in "$@"; do
	[ $# -gt 1 ] && echo "${file}:"
	time=$(grep Duration "${file}" | head -1 | cut -d : -f 2 | sed -E 's:([0-9]+)h:\(\1 * 60*60\): ; s:([0-9]+)mn:\(\1 * 60\): ; s:([0-9]+)s:\(\1\): ; s:([0-9]+)ms:\(1\): ; s:\) \(:\) + \(:g' | bc)
	width=$(grep Width "${file}" | cut -d : -f 2 | sed -E 's: ::g ; s:pixels::')
	height=$(grep Height "${file}" | cut -d : -f 2 | sed -E 's: ::g ; s:pixels::')
	fps=$(grep 'Frame rate  ' "${file}" | cut -d : -f 2 | sed -E 's: ::g ; s:[A-Za-z:]*([0-9.]+).*:\1:')

	calc_bitrate "${width}" "${height}" "${fps}" "${time}" 2
	calc_bitrate "${width}" "${height}" "${fps}" "${time}" 3
	calc_bitrate "${width}" "${height}" "${fps}" "${time}" 4

	[ $# -gt 1 ] && echo 
done

