Files
client/core/examples/duplex_qa.rs
T

815 lines
37 KiB
Rust

//! Exercise the compiled diagnostic core's real TeamSpeak voice path over stdio.
//! Build with `cargo build --locked -p teamspeach-core --bin teamspeach-core` and set
//! `TEAMSPEACH_QA_CORE` to the absolute path of that disposable core executable.
//! Duplex: `cargo run --locked -p teamspeach-core --example duplex_qa`.
//! Whisper: `cargo run --locked -p teamspeach-core --example duplex_qa -- --whisper`.
//! Requires an already running, private TeamSpeak fixture at 127.0.0.1:19987 with
//! an empty default Opus channel (TS6 beta14 for whisper). No server or audio device is started.
//! Playback timing uses monotonic send and receive observations: stdio PCM
//! events do not carry a timestamp. This is not a device latency test.
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitCode, Stdio};
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use base64::{engine::general_purpose::STANDARD, Engine as _};
use serde_json::{json, Value};
const SERVER: &str = "127.0.0.1:19987";
const SAMPLE_RATE: f64 = 48_000.0;
const SAMPLES: usize = 960;
const FRAME: Duration = Duration::from_millis(20);
// The stdio writer prefers control events to already-queued playback frames.
const PLAYBACK_TAIL_FRAMES: u32 = 10; // core/src/output.rs PCM_CAPACITY
const GATE_OBSERVATION: Duration = Duration::from_millis(260);
const CONTROL: Duration = Duration::from_secs(5);
const CONNECT: Duration = Duration::from_secs(12);
const HZ: [u16; 5] = [650, 1150, 900, 1450, 1750];
const A_TONE: usize = 0;
const B_TONE: usize = 1;
const MUTED_TONE: usize = 2;
const OLD_TONE: usize = 3;
const NEW_TONE: usize = 4;
const INITIAL_EPOCH: u32 = 1;
const DENIED_EPOCH: u32 = 2;
const RESTORED_EPOCH: u32 = 3;
// Indexed by tone. The stale 1450 Hz probe reuses the stopped 1150 Hz route's tag.
const WHISPER_TAGS: [Option<u32>; HZ.len()] = [
Some(INITIAL_EPOCH), Some(RESTORED_EPOCH), Some(DENIED_EPOCH), Some(RESTORED_EPOCH), None,
];
type Result<T, E = String> = std::result::Result<T, E>;
struct Tone {
basis: Box<[(f64, f64)]>,
input: Arc<str>,
}
impl Tone {
fn new(hz: u16, whisper: Option<u32>) -> Self {
// These frequencies are integral DFT bins for 20 ms, so repeating a block
// keeps phase continuous. Use both quadratures to tolerate codec delay.
let basis = (0..SAMPLES).map(|i| {
(std::f64::consts::TAU * f64::from(hz) * i as f64 / SAMPLE_RATE).sin_cos()
}).collect::<Vec<_>>().into_boxed_slice();
let mut pcm = vec![0; SAMPLES * 2];
for (bytes, &(sin, _)) in pcm.chunks_exact_mut(2).zip(basis.iter()) {
bytes.copy_from_slice(&((sin * 12_000.0) as i16).to_le_bytes());
}
let mut args = json!({"pcm": STANDARD.encode(pcm)});
if let Some(epoch) = whisper {
args["whisper"] = json!(epoch);
}
let input = format!("{}\n", json!({"cmd": "audio_frame", "args": args})).into();
Self { basis, input }
}
}
fn detect_tone(encoded: &str, tones: &[Tone; HZ.len()], bytes: &mut [u8], pcm: &mut [f64]) -> Result<Option<usize>> {
if STANDARD.decode_slice(encoded, bytes).ok() != Some(bytes.len()) {
return Err("playback event did not carry one 20 ms s16le frame".into());
}
for (sample, bytes) in pcm.iter_mut().zip(bytes.chunks_exact(2)) {
*sample = f64::from(i16::from_le_bytes([bytes[0], bytes[1]]));
}
let energy: f64 = pcm.iter().map(|n| n * n).sum();
if energy < 450.0_f64.powi(2) * SAMPLES as f64 {
return Ok(None);
}
Ok(tones.iter().position(|tone| {
let (s, c) = pcm.iter().zip(tone.basis.iter()).fold((0.0, 0.0), |(s, c), (x, (sin, cos))| {
(s + x * sin, c + x * cos)
});
// At least 60% of the signal energy must fall in this one bin. No two
// candidates can satisfy the threshold; noise and silent PLC cannot pass.
2.0 * (s * s + c * c) >= 0.60 * energy * SAMPLES as f64
}))
}
struct Line {
at: Instant,
value: Value,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Seen {
Playback { from: u64, tone: Option<usize> },
RemoteStarted(u64),
RemoteStopped,
WhisperReceived(u64),
LocalStarted,
Muted,
Offline,
}
#[derive(Clone, Copy)]
enum ReceiveGate {
Open,
Closed,
Draining { speaker: u64, tone: usize, stopped_at: Instant },
}
struct Peer {
label: &'static str,
child: Child,
input: Option<mpsc::SyncSender<Arc<str>>>,
written: mpsc::Receiver<bool>,
output: mpsc::Receiver<Line>,
request_number: u32,
snapshot: Value,
state: Option<&'static str>,
state_changes: usize,
transmitting: bool,
talking: Option<u64>,
seen: Vec<(Instant, Seen)>,
decode_bytes: Box<[u8]>,
decode_pcm: Box<[f64]>,
}
impl Peer {
fn start(label: &'static str, exe: &Path, root: &Path) -> Result<Self> {
let mut child = Command::new(exe)
.arg("--data-dir").arg(root.join(label))
.current_dir(root)
.env("TEAMSPEACH_LOG", "off")
.env("TMP", root).env("TEMP", root).env("TMPDIR", root)
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
.spawn().map_err(|e| format!("{label}: could not start core ({:?})", e.kind()))?;
let mut stdin = child.stdin.take().expect("piped stdin");
let stdout = child.stdout.take().expect("piped stdout");
let (input, outgoing) = mpsc::sync_channel::<Arc<str>>(1);
let (ack, written) = mpsc::sync_channel(1);
let (incoming, output) = mpsc::sync_channel(256);
let start_read = thread::Builder::new().spawn(move || {
for line in BufReader::new(stdout).lines() {
let at = Instant::now();
let Ok(value) = line.and_then(|text| serde_json::from_str(&text).map_err(std::io::Error::other)) else {
break;
};
if incoming.try_send(Line { at, value }).is_err() {
break;
}
}
});
let start_write = thread::Builder::new().spawn(move || {
while let Ok(line) = outgoing.recv() {
let ok = stdin.write_all(line.as_bytes()).is_ok();
if ack.send(ok).is_err() || !ok {
break;
}
}
});
let peer = Self {
label, child, input: Some(input), written, output, request_number: 0, snapshot: Value::Null,
state: None, state_changes: 0, transmitting: false, talking: None, seen: Vec::new(),
decode_bytes: vec![0; SAMPLES * 2].into_boxed_slice(),
decode_pcm: vec![0.0; SAMPLES].into_boxed_slice(),
};
if start_read.is_err() || start_write.is_err() {
return Err(format!("{label}: could not start pipe workers"));
}
let ready = peer.read_before(Instant::now() + CONTROL, "ready")?;
if ready.value["event"] != "ready" || ready.value["protocol"] != 1 {
return Err(format!("{label}: expected protocol 1 ready event"));
}
Ok(peer)
}
fn write_before(&self, line: Arc<str>, deadline: Instant) -> Result<()> {
if Instant::now() >= deadline || self.input.as_ref().is_none_or(|input| input.try_send(line).is_err())
|| self.written.recv_timeout(deadline.saturating_duration_since(Instant::now())) != Ok(true)
{
return Err(format!("{}: core stdin write failed or timed out", self.label));
}
Ok(())
}
fn read_before(&self, deadline: Instant, stage: &str) -> Result<Line> {
let now = Instant::now();
if now >= deadline {
return Err(format!("{}: {stage} timed out", self.label));
}
self.output.recv_timeout(deadline - now)
.map_err(|e| format!("{}: {stage}: core stdout {e}", self.label))
}
fn request(&mut self, tones: &[Tone; HZ.len()], cmd: &str, args: Value, timeout: Duration) -> Result<Value> {
let deadline = Instant::now() + timeout;
self.request_number += 1;
let id = self.request_number.to_string();
let line = format!("{}\n", json!({"id": &id, "cmd": cmd, "args": args}));
self.write_before(line.into(), deadline)?;
loop {
let line = self.read_before(deadline, cmd)?;
if line.value["id"].as_str() == Some(id.as_str()) {
if line.value["ok"] != true {
return Err(format!("{}: core rejected {cmd}", self.label));
}
return Ok(line.value["result"].clone());
}
self.observe(tones, line)?;
}
}
fn observe(&mut self, tones: &[Tone; HZ.len()], Line { at, value }: Line) -> Result<()> {
let seen = match value["event"].as_str() {
Some("snapshot") => {
// A departed client disappears from the book and its decoder
// is evicted without necessarily emitting talking:false.
if let (Some(speaker), Some(clients)) = (self.talking, value["clients"].as_array()) {
if !clients.iter().any(|client| client["id"].as_u64() == Some(speaker)) {
self.talking = None;
}
}
self.snapshot = value;
None
}
Some("state") => {
self.state_changes += 1;
self.state = match value["state"].as_str() {
Some("connecting") => Some("connecting"),
Some("connected") => Some("connected"),
Some("disconnecting") => Some("disconnecting"),
Some("disconnected") => Some("disconnected"),
_ => return Err(format!("{}: invalid connection state", self.label)),
};
None
}
Some("audio_state") => {
let started = !self.transmitting && value["transmitting"] == true;
self.transmitting = value["transmitting"] == true;
started.then_some(Seen::LocalStarted)
}
Some("talking") => {
let from = value["client_id"].as_u64().ok_or("talking event without client ID")?;
if value["talking"] == true {
self.talking = Some(from);
Some(Seen::RemoteStarted(from))
} else {
if self.talking == Some(from) {
self.talking = None;
}
Some(Seen::RemoteStopped)
}
}
Some("whisper_received") => {
let from = value["client_id"].as_u64().ok_or("whisper_received without client ID")?;
Some(Seen::WhisperReceived(from))
}
Some("audio") => {
let from = value["speakers"].as_array().filter(|s| s.len() == 1)
.and_then(|s| s[0].as_u64()).ok_or("expected exactly one decoded speaker")?;
let pcm = value["pcm"].as_str().ok_or("playback event without PCM")?;
let tone = detect_tone(pcm, tones, &mut self.decode_bytes, &mut self.decode_pcm)?;
Some(Seen::Playback { from, tone })
}
Some("error") => match value["error"]["code"].as_str() {
Some("audio_muted") => Some(Seen::Muted),
Some("not_connected") => Some(Seen::Offline),
Some("audio_codec" | "audio_codec_unsupported" | "audio_format" | "audio_overflow") => {
return Err(format!("{}: core reported a voice codec, format, or queue error", self.label));
}
_ => None,
},
_ => None,
};
if let Some(seen) = seen {
self.seen.push((at, seen));
}
Ok(())
}
fn pump(&mut self, tones: &[Tone; HZ.len()]) -> Result<()> {
for _ in 0..256 {
match self.output.try_recv() {
Ok(line) => self.observe(tones, line)?,
Err(mpsc::TryRecvError::Empty) => return Ok(()),
Err(mpsc::TryRecvError::Disconnected) => return Err(format!("{}: core stdout stopped", self.label)),
}
}
Err(format!("{}: core stdout exceeded the observation bound", self.label))
}
fn shutdown(&mut self, tones: &[Tone; HZ.len()]) -> Result<()> {
self.request(tones, "shutdown", json!({}), CONTROL)?;
let deadline = Instant::now() + CONTROL;
while Instant::now() < deadline {
match self.child.try_wait() {
Ok(Some(status)) if status.success() => return Ok(()),
Ok(Some(_)) | Err(_) => return Err(format!("{}: core did not exit cleanly", self.label)),
Ok(None) => thread::sleep(Duration::from_millis(10)),
}
}
Err(format!("{}: core did not exit by its deadline", self.label))
}
}
impl Drop for Peer {
fn drop(&mut self) {
// EOF lets the real core dispose of a still-connected session on failure.
drop(self.input.take());
let deadline = Instant::now() + Duration::from_secs(4);
while matches!(self.child.try_wait(), Ok(None)) && Instant::now() < deadline {
thread::sleep(Duration::from_millis(10));
}
if matches!(self.child.try_wait(), Ok(None)) && self.child.kill().is_ok() {
let deadline = Instant::now() + CONTROL;
while matches!(self.child.try_wait(), Ok(None)) && Instant::now() < deadline {
thread::sleep(Duration::from_millis(10));
}
}
}
}
struct Duplex {
a: Peer,
b: Peer,
tones: [Tone; HZ.len()],
}
#[derive(Clone, Copy)]
struct Receipt {
first: Instant,
last: Instant,
frames: usize,
}
struct Burst {
first: Instant,
last: Instant,
}
impl Duplex {
fn open(exe: &Path, root: &Path, tags: [Option<u32>; HZ.len()]) -> Result<Self> {
let mut qa = Self {
a: Peer::start("a", exe, root)?, b: Peer::start("b", exe, root)?,
tones: std::array::from_fn(|i| Tone::new(HZ[i], tags[i])),
};
for peer in [&mut qa.a, &mut qa.b] {
let empty = peer.request(&qa.tones, "profile_get", json!({}), CONTROL)?;
if empty["exists"] != false {
return Err(format!("{}: profile was not empty", peer.label));
}
let nickname = format!("PeachQA-{}-{}", std::process::id(), peer.label);
peer.request(&qa.tones, "profile_create", json!({"nickname": nickname}), CONTROL)?;
}
Ok(qa)
}
fn connect(peer: &mut Peer, tones: &[Tone; HZ.len()]) -> Result<u64> {
let response = peer.request(tones, "connect", json!({"address": SERVER}), CONNECT)?;
if peer.state != Some("connected") {
return Err(format!("{}: connect did not reach connected state", peer.label));
}
response["own_client_id"].as_u64().ok_or_else(|| format!("{}: missing own client ID", peer.label))
}
fn party(&mut self, a_id: u64, b_id: u64) -> Result<()> {
let isolated = |peer: &Peer, own: u64, other: u64| {
let snap = &peer.snapshot;
snap["own_client_id"].as_u64() == Some(own) && snap["own_channel_id"].as_u64().is_some_and(|channel| {
snap["channels"].as_array().is_some_and(|channels| channels.iter().any(|c| {
c["id"].as_u64() == Some(channel) && matches!(c["codec"].as_str(), Some("opus_voice" | "opus_music"))
})) && snap["clients"].as_array().is_some_and(|clients| {
let mut ids = clients.iter().filter(|c| c["channel_id"].as_u64() == Some(channel)
&& c["client_type"] == "normal").filter_map(|c| c["id"].as_u64());
matches!((ids.next(), ids.next(), ids.next()), (Some(i), Some(j), None)
if (i == own && j == other) || (i == other && j == own))
})
})
};
self.wait_until("both peers in an isolated Opus channel", CONTROL, |qa| {
a_id != b_id && isolated(&qa.a, a_id, b_id) && isolated(&qa.b, b_id, a_id)
})
}
fn pump(&mut self) -> Result<()> {
self.a.pump(&self.tones)?;
self.b.pump(&self.tones)
}
fn wait_until(&mut self, stage: &str, duration: Duration, ready: impl Fn(&Self) -> bool) -> Result<()> {
let deadline = Instant::now() + duration;
loop {
self.pump()?;
if ready(self) {
return Ok(());
}
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(format!("timed out waiting for {stage}"));
}
thread::sleep(remaining.min(Duration::from_millis(5)));
}
}
fn observe_for(&mut self, duration: Duration) -> Result<()> {
let deadline = Instant::now() + duration;
self.wait_until("observation window", duration + CONTROL, |_| Instant::now() >= deadline)
}
fn burst(&mut self, a: Option<usize>, b: Option<usize>, frames: u32) -> Result<Burst> {
let first = Instant::now();
let deadline = first + FRAME * frames + Duration::from_secs(1);
let mut due = first;
let mut last = first;
for _ in 0..frames {
thread::sleep(due.saturating_duration_since(Instant::now()));
let now = Instant::now();
if now >= deadline || now.saturating_duration_since(due) > Duration::from_millis(100) {
return Err("local source missed its real-time pacing deadline".into());
}
let write_deadline = (now + Duration::from_millis(100)).min(deadline);
for (peer, tone) in [(&self.a, a), (&self.b, b)] {
if let Some(tone) = tone {
peer.write_before(self.tones[tone].input.clone(), write_deadline)?;
}
}
// Never send extra frames to catch up after a scheduling slip.
last = now;
due = Instant::now() + FRAME;
self.pump()?;
}
Ok(Burst { first, last })
}
fn receipt(peer: &Peer, phase: &str, from: u64, expected: usize, since: Instant) -> Result<Receipt> {
let mut found: Option<Receipt> = None;
let mut remote_started = false;
for &(at, seen) in peer.seen.iter().filter(|(at, _)| *at >= since) {
match seen {
Seen::RemoteStarted(id) if id == from => remote_started = true,
Seen::RemoteStarted(_) => {
return Err(format!("{phase}: {}: talking start from the wrong peer; {}",
peer.label, Self::evidence(peer, since)));
}
Seen::Playback { from: id, tone } => {
if id != from || tone.is_some_and(|tone| tone != expected) {
return Err(format!("{phase}: {}: expected {} Hz from the sending peer, got {:?} Hz (sender match: {}); {}",
peer.label, HZ[expected], tone.map(|tone| HZ[tone]), id == from, Self::evidence(peer, since)));
}
if tone == Some(expected) {
let receipt = found.get_or_insert(Receipt { first: at, last: at, frames: 0 });
receipt.last = at;
receipt.frames += 1;
}
}
_ => {}
}
}
if let Some(r) = found {
if remote_started && r.frames >= 12 && r.first - since <= Duration::from_millis(550)
&& r.last - r.first >= Duration::from_millis(240)
{
return Ok(r);
}
}
Err(format!("{phase}: {}: expected sustained {} Hz from the sending peer with timely onset ({} matching frames); {}",
peer.label, HZ[expected], found.map_or(0, |r| r.frames), Self::evidence(peer, since)))
}
fn evidence(peer: &Peer, since: Instant) -> String {
let mut tones = [0usize; HZ.len()];
let (mut unknown, mut starts, mut stops, mut whispers, mut tx_starts, mut muted, mut offline) = (0, 0, 0, 0, 0, 0, 0);
for &(_, seen) in peer.seen.iter().filter(|(at, _)| *at >= since) {
match seen {
Seen::Playback { tone: Some(tone), .. } => tones[tone] += 1,
Seen::Playback { tone: None, .. } => unknown += 1,
Seen::RemoteStarted(_) => starts += 1,
Seen::RemoteStopped => stops += 1,
Seen::WhisperReceived(_) => whispers += 1,
Seen::LocalStarted => tx_starts += 1,
Seen::Muted => muted += 1,
Seen::Offline => offline += 1,
}
}
format!("decoded counts {tones:?} for {HZ:?} Hz, unclassified={unknown}, remote starts/stops={starts}/{stops}, whisper_received={whispers}, local starts={tx_starts}, rejected muted/offline={muted}/{offline}, currently talking/transmitting={}/{}",
peer.talking.is_some(), peer.transmitting)
}
fn check_gate(peer: &Peer, phase: &str, since: Instant, block_local: bool, receive: ReceiveGate) -> Result<()> {
let block_remote = !matches!(receive, ReceiveGate::Open);
let mut permitted_tail = 0;
let mut blocked_events = 0;
for &(at, seen) in peer.seen.iter().filter(|(at, _)| *at >= since) {
let forbidden = match seen {
Seen::LocalStarted => block_local,
Seen::RemoteStarted(_) | Seen::WhisperReceived(_) => block_remote,
Seen::Playback { from, tone } => match receive {
ReceiveGate::Open => false,
ReceiveGate::Closed => true,
ReceiveGate::Draining { speaker, tone: old_tone, stopped_at } => {
// No new probe plays in this phase. Same-speaker PCM can
// trail the stop/departure control message; enforce the
// queue depth and require a quiet end to the window.
if from != speaker || tone.is_some_and(|tone| tone != old_tone) {
true
} else if at >= stopped_at {
permitted_tail += 1;
permitted_tail > PLAYBACK_TAIL_FRAMES || at - stopped_at > FRAME * PLAYBACK_TAIL_FRAMES
} else {
false
}
}
},
Seen::RemoteStopped | Seen::Muted | Seen::Offline => false,
};
if forbidden {
blocked_events += 1;
}
}
if blocked_events > 0 || (block_local && peer.transmitting) || (block_remote && peer.talking.is_some()) {
return Err(format!("{phase}: {}: unexpected voice activity ({blocked_events} forbidden events, {permitted_tail} candidate queued tail frames); {}",
peer.label, Self::evidence(peer, since)));
}
Ok(())
}
fn release(&mut self, last_frame: Instant) -> Result<()> {
// The 200 ms idle timeout must not satisfy explicit local release.
let deadline = last_frame + Duration::from_millis(185);
for peer in [&self.a, &self.b] {
peer.write_before(Arc::from("{\"cmd\":\"audio_end\"}\n"), deadline)?;
}
self.wait_until("explicit transmit stop", deadline.saturating_duration_since(Instant::now()), |qa| {
!qa.a.transmitting && !qa.b.transmitting
})?;
if Instant::now() >= deadline {
return Err("local transmission did not stop before the idle timeout".into());
}
// The remote jitter buffers are allowed to finish separately.
self.wait_until("voice end", Duration::from_millis(750), |qa| {
qa.a.talking.is_none() && qa.b.talking.is_none()
})
}
fn mute_a(&mut self, on: bool) -> Result<()> {
let result = self.a.request(&self.tones, "set_audio", json!({"input_muted": on}), CONTROL)?;
if result["input_muted"] != on || result["output_muted"] != false {
return Err("input-mute acknowledgement did not preserve output".into());
}
Ok(())
}
fn disconnect(peer: &mut Peer, tones: &[Tone; HZ.len()]) -> Result<bool> {
let result = peer.request(tones, "disconnect", json!({}), CONTROL)?;
if peer.state != Some("disconnected") {
return Err(format!("{}: core did not reach disconnected state", peer.label));
}
result["clean"].as_bool().ok_or_else(|| format!("{}: missing disconnect acknowledgement", peer.label))
}
}
fn exercise(exe: &Path, root: &Path) -> Result<String> {
let mut qa = Duplex::open(exe, root, [None; HZ.len()])?;
let a_id = Duplex::connect(&mut qa.a, &qa.tones)?;
let b_id = Duplex::connect(&mut qa.b, &qa.tones)?;
qa.party(a_id, b_id)?;
// IPC direct-mode frames emulate a held PTT button; actual key handling is not part of stdio.
let started = qa.burst(Some(A_TONE), Some(B_TONE), 46)?;
let at_a = Duplex::receipt(&qa.a, "initial duplex", b_id, B_TONE, started.first)?;
let at_b = Duplex::receipt(&qa.b, "initial duplex", a_id, A_TONE, started.first)?;
let overlap = at_a.last.min(at_b.last).saturating_duration_since(at_a.first.max(at_b.first));
if overlap < Duration::from_millis(240) || !qa.a.transmitting || !qa.b.transmitting {
return Err("decoded voice was not sustained concurrently in both directions".into());
}
qa.release(started.last)?;
let released = Instant::now();
qa.observe_for(GATE_OBSERVATION)?;
Duplex::check_gate(&qa.a, "explicit release", released, true, ReceiveGate::Draining {
speaker: b_id, tone: B_TONE, stopped_at: released,
})?;
Duplex::check_gate(&qa.b, "explicit release", released, true, ReceiveGate::Draining {
speaker: a_id, tone: A_TONE, stopped_at: released,
})?;
qa.mute_a(true)?;
let muted = qa.burst(Some(MUTED_TONE), Some(B_TONE), 42)?;
Duplex::receipt(&qa.a, "input mute receive control", b_id, B_TONE, muted.first)?;
qa.release(muted.last)?;
qa.observe_for(Duration::from_millis(250))?;
let mute_phase = "input mute (900 Hz blocked marker)";
Duplex::check_gate(&qa.a, mute_phase, muted.first, true, ReceiveGate::Open)?;
Duplex::check_gate(&qa.b, mute_phase, muted.first, false, ReceiveGate::Closed)?;
if !qa.a.seen.iter().any(|&(at, seen)| at >= muted.first && seen == Seen::Muted) {
return Err(format!("{mute_phase}: no core input rejection; {}", Duplex::evidence(&qa.a, muted.first)));
}
qa.mute_a(false)?;
// Disconnect during a proven active spurt. Submit an unrelated marker to
// the same old core pipe while offline, then reuse that process on reconnect.
let resumed = qa.burst(Some(A_TONE), None, 42)?;
Duplex::receipt(&qa.b, "unmuted pre-disconnect voice", a_id, A_TONE, resumed.first)?;
if !qa.a.transmitting {
return Err("unmuted source was not transmitting at disconnect".into());
}
let first_confirmed = Duplex::disconnect(&mut qa.a, &qa.tones)?;
let offline_changes = qa.a.state_changes;
let disconnected = Instant::now();
qa.wait_until("old peer leaving the server", CONTROL, |qa| {
qa.b.snapshot["clients"].as_array().is_some_and(|clients| {
clients.iter().all(|client| client["id"].as_u64() != Some(a_id))
})
})?;
let departed = Instant::now();
qa.observe_for(GATE_OBSERVATION)?;
Duplex::check_gate(&qa.b, "disconnect drain (650 Hz prior voice)", disconnected, false, ReceiveGate::Draining {
speaker: a_id, tone: A_TONE, stopped_at: departed,
})?;
// Do not submit the blocked marker until the old remote stream and stdio
// queue have drained. Every frame after marker injection is forbidden.
let old = qa.burst(Some(OLD_TONE), None, 15)?.first;
let offline_phase = "old session (1450 Hz blocked marker)";
Duplex::check_gate(&qa.a, offline_phase, disconnected, true, ReceiveGate::Closed)?;
Duplex::check_gate(&qa.b, offline_phase, old, true, ReceiveGate::Closed)?;
if !qa.a.seen.iter().any(|&(at, seen)| at >= old && seen == Seen::Offline)
|| qa.a.state_changes != offline_changes
{
return Err(format!("{offline_phase}: no offline rejection or connection state changed; {}", Duplex::evidence(&qa.a, old)));
}
let a_id = Duplex::connect(&mut qa.a, &qa.tones)?;
qa.party(a_id, b_id)?;
qa.observe_for(Duration::from_millis(300))?;
let reconnect_phase = "reconnect before fresh input (1450 Hz must not replay)";
Duplex::check_gate(&qa.a, reconnect_phase, old, true, ReceiveGate::Closed)?;
Duplex::check_gate(&qa.b, reconnect_phase, old, true, ReceiveGate::Closed)?;
let fresh = qa.burst(Some(NEW_TONE), Some(B_TONE), 42)?;
Duplex::receipt(&qa.a, "fresh duplex after reconnect", b_id, B_TONE, fresh.first)?;
Duplex::receipt(&qa.b, "fresh duplex after reconnect", a_id, NEW_TONE, fresh.first)?;
qa.release(fresh.last)?;
let a_confirmed = Duplex::disconnect(&mut qa.a, &qa.tones)?;
let b_confirmed = Duplex::disconnect(&mut qa.b, &qa.tones)?;
qa.a.shutdown(&qa.tones)?;
qa.b.shutdown(&qa.tones)?;
let confirmed = [first_confirmed, a_confirmed, b_confirmed].into_iter().filter(|confirmed| *confirmed).count();
Ok(format!("Duplex IPC passed: A to B {} frames (first {} ms), B to A {} frames (first {} ms), {} ms overlap; release, input mute, disconnected rejection, and fresh voice after reconnect verified. Server confirmed {confirmed}/3 disconnects. No device audio.",
at_b.frames, (at_b.first - started.first).as_millis(), at_a.frames, (at_a.first - started.first).as_millis(), overlap.as_millis()))
}
fn set_whisper_receive(qa: &mut Duplex, mode: &str) -> Result<()> {
let ack = qa.b.request(&qa.tones, "set_whisper_receive", json!({"mode": mode}), CONTROL)?;
if ack["mode"] != mode {
return Err(format!("receiver did not acknowledge {mode}"));
}
Ok(())
}
fn whisper_spurt(qa: &mut Duplex, target_id: u64, target_uid: &str, tone: usize) -> Result<Burst> {
let epoch = WHISPER_TAGS[tone].ok_or("whisper probe must carry an epoch")?;
let ack = qa.a.request(&qa.tones, "whisper_start", json!({
"epoch": epoch,
"target": {"kind": "ids", "clients": [{"id": target_id, "uid": target_uid}], "channel_ids": []}
}), CONTROL)?;
if ack["epoch"] != epoch || ack["kind"] != "ids" || ack["client_ids"] != json!([target_id])
|| ack["channel_ids"] != json!([])
{
return Err("whisper_start did not acknowledge the exact direct route".into());
}
let burst = qa.burst(Some(tone), None, 42)?;
if !qa.a.transmitting || !qa.a.seen.iter().any(|&(at, seen)| at >= burst.first && seen == Seen::LocalStarted) {
return Err(format!("{} Hz whisper did not start transmitting; {}", HZ[tone], Duplex::evidence(&qa.a, burst.first)));
}
// A stop must actually close the live transmission, not follow its idle timeout.
let deadline = burst.last + Duration::from_millis(185);
let ack = qa.a.request(&qa.tones, "whisper_stop", json!({"epoch": epoch}),
deadline.saturating_duration_since(Instant::now()))?;
if ack["epoch"] != epoch || ack["stopped"] != true || qa.a.transmitting || Instant::now() >= deadline {
return Err("whisper_stop did not acknowledge and end the live epoch".into());
}
qa.wait_until("whisper playback end", Duration::from_millis(750), |qa| qa.b.talking.is_none())?;
qa.observe_for(GATE_OBSERVATION)?;
Ok(burst)
}
fn check_whisper_event(peer: &Peer, phase: &str, since: Instant, expected: Option<u64>) -> Result<()> {
let mut received = peer.seen.iter().filter_map(|&(at, seen)| match seen {
Seen::WhisperReceived(from) if at >= since => Some(from),
_ => None,
});
if received.next() != expected || received.next().is_some() {
return Err(format!("{phase}: unexpected whisper_received count or sender; {}", Duplex::evidence(peer, since)));
}
Ok(())
}
fn roster_uid(peer: &Peer, client_id: u64, is_self: bool) -> Option<&str> {
peer.snapshot["clients"].as_array()?.iter().find(|client| {
client["id"].as_u64() == Some(client_id) && client["is_self"].as_bool() == Some(is_self)
})?["uid"].as_str().filter(|uid| !uid.is_empty())
}
fn exercise_whisper(exe: &Path, root: &Path) -> Result<String> {
let mut qa = Duplex::open(exe, root, WHISPER_TAGS)?;
let a_id = Duplex::connect(&mut qa.a, &qa.tones)?;
let b_id = Duplex::connect(&mut qa.b, &qa.tones)?;
qa.party(a_id, b_id)?;
for peer in [&qa.a, &qa.b] {
let snapshot = &peer.snapshot;
let beta14 = snapshot["server"]["version"].as_str().is_some_and(|version| {
version.starts_with("6.") && version.split(|c: char| !c.is_ascii_alphanumeric())
.any(|part| part.eq_ignore_ascii_case("beta14"))
});
let in_default = snapshot["channels"].as_array().is_some_and(|channels| channels.iter().any(|c| {
c["id"] == snapshot["own_channel_id"] && c["is_default"] == true
}));
if !beta14 || !in_default {
return Err("whisper QA requires the loopback TS6 beta14 default channel".into());
}
}
// The server's live UID can differ from the local profile's key-derived UID.
// Match the receiver's own roster entry to the sender's view of that same client.
qa.wait_until("receiver UID in both rosters", CONTROL, |qa| {
roster_uid(&qa.b, b_id, true).is_some() && roster_uid(&qa.a, b_id, false).is_some()
})?;
let b_uid = roster_uid(&qa.b, b_id, true).ok_or("receiver self roster lacks a UID")?;
if roster_uid(&qa.a, b_id, false) != Some(b_uid) {
return Err("receiver UID does not match the sender's live roster".into());
}
let b_uid = b_uid.to_owned();
set_whisper_receive(&mut qa, "allow_all")?;
let initial = whisper_spurt(&mut qa, b_id, &b_uid, A_TONE)?;
let first = Duplex::receipt(&qa.b, "direct whisper", a_id, A_TONE, initial.first)?;
check_whisper_event(&qa.b, "direct whisper", initial.first, Some(a_id))?;
let denied = Instant::now();
set_whisper_receive(&mut qa, "deny_all")?;
whisper_spurt(&mut qa, b_id, &b_uid, MUTED_TONE)?;
Duplex::check_gate(&qa.b, "deny_all (900 Hz whisper)", denied, false, ReceiveGate::Closed)?;
set_whisper_receive(&mut qa, "allow_all")?;
let restored = whisper_spurt(&mut qa, b_id, &b_uid, B_TONE)?;
let again = Duplex::receipt(&qa.b, "restored allow_all", a_id, B_TONE, restored.first)?;
check_whisper_event(&qa.b, "restored allow_all", restored.first, Some(a_id))?;
// Both peers are still connected and receive policy is open. A fallback to either
// whisper or ordinary voice would be visible; the new tone cannot be the old audio tail.
let stale = qa.burst(Some(OLD_TONE), None, 24)?;
qa.observe_for(GATE_OBSERVATION)?;
let stale_phase = "stopped epoch (1450 Hz stale tag)";
Duplex::check_gate(&qa.a, stale_phase, stale.first, true, ReceiveGate::Closed)?;
Duplex::check_gate(&qa.b, stale_phase, stale.first, true, ReceiveGate::Closed)?;
let ordinary = qa.burst(Some(NEW_TONE), None, 42)?;
qa.release(ordinary.last)?;
qa.observe_for(GATE_OBSERVATION)?;
let voice = Duplex::receipt(&qa.b, "ordinary voice control", a_id, NEW_TONE, ordinary.first)?;
check_whisper_event(&qa.b, "ordinary voice control", ordinary.first, None)?;
let a_confirmed = Duplex::disconnect(&mut qa.a, &qa.tones)?;
let b_confirmed = Duplex::disconnect(&mut qa.b, &qa.tones)?;
qa.a.shutdown(&qa.tones)?;
qa.b.shutdown(&qa.tones)?;
let confirmed = [a_confirmed, b_confirmed].into_iter().filter(|confirmed| *confirmed).count();
Ok(format!("Whisper IPC passed: direct 650 Hz + whisper_received ({} frames); deny_all 900 Hz suppressed (no playback or whisper_received); restored allow_all 1150 Hz + whisper_received ({} frames); stale tag 1450 Hz dropped after stop (no ordinary voice); untagged 1750 Hz ordinary voice ({} frames, no whisper_received). Server confirmed {confirmed}/2 disconnects. No device audio.",
first.frames, again.frames, voice.frames))
}
fn run() -> Result<String> {
let mut args = std::env::args_os().skip(1);
let exercise = match (args.next(), args.next()) {
(None, None) => exercise,
(Some(flag), None) if flag == "--whisper" => exercise_whisper,
_ => return Err("usage: duplex_qa [--whisper]".into()),
};
let exe = std::env::var_os("TEAMSPEACH_QA_CORE").map(PathBuf::from)
.filter(|path| path.is_absolute() && path.is_file())
.ok_or("set TEAMSPEACH_QA_CORE to the absolute path of a compiled diagnostic core")?;
let stamp = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| "invalid system clock")?.as_nanos();
let root = std::env::temp_dir().join(format!("teamspeach-duplex-{}-{stamp}", std::process::id()));
if !root.is_absolute() {
return Err("system temporary directory must be absolute".into());
}
fs::create_dir(&root).map_err(|_| "could not create unique scratch directory")?;
let result = exercise(&exe, &root);
let cleaned = fs::remove_dir_all(&root).map_err(|_| "could not remove scratch profiles");
match (result, cleaned) {
(Ok(summary), Ok(())) => Ok(summary),
(Err(error), Ok(())) => Err(error),
(Ok(_), Err(cleanup)) => Err(cleanup.into()),
(Err(error), Err(cleanup)) => Err(format!("{error}; {cleanup}")),
}
}
fn main() -> ExitCode {
match run() {
Ok(summary) => {
println!("{summary}");
ExitCode::SUCCESS
}
Err(error) => {
eprintln!("duplex QA failed: {error}");
ExitCode::FAILURE
}
}
}