From a6cfee9948de86dced17b2f2a9263c85cbad5f26 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 03:39:40 +0000 Subject: [PATCH 1/5] voelinctl: probe-stream, how a late TS6 client can find a running stream The server announces a stream only to the clients in the streamer's channel when it starts; clients that arrive later see only client_is_streaming. To find out what the server offers instead, probe-stream runs two clients: A creates a channel and starts a stream, B arrives afterwards and tries candidate commands from another channel and from A's channel (requeststreaminfo spellings, clientgetvariables, clientinfo, list-like command names, joinstreamrequest with the learned id), A tries updatestream and client_meta_data. Every command both clients exchange is printed raw through a listener on the tsproto connection (tsclientlib's unstable API), so notifications the declarations do not know yet show up too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- Cargo.lock | 1 + tools/voelinctl/Cargo.toml | 4 +- tools/voelinctl/src/main.rs | 5 + tools/voelinctl/src/probe.rs | 477 +++++++++++++++++++++++++++++++++ tools/voelinctl/src/session.rs | 2 +- 5 files changed, 487 insertions(+), 2 deletions(-) create mode 100644 tools/voelinctl/src/probe.rs diff --git a/Cargo.lock b/Cargo.lock index 4525066..4255e3a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9299,6 +9299,7 @@ dependencies = [ "tracing", "tracing-subscriber", "tsclientlib", + "tsproto", "tsproto-packets", "voelin-audio", "voelin-core", diff --git a/tools/voelinctl/Cargo.toml b/tools/voelinctl/Cargo.toml index 5edf9c1..3ed9ccc 100644 --- a/tools/voelinctl/Cargo.toml +++ b/tools/voelinctl/Cargo.toml @@ -19,7 +19,9 @@ serde_json = "1" tokio = { version = "1", features = ["io-std", "io-util", "macros", "rt-multi-thread", "signal", "time"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } -tsclientlib = { path = "../../crates/proto/tsclientlib" } +# `unstable`: the raw connection, for the command log of `probe-stream`. +tsclientlib = { path = "../../crates/proto/tsclientlib", features = ["unstable"] } +tsproto = { path = "../../crates/proto/tsproto" } tsproto-packets = { path = "../../crates/proto/tsproto-packets" } voelin-model = { path = "../../crates/voelin-model" } voelin-query = { path = "../../crates/voelin-query" } diff --git a/tools/voelinctl/src/main.rs b/tools/voelinctl/src/main.rs index b23cef5..4f57f69 100644 --- a/tools/voelinctl/src/main.rs +++ b/tools/voelinctl/src/main.rs @@ -3,6 +3,7 @@ mod gateway; mod identity; mod observe; +mod probe; mod query; mod session; mod stream; @@ -46,6 +47,9 @@ enum Command { Relay(observe::RelayArgs), /// Use a tsgw gateway as a user: presence, chat, history. Gateway(gateway::GatewayArgs), + /// TeamSpeak 6: probe how a client that arrives after a stream started + /// can learn about it; prints every command both clients exchange. + ProbeStream(probe::ProbeStreamArgs), } #[derive(Subcommand, Debug)] @@ -208,6 +212,7 @@ fn main() -> Result<()> { Command::Observe(args) => tokio::runtime::Runtime::new()?.block_on(observe::observe(args)), Command::Relay(args) => tokio::runtime::Runtime::new()?.block_on(observe::relay(args)), Command::Gateway(args) => tokio::runtime::Runtime::new()?.block_on(gateway::run(args)), + Command::ProbeStream(args) => tokio::runtime::Runtime::new()?.block_on(probe::run(args)), } } diff --git a/tools/voelinctl/src/probe.rs b/tools/voelinctl/src/probe.rs new file mode 100644 index 0000000..b864c4a --- /dev/null +++ b/tools/voelinctl/src/probe.rs @@ -0,0 +1,477 @@ +//! `voelinctl probe-stream`: how can a TeamSpeak 6 client that arrives after a +//! stream started learn about it? +//! +//! Client A creates a channel and starts a stream there (signalling only, no +//! media). Client B connects afterwards and tries candidate commands, first +//! from another channel, then from A's channel; A then tries to re-announce +//! the stream. Every command both clients send and receive is printed raw, +//! with the time since the probe started. Findings are kept in +//! `docs/research/ts6-late-join.md`. + +use std::path::PathBuf; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use clap::Args; +use futures::prelude::*; +use tokio::time::{Instant, sleep_until}; +use tsclientlib::prelude::*; +use tsclientlib::{ChannelId, ClientId, Connection, DisconnectOptions, StreamItem}; +use tsproto::connection::Event as RawEvent; +use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType}; +use voelin_stream::{StreamNotification, StreamSetup, proto}; + +use crate::{identity, session}; + +#[derive(Args, Debug)] +pub struct ProbeStreamArgs { + /// A TeamSpeak 6 server. + #[arg(default_value = "127.0.0.1:9988")] + address: String, + /// Identity of the streamer A. A creates a channel, so on servers where + /// guests may not, pass an admin identity. + #[arg(long)] + streamer_identity: Option, + /// Identity of the late client B. + #[arg(long)] + viewer_identity: Option, + /// How long to collect notifications after each answer. + #[arg(long, default_value_t = 1200)] + settle_ms: u64, + /// More raw commands for B to try in A's channel. `{id}` is the stream + /// id, `{a}`/`{b}` the clients' ids, `{cid}` A's channel. + #[arg(long = "try")] + extra: Vec, + /// Also print the noisy notifications (connection info, permissions). + #[arg(long)] + verbose: bool, +} + +/// Which client. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Who { + A, + B, +} + +impl Who { + fn label(self) -> &'static str { + match self { + Who::A => "A", + Who::B => "B", + } + } +} + +/// A raw command as sent or received. +struct Line { + at: Instant, + who: Who, + outgoing: bool, + text: String, +} + +type Lines = Arc>>; + +/// Values the command templates refer to. +#[derive(Clone, Debug, Default)] +struct Vars { + id: String, + a: u16, + b: u16, + cid: u64, +} + +impl Vars { + fn fill(&self, template: &str) -> String { + template + .replace("{id}", &self.id) + .replace("{a}", &self.a.to_string()) + .replace("{b}", &self.b.to_string()) + .replace("{cid}", &self.cid.to_string()) + } +} + +struct Probe { + args: ProbeStreamArgs, + start: Instant, + lines: Lines, + /// Lines already printed. + printed: usize, + a: Connection, + b: Option, + vars: Vars, +} + +/// Notifications that say nothing about streams. +const NOISE: &[&str] = &[ + "notifyconnectioninfo", + "setconnectioninfo", + "notifyclientneededpermissions", + "notifychannelgrouplist", + "notifyservergrouplist", + "notifyclientchannelgroupchanged", + "clientinitiv", + "initivexpand", + "clientek", + "clientinit ", + "notifyclientpermlist", + "channellist ", + "notifychannelsubscribed", + "notifychanneledited", +]; + +pub async fn run(args: ProbeStreamArgs) -> Result<()> { + let start = Instant::now(); + let lines: Lines = Arc::default(); + let a = connect(&args.address, "probe-a", args.streamer_identity.as_ref(), None).await?; + let mut probe = Probe { args, start, lines, printed: 0, a, b: None, vars: Vars::default() }; + probe.attach(Who::A)?; + let result = probe.script().await; + probe.print(); + probe.finish().await; + result +} + +async fn connect( + address: &str, + nick: &str, + identity: Option<&PathBuf>, + channel: Option, +) -> Result { + let nick = format!("{nick}-{}", std::process::id() % 10_000); + let mut options = Connection::build(address.to_owned()).name(nick); + if let Some(path) = identity { + options = options.identity(identity::load(path)?); + } + if let Some(channel) = channel { + options = options.channel_id(channel); + } + let mut con = options.connect().context("failed to start connection")?; + session::wait_connected(&mut con, Instant::now() + Duration::from_secs(30)).await?; + Ok(con) +} + +fn raw(text: &str) -> OutCommand { + OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, text) +} + +impl Probe { + fn con(&mut self, who: Who) -> Result<&mut Connection> { + match who { + Who::A => Ok(&mut self.a), + Who::B => self.b.as_mut().context("B is not connected"), + } + } + + /// Record every command `who` sends and receives from now on. + fn attach(&mut self, who: Who) -> Result<()> { + let lines = self.lines.clone(); + let client = self.con(who)?.get_tsproto_client_mut()?; + client.event_listeners.push(Box::new(move |event: &RawEvent| { + let (outgoing, packet_type, content) = match event { + RawEvent::ReceivePacket(p) => (false, p.header().packet_type(), p.content()), + RawEvent::SendPacket(p) => (true, p.header().packet_type(), p.content()), + _ => return, + }; + if !packet_type.is_command() { + return; + } + let text = String::from_utf8_lossy(content).into_owned(); + let line = Line { at: Instant::now(), who, outgoing, text }; + lines.lock().unwrap_or_else(PoisonError::into_inner).push(line); + })); + Ok(()) + } + + fn note(&mut self, text: &str) { + self.print(); + println!("\n## {text}"); + } + + /// Print the lines recorded since the last call. + fn print(&mut self) { + let lines = self.lines.lock().unwrap_or_else(PoisonError::into_inner); + for line in &lines[self.printed..] { + if !self.args.verbose && NOISE.iter().any(|n| line.text.starts_with(n)) { + continue; + } + let mut text = line.text.clone(); + if text.len() > 600 { + let mut end = 600; + while !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); + text.push_str(" …"); + } + let t = line.at.duration_since(self.start).as_secs_f32(); + let arrow = if line.outgoing { "->" } else { "<-" }; + println!("[{t:7.3}] {} {arrow} {text}", line.who.label()); + } + self.printed = lines.len(); + } + + /// Drive both connections until `deadline` or until `done` returns true + /// for an item; `true` if it did. + async fn pump( + &mut self, + deadline: Instant, + mut done: impl FnMut(Who, &StreamItem) -> bool, + ) -> Result { + loop { + let (who, item) = { + let mut a_events = self.a.events(); + let a = a_events.next(); + let b = async { + match &mut self.b { + Some(b) => b.events().next().await, + None => future::pending().await, + } + }; + tokio::select! { + item = a => (Who::A, item), + item = b => (Who::B, item), + () = sleep_until(deadline) => return Ok(false), + } + }; + match item { + None => bail!("{} was disconnected", who.label()), + Some(Err(e)) => bail!("{}: {e}", who.label()), + Some(Ok(item)) => { + if done(who, &item) { + return Ok(true); + } + } + } + } + } + + async fn settle(&mut self) -> Result<()> { + let deadline = Instant::now() + Duration::from_millis(self.args.settle_ms); + self.pump(deadline, |_, _| false).await?; + Ok(()) + } + + /// Send a raw command (a template, see [`Vars`]), print the answer and + /// what arrives shortly after; the server's error, if any. + async fn send(&mut self, who: Who, template: &str) -> Result> { + let text = self.vars.fill(template); + let handle = raw(&text).send_with_result(self.con(who)?)?; + let mut result = None; + let deadline = Instant::now() + Duration::from_secs(10); + self.pump(deadline, |w, item| match item { + StreamItem::MessageResult(h, r) if w == who && *h == handle => { + result = Some(r.as_ref().err().map(ToString::to_string)); + true + } + _ => false, + }) + .await?; + self.settle().await?; + self.print(); + let error = match result { + None => Some("no answer".to_owned()), + Some(error) => error, + }; + println!( + " {} => {}", + who.label(), + error.as_deref().map_or_else(|| "ok".to_owned(), |e| format!("error: {e}")) + ); + Ok(error) + } + + fn own_client(&mut self, who: Who) -> Result { + Ok(self.con(who)?.get_state()?.own_client) + } + + async fn connect_b(&mut self, channel: Option) -> Result<()> { + let identity = self.args.viewer_identity.clone(); + let connecting = connect(&self.args.address, "probe-b", identity.as_ref(), channel); + // Keep A's connection going while B connects. + let b = { + let mut a = self.a.events(); + let drain_a = async { + loop { + if a.next().await.is_none() { + future::pending::<()>().await; + } + } + }; + tokio::select! { + b = connecting => b?, + () = drain_a => unreachable!(), + } + }; + self.b = Some(b); + self.attach(Who::B)?; + self.vars.b = self.own_client(Who::B)?.0; + self.settle().await?; + self.print(); + let a_id = ClientId(self.vars.a); + let state = self.con(Who::B)?.get_state()?; + let own = state.own_client; + let a = state.clients.get(&a_id); + println!( + " B is clid {} in channel {:?}; B's book: A {}", + own.0, + state.clients.get(&own).map(|c| c.channel.0), + a.map_or_else( + || "not visible".to_owned(), + |a| format!( + "in channel {}, is_streaming {:?}, metadata {:?}", + a.channel.0, a.is_streaming, a.metadata + ) + ) + ); + Ok(()) + } + + async fn disconnect_b(&mut self) -> Result<()> { + if let Some(mut b) = self.b.take() { + b.disconnect(DisconnectOptions::new())?; + let drain = b.events().for_each(|_| future::ready(())); + let _ = tokio::time::timeout(Duration::from_secs(3), drain).await; + } + Ok(()) + } + + async fn finish(&mut self) { + let _ = self.disconnect_b().await; + if self.a.disconnect(DisconnectOptions::new()).is_ok() { + let drain = self.a.events().for_each(|_| future::ready(())); + let _ = tokio::time::timeout(Duration::from_secs(3), drain).await; + } + } + + /// Candidate commands that could tell B about A's stream. + const QUERIES: &[&str] = &[ + "requeststreaminfo id={id}", + "requeststreaminfo id={id} clid={a}", + "requeststreaminfo clid={a}", + "requeststreaminfo stream_id={id}", + "requeststreaminfo stream_id={id} clid={a}", + "requeststreaminfo streamid={id} clid={a}", + "requeststreaminfo id={id} clid={a} msg", + "requeststreaminfo id={id} clid={a} return_code=probe", + "requeststreaminfo cid={cid}", + "requeststreaminfo", + "clientgetvariables clid={a}", + "clientinfo clid={a}", + "requeststreamattendees id={id}", + "streamattendees id={id}", + "streamlist", + "liststreams", + "requeststreams", + "requeststreamlist", + ]; + + async fn queries(&mut self) -> Result<()> { + for q in Self::QUERIES { + self.send(Who::B, q).await?; + } + Ok(()) + } + + async fn script(&mut self) -> Result<()> { + let version = self.a.get_state()?.server.version.clone(); + self.vars.a = self.own_client(Who::A)?.0; + println!("server {version}; A is clid {}", self.vars.a); + + self.note("A creates a channel, moves there and starts a stream"); + let name = format!("probe-{}", std::process::id() % 10_000); + self.send(Who::A, &format!("channelcreate channel_name={name}")).await?; + let cid = { + let state = self.a.get_state()?; + let channel = state.channels.values().find(|c| c.name == name); + channel.context("the new channel is not in A's book")?.id + }; + self.vars.cid = cid.0; + // The creator is usually moved already ("already member of channel"). + self.send(Who::A, "clientmove cid={cid} clid={a}").await?; + let setup = StreamSetup { name: "late join probe".into(), ..Default::default() }; + let handle = proto::setup(&setup).send_with_result(&mut self.a)?; + let own = ClientId(self.vars.a); + let mut id = None; + let deadline = Instant::now() + Duration::from_secs(10); + self.pump(deadline, |who, item| { + if let (Who::A, StreamItem::MessageEvent(msg)) = (who, item) { + for n in StreamNotification::from_message(msg) { + if let StreamNotification::Started { info, .. } = n + && info.streamer == own + { + id = Some(info.id); + } + } + } + matches!(item, StreamItem::MessageResult(h, Err(_)) if *h == handle) || id.is_some() + }) + .await?; + self.vars.id = id.context("setupstream was not confirmed")?; + self.settle().await?; + self.print(); + println!(" stream id {}", self.vars.id); + + self.note("B connects to the default channel, A's stream runs in another channel"); + self.connect_b(None).await?; + self.queries().await?; + self.send(Who::B, "channelsubscribeall").await?; + self.send(Who::B, "requeststreaminfo clid={a}").await?; + self.send(Who::B, "joinstreamrequest id={id} clid={a} msg=probe is_remove=0").await?; + self.send(Who::B, "joinstreamrequest id={id} clid={a} msg is_remove=1").await?; + + self.note("B switches into A's channel"); + self.send(Who::B, "clientmove cid={cid} clid={b}").await?; + self.queries().await?; + for extra in self.args.extra.clone() { + self.send(Who::B, &extra).await?; + } + + self.note("B asks to join with the id it was not told (does the server relay it?)"); + self.send(Who::B, "joinstreamrequest id={id} clid={a} msg=probe is_remove=0").await?; + self.send(Who::B, "joinstreamrequest id={id} clid={a} msg is_remove=1").await?; + + self.note("A tries to re-announce the stream while B is in the channel"); + self.send(Who::A, "updatestream id={id} name=renamed\\sprobe").await?; + self.send(Who::A, "updatestream id={id}").await?; + self.send(Who::A, "updatestream stream_id={id} name=renamed\\sprobe").await?; + self.send( + Who::A, + "updatestream id={id} name=renamed\\sprobe type=3 bitrate=4608 accessibility=1 \ + mode=1 viewer_limit=0 audio=1", + ) + .await?; + self.send( + Who::A, + "updatestream id={id} name=renamed\\sagain type=3 access=1 mode=1 bitrate=4000 \ + viewer_limit=0 audio=1", + ) + .await?; + self.send(Who::A, "requeststreaminfo id={id} clid={a}").await?; + self.send( + Who::A, + "setupstream name=second type=3 bitrate=4608 accessibility=1 mode=1 viewer_limit=0 \ + audio=1", + ) + .await?; + + self.note("A publishes the stream id in its client_meta_data"); + self.send(Who::A, "clientupdate client_meta_data=voelin-stream={id}").await?; + + self.note("B reconnects straight into A's channel"); + self.disconnect_b().await?; + self.settle().await?; + self.connect_b(Some(cid)).await?; + self.send(Who::B, "requeststreaminfo id={id} clid={a}").await?; + self.send(Who::B, "clientgetvariables clid={a}").await?; + self.send(Who::B, "joinstreamrequest id={id} clid={a} msg=probe is_remove=0").await?; + self.send(Who::B, "joinstreamrequest id={id} clid={a} msg is_remove=1").await?; + + self.note("A clears client_meta_data and stops the stream"); + self.send(Who::A, "clientupdate client_meta_data").await?; + self.send(Who::A, "stopstream id={id} reason=1").await?; + Ok(()) + } +} diff --git a/tools/voelinctl/src/session.rs b/tools/voelinctl/src/session.rs index 5548e64..99cb9fa 100644 --- a/tools/voelinctl/src/session.rs +++ b/tools/voelinctl/src/session.rs @@ -113,7 +113,7 @@ pub(crate) async fn pump( } } -async fn wait_connected(con: &mut Connection, deadline: Instant) -> Result<()> { +pub(crate) async fn wait_connected(con: &mut Connection, deadline: Instant) -> Result<()> { let end = pump(con, Some(deadline), |_, item| { Ok(match item { StreamItem::BookEvents(_) => Flow::Stop, From 47878a3ac0ad61b74a851f3cee85efe8069ef26c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 03:41:20 +0000 Subject: [PATCH 2/5] Find TeamSpeak 6 streams that started before we joined The server announces a stream (notifystreamstarted) only to the clients in the streamer's channel when it starts. A client that connects or enters the channel later saw the streamer's client_is_streaming flag but could not watch. The probe (docs/research/ts6-late-join.md) found that `requeststreaminfo clid=` answers with notifystreaminfo, one part per stream of the client, from any channel. voelin-stream gets a discovery module. Streams::update_clients takes the clients on the server (channel and streaming flag), keeps the directory to the streams in our channel, and looks up the streams of streamers in our channel we were not told about: after connecting, after we or they change channels, and when an announcement did not come. The answer fills the directory like an announcement, so Event::StreamsChanged lists the stream and it is watched like any other. Where streams are looked up is a StreamLookup trait (the server now; a gateway directory can plug in with Streams::add_lookup and report through Streams::discovered). notifystreamupdated (updatestream) now updates the directory. The engine and `voelinctl stream list/watch` feed the client list in. The declarations learn the notifystreaminfo answer's fields, notifystreamupdated and requeststreaminfo. Tests: a fake-server session test and an engine live test with a viewer that arrives after the stream is live, discovery unit tests, parsing of the server's answers; it-smoke gets a late-viewer step. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- .../declarations/Messages.toml | 12 +- crates/voelin-core/src/session.rs | 13 +- crates/voelin-core/src/stream.rs | 32 +- crates/voelin-core/tests/stream_live.rs | 104 ++++++ crates/voelin-stream/src/discovery.rs | 333 ++++++++++++++++++ crates/voelin-stream/src/lib.rs | 2 + crates/voelin-stream/src/proto.rs | 92 ++++- crates/voelin-stream/src/session.rs | 51 ++- crates/voelin-stream/tests/sessions.rs | 66 +++- crates/voelin-ui/src/streams.rs | 6 +- crates/voelin-ui/ui/app.slint | 6 +- docs/protocol-notes/ts6-streaming.md | 42 ++- docs/research/ts6-late-join.md | 224 ++++++++++++ scripts/it-smoke.sh | 24 ++ tools/voelinctl/src/stream.rs | 46 ++- 15 files changed, 977 insertions(+), 76 deletions(-) create mode 100644 crates/voelin-stream/src/discovery.rs create mode 100644 docs/research/ts6-late-join.md diff --git a/crates/proto/tsproto-structs/declarations/Messages.toml b/crates/proto/tsproto-structs/declarations/Messages.toml index fa21623..d9921b1 100644 --- a/crates/proto/tsproto-structs/declarations/Messages.toml +++ b/crates/proto/tsproto-structs/declarations/Messages.toml @@ -424,6 +424,7 @@ fields = [ { map="mode@stream", ts="mode", pretty="StreamMode", type="u8" }, { map="bitrate@stream", ts="bitrate", pretty="Bitrate", type="u32" }, { map="viewer_limit@stream", ts="viewer_limit", pretty="ViewerLimit", type="u32" }, + { map="viewer@stream", ts="viewer", pretty="Viewers", type="u32" }, { map="audio@stream", ts="audio", pretty="Audio", type="bool" }, { map="json@stream", ts="json", pretty="Json", type="str" }, { map="offer@stream", ts="offer", pretty="Offer", type="str" }, @@ -502,7 +503,13 @@ msg = [ # notifystreamstarted clid=20 id=e7da957e-7ce0-46cf-bf6d-754d3446b4d4 name=probe type=3 access=1 mode=1 bitrate=4608 viewer_limit=0 audio=1 { name="StreamStarted", notify="notifystreamstarted", attributes=["clid", "id@stream", "name@stream?", "type@stream?", "access@stream?", "mode@stream?", "bitrate@stream?", "viewer_limit@stream?", "audio@stream?", "return_code?"] }, { name="StreamStopped", notify="notifystreamstopped", attributes=["id@stream", "clid?", "reason@stream?"] }, - { name="StreamInfo", notify="notifystreaminfo", attributes=["id@stream", "clid?", "name@stream?", "type@stream?", "access@stream?", "mode@stream?", "bitrate@stream?", "viewer_limit@stream?", "audio@stream?"] }, + # The answer to requeststreaminfo, one part per stream of the client; no + # part but return_code when it has none (docs/research/ts6-late-join.md): + # notifystreaminfo return_code=1 clid=6 id=6b5158dd-22ba-4118-b20d-9196fe975ac7 name=probe type=3 accessibility=1 mode=1 viewer=0 bitrate=4608 viewer_limit=0 audio=1 + { name="StreamInfo", notify="notifystreaminfo", attributes=["id@stream?", "clid?", "name@stream?", "type@stream?", "accessibility@stream?", "mode@stream?", "viewer@stream?", "bitrate@stream?", "viewer_limit@stream?", "audio@stream?", "return_code?"] }, + # After updatestream, to the channel; only the changed fields: + # notifystreamupdated clid=6 id=6b5158dd-22ba-4118-b20d-9196fe975ac7 name=renamed bitrate=4000 + { name="StreamUpdated", notify="notifystreamupdated", attributes=["clid", "id@stream", "name@stream?", "type@stream?", "access@stream?", "mode@stream?", "bitrate@stream?", "viewer_limit@stream?", "audio@stream?", "return_code?"] }, { name="JoinStreamRequest", notify="notifyjoinstreamrequest", attributes=["id@stream", "clid", "msg?", "is_remove@stream?"] }, { name="RespondJoinStreamRequest", notify="notifyrespondjoinstreamrequest", attributes=["id@stream", "clid?", "msg?", "offer@stream?", "decision@stream?"] }, { name="StreamSignaling", notify="notifystreamsignaling", attributes=["id@stream", "clid", "json@stream"] }, @@ -1067,4 +1074,7 @@ msg = [ { name="RespondJoinStreamRequestRequest", notify="respondjoinstreamrequest", attributes=["id@stream", "clid", "msg?", "offer@stream?", "decision@stream"] }, # removeclientfromstream id= clid= reason=; all required { name="RemoveClientFromStream", notify="removeclientfromstream", attributes=["id@stream", "clid", "reason@stream"] }, + # requeststreaminfo clid=; clid is required, id is ignored + # -> {StreamInfo} (with the command's return_code), also for other channels + { name="RequestStreamInfo", notify="requeststreaminfo", attributes=["clid"] }, ] diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 69f5400..dcfd989 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -8,6 +8,7 @@ use tracing::debug; use tsclientlib::ClientId; use voelin_audio::AudioSettings; use voelin_model::{ChatMessage, ChatTarget, Presence}; +use voelin_stream::ClientState; use crate::audio::{self, AudioEvent, AudioHandle, AudioIn}; use crate::gateway::{self, GatewayCmd, GatewayEvent}; @@ -66,8 +67,9 @@ struct Session { streams: Option, stream_peer: PeerConfig, frames: broadcast::Sender, - /// `client_is_streaming` of the voice presence, as last told to the streams. - streaming_clients: BTreeMap>, + /// Channel and `client_is_streaming` of the voice presence, as last told + /// to the streams. + streaming_clients: BTreeMap, open_chats: HashSet, dedup: Dedup, sources_tx: mpsc::UnboundedSender, @@ -460,8 +462,11 @@ impl Session { } } if let Some(s) = &self.streams { - let clients: BTreeMap<_, _> = - p.clients.values().map(|c| (c.id, c.streaming)).collect(); + let clients: BTreeMap<_, _> = p + .clients + .values() + .map(|c| (c.id, ClientState { channel: c.channel, streaming: c.streaming })) + .collect(); if clients != self.streaming_clients { self.streaming_clients = clients.clone(); s.send(StreamInput::Clients(clients)); diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index 6cbdc1e..f1800b4 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -12,15 +12,15 @@ use std::sync::atomic::{AtomicBool, Ordering}; use tokio::sync::{broadcast, mpsc}; use tracing::debug; use tsclientlib::ClientId; +use voelin_stream::{ + ClientState, Output, Request, StreamEvent, StreamNotification, StreamerEvent, StreamerOptions, + Streams, WatchEvent, +}; pub use voelin_stream::{ Codec, EncodedFrame, EndReason, FrameSource, Frequency, LeaveReason, MediaFrame, MediaKind, MediaTime, PeerConfig, StreamInfo, StreamKind, StreamSetup, SyntheticSource, VideoCodec, ViewerInfo, ViewerState, }; -use voelin_stream::{ - Output, Request, StreamEvent, StreamNotification, StreamerEvent, StreamerOptions, Streams, - WatchEvent, -}; use crate::audio::{AudioHandle, AudioIn}; use crate::voice::VoiceCmd; @@ -135,8 +135,8 @@ pub(crate) enum StreamInput { Frame(EncodedFrame), Notification(StreamNotification), RequestFailed(Request, String), - /// Clients on the server with their `client_is_streaming`. - Clients(BTreeMap>), + /// Clients on the server: channel and `client_is_streaming`. + Clients(BTreeMap), /// The voice connection is gone. Shutdown(String), } @@ -165,7 +165,6 @@ impl StreamHandle { audio, tx: tx.clone(), sink: None, - clients: BTreeMap::new(), }; tokio::spawn(task.run(rx)); Self { tx } @@ -188,8 +187,6 @@ struct StreamTask { tx: mpsc::UnboundedSender, /// The sink of our live stream. sink: Option, - /// Clients on the server and their `client_is_streaming`. - clients: BTreeMap>, } impl StreamTask { @@ -250,19 +247,9 @@ impl StreamTask { Ok(()) } StreamInput::Clients(clients) => { - // Streams of clients that left or stopped streaming are gone. - // Only changes count: a snapshot may predate the streaming flag - // of a stream that was just announced. - for (client, streaming) in &clients { - let was = self.clients.get(client).copied().flatten(); - if let (Some(was), Some(now)) = (was, *streaming) - && was != now - { - self.streams.set_client_streaming(ClientId(*client), now); - } - } - self.streams.retain_streamers(|c| clients.contains_key(&c.0)); - self.clients = clients; + // Streams of clients that left, stopped streaming or are not + // in our channel are gone; unannounced ones are looked up. + self.streams.update_clients(clients); Ok(()) } StreamInput::Shutdown(_) => Ok(()), @@ -433,6 +420,7 @@ mod tests { Request::RemoveViewer { id, viewer, reason } => { both(StreamNotification::ViewerLeft { id, viewer, reason: Some(reason) }) } + Request::StreamInfo { .. } => Vec::new(), } } diff --git a/crates/voelin-core/tests/stream_live.rs b/crates/voelin-core/tests/stream_live.rs index 427c909..249d4e7 100644 --- a/crates/voelin-core/tests/stream_live.rs +++ b/crates/voelin-core/tests/stream_live.rs @@ -257,3 +257,107 @@ async fn ts3_has_no_streams() { engine.send(Command::CloseSession { session: 1 }); tokio::time::sleep(Duration::from_millis(500)).await; } + +/// A session that connects after a stream started finds it and watches it: +/// the server does not announce running streams to newcomers, the engine +/// looks them up (`requeststreaminfo`). +#[tokio::test(flavor = "multi_thread")] +async fn ts6_late_viewer_finds_running_stream() { + if !live() { + return; + } + let engine = Engine::start(); + let mut events = engine.subscribe(); + let mut frames = engine.subscribe_frames(); + let tag = std::process::id() % 10_000; + connect(&engine, &mut events, 1, "127.0.0.1:9988", &format!("e-early-{tag}")).await; + let setup = StreamSetup { name: format!("early {tag}"), ..Default::default() }; + engine.send(Command::StartStream { session: 1, setup, auto_accept: true }); + let (id, sink) = wait_for(&mut events, "stream live", |e| match e { + Event::StreamState { session: 1, state: StreamState::Live { id, sink } } => { + Some((id.clone(), sink.clone())) + } + Event::StreamState { session: 1, state: StreamState::Ended(reason) } => { + panic!("stream ended: {reason:?}") + } + _ => None, + }) + .await; + let feeder = tokio::spawn({ + let sink = sink.clone(); + async move { + let mut source = SyntheticSource::new(30, 3000, true); + let mut out = Vec::new(); + while sink.is_live() { + source.poll_frames(Instant::now(), &mut out); + for frame in out.drain(..) { + sink.send(frame); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + }); + + // The late viewer: connected, and the running stream in its list. + let mut options = VoiceOptions::new("127.0.0.1:9988", format!("e-late-{tag}")); + options.stream_peer = PeerConfig::loopback(); + engine.send(Command::ConnectVoice { session: 2, options: Box::new(options) }); + wait_both( + &mut events, + "late viewer connected, with the running stream", + |e| match e { + Event::State { session: 2, state } if state.voice == VoiceState::Connected => Some(()), + _ => None, + }, + |e| match e { + Event::StreamsChanged { session: 2, streams } if streams.iter().any(|s| s.id == id) => { + Some(()) + } + _ => None, + }, + ) + .await; + + engine.send(Command::WatchStream { session: 2, stream_id: id.clone() }); + wait_for(&mut events, "late viewer watching", |e| match e { + Event::WatchState { session: 2, stream_id, state: WatchState::Connected } + if *stream_id == id => + { + Some(()) + } + Event::WatchState { session: 2, state: WatchState::Ended(reason), .. } => { + panic!("watching ended: {reason:?}") + } + _ => None, + }) + .await; + let mut video = 0; + let _ = timeout(Duration::from_secs(10), async { + while video < 30 { + match frames.recv().await { + Ok(f) + if f.session == 2 && f.stream_id == id && f.frame.kind == MediaKind::Video => + { + video += 1; + } + Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {} + Err(_) => break, + } + } + }) + .await; + assert!(video >= 30, "late viewer got {video} video frames"); + + engine.send(Command::StopStream { session: 1 }); + wait_for(&mut events, "stream gone from the late viewer's list", |e| match e { + Event::StreamsChanged { session: 2, streams } if streams.iter().all(|s| s.id != id) => { + Some(()) + } + _ => None, + }) + .await; + feeder.await.unwrap(); + engine.send(Command::CloseSession { session: 1 }); + engine.send(Command::CloseSession { session: 2 }); + tokio::time::sleep(Duration::from_millis(500)).await; +} diff --git a/crates/voelin-stream/src/discovery.rs b/crates/voelin-stream/src/discovery.rs new file mode 100644 index 0000000..1feab33 --- /dev/null +++ b/crates/voelin-stream/src/discovery.rs @@ -0,0 +1,333 @@ +//! Finding streams the server did not announce to us. +//! +//! The server sends `notifystreamstarted` only to the clients that are in the +//! streamer's channel when the stream starts. A client that connects later, or +//! enters the channel later, only sees the streamer's `client_is_streaming=1`. +//! `requeststreaminfo clid=` answers with a `notifystreaminfo` part +//! per stream of that client, for any client on the server (see +//! `docs/research/ts6-late-join.md`). +//! +//! [`Discovery`] follows the clients on the server (their channel and +//! streaming flag, fed by [`Streams::update_clients`](crate::Streams::update_clients)), +//! keeps the [`StreamDirectory`] to the streams in our channel, and looks up +//! the streams of clients that stream in our channel but whose stream we were +//! not told: after connecting, after we or they change channels, and when a +//! streamer's announcement did not come. Where it looks them up is a +//! [`StreamLookup`]: the server ([`ServerLookup`]) now; another directory +//! (e.g. a gateway's) can be added with +//! [`Streams::add_lookup`](crate::Streams::add_lookup) and hands what it finds +//! to [`Streams::discovered`](crate::Streams::discovered). + +use std::collections::{BTreeMap, BTreeSet}; + +use tracing::debug; +use tsclientlib::ClientId; + +use crate::session::{Outbox, Request, StreamDirectory}; + +/// What discovery needs to know about a client on the server. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ClientState { + pub channel: u64, + /// `client_is_streaming`; `None` if the server did not say (TeamSpeak 3). + pub streaming: Option, +} + +/// A place to look up the streams of a client. +pub trait StreamLookup: Send { + /// Start looking up the streams of `streamer`; `false` if this source + /// cannot (then the next one is asked). The server's answer arrives as + /// `notifystreaminfo`; other sources report through + /// [`Streams::discovered`](crate::Streams::discovered). + fn lookup(&mut self, streamer: ClientId, out: &mut Outbox) -> bool; + + /// A request of this source failed on the server. + fn failed(&mut self, _request: &Request, _error: &str) {} +} + +/// Asks the server: `requeststreaminfo clid=`. +#[derive(Debug, Default)] +pub struct ServerLookup { + /// The server does not know the command (older TeamSpeak 6 versions). + unsupported: bool, +} + +impl StreamLookup for ServerLookup { + fn lookup(&mut self, streamer: ClientId, out: &mut Outbox) -> bool { + if self.unsupported { + return false; + } + out.request(Request::StreamInfo { streamer }); + true + } + + fn failed(&mut self, request: &Request, error: &str) { + // "command not found" (error 256): never ask again on this connection. + if error.contains("CommandNotFound") || error.contains("command not found") { + debug!(?request, "the server does not know requeststreaminfo"); + self.unsupported = true; + } + } +} + +/// See the [module docs](self). +pub struct Discovery { + own: ClientId, + /// The clients as of the last update; empty before the first. + clients: BTreeMap, + /// Streamers looked up since they (or we) last changed channel or + /// started streaming; asked again after such a change. + asked: BTreeSet, + lookups: Vec>, +} + +impl std::fmt::Debug for Discovery { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Discovery") + .field("own", &self.own) + .field("clients", &self.clients.len()) + .field("asked", &self.asked) + .field("lookups", &self.lookups.len()) + .finish() + } +} + +impl Discovery { + /// Discovery through the server. + pub fn new(own: ClientId) -> Self { + Self { + own, + clients: BTreeMap::new(), + asked: BTreeSet::new(), + lookups: vec![Box::new(ServerLookup::default())], + } + } + + /// Another place to look streams up, asked after the ones before. + pub fn add_lookup(&mut self, lookup: Box) { + self.lookups.push(lookup); + } + + /// Our channel, once the clients are known. + pub fn own_channel(&self) -> Option { + self.clients.get(&self.own.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 { + match self.own_channel() { + None => true, + Some(own) => self.clients.get(&streamer.0).is_some_and(|c| c.channel == own), + } + } + + /// The clients on the server changed (full list). Updates the streaming + /// flags in `directory`, drops the streams of clients that left or are + /// not in our channel, and looks up the streams we were not told. + /// Returns whether the directory's streams changed. + pub fn update( + &mut self, + clients: BTreeMap, + directory: &mut StreamDirectory, + out: &mut Outbox, + ) -> bool { + let old_channel = self.own_channel(); + let new_channel = clients.get(&self.own.0).map(|c| c.channel); + let mut changed = false; + // Streams announced to us but whose streamer went away or out of our channel. + let first = self.clients.is_empty(); + for (id, now) in &clients { + let was = self.clients.get(id); + match (was.and_then(|c| c.streaming), now.streaming) { + // Only changes count: a list may predate the streaming flag of + // a stream that was just announced. + (Some(was), Some(now)) if was != now => { + changed |= directory.set_streaming(ClientId(*id), now); + } + (None, Some(true)) => { + directory.set_streaming(ClientId(*id), true); + } + _ => {} + } + if was.is_none_or(|was| was.channel != now.channel || was.streaming != now.streaming) { + self.asked.remove(id); + } + } + if old_channel != new_channel { + self.asked.clear(); + } + self.asked.retain(|id| clients.contains_key(id)); + changed |= directory.retain_streamers(|c| { + clients.get(&c.0).is_some_and(|s| new_channel.is_none_or(|own| s.channel == own)) + }); + + // A client in our channel that just started streaming is announced + // by the server itself; look it up only if the announcement has not + // come by the next update. + let just_started = |id: &u16, now: &ClientState| { + let was = self.clients.get(id); + !first + && was.is_some_and(|was| { + was.streaming != Some(true) && Some(was.channel) == old_channel + }) && Some(now.channel) == new_channel + }; + let candidates: Vec = clients + .iter() + .filter(|(id, c)| { + **id != self.own.0 + && c.streaming == Some(true) + && new_channel.is_some_and(|own| c.channel == own) + && directory.by_streamer(ClientId(**id)).is_none() + && !self.asked.contains(id) + && !just_started(id, c) + }) + .map(|(id, _)| *id) + .collect(); + self.clients = clients; + for id in candidates { + let streamer = ClientId(id); + if self.lookups.iter_mut().any(|l| l.lookup(streamer, out)) { + debug!(streamer = id, "looking up an unannounced stream"); + self.asked.insert(id); + } + } + changed + } + + /// A request of a lookup failed on the server. + pub fn failed(&mut self, request: &Request, error: &str) { + for lookup in &mut self.lookups { + lookup.failed(request, error); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::session::Output; + use crate::{StreamInfo, StreamKind, StreamNotification}; + + const OWN: u16 = 1; + + fn clients(list: &[(u16, u64, bool)]) -> BTreeMap { + list.iter() + .map(|&(id, channel, streaming)| { + (id, ClientState { channel, streaming: Some(streaming) }) + }) + .collect() + } + + fn looked_up(out: &mut Outbox) -> Vec { + let mut ids = Vec::new(); + while let Some(o) = out.pop() { + match o { + Output::Request(Request::StreamInfo { streamer }) => ids.push(streamer.0), + other => panic!("unexpected {other:?}"), + } + } + ids + } + + fn started(id: &str, streamer: u16) -> StreamNotification { + StreamNotification::Started { + info: StreamInfo { + id: id.into(), + streamer: ClientId(streamer), + name: String::new(), + kind: StreamKind::Screen, + bitrate: 4608, + viewer_limit: 0, + audio: true, + }, + return_code: None, + } + } + + #[test] + fn looks_up_streams_that_were_not_announced() { + let mut d = Discovery::new(ClientId(OWN)); + let mut dir = StreamDirectory::default(); + let mut out = Outbox::default(); + + // Connected: 2 streams in our channel, 3 in another one. + d.update(clients(&[(OWN, 1, false), (2, 1, true), (3, 5, true)]), &mut dir, &mut out); + assert_eq!(looked_up(&mut out), [2]); + // Asked once, not again on the next update. + d.update( + clients(&[(OWN, 1, false), (2, 1, true), (3, 5, true), (4, 1, false)]), + &mut dir, + &mut out, + ); + assert_eq!(looked_up(&mut out), [] as [u16; 0]); + // The answer fills the directory. + assert!(dir.apply(&started("s-2", 2))); + + // We move to 3's channel: 3 is looked up, 2's stream leaves the list. + let moved = clients(&[(OWN, 5, false), (2, 1, true), (3, 5, true), (4, 1, false)]); + assert!(d.update(moved.clone(), &mut dir, &mut out)); + assert_eq!(looked_up(&mut out), [3]); + assert!(dir.get("s-2").is_none()); + assert!(d.in_our_channel(ClientId(3)) && !d.in_our_channel(ClientId(2))); + + // 4 comes to our channel and starts streaming there: announced by + // the server, so not looked up at once... + let mut now = moved.clone(); + now.insert(4, ClientState { channel: 5, streaming: Some(false) }); + d.update(now.clone(), &mut dir, &mut out); + now.insert(4, ClientState { channel: 5, streaming: Some(true) }); + d.update(now.clone(), &mut dir, &mut out); + assert_eq!(looked_up(&mut out), [] as [u16; 0]); + // ...only if the announcement has not come by the next update. + now.insert(9, ClientState { channel: 1, streaming: Some(false) }); + d.update(now.clone(), &mut dir, &mut out); + assert_eq!(looked_up(&mut out), [4]); + + // A streamer that stops loses its stream; one that left too. + assert!(dir.apply(&started("s-4", 4))); + now.insert(4, ClientState { channel: 5, streaming: Some(false) }); + assert!(d.update(now.clone(), &mut dir, &mut out)); + assert!(dir.get("s-4").is_none()); + assert!(dir.apply(&started("s-3", 3))); + now.remove(&3); + assert!(d.update(now, &mut dir, &mut out)); + assert_eq!(dir.iter().count(), 0); + } + + #[test] + fn a_server_without_the_command_is_not_asked_again() { + let mut d = Discovery::new(ClientId(OWN)); + let mut dir = StreamDirectory::default(); + let mut out = Outbox::default(); + d.update(clients(&[(OWN, 1, false), (2, 1, true)]), &mut dir, &mut out); + let request = Request::StreamInfo { streamer: ClientId(2) }; + assert_eq!(looked_up(&mut out), [2]); + d.failed(&request, "command failed: CommandNotFound"); + d.update(clients(&[(OWN, 1, false), (3, 1, true)]), &mut dir, &mut out); + assert_eq!(looked_up(&mut out), [] as [u16; 0]); + } + + /// A second source, e.g. a gateway's directory. + struct Recorder(std::sync::Arc>>); + + impl StreamLookup for Recorder { + fn lookup(&mut self, streamer: ClientId, _out: &mut Outbox) -> bool { + self.0.lock().unwrap().push(streamer.0); + true + } + } + + #[test] + fn other_lookups_follow_the_server() { + let mut d = Discovery::new(ClientId(OWN)); + let asked = std::sync::Arc::default(); + d.add_lookup(Box::new(Recorder(std::sync::Arc::clone(&asked)))); + let mut dir = StreamDirectory::default(); + let mut out = Outbox::default(); + d.failed(&Request::StreamInfo { streamer: ClientId(2) }, "command not found"); + d.update(clients(&[(OWN, 1, false), (2, 1, true)]), &mut dir, &mut out); + assert_eq!(looked_up(&mut out), [] as [u16; 0]); + assert_eq!(*asked.lock().unwrap(), [2]); + } +} diff --git a/crates/voelin-stream/src/lib.rs b/crates/voelin-stream/src/lib.rs index 9efdcc5..40b02a1 100644 --- a/crates/voelin-stream/src/lib.rs +++ b/crates/voelin-stream/src/lib.rs @@ -9,6 +9,7 @@ //! streams in our channel, our own stream with a peer per viewer, and the //! streams we watch. [`FrameSource`] is where a streamer's encoded frames come from. +pub mod discovery; pub mod layer; pub mod peer; pub mod proto; @@ -17,6 +18,7 @@ pub mod signal; pub mod source; pub mod stun; +pub use discovery::{ClientState, StreamLookup}; pub use layer::{LayerId, LayerSet, LayerSpec}; pub use peer::{MediaFrame, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec}; pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup}; diff --git a/crates/voelin-stream/src/proto.rs b/crates/voelin-stream/src/proto.rs index 1ac7d48..38ed4fe 100644 --- a/crates/voelin-stream/src/proto.rs +++ b/crates/voelin-stream/src/proto.rs @@ -126,7 +126,18 @@ pub enum StreamNotification { info: StreamInfo, return_code: Option, }, + /// A stream in our channel, or the answer to [`stream_info`]. Info(StreamInfo), + /// The streamer changed its stream (`updatestream`); only the changed fields. + Updated { + id: String, + streamer: ClientId, + name: Option, + kind: Option, + bitrate: Option, + viewer_limit: Option, + audio: Option, + }, Stopped { id: String, streamer: Option, @@ -183,11 +194,13 @@ impl StreamNotification { return_code: p.return_code.clone(), }) .collect(), + // The answer for a client without streams has no parts but + // `return_code`. InMessage::StreamInfo(m) => m .iter() .filter_map(|p| { Some(Self::Info(StreamInfo { - id: p.stream_id.clone(), + id: p.stream_id.clone().filter(|id| !id.is_empty())?, streamer: p.client_id?, name: p.stream_name.clone().unwrap_or_default(), kind: StreamKind::from_u8(p.stream_type.unwrap_or(3)), @@ -197,6 +210,18 @@ impl StreamNotification { })) }) .collect(), + InMessage::StreamUpdated(m) => m + .iter() + .map(|p| Self::Updated { + id: p.stream_id.clone(), + streamer: p.client_id, + name: p.stream_name.clone(), + kind: p.stream_type.map(StreamKind::from_u8), + bitrate: p.bitrate, + viewer_limit: p.viewer_limit, + audio: p.audio, + }) + .collect(), InMessage::StreamStopped(m) => m .iter() .map(|p| Self::Stopped { @@ -252,7 +277,8 @@ impl StreamNotification { pub fn stream_id(&self) -> &str { match self { Self::Started { info, .. } | Self::Info(info) => &info.id, - Self::Stopped { id, .. } + Self::Updated { id, .. } + | Self::Stopped { id, .. } | Self::JoinRequest { id, .. } | Self::JoinResponse { id, .. } | Self::Signaling { id, .. } @@ -320,6 +346,17 @@ pub fn signaling(id: &str, peer: ClientId, json: &str) -> OutCommand { )) } +/// `requeststreaminfo`: ask for the streams of `streamer`, also one in +/// another channel. The server answers with `notifystreaminfo` (one part per +/// stream; none if the client does not stream). This is how a client learns +/// about streams that started before it joined the server or the channel: +/// the server announces streams only to those in the channel when they start. +pub fn stream_info(streamer: ClientId) -> OutCommand { + c2s::OutRequestStreamInfoMessage::new(&mut iter::once(c2s::OutRequestStreamInfoPart { + client_id: streamer, + })) +} + /// `removeclientfromstream`: end a viewer's session (`reason` is usually /// [`LeaveReason::Kicked`]; the viewer gets `notifystreamclientleft` with it). pub fn remove_viewer(id: &str, viewer: ClientId, reason: LeaveReason) -> OutCommand { @@ -340,6 +377,56 @@ mod tests { String::from_utf8(cmd.0.content().to_vec()).unwrap() } + /// The stream notifications in a command as the server sends it. + fn parse(command: &str) -> Vec { + use tsproto_packets::packets::{Direction, Flags, InPacket, PacketType}; + let out = OutCommand::new(Direction::S2C, Flags::empty(), PacketType::Command, command); + let packet = InPacket::new(Direction::S2C, out.0.data()); + let msg = InMessage::new(packet.header(), packet.content()).unwrap(); + StreamNotification::from_message(&msg) + } + + #[test] + fn stream_info_answers() { + // As the server answered `requeststreaminfo` (6.0.0-beta13.1). + let answer = parse( + "notifystreaminfo return_code=0 clid=6 id=6b5158dd name=renamed\\sagain type=3 \ + accessibility=1 mode=1 viewer=0 bitrate=4000 viewer_limit=0 audio=1|clid=6 \ + id=069ba23c name=second type=3 accessibility=1 mode=1 viewer=2 bitrate=4608 \ + viewer_limit=0 audio=0", + ); + let infos: Vec<_> = answer + .iter() + .map(|n| match n { + StreamNotification::Info(i) => { + (i.id.as_str(), i.streamer, i.name.as_str(), i.audio) + } + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!( + infos, + [ + ("6b5158dd", ClientId(6), "renamed again", true), + ("069ba23c", ClientId(6), "second", false) + ] + ); + // A client without streams. + assert!(parse("notifystreaminfo return_code=1").is_empty()); + assert_eq!( + parse("notifystreamupdated clid=6 id=6b5158dd name=renamed bitrate=4000"), + [StreamNotification::Updated { + id: "6b5158dd".into(), + streamer: ClientId(6), + name: Some("renamed".into()), + kind: None, + bitrate: Some(4000), + viewer_limit: None, + audio: None, + }] + ); + } + #[test] fn commands() { let s = StreamSetup { name: "my screen".into(), ..Default::default() }; @@ -361,6 +448,7 @@ mod tests { text(remove_viewer("u-1", ClientId(7), LeaveReason::Kicked)), "removeclientfromstream id=u-1 clid=7 reason=5" ); + assert_eq!(text(stream_info(ClientId(6))), "requeststreaminfo clid=6"); let r = text(respond("u-1", ClientId(7), Some("v=0"), true)); assert!(r.starts_with("respondjoinstreamrequest id=u-1 clid=7"), "{r}"); assert!(r.contains("offer=v=0") && r.contains("decision=1"), "{r}"); diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index 378d04a..ae397b2 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -36,6 +36,7 @@ use tracing::{debug, warn}; use tsclientlib::ClientId; use tsproto_packets::packets::OutCommand; +use crate::discovery::{ClientState, Discovery, StreamLookup}; use crate::peer::{MediaFrame, Peer, PeerConfig, PeerEvent}; use crate::proto::{self, LeaveReason, StreamInfo, StreamNotification, StreamSetup}; use crate::signal::Signal; @@ -65,6 +66,8 @@ pub enum Request { Signal { id: String, peer: ClientId, signal: Signal }, /// `removeclientfromstream` RemoveViewer { id: String, viewer: ClientId, reason: LeaveReason }, + /// `requeststreaminfo`: the streams of a client (see [`crate::discovery`]). + StreamInfo { streamer: ClientId }, } impl Request { @@ -81,6 +84,7 @@ impl Request { } Self::Signal { id, peer, signal } => proto::signaling(id, *peer, &signal.to_json()), Self::RemoveViewer { id, viewer, reason } => proto::remove_viewer(id, *viewer, *reason), + Self::StreamInfo { streamer } => proto::stream_info(*streamer), } } } @@ -227,6 +231,18 @@ impl StreamDirectory { self.streaming.insert(info.streamer.0); self.streams.insert(info.id.clone(), info.clone()).as_ref() != Some(info) } + StreamNotification::Updated { + id, name, kind, bitrate, viewer_limit, audio, .. + } => { + let Some(info) = self.streams.get_mut(id) else { return false }; + let before = info.clone(); + info.name = name.clone().unwrap_or(before.name.clone()); + info.kind = kind.unwrap_or(before.kind); + info.bitrate = bitrate.unwrap_or(before.bitrate); + info.viewer_limit = viewer_limit.unwrap_or(before.viewer_limit); + info.audio = audio.unwrap_or(before.audio); + *info != before + } StreamNotification::Stopped { id, .. } => self.streams.remove(id).is_some(), _ => false, } @@ -870,6 +886,7 @@ pub struct Streams { own: ClientId, config: PeerConfig, directory: StreamDirectory, + discovery: Discovery, streamer: Option, viewers: BTreeMap, out: Outbox, @@ -882,6 +899,7 @@ impl Streams { own, config, directory: StreamDirectory::default(), + discovery: Discovery::new(own), streamer: None, viewers: BTreeMap::new(), out: Outbox::default(), @@ -1021,7 +1039,10 @@ impl Streams { /// Feed a stream notification from the connection. pub async fn handle_notification(&mut self, n: StreamNotification) { - if self.directory.apply(&n) { + // Looked up streams of clients that have left our channel since. + let elsewhere = matches!(&n, StreamNotification::Info(info) + if !self.discovery.in_our_channel(info.streamer)); + if !elsewhere && self.directory.apply(&n) { self.emit_streams(); } if let Some(s) = &mut self.streamer @@ -1051,12 +1072,40 @@ impl Streams { } } + /// The clients on the server changed (full list, with ourselves): keeps + /// the directory to the streams in our channel and looks up the streams + /// the server did not announce to us (see [`crate::discovery`]). Covers + /// [`Self::set_client_streaming`] and [`Self::retain_streamers`]. + pub fn update_clients(&mut self, clients: BTreeMap) { + if self.discovery.update(clients, &mut self.directory, &mut self.out) { + self.emit_streams(); + } + } + + /// A stream found by another [`StreamLookup`] (e.g. a gateway's directory). + pub fn discovered(&mut self, info: StreamInfo) { + if self.discovery.in_our_channel(info.streamer) + && self.directory.apply(&StreamNotification::Info(info)) + { + self.emit_streams(); + } + } + + /// Another place to look up unannounced streams, after the server. + pub fn add_lookup(&mut self, lookup: Box) { + self.discovery.add_lookup(lookup); + } + /// A request from [`Output::Request`] failed on the server. pub fn request_failed(&mut self, request: &Request, error: &str) { let watched = match request { Request::Join { id, .. } | Request::Leave { id, .. } | Request::Signal { id, .. } => { self.viewers.get_mut(id) } + Request::StreamInfo { .. } => { + self.discovery.failed(request, error); + return; + } _ => None, }; if let Some(v) = watched { diff --git a/crates/voelin-stream/tests/sessions.rs b/crates/voelin-stream/tests/sessions.rs index 31d910c..2c11cfb 100644 --- a/crates/voelin-stream/tests/sessions.rs +++ b/crates/voelin-stream/tests/sessions.rs @@ -2,15 +2,15 @@ //! commands like the TeamSpeak 6 server does (see //! `docs/protocol-notes/ts6-streaming.md`), with real peers on loopback. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::time::{Duration, Instant}; use tokio::time::timeout; use tsclientlib::ClientId; use voelin_stream::{ - EndReason, FrameSource, LeaveReason, MediaKind, Output, PeerConfig, Request, StreamEvent, - StreamInfo, StreamKind, StreamNotification, StreamSetup, StreamerEvent, StreamerOptions, - Streams, SyntheticSource, ViewerState, WatchEvent, + ClientState, EndReason, FrameSource, LeaveReason, MediaKind, Output, PeerConfig, Request, + StreamEvent, StreamInfo, StreamKind, StreamNotification, StreamSetup, StreamerEvent, + StreamerOptions, Streams, SyntheticSource, ViewerState, WatchEvent, }; const STREAMER: usize = 0; @@ -20,8 +20,11 @@ const IDS: [ClientId; 2] = [ClientId(5), ClientId(6)]; /// Relays requests to notifications, as observed on a TS6 server. #[derive(Default)] struct FakeServer { - streams: HashMap, + streams: HashMap, next: u32, + /// A client that is not in the channel yet: streams that start are not + /// announced to it. + absent: Option, } impl FakeServer { @@ -32,7 +35,6 @@ impl FakeServer { Request::Setup(setup) => { self.next += 1; let id = format!("stream-{}", self.next); - self.streams.insert(id.clone(), from); let info = StreamInfo { id, streamer: from, @@ -42,7 +44,9 @@ impl FakeServer { viewer_limit: setup.viewer_limit, audio: setup.audio, }; + self.streams.insert(info.id.clone(), info.clone()); (0..2) + .filter(|i| self.absent != Some(*i)) .map(|i| { let own = IDS[i] == from; let return_code = own.then(|| "1".to_owned()); @@ -86,6 +90,12 @@ impl FakeServer { everyone(StreamNotification::ViewerLeft { id, viewer, reason: Some(reason) }) .collect() } + Request::StreamInfo { streamer } => self + .streams + .values() + .filter(|s| s.streamer == streamer) + .map(|s| (to(from), StreamNotification::Info(s.clone()))) + .collect(), } } } @@ -280,3 +290,47 @@ async fn stream_between_sessions() { .await; assert!(net.clients[STREAMER].streamer().is_none()); } + +/// The viewer arrives after the stream started: the server did not announce +/// it, the viewer looks it up (`requeststreaminfo`) and watches. +#[tokio::test(flavor = "multi_thread")] +async fn late_viewer_finds_the_stream() { + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut net = Net::new(); + net.server.absent = Some(VIEWER); + let setup = StreamSetup { name: "early".into(), ..Default::default() }; + net.clients[STREAMER] + .start(StreamerOptions { setup, auto_accept: true, ..Default::default() }) + .unwrap(); + net.until("live", |i, e| { + i == STREAMER && matches!(e, StreamEvent::Streamer(StreamerEvent::Live { .. })) + }) + .await; + net.flush().await; + assert!(net.clients[VIEWER].directory().iter().next().is_none(), "not announced"); + + // The viewer's first client list: the streamer streams in its channel. + net.server.absent = None; + let clients: BTreeMap = IDS + .iter() + .map(|c| (c.0, ClientState { channel: 1, streaming: Some(c == &IDS[STREAMER]) })) + .collect(); + net.clients[VIEWER].update_clients(clients); + net.until("looked up stream in the viewer's list", |i, e| { + i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.len() == 1) + }) + .await; + let id = net.clients[VIEWER].directory().by_streamer(IDS[STREAMER]).unwrap().id.clone(); + net.clients[VIEWER].watch(&id, "").unwrap(); + net.until("viewer connected", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.source = Some(SyntheticSource::new(30, 4000, true)); + net.frames(10).await; + net.clients[STREAMER].stop().unwrap(); + net.until("stream gone", |i, e| { + i == VIEWER && matches!(e, StreamEvent::Streams(l) if l.is_empty()) + }) + .await; +} diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index bfc8d1d..7ec3c97 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -174,8 +174,10 @@ impl App { own: view.state.own_client == Some(s.streamer.0), }); } - // Streams that started before we joined are only known by the - // streaming flag: the server does not tell their ids. + // Streams that started before we joined: the server did not + // announce them, and the engine is looking them up (they arrive + // in `StreamsChanged` like the others). Until then only the + // streaming flag is known. let channel = view.state.own_channel; for c in view.presence.clients.values() { let announced = view.streams.iter().any(|s| s.streamer.0 == c.id); diff --git a/crates/voelin-ui/ui/app.slint b/crates/voelin-ui/ui/app.slint index a3afb12..4721b04 100644 --- a/crates/voelin-ui/ui/app.slint +++ b/crates/voelin-ui/ui/app.slint @@ -57,8 +57,8 @@ export struct BookmarkForm { query-password: string, } -// A stream in our channel. An empty id: a client that streams, but the -// server did not announce the stream to us (it started before we joined). +// A stream in our channel. An empty id: a client that streams, but whose +// stream is still being looked up (it started before we joined). export struct StreamItem { id: string, name: string, @@ -566,7 +566,7 @@ component StreamsPanel inherits Rectangle { overflow: elide; } Text { - text: stream.id == "" ? @tr("Started before you joined; the server did not announce it.") : stream.own ? @tr("your stream") : stream.audio ? @tr("by {} · with sound", stream.streamer) : @tr("by {}", stream.streamer); + text: stream.id == "" ? @tr("Started before you joined; looking it up…") : stream.own ? @tr("your stream") : stream.audio ? @tr("by {} · with sound", stream.streamer) : @tr("by {}", stream.streamer); font-size: 11px; color: #8b949e; overflow: elide; diff --git a/docs/protocol-notes/ts6-streaming.md b/docs/protocol-notes/ts6-streaming.md index 8a253a6..b5683fa 100644 --- a/docs/protocol-notes/ts6-streaming.md +++ b/docs/protocol-notes/ts6-streaming.md @@ -167,24 +167,33 @@ property for the planned SFU mode. Errors: `setupstream` refused with error 2568 ("insufficient client permissions") has been seen; no stream permission names are documented. -More text commands and notifications named in the server binary (not probed -yet): `requeststreaminfo` (its protobuf request only has `stream_id`, so it -cannot discover the ids of unknown streams), `updatestream` (`stream_id`, -`stream_name`, `max_width`, `max_height`, `max_framerate`, `properties`), -`notifystreamupdated`, `notifystreamattendees` (`return_code`, `client_id`). +More text commands and notifications named in the server binary: +`requeststreaminfo`, `updatestream` and `notifystreamupdated` (probed, see +below), and `notifystreamattendees` (`return_code`, `client_id`; never seen). +The protobuf `RequestStreamInfoRequest` only has `stream_id`, but the text +command takes `clid` instead. ### Streams that started before we joined (confirmed, 6.0.0-beta13.1, 2026-09-26) `initserver` and `notifycliententerview` carry `client_is_streaming`, but no -stream id, and the server does not send `notifystreamstarted` for running -streams to a client that connects later: a `voelinctl stream list` started while -the desktop app streamed printed only "id not announced", while one connected -before the stream started got the id. Entering the channel later was not -probed separately. `voelinctl stream list` shows such streamers as "id not -announced"; `voelinctl stream watch --id ` can still join when the streamer -is known (`--streamer-nick`, or the only other client streaming). The desktop -app lists them as streaming but not watchable. The smoke test starts the -viewer first. How the official client learns these ids is open. +stream id. The server sends `notifystreamstarted` only to the clients in the +streamer's channel when the stream starts. A client that connects later, or +enters the channel later, gets nothing about running streams. + +`requeststreaminfo clid=` fills the gap. It answers with +`notifystreaminfo` (the command's `return_code`, then one part per stream of +the client: `clid id name type accessibility mode viewer bitrate viewer_limit +audio`), from any channel. For a client without streams, or an unknown +client, the answer has no stream parts. + +`updatestream id= [name type access mode bitrate viewer_limit audio]` +notifies the channel with `notifystreamupdated clid id `. It +sends nothing when nothing changed. + +Full transcript, all the variants tried, and what Voelin does with them: +[docs/research/ts6-late-join.md](../research/ts6-late-join.md). Voelin +looks up unannounced streams in its channel with `requeststreaminfo` +(`voelin_stream::discovery`). ### WebRTC interop with Chromium (confirmed, Chromium 141, 2026-09-26) @@ -216,9 +225,10 @@ libwebrtc, the stack the official client is built on: - [x] Parameters of `stopstream` and `removeclientfromstream` (`reason` is required). - [ ] Which permission gates `setupstream` (error 2568). - [x] Contents of `notifystreamstarted` (see probe results). -- [ ] Contents of `notifystreaminfo` (`requeststreaminfo id=`). +- [x] Contents of `notifystreaminfo` (`requeststreaminfo clid=`, see above). - [x] Whether a client that connects later is told about running streams: no (see above). -- [ ] How the official client finds running streams after connecting. +- [x] How a client finds running streams after connecting: `requeststreaminfo` + (presumably what the official client does too; not captured from it). - [ ] Interop with the official TS6 client (its offer/answer details, codecs it actually picks, whether it trickles candidates, mDNS host candidates). Chromium's WebRTC stack interoperates (see above). diff --git a/docs/research/ts6-late-join.md b/docs/research/ts6-late-join.md new file mode 100644 index 0000000..483d62e --- /dev/null +++ b/docs/research/ts6-late-join.md @@ -0,0 +1,224 @@ +# TeamSpeak 6: streams that started before we arrived + +**Question.** The server sends `notifystreamstarted` only to the clients that +are in the streamer's channel when a stream starts. A client that connects +later, or enters the channel later, sees only the streamer's +`client_is_streaming=1`. How can it learn the stream id, so that it can send +`joinstreamrequest`? + +**Answer.** `requeststreaminfo clid=` works. The server answers with +`notifystreaminfo`: one part per stream of that client, each with the stream +id and the stream's properties. This works from any channel and needs no +permission beyond a guest's. Voelin uses it (see "What Voelin does" below). + +Server: `teamspeaksystems/teamspeak6-server` 6.0.0-beta13.1 [Build: 1790080330], +default permissions, dev/docker-compose.yml. Probed on 2026-09-26 with +`voelinctl probe-stream` (`tools/voelinctl/src/probe.rs`). + +## How the probe works + +``` +voelinctl probe-stream 127.0.0.1:9988 --streamer-identity dev/.state/ts6-admin.json +``` + +1. Client A creates a channel (`channelcreate`), which moves it there, and + starts a stream with `setupstream` (signalling only, no media). +2. Client B connects to the default channel and tries candidate commands. +3. B moves into A's channel and tries them again. Extra commands can be given + with `--try ''`; `{id}`, `{a}`, `{b}` and `{cid}` are replaced + by the stream id, the two client ids and A's channel. +4. B sends `joinstreamrequest` with the id it learned. +5. A sends `updatestream` in several spellings, `requeststreaminfo` for + itself, and a second `setupstream`. +6. A puts the stream id into its `client_meta_data`. B reconnects straight + into A's channel and tries again. +7. A clears `client_meta_data` and stops the stream. + +The probe hooks into the raw connection (tsclientlib's `unstable` API) and +prints every command both clients send and receive. It prints them unparsed, +so notifications the vendored declarations did not know yet +(`notifystreamupdated`) show up too. + +## What the server answered + +Stream id below: `6b5158dd-22ba-4118-b20d-9196fe975ac7`. A is clid 6, B is +clid 7 (8 after reconnecting). `return_code` values are left out. + +### (a) Entering the streamer's channel + +``` +B -> clientmove cid=3 clid=7 +B <- notifycliententerview cfid=0 ctid=3 reasonid=2 clid=6 ... client_meta_data client_is_recording=0 client_is_streaming=1 ... +B <- notifyclientmoved cfid=1 ctid=3 reasonid=0 clid=7 +B <- error id=0 msg=ok +``` + +No `notifystreamstarted` and no `notifystreaminfo`. B only gets the +streaming flag. The same happens when B connects straight into A's channel +(step 6): its `notifycliententerview` for A carries `client_is_streaming=1` +and nothing else about the stream. + +### (b) `requeststreaminfo` + +| Command sent by B | Answer | +|---|---| +| `requeststreaminfo id=` | `error id=1542 msg=missing required parameter` | +| `requeststreaminfo id= clid=6` | `notifystreaminfo clid=6 id= name=late\sjoin\sprobe type=3 accessibility=1 mode=1 viewer=0 bitrate=4608 viewer_limit=0 audio=1`, then ok | +| `requeststreaminfo clid=6` | the same `notifystreaminfo` | +| `requeststreaminfo stream_id=` | 1542 | +| `requeststreaminfo stream_id= clid=6`, `streamid= clid=6`, `id= clid=6 msg` | the same `notifystreaminfo` (only `clid` matters) | +| `requeststreaminfo clid=6 id=00000000-0000-0000-0000-000000000000` | the same `notifystreaminfo` with the real id: `id` is ignored | +| `requeststreaminfo cid=3`, `requeststreaminfo` | 1542 | +| `requeststreaminfo clid=` | `notifystreaminfo return_code=...` with no stream fields, then ok | +| `requeststreaminfo clid=9999` (no such client) | `notifystreaminfo return_code=...` with no stream fields, then ok (no error) | +| `requeststreaminfo clid=9\|clid=10` | answered for the first part only | + +- `clid` is the only required parameter. The notification carries the + command's `return_code`. +- It works the same from the default channel (A's stream in another channel) + and from A's channel. +- A client with two streams (A sent a second `setupstream` in step 5) gets + both streams in one answer, as two parts: + + ``` + notifystreaminfo return_code=0 clid=6 id=6b5158dd-... name=renamed\sagain type=3 accessibility=1 mode=1 viewer=0 bitrate=4000 viewer_limit=0 audio=1|clid=6 id=069ba23c-b71a-4002-9c97-a91d5ab4428b name=second type=3 accessibility=1 mode=1 viewer=0 bitrate=4608 viewer_limit=0 audio=1 + ``` + +- The field names differ from `notifystreamstarted`: `accessibility` (not + `access`), and `viewer`, the current number of viewers. Both match the + `StreamInfoEvent` protobuf message embedded in the server. +- A second `setupstream` while a stream runs is accepted. It creates a + second stream with a new id, and the channel gets `notifystreamstarted` + for it. + +### (c) `clientgetvariables clid=6` + +- From the default channel, without `channelsubscribeall`, the answer is + `error id=512 msg=invalid clientID`: A is not visible to B. +- In A's channel the answer is `notifyclientupdated clid=6 client_version=... + client_platform=... client_created=... client_totalconnections=... ...`. + It has nothing about streams. + +### (d) `clientinfo clid=6` + +The answer has `client_is_streaming=1` among the usual properties, and no +stream id. + +### (e) Other command names + +`requeststreamattendees id=`, `streamattendees id=`, `streamlist`, +`liststreams`, `requeststreams` and `requeststreamlist` all fail with +`error id=256 msg=command not found`. The server binary names no other +stream command in text form: `setupstream`, `stopstream`, `updatestream`, +`requeststreaminfo`, `joinstreamrequest`, `respondjoinstreamrequest`, +`streamsignaling` and `removeclientfromstream` are all of them. +`notifystreamattendees` (protobuf `StreamAttendeesEvent`: `return_code`, +`client_id`) never appeared. + +### (f) `updatestream` by the streamer + +| Command sent by A | Answer | +|---|---| +| `updatestream id= name=renamed\sprobe` | ok; **B** (in the channel) and A get `notifystreamupdated clid=6 id= name=renamed\sprobe` | +| `updatestream id=` | ok, no notification | +| `updatestream stream_id= name=...` | 1542 (`id` is required) | +| `updatestream id= name=renamed\sprobe type=3 bitrate=4608 accessibility=1 mode=1 viewer_limit=0 audio=1` | ok, no notification (nothing changed) | +| `updatestream id= name=renamed\sagain type=3 access=1 mode=1 bitrate=4000 viewer_limit=0 audio=1` | ok; `notifystreamupdated clid=6 id= name=renamed\sagain bitrate=4000` | + +`notifystreamupdated` carries only the fields that changed, and goes only to +the clients in the channel. It re-announces nothing to clients that do not +know the stream: with no change it sends nothing at all. So it is no way +to tell latecomers about a stream. + +### Joining with a learned id + +`joinstreamrequest id= clid=6 msg=probe is_remove=0` from B, with the id +learned through `requeststreaminfo`, reaches A as +`notifyjoinstreamrequest clid=7 id= msg=probe is_remove=0`. `is_remove=1` +is relayed too. B's reconnect in step 6 gave the same result. The full +join with media works (see "Verification" below). + +The server does not limit join requests to the streamer's channel. In a +later run (2026-09-27, same server), B stayed in the default channel, sent +`channelsubscribeall`, looked the stream up and asked to join: + +``` +B -> requeststreaminfo clid=2 +B <- notifystreaminfo clid=2 id=e977003a-... name=late\sjoin\sprobe type=3 accessibility=1 mode=1 viewer=0 bitrate=4608 viewer_limit=0 audio=1 +B -> joinstreamrequest id=e977003a-... clid=2 msg=probe is_remove=0 +A <- notifyjoinstreamrequest clid=3 id=e977003a-... msg=probe is_remove=0 +``` + +So a stream is "channel scoped" only in whom the server announces it to. A +streamer that wants to admit only its channel has to check where the viewer +is. Voelin's `stream.permissions = channel` does that. + +### `client_meta_data` as a side channel + +`clientupdate client_meta_data=voelin-stream=` is accepted from a guest. +The channel gets `notifyclientupdated clid=6 client_meta_data=voelin-stream=`, +and a client that arrives later finds the value in its `notifycliententerview` +for A. So metadata would work as a fallback between Voelin clients, but +`requeststreaminfo` makes it unnecessary. + +### Stopping + +`stopstream id= reason=1`: B, in the channel, gets +`notifystreamstopped clid=6 id= reason=1`. + +## What Voelin does + +- `voelin_stream::proto::stream_info` sends `requeststreaminfo clid=`. + The declarations (`crates/proto/tsproto-structs/declarations/Messages.toml`) + now know the answer's fields (`accessibility`, `viewer`, `return_code`, an + optional `id` for the empty answer) and `notifystreamupdated`. +- `voelin_stream::discovery::Discovery` follows the clients on the server: + their channel and `client_is_streaming`. It keeps the stream directory to + the streams in our own channel. It looks up a client that streams in our + channel and whose stream we were not told: + - after connecting; + - after we or the streamer change channels; + - when a streamer in our channel starts and its `notifystreamstarted` + has not arrived by the next update of the client list. + + Each streamer is looked up once per change of its channel or flag. The + answer arrives as `notifystreaminfo` and fills the directory like an + announcement, so `Event::StreamsChanged` lists the stream and it can be + watched like any other. +- Where to look is a `StreamLookup` trait. `ServerLookup` (`requeststreaminfo`) + is the only lookup now. It stops asking on a connection whose server answers + "command not found". A later source, such as a gateway's stream directory, + plugs in with `Streams::add_lookup`, and hands what it finds to + `Streams::discovered`. +- `notifystreamupdated` updates the directory (name, bitrate, …). +- The engine (`voelin-core`) and `voelinctl stream list/watch` feed the + client list into `Streams::update_clients`. + +Fallbacks (i) and (ii) from the plan were not built, because the native +command works. (i) would have been a re-announcement by the streamer; (ii) +would have put the stream id into `client_meta_data`. The probe shows what +they would do: (i) does not work through `updatestream`, and (ii) would work +between Voelin clients. + +### Limits + +- Streams of official clients are found the same way, since this is a + server command: nothing on the streamer's side is needed. +- Only clients we can see are looked up. That is always true of our own + channel, which is the only place streams are listed. +- Not probed: streams with `accessibility` other than 1 (public), and + whether a server permission can hide streams from `requeststreaminfo`. + +## Verification + +- `voelinctl connect 127.0.0.1:9988 --nick early stream --loopback start --synthetic --auto-accept`, + then, once it is live, `voelinctl connect 127.0.0.1:9988 stream --loopback watch --streamer-nick early --expect-frames 30`: + the late viewer printed `watching of early`, connected and decoded 30 + pictures. +- `scripts/it-smoke.sh`, step "stream (late viewer)", does the same. +- `crates/voelin-core/tests/stream_live.rs` `ts6_late_viewer_finds_running_stream` + (`VOELIN_LIVE=1`): an engine session connects after the stream is live, + gets it in `Event::StreamsChanged`, watches it and receives frames. +- `crates/voelin-stream/tests/sessions.rs` `late_viewer_finds_the_stream` + runs the same flow through a fake server, and `discovery.rs` has unit tests + for when lookups happen. diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index 1971110..1b1624d 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -12,6 +12,8 @@ # 7. gateway (tsgw): login with a TeamSpeak identity, presence, channel chat # both ways, refusal of an identity the server does not know # 8. stream (TeamSpeak 6 only): a viewer watches a synthetic VP8 + Opus stream +# 9. late stream (TeamSpeak 6 only): a viewer that connects after the stream +# started finds it (requeststreaminfo) and watches it # # Usage: scripts/it-smoke.sh [ts3|ts6]... (default: both) # Env: VOELINCTL=path/to/voelinctl (default: builds target/debug/voelinctl) @@ -130,6 +132,27 @@ stream_check() { grep -E "first video frame|received" "$out" } +# TeamSpeak 6: the stream is live before the viewer connects. The server does +# not announce running streams to newcomers; the viewer looks it up. +stream_late_check() { + local addr=$1 out="$STATE_DIR/stream-late-watch.log" streamer_out="$STATE_DIR/stream-late-start.log" + local streamer="early-$$-$RANDOM" + "$VOELINCTL" connect "$addr" --nick "$streamer" stream --loopback start --synthetic \ + --auto-accept --seconds 30 >"$streamer_out" 2>&1 & + local streamer_pid=$! + for _ in $(seq 1 60); do grep -q "is live" "$streamer_out" 2>/dev/null && break; sleep 0.25; done + grep -q "is live" "$streamer_out" || { cat "$streamer_out"; fail "late-join streamer did not go live"; } + if ! "$VOELINCTL" connect "$addr" --nick "late-$$" stream --loopback watch --streamer-nick "$streamer" \ + --expect-frames 60 --timeout 25 >"$out" 2>&1; then + cat "$out" "$streamer_out" + fail "late viewer did not receive the running stream" + fi + # SIGINT: the streamer stops its stream properly. + kill -INT "$streamer_pid" 2>/dev/null || true + wait "$streamer_pid" 2>/dev/null || true + grep -E "watching|received" "$out" +} + # An observer over ServerQuery must see a voice client join. presence_check() { local addr=$1 query=$2 out="$STATE_DIR/observe.log" @@ -237,6 +260,7 @@ for svc in "${SERVERS[@]}"; do gateway_check "$svc" "$addr" if [[ $svc == ts6 ]]; then stream_check "$addr" + stream_late_check "$addr" fi done diff --git a/tools/voelinctl/src/stream.rs b/tools/voelinctl/src/stream.rs index a931df6..be30ec3 100644 --- a/tools/voelinctl/src/stream.rs +++ b/tools/voelinctl/src/stream.rs @@ -11,7 +11,6 @@ use clap::{Args, Subcommand}; use futures::prelude::*; use tokio::io::{AsyncBufReadExt, BufReader, Lines, Stdin}; use tokio::time::{Instant, Interval, sleep_until}; -use tsclientlib::events::{Event, PropertyId}; use tsclientlib::prelude::*; use tsclientlib::{ClientId, Connection, MessageHandle, StreamItem}; use voelin_core::media::voelin_media::capture::SourceId; @@ -22,8 +21,9 @@ use voelin_core::media::{ }; use voelin_model::ServerFlavor; use voelin_stream::{ - EndReason, FrameSource, MediaKind, Output, PeerConfig, Request, StreamEvent, StreamInfo, - StreamNotification, StreamSetup, StreamerEvent, StreamerOptions, Streams, WatchEvent, + ClientState, EndReason, FrameSource, MediaKind, Output, PeerConfig, Request, StreamEvent, + StreamInfo, StreamNotification, StreamSetup, StreamerEvent, StreamerOptions, Streams, + WatchEvent, }; #[derive(Args, Debug, Clone)] @@ -123,6 +123,7 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> { let config = peer_config(&codecs, config); let codec = stream_codec(&codecs, &config); let mut driver = Driver { streams: Streams::new(own, config), pending: HashMap::new() }; + driver.sync_clients(con)?; let result = match &args.command { StreamCommand::Start { name, @@ -279,24 +280,26 @@ impl Driver { self.streams.request_failed(&request, &e.to_string()); } } - StreamItem::BookEvents(events) => { - let state = con.get_state()?; - for e in &events { - if let Event::PropertyChanged { - id: PropertyId::ClientIsStreaming(clid), .. - } = e && let Some(streaming) = - state.clients.get(clid).and_then(|c| c.is_streaming) - { - self.streams.set_client_streaming(*clid, streaming); - } - } - self.streams.retain_streamers(|c| state.clients.contains_key(&c)); - } + StreamItem::BookEvents(_) => self.sync_clients(con)?, _ => {} } Ok(()) } + /// Tell the sessions the clients on the server: streams of clients that + /// left, stopped or are not in our channel are dropped; streams that + /// started before we came are looked up. + fn sync_clients(&mut self, con: &Connection) -> Result<()> { + let state = con.get_state()?; + let clients = state + .clients + .values() + .map(|c| (c.id.0, ClientState { channel: c.channel.0, streaming: c.is_streaming })) + .collect(); + self.streams.update_clients(clients); + Ok(()) + } + /// Send the sessions' requests; returns their events. fn flush(&mut self, con: &mut Connection) -> Result> { let mut events = Vec::new(); @@ -472,12 +475,17 @@ async fn list(con: &mut Connection, driver: &mut Driver, settle: Duration) -> Re if s.audio { ", audio" } else { "" } ); } - // Streams that started before we connected are only known by the flag. + // Streamers in our channel known only by the flag: the lookup failed or + // did not answer in time. let state = con.get_state()?; + let channel = state.clients.get(&state.own_client).map(|c| c.channel); let mut unannounced = 0; for c in state.clients.values() { - if c.is_streaming == Some(true) && !streams.iter().any(|s| s.streamer == c.id) { - println!("? {} (clid {}) is streaming; id not announced to us", c.name, c.id.0); + if c.is_streaming == Some(true) + && Some(c.channel) == channel + && !streams.iter().any(|s| s.streamer == c.id) + { + println!("? {} (clid {}) is streaming; id not known", c.name, c.id.0); unannounced += 1; } } From 5b2c4808a51d51ba689e9331455a53d25e190a35 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 03:56:56 +0000 Subject: [PATCH 3/5] voelin-store: cached statements, batched and raw settings writes The settings service keeps every value in memory and writes changes from its own thread, several at a time. The store gets what that needs: all settings as JSON text, deleting one, and writing a batch in one transaction. Statements go through rusqlite's prepared statement cache, and with WAL the database uses synchronous=NORMAL, so a write does not wait for an fsync (WAL keeps the database consistent; a power loss may lose the last transactions). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- crates/voelin-store/src/store.rs | 68 ++++++++++++++++++++++++++++---- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index 10a6c17..ea216ca 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -155,7 +155,11 @@ impl Store { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; } + // WAL: readers do not block the writer (the settings service writes + // from its own connection). NORMAL is durable with WAL except for + // the last transactions on a power loss, and avoids an fsync per write. db.pragma_update(None, "journal_mode", "WAL")?; + db.pragma_update(None, "synchronous", "NORMAL")?; Self::init(db) } @@ -164,6 +168,8 @@ impl Store { } fn init(db: Connection) -> Result { + // Statements run through `prepare_cached` are parsed once per connection. + db.set_prepared_statement_cache_capacity(64); db.pragma_update(None, "foreign_keys", true)?; let version: i64 = db.pragma_query_value(None, "user_version", |r| r.get(0))?; for (i, migration) in MIGRATIONS.iter().enumerate().skip(version as usize) { @@ -267,17 +273,60 @@ impl Store { pub fn setting(&self, key: &str) -> Result> { let value: Option = self .db - .query_row("SELECT value FROM settings WHERE key = ?1", [key], |r| r.get(0)) + .prepare_cached("SELECT value FROM settings WHERE key = ?1")? + .query_row([key], |r| r.get(0)) .optional()?; value.map(|v| serde_json::from_str(&v).map_err(Error::from)).transpose() } pub fn set_setting(&self, key: &str, value: &T) -> Result<()> { - self.db.execute( - "INSERT INTO settings (key, value) VALUES (?1, ?2) - ON CONFLICT (key) DO UPDATE SET value = excluded.value", - params![key, serde_json::to_string(value)?], - )?; + self.set_setting_json(key, &serde_json::to_string(value)?) + } + + /// Store a setting that is already JSON text. + pub fn set_setting_json(&self, key: &str, json: &str) -> Result<()> { + self.db + .prepare_cached( + "INSERT INTO settings (key, value) VALUES (?1, ?2) + ON CONFLICT (key) DO UPDATE SET value = excluded.value", + )? + .execute(params![key, json])?; + Ok(()) + } + + /// Remove a setting; `true` if it was there. + pub fn delete_setting(&self, key: &str) -> Result { + Ok(self.db.prepare_cached("DELETE FROM settings WHERE key = ?1")?.execute([key])? > 0) + } + + /// All settings as `(key, JSON text)`, ordered by key. + pub fn settings_json(&self) -> Result> { + let mut stmt = self.db.prepare_cached("SELECT key, value FROM settings ORDER BY key")?; + let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?; + Ok(rows.collect::>()?) + } + + /// Store (`Some(JSON text)`) or remove (`None`) several settings in one + /// transaction. + pub fn write_settings<'a>( + &mut self, + changes: impl IntoIterator)>, + ) -> Result<()> { + let tx = self.db.transaction()?; + { + let mut put = tx.prepare_cached( + "INSERT INTO settings (key, value) VALUES (?1, ?2) + ON CONFLICT (key) DO UPDATE SET value = excluded.value", + )?; + let mut delete = tx.prepare_cached("DELETE FROM settings WHERE key = ?1")?; + for (key, json) in changes { + match json { + Some(json) => put.execute(params![key, json])?, + None => delete.execute([key])?, + }; + } + } + tx.commit()?; Ok(()) } @@ -396,11 +445,16 @@ mod tests { #[test] fn settings() { - let store = Store::open_in_memory().unwrap(); + let mut store = Store::open_in_memory().unwrap(); assert_eq!(store.setting::("volume").unwrap(), None); store.set_setting("volume", &80u32).unwrap(); store.set_setting("volume", &90u32).unwrap(); assert_eq!(store.setting::("volume").unwrap(), Some(90)); + store.write_settings([("a", Some("1")), ("volume", None), ("b", Some("\"x\""))]).unwrap(); + let all = store.settings_json().unwrap(); + assert_eq!(all, [("a".to_owned(), "1".to_owned()), ("b".to_owned(), "\"x\"".to_owned())]); + assert!(store.delete_setting("a").unwrap()); + assert!(!store.delete_setting("a").unwrap()); } #[test] From f69ab4d3586ef551f2234ba74d7053300f09f0de Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 03:56:56 +0000 Subject: [PATCH 4/5] 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()) From 9a0c08c22df776dec901e795637f83bd81072e07 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 08:33:20 +0000 Subject: [PATCH 5/5] 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 |