[domistream] Implementation: HTTP, pairing, RTSP/SDP, ENet, control, input, RTP, FEC, video and audio receivers

Per PROTOCOL.md and the Wolf docs; interop with a real host is unverified. Strict, capped parsers throughout,
shared helpers in util.rs. Where PROTOCOL.md says UNKNOWN the Wolf-documented behaviour is used. The audio
receiver waits for the jitter budget before rebuilding a missing packet, so a late packet beats a rebuilt one.
This commit is contained in:
2026-11-25 14:10:24 +01:00
parent 27b26a992b
commit 30a7b90034
27 changed files with 4175 additions and 406 deletions
+160 -23
View File
@@ -1,6 +1,8 @@
//! The SDP-like payloads of DESCRIBE (host → client) and ANNOUNCE (client → host) (`docs/PROTOCOL.md` 2.3, 2.4).
use super::client::StreamConfig;
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;
@@ -29,14 +31,39 @@ impl Sdp {
}
}
/// Parses an SDP payload. Lines end in LF or CRLF.
/// Parses an SDP payload. Lines end in LF or CRLF; empty lines are skipped.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_SDP_BYTES`] or [`MAX_SDP_LINES`], [`crate::Error::Malformed`] for a line
/// that is not UTF-8 or has no `=`. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_sdp(payload: &[u8]) -> crate::Result<Sdp> {
let _ = payload;
Err(crate::Error::Unimplemented)
/// [`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<Sdp> {
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`.
@@ -50,6 +77,12 @@ impl EncryptionFlags {
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`.
@@ -76,16 +109,41 @@ pub struct OpusConfig {
pub mapping: Vec<u8>,
}
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
/// [`crate::Error::Malformed`] for a non-digit, a wrong length, or values that break RFC 7845's rules
/// (`coupled ≤ streams`, `streams + coupled ≤ 255`, mapping entries `< streams + coupled`). Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn parse_surround_params(value: &str) -> crate::Result<OpusConfig> {
let _ = value;
Err(crate::Error::Unimplemented)
/// [`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<OpusConfig> {
let digits: Vec<u8> = value
.bytes()
.map(|b| if b.is_ascii_digit() { Some(b - b'0') } else { None })
.collect::<Option<Vec<u8>>>()
.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.
@@ -107,20 +165,99 @@ impl HostCapabilities {
/// Reads the capabilities from a DESCRIBE payload.
///
/// # Errors
/// [`crate::Error::Malformed`] for a present attribute with a bad value, [`crate::Error::TooLarge`] over
/// [`MAX_OPUS_CONFIGS`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn from_sdp(sdp: &Sdp) -> crate::Result<Self> {
let _ = sdp;
Err(crate::Error::Unimplemented)
/// [`Error::Malformed`] for a present attribute with a bad value, [`Error::TooLarge`] over
/// [`MAX_OPUS_CONFIGS`].
pub fn from_sdp(sdp: &Sdp) -> Result<Self> {
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<EncryptionFlags> {
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
/// [`crate::Error::Unsupported`] when the host lacks control V2 encryption or the requested codec. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn build_announce(config: &StreamConfig, host: &HostCapabilities) -> crate::Result<Vec<u8>> {
let _ = (config, host);
Err(crate::Error::Unimplemented)
/// [`Error::Unsupported`] when the host lacks control V2 encryption or the requested codec.
pub fn build_announce(config: &StreamConfig, host: &HostCapabilities) -> Result<Vec<u8>> {
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())
}