oximedia-videoip 0.1.8

Professional video-over-IP protocol for OxiMedia (patent-free NDI alternative)
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
#![allow(dead_code)]
//! SRT (Secure Reliable Transport) configuration for video-over-IP.
//!
//! Provides configuration types and validation for SRT connections,
//! including caller/listener/rendezvous modes, encryption, latency
//! settings, and bandwidth overhead. SRT is widely used in broadcast
//! contribution and distribution links over the public internet.

use std::fmt;
use std::net::SocketAddr;
use std::time::Duration;

// ---------------------------------------------------------------------------
// Enums
// ---------------------------------------------------------------------------

/// SRT connection mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SrtMode {
    /// Caller initiates the connection to a listener.
    Caller,
    /// Listener waits for incoming caller connections.
    Listener,
    /// Both sides attempt simultaneous connection (firewall traversal).
    Rendezvous,
}

impl fmt::Display for SrtMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Caller => write!(f, "caller"),
            Self::Listener => write!(f, "listener"),
            Self::Rendezvous => write!(f, "rendezvous"),
        }
    }
}

/// SRT encryption key length.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SrtKeyLength {
    /// No encryption.
    None,
    /// AES-128 encryption.
    Aes128,
    /// AES-192 encryption.
    Aes192,
    /// AES-256 encryption.
    Aes256,
}

impl SrtKeyLength {
    /// Return the key length in bits.
    #[must_use]
    pub fn bits(self) -> u32 {
        match self {
            Self::None => 0,
            Self::Aes128 => 128,
            Self::Aes192 => 192,
            Self::Aes256 => 256,
        }
    }
}

/// Congestion control algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CongestionControl {
    /// Live mode (low-latency, UDP-based pacing).
    Live,
    /// File mode (high-throughput, TCP-like congestion avoidance).
    File,
}

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// SRT connection configuration.
#[derive(Debug, Clone)]
pub struct SrtConfig {
    /// Connection mode.
    pub mode: SrtMode,
    /// Local bind address (for listener or rendezvous).
    pub local_addr: SocketAddr,
    /// Remote address (for caller or rendezvous).
    pub remote_addr: Option<SocketAddr>,
    /// Latency (the receive buffer duration). Typical: 120..4000 ms.
    pub latency: Duration,
    /// Peer latency (override for the remote side).
    pub peer_latency: Option<Duration>,
    /// Maximum bandwidth in bits/sec (0 = unlimited).
    pub max_bandwidth_bps: u64,
    /// Overhead bandwidth percentage (5..100).
    pub overhead_percent: u8,
    /// Encryption key length.
    pub encryption: SrtKeyLength,
    /// Passphrase for encryption (10..79 characters).
    pub passphrase: Option<String>,
    /// Stream ID (application-level routing).
    pub stream_id: Option<String>,
    /// Congestion control mode.
    pub congestion_control: CongestionControl,
    /// Maximum segment size (payload bytes per UDP packet).
    pub mss: u16,
    /// Flight flag size (send buffer in packets).
    pub flight_flag_size: u32,
    /// Connection timeout.
    pub connect_timeout: Duration,
    /// Enable periodic NAK reports.
    pub nak_report: bool,
    /// Time-to-live for packets (hops).
    pub ttl: u8,
}

impl Default for SrtConfig {
    fn default() -> Self {
        Self {
            mode: SrtMode::Caller,
            local_addr: "0.0.0.0:0".parse().expect("valid default addr"),
            remote_addr: None,
            latency: Duration::from_millis(120),
            peer_latency: None,
            max_bandwidth_bps: 0,
            overhead_percent: 25,
            encryption: SrtKeyLength::None,
            passphrase: None,
            stream_id: None,
            congestion_control: CongestionControl::Live,
            mss: 1500,
            flight_flag_size: 25600,
            connect_timeout: Duration::from_secs(3),
            nak_report: true,
            ttl: 64,
        }
    }
}

/// Validation error for SRT configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SrtConfigError {
    /// Description of the validation failure.
    pub message: String,
}

impl fmt::Display for SrtConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SRT config error: {}", self.message)
    }
}

impl std::error::Error for SrtConfigError {}

impl SrtConfig {
    /// Create a caller configuration connecting to the given remote.
    #[must_use]
    pub fn caller(remote: SocketAddr) -> Self {
        Self {
            mode: SrtMode::Caller,
            remote_addr: Some(remote),
            ..Default::default()
        }
    }

    /// Create a listener configuration bound to the given address.
    #[must_use]
    pub fn listener(bind: SocketAddr) -> Self {
        Self {
            mode: SrtMode::Listener,
            local_addr: bind,
            ..Default::default()
        }
    }

    /// Create a rendezvous configuration.
    #[must_use]
    pub fn rendezvous(local: SocketAddr, remote: SocketAddr) -> Self {
        Self {
            mode: SrtMode::Rendezvous,
            local_addr: local,
            remote_addr: Some(remote),
            ..Default::default()
        }
    }

    /// Set latency.
    #[must_use]
    pub fn with_latency(mut self, latency: Duration) -> Self {
        self.latency = latency;
        self
    }

    /// Set encryption.
    #[must_use]
    pub fn with_encryption(mut self, key_len: SrtKeyLength, passphrase: &str) -> Self {
        self.encryption = key_len;
        self.passphrase = Some(passphrase.to_owned());
        self
    }

    /// Set stream ID.
    #[must_use]
    pub fn with_stream_id(mut self, id: &str) -> Self {
        self.stream_id = Some(id.to_owned());
        self
    }

    /// Set maximum bandwidth.
    #[must_use]
    pub fn with_max_bandwidth(mut self, bps: u64) -> Self {
        self.max_bandwidth_bps = bps;
        self
    }

    /// Validate the configuration.
    pub fn validate(&self) -> Result<(), SrtConfigError> {
        // Caller and rendezvous require a remote address
        if self.mode != SrtMode::Listener && self.remote_addr.is_none() {
            return Err(SrtConfigError {
                message: format!("{} mode requires a remote address", self.mode),
            });
        }

        // Passphrase length
        if let Some(ref pp) = self.passphrase {
            if pp.len() < 10 || pp.len() > 79 {
                return Err(SrtConfigError {
                    message: "Passphrase must be 10..79 characters".to_owned(),
                });
            }
        }

        // Encryption requires passphrase
        if self.encryption != SrtKeyLength::None && self.passphrase.is_none() {
            return Err(SrtConfigError {
                message: "Encryption requires a passphrase".to_owned(),
            });
        }

        // Overhead
        if self.overhead_percent < 5 || self.overhead_percent > 100 {
            return Err(SrtConfigError {
                message: "Overhead percentage must be 5..100".to_owned(),
            });
        }

        // MSS
        if self.mss < 76 {
            return Err(SrtConfigError {
                message: "MSS must be >= 76".to_owned(),
            });
        }

        // Latency sanity
        if self.latency.as_millis() > 30_000 {
            return Err(SrtConfigError {
                message: "Latency must be <= 30000 ms".to_owned(),
            });
        }

        Ok(())
    }

    /// Build an SRT URI string (srt://host:port?key=val&...).
    #[must_use]
    pub fn to_uri(&self) -> String {
        let addr = self.remote_addr.unwrap_or(self.local_addr);
        let mut params = Vec::new();
        params.push(format!("mode={}", self.mode));
        params.push(format!("latency={}", self.latency.as_millis()));
        if self.encryption != SrtKeyLength::None {
            params.push(format!("pbkeylen={}", self.encryption.bits()));
        }
        if let Some(ref pp) = self.passphrase {
            params.push(format!("passphrase={pp}"));
        }
        if let Some(ref sid) = self.stream_id {
            params.push(format!("streamid={sid}"));
        }
        format!("srt://{}?{}", addr, params.join("&"))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn remote() -> SocketAddr {
        "192.168.1.100:9000"
            .parse()
            .expect("should succeed in test")
    }

    fn local() -> SocketAddr {
        "0.0.0.0:9000".parse().expect("should succeed in test")
    }

    #[test]
    fn test_default_config() {
        let cfg = SrtConfig::default();
        assert_eq!(cfg.mode, SrtMode::Caller);
        assert_eq!(cfg.latency, Duration::from_millis(120));
        assert_eq!(cfg.encryption, SrtKeyLength::None);
        assert!(cfg.passphrase.is_none());
    }

    #[test]
    fn test_caller_factory() {
        let cfg = SrtConfig::caller(remote());
        assert_eq!(cfg.mode, SrtMode::Caller);
        assert_eq!(cfg.remote_addr, Some(remote()));
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_listener_factory() {
        let cfg = SrtConfig::listener(local());
        assert_eq!(cfg.mode, SrtMode::Listener);
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_rendezvous_factory() {
        let cfg = SrtConfig::rendezvous(local(), remote());
        assert_eq!(cfg.mode, SrtMode::Rendezvous);
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_caller_without_remote_fails() {
        let cfg = SrtConfig::default(); // caller but no remote
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_encryption_without_passphrase_fails() {
        let cfg = SrtConfig {
            encryption: SrtKeyLength::Aes256,
            passphrase: None,
            remote_addr: Some(remote()),
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_passphrase_too_short() {
        let cfg = SrtConfig {
            encryption: SrtKeyLength::Aes128,
            passphrase: Some("short".to_owned()),
            remote_addr: Some(remote()),
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_valid_encryption() {
        let cfg = SrtConfig::caller(remote())
            .with_encryption(SrtKeyLength::Aes256, "mySecretPassphrase123");
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_overhead_out_of_range() {
        let cfg = SrtConfig {
            overhead_percent: 3,
            remote_addr: Some(remote()),
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_mss_too_small() {
        let cfg = SrtConfig {
            mss: 50,
            remote_addr: Some(remote()),
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_latency_too_large() {
        let cfg = SrtConfig {
            latency: Duration::from_secs(60),
            remote_addr: Some(remote()),
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn test_key_length_bits() {
        assert_eq!(SrtKeyLength::None.bits(), 0);
        assert_eq!(SrtKeyLength::Aes128.bits(), 128);
        assert_eq!(SrtKeyLength::Aes192.bits(), 192);
        assert_eq!(SrtKeyLength::Aes256.bits(), 256);
    }

    #[test]
    fn test_to_uri() {
        let cfg = SrtConfig::caller(remote())
            .with_latency(Duration::from_millis(200))
            .with_stream_id("camera1");
        let uri = cfg.to_uri();
        assert!(uri.starts_with("srt://"));
        assert!(uri.contains("latency=200"));
        assert!(uri.contains("streamid=camera1"));
    }

    #[test]
    fn test_mode_display() {
        assert_eq!(SrtMode::Caller.to_string(), "caller");
        assert_eq!(SrtMode::Listener.to_string(), "listener");
        assert_eq!(SrtMode::Rendezvous.to_string(), "rendezvous");
    }

    #[test]
    fn test_builder_chain() {
        let cfg = SrtConfig::caller(remote())
            .with_latency(Duration::from_millis(500))
            .with_max_bandwidth(10_000_000)
            .with_stream_id("test");
        assert_eq!(cfg.latency, Duration::from_millis(500));
        assert_eq!(cfg.max_bandwidth_bps, 10_000_000);
        assert_eq!(cfg.stream_id.as_deref(), Some("test"));
    }
}