Compare commits

..

5 Commits

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