//! 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 { cap("announce", MAX_ANNOUNCE_BYTES, payload.len())?; let text = core::str::from_utf8(payload).map_err(|_| malformed("announce: not UTF-8"))?; let mut values: [Option<&str>; ATTRIBUTES.len()] = [None; ATTRIBUTES.len()]; let mut lines = 0usize; let mut attributes = 0usize; let mut unknown = 0u32; for raw in text.split('\n') { let line = raw.strip_suffix('\r').unwrap_or(raw); cap("announce line", MAX_ANNOUNCE_LINE_BYTES, line.len())?; if line.is_empty() { continue; } lines += 1; cap("announce lines", MAX_ANNOUNCE_LINES, lines)?; if line.bytes().any(|b| b.is_ascii_control() && b != b'\t') { return Err(malformed("announce: control character in a line")); } let (kind, rest) = line.split_once('=').ok_or(malformed("announce: line without ="))?; if kind.is_empty() { return Err(malformed("announce: line with an empty type")); } // Only `a=` lines carry settings; `v=`, `o=`, `s=`, `t=`, `m=` and bare lines are not read. if kind != "a" { continue; } attributes += 1; cap("announce attributes", MAX_ANNOUNCE_ATTRIBUTES, attributes)?; let (name, value) = rest.split_once(':').unwrap_or((rest, "")); match ATTRIBUTES.iter().position(|a| a.name == name).and_then(|i| values.get_mut(i)) { Some(Some(_)) => return Err(malformed("announce: an attribute given twice")), Some(slot) => *slot = Some(value.trim_matches([' ', '\t'])), None => unknown = unknown.saturating_add(1), } } let a = Values(&values); let codec = match a.required(BIT_STREAM_FORMAT, 0, 2)? { 0 => VideoCodec::H264, 1 => VideoCodec::Hevc, _ => VideoCodec::Av1, }; Ok(StreamConfig { width: narrow(a.required(VIEWPORT_WD, 1, u64::from(MAX_DIMENSION))?)?, height: narrow(a.required(VIEWPORT_HT, 1, u64::from(MAX_DIMENSION))?)?, max_fps: narrow(a.required(MAX_FPS_ATTR, 1, u64::from(MAX_FPS))?)?, packet_size: narrow(a.required(PACKET_SIZE, u64::from(MIN_PACKET_SIZE), u64::from(MAX_PACKET_SIZE))?)?, bitrate_kbps: narrow(a.required(BITRATE, 1, u64::from(MAX_BITRATE_KBPS))?)?, codec, min_fec_packets: narrow(a.required(MIN_FEC_PACKETS, 0, u64::from(u8::MAX))?)?, video_qos_traffic_type: narrow(a.required(VIDEO_QOS, 0, u64::from(u32::MAX))?)?, audio_packet_duration_ms: narrow(a.required(PACKET_DURATION, 1, u64::from(MAX_AUDIO_PACKET_DURATION_MS))?)?, audio_qos_traffic_type: narrow(a.required(AUDIO_QOS, 0, u64::from(u32::MAX))?)?, max_reference_frames: narrow(a.optional(MAX_REFERENCE_FRAMES, 1, 0, u64::from(u32::MAX))?)?, reference_frame_invalidation: a.optional(REF_PIC_INVALIDATION, 0, 0, 1)? == 1, dynamic_range_mode: narrow(a.optional(DYNAMIC_RANGE_MODE, 0, 0, u64::from(u32::MAX))?)?, encoder_csc_mode: narrow(a.optional(ENCODER_CSC_MODE, 0, 0, u64::from(u32::MAX))?)?, chroma: if a.optional(CHROMA_SAMPLING, 0, 0, 1)? == 1 { ChromaSampling::Yuv444 } else { ChromaSampling::Yuv420 }, encryption: EncryptionFlags(narrow(a.optional(ENCRYPTION_ENABLED, 0, 0, u64::from(u8::MAX))?)?), surround: SurroundSettings { enabled: a.optional(SURROUND_ENABLE, 0, 0, 1)? == 1, channels: narrow(a.optional(SURROUND_CHANNELS, 2, 1, MAX_AUDIO_CHANNELS as u64)?)?, channel_mask: narrow(a.optional(SURROUND_MASK, 0x3, 0, u64::from(u32::MAX))?)?, high_quality: a.optional(AUDIO_QUALITY, 1, 0, 1)? == 1, }, unknown_attributes: unknown, }) } /// Writes `config` as an ANNOUNCE payload (`v=0`, then every known attribute, CRLF line ends) that /// [`parse_announce`] reads back as the same config (with `unknown_attributes` 0). #[must_use] pub fn write_announce(config: &StreamConfig) -> Vec { let codec: u8 = match config.codec { VideoCodec::H264 => 0, VideoCodec::Hevc => 1, VideoCodec::Av1 => 2, }; let chroma: u8 = match config.chroma { ChromaSampling::Yuv420 => 0, ChromaSampling::Yuv444 => 1, }; let s = &config.surround; let values: [(usize, u64); ATTRIBUTES.len()] = [ (VIEWPORT_WD, u64::from(config.width)), (VIEWPORT_HT, u64::from(config.height)), (MAX_FPS_ATTR, u64::from(config.max_fps)), (PACKET_SIZE, u64::from(config.packet_size)), (BITRATE, u64::from(config.bitrate_kbps)), (BIT_STREAM_FORMAT, u64::from(codec)), (MIN_FEC_PACKETS, u64::from(config.min_fec_packets)), (VIDEO_QOS, u64::from(config.video_qos_traffic_type)), (PACKET_DURATION, u64::from(config.audio_packet_duration_ms)), (AUDIO_QOS, u64::from(config.audio_qos_traffic_type)), (MAX_REFERENCE_FRAMES, u64::from(config.max_reference_frames)), (REF_PIC_INVALIDATION, u64::from(config.reference_frame_invalidation)), (DYNAMIC_RANGE_MODE, u64::from(config.dynamic_range_mode)), (ENCODER_CSC_MODE, u64::from(config.encoder_csc_mode)), (CHROMA_SAMPLING, u64::from(chroma)), (ENCRYPTION_ENABLED, u64::from(config.encryption.0)), (SURROUND_ENABLE, u64::from(s.enabled)), (SURROUND_CHANNELS, u64::from(s.channels)), (SURROUND_MASK, u64::from(s.channel_mask)), (AUDIO_QUALITY, u64::from(s.high_quality)), ]; let mut out = String::with_capacity(1024); out.push_str("v=0\r\n"); for (index, value) in values { if let Some(attribute) = ATTRIBUTES.get(index) { out.push_str("a="); out.push_str(attribute.name); out.push(':'); out.push_str(&value.to_string()); out.push_str("\r\n"); } } out.into_bytes() } /// One attribute the host reads (`docs/PROTOCOL.md` 2.4, 2.5). struct Attribute { /// The SDP attribute name. name: &'static str, /// The error text when a required attribute is missing; `None` for attributes with a default. missing: Option<&'static str>, } const fn required(name: &'static str, missing: &'static str) -> Attribute { Attribute { name, missing: Some(missing) } } const fn defaulted(name: &'static str) -> Attribute { Attribute { name, missing: None } } const VIEWPORT_WD: usize = 0; const VIEWPORT_HT: usize = 1; const MAX_FPS_ATTR: usize = 2; const PACKET_SIZE: usize = 3; const BITRATE: usize = 4; const BIT_STREAM_FORMAT: usize = 5; const MIN_FEC_PACKETS: usize = 6; const VIDEO_QOS: usize = 7; const PACKET_DURATION: usize = 8; const AUDIO_QOS: usize = 9; const MAX_REFERENCE_FRAMES: usize = 10; const REF_PIC_INVALIDATION: usize = 11; const DYNAMIC_RANGE_MODE: usize = 12; const ENCODER_CSC_MODE: usize = 13; const CHROMA_SAMPLING: usize = 14; const ENCRYPTION_ENABLED: usize = 15; const SURROUND_ENABLE: usize = 16; const SURROUND_CHANNELS: usize = 17; const SURROUND_MASK: usize = 18; const AUDIO_QUALITY: usize = 19; /// Every attribute read, in the order of the index constants above. The required set is the one a known host /// refuses to stream without (`docs/PROTOCOL.md` 2.5 \[M\]); the others have the defaults documented on /// [`StreamConfig`]. const ATTRIBUTES: [Attribute; 20] = [ required("x-nv-video[0].clientViewportWd", "announce: x-nv-video[0].clientViewportWd missing"), required("x-nv-video[0].clientViewportHt", "announce: x-nv-video[0].clientViewportHt missing"), required("x-nv-video[0].maxFPS", "announce: x-nv-video[0].maxFPS missing"), required("x-nv-video[0].packetSize", "announce: x-nv-video[0].packetSize missing"), required("x-ml-video.configuredBitrateKbps", "announce: x-ml-video.configuredBitrateKbps missing"), required("x-nv-vqos[0].bitStreamFormat", "announce: x-nv-vqos[0].bitStreamFormat missing"), required("x-nv-vqos[0].fec.minRequiredFecPackets", "announce: x-nv-vqos[0].fec.minRequiredFecPackets missing"), required("x-nv-vqos[0].qosTrafficType", "announce: x-nv-vqos[0].qosTrafficType missing"), required("x-nv-aqos.packetDuration", "announce: x-nv-aqos.packetDuration missing"), required("x-nv-aqos.qosTrafficType", "announce: x-nv-aqos.qosTrafficType missing"), defaulted("x-nv-video[0].maxNumReferenceFrames"), defaulted("x-nv-video[0].refPicInvalidation"), defaulted("x-nv-video[0].dynamicRangeMode"), defaulted("x-nv-video[0].encoderCscMode"), defaulted("x-ss-video[0].chromaSamplingType"), defaulted("x-ss-general.encryptionEnabled"), defaulted("x-nv-audio.surround.enable"), defaulted("x-nv-audio.surround.numChannels"), defaulted("x-nv-audio.surround.channelMask"), defaulted("x-nv-audio.surround.AudioQuality"), ]; /// The values found, one slot per entry of [`ATTRIBUTES`]. struct Values<'a, 'b>(&'a [Option<&'b str>; ATTRIBUTES.len()]); impl Values<'_, '_> { /// The attribute's number in `lo..=hi`, or `default` when it is absent. fn optional(&self, index: usize, default: u64, lo: u64, hi: u64) -> Result { let name = ATTRIBUTES.get(index).map_or("announce attribute", |a| a.name); match self.0.get(index).copied().flatten() { None => Ok(default), Some(text) => { let value = parse_dec(name, text)?; if value < lo || value > hi { return Err(Error::UnexpectedValue { what: name, value }); } Ok(value) } } } /// The attribute's number in `lo..=hi`; refused when absent. fn required(&self, index: usize, lo: u64, hi: u64) -> Result { if self.0.get(index).copied().flatten().is_none() { let what = ATTRIBUTES.get(index).and_then(|a| a.missing).unwrap_or("announce: attribute missing"); return Err(malformed(what)); } self.optional(index, 0, lo, hi) } } /// A range-checked number into its field type (cannot fail after the range check; never panics either way). fn narrow>(value: u64) -> Result { T::try_from(value).map_err(|_| Error::UnexpectedValue { what: "announce number", value }) }