#!/bin/bash
#
#    Extension of dvd-menu. See copyright below.
#    Jean-Damien Durand  <Jean-Damien.Durand at cern.ch>
#
#    dvd-mainmenu
#    Copyright 2003 Scott Dylewski  <scott at dylewski.com>
#
#    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 2 of the License, or
#    (at your option) any later version.
#
#    This program 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, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

version='0.5.4-4'

changes () 
{
echo 'Changes:
0.5.4-4	paranoid mode for very difficult input files
        test mode limiting to 1000 frames
0.5.4-3	dvdauthor-0.6.10 now accept only one title per titleset
0.5.4-2	Changed to do movie transcode and burning
0.5.4	No changes.
0.5.2	Fixed audio bug when no audio was used. (re-mplex error)
	Added -c continuous play option (<post> jumps to next title).
	Added -D do not run dvdauthor option.
	Added -W do not create a 50% white background under menu text.
	dvdauthor xml structure changed slightly
	DVD Title (-n) is now optional.
	Added man page.
	Checks for nice fonts.
0.5.0	Changed name to "dvd-menu"
	Only requires lame or oggdec if you are using that file format.
	Fixed some audio bugs (sampling) so it should work better.
	Will automatically delete AUDIO_TS and VIDEO_TS directories
	in your output directory if they already exist.
0.4.6	Fixed bug when checking for toolame (thanks Scott Merrill)
	Removed -t option from toolame for better compatibility with old versions.	
0.4.2	Changed location of main title slightly lower.
	Fixed one hardcoded 720x480 image so PAL option should work better.
	Added -depth 8 to ImageMagick calls to fix ppmtoy4m errors. 
	Upgraded main menu background when no background is passed.
0.4	Fixed bug when no background file was passed. Works now.
	Ogg audio format supported now.
	Uses toolame for mp2 audio encoding when available.
	-p (PAL format option) added.  Not tested, but should work.
	Menu button white background is now 50% transparent.
0.3	Added section to check for required programs
	If no background passed, a black one will be used.
0.2	Initial release'
}

help ()
{
echo "This is NOT dvd-menu original. You are warned."
echo
echo "dvd-menu is part of dvd-slideshow $version"
echo "`basename $0`"
echo "http://freshmeat.net/dvdslideshow/"
echo 'Copyright 2003 Scott Dylewski <scott at dylewski.com>
 
Usage: 
  dvd-menu
    -t <titleset1> ... -t <titlesetN>
    -f <file1> ... -f <fileN>
    -s <gain1> ... -s <gainN>
    -P 1       ... -P 0
    -o output_directory
    -n <dvdtitle>
    [-b <background jpeg>] [ -a <menu audio file> ] [-p]
    [-c] [-D] [-W] 
    [-N] [-B]

Description: 
	Makes mpeg2 from input files and creates
    a simple vmgm menu with buttons that
	link to these modified files.
	
Options: 
 -t <titleset1> -t <titleset2> ... -t <titlesetN>
	Name of each title.  Each string will be used for 
	the button menu corresponding to each file.

 -f <file1> <file2> ...
	Name of each titleset file.
 		
 -P <zero or more characters> <zero or more characters> ...
	Paranoid mode per input: anything non-zero will mean yes
 		
 -s <gain1> <gain2> ...
	Audio gain of each file.
 		
 -o <output directory>
	Directory where the output dvd file system resides

 -b <background jpeg>
	Image to put in the background of the menu.

 -a <audiofile>
	Audio file to use in the background of the
	menu.  The full audio file will keep looping.
	Supports mp3, ogg, or wav.

 -n "dvd_title"
        This string will be placed on the top of the
        menu page.

 -p
        Use PAL format instead of NTSC (untested initial support)

 -c
        Use continuous method.  Each video plays one after another.

 -T
        Test mode: do 1000 frames.

 -W
        Do not generate 50% white background behind menu text.

 -D
        Do not call dvdauthor at the end.  Useful when you want
	to edit your own xml file and pass it to dvdauthor by hand.

 -N
        Skip internal phase where input files are transcoded to mpeg
    files. That is, if you use this option, input files will be used
    directory and untouched for the dvd authoring. So we assume that
    your input files are then mpeg files, directly playable by any
    DVD player.

 -B
        Burn to dvd using output directory content.

 -h or -help 
   Prints this help. 

Requires:
    mencoder
    transcode (latest) and its latest plugins
    mplex
    growisofs
    dvdauthor 0.6.9
    sox
    mjpegtools  (mp2enc, mpeg2enc, ppmtoy4m)
    ImageMagick (convert)
    netPBM
 '
}

if [ $# -lt 1 ]; then
	help
	exit 1
fi


## setup initial variables:
debug=0  # 1 or 0
pal=0
fill_audio=0
tmpdir="."
continuous=0
no_dvdauthor=0
no_transcode=0
burn=0
testmode=0
no_white=0
# define some possible fonts:
font1='/usr/share/fonts/default/Type1/n019003l.pfb' # helvetica normal URW font
font2='/usr/share/fonts/default/TrueType/helr____.ttf' # helvetica regular truetype


#if [ ! -d "$tmpdir" ] ; then
#	## create directory
#	mkdir "$tmpdir"
#fi

let o=0
let n=0
let m=0
let p=0
for arg
do
	case "$arg" in
	-t) shift ; title[$n]="${1}"; let n=$n+1; shift ;;  # each title
	-f) shift ; file[$m]="${1}"; let m=$m+1; shift ;;  # each titleset
	-P) shift ; paranoid[$p]="${1}"; let p=$p+1; shift ;;  # each paranoid mode
	-s) shift ; gain[$o]="${1}"; let o=$o+1; shift ;;  # each gain
	-o) shift; outdir="$1"; shift ;;  # dvd directory
	-b) shift; bgfile="$1"; shift ;;  # background jpeg
	-n) shift; dvd_title="$1"; shift ;; # name of DVD disk
	-N) shift; no_transcode=1 ;;
	-B) shift; burn=1 ;;
	-T) shift; testmode="-frames 1000" ;;
	-p) shift; pal=1 ;;
	-c) shift; continuous=1 ;;
	-D) shift; no_dvdauthor=1 ;;
	-W) shift; no_white=1 ;;
	-a) shift; audiofile="$1"; shift;; # audio file playing during menu
	-h) help ; exit 0 ; shift ;;
	-?) help ; exit 0 ; shift ;;
	-help) help ; exit 0 ; shift ;;
	esac
done

## check_rm checks to see if the file exists before it's deleted:
check_rm ()
{
	if [ -f "${1}" ] ; then
		rm "${1}"
	fi
}

cleanup ()
{
	## clean up temporary files
	echo "[dvd-menu] cleanup..."
	check_rm "$tmpdir/slideshow_background.ppm"
#	check_rm "$tmpdir/silence.mp2"
	check_rm "$tmpdir/button_background.png"
	check_rm "$tmpdir/button_text.png"
	check_rm "$tmpdir/button_mask.png"
	check_rm "$tmpdir/menu.ppm"
	check_rm "$tmpdir/menu.spumux"
	check_rm "$tmpdir/menu_mask.png"
	check_rm "$tmpdir/menu_t.mpg"
	check_rm "$tmpdir/menu_audio.wav"
	check_rm "$tmpdir/audio.mp2"
	check_rm "$tmpdir/audio.wav"
	check_rm "$tmpdir/dvd_title.png"
        k=0
        dk=0
        for file in "${title[@]}"; do
                [ $k -lt 10 ] && dk="0$k" || dk=$k
#              	echo "k=$k  dk=$dk"
                check_rm "$tmpdir"/title_"$dk"_mask.png
                check_rm "$tmpdir"/title_"$k"_mask.png
                check_rm "$tmpdir/title_$dk.ppm"
                check_rm "$tmpdir/title_$k.ppm"
                let k=$k+1
        done
	echo "[dvd-menu] done!"
}

forcequit () ## function gets run when we have some sort of forcequit...
{
	## clean up temporary files
	cleanup
	exit
}

trap 'forcequit' INT
trap 'forcequit' KILL
trap 'forcequit' TERM

## check for the necessary programs:
checkforprog ()
{
        it=`which $1`
        if [ -z "$it" ] ; then
                echo "[dvd-menu] ERROR:  $1 not found! "
                echo "[dvd-menu] Check the dependencies and make sure everything is installed."
                exit 1
        fi
}

checkforprog mencoder
checkforprog transcode
checkforprog mplex
checkforprog growisofs
checkforprog ppmtoy4m
checkforprog sox
checkforprog convert
checkforprog pngtopnm
checkforprog dvdauthor
                                                                                                         
# verify fonts exist:
if [ -f "$font1" ] ; then
        font="-font $font1"
elif [ -f "$font2" ] ; then
        font="-font $font2"
else
        echo "[dvd-menu] Cannot find required fonts.  Using default ImageMagick font."
        font=""
fi

if [ $debug -eq 1 ] ; then
	echo "[dvd-menu] outdir=$outdir"
	echo "[dvd-menu] pal=$pal"
	echo "[dvd-menu] audio files=$audiofile"
	echo "[dvd-menu] menu titles:" 
	echo "[dvd-menu] ${title[@]}" 
	echo "[dvd-menu] source files:" 
	echo "[dvd-menu] ${file[@]}" 
	echo "[dvd-menu] audio gains:" 
	echo "[dvd-menu] ${gain[@]}" 
fi

if [ ! -d "${outdir}" ] ; then	
	echo "[dvd-menu] ERROR: Output directory does not exist!"
	exit 1
else
	## output directory already exists.  Delete old files
#	echo "[dvd-menu] Output directory already exists. "
	echo "[dvd-menu] Deleting AUDIO_TS and VIDEO_TS directories..."
	if [ -d "${outdir}/AUDIO_TS" ] ; then rm -r "${outdir}/AUDIO_TS" ; fi
	if [ -d "${outdir}/VIDEO_TS" ] ; then rm -r "${outdir}/VIDEO_TS" ; fi
fi

hms ()
{
        ## pass a number in hundreths of seconds and get back a
        ## time code of the form HR:MM:SS:HU
        hours=$(( $1 / 360000 ))
        it=$(( $1 - $hours * 360000 ))
        minutes=$(( $it / 6000 ))
        it=$(( $1 - $minutes * 6000 ))
        seconds=$(( $it / 100 ))
        hundreths=$(( $it - $seconds * 100 ))
        it="$hours:$minutes:$seconds.$hundreths"
        echo "${it}"
}

white_button_mask ()
{
	# white_button_mask outfile
	convert -size ${width}x$menuh -quality 100 xc:transparent -depth 8 -fill white \
	-draw "roundRectangle $menu_location_x,$menu_location_y,$menuright,$menubottom 20,20" \
	-draw "Rectangle 0,0,$width,125" \
	-crop $resolution-0-0 "$1"
}

title_text ()
{
	# title_text outfile
	convert -depth 8 -size $resolution xc:transparent -fill black \
	-pointsize $title_font_size -gravity NorthWest $font \
	-draw "text 80,100 \"${dvd_title}\"" "$1" 
}

if [ "$pal" -eq 1 ] ; then
        framerate='25'
        width='720'
        height='576'
        resolution='720x576'
        frames_per_sec=2500  # in 1/100ths of a second
else
        framerate='29.97'
        width='720'
        height='480'
        resolution='720x480'
        frames_per_sec=2997  # in 1/100ths of a second
fi

## other cool colors:  cadetblue cornflowerblue midnightblue
bg_color='steelblue'
menu_height=28
menu_width=288
text_size=$(( 3 * $menu_height / 4 ))
text_loc=$(( $menu_height/2 + $text_size/2 ))
menu_location_x=360
menu_location_y=175  # distance of the top of the first menu item to the top of the screen
title_font_size=48
title_location_y=80
frames=30 	# number of frames in the menu mpg file. 
		# I guess this only really needs to be 1 frame
		# but 30 is easier to debug so we can play it.

## first, do the background image, then do the alpha mask:
if [ -f "${bgfile}" ] ; then
        echo "[dvd-menu] using background image ${bgfile}"
        convert "${bgfile}" -resize x"$height" -bordercolor black -border "$width"x240 -gravity center -crop "$width"x"$height"'+0+0!' -depth 8 -quality 100 $tmpdir/slideshow_background.ppm
        mv "$tmpdir/slideshow_background.ppm" "$tmpdir/menu.ppm"
else
        ## need to write out a blank image of the given size:
        echo "[dvd-menu] creating background image "
        convert -depth 8 -size "$width"'x'"$height" gradient:white-$bg_color -type TrueColor "$tmpdir/menu.ppm"
fi

## create overlay transparent image:
convert -depth 8 -size $resolution xc:transparent $tmpdir/button_background.png
cp "$tmpdir/button_background.png" "$tmpdir/menu_mask.png"

## check to make sure we have less than 9 buttons?  (size restriction)

menuright=$(( $menu_location_x + $menu_width))
menubottom=$(( $height + 50 ))  ## add 50 so we can chop off the bottom later
menuh=$(( $height + 50 ))
if [ "$no_white" -eq 0 ] ; then
	white_button_mask "$tmpdir/button_background.png"
	composite -type TrueColor -depth 8 -dissolve 50 "$tmpdir/button_background.png" "$tmpdir/menu.ppm" "$tmpdir/menu.ppm"
fi

## add dvd title text: (only if passed)
if [ -n "$dvd_title" ] ; then
	title_text "$tmpdir/dvd_title.png"
	composite -depth 8 -type TrueColor "$tmpdir/dvd_title.png" "$tmpdir/menu.ppm" "$tmpdir/menu.ppm"
fi

## loop over each source file
let i=0
for this_file in "${file[@]}"; do
    if [ "$no_transcode" -eq 0 ]; then
      this_gain=${gain[$i]}
	  echo "[dvd-menu] File=$this_file  audio gain=$this_gain  "

      if [ "$pal" -eq 1 ] ; then
        input=$tmpdir/dvd-menu.movie$i.25
        FPS=25.000
        WIDTH_OUT=720
        HEIGHT_OUT=576
      else
        input=$tmpdir/dvd-menu.movie$i.30
        FPS=29.970
        WIDTH_OUT=720
        HEIGHT_OUT=480
      fi

      rm -f $input

      this_paranoid=${paranoid[$i]}
      if [ "$this_paranoid" != "" ]; then
	    echo "[dvd-menu] Paranoid mode for $this_file : doing yet another avi file using mencoder"
        echo "[dvd-menu] mencoder $testmode -mc 0 -noskip -skiplimit 0 -ovc lavc -oac lavc -lavcopts vcodec=mpeg4:vhq:trell:mbd=2:vmax_b_frames=1:v4mv:vb_strategy=0:vlelim=0:vcelim=0:cmp=2:subcmp=2:precmp=2:predia=1:dia=1:vme=4 -o paranoid_$$.avi $this_file"
        mencoder $testmode -mc 0 -noskip -skiplimit 0 -ovc lavc -oac lavc -lavcopts vcodec=mpeg4:vhq:trell:mbd=2:vmax_b_frames=1:v4mv:vb_strategy=0:vlelim=0:vcelim=0:cmp=2:subcmp=2:precmp=2:predia=1:dia=1:vme=4 -o paranoid_$$.avi $this_file
	    echo "[dvd-menu] Resampling paranoid_$$.avi"
        echo "[dvd-menu] mencoder $testmode -srate 48000 -o $input -ovc copy -oac copy -ofps $FPS paranoid_$$.avi"
        mencoder $testmode -srate 48000 -o $input -ovc copy -oac copy -ofps $FPS $this_file >&/dev/null
      else
	    echo "[dvd-menu] Resampling $this_file"
        echo "[dvd-menu] mencoder $testmode -srate 48000 -o $input -ovc copy -oac copy -ofps $FPS $this_file"
        mencoder $testmode -srate 48000 -o $input -ovc copy -oac copy -ofps $FPS $this_file >&/dev/null
      fi

      rm -f paranoid_$$.avi

	  echo "[dvd-menu] Probe $this_file to detect dimensions, eventually aspect ratio"
      this=`tcprobe -i $input 2>&1`; [ $? -ne 0 ] && exit 1
      echo $this
      # See if there is an explicit aspect ratio in the input file
      asr=`echo $this | perl -ne '
        while (<>) {
          chomp;
          if (/aspect ratio: ([\d:]+)/) {
           print "$1\n";
            last;
          }
        }
      '`

      WIDTH=`echo $this  |grep '\[avilib\] V:' |perl -e ' chomp($line=<STDIN>) ; $line =~ /width=(\d+)/   ;  print $1' `
      HEIGHT=`echo $this |grep '\[avilib\] V:' |perl -e ' chomp($line=<STDIN>) ; $line =~ /height=(\d+)/  ;  print $1' `
      echo "[dvd-menu] Video Input: ${WIDTH}x${HEIGHT}"

      if [ -n "$asr" ]; then
        if [ "$asr" = "2" ]; then
          echo "[dvd-menu] Found 4:3 aspect ratio"
        elif [ "$asr" = "3" ]; then
          echo "[dvd-menu] Found 16:9 aspect ratio"
        else
          echo "[dvd-menu] Found asr=$asr ?"
          exit 1
        fi
      else
        echo "[dvd-menu] No explicit aspect ratio"
      fi


      if [ -z "$asr" ]; then
        echo "[dvd-menu] Compute output width x height and borders"
        #
        ## Cut past from widely distributed script to get border value
        #
        ANCHO_1_1_OUT=`echo "($HEIGHT_OUT * 4/3)"|bc -l`
        ALTO_OUT=`echo "$HEIGHT / ($WIDTH / $ANCHO_1_1_OUT)" |bc -l`
        ALTO_OUT=`echo "scale=0 ; $ALTO_OUT/1"|bc -l`
        ALTO_OUT=`echo "scale=0 ; $ALTO_OUT+$ALTO_OUT%2" |bc -l`
        #
        ## As said in transcode man page, final frame width/height should be a multiple of 8
        #
        ALTO_OUT=`echo "scale=0 ; $ALTO_OUT/8*8" |bc -l`
        BORDE=`echo "scale=0 ; ($HEIGHT_OUT-$ALTO_OUT)/2"|bc -l`
        if [ $BORDE -le 0 ]; then
            $BORDER=0
        fi
        echo "[dvd-menu] Video Output: ${WIDTH_OUT}x${HEIGHT_OUT}"
        echo "[dvd-menu] Borders: $BORDE"
      else
        echo "[dvd-menu] Will use --keep_asr option of transcode together with its -Z option (untested)"
      fi

      echo "[dvd-menu] Transcoding to MPEG-2 using transcode"
      output=$input
      if [ $this_gain -gt 0 ]; then
        dogain="-s $this_gain"
      else
        dogain=
      fi
      flags="-c -q 6 -4 2 -2 1 -K file=matrix.txt.$$ -R 2"
      rm -f matrix.txt.$$
      # Steven Schultz's combined HQ matrix
      cat - > matrix.txt.$$ << MATRIX
# High resolution INTRA table
8,16,18,20,24,25,26,30
16,16,20,23,25,26,30,30
18,20,22,24,26,28,29,31
20,21,23,24,26,28,31,31
21,23,24,25,28,30,30,33
23,24,25,28,30,30,33,36
24,25,26,29,29,31,34,38
25,26,28,29,31,34,38,42
# TMPEGEnc NON-INTRA table
16,17,18,19,20,21,22,23
17,18,19,20,21,22,23,24
18,19,20,21,22,23,24,25
19,20,21,22,23,24,26,27
20,21,22,23,25,26,27,28
21,22,23,24,26,27,28,30
22,23,24,26,27,28,30,31
23,24,25,27,28,30,31,33
MATRIX
      bitr="8500"
      #
      ## From transcode author:
      #
      # WARNING: Do not increase it above 8500 regardless of what you've been told. I 
      # know that proffesional DVDs are encoded at a peak value of 9800 kbps, i know 
      # that various pieces of documentation recommend 9800 as One Value To Rule Them 
      # All. Just ignore them. Trust me. If you do otherwise, sooner or later you'll 
      # create a DVD that will not be playable on some standalone players. I learned 
      # that the hard way. You have been warned.
      # Moreover, you don't truly need very high values. I did many evaluations, and 
      # the results are pretty surprising: many scenes that i shot do not take the 
      # peak bitrate above 7000 kbps, and the average is at 2000 or something! Only 
      # very rarely you'll need such high bitrates.
      if [ -z "$asr" ]; then
        echo "[dvd-menu] transcode $dogain -w $bitr -Z ${WIDTH_OUT}x${ALTO_OUT} -Y -$BORDE,0,-$BORDE,0 --export_asr 2 -i $input -V -y mpeg2enc,mp2enc -F 8,\"${flags}\" -Q 5,5 -b 224,0,1 -o $output"
        if [ $this_gain -gt 0 ]; then
          transcode -s $this_gain -w $bitr -Z ${WIDTH_OUT}x${ALTO_OUT} -Y -$BORDE,0,-$BORDE,0 --export_asr 2 -i $input -V -y mpeg2enc,mp2enc -F 8,"${flags}" -Q 5,5 -b 224,0,1 -o $output
        else
          transcode -w $bitr -Z ${WIDTH_OUT}x${ALTO_OUT} -Y -$BORDE,0,-$BORDE,0 --export_asr 2 -i $input -V -y mpeg2enc,mp2enc -F 8,"${flags}" -Q 5,5 -b 224,0,1 -o $output
        fi
      else
        echo "[dvd-menu] transcode $dogain -w $bitr -Z ${WIDTH_OUT}x${HEIGHT_OUT} --keep_asr --export_asr 2 -i $input -V -y mpeg2enc,mp2enc -F 8,\"${flags}\" -Q 5,5 -b 224,0,1 -o $output"
        if [ $this_gain -gt 0 ]; then
          transcode -s $this_gain -w $bitr -Z ${WIDTH_OUT}x${HEIGHT_OUT} --keep_asr --export_asr 2 -i $input -V -y mpeg2enc,mp2enc -F 8,"${flags}" -Q 5,5 -b 224,0,1 -o $output
        else
          transcode -w $bitr -Z ${WIDTH_OUT}x${HEIGHT_OUT} --keep_asr --export_asr 2 -i $input -V -y mpeg2enc,mp2enc -F 8,\"${flags}\" -Q 5,5 -b 224,0,1 -o $output
        fi
      fi
      echo "[dvd-menu] Deleting temporary input `basename $input` and matrix.txt.$$"
      rm -f $input matrix.txt.$$
      echo "[dvd-menu] Multiplexing audio and video"
      echo "[dvd-menu] mplex -f 8 -o $output.dvd.mpg $output.m2v $output.mpa"
      mplex -f 8 -o $output.dvd.mpg $output.m2v $output.mpa
      echo "[$me] ... Deleting temporary audio and video files"
      rm -f $output.m2v $output.mpa
      #
      ## We now create dummy xmlfiles and that's all
      #
      xmlfile[$i]="$tmpdir/dvd-menu.movie$i.xml"
      rm -f ${xmlfile[$i]}
      echo "<vob file=\"$output.dvd.mpg\"/>" > ${xmlfile[$i]}
    else
      xmlfile[$i]="$tmpdir/dvd-menu.movie$i.xml"
      rm -f ${xmlfile[$i]}
      echo "<vob file=\"$this_file\"/>" > ${xmlfile[$i]}
    fi
	let i=$i+1
done

## loop over each title:
let i=0
for this_title in "${title[@]}"; do
	echo "[dvd-menu] Title=$this_title  bgfile=$bgfile  "
	# make each individual button:
	# to be fancy, let's add the button layers in two steps.  first the
	# button background, then the text:
	convert -depth 8 -size ${menu_width}x$menu_height xc:transparent -quality 100 $font \
	-pointsize $text_size -draw "text 20,$text_loc \"${this_title}\"" "$tmpdir/button_text.png"
	# make each individual button mask (for when it's selected)
	convert -depth 8 -size ${menu_width}x$menu_height xc:gray50 -pointsize $text_size $font \
	-fill red -draw "text 20,$text_loc \"${this_title}\"" -quality 100 "$tmpdir/button_mask.png"

	## add each button as necessary, and increment the location downward
	composite -type TrueColor -depth 8 -geometry +$menu_location_x+$menu_location_y "$tmpdir/button_text.png" "$tmpdir/menu.ppm" "$tmpdir/menu.ppm"
	## add each overlay mask for the selection of buttons:
	composite -type TrueColor -depth 8 -quality 100 -geometry +$menu_location_x+$menu_location_y "$tmpdir/button_mask.png" "$tmpdir/menu_mask.png" "$tmpdir/menu_mask.png"

	## now record the button location:
	right[$i]="$(( $menu_location_x + $menu_width ))"
	left[$i]="$(( $menu_location_x ))"
	top[$i]="$(( $menu_location_y ))"
	bottom[$i]="$(( $menu_location_y + $menu_height ))"
	vts="$(( $i + 1 ))"
	echo "[dvd-menu] i=$i vts=$vts"
		
	let menu_location_y=$menu_location_y+$menu_height
	let i=$i+1
done

## now convert the menu background to a mpg
if [ "$pal" -eq 1 ] ; then
	ppmtoy4m -v 0 -n "$frames" -r -F 25:1 -A 59:54 -I p "$tmpdir/menu.ppm" | mpeg2enc -v 0 -a 2 -M 3 -f 8 -o "$tmpdir/menu.mpg"
else
	ppmtoy4m -v 0 -n "$frames" -r -F 30000:1001 -A 10:11 -I p "$tmpdir/menu.ppm" | mpeg2enc -v 0 -a 2 -M 3 -f 8 -o "$tmpdir/menu.mpg"
fi

## reduce mask colors to 4:
## imagemagick can't seem to create a color depth less than 8 bit, so we need to use NetPBM
pngtopnm "$tmpdir/menu_mask.png" | pnmdepth 3 | pnmtopng -transparent "#7f7f7f" > "$tmpdir/menu_mask_o.png"
mv "$tmpdir/menu_mask_o.png" "$tmpdir/menu_mask.png"

# optionally fade out at a certain time?
if [ -n "$audiofile" ] ; then
	## get type of file:  mp3, ogg, or wav
	suffix=`echo "$audiofile" | awk -F. '{print $NF}'`
	echo "[dvd-menu] suffix=$suffix"
	if [ "$suffix" == "mp3" ] ; then
		checkforprog lame
	        lame --decode "$audiofile" "$tmpdir/audio_tmp.wav"
		# convert it to 48khz:
		sox -v 0.95 "$tmpdir/audio_tmp.wav" -r 48000 "$tmpdir/audio.wav"
		rm "$tmpdir/audio_tmp.wav"
	elif [ "$suffix" == "ogg" ] ; then
		checkforprog oggdec
	        oggdec -o "$tmpdir/audio_tmp.wav" "$audiofile"
		# convert it to 48khz:
		sox -v 0.95 "$tmpdir/audio_tmp.wav" -r 48000 "$tmpdir/audio.wav"
		rm "$tmpdir/audio_tmp.wav"
	elif [ "$suffix" == "wav" ] ; then
#	        cp "$audiofile" "$tmpdir/audio_tmp.wav"
		# convert it to 48khz:
		sox -v 0.95 "$audiofile" -r 48000 "$tmpdir/audio.wav"
	else
	        echo "[dvd-menu] ERROR:  Unknown audio file format.  Must be .mp3, .ogg, or .wav"
	fi
else
	## create silence:  
	echo "[dvd-menu] creating silence .wav file"
	sox -t raw -s -w -c 2 -r 48000 /dev/zero -t wav - trim 0 0:01 > "$tmpdir/audio.wav"
fi


## toolame is way faster! (3x in my test)
it=`which toolame`
if [ -n "$it" ] ; then
	echo "[dvd-menu] # using toolame..."
        toolame -s 48 -b 224 "$tmpdir/audio.wav" "$tmpdir/audio.mp2"
else
	echo "[dvd-menu] # using mp2enc"
        mp2enc -v 0 -b 224 -r 48000 -s -o "$tmpdir/audio.mp2" < "$tmpdir/audio.wav"
fi

## now multiplex the audio and video:
echo "[dvd-menu] mplexing the files............."
mplex -v 0 -f 8 -o "$tmpdir/menu_t.mpg" "$tmpdir/menu.mpg" "$tmpdir"/audio.mp2

## start of button subpicture XML file creation for spumux:
## now define the buttons:
echo '<subpictures>' > "$tmpdir/menu.spumux"
echo '	<stream>' >> "$tmpdir/menu.spumux"
echo -n '		<spu start="00:00:00.00" end="00:00:00.00" highlight="' >> "$tmpdir/menu.spumux"
echo "$tmpdir/menu_mask.png"'" force="yes" >' >> "$tmpdir/menu.spumux"
## now loop over the buttons:
let i=0
for it in "${left[@]}"; do
	echo '			<button x0="'${left[$i]}'" y0="'${top[$i]}'" x1="'${right[$i]}'" y1="'${bottom[$i]}'" />' >> "$tmpdir/menu.spumux"
#	echo '			<action label="'${title[$i]}'" />' >> "$tmpdir/menu.spumux"
	let i=$i+1
done
echo '		</spu>' >> "$tmpdir/menu.spumux"
echo '	</stream>' >> "$tmpdir/menu.spumux"
echo '</subpictures>' >> "$tmpdir/menu.spumux"

echo "[dvd-menu] ###############################################"
echo "[dvd-menu] spumuxing the files............."
## using spumux now:
spumux -v 0 -P "$tmpdir/menu.spumux" < "$tmpdir/menu_t.mpg" > "$tmpdir/menu.mpg"

## now build the dvdauthor xml file:
## do we need "jumppad"?
echo '<dvdauthor dest="'${outdir}'" jumppad="off">' > "$tmpdir/vmgm.xml"
echo '        <vmgm>' >> "$tmpdir/vmgm.xml"
echo '           <menus>' >> "$tmpdir/vmgm.xml"
echo '               <pgc entry="title" >' >> "$tmpdir/vmgm.xml"
echo '                    <vob file="'$tmpdir/menu.mpg'" pause="inf"/>' >> "$tmpdir/vmgm.xml"
## now loop over each title:
let i=1   ## titles start from 1, not zero.
for it in "${xmlfile[@]}"; do
    echo '             		<button> jump title '$i'; </button>' >> "$tmpdir/vmgm.xml"
	let i=$i+1
done
echo '                    <post> jump vmgm menu 1; </post>' >> "$tmpdir/vmgm.xml"
echo '                </pgc>' >> "$tmpdir/vmgm.xml"
echo '           </menus>' >> "$tmpdir/vmgm.xml"
echo '        </vmgm>' >> "$tmpdir/vmgm.xml"

## now cat the other ones into this file...
let i=0   
total_files="${#xmlfile[@]}"
for it in "${xmlfile[@]}"; do
	if [ "$(( $i + 1 ))" -eq "$total_files" ] ; then continuous=0 ; fi
	let j=$i+2
	echo "[dvd-menu] xmlfile=${xmlfile[$i]}"
	echo "[dvd-menu] it=$it"
	suffix=`echo ${xmlfile[$i]} | awk -F. '{print $NF}'`
#	echo "[dvd-menu] suffix=$suffix"
	if [ "$suffix" == 'xml' ] ; then
		## xml file exists:  use it!
        echo '	<titleset>' >> "$tmpdir/vmgm.xml"
		echo '		<titles>' >> "$tmpdir/vmgm.xml"
#		echo '         <subpicture lang="EN" />' >> "$tmpdir/vmgm.xml"
		echo '			<pgc>' >> "$tmpdir/vmgm.xml"
		cat "${xmlfile[$i]}" >> "$tmpdir/vmgm.xml"
		if [ "$continuous" -eq 1 ] ; then
            echo "			<post> jump title $j; </post>" >> "$tmpdir/vmgm.xml"
		else
			echo '			<post> call vmgm menu 1; </post>' >> "$tmpdir/vmgm.xml"
		fi
		echo '			</pgc>' >> "$tmpdir/vmgm.xml"
		echo '		</titles>' >> "$tmpdir/vmgm.xml"
		echo '	</titleset>' >> "$tmpdir/vmgm.xml"
	elif [ "$suffix" == 'mpg' ] ; then
		## assume user already made it vob compatible	
		## write the title xml:
        echo '	<titleset>' >> "$tmpdir/vmgm.xml"
		echo '		<titles>' >> "$tmpdir/vmgm.xml"
		echo '			<pgc>' >> "$tmpdir/vmgm.xml"
		echo '				<vob file="'${xmlfile[$i]}'"  />' >> "$tmpdir/vmgm.xml"
		if [ "$continuous" -eq 1 ] ; then
            echo "			<post> jump title $j; </post>" >> "$tmpdir/vmgm.xml"
		else
			echo '			<post> call vmgm menu 1; </post>' >> "$tmpdir/vmgm.xml"
		fi
		echo '			</pgc>' >> "$tmpdir/vmgm.xml"
		echo '		</titles>' >> "$tmpdir/vmgm.xml"
		echo '	</titleset>' >> "$tmpdir/vmgm.xml"
	else
		echo '[dvd-menu] error... filetype not supported!'
		exit
	fi
	let i=$i+1
done

## finish up xml file:
echo '</dvdauthor>' >> "$tmpdir/vmgm.xml"

echo "###############################################"

## run dvdauthor?
if [ "$no_dvdauthor" -eq 0 ] ; then
	echo "[dvd-menu] Running dvdauthor..."
	dvdauthor -o ${outdir} -x "$tmpdir/vmgm.xml"
else
	echo "[dvd-menu] Not running dvdauthor.  Edit the vmgm.xml file"
	echo "[dvd-menu] if you wish, and then run dvdauthor: "
	echo "[dvd-menu] dvdauthor -x vmgm.xml"
	echo " "
fi

if [ "$burn" -ne 0 ] ; then
	echo "[dvd-menu] Running growisofs..."
    growisofs -Z /dev/dvd -dvd-video ${outdir}
fi

cleanup
