diff --git a/crates/domistream/src/audio/mod.rs b/crates/domistream/src/audio/mod.rs index 49bcbe5..6066d82 100644 --- a/crates/domistream/src/audio/mod.rs +++ b/crates/domistream/src/audio/mod.rs @@ -11,15 +11,17 @@ use core::fmt; use std::collections::{HashMap, VecDeque}; use cbc::cipher::block_padding::Pkcs7; -use cbc::cipher::{BlockModeDecrypt, KeyIvInit}; +use cbc::cipher::{BlockModeDecrypt, BlockModeEncrypt, KeyIvInit}; use crate::fec::ReedSolomon; use crate::util::malformed; use crate::{Error, Instant, Result, SessionKeys}; pub mod packet; +pub mod packetizer; pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet}; +pub use packetizer::{AudioPacketizer, AudioPacketizerConfig, AudioParity}; /// Data packets per FEC block. pub const DATA_SHARDS: usize = 4; @@ -78,6 +80,30 @@ impl AudioCipher { } } +impl AudioCipher { + /// Encrypts one payload (host side), the exact mirror of [`Self::decrypt`]: AES-128-CBC with the IV of + /// [`Self::iv`] and PKCS#7 padding, so the ciphertext is the plaintext length rounded up to the next multiple of + /// 16, always 1 to 16 bytes longer (`docs/PROTOCOL.md` 6.3). + /// + /// # Errors + /// [`Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`] (checked before anything is allocated), + /// [`Error::Crypto`] if the cipher refuses (never for a buffer sized as here). + pub fn encrypt(&self, sequence: u16, plaintext: &[u8]) -> Result> { + crate::util::cap("audio plaintext", packet::MAX_AUDIO_PACKET_BYTES, plaintext.len())?; + let iv = self.iv(sequence)?; + let mut buf = vec![0u8; (plaintext.len() / 16 + 1) * 16]; + for (dst, src) in buf.iter_mut().zip(plaintext) { + *dst = *src; + } + let len = cbc::Encryptor::::new((&*self.key).into(), &iv.into()) + .encrypt_padded::(&mut buf, plaintext.len()) + .map_err(|_| Error::Crypto)? + .len(); + buf.truncate(len); + Ok(buf) + } +} + impl fmt::Debug for AudioCipher { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("AudioCipher()") diff --git a/crates/domistream/src/audio/packetizer.rs b/crates/domistream/src/audio/packetizer.rs new file mode 100644 index 0000000..2599fe8 --- /dev/null +++ b/crates/domistream/src/audio/packetizer.rs @@ -0,0 +1,124 @@ +//! The audio send path, host side (`docs/PROTOCOL.md` 6.2, 6.3): one Opus packet → one RTP datagram, the mirror of +//! [`super::AudioDepacketizer`] and tested against it. +//! +//! Each datagram is the 12-byte RTP header (byte 0 `0x80`, payload type 97, sequence BE, timestamp BE in +//! milliseconds, SSRC 0) followed by the Opus packet, AES-128-CBC encrypted with [`AudioCipher::encrypt`] when a +//! cipher is set (6.3: IV from `rikeyid + sequence`, PKCS#7). Sequence numbers count up by one per packet and the +//! timestamp by the packet duration, both wrapping. +//! +//! **No parity packets** (6.4): the audio parity matrix is UNKNOWN U16, and the only value seen has GPL provenance, +//! so [`AudioParity`] has a single variant, [`AudioParity::None`], and clients conceal lost packets. The enum is +//! `#[non_exhaustive]` and [`AudioPacketizer::packetize`] returns a list of datagrams, so a measured matrix can be +//! added later as a new variant that appends the 2 parity datagrams after every block's 4th data packet without +//! changing callers. Blocks start at sequence numbers that are multiples of 4 (6.4), so `first_sequence` must be one +//! already (the client's receiver also counts from the first packet's block start). + +use super::AudioCipher; +use super::packet::{AUDIO_PAYLOAD_TYPE, MAX_AUDIO_PACKET_BYTES}; +use crate::Result; +use crate::rtp::RTP_HEADER_LEN; +use crate::util::{cap, malformed, need}; + +/// Byte 0 of every audio RTP header: version 2, no padding, extension or CSRC (`docs/PROTOCOL.md` 6.2). +pub const AUDIO_RTP_BYTE0: u8 = 0x80; +/// Largest Opus packet sent in the clear: the receiver's datagram cap minus the RTP header. +pub const MAX_OPUS_PLAIN_BYTES: usize = MAX_AUDIO_PACKET_BYTES - RTP_HEADER_LEN; +/// Largest Opus packet sent encrypted: PKCS#7 always adds 1 to 16 bytes, and the ciphertext must fit the cap. +pub const MAX_OPUS_ENCRYPTED_BYTES: usize = MAX_OPUS_PLAIN_BYTES / 16 * 16 - 1; + +/// Which audio parity packets are sent (`docs/PROTOCOL.md` 6.4). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum AudioParity { + /// None: the parity matrix is UNKNOWN U16 (GPL-provenance, unsettled), so clients conceal lost packets. + #[default] + None, +} + +/// Settings of the audio sender. +#[derive(Clone, Debug)] +pub struct AudioPacketizerConfig { + /// Encrypt payloads with this cipher (audio encryption negotiated, or always: UNKNOWN U17). + pub cipher: Option, + /// Packet duration in milliseconds (`x-nv-aqos.packetDuration`): the timestamp step. + pub packet_duration_ms: u8, + /// Parity packets. + pub parity: AudioParity, + /// RTP sequence number of the first packet: a multiple of 4, the start of an FEC block (6.4). + pub first_sequence: u16, + /// RTP timestamp (milliseconds) of the first packet. + pub first_timestamp_ms: u32, +} + +/// The audio sender of one stream. +#[derive(Debug)] +pub struct AudioPacketizer { + config: AudioPacketizerConfig, + next_sequence: u16, + next_timestamp_ms: u32, +} + +impl AudioPacketizer { + /// A sender for one stream. + /// + /// # Errors + /// [`crate::Error::Malformed`] for a zero packet duration or a `first_sequence` that is not a multiple of 4: FEC + /// blocks start at multiples of 4 (6.4), and the client's receiver counts from the start of the first packet's + /// block, so a stream starting mid-block would show it 1 to 3 phantom losses. + pub fn new(config: AudioPacketizerConfig) -> Result { + if config.packet_duration_ms == 0 { + return Err(malformed("audio packet duration")); + } + if !config.first_sequence.is_multiple_of(4) { + return Err(malformed("audio first sequence is not a block start (a multiple of 4)")); + } + Ok(Self { next_sequence: config.first_sequence, next_timestamp_ms: config.first_timestamp_ms, config }) + } + + /// The largest Opus packet accepted: [`MAX_OPUS_ENCRYPTED_BYTES`] with a cipher, else [`MAX_OPUS_PLAIN_BYTES`]. + #[must_use] + pub const fn max_opus_len(&self) -> usize { + if self.config.cipher.is_some() { MAX_OPUS_ENCRYPTED_BYTES } else { MAX_OPUS_PLAIN_BYTES } + } + + /// Packetizes one Opus packet into the datagrams to send now, in order: today exactly one (no parity, see + /// [`AudioParity`]). On error nothing changes (sequence number, timestamp). + /// + /// # Errors + /// [`crate::Error::Truncated`] for an empty packet (Opus packets carry at least their TOC byte, RFC 6716), + /// [`crate::Error::TooLarge`] over [`Self::max_opus_len`] (checked before anything is allocated), + /// [`crate::Error::Crypto`] if the cipher refuses. + pub fn packetize(&mut self, opus: &[u8]) -> Result>> { + const W: &str = "opus packet"; + need(W, 1, opus.len())?; + cap(W, self.max_opus_len(), opus.len())?; + let (sequence, timestamp) = (self.next_sequence, self.next_timestamp_ms); + let mut packet = Vec::with_capacity(RTP_HEADER_LEN + opus.len() + 16); + packet.extend_from_slice(&[AUDIO_RTP_BYTE0, AUDIO_PAYLOAD_TYPE]); + packet.extend_from_slice(&sequence.to_be_bytes()); + packet.extend_from_slice(×tamp.to_be_bytes()); + packet.extend_from_slice(&0u32.to_be_bytes()); // SSRC 0 + match &self.config.cipher { + Some(c) => packet.extend_from_slice(&c.encrypt(sequence, opus)?), + None => packet.extend_from_slice(opus), + } + let datagrams = match self.config.parity { + AudioParity::None => vec![packet], + }; + self.next_sequence = sequence.wrapping_add(1); + self.next_timestamp_ms = timestamp.wrapping_add(u32::from(self.config.packet_duration_ms)); + Ok(datagrams) + } + + /// The RTP sequence number of the next packet. + #[must_use] + pub const fn next_sequence(&self) -> u16 { + self.next_sequence + } + + /// The RTP timestamp (milliseconds) of the next packet. + #[must_use] + pub const fn next_timestamp_ms(&self) -> u32 { + self.next_timestamp_ms + } +} diff --git a/crates/domistream/src/lib.rs b/crates/domistream/src/lib.rs index d333eaa..b3abff6 100644 --- a/crates/domistream/src/lib.rs +++ b/crates/domistream/src/lib.rs @@ -26,8 +26,8 @@ //! | [`input`] | input and gamepad packets (section 4) | //! | [`rtp`] | the RTP header shared by video and audio | //! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) | -//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) | -//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) | +//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5); the host's packetizer | +//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6); the host's packetizer | //! //! Opus and video decoding are not here: they belong to the platform layer (ArenaTV). diff --git a/crates/domistream/src/video/mod.rs b/crates/domistream/src/video/mod.rs index b0f6772..78d1824 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,38 @@ impl VideoCipher { } } +impl VideoCipher { + /// Seals one plaintext packet (host side), the exact mirror of [`Self::decrypt`]: IV = `counter` as 8 bytes LE, + /// 3 zero bytes, `'V'`; output `IV ‖ frame number u32 LE ‖ tag ‖ ciphertext` (`docs/PROTOCOL.md` 7, UNKNOWN + /// U19 against Sunshine). The caller must never reuse a `counter` under one key: the packetizer counts from 0 + /// per session, and the `'V'` byte keeps video nonces apart from control's (`'C'`). + /// + /// # Errors + /// [`Error::TooLarge`] when the sealed packet would exceed [`packet::MAX_VIDEO_PACKET_BYTES`], [`Error::Crypto`] + /// if the cipher refuses (never for packets within the cap). + pub fn encrypt(&self, counter: u64, frame_number: u32, packet: &[u8]) -> Result> { + let sealed = packet.len().saturating_add(ENCRYPTION_PREFIX_LEN); + cap("sealed video packet", packet::MAX_VIDEO_PACKET_BYTES, sealed)?; + let mut iv = [0u8; 12]; + for (dst, src) in iv.iter_mut().zip(counter.to_le_bytes()) { + *dst = src; + } + if let Some(last) = iv.last_mut() { + *last = b'V'; + } + let mut body = packet.to_vec(); + let tag = Aes128Gcm::new((&*self.key).into()) + .encrypt_inout_detached(&iv.into(), b"", body.as_mut_slice().into()) + .map_err(|_| Error::Crypto)?; + let mut out = Vec::with_capacity(sealed); + out.extend_from_slice(&iv); + out.extend_from_slice(&frame_number.to_le_bytes()); + out.extend_from_slice(tag.as_slice()); + out.extend_from_slice(&body); + Ok(out) + } +} + 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..a5a783f --- /dev/null +++ b/crates/domistream/src/video/packetizer.rs @@ -0,0 +1,391 @@ +//! 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. +//! +//! The mirror of [`super::VideoDepacketizer`], and tested against it: +//! +//! 1. Frame data = the 8-byte frame header ([`write_frame_header`], the structured reading of 5.2; UNKNOWN U13 is +//! open, so the writer is one small function) followed by the Annex-B bitstream, cut into `packetSize - 16`-byte +//! data shards, the last one zero-padded (5.2). +//! 2. The data shards are split into at most 4 FEC blocks ([`plan_fec_blocks`]); each block gets +//! `m = ceil(k × percentage / 100)` parity shards, with the percentage raised for the client's minimum parity +//! count and lowered only when a block would exceed 255 shards (5.3). +//! 3. Each data shard becomes a whole packet (RTP header, 4 reserved bytes, NV header, payload). Parity is computed +//! over these whole packets with [`crate::fec::ReedSolomon`] (the Cauchy matrix of 5.3), and only then are the +//! parity packets' RTP and NV header fields written over their first 32 bytes, exactly as 5.3 says. +//! 4. Sequence numbers run on across frames (one per datagram, data and parity alike, wrapping at 16 bits); the +//! stream packet index is the sequence number shifted left by 8 (5.2). +//! 5. With video encryption, every finished packet is sealed with [`VideoCipher::encrypt`] (FEC before +//! encryption, 7), with a per-session nonce counter that starts at 0. +//! +//! The input is trusted (our own encoder), but nothing here panics: sizes are capped with typed errors before +//! anything is allocated, and a refused frame changes no state. +//! +//! Choices of our own, not from a source (to be compared with a real host's capture): the block split (fewest +//! blocks that carry the requested parity; every block but the last has the same `k`), the percentage arithmetic +//! for the minimum parity count, and what happens to a frame too big for its parity (the parity is lowered, counted +//! in [`VideoPacketizerStats::fec_reduced_blocks`]). + +use super::VideoCipher; +use super::packet::{ + FRAME_HEADER_LEN, FrameType, MAX_FEC_BLOCKS, MAX_VIDEO_PACKET_BYTES, NV_HEADER_LEN, PAYLOAD_OFFSET, VIDEO_RTP_LEN, + VideoFlags, +}; +use super::{ENCRYPTION_PREFIX_LEN, MAX_FRAME_BYTES}; +use crate::fec::{MAX_SHARDS, ReedSolomon}; +use crate::util::{cap, malformed}; +use crate::{Error, Result}; + +/// The NV header's multi-FEC flags byte (`docs/PROTOCOL.md` 5.2, UNKNOWN U15: sent as documented, 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; +/// Byte 0 of every video RTP header: version 2, extension bit set (`docs/PROTOCOL.md` 5.2). +pub const VIDEO_RTP_BYTE0: u8 = 0x90; +/// Most data shards one frame can carry: [`MAX_FEC_BLOCKS`] blocks of at most [`MAX_SHARDS`] shards. +pub const MAX_DATA_SHARDS_PER_FRAME: usize = MAX_FEC_BLOCKS * 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`: NV header + payload. Each datagram is `packetSize + 16` bytes (+ 32 when sealed). + pub packet_size: u16, + /// Requested FEC percentage. + 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, probably 90 kHz). + 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 (the receiver derives `m` from it). + pub fec_percentage: u8, + /// The requested parity (percentage and minimum count) did not fit in 255 shards 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 parity was lowered to fit 255 shards. + pub fec_reduced_blocks: u64, +} + +/// The frame type byte of the structured frame header (`docs/PROTOCOL.md` 5.2). +const fn frame_type_byte(t: FrameType) -> u8 { + match t { + FrameType::Predicted => 1, + FrameType::Key => 2, + FrameType::Recovery => 5, + FrameType::Other(v) => v, + } +} + +/// Writes the 8-byte frame header in its structured form (`docs/PROTOCOL.md` 5.2): type `0x01`, processing latency +/// u16 LE, frame type, payload bytes in the last data shard u32 LE. UNKNOWN U13 (Wolf shows a constant instead) is +/// open; this is the form our client reads, and the only place to change if the capture says otherwise. +#[must_use] +pub fn write_frame_header( + frame_type: FrameType, + processing_latency: u16, + last_payload_len: u32, +) -> [u8; FRAME_HEADER_LEN] { + let [l0, l1] = processing_latency.to_le_bytes(); + let [a, b, c, d] = last_payload_len.to_le_bytes(); + [FRAME_HEADER_TYPE, l0, l1, frame_type_byte(frame_type), a, b, c, d] +} + +/// Parity of a block of `k` at percentage `p`: `ceil(k × p / 100)` (the receiver's formula, 5.3). +const fn parity_at(k: usize, p: usize) -> usize { + (k * p).div_ceil(100) +} + +/// The parity the client asks for a block of `k`: the percentage's, but at least the minimum count. +fn target(k: usize, pct: u8, min: u8) -> usize { + let m = parity_at(k, usize::from(pct)); + if m < usize::from(min) { usize::from(min) } else { m } +} + +/// The least percentage, at or above `pct`, whose parity reaches the target, if it is an 8-bit value and keeps the +/// block within [`MAX_SHARDS`]. +fn wished_percentage(k: usize, pct: u8, min: u8) -> Option { + if k == 0 { + return None; + } + let t = target(k, pct, min); + let p = if parity_at(k, usize::from(pct)) >= t { + usize::from(pct) + } else { + // The least p with k·p > 100·(t − 1), i.e. ceil(k·p / 100) ≥ t. + 100 * (t - 1) / k + 1 + }; + (p <= usize::from(u8::MAX) && k + parity_at(k, p) <= MAX_SHARDS).then_some(p) +} + +/// The FEC geometry of one block of `k` data shards. +fn block(k: usize, pct: u8, min: u8) -> Result { + let (p, reduced) = match wished_percentage(k, pct, min) { + Some(p) => (p, false), + // The most parity that fits: the largest p with k + ceil(k·p / 100) ≤ 255. + None => ((100 * MAX_SHARDS.saturating_sub(k) / k.max(1)).min(usize::from(u8::MAX)), true), + }; + let to_u16 = |v: usize| u16::try_from(v).map_err(|_| malformed("video fec block")); + Ok(FecBlock { + data_shards: to_u16(k)?, + parity_shards: to_u16(parity_at(k, p))?, + fec_percentage: u8::try_from(p).map_err(|_| malformed("video fec percentage"))?, + reduced, + }) +} + +/// Splits a frame's `data_shards` into FEC blocks (`docs/PROTOCOL.md` 5.3): the fewest blocks (at most +/// [`MAX_FEC_BLOCKS`]) whose blocks can each carry the requested parity, where every block but the last carries +/// `ceil(data_shards / blocks)` data shards. Each block's percentage is the least one, at or above `fec_percentage`, +/// that gives `max(ceil(k × fec_percentage / 100), min_parity)` parity shards; when that cannot fit in +/// [`MAX_SHARDS`] shards (or an 8-bit percentage), the block gets the most parity that fits and is marked `reduced`. +/// +/// # Errors +/// [`Error::Malformed`] for 0 data shards, [`Error::TooLarge`] over [`MAX_DATA_SHARDS_PER_FRAME`]. +pub fn plan_fec_blocks(data_shards: usize, fec_percentage: u8, min_parity: u8) -> Result> { + if data_shards == 0 { + return Err(malformed("video frame without data shards")); + } + cap("video frame data shards", MAX_DATA_SHARDS_PER_FRAME, data_shards)?; + let blocks = (1..=MAX_FEC_BLOCKS) + .find(|&b| wished_percentage(data_shards.div_ceil(b), fec_percentage, min_parity).is_some()) + .unwrap_or(MAX_FEC_BLOCKS); + let k_full = data_shards.div_ceil(blocks); + let count = data_shards.div_ceil(k_full); + let mut plan = Vec::with_capacity(count); + let mut left = data_shards; + while left > 0 { + let k = left.min(k_full); + plan.push(block(k, fec_percentage, min_parity)?); + left -= k; + } + Ok(plan) +} + +/// The 32 header bytes of one packet (`docs/PROTOCOL.md` 5.2). +struct Header { + sequence: u16, + timestamp: u32, + frame_index: u32, + flags: u8, + block: u8, + last_block: u8, + shard_index: u16, + data_shards: u16, + fec_percentage: u8, +} + +impl Header { + fn bytes(&self) -> [u8; PAYLOAD_OFFSET] { + let fec_info = (u32::from(self.fec_percentage) << 4) + | ((u32::from(self.shard_index) & 0x3FF) << 12) + | ((u32::from(self.data_shards) & 0x3FF) << 22); + let parts: [&[u8]; 11] = [ + &[VIDEO_RTP_BYTE0, 0], // RTP byte 0, payload type 0 + &self.sequence.to_be_bytes(), // sequence, BE + &self.timestamp.to_be_bytes(), // timestamp, BE + &[0; 4], // SSRC 0 + &[0; 4], // reserved + &(u32::from(self.sequence) << 8).to_le_bytes(), // stream packet index, LE + &self.frame_index.to_le_bytes(), // frame index, LE + &[self.flags, 0], // flags, reserved + &[MULTI_FEC_FLAGS], // multi-FEC flags (U15) + &[((self.block & 3) << 4) | ((self.last_block & 3) << 6)], // multi-FEC blocks + &fec_info.to_le_bytes(), // FEC info, LE + ]; + let mut out = [0u8; PAYLOAD_OFFSET]; + for (dst, src) in out.iter_mut().zip(parts.iter().flat_map(|p| p.iter())) { + *dst = *src; + } + out + } +} + +/// The video sender of one stream. +#[derive(Debug)] +pub struct VideoPacketizer { + config: VideoPacketizerConfig, + payload_len: usize, + next_sequence: u16, + /// Next GCM nonce counter (sealed streams only). + next_nonce: u64, + stats: VideoPacketizerStats, +} + +impl VideoPacketizer { + /// A sender for one stream. + /// + /// # Errors + /// [`Error::Malformed`] for a `packet_size` not above the NV header size, or one whose datagrams (sealed, when a + /// cipher is set) would not fit [`MAX_VIDEO_PACKET_BYTES`], the receiver's cap. + pub fn new(config: VideoPacketizerConfig) -> Result { + let size = usize::from(config.packet_size); + let sealed = if config.cipher.is_some() { ENCRYPTION_PREFIX_LEN } else { 0 }; + if size <= NV_HEADER_LEN || size + VIDEO_RTP_LEN + sealed > MAX_VIDEO_PACKET_BYTES { + return Err(malformed("video packet_size")); + } + Ok(Self { + payload_len: size - NV_HEADER_LEN, + next_sequence: config.first_sequence, + config, + next_nonce: 0, + stats: VideoPacketizerStats::default(), + }) + } + + /// The largest bitstream one frame can carry: [`MAX_DATA_SHARDS_PER_FRAME`] shards of payload, and the + /// receiver's [`MAX_FRAME_BYTES`], minus the frame header. + #[must_use] + pub const fn max_bitstream_len(&self) -> usize { + let shards = MAX_DATA_SHARDS_PER_FRAME * self.payload_len; + let max = if shards < MAX_FRAME_BYTES { shards } else { MAX_FRAME_BYTES }; + max - FRAME_HEADER_LEN + } + + /// Packetizes one frame into its datagrams, in send order: block 0's data shards then its parity, block 1, … + /// On error nothing changes (sequence numbers, nonce counter, stats). + /// + /// # Errors + /// [`Error::TooLarge`] for a bitstream over [`Self::max_bitstream_len`] (checked before anything is allocated), + /// [`Error::State`] once the nonce counter of a sealed stream is exhausted (a new session key is needed). + pub fn packetize(&mut self, frame: &EncodedFrame<'_>) -> Result>> { + cap("video access unit", self.max_bitstream_len(), frame.bitstream.len())?; + let p = self.payload_len; + let data_len = FRAME_HEADER_LEN + frame.bitstream.len(); + let n = data_len.div_ceil(p); + let plan = plan_fec_blocks(n, self.config.fec_percentage, self.config.min_required_fec_packets)?; + let total: usize = plan.iter().map(|b| usize::from(b.data_shards) + usize::from(b.parity_shards)).sum(); + let sealed = self.config.cipher.is_some(); + if sealed && self.next_nonce.checked_add(total as u64).is_none() { + return Err(Error::State { expected: "a fresh session key (video nonce counter exhausted)" }); + } + + // Frame data: header + bitstream, zero-padded to n whole shards (5.2). + let last_payload = data_len - (n - 1) * p; + let header = + write_frame_header(frame.frame_type, frame.processing_latency, u32::try_from(last_payload).unwrap_or(0)); + let mut data = Vec::with_capacity(n * p); + data.extend_from_slice(&header); + data.extend_from_slice(frame.bitstream); + data.resize(n * p, 0); + + let last_block = u8::try_from(plan.len() - 1).map_err(|_| malformed("video fec blocks"))?; + let mut sequence = self.next_sequence; + let mut next_header = |flags: u8, block: u8, shard_index: u16, b: &FecBlock| { + let h = Header { + sequence, + timestamp: frame.rtp_timestamp, + frame_index: frame.frame_index, + flags, + block, + last_block, + shard_index, + data_shards: b.data_shards, + fec_percentage: b.fec_percentage, + }; + sequence = sequence.wrapping_add(1); + h.bytes() + }; + + let packet_len = PAYLOAD_OFFSET + p; + let mut out: Vec> = Vec::with_capacity(total); + let mut chunks = data.chunks(p); + let mut shard_no = 0usize; + let mut reduced = 0u64; + let mut parity_packets = 0u64; + for (bi, b) in plan.iter().enumerate() { + let block = u8::try_from(bi).map_err(|_| malformed("video fec blocks"))?; + let (k, m) = (usize::from(b.data_shards), usize::from(b.parity_shards)); + reduced += u64::from(b.reduced); + let mut shards: Vec> = Vec::with_capacity(k + m); + for i in 0..k { + let mut flags = VideoFlags::PICTURE_DATA; + if shard_no == 0 { + flags |= VideoFlags::START_OF_FRAME; + } + if shard_no + 1 == n { + flags |= VideoFlags::END_OF_FRAME; + } + shard_no += 1; + let mut packet = Vec::with_capacity(packet_len); + packet.extend_from_slice(&next_header(flags, block, u16::try_from(i).unwrap_or(u16::MAX), b)); + packet.extend_from_slice(chunks.next().ok_or(malformed("video frame shards"))?); + shards.push(packet); + } + if m > 0 { + // Parity over the whole data packets, headers included (5.3) ... + shards.resize_with(k + m, || vec![0u8; packet_len]); + ReedSolomon::new(k, m)?.encode(&mut shards)?; + // ... and only then the parity packets' own header fields, over their first 32 bytes. + for (j, parity) in shards.iter_mut().skip(k).enumerate() { + let h = next_header(0, block, u16::try_from(k + j).unwrap_or(u16::MAX), b); + if let Some(head) = parity.get_mut(..PAYLOAD_OFFSET) { + head.copy_from_slice(&h); + } + } + parity_packets += m as u64; + } + out.append(&mut shards); + } + + if let Some(cipher) = &self.config.cipher { + let mut nonce = self.next_nonce; + for packet in &mut out { + *packet = cipher.encrypt(nonce, frame.frame_index, packet)?; + nonce += 1; + } + self.next_nonce = nonce; + } + self.next_sequence = sequence; + self.stats.frames += 1; + self.stats.packets += out.len() as u64; + self.stats.parity_packets += parity_packets; + self.stats.fec_reduced_blocks += reduced; + Ok(out) + } + + /// The RTP sequence number of the next datagram. + #[must_use] + pub const fn next_sequence(&self) -> u16 { + self.next_sequence + } + + /// Counters. + #[must_use] + pub const fn stats(&self) -> VideoPacketizerStats { + self.stats + } +} diff --git a/crates/domistream/tests/audio_packetizer.rs b/crates/domistream/tests/audio_packetizer.rs new file mode 100644 index 0000000..252ebcd --- /dev/null +++ b/crates/domistream/tests/audio_packetizer.rs @@ -0,0 +1,261 @@ +//! The audio packetizer, host side (`docs/PROTOCOL.md` 6.2, 6.3), checked against the client half: Opus packets +//! go through the crate's own `AudioDepacketizer` with the session keys and must come out identical, in order, +//! with the millisecond timestamps of 6.2, across sequence and timestamp wrap-around. A fixed vector checks one +//! datagram byte by byte; the cipher is checked against the openssl vectors. No parity packets are sent (U16). + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)] + +mod common; + +use core::time::Duration; + +use common::SeqRng; +use domistream::audio::packet::{MAX_AUDIO_PACKET_BYTES, parse_audio_packet}; +use domistream::audio::packetizer::{MAX_OPUS_ENCRYPTED_BYTES, MAX_OPUS_PLAIN_BYTES}; +use domistream::audio::{ + AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioPacket, AudioPacketizer, + AudioPacketizerConfig, AudioParity, +}; +use domistream::{Error, Instant, SessionKeys}; +use proptest::prelude::*; + +const KEY: [u8; 16] = *b"audio-pack-key!!"; +const RIKEYID: u32 = 0xFFFF_FFF0; // rikeyid + sequence wraps inside the tests + +fn keys() -> SessionKeys { + SessionKeys { rikey: KEY, rikeyid: RIKEYID } +} + +fn cfg(encrypt: bool, first_sequence: u16, first_timestamp_ms: u32, duration: u8) -> AudioPacketizerConfig { + AudioPacketizerConfig { + cipher: encrypt.then(|| AudioCipher::new(&keys())), + packet_duration_ms: duration, + parity: AudioParity::None, + first_sequence, + first_timestamp_ms, + } +} + +fn sender(encrypt: bool, first_sequence: u16, first_timestamp_ms: u32, duration: u8) -> AudioPacketizer { + AudioPacketizer::new(cfg(encrypt, first_sequence, first_timestamp_ms, duration)).expect("AudioPacketizer::new") +} + +fn receiver(encrypt: bool, duration: u8) -> AudioDepacketizer { + AudioDepacketizer::new(AudioConfig { + cipher: encrypt.then(|| AudioCipher::new(&keys())), + packet_duration_ms: duration, + fec: AudioFec::Disabled, + loss_timeout: Duration::from_millis(40), + }) + .expect("AudioDepacketizer::new") +} + +fn receive(rx: &mut AudioDepacketizer, datagrams: &[Vec]) -> Vec { + let mut now = 1_000_000u64; + let mut events = Vec::new(); + for d in datagrams { + rx.push(Instant::from_micros(now), d).expect("push never fails within the size cap"); + now += 5_000; + while let Some(e) = rx.poll_event() { + events.push(e); + } + } + for _ in 0..64 { + now += 1_000_000; + rx.handle_timeout(Instant::from_micros(now)).unwrap(); + while let Some(e) = rx.poll_event() { + events.push(e); + } + if rx.poll_timeout().is_none() { + break; + } + } + events +} + +/// One Opus-sized payload: 1 to 1275 bytes (one Opus frame's maximum, RFC 6716), occasionally up to `max`. +fn opus(rng: &mut SeqRng, max: usize) -> Vec { + let len = if rng.below(20) == 0 { 1 + rng.below(max) } else { 1 + rng.below(1275) }; + rng.bytes(len) +} + +/// Packetizes `payloads` and returns (datagrams, the events a lossless receiver must report). +fn send(tx: &mut AudioPacketizer, payloads: &[Vec], duration: u8) -> (Vec>, Vec) { + let mut datagrams = Vec::new(); + let mut want = Vec::new(); + for o in payloads { + let (seq, ts) = (tx.next_sequence(), tx.next_timestamp_ms()); + let out = tx.packetize(o).expect("packetize"); + assert_eq!(out.len(), 1, "AudioParity::None: one datagram per Opus packet, no parity"); + assert_eq!(tx.next_sequence(), seq.wrapping_add(1)); + assert_eq!(tx.next_timestamp_ms(), ts.wrapping_add(u32::from(duration))); + datagrams.extend(out); + want.push(AudioEvent::Packet { sequence: seq, timestamp_ms: ts, opus: o.clone(), recovered: false }); + } + (datagrams, want) +} + +// ================================================================================================ fixed vectors + +#[test] +fn fixed_vector_plaintext() { + let mut tx = sender(false, 0x0104, 0x0A0B_0C0D, 5); + let out = tx.packetize(&[0xFC, 0xFF, 0xFE]).unwrap(); + #[rustfmt::skip] + let want = vec![ + 0x80, // RTP byte 0: version 2, no extension (6.2) + 0x61, // payload type 97 + 0x01, 0x04, // sequence 0x0104, BE + 0x0A, 0x0B, 0x0C, 0x0D, // timestamp (milliseconds), BE + 0x00, 0x00, 0x00, 0x00, // SSRC 0 + 0xFC, 0xFF, 0xFE, // the Opus packet + ]; + assert_eq!(out, vec![want]); + assert_eq!((tx.next_sequence(), tx.next_timestamp_ms()), (0x0105, 0x0A0B_0C12)); +} + +#[test] +fn fixed_vector_encrypted() { + // Header as above; the payload is AES-128-CBC + PKCS#7 with IV = BE(rikeyid + sequence) || 12 zero bytes (6.3), + // here computed by the RustCrypto test oracle (itself checked against openssl in media.rs). + let mut tx = sender(true, 0x0020, 7, 10); + let opus = [0x11u8; 20]; + let out = tx.packetize(&opus).unwrap(); + let mut want = vec![0x80, 0x61, 0x00, 0x20, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00]; + want.extend(common::audio_encrypt(&KEY, RIKEYID, 0x0020, &opus)); + assert_eq!(out, vec![want]); + assert_eq!(out[0].len(), 12 + 32, "20 bytes pad to 32"); +} + +#[test] +fn audio_cipher_encrypt_matches_openssl_vectors() { + let v = common::audio_vectors(); + for name in ["a_0", "a_1", "a_ffff", "a_wrap", "a_exact_block", "a_one_byte"] { + let rikeyid = v.u32_hex(&format!("{name}_rikeyid")); + let seq = u16::from_str_radix(v.str(&format!("{name}_sequence")), 16).unwrap(); + let c = AudioCipher::new(&SessionKeys { rikey: v.arr16("key"), rikeyid }); + assert_eq!( + c.encrypt(seq, &v.bytes(&format!("{name}_plain"))).unwrap(), + v.bytes(&format!("{name}_cipher")), + "{name}" + ); + } +} + +// ================================================================================================ round trips + +#[test] +fn round_trip_encrypted_across_sequence_and_timestamp_wrap() { + let mut rng = SeqRng::new(1); + // Sequence 0xFF00 wraps after 256 packets; the timestamp wraps too; rikeyid + sequence wraps in the IV. + let mut tx = sender(true, 0xFF00, u32::MAX - 1000, 20); + let payloads: Vec> = (0..600).map(|_| opus(&mut rng, MAX_OPUS_ENCRYPTED_BYTES)).collect(); + let (datagrams, want) = send(&mut tx, &payloads, 20); + assert_eq!(receive(&mut receiver(true, 20), &datagrams), want); +} + +#[test] +fn round_trip_plaintext() { + let mut rng = SeqRng::new(2); + let mut tx = sender(false, 0, 0, 5); + let payloads: Vec> = (0..300).map(|_| opus(&mut rng, MAX_OPUS_PLAIN_BYTES)).collect(); + let (datagrams, want) = send(&mut tx, &payloads, 5); + for d in &datagrams { + assert!(matches!(parse_audio_packet(d), Ok(AudioPacket::Data { .. }))); + } + assert_eq!(receive(&mut receiver(false, 5), &datagrams), want); +} + +#[test] +fn sequence_wraps_from_ffff_to_0() { + let mut tx = sender(true, 0xFFFC, 100, 10); + let mut seen = Vec::new(); + for _ in 0..6 { + let d = tx.packetize(&[1, 2, 3]).unwrap().remove(0); + let Ok(AudioPacket::Data { rtp, .. }) = parse_audio_packet(&d) else { panic!("data packet") }; + seen.push((rtp.sequence, rtp.timestamp)); + } + assert_eq!(seen, vec![(0xFFFC, 100), (0xFFFD, 110), (0xFFFE, 120), (0xFFFF, 130), (0x0000, 140), (0x0001, 150)]); +} + +#[test] +fn lost_packets_are_reported_and_the_rest_arrive() { + let mut rng = SeqRng::new(3); + let mut tx = sender(true, 0x1000, 0, 5); + let payloads: Vec> = (0..200).map(|_| opus(&mut rng, 400)).collect(); + let (datagrams, want) = send(&mut tx, &payloads, 5); + let mut kept = Vec::new(); + let mut expect = Vec::new(); + for (i, (d, w)) in datagrams.into_iter().zip(want).enumerate() { + if i > 0 && i < 199 && rng.below(10) == 0 { + let AudioEvent::Packet { sequence, .. } = w else { unreachable!() }; + expect.push(AudioEvent::Lost { sequence }); + } else { + kept.push(d); + expect.push(w); + } + } + assert_eq!(receive(&mut receiver(true, 5), &kept), expect); +} + +// ================================================================================================ refusals + +#[test] +fn size_caps() { + assert_eq!(MAX_OPUS_PLAIN_BYTES, MAX_AUDIO_PACKET_BYTES - 12); + assert_eq!(MAX_OPUS_ENCRYPTED_BYTES, 2031, "2031 bytes pad to 2032; 12 + 2032 = 2044 <= 2048"); + for (encrypt, max) in [(false, MAX_OPUS_PLAIN_BYTES), (true, MAX_OPUS_ENCRYPTED_BYTES)] { + let mut tx = sender(encrypt, 4, 50, 5); + assert_eq!(tx.max_opus_len(), max); + let state = (tx.next_sequence(), tx.next_timestamp_ms()); + assert_err!(tx.packetize(&[]), Error::Truncated { .. }, "an Opus packet has at least its TOC byte"); + assert_too_large!(tx.packetize(&vec![7; max + 1]), max, max + 1); + assert_too_large!(tx.packetize(&vec![7; 100_000]), max, 100_000); + assert_eq!((tx.next_sequence(), tx.next_timestamp_ms()), state, "a refused packet changes nothing"); + // The largest packet fits the receiver's datagram cap and comes back. + let (datagrams, want) = send(&mut tx, &[vec![9; max], vec![8; 1]], 5); + assert!(datagrams[0].len() <= MAX_AUDIO_PACKET_BYTES); + assert_eq!(receive(&mut receiver(encrypt, 5), &datagrams), want); + } + let c = AudioCipher::new(&keys()); + assert_too_large!( + c.encrypt(0, &vec![0; MAX_AUDIO_PACKET_BYTES + 1]), + MAX_AUDIO_PACKET_BYTES, + MAX_AUDIO_PACKET_BYTES + 1 + ); +} + +#[test] +fn config_refusals() { + assert_err!(AudioPacketizer::new(cfg(true, 0, 0, 0)), Error::Malformed { .. }, "zero packet duration"); + // Blocks start at multiples of 4 (6.4), and the receiver counts from the first block's start: a stream that + // began at 5 would make it report 4 as lost. + for first in [1u16, 2, 3, 5, 0xFFFF] { + assert_err!(AudioPacketizer::new(cfg(true, first, 0, 5)), Error::Malformed { .. }, "first sequence {first}"); + } + assert!(AudioPacketizer::new(cfg(true, 0xFFFC, 0, 5)).is_ok()); + assert_eq!(AudioParity::default(), AudioParity::None); +} + +// ================================================================================================ generated + +proptest! { + #![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })] + + #[test] + fn generated_round_trips( + seed in any::(), + first_sequence in any::(), + first_ts in any::(), + duration in 1u8..=40, + count in 1usize..80, + encrypt in any::(), + ) { + let mut rng = SeqRng::new(seed); + let mut tx = sender(encrypt, first_sequence & !3, first_ts, duration); + let max = tx.max_opus_len(); + let payloads: Vec> = (0..count).map(|_| opus(&mut rng, max)).collect(); + let (datagrams, want) = send(&mut tx, &payloads, duration); + prop_assert_eq!(receive(&mut receiver(encrypt, duration), &datagrams), want); + } +} diff --git a/crates/domistream/tests/video_packetizer.rs b/crates/domistream/tests/video_packetizer.rs new file mode 100644 index 0000000..2ef0608 --- /dev/null +++ b/crates/domistream/tests/video_packetizer.rs @@ -0,0 +1,825 @@ +//! 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: 101 % is the smallest percentage giving + // m = ceil(1 * 101 / 100) = 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, 101)); + // 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); + if datagrams.is_empty() { + // The receiver starts at the frame of the first datagram it sees: let that be frame 0's. + let first = window.iter().position(|d| pair[0].datagrams.contains(d)); + window.swap(0, first.expect("a datagram of frame 0")); + } + 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).wrapping_add(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)); + } +} diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 220e9a4..26d1088 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -468,6 +468,12 @@ Reed-Solomon erasure code over GF(2^8), polynomial `0x11D` [F] [W5]: `P = [[8e f4 47 a7], [f4 8e a7 47]]`; `k = 3, m = 1`: `P = [[01 8e f4]]`. The capture settles it without any loss: parity packets are always sent, so our encoder must reproduce the captured parity bytes (offset 32 on) of every block. +- **Host side (Lumen, `video::packetizer`).** Our own choices, not from a source, until a capture compares them + with a real host: the fewest blocks (at most 4) in which every block can carry the requested parity within + `k + m <= 255`, every block but the last carrying `k = ceil(n / blocks)` data shards; per block the least + percentage, at or above the requested one, whose `m` reaches `minRequiredFecPackets`; a frame too big for that + gets the most parity that still fits (counted in the packetizer's stats). Data shards in order, then the block's + parity, block by block; RTP sequence numbers run on across frames, one per packet. - The audio code is **not** this matrix (section 6.4). ### 5.4 Feedback @@ -526,6 +532,10 @@ coefficients (each parity byte is a linear combination of the 4 data bytes at th parity row, so a handful of byte positions gives a unique solution). Until then, audio loss falls back to the platform's packet-loss concealment. +Host side (Lumen, `audio::packetizer`): no parity packets until U16 is settled (`AudioParity::None`; the API leaves +room for a parity variant). The first sequence number is a multiple of 4, a block start, because our receiver counts +from the first packet's block start and would otherwise report the 1 to 3 numbers before it as lost. + ### 6.5 Decoding **Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index e82bf43..8c61c26 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -211,3 +211,10 @@ path = "fuzz_targets/rtsp_client.rs" test = false doc = false bench = false + +[[bin]] +name = "video_packetizer_roundtrip" +path = "fuzz_targets/video_packetizer_roundtrip.rs" +test = false +doc = false +bench = false diff --git a/fuzz/fuzz_targets/video_packetizer_roundtrip.rs b/fuzz/fuzz_targets/video_packetizer_roundtrip.rs new file mode 100644 index 0000000..ac49761 --- /dev/null +++ b/fuzz/fuzz_targets/video_packetizer_roundtrip.rs @@ -0,0 +1,125 @@ +//! Fuzzes the host's video packetizer against the client's depacketizer (`docs/PROTOCOL.md` 5.2, 5.3, 7). +//! Arbitrary frame bytes and parameters (packet size, FEC percentage, minimum parity, encryption, frame type, +//! latency) → packetize two frames → lose up to `m` packets of every block → depacketize: both frames must come back +//! byte-exact, in order, with their headers. Every valid configuration must be accepted and every frame within +//! `max_bitstream_len` packetized. +//! How to run: see the comment at the top of `fuzz/Cargo.toml`. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +use core::time::Duration; +use std::collections::BTreeMap; + +use domistream::Instant; +use domistream::fec::parity_count; +use domistream::video::packet::parse_video_packet; +use domistream::video::packetizer::{EncodedFrame, VideoPacketizer, VideoPacketizerConfig}; +use domistream::video::{FrameType, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent}; + +const KEY: [u8; 16] = *b"fuzz-video-key!!"; + +/// xorshift64*, seeded from the input: which packets are lost. +struct Rng(u64); + +impl Rng { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + (self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 33) as usize % n.max(1) + } +} + +fuzz_target!(|data: &[u8]| { + let Some((head, body)) = data.split_first_chunk::<10>() else { return }; + let [s0, s1, pct, min, flags, loss, split, l0, l1, first] = *head; + // 17..=4048: every packet size the receiver accepts, sealed or not. + let packet_size = 17 + u16::from_le_bytes([s0, s1]) % 4032; + let encrypt = flags & 1 != 0; + let frame_type = match (flags >> 1) & 3 { + 0 => FrameType::Predicted, + 1 => FrameType::Key, + 2 => FrameType::Recovery, + _ => FrameType::Other((flags >> 3) | 0x08), // 8..=31: never a value with its own name (1, 2, 5) + }; + let lossy = flags & 0x80 != 0; + let cipher = || encrypt.then(|| VideoCipher::new(KEY)); + let config = VideoPacketizerConfig { + packet_size, + fec_percentage: pct, + min_required_fec_packets: min, + cipher: cipher(), + first_sequence: u16::from_le_bytes([first, s0]), + }; + let mut tx = VideoPacketizer::new(config).expect("a valid configuration is accepted"); + let mut rx = + VideoDepacketizer::new(VideoConfig { packet_size, cipher: cipher(), frame_timeout: Duration::from_millis(20) }) + .expect("the receiver accepts the same packet size"); + + let cut = body.len() * usize::from(split) / 255; + let (a, b) = body.split_at(cut); + let frames = [a, b]; + let mut rng = Rng(u64::from_le_bytes([s0, s1, pct, min, flags, loss, split, l0]) | 1); + let mut datagrams = Vec::new(); + for (i, bitstream) in frames.iter().enumerate() { + assert!(bitstream.len() <= tx.max_bitstream_len(), "fuzz inputs stay far below the frame cap"); + let frame = EncodedFrame { + frame_index: 0xFFFF_FFFF_u32.wrapping_add(i as u32), + frame_type, + rtp_timestamp: u32::from(l1) << 8, + processing_latency: u16::from_le_bytes([l0, l1]), + bitstream, + }; + let out = tx.packetize(&frame).expect("a frame within the cap is packetized"); + // Group by block (from the plaintext), then lose up to m of each block. + let mut blocks: BTreeMap, usize)> = BTreeMap::new(); + for (j, d) in out.iter().enumerate() { + let plain = if encrypt { VideoCipher::new(KEY).decrypt(d).expect("our own seal opens") } else { d.clone() }; + let p = parse_video_packet(&plain).expect("our own packet parses"); + let m = parity_count(usize::from(p.nv.fec.data_shards), p.nv.fec.fec_percentage).expect("consistent FEC"); + blocks.entry(p.nv.fec.block_index).or_insert_with(|| (Vec::new(), m)).0.push(j); + } + let mut keep = vec![true; out.len()]; + if lossy { + for (positions, m) in blocks.values() { + let mut left = positions.clone(); + for _ in 0..rng.below(m + 1).min(left.len()) { + let pick = left.swap_remove(rng.below(left.len())); + if let Some(k) = keep.get_mut(pick) { + *k = false; + } + } + } + } + // Sent in order; every block keeps at least k packets, so frame 0 starts the receiver. + datagrams.extend(out.into_iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d)); + } + + let mut us = 1_000u64; + let mut got = Vec::new(); + for d in &datagrams { + rx.push(Instant::from_micros(us), d).expect("within the receiver's cap"); + us += 10; + while let Some(e) = rx.poll_event() { + got.push(e); + } + } + for _ in 0..8 { + us += 1_000_000; + let _ = rx.handle_timeout(Instant::from_micros(us)); + while let Some(e) = rx.poll_event() { + got.push(e); + } + } + assert_eq!(got.len(), 2, "two frames out: {got:?}"); + for (i, (e, want)) in got.iter().zip(frames).enumerate() { + let VideoEvent::Frame(f) = e else { panic!("frame {i} lost: {e:?}") }; + assert_eq!(f.frame_index, 0xFFFF_FFFF_u32.wrapping_add(i as u32)); + assert!(f.bitstream == want, "frame {i}: {} bytes out, {} in", f.bitstream.len(), want.len()); + assert_eq!(f.header.frame_type, frame_type); + assert_eq!(f.header.processing_latency, u16::from_le_bytes([l0, l1])); + assert_eq!(f.rtp_timestamp, u32::from(l1) << 8); + } +});