#!/bin/sh

# Version: 3.21 2017-07-08
#	Added Analogue and Analogue Boost, Alsa Simple Controls. SBP.
#	Added Cardnumber routine to keep alsaequal working with selected card. PH.

# Version: 3.20 2017-03-12
#	Added check for /tmp/dropdown.cfg in pcp_sound_card_dropdown. SBP.
#	Added shini conf parser. SBP.
#	Suppress already mounted message during do_rebootstuff newconfig process. PH.

# Version: 3.11 2017-01-20
#	Fixed the issue with shairport not working when using USB cards. SBP.

# Version: 3.10 2016-12-11
#	Original. SBP.

pcp_debug_log "$0 - Running pcp-soundcard-functions..."

DACLOCATION="/usr/local/etc/pcp/cards"     # <=== Should be in pcp-functions? GE.
#The below line is for development only.
#DACLOCATION="/home/tc/www/cgi-bin/cards"
############

. /usr/local/bin/shini.sh

#========================================================================================
# Check if we use the special Audio kernel or not. As we load special overlays if using Audio kernel
#----------------------------------------------------------------------------------------
pcp_AudioKernel_status() {
	sudo  uname -a | grep pcpAudioCore > /dev/null 2>&1 && KERNELVERSION=Audiokernel || KERNELVERSION=Officialkernel
}
pcp_AudioKernel_status

#========================================================================================
# Disable/re_enable analog audio
#----------------------------------------------------------------------------------------
pcp_disable_analog() {
	sudo sed -i 's/^dtparam=audio=on/#dtparam=audio=on/g' $CONFIGTXT
	sudo sed -i 's/^audio_pwm_mode=2/#audio_pwm_mode=2/g' $CONFIGTXT
}

pcp_re_enable_analog() {
	pcp_disable_analog
	sudo sed -i "/dtparam=audio=on/c\dtparam=audio=on" $CONFIGTXT
	sudo sed -i "/audio_pwm_mode=2/c\audio_pwm_mode=2" $CONFIGTXT
}

#========================================================================================
# Remove Audio dtoverlays
#----------------------------------------------------------------------------------------
pcp_disable_i2s() {
	pcp_re_enable_analog
		# unset DTOVERLAY both the old one that is removed on chooseoutput.cgi and the one from config.cfg to clear all traces of audio dtoverlays
		shini_parse ${DACLOCATION}/${ORIG_AUDIO}.conf
		[ x"" != x"${DTOVERLAY}" ] && sed -i '/dtoverlay='"$DTOVERLAY"'/d' $CONFIGTXT

		shini_parse ${DACLOCATION}/${AUDIO}.conf
		[ x"" != x"${DTOVERLAY}" ] && sed -i '/dtoverlay='"$DTOVERLAY"'/d' $CONFIGTXT
}

#========================================================================================
# Add Audio dtoverlays
#----------------------------------------------------------------------------------------
pcp_enable_i2s() {
	pcp_re_enable_analog
	pcp_selected_soundcontrol
	[ x"$SPARAMS1" != x"" ] && PAR1=','"$SPARAMS1"'' || PAR1="$SPARAMS1"
	[ x"$SPARAMS2" != x"" ] && PAR2=','"$SPARAMS2"'' || PAR2="$SPARAMS2"
	[ x"$SPARAMS3" != x"" ] && PAR3=','"$SPARAMS3"'' || PAR3="$SPARAMS3"
	[ x"$SPARAMS4" != x"" ] && PAR4=','"$SPARAMS4"'' || PAR4="$SPARAMS4"
	[ x"$SPARAMS5" != x"" ] && PAR5=','"$SPARAMS5"'' || PAR5="$SPARAMS5"

	[ x"$DTOVERLAY" != x"" ] && sudo echo dtoverlay=$DTOVERLAY$PAR1$PAR2$PAR3$PAR4$PAR5  >> $CONFIGTXT
}

#========================================================================================
# Enable/disable HDMI settings in config.txt
#----------------------------------------------------------------------------------------
pcp_disable_HDMI() {
	sed -i '/hdmi_drive=2/d' $CONFIGTXT
	sed -i '/hdmi_force_hotplug=1/d' $CONFIGTXT
	sed -i '/hdmi_force_edid_audio=1/d' $CONFIGTXT
}

pcp_enable_HDMI() {
	pcp_disable_i2s
	sudo echo hdmi_drive=2 >> $CONFIGTXT
	sudo echo hdmi_force_hotplug=1 >> $CONFIGTXT
	sudo echo hdmi_force_edid_audio=1 >> $CONFIGTXT
	sudo amixer cset numid=3 2 >/dev/null 2>&1
}

#========================================================================================
# Section that controls loading of DAC overlays
#----------------------------------------------------------------------------------------
pcp_read_chosen_audio() {
	# if noumount, disk is probably already mounted....supress output
	[ "$1" == "noumount" ] && pcp_mount_bootpart > /dev/null 2>&1 || pcp_mount_bootpart
	pcp_disable_HDMI
	pcp_disable_i2s
	pcp_enable_i2s
	# This is to allow no unmount of mmcblk0p1 during booting with newconfig.cfg
	[ "$1" != "noumount" ] && pcp_umount_bootpart
}

#========================================================================================
# Control of sound card routines:
#  - Needs to be populated for each type of soundcard.
#  - Some are without filter options.
#  - USB cards will probably never be supported this way as they are so different.
#----------------------------------------------------------------------------------------
# HELP - To find the controls:
#  - amixer -c 0 scontrols
#  - aplay -l
#----------------------------------------------------------------------------------------
pcp_generic_card_control() {
	case "$GENERIC_CARD" in
		TI51XX)
			amixer -c $CARD scontrols | grep -q 'DSP Program' && DSPfound="yes" || DSPfound="no" 
			if [ "$DSPfound" = "yes" ]; then
				DSP="DSP Program,0"
				FILTER1="Low latency IIR with de-emphasis"
				FILTER2="FIR interpolation with de-emphasis"
				FILTER3="High attenuation with de-emphasis"
				FILTER4="Fixed process flow"
				FILTER5="Ringing-less low latency FIR"
			fi
			ACTUAL_VOL=$(amixer -c $CARD sget $SSET | grep "Right: Playback" | awk '{ print $5 }' | tr -d "[]%")
			ACTUAL_DB=$(amixer -c $CARD sget $SSET | grep "Right: Playback" | awk '{ print $6 }' | tr -d "[]")
			ACTUAL_FILTER=$(amixer -c $CARD sget 'DSP Program,0' | grep "Item0:" | awk '{ print $2 }' | tr -d "'")

			case "$DSPFILTER" in
				FILTER1) FILTER="$FILTER1" ;;
				FILTER2) FILTER="$FILTER2" ;;
				FILTER3) FILTER="$FILTER3" ;;
				FILTER4) FILTER="$FILTER4" ;;
				FILTER5) FILTER="$FILTER5" ;;
			esac

			# Logic to make checked radiobuttons - needs to clear it otherwise we have two FILTERS_CHECK checked.
			FILTER1_CHECK=""
			FILTER2_CHECK=""
			FILTER3_CHECK=""
			FILTER4_CHECK=""
			FILTER5_CHECK=""

			case "$ACTUAL_FILTER" in
				Low) FILTER1_CHECK="checked" ;;
				FIR) FILTER2_CHECK="checked" ;;
				High) FILTER3_CHECK="checked" ;;
				Fixed) FILTER4_CHECK="checked" ;;
				Ringing-less) FILTER5_CHECK="checked" ;;
			esac

			#Logic that will check for Simple mixer controls Analogue and Analogue Playback Boost
				#SMC_ANALOGUE=$(amixer -c $CARD sget Analogue | grep "Capabilities: pvolume"aw)
			#Actual setting for these Analogue controls:
				SMC_ANALOGUE=$(amixer -c $CARD sget 'Analogue' | grep "Front Left:" | awk '{ print $4 }')
				SMC_ANALOGUE_BOOST=$(amixer -c $CARD sget 'Analogue Playback Boost' | grep "Front Left:" | awk '{ print $3 }')

			# Logic to make checked radiobuttons
			case "$SMC_ANALOGUE" in 
				0) SMC_ANALOGUE_CHECK="" ;;
				1) SMC_ANALOGUE_CHECK="checked" ;;
			esac

			case "$SMC_ANALOGUE_BOOST" in 
				0) SMC_ANALOGUE_BOOST_CHECK="" ;;
				1) SMC_ANALOGUE_BOOST_CHECK="checked" ;;
			esac
		;;

		HIFIBERRY_AMP)
			ACTUAL_VOL=$(amixer -c $CARD sget $SSET | grep "Mono:" | awk '{ print $3 }' | tr -d "[]%")
		;;

		ONBOARD)
			ACTUAL_VOL=$(amixer -c $CARD sget $SSET | grep "Mono: Playback" | awk '{ print $4 }' | tr -d "[]%")
			ACTUAL_DB=$(amixer -c $CARD sget $SSET | grep "Mono: Playback" | awk '{ print $5 }' | tr -d "[]")
		;;

#		ES9023)
#			CARD="ALSA"
#			SSET="PCM"
#			ACTUAL_VOL=$(amixer -c $CARD sget $SSET | grep "Mono: Playback" | awk '{ print $4 }' | tr -d "[]%")
#			ACTUAL_DB=$(amixer -c $CARD sget $SSET | grep "Mono: Playback" | awk '{ print $5 }' | tr -d "[]")
#			TEXT="Choosing 384k will enable 352k and 384k sample rates. Selecting bclk_ratio_int_div will use bclk_ratio=50 for 16/24bps and bclk_ratio=100 for 32bps media when sample rate is a multiple of 8kHz and less than 192kHz. Which causes the selection of the 19M2 OSC as the parent for the PCM clock with an integer divider, rather than PLLD with fractional divider and MASH noise shaping."
#			PARAMS1="384k"
#			PARAMS2="bclk_ratio_int_div"
#		;;
	esac
}

#========================================================================================
# This will get us all available AUDIO DACs
#----------------------------------------------------------------------------------------
AUDIO_OPTIONS_EXTRA=$(ls "$DACLOCATION" | grep ".conf" | awk -F'.conf' '{ print $1 }')

#========================================================================================
# Section that populate sound card drop-down list on Squeezelite.cgi
#----------------------------------------------------------------------------------------
pcp_sound_card_dropdown() {
	pcp_blank_audio_conf
	. $CONFIGCFG
	if [ -e /tmp/dropdown.cfg ]; then
		sudo sed -i 's/:selected:/:notselected:/' /tmp/dropdown.cfg
		sudo sed -i "/${AUDIO}:/s/:notselected:/:selected:/" /tmp/dropdown.cfg

	else
		CONF_AUDIO="$AUDIO"
		pcp_blank_audio_conf
		for i in $AUDIO_OPTIONS_EXTRA; do
			AUDIO=$i
			pcp_soundcontrol
			CHECKED="notselected"
			[ "$AUDIO" = "$CONF_AUDIO" ] && CHECKED="selected"
			if [ x"$LISTNAME" != x ]; then
				echo "${AUDIO}:${CHECKED}:${LISTNAME}:${RPI_MODEL}" >> /tmp/dropdown.cfg
			fi
		done
	fi
}

# Find card number for asound.conf when using alsaequal
pcp_find_card_number() {
	pcp_blank_audio_conf
	shini_parse ${DACLOCATION}/${AUDIO}.conf
	case $CARD in
		USB*) CARDNAME="USB";;
		*) CARDNAME=$(echo $OUTPUT | cut -d '=' -f2);;
	esac
	CARDNO=$(cat /proc/asound/cards | grep '\[' | grep $CARDNAME | cut -d ' ' -f2)
}

#========================================================================================
# This will get us available options from the DAC
#----------------------------------------------------------------------------------------
old_pcp_soundcontrol() {
	pcp_blank_audio_conf
	echo "$AUDIO_OPTIONS_EXTRA" | grep -q "$AUDIO" && . "$DACLOCATION"/"$AUDIO".conf
}

# Declare a handler for parsed variables.  This is required.
__shini_parsed() {
#	printf "  %s_%s='%s'\n" "$1" "$2" "$3"
	eval \ $1_$2='"$3"'

	if [ "$KERNELVERSION" = "Audiokernel" ]; then
		if [ "$1" = "PCPAUDIOCORE" ]; then
#			printf "  %s_%s='%s'\n" "$1" "$2" "$3"
			eval \ $2='"$3"'
		fi
	fi

	if [ "$KERNELVERSION" = "Officialkernel" ]; then
		if [ "$1" = "PCPCORE" ]; then
#			printf "  %s_%s='%s'\n" "$1" "$2" "$3"
			eval \ $2='"$3"'
		fi
	fi

	if [ "$1" = "COMMON" ]; then
#		printf "  %s_%s='%s'\n" "$1" "$2" "$3"
		eval \ $2='"$3"'
	fi
}

pcp_soundcontrol() {
	# Parse
	[ "$OUTPUT" = "equal" ] && OUTPUT1="equal" 
	shini_parse ${DACLOCATION}/${AUDIO}.conf
	[ "$OUTPUT1" = "equal" ] && OUTPUT="equal" 
}

#========================================================================================
# This will get us available options from the selected DAC
#----------------------------------------------------------------------------------------
pcp_selected_soundcontrol() {
	pcp_blank_audio_conf
	. "$CONFIGCFG"

	[ $OUTPUT = "equal" ] && OUTPUT1="equal"
	shini_parse ${DACLOCATION}/${AUDIO}.conf
	[ "$OUTPUT1" = "equal" ] && OUTPUT="equal" 
}

pcp_blank_audio_conf() {
	# Remove left-over from previous audio DAC
	CARD=""
	OUTPUT=""
	ALSA_PARAMS=""
	GENERIC_CARD=""
	CONTROL_PAGE=""
	LISTNAME=""
	DTOVERLAY=""
	SSET=""
	PARAMS1=""
	PARAMS2=""
	PARAMS3=""
	PARAMS4=""
	PARAMS5=""
	RPI_MODEL=""
	I=1
	while true; do
		eval TEST="\${TEXT${I}}"
		if [ x"$TEST" != x ]; then 
			eval TEXT${I}=""
			I=$((I+1))
		else
			break
		fi
	done
	}
