//! 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::{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)] 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, /// 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, } /// 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, url: String, config: StreamConfig, cseq: u32, /// The request to hand out, and whether one was handed out and is not answered yet. pending: Option>, outstanding: bool, host: Option, ports: [u16; 3], session_id: Option, } impl RtspClient { /// Prepares the negotiation against `session_url` (`sessionUrl0` from launch). The first request (OPTIONS) /// is ready in [`Self::poll_request`]. /// /// # Errors /// [`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 { 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) -> 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> { let req = self.pending.take(); if req.is_some() { self.outstanding = true; } req } /// Feeds one whole answer (see [`super::RtspFramer`]). /// /// # Errors /// [`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 { 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 { 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. #[must_use] pub const fn state(&self) -> RtspClientState { self.state } } /// `server_port=N` from the `Transport` header (other `;` parts ignored), N in 1..=65535. fn server_port(r: &RtspResponse) -> Result { 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) }