BlueGit

ict rusty-teams

Files

rusty-teams / vendor / libwebrtc / src / native / video_source.rs

video_source.rs

video_source.rs 10.9 KiB Download Raw
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}