str0m/config.rs
1use std::ops::RangeInclusive;
2use std::sync::Arc;
3use std::time::{Duration, Instant};
4
5use crate::Rtc;
6use crate::config::DtlsCert;
7use crate::crypto::CryptoProvider;
8use crate::crypto::dtls::DtlsVersion;
9use crate::format::CodecConfig;
10use crate::format::Vp9PacketizerMode;
11use crate::ice::IceCreds;
12use crate::io::DATAGRAM_MTU_TARGET;
13use crate::io::DATAGRAM_MTU_TARGET_MAX;
14use crate::io::DATAGRAM_MTU_TARGET_MIN;
15use crate::io::DATAGRAM_MTU_WARN;
16use crate::rtp_::{Bitrate, Extension, ExtensionMap};
17
18/// Customized config for creating an [`Rtc`] instance.
19///
20/// ```
21/// # #[cfg(feature = "openssl")] {
22/// use std::time::Instant;
23/// use str0m::RtcConfig;
24///
25/// let rtc = RtcConfig::new()
26/// .set_ice_lite(true)
27/// .build(Instant::now());
28/// # }
29/// ```
30///
31/// Configs implement [`Clone`] to help create multiple `Rtc` instances.
32#[derive(Debug, Clone)]
33pub struct RtcConfig {
34 pub(crate) local_ice_credentials: Option<IceCreds>,
35 pub(crate) crypto_provider: Option<Arc<CryptoProvider>>,
36 pub(crate) dtls_cert: Option<DtlsCert>,
37 pub(crate) fingerprint_verification: bool,
38 pub(crate) ice_lite: bool,
39 pub(crate) initial_stun_rto: Option<Duration>,
40 pub(crate) max_stun_rto: Option<Duration>,
41 pub(crate) max_stun_retransmits: Option<usize>,
42 pub(crate) codec_config: CodecConfig,
43 pub(crate) exts: ExtensionMap,
44 pub(crate) stats_interval: Option<Duration>,
45 pub(crate) intervals: RtcpReportIntervals,
46 pub(crate) bwe_config: Option<BweConfig>,
47 pub(crate) reordering_size_audio: usize,
48 pub(crate) reordering_size_video: usize,
49 pub(crate) reordering_timeout_audio: Option<Duration>,
50 pub(crate) pause_threshold: Duration,
51 pub(crate) send_buffer_audio: usize,
52 pub(crate) send_buffer_video: usize,
53 pub(crate) sctp_max_buffered_amount: usize,
54 pub(crate) sctp_max_message_size: u32,
55 pub(crate) rtp_mode: bool,
56 pub(crate) enable_raw_packets: bool,
57 pub(crate) dtls_version: DtlsVersion,
58 pub(crate) vp9_packetizer_mode: Vp9PacketizerMode,
59 pub(crate) snap_enabled: bool,
60 pub(crate) mtu: RangeInclusive<usize>,
61}
62
63#[derive(Debug, Clone)]
64pub(crate) struct BweConfig {
65 pub(crate) initial_bitrate: Bitrate,
66}
67
68#[derive(Debug, Clone, Copy)]
69pub(crate) struct RtcpReportIntervals {
70 pub(crate) audio: Duration,
71 pub(crate) video: Duration,
72}
73
74impl RtcpReportIntervals {
75 pub(crate) fn for_audio(self, audio: bool) -> Duration {
76 if audio { self.audio } else { self.video }
77 }
78}
79
80impl RtcConfig {
81 /// Creates a new default config.
82 pub fn new() -> Self {
83 RtcConfig::default()
84 }
85
86 /// Get the local ICE credentials, if set.
87 ///
88 /// If not specified, local credentials will be randomly generated when
89 /// building the [`Rtc`] instance.
90 pub fn local_ice_credentials(&self) -> &Option<IceCreds> {
91 &self.local_ice_credentials
92 }
93
94 /// Explicitly sets local ICE credentials.
95 pub fn set_local_ice_credentials(mut self, local_ice_credentials: IceCreds) -> Self {
96 self.local_ice_credentials = Some(local_ice_credentials);
97 self
98 }
99
100 /// Set the crypto provider.
101 ///
102 /// This overrides what is set in [`crate::crypto::CryptoProvider::install_process_default()`].
103 pub fn set_crypto_provider(mut self, p: Arc<CryptoProvider>) -> Self {
104 self.crypto_provider = Some(p);
105 self
106 }
107
108 /// The configured crypto provider, if explicitly set.
109 ///
110 /// Returns `None` if not explicitly set via [`Self::set_crypto_provider()`].
111 /// When `None`, the process default will be checked when building the [`Rtc`] instance.
112 pub fn crypto_provider(&self) -> Option<&Arc<CryptoProvider>> {
113 self.crypto_provider.as_ref()
114 }
115
116 /// Returns the configured DTLS certificate, if set.
117 ///
118 /// If not set, a certificate will be generated automatically.
119 pub fn dtls_cert(&self) -> Option<&DtlsCert> {
120 self.dtls_cert.as_ref()
121 }
122
123 /// Set a pregenerated DTLS certificate.
124 ///
125 /// If not set, a certificate will be generated automatically using
126 /// the configured crypto provider.
127 ///
128 /// ```
129 /// # use str0m::RtcConfig;
130 /// # use str0m::crypto;
131 ///
132 /// let provider = crypto::from_feature_flags();
133 /// let cert = provider.dtls_provider.generate_certificate().unwrap();
134 /// let rtc_config = RtcConfig::default()
135 /// .set_dtls_cert(cert);
136 /// ```
137 pub fn set_dtls_cert(mut self, cert: DtlsCert) -> Self {
138 self.dtls_cert = Some(cert);
139 self
140 }
141
142 /// Toggle ice lite. Ice lite is a mode for WebRTC servers with public IP address.
143 /// An [`Rtc`] instance in ice lite mode will not make STUN binding requests, but only
144 /// answer to requests from the remote peer.
145 ///
146 /// See [ICE RFC][1]
147 ///
148 /// [1]: https://www.rfc-editor.org/rfc/rfc8445#page-13
149 pub fn set_ice_lite(mut self, enabled: bool) -> Self {
150 self.ice_lite = enabled;
151 self
152 }
153
154 /// Sets the initial STUN retransmission timeout (RTO).
155 ///
156 /// This is the initial wait time before a STUN request is retransmitted.
157 /// The timeout will double with each retry, starting from this value.
158 ///
159 /// Defaults to 250ms.
160 pub fn set_initial_stun_rto(&mut self, rto: Duration) {
161 self.initial_stun_rto = Some(rto);
162 }
163
164 /// Sets the maximum STUN retransmission timeout for the ICE agent.
165 ///
166 /// This is the upper bound for how long to wait between retransmissions.
167 /// It also controls how often successful bindings are checked.
168 ///
169 /// Defaults to 3000ms.
170 pub fn set_max_stun_rto(&mut self, rto: Duration) {
171 self.max_stun_rto = Some(rto);
172 }
173
174 /// Sets the maximum number of retransmits for STUN messages.
175 ///
176 /// Defaults to 9.
177 pub fn set_max_stun_retransmits(&mut self, num: usize) {
178 self.max_stun_retransmits = Some(num);
179 }
180
181 /// Get fingerprint verification mode.
182 ///
183 /// ```
184 /// # use str0m::Rtc;
185 /// let config = Rtc::builder();
186 ///
187 /// // Defaults to true.
188 /// assert!(config.fingerprint_verification());
189 /// ```
190 pub fn fingerprint_verification(&self) -> bool {
191 self.fingerprint_verification
192 }
193
194 /// Toggle certificate fingerprint verification.
195 ///
196 /// By default the certificate fingerprint is verified.
197 pub fn set_fingerprint_verification(mut self, enabled: bool) -> Self {
198 self.fingerprint_verification = enabled;
199 self
200 }
201
202 /// Tells whether ice lite is enabled.
203 ///
204 /// ```
205 /// # #[cfg(feature = "openssl")] {
206 /// # use str0m::Rtc;
207 /// let config = Rtc::builder();
208 ///
209 /// // Defaults to false.
210 /// assert_eq!(config.ice_lite(), false);
211 /// # }
212 /// ```
213 pub fn ice_lite(&self) -> bool {
214 self.ice_lite
215 }
216
217 /// Lower level access to precise configuration of codecs (payload types).
218 pub fn codec_config(&mut self) -> &mut CodecConfig {
219 &mut self.codec_config
220 }
221
222 /// Clear all configured codecs.
223 ///
224 /// ```
225 /// # #[cfg(feature = "openssl")] {
226 /// # use std::time::Instant;
227 /// # use str0m::RtcConfig;
228 /// // For the session to use only OPUS and VP8.
229 /// let mut rtc = RtcConfig::default()
230 /// .clear_codecs()
231 /// .enable_opus(true, false)
232 /// .enable_vp8(true)
233 /// .build(Instant::now());
234 /// # }
235 /// ```
236 pub fn clear_codecs(mut self) -> Self {
237 self.codec_config.clear();
238 self
239 }
240
241 /// Enable opus audio codec, optionally with RFC 2198 RED (redundant audio).
242 ///
243 /// Enabled by default (without RED). `use_red` folds a RED payload type onto Opus so the
244 /// receiver can recover packet loss without retransmission, at the cost of extra audio payload
245 /// size. Each audio codec carries its own RED payload type. The redundancy depth is set with
246 /// [`Self::set_red_distances`] (default one level, the previous frame), and wrapping can be
247 /// toggled at runtime on the send side without renegotiation via
248 /// [`DirectApi::set_red_send`][crate::change::DirectApi::set_red_send].
249 pub fn enable_opus(mut self, enabled: bool, use_red: bool) -> Self {
250 self.codec_config.enable_opus(enabled, use_red);
251 self
252 }
253
254 /// Set the RFC 2198 RED send-side redundancy pattern: how many packets back each redundant
255 /// level carries. `[1]` (the default) sends one level, the previous frame, as browsers do;
256 /// `[1, 3, 5]` sends three levels for higher loss at the cost of more bandwidth.
257 ///
258 /// The pattern is sanitised (zeros and values deeper than the recovery depth are dropped, then
259 /// sorted and de-duped) and always includes distance 1 as the recovery anchor (so `[2, 4]`
260 /// becomes `[1, 2, 4]`), falling back to `[1]` if empty. This only sets the pattern; enable RED
261 /// via the `use_red` argument of an audio codec (e.g. [`Self::enable_opus`]) for it to take effect.
262 pub fn set_red_distances(mut self, distances: &[u32]) -> Self {
263 self.codec_config.set_red_distances(distances);
264 self
265 }
266
267 /// Enable PCM μ-law audio codec, optionally with RFC 2198 RED (see [`Self::enable_opus`] for
268 /// `use_red`).
269 ///
270 /// This is 14-bit audio compressed to 8-bit as specified by G.711
271 pub fn enable_pcmu(mut self, enabled: bool, use_red: bool) -> Self {
272 self.codec_config.enable_pcmu(enabled, use_red);
273 self
274 }
275
276 /// Enable PCM a-law audio codec, optionally with RFC 2198 RED (see [`Self::enable_opus`] for
277 /// `use_red`).
278 ///
279 /// This is 13-bit audio compressed to 8-bit as specified by G.711
280 pub fn enable_pcma(mut self, enabled: bool, use_red: bool) -> Self {
281 self.codec_config.enable_pcma(enabled, use_red);
282 self
283 }
284
285 /// Enable G722 audio codec.
286 ///
287 /// This is 16 kHz audio compressed to 64 kbit/s as specified by G.722. Note that
288 /// per RFC 3551 §4.5.2 the RTP clock rate on the wire is 8000 Hz even though the
289 /// codec samples at 16 kHz. str0m treats G722 as a 16 kHz codec in the API and
290 /// handles the 8 kHz RTP timestamp mapping internally. See
291 /// <https://en.wikipedia.org/wiki/RTP_payload_formats#cite_note-55>
292 ///
293 /// See [`Self::enable_opus`] for `use_red`.
294 pub fn enable_g722(mut self, enabled: bool, use_red: bool) -> Self {
295 self.codec_config.enable_g722(enabled, use_red);
296 self
297 }
298
299 /// Enable the RFC 3389 Comfort Noise payload at 8000 Hz.
300 ///
301 /// Disabled by default. Higher clock rates require a dynamic payload type
302 /// and can be added through [`RtcConfig::codec_config`].
303 pub fn enable_comfort_noise(mut self, enabled: bool) -> Self {
304 self.codec_config.enable_comfort_noise(enabled);
305 self
306 }
307
308 /// Enable AMR-WB audio codec.
309 ///
310 /// Disabled by default.
311 pub fn enable_amr_wb(mut self, enabled: bool) -> Self {
312 self.codec_config.enable_amr_wb(enabled);
313 self
314 }
315
316 /// Enable VP8 video codec.
317 ///
318 /// Enabled by default.
319 pub fn enable_vp8(mut self, enabled: bool) -> Self {
320 self.codec_config.enable_vp8(enabled);
321 self
322 }
323
324 /// Enable H264 video codec.
325 ///
326 /// Enabled by default.
327 pub fn enable_h264(mut self, enabled: bool) -> Self {
328 self.codec_config.enable_h264(enabled);
329 self
330 }
331
332 /// Enable H265 video codec.
333 ///
334 /// Enabled by default.
335 pub fn enable_h265(mut self, enabled: bool) -> Self {
336 self.codec_config.enable_h265(enabled);
337 self
338 }
339
340 /// Enable H266 (VVC) video codec.
341 ///
342 /// Disabled by default: no major browser (Chrome, Safari, Firefox)
343 /// currently supports H.266/VVC, so it is opt-in.
344 pub fn enable_h266(mut self, enabled: bool) -> Self {
345 self.codec_config.enable_h266(enabled);
346 self
347 }
348
349 /// Enable VP9 video codec.
350 ///
351 /// Enabled by default.
352 pub fn enable_vp9(mut self, enabled: bool) -> Self {
353 self.codec_config.enable_vp9(enabled);
354 self
355 }
356
357 /// Enable AV1 video codec.
358 ///
359 /// Enabled by default.
360 pub fn enable_av1(mut self, enabled: bool) -> Self {
361 self.codec_config.enable_av1(enabled);
362 self
363 }
364
365 /// Configure the RTP extension mappings.
366 ///
367 /// The default extension map is
368 ///
369 /// ```
370 /// # use str0m::rtp::{Extension, ExtensionMap};
371 /// let exts = ExtensionMap::standard();
372 ///
373 /// assert_eq!(exts.id_of(Extension::AudioLevel), Some(1));
374 /// assert_eq!(exts.id_of(Extension::AbsoluteSendTime), Some(2));
375 /// assert_eq!(exts.id_of(Extension::TransportSequenceNumber), Some(3));
376 /// assert_eq!(exts.id_of(Extension::RtpMid), Some(4));
377 /// assert_eq!(exts.id_of(Extension::RtpStreamId), Some(10));
378 /// assert_eq!(exts.id_of(Extension::RepairedRtpStreamId), Some(11));
379 /// assert_eq!(exts.id_of(Extension::VideoOrientation), Some(13));
380 /// ```
381 pub fn extension_map(&mut self) -> &mut ExtensionMap {
382 &mut self.exts
383 }
384
385 /// Set the extension map replacing the existing.
386 pub fn set_extension_map(mut self, exts: ExtensionMap) -> Self {
387 self.exts = exts;
388 self
389 }
390
391 /// Clear out the standard extension mappings.
392 pub fn clear_extension_map(mut self) -> Self {
393 self.exts.clear();
394
395 self
396 }
397
398 /// Set an extension mapping on session level.
399 ///
400 /// The media level will be capped by the extension enabled on session level.
401 ///
402 /// The id must be 1-14 inclusive (1-indexed).
403 pub fn set_extension(mut self, id: u8, ext: Extension) -> Self {
404 self.exts.set(id, ext);
405 self
406 }
407
408 /// Set the interval between statistics events.
409 ///
410 /// None turns off the stats events.
411 ///
412 /// This includes [`MediaEgressStats`][crate::stats::MediaEgressStats],
413 /// [`MediaIngressStats`][crate::stats::MediaIngressStats]
414 pub fn set_stats_interval(mut self, interval: Option<Duration>) -> Self {
415 self.stats_interval = interval;
416 self
417 }
418
419 /// The configured statistics interval.
420 ///
421 /// None means statistics are disabled.
422 ///
423 /// ```
424 /// # use str0m::Rtc;
425 /// # use std::time::Duration;
426 /// let config = Rtc::builder();
427 ///
428 /// // Defaults to None.
429 /// assert_eq!(config.stats_interval(), None);
430 /// ```
431 pub fn stats_interval(&self) -> Option<Duration> {
432 self.stats_interval
433 }
434
435 /// Sets the interval between RTCP sender/receiver reports for audio streams.
436 ///
437 /// Defaults to 5 seconds.
438 ///
439 /// # Panics
440 ///
441 /// Panics if `interval` is zero.
442 pub fn set_rtcp_report_interval_audio(mut self, interval: Duration) -> Self {
443 assert!(!interval.is_zero());
444 self.intervals.audio = interval;
445 self
446 }
447
448 /// Returns the interval between RTCP sender/receiver reports for audio streams.
449 pub fn rtcp_report_interval_audio(&self) -> Duration {
450 self.intervals.audio
451 }
452
453 /// Sets the interval between RTCP sender/receiver reports for video streams.
454 ///
455 /// Defaults to 1 second.
456 ///
457 /// # Panics
458 ///
459 /// Panics if `interval` is zero.
460 pub fn set_rtcp_report_interval_video(mut self, interval: Duration) -> Self {
461 assert!(!interval.is_zero());
462 self.intervals.video = interval;
463 self
464 }
465
466 /// Returns the interval between RTCP sender/receiver reports for video streams.
467 pub fn rtcp_report_interval_video(&self) -> Duration {
468 self.intervals.video
469 }
470
471 /// Enables estimation of available bandwidth (BWE).
472 ///
473 /// None disables the BWE. This is an estimation of the send bandwidth, not receive.
474 ///
475 /// This includes setting the initial estimate to start with.
476 pub fn enable_bwe(mut self, initial_estimate: Option<Bitrate>) -> Self {
477 match initial_estimate {
478 Some(b) => {
479 let conf = self.bwe_config.get_or_insert(BweConfig::new(b));
480 conf.initial_bitrate = b;
481 }
482 None => {
483 self.bwe_config = None;
484 }
485 }
486
487 self
488 }
489
490 /// The initial bitrate as set by [`Self::enable_bwe()`].
491 ///
492 /// ```
493 /// # use str0m::Rtc;
494 /// let config = Rtc::builder();
495 ///
496 /// // Defaults to None - BWE off.
497 /// assert_eq!(config.bwe_initial_bitrate(), None);
498 /// ```
499 pub fn bwe_initial_bitrate(&self) -> Option<Bitrate> {
500 self.bwe_config.as_ref().map(|c| c.initial_bitrate)
501 }
502
503 /// Sets the number of packets held back for reordering audio packets.
504 ///
505 /// Str0m tries to deliver the frames in order. This number determines how many
506 /// packets to "wait" before releasing media
507 /// [`contiguous: false`][crate::media::MediaData::contiguous].
508 ///
509 /// This setting is ignored in [RTP mode][`RtcConfig::set_rtp_mode()`] where RTP
510 /// packets can arrive out of order.
511 pub fn set_reordering_size_audio(mut self, size: usize) -> Self {
512 self.reordering_size_audio = size;
513
514 self
515 }
516
517 /// Returns the setting for audio reordering size.
518 ///
519 /// ```
520 /// # use str0m::Rtc;
521 /// let config = Rtc::builder();
522 ///
523 /// // Defaults to 15.
524 /// assert_eq!(config.reordering_size_audio(), 15);
525 /// ```
526 ///
527 /// This setting is ignored in [RTP mode][`RtcConfig::set_rtp_mode()`] where RTP
528 /// packets can arrive out of order.
529 pub fn reordering_size_audio(&self) -> usize {
530 self.reordering_size_audio
531 }
532
533 /// Sets how long the oldest audio frame may wait to finish or for missing earlier packets.
534 ///
535 /// On expiry, an incomplete frame is dropped; a complete frame can move past a gap.
536 /// Later frames stay buffered and retain their own deadlines. The default is 1 second.
537 /// `None` disables this deadline and keeps count-based waiting only.
538 /// Applies to audio streams in frame mode, not RTP mode.
539 pub fn set_reordering_timeout_audio(mut self, timeout: Option<Duration>) -> Self {
540 self.reordering_timeout_audio = timeout;
541 self
542 }
543
544 /// Returns the configured audio reordering timeout.
545 pub fn reordering_timeout_audio(&self) -> Option<Duration> {
546 self.reordering_timeout_audio
547 }
548
549 /// Sets the number of packets held back for reordering video packets.
550 ///
551 /// Str0m tries to deliver the frames in order. This number determines how many
552 /// packets to "wait" before releasing media with gaps.
553 ///
554 /// This must be at least as big as the number of packets the biggest keyframe
555 /// can be split over.
556 ///
557 /// WARNING: video is very different to audio. Setting this value too low will result in
558 /// missing video data. The 0 (as described for audio) is not relevant for video.
559 ///
560 /// Video recovery waits for a complete successor and missing packets' NACK attempts
561 /// plus three RTTs. When NACK timing is unavailable, it waits three RTTs from the
562 /// complete candidate's earliest receipt instead (100 ms RTT until measured).
563 /// An incomplete frame without a complete successor has no age deadline.
564 ///
565 /// Default: 30
566 ///
567 /// This setting is ignored in [RTP mode][`RtcConfig::set_rtp_mode()`] where RTP
568 /// packets can arrive out of order.
569 pub fn set_reordering_size_video(mut self, size: usize) -> Self {
570 self.reordering_size_video = size;
571
572 self
573 }
574
575 /// Returns the setting for video reordering size.
576 ///
577 /// ```
578 /// # use str0m::Rtc;
579 /// let config = Rtc::builder();
580 ///
581 /// // Defaults to 30.
582 /// assert_eq!(config.reordering_size_video(), 30);
583 /// ```
584 ///
585 /// This setting is ignored in [RTP mode][`RtcConfig::set_rtp_mode()`] where RTP
586 /// packets can arrive out of order.
587 pub fn reordering_size_video(&self) -> usize {
588 self.reordering_size_video
589 }
590
591 /// Sets how long an incoming stream may receive no packets before it is reported paused.
592 /// Defaults to 1.5 seconds and applies to all incoming streams created by this `Rtc`.
593 pub fn set_pause_threshold(mut self, threshold: Duration) -> Self {
594 self.pause_threshold = threshold;
595 self
596 }
597
598 /// Returns the incoming stream pause threshold.
599 pub fn pause_threshold(&self) -> Duration {
600 self.pause_threshold
601 }
602
603 /// Sets the buffer size for outgoing audio packets.
604 ///
605 /// This must be larger than 0. The value configures an internal ring buffer used as a temporary
606 /// holding space between calling [`Writer::write`][crate::media::Writer::write()] and
607 /// [`Rtc::poll_output`].
608 ///
609 /// For audio one call to `write()` typically results in one RTP packet since the entire
610 /// payload fits in one. If you can guarantee that every `write()` is a single RTP packet,
611 /// and is always followed by a `poll_output()`, it might be possible to set this value to 1.
612 /// But that would give no margins for unexpected patterns.
613 ///
614 /// panics if set to 0.
615 pub fn set_send_buffer_audio(mut self, size: usize) -> Self {
616 assert!(size > 0);
617 self.send_buffer_audio = size;
618 self
619 }
620
621 /// Returns the setting for audio resend size.
622 ///
623 /// ```
624 /// # use str0m::Rtc;
625 /// let config = Rtc::builder();
626 ///
627 /// // Defaults to 50.
628 /// assert_eq!(config.send_buffer_audio(), 50);
629 /// ```
630 pub fn send_buffer_audio(&self) -> usize {
631 self.send_buffer_audio
632 }
633
634 /// Sets the buffer size for outgoing video packets and resends.
635 ///
636 /// This must be larger than 0. The value configures an internal ring buffer that is both
637 /// used as a temporary holding space between calling
638 /// [`Writer::write`][crate::media::Writer::write()] and [`Rtc::poll_output`] as well as for
639 /// fulfilling resends.
640 ///
641 /// For video, this buffer is used for more than for audio. First, a call to `write()` often
642 /// results in multiple RTP packets since large frames don't fit in one payload. That means
643 /// the buffer must be at least as large to hold all those packets. Second, when the remote
644 /// requests resends (NACK), those are fulfilled from this buffer. Third, for Bandwidth
645 /// Estimation (BWE), when probing for available bandwidth, packets from this buffer are used
646 /// to do "spurious resends", i.e. we do resends for packets that were not asked for.
647 pub fn set_send_buffer_video(mut self, size: usize) -> Self {
648 self.send_buffer_video = size;
649 self
650 }
651
652 /// Returns the setting for video resend size.
653 ///
654 /// ```
655 /// # use str0m::Rtc;
656 /// let config = Rtc::builder();
657 ///
658 /// // Defaults to 1000.
659 /// assert_eq!(config.send_buffer_video(), 1000);
660 /// ```
661 pub fn send_buffer_video(&self) -> usize {
662 self.send_buffer_video
663 }
664
665 /// Sets how many bytes the data channels can buffer for sending, summed over all channels.
666 ///
667 /// [`Channel::write()`][crate::channel::Channel::write()] does not accept a message (returns
668 /// `false`) that would take the total [buffered amount][crate::channel::Channel::buffered_amount()]
669 /// above this limit. A message larger than the limit is never accepted.
670 ///
671 /// Written data counts as buffered until the remote peer acknowledges it, including after it
672 /// has been sent. The limit therefore also caps the data in flight, and with it the data
673 /// channel throughput at about this many bytes per round trip. The SCTP congestion window
674 /// and the remote peer's advertised receive window can limit the data in flight further.
675 ///
676 /// Raising the limit helps a sender whose data rate times the round trip time exceeds it.
677 /// Beyond what the network path holds, a higher limit only adds queueing delay, and accepted
678 /// data is kept in memory until it is acknowledged.
679 ///
680 /// Defaults to 128 KiB.
681 pub fn set_sctp_max_buffered_amount(mut self, bytes: usize) -> Self {
682 self.sctp_max_buffered_amount = bytes;
683 self
684 }
685
686 /// Returns how many bytes the data channels can buffer for sending.
687 ///
688 /// ```
689 /// # use str0m::Rtc;
690 /// let config = Rtc::builder();
691 ///
692 /// // Defaults to 128 KiB.
693 /// assert_eq!(config.sctp_max_buffered_amount(), 128 * 1024);
694 /// ```
695 pub fn sctp_max_buffered_amount(&self) -> usize {
696 self.sctp_max_buffered_amount
697 }
698
699 /// Sets the maximum data channel message size this peer can receive, in bytes.
700 ///
701 /// This limit is advertised in SDP as `a=max-message-size` and applied to SCTP,
702 /// including when using the direct API or SNAP. It does not change the remote
703 /// peer's receive limit or the local send buffer limit.
704 ///
705 /// The SCTP receive storage budget is at least 1 MiB and large enough to
706 /// reassemble one message at this limit. Storage is allocated as data arrives.
707 ///
708 /// A value of 0 advertises unlimited message size, subject to local capacity.
709 /// Internally, both the message limit and receive storage budget are `u32::MAX`.
710 ///
711 /// Defaults to 256 KiB.
712 pub fn set_sctp_max_message_size(mut self, bytes: u32) -> Self {
713 self.sctp_max_message_size = bytes;
714 self
715 }
716
717 /// Returns the maximum data channel message size this peer can receive, in bytes.
718 ///
719 /// ```
720 /// # use str0m::RtcConfig;
721 /// let config = RtcConfig::new().set_sctp_max_message_size(512 * 1024);
722 /// assert_eq!(config.sctp_max_message_size(), 512 * 1024);
723 /// ```
724 pub fn sctp_max_message_size(&self) -> u32 {
725 self.sctp_max_message_size
726 }
727
728 /// Make the entire Rtc be in RTP mode.
729 ///
730 /// This means all media, read from [`RtpPacket`][crate::rtp::RtpPacket] and written to
731 /// [`StreamTx::write_rtp`][crate::rtp::StreamTx::write_rtp] are RTP packetized.
732 /// It bypasses all internal packetization/depacketization inside str0m.
733 ///
734 /// WARNING: This is a low level API and is not str0m's primary use case.
735 pub fn set_rtp_mode(mut self, enabled: bool) -> Self {
736 self.rtp_mode = enabled;
737
738 self
739 }
740
741 /// Checks if RTP mode is set.
742 ///
743 /// ```
744 /// # use str0m::Rtc;
745 /// let config = Rtc::builder();
746 ///
747 /// // Defaults to false.
748 /// assert_eq!(config.rtp_mode(), false);
749 /// ```
750 pub fn rtp_mode(&self) -> bool {
751 self.rtp_mode
752 }
753
754 /// Enable the [`Event::RawPacket`][crate::Event::RawPacket] event.
755 ///
756 /// This clones data, and is therefore expensive.
757 /// Should not be enabled outside of tests and troubleshooting.
758 pub fn enable_raw_packets(mut self, enabled: bool) -> Self {
759 self.enable_raw_packets = enabled;
760 self
761 }
762
763 /// Enable SNAP (SCTP Negotiation Acceleration Protocol).
764 ///
765 /// When enabled, the `a=sctp-init` attribute is included in outgoing SDP
766 /// offers, allowing the SCTP association to skip the 4-way handshake
767 /// and go directly to established state. This saves up to two network
768 /// round-trip times when establishing data channels.
769 ///
770 /// If the remote answer does not accept SNAP, str0m logs a warning and
771 /// falls back to the regular SCTP handshake.
772 ///
773 /// When this is `false`, outgoing SDP offers will not include `a=sctp-init`.
774 /// However, incoming offers that contain `a=sctp-init` will still be
775 /// reciprocated in answers, since str0m always supports the extension at
776 /// the protocol level (per §5.4 of draft-hancke-tsvwg-snap).
777 ///
778 /// See [draft-hancke-tsvwg-snap](https://datatracker.ietf.org/doc/draft-hancke-tsvwg-snap/).
779 ///
780 /// Default: `false`
781 pub fn set_snap_enabled(mut self, enabled: bool) -> Self {
782 self.snap_enabled = enabled;
783 self
784 }
785
786 /// Set which DTLS version to use.
787 ///
788 /// Defaults to [`DtlsVersion::Dtls12`].
789 pub fn set_dtls_version(mut self, version: DtlsVersion) -> Self {
790 self.dtls_version = version;
791 self
792 }
793
794 /// Get the configured DTLS version.
795 pub fn dtls_version(&self) -> DtlsVersion {
796 self.dtls_version
797 }
798
799 /// Set the MTU as a `target..=warn` inclusive range.
800 ///
801 /// * `*range.start()` is the **target** MTU: the size str0m aims for when
802 /// fragmenting outgoing packets. Must be within
803 /// `[DATAGRAM_MTU_TARGET_MIN, DATAGRAM_MTU_TARGET_MAX]`.
804 /// * `*range.end()` is the **warn** threshold: packets whose length
805 /// exceeds the target trigger a warning.
806 ///
807 /// Set as `target..=target` to warn packets bigger than target.
808 /// Set as `target..=usize::MAX` to disable warning.
809 ///
810 /// Defaults to `DATAGRAM_MTU_TARGET..=DATAGRAM_MTU_WARN`.
811 pub fn set_mtu(mut self, range: RangeInclusive<usize>) -> Self {
812 let (start, end) = (*range.start(), *range.end());
813 assert!(
814 DATAGRAM_MTU_TARGET_MIN <= start && start <= DATAGRAM_MTU_TARGET_MAX,
815 "mtu target {} out of bounds [{}, {}]",
816 start,
817 DATAGRAM_MTU_TARGET_MIN,
818 DATAGRAM_MTU_TARGET_MAX,
819 );
820 assert!(
821 start <= end,
822 "mtu range start must be <= end, got {}..={}",
823 start,
824 end,
825 );
826 self.mtu = range;
827 self
828 }
829
830 /// Get the configured target MTU (the value str0m aims for).
831 pub fn mtu(&self) -> usize {
832 *self.mtu.start()
833 }
834
835 /// Get the configured warn threshold above which outgoing packets
836 /// trigger a warning trace.
837 pub fn mtu_warn(&self) -> usize {
838 *self.mtu.end()
839 }
840
841 /// Set the VP9 packetizer mode.
842 ///
843 /// VP9 supports two RTP payload descriptor formats:
844 ///
845 /// * [`Vp9PacketizerMode::NonFlexible`] (default) — 5-6 byte header with layer indices
846 /// and scalability structure. Compatible with all major browsers including Safari.
847 /// * [`Vp9PacketizerMode::Flexible`] — minimal 3-byte header. Simpler but may cause
848 /// issues with Safari which drops inter-frames.
849 pub fn set_vp9_packetizer_mode(mut self, mode: Vp9PacketizerMode) -> Self {
850 self.vp9_packetizer_mode = mode;
851 self
852 }
853
854 /// Returns the configured VP9 packetizer mode.
855 ///
856 /// ```
857 /// # use str0m::Rtc;
858 /// # use str0m::format::Vp9PacketizerMode;
859 /// let config = Rtc::builder();
860 ///
861 /// // Defaults to NonFlexible.
862 /// assert_eq!(config.vp9_packetizer_mode(), Vp9PacketizerMode::NonFlexible);
863 /// ```
864 pub fn vp9_packetizer_mode(&self) -> Vp9PacketizerMode {
865 self.vp9_packetizer_mode
866 }
867
868 /// Create a [`Rtc`] from the configuration.
869 pub fn build(self, start: Instant) -> Rtc {
870 Rtc::new_from_config(self, start).expect("Failed to create Rtc from config")
871 }
872}
873
874impl BweConfig {
875 fn new(initial_bitrate: Bitrate) -> Self {
876 Self { initial_bitrate }
877 }
878}
879
880impl Default for RtcConfig {
881 fn default() -> Self {
882 Self {
883 local_ice_credentials: None,
884 crypto_provider: None,
885 dtls_cert: None,
886 fingerprint_verification: true,
887 ice_lite: false,
888 initial_stun_rto: None,
889 max_stun_rto: None,
890 max_stun_retransmits: None,
891 codec_config: CodecConfig::new_with_defaults(),
892 exts: ExtensionMap::standard(),
893 stats_interval: None,
894 intervals: RtcpReportIntervals {
895 audio: Duration::from_secs(5),
896 video: Duration::from_secs(1),
897 },
898 bwe_config: None,
899 reordering_size_audio: 15,
900 reordering_size_video: 30,
901 reordering_timeout_audio: Some(Duration::from_secs(1)),
902 pause_threshold: Duration::from_millis(1500),
903 send_buffer_audio: 50,
904 send_buffer_video: 1000,
905 sctp_max_buffered_amount: crate::sctp::DEFAULT_MAX_BUFFERED_AMOUNT,
906 sctp_max_message_size: crate::sctp::LOCAL_MAX_MESSAGE_SIZE,
907 rtp_mode: false,
908 enable_raw_packets: false,
909 dtls_version: DtlsVersion::Dtls12,
910 vp9_packetizer_mode: Vp9PacketizerMode::default(),
911 snap_enabled: false,
912 mtu: DATAGRAM_MTU_TARGET..=DATAGRAM_MTU_WARN,
913 }
914 }
915}
916
917#[cfg(test)]
918mod tests {
919 use super::*;
920
921 #[test]
922 fn sctp_max_message_size_round_trips() {
923 assert_eq!(
924 RtcConfig::default().sctp_max_message_size(),
925 crate::sctp::LOCAL_MAX_MESSAGE_SIZE
926 );
927 for bytes in [0, 32 * 1024, 512 * 1024, u32::MAX] {
928 let config = RtcConfig::new().set_sctp_max_message_size(bytes);
929 assert_eq!(config.clone().sctp_max_message_size(), bytes);
930 }
931 }
932
933 #[test]
934 fn enable_comfort_noise_updates_codec_config() {
935 let mut cfg = RtcConfig::default().enable_comfort_noise(true);
936
937 assert!(
938 cfg.codec_config()
939 .params()
940 .iter()
941 .any(|p| p.spec().codec == crate::format::Codec::CN)
942 );
943 }
944
945 #[test]
946 fn default_mtu_is_datagram_mtu_target() {
947 let cfg = RtcConfig::default();
948 assert_eq!(cfg.mtu(), DATAGRAM_MTU_TARGET);
949 assert_eq!(cfg.mtu_warn(), DATAGRAM_MTU_WARN);
950 }
951
952 #[test]
953 fn set_mtu_round_trips() {
954 let cfg = RtcConfig::default().set_mtu(900..=1400);
955 assert_eq!(cfg.mtu(), 900);
956 assert_eq!(cfg.mtu_warn(), 1400);
957
958 let cfg = RtcConfig::default().set_mtu(900..=usize::MAX);
959 assert_eq!(cfg.mtu(), 900);
960 assert_eq!(cfg.mtu_warn(), usize::MAX);
961 }
962
963 #[test]
964 fn set_mtu_accepts_equal_bounds() {
965 let cfg = RtcConfig::default().set_mtu(1200..=1200);
966 assert_eq!(cfg.mtu(), 1200);
967 assert_eq!(cfg.mtu_warn(), 1200);
968
969 let cfg = RtcConfig::default().set_mtu(DATAGRAM_MTU_TARGET_MIN..=DATAGRAM_MTU_TARGET_MIN);
970 assert_eq!(cfg.mtu(), DATAGRAM_MTU_TARGET_MIN);
971
972 let cfg = RtcConfig::default().set_mtu(DATAGRAM_MTU_TARGET_MAX..=DATAGRAM_MTU_TARGET_MAX);
973 assert_eq!(cfg.mtu(), DATAGRAM_MTU_TARGET_MAX);
974 }
975
976 #[test]
977 #[should_panic(expected = "mtu target")]
978 fn set_mtu_panics_on_target_below_min() {
979 let _ = RtcConfig::default().set_mtu((DATAGRAM_MTU_TARGET_MIN - 1)..=usize::MAX);
980 }
981
982 #[test]
983 #[should_panic(expected = "mtu target")]
984 fn set_mtu_panics_on_target_above_max() {
985 let _ = RtcConfig::default().set_mtu((DATAGRAM_MTU_TARGET_MAX + 1)..=usize::MAX);
986 }
987
988 #[test]
989 #[should_panic(expected = "mtu range start must be <= end")]
990 fn set_mtu_panics_on_inverted_range() {
991 let _ = RtcConfig::default().set_mtu(RangeInclusive::new(1300, 1299));
992 }
993}