From f69ab4d3586ef551f2234ba74d7053300f09f0de Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 03:56:56 +0000 Subject: [PATCH] voelin-core: a Settings service with typed keys, layers and change events Settings were JSON blobs the UI read once at start and wrote back. The engine had no way to read settings, nothing was notified of changes, and there was no place for command line or config file values. settings::Settings holds typed keys (a Key carries its name, value type, default, validation and a kind for a settings page; a registry lists the registered keys). The effective value comes from the runtime value stored in the client database, else the command line or environment (VOELIN_SETTING_STREAM__FPS, --set key=value), else a config file (TOML or JSON), else the default; reset() removes the runtime value. Reads come from memory as Arc; writes update memory, notify, and go to SQLite on a writer thread in batches. Subscribers get every set and reset; a SettingWatch per key gets value changes. Stored values are versioned: the first migration copies the share dialog's frame rate and bitrate and the crash report opt-in out of the UI's blob, which stays for older versions. The keys the streaming work needs are defined: stream.fps (default 60), stream.bitrate_kbps (8000), stream.layers (LayerSpec-compatible), codec, capture and encoder backends, SRTP profiles, hardware acceleration and stream.permissions, plus audio and crash_reports. No key has a maximum. The engine takes Command::SetSetting/ResetSetting/AttachSettings and reports Event::SettingChanged/SettingRejected for every change, also ones made directly on the settings; a changed audio key is applied to the sessions. stream.permissions answers join requests: everyone accepts, channel accepts clients in our channel and denies others (the server relays requests from any channel), nobody denies, friends asks (no contacts yet). StartStream's auto_accept still accepts everyone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- Cargo.lock | 3 + crates/voelin-core/Cargo.toml | 3 + crates/voelin-core/src/lib.rs | 131 ++- crates/voelin-core/src/session.rs | 15 +- crates/voelin-core/src/settings.rs | 1353 +++++++++++++++++++++++ crates/voelin-core/src/stream.rs | 106 +- crates/voelin-core/tests/settings.rs | 75 ++ crates/voelin-core/tests/stream_live.rs | 4 +- crates/voelin-stream/src/discovery.rs | 5 + crates/voelin-stream/src/session.rs | 5 + 10 files changed, 1690 insertions(+), 10 deletions(-) create mode 100644 crates/voelin-core/src/settings.rs create mode 100644 crates/voelin-core/tests/settings.rs diff --git a/Cargo.lock b/Cargo.lock index 4255e3a..430de1f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9098,10 +9098,12 @@ version = "0.1.0" dependencies = [ "anyhow", "futures", + "serde", "serde_json", "thiserror 2.0.21", "tokio", "tokio-tungstenite 0.30.0", + "toml", "tracing", "tsclientlib", "tsproto-packets", @@ -9111,6 +9113,7 @@ dependencies = [ "voelin-model", "voelin-observer", "voelin-query", + "voelin-store", "voelin-stream", ] diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 29d8ce3..0bbceb3 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -24,10 +24,12 @@ media-desktop = ["media", "voelin-media/default"] [dependencies] anyhow = "1" futures = "0.3" +serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2" tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] } tokio-tungstenite = "0.30" +toml = "1.1.6" tracing = "0.1" voelin-audio = { path = "../voelin-audio", default-features = false } voelin-gateway-proto = { path = "../voelin-gateway-proto" } @@ -35,6 +37,7 @@ voelin-media = { path = "../voelin-media", default-features = false, features = voelin-model = { path = "../voelin-model" } voelin-observer = { path = "../voelin-observer" } voelin-query = { path = "../voelin-query" } +voelin-store = { path = "../voelin-store" } voelin-stream = { path = "../voelin-stream" } tsclientlib = { path = "../proto/tsclientlib" } tsproto-packets = { path = "../proto/tsproto-packets" } diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 5c07021..597d3c5 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -17,6 +17,12 @@ //! of watched streams plays through the session's speakers by itself //! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video //! are in [`media`] (feature `media`). +//! +//! Settings are a [`settings::Settings`] service: typed keys, runtime +//! values stored in the client database ahead of command line, config file +//! and defaults. The engine reads its own keys from it (e.g. who may watch +//! our stream), takes [`Command::SetSetting`] / [`Command::ResetSetting`], +//! and reports every change as [`Event::SettingChanged`]. mod audio; mod gateway; @@ -25,6 +31,7 @@ pub mod media; mod query; mod route; mod session; +pub mod settings; pub mod stream; mod voice; @@ -38,6 +45,7 @@ use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, S use crate::audio::{AudioEvent, AudioHandle, AudioIn}; pub use route::{ChatRoute, Dedup, route_chat}; +use settings::{SettingChange, Settings, SharedSettings}; pub use stream::{StreamFrame, StreamSink, StreamState, WatchState}; use voelin_stream::{EncodedFrame, StreamInfo, StreamSetup, ViewerInfo}; pub use voice::VoiceOptions; @@ -175,6 +183,20 @@ pub enum Command { CloseSession { session: SessionId, }, + /// Set a setting's runtime value (see [`settings`]); invalid values are + /// reported as [`Event::SettingRejected`]. + SetSetting { + key: String, + value: serde_json::Value, + }, + /// Remove a setting's runtime value: the command line, config file or + /// default applies again. + ResetSetting { + key: String, + }, + /// Use these settings from now on (e.g. the ones of the client database, + /// for an engine started without). + AttachSettings(Settings), } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -293,6 +315,16 @@ pub enum Event { stream_id: String, state: WatchState, }, + /// A setting was set or reset (by anyone: a command, the UI through + /// [`Engine::settings`], …). Read the new value from the settings. + SettingChanged { + key: String, + }, + /// A [`Command::SetSetting`] / [`Command::ResetSetting`] was refused. + SettingRejected { + key: String, + message: String, + }, } /// Handle to the engine. Cheap to clone; all methods are non-blocking. @@ -302,17 +334,31 @@ pub struct Engine { events: broadcast::Sender, frames: broadcast::Sender, runtime: tokio::runtime::Handle, + settings: SharedSettings, } impl Engine { - /// Start the engine on the current tokio runtime. + /// Start the engine on the current tokio runtime, with settings that are + /// not stored (see [`Command::AttachSettings`]). pub fn start() -> Self { + Self::start_with_settings(Settings::in_memory()) + } + + /// Start the engine on the current tokio runtime with `settings`. + pub fn start_with_settings(settings: Settings) -> Self { let (commands, rx) = mpsc::unbounded_channel(); let (events, _) = broadcast::channel(4096); // About a minute of one watched stream. let (frames, _) = broadcast::channel(4096); - tokio::spawn(run(rx, events.clone(), frames.clone())); - Self { commands, events, frames, runtime: tokio::runtime::Handle::current() } + let settings = SharedSettings::new(settings); + tokio::spawn(run(rx, events.clone(), frames.clone(), settings.clone())); + Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), settings } + } + + /// The settings the engine uses (read, watch or change them directly; + /// changes are reported as [`Event::SettingChanged`] all the same). + pub fn settings(&self) -> Settings { + self.settings.current() } /// The runtime the engine runs on, for helpers started from other @@ -335,15 +381,60 @@ impl Engine { } } +/// What woke the engine's loop. +enum Input { + Command(Command), + Setting(SettingChange), + /// Changes were missed: the engine re-reads what it uses. + SettingsLagged, +} + +/// A command that applies the stored audio settings if they differ from +/// what runs (e.g. set through [`Command::SetSetting`]). +fn stored_audio(settings: &Settings, running: &AudioSettings) -> Option { + let stored = settings.get_arc(&settings::AUDIO); + (*stored != *running).then(|| Command::SetAudioSettings(Box::new((*stored).clone()))) +} + async fn run( mut commands: mpsc::UnboundedReceiver, events: broadcast::Sender, frames: broadcast::Sender, + shared: SharedSettings, ) { let mut sessions: HashMap = HashMap::new(); + let mut current = shared.current(); + let mut changes = current.subscribe(); let mut settings = AudioSettings::default(); let mut mic_test: Option = None; - while let Some(command) = commands.recv().await { + loop { + let input = tokio::select! { + command = commands.recv() => match command { + Some(command) => Input::Command(command), + None => break, + }, + change = changes.recv() => match change { + Ok(change) => Input::Setting(change), + Err(broadcast::error::RecvError::Lagged(_)) => Input::SettingsLagged, + // Not while `current` holds the settings. + Err(broadcast::error::RecvError::Closed) => continue, + }, + }; + let command = match input { + Input::Command(command) => command, + Input::Setting(change) => { + let audio = change.key == settings::AUDIO.name(); + let _ = events.send(Event::SettingChanged { key: change.key }); + match audio.then(|| stored_audio(¤t, &settings)).flatten() { + Some(command) => command, + None => continue, + } + } + Input::SettingsLagged => match stored_audio(¤t, &settings) { + Some(command) => command, + None => continue, + }, + }; let id = match command { Command::SetAudioSettings(new) => { settings = (*new).clone(); @@ -359,6 +450,24 @@ async fn run( mic_test = on.then(|| test_microphone(&settings, &events)); continue; } + Command::SetSetting { key, value } => { + if let Err(e) = current.set_json(&key, value) { + let _ = events.send(Event::SettingRejected { key, message: e.to_string() }); + } + continue; + } + Command::ResetSetting { key } => { + if let Err(e) = current.reset(&key) { + let _ = events.send(Event::SettingRejected { key, message: e.to_string() }); + } + continue; + } + Command::AttachSettings(new) => { + shared.replace(new.clone()); + changes = new.subscribe(); + current = new; + continue; + } ref command => command_session(command), }; if matches!(command, Command::CloseSession { .. }) { @@ -370,7 +479,13 @@ async fn run( sessions .entry(id) .or_insert_with(|| { - session::SessionHandle::spawn(id, events.clone(), frames.clone(), settings.clone()) + session::SessionHandle::spawn( + id, + events.clone(), + frames.clone(), + settings.clone(), + shared.clone(), + ) }) .send(command); } @@ -422,7 +537,11 @@ fn command_session(command: &Command) -> SessionId { | Command::SetClientVolume { session, .. } | Command::SetClientMuted { session, .. } | Command::CloseSession { session } => *session, - Command::SetAudioSettings(_) | Command::TestMicrophone { .. } => { + Command::SetAudioSettings(_) + | Command::TestMicrophone { .. } + | Command::SetSetting { .. } + | Command::ResetSetting { .. } + | Command::AttachSettings(_) => { unreachable!("engine-wide commands have no session") } } diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index dcfd989..7644a62 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -14,6 +14,7 @@ use crate::audio::{self, AudioEvent, AudioHandle, AudioIn}; use crate::gateway::{self, GatewayCmd, GatewayEvent}; use crate::query::{self, QueryCmd, QueryEvent}; use crate::route::{ChatRoute, Dedup, route_chat}; +use crate::settings::SharedSettings; use crate::stream::{PeerConfig, StreamFrame, StreamHandle, StreamInput}; use crate::voice::{self, VoiceCmd, VoiceEvent}; use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState}; @@ -28,9 +29,10 @@ impl SessionHandle { events: broadcast::Sender, frames: broadcast::Sender, audio_settings: AudioSettings, + settings: SharedSettings, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); - tokio::spawn(Session::new(id, events, frames, audio_settings).run(rx)); + tokio::spawn(Session::new(id, events, frames, audio_settings, settings).run(rx)); Self { tx } } @@ -63,6 +65,7 @@ struct Session { query_presence: Option, audio: Option, audio_settings: AudioSettings, + settings: SharedSettings, /// Streams of the voice connection (TeamSpeak 6 only). streams: Option, stream_peer: PeerConfig, @@ -82,6 +85,7 @@ impl Session { events: broadcast::Sender, frames: broadcast::Sender, audio_settings: AudioSettings, + settings: SharedSettings, ) -> Self { let (sources_tx, sources_rx) = mpsc::unbounded_channel(); Self { @@ -98,6 +102,7 @@ impl Session { query_presence: None, audio: None, audio_settings, + settings, streams: None, stream_peer: PeerConfig::default(), frames, @@ -319,7 +324,12 @@ impl Session { Command::RequestStreamKeyframe { stream_id, .. } => { self.stream_input(StreamInput::RequestKeyframe { stream_id }); } - Command::CloseSession { .. } | Command::TestMicrophone { .. } => {} + // Engine-wide. + Command::CloseSession { .. } + | Command::TestMicrophone { .. } + | Command::SetSetting { .. } + | Command::ResetSetting { .. } + | Command::AttachSettings(_) => {} } } @@ -449,6 +459,7 @@ impl Session { self.events.clone(), self.frames.clone(), self.audio.clone(), + self.settings.clone(), )); } self.emit(Event::ServerInfo { session: self.id, name, flavor, capabilities }); diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs new file mode 100644 index 0000000..04211d7 --- /dev/null +++ b/crates/voelin-core/src/settings.rs @@ -0,0 +1,1353 @@ +//! Settings: typed keys with defaults and validation, values from several +//! layers, change notification, and persistence in the client database. +//! +//! A setting is a [`Key`]: its name, value type, default and validation. +//! Keys are `static`s ([`STREAM_FPS`], …); a [`Settings`] registers a key the +//! first time it is used (the built-in keys when it is created), and +//! [`Settings::keys`] lists the registered keys for a settings page. +//! +//! The effective value of a key comes from the first layer that has a valid +//! one: +//! +//! 1. **runtime**: set while the app runs ([`Settings::set`], +//! [`crate::Command::SetSetting`]); stored in the database, so it is the +//! same after a restart. [`Settings::reset`] removes it. +//! 2. **override**: command line (`--set key=value`) or environment +//! (`VOELIN_SETTING_STREAM__FPS=90` for `stream.fps`). +//! 3. **config**: a config file ([`Settings::load_config_file`]). +//! 4. the key's **default**. +//! +//! Overrides and config files never write to the database: they apply while +//! no runtime value exists. +//! +//! Reads are cheap: the current value of every key is kept in memory, typed +//! and behind an `Arc` ([`Settings::get_arc`]); a [`SettingWatch`] reads it +//! without looking the key up. Writes update the memory at once, notify, and +//! go to SQLite on a writer thread, batched ([`Settings::flush`] waits for +//! them). +//! +//! Changes are announced to [`Settings::subscribe`] (every set and reset), +//! to the [`SettingWatch`]es of the key (when the effective value changed), +//! and by the engine as [`crate::Event::SettingChanged`]. +//! +//! Stored values are versioned: [`Settings::open`] runs the migrations the +//! database has not seen yet (see `MIGRATIONS`). The first one copies the +//! stream choices and the crash report opt-in out of the UI's `ui` blob; the +//! old blobs (`ui`, `audio`, `client_playback`) stay and remain keys. + +use std::any::{Any, TypeId}; +use std::collections::{BTreeMap, HashMap}; +use std::fmt; +use std::marker::PhantomData; +use std::path::Path; +use std::sync::mpsc as std_mpsc; +use std::sync::{Arc, PoisonError, RwLock}; +use std::thread::JoinHandle; + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use tokio::sync::{broadcast, watch}; +use tracing::{debug, warn}; +use voelin_audio::AudioSettings; +use voelin_store::Store; +use voelin_stream::{LayerId, LayerSpec}; + +/// A value of any key, typed (`Arc` of the key's `T`). +type Stored = Arc; + +/// Where the effective value of a key comes from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Source { + /// Set while running; stored in the database. + Runtime, + /// Command line or environment. + Override, + /// A config file. + Config, + Default, +} + +/// What a key holds, for a settings page that shows every key. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Bool, + /// A whole number of at least `min`, without a maximum. + UInt { + min: u64, + }, + /// One of these strings. + Choice(&'static [&'static str]), + /// Any string; these are suggestions. + Text { + suggestions: &'static [&'static str], + }, + /// An ordered list of distinct strings from these. + List(&'static [&'static str]), + /// Structured JSON (objects, lists of objects). + Json, +} + +/// A setting: its name, value type `T`, default and validation. +pub struct Key { + name: &'static str, + doc: &'static str, + kind: Kind, + default: fn() -> T, + validate: fn(&T) -> Result<(), String>, +} + +fn accept(_: &T) -> Result<(), String> { + Ok(()) +} + +impl Key { + /// A key whose every `T` is valid. + pub const fn new( + name: &'static str, + kind: Kind, + doc: &'static str, + default: fn() -> T, + ) -> Self { + Self { name, doc, kind, default, validate: accept:: } + } + + /// The same key with a validation (errors are shown to the user). + pub const fn validated(self, validate: fn(&T) -> Result<(), String>) -> Self { + Self { validate, ..self } + } + + pub const fn name(&self) -> &'static str { + self.name + } + + pub fn default_value(&self) -> T { + (self.default)() + } + + pub fn validate(&self, value: &T) -> Result<(), String> { + (self.validate)(value) + } +} + +impl fmt::Debug for Key { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Key").field("name", &self.name).field("kind", &self.kind).finish() + } +} + +/// A [`Key`] of any type, as the registry holds it. +pub trait Setting: Send + Sync + 'static { + fn name(&self) -> &'static str; + /// One sentence for a settings page. + fn doc(&self) -> &'static str; + fn kind(&self) -> Kind; + fn default_json(&self) -> Value; + /// Check a JSON value; the typed value and its normalized JSON. + fn parse_json(&self, value: &Value) -> Result<(Stored, Value), String>; + #[doc(hidden)] + fn default_stored(&self) -> Stored; + #[doc(hidden)] + fn value_type(&self) -> TypeId; +} + +impl Setting for Key +where + T: Serialize + DeserializeOwned + Send + Sync + 'static, +{ + fn name(&self) -> &'static str { + self.name + } + + fn doc(&self) -> &'static str { + self.doc + } + + fn kind(&self) -> Kind { + self.kind + } + + fn default_json(&self) -> Value { + serde_json::to_value(self.default_value()).unwrap_or(Value::Null) + } + + fn parse_json(&self, value: &Value) -> Result<(Stored, Value), String> { + let typed: T = T::deserialize(value).map_err(|e| e.to_string())?; + self.validate(&typed)?; + let json = serde_json::to_value(&typed).map_err(|e| e.to_string())?; + Ok((Arc::new(typed), json)) + } + + fn default_stored(&self) -> Stored { + Arc::new(self.default_value()) + } + + fn value_type(&self) -> TypeId { + TypeId::of::() + } +} + +/// Why a setting could not be read or changed. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum SettingsError { + #[error("unknown setting {0}")] + UnknownKey(String), + #[error("invalid value for {key}: {message}")] + Invalid { key: String, message: String }, + #[error("settings database: {0}")] + Store(String), + #[error("config file {path}: {message}")] + Config { path: String, message: String }, +} + +impl From for SettingsError { + fn from(e: voelin_store::Error) -> Self { + Self::Store(e.to_string()) + } +} + +/// A set or reset of a key ([`Settings::subscribe`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SettingChange { + pub key: String, + /// Where the key's value now comes from (`None`: not registered). + pub source: Option, +} + +/// The values of one key in each layer, as JSON; kept for keys that are not +/// registered yet too. +#[derive(Clone, Debug, Default)] +struct Layers { + runtime: Option, + overrides: Option, + config: Option, +} + +/// A registered key and its effective value. +struct Slot { + key: &'static dyn Setting, + source: Source, + json: Value, + value: watch::Sender, +} + +#[derive(Default)] +struct State { + layers: HashMap, + slots: HashMap<&'static str, Slot>, +} + +impl State { + /// The effective value of `key` from `layers`; invalid layers are skipped. + fn resolve(key: &'static dyn Setting, layers: Option<&Layers>) -> (Stored, Value, Source) { + if let Some(layers) = layers { + for (source, value) in [ + (Source::Runtime, &layers.runtime), + (Source::Override, &layers.overrides), + (Source::Config, &layers.config), + ] { + let Some(value) = value else { continue }; + match key.parse_json(value) { + Ok((stored, json)) => return (stored, json, source), + Err(e) => warn!(key = key.name(), ?source, "ignoring an invalid value: {e}"), + } + } + } + (key.default_stored(), key.default_json(), Source::Default) + } + + fn register(&mut self, key: &'static dyn Setting) { + if let Some(slot) = self.slots.get(key.name()) { + if slot.key.value_type() != key.value_type() { + warn!( + key = key.name(), + "two keys of different types share a name; keeping the first" + ); + } + return; + } + let (stored, json, source) = Self::resolve(key, self.layers.get(key.name())); + let (value, _) = watch::channel(stored); + self.slots.insert(key.name(), Slot { key, source, json, value }); + } + + /// Recompute a registered key after its layers changed. + fn update(&mut self, name: &str) -> Option { + let slot = self.slots.get_mut(name)?; + let (stored, json, source) = Self::resolve(slot.key, self.layers.get(name)); + slot.source = source; + if slot.json != json { + slot.json = json; + slot.value.send_replace(stored); + } + Some(source) + } +} + +enum WriteOp { + Put(String, String), + Delete(String), + /// Answered once everything before it is written. + Flush(std_mpsc::Sender>), +} + +struct Writer { + tx: std_mpsc::Sender, + thread: JoinHandle<()>, +} + +struct Inner { + state: RwLock, + changes: broadcast::Sender, + writer: Option, +} + +impl Drop for Inner { + fn drop(&mut self) { + // Closing the channel ends the writer after the pending writes. + if let Some(Writer { tx, thread }) = self.writer.take() { + drop(tx); + let _ = thread.join(); + } + } +} + +/// The settings service. Cheap to clone; all clones share the values. +#[derive(Clone)] +pub struct Settings { + inner: Arc, +} + +impl fmt::Debug for Settings { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let state = self.read(); + f.debug_struct("Settings") + .field("keys", &state.slots.len()) + .field("persistent", &self.inner.writer.is_some()) + .finish() + } +} + +impl Default for Settings { + fn default() -> Self { + Self::in_memory() + } +} + +/// Stored in the settings table: how many migrations ran. +const VERSION_KEY: &str = "settings.version"; + +impl Settings { + /// Settings that are not stored (tests, tools, an engine without a database). + pub fn in_memory() -> Self { + Self::build(HashMap::new(), None) + } + + /// Settings stored in the client database at `path` (its own connection). + pub fn open(path: &Path) -> Result { + Self::with_store(Store::open(path)?) + } + + /// Settings stored in `store`, which moves to the writer thread. + pub fn with_store(mut store: Store) -> Result { + let mut version = 0; + let mut values = HashMap::new(); + for (key, text) in store.settings_json()? { + match serde_json::from_str::(&text) { + Ok(v) if key == VERSION_KEY => version = v.as_u64().unwrap_or(0) as usize, + Ok(v) => { + values.insert(key, v); + } + Err(e) => warn!(key, "ignoring a stored setting that is not JSON: {e}"), + } + } + if version < MIGRATIONS.len() { + let mut migrator = Migrator { values, changes: BTreeMap::new() }; + for (i, migration) in MIGRATIONS.iter().enumerate().skip(version) { + debug!(version = i + 1, "migrating settings"); + migration(&mut migrator); + } + let texts: Vec<(String, Option)> = migrator + .changes + .iter() + .map(|(k, v)| (k.clone(), v.as_ref().map(Value::to_string))) + .chain([(VERSION_KEY.to_owned(), Some(MIGRATIONS.len().to_string()))]) + .collect(); + store.write_settings(texts.iter().map(|(k, v)| (k.as_str(), v.as_deref())))?; + values = migrator.values; + } + let (tx, rx) = std_mpsc::channel(); + let thread = std::thread::Builder::new() + .name("settings-writer".into()) + .spawn(move || write_loop(store, rx)) + .map_err(|e| SettingsError::Store(e.to_string()))?; + Ok(Self::build(values, Some(Writer { tx, thread }))) + } + + fn build(runtime: HashMap, writer: Option) -> Self { + let layers = runtime + .into_iter() + .map(|(k, v)| (k, Layers { runtime: Some(v), ..Layers::default() })) + .collect(); + let (changes, _) = broadcast::channel(1024); + let settings = Self { + inner: Arc::new(Inner { + state: RwLock::new(State { layers, slots: HashMap::new() }), + changes, + writer, + }), + }; + for key in builtin_keys() { + settings.register(key); + } + settings + } + + fn read(&self) -> std::sync::RwLockReadGuard<'_, State> { + self.inner.state.read().unwrap_or_else(PoisonError::into_inner) + } + + fn write(&self) -> std::sync::RwLockWriteGuard<'_, State> { + self.inner.state.write().unwrap_or_else(PoisonError::into_inner) + } + + /// Make a key known (keys register themselves on first use, too). + pub fn register(&self, key: &'static dyn Setting) { + if !self.read().slots.contains_key(key.name()) { + self.write().register(key); + } + } + + /// The registered keys, by name. + pub fn keys(&self) -> Vec<&'static dyn Setting> { + let mut keys: Vec<_> = self.read().slots.values().map(|s| s.key).collect(); + keys.sort_by_key(|k| k.name()); + keys + } + + /// The current value. + pub fn get(&self, key: &'static Key) -> T + where + T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static, + { + T::clone(&self.get_arc(key)) + } + + /// The current value, without copying it. + pub fn get_arc(&self, key: &'static Key) -> Arc + where + T: Serialize + DeserializeOwned + Send + Sync + 'static, + { + let stored = { + let state = self.read(); + state.slots.get(key.name).map(|s| s.value.borrow().clone()) + }; + let stored = stored.unwrap_or_else(|| { + self.register(key); + self.read().slots[key.name].value.borrow().clone() + }); + stored.downcast().unwrap_or_else(|_| Arc::new(key.default_value())) + } + + /// The current value of a key by name, as JSON (`None`: not registered). + pub fn get_json(&self, name: &str) -> Option { + self.read().slots.get(name).map(|s| s.json.clone()) + } + + /// Where the value of a key comes from (`None`: not registered). + pub fn source(&self, name: &str) -> Option { + self.read().slots.get(name).map(|s| s.source) + } + + /// Set the runtime value (stored, and ahead of overrides and config). + pub fn set(&self, key: &'static Key, value: T) -> Result<(), SettingsError> + where + T: Serialize + DeserializeOwned + Send + Sync + 'static, + { + let invalid = |message: String| SettingsError::Invalid { key: key.name.into(), message }; + key.validate(&value).map_err(invalid)?; + let json = serde_json::to_value(&value).map_err(|e| invalid(e.to_string()))?; + self.register(key); + self.store_runtime(key.name, json, Arc::new(value)); + Ok(()) + } + + /// Set the runtime value of a registered key from JSON. + pub fn set_json(&self, name: &str, value: Value) -> Result<(), SettingsError> { + let key = self.key(name)?; + let (stored, json) = key + .parse_json(&value) + .map_err(|message| SettingsError::Invalid { key: name.into(), message })?; + self.store_runtime(key.name(), json, stored); + Ok(()) + } + + fn key(&self, name: &str) -> Result<&'static dyn Setting, SettingsError> { + self.read() + .slots + .get(name) + .map(|s| s.key) + .ok_or_else(|| SettingsError::UnknownKey(name.into())) + } + + fn store_runtime(&self, name: &'static str, json: Value, stored: Stored) { + let text = json.to_string(); + { + let mut state = self.write(); + state.layers.entry(name.to_owned()).or_default().runtime = Some(json.clone()); + let slot = state.slots.get_mut(name).expect("registered"); + slot.source = Source::Runtime; + if slot.json != json { + slot.json = json; + slot.value.send_replace(stored); + } + } + self.persist(WriteOp::Put(name.to_owned(), text)); + self.announce(name, Some(Source::Runtime)); + } + + /// Remove the runtime value: the override, config or default applies again. + pub fn reset(&self, name: &str) -> Result<(), SettingsError> { + let source = { + let mut state = self.write(); + if let Some(layers) = state.layers.get_mut(name) { + layers.runtime = None; + } + state.update(name) + }; + self.persist(WriteOp::Delete(name.to_owned())); + self.announce(name, source); + Ok(()) + } + + /// Set the value of a layer below runtime; checked now if the key is + /// registered, else when it registers. + fn set_layer( + &self, + name: &str, + value: Value, + layer: fn(&mut Layers) -> &mut Option, + ) -> Result<(), SettingsError> { + let value = match self.key(name) { + Ok(key) => { + key.parse_json(&value) + .map_err(|message| SettingsError::Invalid { key: name.into(), message })? + .1 + } + Err(_) => value, + }; + let mut state = self.write(); + *layer(state.layers.entry(name.to_owned()).or_default()) = Some(value); + let effective = |state: &State| state.slots.get(name).map(|s| (s.json.clone(), s.source)); + let before = effective(&state); + let source = state.update(name); + let changed = before != effective(&state); + drop(state); + // Announced only if it changed what applies. + if changed { + self.announce(name, source); + } + Ok(()) + } + + /// A command line or environment value (below runtime values). + pub fn set_override(&self, name: &str, value: Value) -> Result<(), SettingsError> { + self.set_layer(name, value, |l| &mut l.overrides) + } + + /// A config file value (below overrides). + pub fn set_config(&self, name: &str, value: Value) -> Result<(), SettingsError> { + self.set_layer(name, value, |l| &mut l.config) + } + + /// Load a config file: TOML, or JSON if the name ends in `.json`. Tables + /// nest key names (`[stream]` `fps = 90` is `stream.fps`) unless the + /// table's name is a registered key (e.g. `[audio]`). Returns the + /// invalid entries, which are skipped. + pub fn load_config_file(&self, path: &Path) -> Result, SettingsError> { + let config_error = + |message: String| SettingsError::Config { path: path.display().to_string(), message }; + let text = std::fs::read_to_string(path).map_err(|e| config_error(e.to_string()))?; + let root: Value = if path.extension().is_some_and(|e| e == "json") { + serde_json::from_str(&text).map_err(|e| config_error(e.to_string()))? + } else { + let table: toml::Table = + toml::from_str(&text).map_err(|e| config_error(e.to_string()))?; + serde_json::to_value(table).map_err(|e| config_error(e.to_string()))? + }; + let Value::Object(root) = root else { + return Err(config_error("expected a table of settings".into())); + }; + let mut entries = Vec::new(); + self.flatten(String::new(), root, &mut entries); + Ok(entries + .into_iter() + .filter_map(|(name, value)| self.set_config(&name, value).err()) + .collect()) + } + + fn flatten( + &self, + prefix: String, + table: serde_json::Map, + out: &mut Vec<(String, Value)>, + ) { + for (k, v) in table { + let name = if prefix.is_empty() { k } else { format!("{prefix}.{k}") }; + match v { + Value::Object(inner) if !self.read().slots.contains_key(name.as_str()) => { + self.flatten(name, inner, out); + } + v => out.push((name, v)), + } + } + } + + /// Overrides from the environment: `VOELIN_SETTING_STREAM__FPS=90` sets + /// `stream.fps` (`__` separates name parts; the rest is lower-cased). + /// Values are JSON, or else strings. Returns the invalid ones. + pub fn apply_env( + &self, + vars: impl IntoIterator, + ) -> Vec { + const PREFIX: &str = "VOELIN_SETTING_"; + vars.into_iter() + .filter_map(|(var, value)| { + let name = var.strip_prefix(PREFIX)?.to_lowercase().replace("__", "."); + self.set_override(&name, parse_text(&value)).err() + }) + .collect() + } + + /// Overrides from `key=value` pairs (e.g. `--set stream.fps=90`); values + /// are JSON, or else strings. Returns the invalid ones. + pub fn apply_overrides<'a>( + &self, + pairs: impl IntoIterator, + ) -> Vec { + pairs + .into_iter() + .filter_map(|pair| match pair.split_once('=') { + Some((name, value)) => self.set_override(name.trim(), parse_text(value)).err(), + None => Some(SettingsError::Invalid { + key: pair.into(), + message: "expected key=value".into(), + }), + }) + .collect() + } + + /// Every set and reset, of any key. + pub fn subscribe(&self) -> broadcast::Receiver { + self.inner.changes.subscribe() + } + + /// The value of one key, updated when it changes. + pub fn watch(&self, key: &'static Key) -> SettingWatch + where + T: Serialize + DeserializeOwned + Send + Sync + 'static, + { + self.register(key); + let rx = self.read().slots[key.name].value.subscribe(); + SettingWatch { key, rx, _type: PhantomData } + } + + /// Wait until the writes so far are in the database. + pub fn flush(&self) -> Result<(), SettingsError> { + let Some(writer) = &self.inner.writer else { return Ok(()) }; + let (tx, rx) = std_mpsc::channel(); + if writer.tx.send(WriteOp::Flush(tx)).is_err() { + return Err(SettingsError::Store("the writer stopped".into())); + } + match rx.recv() { + Ok(None) => Ok(()), + Ok(Some(e)) => Err(SettingsError::Store(e)), + Err(_) => Err(SettingsError::Store("the writer stopped".into())), + } + } + + fn persist(&self, op: WriteOp) { + if let Some(writer) = &self.inner.writer { + let _ = writer.tx.send(op); + } + } + + fn announce(&self, name: &str, source: Option) { + let _ = self.inner.changes.send(SettingChange { key: name.to_owned(), source }); + } +} + +/// JSON if it parses, else the text as a string (`vp9` → `"vp9"`). +fn parse_text(text: &str) -> Value { + serde_json::from_str(text).unwrap_or_else(|_| Value::String(text.to_owned())) +} + +/// Writes batches of changes, the last change of a key winning. +fn write_loop(mut store: Store, rx: std_mpsc::Receiver) { + let mut error = None; + while let Ok(first) = rx.recv() { + let mut batch: BTreeMap> = BTreeMap::new(); + let mut flushes = Vec::new(); + for op in std::iter::once(first).chain(rx.try_iter()) { + match op { + WriteOp::Put(key, value) => { + batch.insert(key, Some(value)); + } + WriteOp::Delete(key) => { + batch.insert(key, None); + } + WriteOp::Flush(done) => flushes.push(done), + } + } + if !batch.is_empty() + && let Err(e) = + store.write_settings(batch.iter().map(|(k, v)| (k.as_str(), v.as_deref()))) + { + warn!("cannot store settings: {e}"); + error = Some(e.to_string()); + } + for done in flushes { + let _ = done.send(error.take()); + } + } +} + +/// The value of one key; see [`Settings::watch`]. +pub struct SettingWatch { + key: &'static Key, + rx: watch::Receiver, + _type: PhantomData T>, +} + +impl SettingWatch { + /// The current value. + pub fn get(&self) -> Arc { + let stored = self.rx.borrow().clone(); + stored.downcast().unwrap_or_else(|_| Arc::new(self.key.default_value())) + } + + /// Whether the value changed since it was last read with [`Self::changed`] + /// or [`Self::get_new`]. + pub fn has_changed(&self) -> bool { + self.rx.has_changed().unwrap_or(false) + } + + /// The value, if it changed since the last call (for polling threads). + pub fn get_new(&mut self) -> Option> { + if !self.has_changed() { + return None; + } + self.rx.mark_unchanged(); + Some(self.get()) + } + + /// Wait for the next change; `None` once the settings are gone. + pub async fn changed(&mut self) -> Option> { + self.rx.changed().await.ok()?; + Some(self.get()) + } +} + +/// Settings stored before this code are upgraded by these, in order; the +/// database remembers how many ran (`settings.version`). Add new ones at the +/// end; never change one that shipped. +const MIGRATIONS: &[fn(&mut Migrator)] = &[split_ui_blob]; + +/// The runtime values during a migration. +struct Migrator { + values: HashMap, + /// Written after the migrations (`None`: removed). + changes: BTreeMap>, +} + +impl Migrator { + fn get(&self, key: &str) -> Option<&Value> { + self.values.get(key) + } + + fn set_if_absent(&mut self, key: &str, value: Value) { + if !self.values.contains_key(key) { + self.values.insert(key.to_owned(), value.clone()); + self.changes.insert(key.to_owned(), Some(value)); + } + } +} + +/// The share dialog's presets before the stream keys existed, by index. +const LEGACY_FPS: [u32; 3] = [15, 30, 60]; +const LEGACY_BITRATES: [u32; 4] = [2500, 4608, 8000, 10_000]; + +/// Version 1: the UI kept everything in its `ui` blob. Copy what now has +/// its own key: the share dialog's last frame rate and bitrate (unless they +/// were the old defaults, 30 fps and 4608 kbit/s, which the user most likely +/// never chose) and the crash report opt-in (which the Android app read +/// from `crash_reports` already). The blob stays for older versions. +fn split_ui_blob(m: &mut Migrator) { + let Some(ui) = m.get("ui").cloned() else { return }; + let share = ui.get("share"); + let index = |field: &str| share.and_then(|s| s.get(field)).and_then(Value::as_u64); + if let Some(fps) = index("fps_index").and_then(|i| LEGACY_FPS.get(i as usize)) + && *fps != 30 + { + m.set_if_absent(STREAM_FPS.name, json!(fps)); + } + if let Some(kbps) = index("bitrate_index").and_then(|i| LEGACY_BITRATES.get(i as usize)) + && *kbps != 4608 + { + m.set_if_absent(STREAM_BITRATE_KBPS.name, json!(kbps)); + } + if let Some(on) = ui.get("crash_reports").and_then(Value::as_bool) { + m.set_if_absent(CRASH_REPORTS.name, json!(on)); + } +} + +// The built-in keys. + +/// Name of [`CRASH_REPORTS`], for code that reads the database directly. +pub const CRASH_REPORTS_KEY: &str = "crash_reports"; + +/// Write crash reports to disk (opt-in; never uploaded). +pub static CRASH_REPORTS: Key = Key::new( + CRASH_REPORTS_KEY, + Kind::Bool, + "Write crash reports to disk (never uploaded).", + bool::default, +); + +/// All audio settings of the sessions, in one value (the `audio` blob). +pub static AUDIO: Key = Key::new( + "audio", + Kind::Json, + "Audio devices, processing and transmit mode.", + AudioSettings::default, +); + +fn at_least_one(v: &u32) -> Result<(), String> { + if *v == 0 { Err("must be at least 1".into()) } else { Ok(()) } +} + +/// Frame rate of our stream (no maximum). +pub static STREAM_FPS: Key = + Key::new("stream.fps", Kind::UInt { min: 1 }, "Frames per second of our stream.", || 60) + .validated(at_least_one); + +/// Video bitrate of our stream in kbit/s (no maximum). +pub static STREAM_BITRATE_KBPS: Key = Key::new( + "stream.bitrate_kbps", + Kind::UInt { min: 1 }, + "Video bitrate of our stream in kbit/s.", + || 8000, +) +.validated(at_least_one); + +/// One simulcast layer as stored; see [`LayerSpec`] for the fields. The +/// serde form of a layer: `{"scale": 0.5, "max_fps": 30, "bitrate": 1500000}` +/// or `{"size": [1280, 720], "bitrate": 4000000, "rid": "h"}`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct LayerSetting { + /// Default: the position in the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + pub scale: f32, + #[serde(skip_serializing_if = "Option::is_none")] + pub size: Option<(u32, u32)>, + #[serde(skip_serializing_if = "Option::is_none")] + pub max_fps: Option, + /// Bit/s. + pub bitrate: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub max_bitrate: Option, + pub min_bitrate: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub rid: Option, +} + +impl Default for LayerSetting { + fn default() -> Self { + let spec = LayerSpec::single(0); + Self { + id: None, + scale: spec.scale, + size: spec.size, + max_fps: spec.max_fps, + bitrate: spec.bitrate, + max_bitrate: spec.max_bitrate, + min_bitrate: spec.min_bitrate, + rid: spec.rid, + } + } +} + +impl LayerSetting { + /// The layer as [`LayerSpec`]; `index` is its position in the list. + pub fn to_spec(&self, index: usize) -> LayerSpec { + LayerSpec { + id: self.id.unwrap_or(index as LayerId), + scale: self.scale, + size: self.size, + max_fps: self.max_fps, + bitrate: self.bitrate, + max_bitrate: self.max_bitrate, + min_bitrate: self.min_bitrate, + rid: self.rid.clone(), + } + } + + pub fn from_spec(spec: &LayerSpec) -> Self { + Self { + id: Some(spec.id), + scale: spec.scale, + size: spec.size, + max_fps: spec.max_fps, + bitrate: spec.bitrate, + max_bitrate: spec.max_bitrate, + min_bitrate: spec.min_bitrate, + rid: spec.rid.clone(), + } + } +} + +/// The layers of [`STREAM_LAYERS`] as [`LayerSpec`]s (empty: a single layer). +pub fn layer_specs(layers: &[LayerSetting]) -> Vec { + layers.iter().enumerate().map(|(i, l)| l.to_spec(i)).collect() +} + +#[allow(clippy::ptr_arg)] // a validation of `Key>` is `fn(&Vec<_>)` +fn valid_layers(layers: &Vec) -> Result<(), String> { + let specs = layer_specs(layers); + for (i, s) in specs.iter().enumerate() { + if s.bitrate == 0 { + return Err(format!("layer {}: bitrate must be above 0", s.id)); + } + if s.size.is_none() && !(s.scale.is_finite() && s.scale > 0.0) { + return Err(format!("layer {}: scale must be above 0", s.id)); + } + if s.size.is_some_and(|(w, h)| w == 0 || h == 0) { + return Err(format!("layer {}: size must not be 0", s.id)); + } + if s.max_fps == Some(0) { + return Err(format!("layer {}: max_fps must be at least 1", s.id)); + } + if s.max_bitrate.is_some_and(|max| max < s.bitrate) { + return Err(format!("layer {}: max_bitrate is below bitrate", s.id)); + } + if specs[..i].iter().any(|o| o.id == s.id) { + return Err(format!("layer id {} appears twice", s.id)); + } + } + Ok(()) +} + +/// Simulcast layers of our stream; empty: one layer. +pub static STREAM_LAYERS: Key> = Key::new( + "stream.layers", + Kind::Json, + "Simulcast layers of our stream (empty: one layer).", + Vec::new, +) +.validated(valid_layers); + +/// Video codec of our stream. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CodecChoice { + /// The best one both ends support. + #[default] + Auto, + Vp8, + Vp9, + H264, + Av1, +} + +pub static STREAM_CODEC: Key = Key::new( + "stream.codec", + Kind::Choice(&["auto", "vp8", "vp9", "h264", "av1"]), + "Video codec of our stream.", + CodecChoice::default, +); + +/// How the screen is captured. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CaptureChoice { + #[default] + Auto, + /// The desktop's ScreenCast portal (Wayland, Flatpak). + Portal, + /// wlroots screencopy. + Wlroots, + X11, +} + +pub static STREAM_CAPTURE_BACKEND: Key = Key::new( + "stream.capture_backend", + Kind::Choice(&["auto", "portal", "wlroots", "x11"]), + "How the screen is captured.", + CaptureChoice::default, +); + +#[allow(clippy::ptr_arg)] // a validation of `Key` is `fn(&String)` +fn not_empty(s: &String) -> Result<(), String> { + if s.trim().is_empty() { Err("must not be empty".into()) } else { Ok(()) } +} + +/// Video encoder: `auto`, `software`, or the name of an encoder backend. +pub static STREAM_ENCODER_BACKEND: Key = Key::new( + "stream.encoder_backend", + Kind::Text { suggestions: &["auto", "software"] }, + "Video encoder: auto, software, or an encoder's name.", + || "auto".into(), +) +.validated(not_empty); + +/// SRTP protection profiles the WebRTC stack knows. +pub const SRTP_PROFILES: &[&str] = &["AES128_CM_SHA1_80", "AEAD_AES_128_GCM", "AEAD_AES_256_GCM"]; + +#[allow(clippy::ptr_arg)] // a validation of `Key>` is `fn(&Vec<_>)` +fn valid_srtp(list: &Vec) -> Result<(), String> { + if list.is_empty() { + return Err("at least one profile is needed".into()); + } + for (i, p) in list.iter().enumerate() { + if !SRTP_PROFILES.contains(&p.as_str()) { + return Err(format!("unknown profile {p} (known: {})", SRTP_PROFILES.join(", "))); + } + if list[..i].contains(p) { + return Err(format!("{p} appears twice")); + } + } + Ok(()) +} + +/// SRTP profiles offered for stream media, most preferred first. +pub static STREAM_SRTP_PROFILES: Key> = Key::new( + "stream.srtp_profiles", + Kind::List(SRTP_PROFILES), + "SRTP profiles for stream media, most preferred first.", + || SRTP_PROFILES.iter().map(|p| (*p).to_owned()).collect(), +) +.validated(valid_srtp); + +/// Use hardware video encoders and decoders where available. +pub static STREAM_HARDWARE_ACCELERATION: Key = Key::new( + "stream.hardware_acceleration", + Kind::Bool, + "Use hardware video encoders and decoders where available.", + || true, +); + +/// Who may watch our stream without being asked. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum StreamPermissions { + /// Every join request is accepted. + Everyone, + /// Friends are accepted. Until there are contacts, every request is + /// shown to the user ([`crate::Event::StreamViewerRequest`]). + Friends, + /// Clients in our channel are accepted, others denied. + #[default] + Channel, + /// Every join request is denied. + Nobody, +} + +pub static STREAM_PERMISSIONS: Key = Key::new( + "stream.permissions", + Kind::Choice(&["everyone", "friends", "channel", "nobody"]), + "Who may watch our stream without being asked.", + StreamPermissions::default, +); + +/// The keys every [`Settings`] knows from the start. +pub fn builtin_keys() -> [&'static dyn Setting; 11] { + [ + &CRASH_REPORTS, + &AUDIO, + &STREAM_FPS, + &STREAM_BITRATE_KBPS, + &STREAM_LAYERS, + &STREAM_CODEC, + &STREAM_CAPTURE_BACKEND, + &STREAM_ENCODER_BACKEND, + &STREAM_SRTP_PROFILES, + &STREAM_HARDWARE_ACCELERATION, + &STREAM_PERMISSIONS, + ] +} + +/// The engine's settings: one [`Settings`] that [`crate::Command::AttachSettings`] +/// can replace, shared by the engine and its sessions. +#[derive(Clone, Debug, Default)] +pub(crate) struct SharedSettings(Arc>); + +impl SharedSettings { + pub fn new(settings: Settings) -> Self { + Self(Arc::new(RwLock::new(settings))) + } + + pub fn current(&self) -> Settings { + self.0.read().unwrap_or_else(PoisonError::into_inner).clone() + } + + pub fn replace(&self, settings: Settings) { + *self.0.write().unwrap_or_else(PoisonError::into_inner) = settings; + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + fn temp_db(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!( + "voelin-settings-{tag}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&dir); + dir.join("client.db") + } + + #[test] + fn defaults_and_registry() { + let s = Settings::in_memory(); + assert_eq!(s.get(&STREAM_FPS), 60); + assert_eq!(s.get(&STREAM_BITRATE_KBPS), 8000); + assert!(s.get(&STREAM_LAYERS).is_empty()); + assert_eq!(s.get(&STREAM_CODEC), CodecChoice::Auto); + assert_eq!(s.get(&STREAM_PERMISSIONS), StreamPermissions::Channel); + assert_eq!( + s.get(&STREAM_SRTP_PROFILES), + ["AES128_CM_SHA1_80", "AEAD_AES_128_GCM", "AEAD_AES_256_GCM"] + ); + assert!(s.get(&STREAM_HARDWARE_ACCELERATION)); + assert_eq!(s.get(&STREAM_ENCODER_BACKEND), "auto"); + assert_eq!(s.source("stream.fps"), Some(Source::Default)); + let names: Vec<_> = s.keys().iter().map(|k| k.name()).collect(); + assert!(names.contains(&"stream.permissions") && names.contains(&"audio")); + assert!(names.windows(2).all(|w| w[0] < w[1]), "sorted: {names:?}"); + assert_eq!(s.get_json("stream.codec"), Some(json!("auto"))); + assert_eq!(s.get_json("nope"), None); + } + + #[test] + fn precedence_and_reset() { + let s = Settings::in_memory(); + s.set_config("stream.fps", json!(24)).unwrap(); + assert_eq!((s.get(&STREAM_FPS), s.source("stream.fps")), (24, Some(Source::Config))); + assert!(s.apply_overrides(["stream.fps=90"]).is_empty()); + assert_eq!((s.get(&STREAM_FPS), s.source("stream.fps")), (90, Some(Source::Override))); + s.set(&STREAM_FPS, 144).unwrap(); + assert_eq!((s.get(&STREAM_FPS), s.source("stream.fps")), (144, Some(Source::Runtime))); + // A later config or override does not beat the runtime value. + s.set_config("stream.fps", json!(10)).unwrap(); + s.set_override("stream.fps", json!(20)).unwrap(); + assert_eq!(s.get(&STREAM_FPS), 144); + s.reset("stream.fps").unwrap(); + assert_eq!((s.get(&STREAM_FPS), s.source("stream.fps")), (20, Some(Source::Override))); + + // Environment names; strings without quotes. + let env = [ + ("VOELIN_SETTING_STREAM__CODEC".to_owned(), "vp9".to_owned()), + ("VOELIN_SETTING_STREAM__BITRATE_KBPS".to_owned(), "25000".to_owned()), + ("OTHER".to_owned(), "x".to_owned()), + ]; + assert!(s.apply_env(env).is_empty()); + assert_eq!(s.get(&STREAM_CODEC), CodecChoice::Vp9); + assert_eq!(s.get(&STREAM_BITRATE_KBPS), 25_000); + } + + #[test] + fn validation() { + let s = Settings::in_memory(); + let invalid = + |r: Result<(), SettingsError>| matches!(r, Err(SettingsError::Invalid { .. })); + assert!(invalid(s.set(&STREAM_FPS, 0))); + assert!(invalid(s.set_json("stream.fps", json!("fast")))); + assert!(invalid(s.set_json("stream.codec", json!("mpeg2")))); + assert!(invalid(s.set_json("stream.srtp_profiles", json!([])))); + assert!(invalid( + s.set_json("stream.srtp_profiles", json!(["AEAD_AES_128_GCM", "AEAD_AES_128_GCM"])) + )); + assert!(invalid(s.set_json("stream.layers", json!([{"bitrate": 0}])))); + assert!(invalid( + s.set_json("stream.layers", json!([{"id": 1, "bitrate": 5}, {"id": 1, "bitrate": 5}])) + )); + assert!(invalid(s.set_override("stream.permissions", json!("strangers")))); + assert!(matches!(s.set_json("stream.nope", json!(1)), Err(SettingsError::UnknownKey(_)))); + assert_eq!(s.apply_overrides(["stream.fps"]).len(), 1, "no ="); + // Nothing changed. + assert_eq!(s.get(&STREAM_FPS), 60); + // No maximum. + s.set_json("stream.fps", json!(1000)).unwrap(); + s.set(&STREAM_BITRATE_KBPS, u32::MAX).unwrap(); + assert_eq!(s.get(&STREAM_BITRATE_KBPS), u32::MAX); + } + + #[test] + fn layers_convert_to_specs() { + let s = Settings::in_memory(); + s.set_json( + "stream.layers", + json!([{"scale": 0.5, "max_fps": 30, "bitrate": 1_500_000, "rid": "l"}, + {"size": [1920, 1080], "bitrate": 6_000_000, "max_bitrate": 9_000_000}]), + ) + .unwrap(); + let specs = layer_specs(&s.get(&STREAM_LAYERS)); + assert_eq!(specs.len(), 2); + assert_eq!((specs[0].id, specs[0].scale, specs[0].rid.as_deref()), (0, 0.5, Some("l"))); + assert_eq!( + (specs[1].id, specs[1].size, specs[1].max_bitrate), + (1, Some((1920, 1080)), Some(9_000_000)) + ); + assert_eq!(LayerSetting::from_spec(&specs[1]).to_spec(7), specs[1]); + } + + #[tokio::test] + async fn notifications() { + let s = Settings::in_memory(); + let mut all = s.subscribe(); + let mut fps = s.watch(&STREAM_FPS); + assert_eq!(*fps.get(), 60); + assert!(!fps.has_changed()); + s.set(&STREAM_FPS, 90).unwrap(); + assert_eq!( + *tokio::time::timeout(Duration::from_secs(1), fps.changed()).await.unwrap().unwrap(), + 90 + ); + assert_eq!( + all.recv().await.unwrap(), + SettingChange { key: "stream.fps".into(), source: Some(Source::Runtime) } + ); + // A set of the same value is announced, but the value did not change. + s.set(&STREAM_FPS, 90).unwrap(); + assert_eq!(all.recv().await.unwrap().key, "stream.fps"); + assert!(fps.get_new().is_none()); + s.reset("stream.fps").unwrap(); + assert_eq!( + all.recv().await.unwrap(), + SettingChange { key: "stream.fps".into(), source: Some(Source::Default) } + ); + assert_eq!(fps.get_new().as_deref(), Some(&60)); + // Other keys do not wake this watch. + s.set(&STREAM_CODEC, CodecChoice::Av1).unwrap(); + assert!(!fps.has_changed()); + assert_eq!(all.recv().await.unwrap().key, "stream.codec"); + } + + #[test] + fn persistence_across_reopen() { + let path = temp_db("reopen"); + { + let s = Settings::open(&path).unwrap(); + s.set(&STREAM_FPS, 75).unwrap(); + s.set(&STREAM_PERMISSIONS, StreamPermissions::Nobody).unwrap(); + s.set(&STREAM_CODEC, CodecChoice::H264).unwrap(); + s.reset("stream.codec").unwrap(); + s.set_override("stream.bitrate_kbps", json!(123)).unwrap(); + s.flush().unwrap(); + } + let s = Settings::open(&path).unwrap(); + assert_eq!(s.get(&STREAM_FPS), 75); + assert_eq!(s.get(&STREAM_PERMISSIONS), StreamPermissions::Nobody); + assert_eq!(s.source("stream.codec"), Some(Source::Default)); + assert_eq!( + s.source("stream.bitrate_kbps"), + Some(Source::Default), + "overrides are not stored" + ); + drop(s); + // Written without flush: the writer finishes when the settings are dropped. + { + let s = Settings::open(&path).unwrap(); + s.set(&STREAM_FPS, 76).unwrap(); + } + assert_eq!(Settings::open(&path).unwrap().get(&STREAM_FPS), 76); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + /// A key another crate defines (like the UI's blobs). + #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] + #[serde(default)] + struct Blob { + a: u32, + b: String, + } + + static BLOB: Key = Key::new("blob", Kind::Json, "A test blob.", Blob::default); + /// The UI's blob, as the UI registers it. + static UI: Key = Key::new("ui", Kind::Json, "The UI's settings.", || Value::Null); + static LATER: Key = Key::new("later.number", Kind::UInt { min: 0 }, "A test key.", || 1); + + #[test] + fn old_blobs_migrate_and_stay() { + let path = temp_db("migrate"); + { + let store = Store::open(&path).unwrap(); + let ui = json!({"global_ptt": true, "ptt_key": "F9", "crash_reports": true, + "share": {"fps_index": 2, "bitrate_index": 1, "audio": false, "auto_accept": true}}); + store.set_setting("ui", &ui).unwrap(); + store + .set_setting("audio", &json!({"transmit": "continuous", "output_volume": 0.5})) + .unwrap(); + store.set_setting("blob", &json!({"a": 3})).unwrap(); + } + let s = Settings::open(&path).unwrap(); + // The chosen 60 fps is copied; the old default bitrate is not. + assert_eq!((s.get(&STREAM_FPS), s.source("stream.fps")), (60, Some(Source::Runtime))); + assert_eq!(s.source("stream.bitrate_kbps"), Some(Source::Default)); + assert!(s.get(&CRASH_REPORTS)); + // The old blobs are keys as before; partial ones fill in defaults. + let audio = s.get(&AUDIO); + assert_eq!((audio.transmit, audio.output_volume), (crate::TransmitMode::Continuous, 0.5)); + assert_eq!(s.get(&BLOB), Blob { a: 3, b: String::new() }); + assert_eq!(s.get_json("ui"), None, "not a core key"); + assert_eq!(s.get(&UI)["ptt_key"], "F9", "registered later"); + // Runs once: a later change is not overwritten by the blob. + s.set(&STREAM_FPS, 50).unwrap(); + drop(s); + let s = Settings::open(&path).unwrap(); + assert_eq!(s.get(&STREAM_FPS), 50); + drop(s); + let store = Store::open(&path).unwrap(); + assert!(store.setting::("ui").unwrap().is_some(), "the blob stays"); + assert_eq!(store.setting::(VERSION_KEY).unwrap(), Some(MIGRATIONS.len())); + drop(store); + std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); + } + + #[test] + fn config_files() { + let path = temp_db("config"); + let dir = path.parent().unwrap(); + std::fs::create_dir_all(dir).unwrap(); + let toml = dir.join("config.toml"); + std::fs::write( + &toml, + "\"stream.codec\" = \"vp8\"\n[stream]\nfps = 30\npermissions = \"loud\"\n\ + [audio]\ntransmit = \"voice_activation\"\n", + ) + .unwrap(); + let s = Settings::in_memory(); + let errors = s.load_config_file(&toml).unwrap(); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(s.get(&STREAM_CODEC), CodecChoice::Vp8); + assert_eq!((s.get(&STREAM_FPS), s.source("stream.fps")), (30, Some(Source::Config))); + assert_eq!(s.get(&AUDIO).transmit, crate::TransmitMode::VoiceActivation); + // Object values need their key registered first; other keys wait + // for their registration. + let json = dir.join("config.json"); + std::fs::write(&json, r#"{"blob": {"b": "x"}, "later": {"number": 5}}"#).unwrap(); + s.register(&BLOB); + assert!(s.load_config_file(&json).unwrap().is_empty()); + assert_eq!(s.get(&BLOB).b, "x"); + assert_eq!((s.get(&LATER), s.source("later.number")), (5, Some(Source::Config))); + assert!(s.load_config_file(&dir.join("missing.toml")).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index f1800b4..cd85980 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -23,6 +23,7 @@ pub use voelin_stream::{ }; use crate::audio::{AudioHandle, AudioIn}; +use crate::settings::{STREAM_PERMISSIONS, SharedSettings, StreamPermissions}; use crate::voice::VoiceCmd; use crate::{Event, SessionId}; @@ -146,6 +147,7 @@ pub(crate) struct StreamHandle { } impl StreamHandle { + #[allow(clippy::too_many_arguments)] // the parts of the session the task uses pub fn spawn( session: SessionId, own_client: u16, @@ -154,6 +156,7 @@ impl StreamHandle { events: broadcast::Sender, frames: broadcast::Sender, audio: Option, + settings: SharedSettings, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); let task = StreamTask { @@ -165,6 +168,7 @@ impl StreamHandle { audio, tx: tx.clone(), sink: None, + settings, }; tokio::spawn(task.run(rx)); Self { tx } @@ -187,6 +191,8 @@ struct StreamTask { tx: mpsc::UnboundedSender, /// The sink of our live stream. sink: Option, + /// `stream.permissions` decides join requests. + settings: SharedSettings, } impl StreamTask { @@ -285,7 +291,23 @@ impl StreamTask { self.emit(Event::StreamState { session, state: StreamState::Live { id, sink } }); } StreamEvent::Streamer(StreamerEvent::Request { viewer, message }) => { - self.emit(Event::StreamViewerRequest { session, viewer: viewer.0, message }); + match self.join_decision(viewer) { + // Answered through the input queue, as the user would. + Some(accept) => { + debug!( + viewer = viewer.0, + accept, "join request answered by stream.permissions" + ); + let _ = self.tx.send(StreamInput::Respond { viewer: viewer.0, accept }); + } + None => { + self.emit(Event::StreamViewerRequest { + session, + viewer: viewer.0, + message, + }); + } + } } StreamEvent::Streamer(StreamerEvent::Viewers(viewers)) => { self.emit(Event::StreamViewers { session, viewers }); @@ -329,6 +351,21 @@ impl StreamTask { } } + /// The answer `stream.permissions` gives to a join request; `None`: ask. + fn join_decision(&self, viewer: ClientId) -> Option { + match *self.settings.current().get_arc(&STREAM_PERMISSIONS) { + StreamPermissions::Everyone => Some(true), + StreamPermissions::Nobody => Some(false), + // No contacts yet: ask for everyone. + StreamPermissions::Friends => None, + StreamPermissions::Channel => { + let discovery = self.streams.discovery(); + let own = discovery.own_channel(); + Some(own.is_some() && discovery.channel_of(viewer) == own) + } + } + } + /// The connection is gone: report our stream and watched streams as ended. fn shutdown(&mut self, reason: String) { let session = self.session; @@ -360,6 +397,7 @@ mod tests { use voelin_stream::{FrameSource, SyntheticSource}; use super::*; + use crate::settings::Settings; const CLIENTS: [u16; 2] = [5, 6]; @@ -445,6 +483,14 @@ mod tests { /// server; `audio` is the viewer's audio thread. fn pair( audio: Option, + ) -> (Handles, broadcast::Receiver, broadcast::Receiver) { + pair_with(audio, &Settings::in_memory()) + } + + /// [`pair`] with `settings` for both tasks. + fn pair_with( + audio: Option, + settings: &Settings, ) -> (Handles, broadcast::Receiver, broadcast::Receiver) { let (events, rx) = broadcast::channel(4096); let (frames, frames_rx) = broadcast::channel(4096); @@ -463,6 +509,7 @@ mod tests { events.clone(), frames.clone(), if session == 2 { audio.take() } else { None }, + SharedSettings::new(settings.clone()), )); voices.push(voice_rx); } @@ -587,6 +634,63 @@ mod tests { handles[1].send(StreamInput::Shutdown("bye".into())); } + /// `stream.permissions` answers join requests unless it is `friends`. + #[tokio::test(flavor = "multi_thread")] + async fn permissions_answer_join_requests() { + let in_channels = |streamer: u64, viewer: u64| { + StreamInput::Clients(BTreeMap::from([ + (CLIENTS[0], ClientState { channel: streamer, streaming: Some(false) }), + (CLIENTS[1], ClientState { channel: viewer, streaming: Some(false) }), + ])) + }; + for (permissions, viewer_channel, expected) in [ + (StreamPermissions::Everyone, 2, Some(true)), + (StreamPermissions::Channel, 1, Some(true)), + (StreamPermissions::Channel, 2, Some(false)), + (StreamPermissions::Nobody, 1, Some(false)), + (StreamPermissions::Friends, 1, None), + ] { + let settings = Settings::in_memory(); + settings.set(&STREAM_PERMISSIONS, permissions).unwrap(); + let (handles, mut rx, _frames) = pair_with(None, &settings); + for h in handles.iter() { + h.send(in_channels(1, viewer_channel)); + } + let setup = StreamSetup { name: "p".into(), ..Default::default() }; + handles[0].send(StreamInput::Start { setup, auto_accept: false }); + let (mut live, mut listed) = (false, false); + wait(&mut rx, |e| { + match e { + Event::StreamState { session: 1, state: StreamState::Live { .. } } => { + live = true + } + Event::StreamsChanged { session: 2, streams } => listed = !streams.is_empty(), + _ => {} + } + (live && listed).then_some(()) + }) + .await; + handles[1].send(StreamInput::Watch { stream_id: "s-1".into() }); + let answer = wait(&mut rx, |e| match e { + Event::WatchState { session: 2, state: WatchState::Connected, .. } => { + Some(Some(true)) + } + Event::WatchState { + session: 2, + state: WatchState::Ended(EndReason::Denied), + .. + } => Some(Some(false)), + Event::StreamViewerRequest { session: 1, .. } => Some(None), + _ => None, + }) + .await; + assert_eq!(answer, expected, "{permissions:?}, viewer in channel {viewer_channel}"); + for h in handles.iter() { + h.send(StreamInput::Shutdown("done".into())); + } + } + } + /// The whole path: test pattern → VP8 → stream task → str0m peers on /// loopback → the viewer's frame bus → decoder. The pictures show the /// moving rectangle. diff --git a/crates/voelin-core/tests/settings.rs b/crates/voelin-core/tests/settings.rs new file mode 100644 index 0000000..30abd65 --- /dev/null +++ b/crates/voelin-core/tests/settings.rs @@ -0,0 +1,75 @@ +//! Settings through the engine: commands, change events, attaching stored +//! settings. + +use std::time::Duration; + +use serde_json::json; +use tokio::sync::broadcast::Receiver; +use tokio::time::timeout; +use voelin_core::settings::{STREAM_CODEC, STREAM_FPS, Settings, Source}; +use voelin_core::{Command, Engine, Event}; + +async fn next_setting_event(rx: &mut Receiver) -> Event { + timeout(Duration::from_secs(5), async { + loop { + let e = rx.recv().await.unwrap(); + if matches!(e, Event::SettingChanged { .. } | Event::SettingRejected { .. }) { + return e; + } + } + }) + .await + .expect("no settings event") +} + +#[tokio::test] +async fn commands_and_change_events() { + let engine = Engine::start(); + let mut events = engine.subscribe(); + + engine.send(Command::SetSetting { key: "stream.fps".into(), value: json!(144) }); + let Event::SettingChanged { key } = next_setting_event(&mut events).await else { + panic!("expected a change") + }; + assert_eq!(key, "stream.fps"); + assert_eq!(engine.settings().get(&STREAM_FPS), 144); + + engine.send(Command::SetSetting { key: "stream.fps".into(), value: json!(0) }); + let Event::SettingRejected { key, message } = next_setting_event(&mut events).await else { + panic!("expected a rejection") + }; + assert_eq!(key, "stream.fps"); + assert!(message.contains("at least 1"), "{message}"); + engine.send(Command::SetSetting { key: "no.such.key".into(), value: json!(1) }); + assert!(matches!(next_setting_event(&mut events).await, Event::SettingRejected { .. })); + + // A change made directly on the settings is reported too. + engine.settings().set_json("stream.codec", json!("av1")).unwrap(); + assert!(matches!( + next_setting_event(&mut events).await, + Event::SettingChanged { key } if key == "stream.codec" + )); + + engine.send(Command::ResetSetting { key: "stream.fps".into() }); + assert!(matches!(next_setting_event(&mut events).await, Event::SettingChanged { .. })); + assert_eq!(engine.settings().get(&STREAM_FPS), 60); + assert_eq!(engine.settings().source("stream.fps"), Some(Source::Default)); + + // Attached settings replace the engine's: their changes are reported, + // the old ones' are not. + let old = engine.settings(); + let attached = Settings::in_memory(); + attached.set_override("stream.fps", json!(30)).unwrap(); + engine.send(Command::AttachSettings(attached.clone())); + engine.send(Command::SetSetting { key: "stream.codec".into(), value: json!("vp9") }); + assert!(matches!(next_setting_event(&mut events).await, Event::SettingChanged { .. })); + assert_eq!(attached.get(&STREAM_CODEC), voelin_core::settings::CodecChoice::Vp9); + assert_eq!(engine.settings().get(&STREAM_FPS), 30); + old.set_json("stream.fps", json!(5)).unwrap(); + attached.set_json("stream.fps", json!(6)).unwrap(); + assert!(matches!( + next_setting_event(&mut events).await, + Event::SettingChanged { key } if key == "stream.fps" + )); + assert_eq!(engine.settings().get(&STREAM_FPS), 6); +} diff --git a/crates/voelin-core/tests/stream_live.rs b/crates/voelin-core/tests/stream_live.rs index 249d4e7..4d1222c 100644 --- a/crates/voelin-core/tests/stream_live.rs +++ b/crates/voelin-core/tests/stream_live.rs @@ -100,7 +100,9 @@ async fn ts6_stream_between_sessions() { connect(&engine, &mut events, 1, "127.0.0.1:9988", &format!("e-streamer-{tag}")).await; connect(&engine, &mut events, 2, "127.0.0.1:9988", &format!("e-viewer-{tag}")).await; - // Stream, asking for each viewer. + // Stream, asking for each viewer ("friends" asks everyone until there + // are contacts; the default, "channel", accepts the viewer by itself). + engine.send(Command::SetSetting { key: "stream.permissions".into(), value: "friends".into() }); let setup = StreamSetup { name: format!("engine {tag}"), ..Default::default() }; engine.send(Command::StartStream { session: 1, setup, auto_accept: false }); // The viewer's list often updates before the streamer goes live, so wait diff --git a/crates/voelin-stream/src/discovery.rs b/crates/voelin-stream/src/discovery.rs index 1feab33..beacbfe 100644 --- a/crates/voelin-stream/src/discovery.rs +++ b/crates/voelin-stream/src/discovery.rs @@ -113,6 +113,11 @@ impl Discovery { self.clients.get(&self.own.0).map(|c| c.channel) } + /// The channel of a client, as of the last update. + pub fn channel_of(&self, client: ClientId) -> Option { + self.clients.get(&client.0).map(|c| c.channel) + } + /// Whether a stream of `streamer` belongs in the directory: it is in our /// channel (or the clients are not known yet). pub fn in_our_channel(&self, streamer: ClientId) -> bool { diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index ae397b2..18597e4 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -914,6 +914,11 @@ impl Streams { &self.directory } + /// The clients' channels as of [`Self::update_clients`]. + pub fn discovery(&self) -> &Discovery { + &self.discovery + } + /// Our stream, while it has not ended. pub fn streamer(&self) -> Option<&StreamerSession> { self.streamer.as_ref().filter(|s| !s.is_ended())