str0m 0.18.0

WebRTC library in Sans-IO style
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Tests for configuration edge cases and validation.

use std::net::Ipv4Addr;
use std::time::{Duration, Instant};

use str0m::media::{Direction, MediaKind};
use str0m::{Event, RtcConfig, RtcError};
use tracing::info_span;

mod common;
use common::{Peer, TestRtc, init_crypto_default, init_log, negotiate, progress};

/// Test set_reordering_size_audio() and set_reordering_size_video() with custom sizes.
#[test]
fn config_reordering_size_custom() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    // Verify config builder correctly sets and retrieves values
    let config = RtcConfig::new()
        .set_reordering_size_audio(20)
        .set_reordering_size_video(50);

    // Verify the config has correct values before building
    assert_eq!(
        config.reordering_size_audio(),
        20,
        "Audio reordering size should be 20"
    );
    assert_eq!(
        config.reordering_size_video(),
        50,
        "Video reordering size should be 50"
    );

    // Verify default values are different
    let default_config = RtcConfig::new();
    assert_eq!(
        default_config.reordering_size_audio(),
        15,
        "Default audio reordering should be 15"
    );
    assert_eq!(
        default_config.reordering_size_video(),
        30,
        "Default video reordering should be 30"
    );

    // Build and verify the Rtc works with custom config
    let rtc = config.build(Instant::now());
    let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc);
    let mut r = TestRtc::new(Peer::Right);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    let mid = negotiate(&mut l, &mut r, |change| {
        change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None)
    });

    loop {
        if l.is_connected() && r.is_connected() {
            break;
        }
        if l.duration() > Duration::from_secs(5) {
            panic!("Failed to connect");
        }
        progress(&mut l, &mut r)?;
    }

    // Send and receive data to verify the config doesn't break functionality
    let params = l.params_opus();
    let pt = params.pt();
    let data = vec![1_u8; 80];

    for _ in 0..20 {
        let wallclock = l.start + l.duration();
        let time = l.duration().into();
        l.writer(mid)
            .unwrap()
            .write(pt, wallclock, time, data.clone())?;
        progress(&mut l, &mut r)?;
    }

    // Verify data was received
    let received_count = r
        .events
        .iter()
        .filter(|(_, e)| matches!(e, Event::MediaData(_)))
        .count();

    assert!(
        received_count > 10,
        "Should receive media data with custom reordering config, got {}",
        received_count
    );

    Ok(())
}

/// Test enable_raw_packets(true) produces RawPacket events.
#[test]
fn config_raw_packets_enabled() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    let rtc = RtcConfig::new()
        .enable_raw_packets(true)
        .build(Instant::now());

    let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc);

    let rtc_r = RtcConfig::new()
        .enable_raw_packets(true)
        .build(Instant::now());
    let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc_r);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    let mid = negotiate(&mut l, &mut r, |change| {
        change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None)
    });

    loop {
        if l.is_connected() && r.is_connected() {
            break;
        }
        if l.duration() > Duration::from_secs(5) {
            panic!("Failed to connect");
        }
        progress(&mut l, &mut r)?;
    }

    // Clear previous events
    l.events.clear();
    r.events.clear();

    // Send some audio data
    let params = l.params_opus();
    let pt = params.pt();
    let data = vec![1_u8; 80];

    for _ in 0..20 {
        let wallclock = l.start + l.duration();
        let time = l.duration().into();
        l.writer(mid)
            .unwrap()
            .write(pt, wallclock, time, data.clone())?;
        progress(&mut l, &mut r)?;
    }

    // Check for RawPacket events
    let raw_packet_count = r
        .events
        .iter()
        .filter(|(_, e)| matches!(e, Event::RawPacket(_)))
        .count();

    assert!(
        raw_packet_count > 0,
        "Should have RawPacket events with enable_raw_packets(true)"
    );

    Ok(())
}

/// Test set_stats_interval with custom duration.
#[test]
fn config_stats_interval_custom() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    let stats_interval = Duration::from_secs(1);
    let rtc = RtcConfig::new()
        .set_stats_interval(Some(stats_interval))
        .build(Instant::now());

    let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc);

    let rtc_r = RtcConfig::new()
        .set_stats_interval(Some(stats_interval))
        .build(Instant::now());
    let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc_r);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    let mid = negotiate(&mut l, &mut r, |change| {
        change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None)
    });

    loop {
        if l.is_connected() && r.is_connected() {
            break;
        }
        progress(&mut l, &mut r)?;
    }

    let max = l.last.max(r.last);
    l.last = max;
    r.last = max;

    let params = l.params_opus();
    let pt = params.pt();
    let data = vec![1_u8; 80];

    l.set_forced_time_advance(Duration::from_millis(1));
    r.set_forced_time_advance(Duration::from_millis(1));

    // Run for 5 seconds to get multiple stats events
    loop {
        let wallclock = l.start + l.duration();
        let time = l.duration().into();
        l.writer(mid)
            .unwrap()
            .write(pt, wallclock, time, data.clone())?;
        progress(&mut l, &mut r)?;
        if l.duration() > Duration::from_secs(5) {
            break;
        }
    }

    // Should have multiple stats events with 1s interval over 5s
    let peer_stats_count = l
        .events
        .iter()
        .filter(|(_, e)| matches!(e, Event::PeerStats(_)))
        .count();

    assert!(
        peer_stats_count >= 3,
        "Expected at least 3 PeerStats events with 1s interval over 5s, got {}",
        peer_stats_count
    );

    Ok(())
}

/// Test set_stats_interval(None) produces no stats events.
#[test]
fn config_stats_disabled() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    let rtc = RtcConfig::new()
        .set_stats_interval(None)
        .build(Instant::now());

    let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc);

    let rtc_r = RtcConfig::new()
        .set_stats_interval(None)
        .build(Instant::now());
    let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc_r);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    let mid = negotiate(&mut l, &mut r, |change| {
        change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None)
    });

    loop {
        if l.is_connected() && r.is_connected() {
            break;
        }
        progress(&mut l, &mut r)?;
    }

    let max = l.last.max(r.last);
    l.last = max;
    r.last = max;

    let params = l.params_opus();
    let pt = params.pt();
    let data = vec![1_u8; 80];

    l.set_forced_time_advance(Duration::from_millis(1));
    r.set_forced_time_advance(Duration::from_millis(1));

    loop {
        let wallclock = l.start + l.duration();
        let time = l.duration().into();
        l.writer(mid)
            .unwrap()
            .write(pt, wallclock, time, data.clone())?;
        progress(&mut l, &mut r)?;
        if l.duration() > Duration::from_secs(3) {
            break;
        }
    }

    let peer_stats_count = l
        .events
        .iter()
        .filter(|(_, e)| matches!(e, Event::PeerStats(_)))
        .count();

    assert_eq!(
        peer_stats_count, 0,
        "Should have no PeerStats events when stats disabled"
    );

    Ok(())
}

/// Test set_fingerprint_verification(false) allows connection with wrong fingerprint.
#[test]
fn config_fingerprint_verification_disabled() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    use str0m::Candidate;
    use str0m::crypto::Fingerprint;

    // Create RTCs with fingerprint verification DISABLED
    let rtc_l = RtcConfig::new()
        .set_fingerprint_verification(false)
        .set_rtp_mode(true)
        .build(Instant::now());

    let rtc_r = RtcConfig::new()
        .set_fingerprint_verification(false)
        .set_rtp_mode(true)
        .build(Instant::now());

    let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc_l);
    let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc_r);

    // Set up candidates
    let host1 = Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp").unwrap();
    let host2 = Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp").unwrap();
    l.add_local_candidate(host1.clone()).unwrap();
    l.add_remote_candidate(host2.clone());
    r.add_local_candidate(host2).unwrap();
    r.add_remote_candidate(host1);

    // Create CORRUPTED fingerprints (all zeros - definitely wrong)
    let corrupted_fingerprint = Fingerprint {
        hash_func: "sha-256".to_string(),
        bytes: vec![0u8; 32], // Wrong fingerprint!
    };

    // Set the WRONG fingerprints as remote (this would fail with verification enabled)
    l.direct_api()
        .set_remote_fingerprint(corrupted_fingerprint.clone());
    r.direct_api().set_remote_fingerprint(corrupted_fingerprint);

    // Exchange ICE credentials
    let creds_l = l.direct_api().local_ice_credentials();
    let creds_r = r.direct_api().local_ice_credentials();
    l.direct_api().set_remote_ice_credentials(creds_r);
    r.direct_api().set_remote_ice_credentials(creds_l);

    l.direct_api().set_ice_controlling(true);
    r.direct_api().set_ice_controlling(false);

    // Start DTLS - this should succeed despite wrong fingerprints
    // because verification is disabled
    l.direct_api().start_dtls(true).unwrap();
    r.direct_api().start_dtls(false).unwrap();

    l.direct_api().start_sctp(true);
    r.direct_api().start_sctp(false);

    // Connection should succeed despite corrupted fingerprints
    loop {
        if l.is_connected() && r.is_connected() {
            break;
        }
        if l.duration() > Duration::from_secs(5) {
            panic!("Failed to connect - fingerprint verification should be disabled");
        }
        progress(&mut l, &mut r)?;
    }

    // Verify we actually connected
    assert!(l.is_connected(), "L should be connected");
    assert!(r.is_connected(), "R should be connected");

    Ok(())
}

/// Test that RtcConfig can be cloned and used for multiple instances.
#[test]
fn config_clone_multiple_instances() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    // Create a config with custom settings (not ice_lite since both can't be ice_lite)
    let config = RtcConfig::new()
        .set_reordering_size_audio(20)
        .set_reordering_size_video(40);

    // Clone the config and create multiple instances
    let rtc1 = config.clone().build(Instant::now());
    let rtc2 = config.build(Instant::now());

    let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc1);
    let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc2);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    let (offer, pending) = l.span.in_scope(|| {
        let mut change = l.rtc.sdp_api();
        let _ = change.add_channel("test".into());
        change.apply().unwrap()
    });

    let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?;
    l.span
        .in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?;

    loop {
        if l.is_connected() && r.is_connected() {
            break;
        }
        if l.duration() > Duration::from_secs(5) {
            panic!("Failed to connect with cloned config");
        }
        progress(&mut l, &mut r)?;
    }

    Ok(())
}

/// Test set_send_buffer_audio and set_send_buffer_video configuration.
#[test]
fn config_send_buffer_sizes() -> Result<(), RtcError> {
    init_log();
    init_crypto_default();

    // Verify config builder correctly sets and retrieves values
    let config = RtcConfig::new()
        .set_send_buffer_audio(100)
        .set_send_buffer_video(2000);

    // Verify the config has correct values before building
    assert_eq!(
        config.send_buffer_audio(),
        100,
        "Audio send buffer should be 100"
    );
    assert_eq!(
        config.send_buffer_video(),
        2000,
        "Video send buffer should be 2000"
    );

    // Verify default values are different
    let default_config = RtcConfig::new();
    assert_eq!(
        default_config.send_buffer_audio(),
        50,
        "Default audio send buffer should be 50"
    );
    assert_eq!(
        default_config.send_buffer_video(),
        1000,
        "Default video send buffer should be 1000"
    );

    // Build and verify the Rtc works with custom config
    let rtc = config.build(Instant::now());
    let mut l = TestRtc::new_with_rtc(info_span!("L"), rtc);
    let mut r = TestRtc::new(Peer::Right);

    l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into());
    r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into());

    let mid = negotiate(&mut l, &mut r, |change| {
        change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None)
    });

    loop {
        if l.is_connected() && r.is_connected() {
            break;
        }
        if l.duration() > Duration::from_secs(5) {
            panic!("Failed to connect");
        }
        progress(&mut l, &mut r)?;
    }

    // Send and receive data to verify the config doesn't break functionality
    let params = l.params_opus();
    let pt = params.pt();
    let data = vec![1_u8; 80];

    for _ in 0..20 {
        let wallclock = l.start + l.duration();
        let time = l.duration().into();
        l.writer(mid)
            .unwrap()
            .write(pt, wallclock, time, data.clone())?;
        progress(&mut l, &mut r)?;
    }

    // Verify data was received
    let received_count = r
        .events
        .iter()
        .filter(|(_, e)| matches!(e, Event::MediaData(_)))
        .count();

    assert!(
        received_count > 10,
        "Should receive media data with custom send buffer config, got {}",
        received_count
    );

    Ok(())
}