Merge late-join stream discovery and the settings service

Conflicts with the SRTP/BWE/simulcast work were in the engine's command
loop, session and stream tasks (both sides kept: SRTP order and layers
next to settings and discovery) and in the voelin-stream exports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-27 08:58:21 +00:00
commit 6538734a6e
30 files changed
+3419 -123

No files matched your search

+118 -5
View File
@@ -17,6 +17,12 @@
//! of watched streams plays through the session's speakers by itself
//! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video
//! are in [`media`] (feature `media`).
//!
//! Settings are a [`settings::Settings`] service: typed keys, runtime
//! values stored in the client database ahead of command line, config file
//! and defaults. The engine reads its own keys from it (e.g. who may watch
//! our stream), takes [`Command::SetSetting`] / [`Command::ResetSetting`],
//! and reports every change as [`Event::SettingChanged`].
mod audio;
mod gateway;
@@ -25,6 +31,7 @@ pub mod media;
mod query;
mod route;
mod session;
pub mod settings;
pub mod stream;
mod voice;
@@ -38,6 +45,7 @@ use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, S
use crate::audio::{AudioEvent, AudioHandle, AudioIn};
pub use route::{ChatRoute, Dedup, route_chat};
use settings::{SettingChange, Settings, SharedSettings};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
use voelin_stream::{
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
@@ -191,6 +199,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)]
@@ -318,6 +340,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.
@@ -327,17 +359,31 @@ pub struct Engine {
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
runtime: tokio::runtime::Handle,
settings: SharedSettings,
}
impl Engine {
/// Start the engine on the current tokio runtime.
/// Start the engine on the current tokio runtime, with settings that are
/// not stored (see [`Command::AttachSettings`]).
pub fn start() -> Self {
Self::start_with_settings(Settings::in_memory())
}
/// Start the engine on the current tokio runtime with `settings`.
pub fn start_with_settings(settings: Settings) -> Self {
let (commands, rx) = mpsc::unbounded_channel();
let (events, _) = broadcast::channel(4096);
// About a minute of one watched stream.
let (frames, _) = broadcast::channel(4096);
tokio::spawn(run(rx, events.clone(), frames.clone()));
Self { commands, events, frames, runtime: tokio::runtime::Handle::current() }
let settings = SharedSettings::new(settings);
tokio::spawn(run(rx, events.clone(), frames.clone(), settings.clone()));
Self { commands, events, frames, runtime: tokio::runtime::Handle::current(), settings }
}
/// The settings the engine uses (read, watch or change them directly;
/// changes are reported as [`Event::SettingChanged`] all the same).
pub fn settings(&self) -> Settings {
self.settings.current()
}
/// The runtime the engine runs on, for helpers started from other
@@ -360,16 +406,61 @@ impl Engine {
}
}
/// What woke the engine's loop.
enum Input {
Command(Command),
Setting(SettingChange),
/// Changes were missed: the engine re-reads what it uses.
SettingsLagged,
}
/// A command that applies the stored audio settings if they differ from
/// what runs (e.g. set through [`Command::SetSetting`]).
fn stored_audio(settings: &Settings, running: &AudioSettings) -> Option<Command> {
let stored = settings.get_arc(&settings::AUDIO);
(*stored != *running).then(|| Command::SetAudioSettings(Box::new((*stored).clone())))
}
async fn run(
mut commands: mpsc::UnboundedReceiver<Command>,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
shared: SharedSettings,
) {
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let mut current = shared.current();
let mut changes = current.subscribe();
let mut settings = AudioSettings::default();
let mut srtp_profiles: Option<Vec<SrtpProfile>> = None;
let mut mic_test: Option<AudioHandle> = None;
while let Some(command) = commands.recv().await {
loop {
let input = tokio::select! {
command = commands.recv() => match command {
Some(command) => Input::Command(command),
None => break,
},
change = changes.recv() => match change {
Ok(change) => Input::Setting(change),
Err(broadcast::error::RecvError::Lagged(_)) => Input::SettingsLagged,
// Not while `current` holds the settings.
Err(broadcast::error::RecvError::Closed) => continue,
},
};
let command = match input {
Input::Command(command) => command,
Input::Setting(change) => {
let audio = change.key == settings::AUDIO.name();
let _ = events.send(Event::SettingChanged { key: change.key });
match audio.then(|| stored_audio(&current, &settings)).flatten() {
Some(command) => command,
None => continue,
}
}
Input::SettingsLagged => match stored_audio(&current, &settings) {
Some(command) => command,
None => continue,
},
};
let id = match command {
Command::SetAudioSettings(new) => {
settings = (*new).clone();
@@ -392,6 +483,24 @@ async fn run(
srtp_profiles = Some(profiles);
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 { .. }) {
@@ -408,6 +517,7 @@ async fn run(
events.clone(),
frames.clone(),
settings.clone(),
shared.clone(),
);
if let Some(profiles) = &srtp_profiles {
s.send(Command::SetSrtpProfiles(profiles.clone()));
@@ -467,7 +577,10 @@ fn command_session(command: &Command) -> SessionId {
| Command::CloseSession { session } => *session,
Command::SetAudioSettings(_)
| Command::SetSrtpProfiles(_)
| Command::TestMicrophone { .. } => {
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
| Command::ResetSetting { .. }
| Command::AttachSettings(_) => {
unreachable!("engine-wide commands have no session")
}
}
+22 -6
View File
@@ -8,11 +8,13 @@ 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};
use crate::query::{self, QueryCmd, QueryEvent};
use crate::route::{ChatRoute, Dedup, route_chat};
use crate::settings::SharedSettings;
use crate::stream::{LayerSpec, PeerConfig, SrtpProfile, StreamFrame, StreamHandle, StreamInput};
use crate::voice::{self, VoiceCmd, VoiceEvent};
use crate::{Command, Event, ObserveState, SessionId, SessionState, Source, VoiceState};
@@ -27,9 +29,10 @@ impl SessionHandle {
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
settings: SharedSettings,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(Session::new(id, events, frames, audio_settings).run(rx));
tokio::spawn(Session::new(id, events, frames, audio_settings, settings).run(rx));
Self { tx }
}
@@ -62,6 +65,7 @@ struct Session {
query_presence: Option<Presence>,
audio: Option<AudioHandle>,
audio_settings: AudioSettings,
settings: SharedSettings,
/// Streams of the voice connection (TeamSpeak 6 only).
streams: Option<StreamHandle>,
stream_peer: PeerConfig,
@@ -71,8 +75,9 @@ struct Session {
/// options' `stream_peer`.
srtp_profiles: Option<Vec<SrtpProfile>>,
frames: broadcast::Sender<StreamFrame>,
/// `client_is_streaming` of the voice presence, as last told to the streams.
streaming_clients: BTreeMap<u16, Option<bool>>,
/// Channel and `client_is_streaming` of the voice presence, as last told
/// to the streams.
streaming_clients: BTreeMap<u16, ClientState>,
open_chats: HashSet<ChatTarget>,
dedup: Dedup,
sources_tx: mpsc::UnboundedSender<SourceEvent>,
@@ -85,6 +90,7 @@ impl Session {
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
settings: SharedSettings,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
Self {
@@ -101,6 +107,7 @@ impl Session {
query_presence: None,
audio: None,
audio_settings,
settings,
streams: None,
stream_peer: PeerConfig::default(),
stream_layers: Vec::new(),
@@ -341,7 +348,12 @@ impl Session {
s.send(StreamInput::SrtpProfiles(profiles));
}
}
Command::CloseSession { .. } | Command::TestMicrophone { .. } => {}
// Engine-wide.
Command::CloseSession { .. }
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
| Command::ResetSetting { .. }
| Command::AttachSettings(_) => {}
}
}
@@ -471,6 +483,7 @@ impl Session {
self.events.clone(),
self.frames.clone(),
self.audio.clone(),
self.settings.clone(),
);
if !self.stream_layers.is_empty() {
streams.send(StreamInput::Layers(self.stream_layers.clone()));
@@ -488,8 +501,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));
File diff suppressed because it is too large. Load diff
+115 -23
View File
@@ -12,17 +12,18 @@ use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::{broadcast, mpsc};
use tracing::debug;
use tsclientlib::ClientId;
use voelin_stream::{
ClientState, LayerFeedback, Output, Request, StreamEvent, StreamNotification, StreamerEvent,
StreamerOptions, Streams, WatchEvent,
};
pub use voelin_stream::{
Codec, EncodedFrame, EndReason, FrameSource, Frequency, LayerId, LayerSet, LayerSpec,
LeaveReason, MediaFrame, MediaKind, MediaTime, PeerConfig, SrtpProfile, StreamInfo, StreamKind,
StreamSetup, SyntheticSource, VideoCodec, ViewerInfo, ViewerState,
};
use voelin_stream::{
LayerFeedback, Output, Request, StreamEvent, StreamNotification, StreamerEvent,
StreamerOptions, Streams, WatchEvent,
};
use crate::audio::{AudioHandle, AudioIn};
use crate::settings::{STREAM_PERMISSIONS, SharedSettings, StreamPermissions};
use crate::voice::VoiceCmd;
use crate::{Event, SessionId};
@@ -142,8 +143,8 @@ pub(crate) enum StreamInput {
Frame(EncodedFrame),
Notification(StreamNotification),
RequestFailed(Request, String),
/// Clients on the server with their `client_is_streaming`.
Clients(BTreeMap<u16, Option<bool>>),
/// Clients on the server: channel and `client_is_streaming`.
Clients(BTreeMap<u16, ClientState>),
/// The voice connection is gone.
Shutdown(String),
}
@@ -153,6 +154,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,
@@ -161,6 +163,7 @@ impl StreamHandle {
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio: Option<AudioHandle>,
settings: SharedSettings,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
let task = StreamTask {
@@ -172,8 +175,8 @@ impl StreamHandle {
audio,
tx: tx.clone(),
sink: None,
clients: BTreeMap::new(),
layers: Vec::new(),
settings,
};
tokio::spawn(task.run(rx));
Self { tx }
@@ -196,10 +199,10 @@ struct StreamTask {
tx: mpsc::UnboundedSender<StreamInput>,
/// The sink of our live stream.
sink: Option<StreamSink>,
/// Clients on the server and their `client_is_streaming`.
clients: BTreeMap<u16, Option<bool>>,
/// Simulcast layers of our stream (empty: one layer).
layers: Vec<LayerSpec>,
/// `stream.permissions` decides join requests.
settings: SharedSettings,
}
impl StreamTask {
@@ -274,19 +277,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(()),
@@ -326,7 +319,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 });
@@ -371,6 +380,21 @@ impl StreamTask {
}
}
/// The answer `stream.permissions` gives to a join request; `None`: ask.
fn join_decision(&self, viewer: ClientId) -> Option<bool> {
match *self.settings.current().get_arc(&STREAM_PERMISSIONS) {
StreamPermissions::Everyone => Some(true),
StreamPermissions::Nobody => Some(false),
// No contacts yet: ask for everyone.
StreamPermissions::Friends => None,
StreamPermissions::Channel => {
let discovery = self.streams.discovery();
let own = discovery.own_channel();
Some(own.is_some() && discovery.channel_of(viewer) == own)
}
}
}
/// The connection is gone: report our stream and watched streams as ended.
fn shutdown(&mut self, reason: String) {
let session = self.session;
@@ -402,6 +426,7 @@ mod tests {
use voelin_stream::{FrameSource, SyntheticSource};
use super::*;
use crate::settings::Settings;
const CLIENTS: [u16; 2] = [5, 6];
@@ -462,6 +487,7 @@ mod tests {
Request::RemoveViewer { id, viewer, reason } => {
both(StreamNotification::ViewerLeft { id, viewer, reason: Some(reason) })
}
Request::StreamInfo { .. } => Vec::new(),
}
}
@@ -486,6 +512,14 @@ mod tests {
/// server; `audio` is the viewer's audio thread.
fn pair(
audio: Option<AudioHandle>,
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
pair_with(audio, &Settings::in_memory())
}
/// [`pair`] with `settings` for both tasks.
fn pair_with(
audio: Option<AudioHandle>,
settings: &Settings,
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
let (events, rx) = broadcast::channel(4096);
let (frames, frames_rx) = broadcast::channel(4096);
@@ -504,6 +538,7 @@ mod tests {
events.clone(),
frames.clone(),
if session == 2 { audio.take() } else { None },
SharedSettings::new(settings.clone()),
));
voices.push(voice_rx);
}
@@ -701,6 +736,63 @@ mod tests {
feeder.await.unwrap();
}
/// `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.