#!/usr/bin/env bash
# $Id: h264enc, v 10.4.7, 2016/01/19, gn Exp $
#
# Encode BDs/DVDs/VCDs/video files to the H.264/AVC/MPEG-4 Part 10
# video format using MEncoder from MPlayer
#
# Copyright (C) 2006-2016, Grozdan Nikolov
#
# h264enc 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.
#
# h264enc 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


shopt -u expand_aliases
export PATH=$PATH:/usr/local/bin
version=10.4.7
configversion=37

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"; }

# Create config dir
H264ENCDIR="$HOME/.h264enc"
if [ ! -d "$H264ENCDIR" ]; then
	mkdir -p "$H264ENCDIR" 2>/dev/null
	if [ $? != 0 ]; then
		error "-> Could not make config directory '$H264ENCDIR'"
		exit 1
	fi
fi

# In case h264enc did not remove its unique temp
# directories, remove them after 5 days. Of course
# this is assuming h264enc is ran again
find "$H264ENCDIR" -name 'job*' -ctime +4 -type d -exec rm -rf {} \; >/dev/null 2>&1

# Generate config file
genconfig_func() {
cat<<EOF>>$H264ENCDIR/config
############## Configuration file for h264enc ##############
#
# Version: $configversion - do not modify or remove this line!
#
# h264enc can also send mails if configured to do so. There are four
# variables that need to be set in the mail settings below:
# MAILNOTIFY    # Enable/disable sending mail with y or n
# EMAIL         # The recepient's email address
# MAILSUBJ      # The mail's subject
# MAILMSG       # The actual mail message
#
# There is no need to add date/time to your email message as this is
# automatically being done.
#
# h264enc uses the 'mail' program which reads the mail settings from
# /home/username/.mailrc. If there's no such file present or it is
# configured incorrectly, mail sending will fail. A gmail example
# settings for .mailrc can look like this:
#
# set smtp-use-starttls
# set smtp=smtp://smtp.gmail.com:587
# set smtp-auth=login
# set smtp-auth-user=your-email@gmail.com
# set smtp-auth-password=your-password
#

# For use with the -e option
EDITOR="nano"

# If one or more of the below
# variables is set to "y", it
# disables globally the specific 
# function
DISABLE_ALL_VID_FILTERS="n"
DISABLE_ALL_AUD_FILTERS="n"
DISABLE_VID_CROP_FILTER="n"
DISABLE_SUBTITLES="n"

DISABLE_ASK_DVD_ANGLE="n"
DISABLE_ASK_DVD_CHAPTERS="n"
DISABLE_ASK_BD_ANGLE="n"
DISABLE_ASK_BD_CHAPTERS="n"

# Video filters
ALLOW_VID_DEINTERLACE="y"
ALLOW_VID_INTERLACE="y"
ALLOW_VID_DEBLOCK="y"
ALLOW_VID_DELOGO="y"
ALLOW_VID_DENOISE="y"
ALLOW_VID_NOISE="y"
ALLOW_VID_DEBAND="y"
ALLOW_VID_UNSHARP="y"
ALLOW_VID_ROTATE="y"
ALLOW_VID_BRIGHTNESS="y"
ALLOW_VID_EQUALIZER="y"
ALLOW_VID_AUTOCROP="n"
ALLOW_VID_FPS_CONVERSION="y"
ALLOW_VID_SCALER_TUNING="n"
ALLOW_VID_DSIZE="y"
ALLOW_VID_EXPAND="y"
ALLOW_VID_COLORSPACE="n"
ALLOW_VID_ASPECT="y"

# Audio filters
ALLOW_AUD_CHANNELS="y"
ALLOW_AUD_RESAMPLE="y"
ALLOW_AUD_NORMALIZE="y"
ALLOW_AUD_VOLUME="y"
ALLOW_AUD_EQUALIZER="y"
ALLOW_AUD_PAN="y"

# Amount of audio tracks to support
# Any non-zero value will do. Set it
# to "auto" to ask for as many as
# detected audio tracks
MAX_AMOUNT_AUD_TRACKS="2"

# Amount of subtitles to support
# Any non-zero value will do. Set
# it to "auto" to ask for as many
# as detected subtitles
MAX_AMOUNT_SUBS="2"

# Max amount of external subs to
# support (for mkv/mp4/ogm importing)
# NOTE: setting it to "auto" is
# not supported!
MAX_AMOUNT_EXT_SUBS="2"

# Containers
ALLOW_MKV_MUXING="y"
ALLOW_MP4_MUXING="y"
ALLOW_TS_MUXING="y"
ALLOW_OGM_MUXING="y"

# Container options
DISABLE_MKV_STATISTICS_TAGS="n"
DISABLE_MKV_GLOBAL_TAGS="n"

# Misc
ALLOW_EDL_LIST="n"
ALLOW_SAMPLE_ENCODING="y"
ALLOW_SCAN_MULTIPLE_VIDSTREAMS="y"
DELETE_AVI_AFTER_REMUX="n"

# Script/mplayer settings
#
# Default software scaler accepts
# values 0-10. Consult the mplayer
# man page for more info
DEFAULT_SOFTWARE_SCALER=""
DEFAULT_VID_BITRATE=""
DEFAULT_VID_CRFQP=""
DEFAULT_AUD_CODEC=""
DEFAULT_OUTPUT=""
TEMPDIR=""
PRIORITY="19"
DVD_DEVICE=""
BLURAY_DEVICE=""
CDROM_DEVICE=""
MPLAYEROPTS="-noconfig all -loop 1"

# Mail settings
MAILNOTIFY="n"
EMAIL=""
MAILSUBJ="[h264enc]: Encoding finished"
MAILMSG="This is a notification mail from the h264enc script to inform you that encoding has finished."

# Paths to executables
MPLAYER="$(which mplayer 2>/dev/null)"
MENCODER="$(which mencoder 2>/dev/null)"
X264="$(which x264 2>/dev/null)"
LSDVD="$(which lsdvd 2>/dev/null)"
DVDXCHAP="$(which dvdxchap 2>/dev/null)"

MP4BOX="$(which MP4Box 2>/dev/null)"
MKVMERGE="$(which mkvmerge 2>/dev/null)"
MKVEXTRACT="$(which mkvextract 2>/dev/null)"
OGMMERGE="$(which ogmmerge 2>/dev/null)"
TSMUXER="$(which tsMuxeR 2>/dev/null)"

OGGENC="$(which oggenc 2>/dev/null)"
FLAC="$(which flac 2>/dev/null)"
FDKAACENC="$(which aac-enc 2>/dev/null)"
NEROAACENC="$(which neroAacEnc 2>/dev/null)"
AACPLUSENC="$(which aacplusenc 2>/dev/null)"
FAAC="$(which faac 2>/dev/null)"
AFTEN="$(which aften 2>/dev/null)"
DCAENC="$(which dcaenc 2>/dev/null)"
OPUSENC="$(which opusenc 2>/dev/null)"

MAIL="$(which mail 2>/dev/null)"
BC="$(which bc 2>/dev/null)"
PV="$(which pv 2>/dev/null)"
DD="$(which dd 2>/dev/null)"
EOF
}

if [ -f $H264ENCDIR/config ]; then
	cver=$(grep '^# Version' $H264ENCDIR/config | awk '{print $3}')
	if [ "$cver" != "$configversion" ]; then
		mv -f $H264ENCDIR/config $H264ENCDIR/config.old
		genconfig_func
		echo
		error "Important notice! The configuration file of h264enc located in"
		error "'$H264ENCDIR/config' 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 h264enc!"
		error "If no changes are made, just restart h264enc to get rid of"
		error "this notice."
		echo
		exit 1
	else
		source "$H264ENCDIR/config"
	fi
else
	genconfig_func
	echo
	green "-> Config file generated in '$H264ENCDIR/config'"
	green "-> Please set things up in there, if needed"
	echo
	source "$H264ENCDIR/config"
fi

# converts a given string from upper to lower chars
tolower() {
	echo $1 |\
	sed -e 'y|ABCDEFGHIJKLMNOPQRSTUVWXYZ|abcdefghijklmnopqrstuvwxyz|'
}

# takes a usual question as an argument
# tokenizes it into the question and the possible answers
# if the user mistypes an answer, the question is asked again
get_selection_func() {
	# extract options:
	#	 Select the Input type [file/dir/dvd/vcd]:
	#	 ->
	#	 file dir dvd vcd
	options=$(\
		echo ${1} \
		| sed -e 's|[^\[]*\[\([^]]*\)\].*|\1|' \
		| sed -e 's|\/| |g' \
		) 
	# an option that contains an upper case letter is the default
	# option (if several do, the last one wins)
	i=0
	for option in ${options}; do
		if echo ${option} | grep -e '[ABCDEFGHIJKLMNOPQRSTUVWXYZ]' 2>&1>/dev/null; then
			default=$(tolower "${option}")
		fi
	done

	# convert all options to lowercase
	options=$(for option in ${options}; do
		echo $(tolower "${option}")
	done)

	while true; do
		read -p "${1}" selection
		selection=$(tolower "$selection")
		if [ -n "${selection}" ]; then
			for value in ${options}; do
				if [ "${selection}" = "${value}" ]; then
					echo ${selection}
					return 0
				fi
			done
		elif [ -n "${default}" ] ; then
			echo ${default}
			return 0
		fi
	done
}

send_email_func() {
	if [ -x "$MAIL" -a "$MAILNOTIFY" = "y" -a ! -z "$EMAIL" -a ! -z "$MAILSUBJ" -a ! -z "$MAILMSG" ]; then
		case "$1" in
			exp)
			echo "test -f \"$HOME/.mailrc\" && echo -e \"$MAILMSG\n\nEncoding for \\\"\$(basename \"${OUTPUT%.*}\")\\\" finished on \$(date)\" | $MAIL -s \"$MAILSUBJ\" \"$EMAIL\""
			echo
			;;
			dir)
			echo "test -f \"$HOME/.mailrc\" && echo -e \"$MAILMSG\n\nEncoding for directory \\\"\$(dirname \"$infile\")\\\" finished on \$(date)\" | $MAIL -s \"$MAILSUBJ\" \"$EMAIL\""
			echo
			;;
			*)
			test -f "$HOME/.mailrc" && echo -e "$MAILMSG\n\nEncoding for \"$(basename "${OUTPUT%.*}")\" finished on $(date)" | $MAIL -s "$MAILSUBJ" "$EMAIL"
			;;
		esac
	fi
}

# Make temp dir
if [ -z "$TEMPDIR" ]; then
	TEMPDIR="$H264ENCDIR/job$$"
	test -d "$TEMPDIR" || mkdir -p "$TEMPDIR"
else
	TEMPDIR="$TEMPDIR/job$$"
	if [ ! -d "$TEMPDIR" ]; then
		mkdir -p "$TEMPDIR" 2>/dev/null
		if [ $? != 0 ]; then
			error "-> Could not create custom temp dir: $TEMPDIR"
			exit 1
		fi
	fi
fi

# User interrupt
interrupt_func() {
	echo
	error "-> Cleaning up and exiting..."
	rm -rf "$TEMPDIR"
	rm -f "$H264ENCDIR/batch$$"
	exit 2
}

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

# Place frequently used MPlayer options
# in a single var in order not to write
# them again and again when we need to
# call MPlayer. This var should go at
# then end of the MPlayer CMD. Note
# that it is not used everywhere as
# sometimes we need different options
MPOPTS="-vo null -ao null -frames 1 -identify"

# Remove temp dir on
# user error/exit
# 0 = clean exit
# 1 = user error/program error
# 2 = user interrupt
exit_func() {
	case "$1" in
		0) ec="0" ;;
		1) ec="1" ;;
		2) ec="2" ;;
	esac
	rm -rf "$TEMPDIR" 
	rm -f "$H264ENCDIR/batch$$"
	exit $ec
}

# Get devices
get_devices_func() {
	case "$1" in
		dvd)
		DEVTYPE="DVD"
		DEVSYM="/dev/dvd*"
		DEVOPT="-dvd-device"
		CONFIGDEV="$DVD_DEVICE"
		DEFAULTDEV="/dev/dvd"
		;;
		bd)
		DEVTYPE="Blu-ray"
		DEVSYM="/dev/dvd*"
		DEVOPT="-bluray-device"
		CONFIGDEV="$BLURAY_DEVICE"
		DEFAULTDEV="/dev/dvd"
		;;
		vcd)
		DEVTYPE="CD-ROM"
		DEVSYM="/dev/cdrom* /dev/cdrw*"
		DEVOPT="-cdrom-device"
		CONFIGDEV="$CDROM_DEVICE"
		DEFAULTDEV="/dev/cdrom"
		;;
	esac
	echo
	if [ -r /proc/sys/dev/cdrom/info ]; then
		DRIVE=$(grep 'drive name' /proc/sys/dev/cdrom/info | sed 's|drive name:||g')
		if [ ! -z "$DRIVE" ]; then
			for i in $DRIVE; do
				green "-> Found device: /dev/$i"
			done
		fi
	else
		error "-> Could not detect the $DEVTYPE device(s)!"
	fi
	for i in $DEVSYM; do
		if [ -L $i ]; then
			green "-> Found symbolic link to $DEVTYPE device: $(ls -l $i | grep -o '/dev.*')"
		fi
	done
	if [ ! -z "$CONFIGDEV" ]; then
		if [ ! -b "$CONFIGDEV" ]; then
			error "-> Invalid block device '$CONFIGDEV' in the config file!"
			echo
			exit_func 1
		fi
		green "-> Using device '$CONFIGDEV' specified in the config file"
		device="$DEVOPT $CONFIGDEV"
	else
		echo
		printf "Specify the $DEVTYPE Device [default is $DEFAULTDEV]: "
		read -e dev
		if [ -z "$dev" ]; then
			device="$DEVOPT $DEFAULTDEV"
		else
			if [ ! -e "$dev" ]; then
				error "-> No such device/file/directory!"
				exit_func 1
			else
				device="$DEVOPT $dev"
			fi
		fi
	fi
}

case "$1" in
	"")
	echo "Usage: h264enc <options>"
	echo "Quick start: h264enc <passmode> -p <preset> [-t <tune>] [-pf <profile>]"
	echo "Use 'h264enc -h' for more information"
	exit_func 1
	;;
	-v)
	echo "h264enc $version"
	exit_func 0
	;;
	-h)
	echo
	brown "+=======================================================+"
	brown "|     h264enc - the interactive shell script ripper     |"
	brown "+=======================================================+"
	echo
	echo "h264enc is a small script which uses the encoding utility"
	echo "MEncoder from MPlayer to encode a DVD or a video file to"
	echo "the high-quality H.264 video format [also known as Advanced Video"
	echo "Coding (AVC) or MPEG-4 Part 10]"
	echo "Note: this script requires MEncoder version 1.0rc2 or higher!"
	echo "For more information, read the man page of h264enc (man h264enc)"
	echo "or visit its official Web site at http://h264enc.sourceforge.net"
	echo
	brown "Options"
	brown "~~~~~~~"
	echo " $(green "-1p")        Encode in one pass mode"
	echo
	echo " $(green "-2p")        Encode in two pass mode"
	echo
	echo " $(green "-3p")        Encode in three pass mode"
	echo
	echo " $(green "-qp")        Encode in fixed-quant mode"
	echo
	echo " $(green "-crf")       Encode in constant rate factor mode"
	echo
	green " <passmode> -p <preset> [-t <tune>] [-pf <profile>]"
	echo
	echo "            Use a predefined H.264 quality preset, where <passmode> is"
	echo "            the desired encoding mode (-1p or -2p or -3p or -qp or -crf)"
	echo "            and <preset> is the desired preset to use (see below). Note"
	echo "            that the -t and -pf options only work with the x264 presets"
	echo "            below! See examples at the end of this option."
	echo
	echo "            PC Presets"
	echo "            ~~~~~~~~~~"
	echo "            cp --------> Load a custom preset file (see example below)"
	echo "            ulq -------> Ultra Low Quality preset"
	echo "            elq -------> Extreme Low Quality preset"
	echo "            vlq -------> Very Low Quality preset"
	echo "            lq --------> Low Quality preset"
	echo "            mq --------> Medium Quality preset"
	echo "            nq --------> Normal Quality preset"
	echo "            hq --------> High Quality preset (recommended)"
	echo "            vhq -------> Very High Quality preset (recommended)"
	echo "            ehq -------> Extreme High Quality preset (recommended)"
	echo "            uhq -------> Ultra High Quality preset"
	echo "            ihq -------> Insane High Quality preset"
	echo "            nlq -------> Near Lossless Quality preset"
	echo "            fghq ------> Film Grain optimized High Quality preset"
	echo "            ani -------> Anime preset"
	echo "            anihq -----> Anime High Quality preset"
	echo "            vdhq ------> VDPAU/DXVA High Quality (High@L4.1) preset"
	echo "            vdehq -----> VDPAU/DXVA Extreme High Quality (High@L4.1) preset"
	echo "            vdihq -----> VDPAU/DXVA Insane High Quality (High@L4.1) preset"
	echo
	echo "            Software Compatible Presets"
	echo "            ~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "            fl --------> Flash Player preset"
	echo "            flhq ------> Flash Player High Quality preset"
	echo "            qt --------> QuickTime preset"
	echo "            qthq ------> QuickTime High Quality preset"
	echo
	echo "            Device Presets"
	echo "            ~~~~~~~~~~~~~~"
	echo "            bd40 ------> Blu-ray (Main@L4.0) preset"
	echo "            bdhq40 ----> Blu-ray High Quality (High@L4.0) preset"
	echo "            bd41 ------> Blu-ray (Main@L4.1) preset"
	echo "            bdhq41 ----> Blu-ray High Quality (High@L4.1) preset"
	echo "            avchd -----> AVCHD (Main@L4.0) preset"
	echo "            avchdhq ---> AVCHD High Quality (High@L4.1) preset"
	echo "            ag1 -------> Android G1 preset"
	echo "            ag1hq -----> Android G1 High Quality preset"
	echo "            ipc -------> Apple iPod Classic preset"
	echo "            ipchq -----> Apple iPod Classic High Quality preset"
	echo "            ip --------> Apple iPod preset"
	echo "            iphq ------> Apple iPod High Quality preset"
	echo "            iph -------> Apple iPhone preset"
	echo "            iphhq -----> Apple iPhone High Quality preset"
	echo "            atv -------> AppleTV preset"
	echo "            atvhq -----> AppleTV High Quality preset"
	echo "            ar --------> Archos 605 preset"
	echo "            arhq ------> Archos 605 High Quality preset"
	echo "            ar5 -------> Archos 5 preset"
	echo "            ar5hq -----> Archos 5 High Quality preset"
	echo "            bb --------> Blackberry Bold 9000 preset"
	echo "            bbhq ------> Blackberry Bold 9000 High Quality preset"
	echo "            nks60 -----> Nokia S60 preset"
	echo "            nks60hq ---> Nokia S60 High Quality preset"
	echo "            psp -------> Sony PSP preset"
	echo "            psphq -----> Sony PSP High Quality preset"
	echo "            ps3 -------> Sony PS3 preset"
	echo "            ps3hq -----> Sony PS3 High Quality preset"
	echo "            mz --------> Microsoft Zune preset"
	echo "            mzhq ------> Microsoft Zune High Quality preset"
	echo "            mx --------> Microsoft XBOX 360 preset"
	echo "            mxhq ------> Microsoft XBOX 360 High Quality preset"
	echo
	echo "            x264 Presets    x264 Tune    x264 Profiles"
	echo "            ~~~~~~~~~~~~    ~~~~~~~~~    ~~~~~~~~~~~~~"
	echo "            ultrafast       film         baseline"
	echo "            superfast       animation    main"
	echo "            veryfast        grain        high"
	echo "            faster          stillimage"
	echo "            fast            psnr"
	echo "            medium          ssim"
	echo "            slow            fastdecode"
	echo "            slower          zerolatency"
	echo "            veryslow"
	echo "            placebo"
	echo
	echo "            Example of presets usage: h264enc -2p -p hq"
	echo
	echo "            The above example will encode the DVD/VCD or input video file"
	echo "            in 2-pass mode using the High Quality (HQ) preset"
	echo
	echo "            Load a custom preset from a file:"
	echo "            h264enc -2p -p cp /path/to/file/preset.cfg"
	echo
	echo "            Please have a look at the 'preset.cfg' file inside the"
	echo "            h264enc package to give you an example on how to write"
	echo "            a custom preset. The 'preset.cfg' file is usually located"
	echo "            inside the doc directory of the h264enc package."
	echo
	echo "            Examples of x264 presets/tune/profiles usage:"
	echo "            h264enc -2p -p slow"
	echo "            h264enc -2p -p slow -t film"
	echo "            h264enc -2p -p slow -pf main"
	echo "            h264enc -2p -p slow -t film -pf high"
	echo
	echo "            The first example encodes the input with x264's slow preset."
	echo "            The second one does the same but tunes the encode settings for"
	echo "            film footage. The third example is as the first one but selects"
	echo "            the main H.264 profile and the last example uses both a tuning for"
	echo "            film and selects the high H.264 profile. You can also switch the"
	echo "            -t and -pf options, eg: h264enc -2p -p slow -pf main -t film"
	echo
	green " -b /path/to/file/batchfile"
	echo
	echo "            Load a batch file generated by *this* script. This option"
	echo "            can be used for testing or debugging the encoding parameters"
	echo "            and for batch encoding."
	echo
	echo " $(green "-e")         Edit the config file from within the terminal. This option defaults"
	echo "            to using the 'nano' text editor but one can manually set his"
	echo "            preferred editor in the EDITOR variable of the config file."
	echo "            The config file is located in $H264ENCDIR"
	echo
	echo " $(green "-r")         Reset configuration file. As of version 8.5.7, h264enc uses a"
	echo "            configuration file which contains the paths to the programs"
	echo "            needed for its correct operation. This option tells the script"
	echo "            to remove and recreate the configuration file using the default"
	echo "            values. It can be used to restore the original values of the"
	echo "            config file in case the user has modified it and wants to get"
	echo "            rid of those modifications. It is also used for resetting the"
	echo "            config file in case the user has installed a required program"
	echo "            AFTER h264enc has generated its config file. If this is the case,"
	echo "            the config file will not contain the path to the newly installed"
	echo "            program so one has to reset the file in order to find it. This is"
	echo "            because the config file is generated/updated only once: if it's not"
	echo "            available on the user's system and during config version updates."
	echo "            The configuration file is located in $H264ENCDIR/config"
	echo
	echo " $(green "-sc")        Perform a sanity check. This will check for the programs"
	echo "            required for the correct operation of this script and it"
	echo "            will print the status in a list. It will also display"
	echo "            which audio codecs are supported by MEncoder."
	echo
	echo " $(green "-scan")      Scan the DVD disc/video file and display extensive information"
	echo "            about it. With this option, one can display or export the information"
	echo "            to a file on disk in text, perl, python, ruby or xml format (only"
	echo "            for DVD scans)"
	echo
	echo " $(green "-iso")       Create an ISO image of the DVD disc. Note that this option"
	echo "            does not do any stripping of specific titles, audio languages and/or"
	echo "            subtitles. It dumps the DVD content 1:1 to an ISO image."
	echo
	echo " $(green "-spr")       Calculate the Sample and Pixel Aspect Ratios (SAR/PAR) for"
	echo "            various resolutions."
	echo
	echo " $(green "-mfr")       Calculate the maximum allowed frame references within DPB"
	echo "            (Decoded Picture Buffer) limits for different H.264 levels and resolutions."
	echo
	echo " $(green "-bpp")       This is an informative option which lets you calculate"
	echo "            the Bits Per Pixel (bpp) values for various resolutions."
	echo "            The bpp value represents how much bits each pixel gets. The"
	echo "            higher the bpp value is, the more distinct colors the pixels"
	echo "            will have which leads to a higher overall picture quality."
	echo "            Note that these values are not absolute! For video content"
	echo "            with a lot of black in it, a bpp value of 0.14 may look"
	echo "            very good. Video content with a lot of high motion scenes"
	echo "            may still look bad with a bpp value of 0.20, so this really"
	echo "            depends on the content you are willing to encode and the"
	echo "            video bitrate and resolution you choose when scaling down."
	echo
	echo " $(green "-bpb")       This option is similar to the -bpp one, except it calculates"
	echo "            the Bits Per Block (bpb) values for various resolutions."
	echo "            The bpb value expresses how many bits each 16x16 macroblock"
	echo "            gets. Good bpb values are between 37-52. As is the case with"
	echo "            Bits Per Pixel, the bpb values are not absolute and depend"
	echo "            on the video content you are willing to encode and the"
	echo "            video bitrate and resolution you choose when scaling down."
	echo
	echo " $(green "-v")         Display version of this script and exit"
	echo
	echo " $(green "-h")         Display this help screen and exit"
	echo
	echo
	echo "TIP: if you don't want to use an option, instead of always answering"
	echo "with 'n', just press Enter."
	echo
	echo "For bug reporting, suggestions, comments, questions, or if this script"
	echo "was useful to you, send me an e-mail at <neutrino8@gmail.com>"
	echo
	exit_func 0
	;;
	-bpp|-bpb|-spr|-mfr)
	# Bits per pixel/block, SAR and PAR calculation
	if [ ! -x "$BC" ]; then
		error "-> Checking for 'bc'... FAILED!"
		exit_func 1
	fi
	case "$1" in
		-bpp)
		echo
		brown "+============================+"
		brown "| Bits Per Pixel Calculation |"
		brown "+============================+"
		echo
		;;
		-bpb)
		echo
		brown "+============================+"
		brown "| Bits Per Block Calculation |"
		brown "+============================+"
		echo
		;;
		-spr)
		echo
		brown "+=================================================+"
		brown "| Sample/Pixel Aspect Ratio (SAR/PAR) Calculation |"
		brown "+=================================================+"
		echo
		;;
		-mfr)
		echo
		brown "+==============================================+"
		brown "| Maximum Allowed Frame References Calculation |"
		brown "+==============================================+"
		echo
		;;
	esac
	cal0() {
		echo "scale=0; $1" | $BC -l | sed 's|^\.|0\.|'
	}
	cal4() {
		echo "scale=4; $1" | $BC -l | sed 's|^\.|0\.|'
	}
	round() {
		D_PART=$(echo "$1" | awk -F. '{print $1}')
		F_PART=$(echo "$1" | awk -F. '{print $2}')
		if [ $F_PART -lt 500 ]; then
			echo $D_PART
		else
			echo $[$D_PART+1]
		fi
	}
	printf "Provide the resolution [default is 720x576]: "
	read O_RES
	if [ -z "$O_RES" ]; then
		RES=720x576
		R_ASP=$(cal4 "720/576")
	else
		RES=$O_RES
		R_ASP=$(cal4 $(echo $O_RES | tr '[:alpha:]' '/'))
	fi
	case "$1" in
		-bpp|-bpb)
		printf "Provide the original unscaled but cropped resolution [WxH]: "
		read U_RES
		if [ -z "$U_RES" ]; then
			error "-> Cropped resolution value is required!"
			exit_func 1
		fi
		;;
	esac
	printf "Provide the aspect ratio [16/9, 4/3, 1.3333, 1.7778... - default is 16/9]: "
	read AR
	if [ -z "$AR" ]; then
		A_RAT=16/9
	else
		A_RAT=$AR
	fi
	case "$1" in
		-bpp|-bpb)
		printf "Provide the video bitrate: "
		read V_BTR
		if [ -z "$V_BTR" ]; then
			error "-> Video bitrate is required!"
			exit_func 1
		fi
		printf "Provide the video's FPS value [integer or float - default is 25]: "
		read VFPS
		if [ -z "$VFPS" ]; then
			M_FPS=25
		else
			M_FPS=$VFPS
		fi
		U_WID=$(echo $U_RES | awk -Fx '{print $1}')
		U_HEI=$(echo $U_RES | awk -Fx '{print $2}')
		E_RAT=$(cal4 "$A_RAT")
		S_WID=$(cal0 "$U_WID*$E_RAT/$R_ASP")
		S_HEI=$U_HEI
		P_AR=$(cal4 "$S_WID/$S_HEI")
		;;
		-spr|-mfr)
		U_WID=$(echo $RES | awk -Fx '{print $1}')
		U_HEI=$(echo $RES | awk -Fx '{print $2}')
		E_RAT=$(cal4 "$A_RAT")
		S_WID=$(cal0 "$U_WID*$E_RAT/$R_ASP")
		S_HEI=$U_HEI
		P_AR=$(cal4 "$S_WID/$S_HEI")
		case "$1" in
			-mfr)
			echo
			brown "H.264 Levels"
			brown "~~~~~~~~~~~~"
			echo "0 -> Level 1.0     8 --> Level 3.1"
			echo "1 -> Level 1.1     9 --> Level 3.2"
			echo "2 -> Level 1.2     10 -> Level 4.0"
			echo "3 -> Level 1.3     11 -> Level 4.1"
			echo "4 -> Level 2.0     12 -> Level 4.2"
			echo "5 -> Level 2.1     13 -> Level 5.0"
			echo "6 -> Level 2.2     14 -> Level 5.1"
			echo "7 -> Level 3.0"
			echo
			printf "Select the H.264 Level [default is 11]: "
			read level
			case "$level" in
				0)		DPB=148 ;;
				1)		DPB=337 ;;
				2|3|4)		DPB=891 ;;
				5)		DPB=1782 ;;
				6|7)		DPB=3037 ;;
				8)		DPB=6750 ;;
				9)		DPB=7680 ;;
				10|11|"")	DPB=12288 ;;
				12)		DPB=13056 ;;
				13)		DPB=41400 ;;
				14)		DPB=69120 ;;
				*)
				error "-> No such option!"
				exit_func 1
				;;
			esac
			;;
		esac
		;;
	esac
	echo
	case "$1" in
		-bpp)
		for ((WID=$U_WID; WID>=320; WID=WID-16)); do
			R_H=$(cal4 "$WID/$P_AR/16")
			HEI=$((16*$(round "$R_H")))
			BPP=$(cal4 "1000*$V_BTR/($WID*$HEI*$M_FPS)")
			BITRATE=$(cal0 "($WID*$HEI*$M_FPS*$BPP)/1000")
			PIX=$(($WID*$HEI))
			echo "Resolution: $(green "${WID}x$HEI") -- Total Pixels: $(green "$PIX") -- BPP: $(green $BPP) -- Bitrate based on BPP: $(green "$BITRATE kbps")"
		done
		;;
		-bpb)
		for ((WID=$U_WID; WID>=320; WID=WID-16)); do
			R_H=$(cal4 "$WID/$P_AR/16")
			HEI=$((16*$(round "$R_H")))
			BPB=$(cal4 "$V_BTR*1000/($M_FPS*($WID*$HEI)/(16*16))")
			PIX=$(($WID*$HEI))
			echo "Resolution: $(green "${WID}x$HEI") -- Total Pixels: $(green "$PIX") -- BPB: $(green $BPB)"
		done
		;;
		-spr)
		for ((WID=$U_WID; WID>=320; WID=WID-16)); do
			R_H=$(cal4 "$WID/$P_AR/16")
			HEI=$((16*$(round "$R_H")))
			SAR=$(cal4 "$WID/$HEI")
			PAR=$(cal4 "$E_RAT/$SAR")
			PIX=$(($WID*$HEI))
			echo "Resolution: $(green "${WID}x$HEI") -- Total Pixels: $(green "$PIX") -- SAR: $(green "$SAR:1") -- PAR: $(green "$PAR:1")"
		done
		;;
		-mfr)
		for ((WID=$U_WID; WID>=320; WID=WID-16)); do
			R_H=$(cal4 "$WID/$P_AR/16")
			HEI=$((16*$(round "$R_H")))
			FRCALC=$(cal0 "($DPB*1024/1.5)/($WID*$HEI)")
			if [[ $FRCALC -gt 16 ]]; then
				REFS=16
				BPYREFS=$(($REFS-1))
			else
				REFS=$FRCALC
				if [[ $REFS -eq 0 ]]; then
					BPYREFS=0
				else
					BPYREFS=$(($REFS-1))
				fi
			fi
			echo "Resolution: $(green "${WID}x$HEI") -- Max allowed frame references: $(green "$REFS") -- With b_pyramid=normal: $(green "$BPYREFS")"
		done
		;;
	esac
	echo
	exit_func 0
	;;
	-b)
	if [ -z "$2" ]; then
		error "-> Option '-b' requires an input file!"
		error "-> Use: h264enc -h"
		exit_func 1
	fi
	if [ ! -f "$2" ]; then
		error "-> No such file: '$2'"
		exit_func 1
	fi
	source "$2"
	exit_func 0
	;;
	-e)
	CFGFILE="$H264ENCDIR/config"
	if [ ! -f "$CFGFILE" ]; then
		error "-> config file '$CFGFILE' does not exist!"
		error "-> Run: 'h264enc -r' to create it!"
		exit_func 1
	fi
	if [ -z "$EDITOR" ]; then
		error "-> Variable 'EDITOR' in the config file is empty!"
		error "-> Please manually set your editor in the config file!"
		exit_func 1
	fi
	if [ ! -x "$(which $EDITOR 2>/dev/null)" ]; then
		error "-> Specified text editor '$EDITOR' does not exist!"
		error "-> Either install it or manually set a different"
		error "   one in the config file!"
		exit_func 1
	fi
	$EDITOR $CFGFILE
	exit_func 0
	;;
	-r)
	green "-> Resetting the config file values"
	rm -f $H264ENCDIR/config
	genconfig_func
	exit_func 0
	;;
	-sc)
	echo
	test -x "$MPLAYER" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'MPlayer'..................... $STATUS"
	if [ -x "$MENCODER" ]; then
		echo "-> Checking for 'MEncoder'.................... $(green "OK")"
		test ! -z "$($MENCODER -ovc help 2>/dev/null | awk '{print $1}' | grep 'x264')" && STATUS="$(green "YES")" || STATUS="$(error "NO")"
		echo "-> H.264 video support in MEncoder............ $STATUS"
		test ! -z "$(ldd $MENCODER | grep 'libbluray')" && STATUS="$(green "YES")" || STATUS="$(error "NO")"
		echo "-> Blu-ray support in MEncoder................ $STATUS"
		test ! -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'faac')" && STATUS="$(green "YES")" || STATUS="$(error "NO")"
		echo "-> AAC (FAAC) audio support in MEncoder....... $STATUS"
		test ! -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'mp3lame')" && STATUS="$(green "YES")" || STATUS="$(error "NO")"
		echo "-> MP3 (LAME) audio support in MEncoder....... $STATUS"
		test ! -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'lavc')" && STATUS="$(green "YES")" || STATUS="$(error "NO")"
		echo "-> AC-3 (lavc) audio support in MEncoder...... $STATUS"
		test ! -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'pcm')" && STATUS="$(green "YES")" || STATUS="$(error "NO")"
		echo "-> PCM audio support in MEncoder.............. $STATUS"
	else
		echo "-> Checking for MEncoder...................... $(error "Failed")"
	fi
	echo
	test -x "$X264" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'x264'........................ $STATUS"
	test -x "$BC" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'bc'.......................... $STATUS"
	test -x "$PV" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'pv'.......................... $STATUS"
	test -x "$DD" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'dd'.......................... $STATUS"
	test -x "$MAIL" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'mail'........................ $STATUS"
	test -x "$NEROAACENC" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'neroAacEnc'.................. $STATUS"
	test -x "$FDKAACENC" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'aac-enc'..................... $STATUS"
	test -x "$AACPLUSENC" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'aacplusenc'.................. $STATUS"
	test -x "$AFTEN" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'aften'....................... $STATUS"
	test -x "$OGGENC" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'oggenc'...................... $STATUS"
	test -x "$OPUSENC" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'opusenc'..................... $STATUS"
	test -x "$FLAC" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'flac'........................ $STATUS"
	test -x "$FAAC" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'faac'........................ $STATUS"
	test -x "$DCAENC" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'dcaenc'...................... $STATUS"
	test -x "$(which less 2>/dev/null)" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'less'........................ $STATUS"
	test -x "$LSDVD" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'lsdvd'....................... $STATUS"
	test -x "$DVDXCHAP" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'dvdxchap' (from ogmtools).... $STATUS"
	test -x "$MKVMERGE" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'mkvmerge' (from mkvtoolnix).. $STATUS"
	test -x "$MKVEXTRACT" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'mkvextract'.................. $STATUS"
	test -x "$OGMMERGE" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'ogmmerge' (from ogmtools).... $STATUS"
	test -x "$MP4BOX" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'MP4Box' (from gpac).......... $STATUS"
	test -x "$TSMUXER" && STATUS="$(green "OK")" || STATUS="$(error "Failed")"
	echo "-> Checking for 'tsMuxeR'..................... $STATUS"
	echo
	echo "If you have installed a required program but the script"
	echo "can't find it, run 'h264enc -r' to reset the config file."
	echo
	exit_func 0
	;;
	-scan)
	echo
	printf "Would you like to scan a video file, VCD, DVD or Blu-ray? [file/vcd/dvd/bd]: "
	read scantype
	case "$scantype" in
		file|vcd|bd)
		if [ ! -x "$BC" -o ! -x "$MPLAYER" ]; then
			error "-> bc or mplayer missing!"
			exit_func 1
		fi
		case "$scantype" in
			file)
			demuxer="-demuxer lavf"
			printf "Provide the input video file: "
			read -e infile
			if [ -z "$infile" ]; then
				error "-> No input specified!"
				exit_func 1
			elif [ ! -e "$infile" ]; then
				error "-> No such file: '$infile'"
				exit_func 1
			fi
			echo
			green "-> Scanning the file..."
			;;
			vcd)
			get_devices_func vcd
			devurl="vcd://2"
			echo
			green "-> Scanning the VCD..."
			;;
			bd)
			demuxer="-demuxer lavf -cache 100"
			get_devices_func bd
			devurl="br://"
			echo
			green "-> Scanning the Blu-ray..."
			;;
		esac
		INFO="$TEMPDIR/info$$"
		$MPLAYER "$infile" $devurl $MPLAYEROPTS $device $demuxer -channels 8 $MPOPTS 2>/dev/null > "$INFO"
		echo
		echo "MPlayer Demuxer:   $(grep '^ID_DEMUXER' "$INFO" | tail -n 1 | awk -F= '{print $2}')"
		echo "Video Format:      $(grep '^ID_VIDEO_FORMAT' "$INFO" | awk -F= '{print $2}')"
		echo "Video Bitrate:     $(echo "scale=1; $(grep '^ID_VIDEO_BITRATE' "$INFO" | awk -F= '{print $2}')/1000" | $BC -l) kbps (May not be accurate)"
		echo "Video FPS:         $(grep '^ID_VIDEO_FPS' "$INFO" | awk -F= '{print $2}')"
		echo "Video Resolution:  $(grep '^VIDEO:' "$INFO" | tail -n 1 | awk '{print $3}') ($(($(grep '^VIDEO:' "$INFO" | tail -n 1 | awk '{print $3}' | sed 's|x|*|'))) pixels)"
		echo "Video Aspect:      $(grep '^ID_VIDEO_ASPECT' "$INFO" | tail -n 1 | awk -F= '{print $2}'):1"
		echo "Video SAR:         $(echo "scale=4; $(grep '^VIDEO:' "$INFO" | tail -n 1 | awk '{print $3}' | sed 's|x|/|')" | $BC -l | sed 's|^\.|0\.|'):1"
		echo "Video PAR:         $(echo "scale=4; $(grep '^ID_VIDEO_ASPECT' "$INFO" | tail -n 1 | awk -F= '{print $2}')/($(grep '^VIDEO:' "$INFO" | tail -n 1 | awk '{print $3}' | sed 's|x|/|'))" | $BC -l | sed 's|^\.|0\.|'):1"
		echo "Video Length:      $(grep '^ID_LENGTH' "$INFO" | awk -F= '{print $2}') seconds or $(echo "scale=1; $(grep '^ID_LENGTH' "$INFO" | awk -F= '{print $2}')/60" | $BC -l | sed 's|^\.|0\.|') minutes (May not be accurate)"
		echo "Number Of Frames:  $(echo "scale=0; $(grep '^ID_LENGTH' "$INFO" | awk -F= '{print $2}') * $(grep '^ID_VIDEO_FPS' "$INFO" | awk -F= '{print $2}')" | $BC -l | awk -F. '{print $1}') (May not be accurate)"
		echo
		echo "Audio Codec:       $(grep '^ID_AUDIO_CODEC' "$INFO" | tail -n 1 | awk -F= '{print $2}')"
		echo "Audio Bitrate:     $(($(grep '^ID_AUDIO_BITRATE' "$INFO" | tail -n 1 | awk -F= '{print $2}')/1000)) kbps (May not be accurate)"
		echo "Audio Sample Rate: $(grep '^ID_AUDIO_RATE' "$INFO" | tail -n 1 | awk -F= '{print $2}') Hz"
		echo "Audio Channels:    $(grep '^ID_AUDIO_NCH' "$INFO" | tail -n 1 | awk -F= '{print $2}')"
		echo
		exit_func 0
		;;
		dvd)
		if [ ! -x "$MPLAYER" -o ! -x "$LSDVD" -o ! -x "$(which less 2>/dev/null)" ]; then
			error "-> 'mplayer', 'lsdvd' or 'less' missing!"
			exit_func 1
		fi
		get_devices_func dvd
		echo
		green "-> Unlocking the DVD disc..."
		GET_TITLES="$($MPLAYER dvd://1 $MPLAYEROPTS $device $MPOPTS 2>/dev/null | grep  '^There are *.* titles')"
		TITLE="$(echo $GET_TITLES | awk '{print $3}')"
		green "-> $GET_TITLES"
		green "-> $($LSDVD $(echo $device | awk '{print $2}') 2>/dev/null | grep 'Longest' | sed 's|track:|title:|')"
		echo
		brown "DVD Information Menu"
		brown "~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> Display Audio Streams"
		echo "1 -> Display Cells"
		echo "2 -> Display Angles"
		echo "3 -> Display Chapters"
		echo "4 -> Display Subtitles"
		echo "5 -> Display Palette Info"
		echo "6 -> Display Title/Video Info"
		echo "7 -> Display All Of The Above"
		echo "8 -> Export Info To A File"
		echo "9 -> Exit"
		echo
		printf "Select an option: "
		read option
		case "$option" in
			[0-8]) true ;;
			9) exit_func 0 ;;
			""|*)
			error "-> Option unknown or not specified!"
			exit_func 1
			;;
		esac
		printf "Specify the DVD title [1-$TITLE/all]: "
		read dvd_title
		if [ "$dvd_title" != "all" ]; then
			title="-t $dvd_title"
			titlenum="title$dvd_title"
		else
			title=
			titlenum="alltitles"
		fi
		case "$option" in
			0) $LSDVD $title -a -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			1) $LSDVD $title -d -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			2) $LSDVD $title -n -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			3) $LSDVD $title -c -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			4) $LSDVD $title -s -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			5) $LSDVD $title -P -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			6) $LSDVD $title -v -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			7) $LSDVD $title -x -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			8)
			printf "Which option to export? [0-7/all]: "
			read opt
			case "$opt" in
				0) info="-a" ;;
				1) info="-d" ;;
				2) info="-n" ;;
				3) info="-c" ;;
				4) info="-s" ;;
				5) info="-P" ;;
				6) info="-v" ;;
				7|all) info="-x" ;;
				*|"")
				error "-> Option unknown or not specified!"
				exit_func 1
				;;
			esac
			printf "In which format to export? [text/perl/python/ruby/xml]: "
			read format
			case "$format" in
				text) ext="txt" ;;
				perl) ext="pl" ;;
				python) ext="py" ;;
				ruby) ext="rb" ;;
				xml) ext="xml" ;;
				*|"")
				error "-> Format unsupported or not specified!"
				exit_func 1
				;;
			esac
			DT="$($LSDVD $(echo $device | awk '{print $2}') 2>/dev/null | grep '^Disc Title' | awk -F': ' '{print $2}')"
			if [ ! -z "$DT" ]; then
				DISC_TITLE="$DT"
			else
				DISC_TITLE="DVD"
			fi
			store_func() {
				case "$1" in
					0) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-audiostreams.$ext" ;;
					1) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-cells.$ext" ;;
					2) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-angles.$ext" ;;
					3) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-chapters.$ext" ;;
					4) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-subtitles.$ext" ;;
					5) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-palette.$ext" ;;
					6) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-title+video.$ext" ;;
					7|all) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-allinfo.$ext" ;;
				esac
			}
			info_func() {
				echo
				green "-> Saving to '$EXPORT_FILE'"
				echo
			}
			lsdvd_dev="$(echo $device | awk '{print $2}')"
			case "$format" in
				text)
				store_func $opt
				info_func
				$LSDVD $title $info -Oh "$lsdvd_dev" 2>/dev/null > $EXPORT_FILE
				;;
				perl)
				store_func $opt
				info_func
				$LSDVD $title $info -Op "$lsdvd_dev" 2>/dev/null > $EXPORT_FILE
				;;
				python)
				store_func $opt
				info_func
				$LSDVD $title $info -Oy "$lsdvd_dev" 2>/dev/null > $EXPORT_FILE
				;;
				ruby)
				store_func $opt
				info_func
				$LSDVD $title $info -Or "$lsdvd_dev" 2>/dev/null > $EXPORT_FILE
				;;
				xml)
				store_func $opt
				info_func
				$LSDVD $title $info -Ox "$lsdvd_dev" 2>/dev/null > $EXPORT_FILE
				;;
			esac
			;;
		esac
		exit_func 0
		;;
		*|"")
		error "-> You didn't specify the source"
		exit_func 1
		;;
	esac
	;;
	-iso)
	# DVD ISO dumping. This requiers
	# 'pv' but we fall back to 'dd'
	# if 'pv' is not on the user's
	# system
	if [ ! -x "$BC" -o ! -x "$DD" -o ! -x "$MPLAYER" -o ! -x "$LSDVD" ]; then
		error "-> bc, dd, mplayer or lsdvd missing!"
		exit_func 1
	fi
	interrupt_iso_func() {
		echo
		error "-> Exiting..."
		rm -f "$OUTPUT" 2>/dev/null
		exit_func 2
	}
	trap 'interrupt_iso_func' SIGHUP SIGTSTP SIGINT SIGQUIT SIGKILL SIGABRT SIGFPE SIGSEGV SIGTERM SIGPIPE SIGIO
	check_space_func() {
		HDSPACE="$(df -k "$(dirname "$OUTPUT")" | tail -n 1 | awk '{print $4}')"
		if [ $HDSPACE -le 9437184 ]; then
			echo
			error "-> You are running out of disk space in '$(dirname "$OUTPUT")'"
			error "-> Space left over: $HDSPACE MiB ($(echo "scale=3; $HDSPACE/1024" | $BC -l | sed 's|^\.|0\.|') GiB)"
			error "-> Please provide a different output directory!"
			echo
			exit_func 1
		fi
	}
	echo
	brown "+=======================+"
	brown "| DVD ISO Image Dumping |"
	brown "+=======================+"
	get_devices_func dvd
	echo
	green "-> Unlocking the DVD disc..."
	$MPLAYER dvd://1 $MPLAYEROPTS $device $MPOPTS 2>/dev/null
	green "-> Scanning for DVD title name..."
	TITLE="$($LSDVD $(echo $device | awk '{print $2}') 2>/dev/null | grep '^Disc Title' | awk -F': ' '{print $2}')"
	if [ ! -z "$TITLE" ]; then
		OUT="$HOME/$TITLE.iso"
	else
		OUT="$HOME/DVD-$$.iso"
	fi
	test -e "$OUT" && mv -f "$OUT" "$OUT.old"
	echo
	printf "Specify the Output for the ISO image [default is $OUT]: "
	read -e iso_out
	if [ -z "$iso_out" ]; then
		OUTPUT="$OUT"
		check_space_func
	else
		if [ -z "$(echo $iso_out | grep '^/')" ]; then
			error "-> You have to provide the full path!"
			exit_func 1
		fi
		test -d "$(dirname "$iso_out")" || mkdir -p "$(dirname "$iso_out")" 2>/dev/null
		OUTPUT="$iso_out"
		check_space_func
	fi
	echo
	green "-> Available disk space: $HDSPACE MiB ($(echo "scale=3; $HDSPACE/1024" | $BC -l) GiB)"
	green "-> Dumping disc content to ISO image, please wait..."
	green "-> This can take a while..."
	echo
	if [ -x "$PV" ]; then
		$PV "$(echo $device | awk '{print $2}')" > "$OUTPUT"
	else
		$DD if="$(echo $device | awk '{print $2}')" bs=2048 conv=noerror,sync of="$OUTPUT" 2>/dev/null
	fi
	green "-> Done"
	echo
	exit_func 0
	;;
	-[1-3]p|-qp|-crf)
	case "$2" in
		-p)
		case "$3" in
			ulq|elq|vlq|lq|mq|nq|hq|vhq|ehq|uhq|ihq|nlq|fghq|ani|anihq|vdhq|vdehq|vdihq|fl|flhq|qt|qthq|bd40|bdhq40|bd41|bdhq41|avchd|avchdhq|ag1|ag1hq|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|psp|psphq|ps3|ps3hq|mz|mzhq|mx|mxhq)
			true
			;;
			ultrafast|superfast|veryfast|faster|fast|medium|slow|slower|veryslow|placebo)
			true
			;;
			cp)
			if [ -z "$4" ]; then
				error "-> You have to load a custom preset file!"
				error "-> Use: h264enc $1 -p cp /path/to/file/preset.cfg"
				exit_func 1
			fi
			if [ ! -f "$4" ]; then
				error "-> No such file: '$4'"
				exit_func 1
			fi
			;;
			"")
			error "-> No preset specified!"
			error "-> Use: 'h264enc -h'"
			exit_func 1
			;;
			*)
			error "-> Unknown preset: '$3'"
			error "-> Use: 'h264enc -h'"
			exit_func 1
			;;
		esac
		;;
		"")
		error "-> No preset specified!"
		error "-> Use: 'h264enc -h'"
		exit_func 1
		;;
		*)
		error "-> Unknown option: '$2'"
		error "-> Use: 'h264enc -h'"
		exit_func 1
		;;
	esac
	;;
	*)
	error "-> Unknown option: '$1'"
	error "-> Use: 'h264enc -h'"
	exit_func 1
	;;
esac

case "$MAX_AMOUNT_AUD_TRACKS" in
	[1-9]*|auto) true ;;
	*)
	error "-> Please check the value of 'MAX_AMOUNT_AUD_TRACKS' in '$H264ENCDIR/config'"
	exit_func 1
	;;
esac

case "$MAX_AMOUNT_SUBS" in
	[1-9]*|auto) true ;;
	*)
	error "-> Please check the value of 'MAX_AMOUNT_SUBS' in '$H264ENCDIR/config'"
	exit_func 1
	;;
esac

case "$MAX_AMOUNT_EXT_SUBS" in
	[a-zA-Z]*|0|"")
	error "-> Please check the value of 'MAX_AMOUNT_EXT_SUBS' in '$H264ENCDIR/config'"
	exit_func 1
	;;
esac

# x264 tune/profile
case "$4" in
	-t|-pf)
	case "$5" in
		film|animation|grain|stillimage|psnr|ssim|fastdecode|zerolatency)
		x264tune=":tune=$5"
		;;
		baseline|main|high)
		x264profile=":profile=$5"
		;;
		"")
		error "-> No tune or profile setting specified!"
		error "-> Use: 'h264enc -h'"
		exit_func 1
		;;
		*)
		error "-> Unknown tune or profile setting: '$5'"
		error "-> Use: 'h264enc -h'"
		exit_func 1
		;;
	esac
	;;
	"") true ;;
	*)
	if [ "$3" != "cp" ]; then
		error "-> Unknown option: '$4'"
		error "-> Use: 'h264enc -h'"
		exit_func 1
	fi
	;;
esac

case "$6" in
	-t|-pf)
	case "$7" in
		film|animation|grain|stillimage|psnr|ssim|fastdecode|zerolatency)
		x264tune=":tune=$7"
		;;
		baseline|main|high)
		x264profile=":profile=$7"
		;;
		"")
		error "-> No tune or profile setting specified!"
		error "-> Use: 'h264enc -h'"
		exit_func 1
		;;
		*)
		error "-> Unknown tune or profile setting: '$7'"
		error "-> Use: 'h264enc -h'"
		exit_func 1
		;;
	esac
	;;
	"") true ;;
	*)
	if [ "$3" != "cp" ]; then
		error "-> Unknown option: '$6'"
		error "-> Use: 'h264enc -h'"
		exit_func 1
	fi
	;;
esac

# The NLQ preset is suppored only in
# fixed-quant mode! Check and warn user
# about that.

if [ "$3" = "nlq" ]; then
	if [ "$1" != "-crf" ]; then
		error "-> The Near Lossless Quality (NLQ) preset is only supported in CRF mode!"
		error "-> Use: h264enc -crf -p nlq"
		exit_func 1
	fi
fi

# Some portable device presets are
# not supported in -qp/-crf mode.

case "$3" in
	ag1|ag1hq|ipc|ipchq|ip|iphq|iph|iphhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|psp|psphq|mz|mzhq)
	if [ "$1" = "-qp" -o "$1" = "-crf" ]; then
		error "-> The '$3' preset is only supported in 1-, 2-, or 3-pass encoding mode!"
		exit_func 1
	fi
	;;
esac

# Informative function for displaying
# the selected quality preset
display_quality_preset_func() {
	case "$1" in
		cp)		green "-> Using custom preset file: '$2'" ;;
		ulq)		green "-> Using \"Ultra Low Quality\" preset" ;;
		elq)		green "-> Using \"Extreme Low Quality\" preset" ;;
		vlq)		green "-> Using \"Very Low Quality\" preset" ;;
		lq)		green "-> Using \"Low Quality\" preset" ;;
		mq)		green "-> Using \"Medium Quality\" preset" ;;
		nq)		green "-> Using \"Normal Quality\" preset" ;;
		hq)		green "-> Using \"High Quality\" preset" ;;
		vhq)		green "-> Using \"Very High Quality\" preset" ;;
		ehq)		green "-> Using \"Extreme High Quality\" preset" ;;
		uhq)		green "-> Using \"Ultra High Quality\" preset" ;;
		ihq)		green "-> Using \"Insane High Quality\" preset" ;;
		nlq)		green "-> Using \"Near Lossless Quality\" preset" ;;
		fghq)		green "-> Using \"Film Grain optimized High Quality\" preset" ;;
		ani)		green "-> Using \"Anime\" preset" ;;
		anihq)		green "-> Using \"Anime High Quality\" preset" ;;
		vdhq)		green "-> Using \"VDPAU/DXVA High Quality (High@L4.1)\" preset" ;;
		vdehq)		green "-> Using \"VDPAU/DXVA Extreme High Quality (High@L4.1)\" preset" ;;
		vdihq)		green "-> Using \"VDPAU/DXVA Insane High Quality (High@L4.1)\" preset" ;;
		fl)		green "-> Using \"Flash Player\" preset" ;;
		flhq)		green "-> Using \"Flash Player High Quality\" preset" ;;
		qt)		green "-> Using \"QuickTime\" preset" ;;
		qthq)		green "-> Using \"QuickTime High Quality\" preset" ;;
		bd40)		green "-> Using \"Blu-ray (Main@L4.0)\" preset" ;;
		bdhq40)		green "-> Using \"Blu-ray High Quality (High@L4.0)\" preset" ;;
		bd41)		green "-> Using \"Blu-ray (Main@L4.0)\" preset" ;;
		bdhq41)		green "-> Using \"Blu-ray High Quality (High@L4.1)\" preset" ;;
		avchd)		green "-> Using \"AVCHD (Main@L4.0)\" preset" ;;
		avchdhq)	green "-> Using \"AVCHD High Quality (High@L4.1)\" preset" ;;
		ag1)		green "-> Using \"Android G1\" preset" ;;
		ag1hq)		green "-> Using \"Android G1 High Quality\" preset" ;;
		ipc)		green "-> Using \"Apple iPod Classic\" preset" ;;
		ipchq)		green "-> Using \"Apple iPod Classic High Quality\" preset" ;;
		ip)		green "-> Using \"Apple iPod\" preset" ;;
		iphq)		green "-> Using \"Apple iPod High Quality\" preset" ;;
		iph)		green "-> Using \"Apple iPhone\" preset" ;;
		iphhq)		green "-> Using \"Apple iPhone High Quality\" preset" ;;
		atv)		green "-> Using \"AppleTV\" preset" ;;
		atvhq)		green "-> Using \"AppleTV High Quality\" preset" ;;
		ar)		green "-> Using \"Archos 605\" preset" ;;
		arhq)		green "-> Using \"Archos 605 High Quality\" preset" ;;
		ar5)		green "-> Using \"Archos 5\" preset" ;;
		ar5hq)		green "-> Using \"Archos 5 High Quality\" preset" ;;
		bb)		green "-> Using \"Blackberry 9000\" preset" ;;
		bbhq)		green "-> Using \"Blackberry 9000 High Quality\" preset" ;;
		nks60)		green "-> Using \"Nokia S60\" preset" ;;
		nks60hq)	green "-> Using \"Nokia S60 High Quality\" preset" ;;
		psp)		green "-> Using \"Sony PSP\" preset" ;;
		psphq)		green "-> Using \"Sony PSP High Quality\" preset" ;;
		ps3)		green "-> Using \"Sony PS3\" preset" ;;
		ps3hq)		green "-> Using \"Sony PS3 High Quality\" preset" ;;
		mz)		green "-> Using \"Microsoft Zune\" preset" ;;
		mzhq)		green "-> Using \"Microsoft Zune High Quality\" preset" ;;
		mx)		green "-> Using \"Microsoft XBOX 360\" preset" ;;
		mxhq)		green "-> Using \"Microsoft XBOX 360\" preset" ;;
		ultrafast)	green "-> Using \"x264 ultrafast\" preset" ;;
		superfast)	green "-> Using \"x264 superfast\" preset" ;;
		veryfast)	green "-> Using \"x264 veryfast\" preset" ;;
		faster)		green "-> Using \"x264 faster\" preset" ;;
		fast)		green "-> Using \"x264 fast\" preset" ;;
		medium)		green "-> Using \"x264 medium\" preset" ;;
		slow)		green "-> Using \"x264 slow\" preset" ;;
		slower)		green "-> Using \"x264 slower\" preset" ;;
		veryslow)	green "-> Using \"x264 veryslow\" preset" ;;
		placebo)	green "-> Using \"x264 placebo\" preset" ;;
	esac
}

###########################################
############## Requirements ###############
###########################################

if [ ! -x "$BC" ]; then
	error "-> Checking for utility 'bc'... FAILED!"
	exit_func 1
fi

if [ ! -x "$MENCODER" ]; then
	error "-> Checking for MEncoder... FAILED!"
	exit_func 1
fi

if [ -z "$($MENCODER -ovc help 2>/dev/null | awk '{print $1}' | grep 'x264')" ]; then
	error "-> Checking for libx264 support in MEncoder... FAILED!"
	error "-> Download libx264 and recompile MPlayer"
	exit_func 1
fi

if [ ! -x "$MPLAYER" ]; then
	error "-> Checking for MPlayer... FAILED!"
	exit_func 1
fi

#####################################################################
#### Video functions shared by both DVD and video file encodings ####
#####################################################################
#
# Video filters that come before the 'scale' filter
# must have a , (comma) appended at their end.
# Video filters that come after the 'scale' filter,
# must be preceded by a , (comma).
#

# Frame rate selection for
# frame doubling deinterlace
# filters. Kicks only in effect
# if the script couldn't detect
# a supported FPS value or if
# we deal with NTSC content.
deint_custom_fps_func() {
	echo
	brown "Deinterlace Frame Rate Selection"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 --> Silent Film @ 31.97 fps (2*16000/1001)"
	echo "1 --> Silent Film @ 35.96 fps (2*18000/1001)"
	echo "2 --> Film @ 48 fps (2*24)"
	echo "3 --> PAL/SECAM @ 50 fps (2*25)"
	echo "4 --> PAL/SECAM @ 100 fps (2*50)"
	echo "5 --> PAL/SECAM @ 200 fps (2*100)"
	echo "6 --> NTSC @ 47.95 fps (2*24000/1001)"
	echo "7 --> NTSC @ 59.94 fps (2*30000/1001)"
	echo "8 --> NTSC @ 60 fps (2*30)"
	echo "9 --> NTSC @ 119.88 fps (2*60000/1001)"
	echo "10 -> NTSC @ 239.76 fps (2*120000/1001)"
	echo
	printf "Select the Deinterlace double frame rate [no default!]: "
	read dfr
	case "$dfr" in
		0) deintfps="32000/1001"; deintofps="32000/1001" ;;
		1) deintfps="36000/1001"; deintofps="36000/1001" ;;
		2) deintfps="48"; deintofps="48" ;;
		3) deintfps="50"; deintofps="50" ;;
		4) deintfps="100"; deintofps="100" ;;
		5) deintfps="200"; deintofps="200" ;;
		6) deintfps="48000/1001"; deintofps="48000/1001" ;;
		7) deintfps="60000/1001"; deintofps="60000/1001" ;;
		8) deintfps="60"; deintofps="60" ;;
		9) deintfps="120000/1001"; deintofps="120000/1001" ;;
		10) deintfps="240000/1001"; deintofps="240000/1001" ;;
		""|*)
		error "-> Option unknown or deinterlace frame rate not specified!"
		error "-> Exiting in function: deint_custom_fps_func()"
		exit_func 1
		;;
	esac
}

# Detect the source FPS value
# of the content. This function
# is used by the deinterlace and
# interlace functions
source_fps_func() {
	echo
	green "-> Detecting source FPS value..."
	$MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid $MPOPTS 2>/dev/null > "$TEMPDIR/sourcefps"
	SOURCEFPS=$(grep '^ID_VIDEO_FPS' "$TEMPDIR/sourcefps" | tail -n 1 | awk -F= '{print $2}')
	rm -f "$TEMPDIR/sourcefps"
	case "$1" in
		deinthalf)
		calc_fps_func() {
			green "-> Setting input/output frame rate to $(echo "scale=3; $deintfps" | $BC -l)/$(echo "scale=3; $deintofps" | $BC -l) FPS"
			green "-> Using '$(echo $deintfilter | sed 's|,$||')' video filters"
		}
		;;
		deintdouble)
		calc_fps_func() {
			green "-> Setting input/output frame rate to $(echo "scale=3; $SOURCEFPS*2" | $BC -l) FPS"
			green "-> Using '$(echo $deintfilter | sed 's|,$||')' video filter(s)"
		}
		;;
		interlace)
		calc_fps_func() {
			green "-> Setting input/output frame rate to $(echo "scale=3; $intfps" | $BC -l)/$(echo "scale=3; $intofps" | $BC -l) FPS"
			green "-> Using '$(echo $intfilter | sed 's|^,||')' video filter(s)"
			echo
		}
		;;
	esac
}

# Deinterlacing function
video_deinterlace_func() {
	int=$(get_selection_func "Is the $type Interlaced? [y/N]: ")
	if [ "$int" = "y" ]; then
		preint=$(get_selection_func "Would you like to Preserve the Interlacing? [y/N]: ")
		if [ "$preint" = "y" ]; then
			# Turn on interlace-aware mode in libx264 and add
			# the ilpack filter to correctly align chroma
			printf "Specify the Interlace field order [tff/bff - default is tff]: "
			read int_order
			case "$int_order" in
				tff|"")	interlaced=":tff:pic_struct" ;;
				bff)	interlaced=":bff:pic_struct" ;;
				*)
				error "-> Unknown interlace option!"
				error "-> Exiting in function: video_deinterlace_func()"
				exit_func 1
				;;
			esac
			ilpack="ilpack=1,"
			# Ask if the user will be using denoise/deblock filters
			# so we can deinterleave the content, apply the denoising,
			# deblocking and interleave the content. This way we can
			# process the content without breaking the interlacing
			ddbc=$(get_selection_func "Will you be using Denoise/Deblock filters later on? [y/N]: ")
			if [ "$ddbc" = "y" ]; then
				ild="il=d,"
				ili="il=i,"
			fi
		else
			interlaced=":nointerlaced"
			echo
			brown "Deinterlace Methods"
			brown "~~~~~~~~~~~~~~~~~~~"
			echo "0 -> Deinterlace at half frame rate"
			echo "1 -> Deinterlace at original frame rate"
			echo "2 -> Deinterlace at double frame rate (bobbing)"
			echo "3 -> Skip deinterlacing"
			echo
			printf "Select the deinterlacing method [default is 1]: "
			read deintmethod
			case "$deintmethod" in
				0)
				echo
				brown "Available Deinterlacing Filters @ Half FPS"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "0 --> Linear Blend Deinterlacer"
				echo "1 --> Linear Interpolating Deinterlacer"
				echo "2 --> Cubic Interpolating Deinterlacer"
				echo "3 --> Median Deinterlacer"
				echo "4 --> FFmpeg Deinterlacer"
				echo "5 --> FIR Lowpass 5 Deinterlacer"
				echo "6 --> Donald Graft's Adaptive Kernel Deinterlacer"
				echo "7 --> Yadif Deinterlacer"
				echo "8 --> Fast Yadif Deinterlacer"
				echo "9 --> Yadif & Linear Blend"
				echo "10 -> Yadif & Linear Interpolation"
				echo "11 -> Yadif & Cubic Interpolation"
				echo "12 -> Yadif & Median deint"
				echo "13 -> Yadif & FFmpeg deint"
				echo "14 -> Yadif & FIR Lowpass 5"
				echo
				printf "Select a deinterlacing filter [default is 7]: "
				read dfilter
				case "$dfilter" in
					0) deintfilter="pp=lb,framestep=2," ;;
					1) deintfilter="pp=li,framestep=2," ;;
					2) deintfilter="pp=ci,framestep=2," ;;
					3) deintfilter="pp=md,framestep=2," ;;
					4) deintfilter="pp=fd,framestep=2," ;;
					5) deintfilter="pp=l5,framestep=2," ;;
					6)
					printf "Specify the deinterlacing threshold [0-255 - default is 5]: "
					read kerntres
					if [ -z "$kerntres" ]; then
						deintfilter="kerndeint=5,framestep=2,"
					else
						deintfilter="kerndeint=$kerntres,framestep=2,"
					fi
					;;
					7|"") deintfilter="yadif=0,framestep=2,"; field_dominance="-field-dominance -1" ;;
					8) deintfilter="yadif=2,framestep=2,"; field_dominance="-field-dominance -1" ;;
					9) deintfilter="yadif=0,pp=lb,framestep=2,"; field_dominance="-field-dominance -1" ;;
					10) deintfilter="yadif=0,pp=li,framestep=2,"; field_dominance="-field-dominance -1" ;;
					11) deintfilter="yadif=0,pp=ci,framestep=2,"; field_dominance="-field-dominance -1" ;;
					12) deintfilter="yadif=0,pp=md,framestep=2,"; field_dominance="-field-dominance -1" ;;
					13) deintfilter="yadif=0,pp=fd,framestep=2,"; field_dominance="-field-dominance -1" ;;
					14) deintfilter="yadif=0,pp=l5,framestep=2,"; field_dominance="-field-dominance -1" ;;
					*)
					error "-> Unknown option: '$dfilter'"
					error "-> Exiting in function: video_deinterlace_func()"
					exit_func 1
					;;
				esac
				source_fps_func deinthalf
				case "$SOURCEFPS" in
					50.00|50.000)
					deintfps="50"
					deintofps="25"
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Double)"
					calc_fps_func
					echo
					;;
					59.94|59.940)
					deintfps="60000/1001"
					deintofps="30000/1001"
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					echo
					;;
					60.00|60.000)
					deintfps="60"
					deintofps="30"
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					echo
					;;
					"")
					error "-> Could not detect the FPS value"
					error "-> Exiting in function: video_deinterlace_func()"
					echo
					exit_func 1
					;;
					*)
					green "-> Detected $SOURCEFPS FPS"
					error "-> Only 50/59.940/60 FPS are supported!"
					error "-> Exiting in function: video_deinterlace_func()"
					echo
					exit_func 1
					;;
				esac
				;;
				1|"")
				echo
				brown "Available Deinterlacing Filters @ Original FPS"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "0 --> Linear Blend Deinterlacer"
				echo "1 --> Linear Interpolating Deinterlacer"
				echo "2 --> Cubic Interpolating Deinterlacer"
				echo "3 --> Median Deinterlacer"
				echo "4 --> FFmpeg Deinterlacer"
				echo "5 --> FIR Lowpass 5 Deinterlacer"
				echo "6 --> Donald Graft's Adaptive Kernel Deinterlacer"
				echo "7 --> Yadif Deinterlacer"
				echo "8 --> Fast Yadif Deinterlacer"
				echo "9 --> Yadif & Linear Blend"
				echo "10 -> Yadif & Linear Interpolation"
				echo "11 -> Yadif & Cubic Interpolation"
				echo "12 -> Yadif & Median deint"
				echo "13 -> Yadif & FFmpeg deint"
				echo "14 -> Yadif & FIR Lowpass 5"
				echo "15 -> Yadif & Fast Mcdeint (top fields)"
				echo "16 -> Yadif & Fast Mcdeint (bottom fields)"
				echo "17 -> Fast Yadif & Fast Mcdeint (top fields)"
				echo "18 -> Fast Yadif & Fast Mcdeint (bottom fields)"
				echo "19 -> Yadif & Medium Mcdeint (top fields)"
				echo "20 -> Yadif & Medium Mcdeint (bottom fields)"
				echo "21 -> Fast Yadif & Medium Mcdeint (top fields)"
				echo "22 -> Fast Yadif & Medium Mcdeint (bottom fields)"
				echo "23 -> Yadif & Slow Mcdeint (top fields)"
				echo "24 -> Yadif & Slow Mcdeint (bottom fields)"
				echo "25 -> Fast Yadif & Slow Mcdeint (top fields)"
				echo "26 -> Fast Yadif & Slow Mcdeint (bottom fields)"
				echo "27 -> Yadif & Slowest Mcdeint (top fields)"
				echo "28 -> Yadif & Slowest Mcdeint (bottom fields)"
				echo "29 -> Fast Yadif & Slowest Mcdeint (top fields)"
				echo "30 -> Fast Yadif & Slowest Mcdeint (bottom fields)"
				echo "31 -> Tfields"
				echo "32 -> Tfields & Fast Mcdeint (top fields)"
				echo "33 -> Tfields & Fast Mcdeint (bottom fields)"
				echo "34 -> Tfields & Medium Mcdeint (top fields)"
				echo "35 -> Tfields & Medium Mcdeint (bottom fields)"
				echo "36 -> Tfields & Slow Mcdeint (top fields)"
				echo "37 -> Tfields & Slow Mcdeint (bottom fields)"
				echo "38 -> Tfields & Slowest Mcdeint (top fields)"
				echo "39 -> Tfields & Slowest Mcdeint (bottom fields)"
				echo
				echo "Tip: Yadif is a good fast general purpose deinterlacer. If you"
				echo "     deal with sports, then the Linear blend deinterlacer may"
				echo "     be preferrable. Yadif & Mcdeint and Tfields & Mcdeint give"
				echo "     the best results but are pretty slow."
				echo
				printf "Select a deinterlacing filter [default is 7]: "
				read dfilter
				case "$dfilter" in
					0) deintfilter="pp=lb," ;;
					1) deintfilter="pp=li," ;;
					2) deintfilter="pp=ci," ;;
					3) deintfilter="pp=md," ;;
					4) deintfilter="pp=fd," ;;
					5) deintfilter="pp=l5," ;;
					6)
					printf "Specify the deinterlacing threshold [0-255 - default is 5]: "
					read kerntres
					if [ -z "$kerntres" ]; then
						deintfilter="kerndeint=5,"
					else
						deintfilter="kerndeint=$kerntres,"
					fi
					;;
					7|"") deintfilter="yadif=0,"; field_dominance="-field-dominance -1" ;;
					8) deintfilter="yadif=2,"; field_dominance="-field-dominance -1" ;;
					9) deintfilter="yadif=0,pp=lb," field_dominance="-field-dominance -1" ;;
					10) deintfilter="yadif=0,pp=li," field_dominance="-field-dominance -1" ;;
					11) deintfilter="yadif=0,pp=ci," field_dominance="-field-dominance -1" ;;
					12) deintfilter="yadif=0,pp=md," field_dominance="-field-dominance -1" ;;
					13) deintfilter="yadif=0,pp=fd," field_dominance="-field-dominance -1" ;;
					14) deintfilter="yadif=0,pp=l5," field_dominance="-field-dominance -1" ;;
					15) deintfilter="yadif=1,mcdeint=0:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					16) deintfilter="yadif=1,mcdeint=0:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					17) deintfilter="yadif=3,mcdeint=0:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					18) deintfilter="yadif=3,mcdeint=0:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					19) deintfilter="yadif=1,mcdeint=1:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					20) deintfilter="yadif=1,mcdeint=1:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					21) deintfilter="yadif=3,mcdeint=1:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					22) deintfilter="yadif=3,mcdeint=1:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					23) deintfilter="yadif=1,mcdeint=2:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					24) deintfilter="yadif=1,mcdeint=2:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
					25) deintfilter="yadif=3,mcdeint=2:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					26) deintfilter="yadif=3,mcdeint=2:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
					27) deintfilter="yadif=1,mcdeint=3:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					28) deintfilter="yadif=1,mcdeint=3:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
					29) deintfilter="yadif=3,mcdeint=3:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					30) deintfilter="yadif=3,mcdeint=3:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
					31) deintfilter="tfields=4,framestep=2,"; field_dominance="-field-dominance -1" ;;
					32) deintfilter="tfields=4,mcdeint=0:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					33) deintfilter="tfields=4,mcdeint=0:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					34) deintfilter="tfields=4,mcdeint=1:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					35) deintfilter="tfields=4,mcdeint=1:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					36) deintfilter="tfields=4,mcdeint=2:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					37) deintfilter="tfields=4,mcdeint=2:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
					38) deintfilter="tfields=4,mcdeint=3:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					39) deintfilter="tfields=4,mcdeint=3:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
					*)
					error "-> Unknown option: '$dfilter'"
					error "-> Exiting in function: video_deinterlace_func()"
					exit_func 1
					;;
				esac
				;;
				2)
				quiet="2>/dev/null"
				echo
				brown "Available Deinterlacing Filters @ Double FPS"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "0 --> Yadif Deinterlacer"
				echo "1 --> Fast Yadif Deinterlacer"
				echo "2 --> Yadif & Fast Mcdeint (top fields)"
				echo "3 --> Yadif & Fast Mcdeint (bottom fields)"
				echo "4 --> Fast Yadif & Fast Mcdeint (top fields)"
				echo "5 --> Fast Yadif & Fast Mcdeint (bottom fields)"
				echo "6 --> Yadif & Medium Mcdeint (top fields)"
				echo "7 --> Yadif & Medium Mcdeint (bottom fields)"
				echo "8 --> Fast Yadif & Medium Mcdeint (top fields)"
				echo "9 --> Fast Yadif & Medium Mcdeint (bottom fields)"
				echo "10 -> Yadif & Slow Mcdeint (top fields)"
				echo "11 -> Yadif & Slow Mcdeint (bottom fields)"
				echo "12 -> Fast Yadif & Slow Mcdeint (top fields)"
				echo "13 -> Fast Yadif & Slow Mcdeint (bottom fields)"
				echo "14 -> Yadif & Slowest Mcdeint (top fields)"
				echo "15 -> Yadif & Slowest Mcdeint (bottom fields)"
				echo "16 -> Fast Yadif & Slowest Mcdeint (top fields)"
				echo "17 -> Fast Yadif & Slowest Mcdeint (bottom fields)"
				echo "18 -> Tfields (top fields)"
				echo "19 -> Tfields (bottom fields)"
				echo "20 -> Tfields & Fast Mcdeint (top fields)"
				echo "21 -> Tfields & Fast Mcdeint (bottom fields)"
				echo "22 -> Tfields & Medium Mcdeint (top fields)"
				echo "23 -> Tfields & Medium Mcdeint (bottom fields)"
				echo "24 -> Tfields & Slow Mcdeint (top fields)"
				echo "25 -> Tfields & Slow Mcdeint (bottom fields)"
				echo "26 -> Tfields & Slowest Mcdeint (top fields)"
				echo "27 -> Tfields & Slowest Mcdeint (bottom fields)"
				echo
				printf "Select a deinterlacing filter [default is 0]: "
				read dfilter
				case "$dfilter" in
					0|"") deintfilter="yadif=1,"; field_dominance="-field-dominance -1" ;;
					1) deintfilter="yadif=3,"; field_dominance="-field-dominance -1" ;;
					2) deintfilter="yadif=1,mcdeint=0:0:10,"; field_dominance="-field-dominance 0" ;;
					3) deintfilter="yadif=1,mcdeint=0:1:10,"; field_dominance="-field-dominance 1" ;;
					4) deintfilter="yadif=3,mcdeint=0:0:10,"; field_dominance="-field-dominance 0" ;;
					5) deintfilter="yadif=3,mcdeint=0:1:10,"; field_dominance="-field-dominance 1" ;;
					6) deintfilter="yadif=1,mcdeint=1:0:10,"; field_dominance="-field-dominance 0" ;;
					7) deintfilter="yadif=1,mcdeint=1:1:10,"; field_dominance="-field-dominance 1" ;;
					8) deintfilter="yadif=3,mcdeint=1:0:10,"; field_dominance="-field-dominance 0" ;;
					9) deintfilter="yadif=3,mcdeint=1:1:10,"; field_dominance="-field-dominance 1" ;;
					10) deintfilter="yadif=1,mcdeint=2:0:10,"; field_dominance="-field-dominance 0" ;;
					11) deintfilter="yadif=1,mcdeint=2:1:10,"; field_dominance="-field-dominance 1" ;;
					12) deintfilter="yadif=3,mcdeint=2:0:10,"; field_dominance="-field-dominance 0" ;;
					13) deintfilter="yadif=3,mcdeint=2:1:10,"; field_dominance="-field-dominance 1" ;;
					14) deintfilter="yadif=1,mcdeint=3:0:10,"; field_dominance="-field-dominance 0" ;;
					15) deintfilter="yadif=1,mcdeint=3:1:10,"; field_dominance="-field-dominance 1" ;;
					16) deintfilter="yadif=3,mcdeint=3:0:10,"; field_dominance="-field-dominance 0" ;;
					17) deintfilter="yadif=3,mcdeint=3:1:10,"; field_dominance="-field-dominance 1" ;;
					18) deintfilter="tfields=4,"; field_dominance="-field-dominance 0" ;;
					19) deintfilter="tfields=4,"; field_dominance="-field-dominance 1" ;;
					20) deintfilter="tfields=4,mcdeint=0:0:10,"; field_dominance="-field-dominance 0" ;;
					21) deintfilter="tfields=4,mcdeint=0:1:10,"; field_dominance="-field-dominance 1" ;;
					22) deintfilter="tfields=4,mcdeint=1:0:10,"; field_dominance="-field-dominance 0" ;;
					23) deintfilter="tfields=4,mcdeint=1:1:10,"; field_dominance="-field-dominance 1" ;;
					24) deintfilter="tfields=4,mcdeint=2:0:10,"; field_dominance="-field-dominance 0" ;;
					25) deintfilter="tfields=4,mcdeint=2:1:10,"; field_dominance="-field-dominance 1" ;;
					26) deintfilter="tfields=4,mcdeint=3:0:10,"; field_dominance="-field-dominance 0" ;;
					27) deintfilter="tfields=4,mcdeint=3:1:10,"; field_dominance="-field-dominance 1" ;;
					*)
					error "-> Unknown option: '$dfilter'"
					error "-> Exiting in function: video_deinterlace_func()"
					exit_func 1
					;;
				esac
				source_fps_func deintdouble
				case "$SOURCEFPS" in
					15.98[4-5]|15.98)
					deintfps="32000/1001"
					deintofps="32000/1001"
					green "-> Detected $SOURCEFPS FPS (Silent Film)"
					calc_fps_func
					echo
					;;
					17.982|17.98)
					deintfps="36000/1001"
					deintofps="36000/1001"
					green "-> Detected $SOURCEFPS FPS (Silent Film)"
					calc_fps_func
					echo
					;;
					24.000|24.00)
					deintfps="48"
					deintofps="48"
					green "-> Detected $SOURCEFPS FPS (Film)"
					calc_fps_func
					echo
					;;
					25.000|25.00)
					deintfps="50"
					deintofps="50"
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Film/Video)"
					calc_fps_func
					echo
					;;
					50.000|50.00)
					deintfps="100"
					deintofps="100"
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Double)"
					calc_fps_func
					echo
					;;
					100.000|100.00)
					deintfps="200"
					deintofps="200"
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Quad)"
					calc_fps_func
					echo
					;;
					23.976|23.97)
					deintfps="48000/1001"
					deintofps="48000/1001"
					green "-> Detected $SOURCEFPS FPS (NTSC Film)"
					calc_fps_func
					echo
					;;
					29.970|29.97)
					set_manual=yes
					deintfps="60000/1001"
					deintofps="60000/1001"
					green "-> Detected $SOURCEFPS FPS (NTSC Video)"
					calc_fps_func
					green "-> Note: NTSC FPS detection is not 100% reliable!"
					echo
					;;
					30.000|30.00)
					deintfps="60"
					deintofps="60"
					green "-> Detected $SOURCEFPS FPS (NTSC Video)"
					calc_fps_func
					echo
					;;
					59.940|59.94)
					deintfps="120000/1001"
					deintofps="120000/1001"
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					echo
					;;
					60.000|60.00)
					deintfps="120"
					deintofps="120"
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					echo
					;;
					119.880|119.88)
					deintfps="240000/1001"
					deintofps="240000/1001"
					green "-> Detected $SOURCEFPS FPS (NTSC Quad)"
					calc_fps_func
					echo
					;;
					""|*)
					green "-> Could not detect a supported frame rate!"
					green "-> You have to set it manually!"
					deint_custom_fps_func
					;;
				esac
				# Offer the user an option to set the
				# fps manually as detection of NTSC
				# is not very reliable! Damn the NTSC
				# crapware!
				if [ "$set_manual" = "yes" ]; then
					printf "Continue (c) with the current setting or set FPS manually (m)? [c/m]: "
					read cfpsm
					case "$cfpsm" in
						c|C) true ;;
						m|M) deint_custom_fps_func ;;
						""|*)
						error "-> Option unknown or not specified!"
						error "-> Exiting in function: video_deinterlace_func()"
						exit_func 1
						;;
					esac
				fi
				;;
				3)
				true
				;;
				*)
				error "-> Unknown deinterlace method: '$deintmethod'"
				error "-> Exiting in function: video_deinterlace_func()"
				exit_func 1
				;;
			esac
		fi
	else
		interlaced=":nointerlaced"
	fi
}

# Video interlacing.
video_interlace_func() {
	if [ -z "$deintfilter" -a "$interlaced" = ":nointerlaced"  ]; then
		intenc=$(get_selection_func "Would you like to Interlace the encoding? [y/N]: ")
		if [ "$intenc" = "y" ]; then
			interlaced=":interlaced:pic_struct"
			echo
			brown "Interlace Field And Frame Orders"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "With the filters below, one can produce interlaced"
			echo "content out of progressive one. Note that only progressive"
			echo "PAL 50 and 100 fps and progressive NTSC 59.94 and 119.88"
			echo "fps content is supported as input! After the encoding is"
			echo "done, you will either have 25 or 50 fps interlaced PAL or"
			echo "29.97 or 59.94 fps interlaced NTSC encode."
			echo
			echo "0 -> Top field first order + odd frames output"
			echo "1 -> Top field first order + even frames output"
			echo "2 -> Bottom field first order + odd frames output"
			echo "3 -> Bottom field first order + even frames output"
			echo "4 -> Capture unknown/varying (auto) + odd frames output"
			echo "5 -> Capture unknown/varying (auto) + even frames output"
			echo "6 -> Auto-select by field flags + odd frames output"
			echo "7 -> Auto-select by field flags + even frames output"
			echo "8 -> Interleave even lines from even frames with odd"
			echo "     lines from odd frames"
			echo "9 -> Skip interlacing"
			echo
			printf "Select the Interlacing method [default is 1]: "
			read intmeth
			case "$intmeth" in
				0) intfilter=",phase=t,tinterlace=1" ;;
				1|"") intfilter=",phase=t,tinterlace=2" ;;
				2) intfilter=",phase=b,tinterlace=1" ;;
				3) intfilter=",phase=b,tinterlace=2" ;;
				4) intfilter=",phase=u,tinterlace=1" ;;
				5) intfilter=",phase=u,tinterlace=2" ;;
				6) intfilter=",phase=a,tinterlace=1" ;;
				7) intfilter=",phase=a,tinterlace=2" ;;
				8) intfilter=",tinterlace=4" ;;
				9) interlaced=":nointerlaced" ;;
				*)
				error "-> Unknown interlace option: '$intmeth'"
				error "-> Exiting in function: video_interlace_func()"
				exit_func 1
				;;
			esac
			case "$intmeth" in
				[0-8]|"")
				quiet="2>/dev/null"
				source_fps_func interlace
				case "$SOURCEFPS" in
					50.000|50.00)
					intfps="50"
					intofps="25"
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Double)"
					calc_fps_func
					;;
					100.000|100.00)
					intfps="100"
					intofps="50"
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Quad)"
					calc_fps_func
					;;
					59.940|59.94)
					intfps="60000/1001"
					intofps="30000/1001"
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					;;
					60.000|60.00)
					intfps="60"
					intofps="30"
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					;;
					119.880|119.88)
					intfps="120000/1001"
					intofps="60000/1001"
					green "-> Detected $SOURCEFPS FPS (NTSC Quad)"
					calc_fps_func
					;;
					"")
					error "-> Could not detect the source FPS value!"
					error "-> Exiting in function: video_interlace_func()"
					echo
					exit_func 1
					;;
					*)
					error "-> The detected source FPS ($SOURCEFPS) is not supported!"
					error "-> Supported frame rates are: 50/100/59.940/60/119.880 FPS"
					error "-> Exiting in function: video_interlace_func()"
					echo
					exit_func 1
					;;
				esac
				;;
			esac
		fi
	fi
}

# Postprocessing
video_deblock_func() {
	db=$(get_selection_func "Would you like to Deblock/Dering the $type? [y/N]: ")
	if [ "$db" = "y" ]; then
		echo
		brown "Postprocessing Deblock/Dering Filters"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "The filters below have tunable parameters."
		echo "Higher values will filter the content more"
		echo "but can also introduce too much blurring"
		echo "and/or smear it. Note to only use deblocking"
		echo "filters if your $type shows blocking artifacts"
		echo
		echo "0 -> spp:  Simple postprocessing filter"
		echo "1 -> uspp: Ultra simple/slow postprocessing filter"
		echo "2 -> fspp: Fast simple postprocessing filter"
		echo "3 -> pp7:  Variant of spp with 7 points DCT"
		echo "4 -> ha/va/dr: Deblock/dering postprocessing filters"
		echo "5 -> ha/va: Deblock postprocessing filters"
		echo "6 -> dr: Dering postprocessing filter"
		echo "7 -> Skip postprocessing"
		echo
		printf "Select a Deblock/Dering filter [default is 0]: "
		read dbfilter
		case "$dbfilter" in
			0|"")
			printf "Specify the Quality level [0-6 - default is 3]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				deblockfilter="spp=3,"
			else
				deblockfilter="spp=$dbqlevel,"
			fi
			;;
			1)
			printf "Specify the Quality level [0-8 - default is 2]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				deblockfilter="uspp=2,"
			else
				deblockfilter="uspp=$dbqlevel,"
			fi
			;;
			2)
			printf "Specify the Quality level [0-6 - default is 4]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				deblockfilter="fspp=4,"
			else
				deblockfilter="fspp=$dbqlevel,"
			fi
			;;
			3)
			printf "Specify the Quality Quantization parameter [0-31 - default is 3]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				deblockfilter="pp7=3,"
			else
				deblockfilter="pp7=$dbqlevel,"
			fi
			;;
			4)
			echo
			brown "ha/va/dr deblock/dering filters"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "The 'ha' and 'va' filters are the old"
			echo "postprocessing deblock filters. Both share"
			echo "two threshold values. The first value is"
			echo "the difference factor where a higher value"
			echo "will do more deblocking. The second value"
			echo "is the flatness threshold where a lower"
			echo "value will do more deblocking. The 'dr'"
			echo "filter is the deringing filter. The format"
			echo "is as follows: difference:flatness"
			echo
			printf "Specify the Difference and Flatness values [default is 164:7]: "
			read dfv
			if [ -z "$dfv" ]; then
				deblockfilter="pp=ha:164:7:c/va:c/dr:c,"
			else
				deblockfilter="pp=ha:$dfv:c/va:c/dr:c,"
			fi
			;;
			5)
			echo
			brown "ha/va deblocking filters"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "The 'ha' and 'va' filters are the old"
			echo "postprocessing deblock filters. Both share"
			echo "two threshold values. The first value is"
			echo "the difference factor where a higher value"
			echo "will do more deblocking. The second value"
			echo "is the flatness threshold where a lower"
			echo "value will do more deblocking. The format"
			echo "is as follows: difference:flatness"
			echo
			printf "Specify the Difference and Flatness values [default is 164:7]: "
			read dfv
			if [ -z "$dfv" ]; then
				deblockfilter="pp=ha:164:7:c/va:c,"
			else
				deblockfilter="pp=ha:$dfv:c/va:c,"
			fi
			;;
			6)
			deblockfilter="pp=dr:c,"
			;;
			7)
			true
			;;
			*)
			error "-> Unknown deblock/dering option: '$dbfilter'"
			error "-> Exiting in function: video_deblock_func()"
			exit_func 1
			;;
		esac
	fi
}

# Postprocessing
video_delogo_func() {
	db=$(get_selection_func "Would you like to Delogo the $type? [y/N]: ")
	if [ "$db" = "y" ]; then
		HANDLE="$TEMPDIR/fifofile"
		wd=10
		hd=10
		xd=10
		yd=10
		wv=25
		hv=25
		xv=1
		yv=1
		mkfifo "$HANDLE"
		$MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid -ao null -quiet -slave -input file="$HANDLE" -vf rectangle="$wv":"$hv":"$xv":"$yv" >/dev/null 2>&1 &
		while [ 0 ]; do
			echo
			brown "Delogo Video Filter"
			brown "~~~~~~~~~~~~~~~~~~~"
			echo "Suppresses a TV station logo by a simple" 
			echo "interpolation of the surrounding pixels." 
			echo "Just set a rectangle covering the logo"
			echo "and watch it disappear (and sometimes" 
			echo "something even uglier appear - your mileage"
			echo "may vary)."
			echo "Specify the positon and size:"
			echo
			echo "0 -> Change X-Pos."
			echo "1 -> Change Y-Pos."
			echo "2 -> Change Width"
			echo "3 -> Change Height"
			echo "4 -> Finish"
			echo
			printf "Select a Delogo function: "
			read delogoval
			case "$delogoval" in
				0)
				while [ 0 ]; do
					clear
					echo
					brown "Delogo Video Filter - X-Position"
					brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
					printf "Change X-Pos=$xv  [default is $xd, q to finish]: "
					read v
					if [ -z "$v" ]; then
						v=$xd
					elif [ "$v" = "q" -o "$v" = "Q" ]; then
						break;
					fi
					xd=$v
					let xv=$xv+$v
					echo "change_rectangle 2 $v" >> $HANDLE
				done
				;;
				1)
				while [ 0 ]; do
					clear
					echo
					brown "Delogo Video Filter - Y-Position"
					brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
					printf "Change Y-Pos=$yv  [default is $yd, q to finish]: "
					read v
					if [ -z "$v" ]; then
						v=$yd
					elif [ "$v" = "q" -o "$v" = "Q" ]; then
						break;
					fi
					yd=$v
					let yv=$yv+$v
					echo "change_rectangle 3 $v" >> $HANDLE
				done
				;;
				2)
				while [ 0 ]; do
					clear
					echo
					brown "Delogo Video Filter - Width"
					brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
					printf "Change Width=$wv  [default is $wd, q to finish]: "
					read v
					if [ -z "$v" ]; then
						v=$wd
					elif [ "$v" = "q" -o "$v" = "Q" ]; then
						break;
					fi
					wd=$v
					let wv=$wv+$v
					echo "change_rectangle 0 $v" >> $HANDLE
				done
				;;
				3)
				while [ 0 ]; do
					clear
					echo
					brown "Delogo Video Filter - Height"
					brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
					printf "Change Height=$hv  [default is $hd, q to finish]: "
					read v
					if [ -z "$v" ]; then
						v=$hd
					elif [ "$v" = "q" -o "$v" = "Q" ]; then
						break;
					fi
					hd=$v
					let hv=$hv+$v
					echo "change_rectangle 1 $v" >> $HANDLE
				done
				;;
				4)
				break;
				;;
			esac
		done
		echo "quit" >> $HANDLE
		delogofilter="delogo=$xv:$yv:$wv:$hv:1,"
	fi
}

# Denoising
video_denoise_func() {
	denoise=$(get_selection_func "Would you like to Denoise the $type? [y/N]: ")
	if [ "$denoise" = "y" ]; then
		echo
		brown "3D Denoiser                     HQ 3D Denoiser"
		brown "~~~~~~~~~~~                     ~~~~~~~~~~~~~~"
		echo "0 --> denoise3d: weak           5 --> hqdn3d: weak"
		echo "1 --> denoise3d: medium         6 --> hqdn3d: medium"
		echo "2 --> denoise3d: strong         7 --> hqdn3d: strong"
		echo "3 --> denoise3d: extra strong   8 --> hqdn3d: extra strong"
		echo "4 --> denoise3d: user defined   9 --> hqdn3d: user defined"
		echo
		brown "Overcomplete Wavelet Denoiser   Temporal Denoiser"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   ~~~~~~~~~~~~~~~~~"
		echo "10 -> ow: weak                  15 -> tn: weak"
		echo "11 -> ow: medium                16 -> tn: medium"
		echo "12 -> ow: strong                17 -> tn: strong"
		echo "13 -> ow: extra strong          18 -> tn: extra strong"
		echo "14 -> ow: user defined          19 -> tn: user defined"
		echo
		brown "             x264 Internal Denoiser"
		brown "             ~~~~~~~~~~~~~~~~~~~~~~"
		echo "              20 -> x264: weak"
		echo "              21 -> x264: medium"
		echo "              22 -> x264: strong"
		echo "              23 -> x264: extra strong"
		echo "              24 -> x264: user defined"
		echo "              25 -> Skip denoising"
		echo
		printf "Select a Denoise filter and strength [default is 6]: "
		read dnfilt
		case "$dnfilt" in
			0) denoisefilter="denoise3d=3:2:5," ;;
			1) denoisefilter="denoise3d=4:3:6," ;;
			2) denoisefilter="denoise3d=7:6:9," ;;
			3) denoisefilter="denoise3d=10:9:12," ;;
			4)
			printf "Specify the Denoise values [default is 3:2:4]: "
			read dnvalues
			if [ -z "$dnvalues" ]; then
				denoisefilter="denoise3d=3:2:4,"
			else
				denoisefilter="denoise3d=$dnvalues,"
			fi
			;;
			5) denoisefilter="hqdn3d=3:2:5," ;;
			6|"") denoisefilter="hqdn3d=4:3:6," ;;
			7) denoisefilter="hqdn3d=7:6:9," ;;
			8) denoisefilter="hqdn3d=10:9:12," ;;
			9)
			printf "Specify the Denoise values [default is 3:2:4]: "
			read dnvalues
			if [ -z "$dnvalues" ]; then
				denoisefilter="hqdn3d=3:2:4,"
			else
				denoisefilter="hqdn3d=$dnvalues,"
			fi
			;;
			10) denoisefilter="ow=3:1.2:1.2," ;;
			11) denoisefilter="ow=6:1.2:1.2," ;;
			12) denoisefilter="ow=9:1.2:1.2," ;;
			13) denoisefilter="ow=12:1.2:1.2," ;;
			14)
			printf "Specify the Denoise values [default is 5:1.2:1.2]: "
			read dnvalues
			if [ -z "$dnvalues" ]; then
				denoisefilter="ow=5:1.2:1.2,"
			else
				denoisefilter="ow=$dnvalues,"
			fi
			;;
			15) denoisefilter="pp=tn:32:64:128:c," ;;
			16) denoisefilter="pp=tn:64:128:256:c," ;;
			17) denoisefilter="pp=tn:128:256:512:c," ;;
			18) denoisefilter="pp=tn:256:512:1024:c," ;;
			19)
			printf "Specify the Denoise values [default is 64:128:256]: "
			read dnvalues
			if [ -z "$dnvalues" ]; then
				denoisefilter="pp=tn:64:128:256:c,"
			else
				denoisefilter="pp=tn:$dnvalues:c,"
			fi
			;;
			20) nr=":nr=250" ;;
			21) nr=":nr=600" ;;
			22) nr=":nr=1200" ;;
			23) nr=":nr=2400" ;;
			24)
			printf "Specify the Denoise value [0-100000 - default is 300]: "
			read dnvalues
			if [ -z "$dnvalues" ]; then
				nr=":nr=300"
			else
				nr=":nr=$dnvalues"
			fi
			;;
			25) true ;;
			*)
			error "-> Unknown denoise option: '$dnfilt'"
			error "-> Exiting in function: video_denoise_func()"
			exit_func 1
			;;
		esac
	fi
}

# Noise filter
video_noise_func() {
	if [ -z "$denoisefilter" -a -z "$nr" ]; then
		noise=$(get_selection_func "Would you like to add Noise to the $type? [y/N]: ")
		if [ "$noise" = "y" ]; then
			echo
			brown "Noise Types"
			brown "~~~~~~~~~~~"
			echo "u -> Uniform noise"
			echo "t -> Temporal noise"
			echo "a -> Averaged temporal noise"
			echo "h -> High quality"
			echo "p -> Mix random noise with a (semi)regular pattern"
			echo
			echo "Example of filter's usage: 8ha:2t"
			echo
			echo "The first value sets the Luma amount and noise type(s)"
			echo "while the second one does so for Chroma. The Luma/Chroma"
			echo "ranges are between 0 and 100 with 0 completely disabling"
			echo "filtering on the Luma and/or Chroma planes. Mixing different"
			echo "types of noise is possible as shown in the above example."
			echo
			printf "Specify the Noise filter parameters [press 'Enter' to skip]: "
			read noiseparam
			if [ ! -z "$noiseparam" ]; then
				noisefilter=",noise=$noiseparam"
			fi
		fi
	fi
}

video_rotate_func() {
	rotate=$(get_selection_func "Would you like to Rotate the $type? [y/N]: ")
	if [ "$rotate" = "y" ]; then
		echo
		brown "Video Rotation"
		brown "~~~~~~~~~~~~~~"
		echo "0 -> Rotate by 90 degrees clockwise and flip"
		echo "1 -> Rotate by 90 degrees clockwise"
		echo "2 -> Rotate by 90 degrees counterclockwise"
		echo "3 -> Rotate by 90 degrees counterclockwise and flip"
		echo
		printf "Specify how to rotate the video [press 'Enter' to skip]: "
		read vidrotate
		if [ ! -z "$vidrotate" ]; then
			rotatefilter=",rotate=$vidrotate"
		fi
	fi
}	

# Debanding filter
video_deband_func() {
	deband=$(get_selection_func "Would you like to Deband the $type? [y/N]: ")
	if [ "$deband" = "y" ]; then
		printf "Specify the Deband filter strength and radius [default is 1.2:16]: "
		read debandparam
		if [ -z "$debandparam" ]; then
			debandfilter="gradfun=1.2:16,"
		else
			debandfilter="gradfun=$debandparam,"
		fi
	fi
}

# (Un)sharp mask/gaussian blur
# video filter
video_unsharp_func() {
	sharpblur=$(get_selection_func "Would you like to Sharpen or Blur the $type? [y/N]: ")
	if [ "$sharpblur" = "y" ]; then
		echo
		brown "(Un)sharp Mask/Gaussian Blur Video Filter"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "With the '(un)sharp mask / gaussian blur' filter"
		echo "one can sharpen or blur the content. The filter"
		echo "can operate only on the Luma (light) components,"
		echo "only on the Chroma (color) components or on both"
		echo "at the same time. It is recommended to use very"
		echo "small values or the content will become too sharp"
		echo "or too blurry. The sane range for the amount of blur"
		echo "or sharpness to add to the image is between -1.50 and"
		echo "1.50. Negative values will blur the image, positive"
		echo "values will sharpen the image. A value of 0.00 (or 0"
		echo "or 0.0) will disable filtering. The filter also uses"
		echo "an odd-sized matrix which defines its operating area"
		echo "in width and height. Below are the recommended"
		echo "matrices one can choose from. Small matrix sizes"
		echo "are usually better, but this depends on the source."
		echo
		echo "0 -> Luma 3x3 matrix     6 --> Chroma 3x3 matrix"
		echo "1 -> Luma 5x5 matrix     7 --> Chroma 5x5 matrix"
		echo "2 -> Luma 7x7 matrix     8 --> Chroma 7x7 matrix"
		echo "3 -> Luma 9x9 matrix     9 --> Chroma 9x9 matrix"
		echo "4 -> Luma 11x11 matrix   10 -> Chroma 11x11 matrix"
		echo "5 -> Luma 13x11 matrix   11 -> Chroma 13x11 matrix"
		echo
		echo "         12 -> Luma & Chroma 3x3 matrix"
		echo "         13 -> Luma & Chroma 5x5 matrix"
		echo "         14 -> Luma & Chroma 7x7 matrix"
		echo "         15 -> Luma & Chroma 9x9 matrix"
		echo "         16 -> Luma & Chroma 11x11 matrix"
		echo "         17 -> Luma & Chroma 13x11 matrix"
		echo "         18 -> Skip sharpen/blur"
		echo
		printf "Select the Filtering Mode and Matrix Size [default is 13]: "
		read fmms
		case "$fmms" in
			[0-5])
			printf "Specify the amount of Luma filtering [default is 0.00]: "
			read lumafilt
			if [ -z "$lumafilt" ]; then
				lumavalue="0.00"
			else
				lumavalue="$lumafilt"
			fi
			case "$fmms" in
				0) unsharpfilter=",unsharp=l3x3:$lumavalue" ;;
				1) unsharpfilter=",unsharp=l5x5:$lumavalue" ;;
				2) unsharpfilter=",unsharp=l7x7:$lumavalue" ;;
				3) unsharpfilter=",unsharp=l9x9:$lumavalue" ;;
				4) unsharpfilter=",unsharp=l11x11:$lumavalue" ;;
				5) unsharpfilter=",unsharp=l13x11:$lumavalue" ;;
			esac
			;;
			[6-9]|1[0-1])
			printf "Specify the amount of Chroma filtering [default is 0.00]: "
			read chromafilt
			if [ -z "$chromafilt" ]; then
				chromavalue="0.00"
			else
				chromavalue="$chromafilt"
			fi
			case "$fmms" in
				6) unsharpfilter=",unsharp=c3x3:$chromavalue" ;;
				7) unsharpfilter=",unsharp=c5x5:$chromavalue" ;;
				8) unsharpfilter=",unsharp=c7x7:$chromavalue" ;;
				9) unsharpfilter=",unsharp=c9x9:$chromavalue" ;;
				10) unsharpfilter=",unsharp=c11x11:$chromavalue" ;;
				11) unsharpfilter=",unsharp=c13x11:$chromavalue" ;;
			esac
			;;
			1[2-7]|"")
			printf "Specify the amount of Luma filtering [default is 0.00]: "
			read lumafilt
			if [ -z "$lumafilt" ]; then
				lumavalue="0.00"
			else
				lumavalue="$lumafilt"
			fi
			printf "Specify the amount of Chroma filtering [default is 0.00]: "
			read chromafilt
			if [ -z "$chromafilt" ]; then
				chromavalue="0.00"
			else
				chromavalue="$chromafilt"
			fi
			case "$fmms" in
				12) unsharpfilter=",unsharp=l3x3:$lumavalue:c3x3:$chromavalue" ;;
				13|"") unsharpfilter=",unsharp=l5x5:$lumavalue:c5x5:$chromavalue" ;;
				14) unsharpfilter=",unsharp=l7x7:$lumavalue:c7x7:$chromavalue" ;;
				15) unsharpfilter=",unsharp=l9x9:$lumavalue:c9x9:$chromavalue" ;;
				16) unsharpfilter=",unsharp=l11x11:$lumavalue:c11x11:$chromavalue" ;;
				17) unsharpfilter=",unsharp=l13x11:$lumavalue:c13x11:$chromavalue" ;;
			esac
			;;
			18)
			true
			;;
			*)
			error "-> Unknown filtering mode and matrix option: '$fmms'"
			error "-> Exiting in function: video_unsharp_func()"
			exit_func 1
			;;
		esac
	fi
}

# Automatic brightness/contrast
# control function
video_brightness_func() {
	abc=$(get_selection_func "Would you like to use Automatic Brightness/Contrast? [y/N]: ")
	if [ "$abc" = "y" ]; then
		echo
		brown "Automatic Brightness/Contrast Control"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> Luminance-only control"
		echo "1 -> Chrominance-only control"
		echo "2 -> Luminance & Chrominance control"
		echo "3 -> Skip automatic brightness/contrast"
		echo
		printf "Select the Automatic brightness/contrast control [default is 2]: "
		read abcc
		case "$abcc" in
			0) brightnessfilter="pp=al:y," ;;
			1) brightnessfilter="pp=al:n," ;;
			2|"") brightnessfilter="pp=al:c," ;;
			3) true ;;
			*)
			error "-> Unknown brightness/contrast option: '$abcc'"
			error "-> Exiting in function: video_brightness_func()"
			exit_func 1
			;;
		esac
	fi
}

# Software EQ filter. Mutually
# exclusive with the above one
video_equalizer_func() {
	if [ -z "$brightnessfilter" ]; then
		softeq=$(get_selection_func "Would you like to use the Software Equalizer filter? [y/N]: ")
		if [ "$softeq" = "y" ]; then
			echo
			brown "Video Software Equalizer Filter"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "The eq2 software equalizer filter operates just like"
			echo "hardware equalizers. In addition to simple brightness"
			echo "and contrast adjustments, it also allows for gamma and"
			echo "saturation corrections. If you're not familiar with"
			echo "its parameters, I suggest consulting the man page of"
			echo "MPlayer and look for the eq2 filter."
			echo
			echo "The format is as follows:"
			echo "gamma:contrast:brightness:saturation:rg:gg:bg:weight"
			echo
			printf "Specify the eq2 values [default is filter defaults]: "
			read eq2
			if [ -z "$eq2" ]; then
				eq2filter=",eq2"
			else
				eq2filter=",eq2=$eq2"
			fi
		fi
	fi
}

# Colorspace conversion. Can only
# be used when the user is scaling
# the content as this filter needs
# the 'scale' filter to do the real
# colorspace conversion. Don't ask
# for colorspace conversion if we
# use a deinterlacer or are
# interlacing progressive content
# as it does not work with these
# filters
video_colorspace_func() {
	if [ -z "$deintfilter" -a -z "$intfilter" ]; then
		csconv=$(get_selection_func "Would you like to perform a Colorspace conversion? [y/N]: ")
		if [ "$csconv" = "y" ]; then
			echo
			brown "Colorspace Formats"
			brown "~~~~~~~~~~~~~~~~~~"
			echo "0 --> 444P (YUV444P - Planar)"
			echo "1 --> 422P (YUV422P - Planar)"
			echo "2 --> 411P (YUV411P - Planar)"
			echo "3 --> YUY2 (YUYV422 - Packed)"
			echo "4 --> UYVY (UYVY422 - Packed)"
			echo "5 --> YVU9 (YUV410P - Planar)"
			echo "6 --> IF09 (YUV410P - Planar)"
			echo "7 --> YV12 (YUV420P - Planar)"
			echo "8 --> I420 (YUV420P - Planar)"
			echo "9 --> Y800 (Gray - Planar)"
			echo "10 -> Skip colorspace conversion"
			echo
			printf "Select a Colorspace format [default is 7]: "
			read csp
			case "$csp" in
				0) colorspacefilter="format=444p," ;;
				1) colorspacefilter="format=422p," ;;
				2) colorspacefilter="format=411p," ;;
				3) colorspacefilter="format=yuy2," ;;
				4) colorspacefilter="format=uyvy," ;;
				5) colorspacefilter="format=yvu9," ;;
				6) colorspacefilter="format=if09," ;;
				7|"") colorspacefilter="format=yv12," ;;
				8) colorspacefilter="format=i420," ;;
				9) colorspacefilter="format=y800," ;;
				10) true ;;
				*)
				error "-> Unknown colorspace option: '$csp'"
				error "-> Exiting in function: video_colorspace_func()"
				exit_func 1
				;;
			esac
		fi
	fi
}

# Subtitles
get_subtitles_func() {
	echo
	green "-> Scanning for subtitles..."
	case "$1" in
		dvd)
		$MPLAYER "$sourcetype" $MPLAYEROPTS $device $MPOPTS 2>/dev/null > "$TEMPDIR/subs"
		SUBS="$(grep '^subtitle' "$TEMPDIR/subs" | sed -e 's|^subtitle ||g' -e 's|( sid ):|Subtitle ID:|g' -e 's|language:|- Language:|g')"
		;;
		file|dir|vcd)
		$MPLAYER "$sourcetype" $MPLAYEROPTS $device -demuxer lavf $MPOPTS 2>/dev/null > "$TEMPDIR/subs"
		SUBS="$(grep '^\[lavf\]' "$TEMPDIR/subs" | grep -o 'subtitle.*' | sed 's| -sid| ID|g')"
		;;
	esac
	rm -f "$TEMPDIR/subs"
	echo
	brown "Available Subtitles On Disc"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	if [ ! -z "$SUBS" ]; then
		SUBT="$(echo "$SUBS" | wc -l)"
		green "$SUBS"
	else
		SUBT="0"
		error "-> No subtitles available or failed to detect them!"
	fi
	if [ "$MAX_AMOUNT_SUBS" = "auto" ]; then
		if [ "$SUBT" = "0" ]; then
			MAX_AMOUNT_SUBS="2"
		else
			MAX_AMOUNT_SUBS="$SUBT"
		fi
	fi
	echo
}

video_subtitles_align_func() {
	echo
	brown "Subtitle Alignment"
	brown "~~~~~~~~~~~~~~~~~~"
	echo "0 -> Original position"
	echo "1 -> Align at top (original behavior)"
	echo "2 -> Align at center"
	echo "3 -> Align at bottom"
	echo
	printf "Select the Subtitle alignment [default is 1]: "
	read subalign
	case "$subalign" in
		0)	spualign="-spualign -1" ;;
		1|"")	spualign="-spualign 0" ;;
		2)	spualign="-spualign 1" ;;
		3)	spualign="-spualign 2" ;;
		*)
		error "-> Unknown option: '$subalign'"
		error "-> Exiting in sub-function: video_subtitles_align_func()"
		exit_func 1
		;;
	esac
}

video_subtitles_codepage_func() {
	printf "Specify a Codepage for the subtitle [press 'Enter' to skip]: "
	read subcodepage
	if [ ! -z "$subcodepage" ]; then
		subcp="-subcp $subcodepage"
	fi
}

video_subtitles_language_func() {
	printf "Provide the 2 or 3 letter Language code (sub $i) [press 'Enter' to skip]: "
	read sublang[i]
	if [ ! -z "${sublang[i]}" ]; then
		SUBLANG[i]="${sublang[i]}"
	else
		SUBLANG[i]=und
	fi
}

video_subtitles_scale_func() {
	printf "Provide the Subtitle Text Autoscale value [0-100, higher is bigger - default is 5]: "
	read sscale
	if [ ! -z "$sscale" ]; then
		subscale="-subfont-text-scale $sscale"
	fi
}

video_subtitles_option_func() {
	nosub="-nosub"
	case "$1" in
		hardcode-external)
		printf "Provide the Subtitle file [press 'Enter' to skip]: "
		read -e subfile
		if [ ! -z "$subfile" ]; then
			if [ ! -f "$subfile" ]; then
				echo
				error "-> No such file: '$subfile'"
				error "-> Skipping subtitle"
				echo
			else
				video_subtitles_codepage_func
				case "$(echo "${subfile##*.}" | tr '[:upper:]' '[:lower:]')" in
					idx|sub|sup|srt|ass|ssa|mks)
					video_subtitles_align_func
					;;
				esac
				video_subtitles_scale_func
				subtitle[1]="-sub \"$subfile\" -subfont-autoscale 1 $spualign $subcp $subscale"
			fi
		fi
		;;
		import-external)
		for i in $(eval echo "{1..$MAX_AMOUNT_EXT_SUBS}"); do
			printf "Provide the Subtitle file (Sub $i) [press 'Enter' to skip]: "
			read -e subfile[i]
			if [ ! -z "${subfile[i]}" ]; then
				if [ ! -f "${subfile[i]}" ]; then
					echo
					error "-> No such file: '${subfile[i]}'"
					error "-> Skipping subtitle $i"
					echo
				else
					video_subtitles_language_func
					EXTSUB[i]="${subfile[i]}"
				fi
			fi
		done
		;;
	esac
}

video_subtitles_func() {
	sub=$(get_selection_func "Would you like to include/rip a Subtitle? [y/N]: ")
	if [ "$sub" = "y" ]; then
		case "$source" in
			file|dir|vcd)
			echo
			brown "Subtitle Methods"
			brown "~~~~~~~~~~~~~~~~"
			echo "0 -> Hardcode an external subtitle"
			echo "1 -> Hardcode an embedded subtitle"
			echo "2 -> Import subtitle(s) into the MKV/MP4/OGM containers"
			echo "3 -> Skip subtitle inclusion"
			echo
			printf "Select the Subtitle Method [default is 0]: "
			read submethod
			case "$submethod" in
				0|"")
				video_subtitles_option_func hardcode-external
				;;
				1)
				get_subtitles_func $source
				printf "Specify the Subtitle's ID number [press 'Enter' to skip]: "
				read subid
				if [ ! -z "$(echo $subid | grep '[a-zA-Z]')" ]; then
					echo
					error "-> You have to specify the Subtitle ID number, not the language code!"
					error "-> Skipping subtitle"
					echo
				else
					if [ ! -z "$subid" ]; then
						video_subtitles_scale_func
						video_subtitles_align_func
						subtitle[1]="-sid $subid -spuaa 4 -spugauss 0.4 $spualign $subscale"
					fi
				fi
				;;
				2)
				video_subtitles_option_func import-external
				;;
				3)
				nosub="-nosub"
				;;
				*)
				error "-> Unknown option: '$submethod'"
				error "-> Exiting in function: video_subtitles_func()"
				exit_func 1
				;;
			esac
			;;
			dvd)
			echo
			brown "Subtitle Methods"
			brown "~~~~~~~~~~~~~~~~"
			echo "0 -> Hardcode a DVD subtitle"
			echo
			echo "1 -> Hardcode an external subtitle"
			echo
			echo "2 -> Dump DVD subtitle(s) to file(s) on disk"
			echo "     and optionally import them into MKV/MP4"
			echo
			echo "3 -> Import external subtitle(s) into MKV/MP4/OGM"
			echo
			echo "4 -> Skip subtitle inclusion"
			echo
			printf "Select the Subtitle Method [default is 2]: "
			read submethod
			case "$submethod" in
				0)
				get_subtitles_func $source
				printf "Specify the Subtitle's ID number [press 'Enter' to skip]: "
				read subid
				if [ ! -z "$(echo $subid | grep '[a-zA-Z]')" ]; then
					echo
					error "-> You have to specify the Subtitle ID number, not the language code!"
					error "-> Skipping subtitle"
					echo
				else
					if [ ! -z "$subid" ]; then
						video_subtitles_align_func
						subtitle[1]="-sid $subid -spuaa 4 -spugauss 0.4 $spualign"
					fi
				fi
				;;
				1)
				video_subtitles_option_func hardcode-external
				;;
				2|"")
				# First subtitle gets dumped during
				# encoding time, second/third/... one after
				# encoding has finished
				get_subtitles_func $source
				for i in $(eval echo "{1..$MAX_AMOUNT_SUBS}"); do
					printf "Specify the Subtitle ID number (sub $i) [press 'Enter' to skip]: "
					read subid[i]
					if [ ! -z "$(echo ${subid[i]} | grep '[a-zA-Z]')" ]; then
						echo
						error "-> You have to specify the Subtitle ID number, not the language code!"
						error "-> Skipping subtitle $i"
						echo
					else
						if [ ! -z "${subid[i]}" ]; then
							subtitle[i]="-sid ${subid[i]}"
							vobsubout[i]="-vobsubout \"${OUTPUT%.*}_sub$i\" -vobsuboutindex $(($i-1))"
							IDXFILE[i]="${OUTPUT%.*}_sub$i.idx"
							SUBFILE[i]="${OUTPUT%.*}_sub$i.sub"
						fi
					fi
				done
				;;
				3)
				video_subtitles_option_func import-external
				;;
				4)
				nosub="-nosub"
				;;
				*)
				error "-> Unknown subtitle method option: '$submethod'"
				error "-> Exiting in function: video_subtitles_func()"
				exit_func 1
				;;
			esac
			;;
			bd)
			echo
			brown "Subtitle Methods"
			brown "~~~~~~~~~~~~~~~~"
			echo "0 -> Hardcode an external subtitle"
			echo "1 -> Import subtitle(s) into the MKV/MP4/OGM containers"
			echo "2 -> Skip subtitle inclusion"
			echo
			printf "Select the Subtitle Method [default is 0]: "
			read submethod
			case "$submethod" in
				0|"")	video_subtitles_option_func hardcode-external ;;
				1)	video_subtitles_option_func import-external ;;
				2)	nosub="-nosub" ;;
			esac
			;;
		esac
	else
		nosub="-nosub"
	fi
}

# Video cropping
video_crop_func() {
	case "$source" in
		dir)
		echo
		error "-> Cropping in directory batch encoding mode is not"
		error "   recommended unless you know what you're doing!"
		;;
	esac
	printf "Specify the Crop Rounding Value [4/8/16 - default is 4]: "
	read cropround
	if [ -z "$cropround" ]; then
		cropdetect="cropdetect=24:4"
	else
		cropdetect="cropdetect=24:$cropround"
	fi
	echo
	green "-> Detecting crop values with the cropdetect filter..."
	$MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid $MPOPTS 2>/dev/null > "$TEMPDIR/cropdetect"
	VLENGTH=$(grep '^ID_LENGTH' "$TEMPDIR/cropdetect" | cut -f '2' -d '=' | cut -f '1' -d '.')
	case "$source" in
		dvd|vcd)
		CROPOPTS="-frames 30 -sstep $(($VLENGTH/30))"
		;;
		bd)
		CROPOPTS="-frames 600 -ss 250"
		cropdetect="$cropdetect:50"
		;;
		*)
		CROPOPTS="-frames 500 -ss $(($VLENGTH/2))"
		;;
	esac
	GETCROP=$($MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid -vf $cropdetect -ao null -vo null $CROPOPTS -nocache 2>/dev/null | tr '\r' '\n' | grep "crop=" | tail -n 1 | awk '{print $9}' | sed 's|crop=||g; s|).||g')
	if [ ! -z "$GETCROP" ]; then
		green "-> Found crop values: $GETCROP"
	else
		echo
		error "-> Failed to get crop values at first try."
		error "-> Doing a second run..."
		echo
		CROPOPTS="-frames 100 -ss $(($VLENGTH/4))"
		GETCROP=$($MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid -vf $cropdetect -ao null -vo null $CROPOPTS -nocache 2>/dev/null | tr '\r' '\n' | grep "crop=" | tail -n 1 | awk '{print $9}' | sed 's|crop=||g; s|).||g')
		if [ -z "$GETCROP" ]; then
			error "-> Failed to get the crop values!"
			error "-> You have to specify them yourself!"
			error "-> The format is as follows: width:height:x:y"
			GETCROP="??"
		else
			green "-> Found crop values: $GETCROP"
		fi
	fi
	rm -f "$TEMPDIR/cropdetect"
	echo
	CROPDETERMINED="n"
	while [ "$CROPDETERMINED" != "y" ]; do
		if [ -z "$cropvalues" ]; then
			printf "Specify the Crop Values [default is $GETCROP]: "
		else
			printf "Specify the Crop Values [last try: "$cropvalues"]: "
		fi
		read cropvalues
		if [ -z "$cropvalues" -a "$GETCROP" = "??" ]; then
			cropfilter=
		else
			if [ -z "$cropvalues" ]; then
				cropfilter="crop=$GETCROP,"
				crop_preview="$GETCROP"
			else
				cropfilter="crop=$cropvalues,"
				crop_preview="$cropvalues"
			fi
			precrop=$(get_selection_func "Preview the Crop Values for 10 seconds? [y/N]: ")
			if [ "$precrop" = "y" ]; then
				printf "Specify the Start Position in hour:min:sec [default is 0:02:00]: "
				read timepos
				if [ -z "$timepos" ]; then
					startpos="0:02:00"
				else
					startpos="$timepos"
				fi
				$MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid -vf rectangle=$crop_preview -nocache -ao null -ss $startpos -endpos 10 >/dev/null 2>&1
			fi
		fi
		CROPDETERMINED=$(get_selection_func "Are you Satisfied with the Crop Area? [y/N]: ")
	done
}

calcbits() {
	echo "scale=2; $1" | $BC -l | sed 's|^\.|0\.|'
}

# Bits per pixel calculation
#
#         $videobitrate * 1000
# $bpp = -----------------------
#        $width * $height * $fps
#
bits_per_pixel_func() {
	if [ "$vres" = "$GETRES" -o -z "$vres" ]; then
		WIDTH=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $2}')
	else
		WIDTH=$(echo $vres | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $vres | tr '[:alpha:]' ' ' | awk '{print $2}')
	fi
	if [ -z "$ofps" ]; then
		VIDFPS="$GETFPS"
	else
		VIDFPS="$(echo $ofps | awk '{print $2}')"
	fi
	if [ "$calcvidbit" = "y" -o "$calcvidbit" = "Y" ]; then
		BPP=$(calcbits "$VBITRATE*1000/($WIDTH*$HEIGHT*$VIDFPS)")
	else
		echo
		green "-> Bits Per Pixel value: $(calcbits "$(echo $bitrate | awk -F= '{print $2}')*1000/($WIDTH*$HEIGHT*$VIDFPS)") bpp"
	fi
}

# Bits per block calculation
#
# MPEG type compression breaks each
# frame into many smaller 16x16 blocks
# and assigns a quantizer to each one
# of them. The below formula can be
# used to calculate how many bits
# each one of these blocks gets
#
#                      $videobitrate * 1000
# $bpb = ---------------------------------------------------
#        $(($fps * $(($(($width * $height))/$((16 * 16))))))
#
bits_per_block_func() {
	if [ "$vres" = "$GETRES" -o -z "$vres" ]; then
		WIDTH=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $2}')
	else
		WIDTH=$(echo $vres | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $vres | tr '[:alpha:]' ' ' | awk '{print $2}')
	fi
	if [ -z "$ofps" ]; then
		VIDFPS="$GETFPS"
	else
		VIDFPS="$(echo $ofps | awk '{print $2}')"
	fi
	if [ "$calcvidbit" = "y" -o "$calcvidbit" = "Y" ]; then
		BPB=$(calcbits "$VBITRATE*1000/($VIDFPS*($WIDTH*$HEIGHT)/(16*16))")
	else
		green "-> Bits Per Block value: $(calcbits "$(echo $bitrate | awk -F= '{print $2}')*1000/($VIDFPS*($WIDTH*$HEIGHT)/(16*16))") bpb"
	fi
}

test_write_func() {
	case "$1" in
		output)
		TESTFILE="$DEFAULT_PATH/.testfile$$"
		touch "$TESTFILE" 2>/dev/null
		if [ $? != 0 ]; then
			echo
			error "-> Output directory '$DEFAULT_PATH' is not writable!"
			error "-> Exiting in function: test_write_func()"
			echo
			exit_func 1
		else
			rm -f "$TESTFILE" 2>/dev/null
		fi
		;;
		batchfile)
		if [ ! -d "$(dirname "$OPTSFILE")" ]; then
			mkdir -p "$(dirname "$OPTSFILE")" 2>/dev/null
			if [ $? != 0 ]; then
				echo
				error "-> Couldn't create destination directory '$(dirname "$OPTSFILE")'"
				green "-> Defaulting to '$HOME'"
				echo
				OPTSFILE="$HOME/batchfile"
			fi
		fi
		TESTFILE="$(dirname "$OPTSFILE")/.testfile$$"
		touch "$TESTFILE" 2>/dev/null
		if [ $? != 0 ]; then
			echo
			error "-> Destination directory '$(dirname "$OPTSFILE")' not writable!"
			error "-> Exiting in function: test_write_func()"
			echo
			exit_func 1
		else
			rm -f "$TESTFILE" 2>/dev/null
		fi
		;;
	esac
}
	
set_output_filename_func() {
	case "$source" in
		file|vcd|bd)
		printf "Provide a name for the Output File [default is H264-$$]: "
		read -e outfile
		if [ -z "$outfile" ]; then
			OUTPUT="H264-$$"
		else
			OUTPUT="$outfile"
		fi
		;;
		dvd)
		green "-> Scanning for DVD title name..."
		GET_TITLE=$($LSDVD $(echo $device | awk '{print $2}') 2>/dev/null | grep '^Disc Title:' | sed 's|Disc Title: ||; s|_| |g')
		if [ ! -z "$GET_TITLE" ]; then
			SET_NAME="$GET_TITLE"
		else
			SET_NAME="H264-$$"
		fi
		echo
		printf "Provide a name for the Output File [default is $SET_NAME]: "
		read -e outfile
		if [ -z "$outfile" ]; then
			OUTPUT="$SET_NAME"
		else
			OUTPUT="$outfile"
		fi
		;;
	esac
	if [ ! -z "$DEFAULT_OUTPUT" ]; then
		if [ ! -z "$(echo "$OUTPUT" | grep '/')" ]; then
			if [ ! -d "$(dirname "$OUTPUT")" ]; then
				mkdir -p "$(dirname "$OUTPUT")" 2>/dev/null
				if [ $? != 0 ]; then
					echo
					error "-> Could not create output dir '$(dirname "$OUTPUT")'"
					error "-> Defaulting to '$HOME'"
					echo
					DEFAULT_PATH="$HOME"
				else
					DEFAULT_PATH="$(dirname "$OUTPUT")"
				fi
			else
				DEFAULT_PATH="$(dirname "$OUTPUT")"
				test_write_func output
			fi
		else
			if [ ! -d "$DEFAULT_OUTPUT" ]; then
				mkdir -p "$DEFAULT_OUTPUT" 2>/dev/null
				if [ $? != 0 ]; then
					echo
					error "-> Could not create default output dir '$DEFAULT_OUTPUT'"
					error "-> Defaulting to '$HOME'"
					echo
					DEFAULT_PATH="$HOME"
				else
					DEFAULT_PATH="$DEFAULT_OUTPUT"
				fi
			else
				DEFAULT_PATH="$DEFAULT_OUTPUT"
				test_write_func output
			fi
		fi
	else
		if [ ! -z "$(echo "$OUTPUT" | grep '/')" ]; then
			if [ ! -d "$(dirname "$OUTPUT")" ]; then
				mkdir -p "$(dirname "$OUTPUT")" 2>/dev/null
				if [ $? != 0 ]; then
					echo
					error "-> Could not create output dir '$(dirname "$OUTPUT")'"
					error "-> Defaulting to '$HOME'"
					echo
					DEFAULT_PATH="$HOME"
				else
					DEFAULT_PATH="$(dirname "$OUTPUT")"
				fi
			else
				DEFAULT_PATH="$(dirname "$OUTPUT")"
				test_write_func output
			fi
		else
			DEFAULT_PATH="$HOME"
		fi
	fi
	OUTPUT="$DEFAULT_PATH/$(basename "${OUTPUT%.*}.avi")"
}

backup_file_func() {
	case "$1" in
		files|chaps)
		case "$1" in
			files)
			EXTFILE="$OUTPUT"
			;;
			chaps)
			EXTFILE="$CHAPTERSFILE"
			;;
		esac
		if [ -e "$EXTFILE" ]; then
			counter=1
			while [ -e "$EXTFILE.$counter.old" ]; do
				counter=$(($counter+1))
			done
			BKOUT="$EXTFILE.$counter.old"
			echo
			green "-> Renaming existing file to '$(basename "$BKOUT")'"
			case "$1" in
				files)
				case "$source" in
					file|vcd|dir) echo ;;
				esac
				;;
				chaps)
				echo
				;;
			esac
			mv -f "$EXTFILE" "$BKOUT"
		fi
		;;
		subs)
		if [ ! -z "${vobsubout[*]}" ]; then
			for i in $(eval echo "{1..$MAX_AMOUNT_SUBS}"); do
				if [ -e "${IDXFILE[i]}" -o -e "${SUBFILE[i]}" ]; then
					echo
					break
				fi
			done
		fi
		counter=1
		for i in $(eval echo "{1..$MAX_AMOUNT_SUBS}"); do
			while [ -e "${IDXFILE[i]}.$counter.old" -o -e "${SUBFILE[i]}.$counter.old" ]; do
				counter=$(($counter+1))
			done
			if [ -e "${IDXFILE[i]}" ]; then
				green "-> Renaming existing file to '$(basename "${IDXFILE[i]}.$counter.old")'"
				mv -f "${IDXFILE[i]}" "${IDXFILE[i]}.$counter.old"
			fi
			if [ -e "${SUBFILE[i]}" ]; then
				green "-> Renaming existing file to '$(basename "${SUBFILE[i]}.$counter.old")'"
				mv -f "${SUBFILE[i]}" "${SUBFILE[i]}.$counter.old"
			fi
		done
		;;
	esac
}

check_diskspace_func() {
	HDOUT="$(df -k "$(dirname "$OUTPUT")" | tail -n 1 | awk '{print $4}')"
	HDCONF="$(df -k "$TEMPDIR" | tail -n 1 | awk '{print $4}')"
	if [ $HDOUT -le 4194304 -o $HDCONF -le 4194304 ]; then
		echo
		echo "Note that you are running out of disk space in"
		echo "the destination output directory and/or in the"
		echo "configuration directory of h264enc!"
		echo
		echo "This could be a problem if you want to convert"
		echo "the final encode to MKV, OGM, TS or to the MP4"
		echo "container. It is recommended to free up some disk"
		echo "space or provide a different destination output"
		echo "directory before continuing with the encoding"
		echo "process if you intend to do some of the above"
		echo "tasks!"
		echo
		error "Space left over in '$(dirname "$OUTPUT")': $HDOUT KiB"
		error "Space left over in '$TEMPDIR': $HDCONF KiB"
		echo
		printf "#### Press 'Enter' to continue, CTRL+C to exit ####"
		read conenc
		case "$source" in
			file|dir) echo ;;
		esac
	fi
}

video_filters_func() {
	if [ "$DISABLE_ALL_VID_FILTERS" = "n" ]; then
		vfilters=$(get_selection_func "Would you like to use Pre/Postprocessing video filters? [y/N]: ")
		if [ "$vfilters" = "y" ]; then
			echo
			brown "+==================================+"
			brown "| Pre/Postprocessing Video Filters |"
			brown "+==================================+"
			echo
			test "$ALLOW_VID_DEINTERLACE" = "y" && video_deinterlace_func
			test "$ALLOW_VID_INTERLACE" = "y" && video_interlace_func
			test "$ALLOW_VID_DEBLOCK" = "y" && video_deblock_func
			test "$ALLOW_VID_DELOGO" = "y" &&  video_delogo_func
			test "$ALLOW_VID_DENOISE" = "y" && video_denoise_func
			test "$ALLOW_VID_DEBAND" = "y" && video_deband_func
			test "$ALLOW_VID_ROTATE" = "y" && video_rotate_func
			test "$ALLOW_VID_NOISE" = "y" && video_noise_func
			test "$ALLOW_VID_UNSHARP" = "y" && video_unsharp_func
			test "$ALLOW_VID_BRIGHTNESS" = "y" && video_brightness_func
			test "$ALLOW_VID_EQUALIZER" = "y" && video_equalizer_func
		else
			interlaced=":nointerlaced"
		fi
	else
		interlaced=":nointerlaced"
	fi
	if [ "$DISABLE_VID_CROP_FILTER" = "n" ]; then
		if [ "$ALLOW_VID_AUTOCROP" = "y" ]; then
			# Skip autocropping for directory
			# batch encoding mode
			case "$source" in
				file|dvd|vcd|bd)
				video_crop_func
				;;
			esac
		else
			cropping=$(get_selection_func "Would you like to Crop the $type? [y/N]: ")
			if [ "$cropping" = "y" ]; then
				video_crop_func
			fi
		fi
	fi
}

ask_video_subtitles_func() {
	if [ "$DISABLE_SUBTITLES" = "n" ]; then
		video_subtitles_func
	else
		true
	fi
}

edl_list_func() {
	if [ "$ALLOW_EDL_LIST" = "y" ]; then
		printf "Provide an EDL List file [press 'Enter' to skip]: "
		read -e edl
		if [ ! -z "$edl" ]; then
			if [ -f "$edl" ]; then
				EDL="-edl \"$edl\""
			else
				echo
				error "-> No such file!"
				error "-> Skipping EDL List function!"
				echo
			fi
		fi
	else
		true
	fi
}

#############################################################
############## BD/DVD/VCD/video file settings ###############
#############################################################

echo
brown " _     ____   __   _  _ "
brown "| |__ |___ \ / /_ | || |   ___ _ __   ___ "
brown "| '_ \  __) | '_ \| || |_ / _ \ '_ \ / __|"
brown "| | | |/ __/| (_) |__   _|  __/ | | | (__"
brown "|_| |_|_____|\___/   |_|  \___|_| |_|\___|"
brown "v$version"
echo

chapters_example_func() {
	echo
	echo "Example: to encode only chapter 2, type: 2-2"
	echo "Example: to encode from chapter 5 until the end of the $type, type: 5"
	echo "Example: to encode from chapter 1 until the end of 3, type: 1-3"
	echo
}

source=$(get_selection_func "Select the Input type [file/dir/vcd/dvd/bd]: ")

case "$source" in
	file)
	type="Video file"
	printf "Provide the Input Video File: "
	read -e infile
	if [ ! -f "$infile" ]; then
		error "-> No such file: '$infile'"
		exit_func 1
	fi
	set_output_filename_func
	check_diskspace_func
	sourcetype="$infile"
	if [ "$sourcetype" = "$OUTPUT" ]; then
		error "-> You cannot use the same file name for both the input and output file!"
		exit_func 1
	fi
	backup_file_func files
	# Scan to see if input file has
	# more than one video stream
	if [ "$ALLOW_SCAN_MULTIPLE_VIDSTREAMS" = "y" ]; then
		mvs=$(get_selection_func "Scan for multiple video streams? [y/N]: ")
		if [ "$mvs" = "y" ]; then
			echo
			green "-> Scanning for video streams..."
			$MPLAYER "$sourcetype" $MPLAYEROPTS $MPOPTS 2>/dev/null > "$TEMPDIR/videostreams"
			if [ $(grep '^ID_VIDEO_ID' "$TEMPDIR/videostreams" | wc -l) -lt 2 ]; then
				vid=
				green "-> Found only one video stream"
				green "-> Skipping stream selection"
				echo
			else
				echo
				for i in $(grep '^ID_VIDEO_ID' "$TEMPDIR/videostreams"); do
					echo "$(echo "Video stream: $(echo $i | awk -F= '{print $2}')")"
				done
				echo
				printf "Specify the video stream number for encoding [default is 0]: "
				read vidstream
				if [ -z "$vidstream" ]; then
					vid="-vid 0"
				else
					vid="-vid $vidstream"
				fi
			fi
			rm -f "$TEMPDIR/videostreams"
		fi
	fi
	if [ -x "$MKVEXTRACT" -o -x "$MP4BOX" ]; then
		case "${infile##*.}" in
			mkv|MKV|mp4|MP4|m4v|M4V|MOV|mov)
			dumpchaps=$(get_selection_func "Extract Chapters Info to a File? [y/N]: ")
			if [ "$dumpchaps" = "y" ]; then
				dump_chaps_info_func() {
					case "$1" in
						info)
						echo
						case "$2" in
							mkv)
							green "-> Extracted chapters to '$MKVCHAPFILE'"
							;;
							mp4)
							green "-> Extracted chapters to '$MP4CHAPFILE'"
							;;
						esac
						echo
						;;
						error)
						echo
						error "-> Chapter file appears to be empty! No chapters info in input file?"
						error "-> Skipping chapters import for MKV/MP4"
						green "-> You still have the option to manually import a different chapters file for MKV/MP4"
						echo
						;;
					esac
				}
				case "${infile##*.}" in
					mkv|MKV)
					MKVCF="${OUTPUT%.*}.chaps"
					test -e "$MKVCF" && mv -f "$MKVCF" "$MKVCF.old" 2>/dev/null
					$MKVEXTRACT chapters "$infile" > "$MKVCF" 2>/dev/null
					if [ ! -z "$(grep '.*' "$MKVCF")" ]; then
						MKVCHAPFILE="$MKVCF"
						dump_chaps_info_func info mkv
					else
						dump_chaps_info_func error
					fi
					;;
					mp4|MP4|m4v|M4V|MOV|mov)
					MP4CF="${OUTPUT%.*}.chap"
					test -e "$MP4CF" && mv -f "$MP4CF" "$MP4CF.old" 2>/dev/null
					$MP4BOX "$infile" -dump-chap -out "$MP4CF" 2>/dev/null
					if [ ! -z "$(grep '.*' "$MP4CF")" ]; then
						MP4CHAPFILE="$MP4CF"
						dump_chaps_info_func info mp4
					else
						dump_chaps_info_func error
					fi
					;;
				esac
			fi
			;;
		esac
	fi
	edl_list_func
	video_filters_func
	ask_video_subtitles_func
	;;
	dir)
	type="Video files"
	printf "Provide one Input Video File from the directory to encode from: "
	read -e infile
	if [ ! -f "$infile" ]; then
		error "-> No such file: '$infile'"
		exit_func 1
	fi
	sourcetype="$infile"
	test -d "$DEFAULT_OUTPUT" && DEFAULT_BATCHDIR="$DEFAULT_OUTPUT" || DEFAULT_BATCHDIR="$HOME"
	printf "Where to store the encodings? [default is $DEFAULT_BATCHDIR/h264enc_$$]: "
	read -e outdir
	if [ -z "$outdir" ]; then
		OUTPUTDIR="$DEFAULT_BATCHDIR/h264enc_$$"
		if [ ! -d "$OUTPUTDIR" ]; then
			mkdir -p "$OUTPUTDIR" 2>/dev/null
			if [ $? != 0 ]; then
				error "-> Failed to create the output directory!"
				error "-> Maybe a permissions problem?"
				exit_func 1
			fi
		fi
	else
		if [ "$(dirname "$sourcetype")" = "$outdir" ]; then
			error "-> You can't use the input directory as output directory!"
			exit_func 1
		fi
		OUTPUTDIR="$outdir"
		if [ ! -d "$OUTPUTDIR" ]; then
			mkdir -p "$OUTPUTDIR" 2>/dev/null
			if [ $? != 0 ]; then
				error "-> Failed to create the output directory!"
				error "-> Maybe a permissions problem?"
				exit_func 1
			fi
		fi
	fi
	OUTPUT="$OUTPUTDIR/\${i%.*}.avi"
	edl_list_func
	video_filters_func
	ask_video_subtitles_func
	;;
	bd)
	type="Blu-ray"
	cache="-cache 100"
	if [ -z "$(ldd $MENCODER | grep 'libbluray')" ]; then
		echo
		error "-> MEncoder does not support $type as input!"
		error "-> Recompile MPlayer with libbluray support!"
		echo
		exit_func 1
	fi
	check_spaces_func() {
		if [ ! -z "$(echo "$device" | sed 's|-bluray-device ||' | grep ' ')" ]; then
			error "-> Spaces in names for devices/ISO/directory not supported!"
			exit_func 1
		fi
	}
	echo
	brown "Input Selection"
	brown "~~~~~~~~~~~~~~~"
	echo "0 -> Encode from a $type disc/drive"
	echo "1 -> Encode from a $type ISO image"
	echo "2 -> Encode from a $type directory"
	echo
	printf "Select the input [default is 0]: "
	read bdsource
	case "$bdsource" in
		0|"")
		get_devices_func bd
		check_spaces_func
		;;
		1)
		printf "Provide the $type ISO image: "
		read -e bdiso
		if [ -z "$bdiso" -o ! -e "$bdiso" ]; then
			error "-> ISO image not specified or does not exist!"
			exit_func 1
		else
			device="-bluray-device $bdiso"
		fi
		check_spaces_func
		;;
		2)
		printf "Provide the $type directory: "
		read -e bddir
		if [ -z "$bddir" -o ! -d "$bddir" ]; then
			error "-> Directory not specified or does not exist!"
			exit_func 1
		else
			device="-bluray-device $bddir"
		fi
		check_spaces_func
		;;
		*)
		error "-> Unknown option: '$bdsource'"
		exit_func 1
		;;
	esac
	set_output_filename_func
	check_diskspace_func
	backup_file_func files
	echo
	green "-> Scanning for $type titles..."
	BDTITLES="$($MPLAYER br:// $MPLAYEROPTS $device $MPOPTS 2>/dev/null | grep '^ID_BLURAY_TITLES' | awk -F= '{print $2}')"
	if [ ! -z "$BDTITLES" ]; then
		green "-> Found $BDTITLES titles"
		echo
		for t in $(eval echo "{1..$BDTITLES}"); do
			TITLELENGTH="$($MPLAYER br:// $MPLAYEROPTS $device $MPOPTS 2>/dev/null | grep "^ID_BLURAY_TITLE_${t}_LENGTH" | awk -F= '{print $2}')"
			if [ ! -z "$TITLELENGTH" -a "$TITLELENGTH" != "0.000" -a "$TITLELENGTH" != "0" ]; then
				green "-> Title $t: $(($(echo "$TITLELENGTH" | awk -F. '{print $1}')/60)) minutes or $TITLELENGTH seconds"
			fi
		done
	else
		error "-> Could not detect any $type titles!"
	fi
	echo
	printf "Specify the $type title for encoding [default is 1]: "
	read title
	if [ -z "$title" ]; then
		sourcetype="br://1"
	else
		sourcetype="br://$title"
	fi
	if [ "$DISABLE_ASK_BD_ANGLE" = "n" ]; then
		BDTITLE="$(echo $sourcetype | sed 's|br://||')"
		angle=$(get_selection_func "Would you like to encode from a Different $type Angle? [y/N]: ")
		if [ "$angle" = "y" ]; then
			echo
			green "-> Scanning for angles in title $BDTITLE..."
			$MPLAYER $sourcetype $MPLAYEROPTS $device $MPOPTS 2>/dev/null > "$TEMPDIR/angles"
			BDANGLE="$(grep "^ID_BLURAY_TITLE_${BDTITLE}_ANGLE" "$TEMPDIR/angles" | awk -F= '{print $2}')"
			if [ ! -z "$BDANGLE" ]; then
				green "-> Found $BDANGLE angles"
			else
				error "-> Could not detect any angles in this $type title!"
			fi
			rm -f "$TEMPDIR/angles"
			echo
			printf "From which Angle to encode the $type? [default is 1]: "
			read bdangle
			if [ ! -z "$bdangle" ]; then
				movieangle="-bluray-angle $bdangle"
			fi
		fi
	fi
	if [ "$DISABLE_ASK_BD_CHAPTERS" = "n" ]; then
		chap=$(get_selection_func "Would you like to Encode only Specific Chapters? [y/N]: ")
		if [ "$chap" = "y" ]; then
			echo
			green "-> Scanning for chapters in title $BDTITLE..."
			$MPLAYER $sourcetype $MPLAYEROPTS $device $MPOPTS 2>/dev/null > "$TEMPDIR/chapters"
			BDCHAPS="$(grep "^ID_BLURAY_TITLE_${BDTITLE}_CHAPTERS" "$TEMPDIR/chapters" | awk -F= '{print $2}')"
			if [ ! -z "$BDCHAPS" -a "$BDCHAPS" != "0" ]; then
				green "-> Found $BDCHAPS chapters"
			else
				error "-> Could not detect any chapters in this $type title!"
			fi
			rm -f "$TEMPDIR/chapters"
			chapters_example_func
			printf "Which chapter(s) to encode from this $type title? [press 'Enter' to skip]: "
			read chapenc
			if [ ! -z "$chapenc" ]; then
				chapters="-chapter $chapenc"
			backup_file_func files
			fi
		fi
	fi
	edl_list_func
	video_filters_func
	ask_video_subtitles_func
	#backup_file_func subs
	;;
	dvd)
	type="DVD"
	if [ ! -x "$LSDVD" ]; then
		error "-> Checking for lsdvd... FAILED!"
		exit_func 1
	fi
	check_spaces_func() {
		if [ ! -z "$(echo "$device" | sed 's|-dvd-device ||' | grep ' ')" ]; then
			error "-> Spaces in file names for devices/ISO/VIDEO_TS not supported!"
			exit_func 1
		fi
	}
	echo
	brown "Input Selection"
	brown "~~~~~~~~~~~~~~~"
	echo "0 -> Encode from a $type disc/drive"
	echo "1 -> Encode from a $type ISO image"
	echo "2 -> Encode from a $type VIDEO_TS directory"
	echo
	printf "Select the input [default is 0]: "
	read dvdsource
	case "$dvdsource" in
		0|"")
		get_devices_func dvd
		check_spaces_func
		;;
		1)
		printf "Provide the $type ISO image: "
		read -e dvdiso
		if [ -z "$dvdiso" -o ! -e "$dvdiso" ]; then
			error "-> ISO image not specified or does not exist!"
			exit_func 1
		else
			device="-dvd-device $dvdiso"
		fi
		check_spaces_func
		;;
		2)
		printf "Provide the DVD VIDEO_TS directory: "
		read -e dvdvt
		if [ -z "$dvdvt" -o ! -d "$dvdvt" ]; then
			error "-> Directory not specified or does not exist!"
			exit_func 1
		else
			device="-dvd-device $dvdvt"
		fi
		check_spaces_func
		;;
		*)
		error "-> Unknown option: '$dvdsource'"
		exit_func 1
		;;
	esac
	# Before scanning the DVD with 'lsdvd' it has to be
	# unlocked or 'lsdvd' will fail to read it, so we
	# run mplayer here just to unlock it
	echo
	green "-> Unlocking the DVD disc..."
	$MPLAYER dvd:// $device $MPOPTS >/dev/null 2>&1
	set_output_filename_func
	check_diskspace_func
	backup_file_func files
	echo
	green "-> Scanning for $type titles..."
	$LSDVD $(echo $device | awk '{print $2}') 2>/dev/null > "$TEMPDIR/dvdtitles"
	ALLTITLES=$(grep '^Title' "$TEMPDIR/dvdtitles" | awk '{print $1,$2,$5,$6,$3,$4}' | sed 's|,| -|g' | cut -f '1' -d '.' | awk '{print $1,$2,$3,$7,$8,$6,$4,$5}')
	DVDTITLE=$(grep 'Longest' "$TEMPDIR/dvdtitles" | awk '{print $3}' | sed 's|^0||')
	TOTAL_TITLES=$(grep '^Title' "$TEMPDIR/dvdtitles" | sed 's|,||g' | awk 'END{print $2}' | sed 's|^0||')
	TITLE_LENGTH=$($LSDVD -t $DVDTITLE $(echo $device | awk '{print $2}') 2>/dev/null | grep "Length" | awk '{print $4}' | cut -f '1' -d '.')
	rm -f "$TEMPDIR/dvdtitles"
	echo
	if [ -z "$DVDTITLE" ]; then
		brown "Disc Title: $GET_TITLE"
		green "$ALLTITLES"
		echo
		green "-> Titles On Disc: $TOTAL_TITLES"
		error "-> Failed to detect longest DVD title!"
		error "-> You have to specify it yourself!"
		DVDTITLE="??"
	else
		brown "Disc Title: $GET_TITLE"
		green "$ALLTITLES"
		echo
		green "-> Titles On Disc: $TOTAL_TITLES"
		green "-> Longest Title:  $DVDTITLE - Title Length: $TITLE_LENGTH"
		
	fi
	echo
	printf "Specify the $type title for encoding [default/longest is $DVDTITLE]: "
	read title
	if [ -z "$title" -a "$DVDTITLE" = "??" ]; then
		error "-> You have to specify the $type title for encoding!"
		exit_func 1
	fi
	if [ -z "$title" ]; then
		sourcetype="dvd://$DVDTITLE"
	else
		sourcetype="dvd://$title"
	fi
	if [ "$DISABLE_ASK_DVD_ANGLE" = "n" ]; then
		DTITLE="$(echo $sourcetype | sed 's|dvd://||')"
		angle=$(get_selection_func "Would you like to encode from a different $type Angle? [y/N]: ")
		if [ "$angle" = "y" ]; then
			echo
			green "-> Scanning for angles in title $DTITLE..."
			ANGLES=$($MPLAYER $sourcetype $MPLAYEROPTS $device $MPOPTS 2>/dev/null | grep "angles")
			if [ ! -z "$ANGLES" ]; then
				green "-> $ANGLES"
			else
				error "-> Could not detect any angles in this $type title!"
			fi
			echo
			printf "From which Angle to encode the $type? [default is 1]: "
			read dvd_angle
			if [ ! -z "$dvd_angle" ]; then
				movieangle="-dvdangle $dvd_angle"
			fi
		fi
	fi
	if [ "$DISABLE_ASK_DVD_CHAPTERS" = "n" ]; then
		chap=$(get_selection_func "Would you like to encode only Specific Chapters? [y/N]: ")
		if [ "$chap" = "y" ]; then
			echo
			green "-> Scanning for chapters in title $DTITLE..."
			$MPLAYER $sourcetype $MPLAYEROPTS $device $MPOPTS 2>/dev/null > "$TEMPDIR/chapters"
			echo
			brown "Available Chapters On Disc"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			if [ ! -z "$(grep '^CHAPTERS' "$TEMPDIR/chapters")" ]; then
				grep '^CHAPTERS' "$TEMPDIR/chapters" | sed 's|CHAPTERS: ||; s|,| |g' > "$TEMPDIR/getchaps"
				for i in $(cat "$TEMPDIR/getchaps"); do
					echo "Chapter: $i - Start position: " >> "$TEMPDIR/lschaps"
				done
				nl "$TEMPDIR/lschaps" | awk '{print $2,$1,$4,$5,$6,$3}'
			else
				error "-> Could not detect any chapters in this $type title!"
			fi
			rm -f "$TEMPDIR/*"
			chapters_example_func
			printf "Which chapter(s) to encode from this $type title? [press 'Enter' to skip]: "
			read chapenc
			if [ ! -z "$chapenc" ]; then
				chapters="-chapter $chapenc"
				backup_file_func files
			fi
		fi
	fi
	# Export chapters information to a file.
	# This can be used to import chapters
	# info when muxing into MKV/MP4/OGM. It
	# requires ogmtools' 'dvdxchap'.
	if [ -x "$DVDXCHAP" ]; then
		chapexp=$(get_selection_func "Export $type Chapters Information to a File on Disk? [y/N]: ")
		if [ "$chapexp" = "y" ]; then
			CHAPTERSFILE="${OUTPUT%.*}.chaps"
			backup_file_func chaps
			$DVDXCHAP -t $(echo $sourcetype | sed 's|dvd://||') $(echo $device | awk '{print $2}') 2>/dev/null | grep '^CHAPTER' > "$CHAPTERSFILE"
		fi
	fi
	edl_list_func
	video_filters_func
	ask_video_subtitles_func
	backup_file_func subs
	;;
	vcd)
	type="VCD"
	get_devices_func vcd
	echo
	green "-> Scanning for $type tracks..."
	$MPLAYER vcd:// $MPLAYEROPTS $device $MPOPTS 2>/dev/null > "$TEMPDIR/vcdtracks"
	VCDTRACKS=$(grep '^ID_VCD_TRACK_.*' "$TEMPDIR/vcdtracks")
	rm -f "$TEMPDIR/vcdtracks"
	if [ ! -z "$VCDTRACKS" ]; then
		echo
		for i in $VCDTRACKS; do
			green "Track: $(echo $i | sed 's|[A-Z]||g; s|_||g; s|=| - Length: |g')"
		done
	else
		error "-> Could not detect any $type tracks!"
	fi
	echo
	printf "Specify the $type track for encoding [default is 2]: "
	read vcdtrack
	if [ -z "$vcdtrack" ]; then
		sourcetype="vcd://2"
	else
		sourcetype="vcd://$vcdtrack"
	fi
	set_output_filename_func
	check_diskspace_func
	backup_file_func files
	edl_list_func
	video_filters_func
	ask_video_subtitles_func
	;;
	*|"")
	error "-> You have to specify the input type (file/dir/vcd/dvd/bd)"
	exit_func 1
	;;
esac


# Mutually exclusive with bobbing and interlacing
# as FPS is already detected and set in the
# respective functions
if [ -z "$intfilter" -a -z "$deintfps" ]; then
	detect_fps_func() {
		case "$1" in
			other)	scanopts="$MPOPTS" ;;
			ntsc)	scanopts="-vo null -nosound -benchmark -identify" ;;
		esac
		$MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid $scanopts 2>/dev/null > "$TEMPDIR/fps"
		GETFPS=$(grep '^ID_VIDEO_FPS' "$TEMPDIR/fps" | tail -n 1 | awk -F= '{print $2}')
		GETLENGTH=$(grep '^ID_LENGTH' "$TEMPDIR/fps" | awk -F= '{print $2}')
	}
	echo
	case "$source" in
		dvd)
		# Try to detect NTSC type. Currently a fast
		# dumb solution and one that also can't
		# distinguish between true hard telecine
		# and interlacing but it works for soft
		# telecine and mixed progressive/telecine
		# content which is more common
		detect_fps_func other
		case "$GETFPS" in
			29.970|29.97)
			green "-> Detecting NTSC type and FPS value"
			green "-> Scanning can take a while..."
			detect_fps_func ntsc
			TC=$(grep 'demux_mpg' "$TEMPDIR/fps" | wc -l)
			case "$TC" in
				0)
				GETFPS="29.970"
				green "-> Detected 0 'demux_mpg' frame rate switchings"
				green "-> $type appears to be Progressive or Hard Telecined (may need IVTC!)"
				;;
				1)
				GETFPS="23.976"
				green "-> Detected 1 'demux_mpg' frame rate switching"
				green "-> $type appears to be Soft Telecined (needs FPS force to 23.976!)"
				;;
				*)
				GETFPS="23.976"
				green "-> Detected $TC 'demux_mpg' frame rate switchings"
				green "-> $type appears to be Mixed Progressive and Telecine (needs IVTC!)"
				;;
			esac
			;;
			*)
			green "-> Detecting FPS value..."
			green "-> Detected $GETFPS FPS"
			;;
		esac
		;;
		*)
		green "-> Detecting FPS value..."
		detect_fps_func other
		green "-> Detected $GETFPS FPS"
		;;
	esac
	green "-> Number of frames: $(echo "scale=0; $GETLENGTH * $GETFPS" | $BC -l | awk -F. '{print $1}')"
	rm -f "$TEMPDIR/fps"
	echo
	
	outfps=$(get_selection_func "Would you like to set/force the Output Frame Rate (FPS)? [y/N]: ")
	if [ "$outfps" = "y" ]; then
		setfps="yes"
		echo
		brown "Frame Rate Selection"
		brown "~~~~~~~~~~~~~~~~~~~~"
		echo "0 --> 15.984 fps (Silent Film)"
		echo "1 --> 17.982 fps (Silent Film)"
		echo "2 --> 24 fps (Film)"
		echo "3 --> 25 fps (PAL/SECAM Film/Video)"
		echo "4 --> 50 fps (PAL/SECAM Double)"
		echo "5 --> 100 fps (PAL/SECAM Quad)"
		echo "6 --> 23.976 fps (NTSC Film)"
		echo "7 --> 29.970 fps (NTSC Video)"
		echo "8 --> 30 fps (NTSC Video)"
		echo "9 --> 59.940 fps (NTSC Double)"
		echo "10 -> 60 fps (NTSC Double)"
		echo "11 -> 119.880 fps (NTSC Quad)"
		echo "12 -> User Defined"
		echo "13 -> Skip frame rate settings"
		echo
		printf "Select a Frame Rate format [default is 3]: "
		read frf
		case "$frf" in
			0) ofps="-ofps 16000/1001" ;;
			1) ofps="-ofps 18000/1001" ;;
			2) ofps="-ofps 24" ;;
			3|"") ofps="-ofps 25" ;;
			4) ofps="-ofps 50" ;;
			5) ofps="-ofps 100" ;;
			6) ofps="-ofps 24000/1001" ;;
			7) ofps="-ofps 30000/1001" ;;
			8) ofps="-ofps 30" ;;
			9) ofps="-ofps 60000/1001" ;;
			10) ofps="-ofps 60" ;;
			11) ofps="-ofps 120000/1001" ;;
			12)
			printf "Specify the Frame Rate value [default is 25]: "
			read frame_rate
			if [ ! -z "$(echo $frame_rate | grep '\.')" ]; then
				error "-> Float is not allowed. Use fractions instead!"
				error "-> Example: 30000/1001"
				exit_func 1
			fi
			if [ -z "$frame_rate" ]; then
				ofps="-ofps 25"
			else
				if [ "$(echo $frame_rate | awk -F/ '{print $2}')" != "1001" ]; then
					error "-> You have to use 1001 as last value of the fraction!"
					error "-> Example: 30000/1001"
					exit_func 1
				fi
				ofps="-ofps $frame_rate"
			fi
			;;
			13) true ;;
			*)
			error "-> Unknown frame rate option: '$frf'"
			exit_func 1
			;;
		esac
	else
		setfps="no"
	fi
else
	GETFPS="25"
	setfps="yes"
fi

# Frame rate conversion. Mutually
# exclusive with frame doubling
# deinterlacers and interlacing
# filters

if [ "$ALLOW_VID_FPS_CONVERSION" = "y" ]; then
	case "$GETFPS" in
		25.000|25.00|29.970|29.97|50.000|50.00|100.000|100.00|59.940|59.94|60.000|60.00|119.880|119.88|"")
		if [ "$setfps" = "no" -a -z "$deintfps" -a -z "$intfps" -a "$interlaced" = ":nointerlaced" ]; then
			fpsconv=$(get_selection_func "Would you like to do Frame Rate Conversion? [y/N]: ")
			if [ "$fpsconv" = "y" ]; then
				quiet="2>/dev/null"
				echo
				brown "Frame Rate Conversion"
				brown "~~~~~~~~~~~~~~~~~~~~~"
				echo "0 -> 50 fps ------> 25 fps (PAL/SECAM Double -> PAL/SECAM)"
				echo "1 -> 100 fps -----> 50 fps (PAL/SECAM Quad -> PAL/SECAM Double)"
				echo "2 -> 29.970 fps --> 23.976 fps (NTSC Video -> NTSC Film)"
				echo "3 -> 59.940 fps --> 23.976 fps (NTSC Double -> NTSC Film)"
				echo "4 -> 59.940 fps --> 29.970 fps (NTSC Double -> NTSC Video)"
				echo "5 -> 60 fps ------> 30 fps (NTSC Double -> NTSC Video)"
				echo "6 -> 119.880 fps -> 59.940 fps (NTSC Quad -> NTSC Double)"
				echo "7 -> 25 fps ------> 50 fps (PAL/SECAM -> PAL/SECAM Double)"
				echo "8 -> 29.970 fps --> 59.940 fps (NTSC Video -> NTSC Double)"
				echo "9 -> Skip frame rate conversion"
				echo
				printf "Select the frame rate conversion [no default!]: "
				read frc
				frc_func() {
					echo
					green "-> Setting input/output frame rate to $(echo "scale=3; $(echo $fps | awk '{print $2}')" | $BC -l)/$(echo "scale=3; $(echo $ofps | awk '{print $2}')" | $BC -l) FPS"
					green "-> Using '$(echo $fpsfilter | sed 's|,$||')' video filter(s)"
				}
				unknown_options_func() {
					error "-> Unknown filters option: '$fpscf'"
					exit_func 1
				}
				case "$frc" in
					0|1)
					echo
					brown "FPS Conversion Filters"
					brown "~~~~~~~~~~~~~~~~~~~~~~"
					echo "0 -> Framestep"
					echo "1 -> Filmdint"
					echo
					printf "Which filter to use? [default is 1]: "
					read fpscf
					case "$frc" in
						0)
						case "$fpscf" in
							0)	fpsfilter="framestep=2," ;;
							1|"")	fpsfilter="filmdint=fast=0/io=50:25/dint_thres=256," ;;
							*)	unknown_options_func ;;
						esac
						fps="-fps 50"
						ofps="-ofps 25"
						frc_func
						;;
						1)
						case "$fpscf" in
							0)	fpsfilter="framestep=2," ;;
							1|"")	fpsfilter="filmdint=fast=0/io=100:50/dint_thres=256," ;;
							*)	unknown_options_func ;;
						esac
						fps="-fps 100"
						ofps="-ofps 50"
						frc_func
						;;
					esac
					;;
					2)
					fpsfilter="filmdint=fast=0/io=30:24/dint_thres=256,"
					fps="-fps 30000/1001"
					ofps="-ofps 24000/1001"
					frc_func
					;;
					3)
					echo
					brown "FPS Conversion Filters"
					brown "~~~~~~~~~~~~~~~~~~~~~~"
					echo "0 -> Framestep & Filmdint"
					echo "1 -> Filmdint"
					echo
					printf "Which filter(s) to use? [default is 1]: "
					read fpscf
					case "$fpscf" in
						0)	fpsfilter="framestep=2,filmdint=fast=0/io=30:24/dint_thres=256," ;;
						1|"")	fpsfilter="filmdint=fast=0/io=60:24/dint_thres=256," ;;
						*)	unknown_options_func ;;
					esac
					fps="-fps 60000/1001"
					ofps="-ofps 24000/1001"
					frc_func
					;;
					4|5|6)
					echo
					brown "FPS Conversion Filters"
					brown "~~~~~~~~~~~~~~~~~~~~~~"
					echo "0 -> Framestep"
					echo "1 -> Filmdint"
					echo
					printf "Which filter to use? [default is 1]: "
					read fpscf
					case "$frc" in
						4)
						case "$fpscf" in
							0)	fpsfilter="framestep=2," ;;
							1|"")	fpsfilter="filmdint=fast=0/io=60:30/dint_thres=256," ;;
							*)	unknown_options_func ;;
						esac
						fps="-fps 60000/1001"
						ofps="-ofps 30000/1001"
						frc_func
						;;
						5)
						case "$fpscf" in
							0)	fpsfilter="framestep=2," ;;
							1|"")	fpsfilter="filmdint=fast=0/io=60:30/dint_thres=256," ;;
							*)	unknown_options_func ;;
						esac
						fps="-fps 60"
						ofps="-ofps 30"
						frc_func
						;;
						6)
						case "$fpscf" in
							0)	fpsfilter="framestep=2," ;;
							1|"")	fpsfilter="filmdint=fast=0/io=120:60/dint_thres=256," ;;
							*)	unknown_options_func ;;
						esac
						fps="-fps 120000/1001"
						ofps="-ofps 60000/1001"
						frc_func
						;;
					esac
					;;
					7)
					fps="-fps 25"
					ofps="-ofps 50"
					echo
					green "-> Setting input/output frame rate to 25/50 FPS"
					;;
					8)
					fps="-fps 30000/1001"
					ofps="-ofps 60000/1001"
					echo
					green "-> Setting input/output frame rate to 29.970/59.940 FPS"
					;;
					9)
					true
					;;
					*|"")
					error "-> Unknown option or frame rate conversion not selected!"
					exit_func 1
					;;
				esac
			fi
		fi
		;;
	esac
fi

if [ "$DISABLE_ALL_VID_FILTERS" = "n" ]; then
	# Pulldown reversal/inverse telecine/telecine
	# 3:2 pulldown filters. Mutually exclusive with
	# (frame doubling) deinterlacing filters and
	# FPS conversion
	case "$GETFPS" in
		23.976|29.970|23.97|29.97|59.94|59.940|"")
		if [ "$setfps" = "no" -a "$interlaced" = ":nointerlaced" -a -z "$deintfilter" -a -z "$frc" ]; then
			tpp=$(get_selection_func "Apply a Telecine/3:2 Pulldown/IVTC/Pullup process? [y/N]: ")
			if [ "$tpp" = "y" ]; then
				echo
				brown "Telecine/3:2 Pulldown/IVTC/Pullup"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "0 -> Inverse Telecine: 29.970 -> 23.976 fps"
				echo "1 -> Inverse Telecine: 59.940 -> 23.976 fps (filmdint/framestep)"
				echo "2 -> Inverse Telecine: 59.940 -> 23.976 fps (tinterlace/filmdint)"
				echo "3 -> Hard Telecine:    23.976 -> 29.970 fps"
				echo "4 -> Skip the Telecine/Pullup process"
				echo
				printf "Which process to use? [default is 0]: "
				read telproc
				case "$telproc" in
					0|"")
					echo
					brown "Available IVTC Filters"
					brown "~~~~~~~~~~~~~~~~~~~~~~"
					echo "0 -> Pullup (4th generation IVTC filter)"
					echo "1 -> Filmdint (3rd generation IVTC filter)"
					echo "2 -> IVTC (2nd generation IVTC filter)"
					echo "3 -> DETC (1st generation IVTC filter)"
					echo
					printf "Which Inverse Telecine/Pullup filter to use? [default is 1]: "
					read ivtc
					case "$ivtc" in
						0) ivtcfilter="pullup," ;;
						1|"") ivtcfilter="filmdint=fast=0," ;;
						2) ivtcfilter="ivtc=1," ;;
						3)
						echo
						brown "DETC Frame Dropping Modes"
						brown "~~~~~~~~~~~~~~~~~~~~~~~~~"
						echo "0 -> Always drop a frame if there has been"
						echo "     no drops or telecine merges in past"
						echo "     5 frames. (detc=dr=1)"
						echo
						echo "1 -> Always maintain exact 5:4 input to"
						echo "     output frame ratio. (detc=dr=2)"
						echo
						printf "Select a DETC frame dropping mode [default is 0]: "
						read detcmode
						case "$detcmode" in
							0|"") ivtcfilter="detc=dr=1," ;;
							1|*) ivtcfilter="detc=dr=2," ;;
						esac
						;;
						*)
						error "-> Unknown IVTC option: '$ivtc'"
						exit_func 1
						;;
					esac
					echo
					green "-> Setting input/output frame rate to 29.970 / 23.976 FPS"
					green "-> Using '$(echo $ivtcfilter | sed 's|,$||')' video filter(s)"
					fps="-fps 30000/1001"
					ofps="-ofps 24000/1001"
					;;
					1)
					fps="-fps 60000/1001"
					ofps="-ofps 24000/1001"
					ivtcfilter="filmdint=fast=0,framestep=2,"
					echo
					green "-> Setting input/output frame rate to 59.940 / 23.976 FPS"
					green "-> Using '$(echo $ivtcfilter | sed 's|,$||')' video filter(s)"
					;;
					2)
					fps="-fps 60000/1001"
					ofps="-ofps 24000/1001"
					ivtcfilter="tinterlace=4,filmdint=fast=0,"
					echo
					green "-> Setting input/output frame rate to 59.940 / 23.976 FPS"
					green "-> Using '$(echo $ivtcfilter | sed 's|,$||')' video filter(s)"
					;;
					3)
					# Both fps and ofps *must* be
					# 30000/1001 or we will lose
					# A/V sync due to limitations
					# in the filter layer of MEncoder
					fps="-fps 30000/1001"
					ofps="-ofps 30000/1001"
					telecinefilter=",telecine"
					interlaced=":interlaced:pic_struct"
					echo
					green "-> Setting input/output frame rate to 29.970 FPS"
					green "-> Using '$(echo $telecinefilter | sed 's|^,||')' video filter(s)"
					;;
					4) true ;;
					*)
					error "-> Unknown IVTC/Pulldown option: '$telproc'"
					exit_func 1
					;;
				esac
			fi
		fi
		;;
	esac
fi

# Overwrite input/output frame rate if the
# user has chosen to interlace his progressive
# content during the encoding process or if
# the user is deinterlacing it with a deinterlace
# filter which doubles the output frame rate.
# Only one at a time of the below conditionals
# can be true, the appropriate functions take
# care of that.

if [ ! -z "$intfilter" ]; then
	fps="-fps $intfps"
	ofps="-ofps $intofps"
fi

if [ ! -z "$deintfps" ]; then
	fps="-fps $deintfps"
	ofps="-ofps $deintofps"
fi

# Valid resolutions for
# portable devices
device_resolution_info_func() {
	case "$1" in
		fl|flhq)			green "-> Valid Flash Player resolutions: unrestricted, up to 1080p (1920x1080)" ;;
		ag1|ag1hq)			green "-> Valid Android G1 resolutions: up to 480x368" ;;
		ipc|ipchq)			green "-> Valid iPod Classic resolutions: 320x240" ;;
		ip|iphq)			green "-> Valid iPod resolutions: 320x240|480x320|640x480" ;;
		iph|iphhq)			green "-> Valid iPhone resolutions: 320x240|640x480" ;;
		atv|atvhq)			green "-> Valid AppleTV resolutions: unrestricted, up to 720p (1280x720)" ;;
		ar|arhq|ar5|ar5hq)		green "-> Valid Archos 605/5 resolutions: up to 720x576" ;;
		bb|bbhq)			green "-> Valid Blackberry 9000 resolutions: 320x240|480x320|640x480" ;;
		nks60|nks60hq)			green "-> Valid Nokia S60 resolutions: 320x240|352x416" ;;
		psp|psphq)			green "-> Valid Sony PSP resolutions: 320x240|368x208|352x480|480x272|720x480" ;;
		ps3|ps3hq)			green "-> Valid Sony PS3 resolutions: unrestricted, up to 1080p (1920x1080)" ;;
		mz|mzhq)			green "-> Valid MS Zune resolutions: 320x240|720x480|720x576" ;;
		mx|mxhq)			green "-> Valid XBOX 360 resolutions: unrestricted, up to 1080p (1920x1080)" ;;
		bd40|bdhq40|bd41|bdhq41)	green "-> Valid Blu-ray resolutions: 1920x1080, 1440x1080, 1280x720, 720x576, 720x480" ;;
		avchd|avchdhq)			green "-> Valid AVCHD resolutions: 1920x1080, 1440x1080, 1280x720, 720x576, 720x480" ;;
	esac
}

# Get resolution from the source and ask
# user if he wants to keep it. If cropping
# was used, then default resolution value
# will be that of the visible area left
# over after the cropping. If no cropping
# was used, then default resolution value
# will be the original one from the source

ratio_and_pixels_func() {
	case "$1" in
		detect)
		VWIDTH="$(echo "$GETRES" | awk -Fx '{print $1}')"
		VHEIGHT="$(echo "$GETRES" | awk -Fx '{print $2}')"
		RATIO="$(grep '^ID_VIDEO_ASPECT' "$TEMPDIR/resolution" | tail -n 1 | awk -F= '{print $2}')"
		DEFRATIO="$RATIO"
		PIXELS="$(($(echo "$GETRES" | sed 's|x|*|')))"
		green "-> Detected Aspect Ratio (AR): $RATIO:1"
		;;
		cropped)
		VWIDTH="$(echo $cropfilter | sed 's|crop=||' | awk -F: '{print $1}')"
		VHEIGHT="$(echo $cropfilter | sed 's|crop=||' | awk -F: '{print $2}')"
		RATIO="$VWIDTH/$VHEIGHT"
		DEFRATIO="$(echo "scale=4; $RATIO" | $BC -l | sed 's|^\.|0\.|')"
		PIXELS="$(($(echo "$GETRES" | sed 's|x|*|')))"
		green "-> Detected Aspect Ratio (AR): $(echo "scale=4; $RATIO" | $BC -l | sed 's|^\.|0\.|'):1"
		;;
		scaled)
		VWIDTH="$(echo $scale | sed "s|${ilpack}scale=||" | awk -F: '{print $1}')"
		VHEIGHT="$(echo $scale | sed "s|${ilpack}scale=||" | awk -F: '{print $2}')"
		RATIO="$VWIDTH/$VHEIGHT"
		DEFRATIO="$(echo "scale=4; $RATIO" | $BC -l | sed 's|^\.|0\.|')"
		PIXELS="$(($(echo $scale | sed "s|${ilpack}scale=||; s|:|*|")))"
		green "-> Aspect Ratio (AR): $(echo "scale=4; $RATIO" | $BC -l | sed 's|^\.|0\.|'):1"
		;;
	esac
	# PAR = aspect_ratio * image_height / image_width
	PAR="$(echo "scale=4; $RATIO*$VHEIGHT/$VWIDTH" | $BC -l | sed 's|^\.|0\.|')"
	green "-> Pixel Aspect Ratio (PAR): $PAR:1"
	green "-> Total pixels: $PIXELS"
}

echo
if [ ! -z "$cropfilter" ]; then
	restype="Cropped"
	green "-> Detecting cropped resolution..."
	GETRES=$(echo $cropfilter | sed 's|crop=||; s|,||; s|:|x|' | awk -F: '{print $1}')
else
	restype="Original"
	green "-> Detecting original resolution..."
	if [ "$source" = "bd" ]; then
		demuxer="-demuxer lavf"
	fi
	$MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid $demuxer $cache -vo null -nosound -identify -frames 1 2>/dev/null > "$TEMPDIR/resolution"
	WORIG=$(awk -F= '/^ID_VIDEO_WIDTH/  { print $2 }' < "$TEMPDIR/resolution")
	HORIG=$(awk -F= '/^ID_VIDEO_HEIGHT/ { print $2 }' < "$TEMPDIR/resolution")
	GETRES="${WORIG}x${HORIG}"
fi

if [ ! -z "$GETRES" ]; then
	green "-> $restype resolution: $GETRES"
	device_resolution_info_func $3
	echo
	if [ ! -z "$cropfilter" ]; then
		ratio_and_pixels_func cropped
	else
		ratio_and_pixels_func detect
	fi
else
	error "-> Failed to detect the $restype resolution!"
	if [ "$DISABLE_ALL_VID_FILTERS" = "n" ]; then
		error "-> You have to provide it yourself!"
		GETRES="??"
	fi
	device_resolution_info_func $3
fi
rm -f "$TEMPDIR/resolution"
echo

if [ "$DISABLE_ALL_VID_FILTERS" = "n" ]; then
	printf "Specify the desired Resolution [default is $GETRES]: "
	read vres
	if [ -z "$vres" -a "$GETRES" = "??" ]; then
		error "-> You have to specify the resolution!"
		exit_func 1
	fi
fi

case "$vres" in
	$GETRES|"")
	if [ ! -z "$ilpack" ]; then
		scale="${ilpack}scale=::1"
	fi
	;;
	*)
	scale="${ilpack}scale=$(echo $vres | tr '[:alpha:]' ':')"
	# Interlace parameters for the scaler
	if [ "$interlaced" = ":tff:pic_struct" -o "$interlaced" = ":bff:pic_struct" -a -z "$intfilter" -a -z "$telecinefilter" ]; then
		isws=":1"
	else
		isws=":0"
	fi
	if [ ! -z "$DEFAULT_SOFTWARE_SCALER" ]; then
		case "$DEFAULT_SOFTWARE_SCALER" in
			[0-9]|10)
			sws="-sws $DEFAULT_SOFTWARE_SCALER"
			case "$DEFAULT_SOFTWARE_SCALER" in
				0)	swstype="Fast Bilinear" ;;
				1)	swstype="Bilinear" ;;
				2)	swstype="Bicubic" ;;
				3)	swstype="Experimental" ;;
				4)	swstype="Nearest Neighbor/Point" ;;
				5)	swstype="Area Averaging" ;;
				6)	swstype="Luma Bicubic/Chroma Bilinear" ;;
				7)	swstype="Gaussian" ;;
				8)	swstype="Sinc" ;;
				9)	swstype="Lanczos" ;;
				10)	swstype="Natural Bicubic Spline" ;;
			esac
			echo
			green "-> Using default software scaler defined in the config file: $swstype"
			echo
			;;
			*)
			echo
			error "-> Invalid default software scaler in the config file!"
			echo
			exit_func 1
			;;
		esac
	else
		echo
		brown "Available Software Scalers"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "0 --> Fast Bilinear"
		echo "1 --> Bilinear"
		echo "2 --> Bicubic"
		echo "3 --> Experimental"
		echo "4 --> Nearest Neighbor/Point"
		echo "5 --> Area Averaging"
		echo "6 --> Luma Bicubic/Chroma Bilinear"
		echo "7 --> Gaussian"
		echo "8 --> Sinc"
		echo "9 --> Lanczos"
		echo "10 -> Natural Bicubic Spline"
		echo
	fi
	# Check if width & height are divisible
	# by 16 and if not display a warning
	WMOD16=$(echo "scale=3; $(echo $scale | sed "s|${ilpack}scale=||" | awk -F: '{print $1}')/16" | $BC -l | awk -F. '{print $2}')
	HMOD16=$(echo "scale=3; $(echo $scale | sed "s|${ilpack}scale=||" | awk -F: '{print $2}')/16" | $BC -l | awk -F. '{print $2}')
	if [ "$WMOD16" != "000" -o "$HMOD16" != "000" ]; then
		error "-> Warning: width and/or height not divisible by 16!"
		error "-> Compression will suffer a bit!"
		echo
	fi
	ratio_and_pixels_func scaled
	echo
	if [ -z "$DEFAULT_SOFTWARE_SCALER" ]; then
		printf "Select a Software Scaler [default is 10]: "
		read softscale
		if [ -z "$softscale" ]; then
			sws="-sws 10"
		else
			sws="-sws $softscale"
		fi
	fi
	# software scaler tuning, only supported
	# by bicubic, bicubic spline, gaussian
	# and lanczos scalers
	if [ "$ALLOW_VID_SCALER_TUNING" = "y" ]; then
		case $(echo "$sws" | awk '{print $2}') in
			2|10)
			sstune=$(get_selection_func "Would you like to tune the Software Scaler? [y/N]: ")
			if [ "$sstune" = "y" ]; then
				echo
				brown "Software Scaler Parameters"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "Here you can tune some parameters of"
				echo "the Bicubic/Natural Bicubic Spline"
				echo "software scalers. The first value"
				echo "represents the amount of blurring while"
				echo "the second value represents the amount"
				echo "of ringing. The higher the values, the"
				echo "more blurring/ringing you'll get."
				echo
				echo "Below are some frequently used settings"
				echo "Format is as follows: blurring:ringing"
				echo
				echo "0 -> 0.00:0.60 -> Default"
				echo "1 -> 0.00:0.75 -> VirtualDub's \"Precise Bicubic\""
				echo "2 -> 0.00:0.50 -> Catmull-Rom Spline"
				echo "3 -> 0.33:0.33 -> Mitchell-Netravali Spline"
				echo "4 -> 1.00:0.00 -> Cubic B-Spline"
				echo "5 -> User defined"
				echo "6 -> Skip parameter settings"
				echo
				printf "Select the Software Scaler Parameters [default is 0]: "
				read ssparam
				case "$ssparam" in
					0|"") swsparam="::0.00:0.60" ;;
					1) swsparam="::0.00:0.75" ;;
					2) swsparam="::0.00:0.50" ;;
					3) swsparam="::0.33:0.33" ;;
					4) swsparam="::1.00:0.00" ;;
					5)
					printf "Specify the Software Scaler Parameters [default is 0.00:0.60]: "
					read ssp
					if [ -z "$ssp" ]; then
						swsparam="::0.00:0.60"
					else
						swsparam="::$ssp"
					fi
					;;
					6) true ;;
					*)
					error "-> Unknown software scaler parameters option: '$ssparam'"
					exit_func 1
					;;
				esac
			fi
			;;
			7)
			sstune=$(get_selection_func "Would you like to tune the Software Scaler? [y/N]: ")
			if [ "$sstune" = "y" ]; then
				echo
				brown "Software Scaler Parameters"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "Here you can tune the sharpness of the"
				echo "Gaussian software scaler. Values are"
				echo "between 0 and 100. The higher the value"
				echo "the sharper the image will be"
				echo
				printf "Specify the Software Scaler Parameter [default is 0]: "
				read ssparam
				if [ ! -z "$ssparam" ]; then
					swsparam="::$ssparam"
				fi
			fi
			;;
			9)
			sstune=$(get_selection_func "Would you like to tune the Software Scaler? [y/N]: ")
			if [ "$sstune" = "y" ]; then
				echo
				brown "Software Scaler Parameters"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "Here you can tune the filter length of"
				echo "the Lanczos software scaler. Values are"
				echo "between 1 and 10. The higher the value"
				echo "the sharper the image will be"
				echo
				printf "Specify the Software Scaler Parameter [default is 1]: "
				read ssparam
				if [ ! -z "$ssparam" ]; then
					swsparam="::$ssparam"
				fi
			fi
			;;
		esac
	fi
	;;
esac

if [ "$DISABLE_ALL_VID_FILTERS" = "n" ]; then
	if [ "$ALLOW_VID_DSIZE" = "y" ]; then
		if [ ! -z "$scale" ]; then
			printf "Specify the Display Size/Aspect [press 'Enter' to skip]: "
			read dsize
			if [ ! -z "$dsize" ]; then
				dsizefilter="dsize=$dsize,"
			fi
		fi
	fi

	if [ "$ALLOW_VID_EXPAND" = "y" ]; then
		printf "Specify the Expand filter parameters [press 'Enter' to skip]: "
		read exp_param
		if [ ! -z "$exp_param" ]; then
			if [ ! -z "$scale" ]; then
				printf "Place the filter before (b) or after (a) the scale filter? [b/a - default is a]: "
				read expandpos
				case "$expandpos" in
					a|A|"")	expandfilter_afr=",expand=$(echo "$exp_param" | tr '[:alpha:]' ':')" ;;
				*)	expandfilter_bfr="expand=$(echo "$exp_param" | tr '[:alpha:]' ':')," ;;
				esac
			else
			expandfilter_bfr="expand=$(echo "$exp_param" | tr '[:alpha:]' ':'),"
			fi
		fi
	fi

	# Do a colorspace conversion?
	# Don't ask for this when using
	# the portable device presets
	if [ "$ALLOW_VID_COLORSPACE" = "y" ]; then
		case "$3" in
			bd40|bdhq40|bd41|bdhq41|avchd|avchdhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|ipc|ipchq|ip|iphq|iph|iphhq|psp|psphq|mz|mzhq)
			true
			;;
			*)
			if [ ! -z "$scale" ]; then
				if [ -z "$fpsfilter" -a -z "$intfilter" -a -z "$telecinefilter" -a "$interlaced" = ":nointerlaced" ]; then
					video_colorspace_func
				fi
			fi
			;;
		esac
	fi
fi

# Aspect ratio
if [ "$ALLOW_VID_ASPECT" = "y" ]; then
	aratio=$(get_selection_func "Would you like to set/force the input Video Aspect Ratio? [y/N]: ")
	if [ "$aratio" = "y" ]; then
		echo
		green "-> Detecting video aspect ratio..."
		if [ ! -z "$DEFRATIO" ]; then
			green "-> Detected: $DEFRATIO"
			V_ASPECT="$DEFRATIO"
		else
			error "-> Could not detect the video aspect!"
			V_ASPECT="16:9"
		fi
		echo
		printf "Specify the Aspect Ratio [4:3/16:9/1.3333/1.7778... - default is $V_ASPECT]: "
		read asra
		if [ -z "$asra" ]; then
			aspect="-aspect $V_ASPECT"
		else
			aspect="-aspect $asra"
		fi
	fi
fi

##############################################
############## H.264 Settings ################
##############################################

echo
brown "+=============================+"
brown "| H.264 Encoder Configuration |"
brown "+=============================+"
echo

# Skip bitrate/quant settings if
# user chooses the NLQ preset
if [ "$3" != "nlq" ]; then
	case "$1" in
		-[1-3]p)
		if [ ! -z "$DEFAULT_VID_BITRATE" ]; then
			green "-> Using default bitrate value from config file: $DEFAULT_VID_BITRATE"
			bitrate="bitrate=$DEFAULT_VID_BITRATE"
		else
			printf "Specify the desired Video Bitrate in kbps [default is 2000]: "
			read vbitrate
			if [ -z "$vbitrate" ]; then
				bitrate="bitrate=2000"
			else
				bitrate="bitrate=$vbitrate"
			fi
		fi
		bits_per_pixel_func
		bits_per_block_func
		;;
		-qp|-crf)
		if [ ! -z "$DEFAULT_VID_CRFQP" ]; then
			case "$DEFAULT_VID_CRFQP" in
				[0-9]|[0-9].[0-9]|1[0-9]|1[0-9].[0-9]|2[0-9]|2[0-9].[0-9]|3[0-9]|3[0-9].[0-9]|4[0-9]|4[0-9].[0-9]|50.[0-9]|51|51.0)
				green "-> Using default CRF/QP value from the config file: $DEFAULT_VID_CRFQP"
				bitrate="$(echo $1 | sed 's|-||')=$DEFAULT_VID_CRFQP"
				;;
				*)
				error "-> Invalid CRF/QP value in the config file: $DEFAULT_VID_CRFQP"
				error "-> Using default value of 18"
				bitrate="$(echo $1 | sed 's|-||')=18"
				echo
				;;
			esac
		else
			printf "Specify the desired $(echo $1 | sed 's|-||' | tr '[:lower:]' '[:upper:]') value [0.0-51.0, lower is better - default is 18]: "
			read crfqp
			if [ -z "$crfqp" ]; then
				bitrate="$(echo $1 | sed 's|-||')=18"
			else
				bitrate="$(echo $1 | sed 's|-||')=$crfqp"
			fi
			echo
		fi
		;;
	esac
fi

#############################################
############### Presets #####################
#############################################

# Set min/max keyframes according
# to chosen/detected FPS value

case "$GETFPS" in
	5.000|5.00)			keyint=":keyint=50" ;;
	10.000|10.00)			keyint=":keyint=100" ;;
	12.000|12.00)			keyint=":keyint=120" ;;
	15.000|15.00)			keyint=":keyint=150" ;;
	15.98[4-5]|15.98)		keyint=":keyint=160" ;;
	17.982|17.98)			keyint=":keyint=180" ;;
	25.000|25.00)			keyint=":keyint=250" ;;
	50.000|50.00)			keyint=":keyint=500" ;;
	100.000|100.00)			keyint=":keyint=1000" ;;
	23.976|24.000|23.97|24.00)	keyint=":keyint=240" ;;
	29.970|29.97|30.000|30.00)	keyint=":keyint=300" ;;
	59.940|59.94|60.000|60.00)	keyint=":keyint=600" ;;
	119.880|119.88)			keyint=":keyint=1200" ;;
	*|"")				keyint=":keyint=250" ;;
esac
# Overwrite the above if the user has
# chosen to set the fps manually or
# has chosen to do an ivtc/3:2 pulldown
# or if he wants to interlace his
# progressive content during the encoding
# or deinterlace it with a frame doubling
# filter.
if [ ! -z "$ofps" ]; then
	if [ ! -z "$(echo $ofps | grep '/')" ]; then
		keyint=":keyint=$(($(echo $ofps | awk '{print $2}')+1))0"
	else
		keyint=":keyint=$(echo $ofps | awk '{print $2}')0"
	fi
fi
keyint_min=":keyint_min=$(($(echo $keyint | awk -F= '{print $2}')/10))"

display_quality_preset_func $3 $4

case "$3" in
	ulq|elq|vlq|lq|mq|nq|hq|vhq|ehq|uhq|ihq|nlq|ani|anihq|fghq)
	echo
	printf "Specify the H.264 Level [default is auto]: "
	read level
	case "$level" in
		auto|"")
		true
		;;
		1.[0-3]|1[0-3]|2.[0-2]|2[0-2]|3.[0-2]|3[0-2]|4.[0-2]|4[0-2]|5.[0-1]|5[0-1])
		h264level=":level_idc=$(echo $level | sed 's|\.||')"
		;;
		*)
		echo
		green "-> Unknown H.264 level: $level"
		green "-> Valid levels: 1.0, 1.1, 1.2, 1.3, 2.0, 2.1, 2.2, 3.0"
		green "                 3.1, 3.2, 4.0, 4.1, 4.2, 5.0, 5.1, auto"
		green "-> Falling back to level 4.1"
		echo
		h264level=":level_idc=41"
		;;
	esac
	;;
esac

case "$3" in
	ulq|elq|vlq|lq|mq|nq|hq|vhq|ehq|uhq|ihq|nlq|ani|anihq|fghq) true ;;
	*) echo ;;
esac

frepa=$(get_selection_func "Define Frame Arrangements for 3D Video? [y/N]: ")
if [ "$frepa" = "y" ]; then
	echo
	brown "Frame Packing for 3D Video"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 -> checkerboard - pixels are alternatively from L and R"
	echo "1 -> column alternation - L and R are interlaced by column"
	echo "2 -> row alternation - L and R are interlaced by row"
	echo "3 -> side by side - L is on the left, R on the right"
	echo "4 -> top bottom - L is on top, R on bottom"
	echo "5 -> frame alternation - one view per frame"
	echo "6 -> mono - 2D frame without any frame packing"
	echo "7 -> tile format - L is on top-left, R split across"
	echo "8 -> Skip this option"
	echo
	printf "Select the Frame Packing mode [default is 3]: "
	read fpm
	case "$fpm" in
		0)	frame_packing=":frame_packing=0" ;;
		1)	frame_packing=":frame_packing=1" ;;
		2)	frame_packing=":frame_packing=2" ;;
		3|"")	frame_packing=":frame_packing=3" ;;
		4)	frame_packing=":frame_packing=4" ;;
		5)	frame_packing=":frame_packing=5" ;;
		6)	frame_packing=":frame_packing=6" ;;
		7)	frame_packing=":frame_packing=7" ;;
		8)	true ;;
		*)
		error "-> Unknown option!"
		exit_func 1
		;;
	esac
fi

if [ "$3" != "cp" ]; then
	cptm=$(get_selection_func "Define Color Primaries, Transfers and Matrices? [y/N]: ")
	if [ "$cptm" = "y" ]; then
		echo
		brown "Color Primaries, Transfers and Matrices"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> NTSC (SMPTE170M)"
		echo "1 -> PAL (BT470BG)"
		echo "2 -> HD/Full HD (BT709)"
		echo
		printf "Select an option [default is not set]: "
		read cptmopt
		case "$cptmopt" in
			0) colorprim=":colorprim=smpte170m:transfer=smpte170m:colormatrix=smpte170m" ;;
			1) colorprim=":colorprim=bt470bg:transfer=bt470bg:colormatrix=bt470bg" ;;
			2) colorprim=":colorprim=bt709:transfer=bt709:colormatrix=bt709" ;;
		esac
	fi
fi

case "$3" in
	bd40|bdhq40|bd41|bdhq41|avchd|avchdhq)
	if [ "$interlaced" = ":nointerlaced" ]; then
		if [ "$ofps" = "-ofps 25" -o "$ofps" = "-ofps 30000/1001" -o "$GETFPS" = "25.000" -o "$GETFPS" = "29.970" ]; then
			fakeint=$(get_selection_func "Flag the Encode as Fake Interlaced? [y/N]: ")
			if [ "$fakeint" = "y" ]; then
				fake_interlaced=":fake_interlaced=1"
			fi
		fi
	fi
	key_int="$(($(echo $keyint | sed 's|:keyint=||')/10))"
	;;
esac

case "$3" in
	cp)		source "$4" ;;
	ulq)		x264params=":force_cfr:frameref=0:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=2:me=dia:subq=1:nombtree:nochroma_me:trellis=0:nocabac:nodeblock:no8x8dct:partitions=none:fast_pskip:dct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	elq)		x264params=":force_cfr:frameref=1:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=2:me=dia:subq=2:nombtree:nochroma_me:trellis=0:nocabac:nodeblock:no8x8dct:partitions=none:fast_pskip:dct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	vlq)		x264params=":force_cfr:frameref=1:nomixed_refs:bframes=4:b_adapt=1:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=2:me=dia:subq=3:nombtree:nochroma_me:trellis=0:nocabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:dct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	lq)		x264params=":force_cfr:frameref=2:nomixed_refs:bframes=6:b_adapt=1:b_pyramid=normal:noweight_b:weightp=0:direct_pred=spatial:aq_mode=2:me=dia:subq=4:nombtree:nochroma_me:trellis=0:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:dct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	mq)		x264params=":force_cfr:frameref=2:mixed_refs:bframes=8:b_adapt=1:b_pyramid=normal:weight_b:weightp=0:direct_pred=spatial:aq_mode=2:me=hex:subq=5:nombtree:nochroma_me:trellis=0:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:dct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	nq)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=10:b_adapt=1:b_pyramid=normal:weight_b:weightp=1:direct_pred=spatial:aq_mode=2:me=hex:subq=6:nombtree:chroma_me:trellis=1:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	hq)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=4:b_adapt=2:b_pyramid=normal:weight_b:weightp=1:direct_pred=auto:aq_mode=1:me=umh:me_range=16:subq=7:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	vhq)		x264params=":force_cfr:frameref=4:mixed_refs:bframes=5:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:aq_strength=1.08:me=umh:me_range=24:subq=9:mbtree:psy_rd=1.0,0.15:chroma_me:trellis=1:cabac:deblock=-1,-1:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	ehq)		x264params=":force_cfr:frameref=5:mixed_refs:bframes=6:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:aq_strength=1.13:me=umh:me_range=32:subq=10:mbtree:rc_lookahead=80:psy_rd=1.1,0.15:chroma_me:trellis=1:cabac:deblock=-1,-1:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	uhq)		x264params=":force_cfr:frameref=6:mixed_refs:bframes=7:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:aq_strength=1.13:me=esa:me_range=48:subq=11:mbtree:rc_lookahead=90:psy_rd=1.1,0.15:chroma_me:trellis=2:cabac:deblock=-1,-1:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	ihq)		x264params=":force_cfr:frameref=10:mixed_refs:bframes=7:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:aq_strength=1.13:me=tesa:me_range=64:subq=11:mbtree:rc_lookahead=100:psy_rd=1.1,0.15:chroma_me:trellis=2:cabac:deblock=-1,-1:8x8dct:partitions=all:nofast_pskip:nodct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	nlq)		bitrate="crf=8"; x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:me=umh:subq=9:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=2:cabac:deblock=-1,-1:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	fghq)		x264params=":force_cfr:frameref=4:mixed_refs:bframes=5:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:aq_strength=0.5:me=umh:me_range=24:subq=8:mbtree:psy_rd=1.0,0.25:chroma_me:trellis=0:cabac:deblock=-2,-2:ip_factor=1.1:pb_factor=1.1:deadzone_intra=6:deadzone_inter=6:qcomp=0.8:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	ani)		x264params=":force_cfr:frameref=8:mixed_refs:bframes=5:b_adapt=2:b_pyramid=normal:noweight_b:weightp=1:direct_pred=auto:aq_mode=2:aq_strength=0.5:me=hex:subq=9:nombtree:psy_rd=0.3,0.0:chroma_me:trellis=1:cabac:deblock=1,1:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	anihq)		x264params=":force_cfr:frameref=10:mixed_refs:bframes=5:b_adapt=2:b_pyramid=normal:noweight_b:weightp=2:direct_pred=auto:aq_mode=1:aq_strength=0.5:me=umh:me_range=24:subq=10:mbtree:psy_rd=0.3,0.0:chroma_me:trellis=2:cabac:deblock=1,1:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:threads=auto$keyint$keyint_min$h264level$frame_packing" ;;
	vdhq)		x264params=":force_cfr:frameref=4:mixed_refs:bframes=3:b_adapt=2:b_pyramid=normal:weight_b:weightp=1:direct_pred=auto:aq_mode=1:me=umh:me_range=24:subq=7:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:vbv_maxrate=5000:vbv_bufsize=5000:threads=auto$keyint$keyint_min$frame_packing" ;;
	vdehq)		x264params=":force_cfr:frameref=4:mixed_refs:bframes=3:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:me=umh:me_range=24:subq=8:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=2:cabac:deblock:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:vbv_maxrate=5000:vbv_bufsize=5000:threads=auto$keyint$keyint_min$frame_packing" ;;
	vdihq)		x264params=":force_cfr:frameref=4:mixed_refs:bframes=3:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:me=tesa:me_range=32:subq=9:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=2:cabac:deblock:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:vbv_maxrate=5000:vbv_bufsize=5000:threads=auto$keyint$keyint_min$frame_packing" ;;
	fl)		x264params=":force_cfr:frameref=2:mixed_refs:bframes=3:b_adapt=2:b_pyramid=none:weight_b:weightp=1:direct_pred=spatial:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:threads=auto$keyint$keyint_min$frame_packing" ;;
	flhq)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=6:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:me=umh:me_range=24:subq=7:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:threads=auto$keyint$keyint_min$frame_packing" ;;
	qt)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=none:weight_b:weightp=1:direct_pred=auto:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:threads=auto$keyint$keyint_min$frame_packing" ;;
	qthq)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:me=umh:me_range=24:subq=7:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:threads=auto$keyint$keyint_min$frame_packing" ;;
	bd40)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=strict:weight_b:weightp=0:direct_pred=auto:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:slices=4:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=40:aud:nal_hrd=vbr:keyint=$key_int:keyint_min=1:vbv_maxrate=20000:vbv_bufsize=25000:bluray_compat=1:threads=auto$colorprim$fake_interlaced$frame_packing" ;;
	bdhq40)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=strict:weight_b:weightp=1:direct_pred=auto:aq_mode=1:aq_strength=1.13:me=umh:me_range=24:subq=10:mbtree:psy_rd=1.1,0.15:chroma_me:trellis=2:cabac:deblock=-1,-1:8x8dct:slices=4:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=40:aud:nal_hrd=vbr:keyint=$key_int:keyint_min=1:vbv_maxrate=25000:vbv_bufsize=30000:bluray_compat=1:threads=auto$colorprim$fake_interlaced$frame_packing" ;;
	bd41)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=strict:weight_b:weightp=0:direct_pred=auto:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:slices=4:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:aud:nal_hrd=vbr:keyint=$key_int:keyint_min=1:vbv_maxrate=40000:vbv_bufsize=30000:bluray_compat=1:threads=auto$colorprim$fake_interlaced$frame_packing" ;;
	bdhq41)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=strict:weight_b:weightp=1:direct_pred=auto:aq_mode=1:aq_strength=1.13:me=umh:me_range=24:subq=10:mbtree:psy_rd=1.1,0.15:chroma_me:trellis=2:cabac:deblock=-1,-1:8x8dct:slices=4:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:aud:nal_hrd=vbr:keyint=$key_int:keyint_min=1:vbv_maxrate=40000:vbv_bufsize=30000:bluray_compat=1:threads=auto$colorprim$fake_interlaced$frame_packing" ;;
	avchd)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=strict:weight_b:weightp=0:direct_pred=auto:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:slices=4:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=40:aud:nal_hrd=vbr:keyint=$key_int:keyint_min=1:vbv_maxrate=18000:vbv_bufsize=17000:bluray_compat=1:threads=auto$colorprim$fake_interlaced$frame_packing" ;;
	avchdhq)	x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=strict:weight_b:weightp=1:direct_pred=auto:aq_mode=1:aq_strength=1.13:me=umh:me_range=24:subq=10:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=2:cabac:deblock=-1,-1:8x8dct:slices=4:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:aud:nal_hrd=vbr:keyint=$key_int:keyint_min=1:vbv_maxrate=18000:vbv_bufsize=17000:bluray_compat=1:threads=auto$colorprim$fake_interlaced$frame_packing" ;;
	ag1)		x264params=":force_cfr:frameref=1:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.0:chroma_me:trellis=1:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:fast_pskip:dct_decimate:level_idc=30:vbv_maxrate=2000:vbv_bufsize=2000:threads=auto$keyint$keyint_min$frame_packing" ;;
	ag1hq)		x264params=":force_cfr:frameref=1:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=1:me=umh:subq=8:mbtree:psy_rd=0.8,0.0:chroma_me:trellis=2:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:fast_pskip:dct_decimate:level_idc=30:vbv_maxrate=2000:vbv_bufsize=2000:threads=auto$keyint$keyint_min$frame_packing" ;;
	ipc)		x264params=":force_cfr:frameref=1:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.0:chroma_me:trellis=1:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:fast_pskip:dct_decimate:level_idc=13:vbv_maxrate=768:vbv_bufsize=500:threads=auto$keyint$keyint_min$frame_packing" ;;
	ipchq)		x264params=":force_cfr:frameref=1:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=1:me=umh:subq=8:mbtree:psy_rd=0.8,0.0:chroma_me:trellis=2:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:nofast_pskip:dct_decimate:level_idc=13:vbv_maxrate=768:vbv_bufsize=500:threads=auto$keyint$keyint_min$frame_packing" ;;
	ip|iph)
	case "$3" in
		ip)	vbv_maxrate=":vbv_maxrate=2500"; vbv_bufsize=":vbv_bufsize=2000" ;;
		iph)	vbv_maxrate=":vbv_maxrate=1500"; vbv_bufsize=":vbv_bufsize=1000" ;;
	esac
	x264params=":force_cfr:frameref=1:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.0:chroma_me:trellis=1:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:fast_pskip:dct_decimate:level_idc=30:threads=auto$vbv_maxrate$vbv_bufsize$keyint$keyint_min$frame_packing"
	;;
	iphq|iphhq)
	case "$3" in
		iphq)	level_idc=":level_idc=30"; vbv_maxrate=":vbv_maxrate=2500"; vbv_bufsize=":vbv_bufsize=2000" ;;
		iphhq)	level_idc=":level_idc=31"; vbv_maxrate=":vbv_maxrate=10000"; vbv_bufsize=":vbv_bufsize=10000" ;;
	esac
	x264params=":force_cfr:frameref=1:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=1:me=umh:subq=8:mbtree:psy_rd=0.8,0.0:chroma_me:trellis=2:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:nofast_pskip:dct_decimate:threads=auto$level_idc$vbv_maxrate$vbv_bufsize$keyint$keyint_min$frame_packing"
	;;
	atv)		x264params=":force_cfr:frameref=1:nomixed_refs:bframes=2:b_adapt=2:b_pyramid=none:noweight_b:weightp=0:direct_pred=auto:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.0:chroma_me:trellis=1:nocabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:dct_decimate:level_idc=30:vbv_maxrate=12000:vbv_bufsize=5000:threads=auto$keyint$keyint_min$frame_packing" ;;
	atvhq)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=normal:weight_b:weightp=0:direct_pred=auto:aq_mode=1:me=umh:me_range=24:subq=7:mbtree:psy_rd=0.8,0.0:chroma_me:trellis=2:nocabac:deblock:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:dct_decimate:level_idc=30:vbv_maxrate=12000:vbv_bufsize=5000:threads=auto$keyint$keyint_min$frame_packing" ;;
	ar)		x264params=":force_cfr:frameref=1:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.0:chroma_me:trellis=1:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:nofast_pskip:dct_decimate:level_idc=30:vbv_maxrate=5000:vbv_bufsize=3000:threads=auto$keyint$keyint_min$frame_packing" ;;
	arhq)		x264params=":force_cfr:frameref=1:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=1:me=umh:me_range=24:subq=8:mbtree:psy_rd=0.8,0.0:chroma_me:trellis=2:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:nofast_pskip:dct_decimate:level_idc=30:vbv_maxrate=5000:vbv_bufsize=3000:threads=auto$keyint$keyint_min$frame_packing" ;;
	ar5)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=2:b_adapt=2:b_pyramid=strict:weight_b:weightp=1:direct_pred=auto:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=40:vbv_maxrate=2000:vbv_bufsize=1700:threads=auto$keyint$keyint_min$frame_packing" ;;
	ar5hq)		x264params=":force_cfr:frameref=4:mixed_refs:bframes=4:b_adapt=2:b_pyramid=strict:weight_b:weightp=2:direct_pred=auto:aq_mode=1:me=umh:me_range=24:subq=7:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=40:vbv_maxrate=2000:vbv_bufsize=1700:threads=auto$keyint$keyint_min$frame_packing" ;;
	bb)		x264params=":force_cfr:frameref=1:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.0:chroma_me:trellis=1:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:nofast_pskip:dct_decimate:level_idc=30:vbv_maxrate=1500:vbv_bufsize=1000:threads=auto$keyint$keyint_min$frame_packing" ;;
	bbhq)		x264params=":force_cfr:frameref=2:mixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=1:me=umh:subq=8:mbtree:psy_rd=0.8,0.0:chroma_me:trellis=2:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:nofast_pskip:dct_decimate:level_idc=30:vbv_maxrate=1500:vbv_bufsize=1000:threads=auto$keyint$keyint_min$frame_packing" ;;
	nks60)		x264params=":force_cfr:frameref=2:mixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.0:chroma_me:trellis=1:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:nofast_pskip:dct_decimate:level_idc=12:vbv_maxrate=384:vbv_bufsize=900:threads=auto$keyint$keyint_min$frame_packing" ;;
	nks60hq)	x264params=":force_cfr:frameref=3:mixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=1:me=umh:subq=8:mbtree:psy_rd=0.8,0.0:chroma_me:trellis=2:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:nofast_pskip:dct_decimate:level_idc=12:vbv_maxrate=384:vbv_bufsize=900:threads=auto$keyint$keyint_min$frame_packing" ;;
	psp)		x264params=":force_cfr:frameref=2:mixed_refs:bframes=3:b_adapt=2:b_pyramid=none:weight_b:weightp=1:direct_pred=spatial:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:fast_pskip:nodct_decimate:level_idc=30:vbv_maxrate=4000:vbv_bufsize=2500:threads=auto$keyint$keyint_min$frame_packing" ;;
	psphq)		x264params=":force_cfr:frameref=2:mixed_refs:bframes=3:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:me=umh:subq=7:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=30:vbv_maxrate=4000:vbv_bufsize=2500:threads=auto$keyint$keyint_min$frame_packing" ;;
	ps3)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=none:weight_b:weightp=1:direct_pred=spatial:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:aud:vbv_maxrate=20000:vbv_bufsize=20000:threads=auto$keyint$keyint_min$frame_packing" ;;
	ps3hq)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=3:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:me=umh:me_range=24:subq=7:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:aud:vbv_maxrate=20000:vbv_bufsize=20000:threads=auto$keyint$keyint_min$frame_packing" ;;
	mz)		x264params=":force_cfr:frameref=1:nomixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.0:chroma_me:trellis=1:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:fast_pskip:dct_decimate:level_idc=30:vbv_maxrate=2500:vbv_bufsize=2000:threads=auto$keyint$keyint_min$frame_packing" ;;
	mzhq)		x264params=":force_cfr:force_cfr:frameref=3:mixed_refs:bframes=0:b_adapt=0:b_pyramid=none:noweight_b:weightp=0:direct_pred=none:aq_mode=1:me=umh:me_range=24:subq=7:mbtree:psy_rd=0.8,0.0:chroma_me:trellis=2:nocabac:deblock:no8x8dct:partitions=p8x8,i4x4:nofast_pskip:dct_decimate:level_idc=30:vbv_maxrate=2500:vbv_bufsize=2000:threads=auto$keyint$keyint_min$frame_packing" ;;
	mx)		x264params=":force_cfr:frameref=2:mixed_refs:bframes=3:b_adapt=2:b_pyramid=none:weight_b:weightp=1:direct_pred=spatial:aq_mode=2:me=hex:subq=6:nombtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:no8x8dct:partitions=p8x8,b8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:vbv_maxrate=20000:vbv_bufsize=20000:threads=auto$keyint$keyint_min$frame_packing" ;;
	mxhq)		x264params=":force_cfr:frameref=3:mixed_refs:bframes=6:b_adapt=2:b_pyramid=normal:weight_b:weightp=2:direct_pred=auto:aq_mode=1:me=umh:me_range=24:subq=7:mbtree:psy_rd=0.8,0.2:chroma_me:trellis=1:cabac:deblock:8x8dct:partitions=p8x8,b8x8,i8x8,i4x4:nofast_pskip:nodct_decimate:level_idc=41:vbv_maxrate=20000:vbv_bufsize=20000:threads=auto$keyint$keyint_min$frame_packing" ;;
	ultrafast|superfast|veryfast|faster|fast|medium|slow|slower|veryslow|placebo)	x264params=":preset=$3$x264tune$x264profile$keyint$keyint_min:force_cfr$frame_packing" ;;
esac

# mbtree causes mencoder to segfault
# due to differences in frames amount
# in the passlog file. So disable it
# for multipass modes
case "$1" in
	-[2-3]p)
	x264params="$(echo "$x264params" | sed 's|:mbtree|:nombtree|')"
	;;
esac

# Custom matrices are only
# supported by presets which
# use High profile settings
case "$3" in
	hq|vhq|ehq|uhq|ihq|ani|anihq|vdhq|vdehq|vdihq|flhq|bdhq40|bdhq41|avchdhq|ps3hq|mxhq)
	cuma=$(get_selection_func "Would you like to use Predefined/Custom Quantization Matrices (cqm)? [y/N]: ")
	if [ "$cuma" = "y" ]; then
		echo
		brown "Predefined/Custom Quantization Matrices"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> Flat -> Predefined flat 16 matrix"
		echo "1 -> JVT --> Predefined JVT matrix"
		echo "2 -> Load a custom matrix file"
		echo "3 -> Skip loading/using matrices"
		echo
		printf "Which one to use? [default is 0]: "
		read cmatrix
		case "$cmatrix" in
			0|"") cqm=":cqm=flat" ;;
			1) cqm=":cqm=jvt" ;;
			2)
			printf "Provide the Custom Matrix file: "
			read -e matrixfile
			if [ ! -f "$matrixfile" ]; then
				echo
				green "-> No such file: '$matrixfile'"
				green "-> Skipping loading of matrix"
				echo
			else
				cqm=":cqm=$matrixfile"
			fi
			;;
		esac
	fi
	;;
esac

# Set priority (nice value) of the whole
# encoding process
if [ ! -z "$PRIORITY" ]; then
	if [ $UID != 0 ]; then
		case "$PRIORITY" in
			[0-9]|1[0-9])	nicelevel="nice -n $PRIORITY" ;;
			*)
			echo
			error "-> Priority level '$PRIORITY' not allowed for regular users!"
			error "-> Check the value of 'PRIORITY' in '$H264ENCDIR/config'"
			error "-> Continuing with default 'nice' value of 0"
			echo
			;;
		esac
	else
		nicelevel="nice -n $PRIORITY"
	fi
else
	priolevel=$(get_selection_func "Would you like to set the encoder Priority Level? [y/N]: ")
	if [ "$priolevel" = "y" ]; then
		if [ $UID != 0 ]; then
			printf "Specify the encoder priority level [0-19 - default is 0]: "
			read nice_value
			case "$nice_value" in
				[0-9]|1[0-9])
				nicelevel="nice -n $nice_value"
				;;
				-[1-9]|-1[0-9]|-20)
				echo
				error "-> You do not have the privilege to set a negative 'nice' value!"
				error "-> Continuing with default 'nice' value of 0"
				;;
			esac
		else
			printf "Specify the encoder priority level [-20-19 - default is 0]: "
			read nice_value
			case "$nice_value" in
				-[1-9]|-1[0-9]|-20|[0-9]|1[0-9])
				nicelevel="nice -n $nice_value"
				;;
			esac
		fi
	fi
fi

#####################################################
############## Audio Configuration ##################
#####################################################

case "$source" in
	file|dir|bd) demuxer="-demuxer lavf" ;;
esac

echo
brown "+=====================+"
brown "| Audio Configuration |"
brown "+=====================+"
case "$source" in
	dir|vcd)
	echo
	TRACKID[1]=yes
	;;
	file|dvd|bd)
	AUDTRKS="$TEMPDIR/audiotracks"
	echo
	green "-> Scanning for audio tracks..."
	case "$source" in
		dvd)
		$MPLAYER $sourcetype $MPLAYEROPTS $device $MPOPTS 2>/dev/null > "$AUDTRKS"
		AUDSTREAMS="$(grep "^audio stream" "$AUDTRKS")"
		if [ ! -z "$AUDSTREAMS" ]; then
			echo
			echo "$AUDSTREAMS" | sed -e 's|^audio stream|Audio track|g' -e 's|format:|Format:|g' -e 's|language:|Language:|g' \
			-e 's|aid:|Audio ID:|g' -e 's|ac3|AC-3|g' -e 's|dts|DTS|g' -e 's|lpcm|LPCM|g' -e 's|pcm|PCM|g' -e 's|\.$||g'
			ATRKS="$(echo "$AUDSTREAMS" | wc -l)"
		else
			error "-> Could not detect any audio tracks!"
			ATRKS="0"
		fi
		;;
		file|bd)
		echo
		$MPLAYER "$sourcetype" $MPLAYEROPTS $device $demuxer $cache -vo null -ao null -identify -frames 1 2>/dev/null > "$AUDTRKS"
		TRKS="$(grep '^\[lavf\]' "$AUDTRKS" | awk '{print $4}' | grep 'audio' | wc -l)"
		if [ "$TRKS" = "0" ]; then
			error "-> Could not detect any audio tracks and info!"
			ATRKS="0"
		else
			ATRKS="$TRKS"
			TRKID="$(($TRKS-1))"
			for i in $(eval echo "{0..$TRKID}"); do
				AUDINFO="$TEMPDIR/audinfo"
				$MPLAYER "$sourcetype" $MPLAYEROPTS $device $demuxer $cache -channels 8 -vo null -ao null -aid $i -identify -frames 1 2>/dev/null > "$AUDINFO"
				AUDCDC="$(grep '^ID_AUDIO_CODEC' "$AUDINFO" | tail -n 1 | awk -F= '{print $2}' | sed 's|ff||g')"
				AUDBTR="$(grep '^ID_AUDIO_BITRATE' "$AUDINFO" | tail -n 1 | awk -F= '{print $2}')"
				AUDCH="$(grep '^ID_AUDIO_NCH' "$AUDINFO" | tail -n 1 | awk -F= '{print $2}')"
				AUDRATE="$(grep '^ID_AUDIO_RATE' "$AUDINFO" | tail -n 1 | awk -F= '{print $2}')"
				AUDLNG="$(grep "^ID_AID_${i}_LANG" "$AUDINFO" | tail -n 1 | awk -F= '{print $2}')"
				if [ -z "$AUDCDC" ]; then
					AUDCDC="?"
				fi
				if [ "$AUDBTR" = "0" -o -z "$AUDBTR" ]; then
					AUDBTR="?"
				else
					if [ "$AUDCDC" = "dca" ]; then
						case "$AUDBTR" in
							1536000)	AUDBTR="1509000" ;;
							768000)		AUDBTR="755000" ;;
						esac
					fi
					AUDBTR="$(($AUDBTR/1000)) kbps"
				fi
				if [ -z "$AUDCH" ]; then
					AUDCH="?"
				fi
				if [ "$AUDCH" != "?" ]; then
					MAXAUDCH[i]="$AUDCH"
				fi
				if [ -z "$AUDRATE" ]; then
					AUDRATE="?"
				else
					AUDKHZ="$(echo "scale=1; $AUDRATE/1000" | $BC -l | sed 's|\.0||') kHz"
					AUDRATE="$AUDRATE Hz ($AUDKHZ)"
				fi
				if [ -z "$AUDLNG" ]; then
					AUDLNG="?"
				fi
				CDCNAME="$(echo "$AUDCDC" | tr '[:lower:]' '[:upper:]' | sed 's|DCA|DTS|; s|AC3|AC-3|; s|TRUEHD|Dolby TrueHD|; s|MP3FLOAT|MP3|; s|EAC3|E-AC-3|')"
				green "-> Track $(($i+1)): Audio ID: $i, Codec: $CDCNAME, Bitrate: $AUDBTR, Rate: $AUDRATE, Channels: $AUDCH, Language: $AUDLNG"
				if [ ! -z "${MAXAUDCH[i]}" ]; then
					if [ ${MAXAUDCH[i]} -gt 6 ]; then
						error "-> Track $(($i+1)): Warning: track contains more than 6 channels. Max supported by h264enc is 6!"
					fi
				fi
				rm -f "$AUDINFO"
			done
		fi
		;;
	esac
	echo
	if [ "$MAX_AMOUNT_AUD_TRACKS" = "auto" ]; then
		if [ "$ATRKS" = "0" ]; then
			MAX_AMOUNT_AUD_TRACKS="2"
		else
			MAX_AMOUNT_AUD_TRACKS="$ATRKS"
		fi
	fi
	for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
		if [ "$i" = "1" ]; then
			case "$source" in
				file|bd)	defdac="default is 0" ;;
				dvd)		defdac="default is 128" ;;
			esac
		else
			defdac="press 'Enter' to skip"
		fi
		printf "Track $i: Specify the Audio ID number [$defdac]: "
		read dac[i]
		if [ ! -z "$(echo ${dac[i]} | grep '[a-zA-Z]')" ]; then
			error "-> You have to specify the 'Audio ID' number, not the language code!"
			exit_func 1
		fi
		if [ -z "${dac[1]}" -a "$i" = "1" ]; then
			TRACKID[1]=yes
			aid[1]="-aid $(echo "$defdac" | awk '{print $3}')"
		elif [ ! -z "${dac[1]}" -a "$i" = "1" ]; then
			TRACKID[1]=yes
			aid[1]="-aid ${dac[1]}"
		else
			if [ ! -z "${dac[i]}" ]; then
				TRACKID[i]=yes
				aid[i]="-aid ${dac[i]}"
			fi
		fi
		case "$source" in
			dvd)
			GETAUDLANG[i]="$(grep "$(echo ${aid[i]} | awk '{print $2}')" "$AUDTRKS" | grep -o 'language.*' | awk '{print $2}')"
			if [ ! -z "${GETAUDLANG[i]}" ]; then
				if [ "${GETAUDLANG[i]}" = "unknown" ]; then
					AUDLANG[i]="und"
				else
					AUDLANG[i]="${GETAUDLANG[i]}"
				fi
			else
				AUDLANG[i]="und"
			fi
			;;
			file|bd)
			if [ "${TRACKID[i]}" = "yes" ]; then
				printf "Track $i: Specify the 2 or 3 letter Language code for Tagging [press 'Enter' to skip]: "
				read audlang[i]
				if [ ! -z "${audlang[i]}" ]; then
					AUDLANG[i]="${audlang[i]}"
				else
					AUDLANG[i]="und"
				fi
			fi
			;;
		esac
	done
	rm -f "$AUDTRKS"
	;;
esac

###############################################
########## Audio Codec Functions ##############
###############################################

mp3_audio_func() {
	printf "Track $i: Specify the MP3 Audio Encoding Mode [ABR/CBR/VBR/PRESET - default is ABR]: "
	read mp3mode[i]
	case "${mp3mode[i]}" in
		a*|A*|"")
		printf "Track $i: Specify the MP3 Average Bitrate [default is 140]: "
		read ab[i]
		if [ -z "${ab[i]}" ]; then
			abitrate[i]="abr:br=140"
		else
			abitrate[i]="abr:br=${ab[i]}"
		fi
		;;
		c*|C*)
		echo
		brown "Track $i: MP3 Audio Bitrates"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> 32 kbps   7 --> 112 kbps"
		echo "1 -> 40 kbps   8 --> 128 kbps"
		echo "2 -> 48 kbps   9 --> 160 kbps"
		echo "3 -> 56 kbps   10 -> 192 kbps"
		echo "4 -> 64 kbps   11 -> 224 kbps"
		echo "5 -> 80 kbps   12 -> 256 kbps"
		echo "6 -> 96 kbps   13 -> 320 kbps"
		echo
		printf "Track $i: Select the MP3 Audio Bitrate [default is 10]: "
		read ab[i]
		case "${ab[i]}" in
			0)	abitrate[i]="cbr:br=32" ;;
			1)	abitrate[i]="cbr:br=40" ;;
			2)	abitrate[i]="cbr:br=48" ;;
			3)	abitrate[i]="cbr:br=56" ;;
			4)	abitrate[i]="cbr:br=64" ;;
			5)	abitrate[i]="cbr:br=80" ;;
			6)	abitrate[i]="cbr:br=96" ;;
			7)	abitrate[i]="cbr:br=112" ;;
			8)	abitrate[i]="cbr:br=128" ;;
			9)	abitrate[i]="cbr:br=160" ;;
			10|"")	abitrate[i]="cbr:br=192" ;;
			11)	abitrate[i]="cbr:br=224" ;;
			12)	abitrate[i]="cbr:br=256" ;;
			13)	abitrate[i]="cbr:br=320" ;;
			*)
			error "-> Track $i: Unknown option: '${ab[i]}'"
			error "-> Exiting in function: mp3_audio_func()"
			exit_func 1
			;;
		esac
		;;
		v*|V*)
		printf "Track $i: Specify the desired MP3 Audio Quality [0-9, lower is better - default is 3]: "
		read ab[i]
		if [ -z "${ab[i]}" ]; then
			abitrate[i]="q=3"
		else
			abitrate[i]="q=${ab[i]}"
		fi
		;;
		p*|P*)
		echo
		brown "Track $i: MP3 Presets"
		brown "~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> Medium (VBR: 150-180 kbps)"
		echo "1 -> Standard (VBR: 170-210 kbps)"
		echo "2 -> Extreme (VBR: 200-240 kbps)"
		echo "3 -> Insane (CBR: 320 kbps)"
		echo
		printf "Track $i: Select an MP3 preset [default is 1]: "
		read mp3preset[i]
		case "${mp3preset[i]}" in
			0)	abitrate[i]="preset=medium" ;;
			1|"")	abitrate[i]="preset=standard" ;;
			2)	abitrate[i]="preset=extreme" ;;
			3)	abitrate[i]="preset=insane" ;;
			*)
			error "-> Track $i: Unknown MP3 preset!"
			error "-> Exiting in function: mp3_audio_func()"
			exit_func 1
			;;
		esac
		;;
		*)
		error "-> Track $i: Unknown MP3 encoding mode: '${mp3mode[i]}'"
		error "-> Exiting in function: mp3_audio_func()"
		exit_func 1
		;;
	esac
	printf "Track $i: Specify the MP3 Algorithmic Quality [0-9, lower is better - default is 3]: "
	read aq[i]
	if [ -z "${aq[i]}" ]; then
		aquality[i]=":aq=3"
	else
		aquality[i]=":aq=${aq[i]}"
	fi
	printf "Track $i: Specify the MP3 Audio Input Gain [0.0-10.0 - default is 2.2]: "
	read aig[i]
	if [ -z "${aig[i]}" ]; then
		again[i]=":vol=2.2"
	else
		again[i]=":vol=${aig[i]}"
	fi
	echo
	brown "Track $i: MP3 Channel Modes"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 -> Stereo"
	echo "1 -> Joint-Stereo"
	echo "2 -> Dual Channel"
	echo "3 -> Mono"
	echo
	printf "Track $i: Select the MP3 Channel Mode [default is 1]: "
	read mp3chan[i]
	case "${mp3chan[i]}" in
		0)	mp3channel[i]=":mode=0" ;;
		1|"")	mp3channel[i]=":mode=1" ;;
		2)	mp3channel[i]=":mode=2" ;;
		3)	mp3channel[i]=":mode=3" ;;
		*)
		error "-> Track $i: Unknown MP3 channel option: '${mp3chan[i]}'"
		error "-> Exiting in function: mp3_audio_func()"
		exit_func 1
		;;
	esac
	acodec[i]="-oac mp3lame -lameopts ${abitrate[i]}${aquality[i]}${again[i]}${mp3channel[i]}"
}

# Shared by both lavc and aften
ac3_bitrate_func() {
	echo
	brown "Track $i: AC-3 Audio Bitrates"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 -> 32 kbps    10 -> 192 kbps"
	echo "1 -> 40 kbps    11 -> 224 kbps"
	echo "2 -> 48 kbps    12 -> 256 kbps"
	echo "3 -> 56 kbps    13 -> 320 kbps"
	echo "4 -> 64 kbps    14 -> 384 kbps"
	echo "5 -> 80 kbps    15 -> 448 kbps"
	echo "6 -> 96 kbps    16 -> 512 kbps"
	echo "7 -> 112 kbps   17 -> 576 kbps"
	echo "8 -> 128 kbps   18 -> 640 kbps"
	echo "9 -> 160 kbps"
	echo
	printf "Track $i: Select the AC-3 Audio Bitrate [default is 15]: "
	read ab[i]
	case "${ab[i]}" in
		0)	abitrate[i]="32" ;;
		1)	abitrate[i]="40" ;;
		2)	abitrate[i]="48" ;;
		3)	abitrate[i]="56" ;;
		4)	abitrate[i]="64" ;;
		5)	abitrate[i]="80" ;;
		6)	abitrate[i]="96" ;;
		7)	abitrate[i]="112" ;;
		8)	abitrate[i]="128" ;;
		9)	abitrate[i]="160" ;;
		10)	abitrate[i]="192" ;;
		11)	abitrate[i]="224" ;;
		12)	abitrate[i]="256" ;;
		13)	abitrate[i]="320" ;;
		14)	abitrate[i]="384" ;;
		15|"")	abitrate[i]="448" ;;
		16)	abitrate[i]="512" ;;
		17)	abitrate[i]="576" ;;
		18)	abitrate[i]="640" ;;
		*)
		error "-> Track $i: Unknown option: '${ab[i]}'"
		error "-> Exiting in function: ac3_bitrate_func()"
		exit_func 1
		;;
	esac
}

aften_ac3_audio_func() {
	acodec[i]="-oac pcm"
	ac3_bitrate_func
	echo
	brown "Track $i: AC-3 Dynamic Range Compression"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 -> Film Light"
	echo "1 -> Film Standard"
	echo "2 -> Music Light"
	echo "3 -> Music Standard"
	echo "4 -> Speech"
	echo "5 -> None"
	echo
	printf "Track $i: Select the AC-3 DRC Profile [default is 5]: "
	read ac3drc[i]
	case "${ac3drc[i]}" in
		0)	drc[i]="0" ;;
		1)	drc[i]="1" ;;
		2)	drc[i]="2" ;;
		3)	drc[i]="3" ;;
		4)	drc[i]="4" ;;
		5|"")	drc[i]="5" ;;
		*)
		error "-> Track $i: Unknown option: '${ac3drc[i]}'"
		error "-> Exiting in function: aften_ac3_audio_func()"
		exit_func 1
		;;
	esac
	printf "Track $i: Specify the AC-3 Exponent Strategy search size [1-32, higher is better - default is 16]: "
	read ac3exp[i]
	if [ -z "${ac3exp[i]}" ]; then
		exps[i]="16"
	else
		exps[i]="${ac3exp[i]}"
	fi
	ac3lfe[i]=$(get_selection_func "Track $i: Apply an AC-3 LFE low-pass filter? [y/N]: ")
	if [ "${ac3lfe[i]}" = "y" ]; then
		lfe[i]="1"
	else
		lfe[i]="0"
	fi
	ac3opts[i]="-b ${abitrate[i]} -dynrng ${drc[i]} -exps ${exps[i]} -lfefilter ${lfe[i]} -readtoeof 1"
}

lavc_ac3_audio_func() {
	ac3_bitrate_func
	#printf "Track $i: Specify the Dynamic Range Compression [0.0-1.0, higher is stronger - default is 0.0]: "
	#read drc[i]
	#if [ ! -z "${drc[i]}" ]; then
	#	ac3drc[i]="-a52drc ${drc[i]}"
	#fi
	acodec[i]="-oac lavc -lavcopts acodec=ac3:abitrate=${abitrate[i]}"
}

eac3_audio_func() {
	acodec[i]="-oac pcm"
	printf "Track $i: Specify the E-AC-3 Audio Bitrate in kbps [default is 384]: "
	read eac3br[i]
	if [ -z "${eac3br[i]}" ]; then
		abitrate[i]="384"
	else
		abitrate[i]="${eac3br[i]}"
	fi
}

dts_audio_func() {
	acodec[i]="-oac pcm"
	printf "Track $i: Specify the DTS Audio Bitrate in kbps [default is 755]: "
	read ab[i]
	if [ -z "${ab[i]}" ]; then
		abitrate[i]="754500"
	else
		if [ "${ab[i]}" -le "1509" ]; then
			abitrate[i]="$((${ab[i]}*1000))"
		else
			echo
			error "-> Maximum allowed bitrate is 1509 kbps!"
			error "-> Defaulting to max allowed bitrate"
			echo
			abitrate[i]="1509750"
		fi
	fi
}

faac_audio_func() {
	case "$1" in
		fl|flhq|qt|qthq|ag1|ag1hq|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|psp|psphq|ps3|ps3hq|mz|mzhq)
		printf "Track $i: Specify the AAC Average Bitrate [default is 128]: "
		read abitrate[i]
		if [ -z "${abitrate[i]}" ]; then
			br[i]="br=128"
		else
			br[i]="br=${abitrate[i]}"
		fi
		case "$1" in
			ag1|ag1hq|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|psp|psphq)
			# Restrict audio bitrate for devices
			# with a maximum allowed bitrate
			if [ $(echo ${br[i]} | awk '{print $2}') -gt 160 ]; then
				echo
				green "-> Track $i: Audio bitrate for this portable device may not exceed 160 kbps!"
				green "-> Track $i: Falling back to 128 kbps!"
				echo
				br[i]="br=128"
			fi
			;;
		esac
		;;
		*)
		printf "Track $i: Specify the AAC encoding mode [ABR/VBR - default is ABR]: "
		read aacmode[i]
		case "${aacmode[i]}" in
			a*|A*|"")
			printf "Track $i: Specify the AAC Average Bitrate [default is 192]: "
			read abitrate[i]
			if [ -z "${abitrate[i]}" ]; then
				br[i]="br=192"
			else
				br[i]="br=${abitrate[i]}"
			fi
			;;
			v*|V*)
			SKIPBTRCALC=yes
			printf "Track $i: Specify the AAC Quality value [10-500, higher is better - default is 150]: "
			read abitrate[i]
			if [ -z "${abitrate[i]}" ]; then
				br[i]="quality=150"
			else
				br[i]="quality=${abitrate[i]}"
			fi
			;;
			*)
			error "-> Track $i: Unknown AAC encoding mode: '${aacmode[i]}'"
			error "-> Exiting in function: aac_audio_func()"
			exit_func 1
			;;
		esac
		;;
	esac
	tempns[i]=$(get_selection_func "Track $i: Enable AAC Temporal Noise Shaping? [y/N]: ")
	if [ "${tempns[i]}" = "y" ]; then
		tns[i]=":tns"
	fi
	acodec[i]="-oac faac -faacopts ${br[i]}${tns[i]}:mpeg=4:object=2"
}

neroaac_audio_func() {
	acodec[i]="-oac pcm"
	case "$1" in
		qt|qthq|ag1|ag1hq|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|psp|psphq|ps3|ps3hq|mz|mzhq|mx|mxhq)
		aacprof[i]="-lc"
		AACTYPE[i]="LC-AAC"
		printf "Track $i: Specify the AAC Audio Bitrate in kbps [default is 128]: "
		read ab[i]
		if [ -z "${ab[i]}" ]; then
			neroaacbr[i]="-br 128000 ${aacprof[i]}"
		else
			neroaacbr[i]="-br $((${ab[i]}*1000)) ${aacprof[i]}"
		fi
		case "$1" in
			ag1|ag1hq|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|psp|psphq)
			if [ $(echo ${neroaacbr[i]} | awk '{print $2}') -gt 160000 ]; then
				echo
				green "-> Track $i: Audio bitrate for this preset may not exceed 160 kbps!"
				green "-> Track $i: Falling back to 128 kbps!"
				echo
				neroaacbr[i]="-br 128000 ${aacprof[i]}"
			fi
			;;
		esac
		nero2p[i]=$(get_selection_func "Track $i: Use 2-pass AAC encoding instead of 1-pass? [y/N]: ")
		if [ "${nero2p[i]}" = "y" ]; then
			neroaacbr[i]="${neroaacbr[i]} -2pass"
		fi
		;;
		*)
		printf "Track $i: Which AAC Profile to use? [LC/HE/HEv2 - default is LC]: "
		read aac_profile[i]
		case "${aac_profile[i]}" in
			LC|lc|"")	aacprof[i]="-lc"; AACTYPE[i]="LC-AAC" ;;
			HE|he)		aacprof[i]="-he"; AACTYPE[i]="HE-AACv1" ;;
			HEv2|hev2)	aacprof[i]="-hev2"; AACTYPE[i]="HE-AACv2" ;;
			*)
			error "-> Track $i: Unknown AAC profile"
			error "-> Exiting in function: neroaac_audio_func()"
			exit_func 1
			;;
		esac
		printf "Track $i: Specify the AAC Encoding Mode [ABR/CBR/VBR - default is ABR]: "
		read aacmode[i]
		case "${aacmode[i]}" in
			a*|A*|"")
			case "${AACTYPE[i]}" in
				LC-AAC)		defaacbr[i]="192" ;;
				HE-AACv1)	defaacbr[i]="55" ;;
				HE-AACv2)	defaacbr[i]="25" ;;
			esac
			printf "Track $i: Specify the AAC Average Bitrate in kbps [default is ${defaacbr[i]}]: "
			read ab[i]
			if [ -z "${ab[i]}" ]; then
				neroaacbr[i]="-br $((${defaacbr[i]}*1000)) ${aacprof[i]}"
			else
				neroaacbr[i]="-br $((${ab[i]}*1000)) ${aacprof[i]}"
			fi
			;;
			c*|C*)
			echo
			brown "Track $i: AAC Audio Bitrates"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "0 -> 32 kbps   7 --> 112 kbps"
			echo "1 -> 40 kbps   8 --> 128 kbps"
			echo "2 -> 48 kbps   9 --> 160 kbps"
			echo "3 -> 56 kbps   10 -> 192 kbps"
			echo "4 -> 64 kbps   11 -> 224 kbps"
			echo "5 -> 80 kbps   12 -> 256 kbps"
			echo "6 -> 96 kbps   13 -> 320 kbps"
			echo
			printf "Track $i: Select the AAC Audio Bitrate [default is 10]: "
			read ab[i]
			case "${ab[i]}" in
				0)	neroaacbr[i]="-cbr 32000 ${aacprof[i]}" ;;
				1)	neroaacbr[i]="-cbr 40000 ${aacprof[i]}" ;;
				2)	neroaacbr[i]="-cbr 48000 ${aacprof[i]}" ;;
				3)	neroaacbr[i]="-cbr 56000 ${aacprof[i]}" ;;
				4)	neroaacbr[i]="-cbr 64000 ${aacprof[i]}" ;;
				5)	neroaacbr[i]="-cbr 80000 ${aacprof[i]}" ;;
				6)	neroaacbr[i]="-cbr 96000 ${aacprof[i]}" ;;
				7)	neroaacbr[i]="-cbr 112000 ${aacprof[i]}" ;;
				8)	neroaacbr[i]="-cbr 128000 ${aacprof[i]}" ;;
				9)	neroaacbr[i]="-cbr 160000 ${aacprof[i]}" ;;
				10|"")	neroaacbr[i]="-cbr 192000 ${aacprof[i]}" ;;
				11)	neroaacbr[i]="-cbr 224000 ${aacprof[i]}" ;;
				12)	neroaacbr[i]="-cbr 256000 ${aacprof[i]}" ;;
				13)	neroaacbr[i]="-cbr 320000 ${aacprof[i]}" ;;
				*)
				error "-> Track $i: Unknown option: '${ab[i]}'"
				error "-> Exiting in function: neroaac_audio_func()"
				exit_func 1
				;;
			esac
			;;
			v*|V*)
			SKIPBTRCALC=yes
			# Assuming Stereo channels
			case "${AACTYPE[i]}" in
				LC-AAC)		defaacbr[i]="0.4" ;;
				HE-AACv1)	defaacbr[i]="0.22" ;;
				HE-AACv2)	defaacbr[i]="0.11" ;;
			esac
			printf "Track $i: Specify the AAC Quality value [0.0-1.0, higher is better - default is ${defaacbr[i]}]: "
			read ab[i]
			if [ -z "${ab[i]}" ]; then
				neroaacbr[i]="-q ${defaacbr[i]} ${aacprof[i]}"
			else
				neroaacbr[i]="-q ${ab[i]} ${aacprof[i]}"
			fi
			;;
			*)
			error "-> Track $i: Unknown option: '${aacmode[i]}'"
			error "-> Exiting in function: neroaac_audio_func()"
			exit_func 1
			;;
		esac
		case "${aacmode[i]}" in
			a*|A*|c*|C*|"")
			nero2p[i]=$(get_selection_func "Track $i: Use 2-pass AAC encoding instead of 1-pass? [y/N]: ")
			if [ "${nero2p[i]}" = "y" ]; then
				neroaacbr[i]="${neroaacbr[i]} -2pass"
			fi
			;;
		esac
		;;
	esac
}

fdkaac_audio_func() {
	acodec[i]="-oac pcm"
	case "$1" in
		qt|qthq|ag1|ag1hq|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|psp|psphq|ps3|ps3hq|mz|mzhq|mx|mxhq)
		aacprof[i]="-t 2"
		AACTYPE[i]="LC-AAC"
		printf "Track $i: Specify the AAC Audio Bitrate in kbps [default is 192]: "
		read ab[i]
		if [ -z "${ab[i]}" ]; then
			fdkaacbr[i]="-r 192000 ${aacprof[i]} -a 1"
		else
			fdkaacbr[i]="-r $((${ab[i]}*1000)) ${aacprof[i]} -a 1"
		fi
		case "$1" in
			ag1|ag1hq|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|psp|psphq)
			if [ $(echo ${fdkaacbr[i]} | awk '{print $2}') -gt 160000 ]; then
				echo
				green "-> Track $i: Audio bitrate for this preset may not exceed 160 kbps!"
				green "-> Track $i: Falling back to 128 kbps!"
				echo
				fdkaacbr[i]="-r 128000 ${aacprof[i]} -a 1"
			fi
			;;
		esac
		;;
		*)
		printf "Track $i: Which AAC Profile to use? [LC/HE/HEv2 - default is LC]: "
		read aac_profile[i]
		case "${aac_profile[i]}" in
			LC|lc|"")	aacprof[i]="-t 2"; AACTYPE[i]="LC-AAC"; defaacbr[i]="192" ;;
			HE|he)		aacprof[i]="-t 5"; AACTYPE[i]="HE-AACv1"; defaacbr[i]="55" ;;
			HEv2|hev2)	aacprof[i]="-t 29"; AACTYPE[i]="HE-AACv2"; defaacbr[i]="25" ;;
			*)
			error "-> Track $i: Unknown AAC profile"
			error "-> Exiting in function: fdkaac_audio_func()"
			exit_func 1
			;;
		esac
		printf "Track $i: Specify the AAC Audio Bitrate in kbps [default is ${defaacbr[i]}]: "
		read ab[i]
		if [ -z "${ab[i]}" ]; then
			fdkaacbr[i]="-r $((${defaacbr[i]}*1000)) ${aacprof[i]} -a 1"
		else
			fdkaacbr[i]="-r $((${ab[i]}*1000)) ${aacprof[i]} -a 1"
		fi
		;;
	esac
}

aacplus_audio_func() {
	acodec[i]="-oac pcm"
	channels[i]="-channels 2"
	printf "Track $i: Specify the AAC+ Audio Bitrate in kbps [default is 55]: "
	read ab[i]
	if [ -z "${ab[i]}" ]; then
		aacplusbr[i]="55"
	else
		if [[ ${ab[i]} -ge 64 ]]; then
			echo
			green "-> Track $i: Bitrates of 64 kbps and up are not supported!"
			green "-> Track $i: Using default bitrate of 55 kbps"
			echo
			aacplusbr[i]="55"
		elif [[ ${ab[i]} -lt 48 ]]; then
			echo
			green "-> Track $i: Bitrates below 48 kbps use Parametric Stereo"
			green "             which is not recommended!"
			green "-> Track $i: Using default bitrate of 55 kbps"
			echo
			aacplusbr[i]="55"
		else
			aacplusbr[i]="${ab[i]}"
		fi
	fi
}

vorbis_audio_func() {
	acodec[i]="-oac pcm"
	printf "Track $i: Select the Vorbis encoding mode [ABR/VBR - default is VBR]: "
	read vorbmode[i]
	case "${vorbmode[i]}" in
		a*|A*)
		printf "Track $i: Specify the Vorbis nominal bitrate in kbps [default is 160]: "
		read ab[i]
		if [ -z "${ab[i]}" ]; then
			vorbq[i]="-b 160"
		else
			vorbq[i]="-b ${ab[i]}"
		fi
		;;
		v*|V*|"")
		printf "Track $i: Specify the Vorbis audio quality [-1-10, higher is better - default is 4]: "
		read ab[i]
		if [ -z "${ab[i]}" ]; then
			vorbq[i]="-q 4"
		else
			if [ ! -z "$(echo ${ab[i]} | grep '\.')" ]; then
				echo
				error "-> Track $i: Floating point values are not supported yet!"
				error "-> Track $i: Rounding value to $(echo ${ab[i]} | awk -F. '{print $1}')"
				echo
				vorbq[i]="-q $(echo ${ab[i]} | awk -F. '{print $1}')"
			else
				vorbq[i]="-q ${ab[i]}"
			fi
		fi
		;;
		*)
		error "-> Unknown option: '${vorbmode[i]}'"
		error "-> Exiting in function: vorbis_audio_func()"
		exit_func 1
		;;
	esac
}

opus_audio_func() {
	acodec[i]="-oac pcm"
	printf "Track $i: Select the Opus encoding mode [CBR/VBR - default is VBR]: "
	read opusm[i]
	case "${opusm[i]}" in
		V*|v*|"")	opusmode[i]="--vbr" ;;
		C*|c*)		opusmode[i]="--hard-cbr" ;;
		*)
		error "-> Unknown option: '${opusm[i]}'"
		error "-> Exiting in function: opus_audio_func()"
		exit_func 1
		;;
	esac
	printf "Track $i: Specify the Audio Bitrate in kbps [default is 128]: "
	read ab[i]
	if [ -z "${ab[i]}" ]; then
		opusbr[i]="128"
	else
		opusbr[i]="${ab[i]}"
	fi
	opusopts[i]="${opusmode[i]} --bitrate ${opusbr[i]} --ignorelength"
}

flac_audio_func() {
	acodec[i]="-oac pcm"
	printf "Track $i: Specify the FLAC Audio compression [0-8, lower is better - default is 5]: "
	read ab[i]
	if [ -z "${ab[i]}" ]; then
		flacq[i]="-5"
	else
		flacq[i]="-${ab[i]}"
	fi
}

# This function is also used to exit in case the
# user mistypes or provides an audio codec we do
# not support
audio_codec_exit_func() {
	case "$1" in
		error)
		error "-> Track $i: Unknown/unsupported audio codec: '${audiocodec[i]}'"
		;;
	esac
	error "-> Exiting in function: audio_codec_exit_func()"
	exit_func 1
}

# Check availability of the selected audio codec.
MISSING="is missing from your system!"
check_audio_codec_func() {
	case "${audiocodec[i]}" in
		mp3)
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'mp3lame')" ]; then
			error "-> MEncoder does not support MP3 audio encoding!"
			audio_codec_exit_func
		fi
		;;
		aac|"")
		#if [ ! -x "$FAAC" ]; then
		#	error "-> 'faac' $MISSING"
		#	audio_codec_exit_func
		#fi
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'faac')" ]; then
			error "-> MEncoder does not support AAC encoding (faac)!"
			audio_codec_exit_func
		fi
		;;
		neroaac)
		if [ ! -x "$NEROAACENC" ]; then
			error "-> 'neroAacEnc' $MISSING"
			audio_codec_exit_func
		fi
		;;
		fdkaac)
		if [ ! -x "$FDKAACENC" ]; then
			error "-> 'aac-enc' $MISSING"
			audio_codec_exit_func
		fi
		;;
		aac+)
		if [ ! -x "$AACPLUSENC" ]; then
			error "-> 'aacplusenc' $MISSING"
			audio_codec_exit_func
		fi
		;;
		vorbis)
		if [ ! -x "$OGGENC" ]; then
			error "-> 'oggenc' $MISSING"
			audio_codec_exit_func
		fi
		;;
		opus)
		if [ ! -x "$OPUSENC" ]; then
			error "-> 'opusenc' $MISSING"
			audio_codec_exit_func
		fi
		;;
		flac)
		if [ ! -x "$FLAC" ]; then
			error "-> 'flac' $MISSING"
			audio_codec_exit_func
		fi
		;;
		dts)
		if [ ! -x "$DCAENC" ]; then
			error "-> 'dcaenc' $MISSING"
			audio_codec_exit_func
		fi
		;;
		pcm)
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'pcm')" ]; then
			error "-> MEncoder does not support PCM audio encoding!"
			audio_codec_exit_func
		fi
		;;
		copy)
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'copy')" ]; then
			error "-> MEncoder does not support audio stream copy!"
			audio_codec_exit_func
		fi
		;;
	esac
}

###############################################
########## Audio Filters Functions ############
###############################################

# Resample function
audio_resample_filters_func() {
	echo
	brown "Track $i: Audio Resample Filters And Modes"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 -> Resample: standard mode, linear interpolation"
	echo "1 -> Resample: HQ mode, linear interpolation"
	echo "2 -> Resample: standard mode, polyphase filterbank & integer processing"
	echo "3 -> Resample: HQ mode, polyphase filterbank & integer processing"
	echo "4 -> Resample: standard mode, polyphase filterbank & floating point processing"
	echo "5 -> Resample: HQ mode, polyphase filterbank & floating point processing"
	echo "6 -> Lavcresample: standard mode"
	echo "7 -> Lavcresample: linear interpolated polyphase filterbank"
	echo "8 -> Skip audio resampling"
	echo
	printf "Track $i: Select a Resample filter [default is 7]: "
	read rsmpfilter[i]
	case "${rsmpfilter[i]}" in
		0) resample[i]="resample=${hertz[i]}:1:0 -srate ${hertz[i]}" ;;
		1) resample[i]="resample=${hertz[i]}:0:0 -srate ${hertz[i]}" ;;
		2) resample[i]="resample=${hertz[i]}:1:1 -srate ${hertz[i]}" ;;
		3) resample[i]="resample=${hertz[i]}:0:1 -srate ${hertz[i]}" ;;
		4) resample[i]="resample=${hertz[i]}:1:2 -srate ${hertz[i]}" ;;
		5) resample[i]="resample=${hertz[i]}:0:2 -srate ${hertz[i]}" ;;
		6) resample[i]="lavcresample=${hertz[i]}:16:0 -srate ${hertz[i]}" ;;
		7|"") resample[i]="lavcresample=${hertz[i]}:16:1 -srate ${hertz[i]}" ;;
		8) skiprsmp=yes ;;
		*)
		error "-> Track $i: Unknown option: '${rsmpfilter[i]}'"
		error "-> Exiting in function: audio_resample_filters_func()"
		exit_func 1
		;;
	esac
}

audio_resample_func() {
	rsmp[i]=$(get_selection_func "Track $i: Would you like to Resample the Audio? [y/N]: ")
	if [ "${rsmp[i]}" = "y" ]; then
		case "$source" in
			file|vcd|dvd|bd)
			echo
			green "-> Track $i: Detecting audio sample rate..."
			AUDSAMPLE[i]=$($MPLAYER "$sourcetype" $MPLAYEROPTS $device ${aid[i]} $demuxer $cache $MPOPTS 2>/dev/null \
			| grep '^ID_AUDIO_RATE' | tail -n 1 | awk -F= '{print $2}')
			if [ ! -z "${AUDSAMPLE[i]}" ]; then
				green "-> Track $i: Detected: ${AUDSAMPLE[i]} Hz ($(echo "scale=1; ${AUDSAMPLE[i]} / 1000" | $BC -l) kHz)"
			else
				error "-> Track $i: Could not detect the sample rate!"
			fi
			;;
		esac
		echo
		brown "Track $i: Available Sample Frequencies"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		case "${audiocodec[i]}" in
			pcm|vorbis|opus)
			echo "0 -> 8000 Hz (8 kHz)"
			echo "1 -> 11025 Hz (11 kHz)"
			echo "2 -> 12000 Hz (12 kHz)"
			echo "3 -> 16000 Hz (16 kHz)"
			echo "4 -> 22050 Hz (22 kHz)"
			echo "5 -> 24000 Hz (24 kHz)"
			echo "6 -> 32000 Hz (32 kHz)"
			echo "7 -> 44100 Hz (44.1 kHz)"
			echo "8 -> 48000 Hz (48 kHz)"
			echo
			printf "Track $i: Select a Sample Frequency [default is 7]: "
			read freq[i]
			case "${freq[i]}" in
				0)	hertz[i]="8000" ;;
				1)	hertz[i]="11025" ;;
				2)	hertz[i]="12000" ;;
				3)	hertz[i]="16000" ;;
				4)	hertz[i]="22050" ;;
				5)	hertz[i]="24000" ;;
				6)	hertz[i]="32000" ;;
				7|"")	hertz[i]="44100" ;;
				8)	hertz[i]="48000" ;;
				*)
				error "-> Track $i: Unknown option: '${freq[i]}'"
				error "-> Exiting in function: audio_resample_func()"
				exit_func 1
				;;
			esac
			;;
			aac|neroaac|fdkaac|flac|"")
			echo "0 --> 8000 Hz (8 kHz)"
			echo "1 --> 11025 Hz (11 kHz)"
			echo "2 --> 12000 Hz (12 kHz)"
			echo "3 --> 16000 Hz (16 kHz)"
			echo "4 --> 22050 Hz (22 kHz)"
			echo "5 --> 24000 Hz (24 kHz)"
			echo "6 --> 32000 Hz (32 kHz)"
			echo "7 --> 44100 Hz (44.1 kHz)"
			echo "8 --> 48000 Hz (48 kHz)"
			echo "9 --> 64000 Hz (64 kHz)"
			echo "10 -> 88200 Hz (88.2 kHz)"
			echo "11 -> 96000 Hz (96 kHz)"
			echo
			printf "Track $i: Select a Sample Frequency [default is 7]: "
			read freq[i]
			case "${freq[i]}" in
				0)	hertz[i]="8000" ;;
				1)	hertz[i]="11025" ;;
				2)	hertz[i]="12000" ;;
				3)	hertz[i]="16000" ;;
				4)	hertz[i]="22050" ;;
				5)	hertz[i]="24000" ;;
				6)	hertz[i]="32000" ;;
				7|"")	hertz[i]="44100" ;;
				8)	hertz[i]="48000" ;;
				9)	hertz[i]="64000" ;;
				10)	hertz[i]="88200" ;;
				11)	hertz[i]="96000" ;;
				*)
				error "-> Track $i: Unknown option: '${freq[i]}'"
				error "-> Exiting in function: audio_resample_func()"
				exit_func 1
				;;
			esac
			;;
			aac+|aftenac3|lavcac3|eac3|mp3|dts)
			echo "0 -> 32000 Hz (32 kHz)"
			echo "1 -> 44100 Hz (44.1 kHz)"
			echo "2 -> 48000 Hz (48 kHz)"
			echo
			printf "Track $i: Select a Sample Frequency [default is 1]: "
			read freq[i]
			case "${freq[i]}" in
				0)	hertz[i]="32000" ;;
				1|"")	hertz[i]="44100" ;;
				2)	hertz[i]="48000" ;;
				*)
				error "-> Track $i: Unknown option: '${freq[i]}'"
				error "-> Exiting in function: audio_resample_func()"
				exit_func 1
				;;
			esac
			;;
		esac
		case "$source" in
			dir)
			audio_resample_filters_func
			;;
			*)
			if [ "${AUDSAMPLE[i]}" = "${hertz[i]}" ]; then
				echo
				error "-> Track $i: Detected sample rate equals selected one!"
				error "-> Track $i: ${AUDSAMPLE[i]} Hz = ${hertz[i]} Hz"
				error "-> Track $i: Skipping resampling"
				resample[i]=
			else
				audio_resample_filters_func
			fi
			;;
		esac
	fi
}

# Audio EQ
audio_equalizer_func() {
	audioeq[i]=$(get_selection_func "Track $i: Would you like to use the Audio Equalizer? [y/N]: ")
	if [ "${audioeq[i]}" = "y" ]; then
		printf "Track $i: Specify the Audio Equalizer parameters [press 'Enter' to skip]: "
		read audeqparams[i]
		if [ ! -z "${audeqparams[i]}" ]; then
			audeq[i]="equalizer=${audeqparams[i]},"
		fi
	fi
}

# Volume normalization
audio_volnorm_func() {
	norm[i]=$(get_selection_func "Track $i: Would you like to Normalize the Audio Volume? [y/N]: ")
	if [ "${norm[i]}" = "y" ]; then
		volnorm[i]="volnorm=1,"
	fi
}

# Volume
audio_volume_func() {
	avolume[i]=$(get_selection_func "Track $i: Would you like to set the Audio Volume? [y/N]: ")
	if [ "${avolume[i]}" = "y" ]; then
		printf "Track $i: Specify the Audio volume in dB [-200-60 - default is 2]: "
		read dbgain[i]
		if [ -z "${dbgain[i]}" ]; then
			volume[i]="volume=2:1,"
		else
			volume[i]="volume=${dbgain[i]}:1,"
		fi
	fi
}

# Audio panning
audio_pan_func() {
	audpan[i]=$(get_selection_func "Track $i: Would you like to Pan the Audio? [y/N]: ")
	if [ "${audpan[i]}" = "y" ]; then
		printf "Track $i: Specify the panning filter values [press 'Enter' to skip]: "
		read panval[i]
		if [ ! -z "${panval[i]}" ]; then
			pan[i]="pan=${panval[i]},"
		fi
	fi
}

# Audio channel routing/removing/adding filter
audio_channels_func() {
	if [ -z "${chanfilter[i]}" ]; then
		audroute[i]=$(get_selection_func "Track $i: Would you like to Add/Remove/Route Audio Channels? [y/N]: ")
		if [ "${audroute[i]}" = "y" ]; then
			printf "Track $i: Specify the Audio Channels filter parameters [press 'Enter' to skip]: "
			read audchanparams[i]
			if [ ! -z "${audchanparams[i]}" ]; then
				audchannels[i]="channels=${audchanparams[i]},"
				if [ "$(echo "${audchannels[i]}" | awk -F: '{print $1}' | sed 's|channels=||; s|,||')" -gt "6" ]; then
					audchannels[i]=
					echo
					error "-> More than 6 channels not supported!"
					error "-> Skipping channels filter"
					echo
				fi
			fi
		fi
	fi
}

# Audio channels decode function
audio_channels_decode_func() {
	case "${audiocodec[i]}" in
		aftenac3|lavcac3|eac3|dts|aac|neroaac|fdkaac|vorbis|opus|flac|pcm|"")
		chan[i]=$(get_selection_func "Track $i: Would you like to Decode/Output more than 2 Audio Channels? [y/N]: ")
		if [ "${chan[i]}" = "y" ]; then
			case "$source" in
				dvd|bd) defchans="6" ;;
				*)	defchans="2" ;;
			esac
			audio_channels_amount_func() {
				printf "Track $i: How many Channels to Decode? [1/2/3/4/5/6 - default is $defchans]: "
				read chandec[i]
				case "${chandec[i]}" in
					[1-6]|"") true ;;
					*)
					echo
					green "-> '${chandec[i]}' channels not supported!"
					green "-> Falling back to 2 channels decoding"
					echo
					chandec[i]=2
					;;
				esac
				if [ -z "${chandec[i]}" ]; then
					channels[i]="-channels $defchans"
				else
					channels[i]="-channels ${chandec[i]}"
				fi
			}
			echo
			brown "Channels Decode And Output"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "Decode: tells MEncoder the amount of channels"
			echo "        to decode, i.e. if the input  has 6"
			echo "        channels and you want to preserve them"
			echo "        without modifications, select the"
			echo "        Decode option and set the amount of"
			echo "        channels to 6 in the next option"
			echo
			echo "Output: tells h264enc to insert the channels"
			echo "        filter in order to output a possibly"
			echo "        different amount of channels. I.e."
			echo "        if the input has 6 channels but you"
			echo "        want to output 4, select the Output"
			echo "        option and set the desired amount"
			echo "        of channels to output in the next"
			echo "        option."
			echo "        Note that this filter is very basic"
			echo "        and will create empty channels in"
			echo "        case the amount of output channels"
			echo "        is higher than the amount of input"
			echo "        channels."
			echo
			printf "Track $i: Decode (D) or Output (O) the Channels? [D/O - default is D]: "
			read decout[i]
			case "${decout[i]}" in
				o|O|0)
				if [ "$DISABLE_ALL_AUD_FILTERS" = "n" ]; then
					audio_channels_amount_func
					if [ "${AACTYPE[i]}" = "HE-AACv2" ]; then
						if [ "$(echo ${channels[i]} | awk '{print $2}')" != "2" ]; then
							echo
							error "-> HE-AACv2 only supports Stereo!"
							error "-> Forcing stereo output decoding"
							echo
							channels[i]="-channels 2"
						fi
					else
						printf "Track $i: How many Channels to Output? [1/2/3/4/5/6 - default is 2]: "
						read outchan[i]
						case "${outchan[i]}" in
							1)	chanfilter[i]="channels=1," ;;
							2|"")	chanfilter[i]="channels=2," ;;
							3)	chanfilter[i]="channels=3," ;;
							4)	chanfilter[i]="channels=4," ;;
							5)	chanfilter[i]="channels=5," ;;
							6)	chanfilter[i]="channels=6," ;;
							*)
							echo
							error "-> '${outchan[i]}' channels not supported!"
							error "-> Exiting in function: audio_channels_decode_func()"
							echo
							exit_func 1
							;;
						esac
					fi
				else
					echo
					error "-> The DISABLE_ALL_AUD_FILTERS variable in the config file"
					error "   is set to \"y\" which disables all audio filters at once."
					error "-> Set it to \"n\" to enable the audio filters."
				fi
				;;
				*|"")
				audio_channels_amount_func
				;;
			esac
		fi
		;;
	esac
}

aac_hev2_func() {
	if [ "${AACTYPE[i]}" = "HE-AACv2" ]; then
		if [ -z "${channels[i]}" ]; then
			channels[i]="-channels 2"
		fi
	fi
}

# Global function for calling
# the above audio filters
audio_filters_func() {
	aud_filters_func() {
		case "${audiocodec[i]}" in
			mp3)
			test "$ALLOW_AUD_PAN" = "y" && audio_pan_func
			test "$ALLOW_AUD_EQUALIZER" = "y" && audio_equalizer_func
			;;
			*)
			test "$ALLOW_AUD_CHANNELS" = "y" && audio_channels_func
			test "$ALLOW_AUD_PAN" = "y" && audio_pan_func
			test "$ALLOW_AUD_EQUALIZER" = "y" && audio_equalizer_func
			test "$ALLOW_AUD_NORMALIZE" = "y" && audio_volnorm_func
			test "$ALLOW_AUD_VOLUME" = "y" && audio_volume_func
			;;
		esac
	}
	if [ "$ALLOW_AUD_CHANNELS" = "y" -o "$ALLOW_AUD_PAN" = "y" -o "$ALLOW_AUD_NORMALIZE" = "y" \
	-o "$ALLOW_AUD_VOLUME" = "y" -o "$ALLOW_AUD_RESAMPLE" = "y" -o "$ALLOW_AUD_EQUALIZER" = "y" ]; then
		use_audfilters[i]=$(get_selection_func "Track $i: Would you like to use Audio filters? [y/N]: ")
		if [ "${use_audfilters[i]}" = "y" ]; then
			case "$1" in
				fl|flhq|ag1|ag1hq|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|psp|psphq|ps3|ps3hq|mz|mzhq|mx|mxhq)
				# Resampling is skipped here. See the
				# audio_filters_var_func function below
				# for resampling for these presets
				aud_filters_func
				;;
				*)
				aud_filters_func
				test "$ALLOW_AUD_RESAMPLE" = "y" && audio_resample_func
				;;
			esac
		fi
	fi
}

audio_filters_var_func() {
	case "$1" in
		fl|flhq)
		afilters[i]="${audchannels[i]}${pan[i]}${audeq[i]}${volnorm[i]}${volume[i]},lavcresample=22050:16:1 -srate 22050"
		channels[i]="-channels 2"
		;;
		qt|qthq)
		afilters[i]="${audchannels[i]}${pan[i]}${audeq[i]}${volnorm[i]}${volume[i]}${resample[i]}"
		channels[i]="-channels 2"
		;;
		ag1|ag1hq|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|ar5|ar5hq|bb|bbhq|psp|psphq|mz|mzhq|mx|mxhq)
		afilters[i]="${audchannels[i]}${pan[i]}${audeq[i]}${volnorm[i]}${volume[i]},lavcresample=48000:16:1 -srate 48000"
		channels[i]="-channels 2"
		;;
		ps3|ps3hq)
		afilters[i]="${chanfilter[i]}${audchannels[i]}${pan[i]}${audeq[i]}${volnorm[i]}${volume[i]},lavcresample=48000:16:1 -srate 48000"
		;;
		nks60|nks60hq)
		afilters[i]="${audchannels[i]}${pan[i]}${audeq[i]}${volnorm[i]}${volume[i]},lavcresample=44100:16:1 -srate 44100"
		channels[i]="-channels 2"
		;;
		*)
		afilters[i]="${chanfilter[i]}${audchannels[i]}${pan[i]}${audeq[i]}${volnorm[i]}${volume[i]}${resample[i]}"
		;;
	esac
}

audio_track_echo_func() {
	for e in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
		if [ "$e" != "1" ]; then
			if [ "${TRACKID[e]}" = "yes" ]; then
				echo
			fi
		fi
	done
}

select_ac3_encoder_func() {
	printf "Track $i: Which AC-3 Encoder to use? [aften/lavc - default is lavc]: "
	read ac3enc[i]
	case "${ac3enc[i]}" in
		lavc|LAVC|"")
		audiocodec[i]="lavcac3"
		lavc_ac3_audio_func
		;;
		aften|AFTEN)
		if [ ! -x "$AFTEN" ]; then
			echo
			error "-> 'aften' is missing from your system!"
			error "-> Falling back to the lavc encoder"
			audiocodec[i]="lavcac3"
			lavc_ac3_audio_func
		else
			audiocodec[i]="aftenac3"
			aften_ac3_audio_func
		fi
		;;
		*)
		error "-> Unsupported AC-3 encoder: '${ac3enc[i]}'"
		error "-> Exiting in function: select_ac3_encoder_func()"
		exit_func 1
		;;
	esac
}

select_audio_codec_func() {
	for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
		if [ "${TRACKID[i]}" = "yes" ]; then
			case "$1" in
				qt|qthq|iph|iphhq|fl|flhq)
				echo
				printf "Track $i: Select the Audio Codec [AAC/NEROAAC/FDKAAC/AAC+/NOSOUND - default is AAC]: "
				;;
				ag1|ag1hq|ipc|ipchq|ip|iphq|atv|atvhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|psp|psphq|mx|mxhq)
				echo
				printf "Track $i: Select the Audio Codec [AAC/NEROAAC/FDKAAC/NOSOUND - default is AAC]: "
				;;
				bd40|bdhq40|bd41|bdhq41)
				echo
				printf "Track $i: Select the Audio Codec [AC3/EAC3/DTS/COPY/NOSOUND - default is AC3]: "
				;;
				avchd|avchdhq)
				echo
				printf "Track $i: Select the Audio Codec [AC3/COPY/NOSOUND - default is AC3]: "
				;;
				ps3|ps3hq)
				echo
				printf "Track $i: Select the Audio Codec [AAC/NEROAAC/FDKAAC/COPY/NOSOUND - default is AAC]: "
				;;
				mz|mzhq)
				echo
				printf "Track $i: Select the Audio Codec [MP3/AAC/NEROAAC/FDKAAC/NOSOUND - default is AAC]: "
				;;
				*)
				printf "Track $i: Select the Audio Codec [default is AAC]: "
				;;
			esac
			read audiocodec[i]
			audiocodec[i]="$(echo "${audiocodec[i]}" | tr '[:upper:]' '[:lower:]')"
			check_audio_codec_func
			case "$source" in
				dir)
				case "${audiocodec[1]}" in
					copy)
					echo
					error "-> Audio stream copy is not recommended with"
					error "   directory batch encoding if you are going"
					error "   to remux the encodes to MKV/MP4/TS/OGM!"
					echo
					;;
				esac
				;;
			esac
		fi
	done
	audio_track_echo_func
}

set_audio_codec_func() {
	if [ ! -z "$DEFAULT_AUD_CODEC" ]; then
		DEF_AUD_CODEC="$(echo "$DEFAULT_AUD_CODEC" | tr '[:lower:]' '[:upper:]')"
		case "$DEF_AUD_CODEC" in
			MP3|AC3|EAC3|DTS|AAC|AAC+|NEROAAC|FDKAAC|VORBIS|OPUS|FLAC|PCM|COPY|NOSOUND)
			echo
			green "-> Using '$DEF_AUD_CODEC' as default audio codec set in the config file"
			echo
			;;
			*)
			echo
			error "-> Unsupported default audio codec: '$DEF_AUD_CODEC'"
			error "-> Please check your config file in '$H264ENCDIR'"
			echo
			exit_func 1
			;;
		esac
		for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
			if [ "${TRACKID[i]}" = "yes" ]; then
				audiocodec[i]="$(echo "$DEFAULT_AUD_CODEC" | tr '[:upper:]' '[:lower:]')"
			fi
		done
	else
		case "$2" in
			codec)
			echo
			brown "Available Audio Codecs"
			brown "~~~~~~~~~~~~~~~~~~~~~~"
			echo "MP3 -----> Container support: AVI, MP4, MKV, OGM, TS"
			echo "AC3 -----> Container support: MP4, MKV, OGM, TS, AVI (only lavc)"
			echo "EAC3 ----> Container support: MKV, TS"
			echo "DTS -----> Container support: MKV, TS"
			echo "AAC -----> Container support: AVI, MP4, MKV, TS"
			echo "AAC+ ----> Container support: MP4, MKV"
			echo "NEROAAC -> Container support: MP4, MKV, TS (only in LC-AAC mode)"
			echo "FDKAAC --> Container support: MP4, MKV, TS (only in LC-AAC mode)"
			echo "VORBIS --> Container support: MP4, MKV, OGM"
			echo "OPUS ----> Container support: MKV"
			echo "FLAC ----> Container support: MKV"
			echo "PCM -----> Container support: AVI, MKV, OGM"
			echo "COPY ----> Container support: Depends on audio codec"
			echo "NOSOUND -> Container support: AVI, MP4, MKV, OGM, TS"
			echo
			;;
		esac
		select_audio_codec_func $1
	fi
}

audio_copy_func() {
	# In case we try to copy AAC audio we need
	# to pass MEncoder the proper audio format
	CPAUD[i]="$($MPLAYER "$sourcetype" $MPLAYEROPTS $device $demuxer $cache ${aid[i]} -vo null -ao null -frames 1 -identify 2>/dev/null | grep '^ID_AUDIO_CODEC' | tail -n 1 | awk -F= '{print $2}')"
	if [ "${CPAUD[i]}" = "ffaac" ]; then
		audiofmt[i]="-fafmttag 0x706d"
	fi
	# For TrueHD audio
	if [ "${CPAUD[i]}" = "fftruehd" ]; then
		acodec[i]="-nosound"
	else
		acodec[i]="-oac copy -mc 0 -noskip -msglevel demuxer=-1 ${audiofmt[i]}"
	fi
}

ask_audio_filters_func() {
	if [ "$DISABLE_ALL_AUD_FILTERS" = "n" ]; then
		audio_filters_func $1
		audio_filters_var_func $1
	else
		true
	fi
}

# Call the audio functions above.
# Order is important here and the
# correct way to call the functions
# is as follows:
#
# *_audio_func
# audio_channels_decode_func
# audio_filters_func
# audio_filters_var_func
# audio_track_echo_func

case "$3" in
	qt|qthq|iph|iphhq|fl|flhq)
	set_audio_codec_func $3
	for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
		if [ "${TRACKID[i]}" = "yes" ]; then
			case "${audiocodec[i]}" in
				aac|"")
				faac_audio_func $3
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				neroaac)
				neroaac_audio_func
				aac_hev2_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				fdkaac)
				fdkaac_audio_func
				aac_hev2_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				aac+)
				aacplus_audio_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				nosound)
				acodec[i]="-nosound"
				aid[i]=
				;;
				*)
				audio_codec_exit_func error
				;;
			esac
		fi
	done
	;;
	ag1|ag1hq|ipc|ipchq|ip|iphq|atv|atvhq|ar|arhq|ar5|ar5hq|bb|bbhq|nks60|nks60hq|psp|psphq|mx|mxhq)
	set_audio_codec_func $3
	for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
		if [ "${TRACKID[i]}" = "yes" ]; then
			case "${audiocodec[i]}" in
				aac|"")
				faac_audio_func $3
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				neroaac)
				neroaac_audio_func $3
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				fdkaac)
				fdkaac_audio_func $3
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				nosound)
				acodec[i]="-nosound"
				aid[i]=
				;;
				*)
				audio_codec_exit_func error
				;;
			esac
		fi
	done
	;;
	bd40|bdhq40|bd41|bdhq41)
	set_audio_codec_func $3
	for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
		if [ "${TRACKID[i]}" = "yes" ]; then
			case "${audiocodec[i]}" in
				ac3|"")
				select_ac3_encoder_func
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				eac3)
				eac3_audio_func
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				dts)
				dts_audio_func
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				copy)
				audio_copy_func
				;;
				nosound)
				acodec[i]="-nosound"
				aid[i]=
				;;
				*)
				audio_codec_exit_func error
				;;
			esac
		fi
	done
	;;
	avchd|avchdhq)
	set_audio_codec_func $3
	for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
		if [ "${TRACKID[i]}" = "yes" ]; then
			case "${audiocodec[i]}" in
				ac3|"")
				select_ac3_encoder_func
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				copy)
				audio_copy_func
				;;
				nosound)
				acodec[i]="-nosound"
				aid[i]=
				;;
				*)
				audio_codec_exit_func error
				;;
			esac
		fi
	done
	;;
	ps3|ps3hq)
	set_audio_codec_func $3
	for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
		if [ "${TRACKID[i]}" = "yes" ]; then
			case "${audiocodec[i]}" in
				aac|"")
				faac_audio_func $3
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				neroaac)
				neroaac_audio_func $3
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				fdkaac)
				fdkaac_audio_func $3
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				copy)
				audio_copy_func
				;;
				nosound)
				acodec[i]="-nosound"
				aid[i]=
				;;
				*)
				audio_codec_exit_func error
				;;
			esac
		fi
	done
	;;
	mz|mzhq)
	set_audio_codec_func $3
	for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
		if [ "${TRACKID[i]}" = "yes" ]; then
			case "${audiocodec[i]}" in
				mp3)
				mp3_audio_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				aac|"")
				faac_audio_func $3
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				neroaac)
				neroaac_audio_func $3
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				fdkaac)
				fdkaac_audio_func $3
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				nosound)
				acodec[i]="-nosound"
				aid[i]=
				;;
				*)
				audio_codec_exit_func error
				;;
			esac
		fi
	done
	;;
	*)
	set_audio_codec_func $3 codec
	for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
		if [ "${TRACKID[i]}" = "yes" ]; then
			case "${audiocodec[i]}" in
				mp3)
				mp3_audio_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				ac3)
				select_ac3_encoder_func
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				eac3)
				eac3_audio_func
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				dts)
				dts_audio_func
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				aac|"")
				faac_audio_func
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				aac+)
				aacplus_audio_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				neroaac)
				neroaac_audio_func
				audio_channels_decode_func
				aac_hev2_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				fdkaac)
				fdkaac_audio_func
				audio_channels_decode_func
				aac_hev2_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				vorbis)
				vorbis_audio_func
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				opus)
				opus_audio_func
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				flac)
				flac_audio_func
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				pcm)
				acodec[i]="-oac pcm"
				audio_channels_decode_func
				ask_audio_filters_func $3
				audio_track_echo_func
				;;
				copy)
				audio_copy_func
				;;
				nosound)
				acodec[i]="-nosound"
				aid[i]=
				;;
				*)
				audio_codec_exit_func error
				;;
			esac
		fi
	done
	;;
esac

echo
brown "+=============================+"
brown "| Miscellaneous Configuration |"
brown "+=============================+"
echo

# AAC VBR not supported
case "$SKIPBTRCALC" in
	yes)
	true
	;;
	*)
	case "$1" in
		-[1-3]p)
		case "${audiocodec[1]}" in
			mp3|aftenac3|lavcac3|eac3|dts|aac|aac+|neroaac|fdkaac|vorbis|opus|pcm|copy|nosound|"")
			calcvidbit=$(get_selection_func "Would you like to set a target file size? [y/N]: ")
			if [ "$calcvidbit" = "y" ]; then
				# Currently we don't take container overhead into account
				echo
				brown "Video Bitrate Calculation/Target File Size"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "h264enc can calculate the video bitrate for you"
				echo "based on the video length, chosen audio bitrate and"
				echo "target file size. The only thing you have to provide"
				echo "here is the desired target size in Mebibytes for the"
				echo "encode. After that, you can choose to keep the bitrate"
				echo "calculated by h264enc, or you can provide a new one."
				echo
				printf "Specify the desired Target File Size in Mebibytes [default is 700]: "
				read tfsm
				if [ -z "$tfsm" ]; then
					TARGET_SIZE=700
				else
					TARGET_SIZE=$tfsm
				fi
				# Get the chosen audio bitrate
				for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
					if [ "${TRACKID[i]}" = "yes" ]; then
						case "${audiocodec[i]}" in
							aftenac3|lavcac3|eac3)
							AUDIO_BITRATE[i]=${abitrate[i]}
							;;
							dts)
							AUDIO_BITRATE[i]=$((${abitrate[i]}/1000))
							;;
							mp3)
							case "${mp3mode[i]}" in
								a*|A*|c*|C*|"")
								AUDIO_BITRATE[i]=$(echo ${abitrate[i]} | awk -F= '{print $2}')
								;;
								v*|V*)
								# Use 10 kbps lesser compared
								# to the LAME specs
								case "${abitrate[i]}" in
									q=0) AUDIO_BITRATE[i]=230 ;;
									q=1) AUDIO_BITRATE[i]=200 ;;
									q=2) AUDIO_BITRATE[i]=180 ;;
									q=3) AUDIO_BITRATE[i]=165 ;;
									q=4) AUDIO_BITRATE[i]=155 ;;
									q=5) AUDIO_BITRATE[i]=120 ;;
									q=6) AUDIO_BITRATE[i]=105 ;;
									q=7) AUDIO_BITRATE[i]=90 ;;
									q=8) AUDIO_BITRATE[i]=75 ;;
									q=9) AUDIO_BITRATE[i]=54 ;;
								esac
								;;
								p*|P*)
								case "${mp3preset[i]}" in
									0|"") AUDIO_BITRATE[i]=160 ;;
									1) AUDIO_BITRATE[i]=185 ;;
									2) AUDIO_BITRATE[i]=210 ;;
									3) AUDIO_BITRATE[i]=320 ;;
								esac
								;;
							esac
							;;
							aac|"")
							AUDIO_BITRATE[i]=$(echo ${br[i]} | sed 's|br=||g')
							;;
							aac+)
							AUDIO_BITRATE[i]=${aacplusbr[i]}
							;;
							neroaac)
							AUDIO_BITRATE[i]=$(($(echo ${neroaacbr[i]} | awk '{print $2}')/1000))
							;;
							fdkaac)
							AUDIO_BITRATE[i]=$(($(echo ${fdkaacbr[i]} | awk '{print $2}')/1000))
							;;
							vorbis)
							case "${vorbmode[i]}" in
								a*|A*)
								AUDIO_BITRATE[i]=$(echo ${vorbq[i]} | awk '{print $2}')
								;;
								v*|V*|"")
								# Quality values -> bitrate mappings
								case "$(echo ${vorbq[i]} | awk '{print $2}')" in
									-1) AUDIO_BITRATE[i]=45 ;;
									0) AUDIO_BITRATE[i]=64 ;;
									1) AUDIO_BITRATE[i]=80 ;;
									2) AUDIO_BITRATE[i]=96 ;;
									3) AUDIO_BITRATE[i]=112 ;;
									4) AUDIO_BITRATE[i]=128 ;;
									5) AUDIO_BITRATE[i]=160 ;;
									6) AUDIO_BITRATE[i]=192 ;;
									7) AUDIO_BITRATE[i]=224 ;;
									8) AUDIO_BITRATE[i]=256 ;;
									9) AUDIO_BITRATE[i]=320 ;;
									10) AUDIO_BITRATE[i]=500 ;;
								esac
								;;
							esac
							;;
							opus)
							AUDIO_BITRATE[i]=${opusbr[i]}
							;;
							pcm)
							# Get channels info. Resampling is not taken
							# into account yet so we assume 48 kHz
							if [ ! -z "${channels[i]}" -a ! -z "${chanfilter[i]}" ]; then
								case "$(echo "${chanfilter[i]}" | sed 's|channels=||; s|,||')" in
									1)	AUDIO_BITRATE[i]=768 ;;
									2)	AUDIO_BITRATE[i]=1536 ;;
									3)	AUDIO_BITRATE[i]=2304 ;;
									4)	AUDIO_BITRATE[i]=3072 ;;
									5)	AUDIO_BITRATE[i]=3840 ;;
									6)	AUDIO_BITRATE[i]=4608 ;;
									7)	AUDIO_BITRATE[i]=5376 ;;
									8)	AUDIO_BITRATE[i]=6144 ;;
								esac
							elif [ ! -z "${channels[i]}" -a -z "${chanfilter[i]}" ]; then
								case "$(echo "${channels[i]}" | awk '{print $2}')" in
									1)	AUDIO_BITRATE[i]=768 ;;
									2)	AUDIO_BITRATE[i]=1536 ;;
									3)	AUDIO_BITRATE[i]=2304 ;;
									4)	AUDIO_BITRATE[i]=3072 ;;
									5)	AUDIO_BITRATE[i]=3840 ;;
									6)	AUDIO_BITRATE[i]=4608 ;;
									7)	AUDIO_BITRATE[i]=5376 ;;
									8)	AUDIO_BITRATE[i]=6144 ;;
								esac
							else
								AUDIO_BITRATE[i]=1536
							fi
							;;
							copy)
							$MPLAYER "$sourcetype" $MPLAYEROPTS $device ${aid[i]} $cache -vo null -ao null -identify -demuxer lavf -frames 1 2>/dev/null > "$TEMPDIR/copybitrate"
							AUDIOBTR[i]="$(grep '^ID_AUDIO_BITRATE' "$TEMPDIR/copybitrate" | tail -n 1 | awk -F= '{print $2}')"
							case "${AUDIOBTR[i]}" in
								[1-9]*)
								AUDIO_BITRATE[i]=$((${AUDIOBTR[i]}/1000))
								;;
								*|"")
								echo
								green "-> Track $i: It seems the audio bitrate could not be detected or it's reported as 0 bps"
								green "-> Track $i: If you know the audio bitrate, please provide it below in kbps"
								echo
								printf "Track $i: Provide the Audio Bitrate in kbps [default is 0]: "
								read cpbtr[i]
								if [ -z "${cpbtr[i]}" ]; then
									AUDIO_BITRATE[i]=0
								else
									AUDIO_BITRATE[i]=${cpbtr[i]}
								fi
								;;
							esac
							rm -f "$TEMPDIR/copybitrate"
							;;
							nosound)
							AUDIO_BITRATE[i]=0
							;;
						esac
					fi
				done
				
				AUDBTR=$(($(echo "${AUDIO_BITRATE[*]}" | sed 's| |+|g')))
				
				echo
				brown "Available Formulas"
				brown "~~~~~~~~~~~~~~~~~~"
				echo "0 -> MeGUI formula"
				echo "1 -> h264enc's refactored MeGUI formula"
				echo "2 -> h264enc/ripdvd old formula"
				echo "3 -> Use a custom factor value"
				echo
				printf "Which formula to use? [default is 0]: "
				read formula
				case "$formula" in
					0|"") FACTOR="0.125" ;;
					1) FACTOR="0.1244" ;;
					2) FACTOR= ;;
					3)
					echo
					brown "Custom Factor Value"
					brown "~~~~~~~~~~~~~~~~~~~"
					echo "You can provide a custom factor value which is"
					echo "used to adjust the formula's bitrate calculation."
					echo "Lower factor values result in higher bitrates while"
					echo "higher factor values result in lower bitrates. The"
					echo "default factor is that of the MeGUI formula, which"
					echo "is 0.125. The factor of h264enc's refactored MeGUI"
					echo "formula is 0.1244 resulting in roughly 10 kbps higher"
					echo "bitrate, thus increasing the final file size by a few"
					echo "Megabytes. A factor of 0.127, for example, will result"
					echo "in a bitrate of ~20 kbps less that the default factor"
					echo "of 0.125"
					echo
					printf "Provide the Factor value [default is 0.125 (MeGUI's factor)]: "
					read customfactor
					if [ -z "$customfactor" ]; then
						FACTOR="0.125"
					else
						FACTOR="$customfactor"
					fi
					;;
					*)
					error "-> Unknown option: '$formula'"
					exit_func 1
					;;
				esac
				echo
				green "-> Detecting video length..."
				$MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid -vo null -ao null -identify -frames 1 2>/dev/null > "$TEMPDIR/videoinfo"
				VIDEO_LENGTH=$(grep "^ID_LENGTH" "$TEMPDIR/videoinfo" | awk -F= '{print $2}')
				rm -f "$TEMPDIR/videoinfo"
				if [ -z "$VIDEO_LENGTH" ]; then
					echo
					green "-> Could not detect the video length!"
					green "-> Skipping video bitrate calculation!"
					echo
				else
					if [ ! -z "$ofps" ]; then
						FRAMES=$(echo "scale=0; $VIDEO_LENGTH * $(echo "$ofps" | awk '{print $2}')" | $BC -l | awk -F. '{print $1}')
					else
						FRAMES=$(echo "scale=0; $VIDEO_LENGTH * $GETFPS" | $BC -l | awk -F. '{print $1}')
					fi
					case "$formula" in
						0|1|3|"")
						VBITRATE=$(echo "scale=0; ($TARGET_SIZE * 1024 * 1024 - $FRAMES * 24 - $AUDBTR * 1000 * $VIDEO_LENGTH * $FACTOR) / ($VIDEO_LENGTH * $FACTOR) / 1000" | $BC -l)
						;;
						2)
						VBITRATE=$(echo "scale=0; ($TARGET_SIZE * 8192 / $VIDEO_LENGTH) - $AUDBTR" | $BC -l)
						;;
					esac
					bits_per_pixel_func
					bits_per_block_func
					green "-> Video length is $(echo "scale=2; $VIDEO_LENGTH / 60" | $BC -l) minutes or $VIDEO_LENGTH seconds"
					green "-> Number of frames: $FRAMES"
					green "-> Chosen/detected audio bitrate is $AUDBTR kbps in total"
					echo
					green "-> Estimated video bitrate for $TARGET_SIZE MiB: $VBITRATE kbps"
					green "-> Bits Per Pixel value: $BPP bpp"
					green "-> Bits Per Block value: $BPB bpb"
					echo
					printf "Specify the new video bitrate in kbps [default is $VBITRATE]: "
					read new_vbitrate
					if [ -z "$new_vbitrate" ]; then
						bitrate="bitrate=$VBITRATE"
					else
						bitrate="bitrate=$new_vbitrate"
					fi
				fi
			fi
			;;
		esac
		;;
	esac
	;;
esac

mencopts=$(get_selection_func "Would you like to pass additional options to MEncoder? [y/N]: ")
if [ "$mencopts" = "y" ]; then
	printf "Specify the MEncoder options: "
	read menc_opts
	if [ ! -z "$menc_opts" ]; then
		MENCOPTS="$menc_opts"
	fi
fi

###############################################################
################# MEncoder configuration ######################
###############################################################

# Audio/video filters variables for all
# passes. Since all filters are the same in
# each pass, we put them in a single
# variable to reduce code duplication and
# filter maintenance.
#
# The softskip filter should come after filters
# which need to see duplicate or skipped frames
# in order to operate correctly. This includes any
# filter that does temporal processing, like the
# temporal denoiser, hqdn3d/denoise3d and all the
# inverse telecine filters. The softskip filter
# should also come before scaling so that the
# scale filter will be skipped if a frame is going
# to be dropped. Deinterlacing or pullup should be
# done before cropping but it can also be done after
# it (it's faster that way too) and since I don't
# want to maintain two filter chains, one for when
# tfields is used and one when it isn't, we'll always
# deinterlace after cropping. The harddup filter
# should be placed before the telecine one so that
# duplicate frames will never get telecined, we don't
# want that. The interlace filters should be placed
# after the softskip and scale filters and after the
# harddup filter so that duplicate frames will never
# get interlaced. The (un)sharp mask / gaussian blur
# filter should come after the scale filter. The 'tfields'
# filter should come after the crop filter as it alters
# the resolution and MEncoder will error out with a
# "crop area outside of the original" message.
#

# Video filters chain
videofilters="-vf $(echo $ivtcfilter$delogofilter$cropfilter$deintfilter$fpsfilter$ild$deblockfilter$denoisefilter$debandfilter$ili$brightnessfilter$colorspacefilter,softskip,$dsizefilter$expandfilter_bfr$scale$isws$swsparam$expandfilter_afr$noisefilter$unsharpfilter$eq2filter,harddup$intfilter$telecinefilter$rotatefilter | sed 's|^,||; s|,,|,|g; s|,$||')"

# Audio filters chain
for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
	if [ "${TRACKID[i]}" = "yes" ]; then
		if [ ! -z "${afilters[i]}" ]; then
			audiofilters[i]="-af $(echo ${afilters[i]} | sed 's|^,||; s|,,|,|g; s|,$||')"
		fi
	fi
done

if [ "$source" = "bd" ]; then
	demuxer="-demuxer lavf -cache 20000"
fi

# Dump first sub during the first pass
case "$1" in
	-1p|-qp|-crf)
	if [ ! -z "${vobsubout[1]}" ]; then
		menc_subtitle="${subtitle[1]} ${vobsubout[1]}"
	else
		menc_subtitle="${subtitle[1]}"
	fi
	;;
	-[2-3]p)
	if [ ! -z "${vobsubout[1]}" ]; then
		menc_subtitle="${subtitle[1]} ${vobsubout[1]}"
		menc_hardsub="-nosub"
	else
		menc_subtitle="${subtitle[1]}"
		menc_hardsub="${subtitle[1]}"
	fi
	# Log file for 2- and 3-pass
	case "$source" in
		dir)	PASSLOG="-passlogfile \"$TEMPDIR/\${i%.*}.log\"" ;;
		*)	PASSLOG="-passlogfile \"$TEMPDIR/$(basename "${OUTPUT%.*}.log")\"" ;;
	esac
	;;
esac

mencoder_opts_func() {
	case "$1" in
		-1p|-crf|-qp)	pass_output1="-o \"$OUTPUT\"" ;;
		-2p) 		passopt1="pass=1:"; passopt2="pass=2:"; pass_output1="-o /dev/null"; pass_output2="-o \"$OUTPUT\"" ;;
		-3p) 		passopt1="pass=1:"; passopt2="pass=3:"; pass_output1="-o /dev/null"; pass_output2="-o /dev/null" ;;
	esac
	# Pass one
	echo "$nicelevel $MENCODER \"$sourcetype\" $pass_output1 $MENCOPTS $PASSLOG $EDL $demuxer $device $vid $chapters $movieangle $nosub $menc_subtitle $fps $ofps $videofilters $field_dominance $aspect $sws ${aid[1]} ${audiofilters[1]} ${channels[1]} ${acodec[1]} -ovc x264 -x264encopts $passopt1$bitrate$interlaced$cqm$nr$x264params $quiet"
	case "$1" in
		-[2-3]p)
		echo
		# Pass two
		echo "$nicelevel $MENCODER \"$sourcetype\" $pass_output2 $MENCOPTS $PASSLOG $EDL $demuxer $device $vid $chapters $movieangle $nosub $menc_hardsub $fps $ofps $videofilters $field_dominance $aspect $sws ${aid[1]} ${audiofilters[1]} ${channels[1]} ${acodec[1]} -ovc x264 -x264encopts $passopt2$bitrate$interlaced$cqm$nr$x264params $quiet"
		case "$1" in
			-3p)
			echo
			# Pass three
			echo "$nicelevel $MENCODER \"$sourcetype\" -o \"$OUTPUT\" $MENCOPTS $PASSLOG $EDL $demuxer $device $vid $chapters $movieangle $nosub $menc_hardsub $fps $ofps $videofilters $field_dominance $aspect $sws ${aid[1]} ${audiofilters[1]} ${channels[1]} ${acodec[1]} -ovc x264 -x264encopts $passopt2$bitrate$interlaced$cqm$nr$x264params $quiet"
			;;
		esac
		;;
	esac
}

# Export the MEncoder parameters to file(s)
# These files will be used to execute MEncoder
# with its parameters.

H264_1PFQ="$TEMPDIR/pass1_crfqp"
H264_2P1="$TEMPDIR/pass1"
H264_2P2="$TEMPDIR/pass2"
H264_2P3="$TEMPDIR/pass3"

case "$source" in
	dir)
	BATCH="$H264ENCDIR/batch$$"
	echo "#!/usr/bin/env bash" > "$BATCH"
	echo "# Automatically generated batch file by h264enc $version on $(date)" >> "$BATCH"
	echo >> "$BATCH"
	chmod 755 "$BATCH"
	echo "################### START OF COMMANDS ###################" >> "$BATCH"
	echo >> "$BATCH"
	echo "cd \"$(dirname "$sourcetype")\"" >> "$BATCH"
	echo "test -d \"$(dirname "$OUTPUT")\" || mkdir -p \"$(dirname "$OUTPUT")\"" >> "$BATCH"
	echo >> "$BATCH"
	echo "for i in *; do" >> "$BATCH"
	echo >> "$BATCH"
	echo "if [ -f \"\$i\" ]; then" >> "$BATCH"
	echo >> "$BATCH"
	echo "test -d \"$TEMPDIR\" || mkdir -p \"$TEMPDIR\"" >> "$BATCH"
	echo >> "$BATCH"
	echo "echo" >> "$BATCH"
	echo "echo -e \"\e[1;32m-> Processing file '$(dirname "$sourcetype")/\$i'\e[0;39;49m\"" >> "$BATCH"
	echo "echo" >> "$BATCH"
	echo "sleep 3" >> "$BATCH"
	echo >> "$BATCH"
	echo "$(mencoder_opts_func $1 | sed "s|$sourcetype|\$i|g")" >> "$BATCH"
	echo >> "$BATCH"
	;;
	*)
	case "$1" in
		-1p|-qp|-crf)
		mencoder_opts_func $1 > "$H264_1PFQ"
		;;
		-2p)
		mencoder_opts_func $1 > "$TEMPDIR/h264enc_2pass"
		# Split 2pass file
		# into two files
		cat "$TEMPDIR/h264enc_2pass" | head -n 1 > "$H264_2P1"
		cat "$TEMPDIR/h264enc_2pass" | tail -n 1 > "$H264_2P2"
		rm -f "$TEMPDIR/h264enc_2pass"
		;;
		-3p)
		mencoder_opts_func $1 > "$TEMPDIR/h264enc_3pass"
		# Split 3pass file
		# into three files
		cat "$TEMPDIR/h264enc_3pass" | head -n 1 > "$H264_2P1"
		cat "$TEMPDIR/h264enc_3pass" | head -n 3 | tail -n 1 > "$H264_2P2"
		cat "$TEMPDIR/h264enc_3pass" | tail -n 1 > "$H264_2P3"
		rm -f "$TEMPDIR/h264enc_3pass"
		;;
	esac
	;;
esac

# Encode a sample
if [ "$ALLOW_SAMPLE_ENCODING" = "y" ]; then
	case "$source" in
		file|dvd|bd|vcd)
		sample=$(get_selection_func "Would you like to encode a Sample? [y/N]: ")
		if [ "$sample" = "y" ]; then
			printf "Specify the start position in hour:min:sec [default is 0:02:00]: "
			read sample_startpos
			if [ -z "$sample_startpos" ]; then
				samplepos="-ss 0:02:00"
			else
				samplepos="-ss $sample_startpos"
			fi
			printf "Specify the duration in seconds for the sample [default is 30]: "
			read sample_duration
			if [ -z "$sample_duration" ]; then
				sampledur="-endpos 30"
			else
				sampledur="-endpos $sample_duration"
			fi
			echo
			green "-> Encoding sample, please wait..."
			test -e $HOME/sample_$$.avi && mv -f $HOME/sample_$$.avi $HOME/sample_$$.avi.old
			case "$1" in
				-1p|-qp|-crf)
				cat "$H264_1PFQ" | sed -e "s|$MENCODER|$MENCODER $samplepos $sampledur|" -e "s|\"$OUTPUT\"|$HOME/sample_$$.avi|" > "$TEMPDIR/sampleopts1"
				;;
				-2p)
				cat "$H264_2P1" | sed "s|$MENCODER|$MENCODER $samplepos $sampledur|" > "$TEMPDIR/sampleopts1"
				cat "$H264_2P2" | sed -e "s|$MENCODER|$MENCODER $samplepos $sampledur|" -e "s|\"$OUTPUT\"|$HOME/sample_$$.avi|" > "$TEMPDIR/sampleopts2"
				;;
				-3p)
				cat "$H264_2P1" | sed "s|$MENCODER|$MENCODER $samplepos $sampledur|" > "$TEMPDIR/sampleopts1"
				cat "$H264_2P2" | sed "s|$MENCODER|$MENCODER $samplepos $sampledur|" > "$TEMPDIR/sampleopts2"
				cat "$H264_2P3" | sed -e "s|$MENCODER|$MENCODER $samplepos $sampledur|" -e "s|\"$OUTPUT\"|$HOME/sample_$$.avi|" > "$TEMPDIR/sampleopts3"
				;;
			esac
			for i in {1..3}; do
				if [ -f "$TEMPDIR/sampleopts$i" ]; then
					green "-> Running pass $i..."
					source "$TEMPDIR/sampleopts$i" >/dev/null 2>&1
					green "-> Done"
				fi
			done
			for i in sampleopts* *.log *.mbtree; do
				rm -f "$TEMPDIR/$i"
			done
			# Remove subs if any
			test -e "${IDXFILE[1]}" && rm -f "${IDXFILE[1]}" "${SUBFILE[1]}"
			if [ -e "$HOME/sample_$$.avi" ]; then
				green "-> Previewing..."
				sleep 1
				$MPLAYER $MPLAYEROPTS -nocache "$HOME/sample_$$.avi" >/dev/null 2>&1
			else
				error "-> Failed"
			fi
			echo
		fi
		;;
	esac
fi

# Display the options before encoding.
# This was a request from a few users :)
# Currently, there's no way how to modify
# these options if the user wants it
case "$source" in
	file|dvd|bd|vcd)
	inspect=$(get_selection_func "Would you like to inspect the MEncoder options? [y/N]: ")
	if [ "$inspect" = "y" ]; then
		echo
		brown "+===========================+"
		brown "| MEncoder encoding options |"
		brown "+===========================+"
		echo
		case "$1" in
			-1p|-qp|-crf)
			echo "$(cat "$H264_1PFQ")"
			;;
			-2p)
			brown "First pass options"
			brown "~~~~~~~~~~~~~~~~~~"
			echo "$(cat "$H264_2P1")"
			echo
			brown "Second pass options"
			brown "~~~~~~~~~~~~~~~~~~~"
			echo "$(cat "$H264_2P2")"
			;;
			-3p)
			brown "First pass options"
			brown "~~~~~~~~~~~~~~~~~~"
			echo "$(cat "$H264_2P1")"
			echo
			brown "Second pass options"
			brown "~~~~~~~~~~~~~~~~~~~"
			echo "$(cat "$H264_2P2")"
			echo
			brown "Third pass options"
			brown "~~~~~~~~~~~~~~~~~~"
			echo "$(cat "$H264_2P3")"
			;;
		esac
		echo
	fi
	;;
esac

# Export the MEncoder parameters to an
# options file. Useful for inspection
# of the parameters or for batch encoding.
case "$source" in
	file|dvd|bd|vcd)
	saveopts=$(get_selection_func "Would you like to save the Parameters to a File? [y/N]: ")
	if [ "$saveopts" = "y" ]; then
		printf "Where to Store the Parameters? [default is $HOME/batchfile]: "
		read -e storeopts
		if [ -z "$storeopts" ]; then
			OPTSFILE="$HOME/batchfile"
		else
			OPTSFILE="$storeopts"
			test_write_func batchfile
		fi
		CMDSTART="################### START OF COMMANDS FOR $OUTPUT ###################"
		DIRTEST="test -d \"$(dirname "$OUTPUT")\" || mkdir -p \"$(dirname "$OUTPUT")\""
		CONFTEST="test -d \"$TEMPDIR\" || mkdir -p \"$TEMPDIR\""
		FILETEST="test -e \"$OUTPUT\" && mv -f \"$OUTPUT\" \"$OUTPUT.old\""
		# Dump the second, third, etc
		# subtitle if selected
		case "${audiocodec[1]}" in
			nosound)	audfmt="-nosound" ;;
			*)		audfmt="-oac pcm" ;;
		esac
		dump_subs_func() {
			for i in $(eval echo "{2..$MAX_AMOUNT_SUBS}"); do
				if [ ! -z "${vobsubout[i]}" ]; then
					echo "$MENCODER $sourcetype $device $chapters $ofps ${subtitle[i]} ${vobsubout[i]} ${aid[i]} $audfmt -ovc copy -o /dev/null"
					echo
				fi
			done
		}
		# Write out...
		if [ -e "$OPTSFILE" ]; then
			if [ -z "$(grep '^#!/usr/bin/env bash' "$OPTSFILE")" \
			-a -z "$(grep '^#!/usr/bin/env sh' "$OPTSFILE")" \
			-a -z "$(grep '^#!/bin/bash' "$OPTSFILE")" \
			-a -z "$(grep '^#!/bin/sh' "$OPTSFILE")" ]; then
				mv -f "$OPTSFILE" "$OPTSFILE$$"
				echo "#!/usr/bin/env bash" > "$OPTSFILE"
				echo "# Automatically generated by h264enc $version on $(date)" >> "$OPTSFILE"
				echo >> "$OPTSFILE"
				cat "$OPTSFILE$$" >> "$OPTSFILE"
				rm -f "$OPTSFILE$$"
				chmod 755 "$OPTSFILE"
			fi
		else
			echo "#!/usr/bin/env bash" > "$OPTSFILE"
			echo "# Automatically generated by h264enc $version on $(date)" >> "$OPTSFILE"
			echo >> "$OPTSFILE"
			chmod 755 "$OPTSFILE"
		fi
		echo "$CMDSTART" >> "$OPTSFILE"
		echo >> "$OPTSFILE"
		echo "$DIRTEST" >> "$OPTSFILE"
		echo "$CONFTEST" >> "$OPTSFILE"
		echo "$FILETEST" >> "$OPTSFILE"
		echo >> "$OPTSFILE"
		case "$1" in
			-1p|-qp|-crf)
			echo "$(cat "$H264_1PFQ")" >> "$OPTSFILE"
			echo >> "$OPTSFILE"
			dump_subs_func >> "$OPTSFILE"
			echo "sleep 2" >> "$OPTSFILE"
			echo >> "$OPTSFILE"
			;;
			-2p)
			echo "$(cat "$H264_2P1")" >> "$OPTSFILE"
			echo >> "$OPTSFILE"
			echo "$(cat "$H264_2P2")" >> "$OPTSFILE"
			echo >> "$OPTSFILE"
			dump_subs_func >> "$OPTSFILE"
			echo "sleep 2" >> "$OPTSFILE"
			echo >> "$OPTSFILE"
			;;
			-3p)
			echo "$(cat "$H264_2P1")" >> "$OPTSFILE"
			echo >> "$OPTSFILE"
			echo "$(cat "$H264_2P2")" >> "$OPTSFILE"
			echo >> "$OPTSFILE"
			echo "$(cat "$H264_2P3")" >> "$OPTSFILE"
			echo >> "$OPTSFILE"
			dump_subs_func >> "$OPTSFILE"
			echo "sleep 2" >> "$OPTSFILE"
			echo >> "$OPTSFILE"
			;;
		esac
	fi
	;;
esac

# Audio code for all audio tracks follows...
#
# Nasty hack for ivtc/fps/deint filters.
# Filter order is all wrong but who
# cares at this point

if [ ! -z "$ivtcfilter" ]; then
	vidfilter=",$(echo $ivtcfilter | sed 's|,$||')"
fi
if [ ! -z "$fpsfilter" ]; then
	vidfilter=",$(echo $fpsfilter | sed 's|,$||')"
fi
if [ "$deintmethod" = "0" ]; then
	vidfilter=",framestep=2"
elif [ "$deintmethod" = "2" ]; then
	vidfilter=",yadif=3"
fi
vidfilteropts="-sws 1 -vf scale=16:16$vidfilter$intfilter$telecinefilter,softskip,harddup"
vidcodecopts="-ovc lavc -lavcopts vcodec=mpeg2video"

AUDPIPE="$TEMPDIR/audio.pipe"
mkfifo "$AUDPIPE"
FIFO="test -p \"$AUDPIPE\" || mkfifo \"$AUDPIPE\""

for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
	if [ "${TRACKID[i]}" = "yes" ]; then
		case "$source" in
			dir) 	AUDIOENC[i]="$BATCH" ;;
			*)	AUDIOENC[i]="$TEMPDIR/audioenc$i" ;;
		esac
		
		if [ "$i" = "1" ]; then
			AUDINPUT="$OUTPUT"
		else
			AUDINPUT="$TEMPDIR/audio$i.avi"
		fi
		if [ "$i" != "1" ]; then
			audflt[i]="${audiofilters[i]}"
		fi
		# aac-enc only supports signed 16 bit WAV format
		# dcaenc misinterprets floating-point WAVs as
		# 32-bit integer ones due to a known bug.
		case "${audiocodec[i]}" in
			fdkaac|dts)
			if [ ! -z "${audflt[i]}" ]; then
				audfilters[i]="${audflt[i]},format=s16le"
			else
				audfilters[i]="-af format=s16le"
			fi
			;;
			*)
			audfilters[i]="${audflt[i]}"
			;;
		esac
		
		MPL[i]="$MPLAYER \"$AUDINPUT\" $MPLAYEROPTS ${channels[i]} ${audfilters[i]} -really-quiet -vc dummy -vo null -nocache -ao pcm:fast:file=\"$AUDPIPE\""
		NERO[i]="$NEROAACENC -ignorelength ${neroaacbr[i]} -if \"$AUDPIPE\" -of \"$TEMPDIR/audio$i.aac\" &"
		FDKAAC[i]="$FDKAACENC ${fdkaacbr[i]} \"$AUDPIPE\" \"$TEMPDIR/audio$i.aac\" &"
		AACPLUS[i]="$AACPLUSENC \"$AUDPIPE\" \"$TEMPDIR/audio$i.aac\" ${aacplusbr[i]} &"
		OGG[i]="$OGGENC ${vorbq[i]} \"$AUDPIPE\" -o \"$TEMPDIR/audio$i.ogg\" &"
		OPUS[i]="$OPUSENC ${opusopts[i]} \"$AUDPIPE\" \"$TEMPDIR/audio$i.opus\" &"
		FLACENC[i]="$FLAC ${flacq[i]} \"$AUDPIPE\" -o \"$TEMPDIR/audio$i.flac\" &"
		DTSENC[i]="$DCAENC \"$AUDPIPE\" \"$TEMPDIR/audio$i.dts\" ${abitrate[i]} &"
		AFTENENC[i]="$AFTEN ${ac3opts[i]} \"$AUDPIPE\" \"$TEMPDIR/audio$i.ac3\" &"
		
		# Identify audio codec
		# for audio stream copy
		case "${audiocodec[i]}" in
			copy)
			echo
			green "-> Track $i: Detecting audio codec..."
			AUDCODEC[i]=$($MPLAYER "$sourcetype" $MPLAYEROPTS $device ${aid[i]} $demuxer $cache -vo null -frames 1 -identify 2>/dev/null | grep '^ID_AUDIO_CODEC' | tail -n 1 | awk -F= '{print $2}')
			case "${AUDCODEC[i]}" in
				*a52*|*ac3*)	audiocodec[i]="ffac3"; detectaud[i]="AC-3" ;;
				*eac3*)		audiocodec[i]="ffeac3"; detectaud[i]="E-AC-3" ;;
				*truehd*)	audiocodec[i]="fftruehd"; detectaud[i]="Dolby TrueHD" ;;
				*dca*|*dts*)	audiocodec[i]="ffdts"; detectaud[i]="DTS" ;;
				*vorbis*)	audiocodec[i]="ffvorbis"; detectaud[i]="Vorbis" ;;
				*opus*)		audiocodec[i]="ffopus"; detectaud[i]="Opus" ;;
				*pcm*)		audiocodec[i]="ffpcm"; detectaud[i]="PCM" ;;
				*faad*|*aac*)	audiocodec[i]="ffaac"; detectaud[i]="AAC" ;;
				*mp3*|*mad*)	audiocodec[i]="ffmp3"; detectaud[i]="MP3" ;;
				*flac*)		audiocodec[i]="ffflac"; detectaud[i]="FLAC" ;;
				*wma*)		audiocodec[i]="unsupported"; detectaud[i]="WMA" ;;
				*dvdpcm*)	audiocodec[i]="unsupported"; detectaud[i]="LPCM" ;;
				*|"")		audiocodec[i]="unsupported"; detectaud[i]="unknown/unsupported" ;;
			esac
			green "-> Track $i: Detected ${detectaud[i]} audio"
			if [ "${audiocodec[i]}" = "unsupported" ]; then
				error "-> Skipping unsupported track $i for the MKV/MP4/TS/OGM containers"
			fi
			;;
		esac
		
		case "${audiocodec[i]}" in
			mp3|lavcac3|aac|"")
			case "${audiocodec[i]}" in
				mp3)		audext[i]="mp3" ;;
				lavcac3)	audext[i]="ac3" ;;
				aac|"")		audext[i]="aac" ;;
			esac
			MENC[i]="$MENCODER \"$sourcetype\" $device $chapters $demuxer $cache ${aid[i]} ${channels[i]} $fps $ofps ${acodec[i]} ${audiofilters[i]} $vidfilteropts $vidcodecopts -of rawaudio -o \"$TEMPDIR/audio$i.${audext[i]}\""
			;;
			ff*)
			# Stream copy so we just dump the audio
			if [ "${audiocodec[i]}" = "ffaac" ]; then
				audformat[i]="-fafmttag 0x706d"
			fi
			case "${audiocodec[i]}" in
				ffac3|ffeac3|fftruehd)	audext[i]="ac3" ;;
				ffdts)			audext[i]="dts" ;;
				ffvorbis)		audext[i]="ogg" ;;
				ffopus)			audext[i]="opus" ;;
				ffpcm)			audext[i]="wav" ;;
				ffaac)			audext[i]="aac" ;;
				ffmp3)			audext[i]="mp3" ;;
				ffflac)			audext[i]="flac" ;;
			esac
			case "${audiocodec[i]}" in
				fftruehd)
				MENC[i]="$MPLAYER \"$sourcetype\" $MPLAYEROPTS $device $demuxer $cache ${aid[i]} -vo null -vc dummy -dumpaudio -dumpfile \"$TEMPDIR/audio$i.${audext[i]}\""
				;;
				*)
				MENC[i]="$MENCODER \"$sourcetype\" $device $chapters $demuxer $cache ${aid[i]} $fps $ofps $vidcodecopts $vidfilteropts ${audformat[i]} -oac copy -mc 0 -noskip -msglevel demuxer=-1 -of rawaudio -o \"$TEMPDIR/audio$i.${audext[i]}\""
				;;
			esac
			;;
			aac+|neroaac|fdkaac|aftenac3|vorbis|opus|flac|dts|pcm)
			MENC[i]="$MENCODER \"$sourcetype\" $device $chapters $demuxer $cache ${aid[i]} ${channels[i]} $fps $ofps $vidcodecopts $vidfilteropts -oac pcm -o \"$TEMPDIR/audio$i.avi\""
			;;
			eac3)
			if [ "$i" = "1" ]; then
				MENCINPUT="$OUTPUT"
				mencfilters="-ovc copy"
			else
				MENCINPUT="$sourcetype"
				mencfilters="$fps $ofps $vidcodecopts $vidfilteropts"
			fi
			MENC[i]="$MENCODER \"$MENCINPUT\" $device $chapters $demuxer $cache ${aid[i]} ${channels[i]} $mencfilters ${audflt[i]} -oac lavc -lavcopts acodec=eac3:abitrate=${abitrate[i]} -mc 0 -noskip -of rawaudio -o \"$TEMPDIR/audio$i.eac3\""
			;;
		esac
		
		audio_encoder_func() {
			case "${audiocodec[i]}" in
				fftruehd|eac3)
				echo "${MENC[i]}"
				echo "sleep 2"
				echo
				;;
				mp3|pcm|lavcac3|ff*|aac|"")
				if [ "$i" != "1" ]; then
					echo "${MENC[i]}"
					echo "sleep 2"
				fi
				;;
				aac+|neroaac|fdkaac|aftenac3|vorbis|opus|flac|dts)
				echo "$FIFO"
				if [ "$i" != "1" ]; then
					echo "${MENC[i]}"
					echo "sleep 2"
					echo
				fi
				case "${audiocodec[i]}" in
					aac+)		echo "${AACPLUS[i]}" ;;
					neroaac)	echo "${NERO[i]}" ;;
					fdkaac)		echo "${FDKAAC[i]}" ;;
					aftenac3)	echo "${AFTENENC[i]}" ;;
					vorbis)		echo "${OGG[i]}" ;;
					opus)		echo "${OPUS[i]}" ;;
					flac)		echo "${FLACENC[i]}" ;;
					dts)		echo "${DTSENC[i]}" ;;
				esac
				echo "${MPL[i]}"
				if [ "${nero2p[i]}" = "y" ]; then
					echo "sleep 2"
					echo "${MPL[i]}"
				fi
				echo "sleep 2"
				;;
			esac
			echo
		}
		
		audio_encoder_func >> "${AUDIOENC[i]}"
		if [ "$saveopts" = "y" ]; then
			audio_encoder_func >> "$OPTSFILE"
		fi
	fi
done
test ! -z "${detectaud[*]}" && echo


# Get audio channels info
# Used for audio tagging
for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
	if [ "${TRACKID[i]}" = "yes" ]; then
		if [ ! -z "${channels[i]}" -a ! -z "${chanfilter[i]}" ]; then
			case "$(echo "${chanfilter[i]}" | sed 's|channels=||; s|,||')" in
				1) 	chaninfo[i]="Mono" ;;
				2)	chaninfo[i]="Stereo" ;;
				3) 	chaninfo[i]="3.0" ;;
				4) 	chaninfo[i]="4.0" ;;
				5) 	chaninfo[i]="5.0" ;;
				6) 	chaninfo[i]="5.1" ;;
				7) 	chaninfo[i]="6.1" ;;
				8)	chaninfo[i]="7.1" ;;
			esac
		elif [ ! -z "${channels[i]}" -a -z "${chanfilter[i]}" ]; then
			case "$(echo "${channels[i]}" | awk '{print $2}')" in
				1)	chaninfo[i]="Mono" ;;
				2)	chaninfo[i]="Stereo" ;;
				3)	chaninfo[i]="3.0" ;;
				4)	chaninfo[i]="4.0" ;;
				5)	chaninfo[i]="5.0" ;;
				6)	chaninfo[i]="5.1" ;;
				7)	chaninfo[i]="6.1" ;;
				8)	chaninfo[i]="7.1" ;;
			esac
		else
			case "${audiocodec[i]}" in
				ff*)	chans[i]="-channels 8" ;;
			esac
			AUDCH[i]="$($MPLAYER "$sourcetype" $MPLAYEROPTS $MPOPTS ${aid[i]} ${chans[i]} $demuxer $cache 2>/dev/null | grep '^ID_AUDIO_NCH' | tail -n 1 | awk -F= '{print $2}')"
			case "${AUDCH[i]}" in
				1)	chaninfo[i]="Mono" ;;
				2)	chaninfo[i]="Stereo" ;;
				3)	chaninfo[i]="3.0" ;;
				4)	chaninfo[i]="4.0" ;;
				5)	chaninfo[i]="5.0" ;;
				6)	chaninfo[i]="5.1" ;;
				7)	chaninfo[i]="6.1" ;;
				8)	chaninfo[i]="7.1" ;;
				*|"")	chaninfo[i]="Stereo" ;;
			esac
		fi
	fi
done

# Ask user if he wants to convert
# from AVI to Matroska container.
if [ "$ALLOW_MKV_MUXING" = "y" ]; then
	case "${audiocodec[1]}" in
		ff*|mp3|aac|aac+|neroaac|fdkaac|vorbis|opus|aftenac3|lavcac3|eac3|dts|pcm|flac|nosound|"")
		avi_mkv=$(get_selection_func "Would you like to convert the final encode from AVI to MKV? [y/N]: ")
		if [ "$avi_mkv" = "y" ]; then
			# Check for mkvmerge
			if [ ! -x "$MKVMERGE" ]; then
				avi_to_mkv=no
				echo
				error "-> Utility 'mkvmerge' is missing!"
				error "-> Skipping AVI to MKV conversion!"
				echo
			else
				avi_to_mkv=yes
				
				# Import of external subtitles.
				# Input type agnostic. Only
				# allow supported subtitle formats
				# by MKV. Others will be skipped
				for i in $(eval echo "{1..$MAX_AMOUNT_EXT_SUBS}"); do
					if [ ! -z "${EXTSUB[i]}" ]; then
						case "$(echo "${EXTSUB[i]##*.}" | tr '[:upper:]' '[:lower:]')" in
							idx|srt|ass|ssa|sup|mks)
							MKVSUBS[i]="--language -1:${SUBLANG[i]} \"${EXTSUB[i]}\""
							;;
							*)
							echo
							error "-> Subtitle format '$(echo "${EXTSUB[i]##*.}" | tr '[:lower:]' '[:upper:]')' not supported by MKV!"
							error "-> Supported subtitle formats are: IDX, SRT, ASS/SSA, SUP, MKS"
							error "-> Skipping import of '${EXTSUB[i]}'"
							echo
							;;
						esac
					fi
				done
				
				case "$source" in
					file|dvd|bd|vcd)
					# Set MKV title
					MKVTITLE="--title \"$(basename "${OUTPUT%.*}")\""
					TRACKTITLE="--track-name 0:\"$(basename "${OUTPUT%.*}")\""
					printf "Specify the Release Year of the content [press 'Enter' to skip]: "
					read mkvyear
					printf "Specify a Genre for the content [press 'Enter' to skip]: "
					read mkvgenre
					# Add cover
					printf "Provide a Cover file in jpeg/png format [press 'Enter' to skip]: "
					read -e mkvcover
					if [ ! -z "$mkvcover" ]; then
						if [ ! -f "$mkvcover" ]; then
							echo
							error "-> No such file: '$mkvcover'"
							error "-> Skipping embedding of cover file"
							echo
						else
							IMGTYPE="$(basename "${mkvcover##*.}" | tr '[:upper:]' '[:lower:]')"
							case "$IMGTYPE" in
								jpg|jpeg|png)
								MKVCOVER="--attachment-mime-type image/$(echo $IMGTYPE | sed 's|jpg|jpeg|') --attachment-name Cover --attach-file \"$mkvcover\""
								;;
								*)
								echo
								error "-> Image type not supported"
								error "-> Supported formats are: jpeg, png"
								error "-> Skipping embedding of cover image"
								echo
								;;
							esac
						fi
					fi
					
					# Audio language
					case "$source" in
						dvd|bd|file)
						case "${audiocodec[1]}" in
							aac+|neroaac|fdkaac|aftenac3|eac3|vorbis|opus|flac|fftruehd)	MKVAUDLANG1="--language 0:${AUDLANG[1]}" ;;
							*|"")								MKVAUDLANG1="--language 1:${AUDLANG[1]}" ;;
						esac
						for i in $(eval echo "{2..$MAX_AMOUNT_AUD_TRACKS}"); do
							if [ "${TRACKID[i]}" = "yes" ]; then
								MKVAUDLANG[i]="--language -1:${AUDLANG[i]}"
							fi
						done
						;;
					esac
						
					case "$source" in
						dvd)
						# Chapters for MKV
						if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
							mkvimpchap=$(get_selection_func "Import chapters information into the MKV container? [y/N]: ")
							if [ "$mkvimpchap" = "y" ]; then
								MKVCHAPS="--chapters \"$CHAPTERSFILE\""
							fi
						fi
						# DVD subs for MKV
						if [ ! -z "${vobsubout[*]}" ]; then
							mkvimpsub=$(get_selection_func "Import the ripped subtitle(s) into the MKV container? [y/N]: ")
							if [ "$mkvimpsub" = "y" ]; then
								for i in $(eval echo "{1..$MAX_AMOUNT_SUBS}"); do
									if [ ! -z "${IDXFILE[i]}" ]; then
										MKVSUBS[i]="\"${IDXFILE[i]}\""
									fi
								done
							fi
						fi
						;;
						file|bd)
						if [ ! -z "$MKVCHAPFILE" ]; then
							mkvimpchaps=$(get_selection_func "Import the extracted Chapters File? [y/N]: ")
							if [ "$mkvimpchaps" = "y" ]; then
								MKVCHAPS="--chapters \"$MKVCHAPFILE\""
							fi
						else
							printf "Provide a Chapters file [press 'Enter' to skip]: "
							read -e mkvchapsfile
							if [ ! -z "$mkvchapsfile" ]; then
								if [ ! -f "$mkvchapsfile" ]; then
									echo
									error "-> No such file: '$mkvchapsfile'"
									error "-> Skipping chapters file import"
									echo
								else
									MKVCHAPS="--chapters \"$mkvchapsfile\""
								fi
							fi
						fi
						;;
					esac
					;;
					dir)
					MKVTITLE="--title \"\${i%.*}\""
					TRACKTITLE="--track-name 0:\"\${i%.*}\""
					;;
				esac
				
				if [ "$DISABLE_MKV_GLOBAL_TAGS" = "n" ]; then
					# Global tags
					mkvtags_func() {
						echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
						echo "<!DOCTYPE Tags SYSTEM \"matroskatags.dtd\">"
						echo "<Tags>"
						echo "  <Tag>"
						echo "    <Simple>"
						echo "      <Name>Source</Name>"
						echo "      <String>$(echo $type | sed 's|s$||')</String>"
						echo "    </Simple>"
						echo "    <Simple>"
						echo "      <Name>Title</Name>"
						case "$source" in
							dir)	echo "      <String>\$(echo \${i%.*} | sed 's|&|&amp;|g; s|<|&lt;|g; s|>|&gt;|g; s|\"|\&quote;|g')</String>" ;;
							*)	echo "      <String>$(echo "$(basename "${OUTPUT%.*}")" | sed 's|&|&amp;|g; s|<|&lt;|g; s|>|&gt;|g; s|\"|\&quote;|g')</String>" ;;
						esac
						echo "    </Simple>"
						if [ ! -z "$mkvyear" ]; then
							echo "    <Simple>"
							echo "      <Name>Release Date</Name>"
							echo "      <String>$mkvyear</String>"
							echo "    </Simple>"
						fi
						if [ ! -z "$mkvgenre" ]; then
							echo "    <Simple>"
							echo "      <Name>Genre</Name>"
							echo "      <String>$mkvgenre</String>"
							echo "    </Simple>"
						fi
						echo "    <Simple>"
						echo "      <Name>Video Filters</Name>"
						echo "      <String>$(echo $videofilters | sed 's|^\-vf ||')</String>"
						echo "    </Simple>"
						for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
							if [ "${TRACKID[i]}" = "yes" ]; then
								if [ "${audiocodec[i]}" != "nosound" ]; then
									echo "    <Simple>"
									echo "      <Name>Audio Codec (Track $i)</Name>"
									case "${audiocodec[i]}" in
										aac|"")				echo "      <String>LC-AAC ${chaninfo[i]}</String>" ;;
										ffaac)				echo "      <String>AAC ${chaninfo[i]}</String>" ;;
										neroaac|fdkaac)			echo "      <String>${AACTYPE[i]} ${chaninfo[i]}</String>" ;;
										aac+)				echo "      <String>HE-AACv1 ${chaninfo[i]}</String>" ;;
										vorbis|ffvorbis)		echo "      <String>Vorbis ${chaninfo[i]}</String>" ;;
										opus|ffopus)			echo "      <String>Opus ${chaninfo[i]}</String>" ;;
										mp3|ffmp3)			echo "      <String>MP3</String>" ;;
										aftenac3|lavcac3|ffac3)		echo "      <String>AC-3 ${chaninfo[i]}</String>" ;;
										eac3)				echo "      <String>E-AC-3 ${chaninfo[i]}</String>" ;;
										fftruehd)			echo "      <String>Dolby TrueHD ${chaninfo[i]}</String>" ;;
										dts|ffdts)			echo "      <String>DTS ${chaninfo[i]}</String>" ;;
										flac|ffflac)			echo "      <String>FLAC ${chaninfo[i]}</String>" ;;
										pcm|ffpcm)			echo "      <String>PCM ${chaninfo[i]}</String>" ;;
										*)				echo "      <String>${detectaud[i]} ${chaninfo[i]}</String>" ;;
									esac
									echo "    </Simple>"
									case "$source" in
										dvd|bd|file)
										echo "    <Simple>"
										echo "      <Name>Audio Language (Track $i)</Name>"
										echo "      <String>${AUDLANG[i]}</String>"
										echo "    </Simple>"
										;;
									esac
									if [ ! -z "${audiofilters[i]}" ]; then
										echo "    <Simple>"
										echo "      <Name>Audio Filters (Track $i)</Name>"
										echo "      <String>$(echo ${audiofilters[i]} | sed 's|^\-af ||; s| \-srate.*||')</String>"
										echo "    </Simple>"
									fi
									echo "    <Simple>"
									echo "      <Name>Audio Encoder (Track $i)</Name>"
									case "${audiocodec[i]}" in
										aac|"")		echo "      <String>faac</String>" ;;
										neroaac)	echo "      <String>neroAacEnc</String>" ;;
										fdkaac)		echo "      <String>aac-enc (fdkaac)</String>" ;;
										aac+)		echo "      <String>aacplusenc</String>" ;;
										vorbis)		echo "      <String>oggenc</String>" ;;
										opus)		echo "      <String>opusenc</String>" ;;
										mp3)		echo "      <String>lame</String>" ;;
										aftenac3)	echo "      <String>aften</String>" ;;
										lavcac3|eac3)	echo "      <String>lavc</String>" ;;
										dts)		echo "      <String>dcaenc</String>" ;;
										flac)		echo "      <String>flac</String>" ;;
										pcm)		echo "      <String>MEncoder</String>" ;;
										ff*)		echo "      <String>Unknown (Stream Copy)</String>" ;;
									esac
									echo "    </Simple>"
								fi
							fi
						done
						for i in $(eval echo "{1..$MAX_AMOUNT_SUBS}"); do
							if [ ! -z  "${SUBLANG[i]}" ]; then
								echo "     <Simple>"
								echo "       <Name>Subtitle Language (Sub $i)</Name>"
								echo "       <String>${SUBLANG[i]}</String>"
								echo "     </Simple>"
							fi
						done
						echo "    <Simple>"
						echo "      <Name>Encoder</Name>"
						echo "      <String>$($MENCODER 2>/dev/null | head -n 1)</String>"
						echo "    </Simple>"
						echo "    <Simple>"
						echo "      <Name>x264 parameters</Name>"
						echo "      <String>$(mencoder_opts_func $1 | tail -n 1 | grep -o '\-x264encopts.*' | sed 's|\-x264encopts ||; s| ||g; s|2>/dev/null||')</String>"
						echo "    </Simple>"
						echo "    <Simple>"
						echo "      <Name>x264 version</Name>"
						echo "      <String>$($X264 --version | head -n 1 | awk '{print $2}')</String>"
						echo "    </Simple>"
						echo "    <Simple>"
						echo "      <Name>mkvmerge version</Name>"
						echo "      <String>$($MKVMERGE --version | awk '{print $2}' | sed 's|v||')</String>"
						echo "    </Simple>"
						echo "    <Simple>"
						echo "      <Name>h264enc parameters</Name>"
						echo "      <String>h264enc $@</String>"
						echo "    </Simple>"
						echo "    <Simple>"
						echo "      <Name>Comment</Name>"
						echo "      <String>Tagged by h264enc $version on $(date +%Y/%m/%d)</String>"
						echo "    </Simple>"
						echo "  </Tag>"
						echo "</Tags>"
					}
					MKVTAGS="--global-tags \"$TEMPDIR/mkvtags.xml\""
					case "$source" in
						dir)
						DIRTAGS="echo \"$(mkvtags_func $@ | sed 's|\"|\\"|g')\" > \"$TEMPDIR/mkvtags.xml\""
						;;
						*)
						mkvtags_func $@ > "$TEMPDIR/mkvtags.xml"
						;;
					esac
				fi
				
				if [ "$DISABLE_MKV_STATISTICS_TAGS" = "y" ]; then
					MKVMERGE_VER="$($MKVMERGE --version | awk '{print $2}' | sed 's|v||; s|\.||g')"
					if [ "$MKVMERGE_VER" -ge "700" ]; then
						NO_MKV_STATS_TAGS="--disable-track-statistics-tags"
					fi
				fi
				
				# MKV audio & tagging for track 1
				case "${audiocodec[1]}" in
					aac+)
					MKVAUD="--track-name 0:\"HE-AACv1 ${chaninfo[1]}\" $MKVAUDLANG1 --aac-is-sbr 0:1 \"$TEMPDIR/audio1.aac\""
					;;
					neroaac|fdkaac)
					case "${AACTYPE[1]}" in
						HE-AACv1|HE-AACv2) MKVSBR="--aac-is-sbr 0:1" ;;
					esac
					MKVAUD="--track-name 0:\"${AACTYPE[1]} ${chaninfo[1]}\" $MKVAUDLANG1 $MKVSBR --no-chapters \"$TEMPDIR/audio1.aac\""
					;;
					vorbis)
					MKVAUD="--track-name 0:\"Vorbis ${chaninfo[1]}\" $MKVAUDLANG1 \"$TEMPDIR/audio1.ogg\""
					;;
					opus)
					MKVAUD="--track-name 0:\"Opus ${chaninfo[1]}\" $MKVAUDLANG1 \"$TEMPDIR/audio1.opus\""
					;;
					flac)
					MKVAUD="--track-name 0:\"FLAC ${chaninfo[1]}\" $MKVAUDLANG1 \"$TEMPDIR/audio1.flac\""
					;;
					fftruehd)
					MKVAUD="--track-name 0:\"Dolby TrueHD ${chaninfo[1]}\" $MKVAUDLANG1 \"$TEMPDIR/audio1.ac3\""
					TRACKNAME="$TRACKTITLE"
					;;
					ff*)
					# Stream copy
					TRACKNAME="$TRACKTITLE $MKVAUDLANG1 --track-name 1:\"${detectaud[1]} ${chaninfo[1]}\""
					;;
					aac|"")
					#MKVAUD="--track-name 0:\"LC-AAC ${chaninfo[1]}\" $MKVAUDLANG1 \"$TEMPDIR/audio1.aac\""
					TRACKNAME="$TRACKTITLE --track-name 1:\"LC-AAC ${chaninfo[1]}\" $MKVAUDLANG1"
					;;
					eac3)
					MKVAUD="--track-name 0:\"E-AC-3 ${chaninfo[1]}\" $MKVAUDLANG1 \"$TEMPDIR/audio1.eac3\""
					;;
					aftenac3)
					MKVAUD="--track-name 0:\"AC-3 ${chaninfo[1]}\" $MKVAUDLANG1 \"$TEMPDIR/audio1.ac3\""
					;;
					lavcac3)
					TRACKNAME="$TRACKTITLE --track-name 1:\"AC-3 ${chaninfo[1]}\" $MKVAUDLANG1"
					;;
					mp3)
					TRACKNAME="$TRACKTITLE --track-name 1:\"MP3\" $MKVAUDLANG1"
					;;
					pcm)
					TRACKNAME="$TRACKTITLE --track-name 1:\"PCM ${chaninfo[1]}\" $MKVAUDLANG1"
					;;
					dts)
					MKVAUD="--track-name 0:\"DTS ${chaninfo[1]}\" $MKVAUDLANG1 \"$TEMPDIR/audio1.dts\""
					;;
				esac
				
				case "${audiocodec[1]}" in
					aac+|neroaac|fdkaac|vorbis|opus|flac|aftenac3|eac3|dts)
					NOAUDIO="-A"
					TRACKNAME="$TRACKTITLE"
					;;
				esac
				
				# MKV audio & tagging for subsequent tracks
				for i in $(eval echo "{2..$MAX_AMOUNT_AUD_TRACKS}"); do
					if [ "${TRACKID[i]}" = "yes" ]; then
						case "${audiocodec[i]}" in
							ff*)
							# Stream copy
							if [ "${audiocodec[i]}" = "ffmp3" ]; then
								audinfo[i]="${detectaud[i]}"
							else
								audinfo[i]="${detectaud[i]} ${chaninfo[i]}"
							fi
							MKVAUD[i]="--track-name -1:\"${audinfo[i]}\" ${MKVAUDLANG[i]} \"$TEMPDIR/audio$i.${audext[i]}\""
							;;
							mp3)
							MKVAUD[i]="--track-name -1:\"MP3\" ${MKVAUDLANG[i]} \"$TEMPDIR/audio$i.mp3\""
							;;
							aac+)
							MKVAUD[i]="--track-name -1:\"HE-AACv1 ${chaninfo[i]}\" ${MKVAUDLANG[i]} --aac-is-sbr 0:1 \"$TEMPDIR/audio$i.aac\""
							;;
							neroaac|fdkaac)
							case "${AACTYPE[i]}" in
								HE-AACv1|HE-AACv2) MKVSBR[i]="--aac-is-sbr 0:1" ;;
							esac
							MKVAUD[i]="--track-name -1:\"${AACTYPE[i]} ${chaninfo[i]}\" ${MKVAUDLANG[i]} ${MKVSBR[i]} --no-chapters \"$TEMPDIR/audio$i.aac\""
							;;
							aac|"")
							MKVAUD[i]="--track-name -1:\"LC-AAC ${chaninfo[i]}\" ${MKVAUDLANG[i]} \"$TEMPDIR/audio$i.aac\""
							;;
							aftenac3)
							MKVAUD[i]="--track-name -1:\"AC-3 ${chaninfo[i]}\" ${MKVAUDLANG[i]} \"$TEMPDIR/audio$i.ac3\""
							;;
							lavcac3)
							MKVAUD[i]="--track-name -1:\"AC-3 ${chaninfo[i]}\" ${MKVAUDLANG[i]} \"$TEMPDIR/audio$i.ac3\""
							;;
							eac3)
							MKVAUD[i]="--track-name -1:\"E-AC-3 ${chaninfo[i]}\" ${MKVAUDLANG[i]} \"$TEMPDIR/audio$i.eac3\""
							;;
							vorbis)
							MKVAUD[i]="--track-name -1:\"Vorbis ${chaninfo[i]}\" ${MKVAUDLANG[i]} \"$TEMPDIR/audio$i.ogg\""
							;;
							opus)
							MKVAUD[i]="--track-name -1:\"Opus ${chaninfo[i]}\" ${MKVAUDLANG[i]} \"$TEMPDIR/audio$i.opus\""
							;;
							flac)
							MKVAUD[i]="--track-name -1:\"FLAC ${chaninfo[i]}\" ${MKVAUDLANG[i]} \"$TEMPDIR/audio$i.flac\""
							;;
							dts)
							MKVAUD[i]="--track-name -1:\"DTS ${chaninfo[i]}\" ${MKVAUDLANG[i]} \"$TEMPDIR/audio$i.dts\""
							;;
							pcm)
							MKVAUD[i]="-D --track-name -1:\"PCM ${chaninfo[i]}\" ${MKVAUDLANG[i]} \"$TEMPDIR/audio$i.avi\""
							;;
						esac
					fi
				done
				
				# Export commands to files
				case "$source" in
					dir)
					MKVOUT="$OUTPUTDIR/\${i%.*}.mkv"
					MKVMUXING="$BATCH"
					;;
					*)
					MKVOUT="${OUTPUT%.*}.mkv"
					MKVMUXING="$TEMPDIR/mkvmuxing"
					;;
				esac
				test ! -z "$DIRTAGS" && echo "$DIRTAGS" >> "$MKVMUXING"
				mkv_export_func() {
					echo
					echo "test -e \"$MKVOUT\" && mv -f \"$MKVOUT\" \"$MKVOUT.old\""
					case "$1" in
						dumpchaps)
						if [ "$mkvimpchaps" = "y" ]; then
							echo
							echo "$MKVEXTRACT chapters \"$infile\" > \"$MKVCHAPFILE\" 2>/dev/null"
						fi
						;;
					esac
					echo
					echo "$MKVMERGE $NO_MKV_STATS_TAGS $MKVCOVER $MKVTAGS $NOAUDIO $MKVTITLE $TRACKNAME \"$OUTPUT\" ${MKVAUD[*]} ${MKVSUBS[*]} $MKVCHAPS -o \"$MKVOUT\""
					echo "sleep 2"
					echo
				}
				mkv_export_func >> "$MKVMUXING"
				if [ "$saveopts" = "y" ]; then
					echo >> "$OPTSFILE"
					echo "####################### MKV Muxing #######################" >> "$OPTSFILE"
					echo >> "$OPTSFILE"
					if [ "$DISABLE_MKV_GLOBAL_TAGS" = "n" ]; then
						echo "echo \"$(mkvtags_func $@ | sed 's|\"|\\"|g')\" > \"$TEMPDIR/mkvtags.xml\"" >> "$OPTSFILE"
					fi
					mkv_export_func dumpchaps >> "$OPTSFILE"
				fi
			fi
		else
			avi_to_mkv=no
		fi
		;;
		*|"")
		avi_to_mkv=no
		;;
	esac
else
	avi_to_mkv=no
fi

# Ask for AVI -> MP4 conversion
if [ "$ALLOW_MP4_MUXING" = "y" ]; then
	case "${audiocodec[1]}" in
		ffmp3|ffaac|ffac3|ffvorbis|mp3|aac|aac+|neroaac|fdkaac|aftenac3|lavcac3|vorbis|nosound|"")
		avi_mp4=$(get_selection_func "Would you like to convert the final encode from AVI to MP4? [y/N]: ")
		if [ "$avi_mp4" = "y" ]; then
			if [ ! -x "$MP4BOX" ]; then
				avi_to_mp4=no
				echo
				error "-> MP4Box (from gpac) is missing!"
				error "-> Skipping AVI to MP4 conversion!"
				echo
			else
				avi_to_mp4=yes
				
				# Global variables
				MP4FPS="$MPLAYER \"$OUTPUT\" $MPLAYEROPTS $MPOPTS 2>/dev/null | grep '^ID_VIDEO_FPS' | tail -n 1 | awk -F= '{print \$2}' > \"$TEMPDIR/mp4fps\""
				MP4VID="$MENCODER \"$OUTPUT\" -nosound -ovc copy -of rawvideo -o \"$TEMPDIR/h264_video.h264\""
				VIDEOINPUT="-add \"$TEMPDIR/h264_video.h264\""
				RMMP4VID="rm -f \"$TEMPDIR/h264_video.h264\""
				case "$3" in
					ipc|ipchq|ip|iphq|iph|iphhq)
					MP4DEVOPTS="-ipod"
					;;
					psp|psphq)
					if [ ! -z "$($MP4BOX -h general | grep '\-psp')" ]; then
						MP4DEVOPTS="-psp"
					fi
					;;
				esac
				
				# Import of external subtitles.
				# Input type agnostic. Only
				# allow supported subtitle formats
				# by MP4. Others will be skipped
				for i in $(eval echo "{1..$MAX_AMOUNT_EXT_SUBS}"); do
					if [ ! -z "${EXTSUB[i]}" ]; then
						case "$(echo "${EXTSUB[i]##*.}" | tr '[:upper:]' '[:lower:]')" in
							idx|srt|ttxt)
							MP4SUBS[i]="-add \"${EXTSUB[i]}\":lang=${SUBLANG[i]}"
							;;
							*)
							echo
							error "-> Subtitle format '$(echo "${EXTSUB[i]##*.}" | tr '[:lower:]' '[:upper:]')' not supported by MP4!"
							error "-> Supported subtitle formats are: IDX, SRT, TTXT"
							error "-> Skipping import of '${EXTSUB[i]}'"
							echo
							;;
						esac
					fi
				done
				
				# Add cover/chaps/DVD subs
				case "$source" in
					file|dvd|bd|vcd)
					# Year - a bit misleading
					# since created could also
					# mean when the file was
					# encoded
					printf "Specify the Release Year of the content [press 'Enter' to skip]: "
					read mp4year
					if [ ! -z "$mp4year" ]; then
						MP4YEAR=":created=\"$mp4year\""
					fi
					# Genre
					printf "Specify a Genre for the content [press 'Enter' to skip]: "
					read mp4genre
					if [ ! -z "$mp4genre" ]; then
						MP4GENRE=":genre=\"$mp4genre\""
					fi
					# Cover
					printf "Provide a Cover file in jpeg/png format [press 'Enter' to skip]: "
					read -e mp4cover
					if [ ! -z "$mp4cover" ]; then
						if [ ! -f "$mp4cover" ]; then
							echo
							error "-> No such file: '$mp4cover'"
							error "-> Skipping embedding of cover file"
							echo
						else
							case "$(basename "${mp4cover##*.}" | tr '[:upper:]' '[:lower:]')" in
								jpg|jpeg|png)
								MP4COVER=":cover=\"$mp4cover\""
								;;
								*)
								echo
								error "-> Image type not supported"
								error "-> Supported formats are: jpeg, png"
								error "-> Skipping embedding of cover image"
								echo
								;;
							esac
						fi
					fi
					
					# Audio language info
					case "$source" in
						dvd|bd|file)
						for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
							if [ "${TRACKID[i]}" = "yes" ]; then
								MP4AUDLANG[i]=":lang=${AUDLANG[i]}"
							fi
						done
						;;
					esac
						
					case "$source" in
						dvd)
						# Chapters for MP4
						if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
							mp4impchap=$(get_selection_func "Import chapters information into the MP4 container? [y/N]: ")
							if [ "$mp4impchap" = "y" ]; then
								MP4CHAPS="-chap \"$CHAPTERSFILE\""
							fi
						fi
						# DVD subs for MP4
						if [ ! -z "${vobsubout[*]}" ]; then
							mp4impsub=$(get_selection_func "Import the ripped subtitle(s) into the MP4 container? [y/N]: ")
							if [ "$mp4impsub" = "y" ]; then
								for i in $(eval echo "{1..$MAX_AMOUNT_SUBS}"); do
									if [ ! -z "${IDXFILE[i]}" ]; then
										MP4SUBS[i]="-add \"${IDXFILE[i]}\""
									fi
								done
							fi
						fi
						;;
						file|bd)
						if [ ! -z "$MP4CHAPFILE" ]; then
							mp4impchaps=$(get_selection_func "Import the dumped Chapters File? [y/N]: ")
							if [ "$mp4impchaps" = "y" ]; then
								MP4CHAPS="-chap \"$MP4CHAPFILE\""
							fi
						else
							printf "Provide a Chapters file [press 'Enter' to skip]: "
							read -e mp4chapsfile
							if [ ! -z "$mp4chapsfile" ]; then
								if [ ! -f "$mp4chapsfile" ]; then
									echo
									error "-> No such file: '$mp4chapsfile'"
									error "-> Skipping chapters file import"
									echo
								else
									MP4CHAPS="-chap \"$mp4chapsfile\""
								fi
							fi
						fi
						;;
					esac
					;;
				esac
				
				# MP4 hinting
				mp4hint=$(get_selection_func "Hint the MP4 file for RTP/RTSP streaming sessions? [y/N]: ")
				if [ "$mp4hint" = "y" ]; then
					MP4HINT="-hint"
				fi
				
				# First audio track for MP4
				case "${audiocodec[1]}" in
					mp3|ffmp3)
					MP4AUD="$MP4BOX -aviraw audio \"$OUTPUT\" -out \"$TEMPDIR/mp3.mp3\""
					AUDIOINPUT="-add \"$TEMPDIR/mp3.mp3\"#audio:name=\"MP3\"${MP4AUDLANG[1]}"
					RMMP4AUD="rm -f \"$TEMPDIR/mp3.mp3\""
					;;
					ffaac)
					MP4AUD="$MP4BOX -aviraw audio \"$OUTPUT\" -out \"$TEMPDIR/aac.aac\""
					AUDIOINPUT="-add \"$TEMPDIR/aac.aac\"#audio:name=\"AAC ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					RMMP4AUD="rm -f \"$TEMPDIR/aac.aac\""
					;;
					ffac3)
					MP4AUD="$MP4BOX -aviraw audio \"$OUTPUT\" -out \"$TEMPDIR/ac3.ac3\""
					AUDIOINPUT="-add \"$TEMPDIR/ac3.ac3\"#audio:name=\"AC-3 ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					RMMP4AUD="rm -f \"$TEMPDIR/ac3.ac3\""
					;;
					ffvorbis)
					MP4AUD="$MP4BOX -aviraw audio \"$OUTPUT\" -out \"$TEMPDIR/vorbis.ogg\""
					AUDIOINPUT="-add \"$TEMPDIR/vorbis.ogg\"#audio:name=\"Vorbis ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					;;
					aac+)
					AUDIOINPUT="-add \"$TEMPDIR/audio1.aac\"#audio:sbr:name=\"HE-AACv1 Stereo\"${MP4AUDLANG[1]}"
					RMMP4AUD="rm -f \"$TEMPDIR/audio1.aac\""
					;;
					neroaac|fdkaac)
					RMMP4AUD="rm -f \"$TEMPDIR/audio1.aac\""
					case "${AACTYPE[1]}" in
						HE-AACv1|HE-AACv2) AACSBR=":sbr" ;;
					esac
					AUDIOINPUT="-add \"$TEMPDIR/audio1.aac\"#audio:name=\"${AACTYPE[1]} ${chaninfo[1]}\"$AACSBR${MP4AUDLANG[1]}"
					;;
					aac|"")
					#AUDIOINPUT="-add \"$TEMPDIR/audio1.aac\"#audio:name=\"LC-AAC ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					MP4AUD="$MP4BOX -aviraw audio \"$OUTPUT\" -out \"$TEMPDIR/aac.aac\""
					AUDIOINPUT="-add \"$TEMPDIR/aac.aac\"#audio:name=\"LC-AAC ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					RMMP4AUD="rm -f \"$TEMPDIR/aac.aac\""
					;;
					aftenac3)
					AUDIOINPUT="-add \"$TEMPDIR/audio1.ac3\"#audio:name=\"AC-3 ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					;;
					lavcac3)
					MP4AUD="$MP4BOX -aviraw audio \"$OUTPUT\" -out \"$TEMPDIR/ac3.ac3\""
					AUDIOINPUT="-add \"$TEMPDIR/ac3.ac3\"#audio:name=\"AC-3 ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					RMMP4AUD="rm -f \"$TEMPDIR/ac3.ac3\""
					;;
					vorbis)
					AUDIOINPUT="-add \"$TEMPDIR/audio1.ogg\"#audio:name=\"Vorbis ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					;;
				esac
				
				# Subsequent tracks
				for i in $(eval echo "{2..$MAX_AMOUNT_AUD_TRACKS}"); do
					if [ "${TRACKID[i]}" = "yes" ]; then
						case "${audiocodec[i]}" in
							ff*)
							# Stream copy
							if [ "${audiocodec[i]}" = "ffmp3" ]; then
								audinfo[i]="${detectaud[i]}"
							else
								audinfo[i]="${detectaud[i]} ${chaninfo[i]}"
							fi
							AUDIOINPUT[i]="-add \"$TEMPDIR/audio$i.${audext[i]}\"#audio:name=\"${audinfo[i]}\"${MP4AUDLANG[i]}"
							;;
							mp3)
							AUDIOINPUT[i]="-add \"$TEMPDIR/audio$i.mp3\"#audio:name=\"MP3\"${MP4AUDLANG[i]}"
							;;
							vorbis)
							AUDIOINPUT[i]="-add \"$TEMPDIR/audio$i.ogg\"#audio:name=\"Vorbis ${chaninfo[i]}\"${MP4AUDLANG[i]}"
							;;
							aftenac3|lavcac3)
							AUDIOINPUT[i]="-add \"$TEMPDIR/audio$i.ac3\"#audio:name=\"AC-3 ${chaninfo[i]}\"${MP4AUDLANG[i]}"
							;;
							aac+)
							AUDIOINPUT[i]="-add \"$TEMPDIR/audio$i.aac\"#audio:sbr:name=\"HE-AACv1 Stereo\"${MP4AUDLANG[i]}"
							;;
							aac|"")
							AUDIOINPUT[i]="-add \"$TEMPDIR/audio$i.aac\"#audio:name=\"LC-AAC ${chaninfo[i]}\"${MP4AUDLANG[i]}"
							;;
							neroaac|fdkaac)
							RMNEROAUD[i]="rm -f \"$TEMPDIR/audio$i.aac\""
							case "${AACTYPE[i]}" in
								HE-AACv1|HE-AACv2) AACSBR[i]=":sbr" ;;
							esac
							AUDIOINPUT[i]="-add \"$TEMPDIR/audio$i.aac\"#audio:name=\"${AACTYPE[i]} ${chaninfo[i]}\"${AACSBR[i]}${MP4AUDLANG[i]}"
							;;
						esac
					fi
				done
				
				# Export commands to files
				case "$source" in
					dir)
					MP4OUT="$OUTPUTDIR/\${i%.*}.mp4"
					MP4TAGS="-itags name=\"\${i%.*}\":comment=\"Tagged by h264enc $version on \$(date)\""
					MP4MUXING="$BATCH"
					;;
					*)
					MP4OUT="${OUTPUT%.*}.mp4"
					MP4TAGS="-itags name=\"$(basename "${OUTPUT%.*}")\"$MP4YEAR$MP4GENRE$MP4COVER:comment=\"Tagged by h264enc $version on \$(date)\""
					MP4MUXING="$TEMPDIR/mp4muxing"
					;;
				esac
				mp4_export_func() {
					echo "test -e \"$MP4OUT\" && mv -f \"$MP4OUT\" \"$MP4OUT.old\""
					echo
					echo "$MP4VID"
					echo "sleep 2"
					echo
					echo "$MP4AUD"
					echo
					echo "$MP4FPS"
					case "$1" in
						dumpchaps)
						if [ "$mp4impchaps" = "y" ]; then
							echo
							echo "$MP4BOX \"$infile\" -dump-chap -out \"$MP4CHAPFILE\" 2>/dev/null"
						fi
						;;
					esac
					echo
					echo "$MP4BOX -fps \$(cat \"$TEMPDIR/mp4fps\") -tmp \"$TEMPDIR\" $VIDEOINPUT $MP4HINT ${AUDIOINPUT[*]} $MP4TAGS ${MP4SUBS[*]} $MP4CHAPS $MP4DEVOPTS -mpeg4 -new \"$MP4OUT\""
					echo "sleep 2"
					echo
					echo "$RMMP4VID"
					echo
					echo "$RMMP4AUD"
					for trk in $(eval echo "{2..$MAX_AMOUNT_AUD_TRACKS}"); do
						test ! -z "${RMNEROAUD[trk]}" && echo "${RMNEROAUD[trk]}"
					done
					echo "sleep 2"
					echo
				}
				mp4_export_func >> "$MP4MUXING"
				if [ "$saveopts" = "y" ]; then
					echo >> "$OPTSFILE"
					echo "####################### MP4 Muxing #######################" >> "$OPTSFILE"
					echo >> "$OPTSFILE"
					mp4_export_func dumpchaps >> "$OPTSFILE"
				fi
			fi
		else
			avi_to_mp4=no
		fi
		;;
		*)
		avi_to_mp4=no
		;;
	esac
else
	avi_to_mp4=no
fi


# AVI -> TS/Blu-ray
if [ "$ALLOW_TS_MUXING" = "y" ]; then
	case "${audiocodec[1]}" in
		ffmp3|ffac3|ffeac3|ffdts|mp3|aac|neroaac|fdkaac|aftenac3|lavcac3|eac3|dts|nosound|"")
		case "$3" in
			bd40|bdhq40|bd41|bdhq41)	TSTYPE="Blu-ray" ;;
			avchd|avchdhq)			TSTYPE="AVCHD" ;;
			*)				TSTYPE="TS" ;;
		esac
		avi_ts=$(get_selection_func "Would you like to convert the final encode from AVI to $TSTYPE? [y/N]: ")
		if [ "$avi_ts" = "y" ]; then
			# Check for tsMuxeR
			if [ ! -x "$TSMUXER" ]; then
				avi_to_ts=no
				echo
				error "-> Utility 'tsMuxeR' is missing!"
				error "-> Skipping AVI to TS/Blu-ray/AVCHD conversion!"
				echo
			else
				avi_to_ts=yes
				
				# Global variables
				TSVID="$MENCODER \"$OUTPUT\" -nosound -ovc copy -of rawvideo -o \"$TEMPDIR/videots.h264\""
				TSFPS="$MPLAYER \"$OUTPUT\" $MPLAYEROPTS $MPOPTS 2>/dev/null | grep '^ID_VIDEO_FPS' | tail -n 1 | awk -F= '{print \$2}' > \"$TEMPDIR/tsfps\""
				
				case "$3" in
					bd40|bdhq40|bd41|bdhq41|avchd|avchdhq)
					case "$3" in
						avchd|avchdhq)	TSOPT="--avchd" ;;
						*)		TSOPT="--blu-ray" ;;
					esac
					METAOPT="echo \"MUXOPT --no-pcr-on-video-pid --new-audio-pes $TSOPT --auto-chapters=5 --vbr\" >> \"$TEMPDIR/tsmuxer.meta\""
					METAVID="echo \"V_MPEG4/ISO/AVC, \\\"$TEMPDIR/videots.h264\\\", fps=\$(cat \"$TEMPDIR/tsfps\")\" >> \"$TEMPDIR/tsmuxer.meta\""
					;;
					*)
					METAOPT="echo \"MUXOPT --no-pcr-on-video-pid --new-audio-pes --vbr\" >> \"$TEMPDIR/tsmuxer.meta\""
					METAVID="echo \"V_MPEG4/ISO/AVC, \\\"$TEMPDIR/videots.h264\\\", insertSEI, contSPS, fps=\$(cat \"$TEMPDIR/tsfps\")\" >> \"$TEMPDIR/tsmuxer.meta\""
					;;
				esac
				
				case "$source" in
					dvd|bd|file)
					for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
						if [ "${TRACKID[i]}" = "yes" ]; then
							TSAUDLANG[i]=", lang=${AUDLANG[i]}"
						fi
					done
					;;
				esac
				
				case "${audiocodec[1]}" in
					mp3|lavcac3|ffmp3|ffac3|ffeac3|ffdts|aac|"")
					TSAUD="$MPLAYER \"$OUTPUT\" $MPLAYEROPTS -vo null -vc null -dumpaudio -dumpfile \"$TEMPDIR/audiots.raw\""
					;;
				esac
				
				case "${audiocodec[1]}" in
					ffac3|ffeac3)
					METAAUD[1]="echo \"A_AC3, \\\"$TEMPDIR/audiots.raw\\\"${TSAUDLANG[1]}\" >> \"$TEMPDIR/tsmuxer.meta\""
					;;
					ffdts)
					METAAUD[1]="echo \"A_DTS, \\\"$TEMPDIR/audiots.raw\\\"${TSAUDLANG[1]}\" >> \"$TEMPDIR/tsmuxer.meta\""
					;;
					neroaac|fdkaac)
					case "${AACTYPE[1]}" in
						LC-AAC)
						METAAUD[1]="echo \"A_AAC, \\\"$TEMPDIR/audio1.aac\\\"${TSAUDLANG[1]}\" >> \"$TEMPDIR/tsmuxer.meta\""
						;;
					esac
					;;
					aac|"")
					METAAUD[1]="echo \"A_AAC, \\\"$TEMPDIR/audiots.raw\\\"${TSAUDLANG[1]}\" >> \"$TEMPDIR/tsmuxer.meta\""
					;;
					mp3|ffmp3)
					METAAUD[1]="echo \"A_MP3, \\\"$TEMPDIR/audiots.raw\\\"${TSAUDLANG[1]}\" >> \"$TEMPDIR/tsmuxer.meta\""
					;;
					aftenac3)
					METAAUD[1]="echo \"A_AC3, \\\"$TEMPDIR/audio1.ac3\\\"${TSAUDLANG[1]}\" >> \"$TEMPDIR/tsmuxer.meta\""
					;;
					lavcac3)
					METAAUD[1]="echo \"A_AC3, \\\"$TEMPDIR/audiots.raw\\\"${TSAUDLANG[1]}\" >> \"$TEMPDIR/tsmuxer.meta\""
					;;
					eac3)
					METAAUD[1]="echo \"A_AC3, \\\"$TEMPDIR/audio1.eac3\\\"${TSAUDLANG[1]}\" >> \"$TEMPDIR/tsmuxer.meta\""
					;;
					dts)
					METAAUD[1]="echo \"A_DTS, \\\"$TEMPDIR/audio1.dts\\\"${TSAUDLANG[1]}\" >> \"$TEMPDIR/tsmuxer.meta\""
					;;
				esac
				
				# Second, third, etc audio tracks
				for i in $(eval echo "{2..$MAX_AMOUNT_AUD_TRACKS}"); do
					if [ "${TRACKID[i]}" = "yes" ]; then
						case "${audiocodec[i]}" in
							ffac3|ffeac3)
							METAAUD[i]="echo \"A_AC3, \\\"$TEMPDIR/audio$i.raw\\\"${TSAUDLANG[i]}\" >> \"$TEMPDIR/tsmuxer.meta\""
							;;
							ffdts)
							METAAUD[i]="echo \"A_DTS, \\\"$TEMPDIR/audio$i.raw\\\"${TSAUDLANG[i]}\" >> \"$TEMPDIR/tsmuxer.meta\""
							;;
							ffmp3)
							METAAUD[i]="echo \"A_MP3, \\\"$TEMPDIR/audio$i.raw\\\"${TSAUDLANG[i]}\" >> \"$TEMPDIR/tsmuxer.meta\""
							;;
							aac|"")
							METAAUD[i]="echo \"A_AAC, \\\"$TEMPDIR/audio$i.aac\\\"${TSAUDLANG[i]}\" >> \"$TEMPDIR/tsmuxer.meta\""
							;;
							mp3)
							METAAUD[i]="echo \"A_MP3, \\\"$TEMPDIR/audio$i.mp3\\\"${TSAUDLANG[i]}\" >> \"$TEMPDIR/tsmuxer.meta\""
							;;
							aftenac3|lavcac3)
							METAAUD[i]="echo \"A_AC3, \\\"$TEMPDIR/audio$i.ac3\\\"${TSAUDLANG[i]}\" >> \"$TEMPDIR/tsmuxer.meta\""
							;;
							eac3)
							METAAUD[i]="echo \"A_AC3, \\\"$TEMPDIR/audio$i.eac3\\\"${TSAUDLANG[i]}\" >> \"$TEMPDIR/tsmuxer.meta\""
							;;
							dts)
							METAAUD[i]="echo \"A_DTS, \\\"$TEMPDIR/audio$i.dts\\\"${TSAUDLANG[i]}\" >> \"$TEMPDIR/tsmuxer.meta\""
							;;
							neroaac|fdkaac)
							case "${AACTYPE[i]}" in
								LC-AAC)
								METAAUD[i]="echo \"A_AAC, \\\"$TEMPDIR/audio$i.aac\\\"${TSAUDLANG[i]}\" >> \"$TEMPDIR/tsmuxer.meta\""
								;;
							esac
							;;
						esac
					fi
				done
				
				# Export commands to files
				case "$source" in
					dir)
					case "$3" in
						bd40|bdhq40|bd41|bdhq41)
						TSOUT="$OUTPUTDIR/\${i%.*}.bluray"
						;;
						avchd|avchdhq)
						TSOUT="$OUTPUTDIR/\${i%.*}.avchd"
						;;
						*)
						TSOUT="$OUTPUTDIR/\${i%.*}.ts"
						;;
					esac
					TSMUXING="$BATCH"
					;;
					*)
					case "$3" in
						bd40|bdhq40|bd41|bdhq41)
						TSOUT="${OUTPUT%.*}.bluray"
						;;
						avchd|avchdhq)
						TSOUT="${OUTPUT%.*}.avchd"
						;;
						*)
						TSOUT="${OUTPUT%.*}.ts"
						;;
					esac
					TSMUXING="$TEMPDIR/tsmuxing"
					;;
				esac
				ts_export_func() {
					echo "test -e \"$TSOUT\" && mv -f \"$TSOUT\" \"$TSOUT.old\""
					echo
					echo "$TSVID"
					echo "$TSAUD"
					echo "$TSFPS"
					echo
					echo "$METAOPT"
					echo "$METAVID"
					for trk in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
						echo "${METAAUD[trk]}"
					done
					echo "$TSMUXER \"$TEMPDIR/tsmuxer.meta\" \"$TSOUT\""
					echo "sleep 2"
					echo
				}
				ts_export_func >> "$TSMUXING"
				if [ "$saveopts" = "y" ]; then
					echo >> "$OPTSFILE"
					echo "####################### TS/Blu-Ray Muxing #######################" >> "$OPTSFILE"
					echo >> "$OPTSFILE"
					ts_export_func >> "$OPTSFILE"
				fi
			fi
		else
			avi_to_ts=no
		fi
		;;
		*)
		avi_to_ts=no
		;;
	esac
else
	avi_to_ts=no
fi

# Ask for AVI -> OGM
# ogmmerge doesn't like raw h264
# video so instead we take it
# directly from the AVI file
if [ "$ALLOW_OGM_MUXING" = "y" ]; then
	case "${audiocodec[1]}" in
		ffmp3|ffvorbis|ffac3|ffpcm|mp3|vorbis|aftenac3|lavcac3|pcm|nosound)
		avi_ogm=$(get_selection_func "Would you like to convert the final encode from AVI to OGM? [y/N]: ")
		if [ "$avi_ogm" = "y" ]; then
			# Check for ogmmerge
			if [ ! -x "$OGMMERGE" ]; then
				avi_to_ogm=no
				echo
				error "-> Utility 'ogmmerge' is missing!"
				error "-> Skipping AVI to OGM conversion!"
			else
				avi_to_ogm=yes
				
				case "${audiocodec[1]}" in
					vorbis)
					# We take the video directly from the AVI,
					# hence the --noaudio option which ignores
					# audio from the AVI
					NOAUDIO="--noaudio"
					case "$source" in
						dvd|bd|file)
						OGMAUD="-c LANGUAGE=${AUDLANG[1]} \"$TEMPDIR/audio1.ogg\""
						;;
						*)
						OGMAUD="\"$TEMPDIR/audio1.ogg\""
						;;
					esac
					;;
					aftenac3)
					NOAUDIO="--noaudio"
					case "$source" in
						dvd|bd|file)
						OGMAUD="-c LANGUAGE=${AUDLANG[1]} \"$TEMPDIR/audio1.ac3\""
						;;
						*)
						OGMAUD="\"$TEMPDIR/audio1.ac3\""
						;;
					esac
					;;
					mp3|lavcac3|ffac3|pcm)
					case "$source" in
						dvd|bd|file)
						OGMAUDLANG="-c LANGUAGE=${AUDLANG[1]}"
						;;
					esac
					;;
				esac
				
				# Subsequent tracks
				for i in $(eval echo "{2..$MAX_AMOUNT_AUD_TRACKS}"); do
					if [ "${TRACKID[i]}" = "yes" ]; then
						case "${audiocodec[i]}" in
							# audio stream copy
							ff*)
							OGMAUD[i]="-c LANGUAGE=${AUDLANG[i]} \"$TEMPDIR/audio$i.${audext[i]}\""
							;;
							mp3)
							OGMAUD[i]="-c LANGUAGE=${AUDLANG[i]} \"$TEMPDIR/audio$i.mp3\""
							;;
							aftenac3|lavcac3)
							OGMAUD[i]="-c LANGUAGE=${AUDLANG[i]} \"$TEMPDIR/audio$i.ac3\""
							;;
							vorbis)
							OGMAUD[i]="-c LANGUAGE=${AUDLANG[i]} \"$TEMPDIR/audio$i.ogg\""
							;;
							pcm)
							OGMAUD[i]="-c LANGUAGE=${AUDLANG[i]} -D \"$TEMPDIR/audio$i.avi\""
							;;
						esac
					fi
				done
				
				# Title/Genre/Year for OGM
				case "$source" in
					file|dvd|bd|vcd)
					OGMTITLE="-c TITLE=\"$(basename "${OUTPUT%.*}")\""
					printf "Specify the Release Year of the content [press 'Enter' to skip]: "
					read ogmyear
					if [ ! -z "$ogmyear" ]; then
						OGMYEAR="-c YEAR=\"$ogmyear\""
					fi
					printf "Provide a Genre for the content [press 'Enter' to skip]: "
					read ogmgenre
					if [ ! -z "$ogmgenre" ]; then
						OGMGENRE="-c GENRE=\"$ogmgenre\""
					fi
					;;
					dir)
					OGMTITLE="-c TITLE=\"\${i%.*}\""
					;;
				esac
				
				# Import of external subtitles.
				# Input type agnostic. Only
				# allow supported subtitle formats
				# by OGM. Others will be skipped
				for i in $(eval echo "{1..$MAX_AMOUNT_EXT_SUBS}"); do
					if [ ! -z "${EXTSUB[i]}" ]; then
						case "$(echo "${EXTSUB[i]##*.}" | tr '[:upper:]' '[:lower:]')" in
							srt|SRT)
							OGMSUBS[i]="-c LANGUAGE=${SUBLANG[i]} \"${EXTSUB[i]}\""
							;;
							*)
							echo
							error "-> Subtitle format '$(echo "${EXTSUB[i]##*.}" | tr '[:lower:]' '[:upper:]')' not supported by OGM!"
							error "-> Supported subtitle formats are: SRT"
							error "-> Skipping import of '${EXTSUB[i]}'"
							echo
							;;
						esac
					fi
				done
				
				case "$source" in
					dvd)
					# Chapters for OGM
					if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
						ogmimpchap=$(get_selection_func "Import chapters information into the OGM container? [y/N]: ")
						if [ "$ogmimpchap" = "y" ]; then
							OGMCHAPS="-c @\"$CHAPTERSFILE\""
						fi
					fi
					;;
					file|bd)
					printf "Provide a Chapters file [press 'Enter' to skip]: "
					read -e ogmchapsfile
					if [ ! -z "$ogmchapsfile" ]; then
						if [ ! -f "$ogmchapsfile" ]; then
							echo
							error "-> No such file: '$ogmchapsfile'"
							error "-> Skipping chapters file import"
							echo
						else
							OGMCHAPS="-c @\"$ogmchapsfile\""
						fi
					fi
					;;
				esac
				
				# Export commands to files
				case "$source" in
					dir)
					OGMOUT="$OUTPUTDIR/\${i%.*}.ogm"
					OGMMUXING="$BATCH"
					;;
					*)
					OGMOUT="${OUTPUT%.*}.ogm"
					OGMMUXING="$TEMPDIR/ogmmuxing"
					;;
				esac
				OGMCOMMENT="-c COMMENT=\"Tagged by h264enc $version on \$(date)\""
				ogm_export_func() {
					echo "test -e \"$OGMOUT\" && mv -f \"$OGMOUT\" \"$OGMOUT.old\""
					echo
					echo "$OGMMERGE $NOAUDIO $OGMTITLE $OGMYEAR $OGMGENRE $OGMAUDLANG $OGMCOMMENT $OGMCHAPS \"$OUTPUT\" ${OGMAUD[*]} ${OGMSUBS[*]} -o \"$OGMOUT\""
					echo "sleep 2"
					echo
				}
				ogm_export_func >> "$OGMMUXING"
				if [ "$saveopts" = "y" ]; then
					echo >> "$OPTSFILE"
					echo "####################### OGM Muxing #######################" >> "$OPTSFILE"
					echo >> "$OPTSFILE"
					ogm_export_func >> "$OPTSFILE"
					echo >> "$OPTSFILE"
				fi
			fi
		else
			avi_to_ogm=no
		fi
		;;
		*|"")
		avi_to_ogm=no
		;;
	esac
else
	avi_to_ogm=no
fi

# Footers for batch files
case "$source" in
	dir)
	if [ "$avi_to_mkv" = "yes" -o "$avi_to_mp4" = "yes" -o "$avi_to_ts" = "yes" -o "$avi_to_ogm" = "yes" ]; then
		rmavi=$(get_selection_func "Delete the AVI file after remuxing? [y/N]: ")
		if [ "$rmavi" = "y" ]; then
			echo "rm -f \"$OUTPUT\"" >> "$BATCH"
		fi
	fi
	echo "rm -rf \"$TEMPDIR\"" >> "$BATCH"
	echo >> "$BATCH"
	echo "fi" >> "$BATCH"
	echo >> "$BATCH"
	echo "done" >> "$BATCH"
	echo >> "$BATCH"
	send_email_func dir >> "$BATCH"
	echo "#################### END OF COMMANDS ####################" >> "$BATCH"
	;;
	*)
	if [ "$saveopts" = "y" ]; then
		echo "rm -rf \"$TEMPDIR\"" >> "$OPTSFILE"
		echo >> "$OPTSFILE"
		send_email_func exp >> "$OPTSFILE"
		echo "#################### END OF COMMANDS FOR $OUTPUT ####################" >> "$OPTSFILE"
		echo >> "$OPTSFILE"
	fi
	if [ "$avi_to_mkv" = "no" -a "$avi_to_mp4" = "no" -a "$avi_to_ts" = "no" -a "$avi_to_ogm" = "no" ]; then
		for i in $(eval echo "{2..$MAX_AMOUNT_AUD_TRACKS}"); do
			if [ "${TRACKID[i]}" = "yes" ]; then
				echo
				error "-> Subsequent audio track(s) only supported by"
				error "   the MKV/MP4/TS/OGM containers!"
				echo
				exit_func 1
			fi
		done
		case "${audiocodec[1]}" in
			neroaac|fdkaac|aac+|aftenac3|eac3|vorbis|opus|flac|dts|fftruehd)
			echo
			error "-> ${audiocodec[1]} audio not supported by the AVI container!"
			echo
			exit_func 1
			;;
		esac
	fi
	;;
esac

case "$1" in
	-1p)	passmode="1-pass mode" ;;
	-qp)	passmode="fixed-quant mode" ;;
	-crf)	passmode="constant rate factor mode" ;;
	-2p)	passmode="2-pass mode" ;;
	-3p)	passmode="3-pass mode" ;;
esac

echo
case "$source" in
	dir)
	green "-> Starting to batch encode $type in '$(dirname "$sourcetype")'"
	display_quality_preset_func $3 $4
	green "-> Using '$(dirname "$OUTPUT")' as output directory for all $type"
	green "-> Using $passmode for all $type"
	green "-> Batch file located in '$BATCH'"
	;;
	*)
	green "-> Starting to encode the $type in $passmode"
	display_quality_preset_func $3 $4
	case "$1" in
		-2p)	green "-> Using '/dev/null' as output for the first pass"; finalpass="for the second pass" ;;
		-3p)	green "-> Using '/dev/null' as output for the first & second pass"; finalpass="for the third pass" ;;
	esac
	green "-> Using '$OUTPUT' as output file $finalpass"
	;;
esac
echo

# Give user a few more seconds
# to read the above
sleep 3

# Small counter :)
counter_func() {
	for i in 5 4 3 2 1 0; 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
}

mencoder_exit_func() {
	if [ $? != 0 ]; then
		error "-> MEncoder has exited with a non-zero value!"
		error "-> Exiting in function: mencoder_exit_func()"
		exit_func 1
	fi
}

color_func blue && printf "Starting to encode in: " && counter_func
color_func normal && echo

# Start encoding
case "$source" in
	dir)
	if [ -f "$BATCH" ]; then
		cp -f $BATCH $HOME
		source $BATCH
		echo
		brown "-> Have a nice day or night! (^_^)"
		echo
		exit_func 0
	else
		error "-> File '$BATCH' is missing!"
		error "-> Exiting..."
		exit_func 1
	fi
	;;
	*)
	case "$1" in
		-1p|-qp|-crf)
		source "$H264_1PFQ"
		mencoder_exit_func
		;;
		-2p)
		source "$H264_2P1"
		mencoder_exit_func
		echo
		brown "=============================================================="
		echo
		color_func blue && printf "Starting the second pass of the encoding process in: " && counter_func
		color_func normal && echo
		source "$H264_2P2"
		mencoder_exit_func
		;;
		-3p)
		# Here's how it works...
		# 1-pass -> collects statistics and stores them to a file
		# 2-pass -> reads those statistics and bases ratecontrol on them
		# 3-pass -> simultaniously reads statistics, overwrites them
		#           and encodes the content
		source "$H264_2P1"
		mencoder_exit_func
		echo
		brown "=============================================================="
		echo
		color_func blue && printf "Starting the second pass of the encoding process in: " && counter_func
		color_func normal && echo
		source "$H264_2P2"
		mencoder_exit_func
		echo
		brown "=============================================================="
		echo
		color_func blue && printf "Starting the third pass of the encoding process in: " && counter_func
		color_func normal && echo
		source "$H264_2P3"
		mencoder_exit_func
		;;
	esac
	;;
esac

# Dump the second/third/... subtitle if selected
case "${audiocodec[1]}" in
	nosound)		audfmt="-nosound" ;;
	*)			audfmt="-oac pcm" ;;
esac

for i in $(eval echo "{2..$MAX_AMOUNT_SUBS}"); do
	if [ ! -z "${vobsubout[i]}" ]; then
		echo
		green "-> Dumping subtitle $i, please wait..."
		sleep 2
		$MENCODER $sourcetype $device $chapters $ofps ${aid[i]} ${subtitle[i]} -vobsubout "${SUBFILE[i]%.*}" -vobsuboutindex $(($i-1)) $audfmt -ovc copy -o /dev/null >/dev/null 2>&1
		if [ -e "${IDXFILE[i]}" ]; then
			green "-> Done"
		else
			error "-> Failed!"
			if [ "$avi_to_mkv" = "yes" -o "$avi_to_mp4" = "yes" ]; then
				if [ "$mkvimpsub" = "y" -o "$mp4impsub" = "y" ]; then
					error "-> Exiting as container conversion will also fail!"
					echo
					exit_func 1
				fi
			fi
			echo
		fi
	fi
done

# Encode audio
if [ "$avi_to_mkv" = "yes" -o "$avi_to_mp4" = "yes" -o "$avi_to_ogm" = "yes" -o "$avi_to_ts" = "yes" ]; then
	for i in $(eval echo "{1..$MAX_AMOUNT_AUD_TRACKS}"); do
		if [ "${TRACKID[i]}" = "yes" ]; then
			if [ ! -z "$(grep '.*' "${AUDIOENC[i]}")" ]; then
				sleep 2
				echo
				case "${audiocodec[i]}" in
					ff*)
					# Stream copy
					audfile[i]="$TEMPDIR/audio$i.${audext[i]}"
					green "-> Track $i: Dumping ${detectaud[i]} audio, please wait..."
					;;
					mp3)
					audfile[i]="$TEMPDIR/audio$i.mp3"
					green "-> Track $i: Encoding audio to MP3, please wait..."
					;;
					neroaac)
					audfile[i]="$TEMPDIR/audio$i.aac"
					green "-> Track $i: Encoding audio with 'neroAacEnc' to ${AACTYPE[i]}, please wait..."
					;;
					fdkaac)
					audfile[i]="$TEMPDIR/audio$i.aac"
					green "-> Track $i: Encoding audio with 'aac-enc' to ${AACTYPE[i]}, please wait..."
					;;
					aac|"")
					audfile[i]="$TEMPDIR/audio$i.aac"
					green "-> Track $i: Encoding audio with 'MEncoder' to LC-AAC, please wait..."
					;;
					aac+)
					audfile[i]="$TEMPDIR/audio$i.aac"
					green "-> Track $i: Encoding audio with 'aacplusenc' to HE-AACv1, please wait..."
					;;
					aftenac3)
					audfile[i]="$TEMPDIR/audio$i.ac3"
					green "-> Track $i: Encoding audio with 'aften' to AC-3, please wait..."
					;;
					lavcac3)
					audfile[i]="$TEMPDIR/audio$i.ac3"
					green "-> Track $i: Encoding audio with 'MEncoder' to AC-3, please wait..."
					;;
					eac3)
					audfile[i]="$TEMPDIR/audio$i.eac3"
					green "-> Track $i: Encoding audio with 'MEncoder' to E-AC-3, please wait..."
					;;
					vorbis)
					audfile[i]="$TEMPDIR/audio$i.ogg"
					green "-> Track $i: Encoding audio with 'oggenc' to Vorbis, please wait..."
					;;
					opus)
					audfile[i]="$TEMPDIR/audio$i.opus"
					green "-> Track $i: Encoding audio with 'opusenc' to Opus, please wait..."
					;;
					flac)
					audfile[i]="$TEMPDIR/audio$i.flac"
					green "-> Track $i: Encoding audio with 'flac' to FLAC, please wait..."
					;;
					dts)
					audfile[i]="$TEMPDIR/audio$i.dts"
					green "-> Track $i: Encoding audio with 'dcaenc' to DTS, please wait..."
					;;
					pcm)
					audfile[i]="$TEMPDIR/audio$i.avi"
					green "-> Track $i: Encoding audio with 'MEncoder' to PCM/WAV, please wait..."
					;;
				esac
				source "${AUDIOENC[i]}" >/dev/null 2>&1
				if [ $(find "${audfile[i]}" -type f -size +20480c 2>/dev/null | wc -l) -gt 0 ]; then
					green "-> Track $i: Done"
				else
					error "-> Track $i: Failed"
					error "-> Exiting as container conversion will also fail!"
					echo
					exit_func 1
				fi
			fi
		fi
	done
fi


##############################################################
########## Container conversion (MKV/MP4/OGM/TS) #############
##############################################################

# AVI -> MKV conversion
if [ "$avi_to_mkv" = "yes" ]; then
	echo
	green "-> Converting AVI file to the MKV container, please wait..."
	sleep 3
	if [ -f "$MKVMUXING" ]; then
		source "$MKVMUXING" >/dev/null 2>&1
		if [ $? = 0 ]; then
			green "-> Done"
		else
			error "-> Failed!"
		fi
	else
		error "-> File '$MKVMUXING' is missing!"
		error "-> Skipping AVI to MKV conversion!"
	fi
fi

# AVI -> MP4 conversion
if [ "$avi_to_mp4" = "yes" ]; then
	echo
	green "-> Converting AVI file to the MP4 container, please wait..."
	sleep 3
	if [ -f "$MP4MUXING" ]; then
		source "$MP4MUXING" >/dev/null 2>&1
		if [ $? = 0 ]; then
			green "-> Done"
		else
			error "-> Failed!"
		fi
	else
		error "-> File '$MP4MUXING' is missing!"
		error "-> Skipping AVI to MP4 conversion!"
	fi
fi

# AVI -> TS conversion
if [ "$avi_to_ts" = "yes" ]; then
	echo
	case "$3" in
		bd40|bdhq40|bd41|bdhq41|avchd|avchdhq)
		green "-> Converting AVI file to Blu-ray/AVCHD disc structure, please wait..."
		;;
		*)
		green "-> Converting AVI file to the TS container, please wait..."
		;;
	esac
	sleep 3
	if [ -f "$TSMUXING" ]; then
		source "$TSMUXING" >/dev/null 2>&1
		if [ -e "$TSOUT" ]; then
			green "-> Done"
		else
			error "-> Failed!"
		fi
	else
		error "-> File '$TSMUXING' is missing!"
		error "-> Skipping AVI to TS/Blu-ray/AVCHD conversion!"
	fi
fi

# AVI -> OGM conversion
if [ "$avi_to_ogm" = "yes" ]; then
	echo
	green "-> Converting AVI file to the OGM container, please wait..."
	sleep 3
	if [ -f "$OGMMUXING" ]; then
		source "$OGMMUXING" >/dev/null 2>&1
		if [ $? = 0 ]; then
			green "-> Done"
		else
			error "-> Failed!"
		fi
	else
		error "-> File '$OGMMUXING' is missing!"
		error "-> Skipping AVI to OGM conversion!"
	fi
fi

rm -rf "$TEMPDIR" 2>/dev/null

# Report final file size
MB_AVI="$(echo "scale=3; $(wc -c < "$OUTPUT")/1048576" | $BC -l | sed 's|^\.|0\.|')"
GB_AVI="$(echo "scale=3; $MB_AVI/1024" | $BC -l | sed 's|^\.|0\.|')"
echo
green "-> AVI file size: $MB_AVI MiB or $GB_AVI GiB ($OUTPUT)"
if [ "$avi_to_mkv" = "yes" ]; then
	if [ -e "$MKVOUT" ]; then
		MB_MKV="$(echo "scale=3; $(wc -c < "$MKVOUT" 2>/dev/null)/1048576" | $BC -l | sed 's|^\.|0\.|')"
		GB_MKV="$(echo "scale=3; $MB_MKV/1024" | $BC -l | sed 's|^\.|0\.|')"
		green "-> MKV file size: $MB_MKV MiB or $GB_MKV GiB ($MKVOUT)"
	fi
fi

if [ "$avi_to_ts" = "yes" ]; then
	if [ -e "$TSOUT" ]; then
		case "$3" in
			bd40|bdhq40|bd41|bdhq41)
			green "-> Blu-ray disc structure created in: $TSOUT"
			;;
			avchd|avchdhq)
			green "-> AVCHD disc structure created in: $TSOUT"
			;;
			*)
			MB_TS="$(echo "scale=3; $(wc -c < "$TSOUT" 2>/dev/null)/1048576" | $BC -l | sed 's|^\.|0\.|')"
			GB_TS="$(echo "scale=3; $MB_TS/1024" | $BC -l | sed 's|^\.|0\.|')"
			green "-> TS file size:  $MB_TS MiB or $GB_TS GiB ($TSOUT)"
			;;
		esac
	fi
fi

if [ "$avi_to_mp4" = "yes" ]; then
	if [ -e "$MP4OUT" ]; then
		MB_MP4="$(echo "scale=3; $(wc -c < "$MP4OUT" 2>/dev/null)/1048576" | $BC -l | sed 's|^\.|0\.|')"
		GB_MP4="$(echo "scale=3; $MB_MP4/1024" | $BC -l | sed 's|^\.|0\.|')"
		green "-> MP4 file size: $MB_MP4 MiB or $GB_MP4 GiB ($MP4OUT)"
	fi
fi

if [ "$avi_to_ogm" = "yes" ]; then
	if [ -e "$OGMOUT" ]; then
		MB_OGM="$(echo "scale=3; $(wc -c < "$OGMOUT" 2>/dev/null)/1048576" | $BC -l | sed 's|^\.|0\.|')"
		GB_OGM="$(echo "scale=3; $MB_OGM/1024" | $BC -l | sed 's|^\.|0\.|')"
		green "-> OGM file size: $MB_OGM MiB or $GB_OGM GiB ($OGMOUT)"
	fi
fi

send_email_func

if [ "$avi_to_mkv" = "yes" -o "$avi_to_mp4" = "yes" -o "$avi_to_ogm" = "yes" -o "$avi_to_ts" = "yes" ]; then
	echo
	if [ "$DELETE_AVI_AFTER_REMUX" = "y" ]; then
		green "-> Auto-deleting the AVI file..."
		rm -f "$OUTPUT"
	else
		delavi=$(get_selection_func "Delete the AVI file? [y/N]: ")
		if [ "$delavi" = "y" ]; then
			rm -f "$OUTPUT"
		fi
	fi
fi

echo
brown "-> Have a nice day or night! (^_^)"
echo

exit 0
