BlueGit

ict rusty-teams

Files

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

screen.rs

screen.rs 30.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_scale, argb_to_i420};
10use libwebrtc::video_frame::I420Buffer;
11
12use crate::capture::Capture;
13use crate::error::{Error, Result};
14use crate::video_frame::VideoPicture;
15use crate::win_timer::HighResSleep;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ShareKind {
19 Screen,
20 Window,
21}
22
23impl ShareKind {
24 fn source_type(self) -> DesktopCaptureSourceType {
25 match self {
26 ShareKind::Screen => DesktopCaptureSourceType::Screen,
27 ShareKind::Window => DesktopCaptureSourceType::Window,
28 }
29 }
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct ShareSource {
34 pub id: u64,
35 pub kind: ShareKind,
36 pub title: String,
37}
38
39impl ShareSource {
40 pub fn label(&self) -> String {
41 match (self.kind, self.title.trim()) {
42 (ShareKind::Screen, "") => "Entire screen".to_owned(),
43 (_, "") => "Window".to_owned(),
44 (_, title) => title.to_owned(),
45 }
46 }
47}
48
49fn capturer(kind: ShareKind) -> Option<DesktopCapturer> {
50 let mut options = DesktopCapturerOptions::new(kind.source_type());
51 options.set_include_cursor(true);
52 DesktopCapturer::new(options)
53}
54
55fn sources_of(kind: ShareKind) -> Vec<(ShareSource, CaptureSource)> {
56 let Some(capturer) = capturer(kind) else {
57 return Vec::new();
58 };
59 capturer
60 .get_source_list()
61 .into_iter()
62 .map(|source| {
63 (
64 ShareSource {
65 id: source.id(),
66 kind,
67 title: source.title(),
68 },
69 source,
70 )
71 })
72 .collect()
73}
74
75pub fn list_share_sources() -> Vec<ShareSource> {
76 [ShareKind::Screen, ShareKind::Window]
77 .into_iter()
78 .flat_map(|kind| sources_of(kind).into_iter().map(|(source, _)| source))
79 .collect()
80}
81
82const THUMBNAIL_ATTEMPTS: u32 = 5;
83const SOURCE_GONE_AFTER: Duration = Duration::from_secs(3);
84const THUMBNAIL_RETRY: Duration = Duration::from_millis(40);
85
86pub fn share_thumbnail(
87 wanted: &ShareSource,
88 max_width: u32,
89 max_height: u32,
90) -> Option<VideoPicture> {
91 let source = sources_of(wanted.kind)
92 .into_iter()
93 .find(|(source, _)| source.id == wanted.id)
94 .map(|(_, raw)| raw)?;
95 let mut capturer = capturer(wanted.kind)?;
96 let captured: Arc<Mutex<Option<VideoPicture>>> = Arc::default();
97 let sink = captured.clone();
98 capturer.start_capture(Some(source), move |result| {
99 let Ok(frame) = result else { return };
100 let (width, height) = (frame.width().max(0) as u32, frame.height().max(0) as u32);
101 if let Some(picture) = scaled_bgra(
102 frame.data(),
103 width,
104 height,
105 frame.stride(),
106 max_width,
107 max_height,
108 ) && let Ok(mut slot) = sink.lock()
109 {
110 *slot = Some(picture);
111 }
112 });
113 for _ in 0..THUMBNAIL_ATTEMPTS {
114 pump_messages();
115 capturer.capture_frame();
116 if let Some(picture) = captured.lock().ok().and_then(|mut slot| slot.take()) {
117 return Some(picture);
118 }
119 std::thread::sleep(THUMBNAIL_RETRY);
120 }
121 None
122}
123
124// Windows Graphics Capture hands frames to a DispatcherQueue on this thread; without a pump none arrive.
125#[cfg(windows)]
126fn pump_messages() {
127 use windows::Win32::UI::WindowsAndMessaging::{
128 DispatchMessageW, MSG, PM_REMOVE, PeekMessageW, TranslateMessage,
129 };
130 let mut message = MSG::default();
131 unsafe {
132 while PeekMessageW(&mut message, None, 0, 0, PM_REMOVE).as_bool() {
133 let _ = TranslateMessage(&message);
134 let _ = DispatchMessageW(&message);
135 }
136 }
137}
138
139#[cfg(not(windows))]
140fn pump_messages() {}
141
142fn scaled_bgra(
143 bytes: &[u8],
144 width: u32,
145 height: u32,
146 stride: u32,
147 max_width: u32,
148 max_height: u32,
149) -> Option<VideoPicture> {
150 if width == 0
151 || height == 0
152 || (stride as usize) < width as usize * 4
153 || bytes.len() < stride as usize * height as usize
154 {
155 return None;
156 }
157 let scale = (max_width as f32 / width as f32)
158 .min(max_height as f32 / height as f32)
159 .min(1.);
160 let (target_width, target_height) = (
161 ((width as f32 * scale) as u32).max(1),
162 ((height as f32 * scale) as u32).max(1),
163 );
164 let mut bgra = Vec::with_capacity(target_width as usize * target_height as usize * 4);
165 for row in 0..target_height {
166 let source_row = (row as u64 * height as u64 / target_height as u64) as usize;
167 for column in 0..target_width {
168 let source_column = (column as u64 * width as u64 / target_width as u64) as usize;
169 let offset = source_row * stride as usize + source_column * 4;
170 bgra.extend_from_slice(&[bytes[offset], bytes[offset + 1], bytes[offset + 2], u8::MAX]);
171 }
172 }
173 Some(VideoPicture {
174 width: target_width,
175 height: target_height,
176 bgra,
177 })
178}
179
180const SHARE_SEND_MAX_FS: u32 = 8160;
181const MACROBLOCK: u32 = 16;
182
183fn macroblocks(width: u32, height: u32) -> u32 {
184 width.div_ceil(MACROBLOCK) * height.div_ceil(MACROBLOCK)
185}
186
187fn even(value: u32) -> u32 {
188 value & !1
189}
190
191fn buffer_covers(bytes: &[u8], width: u32, height: u32, stride: u32) -> bool {
192 width >= 2
193 && height >= 2
194 && stride as usize >= width as usize * 4
195 && bytes.len() >= stride as usize * height as usize
196}
197
198pub(crate) fn fit_share_size(width: u32, height: u32, max_fs: u32) -> (u32, u32) {
199 let (width, height) = (even(width), even(height));
200 if width < 2 || height < 2 || max_fs == 0 || macroblocks(width, height) <= max_fs {
201 return (width, height);
202 }
203 let mut scale = (f64::from(macroblocks(width, height)) / f64::from(max_fs)).sqrt();
204 let mut target_width = even((f64::from(width) / scale) as u32).max(2);
205 let mut target_height = even((f64::from(height) / scale) as u32).max(2);
206 while macroblocks(target_width, target_height) > max_fs && target_width > 2 && target_height > 2
207 {
208 scale *= 1.05;
209 target_width = even((f64::from(width) / scale) as u32).max(2);
210 target_height = even((f64::from(height) / scale) as u32).max(2);
211 }
212 (target_width, target_height)
213}
214
215fn scale_bgra_to(
216 bytes: &[u8],
217 width: u32,
218 height: u32,
219 stride: u32,
220 target_width: u32,
221 target_height: u32,
222) -> Vec<u8> {
223 let mut scaled = vec![0u8; target_width as usize * target_height as usize * 4];
224 argb_scale(
225 bytes,
226 stride,
227 width as i32,
228 height as i32,
229 &mut scaled,
230 target_width * 4,
231 target_width as i32,
232 target_height as i32,
233 );
234 scaled
235}
236
237fn share_frame(bytes: &[u8], width: u32, height: u32, stride: u32) -> Option<I420Buffer> {
238 let (width, height) = (even(width), even(height));
239 if !buffer_covers(bytes, width, height, stride) {
240 return None;
241 }
242 let (target_width, target_height) = fit_share_size(width, height, SHARE_SEND_MAX_FS);
243 if target_width == width && target_height == height {
244 return Some(i420_from_bgra(bytes, width, height, stride));
245 }
246 let scaled = scale_bgra_to(bytes, width, height, stride, target_width, target_height);
247 Some(i420_from_bgra(
248 &scaled,
249 target_width,
250 target_height,
251 target_width * 4,
252 ))
253}
254
255fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buffer {
256 let mut buffer = I420Buffer::new(width, height);
257 let (stride_y, stride_u, stride_v) = buffer.strides();
258 let (plane_y, plane_u, plane_v) = buffer.data_mut();
259 argb_to_i420(
260 bytes,
261 stride,
262 plane_y,
263 stride_y,
264 plane_u,
265 stride_u,
266 plane_v,
267 stride_v,
268 width as i32,
269 height as i32,
270 );
271 buffer
272}
273
274/// `ended` runs at most once, when the share stops on its own: with the reason
275/// to show, or with `None` when the user stopped it outside the app.
276pub fn start_screen_capture(
277 wanted: ShareSource,
278 fps: Arc<AtomicU32>,
279 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
280 ended: impl FnOnce(Option<String>) + Send + 'static,
281) -> Result<Capture> {
282 if current_share_picker() == SharePicker::Portal {
283 let ended = Arc::new(Mutex::new(Some(ended)));
284 let failed = ended.clone();
285 return start_portal_capture(
286 wanted.kind,
287 fps,
288 deliver,
289 move |follow| {
290 if let PortalFollowUp::Notice(text) = follow
291 && let Some(failed) = take_once(&failed)
292 {
293 failed(Some(text.to_owned()));
294 }
295 },
296 move |reason| {
297 if let Some(ended) = take_once(&ended) {
298 ended(reason);
299 }
300 },
301 );
302 }
303 Capture::spawn_thread("screen-capture", move |stop| {
304 let Some(source) = sources_of(wanted.kind)
305 .into_iter()
306 .find(|(source, _)| source.id == wanted.id)
307 .map(|(_, raw)| raw)
308 else {
309 return ended(Some("the shared source is gone".to_owned()));
310 };
311 let Some(mut capturer) = capturer(wanted.kind) else {
312 return ended(Some("screen capture is not available".to_owned()));
313 };
314 let gone_since: Arc<Mutex<Option<Instant>>> = Arc::default();
315 let gone_mark = gone_since.clone();
316 capturer.start_capture(Some(source), move |result| {
317 let frame = match result {
318 Ok(frame) => frame,
319 Err(error) => {
320 if matches!(error, CaptureError::Permanent | CaptureError::SourceGone)
321 && let Ok(mut since) = gone_mark.lock()
322 {
323 since.get_or_insert_with(Instant::now);
324 }
325 return;
326 }
327 };
328 if let Ok(mut since) = gone_mark.lock() {
329 *since = None;
330 }
331 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
332 if let Some(picture) = share_frame(frame.data(), width, height, frame.stride()) {
333 deliver(picture);
334 }
335 });
336 let sleeper = HighResSleep::new();
337 while !stop.load(Ordering::SeqCst) {
338 let started = Instant::now();
339 let gone = gone_since
340 .lock()
341 .is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));
342 if gone {
343 return ended(Some("the shared source is gone".to_owned()));
344 }
345 pump_messages();
346 capturer.capture_frame();
347 let period = Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1);
348 sleeper.sleep_until(started + period);
349 }
350 })
351 .map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
352}
353
354fn take_once<F>(slot: &Mutex<Option<F>>) -> Option<F> {
355 slot.lock().ok()?.take()
356}
357
358/// Where the share menu gets its sources. Wayland and macOS use a system dialog.
359#[derive(Debug, Clone, Copy, PartialEq, Eq)]
360pub enum SharePicker {
361 List,
362 Portal,
363}
364
365pub fn share_picker_for(wayland_display: Option<&str>) -> SharePicker {
366 share_picker_for_host(cfg!(target_os = "macos"), wayland_display)
367}
368
369pub fn share_picker_for_host(macos: bool, wayland_display: Option<&str>) -> SharePicker {
370 if macos {
371 return SharePicker::Portal;
372 }
373 match wayland_display {
374 Some(value) if !value.is_empty() => SharePicker::Portal,
375 _ => SharePicker::List,
376 }
377}
378
379pub fn current_share_picker() -> SharePicker {
380 share_picker_for(std::env::var("WAYLAND_DISPLAY").ok().as_deref())
381}
382
383/// Portal menus must not enumerate or thumbnail sources. That would open the dialog early.
384pub fn share_sources_for_menu(picker: SharePicker, sources: Vec<ShareSource>) -> Vec<ShareSource> {
385 match picker {
386 SharePicker::Portal => Vec::new(),
387 SharePicker::List => sources,
388 }
389}
390
391pub use crate::notices::{PORTAL_UNAVAILABLE_NOTICE, SHARE_SOURCE_GONE_NOTICE};
392
393#[derive(Debug, Clone, PartialEq, Eq)]
394pub enum PortalFollowUp {
395 Share(ShareSource),
396 Quiet,
397 Notice(&'static str),
398}
399
400pub fn portal_follow_up(event: PortalPickerEvent, source: Option<ShareSource>) -> PortalFollowUp {
401 match event {
402 PortalPickerEvent::Selected => match source {
403 Some(source) => PortalFollowUp::Share(source),
404 None => PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE),
405 },
406 PortalPickerEvent::Cancelled => PortalFollowUp::Quiet,
407 PortalPickerEvent::Failed => PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE),
408 }
409}
410
411#[derive(Debug, Clone, Copy, PartialEq, Eq)]
412enum PickerOutcome {
413 Portal(PortalPickerEvent),
414 SourceGone,
415}
416
417fn picker_follow_up(outcome: PickerOutcome, source: Option<ShareSource>) -> PortalFollowUp {
418 match outcome {
419 PickerOutcome::Portal(event) => portal_follow_up(event, source),
420 PickerOutcome::SourceGone => PortalFollowUp::Notice(SHARE_SOURCE_GONE_NOTICE),
421 }
422}
423
424/// What a frame result says about a system picker without a delegated
425/// controller (macOS). Frames start once a source is picked. A cancel turns
426/// into `Cancelled`, a disappearing source turns into `SourceGone`, and a
427/// capture that fails to start turns into `Failed`.
428fn picker_event_from_frame<T>(
429 result: &std::result::Result<T, CaptureError>,
430) -> Option<PickerOutcome> {
431 match result {
432 Ok(_) => Some(PickerOutcome::Portal(PortalPickerEvent::Selected)),
433 Err(CaptureError::Permanent | CaptureError::StoppedByUser) => {
434 Some(PickerOutcome::Portal(PortalPickerEvent::Cancelled))
435 }
436 Err(CaptureError::SourceGone) => Some(PickerOutcome::SourceGone),
437 Err(CaptureError::StartFailed | CaptureError::Interrupted) => {
438 Some(PickerOutcome::Portal(PortalPickerEvent::Failed))
439 }
440 Err(CaptureError::Temporary) => None,
441 }
442}
443
444#[derive(Debug, Clone, Copy, PartialEq, Eq)]
445enum ActiveShareStop {
446 Quiet,
447 Notice(&'static str),
448}
449
450/// Classifies an error received while a portal share is active.
451///
452/// Wayland reports a desktop stop, a closed window, and a PipeWire or compositor
453/// failure after the first frame all as `Permanent`. Those stay quiet: the portal
454/// does not say which one it was, and a notice would fire on every Stop sharing.
455/// A permanent error before the first frame still shows a notice. macOS uses
456/// `StoppedByUser` for the menu-bar stop, so a later `Permanent` there stays a
457/// failure notice.
458fn active_portal_error(
459 error: CaptureError,
460 delegated: bool,
461 seen_frame: bool,
462) -> Option<ActiveShareStop> {
463 match error {
464 CaptureError::StoppedByUser => Some(ActiveShareStop::Quiet),
465 CaptureError::Permanent if delegated && seen_frame => Some(ActiveShareStop::Quiet),
466 CaptureError::StartFailed | CaptureError::Interrupted => {
467 Some(ActiveShareStop::Notice("macOS stopped the capture"))
468 }
469 CaptureError::Permanent => Some(ActiveShareStop::Notice("the system stopped the capture")),
470 CaptureError::Temporary | CaptureError::SourceGone => None,
471 }
472}
473
474pub(crate) fn start_portal_capture(
475 kind: ShareKind,
476 fps: Arc<AtomicU32>,
477 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
478 outcome: impl FnOnce(PortalFollowUp) + Send + 'static,
479 ended: impl FnOnce(Option<String>) + Send + 'static,
480) -> Result<Capture> {
481 Capture::spawn_thread("portal-share", move |stop| {
482 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
483 let Some(mut capturer) = capturer(kind) else {
484 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
485 return;
486 };
487 let mut last_fps = fps.load(Ordering::Relaxed).max(1);
488 capturer.set_max_frame_rate(last_fps);
489 // The Wayland portal reports the pick through a delegated picker. The
490 // macOS system picker has none: it opens in `start_capture` and the
491 // outcome shows in the frame results.
492 let delegated = capturer.has_delegated_picker();
493 if !delegated && !cfg!(target_os = "macos") {
494 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
495 return;
496 }
497 let (sender, receiver) = std::sync::mpsc::channel();
498 let frame_events = (!delegated).then(|| sender.clone());
499 let selected = Arc::new(AtomicBool::new(false));
500 let gate = selected.clone();
501 // A closed window gets the same grace as in the source list: it may
502 // reopen, and the remote side keeps the last frame meanwhile.
503 let gone_since: Arc<Mutex<Option<Instant>>> = Arc::default();
504 let gone_mark = gone_since.clone();
505 let active_end: Arc<Mutex<Option<ActiveShareStop>>> = Arc::default();
506 let end_mark = active_end.clone();
507 let seen_frame = Arc::new(AtomicBool::new(false));
508 capturer.start_capture(None, move |result| {
509 if !gate.load(Ordering::SeqCst) {
510 let Some(events) = &frame_events else { return };
511 let Some(event) = picker_event_from_frame(&result) else {
512 return;
513 };
514 let _ = events.send(event);
515 if event != PickerOutcome::Portal(PortalPickerEvent::Selected) {
516 return;
517 }
518 gate.store(true, Ordering::SeqCst);
519 }
520 match result {
521 Ok(frame) => {
522 seen_frame.store(true, Ordering::SeqCst);
523 if let Ok(mut since) = gone_mark.lock() {
524 *since = None;
525 }
526 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
527 if let Some(picture) = share_frame(frame.data(), width, height, frame.stride())
528 {
529 deliver(picture);
530 }
531 }
532 Err(CaptureError::Temporary) => {
533 if let Ok(mut since) = gone_mark.lock() {
534 *since = None;
535 }
536 }
537 Err(CaptureError::SourceGone) => {
538 if let Ok(mut since) = gone_mark.lock() {
539 since.get_or_insert_with(Instant::now);
540 }
541 }
542 Err(error) => {
543 if let Some(stop_reason) =
544 active_portal_error(error, delegated, seen_frame.load(Ordering::SeqCst))
545 && let Ok(mut slot) = end_mark.lock()
546 {
547 slot.get_or_insert(stop_reason);
548 }
549 }
550 }
551 });
552 if delegated {
553 capturer.watch_picker(move |event| {
554 let _ = sender.send(PickerOutcome::Portal(event));
555 });
556 capturer.ensure_picker_visible();
557 }
558 let event = loop {
559 if stop.load(Ordering::SeqCst) {
560 return;
561 }
562 if !delegated {
563 capturer.capture_frame();
564 }
565 match receiver.recv_timeout(Duration::from_millis(40)) {
566 Ok(event) => break event,
567 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
568 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
569 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
570 return;
571 }
572 }
573 };
574 if stop.load(Ordering::SeqCst) {
575 return;
576 }
577 // The portal already bound this stream. Looking the source up again, or
578 // selecting that id, is what used to tear the stream down and report
579 // "the shared source is gone".
580 let source = if event == PickerOutcome::Portal(PortalPickerEvent::Selected) {
581 selected.store(true, Ordering::SeqCst);
582 Some(ShareSource {
583 id: 0,
584 kind,
585 title: String::new(),
586 })
587 } else {
588 None
589 };
590 let follow = picker_follow_up(event, source);
591 if !matches!(follow, PortalFollowUp::Share(_)) {
592 outcome(follow);
593 return;
594 }
595 if delegated {
596 capturer.capture_frame();
597 }
598 outcome(follow);
599 let reason = loop {
600 if stop.load(Ordering::SeqCst) {
601 return;
602 }
603 let target_fps = fps.load(Ordering::Relaxed).max(1);
604 if target_fps != last_fps {
605 capturer.set_max_frame_rate(target_fps);
606 last_fps = target_fps;
607 }
608 capturer.capture_frame();
609 if let Some(end) = active_end.lock().ok().and_then(|mut slot| slot.take()) {
610 break match end {
611 ActiveShareStop::Quiet => None,
612 ActiveShareStop::Notice(text) => Some(text),
613 };
614 }
615 let gone = gone_since
616 .lock()
617 .is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));
618 if gone {
619 break Some("the shared source is gone");
620 }
621 std::thread::sleep(Duration::from_secs(1) / target_fps);
622 };
623 if !stop.load(Ordering::SeqCst) {
624 ended(reason.map(str::to_owned));
625 }
626 })
627 .map_err(|error| Error::Webrtc(format!("portal thread: {error}")))
628}
629
630#[cfg(test)]
631mod tests {
632 use super::*;
633
634 #[test]
635 fn a_wide_share_fits_the_send_budget_and_a_short_buffer_does_not() {
636 use libwebrtc::video_frame::VideoBuffer;
637 let (width, height) = fit_share_size(2560, 1440, SHARE_SEND_MAX_FS);
638 assert!(macroblocks(width, height) <= SHARE_SEND_MAX_FS);
639 let bytes = vec![0u8; 2560 * 1440 * 4];
640 let frame = share_frame(&bytes, 2560, 1440, 2560 * 4).expect("scaled");
641 assert!(macroblocks(frame.width(), frame.height()) <= SHARE_SEND_MAX_FS);
642 assert!(share_frame(&[0u8; 8], 4, 2, 16).is_none());
643 }
644
645 #[test]
646 fn sources_get_readable_labels() {
647 let screen = ShareSource {
648 id: 1,
649 kind: ShareKind::Screen,
650 title: String::new(),
651 };
652 assert_eq!(screen.label(), "Entire screen");
653 let window = ShareSource {
654 id: 2,
655 kind: ShareKind::Window,
656 title: " Notes ".into(),
657 };
658 assert_eq!(window.label(), "Notes");
659 }
660
661 #[test]
662 fn frames_report_the_macos_picker_outcome() {
663 assert_eq!(
664 picker_event_from_frame(&Ok(())),
665 Some(PickerOutcome::Portal(PortalPickerEvent::Selected))
666 );
667 assert_eq!(
668 picker_event_from_frame::<()>(&Err(CaptureError::Permanent)),
669 Some(PickerOutcome::Portal(PortalPickerEvent::Cancelled))
670 );
671 assert_eq!(
672 picker_event_from_frame::<()>(&Err(CaptureError::StoppedByUser)),
673 Some(PickerOutcome::Portal(PortalPickerEvent::Cancelled))
674 );
675 assert_eq!(
676 picker_event_from_frame::<()>(&Err(CaptureError::StartFailed)),
677 Some(PickerOutcome::Portal(PortalPickerEvent::Failed))
678 );
679 assert_eq!(
680 picker_event_from_frame::<()>(&Err(CaptureError::SourceGone)),
681 Some(PickerOutcome::SourceGone)
682 );
683 assert_eq!(
684 picker_follow_up(PickerOutcome::SourceGone, None),
685 PortalFollowUp::Notice(SHARE_SOURCE_GONE_NOTICE)
686 );
687 assert_eq!(
688 picker_event_from_frame::<()>(&Err(CaptureError::Interrupted)),
689 Some(PickerOutcome::Portal(PortalPickerEvent::Failed))
690 );
691 assert_eq!(
692 picker_event_from_frame::<()>(&Err(CaptureError::Temporary)),
693 None
694 );
695 }
696
697 #[test]
698 fn active_portal_errors_separate_user_stop_from_failures() {
699 assert_eq!(
700 active_portal_error(CaptureError::StoppedByUser, false, false),
701 Some(ActiveShareStop::Quiet)
702 );
703 assert_eq!(
704 active_portal_error(CaptureError::Interrupted, true, true),
705 Some(ActiveShareStop::Notice("macOS stopped the capture"))
706 );
707 assert_eq!(
708 active_portal_error(CaptureError::StartFailed, true, true),
709 Some(ActiveShareStop::Notice("macOS stopped the capture"))
710 );
711 assert_eq!(
712 active_portal_error(CaptureError::Permanent, true, true),
713 Some(ActiveShareStop::Quiet)
714 );
715 assert_eq!(
716 active_portal_error(CaptureError::Permanent, true, false),
717 Some(ActiveShareStop::Notice("the system stopped the capture"))
718 );
719 assert_eq!(
720 active_portal_error(CaptureError::Permanent, false, true),
721 Some(ActiveShareStop::Notice("the system stopped the capture"))
722 );
723 assert_eq!(
724 active_portal_error(CaptureError::SourceGone, true, true),
725 None
726 );
727 assert_eq!(
728 active_portal_error(CaptureError::Temporary, true, true),
729 None
730 );
731 }
732}
733
734#[cfg(test)]
735mod thumbnail_tests {
736 use super::scaled_bgra;
737
738 #[test]
739 fn a_thumbnail_keeps_the_aspect_and_drops_the_row_padding() {
740 let (width, height, stride) = (8u32, 4u32, 40u32);
741 let mut bytes = vec![0u8; (stride * height) as usize];
742 for row in 0..height as usize {
743 for column in 0..width as usize {
744 let offset = row * stride as usize + column * 4;
745 bytes[offset..offset + 4].copy_from_slice(&[column as u8, row as u8, 7, 0]);
746 }
747 }
748 let picture = scaled_bgra(&bytes, width, height, stride, 4, 4).unwrap();
749 assert_eq!((picture.width, picture.height), (4, 2));
750 assert_eq!(picture.bgra.len(), 4 * 2 * 4);
751 assert_eq!(&picture.bgra[4..8], &[2, 0, 7, 255]);
752 assert!(scaled_bgra(&bytes, width, height, 8, 4, 4).is_none());
753 }
754}
755
756#[cfg(test)]
757mod portal_mode_tests {
758 use super::{
759 ShareKind, SharePicker, ShareSource, share_picker_for_host, share_sources_for_menu,
760 };
761
762 #[test]
763 fn portal_mode_follows_wayland_display_and_skips_the_menu_list() {
764 assert_eq!(share_picker_for_host(false, None), SharePicker::List);
765 assert_eq!(share_picker_for_host(false, Some("")), SharePicker::List);
766 assert_eq!(
767 share_picker_for_host(false, Some("wayland-1")),
768 SharePicker::Portal
769 );
770 assert_eq!(share_picker_for_host(true, None), SharePicker::Portal);
771 assert_eq!(share_picker_for_host(true, Some("")), SharePicker::Portal);
772 let sources = vec![ShareSource {
773 id: 1,
774 kind: ShareKind::Screen,
775 title: "Desk".into(),
776 }];
777 assert!(share_sources_for_menu(SharePicker::Portal, sources.clone()).is_empty());
778 assert_eq!(
779 share_sources_for_menu(SharePicker::List, sources.clone()),
780 sources
781 );
782 }
783}
784
785#[cfg(test)]
786mod portal_share_tests {
787 use libwebrtc::desktop_capturer::PortalPickerEvent;
788
789 use super::{
790 PORTAL_UNAVAILABLE_NOTICE, PortalFollowUp, ShareKind, ShareSource, portal_follow_up,
791 };
792
793 #[test]
794 fn portal_share_cancel_is_quiet_and_failure_is_a_notice() {
795 let source = ShareSource {
796 id: 7,
797 kind: ShareKind::Screen,
798 title: "Desk".into(),
799 };
800 assert!(matches!(
801 portal_follow_up(PortalPickerEvent::Selected, Some(source.clone())),
802 PortalFollowUp::Share(chosen) if chosen == source
803 ));
804 assert!(matches!(
805 portal_follow_up(PortalPickerEvent::Selected, None),
806 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
807 ));
808 assert!(matches!(
809 portal_follow_up(PortalPickerEvent::Cancelled, Some(source.clone())),
810 PortalFollowUp::Quiet
811 ));
812 assert!(matches!(
813 portal_follow_up(PortalPickerEvent::Failed, Some(source)),
814 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
815 ));
816 }
817}
818
819#[cfg(all(test, target_os = "macos"))]
820mod macos_window_capturer_tests {
821 use super::{ShareKind, capturer};
822
823 #[test]
824 fn macos_sck_window_capturer_creates_without_opening_picker() {
825 // Creating the window capturer on macOS 14+ binds the ScreenCaptureKit
826 // single-window backend without invoking SCContentSharingPicker until start.
827 let mut window_capturer = capturer(ShareKind::Window).expect("macOS window capturer");
828 window_capturer.set_max_frame_rate(15);
829 }
830}
831
832#[cfg(all(test, target_os = "linux"))]
833mod portal_loop_tests {
834 #[test]
835 fn portal_loop_stays_up_across_ensures() {
836 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
837 let id = libwebrtc::desktop_capturer::shared_glib_loop_id();
838 assert_ne!(id, 0);
839 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
840 assert_eq!(id, libwebrtc::desktop_capturer::shared_glib_loop_id());
841 }
842}
843
844#[cfg(all(test, target_os = "linux"))]
845mod portal_smoke {
846 use std::sync::Arc;
847 use std::sync::atomic::{AtomicU32, Ordering};
848 use std::time::Duration;
849
850 use super::{PortalFollowUp, ShareKind, start_portal_capture};
851
852 #[test]
853 fn portal_smoke_captures_after_the_dialog() {
854 if std::env::var("PORTAL_SMOKE").ok().as_deref() != Some("1") {
855 return;
856 }
857 let frames = Arc::new(AtomicU32::new(0));
858 let counter = frames.clone();
859 let (sender, receiver) = std::sync::mpsc::channel();
860 let capture = start_portal_capture(
861 ShareKind::Screen,
862 Arc::new(AtomicU32::new(5)),
863 move |_| {
864 counter.fetch_add(1, Ordering::Relaxed);
865 },
866 move |follow| {
867 eprintln!("PORTAL_FOLLOW={follow:?}");
868 let _ = sender.send(follow);
869 },
870 |_| {},
871 )
872 .expect("portal thread");
873 let follow = receiver
874 .recv_timeout(Duration::from_secs(40))
875 .expect("no portal result in 40s");
876 std::thread::sleep(Duration::from_millis(700));
877 let count = frames.load(Ordering::Relaxed);
878 eprintln!("PORTAL_FRAMES={count}");
879 drop(capture);
880 match follow {
881 PortalFollowUp::Share(_) => {
882 assert!(count > 0, "the dialog confirmed, but no frame arrived")
883 }
884 PortalFollowUp::Quiet => panic!("the dialog was cancelled"),
885 PortalFollowUp::Notice(text) => panic!("portal notice: {text}"),
886 }
887 }
888}