#!/bin/bash
#
# mk_vtsm_audio - Create audio selection menu (titleset)
#           for authoring a DVD with dvdauthor >= 0.6
#
# Version   0.1 written by Wolfgang Wershofen (mailto: itconsult at wershofen.de)
#           0.4.3: Menu multilingual (Stefan Becker)
#
# needs the following tools to run:
# - ImageMagick >= 5.5.4
# - toolame >= 0.2l
# - ppmtoy4m and mplex from mjpegtools >= 1.6.1
# - mpeg2enc from libmpeg2
# - spumux from dvdauthor >= 0.6.0
#
usage()
{
 cat <<EOF
Usage: `basename $0` [options]

currently supported options:
----------------------------
-C | --config-file	filename of dvdwizard-configuration file
			[~/.dvdwizard/dvdwizard.conf]
-o | --output-dir	Define Output-Directory where ready-made menu-mpegs should
			be written to [.]
-x | --xml-file		Define filename for xml-definition
			[<output-dir>/dvdauthor.menu.xml]
-b | --vtsmbg		Image to use as background for chapter thumbnails.
			If not specified, mk_vtsm will create one from scratch
-N | --tvnorm		TV-Norm to use <PAL|NTSC> [PAL]
-V | --tvsize		Visible area of frame on TV set. At least my tv does not
			show full "$normSize", but maybe yours can. [635x535]
-t | --vts		Titleset on the DVD where the menus should belong to [1]
--hasinfo		Title has EPG-Informations available. A button to jump to the
			info panel will be created (not yet implemented)
-a | --audio		available audio-tracks as comma-separated list of
			format+language eg. mp2+de,ac3+en [mp2+de]
-h | --help		print this lot out

EOF

exit 1
}

# ------------------------------
# Main Processing
#
# 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

#
# Ok, first define some default values
#
set_defaults "$@"
VTSMDIR="."
vts=1
VTSMBG=""
atracks=1
atrackdef=""
info=0
color=( white red yellow )
scolor=black
tcolor='rgb(128,128,196)'

#
# Now deal with command line arguments
#
while [ "$*" != "" ]; do
    case "$1" in
  	-h|--help)
   	    usage
  	;;
  	-C|--config-file)
    	shift
# -C and it's following parm already processed in set_defaults()
        shift
  	;;
	-o|--output)
 		shift
		VTSMDIR="$1"
	    shift
  	;;
  	-x|--xml)
	    shift
   	    XMLFILE="$1"
   	    shift
  	;;
  	-t|--vts)
	    shift
   	    vts="$1"
   	    shift
	;;
  	-b|--vtsmbg)
	    shift
   	    VTSMBG="$1"
   	    shift
  	;;
  	-N|--tvnorm)
	    shift
   	    TVNORM="$1"
            if [ "$TVNORM" == "PAL" -o "$TVNORM" == "NTSC" ]; then
        	:
            else
        	echo "Incorrect TV-Norm $TVNORM specified, only PAL and NTSC are supported. Aborting" >&2
            	usage
            fi
   	    shift
  	;;
  	-V|--tvsize)
	    shift
   	    TVSIZE="$1"
   	    shift
  	;;
  	--hasinfo)
  	    info="1"
   	    shift
  	;;
  	-a|--audio)
   		shift
        atrackdef="$1"
   		atracks=$(echo "$atrackdef" | tr ',' ' ' | wc -w)
		if [ $atracks -gt 8 ]; then
    		echo "Only up to 8 audiotracks are supported. Sorry" >2
        	error_out
 		fi
   		shift
  	;;
  	*)
   	    echo "Unrecognized command line parameter $1. Aborting" >&2
        usage
  	;;
    esac
done

#
# Let's see, if all options are correct
# Check output-directories and files
#
mk_check_dir "$VTSMDIR" "NEW"
mk_check_dir "$TMPDIR" "NEW"
mk_check_file "$XMLFILE" "NEW"
[ ! -z "$VTSMBG" ] && mk_check_file "$VTSMBG" "OLD"

#
# Audio Tracks specified?
#
if [ -z "$atrackdef" ]; then
 	echo "no audio track definition specified" >&2
 	usage
fi

#
# Do some file and directory preparation
#
ls -d "$TMPDIR"/tmp_mk_vtsm* > /dev/null 2>&1 && rm -R "$TMPDIR"/tmp_mk_vtsm*
workDir=`mktemp -d "$TMPDIR"/tmp_mk_vtsm_XXXXXX`
spuxml="$workDir"/tmp_spumux.xml
menumpeg="$VTSMDIR"/vtsm"$vts"_audio.mpg

#
# Create an empty audio track for the menu mpeg
#
create_silence

#
# Prepare the background picture
# ($VTSMBG will be converted to $workbg)
#
prepare_bg "$VTSMBG"
let panelX=150+$offsetX
let panelY=$tvY+$offsetY
menupanel="$workDir"/tmp_panel.png
audiopanel="$workDir"/tmp_audio_panel.png
menuBG="$workDir"/tmp_menu_bg.png
let rectY="($MFONTSIZE+10)*$atracks+($HFONTSIZE*4)"
convert -size "$panelsize"x"$tvY" xc:'rgba(255,255,255,96)' "$menupanel"  || error_out
convert -size "250x300" xc:none -fill 'rgba(128,192,255,128)' \
		-draw 'roundrectangle 5,5 245,295 10,10' "$audiopanel"  || error_out
convert -scale "$normSize"! -density "$normDensity" -units PixelsPerInch \
		-fill 'rgba(255,255,255,96)' -draw 'rectangle '"$offsetX,$offsetY $panelX,$panelY" \
        -fill 'rgba(128,192,255,128)' -draw 'roundrectangle '"$(( $offsetX+25 )),$(( $offsetY+25 ))"' 300,'$rectY' 10,10' \
        "$workbg" "$menuBG" || error_out

#
# Output the xml-commands for dvdauthor
#
echo "Creating Audio-Selection-Menu"
entry="entry=\"audio\""

#
# Ok, define the pgc for the menu and define the intra-menu-navigation buttons
# We need a PRE-command to set the highlighted button to the currently selected audio track
#
echo -e "\t\t\t<pgc $entry pause=\"0\">" >> "$XMLFILE"
echo -e "\t\t\t\t<pre> button=(audio+1)*1024; </pre>" >> "$XMLFILE"
echo -e "\t\t\t\t<vob file=\"$menumpeg\" pause=\"inf\"/>" >> "$XMLFILE"

#
# Audio Selection Button Definitions
# On Click, change audio track and resume to where we came from
#
bnum=1
for ((m=0; m < atracks; m++)); do
	echo -e "\t\t\t\t<button name=\"$bnum\">" >> "$XMLFILE"
	echo -e "\t\t\t\t\t{ audio=${m};" >> "$XMLFILE"
	echo -e "\t\t\t\t\t  if (g1 eq 0) jump vmgm menu entry title;" >> "$XMLFILE"
	echo -e "\t\t\t\t\t  if (g1 eq 1) jump menu entry ptt;" >> "$XMLFILE"
	echo -e "\t\t\t\t\t  if (g1 eq 9) resume; }" >> "$XMLFILE"
	echo -e "\t\t\t\t</button>" >> "$XMLFILE"
    let bnum+=1
done

#
# This is for intra menu navigation
# One button to jump to the Chapter Selection Menu
#
echo -e "\t\t\t\t<button name=\"$bnum\"> jump menu entry ptt; </button>" >> "$XMLFILE"
let bnum+=1

#
# If available, one button to jump to the info panel
#
if [ $info -eq 1 ]; then
	echo -e "\t\t\t\t<button name=\"$bnum\"> jump menu entry angle; </button>" >> "$XMLFILE"
    let bnum+=1
fi

#
# One Button to Return to the Title-Menu of the DVD
#
echo -e "\t\t\t\t<button name=\"$bnum\"> jump vmgm menu entry title; </button>" >> "$XMLFILE"
let bnum+=1

#
# And last not least, the Resume Button
#
echo -e "\t\t\t\t<button name=\"$bnum\">" >> "$XMLFILE"
echo -e "\t\t\t\t\t{ if (g1 eq 0) jump vmgm menu entry title;" >> "$XMLFILE"
echo -e "\t\t\t\t\t  if (g1 eq 1) jump menu entry ptt;" >> "$XMLFILE"
echo -e "\t\t\t\t\t  if (g1 eq 9) resume; }" >> "$XMLFILE"
echo -e "\t\t\t\t</button>" >> "$XMLFILE"

#
# This is for Intra-Menu-Navigation
# Button-Text is printed on the background-image, because the small font flickers on tv when
# specified in the mask-images
#
if [ $info -eq 1 ]; then
	btexte="$TEXT_RETURN DVD-$TEXT_MENU Info-Panel $TEXT_AUDIO_MENU_CHAPTERS"
else
	btexte="$TEXT_RETURN DVD-$TEXT_MENU $TEXT_AUDIO_MENU_CHAPTERS"
fi

#
# Montage the menu background with the thumbnails and create the button-masks
#
for i in 0 1 2; do
	maskPic[i]="$workDir"/tmp_audio_mask_$i.png
	convert -size $TVSIZE xc:none "${maskPic[i]}" || error_out

# Print Menu Header
    if [ $i -eq 0 ]; then
    	mogrify -pointsize $HFONTSIZE \
     		-fill $scolor -draw "$TEXT_SELECT_AUDIO_TRACK1" \
       		-fill $tcolor -draw "$TEXT_SELECT_AUDIO_TRACK2" \
	        "${maskPic[i]}" || error_out
    fi

# Audio-Track Selection Buttons
	polyX1=35
	let polyX2=polyX1+15
	let polyX3=polyX1
	let textX=polyX1+20
	let shadowX=textX+1
	let lineX1=polyX1
	let lineX2=lineX1+200
	let navy=35+$HFONTSIZE
	for ((m=1; m <= atracks; m++)); do
		let textY=$navy+$MFONTSIZE+5
 		let shadowY=$textY+1
  		let polyY1=$textY-$MFONTSIZE+3
   		let polyY3=$textY-3
    	let polyY2=$textY-$MFONTSIZE/2
    	let lineY=$polyY3+6
     	audiodef=$(echo "$atrackdef" | cut -d',' -f $m)
      	aformat=$(echo $audiodef | cut -d'+' -f 1)
       	alang=$(echo $audiodef | cut -d'+' -f 2 | tr [a-z] [A-Z])
        eval "language=\$"$alang
        [ -z "$language" ] && language="unknown"
        [ "$aformat" == "mp2" ] && atext="$language" || atext="$language ($aformat)"
    	if [ $i -eq 0 ]; then
    		mogrify -pointsize $MFONTSIZE \
     				-fill $scolor -draw 'text '$shadowX','$shadowY' "'"$atext"'"' \
        			-fill $tcolor -draw 'text '$textX','$textY' "'"$atext"'"' \
	         		"${maskPic[i]}" || error_out
		else
 			mogrify +antialias -pointsize $MFONTSIZE -fill ${color[i]} \
	    	  		-draw 'polygon '"$polyX1,$polyY1 $polyX2,$polyY2 $polyX3,$polyY3" \
  			  		-draw 'line '"$lineX1,$lineY $lineX2,$lineY" \
	       			"${maskPic[i]}" || error_out
   		fi
    	let navy+=$MFONTSIZE+10
	done

# Intra-Menu-Navigation Buttons
	polyX1=5
	let polyX2=polyX1+15
	let polyX3=polyX1
	let textX=polyX1+20
	let shadowX=textX+1
	let lineX1=polyX1
	let lineX2=lineX1+120
	navy=tvY-50
	for text in $btexte; do
		let textY=$navy+$MFONTSIZE+5
 		let shadowY=$textY+1
  		let polyY1=$textY-$MFONTSIZE+3
   		let polyY3=$textY-3
    	let polyY2=$textY-$MFONTSIZE/2
    	let lineY=$polyY3+6
    	if [ $i -eq 0 ]; then
    		mogrify -pointsize $MFONTSIZE \
     				-fill $scolor -draw 'text '$shadowX','$shadowY' "'"$text"'"' \
        			-fill $tcolor -draw 'text '$textX','$textY' "'"$text"'"' \
	         		"${maskPic[i]}" || error_out
		else
 			mogrify +antialias -pointsize $MFONTSIZE -fill ${color[i]} \
	    	  		-draw 'polygon '"$polyX1,$polyY1 $polyX2,$polyY2 $polyX3,$polyY3" \
  			  		-draw 'line '"$lineX1,$lineY $lineX2,$lineY" \
	       			"${maskPic[i]}" || error_out
   		fi
    	let navy-=$MFONTSIZE+10
	done
done

#
# Combine the results into one Picture
#
for i in 1 2; do
	menumask[i]="$workDir"/vtsm_audio_mask_"$i".png
	convert -size "$normSize" xc:transparent -density "$normDensity" -units PixelsPerInch png:- | \
		composite -compose Over -gravity Center "${maskPic[i]}" - "${menumask[i]}" || error_out
	mogrify -colors 3 "${menumask[i]}" || error_out
done
vtsmBG="$workDir"/tmp_vtsm__audio_bg.ppm
composite -compose Over -gravity Center "${maskPic[0]}" "$menuBG" "$vtsmBG" || error_out
mogrify -depth 8 "$vtsmBG" || error_out

#
# This is the xml to tell spumux what to do
#
cat <<EOF > "$spuxml"
<subpictures>
   <stream>
      <spu start="0"
           highlight="${menumask[1]}"
           select="${menumask[2]}"
           autoorder="columns" force="yes"
           autooutline="infer" outlinewidth="7" />
   </stream>
</subpictures>
EOF

#
# Create MPEG-Stream from Background-Picture and mux with buttonmasks
#
videotrack="$workDir"/tmp_vtsm_audio.m2v
if [ "$TVNORM" == "NTSC" ]; then
	encFrameRate="30000:1001"
	encNorm="n"
else
	encFrameRate="25:1"
	encNorm="p"
fi
ppmtoy4m -n 10 -F "$encFrameRate" -r "$vtsmBG" | \
	mpeg2enc -a 2 -n "$encNorm" -f 8 -o "$videotrack" || error_out
mplex -f 8 -o /dev/stdout "$videotrack" "$audiotrack" | \
	spumux -v4 "$spuxml" > "$menumpeg" || error_out

# Close XML-Definition
echo -e "\t\t\t</pgc>" >> "$XMLFILE"
echo "Audio Menu created"

#
# Ok, work finished. Hope everything is ok. Remove the working directory
#
rm -R "$workDir"

exit 0
