//! Exercise the compiled diagnostic core's real TeamSpeak voice and stream control paths 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`. //! Stream registration and update: `cargo run --locked -p teamspeach-core --example duplex_qa -- --stream-lifecycle`. //! Requires an already running, private TeamSpeak fixture at 127.0.0.1:19987 with //! an empty default Opus channel (TS6 beta14 for whisper and stream registration). //! 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; HZ.len()] = [ Some(INITIAL_EPOCH), Some(RESTORED_EPOCH), Some(DENIED_EPOCH), Some(RESTORED_EPOCH), None, ]; type Result = std::result::Result; struct Tone { basis: Box<[(f64, f64)]>, input: Arc, } impl Tone { fn new(hz: u16, whisper: Option) -> 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::>().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> { 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(PartialEq, Eq)] enum Seen { Playback { from: u64, tone: Option }, RemoteStarted(u64), RemoteStopped, WhisperReceived(Value), 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>>, written: mpsc::Receiver, output: mpsc::Receiver, request_number: u32, snapshot: Value, state: Option<&'static str>, state_changes: usize, transmitting: bool, talking: Option, seen: Vec<(Instant, Seen)>, decode_bytes: Box<[u8]>, decode_pcm: Box<[f64]>, } impl Peer { fn start(label: &'static str, exe: &Path, root: &Path) -> Result { 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::>(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, 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 { 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 { let mut reply = self.request_reply(tones, cmd, args, timeout, |_| {})?; if reply["ok"] != true { return Err(format!("{}: core rejected {cmd}", self.label)); } Ok(reply.get_mut("result").map(std::mem::take).unwrap_or(Value::Null)) } fn request_reply(&mut self, tones: &[Tone; HZ.len()], cmd: &str, args: Value, timeout: Duration, mut inspect: impl FnMut(&Line)) -> Result { 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()) { return Ok(line.value); } inspect(&line); 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") => Some(Seen::WhisperReceived(value)), 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; HZ.len()]) -> Result { 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 { 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, b: Option, frames: u32) -> Result { 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 { let mut found: Option = None; let mut remote_started = false; for &(at, ref 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 &(_, ref 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, ref 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 { 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 { 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 start_whisper(qa: &mut Duplex, target_id: u64, target_uid: &str, epoch: u32) -> Result<()> { 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()); } Ok(()) } fn whisper_spurt(qa: &mut Duplex, target_id: u64, target_uid: &str, tone: usize) -> Result { let epoch = WHISPER_TAGS[tone].ok_or("whisper probe must carry an epoch")?; start_whisper(qa, target_id, target_uid, epoch)?; 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<&Value>) -> Result<()> { let mut received = peer.seen.iter().filter_map(|(at, seen)| match seen { Seen::WhisperReceived(event) if *at >= since => Some(event), _ => None, }); let matched = match (received.next(), expected) { (Some(actual), Some(expected)) => ["client_id", "generation", "uid", "nickname"] .into_iter().all(|key| actual[key] == expected[key]), (None, None) => true, _ => false, }; if !matched || received.next().is_some() { return Err(format!("{phase}: unexpected whisper_received count or sender identity; {}", Duplex::evidence(peer, since))); } Ok(()) } fn roster_identity(peer: &Peer, client_id: u64, is_self: bool) -> Option<(&str, &str)> { let client = peer.snapshot["clients"].as_array()?.iter().find(|client| { client["id"].as_u64() == Some(client_id) && client["is_self"].as_bool() == Some(is_self) })?; let uid = client["uid"].as_str().filter(|uid| !uid.is_empty())?; let nickname = client["nickname"].as_str().filter(|name| !name.is_empty())?; Some((uid, nickname)) } fn is_beta14_default(snapshot: &Value) -> bool { 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")) }) && snapshot["channels"].as_array().is_some_and(|channels| channels.iter().any(|c| { c["id"] == snapshot["own_channel_id"] && c["is_default"] == true })) } fn exercise_whisper(exe: &Path, root: &Path) -> Result { 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] { if !is_beta14_default(&peer.snapshot) { return Err("whisper QA requires the loopback TS6 beta14 default channel".into()); } } // Use independent live rosters, not the profile's key-derived UID or the receipt itself. qa.wait_until("peer identities in both rosters", CONTROL, |qa| { roster_identity(&qa.a, a_id, true).is_some() && roster_identity(&qa.b, a_id, false).is_some() && roster_identity(&qa.b, b_id, true).is_some() && roster_identity(&qa.a, b_id, false).is_some() })?; let sender = roster_identity(&qa.a, a_id, true).ok_or("sender self roster lacks identity")?; if roster_identity(&qa.b, a_id, false) != Some(sender) { return Err("sender identity does not match the receiver's live roster".into()); } let receiver = roster_identity(&qa.b, b_id, true).ok_or("receiver self roster lacks identity")?; if roster_identity(&qa.a, b_id, false) != Some(receiver) { return Err("receiver identity does not match the sender's live roster".into()); } let b_uid = receiver.0.to_owned(); let generation = qa.b.snapshot["generation"].as_u64().filter(|generation| *generation > 0) .ok_or("receiver roster lacks a connection generation")?; let sender_receipt = json!({ "client_id": a_id, "generation": generation, "uid": sender.0, "nickname": sender.1 }); 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(&sender_receipt))?; 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(&sender_receipt))?; // 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)?; // Disconnect with a proven live route, without whisper_stop or audio_end. let held_epoch = RESTORED_EPOCH + 1; qa.tones[OLD_TONE] = Tone::new(HZ[OLD_TONE], Some(held_epoch)); start_whisper(&mut qa, b_id, &b_uid, held_epoch)?; let held = qa.burst(Some(OLD_TONE), None, 42)?; Duplex::receipt(&qa.b, "held whisper before disconnect", a_id, OLD_TONE, held.first)?; check_whisper_event(&qa.b, "held whisper before disconnect", held.first, Some(&sender_receipt))?; if !qa.a.transmitting { return Err("sender was not transmitting at disconnect".into()); } let held_confirmed = Duplex::disconnect(&mut qa.a, &qa.tones)?; qa.wait_until("held whisper sender leaving roster", CONTROL, |qa| { qa.b.snapshot["clients"].as_array().is_some_and(|clients| clients.iter().all(|c| c["id"] != a_id)) })?; let a_id = Duplex::connect(&mut qa.a, &qa.tones)?; qa.party(a_id, b_id)?; qa.observe_for(GATE_OBSERVATION)?; let stale = qa.burst(Some(OLD_TONE), None, 24)?; qa.observe_for(GATE_OBSERVATION)?; for peer in [&qa.a, &qa.b] { Duplex::check_gate(peer, "held epoch from previous connection", 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 = [held_confirmed, a_confirmed, b_confirmed].into_iter().filter(|confirmed| *confirmed).count(); Ok(format!("Whisper IPC passed: direct 650 Hz + roster-matched whisper_received ({} frames); deny_all 900 Hz suppressed (no playback or whisper_received); restored allow_all 1150 Hz + roster-matched whisper_received ({} frames); stale tag 1450 Hz dropped after stop and after reconnect during a live whisper; untagged 1750 Hz ordinary voice after reconnect ({} frames, no whisper_received). Server confirmed {confirmed}/3 disconnects. No device audio.", first.frames, again.frames, voice.frames)) } fn stream_owner(row: &Value) -> Option { row["clid"].as_str()?.parse().ok() } fn stream_notification(line: &Line, since: Instant, event: &str, find: &mut impl FnMut(&Value) -> Option) -> Option { if line.at < since || line.value["event"] != "stream" || line.value["name"] != event { return None; } // A raw TS notification may have multiple pipe-separated rows. line.value["items"].as_array()?.iter().find_map(find) } fn wait_stream_notification(peer: &mut Peer, tones: &[Tone; HZ.len()], since: Instant, event: &str, mut find: impl FnMut(&Value) -> Option) -> Result { let deadline = Instant::now() + CONTROL; let stage = format!("fresh matching {event}"); loop { let line = peer.read_before(deadline, &stage)?; let matched = stream_notification(&line, since, event, &mut find); peer.observe(tones, line)?; if let Some(value) = matched { return Ok(value); } } } fn require_stream_ack(peer: &Peer, cmd: &str, reply: &Value, target: Option) -> Result<()> { let refused = |error: &Value| { let label = peer.label; match error["ts_error"]["id"].as_u64() { Some(2568) => format!("{label}: {cmd}: permission refused (ts_error.id=2568)"), Some(id) => format!("{label}: {cmd}: server refused (ts_error.id={id})"), None => format!("{label}: core rejected {cmd}"), } }; if reply["ok"] != true { return Err(refused(&reply["error"])); } if let Some(target) = target { let Some([row]) = reply["result"]["results"].as_array().map(Vec::as_slice) else { return Err("stream_list: expected one targeted acknowledgement".into()); }; if row["client_id"].as_u64() != Some(target) { return Err("stream_list: acknowledgement did not match publisher client ID".into()); } if row["ok"] != true { return Err(refused(row.get("error").unwrap_or(row))); } } println!("{cmd}: server acknowledged"); Ok(()) } fn request_stream_event(peer: &mut Peer, tones: &[Tone; HZ.len()], cmd: &str, args: Value, target: Option, event: &str, mut find: impl FnMut(&Value) -> Option) -> Result { peer.pump(tones)?; let since = Instant::now(); let mut matched = None; // The notification and command reply are independent and may arrive in either order. let reply = peer.request_reply(tones, cmd, args, CONTROL, |line| { if matched.is_none() { matched = stream_notification(line, since, event, &mut find); } })?; require_stream_ack(peer, cmd, &reply, target)?; match matched { Some(value) => Ok(value), None => wait_stream_notification(peer, tones, since, event, find), } } struct StreamMetadata<'a> { name: &'a str, bitrate: u32, viewer_limit: u16, audio: bool, } impl StreamMetadata<'_> { const TYPE: u64 = 2; const ACCESSIBILITY: u64 = 1; const MODE: u64 = 1; fn args(&self) -> Value { json!({"name": self.name, "type": Self::TYPE, "accessibility": Self::ACCESSIBILITY, "mode": Self::MODE, "bitrate": self.bitrate, "viewer_limit": self.viewer_limit, "audio": self.audio}) } fn verify_list(&self, observer: &mut Peer, tones: &[Tone; HZ.len()], publisher: u64, stream_id: &str, phase: &str, args: Value) -> Result<()> { let audio = if self.audio { "1" } else { "0" }; request_stream_event(observer, tones, "stream_list", args, Some(publisher), "notifystreaminfo", |row| { if row["id"].as_str() != Some(stream_id) || stream_owner(row) != Some(publisher) { return None; } Some((|| { for (field, expected) in [("name", self.name), ("audio", audio)] { let actual = row[field].as_str(); if actual != Some(expected) { return Err(format!("{field}: expected {expected:?}, reported {actual:?}")); } } for (field, expected) in [("type", Self::TYPE), ("accessibility", Self::ACCESSIBILITY), ("mode", Self::MODE), ("bitrate", u64::from(self.bitrate)), ("viewer_limit", u64::from(self.viewer_limit))] { let actual = row[field].as_str(); if actual.and_then(|value| value.parse::().ok()) != Some(expected) { return Err(format!("{field}: expected {expected}, reported {actual:?}")); } } Ok(()) })()) }).and_then(|metadata| metadata).map_err(|error| format!("{phase} stream discovery: {error}"))?; println!("observer: fresh {phase} notifystreaminfo matched stream ID and owner, name={:?}, type={}, accessibility={}, mode={}, bitrate={}, viewer_limit={}, audio={audio}", self.name, Self::TYPE, Self::ACCESSIBILITY, Self::MODE, self.bitrate, self.viewer_limit); Ok(()) } } fn stream_lifecycle(qa: &mut Duplex, name: &str) -> Result<()> { for peer in [&mut qa.a, &mut qa.b] { let mute = peer.request(&qa.tones, "set_audio", json!({"input_muted": true, "output_muted": true}), CONTROL)?; if mute["input_muted"] != true || mute["output_muted"] != true { return Err(format!("{}: both mutes must be active before connect", peer.label)); } } let publisher = Duplex::connect(&mut qa.a, &qa.tones)?; qa.wait_until("publisher alone in beta14 lobby", CONTROL, |qa| { is_beta14_default(&qa.a.snapshot) && qa.a.snapshot["clients"].as_array().is_some_and(|rows| matches!(rows.as_slice(), [own] if own["is_self"] == true && own["id"] == publisher)) })?; let alone = qa.a.request(&qa.tones, "stream_list", json!({}), CONTROL)?; if !alone["results"].as_array().is_some_and(Vec::is_empty) { return Err("untargeted discovery included the only client itself".into()); } println!("stream_list without target: no results for a solitary publisher"); let observer = Duplex::connect(&mut qa.b, &qa.tones)?; if publisher == 0 || observer == 0 { return Err("connect returned a zero client ID".into()); } qa.party(publisher, observer)?; if ![&qa.a, &qa.b].into_iter().all(|peer| is_beta14_default(&peer.snapshot)) { return Err("stream lifecycle QA requires the private loopback TS6 beta14 default channel".into()); } qa.wait_until("both muted peers and self IDs in both rosters", CONTROL, |qa| { [(&qa.a, publisher, observer), (&qa.b, observer, publisher)].into_iter().all(|(peer, own, other)| { peer.snapshot["clients"].as_array().is_some_and(|clients| { [(own, true), (other, false)].into_iter().all(|(id, is_self)| clients.iter().any(|client| { client["id"].as_u64() == Some(id) && client["is_self"].as_bool() == Some(is_self) && client["input_muted"] == true && client["output_muted"] == true })) }) }) })?; println!("connect: private loopback TS6 beta14; two disposable guests, roster IDs verified, both mutes active"); let initial = StreamMetadata { name, bitrate: 1000, viewer_limit: 0, audio: false }; let stream_id = request_stream_event(&mut qa.a, &qa.tones, "stream_setup", initial.args(), None, "notifystreamstarted", |row| { (stream_owner(row) == Some(publisher)).then(|| row["id"].as_str().filter(|id| !id.is_empty()).map(str::to_owned)).flatten() })?; println!("publisher: fresh own notifystreamstarted supplied the registered stream ID"); let checked = (|| { initial.verify_list(&mut qa.b, &qa.tones, publisher, &stream_id, "channel-wide", json!({}))?; let since = Instant::now(); let reply = qa.b.request_reply(&qa.tones, "stream_join", json!({ "stream_id": &stream_id, "client_id": publisher, "message": "QA viewer request", }), CONTROL, |_| {})?; require_stream_ack(&qa.b, "stream_join", &reply, None)?; wait_stream_notification(&mut qa.a, &qa.tones, since, "notifyjoinstreamrequest", |row| { (row["id"].as_str() == Some(stream_id.as_str()) && stream_owner(row) == Some(observer) && row["is_remove"] == "0").then_some(()) })?; let since = Instant::now(); let reply = qa.a.request_reply(&qa.tones, "stream_respond", json!({ "stream_id": &stream_id, "client_id": observer, "decision": false, "offer": "", "message": "QA declined", }), CONTROL, |_| {})?; require_stream_ack(&qa.a, "stream_respond", &reply, None)?; wait_stream_notification(&mut qa.b, &qa.tones, since, "notifyrespondjoinstreamrequest", |row| { (row["id"].as_str() == Some(stream_id.as_str()) && row["decision"] == "0" && row["msg"] == "QA declined" && row["offer"].as_str().unwrap_or("").is_empty()).then_some(()) })?; println!("observer: received the publisher's denial for its join request; no offer"); initial.verify_list(&mut qa.b, &qa.tones, publisher, &stream_id, "after refusal", json!({"client_id":publisher}))?; let updated_name = format!("{name} updated"); let updated = StreamMetadata { name: &updated_name, bitrate: 2500, viewer_limit: 3, audio: true }; let mut args = updated.args(); args["stream_id"] = json!(&stream_id); let reply = qa.a.request_reply(&qa.tones, "stream_update", args, CONTROL, |_| {})?; require_stream_ack(&qa.a, "stream_update", &reply, None)?; // Query only after the update ACK; an unsolicited update notification is not discovery. updated.verify_list(&mut qa.b, &qa.tones, publisher, &stream_id, "updated", json!({"client_id":publisher})) })(); // If discovery or update failed, still unregister the exact ID before disconnecting. let stopped = (|| { let since = Instant::now(); let reply = qa.a.request_reply(&qa.tones, "stream_stop", json!({"stream_id": &stream_id}), CONTROL, |_| {})?; require_stream_ack(&qa.a, "stream_stop", &reply, None)?; let matched_by = wait_stream_notification(&mut qa.b, &qa.tones, since, "notifystreamstopped", |row| { match row.get("id").map(Value::as_str) { None | Some(Some("")) => (stream_owner(row) == Some(publisher)).then_some("publisher ID"), Some(Some(id)) => (id == stream_id).then_some("stream ID"), Some(None) => None, } })?; println!("observer: fresh notifystreamstopped matched by {matched_by}"); Ok(()) })(); match (checked, stopped) { (Ok(()), result) | (result, Ok(())) => result, (Err(check), Err(stop)) => Err(format!("{check}; {stop}")), } } fn exercise_stream_lifecycle(exe: &Path, root: &Path) -> Result { let scratch = root.file_name().and_then(|name| name.to_str()).ok_or("missing QA scratch name")?; let mut qa = Duplex::open(exe, root, [None; HZ.len()])?; let result = stream_lifecycle(&mut qa, &format!("Peach stream {scratch}")); let mut errors = Vec::new(); if let Err(error) = result { errors.push(error); } let mut confirmed = 0; for peer in [&mut qa.a, &mut qa.b] { if matches!(peer.state, Some("connecting" | "connected")) { match Duplex::disconnect(peer, &qa.tones) { Ok(true) => confirmed += 1, Ok(false) => {}, Err(error) => errors.push(error), } } } for peer in [&mut qa.a, &mut qa.b] { if let Err(error) = peer.shutdown(&qa.tones) { errors.push(error); } } if !errors.is_empty() { return Err(errors.join("; ")); } Ok(format!("Stream lifecycle IPC passed: registration, metadata update, and stop. Both cores shut down; server confirmed {confirmed}/2 disconnects. No media or device audio was used.")) } fn run() -> Result { 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, (Some(flag), None) if flag == "--stream-lifecycle" => exercise_stream_lifecycle, _ => return Err("usage: duplex_qa [--whisper | --stream-lifecycle]".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 } } }