diff --git a/crates/domistream/tests/video.rs b/crates/domistream/tests/video.rs new file mode 100644 index 0000000..61fea61 --- /dev/null +++ b/crates/domistream/tests/video.rs @@ -0,0 +1,626 @@ +//! The video depacketizer (`docs/PROTOCOL.md` 5) driven with generated loss patterns over multi-block frames: +//! random, bursty, all parity lost, all data lost but recoverable, last packet lost, reordered, duplicated, +//! sequence and frame index wraps, far-past and far-future packets, encryption. Every frame comes out byte-exact or +//! is reported in a `FrameLost` range; never a corrupt frame. +//! +//! The test host (`common::VideoHost`) packetizes as PROTOCOL.md 5.2-5.3 say, computes parity with the crate's own +//! `ReedSolomon::new` (U14 is unknown; `fec.rs` tests the code itself) and writes the parity packets' headers after +//! the parity, so bytes 0-31 of any recovered data shard are garbage. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)] + +mod common; + +use core::time::Duration; +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use common::{SeqRng, VExpect, VPkt, VideoHost, fec_info, video_packet_bytes}; +use domistream::video::packet::MAX_VIDEO_PACKET_BYTES; +use domistream::video::{MAX_FRAMES_IN_FLIGHT, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent, VideoStats}; +use domistream::{Error, Instant}; +use proptest::prelude::*; + +const PACKET_SIZE: u16 = 64; // payload 48 bytes, packet 80 bytes +const TIMEOUT: Duration = Duration::from_millis(50); +const KEY: [u8; 16] = *b"video-test-key!!"; + +fn config(cipher: bool) -> VideoConfig { + VideoConfig { packet_size: PACKET_SIZE, cipher: cipher.then(|| VideoCipher::new(KEY)), frame_timeout: TIMEOUT } +} + +/// One frame of a scenario: its packets as sent and what must come out. +#[derive(Clone, Debug)] +struct Frame { + packets: Vec, + expect: VExpect, +} + +fn frames(rng: &mut SeqRng, host: &mut VideoHost, first_index: u32, n: usize, percentages: &[u8]) -> Vec { + (0..n) + .map(|i| { + let len = 10 + rng.below(48 * 14); + let bitstream = VideoHost::bitstream(rng, len); + let pct = percentages[rng.below(percentages.len())]; + let blocks = 1 + rng.below(4); + let (packets, expect) = host.frame(first_index.wrapping_add(i as u32), &bitstream, pct, blocks); + Frame { packets, expect } + }) + .collect() +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Outcome { + Deliver, + Lose, +} + +/// Whether a frame can be rebuilt from the packets that arrive (by shard identity, duplicates counted once). +fn outcome(frame: &Frame, arrived: &[&VPkt]) -> Outcome { + let mut have: BTreeMap> = BTreeMap::new(); + for p in arrived { + have.entry(p.block).or_default().insert(p.shard_index); + } + let blocks: BTreeMap = frame.packets.iter().map(|p| (p.block, p.data_shards)).collect(); + if blocks.iter().all(|(b, k)| have.get(b).map_or(0, BTreeSet::len) >= usize::from(*k)) { + Outcome::Deliver + } else { + Outcome::Lose + } +} + +/// Data shards a frame lost (what `recovered_shards` must say when it is delivered). +fn data_lost(frame: &Frame, arrived: &[&VPkt]) -> u16 { + let got: BTreeSet<(u8, u16)> = arrived.iter().map(|p| (p.block, p.shard_index)).collect(); + frame.packets.iter().filter(|p| !p.is_parity && !got.contains(&(p.block, p.shard_index))).count() as u16 +} + +struct Run { + events: Vec, + stats: VideoStats, +} + +fn run_with(cipher: bool, datagrams: &[Vec]) -> Run { + let mut d = VideoDepacketizer::new(config(cipher)).expect("VideoDepacketizer::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 for packets within the size cap"); + now += 10; + while let Some(e) = d.poll_event() { + events.push(e); + } + } + // Flush: let every incomplete frame time out. + 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() } +} + +/// Every Frame event is byte-exact, in order, at most once; every frame marked `Deliver` came out; every frame marked +/// `Lose` is in a FrameLost range; nothing is both. +fn check(frames: &[Frame], outcomes: &[Outcome], recovered: Option<&[u16]>, run: &Run) { + let pos: HashMap = frames.iter().enumerate().map(|(i, f)| (f.expect.frame_index, i)).collect(); + let mut delivered = vec![false; frames.len()]; + let mut lost = vec![false; frames.len()]; + let mut last_pos: Option = None; + for e in &run.events { + match e { + VideoEvent::Frame(f) => { + let &i = pos.get(&f.frame_index).unwrap_or_else(|| panic!("frame {} was never sent", f.frame_index)); + let want = &frames[i].expect; + assert!(f.bitstream == want.bitstream, "frame {} corrupt: {} bytes, want {}", f.frame_index, f.bitstream.len(), want.bitstream.len()); + assert_eq!(f.header.raw, want.header, "frame {} header", f.frame_index); + assert_eq!(f.rtp_timestamp, want.rtp_timestamp, "frame {} timestamp", f.frame_index); + assert!(f.completed_at >= f.first_packet_at); + assert!(!delivered[i], "frame {} delivered twice", f.frame_index); + assert!(last_pos.is_none_or(|l| i > l), "frame {} out of order", f.frame_index); + if let Some(r) = recovered { + assert_eq!(f.recovered_shards, r[i], "frame {} recovered shards", f.frame_index); + } + last_pos = Some(i); + delivered[i] = true; + } + VideoEvent::FrameLost { first, last } => { + let span = last.wrapping_sub(*first); + assert!(span < 1 << 31, "FrameLost {first}..={last} is not a forward range"); + for (i, f) in frames.iter().enumerate() { + if f.expect.frame_index.wrapping_sub(*first) <= span { + lost[i] = true; + } + } + } + } + } + for (i, f) in frames.iter().enumerate() { + let idx = f.expect.frame_index; + assert!(!(delivered[i] && lost[i]), "frame {idx} both delivered and reported lost"); + match outcomes[i] { + Outcome::Deliver => assert!(delivered[i], "frame {idx} was recoverable but not delivered (lost: {})", lost[i]), + Outcome::Lose => assert!(lost[i], "frame {idx} was not recoverable but not reported lost"), + } + } +} + +/// Runs a scenario where `keep(frame_number, packet_number_in_frame, packet)` decides what arrives (frames 0 and +/// last are always kept whole), optionally reordered and duplicated. +fn scenario(seed: u64, n: usize, percentages: &[u8], keep: impl Fn(&mut SeqRng, usize, usize, &VPkt) -> bool) -> (Vec, Vec, Vec, Vec>) { + let mut rng = SeqRng::new(seed); + let mut host = VideoHost::new(PACKET_SIZE); + let fs = frames(&mut rng, &mut host, 0, n, percentages); + let mut outcomes = Vec::new(); + let mut recovered = Vec::new(); + let mut datagrams = Vec::new(); + for (fi, f) in fs.iter().enumerate() { + let arrived: Vec<&VPkt> = f + .packets + .iter() + .enumerate() + .filter(|(pi, p)| fi == 0 || fi == n - 1 || keep(&mut rng, fi, *pi, p)) + .map(|(_, p)| p) + .collect(); + outcomes.push(outcome(f, &arrived)); + recovered.push(data_lost(f, &arrived)); + datagrams.extend(arrived.iter().map(|p| p.bytes.clone())); + } + (fs, outcomes, recovered, datagrams) +} + +const MIXED: &[u8] = &[0, 10, 20, 50, 100, 200]; + +// ================================================================================================ patterns + +#[test] +fn no_loss() { + let (fs, out, rec, dg) = scenario(1, 30, MIXED, |_, _, _, _| true); + assert!(out.iter().all(|o| *o == Outcome::Deliver)); + let r = run_with(false, &dg); + check(&fs, &out, Some(&rec), &r); + assert_eq!(r.stats.frames, 30); + assert_eq!(r.stats.frames_lost, 0); + assert_eq!(r.stats.shards_recovered, 0); + assert_eq!(r.stats.packets_dropped, 0); + assert_eq!(r.stats.packets, dg.len() as u64); +} + +#[test] +fn random_loss() { + for (seed, p) in [(10u64, 5usize), (11, 15), (12, 30), (13, 50), (14, 15), (15, 30)] { + let (fs, out, rec, dg) = scenario(seed, 40, MIXED, move |rng, _, _, _| rng.below(100) >= p); + let r = run_with(false, &dg); + check(&fs, &out, Some(&rec), &r); + let delivered = out.iter().filter(|o| **o == Outcome::Deliver).count() as u64; + assert_eq!(r.stats.frames, delivered, "seed {seed}"); + // At least the shards of delivered frames; blocks rebuilt inside frames that were lost anyway may add more. + assert!(r.stats.shards_recovered >= rec.iter().zip(&out).filter(|(_, o)| **o == Outcome::Deliver).map(|(r, _)| u64::from(*r)).sum::()); + } +} + +#[test] +fn bursty_loss() { + for seed in 20..26u64 { + // One burst of 1..=8 consecutive packets per frame, at a random place. + let mut rng = SeqRng::new(seed * 7); + let bursts: Vec<(usize, usize)> = (0..40).map(|_| (rng.below(30), 1 + rng.below(8))).collect(); + let (fs, out, rec, dg) = scenario(seed, 40, MIXED, move |_, fi, pi, _| { + let (start, len) = bursts[fi]; + !(start..start + len).contains(&pi) + }); + check(&fs, &out, Some(&rec), &run_with(false, &dg)); + } + // A burst across a frame boundary: the tail of one frame and the head of the next. + let (fs, _, _, _) = scenario(27, 3, &[50], |_, _, _, _| true); + let mut dg = Vec::new(); + let mut arrived: Vec> = vec![Vec::new(); 3]; + for (fi, f) in fs.iter().enumerate() { + for (pi, p) in f.packets.iter().enumerate() { + let tail = fi == 1 && pi + 2 >= f.packets.len(); + let head = fi == 2 && pi < 2; + if !(tail || head) { + arrived[fi].push(p); + dg.push(p.bytes.clone()); + } + } + } + let out: Vec = fs.iter().zip(&arrived).map(|(f, a)| outcome(f, a)).collect(); + check(&fs, &out, None, &run_with(false, &dg)); +} + +#[test] +fn all_parity_lost() { + let (fs, out, rec, dg) = scenario(30, 30, &[20, 50, 100], |_, _, _, p| !p.is_parity); + assert!(out.iter().all(|o| *o == Outcome::Deliver)); + assert!(rec.iter().all(|r| *r == 0)); + check(&fs, &out, Some(&rec), &run_with(false, &dg)); +} + +#[test] +fn all_data_lost_but_recoverable() { + // 100 % and 200 % FEC: every data shard of a frame lost, rebuilt from parity alone. + let (fs, out, rec, dg) = scenario(31, 20, &[100, 200], |_, _, _, p| p.is_parity); + assert!(out.iter().all(|o| *o == Outcome::Deliver)); + let r = run_with(false, &dg); + check(&fs, &out, Some(&rec), &r); + assert!(r.stats.shards_recovered > 0); +} + +#[test] +fn last_packet_lost() { + // The last packet of each frame (its last parity packet, or the end-of-frame data packet without FEC). + let (fs, ..) = scenario(32, 30, MIXED, |_, _, _, _| true); + let mut datagrams = Vec::new(); + let mut outcomes = Vec::new(); + let mut recovered = Vec::new(); + for (fi, f) in fs.iter().enumerate() { + let n = f.packets.len(); + let arrived: Vec<&VPkt> = f.packets.iter().take(if fi == 0 || fi + 1 == fs.len() { n } else { n - 1 }).collect(); + outcomes.push(outcome(f, &arrived)); + recovered.push(data_lost(f, &arrived)); + datagrams.extend(arrived.iter().map(|p| p.bytes.clone())); + } + check(&fs, &outcomes, Some(&recovered), &run_with(false, &datagrams)); + + // The end-of-frame data packet itself (flags 0x02), with FEC to rebuild it. + let (fs, out, rec, dg) = scenario(33, 30, &[20, 50], |_, _, _, p| p.is_parity || p.bytes[24] & 0x02 == 0); + assert!(out.iter().all(|o| *o == Outcome::Deliver)); + check(&fs, &out, Some(&rec), &run_with(false, &dg)); + + // ... and without FEC: lost. + let (fs, out, rec, dg) = scenario(34, 10, &[0], |_, _, _, p| p.bytes[24] & 0x02 == 0); + assert!(out[1..9].iter().all(|o| *o == Outcome::Lose)); + check(&fs, &out, Some(&rec), &run_with(false, &dg)); +} + +#[test] +fn reordered() { + for seed in 40..46u64 { + let (fs, out, _, mut dg) = scenario(seed, 30, MIXED, move |rng, _, _, _| rng.below(100) >= 10); + // Shuffle within windows spanning about two frames. + let mut rng = SeqRng::new(seed); + let first_len = fs[0].packets.len(); + let window = 24; + let mut i = first_len; // keep frame 0 first so the stream has a known start + while i < dg.len() { + let end = (i + window).min(dg.len()); + rng.shuffle(&mut dg[i..end]); + i = end; + } + check(&fs, &out, None, &run_with(false, &dg)); + } +} + +#[test] +fn duplicated() { + for seed in 50..54u64 { + let (fs, out, _, dg) = scenario(seed, 30, MIXED, move |rng, _, _, _| rng.below(100) >= 10); + let mut rng = SeqRng::new(seed); + let mut with_dups = Vec::new(); + let mut dups = 0u64; + for (i, g) in dg.iter().enumerate() { + with_dups.push(g.clone()); + if i > 0 && rng.below(100) < 30 { + // Again now, and an earlier packet again later. + with_dups.push(g.clone()); + with_dups.push(dg[rng.below(i)].clone()); + dups += 2; + } + } + let r = run_with(false, &with_dups); + check(&fs, &out, None, &r); + assert!(r.stats.packets_dropped >= dups / 2, "duplicates are counted as dropped: {} of {dups}", r.stats.packets_dropped); + } +} + +#[test] +fn reordered_and_duplicated_with_loss() { + for seed in 60..64u64 { + let (fs, out, _, dg) = scenario(seed, 40, MIXED, move |rng, _, _, _| rng.below(100) >= 20); + let mut rng = SeqRng::new(seed ^ 0xFF); + let mut mixed: Vec> = dg.iter().flat_map(|g| if rng.below(5) == 0 { vec![g.clone(), g.clone()] } else { vec![g.clone()] }).collect(); + let start = fs[0].packets.len(); + let mut i = start; + while i < mixed.len() { + let end = (i + 16).min(mixed.len()); + rng.shuffle(&mut mixed[i..end]); + i = end; + } + check(&fs, &out, None, &run_with(false, &mixed)); + } +} + +// ================================================================================================ untrusted bytes 0-31 + +#[test] +fn recovered_shard_headers_are_not_trusted() { + // Parity computed over data shards whose bytes 0-31 were scrambled: a rebuilt shard's RTP and NV header bytes + // are guaranteed garbage (wrong frame index, flags, FEC fields). Only its payload and its place from the shard + // index may be used. + let mut rng = SeqRng::new(70); + let mut host = VideoHost::new(PACKET_SIZE); + host.scramble_parity_headers = true; + let fs = frames(&mut rng, &mut host, 0, 30, &[50, 100]); + let mut dg = Vec::new(); + let mut out = Vec::new(); + let mut rec = Vec::new(); + for (fi, f) in fs.iter().enumerate() { + // Lose the first data shard of every block (often the start-of-frame packet) and, where the budget allows, + // the end-of-frame packet. + let arrived: Vec<&VPkt> = f + .packets + .iter() + .filter(|p| fi == 0 || p.is_parity || (p.shard_index != 0 && !(p.bytes[24] & 0x02 != 0 && p.parity_shards >= 2))) + .collect(); + out.push(outcome(f, &arrived)); + rec.push(data_lost(f, &arrived)); + dg.extend(arrived.iter().map(|p| p.bytes.clone())); + } + assert!(out.iter().all(|o| *o == Outcome::Deliver)); + let r = run_with(false, &dg); + check(&fs, &out, Some(&rec), &r); + assert!(r.stats.shards_recovered >= 30); +} + +// ================================================================================================ wraps and strays + +#[test] +fn rtp_sequence_wraps_inside_frames() { + let mut rng = SeqRng::new(80); + let mut host = VideoHost::new(PACKET_SIZE); + host.next_sequence = 0xFFE0; + let fs = frames(&mut rng, &mut host, 0, 20, &[20, 50]); + assert!(host.next_sequence < 0xFFE0, "the stream passed 0xFFFF -> 0"); + let mut dg = Vec::new(); + let mut out = Vec::new(); + for (fi, f) in fs.iter().enumerate() { + let arrived: Vec<&VPkt> = f.packets.iter().enumerate().filter(|(pi, _)| fi == 0 || pi % 5 != 1).map(|(_, p)| p).collect(); + out.push(outcome(f, &arrived)); + dg.extend(arrived.iter().map(|p| p.bytes.clone())); + } + check(&fs, &out, None, &run_with(false, &dg)); +} + +#[test] +fn frame_index_wraps() { + let mut rng = SeqRng::new(81); + let mut host = VideoHost::new(PACKET_SIZE); + let fs = frames(&mut rng, &mut host, u32::MAX - 5, 12, &[50]); + assert_eq!(fs[6].expect.frame_index, 0); + let mut dg = Vec::new(); + let mut out = Vec::new(); + for (fi, f) in fs.iter().enumerate() { + // Frame 0 (the one after u32::MAX) is entirely lost; the others lose one packet. + let arrived: Vec<&VPkt> = if f.expect.frame_index == 0 { vec![] } else { f.packets.iter().skip(usize::from(fi != 0)).collect() }; + out.push(outcome(f, &arrived)); + dg.extend(arrived.iter().map(|p| p.bytes.clone())); + } + assert_eq!(out[6], Outcome::Lose); + check(&fs, &out, None, &run_with(false, &dg)); +} + +#[test] +fn far_past_and_far_future_packets() { + let mut rng = SeqRng::new(82); + let mut host = VideoHost::new(PACKET_SIZE); + let fs = frames(&mut rng, &mut host, 5000, 10, &[50]); + let mut dg: Vec> = fs[..5].iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone())).collect(); + // A stray from long ago, a replay of an already delivered frame, and a lone packet from far ahead. + let mut stray = fs[0].packets[0].bytes.clone(); + stray[20..24].copy_from_slice(&(5000u32 - 1000).to_le_bytes()); + dg.push(stray); + dg.push(fs[1].packets[0].bytes.clone()); + let mut future = fs[5].packets[0].bytes.clone(); + future[20..24].copy_from_slice(&(5000u32 + 1_000_000).to_le_bytes()); + dg.push(future); + dg.extend(fs[5..].iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone()))); + let r = run_with(false, &dg); + assert!(r.stats.packets_dropped >= 2, "the far-past stray and the replay are dropped: {:?}", r.stats); + // Whatever the far-future packet does, no frame comes out corrupt, none twice, and none out of order. + let pos: HashMap = fs.iter().enumerate().map(|(i, f)| (f.expect.frame_index, i)).collect(); + let mut seen = BTreeSet::new(); + let mut prev = None; + for e in &r.events { + match e { + VideoEvent::Frame(f) => { + let &i = pos.get(&f.frame_index).unwrap_or_else(|| panic!("frame {} was never sent", f.frame_index)); + assert_eq!(f.bitstream, fs[i].expect.bitstream); + assert!(seen.insert(i)); + assert!(prev.is_none_or(|l| i > l)); + prev = Some(i); + } + VideoEvent::FrameLost { first, last } => assert!(last.wrapping_sub(*first) < 1 << 31), + } + } + assert!((0..5).all(|i| seen.contains(&i)), "frames before the strays are delivered"); +} + +#[test] +fn bad_packets_inside_a_frame_are_dropped_not_used() { + let mut rng = SeqRng::new(83); + let mut host = VideoHost::new(PACKET_SIZE); + let fs = frames(&mut rng, &mut host, 0, 6, &[50]); + let mut dg = Vec::new(); + for f in &fs { + for p in &f.packets { + dg.push(p.bytes.clone()); + } + // Junk carrying the frame's own index: short, long, with impossible FEC fields. + let mut short = f.packets[0].bytes.clone(); + short.truncate(50); + let mut long = f.packets[0].bytes.clone(); + long.extend_from_slice(&[0xEE; 7]); + let bad_fec = video_packet_bytes(0, 0, f.expect.frame_index, 0x01, 0, fec_info(50, 900, 2), &[0xEE; 48]); + dg.extend([short, long, bad_fec, vec![], vec![0x90]]); + } + let r = run_with(false, &dg); + let out = vec![Outcome::Deliver; fs.len()]; + check(&fs, &out, None, &r); + assert!(r.stats.packets_dropped >= 5 * fs.len() as u64); +} + +// ================================================================================================ encryption + +#[test] +fn encrypted_stream_with_loss_and_tampering() { + let mut rng = SeqRng::new(90); + let mut host = VideoHost::new(PACKET_SIZE); + let fs = frames(&mut rng, &mut host, 0, 30, &[50, 100]); + let mut counter = 0u64; + let mut dg = Vec::new(); + let mut out = Vec::new(); + let mut tampered = 0u64; + for (fi, f) in fs.iter().enumerate() { + let mut arrived = Vec::new(); + for (pi, p) in f.packets.iter().enumerate() { + let mut e = common::video_encrypt(&KEY, counter, f.expect.frame_index, &p.bytes); + counter += 1; + if fi != 0 && pi == 1 { + // A flipped ciphertext byte: the tag fails, the packet counts as lost. + let last = e.len() - 1; + e[last] ^= 0x01; + tampered += 1; + } else if fi != 0 && rng.below(100) < 10 { + continue; + } else { + arrived.push(p); + } + dg.push(e); + } + out.push(outcome(f, &arrived)); + } + let r = run_with(true, &dg); + check(&fs, &out, None, &r); + assert!(r.stats.packets_dropped >= tampered); + // The same plaintext packets fed to a receiver that expects encryption are refused, not decoded. + let plain: Vec> = fs.iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone())).collect(); + let r = run_with(true, &plain); + assert!(r.events.iter().all(|e| !matches!(e, VideoEvent::Frame(_)))); + assert_eq!(r.stats.packets_dropped, plain.len() as u64); +} + +// ================================================================================================ API edges + +#[test] +fn config_bounds() { + for ps in [0u16, 1, 15] { + assert_err!(VideoDepacketizer::new(VideoConfig { packet_size: ps, ..config(false) }), Error::Malformed { .. }, "packet_size {ps}"); + } + let max = (MAX_VIDEO_PACKET_BYTES - 16) as u16; + assert!(VideoDepacketizer::new(VideoConfig { packet_size: max, ..config(false) }).is_ok()); + assert_err!(VideoDepacketizer::new(VideoConfig { packet_size: max + 1, ..config(false) }), Error::Malformed { .. }); + assert_err!(VideoDepacketizer::new(VideoConfig { packet_size: u16::MAX, ..config(false) }), Error::Malformed { .. }); + assert!(VideoDepacketizer::new(VideoConfig { packet_size: 1024, ..config(true) }).is_ok()); +} + +#[test] +fn push_sizes() { + let mut d = VideoDepacketizer::new(config(false)).unwrap(); + assert_too_large!(d.push(Instant::ZERO, &vec![0; MAX_VIDEO_PACKET_BYTES + 1]), MAX_VIDEO_PACKET_BYTES, MAX_VIDEO_PACKET_BYTES + 1); + assert_too_large!(d.push(Instant::ZERO, &vec![0; 1 << 20]), MAX_VIDEO_PACKET_BYTES, 1 << 20); + for g in [vec![], vec![0x90], vec![0; 31], vec![0xFF; 80], vec![0; MAX_VIDEO_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 incomplete_frame_times_out() { + let mut rng = SeqRng::new(100); + let mut host = VideoHost::new(PACKET_SIZE); + let fs = frames(&mut rng, &mut host, 0, 2, &[0]); + let mut d = VideoDepacketizer::new(config(false)).unwrap(); + let t0 = Instant::from_micros(5_000_000); + for p in &fs[0].packets { + d.push(t0, &p.bytes).unwrap(); + } + match d.poll_event() { + Some(VideoEvent::Frame(f)) => { + assert_eq!(f.first_packet_at, t0); + assert_eq!(f.completed_at, t0); + assert_eq!(f.frame_index, 0); + } + other => panic!("{other:?}"), + } + assert_eq!(d.poll_timeout(), None, "nothing pending"); + // Frame 1 without its last packet (no FEC): pending until its timeout. + let n = fs[1].packets.len(); + let t1 = Instant::from_micros(6_000_000); + for p in &fs[1].packets[..n - 1] { + d.push(t1, &p.bytes).unwrap(); + } + if n == 1 { + return; + } + assert_eq!(d.poll_event(), None); + let deadline = d.poll_timeout().expect("a deadline for the incomplete frame"); + assert!(deadline > t1 && deadline <= t1.saturating_add(TIMEOUT), "{deadline:?}"); + d.handle_timeout(t1.saturating_add(TIMEOUT / 2)).unwrap(); + assert_eq!(d.poll_event(), None, "not before the timeout"); + d.handle_timeout(t1.saturating_add(TIMEOUT)).unwrap(); + assert_eq!(d.poll_event(), Some(VideoEvent::FrameLost { first: 1, last: 1 })); + assert_eq!(d.stats().frames_lost, 1); +} + +#[test] +fn frames_in_flight_are_capped() { + // One packet each of many incomplete frames: the oldest are declared lost before any timeout. + let mut rng = SeqRng::new(101); + let mut host = VideoHost::new(PACKET_SIZE); + let fs = frames(&mut rng, &mut host, 0, MAX_FRAMES_IN_FLIGHT + 5, &[0]); + let mut d = VideoDepacketizer::new(config(false)).unwrap(); + for p in &fs[0].packets { + d.push(Instant::ZERO, &p.bytes).unwrap(); + } + let mut lost = BTreeSet::new(); + for f in &fs[1..] { + if f.packets.len() < 2 { + continue; + } + d.push(Instant::ZERO, &f.packets[0].bytes).unwrap(); + } + while let Some(e) = d.poll_event() { + if let VideoEvent::FrameLost { first, last } = e { + lost.extend(first..=last); + } + } + assert!(!lost.is_empty(), "more than MAX_FRAMES_IN_FLIGHT incomplete frames: the oldest must be given up"); + assert!(!lost.contains(&0)); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 48, ..ProptestConfig::default() })] + + /// Random frames, random loss, random reordering: exact or reported lost, never corrupt. + #[test] + fn generated_patterns(seed in any::(), loss in 0usize..60, window in 1usize..30, dup in 0usize..30) { + let (fs, out, _, dg) = scenario(seed, 16, MIXED, move |rng, _, _, _| rng.below(100) >= loss); + let mut rng = SeqRng::new(seed.rotate_left(17)); + let mut mixed: Vec> = dg.iter().flat_map(|g| if rng.below(100) < dup { vec![g.clone(), g.clone()] } else { vec![g.clone()] }).collect(); + let mut i = fs[0].packets.len(); + while i < mixed.len() { + let end = (i + window).min(mixed.len()); + rng.shuffle(&mut mixed[i..end]); + i = end; + } + check(&fs, &out, None, &run_with(false, &mixed)); + } + + /// Arbitrary datagrams never panic, and nothing that comes out is larger than the frame cap. + #[test] + fn arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::(), 0..120), 0..60)) { + let r = run_with(false, &datagrams); + for e in r.events { + match e { + VideoEvent::Frame(f) => prop_assert!(f.bitstream.len() <= domistream::video::MAX_FRAME_BYTES), + VideoEvent::FrameLost { first, last } => prop_assert!(last.wrapping_sub(first) < 1 << 31), + } + } + } +}