libwebrtc 0.4.1

Livekit safe bindings to libwebrtc
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
// Copyright 2025 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt::Debug;

use crate::{
    imp::peer_connection_factory as imp_pcf, peer_connection::PeerConnection,
    rtp_parameters::RtpCapabilities, rtp_sender::VideoEncoderBackend, video_codec::VideoCodec,
    MediaType, RtcError,
};

#[derive(Debug, Clone)]
pub struct IceServer {
    pub urls: Vec<String>,
    pub username: String,
    pub password: String,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ContinualGatheringPolicy {
    GatherOnce,
    GatherContinually,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum IceTransportsType {
    Relay,
    NoHost,
    All,
}

/// Configuration for a [`PeerConnection`].
///
/// This type is `#[non_exhaustive]`: construct it from [`RtcConfiguration::default`]
/// and set the fields you need, e.g.
/// ```
/// # use libwebrtc::peer_connection_factory::{IceTransportsType, RtcConfiguration};
/// let mut cfg = RtcConfiguration::default();
/// cfg.ice_transport_type = IceTransportsType::Relay;
/// ```
/// New fields may be added in future releases without a breaking change.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct RtcConfiguration {
    pub ice_servers: Vec<IceServer>,
    pub continual_gathering_policy: ContinualGatheringPolicy,
    pub ice_transport_type: IceTransportsType,
    /// WARP: enable SNAP (SCTP-INIT-in-SDP). Maps to the immutable
    /// `enable_sctp_snap` RTCConfiguration field, so it must be set the same at
    /// PeerConnection creation and every set_configuration.
    pub enable_sctp_snap: bool,
}

impl Default for RtcConfiguration {
    fn default() -> Self {
        Self {
            ice_servers: vec![],
            continual_gathering_policy: ContinualGatheringPolicy::GatherContinually,
            ice_transport_type: IceTransportsType::All,
            enable_sctp_snap: false,
        }
    }
}

#[derive(Clone, Default)]
pub struct PeerConnectionFactory {
    pub(crate) handle: imp_pcf::PeerConnectionFactory,
}

impl Debug for PeerConnectionFactory {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("PeerConnectionFactory").finish()
    }
}

impl PeerConnectionFactory {
    /// Creates a native peer connection factory that renders received video as soon as possible.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn with_zero_playout_delay() -> Self {
        Self { handle: imp_pcf::PeerConnectionFactory::with_zero_playout_delay() }
    }

    /// Creates a native peer connection factory with the given runtime options.
    /// `zero_playout_delay` and `enable_warp` (SPED + SNAP) are independent and
    /// may be combined.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn with_options(zero_playout_delay: bool, enable_warp: bool) -> Self {
        Self {
            handle: imp_pcf::PeerConnectionFactory::with_options(zero_playout_delay, enable_warp),
        }
    }

    pub fn create_peer_connection(
        &self,
        config: RtcConfiguration,
    ) -> Result<PeerConnection, RtcError> {
        self.handle.create_peer_connection(config)
    }

    pub fn get_rtp_sender_capabilities(&self, media_type: MediaType) -> RtpCapabilities {
        self.handle.get_rtp_sender_capabilities(media_type)
    }

    pub fn get_rtp_receiver_capabilities(&self, media_type: MediaType) -> RtpCapabilities {
        self.handle.get_rtp_receiver_capabilities(media_type)
    }

    /// Video codecs advertised by this factory's encoders for `backend`.
    ///
    /// For [`VideoEncoderBackend::Auto`] this is every codec advertised by this
    /// factory's software and hardware encoders, excluding the pre-encoded
    /// pass-through backend. These encoders also provide the fallback when a
    /// sender's requested backend is unavailable. For
    /// [`VideoEncoderBackend::PreEncoded`] it is every codec the pass-through can
    /// forward, whether or not a local encoder exists for it.
    /// Native codec names not recognized by [`VideoCodec`] are omitted.
    ///
    /// ```
    /// use libwebrtc::{peer_connection_factory::PeerConnectionFactory, rtp_sender::VideoEncoderBackend};
    /// use libwebrtc::video_codec::VideoCodec;
    ///
    /// let factory = PeerConnectionFactory::default();
    /// let codecs = factory.video_encoder_codecs(VideoEncoderBackend::Software);
    /// assert!(codecs.contains(&VideoCodec::VP8));
    /// ```
    pub fn video_encoder_codecs(&self, backend: VideoEncoderBackend) -> Vec<VideoCodec> {
        self.handle
            .video_encoder_codecs(backend)
            .into_iter()
            .filter_map(|name| match name.parse::<VideoCodec>() {
                Ok(codec) => Some(codec),
                Err(_) => {
                    log::warn!("ignoring unrecognized video encoder codec {name}");
                    None
                }
            })
            .collect()
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::{PeerConnectionFactory, VideoCodec};
    use crate::rtp_sender::VideoEncoderBackend;

    #[test]
    fn pre_encoded_backend_forwards_every_codec_on_every_host() {
        // Pre-encoded publishing must not depend on a real encoder existing
        // for the codec, so the pass-through set is the same on every host.
        let codecs =
            PeerConnectionFactory::default().video_encoder_codecs(VideoEncoderBackend::PreEncoded);
        for codec in
            [VideoCodec::VP8, VideoCodec::VP9, VideoCodec::AV1, VideoCodec::H264, VideoCodec::H265]
        {
            assert!(codecs.contains(&codec), "pass-through is missing {codec:?}: {codecs:?}");
        }
    }

    #[test]
    fn software_backend_has_no_h265_encoder() {
        // libvpx/libaom/OpenH264 never produce H265; the software set is
        // what a normal session falls back to when no hardware encoder exists.
        let codecs =
            PeerConnectionFactory::default().video_encoder_codecs(VideoEncoderBackend::Software);
        assert!(codecs.contains(&VideoCodec::VP8), "{codecs:?}");
        assert!(!codecs.contains(&VideoCodec::H265), "{codecs:?}");
    }

    #[test]
    fn auto_backend_is_a_superset_of_software() {
        let factory = PeerConnectionFactory::default();
        let auto = factory.video_encoder_codecs(VideoEncoderBackend::Auto);
        let software = factory.video_encoder_codecs(VideoEncoderBackend::Software);
        for codec in &software {
            assert!(auto.contains(codec), "auto is missing {codec:?}: {auto:?}");
        }
    }

    #[test]
    fn video_encoder_codecs_are_released_with_their_factory() {
        // The codec query borrows the encoder factory the peer connection
        // factory owns, so repeated create/query/drop must fully tear the
        // native factory down each time instead of retaining encoders.
        for _ in 0..3 {
            let factory = PeerConnectionFactory::default();
            assert!(factory
                .video_encoder_codecs(VideoEncoderBackend::Auto)
                .contains(&VideoCodec::VP8));
            let native = factory.handle.sys_handle.downgrade();
            drop(factory);
            assert!(native.upgrade().is_null(), "peer connection factory outlived its owner");
        }
    }

    #[test]
    fn zero_playout_delay_factory_uses_force_playout_delay_field_trial() {
        let default_factory = PeerConnectionFactory::default();
        assert!(!default_factory.handle.zero_playout_delay_enabled());
        drop(default_factory);

        let low_latency_factory = PeerConnectionFactory::with_zero_playout_delay();
        assert!(low_latency_factory.handle.zero_playout_delay_enabled());
    }
}

pub mod native {
    use super::PeerConnectionFactory;
    use crate::{
        audio_source::native::NativeAudioSource, audio_track::RtcAudioTrack,
        video_source::native::NativeVideoSource, video_track::RtcVideoTrack,
    };

    pub trait PeerConnectionFactoryExt {
        fn create_video_track(&self, label: &str, source: NativeVideoSource) -> RtcVideoTrack;
        fn create_audio_track(&self, label: &str, source: NativeAudioSource) -> RtcAudioTrack;

        /// Create an audio track that uses the Platform ADM for capture.
        /// The track will capture audio from the selected recording device.
        fn create_device_audio_track(&self, label: &str) -> RtcAudioTrack;

        // Device enumeration
        fn playout_devices(&self) -> i16;
        fn recording_devices(&self) -> i16;
        fn playout_device_name(&self, index: u16) -> String;
        fn recording_device_name(&self, index: u16) -> String;
        /// Get device GUID (platform-specific unique identifier, stable across hot-plug)
        fn playout_device_guid(&self, index: u16) -> String;
        fn recording_device_guid(&self, index: u16) -> String;

        // Device selection by index
        fn set_playout_device(&self, index: u16) -> bool;
        fn set_recording_device(&self, index: u16) -> bool;
        /// Device selection by GUID (preferred - stable across device changes)
        fn set_playout_device_by_guid(&self, guid: &str) -> bool;
        fn set_recording_device_by_guid(&self, guid: &str) -> bool;

        // Recording control (for device switching while active)
        fn stop_recording(&self) -> bool;
        fn init_recording(&self) -> bool;
        fn start_recording(&self) -> bool;
        fn recording_is_initialized(&self) -> bool;

        // Playout control (for device switching while active)
        fn stop_playout(&self) -> bool;
        fn init_playout(&self) -> bool;
        fn start_playout(&self) -> bool;
        fn playout_is_initialized(&self) -> bool;

        // Built-in audio processing (hardware AEC/AGC/NS)
        // Only available on iOS and some Android devices
        fn builtin_aec_is_available(&self) -> bool;
        fn builtin_agc_is_available(&self) -> bool;
        fn builtin_ns_is_available(&self) -> bool;
        fn enable_builtin_aec(&self, enable: bool) -> bool;
        fn enable_builtin_agc(&self, enable: bool) -> bool;
        fn enable_builtin_ns(&self, enable: bool) -> bool;

        // ADM recording control
        // Use this to disable microphone when only using NativeAudioSource
        fn set_adm_recording_enabled(&self, enabled: bool);
        fn adm_recording_enabled(&self) -> bool;

        // ADM playout control
        // When disabled (default), playout uses synthetic mode - remote audio is
        // delivered via FFI callbacks. When enabled, plays through platform speakers.
        fn set_adm_playout_enabled(&self, enabled: bool);
        fn adm_playout_enabled(&self) -> bool;

        // Platform ADM lifecycle management
        // Call acquire_platform_adm when creating PlatformAudio.
        // Call release_platform_adm when disposing PlatformAudio.
        // The Platform ADM is only created when first acquired, and terminated
        // when the last reference is released.
        fn acquire_platform_adm(&self) -> bool;
        fn release_platform_adm(&self);
        fn platform_adm_ref_count(&self) -> i32;
        fn is_platform_adm_active(&self) -> bool;
    }

    impl PeerConnectionFactoryExt for PeerConnectionFactory {
        fn create_video_track(&self, label: &str, source: NativeVideoSource) -> RtcVideoTrack {
            self.handle.create_video_track(label, source)
        }

        fn create_audio_track(&self, label: &str, source: NativeAudioSource) -> RtcAudioTrack {
            self.handle.create_audio_track(label, source)
        }

        fn create_device_audio_track(&self, label: &str) -> RtcAudioTrack {
            self.handle.create_device_audio_track(label)
        }

        fn playout_devices(&self) -> i16 {
            self.handle.playout_devices()
        }

        fn recording_devices(&self) -> i16 {
            self.handle.recording_devices()
        }

        fn playout_device_name(&self, index: u16) -> String {
            self.handle.playout_device_name(index)
        }

        fn recording_device_name(&self, index: u16) -> String {
            self.handle.recording_device_name(index)
        }

        fn playout_device_guid(&self, index: u16) -> String {
            self.handle.playout_device_guid(index)
        }

        fn recording_device_guid(&self, index: u16) -> String {
            self.handle.recording_device_guid(index)
        }

        fn set_playout_device(&self, index: u16) -> bool {
            self.handle.set_playout_device(index)
        }

        fn set_recording_device(&self, index: u16) -> bool {
            self.handle.set_recording_device(index)
        }

        fn set_playout_device_by_guid(&self, guid: &str) -> bool {
            self.handle.set_playout_device_by_guid(guid)
        }

        fn set_recording_device_by_guid(&self, guid: &str) -> bool {
            self.handle.set_recording_device_by_guid(guid)
        }

        fn stop_recording(&self) -> bool {
            self.handle.stop_recording()
        }

        fn init_recording(&self) -> bool {
            self.handle.init_recording()
        }

        fn start_recording(&self) -> bool {
            self.handle.start_recording()
        }

        fn recording_is_initialized(&self) -> bool {
            self.handle.recording_is_initialized()
        }

        fn stop_playout(&self) -> bool {
            self.handle.stop_playout()
        }

        fn init_playout(&self) -> bool {
            self.handle.init_playout()
        }

        fn start_playout(&self) -> bool {
            self.handle.start_playout()
        }

        fn playout_is_initialized(&self) -> bool {
            self.handle.playout_is_initialized()
        }

        fn builtin_aec_is_available(&self) -> bool {
            self.handle.builtin_aec_is_available()
        }

        fn builtin_agc_is_available(&self) -> bool {
            self.handle.builtin_agc_is_available()
        }

        fn builtin_ns_is_available(&self) -> bool {
            self.handle.builtin_ns_is_available()
        }

        fn enable_builtin_aec(&self, enable: bool) -> bool {
            self.handle.enable_builtin_aec(enable)
        }

        fn enable_builtin_agc(&self, enable: bool) -> bool {
            self.handle.enable_builtin_agc(enable)
        }

        fn enable_builtin_ns(&self, enable: bool) -> bool {
            self.handle.enable_builtin_ns(enable)
        }

        fn set_adm_recording_enabled(&self, enabled: bool) {
            self.handle.set_adm_recording_enabled(enabled)
        }

        fn adm_recording_enabled(&self) -> bool {
            self.handle.adm_recording_enabled()
        }

        fn set_adm_playout_enabled(&self, enabled: bool) {
            self.handle.set_adm_playout_enabled(enabled)
        }

        fn adm_playout_enabled(&self) -> bool {
            self.handle.adm_playout_enabled()
        }

        fn acquire_platform_adm(&self) -> bool {
            self.handle.acquire_platform_adm()
        }

        fn release_platform_adm(&self) {
            self.handle.release_platform_adm()
        }

        fn platform_adm_ref_count(&self) -> i32 {
            self.handle.platform_adm_ref_count()
        }

        fn is_platform_adm_active(&self) -> bool {
            self.handle.is_platform_adm_active()
        }
    }
}