1327 lines
56 KiB
Rust
1327 lines
56 KiB
Rust
//! The host's RTSP session (`docs/PROTOCOL.md` 2.2, 2.5): the DESCRIBE writer, the strict ANNOUNCE parser and the
|
|
//! session state machine, driven by our own client entirely in memory, plus order violations, session checks and
|
|
//! hostile input.
|
|
|
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
|
|
|
mod common;
|
|
|
|
use domistream::Error;
|
|
use domistream::http::launch::AudioLayout;
|
|
use domistream::rtsp::client::VideoCodec;
|
|
use domistream::rtsp::sdp::{self, FeatureFlags, MAX_OPUS_CONFIGS};
|
|
use domistream::rtsp::server::{
|
|
ChromaSampling, DEFAULT_SESSION_TIMEOUT_SECS, MAX_ANNOUNCE_ATTRIBUTES, MAX_ANNOUNCE_BYTES, MAX_ANNOUNCE_LINE_BYTES,
|
|
MAX_ANNOUNCE_LINES, MAX_AUDIO_PACKET_DURATION_MS, MAX_BITRATE_KBPS, MAX_DIMENSION, MAX_FPS, MAX_PACKET_SIZE,
|
|
MIN_PACKET_SIZE, SESSION_ID_BYTES, StreamConfig as HostStreamConfig, SurroundSettings, build_describe,
|
|
parse_announce, write_announce,
|
|
};
|
|
use domistream::rtsp::{
|
|
EncryptionFlags, HostCapabilities, HostOffer, MAX_RTSP_MESSAGE_BYTES, Method, NegotiatedStream, OpusConfig,
|
|
RtspClient, RtspClientState, RtspFramer, RtspProgress, RtspRequest, RtspResponse, RtspServer, RtspServerState,
|
|
ServerConfig, ServerEvent, ServerReply, StreamConfig as ClientConfig, StreamPorts, parse_response,
|
|
};
|
|
use proptest::prelude::*;
|
|
|
|
const URL: &str = "rtsp://192.0.2.10:48010";
|
|
const ALL: u8 = EncryptionFlags::CONTROL_V2 | EncryptionFlags::VIDEO | EncryptionFlags::AUDIO;
|
|
const PORTS: StreamPorts = StreamPorts { audio: 48000, video: 47998, control: 47999 };
|
|
|
|
fn opus(digits: &str) -> OpusConfig {
|
|
sdp::parse_surround_params(digits).unwrap()
|
|
}
|
|
|
|
fn offer() -> HostOffer {
|
|
HostOffer {
|
|
feature_flags: FeatureFlags(3),
|
|
encryption_supported: EncryptionFlags(ALL),
|
|
reference_frame_invalidation: true,
|
|
h264: true,
|
|
hevc: true,
|
|
av1: true,
|
|
hdr: true,
|
|
yuv444: false,
|
|
opus_configs: vec![opus("21101"), opus("642012345"), opus("85301234567")],
|
|
}
|
|
}
|
|
|
|
fn server_config() -> ServerConfig {
|
|
ServerConfig {
|
|
ports: PORTS,
|
|
offer: offer(),
|
|
required_encryption: EncryptionFlags(EncryptionFlags::CONTROL_V2),
|
|
require_session_header: false,
|
|
session_timeout_secs: DEFAULT_SESSION_TIMEOUT_SECS,
|
|
}
|
|
}
|
|
|
|
fn server_with(config: ServerConfig) -> RtspServer {
|
|
RtspServer::new(config, &mut common::SeqRng::new(42)).expect("a valid server config")
|
|
}
|
|
|
|
fn server() -> RtspServer {
|
|
server_with(server_config())
|
|
}
|
|
|
|
fn client_config() -> ClientConfig {
|
|
ClientConfig {
|
|
width: 1920,
|
|
height: 1080,
|
|
fps: 60,
|
|
bitrate_kbps: 20_000,
|
|
packet_size: 1024,
|
|
codec: VideoCodec::Hevc,
|
|
hdr: false,
|
|
audio: AudioLayout::Stereo,
|
|
audio_packet_duration_ms: 5,
|
|
min_fec_packets: 2,
|
|
reference_frame_invalidation: true,
|
|
encryption: EncryptionFlags(ALL),
|
|
}
|
|
}
|
|
|
|
/// What the host must read from our client's ANNOUNCE for `c` (the client's builder in `rtsp::sdp`).
|
|
fn expected_from_client(c: &ClientConfig, enabled: EncryptionFlags) -> HostStreamConfig {
|
|
let channels = c.audio.channels();
|
|
HostStreamConfig {
|
|
width: c.width,
|
|
height: c.height,
|
|
max_fps: c.fps,
|
|
packet_size: c.packet_size,
|
|
bitrate_kbps: c.bitrate_kbps,
|
|
codec: c.codec,
|
|
min_fec_packets: c.min_fec_packets,
|
|
video_qos_traffic_type: 5,
|
|
audio_packet_duration_ms: c.audio_packet_duration_ms,
|
|
audio_qos_traffic_type: 4,
|
|
max_reference_frames: if c.reference_frame_invalidation { 0 } else { 1 },
|
|
reference_frame_invalidation: c.reference_frame_invalidation,
|
|
dynamic_range_mode: u32::from(c.hdr),
|
|
encoder_csc_mode: if c.hdr { 5 } else { 0 },
|
|
chroma: ChromaSampling::Yuv420,
|
|
encryption: enabled,
|
|
surround: SurroundSettings {
|
|
enabled: channels > 2,
|
|
channels,
|
|
channel_mask: c.audio.channel_mask(),
|
|
high_quality: true,
|
|
},
|
|
unknown_attributes: 0,
|
|
}
|
|
}
|
|
|
|
fn host_config() -> HostStreamConfig {
|
|
expected_from_client(&client_config(), EncryptionFlags(ALL))
|
|
}
|
|
|
|
// ================================================================================================ client ↔ server
|
|
|
|
/// Runs our client against the server in memory, writing each side's bytes `chunk` bytes at a time. Returns what
|
|
/// the client negotiated and the server's events in order.
|
|
fn run_session(
|
|
client: ClientConfig,
|
|
server: &mut RtspServer,
|
|
chunk: usize,
|
|
) -> (domistream::Result<NegotiatedStream>, Vec<ServerEvent>) {
|
|
let mut c = RtspClient::new(URL, client).unwrap();
|
|
let mut to_server = RtspFramer::for_requests();
|
|
let mut to_client = RtspFramer::new();
|
|
let mut events = Vec::new();
|
|
for _ in 0..16 {
|
|
let Some(request) = c.poll_request() else { break };
|
|
let mut replies = Vec::new();
|
|
for piece in request.chunks(chunk) {
|
|
to_server.push(piece).unwrap();
|
|
while let Some(m) = to_server.next_message().unwrap() {
|
|
let reply = server.handle_request(&m);
|
|
assert_eq!(parse_response(&reply.bytes).expect("the server's answer parses").status, reply.status);
|
|
assert_eq!(reply.status == 200, reply.error.is_none(), "{reply:?}");
|
|
replies.push(reply);
|
|
}
|
|
}
|
|
assert_eq!(replies.len(), 1, "one request, one answer");
|
|
assert_eq!(to_server.buffered(), 0);
|
|
while let Some(e) = server.poll_event() {
|
|
events.push(e);
|
|
}
|
|
let mut answer = None;
|
|
for piece in replies[0].bytes.chunks(chunk) {
|
|
to_client.push(piece).unwrap();
|
|
if let Some(m) = to_client.next_message().unwrap() {
|
|
assert!(answer.is_none(), "one answer");
|
|
answer = Some(m);
|
|
}
|
|
}
|
|
let answer = answer.expect("the answer is framed by Content-Length, not by close");
|
|
match c.handle_response(&answer) {
|
|
Ok(RtspProgress::Continue) => {}
|
|
Ok(RtspProgress::Ready(n)) => return (Ok(n), events),
|
|
Err(e) => return (Err(e), events),
|
|
}
|
|
}
|
|
panic!("the client never finished (state {:?})", c.state());
|
|
}
|
|
|
|
#[test]
|
|
fn client_and_server_negotiate_in_memory() {
|
|
let mut s = server();
|
|
assert_eq!(s.state(), RtspServerState::Options);
|
|
let (n, events) = run_session(client_config(), &mut s, usize::MAX);
|
|
let n = n.expect("the client reaches Ready against our server");
|
|
assert_eq!(n.ports, PORTS);
|
|
assert_eq!(n.encryption, EncryptionFlags(ALL));
|
|
assert_eq!(n.session_id.as_deref(), Some(s.session_id()));
|
|
assert_eq!(
|
|
n.host,
|
|
HostCapabilities {
|
|
encryption_supported: EncryptionFlags(ALL),
|
|
feature_flags: FeatureFlags(3),
|
|
reference_frame_invalidation: true,
|
|
av1: true,
|
|
opus_configs: offer().opus_configs,
|
|
}
|
|
);
|
|
assert_eq!(n.opus, opus("21101"));
|
|
assert_eq!(events, vec![ServerEvent::Announced(host_config()), ServerEvent::PlayRequested]);
|
|
assert_eq!(s.state(), RtspServerState::Playing);
|
|
assert_eq!(s.announced(), Some(&host_config()));
|
|
assert_eq!(s.poll_event(), None);
|
|
}
|
|
|
|
#[test]
|
|
fn client_and_server_one_byte_at_a_time() {
|
|
let mut s = server();
|
|
let (n, events) = run_session(client_config(), &mut s, 1);
|
|
assert_eq!(n.unwrap().ports, PORTS);
|
|
assert_eq!(events.len(), 2);
|
|
assert_eq!(s.state(), RtspServerState::Playing);
|
|
}
|
|
|
|
#[test]
|
|
fn client_and_server_every_codec_layout_and_mode() {
|
|
for codec in [VideoCodec::H264, VideoCodec::Hevc, VideoCodec::Av1] {
|
|
for audio in [AudioLayout::Stereo, AudioLayout::Surround51, AudioLayout::Surround71] {
|
|
for (hdr, rfi) in [(false, false), (true, true), (false, true)] {
|
|
let c = ClientConfig { codec, audio, hdr, reference_frame_invalidation: rfi, ..client_config() };
|
|
let mut s = server();
|
|
let (n, events) = run_session(c.clone(), &mut s, 7);
|
|
let n = n.unwrap_or_else(|e| panic!("{codec:?} {audio:?} hdr={hdr}: {e:?}"));
|
|
assert_eq!(n.opus.channels, audio.channels());
|
|
assert_eq!(
|
|
events[0],
|
|
ServerEvent::Announced(expected_from_client(&c, EncryptionFlags(ALL))),
|
|
"{codec:?} {audio:?} hdr={hdr} rfi={rfi}"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn client_and_server_partial_encryption() {
|
|
// The host offers control V2 and audio only: the client turns on exactly those, the server accepts them.
|
|
let mut cfg = server_config();
|
|
cfg.offer.encryption_supported = EncryptionFlags(EncryptionFlags::CONTROL_V2 | EncryptionFlags::AUDIO);
|
|
let mut s = server_with(cfg);
|
|
let (n, events) = run_session(client_config(), &mut s, usize::MAX);
|
|
assert_eq!(n.unwrap().encryption, EncryptionFlags(5));
|
|
assert_eq!(events[0], ServerEvent::Announced(expected_from_client(&client_config(), EncryptionFlags(5))));
|
|
}
|
|
|
|
#[test]
|
|
fn client_stops_when_server_refuses_the_codec() {
|
|
// AV1 not offered: the client refuses on its own before ANNOUNCE (DESCRIBE has no rtpmap:98).
|
|
let mut cfg = server_config();
|
|
cfg.offer.av1 = false;
|
|
let mut s = server_with(cfg);
|
|
let (n, events) = run_session(ClientConfig { codec: VideoCodec::Av1, ..client_config() }, &mut s, usize::MAX);
|
|
assert_err!(n, Error::Unsupported { .. });
|
|
assert!(events.is_empty());
|
|
// HEVC not offered: DESCRIBE cannot say so, the server refuses the ANNOUNCE with 451 and the client stops.
|
|
let mut cfg = server_config();
|
|
cfg.offer.hevc = false;
|
|
let mut s = server_with(cfg);
|
|
let (n, events) = run_session(client_config(), &mut s, usize::MAX);
|
|
assert_eq!(n.unwrap_err(), Error::HostStatus { code: 451 });
|
|
assert!(events.is_empty());
|
|
assert_eq!(s.state(), RtspServerState::Announce);
|
|
}
|
|
|
|
// ================================================================================================ scripted requests
|
|
|
|
/// Sends hand-made requests with counting CSeq values and, once known, the session id.
|
|
struct Script {
|
|
cseq: u32,
|
|
session: Option<String>,
|
|
send_session: bool,
|
|
}
|
|
|
|
impl Script {
|
|
fn new() -> Self {
|
|
Self { cseq: 0, session: None, send_session: true }
|
|
}
|
|
|
|
fn raw(
|
|
&mut self,
|
|
s: &mut RtspServer,
|
|
method: Method,
|
|
target: &str,
|
|
extra: &[(&str, &str)],
|
|
body: &[u8],
|
|
) -> ServerReply {
|
|
self.cseq += 1;
|
|
let mut headers = vec![("CSeq".to_string(), self.cseq.to_string())];
|
|
if self.send_session
|
|
&& let Some(id) = &self.session
|
|
{
|
|
headers.push(("Session".into(), id.clone()));
|
|
}
|
|
headers.extend(extra.iter().map(|(k, v)| (k.to_string(), v.to_string())));
|
|
if !body.is_empty() {
|
|
headers.push(("Content-Length".into(), body.len().to_string()));
|
|
}
|
|
let bytes = RtspRequest { method, target: target.into(), headers, body: body.to_vec() }.encode().unwrap();
|
|
let reply = s.handle_request(&bytes);
|
|
let r = parse_response(&reply.bytes).expect("every answer parses");
|
|
assert_eq!(r.status, reply.status);
|
|
assert_eq!(r.header("CSeq"), Some(self.cseq.to_string().as_str()), "CSeq echoed: {reply:?}");
|
|
assert_eq!(reply.status == 200, reply.error.is_none(), "{reply:?}");
|
|
if reply.status == 200
|
|
&& method == Method::Setup
|
|
&& let Some(v) = r.header("Session")
|
|
{
|
|
self.session = Some(v.split(';').next().unwrap().trim().to_string());
|
|
}
|
|
reply
|
|
}
|
|
|
|
fn options(&mut self, s: &mut RtspServer) -> ServerReply {
|
|
self.raw(s, Method::Options, URL, &[], b"")
|
|
}
|
|
fn describe(&mut self, s: &mut RtspServer) -> ServerReply {
|
|
self.raw(s, Method::Describe, URL, &[("Accept", "application/sdp")], b"")
|
|
}
|
|
fn setup(&mut self, s: &mut RtspServer, stream: &str) -> ServerReply {
|
|
let target = format!("streamid={stream}/0/0");
|
|
self.raw(s, Method::Setup, &target, &[("Transport", "unicast;X-GS-ClientPort=50000-50001")], b"")
|
|
}
|
|
fn announce(&mut self, s: &mut RtspServer, body: &[u8]) -> ServerReply {
|
|
self.raw(s, Method::Announce, "streamid=control/13/0", &[("Content-type", "application/sdp")], body)
|
|
}
|
|
fn play(&mut self, s: &mut RtspServer) -> ServerReply {
|
|
self.raw(s, Method::Play, URL, &[], b"")
|
|
}
|
|
|
|
/// 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] = [
|
|
(RtspServerState::Options, Self::options),
|
|
(RtspServerState::Describe, Self::describe),
|
|
(RtspServerState::Setup, |sc, s| sc.setup(s, "audio")),
|
|
(RtspServerState::Setup, |sc, s| sc.setup(s, "video")),
|
|
(RtspServerState::Setup, |sc, s| sc.setup(s, "control")),
|
|
(RtspServerState::Announce, |sc, s| sc.announce(s, &write_announce(&host_config()))),
|
|
(RtspServerState::Play, Self::play),
|
|
];
|
|
for (at, step) in steps {
|
|
if s.state() == state {
|
|
return;
|
|
}
|
|
// Steps before the current state are done already (a SETUP state here means none is done yet).
|
|
if rank(at) < rank(s.state()) {
|
|
continue;
|
|
}
|
|
assert_eq!(s.state(), at);
|
|
assert_eq!(step(self, s).status, 200);
|
|
}
|
|
assert_eq!(s.state(), state);
|
|
}
|
|
}
|
|
|
|
fn assert_refused(reply: &ServerReply, status: u16) {
|
|
assert_eq!(reply.status, status, "{reply:?}");
|
|
assert!(reply.error.is_some(), "{reply:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn answers_carry_what_the_client_needs() {
|
|
let mut s = server();
|
|
let mut sc = Script::new();
|
|
let r = parse_response(&sc.options(&mut s).bytes).unwrap();
|
|
let public = r.header("Public").expect("OPTIONS lists the methods");
|
|
for m in ["OPTIONS", "DESCRIBE", "SETUP", "ANNOUNCE", "PLAY"] {
|
|
assert!(public.split(',').any(|p| p.trim() == m), "{public}");
|
|
}
|
|
assert_eq!(r.header("Content-Length"), Some("0"));
|
|
|
|
let r = parse_response(&sc.describe(&mut s).bytes).unwrap();
|
|
assert_eq!(r.header("Content-Type"), Some("application/sdp"));
|
|
assert_eq!(r.header("Content-Length"), Some(r.body.len().to_string().as_str()));
|
|
assert_eq!(r.body, build_describe(&offer()).unwrap());
|
|
|
|
for (stream, port) in [("video", PORTS.video), ("control", PORTS.control), ("audio", PORTS.audio)] {
|
|
let r = parse_response(&sc.setup(&mut s, stream).bytes).unwrap();
|
|
assert_eq!(r.status, 200);
|
|
assert_eq!(r.header("Transport"), Some(format!("server_port={port}").as_str()));
|
|
assert_eq!(r.header("Session"), Some(format!("{};timeout = 90", s.session_id()).as_str()));
|
|
}
|
|
assert_eq!(s.state(), RtspServerState::Announce, "SETUP in any order, each once");
|
|
let r = parse_response(&sc.announce(&mut s, &write_announce(&host_config())).bytes).unwrap();
|
|
assert_eq!((r.status, r.body.len()), (200, 0));
|
|
let r = parse_response(&sc.play(&mut s).bytes).unwrap();
|
|
assert_eq!((r.status, r.body.len()), (200, 0));
|
|
assert_eq!(s.state(), RtspServerState::Playing);
|
|
}
|
|
|
|
#[test]
|
|
fn session_timeout_is_configurable() {
|
|
let mut s = server_with(ServerConfig { session_timeout_secs: 30, ..server_config() });
|
|
let mut sc = Script::new();
|
|
sc.advance_to(&mut s, RtspServerState::Setup);
|
|
let r = parse_response(&sc.setup(&mut s, "audio").bytes).unwrap();
|
|
assert_eq!(r.header("Session"), Some(format!("{};timeout = 30", s.session_id()).as_str()));
|
|
}
|
|
|
|
#[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()));
|
|
let play: Step = Script::play;
|
|
let cases: [(RtspServerState, &[Step]); 5] = [
|
|
(RtspServerState::Options, &[describe, setup, announce, play]),
|
|
(RtspServerState::Describe, &[setup, announce, play]),
|
|
(RtspServerState::Setup, &[describe, announce, play]),
|
|
(RtspServerState::Announce, &[describe, setup, play]),
|
|
(RtspServerState::Play, &[describe, setup, announce]),
|
|
];
|
|
for (state, wrong) in cases {
|
|
for (i, step) in wrong.iter().enumerate() {
|
|
let mut s = server();
|
|
let mut sc = Script::new();
|
|
sc.advance_to(&mut s, state);
|
|
while s.poll_event().is_some() {}
|
|
let reply = step(&mut sc, &mut s);
|
|
assert_refused(&reply, 455);
|
|
assert!(matches!(reply.error, Some(Error::State { .. })), "{state:?} #{i}: {reply:?}");
|
|
assert_eq!(s.state(), state, "a refused request changes nothing");
|
|
assert_eq!(s.poll_event(), None, "a refused request raises no event");
|
|
// The right next request still works.
|
|
sc.advance_to(&mut s, RtspServerState::Playing);
|
|
}
|
|
}
|
|
// After PLAY nothing but OPTIONS.
|
|
let mut s = server();
|
|
let mut sc = Script::new();
|
|
sc.advance_to(&mut s, RtspServerState::Playing);
|
|
for step in [describe, setup, announce, play] {
|
|
assert_refused(&step(&mut sc, &mut s), 455);
|
|
}
|
|
assert_eq!(sc.options(&mut s).status, 200, "OPTIONS may come at any time (RFC 2326 10.1)");
|
|
assert_eq!(s.state(), RtspServerState::Playing);
|
|
}
|
|
|
|
#[test]
|
|
fn options_at_any_time_and_setup_once_each() {
|
|
let mut s = server();
|
|
let mut sc = Script::new();
|
|
sc.advance_to(&mut s, RtspServerState::Setup);
|
|
assert_eq!(sc.options(&mut s).status, 200);
|
|
assert_eq!(s.state(), RtspServerState::Setup);
|
|
assert_eq!(sc.setup(&mut s, "video").status, 200);
|
|
assert_refused(&sc.setup(&mut s, "video"), 455);
|
|
assert_eq!(sc.options(&mut s).status, 200);
|
|
assert_eq!(sc.setup(&mut s, "audio").status, 200);
|
|
assert_refused(&sc.announce(&mut s, &write_announce(&host_config())), 455);
|
|
assert_eq!(sc.setup(&mut s, "control").status, 200);
|
|
assert_eq!(s.state(), RtspServerState::Announce);
|
|
}
|
|
|
|
#[test]
|
|
fn setup_targets_and_transport() {
|
|
let cases: [(&str, &[(&str, &str)], u16); 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),
|
|
("streamid=video/0/0", &[], 400),
|
|
("streamid=bogus/0/0", &[("Transport", "x")], 400),
|
|
("streamid=/0/0", &[("Transport", "x")], 400),
|
|
("rtsp://192.0.2.10:48010", &[("Transport", "x")], 400),
|
|
("streamid=video/streamid=audio", &[("Transport", "x")], 400),
|
|
("streamid=Video/0/0", &[("Transport", "x")], 400),
|
|
];
|
|
for (target, headers, status) in cases {
|
|
let mut s = server();
|
|
let mut sc = Script::new();
|
|
sc.advance_to(&mut s, RtspServerState::Setup);
|
|
let reply = sc.raw(&mut s, Method::Setup, target, headers, b"");
|
|
assert_eq!(reply.status, status, "{target:?} {headers:?}: {reply:?}");
|
|
if status != 200 {
|
|
assert!(matches!(reply.error, Some(Error::Malformed { .. })), "{reply:?}");
|
|
assert_eq!(s.state(), RtspServerState::Setup);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn session_id_is_random_hex_and_checked() {
|
|
let a = RtspServer::new(server_config(), &mut common::SeqRng::new(1)).unwrap();
|
|
let b = RtspServer::new(server_config(), &mut common::SeqRng::new(2)).unwrap();
|
|
let a2 = RtspServer::new(server_config(), &mut common::SeqRng::new(1)).unwrap();
|
|
assert_eq!(a.session_id().len(), 2 * SESSION_ID_BYTES);
|
|
assert!(a.session_id().bytes().all(|c| c.is_ascii_hexdigit()));
|
|
assert_ne!(a.session_id(), b.session_id());
|
|
assert_eq!(a.session_id(), a2.session_id(), "the id comes only from the RandomSource");
|
|
|
|
// A wrong Session after the first SETUP: 454, nothing changes; the right one still works.
|
|
let mut s = server();
|
|
let mut sc = Script::new();
|
|
sc.advance_to(&mut s, RtspServerState::Setup);
|
|
assert_eq!(sc.setup(&mut s, "audio").status, 200);
|
|
let right = sc.session.clone().unwrap();
|
|
assert_eq!(right, s.session_id());
|
|
for wrong in ["0000000000000000", "", "x", &right.to_uppercase(), &format!("{right}0")] {
|
|
if wrong == right {
|
|
continue;
|
|
}
|
|
sc.session = Some(wrong.to_string());
|
|
let reply = sc.setup(&mut s, "video");
|
|
assert_refused(&reply, 454);
|
|
assert_eq!(s.state(), RtspServerState::Setup);
|
|
}
|
|
// The id with parameters after `;` is the same id.
|
|
sc.session = Some(format!("{right};timeout=90"));
|
|
assert_eq!(sc.setup(&mut s, "video").status, 200);
|
|
sc.session = Some(right.clone());
|
|
// Two Session headers that disagree.
|
|
let reply = sc.raw(&mut s, Method::Setup, "streamid=control/0/0", &[("Session", "other"), ("Transport", "x")], b"");
|
|
assert_refused(&reply, 400);
|
|
assert_eq!(sc.setup(&mut s, "control").status, 200);
|
|
// Without a Session header: allowed by default (U5).
|
|
sc.send_session = false;
|
|
assert_eq!(sc.announce(&mut s, &write_announce(&host_config())).status, 200);
|
|
}
|
|
|
|
#[test]
|
|
fn session_before_setup_is_refused() {
|
|
let mut s = server();
|
|
let mut sc = Script::new();
|
|
sc.session = Some(s.session_id().to_string());
|
|
let reply = sc.options(&mut s);
|
|
assert_refused(&reply, 454);
|
|
assert_eq!(s.state(), RtspServerState::Options, "no session was issued yet");
|
|
}
|
|
|
|
#[test]
|
|
fn session_header_can_be_required() {
|
|
let mut s = server_with(ServerConfig { require_session_header: true, ..server_config() });
|
|
let mut sc = Script::new();
|
|
sc.advance_to(&mut s, RtspServerState::Setup);
|
|
assert_eq!(sc.setup(&mut s, "audio").status, 200, "the first SETUP has no session yet");
|
|
sc.send_session = false;
|
|
assert_refused(&sc.setup(&mut s, "video"), 454);
|
|
assert_eq!(sc.options(&mut s).status, 200, "OPTIONS never needs a session");
|
|
sc.send_session = true;
|
|
assert_eq!(sc.setup(&mut s, "video").status, 200);
|
|
assert_eq!(sc.setup(&mut s, "control").status, 200);
|
|
assert_eq!(sc.announce(&mut s, &write_announce(&host_config())).status, 200);
|
|
sc.send_session = false;
|
|
assert_refused(&sc.play(&mut s), 454);
|
|
sc.send_session = true;
|
|
assert_eq!(sc.play(&mut s).status, 200);
|
|
assert_eq!(s.state(), RtspServerState::Playing);
|
|
}
|
|
|
|
/// The CSeq header of an answer.
|
|
fn answer_cseq(reply: &ServerReply) -> Option<String> {
|
|
parse_response(&reply.bytes).unwrap().header("CSeq").map(str::to_string)
|
|
}
|
|
|
|
#[test]
|
|
fn cseq_is_echoed_and_required() {
|
|
let mut s = server();
|
|
for (cseq, status) in [("1", 200), ("4294967295", 200), ("0", 200), ("007", 200)] {
|
|
let req = format!("OPTIONS {URL} RTSP/1.0\r\nCSeq: {cseq}\r\n\r\n");
|
|
let reply = s.handle_request(req.as_bytes());
|
|
assert_eq!(reply.status, status);
|
|
assert_eq!(answer_cseq(&reply).unwrap().parse::<u32>().unwrap(), cseq.parse::<u32>().unwrap());
|
|
}
|
|
for bad in ["", "CSeq: abc\r\n", "CSeq: -1\r\n", "CSeq: 4294967296\r\n", "CSeq: 1\r\nCSeq: 2\r\n"] {
|
|
let req = format!("OPTIONS {URL} RTSP/1.0\r\n{bad}\r\n");
|
|
let reply = s.handle_request(req.as_bytes());
|
|
assert_refused(&reply, 400);
|
|
assert!(matches!(reply.error, Some(Error::Malformed { .. })), "{bad:?}: {reply:?}");
|
|
}
|
|
assert_eq!(s.state(), RtspServerState::Options);
|
|
}
|
|
|
|
#[test]
|
|
fn malformed_and_unknown_requests() {
|
|
let mut s = server();
|
|
// Unknown methods: 501, CSeq still echoed.
|
|
for m in ["TEARDOWN", "GET_PARAMETER", "PAUSE", "options"] {
|
|
let reply = s.handle_request(format!("{m} {URL} RTSP/1.0\r\nCSeq: 5\r\n\r\n").as_bytes());
|
|
assert_refused(&reply, 501);
|
|
assert_eq!(answer_cseq(&reply).as_deref(), Some("5"), "{m}");
|
|
}
|
|
// Broken request lines with a readable CSeq: 400, CSeq echoed.
|
|
for start in ["GARBAGE", "OPTIONS", "OPTIONS x RTSP/2.0", "OPTIONS x RTSP/1.0 extra"] {
|
|
let reply = s.handle_request(format!("{start}\r\nCSeq: 9\r\n\r\n").as_bytes());
|
|
assert_refused(&reply, 400);
|
|
assert_eq!(answer_cseq(&reply).as_deref(), Some("9"), "{start}");
|
|
}
|
|
// Nothing readable: 400 without CSeq.
|
|
for bad in [&b""[..], b"\0\0\0", b"\xff\xfe\r\n\r\n", b"RTSP/1.0 200 OK\r\nCSeq: 1\r\n\r\n"] {
|
|
let reply = s.handle_request(bad);
|
|
assert_refused(&reply, 400);
|
|
}
|
|
let huge = vec![b'O'; MAX_RTSP_MESSAGE_BYTES + 1];
|
|
let reply = s.handle_request(&huge);
|
|
assert_refused(&reply, 400);
|
|
assert!(matches!(reply.error, Some(Error::TooLarge { .. })), "{reply:?}");
|
|
assert_eq!(s.state(), RtspServerState::Options);
|
|
assert_eq!(s.poll_event(), None);
|
|
}
|
|
|
|
#[test]
|
|
fn announce_refusals() {
|
|
let base = host_config();
|
|
let cases: Vec<(ServerConfig, Vec<u8>, u16, &str)> = vec![
|
|
(server_config(), b"v=0\r\nbroken line\r\n".to_vec(), 400, "bad SDP"),
|
|
(server_config(), b"v=0\r\n".to_vec(), 400, "required attributes missing"),
|
|
(server_config(), Vec::new(), 400, "no payload"),
|
|
(
|
|
ServerConfig { offer: HostOffer { av1: false, ..offer() }, ..server_config() },
|
|
write_announce(&HostStreamConfig { codec: VideoCodec::Av1, ..base.clone() }),
|
|
451,
|
|
"AV1 not offered",
|
|
),
|
|
(
|
|
ServerConfig { offer: HostOffer { h264: false, ..offer() }, ..server_config() },
|
|
write_announce(&HostStreamConfig { codec: VideoCodec::H264, ..base.clone() }),
|
|
451,
|
|
"H.264 not offered",
|
|
),
|
|
(
|
|
ServerConfig { offer: HostOffer { hevc: false, ..offer() }, ..server_config() },
|
|
write_announce(&base),
|
|
451,
|
|
"HEVC not offered",
|
|
),
|
|
(
|
|
server_config(),
|
|
write_announce(&HostStreamConfig { encryption: EncryptionFlags(6), ..base.clone() }),
|
|
451,
|
|
"control V2 required but not turned on",
|
|
),
|
|
(
|
|
server_config(),
|
|
write_announce(&HostStreamConfig { encryption: EncryptionFlags(0x0F), ..base.clone() }),
|
|
451,
|
|
"a bit the host did not offer",
|
|
),
|
|
(
|
|
ServerConfig {
|
|
offer: HostOffer { encryption_supported: EncryptionFlags(5), ..offer() },
|
|
..server_config()
|
|
},
|
|
write_announce(&HostStreamConfig { encryption: EncryptionFlags(7), ..base.clone() }),
|
|
451,
|
|
"video encryption not offered",
|
|
),
|
|
(
|
|
ServerConfig { offer: HostOffer { hdr: false, ..offer() }, ..server_config() },
|
|
write_announce(&HostStreamConfig { dynamic_range_mode: 1, ..base.clone() }),
|
|
451,
|
|
"HDR not offered",
|
|
),
|
|
(
|
|
server_config(),
|
|
write_announce(&HostStreamConfig { chroma: ChromaSampling::Yuv444, ..base.clone() }),
|
|
451,
|
|
"4:4:4 not offered",
|
|
),
|
|
];
|
|
for (config, body, status, why) in cases {
|
|
let mut s = server_with(config);
|
|
let mut sc = Script::new();
|
|
sc.advance_to(&mut s, RtspServerState::Announce);
|
|
while s.poll_event().is_some() {}
|
|
let reply = sc.announce(&mut s, &body);
|
|
assert_refused(&reply, status);
|
|
if status == 451 {
|
|
assert!(matches!(reply.error, Some(Error::Unsupported { .. })), "{why}: {reply:?}");
|
|
}
|
|
assert_eq!(s.state(), RtspServerState::Announce, "{why}");
|
|
assert_eq!(s.poll_event(), None, "{why}");
|
|
assert_eq!(s.announced(), None, "{why}");
|
|
}
|
|
// What the offer has is accepted, HDR and 4:4:4 included.
|
|
let mut s = server_with(ServerConfig { offer: HostOffer { yuv444: true, ..offer() }, ..server_config() });
|
|
let mut sc = Script::new();
|
|
sc.advance_to(&mut s, RtspServerState::Announce);
|
|
let wanted = HostStreamConfig { chroma: ChromaSampling::Yuv444, dynamic_range_mode: 1, ..base };
|
|
assert_eq!(sc.announce(&mut s, &write_announce(&wanted)).status, 200);
|
|
assert_eq!(s.poll_event(), Some(ServerEvent::Announced(wanted.clone())));
|
|
assert_eq!(s.announced(), Some(&wanted));
|
|
assert_eq!(sc.play(&mut s).status, 200);
|
|
assert_eq!(s.poll_event(), Some(ServerEvent::PlayRequested));
|
|
assert_eq!(s.poll_event(), None);
|
|
}
|
|
|
|
#[test]
|
|
fn server_refuses_bad_config() {
|
|
let bad = [
|
|
ServerConfig { ports: StreamPorts { audio: 0, ..PORTS }, ..server_config() },
|
|
ServerConfig { ports: StreamPorts { video: 0, ..PORTS }, ..server_config() },
|
|
ServerConfig { ports: StreamPorts { control: 0, ..PORTS }, ..server_config() },
|
|
ServerConfig { session_timeout_secs: 0, ..server_config() },
|
|
ServerConfig { offer: HostOffer { encryption_supported: EncryptionFlags(6), ..offer() }, ..server_config() },
|
|
];
|
|
for config in bad {
|
|
assert_err!(
|
|
RtspServer::new(config.clone(), &mut common::SeqRng::new(1)),
|
|
Error::Malformed { .. },
|
|
"{config:?}"
|
|
);
|
|
}
|
|
let no_codec = HostOffer { h264: false, hevc: false, av1: false, ..offer() };
|
|
assert_err!(
|
|
RtspServer::new(ServerConfig { offer: no_codec, ..server_config() }, &mut common::SeqRng::new(1)),
|
|
Error::Unsupported { .. }
|
|
);
|
|
let nine = OpusConfig { channels: 9, streams: 9, coupled_streams: 0, mapping: (0..9).collect() };
|
|
assert_err!(
|
|
RtspServer::new(
|
|
ServerConfig { offer: HostOffer { opus_configs: vec![nine], ..offer() }, ..server_config() },
|
|
&mut common::SeqRng::new(1)
|
|
),
|
|
Error::Malformed { .. }
|
|
);
|
|
}
|
|
|
|
// ================================================================================================ DESCRIBE writer
|
|
|
|
#[test]
|
|
fn describe_lines_and_order() {
|
|
let text = String::from_utf8(build_describe(&offer()).unwrap()).unwrap();
|
|
assert_eq!(
|
|
text,
|
|
"a=x-ss-general.featureFlags:3\r\n\
|
|
a=x-ss-general.encryptionSupported:7\r\n\
|
|
sprop-parameter-sets=AAAAAU\r\n\
|
|
a=x-nv-video[0].refPicInvalidation:1\r\n\
|
|
a=rtpmap:98 AV1/90000\r\n\
|
|
a=fmtp:96 packetization-mode=1\r\n\
|
|
a=fmtp:97 surround-params=21101\r\n\
|
|
a=fmtp:97 surround-params=642012345\r\n\
|
|
a=fmtp:97 surround-params=85301234567\r\n"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn describe_follows_the_offer() {
|
|
let lean = HostOffer {
|
|
feature_flags: FeatureFlags(0),
|
|
encryption_supported: EncryptionFlags(1),
|
|
reference_frame_invalidation: false,
|
|
h264: false,
|
|
hevc: true,
|
|
av1: false,
|
|
hdr: false,
|
|
yuv444: false,
|
|
opus_configs: vec![],
|
|
};
|
|
let bytes = build_describe(&lean).unwrap();
|
|
let text = String::from_utf8(bytes.clone()).unwrap();
|
|
for absent in ["rtpmap", "fmtp", "refPicInvalidation"] {
|
|
assert!(!text.contains(absent), "{absent} in {text:?}");
|
|
}
|
|
let caps = HostCapabilities::from_sdp(&sdp::parse_sdp(&bytes).unwrap()).unwrap();
|
|
assert_eq!(caps, HostCapabilities { encryption_supported: EncryptionFlags(1), ..HostCapabilities::default() });
|
|
assert_eq!(caps.opus_for(2), OpusConfig::stereo(), "no Opus lines: the client falls back to stereo");
|
|
|
|
let h264 = HostOffer { h264: true, ..lean.clone() };
|
|
assert!(String::from_utf8(build_describe(&h264).unwrap()).unwrap().contains("a=fmtp:96 packetization-mode=1"));
|
|
}
|
|
|
|
#[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] });
|
|
for c in bad {
|
|
let o = HostOffer { opus_configs: vec![c.clone()], ..offer() };
|
|
assert_err!(build_describe(&o), Error::Malformed { .. }, "{c:?}");
|
|
}
|
|
let many = HostOffer { opus_configs: vec![OpusConfig::stereo(); MAX_OPUS_CONFIGS + 1], ..offer() };
|
|
assert_err!(build_describe(&many), Error::TooLarge { .. });
|
|
let max = HostOffer { opus_configs: vec![OpusConfig::stereo(); MAX_OPUS_CONFIGS], ..offer() };
|
|
let caps = HostCapabilities::from_sdp(&sdp::parse_sdp(&build_describe(&max).unwrap()).unwrap()).unwrap();
|
|
assert_eq!(caps.opus_configs.len(), MAX_OPUS_CONFIGS);
|
|
let none = HostOffer { h264: false, hevc: false, av1: false, ..offer() };
|
|
assert_err!(build_describe(&none), Error::Unsupported { .. });
|
|
}
|
|
|
|
// ================================================================================================ ANNOUNCE parser
|
|
|
|
const REQUIRED: [(&str, &str); 10] = [
|
|
("x-nv-video[0].clientViewportWd", "1920"),
|
|
("x-nv-video[0].clientViewportHt", "1080"),
|
|
("x-nv-video[0].maxFPS", "60"),
|
|
("x-nv-video[0].packetSize", "1024"),
|
|
("x-ml-video.configuredBitrateKbps", "20000"),
|
|
("x-nv-vqos[0].bitStreamFormat", "1"),
|
|
("x-nv-vqos[0].fec.minRequiredFecPackets", "2"),
|
|
("x-nv-vqos[0].qosTrafficType", "5"),
|
|
("x-nv-aqos.packetDuration", "5"),
|
|
("x-nv-aqos.qosTrafficType", "4"),
|
|
];
|
|
|
|
const OPTIONAL: [(&str, &str); 10] = [
|
|
("x-nv-video[0].maxNumReferenceFrames", "0"),
|
|
("x-nv-video[0].refPicInvalidation", "1"),
|
|
("x-nv-video[0].dynamicRangeMode", "0"),
|
|
("x-nv-video[0].encoderCscMode", "0"),
|
|
("x-ss-video[0].chromaSamplingType", "0"),
|
|
("x-ss-general.encryptionEnabled", "7"),
|
|
("x-nv-audio.surround.enable", "0"),
|
|
("x-nv-audio.surround.numChannels", "2"),
|
|
("x-nv-audio.surround.channelMask", "3"),
|
|
("x-nv-audio.surround.AudioQuality", "1"),
|
|
];
|
|
|
|
fn sdp_of(attrs: &[(&str, &str)]) -> String {
|
|
let mut s = String::from("v=0\r\n");
|
|
for (k, v) in attrs {
|
|
s.push_str(&format!("a={k}:{v}\r\n"));
|
|
}
|
|
s
|
|
}
|
|
|
|
fn full_attrs() -> Vec<(&'static str, &'static str)> {
|
|
REQUIRED.iter().chain(OPTIONAL.iter()).copied().collect()
|
|
}
|
|
|
|
fn with(name: &str, value: &str) -> String {
|
|
sdp_of(&full_attrs().into_iter().map(|(k, v)| (k, if k == name { value } else { v })).collect::<Vec<_>>())
|
|
}
|
|
|
|
#[test]
|
|
fn announce_sample() {
|
|
let c = parse_announce(sdp_of(&full_attrs()).as_bytes()).unwrap();
|
|
assert_eq!(c, host_config());
|
|
// LF line ends, blanks around values, other SDP lines and empty lines change nothing.
|
|
let mut loose = String::from("v=0\no=- 0 0 IN IP4 0.0.0.0\ns=x\nt=0 0\nm=video 0 RTP/AVP 96\n\n");
|
|
for (k, v) in full_attrs() {
|
|
loose.push_str(&format!("a={k}: {v}\t\n\n"));
|
|
}
|
|
loose.push_str("sprop-parameter-sets=AAAAAU\n");
|
|
assert_eq!(parse_announce(loose.as_bytes()).unwrap(), host_config());
|
|
}
|
|
|
|
#[test]
|
|
fn announce_from_our_client() {
|
|
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(&build_describe(&offer()).unwrap()).unwrap()).unwrap();
|
|
let body = sdp::build_announce(&client_config(), &host).unwrap();
|
|
assert_eq!(parse_announce(&body).unwrap(), host_config());
|
|
}
|
|
|
|
#[test]
|
|
fn announce_defaults() {
|
|
let c = parse_announce(sdp_of(&REQUIRED).as_bytes()).unwrap();
|
|
assert_eq!(c.max_reference_frames, 1);
|
|
assert!(!c.reference_frame_invalidation);
|
|
assert_eq!((c.dynamic_range_mode, c.encoder_csc_mode), (0, 0));
|
|
assert_eq!(c.chroma, ChromaSampling::Yuv420);
|
|
assert_eq!(c.encryption, EncryptionFlags(0));
|
|
assert_eq!(c.surround, SurroundSettings { enabled: false, channels: 2, channel_mask: 3, high_quality: true });
|
|
assert_eq!(c.surround, SurroundSettings::default());
|
|
assert_eq!(c.unknown_attributes, 0);
|
|
}
|
|
|
|
#[test]
|
|
fn announce_required_attributes() {
|
|
for (name, _) in REQUIRED {
|
|
let rest: Vec<_> = full_attrs().into_iter().filter(|(k, _)| *k != name).collect();
|
|
assert_err!(parse_announce(sdp_of(&rest).as_bytes()), Error::Malformed { .. }, "without {name}");
|
|
}
|
|
for (name, _) in OPTIONAL {
|
|
let rest: Vec<_> = full_attrs().into_iter().filter(|(k, _)| *k != name).collect();
|
|
assert!(parse_announce(sdp_of(&rest).as_bytes()).is_ok(), "without {name}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn announce_duplicates_and_unknowns() {
|
|
for (name, value) in full_attrs() {
|
|
let mut attrs = full_attrs();
|
|
attrs.push((name, value));
|
|
assert_err!(parse_announce(sdp_of(&attrs).as_bytes()), Error::Malformed { .. }, "{name} twice");
|
|
}
|
|
let mut attrs = full_attrs();
|
|
attrs.extend([
|
|
("x-nv-general.unknown", "1"),
|
|
("x-nv-general.unknown", "2"),
|
|
("x-nv-video[1].clientViewportWd", "5"),
|
|
]);
|
|
let mut text = sdp_of(&attrs);
|
|
text.push_str("a=recvonly\r\n");
|
|
let c = parse_announce(text.as_bytes()).unwrap();
|
|
assert_eq!(c.unknown_attributes, 4, "unknown attributes are counted, duplicates of them included");
|
|
assert_eq!(HostStreamConfig { unknown_attributes: 0, ..c }, host_config());
|
|
}
|
|
|
|
#[test]
|
|
fn announce_ranges() {
|
|
let refused = [
|
|
("x-nv-video[0].clientViewportWd", "0"),
|
|
("x-nv-video[0].clientViewportWd", "16385"),
|
|
("x-nv-video[0].clientViewportHt", "0"),
|
|
("x-nv-video[0].clientViewportHt", "16385"),
|
|
("x-nv-video[0].maxFPS", "0"),
|
|
("x-nv-video[0].maxFPS", "1001"),
|
|
("x-nv-video[0].packetSize", "199"),
|
|
("x-nv-video[0].packetSize", "65472"),
|
|
("x-ml-video.configuredBitrateKbps", "0"),
|
|
("x-ml-video.configuredBitrateKbps", "4294968"),
|
|
("x-nv-vqos[0].bitStreamFormat", "3"),
|
|
("x-nv-vqos[0].fec.minRequiredFecPackets", "256"),
|
|
("x-nv-vqos[0].qosTrafficType", "4294967296"),
|
|
("x-nv-aqos.packetDuration", "0"),
|
|
("x-nv-aqos.packetDuration", "121"),
|
|
("x-nv-aqos.qosTrafficType", "4294967296"),
|
|
("x-nv-video[0].maxNumReferenceFrames", "4294967296"),
|
|
("x-nv-video[0].refPicInvalidation", "2"),
|
|
("x-nv-video[0].dynamicRangeMode", "4294967296"),
|
|
("x-nv-video[0].encoderCscMode", "4294967296"),
|
|
("x-ss-video[0].chromaSamplingType", "2"),
|
|
("x-ss-general.encryptionEnabled", "256"),
|
|
("x-nv-audio.surround.enable", "2"),
|
|
("x-nv-audio.surround.numChannels", "0"),
|
|
("x-nv-audio.surround.numChannels", "9"),
|
|
("x-nv-audio.surround.channelMask", "4294967296"),
|
|
("x-nv-audio.surround.AudioQuality", "2"),
|
|
];
|
|
for (name, value) in refused {
|
|
assert_err!(parse_announce(with(name, value).as_bytes()), Error::UnexpectedValue { .. }, "{name}={value}");
|
|
}
|
|
let accepted = [
|
|
("x-nv-video[0].clientViewportWd", "16384", "1"),
|
|
("x-nv-video[0].clientViewportHt", "16384", "1"),
|
|
("x-nv-video[0].maxFPS", "1000", "1"),
|
|
("x-nv-video[0].packetSize", "65471", "200"),
|
|
("x-ml-video.configuredBitrateKbps", "4294967", "1"),
|
|
("x-nv-vqos[0].bitStreamFormat", "2", "0"),
|
|
("x-nv-vqos[0].fec.minRequiredFecPackets", "255", "0"),
|
|
("x-nv-aqos.packetDuration", "120", "1"),
|
|
("x-nv-audio.surround.numChannels", "8", "1"),
|
|
("x-ss-general.encryptionEnabled", "255", "0"),
|
|
];
|
|
for (name, high, low) in accepted {
|
|
for v in [high, low] {
|
|
assert!(parse_announce(with(name, v).as_bytes()).is_ok(), "{name}={v}");
|
|
}
|
|
}
|
|
let raw = parse_announce(
|
|
sdp_of(
|
|
&full_attrs()
|
|
.into_iter()
|
|
.map(|(k, v)| match k {
|
|
"x-nv-video[0].dynamicRangeMode" => (k, "4294967295"),
|
|
"x-nv-video[0].encoderCscMode" => (k, "12345"),
|
|
"x-nv-video[0].maxNumReferenceFrames" => (k, "77"),
|
|
"x-nv-vqos[0].qosTrafficType" => (k, "0"),
|
|
"x-nv-audio.surround.channelMask" => (k, "4294967295"),
|
|
_ => (k, v),
|
|
})
|
|
.collect::<Vec<_>>(),
|
|
)
|
|
.as_bytes(),
|
|
)
|
|
.unwrap();
|
|
assert_eq!(raw.dynamic_range_mode, u32::MAX, "kept raw (U6)");
|
|
assert_eq!(raw.encoder_csc_mode, 12345, "kept raw (U6)");
|
|
assert_eq!(raw.max_reference_frames, 77);
|
|
assert_eq!(raw.video_qos_traffic_type, 0);
|
|
assert_eq!(raw.surround.channel_mask, u32::MAX);
|
|
assert_eq!(parse_announce(with("x-nv-vqos[0].bitStreamFormat", "0").as_bytes()).unwrap().codec, VideoCodec::H264);
|
|
assert_eq!(parse_announce(with("x-nv-vqos[0].bitStreamFormat", "2").as_bytes()).unwrap().codec, VideoCodec::Av1);
|
|
}
|
|
|
|
#[test]
|
|
fn announce_number_syntax() {
|
|
for bad in ["", "+5", "-1", "0x10", "1 2", "1.5", "1e3", "٣", "99999999999999999999999", "5;", "5,6"] {
|
|
let r = parse_announce(with("x-nv-video[0].maxFPS", bad).as_bytes());
|
|
assert!(matches!(r, Err(Error::Malformed { .. } | Error::UnexpectedValue { .. })), "{bad:?}: {r:?}");
|
|
}
|
|
assert_eq!(parse_announce(with("x-nv-video[0].maxFPS", "0060").as_bytes()).unwrap().max_fps, 60);
|
|
}
|
|
|
|
#[test]
|
|
fn announce_hostile_lines() {
|
|
let base = sdp_of(&full_attrs());
|
|
for (extra, why) in [
|
|
("no equals sign\r\n", "line without ="),
|
|
("=x\r\n", "empty type"),
|
|
("a=x-nv-video[0].maxFPS\r\n", "known attribute without a value"),
|
|
("a=u:\0\r\n", "NUL"),
|
|
("a=u:\x1b[31m\r\n", "escape"),
|
|
("a=u:1\rb\r\n", "CR inside a line"),
|
|
] {
|
|
let text = format!("{base}{extra}");
|
|
let r = parse_announce(text.as_bytes());
|
|
// The known attribute without a value is also a duplicate; either way it is refused.
|
|
assert_err!(r, Error::Malformed { .. }, "{why}");
|
|
}
|
|
let mut not_utf8 = base.clone().into_bytes();
|
|
not_utf8.extend_from_slice(b"a=u:\xff\xfe\r\n");
|
|
assert_err!(parse_announce(¬_utf8), Error::Malformed { .. });
|
|
}
|
|
|
|
macro_rules! assert_cap {
|
|
($e:expr, $max:expr) => {
|
|
match $e {
|
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"),
|
|
other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other),
|
|
}
|
|
};
|
|
}
|
|
|
|
#[test]
|
|
fn announce_caps() {
|
|
let base = sdp_of(&REQUIRED);
|
|
let base_lines = REQUIRED.len() + 1;
|
|
// Lines.
|
|
let lines = |n: usize| format!("{base}{}", "t=0 0\n".repeat(n - base_lines));
|
|
assert!(parse_announce(lines(MAX_ANNOUNCE_LINES).as_bytes()).is_ok());
|
|
assert_cap!(parse_announce(lines(MAX_ANNOUNCE_LINES + 1).as_bytes()), MAX_ANNOUNCE_LINES);
|
|
// Empty lines are not lines.
|
|
assert!(parse_announce(format!("{}{}", lines(MAX_ANNOUNCE_LINES), "\r\n".repeat(100)).as_bytes()).is_ok());
|
|
// Attributes.
|
|
let attrs = |n: usize| format!("{base}{}", "a=u:1\n".repeat(n - REQUIRED.len()));
|
|
assert_eq!(
|
|
parse_announce(attrs(MAX_ANNOUNCE_ATTRIBUTES).as_bytes()).unwrap().unknown_attributes as usize,
|
|
MAX_ANNOUNCE_ATTRIBUTES - REQUIRED.len()
|
|
);
|
|
assert_cap!(parse_announce(attrs(MAX_ANNOUNCE_ATTRIBUTES + 1).as_bytes()), MAX_ANNOUNCE_ATTRIBUTES);
|
|
// Line length (without the line end).
|
|
let long = |n: usize| format!("{base}a=pad:{}\r\n", "p".repeat(n - 6));
|
|
assert!(parse_announce(long(MAX_ANNOUNCE_LINE_BYTES).as_bytes()).is_ok());
|
|
assert_cap!(parse_announce(long(MAX_ANNOUNCE_LINE_BYTES + 1).as_bytes()), MAX_ANNOUNCE_LINE_BYTES);
|
|
// A last line without a line end counts too.
|
|
assert_cap!(
|
|
parse_announce(format!("{base}a=pad:{}", "p".repeat(MAX_ANNOUNCE_LINE_BYTES)).as_bytes()),
|
|
MAX_ANNOUNCE_LINE_BYTES
|
|
);
|
|
// Bytes: padded with empty lines.
|
|
let sized = |n: usize| format!("{base}{}", "\n".repeat(n - base.len()));
|
|
assert!(parse_announce(sized(MAX_ANNOUNCE_BYTES).as_bytes()).is_ok());
|
|
assert_too_large!(
|
|
parse_announce(sized(MAX_ANNOUNCE_BYTES + 1).as_bytes()),
|
|
MAX_ANNOUNCE_BYTES,
|
|
MAX_ANNOUNCE_BYTES + 1
|
|
);
|
|
assert_too_large!(parse_announce(&vec![b'a'; 1 << 20]), MAX_ANNOUNCE_BYTES, 1 << 20);
|
|
}
|
|
|
|
// ================================================================================================ response codec
|
|
|
|
#[test]
|
|
fn response_encode_round_trip_and_injection() {
|
|
let r = RtspResponse {
|
|
status: 200,
|
|
reason: "OK".into(),
|
|
headers: vec![("CSeq".into(), "3".into()), ("Content-Length".into(), "5".into())],
|
|
body: b"hello".to_vec(),
|
|
};
|
|
let bytes = r.encode().unwrap();
|
|
assert_eq!(bytes, b"RTSP/1.0 200 OK\r\nCSeq: 3\r\nContent-Length: 5\r\n\r\nhello".to_vec());
|
|
assert_eq!(parse_response(&bytes).unwrap(), r);
|
|
let base = || RtspResponse { status: 200, reason: "OK".into(), headers: vec![], body: vec![] };
|
|
let bad = [
|
|
RtspResponse { status: 99, ..base() },
|
|
RtspResponse { status: 1000, ..base() },
|
|
RtspResponse { reason: "OK\r\nX: y".into(), ..base() },
|
|
RtspResponse { headers: vec![("Bad:Name".into(), "v".into())], ..base() },
|
|
RtspResponse { headers: vec![(String::new(), "v".into())], ..base() },
|
|
RtspResponse { headers: vec![("X".into(), "a\r\nY: b".into())], ..base() },
|
|
];
|
|
for r in bad {
|
|
assert_err!(r.encode(), Error::Malformed { .. }, "{r:?}");
|
|
}
|
|
assert_cap!(RtspResponse { body: vec![0; MAX_RTSP_MESSAGE_BYTES], ..base() }.encode(), MAX_RTSP_MESSAGE_BYTES);
|
|
}
|
|
|
|
#[test]
|
|
fn request_framer_ends_at_the_empty_line() {
|
|
let a = b"OPTIONS rtsp://h:1 RTSP/1.0\r\nCSeq: 1\r\n\r\n".to_vec();
|
|
let b = b"ANNOUNCE x RTSP/1.0\r\nCSeq: 2\r\nContent-Length: 3\r\n\r\nabc".to_vec();
|
|
let c = b"PLAY rtsp://h:1 RTSP/1.0\r\nCSeq: 3\r\n\r\n".to_vec();
|
|
let mut f = RtspFramer::for_requests();
|
|
f.push(&[a.clone(), b.clone(), c.clone()].concat()).unwrap();
|
|
assert_eq!(f.next_message().unwrap(), Some(a.clone()), "no Content-Length: no payload (RFC 2326 4.4)");
|
|
assert_eq!(f.next_message().unwrap(), Some(b));
|
|
assert_eq!(f.next_message().unwrap(), Some(c));
|
|
assert_eq!(f.next_message().unwrap(), None);
|
|
assert_eq!(f.finish(), Ok(None));
|
|
// Half a request at close.
|
|
let mut f = RtspFramer::for_requests();
|
|
f.push(&a[..a.len() - 2]).unwrap();
|
|
assert_eq!(f.next_message().unwrap(), None);
|
|
assert_err!(f.finish(), Error::Truncated { .. });
|
|
// The client-side framer still waits for close without Content-Length.
|
|
let mut f = RtspFramer::new();
|
|
f.push(&a).unwrap();
|
|
assert_eq!(f.next_message().unwrap(), None);
|
|
}
|
|
|
|
// ================================================================================================ properties
|
|
|
|
fn codec() -> impl Strategy<Value = VideoCodec> {
|
|
prop_oneof![Just(VideoCodec::H264), Just(VideoCodec::Hevc), Just(VideoCodec::Av1)]
|
|
}
|
|
|
|
fn valid_host_config() -> impl Strategy<Value = HostStreamConfig> {
|
|
(
|
|
(
|
|
1..=MAX_DIMENSION,
|
|
1..=MAX_DIMENSION,
|
|
1..=MAX_FPS,
|
|
MIN_PACKET_SIZE..=MAX_PACKET_SIZE,
|
|
1..=MAX_BITRATE_KBPS,
|
|
codec(),
|
|
any::<u8>(),
|
|
any::<u32>(),
|
|
),
|
|
(
|
|
1..=MAX_AUDIO_PACKET_DURATION_MS,
|
|
any::<u32>(),
|
|
any::<u32>(),
|
|
any::<bool>(),
|
|
any::<u32>(),
|
|
any::<u32>(),
|
|
prop_oneof![Just(ChromaSampling::Yuv420), Just(ChromaSampling::Yuv444)],
|
|
any::<u8>(),
|
|
),
|
|
(any::<bool>(), 1u8..=8, any::<u32>(), any::<bool>()),
|
|
)
|
|
.prop_map(
|
|
|((w, h, fps, ps, br, codec, fec, vq), (dur, aq, refs, rfi, drm, csc, chroma, enc), (on, ch, mask, hq))| {
|
|
HostStreamConfig {
|
|
width: w,
|
|
height: h,
|
|
max_fps: fps,
|
|
packet_size: ps,
|
|
bitrate_kbps: br,
|
|
codec,
|
|
min_fec_packets: fec,
|
|
video_qos_traffic_type: vq,
|
|
audio_packet_duration_ms: dur,
|
|
audio_qos_traffic_type: aq,
|
|
max_reference_frames: refs,
|
|
reference_frame_invalidation: rfi,
|
|
dynamic_range_mode: drm,
|
|
encoder_csc_mode: csc,
|
|
chroma,
|
|
encryption: EncryptionFlags(enc),
|
|
surround: SurroundSettings { enabled: on, channels: ch, channel_mask: mask, high_quality: hq },
|
|
unknown_attributes: 0,
|
|
}
|
|
},
|
|
)
|
|
}
|
|
|
|
fn valid_client_config() -> impl Strategy<Value = ClientConfig> {
|
|
(
|
|
1..=MAX_DIMENSION,
|
|
1..=MAX_DIMENSION,
|
|
1..=MAX_FPS,
|
|
1..=MAX_BITRATE_KBPS,
|
|
MIN_PACKET_SIZE..=MAX_PACKET_SIZE,
|
|
codec(),
|
|
any::<bool>(),
|
|
prop_oneof![Just(AudioLayout::Stereo), Just(AudioLayout::Surround51), Just(AudioLayout::Surround71)],
|
|
1..=MAX_AUDIO_PACKET_DURATION_MS,
|
|
any::<u8>(),
|
|
any::<bool>(),
|
|
(1u8..8).prop_map(|e| EncryptionFlags(e | EncryptionFlags::CONTROL_V2)),
|
|
)
|
|
.prop_map(
|
|
|(width, height, fps, bitrate_kbps, packet_size, codec, hdr, audio, dur, fec, rfi, encryption)| {
|
|
ClientConfig {
|
|
width,
|
|
height,
|
|
fps,
|
|
bitrate_kbps,
|
|
packet_size,
|
|
codec,
|
|
hdr,
|
|
audio,
|
|
audio_packet_duration_ms: dur,
|
|
min_fec_packets: fec,
|
|
reference_frame_invalidation: rfi,
|
|
encryption,
|
|
}
|
|
},
|
|
)
|
|
}
|
|
|
|
proptest! {
|
|
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
|
|
|
/// write_announce then parse_announce gives the config back.
|
|
#[test]
|
|
fn announce_round_trip(c in valid_host_config()) {
|
|
prop_assert_eq!(parse_announce(&write_announce(&c)), Ok(c));
|
|
}
|
|
|
|
/// What our client announces is what the host reads, for any valid client config.
|
|
#[test]
|
|
fn client_announce_is_read_back(c in valid_client_config()) {
|
|
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(&build_describe(&offer()).unwrap()).unwrap()).unwrap();
|
|
let enabled = sdp::negotiated_encryption(&c, &host).unwrap();
|
|
let body = sdp::build_announce(&c, &host).unwrap();
|
|
prop_assert_eq!(parse_announce(&body), Ok(expected_from_client(&c, enabled)));
|
|
}
|
|
|
|
/// Any valid client config negotiates end to end against the server.
|
|
#[test]
|
|
fn any_client_config_negotiates(c in valid_client_config(), seed in any::<u64>()) {
|
|
let mut s = RtspServer::new(server_config(), &mut common::SeqRng::new(seed)).unwrap();
|
|
let (n, events) = run_session(c.clone(), &mut s, usize::MAX);
|
|
let n = n.map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
|
prop_assert_eq!(n.session_id.as_deref(), Some(s.session_id()));
|
|
prop_assert_eq!(&events[0], &ServerEvent::Announced(expected_from_client(&c, n.encryption)));
|
|
}
|
|
|
|
/// Arbitrary bytes never panic the parser, and what it accepts is in range.
|
|
#[test]
|
|
fn announce_never_panics(data in proptest::collection::vec(any::<u8>(), 0..2048)) {
|
|
let r = parse_announce(&data);
|
|
prop_assert!(common::implemented(&r));
|
|
if let Ok(c) = r {
|
|
prop_assert!((1..=MAX_DIMENSION).contains(&c.width) && (1..=MAX_DIMENSION).contains(&c.height));
|
|
prop_assert!(c.packet_size >= MIN_PACKET_SIZE && c.packet_size <= MAX_PACKET_SIZE);
|
|
}
|
|
}
|
|
|
|
/// Attribute-shaped noise: known names with arbitrary values, in any order, never panic.
|
|
#[test]
|
|
fn announce_attribute_noise_never_panics(
|
|
lines in proptest::collection::vec((0usize..21, "[ -~]{0,12}"), 0..40),
|
|
) {
|
|
let names: Vec<&str> = full_attrs().into_iter().map(|(k, _)| k).chain(["x-unknown"]).collect();
|
|
let text: String = lines.iter().map(|(i, v)| format!("a={}:{v}\n", names[*i])).collect();
|
|
let r = parse_announce(text.as_bytes());
|
|
prop_assert!(common::implemented(&r));
|
|
if let Ok(c) = r {
|
|
prop_assert_eq!(parse_announce(&write_announce(&c)), Ok(HostStreamConfig { unknown_attributes: 0, ..c }));
|
|
}
|
|
}
|
|
|
|
/// Arbitrary bytes as a request: always an answer that parses, never a panic, never a state change.
|
|
#[test]
|
|
fn server_never_panics_on_bytes(data in proptest::collection::vec(any::<u8>(), 0..1024)) {
|
|
let mut s = server();
|
|
let reply = s.handle_request(&data);
|
|
prop_assert!(reply.error != Some(Error::Unimplemented));
|
|
prop_assert_eq!(parse_response(&reply.bytes).map(|r| r.status), Ok(reply.status));
|
|
prop_assert!(reply.status == 200 || s.state() == RtspServerState::Options);
|
|
}
|
|
}
|
|
|
|
fn rank(s: RtspServerState) -> u8 {
|
|
match s {
|
|
RtspServerState::Options => 0,
|
|
RtspServerState::Describe => 1,
|
|
RtspServerState::Setup => 2,
|
|
RtspServerState::Announce => 3,
|
|
RtspServerState::Play => 4,
|
|
RtspServerState::Playing => 5,
|
|
}
|
|
}
|
|
|
|
proptest! {
|
|
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
|
|
|
|
/// 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)) {
|
|
let mut s = server();
|
|
let id = s.session_id().to_string();
|
|
let good_announce = write_announce(&host_config());
|
|
let mut announced = 0;
|
|
let mut played = 0;
|
|
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 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 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()));
|
|
}
|
|
req.push_str("\r\n");
|
|
let mut bytes = req.into_bytes();
|
|
bytes.extend_from_slice(body);
|
|
let before = s.state();
|
|
let reply = s.handle_request(&bytes);
|
|
prop_assert!(reply.error != Some(Error::Unimplemented));
|
|
let r = parse_response(&reply.bytes).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
|
prop_assert_eq!(r.status, reply.status);
|
|
prop_assert!([200, 400, 451, 454, 455, 501].contains(&reply.status), "{}", reply.status);
|
|
prop_assert_eq!(reply.status == 200, reply.error.is_none());
|
|
let echoed = cseq.to_string();
|
|
prop_assert_eq!(r.header("CSeq"), Some(echoed.as_str()));
|
|
prop_assert!(rank(s.state()) >= rank(before));
|
|
if reply.status != 200 {
|
|
prop_assert_eq!(s.state(), before);
|
|
}
|
|
while let Some(e) = s.poll_event() {
|
|
match e {
|
|
ServerEvent::Announced(c) => {
|
|
prop_assert_eq!(c, host_config());
|
|
announced += 1;
|
|
}
|
|
ServerEvent::PlayRequested => {
|
|
prop_assert_eq!(announced, 1);
|
|
played += 1;
|
|
}
|
|
}
|
|
}
|
|
prop_assert!(announced <= 1 && played <= 1);
|
|
}
|
|
prop_assert_eq!(played == 1, s.state() == RtspServerState::Playing);
|
|
prop_assert_eq!(announced == 1, rank(s.state()) >= rank(RtspServerState::Play));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn client_failed_state_is_reported() {
|
|
// The client reaches Failed when the server refuses; the server stays where it was.
|
|
let mut cfg = server_config();
|
|
cfg.offer.hevc = false;
|
|
let mut s = server_with(cfg);
|
|
let mut c = RtspClient::new(URL, client_config()).unwrap();
|
|
let mut framer = RtspFramer::for_requests();
|
|
while let Some(req) = c.poll_request() {
|
|
framer.push(&req).unwrap();
|
|
let m = framer.next_message().unwrap().unwrap();
|
|
let reply = s.handle_request(&m);
|
|
if c.handle_response(&reply.bytes).is_err() {
|
|
break;
|
|
}
|
|
}
|
|
assert_eq!(c.state(), RtspClientState::Failed);
|
|
assert_eq!(s.state(), RtspServerState::Announce);
|
|
}
|