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<T> 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<T>; 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-27 03:56:56 +00:00
1 parent 20699bfb9f
commit 178173ad0d
10 files changed
+1690 -10

No files matched your search

Generated
+3
View File
@@ -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",
]
+3
View File
@@ -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" }
+125 -6
View File
@@ -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<Event>,
frames: broadcast::Sender<StreamFrame>,
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<Command> {
let stored = settings.get_arc(&settings::AUDIO);
(*stored != *running).then(|| Command::SetAudioSettings(Box::new((*stored).clone())))
}
async fn run(
mut commands: mpsc::UnboundedReceiver<Command>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
shared: SharedSettings,
) {
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let mut current = shared.current();
let mut changes = current.subscribe();
let mut settings = AudioSettings::default();
let mut mic_test: Option<AudioHandle> = 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(&current, &settings)).flatten() {
Some(command) => command,
None => continue,
}
}
Input::SettingsLagged => match stored_audio(&current, &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")
}
}
+13 -2
View File
@@ -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<Event>,
frames: broadcast::Sender<StreamFrame>,
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<Presence>,
audio: Option<AudioHandle>,
audio_settings: AudioSettings,
settings: SharedSettings,
/// Streams of the voice connection (TeamSpeak 6 only).
streams: Option<StreamHandle>,
stream_peer: PeerConfig,
@@ -82,6 +85,7 @@ impl Session {
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
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 });
File diff suppressed because it is too large. Load diff
+105 -1
View File
@@ -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<Event>,
frames: broadcast::Sender<StreamFrame>,
audio: Option<AudioHandle>,
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<StreamInput>,
/// The sink of our live stream.
sink: Option<StreamSink>,
/// `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<bool> {
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<AudioHandle>,
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
pair_with(audio, &Settings::in_memory())
}
/// [`pair`] with `settings` for both tasks.
fn pair_with(
audio: Option<AudioHandle>,
settings: &Settings,
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
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.
+75
View File
@@ -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>) -> 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);
}
+3 -1
View File
@@ -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
+5
View File
@@ -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<u64> {
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 {
+5
View File
@@ -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())