Drop buffered and stale whisper audio at policy boundaries
This commit is contained in:
1 parent
b19b432281
commit
3b5c49e329
7 files changed
+212
-24
No files matched your search
+162
-16
@@ -1,8 +1,10 @@
|
||||
//! Exercise the compiled diagnostic core's real TeamSpeak voice path over stdio.
|
||||
//! Run with `TEAMSPEACH_QA_CORE` set to an absolute disposable core executable:
|
||||
//! `cargo run --locked -p teamspeach-core --example duplex_qa`.
|
||||
//! 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. This does not start a server or use audio devices.
|
||||
//! 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.
|
||||
|
||||
@@ -32,6 +34,13 @@ 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 {
|
||||
@@ -40,7 +49,7 @@ struct Tone {
|
||||
}
|
||||
|
||||
impl Tone {
|
||||
fn new(hz: u16) -> Self {
|
||||
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| {
|
||||
@@ -50,7 +59,11 @@ impl Tone {
|
||||
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 input = format!("{}\n", json!({"cmd":"audio_frame", "args":{"pcm":STANDARD.encode(pcm)}})).into();
|
||||
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 }
|
||||
}
|
||||
}
|
||||
@@ -86,6 +99,7 @@ enum Seen {
|
||||
Playback { from: u64, tone: Option<usize> },
|
||||
RemoteStarted(u64),
|
||||
RemoteStopped,
|
||||
WhisperReceived(u64),
|
||||
LocalStarted,
|
||||
Muted,
|
||||
Offline,
|
||||
@@ -241,6 +255,10 @@ impl Peer {
|
||||
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")?;
|
||||
@@ -325,10 +343,10 @@ struct Burst {
|
||||
}
|
||||
|
||||
impl Duplex {
|
||||
fn open(exe: &Path, root: &Path) -> Result<Self> {
|
||||
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: HZ.map(Tone::new),
|
||||
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)?;
|
||||
@@ -424,14 +442,14 @@ impl Duplex {
|
||||
for &(at, seen) in peer.seen.iter().filter(|(at, _)| *at >= since) {
|
||||
match seen {
|
||||
Seen::RemoteStarted(id) if id == from => remote_started = true,
|
||||
Seen::RemoteStarted(id) => {
|
||||
return Err(format!("{phase}: {}: expected remote speaker {from}, got talking start for {id}; {}",
|
||||
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 speaker {from} and {} Hz, got speaker {id} and {:?} Hz; {}",
|
||||
peer.label, HZ[expected], tone.map(|tone| HZ[tone]), Self::evidence(peer, since)));
|
||||
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 });
|
||||
@@ -449,25 +467,26 @@ impl Duplex {
|
||||
return Ok(r);
|
||||
}
|
||||
}
|
||||
Err(format!("{phase}: {}: expected sustained {} Hz and speaker {from} with timely onset ({} matching frames); {}",
|
||||
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 tx_starts, mut muted, mut offline) = (0, 0, 0, 0, 0, 0);
|
||||
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}, local starts={tx_starts}, rejected muted/offline={muted}/{offline}, currently talking/transmitting={}/{}",
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -478,7 +497,7 @@ impl Duplex {
|
||||
for &(at, seen) in peer.seen.iter().filter(|(at, _)| *at >= since) {
|
||||
let forbidden = match seen {
|
||||
Seen::LocalStarted => block_local,
|
||||
Seen::RemoteStarted(_) => block_remote,
|
||||
Seen::RemoteStarted(_) | Seen::WhisperReceived(_) => block_remote,
|
||||
Seen::Playback { from, tone } => match receive {
|
||||
ReceiveGate::Open => false,
|
||||
ReceiveGate::Closed => true,
|
||||
@@ -545,7 +564,7 @@ impl Duplex {
|
||||
}
|
||||
|
||||
fn exercise(exe: &Path, root: &Path) -> Result<String> {
|
||||
let mut qa = Duplex::open(exe, root)?;
|
||||
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)?;
|
||||
@@ -634,7 +653,134 @@ fn exercise(exe: &Path, root: &Path) -> Result<String> {
|
||||
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")?;
|
||||
|
||||
+32
-6
@@ -390,12 +390,14 @@ impl Receiver {
|
||||
if !deny {
|
||||
return Vec::new();
|
||||
}
|
||||
let removed: Vec<u16> = self.whisperers.drain().collect();
|
||||
let queues = self.handler.get_mut_queues();
|
||||
for id in &removed {
|
||||
queues.remove(&ClientId(*id));
|
||||
self.dsp.remove(*id);
|
||||
}
|
||||
self.whisperers.clear();
|
||||
let mut removed = Vec::new();
|
||||
self.handler.get_mut_queues().retain(|id, queue| {
|
||||
if !queue.has_pending_whisper() { return true; }
|
||||
removed.push(id.0);
|
||||
self.dsp.remove(id.0);
|
||||
false
|
||||
});
|
||||
self.whisper_starts.clear();
|
||||
removed
|
||||
}
|
||||
@@ -582,6 +584,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denying_whispers_after_end_marker_purges_audio_without_muting_ordinary_speakers() {
|
||||
let mut rx = Receiver::new();
|
||||
let mut encoder = TxEncoder::new(TxCodec::OpusVoice, 6).unwrap();
|
||||
let packet = encoder.encode(&sine(&mut 0.0, 440.0)).unwrap();
|
||||
let payload = &packet.content()[3..];
|
||||
let forward = |audio| InAudioBuf::try_new(Direction::S2C, OutAudio::new(&audio).into_vec()).unwrap();
|
||||
for id in 0..6 {
|
||||
rx.handle_packet(forward(AudioData::S2CWhisper { id, from: 7, codec: CodecType::OpusVoice, data: payload }));
|
||||
rx.handle_packet(forward(AudioData::S2C { id, from: 8, codec: CodecType::OpusVoice, data: payload }));
|
||||
}
|
||||
rx.handle_packet(forward(AudioData::S2CWhisper { id: 6, from: 7, codec: CodecType::OpusVoice, data: &[] }));
|
||||
assert_eq!(rx.set_deny_whispers(true), [7]);
|
||||
let mut out = [0; FRAME_SAMPLES];
|
||||
let mut heard = false;
|
||||
for _ in 0..12 {
|
||||
let mix = rx.mix(&mut out, |_| 1.0);
|
||||
assert!(!mix.speakers.contains(&7));
|
||||
heard |= mix.speakers.contains(&8) && out.iter().any(|s| s.unsigned_abs() > 500);
|
||||
}
|
||||
assert!(heard, "ordinary queued speech must remain audible");
|
||||
assert!(matches!(rx.handle_packet(forward(AudioData::S2C { id: 7, from: 7, codec: CodecType::OpusVoice, data: payload })), RxEvent::Started(7)));
|
||||
}
|
||||
|
||||
/// Offline real encoder/receiver proof for PCM captured by audit-voice-timed.mjs.
|
||||
/// Explicit opt-in: no device, socket or playback is opened by this test.
|
||||
#[test]
|
||||
|
||||
+2
-2
@@ -1485,8 +1485,8 @@ impl Session {
|
||||
async fn tx_frame(&mut self, frame: &CapturedFrame) {
|
||||
if !self.audio_in.validate(frame) { return; }
|
||||
let whisper = frame.whisper;
|
||||
// Capture queued before push-to-whisper must not escape to the ordinary channel.
|
||||
if whisper.is_none() && self.whisper.active_epoch().is_some() {
|
||||
// Neither stale whisper audio nor pre-whisper ordinary audio may alter the current spurt.
|
||||
if whisper != self.whisper.active_epoch() {
|
||||
return;
|
||||
}
|
||||
self.tx.burst_open = true;
|
||||
|
||||
Vendored
+1
@@ -41,6 +41,7 @@ the historical patch alone no longer reproduces the complete tree.
|
||||
6. `src/lib.rs`: `AudioSendMetadata`, `AudioSendGuard` and `send_audio_guarded` forward
|
||||
original capture time, connection generation and privacy epoch to the transport. Ordinary
|
||||
`send_audio` remains for non-capture end markers and existing third-party callers.
|
||||
7. `src/audio.rs`: `AudioQueue::has_pending_whisper` identifies decoder and jitter-buffer state that must be discarded when the receiver switches to Deny All, even after a whisper end marker arrived.
|
||||
|
||||
## `tsproto/`
|
||||
|
||||
|
||||
Vendored
+7
@@ -209,6 +209,13 @@ impl AudioQueue {
|
||||
pub fn get_decoder(&self) -> &Decoder { &self.decoder }
|
||||
pub fn is_whispering(&self) -> bool { self.whispering }
|
||||
|
||||
/// A whisper may still play from buffered packets, decoded samples or loss concealment.
|
||||
pub fn has_pending_whisper(&self) -> bool {
|
||||
self.whispering || self.packet_buffer.iter().any(|p| {
|
||||
matches!(p.packet.data().data(), AudioData::S2CWhisper { data, .. } if data.len() > 1)
|
||||
})
|
||||
}
|
||||
|
||||
/// Size is in samples.
|
||||
fn add_buffer_size(&mut self, size: usize) {
|
||||
if let Ok(size) = (size / USUAL_FRAME_SIZE).try_into() {
|
||||
|
||||
Reference in new issue
Block a user