use alloc::string::{String, ToString};
use core::net::{IpAddr, SocketAddr};
use core::time::Duration;
pub const DEFAULT_PORT: u16 = 9000;
pub const MAX_LATENCY_MS: u16 = 8000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum SrtMode {
#[default]
Caller,
Listener,
}
impl UrlRejection {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
UrlRejection::Authority => "authority",
UrlRejection::LatencyNotANumber => "latency-not-a-number",
UrlRejection::LatencyTooLarge => "latency-too-large",
UrlRejection::Mode => "mode",
UrlRejection::InvalidUtf8 => "invalid-utf8",
UrlRejection::DuplicateKey => "duplicate-key",
}
}
}
impl SrtMode {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
SrtMode::Caller => "caller",
SrtMode::Listener => "listener",
}
}
}
broadcast_common::impl_spec_display!(SrtMode);
broadcast_common::impl_spec_display!(UrlRejection);
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SrtUrl {
pub host: String,
pub port: u16,
pub stream_id: Option<String>,
pub latency: Option<Duration>,
pub mode: SrtMode,
pub passphrase: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum UrlRejection {
Authority,
LatencyNotANumber,
LatencyTooLarge,
Mode,
InvalidUtf8,
DuplicateKey,
}
impl core::fmt::Debug for SrtUrl {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("SrtUrl")
.field("host", &self.host)
.field("port", &self.port)
.field("stream_id", &self.stream_id)
.field("latency", &self.latency)
.field("mode", &self.mode)
.field(
"passphrase",
&self.passphrase.as_ref().map(|_| "<redacted>"),
)
.finish()
}
}
impl SrtUrl {
pub fn parse(url: &str) -> Result<Self, UrlRejection> {
let parsed_url = parse_url(url).ok_or(UrlRejection::Authority)?;
if !parsed_url.username().is_empty() || parsed_url.password().is_some() {
return Err(UrlRejection::Authority);
}
let host = bracketed_host(&parsed_url).ok_or(UrlRejection::Authority)?;
let port = parsed_url.port().unwrap_or(DEFAULT_PORT);
let mut parsed = Self {
host,
port,
stream_id: None,
latency: None,
mode: SrtMode::Caller,
passphrase: None,
};
if let Some(query) = parsed_url.query() {
let mut seen: alloc::vec::Vec<String> = alloc::vec::Vec::new();
for pair in query.split('&') {
if pair.is_empty() {
continue;
}
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
let Ok(key) = percent_decode(key) else {
continue;
};
let recognised =
matches!(key.as_str(), "streamid" | "latency" | "mode" | "passphrase");
if recognised {
if seen.contains(&key) {
return Err(UrlRejection::DuplicateKey);
}
seen.push(key.clone());
}
match key.as_str() {
"streamid" => parsed.stream_id = Some(percent_decode(value)?),
"latency" => {
parsed.latency = Some(parse_latency(value)?);
}
"mode" => parsed.mode = parse_mode(value).ok_or(UrlRejection::Mode)?,
"passphrase" => parsed.passphrase = Some(percent_decode(value)?),
_ => {}
}
}
}
Ok(parsed)
}
#[must_use]
pub fn dial_addr(&self) -> String {
match self.host.parse::<IpAddr>() {
Ok(ip) => SocketAddr::new(ip, self.port).to_string(),
Err(_) => format!("{}:{}", self.host, self.port),
}
}
}
fn parse_url(input: &str) -> Option<url::Url> {
let escaped = escape_query_fragments(input);
if has_srt_scheme(&escaped) {
url::Url::parse(&escaped).ok()
} else {
url::Url::parse(&alloc::format!("srt://{escaped}")).ok()
}
}
fn has_srt_scheme(input: &str) -> bool {
input
.get(.."srt://".len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("srt://"))
}
fn escape_query_fragments(input: &str) -> alloc::string::String {
match input.split_once('?') {
Some((head, query)) => {
let mut out = alloc::string::String::with_capacity(input.len() + 8);
out.push_str(head);
out.push('?');
for ch in query.chars() {
if ch == '#' {
out.push_str("%23");
} else {
out.push(ch);
}
}
out
}
None => input.into(),
}
}
fn bracketed_host(url: &url::Url) -> Option<String> {
url.host_str().map(alloc::string::ToString::to_string)
}
fn parse_latency(value: &str) -> Result<Duration, UrlRejection> {
let ms = value
.parse::<u16>()
.map_err(|_| UrlRejection::LatencyNotANumber)?;
if ms > MAX_LATENCY_MS {
return Err(UrlRejection::LatencyTooLarge);
}
Ok(Duration::from_millis(u64::from(ms)))
}
fn parse_mode(value: &str) -> Option<SrtMode> {
match value {
"caller" => Some(SrtMode::Caller),
"listener" => Some(SrtMode::Listener),
_ => None,
}
}
fn percent_decode(value: &str) -> Result<String, UrlRejection> {
let bytes: alloc::vec::Vec<u8> = percent_encoding::percent_decode_str(value).collect();
String::from_utf8(bytes).map_err(|_| UrlRejection::InvalidUtf8)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_redacts_the_passphrase() {
let url = SrtUrl::parse("srt://h?passphrase=SECRET").expect("passphrase");
let rendered = format!("{url:?}");
assert!(!rendered.contains("SECRET"), "{rendered}");
assert!(rendered.contains("<redacted>"), "{rendered}");
}
#[test]
fn host_only_takes_the_default_port() {
let url = SrtUrl::parse("srt://example.com").expect("host only");
assert_eq!(url.host, "example.com");
assert_eq!(url.port, DEFAULT_PORT);
assert_eq!(url.mode, SrtMode::Caller);
}
#[test]
fn bracketed_ipv6_keeps_its_brackets_off_the_host() {
let url = SrtUrl::parse("srt://[::1]:9001").expect("bracketed v6");
assert_eq!(url.host, "[::1]");
assert_eq!(url.dial_addr(), "[::1]:9001");
}
#[test]
fn a_bare_ipv6_literal_is_ambiguous_not_guessed() {
assert_eq!(SrtUrl::parse("::1:9000"), Err(UrlRejection::Authority));
}
#[test]
fn the_latency_cap_is_the_drafts() {
assert!(SrtUrl::parse("srt://h?latency=8000").is_ok());
assert_eq!(
SrtUrl::parse("srt://h?latency=8001"),
Err(UrlRejection::LatencyTooLarge)
);
assert_eq!(
SrtUrl::parse("srt://h?latency=late"),
Err(UrlRejection::LatencyNotANumber)
);
}
#[test]
fn invalid_utf8_percent_decode_is_rejected() {
assert_eq!(
SrtUrl::parse("srt://h:9000?streamid=%FF"),
Err(UrlRejection::InvalidUtf8)
);
assert_eq!(
SrtUrl::parse("srt://h:9000?passphrase=%C3%28extra"),
Err(UrlRejection::InvalidUtf8)
);
}
#[test]
fn duplicate_query_key_is_rejected() {
assert_eq!(
SrtUrl::parse("srt://h:9000?latency=10&latency=20"),
Err(UrlRejection::DuplicateKey)
);
}
#[test]
fn duplicate_query_key_decoded_is_rejected() {
assert_eq!(
SrtUrl::parse("srt://h:9000?%6Catency=10&latency=20"),
Err(UrlRejection::DuplicateKey)
);
}
#[test]
fn unknown_key_with_invalid_utf8_is_ignored() {
let url = SrtUrl::parse("srt://h:9000?%ff=1&latency=120").expect("ignored key");
assert_eq!(url.latency, Some(Duration::from_millis(120)));
}
#[test]
fn repeated_unknown_query_key_is_ignored() {
assert!(SrtUrl::parse("srt://h:9000?foo=1&foo=2").is_ok());
}
#[test]
fn valid_percent_encoded_utf8_streamid_decodes() {
let url = SrtUrl::parse("srt://h:9000?streamid=%C3%A9").expect("valid utf8");
assert_eq!(url.stream_id.as_deref(), Some("é"));
}
#[test]
fn the_srt_scheme_is_case_insensitive() {
let url = SrtUrl::parse("SRT://h:9000").expect("uppercase scheme names the same endpoint");
assert_eq!(url.host, "h");
assert_eq!(url.port, 9000);
}
#[test]
fn a_hash_inside_a_streamid_value_is_kept_whole() {
let url = SrtUrl::parse("srt://h:9000?streamid=#!::r=live/cam,m=publish")
.expect("hash-bearing streamid");
assert_eq!(url.stream_id.as_deref(), Some("#!::r=live/cam,m=publish"));
}
}