392 lines
17 KiB
Rust
392 lines
17 KiB
Rust
//! 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<VideoCipher>,
|
||
/// 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<usize> {
|
||
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<FecBlock> {
|
||
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<Vec<FecBlock>> {
|
||
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<Self> {
|
||
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<Vec<Vec<u8>>> {
|
||
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<u8>> = 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<u8>> = 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
|
||
}
|
||
}
|