srt-runtime 0.13.1

SRT (Secure Reliable Transport, draft-sharabayko-srt-01) packet codecs, sans-IO HSv5 handshakes, a one-connection link engine, ARQ, TSBPD, LiveCC/FileCC congestion control, optional payload crypto and an optional tokio UDP adapter; no_std core.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! The `srt://` URL a caller dials (draft-sharabayko-srt-01 §3.2.1.3 Stream
//! ID; the scheme itself is SRT's registered URL form).
//!
//! An SRT endpoint is a `host:port` plus the query overrides the Stream ID
//! handshake extension carries: `streamid` (opaque, passed through to the
//! handshake), `latency`, `mode` and `passphrase`. This module parses that
//! form into a typed [`SrtUrl`]; *which* values an endpoint accepts is policy
//! and belongs to the caller (the `multimux` push, for one, dials only in
//! Caller mode and rejects a passphrase).
//!
//! `std` only: the authority and query are parsed with the `url` crate and
//! `streamid` values are percent-decoded with `percent_encoding`.
//!
//! # Accepted shapes
//!
//! Both `srt://host:port?…` and a scheme-less `host:port?…` are accepted (an
//! operator's configured remote is often just `host:port`). An authority may
//! be `host`, `host:port`, `[v6]` or `[v6]:port`; a userinfo prefix is
//! rejected rather than silently dropped, because an SRT authority has no
//! credentials and a stream key written after `@` must not vanish into a bare
//! `host:port`. A bare, unbracketed IPv6 literal is rejected: `::1:9000` is
//! ambiguous (is `9000` a port or the last group?), so the operator brackets
//! it.
//!
//! The whole string is parsed with `url::Url` (so the scheme is matched
//! case-insensitively and the authority is read by the `url` crate, not by a
//! hand-rolled split). A Haivision `streamid=#!::r=…` value contains a `#` that
//! a `Url` treats as a fragment delimiter, which would cut the value short
//! unless it were percent-encoded; every `#` after the query separator is
//! escaped to `%23` before parsing and the query is then split on `&` and
//! percent-decoded value-by-value, restoring it.

use alloc::string::{String, ToString};
use core::net::{IpAddr, SocketAddr};
use core::time::Duration;

/// SRT's registered default port, so a URL that omits the port still names a
/// dialable endpoint.
pub const DEFAULT_PORT: u16 = 9000;

/// The largest `latency` the draft treats as practical
/// (draft-sharabayko-srt-01 §3.2.1.1), in milliseconds. A larger value is
/// rejected rather than clamped: a wrong latency is a real misconfiguration.
pub const MAX_LATENCY_MS: u16 = 8000;

/// Which side opens the SRT handshake (`draft-sharabayko-srt-01` §4.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum SrtMode {
    /// The caller dials a listener.
    #[default]
    Caller,
    /// The endpoint binds and accepts inbound callers.
    Listener,
}

impl UrlRejection {
    /// The `name()` label convention (#204).
    #[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 {
    /// The `name()` label convention (#204).
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            SrtMode::Caller => "caller",
            SrtMode::Listener => "listener",
        }
    }
}

broadcast_core::impl_spec_display!(SrtMode);
broadcast_core::impl_spec_display!(UrlRejection);

/// A parsed `srt://` URL: the endpoint to dial and its Stream ID overrides.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SrtUrl {
    /// The endpoint's host (a domain name or a bracketed IP literal).
    pub host: String,
    /// The endpoint's port, [`DEFAULT_PORT`] when the URL omits it.
    pub port: u16,
    /// The opaque `streamid` value, percent-decoded.
    pub stream_id: Option<String>,
    /// The `latency` value, at most [`MAX_LATENCY_MS`].
    pub latency: Option<Duration>,
    /// The `mode` value; [`SrtMode::Caller`] when absent.
    pub mode: SrtMode,
    /// The `passphrase` value (payload encryption).
    pub passphrase: Option<String>,
}

/// Why an `srt://` URL was rejected: the failing part of the grammar, so a
/// caller can word its own error while the grammar stays in one place.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum UrlRejection {
    /// The authority is not a `host[:port]` — no host, a bad port, a userinfo
    /// prefix, or an ambiguous bare IPv6 literal.
    Authority,
    /// A `latency` that is not whole milliseconds.
    LatencyNotANumber,
    /// A `latency` above [`MAX_LATENCY_MS`].
    LatencyTooLarge,
    /// A `mode` other than `caller` or `listener`.
    Mode,
    /// A percent-decoded value was not valid UTF-8.
    InvalidUtf8,
    /// The same query key appeared more than once.
    DuplicateKey,
}

/// Manual `Debug`: a `passphrase` is a secret and never renders.
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 {
    /// Parse an `srt://` URL; see this module's own doc for the accepted
    /// shapes.
    ///
    /// An absent `latency`, `mode` or `passphrase` leaves the corresponding
    /// field unset, so the caller keeps whatever its handshake config already
    /// holds. Unknown query keys are ignored.
    ///
    /// # Errors
    ///
    /// [`UrlRejection::Authority`] for a bad authority,
    /// [`UrlRejection::LatencyNotANumber`]/[`UrlRejection::LatencyTooLarge`]
    /// for a `latency`, and [`UrlRejection::Mode`] for an unknown `mode`.
    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)
    }

    /// Parse a bare `host:port` endpoint: the authority an operator configures
    /// for a caller-mode dial. Unlike [`SrtUrl::parse`] the port is required
    /// and nothing may follow the authority, so a path, query, fragment or
    /// userinfo is rejected rather than dropped.
    ///
    /// # Errors
    ///
    /// [`UrlRejection::Authority`] when `addr` is not exactly `host:port`
    /// (a bracketed IPv6 literal is accepted, a bare one is not).
    pub fn parse_endpoint(addr: &str) -> Result<Self, UrlRejection> {
        if addr.contains(['/', '?', '#', '@']) {
            return Err(UrlRejection::Authority);
        }
        let parsed_url = url::Url::parse(&alloc::format!("srt://{addr}"))
            .map_err(|_| UrlRejection::Authority)?;
        if parsed_url.port().is_none() {
            return Err(UrlRejection::Authority);
        }
        Self::parse(parsed_url.as_str())
    }

    /// The handshake's dial address: `host:port`, or the literal socket
    /// address when the host already is an IP.
    #[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),
        }
    }
}

/// Parse the whole `srt://host[:port][?query]` or scheme-less `host[:port][?query]`
/// string into a `url::Url`, or `None` when it is not one.
///
/// A Haivision `streamid=#!::r=…` value contains a `#` that a `Url` treats as
/// a fragment delimiter (cutting the value short) unless it is percent-encoded,
/// so every `#` after the query separator is escaped to `%23` before parsing;
/// the query is then percent-decoded value-by-value, restoring it. The SRT
/// scheme is matched case-insensitively by [`has_srt_scheme`], so `SRT://` names
/// the same endpoint as `srt://`; a string with no explicit SRT scheme is an
/// operator's bare `host:port` and is prefixed with `srt://` before parsing.
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()
    }
}

/// Whether `input` opens with an explicit `srt://` scheme, matched
/// case-insensitively. An explicit scheme is parsed as an absolute URL (and a
/// malformed one is rejected), never re-prefixed: that keeps a bad authority
/// like `srt://::1` an error instead of turning into a host named `srt`.
fn has_srt_scheme(input: &str) -> bool {
    input
        .get(.."srt://".len())
        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("srt://"))
}

/// Percent-encode every `#` that occurs after the first `?`, so a `#` inside a
/// query value is not read as a fragment delimiter (see [`parse_url`]).
/// Capacity slack for the percent-escapes this pass may add.
const PERCENT_ESCAPE_SLACK: usize = 8;

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() + PERCENT_ESCAPE_SLACK);
            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(),
    }
}

/// The host as `SrtUrl` exposes it: a bracketed IPv6 literal keeps its
/// brackets (`[::1]`), matching [`SrtUrl::dial_addr`]'s output.
fn bracketed_host(url: &url::Url) -> Option<String> {
    url.host_str().map(alloc::string::ToString::to_string)
}

/// Parse a `latency` value: whole milliseconds, at most [`MAX_LATENCY_MS`].
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)))
}

/// Parse a `mode` value.
fn parse_mode(value: &str) -> Option<SrtMode> {
    match value {
        "caller" => Some(SrtMode::Caller),
        "listener" => Some(SrtMode::Listener),
        _ => None,
    }
}

/// Percent-decode a query value. A stray `%` with no valid hex pair is kept
/// literally rather than dropped.
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 parse_endpoint_accepts_only_a_bare_host_and_port() {
        for ok in ["example.com:9000", "127.0.0.1:9000", "[::1]:9000"] {
            let url = SrtUrl::parse_endpoint(ok).expect(ok);
            assert_eq!(url.port, 9000, "{ok}");
        }
        for bad in [
            "nonsense",
            ":9000",
            "example.com:notaport",
            "example.com:70000",
            "host:9000/path",
            "host:9000?x=1",
            "host:9000#frag",
            "user@host:9000",
            "::1:9000",
        ] {
            assert_eq!(
                SrtUrl::parse_endpoint(bad),
                Err(UrlRejection::Authority),
                "{bad}"
            );
        }
    }

    #[test]
    fn srt_mode_labels() {
        assert_eq!(SrtMode::Caller.name(), "caller");
        assert_eq!(SrtMode::Listener.name(), "listener");
    }

    #[test]
    fn url_rejection_labels() {
        assert_eq!(UrlRejection::Authority.name(), "authority");
        assert_eq!(
            UrlRejection::LatencyNotANumber.name(),
            "latency-not-a-number"
        );
        assert_eq!(UrlRejection::LatencyTooLarge.name(), "latency-too-large");
        assert_eq!(UrlRejection::Mode.name(), "mode");
        assert_eq!(UrlRejection::InvalidUtf8.name(), "invalid-utf8");
        assert_eq!(UrlRejection::DuplicateKey.name(), "duplicate-key");
    }

    #[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() {
        // Before this parsed through `url::Url`, the scheme was matched by a
        // case-sensitive `split_once("srt://")`, so `SRT://` fell through to
        // the scheme-less branch and became a host literally named `SRT://h`.
        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() {
        // A Haivision streamid value carries a `#`; a naive `Url` parse would
        // treat it as a fragment delimiter and cut the value short.
        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"));
    }
}