#!/bin/bash
# Delay audio input
# Sean McGuire <smcguire@soc.lib.md.us>  Tue, 19 Sep 2017 10:55:32 -0400

bcast=/tmp/delayBcast.ogg
ready=/tmp/delayReady.ogg

conf=$HOME/.delay
vorb=/usr/local/share/delay/ogg
icon=/usr/local/share/delay/img/icon.png
grph=/usr/local/share/delay/img/dialog.png
dial="/usr/bin/yad
	--width=480
	--height=300
	--center
	--undecorated
	--borders=15
	--window-icon=${icon}
	--title=DelayControl
	--image-on-top
	--image=${grph}
	"

#### FUNCTIONS ####

function getDelayValue() {
	if [ -f "$conf" ]; then time=$(/bin/cat "$conf"); else time=128; fi
	valu=$($dial \
		--scale \
		--min-value=1 --max-value=400 --step=2 \
		--value=$time \
		--mark=:$time \
		--inc-buttons \
		--button="Delay!${icon}!Begin Transmission:0" \
		--button=gtk-quit:1 \
		2>/dev/null
	)
	if [[ "$valu" == "" ]]; then
		kill -s TERM $proc
	else
		/usr/bin/printf "$valu" > "$conf"
		secs="$(( $valu / 10 )).$(( $valu % 10 ))"
	fi
}

function haltControl() {
	$dial \
		--form \
		--field="\naudio delayed $secs seconds":LBL \
		--align=center \
		--button=gtk-stop:1 \
		2>/dev/null
	/bin/kill $bcid $sxid 2>/dev/null
	/bin/rm -f $bcast $ready
}

function selectFillSound() {
	fctr=0
	while (( $(/usr/bin/bc <<< "$fctr < 0.1") )); do
		list=$(/bin/ls -1 ${vorb}/*.ogg)
		indx=0
		for file in $list; do rand[$indx]="$file"; ((indx++)); done
		size=${#rand[@]}
		indx=$(($RANDOM % $size))
		fill=${rand[$indx]}
		dura=$(/usr/bin/ogginfo $fill | \
			/bin/grep "Playback length:" | \
			/bin/sed 's|.*Playback length: \([0-9]*\)m:\([0-9.]*\)s|/usr/bin/bc <<< "(\1*60) + \2"|' | \
			/bin/bash )
		fctr=$(/usr/bin/bc <<< "scale=10; $dura / $secs")
	done
}

function delayAudio() {
	/usr/bin/sudo /sbin/sysctl fs.pipe-max-size=16777216 > /dev/null 2>&1
	/bin/rm -f $bcast; /usr/bin/mkfifo $bcast
	/bin/rm -f $ready; /usr/bin/mkfifo $ready
	/usr/local/bin/fifo-size $bcast 16 &
	/usr/local/bin/fifo-size $ready 4 &

	cmmd="/usr/bin/sox -q"
	card="-t alsa -e sign -b 16 -r 48000 -c 1"
	outp="-t ogg -C -1"

	if [ $valu -lt 30 ]; then outp="-t ogg -C 10"; fi # Do minimal compression on stream if under 3 seconds

	$cmmd $fill $outp $ready tempo $fctr 32 &
	$cmmd $bcast $card &
	$cmmd $ready $card -d $outp $bcast &

	bcid=`/usr/bin/pgrep -f "$cmmd $bcast"`
        sxid=`/usr/bin/pgrep -f "$cmmd $ready"`
}
#### FUNCTIONS ####

trap "exit 0" TERM
proc=$$
appl=`echo $0 | sed 's|.*/||g'`
usage="Delay audio input.\n  USAGE: $appl"
if [[ "$1" != "" ]]; then /bin/echo -e "$usage"; exit 1; fi

while [ true ]; do
	getDelayValue
	selectFillSound
	delayAudio
	haltControl
done
