BlueGit

ict rusty-teams

Files

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

screen.rs

screen.rs 17.0 KiB Download Raw
1use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
2use std::sync::{Arc, Mutex};
3use std::time::Duration;
4
5use libwebrtc::desktop_capturer::{
6 CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions,
7 PortalPickerEvent,
8};
9use libwebrtc::native::yuv_helper::argb_to_i420;
10use libwebrtc::video_frame::I420Buffer;
11
12use crate::capture::Capture;
13use crate::error::{Error, Result};
14use crate::video_frame::VideoPicture;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum ShareKind {
18 Screen,
19 Window,
20}
21
22impl ShareKind {
23 fn source_type(self) -> DesktopCaptureSourceType {
24 match self {
25 ShareKind::Screen => DesktopCaptureSourceType::Screen,
26 ShareKind::Window => DesktopCaptureSourceType::Window,
27 }
28 }
29}
30
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct ShareSource {
33 pub id: u64,
34 pub kind: ShareKind,
35 pub title: String,
36}
37
38impl ShareSource {
39 pub fn label(&self) -> String {
40 match (self.kind, self.title.trim()) {
41 (ShareKind::Screen, "") => "Entire screen".to_owned(),
42 (_, "") => "Window".to_owned(),
43 (_, title) => title.to_owned(),
44 }
45 }
46}
47
48fn capturer(kind: ShareKind) -> Option<DesktopCapturer> {
49 let mut options = DesktopCapturerOptions::new(kind.source_type());
50 options.set_include_cursor(true);
51 DesktopCapturer::new(options)
52}
53
54fn sources_of(kind: ShareKind) -> Vec<(ShareSource, CaptureSource)> {
55 let Some(capturer) = capturer(kind) else {
56 return Vec::new();
57 };
58 capturer
59 .get_source_list()
60 .into_iter()
61 .map(|source| {
62 (
63 ShareSource {
64 id: source.id(),
65 kind,
66 title: source.title(),
67 },
68 source,
69 )
70 })
71 .collect()
72}
73
74pub fn list_share_sources() -> Vec<ShareSource> {
75 [ShareKind::Screen, ShareKind::Window]
76 .into_iter()
77 .flat_map(|kind| sources_of(kind).into_iter().map(|(source, _)| source))
78 .collect()
79}
80
81const THUMBNAIL_ATTEMPTS: u32 = 5;
82const THUMBNAIL_RETRY: Duration = Duration::from_millis(40);
83
84pub fn share_thumbnail(
85 wanted: &ShareSource,
86 max_width: u32,
87 max_height: u32,
88) -> Option<VideoPicture> {
89 let source = sources_of(wanted.kind)
90 .into_iter()
91 .find(|(source, _)| source.id == wanted.id)
92 .map(|(_, raw)| raw)?;
93 let mut capturer = capturer(wanted.kind)?;
94 let captured: Arc<Mutex<Option<VideoPicture>>> = Arc::default();
95 let sink = captured.clone();
96 capturer.start_capture(Some(source), move |result| {
97 let Ok(frame) = result else { return };
98 let (width, height) = (frame.width().max(0) as u32, frame.height().max(0) as u32);
99 if let Some(picture) = scaled_bgra(
100 frame.data(),
101 width,
102 height,
103 frame.stride(),
104 max_width,
105 max_height,
106 ) && let Ok(mut slot) = sink.lock()
107 {
108 *slot = Some(picture);
109 }
110 });
111 for _ in 0..THUMBNAIL_ATTEMPTS {
112 pump_messages();
113 capturer.capture_frame();
114 if let Some(picture) = captured.lock().ok().and_then(|mut slot| slot.take()) {
115 return Some(picture);
116 }
117 std::thread::sleep(THUMBNAIL_RETRY);
118 }
119 None
120}
121
122// Windows Graphics Capture hands frames to a DispatcherQueue on this thread; without a pump none arrive.
123#[cfg(windows)]
124fn pump_messages() {
125 use windows::Win32::UI::WindowsAndMessaging::{
126 DispatchMessageW, MSG, PM_REMOVE, PeekMessageW, TranslateMessage,
127 };
128 let mut message = MSG::default();
129 unsafe {
130 while PeekMessageW(&mut message, None, 0, 0, PM_REMOVE).as_bool() {
131 let _ = TranslateMessage(&message);
132 let _ = DispatchMessageW(&message);
133 }
134 }
135}
136
137#[cfg(not(windows))]
138fn pump_messages() {}
139
140fn scaled_bgra(
141 bytes: &[u8],
142 width: u32,
143 height: u32,
144 stride: u32,
145 max_width: u32,
146 max_height: u32,
147) -> Option<VideoPicture> {
148 if width == 0
149 || height == 0
150 || (stride as usize) < width as usize * 4
151 || bytes.len() < stride as usize * height as usize
152 {
153 return None;
154 }
155 let scale = (max_width as f32 / width as f32)
156 .min(max_height as f32 / height as f32)
157 .min(1.);
158 let (target_width, target_height) = (
159 ((width as f32 * scale) as u32).max(1),
160 ((height as f32 * scale) as u32).max(1),
161 );
162 let mut bgra = Vec::with_capacity(target_width as usize * target_height as usize * 4);
163 for row in 0..target_height {
164 let source_row = (row as u64 * height as u64 / target_height as u64) as usize;
165 for column in 0..target_width {
166 let source_column = (column as u64 * width as u64 / target_width as u64) as usize;
167 let offset = source_row * stride as usize + source_column * 4;
168 bgra.extend_from_slice(&[bytes[offset], bytes[offset + 1], bytes[offset + 2], u8::MAX]);
169 }
170 }
171 Some(VideoPicture {
172 width: target_width,
173 height: target_height,
174 bgra,
175 })
176}
177
178fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buffer {
179 let mut buffer = I420Buffer::new(width, height);
180 let (stride_y, stride_u, stride_v) = buffer.strides();
181 let (plane_y, plane_u, plane_v) = buffer.data_mut();
182 argb_to_i420(
183 bytes,
184 stride,
185 plane_y,
186 stride_y,
187 plane_u,
188 stride_u,
189 plane_v,
190 stride_v,
191 width as i32,
192 height as i32,
193 );
194 buffer
195}
196
197pub fn start_screen_capture(
198 wanted: ShareSource,
199 fps: Arc<AtomicU32>,
200 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
201 failed: impl FnOnce(String) + Send + 'static,
202) -> Result<Capture> {
203 if current_share_picker() == SharePicker::Portal {
204 return start_portal_capture(wanted.kind, fps, deliver, move |follow| {
205 if let PortalFollowUp::Notice(text) = follow {
206 failed(text.to_owned());
207 }
208 });
209 }
210 Capture::spawn_thread("screen-capture", move |stop| {
211 let Some(source) = sources_of(wanted.kind)
212 .into_iter()
213 .find(|(source, _)| source.id == wanted.id)
214 .map(|(_, raw)| raw)
215 else {
216 return failed("the shared source is gone".to_owned());
217 };
218 let Some(mut capturer) = capturer(wanted.kind) else {
219 return failed("screen capture is not available".to_owned());
220 };
221 capturer.start_capture(Some(source), move |result| {
222 let Ok(frame) = result else { return };
223 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
224 if width >= 2 && height >= 2 {
225 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
226 }
227 });
228 while !stop.load(Ordering::SeqCst) {
229 pump_messages();
230 capturer.capture_frame();
231 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
232 }
233 })
234 .map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
235}
236
237/// Where the share menu gets its sources. Wayland and macOS use a system dialog.
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239pub enum SharePicker {
240 List,
241 Portal,
242}
243
244pub fn share_picker_for(wayland_display: Option<&str>) -> SharePicker {
245 share_picker_for_host(cfg!(target_os = "macos"), wayland_display)
246}
247
248pub fn share_picker_for_host(macos: bool, wayland_display: Option<&str>) -> SharePicker {
249 if macos {
250 return SharePicker::Portal;
251 }
252 match wayland_display {
253 Some(value) if !value.is_empty() => SharePicker::Portal,
254 _ => SharePicker::List,
255 }
256}
257
258pub fn current_share_picker() -> SharePicker {
259 share_picker_for(std::env::var("WAYLAND_DISPLAY").ok().as_deref())
260}
261
262/// Portal menus must not enumerate or thumbnail sources. That would open the dialog early.
263pub fn share_sources_for_menu(picker: SharePicker, sources: Vec<ShareSource>) -> Vec<ShareSource> {
264 match picker {
265 SharePicker::Portal => Vec::new(),
266 SharePicker::List => sources,
267 }
268}
269
270pub use crate::notices::PORTAL_UNAVAILABLE_NOTICE;
271
272#[derive(Debug, Clone, PartialEq, Eq)]
273pub enum PortalFollowUp {
274 Share(ShareSource),
275 Quiet,
276 Notice(&'static str),
277}
278
279pub fn portal_follow_up(event: PortalPickerEvent, source: Option<ShareSource>) -> PortalFollowUp {
280 match event {
281 PortalPickerEvent::Selected => match source {
282 Some(source) => PortalFollowUp::Share(source),
283 None => PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE),
284 },
285 PortalPickerEvent::Cancelled => PortalFollowUp::Quiet,
286 PortalPickerEvent::Failed => PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE),
287 }
288}
289
290pub(crate) fn start_portal_capture(
291 kind: ShareKind,
292 fps: Arc<AtomicU32>,
293 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
294 outcome: impl FnOnce(PortalFollowUp) + Send + 'static,
295) -> Result<Capture> {
296 Capture::spawn_thread("portal-share", move |stop| {
297 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
298 let Some(mut capturer) = capturer(kind) else {
299 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
300 return;
301 };
302 let selected = Arc::new(AtomicBool::new(false));
303 let gate = selected.clone();
304 capturer.start_capture(None, move |result| {
305 if !gate.load(Ordering::SeqCst) {
306 return;
307 }
308 let Ok(frame) = result else { return };
309 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
310 if width >= 2 && height >= 2 {
311 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
312 }
313 });
314 if !capturer.has_delegated_picker() {
315 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
316 return;
317 }
318 let (sender, receiver) = std::sync::mpsc::channel();
319 capturer.watch_picker(move |event| {
320 let _ = sender.send(event);
321 });
322 capturer.ensure_picker_visible();
323 let event = loop {
324 if stop.load(Ordering::SeqCst) {
325 return;
326 }
327 match receiver.recv_timeout(Duration::from_millis(40)) {
328 Ok(event) => break event,
329 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
330 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
331 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
332 return;
333 }
334 }
335 };
336 if stop.load(Ordering::SeqCst) {
337 return;
338 }
339 // The portal already bound this stream. Looking the source up again, or
340 // selecting that id, is what used to tear the stream down and report
341 // "the shared source is gone".
342 let source = if event == PortalPickerEvent::Selected {
343 selected.store(true, Ordering::SeqCst);
344 Some(ShareSource {
345 id: 0,
346 kind,
347 title: String::new(),
348 })
349 } else {
350 None
351 };
352 let follow = portal_follow_up(event, source);
353 if !matches!(follow, PortalFollowUp::Share(_)) {
354 outcome(follow);
355 return;
356 }
357 capturer.capture_frame();
358 outcome(follow);
359 while !stop.load(Ordering::SeqCst) {
360 capturer.capture_frame();
361 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
362 }
363 })
364 .map_err(|error| Error::Webrtc(format!("portal thread: {error}")))
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370
371 #[test]
372 fn sources_get_readable_labels() {
373 let screen = ShareSource {
374 id: 1,
375 kind: ShareKind::Screen,
376 title: String::new(),
377 };
378 assert_eq!(screen.label(), "Entire screen");
379 let window = ShareSource {
380 id: 2,
381 kind: ShareKind::Window,
382 title: " Notes ".into(),
383 };
384 assert_eq!(window.label(), "Notes");
385 }
386}
387
388#[cfg(test)]
389mod thumbnail_tests {
390 use super::scaled_bgra;
391
392 #[test]
393 fn a_thumbnail_keeps_the_aspect_and_drops_the_row_padding() {
394 let (width, height, stride) = (8u32, 4u32, 40u32);
395 let mut bytes = vec![0u8; (stride * height) as usize];
396 for row in 0..height as usize {
397 for column in 0..width as usize {
398 let offset = row * stride as usize + column * 4;
399 bytes[offset..offset + 4].copy_from_slice(&[column as u8, row as u8, 7, 0]);
400 }
401 }
402 let picture = scaled_bgra(&bytes, width, height, stride, 4, 4).unwrap();
403 assert_eq!((picture.width, picture.height), (4, 2));
404 assert_eq!(picture.bgra.len(), 4 * 2 * 4);
405 assert_eq!(&picture.bgra[4..8], &[2, 0, 7, 255]);
406 assert!(scaled_bgra(&bytes, width, height, 8, 4, 4).is_none());
407 }
408}
409
410#[cfg(test)]
411mod portal_mode_tests {
412 use super::{
413 ShareKind, SharePicker, ShareSource, share_picker_for_host, share_sources_for_menu,
414 };
415
416 #[test]
417 fn portal_mode_follows_wayland_display_and_skips_the_menu_list() {
418 assert_eq!(share_picker_for_host(false, None), SharePicker::List);
419 assert_eq!(share_picker_for_host(false, Some("")), SharePicker::List);
420 assert_eq!(
421 share_picker_for_host(false, Some("wayland-1")),
422 SharePicker::Portal
423 );
424 assert_eq!(share_picker_for_host(true, None), SharePicker::Portal);
425 assert_eq!(share_picker_for_host(true, Some("")), SharePicker::Portal);
426 let sources = vec![ShareSource {
427 id: 1,
428 kind: ShareKind::Screen,
429 title: "Desk".into(),
430 }];
431 assert!(share_sources_for_menu(SharePicker::Portal, sources.clone()).is_empty());
432 assert_eq!(
433 share_sources_for_menu(SharePicker::List, sources.clone()),
434 sources
435 );
436 }
437}
438
439#[cfg(test)]
440mod portal_share_tests {
441 use libwebrtc::desktop_capturer::PortalPickerEvent;
442
443 use super::{
444 PORTAL_UNAVAILABLE_NOTICE, PortalFollowUp, ShareKind, ShareSource, portal_follow_up,
445 };
446
447 #[test]
448 fn portal_share_cancel_is_quiet_and_failure_is_a_notice() {
449 let source = ShareSource {
450 id: 7,
451 kind: ShareKind::Screen,
452 title: "Desk".into(),
453 };
454 assert!(matches!(
455 portal_follow_up(PortalPickerEvent::Selected, Some(source.clone())),
456 PortalFollowUp::Share(chosen) if chosen == source
457 ));
458 assert!(matches!(
459 portal_follow_up(PortalPickerEvent::Selected, None),
460 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
461 ));
462 assert!(matches!(
463 portal_follow_up(PortalPickerEvent::Cancelled, Some(source.clone())),
464 PortalFollowUp::Quiet
465 ));
466 assert!(matches!(
467 portal_follow_up(PortalPickerEvent::Failed, Some(source)),
468 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
469 ));
470 }
471}
472
473#[cfg(all(test, target_os = "linux"))]
474mod portal_loop_tests {
475 #[test]
476 fn portal_loop_stays_up_across_ensures() {
477 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
478 let id = libwebrtc::desktop_capturer::shared_glib_loop_id();
479 assert_ne!(id, 0);
480 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
481 assert_eq!(id, libwebrtc::desktop_capturer::shared_glib_loop_id());
482 }
483}
484
485#[cfg(all(test, target_os = "linux"))]
486mod portal_smoke {
487 use std::sync::Arc;
488 use std::sync::atomic::{AtomicU32, Ordering};
489 use std::time::Duration;
490
491 use super::{PortalFollowUp, ShareKind, start_portal_capture};
492
493 #[test]
494 fn portal_smoke_captures_after_the_dialog() {
495 if std::env::var("PORTAL_SMOKE").ok().as_deref() != Some("1") {
496 return;
497 }
498 let frames = Arc::new(AtomicU32::new(0));
499 let counter = frames.clone();
500 let (sender, receiver) = std::sync::mpsc::channel();
501 let capture = start_portal_capture(
502 ShareKind::Screen,
503 Arc::new(AtomicU32::new(5)),
504 move |_| {
505 counter.fetch_add(1, Ordering::Relaxed);
506 },
507 move |follow| {
508 eprintln!("PORTAL_FOLLOW={follow:?}");
509 let _ = sender.send(follow);
510 },
511 )
512 .expect("portal thread");
513 let follow = receiver
514 .recv_timeout(Duration::from_secs(40))
515 .expect("no portal result in 40s");
516 std::thread::sleep(Duration::from_millis(700));
517 let count = frames.load(Ordering::Relaxed);
518 eprintln!("PORTAL_FRAMES={count}");
519 drop(capture);
520 match follow {
521 PortalFollowUp::Share(_) => {
522 assert!(count > 0, "the dialog confirmed, but no frame arrived")
523 }
524 PortalFollowUp::Quiet => panic!("the dialog was cancelled"),
525 PortalFollowUp::Notice(text) => panic!("portal notice: {text}"),
526 }
527 }
528}