Compare commits

...

16 Commits

Author SHA1 Message Date
mnovak fd4285aff0 [domistream] RTSP server: PROTOCOL.md 2.5 (host side, ANNOUNCE required/defaulted table), clean-room sources S-30 to S-32 2026-12-04 12:44:49 +01:00
mnovak a86a689b1f [domistream] RTSP server: session state machine, DESCRIBE writer, strict ANNOUNCE parser, response encoder and request framer; test fixes (escaped CRLF in alloc_caps, CSeq test state, clippy) 2026-12-04 12:44:49 +01:00
mnovak 27b7f2bf1d [fuzz] RTSP server: rtsp_server (session fed arbitrary requests after a valid prefix) and announce targets 2026-12-04 12:44:49 +01:00
mnovak 54bc9f5faf [domistream] RTSP server: tests first (in-memory client/server session, order, Session, ANNOUNCE parser, DESCRIBE writer, caps); API stubs return Unimplemented 2026-12-04 12:44:40 +01:00
mnovak 33b7b90b65 [repo] Merge: feature/host-packetizers (video and audio packetizers, PR #9) 2026-12-04 12:44:34 +01:00
mnovak 81ddf64bee [fuzz] video_packetizer_roundtrip: rustfmt 2026-12-04 12:28:25 +01:00
mnovak 7a6afed575 [fuzz] video_packetizer_roundtrip: arbitrary frames and parameters, packetize, lose up to m per block, depacketize equals input 2026-12-04 12:27:22 +01:00
mnovak 0d3a9a7917 [domistream] Audio packetizer: RTP datagram per Opus packet, AES-128-CBC (AudioCipher::encrypt), no parity until U16; first sequence must start a block 2026-12-04 12:24:45 +01:00
mnovak b62443ef28 [domistream] Video packetizer: frame header, FEC blocks with Cauchy parity over whole packets, sequence numbers, optional AES-GCM sealing (VideoCipher::encrypt) 2026-12-04 12:24:40 +01:00
mnovak e1abd7d060 [domistream] Audio packetizer: tests first (round trips through AudioDepacketizer, wrap-around, caps, fixed vectors), API stubs 2026-12-04 12:20:55 +01:00
mnovak 7983833ba6 [domistream] Video packetizer: tests first (round trips through VideoDepacketizer, loss up to and beyond m, fixed vectors), API stubs 2026-12-04 12:20:55 +01:00
mnovak 514565dbd7 [repo] Merge: docs/lumen-l0 (Lumen L0 results, PR #8) 2026-12-04 12:08:00 +01:00
mnovak 284bf7cc17 [repo] Docs: Lumen L0 results (licences, FP16 capture, NVENC API 12.0, timings); S-23 to S-25 2026-12-04 12:07:53 +01:00
mnovak e4fdca794b [repo] Merge: docs/lumen-decisions (Lumen decisions D1-D6 and the iOS phase, PR #7) 2026-12-04 11:55:55 +01:00
mnovak 73deb851ae [repo] Docs: Lumen decisions D1-D6 (Mark, 2026-12-04), iOS as a later client phase, OBS/FFmpeg forbidden for host work 2026-12-04 11:55:48 +01:00
mnovak 813a0ab8c4 [repo] Merge: docs/lumen-host-plan (Lumen host plan, PR #6) 2026-12-04 11:27:42 +01:00
21 changed files with 4429 additions and 35 deletions
+27 -1
View File
@@ -11,15 +11,17 @@ use core::fmt;
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
use cbc::cipher::block_padding::Pkcs7; use cbc::cipher::block_padding::Pkcs7;
use cbc::cipher::{BlockModeDecrypt, KeyIvInit}; use cbc::cipher::{BlockModeDecrypt, BlockModeEncrypt, KeyIvInit};
use crate::fec::ReedSolomon; use crate::fec::ReedSolomon;
use crate::util::malformed; use crate::util::malformed;
use crate::{Error, Instant, Result, SessionKeys}; use crate::{Error, Instant, Result, SessionKeys};
pub mod packet; pub mod packet;
pub mod packetizer;
pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet}; pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet};
pub use packetizer::{AudioPacketizer, AudioPacketizerConfig, AudioParity};
/// Data packets per FEC block. /// Data packets per FEC block.
pub const DATA_SHARDS: usize = 4; 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 { impl fmt::Debug for AudioCipher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AudioCipher(<redacted>)") f.write_str("AudioCipher(<redacted>)")
+124
View File
@@ -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(&timestamp.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
}
}
+2 -2
View File
@@ -26,8 +26,8 @@
//! | [`input`] | input and gamepad packets (section 4) | //! | [`input`] | input and gamepad packets (section 4) |
//! | [`rtp`] | the RTP header shared by video and audio | //! | [`rtp`] | the RTP header shared by video and audio |
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) | //! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) | //! | [`video`] | video depacketizer with FEC recovery and decryption (section 5); the host's packetizer |
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) | //! | [`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). //! Opus and video decoding are not here: they belong to the platform layer (ArenaTV).
+52 -8
View File
@@ -1,11 +1,13 @@
//! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP, //! 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 client;
pub mod sdp; pub mod sdp;
pub mod server;
pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts}; pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts};
pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp}; 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::util::{cap, malformed, parse_dec};
use crate::{Error, Result}; use crate::{Error, Result};
@@ -132,6 +134,37 @@ impl RtspResponse {
pub fn header(&self, name: &str) -> Option<&str> { pub fn header(&self, name: &str) -> Option<&str> {
header(&self.headers, name) 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. /// 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 }) 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 /// A message ends after its headers plus `Content-Length` payload bytes. Without `Content-Length`, a framer made
/// the host closes the connection ([`RtspFramer::finish`]) (UNKNOWN U5). Never buffers more than /// with [`RtspFramer::new`] (the client reading the host's answers) ends the message when the host closes the
/// [`MAX_RTSP_MESSAGE_BYTES`]. /// 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)] #[derive(Debug, Default)]
pub struct RtspFramer { pub struct RtspFramer {
buffer: Vec<u8>, buffer: Vec<u8>,
/// A missing `Content-Length` means "no payload" (requests) instead of "until close" (answers).
missing_length_is_zero: bool,
} }
impl RtspFramer { impl RtspFramer {
/// An empty framer. /// An empty framer for the host's answers (client side).
#[must_use] #[must_use]
pub const fn new() -> Self { 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. /// Appends received bytes.
@@ -293,7 +336,8 @@ impl RtspFramer {
headers.push((n.to_owned(), v.trim_matches([' ', '\t']).to_owned())); 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. /// Takes the next complete message, if one is buffered.
+1 -1
View File
@@ -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 { const fn bitstream_format(codec: VideoCodec) -> u8 {
match codec { match codec {
VideoCodec::H264 => 0, 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)
}
+402
View File
@@ -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"))
}
+34
View File
@@ -20,8 +20,10 @@ use crate::util::{array, cap, malformed, need};
use crate::{Error, Instant, Result}; use crate::{Error, Instant, Result};
pub mod packet; pub mod packet;
pub mod packetizer;
pub use packet::{FecInfo, FrameHeader, FrameType, NvVideoHeader, VideoFlags, VideoPacket, parse_video_packet}; 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. /// Length of the prefix of an encrypted packet: IV 12 + frame number 4 + tag 16.
pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 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 { impl fmt::Debug for VideoCipher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("VideoCipher(<redacted>)") f.write_str("VideoCipher(<redacted>)")
+391
View File
@@ -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
}
}
+34
View File
@@ -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"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)), |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| { v.push(("rtsp framer", rtsp, |b| {
let mut f = domistream::rtsp::RtspFramer::new(); let mut f = domistream::rtsp::RtspFramer::new();
let pushed = f.push(b); let pushed = f.push(b);
@@ -129,6 +138,29 @@ fn lying_inputs() -> Vec<Case> {
v 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. /// Stateful receivers: the bound is their caps (frames or blocks in flight), never a claimed size.
fn depacketizer_checks() { fn depacketizer_checks() {
use domistream::video::{MAX_FRAME_BYTES, MAX_FRAMES_IN_FLIGHT, VideoConfig, VideoDepacketizer}; 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 response", |b| common::implemented(&domistream::rtsp::parse_response(b))),
("rtsp request", |b| common::implemented(&domistream::rtsp::parse_request(b))), ("rtsp request", |b| common::implemented(&domistream::rtsp::parse_request(b))),
("sdp", |b| common::implemented(&domistream::rtsp::sdp::parse_sdp(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))), ("enet", |b| common::implemented(&domistream::enet::protocol::parse_datagram(b))),
("control frame", |b| common::implemented(&domistream::control::parse_encrypted_frame(b))), ("control frame", |b| common::implemented(&domistream::control::parse_encrypted_frame(b))),
("control message", |b| common::implemented(&domistream::control::parse_host_message(b))), ("control message", |b| common::implemented(&domistream::control::parse_host_message(b))),
+261
View File
@@ -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
+825
View File
@@ -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));
}
}
+13
View File
@@ -14,6 +14,7 @@ GPL-licensed implementation. This file says what may be read, what may not, and
| Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. | | Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. |
| Our own measurements | ours | Captures through our own relay ([tools/lab-relay](../tools/lab-relay)). Mark allowed **one** capture on his PC (answer 16, 2026-11-25), done exactly as [LAB_CAPTURE.md](LAB_CAPTURE.md) says; never his TV, never 192.168.100.217. Recordings stay local (on E:, approved for Play remotely) under `E:\build\play-remotely\lab\`, out of git; only facts and test vectors derived from them go in, with the date and setup. | | Our own measurements | ours | Captures through our own relay ([tools/lab-relay](../tools/lab-relay)). Mark allowed **one** capture on his PC (answer 16, 2026-11-25), done exactly as [LAB_CAPTURE.md](LAB_CAPTURE.md) says; never his TV, never 192.168.100.217. Recordings stay local (on E:, approved for Play remotely) under `E:\build\play-remotely\lab\`, out of git; only facts and test vectors derived from them go in, with the date and setup. |
| Official Sunshine and Moonlight PC **binaries** in that capture | GPL-3.0 (we only run them) | Black-box peers: run, observe their traffic, their `--help` output, their own logs and the files/registry keys they write. Never open their source, never disassemble or decompile them. | | Official Sunshine and Moonlight PC **binaries** in that capture | GPL-3.0 (we only run them) | Black-box peers: run, observe their traffic, their `--help` output, their own logs and the files/registry keys they write. Never open their source, never disassemble or decompile them. |
| Arena Domi Remote (Android, a GPL app built apart from Domi repos) and the official Moonlight PC app, as **clients of Lumen** | GPL-3.0 (we only run them) | Black-box peers (Mark, 2026-12-04, D2): lumen-host logs what they send to it. Same limits as the row above. Their workspaces and source are never opened; the Remote app's own workers drive it and hand over facts only. |
| READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. | | READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. |
| Public OS and SDK documentation (Microsoft Learn; NVIDIA, AMD and Intel encoder SDK docs and API headers; libopus and ViGEm docs) | per vendor | Read for the host side (Lumen), facts in our own words, each page logged. Allowed in the Lumen host lead's brief of 2026-12-04. Never the source of GPL or LGPL projects that wrap these APIs. | | Public OS and SDK documentation (Microsoft Learn; NVIDIA, AMD and Intel encoder SDK docs and API headers; libopus and ViGEm docs) | per vendor | Read for the host side (Lumen), facts in our own words, each page logged. Allowed in the Lumen host lead's brief of 2026-12-04. Never the source of GPL or LGPL projects that wrap these APIs. |
@@ -34,6 +35,10 @@ Never open, read, paste or port code from: **Sunshine, Moonlight (any client: Qt
moonlight-common-c, Moonlight's ENet fork, Apollo, Vibeshine, Rubylight, chiaki** (and forks of them). That also moonlight-common-c, Moonlight's ENet fork, Apollo, Vibeshine, Rubylight, chiaki** (and forks of them). That also
means their source files on GitHub. Their READMEs and wikis are fine for facts. means their source files on GitHub. Their READMEs and wikis are fine for facts.
**For host work (Lumen), also forbidden** (Mark, 2026-12-04, decision D2 in [LUMEN-HOST-PLAN.md](LUMEN-HOST-PLAN.md)):
the source of **OBS Studio** and **FFmpeg** (including any GPL or LGPL code that wraps NVENC, AMF, Quick Sync,
Desktop Duplication or WASAPI). Their documentation pages are fine for facts, like the READMEs above.
### Second-hand GPL facts ### Second-hand GPL facts
Moonshine credits Sunshine for "groundwork" on the host side, and a few Moonshine comments cite Sunshine or Moonshine credits Sunshine for "groundwork" on the host side, and a few Moonshine comments cite Sunshine or
@@ -46,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 | | `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. | | 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` | `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 ## How code gets written
@@ -83,3 +90,9 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea
| S-20 | 2026-11-25 | ArenaTV `docs/research/sunshine-api.md` and `docs/research/this-pc.md` (Domi's own research from LizardByte's docs) | Sunshine's API calls, `--creds`, `bind_address`, port offsets, first-run behaviour, this PC's adapters and old install. | | S-20 | 2026-11-25 | ArenaTV `docs/research/sunshine-api.md` and `docs/research/this-pc.md` (Domi's own research from LizardByte's docs) | Sunshine's API calls, `--creds`, `bind_address`, port offsets, first-run behaviour, this PC's adapters and old install. |
| S-21 | 2026-11-30 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e` (same pin as S-9): `src/session/stream/control/mod.rs` again (client message parsing and the control loop), `src/session/stream/mod.rs` (`StreamConfig`), `src/session/stream/video/mod.rs` (PING handling), `src/config.rs` (nothing relevant); the repository tree listing | BSD-2. U10, as facts only: the host reads **no body** from START_B (0x0307), Ping (0x0200), LOSS_STATS, FRAME_STATS or the IDR request; START_A (0x0305) is not a type it knows; inside the encrypted frame an unknown type or a failed decryption is skipped, outside it an unknown type or a bad length ends the session; INVALIDATE_REF_FRAMES `first`/`last` at message bytes 4..8 and 12..16 (LE), short bodies mean "from 0"; each Ping resets a stop deadline, `StreamConfig.timeout` default 60 s; the client-to-host IV is `seq LE ‖ 6 zero ‖ 'C' 'C'`; host messages go reliable on channel 0; the video receiver waits for START_B and takes exactly the 4 bytes `PING`, each PING updating the client address. No value in these parts cites Sunshine or moonlight-common-c (the HDR payload's Sunshine note is the known S-9 case). Used for the probe's default bodies (all empty) and the PROTOCOL.md 3.3 facts. | | S-21 | 2026-11-30 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e` (same pin as S-9): `src/session/stream/control/mod.rs` again (client message parsing and the control loop), `src/session/stream/mod.rs` (`StreamConfig`), `src/session/stream/video/mod.rs` (PING handling), `src/config.rs` (nothing relevant); the repository tree listing | BSD-2. U10, as facts only: the host reads **no body** from START_B (0x0307), Ping (0x0200), LOSS_STATS, FRAME_STATS or the IDR request; START_A (0x0305) is not a type it knows; inside the encrypted frame an unknown type or a failed decryption is skipped, outside it an unknown type or a bad length ends the session; INVALIDATE_REF_FRAMES `first`/`last` at message bytes 4..8 and 12..16 (LE), short bodies mean "from 0"; each Ping resets a stop deadline, `StreamConfig.timeout` default 60 s; the client-to-host IV is `seq LE ‖ 6 zero ‖ 'C' 'C'`; host messages go reliable on channel 0; the video receiver waits for START_B and takes exactly the 4 bytes `PING`, each PING updating the client address. No value in these parts cites Sunshine or moonlight-common-c (the HDR payload's Sunshine note is the known S-9 case). Used for the probe's default bodies (all empty) and the PROTOCOL.md 3.3 facts. |
| S-22 | 2026-12-04 | Microsoft Learn: [DXGI 1.5 improvements](https://learn.microsoft.com/windows/win32/direct3ddxgi/dxgi-1-5-improvements), [IDXGIOutput5::DuplicateOutput1](https://learn.microsoft.com/windows/win32/api/dxgi1_5/nf-dxgi1_5-idxgioutput5-duplicateoutput1), [IDXGIOutput1::DuplicateOutput](https://learn.microsoft.com/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgioutput1-duplicateoutput), [Desktop duplication](https://learn.microsoft.com/windows-hardware/drivers/display/desktop-duplication-api), [HDR and advanced colour](https://learn.microsoft.com/windows/win32/direct3darticles/high-dynamic-range), [GraphicsCaptureSession](https://learn.microsoft.com/uwp/api/windows.graphics.capture.graphicscapturesession) (`IsBorderRequired`, `IsCursorCaptureEnabled`), [SendInput](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-sendinput), [MOUSEINPUT](https://learn.microsoft.com/windows/win32/api/winuser/ns-winuser-mouseinput), [Security considerations for assistive technologies](https://learn.microsoft.com/windows/win32/winauto/uiauto-securityoverview), [UAC policy for UIAccess in secure locations](https://learn.microsoft.com/windows/client-management/mdm/policy-csp-localpoliciessecurityoptions), [CreateSyntheticPointerDevice](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-createsyntheticpointerdevice), [InjectSyntheticPointerInput](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-injectsyntheticpointerinput), [Loopback recording](https://learn.microsoft.com/windows/win32/coreaudio/loopback-recording), [AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS](https://learn.microsoft.com/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_process_loopback_params) | For [LUMEN-HOST-PLAN.md](LUMEN-HOST-PLAN.md): `DuplicateOutput1` takes a list of formats and can deliver HDR/WCG surfaces unconverted, the list should always hold `B8G8R8A8_UNORM`; E_ACCESSDENIED on the secure desktop unless LocalSystem; four duplicating processes per session by default; re-create after desktop switches and mode changes. WGC draws a border, removable only from build 20348 after user consent; cursor capture from 19041. `SendInput` is subject to UIPI and fails silently; absolute moves are 0..65535, `MOUSEEVENTF_VIRTUALDESK` maps to the whole virtual desktop; relative moves get pointer speed applied. UIAccess needs Authenticode signing, a secure install location and is meant for assistive technology. Synthetic touch/pen injection from Windows 10 1809. WASAPI loopback captures the render mix in shared mode; per-process loopback from build 20348. | | S-22 | 2026-12-04 | Microsoft Learn: [DXGI 1.5 improvements](https://learn.microsoft.com/windows/win32/direct3ddxgi/dxgi-1-5-improvements), [IDXGIOutput5::DuplicateOutput1](https://learn.microsoft.com/windows/win32/api/dxgi1_5/nf-dxgi1_5-idxgioutput5-duplicateoutput1), [IDXGIOutput1::DuplicateOutput](https://learn.microsoft.com/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgioutput1-duplicateoutput), [Desktop duplication](https://learn.microsoft.com/windows-hardware/drivers/display/desktop-duplication-api), [HDR and advanced colour](https://learn.microsoft.com/windows/win32/direct3darticles/high-dynamic-range), [GraphicsCaptureSession](https://learn.microsoft.com/uwp/api/windows.graphics.capture.graphicscapturesession) (`IsBorderRequired`, `IsCursorCaptureEnabled`), [SendInput](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-sendinput), [MOUSEINPUT](https://learn.microsoft.com/windows/win32/api/winuser/ns-winuser-mouseinput), [Security considerations for assistive technologies](https://learn.microsoft.com/windows/win32/winauto/uiauto-securityoverview), [UAC policy for UIAccess in secure locations](https://learn.microsoft.com/windows/client-management/mdm/policy-csp-localpoliciessecurityoptions), [CreateSyntheticPointerDevice](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-createsyntheticpointerdevice), [InjectSyntheticPointerInput](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-injectsyntheticpointerinput), [Loopback recording](https://learn.microsoft.com/windows/win32/coreaudio/loopback-recording), [AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS](https://learn.microsoft.com/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_process_loopback_params) | For [LUMEN-HOST-PLAN.md](LUMEN-HOST-PLAN.md): `DuplicateOutput1` takes a list of formats and can deliver HDR/WCG surfaces unconverted, the list should always hold `B8G8R8A8_UNORM`; E_ACCESSDENIED on the secure desktop unless LocalSystem; four duplicating processes per session by default; re-create after desktop switches and mode changes. WGC draws a border, removable only from build 20348 after user consent; cursor capture from 19041. `SendInput` is subject to UIPI and fails silently; absolute moves are 0..65535, `MOUSEEVENTF_VIRTUALDESK` maps to the whole virtual desktop; relative moves get pointer speed applied. UIAccess needs Authenticode signing, a secure install location and is meant for assistive technology. Synthetic touch/pen injection from Windows 10 1809. WASAPI loopback captures the render mix in shared mode; per-process loopback from build 20348. |
| 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). |
+79 -23
View File
@@ -1,7 +1,7 @@
# Lumen host: the plan # Lumen host: the plan
Status: **plan, 2026-12-04. Nothing is built yet.** Building starts only after Mark has read this plan and answered Status: **plan, 2026-12-04; Mark's go for phase one (L0 + L1) on 2026-12-04**, with all six decisions of section 8
the decisions in section 8. accepted as proposed. Later milestones start after phase one is reported.
Goal (Mark, 2026-12-04): "move away from Sunshine". Today Arena Domi's Play remotely wraps Sunshine, a separate Goal (Mark, 2026-12-04): "move away from Sunshine". Today Arena Domi's Play remotely wraps Sunshine, a separate
GPL-3.0 program that Arena Domi installs and drives only through its local settings API. Lumen is Arena Domi's own GPL-3.0 program that Arena Domi installs and drives only through its local settings API. Lumen is Arena Domi's own
@@ -35,7 +35,7 @@ Words used here:
every parser has a fuzz target. every parser has a fuzz target.
- **No admin rights.** lumen-host runs as the signed-in user, never as a service or as SYSTEM. The only elevation - **No admin rights.** lumen-host runs as the signed-in user, never as a service or as SYSTEM. The only elevation
in the plan is the one Mark already allowed at "Turn on Play remotely", and whether Lumen's firewall rules may use in the plan is the one Mark already allowed at "Turn on Play remotely", and whether Lumen's firewall rules may use
it is decision D1. it is decided: D1, yes, the same single step.
- **Nothing leaves the PC by default.** lumen-host listens only on the addresses Play remotely allows; every - **Nothing leaves the PC by default.** lumen-host listens only on the addresses Play remotely allows; every
session start and stop is audit-recorded, like today. session start and stop is audit-recorded, like today.
- **No injection into a game process, no DirectX/Vulkan hooks, no reading game memory.** Lumen captures the display - **No injection into a game process, no DirectX/Vulkan hooks, no reading game memory.** Lumen captures the display
@@ -70,7 +70,7 @@ Words used here:
paired client launches a game, and stop when the session ends. One streaming session at a time in the first paired client launches a game, and stop when the session ends. One streaming session at a time in the first
version. version.
- **Started by Arena Domi**, never by Windows as a service. Who starts it at sign-in (the tray agent is the natural - **Started by Arena Domi**, never by Windows as a service. Who starts it at sign-in (the tray agent is the natural
owner, because it always runs) is decision D4. owner, because it always runs) is decided: D4, the tray agent, once Lumen is the default.
- **Priorities**: the idle listeners run at below-normal priority. While streaming, the capture/encode thread and - **Priorities**: the idle listeners run at below-normal priority. While streaming, the capture/encode thread and
the packet pacer register with the Multimedia Class Scheduler Service (no admin needed) and everything else stays the packet pacer register with the Multimedia Class Scheduler Service (no admin needed) and everything else stays
normal or below. The cost to the game is measured (section 7.4), not assumed. normal or below. The cost to the game is measured (section 7.4), not assumed.
@@ -90,6 +90,8 @@ Windows 11, where the border can be turned off. Reasons: the reference PC runs W
WGC would draw a yellow border over the game; duplication captures exclusive-fullscreen games; and it hands us FP16 WGC would draw a yellow border over the game; duplication captures exclusive-fullscreen games; and it hands us FP16
directly. Sources: S-22 (section 9). directly. Sources: S-22 (section 9).
- **DPI awareness**: lumen-host is per-monitor DPI aware (v2). Measured in L0: without it `DuplicateOutput1`
fails with `DXGI_ERROR_UNSUPPORTED` and output sizes are DPI-virtualised.
- **Formats asked for**: `R16G16B16A16_FLOAT`, `R10G10B10A2_UNORM`, `B8G8R8A8_UNORM` (the last one always, as - **Formats asked for**: `R16G16B16A16_FLOAT`, `R10G10B10A2_UNORM`, `B8G8R8A8_UNORM` (the last one always, as
Microsoft asks). The format that arrives decides the colour path (1.3). Microsoft asks). The format that arrives decides the colour path (1.3).
- **Frames only on change**: duplication delivers a frame only when something changed. The pacer repeats the last - **Frames only on change**: duplication delivers a frame only when something changed. The pacer repeats the last
@@ -153,7 +155,8 @@ explicit at every step and tested with patterns (7.5).
- **Bitrate**: from the client's request (`configuredBitrateKbps`), capped by what the encoder supports; adaptive - **Bitrate**: from the client's request (`configuredBitrateKbps`), capped by what the encoder supports; adaptive
bitrate belongs to Lumen's own transport (roadmap Day 4). bitrate belongs to Lumen's own transport (roadmap Day 4).
- **Interface to NVENC**: NVIDIA's public API header and the driver's `nvEncodeAPI64.dll`, loaded at run time, so - **Interface to NVENC**: NVIDIA's public API header and the driver's `nvEncodeAPI64.dll`, loaded at run time, so
nothing of NVIDIA ships in Arena Domi. The header's licence is checked and logged in L0 (risk R12). We do not read nothing of NVIDIA ships in Arena Domi. The header is MIT-licensed by its own notice; L0 settled which one (section
10: API 12.0, because current drivers refuse the older API's presets). We do not read
the source of GPL or LGPL projects that wrap NVENC (FFmpeg, OBS Studio and the like); see 6.1. the source of GPL or LGPL projects that wrap NVENC (FFmpeg, OBS Studio and the like); see 6.1.
### 1.5 Audio ### 1.5 Audio
@@ -212,7 +215,7 @@ silent. lumen-host runs at medium integrity, so:
administrator, so Arena Domi can't control it", once per session; administrator, so Arena Domi can't control it", once per session;
- the **secure desktop** (UAC prompts, lock screen) gets no input (and no capture, 1.2); - the **secure desktop** (UAC prompts, lock screen) gets no input (and no capture, 1.2);
- `uiAccess` in the manifest would lift the first limit only for a signed program installed under Program Files, - `uiAccess` in the manifest would lift the first limit only for a signed program installed under Program Files,
and Microsoft reserves it for assistive technology. The plan does not use it (decision D6). and Microsoft reserves it for assistive technology. The plan does not use it (D6, accepted).
### 1.7 Sessions and launching games ### 1.7 Sessions and launching games
@@ -265,7 +268,7 @@ with one click (no PIN, no code, Mark's decision). With Lumen, the host side of
- **Arena Domi Remote (today)**: it pairs the GameStream way. The owner types the 4 digits the phone shows into - **Arena Domi Remote (today)**: it pairs the GameStream way. The owner types the 4 digits the phone shows into
Arena Domi's "Enter the code from your phone" box, exactly as with Sunshine today; lumen-host holds the pending Arena Domi's "Enter the code from your phone" box, exactly as with Sunshine today; lumen-host holds the pending
pairing and the box supplies its PIN. The same box, the same click count. Whether Arena Domi Remote should learn pairing and the box supplies its PIN. The same box, the same click count. Whether Arena Domi Remote should learn
the grant-based pairing instead (which means publishing that small protocol in a GPL app) is decision D5. the grant-based pairing instead was decided against (D5): it keeps the code box.
- **The host's identity**: the GameStream host certificate and its RSA key are made by lumen-host on first run and - **The host's identity**: the GameStream host certificate and its RSA key are made by lumen-host on first run and
the key is kept in Custos, never in a file. The PC's Play remotely signing key (Tessera) stays what it is. the key is kept in Custos, never in a file. The PC's Play remotely signing key (Tessera) stays what it is.
- **Pairing state** (paired client certificates, which device they belong to) is public data on disk, each record - **Pairing state** (paired client certificates, which device they belong to) is public data on disk, each record
@@ -336,7 +339,7 @@ That catches every asymmetric mistake before a real client is involved. The rele
turning Lumen on and off. turning Lumen on and off.
- **Capture and encode** could instead live in DomiCapture (public, CPAL-1.0), which the roadmap names for the - **Capture and encode** could instead live in DomiCapture (public, CPAL-1.0), which the roadmap names for the
zero-copy encode path and which Pictor Domi will share. That crate has no code yet and belongs to the Arena build zero-copy encode path and which Pictor Domi will share. That crate has no code yet and belongs to the Arena build
lead's plan; where Lumen's capture/encode lives is decision D3. lead's plan; D3: capture/encode start in arena-host and move to DomiCapture at L4.
- What touches files outside Play remotely's agreed folders (installer, tray agent, shared seams) goes through the - What touches files outside Play remotely's agreed folders (installer, tray agent, shared seams) goes through the
Arena build lead, one small PR each, as agreed on 2026-11-25. Arena build lead, one small PR each, as agreed on 2026-11-25.
@@ -374,21 +377,31 @@ the load rule. Each milestone ends in a demo Mark can see. Total: **about 18 day
| L1 | Host protocol + first contact | DomiStream host side of section 3.1 (pairing, HTTP, RTSP server, ANNOUNCE, ENet host, control host, both packetizers), the in-memory client↔host session test, fuzz targets. A lumen-host skeleton (listeners on loopback only, no capture) that Arena Domi Remote in the Android emulator can find, pair with (code box) and list games from | 4 | the emulator on this PC pairs with Lumen and shows Arena Domi's game list; test and fuzz report | | L1 | Host protocol + first contact | DomiStream host side of section 3.1 (pairing, HTTP, RTSP server, ANNOUNCE, ENet host, control host, both packetizers), the in-memory client↔host session test, fuzz targets. A lumen-host skeleton (listeners on loopback only, no capture) that Arena Domi Remote in the Android emulator can find, pair with (code box) and list games from | 4 | the emulator on this PC pairs with Lumen and shows Arena Domi's game list; test and fuzz report |
| L2 | First stream | Capture (SDR path, and FP16 → SDR), NVENC HEVC/H.264 low latency, pacing, WASAPI + Opus (no audio parity), keyboard and relative mouse, launch from the library, quit, game mode and audit; beside Sunshine on its own ports | 4 | a game streams from Lumen to the emulator, with sound and keyboard/mouse, while Sunshine is still installed | | L2 | First stream | Capture (SDR path, and FP16 → SDR), NVENC HEVC/H.264 low latency, pacing, WASAPI + Opus (no audio parity), keyboard and relative mouse, launch from the library, quit, game mode and audit; beside Sunshine on its own ports | 4 | a game streams from Lumen to the emulator, with sound and keyboard/mouse, while Sunshine is still installed |
| L3 | Input, all of it | absolute mouse mapping, wheel, scan-code keyboard, text, ViGEmBus pads with rumble, the touch-to-mouse spec and `input::touch`, UIPI detection; the input e2e (7.3) running green | 2 | a scripted tap, long press and two-finger scroll land at the right places in the Arena input probe; e2e report | | L3 | Input, all of it | absolute mouse mapping, wheel, scan-code keyboard, text, ViGEmBus pads with rumble, the touch-to-mouse spec and `input::touch`, UIPI detection; the input e2e (7.3) running green | 2 | a scripted tap, long press and two-finger scroll land at the right places in the Arena input probe; e2e report |
| L4 | Colour and displays | range/colour-space negotiation from measurement, HDR → SDR tone mapping checked, monitor choice and switching, GPU scaling; HDR to HDR clients only if the HDR message has been measured | 2 | test pattern on the PC and on the phone side by side, with the measured colour differences | | L4 | Colour and displays | capture/encode move from arena-host to DomiCapture (D3); range/colour-space negotiation from measurement, HDR → SDR tone mapping checked, monitor choice and switching, GPU scaling; HDR to HDR clients only if the HDR message has been measured | 2 | test pattern on the PC and on the phone side by side, with the measured colour differences |
| L5 | Pairing and per-device engine | Tessera-grant pairing with no PIN for Arena clients, the code box for Arena Domi Remote, the engine per device, Lumen's binding on the allowed addresses, firewall rules (after D1), the installer seam | 2 | gs-probe pairs with Lumen with no PIN; the phone pairs with a code; Settings shows "Streams with: Lumen" | | L5 | Pairing and per-device engine | Tessera-grant pairing with no PIN for Arena clients, the code box for Arena Domi Remote, the engine per device, Lumen's binding on the allowed addresses, firewall rules (after D1), the installer seam | 2 | gs-probe pairs with Lumen with no PIN; the phone pairs with a code; Settings shows "Streams with: Lumen" |
| L6 | Harness and the Day 3 gate | the same-PC latency harness (7.4), Lumen against Sunshine, tuning (pacing, VBV, slices, priorities), the game's frame-rate cost, a 2-hour soak, audio parity once U16 is solved | 2 | the harness table: median and p95 for Lumen and Sunshine, and the gate answer | | L6 | Harness and the Day 3 gate | the same-PC latency harness (7.4), Lumen against Sunshine, tuning (pacing, VBV, slices, priorities), the game's frame-rate cost, a 2-hour soak, audio parity once U16 is solved | 2 | the harness table: median and p95 for Lumen and Sunshine, and the gate answer |
| L7 | Switch-over | stage C for each client that passes, Sunshine as the hidden fallback (stage D), uninstall path checked | 1 | Arena Domi Remote and the Windows client streaming from Lumen by default; Sunshine only under expert options | | L7 | Switch-over | stage C for each client that passes, Sunshine as the hidden fallback (stage D), uninstall path checked | 1 | Arena Domi Remote and the Windows client streaming from Lumen by default; Sunshine only under expert options |
Not in these estimates: Arena Domi TV itself (it switches when it exists, because it is built on DomiStream), Not in these estimates: Arena Domi TV itself (it switches when it exists, because it is built on DomiStream),
Lumen's own transport (roadmap Day 4), AMF/Quick Sync, 4:4:4, a virtual display per client. Lumen's own transport (roadmap Day 4), AMF/Quick Sync, 4:4:4, a virtual display per client, and the iOS client
(5.2).
### 5.1 The first build phase proposed ### 5.1 The first build phase (accepted: Mark's go, 2026-12-04)
**L0 + L1**: the spikes (to retire the GPU and licence risks while they are cheap) and the DomiStream host side **L0 + L1**: the spikes (to retire the GPU and licence risks while they are cheap) and the DomiStream host side
with the in-memory session test, ending with Arena Domi Remote in the emulator pairing with a Lumen skeleton over with the in-memory session test, ending with Arena Domi Remote in the emulator pairing with a Lumen skeleton over
loopback. Nothing touches Sunshine, the owner's desktop, mouse or windows, except the one L0 spike run with Mark loopback. Nothing touches Sunshine, the owner's desktop, mouse or windows, except the one L0 spike run with Mark
present. About 5 days. present. About 5 days.
### 5.2 Later client phase: iOS
Every Domi app eventually runs on Windows, Android and iOS (Mark, 2026-12-04). Lumen's host does not change for
iOS: an iOS client speaks GameStream (later Lumen's own transport) to the same lumen-host. The iOS client is its own
phase after the switch-over (L7): DomiStream compiles for `aarch64-apple-ios` (it is pure Rust with no I/O, so the
check is a build and the test suite on that target), VideoToolbox decodes, the same `input::touch` recogniser maps
gestures, and the client pairs through a Tessera grant like Arena's other clients, with no PIN. It is planned and
estimated when phase L7 is done; no Moonlight iOS code is read for it (the clean room covers every client).
--- ---
## 6. Sources and measurements for the host side ## 6. Sources and measurements for the host side
@@ -402,16 +415,16 @@ present. About 5 days.
configuration), NVIDIA's Video Codec SDK documentation and API header, AMD AMF and Intel oneVPL documentation, the configuration), NVIDIA's Video Codec SDK documentation and API header, AMD AMF and Intel oneVPL documentation, the
libopus documentation, the ViGEm documentation, the Opus and RTP RFCs, ITU-R BT.709 / BT.2020 / BT.2100 and SMPTE libopus documentation, the ViGEm documentation, the Opus and RTP RFCs, ITU-R BT.709 / BT.2020 / BT.2100 and SMPTE
ST 2084. ST 2084.
- **Proposed addition to the forbidden list for host work** (D2): the source of OBS Studio (GPL-2.0) and of FFmpeg - **Forbidden for host work** (D2, Mark 2026-12-04): the source of OBS Studio (GPL-2.0) and of FFmpeg (LGPL/GPL)
(LGPL/GPL) is not read either, because both contain encoder and capture code that would be tempting to port. is not read either, because both contain encoder and capture code that would be tempting to port.
### 6.2 Measurements we make ourselves ### 6.2 Measurements we make ourselves
- **Sunshine as a black-box oracle.** Our own `gs-probe` (a GameStream client) connects to the pinned Sunshine and - **Sunshine as a black-box oracle.** Our own `gs-probe` (a GameStream client) connects to the pinned Sunshine and
logs what it sends, as allowed today ([LIVE-INTEROP.md](LIVE-INTEROP.md)): headers, packet layouts, FEC parity logs what it sends, as allowed today ([LIVE-INTEROP.md](LIVE-INTEROP.md)): headers, packet layouts, FEC parity
(to solve the audio matrix, U16), the HDR message bytes with HDR on (its layout), timings. (to solve the audio matrix, U16), the HDR message bytes with HDR on (its layout), timings.
- **Clients as black boxes.** Arena Domi Remote (in the Android emulator) and, if Mark agrees (D2), the official - **Clients as black boxes** (D2, accepted). Arena Domi Remote (in the Android emulator) and the official
Moonlight PC binary connect to lumen-host, and lumen-host logs what they send: ANNOUNCE values per client setting Moonlight PC app connect to lumen-host, and lumen-host logs what they send: ANNOUNCE values per client setting
(range, codec, HDR), input packets per gesture, ENet details. We run the binaries and read our own logs; we never (range, codec, HDR), input packets per gesture, ENet details. We run the binaries and read our own logs; we never
open their source, disassemble or decompile them. open their source, disassemble or decompile them.
- Every fact found this way goes into PROTOCOL.md with a measurement tag, the date and the setup. - Every fact found this way goes into PROTOCOL.md with a measurement tag, the date and the setup.
@@ -489,16 +502,16 @@ when this suite passes on Lumen as it does on Sunshine, and the harness says Lum
--- ---
## 8. Decisions for Mark ## 8. Decisions (Mark, 2026-12-04: all six accepted as proposed)
| # | Question | Proposal | | # | Question | Decision |
| :-- | :-- | :-- | | :-- | :-- | :-- |
| D1 | Lumen needs Windows firewall rules for `lumen-host.exe` on its ports, which needs admin. May the single UAC prompt at "Turn on Play remotely" (today: Sunshine's installer) create them, scoped to that program and the allowed addresses? | Yes; when Sunshine is gone it is the only elevated step left | | D1 | Lumen needs Windows firewall rules for `lumen-host.exe` on its ports, which needs admin | **Yes**: the existing single UAC step at "Turn on Play remotely" also creates Lumen's rules (scoped to `lumen-host.exe`, its ports and the allowed addresses). No new prompt. They stay until uninstall, like Sunshine's |
| D2 | May lumen-host log what Arena Domi Remote and the official Moonlight PC binary send to it (black-box, no source)? And should OBS Studio and FFmpeg sources join the forbidden list for host work? | Yes to both | | D2 | Black-box logging of what clients send to Lumen; OBS Studio and FFmpeg sources | **Yes**: lumen-host may log what Arena Domi Remote and the official Moonlight PC app send to it (run and observe only, never source, disassembly or decompiling). **OBS Studio and FFmpeg source are forbidden for host work** ([CLEAN_ROOM.md](CLEAN_ROOM.md)) |
| D3 | Lumen's capture and encode: in DomiCapture (public, shared with Pictor Domi, owned by the Arena build lead's plan) or in Arena's `arena-host` first, moved later? | arena-host first, behind traits; moved to DomiCapture when its owner is ready | | D3 | Where capture and encode live | **arena-host first**, behind traits; they **move to DomiCapture at L4** |
| D4 | Who starts lumen-host at sign-in: the tray agent (always running) or the Arena Domi window? | the tray agent (a seam with the Arena build lead) | | D4 | Who starts lumen-host at sign-in | **The tray agent**, once Lumen is the default engine (stage D). Before that, Arena Domi starts it when Play remotely uses Lumen |
| D5 | Arena Domi Remote: keep the 4-digit code box, or give its workers the grant-based pairing spec so it pairs with no code (the spec then becomes public in a GPL app)? | keep the code box until our own Android client exists | | D5 | Arena Domi Remote: the code box or a no-PIN spec | **Keep the code box.** No grant-based pairing spec is published into the GPL app |
| D6 | Games that run as administrator get no input from Lumen (no uiAccess, no admin). Accept and tell the user? | Yes | | D6 | Games running as administrator | **Accepted**: they get no input from Lumen, and the client shows a clear message ("This game runs as administrator, so Arena Domi can't control it") |
--- ---
@@ -510,3 +523,46 @@ Desktop Duplication, HDR and advanced colour, `GraphicsCaptureSession` (`IsBorde
for UIAccess, `CreateSyntheticPointerDevice` / `InjectSyntheticPointerInput`, and WASAPI loopback recording with for UIAccess, `CreateSyntheticPointerDevice` / `InjectSyntheticPointerInput`, and WASAPI loopback recording with
process loopback activation. Everything else here comes from this repository's own documents and the 2026-12-04 process loopback activation. Everything else here comes from this repository's own documents and the 2026-12-04
live evidence (the phone's input packets). live evidence (the phone's input packets).
---
## 10. L0 results (2026-12-04)
**Done:** the licence reading and the GPU spike. The spike is a throwaway Rust program with a small C shim over the
NVENC header, kept outside git. It showed no window, injected nothing and opened no socket. The desktop bitstreams
never left memory (nothing of the screen was written to disk); only two synthetic-pattern encodes were written, and
they stay outside git.
**Licences** (logged as S-23 to S-25 in [CLEAN_ROOM.md](CLEAN_ROOM.md)):
| Piece | Licence | Note |
| :-- | :-- | :-- |
| `nvEncodeAPI.h`, API **12.0**, from NVIDIA's own public repository (VideoProcessingFramework, Apache-2.0 repository, archived) | MIT (the header's own notice) | used. No account and no licence acceptance needed |
| `nvEncodeAPI.h`, API 8.1, NVIDIA's video-sdk-samples | MIT | **not usable**: the driver refuses its presets (below) |
| NVENC API 12.1 or newer headers | NVIDIA's SDK download (account and terms) | not needed for anything planned; if a later feature needs it, that download is Mark's decision |
| libopus | BSD-3-Clause style (Xiph COPYING) | for L2 |
| `opus` crate / `audiopus_sys` | Apache-2.0 or MIT / ISC | candidates for L2, chosen then |
| ViGEmClient | MIT (repository archived) | the client library for ViGEmBus |
| ViGEmBus | BSD-3-Clause (repository archived) | Mark installs it himself; never shipped |
| `vigem-client` crate | MIT | candidate binding for L3 |
| `windows` crate | MIT or Apache-2.0 | used by the spike |
**Measured on the reference PC** (RTX 3090, driver NVENC API maximum 13.1; primary 2560x1440 HDR; one run,
idle desktop):
| What | Result |
| :-- | :-- |
| Display state | both outputs report colour space `RGB_FULL_G2084_NONE_P2020` (HDR on); primary 10 bits per colour; peak 1499 nits, full frame 799; SDR white level 240 nits |
| Desktop Duplication | the HDR desktop arrives as `R16G16B16A16_FLOAT` (FP16 scRGB), as planned. **Needs per-monitor DPI awareness**: without it `DuplicateOutput1` returned `DXGI_ERROR_UNSUPPORTED` and the 4K output showed as 2560x1440 |
| NVENC with the API 8.1 header | `nvEncGetEncodePresetConfig` refuses the legacy low-latency preset (`NV_ENC_ERR_UNSUPPORTED_PARAM`) and initialisation without a preset fails (`NV_ENC_ERR_INVALID_PARAM`) |
| NVENC with the API 12.0 header | preset P1, tuning "ultra low latency", CBR 20 Mbit/s, VBV one frame, infinite GOP: works, 8-bit and 10-bit HEVC; the first access unit is VPS, SPS, PPS, IDR |
| Copy of the captured frame (GPU, waited) | 1.6 ms (one sample: the desktop was idle, so only one new frame arrived) |
| Colour pass FP16 → NV12 / P010, 2560x1440 (one compute dispatch, waited) | median 0.57 / 0.50 ms, p95 1.01 / 0.93 ms |
| NVENC HEVC 2560x1440, synchronous | 8-bit median 2.56 ms, p95 2.70 ms; 10-bit median 2.56 ms, p95 2.80 ms |
| NVENC HEVC 1920x1080 (pattern) | median 1.4 to 1.5 ms, p95 1.7 to 2.5 ms |
| Capture to bitstream, sum of medians, 1440p | about **4.7 ms** on the host |
What L0 did not settle (and where it is settled): capture timing under motion and at a game's frame rate (L2,
with the harness); whether the colour pass matches what a decoder shows (L4, the pattern files are the start);
the asynchronous NVENC mode, which NVIDIA recommends on Windows (L2).
+80
View File
@@ -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. 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) ## 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]]`. `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 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. 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). - The audio code is **not** this matrix (section 6.4).
### 5.4 Feedback ### 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 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. 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 ### 6.5 Decoding
**Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream **Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream
+21
View File
@@ -211,3 +211,24 @@ path = "fuzz_targets/rtsp_client.rs"
test = false test = false
doc = false doc = false
bench = 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
+26
View File
@@ -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 });
});
+172
View File
@@ -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);
}
});