diff --git a/README.md b/README.md index f4ad773f..2153cd91 100644 --- a/README.md +++ b/README.md @@ -56,19 +56,16 @@ These are the basics of how evertything is connected on my rovers, this is hard 4. optionally, a laser pointer connected to another high current driver output, GPIO 27 by default. ### Software on your rover -Raspberry pi OS installation: +Roverd targets Debian-based systems with ARMv6, ARMv7, ARM64, or AMD64 binaries. For the existing AIY Voice HAT rover, use Raspberry Pi OS Bookworm; that hardware setup has not been verified on Trixie. -Everything that runs on the pi is designed for debian Bookworm, because I could not get the AIY voice hat working in Trixie. +The standalone installer is still being implemented. For now: +1. Set up the OS and networking. +2. Install `git` and clone this repository. +3. From the repository, run `sudo rover/install_roverd.sh`. +4. Configure `/etc/roverd.json`, including the rover name, server address, physical audio devices, and enabled media profiles. Media and native Pi GPIO are disabled by default. +5. Run `sudo systemctl restart roverd`. -To install roverd on your pi: -1. Install `Raspberry Pi OS (Legacy) Lite` (exactly what its called in the imager) on your SD card -2. Boot the pi up, plug in your good wifi adapter, use `nmtui` to set it up -3. Install `git`, clone this repo into your home folder -4. Move into the repo folder, run the roverd installer using `sudo rover/install_roverd.sh` -5. Reboot your raspberry pi -6. Roverd, along with the audio and video publishers should now be running. Roverd should have created it's default config file at `/etc/roverd.json` - -Edit the `/etc/roverd.json` config file to change settings like your rover's name, color, and set the server IP. +Roverd supervises the selected streamer commands itself. Disable/remove any previously installed streamer services before starting it. The AIY profiles may request a one-time reboot to activate their boot overlay. See [media profiles and audio routing](docs/rover-media-profiles.md) for configuration and deployment checks. Configuration is now a complete JSON object. See [roverd management](docs/roverd-management.md) for schema/default export, local validation, the management API, and deployment checks. diff --git a/dist/dummy1.json b/dist/dummy1.json index b9f2388e..a32c7f25 100644 --- a/dist/dummy1.json +++ b/dist/dummy1.json @@ -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" diff --git a/dist/dummy2.json b/dist/dummy2.json index 71888904..cc7a5735 100644 --- a/dist/dummy2.json +++ b/dist/dummy2.json @@ -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" diff --git a/dist/dummy3.json b/dist/dummy3.json index c8e737ee..c9aa57b7 100644 --- a/dist/dummy3.json +++ b/dist/dummy3.json @@ -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" diff --git a/dist/roverd-linux-amd64 b/dist/roverd-linux-amd64 index 5796a0b3..43046859 100755 Binary files a/dist/roverd-linux-amd64 and b/dist/roverd-linux-amd64 differ diff --git a/dist/roverd-linux-arm64 b/dist/roverd-linux-arm64 index d910290c..d98ef7d0 100755 Binary files a/dist/roverd-linux-arm64 and b/dist/roverd-linux-arm64 differ diff --git a/dist/roverd-linux-armv6 b/dist/roverd-linux-armv6 index 9749aa9a..109e16d2 100755 Binary files a/dist/roverd-linux-armv6 and b/dist/roverd-linux-armv6 differ diff --git a/dist/roverd-linux-armv7 b/dist/roverd-linux-armv7 index d583a8cb..0143cff2 100755 Binary files a/dist/roverd-linux-armv7 and b/dist/roverd-linux-armv7 differ diff --git a/docs/rover-hardware-config.md b/docs/rover-hardware-config.md index 52ce54ea..09b64fd8 100644 --- a/docs/rover-hardware-config.md +++ b/docs/rover-hardware-config.md @@ -1,6 +1,6 @@ # Rover hardware configuration notes -This document records hardware-specific requirements while the roverd rework is in progress. The existing installer still contains machine-specific setup; the universal bootstrap and media profiles are not implemented yet. Final profile names and JSON examples will be added when those interfaces exist. +This document records hardware-specific requirements while the roverd rework is in progress. Media profiles and shared audio routing are implemented. The standalone bootstrap remains unfinished; current installation uses a checkout. Configuration selections are recorded below. ## Universal configuration requirements @@ -16,11 +16,11 @@ Roverd configuration selects one physical input device and one physical output d The microphone streamer uses the selected input. TTS, horn, and forwarded audio share the selected output while retaining simultaneous playback and separate volume controls. Profiles use the generated logical devices supplied through their environment; they do not each hardcode or independently select physical audio hardware. Use ALSA conversion where supported instead of requiring all devices to accept the existing HAT playback format. -AIY setup enables its hardware and uses this same routing system. The bootstrap still asks only for rover name and server address. This design is agreed but not yet implemented. +AIY setup enables its hardware and uses this same routing system. The bootstrap still asks only for rover name and server address. Audio routing is implemented; the standalone bootstrap remains planned. -## Existing AIY Voice HAT setup +## Historical AIY Voice HAT setup -These facts come from the repository's existing installer/configuration, not a live hardware check: +These facts record the previous installer/configuration, not a live hardware check or the current implementation: - The Pi installer enables `dtoverlay=googlevoicehat-soundcard` and `dtparam=i2s=on`, and disables onboard audio with `dtparam=audio=off`. - The README records that this setup worked on Raspberry Pi OS Bookworm and had problems on Trixie. The rework must not imply that the HAT is verified on every Debian release. @@ -40,12 +40,28 @@ For the new internal GPIO peripheral, enable `piGpio.enabled` on a rover that us The parent switch now defaults to disabled. Saved child settings do not enable GPIO on their own. External peripherals must not advertise the same enabled role unless the conflicting internal role is disabled. -## Remaining implementation work +## Implementation and verification tracking -- [ ] Add AIY capture/playback profiles alongside generic selectable ALSA device profiles. -- [ ] Make TTS, horn, forwarded audio, and mixer routing use configured devices consistently. -- [ ] Generate ALSA routing from the shared input/output configuration, including distinct input/output cards, logical profile devices, format conversion, and independent playback volume controls. +- [x] Add AIY capture/playback profiles alongside generic selectable ALSA device profiles. +- [x] Make TTS, horn, forwarded audio, and mixer routing use configured devices consistently. +- [x] Generate ALSA routing from the shared input/output configuration, including distinct input/output cards, logical profile devices, format conversion, and independent playback volume controls. - [ ] Audit fixed card numbers, named PCM assumptions, capture formats, camera orientation/sensor defaults, serial device defaults, and architecture-specific TTS assets. -- [ ] Keep required one-time host boot changes visible; distinguish a hardware-overlay reboot from ordinary roverd update/restart behavior. -- [ ] Add exact final profile selections and JSON settings for the existing AIY rover. +- [x] Keep required one-time host boot changes visible; distinguish a hardware-overlay reboot from ordinary roverd update/restart behavior. +- [x] Add exact final profile selections and JSON settings for the existing AIY rover. - [ ] Verify on the actual HAT and at least one non-HAT audio device; record results rather than assuming compatibility. + +## Implemented profile/audio selections (2026-11-16) + +The new supervisor and generated ALSA routing are implemented, but not hardware-verified. See [media profile documentation](rover-media-profiles.md). Bundled setup/run commands are contained in YAML, not repository shell helpers. + +For the existing AIY v1 setup, start with these fields in a complete current config: + +- `media.video.profile`: `rpicam`, enabled for the CSI camera; retain the existing resolution/bitrate, inverted mounting, and sensor mode if appropriate. +- `media.audioCapture.profile` and `media.audioPlayback.profile`: `aiy`, enabling each required streamer. Their inline setup enables I2S and the Google Voice HAT overlay. Reboot once if setup changes boot configuration. +- `audio.inputDevice` and `audio.outputDevice`: `hw:CARD=sndrpigooglevoi,DEV=0`, **after verifying that identifier on the rover**. +- `audio.mixerCard`: `sndrpigooglevoi`, matching the verified output card. +- `audio.outputSampleRate`: `16000`; `audio.outputChannels`: `1`, preserving the old HAT mixing format. +- `audio.ttsEnabled`: true if desired; choose `audio.defaultEngine` explicitly. Chrome speech assets now live outside the checkout under `/var/lib/roverd/googletts`. +- Enable the parent `piGpio.enabled` and the desired child roles as described above. The old automatic PWM-overlay installer is gone; the GPIO12/13 PWM overlay remains a documented host wiring requirement, not an audio-profile side effect. + +The HAT setup does not disable unrelated onboard audio or force a card index. Use the configured stable device/card names. Existing installed media systemd units must be removed/disabled before running the new supervisor. Remove any old roverd-specific host ALSA configuration before deployment: the generated config includes the system ALSA definitions, whose hooks can still load host configuration. The old media launchers are no longer used. diff --git a/docs/rover-media-profiles.md b/docs/rover-media-profiles.md new file mode 100644 index 00000000..82917e91 --- /dev/null +++ b/docs/rover-media-profiles.md @@ -0,0 +1,57 @@ +# Rover media profiles and audio + +Roverd reads three YAML catalogs directly from its checkout: `rover/profiles/video.yaml`, `audioCapture.yaml`, and `audioPlayback.yaml`. Each is a list of profiles with `id`, `name`, `description`, optional `setup`, and `run`. + +Commands live in the YAML itself. Bundled profiles must not delegate their setup or run implementation to an in-repository shell helper. Multiline shell commands, arrays, and pipelines are supported through Bash with error/pipe failure handling. Profile identifiers use lowercase letters, digits, underscores, and hyphens; `custom` is reserved. + +Each enabled streamer runs its selected setup on every daemon startup. Setups are serialized to avoid competing package-manager operations; successful setup is not tracked on disk. Each run command then starts independently and retries after two seconds on exit. A failed setup leaves only that streamer stopped. Shutdown kills the complete process group and waits for it. Nothing installs media systemd services. + +Working directories are `/var/lib/roverd/profiles//`. Commands receive environment variables, not interpolated shell source. Quote variables normally. + +| Variables | Meaning | +| --- | --- | +| `ROVER_NAME`, `ROVER_SERVER_HOST` | Identity and server hostname | +| `ROVER_PROFILE_DIR`, `ROVER_REPO_DIR` | Persistent working directory and checkout | +| `ROVER_VIDEO_DEVICE`, `ROVER_VIDEO_INPUT_FORMAT` | Camera input | +| `ROVER_VIDEO_WIDTH`, `ROVER_VIDEO_HEIGHT`, `ROVER_VIDEO_FPS`, `ROVER_VIDEO_BITRATE` | Camera/encoder settings | +| `ROVER_VIDEO_INVERTED`, `ROVER_VIDEO_SENSOR_MODE` | Orientation and optional rpicam mode | +| `ROVER_VIDEO_PUBLISH_URL`, `ROVER_AUDIO_PUBLISH_URL`, `ROVER_AUDIO_PLAYBACK_URL` | Complete derived RTSP URLs | +| `ROVER_AUDIO_INPUT_DEVICE`, `ROVER_AUDIO_OUTPUT_DEVICE` | Generated logical ALSA microphone and forwarded-audio routes | +| `ROVER_AUDIO_SAMPLE_RATE`, `ROVER_AUDIO_CHANNELS`, `ROVER_AUDIO_BITRATE` | Microphone encoding settings | +| `ROVER_AUDIO_NORMALIZE`, `ROVER_AUDIO_NORMALIZE_FILTER` | Forwarded-audio normalization | + +The bundled options are `v4l2` / `rpicam` for video and `alsa` / `aiy` for capture and playback. Hardware encoders or other transports can be supplied as custom commands without adding roverd code. + +## Configuration and UI + +Select `media.video.profile`, `media.audioCapture.profile`, and `media.audioPlayback.profile`, with each category's `enabled` switch. Fleet management renders profile names from the catalogs and has a “Media profiles and output” section for descriptions, current status, output, and custom editing. + +There is one custom profile per category, stored under `/etc/roverd/profiles/.yaml`. Saving it restarts roverd; select `custom` in configuration to use it. Bundled files remain in the checkout. The admin API is `roverManagement:saveProfile` with `{ roverId, category, profile }`. + +Output is always forwarded while management is connected, without viewer subscriptions. Rover queues and server/browser history are bounded; a noisy process can lose old output but cannot indefinitely block streaming or grow history. Current streamer status is retained separately and included in management hello. + +## Audio routing + +`audio.inputDevice` and `audio.outputDevice` select physical ALSA devices independently. Use hardware PCM identifiers such as `hw:CARD=Device,DEV=0`; find the actual identifiers with `arecord -l` and `aplay -l`. The output must support ALSA dmix's hardware slave; arbitrary sound-server/plugin PCM names are not interchangeable with a hardware PCM. + +`audio.mixerCard` selects the output card's mixer identifier. `audio.outputSampleRate` and `audio.outputChannels` configure its hardware mix format. Choose a format supported by that device; `plug` handles client conversion to that format. Input and output may be on separate cards. + +Roverd generates `/var/lib/roverd/asound.conf` and sets `ALSA_CONFIG_PATH` for its children. It does not overwrite the host's ALSA configuration. Its system ALSA include can still load host configuration through ALSA hooks; remove old roverd-specific host ALSA definitions before deployment. Logical devices are `rover_capture`, `rover_tts`, `rover_horn`, and `rover_forward`. TTS, horn, and forwarded audio share a dmix output and have independent soft-volume controls. `amixer` targets the configured mixer card, never a fallback card zero. Some soft-volume controls appear only once their PCM has first been opened; verify volume behavior after playback begins. + +Chrome TTS uses the same generated playback route. Its architecture-specific library/voice files are runtime data under `/var/lib/roverd/googletts`; the installer invokes the independent TTS dependency installer. ARMv6 hosts must use flite/espeak if no matching Chrome library is available. The server no longer substitutes Chrome TTS when a command omits an engine; roverd's configured default applies. + +## Inspection without hardware or setup execution + +```sh +./dist/roverd-linux-amd64 -repo "$PWD" -print-media-profiles +./dist/roverd-linux-amd64 -config rover/roverd/roverd.sample.json -check-config +./dist/roverd-linux-amd64 -config rover/roverd/roverd.sample.json -print-audio-config +``` + +These commands do not install packages, open devices, or start streams. Configuration/schema and architecture binaries have changed together; old JSON objects are not migrated. + +## Deployment checks still required + +Before deploying over an old installation, explicitly disable/remove its old media units so they cannot compete for devices or publish duplicate streams. This rework does not migrate an installed host. The checkout installer now installs only the roverd service and runtime dependencies; standalone bootstrap/update redesign remains a later stage. + +On the actual rover, confirm all selected profiles complete setup, observe output/status in fleet management, and verify video, microphone, forwarded audio, TTS, horn, simultaneous playback, and each gain control. Restart the server or interrupt Wi-Fi: media commands should retry without restarting roverd. Save configuration and verify no media child processes remain from the previous daemon. Capture journal output and observed results. AIY overlay changes require a one-time host reboot; ordinary configuration saves only restart roverd. diff --git a/docs/roverd-management.md b/docs/roverd-management.md index c8a14852..0bb7719e 100644 --- a/docs/roverd-management.md +++ b/docs/roverd-management.md @@ -24,7 +24,7 @@ Select the appropriate architecture binary on a rover. The default object suppli - Management starts independently of hardware initialization and remains available after serial/peripheral startup failure. - Control disconnect docking/reboot behavior still depends on control connectivity. A live management connection does not count as a working control connection. - The server maintains management records independently of the control roster, only in memory. Management disconnect removes the record; hello repopulates it. -- Profile catalogs in hello are currently empty. YAML media profiles are the next media implementation stage, not installed catalogs hidden elsewhere. +- Profile catalogs and current media status arrive in hello; see [media profiles](rover-media-profiles.md). ## Configuration page @@ -72,7 +72,7 @@ Record acknowledgement errors, reconnect hello contents, relevant journal/server ## Pending stages -Browser/live verification of configuration and operational state, YAML media catalogs/child supervision, universal ALSA routing, standalone bootstrap, and replacement update workflow remain pending. The current updater and systemd media supervisor have moved transport but retain their existing implementations until those stages. +YAML media catalogs, child supervision, shared ALSA routing, and Fleet Management profile controls are implemented. Browser/live verification of configuration, operational state, media, and audio remains pending. Standalone bootstrap and the replacement update workflow are the next implementation stage. Apply-field targets the currently management-connected fleet. It clones each rover’s own configuration, replaces an existing field, and sends the complete object for rover-side validation. Inspect individual results for failures. Missing fields and changed connections are reported; offline changes are not queued. Paths traverse object fields, not array elements. Array-valued fields can be replaced as a whole. diff --git a/docs/roverd-rework-plan.md b/docs/roverd-rework-plan.md index 507aa2fe..1acab6bb 100644 --- a/docs/roverd-rework-plan.md +++ b/docs/roverd-rework-plan.md @@ -1,6 +1,6 @@ # Roverd rework plan and implementation tracker -Status: implementation authorized on 2026-11-16; repository/build, internal GPIO, and JSON/management backend implemented; live management verification and remaining stages pending. +Status: implementation authorized on 2026-11-16; repository/build, internal GPIO, JSON/management, Fleet UI, rover state, media profiles/supervision, and shared audio routing implemented; deployment verification, standalone bootstrap, and update redesign remain pending. This is the persistent plan and progress record for the roverd rework. Update it as implementation proceeds, recording completed work, decisions, verification evidence, and remaining work. Keep unfinished work unchecked; distinguish implemented behavior from runtime-verified behavior. @@ -168,15 +168,15 @@ The order below is a working sequence, not a requirement to leave incompatible i - [x] Move reboot, update, media management, host statistics, and daemon status messages to management; update consumers. Preserve the separately authorized user reboot path. - [x] Separate management lifecycle from hardware startup failures (deployment verification pending). - [x] Implement full-object `roverState` and consolidate server/UI operational-state consumers (live verification pending). -- [ ] Add bundled YAML catalogs and one custom YAML profile per media category. -- [ ] Preserve AIY HAT as an explicit profile and expose ordinary audio-device selection on every architecture, including TTS/horn/mixer paths. -- [ ] Generate ALSA routing from shared input/output selections; connect microphone, TTS, horn, forwarded audio, and independent volume controls to the resulting logical devices. +- [x] Add bundled YAML catalogs and one custom YAML profile per media category. (Live verification pending.) +- [x] Preserve AIY HAT as an explicit profile and expose ordinary audio-device selection on every architecture, including TTS/horn/mixer paths. (Live verification pending.) +- [x] Generate ALSA routing from shared input/output selections; connect microphone, TTS, horn, forwarded audio, and independent volume controls to the resulting logical devices. (Live verification pending.) - [ ] Document exact configuration for the existing AIY rover and audit other machine-specific assumptions. -- [ ] Implement command environments, persistent working directories, and setup on each daemon startup. -- [ ] Replace media systemd management with child-process supervision and continuous bounded output forwarding. +- [x] Implement command environments, persistent working directories, and setup on each daemon startup. (Live verification pending.) +- [x] Replace media systemd management with child-process supervision and continuous bounded output forwarding. (Live verification pending.) - [x] Implement per-rover schema editor and complete-object saves (browser/live verification pending). - [x] Implement apply-one-field-to-all-connected-rovers with individual results (browser/live verification pending). -- [ ] Add profile editing/selection, media output/status, reboot, and update UI. +- [x] Add profile editing/selection, media output/status, reboot, and update UI. (Live verification pending.) - [ ] Implement standalone bootstrap with only name/address input and automatic OS architecture selection. - [ ] Implement shared checkout installation and self-update with reconnect-visible results. - [ ] Remove obsolete services, configuration files, scripts, build distinctions, and documentation. @@ -273,3 +273,15 @@ Verification for this stage: - All four architecture binaries rebuilt successfully; focused frontend lint and server syntax checks passed. The two existing roster lifecycle tests passed after updating their state fixture. No new tests added. - Still verify live initial state, toggles through both GPIO/Firmata, reconnect state, disconnect clearing, and darkness restoration. Production UI assets have not been rebuilt. - Next implementation stage: YAML media profiles, command environments and child-process supervision, alongside the planned universal audio routing. + +### Media profiles, supervision, and audio (2026-11-16) + +- Added three YAML catalogs with six profiles: V4L2/rpicam video, generic ALSA/AIY microphone and playback. All bundled setup/run commands are inline YAML; the user explicitly rejected delegation to repository shell helpers, and the AIY helper was removed. +- Each enabled streamer has a persistent working directory, startup setup, independent command restart, complete process-group cleanup, and bounded continuously forwarded output. Setup is serialized for package-manager access with no persistent completion markers. +- Management hello includes catalogs and current media status. Fleet management exposes profile selection, exactly one editable custom profile per category, status, and output. Output is not emitted as chat alerts. +- Shared audio input/output settings generate a private ALSA config for microphone, TTS, horn, and forwarded audio, retaining mixing and independent gains. Hardware output PCM, mixer card, rate, and channels are explicit settings. See hardware notes for AIY values and limitations. +- Removed old media services/launchers, old machine-specific installer modules, static ALSA configs, and duplicate Chrome daemon. The checkout installer now installs only roverd plus runtime dependencies. Standalone bootstrap and self-update redesign remain unfinished. +- The server now respects roverd's configured default speech engine. TTS assets live under `/var/lib/roverd/googletts`; the generic dependency helper selects architecture-specific libraries. +- Added real CLI inspection for catalogs and generated ALSA configuration, without setup execution or hardware access. +- Verification: all four architecture builds passed; six profiles loaded through the actual daemon and all setup/run commands passed Bash syntax checks; current sample config validation and ALSA config rendering passed; installer/TTS shell syntax and server JS syntax passed. Focused frontend lint passed including the final status-display changes. No camera/audio streaming, setup commands, host installation, or browser/server processes were run here. +- Next: verify the remaining frontend check, then standalone bootstrap and update flow. Actual device formats, concurrent playback/gains, child cleanup and network recovery still require the documented rover-side checks. diff --git a/rover/asound.conf b/rover/asound.conf deleted file mode 100644 index b337553d..00000000 --- a/rover/asound.conf +++ /dev/null @@ -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 -} diff --git a/rover/asound.debian-laptop.conf b/rover/asound.debian-laptop.conf deleted file mode 100644 index f2275d39..00000000 --- a/rover/asound.debian-laptop.conf +++ /dev/null @@ -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 -} diff --git a/rover/bin/audio-forward-listener.sh b/rover/bin/audio-forward-listener.sh deleted file mode 100755 index 067d4132..00000000 --- a/rover/bin/audio-forward-listener.sh +++ /dev/null @@ -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 diff --git a/rover/bin/audio-only-publisher.sh b/rover/bin/audio-only-publisher.sh deleted file mode 100644 index f6e646d0..00000000 --- a/rover/bin/audio-only-publisher.sh +++ /dev/null @@ -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 diff --git a/rover/bin/chromegtts-daemon-laptop.py b/rover/bin/chromegtts-daemon-laptop.py deleted file mode 100644 index 46fad6f6..00000000 --- a/rover/bin/chromegtts-daemon-laptop.py +++ /dev/null @@ -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(" 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()) diff --git a/rover/bin/chromegtts-daemon.py b/rover/bin/chromegtts-daemon.py index 2eb7bd1f..a407ba05 100644 --- a/rover/bin/chromegtts-daemon.py +++ b/rover/bin/chromegtts-daemon.py @@ -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 diff --git a/rover/bin/debian-laptop-video-publisher.sh b/rover/bin/debian-laptop-video-publisher.sh deleted file mode 100755 index 2185e3bf..00000000 --- a/rover/bin/debian-laptop-video-publisher.sh +++ /dev/null @@ -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 diff --git a/rover/bin/media-transport.test.sh b/rover/bin/media-transport.test.sh deleted file mode 100755 index a24ab76f..00000000 --- a/rover/bin/media-transport.test.sh +++ /dev/null @@ -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" diff --git a/rover/bin/setup-tts.sh b/rover/bin/setup-tts.sh new file mode 100644 index 00000000..45d1e94c --- /dev/null +++ b/rover/bin/setup-tts.sh @@ -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 diff --git a/rover/bin/video-publisher.sh b/rover/bin/video-publisher.sh deleted file mode 100644 index 1e5e82d5..00000000 --- a/rover/bin/video-publisher.sh +++ /dev/null @@ -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 diff --git a/rover/install/common.sh b/rover/install/common.sh deleted file mode 100644 index 9fca958e..00000000 --- a/rover/install/common.sh +++ /dev/null @@ -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" -} diff --git a/rover/install/debian_laptop_profile.sh b/rover/install/debian_laptop_profile.sh deleted file mode 100644 index c9060022..00000000 --- a/rover/install/debian_laptop_profile.sh +++ /dev/null @@ -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 &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" </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" </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 -} diff --git a/rover/install/media_env.sh b/rover/install/media_env.sh deleted file mode 100644 index e4f7ddb5..00000000 --- a/rover/install/media_env.sh +++ /dev/null @@ -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 -} diff --git a/rover/install/pi_profile.sh b/rover/install/pi_profile.sh deleted file mode 100644 index 523c0733..00000000 --- a/rover/install/pi_profile.sh +++ /dev/null @@ -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 -} diff --git a/rover/install/profiles.sh b/rover/install/profiles.sh deleted file mode 100644 index d0b63dcb..00000000 --- a/rover/install/profiles.sh +++ /dev/null @@ -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 Install profile: pi or debian-laptop (default: pi) - --debian-laptop Shortcut for --profile debian-laptop - -b, --binary Path to the roverd binary (default: detected OS architecture) - -c, --config 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 -} diff --git a/rover/install/self_update.sh b/rover/install/self_update.sh index 201a2fd8..0419a313 100644 --- a/rover/install/self_update.sh +++ b/rover/install/self_update.sh @@ -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" < "$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" } diff --git a/rover/install/systemd.sh b/rover/install/systemd.sh deleted file mode 100644 index b8d018d3..00000000 --- a/rover/install/systemd.sh +++ /dev/null @@ -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 -} diff --git a/rover/install_roverd.sh b/rover/install_roverd.sh index 11530cbc..718a5319 100755 --- a/rover/install_roverd.sh +++ b/rover/install_roverd.sh @@ -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.' diff --git a/rover/profiles/audioCapture.yaml b/rover/profiles/audioCapture.yaml new file mode 100644 index 00000000..92a70b29 --- /dev/null +++ b/rover/profiles/audioCapture.yaml @@ -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 diff --git a/rover/profiles/audioPlayback.yaml b/rover/profiles/audioPlayback.yaml new file mode 100644 index 00000000..803970a4 --- /dev/null +++ b/rover/profiles/audioPlayback.yaml @@ -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 diff --git a/rover/profiles/video.yaml b/rover/profiles/video.yaml new file mode 100644 index 00000000..f36369ea --- /dev/null +++ b/rover/profiles/video.yaml @@ -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" diff --git a/rover/roverd/audio_levels.go b/rover/roverd/audio_levels.go index 8716d2b5..03a1d727 100644 --- a/rover/roverd/audio_levels.go +++ b/rover/roverd/audio_levels.go @@ -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 } diff --git a/rover/roverd/audio_routing.go b/rover/roverd/audio_routing.go new file mode 100644 index 00000000..6b74faaa --- /dev/null +++ b/rover/roverd/audio_routing.go @@ -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 := "\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) +} diff --git a/rover/roverd/cmd/roverd/main.go b/rover/roverd/cmd/roverd/main.go index aad7b70e..adb08482 100644 --- a/rover/roverd/cmd/roverd/main.go +++ b/rover/roverd/cmd/roverd/main.go @@ -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)) diff --git a/rover/roverd/config.go b/rover/roverd/config.go index 904976fb..18c8e770 100644 --- a/rover/roverd/config.go +++ b/rover/roverd/config.go @@ -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 "-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" } diff --git a/rover/roverd/horn.go b/rover/roverd/horn.go index cdb5e496..53f40fc8 100644 --- a/rover/roverd/horn.go +++ b/rover/roverd/horn.go @@ -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() diff --git a/rover/roverd/management.go b/rover/roverd/management.go index c629dbc5..42aa6890 100644 --- a/rover/roverd/management.go +++ b/rover/roverd/management.go @@ -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() +} diff --git a/rover/roverd/media_env.go b/rover/roverd/media_env.go deleted file mode 100644 index e3b1d38d..00000000 --- a/rover/roverd/media_env.go +++ /dev/null @@ -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 -} diff --git a/rover/roverd/media_profiles.go b/rover/roverd/media_profiles.go new file mode 100644 index 00000000..fe5ade87 --- /dev/null +++ b/rover/roverd/media_profiles.go @@ -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")) +} diff --git a/rover/roverd/media_supervisor.go b/rover/roverd/media_supervisor.go index 6e725dd1..b2d2ce23 100644 --- a/rover/roverd/media_supervisor.go +++ b/rover/roverd/media_supervisor.go @@ -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 = © + 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 } diff --git a/rover/roverd/roverd.json b/rover/roverd/roverd.json index 1516179b..f387a61b 100644 --- a/rover/roverd/roverd.json +++ b/rover/roverd/roverd.json @@ -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" diff --git a/rover/roverd/roverd.sample.json b/rover/roverd/roverd.sample.json index 102327af..0e51c320 100644 --- a/rover/roverd/roverd.sample.json +++ b/rover/roverd/roverd.sample.json @@ -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" diff --git a/rover/roverd/roverd.debian-laptop.sample.json b/rover/roverd/roverd.v4l2.sample.json similarity index 88% rename from rover/roverd/roverd.debian-laptop.sample.json rename to rover/roverd/roverd.v4l2.sample.json index d1e0f098..3b82871b 100644 --- a/rover/roverd/roverd.debian-laptop.sample.json +++ b/rover/roverd/roverd.v4l2.sample.json @@ -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" diff --git a/rover/systemd/audio-forward-listener.service b/rover/systemd/audio-forward-listener.service deleted file mode 100644 index b578c062..00000000 --- a/rover/systemd/audio-forward-listener.service +++ /dev/null @@ -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 diff --git a/rover/systemd/audio-only-publisher.service b/rover/systemd/audio-only-publisher.service deleted file mode 100644 index 1af0b999..00000000 --- a/rover/systemd/audio-only-publisher.service +++ /dev/null @@ -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 diff --git a/rover/systemd/debian-laptop-video-publisher.service b/rover/systemd/debian-laptop-video-publisher.service deleted file mode 100644 index a6d76fd6..00000000 --- a/rover/systemd/debian-laptop-video-publisher.service +++ /dev/null @@ -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 diff --git a/rover/systemd/video-publisher.service b/rover/systemd/video-publisher.service deleted file mode 100644 index 42f52c3b..00000000 --- a/rover/systemd/video-publisher.service +++ /dev/null @@ -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 diff --git a/server/src/services/commandService/index.js b/server/src/services/commandService/index.js index 5fdbed89..8d10c984 100644 --- a/server/src/services/commandService/index.js +++ b/server/src/services/commandService/index.js @@ -66,26 +66,6 @@ function enforceLaserRoomLightLock(reason) { forceAllRoverLasersOff(reason); } -function normalizeOutboundCommandPayload(payload = {}) { - if (payload?.type !== 'tts') return payload; - - const tts = payload.tts && typeof payload.tts === 'object' ? payload.tts : {}; - const configuredEngine = typeof tts.engine === 'string' ? tts.engine.trim() : ''; - if (configuredEngine) return payload; - - // The server owns the default for commands it sends. Roverd still keeps its - // own local default for payloads that omit an engine from some other source, - // but normal server-issued TTS should prefer Google speech without requiring - // every caller to remember that policy. - return { - ...payload, - tts: { - ...tts, - engine: 'chromegtts', - }, - }; -} - function issueCommand(roverId, payload, options = {}) { if (['reboot', 'update', 'media'].includes(payload?.type)) { return roverManagement.issueCommand(roverId, payload); @@ -103,7 +83,7 @@ function issueCommand(roverId, payload, options = {}) { } payload = require('../dockingService').protectCommand(record, payload, options); const id = uuidv4(); - const normalizedPayload = normalizeOutboundCommandPayload(payload); + const normalizedPayload = payload; const message = { ...normalizedPayload, id }; record.ws.send(JSON.stringify(message)); observeCommand({ phase: 'dispatched', roverId, commandId: id, command: normalizedPayload }); diff --git a/server/src/services/roverManagementService/index.js b/server/src/services/roverManagementService/index.js index 67493997..d2fd64b2 100644 --- a/server/src/services/roverManagementService/index.js +++ b/server/src/services/roverManagementService/index.js @@ -17,6 +17,7 @@ function snapshot(record) { config: record.config, schema: record.schema, profiles: record.profiles, + mediaStatus: record.mediaStatus, hostStats: record.hostStats || null, notices: record.notices, }; @@ -82,7 +83,7 @@ managementWSS.on('connection', (ws) => { if (typeof msg.name !== 'string' || !msg.name || !msg.config || !msg.schema) throw new Error('Invalid management hello'); clearTimeout(helloTimeout); const previous = rovers.get(msg.name); - record = { roverId: msg.name, ws, config: msg.config, schema: msg.schema, profiles: msg.profiles, notices: [] }; + record = { roverId: msg.name, ws, config: msg.config, schema: msg.schema, profiles: msg.profiles, mediaStatus: msg.mediaStatus || {}, notices: [] }; rovers.set(record.roverId, record); previous?.ws.close(1000, 'Replaced by new connection'); notifyAdmins('roverManagement:changed', snapshot(record)); @@ -97,10 +98,11 @@ managementWSS.on('connection', (ws) => { require('../roverManager').handleHostStats(record.roverId, msg); notifyAdmins('roverManagement:hostStats', { roverId: record.roverId, ...msg }); } else if (msg.type === 'event') { + if (msg.event === 'media.status') record.mediaStatus[msg.data.category] = msg.data.message; record.notices.push(msg); if (record.notices.length > 100) record.notices.shift(); notifyAdmins('roverManagement:event', { roverId: record.roverId, ...msg }); - sendAlert({ color: '#00bcd4', title: record.roverId, message: msg.data?.message || msg.event }); + if (!msg.event?.startsWith('media.')) sendAlert({ color: '#00bcd4', title: record.roverId, message: msg.data?.message || msg.event }); } } catch (error) { logger.warn('Invalid management message', error.message); @@ -173,6 +175,11 @@ io.on('connection', (socket) => { })); return { results }; }); + bind('roverManagement:saveProfile', async ({ roverId, category, profile }) => { + const { id, result } = request(roverId, { type: 'profile.set', category, profile }); + await result; + return { id }; + }); bind('roverManagement:command', async ({ roverId, type, reboot, media }) => { if (!['reboot', 'update', 'media'].includes(type)) throw new Error('Unsupported management command'); const { id, result } = request(roverId, { type, reboot, media }); diff --git a/webui/src/admin/components/RoverConfigurationEditor.jsx b/webui/src/admin/components/RoverConfigurationEditor.jsx index 099606f9..250b32e2 100644 --- a/webui/src/admin/components/RoverConfigurationEditor.jsx +++ b/webui/src/admin/components/RoverConfigurationEditor.jsx @@ -26,6 +26,12 @@ function RoverForm({ socket, record, online }) { const [message, setMessage] = useState(''); const [results, setResults] = useState([]); const options = fields(record.schema); + const schema = structuredClone(record.schema); + for (const category of ['video', 'audioCapture', 'audioPlayback']) { + const property = schema.properties?.media?.properties?.[category]?.properties?.profile; + const profiles = record.profiles?.[category] || []; + if (property && profiles.length) property.oneOf = profiles.map((profile) => ({ const: profile.id, title: profile.name })); + } async function save(all) { setBusy(true); setMessage(''); @@ -50,7 +56,7 @@ function RoverForm({ socket, record, online }) {

{message}

{results.length > 0 &&
    {results.map((result) =>
  • {result.roverId}: {result.success ? 'Saved' : result.error}
  • )}
}
-
setDraft(formData)} onSubmit={() => save(false)}>
@@ -62,9 +68,49 @@ function RoverForm({ socket, record, online }) {
+ ; } +function MediaProfiles({ socket, record, online }) { + const [category, setCategory] = useState('video'); + const [profile, setProfile] = useState({ id: 'custom', name: '', description: '', setup: '', run: '' }); + const [message, setMessage] = useState(''); + const [busy, setBusy] = useState(false); + useEffect(() => { + setProfile(record.profiles?.[category]?.find((entry) => entry.id === 'custom') + || { id: 'custom', name: '', description: '', setup: '', run: '' }); + }, [category, record.profiles]); + async function save() { + setBusy(true); + try { + await request(socket, 'roverManagement:saveProfile', { roverId: record.roverId, category, profile }); + setMessage('Custom profile saved. Rover is restarting. Select custom in the media settings to use it.'); + } catch (error) { setMessage(error.message); } + finally { setBusy(false); } + } + return
+ Media profiles and output + + {(record.profiles?.[category] || []).map((entry) =>

{entry.name}: {entry.description}

)} +

Status: {record.mediaStatus?.[category] || (online ? 'Waiting for status' : 'Offline')}

+

Custom profile

+
+ {['name', 'description', 'setup', 'run'].map((key) =>