#!/usr/bin/env bash
#
#   mk_vtsm_info 
#     - Display Information Panel(s).
#
#   Copyright (c) 2004-2008 W. Wershofen <itconsult at wershofen.de>
#   Copyright (c) 2010-2011 Markus Kohm <kohm at users.sf.net>
#   Copyright (c) 2009-2012 Joo Martin <joomart2009 at users.sf.net>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This package is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Changes:
#
#   2004-04-13  Wolfgang Wershofen
#               * initial version
#   2009-06-23  Joo Martin
#               * add aspect ratio option for menu background image (-r)
#   2010-06-21  Markus Kohm
#               * renamed dvdwizardrc into dvdwizard_common
#               * moved some functions to dvdwizard_common
#               * usage of gettext features for multilanguage ui
#                 -several `echo' replaced by `printf'
#   2010-09-29  Joo Martin
#               * relaced `-ab 224kb' by `-ab 224000' at ffmpeg calls
#   2011-01-04  Joo Martion
#               * setting of VIDEO_FORMAT at call of spumux
#               * fixed: background for the buttons
#   2012-03-18  Joo Martin
#               * user config file always in $HOME/.config/dvdwizard/
#
# -------------------------------------------------------------------------

#
# i18n
#
export TEXTDOMAIN=dvdwizard
export TEXTDOMAINDIR="@LOCALEDIR@"

# We need some sub-routines from dvdwizard_common.
# This file must be found at PATH.
#
. dvdwizard_common || {
    echo $"FATAL ERROR: could not execute common function file \`dvdwizard_common'!
You have to install \`dvdwizard_common' somewhere at PATH." >&2
    exit 1
}

# Usage message
#
usagetext=$"
Usage:	${thisscript} [options] text-file
	${thisscript} -h|--help
	${thisscript} -v|--version

currently supported options:
----------------------------
-C  | --config-file	filename of dvdwizard-configuration file
			[~/.config/dvdwizard/dvdwizard.conf]
-o  | --output		Path where the created menu mpegs will be stored 
			[\$BASEDIR/vtsm]
-x  | --xml		Print dvdauthor XML-specs into this file
			[\$BASEDIR/dvdwizard.xml]
-b  | --vtsmbg		Image to use as background for chapter thumbnails.
			If not specified, mk_vtsm will create one from 
			scratch
-r  | --bgratio		Define aspect ratio of menu background   [4:3]
-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.
			[660x530]
-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.
-h  | --help		print this lot out
-v  | --version         print version information only
--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
"

# ------------------------------------------
# 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 -scene 0 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."
    printf $"Will need %d info menu page(s).\n" $numPages
    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?
#
test_versionhelp "$@"

#
# 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
	        error_help $"Incorrect TV-Norm %s specified.\nOnly PAL and NTSC are supported." "${TVNORM} (-N|--tvnorm ${TVNORM})"
	    fi
   	    shift
  	    ;;
  	-V|--tvsize)
	    shift
   	    TVSIZE="$1"
   	    shift
  	    ;;
  	-M|--menu)
	    shift
	    defMenu=$MENU
   	    MENU=$(echo "$1" | tr [:lower:] [:upper:])
	    eval testtxt=\"\$TXT_VMGM_PLAY_$MENU\"
	    if [ -z "$testtxt" ]; then
		error_help $"Text elements for menu language %s do not seem to be defined correctly." "$1"
	    fi
   	    shift
  	    ;;
	-ms|--vtsmsound)
	    shift
	    vtsmsound="$1"
   	    shift
	    ;;
  	--hasaudio)
  	    audio="1"
   	    shift
  	    ;;
  	--hassubtitle)
  	    subtitle="1"
   	    shift
  	    ;;
  	--hasinfo)
   	    shift
  	    ;;
  	-r|--bgratio)
  	    shift
  	    BGRATIO="$1"
  	    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
    error_help $"No input files specified"
fi

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
    printf $"Creating menu page #%d" $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
	# joo: patch because of seldom false color selection
	replColorLine=$(identify -verbose "$maskPic" | \
	    sed -e 1,/Histogram/d | head -n4 | grep "rgba" | tail -n1)
	replColor='#'$(echo "$replColorLine" | cut -d'#' -f2 | cut -d' ' -f1)
	for s in 1 2; do
            # joo: define SELCOLOR (hiColor[2]) always as background
	    convert "$maskPic" -fill "${hiColor[2]}" \
		-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!
    #
    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 224000 -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 "$pixAspect" -n 1 -F "$encFrameRate" -r "$thisppm" \
	| mpeg2enc -a "$mpgAspect" -n "$encNorm" -f 8 -q 5 -o /dev/stdout \
	| mplex -f 8 -o /dev/stdout /dev/stdin "$audiotrack" \
	| VIDEO_FORMAT="$TVNORM" 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	
