#!/bin/bash
#
# mk_vtsm_info - Display Information Panel(s)
#
# Version   0.1 written by Wolfgang Wershofen (mailto: itconsult at wershofen.de)
#
# See TOOLS in the dvdwizard tarball for info about needed tools and programs
#
usage()
{
 cat <<EOF
Usage:	`basename $0` [options] text-file
	`basename $0` -h|--help

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]
-M  | --menu		Language to use in menu items [en]
			Textelements are defined in config file
-ms | --vtsmsound	Soundfile to be used as background sound for the 
			menu. If empty, a silent audio track will be 
			produced. Can be any format, ffmpeg recognizes and 
			will be converted to ac3, if neccessary.
--hasaudio		Title has multiple audio tracks. A button to jump to
			the audio selection menu will be created
--hassubtitle		Title has at least one Subtitle-Stream which may
			be activated in a subsequent subtitle-menu
--hasinfo		Title has EPG-Informations available. A button to 
			jump to the info panel will be created
-h  | --help		print this lot out

EOF
exit 1
}

# ------------------------------------------
# Initialize constants troughout the whole script
#
init_proc()
{
	for i in DVD CHAPTER AUDIO SUBS INFO RETURN; do
		eval txt_$i=\"\$TXT_VTSM_${i}_$MENU\"
	done

	actMenu="$txt_INFO"	
 
	[ -e "$TMPDIR/common_objects/.menucount" ] \
		&& prevmenus=$(cat "$TMPDIR/common_objects/.menucount") \
		|| prevmenus=2
 
	return 0
}

# ------------------------------------------
# Create Navigation-Panel without Prev/next-Arrows
#
mk_nav_panel()
{
	echo -n "Creating navigation panel..."
	targets="$*"
	navBar=( "$(mktemp -t png.XXXXXXXXXX)"  "$(mktemp -t png.XXXXXXXXXX)" )
	for state in 0 1; do
		convert null: png:"${navBar[state]}"
		for tgt in $targets; do
			if [ "$tgt" == "$actMenu" ]; then
				[ $state -eq 0 ] && btnInd=2 || btnInd=3
			else
				btnInd=$state
			fi
			addbtn="$TMPDIR/common_objects/navbtn_${tgt}_$btnInd.png"
			convert "${navBar[state]}" "$addbtn" +append png:"${navBar[state]}" || error_out
		done
		convert "${navBar[state]}" -crop +2+0 png:"${navBar[state]}" || error_out
	done
	fpat="$TMPDIR/navPnl_%d.png"
	pnlDim=$( convert "${navBar[0]}" -border 10x40 png:- | identify -format %wx%h -)
	draw1='image Copy 0,30 0,0 "'"${navBar[1]}"'"'
	draw2='image Copy 0,20 0,0 "'"$TMPDIR/common_objects/navbtn_${txt_RETURN}_1.png"'"'
	convert -size $pnlDim xc:transparent \
		\( -clone 0 +antialias -bordercolor transparent -border 10 \
			-gravity south -draw "$draw1" \
			-gravity north -draw "$draw2" \) \
		\( -clone 0 -fill $TRANSLUCENT \
			-draw 'roundrectangle 0,0 '$(echo $pnlDim | tr 'x' ',')' 20,20' \
			-bordercolor transparent -border 10 \
			\( +clone -negate -blur 0x8 \) \
			+swap -gravity center -compose src-atop -composite \
			"${navBar[0]}" -gravity south -geometry +0+30 -compose over -composite \
			"$TMPDIR/common_objects/navbtn_${txt_RETURN}_0.png" -gravity north \
			-geometry +0+20 -composite \) \
		-swap 0,2 -delete 2 -crop +0-30 png:"$fpat" || error_out

	navpnlh=$(identify -format %h "$TMPDIR/navPnl_0.png")
	echo "done"
	return 0
}

# ------------------------------------------
# Create Info-Panels
#
mk_info_panel()
{
	echo -n "Creating Info Panels..."
	#
	# Transform text file into one or more fixed-width PNGs 
	#
	numPages=0
	let ipnlW="$TVWidth-100"
	let ipnlH="$TVHeight-$navpnlh-30"
	ipnlSize="$ipnlW"x"$ipnlH"
	pnlPNG="$TMPDIR/infopnl"
	txt2png -s $ipnlSize -o "$pnlPNG" -t "$MFONTTYPE" -f "$MFONTSIZE" -c $TEXTCOLOR $1
	#
	# Put the text on a nice translucent frame
	#
	for pnl in "$pnlPNG"[0-9][0-9].png; do
		convert "$pnl" \
			-bordercolor transparent -border 15 \
			-fill "$TRANSLUCENT" \
			-draw 'roundrectangle 0,0 '"$(( $ipnlW+15 )),$(( $ipnlH+15 ))"' 20,20' \
			-border 15 \( +clone -negate -blur 0x8 \) \
			+swap -gravity center -compose src-atop -composite \
			"$pnl" || error_out
		let "numPages+=1"
	done

	echo "done"
	echo "Will need $numPages info menu page(s)."
	return 0
}
# -------------------------------------------------------------
# Write xml-Definitions (dvdauthor and spumux)
#
write_xml()
{

#
# Start a new xml definition
#
xml_start()
{
let g6="100+$numPages"
cat << EOF >> "$XMLFILE"
			<pgc entry="ptt" pause="0">
				<pre> {
						g4=101; g6=$g6;
						if (g7 lt g4) g7=g4;
						if (g7 gt g6) g7=g6;
EOF

for i in $(seq 1 $numPages); do
let regi="$i+100"
let nexti="$i+1+$prevmenus"
cat << EOF >> "$XMLFILE"
						if (g7 eq $regi) jump menu $nexti;
EOF
done
cat << EOF >> "$XMLFILE"
					  }
				</pre>
				<vob file="$EMPTYMPG" />
			</pgc>
EOF

return 0
}

#
#	Begin new xml-Definition for a pgc
#
xml_begin_pgc()
{
cat << EOF > "$thisspuxml"
<subpictures>
	<stream>
		<spu start="0"
			 highlight="${thisMask[1]}"
			 select="${thisMask[2]}"
			 autoorder="rows" force="yes"
			 autooutline="infer" outlinewidth="2">
EOF

let button="$retbtn*1024"
cat << EOF >> "$XMLFILE"
			<pgc pause="0">
				<pre> { button=$button; } </pre>
				<vob file="$thismpg" pause="inf" />
EOF

return 0
}

#
#	Write the navigation buttons
#
xml_navi()
{
	if [ $page -ne 1 ]; then
		left="left=\"act_Prev\""
		cat << EOF >> "$XMLFILE"
				<button name="nav_Prev"> { g7=g7-1; jump menu entry ptt; } </button>
EOF
		cat << EOF >> "$thisspuxml"
			<button name="nav_Prev" />
EOF
	fi
	[ $page -ne $numPages ] && right="right=\"act_Next\""
	cat << EOF >> "$XMLFILE"
				<button name="nav_Return"> 
					{ if (g1 eq 0) jump vmgm menu entry title; 
 					  if (g1 eq 1) jump menu entry root; 
					  if (g1 eq 9) resume; } 
				</button>
EOF
	cat << EOF >> "$thisspuxml"
			<button name="nav_Return" $left $right />
EOF
	if [ $page -ne $numPages ]; then
		cat << EOF >> "$XMLFILE"
				<button name="nav_Next"> { g7=g7+1; jump menu entry ptt; } </button>
EOF
		cat << EOF >> "$thisspuxml"
			<button name="nav_Next" />
EOF
	fi
	cat << EOF >> "$XMLFILE"
				<button name="nav_VMGM"> { jump vmgm menu entry title; } </button>
				<button name="nav_VTSM"> { jump menu entry root; } </button>
EOF
	cat << EOF >> "$thisspuxml"
			<button name="nav_VMGM" up="nav_Return" />
			<button name="nav_VTSM" up="nav_Return" />
EOF
	if [ $audio -eq 1 ]; then
		cat << EOF >> "$XMLFILE"
				<button name="nav_Audio"> { jump menu entry audio; } </button>
EOF
		cat << EOF >> "$thisspuxml"
			<button name="nav_Audio" up="nav_Return" />
EOF
	fi
	if [ $subtitle -eq 1 ]; then
		cat << EOF >> "$XMLFILE"
				<button name="nav_Subs"> { jump menu entry subtitle; } </button>
EOF
		cat << EOF >> "$thisspuxml"
			<button name="nav_Subs" up="nav_Return" />
EOF
	fi
	if [ $page -ne 1 ]; then
		cat << EOF >> "$XMLFILE"
				<button name="act_Prev"> { g7=g7-1; jump menu entry ptt; } </button>
EOF
		cat << EOF >> "$thisspuxml"
			<button name="act_Prev" />
EOF
	fi
	if [ $page -ne $numPages ]; then
		cat << EOF >> "$XMLFILE"
				<button name="act_Next"> { g7=g7+1; jump menu entry ptt; } </button>
EOF
		cat << EOF >> "$thisspuxml"
			<button name="act_Next" />
EOF
	fi

return 0
}

#
#	End pgc definition
#
xml_end_pgc()
{
cat << EOF >> "$XMLFILE"
			</pgc>
EOF
cat << EOF >> "$thisspuxml"
		</spu>
	</stream>
</subpictures>
EOF

return 0
}

case "$1" in
	start)
		xml_start
	;;
	begin_pgc)
		shift
		xml_begin_pgc $1
	;;
	navigation)
		shift
		xml_navi
	;;
	end_pgc)
		xml_end_pgc
	;;
	*)
		error_out
	;;
esac

return 0
}

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

#
# Ok, first define some default values
#
set_defaults "$@"
VTSMDIR="./vtsm"
vts=1
VTSMBG=""
fList=""
audio=0
subtitle=0

#
# Check for needed tools
#
check_tools

#
# Now deal with command line arguments
#
while [ "$infotxt" == "" -a "$*" != "" ]; do
    case "$1" in
  	-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"
	        	echo "See $thisscript -h for more infos"
    	    	exit 1
			fi >&2
   	    shift
  	;;
  	-V|--tvsize)
	    shift
   	    TVSIZE="$1"
   	    shift
  	;;
  	-M|--menu)
	    shift
		defMenu=$MENU
   	    MENU=$(echo "$1" | tr 'a-z' 'A-Z')
		eval testtxt=\"\$TXT_VMGM_PLAY_$MENU\"
		if [ -z "$testtxt" ]; then
			echo "Text elements for menu language $1 does not seem to be defined correctly. Aborting" >&2
			usge
		fi
   	    shift
  	;;
	-ms|--vtsmsound)
	    shift
		vtsmsound="$1"
   		shift
	;;
  	--hasaudio)
  	    audio="1"
   	    shift
  	;;
  	--hassubtitle)
  	    subtitle="1"
   	    shift
  	;;
  	--hasinfo)
   	    shift
  	;;
  	*)
   		infotxt="$1"
  	;;
    esac
done

#
# Set format parameters for PAL or NTSC
#
set_format

#
# Let's see, if all options are correct
# Check output-directories and files
#
mk_check_dir "$VTSMDIR" "OLD" "\$VTSMDIR -o|--output"
mk_check_file "$XMLFILE" "NEW" "\$XMLFILE -x|--xml"
[ ! -z "$VTSMBG" ] && mk_check_file "$VTSMBG" "OLD" "\$VTSMBG -b|--vtsmbg"
[ ! -z "$vtsmsound" ] && mk_check_file "$vtsmsound" "OLD" "\$vtsmsound -ms|--vtsmsound"
[ -z "$vtsmsound" -a ! -z "$MENUSOUND" ] && mk_check_file "$MENUSOUND" "OLD" "\$MENUSOUND"

#
# Chapter-Pictures supplied and existing?
#
if [ -z "$infotxt" ]; then
 	echo "No input files specified"
    echo "See $thisscript -h for more infos"
    exit 1
fi >&2

mk_check_file "$infotxt" "OLD" "Textfile from command line"

#
# Prepare the background picture
# ($VTSMBG will be converted to $workbg)
#
prepare_bg $vts "$VTSMBG"
create_overlay "INFO"
create_common_objects
cp "$emptympg" "$VTSMDIR/$(basename $emptympg)"
EMPTYMPG="$VTSMDIR/$(basename $emptympg)"
mk_picts

#
# Panel for Intra-Menu-Navigation and Thumbnail-Collections
#
init_proc
thistgt="$txt_DVD $txt_CHAPTER"
[ $audio -eq 1 ] && thistgt="$thistgt $txt_AUDIO"
[ $subtitle -eq 1 ] && thistgt="$thistgt $txt_SUBS"
thistgt="$thistgt $txt_INFO"
mk_nav_buttons $thistgt
mk_nav_panel $thistgt
mk_info_panel "$infotxt"

#
# Write out xml headers
#
write_xml start

#
# For every page with button thumbnails we create its own menu mpg
# First create some temporary files which may be overwritten with each
# titleset
#
thispnl=( "$(mktemp -t png.XXXXXXXXXX)" "$(mktemp -t png.XXXXXXXXXX)" "$(mktemp -t png.XXXXXXXXXX)" )
maskPic="$(mktemp -t png.XXXXXXXXXX)"

#
# Now loop through all pages
#
for page in $(seq 1 $numPages); do
	echo -n "Creating menu page #$page"
	let p="$page-1"
	thisppm="$VTSMDIR"/vts_${vts}_info_${page}.ppm
	thisspuxml="$VTSMDIR/vts_${vts}_info_${page}_spu.xml"
	thisMask=( "dummy" "$VTSMDIR/vts_info_${page}_hi.png" "$VTSMDIR/vts_info_${page}_sel.png" )
	thismpg="$VTSMDIR"/vts_${vts}_info_${page}.mpg
	retbtn=1
	[ $page -ne 1 ] && let "retbtn+=1"
	# write begin of pgc and chapter buttons
	write_xml begin_pgc $page
	echo -n "."
	
	# create previous button, if not first page
	for state in 0 1; do
		if [ $page -ne 1 ]; then 
			convert "$TMPDIR/navPnl_${state}.png" \
					\( "$TMPDIR/common_objects/pictPrev_${state}.png" \) \
					-geometry +15+15 -gravity NorthWest -composite "${thispnl[state]}" || error_out
		else
			cp "$TMPDIR/navPnl_${state}.png" "${thispnl[state]}"
		fi
	done

	# create next button, if not last page
	for state in 0 1; do
		if [ $page -ne $numPages ]; then 
			convert "${thispnl[state]}" \
					\( "$TMPDIR/common_objects/pictNext_${state}.png" \) \
					-geometry +15+15 -gravity NorthEast -composite "${thispnl[state]}" || error_out
		fi
	done

	# write navigation buttons to xml
	write_xml navigation
	write_xml end_pgc
	echo -n "."
	
	# create background picture with nav panel and info panel
	[ $page -le 9 ] && thisipnl="$pnlPNG"0$page.png || thisipnl="$pnlPNG"$page.png
	convert "$TMPDIR/common_objects/menubg_$vts".png \
			"$logoPic" -gravity center -composite \
			"${thispnl[0]}" -gravity south -geometry +0+${offsetTVY} -composite \
			"$thisipnl" -gravity northwest -geometry +${offsetTVX}+${offsetTVY} -composite \
			-depth 8 -density $normDensity -units PixelsPerInch "$thisppm" || error_out
			
	# create button masks
	convert +antialias -size $normSize xc:transparent \
		"${thispnl[1]}" -gravity south -geometry +0+${offsetTVY} -composite \
		-density $normDensity -units PixelsPerInch png:"$maskPic" || error_out
	convert "$maskPic" -depth 8 png:"$maskPic" || error_out
	ccount=$(identify -format %k "$maskPic")
	if [ $ccount -ge 2 ]; then
		replColorLine=$(identify -verbose "$maskPic" | sed -e 1,/Histogram/d | head -n2 | \
					tail -n1)
		[ "$IM_VERSION3" \< "6.2.3" ] && replColor=$(echo "$replColorLine" | cut -d')' -f2) \
									  || replColor=$(echo "$replColorLine" | cut -d':' -f2 | cut -d' ' -f2)
		for s in 1 2; do
			convert "$maskPic" -fill "${hiColor[s]}" -opaque "$replColor" "${thisMask[s]}" || error_out
		done
	else
		for s in 1 2; do
			cp "$maskPic" "${thisMask[s]}"
		done
	fi

	echo "."
	#
	# Add a little motion blur to the menu background to eliminate flickering on
	# TV screens (available for IM >= 6.2.5)
	# Thx to Rick Harris for this hint!
	#
	[ ! "$IM_VERSION3" \< "6.2.5" ] && \
	mogrify -density $normDensity -units PixelsPerInch -motion-blur 0x1+90 -depth 8 \
		"$thisppm"

	#
	# Select Audio Track for menu and convert to ac3, if neccessary
	#
	audiotrack="$vtsmsound"
	[ -z $audiotrack ] && audiotrack="$MENUSOUND"
	[ -z $audiotrack ] && audiotrack="$silence"
	fext="${audiotrack##*.}"
	
	if [ "$fext" != "ac3" ]; then
		audiotrack_ac3="$TMPDIR/common_objects/vts_$vts.ac3"
		if [ ! -e "$audiotrack_ac3" ]; then
			ffmpeg -i "$audiotrack" -ab 224kb -ar 48000 -ac 2 "$audiotrack_ac3" 1>/dev/null 2>&1 || error_out
		fi
		audiotrack="$audiotrack_ac3"
	fi
	
	#
	# Create MPEG-Stream from Background-Picture and mux with buttonmasks
	#
	ppmtoy4m -S 420mpeg2 -A 59:54 -n 1 -F "$encFrameRate" -r "$thisppm" | \
		mpeg2enc -a 2 -n "$encNorm" -f 8 -o /dev/stdout | \
		mplex -f 8 -o /dev/stdout /dev/stdin "$audiotrack" | \
  		spumux -v4 "$thisspuxml" > "$thismpg" || error_out

done
#
# Write out menu count
#
let "prevmenus+=$numPages"
echo $menuCount > "$TMPDIR/common_objects/.menucount"

#
# Finished
#
echo "Creation of Chapter selection menu pages finished."
echo ""	

# Cleanup temporary directory if script was called directly
#
cleanup_tmpdir

exit 0	
