SmartestHome/hosts/touch-panel/configs/mic/mic-in-use

48 lines
2.1 KiB
Bash
Executable File

#!/bin/sh
# Is somebody recording this panel's microphone right now? Prints "1" or "0".
#
# Installed to /usr/local/bin/mic-in-use and polled by the touch dock
# (configs/eww/eww.yuck), which turns a "1" into a red LIVE badge.
#
# WHY THIS EXISTS: this panel can be used as a remote microphone by a desktop in
# another room (mic-follow/). That is a deliberate, useful feature, and it is also a
# microphone in a shared flat that somebody elsewhere can open. Such a thing has to be
# visible IN THE ROOM, not only in Home Assistant — anyone standing in the Loggia
# should be able to see that the panel is listening without knowing mic-follow exists.
#
# It reports what is actually capturing, from PipeWire, rather than trusting anything
# about who asked: a stray process recording for its own reasons lights the badge too,
# which is correct for an indicator whose whole job is to be believed.
#
# Monitor streams — something recording what the panel is PLAYING, like a visualiser —
# are not the microphone and must not light it up.
set -eu
command -v pactl >/dev/null 2>&1 || { echo 0; exit 0; }
if command -v jq >/dev/null 2>&1; then
sources="$(pactl -f json list sources 2>/dev/null || echo '[]')"
outputs="$(pactl -f json list source-outputs 2>/dev/null || echo '[]')"
jq -n --argjson s "$sources" --argjson o "$outputs" '
# The indexes of every monitor source, by either of the two ways one identifies
# itself.
[ $s[]
| select(((.properties["device.class"] // "") | ascii_downcase) == "monitor"
or (.name | endswith(".monitor")))
| .index ] as $monitors
| [ $o[] | select([.source] | inside($monitors) | not) ] | length > 0
| if . then 1 else 0 end
' 2>/dev/null || echo 0
exit 0
fi
# No jq: fall back to counting capture streams without being able to tell a monitor
# apart. That OVER-reports, which is the right direction to be wrong in for a warning
# light — a badge that is on too often gets questioned, one that is off too often gets
# trusted wrongly.
if pactl list source-outputs 2>/dev/null | grep -q "^Source Output #"; then
echo 1
else
echo 0
fi