diff --git a/crates/voelin-core/src/link/media.rs b/crates/voelin-core/src/link/media.rs index efd63f8..f0eccba 100644 --- a/crates/voelin-core/src/link/media.rs +++ b/crates/voelin-core/src/link/media.rs @@ -6,7 +6,7 @@ //! thread speaks; this is the framing in the v1 media codec //! (`voelin_proto::media`, protocol section 6). -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::time::{Duration, Instant}; use bytes::BytesMut; @@ -102,15 +102,40 @@ impl Incoming { /// Who is talking: derived from the media (protocol section 6.4). A talker /// starts with its first packet and stops after [`TALK_SILENCE`] without one. +/// +/// A host can also say that someone talks whose voice it does not carry as +/// media (a `Speaking` signal; TeamSpeak's Speex and CELT talkers are such): +/// that is a hint, which holds until the host says it is over. #[derive(Default)] pub(crate) struct TalkTracker { last: HashMap, + hinted: HashSet, } impl TalkTracker { /// A packet of `client` arrived; whether this starts its talking. pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool { - self.last.insert(client, now).is_none() + let was = self.is_talking(client); + self.last.insert(client, now); + !was + } + + /// The host says `client` talks or has stopped; whether this changes + /// whether it is talking. + pub(crate) fn hint(&mut self, client: u16, talking: bool) -> bool { + let was = self.is_talking(client); + if talking { + self.hinted.insert(client); + } else { + self.hinted.remove(&client); + } + was != self.is_talking(client) + } + + /// Forget the hints about clients `present` does not hold any more: a + /// client that left cannot say it stopped. + pub(crate) fn retain_hints(&mut self, present: impl Fn(u16) -> bool) { + self.hinted.retain(|client| present(*client)); } /// The talkers that have been silent long enough, no longer talking. @@ -125,11 +150,12 @@ impl TalkTracker { for client in &silent { self.last.remove(client); } + silent.retain(|client| !self.hinted.contains(client)); silent } pub(crate) fn is_talking(&self, client: u16) -> bool { - self.last.contains_key(&client) + self.last.contains_key(&client) || self.hinted.contains(&client) } } @@ -253,4 +279,32 @@ mod tests { // A packet after the silence starts it again. assert!(talk.heard(8, t0 + Duration::from_secs(2))); } + + #[test] + fn a_host_that_says_someone_talks_is_believed_until_it_says_otherwise() { + let mut talk = TalkTracker::default(); + let t0 = Instant::now(); + // A talker whose voice is no media: on, and no silence ends it. + assert!(talk.hint(8, true)); + assert!(!talk.hint(8, true), "already talking"); + assert!(talk.is_talking(8)); + assert!(talk.expire(t0 + Duration::from_secs(60)).is_empty()); + assert!(talk.hint(8, false)); + assert!(!talk.is_talking(8)); + // A talker with media that the host also names: the media ends it, when + // the host has said it is over (in either order). + assert!(talk.heard(9, t0)); + assert!(!talk.hint(9, true), "heard already"); + assert!(talk.expire(t0 + Duration::from_millis(500)).is_empty(), "the host still says so"); + assert!(talk.is_talking(9)); + assert!(talk.hint(9, false)); + assert!(!talk.is_talking(9)); + assert!(talk.heard(10, t0)); + assert!(!talk.hint(10, false), "the media goes on"); + assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [10]); + // A hint about somebody who is gone is forgotten. + assert!(talk.hint(11, true)); + talk.retain_hints(|client| client != 11); + assert!(!talk.is_talking(11)); + } } diff --git a/crates/voelin-core/src/link/mod.rs b/crates/voelin-core/src/link/mod.rs index a736c8b..eaab2ec 100644 --- a/crates/voelin-core/src/link/mod.rs +++ b/crates/voelin-core/src/link/mod.rs @@ -349,6 +349,9 @@ pub enum LinkEvent { /// both from the server's version). backend: BackendInfo, capabilities: Capabilities, + /// Our client id when the link connected. TeamSpeak's own reconnect gives + /// a new one, which is not announced; the engine follows it in the + /// snapshots by our unique id. own_client: u16, /// The server's unique id. server_uid: String, @@ -357,6 +360,11 @@ pub enum LinkEvent { }, /// The server's channels and clients as they are now. Presence(Box), + /// The channel we are in, after every [`LinkEvent::Presence`]. The engine + /// derives it itself, from our own voice state in the snapshots of the + /// `Session` it talks to, and so follows us when TeamSpeak's reconnect makes + /// us another client. What an in-process link such as `TsLink` says here only + /// tells the TeamSpeak `Session` made of it that a move has arrived. OwnChannel(ChannelId), Chat(ChatMessage), Poke { @@ -367,7 +375,11 @@ pub enum LinkEvent { }, /// Incoming voice for the audio thread. Audio(VoicePacket), - /// Who is talking (on, and off again when it stopped). + /// Who is talking (on, and off again when it stopped). The engine derives + /// it from the media of its `Session` (protocol section 6.4). What an + /// in-process link such as `TsLink` says here reaches the engine as a + /// speaking hint next to the media: that is what shows the talkers whose + /// packets the link does not forward as Opus (Speex, CELT). Talking { client: u16, talking: bool, diff --git a/crates/voelin-core/src/link/session_link.rs b/crates/voelin-core/src/link/session_link.rs index ced65a5..18863de 100644 --- a/crates/voelin-core/src/link/session_link.rs +++ b/crates/voelin-core/src/link/session_link.rs @@ -44,8 +44,11 @@ use crate::{BackendInfo, Event, JoinFailure}; const SYNC_TIME: Duration = Duration::from_secs(30); /// How long a closing session may take to end. const CLOSE_TIME: Duration = Duration::from_secs(10); -/// Most CHAT scopes the engine subscribes (`Limits.max_chat_subscriptions`). -const MAX_CHAT_SCOPES: usize = 16; +/// How long a session whose push channel ended may take to say that it has. +const END_TIME: Duration = Duration::from_secs(1); +/// Most CHAT scopes the engine subscribes when the host does not say +/// (`Limits.max_chat_subscriptions` of 0 is the v1.0 default, 16). +const DEFAULT_CHAT_SCOPES: usize = 16; /// Starts the voice connections of an engine: each one a `Session` from the /// connector of its address (`docs/session-seam.md` section 4). @@ -232,10 +235,23 @@ async fn drive( return conn.finish().await; } }; - if let Err(reason) = sequence { - session.close(v1::CloseCode::Normal, ""); - let _ = tokio::time::timeout(CLOSE_TIME, session.closed()).await; - return reason; + match sequence { + Ok(()) => {} + Err(None) => { + // The push channel ended, so the session did, and its end says why. (A + // refusal with no words leaves it open: it is closed then.) + if let Ok(reason) = tokio::time::timeout(END_TIME, session.closed()).await { + return close_text(&reason); + } + session.close(v1::CloseCode::Normal, ""); + let _ = tokio::time::timeout(CLOSE_TIME, session.closed()).await; + return None; + } + Err(Some(reason)) => { + session.close(v1::CloseCode::Normal, ""); + let _ = tokio::time::timeout(CLOSE_TIME, session.closed()).await; + return Some(reason); + } } conn.run(cmds, early).await } @@ -264,6 +280,8 @@ struct Batch { home: bool, /// Messages that arrived, as (channel, id). messages: Vec<(u64, u64)>, + /// CHAT scopes whose sync ended: their messages are in the replica now. + synced: Vec, signals: Vec, /// A scope of the server was closed, with the host's words. closed: Vec, @@ -274,6 +292,7 @@ impl Batch { self.view |= other.view; self.home |= other.home; self.messages.extend(other.messages); + self.synced.extend(other.synced); self.signals.extend(other.signals); self.closed.extend(other.closed); } @@ -292,8 +311,12 @@ struct Conn { features: Features, welcome: v1::Welcome, server: u64, + /// The participant and media slot we are, and the user (see `follow_seat`). participant: u32, slot: u32, + user: u64, + /// Most CHAT scopes the host lets us hold (`Limits.max_chat_subscriptions`). + max_chat: usize, input_muted: bool, output_muted: bool, talk: TalkTracker, @@ -326,6 +349,13 @@ impl Conn { let (internal_tx, internal) = mpsc::unbounded_channel(); let welcome = session.welcome().clone(); let features = session.features(); + let max_chat = welcome + .limits + .as_ref() + .map(|limits| limits.max_chat_subscriptions) + .filter(|max| *max != 0) + .map_or(DEFAULT_CHAT_SCOPES, |max| usize::try_from(max).unwrap_or(usize::MAX)); + let user = welcome.user_id; Self { session, pushes, @@ -341,6 +371,8 @@ impl Conn { server: 0, participant: 0, slot: 0, + user, + max_chat, input_muted: false, output_muted: false, talk: TalkTracker::default(), @@ -449,7 +481,13 @@ impl Conn { .ok_or_else(|| Some("the host did not seat us in voice".to_owned()))?; self.participant = voice.participant_id; self.slot = voice.slot; - self.replica.set_own_user(self.own_user()); + self.user = self + .replica + .voice_state(self.server, self.participant) + .map(|v| v.user_id) + .filter(|id| *id != 0) + .unwrap_or(self.welcome.user_id); + self.replica.set_own_user(self.user); let backend = self.backend(); let own_uid = @@ -509,13 +547,45 @@ impl Conn { self.replica.server(self.server).map_or(0, |s| s.default_channel_id) } - /// The user id we are: our voice state's, else the host's word. + /// The user id we are. fn own_user(&self) -> u64 { - self.replica - .voice_state(self.server, self.participant) - .map(|v| v.user_id) - .filter(|id| *id != 0) - .unwrap_or(self.welcome.user_id) + self.user + } + + /// Whether the host is a TeamSpeak server (`Welcome.host.backend`). + fn teamspeak(&self) -> bool { + self.backend().product == "teamspeak" + } + + /// Follow our seat to the participant that is us now. A participant is us + /// for the life of a session, except behind a TeamSpeak server: the + /// connection reconnects by itself, without a word, as another client with + /// the same user (`docs/session-seam.md` 4.4). The seat stays while it is + /// ours; when it is gone, or does not carry our user while another + /// participant does (a ghost of the old connection), the other is our seat. + /// A seat whose user id changed by itself (the snapshot that tells our + /// database id came after the seat) is still ours, and so is the new id. + fn follow_seat(&mut self) { + let seat = self.replica.voice_state(self.server, self.participant); + if self.user == 0 || seat.is_some_and(|v| v.user_id == self.user) || !self.teamspeak() { + return; + } + let seat_user = seat.map(|v| v.user_id).filter(|id| *id != 0); + let other = self + .replica + .voice_states(self.server) + .find(|v| v.user_id == self.user) + .map(|v| (v.participant_id, v.slot)); + match (other, seat_user) { + (Some((participant, slot)), _) => { + debug!(from = self.participant, to = participant, "we are another participant now"); + self.participant = participant; + self.slot = slot; + } + (None, Some(user)) => self.user = user, + // Gone, and nobody takes its place yet. + (None, None) => {} + } } /// Subscribe a scope: the replica first, then the host. @@ -633,7 +703,14 @@ impl Conn { })); self.note_scope(change.scope.as_ref(), &mut batch); } - Some(Body::SyncEnd(end)) => self.note_scope(end.scope.as_ref(), &mut batch), + Some(Body::SyncEnd(end)) => { + self.note_scope(end.scope.as_ref(), &mut batch); + if let Some(ScopeId::Chat(channel)) = + end.scope.as_ref().and_then(ScopeId::from_proto) + { + batch.synced.push(channel); + } + } Some(Body::Signal(signal)) => batch.signals.push(signal.clone()), Some(Body::HostUpdate(update)) => { self.features = Features::new(update.features.clone()); @@ -664,8 +741,9 @@ impl Conn { /// The events of a batch of pushes: the presence, the own channel, the /// messages, the signals; and the CHAT scopes that follow. async fn after(&mut self, batch: Batch) { - let Batch { view, home, messages, signals, closed } = batch; + let Batch { view, home, mut messages, synced, signals, closed } = batch; if view || home { + self.follow_seat(); self.replica.set_own_user(self.own_user()); } for message in closed { @@ -677,11 +755,19 @@ impl Conn { if view || home { self.update_chat_scopes(); } + // The messages of a full sync are staged until its end: a `Change` of it + // cannot be read yet, and this is where they can. + for channel in synced { + messages.extend(self.replica.messages(channel).map(|m| (channel, m.id))); + } for (channel, id) in messages { - if !self.seen.insert((channel, id)) { + // Reported once, and only once it can be read: a message the replica + // does not hold yet stays unreported until it does. + if self.seen.contains(&(channel, id)) { continue; } if let Some(message) = project::chat_message(&self.replica, channel, id) { + self.seen.insert((channel, id)); self.send(LinkEvent::Chat(message)); } } @@ -708,6 +794,9 @@ impl Conn { .voice_states(self.server) .filter_map(|v| Some((v.slot, u16::try_from(v.participant_id).ok()?))) .collect(); + // A client that left cannot say it stopped talking. + let slots = &self.slots; + self.talk.retain_hints(|client| slots.values().any(|present| *present == client)); if self.reported.as_ref() == Some(&presence) { return; } @@ -738,9 +827,11 @@ impl Conn { let own = self.own_channel().filter(|c| self.replica.channel(*c).is_some()); wanted.extend(own); let mut dms: Vec = self.replica.channels(0).map(|c| c.id).collect(); - dms.sort_unstable(); + dms.sort_unstable_by(|a, b| b.cmp(a)); wanted.extend(dms); - wanted.truncate(MAX_CHAT_SCOPES); + // More than the host lets us hold: the server chat and our channel first, + // then the private conversations, the newest first (the ids of a host grow). + wanted.truncate(self.max_chat); let wanted: HashSet = wanted.into_iter().collect(); let leave: Vec = self.chats.difference(&wanted).copied().collect(); let join: Vec = wanted.difference(&self.chats).copied().collect(); @@ -800,6 +891,14 @@ impl Conn { self.send(LinkEvent::Error(notice.text)); } } + // A talker whose voice the host does not carry as media (TeamSpeak's Speex + // and CELT talkers): the host's word that it talks, until it says it is over. + Some(Signal::Speaking(speaking)) => { + let Ok(client) = u16::try_from(speaking.participant_id) else { return }; + if self.talk.hint(client, speaking.on) { + self.send(LinkEvent::Talking { client, talking: speaking.on }); + } + } // Nothing in the engine shows typing, reminders or hints yet. _ => debug!("signal of the host ignored"), } @@ -1678,4 +1777,131 @@ mod tests { assert_eq!(split_path("/docs/a.txt"), ("/docs".into(), "a.txt".into())); assert_eq!(split_path("/a.txt"), ("/".into(), "a.txt".into())); } + + // ---- the replica behind the events --------------------------------------- + + /// A connection over the protocol repository's fake host, driven by hand: + /// the test applies the pushes batch by batch and reads the events. + async fn conn() -> (Conn, mpsc::UnboundedReceiver) { + use voelin_proto::link::Connector; + let connector = voelin_proto::test_util::FakeConnector::new(); + let (params, _media) = voelin_proto::test_util::connect_params("fake://host"); + let connected = connector.connect(params).await.unwrap(); + let (_media_tx, media) = mpsc::unbounded_channel(); + let (events_tx, events) = mpsc::unbounded_channel(); + let ctx = LocalCtx::standalone().link; + (Conn::new(connected.session, connected.pushes, media, None, ctx, events_tx), events) + } + + fn push(body: Body) -> v1::Push { + v1::Push { body: Some(body) } + } + + fn message(channel: u64, id: u64) -> Entity { + Entity { + kind: Some(Kind::Message(v1::Message { + id, + channel_id: channel, + author_name: "alice".into(), + text: format!("m{id}"), + ts_ms: 1_700_000_000_000, + ..Default::default() + })), + } + } + + fn sync_begin(scope: ScopeId) -> v1::Push { + push(Body::SyncBegin(v1::SyncBegin { + scope: Some(scope.to_proto()), + mode: v1::SyncMode::Full as i32, + epoch: 1, + })) + } + + fn sync_change(scope: ScopeId, put: Vec) -> v1::Push { + push(Body::Change(v1::Change { + scope: Some(scope.to_proto()), + rev: 5, + put, + del: Vec::new(), + })) + } + + fn sync_end(scope: ScopeId) -> v1::Push { + push(Body::SyncEnd(v1::SyncEnd { + scope: Some(scope.to_proto()), + cursor: Some(v1::Cursor { epoch: 1, rev: 5 }), + gap: false, + })) + } + + fn texts(events: &mut mpsc::UnboundedReceiver) -> Vec { + let mut texts = Vec::new(); + while let Ok(event) = events.try_recv() { + if let LinkEvent::Chat(message) = event { + texts.push(message.text); + } + } + texts + } + + /// A full sync stages its messages until `SyncEnd`: a message of its + /// `Change` cannot be read when the `Change` is applied, and the batch that + /// carries `SyncEnd` may be another one. + #[tokio::test] + async fn the_messages_of_a_chat_sync_are_reported_when_the_sync_ends() { + let (mut conn, mut events) = conn().await; + let scope = ScopeId::Chat(7); + conn.replica.subscribe(scope); + + // One batch: the start of the sync and its messages. + let mut batch = conn.apply(&sync_begin(scope)); + batch.merge(conn.apply(&sync_change(scope, vec![message(7, 10), message(7, 11)]))); + conn.after(batch).await; + assert!(texts(&mut events).is_empty(), "staged: nothing can be read yet"); + + // The next batch: its end. Both messages are reported now, in order. + let batch = conn.apply(&sync_end(scope)); + conn.after(batch).await; + assert_eq!(texts(&mut events), ["m10", "m11"]); + + // And once: the same window again (a re-subscription) adds a message. + let mut batch = conn.apply(&sync_begin(scope)); + batch.merge(conn.apply(&sync_change(scope, vec![message(7, 10), message(7, 12)]))); + batch.merge(conn.apply(&sync_end(scope))); + conn.after(batch).await; + assert_eq!(texts(&mut events), ["m12"]); + + // A live message is reported once, however often it comes. + let live = push(Body::Change(v1::Change { + scope: Some(scope.to_proto()), + rev: 6, + put: vec![message(7, 13)], + del: Vec::new(), + })); + let mut batch = conn.apply(&live); + batch.merge(conn.apply(&live)); + conn.after(batch).await; + assert_eq!(texts(&mut events), ["m13"]); + } + + /// A message that comes before its scope is subscribed is not lost: it is + /// reported with the sync that holds it. + #[tokio::test] + async fn a_message_that_comes_before_its_scope_is_reported_with_the_sync() { + let (mut conn, mut events) = conn().await; + let scope = ScopeId::Chat(8); + // Nothing subscribed: the replica holds none of it. + let batch = conn.apply(&sync_change(scope, vec![message(8, 20)])); + conn.after(batch).await; + assert!(texts(&mut events).is_empty()); + + conn.replica.subscribe(scope); + let mut batch = conn.apply(&sync_begin(scope)); + batch.merge(conn.apply(&sync_change(scope, vec![message(8, 20), message(8, 21)]))); + conn.after(batch).await; + let batch = conn.apply(&sync_end(scope)); + conn.after(batch).await; + assert_eq!(texts(&mut events), ["m20", "m21"]); + } }