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