[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:
@@ -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)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ pub mod sdp;
|
||||
pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts};
|
||||
pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp};
|
||||
|
||||
use crate::util::{cap, malformed, parse_dec};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Default RTSP port.
|
||||
pub const DEFAULT_RTSP_PORT: u16 = 48010;
|
||||
/// Maximum size of one RTSP message (start line + headers + payload), in bytes.
|
||||
@@ -16,6 +19,9 @@ pub const MAX_RTSP_LINE_BYTES: usize = 4096;
|
||||
/// Maximum number of header lines in one message.
|
||||
pub const MAX_RTSP_HEADERS: usize = 64;
|
||||
|
||||
/// The only protocol version spoken.
|
||||
const VERSION: &str = "RTSP/1.0";
|
||||
|
||||
/// The methods this client sends.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Method {
|
||||
@@ -31,6 +37,24 @@ pub enum Method {
|
||||
Play,
|
||||
}
|
||||
|
||||
impl Method {
|
||||
/// The method token.
|
||||
#[must_use]
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Options => "OPTIONS",
|
||||
Self::Describe => "DESCRIBE",
|
||||
Self::Setup => "SETUP",
|
||||
Self::Announce => "ANNOUNCE",
|
||||
Self::Play => "PLAY",
|
||||
}
|
||||
}
|
||||
|
||||
fn from_token(t: &str) -> Option<Self> {
|
||||
[Self::Options, Self::Describe, Self::Setup, Self::Announce, Self::Play].into_iter().find(|m| m.as_str() == t)
|
||||
}
|
||||
}
|
||||
|
||||
/// An RTSP request.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RtspRequest {
|
||||
@@ -44,15 +68,44 @@ pub struct RtspRequest {
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
fn is_token(b: u8) -> bool {
|
||||
b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
|
||||
}
|
||||
|
||||
impl RtspRequest {
|
||||
/// Serializes the request (CRLF line ends, empty line, payload). Refuses CR or LF inside a target, header
|
||||
/// name or value.
|
||||
/// Serializes the request (CRLF line ends, empty line, payload) with exactly the given headers. Refuses CR or
|
||||
/// LF inside a target, header name or value, whitespace in the target, and header names that are not tokens.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::Malformed`] for a forbidden character, [`crate::Error::TooLarge`] over
|
||||
/// [`MAX_RTSP_MESSAGE_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
||||
pub fn encode(&self) -> crate::Result<Vec<u8>> {
|
||||
Err(crate::Error::Unimplemented)
|
||||
/// [`Error::Malformed`] for a forbidden character, [`Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`].
|
||||
pub fn encode(&self) -> Result<Vec<u8>> {
|
||||
if self.target.is_empty() || self.target.bytes().any(|b| b.is_ascii_whitespace() || b.is_ascii_control()) {
|
||||
return Err(malformed("rtsp target"));
|
||||
}
|
||||
let mut out = format!("{} {} {VERSION}\r\n", self.method.as_str(), self.target);
|
||||
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 request", MAX_RTSP_MESSAGE_BYTES, bytes.len().saturating_add(self.body.len()))?;
|
||||
bytes.extend_from_slice(&self.body);
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// The first header with this name, compared case-insensitively.
|
||||
#[must_use]
|
||||
pub fn header(&self, name: &str) -> Option<&str> {
|
||||
header(&self.headers, name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,32 +122,134 @@ pub struct RtspResponse {
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
|
||||
headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
impl RtspResponse {
|
||||
/// The first header with this name, compared case-insensitively.
|
||||
#[must_use]
|
||||
pub fn header(&self, name: &str) -> Option<&str> {
|
||||
self.headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
|
||||
header(&self.headers, name)
|
||||
}
|
||||
}
|
||||
|
||||
/// A message split into start line, headers and payload.
|
||||
struct Message {
|
||||
start: String,
|
||||
headers: Vec<(String, String)>,
|
||||
body: Vec<u8>,
|
||||
}
|
||||
|
||||
/// One CRLF-terminated line at `pos`: (line without CRLF, position after CRLF). `None` when no LF follows.
|
||||
fn line(data: &[u8], pos: usize) -> Result<Option<(&str, usize)>> {
|
||||
let rest = data.get(pos..).unwrap_or(&[]);
|
||||
let Some(lf) = rest.iter().take(MAX_RTSP_LINE_BYTES + 2).position(|&b| b == b'\n') else {
|
||||
if rest.len() > MAX_RTSP_LINE_BYTES + 1 {
|
||||
return Err(Error::TooLarge { what: "rtsp line", max: MAX_RTSP_LINE_BYTES, actual: rest.len() });
|
||||
}
|
||||
return Ok(None);
|
||||
};
|
||||
let raw = rest.get(..lf).unwrap_or(&[]);
|
||||
let text = raw.strip_suffix(b"\r").ok_or(malformed("rtsp line without CRLF"))?;
|
||||
cap("rtsp line", MAX_RTSP_LINE_BYTES, text.len())?;
|
||||
if text.contains(&b'\r') {
|
||||
return Err(malformed("rtsp: CR inside a line"));
|
||||
}
|
||||
let text = core::str::from_utf8(text).map_err(|_| malformed("rtsp: not UTF-8"))?;
|
||||
Ok(Some((text, pos + lf + 1)))
|
||||
}
|
||||
|
||||
/// Parses headers from `pos` up to the empty line: (headers, position of the payload).
|
||||
fn headers_from(data: &[u8], mut pos: usize) -> Result<(Vec<(String, String)>, usize)> {
|
||||
let mut headers = Vec::new();
|
||||
loop {
|
||||
let (text, next) = line(data, pos)?.ok_or(Error::Truncated {
|
||||
what: "rtsp headers",
|
||||
needed: data.len().saturating_add(2),
|
||||
actual: data.len(),
|
||||
})?;
|
||||
pos = next;
|
||||
if text.is_empty() {
|
||||
return Ok((headers, pos));
|
||||
}
|
||||
let (name, value) = text.split_once(':').ok_or(malformed("rtsp header without :"))?;
|
||||
if name.is_empty() || !name.bytes().all(is_token) {
|
||||
return Err(malformed("rtsp header name"));
|
||||
}
|
||||
headers.push((name.to_owned(), value.trim_matches([' ', '\t']).to_owned()));
|
||||
cap("rtsp headers", MAX_RTSP_HEADERS, headers.len())?;
|
||||
}
|
||||
}
|
||||
|
||||
/// The message's Content-Length, if any: strict digits, all copies equal, within the cap.
|
||||
fn content_length(headers: &[(String, String)], head_len: usize) -> Result<Option<usize>> {
|
||||
let mut found: Option<u64> = None;
|
||||
for (_, v) in headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case("content-length")) {
|
||||
let n = parse_dec("rtsp Content-Length", v)?;
|
||||
if found.is_some_and(|f| f != n) {
|
||||
return Err(malformed("rtsp: two different Content-Length values"));
|
||||
}
|
||||
found = Some(n);
|
||||
}
|
||||
let Some(n) = found else { return Ok(None) };
|
||||
let total = usize::try_from(n).unwrap_or(usize::MAX).saturating_add(head_len);
|
||||
cap("rtsp message", MAX_RTSP_MESSAGE_BYTES, total)?;
|
||||
Ok(Some(total - head_len))
|
||||
}
|
||||
|
||||
fn split_message(msg: &[u8]) -> Result<Message> {
|
||||
cap("rtsp message", MAX_RTSP_MESSAGE_BYTES, msg.len())?;
|
||||
let (start, pos) = line(msg, 0)?.ok_or(malformed("rtsp: no start line"))?;
|
||||
if start.is_empty() {
|
||||
return Err(malformed("rtsp: empty start line"));
|
||||
}
|
||||
let start = start.to_owned();
|
||||
let (headers, body_at) = headers_from(msg, pos)?;
|
||||
let rest = msg.get(body_at..).unwrap_or(&[]);
|
||||
let body = match content_length(&headers, body_at)? {
|
||||
None => rest.to_vec(),
|
||||
Some(n) if rest.len() < n => {
|
||||
return Err(Error::Truncated { what: "rtsp payload", needed: body_at + n, actual: msg.len() });
|
||||
}
|
||||
Some(n) if rest.len() > n => return Err(malformed("rtsp: bytes after the payload")),
|
||||
Some(_) => rest.to_vec(),
|
||||
};
|
||||
Ok(Message { start, headers, body })
|
||||
}
|
||||
|
||||
/// Parses one complete response (as cut by [`RtspFramer`]).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`], [`MAX_RTSP_LINE_BYTES`] or [`MAX_RTSP_HEADERS`],
|
||||
/// [`crate::Error::Malformed`] for a bad start line, header line or `Content-Length`. Phase A: always
|
||||
/// [`crate::Error::Unimplemented`].
|
||||
pub fn parse_response(message: &[u8]) -> crate::Result<RtspResponse> {
|
||||
let _ = message;
|
||||
Err(crate::Error::Unimplemented)
|
||||
/// [`Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`], [`MAX_RTSP_LINE_BYTES`] or [`MAX_RTSP_HEADERS`],
|
||||
/// [`Error::Malformed`] for a bad start line, header line or `Content-Length`, [`Error::Truncated`] when the headers
|
||||
/// or the payload end early.
|
||||
pub fn parse_response(message: &[u8]) -> Result<RtspResponse> {
|
||||
let m = split_message(message)?;
|
||||
let rest = m.start.strip_prefix("RTSP/1.0 ").ok_or(malformed("rtsp: not an RTSP/1.0 response"))?;
|
||||
let (code, reason) = rest.split_once(' ').unwrap_or((rest, ""));
|
||||
if code.len() != 3 || !code.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err(malformed("rtsp status code"));
|
||||
}
|
||||
let status = crate::util::parse_u16("rtsp status code", code)?;
|
||||
Ok(RtspResponse { status, reason: reason.to_owned(), headers: m.headers, body: m.body })
|
||||
}
|
||||
|
||||
/// Parses one complete request. Not used by the client; here for the fuzz harness and the Lumen host (Day 3).
|
||||
///
|
||||
/// # Errors
|
||||
/// As [`parse_response`], plus [`crate::Error::UnexpectedValue`] for an unknown method.
|
||||
pub fn parse_request(message: &[u8]) -> crate::Result<RtspRequest> {
|
||||
let _ = message;
|
||||
Err(crate::Error::Unimplemented)
|
||||
/// As [`parse_response`], plus [`Error::UnexpectedValue`] for an unknown method.
|
||||
pub fn parse_request(message: &[u8]) -> Result<RtspRequest> {
|
||||
let m = split_message(message)?;
|
||||
let mut parts = m.start.splitn(3, ' ');
|
||||
let (Some(method), Some(target), Some(version)) = (parts.next(), parts.next(), parts.next()) else {
|
||||
return Err(malformed("rtsp request line"));
|
||||
};
|
||||
if method.is_empty() || target.is_empty() || version != VERSION {
|
||||
return Err(malformed("rtsp request line"));
|
||||
}
|
||||
let method = Method::from_token(method).ok_or(Error::UnexpectedValue { what: "rtsp method", value: 0 })?;
|
||||
Ok(RtspRequest { method, target: target.to_owned(), headers: m.headers, body: m.body })
|
||||
}
|
||||
|
||||
/// Cuts the TCP byte stream from the host into whole messages.
|
||||
@@ -117,28 +272,63 @@ impl RtspFramer {
|
||||
/// Appends received bytes.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::TooLarge`] when the unfinished message would exceed [`MAX_RTSP_MESSAGE_BYTES`]. Phase A:
|
||||
/// always [`crate::Error::Unimplemented`].
|
||||
pub fn push(&mut self, bytes: &[u8]) -> crate::Result<()> {
|
||||
let _ = bytes;
|
||||
Err(crate::Error::Unimplemented)
|
||||
/// [`Error::TooLarge`] when the buffered bytes would exceed [`MAX_RTSP_MESSAGE_BYTES`] (nothing is appended).
|
||||
pub fn push(&mut self, bytes: &[u8]) -> Result<()> {
|
||||
cap("rtsp stream", MAX_RTSP_MESSAGE_BYTES, self.buffer.len().saturating_add(bytes.len()))?;
|
||||
self.buffer.extend_from_slice(bytes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where the buffered header section ends and the message's Content-Length, if the headers are complete.
|
||||
fn head(&self) -> Result<Option<(usize, Option<usize>)>> {
|
||||
let Some(end) = self.buffer.windows(4).position(|w| w == b"\r\n\r\n") else { return Ok(None) };
|
||||
let head_len = end + 4;
|
||||
let head = self.buffer.get(..head_len).unwrap_or(&[]);
|
||||
let mut headers = Vec::new();
|
||||
for raw in head.split(|&b| b == b'\n').skip(1) {
|
||||
let text = core::str::from_utf8(raw.strip_suffix(b"\r").unwrap_or(raw)).unwrap_or("");
|
||||
if let Some((n, v)) = text.split_once(':') {
|
||||
if n.eq_ignore_ascii_case("content-length") {
|
||||
headers.push((n.to_owned(), v.trim_matches([' ', '\t']).to_owned()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some((head_len, content_length(&headers, head_len)?)))
|
||||
}
|
||||
|
||||
/// Takes the next complete message, if one is buffered.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::Malformed`] for a bad `Content-Length`. Phase A: always [`crate::Error::Unimplemented`].
|
||||
pub fn next_message(&mut self) -> crate::Result<Option<Vec<u8>>> {
|
||||
Err(crate::Error::Unimplemented)
|
||||
/// [`Error::Malformed`] for a bad `Content-Length`, [`Error::TooLarge`] when it announces a message over the cap.
|
||||
pub fn next_message(&mut self) -> Result<Option<Vec<u8>>> {
|
||||
match self.head()? {
|
||||
Some((head, Some(len))) if self.buffer.len() >= head + len => {
|
||||
let rest = self.buffer.split_off(head + len);
|
||||
Ok(Some(core::mem::replace(&mut self.buffer, rest)))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The host closed the connection: returns what is buffered as the last message, if anything.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`crate::Error::Truncated`] when a `Content-Length` promised more. Phase A: always
|
||||
/// [`crate::Error::Unimplemented`].
|
||||
pub fn finish(&mut self) -> crate::Result<Option<Vec<u8>>> {
|
||||
Err(crate::Error::Unimplemented)
|
||||
/// [`Error::Truncated`] when the headers never ended or a `Content-Length` promised more.
|
||||
pub fn finish(&mut self) -> Result<Option<Vec<u8>>> {
|
||||
if self.buffer.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
match self.head()? {
|
||||
None => Err(Error::Truncated {
|
||||
what: "rtsp headers at close",
|
||||
needed: self.buffer.len().saturating_add(4),
|
||||
actual: self.buffer.len(),
|
||||
}),
|
||||
Some((head, Some(len))) if self.buffer.len() < head + len => {
|
||||
Err(Error::Truncated { what: "rtsp payload at close", needed: head + len, actual: self.buffer.len() })
|
||||
}
|
||||
Some(_) => Ok(Some(core::mem::take(&mut self.buffer))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes buffered but not yet returned.
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user