#!/bin/sh
# Version: 0.2.0
# Author: Dimitrios Dimitrakos mail@dimitrios.de
# $Id: vdr2divx.sh,v 1.27 2005/10/08 21:07:07 dimi Exp $

RM=rm
#RM=echo
vco_user=`id -n -u`
homedir=`cat /etc/passwd|grep "^${vco_user}:"|cut -f6 -d ':'`
. $homedir/.vdrconvert/vdrconvert.env
[ -r $homedir/.vdrconvert/vdr2divx.env ] && . $homedir/.vdrconvert/vdr2divx.env

trap do_clean SIGINT SIGQUIT SIGTERM 

PIDFILE="$VCORUNDIR/`basename ${0}.pid`"
echo "$$" >> $PIDFILE

do_clean() {
	if [ -f $PIDFILE ]
	then
		TEMPPID=$LTEMPDIR/`basename $PIDFILE`.$$
		mv $PIDFILE $TEMPPID
		status=$?
		if [ $status -eq 0 ]
		then
			[ `cat $TEMPPID|wc -l` -gt 0 ] && cat $TEMPPID|grep -v $$ > $PIDFILE 
		fi
		[ -f $TEMPPID ] && $RM $TEMPPID
	fi
	exit
}

Exit() {
	do_clean
}

[ "$DIVX_DEBUG" = "yes" ] && set -x 

# Default werte setzen
# Verzeichnisse / Dateinamen
[ -z "$DIVX_DESTDIR" ] 	 && DIVX_DESTDIR=$DESTDIR/divx
[ -z "$DIVXTYPE" ] 	 && DIVXTYPE=lavc
[ -z "$DIVX_SUFFIX" ] 	 && DIVX_SUFFIX=avi
# Optionen
[ -z "$DIVXCCHOPT" ] 	 && DIVXCCHOPT="-cache 32768" 
[ -z "$DIVXENCOPT" ] 	 && DIVXENCOPT="" # Sonstige optionen
[ -z "$DIVXTCMODE" ] 	 && DIVXTCMODE=s
[ -z "$DIVXVLAVCCODEC" ] && DIVXVLAVCCODEC=mpeg4
[ -z "$DIVXQUALITY" ] 	 && DIVXQUALITY=5
[ -z "$DIVXMP3_BITR" ] 	 && DIVXMP3_BITR="192"
[ -z "$DIVXMP3_OPTS" ] 	 && DIVXMP3_OPTS="-b $DIVXMP3_BITR -h"
[ -z "$DIVXSWS" ] 	 && DIVXSWS=2
[ -z "$DIVXCDLEN" ] 	 && DIVXCDLEN=750
[ -z "$DIVXMAXBITR" ] 	 && DIVXMAXBITR=1480 
[ -z "$DIVXMINBITR" ] 	 && DIVXMINBITR=0
[ -z "$DIVX_MAXLEN" ]    && DIVX_MAXLEN=90
[ -z "$DIVX_MAXDIV" ]    && DIVX_MAXDIV=25
# Schalter
[ -z "$DIVXFAKTOR" ]	 && DIVXFAKTOR=2
[ -z "$DIVXAUTOCROP" ]	 && DIVXAUTOCROP=no
[ -z "$DIVX_SPLIT" ]	 && DIVX_SPLIT=no
[ -z "$DIVX_RESDIV" ]	 && DIVX_RESDIV=no
[ -z "$DIVX_USELAME" ]   && DIVX_USELAME=no
[ -z "$DIVX_USE_MPG123" ] && DIVX_USE_MPG123=no
[ -z "$DIVX_ACODEC" ]    && DIVX_ACODEC=mp3lame
[ -z "$DIVXUSESTREAMS" ] && DIVXUSESTREAMS="apid1"
[ -z "$DIVX_FIRST_AVAILABLE_STREAM_ONLY" ] && DIVX_FIRST_AVAILABLE_STREAM_ONLY="no"
# scale ( no, yes, auto, user )
[ -z "$DIVX_SCALE" ]        && DIVX_SCALE="auto"
[ -z "$DIVXALLOWEDWIDTH" ]  && DIVXALLOWEDWIDTH="720 704 352 480"

# Check ob alle Programme ausführbar sind
# TODO

NewJobs=$1
JOBFIL=$2
LOGFILE=$3
LTEMPDIR=${TEMPDIR}/${JOBFIL}

. $VDRCONVERTDIR/bin/helperfunctions.sh

[ -d $DIVX_DESTDIR ] || mkdir -p $DIVX_DESTDIR
[ -d $LTEMPDIR ] || mkdir -p $LTEMPDIR
[ -z "$DIVX_TITLEDATE" ] && DIVX_TITLEDATE=$CONV_TITLEDATE

if [ -w ${LTEMPDIR} -a -w ${DIVX_DESTDIR} ]
then
	printf "`date +"%d-%m-%2Y %T"` : Session %s begin\n" "\$Id: vdr2divx.sh,v 1.27 2005/10/08 21:07:07 dimi Exp $"

	let NLLINES=`cat $VCOQUEUEDIR/${JOBFIL}|nl|wc -l|awk '{ print $1 }'`
	let ALINES=`cat $VCOQUEUEDIR/${JOBFIL}|wc -l|awk '{ print $1 }'`

	if [ $ALINES -ge 1 ]
	then
		TEMPJOBFILE=/$LTEMPDIR/${JOBFIL}.u.$$
		> $TEMPJOBFILE
		printf "%s\n" "`cat $VCOQUEUEDIR/${JOBFIL}|head -n 1`" > $NewJobs
		let LINE=2
		while [ $LINE -le $ALINES ]
		do
			printf "%s\n" "`cat $VCOQUEUEDIR/${JOBFIL}|head -n $LINE|tail -n 1`" >> $TEMPJOBFILE
			let LINE=LINE+1
		done
		[ $NLLINES -gt $ALINES ] && printf "%s" "`cat $VCOQUEUEDIR/${JOBFIL}|tail -n 1`" >> $TEMPJOBFILE
		cp $TEMPJOBFILE $VCOQUEUEDIR/${JOBFIL} && $RM $TEMPJOBFILE

		while [ `cat $NewJobs|grep ^${VDRROOT}|wc -l` -gt 0 ]
		do
			CMDLIN=`head -n 1 $NewJobs`   # Job auslesen
			let Number=1
			echo "`date` : Start conversion for $CMDLIN"
			for i in $CMDLIN
			do
				[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "`echo $0|xargs basename` start for $i" >/dev/null 2>&1
				[ -r $i/vdrconvert.env ] && . $i/vdrconvert.env
				logger "$0 : start for $i"
				pxfiles=""
				[ "$DIVX_SPLIT" = "no" ] && p=${i}/ || p=`echo $i/[0-9][0-9[0-9]*.vdr`
				for j in $p
				do
					printf "\t`date` : Begin conversion %s\n" "$j"

					UniqueDir[Number]=`mktemp -d ${LTEMPDIR}/VDRSYNC.XXXXXX`
					status=$?
					if [ $status -eq 0 ]
					then
						mkdir -p ${UniqueDir[Number]} 
	
						r=`echo ${VDRROOT}|sed 's/\// /g'|wc -w`
						spalten=`echo $i|sed 's/\// /g'|wc -w`
						Record=`echo $i|sed 's/\%//g'|cut -f $spalten -d '/'`
						[ $[$r+2] -lt $[$spalten-1] ] && SubTitel=`echo $i|sed 's/\%//g'|cut -f $[$r+2]-$[$spalten-1] -d '/'` || SubTitel=""
						Datum=`basename $i|cut -f1 -d'.'`
						if [ -z "$SubTitel" ]
						then
							[ "$DIVX_TITLEDATE" = "yes" ] && Titel=${Datum}_${Record} ||Titel=${Record}
						else
							[ "$DIVX_TITLEDATE" = "yes" ] && Titel=${SubTitel}/${Datum}_${Record} || Titel=${SubTitel}/${Record}
						fi
						[ ! -d ${UniqueDir[Number]}/${SubTitel} ] && mkdir -p ${UniqueDir[Number]}/${SubTitel}
						[ ! -d ${DIVX_DESTDIR}/${SubTitel} ] && mkdir -p ${DIVX_DESTDIR}/${SubTitel}
						cd ${UniqueDir[Number]} # Temporaere Dateien sollen hier erstellt werden
						LOG[Number]=${UniqueDir[Number]}/sync.log
						for demux_prg in $DEMUXER
						do
	 
							pxfiles=""
							[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "Try to demux with $demux_prg" >/dev/null 2>&1
							printf "\t`date +"%T"`: Start demux with %s\n" ${demux_prg}
							case `basename $demux_prg` in
								vdrsync)
									printf "`date +"%T"`\t: Start ${VDRSYNC}\n"
									nice -n $PRIO $VDRSYNC -o ${UniqueDir[Number]} $j > ${LOG[Number]} 2>&1
									status=$?
									[ "$DIVX_DEBUG" = "yes" ] && cat ${LOG[Number]} >> $LOGFILE
									if [ $status -ne 0 ]
									then
										echo "ERROR : $VDRSYNC  rc=$status"
										# Cleaning
										cd $VDRCONVERTDIR
										$RM -rf ${UniqueDir[Number]}
										Exit 
									fi
									;;
								vdrsync2)
									printf "`date +"%T"`\t: Start ${VDRSYNC2}\n"
									nice -n $PRIO $VDRSYNC2 -basename 001 -script-output $VDRSYNC_OPTS -o ${UniqueDir[Number]} $j > ${LOG[Number]} 2>&1
									status=$?
									[ "$DIVX_DEBUG" = "yes" ] && cat ${LOG[Number]} >> $LOGFILE
									if [ $status -ne 0 ]
									then
										echo "ERROR : $VDRSYNC2  rc=$status"
										# Cleaning
										cd $VDRCONVERTDIR
										$RM -rf ${UniqueDir[Number]}
										Exit 
									fi
									;;
								vdrsync3)
									printf "`date +"%T"`\t: Start ${VDRSYNC3}\n"
									nice -n $PRIO $VDRSYNC3 -basename 001 -script-output $VDRSYNC_OPTS -o ${UniqueDir[Number]} $j > ${LOG[Number]} 2>&1
									status=$?
									[ "$DIVX_DEBUG" = "yes" ] && cat ${LOG[Number]} >> $LOGFILE
									if [ $status -ne 0 ]
									then
										echo "ERROR : $VDRSYNC3  rc=$status"
										# Cleaning
										cd $VDRCONVERTDIR
										$RM -rf ${UniqueDir[Number]}
										Exit 
									fi
									;;
								px)
									# Virtuellen X-Server starten
									#$XVFB :1 >/dev/null 2>&1 &
									export DISPLAY=:${XVFB_ID}.0
   	 
									[ -d $j ] && vdrfiles=$j/[0-9][0-9][0-9].vdr || vdrfiles=$j
									for l in $vdrfiles
									do
										# fix -n 001 problem
										let len=`$LS -Ls $l|awk '{print $1}'`
										if [ $len -gt 1 ]
										then
											if [ -z "$pxfiles" -a "`echo $l|xargs basename`" != "001.vdr" ]
											then
												ln -s $l ${UniqueDir[Number]}/001.vdr
												l=${UniqueDir[Number]}/001.vdr
											fi
											pxfiles="${pxfiles} ${l}"
										fi
									done
   	 
									# Project X starten
									nice -n $PRIO $JAVA -jar $PX $PXINIOPT $PXINI $PXOUTOPT ${UniqueDir[Number]} $pxfiles > ${LOG[Number]} 2>&1
									status=$?
									[ "$DIVX_DEBUG" = "yes" ] && cat ${LOG[Number]} >> $LOGFILE
									# Umsetzen mpeg spuren
									let z=0
									for i in `cat ${LOG[Number]}|grep "found PES-ID 0xC"|awk '{print $4}'`
									do
			    						    let z=z+1
			    						    str=`cat ${LOG[Number]}|tr -d "\r"|grep ^Audio|grep -v "PTS"|grep "(mp2)"|awk '{print $8}'|head -n $z|tail -n 1|xargs basename`
			    						    strn=`echo $i|cut -f2 -d 'x'|awk '{ print tolower($1)'}`
			    						    mv ${UniqueDir[Number]}/${str}  ${UniqueDir[Number]}/${strn}.mpa
									done
									# Virtuellen X-Server beenden
									#$KILL -15 $XVFB >/dev/null
									if [ $status -ne 0 ]
									then
										echo "ERROR : $PX  rc=$status"
										# Cleaning
										cd $VDRCONVERTDIR
										$RM -rf ${UniqueDir[Number]}
										Exit 
									fi
									;;
								pva)
									# VDR Files zusammenführen
									[ -d $j ] && vdrfiles=$j/[0-9][0-9][0-9].vdr || vdrfiles=$j
									cat $vdrfiles >> ${UniqueDir[Number]}/001.vdr
									[ -f $i/marks.vdr ] && cp $i/marks.vdr ${UniqueDir[Number]}
									[ -f $i/index.vdr ] && cp $i/index.vdr ${UniqueDir[Number]}
									# Winpfad erstellen
									WINEPFAD=`echo ${UniqueDir[Number]}|sed 's/\//\\\/g'`
									WINEFILE="demux \"Z:${WINEPFAD}\\001.vdr\" \"Z:${WINEPFAD}\\001.mpv\" \"Z:${WINEPFAD}\\001.mpa\""
									## Jobfile anlegen
									echo "offeryn pvas job v000001" > ${UniqueDir[Number]}/demux.ajb
									echo "\$JOB" >> ${UniqueDir[Number]}/demux.ajb
									echo "$WINEFILE" >> ${UniqueDir[Number]}/demux.ajb
									cat $VDRCONVERTDIR/share/vdrconvert/pva/demux.template >> ${UniqueDir[Number]}/demux.ajb
   	 
									#$XVFB :1 >/dev/null 2>&1 &
									export DISPLAY=:${XVFB_ID}.0
   	 
									nice -n $PRIO $WINE $VDRCONVERTDIR/share/vdrconvert/pva/cPVAS.exe ${UniqueDir[Number]}/demux.ajb > ${LOG[Number]} 2>&1
									status=$?
									[ "$DIVX_DEBUG" = "yes" ] && cat ${LOG[Number]} >> $LOGFILE
									[ -f "${UniqueDir[Number]}/001.mpv.ac3" ] && mv ${UniqueDir[Number]}/001.mpv.ac3 ${UniqueDir[Number]}/001.ac3
	
									#$KILL -15 $XVFB >/dev/null
									;;
								*)
									echo "No support for Demuxer $demux_prg"
									logger "ERROR : $0 No support for Demuxer $demux_prg"
									[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "`echo $0|xargs basename` No support for Demuxer $demux_prg" >/dev/null 2>&1
									;;
							esac
							# Check audio
							let NAudio=0
							if [ $status -eq 0 ]
							then
								NAudio=`$LS -l ${UniqueDir[Number]}/*.mpa ${UniqueDir[Number]}/*.ac3 2>/dev/null|wc -l|awk '{print $1}'`
								[ $NAudio -eq 0 ] && status=1
							fi
							if [ $status -eq 0 ]
							then
								TDEMUXER[Number]=$demux_prg
								break
							fi
						done
						AC3OPT=""
						NEWSTREAMS[Number]=""
						if [ $status -eq 0 ]
						then
							let ABITR=0
							let field=0
							USESTREAMS=$(find_streams ${TDEMUXER[Number]} ${UniqueDir[Number]} $DIVXUSESTREAMS)
							if [ ! -z "$USESTREAMS" ] 
							then
								for k in $USESTREAMS
								do
									for ii in `$LS ${UniqueDir[Number]}/*.ac3 ${UniqueDir[Number]}/*.mpa 2>/dev/null`
									do
										[ "${UniqueDir[Number]}/$k" = "$ii" ] && NEWSTREAMS[Number]="${NEWSTREAMS[Number]} $k"
									done
								done
							fi

							# Use the first available audio pid only
echo "All Streams = ${NEWSTREAMS[Number]}"
							[ "$DIVX_FIRST_AVAILABLE_STREAM_ONLY" = "yes" ] && NEWSTREAMS[Number]=$(echo ${NEWSTREAMS[Number]}|cut -f1 -d ' ')
echo "Used Streams = ${NEWSTREAMS[Number]}"

							for k in ${NEWSTREAMS[Number]}
							do
								if [ -f ${UniqueDir[Number]}/$k ]
								then
									id=`echo $k|cut -f1 -d '.'`
									ids=`echo $k|cut -f2 -d '.'`
									[ "$ids" = "mpa" ] && ids=mp3
									if [ $field -lt 2 ] 
									then
										MPLEXAUDIO=$MPLEXAUDIO`[ $field -eq 0 ] && echo "-p ${UniqueDir[Number]}/${id}.${ids} " || echo "-s ${UniqueDir[Number]}/${id}.${ids} "`
									fi
									if [ "${ids}" = "ac3" ] 
									then
										AC3OPT="-aid 128 -oac copy" 
										let ABITR=ABITR+448
										DIVX_USELAME="yes"
									else
										if [ "$DIVX_USELAME" != "no" -o "$AC3OPT" = "-aid 128 -oac copy" ]
										then
											[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "`echo $0|xargs basename` start LAME" >/dev/null 2>&1
											printf "\t`date +"%T"`: Start LAME for %s.\n\t\t %s\n" "$k" "$MPLEXAUDIO"
											echo "--mp2input $DIVXMP3_OPTS ${UniqueDir[Number]}/$k ${UniqueDir[Number]}/${id}.${ids}"|xargs nice -n ${PRIO} $LAME > /dev/null 2>&1
											[ "$AC3OPT" != "-aid 128 -oac copy" ] && AC3OPT="-oac copy"
										elif [ "$DIVX_USE_MPG123" != "no" ]
										then
											[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "start mpg123|lame for $k" > /dev/null 2>&1
											printf "\t`date +"%T"`: Start mpg123 | LAME for %s in %s with %s\n" "$k" "${Titel}" "$MP3_OPTS"
											nice -n $PRIO mpg123 -s -w - ${UniqueDir[Number]}/$k | $LAME $MP3_OPTS - ${UniqueDir[Number]}/${id}.${ids} > /dev/null 2>&1
											AC3OPT="-oac copy"
											[ -f out.$$.wav ] && $RM -f out.$$.wav
										else
											mv ${UniqueDir[Number]}/$k ${UniqueDir[Number]}/${id}.${ids}
											if [ "$DIVX_ACODEC" = "mp3lame" ]
											then
												DIVX_ACODEC_OPT="-lameopts  cbr:br=$DIVXMP3_BITR"
											fi
											[ -z "$AC3OPT" ] && AC3OPT="-oac $DIVX_ACODEC $DIVX_ACODEC_OPT"
										fi
										let ABITR=ABITR+DIVXMP3_BITR
									fi
									#break
									let field=field+1
								fi
							done
	
							if [  -z "$MPLEXAUDIO" ]
							then
								echo "No audio found for streams <$DIVXUSESTREAMS>"
								logger "No audio found for streams <$DIVXUSESTREAMS>"
								[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "`echo $0|xargs basename` No audio found for streams <$DIVXUSESTREAMS>" >/dev/null 2>&1
							else
		
								[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "`echo $0|xargs basename` start TCMPLEX" >/dev/null 2>&1
								printf "\t`date +"%T"`: Start TCMPLEX for %s.\n\t\t %s\n" "${Titel}" "$MPLEXAUDIO"
								nice -n ${PRIO} $TCMPLEX -i ${UniqueDir[Number]}/*.mpv $MPLEXAUDIO -m $DIVXTCMODE -o ${UniqueDir[Number]}/${Titel}.mpg >/dev/null 2>&1
								[ "${TDEMUXER[Number]}" = "pva" ] && $RM ${UniqueDir[Number]}/001.vdr
								$RM -rf $VideoStream ${UniqueDir[Number]}/*.ac3 ${UniqueDir[Number]}/*.mpa $transfile.m2v 2>/dev/null
								# Bitrate berechnen
								# Erst Laenge in MB ( nur Info )
								case `basename ${TDEMUXER[Number]}` in
									vdrsync)
										let sec=`cat ${LOG[Number]}|grep "frames written for stream"|tail -n 1|cut -f2 -d '('|cut -f1 -d')'|awk '{print $1}'|cut -f1 -d'.'`
										let min=$((sec/60))
										;;
									vdrsync2)
										let sec=`cat ${LOG[Number]}|grep "Total_time"|tail -n 1|cut -f2 -d '='|cut -f1 -d'.'`
										let min=$((sec/60))
										;;
									vdrsync3)
										let sec=`cat ${LOG[Number]}|grep "Total_time"|tail -n 1|cut -f2 -d '='|cut -f1 -d'.'`
										let min=$((sec/60))
										;;
									px)
										let hours=`strings ${LOG[Number]}|grep ".Video (m2v):"|awk '{print $5}'|cut -f1 -d':'`
										let lmin=`strings ${LOG[Number]}|grep ".Video (m2v):"|awk '{print $5}'|cut -f2 -d':'`
										let fsec=`strings ${LOG[Number]}|grep ".Video (m2v):"|awk '{print $5}'|cut -f3 -d':'|cut -f1 -d'.'`
										let lframes=`strings ${LOG[Number]}|grep ".Video (m2v):"|awk '{print $5}'|cut -f3 -d':'|cut -f2 -d'.'`
										let frames=`strings ${LOG[Number]}|grep ".Video (m2v):"|awk '{print $3}'`
										let min=$((hours*60+lmin))
										let sec=$(((hours*60)+(min*60)+fsec))
										;;
									pva)
										let hours=`strings ${LOG[Number]}|grep "Video 1:"|cut -f2 -d ','|cut -f1 -d ':'|awk '{print $1}'|xargs expr 0 + `
										let min=`strings ${LOG[Number]}|grep "Video 1:"|cut -f2 -d ','|cut -f2 -d ':'|awk '{print $1}'|xargs expr 0 + `
										let fsec=`strings ${LOG[Number]}|grep "Video 1:"|cut -f2 -d ','|cut -f3 -d ':'|awk '{print $1}'|cut -f1 -d'.'|xargs expr 0 + `
										let sec=$(((hours*60)+(min*60)+fsec))
										;;
									*)
										echo "ERROR : No support for Demuxer ${TDEMUXER[Number]}"
										;;
								esac
	
								lmovie=`$LS -s --block-size=1024k ${UniqueDir[Number]}/${Titel}.mpg|awk '{print $1}'`
								[ $min -eq 0 ] && let min=1
								[ "$DIVX_DEBUG" = "yes" ] && echo "File ${Titel} hat eine Länge von $min Minuten bei $lmovie MB"
								if [ "$DIVX_USEFAKTOR" != "no" ]
								then
									# Bitrate kann berechnet werden
									[ $DIVXCDLEN -gt $((lmovie/DIVXFAKTOR)) ] && LEN=$((lmovie/DIVXFAKTOR)) || LEN=$DIVXCDLEN
									[ $LEN -le 0 ] && LEN=1
									VBITRT=$(((((LEN*1024*8/1000)*1024)-(ABITR*min*60))/(min*60)))
									[ $DIVXMINBITR -gt 0 -a $VBITRT -lt $DIVXMINBITR ] && VBITRT=$DIVXMINBITR
									[ $DIVXMAXBITR -gt 0 -a $VBITRT -gt $DIVXMAXBITR ] && VBITRT=$DIVXMAXBITR
									[ "$DIVX_DEBUG" = "yes" ] && echo "Berechnete Bitrate für eine Länge $LEN = $VBITRT"
								else
									# Bitrate ohne Faktor für Brennen
									if [ $((ABITR-1)) -gt 0 -a $DIVXMP3_BITR -le $((ABITR-1)) ]
									then
										[ "$DIVX_DEBUG" = "yes" ] && echo "keine Audiobitrate, setze $DIVXMP3_BITR kb/s"
										ABITR=$DIVXMP3_BITR
									fi
		 		 
									VBITRT=$((((DIVXCDLEN*1000)/sec)*8))
									VBICD=$((((DIVXCDLEN*1000)/($DIVX_MAXLEN*60))*8))
									DIVX_LMIN=$((DIVX_MAXLEN-DIVX_MAXDIV))
									DIVX_LMAX=$((DIVX_MAXLEN+DIVX_MAXDIV))
		
									if [ $((DIVX_LMIN-1)) -gt 0 -a $min -le $((DIVX_LMIN-1)) ]
									then
										[ "$DIVX_DEBUG" = "yes" ] && echo "Das Video($min min) ist kleiner als das CD-Minimum($DIVX_LMIN min)"
										[ "$DIVX_DEBUG" = "yes" ] && echo "berechne Bitrate für $DIVX_MAXLEN min"
										VBITRT=$(((VBITRT/DIVX_MAXLEN)*min))
									else
										if [ $min -gt 0 -a $((DIVX_LMAX+1)) -le $min ]
										then
											[ "$DIVX_DEBUG" = "yes" ] && echo "Das Video($min min) ist größer als das CD-Maximum($DIVX_LMAX min)"
											[ "$DIVX_DEBUG" = "yes" ] && echo "berechne Bitrate für 2 CD's"
											DIVXCDLEN=$(((DIVXCDLEN*2)-50))
											DIVX_MAXLEN=$((DIVX_MAXLEN*2))
											VBITRT=$((((DIVXCDLEN*1000)/sec)*8))
											VBICD=$((((DIVXCDLEN*1000)/($DIVX_MAXLEN*60))*8))
											DIVX_LMIN=$((DIVX_MAXLEN-DIVX_MAXDIV))
											DIVX_LMAX=$((DIVX_MAXLEN+DIVX_MAXDIV))
										else
											[ "$DIVX_DEBUG" = "yes" ] && echo "Das Video($min min) ist im Toleranzbereich von $DIVX_LMIN min bis $DIVX_LMAX min)"
										fi
									fi
									FILELEN=$(((VBITRT*sec)/1000/8))
									if [ $DIVXMINBITR -gt 0 -a $VBITRT -le $DIVXMINBITR ]
									then
										[ "$DIVX_DEBUG" = "yes" ] && echo "ERROR : Berechnete bitrate kleiner als Minimal festgelegte $DIVXMINBITR im environment"
										cd -
										$RM -rf ${UniqueDir[Number]}
										Exit
									fi
									VBITRT=$((VBITRT-ABITR))		
				
									if [ "$DIVX_DEBUG" = "yes" ] 
									then
										echo
										echo "DIVXCDLEN   = $DIVXCDLEN MB"
										echo "FILELEN     = $FILELEN MB"
										echo
										echo "VIDEO_LEN   = $min min"
										echo "DIVX_MIN    = $DIVX_LMIN min"
										echo "DIVX_LEN    = $DIVX_MAXLEN min"
										echo "DIVX_MAX    = $DIVX_LMAX min"
										echo "DIVX_MAXDIV = $DIVX_MAXDIV min"
										echo "DIVXMINBITR = $DIVXMINBITR kb/s"
										echo
										echo "BitRate     = $((VBITRT+ABITR)) kb/s"
										echo "BitRate AUD = $ABITR kb/s"
										echo "BitRate VID = $VBITRT kb/s"
										echo "BitRate CD  = $VBICD kb/s"
										echo
									fi
								fi
		
	
								# Check if need scale
								if [ "$DIVX_SCALE" = "user" ]
								then
									res=`mencoder -frames 0 ${UniqueDir[Number]}/${Titel}.mpg|grep "VIDEO:"|cut -f1 -d 'x'|awk '{print $3}'`
									echo "Resolution ${UniqueDir[Number]}/${Titel}.mpg = $res"
									let need_scale=1
									for width in $DIVXALLOWEDWIDTH
									do
										[ "$res" = "$width" ] && need_scale=0
									done
								elif [ "$DIVX_SCALE" = "auto" ]
								then
									resx=`mencoder -frames 0 ${UniqueDir[Number]}/${Titel}.mpg|grep "VIDEO:"|cut -f1 -d 'x'|awk '{print $3}'`
									resy=`mencoder -frames 0 ${UniqueDir[Number]}/${Titel}.mpg|grep "VIDEO:"|cut -f2 -d 'x'|awk '{print $1}'`
									ASPECT=`$MENCODER -frames 0 ${UniqueDir[Number]}/${Titel}.mpg 2>/dev/null|grep aspect|cut -f1 -d ')'|awk '{print $5}'`
									if [ "$ASPECT" = "3" ]
									then
										X=$((resy*16/9))
										[ "$X" != "$resx" ] && let need_scale=1
									else
										X=$((resy*4/3))
										[ "$X" != "$resx" ] && let need_scale=1
									fi
								elif [ "$DIVX_SCALE" = "no" ]
								then
									let need_scale=0
								else
									let need_scale=1
								fi
				
	
								ASPECT=`$MENCODER -frames 0 ${UniqueDir[Number]}/${Titel}.mpg 2>/dev/null|grep aspect|cut -f1 -d ')'|awk '{print $5}'`
								if [ "$ASPECT" = "3" ] 
								then
									Y=`$MENCODER -frames 0 ${UniqueDir[Number]}/${Titel}.mpg 2>/dev/null|grep aspect|cut -f1 -d ')'|awk '{print $3}'|cut -f2 -d'x'`
									X=$((Y*16/9))
									[ $need_scale -eq 1 ] && ASPOPT="-vop scale=$X:$Y,lavcdeint -sws $DIVXSWS" || ASPOPT="-vop lavcdeint -sws $DIVXSWS"
								if [ "$DIVX_RESDIV" = "yes" -a "$DIVX_SCALE" != "no" ]
								then
									XX=`$MENCODER -frames 0 ${UniqueDir[Number]}/${Titel}.mpg 2>/dev/null|grep aspect|cut -f1 -d ')'|awk '{print $3}'|cut -f1 -d'x'`
									X=$((XX/2))
									Y=$(((X*9)/16))
									ASPOPT="-vop scale=$X:$Y,lavcdeint -sws $DIVXSWS"
								fi
								if [ "$DIVX_NORECALC" = "yes" -a $need_scale -eq 1 ]
								then
									X=`$MENCODER -frames 0 ${UniqueDir[Number]}/${Titel}.mpg 2>/dev/null|grep aspect|cut -f1 -d ')'|awk '{print $3}'|cut -f1 -d'x'`
									Y=$(((X*9)/16))
									ASPOPT="-vop scale=$X:$Y,lavcdeint -sws $DIVXSWS"
								fi
		
								UDIVXCROP=""
								let step=0
								let crop_ok=0
								if [ "$DIVXAUTOCROP" = "yes" ]
								then
									#for k in 00:01:10 00:02:00 00:03:00 00:05:00 00:10:00 00:15:00 00:20:00 00:25:00 00:30:00 00:35:00 00:40:00 00:45:00 01:00:00 01:15:00 01:30:00
									for k in 00:00:10 00:00:50 00:01:00 00:01:30 00:01:50 00:02:00
									do
										DIVXCROP[step]=""
										nice -n ${PRIO} $MENCODER -ss $k -frames 100 $DIVXENCOPT $AC3OPT $DIVXCCHOPT $ASPOPT \
											-vop cropdetect \
											-mc 0 \
											-vc mpeg12 \
											-ovc lavc \
											-lavcopts vcodec=$DIVXVLAVCCODEC:vhq:ildct:vqmin=2:vbitrate=$VBITRT \
											-o /dev/null \
											${UniqueDir[Number]}/${Titel}.mpg > ${UniqueDir[Number]}/crop.log
										status=$?
										[ "$DIVX_DEBUG" = "yes" ] && cat ${UniqueDir[Number]}/crop.log	
										if [ $status -eq 0 ]
										then
											DIVXCROP[step]=`cat ${UniqueDir[Number]}/crop.log|grep crop= |tail -n 1 | cut -f3 -d '('|sed 's/)//'|sed 's/-vop //'`
											[ ! -z "${DIVXCROP[step]}" ] && let step=step+1
										fi
									done
									if [ $step -ge 2 ]
									then
										until [ $step -eq 1 -o $crop_ok -eq 3 ] 
										do
											let crop_ok=0
											let ustep=step
										until [ $ustep -eq 1 -o $crop_ok -eq 3 ] 
										do
											if [ ! -z "${DIVXCROP[ustep]}" -a "${DIVXCROP[ustep]}" = "${DIVXCROP[ustep-1]}" ] 
											then
												let crop_ok=crop_ok+1
												UDIVXCROP=`cat ${UniqueDir[Number]}/crop.log|grep crop= |tail -n 1 | cut -f3 -d '('|sed 's/)//'|sed 's/-vop //'`
											fi
											let ustep=ustep-1
										done
										let step=step-1
									done
								fi
								if [ $crop_ok -eq 3 ]
								then
									X=`$MENCODER -frames 0 ${UniqueDir[Number]}/${Titel}.mpg 2>/dev/null|grep aspect|cut -f1 -d ')'|awk '{print $3}'|cut -f1 -d'x'`
									Y=`$MENCODER -frames 0 ${UniqueDir[Number]}/${Titel}.mpg 2>/dev/null|grep aspect|cut -f1 -d ')'|awk '{print $3}'|cut -f2 -d'x'`
									X=$((Y*16/9))
									CROPMIN=`echo ${UDIVXCROP}|cut -f 4 -d ':'`
									Y=$((Y-CROPMIN-CROPMIN))
									if [ "$DIVX_RESDIV" = "yes" ]
									then
									     Y=$((Y/2))
									     X=$((X/2))
									fi
									ASPOPT="-vop scale=$X:$Y,lavcdeint $UDIVXCROP -sws $DIVXSWS"
								fi
							fi
						else
							UDIVXCROP=""
							let step=0
							let crop_ok=0
		
							if [ "$DIVXAUTOCROP" = "yes" ]
							then
								#for k in 00:01:10 00:02:00 00:03:00 00:05:00 00:10:00 00:15:00 00:20:00 00:25:00 00:30:00 00:35:00 00:40:00 00:45:00 01:00:00 01:15:00 01:30:00
								for k in 00:00:10 00:00:50 00:01:00 00:01:30 00:01:50 00:02:00
								do
									DIVXCROP[step]=""
									nice -n ${PRIO} $MENCODER -ss $k -frames 100 $DIVXENCOPT $AC3OPT $DIVXCCHOPT $ASPOPT \
										-vop cropdetect \
										-mc 0 \
										-vc mpeg12 \
										-ovc lavc \
										-lavcopts vcodec=$DIVXVLAVCCODEC:vhq:ildct:vqmin=2:vbitrate=$VBITRT \
										-o /dev/null \
										${UniqueDir[Number]}/${Titel}.mpg > ${UniqueDir[Number]}/crop.log
									status=$?
									[ "$DIVX_DEBUG" = "yes" ] && cat ${UniqueDir[Number]}/crop.log	
									if [ $status -eq 0 ]
									then
										DIVXCROP[step]=`cat ${UniqueDir[Number]}/crop.log|grep crop= |tail -n 1 | cut -f3 -d '('|sed 's/)//'|sed 's/-vop //'`
										[ ! -z "${DIVXCROP[step]}" ] && let step=step+1
									fi
								done
								if [ $step -ge 2 ]
								then
									until [ $step -eq 1 -o $crop_ok -eq 3 ] 
									do
										let crop_ok=0
										let ustep=step
										until [ $ustep -eq 1 -o $crop_ok -eq 3 ] 
										do
											if [ ! -z "${DIVXCROP[ustep]}" -a "${DIVXCROP[ustep]}" = "${DIVXCROP[ustep-1]}" ] 
											then
											let crop_ok=crop_ok+1
												UDIVXCROP=`cat ${UniqueDir[Number]}/crop.log|grep crop= |tail -n 1 | cut -f3 -d '('|sed 's/)//'|sed 's/-vop //'`
											fi
											let ustep=ustep-1
										done
										let step=step-1
									done
								fi
								if [ $crop_ok -eq 3 ]
								then
									X=`$MENCODER -frames 0 ${UniqueDir[Number]}/${Titel}.mpg 2>/dev/null|grep aspect|cut -f1 -d ')'|awk '{print $3}'|cut -f1 -d'x'`
									Y=`$MENCODER -frames 0 ${UniqueDir[Number]}/${Titel}.mpg 2>/dev/null|grep aspect|cut -f1 -d ')'|awk '{print $3}'|cut -f2 -d'x'`
									X=$((Y*4/3))
									CROPMIN=`echo ${UDIVXCROP}|cut -f 4 -d ':'`
									Y=$((Y-CROPMIN-CROPMIN))
									if [ "$DIVX_RESDIV" = "yes" ]
									then
									     Y=$((Y/2))
									     X=$((X/2))
									fi
									ASPOPT="-vop scale=$X:$Y,lavcdeint $UDIVXCROP -sws $DIVXSWS"
								fi
							fi
							if [ $crop_ok -eq 0 ]
							then
								Y=`$MENCODER -frames 0 ${UniqueDir[Number]}/${Titel}.mpg 2>/dev/null|grep aspect|cut -f1 -d ')'|awk '{print $3}'|cut -f2 -d'x'`
								X=$((Y*4/3))
								[ $need_scale -eq 1 ] && ASPOPT="-vop scale=$X:$Y,lavcdeint -sws $DIVXSWS" || ASPOPT="-vop lavcdeint -sws $DIVXSWS"
								if [ "$DIVX_RESDIV" = "yes" ] 
								then
									YY=$((Y/2))
									X=$((YY*4/3))
									Y=$YY
									[ $need_scale -eq 1 ] && ASPOPT="-vop scale=$X:$Y,lavcdeint -sws $DIVXSWS" || ASPOPT="-vop lavcdeint -sws $DIVXSWS"
								fi
							fi
						fi
   		 
						[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "start mencoder mode $DIVXTYPE for $i" >/dev/null 2>&1
						[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "ASPECT = ${ASPOPT}: ${X}:${Y} Bitr=${VBITRT}" >/dev/null 2>&1
						for t in $DIVXTYPE
						do
							case $t in
								lavc)
									printf "\t`date +"%T"` Erstelle %s Format 2 Pass\n" "$t"
									for pass in 1 2 
									do
										printf "\t`date +"%T"` : Start $MENCODER pass %d %s %s %s %s Videobitr. %s\n" $pass "$DIVXENCOPT" "$AC3OPT" "$DIVXCCHOPT" "$ASPOPT" "$VBITRT"
										nice -n ${PRIO} $MENCODER $DIVXENCOPT $AC3OPT $DIVXCCHOPT $ASPOPT \
											-mc 0 \
											-vc mpeg12 \
											-passlogfile ${UniqueDir[Number]}/divx2pass.log \
											-ovc lavc \
											-lavcopts vcodec=$DIVXVLAVCCODEC:vhq:ildct:vpass=$pass:vqmin=2:vbitrate=$VBITRT \
											-o ${UniqueDir[Number]}/output.avi \
											${UniqueDir[Number]}/${Titel}.mpg > ${LOG[Number]} 2>&1
										status=$?
										[ "$DIVX_DEBUG" = "yes" ] && strings ${LOG[Number]} >> $LOGFILE
									done
									;;
								divx)
									printf "\t`date +"%T"` Erstelle %s Format 2 Pass\n" "$t"
									for pass in 1 2 
									do
										printf "\t`date +"%T"` : Start $MENCODER pass %d %s %s %s %s Videobitr. %s\n" $pass "$DIVXENCOPT" "$AC3OPT" "$DIVXCCHOPT" "$ASPOPT" "$VBITRT"
										nice -n ${PRIO} $MENCODER $DIVXENCOPT $AC3OPT $DIVXCCHOPT $ASPOPT \
											-mc 0 \
											-vc mpeg12 \
											-passlogfile ${UniqueDir[Number]}/divx2pass.log \
											-ovc divx4 \
											-divx4opts pass=$pass:q=$DIVXQUALITY:br=$VBITRT \
											-o ${UniqueDir[Number]}/output.avi \
											${UniqueDir[Number]}/${Titel}.mpg > ${LOG[Number]} 2>&1
										status=$?
										[ "$DIVX_DEBUG" = "yes" ] && strings ${LOG[Number]} >> $LOGFILE
									done
									;;
								xvid)
									printf "\t`date +"%T"` Erstelle %s Format 2 Pass\n" "$t"
									for pass in 1 2
									do
										printf "\t`date +"%T"` : Start $MENCODER pass %d %s %s %s %s Videobitr. %s\n" $pass "$DIVXENCOPT" "$AC3OPT" "$DIVXCCHOPT" "$ASPOPT" "$VBITRT"
										nice -${PRIO} $MENCODER $DIVXENCOPT $AC3OPT $DIVXCCHOPT $ASPOPT \
											-mc 0 \
											-vc mpeg12 \
											-ovc xvid \
											-xvidencopts bitrate=$VBITRT:pass=$pass \
											-o ${UniqueDir[Number]}/output.avi \
											${UniqueDir[Number]}/${Titel}.mpg > ${LOG[Number]} 2>&1
										status=$?
										[ "$DIVX_DEBUG" = "yes" ] && strings ${LOG[Number]} >> $LOGFILE
									done
									;;
								divxlowq)
									printf "\t`date +"%T"` Erstelle %s Format 1 Pass\n" "$t"
									VBITRT=400
									X=$((X/2))
									Y=$((Y/2))
									ASPOPT="-vop scale=$X:$Y,lavcdeint -sws $DIVXSWS"
									printf "\t`date +"%T"` : Erstelle DivX LQ Format (q=1, bitr=400) sincle Pass\n"
									nice -n ${PRIO} $MENCODER $DIVXENCOPT $AC3OPT $DIVXCCHOPT $ASPOPT \
										-mc 0 \
										-vc mpeg12 \
										-o ${UniqueDir[Number]}/output.avi \
										-ovc divx4 \
										-divx4opts q=1:br=400 \
										${UniqueDir[Number]}/${Titel}.mpg  > ${LOG[Number]} 2>&1
									status=$?
									[ "$DIVX_DEBUG" = "yes" ] && strings ${LOG[Number]} >> $LOGFILE
								;;
								*)
									printf "`\tdate +"%T"` ERROR :Encodertype %s wird nicht unterstützt." "$t"
									status=2001
									;;
							esac
	
							if [ $status -ne 0 ]
							then
								[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "`echo $0|xargs basename` for ${Titel} fail" >/dev/null 2>&1
								echo "Bei der Konvertierung von ${Titel} ist es zu Fehlern gekommen.status=<${status}>"
								logger "Bei der Konvertierung von ${Titel} ist es zu Fehlern gekommen.status=<${status}>"
							else
								if [ "$DIVX_EXPANDFILENAME" = "yes" ]
								then
									if [ ! -f ${DIVX_DESTDIR}/${Titel}_${t}_${VBITRT}.${DIVX_SUFFIX} ]
									then
										mkdir -p ${DIVX_DESTDIR}
										mv ${UniqueDir[Number]}/output.avi ${DIVX_DESTDIR}/${Titel}_${t}_${VBITRT}.${DIVX_SUFFIX}
										status=$?
										File=${DIVX_DESTDIR}/${Titel}_${t}_${VBITRT}.${DIVX_SUFFIX}
									else
										let index=1
										until [ ! -f ${DIVX_DESTDIR}/${Titel}_${t}_${VBITRT}_-$index.${DIVX_SUFFIX} ]
										do
											let index=index+1
										done
										mkdir -p ${DIVX_DESTDIR}
										mv ${UniqueDir[Number]}/output.avi ${DIVX_DESTDIR}/${Titel}_${t}_${VBITRT}_-$index.${DIVX_SUFFIX}
										status=$?
										File=${DIVX_DESTDIR}/${Titel}_${t}_${VBITRT}_-$index.${DIVX_SUFFIX}
									fi
								else
									if [ ! -f ${DIVX_DESTDIR}/${Titel}.${DIVX_SUFFIX} ]
									then
										mkdir -p ${DIVX_DESTDIR}
										mv ${UniqueDir[Number]}/output.avi ${DIVX_DESTDIR}/${Titel}.${DIVX_SUFFIX}
										status=$?
										File=${DIVX_DESTDIR}/${Titel}.${DIVX_SUFFIX}
									else
										let index=1
										until [ ! -f ${DIVX_DESTDIR}/${Titel}-$index.${DIVX_SUFFIX} ]
										do
											let index=index+1
										done
										mkdir -p ${DIVX_DESTDIR}
										mv ${UniqueDir[Number]}/output.avi ${DIVX_DESTDIR}/${Titel}-$index.${DIVX_SUFFIX}
										status=$?
										File=${DIVX_DESTDIR}/${Titel}-$index.${DIVX_SUFFIX}
									fi
								fi
								[ "$DIVX_PREVENT_TIME" != "no" ] && touch -r $j $File
								[ "$OSDMONITOR" = "yes" ] && $SVDRPSEND MESG "`echo $0|xargs basename` : $File ready." >/dev/null 2>&1
								if [ "$DIVX_AUTOWRITE" = "yes" ]
								then
									cd -
									echo "$File:CD:DEL" >> $VCOQUEUEDIR/burn
									cd -
								fi
							fi
						done
					fi
				fi
			fi
			# Temp Files löschen
			cd -
			$RM -rf ${UniqueDir[Number]}
			let Number=Number+1
			printf "\t`date` : Finish %s\n" "$i"
			done
		done
		echo "`date` : Parts from $CMDLIN completed"
		#      mv $LOGFILE ${DIVX_DESTDIR}/${Titel}-$index.log
		#      bzip2 ${DIVX_DESTDIR}/${Titel}-$index.log
		cp $NewJobs $NewJobs.$$
		grep -x -v "$CMDLIN" $NewJobs.$$ > $NewJobs 
		$RM $NewJobs.$$
	done
	$RM $NewJobs
fi
else
	echo "Bitte die Schreibrechte für ${LTEMPDIR} und ${DIVX_DESTDIR} überprüfen. Keine verarbeitung möglich"
fi

printf "`date +"%d-%m-%2Y %T"` : Session %s end\n" "$0"
Exit
