[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
+193 -13
View File
@@ -5,8 +5,20 @@
//! answers with [`super::RtspFramer`], and feeds each whole answer to [`RtspClient::handle_response`] until it
//! returns [`RtspProgress::Ready`].
use super::sdp::{EncryptionFlags, HostCapabilities, OpusConfig};
use super::sdp::{self, EncryptionFlags, HostCapabilities, OpusConfig};
use super::{Method, RtspRequest, RtspResponse, parse_response};
use crate::http::launch::AudioLayout;
use crate::util::{check_rtsp_url, malformed, parse_u16};
use crate::{Error, Result};
/// `X-GS-ClientVersion` sent with every request (the value in Wolf's example, UNKNOWN U5).
pub const CLIENT_VERSION: &str = "14";
/// What the client sends to the video and audio ports to open the NAT path (Moonshine accepts it; U8).
pub const PING_PAYLOAD: &[u8] = b"PING";
/// SETUP targets (Moonshine's example form `streamid=control/13/0`; UNKNOWN U5).
const SETUP_TARGETS: [&str; 3] = ["streamid=audio/0/0", "streamid=video/0/0", "streamid=control/13/0"];
/// `Transport` value of the SETUP requests (not interpreted by the hosts we know of; U5).
const TRANSPORT: &str = "unicast;X-GS-ClientPort=50000-50001";
/// Video codecs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -113,6 +125,15 @@ pub enum RtspProgress {
#[derive(Debug)]
pub struct RtspClient {
state: RtspClientState,
url: String,
config: StreamConfig,
cseq: u32,
/// The request to hand out, and whether one was handed out and is not answered yet.
pending: Option<Vec<u8>>,
outstanding: bool,
host: Option<HostCapabilities>,
ports: [u16; 3],
session_id: Option<String>,
}
impl RtspClient {
@@ -120,27 +141,170 @@ impl RtspClient {
/// is ready in [`Self::poll_request`].
///
/// # Errors
/// [`crate::Error::Malformed`] for a URL that is not `rtsp://host:port`, or a config with zero size, frame
/// rate, bitrate or packet size. Phase A: always [`crate::Error::Unimplemented`].
pub fn new(session_url: &str, config: StreamConfig) -> crate::Result<Self> {
let _ = (session_url, config);
Err(crate::Error::Unimplemented)
/// [`Error::Malformed`] for a URL that is not `rtsp://host:port`, or a config with zero size, frame
/// rate, bitrate or packet size.
pub fn new(session_url: &str, config: StreamConfig) -> Result<Self> {
check_rtsp_url("rtsp session URL", session_url)?;
if config.width == 0
|| config.height == 0
|| config.fps == 0
|| config.bitrate_kbps == 0
|| config.packet_size == 0
|| config.audio_packet_duration_ms == 0
{
return Err(malformed("rtsp stream config"));
}
let mut c = Self {
state: RtspClientState::Options,
url: session_url.to_owned(),
config,
cseq: 0,
pending: None,
outstanding: false,
host: None,
ports: [0; 3],
session_id: None,
};
let url = c.url.clone();
c.queue(Method::Options, &url, Vec::new(), Vec::new())?;
Ok(c)
}
fn queue(
&mut self,
method: Method,
target: &str,
mut extra: Vec<(String, String)>,
body: Vec<u8>,
) -> Result<()> {
self.cseq = self.cseq.wrapping_add(1);
let mut headers = vec![("CSeq".to_owned(), self.cseq.to_string())];
headers.push(("X-GS-ClientVersion".to_owned(), CLIENT_VERSION.to_owned()));
if let Some(s) = &self.session_id {
headers.push(("Session".to_owned(), s.clone()));
}
headers.append(&mut extra);
if !body.is_empty() {
headers.push(("Content-Length".to_owned(), body.len().to_string()));
}
let req = RtspRequest { method, target: target.to_owned(), headers, body };
self.pending = Some(req.encode()?);
Ok(())
}
/// The next request to write, if one is due. Each is returned once.
pub fn poll_request(&mut self) -> Option<Vec<u8>> {
None
let req = self.pending.take();
if req.is_some() {
self.outstanding = true;
}
req
}
/// Feeds one whole answer (see [`super::RtspFramer`]).
///
/// # Errors
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for a `CSeq` that does not
/// match or a bad payload, [`crate::Error::Unsupported`] when the host lacks something required,
/// [`crate::Error::State`] when no request is outstanding. Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_response(&mut self, message: &[u8]) -> crate::Result<RtspProgress> {
let _ = message;
Err(crate::Error::Unimplemented)
/// [`Error::HostStatus`] for a non-200 answer, [`Error::Malformed`] for a `CSeq` that does not match or a bad
/// payload, [`Error::Unsupported`] when the host lacks something required, [`Error::State`] when no request is
/// outstanding. Every error but `State` moves the client to [`RtspClientState::Failed`].
pub fn handle_response(&mut self, message: &[u8]) -> Result<RtspProgress> {
if !self.outstanding || matches!(self.state, RtspClientState::Ready | RtspClientState::Failed) {
return Err(Error::State { expected: "an RTSP request outstanding" });
}
self.outstanding = false;
match self.advance(message) {
Ok(p) => Ok(p),
Err(e) => {
self.state = RtspClientState::Failed;
self.pending = None;
Err(e)
}
}
}
fn advance(&mut self, message: &[u8]) -> Result<RtspProgress> {
let r = parse_response(message)?;
let cseq = r.header("CSeq").ok_or(malformed("rtsp answer without CSeq"))?;
if crate::util::parse_u32("rtsp CSeq", cseq)? != self.cseq {
return Err(malformed("rtsp answer to another request (CSeq)"));
}
if r.status != 200 {
return Err(Error::HostStatus { code: u32::from(r.status) });
}
let url = self.url.clone();
match self.state {
RtspClientState::Options => {
self.queue(Method::Describe, &url, vec![("Accept".into(), "application/sdp".into())], Vec::new())?;
self.state = RtspClientState::Describe;
}
RtspClientState::Describe => {
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(&r.body)?)?;
sdp::negotiated_encryption(&self.config, &host)?;
self.host = Some(host);
self.setup(0)?;
self.state = RtspClientState::SetupAudio;
}
RtspClientState::SetupAudio | RtspClientState::SetupVideo | RtspClientState::SetupControl => {
let index = match self.state {
RtspClientState::SetupAudio => 0,
RtspClientState::SetupVideo => 1,
_ => 2,
};
let port = server_port(&r)?;
if let Some(slot) = self.ports.get_mut(index) {
*slot = port;
}
if let Some(s) = r.header("Session") {
let id = s.split(';').next().unwrap_or("").trim();
if !id.is_empty() {
self.session_id = Some(id.to_owned());
}
}
if index < 2 {
self.setup(index + 1)?;
self.state = if index == 0 { RtspClientState::SetupVideo } else { RtspClientState::SetupControl };
} else {
let host = self.host.as_ref().ok_or(Error::State { expected: "DESCRIBE answered" })?;
let body = sdp::build_announce(&self.config, host)?;
let target = SETUP_TARGETS.get(2).copied().unwrap_or("streamid=control/13/0");
self.queue(
Method::Announce,
target,
vec![("Content-type".into(), "application/sdp".into())],
body,
)?;
self.state = RtspClientState::Announce;
}
}
RtspClientState::Announce => {
self.queue(Method::Play, &url, Vec::new(), Vec::new())?;
self.state = RtspClientState::Play;
}
RtspClientState::Play => {
let host = self.host.clone().ok_or(Error::State { expected: "DESCRIBE answered" })?;
let encryption = sdp::negotiated_encryption(&self.config, &host)?;
let [audio, video, control] = self.ports;
let stream = NegotiatedStream {
ports: StreamPorts { audio, video, control },
encryption,
opus: host.opus_for(self.config.audio.channels()),
host,
session_id: self.session_id.clone(),
ping_payload: PING_PAYLOAD.to_vec(),
};
self.state = RtspClientState::Ready;
return Ok(RtspProgress::Ready(stream));
}
RtspClientState::Ready | RtspClientState::Failed => {
return Err(Error::State { expected: "an RTSP request outstanding" });
}
}
Ok(RtspProgress::Continue)
}
fn setup(&mut self, index: usize) -> Result<()> {
let target = SETUP_TARGETS.get(index).copied().ok_or(Error::State { expected: "a SETUP stream" })?;
self.queue(Method::Setup, target, vec![("Transport".into(), TRANSPORT.into())], Vec::new())
}
/// Where the negotiation is.
@@ -149,3 +313,19 @@ impl RtspClient {
self.state
}
}
/// `server_port=N` from the `Transport` header (other `;` parts ignored), N in 1..=65535.
fn server_port(r: &RtspResponse) -> Result<u16> {
let t = r.header("Transport").ok_or(malformed("rtsp SETUP answer without Transport"))?;
let v = t
.split(';')
.find_map(|p| p.trim().strip_prefix("server_port="))
.ok_or(malformed("rtsp Transport without server_port"))?;
// `server_port=a-b` names a range; the first port is the one used.
let first = v.split('-').next().unwrap_or("");
let port = parse_u16("rtsp server_port", first)?;
if port == 0 {
return Err(malformed("rtsp server_port 0"));
}
Ok(port)
}