streamer movement

This commit is contained in:
legop3
2026-11-16 22:59:38 -05:00
parent b0de727d3e
commit 91c9194856
52 changed files with 909 additions and 2518 deletions
-88
View File
@@ -1,88 +0,0 @@
# Use the Google Voice HAT soundcard as the primary device by name (card id is "sndrpigooglevoi")
options snd_rpi_googlevoicehat_soundcard index=0
# Mix multiple playback clients in software with a fixed low-cost format.
pcm.dmixer {
type dmix
ipc_key 1024
ipc_perm 0666
slave {
pcm "hw:0,0"
format S16_LE
rate 16000
channels 1
period_time 0
period_size 1024
buffer_size 4096
}
}
# TTS volume control (used by default playback path).
pcm.tts_softvol {
type softvol
slave.pcm "dmixer"
control {
name "TTSMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Horn volume control.
pcm.horn_softvol {
type softvol
slave.pcm "dmixer"
control {
name "HornMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Forwarded audio volume control.
pcm.forward_softvol {
type softvol
slave.pcm "dmixer"
control {
name "ForwardMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Per-source playback PCMs.
pcm.tts {
type plug
slave.pcm "tts_softvol"
}
pcm.horn {
type plug
slave.pcm "horn_softvol"
}
pcm.forward {
type plug
slave.pcm "forward_softvol"
}
# Capture alias used by rover config defaults.
pcm.rovermic {
type plug
slave.pcm "hw:0,0"
}
# Defaults: TTS direct playback + raw capture on the HAT.
pcm.!default {
type asym
playback.pcm "tts"
capture.pcm "rovermic"
}
ctl.!default {
type hw
card 0
}
-102
View File
@@ -1,102 +0,0 @@
# Reference ALSA routing for the Debian laptop rover profile.
#
# This intentionally mirrors rover/asound.conf as closely as a normal PC can:
# one fixed hardware card, one dmix playback engine, separate softvol controls
# for TTS/horn/forwarded audio, and a raw capture alias for the rover mic.
#
# The Debian laptop installer no longer copies this file directly. It renders
# /etc/asound.conf from /etc/roverd-installer.env so laptops with HDMI as card 0
# can point these same logical mixer devices at their real speaker card.
#
# This is NOT meant to preserve normal desktop audio behavior. The laptop rover
# installer disables PipeWire/PulseAudio so roverd owns the audio hardware like
# the Raspberry Pi rover does. If the laptop's real speaker/mic card is not ALSA
# card 0, rerun the Debian laptop installer and answer the ALSA prompts using:
# aplay -l
# arecord -l
# Mix multiple playback clients in software with a fixed low-cost format.
pcm.dmixer {
type dmix
ipc_key 1024
ipc_perm 0666
slave {
pcm "hw:0,0"
format S16_LE
rate 16000
channels 1
period_time 0
period_size 1024
buffer_size 4096
}
}
# TTS volume control (used by default playback path).
pcm.tts_softvol {
type softvol
slave.pcm "dmixer"
control {
name "TTSMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Horn volume control.
pcm.horn_softvol {
type softvol
slave.pcm "dmixer"
control {
name "HornMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Forwarded audio volume control.
pcm.forward_softvol {
type softvol
slave.pcm "dmixer"
control {
name "ForwardMaster"
card 0
}
min_dB -60.0
max_dB 12.0
}
# Per-source playback PCMs.
pcm.tts {
type plug
slave.pcm "tts_softvol"
}
pcm.horn {
type plug
slave.pcm "horn_softvol"
}
pcm.forward {
type plug
slave.pcm "forward_softvol"
}
# Capture alias used by laptop rover config defaults.
pcm.rovermic {
type plug
slave.pcm "hw:0,0"
}
# Defaults: TTS direct playback + raw capture on the dedicated laptop sound card.
pcm.!default {
type asym
playback.pcm "tts"
capture.pcm "rovermic"
}
ctl.!default {
type hw
card 0
}
-139
View File
@@ -1,139 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
set +H
ENV_FILE="${ROVERD_MEDIA_ENV_FILE:-/var/lib/roverd/media.env}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Environment file ${ENV_FILE} missing; cannot start audio forward listener" >&2
exit 1
fi
# Load KEY=VALUE pairs from media.env without evaluating shell syntax. The forward URL is
# data produced by roverd and must never be interpreted as executable shell code.
load_env_file() {
local content=""
if [[ -r "$ENV_FILE" ]]; then
content="$(cat "$ENV_FILE")"
elif command -v sudo >/dev/null 2>&1; then
content="$(sudo -n cat "$ENV_FILE" 2>/dev/null || true)"
fi
if [[ -z "$content" ]]; then
echo "Cannot read ${ENV_FILE} (permission denied). Run as a user that can read it, or allow sudo -n for cat." >&2
exit 1
fi
local line key val
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
if [[ "$line" =~ ^[[:space:]]*export[[:space:]]+([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
elif [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
else
continue
fi
val="${val#${val%%[![:space:]]*}}"
val="${val%${val##*[![:space:]]}}"
if [[ "$val" =~ ^\".*\"$ ]]; then
val="${val:1:${#val}-2}"
elif [[ "$val" =~ ^\'.*\'$ ]]; then
val="${val:1:${#val}-2}"
fi
printf -v "$key" '%s' "$val"
export "$key"
done <<< "$content"
}
load_env_file
: "${ROVERD_AUDIO_PLAYBACK_ENABLE:?ROVERD_AUDIO_PLAYBACK_ENABLE not set in ${ENV_FILE}}"
if [[ "${ROVERD_AUDIO_PLAYBACK_ENABLE}" -ne 1 ]]; then
echo "Audio playback disabled by roverd media config; skipping audio forward listener" >&2
exit 0
fi
: "${ROVERD_AUDIO_PLAYBACK_FORWARD_URL:?ROVERD_AUDIO_PLAYBACK_FORWARD_URL not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_PLAYBACK_DEVICE:?ROVERD_AUDIO_PLAYBACK_DEVICE not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_PLAYBACK_NORMALIZE:?ROVERD_AUDIO_PLAYBACK_NORMALIZE not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER:?ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER not set in ${ENV_FILE}}"
PLAYBACK_DEVICE="${ROVERD_AUDIO_PLAYBACK_DEVICE}"
if [[ -n "${FFMPEG_BIN:-}" ]]; then
FFMPEG_BIN_PATH="$FFMPEG_BIN"
elif command -v ffmpeg >/dev/null 2>&1; then
FFMPEG_BIN_PATH="$(command -v ffmpeg)"
else
echo "ffmpeg not found; install it via apt install ffmpeg." >&2
exit 1
fi
if command -v aplay >/dev/null 2>&1; then
APLAY_BIN_PATH="$(command -v aplay)"
else
echo "aplay not found; install it via apt install alsa-utils." >&2
exit 1
fi
LAST_FFMPEG_STATUS="unknown"
LAST_APLAY_STATUS="unknown"
run_pipeline() {
set +e
local -a ffmpeg_args=(
-hide_banner
-loglevel warning
-fflags nobuffer
-flags low_delay
-analyzeduration 200k
-probesize 32k
# The forwarded-audio URL is RTSP. Pinning TCP avoids ffmpeg negotiating the
# separate unreliable RTP/UDP transport that the server intentionally disables.
-rtsp_transport tcp
-i "${ROVERD_AUDIO_PLAYBACK_FORWARD_URL}"
-vn
)
if [[ "${ROVERD_AUDIO_PLAYBACK_NORMALIZE}" -ne 0 ]]; then
ffmpeg_args+=(-af "${ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER}")
fi
ffmpeg_args+=(
-ac 1
-ar 16000
-f s16le
pipe:1
)
"${FFMPEG_BIN_PATH}" "${ffmpeg_args[@]}" \
| "${APLAY_BIN_PATH}" \
-q \
-D "${PLAYBACK_DEVICE}" \
-t raw \
-f S16_LE \
-r 16000 \
-c 1
local rc=$?
local -a statuses=("${PIPESTATUS[@]}")
LAST_FFMPEG_STATUS="${statuses[0]:-unknown}"
LAST_APLAY_STATUS="${statuses[1]:-unknown}"
set -e
return "${rc}"
}
trap 'kill 0 2>/dev/null' EXIT INT TERM
while true; do
if run_pipeline; then
exit 0
fi
echo "Audio forward listener exited ffmpeg=${LAST_FFMPEG_STATUS:-unknown} aplay=${LAST_APLAY_STATUS:-unknown}, restarting in 2s..." >&2
sleep 2
done
-171
View File
@@ -1,171 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
set +H
ENV_FILE="${ROVERD_MEDIA_ENV_FILE:-/var/lib/roverd/media.env}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Environment file ${ENV_FILE} missing; cannot publish audio" >&2
exit 1
fi
# Load KEY=VALUE pairs from media.env without evaluating shell syntax. URLs are data;
# sourcing this file would unnecessarily treat server-provided values as shell code.
load_env_file() {
local content=""
if [[ -r "$ENV_FILE" ]]; then
content="$(cat "$ENV_FILE")"
elif command -v sudo >/dev/null 2>&1; then
content="$(sudo -n cat "$ENV_FILE" 2>/dev/null || true)"
fi
if [[ -z "$content" ]]; then
echo "Cannot read ${ENV_FILE} (permission denied). Run as a user that can read it, or allow sudo -n for cat." >&2
exit 1
fi
local line key val
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
if [[ "$line" =~ ^[[:space:]]*export[[:space:]]+([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
elif [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
else
continue
fi
val="${val#${val%%[![:space:]]*}}"
val="${val%${val##*[![:space:]]}}"
if [[ "$val" =~ ^\".*\"$ ]]; then
val="${val:1:${#val}-2}"
elif [[ "$val" =~ ^\'.*\'$ ]]; then
val="${val:1:${#val}-2}"
fi
printf -v "$key" '%s' "$val"
export "$key"
done <<< "$content"
}
load_env_file
: "${ROVERD_AUDIO_CAPTURE_ENABLE:?ROVERD_AUDIO_CAPTURE_ENABLE not set in ${ENV_FILE}}"
if [[ "${ROVERD_AUDIO_CAPTURE_ENABLE}" -ne 1 ]]; then
echo "Audio capture disabled; skipping audio-only publisher" >&2
exit 0
fi
: "${ROVERD_AUDIO_CAPTURE_PUBLISH_URL:?ROVERD_AUDIO_CAPTURE_PUBLISH_URL not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_CAPTURE_DEVICE:?ROVERD_AUDIO_CAPTURE_DEVICE not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_CAPTURE_SAMPLE_RATE:?ROVERD_AUDIO_CAPTURE_SAMPLE_RATE not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_CAPTURE_CHANNELS:?ROVERD_AUDIO_CAPTURE_CHANNELS not set in ${ENV_FILE}}"
: "${ROVERD_AUDIO_CAPTURE_BITRATE:?ROVERD_AUDIO_CAPTURE_BITRATE not set in ${ENV_FILE}}"
CAPTURE_DEVICE="${ROVERD_AUDIO_CAPTURE_DEVICE}"
# At the default 48 kHz stereo S32_LE capture format, the old 65,536-byte ALSA
# buffer represented about 171 ms before ffmpeg could publish microphone audio:
# 65,536 / (48,000 samples * 2 channels * 4 bytes) = 0.1707 seconds
# Keep the defaults much smaller because this publisher feeds an interactive
# rover stream, where late-but-smooth audio is less useful than fresher audio.
# These remain environment-overridable so a noisy Pi or sound card can be tuned
# in the field without changing the installed script.
AUDIO_ALSA_BUFFER_BYTES="${AUDIO_ALSA_BUFFER_BYTES:-16384}"
AUDIO_ALSA_PERIOD_BYTES="${AUDIO_ALSA_PERIOD_BYTES:-1024}"
if [[ -n "${FFMPEG_BIN:-}" ]]; then
FFMPEG_BIN_PATH="$FFMPEG_BIN"
elif command -v ffmpeg >/dev/null 2>&1; then
FFMPEG_BIN_PATH="$(command -v ffmpeg)"
else
echo "ffmpeg not found; install it via apt install ffmpeg." >&2
exit 1
fi
run_pipeline() {
local -a pipeline_statuses=()
local ffmpeg_args=(
-hide_banner
-loglevel warning
-fflags nobuffer
-rtbufsize 0
-thread_queue_size 4096
# Match the raw ALSA stream exactly so ffmpeg does not guess the pipe
# format and so the published audio stays full-band stereo before the
# Opus encoder sees it.
-f s32le
-ar "${ROVERD_AUDIO_CAPTURE_SAMPLE_RATE}"
-ac "${ROVERD_AUDIO_CAPTURE_CHANNELS}"
-i pipe:0
# Keep the known-required microphone boost, but remove the old
# resample/downmix filter. That old filter threw away stereo and
# limited the stream to narrow 16 kHz mono before encoding.
-af "volume=20dB"
# Opus supports up to 510 kbps. Using that ceiling keeps the stream at
# the highest practical quality browsers and MediaMTX can carry without
# trying to push raw PCM through the live path.
-c:a libopus
-b:a "${ROVERD_AUDIO_CAPTURE_BITRATE}"
-ar:a "${ROVERD_AUDIO_CAPTURE_SAMPLE_RATE}"
-ac:a "${ROVERD_AUDIO_CAPTURE_CHANNELS}"
# Use the audio profile for quality. Latency is still controlled by the
# 20 ms Opus frame size and the low-buffering capture/publish options
# around the encoder.
-application audio
-frame_duration 20
-compression_level 0
# RTSP carries the existing Opus stream directly, avoiding MediaMTX's costly
# MPEG-TS demux without changing microphone capture or encoding quality. TCP is
# required for the same reliable local-network behavior as the video publisher.
-flush_packets 1
-muxdelay 0
-muxpreload 0
-f rtsp
-rtsp_transport tcp
"${ROVERD_AUDIO_CAPTURE_PUBLISH_URL}"
)
# The capture format comes from roverd's normalized media config. Keeping
# arecord and ffmpeg on the same env-backed values prevents the publisher
# script from quietly disagreeing with roverd.json about sample rate or
# channel count.
#
# The buffer and period are byte counts because arecord interprets -B/-F in
# microseconds only when the value has an explicit time suffix. Keeping them
# as byte-sized chunks gives direct control over the capture queue. The new
# defaults are roughly 43 ms total buffer and 2.7 ms wakeup periods at
# 48 kHz stereo S32_LE, which removes about 128 ms of avoidable capture
# latency compared with the old 65,536-byte buffer.
arecord -D "${CAPTURE_DEVICE}" -f S32_LE -c "${ROVERD_AUDIO_CAPTURE_CHANNELS}" -r "${ROVERD_AUDIO_CAPTURE_SAMPLE_RATE}" -B "${AUDIO_ALSA_BUFFER_BYTES}" -F "${AUDIO_ALSA_PERIOD_BYTES}" -q -t raw \
| "${FFMPEG_BIN_PATH}" "${ffmpeg_args[@]}"
pipeline_statuses=("${PIPESTATUS[@]}")
# PIPESTATUS belongs to the pipeline that just finished and is replaced by the next shell
# command. Capture it immediately, then return the publisher failure first because that is
# normally the reason arecord receives a secondary broken pipe.
LAST_ARECORD_STATUS="${pipeline_statuses[0]:-unknown}"
LAST_FFMPEG_STATUS="${pipeline_statuses[1]:-unknown}"
if [[ "${LAST_FFMPEG_STATUS}" != "0" ]]; then
return "${LAST_FFMPEG_STATUS}"
fi
return "${LAST_ARECORD_STATUS}"
}
trap 'kill 0 2>/dev/null' EXIT INT TERM
while true; do
if run_pipeline; then
exit 0
fi
echo "Audio-only publisher exited arecord=${LAST_ARECORD_STATUS:-unknown} ffmpeg=${LAST_FFMPEG_STATUS:-unknown}, restarting in 2s..." >&2
sleep 2
done
-202
View File
@@ -1,202 +0,0 @@
#!/usr/bin/env python3
import ctypes
import ctypes.util
import json
import os
import struct
import subprocess
import sys
ASSET_ROOT = "/opt/roverd/googletts"
LIB_PATH = os.path.join(ASSET_ROOT, "libchrometts.so")
VOICE_DIR = os.path.join(ASSET_ROOT, "en-us-x-multi-r30")
PIPELINE = "pipeline.pb"
PLAYBACK_DEVICE = "tts"
SAMPLE_RATE = "24000"
MAX_TEXT_CHARS = 512
VOICES = {
"sfg": "female",
"iob": "female",
"iog": "female",
"iol": "male",
"iom": "male",
"tpc": "female",
"tpd": "male",
"tpf": "female",
}
DEFAULT_VOICE = "tpf"
DEFAULT_PITCH = 1.0
DEFAULT_SPEED = 1.0
MIN_PITCH = 0.5
MAX_PITCH = 2.0
MIN_SPEED = 0.5
MAX_SPEED = 2.0
_runtime_handles = []
def load_shared_library(path):
mode = ctypes.RTLD_GLOBAL | getattr(os, "RTLD_NOW", 0)
return ctypes.CDLL(path, mode=mode)
def preload_runtime_libraries():
# Laptop-only workaround: some ChromeOS libchrometts builds reference
# compiler helper symbols such as __udivmodti4 without declaring the runtime
# library as an ELF dependency. Loading common compiler runtimes globally
# first makes those symbols visible before ctypes loads libchrometts.so.
for name in ("gcc_s", "atomic", "stdc++", "c++", "c++abi"):
lib = ctypes.util.find_library(name)
if not lib:
continue
try:
_runtime_handles.append(load_shared_library(lib))
except OSError:
pass
preload_runtime_libraries()
def varint(value):
out = bytearray()
while value >= 0x80:
out.append((value & 0x7F) | 0x80)
value >>= 7
out.append(value)
return bytes(out)
def field_bytes(number, payload):
return varint((number << 3) | 2) + varint(len(payload)) + payload
def field_float(number, value):
return varint((number << 3) | 5) + struct.pack("<f", float(value))
def build_utterance(text, pitch=1.0, speed=1.0):
params = field_float(2, pitch) + field_float(3, speed)
msg_b = field_bytes(1, text.encode("utf-8")) + field_bytes(20, params)
msg_a = field_bytes(1, msg_b)
return field_bytes(1, msg_a)
def build_speaker(name, gender):
return field_bytes(1, name.encode("utf-8")) + field_bytes(2, gender.encode("utf-8"))
class ChromeTTS:
def __init__(self):
self.lib = load_shared_library(LIB_PATH)
self.lib.GoogleTtsInit.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
self.lib.GoogleTtsInit.restype = ctypes.c_bool
self.lib.GoogleTtsInitBuffered.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int]
self.lib.GoogleTtsInitBuffered.restype = ctypes.c_bool
self.lib.GoogleTtsGetFramesInAudioBuffer.argtypes = []
self.lib.GoogleTtsGetFramesInAudioBuffer.restype = ctypes.c_size_t
self.lib.GoogleTtsReadBuffered.argtypes = [
ctypes.POINTER(ctypes.c_float),
ctypes.POINTER(ctypes.c_size_t),
]
self.lib.GoogleTtsReadBuffered.restype = ctypes.c_int
self.lib.GoogleTtsShutdown.argtypes = []
self.lib.GoogleTtsShutdown.restype = None
voice_dir = os.path.abspath(VOICE_DIR) + os.sep
pipeline = os.path.join(voice_dir, PIPELINE)
if not self.lib.GoogleTtsInit(pipeline.encode("utf-8"), voice_dir.encode("utf-8")):
raise RuntimeError("GoogleTtsInit failed")
self.frames = int(self.lib.GoogleTtsGetFramesInAudioBuffer())
if self.frames <= 0:
raise RuntimeError("invalid Google TTS audio buffer size")
self.buffer = (ctypes.c_float * self.frames)()
def speak_to_aplay(self, text, voice, pitch=DEFAULT_PITCH, speed=DEFAULT_SPEED):
voice = voice if voice in VOICES else DEFAULT_VOICE
pitch = clamp_float(pitch, MIN_PITCH, MAX_PITCH, DEFAULT_PITCH)
speed = clamp_float(speed, MIN_SPEED, MAX_SPEED, DEFAULT_SPEED)
text = text.strip()
if not text:
raise ValueError("text required")
text = text[:MAX_TEXT_CHARS]
utterance = build_utterance(text, pitch=pitch, speed=speed)
speaker = build_speaker(voice, VOICES[voice])
if not self.lib.GoogleTtsInitBuffered(utterance, speaker, len(utterance), len(speaker)):
raise RuntimeError("GoogleTtsInitBuffered failed")
player = subprocess.Popen(
["aplay", "-q", "-D", PLAYBACK_DEVICE, "-r", SAMPLE_RATE, "-f", "FLOAT_LE", "-c", "1"],
stdin=subprocess.PIPE,
)
try:
frames_written = ctypes.c_size_t(0)
while self.lib.GoogleTtsReadBuffered(self.buffer, ctypes.byref(frames_written)) > 0:
frames = int(frames_written.value)
if frames > 0:
player.stdin.write(ctypes.string_at(self.buffer, frames * ctypes.sizeof(ctypes.c_float)))
player.stdin.close()
rc = player.wait()
if rc != 0:
raise RuntimeError(f"aplay exited with {rc}")
finally:
if player.poll() is None:
player.kill()
player.wait()
def shutdown(self):
self.lib.GoogleTtsShutdown()
def respond(payload):
sys.stdout.write(json.dumps(payload, separators=(",", ":")) + "\n")
sys.stdout.flush()
def clamp_float(value, minimum, maximum, fallback):
try:
value = float(value)
except (TypeError, ValueError):
return fallback
if value <= 0:
return fallback
if value < minimum:
return minimum
if value > maximum:
return maximum
return value
def main():
try:
tts = ChromeTTS()
except Exception as exc:
respond({"ok": False, "error": str(exc)})
return 1
respond({"ok": True, "ready": True})
try:
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
request = json.loads(line)
tts.speak_to_aplay(
str(request.get("text") or ""),
str(request.get("voice") or DEFAULT_VOICE),
request.get("pitch", DEFAULT_PITCH),
request.get("speed", DEFAULT_SPEED),
)
respond({"ok": True})
except Exception as exc:
respond({"ok": False, "error": str(exc)})
finally:
tts.shutdown()
return 0
if __name__ == "__main__":
raise SystemExit(main())
+2 -2
View File
@@ -7,11 +7,11 @@ import subprocess
import sys
ASSET_ROOT = "/opt/roverd/googletts"
ASSET_ROOT = "/var/lib/roverd/googletts"
LIB_PATH = os.path.join(ASSET_ROOT, "libchrometts.so")
VOICE_DIR = os.path.join(ASSET_ROOT, "en-us-x-multi-r30")
PIPELINE = "pipeline.pb"
PLAYBACK_DEVICE = "tts"
PLAYBACK_DEVICE = "rover_tts"
SAMPLE_RATE = "24000"
MAX_TEXT_CHARS = 512
-145
View File
@@ -1,145 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
set +H
ENV_FILE="${ROVERD_MEDIA_ENV_FILE:-/var/lib/roverd/media.env}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Environment file ${ENV_FILE} missing; cannot publish laptop video" >&2
exit 1
fi
# Load roverd's generated media.env as data instead of sourcing it as shell. URLs are
# configuration data, so evaluating the file would be both fragile and unnecessary.
load_env_file() {
local content=""
if [[ -r "$ENV_FILE" ]]; then
content="$(cat "$ENV_FILE")"
elif command -v sudo >/dev/null 2>&1; then
content="$(sudo -n cat "$ENV_FILE" 2>/dev/null || true)"
fi
if [[ -z "$content" ]]; then
echo "Cannot read ${ENV_FILE} (permission denied). Run as a user that can read it, or allow sudo -n for cat." >&2
exit 1
fi
local line key val
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
if [[ "$line" =~ ^[[:space:]]*export[[:space:]]+([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
elif [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
else
continue
fi
val="${val#${val%%[![:space:]]*}}"
val="${val%${val##*[![:space:]]}}"
if [[ "$val" =~ ^\".*\"$ ]]; then
val="${val:1:${#val}-2}"
elif [[ "$val" =~ ^\'.*\'$ ]]; then
val="${val:1:${#val}-2}"
fi
printf -v "$key" '%s' "$val"
export "$key"
done <<< "$content"
}
load_env_file
: "${ROVERD_VIDEO_ENABLE:?ROVERD_VIDEO_ENABLE not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_PUBLISH_URL:?ROVERD_VIDEO_PUBLISH_URL not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_DEVICE:?ROVERD_VIDEO_DEVICE not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_INPUT_FORMAT:?ROVERD_VIDEO_INPUT_FORMAT not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_WIDTH:?ROVERD_VIDEO_WIDTH not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_HEIGHT:?ROVERD_VIDEO_HEIGHT not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_FPS:?ROVERD_VIDEO_FPS not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_BITRATE:?ROVERD_VIDEO_BITRATE not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_INVERT:?ROVERD_VIDEO_INVERT not set in ${ENV_FILE}}"
if [[ "${ROVERD_VIDEO_ENABLE}" -ne 1 ]]; then
echo "Laptop video publisher disabled by roverd media config; skipping" >&2
exit 0
fi
if [[ -z "${ROVERD_VIDEO_DEVICE}" ]]; then
echo "ROVERD_VIDEO_DEVICE is required for the debian-laptop V4L2 publisher" >&2
exit 1
fi
INPUT_FORMAT_ARGS=()
if [[ -n "${ROVERD_VIDEO_INPUT_FORMAT}" ]]; then
# Many laptop webcams expose both compressed MJPEG and raw YUYV modes. The
# wrong negotiated format can still produce a decodable stream, but the
# picture appears as green/noisy mush because ffmpeg is interpreting the
# frame bytes with the wrong pixel format. Passing input_format pins V4L2 to
# the camera mode selected in roverd.json.
INPUT_FORMAT_ARGS=(-input_format "${ROVERD_VIDEO_INPUT_FORMAT}")
fi
if [[ -n "${FFMPEG_BIN:-}" ]]; then
FFMPEG_BIN_PATH="$FFMPEG_BIN"
elif command -v ffmpeg >/dev/null 2>&1; then
FFMPEG_BIN_PATH="$(command -v ffmpeg)"
else
echo "ffmpeg not found; install it via apt install ffmpeg." >&2
exit 1
fi
VIDEO_FILTER_ARGS=()
if [[ "${ROVERD_VIDEO_INVERT}" -ne 0 ]]; then
# The Pi publisher uses libcamera rotation. With a generic webcam, ffmpeg's
# transpose pair gives the same 180-degree correction without assuming a
# camera-specific driver feature.
VIDEO_FILTER_ARGS=(-vf "transpose=2,transpose=2")
fi
run_pipeline() {
# Keep laptop rovers on the same transport contract as Pi camera rovers. This changes
# only the encoded stream's carrier; V4L2 capture and H264 encoding remain untouched.
"${FFMPEG_BIN_PATH}" \
-hide_banner \
-loglevel warning \
-fflags nobuffer \
-flags low_delay \
-thread_queue_size 4096 \
-f v4l2 \
"${INPUT_FORMAT_ARGS[@]}" \
-framerate "${ROVERD_VIDEO_FPS}" \
-video_size "${ROVERD_VIDEO_WIDTH}x${ROVERD_VIDEO_HEIGHT}" \
-i "${ROVERD_VIDEO_DEVICE}" \
"${VIDEO_FILTER_ARGS[@]}" \
-an \
-c:v libx264 \
-preset veryfast \
-tune zerolatency \
-profile:v baseline \
-pix_fmt yuv420p \
-b:v "${ROVERD_VIDEO_BITRATE}" \
-maxrate "${ROVERD_VIDEO_BITRATE}" \
-bufsize "$((ROVERD_VIDEO_BITRATE / 2))" \
-g "${ROVERD_VIDEO_FPS}" \
-keyint_min "${ROVERD_VIDEO_FPS}" \
-sc_threshold 0 \
-flush_packets 1 \
-muxdelay 0 \
-muxpreload 0 \
-f rtsp \
-rtsp_transport tcp \
"${ROVERD_VIDEO_PUBLISH_URL}"
}
while true; do
if run_pipeline; then
exit 0
fi
echo "Debian laptop video publisher exited, restarting in 2s..." >&2
sleep 2
done
-37
View File
@@ -1,37 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# These publishers contain hardware-facing infinite retry loops, so executing them in a unit
# test would require unsafe process-group traps and fake camera/ALSA devices. Pin the small
# transport boundary directly instead: every publisher must request RTSP/TCP and none may
# reintroduce the high-latency MPEG-TS muxer.
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
assert_rtsp_tcp() {
local file="$1"
if ! grep -q -- '-f rtsp' "$file"; then
echo "Missing RTSP muxer in $file" >&2
exit 1
fi
if ! grep -q -- '-rtsp_transport tcp' "$file"; then
echo "Missing RTSP/TCP pin in $file" >&2
exit 1
fi
if grep -q -- '-f mpegts' "$file"; then
echo "Unexpected MPEG-TS muxer in $file" >&2
exit 1
fi
}
assert_rtsp_tcp "$SCRIPT_DIR/video-publisher.sh"
assert_rtsp_tcp "$SCRIPT_DIR/debian-laptop-video-publisher.sh"
assert_rtsp_tcp "$SCRIPT_DIR/audio-only-publisher.sh"
# The speaker path reads rather than publishes, so it has no output muxer. It must still pin
# RTSP/TCP before its input URL to match the server's TCP-only listener.
if ! grep -q -- '-rtsp_transport tcp' "$SCRIPT_DIR/audio-forward-listener.sh"; then
echo "Missing RTSP/TCP input pin in audio-forward-listener.sh" >&2
exit 1
fi
echo "Media publisher transport checks passed"
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env bash
set -euo pipefail
log() { echo "$*"; }
apt-get update
apt-get install -y flite espeak python3 curl xz-utils unzip alsa-utils libc++1 libc++abi1
install_google_tts_assets() {
local asset_dir="/var/lib/roverd/googletts"
local voice_dir="${asset_dir}/en-us-x-multi-r30"
local dist_url="https://storage.googleapis.com/chromeos-localmirror/distfiles/googletts-26.5.tar.xz"
local tmp_dir
local lib_member=""
local member
if [[ -f "${asset_dir}/libchrometts.so" && -f "${voice_dir}/pipeline.pb" ]]; then
log "Google Chrome TTS assets already installed; skipping download"
return
fi
tmp_dir="$(mktemp -d)"
log "Downloading Google Chrome TTS assets for this architecture..."
if ! curl -L -o "${tmp_dir}/googletts-26.5.tar.xz" "$dist_url"; then
rm -rf "$tmp_dir"
log "WARNING: failed to download Google Chrome TTS assets; chromegtts will be unavailable"
return
fi
local -a candidate_libs=()
case "$(dpkg --print-architecture)" in
arm64)
candidate_libs=(libchrometts_arm64.so)
;;
armhf)
if [[ "$(uname -m)" == armv6l ]]; then
log "Chrome TTS has no ARMv6 library; use flite or espeak on this host"
rm -rf "$tmp_dir"
return
fi
candidate_libs=(libchrometts_armv7.so)
;;
amd64)
candidate_libs=(libchrometts_x86_64.so libchrometts_amd64.so libchrometts_x64.so libchrometts.so)
;;
i386)
candidate_libs=(libchrometts_x86.so libchrometts_i386.so libchrometts.so)
;;
*)
log "WARNING: unsupported Chrome TTS architecture $(uname -m); skipping Google TTS assets"
rm -rf "$tmp_dir"
return
;;
esac
for member in "${candidate_libs[@]}"; do
if tar -tf "${tmp_dir}/googletts-26.5.tar.xz" "$member" >/dev/null 2>&1; then
lib_member="$member"
break
fi
done
if [[ -z "$lib_member" ]]; then
log "WARNING: no libchrometts library matching $(uname -m) found in Google TTS archive; chromegtts will be unavailable"
rm -rf "$tmp_dir"
return
fi
if ! tar -xf "${tmp_dir}/googletts-26.5.tar.xz" -C "$tmp_dir" en-us-x-multi.zvoice "$lib_member"; then
rm -rf "$tmp_dir"
log "WARNING: failed to unpack Google Chrome TTS assets; chromegtts will be unavailable"
return
fi
install -d -o root -g root -m 0755 "$asset_dir"
install -o root -g root -m 0644 "${tmp_dir}/${lib_member}" "${asset_dir}/libchrometts.so"
rm -rf "$voice_dir"
install -d -o root -g root -m 0755 "$voice_dir"
unzip -q "${tmp_dir}/en-us-x-multi.zvoice" -d "$voice_dir"
chown -R root:root "$asset_dir"
find "$asset_dir" -type d -exec chmod 0755 {} +
find "$asset_dir" -type f -exec chmod 0644 {} +
rm -rf "$tmp_dir"
log "Installed Google Chrome TTS assets to $asset_dir using $lib_member"
}
install_google_tts_assets
-160
View File
@@ -1,160 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# Keep history expansion off so values containing "!" are safe.
set +H
ENV_FILE="${ROVERD_MEDIA_ENV_FILE:-/var/lib/roverd/media.env}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Environment file ${ENV_FILE} missing; cannot publish" >&2
exit 1
fi
# Load KEY=VALUE pairs from ENV_FILE WITHOUT evaluating shell metacharacters.
# This makes URLs containing characters like '&' and '#!' safe without requiring quoting.
load_env_file() {
local content=""
if [[ -r "$ENV_FILE" ]]; then
content="$(cat "$ENV_FILE")"
elif command -v sudo >/dev/null 2>&1; then
# Try to read via sudo without prompting (useful when the service runs as an unprivileged user)
content="$(sudo -n cat "$ENV_FILE" 2>/dev/null || true)"
fi
if [[ -z "$content" ]]; then
echo "Cannot read ${ENV_FILE} (permission denied). Run as a user that can read it, or allow sudo -n for cat." >&2
exit 1
fi
local line key val
while IFS= read -r line || [[ -n "$line" ]]; do
# Skip blank lines and full-line comments.
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
# Support optional leading 'export '
if [[ "$line" =~ ^[[:space:]]*export[[:space:]]+([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
elif [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
else
# Ignore anything that isn't a simple assignment.
continue
fi
# Trim leading/trailing whitespace in value.
val="${val#${val%%[![:space:]]*}}"
val="${val%${val##*[![:space:]]}}"
# If value is wrapped in matching single or double quotes, unwrap.
if [[ "$val" =~ ^\".*\"$ ]]; then
val="${val:1:${#val}-2}"
elif [[ "$val" =~ ^\'.*\'$ ]]; then
val="${val:1:${#val}-2}"
fi
# Assign without evaluation.
printf -v "$key" '%s' "$val"
export "$key"
done <<< "$content"
}
load_env_file
: "${ROVERD_VIDEO_ENABLE:?ROVERD_VIDEO_ENABLE not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_PUBLISH_URL:?ROVERD_VIDEO_PUBLISH_URL not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_WIDTH:?ROVERD_VIDEO_WIDTH not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_HEIGHT:?ROVERD_VIDEO_HEIGHT not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_FPS:?ROVERD_VIDEO_FPS not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_BITRATE:?ROVERD_VIDEO_BITRATE not set in ${ENV_FILE}}"
: "${ROVERD_VIDEO_INVERT:?ROVERD_VIDEO_INVERT not set in ${ENV_FILE}}"
if [[ "${ROVERD_VIDEO_ENABLE}" -ne 1 ]]; then
echo "Video publisher disabled by roverd media config; skipping" >&2
exit 0
fi
# The inversion decision is made in roverd.json and written into media.env, so
# this script only converts the configured logical value into libcamera flags.
FLIP_ARGS=()
if [[ "${ROVERD_VIDEO_INVERT}" -ne 0 ]]; then
FLIP_ARGS=(--rotation 180)
fi
MODE_ARGS=()
if [[ -n "${ROVERD_VIDEO_SENSOR_MODE:-}" ]]; then
MODE_ARGS=(--mode "${ROVERD_VIDEO_SENSOR_MODE}")
fi
if [[ -n "${LIBCAMERA_BIN:-}" ]]; then
LIBCAMERA_BIN_PATH="$LIBCAMERA_BIN"
elif command -v rpicam-vid >/dev/null 2>&1; then
LIBCAMERA_BIN_PATH="$(command -v rpicam-vid)"
elif command -v libcamera-vid >/dev/null 2>&1; then
LIBCAMERA_BIN_PATH="$(command -v libcamera-vid)"
else
echo "Neither rpicam-vid nor libcamera-vid found; install libcamera-apps." >&2
exit 1
fi
if [[ -n "${FFMPEG_BIN:-}" ]]; then
FFMPEG_BIN_PATH="$FFMPEG_BIN"
elif command -v ffmpeg >/dev/null 2>&1; then
FFMPEG_BIN_PATH="$(command -v ffmpeg)"
else
echo "ffmpeg not found; install it via apt install ffmpeg." >&2
exit 1
fi
run_pipeline() {
# MPEG-TS added most of the former rover-to-browser latency inside MediaMTX's
# demuxer. RTSP carries the same encoded H264 without changing the camera or codec.
# TCP is explicit because plain RTSP/RTP over UDP has no retransmission and proved
# unreliable even though MediaMTX still reported the incomplete stream as ready.
"${LIBCAMERA_BIN_PATH}" \
--inline \
--timeout 0 \
"${MODE_ARGS[@]}" \
--width "${ROVERD_VIDEO_WIDTH}" \
--height "${ROVERD_VIDEO_HEIGHT}" \
"${FLIP_ARGS[@]}" \
--framerate "${ROVERD_VIDEO_FPS}" \
--bitrate "${ROVERD_VIDEO_BITRATE}" \
--codec h264 \
--intra 120 \
--profile baseline \
--denoise auto \
--nopreview \
--metering centre \
--ev 0.1 \
--awb auto \
--saturation 0.6 \
--brightness 0 \
--output - \
| "${FFMPEG_BIN_PATH}" \
-hide_banner \
-loglevel warning \
-fflags nobuffer \
-use_wallclock_as_timestamps 1 \
-f h264 \
-i pipe:0 \
-c:v copy \
-an \
-flush_packets 1 \
-muxdelay 0 \
-muxpreload 0 \
-f rtsp \
-rtsp_transport tcp \
"${ROVERD_VIDEO_PUBLISH_URL}"
}
while true; do
if run_pipeline; then
exit 0
fi
echo "Video publisher exited, restarting in 2s..." >&2
sleep 2
done
-79
View File
@@ -1,79 +0,0 @@
#!/usr/bin/env bash
CONFIG_DEST="/etc/roverd.json"
log() {
echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] $*"
}
ensure_user() {
local user="$1"
local groups="${2:-}"
local existing_groups=""
local group
if [[ -n "$groups" ]]; then
IFS=',' read -ra group_list <<< "$groups"
for group in "${group_list[@]}"; do
if getent group "$group" >/dev/null 2>&1; then
existing_groups="${existing_groups:+$existing_groups,}$group"
else
# Different Debian-family installs expose slightly different
# hardware groups. Skipping missing optional groups lets one
# profile script cover ordinary laptops and Raspberry Pi OS.
log "Skipping missing system group '$group' for $user"
fi
done
fi
if ! id -u "$user" >/dev/null 2>&1; then
if [[ -n "$existing_groups" ]]; then
useradd -r -s /usr/sbin/nologin -G "$existing_groups" "$user"
else
useradd -r -s /usr/sbin/nologin "$user"
fi
elif [[ -n "$existing_groups" ]]; then
usermod -a -G "$existing_groups" "$user"
fi
}
require_root() {
if [[ "${EUID}" -ne 0 ]]; then
echo "Please run as root (sudo)" >&2
exit 1
fi
}
validate_install_inputs() {
if [[ ! -f "$BINARY_SRC" ]]; then
echo "Binary not found at $BINARY_SRC" >&2
exit 1
fi
if [[ ! -f "$CONFIG_SRC" ]]; then
echo "Config source not found at $CONFIG_SRC" >&2
exit 1
fi
}
install_roverd_binary() {
ensure_user roverd "$ROVERD_GROUPS"
install -o root -g root -m 0755 "$BINARY_SRC" /usr/local/bin/roverd
log "Installed roverd binary for profile $PROFILE"
}
install_roverd_config() {
CONFIG_EXISTS=0
if [[ -f "$CONFIG_DEST" ]]; then
CONFIG_EXISTS=1
log "Existing $CONFIG_DEST found; leaving it in place"
else
install -D -o root -g root -m 0600 "$CONFIG_SRC" "$CONFIG_DEST"
log "Installed sample config to $CONFIG_DEST (edit before starting service)"
fi
}
install_roverd_unit() {
install -m 0644 rover/systemd/roverd.service /etc/systemd/system/roverd.service
log "Installed roverd systemd unit"
}
-425
View File
@@ -1,425 +0,0 @@
#!/usr/bin/env bash
install_debian_laptop_deps() {
# The laptop rover is a dedicated appliance, not a normal desktop/laptop audio
# install. Keep this package set intentionally close to the Pi profile so the
# same roverd TTS/playback/capture code paths are available on both targets.
if command -v ffmpeg >/dev/null 2>&1 \
&& command -v arecord >/dev/null 2>&1 \
&& command -v aplay >/dev/null 2>&1 \
&& command -v amixer >/dev/null 2>&1 \
&& command -v v4l2-ctl >/dev/null 2>&1 \
&& command -v flite >/dev/null 2>&1 \
&& command -v espeak >/dev/null 2>&1 \
&& command -v python3 >/dev/null 2>&1 \
&& command -v curl >/dev/null 2>&1 \
&& command -v xz >/dev/null 2>&1 \
&& command -v unzip >/dev/null 2>&1 \
&& ldconfig -p 2>/dev/null | grep -q 'libgcc_s\.so\.1' \
&& ldconfig -p 2>/dev/null | grep -q 'libstdc\+\+\.so\.6' \
&& ldconfig -p 2>/dev/null | grep -q 'libc++\.so\.1' \
&& ldconfig -p 2>/dev/null | grep -q 'libc++abi\.so\.1'; then
log "Debian laptop media/audio/TTS dependencies already installed; skipping apt install"
return
fi
log "Installing Debian laptop rover dependencies (ffmpeg, ALSA tools, V4L2 tools, flite/espeak, Chrome TTS runtime deps)..."
apt-get update
apt-get install -y --no-install-recommends \
ffmpeg alsa-utils v4l-utils ca-certificates flite espeak python3 curl xz-utils unzip libasound2-plugins libgcc-s1 libstdc++6 libc++1 libc++abi1 \
|| apt-get install -y --no-install-recommends \
ffmpeg alsa-utils v4l-utils ca-certificates flite espeak python3 curl xz-utils unzip libasound2-plugins libgcc-s1 libstdc++6 libc++1-14 libc++abi1-14
}
DEBIAN_LAPTOP_INSTALLER_CONFIG="/etc/roverd-installer.env"
disable_debian_laptop_desktop_audio_stack() {
# This profile is for a dedicated rover laptop. PipeWire/PulseAudio are good
# desktop defaults, but they can grab the hardware device and make the rover's
# root/systemd ALSA services fail or route through a moving per-user graph.
# Mask them globally and kill already-running instances so ALSA owns the box,
# which is the closest behavior to the Pi rover appliance setup.
log "Disabling desktop audio daemons for dedicated laptop rover audio"
local -a user_units=(
pipewire.service
pipewire.socket
pipewire-pulse.service
pipewire-pulse.socket
wireplumber.service
pulseaudio.service
pulseaudio.socket
)
if command -v systemctl >/dev/null 2>&1; then
systemctl --global disable "${user_units[@]}" >/dev/null 2>&1 || true
systemctl --global mask "${user_units[@]}" >/dev/null 2>&1 || true
fi
pkill -x pipewire >/dev/null 2>&1 || true
pkill -x pipewire-pulse >/dev/null 2>&1 || true
pkill -x wireplumber >/dev/null 2>&1 || true
pkill -x pulseaudio >/dev/null 2>&1 || true
}
derive_debian_laptop_alsa_card_from_device() {
local device="$1"
# The common ALSA hardware device shape is hw:CARD,DEVICE. Pulling the card
# number from that string gives the installer a useful default while still
# allowing the prompt to handle named cards or uncommon PCM strings.
if [[ "$device" =~ ^hw:([0-9]+),[0-9]+$ ]]; then
printf '%s\n' "${BASH_REMATCH[1]}"
return
fi
printf '0\n'
}
read_debian_laptop_installer_value() {
local prompt="$1"
local default_value="$2"
local value=""
# Prompting through /dev/tty keeps this usable even when the installer is
# launched through sudo with stdin redirected. The caller already checks for
# an interactive terminal before reaching this function, so failure here is
# genuinely unexpected and should stop the install instead of guessing.
read -r -p "${prompt} [${default_value}]: " value </dev/tty
if [[ -z "$value" ]]; then
value="$default_value"
fi
printf '%s\n' "$value"
}
validate_debian_laptop_alsa_config() {
# The PCM fields are written inside quoted ALSA strings, so keep them to the
# device spellings ALSA normally uses for hardware/plugin PCMs. Rejecting
# whitespace and shell/config punctuation prevents a bad installer config
# from generating an asound.conf that changes structure instead of values.
if [[ ! "$ROVERD_ALSA_PLAYBACK_DEVICE" =~ ^[A-Za-z0-9_.,:+/-]+$ ]]; then
echo "Invalid ROVERD_ALSA_PLAYBACK_DEVICE: $ROVERD_ALSA_PLAYBACK_DEVICE" >&2
exit 1
fi
if [[ ! "$ROVERD_ALSA_CAPTURE_DEVICE" =~ ^[A-Za-z0-9_.,:+/-]+$ ]]; then
echo "Invalid ROVERD_ALSA_CAPTURE_DEVICE: $ROVERD_ALSA_CAPTURE_DEVICE" >&2
exit 1
fi
# Softvol controls and ctl.!default need the playback card, because
# TTSMaster, HornMaster, and ForwardMaster are all playback mixer controls.
# Keep this numeric to match the prompt and avoid needing quoted ALSA card
# ids in the generated config.
if [[ ! "$ROVERD_ALSA_PLAYBACK_CARD" =~ ^[0-9]+$ ]]; then
echo "Invalid ROVERD_ALSA_PLAYBACK_CARD: $ROVERD_ALSA_PLAYBACK_CARD" >&2
exit 1
fi
}
load_debian_laptop_installer_config_file() {
local config_path="$1"
local line key val
# Read only the small allowlist this installer owns. Avoid sourcing the file
# because it lives in /etc and is meant to be installer data, not shell code.
while IFS= read -r line || [[ -n "$line" ]]; do
[[ "$line" =~ ^[[:space:]]*$ ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
if [[ "$line" =~ ^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2]}"
else
continue
fi
val="${val#${val%%[![:space:]]*}}"
val="${val%${val##*[![:space:]]}}"
if [[ "$val" =~ ^\".*\"$ ]]; then
val="${val:1:${#val}-2}"
elif [[ "$val" =~ ^\'.*\'$ ]]; then
val="${val:1:${#val}-2}"
fi
case "$key" in
ROVERD_ALSA_PLAYBACK_DEVICE|ROVERD_ALSA_PLAYBACK_CARD|ROVERD_ALSA_CAPTURE_DEVICE)
printf -v "$key" '%s' "$val"
export "$key"
;;
esac
done < "$config_path"
}
write_debian_laptop_installer_config_file() {
local config_path="$1"
local tmp_path
tmp_path="$(mktemp)"
# This file is intentionally plain KEY=VALUE shell-style data so future
# installs can reuse the same laptop-specific card choices without asking
# again. It is still parsed by an allowlist reader instead of sourced.
cat > "$tmp_path" <<EOF
# Created by install_roverd.sh for the Debian laptop rover profile.
# These values choose the physical ALSA hardware behind the rover's logical
# mixer devices: tts, horn, forward, default playback, and rovermic capture.
ROVERD_ALSA_PLAYBACK_DEVICE="${ROVERD_ALSA_PLAYBACK_DEVICE}"
ROVERD_ALSA_PLAYBACK_CARD="${ROVERD_ALSA_PLAYBACK_CARD}"
ROVERD_ALSA_CAPTURE_DEVICE="${ROVERD_ALSA_CAPTURE_DEVICE}"
EOF
install -o root -g root -m 0644 "$tmp_path" "$config_path"
rm -f "$tmp_path"
}
load_or_create_debian_laptop_alsa_config() {
if [[ -f "$DEBIAN_LAPTOP_INSTALLER_CONFIG" ]]; then
load_debian_laptop_installer_config_file "$DEBIAN_LAPTOP_INSTALLER_CONFIG"
log "Using Debian laptop ALSA installer config from $DEBIAN_LAPTOP_INSTALLER_CONFIG"
elif [[ -n "${ROVERD_ALSA_PLAYBACK_DEVICE:-}" && -n "${ROVERD_ALSA_PLAYBACK_CARD:-}" && -n "${ROVERD_ALSA_CAPTURE_DEVICE:-}" ]]; then
# This keeps unattended installs possible without adding a pile of CLI
# flags. The generated /etc file still becomes the durable source for
# future installs on the same laptop.
validate_debian_laptop_alsa_config
write_debian_laptop_installer_config_file "$DEBIAN_LAPTOP_INSTALLER_CONFIG"
log "Wrote Debian laptop ALSA installer config to $DEBIAN_LAPTOP_INSTALLER_CONFIG from environment"
else
if ! { true </dev/tty >/dev/tty; } 2>/dev/null; then
echo "Missing $DEBIAN_LAPTOP_INSTALLER_CONFIG and no interactive terminal is available for ALSA setup." >&2
echo "Run sudo ./rover/install_roverd.sh --debian-laptop once from a terminal, then reuse the generated config for future installs." >&2
exit 1
fi
log "No $DEBIAN_LAPTOP_INSTALLER_CONFIG found; creating Debian laptop ALSA installer config"
if command -v aplay >/dev/null 2>&1; then
echo "Playback devices from aplay -l:" >/dev/tty
aplay -l >/dev/tty 2>/dev/tty || true
fi
if command -v arecord >/dev/null 2>&1; then
echo "Capture devices from arecord -l:" >/dev/tty
arecord -l >/dev/tty 2>/dev/tty || true
fi
ROVERD_ALSA_PLAYBACK_DEVICE="$(read_debian_laptop_installer_value "ALSA playback device for rover speaker output" "${ROVERD_ALSA_PLAYBACK_DEVICE:-hw:0,0}")"
ROVERD_ALSA_PLAYBACK_CARD="$(read_debian_laptop_installer_value "ALSA playback card number for mixer controls" "${ROVERD_ALSA_PLAYBACK_CARD:-$(derive_debian_laptop_alsa_card_from_device "$ROVERD_ALSA_PLAYBACK_DEVICE")}")"
ROVERD_ALSA_CAPTURE_DEVICE="$(read_debian_laptop_installer_value "ALSA capture device for rover microphone input" "${ROVERD_ALSA_CAPTURE_DEVICE:-$ROVERD_ALSA_PLAYBACK_DEVICE}")"
validate_debian_laptop_alsa_config
write_debian_laptop_installer_config_file "$DEBIAN_LAPTOP_INSTALLER_CONFIG"
log "Wrote Debian laptop ALSA installer config to $DEBIAN_LAPTOP_INSTALLER_CONFIG"
fi
ROVERD_ALSA_PLAYBACK_DEVICE="${ROVERD_ALSA_PLAYBACK_DEVICE:-hw:0,0}"
ROVERD_ALSA_PLAYBACK_CARD="${ROVERD_ALSA_PLAYBACK_CARD:-$(derive_debian_laptop_alsa_card_from_device "$ROVERD_ALSA_PLAYBACK_DEVICE")}"
ROVERD_ALSA_CAPTURE_DEVICE="${ROVERD_ALSA_CAPTURE_DEVICE:-$ROVERD_ALSA_PLAYBACK_DEVICE}"
validate_debian_laptop_alsa_config
}
render_debian_laptop_asound_config() {
local tmp_path
tmp_path="$(mktemp)"
# The rover-facing ALSA names stay stable even when the laptop's physical
# sound card changes. dmixer owns the one real playback PCM, while tts,
# horn, and forward each wrap that mixer with a separate softvol control.
cat > "$tmp_path" <<EOF
# Dedicated ALSA routing for the Debian laptop rover profile.
#
# Generated by install_roverd.sh from $DEBIAN_LAPTOP_INSTALLER_CONFIG.
# Change the physical devices there, then rerun the Debian laptop installer.
#
# Logical playback devices:
# tts - default text-to-speech output with TTSMaster softvol
# horn - horn synth output with HornMaster softvol
# forward - browser-forwarded audio with ForwardMaster softvol
# default - TTS playback plus rovermic capture
#
# Physical routing selected for this laptop:
# playback PCM: ${ROVERD_ALSA_PLAYBACK_DEVICE}
# playback card: ${ROVERD_ALSA_PLAYBACK_CARD}
# capture PCM: ${ROVERD_ALSA_CAPTURE_DEVICE}
# Mix multiple playback clients in software with a fixed low-cost format.
pcm.dmixer {
type dmix
ipc_key 1024
ipc_perm 0666
slave {
pcm "${ROVERD_ALSA_PLAYBACK_DEVICE}"
format S16_LE
rate 16000
channels 1
period_time 0
period_size 1024
buffer_size 4096
}
}
# TTS volume control. TTS uses the default playback route, so this control lets
# generated speech move independently from horns and forwarded browser audio.
pcm.tts_softvol {
type softvol
slave.pcm "dmixer"
control {
name "TTSMaster"
card ${ROVERD_ALSA_PLAYBACK_CARD}
}
min_dB -60.0
max_dB 12.0
}
# Horn volume control. The horn synth opens the logical "horn" device, which
# keeps horn loudness adjustable without changing the shared hardware PCM.
pcm.horn_softvol {
type softvol
slave.pcm "dmixer"
control {
name "HornMaster"
card ${ROVERD_ALSA_PLAYBACK_CARD}
}
min_dB -60.0
max_dB 12.0
}
# Forwarded audio volume control. The browser-audio listener opens "forward",
# so remote audio can be mixed with local rover sounds without bypassing dmix.
pcm.forward_softvol {
type softvol
slave.pcm "dmixer"
control {
name "ForwardMaster"
card ${ROVERD_ALSA_PLAYBACK_CARD}
}
min_dB -60.0
max_dB 12.0
}
# Per-source playback PCMs.
pcm.tts {
type plug
slave.pcm "tts_softvol"
}
pcm.horn {
type plug
slave.pcm "horn_softvol"
}
pcm.forward {
type plug
slave.pcm "forward_softvol"
}
# Capture alias used by laptop rover config defaults. Capture is deliberately
# separate from playback because laptop speakers and microphones often appear
# on different ALSA cards.
pcm.rovermic {
type plug
slave.pcm "${ROVERD_ALSA_CAPTURE_DEVICE}"
}
# Defaults: TTS direct playback + raw capture on the selected laptop devices.
pcm.!default {
type asym
playback.pcm "tts"
capture.pcm "rovermic"
}
ctl.!default {
type hw
card ${ROVERD_ALSA_PLAYBACK_CARD}
}
EOF
install -o root -g root -m 0644 "$tmp_path" /etc/asound.conf
rm -f "$tmp_path"
log "Installed dedicated Debian laptop ALSA config to /etc/asound.conf using playback ${ROVERD_ALSA_PLAYBACK_DEVICE}"
}
install_debian_laptop_audio_support() {
load_or_create_debian_laptop_alsa_config
render_debian_laptop_asound_config
install -D -o root -g root -m 0755 rover/bin/chromegtts-daemon-laptop.py /usr/local/bin/chromegtts-daemon
log "Installed laptop chromegtts daemon"
install_google_tts_assets_laptop
log "ALSA config updated; reboot recommended before testing laptop rover audio"
}
install_google_tts_assets_laptop() {
local asset_dir="/opt/roverd/googletts"
local voice_dir="${asset_dir}/en-us-x-multi-r30"
local dist_url="https://storage.googleapis.com/chromeos-localmirror/distfiles/googletts-26.5.tar.xz"
local tmp_dir
local lib_member=""
local member
if [[ -f "${asset_dir}/libchrometts.so" && -f "${voice_dir}/pipeline.pb" ]]; then
log "Google Chrome TTS assets already installed; skipping download"
return
fi
tmp_dir="$(mktemp -d)"
log "Downloading Google Chrome TTS assets for Debian laptop profile..."
if ! curl -L -o "${tmp_dir}/googletts-26.5.tar.xz" "$dist_url"; then
rm -rf "$tmp_dir"
log "WARNING: failed to download Google Chrome TTS assets; chromegtts will be unavailable"
return
fi
local -a candidate_libs=()
case "$(uname -m)" in
aarch64|arm64)
candidate_libs=(libchrometts_arm64.so)
;;
armv7l|armhf)
candidate_libs=(libchrometts_armv7.so)
;;
x86_64|amd64)
candidate_libs=(libchrometts_x86_64.so libchrometts_amd64.so libchrometts_x64.so libchrometts.so)
;;
i386|i686)
candidate_libs=(libchrometts_x86.so libchrometts_i386.so libchrometts.so)
;;
*)
log "WARNING: unsupported Chrome TTS architecture $(uname -m); skipping Google TTS assets"
rm -rf "$tmp_dir"
return
;;
esac
for member in "${candidate_libs[@]}"; do
if tar -tf "${tmp_dir}/googletts-26.5.tar.xz" "$member" >/dev/null 2>&1; then
lib_member="$member"
break
fi
done
if [[ -z "$lib_member" ]]; then
log "WARNING: no libchrometts library matching $(uname -m) found in Google TTS archive; chromegtts will be unavailable"
rm -rf "$tmp_dir"
return
fi
if ! tar -xf "${tmp_dir}/googletts-26.5.tar.xz" -C "$tmp_dir" en-us-x-multi.zvoice "$lib_member"; then
rm -rf "$tmp_dir"
log "WARNING: failed to unpack Google Chrome TTS assets; chromegtts will be unavailable"
return
fi
install -d -o root -g root -m 0755 "$asset_dir"
install -o root -g root -m 0644 "${tmp_dir}/${lib_member}" "${asset_dir}/libchrometts.so"
rm -rf "$voice_dir"
install -d -o root -g root -m 0755 "$voice_dir"
unzip -q "${tmp_dir}/en-us-x-multi.zvoice" -d "$voice_dir"
chown -R root:root "$asset_dir"
find "$asset_dir" -type d -exec chmod 0755 {} +
find "$asset_dir" -type f -exec chmod 0644 {} +
rm -rf "$tmp_dir"
log "Installed Google Chrome TTS assets to $asset_dir using $lib_member"
}
install_debian_laptop_profile() {
install_debian_laptop_deps
disable_debian_laptop_desktop_audio_stack
install_debian_laptop_audio_support
}
-89
View File
@@ -1,89 +0,0 @@
#!/usr/bin/env bash
write_media_env_placeholder() {
install -d -o roverd -g roverd /var/lib/roverd
case "$PROFILE" in
pi)
# roverd rewrites media.env after loading /etc/roverd.json. These
# values only make the services syntactically usable before the first
# successful roverd run, so they mirror the Pi defaults instead of
# trying to become a second source of truth.
cat > /var/lib/roverd/media.env <<'ENV'
# Managed by roverd; placeholder values will be overwritten at runtime.
ROVERD_VIDEO_ENABLE=1
ROVERD_VIDEO_PUBLISHER=pi-libcamera
ROVERD_VIDEO_PUBLISH_URL=rtsp://control-server.local:8554/CHANGE_ME
ROVERD_VIDEO_DEVICE=
ROVERD_VIDEO_INPUT_FORMAT=
ROVERD_VIDEO_WIDTH=640
ROVERD_VIDEO_HEIGHT=480
ROVERD_VIDEO_FPS=30
ROVERD_VIDEO_BITRATE=2000000
ROVERD_VIDEO_INVERT=1
ROVERD_VIDEO_SENSOR_MODE=1296:972
ROVERD_AUDIO_CAPTURE_ENABLE=0
ROVERD_AUDIO_CAPTURE_PUBLISH_URL=rtsp://control-server.local:8554/CHANGE_ME-audio
ROVERD_AUDIO_CAPTURE_DEVICE=hw:0,0
ROVERD_AUDIO_CAPTURE_SAMPLE_RATE=48000
ROVERD_AUDIO_CAPTURE_CHANNELS=2
ROVERD_AUDIO_CAPTURE_BITRATE=510000
ROVERD_AUDIO_PLAYBACK_ENABLE=1
ROVERD_AUDIO_PLAYBACK_FORWARD_URL=rtsp://control-server.local:8554/CHANGE_ME-fwd
ROVERD_AUDIO_PLAYBACK_DEVICE=forward
ROVERD_AUDIO_PLAYBACK_NORMALIZE=1
ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER=dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled
ENV
;;
debian-laptop)
# The laptop placeholder uses the same logical ALSA names as the
# installed laptop asound.conf. That keeps forwarded audio under the
# ForwardMaster mixer control while TTS and horn keep their own paths.
cat > /var/lib/roverd/media.env <<'ENV'
# Managed by roverd; placeholder values will be overwritten at runtime.
ROVERD_VIDEO_ENABLE=1
ROVERD_VIDEO_PUBLISHER=debian-laptop-v4l2
ROVERD_VIDEO_PUBLISH_URL=rtsp://control-server.local:8554/CHANGE_ME
ROVERD_VIDEO_DEVICE=/dev/video0
ROVERD_VIDEO_INPUT_FORMAT=mjpeg
ROVERD_VIDEO_WIDTH=640
ROVERD_VIDEO_HEIGHT=480
ROVERD_VIDEO_FPS=30
ROVERD_VIDEO_BITRATE=2000000
ROVERD_VIDEO_INVERT=0
ROVERD_VIDEO_SENSOR_MODE=
ROVERD_AUDIO_CAPTURE_ENABLE=1
ROVERD_AUDIO_CAPTURE_PUBLISH_URL=rtsp://control-server.local:8554/CHANGE_ME-audio
ROVERD_AUDIO_CAPTURE_DEVICE=default
ROVERD_AUDIO_CAPTURE_SAMPLE_RATE=48000
ROVERD_AUDIO_CAPTURE_CHANNELS=2
ROVERD_AUDIO_CAPTURE_BITRATE=510000
ROVERD_AUDIO_PLAYBACK_ENABLE=1
ROVERD_AUDIO_PLAYBACK_FORWARD_URL=rtsp://control-server.local:8554/CHANGE_ME-fwd
ROVERD_AUDIO_PLAYBACK_DEVICE=forward
ROVERD_AUDIO_PLAYBACK_NORMALIZE=1
ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER=dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled
ENV
;;
esac
chown roverd:roverd /var/lib/roverd/media.env
chmod 0640 /var/lib/roverd/media.env
}
install_audio_fifo() {
local fifo_path="/var/lib/roverd/audio.pcm"
# The capture service and publisher service meet at this FIFO. Recreating
# it only when it is missing or the path is not a FIFO preserves a working
# service pipe while still fixing accidental regular-file leftovers.
if [[ -p "$fifo_path" ]]; then
chown roverd:audio "$fifo_path"
chmod 0660 "$fifo_path"
else
rm -f "$fifo_path"
mkfifo "$fifo_path"
chown roverd:audio "$fifo_path"
chmod 0660 "$fifo_path"
fi
}
-160
View File
@@ -1,160 +0,0 @@
#!/usr/bin/env bash
install_pi_video_deps() {
if command -v ffmpeg >/dev/null 2>&1 && (command -v rpicam-vid >/dev/null 2>&1 || command -v libcamera-vid >/dev/null 2>&1); then
log "Video dependencies already installed; skipping apt install"
return
fi
log "Installing video dependencies (libcamera-apps, ffmpeg)..."
apt-get update
apt-get install -y --no-install-recommends libcamera-apps ffmpeg
}
find_boot_config() {
if [[ -f /boot/firmware/config.txt ]]; then
printf "/boot/firmware/config.txt"
return 0
fi
if [[ -f /boot/config.txt ]]; then
printf "/boot/config.txt"
return 0
fi
return 1
}
ensure_pwm_overlay() {
local boot_config
if ! boot_config="$(find_boot_config)"; then
log "WARNING: unable to locate /boot config.txt; please ensure dtoverlay=pwm-2chan is added manually for servo support"
return
fi
if grep -Eq '^\s*dtoverlay=pwm(-2chan)?' "$boot_config"; then
log "PWM overlay already present in $boot_config"
return
fi
local backup="${boot_config}.roverd.$(date +%Y%m%d%H%M%S).bak"
cp "$boot_config" "$backup"
{
echo ""
echo "# Added by roverd installer to expose PWM hardware for camera servo control on GPIO12/13 (leaves GPIO18/19 free for I2S)"
echo "dtoverlay=pwm-2chan,pin=12,func=4,pin2=13,func2=4"
} >> "$boot_config"
log "Enabled dtoverlay=pwm-2chan on GPIO12/13 in $boot_config (backup at $backup). Reboot required for changes to apply."
}
install_pi_audio_support() {
local boot_config
if ! boot_config="$(find_boot_config)"; then
log "WARNING: unable to locate /boot config.txt; please enable googlevoicehat-soundcard overlay manually"
else
# Ensure onboard audio is disabled (prevents card index flapping)
if grep -Eq '^\s*dtparam=audio=on\b' "$boot_config"; then
log "Disabling onboard audio (dtparam=audio=on -> off) in $boot_config"
sed -i 's/^\s*dtparam=audio=on\b/# roverd disabled onboard audio\ndtparam=audio=off/' "$boot_config"
fi
if ! grep -Eq '^\s*dtparam=audio=off\b' "$boot_config"; then
log "Adding dtparam=audio=off to $boot_config"
echo "dtparam=audio=off" >> "$boot_config"
fi
if ! grep -Eq '^\s*dtparam=i2s=on\b' "$boot_config"; then
log "Adding dtparam=i2s=on to $boot_config"
echo "dtparam=i2s=on" >> "$boot_config"
fi
if ! grep -Eq '^\s*dtoverlay=googlevoicehat-soundcard\b' "$boot_config"; then
local backup="${boot_config}.roverd.$(date +%Y%m%d%H%M%S).bak"
cp "$boot_config" "$backup"
{
echo ""
echo "# Added by roverd installer to enable Google AIY v1 sound card"
echo "dtoverlay=googlevoicehat-soundcard"
} >> "$boot_config"
log "Enabled googlevoicehat-soundcard overlay in $boot_config (backup at $backup). Reboot required."
else
log "googlevoicehat-soundcard overlay already present in $boot_config"
fi
fi
if [[ -f rover/asound.conf ]]; then
install -m 0644 rover/asound.conf /etc/asound.conf
log "Installed ALSA config to /etc/asound.conf"
alsa_reload_notice=1
else
log "WARNING: rover/asound.conf missing; skipping ALSA config install"
fi
if [[ "${alsa_reload_notice:-0}" -eq 1 ]]; then
log "ALSA config updated; reboot recommended for overlay + audio changes"
fi
log "Installing TTS/audio packages (flite, espeak, Chrome TTS runtime deps)..."
if command -v flite >/dev/null 2>&1 \
&& command -v espeak >/dev/null 2>&1 \
&& command -v python3 >/dev/null 2>&1 \
&& command -v curl >/dev/null 2>&1 \
&& command -v xz >/dev/null 2>&1 \
&& command -v unzip >/dev/null 2>&1 \
&& command -v aplay >/dev/null 2>&1 \
&& ldconfig -p 2>/dev/null | grep -q 'libc++\.so\.1' \
&& ldconfig -p 2>/dev/null | grep -q 'libc++abi\.so\.1'; then
log "Core TTS packages already installed; skipping apt install"
else
apt-get update
apt-get install -y --no-install-recommends flite espeak python3 curl xz-utils unzip alsa-utils libc++1 libc++abi1 \
|| apt-get install -y --no-install-recommends flite espeak python3 curl xz-utils unzip alsa-utils libc++1-14 libc++abi1-14
fi
install -D -o root -g root -m 0755 rover/bin/chromegtts-daemon.py /usr/local/bin/chromegtts-daemon
log "Installed chromegtts daemon"
install_google_tts_assets
}
install_google_tts_assets() {
local asset_dir="/opt/roverd/googletts"
local voice_dir="${asset_dir}/en-us-x-multi-r30"
local dist_url="https://storage.googleapis.com/chromeos-localmirror/distfiles/googletts-26.5.tar.xz"
local tmp_dir
local lib_member
case "$(uname -m)" in
aarch64|arm64)
lib_member="libchrometts_arm64.so"
;;
armv7l|armhf)
lib_member="libchrometts_armv7.so"
;;
*)
log "WARNING: unsupported Chrome TTS architecture $(uname -m); skipping Google TTS assets"
return
;;
esac
if [[ -f "${asset_dir}/libchrometts.so" && -f "${voice_dir}/pipeline.pb" ]]; then
log "Google Chrome TTS assets already installed; skipping download"
return
fi
tmp_dir="$(mktemp -d)"
log "Downloading Google Chrome TTS assets..."
curl -L -o "${tmp_dir}/googletts-26.5.tar.xz" "$dist_url"
tar -xf "${tmp_dir}/googletts-26.5.tar.xz" -C "$tmp_dir" en-us-x-multi.zvoice "$lib_member"
install -d -o root -g root -m 0755 "$asset_dir"
install -o root -g root -m 0644 "${tmp_dir}/${lib_member}" "${asset_dir}/libchrometts.so"
rm -rf "$voice_dir"
install -d -o root -g root -m 0755 "$voice_dir"
unzip -q "${tmp_dir}/en-us-x-multi.zvoice" -d "$voice_dir"
chown -R root:root "$asset_dir"
find "$asset_dir" -type d -exec chmod 0755 {} +
find "$asset_dir" -type f -exec chmod 0644 {} +
rm -rf "$tmp_dir"
log "Installed Google Chrome TTS assets to $asset_dir"
}
install_pi_profile() {
if ! command -v rpicam-vid >/dev/null 2>&1 && ! command -v libcamera-vid >/dev/null 2>&1; then
log "WARNING: neither rpicam-vid nor libcamera-vid found in PATH; install libcamera-apps."
fi
install_pi_video_deps
ensure_pwm_overlay
install_pi_audio_support
}
-116
View File
@@ -1,116 +0,0 @@
#!/usr/bin/env bash
PROFILE="pi"
BINARY_SRC=""
CONFIG_SRC=""
usage() {
cat <<'USAGE'
Usage: sudo ./rover/install_roverd.sh [options]
Options:
--profile <name> Install profile: pi or debian-laptop (default: pi)
--debian-laptop Shortcut for --profile debian-laptop
-b, --binary <path> Path to the roverd binary (default: detected OS architecture)
-c, --config <path> Source config to install if /etc/roverd.json is missing
(default depends on profile)
-h, --help Show this help text
The script must run from the repository root and as root (sudo). It will:
* create system users/groups if needed
* install /usr/local/bin/roverd and /etc/roverd.json
* install profile-specific video helpers and shared audio helpers
* install profile-specific ALSA/system audio setup
* install the fixed-command self-update helper used by admin-triggered updates
* enable roverd.service and media publisher/listener services
USAGE
}
parse_args() {
while [[ $# -gt 0 ]]; do
case "$1" in
--profile)
PROFILE="${2:-}"
shift 2
;;
--debian-laptop)
PROFILE="debian-laptop"
shift
;;
-b|--binary)
BINARY_SRC="${2:-}"
shift 2
;;
-c|--config)
CONFIG_SRC="${2:-}"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown option: $1" >&2
usage
exit 1
;;
esac
done
}
select_profile() {
# Binary selection follows the installed userland, independent of the
# temporary media installer profiles removed later in the rework.
case "$(dpkg --print-architecture)" in
amd64) binary_arch=amd64 ;;
arm64) binary_arch=arm64 ;;
armhf)
# ARMv6 also runs on ARMv7; use the conservative artifact for
# 32-bit Debian derivatives whose armhf baseline differs.
binary_arch=armv6 ;;
*) echo "Unsupported OS architecture" >&2; exit 1 ;;
esac
BINARY_SRC="${BINARY_SRC:-dist/roverd-linux-$binary_arch}"
case "$PROFILE" in
pi)
CONFIG_SRC="${CONFIG_SRC:-rover/roverd/roverd.sample.json}"
VIDEO_HELPER_SRC="rover/bin/video-publisher.sh"
VIDEO_HELPER_DEST="/usr/local/bin/video-publisher"
VIDEO_SERVICE_SRC="rover/systemd/video-publisher.service"
VIDEO_SERVICE_NAME="video-publisher.service"
ROVERD_GROUPS="dialout,gpio,video,render,audio"
;;
debian-laptop)
CONFIG_SRC="${CONFIG_SRC:-rover/roverd/roverd.debian-laptop.sample.json}"
VIDEO_HELPER_SRC="rover/bin/debian-laptop-video-publisher.sh"
VIDEO_HELPER_DEST="/usr/local/bin/debian-laptop-video-publisher"
VIDEO_SERVICE_SRC="rover/systemd/debian-laptop-video-publisher.service"
VIDEO_SERVICE_NAME="debian-laptop-video-publisher.service"
ROVERD_GROUPS="dialout,video,render,audio"
;;
*)
echo "Unknown profile: $PROFILE" >&2
usage
exit 1
;;
esac
}
install_selected_profile() {
case "$PROFILE" in
pi)
# The Pi profile owns the board-specific camera, PWM, and AIY audio
# setup. Keeping that hardware work behind this dispatcher prevents
# the laptop profile from accidentally inheriting Pi overlays or
# card-index assumptions.
install_pi_profile
;;
debian-laptop)
# The Debian laptop profile only installs ordinary Debian packages
# and a laptop ALSA routing file. Anything that depends on Pi GPIO,
# overlays, or the Google Voice HAT stays out of this path.
install_debian_laptop_profile
;;
esac
}
+6 -34
View File
@@ -1,38 +1,10 @@
#!/usr/bin/env bash
install_self_update_support() {
local sudoers_file="/etc/sudoers.d/roverd-self-update"
local update_env="/etc/roverd-update.env"
local quoted_repo_root
# The self-update helper must know which checkout should receive the git
# pull. Recording the repository root during the normal installer run keeps
# the runtime websocket command simple and prevents the rover from accepting
# a caller-controlled path.
printf -v quoted_repo_root '%q' "$REPO_ROOT"
install -D -o root -g root -m 0644 /dev/null "$update_env"
cat > "$update_env" <<ENV
# Managed by rover/install_roverd.sh.
# This path is intentionally captured from the installer working directory so
# admin-triggered rover updates always operate on the same full repository that
# was used for the manual install.
ROVERD_REPO_DIR=$quoted_repo_root
ENV
log "Registered roverd update repository at $REPO_ROOT"
# The helper is root-owned and argument-free. sudoers grants the roverd
# service user exactly this command and nothing broader, which is important
# because update requests arrive over the rover websocket.
install -D -o root -g root -m 0755 rover/bin/roverd-self-update.sh /usr/local/sbin/roverd-self-update
cat > "$sudoers_file" <<'SUDOERS'
# Managed by rover/install_roverd.sh.
# Allow only the roverd service account to run the fixed self-update helper.
roverd ALL=(root) NOPASSWD: /usr/local/sbin/roverd-self-update
SUDOERS
chown root:root "$sudoers_file"
chmod 0440 "$sudoers_file"
if command -v visudo >/dev/null 2>&1; then
visudo -cf "$sudoers_file" >/dev/null
fi
log "Installed roverd self-update helper and sudoers rule"
local quoted_repo_root
printf -v quoted_repo_root '%q' "$REPO_ROOT"
printf 'ROVERD_REPO_DIR=%s\n' "$quoted_repo_root" > /etc/roverd-update.env
chmod 0600 /etc/roverd-update.env
install -D -o root -g root -m 0755 rover/bin/roverd-self-update.sh /usr/local/sbin/roverd-self-update
log "Registered update checkout at $REPO_ROOT"
}
-43
View File
@@ -1,43 +0,0 @@
#!/usr/bin/env bash
install_media_units() {
# Video publishing is the only profile-specific media service right now:
# Pi uses libcamera/rpicam, while Debian laptops publish from a V4L2 webcam.
install -D -o root -g root -m 0755 "$VIDEO_HELPER_SRC" "$VIDEO_HELPER_DEST"
log "Installed $PROFILE video publisher helper"
install -m 0644 "$VIDEO_SERVICE_SRC" "/etc/systemd/system/$VIDEO_SERVICE_NAME"
log "Installed $PROFILE video publisher systemd unit"
# Audio capture publishing and forwarded-audio playback use the same ffmpeg
# and ALSA contract on both profiles, so they stay as shared installer work.
install -D -o root -g root -m 0755 rover/bin/audio-only-publisher.sh /usr/local/bin/audio-only-publisher
install -m 0644 rover/systemd/audio-only-publisher.service /etc/systemd/system/audio-only-publisher.service
log "Installed audio-only publisher helper + systemd unit"
install -D -o root -g root -m 0755 rover/bin/audio-forward-listener.sh /usr/local/bin/audio-forward-listener
install -m 0644 rover/systemd/audio-forward-listener.service /etc/systemd/system/audio-forward-listener.service
log "Installed audio-forward listener helper + systemd unit"
}
enable_and_restart_units() {
systemctl daemon-reload
systemctl enable roverd.service
systemctl enable "$VIDEO_SERVICE_NAME"
systemctl enable audio-only-publisher.service
systemctl enable audio-forward-listener.service
if [[ $CONFIG_EXISTS -eq 1 ]]; then
# An existing config means this host was already configured, so restart
# immediately to pick up the new binary, helpers, units, and media env.
systemctl restart roverd.service
systemctl restart "$VIDEO_SERVICE_NAME"
systemctl restart audio-only-publisher.service
systemctl restart audio-forward-listener.service
log "Restarted roverd + media publishers/listener"
else
# A freshly installed sample config usually still has placeholder names
# and URLs. Enabling without starting avoids connecting a half-configured
# rover to the control server by accident.
log "Skipped auto-start because config is the sample; edit $CONFIG_DEST then run: sudo systemctl restart roverd ${VIDEO_SERVICE_NAME%.service} audio-only-publisher audio-forward-listener"
fi
}
+25 -44
View File
@@ -1,48 +1,29 @@
#!/usr/bin/env bash
#
# Installer entry point for roverd hosts.
#
# The detailed work lives in rover/install/*.sh so platform-specific setup stays
# local to the profile that needs it. This file should read like the install
# order: choose a profile, validate inputs, install shared roverd pieces,
# install profile support, then enable the services.
# Installs from an existing checkout. Standalone bootstrap is a later stage.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
# The helper scripts use repository-relative paths because those same paths are
# shown in docs and logs. Moving to the repository root once keeps every module
# simple and prevents each function from needing its own path resolver.
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
cd "$REPO_ROOT"
source rover/install/common.sh
source rover/install/profiles.sh
[[ $EUID == 0 ]] || { echo 'Run as root' >&2; exit 1; }
case "$(dpkg --print-architecture)" in
amd64) arch=amd64 ;; arm64) arch=arm64 ;; armhf) arch=armv6 ;;
*) echo 'Unsupported OS architecture' >&2; exit 1 ;;
esac
install -m 0755 "dist/roverd-linux-$arch" /usr/local/bin/roverd
install -d /etc/roverd/profiles /var/lib/roverd
if [[ ! -f /etc/roverd.json ]]; then
/usr/local/bin/roverd -print-default-config > /etc/roverd.json
chmod 600 /etc/roverd.json
echo 'Set name, serverUrl, devices, and enabled profiles in /etc/roverd.json before starting roverd.'
fi
install -m 0644 rover/systemd/roverd.service /etc/systemd/system/roverd.service
# Use this checkout directly for catalogs and command resources.
install -d /etc/systemd/system/roverd.service.d
printf '[Service]\nExecStart=\nExecStart=/usr/local/bin/roverd -config /etc/roverd.json -repo "%s"\n' "$REPO_ROOT" > /etc/systemd/system/roverd.service.d/repository.conf
install -m 0755 rover/bin/chromegtts-daemon.py /usr/local/bin/chromegtts-daemon
bash rover/bin/setup-tts.sh
log() { echo "$*"; }
source rover/install/self_update.sh
source rover/install/pi_profile.sh
source rover/install/debian_laptop_profile.sh
source rover/install/media_env.sh
source rover/install/systemd.sh
main() {
parse_args "$@"
select_profile
require_root
validate_install_inputs
install_roverd_binary
install_self_update_support
install_roverd_config
install_roverd_unit
install_selected_profile
install_media_units
write_media_env_placeholder
install_audio_fifo
enable_and_restart_units
log "Install complete for profile $PROFILE"
}
main "$@"
install_self_update_support
systemctl daemon-reload
systemctl enable roverd.service
echo 'Installed. Run systemctl restart roverd after configuring this rover.'
+34
View File
@@ -0,0 +1,34 @@
- id: alsa
name: ALSA microphone
description: Uses the configured audio input device through roverd's ALSA conversion route.
setup: |
if ! command -v ffmpeg >/dev/null || ! command -v arecord >/dev/null; then
apt-get update && apt-get install -y ffmpeg alsa-utils
fi
run: &run |
exec ffmpeg -nostdin -f alsa -ar "$ROVER_AUDIO_SAMPLE_RATE" -ac "$ROVER_AUDIO_CHANNELS" -i "$ROVER_AUDIO_INPUT_DEVICE" -c:a libopus -b:a "$ROVER_AUDIO_BITRATE" -f rtsp -rtsp_transport tcp "$ROVER_AUDIO_PUBLISH_URL"
- id: aiy
name: Google AIY Voice HAT microphone
description: Same configurable ALSA route; setup enables the HAT overlay. Reboot once after first enabling its hardware.
setup: |
set -euo pipefail
# Capture/playback setup may run concurrently; serialize edits to boot config.
exec 9>/var/lock/roverd-aiy.lock
flock 9
boot=/boot/firmware/config.txt
[[ -f "$boot" ]] || boot=/boot/config.txt
[[ -f "$boot" ]] || { echo 'AIY setup needs a Raspberry Pi boot config.txt' >&2; exit 1; }
changed=0
for setting in dtparam=i2s=on dtoverlay=googlevoicehat-soundcard; do
if ! grep -Fxq "$setting" "$boot"; then
printf '\n%s\n' "$setting" >> "$boot"
changed=1
fi
done
if [[ "$changed" == 1 ]]; then
echo 'AIY hardware enabled. Reboot the host once before using this sound card.'
fi
if ! command -v ffmpeg >/dev/null || ! command -v aplay >/dev/null; then
apt-get update && apt-get install -y ffmpeg alsa-utils
fi
run: *run
+36
View File
@@ -0,0 +1,36 @@
- id: alsa
name: ALSA speaker
description: Uses the configured output alongside TTS and horn with independent volume controls.
setup: |
if ! command -v ffmpeg >/dev/null || ! command -v aplay >/dev/null; then
apt-get update && apt-get install -y ffmpeg alsa-utils
fi
run: &run |
filters=()
if [ "$ROVER_AUDIO_NORMALIZE" = true ]; then filters=(-af "$ROVER_AUDIO_NORMALIZE_FILTER"); fi
exec ffmpeg -nostdin -rtsp_transport tcp -i "$ROVER_AUDIO_PLAYBACK_URL" -vn "${filters[@]}" -f alsa "$ROVER_AUDIO_OUTPUT_DEVICE"
- id: aiy
name: Google AIY Voice HAT speaker
description: Enables the HAT hardware; uses the same configured ALSA routing as other devices. Reboot once after initial setup.
setup: |
set -euo pipefail
# Capture/playback setup may run concurrently; serialize edits to boot config.
exec 9>/var/lock/roverd-aiy.lock
flock 9
boot=/boot/firmware/config.txt
[[ -f "$boot" ]] || boot=/boot/config.txt
[[ -f "$boot" ]] || { echo 'AIY setup needs a Raspberry Pi boot config.txt' >&2; exit 1; }
changed=0
for setting in dtparam=i2s=on dtoverlay=googlevoicehat-soundcard; do
if ! grep -Fxq "$setting" "$boot"; then
printf '\n%s\n' "$setting" >> "$boot"
changed=1
fi
done
if [[ "$changed" == 1 ]]; then
echo 'AIY hardware enabled. Reboot the host once before using this sound card.'
fi
if ! command -v ffmpeg >/dev/null || ! command -v aplay >/dev/null; then
apt-get update && apt-get install -y ffmpeg alsa-utils
fi
run: *run
+25
View File
@@ -0,0 +1,25 @@
- id: v4l2
name: V4L2 camera
description: USB or other Linux V4L2 camera, encoded with software H.264.
setup: |
command -v ffmpeg >/dev/null || { apt-get update && apt-get install -y ffmpeg; }
run: |
filters=()
if [ "$ROVER_VIDEO_INVERTED" = true ]; then filters=(-vf hflip,vflip); fi
exec ffmpeg -nostdin -f v4l2 -input_format "$ROVER_VIDEO_INPUT_FORMAT" -video_size "${ROVER_VIDEO_WIDTH}x${ROVER_VIDEO_HEIGHT}" -framerate "$ROVER_VIDEO_FPS" -i "$ROVER_VIDEO_DEVICE" "${filters[@]}" -an -c:v libx264 -preset ultrafast -tune zerolatency -pix_fmt yuv420p -b:v "$ROVER_VIDEO_BITRATE" -f rtsp -rtsp_transport tcp "$ROVER_VIDEO_PUBLISH_URL"
- id: rpicam
name: Raspberry Pi CSI camera
description: rpicam/libcamera H.264 output, republished through ffmpeg.
setup: |
command -v ffmpeg >/dev/null || { apt-get update && apt-get install -y ffmpeg; }
if ! command -v rpicam-vid >/dev/null && ! command -v libcamera-vid >/dev/null; then
apt-get update
apt-get install -y rpicam-apps
fi
run: |
camera=$(command -v rpicam-vid || command -v libcamera-vid)
options=()
if [ "$ROVER_VIDEO_INVERTED" = true ]; then options+=(--hflip --vflip); fi
if [ -n "$ROVER_VIDEO_SENSOR_MODE" ]; then options+=(--mode "$ROVER_VIDEO_SENSOR_MODE"); fi
"$camera" --timeout 0 --nopreview --inline --codec h264 --width "$ROVER_VIDEO_WIDTH" --height "$ROVER_VIDEO_HEIGHT" --framerate "$ROVER_VIDEO_FPS" --bitrate "$ROVER_VIDEO_BITRATE" "${options[@]}" -o - |
ffmpeg -nostdin -fflags +genpts -f h264 -i pipe:0 -c:v copy -an -f rtsp -rtsp_transport tcp "$ROVER_VIDEO_PUBLISH_URL"
+4 -13
View File
@@ -100,18 +100,9 @@ func (c *WSClient) applyMixerGain(control string, gain float64) {
}
func (c *WSClient) trySetMixerControl(control, value string) error {
// Prefer the active ALSA default route; fall back to card index for compatibility.
candidates := [][]string{
{"-q", "-D", "default", "sset", control, value},
{"-q", "-c", "0", "sset", control, value},
out, err := exec.Command("amixer", "-q", "-c", c.cfg.Audio.MixerCard, "sset", control, value).CombinedOutput()
if err != nil {
return fmt.Errorf("%w (%s)", err, string(out))
}
var lastErr error
for _, args := range candidates {
out, err := exec.Command("amixer", args...).CombinedOutput()
if err == nil {
return nil
}
lastErr = fmt.Errorf("%w (%s)", err, string(out))
}
return lastErr
return nil
}
+60
View File
@@ -0,0 +1,60 @@
package roverd
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
const audioConfigPath = "/var/lib/roverd/asound.conf"
func validateAudioRouting(cfg AudioConfig) error {
for name, value := range map[string]string{"inputDevice": cfg.InputDevice, "outputDevice": cfg.OutputDevice, "mixerCard": cfg.MixerCard} {
if value == "" || strings.ContainsAny(value, "\x00\r\n") {
return fmt.Errorf("audio.%s must be a nonempty single-line ALSA identifier", name)
}
}
return nil
}
// Generate a private ALSA configuration inherited by all roverd children. Do
// not overwrite the host's /etc/asound.conf or impose the AIY card on other hosts.
func AudioConfiguration(cfg AudioConfig) string {
text := "</usr/share/alsa/alsa.conf>\n"
text += fmt.Sprintf(`pcm.rover_capture { type plug slave.pcm %s }
pcm.rover_mix {
type dmix
ipc_key 70601
ipc_key_add_uid true
slave { pcm %s format S16_LE rate %d channels %d }
}
`, strconv.Quote(cfg.InputDevice), strconv.Quote(cfg.OutputDevice), cfg.OutputSampleRate, cfg.OutputChannels)
for _, pair := range [][2]string{{"tts", "TTSMaster"}, {"horn", "HornMaster"}, {"forward", "ForwardMaster"}} {
text += fmt.Sprintf(`pcm.rover_%s_volume {
type softvol
slave.pcm "rover_mix"
control { name %s card %s }
min_dB -60.0
max_dB 12.0
}
pcm.rover_%s { type plug slave.pcm "rover_%s_volume" }
`, pair[0], strconv.Quote(pair[1]), strconv.Quote(cfg.MixerCard), pair[0], pair[0])
}
text += fmt.Sprintf(`pcm.!default { type asym playback.pcm "rover_tts" capture.pcm "rover_capture" }
ctl.!default { type hw card %s }
`, strconv.Quote(cfg.MixerCard))
return text
}
func ConfigureAudio(cfg AudioConfig) error {
text := AudioConfiguration(cfg)
if err := os.MkdirAll(filepath.Dir(audioConfigPath), 0755); err != nil {
return err
}
if err := os.WriteFile(audioConfigPath, []byte(text), 0600); err != nil {
return err
}
return os.Setenv("ALSA_CONFIG_PATH", audioConfigPath)
}
+29 -6
View File
@@ -17,11 +17,24 @@ import (
func main() {
var cfgPath string
var repoPath string
flag.StringVar(&repoPath, "repo", "/opt/roverd", "managed repository checkout")
flag.StringVar(&cfgPath, "config", "/etc/roverd.json", "path to roverd JSON configuration")
printDefaults := flag.Bool("print-default-config", false, "print a complete initial JSON configuration and exit")
printProfiles := flag.Bool("print-media-profiles", false, "read and print media profiles without running commands")
printAudio := flag.Bool("print-audio-config", false, "print generated ALSA configuration without installing it")
printSchema := flag.Bool("print-config-schema", false, "print the configuration JSON Schema and exit")
checkConfig := flag.Bool("check-config", false, "validate configuration without opening hardware or connecting")
flag.Parse()
if *printProfiles {
profiles, err := roverd.LoadMediaProfiles(repoPath)
if err != nil {
log.Fatal(err)
}
data, _ := json.MarshalIndent(profiles, "", " ")
fmt.Println(string(data))
return
}
if *printDefaults {
data, _ := json.MarshalIndent(roverd.DefaultConfig(), "", " ")
fmt.Println(string(data))
@@ -35,11 +48,15 @@ func main() {
if err != nil {
log.Fatalf("load config: %v", err)
}
if *printAudio {
fmt.Print(roverd.AudioConfiguration(cfg.Audio))
return
}
if *checkConfig {
fmt.Println("Configuration valid")
return
}
if run(cfg, cfgPath) {
if run(cfg, cfgPath, repoPath) {
executable, err := os.Executable()
if err != nil {
log.Fatal(err)
@@ -50,7 +67,7 @@ func main() {
}
}
func run(cfg *roverd.Config, cfgPath string) bool {
func run(cfg *roverd.Config, cfgPath, repoPath string) bool {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
logger := log.New(os.Stdout, "roverd: ", log.LstdFlags|log.Lmicroseconds|log.LUTC)
@@ -59,14 +76,20 @@ func run(cfg *roverd.Config, cfgPath string) bool {
console.SetEvents(events)
var restarting atomic.Bool
management := roverd.NewManagementClient(cfg, cfgPath, events, logger, func() { restarting.Store(true); cancel() })
if err := roverd.ConfigureAudio(cfg.Audio); err != nil {
console.Notify(fmt.Sprintf("Audio routing unavailable: %v", err))
}
media, err := roverd.NewMediaSupervisor(cfg, repoPath, events, logger)
if err != nil {
console.Notify(fmt.Sprintf("Media profiles unavailable: %v", err))
}
management.SetMedia(media)
management.SetRepository(repoPath)
managementDone := make(chan struct{})
go func() { defer close(managementDone); management.Run(ctx) }()
// Hardware failures leave management connected until a corrected config
// requests restart. runHardware unwinds its own resources on failure.
media := roverd.NewMediaSupervisor(cfg.Media, logger)
management.SetMedia(media)
if media != nil {
media.Start(ctx)
defer media.Stop()
}
if err := runHardware(ctx, cfg, events, management, media, logger, console); err != nil {
console.Notify(fmt.Sprintf("Hardware unavailable: %v. Management remains connected.", err))
+41 -66
View File
@@ -55,13 +55,15 @@ type BatteryConfig struct {
}
type AudioConfig struct {
// AudioConfig is only for sounds generated by roverd itself. Live capture
// and playback are media-publisher concerns, so those settings live under
// MediaConfig where they can be written directly into media.env.
TTSEnabled bool `json:"ttsEnabled"`
DefaultEngine string `json:"defaultEngine"`
DefaultVoice string `json:"defaultVoice"`
DefaultPitch int `json:"defaultPitch"`
InputDevice string `json:"inputDevice" jsonschema:"minLength=1"`
OutputDevice string `json:"outputDevice" jsonschema:"minLength=1"`
MixerCard string `json:"mixerCard" jsonschema:"minLength=1"`
OutputSampleRate int `json:"outputSampleRate" jsonschema:"minimum=8000,maximum=192000"`
OutputChannels int `json:"outputChannels" jsonschema:"minimum=1,maximum=8"`
TTSEnabled bool `json:"ttsEnabled"`
DefaultEngine string `json:"defaultEngine"`
DefaultVoice string `json:"defaultVoice"`
DefaultPitch int `json:"defaultPitch"`
}
type HornConfig struct {
@@ -69,7 +71,6 @@ type HornConfig struct {
Volume float64 `json:"volume"`
SampleRate int `json:"sampleRate"`
Channels int `json:"channels"`
Device string `json:"device"`
SineGain float64 `json:"sineGain"`
SawGain float64 `json:"sawGain"`
MaxDuration Duration `json:"maxDuration"`
@@ -79,22 +80,15 @@ type MediaConfig struct {
// RTSPPort is shared by the derived video, microphone, and forwarded-audio
// RTSP URLs. Keeping it at this level prevents each nested block from needing
// to repeat the same server port when the common MediaMTX listener is used.
RTSPPort int `json:"rtspPort" jsonschema:"minimum=1,maximum=65535"`
Manage bool `json:"manage"`
HealthURL string `json:"healthUrl"`
HealthInterval Duration `json:"healthInterval"`
Video VideoMediaConfig `json:"video"`
AudioCapture AudioCaptureConfig `json:"audioCapture"`
AudioPlayback AudioPlaybackConfig `json:"audioPlayback"`
RTSPPort int `json:"rtspPort" jsonschema:"minimum=1,maximum=65535"`
Video VideoMediaConfig `json:"video"`
AudioCapture AudioCaptureConfig `json:"audioCapture"`
AudioPlayback AudioPlaybackConfig `json:"audioPlayback"`
}
type VideoMediaConfig struct {
// Publisher selects the installed publisher script/pipeline family. The
// first pass uses pi-libcamera for current rovers; laptop-v4l2 can be added
// without changing the server-facing media shape again.
Enabled bool `json:"enabled"`
Service string `json:"service"`
Publisher string `json:"publisher"`
Profile string `json:"profile" jsonschema:"minLength=1"`
Enabled bool `json:"enabled"`
// PublishURL is derived during validation. It remains in rover metadata for server-side
// consumers through MediaMetadata, but is never persisted in configuration.
PublishURL string `json:"-"`
@@ -109,29 +103,29 @@ type VideoMediaConfig struct {
}
type AudioCaptureConfig struct {
Profile string `json:"profile" jsonschema:"minLength=1"`
// AudioCapture describes the rover microphone stream that browsers can
// subscribe to as "<rover>-audio". A disabled capture block still has
// normalized defaults so enabling it only requires flipping enabled: true.
Enabled bool `json:"enabled"`
Service string `json:"service"`
Enabled bool `json:"enabled"`
// PublishURL follows the same derived-only contract as the video path.
PublishURL string `json:"-"`
Device string `json:"device"`
SampleRate int `json:"sampleRate"`
Channels int `json:"channels"`
Bitrate int `json:"bitrate"`
SampleRate int `json:"sampleRate"`
Channels int `json:"channels"`
Bitrate int `json:"bitrate"`
}
type AudioPlaybackConfig struct {
Profile string `json:"profile" jsonschema:"minLength=1"`
// AudioPlayback describes the reverse stream that VIP users publish into
// MediaMTX for playback on the rover speaker. The URL is a request/read URL
// for the rover listener, while the server converts it to publish mode when
// it needs to inject audio.
Enabled bool `json:"enabled"`
Service string `json:"service"`
Enabled bool `json:"enabled"`
// ForwardURL is derived because the server and rover must agree on the exact -fwd path.
ForwardURL string `json:"-"`
Device string `json:"device"`
ForwardURL string `json:"-"`
Normalize bool `json:"normalize"`
NormalizeFilter string `json:"normalizeFilter"`
}
@@ -267,12 +261,13 @@ func DefaultConfig() Config {
},
MaxWheelMMs: 500,
Media: MediaConfig{
RTSPPort: 8554,
HealthInterval: Duration{Duration: 30 * time.Second},
RTSPPort: 8554,
Video: VideoMediaConfig{
Enabled: true,
Service: "video-publisher.service",
Publisher: "pi-libcamera",
Profile: "v4l2",
Enabled: false,
Device: "/dev/video0", InputFormat: "mjpeg",
Width: 640,
Height: 480,
FPS: 30,
@@ -281,22 +276,23 @@ func DefaultConfig() Config {
SensorMode: "1296:972",
},
AudioCapture: AudioCaptureConfig{
Enabled: false,
Service: "audio-only-publisher.service",
Device: "hw:0,0",
Profile: "alsa",
Enabled: false,
SampleRate: 48000,
Channels: 2,
Bitrate: 510000,
},
AudioPlayback: AudioPlaybackConfig{
Enabled: true,
Service: "audio-forward-listener.service",
Device: "forward",
Profile: "alsa",
Enabled: false,
Normalize: true,
NormalizeFilter: "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled",
},
},
Audio: AudioConfig{
InputDevice: "hw:0,0", OutputDevice: "hw:0,0", MixerCard: "0", OutputSampleRate: 48000, OutputChannels: 2,
TTSEnabled: false,
DefaultEngine: "flite",
DefaultVoice: "rms",
@@ -410,6 +406,9 @@ func validateConfig(cfg *Config) error {
return errors.New("piGpio.brc: nonnegative pin and positive pulse durations required")
}
}
if err := validateAudioRouting(cfg.Audio); err != nil {
return err
}
validateAudioConfig(&cfg.Audio)
validateHornConfig(&cfg.Horn)
validateAutoSideBrushConfig(&cfg.AutoSideBrush)
@@ -481,9 +480,6 @@ func validateMediaConfig(cfg *MediaConfig, serverURL string, roverName string) e
if cfg.RTSPPort <= 0 {
cfg.RTSPPort = 8554
}
if cfg.HealthInterval.Duration <= 0 {
cfg.HealthInterval = Duration{Duration: 30 * time.Second}
}
if err := validateVideoMediaConfig(&cfg.Video, serverURL, roverName, cfg.RTSPPort); err != nil {
return fmt.Errorf("video: %w", err)
}
@@ -497,12 +493,6 @@ func validateMediaConfig(cfg *MediaConfig, serverURL string, roverName string) e
}
func validateVideoMediaConfig(cfg *VideoMediaConfig, serverURL string, roverName string, rtspPort int) error {
if cfg.Service == "" {
cfg.Service = "video-publisher.service"
}
if cfg.Publisher == "" {
cfg.Publisher = "pi-libcamera"
}
// V4L2 input formats are consumed by ffmpeg as lowercase names such as
// mjpeg or yuyv422. Normalizing here keeps the publisher script simple and
// makes hand-edited Debian laptop configs less sensitive to capitalization.
@@ -519,9 +509,6 @@ func validateVideoMediaConfig(cfg *VideoMediaConfig, serverURL string, roverName
if cfg.Bitrate <= 0 {
cfg.Bitrate = 2000000
}
if cfg.SensorMode == "" && cfg.Publisher == "pi-libcamera" {
cfg.SensorMode = "1296:972"
}
/*
Always derive this endpoint. Older rover configs can contain an explicit SRT publishUrl;
honoring it after a binary update would silently leave that rover on the old transport.
@@ -535,12 +522,6 @@ func validateVideoMediaConfig(cfg *VideoMediaConfig, serverURL string, roverName
}
func validateAudioCaptureConfig(cfg *AudioCaptureConfig, serverURL string, roverName string, rtspPort int) error {
if cfg.Service == "" {
cfg.Service = "audio-only-publisher.service"
}
if cfg.Device == "" {
cfg.Device = "hw:0,0"
}
if cfg.SampleRate <= 0 {
cfg.SampleRate = 48000
}
@@ -559,12 +540,6 @@ func validateAudioCaptureConfig(cfg *AudioCaptureConfig, serverURL string, rover
}
func validateAudioPlaybackConfig(cfg *AudioPlaybackConfig, serverURL string, roverName string, rtspPort int) error {
if cfg.Service == "" {
cfg.Service = "audio-forward-listener.service"
}
if cfg.Device == "" {
cfg.Device = "forward"
}
if cfg.NormalizeFilter == "" {
cfg.NormalizeFilter = "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled"
}
+1 -4
View File
@@ -124,10 +124,7 @@ func (h *HornSynth) run(waveform string, freqs []float64, stop <-chan struct{})
h.mu.Unlock()
volume *= gain
device := strings.TrimSpace(h.cfg.Device)
if device == "" {
device = "horn"
}
device := "rover_horn"
args := []string{"-q", "-D", device, "-f", "S16_LE", "-c", fmt.Sprintf("%d", channels), "-r", fmt.Sprintf("%d", rate), "-t", "raw"}
cmd := exec.Command("aplay", args...)
stdin, err := cmd.StdinPipe()
+39 -6
View File
@@ -15,6 +15,7 @@ import (
type ManagementClient struct {
cfg *Config
repo string
configPath string
events chan RoverEvent
log *log.Logger
@@ -26,11 +27,13 @@ type ManagementClient struct {
}
type managementCommand struct {
Type string `json:"type"`
ID string `json:"id"`
Config json.RawMessage `json:"config"`
Reboot *rebootPayload `json:"reboot"`
Media *mediaCommand `json:"media"`
Type string `json:"type"`
ID string `json:"id"`
Config json.RawMessage `json:"config"`
Reboot *rebootPayload `json:"reboot"`
Category string `json:"category"`
Profile *MediaProfile `json:"profile"`
Media *mediaCommand `json:"media"`
}
func NewManagementClient(cfg *Config, path string, events chan RoverEvent, logger *log.Logger, restart func()) *ManagementClient {
@@ -78,7 +81,7 @@ func (m *ManagementClient) connect(parent context.Context) error {
conn.SetReadLimit(1024 * 1024)
if err := writeJSON(ctx, conn, map[string]any{
"type": "hello", "name": m.cfg.Name, "config": m.cfg,
"schema": ConfigurationSchema(), "profiles": map[string]any{"video": []any{}, "audioCapture": []any{}, "audioPlayback": []any{}},
"schema": ConfigurationSchema(), "profiles": m.profileCatalog(), "mediaStatus": m.mediaStatus(),
}); err != nil {
return err
}
@@ -144,6 +147,19 @@ func (m *ManagementClient) execute(ctx context.Context, command managementComman
if m.stopping {
return nil, fmt.Errorf("management action already pending")
}
if command.Type == "profile.set" {
if command.Profile == nil {
return nil, fmt.Errorf("profile required")
}
if err := SaveCustomProfile(command.Category, *command.Profile); err != nil {
return nil, err
}
m.stopping = true
if m.runtime != nil {
_ = m.runtime.PrepareShutdown()
}
return m.restart, nil
}
if command.Type == "media" {
if m.media == nil || command.Media == nil {
return nil, fmt.Errorf("media supervisor unavailable")
@@ -271,3 +287,20 @@ func (m *ManagementClient) emit(event string, data map[string]any) {
default:
}
}
func (m *ManagementClient) SetRepository(repo string) { m.repo = repo }
func (m *ManagementClient) profileCatalog() map[string][]MediaProfile {
profiles, err := LoadMediaProfiles(m.repo)
if err != nil {
m.log.Printf("profile catalog: %v", err)
return map[string][]MediaProfile{}
}
return profiles
}
func (m *ManagementClient) mediaStatus() map[string]string {
if m.media == nil {
return nil
}
return m.media.Status()
}
-68
View File
@@ -1,68 +0,0 @@
package roverd
import (
"bytes"
"fmt"
"os"
"path/filepath"
)
const publisherEnvPath = "/var/lib/roverd/media.env"
func UpdatePublisherEnv(media MediaConfig) error {
if media.Video.Enabled && media.Video.PublishURL == "" {
return fmt.Errorf("media video publishUrl missing")
}
if media.AudioCapture.Enabled && media.AudioCapture.PublishURL == "" {
return fmt.Errorf("media audioCapture publishUrl missing")
}
if media.AudioPlayback.Enabled && media.AudioPlayback.ForwardURL == "" {
return fmt.Errorf("media audioPlayback forwardUrl missing")
}
if media.Video.Width <= 0 || media.Video.Height <= 0 || media.Video.FPS <= 0 || media.Video.Bitrate <= 0 {
return fmt.Errorf("invalid media video dimensions/bitrate")
}
if err := os.MkdirAll(filepath.Dir(publisherEnvPath), 0o755); err != nil {
return err
}
var buf bytes.Buffer
/*
The env file is intentionally verbose: every publisher receives concrete
values instead of silently falling back to script-local defaults. That
makes roverd.json the owner of media behavior while keeping the shell
scripts as small pipeline launchers.
*/
fmt.Fprintf(&buf, "ROVERD_VIDEO_ENABLE=%d\n", boolToInt(media.Video.Enabled))
fmt.Fprintf(&buf, "ROVERD_VIDEO_PUBLISHER=%s\n", media.Video.Publisher)
fmt.Fprintf(&buf, "ROVERD_VIDEO_PUBLISH_URL=%s\n", media.Video.PublishURL)
fmt.Fprintf(&buf, "ROVERD_VIDEO_DEVICE=%s\n", media.Video.Device)
fmt.Fprintf(&buf, "ROVERD_VIDEO_INPUT_FORMAT=%s\n", media.Video.InputFormat)
fmt.Fprintf(&buf, "ROVERD_VIDEO_WIDTH=%d\n", media.Video.Width)
fmt.Fprintf(&buf, "ROVERD_VIDEO_HEIGHT=%d\n", media.Video.Height)
fmt.Fprintf(&buf, "ROVERD_VIDEO_FPS=%d\n", media.Video.FPS)
fmt.Fprintf(&buf, "ROVERD_VIDEO_BITRATE=%d\n", media.Video.Bitrate)
fmt.Fprintf(&buf, "ROVERD_VIDEO_INVERT=%d\n", boolToInt(media.Video.Inverted))
fmt.Fprintf(&buf, "ROVERD_VIDEO_SENSOR_MODE=%s\n", media.Video.SensorMode)
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_ENABLE=%d\n", boolToInt(media.AudioCapture.Enabled))
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_PUBLISH_URL=%s\n", media.AudioCapture.PublishURL)
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_DEVICE=%s\n", media.AudioCapture.Device)
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_SAMPLE_RATE=%d\n", media.AudioCapture.SampleRate)
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_CHANNELS=%d\n", media.AudioCapture.Channels)
fmt.Fprintf(&buf, "ROVERD_AUDIO_CAPTURE_BITRATE=%d\n", media.AudioCapture.Bitrate)
fmt.Fprintf(&buf, "ROVERD_AUDIO_PLAYBACK_ENABLE=%d\n", boolToInt(media.AudioPlayback.Enabled))
fmt.Fprintf(&buf, "ROVERD_AUDIO_PLAYBACK_FORWARD_URL=%s\n", media.AudioPlayback.ForwardURL)
fmt.Fprintf(&buf, "ROVERD_AUDIO_PLAYBACK_DEVICE=%s\n", media.AudioPlayback.Device)
fmt.Fprintf(&buf, "ROVERD_AUDIO_PLAYBACK_NORMALIZE=%d\n", boolToInt(media.AudioPlayback.Normalize))
fmt.Fprintf(&buf, "ROVERD_AUDIO_PLAYBACK_NORMALIZE_FILTER=%s\n", media.AudioPlayback.NormalizeFilter)
if err := os.WriteFile(publisherEnvPath, buf.Bytes(), 0o640); err != nil {
return err
}
return nil
}
func boolToInt(v bool) int {
if v {
return 1
}
return 0
}
+114
View File
@@ -0,0 +1,114 @@
package roverd
import (
"bytes"
"fmt"
"gopkg.in/yaml.v3"
"os"
"path/filepath"
"regexp"
)
var mediaCategories = []string{"video", "audioCapture", "audioPlayback"}
var profileID = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]*$`)
type MediaProfile struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name" json:"name"`
Description string `yaml:"description" json:"description"`
Setup string `yaml:"setup" json:"setup"`
Run string `yaml:"run" json:"run"`
}
func validateProfile(p MediaProfile) error {
if !profileID.MatchString(p.ID) || p.Name == "" || p.Run == "" {
return fmt.Errorf("profile requires a lowercase identifier, name, and run command")
}
return nil
}
func LoadMediaProfiles(repo string) (map[string][]MediaProfile, error) {
catalogs := make(map[string][]MediaProfile)
for _, category := range mediaCategories {
data, err := os.ReadFile(filepath.Join(repo, "rover", "profiles", category+".yaml"))
if err != nil {
return nil, err
}
decoder := yaml.NewDecoder(bytes.NewReader(data))
decoder.KnownFields(true)
var profiles []MediaProfile
if err := decoder.Decode(&profiles); err != nil {
return nil, fmt.Errorf("%s: %w", category, err)
}
seen := map[string]bool{}
for _, p := range profiles {
if err := validateProfile(p); err != nil {
return nil, err
}
if p.ID == "custom" || seen[p.ID] {
return nil, fmt.Errorf("duplicate/reserved profile %s", p.ID)
}
seen[p.ID] = true
}
data, err = os.ReadFile(filepath.Join("/etc/roverd/profiles", category+".yaml"))
if err == nil {
var custom MediaProfile
decoder = yaml.NewDecoder(bytes.NewReader(data))
decoder.KnownFields(true)
if err = decoder.Decode(&custom); err != nil {
return nil, err
}
if err = validateProfile(custom); err != nil {
return nil, err
}
if custom.ID != "custom" {
return nil, fmt.Errorf("custom profile ID must be custom")
}
profiles = append(profiles, custom)
} else if !os.IsNotExist(err) {
return nil, err
}
catalogs[category] = profiles
}
return catalogs, nil
}
func SaveCustomProfile(category string, profile MediaProfile) error {
valid := false
for _, name := range mediaCategories {
if category == name {
valid = true
}
}
if !valid {
return fmt.Errorf("unknown media category")
}
profile.ID = "custom"
if err := validateProfile(profile); err != nil {
return err
}
data, err := yaml.Marshal(profile)
if err != nil {
return err
}
dir := "/etc/roverd/profiles"
if err = os.MkdirAll(dir, 0755); err != nil {
return err
}
file, err := os.CreateTemp(dir, ".profile-*")
if err != nil {
return err
}
defer os.Remove(file.Name())
defer file.Close()
if _, err = file.Write(data); err != nil {
return err
}
if err = file.Sync(); err != nil {
return err
}
if err = file.Close(); err != nil {
return err
}
return os.Rename(file.Name(), filepath.Join(dir, category+".yaml"))
}
+173 -125
View File
@@ -2,162 +2,210 @@ package roverd
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"sync"
"syscall"
"time"
)
type MediaSupervisor struct {
cfg MediaConfig
logger *log.Logger
client *http.Client
checkInterval time.Duration
statusMu sync.Mutex
statuses map[string]string
cfg *Config
repo string
profiles map[string][]MediaProfile
events chan RoverEvent
logger *log.Logger
mu sync.Mutex
setupMu sync.Mutex
cancel context.CancelFunc
done chan struct{}
}
func NewMediaSupervisor(cfg MediaConfig, logger *log.Logger) *MediaSupervisor {
if err := UpdatePublisherEnv(cfg); err != nil {
logger.Printf("media supervisor: update env failed: %v", err)
}
if !cfg.Manage {
return nil
}
interval := cfg.HealthInterval.Duration
if interval <= 0 {
interval = 30 * time.Second
}
var client *http.Client
if cfg.HealthURL != "" {
client = &http.Client{Timeout: 5 * time.Second}
}
return &MediaSupervisor{
cfg: cfg,
logger: logger,
client: client,
checkInterval: interval,
func NewMediaSupervisor(cfg *Config, repo string, events chan RoverEvent, logger *log.Logger) (*MediaSupervisor, error) {
profiles, err := LoadMediaProfiles(repo)
if err != nil {
return nil, err
}
return &MediaSupervisor{cfg: cfg, repo: repo, profiles: profiles, events: events, logger: logger, statuses: make(map[string]string)}, nil
}
func (m *MediaSupervisor) Profiles() map[string][]MediaProfile { return m.profiles }
func (m *MediaSupervisor) emit(kind, category, message string) {
if kind == "media.status" {
m.statusMu.Lock()
m.statuses[category] = message
m.statusMu.Unlock()
}
event := RoverEvent{Type: "event", Event: kind, Ts: time.Now().UnixMilli(), Data: map[string]any{"category": category, "message": message}}
select {
case m.events <- event:
default:
} // Never block a child on a slow/disconnected server.
}
func (m *MediaSupervisor) Start(ctx context.Context) {
if m == nil {
return
}
if err := UpdatePublisherEnv(m.cfg); err != nil {
m.logger.Printf("media supervisor: update env failed: %v", err)
}
if m.cfg.HealthURL == "" || m.client == nil {
m.mu.Lock()
defer m.mu.Unlock()
if m.cancel != nil {
return
}
ctx, m.cancel = context.WithCancel(ctx)
m.done = make(chan struct{})
go func() {
ticker := time.NewTicker(m.checkInterval)
defer ticker.Stop()
if err := m.checkAndRepair(); err != nil {
m.logger.Printf("media supervisor: %v", err)
}
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if err := m.checkAndRepair(); err != nil {
m.logger.Printf("media supervisor: %v", err)
}
defer close(m.done)
var workers sync.WaitGroup
for _, category := range mediaCategories {
enabled, id := m.selection(category)
if !enabled {
m.emit("media.status", category, "disabled")
continue
}
workers.Add(1)
go func(category, id string) { defer workers.Done(); m.supervise(ctx, category, id) }(category, id)
}
workers.Wait()
}()
}
func (m *MediaSupervisor) HandleAction(ctx context.Context, action string) error {
if m == nil {
return errors.New("media supervisor disabled")
func (m *MediaSupervisor) Stop() {
m.mu.Lock()
defer m.mu.Unlock()
if m.cancel == nil {
return
}
if err := UpdatePublisherEnv(m.cfg); err != nil {
return err
}
switch action {
case "start", "stop", "restart", "reload", "status":
return m.runSystemctl(ctx, action)
m.cancel()
<-m.done
m.cancel = nil
}
func (m *MediaSupervisor) selection(category string) (bool, string) {
switch category {
case "video":
return m.cfg.Media.Video.Enabled, m.cfg.Media.Video.Profile
case "audioCapture":
return m.cfg.Media.AudioCapture.Enabled, m.cfg.Media.AudioCapture.Profile
default:
return fmt.Errorf("unknown media action: %s", action)
return m.cfg.Media.AudioPlayback.Enabled, m.cfg.Media.AudioPlayback.Profile
}
}
func (m *MediaSupervisor) checkAndRepair() error {
ctx, cancel := context.WithTimeout(context.Background(), 7*time.Second)
defer cancel()
if m.checkHealth(ctx) {
return nil
}
m.logger.Printf("media supervisor: health check failed, restarting configured media services")
if err := m.runSystemctl(ctx, "restart"); err != nil {
return fmt.Errorf("restart media services: %w", err)
func (m *MediaSupervisor) HandleAction(_ context.Context, action string) error {
if action != "stop" {
return fmt.Errorf("save configuration to start or restart media")
}
m.Stop()
return nil
}
func (m *MediaSupervisor) checkHealth(ctx context.Context) bool {
if m.client == nil || m.cfg.HealthURL == "" {
return true
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, m.cfg.HealthURL, nil)
if err != nil {
m.logger.Printf("media supervisor: health request: %v", err)
return false
}
resp, err := m.client.Do(req)
if err != nil {
m.logger.Printf("media supervisor: health request failed: %v", err)
return false
}
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, resp.Body)
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return true
}
m.logger.Printf("media supervisor: unexpected health status %d", resp.StatusCode)
return false
}
func (m *MediaSupervisor) runSystemctl(ctx context.Context, action string) error {
services := m.managedServices()
if len(services) == 0 {
return errors.New("no media services configured")
}
runCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
for _, service := range services {
cmd := exec.CommandContext(runCtx, "systemctl", action, service)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("systemctl %s %s: %w (%s)", action, service, err, string(output))
func (m *MediaSupervisor) supervise(ctx context.Context, category, id string) {
var profile *MediaProfile
for _, p := range m.profiles[category] {
if p.ID == id {
copy := p
profile = &copy
break
}
}
return nil
if profile == nil {
m.emit("media.status", category, "unknown profile: "+id)
return
}
dir := filepath.Join("/var/lib/roverd/profiles", category, id)
if err := os.MkdirAll(dir, 0755); err != nil {
m.emit("media.status", category, err.Error())
return
}
env := m.environment(dir)
if profile.Setup != "" {
m.emit("media.status", category, "setup")
m.setupMu.Lock()
err := m.command(ctx, category, dir, env, profile.Setup)
m.setupMu.Unlock()
if err != nil {
m.emit("media.status", category, "setup failed: "+err.Error())
return
}
}
for ctx.Err() == nil {
m.emit("media.status", category, "running")
err := m.command(ctx, category, dir, env, profile.Run)
if ctx.Err() != nil {
break
}
m.emit("media.status", category, fmt.Sprintf("exited (%v); retrying in 2s", err))
select {
case <-ctx.Done():
case <-time.After(2 * time.Second):
}
}
m.emit("media.status", category, "stopped")
}
func (m *MediaSupervisor) managedServices() []string {
/*
Only enabled streams are service-managed. This matters for audio capture:
the service may be installed everywhere, but a rover with capture disabled
should not have remote media commands starting a publisher that the config
says should stay off.
*/
services := []string{}
if m.cfg.Video.Enabled && m.cfg.Video.Service != "" {
services = append(services, m.cfg.Video.Service)
type mediaOutput struct {
supervisor *MediaSupervisor
category string
}
func (w mediaOutput) Write(data []byte) (int, error) {
// Split even output without newlines into bounded messages.
count := len(data)
for len(data) > 0 {
n := len(data)
if n > 4096 {
n = 4096
}
w.supervisor.emit("media.output", w.category, string(data[:n]))
data = data[n:]
}
if m.cfg.AudioCapture.Enabled && m.cfg.AudioCapture.Service != "" {
services = append(services, m.cfg.AudioCapture.Service)
return count, nil
}
func (m *MediaSupervisor) command(ctx context.Context, category, dir string, env []string, command string) error {
cmd := exec.CommandContext(ctx, "/bin/bash", "-e", "-o", "pipefail", "-c", command)
cmd.Dir = dir
cmd.Env = env
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Stdout = mediaOutput{m, category}
cmd.Stderr = mediaOutput{m, category}
// Kill the entire group: shell pipelines must not survive cancellation or
// retain stdout pipes after their parent shell exits.
cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) }
cmd.WaitDelay = 2 * time.Second
if err := cmd.Start(); err != nil {
return err
}
if m.cfg.AudioPlayback.Enabled && m.cfg.AudioPlayback.Service != "" {
services = append(services, m.cfg.AudioPlayback.Service)
err := cmd.Wait()
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
return err
}
func (m *MediaSupervisor) environment(dir string) []string {
cfg := m.cfg
host, _ := url.Parse(cfg.ServerURL)
values := map[string]string{
"ROVER_NAME": cfg.Name, "ROVER_SERVER_HOST": host.Hostname(), "ROVER_PROFILE_DIR": dir, "ROVER_REPO_DIR": m.repo,
"ROVER_VIDEO_DEVICE": cfg.Media.Video.Device, "ROVER_VIDEO_INPUT_FORMAT": cfg.Media.Video.InputFormat,
"ROVER_VIDEO_WIDTH": strconv.Itoa(cfg.Media.Video.Width), "ROVER_VIDEO_HEIGHT": strconv.Itoa(cfg.Media.Video.Height),
"ROVER_VIDEO_FPS": strconv.Itoa(cfg.Media.Video.FPS), "ROVER_VIDEO_BITRATE": strconv.Itoa(cfg.Media.Video.Bitrate),
"ROVER_VIDEO_INVERTED": strconv.FormatBool(cfg.Media.Video.Inverted), "ROVER_VIDEO_SENSOR_MODE": cfg.Media.Video.SensorMode,
"ROVER_VIDEO_PUBLISH_URL": cfg.Media.Video.PublishURL, "ROVER_AUDIO_PUBLISH_URL": cfg.Media.AudioCapture.PublishURL,
"ROVER_AUDIO_PLAYBACK_URL": cfg.Media.AudioPlayback.ForwardURL, "ROVER_AUDIO_INPUT_DEVICE": "rover_capture", "ROVER_AUDIO_OUTPUT_DEVICE": "rover_forward",
"ROVER_AUDIO_SAMPLE_RATE": strconv.Itoa(cfg.Media.AudioCapture.SampleRate), "ROVER_AUDIO_CHANNELS": strconv.Itoa(cfg.Media.AudioCapture.Channels),
"ROVER_AUDIO_BITRATE": strconv.Itoa(cfg.Media.AudioCapture.Bitrate), "ROVER_AUDIO_NORMALIZE": strconv.FormatBool(cfg.Media.AudioPlayback.Normalize),
"ROVER_AUDIO_NORMALIZE_FILTER": cfg.Media.AudioPlayback.NormalizeFilter,
}
return services
env := os.Environ()
for key, value := range values {
env = append(env, key+"="+value)
}
return env
}
func (m *MediaSupervisor) Status() map[string]string {
m.statusMu.Lock()
defer m.statusMu.Unlock()
result := make(map[string]string)
for key, value := range m.statuses {
result[key] = value
}
return result
}
+10 -12
View File
@@ -53,15 +53,11 @@
"maxWheelSpeed": 350,
"media": {
"rtspPort": 8554,
"manage": false,
"healthUrl": "http://127.0.0.1:9997/v3/paths/list",
"healthInterval": "30s",
"video": {
"profile": "rpicam",
"enabled": true,
"service": "video-publisher.service",
"publisher": "pi-libcamera",
"device": "",
"inputFormat": "",
"device": "/dev/video0",
"inputFormat": "mjpeg",
"width": 640,
"height": 480,
"fps": 30,
@@ -70,22 +66,25 @@
"sensorMode": "1296:972"
},
"audioCapture": {
"profile": "alsa",
"enabled": false,
"service": "audio-only-publisher.service",
"device": "hw:0,0",
"sampleRate": 48000,
"channels": 2,
"bitrate": 510000
},
"audioPlayback": {
"profile": "alsa",
"enabled": true,
"service": "audio-forward-listener.service",
"device": "forward",
"normalize": true,
"normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled"
}
},
"audio": {
"inputDevice": "hw:0,0",
"outputDevice": "hw:0,0",
"mixerCard": "0",
"outputSampleRate": 48000,
"outputChannels": 2,
"ttsEnabled": false,
"defaultEngine": "flite",
"defaultVoice": "rms",
@@ -96,7 +95,6 @@
"volume": 0.25,
"sampleRate": 48000,
"channels": 1,
"device": "",
"sineGain": 1,
"sawGain": 0.7,
"maxDuration": "10s"
+10 -12
View File
@@ -53,15 +53,11 @@
"maxWheelSpeed": 350,
"media": {
"rtspPort": 8554,
"manage": true,
"healthUrl": "",
"healthInterval": "30s",
"video": {
"profile": "rpicam",
"enabled": true,
"service": "video-publisher.service",
"publisher": "pi-libcamera",
"device": "",
"inputFormat": "",
"device": "/dev/video0",
"inputFormat": "mjpeg",
"width": 640,
"height": 480,
"fps": 30,
@@ -70,22 +66,25 @@
"sensorMode": "1296:972"
},
"audioCapture": {
"profile": "alsa",
"enabled": false,
"service": "audio-only-publisher.service",
"device": "hw:0,0",
"sampleRate": 48000,
"channels": 2,
"bitrate": 510000
},
"audioPlayback": {
"profile": "alsa",
"enabled": true,
"service": "audio-forward-listener.service",
"device": "forward",
"normalize": true,
"normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled"
}
},
"audio": {
"inputDevice": "hw:0,0",
"outputDevice": "hw:0,0",
"mixerCard": "0",
"outputSampleRate": 48000,
"outputChannels": 2,
"ttsEnabled": false,
"defaultEngine": "flite",
"defaultVoice": "rms",
@@ -96,7 +95,6 @@
"volume": 0.25,
"sampleRate": 48000,
"channels": 1,
"device": "",
"sineGain": 1,
"sawGain": 0.7,
"maxDuration": "1.2s"
@@ -53,13 +53,9 @@
"maxWheelSpeed": 350,
"media": {
"rtspPort": 8554,
"manage": true,
"healthUrl": "",
"healthInterval": "30s",
"video": {
"profile": "v4l2",
"enabled": true,
"service": "debian-laptop-video-publisher.service",
"publisher": "debian-laptop-v4l2",
"device": "/dev/video0",
"inputFormat": "mjpeg",
"width": 640,
@@ -70,22 +66,25 @@
"sensorMode": "1296:972"
},
"audioCapture": {
"profile": "alsa",
"enabled": true,
"service": "audio-only-publisher.service",
"device": "default",
"sampleRate": 48000,
"channels": 2,
"bitrate": 510000
},
"audioPlayback": {
"profile": "alsa",
"enabled": true,
"service": "audio-forward-listener.service",
"device": "forward",
"normalize": true,
"normalizeFilter": "dynaudnorm=f=75:g=15:m=10:p=0.9,alimiter=limit=0.85:level=disabled"
}
},
"audio": {
"inputDevice": "hw:0,0",
"outputDevice": "hw:0,0",
"mixerCard": "0",
"outputSampleRate": 48000,
"outputChannels": 2,
"ttsEnabled": true,
"defaultEngine": "flite",
"defaultVoice": "rms",
@@ -96,7 +95,6 @@
"volume": 0.25,
"sampleRate": 48000,
"channels": 1,
"device": "",
"sineGain": 1,
"sawGain": 0.7,
"maxDuration": "10s"
@@ -1,18 +0,0 @@
[Unit]
Description=Rover Audio Forward Listener (RTSP/TCP -> ALSA)
After=network-online.target roverd.service
Wants=network-online.target
[Service]
Type=simple
User=roverd
Group=roverd
EnvironmentFile=/var/lib/roverd/media.env
ExecStart=/usr/local/bin/audio-forward-listener
KillMode=control-group
TimeoutStopSec=5
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
@@ -1,18 +0,0 @@
[Unit]
Description=Rover Audio Publisher (ALSA -> RTSP/TCP)
After=network-online.target roverd.service
Wants=network-online.target
[Service]
Type=simple
User=roverd
Group=roverd
EnvironmentFile=/var/lib/roverd/media.env
ExecStart=/usr/local/bin/audio-only-publisher
KillMode=control-group
TimeoutStopSec=5
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
@@ -1,17 +0,0 @@
[Unit]
Description=Rover Debian Laptop Video Publisher (V4L2 -> RTSP/TCP)
After=network-online.target roverd.service
Wants=network-online.target
[Service]
Type=simple
User=roverd
Group=roverd
WorkingDirectory=/var/lib/roverd
EnvironmentFile=/var/lib/roverd/media.env
ExecStart=/usr/local/bin/debian-laptop-video-publisher
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
-17
View File
@@ -1,17 +0,0 @@
[Unit]
Description=Rover Video Publisher (libcamera -> RTSP/TCP)
After=network-online.target roverd.service
Wants=network-online.target
[Service]
Type=simple
User=roverd
Group=roverd
WorkingDirectory=/var/lib/roverd
EnvironmentFile=/var/lib/roverd/media.env
ExecStart=/usr/local/bin/video-publisher
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target