The review found four defects in SessionLink and the link module, fixed here:
- A message of a CHAT scope's first full sync could be lost. The replica stages
a full sync until its SyncEnd, so a message of a Change of the sync cannot be
read when the Change is applied, and SyncBegin, Change and SyncEnd may come
in different batches; but (channel, id) was marked as reported before the
replica was asked for the message. A message is marked as reported only when
it was shown now, and at the SyncEnd of a CHAT scope the messages of that
channel not shown yet are (two deterministic unit tests, one with SyncEnd in
a later batch and one for a message that comes before its scope).
- When the push channel ended during the connect syncs, the real close reason
of the session was thrown away and the engine showed a silent disconnect. It
now asks closed() (and closes a session that has not ended: a refusal with no
words).
- The CHAT scopes were limited to 16 whatever the host said. The limit is now
Welcome.limits.max_chat_subscriptions (0 or none: the v1.0 default of 16); the
server chat and our channel come first, then the private conversations, the
newest (highest id) first.
- The own participant was pinned to the one of the connect. Behind a TeamSpeak
host the seat now follows our user: it stays while the participant is ours
and moves to the participant that carries our user id when the seat is gone
(tsclientlib's reconnect makes us another client) or no longer carries it (a
ghost of the old connection); a seat whose user id changed by itself is
followed. OwnChannel, the voice flags, the uplink slot and the chat scope of
our channel follow.
A Signal{speaking} of the host is believed (TalkTracker::hint) until the host
says it is over: that is how a talker whose packets are no Opus is shown as
talking. The documentation of LinkEvent::Talking, OwnChannel and
Connected.own_client says what the adapter derives and what it does not.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
311 lines
11 KiB
Rust
311 lines
11 KiB
Rust
//! Voice across the seam, engine side (`docs/session-seam.md` section 6.1):
|
|
//! our encoded frames as RTP on our voice slot, the RTP of other slots as
|
|
//! the audio thread's packets, and who is talking from the media.
|
|
//!
|
|
//! `voelin-audio`'s [`EncodedVoice`] and [`VoicePacket`] stay what the audio
|
|
//! thread speaks; this is the framing in the v1 media codec
|
|
//! (`voelin_proto::media`, protocol section 6).
|
|
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::time::{Duration, Instant};
|
|
|
|
use bytes::BytesMut;
|
|
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
|
|
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
|
|
use voelin_proto::media::opus::{self, Toc};
|
|
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
|
|
use voelin_proto::media::{RtpHeader, RtpView};
|
|
|
|
/// A talker is silent after this long without a packet.
|
|
pub(crate) const TALK_SILENCE: Duration = Duration::from_millis(400);
|
|
|
|
/// Our voice as RTP: the sequence number counts every packet from 0, the
|
|
/// timestamp starts at 0 and advances by the duration of the previous
|
|
/// packet, the marker is set on the first packet of a spurt, and the end of a
|
|
/// spurt is a packet with an empty payload, sent once.
|
|
#[derive(Default)]
|
|
pub(crate) struct Uplink {
|
|
sequence: u16,
|
|
timestamp: u32,
|
|
/// The ticks the last voice packet spans.
|
|
ticks: u32,
|
|
in_spurt: bool,
|
|
}
|
|
|
|
impl Uplink {
|
|
/// `voice` as the RTP packet of our voice slot.
|
|
pub(crate) fn frame(&mut self, slot: u32, voice: &EncodedVoice) -> Option<MediaPacket> {
|
|
let flow = FlowId::new(slot, voice_sub::CHANNEL);
|
|
// The previous packet's duration has passed.
|
|
self.timestamp = self.timestamp.wrapping_add(self.ticks);
|
|
let end = voice.is_end();
|
|
let mut header = RtpHeader::new(PT_OPUS, self.sequence, self.timestamp);
|
|
header.marker = !end && !self.in_spurt;
|
|
self.ticks =
|
|
if end { 0 } else { opus::packet_ticks(&voice.payload).unwrap_or(OPUS_20_MS_TICKS) };
|
|
self.in_spurt = !end;
|
|
self.sequence = self.sequence.wrapping_add(1);
|
|
let mut out = BytesMut::with_capacity(header.encoded_len() + voice.payload.len());
|
|
header.write(flow, &mut out).ok()?;
|
|
out.extend_from_slice(&voice.payload);
|
|
Some(MediaPacket { flow, rtp: out.freeze() })
|
|
}
|
|
}
|
|
|
|
/// A voice packet of some slot, taken from its RTP.
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
pub(crate) struct Incoming {
|
|
pub(crate) slot: u32,
|
|
/// Sent on a whisper sub-flow (1 to 6).
|
|
pub(crate) whisper: bool,
|
|
pub(crate) sequence: u16,
|
|
pub(crate) codec: VoiceCodec,
|
|
/// Empty: the spurt ends.
|
|
pub(crate) payload: Vec<u8>,
|
|
}
|
|
|
|
impl Incoming {
|
|
/// Parse a media packet. `None` for what is not the voice of a slot:
|
|
/// feedback, probes, a flow that is no media, a packet that is no RTP.
|
|
pub(crate) fn parse(packet: &MediaPacket) -> Option<Incoming> {
|
|
if !packet.flow.is_media() {
|
|
return None;
|
|
}
|
|
let view = RtpView::parse(&packet.rtp).ok()?;
|
|
let payload = view.payload();
|
|
// Stereo Opus is music; the jitter buffer decodes both the same way.
|
|
let codec = match Toc::parse(payload) {
|
|
Ok(toc) if toc.stereo() => VoiceCodec::Music,
|
|
_ => VoiceCodec::Voice,
|
|
};
|
|
Some(Incoming {
|
|
slot: packet.flow.slot(),
|
|
whisper: (voice_sub::FIRST_TALK_TARGET..=voice_sub::LAST_TALK_TARGET)
|
|
.contains(&packet.flow.sub()),
|
|
sequence: view.sequence(),
|
|
codec,
|
|
payload: payload.to_vec(),
|
|
})
|
|
}
|
|
|
|
/// The packet for the audio thread, from `talker`.
|
|
pub(crate) fn voice(self, talker: u16) -> VoicePacket {
|
|
VoicePacket {
|
|
talker: TalkerId(talker),
|
|
seq: self.sequence,
|
|
codec: self.codec,
|
|
whisper: self.whisper,
|
|
payload: self.payload,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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<u16, Instant>,
|
|
hinted: HashSet<u16>,
|
|
}
|
|
|
|
impl TalkTracker {
|
|
/// A packet of `client` arrived; whether this starts its talking.
|
|
pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool {
|
|
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.
|
|
pub(crate) fn expire(&mut self, now: Instant) -> Vec<u16> {
|
|
let mut silent: Vec<u16> = self
|
|
.last
|
|
.iter()
|
|
.filter(|(_, last)| now.saturating_duration_since(**last) >= TALK_SILENCE)
|
|
.map(|(client, _)| *client)
|
|
.collect();
|
|
silent.sort_unstable();
|
|
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.hinted.contains(&client)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
/// 20 ms of CELT, mono, one frame.
|
|
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
|
|
|
|
fn voice(payload: &[u8]) -> EncodedVoice {
|
|
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
|
|
}
|
|
|
|
fn view(packet: &MediaPacket) -> RtpView<'_> {
|
|
RtpView::parse(&packet.rtp).unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn our_voice_is_sequenced_stamped_and_marked() {
|
|
let mut up = Uplink::default();
|
|
let first = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
|
let second = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
|
assert_eq!((first.flow.slot(), first.flow.sub()), (8, 0));
|
|
let (a, b) = (view(&first), view(&second));
|
|
assert_eq!((a.sequence(), a.timestamp(), a.marker()), (0, 0, true));
|
|
assert_eq!((b.sequence(), b.timestamp(), b.marker()), (1, OPUS_20_MS_TICKS, false));
|
|
assert_eq!((a.ssrc(), a.payload_type()), (first.flow.0, PT_OPUS));
|
|
assert_eq!(a.payload(), OPUS_20_MS);
|
|
}
|
|
|
|
#[test]
|
|
fn the_end_is_one_empty_packet_and_the_next_spurt_has_a_marker() {
|
|
let mut up = Uplink::default();
|
|
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
|
let end = up.frame(8, &voice(&[])).unwrap();
|
|
assert!(view(&end).payload().is_empty() && !view(&end).marker());
|
|
assert_eq!(view(&end).sequence(), 1);
|
|
let next = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
|
assert!(view(&next).marker());
|
|
assert_eq!(view(&next).sequence(), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn the_sequence_wraps() {
|
|
let mut up = Uplink { sequence: u16::MAX, ..Default::default() };
|
|
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
|
let wrapped = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
|
|
assert_eq!(view(&wrapped).sequence(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn received_voice_is_split_into_slot_sub_flow_sequence_and_codec() {
|
|
let flow = FlowId::new(9, 0);
|
|
let mut header = RtpHeader::new(PT_OPUS, 513, 0);
|
|
header.marker = true;
|
|
let mut rtp = BytesMut::new();
|
|
header.write(flow, &mut rtp).unwrap();
|
|
rtp.extend_from_slice(&OPUS_20_MS);
|
|
let packet = MediaPacket { flow, rtp: rtp.freeze() };
|
|
let got = Incoming::parse(&packet).unwrap();
|
|
assert_eq!(
|
|
got,
|
|
Incoming {
|
|
slot: 9,
|
|
whisper: false,
|
|
sequence: 513,
|
|
codec: VoiceCodec::Voice,
|
|
payload: OPUS_20_MS.to_vec()
|
|
}
|
|
);
|
|
let voice = got.voice(8);
|
|
assert_eq!((voice.talker, voice.seq, voice.whisper), (TalkerId(8), 513, false));
|
|
}
|
|
|
|
#[test]
|
|
fn whispers_stereo_ends_and_what_is_no_voice() {
|
|
let packet = |flow: FlowId, payload: &[u8]| {
|
|
let mut rtp = BytesMut::new();
|
|
RtpHeader::new(PT_OPUS, 1, 0).write(flow, &mut rtp).unwrap();
|
|
rtp.extend_from_slice(payload);
|
|
MediaPacket { flow, rtp: rtp.freeze() }
|
|
};
|
|
assert!(Incoming::parse(&packet(FlowId::new(9, 3), &OPUS_20_MS)).unwrap().whisper);
|
|
assert!(!Incoming::parse(&packet(FlowId::new(9, 7), &OPUS_20_MS)).unwrap().whisper);
|
|
let stereo = [OPUS_20_MS[0] | 0x04, 1, 2];
|
|
assert_eq!(
|
|
Incoming::parse(&packet(FlowId::new(9, 0), &stereo)).unwrap().codec,
|
|
VoiceCodec::Music
|
|
);
|
|
let end = Incoming::parse(&packet(FlowId::new(9, 0), &[])).unwrap();
|
|
assert!(end.payload.is_empty() && end.voice(8).is_end());
|
|
// Feedback and probes are no voice.
|
|
assert!(
|
|
Incoming::parse(&MediaPacket { flow: FlowId::FEEDBACK, rtp: Default::default() })
|
|
.is_none()
|
|
);
|
|
assert!(
|
|
Incoming::parse(&MediaPacket { flow: FlowId::PROBE, rtp: Default::default() })
|
|
.is_none()
|
|
);
|
|
assert!(
|
|
Incoming::parse(&MediaPacket { flow: FlowId::new(9, 0), rtp: vec![1, 2].into() })
|
|
.is_none()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_talker_starts_with_a_packet_and_stops_400_ms_after_its_last() {
|
|
let mut talk = TalkTracker::default();
|
|
let t0 = Instant::now();
|
|
assert!(talk.heard(8, t0));
|
|
assert!(!talk.heard(8, t0 + Duration::from_millis(100)), "already talking");
|
|
assert!(talk.heard(9, t0 + Duration::from_millis(150)));
|
|
assert!(talk.is_talking(8));
|
|
// 399 ms after 8's last packet: still talking.
|
|
assert!(talk.expire(t0 + Duration::from_millis(499)).is_empty());
|
|
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [8]);
|
|
assert!(!talk.is_talking(8) && talk.is_talking(9));
|
|
assert_eq!(talk.expire(t0 + Duration::from_millis(551)), [9]);
|
|
// 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));
|
|
}
|
|
}
|