[domistream] Video API: packet parser, frame header, decryption, depacketizer with FEC

This commit is contained in:
2026-11-25 11:47:55 +01:00
parent e7c69ac956
commit b4a21dfc10
3 changed files with 289 additions and 0 deletions
+1
View File
@@ -47,6 +47,7 @@ pub mod pairing;
pub mod rtp;
pub mod rtsp;
pub mod time;
pub mod video;
pub use entropy::RandomSource;
pub use error::{Error, Result};
+165
View File
@@ -0,0 +1,165 @@
//! 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
//! `INVALIDATE_REF_FRAMES` (when the host supports it) or an IDR request.
use core::fmt;
use crate::{Instant, Result};
pub mod packet;
pub use packet::{FecInfo, FrameHeader, FrameType, NvVideoHeader, VideoFlags, VideoPacket, parse_video_packet};
/// 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;
/// AES-128-GCM for encrypted video packets (`docs/PROTOCOL.md` 7). `Debug` never prints the key.
#[derive(Clone)]
pub struct VideoCipher {
key: [u8; 16],
}
impl VideoCipher {
/// A cipher for `rikey`.
#[must_use]
pub const fn new(rikey: [u8; 16]) -> Self {
Self { key: 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`].
pub fn decrypt(&self, packet: &[u8]) -> Result<Vec<u8>> {
let _ = (packet, &self.key);
Err(crate::Error::Unimplemented)
}
}
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: core::time::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,
}
/// The video receiver.
#[derive(Debug)]
pub struct VideoDepacketizer {
stats: VideoStats,
}
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`].
pub fn new(config: VideoConfig) -> Result<Self> {
let _ = config;
Err(crate::Error::Unimplemented)
}
/// 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`].
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
let _ = (now, datagram);
Err(crate::Error::Unimplemented)
}
/// The next event.
pub fn poll_event(&mut self) -> Option<VideoEvent> {
None
}
/// When an incomplete frame times out.
#[must_use]
pub fn poll_timeout(&self) -> Option<Instant> {
None
}
/// Declares timed-out frames lost.
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
let _ = now;
Err(crate::Error::Unimplemented)
}
/// Counters.
#[must_use]
pub const fn stats(&self) -> VideoStats {
self.stats
}
}
+123
View File
@@ -0,0 +1,123 @@
//! The video packet layout (`docs/PROTOCOL.md` 5.2): RTP header, 4 reserved bytes, the 16-byte NV video header,
//! payload. NV header fields are little-endian.
use crate::rtp::RtpHeader;
/// RTP header plus the 4 reserved bytes.
pub const VIDEO_RTP_LEN: usize = 16;
/// Length of the NV video header.
pub const NV_HEADER_LEN: usize = 16;
/// Offset of the payload in a packet.
pub const PAYLOAD_OFFSET: usize = VIDEO_RTP_LEN + NV_HEADER_LEN;
/// Length of the frame header at the start of each frame's data.
pub const FRAME_HEADER_LEN: usize = 8;
/// Maximum size of one video packet (plaintext or encrypted), in bytes.
pub const MAX_VIDEO_PACKET_BYTES: usize = 4096;
/// Maximum FEC blocks per frame (two-bit block index).
pub const MAX_FEC_BLOCKS: usize = 4;
/// The `packetSize` used when ANNOUNCE does not set one.
pub const DEFAULT_PACKET_SIZE: u16 = 1024;
/// NV video flags.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct VideoFlags(pub u8);
impl VideoFlags {
/// The packet carries picture data (0 on parity packets).
pub const PICTURE_DATA: u8 = 0x01;
/// Last data packet of the frame.
pub const END_OF_FRAME: u8 = 0x02;
/// First data packet of the frame.
pub const START_OF_FRAME: u8 = 0x04;
}
/// The FEC fields of one packet, decoded from `fecInfo` and `multiFecBlocks`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FecInfo {
/// Index in the block: `0..data_shards` data, `data_shards..` parity (`fecInfo` bits 12-21).
pub shard_index: u16,
/// Data shards in this block (`fecInfo` bits 22-31).
pub data_shards: u16,
/// FEC percentage of this block (`fecInfo` bits 4-11).
pub fec_percentage: u8,
/// This block's index in the frame (`multiFecBlocks` bits 4-5).
pub block_index: u8,
/// The frame's last block index (`multiFecBlocks` bits 6-7).
pub last_block_index: u8,
}
/// The NV video header.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct NvVideoHeader {
/// Stream packet index (RTP sequence << 8).
pub stream_packet_index: u32,
/// Frame index.
pub frame_index: u32,
/// Flags.
pub flags: VideoFlags,
/// `multiFecFlags` byte, raw (UNKNOWN U15).
pub multi_fec_flags: u8,
/// FEC fields.
pub fec: FecInfo,
}
/// One plaintext video packet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VideoPacket<'a> {
/// RTP header.
pub rtp: RtpHeader,
/// NV video header.
pub nv: NvVideoHeader,
/// Payload (frame data for data shards, parity bytes for parity shards).
pub payload: &'a [u8],
}
/// Parses one plaintext video packet. Checks the FEC fields are consistent (`shard_index < data + parity`,
/// `block_index <= last_block_index`, `data_shards > 0`).
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_VIDEO_PACKET_BYTES`], [`crate::Error::Truncated`] under
/// [`PAYLOAD_OFFSET`], [`crate::Error::Malformed`] for inconsistent FEC fields. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn parse_video_packet(packet: &[u8]) -> crate::Result<VideoPacket<'_>> {
let _ = packet;
Err(crate::Error::Unimplemented)
}
/// Frame types in the frame header.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FrameType {
/// Predicted (1).
Predicted,
/// Key / IDR (2).
Key,
/// First frame after a reference frame invalidation (5).
Recovery,
/// Any other value.
Other(u8),
}
/// The 8-byte header in front of each frame's bitstream (UNKNOWN U13: Wolf shows a constant, Moonshine these
/// fields).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FrameHeader {
/// The 8 bytes as received.
pub raw: [u8; FRAME_HEADER_LEN],
/// Byte 0.
pub header_type: u8,
/// Bytes 1-2, LE: host processing latency (unit UNKNOWN).
pub processing_latency: u16,
/// Byte 3.
pub frame_type: FrameType,
/// Bytes 4-7, LE: payload bytes in the last data shard.
pub last_payload_len: u32,
}
/// Parses the frame header at the start of a frame's data (the rest is ignored here).
///
/// # Errors
/// [`crate::Error::Truncated`] under [`FRAME_HEADER_LEN`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_frame_header(frame_data: &[u8]) -> crate::Result<FrameHeader> {
let _ = frame_data;
Err(crate::Error::Unimplemented)
}