[domistream] RTSP API: message codec, stream framer, SDP, negotiation state machine

This commit is contained in:
2026-11-25 11:46:10 +01:00
parent 736a8f42b0
commit 024fe14ca6
4 changed files with 427 additions and 0 deletions
+1
View File
@@ -40,6 +40,7 @@ pub mod error;
pub mod http; pub mod http;
pub mod keys; pub mod keys;
pub mod pairing; pub mod pairing;
pub mod rtsp;
pub mod time; pub mod time;
pub use entropy::RandomSource; pub use entropy::RandomSource;
+151
View File
@@ -0,0 +1,151 @@
//! The RTSP client state machine: OPTIONS → DESCRIBE → SETUP audio → SETUP video → SETUP control → ANNOUNCE →
//! PLAY (`docs/PROTOCOL.md` 2.2).
//!
//! The caller opens TCP to the session URL, writes each request from [`RtspClient::poll_request`], cuts the
//! 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 crate::http::launch::AudioLayout;
/// Video codecs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VideoCodec {
/// H.264.
H264,
/// HEVC (H.265).
Hevc,
/// AV1.
Av1,
}
/// What the client asks for in ANNOUNCE.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamConfig {
/// Width in pixels.
pub width: u32,
/// Height in pixels.
pub height: u32,
/// Frames per second.
pub fps: u32,
/// Video bitrate in kbit/s.
pub bitrate_kbps: u32,
/// Video `packetSize` (default 1024).
pub packet_size: u16,
/// Video codec.
pub codec: VideoCodec,
/// HDR (10-bit) stream.
pub hdr: bool,
/// Audio layout.
pub audio: AudioLayout,
/// Audio packet duration in milliseconds (`x-nv-aqos.packetDuration`).
pub audio_packet_duration_ms: u8,
/// Minimum video parity packets per FEC block.
pub min_fec_packets: u8,
/// The client can recover with reference frame invalidation instead of an IDR.
pub reference_frame_invalidation: bool,
/// Encryption the client wants (Day 1: all three); the ANNOUNCE turns on the intersection with the host.
pub encryption: EncryptionFlags,
}
/// The three UDP ports from the SETUP answers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct StreamPorts {
/// Audio RTP port.
pub audio: u16,
/// Video RTP port.
pub video: u16,
/// Control (ENet) port.
pub control: u16,
}
/// Everything the stream stage needs once RTSP is done.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NegotiatedStream {
/// UDP ports.
pub ports: StreamPorts,
/// What the host offered in DESCRIBE.
pub host: HostCapabilities,
/// Encryption turned on in ANNOUNCE.
pub encryption: EncryptionFlags,
/// The Opus configuration chosen for `StreamConfig::audio`, for the platform decoder.
pub opus: OpusConfig,
/// The `Session` id from SETUP, if the host sent one.
pub session_id: Option<String>,
/// The datagram to send to the video and audio ports before the stream starts (UNKNOWN U8; `PING` for
/// Moonshine-like hosts).
pub ping_payload: Vec<u8>,
}
/// Where the negotiation is. Each state names the request just sent.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RtspClientState {
/// OPTIONS sent.
Options,
/// DESCRIBE sent.
Describe,
/// SETUP audio sent.
SetupAudio,
/// SETUP video sent.
SetupVideo,
/// SETUP control sent.
SetupControl,
/// ANNOUNCE sent.
Announce,
/// PLAY sent.
Play,
/// Done; see [`NegotiatedStream`].
Ready,
/// A non-200 answer or a bad payload stopped it.
Failed,
}
/// Result of feeding one answer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RtspProgress {
/// The next request is ready in [`RtspClient::poll_request`].
Continue,
/// Negotiation finished.
Ready(NegotiatedStream),
}
/// The RTSP negotiation for one stream session.
#[derive(Debug)]
pub struct RtspClient {
state: RtspClientState,
}
impl RtspClient {
/// Prepares the negotiation against `session_url` (`sessionUrl0` from launch). The first request (OPTIONS)
/// 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)
}
/// The next request to write, if one is due. Each is returned once.
pub fn poll_request(&mut self) -> Option<Vec<u8>> {
None
}
/// 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)
}
/// Where the negotiation is.
#[must_use]
pub const fn state(&self) -> RtspClientState {
self.state
}
}
+149
View File
@@ -0,0 +1,149 @@
//! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP,
//! and the client state machine.
pub mod client;
pub mod sdp;
pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts};
pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp};
/// Default RTSP port.
pub const DEFAULT_RTSP_PORT: u16 = 48010;
/// Maximum size of one RTSP message (start line + headers + payload), in bytes.
pub const MAX_RTSP_MESSAGE_BYTES: usize = 64 * 1024;
/// Maximum length of one start or header line, in bytes (without CRLF).
pub const MAX_RTSP_LINE_BYTES: usize = 4096;
/// Maximum number of header lines in one message.
pub const MAX_RTSP_HEADERS: usize = 64;
/// The methods this client sends.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Method {
/// `OPTIONS`.
Options,
/// `DESCRIBE`.
Describe,
/// `SETUP`.
Setup,
/// `ANNOUNCE`.
Announce,
/// `PLAY`.
Play,
}
/// An RTSP request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RtspRequest {
/// The method.
pub method: Method,
/// The target, e.g. `rtsp://192.0.2.10:48010` or `streamid=video/0/0`.
pub target: String,
/// Header lines in order, `CSeq` included.
pub headers: Vec<(String, String)>,
/// The payload (SDP for ANNOUNCE), possibly empty.
pub body: Vec<u8>,
}
impl RtspRequest {
/// Serializes the request (CRLF line ends, empty line, payload). Refuses CR or LF inside a target, header
/// name or value.
///
/// # 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)
}
}
/// An RTSP response.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RtspResponse {
/// Status code, e.g. 200.
pub status: u16,
/// Reason phrase.
pub reason: String,
/// Header lines in order.
pub headers: Vec<(String, String)>,
/// The payload (SDP for DESCRIBE), possibly empty.
pub body: Vec<u8>,
}
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())
}
}
/// 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)
}
/// 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)
}
/// Cuts the TCP byte stream from the host into whole messages.
///
/// A message ends after its headers plus `Content-Length` payload bytes; without `Content-Length` it ends when
/// the host closes the connection ([`RtspFramer::finish`]) (UNKNOWN U5). Never buffers more than
/// [`MAX_RTSP_MESSAGE_BYTES`].
#[derive(Debug, Default)]
pub struct RtspFramer {
buffer: Vec<u8>,
}
impl RtspFramer {
/// An empty framer.
#[must_use]
pub const fn new() -> Self {
Self { buffer: Vec::new() }
}
/// 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)
}
/// 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)
}
/// 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)
}
/// Bytes buffered but not yet returned.
#[must_use]
pub fn buffered(&self) -> usize {
self.buffer.len()
}
}
+126
View File
@@ -0,0 +1,126 @@
//! The SDP-like payloads of DESCRIBE (host → client) and ANNOUNCE (client → host) (`docs/PROTOCOL.md` 2.3, 2.4).
use super::client::StreamConfig;
/// 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.
///
/// # 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)
}
/// 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;
}
/// 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<u8>,
}
/// 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)
}
/// 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<OpusConfig>,
}
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)
}
}
/// 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)
}