From 5592a3ce1afa7f886285726d66b299841cdd7f0c Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 22:01:10 +0300 Subject: [PATCH 1/2] Find and watch streams in every channel, without a gateway MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The server announces a stream only to the clients in the streamer's channel. Voelin looked up streams that started before it joined (`requeststreaminfo`), but only in its own channel, so a stream anywhere else on the server appeared only through a gateway's directory. The official client lists and joins them without one: `requeststreaminfo` answers from any channel, and a `joinstreamrequest` from another channel reaches the streamer (confirmed on the TS6 dev server with the probe). - Discovery follows every streaming client on the server: it looks up the streams of clients in other channels as soon as they stream, keeps them when we or they change channels, and drops them when the streamer stops or leaves. - The streams panel lists every channel's streams, ours first, the others with their channel ("by X · in Gaming"); clients still being looked up show in any channel. The viewer's note names the stream's channel instead of claiming it can only be watched from there. - As a streamer with `stream.permissions = channel` (the default), our channel is let in and viewers from other channels are asked, as the setting's description ("who may watch without being asked") says; they were refused before. Tested: discovery unit tests for the new rules; the engine's permission test; the app headless (no gateway) on the TS6 dev server found and played a stream in another channel and one that started before it joined; scripts/it-smoke.sh gains a step where a viewer in the default channel watches a stream in another channel. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-core/src/settings.rs | 3 +- crates/voelin-core/src/stream.rs | 25 ++++---- crates/voelin-stream/src/discovery.rs | 73 ++++++++++++++--------- crates/voelin-stream/src/session.rs | 15 ++--- crates/voelin-ui/src/app.rs | 13 ++++ crates/voelin-ui/src/streams.rs | 28 +++++---- crates/voelin-ui/ui/bridge.slint | 9 ++- crates/voelin-ui/ui/screens/streams.slint | 16 +++-- docs/research/ts6-late-join.md | 18 +++++- scripts/it-smoke.sh | 29 ++++++++- 10 files changed, 162 insertions(+), 67 deletions(-) diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index c246dbd..eb2b7ba 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1048,7 +1048,8 @@ pub enum StreamPermissions { /// Friends (contacts marked friend) are accepted; others are shown to /// the user ([`crate::Event::StreamViewerRequest`]). Friends, - /// Clients in our channel are accepted, others denied. + /// Clients in our channel are accepted; others (a stream can be watched + /// from any channel) are shown to the user. #[default] Channel, /// Every join request is denied. diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index 6060d99..018bda3 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -4,13 +4,16 @@ //! The voice task forwards stream notifications here and sends the resulting //! commands. Only started for TeamSpeak 6 servers. //! -//! Streams that started before we joined are looked up on the server -//! (`requeststreaminfo`) and in the session's gateway directory: its -//! registered entries (stream id and streamer) are handed to the stream -//! sessions ([`voelin_stream::Streams::discovered`]) for streamers in our -//! channel, and a [`StreamLookup`] answers for the gateway when the server -//! cannot. Our own stream's life (live, viewers, ended) goes back to the -//! session ([`OwnStreamEvent`]), which keeps its directory entry. +//! The streams of the whole server are listed, in every channel: a stream can +//! be watched from any channel, as with the official client. Streams that +//! started before we joined, and streams in other channels (the server +//! announces a stream only in its channel), are looked up on the server +//! (`requeststreaminfo`), so no gateway is needed. A gateway's directory is a +//! second source: its registered entries (stream id and streamer) are handed +//! to the stream sessions ([`voelin_stream::Streams::discovered`]), and a +//! [`StreamLookup`] answers for the gateway when the server cannot. Our own +//! stream's life (live, viewers, ended) goes back to the session +//! ([`OwnStreamEvent`]), which keeps its directory entry. use std::collections::{BTreeMap, BTreeSet}; use std::fmt; @@ -554,10 +557,11 @@ impl StreamTask { StreamPermissions::Nobody => Some(false), // Friends are let in; others: ask. StreamPermissions::Friends => self.friends.contains(&viewer.0).then_some(true), + // Our channel is let in; viewers from other channels: ask. StreamPermissions::Channel => { let discovery = self.streams.discovery(); let own = discovery.own_channel(); - Some(own.is_some() && discovery.channel_of(viewer) == own) + (own.is_some() && discovery.channel_of(viewer) == own).then_some(true) } } } @@ -1016,7 +1020,8 @@ mod tests { assert_eq!(parse_kind("game"), StreamKind::Screen); } - /// `stream.permissions` answers join requests (`friends`: friends only, others are asked). + /// `stream.permissions` answers join requests (`friends` and `channel`: + /// those are let in, others are asked). #[tokio::test(flavor = "multi_thread")] async fn permissions_answer_join_requests() { let in_channels = |streamer: u64, viewer: u64| { @@ -1028,7 +1033,7 @@ mod tests { for (permissions, viewer_channel, friend, expected) in [ (StreamPermissions::Everyone, 2, false, Some(true)), (StreamPermissions::Channel, 1, false, Some(true)), - (StreamPermissions::Channel, 2, false, Some(false)), + (StreamPermissions::Channel, 2, false, None), (StreamPermissions::Nobody, 1, false, Some(false)), (StreamPermissions::Friends, 1, false, None), (StreamPermissions::Friends, 2, true, Some(true)), diff --git a/crates/voelin-stream/src/discovery.rs b/crates/voelin-stream/src/discovery.rs index beacbfe..75d3329 100644 --- a/crates/voelin-stream/src/discovery.rs +++ b/crates/voelin-stream/src/discovery.rs @@ -7,12 +7,17 @@ //! per stream of that client, for any client on the server (see //! `docs/research/ts6-late-join.md`). //! +//! The answer works from any channel, and so does `joinstreamrequest`: a +//! client can watch a stream in another channel, as the official client does. +//! //! [`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 +//! keeps the [`StreamDirectory`] to the streams of clients that are on the +//! server and stream, in any channel, and looks up the streams of clients +//! that stream but whose stream we were not told: after connecting, when a +//! client in another channel starts streaming (the server announces it only +//! in that channel), after we or they change channels, and when a streamer's +//! announcement in our channel 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 @@ -118,19 +123,16 @@ impl Discovery { 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 { - match self.own_channel() { - None => true, - Some(own) => self.clients.get(&streamer.0).is_some_and(|c| c.channel == own), - } + /// Whether a stream of `streamer` belongs in the directory: the client is + /// on the server (or the clients are not known yet). + pub fn knows(&self, streamer: ClientId) -> bool { + self.clients.is_empty() || self.clients.contains_key(&streamer.0) } /// 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. + /// flags in `directory`, drops the streams of clients that left, and + /// looks up the streams we were not told, in every channel. Returns + /// whether the directory's streams changed. pub fn update( &mut self, clients: BTreeMap, @@ -140,7 +142,7 @@ impl Discovery { 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. + // Streams announced to us but whose streamer stopped or went away. let first = self.clients.is_empty(); for (id, now) in &clients { let was = self.clients.get(id); @@ -163,9 +165,7 @@ impl Discovery { 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)) - }); + changed |= directory.retain_streamers(|c| clients.contains_key(&c.0)); // A client in our channel that just started streaming is announced // by the server itself; look it up only if the announcement has not @@ -177,12 +177,13 @@ impl Discovery { was.streaming != Some(true) && Some(was.channel) == old_channel }) && Some(now.channel) == new_channel }; + // Once we are on the server ourselves: every 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) + && new_channel.is_some() && directory.by_streamer(ClientId(**id)).is_none() && !self.asked.contains(id) && !just_started(id, c) @@ -256,9 +257,10 @@ mod tests { let mut dir = StreamDirectory::default(); let mut out = Outbox::default(); - // Connected: 2 streams in our channel, 3 in another one. + // Connected: 2 streams in our channel, 3 in another one; both are + // looked up (a stream can be watched from any channel). d.update(clients(&[(OWN, 1, false), (2, 1, true), (3, 5, true)]), &mut dir, &mut out); - assert_eq!(looked_up(&mut out), [2]); + assert_eq!(looked_up(&mut out), [2, 3]); // Asked once, not again on the next update. d.update( clients(&[(OWN, 1, false), (2, 1, true), (3, 5, true), (4, 1, false)]), @@ -266,15 +268,28 @@ mod tests { &mut out, ); assert_eq!(looked_up(&mut out), [] as [u16; 0]); - // The answer fills the directory. + // The answers fill the directory. assert!(dir.apply(&started("s-2", 2))); + assert!(dir.apply(&started("s-3", 3))); - // We move to 3's channel: 3 is looked up, 2's stream leaves the list. + // We move to 3's channel: both streams stay, nothing is asked again. 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))); + assert!(!d.update(moved.clone(), &mut dir, &mut out)); + assert_eq!(looked_up(&mut out), [] as [u16; 0]); + assert!(dir.get("s-2").is_some() && dir.get("s-3").is_some()); + assert!(d.knows(ClientId(2)) && !d.knows(ClientId(7))); + assert_eq!((d.channel_of(ClientId(2)), d.own_channel()), (Some(1), Some(5))); + + // A client in another channel starts streaming: the server does not + // announce it to us, so it is looked up at once. + let mut now = moved.clone(); + now.insert(6, ClientState { channel: 1, streaming: Some(false) }); + d.update(now.clone(), &mut dir, &mut out); + now.insert(6, ClientState { channel: 1, streaming: Some(true) }); + d.update(now.clone(), &mut dir, &mut out); + assert_eq!(looked_up(&mut out), [6]); + now.remove(&6); + d.update(now, &mut dir, &mut out); // 4 comes to our channel and starts streaming there: announced by // the server, so not looked up at once... @@ -294,8 +309,10 @@ mod tests { 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.clone(), &mut dir, &mut out)); + assert!(dir.get("s-3").is_none()); + now.insert(2, ClientState { channel: 1, streaming: Some(false) }); assert!(d.update(now, &mut dir, &mut out)); assert_eq!(dir.iter().count(), 0); } diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index c4b03af..5a58e47 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -1672,10 +1672,10 @@ impl Streams { /// Feed a stream notification from the connection. pub async fn handle_notification(&mut self, n: StreamNotification) { - // 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) { + // Looked up streams of clients that have left the server since. + let gone = matches!(&n, StreamNotification::Info(info) + if !self.discovery.knows(info.streamer)); + if !gone && self.directory.apply(&n) { self.emit_streams(); } if let Some(s) = &mut self.streamer @@ -1706,8 +1706,9 @@ 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 + /// the directory to the streams of clients that are on the server and + /// stream, in any 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) { @@ -1717,7 +1718,7 @@ impl 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) + if self.discovery.knows(info.streamer) && self.directory.apply(&StreamNotification::Info(info)) { self.emit_streams(); diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index fc42ae1..113f858 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -248,6 +248,19 @@ impl SessionView { self.capabilities.streams && self.state.voice == VoiceState::Connected } + /// The channel a client is in. + pub fn channel_of(&self, client: u16) -> Option { + self.presence.clients.get(&client).map(|c| c.channel) + } + + /// The name of a client's channel when it is not ours; empty in ours. + pub fn other_channel_name(&self, client: u16) -> String { + self.channel_of(client) + .filter(|c| Some(*c) != self.state.own_channel) + .and_then(|c| self.presence.channels.get(&c)) + .map_or_else(String::new, |c| c.name.clone()) + } + /// A client's nickname, or its id. pub fn nickname(&self, client: u16) -> String { self.presence diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index 84640a5..7cecbf2 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -215,7 +215,12 @@ impl App { let current = self.current; let mut items: Vec = Vec::new(); if let Some(view) = view.filter(|v| v.streams_available()) { - for s in &view.streams { + // Every channel's streams (they can be watched from anywhere), + // ours first. + let own_channel = view.state.own_channel; + let mut streams: Vec<_> = view.streams.iter().collect(); + streams.sort_by_key(|s| view.channel_of(s.streamer.0) != own_channel); + for s in streams { let watching = self .watch .as_ref() @@ -224,6 +229,7 @@ impl App { id: s.id.clone().into(), name: s.name.clone().into(), streamer: view.nickname(s.streamer.0).into(), + channel: view.other_channel_name(s.streamer.0).into(), streamer_id: i32::from(s.streamer.0), viewers: view.stream_viewers.get(&s.id).map_or(0, |v| *v as i32), audio: s.audio, @@ -239,20 +245,17 @@ impl App { bitrate: bitrate_text(s.bitrate).into(), }); } - // 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; + // Streams that started before we joined, or in another channel: + // 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. for c in view.presence.clients.values() { let announced = view.streams.iter().any(|s| s.streamer.0 == c.id); - if c.streaming == Some(true) - && Some(c.channel) == channel - && !announced && view.state.own_client != Some(c.id) - { + if c.streaming == Some(true) && !announced && view.state.own_client != Some(c.id) { items.push(StreamItem { name: c.nickname.clone().into(), streamer: c.nickname.clone().into(), + channel: view.other_channel_name(c.id).into(), streamer_id: i32::from(c.id), ..StreamItem::default() }); @@ -346,6 +349,11 @@ impl App { .and_then(|v| v.streams.iter().find(|s| s.id == watch.stream_id)) .map_or(-1, |s| i32::from(s.streamer.0)); bridge.set_viewer_streamer_id(streamer); + let channel = u16::try_from(streamer).ok().and_then(|id| { + let view = self.view()?; + view.presence.channels.get(&view.channel_of(id)?).map(|c| c.name.clone()) + }); + bridge.set_viewer_channel(channel.unwrap_or_default().into()); bridge.set_viewer_elapsed(watch.elapsed().into()); let viewers = self.view().and_then(|v| v.stream_viewers.get(&watch.stream_id)).copied(); bridge.set_viewer_count(viewers.unwrap_or(0) as i32); diff --git a/crates/voelin-ui/ui/bridge.slint b/crates/voelin-ui/ui/bridge.slint index 08db46d..df004e5 100644 --- a/crates/voelin-ui/ui/bridge.slint +++ b/crates/voelin-ui/ui/bridge.slint @@ -217,12 +217,15 @@ export struct BookmarkForm { query-password: string, } -// 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). +// A stream on the server, ours first: a stream can be watched from any +// channel. An empty id: a client that streams, but whose stream is still +// being looked up (it started before we joined, or in another channel). export struct StreamItem { id: string, name: string, streamer: string, + // The streamer's channel when it is not ours; empty in ours. + channel: string, // The streamer's client id (their avatar in the members). streamer-id: int, // How many watch it (the gateway's directory; 0 unknown). @@ -384,6 +387,8 @@ export global Bridge { in property viewer-title; // Who streams it (their client id: -1 unknown). in property viewer-streamer; + // The voice channel the watched stream is in. + in property viewer-channel; in property viewer-streamer-id: -1; // Shown instead of (or over) the picture: waiting, ended, errors. in property viewer-status; diff --git a/crates/voelin-ui/ui/screens/streams.slint b/crates/voelin-ui/ui/screens/streams.slint index 799274c..c1adc42 100644 --- a/crates/voelin-ui/ui/screens/streams.slint +++ b/crates/voelin-ui/ui/screens/streams.slint @@ -50,7 +50,10 @@ component StreamCard inherits Rectangle { overflow: elide; } Text { - 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); + text: stream.id == "" ? (stream.channel == "" ? @tr("Started before you joined; looking it up…") : @tr("In {}; looking it up…", stream.channel)) + : stream.own ? @tr("your stream") + : stream.channel != "" ? @tr("by {} · in {}", stream.streamer, stream.channel) + : stream.audio ? @tr("by {} · with sound", stream.streamer) : @tr("by {}", stream.streamer); color: Theme.text-muted; font-size: Theme.font-sm; overflow: elide; @@ -150,7 +153,7 @@ export component StreamsPanel inherits VerticalLayout { } } if Bridge.streams.length == 0: Text { - text: @tr("No streams in your channel."); + text: @tr("No streams on this server."); color: Theme.text-muted; font-size: Theme.font-sm; } @@ -425,7 +428,7 @@ component StreamInfo inherits VerticalLayout { } // The stream we watch. With the shell: the channel's header, the player, -// a note that the stream belongs to the channel, and its chat below. In +// a note on the channel the stream belongs to, and its chat below. In // full screen and on a phone: the player alone. export component StreamViewer inherits Rectangle { // Reading our own width here would loop through the layout, so the @@ -465,8 +468,9 @@ export component StreamViewer inherits Rectangle { padding-bottom: Theme.space-3; StreamPlayer { } } - // Streams on TeamSpeak belong to the channel. - if Bridge.own-channel != "": HorizontalLayout { + // Streams on TeamSpeak belong to a channel (and can be watched from + // any channel; the streamer decides who may). + if Bridge.viewer-channel != "": HorizontalLayout { padding-left: Theme.space-4; padding-right: Theme.space-4; Rectangle { @@ -486,7 +490,7 @@ export component StreamViewer inherits Rectangle { y: (parent.height - self.height) / 2; } Text { - text: @tr("This stream is only available while you're in the {} voice channel.", Bridge.own-channel); + text: Bridge.viewer-channel == Bridge.own-channel ? @tr("Streamed in your voice channel, {}. The streamer decides who may watch.", Bridge.viewer-channel) : @tr("Streamed in the {} voice channel. The streamer decides who may watch.", Bridge.viewer-channel); color: Theme.text-secondary; font-size: Theme.font-sm; vertical-alignment: center; diff --git a/docs/research/ts6-late-join.md b/docs/research/ts6-late-join.md index 483d62e..15588fc 100644 --- a/docs/research/ts6-late-join.md +++ b/docs/research/ts6-late-join.md @@ -174,9 +174,12 @@ for A. So metadata would work as a fallback between Voelin clients, but 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: + the streams of every client on the server that streams, in any channel + (a stream can be watched from another channel, see below). It looks up a + client that streams and whose stream we were not told: - after connecting; + - when a client in another channel starts streaming (the server announces + a stream only in its channel); - 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. @@ -194,6 +197,17 @@ for A. So metadata would work as a fallback between Voelin clients, but - The engine (`voelin-core`) and `voelinctl stream list/watch` feed the client list into `Streams::update_clients`. +Watching from another channel (confirmed, 6.0.0-beta13.1, 2026-10-03): with +B in the default channel and A's stream in another one, `requeststreaminfo +clid=` answers as above and `joinstreamrequest` reaches A +(`notifyjoinstreamrequest`), the probe above shows it. The whole join with +media works too: `scripts/it-smoke.sh`, step "late stream", has a viewer in +the default channel watch a stream in `smoke-elsewhere`, and the app (no +gateway) listed and played a stream in another channel. Voelin lists the +streams of every channel, ours first; as a streamer with `stream.permissions += channel` (the default) it lets its channel in and asks the user about +viewers from other channels. + 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 diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index 2fde60b..2bd82af 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -22,7 +22,8 @@ # later finds it there and watches it # 11. stream (TeamSpeak 6 only): a viewer watches a synthetic VP8 + Opus stream # 12. late stream (TeamSpeak 6 only): a viewer that connects after the stream -# started finds it (requeststreaminfo) and watches it +# started finds it (requeststreaminfo) and watches it; a viewer in the +# default channel finds and watches a stream in another channel # 13. the engine's voice features (voelinctl engine): upload a file and # post its link in chat, another client lists the channel's files and # downloads the linked file (compared byte for byte), the file is @@ -171,6 +172,31 @@ stream_late_check() { grep -E "watching|received" "$out" } +# TeamSpeak 6: the stream runs in another channel. The server announces a +# stream only in its channel; a viewer elsewhere looks it up and watches it +# from where it is, as the official client can. +stream_elsewhere_check() { + local addr=$1 admin=$2 out="$STATE_DIR/stream-elsewhere-watch.log" + local streamer_out="$STATE_DIR/stream-elsewhere-start.log" streamer="far-$$-$RANDOM" + # Semi-permanent, so it outlives this command; it already exists after the first run. + # shellcheck disable=SC2086 + "$VOELINCTL" connect "$addr" $admin --nick admin raw \ + "channelcreate channel_name=smoke-elsewhere channel_flag_semi_permanent=1" >/dev/null 2>&1 || true + "$VOELINCTL" connect "$addr" --nick "$streamer" --channel smoke-elsewhere 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 "streamer in another channel did not go live"; } + if ! "$VOELINCTL" connect "$addr" --nick "elsewhere-$$" stream --loopback watch --streamer-nick "$streamer" \ + --expect-frames 60 --timeout 25 >"$out" 2>&1; then + cat "$out" "$streamer_out" + fail "viewer in the default channel did not receive the stream in another channel" + fi + 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" @@ -488,6 +514,7 @@ for svc in "${SERVERS[@]}"; do if [[ $svc == ts6 ]]; then stream_check "$addr" stream_late_check "$addr" + stream_elsewhere_check "$addr" "$admin" fi done From 5019bed3240d51c042bfe4ea3ec5980d06bd0ee1 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 22:13:31 +0300 Subject: [PATCH 2/2] Answer a streamer's new offer on the running connection Watching a stream from the official client failed. Its log shows why: after our answer it decided our codec choice did not suit it ("remote peer is using unsupported codec, realign") and sent a new offer on the same connection, a renegotiation. Voelin answered every offer with a new peer: new ICE credentials, new DTLS fingerprint (the official client logged both answers, they differ), so the connection the official client kept using was gone and no picture came. - `Peer::renegotiate` answers a new offer on the running peer (str0m `accept_offer` on the same Rtc): same ICE credentials and fingerprint. - The viewer uses it for an `offer` signal while it has a connection; a `reconnectOffer` still starts a new one. - str0m answers a renegotiation in the codec order the connection was built with, so a streamer re-offering another codec first kept sending the old one; `order_like_offer` puts the answer's payload types in the new offer's order. Tests: a unit test (a str0m offerer adds audio in a new offer; same ICE credentials and fingerprint, audio answered) and the order helper; the browser interop test `browser_renegotiates_with_rust` (Chromium streams VP8, re-offers VP9 on the same connection, VP9 frames arrive), passing with Chromium 152. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-stream/src/peer.rs | 99 +++++++++++++++++++ crates/voelin-stream/src/session.rs | 12 +++ crates/voelin-stream/tests/browser_interop.rs | 31 ++++++ docs/protocol-notes/ts6-streaming.md | 16 +++ tests/interop/README.md | 1 + tests/interop/browser-peer.cjs | 15 +++ 6 files changed, 174 insertions(+) diff --git a/crates/voelin-stream/src/peer.rs b/crates/voelin-stream/src/peer.rs index 3d91125..ff5fdc7 100644 --- a/crates/voelin-stream/src/peer.rs +++ b/crates/voelin-stream/src/peer.rs @@ -252,6 +252,7 @@ pub struct MediaFrame { enum Cmd { Answer(String, oneshot::Sender>), + Offer(String, oneshot::Sender>), RemoteCandidate(String), Write { kind: MediaKind, time: MediaTime, data: Arc<[u8]>, rid: Option }, RequestKeyframe, @@ -372,6 +373,16 @@ impl Peer { rx.await.map_err(|_| PeerError::Closed)? } + /// Viewer side: answer a new offer of the streamer on this connection + /// (a renegotiation: the same ICE credentials and DTLS fingerprint). + /// The official client re-offers when the codec our answer chose is one + /// it does not encode, and expects the answer from the same peer. + pub async fn renegotiate(&self, offer: &str) -> Result { + let (tx, rx) = oneshot::channel(); + self.cmd.send(Cmd::Offer(offer.to_owned(), tx)).map_err(|_| PeerError::Closed)?; + rx.await.map_err(|_| PeerError::Closed)? + } + /// Add a trickled remote candidate (`candidate:...`, `a=` prefix optional). pub fn add_remote_candidate(&self, candidate: &str) { let _ = self.cmd.send(Cmd::RemoteCandidate(candidate.to_owned())); @@ -496,6 +507,40 @@ fn build_rtc( dtls::build_rtc(rtc_config, &config.srtp_profiles) } +/// `answer` with the payload types of each media line in the order of the +/// same media line of `offer` (those the offer lacks last). The offerer sends +/// the answer's first codec; str0m answers a new offer on a running +/// connection in the codec order the connection was built with, so without +/// this a streamer that re-offers with another codec first keeps sending the +/// old one. Only the `m=` line order changes, which str0m's own state does +/// not depend on. +fn order_like_offer(answer: &str, offer: &str) -> String { + let offered: Vec> = offer + .lines() + .filter_map(|l| l.trim_end().strip_prefix("m=")) + .map(|m| m.split_whitespace().skip(3).collect()) + .collect(); + let mut section = 0; + let mut out = String::with_capacity(answer.len()); + for line in answer.split_inclusive('\n') { + let Some(media) = line.trim_end().strip_prefix("m=") else { + out.push_str(line); + continue; + }; + let mut parts: Vec<&str> = media.split_whitespace().collect(); + if let Some(order) = offered.get(section) + && parts.len() > 3 + { + parts[3..].sort_by_key(|pt| order.iter().position(|o| o == pt).unwrap_or(usize::MAX)); + } + section += 1; + out.push_str("m="); + out.push_str(&parts.join(" ")); + out.push_str(&line[line.trim_end().len()..]); + } + out +} + /// The video codecs of the first video media line of `sdp`, in offered order. fn offered_video_codecs(sdp: &str) -> Vec { let mut pts: Vec<&str> = Vec::new(); @@ -826,6 +871,13 @@ impl Task { let result = self.accept_answer(&sdp); let _ = reply.send(result); } + Cmd::Offer(sdp, reply) => { + let result = SdpOffer::from_sdp_string(&sdp) + .map_err(|e| PeerError::Sdp(e.to_string())) + .and_then(|offer| Ok(self.rtc.sdp_api().accept_offer(offer)?.to_sdp_string())) + .map(|answer| order_like_offer(&answer, &sdp)); + let _ = reply.send(result); + } Cmd::RemoteCandidate(line) => { let line = line.trim().trim_start_matches("a="); match Candidate::from_sdp_string(line) { @@ -951,6 +1003,53 @@ mod tests { assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}"); } + /// The ICE username fragment and DTLS fingerprint of an SDP. + fn transport(sdp: &str) -> (String, String) { + let line = |prefix: &str| { + sdp.lines().find_map(|l| l.strip_prefix(prefix)).unwrap_or_default().trim().to_owned() + }; + (line("a=ice-ufrag:"), line("a=fingerprint:")) + } + + /// A streamer's new offer (the official client re-offers when it does not + /// encode the codec our answer chose) is answered on the same connection: + /// same ICE credentials and DTLS fingerprint, the new media answered. + #[tokio::test] + async fn a_new_offer_is_answered_on_the_same_connection() { + let mut streamer = RtcConfig::new() + .clear_codecs() + .enable_vp8(true) + .enable_opus(true) + .build(Instant::now()); + let mut api = streamer.sdp_api(); + api.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); + let (offer, pending) = api.apply().unwrap(); + let (peer, answer) = + Peer::answer(&PeerConfig::loopback(), &offer.to_sdp_string()).await.unwrap(); + let answer_sdp = SdpAnswer::from_sdp_string(&answer).unwrap(); + streamer.sdp_api().accept_answer(pending, answer_sdp).unwrap(); + + let mut api = streamer.sdp_api(); + api.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); + let (offer, _pending) = api.apply().unwrap(); + let again = peer.renegotiate(&offer.to_sdp_string()).await.unwrap(); + assert_eq!(transport(&again), transport(&answer), "{again}"); + assert!(again.lines().all(|l| !l.is_empty() || l.ends_with('\r')), "line ends kept"); + assert!(!transport(&again).0.is_empty()); + assert!(again.contains("m=audio") && again.contains("opus/48000"), "{again}"); + } + + #[test] + fn answers_follow_the_offers_codec_order() { + let offer = "v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nm=video 9 UDP/TLS/RTP/SAVPF 98 99 96 97 45\r\n"; + let answer = "v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96 97 7 98 99\r\na=rtpmap:96 VP8/90000\r\n"; + assert_eq!( + order_like_offer(answer, offer), + "v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\nm=video 9 UDP/TLS/RTP/SAVPF 98 99 96 97 7\r\na=rtpmap:96 VP8/90000\r\n" + ); + assert_eq!(order_like_offer("v=0\r\n", offer), "v=0\r\n"); + } + /// An offer of codecs we cannot decode is refused with the reason, not /// answered with a video section the streamer cannot parse. #[tokio::test] diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index 5a58e47..eabba6d 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -1307,6 +1307,18 @@ impl ViewerSession { } } StreamNotification::Signaling { json, .. } => match Signal::parse(json) { + // A new offer on the running connection (the official client + // re-offers when it does not encode the codec we chose) is + // answered by the same peer; `reconnectOffer` starts a new one. + Ok(Signal::Offer { sdp, reconnect: false }) if self.peer.is_some() => { + let peer = self.peer.as_ref().expect("checked above"); + match peer.renegotiate(&sdp).await { + Ok(sdp) => self.signal(Signal::Answer { sdp }, out), + Err(e) => { + self.fail(format!("cannot answer the streamer's new offer: {e}"), out) + } + } + } Ok(Signal::Offer { sdp, .. }) => self.answer(&sdp, out).await, Ok(Signal::IceCandidate { candidate, .. }) => { if let Some(peer) = &self.peer { diff --git a/crates/voelin-stream/tests/browser_interop.rs b/crates/voelin-stream/tests/browser_interop.rs index 538c55c..eea7bea 100644 --- a/crates/voelin-stream/tests/browser_interop.rs +++ b/crates/voelin-stream/tests/browser_interop.rs @@ -273,3 +273,34 @@ async fn browser_streams_to_rust() { assert!(aes_cm_128_sha1_80(&stats["transport"]["srtpCipher"]), "{stats:#}"); browser.quit().await; } + +/// Chromium streams VP8, then renegotiates to VP9 on the same connection, as +/// the official client re-offers when it does not encode the codec our +/// answer chose: our viewer answers on the same peer and keeps receiving, +/// now VP9. +#[tokio::test(flavor = "multi_thread")] +async fn browser_renegotiates_with_rust() { + if !enabled() { + eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)"); + return; + } + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut browser = Browser::start().await; + let offer = browser.call(json!({ "op": "offer", "codec": "VP8", "trickle": false })).await; + let (mut peer, answer) = + Peer::answer(&PeerConfig::loopback(), offer["sdp"].as_str().unwrap()).await.unwrap(); + browser.call(json!({ "op": "accept", "sdp": answer })).await; + wait_connected(&mut peer).await; + let before = receive(&mut peer, Duration::from_secs(5), 30).await; + assert!(before.video.get(Codec::Vp8) >= 30, "before: {:?}", before.video); + + let offer = browser.call(json!({ "op": "reoffer", "codec": "VP9" })).await; + let again = peer.renegotiate(offer["sdp"].as_str().unwrap()).await.unwrap(); + browser.call(json!({ "op": "accept", "sdp": again })).await; + let after = receive(&mut peer, Duration::from_secs(8), 30).await; + eprintln!("after the new offer: video {:?}, audio {:?}", after.video, after.audio); + assert!(after.video.get(Codec::Vp9) >= 30, "after: {:?}", after.video); + let stats = browser.call(json!({ "op": "stats" })).await; + assert_eq!(stats["connectionState"], "connected", "{stats:#}"); + browser.quit().await; +} diff --git a/docs/protocol-notes/ts6-streaming.md b/docs/protocol-notes/ts6-streaming.md index 5213328..d6b9aa9 100644 --- a/docs/protocol-notes/ts6-streaming.md +++ b/docs/protocol-notes/ts6-streaming.md @@ -262,6 +262,22 @@ the official client itself is still to be confirmed: the beta needs a myTeamSpeak sign-in on first start, so it cannot run from a throwaway profile. +### The official client re-offers (confirmed, client 6.0.0-beta4.1, 2026-10-03) + +Streaming from the official client to Voelin, its log shows: our answer +(H.264, VP9, VP8 — no AV1, which the app did not decode) → "remote peer is +using unsupported codec, realign" → a new `offer` signal on the same +connection → our answer → `ENCODER create: H264`. The new offer is a +renegotiation of the running connection: the answer must come from the same +peer (same ICE credentials and DTLS fingerprint). Voelin answered every offer +with a new peer, so the connection broke and nothing was shown. Now +`Peer::renegotiate` answers an `offer` signal on the running connection (a +`reconnectOffer` still starts a new one), in the codec order of the new offer +(str0m keeps the first offer's order; `order_like_offer` fixes the answer's +`m=` lines), so the streamer switches to the codec it re-offered. Tested +against Chromium: `browser_renegotiates_with_rust` (VP8, then a re-offer of +VP9 on the same connection; VP9 frames arrive). + ## Open questions - [x] Viewer side: `joinstreamrequest id clid msg is_remove` (see above). diff --git a/tests/interop/README.md b/tests/interop/README.md index 638c69a..d16948a 100644 --- a/tests/interop/README.md +++ b/tests/interop/README.md @@ -14,6 +14,7 @@ TeamSpeak server is involved. | `browser_streams_to_rust` | Chromium offers a canvas `captureStream` and an oscillator with VP8, VP9, H264 and AV1 preferred in turn (codecs the browser cannot send are skipped); our viewer `Peer::answer` must receive frames of that codec and Opus, over `AES_CM_128_HMAC_SHA1_80`. VP8 also uses trickled browser candidates and checks that a PLI brings a keyframe | | `real_encoders_decode_in_browser` (voelin-core) | Every encoder this machine has (`Codecs::encoders()`), as a share uses it: the 1280x720 test pattern through the `Streamer`, VA-API encoders also from DMA-BUFs as the ScreenCast portal hands over the screen; our streamer peer offers that codec alone (H.264 as Constrained Baseline, see below); the browser must decode at least 60 frames at 1280x720 in 3 s. Codecs the browser does not answer (HEVC, H.264 in Playwright's Chromium) are skipped | | `share_offer_picks_a_codec_every_client_decodes` (voelin-core) | The offer a share makes on this machine (`preferred_codec`, `peer_config`): the browser, answering with the first codec of the offer it lists as the official client does, must pick one every TeamSpeak client decodes (`decoded_everywhere`), and decode it | +| `browser_renegotiates_with_rust` | Chromium streams VP8, then sends a new offer on the same connection with VP9 first (as the official client re-offers when it does not encode the codec we chose); `Peer::renegotiate` answers on the same peer, in the new offer's codec order; VP9 frames must arrive | | `trickled_candidates_reach_browser` | A server-reflexive candidate (from a fake STUN server) as our sessions trickle it (`iceCandidate` signal with the peer's mid) is accepted by `addIceCandidate` | ## Running diff --git a/tests/interop/browser-peer.cjs b/tests/interop/browser-peer.cjs index 3ee84ff..e9f5a5b 100644 --- a/tests/interop/browser-peer.cjs +++ b/tests/interop/browser-peer.cjs @@ -7,6 +7,8 @@ // offer {codec, trickle} send canvas video + oscillator audio; offer with // `codec` preferred -> {sdp} or {unsupported}; // with `trickle` the SDP has no candidates +// reoffer {codec} a new offer on the running connection with `codec` +// preferred (a renegotiation) -> {sdp} or {unsupported} // candidates candidates gathered so far -> {candidates: [{candidate, sdpMid, sdpMLineIndex}]} // accept {sdp} apply the answer to our offer // candidate {candidate, sdpMid, sdpMLineIndex} add a remote candidate @@ -123,6 +125,19 @@ window.peer = { return { sdp }; }, + // A new offer on the running connection with the codec preferred, as the + // official client sends when it re-aligns its codec. + async reoffer({ codec }) { + const pc = this.pc; + const transceiver = pc.getTransceivers().find((t) => t.sender.track && t.sender.track.kind === 'video'); + const all = RTCRtpSender.getCapabilities('video').codecs; + const wanted = all.filter((c) => c.mimeType.toLowerCase() === 'video/' + codec.toLowerCase()); + if (wanted.length === 0) return { unsupported: codec }; + transceiver.setCodecPreferences([...wanted, ...all.filter((c) => !wanted.includes(c))]); + await pc.setLocalDescription(await pc.createOffer()); + return { sdp: pc.localDescription.sdp }; + }, + async candidates() { await gathered(this.pc, 3000); return { candidates: this.localCandidates };