#!/usr/bin/bash
# Simple script for encoding to DVD video, with DVD writing capability
# Version: 5.9
# Date: 2015-09-29
# Copyright (C) 2013-2015, Grozdan Nikolov <neutrino8@gmail.com>
#
# Dedicated to my mom, a big movie lover, who passed away from cancer
# in January 2013.
#
# file2dvd 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.
#
# file2dvd 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

green() { echo -e "\e[1;32m$1\e[0;39;49m"; }
brown() { echo -e "\e[0;33m$1\e[0;39;49m"; }
error() { echo -e "\e[1;31m$1\e[0;39;49m"; }

case "$1" in
	"")
	error "Usage: file2dvd [-1p|-2p|-qp] [-nq|-hq|-vhq|-ehq|-uhq|-cp /path/to/preset]"
	error "Example for 2-pass encoding with the very high-quality preset: file2dvd -2p -vhq"
	error "Use file2dvd -v for version or file2dvd -h for help"
	exit 1
	;;
	-v)	echo "Version: 5.9"; exit 0; ;;
	-h)	man file2dvd; exit 0; ;;
	-1p|-2p|-qp) true ;;
	*)	echo ""; error "-> Unsupported option or passmode: $1"; echo ""; exit 1; ;;
esac

CPUINFO="/proc/cpuinfo"
if [ -r "$CPUINFO" ]; then
	THREADS="$(sed -n -e '/^processor/p' "$CPUINFO" | wc -l)"
	if [ ! -z "$THREADS" ]; then
		threads="$THREADS"
	else
		threads="1"
	fi
fi

case "$2" in
	-nq)
	mencopts="mbd=1:vmax_b_frames=1:mv0:threads=$threads"
	ffopts="-mbd 1 -bf 1 -flags +mv0 -threads 0"
	;;
	-hq)
	mencopts="mbd=2:trell:last_pred=4:mv0:o=mpv_flags=+cbp_rd:vmax_b_frames=1:mv0_threshold=0:threads=$threads"
	ffopts="-mbd 2 -trellis 1 -last_pred 4 -flags +mv0 -mpv_flags +cbp_rd -bf 1 -mv0_threshold 0 -threads 0"
	;;
	-vhq)
	mencopts="mbd=0:mbcmp=2:precmp=2:cmp=2:subcmp=2:trell:dia=2:last_pred=4:mv0:o=mpv_flags=+cbp_rd:vmax_b_frames=1:preme=2:mv0_threshold=0:threads=$threads"
	ffopts="-mbd 0 -mbcmp 2 -precmp 2 -cmp 2 -subcmp 2 -trellis 1 -dia_size 2 -last_pred 4 -flags +mv0 -mpv_flags +cbp_rd -bf 1 -preme 2 -mv0_threshold 0 -threads 0"
	;;
	-ehq)
	mencopts="mbd=0:mbcmp=10:precmp=10:cmp=10:subcmp=10:trell:predia=3:dia=3:last_pred=8:mv0:o=mpv_flags=+cbp_rd,quantizer_noise_shaping=1:vmax_b_frames=1:preme=2:mv0_threshold=0:threads=$threads"
	ffopts="-mbd 0 -mbcmp 10 -precmp 10 -cmp 10 -subcmp 10 -trellis 1 -pre_dia_size 3 -dia_size 3 -last_pred 8 -flags +mv0 -mpv_flags +cbp_rd -bf 1 -preme 2 -mv0_threshold 0 -quantizer_noise_shaping 1 -threads 0"
	;;
	-uhq)
	mencopts="mbd=0:mbcmp=6:precmp=6:cmp=6:subcmp=6:trell:predia=4:dia=4:last_pred=8:mv0:o=mpv_flags=+cbp_rd,quantizer_noise_shaping=2:vmax_b_frames=1:preme=2:mv0_threshold=0:threads=$threads"
	ffopts="-mbd 0 -mbcmp 6 -precmp 6 -cmp 6 -subcmp 6 -trellis 1 -pre_dia_size 4 -dia_size 4 -last_pred 8 -flags +mv0 -mpv_flags +cbp_rd -bf 1 -preme 2 -mv0_threshold 0 -quantizer_noise_shaping 2 -threads 0"
	;;
	-cp)
	if [ -z "$3" ]; then
		error "-> You have to provide a custom preset file!"
		error "-> Example: file2dvd $1 -cp /path/to/preset/preset_file"
		error "-> Look at the 'preset-file' in the file2dvd package for an example"
		exit 1
	fi
	if [ -f "$3" ]; then
		source "$3"
	else
		error "-> No such file: $3"
		exit 1
	fi
	;;
	"")	echo ""; error "-> No preset specified!"; echo ""; exit 1; ;;
	*)	echo ""; error "-> Unsupported preset: $2"; echo ""; exit 1; ;;
esac

CONFIGFILE="$HOME/.file2dvd"
configversion=7

genconfig_func() {
cat<<EOF>>$CONFIGFILE
############### Configuration file for file2dvd ###############
#
# Version: $configversion - do not modify or remove this line!
#
# Specify the default encoder to use. Choose between mencoder
# and ffmpeg

DEFAULT_ENCODER="ffmpeg"

# Specify a default output directory. Note that your encodes
# will be placed in \$DEFAULT_OUTPUT_DIR/file2dvd

DEFAULT_OUTPUT_DIR="$HOME"

# Set a nice value for the encoding. Note that regular users
# can only use values between 0 and 19. root can use between
# -20 and 19

DEFAULT_NICE_VALUE="10"

# Specify a default DVD device to use for ISO image writing

DEFAULT_DVD_DEVICE="/dev/dvd"

# Enable/disable video filters with 'y' or 'n'

ALLOW_VID_SOFT_TELECINE="y"
ALLOW_VID_HARD_TELECINE="y"
ALLOW_VID_PAL_TO_NTSC="y"
ALLOW_VID_NTSC_TO_PAL="y"
ALLOW_VID_DEINTERLACE="y"
ALLOW_VID_INTERLACE="y"
ALLOW_VID_DENOISE="y"
ALLOW_VID_DEBLOCK="y"
ALLOW_VID_CUSTOM_QUANT_MATRIX="y"

# Enable/disable audio filters with 'y' or 'n'

ALLOW_AUD_VOLUME="y"

# Paths to the programs

FFMPEG="$(which ffmpeg 2>/dev/null)"
MENCODER="$(which mencoder 2>/dev/null)"
MPLAYER="$(which mplayer 2>/dev/null)"
DVDAUTHOR="$(which dvdauthor 2>/dev/null)"
MKISOFS="$(which mkisofs 2>/dev/null)"
GENISOIMAGE="$(which genisoimage 2>/dev/null)"
GROWISOFS="$(which growisofs 2>/dev/null)"
DVD_RW_FORMAT="$(which dvd+rw-format 2>/dev/null)"
BC="$(which bc 2>/dev/null)"
EOF
}

if [ -f "$CONFIGFILE" ]; then
	cver=$(grep '^# Version' "$CONFIGFILE" | awk '{print $3}')
	if [ "$cver" != "$configversion" ]; then
		rm -f "$CONFIGFILE"
		genconfig_func
		echo
		error "Important notice! The configuration file of file2dvd located in"
		error "'$CONFIGFILE' has been updated to the latest version!"
		echo
		error "If you have made any prior changes to the configuration file,"
		error "please commit those changes again and restart file2dvd!"
		error "If no changes are made, just restart file2dvd to get rid of"
		error "this notice."
		echo
		exit 1
	else
		source "$CONFIGFILE"
	fi
else
	genconfig_func
	echo
	green "-> Config file generated in '$CONFIGFILE'"
	green "-> Please set things up in there, if needed"
	echo
	source "$CONFIGFILE"
fi

# Do some tests...

if [ ! -x "$MPLAYER" ]; then
	echo
	error "-> MPlayer is missing!"
	error "-> Check '$CONFIGFILE'"
	echo
	exit 1
fi

if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
	if [ ! -x "$MENCODER" ]; then
		echo
		error "-> MEncoder is missing!"
		error "-> Check '$CONFIGFILE'"
		echo
		exit 1
	fi
elif [ "$DEFAULT_ENCODER" = "ffmpeg" ]; then
	if [ ! -x "$FFMPEG" ]; then
		echo
		error "-> ffmpeg is missing!"
		error "-> Check '$CONFIGFILE'"
		echo
		exit 1
	fi
else
	echo
	error "-> Invalid default encoder!"
	error "-> Check '$CONFIGFILE'"
	error "-> Using ffmpeg as default!"
	echo
	DEFAULT_ENCODER="ffmpeg"
fi

if [ ! -x "$BC" ]; then
	echo
	error "-> bc is missing!"
	error "-> Check '$CONFIGFILE'"
	echo
	exit 1
fi

if [ ! -x "$DVDAUTHOR" ]; then
	dvdsc=0
	echo
	error "-> dvdauthor is missing!"
	error "-> Check '$CONFIGFILE'"
	error "-> Disabling DVD structure creation!"
	echo
else
	dvdsc=1
fi

if [ ! -x "$MKISOFS" ]; then
	MKISO="$GENISOIMAGE"
	if [ ! -x "$MKISO" ]; then
		iso=0
		echo
		error "-> mkisofs/genisoimage is missing!"
		error "-> Check '$CONFIGFILE'"
		error "-> Disabling ISO image creation!"
		echo
	else
		iso=1
	fi
else
	iso=1
	MKISO="$MKISOFS"
fi

if [ ! -x "$GROWISOFS" -o ! -x "$DVD_RW_FORMAT" ]; then
	burn=0
	echo
	error "-> growisofs or dvd+rw-format is missing!"
	error "-> Check '$CONFIGFILE'"
	error "-> Disabling DVD burning capability"
	echo
else
	burn=1
fi

if [ -z "$DEFAULT_OUTPUT_DIR" -o -z "$(echo "$DEFAULT_OUTPUT_DIR" | grep '^/')" ]; then
	echo
	error "-> No output directory specified!"
	error "-> Check '$CONFIGFILE' and make sure to use full paths!"
	error "-> Defaulting to '$HOME'"
	echo
	DEFAULT_OUTPUT_DIR="$HOME"
fi

if [ $UID != 0 ]; then
	case "$DEFAULT_NICE_VALUE" in
		[0-9]|1[0-9]) true ;;
		""|*)
		echo
		green "-> Invalid/unsupported nice value in '$CONFIGFILE'"
		green "-> Defaulting to 10"
		echo
		DEFAULT_NICE_VALUE="10"
		;;
	esac
else
	case "$DEFAULT_NICE_VALUE" in
		-20|-1[0-9]|-[1-9]|[0-9]|1[0-9]) true ;;
		""|*)
		echo
		green "-> Invalid/unsupported nice value in '$CONFIGFILE'"
		green "-> Defaulting to 10"
		echo
		DEFAULT_NICE_VALUE="10"
		;;
	esac
fi

printf "Provide the input file: "
read -e input
if [ -z "$input" ]; then
	echo
	error "-> No file provided!"
	echo
	exit 1
fi

if [ ! -f "$input" ]; then
	echo
	error "-> No such file!"
	echo
	exit 1
fi

OUTDIR="$DEFAULT_OUTPUT_DIR/file2dvd/$(basename "${input%.*}" | sed 's| |_|g')"
if [ ! -d "$OUTDIR" ]; then
	mkdir -p "$OUTDIR" 2>/dev/null
	if [ $? != 0 ]; then
		echo
		error "-> Couldn't create output directory '$OUTDIR'"
		echo
		exit 1
	fi
fi

infile="$OUTDIR/tmp$$.${input##*.}"

if [ ! -z "$(echo "$input" | grep '^/')" ]; then
	ln -sf "$input" "$infile"
else
	ln -sf "$(pwd)/$input" "$infile"
fi

clean_func() {
	rm -rf "$OUTDIR" >/dev/null 2>&1
	exit 1
}

trap 'clean_func' SIGHUP SIGINT SIGQUIT SIGKILL SIGABRT SIGFPE SIGSEGV SIGTERM SIGPIPE SIGIO

if [ "$1" = "-qp" ]; then
	printf "Specify the QP value [2-31 - default is 2]: "
	read qp
	if [ -z "$qp" ]; then
		qpval="2"
	else
		qpval="$qp"
	fi
fi

echo
green "-> Detecting video standard and FPS value"
VIDEO_FPS="$($MPLAYER "$input" -vo null -ao null -identify -frames 1 2>/dev/null | grep '^ID_VIDEO_FPS' | tail -n 1 | awk -F= '{print $2}')"
case "$VIDEO_FPS" in
	23.976)
	vidstd="ntsc"
	vidfps="24000/1001"
	green "-> Video standard appears to be NTSC Film and FPS value is 23.976"
	echo
	;;
	25.000)
	vidstd="pal"
	vidfps="25"
	green "-> Video standard appears to be PAL and FPS value is 25"
	echo
	;;
	29.970)
	vidstd="ntsc"
	vidfps="30000/1001"
	green "-> Video standard appears to be NTSC Video and FPS value is 29.970"
	echo
	;;
	50.000)
	vidstd="pal"
	vidfps="25"
	framestep="framestep=2,"
	green "-> Video standard appears to be PAL and FPS value is 50"
	echo
	;;
	59.940)
	vidstd="ntsc"
	vidfps="30000/1001"
	framestep="framestep=2,"
	green "-> Video standard appears to be NTSC and FPS value is 59.940"
	echo
	;;
	*)
	error "-> Couldn't detect FPS value or it's unsupported!"
	echo
	printf "Specify the input file video standard [PAL/NTSC - default is PAL]: "
	read vstd
	case "$vstd" in
		pal|PAL|"")	vidstd="pal" ;;
		ntsc|NTSC)	vidstd="ntsc" ;;
		*)
		echo
		error "-> Unsupported video standard!"
		echo
		clean_func
		;;
	esac
	if [ "$vidstd" = "pal" ]; then
		printf "Specify the input file FPS value [25/50 - default is 25]: "
		read fps
		case "$fps" in
			25)	vidfps="25" ;;
			50)	vidfps="25"; framestep="framestep=2,"; VIDEO_FPS="50.000" ;;
			*)
			echo
			error "-> Unsupported FPS value!"
			echo
			clean_func
			;;
		esac
	else
		printf "Specify the input file FPS value [23.976/29.970/59.940 - default is 29.970]: "
		read fps
		case "$fps" in
			29.970|"")	vidfps="30000/1001" ;;
			23.976)		vidfps="24000/1001" ;;
			59.940)		vidfps="30000/1001"; framestep="framestep=2,"; VIDEO_FPS="59.940" ;;
			*)
			echo
			error "-> Unsupported FPS value!"
			echo
			clean_func
			;;
		esac
	fi
	;;
esac

if [ "$vidfps" = "24000/1001" ]; then
	if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
		if [ "$ALLOW_VID_SOFT_TELECINE" = "y" ]; then
			printf "Set Soft-Telecine flag on the encode? [y/N]: "
			read st
			if [ "$st" = "y" -o "$st" = "Y" ]; then
				softtel=":telecine"
			fi
		fi
	else
		if [ "$ALLOW_VID_HARD_TELECINE" = "y" ]; then
			printf "Hard-Telecine the encode to PAL standard? [y/N]: "
			read htp
			if [ "$htp" = "y" -o "$htp" = "Y" ]; then
				telecine=",telecine=top:222222222223"
				ffopts="$(echo "$ffopts" | sed 's|+mv0|+mv0+ilme+ildct|')"
				vidfps="25"
				vidstd="pal"
				vidfo="-top 1"
			fi
			if [ -z "$telecine" ]; then
				printf "Hard-Telecine the encode to NTSC Video standard? [y/N]: "
				read htn
				if [ "$htn" = "y" -o "$htn" = "Y" ]; then
					telecine=",telecine=top:23"
					ffopts="$(echo "$ffopts" | sed 's|+mv0|+mv0+ilme+ildct|')"
					vidfps="30000/1001"
					vidfo="-top 1"
				fi
			fi
		fi
	fi
fi

case "$vidfps" in
	24000/1001|30000/1001)
	if [ "$ALLOW_VID_NTSC_TO_PAL" = "y" ]; then
		if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
			if [ "$vidfps" = "24000/1001" ]; then
				if [ -z "$softtel" -a -z "$framestep" ]; then
					printf "Soft-Telecine the NTSC content to PAL? [y/N]: "
					read topal
					if [ "$topal" = "y" -o "$topal" = "Y" ]; then
						softtel=":film2pal"
						vidstd="pal"
						# Must be set to 23.976 fps
						vidfps="24000/1001"
					fi
				fi
			fi
		else
			if [ -z "$telecine" -a -z "$framestep" ]; then
				printf "Convert the NTSC content to PAL? [y/N]: "
				read topal
				if [ "$topal" = "y" -o "$topal" = "Y" ]; then
					if [ "$vidfps" = "24000/1001" ]; then
						fpsfilt=",setpts=23976/25000*PTS"
						atempo="atempo=1.04270937604270937604,"
					else
						fpsfilt=",setpts=29970/25000*PTS"
						atempo="atempo=0.83416750083416750083,"
					fi
					vidfps="25"
					vidstd="pal"
				fi
			fi
		fi
	fi
	;;
	25)
	if [ "$ALLOW_VID_PAL_TO_NTSC" = "y" ]; then
		if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
			if [ -z "$framestep" ]; then
				printf "Soft-Telecine the PAL content to NTSC Video? [y/N]: "
				read tontsc
				if [ "$tontsc" = "y" -o "$tontsc" = "Y" ]; then
					softtel=":tele_src=25:tele_dest=30000/1001"
					vidstd="ntsc"
					# Must be set to 25 fps
					vidfps="25"
				fi
			fi
		else
			if [ -z "$framestep" -a -z "$telecine" ]; then
				printf "Convert the PAL content to NTSC Video? [y/N]: "
				read tontsc
				if [ "$tontsc" = "y" -o "$tontsc" = "Y" ]; then
					fpsfilt=",setpts=25000/29970*PTS"
					atempo="atempo=1.19880000000000000000,"
					vidfps="30000/1001"
					vidstd="ntsc"
				fi
			fi
		fi
	fi
	;;
esac


# Set GOP limit
if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
	case "$vidfps" in
		24000/1001|25)	mencopts="$mencopts:keyint=15" ;;
		30000/1001)	mencopts="$mencopts:keyint=18" ;;
	esac
else
	case "$vidfps" in
		24000/1001|25)	ffopts="$ffopts -g 15" ;;
		30000/1001)	ffopts="$ffopts -g 18" ;;
	esac
fi

if [ -z "$telecine" -a -z "$softtel" ]; then
	if [ "$ALLOW_VID_DEINTERLACE" = "y" ]; then
		printf "Is the input file interlaced? [y/N]: "
		read ilaced
		if [ "$ilaced" = "y" -o "$ilaced" = "Y" ]; then
			printf "Preserve (p) or deinterlace (d)? [p/d]: "
			read prede
			if [ "$prede" = "p" -o "$prede" = "P" ]; then
				if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
					interl=":1"
					mencopts="$mencopts:ilme:ildct"
					ilpack="ilpack=1,"
				else
					ffopts="$(echo "$ffopts" | sed 's|+mv0|+mv0+ilme+ildct|')"
					interl=":interl=1"
				fi
			else
				test -z "$framestep" && fstep=",framestep=2," || fstep=","
				echo
				brown "Deinterlace Filters"
				brown "~~~~~~~~~~~~~~~~~~~"
				echo "0 -> yadif"
				echo "1 -> yadif & mcdeint (TFF: top fields first)"
				echo "2 -> yadif & mcdeint (BFF: bottom fields first)"
				echo "3 -> kerndeint"
				if [ "$DEFAULT_ENCODER" = "ffmpeg" ]; then
					echo "4 -> Weston 3 Field Deinterlacing Filter"
				fi
				echo
				printf "Select a deinterlacer [default is 0]: "
				read deint
				case "$deint" in
					0|"")	deinterl="yadif," ;;
					1)	deinterl="yadif=1,mcdeint=1:0:10$fstep"; field_dominance="-field-dominance 0" ;;
					2)	deinterl="yadif=1,mcdeint=1:1:10$fstep"; field_dominance="-field-dominance 1" ;;
					3)
					printf "Specify the filter's threshold value [0-255 - default is 5]: "
					read ftv
					test -z "$ftv" && deinterl="kerndeint=5," || deinterl="kerndeint=$ftv,"
					;;
					4)	deinterl="w3fdif," ;;
					*)
					echo
					error "-> Unknown deinterlacer option!"
					echo
					clean_func
					;;
				esac
				case "$deint" in
					1|2)	test ! -z "$framestep" && framestep="framestep=4," ;;
				esac
			fi
		fi
	fi
fi

if [ "$ALLOW_VID_INTERLACE" = "y" ]; then
	case "$VIDEO_FPS" in
		50.000|59.940)
		if [ -z "$deinterl" -a -z "$interl" ]; then
			printf "Interlace the encode? [y/N]: "
			read intl
			if [ "$intl" = "y" -o "$intl" = "Y" ]; then
				framestep=
				if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
					ilacefilt=",tinterlace=4"
					mencopts="$mencopts:ilme:ildct"
				else
					echo
					brown "Interlace Filters"
					brown "~~~~~~~~~~~~~~~~~"
					echo "0 -> interlace"
					echo "1 -> tinterlace"
					echo
					printf "Select the interlace filter [default is 0]: "
					read if
					case "$if" in
						0|"")	ilacefilt=",interlace=scan=tff" ;;
						1)	ilacefilt=",tinterlace=4" ;;
						*)
						echo
						error "-> Unknown interlace option!"
						echo
						clean_func
						;;
					esac
					ffopts="$(echo "$ffopts" | sed 's|+mv0|+mv0+ilme+ildct|')"
					vidfo="-top 1"
				fi
			fi
		fi
		;;
	esac
fi

if [ -z "$interl" ]; then
	if [ "$ALLOW_VID_DENOISE" = "y" ]; then
		printf "Denoise the input? [y/N]: "
		read denoise
		if [ "$denoise" = "y" -o "$denoise" = "Y" ]; then
			if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
				echo
				brown "Denoise Filters"
				brown "~~~~~~~~~~~~~~~"
				echo "0 -> hqdn3d"
				echo "1 -> ow"
				echo
				printf "Select the denoise filter [default is 0]: "
				read dfilter
				case "$dfilter" in
					0|"")
					printf "Specify the denoise filter values [default is 4:3:6]: "
					read dfv
					test -z "$dfv" && denoisefilt="hqdn3d=4:3:6," || denoisefilt="hqdn3d=$dfv,"
					;;
					1)
					printf "Specify the denoise filter values [default is 8:1.0:1.0]: "
					read dfv
					test -z "$dfv" && denoisefilt="ow=8:1.0:1.0," || denoisefilt="ow=$dfv,"
					;;
					*)
					echo
					error "-> Invalid denoise filter option!"
					echo
					clean_func
					;;
				esac
			else
				echo
				brown "Denoise Filters"
				brown "~~~~~~~~~~~~~~~"
				echo "0 -> hqdn3d"
				echo "1 -> owdenoise"
				echo "2 -> dctdnoiz"
				echo
				printf "Select the denoise filter [default is 0]: "
				read dfilter
				case "$dfilter" in
					0|"")
					printf "Specify the denoise filter values [default is 4:3:6]: "
					read dfv
					test -z "$dfv" && denoisefilt="hqdn3d=4:3:6," || denoisefilt="hqdn3d=$dfv,"
					;;
					1)
					printf "Specify the denoise filter values [default is 8:1.0:1.0]: "
					read dfv
					test -z "$dfv" && denoisefilt="owdenoise=8:1.0:1.0," || denoisefilt="owdenoise=$dfv,"
					;;
					2)
					printf "Specify the denoise filter values [default is 4.0]: "
					read dfv
					test -z "$dfv" && denoisefilt="dctdnoiz=4.0," || denoisefilt="dctdnoiz=$dfv,"
					;;
					*)
					echo
					error "-> Invalid denoise filter option!"
					echo
					clean_func
					;;
				esac
			fi
		fi
	fi
fi

if [ -z "$interl" ]; then
	if [ "$ALLOW_VID_DEBLOCK" = "y" ]; then
		printf "Deblock the input? [y/N]: "
		read db
		if [ "$db" = "y" -o "$db" = "Y" ]; then
			if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
				echo
				brown "Deblock Filters"
				brown "~~~~~~~~~~~~~~~"
				echo "0 -> spp"
				echo "1 -> fspp"
				echo "2 -> uspp"
				echo "3 -> pp7"
				echo
				print "Select a deblock filter [default is 3]: "
				read sd
				case "$sd" in
					0)
					printf "Specify the deblock quality [0-6 - default is 4]: "
					read dbq
					test -z "$dbq" && deblockfilt="spp=4," || deblockfilt="spp=$dbq,"
					;;
					1)
					printf "Specify the deblock quality [0-6 - default is 4]: "
					read dbq
					test -z "$dbq" && deblockfilt="fspp=4," || deblockfilt="fspp=$dbq,"
					;;
					2)
					printf "Specify the deblock quality [0-8 - default is 3]: "
					read dbq
					test -z "$dbq" && deblockfilt="uspp=3," || deblockfilt="uspp=$dbq,"
					;;
					3|"")
					printf "Specify the deblock quality [0-6 - default is 4]: "
					read dbq
					test -z "$dbq" && deblockfilt="pp7=4," || deblockfilt="pp7=$dbq,"
					;;
					*)
					echo
					error "-> Invalid deblock filter option!"
					echo
					clean_func
					;;
				esac
			else
				printf "Specify the deblock quality [0-6 - default is 4]: "
				read dbq
				test -z "$dbq" && deblockfilt="spp=4," || deblockfilt="spp=$dbq,"
			fi
		fi
	fi
fi

if [ -z "$interl" -a -z "$telecine" -a -z "$ilacefilt" ]; then
	if [ "$ALLOW_VID_CUSTOM_QUANT_MATRIX" = "y" ]; then
		printf "Use custom quant matrices? [y/N]: "
		read cqm
		if [ "$cqm" = "y" -o "$cqm" = "Y" ]; then
			echo
			brown "Custom Quant Matrices"
			brown "~~~~~~~~~~~~~~~~~~~~~"
			echo "0 -> file2dvd's custom quant matrix"
			echo "1 -> KVCD Notch"
			echo "2 -> Bach1"
			echo "3 -> HVS Best"
			echo "4 -> QLB (Quenc Lower Bitrate)"
			echo
			printf "Select a custom quant matrix [default is 0]: "
			read matrix
			case "$matrix" in
				0|"")
				# Optimized for low to moderate high bitrates (~2000-4000 kbps)
				intra="10,16,19,22,24,26,27,28,14,16,20,22,26,28,28,30,18,22,24,26,28,30,32,35,20,22,26,28,29,32,34,38,22,26,27,29,32,35,38,46,24,27,29,32,35,38,46,56,26,27,29,34,38,46,99,99,28,29,34,38,46,56,99,99"
				inter="16,17,18,19,20,22,23,24,17,18,19,20,22,23,24,25,18,19,20,21,22,24,25,26,19,20,21,22,24,25,26,27,20,21,22,24,25,26,27,29,21,22,24,25,26,27,29,30,22,24,25,26,27,28,99,99,23,25,26,27,28,30,99,99"
				;;
				1)
				intra="8,9,12,22,26,27,29,34,9,10,14,26,27,29,34,37,12,14,18,27,29,34,37,38,22,26,27,31,36,37,38,40,26,27,29,36,39,38,40,48,27,29,34,37,38,40,48,58,29,34,37,38,40,48,58,69,34,37,38,40,48,58,69,79"
				inter="16,18,20,22,24,26,28,30,18,20,22,24,26,28,30,32,20,22,24,26,28,30,32,34,22,24,26,30,32,32,34,36,24,26,28,32,34,34,36,38,26,28,30,32,34,36,38,40,28,30,32,34,36,38,42,42,30,32,34,36,38,40,42,44"
				;;
				2)
				intra="8,16,19,22,26,27,29,34,16,16,22,24,27,29,34,37,19,22,26,27,29,34,34,38,22,22,26,27,29,34,37,40,22,26,27,29,32,35,40,48,26,27,29,32,35,40,48,58,26,27,29,34,38,46,56,69,27,29,35,38,46,56,69,83"
				inter="16,18,20,22,24,26,28,30,18,20,22,24,26,28,30,32,20,22,24,26,28,30,32,34,22,24,26,30,32,32,34,36,24,26,28,32,34,34,36,38,26,28,30,32,34,36,38,40,28,30,32,34,36,38,42,42,30,32,34,36,38,40,42,44"
				;;
				3)
				intra="8,16,16,16,17,18,21,24,16,16,16,16,17,19,22,25,16,16,17,18,20,22,25,29,16,16,18,21,24,27,31,36,17,17,20,24,30,35,41,47,18,19,22,27,35,44,54,65,21,22,25,31,41,54,70,88,24,25,29,36,47,65,88,115"
				inter="18,18,18,18,19,21,23,27,18,18,18,18,19,21,24,29,18,18,19,20,22,24,28,32,18,18,20,24,27,30,35,40,19,19,22,27,33,39,46,53,21,21,24,30,39,50,61,73,23,24,28,35,46,61,79,98,27,29,32,40,53,73,98,129"
				;;
				4)
				intra="8,16,19,22,26,27,29,34,16,16,22,24,27,29,34,37,19,22,26,27,29,34,37,39,22,22,26,27,29,34,38,42,22,26,27,29,32,36,40,50,26,27,29,32,36,40,50,61,26,27,29,35,40,50,59,75,27,29,35,40,50,59,75,89"
				inter="16,17,18,19,20,21,22,23,17,18,19,20,21,22,23,25,18,19,20,21,22,23,24,26,19,20,21,22,23,24,26,28,20,21,22,23,25,26,28,29,21,22,23,24,26,28,29,31,22,23,24,26,28,29,31,34,23,24,25,28,29,31,34,38"
				;;
				*)
				echo
				error "-> Unknown quant matrix option!"
				echo
				clean_func
				;;
			esac
			if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
				mencopts="$mencopts:intra_matrix=$intra:inter_matrix=$inter"
			else
				ffopts="$ffopts -intra_matrix $intra -inter_matrix $inter"
			fi
		fi
	fi
fi

printf "Use MPEG-style quantizers? [y/N]: "
read mpegq
if [ "$mpegq" = "y" -o "$mpegq" = "Y" ]; then
	if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
		mencopts="$mencopts:mpeg_quant"
	else
		ffopts="$ffopts -mpeg_quant 1"
	fi
fi

echo
brown "Software Scalers"
brown "~~~~~~~~~~~~~~~~"
echo "0 --> Fast Bilinear"
echo "1 --> Bilinear"
echo "2 --> Bicubic"
echo "3 --> Experimental"
echo "4 --> Nearest Neightbor"
echo "5 --> Area"
echo "6 --> Luma Bicubic/Chroma Bilinear"
echo "7 --> Gauss"
echo "8 --> Sinc"
echo "9 --> Lanczos"
echo "10 -> Natural Bicubic Spline"
echo
printf "Select the software scaler [default is 2]: "
read softscale
case "$softscale" in
	0)	scaler="fast_bilinear"; mscaler="0" ;;
	1)	scaler="bilinear"; mscaler="1" ;;
	2|"")	scaler="bicubic"; mscaler="2" ;;
	3)	scaler="experimental"; mscaler="3" ;;
	4)	scaler="neighbor"; mscaler="4" ;;
	5)	scaler="area"; mscaler="5" ;;
	6)	scaler="bicublin"; mscaler="6" ;;
	7)	scaler="gauss"; mscaler="7" ;;
	8)	scaler="sinc"; mscaler="8" ;;
	9)	scaler="lanczos"; mscaler="9" ;;
	10)	scaler="spline"; mscaler="10" ;;
esac

GETVIDASPECT="$($MPLAYER "$input" -vo null -ao null -identify -frames 1 2>/dev/null | grep '^ID_VIDEO_ASPECT' | tail -n 1 | awk -F= '{print $2}')"
if [ ! -z "$GETVIDASPECT" ]; then
	echo
	green "-> Detected $GETVIDASPECT:1 aspect ratio"
	echo
else
	echo
	error "-> Couldn't detect video aspect ratio!"
	echo
fi

printf "Specify the input file aspect ratio [4:3/16:9/anamorphic - default is 16:9]: "
read aspect
case "$aspect" in
	4:3|16:9|"")
	test ! -z "$aspect" && asp_ratio="$aspect" || asp_ratio="16:9"
	test "$vidstd" = "pal" && scale="scale=720:576$interl" || scale="scale=720:480$interl"
	if [ "$DEFAULT_ENCODER" = "ffmpeg" ]; then
		scale="$scale,setdar=$(echo $asp_ratio | sed 's|:|/|')"
	fi
	;;
	ana*)
	printf "Is the input file cropped? [y/N]: "
	read cropped
	case "$cropped" in
		y|Y)
		asp_ratio="16:9"
		if [ "$vidstd" = "pal" ]; then
			if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
				scale="scale=720:432$interl,expand=720:576"
			else
				# padding = (576-432)/2 = 72
				scale="scale=720:432$interl,pad=720:576:0:72,setdar=16/9"
			fi
		else
			if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
				scale="scale=720:368$interl,expand=720:480"
			else
				# padding = (480-368)/2 = 56
				scale="scale=720:368$interl,pad=720:480:0:56,setdar=16/9"
			fi
		fi
		;;
		*|"")
		asp_ratio="16:9"
		test "$vidstd" = "pal" && scale="scale=720:576$interl" || scale="scale=720:480$interl"
		if [ "$DEFAULT_ENCODER" = "ffmpeg" ]; then
			scale="$scale,setdar=$(echo $asp_ratio | sed 's|:|/|')"
		fi
		;;
	esac
	;;
	*)
	echo
	error "-> Unsupported aspect ratio!"
	echo
	clean_func
	;;
esac

if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
	vaspect="$(echo "$asp_ratio" | tr ':' '/')"
fi

# The 'scale' filter is the "central" one, meaning
# that all filters coming before it must have a
# comma at the end. All filters coming after it,
# must be preceded by a comma.

vidfilters="-vf $ilpack$deinterl$denoisefilt$deblockfilt$framestep$softskip$scale$harddup$fpsfilt$telecine$ilacefilt"

echo
green "-> Detecting audio codec and bitrate..."
GETAUDCODEC="$($MPLAYER "$input" -vo null -ao null -identify -frames 1 2>/dev/null | grep '^ID_AUDIO_CODEC' | tail -n 1 | awk -F= '{print $2}')"
GETAUDBR="$($MPLAYER "$input" -vo null -ao null -identify -frames 1 2>/dev/null | grep '^ID_AUDIO_BITRATE' | tail -n 1 | awk -F= '{print $2}')"
GETAUDRATE="$($MPLAYER "$input" -vo null -ao null -identify -frames 1 2>/dev/null | grep '^ID_AUDIO_RATE' | tail -n 1 | awk -F= '{print $2}')"
GETAUDCHAN="$($MPLAYER "$input" -vo null -ao null -channels 8 -identify -frames 1 2>/dev/null | grep '^ID_AUDIO_NCH' | tail -n 1 | awk -F= '{print $2}')"
if [ ! -z "$GETAUDCODEC" ]; then
	case "$GETAUDCODEC" in
		*a52*|*ac3*)	audiocodec="AC-3" ;;
		*eac3*)		audiocodec="E-AC-3" ;;
		*truehd*)	audiocodec="TrueHD" ;;
		*dca*|*dts*)	audiocodec="DTS" ;;
		*dvdpcm*)	audiocodec="LPCM" ;;
		*pcm*)		audiocodec="PCM" ;;
		*vorbis*)	audiocodec="Vorbis" ;;
		*opus*)		audiocodec="Opus" ;;
		*faad*|*aac*)	audiocodec="AAC" ;;
		*mp3*|*mad*)	audiocodec="MP3" ;;
		*mp2*)		audiocodec="MP2" ;;
		*flac*)		audiocodec="FLAC" ;;
		*wma*)		audiocodec="WMA" ;;
		*)		audiocodec="Unknown" ;;
	esac
else
	audiocodec="Unknown"
fi
if [ ! -z "$GETAUDBR" -a "$GETAUDBR" != "0" ]; then
	audiobitrate="$(($GETAUDBR/1000))"
else
	audiobitrate="Unknown"
fi
if [ ! -z "$GETAUDRATE" -a "$GETAUDRATE" != "0" ]; then
	audiorate="$GETAUDRATE"
else
	audiorate="Unknown"
fi
if [ ! -z "$GETAUDCHAN" ]; then
	audchannels="$GETAUDCHAN"
else
	audchannels="Unknown"
fi
if [ -z "$GETAUDCODEC" -a -z "$GETAUDBR" -a -z "$GETAUDRATE" ]; then
	error "-> Couldn't detect audio codec, sample rate and bitrate!"
else
	green "-> Detected $audiocodec audio ($audchannels channels, $audiorate Hz) @ $audiobitrate kbps"
fi
echo

mencoder_aud_func() {
	case "$1" in
		ac3)		mencaud="acodec=ac3:abitrate=$(echo "$audbr" | sed -e 's|-b:a ||; s|k||')"; audopt="-oac lavc" ;;
		mp2)		mencaud="acodec=mp2:abitrate=$(echo "$audbr" | sed -e 's|-b:a ||; s|k||')"; audopt="-oac lavc" ;;
		lpcm)		mencaud="acodec=pcm_s16be"; audopt="-oac lavc" ;;
		copy)		audopt="-oac copy -mc 0 -msglevel demuxer=-1" ;;
		nosound)	audopt="-nosound" ;;
	esac
}

brown "Available Audio Codecs"
brown "~~~~~~~~~~~~~~~~~~~~~~"
echo "0 -> AC-3    3 -> LPCM"
echo "1 -> DTS     4 -> COPY"
echo "2 -> MP2     5 -> NOSOUND"
echo
printf "Select the output audio codec [default is 0]: "
read acodec
case "$acodec" in
	0|1|2|ac3|AC3|ac-3|AC-3|dts|DTS|mp2|MP2|"")
	if [ "$vidstd" = "ntsc" ]; then
		case "$acodec" in
			2|mp2|MP2)
			echo
			error "-> MP2 codec is only allowed in the PAL DVD standard!"
			error "-> Please choose AC-3, DTS or LPCM for the NTSC standard!"
			echo
			clean_func
			;;
		esac
	fi
	cparam="-b:a"
	case "$acodec" in
		0|ac3|AC3|ac-3|AC-3|"")
		audcodec="-c:a ac3"
		echo
		brown "AC-3 Audio Bitrates"
		brown "~~~~~~~~~~~~~~~~~~~"
		echo "0 -> 32 kbps    8 --> 128 kbps"
		echo "1 -> 40 kbps    9 --> 160 kbps"
		echo "2 -> 48 kbps    10 -> 192 kbps"
		echo "3 -> 56 kbps    11 -> 224 kbps"
		echo "4 -> 64 kbps    12 -> 256 kbps"
		echo "5 -> 80 kbps    13 -> 320 kbps"
		echo "6 -> 96 kbps    14 -> 384 kbps"
		echo "7 -> 112 kbps   15 -> 448 kbps"
		echo
		printf "Select the audio bitrate [default is 10]: "
		read audbitrate
		case "$audbitrate" in
			0) audbr="$cparam 32k" ;;
			1) audbr="$cparam 40k" ;;
			2) audbr="$cparam 48k" ;;
			3) audbr="$cparam 56k" ;;
			4) audbr="$cparam 64k" ;;
			5) audbr="$cparam 80k" ;;
			6) audbr="$cparam 96k" ;;
			7) audbr="$cparam 112k" ;;
			8) audbr="$cparam 128k" ;;
			9) audbr="$cparam 160k" ;;
			10|"") audbr="$cparam 192k" ;;
			11) audbr="$cparam 224k" ;;
			12) audbr="$cparam 256k" ;;
			13) audbr="$cparam 320k" ;;
			14) audbr="$cparam 384k" ;;
			15) audbr="$cparam 448k" ;;
			*)
			echo
			error "-> Unsupported audio bitrate!"
			error "-> Defaulting to 192 kbps"
			echo
			audbr="$cparam 192k"
			;;
		esac
		mencoder_aud_func ac3
		;;
		1|dts|DTS)
		if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
			echo
			error "-> DTS audio not supported with MEncoder as encoder!"
			error "-> Please choose AC-3 audio"
			echo
			clean_func
		fi
		audcodec="-c:a dca -strict -2"
		echo
		brown "DTS Audio Bitrates"
		brown "~~~~~~~~~~~~~~~~~~"
		echo "0 -> 384 kbps"
		echo "1 -> 448 kbps"
		echo "2 -> 512 kbps"
		echo "3 -> 576 kbps"
		echo "4 -> 640 kbps"
		echo "5 -> 768 kbps"
		echo
		printf "Select the audio bitrate [default is 0]: "
		read audbitrate
		case "$audbitrate" in
			0|"")	audbr="$cparam 384k" ;;
			1)	audbr="$cparam 448k" ;;
			2)	audbr="$cparam 512k" ;;
			3)	audbr="$cparam 576k" ;;
			4)	audbr="$cparam 640k" ;;
			5)	audbr="$cparam 768k" ;;
			*)
			echo
			error "-> Unsupported audio bitrate!"
			error "-> Defaulting to 384 kbps"
			echo
			audbr="$cparam 384k"
			;;
		esac
		;;
		2|mp2|MP2)
		audcodec="-c:a mp2"
		echo
		brown "MP2 Audio Bitrates"
		brown "~~~~~~~~~~~~~~~~~~"
		echo "0 -> 32 kbps    8 --> 128 kbps"
		echo "1 -> 40 kbps    9 --> 160 kbps"
		echo "2 -> 48 kbps    10 -> 192 kbps"
		echo "3 -> 56 kbps    11 -> 224 kbps"
		echo "4 -> 64 kbps    12 -> 256 kbps"
		echo "5 -> 80 kbps    13 -> 320 kbps"
		echo "6 -> 96 kbps"
		echo "7 -> 112 kbps"
		echo
		printf "Select the audio bitrate [default is 10]: "
		read audbitrate
		case "$audbitrate" in
			0) audbr="$cparam 32k" ;;
			1) audbr="$cparam 40k" ;;
			2) audbr="$cparam 48k" ;;
			3) audbr="$cparam 56k" ;;
			4) audbr="$cparam 64k" ;;
			5) audbr="$cparam 80k" ;;
			6) audbr="$cparam 96k" ;;
			7) audbr="$cparam 112k" ;;
			8) audbr="$cparam 128k" ;;
			9) audbr="$cparam 160k" ;;
			10|"") audbr="$cparam 192k" ;;
			11) audbr="$cparam 224k" ;;
			12) audbr="$cparam 256k" ;;
			13) audbr="$cparam 320k" ;;
			*)
			echo
			error "-> Unsupported audio bitrate!"
			error "-> Defaulting to 192 kbps"
			echo
			audbr="$cparam 192k"
			;;
		esac
		mencoder_aud_func mp2
		;;
	esac
	;;
	3|lpcm|LPCM)
	if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
		mencoder_aud_func lpcm
	else
		audbr="-c:a pcm_s16be"
	fi
	;;
	4|copy|COPY)
	case "$GETAUDCODEC" in
		*a52*|*ac3*|*dca*|*dts*|*mp2*|*dvdpcm*) true ;;
		*)
		echo
		error "-> Codec not supported by the DVD standard!"
		error "-> Please use audio re-encoding instead of copy!"
		echo
		clean_func
		;;
	esac
	if [ "$vidstd" = "ntsc" ]; then
		case "$GETAUDCODEC" in
			*mp2*)
			echo
			error "-> Codec not supported by the NTSC standard!"
			error "-> Please re-encode the audio instead of copying it!"
			echo
			clean_func
			;;
		esac
	fi
	if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
		case "$GETAUDCODEC" in
			*dvdpcm*)
			echo
			error "-> Copying LPCM audio is not supported yet!"
			echo
			clean_func
			;;
			*)	mencoder_aud_func copy ;;
		esac
	else
		audbr="-c:a copy"
	fi
	;;
	5|nosound|NOSOUND)
	if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
		mencoder_aud_func nosound
	else
		audbr="-an"
	fi
	;;
	*)
	echo
	error "-> Unsupported audio codec!"
	echo
	clean_func
	;;
esac

case "$acodec" in
	0|1|3|ac3|ac-3|AC3|AC-3|dts|DTS|lpcm|LPCM|"")
	printf "Specify the amount of audio channels to use [1/2/4/6 - default is 2]: "
	read ac
	case "$ac" in
		1)	ffchans="-ac 1"; menchans="-channels 1" ;;
		2|"")	ffchans="-ac 2"; menchans="-channels 2" ;;
		4)	ffchans="-ac 4"; menchans="-channels 4" ;;
		6)	ffchans="-ac 6"; menchans="-channels 6" ;;
		*)
		echo
		error "-> Invalid audio channels option!"
		error "-> Defaulting to 2"
		echo
		ffchans="-ac 2"
		menchans="-channels 2"
		;;
	esac
	;;
	2|mp2|MP2)
	ffchans="-ac 2"
	menchans="-channels 2"
	;;
esac

case "$acodec" in
	4|5|copy|COPY|nosound|NOSOUND)	true ;;
	""|*)
	if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
		audrate="lavcresample=48000,"
		srate="-srate 48000"
	else
		audrate="aresample=48000,"
	fi
	;;
esac

case "$acodec" in
	0|1|2|3|ac3|AC3|ac-3|AC-3|dts|DTS|mp2|MP2|lpcm|LPCM|"")
	if [ "$ALLOW_AUD_VOLUME" = "y" ]; then
		if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
			printf "Specify the audio volume in dB [-200-60 - default is 0 (no change)]: "
			read volume
			if [ ! -z "$volume" ]; then
				audvolume="volume=$volume:1,"
			fi
		else
			printf "Specify the audio volume increase or decrease [default is 1.0 (no change)]: "
			read volume
			if [ ! -z "$volume" ]; then
				audvolume="volume=$volume,"
			fi
		fi
	fi
	;;
esac

afilters="$(echo "$audvolume$atempo$audrate" | sed 's|,$||')"
test ! -z "$afilters" && audfilters="-af $afilters $srate"

if [ "$1" != "-qp" ]; then
	printf "Specify the target file size in MiB [default is 4200]: "
	read target
	if [ -z "$target" ]; then
		target_size="4200"
	else
		target_size="$target"
	fi
	GETVLENGTH="$($MPLAYER "$input" -vo null -ao null -identify -frames 1 2>/dev/null | grep '^ID_LENGTH' | tail -n 1 | awk -F= '{print $2}')"
	case "$GETVLENGTH" in
		""|0|0.00|0.000)
		echo
		error "-> Failed to detect video length!"
		echo
		printf "Specify the input file video length in seconds: "
		read vlength
		if [ -z "$vlength" ]; then
			echo
			error "-> No video length specified!"
			echo
			clean_func
		else
			GETVLENGTH="$vlength"
		fi
		;;
	esac

	case "$acodec" in
		0|1|2|ac3|AC3|ac-3|AC-3|dts|DTS|mp2|MP2|"")
		VIDBR="$(echo "scale=0; ($target_size * 8192 / $GETVLENGTH) - $(echo "$audbr" | sed -e 's|-b:a ||; s|k||')" | $BC -l)"
		;;
		3|lpcm|LPCM)
		case "$GETAUDCHAN" in
			1)	audchanbr="768" ;;
			2|"")	audchanbr="1536" ;;
			4)	audchanbr="3072" ;;
			6)	audchanbr="4608" ;;
			8)	audchanbr="6144" ;;
			*)	audchanbr="1536" ;;
		esac
		VIDBR="$(echo "scale=0; ($target_size * 8192 / $GETVLENGTH) - $audchanbr" | $BC -l)"
		;;
		4|copy|COPY)
		if [ ! -z "$GETAUDBR" -a "$GETAUDBR" != "0" ]; then
			VIDBR="$(echo "scale=0; ($target_size * 8192 / $GETVLENGTH) - $(($GETAUDBR/1000))" | $BC -l)"
		else
			echo
			error "-> Couldn't detect the file's audio bitrate!"
			echo
			printf "Specify the input file audio bitrate in kbps: "
			read faudbr
			if [ -z "$faudbr" ]; then
				echo
				error "-> No value given!"
				echo
				clean_func
			else
				fileaudbr="$faudbr"
			fi
			VIDBR="$(echo "scale=0; ($target_size * 8192 / $GETVLENGTH) - $fileaudbr" | $BC -l)"
		fi
		;;
		5|nosound|NOSOUND)
		VIDBR="$(echo "scale=0; ($target_size * 8192 / $GETVLENGTH)" | $BC -l)"
		;;
	esac

	if [ $VIDBR -gt 8000 ]; then
		VIDBR="8000"
	fi
fi

if [ "$1" = "-qp" ]; then
	FFMODE="-q:v $qpval -bufsize 1835k -maxrate 9800k"
	MENCMODE="vqscale=$qpval:vrc_maxrate=9800:vrc_buf_size=1835"
else
	FFMODE="-b:v ${VIDBR}k -minrate ${VIDBR}k -maxrate ${VIDBR}k -bufsize 1835k"
	MENCMODE="vbitrate=$VIDBR:vrc_minrate=$VIDBR:vrc_maxrate=$VIDBR:vrc_buf_size=1835"
fi

echo
if [ "$1" != "-qp" ]; then
	green "-> Using $VIDBR kbps as auto-calculated video bitrate"
else
	green "-> Using QP-based encoding"
fi
green "-> Outputting to '$OUTDIR'"
echo
sleep 3

passlog="$OUTDIR/$(basename "$(echo "${input%.*}" | sed 's| |_|g')")"
output="$OUTDIR/$(basename "$(echo "${input%.*}.mpg" | sed 's| |_|g')")"

ffmpegopts="$ffopts -f dvd -c:v mpeg2video $vidfilters -sws_flags $scaler -aspect $asp_ratio -pix_fmt yuv420p $vidfo -r $vidfps $FFMODE $audfilters $audcodec $audbr $ffchans"

mopts="$vidfilters -sws $mscaler -ovc lavc -lavcopts"
mencoderopts="vcodec=mpeg2video:$mencopts:$MENCMODE:aspect=$vaspect:$mencaud $field_dominance $audopt $audfilters $menchans -ofps $vidfps -of mpeg -mpegopts format=dvd:tsaf:interleaving2$softtel"

ffmpeg_exit_func() {
	if [ $? != 0 ]; then
		echo
		error "-> ffmpeg has exited with a non-zero status. Cleaning up and exiting..."
		echo
		clean_func
	fi
}

mencoder_exit_func() {
	if [ $? != 0 ]; then
		echo
		error "-> MEncoder has exited with a non-zero status. Cleaning up and exiting..."
		echo
		clean_func
	fi
}

case "$1" in
	-1p|-qp)
	if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
		nice -n $DEFAULT_NICE_VALUE $MENCODER "$infile" $mopts $mencoderopts -o "$output"
		mencoder_exit_func
	else
		nice -n $DEFAULT_NICE_VALUE $FFMPEG -i "$infile" $ffmpegopts -y "$output"
		ffmpeg_exit_func
	fi
	;;
	-2p)
	if [ "$DEFAULT_ENCODER" = "mencoder" ]; then
		nice -n $DEFAULT_NICE_VALUE $MENCODER "$infile" $mopts turbo:vpass=1:$mencoderopts -passlogfile "$passlog.log" -o /dev/null
		mencoder_exit_func
		echo
		green "-> Starting the second pass..."
		echo
		sleep 3
		nice -n $DEFAULT_NICE_VALUE $MENCODER "$infile" $mopts vpass=2:$mencoderopts -passlogfile "$passlog.log" -o "$output"
		mencoder_exit_func
		rm -f "$passlog.log"
	else
		nice -n $DEFAULT_NICE_VALUE $FFMPEG -i "$infile" $ffmpegopts -passlogfile "$passlog" -pass 1 -y /dev/null
		ffmpeg_exit_func
		echo
		green "-> Starting the second pass..."
		echo
		sleep 3
		nice -n $DEFAULT_NICE_VALUE $FFMPEG -i "$infile" $ffmpegopts -passlogfile "$passlog" -pass 2 -y "$output"
		ffmpeg_exit_func
		rm -f "$passlog-0.log"
	fi
	;;
esac

rm -f "$infile"

if [ "$vidstd" = "pal" ]; then
	vidres="720x576"
elif [ "$vidstd" = "ntsc" ]; then
	vidres="720x480"
fi

OUT="$OUTDIR/$(basename "$(echo "${input%.*}" | sed 's| |_|g')")"

if [ "$dvdsc" = "1" ]; then
	echo
	green "-> Creating DVD structure in '$OUT'"
	echo
	sleep 3
	export VIDEO_FORMAT=$vidstd
# & character is often present in movie titles. Escape it
echo "<dvdauthor>
<vmgm>
</vmgm>
  <titleset>
    <titles>
      <video format=\"$vidstd\" aspect=\"$asp_ratio\" resolution=\"$vidres\" />
        <pgc>
          <vob file=\"$(echo "$output" | sed 's|&|&amp;|g')\" chapters=\"0,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,00:50:00,00:55:00,01:00:00,01:05:00,01:10:00,01:15:00,01:20:00,01:25:00,01:30:00,01:35:00,01:40:00,01:45:00,01:50:00,01:55:00,02:00:00,02:05:00,02:10:00,02:15:00,02:20:00,02:25:00,02:30:00,02:35:00,02:40:00,02:45:00,02:50:00,02:55:00,03:00:00,03:05:00,03:10:00,03:15:00,03:20:00,03:25:00,03:30:00,03:35:00,03:40:00,03:45:00,03:50:00,03:55:00,04:00:00\" />
        </pgc>
    </titles>
  </titleset>
</dvdauthor>" > "$OUT.xml"

	$DVDAUTHOR -o "$OUT" -x "$OUT.xml"
else
	exit 1
fi
if [ $? = 0 ]; then
	rm -f "$OUT.xml"
	$DVDAUTHOR -o "$OUT" --toc
	if [ "$iso" = "1" ]; then
		echo
		green "-> Creating ISO file in '$OUTDIR'"
		echo
		sleep 3
		# Max of 32 characters are supported by Volume IDs
		$MKISO -dvd-video -V "$(basename "$OUT" | awk '{print substr($0,0,32)}')" -o "$OUT.iso" "$OUT"
		if [ $? != 0 ]; then
			burn=0
			echo
			error "-> Failed to create a proper ISO image!"
			error "-> Disabling DVD burning capability"
			echo
		fi
	else
		exit 1
	fi
	if [ $? = 0 ]; then
		if [ "$burn" = "1" ]; then
			dvd_device_func() {
				DEVINFO="/proc/sys/dev/cdrom/info"
				if [ -r "$DEVINFO" ]; then
					DRIVE="$(grep 'drive name' "$DEVINFO" | sed 's|drive name:||g')"
					if [ ! -z "$DRIVE" ]; then
						echo
						for i in $DRIVE; do
							green "-> Found device: /dev/$i"
						done
						for i in /dev/dvd*; do
							if [ -L $i ]; then
								green "-> Found symbolic link to DVD device: $(ls -l $i | grep -o '/dev.*')"
							fi
						done
						echo
					fi
				else
					echo
					error "-> Couldn't detect the DVD device(s)!"
					echo
				fi
				printf "Specify the DVD device to use [default is /dev/dvd]: "
				read -e dvd
				test -z "$dvd" && device="/dev/dvd" || device="$dvd"
				if [ ! -b "$device" ]; then
					echo
					error "-> '$device' is not a block device!"
					dvd_device_func
				fi
			}
			echo
			printf "Write the ISO image to a DVD disc? [y/N]: "
			read write
			if [ "$write" = "y" -o "$write" = "Y" ]; then
				if [ ! -z "$DEFAULT_DVD_DEVICE" ]; then
					device="$DEFAULT_DVD_DEVICE"
					if [ ! -b "$device" ]; then
						echo
						error "-> '$device' is not a block device!"
						error "-> Check '$CONFIGFILE'"
						dvd_device_func
					fi
				else
					dvd_device_func
				fi
				printf "Please insert a blank DVD disc and press Enter to start writing"
				read disc
				echo
				# Small counter :)
				# Give the device 15 seconds to settle
				counter_func() {
					for i in {15..1}; do
						sleep 1 && echo -n "$i "
					done
				}
				# Set counter color
				color_func() {
					BLUE="\033[01;34m"
					NORMAL="\e[0;0m"
					case $1 in
						blue) printf "$BLUE" ;;
						normal) echo -ne "$NORMAL" ;;
					esac
				}
				color_func blue && printf "Starting to write the ISO file in: " && counter_func
				color_func normal && echo ""
				$DVD_RW_FORMAT $device
				$GROWISOFS -dvd-compat -Z $device="$OUT.iso"
			fi
		fi
	fi
else
	echo
	error "-> dvdauthor exited with a non-zero status!"
	error "-> Skipping ISO creation and disabling DVD burning capability!"
	echo
fi

exit $?
