diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 87d0d52..9a862ed 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -1091,6 +1091,8 @@ impl Session { bitrate: 0, viewer_limit: 0, audio: true, + // The UI takes the directory's count, which stays current. + viewers: None, }) }) .collect(); diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index 6060d99..5bcda8b 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -35,6 +35,10 @@ use crate::settings::{STREAM_PERMISSIONS, SharedSettings, StreamPermissions}; use crate::voice::VoiceCmd; use crate::{Event, SessionId}; +/// How often the viewer count of one stream in our channel is asked for +/// (round robin, see [`Streams::refresh_viewer_counts`]). +const VIEWER_COUNTS: std::time::Duration = std::time::Duration::from_secs(5); + /// Our own stream. #[derive(Clone, Debug, PartialEq)] pub enum StreamState { @@ -317,6 +321,8 @@ struct StreamTask { impl StreamTask { async fn run(mut self, mut rx: mpsc::UnboundedReceiver) { + let mut counts = tokio::time::interval(VIEWER_COUNTS); + counts.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); loop { tokio::select! { input = rx.recv() => match input { @@ -328,6 +334,7 @@ impl StreamTask { Some(input) => self.input(input).await, }, () = self.streams.wait_peers() => {} + _ = counts.tick() => self.streams.refresh_viewer_counts(), } self.flush(); } @@ -614,6 +621,7 @@ mod tests { bitrate: setup.bitrate, viewer_limit: setup.viewer_limit, audio: setup.audio, + viewers: Some(0), }; let return_code = (c == from).then(|| "1".to_owned()); (c, StreamNotification::Started { info, return_code }) @@ -973,6 +981,7 @@ mod tests { bitrate: 0, viewer_limit: 0, audio: true, + viewers: None, }; handles[1].send(StreamInput::Directory(vec![entry])); wait(&mut rx, |e| match e { diff --git a/crates/voelin-stream/src/discovery.rs b/crates/voelin-stream/src/discovery.rs index beacbfe..99fc852 100644 --- a/crates/voelin-stream/src/discovery.rs +++ b/crates/voelin-stream/src/discovery.rs @@ -200,6 +200,13 @@ impl Discovery { changed } + /// Ask the server (`requeststreaminfo`) for the streams of `streamer` + /// again, e.g. for their viewer counts; `false` if it cannot answer. + pub fn ask_server(&mut self, streamer: ClientId, out: &mut Outbox) -> bool { + // The server is the first lookup (see `new`). + self.lookups.first_mut().is_some_and(|server| server.lookup(streamer, out)) + } + /// A request of a lookup failed on the server. pub fn failed(&mut self, request: &Request, error: &str) { for lookup in &mut self.lookups { @@ -245,6 +252,7 @@ mod tests { bitrate: 4608, viewer_limit: 0, audio: true, + viewers: Some(0), }, return_code: None, } diff --git a/crates/voelin-stream/src/proto.rs b/crates/voelin-stream/src/proto.rs index 38ed4fe..5600618 100644 --- a/crates/voelin-stream/src/proto.rs +++ b/crates/voelin-stream/src/proto.rs @@ -116,6 +116,11 @@ pub struct StreamInfo { pub bitrate: u32, pub viewer_limit: u32, pub audio: bool, + /// How many watch it: `viewer` of `notifystreaminfo`, 0 for a stream + /// that just started, then kept current from the viewers joining and + /// leaving (see [`StreamDirectory`](crate::session::StreamDirectory)). + /// `None` where nothing told (e.g. a gateway's directory entry). + pub viewers: Option, } /// Stream notifications, decoded from [`InMessage`]. @@ -190,6 +195,7 @@ impl StreamNotification { bitrate: p.bitrate.unwrap_or(0), viewer_limit: p.viewer_limit.unwrap_or(0), audio: p.audio.unwrap_or(false), + viewers: Some(0), }, return_code: p.return_code.clone(), }) @@ -207,6 +213,7 @@ impl StreamNotification { bitrate: p.bitrate.unwrap_or(0), viewer_limit: p.viewer_limit.unwrap_or(0), audio: p.audio.unwrap_or(false), + viewers: p.viewers, })) }) .collect(), @@ -399,7 +406,7 @@ mod tests { .iter() .map(|n| match n { StreamNotification::Info(i) => { - (i.id.as_str(), i.streamer, i.name.as_str(), i.audio) + (i.id.as_str(), i.streamer, i.name.as_str(), i.audio, i.viewers) } other => panic!("{other:?}"), }) @@ -407,8 +414,8 @@ mod tests { assert_eq!( infos, [ - ("6b5158dd", ClientId(6), "renamed again", true), - ("069ba23c", ClientId(6), "second", false) + ("6b5158dd", ClientId(6), "renamed again", true, Some(0)), + ("069ba23c", ClientId(6), "second", false, Some(2)) ] ); // A client without streams. diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index c4b03af..28cbed3 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -284,6 +284,20 @@ impl StreamDirectory { *info != before } StreamNotification::Stopped { id, .. } => self.streams.remove(id).is_some(), + // The server tells the whole channel who joins, but only the + // streamer and the viewer who leaves (and nobody when a viewer + // stops watching by leaving the server): + // [`Streams::refresh_viewer_counts`] asks again now and then. + StreamNotification::ViewerJoined { id, .. } + | StreamNotification::ViewerLeft { id, .. } => { + let joined = matches!(n, StreamNotification::ViewerJoined { .. }); + let Some(count) = self.streams.get_mut(id).and_then(|s| s.viewers.as_mut()) else { + return false; + }; + let before = *count; + *count = if joined { count.saturating_add(1) } else { count.saturating_sub(1) }; + *count != before + } _ => false, } } @@ -1476,6 +1490,8 @@ pub struct Streams { streamer: Option, viewers: BTreeMap, out: Outbox, + /// The stream whose viewer count was asked for last. + counted: Option, } impl Streams { @@ -1489,6 +1505,7 @@ impl Streams { streamer: None, viewers: BTreeMap::new(), out: Outbox::default(), + counted: None, } } @@ -1729,6 +1746,24 @@ impl Streams { self.discovery.add_lookup(lookup); } + /// Ask the server for the viewer count of the next stream of another + /// client in our channel, round robin: one `requeststreaminfo` per call, + /// so a few calls a minute keep the counts close without flooding the + /// server however many stream. Viewers leaving are only announced to the + /// streamer and themselves (see [`StreamDirectory::apply`]). + pub fn refresh_viewer_counts(&mut self) { + let (own, last) = (self.own, self.counted.take()); + let others = || self.directory.iter().filter(|s| s.streamer != own); + let next = others() + .find(|s| last.as_ref().is_some_and(|last| s.id > *last)) + .or_else(|| others().next()) + .map(|s| (s.id.clone(), s.streamer)); + let Some((id, streamer)) = next else { return }; + if self.discovery.ask_server(streamer, &mut self.out) { + self.counted = Some(id); + } + } + /// A request from [`Output::Request`] failed on the server. pub fn request_failed(&mut self, request: &Request, error: &str) { let watched = match request { @@ -1826,6 +1861,7 @@ mod tests { bitrate: 4608, viewer_limit: 0, audio: true, + viewers: Some(0), } } @@ -2222,6 +2258,45 @@ mod tests { assert!(!d.apply(&join(ClientId(3), false))); } + #[tokio::test] + async fn viewer_counts() { + let joined = |id: &str| StreamNotification::ViewerJoined { id: id.into(), viewer: OTHER }; + let left = |id: &str| StreamNotification::ViewerLeft { + id: id.into(), + viewer: OTHER, + reason: Some(LeaveReason::None), + }; + let mut d = StreamDirectory::default(); + assert!(d.apply(&started("a", ClientId(1), false))); + assert_eq!(d.get("a").unwrap().viewers, Some(0)); + assert!(d.apply(&joined("a")) && d.apply(&joined("a")) && d.apply(&left("a"))); + assert_eq!(d.get("a").unwrap().viewers, Some(1)); + // The server's count replaces ours; never below zero. + let counted = StreamInfo { viewers: Some(5), ..info("a", ClientId(1)) }; + assert!(d.apply(&StreamNotification::Info(counted))); + assert_eq!(d.get("a").unwrap().viewers, Some(5)); + let unknown = StreamInfo { viewers: None, ..info("a", ClientId(1)) }; + assert!(d.apply(&StreamNotification::Info(unknown))); + assert!(!d.apply(&joined("a")) && !d.apply(&left("x"))); + assert!(d.apply(&started("z", ClientId(1), false)) && !d.apply(&left("z"))); + + // Asked for one stream of another client at a time, round robin. + let mut s = Streams::new(OWN, PeerConfig::loopback()); + for (id, streamer) in [("a", OWN), ("b", ClientId(2)), ("c", ClientId(3))] { + s.handle_notification(StreamNotification::Info(info(id, streamer))).await; + } + let _ = drain(&mut s); + let mut asked = Vec::new(); + for _ in 0..3 { + s.refresh_viewer_counts(); + asked.extend(drain(&mut s).0.into_iter().map(|r| match r { + Request::StreamInfo { streamer } => streamer.0, + other => panic!("{other:?}"), + })); + } + assert_eq!(asked, [2, 3, 2]); + } + /// Layers for the simulcast tests: 0 needs 2 Mbit/s, 1 needs 600 kbit/s /// (at most 1.2 Mbit/s), 2 is the fallback. fn three_layers() -> Vec { diff --git a/crates/voelin-stream/tests/sessions.rs b/crates/voelin-stream/tests/sessions.rs index 2c11cfb..f45df5b 100644 --- a/crates/voelin-stream/tests/sessions.rs +++ b/crates/voelin-stream/tests/sessions.rs @@ -43,6 +43,7 @@ impl FakeServer { bitrate: setup.bitrate, viewer_limit: setup.viewer_limit, audio: setup.audio, + viewers: Some(0), }; self.streams.insert(info.id.clone(), info.clone()); (0..2) diff --git a/crates/voelin-stream/tests/simulcast.rs b/crates/voelin-stream/tests/simulcast.rs index 90c8c98..9700a02 100644 --- a/crates/voelin-stream/tests/simulcast.rs +++ b/crates/voelin-stream/tests/simulcast.rs @@ -47,6 +47,7 @@ async fn rid_simulcast_over_loopback() { bitrate: 1900, viewer_limit: 0, audio: true, + viewers: Some(0), }; s.handle_notification(StreamNotification::Started { info, return_code: Some("1".into()) }) .await; diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index 8ae1142..5342aae 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -414,6 +414,7 @@ fn demo_ui(app: &mut App) { bitrate: 8000, viewer_limit: 0, audio: true, + viewers: Some(12), }], }, Event::State { diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index 013e608..93c80a2 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -103,6 +103,13 @@ fn share_end_text(reason: &EndReason) -> String { } } +/// How many watch stream `id`: the server's count (TeamSpeak 6 tells it), +/// else the gateway directory's. +fn viewer_count(view: &crate::app::SessionView, id: &str) -> Option { + let native = view.streams.iter().find(|s| s.id == id).and_then(|s| s.viewers); + native.or_else(|| view.stream_viewers.get(id).copied()) +} + /// "8 Mbit/s", "640 kbit/s" (the stream's announced bitrate, kbit/s); "" for 0. fn bitrate_text(kbps: u32) -> String { match kbps { @@ -225,7 +232,7 @@ impl App { name: s.name.clone().into(), streamer: view.nickname(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), + viewers: viewer_count(view, &s.id).unwrap_or(0) as i32, audio: s.audio, watching, own: view.state.own_client == Some(s.streamer.0), @@ -347,7 +354,7 @@ impl App { .map_or(-1, |s| i32::from(s.streamer.0)); bridge.set_viewer_streamer_id(streamer); bridge.set_viewer_elapsed(watch.elapsed().into()); - let viewers = self.view().and_then(|v| v.stream_viewers.get(&watch.stream_id)).copied(); + let viewers = self.view().and_then(|v| viewer_count(v, &watch.stream_id)); bridge.set_viewer_count(viewers.unwrap_or(0) as i32); let qualities = watch.qualities(); let chosen = watch diff --git a/docs/media.md b/docs/media.md index e058807..b44d092 100644 --- a/docs/media.md +++ b/docs/media.md @@ -181,6 +181,14 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder - `Viewer` feeds a `VideoPipeline` from the engine and sends `RequestStreamKeyframe`; `LocalPreview` runs capture → encoder → decoder without a server (the desktop app's `VOELIN_DEMO_STREAM`). +- Viewer counts come from the server: `StreamInfo::viewers` in + `Event::StreamsChanged` is TeamSpeak 6's own count (`viewer` of + `notifystreaminfo`), counted up from `notifystreamclientjoined` and + refreshed with `requeststreaminfo`, one stream every 5 s, because the + server tells only the streamer and the viewer when someone leaves + ([protocol notes](protocol-notes/ts6-streaming.md#viewer-counts-confirmed-600-beta131-2026-10-03)). + The app shows it, and the gateway directory's count where the server + gave none. - The audio of watched streams does not go through this module: the session hands the Opus frames to its audio thread, which plays them through the jitter buffer and mixer under a made-up client id, with its own volume. @@ -993,6 +1001,7 @@ has not run on Windows yet. | Zero-copy from a real screen capture | `voelinctl stream bench --source portal --encoder h264_vaapi` | not run yet (a portal capture asks the person at the desktop); everything up to the portal is tested with the test pattern as DMA-BUFs (rows above, and the measurements) | | Offer [VP9, VP8], a viewer that decodes only VP8 → its own VP8 encoder, VP9 idle, pictures decoded | `voelin-core/tests/media_live.rs` `ts6_viewer_gets_the_codec_it_chose` (`VOELIN_LIVE=1`) | tested against the TeamSpeak 6 dev server (our client on both ends) | | Several codecs against official TeamSpeak viewers | – | not tested (no official client here) | +| Viewer counts: `viewer` of `notifystreaminfo`, counted up and down from the viewers joining and leaving, refreshed one stream at a time | `voelin-stream` `proto::tests::stream_info_answers`, `session::tests::viewer_counts`; `voelinctl stream list` | tested; against the TeamSpeak 6 dev server `stream list` printed "1 watching" while a viewer watched and "0 watching" after | | Test pattern → VP8 → decoder, rectangle position and colour | `voelin-core` `media::tests::local_preview_decodes_the_pattern` | tested | | Test pattern → two engine stream tasks → str0m peers on loopback → decoder | `voelin-core` `stream::tests::test_pattern_through_stream_tasks` | tested | | Stream audio (RTP time → jitter buffer ids, volume, end) | `voelin-core` `audio::tests::stream_audio_with_volume`, stream task test | tested | diff --git a/docs/protocol-notes/ts6-streaming.md b/docs/protocol-notes/ts6-streaming.md index 0eb6b4a..a9b098c 100644 --- a/docs/protocol-notes/ts6-streaming.md +++ b/docs/protocol-notes/ts6-streaming.md @@ -195,6 +195,28 @@ Full transcript, all the variants tried, and what Voelin does with them: looks up unannounced streams in its channel with `requeststreaminfo` (`voelin_stream::discovery`). +### Viewer counts (confirmed, 6.0.0-beta13.1, 2026-10-03) + +Streamer A, viewers B and B2, bystander C in one channel, every command +logged (`--log-commands`): + +- `viewer` of `notifystreaminfo` is the number of viewers the streamer + accepted: `requeststreaminfo clid=` answered `viewer=1` while B2 + watched and `viewer=0` after it left. +- `notifystreamclientjoined clid= id=` goes to everyone in + the channel (C got one for B and one for B2), but not to the viewer who + joined. +- `notifystreamclientleft clid= id= reason=1` goes only to + the streamer and to the viewer who left (`joinstreamrequest ... + is_remove=1`); C got nothing, also not when B left the server. +- No `notifystreamupdated` when viewers come or go (`StreamUpdated` has no + viewer field). + +So a client counts joins itself, and asks `requeststreaminfo` again now and +then for the leaves it is not told about: `StreamInfo::viewers` +(`voelin_stream`), kept by `StreamDirectory` and refreshed one stream at a +time every 5 s by the engine (`Streams::refresh_viewer_counts`). + ### WebRTC interop with Chromium (confirmed, Chromium 141, 2026-09-26) `crates/voelin-stream/tests/browser_interop.rs` (`VOELIN_INTEROP=1`, see diff --git a/tools/voelinctl/src/stream.rs b/tools/voelinctl/src/stream.rs index 93a046a..0b094a6 100644 --- a/tools/voelinctl/src/stream.rs +++ b/tools/voelinctl/src/stream.rs @@ -694,13 +694,14 @@ async fn list(con: &mut Connection, driver: &mut Driver, settle: Duration) -> Re let streams: Vec<&StreamInfo> = driver.streams.directory().iter().collect(); for s in &streams { println!( - "{} {:?} by {} (clid {}), {} kbit/s{}", + "{} {:?} by {} (clid {}), {} kbit/s{}{}", s.id, s.name, nick(con, s.streamer), s.streamer.0, s.bitrate, - if s.audio { ", audio" } else { "" } + if s.audio { ", audio" } else { "" }, + s.viewers.map(|n| format!(", {n} watching")).unwrap_or_default() ); } // Streamers in our channel known only by the flag: the lookup failed or