#!/bin/bash
#
# mpgprobe - check MPEG-Stream for Video and Audio Characteristics
#
# Version   0.01a written by Wolfgang Wershofen (mailto: itconsult at wershofen.de)
#
# needs the following tools to run:
# - transcode >= 0.6.11
#
# Anpassung 29.10.04/Stefan Becker: pcm und dts Audiotracks erkennen, 
#
usage()
{
 cat <<EOF
Usage: `basename $0` mpeg-file

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

#
# If something goes wrong....
#
error_out()
{
 faultRC=$?
 cat << EOF
Hey, something went wrong in this script! Check for error messages
The last command returned a Non-Zero Return-Code ($faultRC)
So I guess it's better to stop here and let you analyze the situation
Hope you'll find the error. ;-)
EOF
exit $faultRC
}

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

#
# Call tcprobe and write stdout to workfile
#
workFile="mpgprobe.tmp"
tcprobe -i "$@" 1>"$workFile" 2>/dev/null || error_out

#
# Extract Video attributes
#
fsize=$(grep "frame size:" $workFile | awk -F"-g " '{print $2}' | cut -d' ' -f 1)
aratio=$(grep "aspect ratio:" $workFile | awk -F": " '{print $2}' | cut -d' ' -f 1)
frate=$(grep "frame rate:" $workFile | awk -F"-f " '{print $2}' | cut -d' ' -f 1)
vstring="$fsize $aratio $frate"
echo "Video:$vstring"

#
# Extract Audio Attributes
#
astring=""
for i in $(grep "audio track:" $workFile | awk -F"-n " '{print $2}' | cut -d' ' -f1); do
	case "$i" in
   	"0x50")
      	astring="$astring mp2"
       ;;
    	"0x2000")
      	astring="$astring ac3"
       ;;
       	"0x1000f")
      	astring="$astring dts"
       ;;
    	"0x10001")
      	astring="$astring pcm"
       ;;
     	*)
      	astring="$astring ??"
       ;;
 	esac
done
echo "Audio:${astring:1}"

#
# Remove the work file
#
rm $workFile

exit 0
