491 lines
19 KiB
Rust
491 lines
19 KiB
Rust
//! 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.
|
|
//!
|
|
//! 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 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;
|
|
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;
|
|
/// Maximum size of one reassembled frame (frame header + bitstream), in bytes.
|
|
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: zeroize::Zeroizing<[u8; 16]>,
|
|
}
|
|
|
|
impl VideoCipher {
|
|
/// A cipher for `rikey`.
|
|
#[must_use]
|
|
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
|
|
/// [`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>> {
|
|
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)
|
|
}
|
|
}
|
|
|
|
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<Vec<u8>> {
|
|
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(<redacted>)")
|
|
}
|
|
}
|
|
|
|
/// Settings of the video receiver.
|
|
#[derive(Clone, Debug)]
|
|
pub struct VideoConfig {
|
|
/// Negotiated `packetSize`.
|
|
pub packet_size: u16,
|
|
/// 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: Duration,
|
|
}
|
|
|
|
/// One complete frame for the decoder.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct VideoFrame {
|
|
/// Frame index.
|
|
pub frame_index: u32,
|
|
/// The frame header.
|
|
pub header: FrameHeader,
|
|
/// Annex-B bitstream (start codes included), frame header and padding removed.
|
|
pub bitstream: Vec<u8>,
|
|
/// RTP timestamp of its first packet.
|
|
pub rtp_timestamp: u32,
|
|
/// When its first packet arrived.
|
|
pub first_packet_at: Instant,
|
|
/// When it was completed.
|
|
pub completed_at: Instant,
|
|
/// Data shards rebuilt by FEC.
|
|
pub recovered_shards: u16,
|
|
}
|
|
|
|
/// What the receiver reports.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum VideoEvent {
|
|
/// A frame is ready, in frame order.
|
|
Frame(VideoFrame),
|
|
/// Frames `first..=last` cannot be completed; ask for recovery.
|
|
FrameLost {
|
|
/// First lost frame index.
|
|
first: u32,
|
|
/// Last lost frame index.
|
|
last: u32,
|
|
},
|
|
}
|
|
|
|
/// Counters for the stats overlay.
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
|
pub struct VideoStats {
|
|
/// Packets accepted.
|
|
pub packets: u64,
|
|
/// Packets refused (bad format, bad tag, duplicate, too old).
|
|
pub packets_dropped: u64,
|
|
/// Data shards rebuilt by FEC.
|
|
pub shards_recovered: u64,
|
|
/// Frames delivered.
|
|
pub frames: u64,
|
|
/// Frames lost.
|
|
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,
|
|
}
|
|
|
|
impl VideoDepacketizer {
|
|
/// A receiver for one stream.
|
|
///
|
|
/// # Errors
|
|
/// [`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 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
|
|
/// [`Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`].
|
|
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
|
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> {
|
|
self.events.pop_front()
|
|
}
|
|
|
|
/// When an incomplete frame times out.
|
|
#[must_use]
|
|
pub fn poll_timeout(&self) -> Option<Instant> {
|
|
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
|
|
/// None today.
|
|
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
|
self.advance(now);
|
|
Ok(())
|
|
}
|
|
|
|
/// Counters.
|
|
#[must_use]
|
|
pub const fn stats(&self) -> VideoStats {
|
|
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,
|
|
))
|
|
}
|