BlueGit

ict rusty-teams

Files

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

screen.rs

screen.rs 16.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 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 const PORTAL_UNAVAILABLE_NOTICE: &str =
244 "Screen sharing needs the desktop share dialog, and it could not open.";
245
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub enum PortalFollowUp {
248 Share(ShareSource),
249 Quiet,
250 Notice(&'static str),
251}
252
253pub fn portal_follow_up(event: PortalPickerEvent, source: Option<ShareSource>) -> PortalFollowUp {
254 match event {
255 PortalPickerEvent::Selected => match source {
256 Some(source) => PortalFollowUp::Share(source),
257 None => PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE),
258 },
259 PortalPickerEvent::Cancelled => PortalFollowUp::Quiet,
260 PortalPickerEvent::Failed => PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE),
261 }
262}
263
264pub(crate) fn start_portal_capture(
265 kind: ShareKind,
266 fps: Arc<AtomicU32>,
267 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
268 outcome: impl FnOnce(PortalFollowUp) + Send + 'static,
269) -> Result<Capture> {
270 Capture::spawn_thread("portal-share", move |stop| {
271 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
272 let Some(mut capturer) = capturer(kind) else {
273 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
274 return;
275 };
276 let selected = Arc::new(AtomicBool::new(false));
277 let gate = selected.clone();
278 capturer.start_capture(None, move |result| {
279 if !gate.load(Ordering::SeqCst) {
280 return;
281 }
282 let Ok(frame) = result else { return };
283 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
284 if width >= 2 && height >= 2 {
285 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
286 }
287 });
288 if !capturer.has_delegated_picker() {
289 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
290 return;
291 }
292 let (sender, receiver) = std::sync::mpsc::channel();
293 capturer.watch_picker(move |event| {
294 let _ = sender.send(event);
295 });
296 capturer.ensure_picker_visible();
297 let event = loop {
298 if stop.load(Ordering::SeqCst) {
299 return;
300 }
301 match receiver.recv_timeout(Duration::from_millis(40)) {
302 Ok(event) => break event,
303 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
304 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
305 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
306 return;
307 }
308 }
309 };
310 if stop.load(Ordering::SeqCst) {
311 return;
312 }
313 // The portal already bound this stream. Looking the source up again, or
314 // selecting that id, is what used to tear the stream down and report
315 // "the shared source is gone".
316 let source = if event == PortalPickerEvent::Selected {
317 selected.store(true, Ordering::SeqCst);
318 Some(ShareSource {
319 id: 0,
320 kind,
321 title: String::new(),
322 })
323 } else {
324 None
325 };
326 let follow = portal_follow_up(event, source);
327 if !matches!(follow, PortalFollowUp::Share(_)) {
328 outcome(follow);
329 return;
330 }
331 capturer.capture_frame();
332 outcome(follow);
333 while !stop.load(Ordering::SeqCst) {
334 capturer.capture_frame();
335 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
336 }
337 })
338 .map_err(|error| Error::Webrtc(format!("portal thread: {error}")))
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344
345 #[test]
346 fn sources_get_readable_labels() {
347 let screen = ShareSource {
348 id: 1,
349 kind: ShareKind::Screen,
350 title: String::new(),
351 };
352 assert_eq!(screen.label(), "Entire screen");
353 let window = ShareSource {
354 id: 2,
355 kind: ShareKind::Window,
356 title: " Notes ".into(),
357 };
358 assert_eq!(window.label(), "Notes");
359 }
360}
361
362#[cfg(test)]
363mod thumbnail_tests {
364 use super::scaled_bgra;
365
366 #[test]
367 fn a_thumbnail_keeps_the_aspect_and_drops_the_row_padding() {
368 let (width, height, stride) = (8u32, 4u32, 40u32);
369 let mut bytes = vec![0u8; (stride * height) as usize];
370 for row in 0..height as usize {
371 for column in 0..width as usize {
372 let offset = row * stride as usize + column * 4;
373 bytes[offset..offset + 4].copy_from_slice(&[column as u8, row as u8, 7, 0]);
374 }
375 }
376 let picture = scaled_bgra(&bytes, width, height, stride, 4, 4).unwrap();
377 assert_eq!((picture.width, picture.height), (4, 2));
378 assert_eq!(picture.bgra.len(), 4 * 2 * 4);
379 assert_eq!(&picture.bgra[4..8], &[2, 0, 7, 255]);
380 assert!(scaled_bgra(&bytes, width, height, 8, 4, 4).is_none());
381 }
382}
383
384#[cfg(test)]
385mod portal_mode_tests {
386 use super::{ShareKind, SharePicker, ShareSource, share_picker_for, share_sources_for_menu};
387
388 #[test]
389 fn portal_mode_follows_wayland_display_and_skips_the_menu_list() {
390 assert_eq!(share_picker_for(None), SharePicker::List);
391 assert_eq!(share_picker_for(Some("")), SharePicker::List);
392 assert_eq!(share_picker_for(Some("wayland-1")), SharePicker::Portal);
393 let sources = vec![ShareSource {
394 id: 1,
395 kind: ShareKind::Screen,
396 title: "Desk".into(),
397 }];
398 assert!(share_sources_for_menu(SharePicker::Portal, sources.clone()).is_empty());
399 assert_eq!(
400 share_sources_for_menu(SharePicker::List, sources.clone()),
401 sources
402 );
403 }
404}
405
406#[cfg(test)]
407mod portal_share_tests {
408 use libwebrtc::desktop_capturer::PortalPickerEvent;
409
410 use super::{
411 PORTAL_UNAVAILABLE_NOTICE, PortalFollowUp, ShareKind, ShareSource, portal_follow_up,
412 };
413
414 #[test]
415 fn portal_share_cancel_is_quiet_and_failure_is_a_notice() {
416 let source = ShareSource {
417 id: 7,
418 kind: ShareKind::Screen,
419 title: "Desk".into(),
420 };
421 assert!(matches!(
422 portal_follow_up(PortalPickerEvent::Selected, Some(source.clone())),
423 PortalFollowUp::Share(chosen) if chosen == source
424 ));
425 assert!(matches!(
426 portal_follow_up(PortalPickerEvent::Selected, None),
427 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
428 ));
429 assert!(matches!(
430 portal_follow_up(PortalPickerEvent::Cancelled, Some(source.clone())),
431 PortalFollowUp::Quiet
432 ));
433 assert!(matches!(
434 portal_follow_up(PortalPickerEvent::Failed, Some(source)),
435 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
436 ));
437 }
438}
439
440#[cfg(all(test, target_os = "linux"))]
441mod portal_loop_tests {
442 #[test]
443 fn portal_loop_stays_up_across_ensures() {
444 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
445 let id = libwebrtc::desktop_capturer::shared_glib_loop_id();
446 assert_ne!(id, 0);
447 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
448 assert_eq!(id, libwebrtc::desktop_capturer::shared_glib_loop_id());
449 }
450}
451
452#[cfg(all(test, target_os = "linux"))]
453mod portal_smoke {
454 use std::sync::Arc;
455 use std::sync::atomic::{AtomicU32, Ordering};
456 use std::time::Duration;
457
458 use super::{PortalFollowUp, ShareKind, start_portal_capture};
459
460 #[test]
461 fn portal_smoke_captures_after_the_dialog() {
462 if std::env::var("PORTAL_SMOKE").ok().as_deref() != Some("1") {
463 return;
464 }
465 let frames = Arc::new(AtomicU32::new(0));
466 let counter = frames.clone();
467 let (sender, receiver) = std::sync::mpsc::channel();
468 let capture = start_portal_capture(
469 ShareKind::Screen,
470 Arc::new(AtomicU32::new(5)),
471 move |_| {
472 counter.fetch_add(1, Ordering::Relaxed);
473 },
474 move |follow| {
475 eprintln!("PORTAL_FOLLOW={follow:?}");
476 let _ = sender.send(follow);
477 },
478 )
479 .expect("portal thread");
480 let follow = receiver
481 .recv_timeout(Duration::from_secs(40))
482 .expect("no portal result in 40s");
483 std::thread::sleep(Duration::from_millis(700));
484 let count = frames.load(Ordering::Relaxed);
485 eprintln!("PORTAL_FRAMES={count}");
486 drop(capture);
487 match follow {
488 PortalFollowUp::Share(_) => {
489 assert!(count > 0, "the dialog confirmed, but no frame arrived")
490 }
491 PortalFollowUp::Quiet => panic!("the dialog was cancelled"),
492 PortalFollowUp::Notice(text) => panic!("portal notice: {text}"),
493 }
494 }
495}