#!/bin/sh
# Points mpv at a capture-card video device. Installed to /usr/local/bin/capture-view.
# Called by thinclient-agent (capture_control.py / main.py) when a capture source is
# selected — the thin client's "receiver box" input switching, see
# hosts/thin-client/README.md's "Capture-card / receiver-box viewing" section.
#
# Kill-and-relaunch, same shape as digest-browser/admin-browser: mpv has no live
# "change input" command worth scripting around, and there is no state to preserve
# across a source switch.
#
# --title=thinclient-capture-view is what makes this safe to relaunch: mpv is ALSO
# used for local media playback and the idle-gallery slideshow on this machine, and a
# bare `pkill -f mpv` here would kill those too. Scoping pkill/pgrep to this exact
# title — never anything broader — is the same fix already applied to
# digest-browser's/admin-browser's own pkill patterns (see the comment there); this
# script starts from that fix rather than needing it retrofitted later.
set -eu

DEVICE="${1:?capture-view: no device path given}"
AUDIO_CARD="${2:-}"

pkill -u "$(id -u)" -f "mpv .*--title=thinclient-capture-view" 2>/dev/null || true

# Wait for the old process to release the device node before relaunching.
i=0
while pgrep -u "$(id -u)" -f "mpv .*--title=thinclient-capture-view" >/dev/null 2>&1 && [ "$i" -lt 20 ]; do
  sleep 0.25
  i=$((i + 1))
done

# --untimed/--no-cache: this is a live source, not a file — play frames as they
# arrive rather than pacing/buffering the way mpv would for on-disk media.
set -- mpv \
  "av://v4l2:${DEVICE}" \
  --title=thinclient-capture-view \
  --profile=low-latency \
  --untimed \
  --no-cache

# Best-effort: many USB HDMI-capture dongles carry their embedded HDMI audio over a
# *separate* USB Audio Class interface rather than in the V4L2 stream itself — see
# capture_control.find_audio_card()'s docstring for how (and how confidently) this
# gets matched. Video-only playback (no crash) if none was found.
if [ -n "$AUDIO_CARD" ]; then
  set -- "$@" "--external-file=alsa://${AUDIO_CARD}"
fi

exec "$@"
