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); +}