[domistream] RTSP server: tests first (in-memory client/server session, order, Session, ANNOUNCE parser, DESCRIBE writer, caps); API stubs return Unimplemented

This commit is contained in:
2026-12-04 12:23:48 +01:00
parent 33b7b90b65
commit 54bc9f5faf
6 changed files with 1720 additions and 8 deletions
+33 -8
View File
@@ -1,11 +1,13 @@
//! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP,
//! 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 <status> <reason>`, CRLF line ends, empty line, payload) with exactly the
/// given headers. The host side's mirror of [`RtspRequest::encode`].
///
/// # Errors
/// [`Error::Malformed`] for a status outside 100..=999, CR, LF or another control character in the reason, a
/// header name that is not a token, or CR or LF in a header value; [`Error::TooLarge`] over
/// [`MAX_RTSP_MESSAGE_BYTES`].
pub fn encode(&self) -> Result<Vec<u8>> {
Err(Error::Unimplemented)
}
}
/// A message split into start line, headers and payload.
@@ -252,21 +265,31 @@ pub fn parse_request(message: &[u8]) -> Result<RtspRequest> {
Ok(RtspRequest { method, target: target.to_owned(), headers: m.headers, body: m.body })
}
/// Cuts the TCP byte stream from the host into whole messages.
/// Cuts a TCP byte stream into whole messages.
///
/// A message ends after its headers plus `Content-Length` payload bytes; without `Content-Length` it ends when
/// the host closes the connection ([`RtspFramer::finish`]) (UNKNOWN U5). Never buffers more than
/// [`MAX_RTSP_MESSAGE_BYTES`].
/// A message ends after its headers plus `Content-Length` payload bytes. Without `Content-Length`, a framer made
/// with [`RtspFramer::new`] (the client reading the host's answers) ends the message when the host closes the
/// connection ([`RtspFramer::finish`]) (UNKNOWN U5); one made with [`RtspFramer::for_requests`] (the host reading
/// a client's requests) takes a missing `Content-Length` as zero, as RFC 2326 section 4.4 says, so the message
/// ends at the empty line (`docs/PROTOCOL.md` 2.5). Never buffers more than [`MAX_RTSP_MESSAGE_BYTES`].
#[derive(Debug, Default)]
pub struct RtspFramer {
buffer: Vec<u8>,
/// A missing `Content-Length` means "no payload" (requests) instead of "until close" (answers).
missing_length_is_zero: bool,
}
impl RtspFramer {
/// An empty framer.
/// An empty framer for the host's answers (client side).
#[must_use]
pub const fn new() -> Self {
Self { buffer: Vec::new() }
Self { buffer: Vec::new(), missing_length_is_zero: false }
}
/// An empty framer for a client's requests (host side): a request without `Content-Length` has no payload.
#[must_use]
pub const fn for_requests() -> Self {
Self { buffer: Vec::new(), missing_length_is_zero: true }
}
/// Appends received bytes.
@@ -293,7 +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.
@@ -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<StreamConfig> {
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<u8> {
let _ = (config, MAX_AUDIO_CHANNELS);
Vec::new()
}
@@ -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<OpusConfig>,
}
/// Builds the DESCRIBE payload for `offer`, in the line order a known host uses (`docs/PROTOCOL.md` 2.5 [M]):
/// feature flags, encryption, `sprop-parameter-sets`, reference invalidation, AV1, H.264, then one
/// `surround-params` line per Opus configuration. CRLF line ends.
///
/// # Errors
/// [`Error::Malformed`] for an Opus configuration that the client's `surround-params` parser would refuse (more
/// than 8 channels, a mapping entry or count above 9, a wrong mapping length, no streams, more coupled streams than
/// streams); [`Error::TooLarge`] over [`crate::rtsp::sdp::MAX_OPUS_CONFIGS`]; [`Error::Unsupported`] when no codec
/// is offered.
pub fn build_describe(offer: &HostOffer) -> Result<Vec<u8>> {
let _ = offer;
Err(Error::Unimplemented)
}
+139
View File
@@ -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=<port>`).
pub ports: StreamPorts,
/// What DESCRIBE offers and ANNOUNCE is checked against.
pub offer: HostOffer,
/// Encryption the client must turn on in ANNOUNCE (Lumen: at least control V2); must be offered.
pub required_encryption: EncryptionFlags,
/// Refuse requests after the first SETUP that carry no `Session` header. Off by default: whether clients echo
/// it is UNKNOWN U5, and a known host does not read it (`docs/PROTOCOL.md` 2.5). A `Session` that is present is
/// always checked.
pub require_session_header: bool,
/// `timeout` in the `Session` header, seconds, 1.. ([`DEFAULT_SESSION_TIMEOUT_SECS`]).
pub session_timeout_secs: u32,
}
/// Which request the session expects next.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RtspServerState {
/// OPTIONS.
Options,
/// DESCRIBE.
Describe,
/// SETUP of the streams not set up yet.
Setup,
/// ANNOUNCE.
Announce,
/// PLAY.
Play,
/// PLAY answered: the streams start. Only OPTIONS is still answered with 200.
Playing,
}
/// What the session tells the caller.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ServerEvent {
/// ANNOUNCE accepted: the stream settings the client asked for.
Announced(StreamConfig),
/// PLAY accepted: start the streams (video and audio wait for the client's PING, control for ENet).
PlayRequested,
}
/// The answer to one request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerReply {
/// The whole RTSP answer to write to the connection.
pub bytes: Vec<u8>,
/// Its status code (200, or 400, 451, 454, 455 or 501).
pub status: u16,
/// Why the request was refused; `None` with status 200.
pub error: Option<Error>,
}
/// The host side of one session's RTSP negotiation.
#[derive(Debug)]
pub struct RtspServer {
config: ServerConfig,
session_id: String,
}
impl RtspServer {
/// Checks `config` and draws a fresh session id from `rng`.
///
/// # Errors
/// [`Error::Malformed`] for a zero port or session timeout, or required encryption the offer lacks; any error
/// of [`build_describe`] for the offer.
pub fn new(config: ServerConfig, rng: &mut dyn RandomSource) -> Result<Self> {
let _ = (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<ServerEvent> {
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
}
}
+45
View File
@@ -60,6 +60,26 @@ fn lying_inputs() -> Vec<Case> {
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|b| common::implemented(&domistream::rtsp::parse_request(b)),
));
v.push((
"rtsp server",
b"ANNOUNCE x RTSP/1.0
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<Case> {
v
}
/// A fresh host RTSP session answers `b`; false only for an `Unimplemented` answer.
fn rtsp_server_answers(b: &[u8]) -> bool {
let config = domistream::rtsp::ServerConfig {
ports: domistream::rtsp::StreamPorts { audio: 48000, video: 47998, control: 47999 },
offer: domistream::rtsp::HostOffer {
feature_flags: domistream::rtsp::sdp::FeatureFlags(3),
encryption_supported: domistream::rtsp::EncryptionFlags(7),
reference_frame_invalidation: true,
h264: true,
hevc: true,
av1: true,
hdr: false,
yuv444: false,
opus_configs: vec![domistream::rtsp::OpusConfig::stereo()],
},
required_encryption: domistream::rtsp::EncryptionFlags(1),
require_session_header: false,
session_timeout_secs: 90,
};
let Ok(mut s) = domistream::rtsp::RtspServer::new(config, &mut common::SeqRng::new(3)) else { return false };
s.handle_request(b).error != Some(domistream::Error::Unimplemented)
}
/// Stateful receivers: the bound is their caps (frames or blocks in flight), never a claimed size.
fn depacketizer_checks() {
use domistream::video::{MAX_FRAME_BYTES, MAX_FRAMES_IN_FLIGHT, VideoConfig, VideoDepacketizer};
@@ -225,6 +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))),
File diff suppressed because it is too large Load Diff