Test the voice path and the conformance suite on the fake host

link/fake_tests.rs holds the tests that need what is private to the crate:

- our voice leaves as RTP on the slot the host gave us (sequence, marker on
  the first packet of a spurt, timestamps that advance by the previous
  packet's duration, an end of spurt that is an empty payload sent once, the
  SSRC that is the flow), read from FakeHandle::sent_media;
- the voice of other slots reaches the audio thread: the talker of the slot,
  a whisper sub-flow, stereo Opus as music, the end of a spurt, and what is
  no voice of a known slot (an unknown slot, probes, feedback) dropped;
- the link conformance suite of the protocol repository, 17 cases, run
  against the session Backends::connect hands over: all pass, none skipped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-24 01:16:23 +03:00
1 parent f9d3f86896
commit 82da64d8d3
2 files changed
+303

No files matched your search

+301
View File
@@ -0,0 +1,301 @@
//! The engine's side of the seam against the protocol repository's fake host
//! (`docs/session-seam.md` sections 9.2 and 16): the voice path through a
//! `SessionLink` that talks to a `FakeSession`, and the link conformance
//! suite run against the session the engine's registry hands over.
//!
//! The tests that need only the engine's public API are in
//! `tests/session_fake.rs`; these need what is private to the crate: the
//! `LinkCmd`/`LinkEvent` vocabulary between `session.rs` and `SessionLink`,
//! the registry's `connect` and the context of a connector called outside an
//! engine.
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
use voelin_proto::link::{FlowId, MediaClass, MediaPacket, voice_sub};
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
use voelin_proto::media::{RtpHeader, RtpView};
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
use voelin_proto::test_util::{
FAKE_HOST_UID, FakeConnector, FakeHandle, connect_params, eventually,
};
use voelin_proto::v1::{self, entity::Kind};
use super::*;
const WAIT: Duration = Duration::from_secs(10);
/// An Opus frame of 20 ms, mono (TOC `0xf8`), and the same as stereo (`0xfc`).
const MONO: [u8; 3] = [0xf8, 0xff, 0xfe];
const STEREO: [u8; 3] = [0xfc, 0xff, 0xfe];
const ALICE: u32 = 50;
const ALICE_SLOT: u32 = 90;
const BOB: u32 = 51;
const BOB_SLOT: u32 = 91;
fn put(connector: &FakeConnector, kind: Kind) {
connector.host().put(v1::Entity { kind: Some(kind) }).expect("the fake host stores it");
}
/// A host with one server, a lobby, and alice and bob talking in it.
fn host() -> FakeConnector {
let connector = FakeConnector::new();
put(
&connector,
Kind::Server(v1::Server {
id: 1,
name: "Fake Host".into(),
uid: "fake-host".into(),
default_channel_id: 10,
..Default::default()
}),
);
put(
&connector,
Kind::Channel(v1::Channel {
id: 10,
server_id: 1,
kind: v1::ChannelKind::Voice as i32,
name: "Lobby".into(),
..Default::default()
}),
);
for (user, participant, slot, name) in
[(2, ALICE, ALICE_SLOT, "alice"), (3, BOB, BOB_SLOT, "bob")]
{
put(
&connector,
Kind::User(v1::User {
id: user,
uid: vec![user as u8; 32].into(),
uid_kind: v1::IdKind::Voelin as i32,
name: name.into(),
..Default::default()
}),
);
put(
&connector,
Kind::Voice(v1::VoiceState {
server_id: 1,
participant_id: participant,
user_id: user,
channel_id: 10,
slot,
nick: name.into(),
..Default::default()
}),
);
}
connector
}
/// A `SessionLink` over a fake host, driven the way `session.rs` drives it.
struct HostRig {
handle: FakeHandle,
cmds: mpsc::UnboundedSender<LinkCmd>,
events: mpsc::UnboundedReceiver<LinkEvent>,
/// Our voice slot, as the host gave it.
own_slot: u32,
/// The clients the link told started talking, in order.
talking: Vec<u16>,
}
/// The next event `f` picks from `events`, skipping the others.
async fn event_of<T>(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
mut f: impl FnMut(LinkEvent) -> Option<T>,
) -> T {
tokio::time::timeout(WAIT, async {
loop {
if let Some(t) = f(events.recv().await.expect("the link lives")) {
return t;
}
}
})
.await
.expect("an event in time")
}
impl HostRig {
async fn connect() -> Self {
let connector = host();
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let link = SessionLink::new(backends);
let (cmds, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
let ctx = LocalCtx::standalone().link;
link.spawn(ConnectOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
let own_client = event_of(&mut events, |e| match e {
LinkEvent::Connected { own_client, .. } => Some(own_client),
_ => None,
})
.await;
event_of(&mut events, |e| matches!(e, LinkEvent::OwnChannel(10)).then_some(())).await;
let own_slot = connector
.host()
.entities(&v1::Scope { kind: v1::ScopeKind::Live as i32, id: 1 })
.into_iter()
.find_map(|e| match e.kind? {
Kind::Voice(v) if v.participant_id == u32::from(own_client) => Some(v.slot),
_ => None,
})
.expect("the host seated us in voice");
let handle = connector.last_session().expect("the connector made a session");
Self { handle, cmds, events, own_slot, talking: Vec::new() }
}
/// The next voice packet the audio thread would get; who started to talk on
/// the way is kept in `talking`.
async fn audio(&mut self) -> VoicePacket {
let talking = &mut self.talking;
event_of(&mut self.events, |e| match e {
LinkEvent::Talking { client, talking: true } => {
talking.push(client);
None
}
LinkEvent::Audio(packet) => Some(packet),
_ => None,
})
.await
}
fn give(&self, cmd: LinkCmd) {
self.cmds.send(cmd).expect("the link listens");
}
}
/// A voice packet of `slot` on sub-flow `sub`, as a host delivers it.
fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket {
let flow = FlowId::new(slot, sub);
let mut out = bytes::BytesMut::new();
RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960)
.write(flow, &mut out)
.expect("a header");
out.extend_from_slice(payload);
MediaPacket { flow, rtp: out.freeze() }
}
fn voice(payload: &[u8]) -> EncodedVoice {
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
}
/// Our voice leaves as RTP on the slot the host gave us: the sequence counts
/// every packet, the timestamp advances by the duration of the previous one,
/// the marker is on the first packet of a spurt, the end of a spurt is an
/// empty payload sent once, and the SSRC is the flow (protocol section 6).
#[tokio::test(flavor = "multi_thread")]
async fn our_voice_is_rtp_on_the_slot_the_host_gave_us() {
let rig = HostRig::connect().await;
// The fake host loops accepted media back; this test looks at what left.
rig.handle.set_loopback(false);
for n in 1..=3 {
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, n])));
}
rig.give(LinkCmd::Audio(voice(&[])));
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, 9])));
let handle = rig.handle.clone();
eventually(WAIT, "the five packets", || handle.sent_media().len() == 5).await;
let flow = FlowId::new(rig.own_slot, voice_sub::CHANNEL);
let sent = rig.handle.sent_media();
let seen: Vec<_> = sent
.iter()
.map(|(class, packet)| {
let view = RtpView::parse(&packet.rtp).expect("RTP");
assert_eq!(*class, MediaClass::Voice);
assert_eq!(packet.flow, flow);
assert_eq!((view.payload_type(), view.ssrc()), (PT_OPUS, flow.0));
(view.sequence(), view.marker(), view.timestamp(), view.payload().to_vec())
})
.collect();
let ticks = OPUS_20_MS_TICKS;
assert_eq!(
seen,
[
(0, true, 0, vec![0xf8, 0xff, 0xfe, 1]),
(1, false, ticks, vec![0xf8, 0xff, 0xfe, 2]),
(2, false, 2 * ticks, vec![0xf8, 0xff, 0xfe, 3]),
// The end of the spurt: no payload, no marker, once.
(3, false, 3 * ticks, vec![]),
// The next spurt marks its first packet again.
(4, true, 3 * ticks, vec![0xf8, 0xff, 0xfe, 9]),
]
);
}
/// The RTP of other slots becomes the packets of the audio thread: the talker
/// is the participant of the slot, a whisper sub-flow is a whisper, a stereo
/// Opus frame is music, an empty payload ends the spurt; what is no voice of a
/// slot the host told about is dropped.
#[tokio::test(flavor = "multi_thread")]
async fn the_voice_of_other_slots_reaches_the_audio_thread() {
let mut rig = HostRig::connect().await;
let handle = rig.handle.clone();
// A slot nobody has, a probe and feedback: nothing. Then alice, mono.
handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &MONO));
handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) });
handle.inject_media(MediaPacket {
flow: FlowId::FEEDBACK,
rtp: bytes::Bytes::from_static(&[1, 2]),
});
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 5, &MONO));
let packet = rig.audio().await;
assert_eq!(
(packet.talker.0, packet.seq, packet.codec, packet.whisper, packet.payload.as_slice()),
(ALICE as u16, 5, VoiceCodec::Voice, false, MONO.as_slice())
);
// Bob whispers (sub-flow 1) in stereo: music, a whisper.
handle.inject_media(voice_packet(BOB_SLOT, 1, 6, &STEREO));
let packet = rig.audio().await;
assert_eq!(
(packet.talker.0, packet.seq, packet.codec, packet.whisper),
(BOB as u16, 6, VoiceCodec::Music, true)
);
// Alice stops: an empty payload.
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 7, &[]));
let packet = rig.audio().await;
assert_eq!((packet.talker.0, packet.seq, packet.payload.len()), (ALICE as u16, 7, 0));
// Who talks comes from the same packets: alice started, then bob, once each
// (the slot nobody has started nobody).
assert_eq!(rig.talking, [ALICE as u16, BOB as u16]);
}
/// The link conformance suite of the protocol repository against the session
/// the engine's registry hands over: the registry adds nothing to a plain
/// connector's session (`Backends::connect` returns it untouched), so the 17
/// cases pass as they do in the protocol repository, none skipped.
#[tokio::test(flavor = "multi_thread")]
async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
async fn through_the_registry() -> Fixture {
let connector = FakeConnector::new();
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let (params, media) = connect_params("fake://conformance");
let local = backends
.connect(params, LocalCtx::standalone())
.await
.unwrap_or_else(|e| panic!("the registry connects: {e}"));
assert_eq!(local.connected.host_uid, FAKE_HOST_UID, "the connector's own answer");
assert!(local.streams.is_none(), "a plain connector has no stream port");
let backend = connector.last_session().expect("the connector made a session");
// The session is the connector's own, so a request id means the same to both.
Fixture {
shared_request_ids: true,
..Fixture::new(local.connected.session, local.connected.pushes, media, backend)
}
}
let report = conformance::run(&through_the_registry).await;
assert_eq!(report.cases.len(), conformance::CASES.len());
assert_eq!(report.cases.len(), 17, "the suite of c8e0e5a has 17 cases");
assert!(
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
"{:?}",
report.cases
);
}
+2
View File
@@ -103,6 +103,8 @@
//! port for now.
mod backends;
#[cfg(test)]
mod fake_tests;
pub(crate) mod media;
pub(crate) mod project;
mod session_link;