#!/bin/bash
#
# mpgprobe - check MPEG-Stream for Video and Audio Characteristics
#
# See TOOLS in the dvdwizard tarball for info about needed tools and programs
#
# Version   0.01a  written by Wolfgang Wershofen (mailto: itconsult at wershofen.de)
# Version   0.02   29.10.04/Stefan Becker: recognize pcm und dts audio tracks
# Version   0.03   12.12.08/Joo Martin: update for newer ffmpeg ('fps' goes to 'tb')
# Version   0.10   25.02.09/Joo Martin: update for newer ffmpeg (more tb variables)

usage()
{
 cat <<EOF
Usage:	`basename $0` mpeg-file
	`basename $0` -h|--help

specify the mpeg-file to be probed
EOF
exit 1
}

# ------------------------------
# Main Processing
#
#
# Is help wanted?
#
case "$1" in
  	-h|--help)
   	    usage
  	;;
esac

# We need some sub-routines from dvdwizardrc
# This file must reside in the same directory as the called script
# Should maybe go into a directory like /usr/local/share/dvdwizard
# but this would require an installation procedure - maybe in some
# later version.
#
rcfile="`dirname $0`/dvdwizardrc"
if [ -e "$rcfile" -a -r "$rcfile" ]; then
	. "$rcfile"
else
	echo "dvdwizardrc not found or is not readable. Aborting" >&2
    exit 1
fi

#
# Check for needed tools
#
check_tools

#
# Check if MPEG-File was specified and if, check if it is valid
#
if [ -z "$@" ]; then
 	echo "No input file specified. Aborting"
    echo "See $thisscript -h for more infos"
    exit 1
fi >&2
if [ ! -e "$@" ]; then
	echo "specified MPEG-file $@ not found. Aborting"
    echo "See $thisscript -h for more infos"
    exit 1
fi >&2

#
# Call ffmpeg on given mpeg file
#
# example of ffmpeg 2007 output:
#Stream #0.0[0x1e0]: Video: mpeg2video, yuv420p, 720x576 [PAR 16:15 DAR 4:3], 6400 kb/s, 25.00 fps(r)
# example of ffmpeg 2008 output:
#Stream #0.0[0x1e0]: Video: mpeg2video, yuv420p, 720x576 [PAR 16:15 DAR 4:3], 6400 kb/s, 25.00 tb(r)
# example of ffmpeg 2009 output:
#Stream #0.0[0x1e0]: Video: mpeg2video, yuv420p, 720x576 [PAR 16:15 DAR 4:3], 9500 kb/s, 25 tbr, 90k tbn, 25 tbc

vstrfull="$(LANG=C ffmpeg -i "$@" 2>&1 |\
	grep 'Stream #' | grep 'Video:' |\
	sed -e 's#\ fps#\ tb#' | sed -e 's#\ tb(r)# tbr#')"
vstring="$(echo "$vstrfull" | \
	sed -e 's#^.*\ \([0-9]\+x[0-9]\+\).*DAR\ \([0-9]\+:[0-9]\+\).*\ \([0-9]\+\.\?[0-9]\+\)\ tbr.*$#\1 \2 \3#g')"
echo "Video:${vstring}"

#
# Extract Audio Attributes
#
echo -n "Audio:"
for i in $(LANG=C ffmpeg -i "$@" 2>&1 | \
		grep 'Stream #' | grep 'Audio:' | \
		sed -e 's/liba52/ac3/g' -e 's/^.*Audio:\ \(.\{3\}\),\ .*$/\1/g'); do 
	echo -n "$i "
done 
echo ""

exit 0
