BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / screen.rs

screen.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 3 weeks ago
a6592765 History
screen.rs 8.1 KiB Download Raw
1use std::sync::atomic::{AtomicU32, Ordering};
2use std::sync::{Arc, Mutex};
3use std::time::Duration;
4
5use libwebrtc::desktop_capturer::{
6 CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions,
7};
8use libwebrtc::native::yuv_helper::argb_to_i420;
9use libwebrtc::video_frame::I420Buffer;
10
11use crate::capture::Capture;
12use crate::error::{Error, Result};
13use crate::video_frame::VideoPicture;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum ShareKind {
17 Screen,
18 Window,
19}
20
21impl ShareKind {
22 fn source_type(self) -> DesktopCaptureSourceType {
23 match self {
24 ShareKind::Screen => DesktopCaptureSourceType::Screen,
25 ShareKind::Window => DesktopCaptureSourceType::Window,
26 }
27 }
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct ShareSource {
32 pub id: u64,
33 pub kind: ShareKind,
34 pub title: String,
35}
36
37impl ShareSource {
38 pub fn label(&self) -> String {
39 match (self.kind, self.title.trim()) {
40 (ShareKind::Screen, "") => "Entire screen".to_owned(),
41 (_, "") => "Window".to_owned(),
42 (_, title) => title.to_owned(),
43 }
44 }
45}
46
47fn capturer(kind: ShareKind) -> Option<DesktopCapturer> {
48 let mut options = DesktopCapturerOptions::new(kind.source_type());
49 options.set_include_cursor(true);
50 DesktopCapturer::new(options)
51}
52
53fn sources_of(kind: ShareKind) -> Vec<(ShareSource, CaptureSource)> {
54 let Some(capturer) = capturer(kind) else {
55 return Vec::new();
56 };
57 capturer
58 .get_source_list()
59 .into_iter()
60 .map(|source| {
61 (
62 ShareSource {
63 id: source.id(),
64 kind,
65 title: source.title(),
66 },
67 source,
68 )
69 })
70 .collect()
71}
72
73pub fn list_share_sources() -> Vec<ShareSource> {
74 [ShareKind::Screen, ShareKind::Window]
75 .into_iter()
76 .flat_map(|kind| sources_of(kind).into_iter().map(|(source, _)| source))
77 .collect()
78}
79
80const THUMBNAIL_ATTEMPTS: u32 = 5;
81const THUMBNAIL_RETRY: Duration = Duration::from_millis(40);
82
83pub fn share_thumbnail(
84 wanted: &ShareSource,
85 max_width: u32,
86 max_height: u32,
87) -> Option<VideoPicture> {
88 let source = sources_of(wanted.kind)
89 .into_iter()
90 .find(|(source, _)| source.id == wanted.id)
91 .map(|(_, raw)| raw)?;
92 let mut capturer = capturer(wanted.kind)?;
93 let captured: Arc<Mutex<Option<VideoPicture>>> = Arc::default();
94 let sink = captured.clone();
95 capturer.start_capture(Some(source), move |result| {
96 let Ok(frame) = result else { return };
97 let (width, height) = (frame.width().max(0) as u32, frame.height().max(0) as u32);
98 if let Some(picture) = scaled_bgra(
99 frame.data(),
100 width,
101 height,
102 frame.stride(),
103 max_width,
104 max_height,
105 ) && let Ok(mut slot) = sink.lock()
106 {
107 *slot = Some(picture);
108 }
109 });
110 for _ in 0..THUMBNAIL_ATTEMPTS {
111 pump_messages();
112 capturer.capture_frame();
113 if let Some(picture) = captured.lock().ok().and_then(|mut slot| slot.take()) {
114 return Some(picture);
115 }
116 std::thread::sleep(THUMBNAIL_RETRY);
117 }
118 None
119}
120
121// Windows Graphics Capture hands frames to a DispatcherQueue on this thread; without a pump none arrive.
122#[cfg(windows)]
123fn pump_messages() {
124 use windows::Win32::UI::WindowsAndMessaging::{
125 DispatchMessageW, MSG, PM_REMOVE, PeekMessageW, TranslateMessage,
126 };
127 let mut message = MSG::default();
128 unsafe {
129 while PeekMessageW(&mut message, None, 0, 0, PM_REMOVE).as_bool() {
130 let _ = TranslateMessage(&message);
131 let _ = DispatchMessageW(&message);
132 }
133 }
134}
135
136#[cfg(not(windows))]
137fn pump_messages() {}
138
139fn scaled_bgra(
140 bytes: &[u8],
141 width: u32,
142 height: u32,
143 stride: u32,
144 max_width: u32,
145 max_height: u32,
146) -> Option<VideoPicture> {
147 if width == 0
148 || height == 0
149 || (stride as usize) < width as usize * 4
150 || bytes.len() < stride as usize * height as usize
151 {
152 return None;
153 }
154 let scale = (max_width as f32 / width as f32)
155 .min(max_height as f32 / height as f32)
156 .min(1.);
157 let (target_width, target_height) = (
158 ((width as f32 * scale) as u32).max(1),
159 ((height as f32 * scale) as u32).max(1),
160 );
161 let mut bgra = Vec::with_capacity(target_width as usize * target_height as usize * 4);
162 for row in 0..target_height {
163 let source_row = (row as u64 * height as u64 / target_height as u64) as usize;
164 for column in 0..target_width {
165 let source_column = (column as u64 * width as u64 / target_width as u64) as usize;
166 let offset = source_row * stride as usize + source_column * 4;
167 bgra.extend_from_slice(&[bytes[offset], bytes[offset + 1], bytes[offset + 2], u8::MAX]);
168 }
169 }
170 Some(VideoPicture {
171 width: target_width,
172 height: target_height,
173 bgra,
174 })
175}
176
177fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buffer {
178 let mut buffer = I420Buffer::new(width, height);
179 let (stride_y, stride_u, stride_v) = buffer.strides();
180 let (plane_y, plane_u, plane_v) = buffer.data_mut();
181 argb_to_i420(
182 bytes,
183 stride,
184 plane_y,
185 stride_y,
186 plane_u,
187 stride_u,
188 plane_v,
189 stride_v,
190 width as i32,
191 height as i32,
192 );
193 buffer
194}
195
196pub fn start_screen_capture(
197 wanted: ShareSource,
198 fps: Arc<AtomicU32>,
199 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
200 failed: impl FnOnce(String) + Send + 'static,
201) -> Result<Capture> {
202 Capture::spawn_thread("screen-capture", move |stop| {
203 let Some(source) = sources_of(wanted.kind)
204 .into_iter()
205 .find(|(source, _)| source.id == wanted.id)
206 .map(|(_, raw)| raw)
207 else {
208 return failed("the shared source is gone".to_owned());
209 };
210 let Some(mut capturer) = capturer(wanted.kind) else {
211 return failed("screen capture is not available".to_owned());
212 };
213 capturer.start_capture(Some(source), move |result| {
214 let Ok(frame) = result else { return };
215 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
216 if width >= 2 && height >= 2 {
217 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
218 }
219 });
220 while !stop.load(Ordering::SeqCst) {
221 pump_messages();
222 capturer.capture_frame();
223 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
224 }
225 })
226 .map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
227}
228
229#[cfg(test)]
230mod tests {
231 use super::*;
232
233 #[test]
234 fn sources_get_readable_labels() {
235 let screen = ShareSource {
236 id: 1,
237 kind: ShareKind::Screen,
238 title: String::new(),
239 };
240 assert_eq!(screen.label(), "Entire screen");
241 let window = ShareSource {
242 id: 2,
243 kind: ShareKind::Window,
244 title: " Notes ".into(),
245 };
246 assert_eq!(window.label(), "Notes");
247 }
248}
249
250#[cfg(test)]
251mod thumbnail_tests {
252 use super::scaled_bgra;
253
254 #[test]
255 fn a_thumbnail_keeps_the_aspect_and_drops_the_row_padding() {
256 let (width, height, stride) = (8u32, 4u32, 40u32);
257 let mut bytes = vec![0u8; (stride * height) as usize];
258 for row in 0..height as usize {
259 for column in 0..width as usize {
260 let offset = row * stride as usize + column * 4;
261 bytes[offset..offset + 4].copy_from_slice(&[column as u8, row as u8, 7, 0]);
262 }
263 }
264 let picture = scaled_bgra(&bytes, width, height, stride, 4, 4).unwrap();
265 assert_eq!((picture.width, picture.height), (4, 2));
266 assert_eq!(picture.bgra.len(), 4 * 2 * 4);
267 assert_eq!(&picture.bgra[4..8], &[2, 0, 7, 255]);
268 assert!(scaled_bgra(&bytes, width, height, 8, 4, 4).is_none());
269 }
270}