diff --git a/crates/domistream/tests/audio.rs b/crates/domistream/tests/audio.rs new file mode 100644 index 0000000..bf54aa1 --- /dev/null +++ b/crates/domistream/tests/audio.rs @@ -0,0 +1,395 @@ +//! The audio depacketizer (`docs/PROTOCOL.md` 6): blocks of 4 data + 2 parity packets with a parity matrix passed +//! through the `AudioFec::ParityMatrix` hook (U16 is unmeasured, so any MDS matrix must work; the tests use a +//! Cauchy matrix and a second one), AES-128-CBC payloads, every loss pattern of a block, sequence wrap, duplicates, +//! reordering, far-past and far-future packets. +//! +//! Reading of PROTOCOL.md 6.2: a parity packet's RTP sequence "continues after the 4 data packets" (base + 4 + +//! shard), which overlaps the next block's data sequence numbers; the receiver must key parity by the FEC header's +//! base sequence and the payload type, never by the parity packet's RTP sequence. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)] + +mod common; + +use core::time::Duration; +use std::collections::HashMap; + +use common::{AExpect, APkt, AudioHost, SeqRng, audio_test_matrix, subsets_of}; +use domistream::audio::packet::MAX_AUDIO_PACKET_BYTES; +use domistream::audio::{AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioStats}; +use domistream::{Error, Instant, SessionKeys}; +use proptest::prelude::*; + +const KEY: [u8; 16] = *b"audio-test-key!!"; +const RIKEYID: u32 = 0xFFFF_FFF0; // rikeyid + sequence wraps inside the tests +const DURATION: u32 = 5; + +fn host(encrypt: bool, matrix: [u8; 8]) -> AudioHost { + AudioHost { key: KEY, rikeyid: RIKEYID, encrypt, matrix, duration_ms: DURATION, opus_len: 37 } +} + +fn config(encrypt: bool, fec: AudioFec) -> AudioConfig { + AudioConfig { + cipher: encrypt.then(|| AudioCipher::new(&SessionKeys { rikey: KEY, rikeyid: RIKEYID })), + packet_duration_ms: DURATION as u8, + fec, + loss_timeout: Duration::from_millis(40), + } +} + +struct Run { + events: Vec, + stats: AudioStats, +} + +fn run(cfg: AudioConfig, datagrams: &[Vec]) -> Run { + let mut d = AudioDepacketizer::new(cfg).expect("AudioDepacketizer::new"); + let mut now = 1_000_000u64; + let mut events = Vec::new(); + for g in datagrams { + d.push(Instant::from_micros(now), g).expect("push never fails within the size cap"); + now += 10; + while let Some(e) = d.poll_event() { + events.push(e); + } + } + for _ in 0..64 { + now += 10_000_000; + d.handle_timeout(Instant::from_micros(now)).unwrap(); + while let Some(e) = d.poll_event() { + events.push(e); + } + if d.poll_timeout().is_none() { + break; + } + } + Run { events, stats: d.stats() } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Want { + /// Arrived as sent. + Packet, + /// Lost and rebuilt by FEC. + Recovered, + /// Gone: reported lost. + Lost, +} + +/// Every data sequence number gets exactly one event, in stream order; packets are byte-exact with the right +/// timestamp; `recovered` is set exactly for rebuilt ones. +fn check(expect: &[AExpect], want: &[Want], r: &Run) { + let pos: HashMap = expect.iter().enumerate().map(|(i, e)| (e.sequence, i)).collect(); + let mut seen = vec![false; expect.len()]; + let mut prev: Option = None; + for e in &r.events { + let (seq, i) = match e { + AudioEvent::Packet { sequence, .. } | AudioEvent::Lost { sequence } => { + (*sequence, *pos.get(sequence).unwrap_or_else(|| panic!("event for sequence {sequence} that was never a data packet"))) + } + }; + assert!(!seen[i], "two events for sequence {seq}"); + assert!(prev.is_none_or(|p| i > p), "sequence {seq} out of order"); + prev = Some(i); + seen[i] = true; + match (e, want[i]) { + (AudioEvent::Packet { timestamp_ms, opus, recovered, .. }, Want::Packet | Want::Recovered) => { + assert_eq!(opus, &expect[i].opus, "sequence {seq} corrupt"); + assert_eq!(*timestamp_ms, expect[i].timestamp_ms, "sequence {seq} timestamp"); + assert_eq!(*recovered, want[i] == Want::Recovered, "sequence {seq} recovered flag"); + } + (AudioEvent::Lost { .. }, Want::Lost) => {} + (got, w) => panic!("sequence {seq}: want {w:?}, got {got:?}"), + } + } + for (i, s) in seen.iter().enumerate() { + assert!(s, "no event for sequence {} (want {:?})", expect[i].sequence, want[i]); + } +} + +/// What must come out of a block, given which of its 6 packets arrived. +fn block_want(arrived: &[bool; 6], fec: bool) -> [Want; 4] { + let count = arrived.iter().filter(|a| **a).count(); + let mut w = [Want::Packet; 4]; + for (i, slot) in w.iter_mut().enumerate() { + if !arrived[i] { + *slot = if fec && count >= 4 { Want::Recovered } else { Want::Lost }; + } + } + w +} + +/// Blocks `1..blocks-1` lose what `lose(block, index)` says; the first and last blocks arrive whole. +fn scenario(h: &AudioHost, seed: u64, first_seq: u16, blocks: usize, fec: bool, lose: impl Fn(usize, usize) -> bool) -> (Vec, Vec, Vec>) { + let mut rng = SeqRng::new(seed); + let (packets, expect) = h.blocks(&mut rng, first_seq, 0x7000_0000, blocks); + let mut want = Vec::new(); + let mut datagrams = Vec::new(); + for b in 0..blocks { + let mut arrived = [true; 6]; + for p in packets.iter().filter(|p| p.block == b) { + if b != 0 && b + 1 != blocks && lose(b, p.index) { + arrived[p.index] = false; + } else { + datagrams.push(p.bytes.clone()); + } + } + want.extend(block_want(&arrived, fec)); + } + (expect, want, datagrams) +} + +// ================================================================================================ every pattern + +#[test] +fn every_loss_pattern_of_a_block() { + // All 64 subsets of the 6 packets lost in the middle block, encrypted, with the Cauchy matrix. + let h = host(true, audio_test_matrix()); + for size in 0..=6 { + for lost in subsets_of(6, size) { + let (expect, want, dg) = scenario(&h, 1, 0, 3, true, |b, i| b == 1 && lost.contains(&i)); + check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg)); + } + } +} + +#[test] +fn every_loss_pattern_plaintext_and_another_matrix() { + // A second MDS matrix (rows 1,1,1,1 and 1,2,4,8) and no encryption. + let m = [1, 1, 1, 1, 1, 2, 4, 8]; + let h = host(false, m); + for size in 0..=6 { + for lost in subsets_of(6, size) { + let (expect, want, dg) = scenario(&h, 2, 400, 3, true, |b, i| b == 1 && lost.contains(&i)); + check(&expect, &want, &run(config(false, AudioFec::ParityMatrix(m)), &dg)); + } + } +} + +#[test] +fn fec_disabled_reports_losses() { + let h = host(true, audio_test_matrix()); + for lost in [vec![0usize], vec![3], vec![1, 2], vec![0, 4, 5]] { + let (expect, want, dg) = scenario(&h, 3, 8, 3, false, |b, i| b == 1 && lost.contains(&i)); + check(&expect, &want, &run(config(true, AudioFec::Disabled), &dg)); + } +} + +#[test] +fn random_losses_over_many_blocks() { + let h = host(true, audio_test_matrix()); + for (seed, pct) in [(10u64, 5usize), (11, 15), (12, 30), (13, 50)] { + let mut rng = SeqRng::new(seed * 31); + let mask: Vec = (0..60 * 6).map(|_| rng.below(100) < pct).collect(); + let (expect, want, dg) = scenario(&h, seed, 0, 60, true, |b, i| mask[b * 6 + i]); + let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg); + check(&expect, &want, &r); + assert_eq!(r.stats.recovered, want.iter().filter(|w| **w == Want::Recovered).count() as u64); + assert_eq!(r.stats.lost, want.iter().filter(|w| **w == Want::Lost).count() as u64); + } +} + +// ================================================================================================ order and strays + +#[test] +fn sequence_wraps() { + // Blocks from 0xFFF0 through 0x000F: data sequence 0xFFFF -> 0, base sequence wrap, rikeyid + seq wrap. + let h = host(true, audio_test_matrix()); + let (expect, want, dg) = scenario(&h, 20, 0xFFF0, 8, true, |b, i| (b + i) % 5 == 0); + assert!(expect.iter().any(|e| e.sequence == 0xFFFF) && expect.iter().any(|e| e.sequence == 0)); + check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg)); +} + +#[test] +fn duplicates_are_dropped() { + let h = host(true, audio_test_matrix()); + let (expect, want, dg) = scenario(&h, 21, 0, 10, true, |b, i| (b * 7 + i) % 6 == 0); + let doubled: Vec> = dg.iter().flat_map(|g| [g.clone(), g.clone()]).collect(); + let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &doubled); + check(&expect, &want, &r); + assert!(r.stats.packets_dropped >= dg.len() as u64 / 2, "{:?}", r.stats); +} + +#[test] +fn reordered_within_and_across_blocks() { + let h = host(true, audio_test_matrix()); + for seed in 30..36u64 { + let (expect, want, mut dg) = scenario(&h, seed, 0, 12, true, |b, i| (b + i + seed as usize) % 7 == 0); + let mut rng = SeqRng::new(seed); + let mut i = 6; // the first block stays first, so the stream has a known start + while i < dg.len() { + let end = (i + 9).min(dg.len()); + rng.shuffle(&mut dg[i..end]); + i = end; + } + check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg)); + } +} + +#[test] +fn far_past_and_far_future() { + let h = host(true, audio_test_matrix()); + let mut rng = SeqRng::new(40); + let (packets, expect) = h.blocks(&mut rng, 1000, 0, 6); + let (old, _) = h.blocks(&mut SeqRng::new(41), 1000u16.wrapping_sub(400), 0, 1); + let (future, _) = h.blocks(&mut SeqRng::new(42), 1000u16.wrapping_add(20_000), 0, 1); + let mut dg: Vec> = packets.iter().filter(|p| p.block < 3).map(|p| p.bytes.clone()).collect(); + dg.extend(old.iter().map(|p| p.bytes.clone())); + dg.extend(packets.iter().filter(|p| p.block < 2).map(|p| p.bytes.clone())); // replays + dg.extend(future.iter().take(1).map(|p| p.bytes.clone())); + dg.extend(packets.iter().filter(|p| p.block >= 3).map(|p| p.bytes.clone())); + let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg); + assert!(r.stats.packets_dropped >= 6 + 12, "far-past block and replays dropped: {:?}", r.stats); + // No event is ever a corrupt packet, the far-past block never comes out, and the first blocks do, in order. + // (Whether the lone far-future packet is played or dropped is the receiver's choice.) + let (_, future_expect) = h.blocks(&mut SeqRng::new(42), 1000u16.wrapping_add(20_000), 0, 1); + let by_seq: HashMap = expect.iter().chain(&future_expect[..1]).map(|e| (e.sequence, e)).collect(); + let mut first_blocks = 0; + for e in &r.events { + if let AudioEvent::Packet { sequence, opus, .. } = e { + assert!(!(600..604).contains(sequence), "far-past sequence {sequence} played"); + let want = by_seq.get(sequence).unwrap_or_else(|| panic!("a packet for sequence {sequence} that only strays carried")); + assert_eq!(opus, &want.opus); + if (1000..1012).contains(sequence) { + first_blocks += 1; + } + } + } + assert_eq!(first_blocks, 12); +} + +fn parity_of(packets: &[APkt], block: usize, index: usize) -> Vec { + packets.iter().find(|p| p.block == block && p.index == index).unwrap().bytes.clone() +} + +#[test] +fn hostile_parity_never_corrupts() { + let h = host(true, audio_test_matrix()); + let mut rng = SeqRng::new(50); + let (packets, expect) = h.blocks(&mut rng, 0, 0, 3); + let mut hostile = Vec::new(); + // Parity for block 1 with a base sequence that is not a multiple of 4. + let mut p = parity_of(&packets, 1, 4); + p[14..16].copy_from_slice(&5u16.to_be_bytes()); + hostile.push(p); + // Parity shorter than the data shards. + let mut p = parity_of(&packets, 1, 5); + p.truncate(p.len() - 16); + hostile.push(p); + // Parity claiming to protect another payload type. + let mut p = parity_of(&packets, 1, 4); + p[13] = 96; + hostile.push(p); + // Block 1 loses data 0 and 1; only the hostile parity (and nothing else) is offered for it. + let mut dg: Vec> = packets.iter().filter(|p| p.block == 0).map(|p| p.bytes.clone()).collect(); + dg.extend(packets.iter().filter(|p| p.block == 1 && (2..4).contains(&p.index)).map(|p| p.bytes.clone())); + dg.extend(hostile); + dg.extend(packets.iter().filter(|p| p.block == 2).map(|p| p.bytes.clone())); + let mut want = vec![Want::Packet; 12]; + want[4] = Want::Lost; + want[5] = Want::Lost; + check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg)); +} + +#[test] +fn undecryptable_data_is_dropped_and_rebuilt() { + // Copies of a data packet with a ciphertext of a wrong length or no payload: dropped, never output, and the + // packet is rebuilt from the rest of its block. + let h = host(true, audio_test_matrix()); + let mut rng = SeqRng::new(60); + let (packets, expect) = h.blocks(&mut rng, 0, 0, 3); + let mut dg: Vec> = Vec::new(); + for p in &packets { + if p.block == 1 && p.index == 2 { + let mut empty = p.bytes.clone(); + empty.truncate(12); + dg.push(empty); + let mut odd = p.bytes.clone(); + odd.pop(); + dg.push(odd); + } else { + dg.push(p.bytes.clone()); + } + } + let mut want = vec![Want::Packet; 12]; + want[6] = Want::Recovered; + let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg); + check(&expect, &want, &r); + assert!(r.stats.packets_dropped >= 2); +} + +// ================================================================================================ API edges + +#[test] +fn config_refusals() { + assert_err!(AudioDepacketizer::new(AudioConfig { packet_duration_ms: 0, ..config(true, AudioFec::Disabled) }), Error::Malformed { .. }); + let mut zero = audio_test_matrix(); + zero[5] = 0; + for bad in [zero, [1; 8], [1, 2, 3, 4, 2, 4, 6, 8], [0; 8]] { + assert_err!(AudioDepacketizer::new(config(true, AudioFec::ParityMatrix(bad))), Error::Malformed { .. }, "{bad:?} is not MDS"); + } + assert!(AudioDepacketizer::new(config(false, AudioFec::ParityMatrix(audio_test_matrix()))).is_ok()); +} + +#[test] +fn push_sizes() { + let mut d = AudioDepacketizer::new(config(true, AudioFec::Disabled)).unwrap(); + assert_too_large!(d.push(Instant::ZERO, &vec![0x80; MAX_AUDIO_PACKET_BYTES + 1]), MAX_AUDIO_PACKET_BYTES, MAX_AUDIO_PACKET_BYTES + 1); + assert_too_large!(d.push(Instant::ZERO, &vec![0x80; 1 << 20]), MAX_AUDIO_PACKET_BYTES, 1 << 20); + for g in [vec![], vec![0x80], vec![0x80, 97, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], vec![0xFF; 40], vec![0x80; MAX_AUDIO_PACKET_BYTES]] { + assert_eq!(d.push(Instant::ZERO, &g), Ok(())); + } + assert_eq!(d.stats().packets_dropped, 5); + assert_eq!(d.poll_event(), None); +} + +#[test] +fn a_missing_packet_waits_for_the_loss_timeout() { + let h = host(false, audio_test_matrix()); + let mut rng = SeqRng::new(70); + let (packets, expect) = h.blocks(&mut rng, 0, 0, 2); + let mut d = AudioDepacketizer::new(config(false, AudioFec::Disabled)).unwrap(); + let t = Instant::from_micros(3_000_000); + // Data 0 and 2 of block 0: 0 comes out, 1 is missing, 2 waits behind it. + d.push(t, &packets[0].bytes).unwrap(); + d.push(t, &packets[2].bytes).unwrap(); + assert!(matches!(d.poll_event(), Some(AudioEvent::Packet { sequence: 0, .. }))); + assert_eq!(d.poll_event(), None, "sequence 2 waits for 1"); + let deadline = d.poll_timeout().expect("a deadline for sequence 1"); + assert!(deadline > t && deadline <= t.saturating_add(Duration::from_millis(40))); + d.handle_timeout(t.saturating_add(Duration::from_millis(39))).unwrap(); + assert_eq!(d.poll_event(), None, "not before the loss timeout"); + d.handle_timeout(t.saturating_add(Duration::from_millis(40))).unwrap(); + assert_eq!(d.poll_event(), Some(AudioEvent::Lost { sequence: 1 })); + match d.poll_event() { + Some(AudioEvent::Packet { sequence: 2, opus, recovered: false, .. }) => assert_eq!(opus, expect[2].opus), + other => panic!("{other:?}"), + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })] + + /// Random loss masks and reordering over random lengths: exact, rebuilt or lost, never corrupt. + #[test] + fn generated_patterns(seed in any::(), first in 0u16..16_384, loss in 0usize..50, opus_len in 1usize..120) { + let mut h = host(true, audio_test_matrix()); + h.opus_len = opus_len; + let mut rng = SeqRng::new(seed); + let mask: Vec = (0..20 * 6).map(|_| rng.below(100) < loss).collect(); + let (expect, want, mut dg) = scenario(&h, seed, first * 4, 20, true, |b, i| mask[b * 6 + i]); + let mut i = 6; + while i < dg.len() { + let end = (i + 1 + rng.below(8)).min(dg.len()); + rng.shuffle(&mut dg[i..end]); + i = end; + } + check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg)); + } + + #[test] + fn arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::(), 0..80), 0..60)) { + let r = run(config(true, AudioFec::ParityMatrix(audio_test_matrix())), &datagrams); + prop_assert!(r.events.len() <= datagrams.len() * 4 + 4); + } +}