BlueGit

ict rusty-teams

Files

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

screen.rs

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