oximedia-net 0.1.3

Network streaming for OxiMedia
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
//! WHEP (WebRTC-HTTP Egress Protocol) client signaling.
//!
//! WHEP (draft-ietf-wish-whep) is the subscriber/playback counterpart to
//! WHIP.  A client sends an SDP offer via HTTP POST to the WHEP endpoint;
//! the server replies with an SDP answer.  The session is identified by the
//! `Location` header returned in the 201 response.
//!
//! This module provides:
//!
//! - [`WhepConfig`] — endpoint URL and optional bearer token
//! - [`WhepSession`] — tracks one WHEP session: SDP offer, optional answer
//! - [`WhepClient`] — creates sessions, formats HTTP request bodies
//!
//! All operations are **synchronous** (no I/O) — this module generates and
//! processes SDP payloads; actual HTTP transport is handled by the caller.
//!
//! # Example
//!
//! ```
//! use oximedia_net::whep_client::{WhepClient, WhepConfig};
//!
//! let config = WhepConfig {
//!     endpoint: "https://media.example.com/whep/live".to_owned(),
//!     bearer_token: Some("secret-token".to_owned()),
//! };
//!
//! let client = WhepClient::new(config);
//! let mut session = client.create_offer();
//!
//! // Simulate receiving an answer from the server
//! client.process_answer(&mut session, "v=0\r\no=- 0 0 IN IP4 0.0.0.0\r\n".to_owned());
//!
//! let body = WhepClient::format_whep_request(&session);
//! assert!(body.contains("application/sdp"));
//! ```

use std::fmt::Write as FmtWrite;

// ─── ICE credential helpers ───────────────────────────────────────────────────

/// Deterministic pseudo-random ICE ufrag derived from a seed.
fn derive_ice_ufrag(seed: &str) -> String {
    let mut h: u32 = 0x811c_9dc5;
    for b in seed.as_bytes() {
        h ^= *b as u32;
        h = h.wrapping_mul(0x0100_0193);
    }
    let chars: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
    let len = chars.len() as u32;
    (0..4)
        .map(|i| chars[((h >> (i * 8)) % len) as usize] as char)
        .collect()
}

/// Deterministic pseudo-random ICE password derived from a seed.
fn derive_ice_pwd(seed: &str) -> String {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325_u64;
    for b in seed.as_bytes() {
        h ^= *b as u64;
        h = h.wrapping_mul(0x0000_0100_0000_01b3_u64);
    }
    let chars: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let len = chars.len() as u64;
    (0u64..24)
        .map(|i| {
            let mixed = h
                .wrapping_add(i.wrapping_mul(6_364_136_223_846_793_005_u64))
                .wrapping_mul((i + 1).wrapping_mul(2_862_933_555_777_941_757_u64));
            chars[((mixed >> 33) % len) as usize] as char
        })
        .collect()
}

/// Monotonic counter for session IDs (module-level, wrapping).
fn next_session_id() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(1);
    COUNTER.fetch_add(1, Ordering::Relaxed)
}

// ─── WhepConfig ───────────────────────────────────────────────────────────────

/// Configuration for a WHEP egress client.
#[derive(Debug, Clone)]
pub struct WhepConfig {
    /// WHEP endpoint URL (HTTP POST target for SDP offer).
    pub endpoint: String,
    /// Optional bearer token for `Authorization: Bearer …` header.
    pub bearer_token: Option<String>,
}

impl WhepConfig {
    /// Create a minimal WHEP config with no authentication.
    #[must_use]
    pub fn new(endpoint: impl Into<String>) -> Self {
        Self {
            endpoint: endpoint.into(),
            bearer_token: None,
        }
    }

    /// Attach a bearer token.
    #[must_use]
    pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
        self.bearer_token = Some(token.into());
        self
    }

    /// Returns the `Authorization` header value if a token is set.
    #[must_use]
    pub fn authorization_header(&self) -> Option<String> {
        self.bearer_token.as_deref().map(|t| format!("Bearer {t}"))
    }
}

// ─── WhepSession ─────────────────────────────────────────────────────────────

/// A single WHEP egress session.
///
/// Carries the SDP offer generated by the client and stores the server's
/// SDP answer once it is received.
#[derive(Debug, Clone)]
pub struct WhepSession {
    /// Unique session identifier (monotonically increasing counter string).
    pub id: String,
    /// The SDP offer body sent to the WHEP server.
    pub sdp_offer: String,
    /// The SDP answer returned by the WHEP server, if available.
    pub sdp_answer: Option<String>,
}

impl WhepSession {
    /// Returns `true` if the server's SDP answer has been received.
    #[must_use]
    pub fn is_answered(&self) -> bool {
        self.sdp_answer.is_some()
    }
}

// ─── WhepClient ───────────────────────────────────────────────────────────────

/// WHEP egress client for generating SDP offers and processing server answers.
///
/// The client is stateless beyond holding the configuration; sessions are
/// independent values that the caller tracks.
pub struct WhepClient {
    config: WhepConfig,
}

impl WhepClient {
    /// Create a new WHEP client with the given configuration.
    #[must_use]
    pub fn new(config: WhepConfig) -> Self {
        Self { config }
    }

    /// Returns a reference to the client configuration.
    #[must_use]
    pub fn config(&self) -> &WhepConfig {
        &self.config
    }

    /// Generate a new WHEP session with a minimal SDP offer.
    ///
    /// The offer includes:
    /// - Session-level ICE credentials
    /// - A video `m=` line with H.264 / PT 96
    /// - An audio `m=` line with Opus / PT 111
    /// - `a=recvonly` direction (the WHEP subscriber receives media)
    ///
    /// Calling this does **not** perform any I/O.
    #[must_use]
    pub fn create_offer(&self) -> WhepSession {
        let seq = next_session_id();
        let id = format!("whep-{seq}");

        let ufrag = derive_ice_ufrag(&id);
        let pwd = derive_ice_pwd(&id);

        let mut sdp = String::with_capacity(512);
        sdp.push_str("v=0\r\n");
        let _ = writeln!(sdp, "o=- {seq} 0 IN IP4 0.0.0.0\r");
        sdp.push_str("s=WHEP Egress\r\n");
        sdp.push_str("t=0 0\r\n");
        let _ = writeln!(sdp, "a=ice-ufrag:{ufrag}\r");
        let _ = writeln!(sdp, "a=ice-pwd:{pwd}\r");
        sdp.push_str(
            "a=fingerprint:sha-256 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:\
00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\r\n",
        );
        sdp.push_str("a=setup:actpass\r\n");
        // Video m= line (subscriber → recvonly)
        sdp.push_str("m=video 9 UDP/TLS/RTP/SAVPF 96\r\n");
        sdp.push_str("c=IN IP4 0.0.0.0\r\n");
        sdp.push_str("a=rtpmap:96 H264/90000\r\n");
        sdp.push_str("a=recvonly\r\n");
        sdp.push_str("a=mid:video\r\n");
        // Audio m= line
        sdp.push_str("m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n");
        sdp.push_str("c=IN IP4 0.0.0.0\r\n");
        sdp.push_str("a=rtpmap:111 opus/48000/2\r\n");
        sdp.push_str("a=recvonly\r\n");
        sdp.push_str("a=mid:audio\r\n");

        WhepSession {
            id,
            sdp_offer: sdp,
            sdp_answer: None,
        }
    }

    /// Store the server's SDP answer in an existing session.
    ///
    /// The `session_id` is matched by value; if no match is found the
    /// `sdp_answer` in the returned session is left unset (no panic).
    ///
    /// # Note
    ///
    /// Since `WhepClient` is stateless (it does not hold sessions), the
    /// caller is responsible for looking up the correct [`WhepSession`] by
    /// `session_id` and passing a mutable reference here.
    pub fn process_answer(&self, session: &mut WhepSession, sdp_answer: String) {
        session.sdp_answer = Some(sdp_answer);
    }

    /// Format the HTTP request body and headers for a WHEP POST.
    ///
    /// Returns a string of the form:
    ///
    /// ```text
    /// Content-Type: application/sdp
    /// Accept: application/sdp
    /// [Authorization: Bearer <token>]
    ///
    /// <sdp_offer>
    /// ```
    ///
    /// The caller is responsible for transmitting this over HTTP.
    #[must_use]
    pub fn format_whep_request(session: &WhepSession) -> String {
        let mut out = String::with_capacity(session.sdp_offer.len() + 256);
        out.push_str("Content-Type: application/sdp\r\n");
        out.push_str("Accept: application/sdp\r\n");
        out.push_str("\r\n");
        out.push_str(&session.sdp_offer);
        out
    }

    /// Format the WHEP request with authorization header included.
    ///
    /// Like [`WhepClient::format_whep_request`] but prepends the `Authorization` header
    /// if the client has a bearer token configured.
    #[must_use]
    pub fn format_whep_request_authenticated(&self, session: &WhepSession) -> String {
        let mut out = String::with_capacity(session.sdp_offer.len() + 256);
        if let Some(auth) = self.config.authorization_header() {
            let _ = writeln!(out, "Authorization: {auth}\r");
        }
        out.push_str("Content-Type: application/sdp\r\n");
        out.push_str("Accept: application/sdp\r\n");
        out.push_str("\r\n");
        out.push_str(&session.sdp_offer);
        out
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

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

    fn make_client() -> WhepClient {
        WhepClient::new(WhepConfig::new("https://example.com/whep"))
    }

    // 1. WhepConfig::new has no bearer token by default
    #[test]
    fn test_whep_config_no_token() {
        let cfg = WhepConfig::new("https://example.com/whep");
        assert!(cfg.bearer_token.is_none());
        assert!(cfg.authorization_header().is_none());
    }

    // 2. WhepConfig::with_bearer_token sets token
    #[test]
    fn test_whep_config_bearer_token() {
        let cfg = WhepConfig::new("https://example.com/whep").with_bearer_token("tok123");
        assert_eq!(cfg.bearer_token.as_deref(), Some("tok123"));
        assert_eq!(cfg.authorization_header().as_deref(), Some("Bearer tok123"));
    }

    // 3. WhepClient::new stores config
    #[test]
    fn test_whep_client_new() {
        let client = make_client();
        assert_eq!(client.config().endpoint, "https://example.com/whep");
    }

    // 4. create_offer returns session with non-empty id
    #[test]
    fn test_create_offer_session_id() {
        let client = make_client();
        let session = client.create_offer();
        assert!(!session.id.is_empty());
        assert!(session.id.starts_with("whep-"));
    }

    // 5. create_offer SDP starts with v=0
    #[test]
    fn test_create_offer_sdp_starts_v0() {
        let client = make_client();
        let session = client.create_offer();
        assert!(session.sdp_offer.starts_with("v=0"), "SDP must begin v=0");
    }

    // 6. create_offer SDP contains recvonly direction
    #[test]
    fn test_create_offer_recvonly() {
        let client = make_client();
        let session = client.create_offer();
        assert!(
            session.sdp_offer.contains("a=recvonly"),
            "WHEP subscriber must use recvonly"
        );
    }

    // 7. create_offer SDP has video m= line
    #[test]
    fn test_create_offer_video_mline() {
        let client = make_client();
        let session = client.create_offer();
        assert!(session.sdp_offer.contains("m=video"), "must have video m=");
    }

    // 8. create_offer SDP has audio m= line
    #[test]
    fn test_create_offer_audio_mline() {
        let client = make_client();
        let session = client.create_offer();
        assert!(session.sdp_offer.contains("m=audio"), "must have audio m=");
    }

    // 9. sdp_answer is None before process_answer
    #[test]
    fn test_no_answer_initially() {
        let client = make_client();
        let session = client.create_offer();
        assert!(!session.is_answered());
        assert!(session.sdp_answer.is_none());
    }

    // 10. process_answer stores answer
    #[test]
    fn test_process_answer_stores() {
        let client = make_client();
        let mut session = client.create_offer();
        client.process_answer(&mut session, "v=0\r\no=- 0 0 IN IP4 0.0.0.0\r\n".to_owned());
        assert!(session.is_answered());
        assert!(session.sdp_answer.is_some());
    }

    // 11. process_answer stores correct SDP
    #[test]
    fn test_process_answer_content() {
        let client = make_client();
        let mut session = client.create_offer();
        let answer_sdp = "v=0\r\no=- 12345 0 IN IP4 192.168.1.1\r\n".to_owned();
        client.process_answer(&mut session, answer_sdp.clone());
        assert_eq!(session.sdp_answer.as_deref(), Some(answer_sdp.as_str()));
    }

    // 12. format_whep_request contains Content-Type header
    #[test]
    fn test_format_whep_request_content_type() {
        let client = make_client();
        let session = client.create_offer();
        let req = WhepClient::format_whep_request(&session);
        assert!(req.contains("Content-Type: application/sdp"));
    }

    // 13. format_whep_request contains Accept header
    #[test]
    fn test_format_whep_request_accept() {
        let client = make_client();
        let session = client.create_offer();
        let req = WhepClient::format_whep_request(&session);
        assert!(req.contains("Accept: application/sdp"));
    }

    // 14. format_whep_request contains the SDP body
    #[test]
    fn test_format_whep_request_body() {
        let client = make_client();
        let session = client.create_offer();
        let req = WhepClient::format_whep_request(&session);
        assert!(req.contains("v=0"));
        assert!(req.contains("m=video"));
    }

    // 15. format_whep_request_authenticated includes Authorization when token set
    #[test]
    fn test_format_whep_request_authenticated_with_token() {
        let cfg = WhepConfig::new("https://example.com/whep").with_bearer_token("my-token");
        let client = WhepClient::new(cfg);
        let session = client.create_offer();
        let req = client.format_whep_request_authenticated(&session);
        assert!(req.contains("Authorization: Bearer my-token"));
    }

    // 16. format_whep_request_authenticated without token has no Authorization
    #[test]
    fn test_format_whep_request_no_auth_when_no_token() {
        let client = make_client();
        let session = client.create_offer();
        let req = client.format_whep_request_authenticated(&session);
        assert!(!req.contains("Authorization:"));
    }

    // 17. Two successive create_offer calls produce distinct session IDs
    #[test]
    fn test_create_offer_unique_ids() {
        let client = make_client();
        let s1 = client.create_offer();
        let s2 = client.create_offer();
        assert_ne!(s1.id, s2.id);
    }

    // 18. SDP ICE ufrag is present in the offer
    #[test]
    fn test_create_offer_ice_ufrag_present() {
        let client = make_client();
        let session = client.create_offer();
        assert!(session.sdp_offer.contains("a=ice-ufrag:"));
    }

    // 19. SDP ICE pwd is present in the offer
    #[test]
    fn test_create_offer_ice_pwd_present() {
        let client = make_client();
        let session = client.create_offer();
        assert!(session.sdp_offer.contains("a=ice-pwd:"));
    }

    // 20. WhepSession is_answered false → true after process_answer
    #[test]
    fn test_is_answered_transitions() {
        let client = make_client();
        let mut session = client.create_offer();
        assert!(!session.is_answered());
        client.process_answer(&mut session, "v=0\r\n".to_owned());
        assert!(session.is_answered());
    }
}