Show TeamSpeak 6's own viewer counts for streams

The streams list and the watch screen showed how many watch a stream only
when a gateway's directory knew it, although TeamSpeak 6 tells the count
itself: `viewer` in `notifystreaminfo`.

StreamInfo gets `viewers`: the server's count from `notifystreaminfo`, 0
for a stream that just started. Probed on the dev server, the server sends
`notifystreamclientjoined` to the whole channel but `notifystreamclientleft`
only to the streamer and the viewer who left, and no `notifystreamupdated`
for either; so the directory counts joins and leaves itself and the engine
asks `requeststreaminfo` again, one stream of another client every 5 s
round robin, which corrects the leaves it was not told about without
flooding the server however many stream. The app shows that count, and the
gateway's where the server gave none; `voelinctl stream list` prints it.

Against the TeamSpeak 6 dev server, a late `stream list` printed
"1 watching" while a viewer watched and "0 watching" after it left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 17:50:35 +03:00
1 parent 11142f2135
commit 81b4976af0
12 files changed
+150 -7

No files matched your search

+2
View File
@@ -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();
+9
View File
@@ -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<StreamInput>) {
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 {
+8
View File
@@ -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,
}
+10 -3
View File
@@ -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<u32>,
}
/// 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.
+75
View File
@@ -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<StreamerSession>,
viewers: BTreeMap<String, ViewerSession>,
out: Outbox,
/// The stream whose viewer count was asked for last.
counted: Option<String>,
}
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<LayerSpec> {
+1
View File
@@ -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)
+1
View File
@@ -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;
+1
View File
@@ -414,6 +414,7 @@ fn demo_ui(app: &mut App) {
bitrate: 8000,
viewer_limit: 0,
audio: true,
viewers: Some(12),
}],
},
Event::State {
+9 -2
View File
@@ -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<u32> {
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