BlueGit

ict rusty-teams

Files

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

screen.rs

screen.rs 17.9 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
312pub(crate) fn start_portal_capture(
313 kind: ShareKind,
314 fps: Arc<AtomicU32>,
315 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
316 outcome: impl FnOnce(PortalFollowUp) + Send + 'static,
317) -> Result<Capture> {
318 Capture::spawn_thread("portal-share", move |stop| {
319 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
320 let Some(mut capturer) = capturer(kind) else {
321 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
322 return;
323 };
324 let selected = Arc::new(AtomicBool::new(false));
325 let gate = selected.clone();
326 capturer.start_capture(None, move |result| {
327 if !gate.load(Ordering::SeqCst) {
328 return;
329 }
330 let Ok(frame) = result else { return };
331 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
332 if width >= 2 && height >= 2 {
333 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
334 }
335 });
336 if !capturer.has_delegated_picker() {
337 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
338 return;
339 }
340 let (sender, receiver) = std::sync::mpsc::channel();
341 capturer.watch_picker(move |event| {
342 let _ = sender.send(event);
343 });
344 capturer.ensure_picker_visible();
345 let event = loop {
346 if stop.load(Ordering::SeqCst) {
347 return;
348 }
349 match receiver.recv_timeout(Duration::from_millis(40)) {
350 Ok(event) => break event,
351 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
352 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
353 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
354 return;
355 }
356 }
357 };
358 if stop.load(Ordering::SeqCst) {
359 return;
360 }
361 // The portal already bound this stream. Looking the source up again, or
362 // selecting that id, is what used to tear the stream down and report
363 // "the shared source is gone".
364 let source = if event == PortalPickerEvent::Selected {
365 selected.store(true, Ordering::SeqCst);
366 Some(ShareSource {
367 id: 0,
368 kind,
369 title: String::new(),
370 })
371 } else {
372 None
373 };
374 let follow = portal_follow_up(event, source);
375 if !matches!(follow, PortalFollowUp::Share(_)) {
376 outcome(follow);
377 return;
378 }
379 capturer.capture_frame();
380 outcome(follow);
381 while !stop.load(Ordering::SeqCst) {
382 capturer.capture_frame();
383 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
384 }
385 })
386 .map_err(|error| Error::Webrtc(format!("portal thread: {error}")))
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392
393 #[test]
394 fn sources_get_readable_labels() {
395 let screen = ShareSource {
396 id: 1,
397 kind: ShareKind::Screen,
398 title: String::new(),
399 };
400 assert_eq!(screen.label(), "Entire screen");
401 let window = ShareSource {
402 id: 2,
403 kind: ShareKind::Window,
404 title: " Notes ".into(),
405 };
406 assert_eq!(window.label(), "Notes");
407 }
408}
409
410#[cfg(test)]
411mod thumbnail_tests {
412 use super::scaled_bgra;
413
414 #[test]
415 fn a_thumbnail_keeps_the_aspect_and_drops_the_row_padding() {
416 let (width, height, stride) = (8u32, 4u32, 40u32);
417 let mut bytes = vec![0u8; (stride * height) as usize];
418 for row in 0..height as usize {
419 for column in 0..width as usize {
420 let offset = row * stride as usize + column * 4;
421 bytes[offset..offset + 4].copy_from_slice(&[column as u8, row as u8, 7, 0]);
422 }
423 }
424 let picture = scaled_bgra(&bytes, width, height, stride, 4, 4).unwrap();
425 assert_eq!((picture.width, picture.height), (4, 2));
426 assert_eq!(picture.bgra.len(), 4 * 2 * 4);
427 assert_eq!(&picture.bgra[4..8], &[2, 0, 7, 255]);
428 assert!(scaled_bgra(&bytes, width, height, 8, 4, 4).is_none());
429 }
430}
431
432#[cfg(test)]
433mod portal_mode_tests {
434 use super::{
435 ShareKind, SharePicker, ShareSource, share_picker_for_host, share_sources_for_menu,
436 };
437
438 #[test]
439 fn portal_mode_follows_wayland_display_and_skips_the_menu_list() {
440 assert_eq!(share_picker_for_host(false, None), SharePicker::List);
441 assert_eq!(share_picker_for_host(false, Some("")), SharePicker::List);
442 assert_eq!(
443 share_picker_for_host(false, Some("wayland-1")),
444 SharePicker::Portal
445 );
446 assert_eq!(share_picker_for_host(true, None), SharePicker::Portal);
447 assert_eq!(share_picker_for_host(true, Some("")), SharePicker::Portal);
448 let sources = vec![ShareSource {
449 id: 1,
450 kind: ShareKind::Screen,
451 title: "Desk".into(),
452 }];
453 assert!(share_sources_for_menu(SharePicker::Portal, sources.clone()).is_empty());
454 assert_eq!(
455 share_sources_for_menu(SharePicker::List, sources.clone()),
456 sources
457 );
458 }
459}
460
461#[cfg(test)]
462mod portal_share_tests {
463 use libwebrtc::desktop_capturer::PortalPickerEvent;
464
465 use super::{
466 PORTAL_UNAVAILABLE_NOTICE, PortalFollowUp, ShareKind, ShareSource, portal_follow_up,
467 };
468
469 #[test]
470 fn portal_share_cancel_is_quiet_and_failure_is_a_notice() {
471 let source = ShareSource {
472 id: 7,
473 kind: ShareKind::Screen,
474 title: "Desk".into(),
475 };
476 assert!(matches!(
477 portal_follow_up(PortalPickerEvent::Selected, Some(source.clone())),
478 PortalFollowUp::Share(chosen) if chosen == source
479 ));
480 assert!(matches!(
481 portal_follow_up(PortalPickerEvent::Selected, None),
482 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
483 ));
484 assert!(matches!(
485 portal_follow_up(PortalPickerEvent::Cancelled, Some(source.clone())),
486 PortalFollowUp::Quiet
487 ));
488 assert!(matches!(
489 portal_follow_up(PortalPickerEvent::Failed, Some(source)),
490 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
491 ));
492 }
493}
494
495#[cfg(all(test, target_os = "linux"))]
496mod portal_loop_tests {
497 #[test]
498 fn portal_loop_stays_up_across_ensures() {
499 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
500 let id = libwebrtc::desktop_capturer::shared_glib_loop_id();
501 assert_ne!(id, 0);
502 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
503 assert_eq!(id, libwebrtc::desktop_capturer::shared_glib_loop_id());
504 }
505}
506
507#[cfg(all(test, target_os = "linux"))]
508mod portal_smoke {
509 use std::sync::Arc;
510 use std::sync::atomic::{AtomicU32, Ordering};
511 use std::time::Duration;
512
513 use super::{PortalFollowUp, ShareKind, start_portal_capture};
514
515 #[test]
516 fn portal_smoke_captures_after_the_dialog() {
517 if std::env::var("PORTAL_SMOKE").ok().as_deref() != Some("1") {
518 return;
519 }
520 let frames = Arc::new(AtomicU32::new(0));
521 let counter = frames.clone();
522 let (sender, receiver) = std::sync::mpsc::channel();
523 let capture = start_portal_capture(
524 ShareKind::Screen,
525 Arc::new(AtomicU32::new(5)),
526 move |_| {
527 counter.fetch_add(1, Ordering::Relaxed);
528 },
529 move |follow| {
530 eprintln!("PORTAL_FOLLOW={follow:?}");
531 let _ = sender.send(follow);
532 },
533 )
534 .expect("portal thread");
535 let follow = receiver
536 .recv_timeout(Duration::from_secs(40))
537 .expect("no portal result in 40s");
538 std::thread::sleep(Duration::from_millis(700));
539 let count = frames.load(Ordering::Relaxed);
540 eprintln!("PORTAL_FRAMES={count}");
541 drop(capture);
542 match follow {
543 PortalFollowUp::Share(_) => {
544 assert!(count > 0, "the dialog confirmed, but no frame arrived")
545 }
546 PortalFollowUp::Quiet => panic!("the dialog was cancelled"),
547 PortalFollowUp::Notice(text) => panic!("portal notice: {text}"),
548 }
549 }
550}