Compare commits
11 Commits
7fce5aa226
...
fd4285aff0
| Author | SHA1 | Date | |
|---|---|---|---|
| fd4285aff0 | |||
| a86a689b1f | |||
| 27b7f2bf1d | |||
| 54bc9f5faf | |||
| 33b7b90b65 | |||
| 81ddf64bee | |||
| 7a6afed575 | |||
| 0d3a9a7917 | |||
| b62443ef28 | |||
| e1abd7d060 | |||
| 7983833ba6 |
@@ -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<Vec<u8>> {
|
||||
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::<aes::Aes128>::new((&*self.key).into(), &iv.into())
|
||||
.encrypt_padded::<Pkcs7>(&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(<redacted>)")
|
||||
|
||||
@@ -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<AudioCipher>,
|
||||
/// 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<Self> {
|
||||
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<Vec<Vec<u8>>> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
//! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP,
|
||||
//! and the client state machine.
|
||||
//! the client state machine and the host's session ([`server`], section 2.5).
|
||||
|
||||
pub mod client;
|
||||
pub mod sdp;
|
||||
pub mod server;
|
||||
|
||||
pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts};
|
||||
pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp};
|
||||
pub use server::{HostOffer, RtspServer, RtspServerState, ServerConfig, ServerEvent, ServerReply};
|
||||
|
||||
use crate::util::{cap, malformed, parse_dec};
|
||||
use crate::{Error, Result};
|
||||
@@ -132,6 +134,37 @@ impl RtspResponse {
|
||||
pub fn header(&self, name: &str) -> Option<&str> {
|
||||
header(&self.headers, name)
|
||||
}
|
||||
|
||||
/// Serializes the response (`RTSP/1.0 <status> <reason>`, CRLF line ends, empty line, payload) with exactly the
|
||||
/// given headers. The host side's mirror of [`RtspRequest::encode`].
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::Malformed`] for a status outside 100..=999, CR, LF or another control character in the reason, a
|
||||
/// header name that is not a token, or CR or LF in a header value; [`Error::TooLarge`] over
|
||||
/// [`MAX_RTSP_MESSAGE_BYTES`].
|
||||
pub fn encode(&self) -> Result<Vec<u8>> {
|
||||
if !(100..=999).contains(&self.status) || self.reason.bytes().any(|b| b.is_ascii_control()) {
|
||||
return Err(malformed("rtsp status line"));
|
||||
}
|
||||
let mut out = format!("{VERSION} {} {}\r\n", self.status, self.reason);
|
||||
for (name, value) in &self.headers {
|
||||
if name.is_empty() || !name.bytes().all(is_token) {
|
||||
return Err(malformed("rtsp header name"));
|
||||
}
|
||||
if value.bytes().any(|b| b == b'\r' || b == b'\n') {
|
||||
return Err(malformed("rtsp header value"));
|
||||
}
|
||||
out.push_str(name);
|
||||
out.push_str(": ");
|
||||
out.push_str(value);
|
||||
out.push_str("\r\n");
|
||||
}
|
||||
out.push_str("\r\n");
|
||||
let mut bytes = out.into_bytes();
|
||||
cap("rtsp response", MAX_RTSP_MESSAGE_BYTES, bytes.len().saturating_add(self.body.len()))?;
|
||||
bytes.extend_from_slice(&self.body);
|
||||
Ok(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// A message split into start line, headers and payload.
|
||||
@@ -252,21 +285,31 @@ pub fn parse_request(message: &[u8]) -> Result<RtspRequest> {
|
||||
Ok(RtspRequest { method, target: target.to_owned(), headers: m.headers, body: m.body })
|
||||
}
|
||||
|
||||
/// Cuts the TCP byte stream from the host into whole messages.
|
||||
/// Cuts a TCP byte stream into whole messages.
|
||||
///
|
||||
/// A message ends after its headers plus `Content-Length` payload bytes; without `Content-Length` it ends when
|
||||
/// the host closes the connection ([`RtspFramer::finish`]) (UNKNOWN U5). Never buffers more than
|
||||
/// [`MAX_RTSP_MESSAGE_BYTES`].
|
||||
/// A message ends after its headers plus `Content-Length` payload bytes. Without `Content-Length`, a framer made
|
||||
/// with [`RtspFramer::new`] (the client reading the host's answers) ends the message when the host closes the
|
||||
/// connection ([`RtspFramer::finish`]) (UNKNOWN U5); one made with [`RtspFramer::for_requests`] (the host reading
|
||||
/// a client's requests) takes a missing `Content-Length` as zero, as RFC 2326 section 4.4 says, so the message
|
||||
/// ends at the empty line (`docs/PROTOCOL.md` 2.5). Never buffers more than [`MAX_RTSP_MESSAGE_BYTES`].
|
||||
#[derive(Debug, Default)]
|
||||
pub struct RtspFramer {
|
||||
buffer: Vec<u8>,
|
||||
/// A missing `Content-Length` means "no payload" (requests) instead of "until close" (answers).
|
||||
missing_length_is_zero: bool,
|
||||
}
|
||||
|
||||
impl RtspFramer {
|
||||
/// An empty framer.
|
||||
/// An empty framer for the host's answers (client side).
|
||||
#[must_use]
|
||||
pub const fn new() -> Self {
|
||||
Self { buffer: Vec::new() }
|
||||
Self { buffer: Vec::new(), missing_length_is_zero: false }
|
||||
}
|
||||
|
||||
/// An empty framer for a client's requests (host side): a request without `Content-Length` has no payload.
|
||||
#[must_use]
|
||||
pub const fn for_requests() -> Self {
|
||||
Self { buffer: Vec::new(), missing_length_is_zero: true }
|
||||
}
|
||||
|
||||
/// Appends received bytes.
|
||||
@@ -293,7 +336,8 @@ impl RtspFramer {
|
||||
headers.push((n.to_owned(), v.trim_matches([' ', '\t']).to_owned()));
|
||||
}
|
||||
}
|
||||
Ok(Some((head_len, content_length(&headers, head_len)?)))
|
||||
let length = content_length(&headers, head_len)?;
|
||||
Ok(Some((head_len, if self.missing_length_is_zero { Some(length.unwrap_or(0)) } else { length })))
|
||||
}
|
||||
|
||||
/// Takes the next complete message, if one is buffered.
|
||||
|
||||
@@ -199,7 +199,7 @@ impl HostCapabilities {
|
||||
}
|
||||
}
|
||||
|
||||
/// `x-nv-vqos[0].bitStreamFormat` values (judgment from the codec order H.264, HEVC, AV1; UNKNOWN U6).
|
||||
/// `x-nv-vqos[0].bitStreamFormat` values: 0 H.264, 1 HEVC, 2 AV1 as a host reads them (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||
const fn bitstream_format(codec: VideoCodec) -> u8 {
|
||||
match codec {
|
||||
VideoCodec::H264 => 0,
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
//! The ANNOUNCE payload on the host side (`docs/PROTOCOL.md` 2.4, 2.5): a strict parser of the client's SDP into a
|
||||
//! typed [`StreamConfig`], and the matching writer.
|
||||
//!
|
||||
//! The payload is hostile input. The parser caps the payload size, the number of lines, the length of each line and
|
||||
//! the number of `a=` attributes before it looks at any of them, allocates nothing while it reads, refuses a known
|
||||
//! attribute that appears twice, range-checks every number, and counts (then ignores) attributes it does not know.
|
||||
|
||||
use crate::rtsp::client::VideoCodec;
|
||||
use crate::rtsp::sdp::{EncryptionFlags, MAX_AUDIO_CHANNELS};
|
||||
use crate::util::{cap, malformed, parse_dec};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Maximum size of an ANNOUNCE payload, in bytes (the SDP cap of `docs/PROTOCOL.md` 2.3).
|
||||
pub const MAX_ANNOUNCE_BYTES: usize = crate::rtsp::sdp::MAX_SDP_BYTES;
|
||||
/// Maximum number of non-empty lines in an ANNOUNCE payload.
|
||||
pub const MAX_ANNOUNCE_LINES: usize = 1024;
|
||||
/// Maximum length of one line, in bytes, without its line end.
|
||||
pub const MAX_ANNOUNCE_LINE_BYTES: usize = 1024;
|
||||
/// Maximum number of `a=` attributes, known or not.
|
||||
pub const MAX_ANNOUNCE_ATTRIBUTES: usize = 512;
|
||||
|
||||
/// Largest width or height accepted, in pixels (our cap, not the protocol's).
|
||||
pub const MAX_DIMENSION: u32 = 16_384;
|
||||
/// Largest frame rate accepted (our cap, not the protocol's).
|
||||
pub const MAX_FPS: u32 = 1000;
|
||||
/// Smallest video `packetSize` a host accepts (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||
pub const MIN_PACKET_SIZE: u16 = 200;
|
||||
/// Largest video `packetSize`: one stream packet in one IPv6 UDP datagram (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||
pub const MAX_PACKET_SIZE: u16 = 65_471;
|
||||
/// Largest bitrate in kbit/s: the value times 1000 must fit in a `u32` (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||
pub const MAX_BITRATE_KBPS: u32 = 4_294_967;
|
||||
/// Longest audio packet in milliseconds: the longest Opus packet (RFC 6716 section 3.2.5).
|
||||
pub const MAX_AUDIO_PACKET_DURATION_MS: u8 = 120;
|
||||
|
||||
/// Chroma subsampling, `x-ss-video[0].chromaSamplingType` (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum ChromaSampling {
|
||||
/// 4:2:0, value 0 (the default).
|
||||
#[default]
|
||||
Yuv420,
|
||||
/// 4:4:4, value 1.
|
||||
Yuv444,
|
||||
}
|
||||
|
||||
/// The audio layout the client asks for (`x-nv-audio.surround.*`, `docs/PROTOCOL.md` 2.5).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct SurroundSettings {
|
||||
/// `x-nv-audio.surround.enable`: 0 or 1, default 0. When off, a Moonshine-like host takes the layout from the
|
||||
/// launch call's `surroundAudioInfo` instead of `channels` and `channel_mask` \[M\].
|
||||
pub enabled: bool,
|
||||
/// `x-nv-audio.surround.numChannels`: 1..=8, default 2 \[M\].
|
||||
pub channels: u8,
|
||||
/// `x-nv-audio.surround.channelMask`: the speaker mask, kept as sent; default `0x3` \[M\].
|
||||
pub channel_mask: u32,
|
||||
/// `x-nv-audio.surround.AudioQuality`: 0 or 1, default 1 (high quality) \[M\].
|
||||
pub high_quality: bool,
|
||||
}
|
||||
|
||||
impl Default for SurroundSettings {
|
||||
fn default() -> Self {
|
||||
Self { enabled: false, channels: 2, channel_mask: 0x3, high_quality: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a client asked for in ANNOUNCE, typed and range-checked (`docs/PROTOCOL.md` 2.4, 2.5).
|
||||
///
|
||||
/// Values whose meaning is not settled are kept as the raw number the client sent.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct StreamConfig {
|
||||
/// `x-nv-video[0].clientViewportWd`, required, 1..=[`MAX_DIMENSION`].
|
||||
pub width: u32,
|
||||
/// `x-nv-video[0].clientViewportHt`, required, 1..=[`MAX_DIMENSION`].
|
||||
pub height: u32,
|
||||
/// `x-nv-video[0].maxFPS`, required, 1..=[`MAX_FPS`].
|
||||
pub max_fps: u32,
|
||||
/// `x-nv-video[0].packetSize`, required, [`MIN_PACKET_SIZE`]..=[`MAX_PACKET_SIZE`].
|
||||
pub packet_size: u16,
|
||||
/// `x-ml-video.configuredBitrateKbps`, required, 1..=[`MAX_BITRATE_KBPS`].
|
||||
pub bitrate_kbps: u32,
|
||||
/// `x-nv-vqos[0].bitStreamFormat`, required: 0 H.264, 1 HEVC, 2 AV1 \[M\]; anything else is refused.
|
||||
pub codec: VideoCodec,
|
||||
/// `x-nv-vqos[0].fec.minRequiredFecPackets`, required, 0..=255.
|
||||
pub min_fec_packets: u8,
|
||||
/// `x-nv-vqos[0].qosTrafficType`, required, kept as sent (a Moonshine-like host turns QoS off for 0 \[M\]).
|
||||
pub video_qos_traffic_type: u32,
|
||||
/// `x-nv-aqos.packetDuration`, required, 1..=[`MAX_AUDIO_PACKET_DURATION_MS`] milliseconds.
|
||||
pub audio_packet_duration_ms: u8,
|
||||
/// `x-nv-aqos.qosTrafficType`, required, kept as sent.
|
||||
pub audio_qos_traffic_type: u32,
|
||||
/// `x-nv-video[0].maxNumReferenceFrames`, default 1 \[M\]. Kept raw: what 0 means has GPL provenance only
|
||||
/// (\[M*\], `docs/PROTOCOL.md` 2.4), so it is not interpreted here.
|
||||
pub max_reference_frames: u32,
|
||||
/// `x-nv-video[0].refPicInvalidation`, 0 or 1. Default 0 (the client cannot invalidate, so the host sends an
|
||||
/// IDR frame on loss, which always works): UNKNOWN U6, settled by measurement.
|
||||
pub reference_frame_invalidation: bool,
|
||||
/// `x-nv-video[0].dynamicRangeMode`, default 0, kept raw. Moonshine reads 0 as SDR \[M\]; no other value has a
|
||||
/// settled meaning: UNKNOWN U6, settled by measurement.
|
||||
pub dynamic_range_mode: u32,
|
||||
/// `x-nv-video[0].encoderCscMode`, default 0, kept raw. Its bit layout has GPL provenance only (\[M*\]):
|
||||
/// UNKNOWN U6, settled by measurement (`docs/LUMEN-HOST-PLAN.md` 1.3).
|
||||
pub encoder_csc_mode: u32,
|
||||
/// `x-ss-video[0].chromaSamplingType`, 0 or 1, default 0 (4:2:0) \[M\].
|
||||
pub chroma: ChromaSampling,
|
||||
/// `x-ss-general.encryptionEnabled`, 0..=255, default 0 \[M\]; bits as in `docs/PROTOCOL.md` 2.3. Kept as sent;
|
||||
/// [`super::RtspServer`] refuses bits the host did not offer.
|
||||
pub encryption: EncryptionFlags,
|
||||
/// `x-nv-audio.surround.*`.
|
||||
pub surround: SurroundSettings,
|
||||
/// `a=` attributes the parser does not know: counted, otherwise ignored (UNKNOWN U6). Not written by
|
||||
/// [`write_announce`].
|
||||
pub unknown_attributes: u32,
|
||||
}
|
||||
|
||||
/// Parses an ANNOUNCE payload (SDP lines, LF or CRLF, empty lines skipped) into a [`StreamConfig`].
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::TooLarge`] over [`MAX_ANNOUNCE_BYTES`], [`MAX_ANNOUNCE_LINES`], [`MAX_ANNOUNCE_LINE_BYTES`] or
|
||||
/// [`MAX_ANNOUNCE_ATTRIBUTES`]; [`Error::Malformed`] for a payload that is not UTF-8, a line without `=`, an empty
|
||||
/// line type, a control character, a known attribute given twice, a required attribute missing or a number that is
|
||||
/// not plain decimal; [`Error::UnexpectedValue`] for a number outside its range.
|
||||
pub fn parse_announce(payload: &[u8]) -> Result<StreamConfig> {
|
||||
cap("announce", MAX_ANNOUNCE_BYTES, payload.len())?;
|
||||
let text = core::str::from_utf8(payload).map_err(|_| malformed("announce: not UTF-8"))?;
|
||||
let mut values: [Option<&str>; ATTRIBUTES.len()] = [None; ATTRIBUTES.len()];
|
||||
let mut lines = 0usize;
|
||||
let mut attributes = 0usize;
|
||||
let mut unknown = 0u32;
|
||||
for raw in text.split('\n') {
|
||||
let line = raw.strip_suffix('\r').unwrap_or(raw);
|
||||
cap("announce line", MAX_ANNOUNCE_LINE_BYTES, line.len())?;
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
lines += 1;
|
||||
cap("announce lines", MAX_ANNOUNCE_LINES, lines)?;
|
||||
if line.bytes().any(|b| b.is_ascii_control() && b != b'\t') {
|
||||
return Err(malformed("announce: control character in a line"));
|
||||
}
|
||||
let (kind, rest) = line.split_once('=').ok_or(malformed("announce: line without ="))?;
|
||||
if kind.is_empty() {
|
||||
return Err(malformed("announce: line with an empty type"));
|
||||
}
|
||||
// Only `a=` lines carry settings; `v=`, `o=`, `s=`, `t=`, `m=` and bare lines are not read.
|
||||
if kind != "a" {
|
||||
continue;
|
||||
}
|
||||
attributes += 1;
|
||||
cap("announce attributes", MAX_ANNOUNCE_ATTRIBUTES, attributes)?;
|
||||
let (name, value) = rest.split_once(':').unwrap_or((rest, ""));
|
||||
match ATTRIBUTES.iter().position(|a| a.name == name).and_then(|i| values.get_mut(i)) {
|
||||
Some(Some(_)) => return Err(malformed("announce: an attribute given twice")),
|
||||
Some(slot) => *slot = Some(value.trim_matches([' ', '\t'])),
|
||||
None => unknown = unknown.saturating_add(1),
|
||||
}
|
||||
}
|
||||
let a = Values(&values);
|
||||
let codec = match a.required(BIT_STREAM_FORMAT, 0, 2)? {
|
||||
0 => VideoCodec::H264,
|
||||
1 => VideoCodec::Hevc,
|
||||
_ => VideoCodec::Av1,
|
||||
};
|
||||
Ok(StreamConfig {
|
||||
width: narrow(a.required(VIEWPORT_WD, 1, u64::from(MAX_DIMENSION))?)?,
|
||||
height: narrow(a.required(VIEWPORT_HT, 1, u64::from(MAX_DIMENSION))?)?,
|
||||
max_fps: narrow(a.required(MAX_FPS_ATTR, 1, u64::from(MAX_FPS))?)?,
|
||||
packet_size: narrow(a.required(PACKET_SIZE, u64::from(MIN_PACKET_SIZE), u64::from(MAX_PACKET_SIZE))?)?,
|
||||
bitrate_kbps: narrow(a.required(BITRATE, 1, u64::from(MAX_BITRATE_KBPS))?)?,
|
||||
codec,
|
||||
min_fec_packets: narrow(a.required(MIN_FEC_PACKETS, 0, u64::from(u8::MAX))?)?,
|
||||
video_qos_traffic_type: narrow(a.required(VIDEO_QOS, 0, u64::from(u32::MAX))?)?,
|
||||
audio_packet_duration_ms: narrow(a.required(PACKET_DURATION, 1, u64::from(MAX_AUDIO_PACKET_DURATION_MS))?)?,
|
||||
audio_qos_traffic_type: narrow(a.required(AUDIO_QOS, 0, u64::from(u32::MAX))?)?,
|
||||
max_reference_frames: narrow(a.optional(MAX_REFERENCE_FRAMES, 1, 0, u64::from(u32::MAX))?)?,
|
||||
reference_frame_invalidation: a.optional(REF_PIC_INVALIDATION, 0, 0, 1)? == 1,
|
||||
dynamic_range_mode: narrow(a.optional(DYNAMIC_RANGE_MODE, 0, 0, u64::from(u32::MAX))?)?,
|
||||
encoder_csc_mode: narrow(a.optional(ENCODER_CSC_MODE, 0, 0, u64::from(u32::MAX))?)?,
|
||||
chroma: if a.optional(CHROMA_SAMPLING, 0, 0, 1)? == 1 {
|
||||
ChromaSampling::Yuv444
|
||||
} else {
|
||||
ChromaSampling::Yuv420
|
||||
},
|
||||
encryption: EncryptionFlags(narrow(a.optional(ENCRYPTION_ENABLED, 0, 0, u64::from(u8::MAX))?)?),
|
||||
surround: SurroundSettings {
|
||||
enabled: a.optional(SURROUND_ENABLE, 0, 0, 1)? == 1,
|
||||
channels: narrow(a.optional(SURROUND_CHANNELS, 2, 1, MAX_AUDIO_CHANNELS as u64)?)?,
|
||||
channel_mask: narrow(a.optional(SURROUND_MASK, 0x3, 0, u64::from(u32::MAX))?)?,
|
||||
high_quality: a.optional(AUDIO_QUALITY, 1, 0, 1)? == 1,
|
||||
},
|
||||
unknown_attributes: unknown,
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes `config` as an ANNOUNCE payload (`v=0`, then every known attribute, CRLF line ends) that
|
||||
/// [`parse_announce`] reads back as the same config (with `unknown_attributes` 0).
|
||||
#[must_use]
|
||||
pub fn write_announce(config: &StreamConfig) -> Vec<u8> {
|
||||
let codec: u8 = match config.codec {
|
||||
VideoCodec::H264 => 0,
|
||||
VideoCodec::Hevc => 1,
|
||||
VideoCodec::Av1 => 2,
|
||||
};
|
||||
let chroma: u8 = match config.chroma {
|
||||
ChromaSampling::Yuv420 => 0,
|
||||
ChromaSampling::Yuv444 => 1,
|
||||
};
|
||||
let s = &config.surround;
|
||||
let values: [(usize, u64); ATTRIBUTES.len()] = [
|
||||
(VIEWPORT_WD, u64::from(config.width)),
|
||||
(VIEWPORT_HT, u64::from(config.height)),
|
||||
(MAX_FPS_ATTR, u64::from(config.max_fps)),
|
||||
(PACKET_SIZE, u64::from(config.packet_size)),
|
||||
(BITRATE, u64::from(config.bitrate_kbps)),
|
||||
(BIT_STREAM_FORMAT, u64::from(codec)),
|
||||
(MIN_FEC_PACKETS, u64::from(config.min_fec_packets)),
|
||||
(VIDEO_QOS, u64::from(config.video_qos_traffic_type)),
|
||||
(PACKET_DURATION, u64::from(config.audio_packet_duration_ms)),
|
||||
(AUDIO_QOS, u64::from(config.audio_qos_traffic_type)),
|
||||
(MAX_REFERENCE_FRAMES, u64::from(config.max_reference_frames)),
|
||||
(REF_PIC_INVALIDATION, u64::from(config.reference_frame_invalidation)),
|
||||
(DYNAMIC_RANGE_MODE, u64::from(config.dynamic_range_mode)),
|
||||
(ENCODER_CSC_MODE, u64::from(config.encoder_csc_mode)),
|
||||
(CHROMA_SAMPLING, u64::from(chroma)),
|
||||
(ENCRYPTION_ENABLED, u64::from(config.encryption.0)),
|
||||
(SURROUND_ENABLE, u64::from(s.enabled)),
|
||||
(SURROUND_CHANNELS, u64::from(s.channels)),
|
||||
(SURROUND_MASK, u64::from(s.channel_mask)),
|
||||
(AUDIO_QUALITY, u64::from(s.high_quality)),
|
||||
];
|
||||
let mut out = String::with_capacity(1024);
|
||||
out.push_str("v=0\r\n");
|
||||
for (index, value) in values {
|
||||
if let Some(attribute) = ATTRIBUTES.get(index) {
|
||||
out.push_str("a=");
|
||||
out.push_str(attribute.name);
|
||||
out.push(':');
|
||||
out.push_str(&value.to_string());
|
||||
out.push_str("\r\n");
|
||||
}
|
||||
}
|
||||
out.into_bytes()
|
||||
}
|
||||
|
||||
/// One attribute the host reads (`docs/PROTOCOL.md` 2.4, 2.5).
|
||||
struct Attribute {
|
||||
/// The SDP attribute name.
|
||||
name: &'static str,
|
||||
/// The error text when a required attribute is missing; `None` for attributes with a default.
|
||||
missing: Option<&'static str>,
|
||||
}
|
||||
|
||||
const fn required(name: &'static str, missing: &'static str) -> Attribute {
|
||||
Attribute { name, missing: Some(missing) }
|
||||
}
|
||||
|
||||
const fn defaulted(name: &'static str) -> Attribute {
|
||||
Attribute { name, missing: None }
|
||||
}
|
||||
|
||||
const VIEWPORT_WD: usize = 0;
|
||||
const VIEWPORT_HT: usize = 1;
|
||||
const MAX_FPS_ATTR: usize = 2;
|
||||
const PACKET_SIZE: usize = 3;
|
||||
const BITRATE: usize = 4;
|
||||
const BIT_STREAM_FORMAT: usize = 5;
|
||||
const MIN_FEC_PACKETS: usize = 6;
|
||||
const VIDEO_QOS: usize = 7;
|
||||
const PACKET_DURATION: usize = 8;
|
||||
const AUDIO_QOS: usize = 9;
|
||||
const MAX_REFERENCE_FRAMES: usize = 10;
|
||||
const REF_PIC_INVALIDATION: usize = 11;
|
||||
const DYNAMIC_RANGE_MODE: usize = 12;
|
||||
const ENCODER_CSC_MODE: usize = 13;
|
||||
const CHROMA_SAMPLING: usize = 14;
|
||||
const ENCRYPTION_ENABLED: usize = 15;
|
||||
const SURROUND_ENABLE: usize = 16;
|
||||
const SURROUND_CHANNELS: usize = 17;
|
||||
const SURROUND_MASK: usize = 18;
|
||||
const AUDIO_QUALITY: usize = 19;
|
||||
|
||||
/// Every attribute read, in the order of the index constants above. The required set is the one a known host
|
||||
/// refuses to stream without (`docs/PROTOCOL.md` 2.5 \[M\]); the others have the defaults documented on
|
||||
/// [`StreamConfig`].
|
||||
const ATTRIBUTES: [Attribute; 20] = [
|
||||
required("x-nv-video[0].clientViewportWd", "announce: x-nv-video[0].clientViewportWd missing"),
|
||||
required("x-nv-video[0].clientViewportHt", "announce: x-nv-video[0].clientViewportHt missing"),
|
||||
required("x-nv-video[0].maxFPS", "announce: x-nv-video[0].maxFPS missing"),
|
||||
required("x-nv-video[0].packetSize", "announce: x-nv-video[0].packetSize missing"),
|
||||
required("x-ml-video.configuredBitrateKbps", "announce: x-ml-video.configuredBitrateKbps missing"),
|
||||
required("x-nv-vqos[0].bitStreamFormat", "announce: x-nv-vqos[0].bitStreamFormat missing"),
|
||||
required("x-nv-vqos[0].fec.minRequiredFecPackets", "announce: x-nv-vqos[0].fec.minRequiredFecPackets missing"),
|
||||
required("x-nv-vqos[0].qosTrafficType", "announce: x-nv-vqos[0].qosTrafficType missing"),
|
||||
required("x-nv-aqos.packetDuration", "announce: x-nv-aqos.packetDuration missing"),
|
||||
required("x-nv-aqos.qosTrafficType", "announce: x-nv-aqos.qosTrafficType missing"),
|
||||
defaulted("x-nv-video[0].maxNumReferenceFrames"),
|
||||
defaulted("x-nv-video[0].refPicInvalidation"),
|
||||
defaulted("x-nv-video[0].dynamicRangeMode"),
|
||||
defaulted("x-nv-video[0].encoderCscMode"),
|
||||
defaulted("x-ss-video[0].chromaSamplingType"),
|
||||
defaulted("x-ss-general.encryptionEnabled"),
|
||||
defaulted("x-nv-audio.surround.enable"),
|
||||
defaulted("x-nv-audio.surround.numChannels"),
|
||||
defaulted("x-nv-audio.surround.channelMask"),
|
||||
defaulted("x-nv-audio.surround.AudioQuality"),
|
||||
];
|
||||
|
||||
/// The values found, one slot per entry of [`ATTRIBUTES`].
|
||||
struct Values<'a, 'b>(&'a [Option<&'b str>; ATTRIBUTES.len()]);
|
||||
|
||||
impl Values<'_, '_> {
|
||||
/// The attribute's number in `lo..=hi`, or `default` when it is absent.
|
||||
fn optional(&self, index: usize, default: u64, lo: u64, hi: u64) -> Result<u64> {
|
||||
let name = ATTRIBUTES.get(index).map_or("announce attribute", |a| a.name);
|
||||
match self.0.get(index).copied().flatten() {
|
||||
None => Ok(default),
|
||||
Some(text) => {
|
||||
let value = parse_dec(name, text)?;
|
||||
if value < lo || value > hi {
|
||||
return Err(Error::UnexpectedValue { what: name, value });
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The attribute's number in `lo..=hi`; refused when absent.
|
||||
fn required(&self, index: usize, lo: u64, hi: u64) -> Result<u64> {
|
||||
if self.0.get(index).copied().flatten().is_none() {
|
||||
let what = ATTRIBUTES.get(index).and_then(|a| a.missing).unwrap_or("announce: attribute missing");
|
||||
return Err(malformed(what));
|
||||
}
|
||||
self.optional(index, 0, lo, hi)
|
||||
}
|
||||
}
|
||||
|
||||
/// A range-checked number into its field type (cannot fail after the range check; never panics either way).
|
||||
fn narrow<T: TryFrom<u64>>(value: u64) -> Result<T> {
|
||||
T::try_from(value).map_err(|_| Error::UnexpectedValue { what: "announce number", value })
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! The DESCRIBE answer (`docs/PROTOCOL.md` 2.3, 2.5): what the host offers, written as the SDP lines the client
|
||||
//! reads with [`crate::rtsp::HostCapabilities::from_sdp`].
|
||||
|
||||
use crate::rtsp::sdp::{EncryptionFlags, FeatureFlags, MAX_OPUS_CONFIGS, OpusConfig, parse_surround_params};
|
||||
use crate::util::{cap, malformed};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// The `sprop-parameter-sets` line a known host sends; its value is not used by clients (`docs/PROTOCOL.md` 2.3).
|
||||
const SPROP_LINE: &str = "sprop-parameter-sets=AAAAAU";
|
||||
|
||||
/// What the host offers: written into the DESCRIBE answer, and checked against the client's ANNOUNCE.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct HostOffer {
|
||||
/// `x-ss-general.featureFlags` (pen/touch, controller touch).
|
||||
pub feature_flags: FeatureFlags,
|
||||
/// `x-ss-general.encryptionSupported`.
|
||||
pub encryption_supported: EncryptionFlags,
|
||||
/// `x-nv-video[0].refPicInvalidation:1`: the host can invalidate reference frames.
|
||||
pub reference_frame_invalidation: bool,
|
||||
/// H.264: `a=fmtp:96 packetization-mode=1`.
|
||||
pub h264: bool,
|
||||
/// HEVC. No DESCRIBE line is known for it (a host advertises it in serverinfo, `docs/PROTOCOL.md` 1.2, U25);
|
||||
/// used only to check ANNOUNCE.
|
||||
pub hevc: bool,
|
||||
/// AV1: `a=rtpmap:98 AV1/90000`.
|
||||
pub av1: bool,
|
||||
/// HDR. No DESCRIBE line is known for it (serverinfo again); used only to check ANNOUNCE: without it, a
|
||||
/// `dynamicRangeMode` other than 0 (SDR \[M\]) is refused.
|
||||
pub hdr: bool,
|
||||
/// 4:4:4 chroma. No DESCRIBE line is known; used only to check ANNOUNCE.
|
||||
pub yuv444: bool,
|
||||
/// One `a=fmtp:97 surround-params=…` line each, in order (at most
|
||||
/// [`crate::rtsp::sdp::MAX_OPUS_CONFIGS`]). The mappings are written as given: whether a host must rotate the
|
||||
/// 5.1/7.1 normal-quality mappings is UNKNOWN U26.
|
||||
pub opus_configs: Vec<OpusConfig>,
|
||||
}
|
||||
|
||||
/// Builds the DESCRIBE payload for `offer`, in the line order a known host uses (`docs/PROTOCOL.md` 2.5 \[M\]):
|
||||
/// feature flags, encryption, `sprop-parameter-sets`, reference invalidation, AV1, H.264, then one
|
||||
/// `surround-params` line per Opus configuration. CRLF line ends.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::Malformed`] for an Opus configuration that the client's `surround-params` parser would refuse (more
|
||||
/// than 8 channels, a mapping entry or count above 9, a wrong mapping length, no streams, more coupled streams than
|
||||
/// streams); [`Error::TooLarge`] over [`crate::rtsp::sdp::MAX_OPUS_CONFIGS`]; [`Error::Unsupported`] when no codec
|
||||
/// is offered.
|
||||
pub fn build_describe(offer: &HostOffer) -> Result<Vec<u8>> {
|
||||
if !(offer.h264 || offer.hevc || offer.av1) {
|
||||
return Err(Error::Unsupported { what: "a video codec in the host offer" });
|
||||
}
|
||||
cap("describe opus configurations", MAX_OPUS_CONFIGS, offer.opus_configs.len())?;
|
||||
let mut out = String::with_capacity(256 + 48 * offer.opus_configs.len());
|
||||
let mut line = |text: &str| {
|
||||
out.push_str(text);
|
||||
out.push_str("\r\n");
|
||||
};
|
||||
line(&format!("a=x-ss-general.featureFlags:{}", offer.feature_flags.0));
|
||||
line(&format!("a=x-ss-general.encryptionSupported:{}", offer.encryption_supported.0));
|
||||
line(SPROP_LINE);
|
||||
if offer.reference_frame_invalidation {
|
||||
line("a=x-nv-video[0].refPicInvalidation:1");
|
||||
}
|
||||
if offer.av1 {
|
||||
line("a=rtpmap:98 AV1/90000");
|
||||
}
|
||||
if offer.h264 {
|
||||
line("a=fmtp:96 packetization-mode=1");
|
||||
}
|
||||
for config in &offer.opus_configs {
|
||||
line(&format!("a=fmtp:97 surround-params={}", surround_digits(config)?));
|
||||
}
|
||||
Ok(out.into_bytes())
|
||||
}
|
||||
|
||||
/// `surround-params` digits for `config` (`docs/PROTOCOL.md` 2.3): channel count, stream count, coupled count, then
|
||||
/// one mapping digit per channel. The client's own parser checks the result, so nothing it refuses is written.
|
||||
fn surround_digits(config: &OpusConfig) -> Result<String> {
|
||||
let mut digits = String::with_capacity(3 + config.mapping.len());
|
||||
for n in [config.channels, config.streams, config.coupled_streams].iter().chain(&config.mapping) {
|
||||
let d = char::from_digit(u32::from(*n), 10).ok_or(malformed("surround-params: a value above 9"))?;
|
||||
digits.push(d);
|
||||
}
|
||||
parse_surround_params(&digits)?;
|
||||
Ok(digits)
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
//! The host's RTSP session (`docs/PROTOCOL.md` 2.2, 2.5), the mirror of [`super::client`]: OPTIONS → DESCRIBE →
|
||||
//! SETUP audio, video and control (any order, each once) → ANNOUNCE → PLAY.
|
||||
//!
|
||||
//! The caller accepts TCP on the RTSP port, cuts each connection's bytes with [`super::RtspFramer::for_requests`],
|
||||
//! feeds every whole request to [`RtspServer::handle_request`], writes the [`ServerReply`] back, and reads
|
||||
//! [`ServerEvent`]s from [`RtspServer::poll_event`]. One [`RtspServer`] belongs to one launched session, not to one
|
||||
//! TCP connection: a client may open a connection per request (UNKNOWN U5, `docs/PROTOCOL.md` 2.5), so the caller
|
||||
//! routes every connection of that session to the same machine.
|
||||
//!
|
||||
//! Every request gets an answer. A request that is malformed, out of order or for another session gets an RTSP error
|
||||
//! status and leaves the state unchanged; [`ServerReply::error`] says why, and the caller decides whether to close the
|
||||
//! connection. Nothing here panics on any input.
|
||||
|
||||
mod announce;
|
||||
mod describe;
|
||||
|
||||
pub use announce::{
|
||||
ChromaSampling, MAX_ANNOUNCE_ATTRIBUTES, MAX_ANNOUNCE_BYTES, MAX_ANNOUNCE_LINE_BYTES, MAX_ANNOUNCE_LINES,
|
||||
MAX_AUDIO_PACKET_DURATION_MS, MAX_BITRATE_KBPS, MAX_DIMENSION, MAX_FPS, MAX_PACKET_SIZE, MIN_PACKET_SIZE,
|
||||
StreamConfig, SurroundSettings, parse_announce, write_announce,
|
||||
};
|
||||
pub use describe::{HostOffer, build_describe};
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use super::client::{StreamPorts, VideoCodec};
|
||||
use super::sdp::EncryptionFlags;
|
||||
use super::{MAX_RTSP_HEADERS, MAX_RTSP_MESSAGE_BYTES, Method, RtspRequest, RtspResponse, parse_request};
|
||||
use crate::util::{hex_encode, malformed, parse_u32};
|
||||
use crate::{Error, RandomSource, Result};
|
||||
|
||||
/// `timeout` of the `Session` header in SETUP answers, in seconds (`docs/PROTOCOL.md` 2.2 \[M\]).
|
||||
pub const DEFAULT_SESSION_TIMEOUT_SECS: u32 = 90;
|
||||
/// Random bytes in a session id (RFC 2326 section 3.4: at least eight octets, chosen at random); written as hex.
|
||||
pub const SESSION_ID_BYTES: usize = 8;
|
||||
|
||||
/// How the host answers.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ServerConfig {
|
||||
/// The UDP ports answered to SETUP audio, video and control (`Transport: server_port=<port>`).
|
||||
pub ports: StreamPorts,
|
||||
/// What DESCRIBE offers and ANNOUNCE is checked against.
|
||||
pub offer: HostOffer,
|
||||
/// Encryption the client must turn on in ANNOUNCE (Lumen: at least control V2); must be offered.
|
||||
pub required_encryption: EncryptionFlags,
|
||||
/// Refuse requests after the first SETUP that carry no `Session` header. Off by default: whether clients echo
|
||||
/// it is UNKNOWN U5, and a known host does not read it (`docs/PROTOCOL.md` 2.5). A `Session` that is present is
|
||||
/// always checked.
|
||||
pub require_session_header: bool,
|
||||
/// `timeout` in the `Session` header, seconds, 1.. ([`DEFAULT_SESSION_TIMEOUT_SECS`]).
|
||||
pub session_timeout_secs: u32,
|
||||
}
|
||||
|
||||
/// Which request the session expects next.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum RtspServerState {
|
||||
/// OPTIONS.
|
||||
Options,
|
||||
/// DESCRIBE.
|
||||
Describe,
|
||||
/// SETUP of the streams not set up yet.
|
||||
Setup,
|
||||
/// ANNOUNCE.
|
||||
Announce,
|
||||
/// PLAY.
|
||||
Play,
|
||||
/// PLAY answered: the streams start. Only OPTIONS is still answered with 200.
|
||||
Playing,
|
||||
}
|
||||
|
||||
/// What the session tells the caller.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ServerEvent {
|
||||
/// ANNOUNCE accepted: the stream settings the client asked for.
|
||||
Announced(StreamConfig),
|
||||
/// PLAY accepted: start the streams (video and audio wait for the client's PING, control for ENet).
|
||||
PlayRequested,
|
||||
}
|
||||
|
||||
/// The answer to one request.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ServerReply {
|
||||
/// The whole RTSP answer to write to the connection.
|
||||
pub bytes: Vec<u8>,
|
||||
/// Its status code (200, or 400, 451, 454, 455 or 501).
|
||||
pub status: u16,
|
||||
/// Why the request was refused; `None` with status 200.
|
||||
pub error: Option<Error>,
|
||||
}
|
||||
|
||||
/// The host side of one session's RTSP negotiation.
|
||||
#[derive(Debug)]
|
||||
pub struct RtspServer {
|
||||
config: ServerConfig,
|
||||
session_id: String,
|
||||
/// The DESCRIBE payload, built once from the offer.
|
||||
describe: Vec<u8>,
|
||||
state: RtspServerState,
|
||||
/// SETUP answered for audio, video, control.
|
||||
set_up: [bool; 3],
|
||||
/// A SETUP was answered, so the session id is known to the client.
|
||||
session_issued: bool,
|
||||
announced: Option<StreamConfig>,
|
||||
/// At most two events ever (one ANNOUNCE, one PLAY).
|
||||
events: VecDeque<ServerEvent>,
|
||||
}
|
||||
|
||||
/// `Public` in the OPTIONS answer (RFC 2326 section 10.1 example form).
|
||||
const PUBLIC: &str = "OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY";
|
||||
/// The streams of SETUP, in the order of `RtspServer::set_up` (`docs/PROTOCOL.md` 2.2).
|
||||
const STREAMS: [&str; 3] = ["audio", "video", "control"];
|
||||
|
||||
/// The CSeq, headers and payload of a 200 answer.
|
||||
type Answer = (u32, Vec<(String, String)>, Vec<u8>);
|
||||
|
||||
/// A refused request: the status, the CSeq to echo if one was readable, and why.
|
||||
struct Refusal {
|
||||
status: u16,
|
||||
cseq: Option<u32>,
|
||||
error: Error,
|
||||
}
|
||||
|
||||
impl RtspServer {
|
||||
/// Checks `config` and draws a fresh session id from `rng`.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::Malformed`] for a zero port or session timeout, or required encryption the offer lacks; any error
|
||||
/// of [`build_describe`] for the offer.
|
||||
pub fn new(config: ServerConfig, rng: &mut dyn RandomSource) -> Result<Self> {
|
||||
let p = config.ports;
|
||||
if p.audio == 0 || p.video == 0 || p.control == 0 {
|
||||
return Err(malformed("rtsp server: stream port 0"));
|
||||
}
|
||||
if config.session_timeout_secs == 0 {
|
||||
return Err(malformed("rtsp server: session timeout 0"));
|
||||
}
|
||||
if !config.offer.encryption_supported.contains(config.required_encryption.0) {
|
||||
return Err(malformed("rtsp server: required encryption is not offered"));
|
||||
}
|
||||
let describe = build_describe(&config.offer)?;
|
||||
let mut id = [0u8; SESSION_ID_BYTES];
|
||||
rng.fill(&mut id);
|
||||
Ok(Self {
|
||||
config,
|
||||
session_id: hex_encode(&id),
|
||||
describe,
|
||||
state: RtspServerState::Options,
|
||||
set_up: [false; 3],
|
||||
session_issued: false,
|
||||
announced: None,
|
||||
events: VecDeque::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Answers one whole request (see [`super::RtspFramer::for_requests`]). Never panics; a refusal leaves the
|
||||
/// state as it was.
|
||||
pub fn handle_request(&mut self, message: &[u8]) -> ServerReply {
|
||||
match self.answer(message) {
|
||||
Ok((cseq, headers, body)) => reply(200, Some(cseq), headers, body, None),
|
||||
Err(r) => reply(r.status, r.cseq, Vec::new(), Vec::new(), Some(r.error)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The headers and payload of a 200 answer, or why the request is refused.
|
||||
fn answer(&mut self, message: &[u8]) -> core::result::Result<Answer, Refusal> {
|
||||
let request = parse_request(message).map_err(|error| {
|
||||
let status = if matches!(error, Error::UnexpectedValue { what: "rtsp method", .. }) { 501 } else { 400 };
|
||||
Refusal { status, cseq: salvage_cseq(message), error }
|
||||
})?;
|
||||
let cseq = request_cseq(&request).map_err(|error| Refusal { status: 400, cseq: None, error })?;
|
||||
let refuse = |status: u16, error: Error| Refusal { status, cseq: Some(cseq), error };
|
||||
self.check_session(&request).map_err(|(status, error)| refuse(status, error))?;
|
||||
let mut headers = Vec::new();
|
||||
let mut body = Vec::new();
|
||||
match request.method {
|
||||
Method::Options => {
|
||||
// OPTIONS may come at any time and changes nothing else (RFC 2326 section 10.1).
|
||||
if self.state == RtspServerState::Options {
|
||||
self.state = RtspServerState::Describe;
|
||||
}
|
||||
headers.push(("Public".to_owned(), PUBLIC.to_owned()));
|
||||
}
|
||||
Method::Describe => {
|
||||
self.expect(RtspServerState::Describe, "DESCRIBE after OPTIONS").map_err(|e| refuse(455, e))?;
|
||||
headers.push(("Content-Type".to_owned(), "application/sdp".to_owned()));
|
||||
body.clone_from(&self.describe);
|
||||
self.state = RtspServerState::Setup;
|
||||
}
|
||||
Method::Setup => {
|
||||
self.expect(RtspServerState::Setup, "SETUP after DESCRIBE").map_err(|e| refuse(455, e))?;
|
||||
// A Transport header must be present; its value is not interpreted (`docs/PROTOCOL.md` 2.2 [M]).
|
||||
if request.header("Transport").is_none() {
|
||||
return Err(refuse(400, malformed("rtsp SETUP without Transport")));
|
||||
}
|
||||
let index = setup_stream(&request.target).map_err(|e| refuse(400, e))?;
|
||||
let port = self.port(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
|
||||
let slot = self.set_up.get_mut(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
|
||||
if *slot {
|
||||
return Err(refuse(455, Error::State { expected: "one SETUP per stream" }));
|
||||
}
|
||||
*slot = true;
|
||||
self.session_issued = true;
|
||||
if self.set_up.iter().all(|done| *done) {
|
||||
self.state = RtspServerState::Announce;
|
||||
}
|
||||
let session = format!("{};timeout = {}", self.session_id, self.config.session_timeout_secs);
|
||||
headers.push(("Session".to_owned(), session));
|
||||
headers.push(("Transport".to_owned(), format!("server_port={port}")));
|
||||
}
|
||||
Method::Announce => {
|
||||
self.expect(RtspServerState::Announce, "ANNOUNCE after the three SETUPs")
|
||||
.map_err(|e| refuse(455, e))?;
|
||||
let config = parse_announce(&request.body).map_err(|e| refuse(400, e))?;
|
||||
self.check_offer(&config).map_err(|e| refuse(451, e))?;
|
||||
self.events.push_back(ServerEvent::Announced(config.clone()));
|
||||
self.announced = Some(config);
|
||||
self.state = RtspServerState::Play;
|
||||
}
|
||||
Method::Play => {
|
||||
self.expect(RtspServerState::Play, "PLAY after ANNOUNCE").map_err(|e| refuse(455, e))?;
|
||||
self.events.push_back(ServerEvent::PlayRequested);
|
||||
self.state = RtspServerState::Playing;
|
||||
}
|
||||
}
|
||||
Ok((cseq, headers, body))
|
||||
}
|
||||
|
||||
fn expect(&self, state: RtspServerState, expected: &'static str) -> Result<()> {
|
||||
if self.state == state { Ok(()) } else { Err(Error::State { expected }) }
|
||||
}
|
||||
|
||||
/// The UDP port answered for stream `index` (audio, video, control).
|
||||
fn port(&self, index: usize) -> Option<u16> {
|
||||
let p = self.config.ports;
|
||||
[p.audio, p.video, p.control].get(index).copied()
|
||||
}
|
||||
|
||||
/// `Session` checks (`docs/PROTOCOL.md` 2.5): a present id must be the one issued in SETUP; a missing one is
|
||||
/// refused only when the config asks for it.
|
||||
fn check_session(&self, request: &RtspRequest) -> core::result::Result<(), (u16, Error)> {
|
||||
let mut ids = request
|
||||
.headers
|
||||
.iter()
|
||||
.filter(|(n, _)| n.eq_ignore_ascii_case("session"))
|
||||
.map(|(_, v)| v.split(';').next().unwrap_or("").trim_matches([' ', '\t']));
|
||||
let first = ids.next();
|
||||
if let Some(id) = first
|
||||
&& ids.any(|other| other != id)
|
||||
{
|
||||
return Err((400, malformed("rtsp: two different Session headers")));
|
||||
}
|
||||
match first {
|
||||
Some(id) if !self.session_issued || id != self.session_id => {
|
||||
Err((454, malformed("rtsp: Session is not this session's id")))
|
||||
}
|
||||
None if self.config.require_session_header && self.session_issued && request.method != Method::Options => {
|
||||
Err((454, malformed("rtsp: Session missing")))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What ANNOUNCE asks for must be in the offer.
|
||||
fn check_offer(&self, config: &StreamConfig) -> Result<()> {
|
||||
let offer = &self.config.offer;
|
||||
let codec_offered = match config.codec {
|
||||
VideoCodec::H264 => offer.h264,
|
||||
VideoCodec::Hevc => offer.hevc,
|
||||
VideoCodec::Av1 => offer.av1,
|
||||
};
|
||||
if !codec_offered {
|
||||
return Err(Error::Unsupported { what: "the requested video codec" });
|
||||
}
|
||||
if config.encryption.0 & !offer.encryption_supported.0 != 0 {
|
||||
return Err(Error::Unsupported { what: "encryption the host did not offer" });
|
||||
}
|
||||
if !config.encryption.contains(self.config.required_encryption.0) {
|
||||
return Err(Error::Unsupported { what: "a stream without the encryption the host requires" });
|
||||
}
|
||||
// 0 is SDR (`docs/PROTOCOL.md` 2.5 [M]); any other value is "not SDR", without a settled meaning (U6).
|
||||
if config.dynamic_range_mode != 0 && !offer.hdr {
|
||||
return Err(Error::Unsupported { what: "HDR" });
|
||||
}
|
||||
if config.chroma == ChromaSampling::Yuv444 && !offer.yuv444 {
|
||||
return Err(Error::Unsupported { what: "4:4:4 chroma" });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The next event, if any.
|
||||
pub fn poll_event(&mut self) -> Option<ServerEvent> {
|
||||
self.events.pop_front()
|
||||
}
|
||||
|
||||
/// Which request the session expects next.
|
||||
#[must_use]
|
||||
pub const fn state(&self) -> RtspServerState {
|
||||
self.state
|
||||
}
|
||||
|
||||
/// The session id sent in SETUP answers.
|
||||
#[must_use]
|
||||
pub fn session_id(&self) -> &str {
|
||||
&self.session_id
|
||||
}
|
||||
|
||||
/// The accepted ANNOUNCE, once there is one.
|
||||
#[must_use]
|
||||
pub const fn announced(&self) -> Option<&StreamConfig> {
|
||||
self.announced.as_ref()
|
||||
}
|
||||
|
||||
/// The configuration the session answers with.
|
||||
#[must_use]
|
||||
pub const fn config(&self) -> &ServerConfig {
|
||||
&self.config
|
||||
}
|
||||
}
|
||||
|
||||
/// The reason phrase of each status the session sends (RFC 2326 section 7.1.1).
|
||||
const fn reason(status: u16) -> &'static str {
|
||||
match status {
|
||||
200 => "OK",
|
||||
400 => "Bad Request",
|
||||
451 => "Parameter Not Understood",
|
||||
454 => "Session Not Found",
|
||||
455 => "Method Not Valid in This State",
|
||||
501 => "Not Implemented",
|
||||
_ => "Internal Server Error",
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the answer: `CSeq` first (when known), the given headers, then `Content-Length` (always, so the client's
|
||||
/// framer never has to wait for the connection to close, `docs/PROTOCOL.md` 2.1 U5).
|
||||
fn reply(
|
||||
status: u16,
|
||||
cseq: Option<u32>,
|
||||
extra: Vec<(String, String)>,
|
||||
body: Vec<u8>,
|
||||
error: Option<Error>,
|
||||
) -> ServerReply {
|
||||
let mut headers = Vec::with_capacity(extra.len() + 2);
|
||||
if let Some(c) = cseq {
|
||||
headers.push(("CSeq".to_owned(), c.to_string()));
|
||||
}
|
||||
headers.extend(extra);
|
||||
headers.push(("Content-Length".to_owned(), body.len().to_string()));
|
||||
match (RtspResponse { status, reason: reason(status).to_owned(), headers, body }).encode() {
|
||||
Ok(bytes) => ServerReply { bytes, status, error },
|
||||
// Only an answer over the message cap could fail, and none is that large; answer 500 rather than panic.
|
||||
Err(e) => ServerReply {
|
||||
bytes: b"RTSP/1.0 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n".to_vec(),
|
||||
status: 500,
|
||||
error: Some(e),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The request's CSeq: present, plain decimal `u32`, every copy equal.
|
||||
fn request_cseq(request: &RtspRequest) -> Result<u32> {
|
||||
let mut found = None;
|
||||
for (_, v) in request.headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case("cseq")) {
|
||||
let n = parse_u32("rtsp CSeq", v)?;
|
||||
if found.is_some_and(|f| f != n) {
|
||||
return Err(malformed("rtsp: two different CSeq values"));
|
||||
}
|
||||
found = Some(n);
|
||||
}
|
||||
found.ok_or(malformed("rtsp request without CSeq"))
|
||||
}
|
||||
|
||||
/// The CSeq of a request that did not parse, if a header line says it plainly, so the refusal can still echo it.
|
||||
/// Reads at most the header section, at most [`MAX_RTSP_HEADERS`] lines, and allocates nothing.
|
||||
fn salvage_cseq(message: &[u8]) -> Option<u32> {
|
||||
let head = message.get(..message.len().min(MAX_RTSP_MESSAGE_BYTES))?;
|
||||
for raw in head.split(|&b| b == b'\n').skip(1).take(MAX_RTSP_HEADERS) {
|
||||
let line = raw.strip_suffix(b"\r").unwrap_or(raw);
|
||||
if line.is_empty() {
|
||||
break;
|
||||
}
|
||||
let Ok(text) = core::str::from_utf8(line) else { continue };
|
||||
if let Some((name, value)) = text.split_once(':')
|
||||
&& name.eq_ignore_ascii_case("cseq")
|
||||
{
|
||||
return parse_u32("rtsp CSeq", value.trim_matches([' ', '\t'])).ok();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The stream a SETUP target names: exactly one `streamid=` followed by `audio`, `video` or `control`, ended by
|
||||
/// `/`, `?`, `&`, `;` or the end (`docs/PROTOCOL.md` 2.2 \[M\], 2.5). Index into [`STREAMS`].
|
||||
fn setup_stream(target: &str) -> Result<usize> {
|
||||
let mut parts = target.split("streamid=");
|
||||
parts.next();
|
||||
let after = parts.next().ok_or(malformed("rtsp SETUP target without streamid"))?;
|
||||
if parts.next().is_some() {
|
||||
return Err(malformed("rtsp SETUP target with two streamid"));
|
||||
}
|
||||
let name = after.split(['/', '?', '&', ';']).next().unwrap_or("");
|
||||
STREAMS.iter().position(|s| *s == name).ok_or(malformed("rtsp SETUP streamid"))
|
||||
}
|
||||
@@ -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<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>)")
|
||||
|
||||
@@ -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<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
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,15 @@ fn lying_inputs() -> Vec<Case> {
|
||||
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|
||||
|b| common::implemented(&domistream::rtsp::parse_request(b)),
|
||||
));
|
||||
v.push((
|
||||
"rtsp server",
|
||||
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|
||||
rtsp_server_answers,
|
||||
));
|
||||
// ANNOUNCE: a number far past any range, then more unknown attributes than the cap allows.
|
||||
let mut announce = b"a=x-nv-video[0].clientViewportWd:99999999999999999999999999999999\n".to_vec();
|
||||
announce.extend_from_slice(&b"a=u:1\n".repeat(600));
|
||||
v.push(("announce", announce, |b| common::implemented(&domistream::rtsp::server::parse_announce(b))));
|
||||
v.push(("rtsp framer", rtsp, |b| {
|
||||
let mut f = domistream::rtsp::RtspFramer::new();
|
||||
let pushed = f.push(b);
|
||||
@@ -129,6 +138,29 @@ fn lying_inputs() -> Vec<Case> {
|
||||
v
|
||||
}
|
||||
|
||||
/// A fresh host RTSP session answers `b`; false only for an `Unimplemented` answer.
|
||||
fn rtsp_server_answers(b: &[u8]) -> bool {
|
||||
let config = domistream::rtsp::ServerConfig {
|
||||
ports: domistream::rtsp::StreamPorts { audio: 48000, video: 47998, control: 47999 },
|
||||
offer: domistream::rtsp::HostOffer {
|
||||
feature_flags: domistream::rtsp::sdp::FeatureFlags(3),
|
||||
encryption_supported: domistream::rtsp::EncryptionFlags(7),
|
||||
reference_frame_invalidation: true,
|
||||
h264: true,
|
||||
hevc: true,
|
||||
av1: true,
|
||||
hdr: false,
|
||||
yuv444: false,
|
||||
opus_configs: vec![domistream::rtsp::OpusConfig::stereo()],
|
||||
},
|
||||
required_encryption: domistream::rtsp::EncryptionFlags(1),
|
||||
require_session_header: false,
|
||||
session_timeout_secs: 90,
|
||||
};
|
||||
let Ok(mut s) = domistream::rtsp::RtspServer::new(config, &mut common::SeqRng::new(3)) else { return false };
|
||||
s.handle_request(b).error != Some(domistream::Error::Unimplemented)
|
||||
}
|
||||
|
||||
/// Stateful receivers: the bound is their caps (frames or blocks in flight), never a claimed size.
|
||||
fn depacketizer_checks() {
|
||||
use domistream::video::{MAX_FRAME_BYTES, MAX_FRAMES_IN_FLIGHT, VideoConfig, VideoDepacketizer};
|
||||
@@ -225,6 +257,8 @@ fn parsers_never_allocate_past_their_caps() {
|
||||
("rtsp response", |b| common::implemented(&domistream::rtsp::parse_response(b))),
|
||||
("rtsp request", |b| common::implemented(&domistream::rtsp::parse_request(b))),
|
||||
("sdp", |b| common::implemented(&domistream::rtsp::sdp::parse_sdp(b))),
|
||||
("announce", |b| common::implemented(&domistream::rtsp::server::parse_announce(b))),
|
||||
("rtsp server", rtsp_server_answers),
|
||||
("enet", |b| common::implemented(&domistream::enet::protocol::parse_datagram(b))),
|
||||
("control frame", |b| common::implemented(&domistream::control::parse_encrypted_frame(b))),
|
||||
("control message", |b| common::implemented(&domistream::control::parse_host_message(b))),
|
||||
|
||||
@@ -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<u8>]) -> Vec<AudioEvent> {
|
||||
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<u8> {
|
||||
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<u8>], duration: u8) -> (Vec<Vec<u8>>, Vec<AudioEvent>) {
|
||||
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<Vec<u8>> = (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<Vec<u8>> = (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<Vec<u8>> = (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::<u64>(),
|
||||
first_sequence in any::<u16>(),
|
||||
first_ts in any::<u32>(),
|
||||
duration in 1u8..=40,
|
||||
count in 1usize..80,
|
||||
encrypt in any::<bool>(),
|
||||
) {
|
||||
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<Vec<u8>> = (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);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<u8> {
|
||||
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<u8>,
|
||||
datagrams: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
fn send_bytes(tx: &mut VideoPacketizer, rng: &mut SeqRng, index: u32, bitstream: Vec<u8>) -> 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<u8> {
|
||||
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<u8, (Vec<usize>, usize)> {
|
||||
let mut out: BTreeMap<u8, (Vec<usize>, 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<Vec<u8>> {
|
||||
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<VideoFrame>,
|
||||
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<u8>]) -> 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::<Vec<_>>(),
|
||||
want.iter().map(|s| s.index).collect::<Vec<_>>(),
|
||||
"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<usize> {
|
||||
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<u8> = (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::<usize>(), 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<Sent> = 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<Vec<u8>> = 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<Sent> = 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<Sent> = (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<Sent> = (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<Sent> = 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<Vec<u8>> = pair.iter().flat_map(|s| s.datagrams.clone()).collect();
|
||||
let dups: Vec<Vec<u8>> =
|
||||
(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<Vec<u8>> = 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<Vec<u8>> = positions[..k].iter().map(|&i| s.datagrams[i].clone()).collect();
|
||||
let matrix: Vec<u8> = (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<Vec<u8>> = [&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::<u64>(),
|
||||
packet_size in 17u16..1500,
|
||||
pct in any::<u8>(),
|
||||
min in 0u8..8,
|
||||
frames in 1usize..6,
|
||||
encrypt in any::<bool>(),
|
||||
) {
|
||||
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<Sent> = (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));
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,8 @@ copied into DomiStream, and settled by our own measurement instead. Known cases:
|
||||
| `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it |
|
||||
| fec-rs `src/reed_solomon.rs` tests (`test_partial_eq_reflects_parity_matrix_changes`) | the same audio parity matrix as Moonshine's encoder | Not taken, same rule. Seen while reading fec-rs on 2026-11-25. |
|
||||
| `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source |
|
||||
| `src/rtsp.rs` (read again as S-30) | `encoderCscMode` bit layout (comment cites Sunshine's colour-space function); `maxNumReferenceFrames` 0 = "host's choice" (comment cites moonlight-common-c); the 5.1/7.1 mapping rotation (comment cites GFE and Moonlight) | Not taken: the host parser keeps both numbers raw and writes the mappings as configured (PROTOCOL.md 2.5, U6, U26) |
|
||||
| `src/session/stream/video/mod.rs` (S-31) | how the stored bitrate is reduced for FEC and audio (comment: "as Sunshine computes it") | Not taken; the parser hands over the client's bitrate unchanged |
|
||||
|
||||
## How code gets written
|
||||
|
||||
@@ -91,3 +93,6 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea
|
||||
| S-23 | 2026-12-04 | NVIDIA [video-sdk-samples](https://github.com/NVIDIA/video-sdk-samples) at `aa3544d`: `Samples/NvCodec/NvEncoder/nvEncodeAPI.h` (API 8.1, sha256 `4d061c34…6042a`); NVIDIA [VideoProcessingFramework](https://github.com/NVIDIA/VideoProcessingFramework) at `e82364f`: `src/TC/third_party/nvEncodeAPI.h` (API 12.0, sha256 `067c5159…b4ad`); GitHub repository metadata of both | Both headers carry NVIDIA's MIT notice for the header file; the repositories are Apache-2.0 / unlicensed samples and the second is archived. Declarations used for the L0 spike shim (struct versions, preset and tuning enums, `NvEncGetEncodePresetConfigEx`, resource registration). No sample `.cpp` file was opened. |
|
||||
| S-24 | 2026-12-04 | [NVENC Video Encoder API Programming Guide](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvenc-video-encoder-api-prog-guide/index.html) (SDK 13.0) | Loading `nvEncodeAPI` at run time and `NvEncodeAPICreateInstance`; `NV_ENC_DEVICE_TYPE_DIRECTX` sessions; registering, mapping and unmapping D3D11 textures; tuning info (low latency, ultra low latency), presets P1-P7, CBR filler, forcing IDR, `NvEncInvalidateRefFrames`, intra refresh, look-ahead latency; lock/unlock of the bitstream; async mode only on Windows 10+ WDDM, recommended there; Main10 settings. |
|
||||
| S-25 | 2026-12-04 | Licences via the GitHub and crates.io APIs and `COPYING` files: nefarius/ViGEmClient (MIT, archived), nefarius/ViGEmBus (BSD-3-Clause, archived), xiph/opus `COPYING` (BSD-style), crates `opus`, `audiopus_sys`, `vigem-client`, `nvidia-video-codec-sdk`, `nvenc`, `windows` | Licence and status only; no source files of these projects were opened. |
|
||||
| S-30 | 2026-12-04 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e3693e09c3a6ab1025bde6cdb67f36a6bc` (same pin as S-9): `src/rtsp.rs` again, read for the host side | BSD-2, facts only. One request per TCP connection, the note that Moonlight opens a connection per request; `CSeq` required (connection closed without it); no method order and no `Session` check; statuses 200/400/500 only; OPTIONS `Public`; SETUP needs `Transport` (400 without), stream from the first `streamid=` query segment, answer `Session: MoonshineSession;timeout = 90` and `Transport: server_port=<port>`; DESCRIBE line order and values (`featureFlags:3`, `encryptionSupported` 5 or 7, `sprop-parameter-sets=AAAAAU`, invalidation, AV1, H.264, surround lines); ANNOUNCE: the ten required attributes (400 when missing), the defaults of the optional ones (`maxNumReferenceFrames` 1, `dynamicRangeMode`/`chromaSamplingType`/`encoderCscMode`/`encryptionEnabled`/`surround.enable` 0, `numChannels` 2, `channelMask` 0x3, `AudioQuality` 1), `maxFPS` 0 refused, bitrate ×1000 must fit a u32, QoS off for `0`. The comments citing Sunshine, moonlight-common-c or GFE are logged as second-hand GPL facts above and not used. |
|
||||
| S-31 | 2026-12-04 | Moonshine at `f184d5e`: `src/session/stream/mod.rs`, `src/session/stream/video/mod.rs`; the repository tree listing (GitHub API) | BSD-2, facts only. `bitStreamFormat` 0 H.264 (default), 1 HEVC, 2 AV1, others invalid; dynamic range 0 SDR (default), 1 HDR; chroma 0 4:2:0 (default), 1 4:4:4; valid video packet size 200..=65471 (one stream packet in an IPv6 UDP datagram), below 200 refused; FEC default 20 %. The bitrate comment citing Sunshine is logged above and not used. |
|
||||
| S-32 | 2026-12-04 | [Wolf: RTSP](https://games-on-whales.github.io/wolf/stable/protocols/rtsp.html) again (as S-3); [RFC 2326](https://www.rfc-editor.org/rfc/rfc2326.txt) | Wolf: nothing new for the host (no per-method answers, no ANNOUNCE list). RFC 2326: reason phrases of 400, 451, 454, 455, 501 (7.1.1); a missing `Content-Length` means zero (4.4); OPTIONS may be sent at any time (10.1); session ids at least 8 random octets (3.4); `Public` as a comma-separated list (10.1 example). |
|
||||
|
||||
@@ -221,6 +221,76 @@ SDP attribute lines `a=<name>:<value>`. Names the host reads [M]; values and the
|
||||
|
||||
Settle U6: lab capture of an ANNOUNCE accepted by Sunshine, then vary one attribute at a time.
|
||||
|
||||
### 2.5 Host side (Lumen): `rtsp::server`
|
||||
|
||||
Facts from Moonshine's host code (`src/rtsp.rs`, `src/session/stream/video/mod.rs` at `f184d5e`, S-30, S-31) and
|
||||
RFC 2326 (S-32); our own choices are marked as such.
|
||||
|
||||
**Connections and framing.** Moonshine reads one request per TCP connection and notes that Moonlight opens a
|
||||
connection per request [M]. So the host's state belongs to the launched session, not to a connection: every
|
||||
connection of that session feeds the same `RtspServer` (UNKNOWN U5 for other clients). A request without
|
||||
`Content-Length` has no payload (RFC 2326 4.4); the host's framer (`RtspFramer::for_requests`) ends it at the empty
|
||||
line. Every answer carries `Content-Length` (ours), so the client never waits for a close. Moonshine needs a parseable
|
||||
`CSeq` and closes without an answer when it is missing [M]; we answer 400 and let the caller close.
|
||||
|
||||
**Order and statuses.** Moonshine checks no order and no `Session` [M]. We enforce 2.2: OPTIONS, DESCRIBE, the three
|
||||
SETUPs (any order, each once: ours, U5), ANNOUNCE, PLAY. OPTIONS may come at any time and changes nothing else
|
||||
(RFC 2326 10.1). Moonshine answers only 200, 400 and 500 [M]; we use the RFC 2326 7.1.1 codes: 400 malformed request
|
||||
or ANNOUNCE payload, 451 a request the offer does not cover (codec, encryption bits, HDR, 4:4:4), 454 a `Session`
|
||||
that is not this session's, 455 a method out of order, 501 an unknown method (TEARDOWN, GET_PARAMETER...). A refused
|
||||
request changes no state; the caller decides whether to close.
|
||||
|
||||
**Session.** Moonshine sends the fixed id `MoonshineSession` and never reads it back [M]. We send a random id
|
||||
(8 bytes from the caller's `RandomSource`, hex; RFC 2326 3.4 asks for at least 8 random octets) as
|
||||
`Session: <id>;timeout = 90` [M]. A `Session` header that is present must carry that id (454 otherwise, and before
|
||||
the first SETUP any id is wrong); a missing one is accepted unless the host config requires it (U5).
|
||||
|
||||
**Answers** [M]: OPTIONS `Public` (we list `OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY`; Moonshine leaves ANNOUNCE
|
||||
out); DESCRIBE the SDP below; SETUP needs a `Transport` header (400 without), takes the stream from the first
|
||||
`streamid=<audio|video|control>` of the target (400 otherwise) and answers `Session` and
|
||||
`Transport: server_port=<port>`; ANNOUNCE and PLAY answer with no payload.
|
||||
|
||||
**DESCRIBE lines, in Moonshine's order** [M]: `a=x-ss-general.featureFlags:3`, `a=x-ss-general.encryptionSupported:`
|
||||
5 or 7 (7 when video encryption is on), `sprop-parameter-sets=AAAAAU`, `a=x-nv-video[0].refPicInvalidation:1`,
|
||||
`a=rtpmap:98 AV1/90000`, `a=fmtp:96 packetization-mode=1`, then one `a=fmtp:97 surround-params=` per Opus
|
||||
configuration. Moonshine writes all of them unconditionally; our writer leaves out the invalidation, AV1 and H.264
|
||||
lines when the host does not offer them. HEVC, HDR and 4:4:4 have no DESCRIBE line (serverinfo, 1.2, U25). Moonshine
|
||||
rotates the 5.1/7.1 normal-quality mappings with a comment that cites GFE and Moonlight [M*]: not used, U26.
|
||||
|
||||
**ANNOUNCE as Moonshine reads it.** Missing or unparseable required attributes give 400 [M]; optional ones fall back
|
||||
to their default [M]. Our parser keeps the required set and the defaults, refuses out-of-range values instead of
|
||||
clamping, refuses a known attribute given twice, and counts unknown attributes.
|
||||
|
||||
| Attribute | Required? | Default | Accepted (ours unless tagged) | Meaning |
|
||||
| :-- | :-- | :-- | :-- | :-- |
|
||||
| `x-nv-video[0].clientViewportWd`, `…Ht` | yes [M] | | 1..=16384 | resolution |
|
||||
| `x-nv-video[0].maxFPS` | yes [M] | | 1..=1000 (0 refused [M]) | frame rate |
|
||||
| `x-nv-video[0].packetSize` | yes [M] | | 200..=65471 [M] (Moonshine clamps above its own cap; we refuse) | video packet size |
|
||||
| `x-ml-video.configuredBitrateKbps` | yes [M] | | 1..=4294967 (×1000 must fit a u32 [M]) | bitrate |
|
||||
| `x-nv-vqos[0].bitStreamFormat` | yes [M] | | 0 H.264, 1 HEVC, 2 AV1 [M]; others refused [M] | codec |
|
||||
| `x-nv-vqos[0].fec.minRequiredFecPackets` | yes [M] | | 0..=255 | minimum parity per block |
|
||||
| `x-nv-vqos[0].qosTrafficType`, `x-nv-aqos.qosTrafficType` | yes [M] | | any u32, kept raw (Moonshine: QoS off for `0` [M]) | DSCP class |
|
||||
| `x-nv-aqos.packetDuration` | yes [M] | | 1..=120 ms (longest Opus packet, RFC 6716) | audio packet duration |
|
||||
| `x-nv-video[0].maxNumReferenceFrames` | no | 1 [M] | any u32, raw (what 0 means is [M*]) | reference frames |
|
||||
| `x-nv-video[0].refPicInvalidation` | no (Moonshine does not read it) | 0: UNKNOWN U6 | 0, 1 | client can invalidate |
|
||||
| `x-nv-video[0].dynamicRangeMode` | no | 0 [M] | any u32, raw; Moonshine: 0 SDR, 1 HDR [M]; a non-zero value needs the host's HDR offer (ours) | U6 |
|
||||
| `x-nv-video[0].encoderCscMode` | no | 0 [M] | any u32, raw; the bit layout is [M*] (Moonshine cites Sunshine) | U6 |
|
||||
| `x-ss-video[0].chromaSamplingType` | no | 0 [M] | 0 4:2:0, 1 4:4:4 [M] | chroma |
|
||||
| `x-ss-general.encryptionEnabled` | no | 0 [M] | 0..=255, only offered bits (ours) | 2.3 bits |
|
||||
| `x-nv-audio.surround.enable` | no | 0 [M] | 0, 1 | when 0, the layout comes from launch's `surroundAudioInfo` [M] |
|
||||
| `x-nv-audio.surround.numChannels` | no | 2 [M] | 1..=8 | channels |
|
||||
| `x-nv-audio.surround.channelMask` | no | 0x3 [M] | any u32, raw | speaker mask |
|
||||
| `x-nv-audio.surround.AudioQuality` | no | 1 [M] | 0, 1 | high quality |
|
||||
|
||||
`bitStreamFormat` 0/1/2 [M] confirms the values our client sends (`rtsp::sdp`, previously a judgment). Payload caps
|
||||
(ours): 32 KiB, 1024 non-empty lines, 1024 bytes per line, 512 `a=` attributes; blanks around values are trimmed.
|
||||
|
||||
UNKNOWNs left for black-box measurement (Arena Domi Remote and the Moonlight PC app as Lumen's clients, decision D2):
|
||||
U5 (connection per request, the SETUP target form, whether clients echo `Session`, whether every client starts with
|
||||
OPTIONS), U6 (whether real clients always send the ten required attributes, `refPicInvalidation`'s default, the
|
||||
meanings of `dynamicRangeMode` and `encoderCscMode` per client setting, whether `qosTrafficType` is always a number,
|
||||
how many attributes a real ANNOUNCE has), U26 (mapping rotation).
|
||||
|
||||
---
|
||||
|
||||
## 3. Control channel (ENet + AES-GCM)
|
||||
@@ -468,6 +538,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 +602,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
|
||||
|
||||
@@ -211,3 +211,24 @@ 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
|
||||
|
||||
[[bin]]
|
||||
name = "rtsp_server"
|
||||
path = "fuzz_targets/rtsp_server.rs"
|
||||
test = false
|
||||
doc = false
|
||||
bench = false
|
||||
|
||||
[[bin]]
|
||||
name = "announce"
|
||||
path = "fuzz_targets/announce.rs"
|
||||
test = false
|
||||
doc = false
|
||||
bench = false
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Fuzzes the host's ANNOUNCE parser (hostile client SDP).
|
||||
//! Asserts invariants, not only "no panic": an accepted payload is within every range and cap, and writing it back
|
||||
//! gives the same config.
|
||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
use domistream::rtsp::server::{
|
||||
MAX_ANNOUNCE_ATTRIBUTES, MAX_AUDIO_PACKET_DURATION_MS, MAX_BITRATE_KBPS, MAX_DIMENSION, MAX_FPS, MAX_PACKET_SIZE,
|
||||
MIN_PACKET_SIZE, StreamConfig, parse_announce, write_announce,
|
||||
};
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
let Ok(c) = parse_announce(data) else { return };
|
||||
assert!((1..=MAX_DIMENSION).contains(&c.width) && (1..=MAX_DIMENSION).contains(&c.height));
|
||||
assert!((1..=MAX_FPS).contains(&c.max_fps));
|
||||
assert!((MIN_PACKET_SIZE..=MAX_PACKET_SIZE).contains(&c.packet_size));
|
||||
assert!((1..=MAX_BITRATE_KBPS).contains(&c.bitrate_kbps));
|
||||
assert!((1..=MAX_AUDIO_PACKET_DURATION_MS).contains(&c.audio_packet_duration_ms));
|
||||
assert!((1..=8).contains(&c.surround.channels));
|
||||
assert!(c.unknown_attributes as usize <= MAX_ANNOUNCE_ATTRIBUTES);
|
||||
let again = parse_announce(&write_announce(&c)).expect("what was accepted writes back");
|
||||
assert_eq!(again, StreamConfig { unknown_attributes: 0, ..c });
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Fuzzes the host's RTSP session with arbitrary requests, optionally after a valid prefix of the negotiation so the
|
||||
//! later states are reached too.
|
||||
//! Asserts invariants, not only "no panic": every answer parses with a documented status, 200 exactly when nothing
|
||||
//! was refused, the state only moves forward and never on a refusal, and the events come once each, in order.
|
||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
use domistream::RandomSource;
|
||||
use domistream::rtsp::client::VideoCodec;
|
||||
use domistream::rtsp::sdp::FeatureFlags;
|
||||
use domistream::rtsp::server::{ChromaSampling, StreamConfig, SurroundSettings, parse_announce, write_announce};
|
||||
use domistream::rtsp::{
|
||||
EncryptionFlags, HostOffer, OpusConfig, RtspFramer, RtspServer, RtspServerState, ServerConfig, ServerEvent,
|
||||
StreamPorts, parse_response,
|
||||
};
|
||||
|
||||
struct Fixed(u8);
|
||||
|
||||
impl RandomSource for Fixed {
|
||||
fn fill(&mut self, dest: &mut [u8]) {
|
||||
dest.fill(self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn rank(s: RtspServerState) -> u8 {
|
||||
match s {
|
||||
RtspServerState::Options => 0,
|
||||
RtspServerState::Describe => 1,
|
||||
RtspServerState::Setup => 2,
|
||||
RtspServerState::Announce => 3,
|
||||
RtspServerState::Play => 4,
|
||||
RtspServerState::Playing => 5,
|
||||
}
|
||||
}
|
||||
|
||||
fn announce() -> StreamConfig {
|
||||
StreamConfig {
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
max_fps: 60,
|
||||
packet_size: 1024,
|
||||
bitrate_kbps: 20_000,
|
||||
codec: VideoCodec::Hevc,
|
||||
min_fec_packets: 2,
|
||||
video_qos_traffic_type: 5,
|
||||
audio_packet_duration_ms: 5,
|
||||
audio_qos_traffic_type: 4,
|
||||
max_reference_frames: 0,
|
||||
reference_frame_invalidation: true,
|
||||
dynamic_range_mode: 0,
|
||||
encoder_csc_mode: 0,
|
||||
chroma: ChromaSampling::Yuv420,
|
||||
encryption: EncryptionFlags(7),
|
||||
surround: SurroundSettings::default(),
|
||||
unknown_attributes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The valid negotiation, one request each.
|
||||
fn prelude(session: &str) -> Vec<Vec<u8>> {
|
||||
let body = write_announce(&announce());
|
||||
let mut v = vec![
|
||||
b"OPTIONS rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 1\r\n\r\n".to_vec(),
|
||||
b"DESCRIBE rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 2\r\n\r\n".to_vec(),
|
||||
];
|
||||
for (i, s) in ["audio", "video", "control"].iter().enumerate() {
|
||||
v.push(
|
||||
format!("SETUP streamid={s}/0/0 RTSP/1.0\r\nCSeq: {}\r\nSession: {session}\r\nTransport: x\r\n\r\n", i + 3)
|
||||
.into_bytes(),
|
||||
);
|
||||
}
|
||||
let mut a = format!("ANNOUNCE streamid=control/13/0 RTSP/1.0\r\nCSeq: 6\r\nContent-Length: {}\r\n\r\n", body.len())
|
||||
.into_bytes();
|
||||
a.extend_from_slice(&body);
|
||||
v.push(a);
|
||||
v.push(b"PLAY rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 7\r\n\r\n".to_vec());
|
||||
// The first SETUP carries no session: none was issued yet.
|
||||
if let Some(first) = v.get_mut(2) {
|
||||
*first = b"SETUP streamid=audio/0/0 RTSP/1.0\r\nCSeq: 3\r\nTransport: x\r\n\r\n".to_vec();
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
struct Checker {
|
||||
announced: u32,
|
||||
played: u32,
|
||||
}
|
||||
|
||||
impl Checker {
|
||||
fn feed(&mut self, s: &mut RtspServer, message: &[u8]) {
|
||||
let before = s.state();
|
||||
let reply = s.handle_request(message);
|
||||
let r = parse_response(&reply.bytes).expect("every answer parses");
|
||||
assert_eq!(r.status, reply.status);
|
||||
assert!([200, 400, 451, 454, 455, 501].contains(&reply.status), "status {}", reply.status);
|
||||
assert_eq!(reply.status == 200, reply.error.is_none());
|
||||
assert!(rank(s.state()) >= rank(before), "state went back");
|
||||
if reply.status != 200 {
|
||||
assert_eq!(s.state(), before, "a refusal changed the state");
|
||||
}
|
||||
while let Some(e) = s.poll_event() {
|
||||
match e {
|
||||
ServerEvent::Announced(c) => {
|
||||
assert_eq!(self.announced, 0);
|
||||
self.announced += 1;
|
||||
let again = parse_announce(&write_announce(&c)).expect("an accepted ANNOUNCE writes back");
|
||||
assert_eq!(again, StreamConfig { unknown_attributes: 0, ..c });
|
||||
}
|
||||
ServerEvent::PlayRequested => {
|
||||
assert_eq!((self.announced, self.played), (1, 0));
|
||||
self.played += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(self.played == 1, s.state() == RtspServerState::Playing);
|
||||
}
|
||||
}
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
let Some((&mode, rest)) = data.split_first() else { return };
|
||||
let config = ServerConfig {
|
||||
ports: StreamPorts { audio: 48000, video: 47998, control: 47999 },
|
||||
offer: HostOffer {
|
||||
feature_flags: FeatureFlags(3),
|
||||
encryption_supported: EncryptionFlags(7),
|
||||
reference_frame_invalidation: true,
|
||||
h264: true,
|
||||
hevc: true,
|
||||
av1: mode & 0x40 != 0,
|
||||
hdr: mode & 0x80 != 0,
|
||||
yuv444: false,
|
||||
opus_configs: vec![OpusConfig::stereo()],
|
||||
},
|
||||
required_encryption: EncryptionFlags(1),
|
||||
require_session_header: mode & 0x20 != 0,
|
||||
session_timeout_secs: 90,
|
||||
};
|
||||
let mut s = RtspServer::new(config, &mut Fixed(mode)).expect("a valid config");
|
||||
let mut check = Checker { announced: 0, played: 0 };
|
||||
let session = s.session_id().to_string();
|
||||
// Bits 2..=4: how many valid requests come first (0..=7).
|
||||
for m in prelude(&session).iter().take(usize::from((mode >> 2) & 0x07)) {
|
||||
check.feed(&mut s, m);
|
||||
}
|
||||
if mode & 0x01 == 0 {
|
||||
// Messages separated by NUL bytes, each fed whole.
|
||||
for m in rest.split(|b| *b == 0).take(32) {
|
||||
check.feed(&mut s, m);
|
||||
}
|
||||
} else {
|
||||
// A byte stream through the request framer.
|
||||
let mut f = RtspFramer::for_requests();
|
||||
for chunk in rest.chunks(if mode & 0x02 == 0 { 7 } else { 512 }) {
|
||||
if f.push(chunk).is_err() {
|
||||
return;
|
||||
}
|
||||
loop {
|
||||
match f.next_message() {
|
||||
Ok(Some(m)) => check.feed(&mut s, &m),
|
||||
Ok(None) => break,
|
||||
Err(_) => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(Some(m)) = f.finish() {
|
||||
check.feed(&mut s, &m);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -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<u8, (Vec<usize>, 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);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user