//! The SDP-like payloads of DESCRIBE (host → client) and ANNOUNCE (client → host) (`docs/PROTOCOL.md` 2.3, 2.4). use super::client::{StreamConfig, VideoCodec}; use crate::util::{cap, malformed, parse_u8, parse_u32}; use crate::{Error, Result}; /// Maximum size of an SDP payload, in bytes. pub const MAX_SDP_BYTES: usize = 32 * 1024; /// Maximum number of lines in an SDP payload. pub const MAX_SDP_LINES: usize = 1024; /// Maximum number of Opus configurations a host may advertise. pub const MAX_OPUS_CONFIGS: usize = 16; /// Maximum number of audio channels (7.1). pub const MAX_AUDIO_CHANNELS: usize = 8; /// A parsed SDP payload: `a=name:value` attributes plus every other `x=value` line, in order. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Sdp { /// `a=` attributes: name and value (value empty for flag attributes). pub attributes: Vec<(String, String)>, /// Other lines: type character and value (e.g. `('v', "0")`), and bare lines such as `sprop-parameter-sets=…` /// with type `'\0'`. pub other: Vec<(char, String)>, } impl Sdp { /// The first attribute with this exact name. #[must_use] pub fn attribute(&self, name: &str) -> Option<&str> { self.attributes.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str()) } } /// Parses an SDP payload. Lines end in LF or CRLF; empty lines are skipped. /// /// # Errors /// [`Error::TooLarge`] over [`MAX_SDP_BYTES`] or [`MAX_SDP_LINES`], [`Error::Malformed`] for a payload that is not /// UTF-8 or a line without `=` or with an empty type. pub fn parse_sdp(payload: &[u8]) -> Result { cap("sdp", MAX_SDP_BYTES, payload.len())?; let text = core::str::from_utf8(payload).map_err(|_| malformed("sdp: not UTF-8"))?; let mut sdp = Sdp::default(); let mut lines = 0usize; for raw in text.split('\n') { let line = raw.strip_suffix('\r').unwrap_or(raw); if line.is_empty() { continue; } lines += 1; cap("sdp lines", MAX_SDP_LINES, lines)?; let (kind, value) = line.split_once('=').ok_or(malformed("sdp line without ="))?; if kind.is_empty() { return Err(malformed("sdp line with an empty type")); } if kind == "a" { let (name, value) = value.split_once(':').unwrap_or((value, "")); sdp.attributes.push((name.to_owned(), value.to_owned())); } else { let mut chars = kind.chars(); match (chars.next(), chars.next()) { (Some(c), None) => sdp.other.push((c, value.to_owned())), _ => sdp.other.push(('\0', line.to_owned())), } } } Ok(sdp) } /// Encryption flag bits of `x-ss-general.encryptionSupported` / `encryptionEnabled`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct EncryptionFlags(pub u8); impl EncryptionFlags { /// Control stream V2 framing with AES-GCM. pub const CONTROL_V2: u8 = 0x01; /// Video AES-GCM. pub const VIDEO: u8 = 0x02; /// Audio AES-CBC. pub const AUDIO: u8 = 0x04; /// Whether every bit of `flags` is set. #[must_use] pub const fn contains(self, flags: u8) -> bool { self.0 & flags == flags } } /// Feature flag bits of `x-ss-general.featureFlags`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct FeatureFlags(pub u32); impl FeatureFlags { /// The host accepts pen and touch events. pub const PEN_TOUCH_EVENTS: u32 = 0x01; /// The host accepts controller touch events. pub const CONTROLLER_TOUCH_EVENTS: u32 = 0x02; } /// One Opus multistream configuration (RFC 7845 §5.1.1), for the platform's Opus decoder. #[derive(Clone, Debug, PartialEq, Eq)] pub struct OpusConfig { /// Output channels (2, 6 or 8). pub channels: u8, /// Opus streams per packet. pub streams: u8, /// Of which coupled (stereo) streams. pub coupled_streams: u8, /// Channel mapping, one entry per channel. pub mapping: Vec, } impl OpusConfig { /// Plain stereo: 2 channels, 1 coupled stream, mapping 0 1 (Wolf's `21101`). #[must_use] pub fn stereo() -> Self { Self { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0, 1] } } } /// Parses one `surround-params` value (single digits: channels, streams, coupled, then one mapping digit per /// channel), e.g. `21101`. /// /// # Errors /// [`Error::Malformed`] for a non-digit, a wrong length, or values that break RFC 7845's rules /// (`1 ≤ channels ≤ 8`, `streams ≥ 1`, `coupled ≤ streams`, mapping entries `< streams + coupled`). pub fn parse_surround_params(value: &str) -> Result { let digits: Vec = value .bytes() .map(|b| if b.is_ascii_digit() { Some(b - b'0') } else { None }) .collect::>>() .ok_or(malformed("surround-params"))?; let (&channels, &streams, &coupled) = match digits.as_slice() { [c, s, k, ..] => (c, s, k), _ => return Err(malformed("surround-params")), }; let mapping = digits.get(3..).unwrap_or(&[]); if channels == 0 || usize::from(channels) > MAX_AUDIO_CHANNELS || streams == 0 || coupled > streams || mapping.len() != usize::from(channels) || mapping.iter().any(|&m| m >= streams + coupled) { return Err(malformed("surround-params")); } Ok(OpusConfig { channels, streams, coupled_streams: coupled, mapping: mapping.to_vec() }) } /// What the host offers, read from the DESCRIBE payload. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct HostCapabilities { /// `x-ss-general.encryptionSupported`. pub encryption_supported: EncryptionFlags, /// `x-ss-general.featureFlags`. pub feature_flags: FeatureFlags, /// `x-nv-video[0].refPicInvalidation:1`. pub reference_frame_invalidation: bool, /// `rtpmap:98 AV1/90000` present. pub av1: bool, /// Every `fmtp:97 surround-params=…`, in order. pub opus_configs: Vec, } impl HostCapabilities { /// Reads the capabilities from a DESCRIBE payload. /// /// # Errors /// [`Error::Malformed`] for a present attribute with a bad value, [`Error::TooLarge`] over /// [`MAX_OPUS_CONFIGS`]. pub fn from_sdp(sdp: &Sdp) -> Result { let mut caps = Self::default(); if let Some(v) = sdp.attribute("x-ss-general.encryptionSupported") { caps.encryption_supported = EncryptionFlags(parse_u8("sdp encryptionSupported", v)?); } if let Some(v) = sdp.attribute("x-ss-general.featureFlags") { caps.feature_flags = FeatureFlags(parse_u32("sdp featureFlags", v)?); } caps.reference_frame_invalidation = sdp.attribute("x-nv-video[0].refPicInvalidation") == Some("1"); caps.av1 = sdp .attributes .iter() .any(|(n, v)| n == "rtpmap" && v.split_whitespace().nth(1).is_some_and(|c| c.starts_with("AV1/"))); for (_, v) in sdp.attributes.iter().filter(|(n, _)| n == "fmtp") { let Some(params) = v.strip_prefix("97 ") else { continue }; for p in params.split(';').map(str::trim) { if let Some(digits) = p.strip_prefix("surround-params=") { caps.opus_configs.push(parse_surround_params(digits)?); cap("sdp opus configurations", MAX_OPUS_CONFIGS, caps.opus_configs.len())?; } } } Ok(caps) } /// The first configuration with `channels` channels, or plain stereo when the host lists none for it. #[must_use] pub fn opus_for(&self, channels: u8) -> OpusConfig { self.opus_configs.iter().find(|c| c.channels == channels).cloned().unwrap_or_else(OpusConfig::stereo) } } /// `x-nv-vqos[0].bitStreamFormat` values (judgment from the codec order H.264, HEVC, AV1; UNKNOWN U6). const fn bitstream_format(codec: VideoCodec) -> u8 { match codec { VideoCodec::H264 => 0, VideoCodec::Hevc => 1, VideoCodec::Av1 => 2, } } /// The encryption flags an ANNOUNCE turns on: what both sides support. Control V2 is required. /// /// # Errors /// [`Error::Unsupported`] when the host or the client config lacks control V2 encryption. pub fn negotiated_encryption(config: &StreamConfig, host: &HostCapabilities) -> Result { let flags = EncryptionFlags(config.encryption.0 & host.encryption_supported.0); if !flags.contains(EncryptionFlags::CONTROL_V2) { return Err(Error::Unsupported { what: "control stream encryption (V2)" }); } Ok(flags) } /// Builds the ANNOUNCE payload for `config`, turning on the encryption flags both sides support. /// /// # Errors /// [`Error::Unsupported`] when the host lacks control V2 encryption or the requested codec. pub fn build_announce(config: &StreamConfig, host: &HostCapabilities) -> Result> { let enabled = negotiated_encryption(config, host)?; if config.codec == VideoCodec::Av1 && !host.av1 { return Err(Error::Unsupported { what: "AV1 video" }); } let channels = config.audio.channels(); let attrs: [(&str, String); 19] = [ ("x-nv-video[0].clientViewportWd", config.width.to_string()), ("x-nv-video[0].clientViewportHt", config.height.to_string()), ("x-nv-video[0].maxFPS", config.fps.to_string()), ("x-nv-video[0].packetSize", config.packet_size.to_string()), ("x-nv-video[0].maxNumReferenceFrames", if config.reference_frame_invalidation { "0" } else { "1" }.into()), ("x-nv-video[0].refPicInvalidation", u8::from(config.reference_frame_invalidation).to_string()), ("x-nv-video[0].dynamicRangeMode", u8::from(config.hdr).to_string()), ("x-nv-video[0].encoderCscMode", if config.hdr { "5" } else { "0" }.into()), ("x-nv-vqos[0].bitStreamFormat", bitstream_format(config.codec).to_string()), ("x-nv-vqos[0].fec.minRequiredFecPackets", config.min_fec_packets.to_string()), ("x-nv-vqos[0].qosTrafficType", "5".into()), ("x-ml-video.configuredBitrateKbps", config.bitrate_kbps.to_string()), ("x-nv-aqos.packetDuration", config.audio_packet_duration_ms.to_string()), ("x-nv-aqos.qosTrafficType", "4".into()), ("x-nv-audio.surround.enable", u8::from(channels > 2).to_string()), ("x-nv-audio.surround.numChannels", channels.to_string()), ("x-nv-audio.surround.channelMask", config.audio.channel_mask().to_string()), ("x-ss-video[0].chromaSamplingType", "0".into()), ("x-ss-general.encryptionEnabled", enabled.0.to_string()), ]; let mut out = String::from("v=0\r\n"); for (name, value) in &attrs { out.push_str("a="); out.push_str(name); out.push(':'); out.push_str(value); out.push_str("\r\n"); } Ok(out.into_bytes()) }