BlueGit

ict rusty-teams

Files

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

screen.rs

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