[domistream] Host: RTSP server, DESCRIBE and ANNOUNCE #10
@@ -143,7 +143,27 @@ impl RtspResponse {
|
||||
/// header name that is not a token, or CR or LF in a header value; [`Error::TooLarge`] over
|
||||
/// [`MAX_RTSP_MESSAGE_BYTES`].
|
||||
pub fn encode(&self) -> Result<Vec<u8>> {
|
||||
Err(Error::Unimplemented)
|
||||
if !(100..=999).contains(&self.status) || self.reason.bytes().any(|b| b.is_ascii_control()) {
|
||||
return Err(malformed("rtsp status line"));
|
||||
}
|
||||
let mut out = format!("{VERSION} {} {}\r\n", self.status, self.reason);
|
||||
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 response", MAX_RTSP_MESSAGE_BYTES, bytes.len().saturating_add(self.body.len()))?;
|
||||
bytes.extend_from_slice(&self.body);
|
||||
Ok(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -317,8 +337,7 @@ impl RtspFramer {
|
||||
}
|
||||
}
|
||||
let length = content_length(&headers, head_len)?;
|
||||
let _ = self.missing_length_is_zero;
|
||||
Ok(Some((head_len, length)))
|
||||
Ok(Some((head_len, if self.missing_length_is_zero { Some(length.unwrap_or(0)) } else { length })))
|
||||
}
|
||||
|
||||
/// Takes the next complete message, if one is buffered.
|
||||
|
||||
@@ -199,7 +199,7 @@ impl HostCapabilities {
|
||||
}
|
||||
}
|
||||
|
||||
/// `x-nv-vqos[0].bitStreamFormat` values (judgment from the codec order H.264, HEVC, AV1; UNKNOWN U6).
|
||||
/// `x-nv-vqos[0].bitStreamFormat` values: 0 H.264, 1 HEVC, 2 AV1 as a host reads them (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||
const fn bitstream_format(codec: VideoCodec) -> u8 {
|
||||
match codec {
|
||||
VideoCodec::H264 => 0,
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
use crate::rtsp::client::VideoCodec;
|
||||
use crate::rtsp::sdp::{EncryptionFlags, MAX_AUDIO_CHANNELS};
|
||||
use crate::util::{cap, malformed, parse_dec};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Maximum size of an ANNOUNCE payload, in bytes (the SDP cap of `docs/PROTOCOL.md` 2.3).
|
||||
@@ -22,16 +23,16 @@ pub const MAX_ANNOUNCE_ATTRIBUTES: usize = 512;
|
||||
pub const MAX_DIMENSION: u32 = 16_384;
|
||||
/// Largest frame rate accepted (our cap, not the protocol's).
|
||||
pub const MAX_FPS: u32 = 1000;
|
||||
/// Smallest video `packetSize` a host accepts (`docs/PROTOCOL.md` 2.5 [M]).
|
||||
/// Smallest video `packetSize` a host accepts (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||
pub const MIN_PACKET_SIZE: u16 = 200;
|
||||
/// Largest video `packetSize`: one stream packet in one IPv6 UDP datagram (`docs/PROTOCOL.md` 2.5 [M]).
|
||||
/// Largest video `packetSize`: one stream packet in one IPv6 UDP datagram (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||
pub const MAX_PACKET_SIZE: u16 = 65_471;
|
||||
/// Largest bitrate in kbit/s: the value times 1000 must fit in a `u32` (`docs/PROTOCOL.md` 2.5 [M]).
|
||||
/// Largest bitrate in kbit/s: the value times 1000 must fit in a `u32` (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||
pub const MAX_BITRATE_KBPS: u32 = 4_294_967;
|
||||
/// Longest audio packet in milliseconds: the longest Opus packet (RFC 6716 section 3.2.5).
|
||||
pub const MAX_AUDIO_PACKET_DURATION_MS: u8 = 120;
|
||||
|
||||
/// Chroma subsampling, `x-ss-video[0].chromaSamplingType` (`docs/PROTOCOL.md` 2.5 [M]).
|
||||
/// Chroma subsampling, `x-ss-video[0].chromaSamplingType` (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum ChromaSampling {
|
||||
/// 4:2:0, value 0 (the default).
|
||||
@@ -45,13 +46,13 @@ pub enum ChromaSampling {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct SurroundSettings {
|
||||
/// `x-nv-audio.surround.enable`: 0 or 1, default 0. When off, a Moonshine-like host takes the layout from the
|
||||
/// launch call's `surroundAudioInfo` instead of `channels` and `channel_mask` [M].
|
||||
/// launch call's `surroundAudioInfo` instead of `channels` and `channel_mask` \[M\].
|
||||
pub enabled: bool,
|
||||
/// `x-nv-audio.surround.numChannels`: 1..=8, default 2 [M].
|
||||
/// `x-nv-audio.surround.numChannels`: 1..=8, default 2 \[M\].
|
||||
pub channels: u8,
|
||||
/// `x-nv-audio.surround.channelMask`: the speaker mask, kept as sent; default `0x3` [M].
|
||||
/// `x-nv-audio.surround.channelMask`: the speaker mask, kept as sent; default `0x3` \[M\].
|
||||
pub channel_mask: u32,
|
||||
/// `x-nv-audio.surround.AudioQuality`: 0 or 1, default 1 (high quality) [M].
|
||||
/// `x-nv-audio.surround.AudioQuality`: 0 or 1, default 1 (high quality) \[M\].
|
||||
pub high_quality: bool,
|
||||
}
|
||||
|
||||
@@ -76,31 +77,31 @@ pub struct StreamConfig {
|
||||
pub packet_size: u16,
|
||||
/// `x-ml-video.configuredBitrateKbps`, required, 1..=[`MAX_BITRATE_KBPS`].
|
||||
pub bitrate_kbps: u32,
|
||||
/// `x-nv-vqos[0].bitStreamFormat`, required: 0 H.264, 1 HEVC, 2 AV1 [M]; anything else is refused.
|
||||
/// `x-nv-vqos[0].bitStreamFormat`, required: 0 H.264, 1 HEVC, 2 AV1 \[M\]; anything else is refused.
|
||||
pub codec: VideoCodec,
|
||||
/// `x-nv-vqos[0].fec.minRequiredFecPackets`, required, 0..=255.
|
||||
pub min_fec_packets: u8,
|
||||
/// `x-nv-vqos[0].qosTrafficType`, required, kept as sent (a Moonshine-like host turns QoS off for 0 [M]).
|
||||
/// `x-nv-vqos[0].qosTrafficType`, required, kept as sent (a Moonshine-like host turns QoS off for 0 \[M\]).
|
||||
pub video_qos_traffic_type: u32,
|
||||
/// `x-nv-aqos.packetDuration`, required, 1..=[`MAX_AUDIO_PACKET_DURATION_MS`] milliseconds.
|
||||
pub audio_packet_duration_ms: u8,
|
||||
/// `x-nv-aqos.qosTrafficType`, required, kept as sent.
|
||||
pub audio_qos_traffic_type: u32,
|
||||
/// `x-nv-video[0].maxNumReferenceFrames`, default 1 [M]. Kept raw: what 0 means has GPL provenance only
|
||||
/// ([M*], `docs/PROTOCOL.md` 2.4), so it is not interpreted here.
|
||||
/// `x-nv-video[0].maxNumReferenceFrames`, default 1 \[M\]. Kept raw: what 0 means has GPL provenance only
|
||||
/// (\[M*\], `docs/PROTOCOL.md` 2.4), so it is not interpreted here.
|
||||
pub max_reference_frames: u32,
|
||||
/// `x-nv-video[0].refPicInvalidation`, 0 or 1. Default 0 (the client cannot invalidate, so the host sends an
|
||||
/// IDR frame on loss, which always works): UNKNOWN U6, settled by measurement.
|
||||
pub reference_frame_invalidation: bool,
|
||||
/// `x-nv-video[0].dynamicRangeMode`, default 0, kept raw. Moonshine reads 0 as SDR [M]; no other value has a
|
||||
/// `x-nv-video[0].dynamicRangeMode`, default 0, kept raw. Moonshine reads 0 as SDR \[M\]; no other value has a
|
||||
/// settled meaning: UNKNOWN U6, settled by measurement.
|
||||
pub dynamic_range_mode: u32,
|
||||
/// `x-nv-video[0].encoderCscMode`, default 0, kept raw. Its bit layout has GPL provenance only ([M*]):
|
||||
/// `x-nv-video[0].encoderCscMode`, default 0, kept raw. Its bit layout has GPL provenance only (\[M*\]):
|
||||
/// UNKNOWN U6, settled by measurement (`docs/LUMEN-HOST-PLAN.md` 1.3).
|
||||
pub encoder_csc_mode: u32,
|
||||
/// `x-ss-video[0].chromaSamplingType`, 0 or 1, default 0 (4:2:0) [M].
|
||||
/// `x-ss-video[0].chromaSamplingType`, 0 or 1, default 0 (4:2:0) \[M\].
|
||||
pub chroma: ChromaSampling,
|
||||
/// `x-ss-general.encryptionEnabled`, 0..=255, default 0 [M]; bits as in `docs/PROTOCOL.md` 2.3. Kept as sent;
|
||||
/// `x-ss-general.encryptionEnabled`, 0..=255, default 0 \[M\]; bits as in `docs/PROTOCOL.md` 2.3. Kept as sent;
|
||||
/// [`super::RtspServer`] refuses bits the host did not offer.
|
||||
pub encryption: EncryptionFlags,
|
||||
/// `x-nv-audio.surround.*`.
|
||||
@@ -118,14 +119,220 @@ pub struct StreamConfig {
|
||||
/// line type, a control character, a known attribute given twice, a required attribute missing or a number that is
|
||||
/// not plain decimal; [`Error::UnexpectedValue`] for a number outside its range.
|
||||
pub fn parse_announce(payload: &[u8]) -> Result<StreamConfig> {
|
||||
let _ = payload;
|
||||
Err(Error::Unimplemented)
|
||||
cap("announce", MAX_ANNOUNCE_BYTES, payload.len())?;
|
||||
let text = core::str::from_utf8(payload).map_err(|_| malformed("announce: not UTF-8"))?;
|
||||
let mut values: [Option<&str>; ATTRIBUTES.len()] = [None; ATTRIBUTES.len()];
|
||||
let mut lines = 0usize;
|
||||
let mut attributes = 0usize;
|
||||
let mut unknown = 0u32;
|
||||
for raw in text.split('\n') {
|
||||
let line = raw.strip_suffix('\r').unwrap_or(raw);
|
||||
cap("announce line", MAX_ANNOUNCE_LINE_BYTES, line.len())?;
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
lines += 1;
|
||||
cap("announce lines", MAX_ANNOUNCE_LINES, lines)?;
|
||||
if line.bytes().any(|b| b.is_ascii_control() && b != b'\t') {
|
||||
return Err(malformed("announce: control character in a line"));
|
||||
}
|
||||
let (kind, rest) = line.split_once('=').ok_or(malformed("announce: line without ="))?;
|
||||
if kind.is_empty() {
|
||||
return Err(malformed("announce: line with an empty type"));
|
||||
}
|
||||
// Only `a=` lines carry settings; `v=`, `o=`, `s=`, `t=`, `m=` and bare lines are not read.
|
||||
if kind != "a" {
|
||||
continue;
|
||||
}
|
||||
attributes += 1;
|
||||
cap("announce attributes", MAX_ANNOUNCE_ATTRIBUTES, attributes)?;
|
||||
let (name, value) = rest.split_once(':').unwrap_or((rest, ""));
|
||||
match ATTRIBUTES.iter().position(|a| a.name == name).and_then(|i| values.get_mut(i)) {
|
||||
Some(Some(_)) => return Err(malformed("announce: an attribute given twice")),
|
||||
Some(slot) => *slot = Some(value.trim_matches([' ', '\t'])),
|
||||
None => unknown = unknown.saturating_add(1),
|
||||
}
|
||||
}
|
||||
let a = Values(&values);
|
||||
let codec = match a.required(BIT_STREAM_FORMAT, 0, 2)? {
|
||||
0 => VideoCodec::H264,
|
||||
1 => VideoCodec::Hevc,
|
||||
_ => VideoCodec::Av1,
|
||||
};
|
||||
Ok(StreamConfig {
|
||||
width: narrow(a.required(VIEWPORT_WD, 1, u64::from(MAX_DIMENSION))?)?,
|
||||
height: narrow(a.required(VIEWPORT_HT, 1, u64::from(MAX_DIMENSION))?)?,
|
||||
max_fps: narrow(a.required(MAX_FPS_ATTR, 1, u64::from(MAX_FPS))?)?,
|
||||
packet_size: narrow(a.required(PACKET_SIZE, u64::from(MIN_PACKET_SIZE), u64::from(MAX_PACKET_SIZE))?)?,
|
||||
bitrate_kbps: narrow(a.required(BITRATE, 1, u64::from(MAX_BITRATE_KBPS))?)?,
|
||||
codec,
|
||||
min_fec_packets: narrow(a.required(MIN_FEC_PACKETS, 0, u64::from(u8::MAX))?)?,
|
||||
video_qos_traffic_type: narrow(a.required(VIDEO_QOS, 0, u64::from(u32::MAX))?)?,
|
||||
audio_packet_duration_ms: narrow(a.required(PACKET_DURATION, 1, u64::from(MAX_AUDIO_PACKET_DURATION_MS))?)?,
|
||||
audio_qos_traffic_type: narrow(a.required(AUDIO_QOS, 0, u64::from(u32::MAX))?)?,
|
||||
max_reference_frames: narrow(a.optional(MAX_REFERENCE_FRAMES, 1, 0, u64::from(u32::MAX))?)?,
|
||||
reference_frame_invalidation: a.optional(REF_PIC_INVALIDATION, 0, 0, 1)? == 1,
|
||||
dynamic_range_mode: narrow(a.optional(DYNAMIC_RANGE_MODE, 0, 0, u64::from(u32::MAX))?)?,
|
||||
encoder_csc_mode: narrow(a.optional(ENCODER_CSC_MODE, 0, 0, u64::from(u32::MAX))?)?,
|
||||
chroma: if a.optional(CHROMA_SAMPLING, 0, 0, 1)? == 1 {
|
||||
ChromaSampling::Yuv444
|
||||
} else {
|
||||
ChromaSampling::Yuv420
|
||||
},
|
||||
encryption: EncryptionFlags(narrow(a.optional(ENCRYPTION_ENABLED, 0, 0, u64::from(u8::MAX))?)?),
|
||||
surround: SurroundSettings {
|
||||
enabled: a.optional(SURROUND_ENABLE, 0, 0, 1)? == 1,
|
||||
channels: narrow(a.optional(SURROUND_CHANNELS, 2, 1, MAX_AUDIO_CHANNELS as u64)?)?,
|
||||
channel_mask: narrow(a.optional(SURROUND_MASK, 0x3, 0, u64::from(u32::MAX))?)?,
|
||||
high_quality: a.optional(AUDIO_QUALITY, 1, 0, 1)? == 1,
|
||||
},
|
||||
unknown_attributes: unknown,
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes `config` as an ANNOUNCE payload (`v=0`, then every known attribute, CRLF line ends) that
|
||||
/// [`parse_announce`] reads back as the same config (with `unknown_attributes` 0).
|
||||
#[must_use]
|
||||
pub fn write_announce(config: &StreamConfig) -> Vec<u8> {
|
||||
let _ = (config, MAX_AUDIO_CHANNELS);
|
||||
Vec::new()
|
||||
let codec: u8 = match config.codec {
|
||||
VideoCodec::H264 => 0,
|
||||
VideoCodec::Hevc => 1,
|
||||
VideoCodec::Av1 => 2,
|
||||
};
|
||||
let chroma: u8 = match config.chroma {
|
||||
ChromaSampling::Yuv420 => 0,
|
||||
ChromaSampling::Yuv444 => 1,
|
||||
};
|
||||
let s = &config.surround;
|
||||
let values: [(usize, u64); ATTRIBUTES.len()] = [
|
||||
(VIEWPORT_WD, u64::from(config.width)),
|
||||
(VIEWPORT_HT, u64::from(config.height)),
|
||||
(MAX_FPS_ATTR, u64::from(config.max_fps)),
|
||||
(PACKET_SIZE, u64::from(config.packet_size)),
|
||||
(BITRATE, u64::from(config.bitrate_kbps)),
|
||||
(BIT_STREAM_FORMAT, u64::from(codec)),
|
||||
(MIN_FEC_PACKETS, u64::from(config.min_fec_packets)),
|
||||
(VIDEO_QOS, u64::from(config.video_qos_traffic_type)),
|
||||
(PACKET_DURATION, u64::from(config.audio_packet_duration_ms)),
|
||||
(AUDIO_QOS, u64::from(config.audio_qos_traffic_type)),
|
||||
(MAX_REFERENCE_FRAMES, u64::from(config.max_reference_frames)),
|
||||
(REF_PIC_INVALIDATION, u64::from(config.reference_frame_invalidation)),
|
||||
(DYNAMIC_RANGE_MODE, u64::from(config.dynamic_range_mode)),
|
||||
(ENCODER_CSC_MODE, u64::from(config.encoder_csc_mode)),
|
||||
(CHROMA_SAMPLING, u64::from(chroma)),
|
||||
(ENCRYPTION_ENABLED, u64::from(config.encryption.0)),
|
||||
(SURROUND_ENABLE, u64::from(s.enabled)),
|
||||
(SURROUND_CHANNELS, u64::from(s.channels)),
|
||||
(SURROUND_MASK, u64::from(s.channel_mask)),
|
||||
(AUDIO_QUALITY, u64::from(s.high_quality)),
|
||||
];
|
||||
let mut out = String::with_capacity(1024);
|
||||
out.push_str("v=0\r\n");
|
||||
for (index, value) in values {
|
||||
if let Some(attribute) = ATTRIBUTES.get(index) {
|
||||
out.push_str("a=");
|
||||
out.push_str(attribute.name);
|
||||
out.push(':');
|
||||
out.push_str(&value.to_string());
|
||||
out.push_str("\r\n");
|
||||
}
|
||||
}
|
||||
out.into_bytes()
|
||||
}
|
||||
|
||||
/// One attribute the host reads (`docs/PROTOCOL.md` 2.4, 2.5).
|
||||
struct Attribute {
|
||||
/// The SDP attribute name.
|
||||
name: &'static str,
|
||||
/// The error text when a required attribute is missing; `None` for attributes with a default.
|
||||
missing: Option<&'static str>,
|
||||
}
|
||||
|
||||
const fn required(name: &'static str, missing: &'static str) -> Attribute {
|
||||
Attribute { name, missing: Some(missing) }
|
||||
}
|
||||
|
||||
const fn defaulted(name: &'static str) -> Attribute {
|
||||
Attribute { name, missing: None }
|
||||
}
|
||||
|
||||
const VIEWPORT_WD: usize = 0;
|
||||
const VIEWPORT_HT: usize = 1;
|
||||
const MAX_FPS_ATTR: usize = 2;
|
||||
const PACKET_SIZE: usize = 3;
|
||||
const BITRATE: usize = 4;
|
||||
const BIT_STREAM_FORMAT: usize = 5;
|
||||
const MIN_FEC_PACKETS: usize = 6;
|
||||
const VIDEO_QOS: usize = 7;
|
||||
const PACKET_DURATION: usize = 8;
|
||||
const AUDIO_QOS: usize = 9;
|
||||
const MAX_REFERENCE_FRAMES: usize = 10;
|
||||
const REF_PIC_INVALIDATION: usize = 11;
|
||||
const DYNAMIC_RANGE_MODE: usize = 12;
|
||||
const ENCODER_CSC_MODE: usize = 13;
|
||||
const CHROMA_SAMPLING: usize = 14;
|
||||
const ENCRYPTION_ENABLED: usize = 15;
|
||||
const SURROUND_ENABLE: usize = 16;
|
||||
const SURROUND_CHANNELS: usize = 17;
|
||||
const SURROUND_MASK: usize = 18;
|
||||
const AUDIO_QUALITY: usize = 19;
|
||||
|
||||
/// Every attribute read, in the order of the index constants above. The required set is the one a known host
|
||||
/// refuses to stream without (`docs/PROTOCOL.md` 2.5 \[M\]); the others have the defaults documented on
|
||||
/// [`StreamConfig`].
|
||||
const ATTRIBUTES: [Attribute; 20] = [
|
||||
required("x-nv-video[0].clientViewportWd", "announce: x-nv-video[0].clientViewportWd missing"),
|
||||
required("x-nv-video[0].clientViewportHt", "announce: x-nv-video[0].clientViewportHt missing"),
|
||||
required("x-nv-video[0].maxFPS", "announce: x-nv-video[0].maxFPS missing"),
|
||||
required("x-nv-video[0].packetSize", "announce: x-nv-video[0].packetSize missing"),
|
||||
required("x-ml-video.configuredBitrateKbps", "announce: x-ml-video.configuredBitrateKbps missing"),
|
||||
required("x-nv-vqos[0].bitStreamFormat", "announce: x-nv-vqos[0].bitStreamFormat missing"),
|
||||
required("x-nv-vqos[0].fec.minRequiredFecPackets", "announce: x-nv-vqos[0].fec.minRequiredFecPackets missing"),
|
||||
required("x-nv-vqos[0].qosTrafficType", "announce: x-nv-vqos[0].qosTrafficType missing"),
|
||||
required("x-nv-aqos.packetDuration", "announce: x-nv-aqos.packetDuration missing"),
|
||||
required("x-nv-aqos.qosTrafficType", "announce: x-nv-aqos.qosTrafficType missing"),
|
||||
defaulted("x-nv-video[0].maxNumReferenceFrames"),
|
||||
defaulted("x-nv-video[0].refPicInvalidation"),
|
||||
defaulted("x-nv-video[0].dynamicRangeMode"),
|
||||
defaulted("x-nv-video[0].encoderCscMode"),
|
||||
defaulted("x-ss-video[0].chromaSamplingType"),
|
||||
defaulted("x-ss-general.encryptionEnabled"),
|
||||
defaulted("x-nv-audio.surround.enable"),
|
||||
defaulted("x-nv-audio.surround.numChannels"),
|
||||
defaulted("x-nv-audio.surround.channelMask"),
|
||||
defaulted("x-nv-audio.surround.AudioQuality"),
|
||||
];
|
||||
|
||||
/// The values found, one slot per entry of [`ATTRIBUTES`].
|
||||
struct Values<'a, 'b>(&'a [Option<&'b str>; ATTRIBUTES.len()]);
|
||||
|
||||
impl Values<'_, '_> {
|
||||
/// The attribute's number in `lo..=hi`, or `default` when it is absent.
|
||||
fn optional(&self, index: usize, default: u64, lo: u64, hi: u64) -> Result<u64> {
|
||||
let name = ATTRIBUTES.get(index).map_or("announce attribute", |a| a.name);
|
||||
match self.0.get(index).copied().flatten() {
|
||||
None => Ok(default),
|
||||
Some(text) => {
|
||||
let value = parse_dec(name, text)?;
|
||||
if value < lo || value > hi {
|
||||
return Err(Error::UnexpectedValue { what: name, value });
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The attribute's number in `lo..=hi`; refused when absent.
|
||||
fn required(&self, index: usize, lo: u64, hi: u64) -> Result<u64> {
|
||||
if self.0.get(index).copied().flatten().is_none() {
|
||||
let what = ATTRIBUTES.get(index).and_then(|a| a.missing).unwrap_or("announce: attribute missing");
|
||||
return Err(malformed(what));
|
||||
}
|
||||
self.optional(index, 0, lo, hi)
|
||||
}
|
||||
}
|
||||
|
||||
/// A range-checked number into its field type (cannot fail after the range check; never panics either way).
|
||||
fn narrow<T: TryFrom<u64>>(value: u64) -> Result<T> {
|
||||
T::try_from(value).map_err(|_| Error::UnexpectedValue { what: "announce number", value })
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
//! The DESCRIBE answer (`docs/PROTOCOL.md` 2.3, 2.5): what the host offers, written as the SDP lines the client
|
||||
//! reads with [`crate::rtsp::HostCapabilities::from_sdp`].
|
||||
|
||||
use crate::rtsp::sdp::{EncryptionFlags, FeatureFlags, OpusConfig};
|
||||
use crate::rtsp::sdp::{EncryptionFlags, FeatureFlags, MAX_OPUS_CONFIGS, OpusConfig, parse_surround_params};
|
||||
use crate::util::{cap, malformed};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// The `sprop-parameter-sets` line a known host sends; its value is not used by clients (`docs/PROTOCOL.md` 2.3).
|
||||
const SPROP_LINE: &str = "sprop-parameter-sets=AAAAAU";
|
||||
|
||||
/// What the host offers: written into the DESCRIBE answer, and checked against the client's ANNOUNCE.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct HostOffer {
|
||||
@@ -21,7 +25,7 @@ pub struct HostOffer {
|
||||
/// AV1: `a=rtpmap:98 AV1/90000`.
|
||||
pub av1: bool,
|
||||
/// HDR. No DESCRIBE line is known for it (serverinfo again); used only to check ANNOUNCE: without it, a
|
||||
/// `dynamicRangeMode` other than 0 (SDR [M]) is refused.
|
||||
/// `dynamicRangeMode` other than 0 (SDR \[M\]) is refused.
|
||||
pub hdr: bool,
|
||||
/// 4:4:4 chroma. No DESCRIBE line is known; used only to check ANNOUNCE.
|
||||
pub yuv444: bool,
|
||||
@@ -31,7 +35,7 @@ pub struct HostOffer {
|
||||
pub opus_configs: Vec<OpusConfig>,
|
||||
}
|
||||
|
||||
/// Builds the DESCRIBE payload for `offer`, in the line order a known host uses (`docs/PROTOCOL.md` 2.5 [M]):
|
||||
/// Builds the DESCRIBE payload for `offer`, in the line order a known host uses (`docs/PROTOCOL.md` 2.5 \[M\]):
|
||||
/// feature flags, encryption, `sprop-parameter-sets`, reference invalidation, AV1, H.264, then one
|
||||
/// `surround-params` line per Opus configuration. CRLF line ends.
|
||||
///
|
||||
@@ -41,6 +45,41 @@ pub struct HostOffer {
|
||||
/// streams); [`Error::TooLarge`] over [`crate::rtsp::sdp::MAX_OPUS_CONFIGS`]; [`Error::Unsupported`] when no codec
|
||||
/// is offered.
|
||||
pub fn build_describe(offer: &HostOffer) -> Result<Vec<u8>> {
|
||||
let _ = offer;
|
||||
Err(Error::Unimplemented)
|
||||
if !(offer.h264 || offer.hevc || offer.av1) {
|
||||
return Err(Error::Unsupported { what: "a video codec in the host offer" });
|
||||
}
|
||||
cap("describe opus configurations", MAX_OPUS_CONFIGS, offer.opus_configs.len())?;
|
||||
let mut out = String::with_capacity(256 + 48 * offer.opus_configs.len());
|
||||
let mut line = |text: &str| {
|
||||
out.push_str(text);
|
||||
out.push_str("\r\n");
|
||||
};
|
||||
line(&format!("a=x-ss-general.featureFlags:{}", offer.feature_flags.0));
|
||||
line(&format!("a=x-ss-general.encryptionSupported:{}", offer.encryption_supported.0));
|
||||
line(SPROP_LINE);
|
||||
if offer.reference_frame_invalidation {
|
||||
line("a=x-nv-video[0].refPicInvalidation:1");
|
||||
}
|
||||
if offer.av1 {
|
||||
line("a=rtpmap:98 AV1/90000");
|
||||
}
|
||||
if offer.h264 {
|
||||
line("a=fmtp:96 packetization-mode=1");
|
||||
}
|
||||
for config in &offer.opus_configs {
|
||||
line(&format!("a=fmtp:97 surround-params={}", surround_digits(config)?));
|
||||
}
|
||||
Ok(out.into_bytes())
|
||||
}
|
||||
|
||||
/// `surround-params` digits for `config` (`docs/PROTOCOL.md` 2.3): channel count, stream count, coupled count, then
|
||||
/// one mapping digit per channel. The client's own parser checks the result, so nothing it refuses is written.
|
||||
fn surround_digits(config: &OpusConfig) -> Result<String> {
|
||||
let mut digits = String::with_capacity(3 + config.mapping.len());
|
||||
for n in [config.channels, config.streams, config.coupled_streams].iter().chain(&config.mapping) {
|
||||
let d = char::from_digit(u32::from(*n), 10).ok_or(malformed("surround-params: a value above 9"))?;
|
||||
digits.push(d);
|
||||
}
|
||||
parse_surround_params(&digits)?;
|
||||
Ok(digits)
|
||||
}
|
||||
|
||||
@@ -21,11 +21,15 @@ pub use announce::{
|
||||
};
|
||||
pub use describe::{HostOffer, build_describe};
|
||||
|
||||
use super::client::StreamPorts;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use super::client::{StreamPorts, VideoCodec};
|
||||
use super::sdp::EncryptionFlags;
|
||||
use super::{MAX_RTSP_HEADERS, MAX_RTSP_MESSAGE_BYTES, Method, RtspRequest, RtspResponse, parse_request};
|
||||
use crate::util::{hex_encode, malformed, parse_u32};
|
||||
use crate::{Error, RandomSource, Result};
|
||||
|
||||
/// `timeout` of the `Session` header in SETUP answers, in seconds (`docs/PROTOCOL.md` 2.2 [M]).
|
||||
/// `timeout` of the `Session` header in SETUP answers, in seconds (`docs/PROTOCOL.md` 2.2 \[M\]).
|
||||
pub const DEFAULT_SESSION_TIMEOUT_SECS: u32 = 90;
|
||||
/// Random bytes in a session id (RFC 2326 section 3.4: at least eight octets, chosen at random); written as hex.
|
||||
pub const SESSION_ID_BYTES: usize = 8;
|
||||
@@ -89,6 +93,31 @@ pub struct ServerReply {
|
||||
pub struct RtspServer {
|
||||
config: ServerConfig,
|
||||
session_id: String,
|
||||
/// The DESCRIBE payload, built once from the offer.
|
||||
describe: Vec<u8>,
|
||||
state: RtspServerState,
|
||||
/// SETUP answered for audio, video, control.
|
||||
set_up: [bool; 3],
|
||||
/// A SETUP was answered, so the session id is known to the client.
|
||||
session_issued: bool,
|
||||
announced: Option<StreamConfig>,
|
||||
/// At most two events ever (one ANNOUNCE, one PLAY).
|
||||
events: VecDeque<ServerEvent>,
|
||||
}
|
||||
|
||||
/// `Public` in the OPTIONS answer (RFC 2326 section 10.1 example form).
|
||||
const PUBLIC: &str = "OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY";
|
||||
/// The streams of SETUP, in the order of `RtspServer::set_up` (`docs/PROTOCOL.md` 2.2).
|
||||
const STREAMS: [&str; 3] = ["audio", "video", "control"];
|
||||
|
||||
/// The CSeq, headers and payload of a 200 answer.
|
||||
type Answer = (u32, Vec<(String, String)>, Vec<u8>);
|
||||
|
||||
/// A refused request: the status, the CSeq to echo if one was readable, and why.
|
||||
struct Refusal {
|
||||
status: u16,
|
||||
cseq: Option<u32>,
|
||||
error: Error,
|
||||
}
|
||||
|
||||
impl RtspServer {
|
||||
@@ -98,25 +127,175 @@ impl RtspServer {
|
||||
/// [`Error::Malformed`] for a zero port or session timeout, or required encryption the offer lacks; any error
|
||||
/// of [`build_describe`] for the offer.
|
||||
pub fn new(config: ServerConfig, rng: &mut dyn RandomSource) -> Result<Self> {
|
||||
let _ = (config, rng);
|
||||
Err(Error::Unimplemented)
|
||||
let p = config.ports;
|
||||
if p.audio == 0 || p.video == 0 || p.control == 0 {
|
||||
return Err(malformed("rtsp server: stream port 0"));
|
||||
}
|
||||
if config.session_timeout_secs == 0 {
|
||||
return Err(malformed("rtsp server: session timeout 0"));
|
||||
}
|
||||
if !config.offer.encryption_supported.contains(config.required_encryption.0) {
|
||||
return Err(malformed("rtsp server: required encryption is not offered"));
|
||||
}
|
||||
let describe = build_describe(&config.offer)?;
|
||||
let mut id = [0u8; SESSION_ID_BYTES];
|
||||
rng.fill(&mut id);
|
||||
Ok(Self {
|
||||
config,
|
||||
session_id: hex_encode(&id),
|
||||
describe,
|
||||
state: RtspServerState::Options,
|
||||
set_up: [false; 3],
|
||||
session_issued: false,
|
||||
announced: None,
|
||||
events: VecDeque::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Answers one whole request (see [`super::RtspFramer::for_requests`]).
|
||||
/// Answers one whole request (see [`super::RtspFramer::for_requests`]). Never panics; a refusal leaves the
|
||||
/// state as it was.
|
||||
pub fn handle_request(&mut self, message: &[u8]) -> ServerReply {
|
||||
let _ = message;
|
||||
ServerReply { bytes: Vec::new(), status: 501, error: Some(Error::Unimplemented) }
|
||||
match self.answer(message) {
|
||||
Ok((cseq, headers, body)) => reply(200, Some(cseq), headers, body, None),
|
||||
Err(r) => reply(r.status, r.cseq, Vec::new(), Vec::new(), Some(r.error)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The headers and payload of a 200 answer, or why the request is refused.
|
||||
fn answer(&mut self, message: &[u8]) -> core::result::Result<Answer, Refusal> {
|
||||
let request = parse_request(message).map_err(|error| {
|
||||
let status = if matches!(error, Error::UnexpectedValue { what: "rtsp method", .. }) { 501 } else { 400 };
|
||||
Refusal { status, cseq: salvage_cseq(message), error }
|
||||
})?;
|
||||
let cseq = request_cseq(&request).map_err(|error| Refusal { status: 400, cseq: None, error })?;
|
||||
let refuse = |status: u16, error: Error| Refusal { status, cseq: Some(cseq), error };
|
||||
self.check_session(&request).map_err(|(status, error)| refuse(status, error))?;
|
||||
let mut headers = Vec::new();
|
||||
let mut body = Vec::new();
|
||||
match request.method {
|
||||
Method::Options => {
|
||||
// OPTIONS may come at any time and changes nothing else (RFC 2326 section 10.1).
|
||||
if self.state == RtspServerState::Options {
|
||||
self.state = RtspServerState::Describe;
|
||||
}
|
||||
headers.push(("Public".to_owned(), PUBLIC.to_owned()));
|
||||
}
|
||||
Method::Describe => {
|
||||
self.expect(RtspServerState::Describe, "DESCRIBE after OPTIONS").map_err(|e| refuse(455, e))?;
|
||||
headers.push(("Content-Type".to_owned(), "application/sdp".to_owned()));
|
||||
body.clone_from(&self.describe);
|
||||
self.state = RtspServerState::Setup;
|
||||
}
|
||||
Method::Setup => {
|
||||
self.expect(RtspServerState::Setup, "SETUP after DESCRIBE").map_err(|e| refuse(455, e))?;
|
||||
// A Transport header must be present; its value is not interpreted (`docs/PROTOCOL.md` 2.2 [M]).
|
||||
if request.header("Transport").is_none() {
|
||||
return Err(refuse(400, malformed("rtsp SETUP without Transport")));
|
||||
}
|
||||
let index = setup_stream(&request.target).map_err(|e| refuse(400, e))?;
|
||||
let port = self.port(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
|
||||
let slot = self.set_up.get_mut(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
|
||||
if *slot {
|
||||
return Err(refuse(455, Error::State { expected: "one SETUP per stream" }));
|
||||
}
|
||||
*slot = true;
|
||||
self.session_issued = true;
|
||||
if self.set_up.iter().all(|done| *done) {
|
||||
self.state = RtspServerState::Announce;
|
||||
}
|
||||
let session = format!("{};timeout = {}", self.session_id, self.config.session_timeout_secs);
|
||||
headers.push(("Session".to_owned(), session));
|
||||
headers.push(("Transport".to_owned(), format!("server_port={port}")));
|
||||
}
|
||||
Method::Announce => {
|
||||
self.expect(RtspServerState::Announce, "ANNOUNCE after the three SETUPs")
|
||||
.map_err(|e| refuse(455, e))?;
|
||||
let config = parse_announce(&request.body).map_err(|e| refuse(400, e))?;
|
||||
self.check_offer(&config).map_err(|e| refuse(451, e))?;
|
||||
self.events.push_back(ServerEvent::Announced(config.clone()));
|
||||
self.announced = Some(config);
|
||||
self.state = RtspServerState::Play;
|
||||
}
|
||||
Method::Play => {
|
||||
self.expect(RtspServerState::Play, "PLAY after ANNOUNCE").map_err(|e| refuse(455, e))?;
|
||||
self.events.push_back(ServerEvent::PlayRequested);
|
||||
self.state = RtspServerState::Playing;
|
||||
}
|
||||
}
|
||||
Ok((cseq, headers, body))
|
||||
}
|
||||
|
||||
fn expect(&self, state: RtspServerState, expected: &'static str) -> Result<()> {
|
||||
if self.state == state { Ok(()) } else { Err(Error::State { expected }) }
|
||||
}
|
||||
|
||||
/// The UDP port answered for stream `index` (audio, video, control).
|
||||
fn port(&self, index: usize) -> Option<u16> {
|
||||
let p = self.config.ports;
|
||||
[p.audio, p.video, p.control].get(index).copied()
|
||||
}
|
||||
|
||||
/// `Session` checks (`docs/PROTOCOL.md` 2.5): a present id must be the one issued in SETUP; a missing one is
|
||||
/// refused only when the config asks for it.
|
||||
fn check_session(&self, request: &RtspRequest) -> core::result::Result<(), (u16, Error)> {
|
||||
let mut ids = request
|
||||
.headers
|
||||
.iter()
|
||||
.filter(|(n, _)| n.eq_ignore_ascii_case("session"))
|
||||
.map(|(_, v)| v.split(';').next().unwrap_or("").trim_matches([' ', '\t']));
|
||||
let first = ids.next();
|
||||
if let Some(id) = first
|
||||
&& ids.any(|other| other != id)
|
||||
{
|
||||
return Err((400, malformed("rtsp: two different Session headers")));
|
||||
}
|
||||
match first {
|
||||
Some(id) if !self.session_issued || id != self.session_id => {
|
||||
Err((454, malformed("rtsp: Session is not this session's id")))
|
||||
}
|
||||
None if self.config.require_session_header && self.session_issued && request.method != Method::Options => {
|
||||
Err((454, malformed("rtsp: Session missing")))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What ANNOUNCE asks for must be in the offer.
|
||||
fn check_offer(&self, config: &StreamConfig) -> Result<()> {
|
||||
let offer = &self.config.offer;
|
||||
let codec_offered = match config.codec {
|
||||
VideoCodec::H264 => offer.h264,
|
||||
VideoCodec::Hevc => offer.hevc,
|
||||
VideoCodec::Av1 => offer.av1,
|
||||
};
|
||||
if !codec_offered {
|
||||
return Err(Error::Unsupported { what: "the requested video codec" });
|
||||
}
|
||||
if config.encryption.0 & !offer.encryption_supported.0 != 0 {
|
||||
return Err(Error::Unsupported { what: "encryption the host did not offer" });
|
||||
}
|
||||
if !config.encryption.contains(self.config.required_encryption.0) {
|
||||
return Err(Error::Unsupported { what: "a stream without the encryption the host requires" });
|
||||
}
|
||||
// 0 is SDR (`docs/PROTOCOL.md` 2.5 [M]); any other value is "not SDR", without a settled meaning (U6).
|
||||
if config.dynamic_range_mode != 0 && !offer.hdr {
|
||||
return Err(Error::Unsupported { what: "HDR" });
|
||||
}
|
||||
if config.chroma == ChromaSampling::Yuv444 && !offer.yuv444 {
|
||||
return Err(Error::Unsupported { what: "4:4:4 chroma" });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The next event, if any.
|
||||
pub fn poll_event(&mut self) -> Option<ServerEvent> {
|
||||
None
|
||||
self.events.pop_front()
|
||||
}
|
||||
|
||||
/// Which request the session expects next.
|
||||
#[must_use]
|
||||
pub const fn state(&self) -> RtspServerState {
|
||||
RtspServerState::Options
|
||||
self.state
|
||||
}
|
||||
|
||||
/// The session id sent in SETUP answers.
|
||||
@@ -128,7 +307,7 @@ impl RtspServer {
|
||||
/// The accepted ANNOUNCE, once there is one.
|
||||
#[must_use]
|
||||
pub const fn announced(&self) -> Option<&StreamConfig> {
|
||||
None
|
||||
self.announced.as_ref()
|
||||
}
|
||||
|
||||
/// The configuration the session answers with.
|
||||
@@ -137,3 +316,87 @@ impl RtspServer {
|
||||
&self.config
|
||||
}
|
||||
}
|
||||
|
||||
/// The reason phrase of each status the session sends (RFC 2326 section 7.1.1).
|
||||
const fn reason(status: u16) -> &'static str {
|
||||
match status {
|
||||
200 => "OK",
|
||||
400 => "Bad Request",
|
||||
451 => "Parameter Not Understood",
|
||||
454 => "Session Not Found",
|
||||
455 => "Method Not Valid in This State",
|
||||
501 => "Not Implemented",
|
||||
_ => "Internal Server Error",
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the answer: `CSeq` first (when known), the given headers, then `Content-Length` (always, so the client's
|
||||
/// framer never has to wait for the connection to close, `docs/PROTOCOL.md` 2.1 U5).
|
||||
fn reply(
|
||||
status: u16,
|
||||
cseq: Option<u32>,
|
||||
extra: Vec<(String, String)>,
|
||||
body: Vec<u8>,
|
||||
error: Option<Error>,
|
||||
) -> ServerReply {
|
||||
let mut headers = Vec::with_capacity(extra.len() + 2);
|
||||
if let Some(c) = cseq {
|
||||
headers.push(("CSeq".to_owned(), c.to_string()));
|
||||
}
|
||||
headers.extend(extra);
|
||||
headers.push(("Content-Length".to_owned(), body.len().to_string()));
|
||||
match (RtspResponse { status, reason: reason(status).to_owned(), headers, body }).encode() {
|
||||
Ok(bytes) => ServerReply { bytes, status, error },
|
||||
// Only an answer over the message cap could fail, and none is that large; answer 500 rather than panic.
|
||||
Err(e) => ServerReply {
|
||||
bytes: b"RTSP/1.0 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n".to_vec(),
|
||||
status: 500,
|
||||
error: Some(e),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The request's CSeq: present, plain decimal `u32`, every copy equal.
|
||||
fn request_cseq(request: &RtspRequest) -> Result<u32> {
|
||||
let mut found = None;
|
||||
for (_, v) in request.headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case("cseq")) {
|
||||
let n = parse_u32("rtsp CSeq", v)?;
|
||||
if found.is_some_and(|f| f != n) {
|
||||
return Err(malformed("rtsp: two different CSeq values"));
|
||||
}
|
||||
found = Some(n);
|
||||
}
|
||||
found.ok_or(malformed("rtsp request without CSeq"))
|
||||
}
|
||||
|
||||
/// The CSeq of a request that did not parse, if a header line says it plainly, so the refusal can still echo it.
|
||||
/// Reads at most the header section, at most [`MAX_RTSP_HEADERS`] lines, and allocates nothing.
|
||||
fn salvage_cseq(message: &[u8]) -> Option<u32> {
|
||||
let head = message.get(..message.len().min(MAX_RTSP_MESSAGE_BYTES))?;
|
||||
for raw in head.split(|&b| b == b'\n').skip(1).take(MAX_RTSP_HEADERS) {
|
||||
let line = raw.strip_suffix(b"\r").unwrap_or(raw);
|
||||
if line.is_empty() {
|
||||
break;
|
||||
}
|
||||
let Ok(text) = core::str::from_utf8(line) else { continue };
|
||||
if let Some((name, value)) = text.split_once(':')
|
||||
&& name.eq_ignore_ascii_case("cseq")
|
||||
{
|
||||
return parse_u32("rtsp CSeq", value.trim_matches([' ', '\t'])).ok();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The stream a SETUP target names: exactly one `streamid=` followed by `audio`, `video` or `control`, ended by
|
||||
/// `/`, `?`, `&`, `;` or the end (`docs/PROTOCOL.md` 2.2 \[M\], 2.5). Index into [`STREAMS`].
|
||||
fn setup_stream(target: &str) -> Result<usize> {
|
||||
let mut parts = target.split("streamid=");
|
||||
parts.next();
|
||||
let after = parts.next().ok_or(malformed("rtsp SETUP target without streamid"))?;
|
||||
if parts.next().is_some() {
|
||||
return Err(malformed("rtsp SETUP target with two streamid"));
|
||||
}
|
||||
let name = after.split(['/', '?', '&', ';']).next().unwrap_or("");
|
||||
STREAMS.iter().position(|s| *s == name).ok_or(malformed("rtsp SETUP streamid"))
|
||||
}
|
||||
|
||||
@@ -62,23 +62,12 @@ fn lying_inputs() -> Vec<Case> {
|
||||
));
|
||||
v.push((
|
||||
"rtsp server",
|
||||
b"ANNOUNCE x RTSP/1.0
|
||||
CSeq: 1
|
||||
Content-Length: 4294967295
|
||||
|
||||
abc"
|
||||
.to_vec(),
|
||||
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|
||||
rtsp_server_answers,
|
||||
));
|
||||
// ANNOUNCE: numbers far past any range, a line that claims nothing but is long, many unknown attributes.
|
||||
let mut announce = b"a=x-nv-video[0].clientViewportWd:99999999999999999999999999999999
|
||||
"
|
||||
.to_vec();
|
||||
announce.extend_from_slice(
|
||||
&b"a=u:1
|
||||
"
|
||||
.repeat(600),
|
||||
);
|
||||
// ANNOUNCE: a number far past any range, then more unknown attributes than the cap allows.
|
||||
let mut announce = b"a=x-nv-video[0].clientViewportWd:99999999999999999999999999999999\n".to_vec();
|
||||
announce.extend_from_slice(&b"a=u:1\n".repeat(600));
|
||||
v.push(("announce", announce, |b| common::implemented(&domistream::rtsp::server::parse_announce(b))));
|
||||
v.push(("rtsp framer", rtsp, |b| {
|
||||
let mut f = domistream::rtsp::RtspFramer::new();
|
||||
|
||||
@@ -249,6 +249,9 @@ fn client_stops_when_server_refuses_the_codec() {
|
||||
|
||||
// ================================================================================================ scripted requests
|
||||
|
||||
/// One scripted request.
|
||||
type Step = fn(&mut Script, &mut RtspServer) -> ServerReply;
|
||||
|
||||
/// Sends hand-made requests with counting CSeq values and, once known, the session id.
|
||||
struct Script {
|
||||
cseq: u32,
|
||||
@@ -314,7 +317,7 @@ impl Script {
|
||||
|
||||
/// Valid requests until the server expects `state`.
|
||||
fn advance_to(&mut self, s: &mut RtspServer, state: RtspServerState) {
|
||||
let steps: [(RtspServerState, fn(&mut Self, &mut RtspServer) -> ServerReply); 7] = [
|
||||
let steps: [(RtspServerState, Step); 7] = [
|
||||
(RtspServerState::Options, Self::options),
|
||||
(RtspServerState::Describe, Self::describe),
|
||||
(RtspServerState::Setup, |sc, s| sc.setup(s, "audio")),
|
||||
@@ -384,7 +387,6 @@ fn session_timeout_is_configurable() {
|
||||
|
||||
#[test]
|
||||
fn order_violations_get_455_and_change_nothing() {
|
||||
type Step = fn(&mut Script, &mut RtspServer) -> ServerReply;
|
||||
let describe: Step = Script::describe;
|
||||
let setup: Step = |sc, s| sc.setup(s, "audio");
|
||||
let announce: Step = |sc, s| sc.announce(s, &write_announce(&host_config()));
|
||||
@@ -440,7 +442,8 @@ fn options_at_any_time_and_setup_once_each() {
|
||||
|
||||
#[test]
|
||||
fn setup_targets_and_transport() {
|
||||
let cases: [(&str, &[(&str, &str)], u16); 9] = [
|
||||
type Case<'a> = (&'a str, &'a [(&'a str, &'a str)], u16);
|
||||
let cases: [Case<'_>; 9] = [
|
||||
("streamid=video/0/0", &[("Transport", "x")], 200),
|
||||
("rtsp://192.0.2.10:48010/streamid=video/0/0", &[("Transport", "x")], 200),
|
||||
("streamid=video", &[("Transport", "x")], 200),
|
||||
@@ -553,7 +556,7 @@ fn cseq_is_echoed_and_required() {
|
||||
assert_refused(&reply, 400);
|
||||
assert!(matches!(reply.error, Some(Error::Malformed { .. })), "{bad:?}: {reply:?}");
|
||||
}
|
||||
assert_eq!(s.state(), RtspServerState::Options);
|
||||
assert_eq!(s.state(), RtspServerState::Describe, "the accepted OPTIONS moved it; the refusals did not");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -748,14 +751,15 @@ fn describe_follows_the_offer() {
|
||||
|
||||
#[test]
|
||||
fn describe_refuses_what_the_client_would_refuse() {
|
||||
let mut bad = Vec::new();
|
||||
bad.push(OpusConfig { channels: 0, streams: 1, coupled_streams: 0, mapping: vec![] });
|
||||
bad.push(OpusConfig { channels: 2, streams: 0, coupled_streams: 0, mapping: vec![0, 0] });
|
||||
bad.push(OpusConfig { channels: 2, streams: 1, coupled_streams: 2, mapping: vec![0, 1] });
|
||||
bad.push(OpusConfig { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0] });
|
||||
bad.push(OpusConfig { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0, 2] });
|
||||
bad.push(OpusConfig { channels: 8, streams: 10, coupled_streams: 0, mapping: vec![0; 8] });
|
||||
bad.push(OpusConfig { channels: 2, streams: 12, coupled_streams: 1, mapping: vec![0, 10] });
|
||||
let bad = [
|
||||
OpusConfig { channels: 0, streams: 1, coupled_streams: 0, mapping: vec![] },
|
||||
OpusConfig { channels: 2, streams: 0, coupled_streams: 0, mapping: vec![0, 0] },
|
||||
OpusConfig { channels: 2, streams: 1, coupled_streams: 2, mapping: vec![0, 1] },
|
||||
OpusConfig { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0] },
|
||||
OpusConfig { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0, 2] },
|
||||
OpusConfig { channels: 8, streams: 10, coupled_streams: 0, mapping: vec![0; 8] },
|
||||
OpusConfig { channels: 2, streams: 12, coupled_streams: 1, mapping: vec![0, 10] },
|
||||
];
|
||||
for c in bad {
|
||||
let o = HostOffer { opus_configs: vec![c.clone()], ..offer() };
|
||||
assert_err!(build_describe(&o), Error::Malformed { .. }, "{c:?}");
|
||||
@@ -1254,7 +1258,9 @@ proptest! {
|
||||
/// Random request sequences: every answer parses and echoes CSeq, the status is one of the documented ones, the
|
||||
/// state only moves forward, and the events come at most once each, in order.
|
||||
#[test]
|
||||
fn server_random_sequences(steps in proptest::collection::vec((0u8..7, 0u8..6, 0u8..3, 0u8..3, any::<u32>()), 0..24)) {
|
||||
fn server_random_sequences(
|
||||
steps in proptest::collection::vec((0u8..7, 0u8..6, 0u8..3, 0u8..3, any::<u32>()), 0..24),
|
||||
) {
|
||||
let mut s = server();
|
||||
let id = s.session_id().to_string();
|
||||
let good_announce = write_announce(&host_config());
|
||||
@@ -1263,9 +1269,14 @@ proptest! {
|
||||
for (m, t, sess, body, cseq) in steps {
|
||||
let target = ["rtsp://192.0.2.10:48010", "streamid=audio/0/0", "streamid=video/0/0",
|
||||
"streamid=control/13/0", "streamid=bogus/0/0", "*"][usize::from(t)];
|
||||
let session = match sess { 1 => format!("Session: {id}\r\n"), 2 => "Session: nope\r\n".into(), _ => String::new() };
|
||||
let session = match sess {
|
||||
1 => format!("Session: {id}\r\n"),
|
||||
2 => "Session: nope\r\n".into(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let body: &[u8] = match body { 1 => &good_announce, 2 => b"v=0\r\nx\r\n", _ => b"" };
|
||||
let method = ["OPTIONS", "DESCRIBE", "SETUP", "ANNOUNCE", "PLAY", "TEARDOWN", "GARBAGE GARBAGE"][usize::from(m)];
|
||||
let methods = ["OPTIONS", "DESCRIBE", "SETUP", "ANNOUNCE", "PLAY", "TEARDOWN", "GARBAGE GARBAGE"];
|
||||
let method = methods[usize::from(m)];
|
||||
let mut req = format!("{method} {target} RTSP/1.0\r\nCSeq: {cseq}\r\n{session}Transport: x\r\n");
|
||||
if !body.is_empty() {
|
||||
req.push_str(&format!("Content-Length: {}\r\n", body.len()));
|
||||
|
||||
Reference in New Issue
Block a user