diff --git a/crates/domistream/src/video/mod.rs b/crates/domistream/src/video/mod.rs index b0f6772..5a54a64 100644 --- a/crates/domistream/src/video/mod.rs +++ b/crates/domistream/src/video/mod.rs @@ -20,8 +20,10 @@ use crate::util::{array, cap, malformed, need}; use crate::{Error, Instant, Result}; pub mod packet; +pub mod packetizer; pub use packet::{FecInfo, FrameHeader, FrameType, NvVideoHeader, VideoFlags, VideoPacket, parse_video_packet}; +pub use packetizer::{EncodedFrame, VideoPacketizer, VideoPacketizerConfig}; /// Length of the prefix of an encrypted packet: IV 12 + frame number 4 + tag 16. pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16; @@ -69,6 +71,17 @@ impl VideoCipher { } } +impl VideoCipher { + /// Seals one plaintext packet (host side): `IV ‖ frame number ‖ tag ‖ ciphertext`. + /// + /// # Errors + /// [`Error::Unimplemented`] (stub). + pub fn encrypt(&self, counter: u64, frame_number: u32, packet: &[u8]) -> Result> { + let _ = (counter, frame_number, packet, &self.key); + Err(Error::Unimplemented) + } +} + impl fmt::Debug for VideoCipher { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("VideoCipher()") diff --git a/crates/domistream/src/video/packetizer.rs b/crates/domistream/src/video/packetizer.rs new file mode 100644 index 0000000..298447d --- /dev/null +++ b/crates/domistream/src/video/packetizer.rs @@ -0,0 +1,136 @@ +//! The video send path, host side (`docs/PROTOCOL.md` 5.2, 5.3, 7): one encoded access unit → the RTP + NV-header +//! datagrams of one frame, in FEC blocks with Reed-Solomon parity, optionally AES-128-GCM sealed. +//! +//! Stub: the API is fixed and tested first; the bodies follow. + +use super::VideoCipher; +use super::packet::{FRAME_HEADER_LEN, FrameType}; +use crate::{Error, Result}; + +/// The NV header's multi-FEC flags byte (`docs/PROTOCOL.md` 5.2, UNKNOWN U15: sent as observed, meaning unknown). +pub const MULTI_FEC_FLAGS: u8 = 0x10; +/// Byte 0 of the structured frame header (`docs/PROTOCOL.md` 5.2). +pub const FRAME_HEADER_TYPE: u8 = 0x01; +/// Most data shards one frame can carry: [`super::packet::MAX_FEC_BLOCKS`] blocks of at most +/// [`crate::fec::MAX_SHARDS`] shards. +pub const MAX_DATA_SHARDS_PER_FRAME: usize = super::packet::MAX_FEC_BLOCKS * crate::fec::MAX_SHARDS; + +/// Settings of the video sender, from the client's ANNOUNCE (`docs/PROTOCOL.md` 2.4). +#[derive(Clone, Debug)] +pub struct VideoPacketizerConfig { + /// Negotiated `packetSize` (payload + 16-byte NV header; the datagram adds the 16-byte RTP part). + pub packet_size: u16, + /// Requested FEC percentage (`x-nv-vqos[0].fec.repairPercent` or equivalent). + pub fec_percentage: u8, + /// Minimum parity packets per block (`x-nv-vqos[0].fec.minRequiredFecPackets`). + pub min_required_fec_packets: u8, + /// Seal every datagram with this cipher when video encryption was negotiated. + pub cipher: Option, + /// RTP sequence number of the first datagram. + pub first_sequence: u16, +} + +/// One encoded access unit from the encoder. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EncodedFrame<'a> { + /// Frame index (NV header bytes 20-23). + pub frame_index: u32, + /// Frame type written into the frame header. + pub frame_type: FrameType, + /// RTP timestamp shared by every datagram of the frame (UNKNOWN U29: clock rate). + pub rtp_timestamp: u32, + /// Host processing latency, frame header bytes 1-2 (unit UNKNOWN, U13). + pub processing_latency: u16, + /// The Annex-B bitstream, start codes included. + pub bitstream: &'a [u8], +} + +/// The FEC geometry of one block. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct FecBlock { + /// Data shards `k`. + pub data_shards: u16, + /// Parity shards `m = ceil(k × percentage / 100)`. + pub parity_shards: u16, + /// The percentage written into the block's FEC info. + pub fec_percentage: u8, + /// The requested protection did not fit (`k + m <= 255`) and was lowered. + pub reduced: bool, +} + +/// Counters. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct VideoPacketizerStats { + /// Frames packetized. + pub frames: u64, + /// Datagrams produced (data + parity). + pub packets: u64, + /// Parity datagrams among them. + pub parity_packets: u64, + /// Blocks whose FEC was lowered to fit 255 shards. + pub fec_reduced_blocks: u64, +} + +/// Writes the structured 8-byte frame header (`docs/PROTOCOL.md` 5.2). +#[must_use] +pub fn write_frame_header( + frame_type: FrameType, + processing_latency: u16, + last_payload_len: u32, +) -> [u8; FRAME_HEADER_LEN] { + let _ = (frame_type, processing_latency, last_payload_len); + [0; FRAME_HEADER_LEN] +} + +/// Splits `data_shards` into FEC blocks. +/// +/// # Errors +/// [`Error::Unimplemented`] (stub). +pub fn plan_fec_blocks(data_shards: usize, fec_percentage: u8, min_parity: u8) -> Result> { + let _ = (data_shards, fec_percentage, min_parity); + Err(Error::Unimplemented) +} + +/// The video sender of one stream. +#[derive(Debug)] +pub struct VideoPacketizer { + config: VideoPacketizerConfig, +} + +impl VideoPacketizer { + /// A sender for one stream. + /// + /// # Errors + /// [`Error::Unimplemented`] (stub). + pub fn new(config: VideoPacketizerConfig) -> Result { + let _ = config; + Err(Error::Unimplemented) + } + + /// The largest bitstream one frame can carry. + #[must_use] + pub const fn max_bitstream_len(&self) -> usize { + 0 + } + + /// Packetizes one frame. + /// + /// # Errors + /// [`Error::Unimplemented`] (stub). + pub fn packetize(&mut self, frame: &EncodedFrame<'_>) -> Result>> { + let _ = (frame, &self.config); + Err(Error::Unimplemented) + } + + /// The RTP sequence number of the next datagram. + #[must_use] + pub const fn next_sequence(&self) -> u16 { + 0 + } + + /// Counters. + #[must_use] + pub const fn stats(&self) -> VideoPacketizerStats { + VideoPacketizerStats { frames: 0, packets: 0, parity_packets: 0, fec_reduced_blocks: 0 } + } +} diff --git a/crates/domistream/tests/video_packetizer.rs b/crates/domistream/tests/video_packetizer.rs new file mode 100644 index 0000000..c2d7a35 --- /dev/null +++ b/crates/domistream/tests/video_packetizer.rs @@ -0,0 +1,819 @@ +//! The video packetizer, host side (`docs/PROTOCOL.md` 5.2, 5.3, 7), checked against the client half: every frame +//! goes through the crate's own `VideoDepacketizer` and must come out identical and in order, also with up to `m` +//! packets of every block lost, reordered or duplicated; with more lost, the frame is reported lost, never corrupt. +//! Fixed vectors check one small frame byte by byte against the field table of 5.2, and the parity against an +//! independent GF(2^8) encoder with the Cauchy matrix of 5.3. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)] + +mod common; + +use core::time::Duration; +use std::collections::BTreeMap; + +use common::{SeqRng, gf}; +use domistream::fec::parity_count; +use domistream::video::packet::{ + FRAME_HEADER_LEN, MAX_FEC_BLOCKS, MAX_VIDEO_PACKET_BYTES, PAYLOAD_OFFSET, parse_frame_header, parse_video_packet, +}; +use domistream::video::packetizer::{ + EncodedFrame, MAX_DATA_SHARDS_PER_FRAME, VideoPacketizer, VideoPacketizerConfig, VideoPacketizerStats, + plan_fec_blocks, write_frame_header, +}; +use domistream::video::{ + ENCRYPTION_PREFIX_LEN, FrameType, MAX_FRAME_BYTES, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent, + VideoFrame, +}; +use domistream::{Error, Instant}; +use proptest::prelude::*; + +const KEY: [u8; 16] = *b"video-pack-key!!"; + +fn config(packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> VideoPacketizerConfig { + VideoPacketizerConfig { + packet_size, + fec_percentage: pct, + min_required_fec_packets: min, + cipher: encrypt.then(|| VideoCipher::new(KEY)), + first_sequence, + } +} + +fn sender(packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> VideoPacketizer { + VideoPacketizer::new(config(packet_size, pct, min, encrypt, first_sequence)).expect("VideoPacketizer::new") +} + +fn receiver(packet_size: u16, encrypt: bool) -> VideoDepacketizer { + VideoDepacketizer::new(VideoConfig { + packet_size, + cipher: encrypt.then(|| VideoCipher::new(KEY)), + frame_timeout: Duration::from_millis(50), + }) + .expect("VideoDepacketizer::new") +} + +/// A bitstream of exactly `len` bytes: a start code, then random bytes, every third frame with a zero tail (the +/// frame header's last-payload length, not the content, says where the frame ends). +fn bitstream(rng: &mut SeqRng, len: usize) -> Vec { + let mut b = rng.bytes(len); + for (dst, src) in b.iter_mut().zip([0u8, 0, 0, 1, 0x65]) { + *dst = src; + } + if rng.below(3) == 0 { + let tail = rng.below(len / 2 + 1); + for x in &mut b[len - tail..] { + *x = 0; + } + } + b +} + +/// One frame as sent. +#[derive(Clone, Debug)] +struct Sent { + index: u32, + frame_type: FrameType, + latency: u16, + timestamp: u32, + bitstream: Vec, + datagrams: Vec>, +} + +fn send_bytes(tx: &mut VideoPacketizer, rng: &mut SeqRng, index: u32, bitstream: Vec) -> Sent { + let frame_type = [FrameType::Predicted, FrameType::Key, FrameType::Recovery][rng.below(3)]; + let latency = rng.below(65_536) as u16; + let timestamp = rng.next_u64() as u32; + let frame = EncodedFrame { + frame_index: index, + frame_type, + rtp_timestamp: timestamp, + processing_latency: latency, + bitstream: &bitstream, + }; + let datagrams = tx.packetize(&frame).expect("packetize"); + Sent { index, frame_type, latency, timestamp, bitstream, datagrams } +} + +fn send(tx: &mut VideoPacketizer, rng: &mut SeqRng, index: u32, len: usize) -> Sent { + let b = bitstream(rng, len); + send_bytes(tx, rng, index, b) +} + +fn plain(datagram: &[u8], encrypt: bool) -> Vec { + if encrypt { VideoCipher::new(KEY).decrypt(datagram).expect("decrypt our own datagram") } else { datagram.to_vec() } +} + +/// A datagram's place in its frame, read from its plaintext. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Place { + block: u8, + shard: u16, + k: u16, + m: u16, +} + +fn place(datagram: &[u8], encrypt: bool) -> Place { + let bytes = plain(datagram, encrypt); + let p = parse_video_packet(&bytes).expect("our own datagram parses"); + let k = p.nv.fec.data_shards; + let m = parity_count(usize::from(k), p.nv.fec.fec_percentage).expect("consistent FEC fields") as u16; + Place { block: p.nv.fec.block_index, shard: p.nv.fec.shard_index, k, m } +} + +/// Datagram positions of each block, and the block's parity count. +fn blocks_of(sent: &Sent, encrypt: bool) -> BTreeMap, usize)> { + let mut out: BTreeMap, usize)> = BTreeMap::new(); + for (i, d) in sent.datagrams.iter().enumerate() { + let p = place(d, encrypt); + let e = out.entry(p.block).or_insert_with(|| (Vec::new(), usize::from(p.m))); + e.0.push(i); + } + out +} + +/// The frame's datagrams with, in every block, a random subset of `extra(m)` lost (`extra = 0` keeps all). +fn with_loss(rng: &mut SeqRng, sent: &Sent, encrypt: bool, lose: impl Fn(&mut SeqRng, usize) -> usize) -> Vec> { + let mut keep = vec![true; sent.datagrams.len()]; + for (positions, m) in blocks_of(sent, encrypt).values() { + let n = lose(rng, *m).min(positions.len()); + for i in rng.subset(positions.len(), n) { + keep[positions[i]] = false; + } + } + sent.datagrams.iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d.clone()).collect() +} + +#[derive(Debug, Default)] +struct Out { + frames: Vec, + lost: Vec<(u32, u32)>, +} + +fn drain(rx: &mut VideoDepacketizer, out: &mut Out) { + while let Some(e) = rx.poll_event() { + match e { + VideoEvent::Frame(f) => out.frames.push(f), + VideoEvent::FrameLost { first, last } => out.lost.push((first, last)), + } + } +} + +fn receive(rx: &mut VideoDepacketizer, datagrams: &[Vec]) -> Out { + let mut now = 1_000_000u64; + let mut out = Out::default(); + for d in datagrams { + rx.push(Instant::from_micros(now), d).expect("push never fails within the size cap"); + now += 10; + drain(rx, &mut out); + } + for _ in 0..64 { + now += 10_000_000; + rx.handle_timeout(Instant::from_micros(now)).unwrap(); + drain(rx, &mut out); + if rx.poll_timeout().is_none() { + break; + } + } + out +} + +/// Every frame not in `lost` came out identical and in order; every frame in `lost` is in a FrameLost range. +fn check(sent: &[Sent], lost: &[u32], out: &Out) { + let want: Vec<&Sent> = sent.iter().filter(|s| !lost.contains(&s.index)).collect(); + assert_eq!( + out.frames.iter().map(|f| f.frame_index).collect::>(), + want.iter().map(|s| s.index).collect::>(), + "frames delivered (lost ranges {:?})", + out.lost + ); + for (f, s) in out.frames.iter().zip(&want) { + assert!( + f.bitstream == s.bitstream, + "frame {} differs: {} bytes, want {}", + s.index, + f.bitstream.len(), + s.bitstream.len() + ); + assert_eq!(f.header.header_type, 0x01, "frame {} header type", s.index); + assert_eq!(f.header.frame_type, s.frame_type, "frame {} type", s.index); + assert_eq!(f.header.processing_latency, s.latency, "frame {} latency", s.index); + assert_eq!(f.rtp_timestamp, s.timestamp, "frame {} timestamp", s.index); + } + for &l in lost { + assert!( + out.lost.iter().any(|&(a, b)| l.wrapping_sub(a) <= b.wrapping_sub(a)), + "frame {l} was not reported lost: {:?}", + out.lost + ); + } +} + +/// Checks every field of every datagram of a frame against PROTOCOL.md 5.2/5.3 and returns the next sequence. +fn check_layout(s: &Sent, packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> u16 { + let payload = usize::from(packet_size) - 16; + let n = (FRAME_HEADER_LEN + s.bitstream.len()).div_ceil(payload); + let plan = plan_fec_blocks(n, pct, min).expect("plan"); + let total: usize = plan.iter().map(|b| usize::from(b.data_shards) + usize::from(b.parity_shards)).sum(); + assert_eq!(s.datagrams.len(), total, "frame {}: datagram count", s.index); + let last_block = (plan.len() - 1) as u8; + let mut seq = first_sequence; + let mut it = s.datagrams.iter(); + let mut data_seen = 0usize; + for (b, blk) in plan.iter().enumerate() { + let (k, m) = (usize::from(blk.data_shards), usize::from(blk.parity_shards)); + assert_eq!(m, parity_count(k, blk.fec_percentage).unwrap(), "plan m = ceil(k * pct / 100)"); + for shard in 0..k + m { + let d = it.next().expect("datagram"); + let extra = if encrypt { ENCRYPTION_PREFIX_LEN } else { 0 }; + assert_eq!(d.len(), usize::from(packet_size) + 16 + extra, "datagram length"); + let bytes = plain(d, encrypt); + let p = parse_video_packet(&bytes).expect("parses"); + assert_eq!(bytes[0], 0x90, "RTP byte 0"); + assert_eq!(p.rtp.payload_type, 0); + assert_eq!(p.rtp.sequence, seq, "sequence numbers are consecutive"); + assert_eq!(p.rtp.timestamp, s.timestamp); + assert_eq!(p.rtp.ssrc, 0); + assert_eq!(&bytes[12..16], &[0, 0, 0, 0], "reserved"); + assert_eq!(p.nv.stream_packet_index, u32::from(seq) << 8, "stream packet index"); + assert_eq!(p.nv.frame_index, s.index); + assert_eq!(bytes[25], 0, "reserved byte 25"); + assert_eq!(p.nv.multi_fec_flags, 0x10, "multi-FEC flags (U15)"); + assert_eq!(bytes[27] & 0x0F, 0, "multi-FEC blocks low bits"); + assert_eq!(bytes[28] & 0x0F, 0, "FEC info low bits"); + assert_eq!(p.nv.fec.block_index, b as u8); + assert_eq!(p.nv.fec.last_block_index, last_block); + assert_eq!(usize::from(p.nv.fec.shard_index), shard, "data first, then parity"); + assert_eq!(usize::from(p.nv.fec.data_shards), k); + assert_eq!(p.nv.fec.fec_percentage, blk.fec_percentage); + let flags = p.nv.flags.0; + if shard < k { + let mut want = 0x01; + if data_seen == 0 { + want |= 0x04; + } + if data_seen == n - 1 { + want |= 0x02; + } + assert_eq!(flags, want, "frame {} data shard {data_seen} flags", s.index); + data_seen += 1; + } else { + assert_eq!(flags, 0, "parity flags"); + } + seq = seq.wrapping_add(1); + } + } + assert_eq!(data_seen, n); + seq +} + +fn sizes(rng: &mut SeqRng, payload: usize, count: usize) -> Vec { + let max = MAX_DATA_SHARDS_PER_FRAME * payload - FRAME_HEADER_LEN; + // Around the shard boundaries: frame data (8 + len) of exactly one and two shards, and one byte either side. + let mut out = vec![0, 1]; + for edge in [payload, 2 * payload] { + let at = edge.saturating_sub(FRAME_HEADER_LEN); + out.extend([at.saturating_sub(1), at, at + 1]); + } + while out.len() < count { + out.push(match rng.below(4) { + 0 => rng.below(payload * 3), + 1 => rng.below(payload * 40), + _ => rng.below(payload * 300), + }); + } + out.into_iter().map(|s| s.min(max)).collect() +} + +const PACKET_SIZES: [u16; 9] = [17, 18, 20, 64, 100, 1024, 1040, 1408, 4080]; +const PERCENTAGES: [u8; 8] = [0, 1, 10, 20, 50, 100, 200, 255]; + +// ================================================================================================ fixed vectors + +#[test] +fn fixed_vector_one_small_frame() { + // packetSize 32: 16 bytes of payload per datagram. Frame data = 8-byte header + 7-byte bitstream = 15 bytes, + // so one data shard (zero-padded to 16) and, at 100 %, ceil(1 * 100 / 100) = 1 parity shard. + let mut tx = sender(32, 100, 0, false, 0x1234); + let bitstream = [0x00, 0x00, 0x00, 0x01, 0x65, 0xAA, 0xBB]; + let frame = EncodedFrame { + frame_index: 7, + frame_type: FrameType::Key, + rtp_timestamp: 90_000, + processing_latency: 0x0102, + bitstream: &bitstream, + }; + let out = tx.packetize(&frame).unwrap(); + #[rustfmt::skip] + let payload: [u8; 16] = [ + 0x01, // frame header type + 0x02, 0x01, // processing latency 0x0102, LE + 0x02, // frame type: key + 0x0F, 0x00, 0x00, 0x00, // last shard payload length 15, LE + 0x00, 0x00, 0x00, 0x01, 0x65, 0xAA, 0xBB, // the bitstream + 0x00, // zero padding to the full shard + ]; + #[rustfmt::skip] + let mut data = vec![ + 0x90, // RTP byte 0: version 2, extension bit + 0x00, // payload type 0 + 0x12, 0x34, // sequence 0x1234, BE + 0x00, 0x01, 0x5F, 0x90, // timestamp 90000, BE + 0x00, 0x00, 0x00, 0x00, // SSRC 0 + 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, 0x34, 0x12, 0x00, // stream packet index 0x1234 << 8 = 0x00123400, LE + 0x07, 0x00, 0x00, 0x00, // frame index 7, LE + 0x07, // flags: picture data 0x01 | end of frame 0x02 | start of frame 0x04 + 0x00, // reserved + 0x10, // multi-FEC flags (U15) + 0x00, // multi-FEC blocks: this block 0 (bits 4-5), last block 0 (bits 6-7) + 0x40, 0x06, 0x40, 0x00, // FEC info 0x00400640, LE: 100 << 4 | shard 0 << 12 | k 1 << 22 + ]; + data.extend_from_slice(&payload); + #[rustfmt::skip] + let mut parity = vec![ + 0x90, 0x00, // RTP byte 0, payload type 0 + 0x12, 0x35, // sequence 0x1235: the parity packet takes the next number + 0x00, 0x01, 0x5F, 0x90, // the frame's timestamp + 0x00, 0x00, 0x00, 0x00, // SSRC 0 + 0x00, 0x00, 0x00, 0x00, // reserved + 0x00, 0x35, 0x12, 0x00, // stream packet index 0x1235 << 8, LE + 0x07, 0x00, 0x00, 0x00, // frame index 7 + 0x00, // flags 0 on parity packets + 0x00, // reserved + 0x10, // multi-FEC flags + 0x00, // block 0 of 0 + 0x40, 0x16, 0x40, 0x00, // FEC info 0x00401640: 100 << 4 | shard 1 << 12 | k 1 << 22 + ]; + // k = 1, m = 1: the Cauchy matrix is [[1 / ((1 + 0) XOR 0)]] = [[1]], so the parity is the data packet itself + // and its payload part equals the data payload. + parity.extend_from_slice(&payload); + assert_eq!(out, vec![data, parity]); + assert_eq!(tx.next_sequence(), 0x1236); + assert_eq!(tx.stats(), VideoPacketizerStats { frames: 1, packets: 2, parity_packets: 1, fec_reduced_blocks: 0 }); +} + +#[test] +fn fixed_vector_cauchy_parity_k3_m1() { + // packetSize 20: 4 bytes of payload. 8 + 4 = 12 bytes of frame data = 3 data shards, last one full (4 bytes). + // At 33 %: m = ceil(3 * 33 / 100) = 1. PROTOCOL.md 5.3 gives P = [01 8e f4] for k = 3, m = 1. + let mut tx = sender(20, 33, 0, false, 0); + let bitstream = [0x00, 0x00, 0x01, 0x09]; + let frame = EncodedFrame { + frame_index: 0x0102_0304, + frame_type: FrameType::Predicted, + rtp_timestamp: 1, + processing_latency: 0xBEEF, + bitstream: &bitstream, + }; + let out = tx.packetize(&frame).unwrap(); + assert_eq!(out.len(), 4); + let shards: [[u8; 4]; 3] = [ + [0x01, 0xEF, 0xBE, 0x01], // header type, latency 0xBEEF LE, predicted + [0x04, 0x00, 0x00, 0x00], // last shard payload length 4, LE + [0x00, 0x00, 0x01, 0x09], // bitstream + ]; + for (i, s) in shards.iter().enumerate() { + assert_eq!(&out[i][PAYLOAD_OFFSET..], s, "data shard {i}"); + // FEC info: 33 << 4 | i << 12 | 3 << 22 + let info = (33u32 << 4) | ((i as u32) << 12) | (3 << 22); + assert_eq!(&out[i][28..32], &info.to_le_bytes(), "FEC info of shard {i}"); + } + let p = [0x01u8, 0x8E, 0xF4]; + let want: Vec = (0..4).map(|x| (0..3).fold(0, |acc, i| acc ^ gf::mul(p[i], shards[i][x]))).collect(); + assert_eq!(&out[3][PAYLOAD_OFFSET..], want.as_slice(), "parity = 01*d0 + 8e*d1 + f4*d2"); + assert_eq!(&out[3][28..32], &((33u32 << 4) | (3 << 12) | (3 << 22)).to_le_bytes(), "parity FEC info"); + assert_eq!(out[3][24], 0, "parity flags"); + assert_eq!(&out[3][2..4], &3u16.to_be_bytes(), "parity sequence"); +} + +#[test] +fn frame_header_writer_round_trips() { + for (t, byte) in + [(FrameType::Predicted, 1u8), (FrameType::Key, 2), (FrameType::Recovery, 5), (FrameType::Other(9), 9)] + { + for (lat, last) in [(0u16, 1u32), (0xFFFF, 4064), (0x1234, 0x0A0B_0C0D)] { + let h = write_frame_header(t, lat, last); + let mut want = vec![0x01]; + want.extend_from_slice(&lat.to_le_bytes()); + want.push(byte); + want.extend_from_slice(&last.to_le_bytes()); + assert_eq!(h.to_vec(), want); + let back = parse_frame_header(&h).unwrap(); + assert_eq!( + (back.header_type, back.processing_latency, back.frame_type, back.last_payload_len), + (1, lat, t, last) + ); + } + } +} + +// ================================================================================================ the FEC plan + +/// Parity the client asks for a block of `k`: `max(ceil(k * pct / 100), min)`. +fn target(k: usize, pct: u8, min: u8) -> usize { + (k * usize::from(pct)).div_ceil(100).max(usize::from(min)) +} + +/// Parity a block of `k` gets at percentage `p` (the receiver's formula). +fn m_at(k: usize, p: usize) -> usize { + (k * p).div_ceil(100) +} + +/// Whether the least percentage (at or above the request) that gives a block of `k` its target is an 8-bit value +/// and keeps the block within 255 shards. Parity comes in steps of `ceil(k * p / 100)`, so for `k > 100` the least +/// step can overshoot the target. +fn achievable(k: usize, pct: u8, min: u8) -> bool { + let t = target(k, pct, min); + let p = (usize::from(pct)..=255).find(|&p| m_at(k, p) >= t); + k <= 255 && p.is_some_and(|p| k + m_at(k, p) <= 255) +} + +#[test] +fn fec_plan_properties() { + for n in (1..=MAX_DATA_SHARDS_PER_FRAME).filter(|n| *n < 40 || n % 7 == 0 || *n > 1000) { + for pct in PERCENTAGES.into_iter().chain([3, 33, 34, 99]) { + for min in [0u8, 1, 2, 3, 4, 10, 255] { + let ctx = format!("n {n} pct {pct} min {min}"); + let plan = plan_fec_blocks(n, pct, min).unwrap(); + assert!((1..=MAX_FEC_BLOCKS).contains(&plan.len()), "{ctx}: {} blocks", plan.len()); + assert_eq!(plan.iter().map(|b| usize::from(b.data_shards)).sum::(), n, "{ctx}"); + let first_k = plan[0].data_shards; + for (i, b) in plan.iter().enumerate() { + let (k, m, p) = + (usize::from(b.data_shards), usize::from(b.parity_shards), usize::from(b.fec_percentage)); + assert!(k >= 1 && k + m <= 255, "{ctx}: k {k} m {m}"); + assert_eq!(m, parity_count(k, b.fec_percentage).unwrap(), "{ctx}: m follows from the percentage"); + if i + 1 < plan.len() { + assert_eq!(b.data_shards, first_k, "{ctx}: every block but the last carries the same k"); + } else { + assert!(b.data_shards <= first_k, "{ctx}"); + } + let t = target(k, pct, min); + assert_eq!( + b.reduced, + !achievable(k, pct, min), + "{ctx}: reduced exactly when the target cannot fit" + ); + if b.reduced { + // The most parity that fits: one percent more would not. + assert!(m < t, "{ctx}"); + assert!(p == 255 || k + m_at(k, p + 1) > 255, "{ctx}: k {k} p {p}: not the most that fits"); + } else { + // The least percentage, at or above the request, that gives the target. + assert!(m >= t && p >= usize::from(pct), "{ctx}: k {k} m {m} p {p}"); + assert!(p == usize::from(pct) || m_at(k, p - 1) < t, "{ctx}: k {k} p {p}: raised too far"); + } + } + // Fewest blocks: one block fewer could not carry the frame with the requested parity. + if plan.len() > 1 && !plan[0].reduced { + let fewer = plan.len() - 1; + assert!(!achievable(n.div_ceil(fewer), pct, min), "{ctx}: {} blocks where {fewer} do", plan.len()); + } + } + } + } + assert_err!(plan_fec_blocks(0, 20, 0), Error::Malformed { .. }); + assert_too_large!( + plan_fec_blocks(MAX_DATA_SHARDS_PER_FRAME + 1, 0, 0), + MAX_DATA_SHARDS_PER_FRAME, + MAX_DATA_SHARDS_PER_FRAME + 1 + ); +} + +#[test] +fn minimum_parity_raises_the_written_percentage() { + // One data shard at 0 % with at least 2 parity packets: 200 % is the smallest percentage giving m = 2. + let plan = plan_fec_blocks(1, 0, 2).unwrap(); + assert_eq!((plan[0].data_shards, plan[0].parity_shards, plan[0].fec_percentage), (1, 2, 200)); + // 3 shards, at least 2: 34 % (ceil(1.02) = 2), not 67 % (which would give 3). + let plan = plan_fec_blocks(3, 0, 2).unwrap(); + assert_eq!((plan[0].parity_shards, plan[0].fec_percentage), (2, 34)); + // Already enough: unchanged. + let plan = plan_fec_blocks(10, 50, 2).unwrap(); + assert_eq!((plan[0].parity_shards, plan[0].fec_percentage, plan[0].reduced), (5, 50, false)); +} + +// ================================================================================================ round trips + +#[test] +fn round_trip_random_sizes() { + for seed in 0..12u64 { + let mut rng = SeqRng::new(seed); + let packet_size = + if seed < PACKET_SIZES.len() as u64 { PACKET_SIZES[seed as usize] } else { 17 + rng.below(4064) as u16 }; + let pct = PERCENTAGES[rng.below(PERCENTAGES.len())]; + let min = [0u8, 1, 2, 4][rng.below(4)]; + let payload = usize::from(packet_size) - 16; + let first_sequence = rng.next_u64() as u16; + let mut tx = sender(packet_size, pct, min, false, first_sequence); + let mut seq = first_sequence; + let first_index = rng.next_u64() as u32; + let sent: Vec = sizes(&mut rng, payload, 16) + .into_iter() + .enumerate() + .map(|(i, len)| send(&mut tx, &mut rng, first_index.wrapping_add(i as u32), len)) + .collect(); + for s in &sent { + seq = check_layout(s, packet_size, pct, min, false, seq); + } + assert_eq!(tx.next_sequence(), seq); + let all: Vec> = sent.iter().flat_map(|s| s.datagrams.clone()).collect(); + check(&sent, &[], &receive(&mut receiver(packet_size, false), &all)); + let stats = tx.stats(); + assert_eq!(stats.frames, sent.len() as u64); + assert_eq!(stats.packets, all.len() as u64); + } +} + +#[test] +fn round_trip_with_up_to_m_lost_per_block() { + for seed in 100..112u64 { + let mut rng = SeqRng::new(seed); + let packet_size = PACKET_SIZES[rng.below(PACKET_SIZES.len())]; + let pct = [10u8, 20, 50, 100, 200, 255][rng.below(6)]; + let min = [0u8, 1, 2][rng.below(3)]; + let payload = usize::from(packet_size) - 16; + let mut tx = sender(packet_size, pct, min, false, rng.next_u64() as u16); + let sent: Vec = sizes(&mut rng, payload, 14) + .into_iter() + .enumerate() + .map(|(i, l)| send(&mut tx, &mut rng, i as u32, l)) + .collect(); + let mut datagrams = Vec::new(); + for s in &sent { + datagrams.extend(with_loss(&mut rng, s, false, |r, m| if r.below(3) == 0 { m } else { r.below(m + 1) })); + } + let out = receive(&mut receiver(packet_size, false), &datagrams); + check(&sent, &[], &out); + } +} + +#[test] +fn every_data_shard_lost_is_rebuilt_when_parity_covers_it() { + // 100 %: m = k, so the parity alone carries the frame. + let mut rng = SeqRng::new(7); + let mut tx = sender(64, 100, 0, false, 0); + let sent: Vec = (0..6).map(|i| send(&mut tx, &mut rng, i, 48 * (1 + 5 * i as usize))).collect(); + let mut datagrams = Vec::new(); + for s in &sent { + datagrams.extend(s.datagrams.iter().filter(|d| place(d, false).shard >= place(d, false).k).cloned()); + } + let out = receive(&mut receiver(64, false), &datagrams); + check(&sent, &[], &out); + assert!(out.frames.iter().all(|f| f.recovered_shards > 0)); +} + +#[test] +fn more_than_m_lost_reports_the_frame_lost() { + for seed in 200..216u64 { + let mut rng = SeqRng::new(seed); + let packet_size = PACKET_SIZES[1 + rng.below(PACKET_SIZES.len() - 1)]; + let pct = [0u8, 10, 20, 50, 100][rng.below(5)]; + let payload = usize::from(packet_size) - 16; + let mut tx = sender(packet_size, pct, 0, false, 0xFFF0); + let sent: Vec = (0..7) + .map(|i| { + let len = 1 + rng.below(payload * 30); + send(&mut tx, &mut rng, 1000 + i, len) + }) + .collect(); + let victim = 1 + rng.below(5); + let mut datagrams = Vec::new(); + for (i, s) in sent.iter().enumerate() { + if i == victim { + // One block loses m + 1 packets, the others up to m. + let blocks = blocks_of(s, false); + let hit = *blocks.keys().nth(rng.below(blocks.len())).unwrap(); + let mut keep = vec![true; s.datagrams.len()]; + for (b, (positions, m)) in &blocks { + let n = if *b == hit { m + 1 } else { rng.below(m + 1) }; + for j in rng.subset(positions.len(), n) { + keep[positions[j]] = false; + } + } + datagrams.extend(s.datagrams.iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d.clone())); + } else { + datagrams.extend(s.datagrams.iter().cloned()); + } + } + let out = receive(&mut receiver(packet_size, false), &datagrams); + check(&sent, &[1000 + victim as u32], &out); + } +} + +#[test] +fn reordered_and_duplicated() { + for seed in 300..310u64 { + let mut rng = SeqRng::new(seed); + let packet_size = PACKET_SIZES[rng.below(PACKET_SIZES.len())]; + let pct = [0u8, 20, 50][rng.below(3)]; + let payload = usize::from(packet_size) - 16; + let mut tx = sender(packet_size, pct, 1, false, rng.next_u64() as u16); + let sent: Vec = sizes(&mut rng, payload, 12) + .into_iter() + .enumerate() + .map(|(i, l)| send(&mut tx, &mut rng, i as u32, l)) + .collect(); + let mut datagrams = Vec::new(); + for pair in sent.chunks(2) { + // Two frames' datagrams interleaved in random order, with random duplicates. + let mut window: Vec> = pair.iter().flat_map(|s| s.datagrams.clone()).collect(); + let dups: Vec> = + (0..rng.below(window.len() + 1)).map(|_| window[rng.below(window.len())].clone()).collect(); + window.extend(dups); + rng.shuffle(&mut window); + datagrams.extend(window); + } + // And a few stale duplicates of earlier frames at the end. + for _ in 0..5 { + let s = &sent[rng.below(sent.len())]; + datagrams.push(s.datagrams[rng.below(s.datagrams.len())].clone()); + } + check(&sent, &[], &receive(&mut receiver(packet_size, false), &datagrams)); + } +} + +#[test] +fn sequence_numbers_continue_across_frames_and_wrap() { + let mut rng = SeqRng::new(9); + let mut tx = sender(64, 50, 0, false, 0xFFF0); + let mut seq = 0xFFF0u16; + let mut sent = Vec::new(); + for i in 0..10u32 { + let s = send(&mut tx, &mut rng, u32::MAX - 4 + i, 48 * 3); + seq = check_layout(&s, 64, 50, 0, false, seq); + sent.push(s); + } + assert!(seq < 0xFFF0, "the sequence wrapped"); + assert_eq!(tx.next_sequence(), seq); + let all: Vec> = sent.iter().flat_map(|s| s.datagrams.clone()).collect(); + check(&sent, &[], &receive(&mut receiver(64, false), &all)); +} + +#[test] +fn parity_matches_an_independent_cauchy_encoder() { + // Parity over whole packets (5.3): bytes 32 on of parity j = sum_i 1 / ((m + i) XOR j) * data_i, with headers + // of the parity packets written afterwards. + let mut rng = SeqRng::new(11); + for (packet_size, pct, len) in [(64u16, 50u8, 48 * 9), (100, 20, 84 * 30), (1024, 100, 1008 * 4 + 3), (17, 255, 40)] + { + let mut tx = sender(packet_size, pct, 0, false, 0); + let s = send(&mut tx, &mut rng, 5, len); + for (positions, m) in blocks_of(&s, false).values() { + let k = positions.len() - m; + let data: Vec> = positions[..k].iter().map(|&i| s.datagrams[i].clone()).collect(); + let matrix: Vec = (0..*m).flat_map(|j| (0..k).map(move |i| gf::inv(((m + i) ^ j) as u8))).collect(); + let parity = gf::encode(&matrix, &data, *m); + for (j, &pos) in positions[k..].iter().enumerate() { + assert_eq!(&s.datagrams[pos][PAYLOAD_OFFSET..], &parity[j][PAYLOAD_OFFSET..], "parity {j}"); + } + } + } +} + +#[test] +fn several_megabyte_frames() { + let mut rng = SeqRng::new(13); + let packet_size = 4080; // largest: 4064 bytes of payload, 4096-byte datagrams + let mut tx = sender(packet_size, 20, 2, false, 0); + let max = tx.max_bitstream_len(); + assert_eq!(max, (MAX_DATA_SHARDS_PER_FRAME * 4064 - FRAME_HEADER_LEN).min(MAX_FRAME_BYTES - FRAME_HEADER_LEN)); + let big = send(&mut tx, &mut rng, 1, 3_000_000); + let lossy = with_loss(&mut rng, &big, false, |_, m| m); + let out = receive(&mut receiver(packet_size, false), &lossy); + check(std::slice::from_ref(&big), &[], &out); + // The largest frame: 4 blocks of 255 data shards, no room for parity, so the FEC is lowered and counted. + let before = tx.stats().fec_reduced_blocks; + let largest = send(&mut tx, &mut rng, 2, max); + assert_eq!(tx.stats().fec_reduced_blocks - before, 4); + assert_eq!(largest.datagrams.len(), MAX_DATA_SHARDS_PER_FRAME); + let out = receive(&mut receiver(packet_size, false), &largest.datagrams); + check(std::slice::from_ref(&largest), &[], &out); +} + +// ================================================================================================ encryption + +#[test] +fn video_cipher_encrypt_matches_dotnet_vectors() { + let v = common::video_vectors(); + let c = VideoCipher::new(v.arr16("key")); + for (name, counter, frame) in + [("v_0", 0u64, 0u32), ("v_1", 1, 0), ("v_big_counter", 0x0102_0304_0506_0708, 0x1122_3344), ("v_1040", 7, 3)] + { + assert_eq!( + c.encrypt(counter, frame, &v.bytes(&format!("{name}_plain"))).unwrap(), + v.bytes(&format!("{name}_packet")), + "{name}" + ); + } + let too_big = vec![0u8; MAX_VIDEO_PACKET_BYTES - ENCRYPTION_PREFIX_LEN + 1]; + assert_too_large!(c.encrypt(0, 0, &too_big), MAX_VIDEO_PACKET_BYTES, MAX_VIDEO_PACKET_BYTES + 1); +} + +#[test] +fn encrypted_stream_round_trips_with_loss() { + let mut rng = SeqRng::new(17); + let mut tx = sender(1024, 20, 1, true, 100); + let mut clear = sender(1024, 20, 1, false, 100); + let mut counter = 0u64; + let mut sent = Vec::new(); + for i in 0..10u32 { + let len = rng.below(1008 * 12); + let b = bitstream(&mut rng, len); + let mut r2 = rng.clone(); + let s = send_bytes(&mut tx, &mut rng, i, b.clone()); + let c = send_bytes(&mut clear, &mut r2, i, b); + assert_eq!(s.datagrams.len(), c.datagrams.len()); + for (d, p) in s.datagrams.iter().zip(&c.datagrams) { + // IV = 8-byte LE counter, 3 zero bytes, 'V'; then the frame number, LE (PROTOCOL.md 7). + assert_eq!(&d[..8], &counter.to_le_bytes(), "nonce counter"); + assert_eq!(&d[8..12], &[0, 0, 0, b'V']); + assert_eq!(&d[12..16], &i.to_le_bytes(), "frame number"); + assert_eq!( + &VideoCipher::new(KEY).decrypt(d).unwrap(), + p, + "FEC before encryption: the plaintext is the clear packet" + ); + counter += 1; + } + sent.push(s); + } + let mut datagrams = Vec::new(); + for s in &sent { + datagrams.extend(with_loss(&mut rng, s, true, |r, m| r.below(m + 1))); + } + check(&sent, &[], &receive(&mut receiver(1024, true), &datagrams)); +} + +// ================================================================================================ refusals + +#[test] +fn config_refusals() { + for size in [0u16, 1, 16] { + assert_err!(VideoPacketizer::new(config(size, 20, 0, false, 0)), Error::Malformed { .. }, "{size}"); + } + assert!(VideoPacketizer::new(config(17, 20, 0, false, 0)).is_ok()); + assert!(VideoPacketizer::new(config(4080, 20, 0, false, 0)).is_ok()); + assert_err!(VideoPacketizer::new(config(4081, 20, 0, false, 0)), Error::Malformed { .. }); + // Sealed datagrams carry 32 more bytes and must stay within the receiver's cap too. + assert!(VideoPacketizer::new(config(4048, 20, 0, true, 0)).is_ok()); + assert_err!(VideoPacketizer::new(config(4049, 20, 0, true, 0)), Error::Malformed { .. }); +} + +#[test] +fn oversized_frame_is_refused_and_nothing_advances() { + for (packet_size, encrypt) in [(17u16, false), (64, true), (1024, false)] { + let mut rng = SeqRng::new(u64::from(packet_size)); + let mut tx = sender(packet_size, 20, 0, encrypt, 77); + let max = tx.max_bitstream_len(); + let payload = usize::from(packet_size) - 16; + assert_eq!(max, (MAX_DATA_SHARDS_PER_FRAME * payload).min(MAX_FRAME_BYTES) - FRAME_HEADER_LEN); + let first = send(&mut tx, &mut rng, 0, 10); + let (seq, stats) = (tx.next_sequence(), tx.stats()); + let big = vec![1u8; max + 1]; + let frame = EncodedFrame { + frame_index: 1, + frame_type: FrameType::Key, + rtp_timestamp: 0, + processing_latency: 0, + bitstream: &big, + }; + assert_too_large!(tx.packetize(&frame), max, max + 1); + assert_eq!((tx.next_sequence(), tx.stats()), (seq, stats), "a refused frame changes nothing"); + // The next frame follows on directly, and the receiver sees no gap (also no nonce reuse when sealed). + let second = send(&mut tx, &mut rng, 1, max); + let all: Vec> = [&first, &second].iter().flat_map(|s| s.datagrams.clone()).collect(); + check(&[first, second], &[], &receive(&mut receiver(packet_size, encrypt), &all)); + } +} + +// ================================================================================================ generated + +proptest! { + #![proptest_config(ProptestConfig { cases: 32, ..ProptestConfig::default() })] + + /// Any sizes, packet sizes, percentages and minimums; up to m lost per block; identical frames out. + #[test] + fn generated_round_trips( + seed in any::(), + packet_size in 17u16..1500, + pct in any::(), + min in 0u8..8, + frames in 1usize..6, + encrypt in any::(), + ) { + let mut rng = SeqRng::new(seed); + let payload = usize::from(packet_size) - 16; + let mut tx = sender(packet_size, pct, min, encrypt, rng.next_u64() as u16); + let max = tx.max_bitstream_len(); + let first = rng.next_u64() as u32; + let sent: Vec = (0..frames) + .map(|i| { let len = rng.below(payload * 30).min(max); send(&mut tx, &mut rng, first.wrapping_add(i as u32), len) }) + .collect(); + let mut datagrams = Vec::new(); + for s in &sent { + datagrams.extend(with_loss(&mut rng, s, encrypt, |r, m| r.below(m + 1))); + } + check(&sent, &[], &receive(&mut receiver(packet_size, encrypt), &datagrams)); + } +}