From 54bc9f5faf1be201653090d311a4962d4552afba Mon Sep 17 00:00:00 2001 From: mnovak Date: Fri, 4 Dec 2026 12:23:48 +0100 Subject: [PATCH 1/4] [domistream] RTSP server: tests first (in-memory client/server session, order, Session, ANNOUNCE parser, DESCRIBE writer, caps); API stubs return Unimplemented --- crates/domistream/src/rtsp/mod.rs | 41 +- crates/domistream/src/rtsp/server/announce.rs | 131 ++ crates/domistream/src/rtsp/server/describe.rs | 46 + crates/domistream/src/rtsp/server/mod.rs | 139 ++ crates/domistream/tests/alloc_caps.rs | 45 + crates/domistream/tests/rtsp_server.rs | 1326 +++++++++++++++++ 6 files changed, 1720 insertions(+), 8 deletions(-) create mode 100644 crates/domistream/src/rtsp/server/announce.rs create mode 100644 crates/domistream/src/rtsp/server/describe.rs create mode 100644 crates/domistream/src/rtsp/server/mod.rs create mode 100644 crates/domistream/tests/rtsp_server.rs diff --git a/crates/domistream/src/rtsp/mod.rs b/crates/domistream/src/rtsp/mod.rs index 241bd29..e76026e 100644 --- a/crates/domistream/src/rtsp/mod.rs +++ b/crates/domistream/src/rtsp/mod.rs @@ -1,11 +1,13 @@ //! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP, -//! and the client state machine. +//! the client state machine and the host's session ([`server`], section 2.5). pub mod client; pub mod sdp; +pub mod server; pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts}; pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp}; +pub use server::{HostOffer, RtspServer, RtspServerState, ServerConfig, ServerEvent, ServerReply}; use crate::util::{cap, malformed, parse_dec}; use crate::{Error, Result}; @@ -132,6 +134,17 @@ impl RtspResponse { pub fn header(&self, name: &str) -> Option<&str> { header(&self.headers, name) } + + /// Serializes the response (`RTSP/1.0 `, 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> { + Err(Error::Unimplemented) + } } /// A message split into start line, headers and payload. @@ -252,21 +265,31 @@ pub fn parse_request(message: &[u8]) -> Result { Ok(RtspRequest { method, target: target.to_owned(), headers: m.headers, body: m.body }) } -/// Cuts the TCP byte stream from the host into whole messages. +/// Cuts a TCP byte stream into whole messages. /// -/// A message ends after its headers plus `Content-Length` payload bytes; without `Content-Length` it ends when -/// the host closes the connection ([`RtspFramer::finish`]) (UNKNOWN U5). Never buffers more than -/// [`MAX_RTSP_MESSAGE_BYTES`]. +/// A message ends after its headers plus `Content-Length` payload bytes. Without `Content-Length`, a framer made +/// with [`RtspFramer::new`] (the client reading the host's answers) ends the message when the host closes the +/// connection ([`RtspFramer::finish`]) (UNKNOWN U5); one made with [`RtspFramer::for_requests`] (the host reading +/// a client's requests) takes a missing `Content-Length` as zero, as RFC 2326 section 4.4 says, so the message +/// ends at the empty line (`docs/PROTOCOL.md` 2.5). Never buffers more than [`MAX_RTSP_MESSAGE_BYTES`]. #[derive(Debug, Default)] pub struct RtspFramer { buffer: Vec, + /// A missing `Content-Length` means "no payload" (requests) instead of "until close" (answers). + missing_length_is_zero: bool, } impl RtspFramer { - /// An empty framer. + /// An empty framer for the host's answers (client side). #[must_use] pub const fn new() -> Self { - Self { buffer: Vec::new() } + Self { buffer: Vec::new(), missing_length_is_zero: false } + } + + /// An empty framer for a client's requests (host side): a request without `Content-Length` has no payload. + #[must_use] + pub const fn for_requests() -> Self { + Self { buffer: Vec::new(), missing_length_is_zero: true } } /// Appends received bytes. @@ -293,7 +316,9 @@ impl RtspFramer { headers.push((n.to_owned(), v.trim_matches([' ', '\t']).to_owned())); } } - Ok(Some((head_len, content_length(&headers, head_len)?))) + let length = content_length(&headers, head_len)?; + let _ = self.missing_length_is_zero; + Ok(Some((head_len, length))) } /// Takes the next complete message, if one is buffered. diff --git a/crates/domistream/src/rtsp/server/announce.rs b/crates/domistream/src/rtsp/server/announce.rs new file mode 100644 index 0000000..a12cc02 --- /dev/null +++ b/crates/domistream/src/rtsp/server/announce.rs @@ -0,0 +1,131 @@ +//! 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::{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 { + let _ = payload; + Err(Error::Unimplemented) +} + +/// 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 { + let _ = (config, MAX_AUDIO_CHANNELS); + Vec::new() +} diff --git a/crates/domistream/src/rtsp/server/describe.rs b/crates/domistream/src/rtsp/server/describe.rs new file mode 100644 index 0000000..ced4dcf --- /dev/null +++ b/crates/domistream/src/rtsp/server/describe.rs @@ -0,0 +1,46 @@ +//! 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, OpusConfig}; +use crate::{Error, Result}; + +/// 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, +} + +/// 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> { + let _ = offer; + Err(Error::Unimplemented) +} diff --git a/crates/domistream/src/rtsp/server/mod.rs b/crates/domistream/src/rtsp/server/mod.rs new file mode 100644 index 0000000..9b4eac6 --- /dev/null +++ b/crates/domistream/src/rtsp/server/mod.rs @@ -0,0 +1,139 @@ +//! 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 super::client::StreamPorts; +use super::sdp::EncryptionFlags; +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=`). + 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, + /// 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, +} + +/// The host side of one session's RTSP negotiation. +#[derive(Debug)] +pub struct RtspServer { + config: ServerConfig, + session_id: String, +} + +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 { + let _ = (config, rng); + Err(Error::Unimplemented) + } + + /// Answers one whole request (see [`super::RtspFramer::for_requests`]). + pub fn handle_request(&mut self, message: &[u8]) -> ServerReply { + let _ = message; + ServerReply { bytes: Vec::new(), status: 501, error: Some(Error::Unimplemented) } + } + + /// The next event, if any. + pub fn poll_event(&mut self) -> Option { + None + } + + /// Which request the session expects next. + #[must_use] + pub const fn state(&self) -> RtspServerState { + RtspServerState::Options + } + + /// 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> { + None + } + + /// The configuration the session answers with. + #[must_use] + pub const fn config(&self) -> &ServerConfig { + &self.config + } +} diff --git a/crates/domistream/tests/alloc_caps.rs b/crates/domistream/tests/alloc_caps.rs index 836941f..2218dec 100644 --- a/crates/domistream/tests/alloc_caps.rs +++ b/crates/domistream/tests/alloc_caps.rs @@ -60,6 +60,26 @@ fn lying_inputs() -> 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)), )); + v.push(( + "rtsp server", + b"ANNOUNCE x RTSP/1.0 +CSeq: 1 +Content-Length: 4294967295 + +abc" + .to_vec(), + rtsp_server_answers, + )); + // ANNOUNCE: numbers far past any range, a line that claims nothing but is long, many unknown attributes. + let mut announce = b"a=x-nv-video[0].clientViewportWd:99999999999999999999999999999999 +" + .to_vec(); + announce.extend_from_slice( + &b"a=u:1 +" + .repeat(600), + ); + v.push(("announce", announce, |b| common::implemented(&domistream::rtsp::server::parse_announce(b)))); v.push(("rtsp framer", rtsp, |b| { let mut f = domistream::rtsp::RtspFramer::new(); let pushed = f.push(b); @@ -129,6 +149,29 @@ fn lying_inputs() -> Vec { v } +/// A fresh host RTSP session answers `b`; false only for an `Unimplemented` answer. +fn rtsp_server_answers(b: &[u8]) -> bool { + let config = domistream::rtsp::ServerConfig { + ports: domistream::rtsp::StreamPorts { audio: 48000, video: 47998, control: 47999 }, + offer: domistream::rtsp::HostOffer { + feature_flags: domistream::rtsp::sdp::FeatureFlags(3), + encryption_supported: domistream::rtsp::EncryptionFlags(7), + reference_frame_invalidation: true, + h264: true, + hevc: true, + av1: true, + hdr: false, + yuv444: false, + opus_configs: vec![domistream::rtsp::OpusConfig::stereo()], + }, + required_encryption: domistream::rtsp::EncryptionFlags(1), + require_session_header: false, + session_timeout_secs: 90, + }; + let Ok(mut s) = domistream::rtsp::RtspServer::new(config, &mut common::SeqRng::new(3)) else { return false }; + s.handle_request(b).error != Some(domistream::Error::Unimplemented) +} + /// Stateful receivers: the bound is their caps (frames or blocks in flight), never a claimed size. fn depacketizer_checks() { use domistream::video::{MAX_FRAME_BYTES, MAX_FRAMES_IN_FLIGHT, VideoConfig, VideoDepacketizer}; @@ -225,6 +268,8 @@ fn parsers_never_allocate_past_their_caps() { ("rtsp response", |b| common::implemented(&domistream::rtsp::parse_response(b))), ("rtsp request", |b| common::implemented(&domistream::rtsp::parse_request(b))), ("sdp", |b| common::implemented(&domistream::rtsp::sdp::parse_sdp(b))), + ("announce", |b| common::implemented(&domistream::rtsp::server::parse_announce(b))), + ("rtsp server", rtsp_server_answers), ("enet", |b| common::implemented(&domistream::enet::protocol::parse_datagram(b))), ("control frame", |b| common::implemented(&domistream::control::parse_encrypted_frame(b))), ("control message", |b| common::implemented(&domistream::control::parse_host_message(b))), diff --git a/crates/domistream/tests/rtsp_server.rs b/crates/domistream/tests/rtsp_server.rs new file mode 100644 index 0000000..2a66a3d --- /dev/null +++ b/crates/domistream/tests/rtsp_server.rs @@ -0,0 +1,1326 @@ +//! The host's RTSP session (`docs/PROTOCOL.md` 2.2, 2.5): the DESCRIBE writer, the strict ANNOUNCE parser and the +//! session state machine, driven by our own client entirely in memory, plus order violations, session checks and +//! hostile input. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)] + +mod common; + +use domistream::Error; +use domistream::http::launch::AudioLayout; +use domistream::rtsp::client::VideoCodec; +use domistream::rtsp::sdp::{self, FeatureFlags, MAX_OPUS_CONFIGS}; +use domistream::rtsp::server::{ + ChromaSampling, DEFAULT_SESSION_TIMEOUT_SECS, 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, SESSION_ID_BYTES, StreamConfig as HostStreamConfig, SurroundSettings, build_describe, + parse_announce, write_announce, +}; +use domistream::rtsp::{ + EncryptionFlags, HostCapabilities, HostOffer, MAX_RTSP_MESSAGE_BYTES, Method, NegotiatedStream, OpusConfig, + RtspClient, RtspClientState, RtspFramer, RtspProgress, RtspRequest, RtspResponse, RtspServer, RtspServerState, + ServerConfig, ServerEvent, ServerReply, StreamConfig as ClientConfig, StreamPorts, parse_response, +}; +use proptest::prelude::*; + +const URL: &str = "rtsp://192.0.2.10:48010"; +const ALL: u8 = EncryptionFlags::CONTROL_V2 | EncryptionFlags::VIDEO | EncryptionFlags::AUDIO; +const PORTS: StreamPorts = StreamPorts { audio: 48000, video: 47998, control: 47999 }; + +fn opus(digits: &str) -> OpusConfig { + sdp::parse_surround_params(digits).unwrap() +} + +fn offer() -> HostOffer { + HostOffer { + feature_flags: FeatureFlags(3), + encryption_supported: EncryptionFlags(ALL), + reference_frame_invalidation: true, + h264: true, + hevc: true, + av1: true, + hdr: true, + yuv444: false, + opus_configs: vec![opus("21101"), opus("642012345"), opus("85301234567")], + } +} + +fn server_config() -> ServerConfig { + ServerConfig { + ports: PORTS, + offer: offer(), + required_encryption: EncryptionFlags(EncryptionFlags::CONTROL_V2), + require_session_header: false, + session_timeout_secs: DEFAULT_SESSION_TIMEOUT_SECS, + } +} + +fn server_with(config: ServerConfig) -> RtspServer { + RtspServer::new(config, &mut common::SeqRng::new(42)).expect("a valid server config") +} + +fn server() -> RtspServer { + server_with(server_config()) +} + +fn client_config() -> ClientConfig { + ClientConfig { + width: 1920, + height: 1080, + fps: 60, + bitrate_kbps: 20_000, + packet_size: 1024, + codec: VideoCodec::Hevc, + hdr: false, + audio: AudioLayout::Stereo, + audio_packet_duration_ms: 5, + min_fec_packets: 2, + reference_frame_invalidation: true, + encryption: EncryptionFlags(ALL), + } +} + +/// What the host must read from our client's ANNOUNCE for `c` (the client's builder in `rtsp::sdp`). +fn expected_from_client(c: &ClientConfig, enabled: EncryptionFlags) -> HostStreamConfig { + let channels = c.audio.channels(); + HostStreamConfig { + width: c.width, + height: c.height, + max_fps: c.fps, + packet_size: c.packet_size, + bitrate_kbps: c.bitrate_kbps, + codec: c.codec, + min_fec_packets: c.min_fec_packets, + video_qos_traffic_type: 5, + audio_packet_duration_ms: c.audio_packet_duration_ms, + audio_qos_traffic_type: 4, + max_reference_frames: if c.reference_frame_invalidation { 0 } else { 1 }, + reference_frame_invalidation: c.reference_frame_invalidation, + dynamic_range_mode: u32::from(c.hdr), + encoder_csc_mode: if c.hdr { 5 } else { 0 }, + chroma: ChromaSampling::Yuv420, + encryption: enabled, + surround: SurroundSettings { + enabled: channels > 2, + channels, + channel_mask: c.audio.channel_mask(), + high_quality: true, + }, + unknown_attributes: 0, + } +} + +fn host_config() -> HostStreamConfig { + expected_from_client(&client_config(), EncryptionFlags(ALL)) +} + +// ================================================================================================ client ↔ server + +/// Runs our client against the server in memory, writing each side's bytes `chunk` bytes at a time. Returns what +/// the client negotiated and the server's events in order. +fn run_session( + client: ClientConfig, + server: &mut RtspServer, + chunk: usize, +) -> (domistream::Result, Vec) { + let mut c = RtspClient::new(URL, client).unwrap(); + let mut to_server = RtspFramer::for_requests(); + let mut to_client = RtspFramer::new(); + let mut events = Vec::new(); + for _ in 0..16 { + let Some(request) = c.poll_request() else { break }; + let mut replies = Vec::new(); + for piece in request.chunks(chunk) { + to_server.push(piece).unwrap(); + while let Some(m) = to_server.next_message().unwrap() { + let reply = server.handle_request(&m); + assert_eq!(parse_response(&reply.bytes).expect("the server's answer parses").status, reply.status); + assert_eq!(reply.status == 200, reply.error.is_none(), "{reply:?}"); + replies.push(reply); + } + } + assert_eq!(replies.len(), 1, "one request, one answer"); + assert_eq!(to_server.buffered(), 0); + while let Some(e) = server.poll_event() { + events.push(e); + } + let mut answer = None; + for piece in replies[0].bytes.chunks(chunk) { + to_client.push(piece).unwrap(); + if let Some(m) = to_client.next_message().unwrap() { + assert!(answer.is_none(), "one answer"); + answer = Some(m); + } + } + let answer = answer.expect("the answer is framed by Content-Length, not by close"); + match c.handle_response(&answer) { + Ok(RtspProgress::Continue) => {} + Ok(RtspProgress::Ready(n)) => return (Ok(n), events), + Err(e) => return (Err(e), events), + } + } + panic!("the client never finished (state {:?})", c.state()); +} + +#[test] +fn client_and_server_negotiate_in_memory() { + let mut s = server(); + assert_eq!(s.state(), RtspServerState::Options); + let (n, events) = run_session(client_config(), &mut s, usize::MAX); + let n = n.expect("the client reaches Ready against our server"); + assert_eq!(n.ports, PORTS); + assert_eq!(n.encryption, EncryptionFlags(ALL)); + assert_eq!(n.session_id.as_deref(), Some(s.session_id())); + assert_eq!( + n.host, + HostCapabilities { + encryption_supported: EncryptionFlags(ALL), + feature_flags: FeatureFlags(3), + reference_frame_invalidation: true, + av1: true, + opus_configs: offer().opus_configs, + } + ); + assert_eq!(n.opus, opus("21101")); + assert_eq!(events, vec![ServerEvent::Announced(host_config()), ServerEvent::PlayRequested]); + assert_eq!(s.state(), RtspServerState::Playing); + assert_eq!(s.announced(), Some(&host_config())); + assert_eq!(s.poll_event(), None); +} + +#[test] +fn client_and_server_one_byte_at_a_time() { + let mut s = server(); + let (n, events) = run_session(client_config(), &mut s, 1); + assert_eq!(n.unwrap().ports, PORTS); + assert_eq!(events.len(), 2); + assert_eq!(s.state(), RtspServerState::Playing); +} + +#[test] +fn client_and_server_every_codec_layout_and_mode() { + for codec in [VideoCodec::H264, VideoCodec::Hevc, VideoCodec::Av1] { + for audio in [AudioLayout::Stereo, AudioLayout::Surround51, AudioLayout::Surround71] { + for (hdr, rfi) in [(false, false), (true, true), (false, true)] { + let c = ClientConfig { codec, audio, hdr, reference_frame_invalidation: rfi, ..client_config() }; + let mut s = server(); + let (n, events) = run_session(c.clone(), &mut s, 7); + let n = n.unwrap_or_else(|e| panic!("{codec:?} {audio:?} hdr={hdr}: {e:?}")); + assert_eq!(n.opus.channels, audio.channels()); + assert_eq!( + events[0], + ServerEvent::Announced(expected_from_client(&c, EncryptionFlags(ALL))), + "{codec:?} {audio:?} hdr={hdr} rfi={rfi}" + ); + } + } + } +} + +#[test] +fn client_and_server_partial_encryption() { + // The host offers control V2 and audio only: the client turns on exactly those, the server accepts them. + let mut cfg = server_config(); + cfg.offer.encryption_supported = EncryptionFlags(EncryptionFlags::CONTROL_V2 | EncryptionFlags::AUDIO); + let mut s = server_with(cfg); + let (n, events) = run_session(client_config(), &mut s, usize::MAX); + assert_eq!(n.unwrap().encryption, EncryptionFlags(5)); + assert_eq!(events[0], ServerEvent::Announced(expected_from_client(&client_config(), EncryptionFlags(5)))); +} + +#[test] +fn client_stops_when_server_refuses_the_codec() { + // AV1 not offered: the client refuses on its own before ANNOUNCE (DESCRIBE has no rtpmap:98). + let mut cfg = server_config(); + cfg.offer.av1 = false; + let mut s = server_with(cfg); + let (n, events) = run_session(ClientConfig { codec: VideoCodec::Av1, ..client_config() }, &mut s, usize::MAX); + assert_err!(n, Error::Unsupported { .. }); + assert!(events.is_empty()); + // HEVC not offered: DESCRIBE cannot say so, the server refuses the ANNOUNCE with 451 and the client stops. + let mut cfg = server_config(); + cfg.offer.hevc = false; + let mut s = server_with(cfg); + let (n, events) = run_session(client_config(), &mut s, usize::MAX); + assert_eq!(n.unwrap_err(), Error::HostStatus { code: 451 }); + assert!(events.is_empty()); + assert_eq!(s.state(), RtspServerState::Announce); +} + +// ================================================================================================ scripted requests + +/// Sends hand-made requests with counting CSeq values and, once known, the session id. +struct Script { + cseq: u32, + session: Option, + send_session: bool, +} + +impl Script { + fn new() -> Self { + Self { cseq: 0, session: None, send_session: true } + } + + fn raw( + &mut self, + s: &mut RtspServer, + method: Method, + target: &str, + extra: &[(&str, &str)], + body: &[u8], + ) -> ServerReply { + self.cseq += 1; + let mut headers = vec![("CSeq".to_string(), self.cseq.to_string())]; + if self.send_session + && let Some(id) = &self.session + { + headers.push(("Session".into(), id.clone())); + } + headers.extend(extra.iter().map(|(k, v)| (k.to_string(), v.to_string()))); + if !body.is_empty() { + headers.push(("Content-Length".into(), body.len().to_string())); + } + let bytes = RtspRequest { method, target: target.into(), headers, body: body.to_vec() }.encode().unwrap(); + let reply = s.handle_request(&bytes); + let r = parse_response(&reply.bytes).expect("every answer parses"); + assert_eq!(r.status, reply.status); + assert_eq!(r.header("CSeq"), Some(self.cseq.to_string().as_str()), "CSeq echoed: {reply:?}"); + assert_eq!(reply.status == 200, reply.error.is_none(), "{reply:?}"); + if reply.status == 200 + && method == Method::Setup + && let Some(v) = r.header("Session") + { + self.session = Some(v.split(';').next().unwrap().trim().to_string()); + } + reply + } + + fn options(&mut self, s: &mut RtspServer) -> ServerReply { + self.raw(s, Method::Options, URL, &[], b"") + } + fn describe(&mut self, s: &mut RtspServer) -> ServerReply { + self.raw(s, Method::Describe, URL, &[("Accept", "application/sdp")], b"") + } + fn setup(&mut self, s: &mut RtspServer, stream: &str) -> ServerReply { + let target = format!("streamid={stream}/0/0"); + self.raw(s, Method::Setup, &target, &[("Transport", "unicast;X-GS-ClientPort=50000-50001")], b"") + } + fn announce(&mut self, s: &mut RtspServer, body: &[u8]) -> ServerReply { + self.raw(s, Method::Announce, "streamid=control/13/0", &[("Content-type", "application/sdp")], body) + } + fn play(&mut self, s: &mut RtspServer) -> ServerReply { + self.raw(s, Method::Play, URL, &[], b"") + } + + /// Valid requests until the server expects `state`. + fn advance_to(&mut self, s: &mut RtspServer, state: RtspServerState) { + let steps: [(RtspServerState, fn(&mut Self, &mut RtspServer) -> ServerReply); 7] = [ + (RtspServerState::Options, Self::options), + (RtspServerState::Describe, Self::describe), + (RtspServerState::Setup, |sc, s| sc.setup(s, "audio")), + (RtspServerState::Setup, |sc, s| sc.setup(s, "video")), + (RtspServerState::Setup, |sc, s| sc.setup(s, "control")), + (RtspServerState::Announce, |sc, s| sc.announce(s, &write_announce(&host_config()))), + (RtspServerState::Play, Self::play), + ]; + for (at, step) in steps { + if s.state() == state { + return; + } + // Steps before the current state are done already (a SETUP state here means none is done yet). + if rank(at) < rank(s.state()) { + continue; + } + assert_eq!(s.state(), at); + assert_eq!(step(self, s).status, 200); + } + assert_eq!(s.state(), state); + } +} + +fn assert_refused(reply: &ServerReply, status: u16) { + assert_eq!(reply.status, status, "{reply:?}"); + assert!(reply.error.is_some(), "{reply:?}"); +} + +#[test] +fn answers_carry_what_the_client_needs() { + let mut s = server(); + let mut sc = Script::new(); + let r = parse_response(&sc.options(&mut s).bytes).unwrap(); + let public = r.header("Public").expect("OPTIONS lists the methods"); + for m in ["OPTIONS", "DESCRIBE", "SETUP", "ANNOUNCE", "PLAY"] { + assert!(public.split(',').any(|p| p.trim() == m), "{public}"); + } + assert_eq!(r.header("Content-Length"), Some("0")); + + let r = parse_response(&sc.describe(&mut s).bytes).unwrap(); + assert_eq!(r.header("Content-Type"), Some("application/sdp")); + assert_eq!(r.header("Content-Length"), Some(r.body.len().to_string().as_str())); + assert_eq!(r.body, build_describe(&offer()).unwrap()); + + for (stream, port) in [("video", PORTS.video), ("control", PORTS.control), ("audio", PORTS.audio)] { + let r = parse_response(&sc.setup(&mut s, stream).bytes).unwrap(); + assert_eq!(r.status, 200); + assert_eq!(r.header("Transport"), Some(format!("server_port={port}").as_str())); + assert_eq!(r.header("Session"), Some(format!("{};timeout = 90", s.session_id()).as_str())); + } + assert_eq!(s.state(), RtspServerState::Announce, "SETUP in any order, each once"); + let r = parse_response(&sc.announce(&mut s, &write_announce(&host_config())).bytes).unwrap(); + assert_eq!((r.status, r.body.len()), (200, 0)); + let r = parse_response(&sc.play(&mut s).bytes).unwrap(); + assert_eq!((r.status, r.body.len()), (200, 0)); + assert_eq!(s.state(), RtspServerState::Playing); +} + +#[test] +fn session_timeout_is_configurable() { + let mut s = server_with(ServerConfig { session_timeout_secs: 30, ..server_config() }); + let mut sc = Script::new(); + sc.advance_to(&mut s, RtspServerState::Setup); + let r = parse_response(&sc.setup(&mut s, "audio").bytes).unwrap(); + assert_eq!(r.header("Session"), Some(format!("{};timeout = 30", s.session_id()).as_str())); +} + +#[test] +fn order_violations_get_455_and_change_nothing() { + type Step = fn(&mut Script, &mut RtspServer) -> ServerReply; + let describe: Step = Script::describe; + let setup: Step = |sc, s| sc.setup(s, "audio"); + let announce: Step = |sc, s| sc.announce(s, &write_announce(&host_config())); + let play: Step = Script::play; + let cases: [(RtspServerState, &[Step]); 5] = [ + (RtspServerState::Options, &[describe, setup, announce, play]), + (RtspServerState::Describe, &[setup, announce, play]), + (RtspServerState::Setup, &[describe, announce, play]), + (RtspServerState::Announce, &[describe, setup, play]), + (RtspServerState::Play, &[describe, setup, announce]), + ]; + for (state, wrong) in cases { + for (i, step) in wrong.iter().enumerate() { + let mut s = server(); + let mut sc = Script::new(); + sc.advance_to(&mut s, state); + while s.poll_event().is_some() {} + let reply = step(&mut sc, &mut s); + assert_refused(&reply, 455); + assert!(matches!(reply.error, Some(Error::State { .. })), "{state:?} #{i}: {reply:?}"); + assert_eq!(s.state(), state, "a refused request changes nothing"); + assert_eq!(s.poll_event(), None, "a refused request raises no event"); + // The right next request still works. + sc.advance_to(&mut s, RtspServerState::Playing); + } + } + // After PLAY nothing but OPTIONS. + let mut s = server(); + let mut sc = Script::new(); + sc.advance_to(&mut s, RtspServerState::Playing); + for step in [describe, setup, announce, play] { + assert_refused(&step(&mut sc, &mut s), 455); + } + assert_eq!(sc.options(&mut s).status, 200, "OPTIONS may come at any time (RFC 2326 10.1)"); + assert_eq!(s.state(), RtspServerState::Playing); +} + +#[test] +fn options_at_any_time_and_setup_once_each() { + let mut s = server(); + let mut sc = Script::new(); + sc.advance_to(&mut s, RtspServerState::Setup); + assert_eq!(sc.options(&mut s).status, 200); + assert_eq!(s.state(), RtspServerState::Setup); + assert_eq!(sc.setup(&mut s, "video").status, 200); + assert_refused(&sc.setup(&mut s, "video"), 455); + assert_eq!(sc.options(&mut s).status, 200); + assert_eq!(sc.setup(&mut s, "audio").status, 200); + assert_refused(&sc.announce(&mut s, &write_announce(&host_config())), 455); + assert_eq!(sc.setup(&mut s, "control").status, 200); + assert_eq!(s.state(), RtspServerState::Announce); +} + +#[test] +fn setup_targets_and_transport() { + let cases: [(&str, &[(&str, &str)], u16); 9] = [ + ("streamid=video/0/0", &[("Transport", "x")], 200), + ("rtsp://192.0.2.10:48010/streamid=video/0/0", &[("Transport", "x")], 200), + ("streamid=video", &[("Transport", "x")], 200), + ("streamid=video/0/0", &[], 400), + ("streamid=bogus/0/0", &[("Transport", "x")], 400), + ("streamid=/0/0", &[("Transport", "x")], 400), + ("rtsp://192.0.2.10:48010", &[("Transport", "x")], 400), + ("streamid=video/streamid=audio", &[("Transport", "x")], 400), + ("streamid=Video/0/0", &[("Transport", "x")], 400), + ]; + for (target, headers, status) in cases { + let mut s = server(); + let mut sc = Script::new(); + sc.advance_to(&mut s, RtspServerState::Setup); + let reply = sc.raw(&mut s, Method::Setup, target, headers, b""); + assert_eq!(reply.status, status, "{target:?} {headers:?}: {reply:?}"); + if status != 200 { + assert!(matches!(reply.error, Some(Error::Malformed { .. })), "{reply:?}"); + assert_eq!(s.state(), RtspServerState::Setup); + } + } +} + +#[test] +fn session_id_is_random_hex_and_checked() { + let a = RtspServer::new(server_config(), &mut common::SeqRng::new(1)).unwrap(); + let b = RtspServer::new(server_config(), &mut common::SeqRng::new(2)).unwrap(); + let a2 = RtspServer::new(server_config(), &mut common::SeqRng::new(1)).unwrap(); + assert_eq!(a.session_id().len(), 2 * SESSION_ID_BYTES); + assert!(a.session_id().bytes().all(|c| c.is_ascii_hexdigit())); + assert_ne!(a.session_id(), b.session_id()); + assert_eq!(a.session_id(), a2.session_id(), "the id comes only from the RandomSource"); + + // A wrong Session after the first SETUP: 454, nothing changes; the right one still works. + let mut s = server(); + let mut sc = Script::new(); + sc.advance_to(&mut s, RtspServerState::Setup); + assert_eq!(sc.setup(&mut s, "audio").status, 200); + let right = sc.session.clone().unwrap(); + assert_eq!(right, s.session_id()); + for wrong in ["0000000000000000", "", "x", &right.to_uppercase(), &format!("{right}0")] { + if wrong == right { + continue; + } + sc.session = Some(wrong.to_string()); + let reply = sc.setup(&mut s, "video"); + assert_refused(&reply, 454); + assert_eq!(s.state(), RtspServerState::Setup); + } + // The id with parameters after `;` is the same id. + sc.session = Some(format!("{right};timeout=90")); + assert_eq!(sc.setup(&mut s, "video").status, 200); + sc.session = Some(right.clone()); + // Two Session headers that disagree. + let reply = sc.raw(&mut s, Method::Setup, "streamid=control/0/0", &[("Session", "other"), ("Transport", "x")], b""); + assert_refused(&reply, 400); + assert_eq!(sc.setup(&mut s, "control").status, 200); + // Without a Session header: allowed by default (U5). + sc.send_session = false; + assert_eq!(sc.announce(&mut s, &write_announce(&host_config())).status, 200); +} + +#[test] +fn session_before_setup_is_refused() { + let mut s = server(); + let mut sc = Script::new(); + sc.session = Some(s.session_id().to_string()); + let reply = sc.options(&mut s); + assert_refused(&reply, 454); + assert_eq!(s.state(), RtspServerState::Options, "no session was issued yet"); +} + +#[test] +fn session_header_can_be_required() { + let mut s = server_with(ServerConfig { require_session_header: true, ..server_config() }); + let mut sc = Script::new(); + sc.advance_to(&mut s, RtspServerState::Setup); + assert_eq!(sc.setup(&mut s, "audio").status, 200, "the first SETUP has no session yet"); + sc.send_session = false; + assert_refused(&sc.setup(&mut s, "video"), 454); + assert_eq!(sc.options(&mut s).status, 200, "OPTIONS never needs a session"); + sc.send_session = true; + assert_eq!(sc.setup(&mut s, "video").status, 200); + assert_eq!(sc.setup(&mut s, "control").status, 200); + assert_eq!(sc.announce(&mut s, &write_announce(&host_config())).status, 200); + sc.send_session = false; + assert_refused(&sc.play(&mut s), 454); + sc.send_session = true; + assert_eq!(sc.play(&mut s).status, 200); + assert_eq!(s.state(), RtspServerState::Playing); +} + +/// The CSeq header of an answer. +fn answer_cseq(reply: &ServerReply) -> Option { + parse_response(&reply.bytes).unwrap().header("CSeq").map(str::to_string) +} + +#[test] +fn cseq_is_echoed_and_required() { + let mut s = server(); + for (cseq, status) in [("1", 200), ("4294967295", 200), ("0", 200), ("007", 200)] { + let req = format!("OPTIONS {URL} RTSP/1.0\r\nCSeq: {cseq}\r\n\r\n"); + let reply = s.handle_request(req.as_bytes()); + assert_eq!(reply.status, status); + assert_eq!(answer_cseq(&reply).unwrap().parse::().unwrap(), cseq.parse::().unwrap()); + } + for bad in ["", "CSeq: abc\r\n", "CSeq: -1\r\n", "CSeq: 4294967296\r\n", "CSeq: 1\r\nCSeq: 2\r\n"] { + let req = format!("OPTIONS {URL} RTSP/1.0\r\n{bad}\r\n"); + let reply = s.handle_request(req.as_bytes()); + assert_refused(&reply, 400); + assert!(matches!(reply.error, Some(Error::Malformed { .. })), "{bad:?}: {reply:?}"); + } + assert_eq!(s.state(), RtspServerState::Options); +} + +#[test] +fn malformed_and_unknown_requests() { + let mut s = server(); + // Unknown methods: 501, CSeq still echoed. + for m in ["TEARDOWN", "GET_PARAMETER", "PAUSE", "options"] { + let reply = s.handle_request(format!("{m} {URL} RTSP/1.0\r\nCSeq: 5\r\n\r\n").as_bytes()); + assert_refused(&reply, 501); + assert_eq!(answer_cseq(&reply).as_deref(), Some("5"), "{m}"); + } + // Broken request lines with a readable CSeq: 400, CSeq echoed. + for start in ["GARBAGE", "OPTIONS", "OPTIONS x RTSP/2.0", "OPTIONS x RTSP/1.0 extra"] { + let reply = s.handle_request(format!("{start}\r\nCSeq: 9\r\n\r\n").as_bytes()); + assert_refused(&reply, 400); + assert_eq!(answer_cseq(&reply).as_deref(), Some("9"), "{start}"); + } + // Nothing readable: 400 without CSeq. + for bad in [&b""[..], b"\0\0\0", b"\xff\xfe\r\n\r\n", b"RTSP/1.0 200 OK\r\nCSeq: 1\r\n\r\n"] { + let reply = s.handle_request(bad); + assert_refused(&reply, 400); + } + let huge = vec![b'O'; MAX_RTSP_MESSAGE_BYTES + 1]; + let reply = s.handle_request(&huge); + assert_refused(&reply, 400); + assert!(matches!(reply.error, Some(Error::TooLarge { .. })), "{reply:?}"); + assert_eq!(s.state(), RtspServerState::Options); + assert_eq!(s.poll_event(), None); +} + +#[test] +fn announce_refusals() { + let base = host_config(); + let cases: Vec<(ServerConfig, Vec, u16, &str)> = vec![ + (server_config(), b"v=0\r\nbroken line\r\n".to_vec(), 400, "bad SDP"), + (server_config(), b"v=0\r\n".to_vec(), 400, "required attributes missing"), + (server_config(), Vec::new(), 400, "no payload"), + ( + ServerConfig { offer: HostOffer { av1: false, ..offer() }, ..server_config() }, + write_announce(&HostStreamConfig { codec: VideoCodec::Av1, ..base.clone() }), + 451, + "AV1 not offered", + ), + ( + ServerConfig { offer: HostOffer { h264: false, ..offer() }, ..server_config() }, + write_announce(&HostStreamConfig { codec: VideoCodec::H264, ..base.clone() }), + 451, + "H.264 not offered", + ), + ( + ServerConfig { offer: HostOffer { hevc: false, ..offer() }, ..server_config() }, + write_announce(&base), + 451, + "HEVC not offered", + ), + ( + server_config(), + write_announce(&HostStreamConfig { encryption: EncryptionFlags(6), ..base.clone() }), + 451, + "control V2 required but not turned on", + ), + ( + server_config(), + write_announce(&HostStreamConfig { encryption: EncryptionFlags(0x0F), ..base.clone() }), + 451, + "a bit the host did not offer", + ), + ( + ServerConfig { + offer: HostOffer { encryption_supported: EncryptionFlags(5), ..offer() }, + ..server_config() + }, + write_announce(&HostStreamConfig { encryption: EncryptionFlags(7), ..base.clone() }), + 451, + "video encryption not offered", + ), + ( + ServerConfig { offer: HostOffer { hdr: false, ..offer() }, ..server_config() }, + write_announce(&HostStreamConfig { dynamic_range_mode: 1, ..base.clone() }), + 451, + "HDR not offered", + ), + ( + server_config(), + write_announce(&HostStreamConfig { chroma: ChromaSampling::Yuv444, ..base.clone() }), + 451, + "4:4:4 not offered", + ), + ]; + for (config, body, status, why) in cases { + let mut s = server_with(config); + let mut sc = Script::new(); + sc.advance_to(&mut s, RtspServerState::Announce); + while s.poll_event().is_some() {} + let reply = sc.announce(&mut s, &body); + assert_refused(&reply, status); + if status == 451 { + assert!(matches!(reply.error, Some(Error::Unsupported { .. })), "{why}: {reply:?}"); + } + assert_eq!(s.state(), RtspServerState::Announce, "{why}"); + assert_eq!(s.poll_event(), None, "{why}"); + assert_eq!(s.announced(), None, "{why}"); + } + // What the offer has is accepted, HDR and 4:4:4 included. + let mut s = server_with(ServerConfig { offer: HostOffer { yuv444: true, ..offer() }, ..server_config() }); + let mut sc = Script::new(); + sc.advance_to(&mut s, RtspServerState::Announce); + let wanted = HostStreamConfig { chroma: ChromaSampling::Yuv444, dynamic_range_mode: 1, ..base }; + assert_eq!(sc.announce(&mut s, &write_announce(&wanted)).status, 200); + assert_eq!(s.poll_event(), Some(ServerEvent::Announced(wanted.clone()))); + assert_eq!(s.announced(), Some(&wanted)); + assert_eq!(sc.play(&mut s).status, 200); + assert_eq!(s.poll_event(), Some(ServerEvent::PlayRequested)); + assert_eq!(s.poll_event(), None); +} + +#[test] +fn server_refuses_bad_config() { + let bad = [ + ServerConfig { ports: StreamPorts { audio: 0, ..PORTS }, ..server_config() }, + ServerConfig { ports: StreamPorts { video: 0, ..PORTS }, ..server_config() }, + ServerConfig { ports: StreamPorts { control: 0, ..PORTS }, ..server_config() }, + ServerConfig { session_timeout_secs: 0, ..server_config() }, + ServerConfig { offer: HostOffer { encryption_supported: EncryptionFlags(6), ..offer() }, ..server_config() }, + ]; + for config in bad { + assert_err!( + RtspServer::new(config.clone(), &mut common::SeqRng::new(1)), + Error::Malformed { .. }, + "{config:?}" + ); + } + let no_codec = HostOffer { h264: false, hevc: false, av1: false, ..offer() }; + assert_err!( + RtspServer::new(ServerConfig { offer: no_codec, ..server_config() }, &mut common::SeqRng::new(1)), + Error::Unsupported { .. } + ); + let nine = OpusConfig { channels: 9, streams: 9, coupled_streams: 0, mapping: (0..9).collect() }; + assert_err!( + RtspServer::new( + ServerConfig { offer: HostOffer { opus_configs: vec![nine], ..offer() }, ..server_config() }, + &mut common::SeqRng::new(1) + ), + Error::Malformed { .. } + ); +} + +// ================================================================================================ DESCRIBE writer + +#[test] +fn describe_lines_and_order() { + let text = String::from_utf8(build_describe(&offer()).unwrap()).unwrap(); + assert_eq!( + text, + "a=x-ss-general.featureFlags:3\r\n\ + a=x-ss-general.encryptionSupported:7\r\n\ + sprop-parameter-sets=AAAAAU\r\n\ + a=x-nv-video[0].refPicInvalidation:1\r\n\ + a=rtpmap:98 AV1/90000\r\n\ + a=fmtp:96 packetization-mode=1\r\n\ + a=fmtp:97 surround-params=21101\r\n\ + a=fmtp:97 surround-params=642012345\r\n\ + a=fmtp:97 surround-params=85301234567\r\n" + ); +} + +#[test] +fn describe_follows_the_offer() { + let lean = HostOffer { + feature_flags: FeatureFlags(0), + encryption_supported: EncryptionFlags(1), + reference_frame_invalidation: false, + h264: false, + hevc: true, + av1: false, + hdr: false, + yuv444: false, + opus_configs: vec![], + }; + let bytes = build_describe(&lean).unwrap(); + let text = String::from_utf8(bytes.clone()).unwrap(); + for absent in ["rtpmap", "fmtp", "refPicInvalidation"] { + assert!(!text.contains(absent), "{absent} in {text:?}"); + } + let caps = HostCapabilities::from_sdp(&sdp::parse_sdp(&bytes).unwrap()).unwrap(); + assert_eq!(caps, HostCapabilities { encryption_supported: EncryptionFlags(1), ..HostCapabilities::default() }); + assert_eq!(caps.opus_for(2), OpusConfig::stereo(), "no Opus lines: the client falls back to stereo"); + + let h264 = HostOffer { h264: true, ..lean.clone() }; + assert!(String::from_utf8(build_describe(&h264).unwrap()).unwrap().contains("a=fmtp:96 packetization-mode=1")); +} + +#[test] +fn describe_refuses_what_the_client_would_refuse() { + let mut bad = Vec::new(); + bad.push(OpusConfig { channels: 0, streams: 1, coupled_streams: 0, mapping: vec![] }); + bad.push(OpusConfig { channels: 2, streams: 0, coupled_streams: 0, mapping: vec![0, 0] }); + bad.push(OpusConfig { channels: 2, streams: 1, coupled_streams: 2, mapping: vec![0, 1] }); + bad.push(OpusConfig { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0] }); + bad.push(OpusConfig { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0, 2] }); + bad.push(OpusConfig { channels: 8, streams: 10, coupled_streams: 0, mapping: vec![0; 8] }); + bad.push(OpusConfig { channels: 2, streams: 12, coupled_streams: 1, mapping: vec![0, 10] }); + for c in bad { + let o = HostOffer { opus_configs: vec![c.clone()], ..offer() }; + assert_err!(build_describe(&o), Error::Malformed { .. }, "{c:?}"); + } + let many = HostOffer { opus_configs: vec![OpusConfig::stereo(); MAX_OPUS_CONFIGS + 1], ..offer() }; + assert_err!(build_describe(&many), Error::TooLarge { .. }); + let max = HostOffer { opus_configs: vec![OpusConfig::stereo(); MAX_OPUS_CONFIGS], ..offer() }; + let caps = HostCapabilities::from_sdp(&sdp::parse_sdp(&build_describe(&max).unwrap()).unwrap()).unwrap(); + assert_eq!(caps.opus_configs.len(), MAX_OPUS_CONFIGS); + let none = HostOffer { h264: false, hevc: false, av1: false, ..offer() }; + assert_err!(build_describe(&none), Error::Unsupported { .. }); +} + +// ================================================================================================ ANNOUNCE parser + +const REQUIRED: [(&str, &str); 10] = [ + ("x-nv-video[0].clientViewportWd", "1920"), + ("x-nv-video[0].clientViewportHt", "1080"), + ("x-nv-video[0].maxFPS", "60"), + ("x-nv-video[0].packetSize", "1024"), + ("x-ml-video.configuredBitrateKbps", "20000"), + ("x-nv-vqos[0].bitStreamFormat", "1"), + ("x-nv-vqos[0].fec.minRequiredFecPackets", "2"), + ("x-nv-vqos[0].qosTrafficType", "5"), + ("x-nv-aqos.packetDuration", "5"), + ("x-nv-aqos.qosTrafficType", "4"), +]; + +const OPTIONAL: [(&str, &str); 10] = [ + ("x-nv-video[0].maxNumReferenceFrames", "0"), + ("x-nv-video[0].refPicInvalidation", "1"), + ("x-nv-video[0].dynamicRangeMode", "0"), + ("x-nv-video[0].encoderCscMode", "0"), + ("x-ss-video[0].chromaSamplingType", "0"), + ("x-ss-general.encryptionEnabled", "7"), + ("x-nv-audio.surround.enable", "0"), + ("x-nv-audio.surround.numChannels", "2"), + ("x-nv-audio.surround.channelMask", "3"), + ("x-nv-audio.surround.AudioQuality", "1"), +]; + +fn sdp_of(attrs: &[(&str, &str)]) -> String { + let mut s = String::from("v=0\r\n"); + for (k, v) in attrs { + s.push_str(&format!("a={k}:{v}\r\n")); + } + s +} + +fn full_attrs() -> Vec<(&'static str, &'static str)> { + REQUIRED.iter().chain(OPTIONAL.iter()).copied().collect() +} + +fn with(name: &str, value: &str) -> String { + sdp_of(&full_attrs().into_iter().map(|(k, v)| (k, if k == name { value } else { v })).collect::>()) +} + +#[test] +fn announce_sample() { + let c = parse_announce(sdp_of(&full_attrs()).as_bytes()).unwrap(); + assert_eq!(c, host_config()); + // LF line ends, blanks around values, other SDP lines and empty lines change nothing. + let mut loose = String::from("v=0\no=- 0 0 IN IP4 0.0.0.0\ns=x\nt=0 0\nm=video 0 RTP/AVP 96\n\n"); + for (k, v) in full_attrs() { + loose.push_str(&format!("a={k}: {v}\t\n\n")); + } + loose.push_str("sprop-parameter-sets=AAAAAU\n"); + assert_eq!(parse_announce(loose.as_bytes()).unwrap(), host_config()); +} + +#[test] +fn announce_from_our_client() { + let host = HostCapabilities::from_sdp(&sdp::parse_sdp(&build_describe(&offer()).unwrap()).unwrap()).unwrap(); + let body = sdp::build_announce(&client_config(), &host).unwrap(); + assert_eq!(parse_announce(&body).unwrap(), host_config()); +} + +#[test] +fn announce_defaults() { + let c = parse_announce(sdp_of(&REQUIRED).as_bytes()).unwrap(); + assert_eq!(c.max_reference_frames, 1); + assert!(!c.reference_frame_invalidation); + assert_eq!((c.dynamic_range_mode, c.encoder_csc_mode), (0, 0)); + assert_eq!(c.chroma, ChromaSampling::Yuv420); + assert_eq!(c.encryption, EncryptionFlags(0)); + assert_eq!(c.surround, SurroundSettings { enabled: false, channels: 2, channel_mask: 3, high_quality: true }); + assert_eq!(c.surround, SurroundSettings::default()); + assert_eq!(c.unknown_attributes, 0); +} + +#[test] +fn announce_required_attributes() { + for (name, _) in REQUIRED { + let rest: Vec<_> = full_attrs().into_iter().filter(|(k, _)| *k != name).collect(); + assert_err!(parse_announce(sdp_of(&rest).as_bytes()), Error::Malformed { .. }, "without {name}"); + } + for (name, _) in OPTIONAL { + let rest: Vec<_> = full_attrs().into_iter().filter(|(k, _)| *k != name).collect(); + assert!(parse_announce(sdp_of(&rest).as_bytes()).is_ok(), "without {name}"); + } +} + +#[test] +fn announce_duplicates_and_unknowns() { + for (name, value) in full_attrs() { + let mut attrs = full_attrs(); + attrs.push((name, value)); + assert_err!(parse_announce(sdp_of(&attrs).as_bytes()), Error::Malformed { .. }, "{name} twice"); + } + let mut attrs = full_attrs(); + attrs.extend([ + ("x-nv-general.unknown", "1"), + ("x-nv-general.unknown", "2"), + ("x-nv-video[1].clientViewportWd", "5"), + ]); + let mut text = sdp_of(&attrs); + text.push_str("a=recvonly\r\n"); + let c = parse_announce(text.as_bytes()).unwrap(); + assert_eq!(c.unknown_attributes, 4, "unknown attributes are counted, duplicates of them included"); + assert_eq!(HostStreamConfig { unknown_attributes: 0, ..c }, host_config()); +} + +#[test] +fn announce_ranges() { + let refused = [ + ("x-nv-video[0].clientViewportWd", "0"), + ("x-nv-video[0].clientViewportWd", "16385"), + ("x-nv-video[0].clientViewportHt", "0"), + ("x-nv-video[0].clientViewportHt", "16385"), + ("x-nv-video[0].maxFPS", "0"), + ("x-nv-video[0].maxFPS", "1001"), + ("x-nv-video[0].packetSize", "199"), + ("x-nv-video[0].packetSize", "65472"), + ("x-ml-video.configuredBitrateKbps", "0"), + ("x-ml-video.configuredBitrateKbps", "4294968"), + ("x-nv-vqos[0].bitStreamFormat", "3"), + ("x-nv-vqos[0].fec.minRequiredFecPackets", "256"), + ("x-nv-vqos[0].qosTrafficType", "4294967296"), + ("x-nv-aqos.packetDuration", "0"), + ("x-nv-aqos.packetDuration", "121"), + ("x-nv-aqos.qosTrafficType", "4294967296"), + ("x-nv-video[0].maxNumReferenceFrames", "4294967296"), + ("x-nv-video[0].refPicInvalidation", "2"), + ("x-nv-video[0].dynamicRangeMode", "4294967296"), + ("x-nv-video[0].encoderCscMode", "4294967296"), + ("x-ss-video[0].chromaSamplingType", "2"), + ("x-ss-general.encryptionEnabled", "256"), + ("x-nv-audio.surround.enable", "2"), + ("x-nv-audio.surround.numChannels", "0"), + ("x-nv-audio.surround.numChannels", "9"), + ("x-nv-audio.surround.channelMask", "4294967296"), + ("x-nv-audio.surround.AudioQuality", "2"), + ]; + for (name, value) in refused { + assert_err!(parse_announce(with(name, value).as_bytes()), Error::UnexpectedValue { .. }, "{name}={value}"); + } + let accepted = [ + ("x-nv-video[0].clientViewportWd", "16384", "1"), + ("x-nv-video[0].clientViewportHt", "16384", "1"), + ("x-nv-video[0].maxFPS", "1000", "1"), + ("x-nv-video[0].packetSize", "65471", "200"), + ("x-ml-video.configuredBitrateKbps", "4294967", "1"), + ("x-nv-vqos[0].bitStreamFormat", "2", "0"), + ("x-nv-vqos[0].fec.minRequiredFecPackets", "255", "0"), + ("x-nv-aqos.packetDuration", "120", "1"), + ("x-nv-audio.surround.numChannels", "8", "1"), + ("x-ss-general.encryptionEnabled", "255", "0"), + ]; + for (name, high, low) in accepted { + for v in [high, low] { + assert!(parse_announce(with(name, v).as_bytes()).is_ok(), "{name}={v}"); + } + } + let raw = parse_announce( + sdp_of( + &full_attrs() + .into_iter() + .map(|(k, v)| match k { + "x-nv-video[0].dynamicRangeMode" => (k, "4294967295"), + "x-nv-video[0].encoderCscMode" => (k, "12345"), + "x-nv-video[0].maxNumReferenceFrames" => (k, "77"), + "x-nv-vqos[0].qosTrafficType" => (k, "0"), + "x-nv-audio.surround.channelMask" => (k, "4294967295"), + _ => (k, v), + }) + .collect::>(), + ) + .as_bytes(), + ) + .unwrap(); + assert_eq!(raw.dynamic_range_mode, u32::MAX, "kept raw (U6)"); + assert_eq!(raw.encoder_csc_mode, 12345, "kept raw (U6)"); + assert_eq!(raw.max_reference_frames, 77); + assert_eq!(raw.video_qos_traffic_type, 0); + assert_eq!(raw.surround.channel_mask, u32::MAX); + assert_eq!(parse_announce(with("x-nv-vqos[0].bitStreamFormat", "0").as_bytes()).unwrap().codec, VideoCodec::H264); + assert_eq!(parse_announce(with("x-nv-vqos[0].bitStreamFormat", "2").as_bytes()).unwrap().codec, VideoCodec::Av1); +} + +#[test] +fn announce_number_syntax() { + for bad in ["", "+5", "-1", "0x10", "1 2", "1.5", "1e3", "٣", "99999999999999999999999", "5;", "5,6"] { + let r = parse_announce(with("x-nv-video[0].maxFPS", bad).as_bytes()); + assert!(matches!(r, Err(Error::Malformed { .. } | Error::UnexpectedValue { .. })), "{bad:?}: {r:?}"); + } + assert_eq!(parse_announce(with("x-nv-video[0].maxFPS", "0060").as_bytes()).unwrap().max_fps, 60); +} + +#[test] +fn announce_hostile_lines() { + let base = sdp_of(&full_attrs()); + for (extra, why) in [ + ("no equals sign\r\n", "line without ="), + ("=x\r\n", "empty type"), + ("a=x-nv-video[0].maxFPS\r\n", "known attribute without a value"), + ("a=u:\0\r\n", "NUL"), + ("a=u:\x1b[31m\r\n", "escape"), + ("a=u:1\rb\r\n", "CR inside a line"), + ] { + let text = format!("{base}{extra}"); + let r = parse_announce(text.as_bytes()); + // The known attribute without a value is also a duplicate; either way it is refused. + assert_err!(r, Error::Malformed { .. }, "{why}"); + } + let mut not_utf8 = base.clone().into_bytes(); + not_utf8.extend_from_slice(b"a=u:\xff\xfe\r\n"); + assert_err!(parse_announce(¬_utf8), Error::Malformed { .. }); +} + +macro_rules! assert_cap { + ($e:expr, $max:expr) => { + match $e { + Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"), + other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other), + } + }; +} + +#[test] +fn announce_caps() { + let base = sdp_of(&REQUIRED); + let base_lines = REQUIRED.len() + 1; + // Lines. + let lines = |n: usize| format!("{base}{}", "t=0 0\n".repeat(n - base_lines)); + assert!(parse_announce(lines(MAX_ANNOUNCE_LINES).as_bytes()).is_ok()); + assert_cap!(parse_announce(lines(MAX_ANNOUNCE_LINES + 1).as_bytes()), MAX_ANNOUNCE_LINES); + // Empty lines are not lines. + assert!(parse_announce(format!("{}{}", lines(MAX_ANNOUNCE_LINES), "\r\n".repeat(100)).as_bytes()).is_ok()); + // Attributes. + let attrs = |n: usize| format!("{base}{}", "a=u:1\n".repeat(n - REQUIRED.len())); + assert_eq!( + parse_announce(attrs(MAX_ANNOUNCE_ATTRIBUTES).as_bytes()).unwrap().unknown_attributes as usize, + MAX_ANNOUNCE_ATTRIBUTES - REQUIRED.len() + ); + assert_cap!(parse_announce(attrs(MAX_ANNOUNCE_ATTRIBUTES + 1).as_bytes()), MAX_ANNOUNCE_ATTRIBUTES); + // Line length (without the line end). + let long = |n: usize| format!("{base}a=pad:{}\r\n", "p".repeat(n - 6)); + assert!(parse_announce(long(MAX_ANNOUNCE_LINE_BYTES).as_bytes()).is_ok()); + assert_cap!(parse_announce(long(MAX_ANNOUNCE_LINE_BYTES + 1).as_bytes()), MAX_ANNOUNCE_LINE_BYTES); + // A last line without a line end counts too. + assert_cap!( + parse_announce(format!("{base}a=pad:{}", "p".repeat(MAX_ANNOUNCE_LINE_BYTES)).as_bytes()), + MAX_ANNOUNCE_LINE_BYTES + ); + // Bytes: padded with empty lines. + let sized = |n: usize| format!("{base}{}", "\n".repeat(n - base.len())); + assert!(parse_announce(sized(MAX_ANNOUNCE_BYTES).as_bytes()).is_ok()); + assert_too_large!( + parse_announce(sized(MAX_ANNOUNCE_BYTES + 1).as_bytes()), + MAX_ANNOUNCE_BYTES, + MAX_ANNOUNCE_BYTES + 1 + ); + assert_too_large!(parse_announce(&vec![b'a'; 1 << 20]), MAX_ANNOUNCE_BYTES, 1 << 20); +} + +// ================================================================================================ response codec + +#[test] +fn response_encode_round_trip_and_injection() { + let r = RtspResponse { + status: 200, + reason: "OK".into(), + headers: vec![("CSeq".into(), "3".into()), ("Content-Length".into(), "5".into())], + body: b"hello".to_vec(), + }; + let bytes = r.encode().unwrap(); + assert_eq!(bytes, b"RTSP/1.0 200 OK\r\nCSeq: 3\r\nContent-Length: 5\r\n\r\nhello".to_vec()); + assert_eq!(parse_response(&bytes).unwrap(), r); + let base = || RtspResponse { status: 200, reason: "OK".into(), headers: vec![], body: vec![] }; + let bad = [ + RtspResponse { status: 99, ..base() }, + RtspResponse { status: 1000, ..base() }, + RtspResponse { reason: "OK\r\nX: y".into(), ..base() }, + RtspResponse { headers: vec![("Bad:Name".into(), "v".into())], ..base() }, + RtspResponse { headers: vec![(String::new(), "v".into())], ..base() }, + RtspResponse { headers: vec![("X".into(), "a\r\nY: b".into())], ..base() }, + ]; + for r in bad { + assert_err!(r.encode(), Error::Malformed { .. }, "{r:?}"); + } + assert_cap!(RtspResponse { body: vec![0; MAX_RTSP_MESSAGE_BYTES], ..base() }.encode(), MAX_RTSP_MESSAGE_BYTES); +} + +#[test] +fn request_framer_ends_at_the_empty_line() { + let a = b"OPTIONS rtsp://h:1 RTSP/1.0\r\nCSeq: 1\r\n\r\n".to_vec(); + let b = b"ANNOUNCE x RTSP/1.0\r\nCSeq: 2\r\nContent-Length: 3\r\n\r\nabc".to_vec(); + let c = b"PLAY rtsp://h:1 RTSP/1.0\r\nCSeq: 3\r\n\r\n".to_vec(); + let mut f = RtspFramer::for_requests(); + f.push(&[a.clone(), b.clone(), c.clone()].concat()).unwrap(); + assert_eq!(f.next_message().unwrap(), Some(a.clone()), "no Content-Length: no payload (RFC 2326 4.4)"); + assert_eq!(f.next_message().unwrap(), Some(b)); + assert_eq!(f.next_message().unwrap(), Some(c)); + assert_eq!(f.next_message().unwrap(), None); + assert_eq!(f.finish(), Ok(None)); + // Half a request at close. + let mut f = RtspFramer::for_requests(); + f.push(&a[..a.len() - 2]).unwrap(); + assert_eq!(f.next_message().unwrap(), None); + assert_err!(f.finish(), Error::Truncated { .. }); + // The client-side framer still waits for close without Content-Length. + let mut f = RtspFramer::new(); + f.push(&a).unwrap(); + assert_eq!(f.next_message().unwrap(), None); +} + +// ================================================================================================ properties + +fn codec() -> impl Strategy { + prop_oneof![Just(VideoCodec::H264), Just(VideoCodec::Hevc), Just(VideoCodec::Av1)] +} + +fn valid_host_config() -> impl Strategy { + ( + ( + 1..=MAX_DIMENSION, + 1..=MAX_DIMENSION, + 1..=MAX_FPS, + MIN_PACKET_SIZE..=MAX_PACKET_SIZE, + 1..=MAX_BITRATE_KBPS, + codec(), + any::(), + any::(), + ), + ( + 1..=MAX_AUDIO_PACKET_DURATION_MS, + any::(), + any::(), + any::(), + any::(), + any::(), + prop_oneof![Just(ChromaSampling::Yuv420), Just(ChromaSampling::Yuv444)], + any::(), + ), + (any::(), 1u8..=8, any::(), any::()), + ) + .prop_map( + |((w, h, fps, ps, br, codec, fec, vq), (dur, aq, refs, rfi, drm, csc, chroma, enc), (on, ch, mask, hq))| { + HostStreamConfig { + width: w, + height: h, + max_fps: fps, + packet_size: ps, + bitrate_kbps: br, + codec, + min_fec_packets: fec, + video_qos_traffic_type: vq, + audio_packet_duration_ms: dur, + audio_qos_traffic_type: aq, + max_reference_frames: refs, + reference_frame_invalidation: rfi, + dynamic_range_mode: drm, + encoder_csc_mode: csc, + chroma, + encryption: EncryptionFlags(enc), + surround: SurroundSettings { enabled: on, channels: ch, channel_mask: mask, high_quality: hq }, + unknown_attributes: 0, + } + }, + ) +} + +fn valid_client_config() -> impl Strategy { + ( + 1..=MAX_DIMENSION, + 1..=MAX_DIMENSION, + 1..=MAX_FPS, + 1..=MAX_BITRATE_KBPS, + MIN_PACKET_SIZE..=MAX_PACKET_SIZE, + codec(), + any::(), + prop_oneof![Just(AudioLayout::Stereo), Just(AudioLayout::Surround51), Just(AudioLayout::Surround71)], + 1..=MAX_AUDIO_PACKET_DURATION_MS, + any::(), + any::(), + (1u8..8).prop_map(|e| EncryptionFlags(e | EncryptionFlags::CONTROL_V2)), + ) + .prop_map( + |(width, height, fps, bitrate_kbps, packet_size, codec, hdr, audio, dur, fec, rfi, encryption)| { + ClientConfig { + width, + height, + fps, + bitrate_kbps, + packet_size, + codec, + hdr, + audio, + audio_packet_duration_ms: dur, + min_fec_packets: fec, + reference_frame_invalidation: rfi, + encryption, + } + }, + ) +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + /// write_announce then parse_announce gives the config back. + #[test] + fn announce_round_trip(c in valid_host_config()) { + prop_assert_eq!(parse_announce(&write_announce(&c)), Ok(c)); + } + + /// What our client announces is what the host reads, for any valid client config. + #[test] + fn client_announce_is_read_back(c in valid_client_config()) { + let host = HostCapabilities::from_sdp(&sdp::parse_sdp(&build_describe(&offer()).unwrap()).unwrap()).unwrap(); + let enabled = sdp::negotiated_encryption(&c, &host).unwrap(); + let body = sdp::build_announce(&c, &host).unwrap(); + prop_assert_eq!(parse_announce(&body), Ok(expected_from_client(&c, enabled))); + } + + /// Any valid client config negotiates end to end against the server. + #[test] + fn any_client_config_negotiates(c in valid_client_config(), seed in any::()) { + let mut s = RtspServer::new(server_config(), &mut common::SeqRng::new(seed)).unwrap(); + let (n, events) = run_session(c.clone(), &mut s, usize::MAX); + let n = n.map_err(|e| TestCaseError::fail(format!("{e:?}")))?; + prop_assert_eq!(n.session_id.as_deref(), Some(s.session_id())); + prop_assert_eq!(&events[0], &ServerEvent::Announced(expected_from_client(&c, n.encryption))); + } + + /// Arbitrary bytes never panic the parser, and what it accepts is in range. + #[test] + fn announce_never_panics(data in proptest::collection::vec(any::(), 0..2048)) { + let r = parse_announce(&data); + prop_assert!(common::implemented(&r)); + if let Ok(c) = r { + prop_assert!((1..=MAX_DIMENSION).contains(&c.width) && (1..=MAX_DIMENSION).contains(&c.height)); + prop_assert!(c.packet_size >= MIN_PACKET_SIZE && c.packet_size <= MAX_PACKET_SIZE); + } + } + + /// Attribute-shaped noise: known names with arbitrary values, in any order, never panic. + #[test] + fn announce_attribute_noise_never_panics( + lines in proptest::collection::vec((0usize..21, "[ -~]{0,12}"), 0..40), + ) { + let names: Vec<&str> = full_attrs().into_iter().map(|(k, _)| k).chain(["x-unknown"]).collect(); + let text: String = lines.iter().map(|(i, v)| format!("a={}:{v}\n", names[*i])).collect(); + let r = parse_announce(text.as_bytes()); + prop_assert!(common::implemented(&r)); + if let Ok(c) = r { + prop_assert_eq!(parse_announce(&write_announce(&c)), Ok(HostStreamConfig { unknown_attributes: 0, ..c })); + } + } + + /// Arbitrary bytes as a request: always an answer that parses, never a panic, never a state change. + #[test] + fn server_never_panics_on_bytes(data in proptest::collection::vec(any::(), 0..1024)) { + let mut s = server(); + let reply = s.handle_request(&data); + prop_assert!(reply.error != Some(Error::Unimplemented)); + prop_assert_eq!(parse_response(&reply.bytes).map(|r| r.status), Ok(reply.status)); + prop_assert!(reply.status == 200 || s.state() == RtspServerState::Options); + } +} + +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, + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })] + + /// Random request sequences: every answer parses and echoes CSeq, the status is one of the documented ones, the + /// state only moves forward, and the events come at most once each, in order. + #[test] + fn server_random_sequences(steps in proptest::collection::vec((0u8..7, 0u8..6, 0u8..3, 0u8..3, any::()), 0..24)) { + let mut s = server(); + let id = s.session_id().to_string(); + let good_announce = write_announce(&host_config()); + let mut announced = 0; + let mut played = 0; + for (m, t, sess, body, cseq) in steps { + let target = ["rtsp://192.0.2.10:48010", "streamid=audio/0/0", "streamid=video/0/0", + "streamid=control/13/0", "streamid=bogus/0/0", "*"][usize::from(t)]; + let session = match sess { 1 => format!("Session: {id}\r\n"), 2 => "Session: nope\r\n".into(), _ => String::new() }; + let body: &[u8] = match body { 1 => &good_announce, 2 => b"v=0\r\nx\r\n", _ => b"" }; + let method = ["OPTIONS", "DESCRIBE", "SETUP", "ANNOUNCE", "PLAY", "TEARDOWN", "GARBAGE GARBAGE"][usize::from(m)]; + let mut req = format!("{method} {target} RTSP/1.0\r\nCSeq: {cseq}\r\n{session}Transport: x\r\n"); + if !body.is_empty() { + req.push_str(&format!("Content-Length: {}\r\n", body.len())); + } + req.push_str("\r\n"); + let mut bytes = req.into_bytes(); + bytes.extend_from_slice(body); + let before = s.state(); + let reply = s.handle_request(&bytes); + prop_assert!(reply.error != Some(Error::Unimplemented)); + let r = parse_response(&reply.bytes).map_err(|e| TestCaseError::fail(format!("{e:?}")))?; + prop_assert_eq!(r.status, reply.status); + prop_assert!([200, 400, 451, 454, 455, 501].contains(&reply.status), "{}", reply.status); + prop_assert_eq!(reply.status == 200, reply.error.is_none()); + let echoed = cseq.to_string(); + prop_assert_eq!(r.header("CSeq"), Some(echoed.as_str())); + prop_assert!(rank(s.state()) >= rank(before)); + if reply.status != 200 { + prop_assert_eq!(s.state(), before); + } + while let Some(e) = s.poll_event() { + match e { + ServerEvent::Announced(c) => { + prop_assert_eq!(c, host_config()); + announced += 1; + } + ServerEvent::PlayRequested => { + prop_assert_eq!(announced, 1); + played += 1; + } + } + } + prop_assert!(announced <= 1 && played <= 1); + } + prop_assert_eq!(played == 1, s.state() == RtspServerState::Playing); + prop_assert_eq!(announced == 1, rank(s.state()) >= rank(RtspServerState::Play)); + } +} + +#[test] +fn client_failed_state_is_reported() { + // The client reaches Failed when the server refuses; the server stays where it was. + let mut cfg = server_config(); + cfg.offer.hevc = false; + let mut s = server_with(cfg); + let mut c = RtspClient::new(URL, client_config()).unwrap(); + let mut framer = RtspFramer::for_requests(); + while let Some(req) = c.poll_request() { + framer.push(&req).unwrap(); + let m = framer.next_message().unwrap().unwrap(); + let reply = s.handle_request(&m); + if c.handle_response(&reply.bytes).is_err() { + break; + } + } + assert_eq!(c.state(), RtspClientState::Failed); + assert_eq!(s.state(), RtspServerState::Announce); +} -- 2.53.0 From 27b7f2bf1db844dba4258ad4e8639d23c1661055 Mon Sep 17 00:00:00 2001 From: mnovak Date: Fri, 4 Dec 2026 12:23:48 +0100 Subject: [PATCH 2/4] [fuzz] RTSP server: rtsp_server (session fed arbitrary requests after a valid prefix) and announce targets --- fuzz/Cargo.toml | 14 +++ fuzz/fuzz_targets/announce.rs | 26 +++++ fuzz/fuzz_targets/rtsp_server.rs | 172 +++++++++++++++++++++++++++++++ 3 files changed, 212 insertions(+) create mode 100644 fuzz/fuzz_targets/announce.rs create mode 100644 fuzz/fuzz_targets/rtsp_server.rs diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 8c61c26..0509116 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -218,3 +218,17 @@ 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 diff --git a/fuzz/fuzz_targets/announce.rs b/fuzz/fuzz_targets/announce.rs new file mode 100644 index 0000000..d15cb8f --- /dev/null +++ b/fuzz/fuzz_targets/announce.rs @@ -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 }); +}); diff --git a/fuzz/fuzz_targets/rtsp_server.rs b/fuzz/fuzz_targets/rtsp_server.rs new file mode 100644 index 0000000..c31a18a --- /dev/null +++ b/fuzz/fuzz_targets/rtsp_server.rs @@ -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> { + 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); + } + } +}); -- 2.53.0 From a86a689b1f9d5a0692cefda562814a1afc5f939b Mon Sep 17 00:00:00 2001 From: mnovak Date: Fri, 4 Dec 2026 12:31:28 +0100 Subject: [PATCH 3/4] [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) --- crates/domistream/src/rtsp/mod.rs | 25 +- crates/domistream/src/rtsp/sdp.rs | 2 +- crates/domistream/src/rtsp/server/announce.rs | 247 +++++++++++++-- crates/domistream/src/rtsp/server/describe.rs | 49 ++- crates/domistream/src/rtsp/server/mod.rs | 283 +++++++++++++++++- crates/domistream/tests/alloc_caps.rs | 19 +- crates/domistream/tests/rtsp_server.rs | 41 ++- 7 files changed, 597 insertions(+), 69 deletions(-) diff --git a/crates/domistream/src/rtsp/mod.rs b/crates/domistream/src/rtsp/mod.rs index e76026e..948d91c 100644 --- a/crates/domistream/src/rtsp/mod.rs +++ b/crates/domistream/src/rtsp/mod.rs @@ -143,7 +143,27 @@ impl RtspResponse { /// 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> { - Err(Error::Unimplemented) + 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) } } @@ -317,8 +337,7 @@ impl RtspFramer { } } let length = content_length(&headers, head_len)?; - let _ = self.missing_length_is_zero; - Ok(Some((head_len, length))) + 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. diff --git a/crates/domistream/src/rtsp/sdp.rs b/crates/domistream/src/rtsp/sdp.rs index 49fa92a..0d3fb53 100644 --- a/crates/domistream/src/rtsp/sdp.rs +++ b/crates/domistream/src/rtsp/sdp.rs @@ -199,7 +199,7 @@ impl HostCapabilities { } } -/// `x-nv-vqos[0].bitStreamFormat` values (judgment from the codec order H.264, HEVC, AV1; UNKNOWN U6). +/// `x-nv-vqos[0].bitStreamFormat` values: 0 H.264, 1 HEVC, 2 AV1 as a host reads them (`docs/PROTOCOL.md` 2.5 \[M\]). const fn bitstream_format(codec: VideoCodec) -> u8 { match codec { VideoCodec::H264 => 0, diff --git a/crates/domistream/src/rtsp/server/announce.rs b/crates/domistream/src/rtsp/server/announce.rs index a12cc02..2cfb7df 100644 --- a/crates/domistream/src/rtsp/server/announce.rs +++ b/crates/domistream/src/rtsp/server/announce.rs @@ -7,6 +7,7 @@ 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). @@ -22,16 +23,16 @@ pub const MAX_ANNOUNCE_ATTRIBUTES: usize = 512; 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]). +/// 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]). +/// 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]). +/// 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]). +/// 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). @@ -45,13 +46,13 @@ pub enum ChromaSampling { #[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]. + /// launch call's `surroundAudioInfo` instead of `channels` and `channel_mask` \[M\]. pub enabled: bool, - /// `x-nv-audio.surround.numChannels`: 1..=8, default 2 [M]. + /// `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]. + /// `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]. + /// `x-nv-audio.surround.AudioQuality`: 0 or 1, default 1 (high quality) \[M\]. pub high_quality: bool, } @@ -76,31 +77,31 @@ pub struct StreamConfig { 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. + /// `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]). + /// `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. + /// `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 + /// `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*]): + /// `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]. + /// `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; + /// `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.*`. @@ -118,14 +119,220 @@ pub struct StreamConfig { /// 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 { - let _ = payload; - Err(Error::Unimplemented) + 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 { - let _ = (config, MAX_AUDIO_CHANNELS); - Vec::new() + 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 { + 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 { + 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>(value: u64) -> Result { + T::try_from(value).map_err(|_| Error::UnexpectedValue { what: "announce number", value }) } diff --git a/crates/domistream/src/rtsp/server/describe.rs b/crates/domistream/src/rtsp/server/describe.rs index ced4dcf..6013f52 100644 --- a/crates/domistream/src/rtsp/server/describe.rs +++ b/crates/domistream/src/rtsp/server/describe.rs @@ -1,9 +1,13 @@ //! 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, OpusConfig}; +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 { @@ -21,7 +25,7 @@ pub struct HostOffer { /// 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. + /// `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, @@ -31,7 +35,7 @@ pub struct HostOffer { pub opus_configs: Vec, } -/// Builds the DESCRIBE payload for `offer`, in the line order a known host uses (`docs/PROTOCOL.md` 2.5 [M]): +/// 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. /// @@ -41,6 +45,41 @@ pub struct HostOffer { /// streams); [`Error::TooLarge`] over [`crate::rtsp::sdp::MAX_OPUS_CONFIGS`]; [`Error::Unsupported`] when no codec /// is offered. pub fn build_describe(offer: &HostOffer) -> Result> { - let _ = offer; - Err(Error::Unimplemented) + 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 { + 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) } diff --git a/crates/domistream/src/rtsp/server/mod.rs b/crates/domistream/src/rtsp/server/mod.rs index 9b4eac6..fe769f0 100644 --- a/crates/domistream/src/rtsp/server/mod.rs +++ b/crates/domistream/src/rtsp/server/mod.rs @@ -21,11 +21,15 @@ pub use announce::{ }; pub use describe::{HostOffer, build_describe}; -use super::client::StreamPorts; +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]). +/// `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; @@ -89,6 +93,31 @@ pub struct ServerReply { pub struct RtspServer { config: ServerConfig, session_id: String, + /// The DESCRIBE payload, built once from the offer. + describe: Vec, + 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, + /// At most two events ever (one ANNOUNCE, one PLAY). + events: VecDeque, +} + +/// `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); + +/// A refused request: the status, the CSeq to echo if one was readable, and why. +struct Refusal { + status: u16, + cseq: Option, + error: Error, } impl RtspServer { @@ -98,25 +127,175 @@ impl RtspServer { /// [`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 { - let _ = (config, rng); - Err(Error::Unimplemented) + 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`]). + /// 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 { - let _ = message; - ServerReply { bytes: Vec::new(), status: 501, error: Some(Error::Unimplemented) } + 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 { + 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 { + 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 { - None + self.events.pop_front() } /// Which request the session expects next. #[must_use] pub const fn state(&self) -> RtspServerState { - RtspServerState::Options + self.state } /// The session id sent in SETUP answers. @@ -128,7 +307,7 @@ impl RtspServer { /// The accepted ANNOUNCE, once there is one. #[must_use] pub const fn announced(&self) -> Option<&StreamConfig> { - None + self.announced.as_ref() } /// The configuration the session answers with. @@ -137,3 +316,87 @@ impl RtspServer { &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, + extra: Vec<(String, String)>, + body: Vec, + error: Option, +) -> 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 { + 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 { + 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 { + 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")) +} diff --git a/crates/domistream/tests/alloc_caps.rs b/crates/domistream/tests/alloc_caps.rs index 2218dec..11dffb0 100644 --- a/crates/domistream/tests/alloc_caps.rs +++ b/crates/domistream/tests/alloc_caps.rs @@ -62,23 +62,12 @@ fn lying_inputs() -> Vec { )); v.push(( "rtsp server", - b"ANNOUNCE x RTSP/1.0 -CSeq: 1 -Content-Length: 4294967295 - -abc" - .to_vec(), + b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(), rtsp_server_answers, )); - // ANNOUNCE: numbers far past any range, a line that claims nothing but is long, many unknown attributes. - let mut announce = b"a=x-nv-video[0].clientViewportWd:99999999999999999999999999999999 -" - .to_vec(); - announce.extend_from_slice( - &b"a=u:1 -" - .repeat(600), - ); + // ANNOUNCE: a number far past any range, then more unknown attributes than the cap allows. + let mut announce = b"a=x-nv-video[0].clientViewportWd:99999999999999999999999999999999\n".to_vec(); + announce.extend_from_slice(&b"a=u:1\n".repeat(600)); v.push(("announce", announce, |b| common::implemented(&domistream::rtsp::server::parse_announce(b)))); v.push(("rtsp framer", rtsp, |b| { let mut f = domistream::rtsp::RtspFramer::new(); diff --git a/crates/domistream/tests/rtsp_server.rs b/crates/domistream/tests/rtsp_server.rs index 2a66a3d..bbad16f 100644 --- a/crates/domistream/tests/rtsp_server.rs +++ b/crates/domistream/tests/rtsp_server.rs @@ -249,6 +249,9 @@ fn client_stops_when_server_refuses_the_codec() { // ================================================================================================ scripted requests +/// One scripted request. +type Step = fn(&mut Script, &mut RtspServer) -> ServerReply; + /// Sends hand-made requests with counting CSeq values and, once known, the session id. struct Script { cseq: u32, @@ -314,7 +317,7 @@ impl Script { /// Valid requests until the server expects `state`. fn advance_to(&mut self, s: &mut RtspServer, state: RtspServerState) { - let steps: [(RtspServerState, fn(&mut Self, &mut RtspServer) -> ServerReply); 7] = [ + let steps: [(RtspServerState, Step); 7] = [ (RtspServerState::Options, Self::options), (RtspServerState::Describe, Self::describe), (RtspServerState::Setup, |sc, s| sc.setup(s, "audio")), @@ -384,7 +387,6 @@ fn session_timeout_is_configurable() { #[test] fn order_violations_get_455_and_change_nothing() { - type Step = fn(&mut Script, &mut RtspServer) -> ServerReply; let describe: Step = Script::describe; let setup: Step = |sc, s| sc.setup(s, "audio"); let announce: Step = |sc, s| sc.announce(s, &write_announce(&host_config())); @@ -440,7 +442,8 @@ fn options_at_any_time_and_setup_once_each() { #[test] fn setup_targets_and_transport() { - let cases: [(&str, &[(&str, &str)], u16); 9] = [ + type Case<'a> = (&'a str, &'a [(&'a str, &'a str)], u16); + let cases: [Case<'_>; 9] = [ ("streamid=video/0/0", &[("Transport", "x")], 200), ("rtsp://192.0.2.10:48010/streamid=video/0/0", &[("Transport", "x")], 200), ("streamid=video", &[("Transport", "x")], 200), @@ -553,7 +556,7 @@ fn cseq_is_echoed_and_required() { assert_refused(&reply, 400); assert!(matches!(reply.error, Some(Error::Malformed { .. })), "{bad:?}: {reply:?}"); } - assert_eq!(s.state(), RtspServerState::Options); + assert_eq!(s.state(), RtspServerState::Describe, "the accepted OPTIONS moved it; the refusals did not"); } #[test] @@ -748,14 +751,15 @@ fn describe_follows_the_offer() { #[test] fn describe_refuses_what_the_client_would_refuse() { - let mut bad = Vec::new(); - bad.push(OpusConfig { channels: 0, streams: 1, coupled_streams: 0, mapping: vec![] }); - bad.push(OpusConfig { channels: 2, streams: 0, coupled_streams: 0, mapping: vec![0, 0] }); - bad.push(OpusConfig { channels: 2, streams: 1, coupled_streams: 2, mapping: vec![0, 1] }); - bad.push(OpusConfig { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0] }); - bad.push(OpusConfig { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0, 2] }); - bad.push(OpusConfig { channels: 8, streams: 10, coupled_streams: 0, mapping: vec![0; 8] }); - bad.push(OpusConfig { channels: 2, streams: 12, coupled_streams: 1, mapping: vec![0, 10] }); + let bad = [ + OpusConfig { channels: 0, streams: 1, coupled_streams: 0, mapping: vec![] }, + OpusConfig { channels: 2, streams: 0, coupled_streams: 0, mapping: vec![0, 0] }, + OpusConfig { channels: 2, streams: 1, coupled_streams: 2, mapping: vec![0, 1] }, + OpusConfig { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0] }, + OpusConfig { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0, 2] }, + OpusConfig { channels: 8, streams: 10, coupled_streams: 0, mapping: vec![0; 8] }, + OpusConfig { channels: 2, streams: 12, coupled_streams: 1, mapping: vec![0, 10] }, + ]; for c in bad { let o = HostOffer { opus_configs: vec![c.clone()], ..offer() }; assert_err!(build_describe(&o), Error::Malformed { .. }, "{c:?}"); @@ -1254,7 +1258,9 @@ proptest! { /// Random request sequences: every answer parses and echoes CSeq, the status is one of the documented ones, the /// state only moves forward, and the events come at most once each, in order. #[test] - fn server_random_sequences(steps in proptest::collection::vec((0u8..7, 0u8..6, 0u8..3, 0u8..3, any::()), 0..24)) { + fn server_random_sequences( + steps in proptest::collection::vec((0u8..7, 0u8..6, 0u8..3, 0u8..3, any::()), 0..24), + ) { let mut s = server(); let id = s.session_id().to_string(); let good_announce = write_announce(&host_config()); @@ -1263,9 +1269,14 @@ proptest! { for (m, t, sess, body, cseq) in steps { let target = ["rtsp://192.0.2.10:48010", "streamid=audio/0/0", "streamid=video/0/0", "streamid=control/13/0", "streamid=bogus/0/0", "*"][usize::from(t)]; - let session = match sess { 1 => format!("Session: {id}\r\n"), 2 => "Session: nope\r\n".into(), _ => String::new() }; + let session = match sess { + 1 => format!("Session: {id}\r\n"), + 2 => "Session: nope\r\n".into(), + _ => String::new(), + }; let body: &[u8] = match body { 1 => &good_announce, 2 => b"v=0\r\nx\r\n", _ => b"" }; - let method = ["OPTIONS", "DESCRIBE", "SETUP", "ANNOUNCE", "PLAY", "TEARDOWN", "GARBAGE GARBAGE"][usize::from(m)]; + let methods = ["OPTIONS", "DESCRIBE", "SETUP", "ANNOUNCE", "PLAY", "TEARDOWN", "GARBAGE GARBAGE"]; + let method = methods[usize::from(m)]; let mut req = format!("{method} {target} RTSP/1.0\r\nCSeq: {cseq}\r\n{session}Transport: x\r\n"); if !body.is_empty() { req.push_str(&format!("Content-Length: {}\r\n", body.len())); -- 2.53.0 From fd4285aff07e15dccbc7cb3edff1a0b3ddc6d0cb Mon Sep 17 00:00:00 2001 From: mnovak Date: Fri, 4 Dec 2026 12:31:28 +0100 Subject: [PATCH 4/4] [domistream] RTSP server: PROTOCOL.md 2.5 (host side, ANNOUNCE required/defaulted table), clean-room sources S-30 to S-32 --- docs/CLEAN_ROOM.md | 5 ++++ docs/PROTOCOL.md | 70 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/docs/CLEAN_ROOM.md b/docs/CLEAN_ROOM.md index 6fd44e6..4d6e33a 100644 --- a/docs/CLEAN_ROOM.md +++ b/docs/CLEAN_ROOM.md @@ -51,6 +51,8 @@ copied into DomiStream, and settled by our own measurement instead. Known cases: | `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it | | fec-rs `src/reed_solomon.rs` tests (`test_partial_eq_reflects_parity_matrix_changes`) | the same audio parity matrix as Moonshine's encoder | Not taken, same rule. Seen while reading fec-rs on 2026-11-25. | | `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source | +| `src/rtsp.rs` (read again as S-30) | `encoderCscMode` bit layout (comment cites Sunshine's colour-space function); `maxNumReferenceFrames` 0 = "host's choice" (comment cites moonlight-common-c); the 5.1/7.1 mapping rotation (comment cites GFE and Moonlight) | Not taken: the host parser keeps both numbers raw and writes the mappings as configured (PROTOCOL.md 2.5, U6, U26) | +| `src/session/stream/video/mod.rs` (S-31) | how the stored bitrate is reduced for FEC and audio (comment: "as Sunshine computes it") | Not taken; the parser hands over the client's bitrate unchanged | ## How code gets written @@ -91,3 +93,6 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea | S-23 | 2026-12-04 | NVIDIA [video-sdk-samples](https://github.com/NVIDIA/video-sdk-samples) at `aa3544d`: `Samples/NvCodec/NvEncoder/nvEncodeAPI.h` (API 8.1, sha256 `4d061c34…6042a`); NVIDIA [VideoProcessingFramework](https://github.com/NVIDIA/VideoProcessingFramework) at `e82364f`: `src/TC/third_party/nvEncodeAPI.h` (API 12.0, sha256 `067c5159…b4ad`); GitHub repository metadata of both | Both headers carry NVIDIA's MIT notice for the header file; the repositories are Apache-2.0 / unlicensed samples and the second is archived. Declarations used for the L0 spike shim (struct versions, preset and tuning enums, `NvEncGetEncodePresetConfigEx`, resource registration). No sample `.cpp` file was opened. | | S-24 | 2026-12-04 | [NVENC Video Encoder API Programming Guide](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvenc-video-encoder-api-prog-guide/index.html) (SDK 13.0) | Loading `nvEncodeAPI` at run time and `NvEncodeAPICreateInstance`; `NV_ENC_DEVICE_TYPE_DIRECTX` sessions; registering, mapping and unmapping D3D11 textures; tuning info (low latency, ultra low latency), presets P1-P7, CBR filler, forcing IDR, `NvEncInvalidateRefFrames`, intra refresh, look-ahead latency; lock/unlock of the bitstream; async mode only on Windows 10+ WDDM, recommended there; Main10 settings. | | S-25 | 2026-12-04 | Licences via the GitHub and crates.io APIs and `COPYING` files: nefarius/ViGEmClient (MIT, archived), nefarius/ViGEmBus (BSD-3-Clause, archived), xiph/opus `COPYING` (BSD-style), crates `opus`, `audiopus_sys`, `vigem-client`, `nvidia-video-codec-sdk`, `nvenc`, `windows` | Licence and status only; no source files of these projects were opened. | +| S-30 | 2026-12-04 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e3693e09c3a6ab1025bde6cdb67f36a6bc` (same pin as S-9): `src/rtsp.rs` again, read for the host side | BSD-2, facts only. One request per TCP connection, the note that Moonlight opens a connection per request; `CSeq` required (connection closed without it); no method order and no `Session` check; statuses 200/400/500 only; OPTIONS `Public`; SETUP needs `Transport` (400 without), stream from the first `streamid=` query segment, answer `Session: MoonshineSession;timeout = 90` and `Transport: server_port=`; 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). | diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 26d1088..0738bef 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -221,6 +221,76 @@ SDP attribute lines `a=:`. Names the host reads [M]; values and the Settle U6: lab capture of an ANNOUNCE accepted by Sunshine, then vary one attribute at a time. +### 2.5 Host side (Lumen): `rtsp::server` + +Facts from Moonshine's host code (`src/rtsp.rs`, `src/session/stream/video/mod.rs` at `f184d5e`, S-30, S-31) and +RFC 2326 (S-32); our own choices are marked as such. + +**Connections and framing.** Moonshine reads one request per TCP connection and notes that Moonlight opens a +connection per request [M]. So the host's state belongs to the launched session, not to a connection: every +connection of that session feeds the same `RtspServer` (UNKNOWN U5 for other clients). A request without +`Content-Length` has no payload (RFC 2326 4.4); the host's framer (`RtspFramer::for_requests`) ends it at the empty +line. Every answer carries `Content-Length` (ours), so the client never waits for a close. Moonshine needs a parseable +`CSeq` and closes without an answer when it is missing [M]; we answer 400 and let the caller close. + +**Order and statuses.** Moonshine checks no order and no `Session` [M]. We enforce 2.2: OPTIONS, DESCRIBE, the three +SETUPs (any order, each once: ours, U5), ANNOUNCE, PLAY. OPTIONS may come at any time and changes nothing else +(RFC 2326 10.1). Moonshine answers only 200, 400 and 500 [M]; we use the RFC 2326 7.1.1 codes: 400 malformed request +or ANNOUNCE payload, 451 a request the offer does not cover (codec, encryption bits, HDR, 4:4:4), 454 a `Session` +that is not this session's, 455 a method out of order, 501 an unknown method (TEARDOWN, GET_PARAMETER...). A refused +request changes no state; the caller decides whether to close. + +**Session.** Moonshine sends the fixed id `MoonshineSession` and never reads it back [M]. We send a random id +(8 bytes from the caller's `RandomSource`, hex; RFC 2326 3.4 asks for at least 8 random octets) as +`Session: ;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=` of the target (400 otherwise) and answers `Session` and +`Transport: server_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) -- 2.53.0