[domistream] Implementation: HTTP, pairing, RTSP/SDP, ENet, control, input, RTP, FEC, video and audio receivers
Per PROTOCOL.md and the Wolf docs; interop with a real host is unverified. Strict, capped parsers throughout, shared helpers in util.rs. Where PROTOCOL.md says UNKNOWN the Wolf-documented behaviour is used. The audio receiver waits for the jitter budget before rebuilding a missing packet, so a late packet beats a rebuilt one.
This commit is contained in:
@@ -1,12 +1,23 @@
|
||||
//! The video receive path (`docs/PROTOCOL.md` section 5): decrypt (if negotiated) → parse → group by frame and
|
||||
//! FEC block → rebuild lost data shards → reassemble the frame → hand the Annex-B bitstream to the platform decoder.
|
||||
//!
|
||||
//! Lost frames become [`VideoEvent::FrameLost`], which the caller answers on the control stream with
|
||||
//! Frames come out strictly in frame order, each at most once and byte-exact; a frame that cannot be completed is
|
||||
//! reported in a [`VideoEvent::FrameLost`] range, which the caller answers on the control stream with
|
||||
//! `INVALIDATE_REF_FRAMES` (when the host supports it) or an IDR request.
|
||||
//!
|
||||
//! Only a shard's payload is used: the RTP and NV header bytes of a shard rebuilt by FEC are garbage (the host
|
||||
//! writes parity headers after computing parity), so a shard's place comes from its FEC fields alone.
|
||||
|
||||
use core::fmt;
|
||||
use core::time::Duration;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
|
||||
|
||||
use crate::{Instant, Result};
|
||||
use aes_gcm::Aes128Gcm;
|
||||
use aes_gcm::aead::{AeadInOut, KeyInit};
|
||||
|
||||
use crate::fec::ReedSolomon;
|
||||
use crate::util::{array, cap, malformed, need};
|
||||
use crate::{Error, Instant, Result};
|
||||
|
||||
pub mod packet;
|
||||
|
||||
@@ -18,29 +29,43 @@ pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16;
|
||||
pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
|
||||
/// Maximum frames being assembled at once; older ones are declared lost.
|
||||
pub const MAX_FRAMES_IN_FLIGHT: usize = 8;
|
||||
/// Packets for frames further than this ahead of the next expected frame are dropped.
|
||||
pub const MAX_FRAMES_AHEAD: u32 = 1024;
|
||||
/// Finished frames remembered, so their late parity packets are not counted as drops but replays are.
|
||||
const RECENT_FRAMES: usize = 32;
|
||||
|
||||
/// AES-128-GCM for encrypted video packets (`docs/PROTOCOL.md` 7). `Debug` never prints the key.
|
||||
#[derive(Clone)]
|
||||
pub struct VideoCipher {
|
||||
key: [u8; 16],
|
||||
key: zeroize::Zeroizing<[u8; 16]>,
|
||||
}
|
||||
|
||||
impl VideoCipher {
|
||||
/// A cipher for `rikey`.
|
||||
#[must_use]
|
||||
pub const fn new(rikey: [u8; 16]) -> Self {
|
||||
Self { key: rikey }
|
||||
pub fn new(rikey: [u8; 16]) -> Self {
|
||||
Self { key: zeroize::Zeroizing::new(rikey) }
|
||||
}
|
||||
|
||||
/// Decrypts one encrypted packet (`IV ‖ frame number ‖ tag ‖ ciphertext`) into the plaintext packet.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`], [`crate::Error::Truncated`] under the
|
||||
/// prefix, [`crate::Error::Malformed`] for an IV whose byte 11 is not `'V'`, [`crate::Error::Crypto`] for a bad
|
||||
/// tag. Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// [`Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`], [`Error::Truncated`] under the prefix,
|
||||
/// [`Error::Malformed`] for an IV whose byte 11 is not `'V'`, [`Error::Crypto`] for a bad tag.
|
||||
pub fn decrypt(&self, packet: &[u8]) -> Result<Vec<u8>> {
|
||||
let _ = (packet, &self.key);
|
||||
Err(crate::Error::Unimplemented)
|
||||
const W: &str = "encrypted video packet";
|
||||
cap(W, packet::MAX_VIDEO_PACKET_BYTES, packet.len())?;
|
||||
need(W, ENCRYPTION_PREFIX_LEN, packet.len())?;
|
||||
let iv = array::<12>(W, packet, 0)?;
|
||||
if iv.get(11) != Some(&b'V') {
|
||||
return Err(malformed("video IV byte 11 is not 'V'"));
|
||||
}
|
||||
let tag = array::<16>(W, packet, 16)?;
|
||||
let mut body = packet.get(ENCRYPTION_PREFIX_LEN..).unwrap_or(&[]).to_vec();
|
||||
Aes128Gcm::new((&*self.key).into())
|
||||
.decrypt_inout_detached(&iv.into(), b"", body.as_mut_slice().into(), &tag.into())
|
||||
.map_err(|_| Error::Crypto)?;
|
||||
Ok(body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +83,7 @@ pub struct VideoConfig {
|
||||
/// Decrypt packets with this cipher when video encryption was negotiated.
|
||||
pub cipher: Option<VideoCipher>,
|
||||
/// How long to wait for missing shards of a frame before declaring it lost.
|
||||
pub frame_timeout: core::time::Duration,
|
||||
pub frame_timeout: Duration,
|
||||
}
|
||||
|
||||
/// One complete frame for the decoder.
|
||||
@@ -109,9 +134,34 @@ pub struct VideoStats {
|
||||
pub frames_lost: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Block {
|
||||
data_shards: u16,
|
||||
parity_shards: u16,
|
||||
fec_percentage: u8,
|
||||
shards: BTreeMap<u16, Vec<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Pending {
|
||||
first_packet_at: Instant,
|
||||
rtp_timestamp: u32,
|
||||
last_block: u8,
|
||||
blocks: [Option<Block>; packet::MAX_FEC_BLOCKS],
|
||||
/// Every shard seen, by (block, shard index).
|
||||
seen: BTreeSet<(u8, u16)>,
|
||||
complete: Option<VideoFrame>,
|
||||
}
|
||||
|
||||
/// The video receiver.
|
||||
#[derive(Debug)]
|
||||
pub struct VideoDepacketizer {
|
||||
config: VideoConfig,
|
||||
payload_len: usize,
|
||||
next_frame: Option<u32>,
|
||||
frames: HashMap<u32, Pending>,
|
||||
recent: VecDeque<(u32, BTreeSet<(u8, u16)>)>,
|
||||
events: VecDeque<VideoEvent>,
|
||||
stats: VideoStats,
|
||||
}
|
||||
|
||||
@@ -119,42 +169,230 @@ impl VideoDepacketizer {
|
||||
/// A receiver for one stream.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::Malformed`] for a `packet_size` below the NV header size or above what fits in
|
||||
/// [`packet::MAX_VIDEO_PACKET_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// [`Error::Malformed`] for a `packet_size` not above the NV header size or above what fits in
|
||||
/// [`packet::MAX_VIDEO_PACKET_BYTES`].
|
||||
pub fn new(config: VideoConfig) -> Result<Self> {
|
||||
let _ = config;
|
||||
Err(crate::Error::Unimplemented)
|
||||
let size = usize::from(config.packet_size);
|
||||
if size <= packet::NV_HEADER_LEN || size + packet::VIDEO_RTP_LEN > packet::MAX_VIDEO_PACKET_BYTES {
|
||||
return Err(malformed("video packet_size"));
|
||||
}
|
||||
Ok(Self {
|
||||
payload_len: size - packet::NV_HEADER_LEN,
|
||||
config,
|
||||
next_frame: None,
|
||||
frames: HashMap::new(),
|
||||
recent: VecDeque::new(),
|
||||
events: VecDeque::new(),
|
||||
stats: VideoStats::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn drop_packet(&mut self) -> Result<()> {
|
||||
self.stats.packets_dropped += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Feeds one datagram from the video port. Bad, duplicate and too-old packets are counted and dropped; only
|
||||
/// an oversized datagram is an error.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`]. Phase A: always
|
||||
/// [`crate::Error::Unimplemented`].
|
||||
/// [`Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`].
|
||||
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
||||
let _ = (now, datagram);
|
||||
Err(crate::Error::Unimplemented)
|
||||
cap("video datagram", packet::MAX_VIDEO_PACKET_BYTES, datagram.len())?;
|
||||
let plain;
|
||||
let bytes = match &self.config.cipher {
|
||||
Some(c) => match c.decrypt(datagram) {
|
||||
Ok(p) => {
|
||||
plain = p;
|
||||
plain.as_slice()
|
||||
}
|
||||
Err(_) => return self.drop_packet(),
|
||||
},
|
||||
None => datagram,
|
||||
};
|
||||
let Ok(p) = parse_video_packet(bytes) else { return self.drop_packet() };
|
||||
if p.payload.len() != self.payload_len {
|
||||
return self.drop_packet();
|
||||
}
|
||||
let frame = p.nv.frame_index;
|
||||
let next = *self.next_frame.get_or_insert(frame);
|
||||
let ahead = frame.wrapping_sub(next);
|
||||
let shard = (p.nv.fec.block_index, p.nv.fec.shard_index);
|
||||
if ahead >= 1 << 31 {
|
||||
// Before the next frame: late parity of a finished frame is fine, anything seen before is a replay.
|
||||
let late = self.recent.iter_mut().find(|(f, _)| *f == frame).is_some_and(|(_, seen)| seen.insert(shard));
|
||||
if late {
|
||||
self.stats.packets += 1;
|
||||
return Ok(());
|
||||
}
|
||||
return self.drop_packet();
|
||||
}
|
||||
if ahead >= MAX_FRAMES_AHEAD {
|
||||
return self.drop_packet();
|
||||
}
|
||||
if !self.frames.contains_key(&frame) {
|
||||
while self.frames.len() >= MAX_FRAMES_IN_FLIGHT {
|
||||
self.give_up_head(now);
|
||||
}
|
||||
if self.next_frame.is_some_and(|n| frame.wrapping_sub(n) >= 1 << 31) {
|
||||
// The forced advance passed this frame.
|
||||
return self.drop_packet();
|
||||
}
|
||||
self.frames.insert(
|
||||
frame,
|
||||
Pending {
|
||||
first_packet_at: now,
|
||||
rtp_timestamp: p.rtp.timestamp,
|
||||
last_block: p.nv.fec.last_block_index,
|
||||
blocks: [None, None, None, None],
|
||||
seen: BTreeSet::new(),
|
||||
complete: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
let accepted = self.store(frame, &p, now);
|
||||
if !accepted {
|
||||
return self.drop_packet();
|
||||
}
|
||||
self.stats.packets += 1;
|
||||
self.advance(now);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stores one packet in its frame; false for a duplicate or a packet that contradicts the frame's FEC layout.
|
||||
fn store(&mut self, frame: u32, p: &VideoPacket<'_>, now: Instant) -> bool {
|
||||
let payload_len = self.payload_len;
|
||||
let Some(f) = self.frames.get_mut(&frame) else { return false };
|
||||
let fec = p.nv.fec;
|
||||
if fec.last_block_index != f.last_block || !f.seen.insert((fec.block_index, fec.shard_index)) {
|
||||
return false;
|
||||
}
|
||||
if f.complete.is_some() {
|
||||
return true;
|
||||
}
|
||||
let Some(slot) = f.blocks.get_mut(usize::from(fec.block_index)) else { return false };
|
||||
let block = slot.get_or_insert_with(|| Block {
|
||||
data_shards: fec.data_shards,
|
||||
parity_shards: crate::fec::parity_count(usize::from(fec.data_shards), fec.fec_percentage)
|
||||
.ok()
|
||||
.and_then(|m| u16::try_from(m).ok())
|
||||
.unwrap_or(0),
|
||||
fec_percentage: fec.fec_percentage,
|
||||
shards: BTreeMap::new(),
|
||||
});
|
||||
if block.data_shards != fec.data_shards || block.fec_percentage != fec.fec_percentage {
|
||||
f.seen.remove(&(fec.block_index, fec.shard_index));
|
||||
return false;
|
||||
}
|
||||
block.shards.insert(fec.shard_index, p.payload.to_vec());
|
||||
let complete = (0..=usize::from(f.last_block)).all(|b| {
|
||||
f.blocks
|
||||
.get(b)
|
||||
.and_then(Option::as_ref)
|
||||
.is_some_and(|blk| blk.shards.len() >= usize::from(blk.data_shards))
|
||||
});
|
||||
if complete {
|
||||
match assemble(f, frame, payload_len, now) {
|
||||
Some((v, recovered)) => {
|
||||
self.stats.shards_recovered += u64::from(recovered);
|
||||
f.complete = Some(v);
|
||||
for b in &mut f.blocks {
|
||||
*b = None;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// Rebuilt but unusable: it can never complete; the timeout reports it lost.
|
||||
for b in &mut f.blocks {
|
||||
*b = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn lose(&mut self, first: u32, last: u32) {
|
||||
self.events.push_back(VideoEvent::FrameLost { first, last });
|
||||
let span = last.wrapping_sub(first);
|
||||
self.stats.frames_lost += u64::from(span) + 1;
|
||||
self.frames.retain(|&f, _| f.wrapping_sub(first) > span);
|
||||
self.next_frame = Some(last.wrapping_add(1));
|
||||
}
|
||||
|
||||
fn deliver(&mut self, frame: u32) {
|
||||
if let Some(mut f) = self.frames.remove(&frame) {
|
||||
if let Some(v) = f.complete.take() {
|
||||
self.events.push_back(VideoEvent::Frame(v));
|
||||
self.stats.frames += 1;
|
||||
}
|
||||
if self.recent.len() >= RECENT_FRAMES {
|
||||
self.recent.pop_front();
|
||||
}
|
||||
self.recent.push_back((frame, core::mem::take(&mut f.seen)));
|
||||
}
|
||||
self.next_frame = Some(frame.wrapping_add(1));
|
||||
}
|
||||
|
||||
/// The pending frame closest after `next`, as (frame index, distance).
|
||||
fn lowest_pending(&self, next: u32) -> Option<(u32, u32)> {
|
||||
self.frames.keys().map(|&f| (f, f.wrapping_sub(next))).min_by_key(|&(_, d)| d)
|
||||
}
|
||||
|
||||
/// Delivers or gives up frames at the head while it is complete or has timed out.
|
||||
fn advance(&mut self, now: Instant) {
|
||||
let timeout = self.config.frame_timeout;
|
||||
while let Some(next) = self.next_frame {
|
||||
match self.frames.get(&next) {
|
||||
Some(f) if f.complete.is_some() => self.deliver(next),
|
||||
Some(f) if f.first_packet_at.saturating_add(timeout) <= now => self.lose(next, next),
|
||||
Some(_) => return,
|
||||
None => {
|
||||
let Some((lowest, _)) = self.lowest_pending(next) else { return };
|
||||
let expired =
|
||||
self.frames.get(&lowest).is_some_and(|f| f.first_packet_at.saturating_add(timeout) <= now);
|
||||
if !expired {
|
||||
return;
|
||||
}
|
||||
self.lose(next, lowest.wrapping_sub(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees one slot: delivers the head if complete, else declares it (or the gap before the oldest frame) lost.
|
||||
fn give_up_head(&mut self, now: Instant) {
|
||||
let Some(next) = self.next_frame else { return };
|
||||
match self.frames.get(&next) {
|
||||
Some(f) if f.complete.is_some() => self.deliver(next),
|
||||
Some(_) => self.lose(next, next),
|
||||
None => match self.lowest_pending(next) {
|
||||
Some((lowest, _)) => self.lose(next, lowest.wrapping_sub(1)),
|
||||
None => return,
|
||||
},
|
||||
}
|
||||
self.advance(now);
|
||||
}
|
||||
|
||||
/// The next event.
|
||||
pub fn poll_event(&mut self) -> Option<VideoEvent> {
|
||||
None
|
||||
self.events.pop_front()
|
||||
}
|
||||
|
||||
/// When an incomplete frame times out.
|
||||
#[must_use]
|
||||
pub fn poll_timeout(&self) -> Option<Instant> {
|
||||
None
|
||||
let next = self.next_frame?;
|
||||
let head = self.frames.get(&next).map(|_| next).or_else(|| self.lowest_pending(next).map(|(f, _)| f))?;
|
||||
self.frames.get(&head).map(|f| f.first_packet_at.saturating_add(self.config.frame_timeout))
|
||||
}
|
||||
|
||||
/// Declares timed-out frames lost.
|
||||
///
|
||||
/// # Errors
|
||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
||||
/// None today.
|
||||
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
||||
let _ = now;
|
||||
Err(crate::Error::Unimplemented)
|
||||
self.advance(now);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Counters.
|
||||
@@ -163,3 +401,59 @@ impl VideoDepacketizer {
|
||||
self.stats
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the frame of a pending entry whose every block has enough shards: rebuilds missing data shards, joins the
|
||||
/// data in block order and trims the frame header and padding. `None` when the result is unusable.
|
||||
fn assemble(f: &Pending, frame_index: u32, payload_len: usize, now: Instant) -> Option<(VideoFrame, u16)> {
|
||||
let mut data: Vec<u8> = Vec::new();
|
||||
let mut recovered: u16 = 0;
|
||||
let mut shards_total = 0usize;
|
||||
for b in 0..=usize::from(f.last_block) {
|
||||
let block = f.blocks.get(b)?.as_ref()?;
|
||||
let k = usize::from(block.data_shards);
|
||||
let m = usize::from(block.parity_shards);
|
||||
shards_total += k;
|
||||
if data.len().saturating_add(k * payload_len) > MAX_FRAME_BYTES + payload_len {
|
||||
return None;
|
||||
}
|
||||
let missing = (0..block.data_shards).filter(|i| !block.shards.contains_key(i)).count();
|
||||
if missing == 0 {
|
||||
for i in 0..block.data_shards {
|
||||
data.extend_from_slice(block.shards.get(&i)?);
|
||||
}
|
||||
} else {
|
||||
let code = ReedSolomon::new(k, m).ok()?;
|
||||
let mut shards: Vec<Option<Vec<u8>>> =
|
||||
(0..k + m).map(|i| u16::try_from(i).ok().and_then(|i| block.shards.get(&i).cloned())).collect();
|
||||
code.reconstruct(&mut shards).ok()?;
|
||||
for s in shards.iter().take(k) {
|
||||
data.extend_from_slice(s.as_ref()?);
|
||||
}
|
||||
recovered = recovered.saturating_add(u16::try_from(missing).unwrap_or(u16::MAX));
|
||||
}
|
||||
}
|
||||
let header = packet::parse_frame_header(&data).ok()?;
|
||||
let last = usize::try_from(header.last_payload_len).unwrap_or(0);
|
||||
let end = if (1..=payload_len).contains(&last) && shards_total >= 1 {
|
||||
(shards_total - 1) * payload_len + last
|
||||
} else {
|
||||
// The header does not say where the frame ends (Wolf's constant, U13): trim the zero padding.
|
||||
data.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1)
|
||||
};
|
||||
let bitstream = data.get(packet::FRAME_HEADER_LEN..end)?.to_vec();
|
||||
if bitstream.len() > MAX_FRAME_BYTES {
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
VideoFrame {
|
||||
frame_index,
|
||||
header,
|
||||
bitstream,
|
||||
rtp_timestamp: f.rtp_timestamp,
|
||||
first_packet_at: f.first_packet_at,
|
||||
completed_at: now,
|
||||
recovered_shards: recovered,
|
||||
},
|
||||
recovered,
|
||||
))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user