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; } }