BlueGit

ict rusty-teams

feat(call): speaking frame and speaker to the front from the RTP sources

- like Teams web getContributingSources: the meeting mixer lists who it mixes in as CSRCs, mapped to people by their audio sourceId; a direct call uses the peer's audio level
- polled every 200 ms with the stats; the Trouter csrcInfo callback never arrived
- vendored libwebrtc 0.3.51 and webrtc-sys gain RtpReceiver::sources (GetSources)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-11 · 2 weeks ago

Hash
dc7f29feafc3a575dba7cc54b599489f231bff84
Parent
8a68a986
66 files changed +11779 −0
Cargo.toml +1 −0
@@ -48,6 +48,7 @@ webview = { path = "crates/webview" }
48 48 gpui-base = { path = "vendor/gpui-base" }
49 49 gpui-component = { path = "vendor/gpui-component" }
50 50 webrtc-sys = { path = "vendor/webrtc-sys" }
51 libwebrtc = { path = "vendor/libwebrtc" }
51 52
52 53 [profile.dev]
53 54 debug = "line-tables-only"
@@ -48,6 +48,7 @@ webview = { path = "crates/webview" }
48gpui-base = { path = "vendor/gpui-base" }
48gpui-base = { path = "vendor/gpui-base" }
49gpui-component = { path = "vendor/gpui-component" }
49gpui-component = { path = "vendor/gpui-component" }
50webrtc-sys = { path = "vendor/webrtc-sys" }
50webrtc-sys = { path = "vendor/webrtc-sys" }
51libwebrtc = { path = "vendor/libwebrtc" }
51
52
52[profile.dev]
53[profile.dev]
53debug = "line-tables-only"
54debug = "line-tables-only"
crates/calling/src/active_speakers.rs added +72 −0
@@ -0,0 +1,72 @@
1 use libwebrtc::peer_connection::PeerConnection;
2 use libwebrtc::prelude::MediaStreamTrack;
3 use libwebrtc::rtp_receiver::RtpSource;
4
5 /// How long after its last packet a contributing source still counts as speaking.
6 const RECENT_MS: i64 = 400;
7 /// Audio level in -dBov at or below which a source counts as speaking (0 loudest, 127 silence).
8 const SPEAKING_LEVEL: u8 = 60;
9
10 pub fn audio_sources(peer: &PeerConnection) -> Vec<RtpSource> {
11 peer.receivers()
12 .into_iter()
13 .filter(|receiver| matches!(receiver.track(), Some(MediaStreamTrack::Audio(_))))
14 .flat_map(|receiver| receiver.sources())
15 .collect()
16 }
17
18 /// The source ids that are speaking now, like Teams web's `getContributingSources()` reading of the mixed meeting audio.
19 /// A mixer lists the people it mixes in as CSRCs; a direct call has only the peer's SSRC with its level.
20 pub fn speaking_sources(sources: &[RtpSource]) -> Vec<u32> {
21 let Some(newest) = sources.iter().map(|source| source.timestamp_ms).max() else {
22 return Vec::new();
23 };
24 let has_contributors = sources.iter().any(|source| source.contributing);
25 let mut speaking: Vec<u32> = sources
26 .iter()
27 .filter(|source| source.contributing == has_contributors)
28 .filter(|source| newest - source.timestamp_ms <= RECENT_MS)
29 .filter(|source| match source.audio_level {
30 Some(level) => level <= SPEAKING_LEVEL,
31 None => source.contributing,
32 })
33 .map(|source| source.source_id)
34 .collect();
35 speaking.sort_unstable();
36 speaking.dedup();
37 speaking
38 }
39
40 #[cfg(test)]
41 mod tests {
42 use super::*;
43
44 fn source(source_id: u32, contributing: bool, audio_level: Option<u8>, timestamp_ms: i64) -> RtpSource {
45 RtpSource { source_id, contributing, audio_level, timestamp_ms }
46 }
47
48 #[test]
49 fn mixer_contributors_seen_just_now_are_speaking() {
50 let sources = [
51 source(900, false, Some(30), 10_000),
52 source(7, true, None, 9_900),
53 source(8, true, Some(40), 10_000),
54 source(9, true, None, 9_000),
55 ];
56 assert_eq!(speaking_sources(&sources), vec![7, 8]);
57 }
58
59 #[test]
60 fn a_quiet_contributor_is_not_speaking() {
61 let sources = [source(900, false, Some(30), 10_000), source(8, true, Some(100), 10_000)];
62 assert!(speaking_sources(&sources).is_empty());
63 }
64
65 #[test]
66 fn a_direct_call_uses_the_peer_level() {
67 assert_eq!(speaking_sources(&[source(42, false, Some(35), 5_000)]), vec![42]);
68 assert!(speaking_sources(&[source(42, false, Some(127), 5_000)]).is_empty());
69 assert!(speaking_sources(&[source(42, false, None, 5_000)]).is_empty());
70 assert!(speaking_sources(&[]).is_empty());
71 }
72 }
@@ -0,0 +1,72 @@
1use libwebrtc::peer_connection::PeerConnection;
2use libwebrtc::prelude::MediaStreamTrack;
3use libwebrtc::rtp_receiver::RtpSource;
4
5/// How long after its last packet a contributing source still counts as speaking.
6const RECENT_MS: i64 = 400;
7/// Audio level in -dBov at or below which a source counts as speaking (0 loudest, 127 silence).
8const SPEAKING_LEVEL: u8 = 60;
9
10pub fn audio_sources(peer: &PeerConnection) -> Vec<RtpSource> {
11 peer.receivers()
12 .into_iter()
13 .filter(|receiver| matches!(receiver.track(), Some(MediaStreamTrack::Audio(_))))
14 .flat_map(|receiver| receiver.sources())
15 .collect()
16}
17
18/// The source ids that are speaking now, like Teams web's `getContributingSources()` reading of the mixed meeting audio.
19/// A mixer lists the people it mixes in as CSRCs; a direct call has only the peer's SSRC with its level.
20pub fn speaking_sources(sources: &[RtpSource]) -> Vec<u32> {
21 let Some(newest) = sources.iter().map(|source| source.timestamp_ms).max() else {
22 return Vec::new();
23 };
24 let has_contributors = sources.iter().any(|source| source.contributing);
25 let mut speaking: Vec<u32> = sources
26 .iter()
27 .filter(|source| source.contributing == has_contributors)
28 .filter(|source| newest - source.timestamp_ms <= RECENT_MS)
29 .filter(|source| match source.audio_level {
30 Some(level) => level <= SPEAKING_LEVEL,
31 None => source.contributing,
32 })
33 .map(|source| source.source_id)
34 .collect();
35 speaking.sort_unstable();
36 speaking.dedup();
37 speaking
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43
44 fn source(source_id: u32, contributing: bool, audio_level: Option<u8>, timestamp_ms: i64) -> RtpSource {
45 RtpSource { source_id, contributing, audio_level, timestamp_ms }
46 }
47
48 #[test]
49 fn mixer_contributors_seen_just_now_are_speaking() {
50 let sources = [
51 source(900, false, Some(30), 10_000),
52 source(7, true, None, 9_900),
53 source(8, true, Some(40), 10_000),
54 source(9, true, None, 9_000),
55 ];
56 assert_eq!(speaking_sources(&sources), vec![7, 8]);
57 }
58
59 #[test]
60 fn a_quiet_contributor_is_not_speaking() {
61 let sources = [source(900, false, Some(30), 10_000), source(8, true, Some(100), 10_000)];
62 assert!(speaking_sources(&sources).is_empty());
63 }
64
65 #[test]
66 fn a_direct_call_uses_the_peer_level() {
67 assert_eq!(speaking_sources(&[source(42, false, Some(35), 5_000)]), vec![42]);
68 assert!(speaking_sources(&[source(42, false, Some(127), 5_000)]).is_empty());
69 assert!(speaking_sources(&[source(42, false, None, 5_000)]).is_empty());
70 assert!(speaking_sources(&[]).is_empty());
71 }
72}
crates/calling/src/call.rs +19 −0
@@ -17,6 +17,7 @@ use tokio::sync::{Mutex, mpsc};
17 17 use tokio::task::JoinHandle;
18 18 use tokio::time::{Instant, interval, sleep_until, timeout};
19 19
20 use crate::active_speakers;
20 21 use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};
21 22 use crate::audio_io::{AudioMode, AudioSetup};
22 23 use crate::background::{BackgroundChoice, BackgroundPicture};
@@ -1019,6 +1020,8 @@ async fn drive(
1019 1020 }
1020 1021
1021 1022 let mut stats_tick = interval(STATS_PERIOD);
1023 let mut speaking_sources: Vec<u32> = Vec::new();
1024 let mut speaker_sources_seen = false;
1022 1025 let hard_deadline = options.hard_limit.map(|limit| call_started + limit);
1023 1026 let mut leave_at = hard_deadline;
1024 1027 let mut reconnect_deadline: Option<Instant> = None;
@@ -2297,6 +2300,22 @@ async fn drive(
2297 2300 }
2298 2301 },
2299 2302 _ = stats_tick.tick(), if remote_set => {
2303 let speaking = active_speakers::speaking_sources(&active_speakers::audio_sources(&current.peer));
2304 if speaking != speaking_sources {
2305 if speaking_sources.is_empty() && !speaker_sources_seen {
2306 speaker_sources_seen = true;
2307 timeline.record("active speakers", format!("{} source(s) from RTP", speaking.len()));
2308 }
2309 speaking_sources = speaking;
2310 let mut speakers = roster.mris_for_sources(&speaking_sources);
2311 if speakers.is_empty() && !speaking_sources.is_empty() && layout == Layout::OneToOne {
2312 speakers = roster.entries().into_iter().map(|entry| entry.mri).filter(|mri| *mri != own_mri).collect();
2313 }
2314 if video.note_speakers(&speakers) {
2315 send_receive_change(control, video.reselect(&roster));
2316 }
2317 control.send(CallUpdate::Speakers(speakers));
2318 }
2300 2319 let snapshot = collect_stats(&current.peer, &layout_plan.screen_share_mids).await;
2301 2320 ticks += 1;
2302 2321 if caption_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
@@ -17,6 +17,7 @@ use tokio::sync::{Mutex, mpsc};
17use tokio::task::JoinHandle;
17use tokio::task::JoinHandle;
18use tokio::time::{Instant, interval, sleep_until, timeout};
18use tokio::time::{Instant, interval, sleep_until, timeout};
19
19
20use crate::active_speakers;
20use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};
21use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};
21use crate::audio_io::{AudioMode, AudioSetup};
22use crate::audio_io::{AudioMode, AudioSetup};
22use crate::background::{BackgroundChoice, BackgroundPicture};
23use crate::background::{BackgroundChoice, BackgroundPicture};
@@ -1019,6 +1020,8 @@ async fn drive(
1019 }
1020 }
1020
1021
1021 let mut stats_tick = interval(STATS_PERIOD);
1022 let mut stats_tick = interval(STATS_PERIOD);
1023 let mut speaking_sources: Vec<u32> = Vec::new();
1024 let mut speaker_sources_seen = false;
1022 let hard_deadline = options.hard_limit.map(|limit| call_started + limit);
1025 let hard_deadline = options.hard_limit.map(|limit| call_started + limit);
1023 let mut leave_at = hard_deadline;
1026 let mut leave_at = hard_deadline;
1024 let mut reconnect_deadline: Option<Instant> = None;
1027 let mut reconnect_deadline: Option<Instant> = None;
@@ -2297,6 +2300,22 @@ async fn drive(
2297 }
2300 }
2298 },
2301 },
2299 _ = stats_tick.tick(), if remote_set => {
2302 _ = stats_tick.tick(), if remote_set => {
2303 let speaking = active_speakers::speaking_sources(&active_speakers::audio_sources(&current.peer));
2304 if speaking != speaking_sources {
2305 if speaking_sources.is_empty() && !speaker_sources_seen {
2306 speaker_sources_seen = true;
2307 timeline.record("active speakers", format!("{} source(s) from RTP", speaking.len()));
2308 }
2309 speaking_sources = speaking;
2310 let mut speakers = roster.mris_for_sources(&speaking_sources);
2311 if speakers.is_empty() && !speaking_sources.is_empty() && layout == Layout::OneToOne {
2312 speakers = roster.entries().into_iter().map(|entry| entry.mri).filter(|mri| *mri != own_mri).collect();
2313 }
2314 if video.note_speakers(&speakers) {
2315 send_receive_change(control, video.reselect(&roster));
2316 }
2317 control.send(CallUpdate::Speakers(speakers));
2318 }
2300 let snapshot = collect_stats(&current.peer, &layout_plan.screen_share_mids).await;
2319 let snapshot = collect_stats(&current.peer, &layout_plan.screen_share_mids).await;
2301 ticks += 1;
2320 ticks += 1;
2302 if caption_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
2321 if caption_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
crates/calling/src/lib.rs +1 −0
@@ -1,3 +1,4 @@
1 pub mod active_speakers;
1 2 pub mod audio;
2 3 pub mod audio_io;
3 4 pub mod awake;
@@ -1,3 +1,4 @@
1pub mod active_speakers;
1pub mod audio;
2pub mod audio;
2pub mod audio_io;
3pub mod audio_io;
3pub mod awake;
4pub mod awake;
vendor/libwebrtc/.cargo-ok added +1 −0
@@ -0,0 +1 @@
1 {"v":1}
@@ -0,0 +1 @@
1{"v":1}
vendor/libwebrtc/.cargo_vcs_info.json added +6 −0
@@ -0,0 +1,6 @@
1 {
2 "git": {
3 "sha1": "a6f93a16fa71fe811d040de175e070e233d9b1fe"
4 },
5 "path_in_vcs": "libwebrtc"
6 }
@@ -0,0 +1,6 @@
1{
2 "git": {
3 "sha1": "a6f93a16fa71fe811d040de175e070e233d9b1fe"
4 },
5 "path_in_vcs": "libwebrtc"
6}
vendor/libwebrtc/CHANGELOG.md added +513 −0
@@ -0,0 +1,513 @@
1 # Changelog
2
3 All notable changes to this project will be documented in this file.
4
5 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6 and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
8 ## [Unreleased]
9
10 ## [0.3.26](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.25...rust-sdks/libwebrtc@0.3.26) - 2026-02-16
11
12 ### Other
13
14 - add is_screencast to VideoSource ([#896](https://github.com/livekit/rust-sdks/pull/896))
15
16 ## [0.3.25](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.24...rust-sdks/libwebrtc@0.3.25) - 2026-02-09
17
18 ### Fixed
19
20 - fix the 440->441 samples issue and pass a noop callback for release ([#848](https://github.com/livekit/rust-sdks/pull/848))
21
22 ### Other
23
24 - Use workspace dependencies & settings ([#856](https://github.com/livekit/rust-sdks/pull/856))
25 - allow apm >=10ms frames ([#843](https://github.com/livekit/rust-sdks/pull/843))
26
27 ## [0.3.24](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.23...rust-sdks/libwebrtc@0.3.24) - 2026-01-15
28
29 ### Other
30
31 - updated the following local packages: webrtc-sys
32
33 ## [0.3.23](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.22...rust-sdks/libwebrtc@0.3.23) - 2025-12-19
34
35 ### Fixed
36
37 - Exclude the desktop-capturer module link for mobile. ([#817](https://github.com/livekit/rust-sdks/pull/817))
38
39 ## [0.3.22](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.21...rust-sdks/libwebrtc@0.3.22) - 2025-12-17
40
41 ### Other
42
43 - Expose WebRTC's audio_mixer ([#806](https://github.com/livekit/rust-sdks/pull/806))
44
45 ## [0.3.21](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.20...rust-sdks/libwebrtc@0.3.21) - 2025-12-04
46
47 ### Other
48
49 - move starting/stopping GLib event loop into libwebrtc crate ([#798](https://github.com/livekit/rust-sdks/pull/798))
50 - Expose desktop capturer ([#725](https://github.com/livekit/rust-sdks/pull/725))
51
52 ## [0.3.20](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.19...rust-sdks/libwebrtc@0.3.20) - 2025-11-20
53
54 ### Other
55
56 - Fix the fast path in capture_frame function, without buffering ([#778](https://github.com/livekit/rust-sdks/pull/778))
57
58 ## [0.3.19](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.18...rust-sdks/libwebrtc@0.3.19) - 2025-10-27
59
60 ### Other
61
62 - updated the following local packages: webrtc-sys
63
64 ## [0.3.18](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.17...rust-sdks/libwebrtc@0.3.18) - 2025-10-22
65
66 ### Other
67
68 - License check ([#746](https://github.com/livekit/rust-sdks/pull/746))
69
70 ## [0.3.17](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.16...rust-sdks/libwebrtc@0.3.17) - 2025-10-13
71
72 ### Added
73
74 - *(e2ee)* add data channel encryption ([#708](https://github.com/livekit/rust-sdks/pull/708))
75
76 ### Other
77
78 - Enable buffer scaling ([#473](https://github.com/livekit/rust-sdks/pull/473))
79
80 ## [0.3.16](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.15...rust-sdks/libwebrtc@0.3.16) - 2025-10-03
81
82 ### Other
83
84 - updated the following local packages: webrtc-sys
85
86 ## [0.3.15](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.14...rust-sdks/libwebrtc@0.3.15) - 2025-09-29
87
88 ### Fixed
89
90 - fix Builds/E2E Tests CI. ([#715](https://github.com/livekit/rust-sdks/pull/715))
91
92 ## [0.3.14](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.13...rust-sdks/libwebrtc@0.3.14) - 2025-09-09
93
94 ### Other
95
96 - updated the following local packages: webrtc-sys
97
98 ## [0.3.13](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.12...rust-sdks/libwebrtc@0.3.13) - 2025-09-03
99
100 ### Other
101
102 - updated the following local packages: webrtc-sys
103 # Changelog
104
105 ## [0.3.12](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.11...rust-sdks/libwebrtc@0.3.12) - 2025-06-17
106
107 ### Other
108
109 - updated the following local packages: livekit-protocol, webrtc-sys
110
111 ## [0.3.11](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.10...rust-sdks/libwebrtc@0.3.11) - 2025-06-11
112
113 ### Fixed
114
115 - fix uint32 overflow ([#615](https://github.com/livekit/rust-sdks/pull/615))
116
117 ### Other
118
119 - remove ([#633](https://github.com/livekit/rust-sdks/pull/633))
120 - expose apm stream_delay ([#616](https://github.com/livekit/rust-sdks/pull/616))
121 - Add i420_to_nv12 ([#605](https://github.com/livekit/rust-sdks/pull/605))
122 - ffi-v0.13.0 ([#590](https://github.com/livekit/rust-sdks/pull/590))
123 - add AudioProcessingModule ([#580](https://github.com/livekit/rust-sdks/pull/580))
124
125 ## [0.3.10] - 2025-02-05
126
127 ### Fixed
128
129 - Fix build issue
130
131 ## [0.3.9] - 2025-01-17
132
133 ### Added
134
135 - Expose DataChannel.bufferedAmount property
136
137 ## [0.3.8] - 2024-12-14
138
139 ### Added
140
141 - bump libwebrtc to m125
142 ## 0.3.51 (2026-10-07)
143
144 ### Fixes
145
146 - Manage VAAPI displays across capability probes and encoder lifecycles so driver resources and threads are released without invalidating active encoders.
147
148 ## 0.3.50 (2026-09-24)
149
150 ### Fixes
151
152 - Avoid panics when malformed RTC error headers contain non-ASCII text.
153 - Java version in libwebrtc was bumped by Google, downgrade it again for Unity 2022 build compatibility - #1456 (@MaxHeimbrock)
154
155 ## 0.3.49 (2026-09-22)
156
157 ### Fixes
158
159 - Correct the AppKit framework name so macOS linking works with case-sensitive SDK filesystems.
160 - Cleanup unused dependencies
161
162 ## 0.3.48 (2026-09-09)
163
164 ### Fixes
165
166 - Load the Jetson MMAPI encoder's runtime libraries (libnvbufsurface, libv4l2/libnvv4l2) lazily via dlopen instead of linking them, so an aarch64 binary built with Jetson support also loads on non-Jetson ARM systems and falls back to other encoders there.
167
168 #### Own the add_ice_candidate completion state
169
170 `PeerConnection::add_ice_candidate` captured `ctx` and `on_complete` by reference in the
171 completion lambda it hands to libwebrtc. That completion runs asynchronously on the signaling
172 thread and is deferred behind the operations chain whenever it is busy, for example while a
173 `SetRemoteDescription` is in flight, so it could execute after the calling frame had returned
174 and dereference freed stack memory (a crash on the signaling thread on the first ICE candidate
175 in practice). The lambda now owns its state through a `shared_ptr`.
176
177 ## 0.3.47 (2026-09-08)
178
179 ### Features
180
181 - Handle capture of dmabuf using existing capture path
182 - Removes livekit-runtime and converts this package to be tokio only again - #1375 (@1egoman)
183
184 #### Expose network_type on IceCandidateStats
185
186 Chromium's local `RTCIceCandidateStats` carries a non-standard `networkType` field (WiFi,
187 cellular, ethernet, etc.), but `IceCandidateStats` had no place to put it, so it was silently
188 dropped during `get_stats()` deserialization. Adds `network_type: Option<String>` to the struct;
189 non-breaking since it already derives `#[serde(default)]`.
190
191 ### Fixes
192
193 - Fix pre-encoded frame segfault on macOS
194
195 #### Make AdmProxy worker-thread-affine: all platform ADM access now happens on the WebRTC worker thread, matching the ADM threading contract.
196
197 - The platform ADM is now created lazily on the first PlatformAudio acquire on all platforms, so apps that never use platform audio never construct it.
198 - Fixes Android platform recording delivering no audio: the audio transport was never registered on the lazily created ADM.
199 - Fixes a shutdown race by keeping the runtime threads alive as long as Rust can reach the audio device controller.
200 - Adds a `platform_audio` example exercising the PlatformAudio API and the worker-thread marshaling.
201
202 #### Add agent guidance for detecting and preventing memory-lifecycle regressions in
203
204 Rust, FFI, and native WebRTC code.
205
206 #### Fix CUDA and FFI resource cleanup during SDK shutdown.
207
208 NVIDIA encoder and decoder factories now share a reference-counted CUDA context
209 and destroy it when the final factory is dropped. FFI shutdown now releases
210 leftover handles one at a time so nested `drop_handle` calls do not re-enter
211 `DashMap::clear()`. Adds regression coverage for FFI-handle, watcher, and
212 configuration cleanup during disposal.
213
214 #### Fix room-session and data-channel leaks across connect/disconnect cycles.
215
216 The E2EE manager callback now captures `RoomSession` weakly so the session can
217 drop after disconnect. Data-channel observer callbacks are cleared during RTC
218 teardown so the observer/callback cycle cannot keep peer connections alive.
219 Adds regression coverage for room-session destruction and data-channel callback
220 cleanup.
221
222 #### Fix native video-source lifecycle and NVENC initialization failure handling.
223
224 The raw-video keepalive task now uses a weak liveness check and defers its
225 black I420 buffer allocation until source liveness is confirmed, so dropping
226 an unused source releases its resources. `nvEncInitializeEncoder` failures now
227 propagate instead of leaving the encoder half-initialized.
228
229 ## 0.3.46 (2026-08-25)
230
231 ### Features
232
233 #### feat: enable WARP (SPED + SNAP) by default, gated by the server
234
235 WARP is now always enabled on the client and negotiated with the SFU: SPED
236 (DTLS-in-STUN) via the `WebRTC-IceHandshakeDtls` field trial, and SNAP
237 (SCTP-INIT-in-SDP) via the `RtcConfiguration.enable_sctp_snap` field. When the
238 server does not enable WARP it is not advertised and the connection falls back to
239 plain DTLS/SCTP, so there is no client-side toggle.
240
241 BREAKING CHANGE: `libwebrtc::RtcConfiguration` is now `#[non_exhaustive]` and has a
242 new `enable_sctp_snap` field. Construct it from `RtcConfiguration::default()` and set
243 the fields you need instead of a struct literal.
244
245 ### Fixes
246
247 - Automatically retry webrtc build downloads
248 - feat: upgrade libwebrtc to m150. - #1284 (@cloudwebrtc)
249
250 #### fix: bump libwebrtc to webrtc-b9233c3-2 so TURN/TLS can use the OS trust store
251
252 WebRTC validates TURN/TLS against a small set of anchors compiled into
253 `rtc_base/ssl_roots.h`, generated in 2023 from Google's own PKI list. It has no
254 Amazon, Starfield Services or ISRG roots, so a relay-only connection to a TURN
255 server fronted by AWS ACM or Let's Encrypt times out with `unknown_ca` even
256 though the host OS trusts the chain.
257
258 This build picks up webrtc-sdk/webrtc#277, which falls back to the operating
259 system's trust store when the built-in anchors yield no path. It sits in
260 `rtc_base` below every SDK, so the C++ API that webrtc-sys binds is covered
261 without any Rust-side change.
262
263 ## 0.3.45 (2026-08-10)
264
265 ### Fixes
266
267 - Only advertise internal H264 decode formats if the decoder works - #1313 (@MaxHeimbrock)
268
269 ## 0.3.44 (2026-08-03)
270
271 ### Fixes
272
273 #### Fix H.264, H.265, and AV1 NVENC sessions so live bitrate and frame rate updates
274
275 reconfigure the hardware without restarting the encoder.
276
277 ## 0.3.43 (2026-07-27)
278
279 ### Fixes
280
281 - Emit black keepalive frames from NativeVideoSource instead of uninitialized memory. webrtc::I420Buffer::Create leaves the pixel planes uninitialized, so the pre-capture keepalive frames could leak recycled heap contents (often fragments of earlier frames from the same process) to subscribers as the first keyframes - #1271 (@eh-steve)
282 - Add NVIDIA NVENC AV1 encoding when the GPU reports AV1 encode support.
283
284 ## 0.3.42 (2026-07-17)
285
286 ### Features
287
288 - fix compiler warnings in libwebrtc
289 - Add a pre-encoded video publish path: a passthrough video encoder and encoded video frame buffer in webrtc-sys, and `EncodedVideoFrame`/`EncodedVideoCodec`/`EncodedFrameType` publish APIs with a `VideoEncoderBackend::PreEncoded` backend in libwebrtc. WebRTC rate-control targets and keyframe requests are forwarded to encoded sources, and pre-encoded AV1 and H265 access units are validated on ingest.
290
291 ## 0.3.41 (2026-07-14)
292
293 ### Fixes
294
295 - Add an opt-in zero-playout-delay mode for native video subscribers, expose it through the `local_video` subscriber's `--low-latency` flag, and isolate subscriber diagnostics from frame-driven video rendering.
296
297 ## 0.3.40 (2026-07-09)
298
299 ### Fixes
300
301 - Fix malformed RTC error handling
302 - introduce LiveKitAPI construct, added smoke tests - #1220 (@davidzhao)
303
304 ## 0.3.39 (2026-06-30)
305
306 ### Features
307
308 #### Improve initial video quality by setting `x-google-start-bitrate` SDP hint for all video codecs (VP8, VP9, AV1, H264, H265) and defaulting to `MaintainResolution` degradation preference.
309
310 This addresses the issue where video starts blurry for several seconds before improving, by:
311 1. Telling WebRTC's bandwidth estimator to start at 70% of target bitrate instead of ramping up from ~300kbps
312 2. Preferring frame drops over resolution reduction when bandwidth is constrained
313
314 The `DegradationPreference` option is now exposed via FFI for Python, C++, Unity, and Node SDKs.
315
316 #### Add `MaintainFramerateAndResolution` to `DegradationPreference` enum to align with WebRTC M144.
317
318 - `MAINTAIN_FRAMERATE_AND_RESOLUTION` is now the recommended value (replaces deprecated `DISABLED`)
319 - `DISABLED` is deprecated but still supported for backwards compatibility
320 - Both values map to the same behavior: maintain framerate and resolution, dropping frames if needed
321
322 ### Fixes
323
324 - Fix AV1 subscriber decode when packet trailers are enabled.
325
326 ## 0.3.38 (2026-06-23)
327
328 ### Fixes
329
330 - Upgrade protocol to v1.48.0
331
332 ## 0.3.37 (2026-06-17)
333
334 ### Features
335
336 #### Add dynacast support - #1003 (@chenosaurus, @stephen-derosa)
337
338 This includes a minor breaking change for `libwebrtc`: `RtpParameters` now
339 contains additional RTP sender state that must be preserved when round-tripping
340 through `set_parameters()`.
341
342 #### Make GLib an opt-in dependency
343
344 `webrtc-sys` no longer links against `glib-2.0`/`gobject-2.0`/`gio-2.0` by default.
345
346 Breaking: Wayland screen sharing now requires the `glib-main-loop` feature on `livekit` (or `libwebrtc`).
347
348 ### Fixes
349
350 - Fix silent subscription failures in single-pc mode when the SFU reuses an existing empty transceiver for a new remote track. Also make `RtpTransceiver::mid()` safe to call on transceivers that haven't been negotiated yet — libwebrtc is built with `-fno-exceptions`, so `std::optional::value()` aborted the process instead of throwing.
351 - Add `LK_DISABLE_NVDEC` to bypass NVIDIA NVDEC decoder registration when the environment variable is set.
352 - Add Jetson DMA-buffer video publishing support for libargus MIPI capture and the Jetson hardware encoder, including AV1 hardware encoding on supported Jetson Orin devices.
353
354 ## 0.3.36 (2026-06-09)
355
356 ### Fixes
357
358 - Fix NVIDIA encoder I420 uploads to copy each plane using its actual source stride, avoiding chroma corruption when source frames use padded YUV planes. Also fix the `local_video` publisher reusing mutable I420 frame storage after handing frames to WebRTC.
359 - Keep one-frame native video streams as latest-frame queues. Move local video subscriber timing metrics into the example and use the WGPU paint callback as the render boundary.
360 - Add per-publication video encoder backend selection. Add a video encoder backend availability query. Remove `LIVEKIT_PREFERRED_HW_ENCODER` in favor of per-publication backend selection.
361
362 ## 0.3.35 (2026-05-29)
363
364 ### Fixes
365
366 - Add native video pipeline timing instrumentation for local video measurements, exposing local publish and subscribe timing through async streams and subscriber overlay GPU upload and receive-to-GPU latency metrics through explicit timing observers.
367
368 ## 0.3.34 (2026-05-21)
369
370 ### Fixes
371
372 #### feat: add Android application context initialization for PlatformAudio support.
373
374 Android requires `ContextUtils.initialize(applicationContext)` before WebRTC audio components can be created. This change:
375
376 - Adds `livekit_ffi_initialize_android_context()` C FFI function for Unity and other FFI consumers
377 - Uses `CreateAndroidAudioDeviceModule()` instead of generic `CreateAudioDeviceModule()` on Android
378 - Handles empty device GUIDs on Android (falls back to index 0)
379 - Documents Android-specific limitations: single default device, no app-level device selection
380
381 Platform notes:
382 - Android device enumeration returns only one "default" device with empty name/GUID
383 - Audio routing (speaker/earpiece/Bluetooth) is controlled by Android's AudioManager, not WebRTC
384
385 ## 0.3.33 (2026-05-14)
386
387 ### Fixes
388
389 - feat: add scalability mode for AV1/VP9. - #1076 (@cloudwebrtc)
390 - Add `LIVEKIT_PREFERRED_HW_ENCODER` to prefer `nvenc` or `vaapi` hardware video encoding when both are available.
391 - Relocate unrelated types out of `livekit-protocol`
392
393 #### Get WebRTC ADM into Rust - #1037 (@xianshijing-lk)
394
395 This PR introduces platform audio device management via WebRTC's Audio Device Module (ADM).
396
397 #### Features
398 - **ADM Proxy**: New `AdmProxy` class that switches between Dummy ADM (synthetic mode) and Platform ADM (real audio I/O)
399 - **PlatformAudio API**: High-level Rust API for microphone capture and speaker playout with AEC/AGC/NS
400 - **Device enumeration**: List and select recording/playout devices by index or GUID
401 - **Mode switching**: Seamlessly switch between synthetic mode (FFI callbacks) and platform mode (native speakers) while audio is active
402 - **FFI platform audio support**: Expose platform audio device enumeration and selection through `livekit-ffi`
403 - **Audio processing**: Configure echo cancellation, noise suppression, and auto gain control with platform-specific defaults (hardware on iOS, software elsewhere)
404
405 #### Audio Modes
406 | Mode | Recording | Playout | Use Case |
407 |------|-----------|---------|----------|
408 | Synthetic | NativeAudioSource | Dummy ADM + FFI | Unity audio, agents |
409 | Platform | Platform ADM mic | Platform ADM speakers | VoIP with AEC |
410
411 #### API
412 ```rust
413 // Create PlatformAudio for microphone/speaker access
414 let audio = PlatformAudio::new()?;
415
416 // Enumerate and select devices
417 for i in 0..audio.recording_devices() as u16 {
418 println!("Mic {}: {}", i, audio.recording_device_name(i));
419 }
420 audio.set_recording_device(0)?;
421
422 // Create audio track for publishing
423 let track = LocalAudioTrack::create_audio_track("mic", audio.rtc_source());
424 ```
425
426 ## 0.3.32 (2026-05-11)
427
428 ### Fixes
429
430 - Upgrade protocol to v1.45.8
431
432 ## 0.3.31 (2026-05-10)
433
434 ### Fixes
435
436 - Fix missing `libwebrtc.jar` for Android builds, harden build scripts
437 - fix race in download_webrtc to reduce flaky build - #1047 (@hechen-eng)
438 - Improve WebRTC build scripts and add external_audio_source patch - #1053 (@xianshijing-lk)
439
440 ## 0.3.30 (2026-04-23)
441
442 ### Features
443
444 #### Add support for frame level packet trailer
445
446 ##890 by @chenosaurus
447
448 - Add support to attach/parse frame level timestamps & frame ID to VideoTracks as a custom payload trailer.
449 - Breaking change in VideoFrame API, must include `frame_metadata` or use VideoFrame::new().
450
451 ## 0.3.29 (2026-04-02)
452
453 ### Features
454
455 #### chore: upgrade libwebrtc to m144.
456
457 ##965 by @cloudwebrtc
458
459 ### Fixes
460
461 #### use the bounded buffer for video stream
462
463 ##956 by @xianshijing-lk
464
465 Before this PR, it uses an unbounded buffer for video stream, that will cause multiple problems:
466 1, video will be lagged behind if rendering is slow or just wake up from background
467 2, it will be out of sync with audio
468
469 This PRs provides options to set a bounded buffer for video stream, and use 1 buffer as the default option.
470
471 ## 0.3.28 (2026-03-31)
472
473 ### Fixes
474
475 - Upgrade to thiserror 2
476
477 #### fix: fix unavailable sem symbol for Linux aarch64.
478
479 ##975 by @cloudwebrtc
480
481 ## 0.3.27 (2026-03-22)
482
483 ### Features
484
485 #### E2EE: allow setting key_ring_size and key_derivation_algorithm, update webrtc to m144
486
487 ##921 by @onestacked
488
489 This PR uses [this webrtc-sdk PR](https://github.com/webrtc-sdk/webrtc/pull/224) to configure the KDF.
490
491 I've tested this with https://codeberg.org/esoteric_programmer/matrix-jukebox and it is compatible with Element Call.
492
493 Fixed: https://github.com/livekit/rust-sdks/issues/796
494
495 ### Fixes
496
497 - Fix H.264 codec matching
498
499 #### add bounded buffer to audio_stream, and use 10 frames as the default
500
501 ##945 by @xianshijing-lk
502
503 #### fix clang build issue from zed patches (#949)
504
505 ##950 by @cloudwebrtc
506
507 * webrtc-sys: Use clang instead of gcc
508
509 * Debug CI output for aarch64-linux
510
511 * ci: Install lld for aarch64-linux FFI builders
512
513 * webrtc-sys: Disable CREL
@@ -0,0 +1,513 @@
1# Changelog
2
3All notable changes to this project will be documented in this file.
4
5The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
8## [Unreleased]
9
10## [0.3.26](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.25...rust-sdks/libwebrtc@0.3.26) - 2026-02-16
11
12### Other
13
14- add is_screencast to VideoSource ([#896](https://github.com/livekit/rust-sdks/pull/896))
15
16## [0.3.25](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.24...rust-sdks/libwebrtc@0.3.25) - 2026-02-09
17
18### Fixed
19
20- fix the 440->441 samples issue and pass a noop callback for release ([#848](https://github.com/livekit/rust-sdks/pull/848))
21
22### Other
23
24- Use workspace dependencies & settings ([#856](https://github.com/livekit/rust-sdks/pull/856))
25- allow apm >=10ms frames ([#843](https://github.com/livekit/rust-sdks/pull/843))
26
27## [0.3.24](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.23...rust-sdks/libwebrtc@0.3.24) - 2026-01-15
28
29### Other
30
31- updated the following local packages: webrtc-sys
32
33## [0.3.23](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.22...rust-sdks/libwebrtc@0.3.23) - 2025-12-19
34
35### Fixed
36
37- Exclude the desktop-capturer module link for mobile. ([#817](https://github.com/livekit/rust-sdks/pull/817))
38
39## [0.3.22](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.21...rust-sdks/libwebrtc@0.3.22) - 2025-12-17
40
41### Other
42
43- Expose WebRTC's audio_mixer ([#806](https://github.com/livekit/rust-sdks/pull/806))
44
45## [0.3.21](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.20...rust-sdks/libwebrtc@0.3.21) - 2025-12-04
46
47### Other
48
49- move starting/stopping GLib event loop into libwebrtc crate ([#798](https://github.com/livekit/rust-sdks/pull/798))
50- Expose desktop capturer ([#725](https://github.com/livekit/rust-sdks/pull/725))
51
52## [0.3.20](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.19...rust-sdks/libwebrtc@0.3.20) - 2025-11-20
53
54### Other
55
56- Fix the fast path in capture_frame function, without buffering ([#778](https://github.com/livekit/rust-sdks/pull/778))
57
58## [0.3.19](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.18...rust-sdks/libwebrtc@0.3.19) - 2025-10-27
59
60### Other
61
62- updated the following local packages: webrtc-sys
63
64## [0.3.18](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.17...rust-sdks/libwebrtc@0.3.18) - 2025-10-22
65
66### Other
67
68- License check ([#746](https://github.com/livekit/rust-sdks/pull/746))
69
70## [0.3.17](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.16...rust-sdks/libwebrtc@0.3.17) - 2025-10-13
71
72### Added
73
74- *(e2ee)* add data channel encryption ([#708](https://github.com/livekit/rust-sdks/pull/708))
75
76### Other
77
78- Enable buffer scaling ([#473](https://github.com/livekit/rust-sdks/pull/473))
79
80## [0.3.16](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.15...rust-sdks/libwebrtc@0.3.16) - 2025-10-03
81
82### Other
83
84- updated the following local packages: webrtc-sys
85
86## [0.3.15](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.14...rust-sdks/libwebrtc@0.3.15) - 2025-09-29
87
88### Fixed
89
90- fix Builds/E2E Tests CI. ([#715](https://github.com/livekit/rust-sdks/pull/715))
91
92## [0.3.14](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.13...rust-sdks/libwebrtc@0.3.14) - 2025-09-09
93
94### Other
95
96- updated the following local packages: webrtc-sys
97
98## [0.3.13](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.12...rust-sdks/libwebrtc@0.3.13) - 2025-09-03
99
100### Other
101
102- updated the following local packages: webrtc-sys
103# Changelog
104
105## [0.3.12](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.11...rust-sdks/libwebrtc@0.3.12) - 2025-06-17
106
107### Other
108
109- updated the following local packages: livekit-protocol, webrtc-sys
110
111## [0.3.11](https://github.com/livekit/rust-sdks/compare/rust-sdks/libwebrtc@0.3.10...rust-sdks/libwebrtc@0.3.11) - 2025-06-11
112
113### Fixed
114
115- fix uint32 overflow ([#615](https://github.com/livekit/rust-sdks/pull/615))
116
117### Other
118
119- remove ([#633](https://github.com/livekit/rust-sdks/pull/633))
120- expose apm stream_delay ([#616](https://github.com/livekit/rust-sdks/pull/616))
121- Add i420_to_nv12 ([#605](https://github.com/livekit/rust-sdks/pull/605))
122- ffi-v0.13.0 ([#590](https://github.com/livekit/rust-sdks/pull/590))
123- add AudioProcessingModule ([#580](https://github.com/livekit/rust-sdks/pull/580))
124
125## [0.3.10] - 2025-02-05
126
127### Fixed
128
129- Fix build issue
130
131## [0.3.9] - 2025-01-17
132
133### Added
134
135- Expose DataChannel.bufferedAmount property
136
137## [0.3.8] - 2024-12-14
138
139### Added
140
141- bump libwebrtc to m125
142## 0.3.51 (2026-10-07)
143
144### Fixes
145
146- Manage VAAPI displays across capability probes and encoder lifecycles so driver resources and threads are released without invalidating active encoders.
147
148## 0.3.50 (2026-09-24)
149
150### Fixes
151
152- Avoid panics when malformed RTC error headers contain non-ASCII text.
153- Java version in libwebrtc was bumped by Google, downgrade it again for Unity 2022 build compatibility - #1456 (@MaxHeimbrock)
154
155## 0.3.49 (2026-09-22)
156
157### Fixes
158
159- Correct the AppKit framework name so macOS linking works with case-sensitive SDK filesystems.
160- Cleanup unused dependencies
161
162## 0.3.48 (2026-09-09)
163
164### Fixes
165
166- Load the Jetson MMAPI encoder's runtime libraries (libnvbufsurface, libv4l2/libnvv4l2) lazily via dlopen instead of linking them, so an aarch64 binary built with Jetson support also loads on non-Jetson ARM systems and falls back to other encoders there.
167
168#### Own the add_ice_candidate completion state
169
170`PeerConnection::add_ice_candidate` captured `ctx` and `on_complete` by reference in the
171completion lambda it hands to libwebrtc. That completion runs asynchronously on the signaling
172thread and is deferred behind the operations chain whenever it is busy, for example while a
173`SetRemoteDescription` is in flight, so it could execute after the calling frame had returned
174and dereference freed stack memory (a crash on the signaling thread on the first ICE candidate
175in practice). The lambda now owns its state through a `shared_ptr`.
176
177## 0.3.47 (2026-09-08)
178
179### Features
180
181- Handle capture of dmabuf using existing capture path
182- Removes livekit-runtime and converts this package to be tokio only again - #1375 (@1egoman)
183
184#### Expose network_type on IceCandidateStats
185
186Chromium's local `RTCIceCandidateStats` carries a non-standard `networkType` field (WiFi,
187cellular, ethernet, etc.), but `IceCandidateStats` had no place to put it, so it was silently
188dropped during `get_stats()` deserialization. Adds `network_type: Option<String>` to the struct;
189non-breaking since it already derives `#[serde(default)]`.
190
191### Fixes
192
193- Fix pre-encoded frame segfault on macOS
194
195#### Make AdmProxy worker-thread-affine: all platform ADM access now happens on the WebRTC worker thread, matching the ADM threading contract.
196
197- The platform ADM is now created lazily on the first PlatformAudio acquire on all platforms, so apps that never use platform audio never construct it.
198- Fixes Android platform recording delivering no audio: the audio transport was never registered on the lazily created ADM.
199- Fixes a shutdown race by keeping the runtime threads alive as long as Rust can reach the audio device controller.
200- Adds a `platform_audio` example exercising the PlatformAudio API and the worker-thread marshaling.
201
202#### Add agent guidance for detecting and preventing memory-lifecycle regressions in
203
204Rust, FFI, and native WebRTC code.
205
206#### Fix CUDA and FFI resource cleanup during SDK shutdown.
207
208NVIDIA encoder and decoder factories now share a reference-counted CUDA context
209and destroy it when the final factory is dropped. FFI shutdown now releases
210leftover handles one at a time so nested `drop_handle` calls do not re-enter
211`DashMap::clear()`. Adds regression coverage for FFI-handle, watcher, and
212configuration cleanup during disposal.
213
214#### Fix room-session and data-channel leaks across connect/disconnect cycles.
215
216The E2EE manager callback now captures `RoomSession` weakly so the session can
217drop after disconnect. Data-channel observer callbacks are cleared during RTC
218teardown so the observer/callback cycle cannot keep peer connections alive.
219Adds regression coverage for room-session destruction and data-channel callback
220cleanup.
221
222#### Fix native video-source lifecycle and NVENC initialization failure handling.
223
224The raw-video keepalive task now uses a weak liveness check and defers its
225black I420 buffer allocation until source liveness is confirmed, so dropping
226an unused source releases its resources. `nvEncInitializeEncoder` failures now
227propagate instead of leaving the encoder half-initialized.
228
229## 0.3.46 (2026-08-25)
230
231### Features
232
233#### feat: enable WARP (SPED + SNAP) by default, gated by the server
234
235WARP is now always enabled on the client and negotiated with the SFU: SPED
236(DTLS-in-STUN) via the `WebRTC-IceHandshakeDtls` field trial, and SNAP
237(SCTP-INIT-in-SDP) via the `RtcConfiguration.enable_sctp_snap` field. When the
238server does not enable WARP it is not advertised and the connection falls back to
239plain DTLS/SCTP, so there is no client-side toggle.
240
241BREAKING CHANGE: `libwebrtc::RtcConfiguration` is now `#[non_exhaustive]` and has a
242new `enable_sctp_snap` field. Construct it from `RtcConfiguration::default()` and set
243the fields you need instead of a struct literal.
244
245### Fixes
246
247- Automatically retry webrtc build downloads
248- feat: upgrade libwebrtc to m150. - #1284 (@cloudwebrtc)
249
250#### fix: bump libwebrtc to webrtc-b9233c3-2 so TURN/TLS can use the OS trust store
251
252WebRTC validates TURN/TLS against a small set of anchors compiled into
253`rtc_base/ssl_roots.h`, generated in 2023 from Google's own PKI list. It has no
254Amazon, Starfield Services or ISRG roots, so a relay-only connection to a TURN
255server fronted by AWS ACM or Let's Encrypt times out with `unknown_ca` even
256though the host OS trusts the chain.
257
258This build picks up webrtc-sdk/webrtc#277, which falls back to the operating
259system's trust store when the built-in anchors yield no path. It sits in
260`rtc_base` below every SDK, so the C++ API that webrtc-sys binds is covered
261without any Rust-side change.
262
263## 0.3.45 (2026-08-10)
264
265### Fixes
266
267- Only advertise internal H264 decode formats if the decoder works - #1313 (@MaxHeimbrock)
268
269## 0.3.44 (2026-08-03)
270
271### Fixes
272
273#### Fix H.264, H.265, and AV1 NVENC sessions so live bitrate and frame rate updates
274
275reconfigure the hardware without restarting the encoder.
276
277## 0.3.43 (2026-07-27)
278
279### Fixes
280
281- Emit black keepalive frames from NativeVideoSource instead of uninitialized memory. webrtc::I420Buffer::Create leaves the pixel planes uninitialized, so the pre-capture keepalive frames could leak recycled heap contents (often fragments of earlier frames from the same process) to subscribers as the first keyframes - #1271 (@eh-steve)
282- Add NVIDIA NVENC AV1 encoding when the GPU reports AV1 encode support.
283
284## 0.3.42 (2026-07-17)
285
286### Features
287
288- fix compiler warnings in libwebrtc
289- Add a pre-encoded video publish path: a passthrough video encoder and encoded video frame buffer in webrtc-sys, and `EncodedVideoFrame`/`EncodedVideoCodec`/`EncodedFrameType` publish APIs with a `VideoEncoderBackend::PreEncoded` backend in libwebrtc. WebRTC rate-control targets and keyframe requests are forwarded to encoded sources, and pre-encoded AV1 and H265 access units are validated on ingest.
290
291## 0.3.41 (2026-07-14)
292
293### Fixes
294
295- Add an opt-in zero-playout-delay mode for native video subscribers, expose it through the `local_video` subscriber's `--low-latency` flag, and isolate subscriber diagnostics from frame-driven video rendering.
296
297## 0.3.40 (2026-07-09)
298
299### Fixes
300
301- Fix malformed RTC error handling
302- introduce LiveKitAPI construct, added smoke tests - #1220 (@davidzhao)
303
304## 0.3.39 (2026-06-30)
305
306### Features
307
308#### Improve initial video quality by setting `x-google-start-bitrate` SDP hint for all video codecs (VP8, VP9, AV1, H264, H265) and defaulting to `MaintainResolution` degradation preference.
309
310This addresses the issue where video starts blurry for several seconds before improving, by:
3111. Telling WebRTC's bandwidth estimator to start at 70% of target bitrate instead of ramping up from ~300kbps
3122. Preferring frame drops over resolution reduction when bandwidth is constrained
313
314The `DegradationPreference` option is now exposed via FFI for Python, C++, Unity, and Node SDKs.
315
316#### Add `MaintainFramerateAndResolution` to `DegradationPreference` enum to align with WebRTC M144.
317
318- `MAINTAIN_FRAMERATE_AND_RESOLUTION` is now the recommended value (replaces deprecated `DISABLED`)
319- `DISABLED` is deprecated but still supported for backwards compatibility
320- Both values map to the same behavior: maintain framerate and resolution, dropping frames if needed
321
322### Fixes
323
324- Fix AV1 subscriber decode when packet trailers are enabled.
325
326## 0.3.38 (2026-06-23)
327
328### Fixes
329
330- Upgrade protocol to v1.48.0
331
332## 0.3.37 (2026-06-17)
333
334### Features
335
336#### Add dynacast support - #1003 (@chenosaurus, @stephen-derosa)
337
338This includes a minor breaking change for `libwebrtc`: `RtpParameters` now
339contains additional RTP sender state that must be preserved when round-tripping
340through `set_parameters()`.
341
342#### Make GLib an opt-in dependency
343
344`webrtc-sys` no longer links against `glib-2.0`/`gobject-2.0`/`gio-2.0` by default.
345
346Breaking: Wayland screen sharing now requires the `glib-main-loop` feature on `livekit` (or `libwebrtc`).
347
348### Fixes
349
350- Fix silent subscription failures in single-pc mode when the SFU reuses an existing empty transceiver for a new remote track. Also make `RtpTransceiver::mid()` safe to call on transceivers that haven't been negotiated yet — libwebrtc is built with `-fno-exceptions`, so `std::optional::value()` aborted the process instead of throwing.
351- Add `LK_DISABLE_NVDEC` to bypass NVIDIA NVDEC decoder registration when the environment variable is set.
352- Add Jetson DMA-buffer video publishing support for libargus MIPI capture and the Jetson hardware encoder, including AV1 hardware encoding on supported Jetson Orin devices.
353
354## 0.3.36 (2026-06-09)
355
356### Fixes
357
358- Fix NVIDIA encoder I420 uploads to copy each plane using its actual source stride, avoiding chroma corruption when source frames use padded YUV planes. Also fix the `local_video` publisher reusing mutable I420 frame storage after handing frames to WebRTC.
359- Keep one-frame native video streams as latest-frame queues. Move local video subscriber timing metrics into the example and use the WGPU paint callback as the render boundary.
360- Add per-publication video encoder backend selection. Add a video encoder backend availability query. Remove `LIVEKIT_PREFERRED_HW_ENCODER` in favor of per-publication backend selection.
361
362## 0.3.35 (2026-05-29)
363
364### Fixes
365
366- Add native video pipeline timing instrumentation for local video measurements, exposing local publish and subscribe timing through async streams and subscriber overlay GPU upload and receive-to-GPU latency metrics through explicit timing observers.
367
368## 0.3.34 (2026-05-21)
369
370### Fixes
371
372#### feat: add Android application context initialization for PlatformAudio support.
373
374Android requires `ContextUtils.initialize(applicationContext)` before WebRTC audio components can be created. This change:
375
376- Adds `livekit_ffi_initialize_android_context()` C FFI function for Unity and other FFI consumers
377- Uses `CreateAndroidAudioDeviceModule()` instead of generic `CreateAudioDeviceModule()` on Android
378- Handles empty device GUIDs on Android (falls back to index 0)
379- Documents Android-specific limitations: single default device, no app-level device selection
380
381Platform notes:
382- Android device enumeration returns only one "default" device with empty name/GUID
383- Audio routing (speaker/earpiece/Bluetooth) is controlled by Android's AudioManager, not WebRTC
384
385## 0.3.33 (2026-05-14)
386
387### Fixes
388
389- feat: add scalability mode for AV1/VP9. - #1076 (@cloudwebrtc)
390- Add `LIVEKIT_PREFERRED_HW_ENCODER` to prefer `nvenc` or `vaapi` hardware video encoding when both are available.
391- Relocate unrelated types out of `livekit-protocol`
392
393#### Get WebRTC ADM into Rust - #1037 (@xianshijing-lk)
394
395This PR introduces platform audio device management via WebRTC's Audio Device Module (ADM).
396
397#### Features
398- **ADM Proxy**: New `AdmProxy` class that switches between Dummy ADM (synthetic mode) and Platform ADM (real audio I/O)
399- **PlatformAudio API**: High-level Rust API for microphone capture and speaker playout with AEC/AGC/NS
400- **Device enumeration**: List and select recording/playout devices by index or GUID
401- **Mode switching**: Seamlessly switch between synthetic mode (FFI callbacks) and platform mode (native speakers) while audio is active
402- **FFI platform audio support**: Expose platform audio device enumeration and selection through `livekit-ffi`
403- **Audio processing**: Configure echo cancellation, noise suppression, and auto gain control with platform-specific defaults (hardware on iOS, software elsewhere)
404
405#### Audio Modes
406| Mode | Recording | Playout | Use Case |
407|------|-----------|---------|----------|
408| Synthetic | NativeAudioSource | Dummy ADM + FFI | Unity audio, agents |
409| Platform | Platform ADM mic | Platform ADM speakers | VoIP with AEC |
410
411#### API
412```rust
413// Create PlatformAudio for microphone/speaker access
414let audio = PlatformAudio::new()?;
415
416// Enumerate and select devices
417for i in 0..audio.recording_devices() as u16 {
418 println!("Mic {}: {}", i, audio.recording_device_name(i));
419}
420audio.set_recording_device(0)?;
421
422// Create audio track for publishing
423let track = LocalAudioTrack::create_audio_track("mic", audio.rtc_source());
424```
425
426## 0.3.32 (2026-05-11)
427
428### Fixes
429
430- Upgrade protocol to v1.45.8
431
432## 0.3.31 (2026-05-10)
433
434### Fixes
435
436- Fix missing `libwebrtc.jar` for Android builds, harden build scripts
437- fix race in download_webrtc to reduce flaky build - #1047 (@hechen-eng)
438- Improve WebRTC build scripts and add external_audio_source patch - #1053 (@xianshijing-lk)
439
440## 0.3.30 (2026-04-23)
441
442### Features
443
444#### Add support for frame level packet trailer
445
446##890 by @chenosaurus
447
448- Add support to attach/parse frame level timestamps & frame ID to VideoTracks as a custom payload trailer.
449- Breaking change in VideoFrame API, must include `frame_metadata` or use VideoFrame::new().
450
451## 0.3.29 (2026-04-02)
452
453### Features
454
455#### chore: upgrade libwebrtc to m144.
456
457##965 by @cloudwebrtc
458
459### Fixes
460
461#### use the bounded buffer for video stream
462
463##956 by @xianshijing-lk
464
465Before this PR, it uses an unbounded buffer for video stream, that will cause multiple problems:
4661, video will be lagged behind if rendering is slow or just wake up from background
4672, it will be out of sync with audio
468
469This PRs provides options to set a bounded buffer for video stream, and use 1 buffer as the default option.
470
471## 0.3.28 (2026-03-31)
472
473### Fixes
474
475- Upgrade to thiserror 2
476
477#### fix: fix unavailable sem symbol for Linux aarch64.
478
479##975 by @cloudwebrtc
480
481## 0.3.27 (2026-03-22)
482
483### Features
484
485#### E2EE: allow setting key_ring_size and key_derivation_algorithm, update webrtc to m144
486
487##921 by @onestacked
488
489This PR uses [this webrtc-sdk PR](https://github.com/webrtc-sdk/webrtc/pull/224) to configure the KDF.
490
491I've tested this with https://codeberg.org/esoteric_programmer/matrix-jukebox and it is compatible with Element Call.
492
493Fixed: https://github.com/livekit/rust-sdks/issues/796
494
495### Fixes
496
497- Fix H.264 codec matching
498
499#### add bounded buffer to audio_stream, and use 10 frames as the default
500
501##945 by @xianshijing-lk
502
503#### fix clang build issue from zed patches (#949)
504
505##950 by @cloudwebrtc
506
507* webrtc-sys: Use clang instead of gcc
508
509* Debug CI output for aarch64-linux
510
511* ci: Install lld for aarch64-linux FFI builders
512
513* webrtc-sys: Disable CREL
vendor/libwebrtc/Cargo.toml added +115 −0
@@ -0,0 +1,115 @@
1 # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
2 #
3 # When uploading crates to the registry Cargo will automatically
4 # "normalize" Cargo.toml files for maximal compatibility
5 # with all versions of Cargo and also rewrite `path` dependencies
6 # to registry (e.g., crates.io) dependencies.
7 #
8 # If you are reading this file be aware that the original Cargo.toml
9 # will likely look very different (and much more reasonable).
10 # See Cargo.toml.orig for the original contents.
11
12 [package]
13 edition = "2021"
14 name = "libwebrtc"
15 version = "0.3.51"
16 build = false
17 autolib = false
18 autobins = false
19 autoexamples = false
20 autotests = false
21 autobenches = false
22 description = "Livekit safe bindings to libwebrtc"
23 homepage = "https://livekit.io"
24 readme = false
25 license = "Apache-2.0"
26 repository = "https://github.com/livekit/rust-sdks"
27
28 [package.metadata.feature-combinations]
29 mode = "powerset"
30
31 [features]
32 default = []
33 glib-main-loop = ["dep:glib"]
34
35 [lib]
36 name = "libwebrtc"
37 path = "src/lib.rs"
38
39 [dependencies.log]
40 version = "0.4"
41
42 [dependencies.serde]
43 version = "1"
44 features = ["derive"]
45
46 [dependencies.serde_json]
47 version = "1.0"
48
49 [dependencies.thiserror]
50 version = "2"
51
52 [dev-dependencies.env_logger]
53 version = "0.11"
54
55 [target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies.glib]
56 version = "0.21.3"
57 optional = true
58
59 [target.'cfg(not(target_arch = "wasm32"))'.dependencies.cxx]
60 version = "1.0"
61
62 [target.'cfg(not(target_arch = "wasm32"))'.dependencies.lazy_static]
63 version = "1.4"
64
65 [target.'cfg(not(target_arch = "wasm32"))'.dependencies.parking_lot]
66 version = "0.12"
67
68 [target.'cfg(not(target_arch = "wasm32"))'.dependencies.rtrb]
69 version = "0.3.3"
70
71 [target.'cfg(not(target_arch = "wasm32"))'.dependencies.tokio]
72 version = "1"
73 features = [
74 "sync",
75 "macros",
76 "time",
77 "rt-multi-thread",
78 ]
79 default-features = false
80
81 [target.'cfg(not(target_arch = "wasm32"))'.dependencies.tokio-stream]
82 version = "0.1"
83
84 [target.'cfg(not(target_arch = "wasm32"))'.dependencies.webrtc-sys]
85 version = "0.3.48"
86
87 [target.'cfg(target_arch = "wasm32")'.dependencies.js-sys]
88 version = "0.3"
89
90 [target.'cfg(target_arch = "wasm32")'.dependencies.wasm-bindgen]
91 version = "0.2"
92
93 [target.'cfg(target_arch = "wasm32")'.dependencies.wasm-bindgen-futures]
94 version = "0.4"
95
96 [target.'cfg(target_arch = "wasm32")'.dependencies.web-sys]
97 version = "0.3"
98 features = [
99 "MessageEvent",
100 "RtcPeerConnection",
101 "RtcSignalingState",
102 "RtcSdpType",
103 "RtcSessionDescriptionInit",
104 "RtcPeerConnectionIceEvent",
105 "RtcIceCandidate",
106 "RtcDataChannel",
107 "RtcDataChannelEvent",
108 "RtcDataChannelState",
109 "EventTarget",
110 "WebGlRenderingContext",
111 "WebGlTexture",
112 ]
113
114 [target.'cfg(target_os = "android")'.dependencies.jni]
115 version = "0.21"
@@ -0,0 +1,115 @@
1# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
2#
3# When uploading crates to the registry Cargo will automatically
4# "normalize" Cargo.toml files for maximal compatibility
5# with all versions of Cargo and also rewrite `path` dependencies
6# to registry (e.g., crates.io) dependencies.
7#
8# If you are reading this file be aware that the original Cargo.toml
9# will likely look very different (and much more reasonable).
10# See Cargo.toml.orig for the original contents.
11
12[package]
13edition = "2021"
14name = "libwebrtc"
15version = "0.3.51"
16build = false
17autolib = false
18autobins = false
19autoexamples = false
20autotests = false
21autobenches = false
22description = "Livekit safe bindings to libwebrtc"
23homepage = "https://livekit.io"
24readme = false
25license = "Apache-2.0"
26repository = "https://github.com/livekit/rust-sdks"
27
28[package.metadata.feature-combinations]
29mode = "powerset"
30
31[features]
32default = []
33glib-main-loop = ["dep:glib"]
34
35[lib]
36name = "libwebrtc"
37path = "src/lib.rs"
38
39[dependencies.log]
40version = "0.4"
41
42[dependencies.serde]
43version = "1"
44features = ["derive"]
45
46[dependencies.serde_json]
47version = "1.0"
48
49[dependencies.thiserror]
50version = "2"
51
52[dev-dependencies.env_logger]
53version = "0.11"
54
55[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies.glib]
56version = "0.21.3"
57optional = true
58
59[target.'cfg(not(target_arch = "wasm32"))'.dependencies.cxx]
60version = "1.0"
61
62[target.'cfg(not(target_arch = "wasm32"))'.dependencies.lazy_static]
63version = "1.4"
64
65[target.'cfg(not(target_arch = "wasm32"))'.dependencies.parking_lot]
66version = "0.12"
67
68[target.'cfg(not(target_arch = "wasm32"))'.dependencies.rtrb]
69version = "0.3.3"
70
71[target.'cfg(not(target_arch = "wasm32"))'.dependencies.tokio]
72version = "1"
73features = [
74 "sync",
75 "macros",
76 "time",
77 "rt-multi-thread",
78]
79default-features = false
80
81[target.'cfg(not(target_arch = "wasm32"))'.dependencies.tokio-stream]
82version = "0.1"
83
84[target.'cfg(not(target_arch = "wasm32"))'.dependencies.webrtc-sys]
85version = "0.3.48"
86
87[target.'cfg(target_arch = "wasm32")'.dependencies.js-sys]
88version = "0.3"
89
90[target.'cfg(target_arch = "wasm32")'.dependencies.wasm-bindgen]
91version = "0.2"
92
93[target.'cfg(target_arch = "wasm32")'.dependencies.wasm-bindgen-futures]
94version = "0.4"
95
96[target.'cfg(target_arch = "wasm32")'.dependencies.web-sys]
97version = "0.3"
98features = [
99 "MessageEvent",
100 "RtcPeerConnection",
101 "RtcSignalingState",
102 "RtcSdpType",
103 "RtcSessionDescriptionInit",
104 "RtcPeerConnectionIceEvent",
105 "RtcIceCandidate",
106 "RtcDataChannel",
107 "RtcDataChannelEvent",
108 "RtcDataChannelState",
109 "EventTarget",
110 "WebGlRenderingContext",
111 "WebGlTexture",
112]
113
114[target.'cfg(target_os = "android")'.dependencies.jni]
115version = "0.21"
vendor/libwebrtc/Cargo.toml.orig added +66 −0
@@ -0,0 +1,66 @@
1 [package]
2 name = "libwebrtc"
3 version = "0.3.51"
4 edition.workspace = true
5 homepage = "https://livekit.io"
6 license.workspace = true
7 description = "Livekit safe bindings to libwebrtc"
8 repository.workspace = true
9
10 [features]
11 default = []
12
13 # On Wayland, libwebrtc uses GDBus to communicate with the XDG Desktop Portal.
14 # GDBus requires a GLib event loop to be running. Enable this feature if you
15 # wish to use screensharing, and you do not already have a GLib event loop
16 # running in your application.
17 glib-main-loop = [ "dep:glib" ]
18
19 # How CI checks this crate's features, read by
20 # `.github/workflows/feature-combinations-curated.yml` via `cargo metadata`.
21 [package.metadata.feature-combinations]
22 mode = "powerset"
23
24 [dependencies]
25 log = { workspace = true }
26 serde = { workspace = true, features = ["derive"] }
27 serde_json = { workspace = true }
28 thiserror = { workspace = true }
29
30 [target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
31 glib = { version = "0.21.3", optional = true }
32
33 [target.'cfg(target_os = "android")'.dependencies]
34 jni = "0.21"
35
36 [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
37 webrtc-sys = { workspace = true }
38 tokio-stream = { workspace = true }
39 lazy_static = { workspace = true }
40 parking_lot = { workspace = true }
41 tokio = { workspace = true, default-features = false, features = ["sync", "macros", "time", "rt-multi-thread"] }
42 cxx = "1.0"
43 rtrb = "0.3.3"
44
45 [target.'cfg(target_arch = "wasm32")'.dependencies]
46 wasm-bindgen = "0.2"
47 js-sys = "0.3"
48 wasm-bindgen-futures = "0.4"
49 web-sys = { version = "0.3", features = [
50 "MessageEvent",
51 "RtcPeerConnection",
52 "RtcSignalingState",
53 "RtcSdpType",
54 "RtcSessionDescriptionInit",
55 "RtcPeerConnectionIceEvent",
56 "RtcIceCandidate",
57 "RtcDataChannel",
58 "RtcDataChannelEvent",
59 "RtcDataChannelState",
60 "EventTarget",
61 "WebGlRenderingContext",
62 "WebGlTexture",
63 ] }
64
65 [dev-dependencies]
66 env_logger = { workspace = true }
@@ -0,0 +1,66 @@
1[package]
2name = "libwebrtc"
3version = "0.3.51"
4edition.workspace = true
5homepage = "https://livekit.io"
6license.workspace = true
7description = "Livekit safe bindings to libwebrtc"
8repository.workspace = true
9
10[features]
11default = []
12
13# On Wayland, libwebrtc uses GDBus to communicate with the XDG Desktop Portal.
14# GDBus requires a GLib event loop to be running. Enable this feature if you
15# wish to use screensharing, and you do not already have a GLib event loop
16# running in your application.
17glib-main-loop = [ "dep:glib" ]
18
19# How CI checks this crate's features, read by
20# `.github/workflows/feature-combinations-curated.yml` via `cargo metadata`.
21[package.metadata.feature-combinations]
22mode = "powerset"
23
24[dependencies]
25log = { workspace = true }
26serde = { workspace = true, features = ["derive"] }
27serde_json = { workspace = true }
28thiserror = { workspace = true }
29
30[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
31glib = { version = "0.21.3", optional = true }
32
33[target.'cfg(target_os = "android")'.dependencies]
34jni = "0.21"
35
36[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
37webrtc-sys = { workspace = true }
38tokio-stream = { workspace = true }
39lazy_static = { workspace = true }
40parking_lot = { workspace = true }
41tokio = { workspace = true, default-features = false, features = ["sync", "macros", "time", "rt-multi-thread"] }
42cxx = "1.0"
43rtrb = "0.3.3"
44
45[target.'cfg(target_arch = "wasm32")'.dependencies]
46wasm-bindgen = "0.2"
47js-sys = "0.3"
48wasm-bindgen-futures = "0.4"
49web-sys = { version = "0.3", features = [
50 "MessageEvent",
51 "RtcPeerConnection",
52 "RtcSignalingState",
53 "RtcSdpType",
54 "RtcSessionDescriptionInit",
55 "RtcPeerConnectionIceEvent",
56 "RtcIceCandidate",
57 "RtcDataChannel",
58 "RtcDataChannelEvent",
59 "RtcDataChannelState",
60 "EventTarget",
61 "WebGlRenderingContext",
62 "WebGlTexture",
63] }
64
65[dev-dependencies]
66env_logger = { workspace = true }
vendor/libwebrtc/src/audio_frame.rs added +35 −0
@@ -0,0 +1,35 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::borrow::Cow;
16
17 #[derive(Debug, Clone)]
18 pub struct AudioFrame<'a> {
19 pub data: Cow<'a, [i16]>,
20 pub sample_rate: u32,
21 pub num_channels: u32,
22 pub samples_per_channel: u32,
23 }
24
25 impl AudioFrame<'_> {
26 // Owned
27 pub fn new(sample_rate: u32, num_channels: u32, samples_per_channel: u32) -> Self {
28 Self {
29 data: vec![0; (num_channels * samples_per_channel) as usize].into(),
30 sample_rate,
31 num_channels,
32 samples_per_channel,
33 }
34 }
35 }
@@ -0,0 +1,35 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::borrow::Cow;
16
17#[derive(Debug, Clone)]
18pub struct AudioFrame<'a> {
19 pub data: Cow<'a, [i16]>,
20 pub sample_rate: u32,
21 pub num_channels: u32,
22 pub samples_per_channel: u32,
23}
24
25impl AudioFrame<'_> {
26 // Owned
27 pub fn new(sample_rate: u32, num_channels: u32, samples_per_channel: u32) -> Self {
28 Self {
29 data: vec![0; (num_channels * samples_per_channel) as usize].into(),
30 sample_rate,
31 num_channels,
32 samples_per_channel,
33 }
34 }
35}
vendor/libwebrtc/src/audio_source.rs added +214 −0
@@ -0,0 +1,214 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /// Default sample rate used by WebRTC audio pipelines (48kHz).
16 pub const DEFAULT_SAMPLE_RATE: u32 = 48000;
17
18 /// Default number of audio channels (mono).
19 pub const DEFAULT_NUM_CHANNELS: u32 = 1;
20
21 #[derive(Default, Debug)]
22 pub struct AudioSourceOptions {
23 pub echo_cancellation: bool,
24 pub noise_suppression: bool,
25 pub auto_gain_control: bool,
26 }
27
28 /// Audio source type for creating audio tracks.
29 ///
30 /// Choose the appropriate source based on your use case:
31 ///
32 /// | Use Case | Source | Description |
33 /// |----------|--------|-------------|
34 /// | Manual audio (TTS, files) | `RtcAudioSource::Native(source)` | Push frames manually |
35 /// | Microphone capture | `RtcAudioSource::Device` | Automatic via Platform ADM |
36 /// | Both (mic + screen) | Use both types | Multiple tracks supported |
37 ///
38 /// # Combining Sources
39 ///
40 /// You can have multiple audio tracks with different source types:
41 /// - Track A: `RtcAudioSource::Device` for microphone (via `PlatformAudio`)
42 /// - Track B: `RtcAudioSource::Native` for screen capture or TTS
43 #[non_exhaustive]
44 #[derive(Debug, Clone)]
45 pub enum RtcAudioSource {
46 /// Native audio source for manual audio frame capture.
47 ///
48 /// Use this with Synthetic ADM mode (the default). You push audio frames
49 /// manually via `NativeAudioSource::capture_frame()`.
50 ///
51 /// # Example
52 ///
53 /// ```rust,ignore
54 /// use livekit::webrtc::audio_source::native::NativeAudioSource;
55 /// use livekit::webrtc::audio_source::{AudioSourceOptions, RtcAudioSource};
56 ///
57 /// let source = NativeAudioSource::new(
58 /// AudioSourceOptions::default(),
59 /// 48000, 2, 100,
60 /// );
61 /// source.capture_frame(&frame).await?;
62 ///
63 /// let track = LocalAudioTrack::create_audio_track(
64 /// "audio",
65 /// RtcAudioSource::Native(source),
66 /// );
67 /// ```
68 #[cfg(not(target_arch = "wasm32"))]
69 Native(native::NativeAudioSource),
70
71 /// Device audio source - uses Platform ADM for automatic microphone capture.
72 ///
73 /// WebRTC automatically captures audio from the selected recording device
74 /// (microphone). You do NOT push frames manually.
75 ///
76 /// # Usage
77 ///
78 /// Use `PlatformAudio` from the `livekit` crate, which manages the Platform ADM
79 /// lifecycle and provides `RtcAudioSource::Device` via `rtc_source()`:
80 ///
81 /// ```rust,ignore
82 /// use livekit::prelude::*;
83 ///
84 /// // Create PlatformAudio (enables Platform ADM)
85 /// let audio = PlatformAudio::new()?;
86 ///
87 /// // Optionally select a specific device
88 /// if let Some(device) = audio.recording_devices().next() {
89 /// audio.set_recording_device(&device.id)?;
90 /// }
91 ///
92 /// // Create track using the device source
93 /// let track = LocalAudioTrack::create_audio_track("mic", audio.rtc_source());
94 /// ```
95 ///
96 /// # Combining with NativeAudioSource
97 ///
98 /// You CAN use `NativeAudioSource` alongside Platform ADM to have multiple
99 /// audio tracks with different sources (e.g., microphone + screen capture).
100 ///
101 /// # Platform Support
102 ///
103 /// - **iOS**: CoreAudio with VPIO (Voice Processing IO)
104 /// - **macOS**: CoreAudio
105 /// - **Windows**: WASAPI
106 /// - **Linux**: PulseAudio / ALSA
107 /// - **Android**: AAudio / OpenSL ES
108 #[cfg(not(target_arch = "wasm32"))]
109 Device,
110 }
111
112 impl RtcAudioSource {
113 /// Set audio processing options.
114 /// Note: For `Device` source, options are controlled by the Platform ADM.
115 pub fn set_audio_options(&self, options: AudioSourceOptions) {
116 match self {
117 #[cfg(not(target_arch = "wasm32"))]
118 RtcAudioSource::Native(source) => source.set_audio_options(options),
119 #[cfg(not(target_arch = "wasm32"))]
120 RtcAudioSource::Device => {
121 // Device source options are managed by the Platform ADM
122 // This is a no-op
123 }
124 }
125 }
126
127 /// Get audio processing options.
128 /// Note: For `Device` source, returns default options (actual options are managed by ADM).
129 pub fn audio_options(&self) -> AudioSourceOptions {
130 match self {
131 #[cfg(not(target_arch = "wasm32"))]
132 RtcAudioSource::Native(source) => source.audio_options(),
133 #[cfg(not(target_arch = "wasm32"))]
134 RtcAudioSource::Device => AudioSourceOptions::default(),
135 }
136 }
137
138 /// Get the sample rate.
139 /// Note: For `Device` source, returns [`DEFAULT_SAMPLE_RATE`] (48kHz).
140 pub fn sample_rate(&self) -> u32 {
141 match self {
142 #[cfg(not(target_arch = "wasm32"))]
143 RtcAudioSource::Native(source) => source.sample_rate(),
144 #[cfg(not(target_arch = "wasm32"))]
145 RtcAudioSource::Device => DEFAULT_SAMPLE_RATE,
146 }
147 }
148
149 /// Get the number of channels.
150 /// Note: For `Device` source, returns [`DEFAULT_NUM_CHANNELS`] (mono).
151 pub fn num_channels(&self) -> u32 {
152 match self {
153 #[cfg(not(target_arch = "wasm32"))]
154 RtcAudioSource::Native(source) => source.num_channels(),
155 #[cfg(not(target_arch = "wasm32"))]
156 RtcAudioSource::Device => DEFAULT_NUM_CHANNELS,
157 }
158 }
159 }
160
161 #[cfg(not(target_arch = "wasm32"))]
162 pub mod native {
163 use std::fmt::{Debug, Formatter};
164
165 use super::*;
166 use crate::imp::audio_source::NativeAudioSource as ImpAudioSource;
167 use crate::{audio_frame::AudioFrame, RtcError};
168
169 #[derive(Clone)]
170 pub struct NativeAudioSource {
171 pub(crate) handle: ImpAudioSource,
172 }
173
174 impl Debug for NativeAudioSource {
175 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
176 f.debug_struct("NativeAudioSource").finish()
177 }
178 }
179
180 impl NativeAudioSource {
181 pub fn new(
182 options: AudioSourceOptions,
183 sample_rate: u32,
184 num_channels: u32,
185 queue_size_ms: u32,
186 ) -> NativeAudioSource {
187 Self { handle: ImpAudioSource::new(options, sample_rate, num_channels, queue_size_ms) }
188 }
189
190 pub fn clear_buffer(&self) {
191 self.handle.clear_buffer()
192 }
193
194 pub async fn capture_frame(&self, frame: &AudioFrame<'_>) -> Result<(), RtcError> {
195 self.handle.capture_frame(frame).await
196 }
197
198 pub fn set_audio_options(&self, options: AudioSourceOptions) {
199 self.handle.set_audio_options(options)
200 }
201
202 pub fn audio_options(&self) -> AudioSourceOptions {
203 self.handle.audio_options()
204 }
205
206 pub fn sample_rate(&self) -> u32 {
207 self.handle.sample_rate()
208 }
209
210 pub fn num_channels(&self) -> u32 {
211 self.handle.num_channels()
212 }
213 }
214 }
@@ -0,0 +1,214 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/// Default sample rate used by WebRTC audio pipelines (48kHz).
16pub const DEFAULT_SAMPLE_RATE: u32 = 48000;
17
18/// Default number of audio channels (mono).
19pub const DEFAULT_NUM_CHANNELS: u32 = 1;
20
21#[derive(Default, Debug)]
22pub struct AudioSourceOptions {
23 pub echo_cancellation: bool,
24 pub noise_suppression: bool,
25 pub auto_gain_control: bool,
26}
27
28/// Audio source type for creating audio tracks.
29///
30/// Choose the appropriate source based on your use case:
31///
32/// | Use Case | Source | Description |
33/// |----------|--------|-------------|
34/// | Manual audio (TTS, files) | `RtcAudioSource::Native(source)` | Push frames manually |
35/// | Microphone capture | `RtcAudioSource::Device` | Automatic via Platform ADM |
36/// | Both (mic + screen) | Use both types | Multiple tracks supported |
37///
38/// # Combining Sources
39///
40/// You can have multiple audio tracks with different source types:
41/// - Track A: `RtcAudioSource::Device` for microphone (via `PlatformAudio`)
42/// - Track B: `RtcAudioSource::Native` for screen capture or TTS
43#[non_exhaustive]
44#[derive(Debug, Clone)]
45pub enum RtcAudioSource {
46 /// Native audio source for manual audio frame capture.
47 ///
48 /// Use this with Synthetic ADM mode (the default). You push audio frames
49 /// manually via `NativeAudioSource::capture_frame()`.
50 ///
51 /// # Example
52 ///
53 /// ```rust,ignore
54 /// use livekit::webrtc::audio_source::native::NativeAudioSource;
55 /// use livekit::webrtc::audio_source::{AudioSourceOptions, RtcAudioSource};
56 ///
57 /// let source = NativeAudioSource::new(
58 /// AudioSourceOptions::default(),
59 /// 48000, 2, 100,
60 /// );
61 /// source.capture_frame(&frame).await?;
62 ///
63 /// let track = LocalAudioTrack::create_audio_track(
64 /// "audio",
65 /// RtcAudioSource::Native(source),
66 /// );
67 /// ```
68 #[cfg(not(target_arch = "wasm32"))]
69 Native(native::NativeAudioSource),
70
71 /// Device audio source - uses Platform ADM for automatic microphone capture.
72 ///
73 /// WebRTC automatically captures audio from the selected recording device
74 /// (microphone). You do NOT push frames manually.
75 ///
76 /// # Usage
77 ///
78 /// Use `PlatformAudio` from the `livekit` crate, which manages the Platform ADM
79 /// lifecycle and provides `RtcAudioSource::Device` via `rtc_source()`:
80 ///
81 /// ```rust,ignore
82 /// use livekit::prelude::*;
83 ///
84 /// // Create PlatformAudio (enables Platform ADM)
85 /// let audio = PlatformAudio::new()?;
86 ///
87 /// // Optionally select a specific device
88 /// if let Some(device) = audio.recording_devices().next() {
89 /// audio.set_recording_device(&device.id)?;
90 /// }
91 ///
92 /// // Create track using the device source
93 /// let track = LocalAudioTrack::create_audio_track("mic", audio.rtc_source());
94 /// ```
95 ///
96 /// # Combining with NativeAudioSource
97 ///
98 /// You CAN use `NativeAudioSource` alongside Platform ADM to have multiple
99 /// audio tracks with different sources (e.g., microphone + screen capture).
100 ///
101 /// # Platform Support
102 ///
103 /// - **iOS**: CoreAudio with VPIO (Voice Processing IO)
104 /// - **macOS**: CoreAudio
105 /// - **Windows**: WASAPI
106 /// - **Linux**: PulseAudio / ALSA
107 /// - **Android**: AAudio / OpenSL ES
108 #[cfg(not(target_arch = "wasm32"))]
109 Device,
110}
111
112impl RtcAudioSource {
113 /// Set audio processing options.
114 /// Note: For `Device` source, options are controlled by the Platform ADM.
115 pub fn set_audio_options(&self, options: AudioSourceOptions) {
116 match self {
117 #[cfg(not(target_arch = "wasm32"))]
118 RtcAudioSource::Native(source) => source.set_audio_options(options),
119 #[cfg(not(target_arch = "wasm32"))]
120 RtcAudioSource::Device => {
121 // Device source options are managed by the Platform ADM
122 // This is a no-op
123 }
124 }
125 }
126
127 /// Get audio processing options.
128 /// Note: For `Device` source, returns default options (actual options are managed by ADM).
129 pub fn audio_options(&self) -> AudioSourceOptions {
130 match self {
131 #[cfg(not(target_arch = "wasm32"))]
132 RtcAudioSource::Native(source) => source.audio_options(),
133 #[cfg(not(target_arch = "wasm32"))]
134 RtcAudioSource::Device => AudioSourceOptions::default(),
135 }
136 }
137
138 /// Get the sample rate.
139 /// Note: For `Device` source, returns [`DEFAULT_SAMPLE_RATE`] (48kHz).
140 pub fn sample_rate(&self) -> u32 {
141 match self {
142 #[cfg(not(target_arch = "wasm32"))]
143 RtcAudioSource::Native(source) => source.sample_rate(),
144 #[cfg(not(target_arch = "wasm32"))]
145 RtcAudioSource::Device => DEFAULT_SAMPLE_RATE,
146 }
147 }
148
149 /// Get the number of channels.
150 /// Note: For `Device` source, returns [`DEFAULT_NUM_CHANNELS`] (mono).
151 pub fn num_channels(&self) -> u32 {
152 match self {
153 #[cfg(not(target_arch = "wasm32"))]
154 RtcAudioSource::Native(source) => source.num_channels(),
155 #[cfg(not(target_arch = "wasm32"))]
156 RtcAudioSource::Device => DEFAULT_NUM_CHANNELS,
157 }
158 }
159}
160
161#[cfg(not(target_arch = "wasm32"))]
162pub mod native {
163 use std::fmt::{Debug, Formatter};
164
165 use super::*;
166 use crate::imp::audio_source::NativeAudioSource as ImpAudioSource;
167 use crate::{audio_frame::AudioFrame, RtcError};
168
169 #[derive(Clone)]
170 pub struct NativeAudioSource {
171 pub(crate) handle: ImpAudioSource,
172 }
173
174 impl Debug for NativeAudioSource {
175 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
176 f.debug_struct("NativeAudioSource").finish()
177 }
178 }
179
180 impl NativeAudioSource {
181 pub fn new(
182 options: AudioSourceOptions,
183 sample_rate: u32,
184 num_channels: u32,
185 queue_size_ms: u32,
186 ) -> NativeAudioSource {
187 Self { handle: ImpAudioSource::new(options, sample_rate, num_channels, queue_size_ms) }
188 }
189
190 pub fn clear_buffer(&self) {
191 self.handle.clear_buffer()
192 }
193
194 pub async fn capture_frame(&self, frame: &AudioFrame<'_>) -> Result<(), RtcError> {
195 self.handle.capture_frame(frame).await
196 }
197
198 pub fn set_audio_options(&self, options: AudioSourceOptions) {
199 self.handle.set_audio_options(options)
200 }
201
202 pub fn audio_options(&self) -> AudioSourceOptions {
203 self.handle.audio_options()
204 }
205
206 pub fn sample_rate(&self) -> u32 {
207 self.handle.sample_rate()
208 }
209
210 pub fn num_channels(&self) -> u32 {
211 self.handle.num_channels()
212 }
213 }
214}
vendor/libwebrtc/src/audio_stream.rs added +113 −0
@@ -0,0 +1,113 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use crate::imp::audio_stream as stream_imp;
16
17 #[cfg(not(target_arch = "wasm32"))]
18 pub mod native {
19 use std::{
20 fmt::{Debug, Formatter},
21 pin::Pin,
22 task::{Context, Poll},
23 };
24
25 use tokio_stream::Stream;
26
27 use super::stream_imp;
28 use crate::{audio_frame::AudioFrame, audio_track::RtcAudioTrack};
29
30 const DEFAULT_QUEUE_SIZE_FRAMES: usize = 10;
31
32 #[derive(Clone, Debug, Default)]
33 pub struct NativeAudioStreamOptions {
34 /// Maximum number of queued WebRTC sink frames after the audio callback.
35 ///
36 /// Each queued frame corresponds to roughly 10 ms of decoded PCM audio
37 /// on the WebRTC sink path.
38 ///
39 /// `None` uses the default bounded queue size of 10 frames. `Some(0)`
40 /// opts into unbounded buffering. Positive values bound the queue, and
41 /// the stream drops the oldest queued frames on overflow so latency
42 /// stays bounded.
43 ///
44 /// If your application consumes both audio and video, keep the queue
45 /// sizing strategy coordinated across both streams. Using a much larger
46 /// queue, or unbounded buffering, for only one of them can increase
47 /// end-to-end latency for that stream and cause audio/video drift.
48 pub queue_size_frames: Option<usize>,
49 }
50
51 pub struct NativeAudioStream {
52 pub(crate) handle: stream_imp::NativeAudioStream,
53 }
54
55 impl Debug for NativeAudioStream {
56 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
57 f.debug_struct("NativeAudioStream").field("track", &self.track()).finish()
58 }
59 }
60
61 impl NativeAudioStream {
62 pub fn new(audio_track: RtcAudioTrack, sample_rate: i32, num_channels: i32) -> Self {
63 Self {
64 handle: stream_imp::NativeAudioStream::new(
65 audio_track,
66 sample_rate,
67 num_channels,
68 Some(DEFAULT_QUEUE_SIZE_FRAMES),
69 ),
70 }
71 }
72
73 pub fn with_options(
74 audio_track: RtcAudioTrack,
75 sample_rate: i32,
76 num_channels: i32,
77 options: NativeAudioStreamOptions,
78 ) -> Self {
79 Self {
80 handle: stream_imp::NativeAudioStream::new(
81 audio_track,
82 sample_rate,
83 num_channels,
84 normalize_queue_size_frames(options.queue_size_frames),
85 ),
86 }
87 }
88
89 pub fn track(&self) -> RtcAudioTrack {
90 self.handle.track()
91 }
92
93 pub fn close(&mut self) {
94 self.handle.close()
95 }
96 }
97
98 impl Stream for NativeAudioStream {
99 type Item = AudioFrame<'static>;
100
101 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
102 Pin::new(&mut self.get_mut().handle).poll_next(cx)
103 }
104 }
105
106 fn normalize_queue_size_frames(queue_size_frames: Option<usize>) -> Option<usize> {
107 match queue_size_frames {
108 None => Some(DEFAULT_QUEUE_SIZE_FRAMES),
109 Some(0) => None,
110 Some(value) => Some(value),
111 }
112 }
113 }
@@ -0,0 +1,113 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::imp::audio_stream as stream_imp;
16
17#[cfg(not(target_arch = "wasm32"))]
18pub mod native {
19 use std::{
20 fmt::{Debug, Formatter},
21 pin::Pin,
22 task::{Context, Poll},
23 };
24
25 use tokio_stream::Stream;
26
27 use super::stream_imp;
28 use crate::{audio_frame::AudioFrame, audio_track::RtcAudioTrack};
29
30 const DEFAULT_QUEUE_SIZE_FRAMES: usize = 10;
31
32 #[derive(Clone, Debug, Default)]
33 pub struct NativeAudioStreamOptions {
34 /// Maximum number of queued WebRTC sink frames after the audio callback.
35 ///
36 /// Each queued frame corresponds to roughly 10 ms of decoded PCM audio
37 /// on the WebRTC sink path.
38 ///
39 /// `None` uses the default bounded queue size of 10 frames. `Some(0)`
40 /// opts into unbounded buffering. Positive values bound the queue, and
41 /// the stream drops the oldest queued frames on overflow so latency
42 /// stays bounded.
43 ///
44 /// If your application consumes both audio and video, keep the queue
45 /// sizing strategy coordinated across both streams. Using a much larger
46 /// queue, or unbounded buffering, for only one of them can increase
47 /// end-to-end latency for that stream and cause audio/video drift.
48 pub queue_size_frames: Option<usize>,
49 }
50
51 pub struct NativeAudioStream {
52 pub(crate) handle: stream_imp::NativeAudioStream,
53 }
54
55 impl Debug for NativeAudioStream {
56 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
57 f.debug_struct("NativeAudioStream").field("track", &self.track()).finish()
58 }
59 }
60
61 impl NativeAudioStream {
62 pub fn new(audio_track: RtcAudioTrack, sample_rate: i32, num_channels: i32) -> Self {
63 Self {
64 handle: stream_imp::NativeAudioStream::new(
65 audio_track,
66 sample_rate,
67 num_channels,
68 Some(DEFAULT_QUEUE_SIZE_FRAMES),
69 ),
70 }
71 }
72
73 pub fn with_options(
74 audio_track: RtcAudioTrack,
75 sample_rate: i32,
76 num_channels: i32,
77 options: NativeAudioStreamOptions,
78 ) -> Self {
79 Self {
80 handle: stream_imp::NativeAudioStream::new(
81 audio_track,
82 sample_rate,
83 num_channels,
84 normalize_queue_size_frames(options.queue_size_frames),
85 ),
86 }
87 }
88
89 pub fn track(&self) -> RtcAudioTrack {
90 self.handle.track()
91 }
92
93 pub fn close(&mut self) {
94 self.handle.close()
95 }
96 }
97
98 impl Stream for NativeAudioStream {
99 type Item = AudioFrame<'static>;
100
101 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
102 Pin::new(&mut self.get_mut().handle).poll_next(cx)
103 }
104 }
105
106 fn normalize_queue_size_frames(queue_size_frames: Option<usize>) -> Option<usize> {
107 match queue_size_frames {
108 None => Some(DEFAULT_QUEUE_SIZE_FRAMES),
109 Some(0) => None,
110 Some(value) => Some(value),
111 }
112 }
113}
vendor/libwebrtc/src/audio_track.rs added +39 −0
@@ -0,0 +1,39 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::fmt::Debug;
16
17 use crate::{
18 imp::audio_track as imp_at,
19 media_stream_track::{media_stream_track, RtcTrackState},
20 };
21
22 #[derive(Clone)]
23 pub struct RtcAudioTrack {
24 pub(crate) handle: imp_at::RtcAudioTrack,
25 }
26
27 impl RtcAudioTrack {
28 media_stream_track!();
29 }
30
31 impl Debug for RtcAudioTrack {
32 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33 f.debug_struct("RtcAudioTrack")
34 .field("id", &self.id())
35 .field("enabled", &self.enabled())
36 .field("state", &self.state())
37 .finish()
38 }
39 }
@@ -0,0 +1,39 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use crate::{
18 imp::audio_track as imp_at,
19 media_stream_track::{media_stream_track, RtcTrackState},
20};
21
22#[derive(Clone)]
23pub struct RtcAudioTrack {
24 pub(crate) handle: imp_at::RtcAudioTrack,
25}
26
27impl RtcAudioTrack {
28 media_stream_track!();
29}
30
31impl Debug for RtcAudioTrack {
32 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33 f.debug_struct("RtcAudioTrack")
34 .field("id", &self.id())
35 .field("enabled", &self.enabled())
36 .field("state", &self.state())
37 .finish()
38 }
39}
vendor/libwebrtc/src/data_channel.rs added +125 −0
@@ -0,0 +1,125 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::{fmt::Debug, str::Utf8Error};
16
17 use serde::Deserialize;
18 use thiserror::Error;
19
20 use crate::{imp::data_channel as dc_imp, rtp_parameters::Priority};
21
22 #[derive(Clone, Debug)]
23 pub struct DataChannelInit {
24 pub ordered: bool,
25 pub max_retransmit_time: Option<i32>,
26 pub max_retransmits: Option<i32>,
27 pub protocol: String,
28 pub negotiated: bool,
29 pub id: i32,
30 pub priority: Option<Priority>,
31 }
32
33 impl Default for DataChannelInit {
34 fn default() -> Self {
35 Self {
36 ordered: true,
37 max_retransmit_time: None,
38 max_retransmits: None,
39 protocol: String::new(),
40 negotiated: false,
41 id: -1,
42 priority: None,
43 }
44 }
45 }
46
47 #[derive(Debug, Error)]
48 pub enum DataChannelError {
49 #[error("failed to send data, dc not open? send buffer is full ?")]
50 Send,
51 #[error("only utf8 strings can be sent")]
52 Utf8(#[from] Utf8Error),
53 }
54
55 #[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
56 #[serde(rename_all = "lowercase")]
57 pub enum DataChannelState {
58 Connecting,
59 Open,
60 Closing,
61 Closed,
62 }
63
64 #[derive(Debug)]
65 pub struct DataBuffer<'a> {
66 pub data: &'a [u8],
67 pub binary: bool,
68 }
69
70 pub type OnStateChange = Box<dyn FnMut(DataChannelState) + Send + Sync>;
71 pub type OnMessage = Box<dyn FnMut(DataBuffer) + Send + Sync>;
72 pub type OnBufferedAmountChange = Box<dyn FnMut(u64) + Send + Sync>;
73
74 #[derive(Clone)]
75 pub struct DataChannel {
76 pub(crate) handle: dc_imp::DataChannel,
77 }
78
79 impl DataChannel {
80 pub fn send(&self, data: &[u8], binary: bool) -> Result<(), DataChannelError> {
81 self.handle.send(data, binary)
82 }
83
84 pub fn id(&self) -> i32 {
85 self.handle.id()
86 }
87
88 pub fn label(&self) -> String {
89 self.handle.label()
90 }
91
92 pub fn state(&self) -> DataChannelState {
93 self.handle.state()
94 }
95
96 pub fn close(&self) {
97 self.handle.close()
98 }
99
100 pub fn buffered_amount(&self) -> u64 {
101 self.handle.buffered_amount()
102 }
103
104 pub fn on_state_change(&self, callback: Option<OnStateChange>) {
105 self.handle.on_state_change(callback)
106 }
107
108 pub fn on_message(&self, callback: Option<OnMessage>) {
109 self.handle.on_message(callback)
110 }
111
112 pub fn on_buffered_amount_change(&self, callback: Option<OnBufferedAmountChange>) {
113 self.handle.on_buffered_amount_change(callback)
114 }
115 }
116
117 impl Debug for DataChannel {
118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 f.debug_struct("DataChannel")
120 .field("id", &self.id())
121 .field("label", &self.label())
122 .field("state", &self.state())
123 .finish()
124 }
125 }
@@ -0,0 +1,125 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{fmt::Debug, str::Utf8Error};
16
17use serde::Deserialize;
18use thiserror::Error;
19
20use crate::{imp::data_channel as dc_imp, rtp_parameters::Priority};
21
22#[derive(Clone, Debug)]
23pub struct DataChannelInit {
24 pub ordered: bool,
25 pub max_retransmit_time: Option<i32>,
26 pub max_retransmits: Option<i32>,
27 pub protocol: String,
28 pub negotiated: bool,
29 pub id: i32,
30 pub priority: Option<Priority>,
31}
32
33impl Default for DataChannelInit {
34 fn default() -> Self {
35 Self {
36 ordered: true,
37 max_retransmit_time: None,
38 max_retransmits: None,
39 protocol: String::new(),
40 negotiated: false,
41 id: -1,
42 priority: None,
43 }
44 }
45}
46
47#[derive(Debug, Error)]
48pub enum DataChannelError {
49 #[error("failed to send data, dc not open? send buffer is full ?")]
50 Send,
51 #[error("only utf8 strings can be sent")]
52 Utf8(#[from] Utf8Error),
53}
54
55#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
56#[serde(rename_all = "lowercase")]
57pub enum DataChannelState {
58 Connecting,
59 Open,
60 Closing,
61 Closed,
62}
63
64#[derive(Debug)]
65pub struct DataBuffer<'a> {
66 pub data: &'a [u8],
67 pub binary: bool,
68}
69
70pub type OnStateChange = Box<dyn FnMut(DataChannelState) + Send + Sync>;
71pub type OnMessage = Box<dyn FnMut(DataBuffer) + Send + Sync>;
72pub type OnBufferedAmountChange = Box<dyn FnMut(u64) + Send + Sync>;
73
74#[derive(Clone)]
75pub struct DataChannel {
76 pub(crate) handle: dc_imp::DataChannel,
77}
78
79impl DataChannel {
80 pub fn send(&self, data: &[u8], binary: bool) -> Result<(), DataChannelError> {
81 self.handle.send(data, binary)
82 }
83
84 pub fn id(&self) -> i32 {
85 self.handle.id()
86 }
87
88 pub fn label(&self) -> String {
89 self.handle.label()
90 }
91
92 pub fn state(&self) -> DataChannelState {
93 self.handle.state()
94 }
95
96 pub fn close(&self) {
97 self.handle.close()
98 }
99
100 pub fn buffered_amount(&self) -> u64 {
101 self.handle.buffered_amount()
102 }
103
104 pub fn on_state_change(&self, callback: Option<OnStateChange>) {
105 self.handle.on_state_change(callback)
106 }
107
108 pub fn on_message(&self, callback: Option<OnMessage>) {
109 self.handle.on_message(callback)
110 }
111
112 pub fn on_buffered_amount_change(&self, callback: Option<OnBufferedAmountChange>) {
113 self.handle.on_buffered_amount_change(callback)
114 }
115}
116
117impl Debug for DataChannel {
118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 f.debug_struct("DataChannel")
120 .field("id", &self.id())
121 .field("label", &self.label())
122 .field("state", &self.state())
123 .finish()
124 }
125}
vendor/libwebrtc/src/desktop_capturer.rs added +230 −0
@@ -0,0 +1,230 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use crate::imp::desktop_capturer as imp_dc;
16
17 /// Configuration options for creating a desktop capturer.
18 ///
19 /// It contains a subset of libwebrtc's DesktopCaptureOptions.
20 ///
21 /// By default, it captures the entire screen and does not include the cursor.
22 ///
23 /// # Example
24 /// ```no_run
25 /// use libwebrtc::desktop_capturer::{DesktopCapturerOptions, DesktopCaptureSourceType};
26 ///
27 /// let mut options = DesktopCapturerOptions::new(DesktopCaptureSourceType::Screen);
28 /// options.set_include_cursor(true);
29 /// ```
30 pub struct DesktopCapturerOptions {
31 sys_handle: imp_dc::DesktopCapturerOptions,
32 }
33
34 /// Specifies the type of source that a desktop capturer should capture.
35 #[derive(Debug, Copy, Clone, PartialEq)]
36 pub enum DesktopCaptureSourceType {
37 Screen,
38 Window,
39 #[cfg(any(target_os = "macos", target_os = "linux"))]
40 Generic,
41 }
42
43 impl DesktopCapturerOptions {
44 /// Creates a new `DesktopCapturerOptions` with default values.
45 ///
46 /// # Arguments
47 ///
48 /// * `source_type` - The type of source to capture (screen or window).
49 ///
50 /// # Defaults
51 ///
52 /// - Cursor is not included in captured frames (use [`set_include_cursor`](Self::set_include_cursor) to change)
53 /// - On macOS, the ScreenCaptureKit system picker is enabled (use [`set_sck_system_picker`](Self::set_sck_system_picker) to change)
54 pub fn new(source_type: DesktopCaptureSourceType) -> Self {
55 let source_type = match source_type {
56 DesktopCaptureSourceType::Screen => imp_dc::SourceType::Screen,
57 DesktopCaptureSourceType::Window => imp_dc::SourceType::Window,
58 #[cfg(any(target_os = "macos", target_os = "linux"))]
59 DesktopCaptureSourceType::Generic => imp_dc::SourceType::Generic,
60 };
61 Self { sys_handle: imp_dc::DesktopCapturerOptions::new(source_type) }
62 }
63
64 /// Sets whether to include the cursor in captured frames.
65 pub fn set_include_cursor(&mut self, include: bool) {
66 self.sys_handle = self.sys_handle.with_cursor(include);
67 }
68
69 /// Sets whether to allow the ScreenCaptureKit system picker on macOS.
70 ///
71 /// This is enabled by default.
72 ///
73 /// When disabled, for capturing displays the client should get the source id
74 /// via a different way as [`DesktopCapturer::get_source_list`] returns an empty vector.
75 #[cfg(target_os = "macos")]
76 pub fn set_sck_system_picker(&mut self, allow_sck_system_picker: bool) {
77 self.sys_handle = self.sys_handle.with_sck_system_picker(allow_sck_system_picker);
78 }
79 }
80
81 /// A desktop capturer for capturing screens or windows.
82 pub struct DesktopCapturer {
83 handle: imp_dc::DesktopCapturer,
84 }
85
86 impl DesktopCapturer {
87 /// Creates a new `DesktopCapturer` with the specified callback and options.
88 ///
89 /// # Arguments
90 ///
91 /// * `options` - Configuration options for the capturer
92 ///
93 /// # Returns
94 ///
95 /// Returns `Some(DesktopCapturer)` if the capturer was created successfully,
96 /// or `None` if creation failed (e.g., due to platform limitations or permissions).
97 pub fn new(options: DesktopCapturerOptions) -> Option<Self> {
98 let desktop_capturer = imp_dc::DesktopCapturer::new(options.sys_handle);
99 if desktop_capturer.is_none() {
100 return None;
101 }
102 Some(Self { handle: desktop_capturer.unwrap() })
103 }
104
105 /// Starts capturing from the specified source.
106 ///
107 /// # Arguments
108 ///
109 /// * `source` - The capture source to use. It should be None when the capturer
110 /// is configured to use the system picker (on platforms that support it).
111 /// * `callback` - A function that will be called for each captured frame. The callback
112 /// receives a [`CaptureResult`] indicating success or error, and a [`DesktopFrame`]
113 /// containing the captured image data.
114 ///
115 /// # Note
116 ///
117 /// After calling this method, you must call [`capture_frame`](Self::capture_frame)
118 /// to actually capture frames. This method only initializes the capture session.
119 pub fn start_capture<T>(&mut self, source: Option<CaptureSource>, mut callback: T)
120 where
121 T: FnMut(Result<DesktopFrame, CaptureError>) + Send + 'static,
122 {
123 if let Some(source) = source {
124 self.handle.select_source(source.sys_handle.id());
125 }
126 let inner_callback = move |result: Result<imp_dc::DesktopFrame, imp_dc::CaptureError>| {
127 callback(capture_result_from_sys(result));
128 };
129 self.handle.start(inner_callback);
130 }
131
132 /// Captures a single frame.
133 ///
134 /// You must call [`start_capture`](Self::start_capture) before calling this method.
135 pub fn capture_frame(&mut self) {
136 self.handle.capture_frame();
137 }
138
139 /// Retrieves a list of available capture sources.
140 ///
141 /// Returns a list of screens or windows that can be captured, depending
142 /// on whether the capturer was configured for window or screen capture.
143 ///
144 /// # Returns
145 ///
146 /// A vector of [`CaptureSource`] objects representing available capture sources.
147 pub fn get_source_list(&self) -> Vec<CaptureSource> {
148 let source_list = self.handle.get_source_list();
149 source_list.into_iter().map(|source| CaptureSource { sys_handle: source }).collect()
150 }
151 }
152
153 pub struct DesktopFrame {
154 sys_handle: imp_dc::DesktopFrame,
155 }
156
157 impl DesktopFrame {
158 fn new(sys_handle: imp_dc::DesktopFrame) -> Self {
159 Self { sys_handle }
160 }
161
162 pub fn width(&self) -> i32 {
163 self.sys_handle.width() as i32
164 }
165
166 pub fn height(&self) -> i32 {
167 self.sys_handle.height() as i32
168 }
169
170 pub fn stride(&self) -> u32 {
171 self.sys_handle.stride() as u32
172 }
173
174 pub fn left(&self) -> i32 {
175 self.sys_handle.left()
176 }
177
178 pub fn top(&self) -> i32 {
179 self.sys_handle.top()
180 }
181
182 pub fn data(&self) -> &[u8] {
183 self.sys_handle.data()
184 }
185 }
186
187 #[derive(Clone)]
188 pub struct CaptureSource {
189 sys_handle: imp_dc::CaptureSource,
190 }
191
192 impl CaptureSource {
193 pub fn id(&self) -> u64 {
194 self.sys_handle.id()
195 }
196 pub fn title(&self) -> String {
197 self.sys_handle.title()
198 }
199 pub fn display_id(&self) -> i64 {
200 self.sys_handle.display_id()
201 }
202 }
203
204 impl std::fmt::Display for CaptureSource {
205 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206 f.debug_struct("CaptureSource")
207 .field("id", &self.id())
208 .field("title", &self.title())
209 .field("display_id", &self.display_id())
210 .finish()
211 }
212 }
213
214 #[derive(Debug, PartialEq)]
215 pub enum CaptureError {
216 Temporary,
217 Permanent,
218 }
219
220 fn capture_result_from_sys(
221 result: Result<imp_dc::DesktopFrame, imp_dc::CaptureError>,
222 ) -> Result<DesktopFrame, CaptureError> {
223 match result {
224 Ok(frame) => Ok(DesktopFrame::new(frame)),
225 Err(error) => Err(match error {
226 imp_dc::CaptureError::Temporary => CaptureError::Temporary,
227 imp_dc::CaptureError::Permanent => CaptureError::Permanent,
228 }),
229 }
230 }
@@ -0,0 +1,230 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::imp::desktop_capturer as imp_dc;
16
17/// Configuration options for creating a desktop capturer.
18///
19/// It contains a subset of libwebrtc's DesktopCaptureOptions.
20///
21/// By default, it captures the entire screen and does not include the cursor.
22///
23/// # Example
24/// ```no_run
25/// use libwebrtc::desktop_capturer::{DesktopCapturerOptions, DesktopCaptureSourceType};
26///
27/// let mut options = DesktopCapturerOptions::new(DesktopCaptureSourceType::Screen);
28/// options.set_include_cursor(true);
29/// ```
30pub struct DesktopCapturerOptions {
31 sys_handle: imp_dc::DesktopCapturerOptions,
32}
33
34/// Specifies the type of source that a desktop capturer should capture.
35#[derive(Debug, Copy, Clone, PartialEq)]
36pub enum DesktopCaptureSourceType {
37 Screen,
38 Window,
39 #[cfg(any(target_os = "macos", target_os = "linux"))]
40 Generic,
41}
42
43impl DesktopCapturerOptions {
44 /// Creates a new `DesktopCapturerOptions` with default values.
45 ///
46 /// # Arguments
47 ///
48 /// * `source_type` - The type of source to capture (screen or window).
49 ///
50 /// # Defaults
51 ///
52 /// - Cursor is not included in captured frames (use [`set_include_cursor`](Self::set_include_cursor) to change)
53 /// - On macOS, the ScreenCaptureKit system picker is enabled (use [`set_sck_system_picker`](Self::set_sck_system_picker) to change)
54 pub fn new(source_type: DesktopCaptureSourceType) -> Self {
55 let source_type = match source_type {
56 DesktopCaptureSourceType::Screen => imp_dc::SourceType::Screen,
57 DesktopCaptureSourceType::Window => imp_dc::SourceType::Window,
58 #[cfg(any(target_os = "macos", target_os = "linux"))]
59 DesktopCaptureSourceType::Generic => imp_dc::SourceType::Generic,
60 };
61 Self { sys_handle: imp_dc::DesktopCapturerOptions::new(source_type) }
62 }
63
64 /// Sets whether to include the cursor in captured frames.
65 pub fn set_include_cursor(&mut self, include: bool) {
66 self.sys_handle = self.sys_handle.with_cursor(include);
67 }
68
69 /// Sets whether to allow the ScreenCaptureKit system picker on macOS.
70 ///
71 /// This is enabled by default.
72 ///
73 /// When disabled, for capturing displays the client should get the source id
74 /// via a different way as [`DesktopCapturer::get_source_list`] returns an empty vector.
75 #[cfg(target_os = "macos")]
76 pub fn set_sck_system_picker(&mut self, allow_sck_system_picker: bool) {
77 self.sys_handle = self.sys_handle.with_sck_system_picker(allow_sck_system_picker);
78 }
79}
80
81/// A desktop capturer for capturing screens or windows.
82pub struct DesktopCapturer {
83 handle: imp_dc::DesktopCapturer,
84}
85
86impl DesktopCapturer {
87 /// Creates a new `DesktopCapturer` with the specified callback and options.
88 ///
89 /// # Arguments
90 ///
91 /// * `options` - Configuration options for the capturer
92 ///
93 /// # Returns
94 ///
95 /// Returns `Some(DesktopCapturer)` if the capturer was created successfully,
96 /// or `None` if creation failed (e.g., due to platform limitations or permissions).
97 pub fn new(options: DesktopCapturerOptions) -> Option<Self> {
98 let desktop_capturer = imp_dc::DesktopCapturer::new(options.sys_handle);
99 if desktop_capturer.is_none() {
100 return None;
101 }
102 Some(Self { handle: desktop_capturer.unwrap() })
103 }
104
105 /// Starts capturing from the specified source.
106 ///
107 /// # Arguments
108 ///
109 /// * `source` - The capture source to use. It should be None when the capturer
110 /// is configured to use the system picker (on platforms that support it).
111 /// * `callback` - A function that will be called for each captured frame. The callback
112 /// receives a [`CaptureResult`] indicating success or error, and a [`DesktopFrame`]
113 /// containing the captured image data.
114 ///
115 /// # Note
116 ///
117 /// After calling this method, you must call [`capture_frame`](Self::capture_frame)
118 /// to actually capture frames. This method only initializes the capture session.
119 pub fn start_capture<T>(&mut self, source: Option<CaptureSource>, mut callback: T)
120 where
121 T: FnMut(Result<DesktopFrame, CaptureError>) + Send + 'static,
122 {
123 if let Some(source) = source {
124 self.handle.select_source(source.sys_handle.id());
125 }
126 let inner_callback = move |result: Result<imp_dc::DesktopFrame, imp_dc::CaptureError>| {
127 callback(capture_result_from_sys(result));
128 };
129 self.handle.start(inner_callback);
130 }
131
132 /// Captures a single frame.
133 ///
134 /// You must call [`start_capture`](Self::start_capture) before calling this method.
135 pub fn capture_frame(&mut self) {
136 self.handle.capture_frame();
137 }
138
139 /// Retrieves a list of available capture sources.
140 ///
141 /// Returns a list of screens or windows that can be captured, depending
142 /// on whether the capturer was configured for window or screen capture.
143 ///
144 /// # Returns
145 ///
146 /// A vector of [`CaptureSource`] objects representing available capture sources.
147 pub fn get_source_list(&self) -> Vec<CaptureSource> {
148 let source_list = self.handle.get_source_list();
149 source_list.into_iter().map(|source| CaptureSource { sys_handle: source }).collect()
150 }
151}
152
153pub struct DesktopFrame {
154 sys_handle: imp_dc::DesktopFrame,
155}
156
157impl DesktopFrame {
158 fn new(sys_handle: imp_dc::DesktopFrame) -> Self {
159 Self { sys_handle }
160 }
161
162 pub fn width(&self) -> i32 {
163 self.sys_handle.width() as i32
164 }
165
166 pub fn height(&self) -> i32 {
167 self.sys_handle.height() as i32
168 }
169
170 pub fn stride(&self) -> u32 {
171 self.sys_handle.stride() as u32
172 }
173
174 pub fn left(&self) -> i32 {
175 self.sys_handle.left()
176 }
177
178 pub fn top(&self) -> i32 {
179 self.sys_handle.top()
180 }
181
182 pub fn data(&self) -> &[u8] {
183 self.sys_handle.data()
184 }
185}
186
187#[derive(Clone)]
188pub struct CaptureSource {
189 sys_handle: imp_dc::CaptureSource,
190}
191
192impl CaptureSource {
193 pub fn id(&self) -> u64 {
194 self.sys_handle.id()
195 }
196 pub fn title(&self) -> String {
197 self.sys_handle.title()
198 }
199 pub fn display_id(&self) -> i64 {
200 self.sys_handle.display_id()
201 }
202}
203
204impl std::fmt::Display for CaptureSource {
205 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206 f.debug_struct("CaptureSource")
207 .field("id", &self.id())
208 .field("title", &self.title())
209 .field("display_id", &self.display_id())
210 .finish()
211 }
212}
213
214#[derive(Debug, PartialEq)]
215pub enum CaptureError {
216 Temporary,
217 Permanent,
218}
219
220fn capture_result_from_sys(
221 result: Result<imp_dc::DesktopFrame, imp_dc::CaptureError>,
222) -> Result<DesktopFrame, CaptureError> {
223 match result {
224 Ok(frame) => Ok(DesktopFrame::new(frame)),
225 Err(error) => Err(match error {
226 imp_dc::CaptureError::Temporary => CaptureError::Temporary,
227 imp_dc::CaptureError::Permanent => CaptureError::Permanent,
228 }),
229 }
230}
vendor/libwebrtc/src/enum_dispatch.rs added +41 −0
@@ -0,0 +1,41 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // TODO(theomonnom): Async methods
16 #[macro_export]
17 macro_rules! enum_dispatch {
18 // This arm is used to avoid nested loops with the arguments
19 // The arguments are transformed to $combined_args tt
20 (@match [$($variant:ident),+]: $fnc:ident, $self:ident, $combined_args:tt) => {
21 match $self {
22 $(
23 Self::$variant(inner) => inner.$fnc$combined_args,
24 )+
25 }
26 };
27
28 // Create the function and extract self fron the $args tt (little hack)
29 (@fnc [$($variant:ident),+]: $vis:vis fn $fnc:ident($self:ident: $sty:ty $(, $arg:ident: $t:ty)*) -> $ret:ty) => {
30 #[inline]
31 $vis fn $fnc($self: $sty, $($arg: $t),*) -> $ret {
32 $crate::enum_dispatch!(@match [$($variant),+]: $fnc, $self, ($($arg,)*))
33 }
34 };
35
36 ($variants:tt; $($vis:vis fn $fnc:ident$args:tt -> $ret:ty;)+) => {
37 $(
38 $crate::enum_dispatch!(@fnc $variants: $vis fn $fnc$args -> $ret);
39 )+
40 };
41 }
@@ -0,0 +1,41 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// TODO(theomonnom): Async methods
16#[macro_export]
17macro_rules! enum_dispatch {
18 // This arm is used to avoid nested loops with the arguments
19 // The arguments are transformed to $combined_args tt
20 (@match [$($variant:ident),+]: $fnc:ident, $self:ident, $combined_args:tt) => {
21 match $self {
22 $(
23 Self::$variant(inner) => inner.$fnc$combined_args,
24 )+
25 }
26 };
27
28 // Create the function and extract self fron the $args tt (little hack)
29 (@fnc [$($variant:ident),+]: $vis:vis fn $fnc:ident($self:ident: $sty:ty $(, $arg:ident: $t:ty)*) -> $ret:ty) => {
30 #[inline]
31 $vis fn $fnc($self: $sty, $($arg: $t),*) -> $ret {
32 $crate::enum_dispatch!(@match [$($variant),+]: $fnc, $self, ($($arg,)*))
33 }
34 };
35
36 ($variants:tt; $($vis:vis fn $fnc:ident$args:tt -> $ret:ty;)+) => {
37 $(
38 $crate::enum_dispatch!(@fnc $variants: $vis fn $fnc$args -> $ret);
39 )+
40 };
41}
vendor/libwebrtc/src/ice_candidate.rs added +55 −0
@@ -0,0 +1,55 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::fmt::Debug;
16
17 use crate::{imp::ice_candidate as imp_ic, session_description::SdpParseError};
18
19 pub struct IceCandidate {
20 pub(crate) handle: imp_ic::IceCandidate,
21 }
22
23 impl IceCandidate {
24 pub fn parse(
25 sdp_mid: &str,
26 sdp_mline_index: i32,
27 sdp: &str,
28 ) -> Result<IceCandidate, SdpParseError> {
29 imp_ic::IceCandidate::parse(sdp_mid, sdp_mline_index, sdp)
30 }
31
32 pub fn sdp_mid(&self) -> String {
33 self.handle.sdp_mid()
34 }
35
36 pub fn sdp_mline_index(&self) -> i32 {
37 self.handle.sdp_mline_index()
38 }
39
40 pub fn candidate(&self) -> String {
41 self.handle.candidate()
42 }
43 }
44
45 impl ToString for IceCandidate {
46 fn to_string(&self) -> String {
47 self.handle.to_string()
48 }
49 }
50
51 impl Debug for IceCandidate {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 f.debug_struct("IceCandidate").field("candidate", &self.to_string()).finish()
54 }
55 }
@@ -0,0 +1,55 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use crate::{imp::ice_candidate as imp_ic, session_description::SdpParseError};
18
19pub struct IceCandidate {
20 pub(crate) handle: imp_ic::IceCandidate,
21}
22
23impl IceCandidate {
24 pub fn parse(
25 sdp_mid: &str,
26 sdp_mline_index: i32,
27 sdp: &str,
28 ) -> Result<IceCandidate, SdpParseError> {
29 imp_ic::IceCandidate::parse(sdp_mid, sdp_mline_index, sdp)
30 }
31
32 pub fn sdp_mid(&self) -> String {
33 self.handle.sdp_mid()
34 }
35
36 pub fn sdp_mline_index(&self) -> i32 {
37 self.handle.sdp_mline_index()
38 }
39
40 pub fn candidate(&self) -> String {
41 self.handle.candidate()
42 }
43}
44
45impl ToString for IceCandidate {
46 fn to_string(&self) -> String {
47 self.handle.to_string()
48 }
49}
50
51impl Debug for IceCandidate {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 f.debug_struct("IceCandidate").field("candidate", &self.to_string()).finish()
54 }
55}
vendor/libwebrtc/src/lib.rs added +81 −0
@@ -0,0 +1,81 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use thiserror::Error;
16
17 #[cfg_attr(target_arch = "wasm32", path = "web/mod.rs")]
18 #[cfg_attr(not(target_arch = "wasm32"), path = "native/mod.rs")]
19 mod imp;
20
21 mod enum_dispatch;
22
23 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
24 pub enum MediaType {
25 Audio,
26 Video,
27 Data,
28 Unsupported,
29 }
30
31 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
32 pub enum RtcErrorType {
33 Internal,
34 InvalidSdp,
35 InvalidState,
36 }
37
38 #[derive(Error, Debug)]
39 #[error("an RtcError occurred: {error_type:?} - {message}")]
40 pub struct RtcError {
41 pub error_type: RtcErrorType,
42 pub message: String,
43 }
44
45 pub mod audio_frame;
46 pub mod audio_source;
47 pub mod audio_stream;
48 pub mod audio_track;
49 pub mod data_channel;
50 #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
51 pub mod desktop_capturer;
52 pub mod ice_candidate;
53 pub mod media_stream;
54 pub mod media_stream_track;
55 pub mod peer_connection;
56 pub mod peer_connection_factory;
57 pub mod prelude;
58 pub mod rtp_parameters;
59 pub mod rtp_receiver;
60 pub mod rtp_sender;
61 pub mod rtp_transceiver;
62 pub mod session_description;
63 pub mod stats;
64 pub mod video_frame;
65 pub mod video_source;
66 pub mod video_stream;
67 pub mod video_track;
68
69 #[cfg(not(target_arch = "wasm32"))]
70 pub mod native {
71 pub use webrtc_sys::webrtc::ffi::create_random_uuid;
72
73 pub use crate::imp::{
74 apm, audio_mixer, audio_resampler, frame_cryptor, packet_trailer, yuv_helper,
75 };
76 }
77
78 #[cfg(target_os = "android")]
79 pub mod android {
80 pub use crate::imp::android::*;
81 }
@@ -0,0 +1,81 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use thiserror::Error;
16
17#[cfg_attr(target_arch = "wasm32", path = "web/mod.rs")]
18#[cfg_attr(not(target_arch = "wasm32"), path = "native/mod.rs")]
19mod imp;
20
21mod enum_dispatch;
22
23#[derive(Debug, Copy, Clone, PartialEq, Eq)]
24pub enum MediaType {
25 Audio,
26 Video,
27 Data,
28 Unsupported,
29}
30
31#[derive(Debug, Copy, Clone, PartialEq, Eq)]
32pub enum RtcErrorType {
33 Internal,
34 InvalidSdp,
35 InvalidState,
36}
37
38#[derive(Error, Debug)]
39#[error("an RtcError occurred: {error_type:?} - {message}")]
40pub struct RtcError {
41 pub error_type: RtcErrorType,
42 pub message: String,
43}
44
45pub mod audio_frame;
46pub mod audio_source;
47pub mod audio_stream;
48pub mod audio_track;
49pub mod data_channel;
50#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
51pub mod desktop_capturer;
52pub mod ice_candidate;
53pub mod media_stream;
54pub mod media_stream_track;
55pub mod peer_connection;
56pub mod peer_connection_factory;
57pub mod prelude;
58pub mod rtp_parameters;
59pub mod rtp_receiver;
60pub mod rtp_sender;
61pub mod rtp_transceiver;
62pub mod session_description;
63pub mod stats;
64pub mod video_frame;
65pub mod video_source;
66pub mod video_stream;
67pub mod video_track;
68
69#[cfg(not(target_arch = "wasm32"))]
70pub mod native {
71 pub use webrtc_sys::webrtc::ffi::create_random_uuid;
72
73 pub use crate::imp::{
74 apm, audio_mixer, audio_resampler, frame_cryptor, packet_trailer, yuv_helper,
75 };
76}
77
78#[cfg(target_os = "android")]
79pub mod android {
80 pub use crate::imp::android::*;
81}
vendor/libwebrtc/src/media_stream.rs added +46 −0
@@ -0,0 +1,46 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::fmt::Debug;
16
17 use crate::{audio_track::RtcAudioTrack, imp::media_stream as imp_ms, video_track::RtcVideoTrack};
18
19 #[derive(Clone)]
20 pub struct MediaStream {
21 pub(crate) handle: imp_ms::MediaStream,
22 }
23
24 impl MediaStream {
25 pub fn id(&self) -> String {
26 self.handle.id()
27 }
28
29 pub fn audio_tracks(&self) -> Vec<RtcAudioTrack> {
30 self.handle.audio_tracks()
31 }
32
33 pub fn video_tracks(&self) -> Vec<RtcVideoTrack> {
34 self.handle.video_tracks()
35 }
36 }
37
38 impl Debug for MediaStream {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 f.debug_struct("MediaStream")
41 .field("id", &self.id())
42 .field("audio_tracks", &self.audio_tracks())
43 .field("video_tracks", &self.video_tracks())
44 .finish()
45 }
46 }
@@ -0,0 +1,46 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use crate::{audio_track::RtcAudioTrack, imp::media_stream as imp_ms, video_track::RtcVideoTrack};
18
19#[derive(Clone)]
20pub struct MediaStream {
21 pub(crate) handle: imp_ms::MediaStream,
22}
23
24impl MediaStream {
25 pub fn id(&self) -> String {
26 self.handle.id()
27 }
28
29 pub fn audio_tracks(&self) -> Vec<RtcAudioTrack> {
30 self.handle.audio_tracks()
31 }
32
33 pub fn video_tracks(&self) -> Vec<RtcVideoTrack> {
34 self.handle.video_tracks()
35 }
36}
37
38impl Debug for MediaStream {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 f.debug_struct("MediaStream")
41 .field("id", &self.id())
42 .field("audio_tracks", &self.audio_tracks())
43 .field("video_tracks", &self.video_tracks())
44 .finish()
45 }
46}
vendor/libwebrtc/src/media_stream_track.rs added +86 −0
@@ -0,0 +1,86 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use crate::{audio_track::RtcAudioTrack, enum_dispatch, video_track::RtcVideoTrack};
16
17 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
18 pub enum RtcTrackState {
19 Live,
20 Ended,
21 }
22
23 #[derive(Debug, Clone)]
24 pub enum MediaStreamTrack {
25 Video(RtcVideoTrack),
26 Audio(RtcAudioTrack),
27 }
28
29 #[cfg(not(target_arch = "wasm32"))]
30 impl MediaStreamTrack {
31 enum_dispatch!(
32 [Video, Audio];
33 pub(crate) fn sys_handle(self: &Self) -> cxx::SharedPtr<webrtc_sys::media_stream::ffi::MediaStreamTrack>;
34 );
35 }
36
37 impl MediaStreamTrack {
38 enum_dispatch!(
39 [Video, Audio];
40 pub fn id(self: &Self) -> String;
41 pub fn enabled(self: &Self) -> bool;
42 pub fn set_enabled(self: &Self, enabled: bool) -> bool;
43 pub fn state(self: &Self) -> RtcTrackState;
44 );
45 }
46
47 macro_rules! media_stream_track {
48 () => {
49 pub fn id(&self) -> String {
50 self.handle.id()
51 }
52
53 pub fn enabled(&self) -> bool {
54 self.handle.enabled()
55 }
56
57 pub fn set_enabled(&self, enabled: bool) -> bool {
58 self.handle.set_enabled(enabled)
59 }
60
61 pub fn state(&self) -> RtcTrackState {
62 self.handle.state().into()
63 }
64
65 #[cfg(not(target_arch = "wasm32"))]
66 pub(crate) fn sys_handle(
67 &self,
68 ) -> cxx::SharedPtr<webrtc_sys::media_stream::ffi::MediaStreamTrack> {
69 self.handle.sys_handle()
70 }
71 };
72 }
73
74 pub(crate) use media_stream_track;
75
76 impl From<RtcAudioTrack> for MediaStreamTrack {
77 fn from(track: RtcAudioTrack) -> Self {
78 Self::Audio(track)
79 }
80 }
81
82 impl From<RtcVideoTrack> for MediaStreamTrack {
83 fn from(track: RtcVideoTrack) -> Self {
84 Self::Video(track)
85 }
86 }
@@ -0,0 +1,86 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::{audio_track::RtcAudioTrack, enum_dispatch, video_track::RtcVideoTrack};
16
17#[derive(Debug, Copy, Clone, PartialEq, Eq)]
18pub enum RtcTrackState {
19 Live,
20 Ended,
21}
22
23#[derive(Debug, Clone)]
24pub enum MediaStreamTrack {
25 Video(RtcVideoTrack),
26 Audio(RtcAudioTrack),
27}
28
29#[cfg(not(target_arch = "wasm32"))]
30impl MediaStreamTrack {
31 enum_dispatch!(
32 [Video, Audio];
33 pub(crate) fn sys_handle(self: &Self) -> cxx::SharedPtr<webrtc_sys::media_stream::ffi::MediaStreamTrack>;
34 );
35}
36
37impl MediaStreamTrack {
38 enum_dispatch!(
39 [Video, Audio];
40 pub fn id(self: &Self) -> String;
41 pub fn enabled(self: &Self) -> bool;
42 pub fn set_enabled(self: &Self, enabled: bool) -> bool;
43 pub fn state(self: &Self) -> RtcTrackState;
44 );
45}
46
47macro_rules! media_stream_track {
48 () => {
49 pub fn id(&self) -> String {
50 self.handle.id()
51 }
52
53 pub fn enabled(&self) -> bool {
54 self.handle.enabled()
55 }
56
57 pub fn set_enabled(&self, enabled: bool) -> bool {
58 self.handle.set_enabled(enabled)
59 }
60
61 pub fn state(&self) -> RtcTrackState {
62 self.handle.state().into()
63 }
64
65 #[cfg(not(target_arch = "wasm32"))]
66 pub(crate) fn sys_handle(
67 &self,
68 ) -> cxx::SharedPtr<webrtc_sys::media_stream::ffi::MediaStreamTrack> {
69 self.handle.sys_handle()
70 }
71 };
72}
73
74pub(crate) use media_stream_track;
75
76impl From<RtcAudioTrack> for MediaStreamTrack {
77 fn from(track: RtcAudioTrack) -> Self {
78 Self::Audio(track)
79 }
80}
81
82impl From<RtcVideoTrack> for MediaStreamTrack {
83 fn from(track: RtcVideoTrack) -> Self {
84 Self::Video(track)
85 }
86}
vendor/libwebrtc/src/native/android.rs added +65 −0
@@ -0,0 +1,65 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use jni::objects::JObject;
16 use webrtc_sys::android::ffi as sys_android;
17
18 /// Initialize Android WebRTC with the JVM.
19 ///
20 /// This is automatically called by [`initialize_android_context`], so you only
21 /// need to call this directly if you don't have access to an Android Context
22 /// (e.g., in `JNI_OnLoad`).
23 ///
24 /// This function is idempotent - safe to call multiple times.
25 pub fn initialize_android(vm: &jni::JavaVM) {
26 unsafe {
27 sys_android::init_android(vm.get_java_vm_pointer() as *mut _);
28 }
29 }
30
31 /// Initialize Android WebRTC with the application context.
32 ///
33 /// This is the main initialization function for Android. It performs both:
34 /// 1. JVM initialization (same as [`initialize_android`])
35 /// 2. Context initialization (required for PlatformAudio)
36 ///
37 /// This function is idempotent - safe to call multiple times.
38 ///
39 /// # Arguments
40 /// * `vm` - The JavaVM instance
41 /// * `context` - The Android application context
42 ///
43 /// # Returns
44 /// `true` if context initialization succeeded, `false` otherwise.
45 /// Note: JVM initialization always happens regardless of return value.
46 ///
47 /// # Example
48 /// ```ignore
49 /// use jni::JavaVM;
50 /// use jni::objects::JObject;
51 /// use livekit::webrtc::android::initialize_android_context;
52 ///
53 /// fn init(vm: JavaVM, context: JObject) {
54 /// // Just one call needed - handles both JVM and context init
55 /// initialize_android_context(&vm, &context);
56 /// }
57 /// ```
58 pub fn initialize_android_context(vm: &jni::JavaVM, context: &JObject) -> bool {
59 unsafe {
60 sys_android::init_android_context(
61 vm.get_java_vm_pointer() as *mut _,
62 context.as_raw() as usize,
63 )
64 }
65 }
@@ -0,0 +1,65 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use jni::objects::JObject;
16use webrtc_sys::android::ffi as sys_android;
17
18/// Initialize Android WebRTC with the JVM.
19///
20/// This is automatically called by [`initialize_android_context`], so you only
21/// need to call this directly if you don't have access to an Android Context
22/// (e.g., in `JNI_OnLoad`).
23///
24/// This function is idempotent - safe to call multiple times.
25pub fn initialize_android(vm: &jni::JavaVM) {
26 unsafe {
27 sys_android::init_android(vm.get_java_vm_pointer() as *mut _);
28 }
29}
30
31/// Initialize Android WebRTC with the application context.
32///
33/// This is the main initialization function for Android. It performs both:
34/// 1. JVM initialization (same as [`initialize_android`])
35/// 2. Context initialization (required for PlatformAudio)
36///
37/// This function is idempotent - safe to call multiple times.
38///
39/// # Arguments
40/// * `vm` - The JavaVM instance
41/// * `context` - The Android application context
42///
43/// # Returns
44/// `true` if context initialization succeeded, `false` otherwise.
45/// Note: JVM initialization always happens regardless of return value.
46///
47/// # Example
48/// ```ignore
49/// use jni::JavaVM;
50/// use jni::objects::JObject;
51/// use livekit::webrtc::android::initialize_android_context;
52///
53/// fn init(vm: JavaVM, context: JObject) {
54/// // Just one call needed - handles both JVM and context init
55/// initialize_android_context(&vm, &context);
56/// }
57/// ```
58pub fn initialize_android_context(vm: &jni::JavaVM, context: &JObject) -> bool {
59 unsafe {
60 sys_android::init_android_context(
61 vm.get_java_vm_pointer() as *mut _,
62 context.as_raw() as usize,
63 )
64 }
65}
vendor/libwebrtc/src/native/apm.rs added +119 −0
@@ -0,0 +1,119 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::UniquePtr;
16 use webrtc_sys::apm::ffi as sys_apm;
17
18 use crate::{RtcError, RtcErrorType};
19
20 pub struct AudioProcessingModule {
21 sys_handle: UniquePtr<sys_apm::AudioProcessingModule>,
22 }
23
24 impl AudioProcessingModule {
25 pub fn new(
26 echo_canceller_enabled: bool,
27 gain_controller_enabled: bool,
28 high_pass_filter_enabled: bool,
29 noise_suppression_enabled: bool,
30 ) -> Self {
31 Self {
32 sys_handle: sys_apm::create_apm(
33 echo_canceller_enabled,
34 gain_controller_enabled,
35 high_pass_filter_enabled,
36 noise_suppression_enabled,
37 ),
38 }
39 }
40
41 pub fn process_stream(
42 &mut self,
43 data: &mut [i16],
44 sample_rate: i32,
45 num_channels: i32,
46 ) -> Result<(), RtcError> {
47 let samples_per_10ms = (sample_rate as usize / 100) * num_channels as usize;
48 assert!(
49 data.len() % samples_per_10ms == 0 && data.len() >= samples_per_10ms,
50 "slice must have a multiple of 10ms worth of samples"
51 );
52
53 for chunk in data.chunks_mut(samples_per_10ms) {
54 if unsafe {
55 self.sys_handle.pin_mut().process_stream(
56 chunk.as_mut_ptr(),
57 chunk.len(),
58 chunk.as_mut_ptr(),
59 chunk.len(),
60 sample_rate,
61 num_channels,
62 )
63 } != 0
64 {
65 return Err(RtcError {
66 error_type: RtcErrorType::Internal,
67 message: "Failed to process stream".to_string(),
68 });
69 }
70 }
71
72 Ok(())
73 }
74
75 pub fn process_reverse_stream(
76 &mut self,
77 data: &mut [i16],
78 sample_rate: i32,
79 num_channels: i32,
80 ) -> Result<(), RtcError> {
81 let samples_per_10ms = (sample_rate as usize / 100) * num_channels as usize;
82 assert!(
83 data.len() % samples_per_10ms == 0 && data.len() >= samples_per_10ms,
84 "slice must have a multiple of 10ms worth of samples"
85 );
86
87 for chunk in data.chunks_mut(samples_per_10ms) {
88 if unsafe {
89 self.sys_handle.pin_mut().process_reverse_stream(
90 chunk.as_mut_ptr(),
91 chunk.len(),
92 chunk.as_mut_ptr(),
93 chunk.len(),
94 sample_rate,
95 num_channels,
96 )
97 } != 0
98 {
99 return Err(RtcError {
100 error_type: RtcErrorType::Internal,
101 message: "Failed to process reverse stream".to_string(),
102 });
103 }
104 }
105
106 Ok(())
107 }
108
109 pub fn set_stream_delay_ms(&mut self, delay_ms: i32) -> Result<(), RtcError> {
110 if self.sys_handle.pin_mut().set_stream_delay_ms(delay_ms) == 0 {
111 Ok(())
112 } else {
113 Err(RtcError {
114 error_type: RtcErrorType::Internal,
115 message: "Failed to set stream delay".to_string(),
116 })
117 }
118 }
119 }
@@ -0,0 +1,119 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::UniquePtr;
16use webrtc_sys::apm::ffi as sys_apm;
17
18use crate::{RtcError, RtcErrorType};
19
20pub struct AudioProcessingModule {
21 sys_handle: UniquePtr<sys_apm::AudioProcessingModule>,
22}
23
24impl AudioProcessingModule {
25 pub fn new(
26 echo_canceller_enabled: bool,
27 gain_controller_enabled: bool,
28 high_pass_filter_enabled: bool,
29 noise_suppression_enabled: bool,
30 ) -> Self {
31 Self {
32 sys_handle: sys_apm::create_apm(
33 echo_canceller_enabled,
34 gain_controller_enabled,
35 high_pass_filter_enabled,
36 noise_suppression_enabled,
37 ),
38 }
39 }
40
41 pub fn process_stream(
42 &mut self,
43 data: &mut [i16],
44 sample_rate: i32,
45 num_channels: i32,
46 ) -> Result<(), RtcError> {
47 let samples_per_10ms = (sample_rate as usize / 100) * num_channels as usize;
48 assert!(
49 data.len() % samples_per_10ms == 0 && data.len() >= samples_per_10ms,
50 "slice must have a multiple of 10ms worth of samples"
51 );
52
53 for chunk in data.chunks_mut(samples_per_10ms) {
54 if unsafe {
55 self.sys_handle.pin_mut().process_stream(
56 chunk.as_mut_ptr(),
57 chunk.len(),
58 chunk.as_mut_ptr(),
59 chunk.len(),
60 sample_rate,
61 num_channels,
62 )
63 } != 0
64 {
65 return Err(RtcError {
66 error_type: RtcErrorType::Internal,
67 message: "Failed to process stream".to_string(),
68 });
69 }
70 }
71
72 Ok(())
73 }
74
75 pub fn process_reverse_stream(
76 &mut self,
77 data: &mut [i16],
78 sample_rate: i32,
79 num_channels: i32,
80 ) -> Result<(), RtcError> {
81 let samples_per_10ms = (sample_rate as usize / 100) * num_channels as usize;
82 assert!(
83 data.len() % samples_per_10ms == 0 && data.len() >= samples_per_10ms,
84 "slice must have a multiple of 10ms worth of samples"
85 );
86
87 for chunk in data.chunks_mut(samples_per_10ms) {
88 if unsafe {
89 self.sys_handle.pin_mut().process_reverse_stream(
90 chunk.as_mut_ptr(),
91 chunk.len(),
92 chunk.as_mut_ptr(),
93 chunk.len(),
94 sample_rate,
95 num_channels,
96 )
97 } != 0
98 {
99 return Err(RtcError {
100 error_type: RtcErrorType::Internal,
101 message: "Failed to process reverse stream".to_string(),
102 });
103 }
104 }
105
106 Ok(())
107 }
108
109 pub fn set_stream_delay_ms(&mut self, delay_ms: i32) -> Result<(), RtcError> {
110 if self.sys_handle.pin_mut().set_stream_delay_ms(delay_ms) == 0 {
111 Ok(())
112 } else {
113 Err(RtcError {
114 error_type: RtcErrorType::Internal,
115 message: "Failed to set stream delay".to_string(),
116 })
117 }
118 }
119}
vendor/libwebrtc/src/native/audio_mixer.rs added +108 −0
@@ -0,0 +1,108 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use crate::audio_frame::AudioFrame;
16 use cxx::UniquePtr;
17 use std::sync::Arc;
18 use webrtc_sys::audio_mixer as sys;
19 use webrtc_sys::audio_mixer::ffi;
20
21 pub struct AudioMixer {
22 sys_handle: UniquePtr<ffi::AudioMixer>,
23 }
24
25 pub use ffi::AudioFrameInfo;
26
27 pub trait AudioMixerSource {
28 fn ssrc(&self) -> i32;
29 fn preferred_sample_rate(&self) -> u32;
30 fn get_audio_frame_with_info(&self, target_sample_rate: u32) -> Option<AudioFrame<'_>>;
31 }
32
33 struct AudioMixerSourceImpl<T> {
34 inner: T,
35 }
36 impl<T: AudioMixerSource> sys::AudioMixerSource for AudioMixerSourceImpl<T> {
37 fn ssrc(&self) -> i32 {
38 self.inner.ssrc()
39 }
40
41 fn preferred_sample_rate(&self) -> i32 {
42 self.inner.preferred_sample_rate() as i32
43 }
44
45 fn get_audio_frame_with_info(
46 &self,
47 target_sample_rate: i32,
48 native_frame: sys::NativeAudioFrame,
49 ) -> AudioFrameInfo {
50 if let Some(frame) = self.inner.get_audio_frame_with_info(target_sample_rate as u32) {
51 let samples_count = (frame.sample_rate as usize / 100) as usize;
52 assert_eq!(
53 frame.sample_rate, target_sample_rate as u32,
54 "sample rate must match target_sample_rate"
55 );
56 assert_eq!(
57 frame.samples_per_channel as usize, samples_count,
58 "frame must contain 10ms of samples"
59 );
60 assert_eq!(
61 frame.data.len(),
62 samples_count * frame.num_channels as usize,
63 "slice must contain 10ms of samples"
64 );
65
66 unsafe {
67 native_frame.update_frame(
68 0,
69 frame.data.as_ptr(),
70 frame.samples_per_channel as usize,
71 frame.sample_rate as i32,
72 frame.num_channels as usize,
73 );
74 }
75 return ffi::AudioFrameInfo::Normal;
76 } else {
77 return ffi::AudioFrameInfo::Muted;
78 }
79 }
80 }
81
82 impl AudioMixer {
83 pub fn new() -> Self {
84 let sys_handle = ffi::create_audio_mixer();
85 Self { sys_handle }
86 }
87
88 pub fn add_source(&mut self, source: impl AudioMixerSource + 'static) {
89 let source_impl = AudioMixerSourceImpl { inner: source };
90 let wrapper = Box::new(sys::AudioMixerSourceWrapper::new(Arc::new(source_impl)));
91 unsafe {
92 self.sys_handle.pin_mut().add_source(wrapper);
93 }
94 }
95
96 pub fn remove_source(&mut self, ssrc: i32) {
97 unsafe {
98 self.sys_handle.pin_mut().remove_source(ssrc);
99 }
100 }
101
102 pub fn mix(&mut self, num_channels: usize) -> &[i16] {
103 unsafe {
104 let len = self.sys_handle.pin_mut().mix(num_channels);
105 std::slice::from_raw_parts(self.sys_handle.data(), len)
106 }
107 }
108 }
@@ -0,0 +1,108 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::audio_frame::AudioFrame;
16use cxx::UniquePtr;
17use std::sync::Arc;
18use webrtc_sys::audio_mixer as sys;
19use webrtc_sys::audio_mixer::ffi;
20
21pub struct AudioMixer {
22 sys_handle: UniquePtr<ffi::AudioMixer>,
23}
24
25pub use ffi::AudioFrameInfo;
26
27pub trait AudioMixerSource {
28 fn ssrc(&self) -> i32;
29 fn preferred_sample_rate(&self) -> u32;
30 fn get_audio_frame_with_info(&self, target_sample_rate: u32) -> Option<AudioFrame<'_>>;
31}
32
33struct AudioMixerSourceImpl<T> {
34 inner: T,
35}
36impl<T: AudioMixerSource> sys::AudioMixerSource for AudioMixerSourceImpl<T> {
37 fn ssrc(&self) -> i32 {
38 self.inner.ssrc()
39 }
40
41 fn preferred_sample_rate(&self) -> i32 {
42 self.inner.preferred_sample_rate() as i32
43 }
44
45 fn get_audio_frame_with_info(
46 &self,
47 target_sample_rate: i32,
48 native_frame: sys::NativeAudioFrame,
49 ) -> AudioFrameInfo {
50 if let Some(frame) = self.inner.get_audio_frame_with_info(target_sample_rate as u32) {
51 let samples_count = (frame.sample_rate as usize / 100) as usize;
52 assert_eq!(
53 frame.sample_rate, target_sample_rate as u32,
54 "sample rate must match target_sample_rate"
55 );
56 assert_eq!(
57 frame.samples_per_channel as usize, samples_count,
58 "frame must contain 10ms of samples"
59 );
60 assert_eq!(
61 frame.data.len(),
62 samples_count * frame.num_channels as usize,
63 "slice must contain 10ms of samples"
64 );
65
66 unsafe {
67 native_frame.update_frame(
68 0,
69 frame.data.as_ptr(),
70 frame.samples_per_channel as usize,
71 frame.sample_rate as i32,
72 frame.num_channels as usize,
73 );
74 }
75 return ffi::AudioFrameInfo::Normal;
76 } else {
77 return ffi::AudioFrameInfo::Muted;
78 }
79 }
80}
81
82impl AudioMixer {
83 pub fn new() -> Self {
84 let sys_handle = ffi::create_audio_mixer();
85 Self { sys_handle }
86 }
87
88 pub fn add_source(&mut self, source: impl AudioMixerSource + 'static) {
89 let source_impl = AudioMixerSourceImpl { inner: source };
90 let wrapper = Box::new(sys::AudioMixerSourceWrapper::new(Arc::new(source_impl)));
91 unsafe {
92 self.sys_handle.pin_mut().add_source(wrapper);
93 }
94 }
95
96 pub fn remove_source(&mut self, ssrc: i32) {
97 unsafe {
98 self.sys_handle.pin_mut().remove_source(ssrc);
99 }
100 }
101
102 pub fn mix(&mut self, num_channels: usize) -> &[i16] {
103 unsafe {
104 let len = self.sys_handle.pin_mut().mix(num_channels);
105 std::slice::from_raw_parts(self.sys_handle.data(), len)
106 }
107 }
108}
vendor/libwebrtc/src/native/audio_resampler.rs added +53 −0
@@ -0,0 +1,53 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::UniquePtr;
16 use webrtc_sys::audio_resampler as sys_ar;
17
18 pub struct AudioResampler {
19 sys_handle: UniquePtr<sys_ar::ffi::AudioResampler>,
20 }
21
22 impl Default for AudioResampler {
23 fn default() -> Self {
24 Self { sys_handle: sys_ar::ffi::create_audio_resampler() }
25 }
26 }
27
28 impl AudioResampler {
29 pub fn remix_and_resample<'a>(
30 &'a mut self,
31 src: &[i16],
32 samples_per_channel: u32,
33 num_channels: u32,
34 sample_rate: u32,
35 dst_num_channels: u32,
36 dst_sample_rate: u32,
37 ) -> &'a [i16] {
38 assert!(src.len() >= (samples_per_channel * num_channels) as usize, "src buffer too small");
39
40 unsafe {
41 let len = self.sys_handle.pin_mut().remix_and_resample(
42 src.as_ptr(),
43 samples_per_channel as usize,
44 num_channels as usize,
45 sample_rate as i32,
46 dst_num_channels as usize,
47 dst_sample_rate as i32,
48 );
49
50 std::slice::from_raw_parts(self.sys_handle.data(), len / 2)
51 }
52 }
53 }
@@ -0,0 +1,53 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::UniquePtr;
16use webrtc_sys::audio_resampler as sys_ar;
17
18pub struct AudioResampler {
19 sys_handle: UniquePtr<sys_ar::ffi::AudioResampler>,
20}
21
22impl Default for AudioResampler {
23 fn default() -> Self {
24 Self { sys_handle: sys_ar::ffi::create_audio_resampler() }
25 }
26}
27
28impl AudioResampler {
29 pub fn remix_and_resample<'a>(
30 &'a mut self,
31 src: &[i16],
32 samples_per_channel: u32,
33 num_channels: u32,
34 sample_rate: u32,
35 dst_num_channels: u32,
36 dst_sample_rate: u32,
37 ) -> &'a [i16] {
38 assert!(src.len() >= (samples_per_channel * num_channels) as usize, "src buffer too small");
39
40 unsafe {
41 let len = self.sys_handle.pin_mut().remix_and_resample(
42 src.as_ptr(),
43 samples_per_channel as usize,
44 num_channels as usize,
45 sample_rate as i32,
46 dst_num_channels as usize,
47 dst_sample_rate as i32,
48 );
49
50 std::slice::from_raw_parts(self.sys_handle.data(), len / 2)
51 }
52 }
53}
vendor/libwebrtc/src/native/audio_source.rs added +205 −0
@@ -0,0 +1,205 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::SharedPtr;
16 use tokio::sync::oneshot;
17 use webrtc_sys::audio_track as sys_at;
18
19 use crate::{audio_frame::AudioFrame, audio_source::AudioSourceOptions, RtcError, RtcErrorType};
20
21 #[derive(Clone)]
22 pub struct NativeAudioSource {
23 sys_handle: SharedPtr<sys_at::ffi::AudioTrackSource>,
24 sample_rate: u32,
25 num_channels: u32,
26 queue_size_samples: u32,
27 }
28
29 impl NativeAudioSource {
30 /// Creates a new [`NativeAudioSource`].
31 ///
32 /// # Arguments
33 /// * `options` – Configuration options for the source (e.g. echo cancellation, noise suppression).
34 /// * `sample_rate` – Sampling rate in Hz (for example, `48000`).
35 /// * `num_channels` – Number of audio channels (`1` for mono, `2` for stereo, etc.).
36 /// * `queue_size_ms` – Size of the internal buffering queue, in milliseconds.
37 ///
38 /// # Behavior
39 /// - If `queue_size_ms` is **zero**, buffering is **disabled** and audio frames are
40 /// delivered directly to webrtc sinks. In this mode, the caller **must provide 10 ms frames**
41 /// (i.e., `sample_rate / 100` samples per channel) when calling [`capture_frame`].
42 /// - If `queue_size_ms` is **non-zero**, buffering is enabled. The value must be a
43 /// **multiple of 10**, representing the total buffering duration in milliseconds.
44 /// Frames will be queued and flushed to sinks asynchronously once the buffer
45 /// reaches the configured threshold.
46 ///
47 /// # Panics
48 /// assert if `queue_size_ms` is not a multiple of 10.
49 pub fn new(
50 options: AudioSourceOptions,
51 sample_rate: u32,
52 num_channels: u32,
53 queue_size_ms: u32,
54 ) -> NativeAudioSource {
55 assert!(queue_size_ms % 10 == 0, "queue_size_ms must be a multiple of 10");
56
57 let sys_handle = sys_at::ffi::new_audio_track_source(
58 options.into(),
59 sample_rate.try_into().unwrap(),
60 num_channels.try_into().unwrap(),
61 queue_size_ms.try_into().unwrap(),
62 );
63
64 let queue_size_samples = (queue_size_ms * sample_rate * num_channels) / 1000;
65 Self { sys_handle, sample_rate, num_channels, queue_size_samples }
66 }
67
68 pub fn sys_handle(&self) -> SharedPtr<sys_at::ffi::AudioTrackSource> {
69 self.sys_handle.clone()
70 }
71
72 pub fn set_audio_options(&self, options: AudioSourceOptions) {
73 self.sys_handle.set_audio_options(&sys_at::ffi::AudioSourceOptions::from(options))
74 }
75
76 pub fn audio_options(&self) -> AudioSourceOptions {
77 self.sys_handle.audio_options().into()
78 }
79
80 pub fn sample_rate(&self) -> u32 {
81 self.sample_rate
82 }
83
84 pub fn num_channels(&self) -> u32 {
85 self.num_channels
86 }
87
88 pub fn clear_buffer(&self) {
89 self.sys_handle.clear_buffer();
90 }
91
92 pub async fn capture_frame(&self, frame: &AudioFrame<'_>) -> Result<(), RtcError> {
93 if self.sample_rate != frame.sample_rate || self.num_channels != frame.num_channels {
94 return Err(RtcError {
95 error_type: RtcErrorType::InvalidState,
96 message: "sample_rate and num_channels don't match".to_owned(),
97 });
98 }
99
100 // Fast path: no buffering
101 if self.queue_size_samples == 0 {
102 // frame size must be 10ms for fast path
103 let expected_frames_per_ch = (self.sample_rate / 100) as usize;
104 if frame.data.len() % (self.num_channels as usize) != 0 {
105 return Err(RtcError {
106 error_type: RtcErrorType::InvalidState,
107 message: "frame.data length not divisible by channel count".to_owned(),
108 });
109 }
110 let nb_frames = frame.data.len() / (self.num_channels as usize);
111 if nb_frames != expected_frames_per_ch {
112 return Err(RtcError {
113 error_type: RtcErrorType::InvalidState,
114 message: format!(
115 "direct capture requires 10ms frames: got {} frames, expected {}",
116 nb_frames, expected_frames_per_ch
117 ),
118 });
119 }
120
121 // Define a no-op callback for fast path (queue_size_ms=0)
122 // This is safer than passing null, which can cause UB in release mode optimizations
123 extern "C" fn noop_complete_callback(_ctx: *const sys_at::SourceContext) {
124 // No-op: fast path completes synchronously, no callback needed
125 }
126
127 unsafe {
128 let data: &[i16] = frame.data.as_ref();
129 // Use a valid no-op callback instead of null for safety
130 // In release mode, transmuting null pointers can cause UB
131 let noop_callback = sys_at::CompleteCallback(noop_complete_callback);
132 let ok = self.sys_handle.capture_frame(
133 data,
134 self.sample_rate,
135 self.num_channels,
136 nb_frames,
137 std::ptr::null(), // Context is still null - callback won't use it
138 noop_callback,
139 );
140 if !ok {
141 return Err(RtcError {
142 error_type: RtcErrorType::InvalidState,
143 message: "failed to capture frame without buffering".to_owned(),
144 });
145 }
146 }
147 return Ok(());
148 }
149
150 // Buffered path.
151 extern "C" fn lk_audio_source_complete(userdata: *const sys_at::SourceContext) {
152 let tx = unsafe { Box::from_raw(userdata as *mut oneshot::Sender<()>) };
153 let _ = tx.send(());
154 }
155
156 // iterate over chunks of self._queue_size_samples
157 for chunk in frame.data.chunks(self.queue_size_samples as usize) {
158 let nb_frames = chunk.len() / self.num_channels as usize;
159 let (tx, rx) = oneshot::channel::<()>();
160 let ctx = Box::new(tx);
161 let ctx_ptr = Box::into_raw(ctx) as *const sys_at::SourceContext;
162
163 unsafe {
164 // In the fast path, C++ never store / invoke on_complete / ctx.
165 if !self.sys_handle.capture_frame(
166 chunk,
167 self.sample_rate,
168 self.num_channels,
169 nb_frames,
170 ctx_ptr,
171 sys_at::CompleteCallback(lk_audio_source_complete),
172 ) {
173 return Err(RtcError {
174 error_type: RtcErrorType::InvalidState,
175 message: "failed to capture frame".to_owned(),
176 });
177 }
178 }
179
180 let _ = rx.await;
181 }
182
183 Ok(())
184 }
185 }
186
187 impl From<sys_at::ffi::AudioSourceOptions> for AudioSourceOptions {
188 fn from(options: sys_at::ffi::AudioSourceOptions) -> Self {
189 Self {
190 echo_cancellation: options.echo_cancellation,
191 noise_suppression: options.noise_suppression,
192 auto_gain_control: options.auto_gain_control,
193 }
194 }
195 }
196
197 impl From<AudioSourceOptions> for sys_at::ffi::AudioSourceOptions {
198 fn from(options: AudioSourceOptions) -> Self {
199 Self {
200 echo_cancellation: options.echo_cancellation,
201 noise_suppression: options.noise_suppression,
202 auto_gain_control: options.auto_gain_control,
203 }
204 }
205 }
@@ -0,0 +1,205 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::SharedPtr;
16use tokio::sync::oneshot;
17use webrtc_sys::audio_track as sys_at;
18
19use crate::{audio_frame::AudioFrame, audio_source::AudioSourceOptions, RtcError, RtcErrorType};
20
21#[derive(Clone)]
22pub struct NativeAudioSource {
23 sys_handle: SharedPtr<sys_at::ffi::AudioTrackSource>,
24 sample_rate: u32,
25 num_channels: u32,
26 queue_size_samples: u32,
27}
28
29impl NativeAudioSource {
30 /// Creates a new [`NativeAudioSource`].
31 ///
32 /// # Arguments
33 /// * `options` – Configuration options for the source (e.g. echo cancellation, noise suppression).
34 /// * `sample_rate` – Sampling rate in Hz (for example, `48000`).
35 /// * `num_channels` – Number of audio channels (`1` for mono, `2` for stereo, etc.).
36 /// * `queue_size_ms` – Size of the internal buffering queue, in milliseconds.
37 ///
38 /// # Behavior
39 /// - If `queue_size_ms` is **zero**, buffering is **disabled** and audio frames are
40 /// delivered directly to webrtc sinks. In this mode, the caller **must provide 10 ms frames**
41 /// (i.e., `sample_rate / 100` samples per channel) when calling [`capture_frame`].
42 /// - If `queue_size_ms` is **non-zero**, buffering is enabled. The value must be a
43 /// **multiple of 10**, representing the total buffering duration in milliseconds.
44 /// Frames will be queued and flushed to sinks asynchronously once the buffer
45 /// reaches the configured threshold.
46 ///
47 /// # Panics
48 /// assert if `queue_size_ms` is not a multiple of 10.
49 pub fn new(
50 options: AudioSourceOptions,
51 sample_rate: u32,
52 num_channels: u32,
53 queue_size_ms: u32,
54 ) -> NativeAudioSource {
55 assert!(queue_size_ms % 10 == 0, "queue_size_ms must be a multiple of 10");
56
57 let sys_handle = sys_at::ffi::new_audio_track_source(
58 options.into(),
59 sample_rate.try_into().unwrap(),
60 num_channels.try_into().unwrap(),
61 queue_size_ms.try_into().unwrap(),
62 );
63
64 let queue_size_samples = (queue_size_ms * sample_rate * num_channels) / 1000;
65 Self { sys_handle, sample_rate, num_channels, queue_size_samples }
66 }
67
68 pub fn sys_handle(&self) -> SharedPtr<sys_at::ffi::AudioTrackSource> {
69 self.sys_handle.clone()
70 }
71
72 pub fn set_audio_options(&self, options: AudioSourceOptions) {
73 self.sys_handle.set_audio_options(&sys_at::ffi::AudioSourceOptions::from(options))
74 }
75
76 pub fn audio_options(&self) -> AudioSourceOptions {
77 self.sys_handle.audio_options().into()
78 }
79
80 pub fn sample_rate(&self) -> u32 {
81 self.sample_rate
82 }
83
84 pub fn num_channels(&self) -> u32 {
85 self.num_channels
86 }
87
88 pub fn clear_buffer(&self) {
89 self.sys_handle.clear_buffer();
90 }
91
92 pub async fn capture_frame(&self, frame: &AudioFrame<'_>) -> Result<(), RtcError> {
93 if self.sample_rate != frame.sample_rate || self.num_channels != frame.num_channels {
94 return Err(RtcError {
95 error_type: RtcErrorType::InvalidState,
96 message: "sample_rate and num_channels don't match".to_owned(),
97 });
98 }
99
100 // Fast path: no buffering
101 if self.queue_size_samples == 0 {
102 // frame size must be 10ms for fast path
103 let expected_frames_per_ch = (self.sample_rate / 100) as usize;
104 if frame.data.len() % (self.num_channels as usize) != 0 {
105 return Err(RtcError {
106 error_type: RtcErrorType::InvalidState,
107 message: "frame.data length not divisible by channel count".to_owned(),
108 });
109 }
110 let nb_frames = frame.data.len() / (self.num_channels as usize);
111 if nb_frames != expected_frames_per_ch {
112 return Err(RtcError {
113 error_type: RtcErrorType::InvalidState,
114 message: format!(
115 "direct capture requires 10ms frames: got {} frames, expected {}",
116 nb_frames, expected_frames_per_ch
117 ),
118 });
119 }
120
121 // Define a no-op callback for fast path (queue_size_ms=0)
122 // This is safer than passing null, which can cause UB in release mode optimizations
123 extern "C" fn noop_complete_callback(_ctx: *const sys_at::SourceContext) {
124 // No-op: fast path completes synchronously, no callback needed
125 }
126
127 unsafe {
128 let data: &[i16] = frame.data.as_ref();
129 // Use a valid no-op callback instead of null for safety
130 // In release mode, transmuting null pointers can cause UB
131 let noop_callback = sys_at::CompleteCallback(noop_complete_callback);
132 let ok = self.sys_handle.capture_frame(
133 data,
134 self.sample_rate,
135 self.num_channels,
136 nb_frames,
137 std::ptr::null(), // Context is still null - callback won't use it
138 noop_callback,
139 );
140 if !ok {
141 return Err(RtcError {
142 error_type: RtcErrorType::InvalidState,
143 message: "failed to capture frame without buffering".to_owned(),
144 });
145 }
146 }
147 return Ok(());
148 }
149
150 // Buffered path.
151 extern "C" fn lk_audio_source_complete(userdata: *const sys_at::SourceContext) {
152 let tx = unsafe { Box::from_raw(userdata as *mut oneshot::Sender<()>) };
153 let _ = tx.send(());
154 }
155
156 // iterate over chunks of self._queue_size_samples
157 for chunk in frame.data.chunks(self.queue_size_samples as usize) {
158 let nb_frames = chunk.len() / self.num_channels as usize;
159 let (tx, rx) = oneshot::channel::<()>();
160 let ctx = Box::new(tx);
161 let ctx_ptr = Box::into_raw(ctx) as *const sys_at::SourceContext;
162
163 unsafe {
164 // In the fast path, C++ never store / invoke on_complete / ctx.
165 if !self.sys_handle.capture_frame(
166 chunk,
167 self.sample_rate,
168 self.num_channels,
169 nb_frames,
170 ctx_ptr,
171 sys_at::CompleteCallback(lk_audio_source_complete),
172 ) {
173 return Err(RtcError {
174 error_type: RtcErrorType::InvalidState,
175 message: "failed to capture frame".to_owned(),
176 });
177 }
178 }
179
180 let _ = rx.await;
181 }
182
183 Ok(())
184 }
185}
186
187impl From<sys_at::ffi::AudioSourceOptions> for AudioSourceOptions {
188 fn from(options: sys_at::ffi::AudioSourceOptions) -> Self {
189 Self {
190 echo_cancellation: options.echo_cancellation,
191 noise_suppression: options.noise_suppression,
192 auto_gain_control: options.auto_gain_control,
193 }
194 }
195}
196
197impl From<AudioSourceOptions> for sys_at::ffi::AudioSourceOptions {
198 fn from(options: AudioSourceOptions) -> Self {
199 Self {
200 echo_cancellation: options.echo_cancellation,
201 noise_suppression: options.noise_suppression,
202 auto_gain_control: options.auto_gain_control,
203 }
204 }
205}
vendor/libwebrtc/src/native/audio_stream.rs added +314 −0
@@ -0,0 +1,314 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::{
16 collections::VecDeque,
17 pin::Pin,
18 sync::{
19 atomic::{AtomicBool, AtomicU64, Ordering},
20 Arc,
21 },
22 task::{Context, Poll, Waker},
23 };
24
25 use cxx::SharedPtr;
26 use parking_lot::Mutex;
27 use rtrb::{Consumer, Producer, PushError, RingBuffer};
28 use tokio_stream::Stream;
29 use webrtc_sys::audio_track as sys_at;
30
31 use crate::{audio_frame::AudioFrame, audio_track::RtcAudioTrack};
32
33 pub struct NativeAudioStream {
34 native_sink: SharedPtr<sys_at::ffi::NativeAudioSink>,
35 audio_track: RtcAudioTrack,
36 frame_queue: Arc<AudioFrameQueue>,
37 }
38
39 impl NativeAudioStream {
40 pub fn new(
41 audio_track: RtcAudioTrack,
42 sample_rate: i32,
43 num_channels: i32,
44 queue_size_frames: Option<usize>,
45 ) -> Self {
46 let frame_queue = Arc::new(AudioFrameQueue::new(queue_size_frames));
47 let observer = Arc::new(AudioTrackObserver { frame_queue: frame_queue.clone() });
48 let native_sink = sys_at::ffi::new_native_audio_sink(
49 Box::new(sys_at::AudioSinkWrapper::new(observer.clone())),
50 sample_rate,
51 num_channels,
52 );
53
54 let audio = unsafe { sys_at::ffi::media_to_audio(audio_track.sys_handle()) };
55 audio.add_sink(&native_sink);
56
57 Self { native_sink, audio_track, frame_queue }
58 }
59
60 pub fn track(&self) -> RtcAudioTrack {
61 self.audio_track.clone()
62 }
63
64 pub fn close(&mut self) {
65 let audio = unsafe { sys_at::ffi::media_to_audio(self.audio_track.sys_handle()) };
66 audio.remove_sink(&self.native_sink);
67
68 self.frame_queue.close();
69 }
70 }
71
72 impl Drop for NativeAudioStream {
73 fn drop(&mut self) {
74 self.close();
75 }
76 }
77
78 impl Stream for NativeAudioStream {
79 type Item = AudioFrame<'static>;
80
81 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
82 self.frame_queue.poll_recv(cx)
83 }
84 }
85
86 pub struct AudioTrackObserver {
87 frame_queue: Arc<AudioFrameQueue>,
88 }
89
90 impl sys_at::AudioSink for AudioTrackObserver {
91 fn on_data(&self, data: &[i16], sample_rate: i32, nb_channels: usize, nb_frames: usize) {
92 self.frame_queue.push(AudioFrame {
93 data: data.to_owned().into(),
94 sample_rate: sample_rate as u32,
95 num_channels: nb_channels as u32,
96 samples_per_channel: nb_frames as u32,
97 });
98 }
99 }
100
101 struct AudioFrameQueue {
102 kind: AudioFrameQueueKind,
103 closed: AtomicBool,
104 dropped_frames: AtomicU64,
105 waker: Mutex<Option<Waker>>,
106 }
107
108 enum AudioFrameQueueKind {
109 Bounded(BoundedAudioFrameQueue),
110 Unbounded(UnboundedAudioFrameQueue),
111 }
112
113 struct BoundedAudioFrameQueue {
114 producer: Mutex<Producer<AudioFrame<'static>>>,
115 consumer: Mutex<Consumer<AudioFrame<'static>>>,
116 }
117
118 struct UnboundedAudioFrameQueue {
119 frames: Mutex<VecDeque<AudioFrame<'static>>>,
120 }
121
122 impl AudioFrameQueue {
123 fn new(capacity: Option<usize>) -> Self {
124 let kind = match capacity.filter(|capacity| *capacity > 0) {
125 Some(capacity) => {
126 let (producer, consumer) = RingBuffer::new(capacity);
127 AudioFrameQueueKind::Bounded(BoundedAudioFrameQueue {
128 producer: Mutex::new(producer),
129 consumer: Mutex::new(consumer),
130 })
131 }
132 None => AudioFrameQueueKind::Unbounded(UnboundedAudioFrameQueue {
133 frames: Mutex::new(VecDeque::new()),
134 }),
135 };
136
137 Self {
138 kind,
139 closed: AtomicBool::new(false),
140 dropped_frames: AtomicU64::new(0),
141 waker: Mutex::new(None),
142 }
143 }
144
145 fn push(&self, frame: AudioFrame<'static>) {
146 if self.closed.load(Ordering::Acquire) {
147 return;
148 }
149
150 match &self.kind {
151 AudioFrameQueueKind::Bounded(queue) => self.push_bounded(queue, frame),
152 AudioFrameQueueKind::Unbounded(queue) => {
153 queue.frames.lock().push_back(frame);
154 }
155 }
156
157 self.wake_receiver();
158 }
159
160 fn push_bounded(&self, queue: &BoundedAudioFrameQueue, mut frame: AudioFrame<'static>) {
161 loop {
162 let push_result = queue.producer.lock().push(frame);
163 match push_result {
164 Ok(()) => return,
165 Err(PushError::Full(returned_frame)) => {
166 frame = returned_frame;
167
168 let dropped = queue.consumer.lock().pop().is_ok();
169
170 if dropped {
171 self.record_drop();
172 } else {
173 return;
174 }
175 }
176 }
177 }
178 }
179
180 fn close(&self) {
181 self.closed.store(true, Ordering::Release);
182 self.wake_receiver();
183
184 match &self.kind {
185 AudioFrameQueueKind::Bounded(queue) => {
186 let mut consumer = queue.consumer.lock();
187 while consumer.pop().is_ok() {}
188 }
189 AudioFrameQueueKind::Unbounded(queue) => {
190 queue.frames.lock().clear();
191 }
192 }
193 }
194
195 fn poll_recv(&self, cx: &mut Context<'_>) -> Poll<Option<AudioFrame<'static>>> {
196 if let Some(frame) = self.try_pop() {
197 return Poll::Ready(Some(frame));
198 }
199
200 if self.closed.load(Ordering::Acquire) {
201 return Poll::Ready(None);
202 }
203
204 *self.waker.lock() = Some(cx.waker().clone());
205
206 if let Some(frame) = self.try_pop() {
207 self.waker.lock().take();
208 Poll::Ready(Some(frame))
209 } else if self.closed.load(Ordering::Acquire) {
210 Poll::Ready(None)
211 } else {
212 Poll::Pending
213 }
214 }
215
216 fn try_pop(&self) -> Option<AudioFrame<'static>> {
217 match &self.kind {
218 AudioFrameQueueKind::Bounded(queue) => queue.consumer.lock().pop().ok(),
219 AudioFrameQueueKind::Unbounded(queue) => queue.frames.lock().pop_front(),
220 }
221 }
222
223 fn wake_receiver(&self) {
224 let waker = self.waker.lock().take();
225 if let Some(waker) = waker {
226 waker.wake();
227 }
228 }
229
230 fn record_drop(&self) {
231 let dropped_frames = self.dropped_frames.fetch_add(1, Ordering::Relaxed) + 1;
232 if dropped_frames == 1 || dropped_frames % 100 == 0 {
233 log::warn!(
234 "native audio stream queue overflow; dropped {} queued frames",
235 dropped_frames
236 );
237 }
238 }
239 }
240
241 #[cfg(test)]
242 mod tests {
243 use std::sync::atomic::Ordering;
244
245 use super::AudioFrameQueue;
246 use crate::audio_frame::AudioFrame;
247
248 fn test_frame(marker: i16) -> AudioFrame<'static> {
249 AudioFrame {
250 data: vec![marker].into(),
251 sample_rate: 48_000,
252 num_channels: 1,
253 samples_per_channel: 1,
254 }
255 }
256
257 fn pop_marker(queue: &AudioFrameQueue) -> Option<i16> {
258 queue.try_pop().map(|frame| frame.data[0])
259 }
260
261 #[test]
262 fn bounded_queue_preserves_fifo_order_under_capacity() {
263 let queue = AudioFrameQueue::new(Some(3));
264
265 queue.push(test_frame(1));
266 queue.push(test_frame(2));
267 queue.push(test_frame(3));
268
269 assert_eq!(pop_marker(&queue), Some(1));
270 assert_eq!(pop_marker(&queue), Some(2));
271 assert_eq!(pop_marker(&queue), Some(3));
272 assert_eq!(pop_marker(&queue), None);
273 }
274
275 #[test]
276 fn bounded_queue_drops_oldest_when_full() {
277 let queue = AudioFrameQueue::new(Some(2));
278
279 queue.push(test_frame(1));
280 queue.push(test_frame(2));
281 queue.push(test_frame(3));
282
283 assert_eq!(queue.dropped_frames.load(Ordering::Relaxed), 1);
284 assert_eq!(pop_marker(&queue), Some(2));
285 assert_eq!(pop_marker(&queue), Some(3));
286 assert_eq!(pop_marker(&queue), None);
287 }
288
289 #[test]
290 fn unbounded_queue_retains_all_frames() {
291 let queue = AudioFrameQueue::new(None);
292
293 for marker in 1..=4 {
294 queue.push(test_frame(marker));
295 }
296
297 for marker in 1..=4 {
298 assert_eq!(pop_marker(&queue), Some(marker));
299 }
300 assert_eq!(pop_marker(&queue), None);
301 assert_eq!(queue.dropped_frames.load(Ordering::Relaxed), 0);
302 }
303
304 #[test]
305 fn close_clears_buffer_and_rejects_future_pushes() {
306 let queue = AudioFrameQueue::new(Some(2));
307
308 queue.push(test_frame(1));
309 queue.close();
310 queue.push(test_frame(2));
311
312 assert_eq!(pop_marker(&queue), None);
313 }
314 }
@@ -0,0 +1,314 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{
16 collections::VecDeque,
17 pin::Pin,
18 sync::{
19 atomic::{AtomicBool, AtomicU64, Ordering},
20 Arc,
21 },
22 task::{Context, Poll, Waker},
23};
24
25use cxx::SharedPtr;
26use parking_lot::Mutex;
27use rtrb::{Consumer, Producer, PushError, RingBuffer};
28use tokio_stream::Stream;
29use webrtc_sys::audio_track as sys_at;
30
31use crate::{audio_frame::AudioFrame, audio_track::RtcAudioTrack};
32
33pub struct NativeAudioStream {
34 native_sink: SharedPtr<sys_at::ffi::NativeAudioSink>,
35 audio_track: RtcAudioTrack,
36 frame_queue: Arc<AudioFrameQueue>,
37}
38
39impl NativeAudioStream {
40 pub fn new(
41 audio_track: RtcAudioTrack,
42 sample_rate: i32,
43 num_channels: i32,
44 queue_size_frames: Option<usize>,
45 ) -> Self {
46 let frame_queue = Arc::new(AudioFrameQueue::new(queue_size_frames));
47 let observer = Arc::new(AudioTrackObserver { frame_queue: frame_queue.clone() });
48 let native_sink = sys_at::ffi::new_native_audio_sink(
49 Box::new(sys_at::AudioSinkWrapper::new(observer.clone())),
50 sample_rate,
51 num_channels,
52 );
53
54 let audio = unsafe { sys_at::ffi::media_to_audio(audio_track.sys_handle()) };
55 audio.add_sink(&native_sink);
56
57 Self { native_sink, audio_track, frame_queue }
58 }
59
60 pub fn track(&self) -> RtcAudioTrack {
61 self.audio_track.clone()
62 }
63
64 pub fn close(&mut self) {
65 let audio = unsafe { sys_at::ffi::media_to_audio(self.audio_track.sys_handle()) };
66 audio.remove_sink(&self.native_sink);
67
68 self.frame_queue.close();
69 }
70}
71
72impl Drop for NativeAudioStream {
73 fn drop(&mut self) {
74 self.close();
75 }
76}
77
78impl Stream for NativeAudioStream {
79 type Item = AudioFrame<'static>;
80
81 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
82 self.frame_queue.poll_recv(cx)
83 }
84}
85
86pub struct AudioTrackObserver {
87 frame_queue: Arc<AudioFrameQueue>,
88}
89
90impl sys_at::AudioSink for AudioTrackObserver {
91 fn on_data(&self, data: &[i16], sample_rate: i32, nb_channels: usize, nb_frames: usize) {
92 self.frame_queue.push(AudioFrame {
93 data: data.to_owned().into(),
94 sample_rate: sample_rate as u32,
95 num_channels: nb_channels as u32,
96 samples_per_channel: nb_frames as u32,
97 });
98 }
99}
100
101struct AudioFrameQueue {
102 kind: AudioFrameQueueKind,
103 closed: AtomicBool,
104 dropped_frames: AtomicU64,
105 waker: Mutex<Option<Waker>>,
106}
107
108enum AudioFrameQueueKind {
109 Bounded(BoundedAudioFrameQueue),
110 Unbounded(UnboundedAudioFrameQueue),
111}
112
113struct BoundedAudioFrameQueue {
114 producer: Mutex<Producer<AudioFrame<'static>>>,
115 consumer: Mutex<Consumer<AudioFrame<'static>>>,
116}
117
118struct UnboundedAudioFrameQueue {
119 frames: Mutex<VecDeque<AudioFrame<'static>>>,
120}
121
122impl AudioFrameQueue {
123 fn new(capacity: Option<usize>) -> Self {
124 let kind = match capacity.filter(|capacity| *capacity > 0) {
125 Some(capacity) => {
126 let (producer, consumer) = RingBuffer::new(capacity);
127 AudioFrameQueueKind::Bounded(BoundedAudioFrameQueue {
128 producer: Mutex::new(producer),
129 consumer: Mutex::new(consumer),
130 })
131 }
132 None => AudioFrameQueueKind::Unbounded(UnboundedAudioFrameQueue {
133 frames: Mutex::new(VecDeque::new()),
134 }),
135 };
136
137 Self {
138 kind,
139 closed: AtomicBool::new(false),
140 dropped_frames: AtomicU64::new(0),
141 waker: Mutex::new(None),
142 }
143 }
144
145 fn push(&self, frame: AudioFrame<'static>) {
146 if self.closed.load(Ordering::Acquire) {
147 return;
148 }
149
150 match &self.kind {
151 AudioFrameQueueKind::Bounded(queue) => self.push_bounded(queue, frame),
152 AudioFrameQueueKind::Unbounded(queue) => {
153 queue.frames.lock().push_back(frame);
154 }
155 }
156
157 self.wake_receiver();
158 }
159
160 fn push_bounded(&self, queue: &BoundedAudioFrameQueue, mut frame: AudioFrame<'static>) {
161 loop {
162 let push_result = queue.producer.lock().push(frame);
163 match push_result {
164 Ok(()) => return,
165 Err(PushError::Full(returned_frame)) => {
166 frame = returned_frame;
167
168 let dropped = queue.consumer.lock().pop().is_ok();
169
170 if dropped {
171 self.record_drop();
172 } else {
173 return;
174 }
175 }
176 }
177 }
178 }
179
180 fn close(&self) {
181 self.closed.store(true, Ordering::Release);
182 self.wake_receiver();
183
184 match &self.kind {
185 AudioFrameQueueKind::Bounded(queue) => {
186 let mut consumer = queue.consumer.lock();
187 while consumer.pop().is_ok() {}
188 }
189 AudioFrameQueueKind::Unbounded(queue) => {
190 queue.frames.lock().clear();
191 }
192 }
193 }
194
195 fn poll_recv(&self, cx: &mut Context<'_>) -> Poll<Option<AudioFrame<'static>>> {
196 if let Some(frame) = self.try_pop() {
197 return Poll::Ready(Some(frame));
198 }
199
200 if self.closed.load(Ordering::Acquire) {
201 return Poll::Ready(None);
202 }
203
204 *self.waker.lock() = Some(cx.waker().clone());
205
206 if let Some(frame) = self.try_pop() {
207 self.waker.lock().take();
208 Poll::Ready(Some(frame))
209 } else if self.closed.load(Ordering::Acquire) {
210 Poll::Ready(None)
211 } else {
212 Poll::Pending
213 }
214 }
215
216 fn try_pop(&self) -> Option<AudioFrame<'static>> {
217 match &self.kind {
218 AudioFrameQueueKind::Bounded(queue) => queue.consumer.lock().pop().ok(),
219 AudioFrameQueueKind::Unbounded(queue) => queue.frames.lock().pop_front(),
220 }
221 }
222
223 fn wake_receiver(&self) {
224 let waker = self.waker.lock().take();
225 if let Some(waker) = waker {
226 waker.wake();
227 }
228 }
229
230 fn record_drop(&self) {
231 let dropped_frames = self.dropped_frames.fetch_add(1, Ordering::Relaxed) + 1;
232 if dropped_frames == 1 || dropped_frames % 100 == 0 {
233 log::warn!(
234 "native audio stream queue overflow; dropped {} queued frames",
235 dropped_frames
236 );
237 }
238 }
239}
240
241#[cfg(test)]
242mod tests {
243 use std::sync::atomic::Ordering;
244
245 use super::AudioFrameQueue;
246 use crate::audio_frame::AudioFrame;
247
248 fn test_frame(marker: i16) -> AudioFrame<'static> {
249 AudioFrame {
250 data: vec![marker].into(),
251 sample_rate: 48_000,
252 num_channels: 1,
253 samples_per_channel: 1,
254 }
255 }
256
257 fn pop_marker(queue: &AudioFrameQueue) -> Option<i16> {
258 queue.try_pop().map(|frame| frame.data[0])
259 }
260
261 #[test]
262 fn bounded_queue_preserves_fifo_order_under_capacity() {
263 let queue = AudioFrameQueue::new(Some(3));
264
265 queue.push(test_frame(1));
266 queue.push(test_frame(2));
267 queue.push(test_frame(3));
268
269 assert_eq!(pop_marker(&queue), Some(1));
270 assert_eq!(pop_marker(&queue), Some(2));
271 assert_eq!(pop_marker(&queue), Some(3));
272 assert_eq!(pop_marker(&queue), None);
273 }
274
275 #[test]
276 fn bounded_queue_drops_oldest_when_full() {
277 let queue = AudioFrameQueue::new(Some(2));
278
279 queue.push(test_frame(1));
280 queue.push(test_frame(2));
281 queue.push(test_frame(3));
282
283 assert_eq!(queue.dropped_frames.load(Ordering::Relaxed), 1);
284 assert_eq!(pop_marker(&queue), Some(2));
285 assert_eq!(pop_marker(&queue), Some(3));
286 assert_eq!(pop_marker(&queue), None);
287 }
288
289 #[test]
290 fn unbounded_queue_retains_all_frames() {
291 let queue = AudioFrameQueue::new(None);
292
293 for marker in 1..=4 {
294 queue.push(test_frame(marker));
295 }
296
297 for marker in 1..=4 {
298 assert_eq!(pop_marker(&queue), Some(marker));
299 }
300 assert_eq!(pop_marker(&queue), None);
301 assert_eq!(queue.dropped_frames.load(Ordering::Relaxed), 0);
302 }
303
304 #[test]
305 fn close_clears_buffer_and_rejects_future_pushes() {
306 let queue = AudioFrameQueue::new(Some(2));
307
308 queue.push(test_frame(1));
309 queue.close();
310 queue.push(test_frame(2));
311
312 assert_eq!(pop_marker(&queue), None);
313 }
314}
vendor/libwebrtc/src/native/audio_track.rs added +33 −0
@@ -0,0 +1,33 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::SharedPtr;
16 use sys_at::ffi::audio_to_media;
17 use webrtc_sys::audio_track as sys_at;
18
19 use super::media_stream_track::impl_media_stream_track;
20 use crate::media_stream_track::RtcTrackState;
21
22 #[derive(Clone)]
23 pub struct RtcAudioTrack {
24 pub(crate) sys_handle: SharedPtr<sys_at::ffi::AudioTrack>,
25 }
26
27 impl RtcAudioTrack {
28 impl_media_stream_track!(audio_to_media);
29
30 pub fn sys_handle(&self) -> SharedPtr<sys_at::ffi::MediaStreamTrack> {
31 audio_to_media(self.sys_handle.clone())
32 }
33 }
@@ -0,0 +1,33 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::SharedPtr;
16use sys_at::ffi::audio_to_media;
17use webrtc_sys::audio_track as sys_at;
18
19use super::media_stream_track::impl_media_stream_track;
20use crate::media_stream_track::RtcTrackState;
21
22#[derive(Clone)]
23pub struct RtcAudioTrack {
24 pub(crate) sys_handle: SharedPtr<sys_at::ffi::AudioTrack>,
25}
26
27impl RtcAudioTrack {
28 impl_media_stream_track!(audio_to_media);
29
30 pub fn sys_handle(&self) -> SharedPtr<sys_at::ffi::MediaStreamTrack> {
31 audio_to_media(self.sys_handle.clone())
32 }
33}
vendor/libwebrtc/src/native/data_channel.rs added +142 −0
@@ -0,0 +1,142 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::{str, sync::Arc};
16
17 use cxx::SharedPtr;
18 use parking_lot::Mutex;
19 use webrtc_sys::data_channel as sys_dc;
20
21 use crate::data_channel::{
22 DataBuffer, DataChannelError, DataChannelInit, DataChannelState, OnBufferedAmountChange,
23 OnMessage, OnStateChange,
24 };
25
26 impl From<sys_dc::ffi::DataState> for DataChannelState {
27 fn from(value: sys_dc::ffi::DataState) -> Self {
28 match value {
29 sys_dc::ffi::DataState::Connecting => Self::Connecting,
30 sys_dc::ffi::DataState::Open => Self::Open,
31 sys_dc::ffi::DataState::Closing => Self::Closing,
32 sys_dc::ffi::DataState::Closed => Self::Closed,
33 _ => panic!("unknown data channel state"),
34 }
35 }
36 }
37
38 impl From<DataChannelInit> for sys_dc::ffi::DataChannelInit {
39 fn from(value: DataChannelInit) -> Self {
40 Self {
41 ordered: value.ordered,
42 has_max_retransmit_time: value.max_retransmit_time.is_some(),
43 max_retransmit_time: value.max_retransmit_time.unwrap_or_default(),
44 has_max_retransmits: value.max_retransmits.is_some(),
45 max_retransmits: value.max_retransmits.unwrap_or_default(),
46 protocol: value.protocol,
47 id: value.id,
48 has_priority: false,
49 priority: sys_dc::ffi::Priority::Medium,
50 negotiated: value.negotiated,
51 }
52 }
53 }
54
55 #[derive(Clone)]
56 pub struct DataChannel {
57 observer: Arc<DataChannelObserver>,
58 pub(crate) sys_handle: SharedPtr<sys_dc::ffi::DataChannel>,
59 }
60
61 impl DataChannel {
62 pub fn configure(sys_handle: SharedPtr<sys_dc::ffi::DataChannel>) -> Self {
63 let observer = Arc::new(DataChannelObserver::default());
64 let dc = Self { sys_handle: sys_handle.clone(), observer: observer.clone() };
65
66 dc.sys_handle
67 .register_observer(Box::new(sys_dc::DataChannelObserverWrapper::new(observer)));
68 dc
69 }
70
71 pub fn send(&self, data: &[u8], binary: bool) -> Result<(), DataChannelError> {
72 if !binary {
73 str::from_utf8(data)?;
74 }
75
76 let buffer = sys_dc::ffi::DataBuffer { ptr: data.as_ptr(), len: data.len(), binary };
77
78 self.sys_handle.send(&buffer).then_some(()).ok_or(DataChannelError::Send)
79 }
80
81 pub fn id(&self) -> i32 {
82 self.sys_handle.id()
83 }
84
85 pub fn label(&self) -> String {
86 self.sys_handle.label()
87 }
88
89 pub fn state(&self) -> DataChannelState {
90 self.sys_handle.state().into()
91 }
92
93 pub fn close(&self) {
94 self.sys_handle.close();
95 }
96
97 pub fn buffered_amount(&self) -> u64 {
98 self.sys_handle.buffered_amount()
99 }
100
101 pub fn on_state_change(&self, handler: Option<OnStateChange>) {
102 *self.observer.state_change_handler.lock() = handler;
103 }
104
105 pub fn on_message(&self, handler: Option<OnMessage>) {
106 *self.observer.message_handler.lock() = handler;
107 }
108
109 pub fn on_buffered_amount_change(&self, handler: Option<OnBufferedAmountChange>) {
110 *self.observer.buffered_amount_change_handler.lock() = handler;
111 }
112 }
113
114 #[derive(Default)]
115 struct DataChannelObserver {
116 state_change_handler: Mutex<Option<OnStateChange>>,
117 message_handler: Mutex<Option<OnMessage>>,
118 buffered_amount_change_handler: Mutex<Option<OnBufferedAmountChange>>,
119 }
120
121 impl sys_dc::DataChannelObserver for DataChannelObserver {
122 fn on_state_change(&self, state: sys_dc::ffi::DataState) {
123 let mut handler = self.state_change_handler.lock();
124 if let Some(f) = handler.as_mut() {
125 f(state.into());
126 }
127 }
128
129 fn on_message(&self, data: &[u8], binary: bool) {
130 let mut handler = self.message_handler.lock();
131 if let Some(f) = handler.as_mut() {
132 f(DataBuffer { data, binary });
133 }
134 }
135
136 fn on_buffered_amount_change(&self, sent_data_size: u64) {
137 let mut handler = self.buffered_amount_change_handler.lock();
138 if let Some(f) = handler.as_mut() {
139 f(sent_data_size);
140 }
141 }
142 }
@@ -0,0 +1,142 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{str, sync::Arc};
16
17use cxx::SharedPtr;
18use parking_lot::Mutex;
19use webrtc_sys::data_channel as sys_dc;
20
21use crate::data_channel::{
22 DataBuffer, DataChannelError, DataChannelInit, DataChannelState, OnBufferedAmountChange,
23 OnMessage, OnStateChange,
24};
25
26impl From<sys_dc::ffi::DataState> for DataChannelState {
27 fn from(value: sys_dc::ffi::DataState) -> Self {
28 match value {
29 sys_dc::ffi::DataState::Connecting => Self::Connecting,
30 sys_dc::ffi::DataState::Open => Self::Open,
31 sys_dc::ffi::DataState::Closing => Self::Closing,
32 sys_dc::ffi::DataState::Closed => Self::Closed,
33 _ => panic!("unknown data channel state"),
34 }
35 }
36}
37
38impl From<DataChannelInit> for sys_dc::ffi::DataChannelInit {
39 fn from(value: DataChannelInit) -> Self {
40 Self {
41 ordered: value.ordered,
42 has_max_retransmit_time: value.max_retransmit_time.is_some(),
43 max_retransmit_time: value.max_retransmit_time.unwrap_or_default(),
44 has_max_retransmits: value.max_retransmits.is_some(),
45 max_retransmits: value.max_retransmits.unwrap_or_default(),
46 protocol: value.protocol,
47 id: value.id,
48 has_priority: false,
49 priority: sys_dc::ffi::Priority::Medium,
50 negotiated: value.negotiated,
51 }
52 }
53}
54
55#[derive(Clone)]
56pub struct DataChannel {
57 observer: Arc<DataChannelObserver>,
58 pub(crate) sys_handle: SharedPtr<sys_dc::ffi::DataChannel>,
59}
60
61impl DataChannel {
62 pub fn configure(sys_handle: SharedPtr<sys_dc::ffi::DataChannel>) -> Self {
63 let observer = Arc::new(DataChannelObserver::default());
64 let dc = Self { sys_handle: sys_handle.clone(), observer: observer.clone() };
65
66 dc.sys_handle
67 .register_observer(Box::new(sys_dc::DataChannelObserverWrapper::new(observer)));
68 dc
69 }
70
71 pub fn send(&self, data: &[u8], binary: bool) -> Result<(), DataChannelError> {
72 if !binary {
73 str::from_utf8(data)?;
74 }
75
76 let buffer = sys_dc::ffi::DataBuffer { ptr: data.as_ptr(), len: data.len(), binary };
77
78 self.sys_handle.send(&buffer).then_some(()).ok_or(DataChannelError::Send)
79 }
80
81 pub fn id(&self) -> i32 {
82 self.sys_handle.id()
83 }
84
85 pub fn label(&self) -> String {
86 self.sys_handle.label()
87 }
88
89 pub fn state(&self) -> DataChannelState {
90 self.sys_handle.state().into()
91 }
92
93 pub fn close(&self) {
94 self.sys_handle.close();
95 }
96
97 pub fn buffered_amount(&self) -> u64 {
98 self.sys_handle.buffered_amount()
99 }
100
101 pub fn on_state_change(&self, handler: Option<OnStateChange>) {
102 *self.observer.state_change_handler.lock() = handler;
103 }
104
105 pub fn on_message(&self, handler: Option<OnMessage>) {
106 *self.observer.message_handler.lock() = handler;
107 }
108
109 pub fn on_buffered_amount_change(&self, handler: Option<OnBufferedAmountChange>) {
110 *self.observer.buffered_amount_change_handler.lock() = handler;
111 }
112}
113
114#[derive(Default)]
115struct DataChannelObserver {
116 state_change_handler: Mutex<Option<OnStateChange>>,
117 message_handler: Mutex<Option<OnMessage>>,
118 buffered_amount_change_handler: Mutex<Option<OnBufferedAmountChange>>,
119}
120
121impl sys_dc::DataChannelObserver for DataChannelObserver {
122 fn on_state_change(&self, state: sys_dc::ffi::DataState) {
123 let mut handler = self.state_change_handler.lock();
124 if let Some(f) = handler.as_mut() {
125 f(state.into());
126 }
127 }
128
129 fn on_message(&self, data: &[u8], binary: bool) {
130 let mut handler = self.message_handler.lock();
131 if let Some(f) = handler.as_mut() {
132 f(DataBuffer { data, binary });
133 }
134 }
135
136 fn on_buffered_amount_change(&self, sent_data_size: u64) {
137 let mut handler = self.buffered_amount_change_handler.lock();
138 if let Some(f) = handler.as_mut() {
139 f(sent_data_size);
140 }
141 }
142}
vendor/libwebrtc/src/native/desktop_capturer.rs added +249 −0
@@ -0,0 +1,249 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::UniquePtr;
16 use webrtc_sys::desktop_capturer::{self as sys_dc, ffi::new_desktop_capturer};
17
18 #[derive(Debug, Copy, Clone, PartialEq)]
19 pub(crate) enum SourceType {
20 Screen,
21 Window,
22 #[cfg(any(target_os = "macos", target_os = "linux"))]
23 Generic,
24 }
25
26 #[derive(Copy, Clone, Debug)]
27 pub(crate) struct DesktopCapturerOptions {
28 source_type: SourceType,
29 include_cursor: bool,
30 #[cfg(target_os = "macos")]
31 allow_sck_system_picker: bool,
32 }
33
34 impl Default for DesktopCapturerOptions {
35 fn default() -> Self {
36 Self {
37 source_type: SourceType::Screen,
38 include_cursor: false,
39 #[cfg(target_os = "macos")]
40 allow_sck_system_picker: true,
41 }
42 }
43 }
44
45 impl DesktopCapturerOptions {
46 pub(crate) fn new(source_type: SourceType) -> Self {
47 Self { source_type, ..Default::default() }
48 }
49
50 pub(crate) fn with_cursor(mut self, include: bool) -> Self {
51 self.include_cursor = include;
52 self
53 }
54
55 #[cfg(target_os = "macos")]
56 pub(crate) fn with_sck_system_picker(mut self, allow_sck_system_picker: bool) -> Self {
57 self.allow_sck_system_picker = allow_sck_system_picker;
58 self
59 }
60
61 pub(crate) fn to_sys_handle(&self) -> sys_dc::ffi::DesktopCapturerOptions {
62 let source_type = match self.source_type {
63 SourceType::Screen => sys_dc::ffi::SourceType::Screen,
64 SourceType::Window => sys_dc::ffi::SourceType::Window,
65 #[cfg(any(target_os = "macos", target_os = "linux"))]
66 SourceType::Generic => sys_dc::ffi::SourceType::Generic,
67 };
68 let sys_handle = sys_dc::ffi::DesktopCapturerOptions {
69 source_type,
70 include_cursor: self.include_cursor,
71 allow_sck_system_picker: {
72 #[cfg(target_os = "macos")]
73 {
74 self.allow_sck_system_picker
75 }
76 #[cfg(not(target_os = "macos"))]
77 {
78 false
79 }
80 },
81 };
82
83 sys_handle
84 }
85 }
86
87 pub(crate) struct DesktopCapturer {
88 sys_handle: UniquePtr<sys_dc::ffi::DesktopCapturer>,
89 #[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "glib-main-loop"))]
90 glib_loop: Option<glib::MainLoop>,
91 }
92
93 impl DesktopCapturer {
94 pub(crate) fn new(options: DesktopCapturerOptions) -> Option<Self> {
95 let sys_handle = new_desktop_capturer(options.to_sys_handle());
96 if sys_handle.is_null() {
97 None
98 } else {
99 Some(Self {
100 sys_handle,
101 #[cfg(all(
102 any(target_os = "linux", target_os = "freebsd"),
103 feature = "glib-main-loop"
104 ))]
105 glib_loop: None,
106 })
107 }
108 }
109
110 pub(crate) fn capture_frame(&self) {
111 self.sys_handle.capture_frame();
112 }
113
114 pub(crate) fn start<T>(&mut self, callback: T)
115 where
116 T: FnMut(Result<DesktopFrame, CaptureError>) + Send + 'static,
117 {
118 #[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "glib-main-loop"))]
119 if std::env::var("WAYLAND_DISPLAY").is_ok() {
120 let main_loop = glib::MainLoop::new(None, false);
121 self.glib_loop = Some(main_loop.clone());
122 let _handle = std::thread::spawn(move || {
123 main_loop.run();
124 });
125 }
126 let pin_handle = self.sys_handle.pin_mut();
127 let callback = DesktopCallback::new(callback);
128 let callback_wrapper = sys_dc::DesktopCapturerCallbackWrapper::new(Box::new(callback));
129 pin_handle.start(Box::new(callback_wrapper));
130 }
131
132 pub(crate) fn select_source(&self, id: u64) -> bool {
133 self.sys_handle.select_source(id)
134 }
135
136 pub(crate) fn get_source_list(&self) -> Vec<CaptureSource> {
137 let mut sources = Vec::new();
138 let source_list = self.sys_handle.get_source_list();
139 for source in source_list.iter() {
140 sources.push(CaptureSource { sys_handle: source.clone() });
141 }
142 sources
143 }
144 }
145
146 #[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "glib-main-loop"))]
147 impl Drop for DesktopCapturer {
148 fn drop(&mut self) {
149 if let Some(glib_loop) = &self.glib_loop {
150 glib_loop.quit();
151 }
152 }
153 }
154
155 pub(crate) struct DesktopFrame {
156 sys_handle: UniquePtr<sys_dc::ffi::DesktopFrame>,
157 }
158
159 impl DesktopFrame {
160 fn new(sys_handle: UniquePtr<sys_dc::ffi::DesktopFrame>) -> Self {
161 Self { sys_handle }
162 }
163
164 pub(crate) fn width(&self) -> i32 {
165 self.sys_handle.width()
166 }
167
168 pub(crate) fn height(&self) -> i32 {
169 self.sys_handle.height()
170 }
171
172 pub(crate) fn stride(&self) -> u32 {
173 self.sys_handle.stride() as u32
174 }
175
176 pub(crate) fn left(&self) -> i32 {
177 self.sys_handle.left()
178 }
179
180 pub(crate) fn top(&self) -> i32 {
181 self.sys_handle.top()
182 }
183
184 pub(crate) fn data(&self) -> &[u8] {
185 let data = self.sys_handle.data();
186 unsafe { std::slice::from_raw_parts(data, self.stride() as usize * self.height() as usize) }
187 }
188 }
189
190 struct DesktopCallback<T: FnMut(Result<DesktopFrame, CaptureError>) + Send> {
191 callback: T,
192 }
193
194 impl<T> DesktopCallback<T>
195 where
196 T: FnMut(Result<DesktopFrame, CaptureError>) + Send,
197 {
198 fn new(callback: T) -> Self {
199 Self { callback }
200 }
201
202 fn capture_result_from_sys(
203 result: Result<UniquePtr<sys_dc::ffi::DesktopFrame>, sys_dc::CaptureError>,
204 ) -> Result<DesktopFrame, CaptureError> {
205 match result {
206 Ok(frame) => Ok(DesktopFrame::new(frame)),
207 Err(error) => Err(match error {
208 sys_dc::CaptureError::Temporary => CaptureError::Temporary,
209 sys_dc::CaptureError::Permanent => CaptureError::Permanent,
210 }),
211 }
212 }
213 }
214
215 impl<T> sys_dc::DesktopCapturerCallback for DesktopCallback<T>
216 where
217 T: FnMut(Result<DesktopFrame, CaptureError>) + Send,
218 {
219 fn on_capture_result(
220 &mut self,
221 result: Result<UniquePtr<sys_dc::ffi::DesktopFrame>, sys_dc::CaptureError>,
222 ) {
223 (self.callback)(DesktopCallback::<T>::capture_result_from_sys(result));
224 }
225 }
226
227 #[derive(Clone)]
228 pub(crate) struct CaptureSource {
229 sys_handle: sys_dc::ffi::Source,
230 }
231
232 impl CaptureSource {
233 pub(crate) fn id(&self) -> u64 {
234 self.sys_handle.id
235 }
236
237 pub(crate) fn title(&self) -> String {
238 self.sys_handle.title.clone()
239 }
240
241 pub(crate) fn display_id(&self) -> i64 {
242 self.sys_handle.display_id
243 }
244 }
245
246 pub(crate) enum CaptureError {
247 Temporary,
248 Permanent,
249 }
@@ -0,0 +1,249 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::UniquePtr;
16use webrtc_sys::desktop_capturer::{self as sys_dc, ffi::new_desktop_capturer};
17
18#[derive(Debug, Copy, Clone, PartialEq)]
19pub(crate) enum SourceType {
20 Screen,
21 Window,
22 #[cfg(any(target_os = "macos", target_os = "linux"))]
23 Generic,
24}
25
26#[derive(Copy, Clone, Debug)]
27pub(crate) struct DesktopCapturerOptions {
28 source_type: SourceType,
29 include_cursor: bool,
30 #[cfg(target_os = "macos")]
31 allow_sck_system_picker: bool,
32}
33
34impl Default for DesktopCapturerOptions {
35 fn default() -> Self {
36 Self {
37 source_type: SourceType::Screen,
38 include_cursor: false,
39 #[cfg(target_os = "macos")]
40 allow_sck_system_picker: true,
41 }
42 }
43}
44
45impl DesktopCapturerOptions {
46 pub(crate) fn new(source_type: SourceType) -> Self {
47 Self { source_type, ..Default::default() }
48 }
49
50 pub(crate) fn with_cursor(mut self, include: bool) -> Self {
51 self.include_cursor = include;
52 self
53 }
54
55 #[cfg(target_os = "macos")]
56 pub(crate) fn with_sck_system_picker(mut self, allow_sck_system_picker: bool) -> Self {
57 self.allow_sck_system_picker = allow_sck_system_picker;
58 self
59 }
60
61 pub(crate) fn to_sys_handle(&self) -> sys_dc::ffi::DesktopCapturerOptions {
62 let source_type = match self.source_type {
63 SourceType::Screen => sys_dc::ffi::SourceType::Screen,
64 SourceType::Window => sys_dc::ffi::SourceType::Window,
65 #[cfg(any(target_os = "macos", target_os = "linux"))]
66 SourceType::Generic => sys_dc::ffi::SourceType::Generic,
67 };
68 let sys_handle = sys_dc::ffi::DesktopCapturerOptions {
69 source_type,
70 include_cursor: self.include_cursor,
71 allow_sck_system_picker: {
72 #[cfg(target_os = "macos")]
73 {
74 self.allow_sck_system_picker
75 }
76 #[cfg(not(target_os = "macos"))]
77 {
78 false
79 }
80 },
81 };
82
83 sys_handle
84 }
85}
86
87pub(crate) struct DesktopCapturer {
88 sys_handle: UniquePtr<sys_dc::ffi::DesktopCapturer>,
89 #[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "glib-main-loop"))]
90 glib_loop: Option<glib::MainLoop>,
91}
92
93impl DesktopCapturer {
94 pub(crate) fn new(options: DesktopCapturerOptions) -> Option<Self> {
95 let sys_handle = new_desktop_capturer(options.to_sys_handle());
96 if sys_handle.is_null() {
97 None
98 } else {
99 Some(Self {
100 sys_handle,
101 #[cfg(all(
102 any(target_os = "linux", target_os = "freebsd"),
103 feature = "glib-main-loop"
104 ))]
105 glib_loop: None,
106 })
107 }
108 }
109
110 pub(crate) fn capture_frame(&self) {
111 self.sys_handle.capture_frame();
112 }
113
114 pub(crate) fn start<T>(&mut self, callback: T)
115 where
116 T: FnMut(Result<DesktopFrame, CaptureError>) + Send + 'static,
117 {
118 #[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "glib-main-loop"))]
119 if std::env::var("WAYLAND_DISPLAY").is_ok() {
120 let main_loop = glib::MainLoop::new(None, false);
121 self.glib_loop = Some(main_loop.clone());
122 let _handle = std::thread::spawn(move || {
123 main_loop.run();
124 });
125 }
126 let pin_handle = self.sys_handle.pin_mut();
127 let callback = DesktopCallback::new(callback);
128 let callback_wrapper = sys_dc::DesktopCapturerCallbackWrapper::new(Box::new(callback));
129 pin_handle.start(Box::new(callback_wrapper));
130 }
131
132 pub(crate) fn select_source(&self, id: u64) -> bool {
133 self.sys_handle.select_source(id)
134 }
135
136 pub(crate) fn get_source_list(&self) -> Vec<CaptureSource> {
137 let mut sources = Vec::new();
138 let source_list = self.sys_handle.get_source_list();
139 for source in source_list.iter() {
140 sources.push(CaptureSource { sys_handle: source.clone() });
141 }
142 sources
143 }
144}
145
146#[cfg(all(any(target_os = "linux", target_os = "freebsd"), feature = "glib-main-loop"))]
147impl Drop for DesktopCapturer {
148 fn drop(&mut self) {
149 if let Some(glib_loop) = &self.glib_loop {
150 glib_loop.quit();
151 }
152 }
153}
154
155pub(crate) struct DesktopFrame {
156 sys_handle: UniquePtr<sys_dc::ffi::DesktopFrame>,
157}
158
159impl DesktopFrame {
160 fn new(sys_handle: UniquePtr<sys_dc::ffi::DesktopFrame>) -> Self {
161 Self { sys_handle }
162 }
163
164 pub(crate) fn width(&self) -> i32 {
165 self.sys_handle.width()
166 }
167
168 pub(crate) fn height(&self) -> i32 {
169 self.sys_handle.height()
170 }
171
172 pub(crate) fn stride(&self) -> u32 {
173 self.sys_handle.stride() as u32
174 }
175
176 pub(crate) fn left(&self) -> i32 {
177 self.sys_handle.left()
178 }
179
180 pub(crate) fn top(&self) -> i32 {
181 self.sys_handle.top()
182 }
183
184 pub(crate) fn data(&self) -> &[u8] {
185 let data = self.sys_handle.data();
186 unsafe { std::slice::from_raw_parts(data, self.stride() as usize * self.height() as usize) }
187 }
188}
189
190struct DesktopCallback<T: FnMut(Result<DesktopFrame, CaptureError>) + Send> {
191 callback: T,
192}
193
194impl<T> DesktopCallback<T>
195where
196 T: FnMut(Result<DesktopFrame, CaptureError>) + Send,
197{
198 fn new(callback: T) -> Self {
199 Self { callback }
200 }
201
202 fn capture_result_from_sys(
203 result: Result<UniquePtr<sys_dc::ffi::DesktopFrame>, sys_dc::CaptureError>,
204 ) -> Result<DesktopFrame, CaptureError> {
205 match result {
206 Ok(frame) => Ok(DesktopFrame::new(frame)),
207 Err(error) => Err(match error {
208 sys_dc::CaptureError::Temporary => CaptureError::Temporary,
209 sys_dc::CaptureError::Permanent => CaptureError::Permanent,
210 }),
211 }
212 }
213}
214
215impl<T> sys_dc::DesktopCapturerCallback for DesktopCallback<T>
216where
217 T: FnMut(Result<DesktopFrame, CaptureError>) + Send,
218{
219 fn on_capture_result(
220 &mut self,
221 result: Result<UniquePtr<sys_dc::ffi::DesktopFrame>, sys_dc::CaptureError>,
222 ) {
223 (self.callback)(DesktopCallback::<T>::capture_result_from_sys(result));
224 }
225}
226
227#[derive(Clone)]
228pub(crate) struct CaptureSource {
229 sys_handle: sys_dc::ffi::Source,
230}
231
232impl CaptureSource {
233 pub(crate) fn id(&self) -> u64 {
234 self.sys_handle.id
235 }
236
237 pub(crate) fn title(&self) -> String {
238 self.sys_handle.title.clone()
239 }
240
241 pub(crate) fn display_id(&self) -> i64 {
242 self.sys_handle.display_id
243 }
244}
245
246pub(crate) enum CaptureError {
247 Temporary,
248 Permanent,
249}
vendor/libwebrtc/src/native/frame_cryptor.rs added +316 −0
@@ -0,0 +1,316 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::sync::Arc;
16
17 use cxx::SharedPtr;
18 use parking_lot::Mutex;
19 use webrtc_sys::frame_cryptor::{self as sys_fc};
20
21 use crate::{
22 native::packet_trailer::PacketTrailerHandler, peer_connection_factory::PeerConnectionFactory,
23 rtp_receiver::RtpReceiver, rtp_sender::RtpSender,
24 };
25
26 pub type OnStateChange = Box<dyn FnMut(String, EncryptionState) + Send + Sync>;
27
28 #[derive(Copy, Clone, Debug)]
29 #[non_exhaustive]
30 pub enum KeyDerivationAlgorithm {
31 PBKDF2,
32 HKDF,
33 }
34 impl Into<sys_fc::ffi::KeyDerivationAlgorithm> for KeyDerivationAlgorithm {
35 fn into(self) -> sys_fc::ffi::KeyDerivationAlgorithm {
36 match self {
37 KeyDerivationAlgorithm::PBKDF2 => sys_fc::ffi::KeyDerivationAlgorithm::PBKDF2,
38 KeyDerivationAlgorithm::HKDF => sys_fc::ffi::KeyDerivationAlgorithm::HKDF,
39 }
40 }
41 }
42
43 #[derive(Debug, Clone)]
44 pub struct KeyProviderOptions {
45 pub shared_key: bool,
46 pub ratchet_window_size: i32,
47 pub ratchet_salt: Vec<u8>,
48 pub failure_tolerance: i32,
49 pub key_ring_size: i32,
50 pub key_derivation_algorithm: KeyDerivationAlgorithm,
51 }
52
53 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
54 pub enum EncryptionAlgorithm {
55 AesGcm,
56 AesCbc,
57 }
58
59 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
60 pub enum EncryptionState {
61 New,
62 Ok,
63 EncryptionFailed,
64 DecryptionFailed,
65 MissingKey,
66 KeyRatcheted,
67 InternalError,
68 }
69
70 #[derive(Debug, Clone)]
71 pub struct EncryptedPacket {
72 pub data: Vec<u8>,
73 pub iv: Vec<u8>,
74 pub key_index: u32,
75 }
76
77 #[derive(Clone)]
78 pub struct KeyProvider {
79 pub(crate) sys_handle: SharedPtr<sys_fc::ffi::KeyProvider>,
80 }
81
82 impl KeyProvider {
83 pub fn new(options: KeyProviderOptions) -> Self {
84 Self { sys_handle: sys_fc::ffi::new_key_provider(options.into()) }
85 }
86
87 pub fn set_shared_key(&self, key_index: i32, key: Vec<u8>) -> bool {
88 self.sys_handle.set_shared_key(key_index, key)
89 }
90
91 pub fn ratchet_shared_key(&self, key_index: i32) -> Option<Vec<u8>> {
92 self.sys_handle.ratchet_shared_key(key_index).ok()
93 }
94
95 pub fn get_shared_key(&self, key_index: i32) -> Option<Vec<u8>> {
96 self.sys_handle.get_shared_key(key_index).ok()
97 }
98
99 pub fn set_key(&self, participant_id: String, key_index: i32, key: Vec<u8>) -> bool {
100 self.sys_handle.set_key(participant_id, key_index, key)
101 }
102
103 pub fn ratchet_key(&self, participant_id: String, key_index: i32) -> Option<Vec<u8>> {
104 self.sys_handle.ratchet_key(participant_id, key_index).ok()
105 }
106
107 pub fn get_key(&self, participant_id: String, key_index: i32) -> Option<Vec<u8>> {
108 self.sys_handle.get_key(participant_id, key_index).ok()
109 }
110
111 pub fn set_sif_trailer(&self, trailer: Vec<u8>) {
112 self.sys_handle.set_sif_trailer(trailer);
113 }
114 }
115
116 #[derive(Clone)]
117 pub struct FrameCryptor {
118 observer: Arc<RtcFrameCryptorObserver>,
119 pub(crate) sys_handle: SharedPtr<sys_fc::ffi::FrameCryptor>,
120 }
121
122 impl FrameCryptor {
123 pub fn new_for_rtp_sender(
124 peer_factory: &PeerConnectionFactory,
125 participant_id: String,
126 algorithm: EncryptionAlgorithm,
127 key_provider: KeyProvider,
128 sender: RtpSender,
129 ) -> Self {
130 let observer = Arc::new(RtcFrameCryptorObserver::default());
131 let sys_handle = sys_fc::ffi::new_frame_cryptor_for_rtp_sender(
132 peer_factory.handle.sys_handle.clone(),
133 participant_id,
134 algorithm.into(),
135 key_provider.sys_handle,
136 sender.handle.sys_handle,
137 );
138 let fc = Self { observer: observer.clone(), sys_handle: sys_handle.clone() };
139 fc.sys_handle
140 .register_observer(Box::new(sys_fc::RtcFrameCryptorObserverWrapper::new(observer)));
141 fc
142 }
143
144 pub fn new_for_rtp_receiver(
145 peer_factory: &PeerConnectionFactory,
146 participant_id: String,
147 algorithm: EncryptionAlgorithm,
148 key_provider: KeyProvider,
149 receiver: RtpReceiver,
150 ) -> Self {
151 let observer = Arc::new(RtcFrameCryptorObserver::default());
152 let sys_handle = sys_fc::ffi::new_frame_cryptor_for_rtp_receiver(
153 peer_factory.handle.sys_handle.clone(),
154 participant_id,
155 algorithm.into(),
156 key_provider.sys_handle,
157 receiver.handle.sys_handle,
158 );
159 let fc = Self { observer: observer.clone(), sys_handle: sys_handle.clone() };
160 fc.sys_handle
161 .register_observer(Box::new(sys_fc::RtcFrameCryptorObserverWrapper::new(observer)));
162 fc
163 }
164
165 pub fn set_enabled(self: &FrameCryptor, enabled: bool) {
166 self.sys_handle.set_enabled(enabled);
167 }
168
169 pub fn enabled(self: &FrameCryptor) -> bool {
170 self.sys_handle.enabled()
171 }
172
173 pub fn set_key_index(self: &FrameCryptor, index: i32) {
174 self.sys_handle.set_key_index(index);
175 }
176
177 pub fn key_index(self: &FrameCryptor) -> i32 {
178 self.sys_handle.key_index()
179 }
180
181 pub fn participant_id(self: &FrameCryptor) -> String {
182 self.sys_handle.participant_id()
183 }
184
185 pub fn on_state_change(&self, handler: Option<OnStateChange>) {
186 *self.observer.state_change_handler.lock() = handler;
187 }
188
189 pub fn set_packet_trailer_handler(&self, handler: &PacketTrailerHandler) {
190 self.sys_handle.set_packet_trailer_handler(handler.sys_handle());
191 }
192 }
193
194 #[derive(Clone)]
195 pub struct DataPacketCryptor {
196 pub(crate) sys_handle: SharedPtr<sys_fc::ffi::DataPacketCryptor>,
197 }
198
199 impl DataPacketCryptor {
200 pub fn new(algorithm: EncryptionAlgorithm, key_provider: KeyProvider) -> Self {
201 Self {
202 sys_handle: sys_fc::ffi::new_data_packet_cryptor(
203 algorithm.into(),
204 key_provider.sys_handle,
205 ),
206 }
207 }
208
209 pub fn encrypt(
210 &self,
211 participant_id: &str,
212 key_index: u32,
213 data: &[u8],
214 ) -> Result<EncryptedPacket, Box<dyn std::error::Error>> {
215 let data_vec: Vec<u8> = data.to_vec();
216 match self.sys_handle.encrypt_data_packet(participant_id.to_string(), key_index, data_vec) {
217 Ok(packet) => Ok(packet.into()),
218 Err(e) => Err(format!("Encryption failed: {}", e).into()),
219 }
220 }
221
222 pub fn decrypt(
223 &self,
224 participant_id: &str,
225 encrypted_packet: &EncryptedPacket,
226 ) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
227 match self
228 .sys_handle
229 .decrypt_data_packet(participant_id.to_string(), &encrypted_packet.clone().into())
230 {
231 Ok(data) => Ok(data.into_iter().collect()),
232 Err(e) => Err(format!("Decryption failed: {}", e).into()),
233 }
234 }
235 }
236
237 #[derive(Default)]
238 struct RtcFrameCryptorObserver {
239 state_change_handler: Mutex<Option<OnStateChange>>,
240 }
241
242 impl sys_fc::RtcFrameCryptorObserver for RtcFrameCryptorObserver {
243 fn on_frame_cryption_state_change(
244 &self,
245 participant_id: String,
246 state: sys_fc::ffi::FrameCryptionState,
247 ) {
248 let mut handler = self.state_change_handler.lock();
249 if let Some(f) = handler.as_mut() {
250 f(participant_id, state.into());
251 }
252 }
253 }
254
255 impl From<sys_fc::ffi::Algorithm> for EncryptionAlgorithm {
256 fn from(value: sys_fc::ffi::Algorithm) -> Self {
257 match value {
258 sys_fc::ffi::Algorithm::AesGcm => Self::AesGcm,
259 sys_fc::ffi::Algorithm::AesCbc => Self::AesCbc,
260 _ => panic!("unknown frame cyrptor Algorithm"),
261 }
262 }
263 }
264
265 impl From<EncryptionAlgorithm> for sys_fc::ffi::Algorithm {
266 fn from(value: EncryptionAlgorithm) -> Self {
267 match value {
268 EncryptionAlgorithm::AesGcm => Self::AesGcm,
269 EncryptionAlgorithm::AesCbc => Self::AesCbc,
270 }
271 }
272 }
273
274 impl From<sys_fc::ffi::FrameCryptionState> for EncryptionState {
275 fn from(value: sys_fc::ffi::FrameCryptionState) -> Self {
276 match value {
277 sys_fc::ffi::FrameCryptionState::New => Self::New,
278 sys_fc::ffi::FrameCryptionState::Ok => Self::Ok,
279 sys_fc::ffi::FrameCryptionState::EncryptionFailed => Self::EncryptionFailed,
280 sys_fc::ffi::FrameCryptionState::DecryptionFailed => Self::DecryptionFailed,
281 sys_fc::ffi::FrameCryptionState::MissingKey => Self::MissingKey,
282 sys_fc::ffi::FrameCryptionState::KeyRatcheted => Self::KeyRatcheted,
283 sys_fc::ffi::FrameCryptionState::InternalError => Self::InternalError,
284 _ => panic!("unknown frame cyrptor FrameCryptionState"),
285 }
286 }
287 }
288
289 impl From<KeyProviderOptions> for sys_fc::ffi::KeyProviderOptions {
290 fn from(value: KeyProviderOptions) -> Self {
291 Self {
292 shared_key: value.shared_key,
293 ratchet_window_size: value.ratchet_window_size,
294 ratchet_salt: value.ratchet_salt,
295 failure_tolerance: value.failure_tolerance,
296 key_ring_size: value.key_ring_size,
297 key_derivation_algorithm: value.key_derivation_algorithm.into(),
298 }
299 }
300 }
301
302 impl From<sys_fc::ffi::EncryptedPacket> for EncryptedPacket {
303 fn from(value: sys_fc::ffi::EncryptedPacket) -> Self {
304 Self {
305 data: value.data.into_iter().collect(),
306 iv: value.iv.into_iter().collect(),
307 key_index: value.key_index,
308 }
309 }
310 }
311
312 impl From<EncryptedPacket> for sys_fc::ffi::EncryptedPacket {
313 fn from(value: EncryptedPacket) -> Self {
314 Self { data: value.data, iv: value.iv, key_index: value.key_index }
315 }
316 }
@@ -0,0 +1,316 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::Arc;
16
17use cxx::SharedPtr;
18use parking_lot::Mutex;
19use webrtc_sys::frame_cryptor::{self as sys_fc};
20
21use crate::{
22 native::packet_trailer::PacketTrailerHandler, peer_connection_factory::PeerConnectionFactory,
23 rtp_receiver::RtpReceiver, rtp_sender::RtpSender,
24};
25
26pub type OnStateChange = Box<dyn FnMut(String, EncryptionState) + Send + Sync>;
27
28#[derive(Copy, Clone, Debug)]
29#[non_exhaustive]
30pub enum KeyDerivationAlgorithm {
31 PBKDF2,
32 HKDF,
33}
34impl Into<sys_fc::ffi::KeyDerivationAlgorithm> for KeyDerivationAlgorithm {
35 fn into(self) -> sys_fc::ffi::KeyDerivationAlgorithm {
36 match self {
37 KeyDerivationAlgorithm::PBKDF2 => sys_fc::ffi::KeyDerivationAlgorithm::PBKDF2,
38 KeyDerivationAlgorithm::HKDF => sys_fc::ffi::KeyDerivationAlgorithm::HKDF,
39 }
40 }
41}
42
43#[derive(Debug, Clone)]
44pub struct KeyProviderOptions {
45 pub shared_key: bool,
46 pub ratchet_window_size: i32,
47 pub ratchet_salt: Vec<u8>,
48 pub failure_tolerance: i32,
49 pub key_ring_size: i32,
50 pub key_derivation_algorithm: KeyDerivationAlgorithm,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum EncryptionAlgorithm {
55 AesGcm,
56 AesCbc,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum EncryptionState {
61 New,
62 Ok,
63 EncryptionFailed,
64 DecryptionFailed,
65 MissingKey,
66 KeyRatcheted,
67 InternalError,
68}
69
70#[derive(Debug, Clone)]
71pub struct EncryptedPacket {
72 pub data: Vec<u8>,
73 pub iv: Vec<u8>,
74 pub key_index: u32,
75}
76
77#[derive(Clone)]
78pub struct KeyProvider {
79 pub(crate) sys_handle: SharedPtr<sys_fc::ffi::KeyProvider>,
80}
81
82impl KeyProvider {
83 pub fn new(options: KeyProviderOptions) -> Self {
84 Self { sys_handle: sys_fc::ffi::new_key_provider(options.into()) }
85 }
86
87 pub fn set_shared_key(&self, key_index: i32, key: Vec<u8>) -> bool {
88 self.sys_handle.set_shared_key(key_index, key)
89 }
90
91 pub fn ratchet_shared_key(&self, key_index: i32) -> Option<Vec<u8>> {
92 self.sys_handle.ratchet_shared_key(key_index).ok()
93 }
94
95 pub fn get_shared_key(&self, key_index: i32) -> Option<Vec<u8>> {
96 self.sys_handle.get_shared_key(key_index).ok()
97 }
98
99 pub fn set_key(&self, participant_id: String, key_index: i32, key: Vec<u8>) -> bool {
100 self.sys_handle.set_key(participant_id, key_index, key)
101 }
102
103 pub fn ratchet_key(&self, participant_id: String, key_index: i32) -> Option<Vec<u8>> {
104 self.sys_handle.ratchet_key(participant_id, key_index).ok()
105 }
106
107 pub fn get_key(&self, participant_id: String, key_index: i32) -> Option<Vec<u8>> {
108 self.sys_handle.get_key(participant_id, key_index).ok()
109 }
110
111 pub fn set_sif_trailer(&self, trailer: Vec<u8>) {
112 self.sys_handle.set_sif_trailer(trailer);
113 }
114}
115
116#[derive(Clone)]
117pub struct FrameCryptor {
118 observer: Arc<RtcFrameCryptorObserver>,
119 pub(crate) sys_handle: SharedPtr<sys_fc::ffi::FrameCryptor>,
120}
121
122impl FrameCryptor {
123 pub fn new_for_rtp_sender(
124 peer_factory: &PeerConnectionFactory,
125 participant_id: String,
126 algorithm: EncryptionAlgorithm,
127 key_provider: KeyProvider,
128 sender: RtpSender,
129 ) -> Self {
130 let observer = Arc::new(RtcFrameCryptorObserver::default());
131 let sys_handle = sys_fc::ffi::new_frame_cryptor_for_rtp_sender(
132 peer_factory.handle.sys_handle.clone(),
133 participant_id,
134 algorithm.into(),
135 key_provider.sys_handle,
136 sender.handle.sys_handle,
137 );
138 let fc = Self { observer: observer.clone(), sys_handle: sys_handle.clone() };
139 fc.sys_handle
140 .register_observer(Box::new(sys_fc::RtcFrameCryptorObserverWrapper::new(observer)));
141 fc
142 }
143
144 pub fn new_for_rtp_receiver(
145 peer_factory: &PeerConnectionFactory,
146 participant_id: String,
147 algorithm: EncryptionAlgorithm,
148 key_provider: KeyProvider,
149 receiver: RtpReceiver,
150 ) -> Self {
151 let observer = Arc::new(RtcFrameCryptorObserver::default());
152 let sys_handle = sys_fc::ffi::new_frame_cryptor_for_rtp_receiver(
153 peer_factory.handle.sys_handle.clone(),
154 participant_id,
155 algorithm.into(),
156 key_provider.sys_handle,
157 receiver.handle.sys_handle,
158 );
159 let fc = Self { observer: observer.clone(), sys_handle: sys_handle.clone() };
160 fc.sys_handle
161 .register_observer(Box::new(sys_fc::RtcFrameCryptorObserverWrapper::new(observer)));
162 fc
163 }
164
165 pub fn set_enabled(self: &FrameCryptor, enabled: bool) {
166 self.sys_handle.set_enabled(enabled);
167 }
168
169 pub fn enabled(self: &FrameCryptor) -> bool {
170 self.sys_handle.enabled()
171 }
172
173 pub fn set_key_index(self: &FrameCryptor, index: i32) {
174 self.sys_handle.set_key_index(index);
175 }
176
177 pub fn key_index(self: &FrameCryptor) -> i32 {
178 self.sys_handle.key_index()
179 }
180
181 pub fn participant_id(self: &FrameCryptor) -> String {
182 self.sys_handle.participant_id()
183 }
184
185 pub fn on_state_change(&self, handler: Option<OnStateChange>) {
186 *self.observer.state_change_handler.lock() = handler;
187 }
188
189 pub fn set_packet_trailer_handler(&self, handler: &PacketTrailerHandler) {
190 self.sys_handle.set_packet_trailer_handler(handler.sys_handle());
191 }
192}
193
194#[derive(Clone)]
195pub struct DataPacketCryptor {
196 pub(crate) sys_handle: SharedPtr<sys_fc::ffi::DataPacketCryptor>,
197}
198
199impl DataPacketCryptor {
200 pub fn new(algorithm: EncryptionAlgorithm, key_provider: KeyProvider) -> Self {
201 Self {
202 sys_handle: sys_fc::ffi::new_data_packet_cryptor(
203 algorithm.into(),
204 key_provider.sys_handle,
205 ),
206 }
207 }
208
209 pub fn encrypt(
210 &self,
211 participant_id: &str,
212 key_index: u32,
213 data: &[u8],
214 ) -> Result<EncryptedPacket, Box<dyn std::error::Error>> {
215 let data_vec: Vec<u8> = data.to_vec();
216 match self.sys_handle.encrypt_data_packet(participant_id.to_string(), key_index, data_vec) {
217 Ok(packet) => Ok(packet.into()),
218 Err(e) => Err(format!("Encryption failed: {}", e).into()),
219 }
220 }
221
222 pub fn decrypt(
223 &self,
224 participant_id: &str,
225 encrypted_packet: &EncryptedPacket,
226 ) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
227 match self
228 .sys_handle
229 .decrypt_data_packet(participant_id.to_string(), &encrypted_packet.clone().into())
230 {
231 Ok(data) => Ok(data.into_iter().collect()),
232 Err(e) => Err(format!("Decryption failed: {}", e).into()),
233 }
234 }
235}
236
237#[derive(Default)]
238struct RtcFrameCryptorObserver {
239 state_change_handler: Mutex<Option<OnStateChange>>,
240}
241
242impl sys_fc::RtcFrameCryptorObserver for RtcFrameCryptorObserver {
243 fn on_frame_cryption_state_change(
244 &self,
245 participant_id: String,
246 state: sys_fc::ffi::FrameCryptionState,
247 ) {
248 let mut handler = self.state_change_handler.lock();
249 if let Some(f) = handler.as_mut() {
250 f(participant_id, state.into());
251 }
252 }
253}
254
255impl From<sys_fc::ffi::Algorithm> for EncryptionAlgorithm {
256 fn from(value: sys_fc::ffi::Algorithm) -> Self {
257 match value {
258 sys_fc::ffi::Algorithm::AesGcm => Self::AesGcm,
259 sys_fc::ffi::Algorithm::AesCbc => Self::AesCbc,
260 _ => panic!("unknown frame cyrptor Algorithm"),
261 }
262 }
263}
264
265impl From<EncryptionAlgorithm> for sys_fc::ffi::Algorithm {
266 fn from(value: EncryptionAlgorithm) -> Self {
267 match value {
268 EncryptionAlgorithm::AesGcm => Self::AesGcm,
269 EncryptionAlgorithm::AesCbc => Self::AesCbc,
270 }
271 }
272}
273
274impl From<sys_fc::ffi::FrameCryptionState> for EncryptionState {
275 fn from(value: sys_fc::ffi::FrameCryptionState) -> Self {
276 match value {
277 sys_fc::ffi::FrameCryptionState::New => Self::New,
278 sys_fc::ffi::FrameCryptionState::Ok => Self::Ok,
279 sys_fc::ffi::FrameCryptionState::EncryptionFailed => Self::EncryptionFailed,
280 sys_fc::ffi::FrameCryptionState::DecryptionFailed => Self::DecryptionFailed,
281 sys_fc::ffi::FrameCryptionState::MissingKey => Self::MissingKey,
282 sys_fc::ffi::FrameCryptionState::KeyRatcheted => Self::KeyRatcheted,
283 sys_fc::ffi::FrameCryptionState::InternalError => Self::InternalError,
284 _ => panic!("unknown frame cyrptor FrameCryptionState"),
285 }
286 }
287}
288
289impl From<KeyProviderOptions> for sys_fc::ffi::KeyProviderOptions {
290 fn from(value: KeyProviderOptions) -> Self {
291 Self {
292 shared_key: value.shared_key,
293 ratchet_window_size: value.ratchet_window_size,
294 ratchet_salt: value.ratchet_salt,
295 failure_tolerance: value.failure_tolerance,
296 key_ring_size: value.key_ring_size,
297 key_derivation_algorithm: value.key_derivation_algorithm.into(),
298 }
299 }
300}
301
302impl From<sys_fc::ffi::EncryptedPacket> for EncryptedPacket {
303 fn from(value: sys_fc::ffi::EncryptedPacket) -> Self {
304 Self {
305 data: value.data.into_iter().collect(),
306 iv: value.iv.into_iter().collect(),
307 key_index: value.key_index,
308 }
309 }
310}
311
312impl From<EncryptedPacket> for sys_fc::ffi::EncryptedPacket {
313 fn from(value: EncryptedPacket) -> Self {
314 Self { data: value.data, iv: value.iv, key_index: value.key_index }
315 }
316}
vendor/libwebrtc/src/native/ice_candidate.rs added +60 −0
@@ -0,0 +1,60 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::SharedPtr;
16 use webrtc_sys::jsep as sys_jsep;
17
18 use crate::{ice_candidate as ic, session_description::SdpParseError};
19
20 #[derive(Clone)]
21 pub struct IceCandidate {
22 pub(crate) sys_handle: SharedPtr<sys_jsep::ffi::IceCandidate>,
23 }
24
25 impl IceCandidate {
26 pub fn parse(
27 sdp_mid: &str,
28 sdp_mline_index: i32,
29 sdp: &str,
30 ) -> Result<ic::IceCandidate, SdpParseError> {
31 let res = sys_jsep::ffi::create_ice_candidate(
32 sdp_mid.to_string(),
33 sdp_mline_index,
34 sdp.to_string(),
35 );
36
37 match res {
38 Ok(sys_handle) => Ok(ic::IceCandidate { handle: IceCandidate { sys_handle } }),
39 Err(e) => Err(unsafe { sys_jsep::ffi::SdpParseError::from(e.what()).into() }),
40 }
41 }
42
43 pub fn sdp_mid(&self) -> String {
44 self.sys_handle.sdp_mid()
45 }
46
47 pub fn sdp_mline_index(&self) -> i32 {
48 self.sys_handle.sdp_mline_index()
49 }
50
51 pub fn candidate(&self) -> String {
52 self.sys_handle.candidate()
53 }
54 }
55
56 impl ToString for IceCandidate {
57 fn to_string(&self) -> String {
58 self.sys_handle.stringify()
59 }
60 }
@@ -0,0 +1,60 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::SharedPtr;
16use webrtc_sys::jsep as sys_jsep;
17
18use crate::{ice_candidate as ic, session_description::SdpParseError};
19
20#[derive(Clone)]
21pub struct IceCandidate {
22 pub(crate) sys_handle: SharedPtr<sys_jsep::ffi::IceCandidate>,
23}
24
25impl IceCandidate {
26 pub fn parse(
27 sdp_mid: &str,
28 sdp_mline_index: i32,
29 sdp: &str,
30 ) -> Result<ic::IceCandidate, SdpParseError> {
31 let res = sys_jsep::ffi::create_ice_candidate(
32 sdp_mid.to_string(),
33 sdp_mline_index,
34 sdp.to_string(),
35 );
36
37 match res {
38 Ok(sys_handle) => Ok(ic::IceCandidate { handle: IceCandidate { sys_handle } }),
39 Err(e) => Err(unsafe { sys_jsep::ffi::SdpParseError::from(e.what()).into() }),
40 }
41 }
42
43 pub fn sdp_mid(&self) -> String {
44 self.sys_handle.sdp_mid()
45 }
46
47 pub fn sdp_mline_index(&self) -> i32 {
48 self.sys_handle.sdp_mline_index()
49 }
50
51 pub fn candidate(&self) -> String {
52 self.sys_handle.candidate()
53 }
54}
55
56impl ToString for IceCandidate {
57 fn to_string(&self) -> String {
58 self.sys_handle.stringify()
59 }
60}
vendor/libwebrtc/src/native/media_stream.rs added +49 −0
@@ -0,0 +1,49 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::SharedPtr;
16 use webrtc_sys::media_stream as sys_ms;
17
18 use crate::{
19 audio_track,
20 imp::{audio_track::RtcAudioTrack, video_track::RtcVideoTrack},
21 video_track,
22 };
23
24 #[derive(Clone)]
25 pub struct MediaStream {
26 pub(crate) sys_handle: SharedPtr<sys_ms::ffi::MediaStream>,
27 }
28
29 impl MediaStream {
30 pub fn id(&self) -> String {
31 self.sys_handle.id()
32 }
33
34 pub fn audio_tracks(&self) -> Vec<audio_track::RtcAudioTrack> {
35 self.sys_handle
36 .get_audio_tracks()
37 .into_iter()
38 .map(|t| audio_track::RtcAudioTrack { handle: RtcAudioTrack { sys_handle: t.ptr } })
39 .collect()
40 }
41
42 pub fn video_tracks(&self) -> Vec<video_track::RtcVideoTrack> {
43 self.sys_handle
44 .get_video_tracks()
45 .into_iter()
46 .map(|t| video_track::RtcVideoTrack { handle: RtcVideoTrack::new(t.ptr) })
47 .collect()
48 }
49 }
@@ -0,0 +1,49 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::SharedPtr;
16use webrtc_sys::media_stream as sys_ms;
17
18use crate::{
19 audio_track,
20 imp::{audio_track::RtcAudioTrack, video_track::RtcVideoTrack},
21 video_track,
22};
23
24#[derive(Clone)]
25pub struct MediaStream {
26 pub(crate) sys_handle: SharedPtr<sys_ms::ffi::MediaStream>,
27}
28
29impl MediaStream {
30 pub fn id(&self) -> String {
31 self.sys_handle.id()
32 }
33
34 pub fn audio_tracks(&self) -> Vec<audio_track::RtcAudioTrack> {
35 self.sys_handle
36 .get_audio_tracks()
37 .into_iter()
38 .map(|t| audio_track::RtcAudioTrack { handle: RtcAudioTrack { sys_handle: t.ptr } })
39 .collect()
40 }
41
42 pub fn video_tracks(&self) -> Vec<video_track::RtcVideoTrack> {
43 self.sys_handle
44 .get_video_tracks()
45 .into_iter()
46 .map(|t| video_track::RtcVideoTrack { handle: RtcVideoTrack::new(t.ptr) })
47 .collect()
48 }
49}
vendor/libwebrtc/src/native/media_stream_track.rs added +78 −0
@@ -0,0 +1,78 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::SharedPtr;
16 use webrtc_sys::{
17 audio_track::ffi::media_to_audio, media_stream_track as sys_mst,
18 video_track::ffi::media_to_video, MEDIA_TYPE_AUDIO, MEDIA_TYPE_VIDEO,
19 };
20
21 use crate::{
22 audio_track,
23 imp::{audio_track::RtcAudioTrack, video_track::RtcVideoTrack},
24 media_stream_track::{MediaStreamTrack, RtcTrackState},
25 video_track,
26 };
27
28 impl From<sys_mst::ffi::TrackState> for RtcTrackState {
29 fn from(state: sys_mst::ffi::TrackState) -> Self {
30 match state {
31 sys_mst::ffi::TrackState::Live => RtcTrackState::Live,
32 sys_mst::ffi::TrackState::Ended => RtcTrackState::Ended,
33 _ => panic!("unknown TrackState"),
34 }
35 }
36 }
37
38 pub fn new_media_stream_track(
39 sys_handle: SharedPtr<sys_mst::ffi::MediaStreamTrack>,
40 ) -> MediaStreamTrack {
41 if sys_handle.kind() == MEDIA_TYPE_AUDIO {
42 MediaStreamTrack::Audio(audio_track::RtcAudioTrack {
43 handle: RtcAudioTrack { sys_handle: unsafe { media_to_audio(sys_handle) } },
44 })
45 } else if sys_handle.kind() == MEDIA_TYPE_VIDEO {
46 MediaStreamTrack::Video(video_track::RtcVideoTrack {
47 handle: RtcVideoTrack::new(unsafe { media_to_video(sys_handle) }),
48 })
49 } else {
50 panic!("unknown track kind")
51 }
52 }
53
54 macro_rules! impl_media_stream_track {
55 ($cast:expr) => {
56 pub fn id(&self) -> String {
57 let ptr = $cast(self.sys_handle.clone());
58 ptr.id()
59 }
60
61 pub fn enabled(&self) -> bool {
62 let ptr = $cast(self.sys_handle.clone());
63 ptr.enabled()
64 }
65
66 pub fn set_enabled(&self, enabled: bool) -> bool {
67 let ptr = $cast(self.sys_handle.clone());
68 ptr.set_enabled(enabled)
69 }
70
71 pub fn state(&self) -> RtcTrackState {
72 let ptr = $cast(self.sys_handle.clone());
73 ptr.state().into()
74 }
75 };
76 }
77
78 pub(super) use impl_media_stream_track;
@@ -0,0 +1,78 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::SharedPtr;
16use webrtc_sys::{
17 audio_track::ffi::media_to_audio, media_stream_track as sys_mst,
18 video_track::ffi::media_to_video, MEDIA_TYPE_AUDIO, MEDIA_TYPE_VIDEO,
19};
20
21use crate::{
22 audio_track,
23 imp::{audio_track::RtcAudioTrack, video_track::RtcVideoTrack},
24 media_stream_track::{MediaStreamTrack, RtcTrackState},
25 video_track,
26};
27
28impl From<sys_mst::ffi::TrackState> for RtcTrackState {
29 fn from(state: sys_mst::ffi::TrackState) -> Self {
30 match state {
31 sys_mst::ffi::TrackState::Live => RtcTrackState::Live,
32 sys_mst::ffi::TrackState::Ended => RtcTrackState::Ended,
33 _ => panic!("unknown TrackState"),
34 }
35 }
36}
37
38pub fn new_media_stream_track(
39 sys_handle: SharedPtr<sys_mst::ffi::MediaStreamTrack>,
40) -> MediaStreamTrack {
41 if sys_handle.kind() == MEDIA_TYPE_AUDIO {
42 MediaStreamTrack::Audio(audio_track::RtcAudioTrack {
43 handle: RtcAudioTrack { sys_handle: unsafe { media_to_audio(sys_handle) } },
44 })
45 } else if sys_handle.kind() == MEDIA_TYPE_VIDEO {
46 MediaStreamTrack::Video(video_track::RtcVideoTrack {
47 handle: RtcVideoTrack::new(unsafe { media_to_video(sys_handle) }),
48 })
49 } else {
50 panic!("unknown track kind")
51 }
52}
53
54macro_rules! impl_media_stream_track {
55 ($cast:expr) => {
56 pub fn id(&self) -> String {
57 let ptr = $cast(self.sys_handle.clone());
58 ptr.id()
59 }
60
61 pub fn enabled(&self) -> bool {
62 let ptr = $cast(self.sys_handle.clone());
63 ptr.enabled()
64 }
65
66 pub fn set_enabled(&self, enabled: bool) -> bool {
67 let ptr = $cast(self.sys_handle.clone());
68 ptr.set_enabled(enabled)
69 }
70
71 pub fn state(&self) -> RtcTrackState {
72 let ptr = $cast(self.sys_handle.clone());
73 ptr.state().into()
74 }
75 };
76}
77
78pub(super) use impl_media_stream_track;
vendor/libwebrtc/src/native/mod.rs added +72 −0
@@ -0,0 +1,72 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #[cfg(target_os = "android")]
16 pub mod android;
17 pub mod apm;
18 pub mod audio_mixer;
19 pub mod audio_resampler;
20 pub mod audio_source;
21 pub mod audio_stream;
22 pub mod audio_track;
23 pub mod data_channel;
24 #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
25 pub mod desktop_capturer;
26 pub mod frame_cryptor;
27 pub mod ice_candidate;
28 pub mod media_stream;
29 pub mod media_stream_track;
30 pub mod packet_trailer;
31 pub mod peer_connection;
32 pub mod peer_connection_factory;
33 pub mod rtp_parameters;
34 pub mod rtp_receiver;
35 pub mod rtp_sender;
36 pub mod rtp_transceiver;
37 pub mod session_description;
38 pub mod video_frame;
39 pub mod video_source;
40 pub mod video_stream;
41 pub mod video_track;
42 pub mod yuv_helper;
43
44 use webrtc_sys::{rtc_error as sys_err, webrtc as sys_rtc};
45
46 use crate::{MediaType, RtcError, RtcErrorType};
47
48 impl From<sys_err::ffi::RtcErrorType> for RtcErrorType {
49 fn from(value: sys_err::ffi::RtcErrorType) -> Self {
50 match value {
51 sys_err::ffi::RtcErrorType::InvalidState => Self::InvalidState,
52 _ => Self::Internal,
53 }
54 }
55 }
56
57 impl From<sys_err::ffi::RtcError> for RtcError {
58 fn from(value: sys_err::ffi::RtcError) -> Self {
59 Self { error_type: value.error_type.into(), message: value.message }
60 }
61 }
62
63 impl From<MediaType> for sys_rtc::ffi::MediaType {
64 fn from(value: MediaType) -> Self {
65 match value {
66 MediaType::Audio => Self::Audio,
67 MediaType::Video => Self::Video,
68 MediaType::Data => Self::Data,
69 MediaType::Unsupported => Self::Unsupported,
70 }
71 }
72 }
@@ -0,0 +1,72 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[cfg(target_os = "android")]
16pub mod android;
17pub mod apm;
18pub mod audio_mixer;
19pub mod audio_resampler;
20pub mod audio_source;
21pub mod audio_stream;
22pub mod audio_track;
23pub mod data_channel;
24#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
25pub mod desktop_capturer;
26pub mod frame_cryptor;
27pub mod ice_candidate;
28pub mod media_stream;
29pub mod media_stream_track;
30pub mod packet_trailer;
31pub mod peer_connection;
32pub mod peer_connection_factory;
33pub mod rtp_parameters;
34pub mod rtp_receiver;
35pub mod rtp_sender;
36pub mod rtp_transceiver;
37pub mod session_description;
38pub mod video_frame;
39pub mod video_source;
40pub mod video_stream;
41pub mod video_track;
42pub mod yuv_helper;
43
44use webrtc_sys::{rtc_error as sys_err, webrtc as sys_rtc};
45
46use crate::{MediaType, RtcError, RtcErrorType};
47
48impl From<sys_err::ffi::RtcErrorType> for RtcErrorType {
49 fn from(value: sys_err::ffi::RtcErrorType) -> Self {
50 match value {
51 sys_err::ffi::RtcErrorType::InvalidState => Self::InvalidState,
52 _ => Self::Internal,
53 }
54 }
55}
56
57impl From<sys_err::ffi::RtcError> for RtcError {
58 fn from(value: sys_err::ffi::RtcError) -> Self {
59 Self { error_type: value.error_type.into(), message: value.message }
60 }
61}
62
63impl From<MediaType> for sys_rtc::ffi::MediaType {
64 fn from(value: MediaType) -> Self {
65 match value {
66 MediaType::Audio => Self::Audio,
67 MediaType::Video => Self::Video,
68 MediaType::Data => Self::Data,
69 MediaType::Unsupported => Self::Unsupported,
70 }
71 }
72}
vendor/libwebrtc/src/native/packet_trailer.rs added +281 −0
@@ -0,0 +1,281 @@
1 // Copyright 2026 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //! Packet trailer support for end-to-end frame metadata propagation.
16 //!
17 //! This module provides functionality to embed user-supplied metadata
18 //! in encoded video frames as trailers. The timestamps/frameIDs are preserved
19 //! through the WebRTC pipeline and can be extracted on the receiver side.
20 //!
21 //! On the send side, user timestamps/frameIDs are stored in the handler's internal
22 //! map keyed by RTP timestamp. When the encoder produces a frame,
23 //! the transformer looks up the metadata via the frame's CaptureTime().
24 //!
25 //! On the receive side, extracted frame metadata is stored in an
26 //! internal map keyed by RTP timestamp. Decoded frames look up their
27 //! metadata via lookup_frame_metadata(rtp_timestamp).
28
29 use std::sync::Arc;
30
31 use cxx::SharedPtr;
32 use webrtc_sys::packet_trailer::ffi as sys_pt;
33
34 use crate::{
35 peer_connection_factory::PeerConnectionFactory, rtp_receiver::RtpReceiver,
36 rtp_sender::RtpSender,
37 };
38
39 /// Stage reached by a native local video frame in the publish pipeline.
40 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
41 pub enum PublishTimingStage {
42 /// The adapted raw frame was handed to WebRTC's encoder path.
43 EncoderUpload,
44 /// WebRTC produced an encoded frame for packetization.
45 EncoderOutput,
46 /// The encoded frame was handed back to WebRTC's packetizer.
47 WebrtcPacketize,
48 }
49
50 /// Stage reached by a native remote video frame in the subscribe pipeline.
51 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
52 pub enum SubscribeTimingStage {
53 /// WebRTC produced an encoded frame after RTP depacketization.
54 WebrtcReceive,
55 /// The encoded frame was handed to WebRTC's decoder.
56 DecoderUpload,
57 /// WebRTC produced a decoded frame for the native video sink.
58 DecoderOutput,
59 }
60
61 /// Timestamped native local video publish pipeline event.
62 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
63 pub struct PublishTimingEvent {
64 /// Publish pipeline stage reached by the frame.
65 pub stage: PublishTimingStage,
66 /// Wall-clock time when this stage was observed, in microseconds since the Unix epoch.
67 pub timestamp_us: u64,
68 /// User capture timestamp associated with this frame, in microseconds since the Unix epoch.
69 pub capture_timestamp_us: u64,
70 /// Optional application frame ID associated with this frame.
71 pub frame_id: Option<u32>,
72 }
73
74 /// Timestamped native remote video subscribe pipeline event.
75 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
76 pub struct SubscribeTimingEvent {
77 /// Subscribe pipeline stage reached by the frame.
78 pub stage: SubscribeTimingStage,
79 /// Wall-clock time when this stage was observed, in microseconds since the Unix epoch.
80 pub timestamp_us: u64,
81 /// User capture timestamp associated with this frame, in microseconds since the Unix epoch.
82 pub capture_timestamp_us: u64,
83 /// Optional application frame ID associated with this frame.
84 pub frame_id: Option<u32>,
85 }
86
87 /// Callback invoked for native local video publish timing events.
88 pub type PublishTimingObserver = Arc<dyn Fn(PublishTimingEvent) + Send + Sync + 'static>;
89 /// Callback invoked for native remote video subscribe timing events.
90 pub type SubscribeTimingObserver = Arc<dyn Fn(SubscribeTimingEvent) + Send + Sync + 'static>;
91
92 impl From<sys_pt::VideoPublishTimingStage> for PublishTimingStage {
93 fn from(stage: sys_pt::VideoPublishTimingStage) -> Self {
94 match stage {
95 sys_pt::VideoPublishTimingStage::EncoderUpload => Self::EncoderUpload,
96 sys_pt::VideoPublishTimingStage::EncoderOutput => Self::EncoderOutput,
97 sys_pt::VideoPublishTimingStage::WebrtcPacketize => Self::WebrtcPacketize,
98 _ => Self::WebrtcPacketize,
99 }
100 }
101 }
102
103 impl From<sys_pt::VideoPublishTimingEvent> for PublishTimingEvent {
104 fn from(event: sys_pt::VideoPublishTimingEvent) -> Self {
105 Self {
106 stage: event.stage.into(),
107 timestamp_us: event.timestamp_us,
108 capture_timestamp_us: event.capture_timestamp_us,
109 frame_id: (event.frame_id != 0).then_some(event.frame_id),
110 }
111 }
112 }
113
114 impl From<sys_pt::VideoSubscribeTimingStage> for SubscribeTimingStage {
115 fn from(stage: sys_pt::VideoSubscribeTimingStage) -> Self {
116 match stage {
117 sys_pt::VideoSubscribeTimingStage::WebrtcReceive => Self::WebrtcReceive,
118 sys_pt::VideoSubscribeTimingStage::DecoderUpload => Self::DecoderUpload,
119 sys_pt::VideoSubscribeTimingStage::DecoderOutput => Self::DecoderOutput,
120 _ => Self::DecoderOutput,
121 }
122 }
123 }
124
125 impl From<sys_pt::VideoSubscribeTimingEvent> for SubscribeTimingEvent {
126 fn from(event: sys_pt::VideoSubscribeTimingEvent) -> Self {
127 Self {
128 stage: event.stage.into(),
129 timestamp_us: event.timestamp_us,
130 capture_timestamp_us: event.capture_timestamp_us,
131 frame_id: (event.frame_id != 0).then_some(event.frame_id),
132 }
133 }
134 }
135
136 /// Handler for packet trailer embedding/extraction on RTP streams.
137 ///
138 /// For sender side: Stores frame metadata keyed by capture timestamp
139 /// and embeds them as binary payload trailers on encoded frames before they
140 /// are sent. Use `store_frame_metadata()` to associate metadata with
141 /// a captured frame.
142 ///
143 /// For receiver side: Extracts frame metadata from received frames
144 /// and makes them available for retrieval via `lookup_frame_metadata()`.
145 #[derive(Clone)]
146 pub struct PacketTrailerHandler {
147 sys_handle: SharedPtr<sys_pt::PacketTrailerHandler>,
148 }
149
150 impl PacketTrailerHandler {
151 /// Enable or disable timestamp embedding/extraction.
152 pub fn set_enabled(&self, enabled: bool) {
153 self.sys_handle.set_enabled(enabled);
154 }
155
156 /// Check if timestamp embedding/extraction is enabled.
157 pub fn enabled(&self) -> bool {
158 self.sys_handle.enabled()
159 }
160
161 /// Lookup the frame metadata for a given RTP timestamp (receiver side).
162 /// Returns `Some((user_timestamp, frame_id, user_data))` if found,
163 /// `None` otherwise. The entry is removed from the map after a
164 /// successful lookup.
165 pub fn lookup_frame_metadata(&self, rtp_timestamp: u32) -> Option<(u64, u32, Vec<u8>)> {
166 let ts = self.sys_handle.lookup_timestamp(rtp_timestamp);
167 if ts != u64::MAX {
168 let frame_id = self.sys_handle.last_lookup_frame_id();
169 let user_data = self.sys_handle.last_lookup_user_data();
170 Some((ts, frame_id, user_data))
171 } else {
172 None
173 }
174 }
175
176 /// Store frame metadata for a given capture timestamp (sender side).
177 ///
178 /// The `capture_timestamp_us` must be the TimestampAligner-adjusted
179 /// timestamp (as produced by `VideoTrackSource::on_captured_frame`),
180 /// NOT the original `timestamp_us` from the VideoFrame. The transformer
181 /// looks up the metadata by the frame's `CaptureTime()` which is
182 /// derived from the aligned value.
183 ///
184 /// In normal usage this is called automatically by the C++ layer --
185 /// callers should set `user_timestamp` and `frame_id` on the
186 /// `VideoFrame` and let `capture_frame` / `on_captured_frame` handle
187 /// the rest.
188 pub fn store_frame_metadata(
189 &self,
190 capture_timestamp_us: i64,
191 user_timestamp: u64,
192 frame_id: u32,
193 user_data: &[u8],
194 ) {
195 self.sys_handle.store_frame_metadata(
196 capture_timestamp_us,
197 user_timestamp,
198 frame_id,
199 user_data,
200 );
201 }
202
203 pub(crate) fn sys_handle(&self) -> SharedPtr<sys_pt::PacketTrailerHandler> {
204 self.sys_handle.clone()
205 }
206
207 /// Set the callback receiving sender-side publish timing events.
208 pub fn set_publish_timing_observer(&self, observer: Option<PublishTimingObserver>) {
209 if let Some(observer) = observer {
210 self.sys_handle.set_publish_timing_observer(Box::new(
211 webrtc_sys::packet_trailer::VideoPublishTimingObserverWrapper::new(Box::new(
212 move |event| observer(event.into()),
213 )),
214 ));
215 } else {
216 self.sys_handle.clear_publish_timing_observer();
217 }
218 }
219
220 /// Set the callback receiving receiver-side subscribe timing events.
221 pub fn set_subscribe_timing_observer(&self, observer: Option<SubscribeTimingObserver>) {
222 if let Some(observer) = observer {
223 self.sys_handle.set_subscribe_timing_observer(Box::new(
224 webrtc_sys::packet_trailer::VideoSubscribeTimingObserverWrapper::new(Box::new(
225 move |event| observer(event.into()),
226 )),
227 ));
228 } else {
229 self.sys_handle.clear_subscribe_timing_observer();
230 }
231 }
232
233 pub(crate) fn emit_subscribe_timing(
234 &self,
235 stage: SubscribeTimingStage,
236 capture_timestamp_us: u64,
237 frame_id: u32,
238 ) {
239 let stage = match stage {
240 SubscribeTimingStage::WebrtcReceive => sys_pt::VideoSubscribeTimingStage::WebrtcReceive,
241 SubscribeTimingStage::DecoderUpload => sys_pt::VideoSubscribeTimingStage::DecoderUpload,
242 SubscribeTimingStage::DecoderOutput => sys_pt::VideoSubscribeTimingStage::DecoderOutput,
243 };
244 self.sys_handle.emit_subscribe_timing(stage, capture_timestamp_us, frame_id);
245 }
246 }
247
248 /// Create a sender-side packet trailer handler.
249 ///
250 /// This handler will embed frame metadata into encoded frames before
251 /// they are packetized and sent. Use `store_frame_metadata()` to
252 /// associate metadata with a captured frame's capture timestamp.
253 pub fn create_sender_handler(
254 peer_factory: &PeerConnectionFactory,
255 sender: &RtpSender,
256 ) -> PacketTrailerHandler {
257 PacketTrailerHandler {
258 sys_handle: sys_pt::new_packet_trailer_sender(
259 peer_factory.handle.sys_handle.clone(),
260 sender.handle.sys_handle.clone(),
261 ),
262 }
263 }
264
265 /// Create a receiver-side packet trailer handler.
266 ///
267 /// This handler will extract frame metadata from received frames
268 /// and store them in a map keyed by RTP timestamp. Use
269 /// `lookup_frame_metadata(rtp_timestamp)` to retrieve the metadata
270 /// for a specific decoded frame.
271 pub fn create_receiver_handler(
272 peer_factory: &PeerConnectionFactory,
273 receiver: &RtpReceiver,
274 ) -> PacketTrailerHandler {
275 PacketTrailerHandler {
276 sys_handle: sys_pt::new_packet_trailer_receiver(
277 peer_factory.handle.sys_handle.clone(),
278 receiver.handle.sys_handle.clone(),
279 ),
280 }
281 }
@@ -0,0 +1,281 @@
1// Copyright 2026 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Packet trailer support for end-to-end frame metadata propagation.
16//!
17//! This module provides functionality to embed user-supplied metadata
18//! in encoded video frames as trailers. The timestamps/frameIDs are preserved
19//! through the WebRTC pipeline and can be extracted on the receiver side.
20//!
21//! On the send side, user timestamps/frameIDs are stored in the handler's internal
22//! map keyed by RTP timestamp. When the encoder produces a frame,
23//! the transformer looks up the metadata via the frame's CaptureTime().
24//!
25//! On the receive side, extracted frame metadata is stored in an
26//! internal map keyed by RTP timestamp. Decoded frames look up their
27//! metadata via lookup_frame_metadata(rtp_timestamp).
28
29use std::sync::Arc;
30
31use cxx::SharedPtr;
32use webrtc_sys::packet_trailer::ffi as sys_pt;
33
34use crate::{
35 peer_connection_factory::PeerConnectionFactory, rtp_receiver::RtpReceiver,
36 rtp_sender::RtpSender,
37};
38
39/// Stage reached by a native local video frame in the publish pipeline.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum PublishTimingStage {
42 /// The adapted raw frame was handed to WebRTC's encoder path.
43 EncoderUpload,
44 /// WebRTC produced an encoded frame for packetization.
45 EncoderOutput,
46 /// The encoded frame was handed back to WebRTC's packetizer.
47 WebrtcPacketize,
48}
49
50/// Stage reached by a native remote video frame in the subscribe pipeline.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum SubscribeTimingStage {
53 /// WebRTC produced an encoded frame after RTP depacketization.
54 WebrtcReceive,
55 /// The encoded frame was handed to WebRTC's decoder.
56 DecoderUpload,
57 /// WebRTC produced a decoded frame for the native video sink.
58 DecoderOutput,
59}
60
61/// Timestamped native local video publish pipeline event.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct PublishTimingEvent {
64 /// Publish pipeline stage reached by the frame.
65 pub stage: PublishTimingStage,
66 /// Wall-clock time when this stage was observed, in microseconds since the Unix epoch.
67 pub timestamp_us: u64,
68 /// User capture timestamp associated with this frame, in microseconds since the Unix epoch.
69 pub capture_timestamp_us: u64,
70 /// Optional application frame ID associated with this frame.
71 pub frame_id: Option<u32>,
72}
73
74/// Timestamped native remote video subscribe pipeline event.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct SubscribeTimingEvent {
77 /// Subscribe pipeline stage reached by the frame.
78 pub stage: SubscribeTimingStage,
79 /// Wall-clock time when this stage was observed, in microseconds since the Unix epoch.
80 pub timestamp_us: u64,
81 /// User capture timestamp associated with this frame, in microseconds since the Unix epoch.
82 pub capture_timestamp_us: u64,
83 /// Optional application frame ID associated with this frame.
84 pub frame_id: Option<u32>,
85}
86
87/// Callback invoked for native local video publish timing events.
88pub type PublishTimingObserver = Arc<dyn Fn(PublishTimingEvent) + Send + Sync + 'static>;
89/// Callback invoked for native remote video subscribe timing events.
90pub type SubscribeTimingObserver = Arc<dyn Fn(SubscribeTimingEvent) + Send + Sync + 'static>;
91
92impl From<sys_pt::VideoPublishTimingStage> for PublishTimingStage {
93 fn from(stage: sys_pt::VideoPublishTimingStage) -> Self {
94 match stage {
95 sys_pt::VideoPublishTimingStage::EncoderUpload => Self::EncoderUpload,
96 sys_pt::VideoPublishTimingStage::EncoderOutput => Self::EncoderOutput,
97 sys_pt::VideoPublishTimingStage::WebrtcPacketize => Self::WebrtcPacketize,
98 _ => Self::WebrtcPacketize,
99 }
100 }
101}
102
103impl From<sys_pt::VideoPublishTimingEvent> for PublishTimingEvent {
104 fn from(event: sys_pt::VideoPublishTimingEvent) -> Self {
105 Self {
106 stage: event.stage.into(),
107 timestamp_us: event.timestamp_us,
108 capture_timestamp_us: event.capture_timestamp_us,
109 frame_id: (event.frame_id != 0).then_some(event.frame_id),
110 }
111 }
112}
113
114impl From<sys_pt::VideoSubscribeTimingStage> for SubscribeTimingStage {
115 fn from(stage: sys_pt::VideoSubscribeTimingStage) -> Self {
116 match stage {
117 sys_pt::VideoSubscribeTimingStage::WebrtcReceive => Self::WebrtcReceive,
118 sys_pt::VideoSubscribeTimingStage::DecoderUpload => Self::DecoderUpload,
119 sys_pt::VideoSubscribeTimingStage::DecoderOutput => Self::DecoderOutput,
120 _ => Self::DecoderOutput,
121 }
122 }
123}
124
125impl From<sys_pt::VideoSubscribeTimingEvent> for SubscribeTimingEvent {
126 fn from(event: sys_pt::VideoSubscribeTimingEvent) -> Self {
127 Self {
128 stage: event.stage.into(),
129 timestamp_us: event.timestamp_us,
130 capture_timestamp_us: event.capture_timestamp_us,
131 frame_id: (event.frame_id != 0).then_some(event.frame_id),
132 }
133 }
134}
135
136/// Handler for packet trailer embedding/extraction on RTP streams.
137///
138/// For sender side: Stores frame metadata keyed by capture timestamp
139/// and embeds them as binary payload trailers on encoded frames before they
140/// are sent. Use `store_frame_metadata()` to associate metadata with
141/// a captured frame.
142///
143/// For receiver side: Extracts frame metadata from received frames
144/// and makes them available for retrieval via `lookup_frame_metadata()`.
145#[derive(Clone)]
146pub struct PacketTrailerHandler {
147 sys_handle: SharedPtr<sys_pt::PacketTrailerHandler>,
148}
149
150impl PacketTrailerHandler {
151 /// Enable or disable timestamp embedding/extraction.
152 pub fn set_enabled(&self, enabled: bool) {
153 self.sys_handle.set_enabled(enabled);
154 }
155
156 /// Check if timestamp embedding/extraction is enabled.
157 pub fn enabled(&self) -> bool {
158 self.sys_handle.enabled()
159 }
160
161 /// Lookup the frame metadata for a given RTP timestamp (receiver side).
162 /// Returns `Some((user_timestamp, frame_id, user_data))` if found,
163 /// `None` otherwise. The entry is removed from the map after a
164 /// successful lookup.
165 pub fn lookup_frame_metadata(&self, rtp_timestamp: u32) -> Option<(u64, u32, Vec<u8>)> {
166 let ts = self.sys_handle.lookup_timestamp(rtp_timestamp);
167 if ts != u64::MAX {
168 let frame_id = self.sys_handle.last_lookup_frame_id();
169 let user_data = self.sys_handle.last_lookup_user_data();
170 Some((ts, frame_id, user_data))
171 } else {
172 None
173 }
174 }
175
176 /// Store frame metadata for a given capture timestamp (sender side).
177 ///
178 /// The `capture_timestamp_us` must be the TimestampAligner-adjusted
179 /// timestamp (as produced by `VideoTrackSource::on_captured_frame`),
180 /// NOT the original `timestamp_us` from the VideoFrame. The transformer
181 /// looks up the metadata by the frame's `CaptureTime()` which is
182 /// derived from the aligned value.
183 ///
184 /// In normal usage this is called automatically by the C++ layer --
185 /// callers should set `user_timestamp` and `frame_id` on the
186 /// `VideoFrame` and let `capture_frame` / `on_captured_frame` handle
187 /// the rest.
188 pub fn store_frame_metadata(
189 &self,
190 capture_timestamp_us: i64,
191 user_timestamp: u64,
192 frame_id: u32,
193 user_data: &[u8],
194 ) {
195 self.sys_handle.store_frame_metadata(
196 capture_timestamp_us,
197 user_timestamp,
198 frame_id,
199 user_data,
200 );
201 }
202
203 pub(crate) fn sys_handle(&self) -> SharedPtr<sys_pt::PacketTrailerHandler> {
204 self.sys_handle.clone()
205 }
206
207 /// Set the callback receiving sender-side publish timing events.
208 pub fn set_publish_timing_observer(&self, observer: Option<PublishTimingObserver>) {
209 if let Some(observer) = observer {
210 self.sys_handle.set_publish_timing_observer(Box::new(
211 webrtc_sys::packet_trailer::VideoPublishTimingObserverWrapper::new(Box::new(
212 move |event| observer(event.into()),
213 )),
214 ));
215 } else {
216 self.sys_handle.clear_publish_timing_observer();
217 }
218 }
219
220 /// Set the callback receiving receiver-side subscribe timing events.
221 pub fn set_subscribe_timing_observer(&self, observer: Option<SubscribeTimingObserver>) {
222 if let Some(observer) = observer {
223 self.sys_handle.set_subscribe_timing_observer(Box::new(
224 webrtc_sys::packet_trailer::VideoSubscribeTimingObserverWrapper::new(Box::new(
225 move |event| observer(event.into()),
226 )),
227 ));
228 } else {
229 self.sys_handle.clear_subscribe_timing_observer();
230 }
231 }
232
233 pub(crate) fn emit_subscribe_timing(
234 &self,
235 stage: SubscribeTimingStage,
236 capture_timestamp_us: u64,
237 frame_id: u32,
238 ) {
239 let stage = match stage {
240 SubscribeTimingStage::WebrtcReceive => sys_pt::VideoSubscribeTimingStage::WebrtcReceive,
241 SubscribeTimingStage::DecoderUpload => sys_pt::VideoSubscribeTimingStage::DecoderUpload,
242 SubscribeTimingStage::DecoderOutput => sys_pt::VideoSubscribeTimingStage::DecoderOutput,
243 };
244 self.sys_handle.emit_subscribe_timing(stage, capture_timestamp_us, frame_id);
245 }
246}
247
248/// Create a sender-side packet trailer handler.
249///
250/// This handler will embed frame metadata into encoded frames before
251/// they are packetized and sent. Use `store_frame_metadata()` to
252/// associate metadata with a captured frame's capture timestamp.
253pub fn create_sender_handler(
254 peer_factory: &PeerConnectionFactory,
255 sender: &RtpSender,
256) -> PacketTrailerHandler {
257 PacketTrailerHandler {
258 sys_handle: sys_pt::new_packet_trailer_sender(
259 peer_factory.handle.sys_handle.clone(),
260 sender.handle.sys_handle.clone(),
261 ),
262 }
263}
264
265/// Create a receiver-side packet trailer handler.
266///
267/// This handler will extract frame metadata from received frames
268/// and store them in a map keyed by RTP timestamp. Use
269/// `lookup_frame_metadata(rtp_timestamp)` to retrieve the metadata
270/// for a specific decoded frame.
271pub fn create_receiver_handler(
272 peer_factory: &PeerConnectionFactory,
273 receiver: &RtpReceiver,
274) -> PacketTrailerHandler {
275 PacketTrailerHandler {
276 sys_handle: sys_pt::new_packet_trailer_receiver(
277 peer_factory.handle.sys_handle.clone(),
278 receiver.handle.sys_handle.clone(),
279 ),
280 }
281}
vendor/libwebrtc/src/native/peer_connection.rs added +620 −0
@@ -0,0 +1,620 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::sync::Arc;
16
17 use cxx::SharedPtr;
18 use parking_lot::Mutex;
19 use tokio::sync::{mpsc, oneshot};
20 use webrtc_sys::{
21 data_channel as sys_dc, jsep as sys_jsep, peer_connection as sys_pc,
22 peer_connection_factory as sys_pcf, rtc_error as sys_err,
23 };
24
25 use crate::{
26 data_channel::{DataChannel, DataChannelInit},
27 ice_candidate::IceCandidate,
28 imp::{
29 data_channel as imp_dc, ice_candidate as imp_ic, media_stream as imp_ms,
30 media_stream_track as imp_mst, rtp_receiver as imp_rr, rtp_sender as imp_rs,
31 rtp_transceiver as imp_rt, session_description as imp_sdp,
32 },
33 media_stream::MediaStream,
34 media_stream_track::MediaStreamTrack,
35 peer_connection::{
36 AnswerOptions, IceCandidateError, IceConnectionState, IceGatheringState, OfferOptions,
37 OnConnectionChange, OnDataChannel, OnIceCandidate, OnIceCandidateError,
38 OnIceConnectionChange, OnIceGatheringChange, OnNegotiationNeeded, OnSignalingChange,
39 OnTrack, PeerConnectionState, SignalingState, TrackEvent,
40 },
41 peer_connection_factory::{
42 ContinualGatheringPolicy, IceServer, IceTransportsType, RtcConfiguration,
43 },
44 rtp_receiver::RtpReceiver,
45 rtp_sender::RtpSender,
46 rtp_transceiver::{RtpTransceiver, RtpTransceiverInit},
47 session_description::SessionDescription,
48 stats::RtcStats,
49 MediaType, RtcError, RtcErrorType,
50 };
51
52 impl From<OfferOptions> for sys_pc::ffi::RtcOfferAnswerOptions {
53 fn from(options: OfferOptions) -> Self {
54 Self {
55 ice_restart: options.ice_restart,
56 offer_to_receive_audio: options.offer_to_receive_audio as i32,
57 offer_to_receive_video: options.offer_to_receive_video as i32,
58 ..Default::default()
59 }
60 }
61 }
62
63 impl From<AnswerOptions> for sys_pc::ffi::RtcOfferAnswerOptions {
64 fn from(_options: AnswerOptions) -> Self {
65 Self::default()
66 }
67 }
68
69 impl From<sys_pc::ffi::PeerConnectionState> for PeerConnectionState {
70 fn from(state: sys_pc::ffi::PeerConnectionState) -> Self {
71 match state {
72 sys_pc::ffi::PeerConnectionState::New => PeerConnectionState::New,
73 sys_pc::ffi::PeerConnectionState::Connecting => PeerConnectionState::Connecting,
74 sys_pc::ffi::PeerConnectionState::Connected => PeerConnectionState::Connected,
75 sys_pc::ffi::PeerConnectionState::Disconnected => PeerConnectionState::Disconnected,
76 sys_pc::ffi::PeerConnectionState::Failed => PeerConnectionState::Failed,
77 sys_pc::ffi::PeerConnectionState::Closed => PeerConnectionState::Closed,
78 _ => panic!("unknown PeerConnectionState"),
79 }
80 }
81 }
82
83 impl From<sys_pc::ffi::IceConnectionState> for IceConnectionState {
84 fn from(state: sys_pc::ffi::IceConnectionState) -> Self {
85 match state {
86 sys_pc::ffi::IceConnectionState::IceConnectionNew => IceConnectionState::New,
87 sys_pc::ffi::IceConnectionState::IceConnectionChecking => IceConnectionState::Checking,
88 sys_pc::ffi::IceConnectionState::IceConnectionConnected => {
89 IceConnectionState::Connected
90 }
91 sys_pc::ffi::IceConnectionState::IceConnectionCompleted => {
92 IceConnectionState::Completed
93 }
94 sys_pc::ffi::IceConnectionState::IceConnectionFailed => IceConnectionState::Failed,
95 sys_pc::ffi::IceConnectionState::IceConnectionDisconnected => {
96 IceConnectionState::Disconnected
97 }
98 sys_pc::ffi::IceConnectionState::IceConnectionClosed => IceConnectionState::Closed,
99 sys_pc::ffi::IceConnectionState::IceConnectionMax => IceConnectionState::Max,
100 _ => panic!("unknown IceConnectionState"),
101 }
102 }
103 }
104
105 impl From<sys_pc::ffi::IceGatheringState> for IceGatheringState {
106 fn from(state: sys_pc::ffi::IceGatheringState) -> Self {
107 match state {
108 sys_pc::ffi::IceGatheringState::IceGatheringNew => IceGatheringState::New,
109 sys_pc::ffi::IceGatheringState::IceGatheringGathering => IceGatheringState::Gathering,
110 sys_pc::ffi::IceGatheringState::IceGatheringComplete => IceGatheringState::Complete,
111 _ => panic!("unknown IceGatheringState"),
112 }
113 }
114 }
115
116 impl From<sys_pc::ffi::SignalingState> for SignalingState {
117 fn from(state: sys_pc::ffi::SignalingState) -> Self {
118 match state {
119 sys_pc::ffi::SignalingState::Stable => SignalingState::Stable,
120 sys_pc::ffi::SignalingState::HaveLocalOffer => SignalingState::HaveLocalOffer,
121 sys_pc::ffi::SignalingState::HaveRemoteOffer => SignalingState::HaveRemoteOffer,
122 sys_pc::ffi::SignalingState::HaveLocalPrAnswer => SignalingState::HaveLocalPrAnswer,
123 sys_pc::ffi::SignalingState::HaveRemotePrAnswer => SignalingState::HaveRemotePrAnswer,
124 sys_pc::ffi::SignalingState::Closed => SignalingState::Closed,
125 _ => panic!("unknown SignalingState"),
126 }
127 }
128 }
129
130 impl From<IceServer> for sys_pc::ffi::IceServer {
131 fn from(value: IceServer) -> Self {
132 sys_pc::ffi::IceServer {
133 urls: value.urls,
134 username: value.username,
135 password: value.password,
136 }
137 }
138 }
139
140 impl From<ContinualGatheringPolicy> for sys_pc::ffi::ContinualGatheringPolicy {
141 fn from(value: ContinualGatheringPolicy) -> Self {
142 match value {
143 ContinualGatheringPolicy::GatherOnce => {
144 sys_pc::ffi::ContinualGatheringPolicy::GatherOnce
145 }
146 ContinualGatheringPolicy::GatherContinually => {
147 sys_pc::ffi::ContinualGatheringPolicy::GatherContinually
148 }
149 }
150 }
151 }
152
153 impl From<IceTransportsType> for sys_pc::ffi::IceTransportsType {
154 fn from(value: IceTransportsType) -> Self {
155 match value {
156 IceTransportsType::Relay => sys_pc::ffi::IceTransportsType::Relay,
157 IceTransportsType::NoHost => sys_pc::ffi::IceTransportsType::NoHost,
158 IceTransportsType::All => sys_pc::ffi::IceTransportsType::All,
159 }
160 }
161 }
162
163 impl From<RtcConfiguration> for sys_pc::ffi::RtcConfiguration {
164 fn from(value: RtcConfiguration) -> Self {
165 Self {
166 ice_servers: value.ice_servers.into_iter().map(Into::into).collect(),
167 continual_gathering_policy: value.continual_gathering_policy.into(),
168 ice_transport_type: value.ice_transport_type.into(),
169 enable_sctp_snap: value.enable_sctp_snap,
170 }
171 }
172 }
173
174 #[derive(Clone)]
175 pub struct PeerConnection {
176 observer: Arc<PeerObserver>,
177 pub(crate) sys_handle: SharedPtr<sys_pc::ffi::PeerConnection>,
178 }
179
180 impl PeerConnection {
181 pub fn configure(
182 sys_handle: SharedPtr<sys_pc::ffi::PeerConnection>,
183 observer: Arc<PeerObserver>,
184 ) -> Self {
185 Self { sys_handle, observer }
186 }
187
188 pub fn set_configuration(&self, config: RtcConfiguration) -> Result<(), RtcError> {
189 let res = self.sys_handle.set_configuration(config.into());
190
191 match res {
192 Ok(_) => Ok(()),
193 Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) },
194 }
195 }
196
197 pub async fn create_offer(
198 &self,
199 options: OfferOptions,
200 ) -> Result<SessionDescription, RtcError> {
201 let (tx, mut rx) = mpsc::channel::<Result<SessionDescription, RtcError>>(1);
202 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
203 type CtxType = mpsc::Sender<Result<SessionDescription, RtcError>>;
204
205 self.sys_handle.create_offer(
206 options.into(),
207 ctx,
208 |ctx, sdp| {
209 let tx = *ctx.0.downcast::<CtxType>().unwrap();
210 let _ = tx.blocking_send(Ok(SessionDescription {
211 handle: imp_sdp::SessionDescription { sys_handle: sdp },
212 }));
213 },
214 |ctx, error| {
215 let tx = *ctx.0.downcast::<CtxType>().unwrap();
216 let _ = tx.blocking_send(Err(error.into()));
217 },
218 );
219
220 rx.recv().await.unwrap()
221 }
222
223 pub async fn create_answer(
224 &self,
225 options: AnswerOptions,
226 ) -> Result<SessionDescription, RtcError> {
227 let (tx, mut rx) = mpsc::channel::<Result<SessionDescription, RtcError>>(1);
228 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
229 type CtxType = mpsc::Sender<Result<SessionDescription, RtcError>>;
230
231 self.sys_handle.create_answer(
232 options.into(),
233 ctx,
234 |ctx, sdp| {
235 let tx = *ctx.0.downcast::<CtxType>().unwrap();
236 let _ = tx.blocking_send(Ok(SessionDescription {
237 handle: imp_sdp::SessionDescription { sys_handle: sdp },
238 }));
239 },
240 |ctx, error| {
241 let tx = *ctx.0.downcast::<CtxType>().unwrap();
242 let _ = tx.blocking_send(Err(error.into()));
243 },
244 );
245
246 rx.recv().await.unwrap()
247 }
248
249 pub async fn set_local_description(&self, desc: SessionDescription) -> Result<(), RtcError> {
250 let (tx, rx) = oneshot::channel::<Result<(), RtcError>>();
251 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
252
253 self.sys_handle.set_local_description(desc.handle.sys_handle, ctx, |ctx, err| {
254 let tx = ctx.0.downcast::<oneshot::Sender<Result<(), RtcError>>>().unwrap();
255
256 if err.ok() {
257 let _ = tx.send(Ok(()));
258 } else {
259 let _ = tx.send(Err(err.into()));
260 }
261 });
262
263 rx.await.unwrap()
264 }
265
266 pub async fn set_remote_description(&self, desc: SessionDescription) -> Result<(), RtcError> {
267 let (tx, rx) = oneshot::channel::<Result<(), RtcError>>();
268 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
269
270 self.sys_handle.set_remote_description(desc.handle.sys_handle, ctx, |ctx, err| {
271 let tx = ctx.0.downcast::<oneshot::Sender<Result<(), RtcError>>>().unwrap();
272
273 if err.ok() {
274 let _ = tx.send(Ok(()));
275 } else {
276 let _ = tx.send(Err(err.into()));
277 }
278 });
279
280 rx.await.map_err(|_| RtcError {
281 error_type: RtcErrorType::Internal,
282 message: "set_remote_description cancelled".to_owned(),
283 })?
284 }
285
286 pub async fn add_ice_candidate(&self, candidate: IceCandidate) -> Result<(), RtcError> {
287 let (tx, rx) = oneshot::channel::<Result<(), RtcError>>();
288 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
289
290 self.sys_handle.add_ice_candidate(candidate.handle.sys_handle, ctx, |ctx, err| {
291 let tx = ctx.0.downcast::<oneshot::Sender<Result<(), RtcError>>>().unwrap();
292
293 if err.ok() {
294 let _ = tx.send(Ok(()));
295 } else {
296 let _ = tx.send(Err(err.into()));
297 }
298 });
299
300 rx.await.map_err(|_| RtcError {
301 error_type: RtcErrorType::Internal,
302 message: "add_ice_candidate cancelled".to_owned(),
303 })?
304 }
305
306 pub fn create_data_channel(
307 &self,
308 label: &str,
309 init: DataChannelInit,
310 ) -> Result<DataChannel, RtcError> {
311 let res = self.sys_handle.create_data_channel(label.to_string(), init.into());
312
313 match res {
314 Ok(sys_handle) => {
315 Ok(DataChannel { handle: imp_dc::DataChannel::configure(sys_handle) })
316 }
317 Err(e) => Err(unsafe { sys_err::ffi::RtcError::from(e.what()).into() }),
318 }
319 }
320
321 pub fn add_track<T: AsRef<str>>(
322 &self,
323 track: MediaStreamTrack,
324 stream_ids: &[T],
325 ) -> Result<RtpSender, RtcError> {
326 let stream_ids = stream_ids.iter().map(|s| s.as_ref().to_owned()).collect();
327 let res = self.sys_handle.add_track(track.sys_handle(), &stream_ids);
328
329 match res {
330 Ok(sys_handle) => Ok(RtpSender { handle: imp_rs::RtpSender { sys_handle } }),
331 Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) },
332 }
333 }
334
335 pub fn add_transceiver(
336 &self,
337 track: MediaStreamTrack,
338 init: RtpTransceiverInit,
339 ) -> Result<RtpTransceiver, RtcError> {
340 let res = self.sys_handle.add_transceiver(track.sys_handle(), init.into());
341
342 match res {
343 Ok(sys_handle) => Ok(RtpTransceiver { handle: imp_rt::RtpTransceiver { sys_handle } }),
344 Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) },
345 }
346 }
347
348 pub fn add_transceiver_for_media(
349 &self,
350 media_type: MediaType,
351 init: RtpTransceiverInit,
352 ) -> Result<RtpTransceiver, RtcError> {
353 let res = self.sys_handle.add_transceiver_for_media(media_type.into(), init.into());
354
355 match res {
356 Ok(cxx_handle) => {
357 Ok(RtpTransceiver { handle: imp_rt::RtpTransceiver { sys_handle: cxx_handle } })
358 }
359 Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) },
360 }
361 }
362
363 pub fn restart_ice(&self) {
364 self.sys_handle.restart_ice();
365 }
366
367 pub fn close(&self) {
368 self.sys_handle.close();
369 }
370
371 pub fn connection_state(&self) -> PeerConnectionState {
372 self.sys_handle.connection_state().into()
373 }
374
375 pub fn ice_connection_state(&self) -> IceConnectionState {
376 self.sys_handle.ice_connection_state().into()
377 }
378
379 pub fn ice_gathering_state(&self) -> IceGatheringState {
380 self.sys_handle.ice_gathering_state().into()
381 }
382
383 pub fn signaling_state(&self) -> SignalingState {
384 self.sys_handle.signaling_state().into()
385 }
386
387 pub fn current_local_description(&self) -> Option<SessionDescription> {
388 let sdp = self.sys_handle.current_local_description();
389 if sdp.is_null() {
390 return None;
391 }
392
393 Some(SessionDescription { handle: imp_sdp::SessionDescription { sys_handle: sdp } })
394 }
395
396 pub fn current_remote_description(&self) -> Option<SessionDescription> {
397 let sdp = self.sys_handle.current_remote_description();
398 if sdp.is_null() {
399 return None;
400 }
401
402 Some(SessionDescription { handle: imp_sdp::SessionDescription { sys_handle: sdp } })
403 }
404
405 pub fn remove_track(&self, sender: RtpSender) -> Result<(), RtcError> {
406 self.sys_handle
407 .remove_track(sender.handle.sys_handle)
408 .map_err(|e| unsafe { sys_err::ffi::RtcError::from(e.what()).into() })
409 }
410
411 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
412 let (tx, rx) = oneshot::channel::<Result<Vec<RtcStats>, RtcError>>();
413 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
414
415 self.sys_handle.get_stats(ctx, |ctx, stats| {
416 let tx = ctx.0.downcast::<oneshot::Sender<Result<Vec<RtcStats>, RtcError>>>().unwrap();
417
418 if stats.is_empty() {
419 let _ = tx.send(Ok(vec![]));
420 return;
421 }
422
423 // Unwrap because it should not happens
424 let vec = serde_json::from_str(&stats).unwrap();
425 let _ = tx.send(Ok(vec));
426 });
427
428 rx.await.map_err(|_| RtcError {
429 error_type: RtcErrorType::Internal,
430 message: "get_stats cancelled".to_owned(),
431 })?
432 }
433
434 pub fn senders(&self) -> Vec<RtpSender> {
435 self.sys_handle
436 .get_senders()
437 .into_iter()
438 .map(|sender| RtpSender { handle: imp_rs::RtpSender { sys_handle: sender.ptr } })
439 .collect()
440 }
441
442 pub fn receivers(&self) -> Vec<RtpReceiver> {
443 self.sys_handle
444 .get_receivers()
445 .into_iter()
446 .map(|receiver| RtpReceiver {
447 handle: imp_rr::RtpReceiver { sys_handle: receiver.ptr },
448 })
449 .collect()
450 }
451
452 pub fn transceivers(&self) -> Vec<RtpTransceiver> {
453 self.sys_handle
454 .get_transceivers()
455 .into_iter()
456 .map(|transceiver| RtpTransceiver {
457 handle: imp_rt::RtpTransceiver { sys_handle: transceiver.ptr },
458 })
459 .collect()
460 }
461
462 pub fn on_connection_state_change(&self, f: Option<OnConnectionChange>) {
463 *self.observer.connection_change_handler.lock() = f;
464 }
465
466 pub fn on_data_channel(&self, f: Option<OnDataChannel>) {
467 *self.observer.data_channel_handler.lock() = f;
468 }
469
470 pub fn on_ice_candidate(&self, f: Option<OnIceCandidate>) {
471 *self.observer.ice_candidate_handler.lock() = f;
472 }
473
474 pub fn on_ice_candidate_error(&self, f: Option<OnIceCandidateError>) {
475 *self.observer.ice_candidate_error_handler.lock() = f;
476 }
477
478 pub fn on_ice_connection_state_change(&self, f: Option<OnIceConnectionChange>) {
479 *self.observer.ice_connection_change_handler.lock() = f;
480 }
481
482 pub fn on_ice_gathering_state_change(&self, f: Option<OnIceGatheringChange>) {
483 *self.observer.ice_gathering_change_handler.lock() = f;
484 }
485
486 pub fn on_negotiation_needed(&self, f: Option<OnNegotiationNeeded>) {
487 *self.observer.negotiation_needed_handler.lock() = f;
488 }
489
490 pub fn on_signaling_state_change(&self, f: Option<OnSignalingChange>) {
491 *self.observer.signaling_change_handler.lock() = f;
492 }
493
494 pub fn on_track(&self, f: Option<OnTrack>) {
495 *self.observer.track_handler.lock() = f;
496 }
497 }
498
499 #[derive(Default)]
500 pub struct PeerObserver {
501 pub connection_change_handler: Mutex<Option<OnConnectionChange>>,
502 pub data_channel_handler: Mutex<Option<OnDataChannel>>,
503 pub ice_candidate_handler: Mutex<Option<OnIceCandidate>>,
504 pub ice_candidate_error_handler: Mutex<Option<OnIceCandidateError>>,
505 pub ice_connection_change_handler: Mutex<Option<OnIceConnectionChange>>,
506 pub ice_gathering_change_handler: Mutex<Option<OnIceGatheringChange>>,
507 pub negotiation_needed_handler: Mutex<Option<OnNegotiationNeeded>>,
508 pub signaling_change_handler: Mutex<Option<OnSignalingChange>>,
509 pub track_handler: Mutex<Option<OnTrack>>,
510 }
511
512 impl sys_pcf::PeerConnectionObserver for PeerObserver {
513 fn on_signaling_change(&self, new_state: sys_pc::ffi::SignalingState) {
514 if let Some(f) = self.signaling_change_handler.lock().as_mut() {
515 f(new_state.into());
516 }
517 }
518
519 fn on_add_stream(&self, _stream: SharedPtr<webrtc_sys::media_stream::ffi::MediaStream>) {}
520
521 fn on_remove_stream(&self, _stream: SharedPtr<webrtc_sys::media_stream::ffi::MediaStream>) {}
522
523 fn on_data_channel(&self, data_channel: SharedPtr<sys_dc::ffi::DataChannel>) {
524 if let Some(f) = self.data_channel_handler.lock().as_mut() {
525 f(DataChannel { handle: imp_dc::DataChannel::configure(data_channel) });
526 }
527 }
528
529 fn on_renegotiation_needed(&self) {}
530
531 fn on_negotiation_needed_event(&self, event: u32) {
532 if let Some(f) = self.negotiation_needed_handler.lock().as_mut() {
533 f(event);
534 }
535 }
536
537 fn on_ice_connection_change(&self, _new_state: sys_pc::ffi::IceConnectionState) {}
538
539 fn on_standardized_ice_connection_change(&self, new_state: sys_pc::ffi::IceConnectionState) {
540 if let Some(f) = self.ice_connection_change_handler.lock().as_mut() {
541 f(new_state.into());
542 }
543 }
544
545 fn on_connection_change(&self, new_state: sys_pc::ffi::PeerConnectionState) {
546 if let Some(f) = self.connection_change_handler.lock().as_mut() {
547 f(new_state.into());
548 }
549 }
550
551 fn on_ice_gathering_change(&self, new_state: sys_pc::ffi::IceGatheringState) {
552 if let Some(f) = self.ice_gathering_change_handler.lock().as_mut() {
553 f(new_state.into());
554 }
555 }
556
557 fn on_ice_candidate(&self, candidate: SharedPtr<sys_jsep::ffi::IceCandidate>) {
558 if let Some(f) = self.ice_candidate_handler.lock().as_mut() {
559 f(IceCandidate { handle: imp_ic::IceCandidate { sys_handle: candidate } });
560 }
561 }
562
563 fn on_ice_candidate_error(
564 &self,
565 address: String,
566 port: i32,
567 url: String,
568 error_code: i32,
569 error_text: String,
570 ) {
571 if let Some(f) = self.ice_candidate_error_handler.lock().as_mut() {
572 f(IceCandidateError { address, port, url, error_code, error_text });
573 }
574 }
575
576 fn on_ice_candidates_removed(
577 &self,
578 _removed: Vec<SharedPtr<webrtc_sys::candidate::ffi::Candidate>>,
579 ) {
580 }
581
582 fn on_ice_connection_receiving_change(&self, _receiving: bool) {}
583
584 fn on_ice_selected_candidate_pair_changed(
585 &self,
586 _event: sys_pcf::ffi::CandidatePairChangeEvent,
587 ) {
588 }
589
590 fn on_add_track(
591 &self,
592 _receiver: SharedPtr<webrtc_sys::rtp_receiver::ffi::RtpReceiver>,
593 _streams: Vec<SharedPtr<webrtc_sys::media_stream::ffi::MediaStream>>,
594 ) {
595 }
596
597 fn on_track(&self, transceiver: SharedPtr<webrtc_sys::rtp_transceiver::ffi::RtpTransceiver>) {
598 if let Some(f) = self.track_handler.lock().as_mut() {
599 let receiver = transceiver.receiver();
600 let streams = receiver.streams();
601 let track = receiver.track();
602
603 f(TrackEvent {
604 receiver: RtpReceiver { handle: imp_rr::RtpReceiver { sys_handle: receiver } },
605 streams: streams
606 .into_iter()
607 .map(|s| MediaStream { handle: imp_ms::MediaStream { sys_handle: s.ptr } })
608 .collect(),
609 track: imp_mst::new_media_stream_track(track),
610 transceiver: RtpTransceiver {
611 handle: imp_rt::RtpTransceiver { sys_handle: transceiver },
612 },
613 });
614 }
615 }
616
617 fn on_remove_track(&self, _receiver: SharedPtr<webrtc_sys::rtp_receiver::ffi::RtpReceiver>) {}
618
619 fn on_interesting_usage(&self, _usage_pattern: i32) {}
620 }
@@ -0,0 +1,620 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::Arc;
16
17use cxx::SharedPtr;
18use parking_lot::Mutex;
19use tokio::sync::{mpsc, oneshot};
20use webrtc_sys::{
21 data_channel as sys_dc, jsep as sys_jsep, peer_connection as sys_pc,
22 peer_connection_factory as sys_pcf, rtc_error as sys_err,
23};
24
25use crate::{
26 data_channel::{DataChannel, DataChannelInit},
27 ice_candidate::IceCandidate,
28 imp::{
29 data_channel as imp_dc, ice_candidate as imp_ic, media_stream as imp_ms,
30 media_stream_track as imp_mst, rtp_receiver as imp_rr, rtp_sender as imp_rs,
31 rtp_transceiver as imp_rt, session_description as imp_sdp,
32 },
33 media_stream::MediaStream,
34 media_stream_track::MediaStreamTrack,
35 peer_connection::{
36 AnswerOptions, IceCandidateError, IceConnectionState, IceGatheringState, OfferOptions,
37 OnConnectionChange, OnDataChannel, OnIceCandidate, OnIceCandidateError,
38 OnIceConnectionChange, OnIceGatheringChange, OnNegotiationNeeded, OnSignalingChange,
39 OnTrack, PeerConnectionState, SignalingState, TrackEvent,
40 },
41 peer_connection_factory::{
42 ContinualGatheringPolicy, IceServer, IceTransportsType, RtcConfiguration,
43 },
44 rtp_receiver::RtpReceiver,
45 rtp_sender::RtpSender,
46 rtp_transceiver::{RtpTransceiver, RtpTransceiverInit},
47 session_description::SessionDescription,
48 stats::RtcStats,
49 MediaType, RtcError, RtcErrorType,
50};
51
52impl From<OfferOptions> for sys_pc::ffi::RtcOfferAnswerOptions {
53 fn from(options: OfferOptions) -> Self {
54 Self {
55 ice_restart: options.ice_restart,
56 offer_to_receive_audio: options.offer_to_receive_audio as i32,
57 offer_to_receive_video: options.offer_to_receive_video as i32,
58 ..Default::default()
59 }
60 }
61}
62
63impl From<AnswerOptions> for sys_pc::ffi::RtcOfferAnswerOptions {
64 fn from(_options: AnswerOptions) -> Self {
65 Self::default()
66 }
67}
68
69impl From<sys_pc::ffi::PeerConnectionState> for PeerConnectionState {
70 fn from(state: sys_pc::ffi::PeerConnectionState) -> Self {
71 match state {
72 sys_pc::ffi::PeerConnectionState::New => PeerConnectionState::New,
73 sys_pc::ffi::PeerConnectionState::Connecting => PeerConnectionState::Connecting,
74 sys_pc::ffi::PeerConnectionState::Connected => PeerConnectionState::Connected,
75 sys_pc::ffi::PeerConnectionState::Disconnected => PeerConnectionState::Disconnected,
76 sys_pc::ffi::PeerConnectionState::Failed => PeerConnectionState::Failed,
77 sys_pc::ffi::PeerConnectionState::Closed => PeerConnectionState::Closed,
78 _ => panic!("unknown PeerConnectionState"),
79 }
80 }
81}
82
83impl From<sys_pc::ffi::IceConnectionState> for IceConnectionState {
84 fn from(state: sys_pc::ffi::IceConnectionState) -> Self {
85 match state {
86 sys_pc::ffi::IceConnectionState::IceConnectionNew => IceConnectionState::New,
87 sys_pc::ffi::IceConnectionState::IceConnectionChecking => IceConnectionState::Checking,
88 sys_pc::ffi::IceConnectionState::IceConnectionConnected => {
89 IceConnectionState::Connected
90 }
91 sys_pc::ffi::IceConnectionState::IceConnectionCompleted => {
92 IceConnectionState::Completed
93 }
94 sys_pc::ffi::IceConnectionState::IceConnectionFailed => IceConnectionState::Failed,
95 sys_pc::ffi::IceConnectionState::IceConnectionDisconnected => {
96 IceConnectionState::Disconnected
97 }
98 sys_pc::ffi::IceConnectionState::IceConnectionClosed => IceConnectionState::Closed,
99 sys_pc::ffi::IceConnectionState::IceConnectionMax => IceConnectionState::Max,
100 _ => panic!("unknown IceConnectionState"),
101 }
102 }
103}
104
105impl From<sys_pc::ffi::IceGatheringState> for IceGatheringState {
106 fn from(state: sys_pc::ffi::IceGatheringState) -> Self {
107 match state {
108 sys_pc::ffi::IceGatheringState::IceGatheringNew => IceGatheringState::New,
109 sys_pc::ffi::IceGatheringState::IceGatheringGathering => IceGatheringState::Gathering,
110 sys_pc::ffi::IceGatheringState::IceGatheringComplete => IceGatheringState::Complete,
111 _ => panic!("unknown IceGatheringState"),
112 }
113 }
114}
115
116impl From<sys_pc::ffi::SignalingState> for SignalingState {
117 fn from(state: sys_pc::ffi::SignalingState) -> Self {
118 match state {
119 sys_pc::ffi::SignalingState::Stable => SignalingState::Stable,
120 sys_pc::ffi::SignalingState::HaveLocalOffer => SignalingState::HaveLocalOffer,
121 sys_pc::ffi::SignalingState::HaveRemoteOffer => SignalingState::HaveRemoteOffer,
122 sys_pc::ffi::SignalingState::HaveLocalPrAnswer => SignalingState::HaveLocalPrAnswer,
123 sys_pc::ffi::SignalingState::HaveRemotePrAnswer => SignalingState::HaveRemotePrAnswer,
124 sys_pc::ffi::SignalingState::Closed => SignalingState::Closed,
125 _ => panic!("unknown SignalingState"),
126 }
127 }
128}
129
130impl From<IceServer> for sys_pc::ffi::IceServer {
131 fn from(value: IceServer) -> Self {
132 sys_pc::ffi::IceServer {
133 urls: value.urls,
134 username: value.username,
135 password: value.password,
136 }
137 }
138}
139
140impl From<ContinualGatheringPolicy> for sys_pc::ffi::ContinualGatheringPolicy {
141 fn from(value: ContinualGatheringPolicy) -> Self {
142 match value {
143 ContinualGatheringPolicy::GatherOnce => {
144 sys_pc::ffi::ContinualGatheringPolicy::GatherOnce
145 }
146 ContinualGatheringPolicy::GatherContinually => {
147 sys_pc::ffi::ContinualGatheringPolicy::GatherContinually
148 }
149 }
150 }
151}
152
153impl From<IceTransportsType> for sys_pc::ffi::IceTransportsType {
154 fn from(value: IceTransportsType) -> Self {
155 match value {
156 IceTransportsType::Relay => sys_pc::ffi::IceTransportsType::Relay,
157 IceTransportsType::NoHost => sys_pc::ffi::IceTransportsType::NoHost,
158 IceTransportsType::All => sys_pc::ffi::IceTransportsType::All,
159 }
160 }
161}
162
163impl From<RtcConfiguration> for sys_pc::ffi::RtcConfiguration {
164 fn from(value: RtcConfiguration) -> Self {
165 Self {
166 ice_servers: value.ice_servers.into_iter().map(Into::into).collect(),
167 continual_gathering_policy: value.continual_gathering_policy.into(),
168 ice_transport_type: value.ice_transport_type.into(),
169 enable_sctp_snap: value.enable_sctp_snap,
170 }
171 }
172}
173
174#[derive(Clone)]
175pub struct PeerConnection {
176 observer: Arc<PeerObserver>,
177 pub(crate) sys_handle: SharedPtr<sys_pc::ffi::PeerConnection>,
178}
179
180impl PeerConnection {
181 pub fn configure(
182 sys_handle: SharedPtr<sys_pc::ffi::PeerConnection>,
183 observer: Arc<PeerObserver>,
184 ) -> Self {
185 Self { sys_handle, observer }
186 }
187
188 pub fn set_configuration(&self, config: RtcConfiguration) -> Result<(), RtcError> {
189 let res = self.sys_handle.set_configuration(config.into());
190
191 match res {
192 Ok(_) => Ok(()),
193 Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) },
194 }
195 }
196
197 pub async fn create_offer(
198 &self,
199 options: OfferOptions,
200 ) -> Result<SessionDescription, RtcError> {
201 let (tx, mut rx) = mpsc::channel::<Result<SessionDescription, RtcError>>(1);
202 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
203 type CtxType = mpsc::Sender<Result<SessionDescription, RtcError>>;
204
205 self.sys_handle.create_offer(
206 options.into(),
207 ctx,
208 |ctx, sdp| {
209 let tx = *ctx.0.downcast::<CtxType>().unwrap();
210 let _ = tx.blocking_send(Ok(SessionDescription {
211 handle: imp_sdp::SessionDescription { sys_handle: sdp },
212 }));
213 },
214 |ctx, error| {
215 let tx = *ctx.0.downcast::<CtxType>().unwrap();
216 let _ = tx.blocking_send(Err(error.into()));
217 },
218 );
219
220 rx.recv().await.unwrap()
221 }
222
223 pub async fn create_answer(
224 &self,
225 options: AnswerOptions,
226 ) -> Result<SessionDescription, RtcError> {
227 let (tx, mut rx) = mpsc::channel::<Result<SessionDescription, RtcError>>(1);
228 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
229 type CtxType = mpsc::Sender<Result<SessionDescription, RtcError>>;
230
231 self.sys_handle.create_answer(
232 options.into(),
233 ctx,
234 |ctx, sdp| {
235 let tx = *ctx.0.downcast::<CtxType>().unwrap();
236 let _ = tx.blocking_send(Ok(SessionDescription {
237 handle: imp_sdp::SessionDescription { sys_handle: sdp },
238 }));
239 },
240 |ctx, error| {
241 let tx = *ctx.0.downcast::<CtxType>().unwrap();
242 let _ = tx.blocking_send(Err(error.into()));
243 },
244 );
245
246 rx.recv().await.unwrap()
247 }
248
249 pub async fn set_local_description(&self, desc: SessionDescription) -> Result<(), RtcError> {
250 let (tx, rx) = oneshot::channel::<Result<(), RtcError>>();
251 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
252
253 self.sys_handle.set_local_description(desc.handle.sys_handle, ctx, |ctx, err| {
254 let tx = ctx.0.downcast::<oneshot::Sender<Result<(), RtcError>>>().unwrap();
255
256 if err.ok() {
257 let _ = tx.send(Ok(()));
258 } else {
259 let _ = tx.send(Err(err.into()));
260 }
261 });
262
263 rx.await.unwrap()
264 }
265
266 pub async fn set_remote_description(&self, desc: SessionDescription) -> Result<(), RtcError> {
267 let (tx, rx) = oneshot::channel::<Result<(), RtcError>>();
268 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
269
270 self.sys_handle.set_remote_description(desc.handle.sys_handle, ctx, |ctx, err| {
271 let tx = ctx.0.downcast::<oneshot::Sender<Result<(), RtcError>>>().unwrap();
272
273 if err.ok() {
274 let _ = tx.send(Ok(()));
275 } else {
276 let _ = tx.send(Err(err.into()));
277 }
278 });
279
280 rx.await.map_err(|_| RtcError {
281 error_type: RtcErrorType::Internal,
282 message: "set_remote_description cancelled".to_owned(),
283 })?
284 }
285
286 pub async fn add_ice_candidate(&self, candidate: IceCandidate) -> Result<(), RtcError> {
287 let (tx, rx) = oneshot::channel::<Result<(), RtcError>>();
288 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
289
290 self.sys_handle.add_ice_candidate(candidate.handle.sys_handle, ctx, |ctx, err| {
291 let tx = ctx.0.downcast::<oneshot::Sender<Result<(), RtcError>>>().unwrap();
292
293 if err.ok() {
294 let _ = tx.send(Ok(()));
295 } else {
296 let _ = tx.send(Err(err.into()));
297 }
298 });
299
300 rx.await.map_err(|_| RtcError {
301 error_type: RtcErrorType::Internal,
302 message: "add_ice_candidate cancelled".to_owned(),
303 })?
304 }
305
306 pub fn create_data_channel(
307 &self,
308 label: &str,
309 init: DataChannelInit,
310 ) -> Result<DataChannel, RtcError> {
311 let res = self.sys_handle.create_data_channel(label.to_string(), init.into());
312
313 match res {
314 Ok(sys_handle) => {
315 Ok(DataChannel { handle: imp_dc::DataChannel::configure(sys_handle) })
316 }
317 Err(e) => Err(unsafe { sys_err::ffi::RtcError::from(e.what()).into() }),
318 }
319 }
320
321 pub fn add_track<T: AsRef<str>>(
322 &self,
323 track: MediaStreamTrack,
324 stream_ids: &[T],
325 ) -> Result<RtpSender, RtcError> {
326 let stream_ids = stream_ids.iter().map(|s| s.as_ref().to_owned()).collect();
327 let res = self.sys_handle.add_track(track.sys_handle(), &stream_ids);
328
329 match res {
330 Ok(sys_handle) => Ok(RtpSender { handle: imp_rs::RtpSender { sys_handle } }),
331 Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) },
332 }
333 }
334
335 pub fn add_transceiver(
336 &self,
337 track: MediaStreamTrack,
338 init: RtpTransceiverInit,
339 ) -> Result<RtpTransceiver, RtcError> {
340 let res = self.sys_handle.add_transceiver(track.sys_handle(), init.into());
341
342 match res {
343 Ok(sys_handle) => Ok(RtpTransceiver { handle: imp_rt::RtpTransceiver { sys_handle } }),
344 Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) },
345 }
346 }
347
348 pub fn add_transceiver_for_media(
349 &self,
350 media_type: MediaType,
351 init: RtpTransceiverInit,
352 ) -> Result<RtpTransceiver, RtcError> {
353 let res = self.sys_handle.add_transceiver_for_media(media_type.into(), init.into());
354
355 match res {
356 Ok(cxx_handle) => {
357 Ok(RtpTransceiver { handle: imp_rt::RtpTransceiver { sys_handle: cxx_handle } })
358 }
359 Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) },
360 }
361 }
362
363 pub fn restart_ice(&self) {
364 self.sys_handle.restart_ice();
365 }
366
367 pub fn close(&self) {
368 self.sys_handle.close();
369 }
370
371 pub fn connection_state(&self) -> PeerConnectionState {
372 self.sys_handle.connection_state().into()
373 }
374
375 pub fn ice_connection_state(&self) -> IceConnectionState {
376 self.sys_handle.ice_connection_state().into()
377 }
378
379 pub fn ice_gathering_state(&self) -> IceGatheringState {
380 self.sys_handle.ice_gathering_state().into()
381 }
382
383 pub fn signaling_state(&self) -> SignalingState {
384 self.sys_handle.signaling_state().into()
385 }
386
387 pub fn current_local_description(&self) -> Option<SessionDescription> {
388 let sdp = self.sys_handle.current_local_description();
389 if sdp.is_null() {
390 return None;
391 }
392
393 Some(SessionDescription { handle: imp_sdp::SessionDescription { sys_handle: sdp } })
394 }
395
396 pub fn current_remote_description(&self) -> Option<SessionDescription> {
397 let sdp = self.sys_handle.current_remote_description();
398 if sdp.is_null() {
399 return None;
400 }
401
402 Some(SessionDescription { handle: imp_sdp::SessionDescription { sys_handle: sdp } })
403 }
404
405 pub fn remove_track(&self, sender: RtpSender) -> Result<(), RtcError> {
406 self.sys_handle
407 .remove_track(sender.handle.sys_handle)
408 .map_err(|e| unsafe { sys_err::ffi::RtcError::from(e.what()).into() })
409 }
410
411 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
412 let (tx, rx) = oneshot::channel::<Result<Vec<RtcStats>, RtcError>>();
413 let ctx = Box::new(sys_pc::PeerContext(Box::new(tx)));
414
415 self.sys_handle.get_stats(ctx, |ctx, stats| {
416 let tx = ctx.0.downcast::<oneshot::Sender<Result<Vec<RtcStats>, RtcError>>>().unwrap();
417
418 if stats.is_empty() {
419 let _ = tx.send(Ok(vec![]));
420 return;
421 }
422
423 // Unwrap because it should not happens
424 let vec = serde_json::from_str(&stats).unwrap();
425 let _ = tx.send(Ok(vec));
426 });
427
428 rx.await.map_err(|_| RtcError {
429 error_type: RtcErrorType::Internal,
430 message: "get_stats cancelled".to_owned(),
431 })?
432 }
433
434 pub fn senders(&self) -> Vec<RtpSender> {
435 self.sys_handle
436 .get_senders()
437 .into_iter()
438 .map(|sender| RtpSender { handle: imp_rs::RtpSender { sys_handle: sender.ptr } })
439 .collect()
440 }
441
442 pub fn receivers(&self) -> Vec<RtpReceiver> {
443 self.sys_handle
444 .get_receivers()
445 .into_iter()
446 .map(|receiver| RtpReceiver {
447 handle: imp_rr::RtpReceiver { sys_handle: receiver.ptr },
448 })
449 .collect()
450 }
451
452 pub fn transceivers(&self) -> Vec<RtpTransceiver> {
453 self.sys_handle
454 .get_transceivers()
455 .into_iter()
456 .map(|transceiver| RtpTransceiver {
457 handle: imp_rt::RtpTransceiver { sys_handle: transceiver.ptr },
458 })
459 .collect()
460 }
461
462 pub fn on_connection_state_change(&self, f: Option<OnConnectionChange>) {
463 *self.observer.connection_change_handler.lock() = f;
464 }
465
466 pub fn on_data_channel(&self, f: Option<OnDataChannel>) {
467 *self.observer.data_channel_handler.lock() = f;
468 }
469
470 pub fn on_ice_candidate(&self, f: Option<OnIceCandidate>) {
471 *self.observer.ice_candidate_handler.lock() = f;
472 }
473
474 pub fn on_ice_candidate_error(&self, f: Option<OnIceCandidateError>) {
475 *self.observer.ice_candidate_error_handler.lock() = f;
476 }
477
478 pub fn on_ice_connection_state_change(&self, f: Option<OnIceConnectionChange>) {
479 *self.observer.ice_connection_change_handler.lock() = f;
480 }
481
482 pub fn on_ice_gathering_state_change(&self, f: Option<OnIceGatheringChange>) {
483 *self.observer.ice_gathering_change_handler.lock() = f;
484 }
485
486 pub fn on_negotiation_needed(&self, f: Option<OnNegotiationNeeded>) {
487 *self.observer.negotiation_needed_handler.lock() = f;
488 }
489
490 pub fn on_signaling_state_change(&self, f: Option<OnSignalingChange>) {
491 *self.observer.signaling_change_handler.lock() = f;
492 }
493
494 pub fn on_track(&self, f: Option<OnTrack>) {
495 *self.observer.track_handler.lock() = f;
496 }
497}
498
499#[derive(Default)]
500pub struct PeerObserver {
501 pub connection_change_handler: Mutex<Option<OnConnectionChange>>,
502 pub data_channel_handler: Mutex<Option<OnDataChannel>>,
503 pub ice_candidate_handler: Mutex<Option<OnIceCandidate>>,
504 pub ice_candidate_error_handler: Mutex<Option<OnIceCandidateError>>,
505 pub ice_connection_change_handler: Mutex<Option<OnIceConnectionChange>>,
506 pub ice_gathering_change_handler: Mutex<Option<OnIceGatheringChange>>,
507 pub negotiation_needed_handler: Mutex<Option<OnNegotiationNeeded>>,
508 pub signaling_change_handler: Mutex<Option<OnSignalingChange>>,
509 pub track_handler: Mutex<Option<OnTrack>>,
510}
511
512impl sys_pcf::PeerConnectionObserver for PeerObserver {
513 fn on_signaling_change(&self, new_state: sys_pc::ffi::SignalingState) {
514 if let Some(f) = self.signaling_change_handler.lock().as_mut() {
515 f(new_state.into());
516 }
517 }
518
519 fn on_add_stream(&self, _stream: SharedPtr<webrtc_sys::media_stream::ffi::MediaStream>) {}
520
521 fn on_remove_stream(&self, _stream: SharedPtr<webrtc_sys::media_stream::ffi::MediaStream>) {}
522
523 fn on_data_channel(&self, data_channel: SharedPtr<sys_dc::ffi::DataChannel>) {
524 if let Some(f) = self.data_channel_handler.lock().as_mut() {
525 f(DataChannel { handle: imp_dc::DataChannel::configure(data_channel) });
526 }
527 }
528
529 fn on_renegotiation_needed(&self) {}
530
531 fn on_negotiation_needed_event(&self, event: u32) {
532 if let Some(f) = self.negotiation_needed_handler.lock().as_mut() {
533 f(event);
534 }
535 }
536
537 fn on_ice_connection_change(&self, _new_state: sys_pc::ffi::IceConnectionState) {}
538
539 fn on_standardized_ice_connection_change(&self, new_state: sys_pc::ffi::IceConnectionState) {
540 if let Some(f) = self.ice_connection_change_handler.lock().as_mut() {
541 f(new_state.into());
542 }
543 }
544
545 fn on_connection_change(&self, new_state: sys_pc::ffi::PeerConnectionState) {
546 if let Some(f) = self.connection_change_handler.lock().as_mut() {
547 f(new_state.into());
548 }
549 }
550
551 fn on_ice_gathering_change(&self, new_state: sys_pc::ffi::IceGatheringState) {
552 if let Some(f) = self.ice_gathering_change_handler.lock().as_mut() {
553 f(new_state.into());
554 }
555 }
556
557 fn on_ice_candidate(&self, candidate: SharedPtr<sys_jsep::ffi::IceCandidate>) {
558 if let Some(f) = self.ice_candidate_handler.lock().as_mut() {
559 f(IceCandidate { handle: imp_ic::IceCandidate { sys_handle: candidate } });
560 }
561 }
562
563 fn on_ice_candidate_error(
564 &self,
565 address: String,
566 port: i32,
567 url: String,
568 error_code: i32,
569 error_text: String,
570 ) {
571 if let Some(f) = self.ice_candidate_error_handler.lock().as_mut() {
572 f(IceCandidateError { address, port, url, error_code, error_text });
573 }
574 }
575
576 fn on_ice_candidates_removed(
577 &self,
578 _removed: Vec<SharedPtr<webrtc_sys::candidate::ffi::Candidate>>,
579 ) {
580 }
581
582 fn on_ice_connection_receiving_change(&self, _receiving: bool) {}
583
584 fn on_ice_selected_candidate_pair_changed(
585 &self,
586 _event: sys_pcf::ffi::CandidatePairChangeEvent,
587 ) {
588 }
589
590 fn on_add_track(
591 &self,
592 _receiver: SharedPtr<webrtc_sys::rtp_receiver::ffi::RtpReceiver>,
593 _streams: Vec<SharedPtr<webrtc_sys::media_stream::ffi::MediaStream>>,
594 ) {
595 }
596
597 fn on_track(&self, transceiver: SharedPtr<webrtc_sys::rtp_transceiver::ffi::RtpTransceiver>) {
598 if let Some(f) = self.track_handler.lock().as_mut() {
599 let receiver = transceiver.receiver();
600 let streams = receiver.streams();
601 let track = receiver.track();
602
603 f(TrackEvent {
604 receiver: RtpReceiver { handle: imp_rr::RtpReceiver { sys_handle: receiver } },
605 streams: streams
606 .into_iter()
607 .map(|s| MediaStream { handle: imp_ms::MediaStream { sys_handle: s.ptr } })
608 .collect(),
609 track: imp_mst::new_media_stream_track(track),
610 transceiver: RtpTransceiver {
611 handle: imp_rt::RtpTransceiver { sys_handle: transceiver },
612 },
613 });
614 }
615 }
616
617 fn on_remove_track(&self, _receiver: SharedPtr<webrtc_sys::rtp_receiver::ffi::RtpReceiver>) {}
618
619 fn on_interesting_usage(&self, _usage_pattern: i32) {}
620}
vendor/libwebrtc/src/native/peer_connection_factory.rs added +376 −0
@@ -0,0 +1,376 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::sync::Arc;
16
17 use cxx::{SharedPtr, UniquePtr};
18 use lazy_static::lazy_static;
19 use parking_lot::Mutex;
20 use webrtc_sys::{peer_connection_factory as sys_pcf, rtc_error as sys_err, webrtc as sys_rtc};
21
22 use crate::{
23 audio_source::native::NativeAudioSource,
24 audio_track::RtcAudioTrack,
25 imp::{audio_track as imp_at, peer_connection as imp_pc, video_track as imp_vt},
26 peer_connection::PeerConnection,
27 peer_connection_factory::RtcConfiguration,
28 rtp_parameters::RtpCapabilities,
29 video_source::native::NativeVideoSource,
30 video_track::RtcVideoTrack,
31 MediaType, RtcError,
32 };
33
34 lazy_static! {
35 static ref LOG_SINK: Mutex<Option<UniquePtr<sys_rtc::ffi::LogSink>>> = Default::default();
36 }
37
38 fn ensure_log_sink() {
39 let mut log_sink = LOG_SINK.lock();
40 if log_sink.is_none() {
41 *log_sink = Some(sys_rtc::ffi::new_log_sink(|msg, _| {
42 let msg = msg.strip_suffix("\r\n").or(msg.strip_suffix('\n')).unwrap_or(&msg);
43 log::debug!(target: "libwebrtc", "{}", msg);
44 }));
45 }
46 }
47
48 #[derive(Clone)]
49 pub struct PeerConnectionFactory {
50 pub(crate) sys_handle: SharedPtr<sys_pcf::ffi::PeerConnectionFactory>,
51 }
52
53 impl Default for PeerConnectionFactory {
54 fn default() -> Self {
55 ensure_log_sink();
56 let sys_handle = sys_pcf::ffi::create_peer_connection_factory();
57 Self { sys_handle }
58 }
59 }
60
61 impl PeerConnectionFactory {
62 /// Creates a [`PeerConnectionFactory`] with the WebRTC-ForcePlayoutDelay field trial enabled.
63 pub fn with_zero_playout_delay() -> Self {
64 ensure_log_sink();
65 let sys_handle = sys_pcf::ffi::create_peer_connection_factory_with_zero_playout_delay();
66 Self { sys_handle }
67 }
68
69 /// Creates a [`PeerConnectionFactory`] with the given runtime options.
70 /// `zero_playout_delay` enables the WebRTC-ForcePlayoutDelay field trial;
71 /// `enable_warp` enables WARP (SPED via the WebRTC-IceHandshakeDtls field
72 /// trial; SNAP is carried on the RtcConfiguration, not a field trial). The
73 /// two are independent and may be combined.
74 pub fn with_options(zero_playout_delay: bool, enable_warp: bool) -> Self {
75 ensure_log_sink();
76 let sys_handle = sys_pcf::ffi::create_peer_connection_factory_with_options(
77 zero_playout_delay,
78 enable_warp,
79 );
80 Self { sys_handle }
81 }
82
83 #[cfg(test)]
84 pub(crate) fn zero_playout_delay_enabled(&self) -> bool {
85 self.sys_handle.zero_playout_delay_enabled()
86 }
87
88 pub fn create_peer_connection(
89 &self,
90 config: RtcConfiguration,
91 ) -> Result<PeerConnection, RtcError> {
92 let observer = Arc::new(imp_pc::PeerObserver::default());
93 let res = self.sys_handle.create_peer_connection(
94 config.into(),
95 Box::new(sys_pcf::PeerConnectionObserverWrapper::new(observer.clone())),
96 );
97
98 match res {
99 Ok(sys_handle) => Ok(PeerConnection {
100 handle: imp_pc::PeerConnection::configure(sys_handle, observer),
101 }),
102 Err(e) => Err(unsafe { sys_err::ffi::RtcError::from(e.what()).into() }),
103 }
104 }
105
106 pub fn create_video_track(&self, label: &str, source: NativeVideoSource) -> RtcVideoTrack {
107 RtcVideoTrack {
108 handle: imp_vt::RtcVideoTrack::new(
109 self.sys_handle.create_video_track(label.to_string(), source.handle.sys_handle()),
110 ),
111 }
112 }
113
114 pub fn create_audio_track(&self, label: &str, source: NativeAudioSource) -> RtcAudioTrack {
115 RtcAudioTrack {
116 handle: imp_at::RtcAudioTrack {
117 sys_handle: self
118 .sys_handle
119 .create_audio_track(label.to_string(), source.handle.sys_handle()),
120 },
121 }
122 }
123
124 /// Create an audio track that uses the Platform ADM for capture.
125 ///
126 /// This requires that `enable_platform_adm()` was called first.
127 /// The track will capture audio from the selected recording device.
128 pub fn create_device_audio_track(&self, label: &str) -> RtcAudioTrack {
129 RtcAudioTrack {
130 handle: imp_at::RtcAudioTrack {
131 sys_handle: self.sys_handle.create_device_audio_track(label.to_string()),
132 },
133 }
134 }
135
136 pub fn get_rtp_sender_capabilities(&self, media_type: MediaType) -> RtpCapabilities {
137 self.sys_handle.rtp_sender_capabilities(media_type.into()).into()
138 }
139
140 pub fn get_rtp_receiver_capabilities(&self, media_type: MediaType) -> RtpCapabilities {
141 self.sys_handle.rtp_receiver_capabilities(media_type.into()).into()
142 }
143
144 // ===== Device Management Methods =====
145
146 /// Get the number of playout (output) devices
147 pub fn playout_devices(&self) -> i16 {
148 self.sys_handle.audio_device().playout_devices()
149 }
150
151 /// Get the number of recording (input) devices
152 pub fn recording_devices(&self) -> i16 {
153 self.sys_handle.audio_device().recording_devices()
154 }
155
156 /// Get the name of a playout device by index
157 pub fn playout_device_name(&self, index: u16) -> String {
158 self.sys_handle.audio_device().playout_device_name(index)
159 }
160
161 /// Get the name of a recording device by index
162 pub fn recording_device_name(&self, index: u16) -> String {
163 self.sys_handle.audio_device().recording_device_name(index)
164 }
165
166 /// Get the GUID of a playout device by index
167 /// The GUID is a platform-specific unique identifier that is stable across device hot-plug events.
168 pub fn playout_device_guid(&self, index: u16) -> String {
169 self.sys_handle.audio_device().playout_device_guid(index)
170 }
171
172 /// Get the GUID of a recording device by index
173 /// The GUID is a platform-specific unique identifier that is stable across device hot-plug events.
174 pub fn recording_device_guid(&self, index: u16) -> String {
175 self.sys_handle.audio_device().recording_device_guid(index)
176 }
177
178 /// Set the playout device by index
179 pub fn set_playout_device(&self, index: u16) -> bool {
180 self.sys_handle.audio_device().set_playout_device(index)
181 }
182
183 /// Set the recording device by index
184 pub fn set_recording_device(&self, index: u16) -> bool {
185 self.sys_handle.audio_device().set_recording_device(index)
186 }
187
188 /// Set the playout device by GUID
189 /// This is preferred over index as GUIDs are stable across device hot-plug events.
190 pub fn set_playout_device_by_guid(&self, guid: &str) -> bool {
191 self.sys_handle.audio_device().set_playout_device_by_guid(guid.to_string())
192 }
193
194 /// Set the recording device by GUID
195 /// This is preferred over index as GUIDs are stable across device hot-plug events.
196 pub fn set_recording_device_by_guid(&self, guid: &str) -> bool {
197 self.sys_handle.audio_device().set_recording_device_by_guid(guid.to_string())
198 }
199
200 /// Stop recording (clears initialized state, allowing device switch)
201 pub fn stop_recording(&self) -> bool {
202 self.sys_handle.audio_device().stop_recording()
203 }
204
205 /// Initialize recording
206 pub fn init_recording(&self) -> bool {
207 self.sys_handle.audio_device().init_recording()
208 }
209
210 /// Start recording
211 pub fn start_recording(&self) -> bool {
212 self.sys_handle.audio_device().start_recording()
213 }
214
215 /// Check if recording is initialized
216 pub fn recording_is_initialized(&self) -> bool {
217 self.sys_handle.audio_device().recording_is_initialized()
218 }
219
220 /// Stop playout (clears initialized state, allowing device switch)
221 pub fn stop_playout(&self) -> bool {
222 self.sys_handle.audio_device().stop_playout()
223 }
224
225 /// Initialize playout
226 pub fn init_playout(&self) -> bool {
227 self.sys_handle.audio_device().init_playout()
228 }
229
230 /// Start playout
231 pub fn start_playout(&self) -> bool {
232 self.sys_handle.audio_device().start_playout()
233 }
234
235 /// Check if playout is initialized
236 pub fn playout_is_initialized(&self) -> bool {
237 self.sys_handle.audio_device().playout_is_initialized()
238 }
239
240 // ===== Built-in Audio Processing Methods =====
241 // These control hardware AEC/AGC/NS on platforms that support it (iOS, some Android)
242
243 /// Check if built-in (hardware) AEC is available on this device.
244 ///
245 /// Returns true on iOS (VPIO) and some Android devices.
246 /// Returns false on desktop platforms (macOS, Windows, Linux).
247 pub fn builtin_aec_is_available(&self) -> bool {
248 self.sys_handle.audio_device().builtin_aec_is_available()
249 }
250
251 /// Check if built-in (hardware) AGC is available on this device.
252 ///
253 /// Returns true on iOS (VPIO) and some Android devices.
254 /// Returns false on desktop platforms (macOS, Windows, Linux).
255 pub fn builtin_agc_is_available(&self) -> bool {
256 self.sys_handle.audio_device().builtin_agc_is_available()
257 }
258
259 /// Check if built-in (hardware) NS is available on this device.
260 ///
261 /// Returns true on iOS (VPIO) and some Android devices.
262 /// Returns false on desktop platforms (macOS, Windows, Linux).
263 pub fn builtin_ns_is_available(&self) -> bool {
264 self.sys_handle.audio_device().builtin_ns_is_available()
265 }
266
267 /// Enable or disable built-in (hardware) AEC.
268 ///
269 /// When disabled on platforms that support it, WebRTC's software AEC
270 /// will be used instead.
271 pub fn enable_builtin_aec(&self, enable: bool) -> bool {
272 self.sys_handle.audio_device().enable_builtin_aec(enable)
273 }
274
275 /// Enable or disable built-in (hardware) AGC.
276 ///
277 /// When disabled on platforms that support it, WebRTC's software AGC
278 /// will be used instead.
279 pub fn enable_builtin_agc(&self, enable: bool) -> bool {
280 self.sys_handle.audio_device().enable_builtin_agc(enable)
281 }
282
283 /// Enable or disable built-in (hardware) NS.
284 ///
285 /// When disabled on platforms that support it, WebRTC's software NS
286 /// will be used instead.
287 pub fn enable_builtin_ns(&self, enable: bool) -> bool {
288 self.sys_handle.audio_device().enable_builtin_ns(enable)
289 }
290
291 /// Control whether ADM recording (microphone) is enabled.
292 ///
293 /// When disabled, WebRTC's calls to InitRecording/StartRecording will be no-ops.
294 /// Use this when only using NativeAudioSource (no microphone capture needed).
295 /// This prevents the microphone from interfering with the audio pipeline.
296 pub fn set_adm_recording_enabled(&self, enabled: bool) {
297 self.sys_handle.audio_device().set_adm_recording_enabled(enabled)
298 }
299
300 /// Check if ADM recording (microphone) is enabled.
301 pub fn adm_recording_enabled(&self) -> bool {
302 self.sys_handle.audio_device().adm_recording_enabled()
303 }
304
305 /// Control whether ADM playout (speakers) is enabled.
306 ///
307 /// When disabled (default), playout uses synthetic mode - remote audio is
308 /// delivered via FFI callbacks to the application (e.g., Unity AudioSource).
309 /// When enabled, remote audio plays through the platform speakers with AEC.
310 pub fn set_adm_playout_enabled(&self, enabled: bool) {
311 self.sys_handle.audio_device().set_adm_playout_enabled(enabled)
312 }
313
314 /// Check if ADM playout (speakers) is enabled.
315 pub fn adm_playout_enabled(&self) -> bool {
316 self.sys_handle.audio_device().adm_playout_enabled()
317 }
318
319 // ===== Platform ADM Lifecycle Management =====
320
321 /// Acquires a reference to the Platform ADM.
322 ///
323 /// On first call, creates and initializes the Platform ADM. On subsequent
324 /// calls, just increments the reference count.
325 ///
326 /// Returns true if Platform ADM is ready for use, false if initialization failed.
327 pub fn acquire_platform_adm(&self) -> bool {
328 self.sys_handle.audio_device().acquire_platform_adm()
329 }
330
331 /// Releases a reference to the Platform ADM.
332 ///
333 /// When the reference count reaches zero, the Platform ADM is terminated
334 /// and the proxy returns to synthetic mode.
335 pub fn release_platform_adm(&self) {
336 self.sys_handle.audio_device().release_platform_adm()
337 }
338
339 /// Returns the current reference count for the Platform ADM.
340 pub fn platform_adm_ref_count(&self) -> i32 {
341 self.sys_handle.audio_device().platform_adm_ref_count()
342 }
343
344 /// Returns true if Platform ADM is currently active (ref_count > 0).
345 pub fn is_platform_adm_active(&self) -> bool {
346 self.sys_handle.audio_device().is_platform_adm_active()
347 }
348 }
349
350 #[cfg(test)]
351 mod tests {
352 use super::*;
353 use std::sync::Mutex;
354
355 static TEST_MUTEX: Mutex<()> = Mutex::new(());
356
357 #[tokio::test]
358 async fn test_peer_connection_factory_and_audio_device_controller_bridge() {
359 let _guard = TEST_MUTEX.lock().expect("test mutex poisoned");
360 let _ = env_logger::builder().is_test(true).try_init();
361
362 let factory = PeerConnectionFactory::default();
363 let source = NativeVideoSource::default();
364 let _track = factory.create_video_track("test", source);
365 let recording_count = factory.recording_devices();
366 let playout_count = factory.playout_devices();
367
368 assert!(recording_count >= 0);
369 assert!(playout_count >= 0);
370
371 let initial_recording = factory.adm_recording_enabled();
372 factory.set_adm_recording_enabled(!initial_recording);
373 assert_eq!(factory.adm_recording_enabled(), !initial_recording);
374 factory.set_adm_recording_enabled(initial_recording);
375 }
376 }
@@ -0,0 +1,376 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::Arc;
16
17use cxx::{SharedPtr, UniquePtr};
18use lazy_static::lazy_static;
19use parking_lot::Mutex;
20use webrtc_sys::{peer_connection_factory as sys_pcf, rtc_error as sys_err, webrtc as sys_rtc};
21
22use crate::{
23 audio_source::native::NativeAudioSource,
24 audio_track::RtcAudioTrack,
25 imp::{audio_track as imp_at, peer_connection as imp_pc, video_track as imp_vt},
26 peer_connection::PeerConnection,
27 peer_connection_factory::RtcConfiguration,
28 rtp_parameters::RtpCapabilities,
29 video_source::native::NativeVideoSource,
30 video_track::RtcVideoTrack,
31 MediaType, RtcError,
32};
33
34lazy_static! {
35 static ref LOG_SINK: Mutex<Option<UniquePtr<sys_rtc::ffi::LogSink>>> = Default::default();
36}
37
38fn ensure_log_sink() {
39 let mut log_sink = LOG_SINK.lock();
40 if log_sink.is_none() {
41 *log_sink = Some(sys_rtc::ffi::new_log_sink(|msg, _| {
42 let msg = msg.strip_suffix("\r\n").or(msg.strip_suffix('\n')).unwrap_or(&msg);
43 log::debug!(target: "libwebrtc", "{}", msg);
44 }));
45 }
46}
47
48#[derive(Clone)]
49pub struct PeerConnectionFactory {
50 pub(crate) sys_handle: SharedPtr<sys_pcf::ffi::PeerConnectionFactory>,
51}
52
53impl Default for PeerConnectionFactory {
54 fn default() -> Self {
55 ensure_log_sink();
56 let sys_handle = sys_pcf::ffi::create_peer_connection_factory();
57 Self { sys_handle }
58 }
59}
60
61impl PeerConnectionFactory {
62 /// Creates a [`PeerConnectionFactory`] with the WebRTC-ForcePlayoutDelay field trial enabled.
63 pub fn with_zero_playout_delay() -> Self {
64 ensure_log_sink();
65 let sys_handle = sys_pcf::ffi::create_peer_connection_factory_with_zero_playout_delay();
66 Self { sys_handle }
67 }
68
69 /// Creates a [`PeerConnectionFactory`] with the given runtime options.
70 /// `zero_playout_delay` enables the WebRTC-ForcePlayoutDelay field trial;
71 /// `enable_warp` enables WARP (SPED via the WebRTC-IceHandshakeDtls field
72 /// trial; SNAP is carried on the RtcConfiguration, not a field trial). The
73 /// two are independent and may be combined.
74 pub fn with_options(zero_playout_delay: bool, enable_warp: bool) -> Self {
75 ensure_log_sink();
76 let sys_handle = sys_pcf::ffi::create_peer_connection_factory_with_options(
77 zero_playout_delay,
78 enable_warp,
79 );
80 Self { sys_handle }
81 }
82
83 #[cfg(test)]
84 pub(crate) fn zero_playout_delay_enabled(&self) -> bool {
85 self.sys_handle.zero_playout_delay_enabled()
86 }
87
88 pub fn create_peer_connection(
89 &self,
90 config: RtcConfiguration,
91 ) -> Result<PeerConnection, RtcError> {
92 let observer = Arc::new(imp_pc::PeerObserver::default());
93 let res = self.sys_handle.create_peer_connection(
94 config.into(),
95 Box::new(sys_pcf::PeerConnectionObserverWrapper::new(observer.clone())),
96 );
97
98 match res {
99 Ok(sys_handle) => Ok(PeerConnection {
100 handle: imp_pc::PeerConnection::configure(sys_handle, observer),
101 }),
102 Err(e) => Err(unsafe { sys_err::ffi::RtcError::from(e.what()).into() }),
103 }
104 }
105
106 pub fn create_video_track(&self, label: &str, source: NativeVideoSource) -> RtcVideoTrack {
107 RtcVideoTrack {
108 handle: imp_vt::RtcVideoTrack::new(
109 self.sys_handle.create_video_track(label.to_string(), source.handle.sys_handle()),
110 ),
111 }
112 }
113
114 pub fn create_audio_track(&self, label: &str, source: NativeAudioSource) -> RtcAudioTrack {
115 RtcAudioTrack {
116 handle: imp_at::RtcAudioTrack {
117 sys_handle: self
118 .sys_handle
119 .create_audio_track(label.to_string(), source.handle.sys_handle()),
120 },
121 }
122 }
123
124 /// Create an audio track that uses the Platform ADM for capture.
125 ///
126 /// This requires that `enable_platform_adm()` was called first.
127 /// The track will capture audio from the selected recording device.
128 pub fn create_device_audio_track(&self, label: &str) -> RtcAudioTrack {
129 RtcAudioTrack {
130 handle: imp_at::RtcAudioTrack {
131 sys_handle: self.sys_handle.create_device_audio_track(label.to_string()),
132 },
133 }
134 }
135
136 pub fn get_rtp_sender_capabilities(&self, media_type: MediaType) -> RtpCapabilities {
137 self.sys_handle.rtp_sender_capabilities(media_type.into()).into()
138 }
139
140 pub fn get_rtp_receiver_capabilities(&self, media_type: MediaType) -> RtpCapabilities {
141 self.sys_handle.rtp_receiver_capabilities(media_type.into()).into()
142 }
143
144 // ===== Device Management Methods =====
145
146 /// Get the number of playout (output) devices
147 pub fn playout_devices(&self) -> i16 {
148 self.sys_handle.audio_device().playout_devices()
149 }
150
151 /// Get the number of recording (input) devices
152 pub fn recording_devices(&self) -> i16 {
153 self.sys_handle.audio_device().recording_devices()
154 }
155
156 /// Get the name of a playout device by index
157 pub fn playout_device_name(&self, index: u16) -> String {
158 self.sys_handle.audio_device().playout_device_name(index)
159 }
160
161 /// Get the name of a recording device by index
162 pub fn recording_device_name(&self, index: u16) -> String {
163 self.sys_handle.audio_device().recording_device_name(index)
164 }
165
166 /// Get the GUID of a playout device by index
167 /// The GUID is a platform-specific unique identifier that is stable across device hot-plug events.
168 pub fn playout_device_guid(&self, index: u16) -> String {
169 self.sys_handle.audio_device().playout_device_guid(index)
170 }
171
172 /// Get the GUID of a recording device by index
173 /// The GUID is a platform-specific unique identifier that is stable across device hot-plug events.
174 pub fn recording_device_guid(&self, index: u16) -> String {
175 self.sys_handle.audio_device().recording_device_guid(index)
176 }
177
178 /// Set the playout device by index
179 pub fn set_playout_device(&self, index: u16) -> bool {
180 self.sys_handle.audio_device().set_playout_device(index)
181 }
182
183 /// Set the recording device by index
184 pub fn set_recording_device(&self, index: u16) -> bool {
185 self.sys_handle.audio_device().set_recording_device(index)
186 }
187
188 /// Set the playout device by GUID
189 /// This is preferred over index as GUIDs are stable across device hot-plug events.
190 pub fn set_playout_device_by_guid(&self, guid: &str) -> bool {
191 self.sys_handle.audio_device().set_playout_device_by_guid(guid.to_string())
192 }
193
194 /// Set the recording device by GUID
195 /// This is preferred over index as GUIDs are stable across device hot-plug events.
196 pub fn set_recording_device_by_guid(&self, guid: &str) -> bool {
197 self.sys_handle.audio_device().set_recording_device_by_guid(guid.to_string())
198 }
199
200 /// Stop recording (clears initialized state, allowing device switch)
201 pub fn stop_recording(&self) -> bool {
202 self.sys_handle.audio_device().stop_recording()
203 }
204
205 /// Initialize recording
206 pub fn init_recording(&self) -> bool {
207 self.sys_handle.audio_device().init_recording()
208 }
209
210 /// Start recording
211 pub fn start_recording(&self) -> bool {
212 self.sys_handle.audio_device().start_recording()
213 }
214
215 /// Check if recording is initialized
216 pub fn recording_is_initialized(&self) -> bool {
217 self.sys_handle.audio_device().recording_is_initialized()
218 }
219
220 /// Stop playout (clears initialized state, allowing device switch)
221 pub fn stop_playout(&self) -> bool {
222 self.sys_handle.audio_device().stop_playout()
223 }
224
225 /// Initialize playout
226 pub fn init_playout(&self) -> bool {
227 self.sys_handle.audio_device().init_playout()
228 }
229
230 /// Start playout
231 pub fn start_playout(&self) -> bool {
232 self.sys_handle.audio_device().start_playout()
233 }
234
235 /// Check if playout is initialized
236 pub fn playout_is_initialized(&self) -> bool {
237 self.sys_handle.audio_device().playout_is_initialized()
238 }
239
240 // ===== Built-in Audio Processing Methods =====
241 // These control hardware AEC/AGC/NS on platforms that support it (iOS, some Android)
242
243 /// Check if built-in (hardware) AEC is available on this device.
244 ///
245 /// Returns true on iOS (VPIO) and some Android devices.
246 /// Returns false on desktop platforms (macOS, Windows, Linux).
247 pub fn builtin_aec_is_available(&self) -> bool {
248 self.sys_handle.audio_device().builtin_aec_is_available()
249 }
250
251 /// Check if built-in (hardware) AGC is available on this device.
252 ///
253 /// Returns true on iOS (VPIO) and some Android devices.
254 /// Returns false on desktop platforms (macOS, Windows, Linux).
255 pub fn builtin_agc_is_available(&self) -> bool {
256 self.sys_handle.audio_device().builtin_agc_is_available()
257 }
258
259 /// Check if built-in (hardware) NS is available on this device.
260 ///
261 /// Returns true on iOS (VPIO) and some Android devices.
262 /// Returns false on desktop platforms (macOS, Windows, Linux).
263 pub fn builtin_ns_is_available(&self) -> bool {
264 self.sys_handle.audio_device().builtin_ns_is_available()
265 }
266
267 /// Enable or disable built-in (hardware) AEC.
268 ///
269 /// When disabled on platforms that support it, WebRTC's software AEC
270 /// will be used instead.
271 pub fn enable_builtin_aec(&self, enable: bool) -> bool {
272 self.sys_handle.audio_device().enable_builtin_aec(enable)
273 }
274
275 /// Enable or disable built-in (hardware) AGC.
276 ///
277 /// When disabled on platforms that support it, WebRTC's software AGC
278 /// will be used instead.
279 pub fn enable_builtin_agc(&self, enable: bool) -> bool {
280 self.sys_handle.audio_device().enable_builtin_agc(enable)
281 }
282
283 /// Enable or disable built-in (hardware) NS.
284 ///
285 /// When disabled on platforms that support it, WebRTC's software NS
286 /// will be used instead.
287 pub fn enable_builtin_ns(&self, enable: bool) -> bool {
288 self.sys_handle.audio_device().enable_builtin_ns(enable)
289 }
290
291 /// Control whether ADM recording (microphone) is enabled.
292 ///
293 /// When disabled, WebRTC's calls to InitRecording/StartRecording will be no-ops.
294 /// Use this when only using NativeAudioSource (no microphone capture needed).
295 /// This prevents the microphone from interfering with the audio pipeline.
296 pub fn set_adm_recording_enabled(&self, enabled: bool) {
297 self.sys_handle.audio_device().set_adm_recording_enabled(enabled)
298 }
299
300 /// Check if ADM recording (microphone) is enabled.
301 pub fn adm_recording_enabled(&self) -> bool {
302 self.sys_handle.audio_device().adm_recording_enabled()
303 }
304
305 /// Control whether ADM playout (speakers) is enabled.
306 ///
307 /// When disabled (default), playout uses synthetic mode - remote audio is
308 /// delivered via FFI callbacks to the application (e.g., Unity AudioSource).
309 /// When enabled, remote audio plays through the platform speakers with AEC.
310 pub fn set_adm_playout_enabled(&self, enabled: bool) {
311 self.sys_handle.audio_device().set_adm_playout_enabled(enabled)
312 }
313
314 /// Check if ADM playout (speakers) is enabled.
315 pub fn adm_playout_enabled(&self) -> bool {
316 self.sys_handle.audio_device().adm_playout_enabled()
317 }
318
319 // ===== Platform ADM Lifecycle Management =====
320
321 /// Acquires a reference to the Platform ADM.
322 ///
323 /// On first call, creates and initializes the Platform ADM. On subsequent
324 /// calls, just increments the reference count.
325 ///
326 /// Returns true if Platform ADM is ready for use, false if initialization failed.
327 pub fn acquire_platform_adm(&self) -> bool {
328 self.sys_handle.audio_device().acquire_platform_adm()
329 }
330
331 /// Releases a reference to the Platform ADM.
332 ///
333 /// When the reference count reaches zero, the Platform ADM is terminated
334 /// and the proxy returns to synthetic mode.
335 pub fn release_platform_adm(&self) {
336 self.sys_handle.audio_device().release_platform_adm()
337 }
338
339 /// Returns the current reference count for the Platform ADM.
340 pub fn platform_adm_ref_count(&self) -> i32 {
341 self.sys_handle.audio_device().platform_adm_ref_count()
342 }
343
344 /// Returns true if Platform ADM is currently active (ref_count > 0).
345 pub fn is_platform_adm_active(&self) -> bool {
346 self.sys_handle.audio_device().is_platform_adm_active()
347 }
348}
349
350#[cfg(test)]
351mod tests {
352 use super::*;
353 use std::sync::Mutex;
354
355 static TEST_MUTEX: Mutex<()> = Mutex::new(());
356
357 #[tokio::test]
358 async fn test_peer_connection_factory_and_audio_device_controller_bridge() {
359 let _guard = TEST_MUTEX.lock().expect("test mutex poisoned");
360 let _ = env_logger::builder().is_test(true).try_init();
361
362 let factory = PeerConnectionFactory::default();
363 let source = NativeVideoSource::default();
364 let _track = factory.create_video_track("test", source);
365 let recording_count = factory.recording_devices();
366 let playout_count = factory.playout_devices();
367
368 assert!(recording_count >= 0);
369 assert!(playout_count >= 0);
370
371 let initial_recording = factory.adm_recording_enabled();
372 factory.set_adm_recording_enabled(!initial_recording);
373 assert_eq!(factory.adm_recording_enabled(), !initial_recording);
374 factory.set_adm_recording_enabled(initial_recording);
375 }
376}
vendor/libwebrtc/src/native/rtp_parameters.rs added +312 −0
@@ -0,0 +1,312 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use webrtc_sys::{rtp_parameters as sys_rp, webrtc as sys_webrtc};
16
17 use crate::rtp_parameters::*;
18
19 impl From<sys_webrtc::ffi::Priority> for Priority {
20 fn from(value: sys_webrtc::ffi::Priority) -> Self {
21 match value {
22 sys_webrtc::ffi::Priority::VeryLow => Self::VeryLow,
23 sys_webrtc::ffi::Priority::Low => Self::Low,
24 sys_webrtc::ffi::Priority::Medium => Self::Medium,
25 sys_webrtc::ffi::Priority::High => Self::High,
26 _ => panic!("unknown Priority"),
27 }
28 }
29 }
30
31 impl From<sys_rp::ffi::RtpExtension> for RtpHeaderExtensionParameters {
32 fn from(value: sys_rp::ffi::RtpExtension) -> Self {
33 Self { uri: value.uri, id: value.id, encrypted: value.encrypt }
34 }
35 }
36
37 impl From<sys_rp::ffi::RtpParameters> for RtpParameters {
38 fn from(value: sys_rp::ffi::RtpParameters) -> Self {
39 Self {
40 codecs: value.codecs.into_iter().map(Into::into).collect(),
41 header_extensions: value.header_extensions.into_iter().map(Into::into).collect(),
42 encodings: value.encodings.into_iter().map(Into::into).collect(),
43 rtcp: value.rtcp.into(),
44 transaction_id: value.transaction_id,
45 mid: value.mid,
46 has_degradation_preference: value.has_degradation_preference,
47 degradation_preference: value.degradation_preference.repr,
48 }
49 }
50 }
51
52 impl From<sys_rp::ffi::RtpCodecParameters> for RtpCodecParameters {
53 fn from(value: sys_rp::ffi::RtpCodecParameters) -> Self {
54 Self {
55 mime_type: value.mime_type,
56 payload_type: value.payload_type as u8,
57 clock_rate: value.has_clock_rate.then_some(value.clock_rate as u64),
58 channels: value.has_num_channels.then_some(value.num_channels as u16),
59 name: value.name,
60 kind: value.kind.repr,
61 has_max_ptime: value.has_max_ptime,
62 max_ptime: value.max_ptime,
63 has_ptime: value.has_ptime,
64 ptime: value.ptime,
65 rtcp_feedback: value
66 .rtcp_feedback
67 .into_iter()
68 .map(|f| CodecFeedback {
69 feedback_type: f.feedback_type.repr,
70 has_message_type: f.has_message_type,
71 message_type: f.message_type.repr,
72 })
73 .collect(),
74 parameters: value.parameters.into_iter().map(|kv| (kv.key, kv.value)).collect(),
75 }
76 }
77 }
78
79 impl From<sys_rp::ffi::RtcpParameters> for RtcpParameters {
80 fn from(value: sys_rp::ffi::RtcpParameters) -> Self {
81 Self {
82 cname: value.cname,
83 reduced_size: value.reduced_size,
84 mux: value.mux,
85 has_ssrc: value.has_ssrc,
86 ssrc: value.ssrc,
87 }
88 }
89 }
90
91 impl From<sys_rp::ffi::RtpEncodingParameters> for RtpEncodingParameters {
92 fn from(value: sys_rp::ffi::RtpEncodingParameters) -> Self {
93 Self {
94 active: value.active,
95 max_bitrate: value.has_max_bitrate_bps.then_some(value.max_bitrate_bps as u64),
96 max_framerate: value.has_max_framerate.then_some(value.max_framerate),
97 priority: value.network_priority.into(),
98 rid: value.rid,
99 scale_resolution_down_by: value
100 .has_scale_resolution_down_by
101 .then_some(value.scale_resolution_down_by),
102 scalability_mode: value.has_scalability_mode.then_some(value.scalability_mode),
103 has_ssrc: value.has_ssrc,
104 ssrc: value.ssrc,
105 }
106 }
107 }
108
109 impl From<sys_rp::ffi::RtpCodecCapability> for RtpCodecCapability {
110 fn from(value: sys_rp::ffi::RtpCodecCapability) -> Self {
111 Self {
112 channels: value.has_num_channels.then_some(value.num_channels as u16),
113 mime_type: value.mime_type,
114 clock_rate: value.has_clock_rate.then_some(value.clock_rate as u64),
115 sdp_fmtp_line: {
116 let parameters: Vec<String> = value
117 .parameters
118 .into_iter()
119 .map(|key_value| {
120 if !key_value.key.is_empty() {
121 format!("{}={}", key_value.key, key_value.value)
122 } else {
123 key_value.value
124 }
125 })
126 .collect();
127
128 if !parameters.is_empty() {
129 Some(parameters.join(";"))
130 } else {
131 None
132 }
133 },
134 }
135 }
136 }
137
138 impl From<sys_rp::ffi::RtpHeaderExtensionCapability> for RtpHeaderExtensionCapability {
139 fn from(value: sys_rp::ffi::RtpHeaderExtensionCapability) -> Self {
140 Self { direction: value.direction.into(), uri: value.uri }
141 }
142 }
143
144 impl From<sys_rp::ffi::RtpCapabilities> for RtpCapabilities {
145 fn from(value: sys_rp::ffi::RtpCapabilities) -> Self {
146 Self {
147 codecs: value.codecs.into_iter().map(Into::into).collect(),
148 header_extensions: value.header_extensions.into_iter().map(Into::into).collect(),
149 }
150 }
151 }
152
153 impl From<Priority> for sys_webrtc::ffi::Priority {
154 fn from(value: Priority) -> Self {
155 match value {
156 Priority::VeryLow => Self::VeryLow,
157 Priority::Low => Self::Low,
158 Priority::Medium => Self::Medium,
159 Priority::High => Self::High,
160 }
161 }
162 }
163
164 impl From<RtpHeaderExtensionParameters> for sys_rp::ffi::RtpExtension {
165 fn from(value: RtpHeaderExtensionParameters) -> Self {
166 Self { uri: value.uri, id: value.id, encrypt: value.encrypted }
167 }
168 }
169
170 impl From<RtpParameters> for sys_rp::ffi::RtpParameters {
171 fn from(value: RtpParameters) -> Self {
172 let degradation_preference =
173 sys_rp::ffi::DegradationPreference { repr: value.degradation_preference };
174 Self {
175 codecs: value.codecs.into_iter().map(Into::into).collect(),
176 header_extensions: value.header_extensions.into_iter().map(Into::into).collect(),
177 encodings: value.encodings.into_iter().map(Into::into).collect(),
178 rtcp: value.rtcp.into(),
179 transaction_id: value.transaction_id,
180 mid: value.mid,
181 has_degradation_preference: value.has_degradation_preference,
182 degradation_preference,
183 }
184 }
185 }
186
187 impl From<RtpCodecParameters> for sys_rp::ffi::RtpCodecParameters {
188 fn from(value: RtpCodecParameters) -> Self {
189 let kind = sys_webrtc::ffi::MediaType { repr: value.kind };
190 Self {
191 payload_type: value.payload_type as i32,
192 mime_type: value.mime_type,
193 has_clock_rate: value.clock_rate.is_some(),
194 clock_rate: value.clock_rate.unwrap_or_default() as i32,
195 has_num_channels: value.channels.is_some(),
196 num_channels: value.channels.unwrap_or_default() as i32,
197 name: value.name,
198 kind,
199 has_max_ptime: value.has_max_ptime,
200 max_ptime: value.max_ptime,
201 has_ptime: value.has_ptime,
202 ptime: value.ptime,
203 rtcp_feedback: value
204 .rtcp_feedback
205 .into_iter()
206 .map(|f| {
207 let feedback_type = sys_rp::ffi::RtcpFeedbackType { repr: f.feedback_type };
208 let message_type =
209 sys_rp::ffi::RtcpFeedbackMessageType { repr: f.message_type };
210 sys_rp::ffi::RtcpFeedback {
211 feedback_type,
212 has_message_type: f.has_message_type,
213 message_type,
214 }
215 })
216 .collect(),
217 parameters: value
218 .parameters
219 .into_iter()
220 .map(|(key, value)| sys_rp::ffi::StringKeyValue { key, value })
221 .collect(),
222 }
223 }
224 }
225
226 impl From<RtcpParameters> for sys_rp::ffi::RtcpParameters {
227 fn from(value: RtcpParameters) -> Self {
228 Self {
229 cname: value.cname,
230 reduced_size: value.reduced_size,
231 has_ssrc: value.has_ssrc,
232 ssrc: value.ssrc,
233 mux: value.mux,
234 }
235 }
236 }
237
238 impl From<RtpEncodingParameters> for sys_rp::ffi::RtpEncodingParameters {
239 fn from(value: RtpEncodingParameters) -> Self {
240 Self {
241 active: value.active,
242 has_max_bitrate_bps: value.max_bitrate.is_some(),
243 max_bitrate_bps: value.max_bitrate.unwrap_or_default() as i32,
244 has_max_framerate: value.max_framerate.is_some(),
245 max_framerate: value.max_framerate.unwrap_or_default(),
246 network_priority: value.priority.into(),
247 rid: value.rid,
248 has_scale_resolution_down_by: value.scale_resolution_down_by.is_some(),
249 scale_resolution_down_by: value.scale_resolution_down_by.unwrap_or_default(),
250 adaptive_ptime: false,
251 bitrate_priority: sys_rp::DEFAULT_BITRATE_PRIORITY,
252 has_min_bitrate_bps: false,
253 min_bitrate_bps: 0,
254 has_num_temporal_layers: false,
255 num_temporal_layers: 0,
256 has_scalability_mode: value.scalability_mode.is_some(),
257 scalability_mode: value.scalability_mode.unwrap_or_default(),
258 has_ssrc: value.has_ssrc,
259 ssrc: value.ssrc,
260 }
261 }
262 }
263
264 impl From<RtpCodecCapability> for sys_rp::ffi::RtpCodecCapability {
265 fn from(value: RtpCodecCapability) -> Self {
266 let mime_type: Vec<&str> = value.mime_type.split('/').collect();
267 let kind = match mime_type[0] {
268 "audio" => sys_webrtc::ffi::MediaType::Audio,
269 "video" => sys_webrtc::ffi::MediaType::Video,
270 _ => panic!("invalid media type"),
271 };
272 let name = mime_type[1].to_string();
273
274 Self {
275 name,
276 kind,
277 has_clock_rate: value.clock_rate.is_some(),
278 clock_rate: value.clock_rate.unwrap_or_default() as i32,
279 has_num_channels: value.channels.is_some(),
280 num_channels: value.channels.unwrap_or_default() as i32,
281 parameters: {
282 value
283 .sdp_fmtp_line
284 .map(|sdp_fmtp_line| {
285 sdp_fmtp_line
286 .split(';')
287 .map(|v| {
288 let key_value: Vec<&str> = v.split('=').collect();
289 if key_value.len() == 2 {
290 sys_rp::ffi::StringKeyValue {
291 key: key_value[0].to_string(),
292 value: key_value[1].to_string(),
293 }
294 } else {
295 sys_rp::ffi::StringKeyValue {
296 key: "".to_string(),
297 value: key_value[0].to_string(),
298 }
299 }
300 })
301 .collect()
302 })
303 .unwrap_or_default()
304 },
305 // Ignore
306 mime_type: String::default(), // !!
307 has_preferred_payload_type: false,
308 preferred_payload_type: 0,
309 rtcp_feedback: Vec::default(),
310 }
311 }
312 }
@@ -0,0 +1,312 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use webrtc_sys::{rtp_parameters as sys_rp, webrtc as sys_webrtc};
16
17use crate::rtp_parameters::*;
18
19impl From<sys_webrtc::ffi::Priority> for Priority {
20 fn from(value: sys_webrtc::ffi::Priority) -> Self {
21 match value {
22 sys_webrtc::ffi::Priority::VeryLow => Self::VeryLow,
23 sys_webrtc::ffi::Priority::Low => Self::Low,
24 sys_webrtc::ffi::Priority::Medium => Self::Medium,
25 sys_webrtc::ffi::Priority::High => Self::High,
26 _ => panic!("unknown Priority"),
27 }
28 }
29}
30
31impl From<sys_rp::ffi::RtpExtension> for RtpHeaderExtensionParameters {
32 fn from(value: sys_rp::ffi::RtpExtension) -> Self {
33 Self { uri: value.uri, id: value.id, encrypted: value.encrypt }
34 }
35}
36
37impl From<sys_rp::ffi::RtpParameters> for RtpParameters {
38 fn from(value: sys_rp::ffi::RtpParameters) -> Self {
39 Self {
40 codecs: value.codecs.into_iter().map(Into::into).collect(),
41 header_extensions: value.header_extensions.into_iter().map(Into::into).collect(),
42 encodings: value.encodings.into_iter().map(Into::into).collect(),
43 rtcp: value.rtcp.into(),
44 transaction_id: value.transaction_id,
45 mid: value.mid,
46 has_degradation_preference: value.has_degradation_preference,
47 degradation_preference: value.degradation_preference.repr,
48 }
49 }
50}
51
52impl From<sys_rp::ffi::RtpCodecParameters> for RtpCodecParameters {
53 fn from(value: sys_rp::ffi::RtpCodecParameters) -> Self {
54 Self {
55 mime_type: value.mime_type,
56 payload_type: value.payload_type as u8,
57 clock_rate: value.has_clock_rate.then_some(value.clock_rate as u64),
58 channels: value.has_num_channels.then_some(value.num_channels as u16),
59 name: value.name,
60 kind: value.kind.repr,
61 has_max_ptime: value.has_max_ptime,
62 max_ptime: value.max_ptime,
63 has_ptime: value.has_ptime,
64 ptime: value.ptime,
65 rtcp_feedback: value
66 .rtcp_feedback
67 .into_iter()
68 .map(|f| CodecFeedback {
69 feedback_type: f.feedback_type.repr,
70 has_message_type: f.has_message_type,
71 message_type: f.message_type.repr,
72 })
73 .collect(),
74 parameters: value.parameters.into_iter().map(|kv| (kv.key, kv.value)).collect(),
75 }
76 }
77}
78
79impl From<sys_rp::ffi::RtcpParameters> for RtcpParameters {
80 fn from(value: sys_rp::ffi::RtcpParameters) -> Self {
81 Self {
82 cname: value.cname,
83 reduced_size: value.reduced_size,
84 mux: value.mux,
85 has_ssrc: value.has_ssrc,
86 ssrc: value.ssrc,
87 }
88 }
89}
90
91impl From<sys_rp::ffi::RtpEncodingParameters> for RtpEncodingParameters {
92 fn from(value: sys_rp::ffi::RtpEncodingParameters) -> Self {
93 Self {
94 active: value.active,
95 max_bitrate: value.has_max_bitrate_bps.then_some(value.max_bitrate_bps as u64),
96 max_framerate: value.has_max_framerate.then_some(value.max_framerate),
97 priority: value.network_priority.into(),
98 rid: value.rid,
99 scale_resolution_down_by: value
100 .has_scale_resolution_down_by
101 .then_some(value.scale_resolution_down_by),
102 scalability_mode: value.has_scalability_mode.then_some(value.scalability_mode),
103 has_ssrc: value.has_ssrc,
104 ssrc: value.ssrc,
105 }
106 }
107}
108
109impl From<sys_rp::ffi::RtpCodecCapability> for RtpCodecCapability {
110 fn from(value: sys_rp::ffi::RtpCodecCapability) -> Self {
111 Self {
112 channels: value.has_num_channels.then_some(value.num_channels as u16),
113 mime_type: value.mime_type,
114 clock_rate: value.has_clock_rate.then_some(value.clock_rate as u64),
115 sdp_fmtp_line: {
116 let parameters: Vec<String> = value
117 .parameters
118 .into_iter()
119 .map(|key_value| {
120 if !key_value.key.is_empty() {
121 format!("{}={}", key_value.key, key_value.value)
122 } else {
123 key_value.value
124 }
125 })
126 .collect();
127
128 if !parameters.is_empty() {
129 Some(parameters.join(";"))
130 } else {
131 None
132 }
133 },
134 }
135 }
136}
137
138impl From<sys_rp::ffi::RtpHeaderExtensionCapability> for RtpHeaderExtensionCapability {
139 fn from(value: sys_rp::ffi::RtpHeaderExtensionCapability) -> Self {
140 Self { direction: value.direction.into(), uri: value.uri }
141 }
142}
143
144impl From<sys_rp::ffi::RtpCapabilities> for RtpCapabilities {
145 fn from(value: sys_rp::ffi::RtpCapabilities) -> Self {
146 Self {
147 codecs: value.codecs.into_iter().map(Into::into).collect(),
148 header_extensions: value.header_extensions.into_iter().map(Into::into).collect(),
149 }
150 }
151}
152
153impl From<Priority> for sys_webrtc::ffi::Priority {
154 fn from(value: Priority) -> Self {
155 match value {
156 Priority::VeryLow => Self::VeryLow,
157 Priority::Low => Self::Low,
158 Priority::Medium => Self::Medium,
159 Priority::High => Self::High,
160 }
161 }
162}
163
164impl From<RtpHeaderExtensionParameters> for sys_rp::ffi::RtpExtension {
165 fn from(value: RtpHeaderExtensionParameters) -> Self {
166 Self { uri: value.uri, id: value.id, encrypt: value.encrypted }
167 }
168}
169
170impl From<RtpParameters> for sys_rp::ffi::RtpParameters {
171 fn from(value: RtpParameters) -> Self {
172 let degradation_preference =
173 sys_rp::ffi::DegradationPreference { repr: value.degradation_preference };
174 Self {
175 codecs: value.codecs.into_iter().map(Into::into).collect(),
176 header_extensions: value.header_extensions.into_iter().map(Into::into).collect(),
177 encodings: value.encodings.into_iter().map(Into::into).collect(),
178 rtcp: value.rtcp.into(),
179 transaction_id: value.transaction_id,
180 mid: value.mid,
181 has_degradation_preference: value.has_degradation_preference,
182 degradation_preference,
183 }
184 }
185}
186
187impl From<RtpCodecParameters> for sys_rp::ffi::RtpCodecParameters {
188 fn from(value: RtpCodecParameters) -> Self {
189 let kind = sys_webrtc::ffi::MediaType { repr: value.kind };
190 Self {
191 payload_type: value.payload_type as i32,
192 mime_type: value.mime_type,
193 has_clock_rate: value.clock_rate.is_some(),
194 clock_rate: value.clock_rate.unwrap_or_default() as i32,
195 has_num_channels: value.channels.is_some(),
196 num_channels: value.channels.unwrap_or_default() as i32,
197 name: value.name,
198 kind,
199 has_max_ptime: value.has_max_ptime,
200 max_ptime: value.max_ptime,
201 has_ptime: value.has_ptime,
202 ptime: value.ptime,
203 rtcp_feedback: value
204 .rtcp_feedback
205 .into_iter()
206 .map(|f| {
207 let feedback_type = sys_rp::ffi::RtcpFeedbackType { repr: f.feedback_type };
208 let message_type =
209 sys_rp::ffi::RtcpFeedbackMessageType { repr: f.message_type };
210 sys_rp::ffi::RtcpFeedback {
211 feedback_type,
212 has_message_type: f.has_message_type,
213 message_type,
214 }
215 })
216 .collect(),
217 parameters: value
218 .parameters
219 .into_iter()
220 .map(|(key, value)| sys_rp::ffi::StringKeyValue { key, value })
221 .collect(),
222 }
223 }
224}
225
226impl From<RtcpParameters> for sys_rp::ffi::RtcpParameters {
227 fn from(value: RtcpParameters) -> Self {
228 Self {
229 cname: value.cname,
230 reduced_size: value.reduced_size,
231 has_ssrc: value.has_ssrc,
232 ssrc: value.ssrc,
233 mux: value.mux,
234 }
235 }
236}
237
238impl From<RtpEncodingParameters> for sys_rp::ffi::RtpEncodingParameters {
239 fn from(value: RtpEncodingParameters) -> Self {
240 Self {
241 active: value.active,
242 has_max_bitrate_bps: value.max_bitrate.is_some(),
243 max_bitrate_bps: value.max_bitrate.unwrap_or_default() as i32,
244 has_max_framerate: value.max_framerate.is_some(),
245 max_framerate: value.max_framerate.unwrap_or_default(),
246 network_priority: value.priority.into(),
247 rid: value.rid,
248 has_scale_resolution_down_by: value.scale_resolution_down_by.is_some(),
249 scale_resolution_down_by: value.scale_resolution_down_by.unwrap_or_default(),
250 adaptive_ptime: false,
251 bitrate_priority: sys_rp::DEFAULT_BITRATE_PRIORITY,
252 has_min_bitrate_bps: false,
253 min_bitrate_bps: 0,
254 has_num_temporal_layers: false,
255 num_temporal_layers: 0,
256 has_scalability_mode: value.scalability_mode.is_some(),
257 scalability_mode: value.scalability_mode.unwrap_or_default(),
258 has_ssrc: value.has_ssrc,
259 ssrc: value.ssrc,
260 }
261 }
262}
263
264impl From<RtpCodecCapability> for sys_rp::ffi::RtpCodecCapability {
265 fn from(value: RtpCodecCapability) -> Self {
266 let mime_type: Vec<&str> = value.mime_type.split('/').collect();
267 let kind = match mime_type[0] {
268 "audio" => sys_webrtc::ffi::MediaType::Audio,
269 "video" => sys_webrtc::ffi::MediaType::Video,
270 _ => panic!("invalid media type"),
271 };
272 let name = mime_type[1].to_string();
273
274 Self {
275 name,
276 kind,
277 has_clock_rate: value.clock_rate.is_some(),
278 clock_rate: value.clock_rate.unwrap_or_default() as i32,
279 has_num_channels: value.channels.is_some(),
280 num_channels: value.channels.unwrap_or_default() as i32,
281 parameters: {
282 value
283 .sdp_fmtp_line
284 .map(|sdp_fmtp_line| {
285 sdp_fmtp_line
286 .split(';')
287 .map(|v| {
288 let key_value: Vec<&str> = v.split('=').collect();
289 if key_value.len() == 2 {
290 sys_rp::ffi::StringKeyValue {
291 key: key_value[0].to_string(),
292 value: key_value[1].to_string(),
293 }
294 } else {
295 sys_rp::ffi::StringKeyValue {
296 key: "".to_string(),
297 value: key_value[0].to_string(),
298 }
299 }
300 })
301 .collect()
302 })
303 .unwrap_or_default()
304 },
305 // Ignore
306 mime_type: String::default(), // !!
307 has_preferred_payload_type: false,
308 preferred_payload_type: 0,
309 rtcp_feedback: Vec::default(),
310 }
311 }
312}
vendor/libwebrtc/src/native/rtp_receiver.rs added +94 −0
@@ -0,0 +1,94 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::SharedPtr;
16 use tokio::sync::oneshot;
17 use webrtc_sys::rtp_receiver as sys_rr;
18
19 use crate::{
20 imp::{media_stream as imp_ms, media_stream_track::new_media_stream_track},
21 media_stream::MediaStream,
22 media_stream_track::MediaStreamTrack,
23 rtp_parameters::RtpParameters,
24 stats::RtcStats,
25 RtcError, RtcErrorType,
26 };
27
28 #[derive(Clone)]
29 pub struct RtpReceiver {
30 pub(crate) sys_handle: SharedPtr<sys_rr::ffi::RtpReceiver>,
31 }
32
33 impl RtpReceiver {
34 pub fn sources(&self) -> Vec<crate::rtp_receiver::RtpSource> {
35 self.sys_handle
36 .get_sources()
37 .into_iter()
38 .map(|entry| crate::rtp_receiver::RtpSource {
39 source_id: entry.source_id,
40 contributing: entry.is_csrc,
41 audio_level: u8::try_from(entry.audio_level).ok(),
42 timestamp_ms: entry.timestamp_ms,
43 })
44 .collect()
45 }
46
47 pub fn track(&self) -> Option<MediaStreamTrack> {
48 let track_handle = self.sys_handle.track();
49 if track_handle.is_null() {
50 return None;
51 }
52
53 Some(new_media_stream_track(track_handle))
54 }
55
56 pub fn stream_ids(&self) -> Vec<String> {
57 self.sys_handle.stream_ids()
58 }
59
60 pub fn streams(&self) -> Vec<MediaStream> {
61 self.sys_handle
62 .streams()
63 .into_iter()
64 .map(|s| MediaStream { handle: imp_ms::MediaStream { sys_handle: s.ptr } })
65 .collect()
66 }
67
68 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
69 let (tx, rx) = oneshot::channel::<Result<Vec<RtcStats>, RtcError>>();
70 let ctx = Box::new(sys_rr::ReceiverContext(Box::new(tx)));
71
72 self.sys_handle.get_stats(ctx, |ctx, stats| {
73 let tx = ctx.0.downcast::<oneshot::Sender<Result<Vec<RtcStats>, RtcError>>>().unwrap();
74
75 if stats.is_empty() {
76 let _ = tx.send(Ok(vec![]));
77 return;
78 }
79
80 // Unwrap because it should not happens
81 let vec = serde_json::from_str(&stats).unwrap();
82 let _ = tx.send(Ok(vec));
83 });
84
85 rx.await.map_err(|_| RtcError {
86 error_type: RtcErrorType::Internal,
87 message: "get_stats cancelled".to_owned(),
88 })?
89 }
90
91 pub fn parameters(&self) -> RtpParameters {
92 self.sys_handle.get_parameters().into()
93 }
94 }
@@ -0,0 +1,94 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::SharedPtr;
16use tokio::sync::oneshot;
17use webrtc_sys::rtp_receiver as sys_rr;
18
19use crate::{
20 imp::{media_stream as imp_ms, media_stream_track::new_media_stream_track},
21 media_stream::MediaStream,
22 media_stream_track::MediaStreamTrack,
23 rtp_parameters::RtpParameters,
24 stats::RtcStats,
25 RtcError, RtcErrorType,
26};
27
28#[derive(Clone)]
29pub struct RtpReceiver {
30 pub(crate) sys_handle: SharedPtr<sys_rr::ffi::RtpReceiver>,
31}
32
33impl RtpReceiver {
34 pub fn sources(&self) -> Vec<crate::rtp_receiver::RtpSource> {
35 self.sys_handle
36 .get_sources()
37 .into_iter()
38 .map(|entry| crate::rtp_receiver::RtpSource {
39 source_id: entry.source_id,
40 contributing: entry.is_csrc,
41 audio_level: u8::try_from(entry.audio_level).ok(),
42 timestamp_ms: entry.timestamp_ms,
43 })
44 .collect()
45 }
46
47 pub fn track(&self) -> Option<MediaStreamTrack> {
48 let track_handle = self.sys_handle.track();
49 if track_handle.is_null() {
50 return None;
51 }
52
53 Some(new_media_stream_track(track_handle))
54 }
55
56 pub fn stream_ids(&self) -> Vec<String> {
57 self.sys_handle.stream_ids()
58 }
59
60 pub fn streams(&self) -> Vec<MediaStream> {
61 self.sys_handle
62 .streams()
63 .into_iter()
64 .map(|s| MediaStream { handle: imp_ms::MediaStream { sys_handle: s.ptr } })
65 .collect()
66 }
67
68 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
69 let (tx, rx) = oneshot::channel::<Result<Vec<RtcStats>, RtcError>>();
70 let ctx = Box::new(sys_rr::ReceiverContext(Box::new(tx)));
71
72 self.sys_handle.get_stats(ctx, |ctx, stats| {
73 let tx = ctx.0.downcast::<oneshot::Sender<Result<Vec<RtcStats>, RtcError>>>().unwrap();
74
75 if stats.is_empty() {
76 let _ = tx.send(Ok(vec![]));
77 return;
78 }
79
80 // Unwrap because it should not happens
81 let vec = serde_json::from_str(&stats).unwrap();
82 let _ = tx.send(Ok(vec));
83 });
84
85 rx.await.map_err(|_| RtcError {
86 error_type: RtcErrorType::Internal,
87 message: "get_stats cancelled".to_owned(),
88 })?
89 }
90
91 pub fn parameters(&self) -> RtpParameters {
92 self.sys_handle.get_parameters().into()
93 }
94}
vendor/libwebrtc/src/native/rtp_sender.rs added +143 −0
@@ -0,0 +1,143 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::SharedPtr;
16 use tokio::sync::oneshot;
17 use webrtc_sys::{rtc_error as sys_err, rtp_sender as sys_rs, webrtc as sys_webrtc};
18
19 use super::media_stream_track::new_media_stream_track;
20 use crate::{
21 media_stream_track::MediaStreamTrack, rtp_parameters::RtpParameters,
22 rtp_sender::VideoEncoderBackend, stats::RtcStats, RtcError, RtcErrorType,
23 };
24
25 #[derive(Clone)]
26 pub struct RtpSender {
27 pub(crate) sys_handle: SharedPtr<sys_rs::ffi::RtpSender>,
28 }
29
30 impl RtpSender {
31 pub fn track(&self) -> Option<MediaStreamTrack> {
32 let track_handle = self.sys_handle.track();
33 if track_handle.is_null() {
34 return None;
35 }
36
37 Some(new_media_stream_track(track_handle))
38 }
39
40 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
41 let (tx, rx) = oneshot::channel::<Result<Vec<RtcStats>, RtcError>>();
42 let ctx = Box::new(sys_rs::SenderContext(Box::new(tx)));
43
44 self.sys_handle.get_stats(ctx, |ctx, stats| {
45 let tx = ctx.0.downcast::<oneshot::Sender<Result<Vec<RtcStats>, RtcError>>>().unwrap();
46
47 if stats.is_empty() {
48 let _ = tx.send(Ok(vec![]));
49 return;
50 }
51
52 // Unwrap because it should not happens
53 let vec = serde_json::from_str(&stats).unwrap();
54 let _ = tx.send(Ok(vec));
55 });
56
57 rx.await.map_err(|_| RtcError {
58 error_type: RtcErrorType::Internal,
59 message: "get_stats cancelled".to_owned(),
60 })?
61 }
62
63 pub fn set_track(&self, track: Option<MediaStreamTrack>) -> Result<(), RtcError> {
64 if !self.sys_handle.set_track(track.map_or(SharedPtr::null(), |t| t.sys_handle())) {
65 return Err(RtcError {
66 error_type: RtcErrorType::InvalidState,
67 message: "Failed to set track".to_string(),
68 });
69 }
70
71 Ok(())
72 }
73
74 pub fn parameters(&self) -> RtpParameters {
75 self.sys_handle.get_parameters().into()
76 }
77
78 pub fn set_parameters(&self, parameters: RtpParameters) -> Result<(), RtcError> {
79 self.sys_handle
80 .set_parameters(parameters.into())
81 .map_err(|e| unsafe { sys_err::ffi::RtcError::from(e.what()).into() })
82 }
83
84 pub fn set_video_encoder_backend(&self, backend: VideoEncoderBackend) {
85 self.sys_handle.set_video_encoder_backend(backend.into());
86 }
87 }
88
89 impl From<VideoEncoderBackend> for sys_webrtc::ffi::VideoEncoderBackend {
90 fn from(value: VideoEncoderBackend) -> Self {
91 match value {
92 VideoEncoderBackend::Auto => Self::Auto,
93 VideoEncoderBackend::Software => Self::Software,
94 VideoEncoderBackend::Hardware => Self::Hardware,
95 VideoEncoderBackend::Nvenc => Self::Nvenc,
96 VideoEncoderBackend::Vaapi => Self::Vaapi,
97 VideoEncoderBackend::VideoToolbox => Self::VideoToolbox,
98 VideoEncoderBackend::PreEncoded => Self::PreEncoded,
99 }
100 }
101 }
102
103 impl From<sys_webrtc::ffi::VideoEncoderBackend> for VideoEncoderBackend {
104 fn from(value: sys_webrtc::ffi::VideoEncoderBackend) -> Self {
105 match value {
106 sys_webrtc::ffi::VideoEncoderBackend::Auto => Self::Auto,
107 sys_webrtc::ffi::VideoEncoderBackend::Software => Self::Software,
108 sys_webrtc::ffi::VideoEncoderBackend::Hardware => Self::Hardware,
109 sys_webrtc::ffi::VideoEncoderBackend::Nvenc => Self::Nvenc,
110 sys_webrtc::ffi::VideoEncoderBackend::Vaapi => Self::Vaapi,
111 sys_webrtc::ffi::VideoEncoderBackend::VideoToolbox => Self::VideoToolbox,
112 sys_webrtc::ffi::VideoEncoderBackend::PreEncoded => Self::PreEncoded,
113 _ => panic!("unknown VideoEncoderBackend"),
114 }
115 }
116 }
117
118 pub fn video_encoder_backend_list() -> Vec<VideoEncoderBackend> {
119 sys_webrtc::ffi::video_encoder_backend_list().into_iter().map(Into::into).collect()
120 }
121
122 #[cfg(test)]
123 mod tests {
124 use super::{sys_webrtc, VideoEncoderBackend};
125
126 #[test]
127 fn video_encoder_backend_maps_to_native_enum() {
128 let cases = [
129 (VideoEncoderBackend::Auto, sys_webrtc::ffi::VideoEncoderBackend::Auto),
130 (VideoEncoderBackend::Software, sys_webrtc::ffi::VideoEncoderBackend::Software),
131 (VideoEncoderBackend::Hardware, sys_webrtc::ffi::VideoEncoderBackend::Hardware),
132 (VideoEncoderBackend::Nvenc, sys_webrtc::ffi::VideoEncoderBackend::Nvenc),
133 (VideoEncoderBackend::Vaapi, sys_webrtc::ffi::VideoEncoderBackend::Vaapi),
134 (VideoEncoderBackend::VideoToolbox, sys_webrtc::ffi::VideoEncoderBackend::VideoToolbox),
135 (VideoEncoderBackend::PreEncoded, sys_webrtc::ffi::VideoEncoderBackend::PreEncoded),
136 ];
137
138 for (backend, expected) in cases {
139 assert_eq!(sys_webrtc::ffi::VideoEncoderBackend::from(backend), expected);
140 assert_eq!(VideoEncoderBackend::from(expected), backend);
141 }
142 }
143 }
@@ -0,0 +1,143 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::SharedPtr;
16use tokio::sync::oneshot;
17use webrtc_sys::{rtc_error as sys_err, rtp_sender as sys_rs, webrtc as sys_webrtc};
18
19use super::media_stream_track::new_media_stream_track;
20use crate::{
21 media_stream_track::MediaStreamTrack, rtp_parameters::RtpParameters,
22 rtp_sender::VideoEncoderBackend, stats::RtcStats, RtcError, RtcErrorType,
23};
24
25#[derive(Clone)]
26pub struct RtpSender {
27 pub(crate) sys_handle: SharedPtr<sys_rs::ffi::RtpSender>,
28}
29
30impl RtpSender {
31 pub fn track(&self) -> Option<MediaStreamTrack> {
32 let track_handle = self.sys_handle.track();
33 if track_handle.is_null() {
34 return None;
35 }
36
37 Some(new_media_stream_track(track_handle))
38 }
39
40 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
41 let (tx, rx) = oneshot::channel::<Result<Vec<RtcStats>, RtcError>>();
42 let ctx = Box::new(sys_rs::SenderContext(Box::new(tx)));
43
44 self.sys_handle.get_stats(ctx, |ctx, stats| {
45 let tx = ctx.0.downcast::<oneshot::Sender<Result<Vec<RtcStats>, RtcError>>>().unwrap();
46
47 if stats.is_empty() {
48 let _ = tx.send(Ok(vec![]));
49 return;
50 }
51
52 // Unwrap because it should not happens
53 let vec = serde_json::from_str(&stats).unwrap();
54 let _ = tx.send(Ok(vec));
55 });
56
57 rx.await.map_err(|_| RtcError {
58 error_type: RtcErrorType::Internal,
59 message: "get_stats cancelled".to_owned(),
60 })?
61 }
62
63 pub fn set_track(&self, track: Option<MediaStreamTrack>) -> Result<(), RtcError> {
64 if !self.sys_handle.set_track(track.map_or(SharedPtr::null(), |t| t.sys_handle())) {
65 return Err(RtcError {
66 error_type: RtcErrorType::InvalidState,
67 message: "Failed to set track".to_string(),
68 });
69 }
70
71 Ok(())
72 }
73
74 pub fn parameters(&self) -> RtpParameters {
75 self.sys_handle.get_parameters().into()
76 }
77
78 pub fn set_parameters(&self, parameters: RtpParameters) -> Result<(), RtcError> {
79 self.sys_handle
80 .set_parameters(parameters.into())
81 .map_err(|e| unsafe { sys_err::ffi::RtcError::from(e.what()).into() })
82 }
83
84 pub fn set_video_encoder_backend(&self, backend: VideoEncoderBackend) {
85 self.sys_handle.set_video_encoder_backend(backend.into());
86 }
87}
88
89impl From<VideoEncoderBackend> for sys_webrtc::ffi::VideoEncoderBackend {
90 fn from(value: VideoEncoderBackend) -> Self {
91 match value {
92 VideoEncoderBackend::Auto => Self::Auto,
93 VideoEncoderBackend::Software => Self::Software,
94 VideoEncoderBackend::Hardware => Self::Hardware,
95 VideoEncoderBackend::Nvenc => Self::Nvenc,
96 VideoEncoderBackend::Vaapi => Self::Vaapi,
97 VideoEncoderBackend::VideoToolbox => Self::VideoToolbox,
98 VideoEncoderBackend::PreEncoded => Self::PreEncoded,
99 }
100 }
101}
102
103impl From<sys_webrtc::ffi::VideoEncoderBackend> for VideoEncoderBackend {
104 fn from(value: sys_webrtc::ffi::VideoEncoderBackend) -> Self {
105 match value {
106 sys_webrtc::ffi::VideoEncoderBackend::Auto => Self::Auto,
107 sys_webrtc::ffi::VideoEncoderBackend::Software => Self::Software,
108 sys_webrtc::ffi::VideoEncoderBackend::Hardware => Self::Hardware,
109 sys_webrtc::ffi::VideoEncoderBackend::Nvenc => Self::Nvenc,
110 sys_webrtc::ffi::VideoEncoderBackend::Vaapi => Self::Vaapi,
111 sys_webrtc::ffi::VideoEncoderBackend::VideoToolbox => Self::VideoToolbox,
112 sys_webrtc::ffi::VideoEncoderBackend::PreEncoded => Self::PreEncoded,
113 _ => panic!("unknown VideoEncoderBackend"),
114 }
115 }
116}
117
118pub fn video_encoder_backend_list() -> Vec<VideoEncoderBackend> {
119 sys_webrtc::ffi::video_encoder_backend_list().into_iter().map(Into::into).collect()
120}
121
122#[cfg(test)]
123mod tests {
124 use super::{sys_webrtc, VideoEncoderBackend};
125
126 #[test]
127 fn video_encoder_backend_maps_to_native_enum() {
128 let cases = [
129 (VideoEncoderBackend::Auto, sys_webrtc::ffi::VideoEncoderBackend::Auto),
130 (VideoEncoderBackend::Software, sys_webrtc::ffi::VideoEncoderBackend::Software),
131 (VideoEncoderBackend::Hardware, sys_webrtc::ffi::VideoEncoderBackend::Hardware),
132 (VideoEncoderBackend::Nvenc, sys_webrtc::ffi::VideoEncoderBackend::Nvenc),
133 (VideoEncoderBackend::Vaapi, sys_webrtc::ffi::VideoEncoderBackend::Vaapi),
134 (VideoEncoderBackend::VideoToolbox, sys_webrtc::ffi::VideoEncoderBackend::VideoToolbox),
135 (VideoEncoderBackend::PreEncoded, sys_webrtc::ffi::VideoEncoderBackend::PreEncoded),
136 ];
137
138 for (backend, expected) in cases {
139 assert_eq!(sys_webrtc::ffi::VideoEncoderBackend::from(backend), expected);
140 assert_eq!(VideoEncoderBackend::from(expected), backend);
141 }
142 }
143}
vendor/libwebrtc/src/native/rtp_transceiver.rs added +100 −0
@@ -0,0 +1,100 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::SharedPtr;
16 use webrtc_sys::{rtc_error as sys_err, rtp_transceiver as sys_rt, webrtc as sys_webrtc};
17
18 use crate::{
19 imp::{rtp_receiver::RtpReceiver, rtp_sender::RtpSender},
20 rtp_parameters::RtpCodecCapability,
21 rtp_receiver, rtp_sender,
22 rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit},
23 RtcError,
24 };
25
26 impl From<sys_webrtc::ffi::RtpTransceiverDirection> for RtpTransceiverDirection {
27 fn from(value: sys_webrtc::ffi::RtpTransceiverDirection) -> Self {
28 match value {
29 sys_webrtc::ffi::RtpTransceiverDirection::SendRecv => Self::SendRecv,
30 sys_webrtc::ffi::RtpTransceiverDirection::SendOnly => Self::SendOnly,
31 sys_webrtc::ffi::RtpTransceiverDirection::RecvOnly => Self::RecvOnly,
32 sys_webrtc::ffi::RtpTransceiverDirection::Inactive => Self::Inactive,
33 sys_webrtc::ffi::RtpTransceiverDirection::Stopped => Self::Stopped,
34 _ => panic!("unknown RtpTransceiverDirection"),
35 }
36 }
37 }
38
39 impl From<RtpTransceiverDirection> for sys_webrtc::ffi::RtpTransceiverDirection {
40 fn from(value: RtpTransceiverDirection) -> Self {
41 match value {
42 RtpTransceiverDirection::SendRecv => Self::SendRecv,
43 RtpTransceiverDirection::SendOnly => Self::SendOnly,
44 RtpTransceiverDirection::RecvOnly => Self::RecvOnly,
45 RtpTransceiverDirection::Inactive => Self::Inactive,
46 RtpTransceiverDirection::Stopped => Self::Stopped,
47 }
48 }
49 }
50
51 impl From<RtpTransceiverInit> for sys_rt::ffi::RtpTransceiverInit {
52 fn from(value: RtpTransceiverInit) -> Self {
53 Self {
54 direction: value.direction.into(),
55 stream_ids: value.stream_ids,
56 send_encodings: value.send_encodings.into_iter().map(Into::into).collect(),
57 }
58 }
59 }
60
61 #[derive(Clone)]
62 pub struct RtpTransceiver {
63 pub(crate) sys_handle: SharedPtr<sys_rt::ffi::RtpTransceiver>,
64 }
65
66 impl RtpTransceiver {
67 pub fn mid(&self) -> Option<String> {
68 // The C++ shim returns "" when libwebrtc has no mid yet (instead of
69 // calling std::optional::value() which would abort under -fno-exceptions).
70 self.sys_handle.mid().ok().filter(|s| !s.is_empty())
71 }
72
73 pub fn current_direction(&self) -> Option<RtpTransceiverDirection> {
74 self.sys_handle.current_direction().ok().map(Into::into)
75 }
76
77 pub fn direction(&self) -> RtpTransceiverDirection {
78 self.sys_handle.direction().into()
79 }
80
81 pub fn sender(&self) -> rtp_sender::RtpSender {
82 rtp_sender::RtpSender { handle: RtpSender { sys_handle: self.sys_handle.sender() } }
83 }
84
85 pub fn receiver(&self) -> rtp_receiver::RtpReceiver {
86 rtp_receiver::RtpReceiver { handle: RtpReceiver { sys_handle: self.sys_handle.receiver() } }
87 }
88
89 pub fn set_codec_preferences(&self, codecs: Vec<RtpCodecCapability>) -> Result<(), RtcError> {
90 self.sys_handle
91 .set_codec_preferences(codecs.into_iter().map(Into::into).collect())
92 .map_err(|e| unsafe { sys_err::ffi::RtcError::from(e.what()).into() })
93 }
94
95 pub fn stop(&self) -> Result<(), RtcError> {
96 self.sys_handle
97 .stop_standard()
98 .map_err(|e| unsafe { sys_err::ffi::RtcError::from(e.what()).into() })
99 }
100 }
@@ -0,0 +1,100 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::SharedPtr;
16use webrtc_sys::{rtc_error as sys_err, rtp_transceiver as sys_rt, webrtc as sys_webrtc};
17
18use crate::{
19 imp::{rtp_receiver::RtpReceiver, rtp_sender::RtpSender},
20 rtp_parameters::RtpCodecCapability,
21 rtp_receiver, rtp_sender,
22 rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit},
23 RtcError,
24};
25
26impl From<sys_webrtc::ffi::RtpTransceiverDirection> for RtpTransceiverDirection {
27 fn from(value: sys_webrtc::ffi::RtpTransceiverDirection) -> Self {
28 match value {
29 sys_webrtc::ffi::RtpTransceiverDirection::SendRecv => Self::SendRecv,
30 sys_webrtc::ffi::RtpTransceiverDirection::SendOnly => Self::SendOnly,
31 sys_webrtc::ffi::RtpTransceiverDirection::RecvOnly => Self::RecvOnly,
32 sys_webrtc::ffi::RtpTransceiverDirection::Inactive => Self::Inactive,
33 sys_webrtc::ffi::RtpTransceiverDirection::Stopped => Self::Stopped,
34 _ => panic!("unknown RtpTransceiverDirection"),
35 }
36 }
37}
38
39impl From<RtpTransceiverDirection> for sys_webrtc::ffi::RtpTransceiverDirection {
40 fn from(value: RtpTransceiverDirection) -> Self {
41 match value {
42 RtpTransceiverDirection::SendRecv => Self::SendRecv,
43 RtpTransceiverDirection::SendOnly => Self::SendOnly,
44 RtpTransceiverDirection::RecvOnly => Self::RecvOnly,
45 RtpTransceiverDirection::Inactive => Self::Inactive,
46 RtpTransceiverDirection::Stopped => Self::Stopped,
47 }
48 }
49}
50
51impl From<RtpTransceiverInit> for sys_rt::ffi::RtpTransceiverInit {
52 fn from(value: RtpTransceiverInit) -> Self {
53 Self {
54 direction: value.direction.into(),
55 stream_ids: value.stream_ids,
56 send_encodings: value.send_encodings.into_iter().map(Into::into).collect(),
57 }
58 }
59}
60
61#[derive(Clone)]
62pub struct RtpTransceiver {
63 pub(crate) sys_handle: SharedPtr<sys_rt::ffi::RtpTransceiver>,
64}
65
66impl RtpTransceiver {
67 pub fn mid(&self) -> Option<String> {
68 // The C++ shim returns "" when libwebrtc has no mid yet (instead of
69 // calling std::optional::value() which would abort under -fno-exceptions).
70 self.sys_handle.mid().ok().filter(|s| !s.is_empty())
71 }
72
73 pub fn current_direction(&self) -> Option<RtpTransceiverDirection> {
74 self.sys_handle.current_direction().ok().map(Into::into)
75 }
76
77 pub fn direction(&self) -> RtpTransceiverDirection {
78 self.sys_handle.direction().into()
79 }
80
81 pub fn sender(&self) -> rtp_sender::RtpSender {
82 rtp_sender::RtpSender { handle: RtpSender { sys_handle: self.sys_handle.sender() } }
83 }
84
85 pub fn receiver(&self) -> rtp_receiver::RtpReceiver {
86 rtp_receiver::RtpReceiver { handle: RtpReceiver { sys_handle: self.sys_handle.receiver() } }
87 }
88
89 pub fn set_codec_preferences(&self, codecs: Vec<RtpCodecCapability>) -> Result<(), RtcError> {
90 self.sys_handle
91 .set_codec_preferences(codecs.into_iter().map(Into::into).collect())
92 .map_err(|e| unsafe { sys_err::ffi::RtcError::from(e.what()).into() })
93 }
94
95 pub fn stop(&self) -> Result<(), RtcError> {
96 self.sys_handle
97 .stop_standard()
98 .map_err(|e| unsafe { sys_err::ffi::RtcError::from(e.what()).into() })
99 }
100}
vendor/libwebrtc/src/native/session_description.rs added +82 −0
@@ -0,0 +1,82 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use cxx::UniquePtr;
16 use webrtc_sys::jsep as sys_jsep;
17
18 use crate::session_description::{self, SdpParseError, SdpType};
19
20 impl From<sys_jsep::ffi::SdpType> for SdpType {
21 fn from(sdp_type: sys_jsep::ffi::SdpType) -> Self {
22 match sdp_type {
23 sys_jsep::ffi::SdpType::Offer => SdpType::Offer,
24 sys_jsep::ffi::SdpType::PrAnswer => SdpType::PrAnswer,
25 sys_jsep::ffi::SdpType::Answer => SdpType::Answer,
26 sys_jsep::ffi::SdpType::Rollback => SdpType::Rollback,
27 _ => panic!("unknown SdpType"),
28 }
29 }
30 }
31
32 impl From<SdpType> for sys_jsep::ffi::SdpType {
33 fn from(sdp_type: SdpType) -> Self {
34 match sdp_type {
35 SdpType::Offer => sys_jsep::ffi::SdpType::Offer,
36 SdpType::PrAnswer => sys_jsep::ffi::SdpType::PrAnswer,
37 SdpType::Answer => sys_jsep::ffi::SdpType::Answer,
38 SdpType::Rollback => sys_jsep::ffi::SdpType::Rollback,
39 }
40 }
41 }
42
43 impl From<sys_jsep::ffi::SdpParseError> for SdpParseError {
44 fn from(e: sys_jsep::ffi::SdpParseError) -> Self {
45 Self { line: e.line, description: e.description }
46 }
47 }
48
49 pub struct SessionDescription {
50 pub(crate) sys_handle: UniquePtr<sys_jsep::ffi::SessionDescription>,
51 }
52
53 impl SessionDescription {
54 pub fn parse(
55 sdp: &str,
56 sdp_type: SdpType,
57 ) -> Result<session_description::SessionDescription, SdpParseError> {
58 let res = sys_jsep::ffi::create_session_description(sdp_type.into(), sdp.to_owned());
59 match res {
60 Ok(sys_handle) => Ok(session_description::SessionDescription {
61 handle: SessionDescription { sys_handle },
62 }),
63 Err(e) => Err(unsafe { sys_jsep::ffi::SdpParseError::from(e.what()).into() }),
64 }
65 }
66
67 pub fn sdp_type(&self) -> SdpType {
68 self.sys_handle.sdp_type().into()
69 }
70 }
71
72 impl ToString for SessionDescription {
73 fn to_string(&self) -> String {
74 self.sys_handle.stringify()
75 }
76 }
77
78 impl Clone for SessionDescription {
79 fn clone(&self) -> Self {
80 SessionDescription { sys_handle: self.sys_handle.clone() }
81 }
82 }
@@ -0,0 +1,82 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use cxx::UniquePtr;
16use webrtc_sys::jsep as sys_jsep;
17
18use crate::session_description::{self, SdpParseError, SdpType};
19
20impl From<sys_jsep::ffi::SdpType> for SdpType {
21 fn from(sdp_type: sys_jsep::ffi::SdpType) -> Self {
22 match sdp_type {
23 sys_jsep::ffi::SdpType::Offer => SdpType::Offer,
24 sys_jsep::ffi::SdpType::PrAnswer => SdpType::PrAnswer,
25 sys_jsep::ffi::SdpType::Answer => SdpType::Answer,
26 sys_jsep::ffi::SdpType::Rollback => SdpType::Rollback,
27 _ => panic!("unknown SdpType"),
28 }
29 }
30}
31
32impl From<SdpType> for sys_jsep::ffi::SdpType {
33 fn from(sdp_type: SdpType) -> Self {
34 match sdp_type {
35 SdpType::Offer => sys_jsep::ffi::SdpType::Offer,
36 SdpType::PrAnswer => sys_jsep::ffi::SdpType::PrAnswer,
37 SdpType::Answer => sys_jsep::ffi::SdpType::Answer,
38 SdpType::Rollback => sys_jsep::ffi::SdpType::Rollback,
39 }
40 }
41}
42
43impl From<sys_jsep::ffi::SdpParseError> for SdpParseError {
44 fn from(e: sys_jsep::ffi::SdpParseError) -> Self {
45 Self { line: e.line, description: e.description }
46 }
47}
48
49pub struct SessionDescription {
50 pub(crate) sys_handle: UniquePtr<sys_jsep::ffi::SessionDescription>,
51}
52
53impl SessionDescription {
54 pub fn parse(
55 sdp: &str,
56 sdp_type: SdpType,
57 ) -> Result<session_description::SessionDescription, SdpParseError> {
58 let res = sys_jsep::ffi::create_session_description(sdp_type.into(), sdp.to_owned());
59 match res {
60 Ok(sys_handle) => Ok(session_description::SessionDescription {
61 handle: SessionDescription { sys_handle },
62 }),
63 Err(e) => Err(unsafe { sys_jsep::ffi::SdpParseError::from(e.what()).into() }),
64 }
65 }
66
67 pub fn sdp_type(&self) -> SdpType {
68 self.sys_handle.sdp_type().into()
69 }
70}
71
72impl ToString for SessionDescription {
73 fn to_string(&self) -> String {
74 self.sys_handle.stringify()
75 }
76}
77
78impl Clone for SessionDescription {
79 fn clone(&self) -> Self {
80 SessionDescription { sys_handle: self.sys_handle.clone() }
81 }
82}
vendor/libwebrtc/src/native/video_frame.rs added +938 −0
@@ -0,0 +1,938 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::slice;
16
17 use cxx::UniquePtr;
18 use webrtc_sys::{video_frame as vf_sys, video_frame_buffer as vfb_sys};
19
20 use super::yuv_helper;
21 use crate::video_frame::{self as vf, VideoFormatType, VideoRotation};
22
23 /// We don't use vf::VideoFrameBuffer trait for the types inside this module to avoid confusion
24 /// because directly using platform specific types is not valid (e.g user callback)
25 /// All the types inside this module are only used internally. For public types, see the top level
26 /// video_frame.rs
27
28 pub fn new_video_frame_buffer(
29 mut sys_handle: UniquePtr<vfb_sys::ffi::VideoFrameBuffer>,
30 ) -> Box<dyn vf::VideoBuffer + Send + Sync> {
31 unsafe {
32 match sys_handle.buffer_type() {
33 vfb_sys::ffi::VideoFrameBufferType::Native => {
34 Box::new(vf::native::NativeBuffer { handle: NativeBuffer { sys_handle } })
35 }
36 vfb_sys::ffi::VideoFrameBufferType::I420 => Box::new(vf::I420Buffer {
37 handle: I420Buffer { sys_handle: sys_handle.pin_mut().get_i420() },
38 }),
39 vfb_sys::ffi::VideoFrameBufferType::I420A => Box::new(vf::I420ABuffer {
40 handle: I420ABuffer { sys_handle: sys_handle.pin_mut().get_i420a() },
41 }),
42 vfb_sys::ffi::VideoFrameBufferType::I422 => Box::new(vf::I422Buffer {
43 handle: I422Buffer { sys_handle: sys_handle.pin_mut().get_i422() },
44 }),
45 vfb_sys::ffi::VideoFrameBufferType::I444 => Box::new(vf::I444Buffer {
46 handle: I444Buffer { sys_handle: sys_handle.pin_mut().get_i444() },
47 }),
48 vfb_sys::ffi::VideoFrameBufferType::I010 => Box::new(vf::I010Buffer {
49 handle: I010Buffer { sys_handle: sys_handle.pin_mut().get_i010() },
50 }),
51 vfb_sys::ffi::VideoFrameBufferType::NV12 => Box::new(vf::NV12Buffer {
52 handle: NV12Buffer { sys_handle: sys_handle.pin_mut().get_nv12() },
53 }),
54 _ => unreachable!(),
55 }
56 }
57 }
58
59 impl From<vf_sys::ffi::VideoRotation> for VideoRotation {
60 fn from(rotation: vf_sys::ffi::VideoRotation) -> Self {
61 match rotation {
62 vf_sys::ffi::VideoRotation::VideoRotation0 => Self::VideoRotation0,
63 vf_sys::ffi::VideoRotation::VideoRotation90 => Self::VideoRotation90,
64 vf_sys::ffi::VideoRotation::VideoRotation180 => Self::VideoRotation180,
65 vf_sys::ffi::VideoRotation::VideoRotation270 => Self::VideoRotation270,
66 _ => panic!("invalid VideoRotation"),
67 }
68 }
69 }
70
71 impl From<VideoRotation> for vf_sys::ffi::VideoRotation {
72 fn from(rotation: VideoRotation) -> Self {
73 match rotation {
74 VideoRotation::VideoRotation0 => Self::VideoRotation0,
75 VideoRotation::VideoRotation90 => Self::VideoRotation90,
76 VideoRotation::VideoRotation180 => Self::VideoRotation180,
77 VideoRotation::VideoRotation270 => Self::VideoRotation270,
78 }
79 }
80 }
81
82 macro_rules! recursive_cast {
83 ($ptr:expr $(, $fnc:ident)*) => {
84 {
85 let ptr = $ptr;
86 $(
87 let ptr = vfb_sys::ffi::$fnc(ptr);
88 )*
89 ptr
90 }
91 };
92 }
93
94 pub struct NativeBuffer {
95 sys_handle: UniquePtr<vfb_sys::ffi::VideoFrameBuffer>,
96 }
97
98 pub struct I420Buffer {
99 sys_handle: UniquePtr<vfb_sys::ffi::I420Buffer>,
100 }
101
102 pub struct I420ABuffer {
103 sys_handle: UniquePtr<vfb_sys::ffi::I420ABuffer>,
104 }
105
106 pub struct I422Buffer {
107 sys_handle: UniquePtr<vfb_sys::ffi::I422Buffer>,
108 }
109
110 pub struct I444Buffer {
111 sys_handle: UniquePtr<vfb_sys::ffi::I444Buffer>,
112 }
113
114 pub struct I010Buffer {
115 sys_handle: UniquePtr<vfb_sys::ffi::I010Buffer>,
116 }
117
118 pub struct NV12Buffer {
119 sys_handle: UniquePtr<vfb_sys::ffi::NV12Buffer>,
120 }
121
122 macro_rules! impl_to_argb {
123 (I420Buffer [$($variant:ident: $fnc:ident),+], $format:ident, $self:ident, $dst:ident, $dst_stride:ident, $dst_width:ident, $dst_height:ident) => {
124 match $format {
125 $(
126 VideoFormatType::$variant => {
127 let (data_y, data_u, data_v) = $self.data();
128 yuv_helper::$fnc(
129 data_y,
130 $self.stride_y(),
131 data_u,
132 $self.stride_u(),
133 data_v,
134 $self.stride_v(),
135 $dst,
136 $dst_stride,
137 $dst_width,
138 $dst_height,
139 )
140 }
141 )+
142 }
143 };
144 (I420ABuffer) => {
145 todo!();
146 }
147 }
148
149 #[allow(unused_unsafe)]
150 impl NativeBuffer {
151 #[cfg(any(target_os = "macos", target_os = "ios"))]
152 pub unsafe fn from_cv_pixel_buffer(
153 cv_pixel_buffer: *mut std::ffi::c_void,
154 ) -> vf::native::NativeBuffer {
155 vf::native::NativeBuffer {
156 handle: NativeBuffer {
157 sys_handle: vfb_sys::ffi::new_native_buffer_from_platform_image_buffer(
158 cv_pixel_buffer as *mut _,
159 ),
160 },
161 }
162 }
163
164 #[cfg(any(target_os = "macos", target_os = "ios"))]
165 pub fn get_cv_pixel_buffer(&self) -> *mut std::ffi::c_void {
166 unsafe { vfb_sys::ffi::native_buffer_to_platform_image_buffer(&self.sys_handle) as *mut _ }
167 }
168
169 #[cfg(target_os = "linux")]
170 pub fn from_dmabuf(
171 dmabuf_fd: vf::native::DmaBufFileDescriptor,
172 resolution: crate::video_source::VideoResolution,
173 pixel_format: vf::native::DmaBufPixelFormat,
174 ) -> vf::native::NativeBuffer {
175 vf::native::NativeBuffer {
176 handle: NativeBuffer {
177 sys_handle: vfb_sys::ffi::new_native_buffer_from_dmabuf(
178 dmabuf_fd,
179 resolution.width as i32,
180 resolution.height as i32,
181 pixel_format as i32,
182 ),
183 },
184 }
185 }
186
187 #[cfg(target_os = "linux")]
188 pub fn get_dmabuf_fd(&self) -> Option<vf::native::DmaBufFileDescriptor> {
189 let fd = vfb_sys::ffi::native_buffer_to_dmabuf_fd(&self.sys_handle);
190 (fd >= 0).then_some(fd)
191 }
192
193 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
194 &self.sys_handle
195 }
196
197 pub fn width(&self) -> u32 {
198 self.sys_handle.width()
199 }
200
201 pub fn height(&self) -> u32 {
202 self.sys_handle.height()
203 }
204
205 pub fn to_i420(&self) -> I420Buffer {
206 I420Buffer { sys_handle: unsafe { self.sys_handle.to_i420() } }
207 }
208
209 pub fn to_argb(
210 &self,
211 format: VideoFormatType,
212 dst: &mut [u8],
213 dst_stride: u32,
214 dst_width: i32,
215 dst_height: i32,
216 ) {
217 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
218 }
219 }
220
221 impl I420Buffer {
222 pub fn new(
223 width: u32,
224 height: u32,
225 stride_y: u32,
226 stride_u: u32,
227 stride_v: u32,
228 ) -> vf::I420Buffer {
229 vf::I420Buffer {
230 handle: I420Buffer {
231 sys_handle: vfb_sys::ffi::new_i420_buffer(
232 width.try_into().unwrap(),
233 height.try_into().unwrap(),
234 stride_y.try_into().unwrap(),
235 stride_u.try_into().unwrap(),
236 stride_v.try_into().unwrap(),
237 ),
238 },
239 }
240 }
241
242 pub fn new_black(
243 width: u32,
244 height: u32,
245 stride_y: u32,
246 stride_u: u32,
247 stride_v: u32,
248 ) -> vf::I420Buffer {
249 vf::I420Buffer {
250 handle: I420Buffer {
251 sys_handle: vfb_sys::ffi::new_black_i420_buffer(
252 width.try_into().unwrap(),
253 height.try_into().unwrap(),
254 stride_y.try_into().unwrap(),
255 stride_u.try_into().unwrap(),
256 stride_v.try_into().unwrap(),
257 ),
258 },
259 }
260 }
261
262 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
263 unsafe { &*recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv, yuv_to_vfb) }
264 }
265
266 pub fn width(&self) -> u32 {
267 unsafe {
268 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
269 (*ptr).width()
270 }
271 }
272
273 pub fn height(&self) -> u32 {
274 unsafe {
275 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
276 (*ptr).height()
277 }
278 }
279
280 pub fn chroma_width(&self) -> u32 {
281 unsafe {
282 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv);
283 (*ptr).chroma_width()
284 }
285 }
286
287 pub fn chroma_height(&self) -> u32 {
288 unsafe {
289 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv);
290 (*ptr).chroma_height()
291 }
292 }
293
294 pub fn stride_y(&self) -> u32 {
295 unsafe {
296 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv);
297 (*ptr).stride_y()
298 }
299 }
300
301 pub fn stride_u(&self) -> u32 {
302 unsafe {
303 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv);
304 (*ptr).stride_u()
305 }
306 }
307
308 pub fn stride_v(&self) -> u32 {
309 unsafe {
310 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv);
311 (*ptr).stride_v()
312 }
313 }
314
315 pub fn to_i420(&self) -> I420Buffer {
316 I420Buffer {
317 sys_handle: unsafe {
318 // We make a copy of the buffer because internally, when calling ToI420()
319 // if the buffer is of type I420, libwebrtc will reuse the same underlying pointer
320 // for the new created type
321 let copy = vfb_sys::ffi::copy_i420_buffer(&self.sys_handle);
322 let ptr = recursive_cast!(&*copy, i420_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
323 (*ptr).to_i420()
324 },
325 }
326 }
327
328 pub fn to_argb(
329 &self,
330 format: VideoFormatType,
331 dst: &mut [u8],
332 dst_stride: u32,
333 dst_width: i32,
334 dst_height: i32,
335 ) {
336 impl_to_argb!(
337 I420Buffer
338 [
339 ARGB: i420_to_argb,
340 BGRA: i420_to_bgra,
341 ABGR: i420_to_abgr,
342 RGBA: i420_to_rgba
343 ],
344 format, self, dst, dst_stride, dst_width, dst_height
345 )
346 }
347
348 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
349 unsafe {
350 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8);
351 let chroma_height = (self.height() + 1) / 2;
352 (
353 slice::from_raw_parts((*ptr).data_y(), (self.stride_y() * self.height()) as usize),
354 slice::from_raw_parts((*ptr).data_u(), (self.stride_u() * chroma_height) as usize),
355 slice::from_raw_parts((*ptr).data_v(), (self.stride_v() * chroma_height) as usize),
356 )
357 }
358 }
359
360 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::I420Buffer {
361 vf::I420Buffer {
362 handle: I420Buffer {
363 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
364 },
365 }
366 }
367 }
368
369 impl I420ABuffer {
370 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
371 unsafe { &*recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv, yuv_to_vfb) }
372 }
373
374 pub fn width(&self) -> u32 {
375 unsafe {
376 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
377 (*ptr).width()
378 }
379 }
380
381 pub fn height(&self) -> u32 {
382 unsafe {
383 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
384 (*ptr).height()
385 }
386 }
387
388 pub fn chroma_width(&self) -> u32 {
389 unsafe {
390 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv);
391 (*ptr).chroma_width()
392 }
393 }
394
395 pub fn chroma_height(&self) -> u32 {
396 unsafe {
397 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv);
398 (*ptr).chroma_height()
399 }
400 }
401
402 pub fn stride_y(&self) -> u32 {
403 unsafe {
404 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv);
405 (*ptr).stride_y()
406 }
407 }
408
409 pub fn stride_u(&self) -> u32 {
410 unsafe {
411 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv);
412 (*ptr).stride_u()
413 }
414 }
415
416 pub fn stride_v(&self) -> u32 {
417 unsafe {
418 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv);
419 (*ptr).stride_v()
420 }
421 }
422
423 pub fn stride_a(&self) -> u32 {
424 self.sys_handle.stride_a()
425 }
426
427 pub fn to_i420(&self) -> I420Buffer {
428 I420Buffer {
429 sys_handle: unsafe {
430 let ptr =
431 recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
432 (*ptr).to_i420()
433 },
434 }
435 }
436
437 pub fn to_argb(
438 &self,
439 format: VideoFormatType,
440 dst: &mut [u8],
441 dst_stride: u32,
442 dst_width: i32,
443 dst_height: i32,
444 ) {
445 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
446 }
447
448 pub fn data(&self) -> (&[u8], &[u8], &[u8], Option<&[u8]>) {
449 unsafe {
450 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8);
451 let chroma_height = (self.height() + 1) / 2;
452 let data_a = self.sys_handle.data_a();
453 let has_data_a = !data_a.is_null();
454 (
455 slice::from_raw_parts((*ptr).data_y(), (self.stride_y() * self.height()) as usize),
456 slice::from_raw_parts((*ptr).data_u(), (self.stride_u() * chroma_height) as usize),
457 slice::from_raw_parts((*ptr).data_v(), (self.stride_v() * chroma_height) as usize),
458 has_data_a.then_some(slice::from_raw_parts(
459 data_a,
460 (self.stride_a() * self.height()) as usize,
461 )),
462 )
463 }
464 }
465
466 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::I420ABuffer {
467 vf::I420ABuffer {
468 handle: I420ABuffer {
469 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
470 },
471 }
472 }
473 }
474
475 impl I422Buffer {
476 pub fn new(
477 width: u32,
478 height: u32,
479 stride_y: u32,
480 stride_u: u32,
481 stride_v: u32,
482 ) -> vf::I422Buffer {
483 vf::I422Buffer {
484 handle: I422Buffer {
485 sys_handle: vfb_sys::ffi::new_i422_buffer(
486 width.try_into().unwrap(),
487 height.try_into().unwrap(),
488 stride_y.try_into().unwrap(),
489 stride_u.try_into().unwrap(),
490 stride_v.try_into().unwrap(),
491 ),
492 },
493 }
494 }
495
496 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
497 unsafe { &*recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv, yuv_to_vfb) }
498 }
499
500 pub fn width(&self) -> u32 {
501 unsafe {
502 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
503 (*ptr).width()
504 }
505 }
506
507 pub fn height(&self) -> u32 {
508 unsafe {
509 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
510 (*ptr).height()
511 }
512 }
513
514 pub fn chroma_width(&self) -> u32 {
515 unsafe {
516 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv);
517 (*ptr).chroma_width()
518 }
519 }
520
521 pub fn chroma_height(&self) -> u32 {
522 unsafe {
523 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv);
524 (*ptr).chroma_height()
525 }
526 }
527
528 pub fn stride_y(&self) -> u32 {
529 unsafe {
530 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv);
531 (*ptr).stride_y()
532 }
533 }
534
535 pub fn stride_u(&self) -> u32 {
536 unsafe {
537 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv);
538 (*ptr).stride_u()
539 }
540 }
541
542 pub fn stride_v(&self) -> u32 {
543 unsafe {
544 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv);
545 (*ptr).stride_v()
546 }
547 }
548
549 pub fn to_i420(&self) -> I420Buffer {
550 I420Buffer {
551 sys_handle: unsafe {
552 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
553 (*ptr).to_i420()
554 },
555 }
556 }
557
558 pub fn to_argb(
559 &self,
560 format: VideoFormatType,
561 dst: &mut [u8],
562 dst_stride: u32,
563 dst_width: i32,
564 dst_height: i32,
565 ) {
566 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
567 }
568
569 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
570 unsafe {
571 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8);
572 (
573 slice::from_raw_parts((*ptr).data_y(), (self.stride_y() * self.height()) as usize),
574 slice::from_raw_parts((*ptr).data_u(), (self.stride_u() * self.height()) as usize),
575 slice::from_raw_parts((*ptr).data_v(), (self.stride_v() * self.height()) as usize),
576 )
577 }
578 }
579
580 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::I422Buffer {
581 vf::I422Buffer {
582 handle: I422Buffer {
583 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
584 },
585 }
586 }
587 }
588 impl I444Buffer {
589 pub fn new(
590 width: u32,
591 height: u32,
592 stride_y: u32,
593 stride_u: u32,
594 stride_v: u32,
595 ) -> vf::I444Buffer {
596 vf::I444Buffer {
597 handle: I444Buffer {
598 sys_handle: vfb_sys::ffi::new_i444_buffer(
599 width.try_into().unwrap(),
600 height.try_into().unwrap(),
601 stride_y.try_into().unwrap(),
602 stride_u.try_into().unwrap(),
603 stride_v.try_into().unwrap(),
604 ),
605 },
606 }
607 }
608
609 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
610 unsafe { &*recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv, yuv_to_vfb) }
611 }
612
613 pub fn width(&self) -> u32 {
614 unsafe {
615 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
616 (*ptr).width()
617 }
618 }
619
620 pub fn height(&self) -> u32 {
621 unsafe {
622 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
623 (*ptr).height()
624 }
625 }
626
627 pub fn chroma_width(&self) -> u32 {
628 unsafe {
629 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv);
630 (*ptr).chroma_width()
631 }
632 }
633
634 pub fn chroma_height(&self) -> u32 {
635 unsafe {
636 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv);
637 (*ptr).chroma_height()
638 }
639 }
640
641 pub fn stride_y(&self) -> u32 {
642 unsafe {
643 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv);
644 (*ptr).stride_y()
645 }
646 }
647
648 pub fn stride_u(&self) -> u32 {
649 unsafe {
650 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv);
651 (*ptr).stride_u()
652 }
653 }
654
655 pub fn stride_v(&self) -> u32 {
656 unsafe {
657 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv);
658 (*ptr).stride_v()
659 }
660 }
661
662 pub fn to_i420(&self) -> I420Buffer {
663 I420Buffer {
664 sys_handle: unsafe {
665 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
666 (*ptr).to_i420()
667 },
668 }
669 }
670
671 pub fn to_argb(
672 &self,
673 format: VideoFormatType,
674 dst: &mut [u8],
675 dst_stride: u32,
676 dst_width: i32,
677 dst_height: i32,
678 ) {
679 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
680 }
681
682 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
683 unsafe {
684 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8);
685 (
686 slice::from_raw_parts((*ptr).data_y(), (self.stride_y() * self.height()) as usize),
687 slice::from_raw_parts((*ptr).data_u(), (self.stride_u() * self.height()) as usize),
688 slice::from_raw_parts((*ptr).data_v(), (self.stride_v() * self.height()) as usize),
689 )
690 }
691 }
692
693 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::I444Buffer {
694 vf::I444Buffer {
695 handle: I444Buffer {
696 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
697 },
698 }
699 }
700 }
701
702 impl I010Buffer {
703 pub fn new(
704 width: u32,
705 height: u32,
706 stride_y: u32,
707 stride_u: u32,
708 stride_v: u32,
709 ) -> vf::I010Buffer {
710 vf::I010Buffer {
711 handle: I010Buffer {
712 sys_handle: vfb_sys::ffi::new_i010_buffer(
713 width.try_into().unwrap(),
714 height.try_into().unwrap(),
715 stride_y.try_into().unwrap(),
716 stride_u.try_into().unwrap(),
717 stride_v.try_into().unwrap(),
718 ),
719 },
720 }
721 }
722
723 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
724 unsafe { &*recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv, yuv_to_vfb) }
725 }
726
727 pub fn width(&self) -> u32 {
728 unsafe {
729 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv, yuv_to_vfb);
730 (*ptr).width()
731 }
732 }
733
734 pub fn height(&self) -> u32 {
735 unsafe {
736 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv, yuv_to_vfb);
737 (*ptr).height()
738 }
739 }
740
741 pub fn chroma_width(&self) -> u32 {
742 unsafe {
743 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv);
744 (*ptr).chroma_width()
745 }
746 }
747
748 pub fn chroma_height(&self) -> u32 {
749 unsafe {
750 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv);
751 (*ptr).chroma_height()
752 }
753 }
754
755 pub fn stride_y(&self) -> u32 {
756 unsafe {
757 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv);
758 (*ptr).stride_y()
759 }
760 }
761
762 pub fn stride_u(&self) -> u32 {
763 unsafe {
764 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv);
765 (*ptr).stride_u()
766 }
767 }
768
769 pub fn stride_v(&self) -> u32 {
770 unsafe {
771 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv);
772 (*ptr).stride_v()
773 }
774 }
775
776 pub fn to_i420(&self) -> I420Buffer {
777 I420Buffer {
778 sys_handle: unsafe {
779 let ptr =
780 recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv, yuv_to_vfb);
781 (*ptr).to_i420()
782 },
783 }
784 }
785
786 pub fn to_argb(
787 &self,
788 format: VideoFormatType,
789 dst: &mut [u8],
790 dst_stride: u32,
791 dst_width: i32,
792 dst_height: i32,
793 ) {
794 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
795 }
796
797 pub fn data(&self) -> (&[u16], &[u16], &[u16]) {
798 unsafe {
799 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b);
800 let chroma_height = (self.height() + 1) / 2;
801 (
802 slice::from_raw_parts(
803 (*ptr).data_y(),
804 (self.stride_y() * self.height()) as usize / 2,
805 ),
806 slice::from_raw_parts(
807 (*ptr).data_u(),
808 (self.stride_u() * chroma_height) as usize / 2,
809 ),
810 slice::from_raw_parts(
811 (*ptr).data_v(),
812 (self.stride_v() * chroma_height) as usize / 2,
813 ),
814 )
815 }
816 }
817
818 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::I010Buffer {
819 vf::I010Buffer {
820 handle: I010Buffer {
821 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
822 },
823 }
824 }
825 }
826
827 impl NV12Buffer {
828 pub fn new(width: u32, height: u32, stride_y: u32, stride_uv: u32) -> vf::NV12Buffer {
829 vf::NV12Buffer {
830 handle: NV12Buffer {
831 sys_handle: vfb_sys::ffi::new_nv12_buffer(
832 width.try_into().unwrap(),
833 height.try_into().unwrap(),
834 stride_y.try_into().unwrap(),
835 stride_uv.try_into().unwrap(),
836 ),
837 },
838 }
839 }
840
841 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
842 unsafe {
843 &*recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv, biyuv_to_vfb)
844 }
845 }
846
847 pub fn width(&self) -> u32 {
848 unsafe {
849 let ptr =
850 recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv, biyuv_to_vfb);
851 (*ptr).width()
852 }
853 }
854
855 pub fn height(&self) -> u32 {
856 unsafe {
857 let ptr =
858 recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv, biyuv_to_vfb);
859 (*ptr).height()
860 }
861 }
862
863 pub fn chroma_width(&self) -> u32 {
864 unsafe {
865 let ptr = recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv);
866 (*ptr).chroma_width()
867 }
868 }
869
870 pub fn chroma_height(&self) -> u32 {
871 unsafe {
872 let ptr = recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv);
873 (*ptr).chroma_height()
874 }
875 }
876
877 pub fn stride_y(&self) -> u32 {
878 unsafe {
879 let ptr = recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv);
880 (*ptr).stride_y()
881 }
882 }
883
884 pub fn stride_uv(&self) -> u32 {
885 unsafe {
886 let ptr = recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv);
887 (*ptr).stride_uv()
888 }
889 }
890
891 pub fn to_i420(&self) -> I420Buffer {
892 I420Buffer {
893 sys_handle: unsafe {
894 let ptr = recursive_cast!(
895 &*self.sys_handle,
896 nv12_to_biyuv8,
897 biyuv8_to_biyuv,
898 biyuv_to_vfb
899 );
900 (*ptr).to_i420()
901 },
902 }
903 }
904
905 pub fn to_argb(
906 &self,
907 format: VideoFormatType,
908 dst: &mut [u8],
909 dst_stride: u32,
910 dst_width: i32,
911 dst_height: i32,
912 ) {
913 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
914 }
915
916 pub fn data(&self) -> (&[u8], &[u8]) {
917 unsafe {
918 let ptr = recursive_cast!(&*self.sys_handle, nv12_to_biyuv8);
919 let chroma_height = (self.height() + 1) / 2;
920
921 (
922 slice::from_raw_parts((*ptr).data_y(), (self.stride_y() * self.height()) as usize),
923 slice::from_raw_parts(
924 (*ptr).data_uv(),
925 (self.stride_uv() * chroma_height) as usize,
926 ),
927 )
928 }
929 }
930
931 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::NV12Buffer {
932 vf::NV12Buffer {
933 handle: NV12Buffer {
934 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
935 },
936 }
937 }
938 }
@@ -0,0 +1,938 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::slice;
16
17use cxx::UniquePtr;
18use webrtc_sys::{video_frame as vf_sys, video_frame_buffer as vfb_sys};
19
20use super::yuv_helper;
21use crate::video_frame::{self as vf, VideoFormatType, VideoRotation};
22
23/// We don't use vf::VideoFrameBuffer trait for the types inside this module to avoid confusion
24/// because directly using platform specific types is not valid (e.g user callback)
25/// All the types inside this module are only used internally. For public types, see the top level
26/// video_frame.rs
27
28pub fn new_video_frame_buffer(
29 mut sys_handle: UniquePtr<vfb_sys::ffi::VideoFrameBuffer>,
30) -> Box<dyn vf::VideoBuffer + Send + Sync> {
31 unsafe {
32 match sys_handle.buffer_type() {
33 vfb_sys::ffi::VideoFrameBufferType::Native => {
34 Box::new(vf::native::NativeBuffer { handle: NativeBuffer { sys_handle } })
35 }
36 vfb_sys::ffi::VideoFrameBufferType::I420 => Box::new(vf::I420Buffer {
37 handle: I420Buffer { sys_handle: sys_handle.pin_mut().get_i420() },
38 }),
39 vfb_sys::ffi::VideoFrameBufferType::I420A => Box::new(vf::I420ABuffer {
40 handle: I420ABuffer { sys_handle: sys_handle.pin_mut().get_i420a() },
41 }),
42 vfb_sys::ffi::VideoFrameBufferType::I422 => Box::new(vf::I422Buffer {
43 handle: I422Buffer { sys_handle: sys_handle.pin_mut().get_i422() },
44 }),
45 vfb_sys::ffi::VideoFrameBufferType::I444 => Box::new(vf::I444Buffer {
46 handle: I444Buffer { sys_handle: sys_handle.pin_mut().get_i444() },
47 }),
48 vfb_sys::ffi::VideoFrameBufferType::I010 => Box::new(vf::I010Buffer {
49 handle: I010Buffer { sys_handle: sys_handle.pin_mut().get_i010() },
50 }),
51 vfb_sys::ffi::VideoFrameBufferType::NV12 => Box::new(vf::NV12Buffer {
52 handle: NV12Buffer { sys_handle: sys_handle.pin_mut().get_nv12() },
53 }),
54 _ => unreachable!(),
55 }
56 }
57}
58
59impl From<vf_sys::ffi::VideoRotation> for VideoRotation {
60 fn from(rotation: vf_sys::ffi::VideoRotation) -> Self {
61 match rotation {
62 vf_sys::ffi::VideoRotation::VideoRotation0 => Self::VideoRotation0,
63 vf_sys::ffi::VideoRotation::VideoRotation90 => Self::VideoRotation90,
64 vf_sys::ffi::VideoRotation::VideoRotation180 => Self::VideoRotation180,
65 vf_sys::ffi::VideoRotation::VideoRotation270 => Self::VideoRotation270,
66 _ => panic!("invalid VideoRotation"),
67 }
68 }
69}
70
71impl From<VideoRotation> for vf_sys::ffi::VideoRotation {
72 fn from(rotation: VideoRotation) -> Self {
73 match rotation {
74 VideoRotation::VideoRotation0 => Self::VideoRotation0,
75 VideoRotation::VideoRotation90 => Self::VideoRotation90,
76 VideoRotation::VideoRotation180 => Self::VideoRotation180,
77 VideoRotation::VideoRotation270 => Self::VideoRotation270,
78 }
79 }
80}
81
82macro_rules! recursive_cast {
83 ($ptr:expr $(, $fnc:ident)*) => {
84 {
85 let ptr = $ptr;
86 $(
87 let ptr = vfb_sys::ffi::$fnc(ptr);
88 )*
89 ptr
90 }
91 };
92}
93
94pub struct NativeBuffer {
95 sys_handle: UniquePtr<vfb_sys::ffi::VideoFrameBuffer>,
96}
97
98pub struct I420Buffer {
99 sys_handle: UniquePtr<vfb_sys::ffi::I420Buffer>,
100}
101
102pub struct I420ABuffer {
103 sys_handle: UniquePtr<vfb_sys::ffi::I420ABuffer>,
104}
105
106pub struct I422Buffer {
107 sys_handle: UniquePtr<vfb_sys::ffi::I422Buffer>,
108}
109
110pub struct I444Buffer {
111 sys_handle: UniquePtr<vfb_sys::ffi::I444Buffer>,
112}
113
114pub struct I010Buffer {
115 sys_handle: UniquePtr<vfb_sys::ffi::I010Buffer>,
116}
117
118pub struct NV12Buffer {
119 sys_handle: UniquePtr<vfb_sys::ffi::NV12Buffer>,
120}
121
122macro_rules! impl_to_argb {
123 (I420Buffer [$($variant:ident: $fnc:ident),+], $format:ident, $self:ident, $dst:ident, $dst_stride:ident, $dst_width:ident, $dst_height:ident) => {
124 match $format {
125 $(
126 VideoFormatType::$variant => {
127 let (data_y, data_u, data_v) = $self.data();
128 yuv_helper::$fnc(
129 data_y,
130 $self.stride_y(),
131 data_u,
132 $self.stride_u(),
133 data_v,
134 $self.stride_v(),
135 $dst,
136 $dst_stride,
137 $dst_width,
138 $dst_height,
139 )
140 }
141 )+
142 }
143 };
144 (I420ABuffer) => {
145 todo!();
146 }
147}
148
149#[allow(unused_unsafe)]
150impl NativeBuffer {
151 #[cfg(any(target_os = "macos", target_os = "ios"))]
152 pub unsafe fn from_cv_pixel_buffer(
153 cv_pixel_buffer: *mut std::ffi::c_void,
154 ) -> vf::native::NativeBuffer {
155 vf::native::NativeBuffer {
156 handle: NativeBuffer {
157 sys_handle: vfb_sys::ffi::new_native_buffer_from_platform_image_buffer(
158 cv_pixel_buffer as *mut _,
159 ),
160 },
161 }
162 }
163
164 #[cfg(any(target_os = "macos", target_os = "ios"))]
165 pub fn get_cv_pixel_buffer(&self) -> *mut std::ffi::c_void {
166 unsafe { vfb_sys::ffi::native_buffer_to_platform_image_buffer(&self.sys_handle) as *mut _ }
167 }
168
169 #[cfg(target_os = "linux")]
170 pub fn from_dmabuf(
171 dmabuf_fd: vf::native::DmaBufFileDescriptor,
172 resolution: crate::video_source::VideoResolution,
173 pixel_format: vf::native::DmaBufPixelFormat,
174 ) -> vf::native::NativeBuffer {
175 vf::native::NativeBuffer {
176 handle: NativeBuffer {
177 sys_handle: vfb_sys::ffi::new_native_buffer_from_dmabuf(
178 dmabuf_fd,
179 resolution.width as i32,
180 resolution.height as i32,
181 pixel_format as i32,
182 ),
183 },
184 }
185 }
186
187 #[cfg(target_os = "linux")]
188 pub fn get_dmabuf_fd(&self) -> Option<vf::native::DmaBufFileDescriptor> {
189 let fd = vfb_sys::ffi::native_buffer_to_dmabuf_fd(&self.sys_handle);
190 (fd >= 0).then_some(fd)
191 }
192
193 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
194 &self.sys_handle
195 }
196
197 pub fn width(&self) -> u32 {
198 self.sys_handle.width()
199 }
200
201 pub fn height(&self) -> u32 {
202 self.sys_handle.height()
203 }
204
205 pub fn to_i420(&self) -> I420Buffer {
206 I420Buffer { sys_handle: unsafe { self.sys_handle.to_i420() } }
207 }
208
209 pub fn to_argb(
210 &self,
211 format: VideoFormatType,
212 dst: &mut [u8],
213 dst_stride: u32,
214 dst_width: i32,
215 dst_height: i32,
216 ) {
217 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
218 }
219}
220
221impl I420Buffer {
222 pub fn new(
223 width: u32,
224 height: u32,
225 stride_y: u32,
226 stride_u: u32,
227 stride_v: u32,
228 ) -> vf::I420Buffer {
229 vf::I420Buffer {
230 handle: I420Buffer {
231 sys_handle: vfb_sys::ffi::new_i420_buffer(
232 width.try_into().unwrap(),
233 height.try_into().unwrap(),
234 stride_y.try_into().unwrap(),
235 stride_u.try_into().unwrap(),
236 stride_v.try_into().unwrap(),
237 ),
238 },
239 }
240 }
241
242 pub fn new_black(
243 width: u32,
244 height: u32,
245 stride_y: u32,
246 stride_u: u32,
247 stride_v: u32,
248 ) -> vf::I420Buffer {
249 vf::I420Buffer {
250 handle: I420Buffer {
251 sys_handle: vfb_sys::ffi::new_black_i420_buffer(
252 width.try_into().unwrap(),
253 height.try_into().unwrap(),
254 stride_y.try_into().unwrap(),
255 stride_u.try_into().unwrap(),
256 stride_v.try_into().unwrap(),
257 ),
258 },
259 }
260 }
261
262 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
263 unsafe { &*recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv, yuv_to_vfb) }
264 }
265
266 pub fn width(&self) -> u32 {
267 unsafe {
268 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
269 (*ptr).width()
270 }
271 }
272
273 pub fn height(&self) -> u32 {
274 unsafe {
275 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
276 (*ptr).height()
277 }
278 }
279
280 pub fn chroma_width(&self) -> u32 {
281 unsafe {
282 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv);
283 (*ptr).chroma_width()
284 }
285 }
286
287 pub fn chroma_height(&self) -> u32 {
288 unsafe {
289 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv);
290 (*ptr).chroma_height()
291 }
292 }
293
294 pub fn stride_y(&self) -> u32 {
295 unsafe {
296 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv);
297 (*ptr).stride_y()
298 }
299 }
300
301 pub fn stride_u(&self) -> u32 {
302 unsafe {
303 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv);
304 (*ptr).stride_u()
305 }
306 }
307
308 pub fn stride_v(&self) -> u32 {
309 unsafe {
310 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8, yuv8_to_yuv);
311 (*ptr).stride_v()
312 }
313 }
314
315 pub fn to_i420(&self) -> I420Buffer {
316 I420Buffer {
317 sys_handle: unsafe {
318 // We make a copy of the buffer because internally, when calling ToI420()
319 // if the buffer is of type I420, libwebrtc will reuse the same underlying pointer
320 // for the new created type
321 let copy = vfb_sys::ffi::copy_i420_buffer(&self.sys_handle);
322 let ptr = recursive_cast!(&*copy, i420_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
323 (*ptr).to_i420()
324 },
325 }
326 }
327
328 pub fn to_argb(
329 &self,
330 format: VideoFormatType,
331 dst: &mut [u8],
332 dst_stride: u32,
333 dst_width: i32,
334 dst_height: i32,
335 ) {
336 impl_to_argb!(
337 I420Buffer
338 [
339 ARGB: i420_to_argb,
340 BGRA: i420_to_bgra,
341 ABGR: i420_to_abgr,
342 RGBA: i420_to_rgba
343 ],
344 format, self, dst, dst_stride, dst_width, dst_height
345 )
346 }
347
348 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
349 unsafe {
350 let ptr = recursive_cast!(&*self.sys_handle, i420_to_yuv8);
351 let chroma_height = (self.height() + 1) / 2;
352 (
353 slice::from_raw_parts((*ptr).data_y(), (self.stride_y() * self.height()) as usize),
354 slice::from_raw_parts((*ptr).data_u(), (self.stride_u() * chroma_height) as usize),
355 slice::from_raw_parts((*ptr).data_v(), (self.stride_v() * chroma_height) as usize),
356 )
357 }
358 }
359
360 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::I420Buffer {
361 vf::I420Buffer {
362 handle: I420Buffer {
363 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
364 },
365 }
366 }
367}
368
369impl I420ABuffer {
370 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
371 unsafe { &*recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv, yuv_to_vfb) }
372 }
373
374 pub fn width(&self) -> u32 {
375 unsafe {
376 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
377 (*ptr).width()
378 }
379 }
380
381 pub fn height(&self) -> u32 {
382 unsafe {
383 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
384 (*ptr).height()
385 }
386 }
387
388 pub fn chroma_width(&self) -> u32 {
389 unsafe {
390 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv);
391 (*ptr).chroma_width()
392 }
393 }
394
395 pub fn chroma_height(&self) -> u32 {
396 unsafe {
397 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv);
398 (*ptr).chroma_height()
399 }
400 }
401
402 pub fn stride_y(&self) -> u32 {
403 unsafe {
404 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv);
405 (*ptr).stride_y()
406 }
407 }
408
409 pub fn stride_u(&self) -> u32 {
410 unsafe {
411 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv);
412 (*ptr).stride_u()
413 }
414 }
415
416 pub fn stride_v(&self) -> u32 {
417 unsafe {
418 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv);
419 (*ptr).stride_v()
420 }
421 }
422
423 pub fn stride_a(&self) -> u32 {
424 self.sys_handle.stride_a()
425 }
426
427 pub fn to_i420(&self) -> I420Buffer {
428 I420Buffer {
429 sys_handle: unsafe {
430 let ptr =
431 recursive_cast!(&*self.sys_handle, i420a_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
432 (*ptr).to_i420()
433 },
434 }
435 }
436
437 pub fn to_argb(
438 &self,
439 format: VideoFormatType,
440 dst: &mut [u8],
441 dst_stride: u32,
442 dst_width: i32,
443 dst_height: i32,
444 ) {
445 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
446 }
447
448 pub fn data(&self) -> (&[u8], &[u8], &[u8], Option<&[u8]>) {
449 unsafe {
450 let ptr = recursive_cast!(&*self.sys_handle, i420a_to_yuv8);
451 let chroma_height = (self.height() + 1) / 2;
452 let data_a = self.sys_handle.data_a();
453 let has_data_a = !data_a.is_null();
454 (
455 slice::from_raw_parts((*ptr).data_y(), (self.stride_y() * self.height()) as usize),
456 slice::from_raw_parts((*ptr).data_u(), (self.stride_u() * chroma_height) as usize),
457 slice::from_raw_parts((*ptr).data_v(), (self.stride_v() * chroma_height) as usize),
458 has_data_a.then_some(slice::from_raw_parts(
459 data_a,
460 (self.stride_a() * self.height()) as usize,
461 )),
462 )
463 }
464 }
465
466 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::I420ABuffer {
467 vf::I420ABuffer {
468 handle: I420ABuffer {
469 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
470 },
471 }
472 }
473}
474
475impl I422Buffer {
476 pub fn new(
477 width: u32,
478 height: u32,
479 stride_y: u32,
480 stride_u: u32,
481 stride_v: u32,
482 ) -> vf::I422Buffer {
483 vf::I422Buffer {
484 handle: I422Buffer {
485 sys_handle: vfb_sys::ffi::new_i422_buffer(
486 width.try_into().unwrap(),
487 height.try_into().unwrap(),
488 stride_y.try_into().unwrap(),
489 stride_u.try_into().unwrap(),
490 stride_v.try_into().unwrap(),
491 ),
492 },
493 }
494 }
495
496 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
497 unsafe { &*recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv, yuv_to_vfb) }
498 }
499
500 pub fn width(&self) -> u32 {
501 unsafe {
502 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
503 (*ptr).width()
504 }
505 }
506
507 pub fn height(&self) -> u32 {
508 unsafe {
509 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
510 (*ptr).height()
511 }
512 }
513
514 pub fn chroma_width(&self) -> u32 {
515 unsafe {
516 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv);
517 (*ptr).chroma_width()
518 }
519 }
520
521 pub fn chroma_height(&self) -> u32 {
522 unsafe {
523 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv);
524 (*ptr).chroma_height()
525 }
526 }
527
528 pub fn stride_y(&self) -> u32 {
529 unsafe {
530 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv);
531 (*ptr).stride_y()
532 }
533 }
534
535 pub fn stride_u(&self) -> u32 {
536 unsafe {
537 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv);
538 (*ptr).stride_u()
539 }
540 }
541
542 pub fn stride_v(&self) -> u32 {
543 unsafe {
544 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv);
545 (*ptr).stride_v()
546 }
547 }
548
549 pub fn to_i420(&self) -> I420Buffer {
550 I420Buffer {
551 sys_handle: unsafe {
552 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
553 (*ptr).to_i420()
554 },
555 }
556 }
557
558 pub fn to_argb(
559 &self,
560 format: VideoFormatType,
561 dst: &mut [u8],
562 dst_stride: u32,
563 dst_width: i32,
564 dst_height: i32,
565 ) {
566 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
567 }
568
569 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
570 unsafe {
571 let ptr = recursive_cast!(&*self.sys_handle, i422_to_yuv8);
572 (
573 slice::from_raw_parts((*ptr).data_y(), (self.stride_y() * self.height()) as usize),
574 slice::from_raw_parts((*ptr).data_u(), (self.stride_u() * self.height()) as usize),
575 slice::from_raw_parts((*ptr).data_v(), (self.stride_v() * self.height()) as usize),
576 )
577 }
578 }
579
580 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::I422Buffer {
581 vf::I422Buffer {
582 handle: I422Buffer {
583 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
584 },
585 }
586 }
587}
588impl I444Buffer {
589 pub fn new(
590 width: u32,
591 height: u32,
592 stride_y: u32,
593 stride_u: u32,
594 stride_v: u32,
595 ) -> vf::I444Buffer {
596 vf::I444Buffer {
597 handle: I444Buffer {
598 sys_handle: vfb_sys::ffi::new_i444_buffer(
599 width.try_into().unwrap(),
600 height.try_into().unwrap(),
601 stride_y.try_into().unwrap(),
602 stride_u.try_into().unwrap(),
603 stride_v.try_into().unwrap(),
604 ),
605 },
606 }
607 }
608
609 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
610 unsafe { &*recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv, yuv_to_vfb) }
611 }
612
613 pub fn width(&self) -> u32 {
614 unsafe {
615 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
616 (*ptr).width()
617 }
618 }
619
620 pub fn height(&self) -> u32 {
621 unsafe {
622 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
623 (*ptr).height()
624 }
625 }
626
627 pub fn chroma_width(&self) -> u32 {
628 unsafe {
629 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv);
630 (*ptr).chroma_width()
631 }
632 }
633
634 pub fn chroma_height(&self) -> u32 {
635 unsafe {
636 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv);
637 (*ptr).chroma_height()
638 }
639 }
640
641 pub fn stride_y(&self) -> u32 {
642 unsafe {
643 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv);
644 (*ptr).stride_y()
645 }
646 }
647
648 pub fn stride_u(&self) -> u32 {
649 unsafe {
650 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv);
651 (*ptr).stride_u()
652 }
653 }
654
655 pub fn stride_v(&self) -> u32 {
656 unsafe {
657 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv);
658 (*ptr).stride_v()
659 }
660 }
661
662 pub fn to_i420(&self) -> I420Buffer {
663 I420Buffer {
664 sys_handle: unsafe {
665 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8, yuv8_to_yuv, yuv_to_vfb);
666 (*ptr).to_i420()
667 },
668 }
669 }
670
671 pub fn to_argb(
672 &self,
673 format: VideoFormatType,
674 dst: &mut [u8],
675 dst_stride: u32,
676 dst_width: i32,
677 dst_height: i32,
678 ) {
679 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
680 }
681
682 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
683 unsafe {
684 let ptr = recursive_cast!(&*self.sys_handle, i444_to_yuv8);
685 (
686 slice::from_raw_parts((*ptr).data_y(), (self.stride_y() * self.height()) as usize),
687 slice::from_raw_parts((*ptr).data_u(), (self.stride_u() * self.height()) as usize),
688 slice::from_raw_parts((*ptr).data_v(), (self.stride_v() * self.height()) as usize),
689 )
690 }
691 }
692
693 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::I444Buffer {
694 vf::I444Buffer {
695 handle: I444Buffer {
696 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
697 },
698 }
699 }
700}
701
702impl I010Buffer {
703 pub fn new(
704 width: u32,
705 height: u32,
706 stride_y: u32,
707 stride_u: u32,
708 stride_v: u32,
709 ) -> vf::I010Buffer {
710 vf::I010Buffer {
711 handle: I010Buffer {
712 sys_handle: vfb_sys::ffi::new_i010_buffer(
713 width.try_into().unwrap(),
714 height.try_into().unwrap(),
715 stride_y.try_into().unwrap(),
716 stride_u.try_into().unwrap(),
717 stride_v.try_into().unwrap(),
718 ),
719 },
720 }
721 }
722
723 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
724 unsafe { &*recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv, yuv_to_vfb) }
725 }
726
727 pub fn width(&self) -> u32 {
728 unsafe {
729 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv, yuv_to_vfb);
730 (*ptr).width()
731 }
732 }
733
734 pub fn height(&self) -> u32 {
735 unsafe {
736 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv, yuv_to_vfb);
737 (*ptr).height()
738 }
739 }
740
741 pub fn chroma_width(&self) -> u32 {
742 unsafe {
743 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv);
744 (*ptr).chroma_width()
745 }
746 }
747
748 pub fn chroma_height(&self) -> u32 {
749 unsafe {
750 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv);
751 (*ptr).chroma_height()
752 }
753 }
754
755 pub fn stride_y(&self) -> u32 {
756 unsafe {
757 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv);
758 (*ptr).stride_y()
759 }
760 }
761
762 pub fn stride_u(&self) -> u32 {
763 unsafe {
764 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv);
765 (*ptr).stride_u()
766 }
767 }
768
769 pub fn stride_v(&self) -> u32 {
770 unsafe {
771 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv);
772 (*ptr).stride_v()
773 }
774 }
775
776 pub fn to_i420(&self) -> I420Buffer {
777 I420Buffer {
778 sys_handle: unsafe {
779 let ptr =
780 recursive_cast!(&*self.sys_handle, i010_to_yuv16b, yuv16b_to_yuv, yuv_to_vfb);
781 (*ptr).to_i420()
782 },
783 }
784 }
785
786 pub fn to_argb(
787 &self,
788 format: VideoFormatType,
789 dst: &mut [u8],
790 dst_stride: u32,
791 dst_width: i32,
792 dst_height: i32,
793 ) {
794 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
795 }
796
797 pub fn data(&self) -> (&[u16], &[u16], &[u16]) {
798 unsafe {
799 let ptr = recursive_cast!(&*self.sys_handle, i010_to_yuv16b);
800 let chroma_height = (self.height() + 1) / 2;
801 (
802 slice::from_raw_parts(
803 (*ptr).data_y(),
804 (self.stride_y() * self.height()) as usize / 2,
805 ),
806 slice::from_raw_parts(
807 (*ptr).data_u(),
808 (self.stride_u() * chroma_height) as usize / 2,
809 ),
810 slice::from_raw_parts(
811 (*ptr).data_v(),
812 (self.stride_v() * chroma_height) as usize / 2,
813 ),
814 )
815 }
816 }
817
818 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::I010Buffer {
819 vf::I010Buffer {
820 handle: I010Buffer {
821 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
822 },
823 }
824 }
825}
826
827impl NV12Buffer {
828 pub fn new(width: u32, height: u32, stride_y: u32, stride_uv: u32) -> vf::NV12Buffer {
829 vf::NV12Buffer {
830 handle: NV12Buffer {
831 sys_handle: vfb_sys::ffi::new_nv12_buffer(
832 width.try_into().unwrap(),
833 height.try_into().unwrap(),
834 stride_y.try_into().unwrap(),
835 stride_uv.try_into().unwrap(),
836 ),
837 },
838 }
839 }
840
841 pub fn sys_handle(&self) -> &vfb_sys::ffi::VideoFrameBuffer {
842 unsafe {
843 &*recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv, biyuv_to_vfb)
844 }
845 }
846
847 pub fn width(&self) -> u32 {
848 unsafe {
849 let ptr =
850 recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv, biyuv_to_vfb);
851 (*ptr).width()
852 }
853 }
854
855 pub fn height(&self) -> u32 {
856 unsafe {
857 let ptr =
858 recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv, biyuv_to_vfb);
859 (*ptr).height()
860 }
861 }
862
863 pub fn chroma_width(&self) -> u32 {
864 unsafe {
865 let ptr = recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv);
866 (*ptr).chroma_width()
867 }
868 }
869
870 pub fn chroma_height(&self) -> u32 {
871 unsafe {
872 let ptr = recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv);
873 (*ptr).chroma_height()
874 }
875 }
876
877 pub fn stride_y(&self) -> u32 {
878 unsafe {
879 let ptr = recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv);
880 (*ptr).stride_y()
881 }
882 }
883
884 pub fn stride_uv(&self) -> u32 {
885 unsafe {
886 let ptr = recursive_cast!(&*self.sys_handle, nv12_to_biyuv8, biyuv8_to_biyuv);
887 (*ptr).stride_uv()
888 }
889 }
890
891 pub fn to_i420(&self) -> I420Buffer {
892 I420Buffer {
893 sys_handle: unsafe {
894 let ptr = recursive_cast!(
895 &*self.sys_handle,
896 nv12_to_biyuv8,
897 biyuv8_to_biyuv,
898 biyuv_to_vfb
899 );
900 (*ptr).to_i420()
901 },
902 }
903 }
904
905 pub fn to_argb(
906 &self,
907 format: VideoFormatType,
908 dst: &mut [u8],
909 dst_stride: u32,
910 dst_width: i32,
911 dst_height: i32,
912 ) {
913 self.to_i420().to_argb(format, dst, dst_stride, dst_width, dst_height)
914 }
915
916 pub fn data(&self) -> (&[u8], &[u8]) {
917 unsafe {
918 let ptr = recursive_cast!(&*self.sys_handle, nv12_to_biyuv8);
919 let chroma_height = (self.height() + 1) / 2;
920
921 (
922 slice::from_raw_parts((*ptr).data_y(), (self.stride_y() * self.height()) as usize),
923 slice::from_raw_parts(
924 (*ptr).data_uv(),
925 (self.stride_uv() * chroma_height) as usize,
926 ),
927 )
928 }
929 }
930
931 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> vf::NV12Buffer {
932 vf::NV12Buffer {
933 handle: NV12Buffer {
934 sys_handle: self.sys_handle.pin_mut().scale(scaled_width, scaled_height),
935 },
936 }
937 }
938}
vendor/libwebrtc/src/native/video_source.rs added +315 −0
@@ -0,0 +1,315 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::{
16 sync::{
17 atomic::{AtomicUsize, Ordering},
18 Arc, Weak,
19 },
20 time::{Duration, SystemTime, UNIX_EPOCH},
21 };
22
23 use cxx::SharedPtr;
24 use tokio::time::interval;
25 use webrtc_sys::{video_frame as vf_sys, video_frame::ffi::VideoRotation, video_track as vt_sys};
26
27 use crate::{
28 native::packet_trailer::PacketTrailerHandler,
29 video_frame::{EncodedVideoFrame, I420Buffer, VideoBuffer, VideoFrame},
30 video_source::{EncodedRateControl, VideoResolution},
31 };
32
33 impl From<vt_sys::ffi::VideoResolution> for VideoResolution {
34 fn from(res: vt_sys::ffi::VideoResolution) -> Self {
35 Self { width: res.width, height: res.height }
36 }
37 }
38
39 impl From<VideoResolution> for vt_sys::ffi::VideoResolution {
40 fn from(res: VideoResolution) -> Self {
41 Self { width: res.width, height: res.height }
42 }
43 }
44
45 #[derive(Clone)]
46 pub struct NativeVideoSource {
47 sys_handle: SharedPtr<vt_sys::ffi::VideoTrackSource>,
48 captured_frames: Arc<AtomicUsize>,
49 }
50
51 fn keepalive_should_continue(captured_frames: &Weak<AtomicUsize>) -> bool {
52 captured_frames
53 .upgrade()
54 .is_some_and(|captured_frames| captured_frames.load(Ordering::Relaxed) == 0)
55 }
56
57 async fn raw_keepalive_task(
58 resolution: VideoResolution,
59 captured_frames: Weak<AtomicUsize>,
60 sys_handle: SharedPtr<vt_sys::ffi::VideoTrackSource>,
61 ) {
62 if !keepalive_should_continue(&captured_frames) {
63 return;
64 }
65
66 // This buffer reaches the encoder without any plane ever being
67 // written, so it must be black-initialized: `I420Buffer::new`
68 // leaves the pixel data uninitialized and would leak recycled
69 // heap memory to subscribers in the first keyframes.
70 let i420 = I420Buffer::new_black(resolution.width, resolution.height);
71 let mut interval = interval(Duration::from_millis(100)); // 10 fps
72
73 loop {
74 interval.tick().await;
75
76 if !keepalive_should_continue(&captured_frames) {
77 break;
78 }
79
80 let mut builder = vf_sys::ffi::new_video_frame_builder();
81 builder.pin_mut().set_rotation(VideoRotation::VideoRotation0);
82 builder.pin_mut().set_video_frame_buffer(i420.as_ref().sys_handle());
83
84 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
85 builder.pin_mut().set_timestamp_us(now.as_micros() as i64);
86
87 sys_handle.on_captured_frame(
88 &builder.pin_mut().build(),
89 &vt_sys::ffi::FrameMetadata {
90 has_packet_trailer: false,
91 user_timestamp: 0,
92 frame_id: 0,
93 user_data: Vec::new(),
94 },
95 );
96 }
97 }
98
99 impl NativeVideoSource {
100 pub fn new(resolution: VideoResolution, is_screencast: bool) -> NativeVideoSource {
101 Self::new_inner(resolution, is_screencast, true)
102 }
103
104 /// Creates a source for pre-encoded access units.
105 ///
106 /// Unlike [`NativeVideoSource::new`], no raw black-frame keepalive is
107 /// injected before the first capture: raw frames would start a real
108 /// encoder on a sender meant for the pass-through encoder and corrupt
109 /// the encoded stream.
110 pub fn new_encoded(resolution: VideoResolution) -> NativeVideoSource {
111 Self::new_inner(resolution, false, false)
112 }
113
114 fn new_inner(
115 resolution: VideoResolution,
116 is_screencast: bool,
117 raw_keepalive: bool,
118 ) -> NativeVideoSource {
119 let source = Self {
120 sys_handle: vt_sys::ffi::new_video_track_source(
121 &vt_sys::ffi::VideoResolution::from(resolution.clone()),
122 is_screencast,
123 ),
124 captured_frames: Arc::new(AtomicUsize::new(0)),
125 };
126
127 if raw_keepalive {
128 let captured_frames = Arc::downgrade(&source.captured_frames);
129 let sys_handle = source.sys_handle.clone();
130 let _keepalive_task =
131 tokio::spawn(raw_keepalive_task(resolution, captured_frames, sys_handle));
132 }
133
134 source
135 }
136
137 pub fn sys_handle(&self) -> SharedPtr<vt_sys::ffi::VideoTrackSource> {
138 self.sys_handle.clone()
139 }
140
141 /// Returns `false` if the frame was dropped by the adapter (e.g. due to
142 /// resolution/frame-rate adaptation) instead of being forwarded.
143 pub fn capture_frame<T: AsRef<dyn VideoBuffer>>(&self, frame: &VideoFrame<T>) -> bool {
144 let mut builder = vf_sys::ffi::new_video_frame_builder();
145 builder.pin_mut().set_rotation(frame.rotation.into());
146 builder.pin_mut().set_video_frame_buffer(frame.buffer.as_ref().sys_handle());
147
148 let capture_ts = if frame.timestamp_us == 0 {
149 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
150 now.as_micros() as i64
151 } else {
152 frame.timestamp_us
153 };
154 builder.pin_mut().set_timestamp_us(capture_ts);
155
156 let (has_trailer, user_ts, fid, user_data) = match &frame.frame_metadata {
157 Some(meta) => (
158 true,
159 meta.user_timestamp.unwrap_or(0),
160 meta.frame_id.unwrap_or(0),
161 meta.user_data.clone().unwrap_or_default(),
162 ),
163 None => (false, 0, 0, Vec::new()),
164 };
165
166 self.captured_frames.fetch_add(1, Ordering::Relaxed);
167
168 self.sys_handle.on_captured_frame(
169 &builder.pin_mut().build(),
170 &vt_sys::ffi::FrameMetadata {
171 has_packet_trailer: has_trailer,
172 user_timestamp: user_ts,
173 frame_id: fid,
174 user_data,
175 },
176 )
177 }
178
179 pub fn capture_encoded_frame(&self, frame: &EncodedVideoFrame<'_>) -> bool {
180 let (has_trailer, user_ts, fid, user_data) = match &frame.frame_metadata {
181 Some(meta) => (
182 true,
183 meta.user_timestamp.unwrap_or(0),
184 meta.frame_id.unwrap_or(0),
185 meta.user_data.clone().unwrap_or_default(),
186 ),
187 None => (false, 0, 0, Vec::new()),
188 };
189
190 let capture_ts = if frame.timestamp_us == 0 {
191 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
192 now.as_micros() as i64
193 } else {
194 frame.timestamp_us
195 };
196
197 self.captured_frames.fetch_add(1, Ordering::Relaxed);
198 self.sys_handle.capture_encoded_frame(
199 frame.resolution.width as i32,
200 frame.resolution.height as i32,
201 &vt_sys::ffi::EncodedVideoFrameData {
202 codec: frame.codec.into(),
203 frame_type: frame.frame_type.into(),
204 timestamp_us: capture_ts,
205 },
206 frame.payload,
207 &vt_sys::ffi::FrameMetadata {
208 has_packet_trailer: has_trailer,
209 user_timestamp: user_ts,
210 frame_id: fid,
211 user_data,
212 },
213 )
214 }
215
216 /// Returns and clears the pending keyframe request raised by the
217 /// pass-through encoder (PLI/FIR or reconfiguration). Poll from the
218 /// capture loop and forward the request to the upstream encoder.
219 pub fn take_keyframe_request(&self) -> bool {
220 self.sys_handle.take_keyframe_request()
221 }
222
223 /// Returns and clears the pending rate-control target raised by the
224 /// pass-through encoder.
225 pub fn take_rate_control_request(&self) -> Option<EncodedRateControl> {
226 let request = self.sys_handle.take_rate_control_request();
227 request.has_request.then_some(EncodedRateControl {
228 target_bitrate_bps: request.target_bitrate_bps,
229 framerate_fps: request.framerate_fps,
230 })
231 }
232
233 /// Set the packet trailer handler used by this source.
234 ///
235 /// When set, any frame captured with a `user_timestamp` value will
236 /// automatically have its timestamp stored in the handler so the
237 /// `PacketTrailerTransformer` can embed it into the encoded frame.
238 /// The handler is set on the C++ VideoTrackSource so it has access to
239 /// the TimestampAligner-adjusted capture timestamp for correct keying.
240 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
241 self.sys_handle.set_packet_trailer_handler(handler.sys_handle());
242 }
243
244 pub fn video_resolution(&self) -> VideoResolution {
245 self.sys_handle.video_resolution().into()
246 }
247 }
248
249 #[cfg(test)]
250 mod tests {
251 use std::sync::{
252 atomic::{AtomicUsize, Ordering},
253 Arc,
254 };
255 use std::time::Duration;
256
257 use super::{keepalive_should_continue, raw_keepalive_task, NativeVideoSource};
258 use crate::video_source::VideoResolution;
259
260 #[test]
261 fn keepalive_continues_before_first_capture() {
262 let captured_frames = Arc::new(AtomicUsize::new(0));
263
264 assert!(keepalive_should_continue(&Arc::downgrade(&captured_frames)));
265 }
266
267 #[test]
268 fn keepalive_stops_after_first_capture() {
269 let captured_frames = Arc::new(AtomicUsize::new(0));
270 let weak_captured_frames = Arc::downgrade(&captured_frames);
271 captured_frames.fetch_add(1, Ordering::Relaxed);
272
273 assert!(!keepalive_should_continue(&weak_captured_frames));
274 }
275
276 #[test]
277 fn keepalive_stops_when_source_is_dropped() {
278 let weak_captured_frames = {
279 let captured_frames = Arc::new(AtomicUsize::new(0));
280 Arc::downgrade(&captured_frames)
281 };
282
283 assert!(!keepalive_should_continue(&weak_captured_frames));
284 }
285
286 #[tokio::test]
287 async fn keepalive_task_does_not_keep_capture_state_alive() {
288 let source = NativeVideoSource::new(VideoResolution { width: 16, height: 16 }, false);
289 let captured_frames = Arc::downgrade(&source.captured_frames);
290
291 tokio::task::yield_now().await;
292 drop(source);
293
294 assert!(captured_frames.upgrade().is_none());
295 }
296
297 #[tokio::test]
298 async fn keepalive_task_releases_native_source_after_drop() {
299 let resolution = VideoResolution { width: 16, height: 16 };
300 let source = NativeVideoSource::new_inner(resolution.clone(), false, false);
301 let keepalive_task = tokio::spawn(raw_keepalive_task(
302 resolution,
303 Arc::downgrade(&source.captured_frames),
304 source.sys_handle.clone(),
305 ));
306
307 tokio::task::yield_now().await;
308 drop(source);
309
310 tokio::time::timeout(Duration::from_secs(1), keepalive_task)
311 .await
312 .expect("keepalive task retained its resources after the source was dropped")
313 .expect("keepalive task panicked");
314 }
315 }
@@ -0,0 +1,315 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{
16 sync::{
17 atomic::{AtomicUsize, Ordering},
18 Arc, Weak,
19 },
20 time::{Duration, SystemTime, UNIX_EPOCH},
21};
22
23use cxx::SharedPtr;
24use tokio::time::interval;
25use webrtc_sys::{video_frame as vf_sys, video_frame::ffi::VideoRotation, video_track as vt_sys};
26
27use crate::{
28 native::packet_trailer::PacketTrailerHandler,
29 video_frame::{EncodedVideoFrame, I420Buffer, VideoBuffer, VideoFrame},
30 video_source::{EncodedRateControl, VideoResolution},
31};
32
33impl From<vt_sys::ffi::VideoResolution> for VideoResolution {
34 fn from(res: vt_sys::ffi::VideoResolution) -> Self {
35 Self { width: res.width, height: res.height }
36 }
37}
38
39impl From<VideoResolution> for vt_sys::ffi::VideoResolution {
40 fn from(res: VideoResolution) -> Self {
41 Self { width: res.width, height: res.height }
42 }
43}
44
45#[derive(Clone)]
46pub struct NativeVideoSource {
47 sys_handle: SharedPtr<vt_sys::ffi::VideoTrackSource>,
48 captured_frames: Arc<AtomicUsize>,
49}
50
51fn keepalive_should_continue(captured_frames: &Weak<AtomicUsize>) -> bool {
52 captured_frames
53 .upgrade()
54 .is_some_and(|captured_frames| captured_frames.load(Ordering::Relaxed) == 0)
55}
56
57async fn raw_keepalive_task(
58 resolution: VideoResolution,
59 captured_frames: Weak<AtomicUsize>,
60 sys_handle: SharedPtr<vt_sys::ffi::VideoTrackSource>,
61) {
62 if !keepalive_should_continue(&captured_frames) {
63 return;
64 }
65
66 // This buffer reaches the encoder without any plane ever being
67 // written, so it must be black-initialized: `I420Buffer::new`
68 // leaves the pixel data uninitialized and would leak recycled
69 // heap memory to subscribers in the first keyframes.
70 let i420 = I420Buffer::new_black(resolution.width, resolution.height);
71 let mut interval = interval(Duration::from_millis(100)); // 10 fps
72
73 loop {
74 interval.tick().await;
75
76 if !keepalive_should_continue(&captured_frames) {
77 break;
78 }
79
80 let mut builder = vf_sys::ffi::new_video_frame_builder();
81 builder.pin_mut().set_rotation(VideoRotation::VideoRotation0);
82 builder.pin_mut().set_video_frame_buffer(i420.as_ref().sys_handle());
83
84 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
85 builder.pin_mut().set_timestamp_us(now.as_micros() as i64);
86
87 sys_handle.on_captured_frame(
88 &builder.pin_mut().build(),
89 &vt_sys::ffi::FrameMetadata {
90 has_packet_trailer: false,
91 user_timestamp: 0,
92 frame_id: 0,
93 user_data: Vec::new(),
94 },
95 );
96 }
97}
98
99impl NativeVideoSource {
100 pub fn new(resolution: VideoResolution, is_screencast: bool) -> NativeVideoSource {
101 Self::new_inner(resolution, is_screencast, true)
102 }
103
104 /// Creates a source for pre-encoded access units.
105 ///
106 /// Unlike [`NativeVideoSource::new`], no raw black-frame keepalive is
107 /// injected before the first capture: raw frames would start a real
108 /// encoder on a sender meant for the pass-through encoder and corrupt
109 /// the encoded stream.
110 pub fn new_encoded(resolution: VideoResolution) -> NativeVideoSource {
111 Self::new_inner(resolution, false, false)
112 }
113
114 fn new_inner(
115 resolution: VideoResolution,
116 is_screencast: bool,
117 raw_keepalive: bool,
118 ) -> NativeVideoSource {
119 let source = Self {
120 sys_handle: vt_sys::ffi::new_video_track_source(
121 &vt_sys::ffi::VideoResolution::from(resolution.clone()),
122 is_screencast,
123 ),
124 captured_frames: Arc::new(AtomicUsize::new(0)),
125 };
126
127 if raw_keepalive {
128 let captured_frames = Arc::downgrade(&source.captured_frames);
129 let sys_handle = source.sys_handle.clone();
130 let _keepalive_task =
131 tokio::spawn(raw_keepalive_task(resolution, captured_frames, sys_handle));
132 }
133
134 source
135 }
136
137 pub fn sys_handle(&self) -> SharedPtr<vt_sys::ffi::VideoTrackSource> {
138 self.sys_handle.clone()
139 }
140
141 /// Returns `false` if the frame was dropped by the adapter (e.g. due to
142 /// resolution/frame-rate adaptation) instead of being forwarded.
143 pub fn capture_frame<T: AsRef<dyn VideoBuffer>>(&self, frame: &VideoFrame<T>) -> bool {
144 let mut builder = vf_sys::ffi::new_video_frame_builder();
145 builder.pin_mut().set_rotation(frame.rotation.into());
146 builder.pin_mut().set_video_frame_buffer(frame.buffer.as_ref().sys_handle());
147
148 let capture_ts = if frame.timestamp_us == 0 {
149 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
150 now.as_micros() as i64
151 } else {
152 frame.timestamp_us
153 };
154 builder.pin_mut().set_timestamp_us(capture_ts);
155
156 let (has_trailer, user_ts, fid, user_data) = match &frame.frame_metadata {
157 Some(meta) => (
158 true,
159 meta.user_timestamp.unwrap_or(0),
160 meta.frame_id.unwrap_or(0),
161 meta.user_data.clone().unwrap_or_default(),
162 ),
163 None => (false, 0, 0, Vec::new()),
164 };
165
166 self.captured_frames.fetch_add(1, Ordering::Relaxed);
167
168 self.sys_handle.on_captured_frame(
169 &builder.pin_mut().build(),
170 &vt_sys::ffi::FrameMetadata {
171 has_packet_trailer: has_trailer,
172 user_timestamp: user_ts,
173 frame_id: fid,
174 user_data,
175 },
176 )
177 }
178
179 pub fn capture_encoded_frame(&self, frame: &EncodedVideoFrame<'_>) -> bool {
180 let (has_trailer, user_ts, fid, user_data) = match &frame.frame_metadata {
181 Some(meta) => (
182 true,
183 meta.user_timestamp.unwrap_or(0),
184 meta.frame_id.unwrap_or(0),
185 meta.user_data.clone().unwrap_or_default(),
186 ),
187 None => (false, 0, 0, Vec::new()),
188 };
189
190 let capture_ts = if frame.timestamp_us == 0 {
191 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
192 now.as_micros() as i64
193 } else {
194 frame.timestamp_us
195 };
196
197 self.captured_frames.fetch_add(1, Ordering::Relaxed);
198 self.sys_handle.capture_encoded_frame(
199 frame.resolution.width as i32,
200 frame.resolution.height as i32,
201 &vt_sys::ffi::EncodedVideoFrameData {
202 codec: frame.codec.into(),
203 frame_type: frame.frame_type.into(),
204 timestamp_us: capture_ts,
205 },
206 frame.payload,
207 &vt_sys::ffi::FrameMetadata {
208 has_packet_trailer: has_trailer,
209 user_timestamp: user_ts,
210 frame_id: fid,
211 user_data,
212 },
213 )
214 }
215
216 /// Returns and clears the pending keyframe request raised by the
217 /// pass-through encoder (PLI/FIR or reconfiguration). Poll from the
218 /// capture loop and forward the request to the upstream encoder.
219 pub fn take_keyframe_request(&self) -> bool {
220 self.sys_handle.take_keyframe_request()
221 }
222
223 /// Returns and clears the pending rate-control target raised by the
224 /// pass-through encoder.
225 pub fn take_rate_control_request(&self) -> Option<EncodedRateControl> {
226 let request = self.sys_handle.take_rate_control_request();
227 request.has_request.then_some(EncodedRateControl {
228 target_bitrate_bps: request.target_bitrate_bps,
229 framerate_fps: request.framerate_fps,
230 })
231 }
232
233 /// Set the packet trailer handler used by this source.
234 ///
235 /// When set, any frame captured with a `user_timestamp` value will
236 /// automatically have its timestamp stored in the handler so the
237 /// `PacketTrailerTransformer` can embed it into the encoded frame.
238 /// The handler is set on the C++ VideoTrackSource so it has access to
239 /// the TimestampAligner-adjusted capture timestamp for correct keying.
240 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
241 self.sys_handle.set_packet_trailer_handler(handler.sys_handle());
242 }
243
244 pub fn video_resolution(&self) -> VideoResolution {
245 self.sys_handle.video_resolution().into()
246 }
247}
248
249#[cfg(test)]
250mod tests {
251 use std::sync::{
252 atomic::{AtomicUsize, Ordering},
253 Arc,
254 };
255 use std::time::Duration;
256
257 use super::{keepalive_should_continue, raw_keepalive_task, NativeVideoSource};
258 use crate::video_source::VideoResolution;
259
260 #[test]
261 fn keepalive_continues_before_first_capture() {
262 let captured_frames = Arc::new(AtomicUsize::new(0));
263
264 assert!(keepalive_should_continue(&Arc::downgrade(&captured_frames)));
265 }
266
267 #[test]
268 fn keepalive_stops_after_first_capture() {
269 let captured_frames = Arc::new(AtomicUsize::new(0));
270 let weak_captured_frames = Arc::downgrade(&captured_frames);
271 captured_frames.fetch_add(1, Ordering::Relaxed);
272
273 assert!(!keepalive_should_continue(&weak_captured_frames));
274 }
275
276 #[test]
277 fn keepalive_stops_when_source_is_dropped() {
278 let weak_captured_frames = {
279 let captured_frames = Arc::new(AtomicUsize::new(0));
280 Arc::downgrade(&captured_frames)
281 };
282
283 assert!(!keepalive_should_continue(&weak_captured_frames));
284 }
285
286 #[tokio::test]
287 async fn keepalive_task_does_not_keep_capture_state_alive() {
288 let source = NativeVideoSource::new(VideoResolution { width: 16, height: 16 }, false);
289 let captured_frames = Arc::downgrade(&source.captured_frames);
290
291 tokio::task::yield_now().await;
292 drop(source);
293
294 assert!(captured_frames.upgrade().is_none());
295 }
296
297 #[tokio::test]
298 async fn keepalive_task_releases_native_source_after_drop() {
299 let resolution = VideoResolution { width: 16, height: 16 };
300 let source = NativeVideoSource::new_inner(resolution.clone(), false, false);
301 let keepalive_task = tokio::spawn(raw_keepalive_task(
302 resolution,
303 Arc::downgrade(&source.captured_frames),
304 source.sys_handle.clone(),
305 ));
306
307 tokio::task::yield_now().await;
308 drop(source);
309
310 tokio::time::timeout(Duration::from_secs(1), keepalive_task)
311 .await
312 .expect("keepalive task retained its resources after the source was dropped")
313 .expect("keepalive task panicked");
314 }
315}
vendor/libwebrtc/src/native/video_stream.rs added +389 −0
@@ -0,0 +1,389 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::{
16 collections::VecDeque,
17 pin::Pin,
18 sync::{
19 atomic::{AtomicBool, AtomicU64, Ordering},
20 Arc,
21 },
22 task::{Context, Poll, Waker},
23 };
24
25 use cxx::{SharedPtr, UniquePtr};
26 use parking_lot::Mutex;
27 use rtrb::{Consumer, Producer, PushError, RingBuffer};
28 use tokio_stream::Stream;
29 use webrtc_sys::video_track as sys_vt;
30
31 use super::{packet_trailer::SubscribeTimingStage, video_frame::new_video_frame_buffer};
32 use crate::{
33 native::packet_trailer::PacketTrailerHandler,
34 video_frame::{BoxVideoFrame, FrameMetadata, VideoFrame},
35 video_track::RtcVideoTrack,
36 };
37
38 pub struct NativeVideoStream {
39 native_sink: SharedPtr<sys_vt::ffi::NativeVideoSink>,
40 observer: Arc<VideoTrackObserver>,
41 video_track: RtcVideoTrack,
42 frame_queue: Arc<VideoFrameQueue>,
43 }
44
45 impl NativeVideoStream {
46 pub fn new(video_track: RtcVideoTrack, queue_size_frames: Option<usize>) -> Self {
47 let frame_queue = Arc::new(VideoFrameQueue::new(queue_size_frames));
48 // Auto-wire the packet trailer handler from the track if one is set.
49 let observer = Arc::new(VideoTrackObserver {
50 frame_queue: frame_queue.clone(),
51 packet_trailer_handler: Mutex::new(video_track.handle.packet_trailer_handler()),
52 });
53 let native_sink = sys_vt::ffi::new_native_video_sink(Box::new(
54 sys_vt::VideoSinkWrapper::new(observer.clone()),
55 ));
56
57 let video = unsafe { sys_vt::ffi::media_to_video(video_track.sys_handle()) };
58 video.add_sink(&native_sink);
59
60 Self { native_sink, observer, video_track, frame_queue }
61 }
62
63 /// Set the packet trailer handler for this stream.
64 ///
65 /// When set, each frame produced by this stream will have its
66 /// `user_timestamp` field populated from the handler's receive
67 /// map (looked up by RTP timestamp).
68 ///
69 /// Note: If the handler was already set on the `RtcVideoTrack` before
70 /// creating this stream, it is automatically wired up. This method is
71 /// only needed if you want to override or set the handler after
72 /// construction.
73 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
74 *self.observer.packet_trailer_handler.lock() = Some(handler);
75 }
76
77 pub fn track(&self) -> RtcVideoTrack {
78 self.video_track.clone()
79 }
80
81 pub fn close(&mut self) {
82 let video = unsafe { sys_vt::ffi::media_to_video(self.video_track.sys_handle()) };
83 video.remove_sink(&self.native_sink);
84 self.frame_queue.close();
85 }
86 }
87
88 impl Drop for NativeVideoStream {
89 fn drop(&mut self) {
90 self.close();
91 }
92 }
93
94 impl Stream for NativeVideoStream {
95 type Item = BoxVideoFrame;
96
97 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
98 self.frame_queue.poll_recv(cx)
99 }
100 }
101
102 struct VideoTrackObserver {
103 frame_queue: Arc<VideoFrameQueue>,
104 packet_trailer_handler: Mutex<Option<PacketTrailerHandler>>,
105 }
106
107 impl VideoTrackObserver {
108 fn frame_metadata(
109 &self,
110 rtp_timestamp: u32,
111 handler: Option<&PacketTrailerHandler>,
112 ) -> Option<FrameMetadata> {
113 handler
114 .and_then(|handler| {
115 handler.lookup_frame_metadata(rtp_timestamp).map(|(ts, fid, user_data)| {
116 handler.emit_subscribe_timing(SubscribeTimingStage::DecoderOutput, ts, fid);
117 (ts, fid, user_data)
118 })
119 })
120 .map(|(ts, fid, user_data)| FrameMetadata {
121 user_timestamp: if ts != 0 { Some(ts) } else { None },
122 frame_id: if fid != 0 { Some(fid) } else { None },
123 user_data: if user_data.is_empty() { None } else { Some(user_data) },
124 })
125 }
126 }
127
128 impl sys_vt::VideoSink for VideoTrackObserver {
129 fn on_frame(&self, frame: UniquePtr<webrtc_sys::video_frame::ffi::VideoFrame>) {
130 let packet_trailer_handler = self.packet_trailer_handler.lock().clone();
131 let frame_metadata =
132 self.frame_metadata(frame.timestamp(), packet_trailer_handler.as_ref());
133
134 self.frame_queue.push(VideoFrame {
135 rotation: frame.rotation().into(),
136 timestamp_us: frame.timestamp_us(),
137 frame_metadata,
138 buffer: new_video_frame_buffer(unsafe { frame.video_frame_buffer() }),
139 });
140 }
141
142 fn on_discarded_frame(&self) {}
143
144 fn on_constraints_changed(&self, _constraints: sys_vt::ffi::VideoTrackSourceConstraints) {}
145 }
146
147 struct VideoFrameQueue {
148 kind: VideoFrameQueueKind,
149 closed: AtomicBool,
150 dropped_frames: AtomicU64,
151 waker: Mutex<Option<Waker>>,
152 }
153
154 enum VideoFrameQueueKind {
155 Latest(LatestVideoFrameQueue),
156 Bounded(BoundedVideoFrameQueue),
157 Unbounded(UnboundedVideoFrameQueue),
158 }
159
160 struct LatestVideoFrameQueue {
161 frame: Mutex<Option<BoxVideoFrame>>,
162 }
163
164 struct BoundedVideoFrameQueue {
165 producer: Mutex<Producer<BoxVideoFrame>>,
166 consumer: Mutex<Consumer<BoxVideoFrame>>,
167 }
168
169 struct UnboundedVideoFrameQueue {
170 frames: Mutex<VecDeque<BoxVideoFrame>>,
171 }
172
173 impl VideoFrameQueue {
174 fn new(capacity: Option<usize>) -> Self {
175 let kind = match capacity.filter(|capacity| *capacity > 0) {
176 Some(1) => {
177 VideoFrameQueueKind::Latest(LatestVideoFrameQueue { frame: Mutex::new(None) })
178 }
179 Some(capacity) => {
180 let (producer, consumer) = RingBuffer::new(capacity);
181 VideoFrameQueueKind::Bounded(BoundedVideoFrameQueue {
182 producer: Mutex::new(producer),
183 consumer: Mutex::new(consumer),
184 })
185 }
186 None => VideoFrameQueueKind::Unbounded(UnboundedVideoFrameQueue {
187 frames: Mutex::new(VecDeque::new()),
188 }),
189 };
190
191 Self {
192 kind,
193 closed: AtomicBool::new(false),
194 dropped_frames: AtomicU64::new(0),
195 waker: Mutex::new(None),
196 }
197 }
198
199 fn push(&self, frame: BoxVideoFrame) {
200 if self.closed.load(Ordering::Acquire) {
201 return;
202 }
203
204 match &self.kind {
205 VideoFrameQueueKind::Latest(queue) => {
206 if queue.frame.lock().replace(frame).is_some() {
207 self.record_drop();
208 }
209 }
210 VideoFrameQueueKind::Bounded(queue) => self.push_bounded(queue, frame),
211 VideoFrameQueueKind::Unbounded(queue) => {
212 queue.frames.lock().push_back(frame);
213 }
214 }
215
216 self.wake_receiver();
217 }
218
219 fn push_bounded(&self, queue: &BoundedVideoFrameQueue, mut frame: BoxVideoFrame) {
220 loop {
221 let push_result = queue.producer.lock().push(frame);
222 match push_result {
223 Ok(()) => return,
224 Err(PushError::Full(returned_frame)) => {
225 frame = returned_frame;
226
227 let dropped = queue.consumer.lock().pop().is_ok();
228 if dropped {
229 self.record_drop();
230 } else {
231 return;
232 }
233 }
234 }
235 }
236 }
237
238 fn close(&self) {
239 self.closed.store(true, Ordering::Release);
240 self.wake_receiver();
241
242 match &self.kind {
243 VideoFrameQueueKind::Latest(queue) => {
244 queue.frame.lock().take();
245 }
246 VideoFrameQueueKind::Bounded(queue) => {
247 let mut consumer = queue.consumer.lock();
248 while consumer.pop().is_ok() {}
249 }
250 VideoFrameQueueKind::Unbounded(queue) => {
251 queue.frames.lock().clear();
252 }
253 }
254 }
255
256 fn poll_recv(&self, cx: &mut Context<'_>) -> Poll<Option<BoxVideoFrame>> {
257 if let Some(frame) = self.try_pop() {
258 return Poll::Ready(Some(frame));
259 }
260
261 if self.closed.load(Ordering::Acquire) {
262 return Poll::Ready(None);
263 }
264
265 *self.waker.lock() = Some(cx.waker().clone());
266
267 if let Some(frame) = self.try_pop() {
268 self.waker.lock().take();
269 Poll::Ready(Some(frame))
270 } else if self.closed.load(Ordering::Acquire) {
271 Poll::Ready(None)
272 } else {
273 Poll::Pending
274 }
275 }
276
277 fn try_pop(&self) -> Option<BoxVideoFrame> {
278 match &self.kind {
279 VideoFrameQueueKind::Latest(queue) => queue.frame.lock().take(),
280 VideoFrameQueueKind::Bounded(queue) => queue.consumer.lock().pop().ok(),
281 VideoFrameQueueKind::Unbounded(queue) => queue.frames.lock().pop_front(),
282 }
283 }
284
285 fn wake_receiver(&self) {
286 let waker = self.waker.lock().take();
287 if let Some(waker) = waker {
288 waker.wake();
289 }
290 }
291
292 fn record_drop(&self) {
293 let dropped_frames = self.dropped_frames.fetch_add(1, Ordering::Relaxed) + 1;
294 if dropped_frames == 1 || dropped_frames % 100 == 0 {
295 log::warn!(
296 "native video stream queue overflow; dropped {} queued frames",
297 dropped_frames
298 );
299 }
300 }
301 }
302
303 #[cfg(test)]
304 mod tests {
305 use std::sync::atomic::Ordering;
306
307 use super::VideoFrameQueue;
308 use crate::video_frame::{BoxVideoFrame, I420Buffer, VideoFrame, VideoRotation};
309
310 fn test_frame(timestamp_us: i64) -> BoxVideoFrame {
311 VideoFrame {
312 rotation: VideoRotation::VideoRotation0,
313 timestamp_us,
314 frame_metadata: None,
315 buffer: Box::new(I420Buffer::new(2, 2)),
316 }
317 }
318
319 fn pop_timestamp(queue: &VideoFrameQueue) -> Option<i64> {
320 queue.try_pop().map(|frame| frame.timestamp_us)
321 }
322
323 #[test]
324 fn bounded_queue_preserves_fifo_order_under_capacity() {
325 let queue = VideoFrameQueue::new(Some(3));
326
327 queue.push(test_frame(1));
328 queue.push(test_frame(2));
329 queue.push(test_frame(3));
330
331 assert_eq!(pop_timestamp(&queue), Some(1));
332 assert_eq!(pop_timestamp(&queue), Some(2));
333 assert_eq!(pop_timestamp(&queue), Some(3));
334 assert_eq!(pop_timestamp(&queue), None);
335 }
336
337 #[test]
338 fn bounded_queue_drops_oldest_when_full() {
339 let queue = VideoFrameQueue::new(Some(2));
340
341 queue.push(test_frame(1));
342 queue.push(test_frame(2));
343 queue.push(test_frame(3));
344
345 assert_eq!(queue.dropped_frames.load(Ordering::Relaxed), 1);
346 assert_eq!(pop_timestamp(&queue), Some(2));
347 assert_eq!(pop_timestamp(&queue), Some(3));
348 assert_eq!(pop_timestamp(&queue), None);
349 }
350
351 #[test]
352 fn one_frame_queue_keeps_latest_frame() {
353 let queue = VideoFrameQueue::new(Some(1));
354
355 queue.push(test_frame(1));
356 queue.push(test_frame(2));
357 queue.push(test_frame(3));
358
359 assert_eq!(queue.dropped_frames.load(Ordering::Relaxed), 2);
360 assert_eq!(pop_timestamp(&queue), Some(3));
361 assert_eq!(pop_timestamp(&queue), None);
362 }
363
364 #[test]
365 fn unbounded_queue_retains_all_frames() {
366 let queue = VideoFrameQueue::new(None);
367
368 for timestamp_us in 1..=4 {
369 queue.push(test_frame(timestamp_us));
370 }
371
372 for timestamp_us in 1..=4 {
373 assert_eq!(pop_timestamp(&queue), Some(timestamp_us));
374 }
375 assert_eq!(pop_timestamp(&queue), None);
376 assert_eq!(queue.dropped_frames.load(Ordering::Relaxed), 0);
377 }
378
379 #[test]
380 fn close_clears_buffer_and_rejects_future_pushes() {
381 let queue = VideoFrameQueue::new(Some(2));
382
383 queue.push(test_frame(1));
384 queue.close();
385 queue.push(test_frame(2));
386
387 assert_eq!(pop_timestamp(&queue), None);
388 }
389 }
@@ -0,0 +1,389 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{
16 collections::VecDeque,
17 pin::Pin,
18 sync::{
19 atomic::{AtomicBool, AtomicU64, Ordering},
20 Arc,
21 },
22 task::{Context, Poll, Waker},
23};
24
25use cxx::{SharedPtr, UniquePtr};
26use parking_lot::Mutex;
27use rtrb::{Consumer, Producer, PushError, RingBuffer};
28use tokio_stream::Stream;
29use webrtc_sys::video_track as sys_vt;
30
31use super::{packet_trailer::SubscribeTimingStage, video_frame::new_video_frame_buffer};
32use crate::{
33 native::packet_trailer::PacketTrailerHandler,
34 video_frame::{BoxVideoFrame, FrameMetadata, VideoFrame},
35 video_track::RtcVideoTrack,
36};
37
38pub struct NativeVideoStream {
39 native_sink: SharedPtr<sys_vt::ffi::NativeVideoSink>,
40 observer: Arc<VideoTrackObserver>,
41 video_track: RtcVideoTrack,
42 frame_queue: Arc<VideoFrameQueue>,
43}
44
45impl NativeVideoStream {
46 pub fn new(video_track: RtcVideoTrack, queue_size_frames: Option<usize>) -> Self {
47 let frame_queue = Arc::new(VideoFrameQueue::new(queue_size_frames));
48 // Auto-wire the packet trailer handler from the track if one is set.
49 let observer = Arc::new(VideoTrackObserver {
50 frame_queue: frame_queue.clone(),
51 packet_trailer_handler: Mutex::new(video_track.handle.packet_trailer_handler()),
52 });
53 let native_sink = sys_vt::ffi::new_native_video_sink(Box::new(
54 sys_vt::VideoSinkWrapper::new(observer.clone()),
55 ));
56
57 let video = unsafe { sys_vt::ffi::media_to_video(video_track.sys_handle()) };
58 video.add_sink(&native_sink);
59
60 Self { native_sink, observer, video_track, frame_queue }
61 }
62
63 /// Set the packet trailer handler for this stream.
64 ///
65 /// When set, each frame produced by this stream will have its
66 /// `user_timestamp` field populated from the handler's receive
67 /// map (looked up by RTP timestamp).
68 ///
69 /// Note: If the handler was already set on the `RtcVideoTrack` before
70 /// creating this stream, it is automatically wired up. This method is
71 /// only needed if you want to override or set the handler after
72 /// construction.
73 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
74 *self.observer.packet_trailer_handler.lock() = Some(handler);
75 }
76
77 pub fn track(&self) -> RtcVideoTrack {
78 self.video_track.clone()
79 }
80
81 pub fn close(&mut self) {
82 let video = unsafe { sys_vt::ffi::media_to_video(self.video_track.sys_handle()) };
83 video.remove_sink(&self.native_sink);
84 self.frame_queue.close();
85 }
86}
87
88impl Drop for NativeVideoStream {
89 fn drop(&mut self) {
90 self.close();
91 }
92}
93
94impl Stream for NativeVideoStream {
95 type Item = BoxVideoFrame;
96
97 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
98 self.frame_queue.poll_recv(cx)
99 }
100}
101
102struct VideoTrackObserver {
103 frame_queue: Arc<VideoFrameQueue>,
104 packet_trailer_handler: Mutex<Option<PacketTrailerHandler>>,
105}
106
107impl VideoTrackObserver {
108 fn frame_metadata(
109 &self,
110 rtp_timestamp: u32,
111 handler: Option<&PacketTrailerHandler>,
112 ) -> Option<FrameMetadata> {
113 handler
114 .and_then(|handler| {
115 handler.lookup_frame_metadata(rtp_timestamp).map(|(ts, fid, user_data)| {
116 handler.emit_subscribe_timing(SubscribeTimingStage::DecoderOutput, ts, fid);
117 (ts, fid, user_data)
118 })
119 })
120 .map(|(ts, fid, user_data)| FrameMetadata {
121 user_timestamp: if ts != 0 { Some(ts) } else { None },
122 frame_id: if fid != 0 { Some(fid) } else { None },
123 user_data: if user_data.is_empty() { None } else { Some(user_data) },
124 })
125 }
126}
127
128impl sys_vt::VideoSink for VideoTrackObserver {
129 fn on_frame(&self, frame: UniquePtr<webrtc_sys::video_frame::ffi::VideoFrame>) {
130 let packet_trailer_handler = self.packet_trailer_handler.lock().clone();
131 let frame_metadata =
132 self.frame_metadata(frame.timestamp(), packet_trailer_handler.as_ref());
133
134 self.frame_queue.push(VideoFrame {
135 rotation: frame.rotation().into(),
136 timestamp_us: frame.timestamp_us(),
137 frame_metadata,
138 buffer: new_video_frame_buffer(unsafe { frame.video_frame_buffer() }),
139 });
140 }
141
142 fn on_discarded_frame(&self) {}
143
144 fn on_constraints_changed(&self, _constraints: sys_vt::ffi::VideoTrackSourceConstraints) {}
145}
146
147struct VideoFrameQueue {
148 kind: VideoFrameQueueKind,
149 closed: AtomicBool,
150 dropped_frames: AtomicU64,
151 waker: Mutex<Option<Waker>>,
152}
153
154enum VideoFrameQueueKind {
155 Latest(LatestVideoFrameQueue),
156 Bounded(BoundedVideoFrameQueue),
157 Unbounded(UnboundedVideoFrameQueue),
158}
159
160struct LatestVideoFrameQueue {
161 frame: Mutex<Option<BoxVideoFrame>>,
162}
163
164struct BoundedVideoFrameQueue {
165 producer: Mutex<Producer<BoxVideoFrame>>,
166 consumer: Mutex<Consumer<BoxVideoFrame>>,
167}
168
169struct UnboundedVideoFrameQueue {
170 frames: Mutex<VecDeque<BoxVideoFrame>>,
171}
172
173impl VideoFrameQueue {
174 fn new(capacity: Option<usize>) -> Self {
175 let kind = match capacity.filter(|capacity| *capacity > 0) {
176 Some(1) => {
177 VideoFrameQueueKind::Latest(LatestVideoFrameQueue { frame: Mutex::new(None) })
178 }
179 Some(capacity) => {
180 let (producer, consumer) = RingBuffer::new(capacity);
181 VideoFrameQueueKind::Bounded(BoundedVideoFrameQueue {
182 producer: Mutex::new(producer),
183 consumer: Mutex::new(consumer),
184 })
185 }
186 None => VideoFrameQueueKind::Unbounded(UnboundedVideoFrameQueue {
187 frames: Mutex::new(VecDeque::new()),
188 }),
189 };
190
191 Self {
192 kind,
193 closed: AtomicBool::new(false),
194 dropped_frames: AtomicU64::new(0),
195 waker: Mutex::new(None),
196 }
197 }
198
199 fn push(&self, frame: BoxVideoFrame) {
200 if self.closed.load(Ordering::Acquire) {
201 return;
202 }
203
204 match &self.kind {
205 VideoFrameQueueKind::Latest(queue) => {
206 if queue.frame.lock().replace(frame).is_some() {
207 self.record_drop();
208 }
209 }
210 VideoFrameQueueKind::Bounded(queue) => self.push_bounded(queue, frame),
211 VideoFrameQueueKind::Unbounded(queue) => {
212 queue.frames.lock().push_back(frame);
213 }
214 }
215
216 self.wake_receiver();
217 }
218
219 fn push_bounded(&self, queue: &BoundedVideoFrameQueue, mut frame: BoxVideoFrame) {
220 loop {
221 let push_result = queue.producer.lock().push(frame);
222 match push_result {
223 Ok(()) => return,
224 Err(PushError::Full(returned_frame)) => {
225 frame = returned_frame;
226
227 let dropped = queue.consumer.lock().pop().is_ok();
228 if dropped {
229 self.record_drop();
230 } else {
231 return;
232 }
233 }
234 }
235 }
236 }
237
238 fn close(&self) {
239 self.closed.store(true, Ordering::Release);
240 self.wake_receiver();
241
242 match &self.kind {
243 VideoFrameQueueKind::Latest(queue) => {
244 queue.frame.lock().take();
245 }
246 VideoFrameQueueKind::Bounded(queue) => {
247 let mut consumer = queue.consumer.lock();
248 while consumer.pop().is_ok() {}
249 }
250 VideoFrameQueueKind::Unbounded(queue) => {
251 queue.frames.lock().clear();
252 }
253 }
254 }
255
256 fn poll_recv(&self, cx: &mut Context<'_>) -> Poll<Option<BoxVideoFrame>> {
257 if let Some(frame) = self.try_pop() {
258 return Poll::Ready(Some(frame));
259 }
260
261 if self.closed.load(Ordering::Acquire) {
262 return Poll::Ready(None);
263 }
264
265 *self.waker.lock() = Some(cx.waker().clone());
266
267 if let Some(frame) = self.try_pop() {
268 self.waker.lock().take();
269 Poll::Ready(Some(frame))
270 } else if self.closed.load(Ordering::Acquire) {
271 Poll::Ready(None)
272 } else {
273 Poll::Pending
274 }
275 }
276
277 fn try_pop(&self) -> Option<BoxVideoFrame> {
278 match &self.kind {
279 VideoFrameQueueKind::Latest(queue) => queue.frame.lock().take(),
280 VideoFrameQueueKind::Bounded(queue) => queue.consumer.lock().pop().ok(),
281 VideoFrameQueueKind::Unbounded(queue) => queue.frames.lock().pop_front(),
282 }
283 }
284
285 fn wake_receiver(&self) {
286 let waker = self.waker.lock().take();
287 if let Some(waker) = waker {
288 waker.wake();
289 }
290 }
291
292 fn record_drop(&self) {
293 let dropped_frames = self.dropped_frames.fetch_add(1, Ordering::Relaxed) + 1;
294 if dropped_frames == 1 || dropped_frames % 100 == 0 {
295 log::warn!(
296 "native video stream queue overflow; dropped {} queued frames",
297 dropped_frames
298 );
299 }
300 }
301}
302
303#[cfg(test)]
304mod tests {
305 use std::sync::atomic::Ordering;
306
307 use super::VideoFrameQueue;
308 use crate::video_frame::{BoxVideoFrame, I420Buffer, VideoFrame, VideoRotation};
309
310 fn test_frame(timestamp_us: i64) -> BoxVideoFrame {
311 VideoFrame {
312 rotation: VideoRotation::VideoRotation0,
313 timestamp_us,
314 frame_metadata: None,
315 buffer: Box::new(I420Buffer::new(2, 2)),
316 }
317 }
318
319 fn pop_timestamp(queue: &VideoFrameQueue) -> Option<i64> {
320 queue.try_pop().map(|frame| frame.timestamp_us)
321 }
322
323 #[test]
324 fn bounded_queue_preserves_fifo_order_under_capacity() {
325 let queue = VideoFrameQueue::new(Some(3));
326
327 queue.push(test_frame(1));
328 queue.push(test_frame(2));
329 queue.push(test_frame(3));
330
331 assert_eq!(pop_timestamp(&queue), Some(1));
332 assert_eq!(pop_timestamp(&queue), Some(2));
333 assert_eq!(pop_timestamp(&queue), Some(3));
334 assert_eq!(pop_timestamp(&queue), None);
335 }
336
337 #[test]
338 fn bounded_queue_drops_oldest_when_full() {
339 let queue = VideoFrameQueue::new(Some(2));
340
341 queue.push(test_frame(1));
342 queue.push(test_frame(2));
343 queue.push(test_frame(3));
344
345 assert_eq!(queue.dropped_frames.load(Ordering::Relaxed), 1);
346 assert_eq!(pop_timestamp(&queue), Some(2));
347 assert_eq!(pop_timestamp(&queue), Some(3));
348 assert_eq!(pop_timestamp(&queue), None);
349 }
350
351 #[test]
352 fn one_frame_queue_keeps_latest_frame() {
353 let queue = VideoFrameQueue::new(Some(1));
354
355 queue.push(test_frame(1));
356 queue.push(test_frame(2));
357 queue.push(test_frame(3));
358
359 assert_eq!(queue.dropped_frames.load(Ordering::Relaxed), 2);
360 assert_eq!(pop_timestamp(&queue), Some(3));
361 assert_eq!(pop_timestamp(&queue), None);
362 }
363
364 #[test]
365 fn unbounded_queue_retains_all_frames() {
366 let queue = VideoFrameQueue::new(None);
367
368 for timestamp_us in 1..=4 {
369 queue.push(test_frame(timestamp_us));
370 }
371
372 for timestamp_us in 1..=4 {
373 assert_eq!(pop_timestamp(&queue), Some(timestamp_us));
374 }
375 assert_eq!(pop_timestamp(&queue), None);
376 assert_eq!(queue.dropped_frames.load(Ordering::Relaxed), 0);
377 }
378
379 #[test]
380 fn close_clears_buffer_and_rejects_future_pushes() {
381 let queue = VideoFrameQueue::new(Some(2));
382
383 queue.push(test_frame(1));
384 queue.close();
385 queue.push(test_frame(2));
386
387 assert_eq!(pop_timestamp(&queue), None);
388 }
389}
vendor/libwebrtc/src/native/video_track.rs added +56 −0
@@ -0,0 +1,56 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::sync::Arc;
16
17 use cxx::SharedPtr;
18 use parking_lot::Mutex;
19 use sys_vt::ffi::video_to_media;
20 use webrtc_sys::video_track as sys_vt;
21
22 use super::media_stream_track::impl_media_stream_track;
23 use super::packet_trailer::PacketTrailerHandler;
24 use crate::media_stream_track::RtcTrackState;
25
26 #[derive(Clone)]
27 pub struct RtcVideoTrack {
28 pub(crate) sys_handle: SharedPtr<sys_vt::ffi::VideoTrack>,
29 packet_trailer_handler: Arc<Mutex<Option<PacketTrailerHandler>>>,
30 }
31
32 impl RtcVideoTrack {
33 impl_media_stream_track!(video_to_media);
34
35 pub(crate) fn new(sys_handle: SharedPtr<sys_vt::ffi::VideoTrack>) -> Self {
36 Self { sys_handle, packet_trailer_handler: Arc::new(Mutex::new(None)) }
37 }
38
39 pub fn sys_handle(&self) -> SharedPtr<sys_vt::ffi::MediaStreamTrack> {
40 video_to_media(self.sys_handle.clone())
41 }
42
43 /// Set the packet trailer handler for this track.
44 ///
45 /// When set, any `NativeVideoStream` created from this track will
46 /// automatically use this handler to populate `user_timestamp`
47 /// on each decoded frame.
48 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
49 self.packet_trailer_handler.lock().replace(handler);
50 }
51
52 /// Get the packet trailer handler, if one has been set.
53 pub fn packet_trailer_handler(&self) -> Option<PacketTrailerHandler> {
54 self.packet_trailer_handler.lock().clone()
55 }
56 }
@@ -0,0 +1,56 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::Arc;
16
17use cxx::SharedPtr;
18use parking_lot::Mutex;
19use sys_vt::ffi::video_to_media;
20use webrtc_sys::video_track as sys_vt;
21
22use super::media_stream_track::impl_media_stream_track;
23use super::packet_trailer::PacketTrailerHandler;
24use crate::media_stream_track::RtcTrackState;
25
26#[derive(Clone)]
27pub struct RtcVideoTrack {
28 pub(crate) sys_handle: SharedPtr<sys_vt::ffi::VideoTrack>,
29 packet_trailer_handler: Arc<Mutex<Option<PacketTrailerHandler>>>,
30}
31
32impl RtcVideoTrack {
33 impl_media_stream_track!(video_to_media);
34
35 pub(crate) fn new(sys_handle: SharedPtr<sys_vt::ffi::VideoTrack>) -> Self {
36 Self { sys_handle, packet_trailer_handler: Arc::new(Mutex::new(None)) }
37 }
38
39 pub fn sys_handle(&self) -> SharedPtr<sys_vt::ffi::MediaStreamTrack> {
40 video_to_media(self.sys_handle.clone())
41 }
42
43 /// Set the packet trailer handler for this track.
44 ///
45 /// When set, any `NativeVideoStream` created from this track will
46 /// automatically use this handler to populate `user_timestamp`
47 /// on each decoded frame.
48 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
49 self.packet_trailer_handler.lock().replace(handler);
50 }
51
52 /// Get the packet trailer handler, if one has been set.
53 pub fn packet_trailer_handler(&self) -> Option<PacketTrailerHandler> {
54 self.packet_trailer_handler.lock().clone()
55 }
56}
vendor/libwebrtc/src/native/yuv_helper.rs added +868 −0
@@ -0,0 +1,868 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #![allow(clippy::too_many_arguments)]
16
17 use webrtc_sys::yuv_helper as yuv_sys;
18
19 fn argb_assert_safety(src: &[u8], src_stride: u32, _width: i32, height: i32) {
20 let height_abs = height.unsigned_abs();
21 let min = (src_stride * height_abs) as usize;
22 assert!(src.len() >= min, "src isn't large enough");
23 }
24
25 fn i420_assert_safety(
26 src_y: &[u8],
27 src_stride_y: u32,
28 src_u: &[u8],
29 src_stride_u: u32,
30 src_v: &[u8],
31 src_stride_v: u32,
32 _width: i32,
33 height: i32,
34 ) {
35 let height_abs = height.unsigned_abs();
36 let chroma_height = (height_abs + 1) / 2;
37 let min_y = (src_stride_y * height_abs) as usize;
38 let min_u = (src_stride_u * chroma_height) as usize;
39 let min_v = (src_stride_v * chroma_height) as usize;
40
41 assert!(src_y.len() >= min_y, "src_y isn't large enough");
42 assert!(src_u.len() >= min_u, "src_u isn't large enough");
43 assert!(src_v.len() >= min_v, "src_v isn't large enough");
44 }
45
46 fn nv12_assert_safety(
47 src_y: &[u8],
48 src_stride_y: u32,
49 src_uv: &[u8],
50 src_stride_uv: u32,
51 _width: i32,
52 height: i32,
53 ) {
54 let height_abs = height.unsigned_abs();
55 let chroma_height = (height_abs + 1) / 2;
56
57 let min_y = (src_stride_y * height_abs) as usize;
58 let min_uv = (src_stride_uv * chroma_height) as usize;
59
60 assert!(src_y.len() >= min_y, "src_y isn't large enough");
61 assert!(src_uv.len() >= min_uv, "src_uv isn't large enough");
62 }
63
64 fn i444_assert_safety(
65 src_y: &[u8],
66 src_stride_y: u32,
67 src_u: &[u8],
68 src_stride_u: u32,
69 src_v: &[u8],
70 src_stride_v: u32,
71 _width: i32,
72 height: i32,
73 ) {
74 let height_abs = height.unsigned_abs();
75 let min_y = (src_stride_y * height_abs) as usize;
76 let min_u = (src_stride_u * height_abs) as usize;
77 let min_v = (src_stride_v * height_abs) as usize;
78
79 assert!(src_y.len() >= min_y, "src_y isn't large enough");
80 assert!(src_u.len() >= min_u, "src_u isn't large enough");
81 assert!(src_v.len() >= min_v, "src_v isn't large enough");
82 }
83
84 fn i422_assert_safety(
85 src_y: &[u8],
86 src_stride_y: u32,
87 src_u: &[u8],
88 src_stride_u: u32,
89 src_v: &[u8],
90 src_stride_v: u32,
91 _width: i32,
92 height: i32,
93 ) {
94 let height_abs = height.unsigned_abs();
95 let min_y = (src_stride_y * height_abs) as usize;
96 let min_u = (src_stride_u * height_abs) as usize;
97 let min_v = (src_stride_v * height_abs) as usize;
98
99 assert!(src_y.len() >= min_y, "src_y isn't large enough");
100 assert!(src_u.len() >= min_u, "src_u isn't large enough");
101 assert!(src_v.len() >= min_v, "src_v isn't large enough");
102 }
103
104 fn i010_assert_safety(
105 src_y: &[u16],
106 src_stride_y: u32,
107 src_u: &[u16],
108 src_stride_u: u32,
109 src_v: &[u16],
110 src_stride_v: u32,
111 _width: i32,
112 height: i32,
113 ) {
114 let height_abs: u32 = height.unsigned_abs();
115 let chroma_height = height_abs / 2;
116 let min_y = (src_stride_y * height_abs) as usize / 2;
117 let min_u = (src_stride_u * chroma_height) as usize / 2;
118 let min_v = (src_stride_v * chroma_height) as usize / 2;
119
120 assert!(src_y.len() >= min_y, "src_y isn't large enough");
121 assert!(src_u.len() >= min_u, "src_u isn't large enough");
122 assert!(src_v.len() >= min_v, "src_v isn't large enough");
123 }
124
125 macro_rules! i420_to_rgba {
126 ($x:ident) => {
127 pub fn $x(
128 src_y: &[u8],
129 src_stride_y: u32,
130 src_u: &[u8],
131 src_stride_u: u32,
132 src_v: &[u8],
133 src_stride_v: u32,
134 dst: &mut [u8],
135 dst_stride: u32,
136 width: i32,
137 height: i32,
138 ) {
139 i420_assert_safety(
140 src_y,
141 src_stride_y,
142 src_u,
143 src_stride_u,
144 src_v,
145 src_stride_v,
146 width,
147 height,
148 );
149 argb_assert_safety(dst, dst_stride, width, height);
150
151 unsafe {
152 yuv_sys::ffi::$x(
153 src_y.as_ptr(),
154 src_stride_y as i32,
155 src_u.as_ptr(),
156 src_stride_u as i32,
157 src_v.as_ptr(),
158 src_stride_v as i32,
159 dst.as_mut_ptr(),
160 dst_stride as i32,
161 width,
162 height,
163 )
164 .unwrap();
165 }
166 }
167 };
168 }
169
170 macro_rules! rgba_to_i420 {
171 ($x:ident) => {
172 pub fn $x(
173 src_argb: &[u8],
174 src_stride_argb: u32,
175 dst_y: &mut [u8],
176 dst_stride_y: u32,
177 dst_u: &mut [u8],
178 dst_stride_u: u32,
179 dst_v: &mut [u8],
180 dst_stride_v: u32,
181 width: i32,
182 height: i32,
183 ) {
184 i420_assert_safety(
185 dst_y,
186 dst_stride_y,
187 dst_u,
188 dst_stride_u,
189 dst_v,
190 dst_stride_v,
191 width,
192 height,
193 );
194 argb_assert_safety(src_argb, src_stride_argb, width, height);
195
196 unsafe {
197 yuv_sys::ffi::$x(
198 src_argb.as_ptr(),
199 src_stride_argb as i32,
200 dst_y.as_mut_ptr(),
201 dst_stride_y as i32,
202 dst_u.as_mut_ptr(),
203 dst_stride_u as i32,
204 dst_v.as_mut_ptr(),
205 dst_stride_v as i32,
206 width,
207 height,
208 )
209 .unwrap();
210 }
211 }
212 };
213 }
214
215 pub fn argb_to_rgb24(
216 src_argb: &[u8],
217 src_stride_argb: u32,
218 dst_rgb24: &mut [u8],
219 dst_stride_rgb24: u32,
220 width: i32,
221 height: i32,
222 ) {
223 argb_assert_safety(src_argb, src_stride_argb, width, height);
224 argb_assert_safety(dst_rgb24, dst_stride_rgb24, width, height);
225
226 unsafe {
227 yuv_sys::ffi::argb_to_rgb24(
228 src_argb.as_ptr(),
229 src_stride_argb as i32,
230 dst_rgb24.as_mut_ptr(),
231 dst_stride_rgb24 as i32,
232 width,
233 height,
234 )
235 .unwrap();
236 }
237 }
238
239 // I420 <> RGB conversion
240 rgba_to_i420!(argb_to_i420);
241 rgba_to_i420!(abgr_to_i420);
242
243 i420_to_rgba!(i420_to_argb);
244 i420_to_rgba!(i420_to_bgra);
245 i420_to_rgba!(i420_to_abgr);
246 i420_to_rgba!(i420_to_rgba);
247
248 pub fn i420_to_nv12(
249 src_y: &[u8],
250 src_stride_y: u32,
251 src_u: &[u8],
252 src_stride_u: u32,
253 src_v: &[u8],
254 src_stride_v: u32,
255 dst_y: &mut [u8],
256 dst_stride_y: u32,
257 dst_uv: &mut [u8],
258 dst_stride_uv: u32,
259 width: i32,
260 height: i32,
261 ) {
262 i420_assert_safety(
263 src_y,
264 src_stride_y,
265 src_u,
266 src_stride_u,
267 src_v,
268 src_stride_v,
269 width,
270 height,
271 );
272 nv12_assert_safety(dst_y, dst_stride_y, dst_uv, dst_stride_uv, width, height);
273
274 unsafe {
275 yuv_sys::ffi::i420_to_nv12(
276 src_y.as_ptr(),
277 src_stride_y as i32,
278 src_u.as_ptr(),
279 src_stride_u as i32,
280 src_v.as_ptr(),
281 src_stride_v as i32,
282 dst_y.as_mut_ptr(),
283 dst_stride_y as i32,
284 dst_uv.as_mut_ptr(),
285 dst_stride_uv as i32,
286 width,
287 height,
288 )
289 .unwrap();
290 }
291 }
292
293 pub fn nv12_to_i420(
294 src_y: &[u8],
295 src_stride_y: u32,
296 src_uv: &[u8],
297 src_stride_uv: u32,
298 dst_y: &mut [u8],
299 dst_stride_y: u32,
300 dst_u: &mut [u8],
301 dst_stride_u: u32,
302 dst_v: &mut [u8],
303 dst_stride_v: u32,
304 width: i32,
305 height: i32,
306 ) {
307 nv12_assert_safety(src_y, src_stride_y, src_uv, src_stride_uv, width, height);
308 i420_assert_safety(
309 dst_y,
310 dst_stride_y,
311 dst_u,
312 dst_stride_u,
313 dst_v,
314 dst_stride_v,
315 width,
316 height,
317 );
318
319 unsafe {
320 yuv_sys::ffi::nv12_to_i420(
321 src_y.as_ptr(),
322 src_stride_y as i32,
323 src_uv.as_ptr(),
324 src_stride_uv as i32,
325 dst_y.as_mut_ptr(),
326 dst_stride_y as i32,
327 dst_u.as_mut_ptr(),
328 dst_stride_u as i32,
329 dst_v.as_mut_ptr(),
330 dst_stride_v as i32,
331 width,
332 height,
333 )
334 .unwrap();
335 }
336 }
337
338 pub fn i444_to_i420(
339 src_y: &[u8],
340 src_stride_y: u32,
341 src_u: &[u8],
342 src_stride_u: u32,
343 src_v: &[u8],
344 src_stride_v: u32,
345 dst_y: &mut [u8],
346 dst_stride_y: u32,
347 dst_u: &mut [u8],
348 dst_stride_u: u32,
349 dst_v: &mut [u8],
350 dst_stride_v: u32,
351 width: i32,
352 height: i32,
353 ) {
354 i444_assert_safety(
355 src_y,
356 src_stride_y,
357 src_u,
358 src_stride_u,
359 src_v,
360 src_stride_v,
361 width,
362 height,
363 );
364 i420_assert_safety(
365 dst_y,
366 dst_stride_y,
367 dst_u,
368 dst_stride_u,
369 dst_v,
370 dst_stride_v,
371 width,
372 height,
373 );
374
375 unsafe {
376 yuv_sys::ffi::i444_to_i420(
377 src_y.as_ptr(),
378 src_stride_y as i32,
379 src_u.as_ptr(),
380 src_stride_u as i32,
381 src_v.as_ptr(),
382 src_stride_v as i32,
383 dst_y.as_mut_ptr(),
384 dst_stride_y as i32,
385 dst_u.as_mut_ptr(),
386 dst_stride_u as i32,
387 dst_v.as_mut_ptr(),
388 dst_stride_v as i32,
389 width,
390 height,
391 )
392 .unwrap();
393 }
394 }
395
396 pub fn i422_to_i420(
397 src_y: &[u8],
398 src_stride_y: u32,
399 src_u: &[u8],
400 src_stride_u: u32,
401 src_v: &[u8],
402 src_stride_v: u32,
403 dst_y: &mut [u8],
404 dst_stride_y: u32,
405 dst_u: &mut [u8],
406 dst_stride_u: u32,
407 dst_v: &mut [u8],
408 dst_stride_v: u32,
409 width: i32,
410 height: i32,
411 ) {
412 i422_assert_safety(
413 src_y,
414 src_stride_y,
415 src_u,
416 src_stride_u,
417 src_v,
418 src_stride_v,
419 width,
420 height,
421 );
422 i420_assert_safety(
423 dst_y,
424 dst_stride_y,
425 dst_u,
426 dst_stride_u,
427 dst_v,
428 dst_stride_v,
429 width,
430 height,
431 );
432
433 unsafe {
434 yuv_sys::ffi::i422_to_i420(
435 src_y.as_ptr(),
436 src_stride_y as i32,
437 src_u.as_ptr(),
438 src_stride_u as i32,
439 src_v.as_ptr(),
440 src_stride_v as i32,
441 dst_y.as_mut_ptr(),
442 dst_stride_y as i32,
443 dst_u.as_mut_ptr(),
444 dst_stride_u as i32,
445 dst_v.as_mut_ptr(),
446 dst_stride_v as i32,
447 width,
448 height,
449 )
450 .unwrap()
451 }
452 }
453
454 pub fn i010_to_i420(
455 src_y: &[u16],
456 src_stride_y: u32,
457 src_u: &[u16],
458 src_stride_u: u32,
459 src_v: &[u16],
460 src_stride_v: u32,
461 dst_y: &mut [u8],
462 dst_stride_y: u32,
463 dst_u: &mut [u8],
464 dst_stride_u: u32,
465 dst_v: &mut [u8],
466 dst_stride_v: u32,
467 width: i32,
468 height: i32,
469 ) {
470 i010_assert_safety(
471 src_y,
472 src_stride_y,
473 src_u,
474 src_stride_u,
475 src_v,
476 src_stride_v,
477 width,
478 height,
479 );
480 i420_assert_safety(
481 dst_y,
482 dst_stride_y,
483 dst_u,
484 dst_stride_u,
485 dst_v,
486 dst_stride_v,
487 width,
488 height,
489 );
490
491 unsafe {
492 yuv_sys::ffi::i010_to_i420(
493 src_y.as_ptr(),
494 src_stride_y as i32,
495 src_u.as_ptr(),
496 src_stride_u as i32,
497 src_v.as_ptr(),
498 src_stride_v as i32,
499 dst_y.as_mut_ptr(),
500 dst_stride_y as i32,
501 dst_u.as_mut_ptr(),
502 dst_stride_u as i32,
503 dst_v.as_mut_ptr(),
504 dst_stride_v as i32,
505 width,
506 height,
507 )
508 .unwrap()
509 }
510 }
511
512 pub fn nv12_to_argb(
513 src_y: &[u8],
514 src_stride_y: u32,
515 src_uv: &[u8],
516 src_stride_uv: u32,
517 dst_argb: &mut [u8],
518 dst_stride_argb: u32,
519 width: i32,
520 height: i32,
521 ) {
522 nv12_assert_safety(src_y, src_stride_y, src_uv, src_stride_uv, width, height);
523 argb_assert_safety(dst_argb, dst_stride_argb, width, height);
524
525 unsafe {
526 yuv_sys::ffi::nv12_to_argb(
527 src_y.as_ptr(),
528 src_stride_y as i32,
529 src_uv.as_ptr(),
530 src_stride_uv as i32,
531 dst_argb.as_mut_ptr(),
532 dst_stride_argb as i32,
533 width,
534 height,
535 )
536 .unwrap();
537 }
538 }
539
540 pub fn nv12_to_abgr(
541 src_y: &[u8],
542 src_stride_y: u32,
543 src_uv: &[u8],
544 src_stride_uv: u32,
545 dst_abgr: &mut [u8],
546 dst_stride_abgr: u32,
547 width: i32,
548 height: i32,
549 ) {
550 nv12_assert_safety(src_y, src_stride_y, src_uv, src_stride_uv, width, height);
551 argb_assert_safety(dst_abgr, dst_stride_abgr, width, height);
552
553 unsafe {
554 yuv_sys::ffi::nv12_to_abgr(
555 src_y.as_ptr(),
556 src_stride_y as i32,
557 src_uv.as_ptr(),
558 src_stride_uv as i32,
559 dst_abgr.as_mut_ptr(),
560 dst_stride_abgr as i32,
561 width,
562 height,
563 )
564 .unwrap();
565 }
566 }
567
568 pub fn i444_to_argb(
569 src_y: &[u8],
570 src_stride_y: u32,
571 src_u: &[u8],
572 src_stride_u: u32,
573 src_v: &[u8],
574 src_stride_v: u32,
575 dst_argb: &mut [u8],
576 dst_stride_argb: u32,
577 width: i32,
578 height: i32,
579 ) {
580 i444_assert_safety(
581 src_y,
582 src_stride_y,
583 src_u,
584 src_stride_u,
585 src_v,
586 src_stride_v,
587 width,
588 height,
589 );
590 argb_assert_safety(dst_argb, dst_stride_argb, width, height);
591
592 unsafe {
593 yuv_sys::ffi::i444_to_argb(
594 src_y.as_ptr(),
595 src_stride_y as i32,
596 src_u.as_ptr(),
597 src_stride_u as i32,
598 src_v.as_ptr(),
599 src_stride_v as i32,
600 dst_argb.as_mut_ptr(),
601 dst_stride_argb as i32,
602 width,
603 height,
604 )
605 .unwrap();
606 }
607 }
608
609 pub fn i444_to_abgr(
610 src_y: &[u8],
611 src_stride_y: u32,
612 src_u: &[u8],
613 src_stride_u: u32,
614 src_v: &[u8],
615 src_stride_v: u32,
616 dst_abgr: &mut [u8],
617 dst_stride_abgr: u32,
618 width: i32,
619 height: i32,
620 ) {
621 i444_assert_safety(
622 src_y,
623 src_stride_y,
624 src_u,
625 src_stride_u,
626 src_v,
627 src_stride_v,
628 width,
629 height,
630 );
631 argb_assert_safety(dst_abgr, dst_stride_abgr, width, height);
632
633 unsafe {
634 yuv_sys::ffi::i444_to_abgr(
635 src_y.as_ptr(),
636 src_stride_y as i32,
637 src_u.as_ptr(),
638 src_stride_u as i32,
639 src_v.as_ptr(),
640 src_stride_v as i32,
641 dst_abgr.as_mut_ptr(),
642 dst_stride_abgr as i32,
643 width,
644 height,
645 )
646 .unwrap()
647 }
648 }
649
650 pub fn i422_to_argb(
651 src_y: &[u8],
652 src_stride_y: u32,
653 src_u: &[u8],
654 src_stride_u: u32,
655 src_v: &[u8],
656 src_stride_v: u32,
657 dst_argb: &mut [u8],
658 dst_stride_argb: u32,
659 width: i32,
660 height: i32,
661 ) {
662 i422_assert_safety(
663 src_y,
664 src_stride_y,
665 src_u,
666 src_stride_u,
667 src_v,
668 src_stride_v,
669 width,
670 height,
671 );
672 argb_assert_safety(dst_argb, dst_stride_argb, width, height);
673
674 unsafe {
675 yuv_sys::ffi::i422_to_argb(
676 src_y.as_ptr(),
677 src_stride_y as i32,
678 src_u.as_ptr(),
679 src_stride_u as i32,
680 src_v.as_ptr(),
681 src_stride_v as i32,
682 dst_argb.as_mut_ptr(),
683 dst_stride_argb as i32,
684 width,
685 height,
686 )
687 .unwrap();
688 }
689 }
690
691 pub fn i422_to_abgr(
692 src_y: &[u8],
693 src_stride_y: u32,
694 src_u: &[u8],
695 src_stride_u: u32,
696 src_v: &[u8],
697 src_stride_v: u32,
698 dst_abgr: &mut [u8],
699 dst_stride_abgr: u32,
700 width: i32,
701 height: i32,
702 ) {
703 i422_assert_safety(
704 src_y,
705 src_stride_y,
706 src_u,
707 src_stride_u,
708 src_v,
709 src_stride_v,
710 width,
711 height,
712 );
713 argb_assert_safety(dst_abgr, dst_stride_abgr, width, height);
714
715 unsafe {
716 yuv_sys::ffi::i422_to_abgr(
717 src_y.as_ptr(),
718 src_stride_y as i32,
719 src_u.as_ptr(),
720 src_stride_u as i32,
721 src_v.as_ptr(),
722 src_stride_v as i32,
723 dst_abgr.as_mut_ptr(),
724 dst_stride_abgr as i32,
725 width,
726 height,
727 )
728 .unwrap()
729 }
730 }
731
732 pub fn i010_to_argb(
733 src_y: &[u16],
734 src_stride_y: u32,
735 src_u: &[u16],
736 src_stride_u: u32,
737 src_v: &[u16],
738 src_stride_v: u32,
739 dst_argb: &mut [u8],
740 dst_stride_argb: u32,
741 width: i32,
742 height: i32,
743 ) {
744 i010_assert_safety(
745 src_y,
746 src_stride_y,
747 src_u,
748 src_stride_u,
749 src_v,
750 src_stride_v,
751 width,
752 height,
753 );
754 argb_assert_safety(dst_argb, dst_stride_argb, width, height);
755
756 unsafe {
757 yuv_sys::ffi::i010_to_argb(
758 src_y.as_ptr(),
759 src_stride_y as i32,
760 src_u.as_ptr(),
761 src_stride_u as i32,
762 src_v.as_ptr(),
763 src_stride_v as i32,
764 dst_argb.as_mut_ptr(),
765 dst_stride_argb as i32,
766 width,
767 height,
768 )
769 .unwrap()
770 }
771 }
772
773 pub fn i010_to_abgr(
774 src_y: &[u16],
775 src_stride_y: u32,
776 src_u: &[u16],
777 src_stride_u: u32,
778 src_v: &[u16],
779 src_stride_v: u32,
780 dst_abgr: &mut [u8],
781 dst_stride_abgr: u32,
782 width: i32,
783 height: i32,
784 ) {
785 i010_assert_safety(
786 src_y,
787 src_stride_y,
788 src_u,
789 src_stride_u,
790 src_v,
791 src_stride_v,
792 width,
793 height,
794 );
795 argb_assert_safety(dst_abgr, dst_stride_abgr, width, height);
796
797 unsafe {
798 yuv_sys::ffi::i010_to_abgr(
799 src_y.as_ptr(),
800 src_stride_y as i32,
801 src_u.as_ptr(),
802 src_stride_u as i32,
803 src_v.as_ptr(),
804 src_stride_v as i32,
805 dst_abgr.as_mut_ptr(),
806 dst_stride_abgr as i32,
807 width,
808 height,
809 )
810 .unwrap()
811 }
812 }
813
814 pub fn abgr_to_nv12(
815 src_abgr: &[u8],
816 src_stride_abgr: u32,
817 dst_y: &mut [u8],
818 dst_stride_y: u32,
819 dst_uv: &mut [u8],
820 dst_stride_uv: u32,
821 width: i32,
822 height: i32,
823 ) {
824 argb_assert_safety(src_abgr, src_stride_abgr, width, height);
825 nv12_assert_safety(dst_y, dst_stride_y, dst_uv, dst_stride_uv, width, height);
826
827 unsafe {
828 yuv_sys::ffi::abgr_to_nv12(
829 src_abgr.as_ptr(),
830 src_stride_abgr as i32,
831 dst_y.as_mut_ptr(),
832 dst_stride_y as i32,
833 dst_uv.as_mut_ptr(),
834 dst_stride_uv as i32,
835 width,
836 height,
837 )
838 .unwrap()
839 }
840 }
841
842 pub fn argb_to_nv12(
843 src_argb: &[u8],
844 src_stride_argb: u32,
845 dst_y: &mut [u8],
846 dst_stride_y: u32,
847 dst_uv: &mut [u8],
848 dst_stride_uv: u32,
849 width: i32,
850 height: i32,
851 ) {
852 argb_assert_safety(src_argb, src_stride_argb, width, height);
853 nv12_assert_safety(dst_y, dst_stride_y, dst_uv, dst_stride_uv, width, height);
854
855 unsafe {
856 yuv_sys::ffi::argb_to_nv12(
857 src_argb.as_ptr(),
858 src_stride_argb as i32,
859 dst_y.as_mut_ptr(),
860 dst_stride_y as i32,
861 dst_uv.as_mut_ptr(),
862 dst_stride_uv as i32,
863 width,
864 height,
865 )
866 .unwrap()
867 }
868 }
@@ -0,0 +1,868 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![allow(clippy::too_many_arguments)]
16
17use webrtc_sys::yuv_helper as yuv_sys;
18
19fn argb_assert_safety(src: &[u8], src_stride: u32, _width: i32, height: i32) {
20 let height_abs = height.unsigned_abs();
21 let min = (src_stride * height_abs) as usize;
22 assert!(src.len() >= min, "src isn't large enough");
23}
24
25fn i420_assert_safety(
26 src_y: &[u8],
27 src_stride_y: u32,
28 src_u: &[u8],
29 src_stride_u: u32,
30 src_v: &[u8],
31 src_stride_v: u32,
32 _width: i32,
33 height: i32,
34) {
35 let height_abs = height.unsigned_abs();
36 let chroma_height = (height_abs + 1) / 2;
37 let min_y = (src_stride_y * height_abs) as usize;
38 let min_u = (src_stride_u * chroma_height) as usize;
39 let min_v = (src_stride_v * chroma_height) as usize;
40
41 assert!(src_y.len() >= min_y, "src_y isn't large enough");
42 assert!(src_u.len() >= min_u, "src_u isn't large enough");
43 assert!(src_v.len() >= min_v, "src_v isn't large enough");
44}
45
46fn nv12_assert_safety(
47 src_y: &[u8],
48 src_stride_y: u32,
49 src_uv: &[u8],
50 src_stride_uv: u32,
51 _width: i32,
52 height: i32,
53) {
54 let height_abs = height.unsigned_abs();
55 let chroma_height = (height_abs + 1) / 2;
56
57 let min_y = (src_stride_y * height_abs) as usize;
58 let min_uv = (src_stride_uv * chroma_height) as usize;
59
60 assert!(src_y.len() >= min_y, "src_y isn't large enough");
61 assert!(src_uv.len() >= min_uv, "src_uv isn't large enough");
62}
63
64fn i444_assert_safety(
65 src_y: &[u8],
66 src_stride_y: u32,
67 src_u: &[u8],
68 src_stride_u: u32,
69 src_v: &[u8],
70 src_stride_v: u32,
71 _width: i32,
72 height: i32,
73) {
74 let height_abs = height.unsigned_abs();
75 let min_y = (src_stride_y * height_abs) as usize;
76 let min_u = (src_stride_u * height_abs) as usize;
77 let min_v = (src_stride_v * height_abs) as usize;
78
79 assert!(src_y.len() >= min_y, "src_y isn't large enough");
80 assert!(src_u.len() >= min_u, "src_u isn't large enough");
81 assert!(src_v.len() >= min_v, "src_v isn't large enough");
82}
83
84fn i422_assert_safety(
85 src_y: &[u8],
86 src_stride_y: u32,
87 src_u: &[u8],
88 src_stride_u: u32,
89 src_v: &[u8],
90 src_stride_v: u32,
91 _width: i32,
92 height: i32,
93) {
94 let height_abs = height.unsigned_abs();
95 let min_y = (src_stride_y * height_abs) as usize;
96 let min_u = (src_stride_u * height_abs) as usize;
97 let min_v = (src_stride_v * height_abs) as usize;
98
99 assert!(src_y.len() >= min_y, "src_y isn't large enough");
100 assert!(src_u.len() >= min_u, "src_u isn't large enough");
101 assert!(src_v.len() >= min_v, "src_v isn't large enough");
102}
103
104fn i010_assert_safety(
105 src_y: &[u16],
106 src_stride_y: u32,
107 src_u: &[u16],
108 src_stride_u: u32,
109 src_v: &[u16],
110 src_stride_v: u32,
111 _width: i32,
112 height: i32,
113) {
114 let height_abs: u32 = height.unsigned_abs();
115 let chroma_height = height_abs / 2;
116 let min_y = (src_stride_y * height_abs) as usize / 2;
117 let min_u = (src_stride_u * chroma_height) as usize / 2;
118 let min_v = (src_stride_v * chroma_height) as usize / 2;
119
120 assert!(src_y.len() >= min_y, "src_y isn't large enough");
121 assert!(src_u.len() >= min_u, "src_u isn't large enough");
122 assert!(src_v.len() >= min_v, "src_v isn't large enough");
123}
124
125macro_rules! i420_to_rgba {
126 ($x:ident) => {
127 pub fn $x(
128 src_y: &[u8],
129 src_stride_y: u32,
130 src_u: &[u8],
131 src_stride_u: u32,
132 src_v: &[u8],
133 src_stride_v: u32,
134 dst: &mut [u8],
135 dst_stride: u32,
136 width: i32,
137 height: i32,
138 ) {
139 i420_assert_safety(
140 src_y,
141 src_stride_y,
142 src_u,
143 src_stride_u,
144 src_v,
145 src_stride_v,
146 width,
147 height,
148 );
149 argb_assert_safety(dst, dst_stride, width, height);
150
151 unsafe {
152 yuv_sys::ffi::$x(
153 src_y.as_ptr(),
154 src_stride_y as i32,
155 src_u.as_ptr(),
156 src_stride_u as i32,
157 src_v.as_ptr(),
158 src_stride_v as i32,
159 dst.as_mut_ptr(),
160 dst_stride as i32,
161 width,
162 height,
163 )
164 .unwrap();
165 }
166 }
167 };
168}
169
170macro_rules! rgba_to_i420 {
171 ($x:ident) => {
172 pub fn $x(
173 src_argb: &[u8],
174 src_stride_argb: u32,
175 dst_y: &mut [u8],
176 dst_stride_y: u32,
177 dst_u: &mut [u8],
178 dst_stride_u: u32,
179 dst_v: &mut [u8],
180 dst_stride_v: u32,
181 width: i32,
182 height: i32,
183 ) {
184 i420_assert_safety(
185 dst_y,
186 dst_stride_y,
187 dst_u,
188 dst_stride_u,
189 dst_v,
190 dst_stride_v,
191 width,
192 height,
193 );
194 argb_assert_safety(src_argb, src_stride_argb, width, height);
195
196 unsafe {
197 yuv_sys::ffi::$x(
198 src_argb.as_ptr(),
199 src_stride_argb as i32,
200 dst_y.as_mut_ptr(),
201 dst_stride_y as i32,
202 dst_u.as_mut_ptr(),
203 dst_stride_u as i32,
204 dst_v.as_mut_ptr(),
205 dst_stride_v as i32,
206 width,
207 height,
208 )
209 .unwrap();
210 }
211 }
212 };
213}
214
215pub fn argb_to_rgb24(
216 src_argb: &[u8],
217 src_stride_argb: u32,
218 dst_rgb24: &mut [u8],
219 dst_stride_rgb24: u32,
220 width: i32,
221 height: i32,
222) {
223 argb_assert_safety(src_argb, src_stride_argb, width, height);
224 argb_assert_safety(dst_rgb24, dst_stride_rgb24, width, height);
225
226 unsafe {
227 yuv_sys::ffi::argb_to_rgb24(
228 src_argb.as_ptr(),
229 src_stride_argb as i32,
230 dst_rgb24.as_mut_ptr(),
231 dst_stride_rgb24 as i32,
232 width,
233 height,
234 )
235 .unwrap();
236 }
237}
238
239// I420 <> RGB conversion
240rgba_to_i420!(argb_to_i420);
241rgba_to_i420!(abgr_to_i420);
242
243i420_to_rgba!(i420_to_argb);
244i420_to_rgba!(i420_to_bgra);
245i420_to_rgba!(i420_to_abgr);
246i420_to_rgba!(i420_to_rgba);
247
248pub fn i420_to_nv12(
249 src_y: &[u8],
250 src_stride_y: u32,
251 src_u: &[u8],
252 src_stride_u: u32,
253 src_v: &[u8],
254 src_stride_v: u32,
255 dst_y: &mut [u8],
256 dst_stride_y: u32,
257 dst_uv: &mut [u8],
258 dst_stride_uv: u32,
259 width: i32,
260 height: i32,
261) {
262 i420_assert_safety(
263 src_y,
264 src_stride_y,
265 src_u,
266 src_stride_u,
267 src_v,
268 src_stride_v,
269 width,
270 height,
271 );
272 nv12_assert_safety(dst_y, dst_stride_y, dst_uv, dst_stride_uv, width, height);
273
274 unsafe {
275 yuv_sys::ffi::i420_to_nv12(
276 src_y.as_ptr(),
277 src_stride_y as i32,
278 src_u.as_ptr(),
279 src_stride_u as i32,
280 src_v.as_ptr(),
281 src_stride_v as i32,
282 dst_y.as_mut_ptr(),
283 dst_stride_y as i32,
284 dst_uv.as_mut_ptr(),
285 dst_stride_uv as i32,
286 width,
287 height,
288 )
289 .unwrap();
290 }
291}
292
293pub fn nv12_to_i420(
294 src_y: &[u8],
295 src_stride_y: u32,
296 src_uv: &[u8],
297 src_stride_uv: u32,
298 dst_y: &mut [u8],
299 dst_stride_y: u32,
300 dst_u: &mut [u8],
301 dst_stride_u: u32,
302 dst_v: &mut [u8],
303 dst_stride_v: u32,
304 width: i32,
305 height: i32,
306) {
307 nv12_assert_safety(src_y, src_stride_y, src_uv, src_stride_uv, width, height);
308 i420_assert_safety(
309 dst_y,
310 dst_stride_y,
311 dst_u,
312 dst_stride_u,
313 dst_v,
314 dst_stride_v,
315 width,
316 height,
317 );
318
319 unsafe {
320 yuv_sys::ffi::nv12_to_i420(
321 src_y.as_ptr(),
322 src_stride_y as i32,
323 src_uv.as_ptr(),
324 src_stride_uv as i32,
325 dst_y.as_mut_ptr(),
326 dst_stride_y as i32,
327 dst_u.as_mut_ptr(),
328 dst_stride_u as i32,
329 dst_v.as_mut_ptr(),
330 dst_stride_v as i32,
331 width,
332 height,
333 )
334 .unwrap();
335 }
336}
337
338pub fn i444_to_i420(
339 src_y: &[u8],
340 src_stride_y: u32,
341 src_u: &[u8],
342 src_stride_u: u32,
343 src_v: &[u8],
344 src_stride_v: u32,
345 dst_y: &mut [u8],
346 dst_stride_y: u32,
347 dst_u: &mut [u8],
348 dst_stride_u: u32,
349 dst_v: &mut [u8],
350 dst_stride_v: u32,
351 width: i32,
352 height: i32,
353) {
354 i444_assert_safety(
355 src_y,
356 src_stride_y,
357 src_u,
358 src_stride_u,
359 src_v,
360 src_stride_v,
361 width,
362 height,
363 );
364 i420_assert_safety(
365 dst_y,
366 dst_stride_y,
367 dst_u,
368 dst_stride_u,
369 dst_v,
370 dst_stride_v,
371 width,
372 height,
373 );
374
375 unsafe {
376 yuv_sys::ffi::i444_to_i420(
377 src_y.as_ptr(),
378 src_stride_y as i32,
379 src_u.as_ptr(),
380 src_stride_u as i32,
381 src_v.as_ptr(),
382 src_stride_v as i32,
383 dst_y.as_mut_ptr(),
384 dst_stride_y as i32,
385 dst_u.as_mut_ptr(),
386 dst_stride_u as i32,
387 dst_v.as_mut_ptr(),
388 dst_stride_v as i32,
389 width,
390 height,
391 )
392 .unwrap();
393 }
394}
395
396pub fn i422_to_i420(
397 src_y: &[u8],
398 src_stride_y: u32,
399 src_u: &[u8],
400 src_stride_u: u32,
401 src_v: &[u8],
402 src_stride_v: u32,
403 dst_y: &mut [u8],
404 dst_stride_y: u32,
405 dst_u: &mut [u8],
406 dst_stride_u: u32,
407 dst_v: &mut [u8],
408 dst_stride_v: u32,
409 width: i32,
410 height: i32,
411) {
412 i422_assert_safety(
413 src_y,
414 src_stride_y,
415 src_u,
416 src_stride_u,
417 src_v,
418 src_stride_v,
419 width,
420 height,
421 );
422 i420_assert_safety(
423 dst_y,
424 dst_stride_y,
425 dst_u,
426 dst_stride_u,
427 dst_v,
428 dst_stride_v,
429 width,
430 height,
431 );
432
433 unsafe {
434 yuv_sys::ffi::i422_to_i420(
435 src_y.as_ptr(),
436 src_stride_y as i32,
437 src_u.as_ptr(),
438 src_stride_u as i32,
439 src_v.as_ptr(),
440 src_stride_v as i32,
441 dst_y.as_mut_ptr(),
442 dst_stride_y as i32,
443 dst_u.as_mut_ptr(),
444 dst_stride_u as i32,
445 dst_v.as_mut_ptr(),
446 dst_stride_v as i32,
447 width,
448 height,
449 )
450 .unwrap()
451 }
452}
453
454pub fn i010_to_i420(
455 src_y: &[u16],
456 src_stride_y: u32,
457 src_u: &[u16],
458 src_stride_u: u32,
459 src_v: &[u16],
460 src_stride_v: u32,
461 dst_y: &mut [u8],
462 dst_stride_y: u32,
463 dst_u: &mut [u8],
464 dst_stride_u: u32,
465 dst_v: &mut [u8],
466 dst_stride_v: u32,
467 width: i32,
468 height: i32,
469) {
470 i010_assert_safety(
471 src_y,
472 src_stride_y,
473 src_u,
474 src_stride_u,
475 src_v,
476 src_stride_v,
477 width,
478 height,
479 );
480 i420_assert_safety(
481 dst_y,
482 dst_stride_y,
483 dst_u,
484 dst_stride_u,
485 dst_v,
486 dst_stride_v,
487 width,
488 height,
489 );
490
491 unsafe {
492 yuv_sys::ffi::i010_to_i420(
493 src_y.as_ptr(),
494 src_stride_y as i32,
495 src_u.as_ptr(),
496 src_stride_u as i32,
497 src_v.as_ptr(),
498 src_stride_v as i32,
499 dst_y.as_mut_ptr(),
500 dst_stride_y as i32,
501 dst_u.as_mut_ptr(),
502 dst_stride_u as i32,
503 dst_v.as_mut_ptr(),
504 dst_stride_v as i32,
505 width,
506 height,
507 )
508 .unwrap()
509 }
510}
511
512pub fn nv12_to_argb(
513 src_y: &[u8],
514 src_stride_y: u32,
515 src_uv: &[u8],
516 src_stride_uv: u32,
517 dst_argb: &mut [u8],
518 dst_stride_argb: u32,
519 width: i32,
520 height: i32,
521) {
522 nv12_assert_safety(src_y, src_stride_y, src_uv, src_stride_uv, width, height);
523 argb_assert_safety(dst_argb, dst_stride_argb, width, height);
524
525 unsafe {
526 yuv_sys::ffi::nv12_to_argb(
527 src_y.as_ptr(),
528 src_stride_y as i32,
529 src_uv.as_ptr(),
530 src_stride_uv as i32,
531 dst_argb.as_mut_ptr(),
532 dst_stride_argb as i32,
533 width,
534 height,
535 )
536 .unwrap();
537 }
538}
539
540pub fn nv12_to_abgr(
541 src_y: &[u8],
542 src_stride_y: u32,
543 src_uv: &[u8],
544 src_stride_uv: u32,
545 dst_abgr: &mut [u8],
546 dst_stride_abgr: u32,
547 width: i32,
548 height: i32,
549) {
550 nv12_assert_safety(src_y, src_stride_y, src_uv, src_stride_uv, width, height);
551 argb_assert_safety(dst_abgr, dst_stride_abgr, width, height);
552
553 unsafe {
554 yuv_sys::ffi::nv12_to_abgr(
555 src_y.as_ptr(),
556 src_stride_y as i32,
557 src_uv.as_ptr(),
558 src_stride_uv as i32,
559 dst_abgr.as_mut_ptr(),
560 dst_stride_abgr as i32,
561 width,
562 height,
563 )
564 .unwrap();
565 }
566}
567
568pub fn i444_to_argb(
569 src_y: &[u8],
570 src_stride_y: u32,
571 src_u: &[u8],
572 src_stride_u: u32,
573 src_v: &[u8],
574 src_stride_v: u32,
575 dst_argb: &mut [u8],
576 dst_stride_argb: u32,
577 width: i32,
578 height: i32,
579) {
580 i444_assert_safety(
581 src_y,
582 src_stride_y,
583 src_u,
584 src_stride_u,
585 src_v,
586 src_stride_v,
587 width,
588 height,
589 );
590 argb_assert_safety(dst_argb, dst_stride_argb, width, height);
591
592 unsafe {
593 yuv_sys::ffi::i444_to_argb(
594 src_y.as_ptr(),
595 src_stride_y as i32,
596 src_u.as_ptr(),
597 src_stride_u as i32,
598 src_v.as_ptr(),
599 src_stride_v as i32,
600 dst_argb.as_mut_ptr(),
601 dst_stride_argb as i32,
602 width,
603 height,
604 )
605 .unwrap();
606 }
607}
608
609pub fn i444_to_abgr(
610 src_y: &[u8],
611 src_stride_y: u32,
612 src_u: &[u8],
613 src_stride_u: u32,
614 src_v: &[u8],
615 src_stride_v: u32,
616 dst_abgr: &mut [u8],
617 dst_stride_abgr: u32,
618 width: i32,
619 height: i32,
620) {
621 i444_assert_safety(
622 src_y,
623 src_stride_y,
624 src_u,
625 src_stride_u,
626 src_v,
627 src_stride_v,
628 width,
629 height,
630 );
631 argb_assert_safety(dst_abgr, dst_stride_abgr, width, height);
632
633 unsafe {
634 yuv_sys::ffi::i444_to_abgr(
635 src_y.as_ptr(),
636 src_stride_y as i32,
637 src_u.as_ptr(),
638 src_stride_u as i32,
639 src_v.as_ptr(),
640 src_stride_v as i32,
641 dst_abgr.as_mut_ptr(),
642 dst_stride_abgr as i32,
643 width,
644 height,
645 )
646 .unwrap()
647 }
648}
649
650pub fn i422_to_argb(
651 src_y: &[u8],
652 src_stride_y: u32,
653 src_u: &[u8],
654 src_stride_u: u32,
655 src_v: &[u8],
656 src_stride_v: u32,
657 dst_argb: &mut [u8],
658 dst_stride_argb: u32,
659 width: i32,
660 height: i32,
661) {
662 i422_assert_safety(
663 src_y,
664 src_stride_y,
665 src_u,
666 src_stride_u,
667 src_v,
668 src_stride_v,
669 width,
670 height,
671 );
672 argb_assert_safety(dst_argb, dst_stride_argb, width, height);
673
674 unsafe {
675 yuv_sys::ffi::i422_to_argb(
676 src_y.as_ptr(),
677 src_stride_y as i32,
678 src_u.as_ptr(),
679 src_stride_u as i32,
680 src_v.as_ptr(),
681 src_stride_v as i32,
682 dst_argb.as_mut_ptr(),
683 dst_stride_argb as i32,
684 width,
685 height,
686 )
687 .unwrap();
688 }
689}
690
691pub fn i422_to_abgr(
692 src_y: &[u8],
693 src_stride_y: u32,
694 src_u: &[u8],
695 src_stride_u: u32,
696 src_v: &[u8],
697 src_stride_v: u32,
698 dst_abgr: &mut [u8],
699 dst_stride_abgr: u32,
700 width: i32,
701 height: i32,
702) {
703 i422_assert_safety(
704 src_y,
705 src_stride_y,
706 src_u,
707 src_stride_u,
708 src_v,
709 src_stride_v,
710 width,
711 height,
712 );
713 argb_assert_safety(dst_abgr, dst_stride_abgr, width, height);
714
715 unsafe {
716 yuv_sys::ffi::i422_to_abgr(
717 src_y.as_ptr(),
718 src_stride_y as i32,
719 src_u.as_ptr(),
720 src_stride_u as i32,
721 src_v.as_ptr(),
722 src_stride_v as i32,
723 dst_abgr.as_mut_ptr(),
724 dst_stride_abgr as i32,
725 width,
726 height,
727 )
728 .unwrap()
729 }
730}
731
732pub fn i010_to_argb(
733 src_y: &[u16],
734 src_stride_y: u32,
735 src_u: &[u16],
736 src_stride_u: u32,
737 src_v: &[u16],
738 src_stride_v: u32,
739 dst_argb: &mut [u8],
740 dst_stride_argb: u32,
741 width: i32,
742 height: i32,
743) {
744 i010_assert_safety(
745 src_y,
746 src_stride_y,
747 src_u,
748 src_stride_u,
749 src_v,
750 src_stride_v,
751 width,
752 height,
753 );
754 argb_assert_safety(dst_argb, dst_stride_argb, width, height);
755
756 unsafe {
757 yuv_sys::ffi::i010_to_argb(
758 src_y.as_ptr(),
759 src_stride_y as i32,
760 src_u.as_ptr(),
761 src_stride_u as i32,
762 src_v.as_ptr(),
763 src_stride_v as i32,
764 dst_argb.as_mut_ptr(),
765 dst_stride_argb as i32,
766 width,
767 height,
768 )
769 .unwrap()
770 }
771}
772
773pub fn i010_to_abgr(
774 src_y: &[u16],
775 src_stride_y: u32,
776 src_u: &[u16],
777 src_stride_u: u32,
778 src_v: &[u16],
779 src_stride_v: u32,
780 dst_abgr: &mut [u8],
781 dst_stride_abgr: u32,
782 width: i32,
783 height: i32,
784) {
785 i010_assert_safety(
786 src_y,
787 src_stride_y,
788 src_u,
789 src_stride_u,
790 src_v,
791 src_stride_v,
792 width,
793 height,
794 );
795 argb_assert_safety(dst_abgr, dst_stride_abgr, width, height);
796
797 unsafe {
798 yuv_sys::ffi::i010_to_abgr(
799 src_y.as_ptr(),
800 src_stride_y as i32,
801 src_u.as_ptr(),
802 src_stride_u as i32,
803 src_v.as_ptr(),
804 src_stride_v as i32,
805 dst_abgr.as_mut_ptr(),
806 dst_stride_abgr as i32,
807 width,
808 height,
809 )
810 .unwrap()
811 }
812}
813
814pub fn abgr_to_nv12(
815 src_abgr: &[u8],
816 src_stride_abgr: u32,
817 dst_y: &mut [u8],
818 dst_stride_y: u32,
819 dst_uv: &mut [u8],
820 dst_stride_uv: u32,
821 width: i32,
822 height: i32,
823) {
824 argb_assert_safety(src_abgr, src_stride_abgr, width, height);
825 nv12_assert_safety(dst_y, dst_stride_y, dst_uv, dst_stride_uv, width, height);
826
827 unsafe {
828 yuv_sys::ffi::abgr_to_nv12(
829 src_abgr.as_ptr(),
830 src_stride_abgr as i32,
831 dst_y.as_mut_ptr(),
832 dst_stride_y as i32,
833 dst_uv.as_mut_ptr(),
834 dst_stride_uv as i32,
835 width,
836 height,
837 )
838 .unwrap()
839 }
840}
841
842pub fn argb_to_nv12(
843 src_argb: &[u8],
844 src_stride_argb: u32,
845 dst_y: &mut [u8],
846 dst_stride_y: u32,
847 dst_uv: &mut [u8],
848 dst_stride_uv: u32,
849 width: i32,
850 height: i32,
851) {
852 argb_assert_safety(src_argb, src_stride_argb, width, height);
853 nv12_assert_safety(dst_y, dst_stride_y, dst_uv, dst_stride_uv, width, height);
854
855 unsafe {
856 yuv_sys::ffi::argb_to_nv12(
857 src_argb.as_ptr(),
858 src_stride_argb as i32,
859 dst_y.as_mut_ptr(),
860 dst_stride_y as i32,
861 dst_uv.as_mut_ptr(),
862 dst_stride_uv as i32,
863 width,
864 height,
865 )
866 .unwrap()
867 }
868}
vendor/libwebrtc/src/peer_connection.rs added +346 −0
@@ -0,0 +1,346 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::fmt::Debug;
16
17 use crate::{
18 data_channel::{DataChannel, DataChannelInit},
19 ice_candidate::IceCandidate,
20 imp::peer_connection as imp_pc,
21 media_stream::MediaStream,
22 media_stream_track::MediaStreamTrack,
23 peer_connection_factory::RtcConfiguration,
24 rtp_receiver::RtpReceiver,
25 rtp_sender::RtpSender,
26 rtp_transceiver::{RtpTransceiver, RtpTransceiverInit},
27 session_description::SessionDescription,
28 stats::RtcStats,
29 MediaType, RtcError,
30 };
31
32 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
33 pub enum PeerConnectionState {
34 New,
35 Connecting,
36 Connected,
37 Disconnected,
38 Failed,
39 Closed,
40 }
41
42 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
43 pub enum IceConnectionState {
44 New,
45 Checking,
46 Connected,
47 Completed,
48 Failed,
49 Disconnected,
50 Closed,
51 Max,
52 }
53
54 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
55 pub enum IceGatheringState {
56 New,
57 Gathering,
58 Complete,
59 }
60
61 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
62 pub enum SignalingState {
63 Stable,
64 HaveLocalOffer,
65 HaveLocalPrAnswer,
66 HaveRemoteOffer,
67 HaveRemotePrAnswer,
68 Closed,
69 }
70
71 #[derive(Debug, Clone, Default)]
72 pub struct OfferOptions {
73 pub ice_restart: bool,
74 pub offer_to_receive_audio: bool,
75 pub offer_to_receive_video: bool,
76 }
77
78 #[derive(Debug, Clone, Default)]
79 pub struct AnswerOptions {}
80
81 #[derive(Debug, Clone)]
82 pub struct IceCandidateError {
83 pub address: String,
84 pub port: i32,
85 pub url: String,
86 pub error_code: i32,
87 pub error_text: String,
88 }
89
90 #[derive(Debug, Clone)]
91 pub struct TrackEvent {
92 pub receiver: RtpReceiver,
93 pub streams: Vec<MediaStream>,
94 pub track: MediaStreamTrack,
95 pub transceiver: RtpTransceiver,
96 }
97
98 pub type OnConnectionChange = Box<dyn FnMut(PeerConnectionState) + Send + Sync>;
99 pub type OnDataChannel = Box<dyn FnMut(DataChannel) + Send + Sync>;
100 pub type OnIceCandidate = Box<dyn FnMut(IceCandidate) + Send + Sync>;
101 pub type OnIceCandidateError = Box<dyn FnMut(IceCandidateError) + Send + Sync>;
102 pub type OnIceConnectionChange = Box<dyn FnMut(IceConnectionState) + Send + Sync>;
103 pub type OnIceGatheringChange = Box<dyn FnMut(IceGatheringState) + Send + Sync>;
104 pub type OnNegotiationNeeded = Box<dyn FnMut(u32) + Send + Sync>;
105 pub type OnSignalingChange = Box<dyn FnMut(SignalingState) + Send + Sync>;
106 pub type OnTrack = Box<dyn FnMut(TrackEvent) + Send + Sync>;
107
108 #[derive(Clone)]
109 pub struct PeerConnection {
110 pub(crate) handle: imp_pc::PeerConnection,
111 }
112
113 impl PeerConnection {
114 pub fn set_configuration(&self, config: RtcConfiguration) -> Result<(), RtcError> {
115 self.handle.set_configuration(config)
116 }
117
118 pub async fn create_offer(
119 &self,
120 options: OfferOptions,
121 ) -> Result<SessionDescription, RtcError> {
122 self.handle.create_offer(options).await
123 }
124
125 pub async fn create_answer(
126 &self,
127 options: AnswerOptions,
128 ) -> Result<SessionDescription, RtcError> {
129 self.handle.create_answer(options).await
130 }
131
132 pub async fn set_local_description(&self, desc: SessionDescription) -> Result<(), RtcError> {
133 self.handle.set_local_description(desc).await
134 }
135
136 pub async fn set_remote_description(&self, desc: SessionDescription) -> Result<(), RtcError> {
137 self.handle.set_remote_description(desc).await
138 }
139
140 pub async fn add_ice_candidate(&self, candidate: IceCandidate) -> Result<(), RtcError> {
141 self.handle.add_ice_candidate(candidate).await
142 }
143
144 pub fn create_data_channel(
145 &self,
146 label: &str,
147 init: DataChannelInit,
148 ) -> Result<DataChannel, RtcError> {
149 self.handle.create_data_channel(label, init)
150 }
151
152 pub fn add_track<T: AsRef<str>>(
153 &self,
154 track: MediaStreamTrack,
155 streams_ids: &[T],
156 ) -> Result<RtpSender, RtcError> {
157 self.handle.add_track(track, streams_ids)
158 }
159
160 pub fn remove_track(&self, sender: RtpSender) -> Result<(), RtcError> {
161 self.handle.remove_track(sender)
162 }
163
164 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
165 self.handle.get_stats().await
166 }
167
168 pub fn add_transceiver(
169 &self,
170 track: MediaStreamTrack,
171 init: RtpTransceiverInit,
172 ) -> Result<RtpTransceiver, RtcError> {
173 self.handle.add_transceiver(track, init)
174 }
175
176 pub fn add_transceiver_for_media(
177 &self,
178 media_type: MediaType,
179 init: RtpTransceiverInit,
180 ) -> Result<RtpTransceiver, RtcError> {
181 self.handle.add_transceiver_for_media(media_type, init)
182 }
183
184 pub fn close(&self) {
185 self.handle.close()
186 }
187
188 pub fn restart_ice(&self) {
189 self.handle.restart_ice()
190 }
191
192 pub fn connection_state(&self) -> PeerConnectionState {
193 self.handle.connection_state()
194 }
195
196 pub fn ice_connection_state(&self) -> IceConnectionState {
197 self.handle.ice_connection_state()
198 }
199
200 pub fn ice_gathering_state(&self) -> IceGatheringState {
201 self.handle.ice_gathering_state()
202 }
203
204 pub fn signaling_state(&self) -> SignalingState {
205 self.handle.signaling_state()
206 }
207
208 pub fn current_local_description(&self) -> Option<SessionDescription> {
209 self.handle.current_local_description()
210 }
211
212 pub fn current_remote_description(&self) -> Option<SessionDescription> {
213 self.handle.current_remote_description()
214 }
215
216 pub fn senders(&self) -> Vec<RtpSender> {
217 self.handle.senders()
218 }
219
220 pub fn receivers(&self) -> Vec<RtpReceiver> {
221 self.handle.receivers()
222 }
223
224 pub fn transceivers(&self) -> Vec<RtpTransceiver> {
225 self.handle.transceivers()
226 }
227
228 pub fn on_connection_state_change(&self, f: Option<OnConnectionChange>) {
229 self.handle.on_connection_state_change(f)
230 }
231
232 pub fn on_data_channel(&self, f: Option<OnDataChannel>) {
233 self.handle.on_data_channel(f)
234 }
235
236 pub fn on_ice_candidate(&self, f: Option<OnIceCandidate>) {
237 self.handle.on_ice_candidate(f)
238 }
239
240 pub fn on_ice_candidate_error(&self, f: Option<OnIceCandidateError>) {
241 self.handle.on_ice_candidate_error(f)
242 }
243
244 pub fn on_ice_connection_state_change(&self, f: Option<OnIceConnectionChange>) {
245 self.handle.on_ice_connection_state_change(f)
246 }
247
248 pub fn on_ice_gathering_state_change(&self, f: Option<OnIceGatheringChange>) {
249 self.handle.on_ice_gathering_state_change(f)
250 }
251
252 pub fn on_negotiation_needed(&self, f: Option<OnNegotiationNeeded>) {
253 self.handle.on_negotiation_needed(f)
254 }
255
256 pub fn on_signaling_state_change(&self, f: Option<OnSignalingChange>) {
257 self.handle.on_signaling_state_change(f)
258 }
259
260 pub fn on_track(&self, f: Option<OnTrack>) {
261 self.handle.on_track(f)
262 }
263 }
264
265 impl Debug for PeerConnection {
266 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267 f.debug_struct("PeerConnection")
268 .field("state", &self.connection_state())
269 .field("ice_state", &self.ice_connection_state())
270 .finish()
271 }
272 }
273
274 #[cfg(test)]
275 mod tests {
276 use log::trace;
277 use tokio::sync::mpsc;
278
279 use crate::{peer_connection::*, peer_connection_factory::*};
280
281 #[tokio::test]
282 async fn create_pc() {
283 let _ = env_logger::builder().is_test(true).try_init();
284
285 let factory = PeerConnectionFactory::default();
286 let config = RtcConfiguration {
287 ice_servers: vec![IceServer {
288 urls: vec!["stun:stun1.l.google.com:19302".to_string()],
289 username: "".into(),
290 password: "".into(),
291 }],
292 continual_gathering_policy: ContinualGatheringPolicy::GatherOnce,
293 ice_transport_type: IceTransportsType::All,
294 enable_sctp_snap: false,
295 };
296
297 let bob = factory.create_peer_connection(config.clone()).unwrap();
298 let alice = factory.create_peer_connection(config.clone()).unwrap();
299
300 let (bob_ice_tx, mut bob_ice_rx) = mpsc::unbounded_channel::<IceCandidate>();
301 let (alice_ice_tx, mut alice_ice_rx) = mpsc::unbounded_channel::<IceCandidate>();
302 let (alice_dc_tx, mut alice_dc_rx) = mpsc::unbounded_channel::<DataChannel>();
303
304 bob.on_ice_candidate(Some(Box::new(move |candidate| {
305 bob_ice_tx.send(candidate).unwrap();
306 })));
307
308 alice.on_ice_candidate(Some(Box::new(move |candidate| {
309 alice_ice_tx.send(candidate).unwrap();
310 })));
311
312 alice.on_data_channel(Some(Box::new(move |dc| {
313 alice_dc_tx.send(dc).unwrap();
314 })));
315
316 let bob_dc = bob.create_data_channel("test_dc", DataChannelInit::default()).unwrap();
317
318 let offer = bob.create_offer(OfferOptions::default()).await.unwrap();
319 trace!("Bob offer: {:?}", offer);
320 bob.set_local_description(offer.clone()).await.unwrap();
321 alice.set_remote_description(offer).await.unwrap();
322
323 let answer = alice.create_answer(AnswerOptions::default()).await.unwrap();
324 trace!("Alice answer: {:?}", answer);
325 alice.set_local_description(answer.clone()).await.unwrap();
326 bob.set_remote_description(answer).await.unwrap();
327
328 let bob_ice = bob_ice_rx.recv().await.unwrap();
329 let alice_ice = alice_ice_rx.recv().await.unwrap();
330
331 bob.add_ice_candidate(alice_ice).await.unwrap();
332 alice.add_ice_candidate(bob_ice).await.unwrap();
333
334 let (data_tx, mut data_rx) = mpsc::unbounded_channel::<String>();
335 let alice_dc = alice_dc_rx.recv().await.unwrap();
336 alice_dc.on_message(Some(Box::new(move |buffer| {
337 data_tx.send(String::from_utf8_lossy(buffer.data).to_string()).unwrap();
338 })));
339
340 bob_dc.send(b"This is a test", true).unwrap();
341 assert_eq!(data_rx.recv().await.unwrap(), "This is a test");
342
343 alice.close();
344 bob.close();
345 }
346 }
@@ -0,0 +1,346 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use crate::{
18 data_channel::{DataChannel, DataChannelInit},
19 ice_candidate::IceCandidate,
20 imp::peer_connection as imp_pc,
21 media_stream::MediaStream,
22 media_stream_track::MediaStreamTrack,
23 peer_connection_factory::RtcConfiguration,
24 rtp_receiver::RtpReceiver,
25 rtp_sender::RtpSender,
26 rtp_transceiver::{RtpTransceiver, RtpTransceiverInit},
27 session_description::SessionDescription,
28 stats::RtcStats,
29 MediaType, RtcError,
30};
31
32#[derive(Debug, Copy, Clone, PartialEq, Eq)]
33pub enum PeerConnectionState {
34 New,
35 Connecting,
36 Connected,
37 Disconnected,
38 Failed,
39 Closed,
40}
41
42#[derive(Debug, Copy, Clone, PartialEq, Eq)]
43pub enum IceConnectionState {
44 New,
45 Checking,
46 Connected,
47 Completed,
48 Failed,
49 Disconnected,
50 Closed,
51 Max,
52}
53
54#[derive(Debug, Copy, Clone, PartialEq, Eq)]
55pub enum IceGatheringState {
56 New,
57 Gathering,
58 Complete,
59}
60
61#[derive(Debug, Copy, Clone, PartialEq, Eq)]
62pub enum SignalingState {
63 Stable,
64 HaveLocalOffer,
65 HaveLocalPrAnswer,
66 HaveRemoteOffer,
67 HaveRemotePrAnswer,
68 Closed,
69}
70
71#[derive(Debug, Clone, Default)]
72pub struct OfferOptions {
73 pub ice_restart: bool,
74 pub offer_to_receive_audio: bool,
75 pub offer_to_receive_video: bool,
76}
77
78#[derive(Debug, Clone, Default)]
79pub struct AnswerOptions {}
80
81#[derive(Debug, Clone)]
82pub struct IceCandidateError {
83 pub address: String,
84 pub port: i32,
85 pub url: String,
86 pub error_code: i32,
87 pub error_text: String,
88}
89
90#[derive(Debug, Clone)]
91pub struct TrackEvent {
92 pub receiver: RtpReceiver,
93 pub streams: Vec<MediaStream>,
94 pub track: MediaStreamTrack,
95 pub transceiver: RtpTransceiver,
96}
97
98pub type OnConnectionChange = Box<dyn FnMut(PeerConnectionState) + Send + Sync>;
99pub type OnDataChannel = Box<dyn FnMut(DataChannel) + Send + Sync>;
100pub type OnIceCandidate = Box<dyn FnMut(IceCandidate) + Send + Sync>;
101pub type OnIceCandidateError = Box<dyn FnMut(IceCandidateError) + Send + Sync>;
102pub type OnIceConnectionChange = Box<dyn FnMut(IceConnectionState) + Send + Sync>;
103pub type OnIceGatheringChange = Box<dyn FnMut(IceGatheringState) + Send + Sync>;
104pub type OnNegotiationNeeded = Box<dyn FnMut(u32) + Send + Sync>;
105pub type OnSignalingChange = Box<dyn FnMut(SignalingState) + Send + Sync>;
106pub type OnTrack = Box<dyn FnMut(TrackEvent) + Send + Sync>;
107
108#[derive(Clone)]
109pub struct PeerConnection {
110 pub(crate) handle: imp_pc::PeerConnection,
111}
112
113impl PeerConnection {
114 pub fn set_configuration(&self, config: RtcConfiguration) -> Result<(), RtcError> {
115 self.handle.set_configuration(config)
116 }
117
118 pub async fn create_offer(
119 &self,
120 options: OfferOptions,
121 ) -> Result<SessionDescription, RtcError> {
122 self.handle.create_offer(options).await
123 }
124
125 pub async fn create_answer(
126 &self,
127 options: AnswerOptions,
128 ) -> Result<SessionDescription, RtcError> {
129 self.handle.create_answer(options).await
130 }
131
132 pub async fn set_local_description(&self, desc: SessionDescription) -> Result<(), RtcError> {
133 self.handle.set_local_description(desc).await
134 }
135
136 pub async fn set_remote_description(&self, desc: SessionDescription) -> Result<(), RtcError> {
137 self.handle.set_remote_description(desc).await
138 }
139
140 pub async fn add_ice_candidate(&self, candidate: IceCandidate) -> Result<(), RtcError> {
141 self.handle.add_ice_candidate(candidate).await
142 }
143
144 pub fn create_data_channel(
145 &self,
146 label: &str,
147 init: DataChannelInit,
148 ) -> Result<DataChannel, RtcError> {
149 self.handle.create_data_channel(label, init)
150 }
151
152 pub fn add_track<T: AsRef<str>>(
153 &self,
154 track: MediaStreamTrack,
155 streams_ids: &[T],
156 ) -> Result<RtpSender, RtcError> {
157 self.handle.add_track(track, streams_ids)
158 }
159
160 pub fn remove_track(&self, sender: RtpSender) -> Result<(), RtcError> {
161 self.handle.remove_track(sender)
162 }
163
164 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
165 self.handle.get_stats().await
166 }
167
168 pub fn add_transceiver(
169 &self,
170 track: MediaStreamTrack,
171 init: RtpTransceiverInit,
172 ) -> Result<RtpTransceiver, RtcError> {
173 self.handle.add_transceiver(track, init)
174 }
175
176 pub fn add_transceiver_for_media(
177 &self,
178 media_type: MediaType,
179 init: RtpTransceiverInit,
180 ) -> Result<RtpTransceiver, RtcError> {
181 self.handle.add_transceiver_for_media(media_type, init)
182 }
183
184 pub fn close(&self) {
185 self.handle.close()
186 }
187
188 pub fn restart_ice(&self) {
189 self.handle.restart_ice()
190 }
191
192 pub fn connection_state(&self) -> PeerConnectionState {
193 self.handle.connection_state()
194 }
195
196 pub fn ice_connection_state(&self) -> IceConnectionState {
197 self.handle.ice_connection_state()
198 }
199
200 pub fn ice_gathering_state(&self) -> IceGatheringState {
201 self.handle.ice_gathering_state()
202 }
203
204 pub fn signaling_state(&self) -> SignalingState {
205 self.handle.signaling_state()
206 }
207
208 pub fn current_local_description(&self) -> Option<SessionDescription> {
209 self.handle.current_local_description()
210 }
211
212 pub fn current_remote_description(&self) -> Option<SessionDescription> {
213 self.handle.current_remote_description()
214 }
215
216 pub fn senders(&self) -> Vec<RtpSender> {
217 self.handle.senders()
218 }
219
220 pub fn receivers(&self) -> Vec<RtpReceiver> {
221 self.handle.receivers()
222 }
223
224 pub fn transceivers(&self) -> Vec<RtpTransceiver> {
225 self.handle.transceivers()
226 }
227
228 pub fn on_connection_state_change(&self, f: Option<OnConnectionChange>) {
229 self.handle.on_connection_state_change(f)
230 }
231
232 pub fn on_data_channel(&self, f: Option<OnDataChannel>) {
233 self.handle.on_data_channel(f)
234 }
235
236 pub fn on_ice_candidate(&self, f: Option<OnIceCandidate>) {
237 self.handle.on_ice_candidate(f)
238 }
239
240 pub fn on_ice_candidate_error(&self, f: Option<OnIceCandidateError>) {
241 self.handle.on_ice_candidate_error(f)
242 }
243
244 pub fn on_ice_connection_state_change(&self, f: Option<OnIceConnectionChange>) {
245 self.handle.on_ice_connection_state_change(f)
246 }
247
248 pub fn on_ice_gathering_state_change(&self, f: Option<OnIceGatheringChange>) {
249 self.handle.on_ice_gathering_state_change(f)
250 }
251
252 pub fn on_negotiation_needed(&self, f: Option<OnNegotiationNeeded>) {
253 self.handle.on_negotiation_needed(f)
254 }
255
256 pub fn on_signaling_state_change(&self, f: Option<OnSignalingChange>) {
257 self.handle.on_signaling_state_change(f)
258 }
259
260 pub fn on_track(&self, f: Option<OnTrack>) {
261 self.handle.on_track(f)
262 }
263}
264
265impl Debug for PeerConnection {
266 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267 f.debug_struct("PeerConnection")
268 .field("state", &self.connection_state())
269 .field("ice_state", &self.ice_connection_state())
270 .finish()
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 use log::trace;
277 use tokio::sync::mpsc;
278
279 use crate::{peer_connection::*, peer_connection_factory::*};
280
281 #[tokio::test]
282 async fn create_pc() {
283 let _ = env_logger::builder().is_test(true).try_init();
284
285 let factory = PeerConnectionFactory::default();
286 let config = RtcConfiguration {
287 ice_servers: vec![IceServer {
288 urls: vec!["stun:stun1.l.google.com:19302".to_string()],
289 username: "".into(),
290 password: "".into(),
291 }],
292 continual_gathering_policy: ContinualGatheringPolicy::GatherOnce,
293 ice_transport_type: IceTransportsType::All,
294 enable_sctp_snap: false,
295 };
296
297 let bob = factory.create_peer_connection(config.clone()).unwrap();
298 let alice = factory.create_peer_connection(config.clone()).unwrap();
299
300 let (bob_ice_tx, mut bob_ice_rx) = mpsc::unbounded_channel::<IceCandidate>();
301 let (alice_ice_tx, mut alice_ice_rx) = mpsc::unbounded_channel::<IceCandidate>();
302 let (alice_dc_tx, mut alice_dc_rx) = mpsc::unbounded_channel::<DataChannel>();
303
304 bob.on_ice_candidate(Some(Box::new(move |candidate| {
305 bob_ice_tx.send(candidate).unwrap();
306 })));
307
308 alice.on_ice_candidate(Some(Box::new(move |candidate| {
309 alice_ice_tx.send(candidate).unwrap();
310 })));
311
312 alice.on_data_channel(Some(Box::new(move |dc| {
313 alice_dc_tx.send(dc).unwrap();
314 })));
315
316 let bob_dc = bob.create_data_channel("test_dc", DataChannelInit::default()).unwrap();
317
318 let offer = bob.create_offer(OfferOptions::default()).await.unwrap();
319 trace!("Bob offer: {:?}", offer);
320 bob.set_local_description(offer.clone()).await.unwrap();
321 alice.set_remote_description(offer).await.unwrap();
322
323 let answer = alice.create_answer(AnswerOptions::default()).await.unwrap();
324 trace!("Alice answer: {:?}", answer);
325 alice.set_local_description(answer.clone()).await.unwrap();
326 bob.set_remote_description(answer).await.unwrap();
327
328 let bob_ice = bob_ice_rx.recv().await.unwrap();
329 let alice_ice = alice_ice_rx.recv().await.unwrap();
330
331 bob.add_ice_candidate(alice_ice).await.unwrap();
332 alice.add_ice_candidate(bob_ice).await.unwrap();
333
334 let (data_tx, mut data_rx) = mpsc::unbounded_channel::<String>();
335 let alice_dc = alice_dc_rx.recv().await.unwrap();
336 alice_dc.on_message(Some(Box::new(move |buffer| {
337 data_tx.send(String::from_utf8_lossy(buffer.data).to_string()).unwrap();
338 })));
339
340 bob_dc.send(b"This is a test", true).unwrap();
341 assert_eq!(data_rx.recv().await.unwrap(), "This is a test");
342
343 alice.close();
344 bob.close();
345 }
346}
vendor/libwebrtc/src/peer_connection_factory.rs added +349 −0
@@ -0,0 +1,349 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::fmt::Debug;
16
17 use crate::{
18 imp::peer_connection_factory as imp_pcf, peer_connection::PeerConnection,
19 rtp_parameters::RtpCapabilities, MediaType, RtcError,
20 };
21
22 #[derive(Debug, Clone)]
23 pub struct IceServer {
24 pub urls: Vec<String>,
25 pub username: String,
26 pub password: String,
27 }
28
29 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
30 pub enum ContinualGatheringPolicy {
31 GatherOnce,
32 GatherContinually,
33 }
34
35 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
36 pub enum IceTransportsType {
37 Relay,
38 NoHost,
39 All,
40 }
41
42 /// Configuration for a [`PeerConnection`].
43 ///
44 /// This type is `#[non_exhaustive]`: construct it from [`RtcConfiguration::default`]
45 /// and set the fields you need, e.g.
46 /// ```
47 /// # use libwebrtc::peer_connection_factory::{IceTransportsType, RtcConfiguration};
48 /// let mut cfg = RtcConfiguration::default();
49 /// cfg.ice_transport_type = IceTransportsType::Relay;
50 /// ```
51 /// New fields may be added in future releases without a breaking change.
52 #[derive(Debug, Clone)]
53 #[non_exhaustive]
54 pub struct RtcConfiguration {
55 pub ice_servers: Vec<IceServer>,
56 pub continual_gathering_policy: ContinualGatheringPolicy,
57 pub ice_transport_type: IceTransportsType,
58 /// WARP: enable SNAP (SCTP-INIT-in-SDP). Maps to the immutable
59 /// `enable_sctp_snap` RTCConfiguration field, so it must be set the same at
60 /// PeerConnection creation and every set_configuration.
61 pub enable_sctp_snap: bool,
62 }
63
64 impl Default for RtcConfiguration {
65 fn default() -> Self {
66 Self {
67 ice_servers: vec![],
68 continual_gathering_policy: ContinualGatheringPolicy::GatherContinually,
69 ice_transport_type: IceTransportsType::All,
70 enable_sctp_snap: false,
71 }
72 }
73 }
74
75 #[derive(Clone, Default)]
76 pub struct PeerConnectionFactory {
77 pub(crate) handle: imp_pcf::PeerConnectionFactory,
78 }
79
80 impl Debug for PeerConnectionFactory {
81 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
82 f.debug_struct("PeerConnectionFactory").finish()
83 }
84 }
85
86 impl PeerConnectionFactory {
87 /// Creates a native peer connection factory that renders received video as soon as possible.
88 #[cfg(not(target_arch = "wasm32"))]
89 pub fn with_zero_playout_delay() -> Self {
90 Self { handle: imp_pcf::PeerConnectionFactory::with_zero_playout_delay() }
91 }
92
93 /// Creates a native peer connection factory with the given runtime options.
94 /// `zero_playout_delay` and `enable_warp` (SPED + SNAP) are independent and
95 /// may be combined.
96 #[cfg(not(target_arch = "wasm32"))]
97 pub fn with_options(zero_playout_delay: bool, enable_warp: bool) -> Self {
98 Self {
99 handle: imp_pcf::PeerConnectionFactory::with_options(zero_playout_delay, enable_warp),
100 }
101 }
102
103 pub fn create_peer_connection(
104 &self,
105 config: RtcConfiguration,
106 ) -> Result<PeerConnection, RtcError> {
107 self.handle.create_peer_connection(config)
108 }
109
110 pub fn get_rtp_sender_capabilities(&self, media_type: MediaType) -> RtpCapabilities {
111 self.handle.get_rtp_sender_capabilities(media_type)
112 }
113
114 pub fn get_rtp_receiver_capabilities(&self, media_type: MediaType) -> RtpCapabilities {
115 self.handle.get_rtp_receiver_capabilities(media_type)
116 }
117 }
118
119 #[cfg(all(test, not(target_arch = "wasm32")))]
120 mod tests {
121 use super::PeerConnectionFactory;
122
123 #[test]
124 fn zero_playout_delay_factory_uses_force_playout_delay_field_trial() {
125 let default_factory = PeerConnectionFactory::default();
126 assert!(!default_factory.handle.zero_playout_delay_enabled());
127 drop(default_factory);
128
129 let low_latency_factory = PeerConnectionFactory::with_zero_playout_delay();
130 assert!(low_latency_factory.handle.zero_playout_delay_enabled());
131 }
132 }
133
134 pub mod native {
135 use super::PeerConnectionFactory;
136 use crate::{
137 audio_source::native::NativeAudioSource, audio_track::RtcAudioTrack,
138 video_source::native::NativeVideoSource, video_track::RtcVideoTrack,
139 };
140
141 pub trait PeerConnectionFactoryExt {
142 fn create_video_track(&self, label: &str, source: NativeVideoSource) -> RtcVideoTrack;
143 fn create_audio_track(&self, label: &str, source: NativeAudioSource) -> RtcAudioTrack;
144
145 /// Create an audio track that uses the Platform ADM for capture.
146 /// The track will capture audio from the selected recording device.
147 fn create_device_audio_track(&self, label: &str) -> RtcAudioTrack;
148
149 // Device enumeration
150 fn playout_devices(&self) -> i16;
151 fn recording_devices(&self) -> i16;
152 fn playout_device_name(&self, index: u16) -> String;
153 fn recording_device_name(&self, index: u16) -> String;
154 /// Get device GUID (platform-specific unique identifier, stable across hot-plug)
155 fn playout_device_guid(&self, index: u16) -> String;
156 fn recording_device_guid(&self, index: u16) -> String;
157
158 // Device selection by index
159 fn set_playout_device(&self, index: u16) -> bool;
160 fn set_recording_device(&self, index: u16) -> bool;
161 /// Device selection by GUID (preferred - stable across device changes)
162 fn set_playout_device_by_guid(&self, guid: &str) -> bool;
163 fn set_recording_device_by_guid(&self, guid: &str) -> bool;
164
165 // Recording control (for device switching while active)
166 fn stop_recording(&self) -> bool;
167 fn init_recording(&self) -> bool;
168 fn start_recording(&self) -> bool;
169 fn recording_is_initialized(&self) -> bool;
170
171 // Playout control (for device switching while active)
172 fn stop_playout(&self) -> bool;
173 fn init_playout(&self) -> bool;
174 fn start_playout(&self) -> bool;
175 fn playout_is_initialized(&self) -> bool;
176
177 // Built-in audio processing (hardware AEC/AGC/NS)
178 // Only available on iOS and some Android devices
179 fn builtin_aec_is_available(&self) -> bool;
180 fn builtin_agc_is_available(&self) -> bool;
181 fn builtin_ns_is_available(&self) -> bool;
182 fn enable_builtin_aec(&self, enable: bool) -> bool;
183 fn enable_builtin_agc(&self, enable: bool) -> bool;
184 fn enable_builtin_ns(&self, enable: bool) -> bool;
185
186 // ADM recording control
187 // Use this to disable microphone when only using NativeAudioSource
188 fn set_adm_recording_enabled(&self, enabled: bool);
189 fn adm_recording_enabled(&self) -> bool;
190
191 // ADM playout control
192 // When disabled (default), playout uses synthetic mode - remote audio is
193 // delivered via FFI callbacks. When enabled, plays through platform speakers.
194 fn set_adm_playout_enabled(&self, enabled: bool);
195 fn adm_playout_enabled(&self) -> bool;
196
197 // Platform ADM lifecycle management
198 // Call acquire_platform_adm when creating PlatformAudio.
199 // Call release_platform_adm when disposing PlatformAudio.
200 // The Platform ADM is only created when first acquired, and terminated
201 // when the last reference is released.
202 fn acquire_platform_adm(&self) -> bool;
203 fn release_platform_adm(&self);
204 fn platform_adm_ref_count(&self) -> i32;
205 fn is_platform_adm_active(&self) -> bool;
206 }
207
208 impl PeerConnectionFactoryExt for PeerConnectionFactory {
209 fn create_video_track(&self, label: &str, source: NativeVideoSource) -> RtcVideoTrack {
210 self.handle.create_video_track(label, source)
211 }
212
213 fn create_audio_track(&self, label: &str, source: NativeAudioSource) -> RtcAudioTrack {
214 self.handle.create_audio_track(label, source)
215 }
216
217 fn create_device_audio_track(&self, label: &str) -> RtcAudioTrack {
218 self.handle.create_device_audio_track(label)
219 }
220
221 fn playout_devices(&self) -> i16 {
222 self.handle.playout_devices()
223 }
224
225 fn recording_devices(&self) -> i16 {
226 self.handle.recording_devices()
227 }
228
229 fn playout_device_name(&self, index: u16) -> String {
230 self.handle.playout_device_name(index)
231 }
232
233 fn recording_device_name(&self, index: u16) -> String {
234 self.handle.recording_device_name(index)
235 }
236
237 fn playout_device_guid(&self, index: u16) -> String {
238 self.handle.playout_device_guid(index)
239 }
240
241 fn recording_device_guid(&self, index: u16) -> String {
242 self.handle.recording_device_guid(index)
243 }
244
245 fn set_playout_device(&self, index: u16) -> bool {
246 self.handle.set_playout_device(index)
247 }
248
249 fn set_recording_device(&self, index: u16) -> bool {
250 self.handle.set_recording_device(index)
251 }
252
253 fn set_playout_device_by_guid(&self, guid: &str) -> bool {
254 self.handle.set_playout_device_by_guid(guid)
255 }
256
257 fn set_recording_device_by_guid(&self, guid: &str) -> bool {
258 self.handle.set_recording_device_by_guid(guid)
259 }
260
261 fn stop_recording(&self) -> bool {
262 self.handle.stop_recording()
263 }
264
265 fn init_recording(&self) -> bool {
266 self.handle.init_recording()
267 }
268
269 fn start_recording(&self) -> bool {
270 self.handle.start_recording()
271 }
272
273 fn recording_is_initialized(&self) -> bool {
274 self.handle.recording_is_initialized()
275 }
276
277 fn stop_playout(&self) -> bool {
278 self.handle.stop_playout()
279 }
280
281 fn init_playout(&self) -> bool {
282 self.handle.init_playout()
283 }
284
285 fn start_playout(&self) -> bool {
286 self.handle.start_playout()
287 }
288
289 fn playout_is_initialized(&self) -> bool {
290 self.handle.playout_is_initialized()
291 }
292
293 fn builtin_aec_is_available(&self) -> bool {
294 self.handle.builtin_aec_is_available()
295 }
296
297 fn builtin_agc_is_available(&self) -> bool {
298 self.handle.builtin_agc_is_available()
299 }
300
301 fn builtin_ns_is_available(&self) -> bool {
302 self.handle.builtin_ns_is_available()
303 }
304
305 fn enable_builtin_aec(&self, enable: bool) -> bool {
306 self.handle.enable_builtin_aec(enable)
307 }
308
309 fn enable_builtin_agc(&self, enable: bool) -> bool {
310 self.handle.enable_builtin_agc(enable)
311 }
312
313 fn enable_builtin_ns(&self, enable: bool) -> bool {
314 self.handle.enable_builtin_ns(enable)
315 }
316
317 fn set_adm_recording_enabled(&self, enabled: bool) {
318 self.handle.set_adm_recording_enabled(enabled)
319 }
320
321 fn adm_recording_enabled(&self) -> bool {
322 self.handle.adm_recording_enabled()
323 }
324
325 fn set_adm_playout_enabled(&self, enabled: bool) {
326 self.handle.set_adm_playout_enabled(enabled)
327 }
328
329 fn adm_playout_enabled(&self) -> bool {
330 self.handle.adm_playout_enabled()
331 }
332
333 fn acquire_platform_adm(&self) -> bool {
334 self.handle.acquire_platform_adm()
335 }
336
337 fn release_platform_adm(&self) {
338 self.handle.release_platform_adm()
339 }
340
341 fn platform_adm_ref_count(&self) -> i32 {
342 self.handle.platform_adm_ref_count()
343 }
344
345 fn is_platform_adm_active(&self) -> bool {
346 self.handle.is_platform_adm_active()
347 }
348 }
349 }
@@ -0,0 +1,349 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use crate::{
18 imp::peer_connection_factory as imp_pcf, peer_connection::PeerConnection,
19 rtp_parameters::RtpCapabilities, MediaType, RtcError,
20};
21
22#[derive(Debug, Clone)]
23pub struct IceServer {
24 pub urls: Vec<String>,
25 pub username: String,
26 pub password: String,
27}
28
29#[derive(Debug, Copy, Clone, PartialEq, Eq)]
30pub enum ContinualGatheringPolicy {
31 GatherOnce,
32 GatherContinually,
33}
34
35#[derive(Debug, Copy, Clone, PartialEq, Eq)]
36pub enum IceTransportsType {
37 Relay,
38 NoHost,
39 All,
40}
41
42/// Configuration for a [`PeerConnection`].
43///
44/// This type is `#[non_exhaustive]`: construct it from [`RtcConfiguration::default`]
45/// and set the fields you need, e.g.
46/// ```
47/// # use libwebrtc::peer_connection_factory::{IceTransportsType, RtcConfiguration};
48/// let mut cfg = RtcConfiguration::default();
49/// cfg.ice_transport_type = IceTransportsType::Relay;
50/// ```
51/// New fields may be added in future releases without a breaking change.
52#[derive(Debug, Clone)]
53#[non_exhaustive]
54pub struct RtcConfiguration {
55 pub ice_servers: Vec<IceServer>,
56 pub continual_gathering_policy: ContinualGatheringPolicy,
57 pub ice_transport_type: IceTransportsType,
58 /// WARP: enable SNAP (SCTP-INIT-in-SDP). Maps to the immutable
59 /// `enable_sctp_snap` RTCConfiguration field, so it must be set the same at
60 /// PeerConnection creation and every set_configuration.
61 pub enable_sctp_snap: bool,
62}
63
64impl Default for RtcConfiguration {
65 fn default() -> Self {
66 Self {
67 ice_servers: vec![],
68 continual_gathering_policy: ContinualGatheringPolicy::GatherContinually,
69 ice_transport_type: IceTransportsType::All,
70 enable_sctp_snap: false,
71 }
72 }
73}
74
75#[derive(Clone, Default)]
76pub struct PeerConnectionFactory {
77 pub(crate) handle: imp_pcf::PeerConnectionFactory,
78}
79
80impl Debug for PeerConnectionFactory {
81 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
82 f.debug_struct("PeerConnectionFactory").finish()
83 }
84}
85
86impl PeerConnectionFactory {
87 /// Creates a native peer connection factory that renders received video as soon as possible.
88 #[cfg(not(target_arch = "wasm32"))]
89 pub fn with_zero_playout_delay() -> Self {
90 Self { handle: imp_pcf::PeerConnectionFactory::with_zero_playout_delay() }
91 }
92
93 /// Creates a native peer connection factory with the given runtime options.
94 /// `zero_playout_delay` and `enable_warp` (SPED + SNAP) are independent and
95 /// may be combined.
96 #[cfg(not(target_arch = "wasm32"))]
97 pub fn with_options(zero_playout_delay: bool, enable_warp: bool) -> Self {
98 Self {
99 handle: imp_pcf::PeerConnectionFactory::with_options(zero_playout_delay, enable_warp),
100 }
101 }
102
103 pub fn create_peer_connection(
104 &self,
105 config: RtcConfiguration,
106 ) -> Result<PeerConnection, RtcError> {
107 self.handle.create_peer_connection(config)
108 }
109
110 pub fn get_rtp_sender_capabilities(&self, media_type: MediaType) -> RtpCapabilities {
111 self.handle.get_rtp_sender_capabilities(media_type)
112 }
113
114 pub fn get_rtp_receiver_capabilities(&self, media_type: MediaType) -> RtpCapabilities {
115 self.handle.get_rtp_receiver_capabilities(media_type)
116 }
117}
118
119#[cfg(all(test, not(target_arch = "wasm32")))]
120mod tests {
121 use super::PeerConnectionFactory;
122
123 #[test]
124 fn zero_playout_delay_factory_uses_force_playout_delay_field_trial() {
125 let default_factory = PeerConnectionFactory::default();
126 assert!(!default_factory.handle.zero_playout_delay_enabled());
127 drop(default_factory);
128
129 let low_latency_factory = PeerConnectionFactory::with_zero_playout_delay();
130 assert!(low_latency_factory.handle.zero_playout_delay_enabled());
131 }
132}
133
134pub mod native {
135 use super::PeerConnectionFactory;
136 use crate::{
137 audio_source::native::NativeAudioSource, audio_track::RtcAudioTrack,
138 video_source::native::NativeVideoSource, video_track::RtcVideoTrack,
139 };
140
141 pub trait PeerConnectionFactoryExt {
142 fn create_video_track(&self, label: &str, source: NativeVideoSource) -> RtcVideoTrack;
143 fn create_audio_track(&self, label: &str, source: NativeAudioSource) -> RtcAudioTrack;
144
145 /// Create an audio track that uses the Platform ADM for capture.
146 /// The track will capture audio from the selected recording device.
147 fn create_device_audio_track(&self, label: &str) -> RtcAudioTrack;
148
149 // Device enumeration
150 fn playout_devices(&self) -> i16;
151 fn recording_devices(&self) -> i16;
152 fn playout_device_name(&self, index: u16) -> String;
153 fn recording_device_name(&self, index: u16) -> String;
154 /// Get device GUID (platform-specific unique identifier, stable across hot-plug)
155 fn playout_device_guid(&self, index: u16) -> String;
156 fn recording_device_guid(&self, index: u16) -> String;
157
158 // Device selection by index
159 fn set_playout_device(&self, index: u16) -> bool;
160 fn set_recording_device(&self, index: u16) -> bool;
161 /// Device selection by GUID (preferred - stable across device changes)
162 fn set_playout_device_by_guid(&self, guid: &str) -> bool;
163 fn set_recording_device_by_guid(&self, guid: &str) -> bool;
164
165 // Recording control (for device switching while active)
166 fn stop_recording(&self) -> bool;
167 fn init_recording(&self) -> bool;
168 fn start_recording(&self) -> bool;
169 fn recording_is_initialized(&self) -> bool;
170
171 // Playout control (for device switching while active)
172 fn stop_playout(&self) -> bool;
173 fn init_playout(&self) -> bool;
174 fn start_playout(&self) -> bool;
175 fn playout_is_initialized(&self) -> bool;
176
177 // Built-in audio processing (hardware AEC/AGC/NS)
178 // Only available on iOS and some Android devices
179 fn builtin_aec_is_available(&self) -> bool;
180 fn builtin_agc_is_available(&self) -> bool;
181 fn builtin_ns_is_available(&self) -> bool;
182 fn enable_builtin_aec(&self, enable: bool) -> bool;
183 fn enable_builtin_agc(&self, enable: bool) -> bool;
184 fn enable_builtin_ns(&self, enable: bool) -> bool;
185
186 // ADM recording control
187 // Use this to disable microphone when only using NativeAudioSource
188 fn set_adm_recording_enabled(&self, enabled: bool);
189 fn adm_recording_enabled(&self) -> bool;
190
191 // ADM playout control
192 // When disabled (default), playout uses synthetic mode - remote audio is
193 // delivered via FFI callbacks. When enabled, plays through platform speakers.
194 fn set_adm_playout_enabled(&self, enabled: bool);
195 fn adm_playout_enabled(&self) -> bool;
196
197 // Platform ADM lifecycle management
198 // Call acquire_platform_adm when creating PlatformAudio.
199 // Call release_platform_adm when disposing PlatformAudio.
200 // The Platform ADM is only created when first acquired, and terminated
201 // when the last reference is released.
202 fn acquire_platform_adm(&self) -> bool;
203 fn release_platform_adm(&self);
204 fn platform_adm_ref_count(&self) -> i32;
205 fn is_platform_adm_active(&self) -> bool;
206 }
207
208 impl PeerConnectionFactoryExt for PeerConnectionFactory {
209 fn create_video_track(&self, label: &str, source: NativeVideoSource) -> RtcVideoTrack {
210 self.handle.create_video_track(label, source)
211 }
212
213 fn create_audio_track(&self, label: &str, source: NativeAudioSource) -> RtcAudioTrack {
214 self.handle.create_audio_track(label, source)
215 }
216
217 fn create_device_audio_track(&self, label: &str) -> RtcAudioTrack {
218 self.handle.create_device_audio_track(label)
219 }
220
221 fn playout_devices(&self) -> i16 {
222 self.handle.playout_devices()
223 }
224
225 fn recording_devices(&self) -> i16 {
226 self.handle.recording_devices()
227 }
228
229 fn playout_device_name(&self, index: u16) -> String {
230 self.handle.playout_device_name(index)
231 }
232
233 fn recording_device_name(&self, index: u16) -> String {
234 self.handle.recording_device_name(index)
235 }
236
237 fn playout_device_guid(&self, index: u16) -> String {
238 self.handle.playout_device_guid(index)
239 }
240
241 fn recording_device_guid(&self, index: u16) -> String {
242 self.handle.recording_device_guid(index)
243 }
244
245 fn set_playout_device(&self, index: u16) -> bool {
246 self.handle.set_playout_device(index)
247 }
248
249 fn set_recording_device(&self, index: u16) -> bool {
250 self.handle.set_recording_device(index)
251 }
252
253 fn set_playout_device_by_guid(&self, guid: &str) -> bool {
254 self.handle.set_playout_device_by_guid(guid)
255 }
256
257 fn set_recording_device_by_guid(&self, guid: &str) -> bool {
258 self.handle.set_recording_device_by_guid(guid)
259 }
260
261 fn stop_recording(&self) -> bool {
262 self.handle.stop_recording()
263 }
264
265 fn init_recording(&self) -> bool {
266 self.handle.init_recording()
267 }
268
269 fn start_recording(&self) -> bool {
270 self.handle.start_recording()
271 }
272
273 fn recording_is_initialized(&self) -> bool {
274 self.handle.recording_is_initialized()
275 }
276
277 fn stop_playout(&self) -> bool {
278 self.handle.stop_playout()
279 }
280
281 fn init_playout(&self) -> bool {
282 self.handle.init_playout()
283 }
284
285 fn start_playout(&self) -> bool {
286 self.handle.start_playout()
287 }
288
289 fn playout_is_initialized(&self) -> bool {
290 self.handle.playout_is_initialized()
291 }
292
293 fn builtin_aec_is_available(&self) -> bool {
294 self.handle.builtin_aec_is_available()
295 }
296
297 fn builtin_agc_is_available(&self) -> bool {
298 self.handle.builtin_agc_is_available()
299 }
300
301 fn builtin_ns_is_available(&self) -> bool {
302 self.handle.builtin_ns_is_available()
303 }
304
305 fn enable_builtin_aec(&self, enable: bool) -> bool {
306 self.handle.enable_builtin_aec(enable)
307 }
308
309 fn enable_builtin_agc(&self, enable: bool) -> bool {
310 self.handle.enable_builtin_agc(enable)
311 }
312
313 fn enable_builtin_ns(&self, enable: bool) -> bool {
314 self.handle.enable_builtin_ns(enable)
315 }
316
317 fn set_adm_recording_enabled(&self, enabled: bool) {
318 self.handle.set_adm_recording_enabled(enabled)
319 }
320
321 fn adm_recording_enabled(&self) -> bool {
322 self.handle.adm_recording_enabled()
323 }
324
325 fn set_adm_playout_enabled(&self, enabled: bool) {
326 self.handle.set_adm_playout_enabled(enabled)
327 }
328
329 fn adm_playout_enabled(&self) -> bool {
330 self.handle.adm_playout_enabled()
331 }
332
333 fn acquire_platform_adm(&self) -> bool {
334 self.handle.acquire_platform_adm()
335 }
336
337 fn release_platform_adm(&self) {
338 self.handle.release_platform_adm()
339 }
340
341 fn platform_adm_ref_count(&self) -> i32 {
342 self.handle.platform_adm_ref_count()
343 }
344
345 fn is_platform_adm_active(&self) -> bool {
346 self.handle.is_platform_adm_active()
347 }
348 }
349}
vendor/libwebrtc/src/prelude.rs added +43 −0
@@ -0,0 +1,43 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 pub use crate::{
16 audio_frame::AudioFrame,
17 audio_source::{AudioSourceOptions, RtcAudioSource},
18 audio_track::RtcAudioTrack,
19 data_channel::{DataBuffer, DataChannel, DataChannelError, DataChannelInit, DataChannelState},
20 ice_candidate::IceCandidate,
21 media_stream::MediaStream,
22 media_stream_track::{MediaStreamTrack, RtcTrackState},
23 peer_connection::{
24 AnswerOptions, IceConnectionState, IceGatheringState, OfferOptions, PeerConnection,
25 PeerConnectionState, SignalingState,
26 },
27 peer_connection_factory::{
28 ContinualGatheringPolicy, IceServer, IceTransportsType, PeerConnectionFactory,
29 RtcConfiguration,
30 },
31 rtp_parameters::*,
32 rtp_receiver::RtpReceiver,
33 rtp_sender::{RtpSender, VideoEncoderBackend},
34 rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit},
35 session_description::{SdpType, SessionDescription},
36 video_frame::{
37 BoxVideoBuffer, BoxVideoFrame, I010Buffer, I420ABuffer, I420Buffer, I422Buffer, I444Buffer,
38 NV12Buffer, VideoBuffer, VideoBufferType, VideoFormatType, VideoFrame, VideoRotation,
39 },
40 video_source::{RtcVideoSource, VideoResolution},
41 video_track::RtcVideoTrack,
42 MediaType, RtcError, RtcErrorType,
43 };
@@ -0,0 +1,43 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub use crate::{
16 audio_frame::AudioFrame,
17 audio_source::{AudioSourceOptions, RtcAudioSource},
18 audio_track::RtcAudioTrack,
19 data_channel::{DataBuffer, DataChannel, DataChannelError, DataChannelInit, DataChannelState},
20 ice_candidate::IceCandidate,
21 media_stream::MediaStream,
22 media_stream_track::{MediaStreamTrack, RtcTrackState},
23 peer_connection::{
24 AnswerOptions, IceConnectionState, IceGatheringState, OfferOptions, PeerConnection,
25 PeerConnectionState, SignalingState,
26 },
27 peer_connection_factory::{
28 ContinualGatheringPolicy, IceServer, IceTransportsType, PeerConnectionFactory,
29 RtcConfiguration,
30 },
31 rtp_parameters::*,
32 rtp_receiver::RtpReceiver,
33 rtp_sender::{RtpSender, VideoEncoderBackend},
34 rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit},
35 session_description::{SdpType, SessionDescription},
36 video_frame::{
37 BoxVideoBuffer, BoxVideoFrame, I010Buffer, I420ABuffer, I420Buffer, I422Buffer, I444Buffer,
38 NV12Buffer, VideoBuffer, VideoBufferType, VideoFormatType, VideoFrame, VideoRotation,
39 },
40 video_source::{RtcVideoSource, VideoResolution},
41 video_track::RtcVideoTrack,
42 MediaType, RtcError, RtcErrorType,
43};
vendor/libwebrtc/src/rtp_parameters.rs added +181 −0
@@ -0,0 +1,181 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use crate::rtp_transceiver::RtpTransceiverDirection;
16
17 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
18 pub enum Priority {
19 VeryLow,
20 Low,
21 Medium,
22 High,
23 }
24
25 /// Controls how the encoder degrades quality when bandwidth is constrained.
26 #[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
27 pub enum DegradationPreference {
28 /// Maintain both framerate and resolution. Frames may be dropped before encoding
29 /// if necessary to avoid overusing network and encoder resources.
30 MaintainFramerateAndResolution,
31 /// Degrade framerate to maintain resolution.
32 MaintainFramerate,
33 /// Degrade resolution to maintain framerate.
34 MaintainResolution,
35 /// Balance between framerate and resolution degradation.
36 #[default]
37 Balanced,
38 }
39
40 impl DegradationPreference {
41 /// Deprecated: Use `MaintainFramerateAndResolution` instead.
42 #[deprecated(since = "0.8.0", note = "Use MaintainFramerateAndResolution instead")]
43 #[allow(non_upper_case_globals)]
44 pub const Disabled: Self = Self::MaintainFramerateAndResolution;
45 }
46
47 #[derive(Debug, Clone)]
48 pub struct RtpHeaderExtensionParameters {
49 pub uri: String,
50 pub id: i32,
51 pub encrypted: bool,
52 }
53
54 #[derive(Debug, Clone, Default)]
55 pub struct RtpParameters {
56 pub codecs: Vec<RtpCodecParameters>,
57 pub header_extensions: Vec<RtpHeaderExtensionParameters>,
58 pub encodings: Vec<RtpEncodingParameters>,
59 pub rtcp: RtcpParameters,
60 /// Opaque token used by WebRTC to pair getParameters/setParameters calls.
61 /// Must be preserved when round-tripping through set_parameters().
62 pub(crate) transaction_id: String,
63 pub(crate) mid: String,
64 pub(crate) has_degradation_preference: bool,
65 pub(crate) degradation_preference: i32,
66 }
67
68 impl RtpParameters {
69 /// Sets the degradation preference for this RTP sender.
70 ///
71 /// This controls how the encoder trades off between resolution and framerate
72 /// when bandwidth is constrained.
73 pub fn set_degradation_preference(&mut self, preference: DegradationPreference) {
74 self.has_degradation_preference = true;
75 self.degradation_preference = match preference {
76 DegradationPreference::MaintainFramerateAndResolution => 0,
77 DegradationPreference::MaintainFramerate => 1,
78 DegradationPreference::MaintainResolution => 2,
79 DegradationPreference::Balanced => 3,
80 };
81 }
82
83 /// Gets the current degradation preference, if set.
84 pub fn degradation_preference(&self) -> Option<DegradationPreference> {
85 if !self.has_degradation_preference {
86 return None;
87 }
88 Some(match self.degradation_preference {
89 0 => DegradationPreference::MaintainFramerateAndResolution,
90 1 => DegradationPreference::MaintainFramerate,
91 2 => DegradationPreference::MaintainResolution,
92 3 => DegradationPreference::Balanced,
93 _ => DegradationPreference::Balanced,
94 })
95 }
96 }
97
98 /// Mirrors webrtc_sys RtcpFeedback for round-trip fidelity.
99 #[derive(Debug, Clone, Default)]
100 pub(crate) struct CodecFeedback {
101 pub feedback_type: i32,
102 pub has_message_type: bool,
103 pub message_type: i32,
104 }
105
106 #[derive(Debug, Clone, Default)]
107 pub struct RtpCodecParameters {
108 pub payload_type: u8,
109 pub mime_type: String, // read-only
110 pub clock_rate: Option<u64>,
111 pub channels: Option<u16>,
112 pub(crate) name: String,
113 pub(crate) kind: i32,
114 pub(crate) has_max_ptime: bool,
115 pub(crate) max_ptime: i32,
116 pub(crate) has_ptime: bool,
117 pub(crate) ptime: i32,
118 pub(crate) rtcp_feedback: Vec<CodecFeedback>,
119 pub(crate) parameters: Vec<(String, String)>,
120 }
121
122 #[derive(Debug, Clone, Default)]
123 pub struct RtcpParameters {
124 pub cname: String,
125 pub reduced_size: bool,
126 pub(crate) mux: bool,
127 pub(crate) has_ssrc: bool,
128 pub(crate) ssrc: u32,
129 }
130
131 #[derive(Debug, Clone)]
132 pub struct RtpEncodingParameters {
133 pub active: bool,
134 pub max_bitrate: Option<u64>,
135 pub max_framerate: Option<f64>,
136 pub priority: Priority,
137 pub rid: String,
138 pub scale_resolution_down_by: Option<f64>,
139 /// RTP scalability mode (e.g. "L3T3_KEY"). Required to enable true
140 /// SVC for codecs that support it (VP9, AV1).
141 pub scalability_mode: Option<String>,
142 /// Preserved for round-trip fidelity with WebRTC's getParameters/setParameters.
143 pub has_ssrc: bool,
144 pub ssrc: u32,
145 }
146
147 #[derive(Debug, Clone)]
148 pub struct RtpCodecCapability {
149 pub channels: Option<u16>,
150 pub clock_rate: Option<u64>,
151 pub mime_type: String,
152 pub sdp_fmtp_line: Option<String>,
153 }
154
155 #[derive(Debug, Clone)]
156 pub struct RtpHeaderExtensionCapability {
157 pub uri: String,
158 pub direction: RtpTransceiverDirection,
159 }
160
161 #[derive(Debug, Clone)]
162 pub struct RtpCapabilities {
163 pub codecs: Vec<RtpCodecCapability>,
164 pub header_extensions: Vec<RtpHeaderExtensionCapability>,
165 }
166
167 impl Default for RtpEncodingParameters {
168 fn default() -> Self {
169 Self {
170 active: true,
171 max_bitrate: None,
172 max_framerate: None,
173 priority: Priority::Low,
174 rid: String::default(),
175 scale_resolution_down_by: None,
176 scalability_mode: None,
177 has_ssrc: false,
178 ssrc: 0,
179 }
180 }
181 }
@@ -0,0 +1,181 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::rtp_transceiver::RtpTransceiverDirection;
16
17#[derive(Debug, Copy, Clone, PartialEq, Eq)]
18pub enum Priority {
19 VeryLow,
20 Low,
21 Medium,
22 High,
23}
24
25/// Controls how the encoder degrades quality when bandwidth is constrained.
26#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
27pub enum DegradationPreference {
28 /// Maintain both framerate and resolution. Frames may be dropped before encoding
29 /// if necessary to avoid overusing network and encoder resources.
30 MaintainFramerateAndResolution,
31 /// Degrade framerate to maintain resolution.
32 MaintainFramerate,
33 /// Degrade resolution to maintain framerate.
34 MaintainResolution,
35 /// Balance between framerate and resolution degradation.
36 #[default]
37 Balanced,
38}
39
40impl DegradationPreference {
41 /// Deprecated: Use `MaintainFramerateAndResolution` instead.
42 #[deprecated(since = "0.8.0", note = "Use MaintainFramerateAndResolution instead")]
43 #[allow(non_upper_case_globals)]
44 pub const Disabled: Self = Self::MaintainFramerateAndResolution;
45}
46
47#[derive(Debug, Clone)]
48pub struct RtpHeaderExtensionParameters {
49 pub uri: String,
50 pub id: i32,
51 pub encrypted: bool,
52}
53
54#[derive(Debug, Clone, Default)]
55pub struct RtpParameters {
56 pub codecs: Vec<RtpCodecParameters>,
57 pub header_extensions: Vec<RtpHeaderExtensionParameters>,
58 pub encodings: Vec<RtpEncodingParameters>,
59 pub rtcp: RtcpParameters,
60 /// Opaque token used by WebRTC to pair getParameters/setParameters calls.
61 /// Must be preserved when round-tripping through set_parameters().
62 pub(crate) transaction_id: String,
63 pub(crate) mid: String,
64 pub(crate) has_degradation_preference: bool,
65 pub(crate) degradation_preference: i32,
66}
67
68impl RtpParameters {
69 /// Sets the degradation preference for this RTP sender.
70 ///
71 /// This controls how the encoder trades off between resolution and framerate
72 /// when bandwidth is constrained.
73 pub fn set_degradation_preference(&mut self, preference: DegradationPreference) {
74 self.has_degradation_preference = true;
75 self.degradation_preference = match preference {
76 DegradationPreference::MaintainFramerateAndResolution => 0,
77 DegradationPreference::MaintainFramerate => 1,
78 DegradationPreference::MaintainResolution => 2,
79 DegradationPreference::Balanced => 3,
80 };
81 }
82
83 /// Gets the current degradation preference, if set.
84 pub fn degradation_preference(&self) -> Option<DegradationPreference> {
85 if !self.has_degradation_preference {
86 return None;
87 }
88 Some(match self.degradation_preference {
89 0 => DegradationPreference::MaintainFramerateAndResolution,
90 1 => DegradationPreference::MaintainFramerate,
91 2 => DegradationPreference::MaintainResolution,
92 3 => DegradationPreference::Balanced,
93 _ => DegradationPreference::Balanced,
94 })
95 }
96}
97
98/// Mirrors webrtc_sys RtcpFeedback for round-trip fidelity.
99#[derive(Debug, Clone, Default)]
100pub(crate) struct CodecFeedback {
101 pub feedback_type: i32,
102 pub has_message_type: bool,
103 pub message_type: i32,
104}
105
106#[derive(Debug, Clone, Default)]
107pub struct RtpCodecParameters {
108 pub payload_type: u8,
109 pub mime_type: String, // read-only
110 pub clock_rate: Option<u64>,
111 pub channels: Option<u16>,
112 pub(crate) name: String,
113 pub(crate) kind: i32,
114 pub(crate) has_max_ptime: bool,
115 pub(crate) max_ptime: i32,
116 pub(crate) has_ptime: bool,
117 pub(crate) ptime: i32,
118 pub(crate) rtcp_feedback: Vec<CodecFeedback>,
119 pub(crate) parameters: Vec<(String, String)>,
120}
121
122#[derive(Debug, Clone, Default)]
123pub struct RtcpParameters {
124 pub cname: String,
125 pub reduced_size: bool,
126 pub(crate) mux: bool,
127 pub(crate) has_ssrc: bool,
128 pub(crate) ssrc: u32,
129}
130
131#[derive(Debug, Clone)]
132pub struct RtpEncodingParameters {
133 pub active: bool,
134 pub max_bitrate: Option<u64>,
135 pub max_framerate: Option<f64>,
136 pub priority: Priority,
137 pub rid: String,
138 pub scale_resolution_down_by: Option<f64>,
139 /// RTP scalability mode (e.g. "L3T3_KEY"). Required to enable true
140 /// SVC for codecs that support it (VP9, AV1).
141 pub scalability_mode: Option<String>,
142 /// Preserved for round-trip fidelity with WebRTC's getParameters/setParameters.
143 pub has_ssrc: bool,
144 pub ssrc: u32,
145}
146
147#[derive(Debug, Clone)]
148pub struct RtpCodecCapability {
149 pub channels: Option<u16>,
150 pub clock_rate: Option<u64>,
151 pub mime_type: String,
152 pub sdp_fmtp_line: Option<String>,
153}
154
155#[derive(Debug, Clone)]
156pub struct RtpHeaderExtensionCapability {
157 pub uri: String,
158 pub direction: RtpTransceiverDirection,
159}
160
161#[derive(Debug, Clone)]
162pub struct RtpCapabilities {
163 pub codecs: Vec<RtpCodecCapability>,
164 pub header_extensions: Vec<RtpHeaderExtensionCapability>,
165}
166
167impl Default for RtpEncodingParameters {
168 fn default() -> Self {
169 Self {
170 active: true,
171 max_bitrate: None,
172 max_framerate: None,
173 priority: Priority::Low,
174 rid: String::default(),
175 scale_resolution_down_by: None,
176 scalability_mode: None,
177 has_ssrc: false,
178 ssrc: 0,
179 }
180 }
181}
vendor/libwebrtc/src/rtp_receiver.rs added +70 −0
@@ -0,0 +1,70 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::fmt::Debug;
16
17 use crate::{
18 imp::rtp_receiver as imp_rr, media_stream::MediaStream, media_stream_track::MediaStreamTrack,
19 rtp_parameters::RtpParameters, stats::RtcStats, RtcError,
20 };
21
22 #[derive(Clone)]
23 pub struct RtpReceiver {
24 pub(crate) handle: imp_rr::RtpReceiver,
25 }
26
27 impl RtpReceiver {
28 pub fn track(&self) -> Option<MediaStreamTrack> {
29 self.handle.track()
30 }
31
32 pub fn stream_ids(&self) -> Vec<String> {
33 self.handle.stream_ids()
34 }
35
36 pub fn streams(&self) -> Vec<MediaStream> {
37 self.handle.streams()
38 }
39
40 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
41 self.handle.get_stats().await
42 }
43
44 pub fn parameters(&self) -> RtpParameters {
45 self.handle.parameters()
46 }
47
48 /// The SSRC and CSRC sources of the last few seconds, like the browser's getSynchronizationSources and getContributingSources.
49 pub fn sources(&self) -> Vec<RtpSource> {
50 self.handle.sources()
51 }
52 }
53
54 /// One RTP source; `audio_level` is in -dBov (0 loudest, 127 silent) when the packet carried it.
55 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
56 pub struct RtpSource {
57 pub source_id: u32,
58 pub contributing: bool,
59 pub audio_level: Option<u8>,
60 pub timestamp_ms: i64,
61 }
62
63 impl Debug for RtpReceiver {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65 f.debug_struct("RtpReceiver")
66 .field("track", &self.track())
67 .field("cname", &self.parameters().rtcp.cname)
68 .finish()
69 }
70 }
@@ -0,0 +1,70 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use crate::{
18 imp::rtp_receiver as imp_rr, media_stream::MediaStream, media_stream_track::MediaStreamTrack,
19 rtp_parameters::RtpParameters, stats::RtcStats, RtcError,
20};
21
22#[derive(Clone)]
23pub struct RtpReceiver {
24 pub(crate) handle: imp_rr::RtpReceiver,
25}
26
27impl RtpReceiver {
28 pub fn track(&self) -> Option<MediaStreamTrack> {
29 self.handle.track()
30 }
31
32 pub fn stream_ids(&self) -> Vec<String> {
33 self.handle.stream_ids()
34 }
35
36 pub fn streams(&self) -> Vec<MediaStream> {
37 self.handle.streams()
38 }
39
40 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
41 self.handle.get_stats().await
42 }
43
44 pub fn parameters(&self) -> RtpParameters {
45 self.handle.parameters()
46 }
47
48 /// The SSRC and CSRC sources of the last few seconds, like the browser's getSynchronizationSources and getContributingSources.
49 pub fn sources(&self) -> Vec<RtpSource> {
50 self.handle.sources()
51 }
52}
53
54/// One RTP source; `audio_level` is in -dBov (0 loudest, 127 silent) when the packet carried it.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct RtpSource {
57 pub source_id: u32,
58 pub contributing: bool,
59 pub audio_level: Option<u8>,
60 pub timestamp_ms: i64,
61}
62
63impl Debug for RtpReceiver {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65 f.debug_struct("RtpReceiver")
66 .field("track", &self.track())
67 .field("cname", &self.parameters().rtcp.cname)
68 .finish()
69 }
70}
vendor/libwebrtc/src/rtp_sender.rs added +100 −0
@@ -0,0 +1,100 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::fmt::Debug;
16
17 use crate::{
18 imp::rtp_sender as imp_rs, media_stream_track::MediaStreamTrack, rtp_parameters::RtpParameters,
19 stats::RtcStats, RtcError,
20 };
21
22 /// Preferred backend for video encoding on an [`RtpSender`].
23 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
24 #[non_exhaustive]
25 pub enum VideoEncoderBackend {
26 /// Use the SDK's default encoder selection.
27 #[default]
28 Auto,
29 /// Prefer a software encoder.
30 Software,
31 /// Prefer any available hardware encoder.
32 Hardware,
33 /// Prefer NVIDIA NVENC when available.
34 Nvenc,
35 /// Prefer VAAPI when available.
36 Vaapi,
37 /// Prefer VideoToolbox on Apple platforms when available.
38 VideoToolbox,
39 /// Pass pre-encoded frames through without encoding raw video frames.
40 PreEncoded,
41 }
42
43 impl VideoEncoderBackend {
44 /// Returns the video encoder backends available in this process.
45 ///
46 /// The result reflects the current platform, build flags, and runtime
47 /// hardware capability checks.
48 ///
49 /// ```
50 /// use libwebrtc::rtp_sender::VideoEncoderBackend;
51 ///
52 /// let backends: Vec<_> = VideoEncoderBackend::list_available().into_iter().collect();
53 /// assert!(backends.contains(&VideoEncoderBackend::Auto));
54 /// assert!(backends.contains(&VideoEncoderBackend::Software));
55 /// ```
56 pub fn list_available() -> impl IntoIterator<Item = VideoEncoderBackend> {
57 imp_rs::video_encoder_backend_list()
58 }
59 }
60
61 #[derive(Clone)]
62 pub struct RtpSender {
63 pub(crate) handle: imp_rs::RtpSender,
64 }
65
66 impl RtpSender {
67 pub fn track(&self) -> Option<MediaStreamTrack> {
68 self.handle.track()
69 }
70
71 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
72 self.handle.get_stats().await
73 }
74
75 pub fn set_track(&self, track: Option<MediaStreamTrack>) -> Result<(), RtcError> {
76 self.handle.set_track(track)
77 }
78
79 pub fn parameters(&self) -> RtpParameters {
80 self.handle.parameters()
81 }
82
83 pub fn set_parameters(&self, parameters: RtpParameters) -> Result<(), RtcError> {
84 self.handle.set_parameters(parameters)
85 }
86
87 /// Sets the preferred video encoder backend for this sender.
88 ///
89 /// If the requested backend is unavailable, libwebrtc falls back to another
90 /// compatible encoder.
91 pub fn set_video_encoder_backend(&self, backend: VideoEncoderBackend) {
92 self.handle.set_video_encoder_backend(backend)
93 }
94 }
95
96 impl Debug for RtpSender {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 f.debug_struct("RtpReceiver").field("cname", &self.parameters().rtcp.cname).finish()
99 }
100 }
@@ -0,0 +1,100 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use crate::{
18 imp::rtp_sender as imp_rs, media_stream_track::MediaStreamTrack, rtp_parameters::RtpParameters,
19 stats::RtcStats, RtcError,
20};
21
22/// Preferred backend for video encoding on an [`RtpSender`].
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum VideoEncoderBackend {
26 /// Use the SDK's default encoder selection.
27 #[default]
28 Auto,
29 /// Prefer a software encoder.
30 Software,
31 /// Prefer any available hardware encoder.
32 Hardware,
33 /// Prefer NVIDIA NVENC when available.
34 Nvenc,
35 /// Prefer VAAPI when available.
36 Vaapi,
37 /// Prefer VideoToolbox on Apple platforms when available.
38 VideoToolbox,
39 /// Pass pre-encoded frames through without encoding raw video frames.
40 PreEncoded,
41}
42
43impl VideoEncoderBackend {
44 /// Returns the video encoder backends available in this process.
45 ///
46 /// The result reflects the current platform, build flags, and runtime
47 /// hardware capability checks.
48 ///
49 /// ```
50 /// use libwebrtc::rtp_sender::VideoEncoderBackend;
51 ///
52 /// let backends: Vec<_> = VideoEncoderBackend::list_available().into_iter().collect();
53 /// assert!(backends.contains(&VideoEncoderBackend::Auto));
54 /// assert!(backends.contains(&VideoEncoderBackend::Software));
55 /// ```
56 pub fn list_available() -> impl IntoIterator<Item = VideoEncoderBackend> {
57 imp_rs::video_encoder_backend_list()
58 }
59}
60
61#[derive(Clone)]
62pub struct RtpSender {
63 pub(crate) handle: imp_rs::RtpSender,
64}
65
66impl RtpSender {
67 pub fn track(&self) -> Option<MediaStreamTrack> {
68 self.handle.track()
69 }
70
71 pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> {
72 self.handle.get_stats().await
73 }
74
75 pub fn set_track(&self, track: Option<MediaStreamTrack>) -> Result<(), RtcError> {
76 self.handle.set_track(track)
77 }
78
79 pub fn parameters(&self) -> RtpParameters {
80 self.handle.parameters()
81 }
82
83 pub fn set_parameters(&self, parameters: RtpParameters) -> Result<(), RtcError> {
84 self.handle.set_parameters(parameters)
85 }
86
87 /// Sets the preferred video encoder backend for this sender.
88 ///
89 /// If the requested backend is unavailable, libwebrtc falls back to another
90 /// compatible encoder.
91 pub fn set_video_encoder_backend(&self, backend: VideoEncoderBackend) {
92 self.handle.set_video_encoder_backend(backend)
93 }
94}
95
96impl Debug for RtpSender {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 f.debug_struct("RtpReceiver").field("cname", &self.parameters().rtcp.cname).finish()
99 }
100}
vendor/libwebrtc/src/rtp_transceiver.rs added +85 −0
@@ -0,0 +1,85 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::fmt::Debug;
16
17 use crate::{
18 imp::rtp_transceiver as imp_rt,
19 rtp_parameters::{RtpCodecCapability, RtpEncodingParameters},
20 rtp_receiver::RtpReceiver,
21 rtp_sender::RtpSender,
22 RtcError,
23 };
24
25 #[derive(Debug, Clone)]
26 pub struct RtpTransceiverInit {
27 pub direction: RtpTransceiverDirection,
28 pub stream_ids: Vec<String>,
29 pub send_encodings: Vec<RtpEncodingParameters>,
30 }
31
32 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
33 pub enum RtpTransceiverDirection {
34 SendRecv,
35 SendOnly,
36 RecvOnly,
37 Inactive,
38 Stopped,
39 }
40
41 #[derive(Clone)]
42 pub struct RtpTransceiver {
43 pub(crate) handle: imp_rt::RtpTransceiver,
44 }
45
46 impl RtpTransceiver {
47 pub fn mid(&self) -> Option<String> {
48 self.handle.mid()
49 }
50
51 pub fn current_direction(&self) -> Option<RtpTransceiverDirection> {
52 self.handle.current_direction()
53 }
54
55 pub fn direction(&self) -> RtpTransceiverDirection {
56 self.handle.direction()
57 }
58
59 pub fn sender(&self) -> RtpSender {
60 self.handle.sender()
61 }
62
63 pub fn receiver(&self) -> RtpReceiver {
64 self.handle.receiver()
65 }
66
67 pub fn set_codec_preferences(&self, codecs: Vec<RtpCodecCapability>) -> Result<(), RtcError> {
68 self.handle.set_codec_preferences(codecs)
69 }
70
71 pub fn stop(&self) -> Result<(), RtcError> {
72 self.handle.stop()
73 }
74 }
75
76 impl Debug for RtpTransceiver {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 f.debug_struct("RtpTransceiver")
79 .field("mid", &self.mid())
80 .field("direction", &self.direction())
81 .field("sender", &self.sender())
82 .field("receiver", &self.receiver())
83 .finish()
84 }
85 }
@@ -0,0 +1,85 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use crate::{
18 imp::rtp_transceiver as imp_rt,
19 rtp_parameters::{RtpCodecCapability, RtpEncodingParameters},
20 rtp_receiver::RtpReceiver,
21 rtp_sender::RtpSender,
22 RtcError,
23};
24
25#[derive(Debug, Clone)]
26pub struct RtpTransceiverInit {
27 pub direction: RtpTransceiverDirection,
28 pub stream_ids: Vec<String>,
29 pub send_encodings: Vec<RtpEncodingParameters>,
30}
31
32#[derive(Debug, Copy, Clone, PartialEq, Eq)]
33pub enum RtpTransceiverDirection {
34 SendRecv,
35 SendOnly,
36 RecvOnly,
37 Inactive,
38 Stopped,
39}
40
41#[derive(Clone)]
42pub struct RtpTransceiver {
43 pub(crate) handle: imp_rt::RtpTransceiver,
44}
45
46impl RtpTransceiver {
47 pub fn mid(&self) -> Option<String> {
48 self.handle.mid()
49 }
50
51 pub fn current_direction(&self) -> Option<RtpTransceiverDirection> {
52 self.handle.current_direction()
53 }
54
55 pub fn direction(&self) -> RtpTransceiverDirection {
56 self.handle.direction()
57 }
58
59 pub fn sender(&self) -> RtpSender {
60 self.handle.sender()
61 }
62
63 pub fn receiver(&self) -> RtpReceiver {
64 self.handle.receiver()
65 }
66
67 pub fn set_codec_preferences(&self, codecs: Vec<RtpCodecCapability>) -> Result<(), RtcError> {
68 self.handle.set_codec_preferences(codecs)
69 }
70
71 pub fn stop(&self) -> Result<(), RtcError> {
72 self.handle.stop()
73 }
74}
75
76impl Debug for RtpTransceiver {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 f.debug_struct("RtpTransceiver")
79 .field("mid", &self.mid())
80 .field("direction", &self.direction())
81 .field("sender", &self.sender())
82 .field("receiver", &self.receiver())
83 .finish()
84 }
85}
vendor/libwebrtc/src/session_description.rs added +90 −0
@@ -0,0 +1,90 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::{
16 fmt::{Debug, Display},
17 str::FromStr,
18 };
19
20 use thiserror::Error;
21
22 use crate::imp::session_description as sd_imp;
23
24 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
25 pub enum SdpType {
26 Offer,
27 PrAnswer,
28 Answer,
29 Rollback,
30 }
31
32 impl FromStr for SdpType {
33 type Err = &'static str;
34
35 fn from_str(sdp_type: &str) -> Result<Self, Self::Err> {
36 match sdp_type {
37 "offer" => Ok(Self::Offer),
38 "pranswer" => Ok(Self::PrAnswer),
39 "answer" => Ok(Self::Answer),
40 "rollback" => Ok(Self::Rollback),
41 _ => Err("invalid SdpType"),
42 }
43 }
44 }
45
46 impl Display for SdpType {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 let s = match self {
49 SdpType::Offer => "offer",
50 SdpType::PrAnswer => "pranswer",
51 SdpType::Answer => "answer",
52 SdpType::Rollback => "rollback",
53 };
54 write!(f, "{}", s)
55 }
56 }
57
58 #[derive(Clone)]
59 pub struct SessionDescription {
60 pub(crate) handle: sd_imp::SessionDescription,
61 }
62
63 #[derive(Clone, Error, Debug)]
64 #[error("Failed to parse sdp: {line} - {description}")]
65 pub struct SdpParseError {
66 pub line: String,
67 pub description: String,
68 }
69
70 impl SessionDescription {
71 pub fn parse(sdp: &str, sdp_type: SdpType) -> Result<Self, SdpParseError> {
72 sd_imp::SessionDescription::parse(sdp, sdp_type)
73 }
74
75 pub fn sdp_type(&self) -> SdpType {
76 self.handle.sdp_type()
77 }
78 }
79
80 impl ToString for SessionDescription {
81 fn to_string(&self) -> String {
82 self.handle.to_string()
83 }
84 }
85
86 impl Debug for SessionDescription {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 f.debug_struct("SessionDescription").field("sdp_type", &self.sdp_type()).finish()
89 }
90 }
@@ -0,0 +1,90 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{
16 fmt::{Debug, Display},
17 str::FromStr,
18};
19
20use thiserror::Error;
21
22use crate::imp::session_description as sd_imp;
23
24#[derive(Debug, Copy, Clone, PartialEq, Eq)]
25pub enum SdpType {
26 Offer,
27 PrAnswer,
28 Answer,
29 Rollback,
30}
31
32impl FromStr for SdpType {
33 type Err = &'static str;
34
35 fn from_str(sdp_type: &str) -> Result<Self, Self::Err> {
36 match sdp_type {
37 "offer" => Ok(Self::Offer),
38 "pranswer" => Ok(Self::PrAnswer),
39 "answer" => Ok(Self::Answer),
40 "rollback" => Ok(Self::Rollback),
41 _ => Err("invalid SdpType"),
42 }
43 }
44}
45
46impl Display for SdpType {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 let s = match self {
49 SdpType::Offer => "offer",
50 SdpType::PrAnswer => "pranswer",
51 SdpType::Answer => "answer",
52 SdpType::Rollback => "rollback",
53 };
54 write!(f, "{}", s)
55 }
56}
57
58#[derive(Clone)]
59pub struct SessionDescription {
60 pub(crate) handle: sd_imp::SessionDescription,
61}
62
63#[derive(Clone, Error, Debug)]
64#[error("Failed to parse sdp: {line} - {description}")]
65pub struct SdpParseError {
66 pub line: String,
67 pub description: String,
68}
69
70impl SessionDescription {
71 pub fn parse(sdp: &str, sdp_type: SdpType) -> Result<Self, SdpParseError> {
72 sd_imp::SessionDescription::parse(sdp, sdp_type)
73 }
74
75 pub fn sdp_type(&self) -> SdpType {
76 self.handle.sdp_type()
77 }
78}
79
80impl ToString for SessionDescription {
81 fn to_string(&self) -> String {
82 self.handle.to_string()
83 }
84}
85
86impl Debug for SessionDescription {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 f.debug_struct("SessionDescription").field("sdp_type", &self.sdp_type()).finish()
89 }
90}
vendor/libwebrtc/src/stats.rs added +627 −0
@@ -0,0 +1,627 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::collections::HashMap;
16
17 use serde::Deserialize;
18
19 use crate::data_channel::DataChannelState;
20
21 /// Values from https://www.w3.org/TR/webrtc-stats/ (NOTE: Some of the structs are not in the SPEC
22 /// but inside libwebrtc)
23 /// serde will handle the magic of correctly deserializing the json into our structs.
24 /// The enums values are inside encapsulated inside option because we're not sure about their
25 /// default values (So we default to None instead of an arbitrary value)
26
27 #[derive(Debug, Clone, Deserialize)]
28 #[serde(tag = "type")]
29 #[serde(rename_all = "kebab-case")]
30 pub enum RtcStats {
31 Codec(CodecStats),
32 InboundRtp(InboundRtpStats),
33 OutboundRtp(OutboundRtpStats),
34 RemoteInboundRtp(RemoteInboundRtpStats),
35 RemoteOutboundRtp(RemoteOutboundRtpStats),
36 MediaSource(MediaSourceStats),
37 MediaPlayout(MediaPlayoutStats),
38 PeerConnection(PeerConnectionStats),
39 DataChannel(DataChannelStats),
40 Transport(TransportStats),
41 CandidatePair(CandidatePairStats),
42 LocalCandidate(LocalCandidateStats),
43 RemoteCandidate(RemoteCandidateStats),
44 Certificate(CertificateStats),
45 Stream(StreamStats),
46 Track, // Deprecated
47 }
48
49 #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Deserialize)]
50 #[serde(rename_all = "lowercase")]
51 pub enum QualityLimitationReason {
52 #[default]
53 None,
54 Cpu,
55 Bandwidth,
56 Other,
57 }
58
59 #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Deserialize)]
60 #[serde(rename_all = "lowercase")]
61 pub enum IceRole {
62 #[default]
63 Unknown,
64 Controlling,
65 Controlled,
66 }
67
68 #[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
69 #[serde(rename_all = "lowercase")]
70 pub enum DtlsTransportState {
71 New,
72 Connecting,
73 Connected,
74 Closed,
75 Failed,
76 }
77
78 #[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
79 #[serde(rename_all = "lowercase")]
80 pub enum IceTransportState {
81 New,
82 Checking,
83 Connected,
84 Completed,
85 Disconnected,
86 Failed,
87 Closed,
88 }
89
90 #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Deserialize)]
91 #[serde(rename_all = "lowercase")]
92 pub enum DtlsRole {
93 Client,
94 Server,
95 #[default]
96 Unknown,
97 }
98
99 #[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
100 #[serde(rename_all = "kebab-case")]
101 pub enum IceCandidatePairState {
102 Frozen,
103 Waiting,
104 InProgress, // in-progress
105 Failed,
106 Succeeded,
107 }
108
109 #[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
110 #[serde(rename_all = "lowercase")]
111 pub enum IceCandidateType {
112 Host,
113 Srflx,
114 Prflx,
115 Relay,
116 }
117
118 #[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
119 #[serde(rename_all = "lowercase")]
120 pub enum IceServerTransportProtocol {
121 Udp,
122 Tcp,
123 Tls,
124 }
125
126 #[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
127 #[serde(rename_all = "lowercase")]
128 pub enum IceTcpCandidateType {
129 Active,
130 Passive,
131 So,
132 }
133
134 #[derive(Debug, Default, Clone, Deserialize)]
135 pub struct CodecStats {
136 #[serde(flatten)]
137 pub rtc: dictionaries::RtcStats,
138
139 #[serde(flatten)]
140 pub codec: dictionaries::CodecStats,
141 }
142
143 #[derive(Debug, Default, Clone, Deserialize)]
144 pub struct InboundRtpStats {
145 #[serde(flatten)]
146 pub rtc: dictionaries::RtcStats,
147
148 #[serde(flatten)]
149 pub stream: dictionaries::RtpStreamStats,
150
151 #[serde(flatten)]
152 pub received: dictionaries::ReceivedRtpStreamStats,
153
154 #[serde(flatten)]
155 pub inbound: dictionaries::InboundRtpStreamStats,
156 }
157
158 #[derive(Debug, Default, Clone, Deserialize)]
159 pub struct OutboundRtpStats {
160 #[serde(flatten)]
161 pub rtc: dictionaries::RtcStats,
162
163 #[serde(flatten)]
164 pub stream: dictionaries::RtpStreamStats,
165
166 #[serde(flatten)]
167 pub sent: dictionaries::SentRtpStreamStats,
168
169 #[serde(flatten)]
170 pub outbound: dictionaries::OutboundRtpStreamStats,
171 }
172
173 #[derive(Debug, Default, Clone, Deserialize)]
174 pub struct RemoteInboundRtpStats {
175 #[serde(flatten)]
176 pub rtc: dictionaries::RtcStats,
177
178 #[serde(flatten)]
179 pub stream: dictionaries::RtpStreamStats,
180
181 #[serde(flatten)]
182 pub received: dictionaries::ReceivedRtpStreamStats,
183
184 #[serde(flatten)]
185 pub remote_inbound: dictionaries::RemoteInboundRtpStreamStats,
186 }
187
188 #[derive(Debug, Default, Clone, Deserialize)]
189 pub struct RemoteOutboundRtpStats {
190 #[serde(flatten)]
191 pub rtc: dictionaries::RtcStats,
192
193 #[serde(flatten)]
194 pub stream: dictionaries::RtpStreamStats,
195
196 #[serde(flatten)]
197 pub sent: dictionaries::SentRtpStreamStats,
198
199 #[serde(flatten)]
200 pub remote_outbound: dictionaries::RemoteOutboundRtpStreamStats,
201 }
202
203 #[derive(Debug, Default, Clone, Deserialize)]
204 pub struct MediaSourceStats {
205 #[serde(flatten)]
206 pub rtc: dictionaries::RtcStats,
207
208 #[serde(flatten)]
209 pub source: dictionaries::MediaSourceStats,
210
211 #[serde(flatten)]
212 pub audio: dictionaries::AudioSourceStats,
213
214 #[serde(flatten)]
215 pub video: dictionaries::VideoSourceStats,
216 }
217
218 #[derive(Debug, Default, Clone, Deserialize)]
219 pub struct MediaPlayoutStats {
220 #[serde(flatten)]
221 pub rtc: dictionaries::RtcStats,
222
223 #[serde(flatten)]
224 pub audio_playout: dictionaries::AudioPlayoutStats,
225 }
226
227 #[derive(Debug, Default, Clone, Deserialize)]
228 pub struct PeerConnectionStats {
229 #[serde(flatten)]
230 pub rtc: dictionaries::RtcStats,
231
232 #[serde(flatten)]
233 pub pc: dictionaries::PeerConnectionStats,
234 }
235
236 #[derive(Debug, Default, Clone, Deserialize)]
237 pub struct DataChannelStats {
238 #[serde(flatten)]
239 pub rtc: dictionaries::RtcStats,
240
241 #[serde(flatten)]
242 pub dc: dictionaries::DataChannelStats,
243 }
244
245 #[derive(Debug, Default, Clone, Deserialize)]
246 pub struct TransportStats {
247 #[serde(flatten)]
248 pub rtc: dictionaries::RtcStats,
249
250 #[serde(flatten)]
251 pub transport: dictionaries::TransportStats,
252 }
253
254 #[derive(Debug, Default, Clone, Deserialize)]
255 pub struct CandidatePairStats {
256 #[serde(flatten)]
257 pub rtc: dictionaries::RtcStats,
258
259 #[serde(flatten)]
260 pub candidate_pair: dictionaries::CandidatePairStats,
261 }
262
263 #[derive(Debug, Default, Clone, Deserialize)]
264 pub struct LocalCandidateStats {
265 #[serde(flatten)]
266 pub rtc: dictionaries::RtcStats,
267
268 #[serde(flatten)]
269 pub local_candidate: dictionaries::IceCandidateStats,
270 }
271
272 #[derive(Debug, Default, Clone, Deserialize)]
273 pub struct RemoteCandidateStats {
274 #[serde(flatten)]
275 pub rtc: dictionaries::RtcStats,
276
277 #[serde(flatten)]
278 pub remote_candidate: dictionaries::IceCandidateStats,
279 }
280
281 #[derive(Debug, Default, Clone, Deserialize)]
282 pub struct CertificateStats {
283 #[serde(flatten)]
284 pub rtc: dictionaries::RtcStats,
285
286 #[serde(flatten)]
287 pub certificate: dictionaries::CertificateStats,
288 }
289
290 #[derive(Debug, Default, Clone, Deserialize)]
291 pub struct StreamStats {
292 #[serde(flatten)]
293 pub rtc: dictionaries::RtcStats,
294
295 #[serde(flatten)]
296 pub stream: dictionaries::StreamStats,
297 }
298
299 #[derive(Debug, Default, Clone, Deserialize)]
300 pub struct TrackStats {}
301
302 pub mod dictionaries {
303 use super::*;
304
305 #[derive(Debug, Default, Clone, Deserialize)]
306 #[serde(rename_all = "camelCase")]
307 #[serde(default)]
308 pub struct RtcStats {
309 pub id: String,
310 pub timestamp: i64,
311 }
312
313 #[derive(Debug, Default, Clone, Deserialize)]
314 #[serde(rename_all = "camelCase")]
315 #[serde(default)]
316 pub struct CodecStats {
317 pub payload_type: u32,
318 pub transport_id: String,
319 pub mime_type: String,
320 pub clock_rate: u32,
321 pub channels: u32,
322 pub sdp_fmtp_line: String,
323 }
324
325 #[derive(Debug, Default, Clone, Deserialize)]
326 #[serde(rename_all = "camelCase")]
327 #[serde(default)]
328 pub struct RtpStreamStats {
329 pub ssrc: u32,
330 pub kind: String,
331 pub transport_id: String,
332 pub codec_id: String,
333 }
334
335 #[derive(Debug, Default, Clone, Deserialize)]
336 #[serde(rename_all = "camelCase")]
337 #[serde(default)]
338 pub struct ReceivedRtpStreamStats {
339 pub packets_received: u64,
340 pub packets_lost: i64,
341 pub jitter: f64,
342 }
343
344 #[derive(Debug, Default, Clone, Deserialize)]
345 #[serde(rename_all = "camelCase")]
346 #[serde(default)]
347 pub struct InboundRtpStreamStats {
348 pub track_identifier: String,
349 pub mid: String,
350 pub remote_id: String,
351 pub frames_decoded: u32,
352 pub key_frames_decoded: u32,
353 pub frames_rendered: u32,
354 pub frames_dropped: u32,
355 pub frame_width: u32,
356 pub frame_height: u32,
357 pub frames_per_second: f64,
358 pub qp_sum: u64,
359 pub total_decode_time: f64,
360 pub total_inter_frame_delay: f64,
361 pub total_squared_inter_frame_delay: f64,
362 pub pause_count: u32,
363 pub total_pause_duration: f64,
364 pub freeze_count: u32,
365 pub total_freeze_duration: f64,
366 pub last_packet_received_timestamp: f64,
367 pub header_bytes_received: u64,
368 pub packets_discarded: u64,
369 pub fec_bytes_received: u64,
370 pub fec_packets_received: u64,
371 pub fec_packets_discarded: u64,
372 pub bytes_received: u64,
373 pub nack_count: u32,
374 pub fir_count: u32,
375 pub pli_count: u32,
376 pub total_processing_delay: f64,
377 pub estimated_playout_timestamp: f64,
378 pub jitter_buffer_delay: f64,
379 pub jitter_buffer_target_delay: f64,
380 pub jitter_buffer_emitted_count: u64,
381 pub jitter_buffer_minimum_delay: f64,
382 pub total_samples_received: u64,
383 pub concealed_samples: u64,
384 pub silent_concealed_samples: u64,
385 pub concealment_events: u64,
386 pub inserted_samples_for_deceleration: u64,
387 pub removed_samples_for_acceleration: u64,
388 pub audio_level: f64,
389 pub total_audio_energy: f64,
390 pub total_samples_duration: f64,
391 pub frames_received: u64,
392 pub decoder_implementation: String,
393 pub playout_id: String,
394 pub power_efficient_decoder: bool,
395 pub frames_assembled_from_multiple_packets: u64,
396 pub total_assembly_time: f64,
397 pub retransmitted_packets_received: u64,
398 pub retransmitted_bytes_received: u64,
399 pub rtx_ssrc: u32,
400 pub fec_ssrc: u32,
401 }
402
403 #[derive(Debug, Default, Clone, Deserialize)]
404 #[serde(rename_all = "camelCase")]
405 #[serde(default)]
406 pub struct SentRtpStreamStats {
407 pub packets_sent: u64,
408 pub bytes_sent: u64,
409 }
410
411 #[derive(Debug, Default, Clone, Deserialize)]
412 #[serde(rename_all = "camelCase")]
413 #[serde(default)]
414 pub struct OutboundRtpStreamStats {
415 pub mid: String,
416 pub media_source_id: String,
417 pub remote_id: String,
418 pub rid: String,
419 pub header_bytes_sent: u64,
420 pub retransmitted_packets_sent: u64,
421 pub retransmitted_bytes_sent: u64,
422 pub rtx_ssrc: u32,
423 pub target_bitrate: f64,
424 pub total_encoded_bytes_target: u64,
425 pub frame_width: u32,
426 pub frame_height: u32,
427 pub frames_per_second: f64,
428 pub frames_sent: u32,
429 pub huge_frames_sent: u32,
430 pub frames_encoded: u32,
431 pub key_frames_encoded: u32,
432 pub qp_sum: u64,
433 pub total_encode_time: f64,
434 pub total_packet_send_delay: f64,
435 pub quality_limitation_reason: QualityLimitationReason,
436 pub quality_limitation_durations: HashMap<String, f64>,
437 pub quality_limitation_resolution_changes: u32,
438 pub nack_count: u32,
439 pub fir_count: u32,
440 pub pli_count: u32,
441 pub encoder_implementation: String,
442 pub power_efficient_encoder: bool,
443 pub active: bool,
444 pub scalibility_mode: String,
445 }
446
447 #[derive(Debug, Default, Clone, Deserialize)]
448 #[serde(rename_all = "camelCase")]
449 #[serde(default)]
450 pub struct RemoteInboundRtpStreamStats {
451 pub local_id: String,
452 pub round_trip_time: f64,
453 pub total_round_trip_time: f64,
454 pub fraction_lost: f64,
455 pub round_trip_time_measurements: u64,
456 }
457
458 #[derive(Debug, Default, Clone, Deserialize)]
459 #[serde(rename_all = "camelCase")]
460 #[serde(default)]
461 pub struct RemoteOutboundRtpStreamStats {
462 pub local_id: String,
463 pub remote_timestamp: f64,
464 pub reports_sent: u64,
465 pub round_trip_time: f64,
466 pub total_round_trip_time: f64,
467 pub round_trip_time_measurements: u64,
468 }
469
470 #[derive(Debug, Default, Clone, Deserialize)]
471 #[serde(rename_all = "camelCase")]
472 #[serde(default)]
473 pub struct MediaSourceStats {
474 pub track_identifier: String,
475 pub kind: String,
476 }
477
478 #[derive(Debug, Default, Clone, Deserialize)]
479 #[serde(rename_all = "camelCase")]
480 #[serde(default)]
481 pub struct AudioSourceStats {
482 pub audio_level: f64,
483 pub total_audio_energy: f64,
484 pub total_samples_duration: f64,
485 pub echo_return_loss: f64,
486 pub echo_return_loss_enhancement: f64,
487 pub dropped_samples_duration: f64,
488 pub dropped_samples_events: u32,
489 pub total_capture_delay: f64,
490 pub total_samples_captured: u64,
491 }
492
493 #[derive(Debug, Default, Clone, Deserialize)]
494 #[serde(rename_all = "camelCase")]
495 #[serde(default)]
496 pub struct VideoSourceStats {
497 pub width: u32,
498 pub height: u32,
499 pub frames: u32,
500 pub frames_per_second: f64,
501 }
502
503 #[derive(Debug, Default, Clone, Deserialize)]
504 #[serde(rename_all = "camelCase")]
505 #[serde(default)]
506 pub struct AudioPlayoutStats {
507 pub kind: String,
508 pub synthesized_samples_duration: f64,
509 pub synthesized_samples_events: u32,
510 pub total_samples_duration: f64,
511 pub total_playout_delay: f64,
512 pub total_samples_count: u64,
513 }
514
515 #[derive(Debug, Default, Clone, Deserialize)]
516 #[serde(rename_all = "camelCase")]
517 #[serde(default)]
518 pub struct PeerConnectionStats {
519 pub data_channels_opened: u32,
520 pub data_channels_closed: u32,
521 }
522
523 #[derive(Debug, Default, Clone, Deserialize)]
524 #[serde(rename_all = "camelCase")]
525 #[serde(default)]
526 pub struct DataChannelStats {
527 pub label: String,
528 pub protocol: String,
529 pub data_channel_identifier: i32,
530 pub state: Option<DataChannelState>,
531 pub messages_sent: u32,
532 pub bytes_sent: u64,
533 pub messages_received: u32,
534 pub bytes_received: u64,
535 }
536
537 #[derive(Debug, Default, Clone, Deserialize)]
538 #[serde(rename_all = "camelCase")]
539 #[serde(default)]
540 pub struct TransportStats {
541 pub packets_sent: u64,
542 pub packets_received: u64,
543 pub bytes_sent: u64,
544 pub bytes_received: u64,
545 pub ice_role: IceRole,
546 pub ice_local_username_fragment: String,
547 pub dtls_state: Option<DtlsTransportState>,
548 pub ice_state: Option<IceTransportState>,
549 pub selected_candidate_pair_id: String,
550 pub local_certificate_id: String,
551 pub remote_certificate_id: String,
552 pub tls_version: String,
553 pub dtls_cipher: String,
554 pub dtls_role: DtlsRole,
555 pub srtp_cipher: String,
556 pub selected_candidate_pair_changes: u32,
557 }
558
559 #[derive(Debug, Default, Clone, Deserialize)]
560 #[serde(rename_all = "camelCase")]
561 #[serde(default)]
562 pub struct CandidatePairStats {
563 pub transport_id: String,
564 pub local_candidate_id: String,
565 pub remote_candidate_id: String,
566 pub state: Option<IceCandidatePairState>,
567 pub nominated: bool,
568 pub packets_sent: u64,
569 pub packets_received: u64,
570 pub bytes_sent: u64,
571 pub bytes_received: u64,
572 pub last_packet_sent_timestamp: f64,
573 pub last_packet_received_timestamp: f64,
574 pub total_round_trip_time: f64,
575 pub current_round_trip_time: f64,
576 pub available_outgoing_bitrate: f64,
577 pub available_incoming_bitrate: f64,
578 pub requests_received: u64,
579 pub requests_sent: u64,
580 pub responses_received: u64,
581 pub responses_sent: u64,
582 pub consent_requests_sent: u64,
583 pub packets_discarded_on_send: u32,
584 pub bytes_discarded_on_send: u64,
585 }
586
587 #[derive(Debug, Default, Clone, Deserialize)]
588 #[serde(rename_all = "camelCase")]
589 #[serde(default)]
590 pub struct IceCandidateStats {
591 pub transport_id: String,
592 pub address: String,
593 pub port: i32,
594 pub protocol: String,
595 pub candidate_type: Option<IceCandidateType>,
596 pub priority: i32,
597 pub url: String,
598 pub relay_protocol: Option<IceServerTransportProtocol>,
599 pub foundation: String,
600 pub related_address: String,
601 pub related_port: i32,
602 pub username_fragment: String,
603 pub tcp_type: Option<IceTcpCandidateType>,
604 /// Chromium's non-standard `RTCIceCandidateStats.networkType` (WiFi, cellular, ethernet,
605 /// etc.), reported only for local candidates.
606 pub network_type: Option<String>,
607 }
608
609 #[derive(Debug, Default, Clone, Deserialize)]
610 #[serde(rename_all = "camelCase")]
611 #[serde(default)]
612 pub struct CertificateStats {
613 pub fingerprint: String,
614 pub fingerprint_algorithm: String,
615 pub base64_certificate: String,
616 pub issuer_certificate_id: String,
617 }
618
619 #[derive(Debug, Default, Clone, Deserialize)]
620 #[serde(rename_all = "camelCase")]
621 #[serde(default)]
622 pub struct StreamStats {
623 pub id: String,
624 pub stream_identifier: String,
625 // pub timestamp: i64,
626 }
627 }
@@ -0,0 +1,627 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16
17use serde::Deserialize;
18
19use crate::data_channel::DataChannelState;
20
21/// Values from https://www.w3.org/TR/webrtc-stats/ (NOTE: Some of the structs are not in the SPEC
22/// but inside libwebrtc)
23/// serde will handle the magic of correctly deserializing the json into our structs.
24/// The enums values are inside encapsulated inside option because we're not sure about their
25/// default values (So we default to None instead of an arbitrary value)
26
27#[derive(Debug, Clone, Deserialize)]
28#[serde(tag = "type")]
29#[serde(rename_all = "kebab-case")]
30pub enum RtcStats {
31 Codec(CodecStats),
32 InboundRtp(InboundRtpStats),
33 OutboundRtp(OutboundRtpStats),
34 RemoteInboundRtp(RemoteInboundRtpStats),
35 RemoteOutboundRtp(RemoteOutboundRtpStats),
36 MediaSource(MediaSourceStats),
37 MediaPlayout(MediaPlayoutStats),
38 PeerConnection(PeerConnectionStats),
39 DataChannel(DataChannelStats),
40 Transport(TransportStats),
41 CandidatePair(CandidatePairStats),
42 LocalCandidate(LocalCandidateStats),
43 RemoteCandidate(RemoteCandidateStats),
44 Certificate(CertificateStats),
45 Stream(StreamStats),
46 Track, // Deprecated
47}
48
49#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Deserialize)]
50#[serde(rename_all = "lowercase")]
51pub enum QualityLimitationReason {
52 #[default]
53 None,
54 Cpu,
55 Bandwidth,
56 Other,
57}
58
59#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Deserialize)]
60#[serde(rename_all = "lowercase")]
61pub enum IceRole {
62 #[default]
63 Unknown,
64 Controlling,
65 Controlled,
66}
67
68#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
69#[serde(rename_all = "lowercase")]
70pub enum DtlsTransportState {
71 New,
72 Connecting,
73 Connected,
74 Closed,
75 Failed,
76}
77
78#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
79#[serde(rename_all = "lowercase")]
80pub enum IceTransportState {
81 New,
82 Checking,
83 Connected,
84 Completed,
85 Disconnected,
86 Failed,
87 Closed,
88}
89
90#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Deserialize)]
91#[serde(rename_all = "lowercase")]
92pub enum DtlsRole {
93 Client,
94 Server,
95 #[default]
96 Unknown,
97}
98
99#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
100#[serde(rename_all = "kebab-case")]
101pub enum IceCandidatePairState {
102 Frozen,
103 Waiting,
104 InProgress, // in-progress
105 Failed,
106 Succeeded,
107}
108
109#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
110#[serde(rename_all = "lowercase")]
111pub enum IceCandidateType {
112 Host,
113 Srflx,
114 Prflx,
115 Relay,
116}
117
118#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
119#[serde(rename_all = "lowercase")]
120pub enum IceServerTransportProtocol {
121 Udp,
122 Tcp,
123 Tls,
124}
125
126#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
127#[serde(rename_all = "lowercase")]
128pub enum IceTcpCandidateType {
129 Active,
130 Passive,
131 So,
132}
133
134#[derive(Debug, Default, Clone, Deserialize)]
135pub struct CodecStats {
136 #[serde(flatten)]
137 pub rtc: dictionaries::RtcStats,
138
139 #[serde(flatten)]
140 pub codec: dictionaries::CodecStats,
141}
142
143#[derive(Debug, Default, Clone, Deserialize)]
144pub struct InboundRtpStats {
145 #[serde(flatten)]
146 pub rtc: dictionaries::RtcStats,
147
148 #[serde(flatten)]
149 pub stream: dictionaries::RtpStreamStats,
150
151 #[serde(flatten)]
152 pub received: dictionaries::ReceivedRtpStreamStats,
153
154 #[serde(flatten)]
155 pub inbound: dictionaries::InboundRtpStreamStats,
156}
157
158#[derive(Debug, Default, Clone, Deserialize)]
159pub struct OutboundRtpStats {
160 #[serde(flatten)]
161 pub rtc: dictionaries::RtcStats,
162
163 #[serde(flatten)]
164 pub stream: dictionaries::RtpStreamStats,
165
166 #[serde(flatten)]
167 pub sent: dictionaries::SentRtpStreamStats,
168
169 #[serde(flatten)]
170 pub outbound: dictionaries::OutboundRtpStreamStats,
171}
172
173#[derive(Debug, Default, Clone, Deserialize)]
174pub struct RemoteInboundRtpStats {
175 #[serde(flatten)]
176 pub rtc: dictionaries::RtcStats,
177
178 #[serde(flatten)]
179 pub stream: dictionaries::RtpStreamStats,
180
181 #[serde(flatten)]
182 pub received: dictionaries::ReceivedRtpStreamStats,
183
184 #[serde(flatten)]
185 pub remote_inbound: dictionaries::RemoteInboundRtpStreamStats,
186}
187
188#[derive(Debug, Default, Clone, Deserialize)]
189pub struct RemoteOutboundRtpStats {
190 #[serde(flatten)]
191 pub rtc: dictionaries::RtcStats,
192
193 #[serde(flatten)]
194 pub stream: dictionaries::RtpStreamStats,
195
196 #[serde(flatten)]
197 pub sent: dictionaries::SentRtpStreamStats,
198
199 #[serde(flatten)]
200 pub remote_outbound: dictionaries::RemoteOutboundRtpStreamStats,
201}
202
203#[derive(Debug, Default, Clone, Deserialize)]
204pub struct MediaSourceStats {
205 #[serde(flatten)]
206 pub rtc: dictionaries::RtcStats,
207
208 #[serde(flatten)]
209 pub source: dictionaries::MediaSourceStats,
210
211 #[serde(flatten)]
212 pub audio: dictionaries::AudioSourceStats,
213
214 #[serde(flatten)]
215 pub video: dictionaries::VideoSourceStats,
216}
217
218#[derive(Debug, Default, Clone, Deserialize)]
219pub struct MediaPlayoutStats {
220 #[serde(flatten)]
221 pub rtc: dictionaries::RtcStats,
222
223 #[serde(flatten)]
224 pub audio_playout: dictionaries::AudioPlayoutStats,
225}
226
227#[derive(Debug, Default, Clone, Deserialize)]
228pub struct PeerConnectionStats {
229 #[serde(flatten)]
230 pub rtc: dictionaries::RtcStats,
231
232 #[serde(flatten)]
233 pub pc: dictionaries::PeerConnectionStats,
234}
235
236#[derive(Debug, Default, Clone, Deserialize)]
237pub struct DataChannelStats {
238 #[serde(flatten)]
239 pub rtc: dictionaries::RtcStats,
240
241 #[serde(flatten)]
242 pub dc: dictionaries::DataChannelStats,
243}
244
245#[derive(Debug, Default, Clone, Deserialize)]
246pub struct TransportStats {
247 #[serde(flatten)]
248 pub rtc: dictionaries::RtcStats,
249
250 #[serde(flatten)]
251 pub transport: dictionaries::TransportStats,
252}
253
254#[derive(Debug, Default, Clone, Deserialize)]
255pub struct CandidatePairStats {
256 #[serde(flatten)]
257 pub rtc: dictionaries::RtcStats,
258
259 #[serde(flatten)]
260 pub candidate_pair: dictionaries::CandidatePairStats,
261}
262
263#[derive(Debug, Default, Clone, Deserialize)]
264pub struct LocalCandidateStats {
265 #[serde(flatten)]
266 pub rtc: dictionaries::RtcStats,
267
268 #[serde(flatten)]
269 pub local_candidate: dictionaries::IceCandidateStats,
270}
271
272#[derive(Debug, Default, Clone, Deserialize)]
273pub struct RemoteCandidateStats {
274 #[serde(flatten)]
275 pub rtc: dictionaries::RtcStats,
276
277 #[serde(flatten)]
278 pub remote_candidate: dictionaries::IceCandidateStats,
279}
280
281#[derive(Debug, Default, Clone, Deserialize)]
282pub struct CertificateStats {
283 #[serde(flatten)]
284 pub rtc: dictionaries::RtcStats,
285
286 #[serde(flatten)]
287 pub certificate: dictionaries::CertificateStats,
288}
289
290#[derive(Debug, Default, Clone, Deserialize)]
291pub struct StreamStats {
292 #[serde(flatten)]
293 pub rtc: dictionaries::RtcStats,
294
295 #[serde(flatten)]
296 pub stream: dictionaries::StreamStats,
297}
298
299#[derive(Debug, Default, Clone, Deserialize)]
300pub struct TrackStats {}
301
302pub mod dictionaries {
303 use super::*;
304
305 #[derive(Debug, Default, Clone, Deserialize)]
306 #[serde(rename_all = "camelCase")]
307 #[serde(default)]
308 pub struct RtcStats {
309 pub id: String,
310 pub timestamp: i64,
311 }
312
313 #[derive(Debug, Default, Clone, Deserialize)]
314 #[serde(rename_all = "camelCase")]
315 #[serde(default)]
316 pub struct CodecStats {
317 pub payload_type: u32,
318 pub transport_id: String,
319 pub mime_type: String,
320 pub clock_rate: u32,
321 pub channels: u32,
322 pub sdp_fmtp_line: String,
323 }
324
325 #[derive(Debug, Default, Clone, Deserialize)]
326 #[serde(rename_all = "camelCase")]
327 #[serde(default)]
328 pub struct RtpStreamStats {
329 pub ssrc: u32,
330 pub kind: String,
331 pub transport_id: String,
332 pub codec_id: String,
333 }
334
335 #[derive(Debug, Default, Clone, Deserialize)]
336 #[serde(rename_all = "camelCase")]
337 #[serde(default)]
338 pub struct ReceivedRtpStreamStats {
339 pub packets_received: u64,
340 pub packets_lost: i64,
341 pub jitter: f64,
342 }
343
344 #[derive(Debug, Default, Clone, Deserialize)]
345 #[serde(rename_all = "camelCase")]
346 #[serde(default)]
347 pub struct InboundRtpStreamStats {
348 pub track_identifier: String,
349 pub mid: String,
350 pub remote_id: String,
351 pub frames_decoded: u32,
352 pub key_frames_decoded: u32,
353 pub frames_rendered: u32,
354 pub frames_dropped: u32,
355 pub frame_width: u32,
356 pub frame_height: u32,
357 pub frames_per_second: f64,
358 pub qp_sum: u64,
359 pub total_decode_time: f64,
360 pub total_inter_frame_delay: f64,
361 pub total_squared_inter_frame_delay: f64,
362 pub pause_count: u32,
363 pub total_pause_duration: f64,
364 pub freeze_count: u32,
365 pub total_freeze_duration: f64,
366 pub last_packet_received_timestamp: f64,
367 pub header_bytes_received: u64,
368 pub packets_discarded: u64,
369 pub fec_bytes_received: u64,
370 pub fec_packets_received: u64,
371 pub fec_packets_discarded: u64,
372 pub bytes_received: u64,
373 pub nack_count: u32,
374 pub fir_count: u32,
375 pub pli_count: u32,
376 pub total_processing_delay: f64,
377 pub estimated_playout_timestamp: f64,
378 pub jitter_buffer_delay: f64,
379 pub jitter_buffer_target_delay: f64,
380 pub jitter_buffer_emitted_count: u64,
381 pub jitter_buffer_minimum_delay: f64,
382 pub total_samples_received: u64,
383 pub concealed_samples: u64,
384 pub silent_concealed_samples: u64,
385 pub concealment_events: u64,
386 pub inserted_samples_for_deceleration: u64,
387 pub removed_samples_for_acceleration: u64,
388 pub audio_level: f64,
389 pub total_audio_energy: f64,
390 pub total_samples_duration: f64,
391 pub frames_received: u64,
392 pub decoder_implementation: String,
393 pub playout_id: String,
394 pub power_efficient_decoder: bool,
395 pub frames_assembled_from_multiple_packets: u64,
396 pub total_assembly_time: f64,
397 pub retransmitted_packets_received: u64,
398 pub retransmitted_bytes_received: u64,
399 pub rtx_ssrc: u32,
400 pub fec_ssrc: u32,
401 }
402
403 #[derive(Debug, Default, Clone, Deserialize)]
404 #[serde(rename_all = "camelCase")]
405 #[serde(default)]
406 pub struct SentRtpStreamStats {
407 pub packets_sent: u64,
408 pub bytes_sent: u64,
409 }
410
411 #[derive(Debug, Default, Clone, Deserialize)]
412 #[serde(rename_all = "camelCase")]
413 #[serde(default)]
414 pub struct OutboundRtpStreamStats {
415 pub mid: String,
416 pub media_source_id: String,
417 pub remote_id: String,
418 pub rid: String,
419 pub header_bytes_sent: u64,
420 pub retransmitted_packets_sent: u64,
421 pub retransmitted_bytes_sent: u64,
422 pub rtx_ssrc: u32,
423 pub target_bitrate: f64,
424 pub total_encoded_bytes_target: u64,
425 pub frame_width: u32,
426 pub frame_height: u32,
427 pub frames_per_second: f64,
428 pub frames_sent: u32,
429 pub huge_frames_sent: u32,
430 pub frames_encoded: u32,
431 pub key_frames_encoded: u32,
432 pub qp_sum: u64,
433 pub total_encode_time: f64,
434 pub total_packet_send_delay: f64,
435 pub quality_limitation_reason: QualityLimitationReason,
436 pub quality_limitation_durations: HashMap<String, f64>,
437 pub quality_limitation_resolution_changes: u32,
438 pub nack_count: u32,
439 pub fir_count: u32,
440 pub pli_count: u32,
441 pub encoder_implementation: String,
442 pub power_efficient_encoder: bool,
443 pub active: bool,
444 pub scalibility_mode: String,
445 }
446
447 #[derive(Debug, Default, Clone, Deserialize)]
448 #[serde(rename_all = "camelCase")]
449 #[serde(default)]
450 pub struct RemoteInboundRtpStreamStats {
451 pub local_id: String,
452 pub round_trip_time: f64,
453 pub total_round_trip_time: f64,
454 pub fraction_lost: f64,
455 pub round_trip_time_measurements: u64,
456 }
457
458 #[derive(Debug, Default, Clone, Deserialize)]
459 #[serde(rename_all = "camelCase")]
460 #[serde(default)]
461 pub struct RemoteOutboundRtpStreamStats {
462 pub local_id: String,
463 pub remote_timestamp: f64,
464 pub reports_sent: u64,
465 pub round_trip_time: f64,
466 pub total_round_trip_time: f64,
467 pub round_trip_time_measurements: u64,
468 }
469
470 #[derive(Debug, Default, Clone, Deserialize)]
471 #[serde(rename_all = "camelCase")]
472 #[serde(default)]
473 pub struct MediaSourceStats {
474 pub track_identifier: String,
475 pub kind: String,
476 }
477
478 #[derive(Debug, Default, Clone, Deserialize)]
479 #[serde(rename_all = "camelCase")]
480 #[serde(default)]
481 pub struct AudioSourceStats {
482 pub audio_level: f64,
483 pub total_audio_energy: f64,
484 pub total_samples_duration: f64,
485 pub echo_return_loss: f64,
486 pub echo_return_loss_enhancement: f64,
487 pub dropped_samples_duration: f64,
488 pub dropped_samples_events: u32,
489 pub total_capture_delay: f64,
490 pub total_samples_captured: u64,
491 }
492
493 #[derive(Debug, Default, Clone, Deserialize)]
494 #[serde(rename_all = "camelCase")]
495 #[serde(default)]
496 pub struct VideoSourceStats {
497 pub width: u32,
498 pub height: u32,
499 pub frames: u32,
500 pub frames_per_second: f64,
501 }
502
503 #[derive(Debug, Default, Clone, Deserialize)]
504 #[serde(rename_all = "camelCase")]
505 #[serde(default)]
506 pub struct AudioPlayoutStats {
507 pub kind: String,
508 pub synthesized_samples_duration: f64,
509 pub synthesized_samples_events: u32,
510 pub total_samples_duration: f64,
511 pub total_playout_delay: f64,
512 pub total_samples_count: u64,
513 }
514
515 #[derive(Debug, Default, Clone, Deserialize)]
516 #[serde(rename_all = "camelCase")]
517 #[serde(default)]
518 pub struct PeerConnectionStats {
519 pub data_channels_opened: u32,
520 pub data_channels_closed: u32,
521 }
522
523 #[derive(Debug, Default, Clone, Deserialize)]
524 #[serde(rename_all = "camelCase")]
525 #[serde(default)]
526 pub struct DataChannelStats {
527 pub label: String,
528 pub protocol: String,
529 pub data_channel_identifier: i32,
530 pub state: Option<DataChannelState>,
531 pub messages_sent: u32,
532 pub bytes_sent: u64,
533 pub messages_received: u32,
534 pub bytes_received: u64,
535 }
536
537 #[derive(Debug, Default, Clone, Deserialize)]
538 #[serde(rename_all = "camelCase")]
539 #[serde(default)]
540 pub struct TransportStats {
541 pub packets_sent: u64,
542 pub packets_received: u64,
543 pub bytes_sent: u64,
544 pub bytes_received: u64,
545 pub ice_role: IceRole,
546 pub ice_local_username_fragment: String,
547 pub dtls_state: Option<DtlsTransportState>,
548 pub ice_state: Option<IceTransportState>,
549 pub selected_candidate_pair_id: String,
550 pub local_certificate_id: String,
551 pub remote_certificate_id: String,
552 pub tls_version: String,
553 pub dtls_cipher: String,
554 pub dtls_role: DtlsRole,
555 pub srtp_cipher: String,
556 pub selected_candidate_pair_changes: u32,
557 }
558
559 #[derive(Debug, Default, Clone, Deserialize)]
560 #[serde(rename_all = "camelCase")]
561 #[serde(default)]
562 pub struct CandidatePairStats {
563 pub transport_id: String,
564 pub local_candidate_id: String,
565 pub remote_candidate_id: String,
566 pub state: Option<IceCandidatePairState>,
567 pub nominated: bool,
568 pub packets_sent: u64,
569 pub packets_received: u64,
570 pub bytes_sent: u64,
571 pub bytes_received: u64,
572 pub last_packet_sent_timestamp: f64,
573 pub last_packet_received_timestamp: f64,
574 pub total_round_trip_time: f64,
575 pub current_round_trip_time: f64,
576 pub available_outgoing_bitrate: f64,
577 pub available_incoming_bitrate: f64,
578 pub requests_received: u64,
579 pub requests_sent: u64,
580 pub responses_received: u64,
581 pub responses_sent: u64,
582 pub consent_requests_sent: u64,
583 pub packets_discarded_on_send: u32,
584 pub bytes_discarded_on_send: u64,
585 }
586
587 #[derive(Debug, Default, Clone, Deserialize)]
588 #[serde(rename_all = "camelCase")]
589 #[serde(default)]
590 pub struct IceCandidateStats {
591 pub transport_id: String,
592 pub address: String,
593 pub port: i32,
594 pub protocol: String,
595 pub candidate_type: Option<IceCandidateType>,
596 pub priority: i32,
597 pub url: String,
598 pub relay_protocol: Option<IceServerTransportProtocol>,
599 pub foundation: String,
600 pub related_address: String,
601 pub related_port: i32,
602 pub username_fragment: String,
603 pub tcp_type: Option<IceTcpCandidateType>,
604 /// Chromium's non-standard `RTCIceCandidateStats.networkType` (WiFi, cellular, ethernet,
605 /// etc.), reported only for local candidates.
606 pub network_type: Option<String>,
607 }
608
609 #[derive(Debug, Default, Clone, Deserialize)]
610 #[serde(rename_all = "camelCase")]
611 #[serde(default)]
612 pub struct CertificateStats {
613 pub fingerprint: String,
614 pub fingerprint_algorithm: String,
615 pub base64_certificate: String,
616 pub issuer_certificate_id: String,
617 }
618
619 #[derive(Debug, Default, Clone, Deserialize)]
620 #[serde(rename_all = "camelCase")]
621 #[serde(default)]
622 pub struct StreamStats {
623 pub id: String,
624 pub stream_identifier: String,
625 // pub timestamp: i64,
626 }
627}
vendor/libwebrtc/src/video_frame.rs added +691 −0
@@ -0,0 +1,691 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::fmt::Debug;
16
17 use thiserror::Error;
18
19 use crate::{imp::video_frame as vf_imp, video_source::VideoResolution};
20
21 #[derive(Debug, Error)]
22 pub enum SinkError {
23 #[error("platform error: {0}")]
24 Platform(String),
25 }
26
27 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
28 pub enum VideoRotation {
29 VideoRotation0 = 0,
30 VideoRotation90 = 90,
31 VideoRotation180 = 180,
32 VideoRotation270 = 270,
33 }
34
35 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
36 pub enum VideoFormatType {
37 ARGB,
38 BGRA,
39 ABGR,
40 RGBA,
41 }
42
43 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
44 #[non_exhaustive]
45 pub enum VideoBufferType {
46 Native,
47 I420,
48 I420A,
49 I422,
50 I444,
51 I010,
52 NV12,
53 }
54
55 /// Metadata carried alongside a video frame via the packet trailer mechanism.
56 ///
57 /// Each field corresponds to an independently negotiable packet trailer feature
58 /// (`PTF_USER_TIMESTAMP`, `PTF_FRAME_ID`, `PTF_USER_DATA`), so individual fields
59 /// are `Option`.
60 #[derive(Debug, Clone)]
61 pub struct FrameMetadata {
62 /// Wall-clock capture time in microseconds, when `PTF_USER_TIMESTAMP` is enabled.
63 pub user_timestamp: Option<u64>,
64 /// Monotonically increasing frame identifier, when `PTF_FRAME_ID` is enabled.
65 pub frame_id: Option<u32>,
66 /// Arbitrary application-supplied bytes, when `PTF_USER_DATA` is enabled.
67 ///
68 /// Bounded by the packet trailer size budget (~232 bytes when the other
69 /// features are also active); oversize payloads are dropped on the send
70 /// side rather than truncated.
71 pub user_data: Option<Vec<u8>>,
72 }
73
74 /// Codec carried by a pre-encoded video access unit.
75 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
76 #[non_exhaustive]
77 pub enum EncodedVideoCodec {
78 /// H.264/AVC video.
79 H264,
80 /// H.265/HEVC video.
81 H265,
82 /// VP8 video.
83 VP8,
84 /// VP9 video.
85 VP9,
86 /// AV1 video.
87 AV1,
88 }
89
90 /// Frame type of a pre-encoded video access unit.
91 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
92 pub enum EncodedFrameType {
93 /// A key frame.
94 Key,
95 /// A delta frame.
96 Delta,
97 }
98
99 /// A pre-encoded video access unit ready for passthrough publishing.
100 #[derive(Debug, Clone)]
101 pub struct EncodedVideoFrame<'a> {
102 /// Encoded video codec.
103 pub codec: EncodedVideoCodec,
104 /// Encoded access-unit payload.
105 pub payload: &'a [u8],
106 /// Capture timestamp in microseconds.
107 pub timestamp_us: i64,
108 /// Encoded frame type.
109 pub frame_type: EncodedFrameType,
110 /// Encoded frame resolution in pixels.
111 pub resolution: VideoResolution,
112 /// Optional metadata to attach through packet trailers.
113 pub frame_metadata: Option<FrameMetadata>,
114 }
115
116 #[cfg(not(target_arch = "wasm32"))]
117 impl From<EncodedVideoCodec> for webrtc_sys::video_track::ffi::EncodedVideoCodec {
118 fn from(value: EncodedVideoCodec) -> Self {
119 match value {
120 EncodedVideoCodec::H264 => Self::H264,
121 EncodedVideoCodec::H265 => Self::H265,
122 EncodedVideoCodec::VP8 => Self::VP8,
123 EncodedVideoCodec::VP9 => Self::VP9,
124 EncodedVideoCodec::AV1 => Self::AV1,
125 }
126 }
127 }
128
129 #[cfg(not(target_arch = "wasm32"))]
130 impl From<EncodedFrameType> for webrtc_sys::video_track::ffi::EncodedFrameType {
131 fn from(value: EncodedFrameType) -> Self {
132 match value {
133 EncodedFrameType::Key => Self::Key,
134 EncodedFrameType::Delta => Self::Delta,
135 }
136 }
137 }
138
139 #[derive(Debug)]
140 pub struct VideoFrame<T>
141 where
142 T: AsRef<dyn VideoBuffer>,
143 {
144 pub rotation: VideoRotation,
145 pub timestamp_us: i64, // When the frame was captured in microseconds
146 /// Packet-trailer metadata, if any trailer features are active.
147 pub frame_metadata: Option<FrameMetadata>,
148 pub buffer: T,
149 }
150
151 impl<T: AsRef<dyn VideoBuffer>> VideoFrame<T> {
152 pub fn new(rotation: VideoRotation, buffer: T) -> Self {
153 Self { rotation, timestamp_us: 0, frame_metadata: None, buffer }
154 }
155 }
156
157 pub type BoxVideoBuffer = Box<dyn VideoBuffer>;
158 pub type BoxVideoFrame = VideoFrame<BoxVideoBuffer>;
159
160 pub(crate) mod internal {
161 use super::{I420Buffer, VideoFormatType};
162
163 pub trait BufferSealed: Send + Sync {
164 #[cfg(not(target_arch = "wasm32"))]
165 fn sys_handle(&self) -> &webrtc_sys::video_frame_buffer::ffi::VideoFrameBuffer;
166
167 #[cfg(not(target_arch = "wasm32"))]
168 fn to_i420(&self) -> I420Buffer;
169
170 #[cfg(not(target_arch = "wasm32"))]
171 fn to_argb(
172 &self,
173 format: VideoFormatType,
174 dst: &mut [u8],
175 dst_stride: u32,
176 dst_width: i32,
177 dst_height: i32,
178 );
179 }
180 }
181
182 pub trait VideoBuffer: internal::BufferSealed + Debug {
183 fn width(&self) -> u32;
184 fn height(&self) -> u32;
185 fn buffer_type(&self) -> VideoBufferType;
186
187 #[cfg(not(target_arch = "wasm32"))]
188 fn as_native(&self) -> Option<&native::NativeBuffer> {
189 None
190 }
191
192 fn as_i420(&self) -> Option<&I420Buffer> {
193 None
194 }
195
196 fn as_i420a(&self) -> Option<&I420ABuffer> {
197 None
198 }
199
200 fn as_i422(&self) -> Option<&I422Buffer> {
201 None
202 }
203
204 fn as_i444(&self) -> Option<&I444Buffer> {
205 None
206 }
207
208 fn as_i010(&self) -> Option<&I010Buffer> {
209 None
210 }
211
212 fn as_nv12(&self) -> Option<&NV12Buffer> {
213 None
214 }
215 }
216
217 macro_rules! new_buffer_type {
218 ($type:ident, $variant:ident, $as:ident) => {
219 pub struct $type {
220 pub(crate) handle: vf_imp::$type,
221 }
222
223 impl $crate::video_frame::internal::BufferSealed for $type {
224 #[cfg(not(target_arch = "wasm32"))]
225 fn sys_handle(&self) -> &webrtc_sys::video_frame_buffer::ffi::VideoFrameBuffer {
226 self.handle.sys_handle()
227 }
228
229 #[cfg(not(target_arch = "wasm32"))]
230 fn to_i420(&self) -> I420Buffer {
231 I420Buffer { handle: self.handle.to_i420() }
232 }
233
234 #[cfg(not(target_arch = "wasm32"))]
235 fn to_argb(
236 &self,
237 format: VideoFormatType,
238 dst: &mut [u8],
239 stride: u32,
240 width: i32,
241 height: i32,
242 ) {
243 self.handle.to_argb(format, dst, stride, width, height)
244 }
245 }
246
247 impl VideoBuffer for $type {
248 fn width(&self) -> u32 {
249 self.handle.width()
250 }
251
252 fn height(&self) -> u32 {
253 self.handle.height()
254 }
255
256 fn buffer_type(&self) -> VideoBufferType {
257 VideoBufferType::$variant
258 }
259
260 fn $as(&self) -> Option<&$type> {
261 Some(self)
262 }
263 }
264
265 impl Debug for $type {
266 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267 f.debug_struct(stringify!($type))
268 .field("width", &self.width())
269 .field("height", &self.height())
270 .finish()
271 }
272 }
273
274 impl AsRef<dyn VideoBuffer> for $type {
275 fn as_ref(&self) -> &(dyn VideoBuffer + 'static) {
276 self
277 }
278 }
279 };
280 }
281
282 new_buffer_type!(I420Buffer, I420, as_i420);
283 new_buffer_type!(I420ABuffer, I420A, as_i420a);
284 new_buffer_type!(I422Buffer, I422, as_i422);
285 new_buffer_type!(I444Buffer, I444, as_i444);
286 new_buffer_type!(I010Buffer, I010, as_i010);
287 new_buffer_type!(NV12Buffer, NV12, as_nv12);
288
289 impl I420Buffer {
290 pub fn with_strides(
291 width: u32,
292 height: u32,
293 stride_y: u32,
294 stride_u: u32,
295 stride_v: u32,
296 ) -> I420Buffer {
297 vf_imp::I420Buffer::new(width, height, stride_y, stride_u, stride_v)
298 }
299
300 pub fn new(width: u32, height: u32) -> I420Buffer {
301 Self::with_strides(width, height, width, (width + 1) / 2, (width + 1) / 2)
302 }
303
304 /// Like [`I420Buffer::new`], but with the pixel data initialized to black
305 /// (Y=0, U=V=128) instead of left uninitialized.
306 pub fn new_black(width: u32, height: u32) -> I420Buffer {
307 vf_imp::I420Buffer::new_black(width, height, width, (width + 1) / 2, (width + 1) / 2)
308 }
309
310 pub fn chroma_width(&self) -> u32 {
311 self.handle.chroma_width()
312 }
313
314 pub fn chroma_height(&self) -> u32 {
315 self.handle.chroma_height()
316 }
317
318 pub fn strides(&self) -> (u32, u32, u32) {
319 (self.handle.stride_y(), self.handle.stride_u(), self.handle.stride_v())
320 }
321
322 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
323 self.handle.data()
324 }
325
326 pub fn data_mut(&mut self) -> (&mut [u8], &mut [u8], &mut [u8]) {
327 let (data_y, data_u, data_v) = self.handle.data();
328 unsafe {
329 (
330 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u8, data_y.len()),
331 std::slice::from_raw_parts_mut(data_u.as_ptr() as *mut u8, data_u.len()),
332 std::slice::from_raw_parts_mut(data_v.as_ptr() as *mut u8, data_v.len()),
333 )
334 }
335 }
336
337 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> I420Buffer {
338 self.handle.scale(scaled_width, scaled_height)
339 }
340 }
341
342 impl I420ABuffer {
343 pub fn chroma_width(&self) -> u32 {
344 self.handle.chroma_width()
345 }
346
347 pub fn chroma_height(&self) -> u32 {
348 self.handle.chroma_height()
349 }
350
351 pub fn strides(&self) -> (u32, u32, u32, u32) {
352 (
353 self.handle.stride_y(),
354 self.handle.stride_u(),
355 self.handle.stride_v(),
356 self.handle.stride_a(),
357 )
358 }
359
360 #[allow(clippy::type_complexity)]
361 pub fn data(&self) -> (&[u8], &[u8], &[u8], Option<&[u8]>) {
362 self.handle.data()
363 }
364
365 #[allow(clippy::type_complexity)]
366 pub fn data_mut(&self) -> (&mut [u8], &mut [u8], &mut [u8], Option<&mut [u8]>) {
367 let (data_y, data_u, data_v, data_a) = self.handle.data();
368 unsafe {
369 (
370 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u8, data_y.len()),
371 std::slice::from_raw_parts_mut(data_u.as_ptr() as *mut u8, data_u.len()),
372 std::slice::from_raw_parts_mut(data_v.as_ptr() as *mut u8, data_v.len()),
373 data_a.map(|data_a| {
374 std::slice::from_raw_parts_mut(data_a.as_ptr() as *mut u8, data_a.len())
375 }),
376 )
377 }
378 }
379
380 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> I420ABuffer {
381 self.handle.scale(scaled_width, scaled_height)
382 }
383 }
384
385 impl I422Buffer {
386 pub fn with_strides(
387 width: u32,
388 height: u32,
389 stride_y: u32,
390 stride_u: u32,
391 stride_v: u32,
392 ) -> I422Buffer {
393 vf_imp::I422Buffer::new(width, height, stride_y, stride_u, stride_v)
394 }
395
396 pub fn new(width: u32, height: u32) -> I422Buffer {
397 Self::with_strides(width, height, width, (width + 1) / 2, (width + 1) / 2)
398 }
399
400 pub fn chroma_width(&self) -> u32 {
401 self.handle.chroma_width()
402 }
403
404 pub fn chroma_height(&self) -> u32 {
405 self.handle.chroma_height()
406 }
407
408 pub fn strides(&self) -> (u32, u32, u32) {
409 (self.handle.stride_y(), self.handle.stride_u(), self.handle.stride_v())
410 }
411
412 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
413 self.handle.data()
414 }
415
416 pub fn data_mut(&mut self) -> (&mut [u8], &mut [u8], &mut [u8]) {
417 let (data_y, data_u, data_v) = self.handle.data();
418 unsafe {
419 (
420 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u8, data_y.len()),
421 std::slice::from_raw_parts_mut(data_u.as_ptr() as *mut u8, data_u.len()),
422 std::slice::from_raw_parts_mut(data_v.as_ptr() as *mut u8, data_v.len()),
423 )
424 }
425 }
426
427 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> I422Buffer {
428 self.handle.scale(scaled_width, scaled_height)
429 }
430 }
431
432 impl I444Buffer {
433 pub fn with_strides(
434 width: u32,
435 height: u32,
436 stride_y: u32,
437 stride_u: u32,
438 stride_v: u32,
439 ) -> I444Buffer {
440 vf_imp::I444Buffer::new(width, height, stride_y, stride_u, stride_v)
441 }
442
443 pub fn new(width: u32, height: u32) -> I444Buffer {
444 Self::with_strides(width, height, width, width, width)
445 }
446
447 pub fn chroma_width(&self) -> u32 {
448 self.handle.chroma_width()
449 }
450
451 pub fn chroma_height(&self) -> u32 {
452 self.handle.chroma_height()
453 }
454
455 pub fn strides(&self) -> (u32, u32, u32) {
456 (self.handle.stride_y(), self.handle.stride_u(), self.handle.stride_v())
457 }
458
459 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
460 self.handle.data()
461 }
462
463 pub fn data_mut(&mut self) -> (&mut [u8], &mut [u8], &mut [u8]) {
464 let (data_y, data_u, data_v) = self.handle.data();
465 unsafe {
466 (
467 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u8, data_y.len()),
468 std::slice::from_raw_parts_mut(data_u.as_ptr() as *mut u8, data_u.len()),
469 std::slice::from_raw_parts_mut(data_v.as_ptr() as *mut u8, data_v.len()),
470 )
471 }
472 }
473
474 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> I444Buffer {
475 self.handle.scale(scaled_width, scaled_height)
476 }
477 }
478
479 impl I010Buffer {
480 pub fn with_strides(
481 width: u32,
482 height: u32,
483 stride_y: u32,
484 stride_u: u32,
485 stride_v: u32,
486 ) -> I010Buffer {
487 vf_imp::I010Buffer::new(width, height, stride_y, stride_u, stride_v)
488 }
489
490 pub fn new(width: u32, height: u32) -> I010Buffer {
491 Self::with_strides(width, height, width, (width + 1) / 2, (width + 1) / 2)
492 }
493
494 pub fn chroma_width(&self) -> u32 {
495 self.handle.chroma_width()
496 }
497
498 pub fn chroma_height(&self) -> u32 {
499 self.handle.chroma_height()
500 }
501
502 pub fn strides(&self) -> (u32, u32, u32) {
503 (self.handle.stride_y(), self.handle.stride_u(), self.handle.stride_v())
504 }
505
506 pub fn data(&self) -> (&[u16], &[u16], &[u16]) {
507 self.handle.data()
508 }
509
510 pub fn data_mut(&mut self) -> (&mut [u16], &mut [u16], &mut [u16]) {
511 let (data_y, data_u, data_v) = self.handle.data();
512 unsafe {
513 (
514 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u16, data_y.len()),
515 std::slice::from_raw_parts_mut(data_u.as_ptr() as *mut u16, data_u.len()),
516 std::slice::from_raw_parts_mut(data_v.as_ptr() as *mut u16, data_v.len()),
517 )
518 }
519 }
520
521 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> I010Buffer {
522 self.handle.scale(scaled_width, scaled_height)
523 }
524 }
525
526 impl NV12Buffer {
527 pub fn with_strides(width: u32, height: u32, stride_y: u32, stride_uv: u32) -> NV12Buffer {
528 vf_imp::NV12Buffer::new(width, height, stride_y, stride_uv)
529 }
530
531 pub fn new(width: u32, height: u32) -> NV12Buffer {
532 Self::with_strides(width, height, width, width + width % 2)
533 }
534
535 pub fn chroma_width(&self) -> u32 {
536 self.handle.chroma_width()
537 }
538
539 pub fn chroma_height(&self) -> u32 {
540 self.handle.chroma_height()
541 }
542
543 pub fn strides(&self) -> (u32, u32) {
544 (self.handle.stride_y(), self.handle.stride_uv())
545 }
546
547 pub fn data(&self) -> (&[u8], &[u8]) {
548 self.handle.data()
549 }
550
551 pub fn data_mut(&mut self) -> (&mut [u8], &mut [u8]) {
552 let (data_y, data_uv) = self.handle.data();
553 unsafe {
554 (
555 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u8, data_y.len()),
556 std::slice::from_raw_parts_mut(data_uv.as_ptr() as *mut u8, data_uv.len()),
557 )
558 }
559 }
560
561 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> NV12Buffer {
562 self.handle.scale(scaled_width, scaled_height)
563 }
564 }
565
566 #[cfg(not(target_arch = "wasm32"))]
567 pub mod native {
568 use std::fmt::Debug;
569
570 use super::{vf_imp, I420Buffer, VideoBuffer, VideoBufferType, VideoFormatType};
571 #[cfg(target_os = "linux")]
572 use crate::video_source::VideoResolution;
573
574 new_buffer_type!(NativeBuffer, Native, as_native);
575
576 /// A borrowed DMA-BUF file descriptor.
577 ///
578 /// This is a plain [`RawFd`](std::os::fd::RawFd) (a C `int`, hence `i32`):
579 /// APIs taking this type borrow the descriptor rather than own it, so the
580 /// caller remains responsible for keeping it valid and closing it.
581 #[cfg(target_os = "linux")]
582 pub type DmaBufFileDescriptor = std::os::fd::RawFd;
583
584 /// Pixel format of a DMA-BUF backed video buffer.
585 #[cfg(target_os = "linux")]
586 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
587 #[non_exhaustive]
588 pub enum DmaBufPixelFormat {
589 NV12 = 0,
590 YUV420M = 1,
591 }
592
593 impl NativeBuffer {
594 /// Creates a `NativeBuffer` from a `CVPixelBufferRef` pointer.
595 ///
596 /// This function does not bump the reference count of the pixel buffer.
597 ///
598 /// Safety: The given pointer must be a valid `CVPixelBufferRef`.
599 #[cfg(any(target_os = "macos", target_os = "ios"))]
600 pub unsafe fn from_cv_pixel_buffer(cv_pixel_buffer: *mut std::ffi::c_void) -> Self {
601 vf_imp::NativeBuffer::from_cv_pixel_buffer(cv_pixel_buffer)
602 }
603
604 /// Returns the `CVPixelBufferRef` that backs this buffer, or `null` if
605 /// this buffer is not currently backed by a `CVPixelBufferRef`.
606 ///
607 /// This function does not bump the reference count of the pixel buffer.
608 #[cfg(any(target_os = "macos", target_os = "ios"))]
609 pub fn get_cv_pixel_buffer(&self) -> *mut std::ffi::c_void {
610 self.handle.get_cv_pixel_buffer()
611 }
612
613 /// Creates a `NativeBuffer` backed by a DMA-BUF file descriptor
614 /// (Jetson `NvBufSurface`), for zero-copy hand-off to the hardware
615 /// encoder.
616 ///
617 /// This function does not take ownership of the fd: the caller must
618 /// keep it valid until every frame captured from it has been consumed
619 /// by the encoder.
620 #[cfg(target_os = "linux")]
621 pub fn from_dmabuf(
622 dmabuf_fd: DmaBufFileDescriptor,
623 resolution: VideoResolution,
624 pixel_format: DmaBufPixelFormat,
625 ) -> Self {
626 vf_imp::NativeBuffer::from_dmabuf(dmabuf_fd, resolution, pixel_format)
627 }
628
629 /// Returns the DMA-BUF fd that backs this buffer, or `None` if this
630 /// buffer is not DMA-BUF backed.
631 ///
632 /// This function does not transfer ownership of the fd.
633 #[cfg(target_os = "linux")]
634 pub fn get_dmabuf_fd(&self) -> Option<DmaBufFileDescriptor> {
635 self.handle.get_dmabuf_fd()
636 }
637 }
638
639 pub trait VideoFrameBufferExt: VideoBuffer {
640 fn to_i420(&self) -> I420Buffer;
641 fn to_argb(
642 &self,
643 format: VideoFormatType,
644 dst: &mut [u8],
645 dst_stride: u32,
646 dst_width: i32,
647 dst_height: i32,
648 );
649 }
650
651 impl<T: VideoBuffer> VideoFrameBufferExt for T {
652 fn to_i420(&self) -> I420Buffer {
653 self.to_i420()
654 }
655
656 fn to_argb(
657 &self,
658 format: VideoFormatType,
659 dst: &mut [u8],
660 dst_stride: u32,
661 dst_width: i32,
662 dst_height: i32,
663 ) {
664 self.to_argb(format, dst, dst_stride, dst_width, dst_height)
665 }
666 }
667 }
668
669 #[cfg(target_arch = "wasm32")]
670 pub mod web {
671 use super::VideoFrameBuffer;
672
673 #[derive(Debug)]
674 pub struct WebGlBuffer {}
675
676 impl VideoFrameBuffer for WebGlBuffer {}
677 }
678
679 #[cfg(all(test, not(target_arch = "wasm32")))]
680 mod tests {
681 use super::I420Buffer;
682
683 #[test]
684 fn new_black_initializes_every_plane() {
685 let buffer = I420Buffer::new_black(64, 32);
686 let (data_y, data_u, data_v) = buffer.data();
687 assert!(data_y.iter().all(|&px| px == 0));
688 assert!(data_u.iter().all(|&px| px == 128));
689 assert!(data_v.iter().all(|&px| px == 128));
690 }
691 }
@@ -0,0 +1,691 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use thiserror::Error;
18
19use crate::{imp::video_frame as vf_imp, video_source::VideoResolution};
20
21#[derive(Debug, Error)]
22pub enum SinkError {
23 #[error("platform error: {0}")]
24 Platform(String),
25}
26
27#[derive(Debug, Copy, Clone, PartialEq, Eq)]
28pub enum VideoRotation {
29 VideoRotation0 = 0,
30 VideoRotation90 = 90,
31 VideoRotation180 = 180,
32 VideoRotation270 = 270,
33}
34
35#[derive(Debug, Copy, Clone, PartialEq, Eq)]
36pub enum VideoFormatType {
37 ARGB,
38 BGRA,
39 ABGR,
40 RGBA,
41}
42
43#[derive(Debug, Copy, Clone, PartialEq, Eq)]
44#[non_exhaustive]
45pub enum VideoBufferType {
46 Native,
47 I420,
48 I420A,
49 I422,
50 I444,
51 I010,
52 NV12,
53}
54
55/// Metadata carried alongside a video frame via the packet trailer mechanism.
56///
57/// Each field corresponds to an independently negotiable packet trailer feature
58/// (`PTF_USER_TIMESTAMP`, `PTF_FRAME_ID`, `PTF_USER_DATA`), so individual fields
59/// are `Option`.
60#[derive(Debug, Clone)]
61pub struct FrameMetadata {
62 /// Wall-clock capture time in microseconds, when `PTF_USER_TIMESTAMP` is enabled.
63 pub user_timestamp: Option<u64>,
64 /// Monotonically increasing frame identifier, when `PTF_FRAME_ID` is enabled.
65 pub frame_id: Option<u32>,
66 /// Arbitrary application-supplied bytes, when `PTF_USER_DATA` is enabled.
67 ///
68 /// Bounded by the packet trailer size budget (~232 bytes when the other
69 /// features are also active); oversize payloads are dropped on the send
70 /// side rather than truncated.
71 pub user_data: Option<Vec<u8>>,
72}
73
74/// Codec carried by a pre-encoded video access unit.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76#[non_exhaustive]
77pub enum EncodedVideoCodec {
78 /// H.264/AVC video.
79 H264,
80 /// H.265/HEVC video.
81 H265,
82 /// VP8 video.
83 VP8,
84 /// VP9 video.
85 VP9,
86 /// AV1 video.
87 AV1,
88}
89
90/// Frame type of a pre-encoded video access unit.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum EncodedFrameType {
93 /// A key frame.
94 Key,
95 /// A delta frame.
96 Delta,
97}
98
99/// A pre-encoded video access unit ready for passthrough publishing.
100#[derive(Debug, Clone)]
101pub struct EncodedVideoFrame<'a> {
102 /// Encoded video codec.
103 pub codec: EncodedVideoCodec,
104 /// Encoded access-unit payload.
105 pub payload: &'a [u8],
106 /// Capture timestamp in microseconds.
107 pub timestamp_us: i64,
108 /// Encoded frame type.
109 pub frame_type: EncodedFrameType,
110 /// Encoded frame resolution in pixels.
111 pub resolution: VideoResolution,
112 /// Optional metadata to attach through packet trailers.
113 pub frame_metadata: Option<FrameMetadata>,
114}
115
116#[cfg(not(target_arch = "wasm32"))]
117impl From<EncodedVideoCodec> for webrtc_sys::video_track::ffi::EncodedVideoCodec {
118 fn from(value: EncodedVideoCodec) -> Self {
119 match value {
120 EncodedVideoCodec::H264 => Self::H264,
121 EncodedVideoCodec::H265 => Self::H265,
122 EncodedVideoCodec::VP8 => Self::VP8,
123 EncodedVideoCodec::VP9 => Self::VP9,
124 EncodedVideoCodec::AV1 => Self::AV1,
125 }
126 }
127}
128
129#[cfg(not(target_arch = "wasm32"))]
130impl From<EncodedFrameType> for webrtc_sys::video_track::ffi::EncodedFrameType {
131 fn from(value: EncodedFrameType) -> Self {
132 match value {
133 EncodedFrameType::Key => Self::Key,
134 EncodedFrameType::Delta => Self::Delta,
135 }
136 }
137}
138
139#[derive(Debug)]
140pub struct VideoFrame<T>
141where
142 T: AsRef<dyn VideoBuffer>,
143{
144 pub rotation: VideoRotation,
145 pub timestamp_us: i64, // When the frame was captured in microseconds
146 /// Packet-trailer metadata, if any trailer features are active.
147 pub frame_metadata: Option<FrameMetadata>,
148 pub buffer: T,
149}
150
151impl<T: AsRef<dyn VideoBuffer>> VideoFrame<T> {
152 pub fn new(rotation: VideoRotation, buffer: T) -> Self {
153 Self { rotation, timestamp_us: 0, frame_metadata: None, buffer }
154 }
155}
156
157pub type BoxVideoBuffer = Box<dyn VideoBuffer>;
158pub type BoxVideoFrame = VideoFrame<BoxVideoBuffer>;
159
160pub(crate) mod internal {
161 use super::{I420Buffer, VideoFormatType};
162
163 pub trait BufferSealed: Send + Sync {
164 #[cfg(not(target_arch = "wasm32"))]
165 fn sys_handle(&self) -> &webrtc_sys::video_frame_buffer::ffi::VideoFrameBuffer;
166
167 #[cfg(not(target_arch = "wasm32"))]
168 fn to_i420(&self) -> I420Buffer;
169
170 #[cfg(not(target_arch = "wasm32"))]
171 fn to_argb(
172 &self,
173 format: VideoFormatType,
174 dst: &mut [u8],
175 dst_stride: u32,
176 dst_width: i32,
177 dst_height: i32,
178 );
179 }
180}
181
182pub trait VideoBuffer: internal::BufferSealed + Debug {
183 fn width(&self) -> u32;
184 fn height(&self) -> u32;
185 fn buffer_type(&self) -> VideoBufferType;
186
187 #[cfg(not(target_arch = "wasm32"))]
188 fn as_native(&self) -> Option<&native::NativeBuffer> {
189 None
190 }
191
192 fn as_i420(&self) -> Option<&I420Buffer> {
193 None
194 }
195
196 fn as_i420a(&self) -> Option<&I420ABuffer> {
197 None
198 }
199
200 fn as_i422(&self) -> Option<&I422Buffer> {
201 None
202 }
203
204 fn as_i444(&self) -> Option<&I444Buffer> {
205 None
206 }
207
208 fn as_i010(&self) -> Option<&I010Buffer> {
209 None
210 }
211
212 fn as_nv12(&self) -> Option<&NV12Buffer> {
213 None
214 }
215}
216
217macro_rules! new_buffer_type {
218 ($type:ident, $variant:ident, $as:ident) => {
219 pub struct $type {
220 pub(crate) handle: vf_imp::$type,
221 }
222
223 impl $crate::video_frame::internal::BufferSealed for $type {
224 #[cfg(not(target_arch = "wasm32"))]
225 fn sys_handle(&self) -> &webrtc_sys::video_frame_buffer::ffi::VideoFrameBuffer {
226 self.handle.sys_handle()
227 }
228
229 #[cfg(not(target_arch = "wasm32"))]
230 fn to_i420(&self) -> I420Buffer {
231 I420Buffer { handle: self.handle.to_i420() }
232 }
233
234 #[cfg(not(target_arch = "wasm32"))]
235 fn to_argb(
236 &self,
237 format: VideoFormatType,
238 dst: &mut [u8],
239 stride: u32,
240 width: i32,
241 height: i32,
242 ) {
243 self.handle.to_argb(format, dst, stride, width, height)
244 }
245 }
246
247 impl VideoBuffer for $type {
248 fn width(&self) -> u32 {
249 self.handle.width()
250 }
251
252 fn height(&self) -> u32 {
253 self.handle.height()
254 }
255
256 fn buffer_type(&self) -> VideoBufferType {
257 VideoBufferType::$variant
258 }
259
260 fn $as(&self) -> Option<&$type> {
261 Some(self)
262 }
263 }
264
265 impl Debug for $type {
266 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267 f.debug_struct(stringify!($type))
268 .field("width", &self.width())
269 .field("height", &self.height())
270 .finish()
271 }
272 }
273
274 impl AsRef<dyn VideoBuffer> for $type {
275 fn as_ref(&self) -> &(dyn VideoBuffer + 'static) {
276 self
277 }
278 }
279 };
280}
281
282new_buffer_type!(I420Buffer, I420, as_i420);
283new_buffer_type!(I420ABuffer, I420A, as_i420a);
284new_buffer_type!(I422Buffer, I422, as_i422);
285new_buffer_type!(I444Buffer, I444, as_i444);
286new_buffer_type!(I010Buffer, I010, as_i010);
287new_buffer_type!(NV12Buffer, NV12, as_nv12);
288
289impl I420Buffer {
290 pub fn with_strides(
291 width: u32,
292 height: u32,
293 stride_y: u32,
294 stride_u: u32,
295 stride_v: u32,
296 ) -> I420Buffer {
297 vf_imp::I420Buffer::new(width, height, stride_y, stride_u, stride_v)
298 }
299
300 pub fn new(width: u32, height: u32) -> I420Buffer {
301 Self::with_strides(width, height, width, (width + 1) / 2, (width + 1) / 2)
302 }
303
304 /// Like [`I420Buffer::new`], but with the pixel data initialized to black
305 /// (Y=0, U=V=128) instead of left uninitialized.
306 pub fn new_black(width: u32, height: u32) -> I420Buffer {
307 vf_imp::I420Buffer::new_black(width, height, width, (width + 1) / 2, (width + 1) / 2)
308 }
309
310 pub fn chroma_width(&self) -> u32 {
311 self.handle.chroma_width()
312 }
313
314 pub fn chroma_height(&self) -> u32 {
315 self.handle.chroma_height()
316 }
317
318 pub fn strides(&self) -> (u32, u32, u32) {
319 (self.handle.stride_y(), self.handle.stride_u(), self.handle.stride_v())
320 }
321
322 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
323 self.handle.data()
324 }
325
326 pub fn data_mut(&mut self) -> (&mut [u8], &mut [u8], &mut [u8]) {
327 let (data_y, data_u, data_v) = self.handle.data();
328 unsafe {
329 (
330 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u8, data_y.len()),
331 std::slice::from_raw_parts_mut(data_u.as_ptr() as *mut u8, data_u.len()),
332 std::slice::from_raw_parts_mut(data_v.as_ptr() as *mut u8, data_v.len()),
333 )
334 }
335 }
336
337 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> I420Buffer {
338 self.handle.scale(scaled_width, scaled_height)
339 }
340}
341
342impl I420ABuffer {
343 pub fn chroma_width(&self) -> u32 {
344 self.handle.chroma_width()
345 }
346
347 pub fn chroma_height(&self) -> u32 {
348 self.handle.chroma_height()
349 }
350
351 pub fn strides(&self) -> (u32, u32, u32, u32) {
352 (
353 self.handle.stride_y(),
354 self.handle.stride_u(),
355 self.handle.stride_v(),
356 self.handle.stride_a(),
357 )
358 }
359
360 #[allow(clippy::type_complexity)]
361 pub fn data(&self) -> (&[u8], &[u8], &[u8], Option<&[u8]>) {
362 self.handle.data()
363 }
364
365 #[allow(clippy::type_complexity)]
366 pub fn data_mut(&self) -> (&mut [u8], &mut [u8], &mut [u8], Option<&mut [u8]>) {
367 let (data_y, data_u, data_v, data_a) = self.handle.data();
368 unsafe {
369 (
370 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u8, data_y.len()),
371 std::slice::from_raw_parts_mut(data_u.as_ptr() as *mut u8, data_u.len()),
372 std::slice::from_raw_parts_mut(data_v.as_ptr() as *mut u8, data_v.len()),
373 data_a.map(|data_a| {
374 std::slice::from_raw_parts_mut(data_a.as_ptr() as *mut u8, data_a.len())
375 }),
376 )
377 }
378 }
379
380 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> I420ABuffer {
381 self.handle.scale(scaled_width, scaled_height)
382 }
383}
384
385impl I422Buffer {
386 pub fn with_strides(
387 width: u32,
388 height: u32,
389 stride_y: u32,
390 stride_u: u32,
391 stride_v: u32,
392 ) -> I422Buffer {
393 vf_imp::I422Buffer::new(width, height, stride_y, stride_u, stride_v)
394 }
395
396 pub fn new(width: u32, height: u32) -> I422Buffer {
397 Self::with_strides(width, height, width, (width + 1) / 2, (width + 1) / 2)
398 }
399
400 pub fn chroma_width(&self) -> u32 {
401 self.handle.chroma_width()
402 }
403
404 pub fn chroma_height(&self) -> u32 {
405 self.handle.chroma_height()
406 }
407
408 pub fn strides(&self) -> (u32, u32, u32) {
409 (self.handle.stride_y(), self.handle.stride_u(), self.handle.stride_v())
410 }
411
412 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
413 self.handle.data()
414 }
415
416 pub fn data_mut(&mut self) -> (&mut [u8], &mut [u8], &mut [u8]) {
417 let (data_y, data_u, data_v) = self.handle.data();
418 unsafe {
419 (
420 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u8, data_y.len()),
421 std::slice::from_raw_parts_mut(data_u.as_ptr() as *mut u8, data_u.len()),
422 std::slice::from_raw_parts_mut(data_v.as_ptr() as *mut u8, data_v.len()),
423 )
424 }
425 }
426
427 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> I422Buffer {
428 self.handle.scale(scaled_width, scaled_height)
429 }
430}
431
432impl I444Buffer {
433 pub fn with_strides(
434 width: u32,
435 height: u32,
436 stride_y: u32,
437 stride_u: u32,
438 stride_v: u32,
439 ) -> I444Buffer {
440 vf_imp::I444Buffer::new(width, height, stride_y, stride_u, stride_v)
441 }
442
443 pub fn new(width: u32, height: u32) -> I444Buffer {
444 Self::with_strides(width, height, width, width, width)
445 }
446
447 pub fn chroma_width(&self) -> u32 {
448 self.handle.chroma_width()
449 }
450
451 pub fn chroma_height(&self) -> u32 {
452 self.handle.chroma_height()
453 }
454
455 pub fn strides(&self) -> (u32, u32, u32) {
456 (self.handle.stride_y(), self.handle.stride_u(), self.handle.stride_v())
457 }
458
459 pub fn data(&self) -> (&[u8], &[u8], &[u8]) {
460 self.handle.data()
461 }
462
463 pub fn data_mut(&mut self) -> (&mut [u8], &mut [u8], &mut [u8]) {
464 let (data_y, data_u, data_v) = self.handle.data();
465 unsafe {
466 (
467 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u8, data_y.len()),
468 std::slice::from_raw_parts_mut(data_u.as_ptr() as *mut u8, data_u.len()),
469 std::slice::from_raw_parts_mut(data_v.as_ptr() as *mut u8, data_v.len()),
470 )
471 }
472 }
473
474 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> I444Buffer {
475 self.handle.scale(scaled_width, scaled_height)
476 }
477}
478
479impl I010Buffer {
480 pub fn with_strides(
481 width: u32,
482 height: u32,
483 stride_y: u32,
484 stride_u: u32,
485 stride_v: u32,
486 ) -> I010Buffer {
487 vf_imp::I010Buffer::new(width, height, stride_y, stride_u, stride_v)
488 }
489
490 pub fn new(width: u32, height: u32) -> I010Buffer {
491 Self::with_strides(width, height, width, (width + 1) / 2, (width + 1) / 2)
492 }
493
494 pub fn chroma_width(&self) -> u32 {
495 self.handle.chroma_width()
496 }
497
498 pub fn chroma_height(&self) -> u32 {
499 self.handle.chroma_height()
500 }
501
502 pub fn strides(&self) -> (u32, u32, u32) {
503 (self.handle.stride_y(), self.handle.stride_u(), self.handle.stride_v())
504 }
505
506 pub fn data(&self) -> (&[u16], &[u16], &[u16]) {
507 self.handle.data()
508 }
509
510 pub fn data_mut(&mut self) -> (&mut [u16], &mut [u16], &mut [u16]) {
511 let (data_y, data_u, data_v) = self.handle.data();
512 unsafe {
513 (
514 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u16, data_y.len()),
515 std::slice::from_raw_parts_mut(data_u.as_ptr() as *mut u16, data_u.len()),
516 std::slice::from_raw_parts_mut(data_v.as_ptr() as *mut u16, data_v.len()),
517 )
518 }
519 }
520
521 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> I010Buffer {
522 self.handle.scale(scaled_width, scaled_height)
523 }
524}
525
526impl NV12Buffer {
527 pub fn with_strides(width: u32, height: u32, stride_y: u32, stride_uv: u32) -> NV12Buffer {
528 vf_imp::NV12Buffer::new(width, height, stride_y, stride_uv)
529 }
530
531 pub fn new(width: u32, height: u32) -> NV12Buffer {
532 Self::with_strides(width, height, width, width + width % 2)
533 }
534
535 pub fn chroma_width(&self) -> u32 {
536 self.handle.chroma_width()
537 }
538
539 pub fn chroma_height(&self) -> u32 {
540 self.handle.chroma_height()
541 }
542
543 pub fn strides(&self) -> (u32, u32) {
544 (self.handle.stride_y(), self.handle.stride_uv())
545 }
546
547 pub fn data(&self) -> (&[u8], &[u8]) {
548 self.handle.data()
549 }
550
551 pub fn data_mut(&mut self) -> (&mut [u8], &mut [u8]) {
552 let (data_y, data_uv) = self.handle.data();
553 unsafe {
554 (
555 std::slice::from_raw_parts_mut(data_y.as_ptr() as *mut u8, data_y.len()),
556 std::slice::from_raw_parts_mut(data_uv.as_ptr() as *mut u8, data_uv.len()),
557 )
558 }
559 }
560
561 pub fn scale(&mut self, scaled_width: i32, scaled_height: i32) -> NV12Buffer {
562 self.handle.scale(scaled_width, scaled_height)
563 }
564}
565
566#[cfg(not(target_arch = "wasm32"))]
567pub mod native {
568 use std::fmt::Debug;
569
570 use super::{vf_imp, I420Buffer, VideoBuffer, VideoBufferType, VideoFormatType};
571 #[cfg(target_os = "linux")]
572 use crate::video_source::VideoResolution;
573
574 new_buffer_type!(NativeBuffer, Native, as_native);
575
576 /// A borrowed DMA-BUF file descriptor.
577 ///
578 /// This is a plain [`RawFd`](std::os::fd::RawFd) (a C `int`, hence `i32`):
579 /// APIs taking this type borrow the descriptor rather than own it, so the
580 /// caller remains responsible for keeping it valid and closing it.
581 #[cfg(target_os = "linux")]
582 pub type DmaBufFileDescriptor = std::os::fd::RawFd;
583
584 /// Pixel format of a DMA-BUF backed video buffer.
585 #[cfg(target_os = "linux")]
586 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
587 #[non_exhaustive]
588 pub enum DmaBufPixelFormat {
589 NV12 = 0,
590 YUV420M = 1,
591 }
592
593 impl NativeBuffer {
594 /// Creates a `NativeBuffer` from a `CVPixelBufferRef` pointer.
595 ///
596 /// This function does not bump the reference count of the pixel buffer.
597 ///
598 /// Safety: The given pointer must be a valid `CVPixelBufferRef`.
599 #[cfg(any(target_os = "macos", target_os = "ios"))]
600 pub unsafe fn from_cv_pixel_buffer(cv_pixel_buffer: *mut std::ffi::c_void) -> Self {
601 vf_imp::NativeBuffer::from_cv_pixel_buffer(cv_pixel_buffer)
602 }
603
604 /// Returns the `CVPixelBufferRef` that backs this buffer, or `null` if
605 /// this buffer is not currently backed by a `CVPixelBufferRef`.
606 ///
607 /// This function does not bump the reference count of the pixel buffer.
608 #[cfg(any(target_os = "macos", target_os = "ios"))]
609 pub fn get_cv_pixel_buffer(&self) -> *mut std::ffi::c_void {
610 self.handle.get_cv_pixel_buffer()
611 }
612
613 /// Creates a `NativeBuffer` backed by a DMA-BUF file descriptor
614 /// (Jetson `NvBufSurface`), for zero-copy hand-off to the hardware
615 /// encoder.
616 ///
617 /// This function does not take ownership of the fd: the caller must
618 /// keep it valid until every frame captured from it has been consumed
619 /// by the encoder.
620 #[cfg(target_os = "linux")]
621 pub fn from_dmabuf(
622 dmabuf_fd: DmaBufFileDescriptor,
623 resolution: VideoResolution,
624 pixel_format: DmaBufPixelFormat,
625 ) -> Self {
626 vf_imp::NativeBuffer::from_dmabuf(dmabuf_fd, resolution, pixel_format)
627 }
628
629 /// Returns the DMA-BUF fd that backs this buffer, or `None` if this
630 /// buffer is not DMA-BUF backed.
631 ///
632 /// This function does not transfer ownership of the fd.
633 #[cfg(target_os = "linux")]
634 pub fn get_dmabuf_fd(&self) -> Option<DmaBufFileDescriptor> {
635 self.handle.get_dmabuf_fd()
636 }
637 }
638
639 pub trait VideoFrameBufferExt: VideoBuffer {
640 fn to_i420(&self) -> I420Buffer;
641 fn to_argb(
642 &self,
643 format: VideoFormatType,
644 dst: &mut [u8],
645 dst_stride: u32,
646 dst_width: i32,
647 dst_height: i32,
648 );
649 }
650
651 impl<T: VideoBuffer> VideoFrameBufferExt for T {
652 fn to_i420(&self) -> I420Buffer {
653 self.to_i420()
654 }
655
656 fn to_argb(
657 &self,
658 format: VideoFormatType,
659 dst: &mut [u8],
660 dst_stride: u32,
661 dst_width: i32,
662 dst_height: i32,
663 ) {
664 self.to_argb(format, dst, dst_stride, dst_width, dst_height)
665 }
666 }
667}
668
669#[cfg(target_arch = "wasm32")]
670pub mod web {
671 use super::VideoFrameBuffer;
672
673 #[derive(Debug)]
674 pub struct WebGlBuffer {}
675
676 impl VideoFrameBuffer for WebGlBuffer {}
677}
678
679#[cfg(all(test, not(target_arch = "wasm32")))]
680mod tests {
681 use super::I420Buffer;
682
683 #[test]
684 fn new_black_initializes_every_plane() {
685 let buffer = I420Buffer::new_black(64, 32);
686 let (data_y, data_u, data_v) = buffer.data();
687 assert!(data_y.iter().all(|&px| px == 0));
688 assert!(data_u.iter().all(|&px| px == 128));
689 assert!(data_v.iter().all(|&px| px == 128));
690 }
691}
vendor/libwebrtc/src/video_source.rs added +193 −0
@@ -0,0 +1,193 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use crate::{enum_dispatch, imp::video_source as vs_imp};
16
17 #[derive(Debug, Clone)]
18 pub struct VideoResolution {
19 pub width: u32,
20 pub height: u32,
21 }
22
23 /// Encoder rate-control target requested by WebRTC for a pre-encoded source.
24 #[derive(Debug, Clone, Copy, PartialEq)]
25 pub struct EncodedRateControl {
26 /// Target bitrate in bits per second.
27 pub target_bitrate_bps: u64,
28 /// Target frame rate in frames per second.
29 pub framerate_fps: f64,
30 }
31
32 impl Default for VideoResolution {
33 // Default to 720p
34 fn default() -> Self {
35 VideoResolution { width: 1280, height: 720 }
36 }
37 }
38
39 #[non_exhaustive]
40 #[derive(Debug, Clone)]
41 pub enum RtcVideoSource {
42 // TODO(theomonnom): Web video sources (eq. to tracks on browsers?)
43 #[cfg(not(target_arch = "wasm32"))]
44 Native(native::NativeVideoSource),
45 }
46
47 // TODO(theomonnom): Support enum dispatch with conditional compilation?
48 impl RtcVideoSource {
49 enum_dispatch!(
50 [Native];
51 pub fn video_resolution(self: &Self) -> VideoResolution;
52 );
53 }
54
55 #[cfg(not(target_arch = "wasm32"))]
56 pub mod native {
57 use std::fmt::{Debug, Formatter};
58
59 use super::*;
60 use crate::native::packet_trailer::PacketTrailerHandler;
61 #[cfg(target_os = "linux")]
62 use crate::video_frame::{
63 native::{DmaBufPixelFormat, NativeBuffer},
64 FrameMetadata, VideoRotation,
65 };
66 use crate::video_frame::{EncodedVideoFrame, VideoBuffer, VideoFrame};
67
68 #[derive(Clone)]
69 pub struct NativeVideoSource {
70 pub(crate) handle: vs_imp::NativeVideoSource,
71 }
72
73 impl Debug for NativeVideoSource {
74 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
75 f.debug_struct("NativeVideoSource").finish()
76 }
77 }
78
79 impl Default for NativeVideoSource {
80 fn default() -> Self {
81 Self::new(VideoResolution::default(), false)
82 }
83 }
84
85 impl NativeVideoSource {
86 pub fn new(resolution: VideoResolution, is_screencast: bool) -> Self {
87 Self { handle: vs_imp::NativeVideoSource::new(resolution, is_screencast) }
88 }
89
90 /// Creates a source for pre-encoded access units: no raw black-frame
91 /// keepalive is injected before the first capture.
92 pub fn new_encoded(resolution: VideoResolution) -> Self {
93 Self { handle: vs_imp::NativeVideoSource::new_encoded(resolution) }
94 }
95
96 pub fn capture_frame<T: AsRef<dyn VideoBuffer>>(&self, frame: &VideoFrame<T>) -> bool {
97 self.handle.capture_frame(frame)
98 }
99
100 /// Captures a Jetson DMA-buffer backed video frame.
101 ///
102 /// `pixel_format` is `0` for NV12 and `1` for YUV420M.
103 #[cfg(target_os = "linux")]
104 #[deprecated(
105 note = "wrap the fd with `NativeBuffer::from_dmabuf` and use `capture_frame` instead"
106 )]
107 #[allow(deprecated)]
108 pub fn capture_dmabuf_frame(
109 &self,
110 dmabuf_fd: i32,
111 width: u32,
112 height: u32,
113 pixel_format: i32,
114 timestamp_us: i64,
115 ) -> bool {
116 self.capture_dmabuf_frame_with_metadata(
117 dmabuf_fd,
118 width,
119 height,
120 pixel_format,
121 timestamp_us,
122 None,
123 )
124 }
125
126 /// Captures a Jetson DMA-buffer backed video frame with packet trailer metadata.
127 ///
128 /// `pixel_format` is `0` for NV12 and `1` for YUV420M.
129 #[cfg(target_os = "linux")]
130 #[deprecated(
131 note = "wrap the fd with `NativeBuffer::from_dmabuf` and use `capture_frame` instead"
132 )]
133 pub fn capture_dmabuf_frame_with_metadata(
134 &self,
135 dmabuf_fd: i32,
136 width: u32,
137 height: u32,
138 pixel_format: i32,
139 timestamp_us: i64,
140 frame_metadata: Option<FrameMetadata>,
141 ) -> bool {
142 let pixel_format = if pixel_format == 0 {
143 DmaBufPixelFormat::NV12
144 } else {
145 DmaBufPixelFormat::YUV420M
146 };
147 self.handle.capture_frame(&VideoFrame {
148 rotation: VideoRotation::VideoRotation0,
149 timestamp_us,
150 frame_metadata,
151 buffer: NativeBuffer::from_dmabuf(
152 dmabuf_fd,
153 VideoResolution { width, height },
154 pixel_format,
155 ),
156 })
157 }
158
159 /// Captures one pre-encoded video access unit.
160 pub fn capture_encoded_frame(&self, frame: &EncodedVideoFrame<'_>) -> bool {
161 self.handle.capture_encoded_frame(frame)
162 }
163
164 /// Returns and clears the pending keyframe request raised by the
165 /// pass-through encoder (PLI/FIR or reconfiguration).
166 pub fn take_keyframe_request(&self) -> bool {
167 self.handle.take_keyframe_request()
168 }
169
170 /// Returns and clears the pending rate-control target raised by the
171 /// pass-through encoder.
172 pub fn take_rate_control_request(&self) -> Option<EncodedRateControl> {
173 self.handle.take_rate_control_request()
174 }
175
176 /// Set the packet trailer handler used by this source.
177 ///
178 /// When set, any frame captured with a `user_timestamp` value will
179 /// automatically have its timestamp stored in the handler (keyed by
180 /// the TimestampAligner-adjusted capture timestamp) so the
181 /// `PacketTrailerTransformer` can embed it into the encoded frame.
182 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
183 self.handle.set_packet_trailer_handler(handler)
184 }
185
186 pub fn video_resolution(&self) -> VideoResolution {
187 self.handle.video_resolution()
188 }
189 }
190 }
191
192 #[cfg(target_arch = "wasm32")]
193 pub mod web {}
@@ -0,0 +1,193 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::{enum_dispatch, imp::video_source as vs_imp};
16
17#[derive(Debug, Clone)]
18pub struct VideoResolution {
19 pub width: u32,
20 pub height: u32,
21}
22
23/// Encoder rate-control target requested by WebRTC for a pre-encoded source.
24#[derive(Debug, Clone, Copy, PartialEq)]
25pub struct EncodedRateControl {
26 /// Target bitrate in bits per second.
27 pub target_bitrate_bps: u64,
28 /// Target frame rate in frames per second.
29 pub framerate_fps: f64,
30}
31
32impl Default for VideoResolution {
33 // Default to 720p
34 fn default() -> Self {
35 VideoResolution { width: 1280, height: 720 }
36 }
37}
38
39#[non_exhaustive]
40#[derive(Debug, Clone)]
41pub enum RtcVideoSource {
42 // TODO(theomonnom): Web video sources (eq. to tracks on browsers?)
43 #[cfg(not(target_arch = "wasm32"))]
44 Native(native::NativeVideoSource),
45}
46
47// TODO(theomonnom): Support enum dispatch with conditional compilation?
48impl RtcVideoSource {
49 enum_dispatch!(
50 [Native];
51 pub fn video_resolution(self: &Self) -> VideoResolution;
52 );
53}
54
55#[cfg(not(target_arch = "wasm32"))]
56pub mod native {
57 use std::fmt::{Debug, Formatter};
58
59 use super::*;
60 use crate::native::packet_trailer::PacketTrailerHandler;
61 #[cfg(target_os = "linux")]
62 use crate::video_frame::{
63 native::{DmaBufPixelFormat, NativeBuffer},
64 FrameMetadata, VideoRotation,
65 };
66 use crate::video_frame::{EncodedVideoFrame, VideoBuffer, VideoFrame};
67
68 #[derive(Clone)]
69 pub struct NativeVideoSource {
70 pub(crate) handle: vs_imp::NativeVideoSource,
71 }
72
73 impl Debug for NativeVideoSource {
74 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
75 f.debug_struct("NativeVideoSource").finish()
76 }
77 }
78
79 impl Default for NativeVideoSource {
80 fn default() -> Self {
81 Self::new(VideoResolution::default(), false)
82 }
83 }
84
85 impl NativeVideoSource {
86 pub fn new(resolution: VideoResolution, is_screencast: bool) -> Self {
87 Self { handle: vs_imp::NativeVideoSource::new(resolution, is_screencast) }
88 }
89
90 /// Creates a source for pre-encoded access units: no raw black-frame
91 /// keepalive is injected before the first capture.
92 pub fn new_encoded(resolution: VideoResolution) -> Self {
93 Self { handle: vs_imp::NativeVideoSource::new_encoded(resolution) }
94 }
95
96 pub fn capture_frame<T: AsRef<dyn VideoBuffer>>(&self, frame: &VideoFrame<T>) -> bool {
97 self.handle.capture_frame(frame)
98 }
99
100 /// Captures a Jetson DMA-buffer backed video frame.
101 ///
102 /// `pixel_format` is `0` for NV12 and `1` for YUV420M.
103 #[cfg(target_os = "linux")]
104 #[deprecated(
105 note = "wrap the fd with `NativeBuffer::from_dmabuf` and use `capture_frame` instead"
106 )]
107 #[allow(deprecated)]
108 pub fn capture_dmabuf_frame(
109 &self,
110 dmabuf_fd: i32,
111 width: u32,
112 height: u32,
113 pixel_format: i32,
114 timestamp_us: i64,
115 ) -> bool {
116 self.capture_dmabuf_frame_with_metadata(
117 dmabuf_fd,
118 width,
119 height,
120 pixel_format,
121 timestamp_us,
122 None,
123 )
124 }
125
126 /// Captures a Jetson DMA-buffer backed video frame with packet trailer metadata.
127 ///
128 /// `pixel_format` is `0` for NV12 and `1` for YUV420M.
129 #[cfg(target_os = "linux")]
130 #[deprecated(
131 note = "wrap the fd with `NativeBuffer::from_dmabuf` and use `capture_frame` instead"
132 )]
133 pub fn capture_dmabuf_frame_with_metadata(
134 &self,
135 dmabuf_fd: i32,
136 width: u32,
137 height: u32,
138 pixel_format: i32,
139 timestamp_us: i64,
140 frame_metadata: Option<FrameMetadata>,
141 ) -> bool {
142 let pixel_format = if pixel_format == 0 {
143 DmaBufPixelFormat::NV12
144 } else {
145 DmaBufPixelFormat::YUV420M
146 };
147 self.handle.capture_frame(&VideoFrame {
148 rotation: VideoRotation::VideoRotation0,
149 timestamp_us,
150 frame_metadata,
151 buffer: NativeBuffer::from_dmabuf(
152 dmabuf_fd,
153 VideoResolution { width, height },
154 pixel_format,
155 ),
156 })
157 }
158
159 /// Captures one pre-encoded video access unit.
160 pub fn capture_encoded_frame(&self, frame: &EncodedVideoFrame<'_>) -> bool {
161 self.handle.capture_encoded_frame(frame)
162 }
163
164 /// Returns and clears the pending keyframe request raised by the
165 /// pass-through encoder (PLI/FIR or reconfiguration).
166 pub fn take_keyframe_request(&self) -> bool {
167 self.handle.take_keyframe_request()
168 }
169
170 /// Returns and clears the pending rate-control target raised by the
171 /// pass-through encoder.
172 pub fn take_rate_control_request(&self) -> Option<EncodedRateControl> {
173 self.handle.take_rate_control_request()
174 }
175
176 /// Set the packet trailer handler used by this source.
177 ///
178 /// When set, any frame captured with a `user_timestamp` value will
179 /// automatically have its timestamp stored in the handler (keyed by
180 /// the TimestampAligner-adjusted capture timestamp) so the
181 /// `PacketTrailerTransformer` can embed it into the encoded frame.
182 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
183 self.handle.set_packet_trailer_handler(handler)
184 }
185
186 pub fn video_resolution(&self) -> VideoResolution {
187 self.handle.video_resolution()
188 }
189 }
190}
191
192#[cfg(target_arch = "wasm32")]
193pub mod web {}
vendor/libwebrtc/src/video_stream.rs added +123 −0
@@ -0,0 +1,123 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use crate::imp::video_stream as stream_imp;
16
17 // There is no shared sink between native and web platforms.
18 // Each platform requires different configuration (e.g: WebGlContext, ..)
19
20 #[cfg(not(target_arch = "wasm32"))]
21 pub mod native {
22 use std::{
23 fmt::{Debug, Formatter},
24 pin::Pin,
25 task::{Context, Poll},
26 };
27
28 use super::stream_imp;
29 use crate::{
30 native::packet_trailer::PacketTrailerHandler, video_frame::BoxVideoFrame,
31 video_track::RtcVideoTrack,
32 };
33 use tokio_stream::Stream;
34
35 const DEFAULT_QUEUE_SIZE_FRAMES: usize = 1;
36
37 #[derive(Clone, Debug, Default)]
38 pub struct NativeVideoStreamOptions {
39 /// Maximum number of queued WebRTC sink frames after the video callback.
40 ///
41 /// `None` uses the default bounded queue size of 1 frame. `Some(0)`
42 /// opts into unbounded buffering. Positive values bound the queue, and
43 /// the stream drops the oldest queued frames on overflow so render
44 /// latency stays bounded.
45 ///
46 /// If your application consumes both audio and video, keep the queue
47 /// sizing strategy coordinated across both streams. Using a much larger
48 /// queue, or unbounded buffering, for only one of them can increase
49 /// end-to-end latency for that stream and cause audio/video drift.
50 pub queue_size_frames: Option<usize>,
51 }
52
53 pub struct NativeVideoStream {
54 pub(crate) handle: stream_imp::NativeVideoStream,
55 }
56
57 impl Debug for NativeVideoStream {
58 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
59 f.debug_struct("NativeVideoStream").field("track", &self.track()).finish()
60 }
61 }
62
63 impl NativeVideoStream {
64 pub fn new(video_track: RtcVideoTrack) -> Self {
65 Self {
66 handle: stream_imp::NativeVideoStream::new(
67 video_track,
68 Some(DEFAULT_QUEUE_SIZE_FRAMES),
69 ),
70 }
71 }
72
73 pub fn with_options(video_track: RtcVideoTrack, options: NativeVideoStreamOptions) -> Self {
74 Self {
75 handle: stream_imp::NativeVideoStream::new(
76 video_track,
77 normalize_queue_size_frames(options.queue_size_frames),
78 ),
79 }
80 }
81
82 /// Set the packet trailer handler for this stream.
83 ///
84 /// When set, each frame produced by this stream will have its
85 /// `user_timestamp` field populated by looking up the user
86 /// timestamp for each frame's RTP timestamp.
87 ///
88 /// Note: If the handler was already set on the `RtcVideoTrack`
89 /// before creating this stream, it is automatically wired up.
90 /// This method is only needed to override or set the handler
91 /// after construction.
92 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
93 self.handle.set_packet_trailer_handler(handler);
94 }
95
96 pub fn track(&self) -> RtcVideoTrack {
97 self.handle.track()
98 }
99
100 pub fn close(&mut self) {
101 self.handle.close();
102 }
103 }
104
105 impl Stream for NativeVideoStream {
106 type Item = BoxVideoFrame;
107
108 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
109 Pin::new(&mut self.get_mut().handle).poll_next(cx)
110 }
111 }
112
113 fn normalize_queue_size_frames(queue_size_frames: Option<usize>) -> Option<usize> {
114 match queue_size_frames {
115 None => Some(DEFAULT_QUEUE_SIZE_FRAMES),
116 Some(0) => None,
117 Some(value) => Some(value),
118 }
119 }
120 }
121
122 #[cfg(target_arch = "wasm32")]
123 pub mod web {}
@@ -0,0 +1,123 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::imp::video_stream as stream_imp;
16
17// There is no shared sink between native and web platforms.
18// Each platform requires different configuration (e.g: WebGlContext, ..)
19
20#[cfg(not(target_arch = "wasm32"))]
21pub mod native {
22 use std::{
23 fmt::{Debug, Formatter},
24 pin::Pin,
25 task::{Context, Poll},
26 };
27
28 use super::stream_imp;
29 use crate::{
30 native::packet_trailer::PacketTrailerHandler, video_frame::BoxVideoFrame,
31 video_track::RtcVideoTrack,
32 };
33 use tokio_stream::Stream;
34
35 const DEFAULT_QUEUE_SIZE_FRAMES: usize = 1;
36
37 #[derive(Clone, Debug, Default)]
38 pub struct NativeVideoStreamOptions {
39 /// Maximum number of queued WebRTC sink frames after the video callback.
40 ///
41 /// `None` uses the default bounded queue size of 1 frame. `Some(0)`
42 /// opts into unbounded buffering. Positive values bound the queue, and
43 /// the stream drops the oldest queued frames on overflow so render
44 /// latency stays bounded.
45 ///
46 /// If your application consumes both audio and video, keep the queue
47 /// sizing strategy coordinated across both streams. Using a much larger
48 /// queue, or unbounded buffering, for only one of them can increase
49 /// end-to-end latency for that stream and cause audio/video drift.
50 pub queue_size_frames: Option<usize>,
51 }
52
53 pub struct NativeVideoStream {
54 pub(crate) handle: stream_imp::NativeVideoStream,
55 }
56
57 impl Debug for NativeVideoStream {
58 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
59 f.debug_struct("NativeVideoStream").field("track", &self.track()).finish()
60 }
61 }
62
63 impl NativeVideoStream {
64 pub fn new(video_track: RtcVideoTrack) -> Self {
65 Self {
66 handle: stream_imp::NativeVideoStream::new(
67 video_track,
68 Some(DEFAULT_QUEUE_SIZE_FRAMES),
69 ),
70 }
71 }
72
73 pub fn with_options(video_track: RtcVideoTrack, options: NativeVideoStreamOptions) -> Self {
74 Self {
75 handle: stream_imp::NativeVideoStream::new(
76 video_track,
77 normalize_queue_size_frames(options.queue_size_frames),
78 ),
79 }
80 }
81
82 /// Set the packet trailer handler for this stream.
83 ///
84 /// When set, each frame produced by this stream will have its
85 /// `user_timestamp` field populated by looking up the user
86 /// timestamp for each frame's RTP timestamp.
87 ///
88 /// Note: If the handler was already set on the `RtcVideoTrack`
89 /// before creating this stream, it is automatically wired up.
90 /// This method is only needed to override or set the handler
91 /// after construction.
92 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
93 self.handle.set_packet_trailer_handler(handler);
94 }
95
96 pub fn track(&self) -> RtcVideoTrack {
97 self.handle.track()
98 }
99
100 pub fn close(&mut self) {
101 self.handle.close();
102 }
103 }
104
105 impl Stream for NativeVideoStream {
106 type Item = BoxVideoFrame;
107
108 fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
109 Pin::new(&mut self.get_mut().handle).poll_next(cx)
110 }
111 }
112
113 fn normalize_queue_size_frames(queue_size_frames: Option<usize>) -> Option<usize> {
114 match queue_size_frames {
115 None => Some(DEFAULT_QUEUE_SIZE_FRAMES),
116 Some(0) => None,
117 Some(value) => Some(value),
118 }
119 }
120}
121
122#[cfg(target_arch = "wasm32")]
123pub mod web {}
vendor/libwebrtc/src/video_track.rs added +58 −0
@@ -0,0 +1,58 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::fmt::Debug;
16
17 use crate::{
18 imp::video_track as imp_vt,
19 media_stream_track::{media_stream_track, RtcTrackState},
20 };
21
22 #[cfg(not(target_arch = "wasm32"))]
23 use crate::native::packet_trailer::PacketTrailerHandler;
24
25 #[derive(Clone)]
26 pub struct RtcVideoTrack {
27 pub(crate) handle: imp_vt::RtcVideoTrack,
28 }
29
30 impl RtcVideoTrack {
31 media_stream_track!();
32
33 /// Set the packet trailer handler for this track.
34 ///
35 /// When set, any `NativeVideoStream` created from this track will
36 /// automatically use this handler to populate `user_timestamp`
37 /// on each decoded frame.
38 #[cfg(not(target_arch = "wasm32"))]
39 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
40 self.handle.set_packet_trailer_handler(handler);
41 }
42
43 /// Get the packet trailer handler, if one has been set.
44 #[cfg(not(target_arch = "wasm32"))]
45 pub fn packet_trailer_handler(&self) -> Option<PacketTrailerHandler> {
46 self.handle.packet_trailer_handler()
47 }
48 }
49
50 impl Debug for RtcVideoTrack {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 f.debug_struct("RtcVideoTrack")
53 .field("id", &self.id())
54 .field("enabled", &self.enabled())
55 .field("state", &self.state())
56 .finish()
57 }
58 }
@@ -0,0 +1,58 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16
17use crate::{
18 imp::video_track as imp_vt,
19 media_stream_track::{media_stream_track, RtcTrackState},
20};
21
22#[cfg(not(target_arch = "wasm32"))]
23use crate::native::packet_trailer::PacketTrailerHandler;
24
25#[derive(Clone)]
26pub struct RtcVideoTrack {
27 pub(crate) handle: imp_vt::RtcVideoTrack,
28}
29
30impl RtcVideoTrack {
31 media_stream_track!();
32
33 /// Set the packet trailer handler for this track.
34 ///
35 /// When set, any `NativeVideoStream` created from this track will
36 /// automatically use this handler to populate `user_timestamp`
37 /// on each decoded frame.
38 #[cfg(not(target_arch = "wasm32"))]
39 pub fn set_packet_trailer_handler(&self, handler: PacketTrailerHandler) {
40 self.handle.set_packet_trailer_handler(handler);
41 }
42
43 /// Get the packet trailer handler, if one has been set.
44 #[cfg(not(target_arch = "wasm32"))]
45 pub fn packet_trailer_handler(&self) -> Option<PacketTrailerHandler> {
46 self.handle.packet_trailer_handler()
47 }
48}
49
50impl Debug for RtcVideoTrack {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 f.debug_struct("RtcVideoTrack")
53 .field("id", &self.id())
54 .field("enabled", &self.enabled())
55 .field("state", &self.state())
56 .finish()
57 }
58}
vendor/libwebrtc/src/web/data_channel.rs added +117 −0
@@ -0,0 +1,117 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use core::str;
16 use std::cell::RefCell;
17 use std::rc::Rc;
18 use wasm_bindgen::prelude::*;
19 use web_sys::{MessageEvent, RtcDataChannelEvent, RtcDataChannelState};
20
21 use crate::data_channel::{
22 DataChannelError, DataChannelTrait, DataState, OnBufferedAmountChange, OnMessage, OnStateChange,
23 };
24
25 impl From<RtcDataChannelState> for DataState {
26 fn from(value: RtcDataChannelState) -> Self {
27 match value {
28 RtcDataChannelState::Connecting => Self::Connecting,
29 RtcDataChannelState::Open => Self::Open,
30 RtcDataChannelState::Closing => Self::Closing,
31 RtcDataChannelState::Closed => Self::Closed,
32 _ => panic!("unknown data channel state"),
33 }
34 }
35 }
36
37 #[derive(Clone)]
38 pub struct DataChannel {
39 sys_handle: web_sys::RtcDataChannel,
40 on_closing: Rc<RefCell<Option<JsValue>>>,
41 }
42
43 impl DataChannelTrait for DataChannel {
44 fn send(&self, data: &[u8], binary: bool) -> Result<(), DataChannelError> {
45 if binary {
46 self.sys_handle
47 .send_with_u8_array(data)
48 .map_err(|_| DataChannelError::Send)
49 } else {
50 let utf8 = str::from_utf8(data)?;
51 self.sys_handle
52 .send_with_str(utf8)
53 .map_err(|_| DataChannelError::Send)
54 }
55 }
56
57 fn label(&self) -> String {
58 self.sys_handle.label()
59 }
60
61 fn state(&self) -> DataState {
62 self.sys_handle.ready_state().into()
63 }
64
65 fn close(&self) {
66 self.sys_handle.close();
67 }
68
69 fn on_state_change(&self, callback: Option<OnStateChange>) {
70 if let Some(mut callback) = callback {
71 let dc = self.clone();
72 let js_callback = Closure::new(move |_: RtcDataChannelEvent| {
73 callback(dc.state());
74 });
75 let js_callback = js_callback.into_js_value();
76 self.sys_handle
77 .set_onopen(Some(js_callback.unchecked_ref()));
78 self.sys_handle
79 .set_onclose(Some(js_callback.unchecked_ref()));
80 self.sys_handle
81 .add_event_listener_with_callback("closing", js_callback.unchecked_ref())
82 .unwrap();
83
84 self.on_closing.replace(Some(js_callback));
85 } else {
86 self.sys_handle.set_onopen(None);
87 self.sys_handle.set_onclose(None);
88 if let Some(on_closing) = self.on_closing.take() {
89 self.sys_handle
90 .remove_event_listener_with_callback("closing", on_closing.unchecked_ref())
91 .unwrap();
92 }
93 self.on_closing.replace(None);
94 }
95 }
96
97 fn on_message(&self, callback: Option<OnMessage>) {
98 let js_callback = callback.map(|mut callback| {
99 Closure::new(move |event: MessageEvent| {
100 if let Some(str) = event.as_string() {
101 callback(str.as_bytes(), false);
102 }
103 })
104 .into_js_value()
105 });
106
107 self.sys_handle.set_onmessage(
108 js_callback
109 .as_ref()
110 .map(|callback| callback.unchecked_ref()),
111 );
112 }
113
114 fn on_buffered_amount_change(&self, _callback: Option<OnBufferedAmountChange>) {
115 todo!("onbufferedamountlow instead?")
116 }
117 }
@@ -0,0 +1,117 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use core::str;
16use std::cell::RefCell;
17use std::rc::Rc;
18use wasm_bindgen::prelude::*;
19use web_sys::{MessageEvent, RtcDataChannelEvent, RtcDataChannelState};
20
21use crate::data_channel::{
22 DataChannelError, DataChannelTrait, DataState, OnBufferedAmountChange, OnMessage, OnStateChange,
23};
24
25impl From<RtcDataChannelState> for DataState {
26 fn from(value: RtcDataChannelState) -> Self {
27 match value {
28 RtcDataChannelState::Connecting => Self::Connecting,
29 RtcDataChannelState::Open => Self::Open,
30 RtcDataChannelState::Closing => Self::Closing,
31 RtcDataChannelState::Closed => Self::Closed,
32 _ => panic!("unknown data channel state"),
33 }
34 }
35}
36
37#[derive(Clone)]
38pub struct DataChannel {
39 sys_handle: web_sys::RtcDataChannel,
40 on_closing: Rc<RefCell<Option<JsValue>>>,
41}
42
43impl DataChannelTrait for DataChannel {
44 fn send(&self, data: &[u8], binary: bool) -> Result<(), DataChannelError> {
45 if binary {
46 self.sys_handle
47 .send_with_u8_array(data)
48 .map_err(|_| DataChannelError::Send)
49 } else {
50 let utf8 = str::from_utf8(data)?;
51 self.sys_handle
52 .send_with_str(utf8)
53 .map_err(|_| DataChannelError::Send)
54 }
55 }
56
57 fn label(&self) -> String {
58 self.sys_handle.label()
59 }
60
61 fn state(&self) -> DataState {
62 self.sys_handle.ready_state().into()
63 }
64
65 fn close(&self) {
66 self.sys_handle.close();
67 }
68
69 fn on_state_change(&self, callback: Option<OnStateChange>) {
70 if let Some(mut callback) = callback {
71 let dc = self.clone();
72 let js_callback = Closure::new(move |_: RtcDataChannelEvent| {
73 callback(dc.state());
74 });
75 let js_callback = js_callback.into_js_value();
76 self.sys_handle
77 .set_onopen(Some(js_callback.unchecked_ref()));
78 self.sys_handle
79 .set_onclose(Some(js_callback.unchecked_ref()));
80 self.sys_handle
81 .add_event_listener_with_callback("closing", js_callback.unchecked_ref())
82 .unwrap();
83
84 self.on_closing.replace(Some(js_callback));
85 } else {
86 self.sys_handle.set_onopen(None);
87 self.sys_handle.set_onclose(None);
88 if let Some(on_closing) = self.on_closing.take() {
89 self.sys_handle
90 .remove_event_listener_with_callback("closing", on_closing.unchecked_ref())
91 .unwrap();
92 }
93 self.on_closing.replace(None);
94 }
95 }
96
97 fn on_message(&self, callback: Option<OnMessage>) {
98 let js_callback = callback.map(|mut callback| {
99 Closure::new(move |event: MessageEvent| {
100 if let Some(str) = event.as_string() {
101 callback(str.as_bytes(), false);
102 }
103 })
104 .into_js_value()
105 });
106
107 self.sys_handle.set_onmessage(
108 js_callback
109 .as_ref()
110 .map(|callback| callback.unchecked_ref()),
111 );
112 }
113
114 fn on_buffered_amount_change(&self, _callback: Option<OnBufferedAmountChange>) {
115 todo!("onbufferedamountlow instead?")
116 }
117}
vendor/libwebrtc/src/web/media_stream.rs added +372 −0
@@ -0,0 +1,372 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use super::VideoTrack;
16 use crate::{
17 media_stream::{
18 BiplanarYuv8Buffer, BiplanarYuvBuffer, PlanarYuv16BBuffer, PlanarYuv8Buffer,
19 PlanarYuvBuffer, VideoFrameBuffer,
20 },
21 video_frame::{BiplanarYuv8Buffer, I420Buffer, SinkError, VideoFrame, VideoFrameBuffer},
22 I010Buffer, I420ABuffer, I422Buffer, I444Buffer, NV12Buffer,
23 };
24 use std::sync::mpsc;
25 use web_sys::{WebGlRenderingContext, WebGlTexture};
26
27 #[derive(Debug)]
28 pub struct WebGlVideoSink {
29 track: Arc<VideoTrack>,
30 gl_ctx: WebGlRenderingContext,
31 tex: WebGlTexture,
32 }
33
34 /// Create a new WebGL texture and update it inside requestAnimationFrame
35 impl WebGlVideoSink {
36 pub fn new(
37 track: Arc<VideoTrack>,
38 gl_ctx: WebGlRenderingContext,
39 ) -> Result<(Self, mpsc::Receiver<VideoFrame<WebGlBuffer>>), SinkError> {
40 let (sender, receiver) = mpsc::channel();
41 let tex = gl_ctx.create_texture()?;
42 Ok((Self { track, gl_ctx, tex }, receiver))
43 }
44 }
45
46 #[derive(Debug, Clone)]
47 pub struct WebGlBuffer {
48 width: i32,
49 height: i32,
50 tex: WebGlTexture,
51 }
52
53 impl VideoFrameBuffer for WebGlBuffer {
54 fn width(&self) -> i32 {
55 self.width
56 }
57
58 fn height(&self) -> i32 {
59 self.height
60 }
61 }
62
63 /// The following types could be implemented if we want
64 /// to support VideoFrame with WebCodecs
65
66 #[derive(Debug)]
67 pub struct I420Buffer {}
68
69 #[derive(Debug)]
70 pub struct I420ABuffer {}
71
72 #[derive(Debug)]
73 pub struct I422Buffer {}
74
75 #[derive(Debug)]
76 pub struct I444Buffer {}
77
78 #[derive(Debug)]
79 pub struct I010Buffer {}
80
81 #[derive(Debug)]
82 pub struct NV12Buffer {}
83
84 impl VideoFrameBuffer for I420Buffer {
85 fn width(&self) -> i32 {
86 unimplemented!()
87 }
88
89 fn height(&self) -> i32 {
90 unimplemented!()
91 }
92 }
93
94 impl VideoFrameBuffer for I420ABuffer {
95 fn width(&self) -> i32 {
96 unimplemented!()
97 }
98
99 fn height(&self) -> i32 {
100 unimplemented!()
101 }
102 }
103
104 impl VideoFrameBuffer for I422Buffer {
105 fn width(&self) -> i32 {
106 unimplemented!()
107 }
108
109 fn height(&self) -> i32 {
110 unimplemented!()
111 }
112 }
113
114 impl VideoFrameBuffer for I444Buffer {
115 fn width(&self) -> i32 {
116 unimplemented!()
117 }
118
119 fn height(&self) -> i32 {
120 unimplemented!()
121 }
122 }
123
124 impl VideoFrameBuffer for I010Buffer {
125 fn width(&self) -> i32 {
126 unimplemented!()
127 }
128
129 fn height(&self) -> i32 {
130 unimplemented!()
131 }
132 }
133
134 impl VideoFrameBuffer for NV12Buffer {
135 fn width(&self) -> i32 {
136 unimplemented!()
137 }
138
139 fn height(&self) -> i32 {
140 unimplemented!()
141 }
142 }
143
144 impl PlanarYuvBuffer for I420Buffer {
145 fn chroma_width(&self) -> i32 {
146 unimplemented!()
147 }
148
149 fn chroma_height(&self) -> i32 {
150 unimplemented!()
151 }
152
153 fn stride_y(&self) -> i32 {
154 unimplemented!()
155 }
156
157 fn stride_u(&self) -> i32 {
158 unimplemented!()
159 }
160
161 fn stride_v(&self) -> i32 {
162 unimplemented!()
163 }
164 }
165
166 impl PlanarYuvBuffer for I420ABuffer {
167 fn chroma_width(&self) -> i32 {
168 unimplemented!()
169 }
170
171 fn chroma_height(&self) -> i32 {
172 unimplemented!()
173 }
174
175 fn stride_y(&self) -> i32 {
176 unimplemented!()
177 }
178
179 fn stride_u(&self) -> i32 {
180 unimplemented!()
181 }
182
183 fn stride_v(&self) -> i32 {
184 unimplemented!()
185 }
186 }
187
188 impl PlanarYuvBuffer for I422Buffer {
189 fn chroma_width(&self) -> i32 {
190 unimplemented!()
191 }
192
193 fn chroma_height(&self) -> i32 {
194 unimplemented!()
195 }
196
197 fn stride_y(&self) -> i32 {
198 unimplemented!()
199 }
200
201 fn stride_u(&self) -> i32 {
202 unimplemented!()
203 }
204
205 fn stride_v(&self) -> i32 {
206 unimplemented!()
207 }
208 }
209
210 impl PlanarYuvBuffer for I444Buffer {
211 fn chroma_width(&self) -> i32 {
212 unimplemented!()
213 }
214
215 fn chroma_height(&self) -> i32 {
216 unimplemented!()
217 }
218
219 fn stride_y(&self) -> i32 {
220 unimplemented!()
221 }
222
223 fn stride_u(&self) -> i32 {
224 unimplemented!()
225 }
226
227 fn stride_v(&self) -> i32 {
228 unimplemented!()
229 }
230 }
231
232 impl PlanarYuvBuffer for I010Buffer {
233 fn chroma_width(&self) -> i32 {
234 unimplemented!()
235 }
236
237 fn chroma_height(&self) -> i32 {
238 unimplemented!()
239 }
240
241 fn stride_y(&self) -> i32 {
242 unimplemented!()
243 }
244
245 fn stride_u(&self) -> i32 {
246 unimplemented!()
247 }
248
249 fn stride_v(&self) -> i32 {
250 unimplemented!()
251 }
252 }
253
254 impl PlanarYuvBuffer for NV12Buffer {
255 fn chroma_width(&self) -> i32 {
256 unimplemented!()
257 }
258
259 fn chroma_height(&self) -> i32 {
260 unimplemented!()
261 }
262
263 fn stride_y(&self) -> i32 {
264 unimplemented!()
265 }
266
267 fn stride_u(&self) -> i32 {
268 unimplemented!()
269 }
270
271 fn stride_v(&self) -> i32 {
272 unimplemented!()
273 }
274 }
275
276 impl PlanarYuv8Buffer for I420Buffer {
277 fn data_y(&self) -> &[u8] {
278 unimplemented!()
279 }
280
281 fn data_u(&self) -> &[u8] {
282 unimplemented!()
283 }
284
285 fn data_v(&self) -> &[u8] {
286 unimplemented!()
287 }
288 }
289
290 impl PlanarYuv8Buffer for I420ABuffer {
291 fn data_y(&self) -> &[u8] {
292 unimplemented!()
293 }
294
295 fn data_u(&self) -> &[u8] {
296 unimplemented!()
297 }
298
299 fn data_v(&self) -> &[u8] {
300 unimplemented!()
301 }
302 }
303
304 impl PlanarYuv8Buffer for I422Buffer {
305 fn data_y(&self) -> &[u8] {
306 unimplemented!()
307 }
308
309 fn data_u(&self) -> &[u8] {
310 unimplemented!()
311 }
312
313 fn data_v(&self) -> &[u8] {
314 unimplemented!()
315 }
316 }
317
318 impl PlanarYuv8Buffer for I444Buffer {
319 fn data_y(&self) -> &[u8] {
320 unimplemented!()
321 }
322
323 fn data_u(&self) -> &[u8] {
324 unimplemented!()
325 }
326
327 fn data_v(&self) -> &[u8] {
328 unimplemented!()
329 }
330 }
331
332 impl PlanarYuv16BBuffer for I010Buffer {
333 fn data_y(&self) -> &[u16] {
334 unimplemented!()
335 }
336
337 fn data_u(&self) -> &[u16] {
338 unimplemented!()
339 }
340
341 fn data_v(&self) -> &[u16] {
342 unimplemented!()
343 }
344 }
345
346 impl BiplanarYuvBuffer for NV12Buffer {
347 fn chroma_width(&self) -> i32 {
348 unimplemented!()
349 }
350
351 fn chroma_height(&self) -> i32 {
352 unimplemented!()
353 }
354
355 fn stride_y(&self) -> i32 {
356 unimplemented!()
357 }
358
359 fn stride_uv(&self) -> i32 {
360 unimplemented!()
361 }
362 }
363
364 impl BiplanarYuv8Buffer for NV12Buffer {
365 fn data_y(&self) -> &[u8] {
366 unimplemented!()
367 }
368
369 fn data_uv(&self) -> &[u8] {
370 unimplemented!()
371 }
372 }
@@ -0,0 +1,372 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use super::VideoTrack;
16use crate::{
17 media_stream::{
18 BiplanarYuv8Buffer, BiplanarYuvBuffer, PlanarYuv16BBuffer, PlanarYuv8Buffer,
19 PlanarYuvBuffer, VideoFrameBuffer,
20 },
21 video_frame::{BiplanarYuv8Buffer, I420Buffer, SinkError, VideoFrame, VideoFrameBuffer},
22 I010Buffer, I420ABuffer, I422Buffer, I444Buffer, NV12Buffer,
23};
24use std::sync::mpsc;
25use web_sys::{WebGlRenderingContext, WebGlTexture};
26
27#[derive(Debug)]
28pub struct WebGlVideoSink {
29 track: Arc<VideoTrack>,
30 gl_ctx: WebGlRenderingContext,
31 tex: WebGlTexture,
32}
33
34/// Create a new WebGL texture and update it inside requestAnimationFrame
35impl WebGlVideoSink {
36 pub fn new(
37 track: Arc<VideoTrack>,
38 gl_ctx: WebGlRenderingContext,
39 ) -> Result<(Self, mpsc::Receiver<VideoFrame<WebGlBuffer>>), SinkError> {
40 let (sender, receiver) = mpsc::channel();
41 let tex = gl_ctx.create_texture()?;
42 Ok((Self { track, gl_ctx, tex }, receiver))
43 }
44}
45
46#[derive(Debug, Clone)]
47pub struct WebGlBuffer {
48 width: i32,
49 height: i32,
50 tex: WebGlTexture,
51}
52
53impl VideoFrameBuffer for WebGlBuffer {
54 fn width(&self) -> i32 {
55 self.width
56 }
57
58 fn height(&self) -> i32 {
59 self.height
60 }
61}
62
63/// The following types could be implemented if we want
64/// to support VideoFrame with WebCodecs
65
66#[derive(Debug)]
67pub struct I420Buffer {}
68
69#[derive(Debug)]
70pub struct I420ABuffer {}
71
72#[derive(Debug)]
73pub struct I422Buffer {}
74
75#[derive(Debug)]
76pub struct I444Buffer {}
77
78#[derive(Debug)]
79pub struct I010Buffer {}
80
81#[derive(Debug)]
82pub struct NV12Buffer {}
83
84impl VideoFrameBuffer for I420Buffer {
85 fn width(&self) -> i32 {
86 unimplemented!()
87 }
88
89 fn height(&self) -> i32 {
90 unimplemented!()
91 }
92}
93
94impl VideoFrameBuffer for I420ABuffer {
95 fn width(&self) -> i32 {
96 unimplemented!()
97 }
98
99 fn height(&self) -> i32 {
100 unimplemented!()
101 }
102}
103
104impl VideoFrameBuffer for I422Buffer {
105 fn width(&self) -> i32 {
106 unimplemented!()
107 }
108
109 fn height(&self) -> i32 {
110 unimplemented!()
111 }
112}
113
114impl VideoFrameBuffer for I444Buffer {
115 fn width(&self) -> i32 {
116 unimplemented!()
117 }
118
119 fn height(&self) -> i32 {
120 unimplemented!()
121 }
122}
123
124impl VideoFrameBuffer for I010Buffer {
125 fn width(&self) -> i32 {
126 unimplemented!()
127 }
128
129 fn height(&self) -> i32 {
130 unimplemented!()
131 }
132}
133
134impl VideoFrameBuffer for NV12Buffer {
135 fn width(&self) -> i32 {
136 unimplemented!()
137 }
138
139 fn height(&self) -> i32 {
140 unimplemented!()
141 }
142}
143
144impl PlanarYuvBuffer for I420Buffer {
145 fn chroma_width(&self) -> i32 {
146 unimplemented!()
147 }
148
149 fn chroma_height(&self) -> i32 {
150 unimplemented!()
151 }
152
153 fn stride_y(&self) -> i32 {
154 unimplemented!()
155 }
156
157 fn stride_u(&self) -> i32 {
158 unimplemented!()
159 }
160
161 fn stride_v(&self) -> i32 {
162 unimplemented!()
163 }
164}
165
166impl PlanarYuvBuffer for I420ABuffer {
167 fn chroma_width(&self) -> i32 {
168 unimplemented!()
169 }
170
171 fn chroma_height(&self) -> i32 {
172 unimplemented!()
173 }
174
175 fn stride_y(&self) -> i32 {
176 unimplemented!()
177 }
178
179 fn stride_u(&self) -> i32 {
180 unimplemented!()
181 }
182
183 fn stride_v(&self) -> i32 {
184 unimplemented!()
185 }
186}
187
188impl PlanarYuvBuffer for I422Buffer {
189 fn chroma_width(&self) -> i32 {
190 unimplemented!()
191 }
192
193 fn chroma_height(&self) -> i32 {
194 unimplemented!()
195 }
196
197 fn stride_y(&self) -> i32 {
198 unimplemented!()
199 }
200
201 fn stride_u(&self) -> i32 {
202 unimplemented!()
203 }
204
205 fn stride_v(&self) -> i32 {
206 unimplemented!()
207 }
208}
209
210impl PlanarYuvBuffer for I444Buffer {
211 fn chroma_width(&self) -> i32 {
212 unimplemented!()
213 }
214
215 fn chroma_height(&self) -> i32 {
216 unimplemented!()
217 }
218
219 fn stride_y(&self) -> i32 {
220 unimplemented!()
221 }
222
223 fn stride_u(&self) -> i32 {
224 unimplemented!()
225 }
226
227 fn stride_v(&self) -> i32 {
228 unimplemented!()
229 }
230}
231
232impl PlanarYuvBuffer for I010Buffer {
233 fn chroma_width(&self) -> i32 {
234 unimplemented!()
235 }
236
237 fn chroma_height(&self) -> i32 {
238 unimplemented!()
239 }
240
241 fn stride_y(&self) -> i32 {
242 unimplemented!()
243 }
244
245 fn stride_u(&self) -> i32 {
246 unimplemented!()
247 }
248
249 fn stride_v(&self) -> i32 {
250 unimplemented!()
251 }
252}
253
254impl PlanarYuvBuffer for NV12Buffer {
255 fn chroma_width(&self) -> i32 {
256 unimplemented!()
257 }
258
259 fn chroma_height(&self) -> i32 {
260 unimplemented!()
261 }
262
263 fn stride_y(&self) -> i32 {
264 unimplemented!()
265 }
266
267 fn stride_u(&self) -> i32 {
268 unimplemented!()
269 }
270
271 fn stride_v(&self) -> i32 {
272 unimplemented!()
273 }
274}
275
276impl PlanarYuv8Buffer for I420Buffer {
277 fn data_y(&self) -> &[u8] {
278 unimplemented!()
279 }
280
281 fn data_u(&self) -> &[u8] {
282 unimplemented!()
283 }
284
285 fn data_v(&self) -> &[u8] {
286 unimplemented!()
287 }
288}
289
290impl PlanarYuv8Buffer for I420ABuffer {
291 fn data_y(&self) -> &[u8] {
292 unimplemented!()
293 }
294
295 fn data_u(&self) -> &[u8] {
296 unimplemented!()
297 }
298
299 fn data_v(&self) -> &[u8] {
300 unimplemented!()
301 }
302}
303
304impl PlanarYuv8Buffer for I422Buffer {
305 fn data_y(&self) -> &[u8] {
306 unimplemented!()
307 }
308
309 fn data_u(&self) -> &[u8] {
310 unimplemented!()
311 }
312
313 fn data_v(&self) -> &[u8] {
314 unimplemented!()
315 }
316}
317
318impl PlanarYuv8Buffer for I444Buffer {
319 fn data_y(&self) -> &[u8] {
320 unimplemented!()
321 }
322
323 fn data_u(&self) -> &[u8] {
324 unimplemented!()
325 }
326
327 fn data_v(&self) -> &[u8] {
328 unimplemented!()
329 }
330}
331
332impl PlanarYuv16BBuffer for I010Buffer {
333 fn data_y(&self) -> &[u16] {
334 unimplemented!()
335 }
336
337 fn data_u(&self) -> &[u16] {
338 unimplemented!()
339 }
340
341 fn data_v(&self) -> &[u16] {
342 unimplemented!()
343 }
344}
345
346impl BiplanarYuvBuffer for NV12Buffer {
347 fn chroma_width(&self) -> i32 {
348 unimplemented!()
349 }
350
351 fn chroma_height(&self) -> i32 {
352 unimplemented!()
353 }
354
355 fn stride_y(&self) -> i32 {
356 unimplemented!()
357 }
358
359 fn stride_uv(&self) -> i32 {
360 unimplemented!()
361 }
362}
363
364impl BiplanarYuv8Buffer for NV12Buffer {
365 fn data_y(&self) -> &[u8] {
366 unimplemented!()
367 }
368
369 fn data_uv(&self) -> &[u8] {
370 unimplemented!()
371 }
372}
vendor/libwebrtc/src/web/mod.rs added +15 −0
@@ -0,0 +1,15 @@
1 // Copyright 2025 LiveKit, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 unimplemented!();
@@ -0,0 +1,15 @@
1// Copyright 2025 LiveKit, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15unimplemented!();
vendor/webrtc-sys/include/livekit/rtp_receiver.h +2 −0
@@ -62,6 +62,8 @@ class RtpReceiver {
62 62 void set_jitter_buffer_minimum_delay(bool is_some,
63 63 double delay_seconds) const;
64 64
65 rust::Vec<RtpSourceEntry> get_sources() const;
66
65 67 webrtc::scoped_refptr<webrtc::RtpReceiverInterface> rtc_receiver() const {
66 68 return receiver_;
67 69 }
@@ -62,6 +62,8 @@ class RtpReceiver {
62 void set_jitter_buffer_minimum_delay(bool is_some,
62 void set_jitter_buffer_minimum_delay(bool is_some,
63 double delay_seconds) const;
63 double delay_seconds) const;
64
64
65 rust::Vec<RtpSourceEntry> get_sources() const;
66
65 webrtc::scoped_refptr<webrtc::RtpReceiverInterface> rtc_receiver() const {
67 webrtc::scoped_refptr<webrtc::RtpReceiverInterface> rtc_receiver() const {
66 return receiver_;
68 return receiver_;
67 }
69 }
vendor/webrtc-sys/src/rtp_receiver.cpp +13 −0
@@ -78,4 +78,17 @@ void RtpReceiver::set_jitter_buffer_minimum_delay(bool is_some,
78 78 is_some ? absl::make_optional(delay_seconds) : absl::nullopt);
79 79 }
80 80
81 rust::Vec<RtpSourceEntry> RtpReceiver::get_sources() const {
82 rust::Vec<RtpSourceEntry> entries;
83 for (const auto& source : receiver_->GetSources()) {
84 auto level = source.audio_level();
85 entries.push_back(RtpSourceEntry{
86 source.source_id(),
87 source.source_type() == webrtc::RtpSourceType::CSRC,
88 level ? static_cast<int16_t>(*level) : static_cast<int16_t>(-1),
89 source.timestamp().ms()});
90 }
91 return entries;
92 }
93
81 94 } // namespace livekit_ffi
@@ -78,4 +78,17 @@ void RtpReceiver::set_jitter_buffer_minimum_delay(bool is_some,
78 is_some ? absl::make_optional(delay_seconds) : absl::nullopt);
78 is_some ? absl::make_optional(delay_seconds) : absl::nullopt);
79}
79}
80
80
81rust::Vec<RtpSourceEntry> RtpReceiver::get_sources() const {
82 rust::Vec<RtpSourceEntry> entries;
83 for (const auto& source : receiver_->GetSources()) {
84 auto level = source.audio_level();
85 entries.push_back(RtpSourceEntry{
86 source.source_id(),
87 source.source_type() == webrtc::RtpSourceType::CSRC,
88 level ? static_cast<int16_t>(*level) : static_cast<int16_t>(-1),
89 source.timestamp().ms()});
90 }
91 return entries;
92}
93
81} // namespace livekit_ffi
94} // namespace livekit_ffi
vendor/webrtc-sys/src/rtp_receiver.rs +8 −0
@@ -32,6 +32,13 @@ pub mod ffi {
32 32 type MediaStream = crate::media_stream::ffi::MediaStream;
33 33 }
34 34
35 pub struct RtpSourceEntry {
36 pub source_id: u32,
37 pub is_csrc: bool,
38 pub audio_level: i16,
39 pub timestamp_ms: i64,
40 }
41
35 42 unsafe extern "C++" {
36 43 include!("livekit/rtp_receiver.h");
37 44
@@ -49,6 +56,7 @@ pub mod ffi {
49 56 fn id(self: &RtpReceiver) -> String;
50 57 fn get_parameters(self: &RtpReceiver) -> RtpParameters;
51 58 fn set_jitter_buffer_minimum_delay(self: &RtpReceiver, is_some: bool, delay_seconds: f64);
59 fn get_sources(self: &RtpReceiver) -> Vec<RtpSourceEntry>;
52 60
53 61 fn _shared_rtp_receiver() -> SharedPtr<RtpReceiver>;
54 62 }
@@ -32,6 +32,13 @@ pub mod ffi {
32 type MediaStream = crate::media_stream::ffi::MediaStream;
32 type MediaStream = crate::media_stream::ffi::MediaStream;
33 }
33 }
34
34
35 pub struct RtpSourceEntry {
36 pub source_id: u32,
37 pub is_csrc: bool,
38 pub audio_level: i16,
39 pub timestamp_ms: i64,
40 }
41
35 unsafe extern "C++" {
42 unsafe extern "C++" {
36 include!("livekit/rtp_receiver.h");
43 include!("livekit/rtp_receiver.h");
37
44
@@ -49,6 +56,7 @@ pub mod ffi {
49 fn id(self: &RtpReceiver) -> String;
56 fn id(self: &RtpReceiver) -> String;
50 fn get_parameters(self: &RtpReceiver) -> RtpParameters;
57 fn get_parameters(self: &RtpReceiver) -> RtpParameters;
51 fn set_jitter_buffer_minimum_delay(self: &RtpReceiver, is_some: bool, delay_seconds: f64);
58 fn set_jitter_buffer_minimum_delay(self: &RtpReceiver, is_some: bool, delay_seconds: f64);
59 fn get_sources(self: &RtpReceiver) -> Vec<RtpSourceEntry>;
52
60
53 fn _shared_rtp_receiver() -> SharedPtr<RtpReceiver>;
61 fn _shared_rtp_receiver() -> SharedPtr<RtpReceiver>;
54 }
62 }