#!/bin/bash

# Script version
PLUGIN_VERSION="0.0.009-TEN"

# Home of this version: http://ten.htpc-forum.de - Thanks to HelAu for hosting!
# Patchlevel: 2006-04-19 by TEN
# Introduced at: http://www.vdr-portal.de/board/thread.php?threadid=48264#post452236
# Credits: LordJaxom, HelAu, FireFly, wilderigel, gonz, Bert

# Requirements:
# VDR parent plugin: burn 0.0.009 from http://www.e-tobi.net/vdr-experimental/pool/source/vdr/vdr-plugin-burn_0.0.009.orig.tar.gz
# ProjectX 0.90.4/30.03.2006 installed according to http://www.htpc-forum.de/forum/index.php?act=ST&f=12&t=2238&st=30#entry15053
# optional: FireFly's marks2bytepos.pl from http://www.vdr-portal.de/board/thread.php?postid=406015#post406015
#
# ProjectX may be used be used as demultiplexer instead of vdrsync
# Complete set of audio streams will be transferred to DVD
# Parameters parsed from "D " line of info.vdr for the respective recording:
# "||Widescreen" enforces 16:9
# "||Zweikanalton LanguageLeft/LanguageRight" splits German variant of dual-language audio channels (transmitted as stereo) into separate mono streams

# Length in minutes of each chapter when DVD without menus is created
CHAPTER_LEN="5"

# Use cut function (yes|no) of vdrsync or ProjectX
USE_CUT="no"

# Use "tcrequant" (yes|no) or plain "requant" command
USE_TCREQUANT="yes"

# Use "tcmplex" (yes|no) or "mplex" command
USE_TCMPLEX="no"

# read user customization if any, otherwise use default values
BURNSETUPCONF="/etc/vdr/plugins/burn-ten/vdrburnscript.conf"
if [ -f "$BURNSETUPCONF" ]; then
    # we found a file, we trust the user :-)
    source $BURNSETUPCONF
else
    echo "To keep settings between releases, customize $0 in $BURNSETUPCONF"
fi

# Any overrides that should take precedence over the config file... place here:

# Burn the ISO on the fly
BURN_ON_THE_FLY="no"

# Start Command with nice ? If not wished then set NICE=""
NICE="nice -n 19"

# Use ProjectX as 'headless' Java (yes|no) rather than vdrsync.pl
USE_PROJECTX="yes"

# when script is called out of $PATH then add directory of script to $PATH
# there may be other needed programs in this directory
export PATH=$PATH:$(dirname $0)

logger -s "<$*>"

IsExecutable() {
    if type "$1" >/dev/null 2>&1; then
        return 0
    fi
    return 1
}

DetectTcrequant() {
    if IsExecutable tcrequant; then
        USE_TCREQUANT=yes
    else
        if [ "$USE_TCREQUANT" != "yes" ]; then
            logger "Unable to find valid requant program."
            exit 1
        fi
        DetectRequant
    fi
}

DetectRequant() {
    if IsExecutable requant; then
        USE_TCREQUANT=no
    else
        if [ "$USE_TCREQUANT" == "yes" ]; then
            logger "Unable to find valid requant program."
            exit 1
        fi
        DetectTcrequant
    fi
}

DetectRequanter() {
    if [ "$USE_TCREQUANT" == "yes" ]; then
        DetectTcrequant
    else
        DetectRequant
    fi
}

DetectTcmplex() {
    if IsExecutable tcmplex-panteltje; then
        TCMPLEX=tcmplex-panteltje
        USE_TCMPLEX=yes
    elif IsExecutable tcmplex; then
        TCMPLEX=tcmplex
        USE_TCMPLEX=yes
    else
        # check if we already are the fallback
        if [ "$USE_TCMPLEX" != "yes" ]; then
            logger "Unable to find valid mplex program."
            exit 1
        fi
        DetectMplex
    fi
}

DetectMplex() {
    if IsExecutable mplex; then
        TCMPLEX=mplex
        USE_TCMPLEX=no
    else
        # check if we already are the fallback
        if [ "$USE_TCMPLEX" == "yes" ]; then
            logger "Unable to find valid mplex program."
            exit 1
        fi
        DetectTcmplex
    fi
}

DetectMplexer() {
    if [ "$USE_TCMPLEX" == "yes" ]; then
        DetectTcmplex
    else
        DetectMplex
    fi
}

Png2Yuv() {
    if IsExecutable y4mscaler; then
        convert "$1" pnm:- |
            ppmtoy4m -n 1 -F25:1 -A 59:54 -I t -L -r -v 0 |
            y4mscaler -O chromass=420_MPEG2
    elif IsExecutable png2yuv; then
        png2yuv -n1 -f25 -It -L1 -v0 -j "$1"
    else
        convert "$1" pnm:- |
            ppmtoy4m -n 1 -F25:1 -A 59:54 -I t -L -r -v 0
        logger "Unable to find valid png to yuv converter program - trying to work anyway"
    fi
}

PXDemux() {
   PX_JAR="/usr/local/src/ProjectX_Source_0.90.4/ProjectX.jar"
   PX_INI="/etc/vdr/plugins/burn-ten/ProjectX.ini" # defaults for the burn plugin
   
   if [ -e $PX_INI ]; then
      cat $PX_INI > $1/ProjectX.ini
   fi
   logger -s "Audio split setup for $2:"
   # echo "VideoPanel.clearCdf=1" >> $1/ProjectX.ini # Zoran fix cf. http://www.dvdboard.de/FAQ/index.php?sid=115297&lang=de&action=artikel&cat=10&id=152&artlang=de
   echo "ExternPanel.renameAudio=1" >> $1/ProjectX.ini # turn anything but .ac3 into .mpa
   if [ -e $2/info.vdr ]; then
      DESCR=$(grep "^D .*Zweikanalton " $2/info.vdr)
      if [ 0 == $? ]; then
         L_mpa=$(echo $DESCR|sed 's/^D .*Zweikanalton \(.*\)\/.*/\1/g')
         R_mpa=$(echo $DESCR|sed 's/^D .*Zweikanalton .*\/\(.*\)/\1/g')
         logger -s "Zweikanalton "$L_mpa:$R_mpa
         echo "AudioPanel.loslessMpaConversionMode=4" >> $1/ProjectX.ini
      else
         logger -s "Stereo"
      fi
      WS=$(grep "^D .*Widescreen" $2/info.vdr)
      if [ "$WS" != "" ]; then
         logger -s "Widescreen aspect ratio 16:9"
         echo "VideoPanel.ChangeAspectRatio=3" >> $1/ProjectX.ini
      else
         logger -s "Original aspect ratio"
         # VideoPanel.ChangeAspectRatio=2 to enforce 4:3
      fi
   else
      logger -s "Missing $2/info.vdr"
   fi
   
   logger -s $(cat $1/ProjectX.ini)

   if [ "$USE_CUT" == "yes" ]; then
       CUTCMD="-cut $1/px.cut"
       /usr/bin/marks2bytepos.pl $2 >$1/px.cut
       logger -s "Cutmarks at byte $(cat $1/px.cut)"
   fi

   # To prevent issues with special character conversion in Java, we avoid the actual recording path (which may contain äöüÄÖÜß) by passing only a simple link (LordJaxom requests that this be set from /tmp/.vdr* rather than from /video)
   test -e "$1/convert" && rm "$1/convert"
   ln -s "$2" "$1/convert"
   
	logger -s "$1/convert->$2"

   ExecCmd /opt/blackdown-jdk-1.4.1/bin/java -Djava.awt.headless=true -jar $PX_JAR -ini $1/ProjectX.ini $CUTCMD -demux -out "$1" -name "vdrsync" $(ls $1/convert/[0-9][0-9][0-9].vdr)
}

ExecCmd() {
    logger -s "Starting <$NICE $*>"
    $NICE "$@"
}

CheckCmd() {
    if IsExecutable "$1"; then
        echo "Unable to find '$1'."
        return 1
    fi
    return 0
}

# debug script execution
#set -x

DetectMplexer
DetectRequanter

# Sync Syntax: TempDir Number FileName
case "${1}" in
    SYNC)
        if [ "$USE_CUT" == "yes" ]; then
           CUTCMD="-cut"
        fi
        if [ "$USE_PROJECTX" == "yes" ]; then
           PXDemux "$2/VDRSYNC.$3" "$4"	
        else
           ExecCmd vdrsync.pl $CUTCMD -o "$2/VDRSYNC.$3" "$4"
        fi   

        ;;

    # Requant Syntax: TempDir Number Filename Faktor
    REQUANT)
        if [ "$USE_TCREQUANT" == "yes" ]; then
            ExecCmd tcrequant -f "$5" -i "$4" -o "$2/VDRSYNC.$3/requant.mpv"
        else
            ExecCmd requant "$5" < "$4" > "$2/VDRSYNC.$3/requant.mpv"
        fi
        mv "$2/VDRSYNC.$3/requant.mpv" "$2/VDRSYNC.$3/vdrsync.mpv" 
        ;;

    # Mplex Syntax: TempDir FileName1 FileName2 FileName3
    MPLEX)
        if [ "$USE_TCMPLEX" == "yes" ]; then
            if [ "$5" != "" ]; then
                ExecCmd $TCMPLEX -i "$3" -p "$4" -s "$5" -m d -o "$2/movie.mpg"
            else
                ExecCmd $TCMPLEX -i "$3" -p "$4" -m d -o "$2/movie.mpg"
            fi
        else
            ExecCmd mplex -f 8 -vbr -v 1 -o "$2/movie.mpg" "$3" $(ls $2/*.mpa -S 2>/dev/null) $(ls $2/*.ac3 -S 2>/dev/null)
#            if [ "$5" != "" ]; then
#                ExecCmd mplex -f 8 -vbr -v 1 -o "$2/movie.mpg" "$3" "$4" "$5"
#            else
#                ExecCmd mplex -f 8 -vbr -v 1 -o "$2/movie.mpg" "$3" "$4"
#            fi
        fi
        ;;

    MKMENU)
        if [ "$USE_TCMPLEX" == "yes" ]; then
            Png2Yuv "$2/menu-bg-$3.png" |
                mpeg2enc -q 2 -a 2 -n p -f 8 -v 0 -o "$2/menu-bg-$3.m2v" &&
                $TCMPLEX -i "$2/menu-bg-$3.m2v" -p "$4/menu-silence.mp2" -m d -o /dev/stdout |
                spumux -v 2 "$2/menu-$3.xml" > "$2/menu-bg-$3.mpg"
        else
            Png2Yuv "$2/menu-bg-$3.png" |
                mpeg2enc -q 2 -a 2 -n p -f 8 -v 0 -o "$2/menu-bg-$3.m2v" &&
                mplex -f 8 -vbr -v 0 -o /dev/stdout "$2/menu-bg-$3.m2v" "$4/menu-silence.mp2" |
                spumux -v 2 "$2/menu-$3.xml" > "$2/menu-bg-$3.mpg"
        fi
        ;;

    # Author Syntax: TempDir or XML-File
    AUTHOR)
        if [ -d "$2" ]; then
            cd "$2"
            for i in $(seq 0 99) ; do
                if [ -f "VDRSYNC.$i/movie.mpg" ] ; then
                    echo "Found: VDRSYNC.$i"
                    CS="-c 0"
                    for j in $(seq $CHAPTER_LEN $CHAPTER_LEN 300) ; do
                        SH=$(($j / 60))
                        SM=$(($j % 60))
                        CS="$CS,$SH:$SM:0"
                    done
                    ExecCmd dvdauthor -o "$2/DVDAUTHOR" $CS -f "$2/VDRSYNC.$i/movie.mpg"
                    # ExecCmd rm "$2/VDRSYNC.$i/movie.mpg"
                else
                    break
                fi
            done
            ExecCmd dvdauthor -T -o "$2/DVDAUTHOR"
        else
            ExecCmd dvdauthor -x "$2"
            ExecCmd rm `echo $2|sed "s/dvd\.xml//"`VDRSYNC.*/movie.mpg
        fi
        ;;

    # AUTHORONLY Syntax: TempDir IsoDir JobTitle
    AUTHORONLY)
	mv -gf "$2/DVDAUTHOR" "$3/$4"
	chmod -R 0777 "$3/$4"
        ;;

    # MkIso Syntax: TempDir IsoDir JobTitle
    MKISO)
        ExecCmd mkisofs -V "${4:0:32}" -dvd-video "$2/DVDAUTHOR" > "$3/$4.iso"
        ;;

    # Burn Syntax: TempDir Device JobTitle
    BURN)
        ExecCmd growisofs -use-the-force-luke=tty -speed=2 -dvd-compat -Z "$3" -V "${4:0:32}" -dvd-video "$2/DVDAUTHOR"
        ;;

    # MkIso-Burn Syntax: TempDir Device IsoDir JobTitle FifoPath
    MKISO_BURN)
        if [ "BURN_ON_THE_FLY" = "yes" ] ; then
	   ExecCmd growisofs -use-the-force-luke=tty -speed=2 -dvd-compat -Z "$3=$6" | mkisofs -V "${5:0:32}" -dvd-video "$2/DVDAUTHOR" | tee "$4/$5.iso" > "$6"
	else
	   ExecCmd mkisofs -V "${5:0:32}" -dvd-video "$2/DVDAUTHOR" > "$4/$5.iso"
	   ExecCmd growisofs -use-the-force-luke=tty -speed=2 -Z "$3=$4/$5.iso"
	fi   
        ;;

    CHECK)
#        if [ "$2" != "$PLUGIN_VERSION" ]; then
#            echo "Invalid plugin version $2 != $PLUGIN_VERSION."
#            exit
#        fi  
        CheckCmd growisofs &&
        CheckCmd mkisofs &&
        CheckCmd dvdauthor &&
        CheckCmd png2yuv &&
        CheckCmd ppmtoy4m &&
        CheckCmd y4mscaler &&
        CheckCmd mpeg2enc &&
        CheckCmd spumux &&
        CheckCmd vdrsync.pl
        if [ "$?" -eq 0 ]; then
            if [ "$USE_TCMPLEX" == "yes" ]; then
                CheckCmd $TCMPLEX
            else
                CheckCmd mplex
            fi
            if [ "$?" -eq 0 ]; then
                echo "Ok"
            fi
        fi
        ;;
    *)
        echo "Illegal Parameter <$1>"
        ;;
esac
