#!/bin/sh
# summary: Play the volume-change sound.
# starchaser volume blip: the "volume changed" sound, at the new volume (the taskbar speaker, quick settings, keys).
#
#   starchaser volume blip         play it (silent while muted)
#   starchaser volume blip wake    quietly wake the speakers (the volume slider opened: a change is coming)
#
# PipeWire puts an idle output to sleep after a few seconds. Waking it takes time (a Bluetooth speaker about half a
# second), and the blip lasts 0.07 s, so the first change after a pause made no sound. When the output is asleep
# the blip gets a silent lead-in long enough for it to wake (Bluetooth longer), made once with ffmpeg.
case "${1:-}" in
    -h|--help|help) sed -n '3,6p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    ""|wake) ;;
    *) printf "starchaser volume blip: unknown command '%s'. Run 'starchaser volume blip --help' for more help.\n" "$1" >&2; exit 2 ;;
esac
SOUND=/usr/share/sounds/freedesktop/stereo/audio-volume-change.oga
[ -r "$SOUND" ] || exit 0                                       # no sound theme installed: stay quiet, not an error
CACHE=${XDG_CACHE_HOME:-$HOME/.cache}/starchaser
PIDFILE=${XDG_RUNTIME_DIR:-/tmp}/starchaser-volume-blip.pid
SINK=$(pactl get-default-sink 2>/dev/null)
STATE=$(pactl list sinks short 2>/dev/null | awk -v s="$SINK" '$2 == s { print $NF }')
case "$SINK" in bluez_*) LEAD=0.7 ;; *) LEAD=0.25 ;; esac

padded() {   # $1 = seconds of silence before the sound (or "only" for silence alone)
    f=$CACHE/volume-blip-$1.oga
    if [ ! -s "$f" ] && command -v ffmpeg >/dev/null; then
        mkdir -p "$CACHE"
        if [ "$1" = only ]; then
            ffmpeg -loglevel error -y -f lavfi -i anullsrc=r=48000:cl=stereo -t 2 -c:a libvorbis "$f"
        else
            ffmpeg -loglevel error -y -i "$SOUND" -af "adelay=$(awk "BEGIN { print int($1 * 1000) }"):all=1" -c:a libvorbis "$f"
        fi
    fi
    [ -s "$f" ] && echo "$f"
}

if [ "$1" = wake ]; then
    [ "$STATE" = SUSPENDED ] || exit 0
    f=$(padded only) && exec pw-play --media-role Notification "$f" 2>/dev/null
    exit 0
fi

wpctl get-volume @DEFAULT_AUDIO_SINK@ | grep -q MUTED && exit 0
[ -f "$PIDFILE" ] && kill "$(cat "$PIDFILE")" 2>/dev/null       # holding a key repeats fast: don't stack them
f=$SOUND
[ "$STATE" = SUSPENDED ] && f=$(padded "$LEAD") || true
pw-play --media-role Notification "${f:-$SOUND}" 2>/dev/null &
echo $! > "$PIDFILE"
