From 2f82a01ca97079685d059cd810df97b57ccf639f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 08:33:20 +0000 Subject: [PATCH] voelin-ui: settings through the settings service; free frame rate and bitrate The window read its blobs (ui, audio, client_playback) from the store once and wrote them back. It now opens the settings service on the client database, attaches it to the engine, registers its own keys (ui, client_playback), and loads config file, VOELIN_SETTING_* and `--set key=value` overrides below the stored values. Its edits are set on the service, which stores them off the UI thread and flushes on exit; changes made elsewhere (e.g. Command::SetSetting) update the window's copies of the audio, crash report and client volume settings. The crash report opt-in is the crash_reports key the Android app already read (and stays in the blob for older versions). The share dialog starts from stream.fps and stream.bitrate_kbps and takes any value typed next to the presets, which remain as shortcuts; what was used is stored back. docs/architecture.md describes stream discovery and the settings service. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-android/src/app.rs | 6 ++- crates/voelin-ui/src/app.rs | 84 ++++++++++++++++++++++++++++---- crates/voelin-ui/src/main.rs | 20 +++++++- crates/voelin-ui/src/settings.rs | 53 +++++++++++++++++--- crates/voelin-ui/src/streams.rs | 38 +++++++++++---- crates/voelin-ui/ui/app.slint | 20 ++++++++ docs/architecture.md | 20 ++++++++ 7 files changed, 212 insertions(+), 29 deletions(-) diff --git a/crates/voelin-android/src/app.rs b/crates/voelin-android/src/app.rs index c1a5b3d..4290811 100644 --- a/crates/voelin-android/src/app.rs +++ b/crates/voelin-android/src/app.rs @@ -16,8 +16,9 @@ use crate::foreground::Foreground; use crate::host::EngineHost; use crate::{bridge, capture, egl, secrets}; -/// Store setting (`bool`): the user's opt-in to local crash reports. -pub const CRASH_REPORTS_SETTING: &str = "crash_reports"; +/// Store setting (`bool`): the user's opt-in to local crash reports (read +/// before the settings service starts, straight from the database). +pub const CRASH_REPORTS_SETTING: &str = voelin_core::settings::CRASH_REPORTS_KEY; static HOST: OnceLock = OnceLock::new(); static FOREGROUND: Mutex> = Mutex::new(None); @@ -92,6 +93,7 @@ fn run(app: AndroidApp) -> anyhow::Result<()> { runtime: attached.runtime, events: attached.events, }), + setting_overrides: Vec::new(), }) } diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 199cf54..9db99c9 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -14,6 +14,7 @@ use anyhow::{Context, Result}; use slint::{ComponentHandle, ModelRc, SharedString, VecModel}; use tokio::runtime::Runtime; use tracing::warn; +use voelin_core::settings::{AUDIO, CRASH_REPORTS, Settings}; use voelin_core::stream::StreamInfo; use voelin_core::{ AudioSettings, Command, Engine, Event, ObserveState, SessionState, Source, VoiceOptions, @@ -27,14 +28,40 @@ use voelin_store::{Bookmark, MemorySecrets, QueryConfig, QueryTransport, Secrets use crate::hotkey::GlobalPtt; use crate::settings::{ - self, AUDIO_KEY, CLIENT_PLAYBACK_KEY, ClientPlayback, ClientPlaybackMap, DeviceChoices, UI_KEY, - UiSettings, + self, CLIENT_PLAYBACK, ClientPlayback, ClientPlaybackMap, DeviceChoices, UI, UiSettings, }; use crate::streams::{Share, Watch}; use crate::video::Video; slint::include_modules!(); +/// The settings service on the client database: the UI's keys registered, +/// then a config file (`VOELIN_CONFIG`, else `/config.toml` if it +/// exists), `VOELIN_SETTING_*` variables and `overrides` below the stored +/// values. Without the database the settings live in memory. +fn open_settings(dir: &Path, overrides: &[String]) -> Settings { + let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| { + warn!(%e, "settings are not stored this time"); + Settings::in_memory() + }); + prefs.register(&UI); + prefs.register(&CLIENT_PLAYBACK); + let config = std::env::var_os("VOELIN_CONFIG") + .map(PathBuf::from) + .or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists())); + let mut errors = match config.map(|path| prefs.load_config_file(&path)) { + Some(Ok(errors)) => errors, + Some(Err(e)) => vec![e], + None => Vec::new(), + }; + errors.extend(prefs.apply_env(std::env::vars())); + errors.extend(prefs.apply_overrides(overrides.iter().map(String::as_str))); + for e in errors { + warn!(%e, "setting ignored"); + } + prefs +} + /// Secrets in the OS keyring, or in memory when there is none (headless /// Linux without a Secret Service). #[cfg(not(target_os = "android"))] @@ -149,6 +176,9 @@ pub(crate) struct App { pub current: Option, pub sessions: HashMap, status: String, + /// The settings service (shared with the engine); `settings`, `audio` + /// and `playback` are working copies of its keys. + pub prefs: Settings, pub settings: UiSettings, audio: AudioSettings, /// Audio settings changed since they were last stored. @@ -208,6 +238,9 @@ pub struct RunOptions { /// goes on in a service while the activity is recreated). Default: an /// engine that stops with the window. pub engine: Option, + /// Setting overrides as `key=value` (e.g. `--set` on the command line); + /// values set in the app take precedence. + pub setting_overrides: Vec, } impl std::fmt::Debug for RunOptions { @@ -216,6 +249,7 @@ impl std::fmt::Debug for RunOptions { .field("data_dir", &self.data_dir) .field("secrets", &self.secrets.is_some()) .field("engine", &self.engine.is_some()) + .field("setting_overrides", &self.setting_overrides) .finish() } } @@ -294,12 +328,14 @@ pub fn run(options: RunOptions) -> Result<()> { identity } }; - let settings: UiSettings = store.setting(UI_KEY).ok().flatten().unwrap_or_default(); + let prefs = open_settings(&dir, &options.setting_overrides); + engine.send(Command::AttachSettings(prefs.clone())); + let mut settings: UiSettings = (*prefs.get_arc(&UI)).clone(); + settings.crash_reports = prefs.get(&CRASH_REPORTS); crash::set_enabled(settings.crash_reports); crash::test_crash_if_requested(); - let audio: AudioSettings = store.setting(AUDIO_KEY).ok().flatten().unwrap_or_default(); - let playback: ClientPlaybackMap = - store.setting(CLIENT_PLAYBACK_KEY).ok().flatten().unwrap_or_default(); + let audio: AudioSettings = prefs.get(&AUDIO); + let playback: ClientPlaybackMap = prefs.get(&CLIENT_PLAYBACK); engine.send(Command::SetAudioSettings(Box::new(audio.clone()))); let ui = MainWindow::new()?; @@ -331,6 +367,7 @@ pub fn run(options: RunOptions) -> Result<()> { bookmarks, sessions: HashMap::new(), status: "Ready".into(), + prefs, settings, audio, audio_dirty: false, @@ -424,6 +461,9 @@ pub fn run(options: RunOptions) -> Result<()> { let own = own_runtime.is_some(); let open = with_app(|app| { app.save_audio(); + if let Err(e) = app.prefs.flush() { + warn!(%e, "could not store settings"); + } app.watch = None; app.share = None; if own { @@ -672,11 +712,29 @@ impl App { } pub fn store_settings(&self) { - if let Err(e) = self.store.set_setting(UI_KEY, &self.settings) { + if let Err(e) = self.prefs.set(&UI, self.settings.clone()) { warn!(%e, "could not store settings"); } } + /// A setting changed, maybe elsewhere (a command, another window): take + /// the values the window keeps copies of. The engine applies audio + /// settings itself. + fn setting_changed(&mut self, key: &str) { + if key == AUDIO.name() && !self.audio_dirty { + self.audio = self.prefs.get(&AUDIO); + } else if key == CRASH_REPORTS.name() { + let enabled = self.prefs.get(&CRASH_REPORTS); + if enabled != self.settings.crash_reports { + self.settings.crash_reports = enabled; + crash::set_enabled(enabled); + self.refresh_settings_flags(); + } + } else if key == CLIENT_PLAYBACK.name() { + self.playback = self.prefs.get(&CLIENT_PLAYBACK); + } + } + fn connect_voice(&mut self) { let Some(b) = self.current.and_then(|id| self.bookmark(id)).cloned() else { return }; let mut options = VoiceOptions::new(&b.address, &b.nickname); @@ -980,6 +1038,10 @@ impl App { } Event::Chat { session, message } => self.add_message(session as i64, message), Event::Error { message, .. } => self.set_status(message), + Event::SettingChanged { key } => self.setting_changed(&key), + Event::SettingRejected { key, message } => { + self.set_status(format!("Setting {key}: {message}")); + } event => self.stream_event(event), } } @@ -1230,7 +1292,7 @@ impl App { return; } self.audio_dirty = false; - if let Err(e) = self.store.set_setting(AUDIO_KEY, &self.audio) { + if let Err(e) = self.prefs.set(&AUDIO, self.audio.clone()) { warn!(%e, "could not store audio settings"); } } @@ -1304,7 +1366,11 @@ impl App { fn set_crash_reports(&mut self, enabled: bool) { self.settings.crash_reports = enabled; + // Also in the blob, for older versions. self.store_settings(); + if let Err(e) = self.prefs.set(&CRASH_REPORTS, enabled) { + warn!(%e, "could not store the crash report setting"); + } crash::set_enabled(enabled); } @@ -1372,7 +1438,7 @@ impl App { } else { self.playback.insert(uid, playback); } - if let Err(e) = self.store.set_setting(CLIENT_PLAYBACK_KEY, &self.playback) { + if let Err(e) = self.prefs.set(&CLIENT_PLAYBACK, self.playback.clone()) { warn!(%e, "could not store client volumes"); } } diff --git a/crates/voelin-ui/src/main.rs b/crates/voelin-ui/src/main.rs index d08419f..674f3b0 100644 --- a/crates/voelin-ui/src/main.rs +++ b/crates/voelin-ui/src/main.rs @@ -13,5 +13,23 @@ fn main() -> Result<()> { EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")), ) .init(); - voelin_ui::run(voelin_ui::RunOptions::default()) + let options = voelin_ui::RunOptions { + setting_overrides: setting_overrides(std::env::args().skip(1)), + ..Default::default() + }; + voelin_ui::run(options) +} + +/// `--set key=value` (or `--set=key=value`), repeatable: settings for this +/// run, below those changed in the app. +fn setting_overrides(mut args: impl Iterator) -> Vec { + let mut overrides = Vec::new(); + while let Some(arg) = args.next() { + match arg.strip_prefix("--set") { + Some("") => overrides.extend(args.next()), + Some(rest) if rest.starts_with('=') => overrides.push(rest[1..].to_owned()), + _ => eprintln!("ignoring argument {arg:?}; usage: voelin [--set key=value]..."), + } + } + overrides } diff --git a/crates/voelin-ui/src/settings.rs b/crates/voelin-ui/src/settings.rs index 7fb69af..33f0908 100644 --- a/crates/voelin-ui/src/settings.rs +++ b/crates/voelin-ui/src/settings.rs @@ -1,23 +1,47 @@ -//! Settings kept in the store (besides bookmarks and identities), and their -//! conversion to and from the forms of the settings page. +//! The UI's settings keys (besides the engine's, in +//! `voelin_core::settings`), and their conversion to and from the forms of +//! the settings page. use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use voelin_audio::process::NoiseLevel; +use voelin_core::settings::{Key, Kind}; use voelin_core::{AudioSettings, TransmitMode}; use crate::app::AudioForm; -/// Store keys. -pub const AUDIO_KEY: &str = "audio"; -pub const UI_KEY: &str = "ui"; -pub const CLIENT_PLAYBACK_KEY: &str = "client_playback"; +/// The window's settings, one value (the `ui` blob of earlier versions). +pub static UI: Key = Key::new( + "ui", + Kind::Json, + "The window's settings: push-to-talk key, H.264, the share dialog's choices.", + UiSettings::default, +); -/// Frame rates and bitrates (kbit/s) of the share dialog. +/// Volume and mute of clients, by unique id. +pub static CLIENT_PLAYBACK: Key = Key::new( + "client_playback", + Kind::Json, + "Volume and mute of clients, by unique id.", + ClientPlaybackMap::new, +); + +/// Frame rates and bitrates (kbit/s) the share dialog offers; any other +/// value can be typed in. pub const FPS_CHOICES: [u32; 3] = [15, 30, 60]; pub const BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000]; +/// The index of the choice closest to `value`. +pub fn nearest_choice(choices: &[u32], value: u32) -> usize { + (0..choices.len()).min_by_key(|&i| choices[i].abs_diff(value)).unwrap_or(0) +} + +/// A whole number above 0 typed into a form field. +pub fn parse_positive(text: &str) -> Option { + text.trim().parse().ok().filter(|v| *v > 0) +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] pub struct UiSettings { @@ -47,7 +71,9 @@ impl Default for UiSettings { } } -/// The last choices in the share dialog. +/// The last choices in the share dialog. Frame rate and bitrate are the +/// settings `stream.fps` and `stream.bitrate_kbps`; the indices of the +/// closest choices are kept for older versions. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] pub struct ShareDefaults { @@ -249,6 +275,17 @@ mod tests { assert_eq!(changed.playback_buffer_ms, 180); } + #[test] + fn free_values() { + assert_eq!(nearest_choice(&FPS_CHOICES, 60), 2); + assert_eq!(nearest_choice(&FPS_CHOICES, 144), 2); + assert_eq!(nearest_choice(&BITRATE_CHOICES, 3000), 0); + assert_eq!(nearest_choice(&BITRATE_CHOICES, 50_000), 3); + assert_eq!(parse_positive(" 144 "), Some(144)); + assert_eq!(parse_positive("0"), None); + assert_eq!(parse_positive("fast"), None); + } + #[test] fn ui_settings_defaults() { let parsed: UiSettings = serde_json::from_str(r#"{"openh264":true}"#).unwrap(); diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index 7ec3c97..1f46230 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -3,11 +3,15 @@ //! encodes and decodes. use slint::{ComponentHandle, Model}; +use tracing::warn; +use voelin_core::settings::{STREAM_BITRATE_KBPS, STREAM_FPS}; use voelin_core::stream::{EndReason, LeaveReason, StreamSetup, ViewerInfo, ViewerState}; use voelin_core::{Command, Event, StreamState, WatchState}; use crate::app::{App, Bridge, ShareForm, SourceItem, StreamItem, ViewerItem, later, model}; -use crate::settings::{BITRATE_CHOICES, FPS_CHOICES, ShareDefaults}; +use crate::settings::{ + BITRATE_CHOICES, FPS_CHOICES, ShareDefaults, nearest_choice, parse_positive, +}; use crate::video::{self, Capture, CaptureRequest, Decoder}; /// Our stream. @@ -333,14 +337,17 @@ impl App { self.refresh_streams(); let defaults = &self.settings.share; let nickname = self.current.and_then(|id| self.bookmark(id)).map(|b| b.nickname.clone()); + let (fps, bitrate) = (self.prefs.get(&STREAM_FPS), self.prefs.get(&STREAM_BITRATE_KBPS)); ShareForm { source: 0, name: match nickname { Some(nick) if !nick.is_empty() => format!("{nick}'s screen").into(), _ => "Screen".into(), }, - fps_index: defaults.fps_index.min(FPS_CHOICES.len() - 1) as i32, - bitrate_index: defaults.bitrate_index.min(BITRATE_CHOICES.len() - 1) as i32, + fps_index: nearest_choice(&FPS_CHOICES, fps) as i32, + fps: fps.to_string().into(), + bitrate_index: nearest_choice(&BITRATE_CHOICES, bitrate) as i32, + bitrate: bitrate.to_string().into(), audio: defaults.audio, auto_accept: defaults.auto_accept, } @@ -368,20 +375,33 @@ impl App { if self.share_busy || self.share.is_some() { return; } - let index = |i: i32, len: usize| usize::try_from(i).unwrap_or(0).min(len - 1); + // Typed values (no maximum), else the chosen presets. + let choice = |i: i32, choices: &[u32]| { + choices[usize::try_from(i).unwrap_or(0).min(choices.len() - 1)] + }; + let fps = parse_positive(&form.fps).unwrap_or_else(|| choice(form.fps_index, &FPS_CHOICES)); + let bitrate = parse_positive(&form.bitrate) + .unwrap_or_else(|| choice(form.bitrate_index, &BITRATE_CHOICES)); + // The next share starts from these. + for result in + [self.prefs.set(&STREAM_FPS, fps), self.prefs.set(&STREAM_BITRATE_KBPS, bitrate)] + { + if let Err(e) = result { + warn!(%e, "could not store the share settings"); + } + } let defaults = ShareDefaults { - fps_index: index(form.fps_index, FPS_CHOICES.len()), - bitrate_index: index(form.bitrate_index, BITRATE_CHOICES.len()), + fps_index: nearest_choice(&FPS_CHOICES, fps), + bitrate_index: nearest_choice(&BITRATE_CHOICES, bitrate), audio: form.audio, auto_accept: form.auto_accept, }; let request = CaptureRequest { - fps: FPS_CHOICES[defaults.fps_index], - bitrate_kbps: BITRATE_CHOICES[defaults.bitrate_index], + fps, + bitrate_kbps: bitrate, audio: form.audio, restore_token: self.settings.portal_restore_token.clone(), }; - let bitrate = request.bitrate_kbps; self.settings.share = defaults; self.store_settings(); self.share_busy = true; diff --git a/crates/voelin-ui/ui/app.slint b/crates/voelin-ui/ui/app.slint index 4721b04..ced2ac7 100644 --- a/crates/voelin-ui/ui/app.slint +++ b/crates/voelin-ui/ui/app.slint @@ -89,8 +89,12 @@ export struct ShareForm { name: string, // Index into the frame rate choices (15, 30, 60). fps-index: int, + // Frames per second as typed; a choice fills it in. Any number above 0. + fps: string, // Index into the bitrate choices (2.5, 4.6, 8, 10 Mbit/s). bitrate-index: int, + // Video bitrate in kbit/s as typed; a choice fills it in. + bitrate: string, audio: bool, auto-accept: bool, } @@ -935,8 +939,16 @@ component ShareDialog inherits Dialog { ComboBox { model: [@tr("15 fps"), @tr("30 fps"), @tr("60 fps")]; current-index <=> form.fps-index; + selected => { form.fps = [15, 30, 60][self.current-index]; } accessible-label: @tr("Frame rate"); } + LineEdit { + text <=> form.fps; + input-type: number; + placeholder-text: @tr("fps"); + width: 90px; + accessible-label: @tr("Frames per second"); + } } HorizontalLayout { spacing: 8px; @@ -948,8 +960,16 @@ component ShareDialog inherits Dialog { ComboBox { model: [@tr("Low (2.5 Mbit/s)"), @tr("Standard (4.6 Mbit/s)"), @tr("High (8 Mbit/s)"), @tr("Best (10 Mbit/s)")]; current-index <=> form.bitrate-index; + selected => { form.bitrate = [2500, 4608, 8000, 10000][self.current-index]; } accessible-label: @tr("Quality"); } + LineEdit { + text <=> form.bitrate; + input-type: number; + placeholder-text: @tr("kbit/s"); + width: 90px; + accessible-label: @tr("Bitrate in kbit/s"); + } } CheckBox { text: @tr("Share system audio"); diff --git a/docs/architecture.md b/docs/architecture.md index 5b0b1c3..89ef5e7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -110,6 +110,26 @@ and asking for one) and hands pictures to the UI, which keeps only the newest for `voelinctl stream start`; `SyntheticSource` (fake VP8 bytes) remains for voelin-stream's own tests. +The server announces a stream only to the clients in the streamer's channel +at its start. `voelin-stream::discovery` follows the clients' channels and +streaming flags (`Streams::update_clients`), and looks up streams nobody +announced to us with `requeststreaminfo clid=` +([research/ts6-late-join.md](research/ts6-late-join.md)). The lookup is a +`StreamLookup` trait, so another directory (a gateway's) can be added. + +## Settings + +`voelin-core::settings::Settings` is the settings service. Keys are typed +statics (`Key`: name, default, validation, a `Kind` for a settings page); +the effective value is the runtime value stored in the client database, else +a command line or environment override, else a config file, else the +default. Reads come from memory (`get`, `get_arc`, or a `SettingWatch` per +key); writes notify subscribers and go to SQLite on a writer thread. The +engine holds one (`Engine::settings`, `Command::AttachSettings`), takes +`Command::SetSetting` / `ResetSetting` and reports `Event::SettingChanged`. +The UI opens it on its database and registers its own keys (`ui`, +`client_playback`); the stream keys (`stream.*`) are defined in the core. + ## Milestones | | Scope | Exit criteria |