| 1 | use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; |
| 2 | use std::sync::{Arc, Mutex}; |
| 3 | use std::time::{Duration, Instant}; |
| 4 | |
| 5 | use libwebrtc::desktop_capturer::{ |
| 6 | CaptureError, CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions, |
| 7 | PortalPickerEvent, |
| 8 | }; |
| 9 | use libwebrtc::native::yuv_helper::{argb_scale, argb_to_i420}; |
| 10 | use libwebrtc::video_frame::I420Buffer; |
| 11 | |
| 12 | use crate::capture::Capture; |
| 13 | use crate::error::{Error, Result}; |
| 14 | use crate::video_frame::VideoPicture; |
| 15 | use crate::win_timer::HighResSleep; |
| 16 | |
| 17 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 18 | pub enum ShareKind { |
| 19 | Screen, |
| 20 | Window, |
| 21 | } |
| 22 | |
| 23 | impl 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)] |
| 33 | pub struct ShareSource { |
| 34 | pub id: u64, |
| 35 | pub kind: ShareKind, |
| 36 | pub title: String, |
| 37 | } |
| 38 | |
| 39 | impl 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 | |
| 49 | fn 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 | |
| 55 | fn 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 | |
| 75 | pub 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 | |
| 82 | const THUMBNAIL_ATTEMPTS: u32 = 5; |
| 83 | const SOURCE_GONE_AFTER: Duration = Duration::from_secs(3); |
| 84 | const THUMBNAIL_RETRY: Duration = Duration::from_millis(40); |
| 85 | |
| 86 | pub 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)] |
| 126 | fn 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))] |
| 140 | fn pump_messages() {} |
| 141 | |
| 142 | fn 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 | |
| 180 | const SHARE_SEND_MAX_FS: u32 = 8160; |
| 181 | const MACROBLOCK: u32 = 16; |
| 182 | |
| 183 | fn macroblocks(width: u32, height: u32) -> u32 { |
| 184 | width.div_ceil(MACROBLOCK) * height.div_ceil(MACROBLOCK) |
| 185 | } |
| 186 | |
| 187 | fn even(value: u32) -> u32 { |
| 188 | value & !1 |
| 189 | } |
| 190 | |
| 191 | fn 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 | |
| 198 | pub(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 | |
| 215 | fn 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 | |
| 237 | fn 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 | |
| 255 | fn 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. |
| 276 | pub 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 | |
| 354 | fn 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)] |
| 360 | pub enum SharePicker { |
| 361 | List, |
| 362 | Portal, |
| 363 | } |
| 364 | |
| 365 | pub fn share_picker_for(wayland_display: Option<&str>) -> SharePicker { |
| 366 | share_picker_for_host(cfg!(target_os = "macos"), wayland_display) |
| 367 | } |
| 368 | |
| 369 | pub 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 | |
| 379 | pub 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. |
| 384 | pub 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 | |
| 391 | pub use crate::notices::{PORTAL_UNAVAILABLE_NOTICE, SHARE_SOURCE_GONE_NOTICE}; |
| 392 | |
| 393 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 394 | pub enum PortalFollowUp { |
| 395 | Share(ShareSource), |
| 396 | Quiet, |
| 397 | Notice(&'static str), |
| 398 | } |
| 399 | |
| 400 | pub 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)] |
| 412 | enum PickerOutcome { |
| 413 | Portal(PortalPickerEvent), |
| 414 | SourceGone, |
| 415 | } |
| 416 | |
| 417 | fn 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`. |
| 428 | fn 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)] |
| 445 | enum ActiveShareStop { |
| 446 | Quiet, |
| 447 | Notice(&'static str), |
| 448 | } |
| 449 | |
| 450 | /// Classifies an error received while a portal share is active. |
| 451 | fn active_portal_error(error: CaptureError) -> Option<ActiveShareStop> { |
| 452 | match error { |
| 453 | CaptureError::StoppedByUser => Some(ActiveShareStop::Quiet), |
| 454 | CaptureError::StartFailed | CaptureError::Interrupted => { |
| 455 | Some(ActiveShareStop::Notice("macOS stopped the capture")) |
| 456 | } |
| 457 | CaptureError::Permanent => Some(ActiveShareStop::Notice("the system stopped the capture")), |
| 458 | CaptureError::Temporary | CaptureError::SourceGone => None, |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | pub(crate) fn start_portal_capture( |
| 463 | kind: ShareKind, |
| 464 | fps: Arc<AtomicU32>, |
| 465 | mut deliver: impl FnMut(I420Buffer) + Send + 'static, |
| 466 | outcome: impl FnOnce(PortalFollowUp) + Send + 'static, |
| 467 | ended: impl FnOnce(Option<String>) + Send + 'static, |
| 468 | ) -> Result<Capture> { |
| 469 | Capture::spawn_thread("portal-share", move |stop| { |
| 470 | libwebrtc::desktop_capturer::ensure_shared_glib_loop(); |
| 471 | let Some(mut capturer) = capturer(kind) else { |
| 472 | outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)); |
| 473 | return; |
| 474 | }; |
| 475 | let mut last_fps = fps.load(Ordering::Relaxed).max(1); |
| 476 | capturer.set_max_frame_rate(last_fps); |
| 477 | // The Wayland portal reports the pick through a delegated picker. The |
| 478 | // macOS system picker has none: it opens in `start_capture` and the |
| 479 | // outcome shows in the frame results. |
| 480 | let delegated = capturer.has_delegated_picker(); |
| 481 | if !delegated && !cfg!(target_os = "macos") { |
| 482 | outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)); |
| 483 | return; |
| 484 | } |
| 485 | let (sender, receiver) = std::sync::mpsc::channel(); |
| 486 | let frame_events = (!delegated).then(|| sender.clone()); |
| 487 | let selected = Arc::new(AtomicBool::new(false)); |
| 488 | let gate = selected.clone(); |
| 489 | // A closed window gets the same grace as in the source list: it may |
| 490 | // reopen, and the remote side keeps the last frame meanwhile. |
| 491 | let gone_since: Arc<Mutex<Option<Instant>>> = Arc::default(); |
| 492 | let gone_mark = gone_since.clone(); |
| 493 | let active_end: Arc<Mutex<Option<ActiveShareStop>>> = Arc::default(); |
| 494 | let end_mark = active_end.clone(); |
| 495 | capturer.start_capture(None, move |result| { |
| 496 | if !gate.load(Ordering::SeqCst) { |
| 497 | let Some(events) = &frame_events else { return }; |
| 498 | let Some(event) = picker_event_from_frame(&result) else { |
| 499 | return; |
| 500 | }; |
| 501 | let _ = events.send(event); |
| 502 | if event != PickerOutcome::Portal(PortalPickerEvent::Selected) { |
| 503 | return; |
| 504 | } |
| 505 | gate.store(true, Ordering::SeqCst); |
| 506 | } |
| 507 | match result { |
| 508 | Ok(frame) => { |
| 509 | if let Ok(mut since) = gone_mark.lock() { |
| 510 | *since = None; |
| 511 | } |
| 512 | let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1); |
| 513 | if let Some(picture) = share_frame(frame.data(), width, height, frame.stride()) |
| 514 | { |
| 515 | deliver(picture); |
| 516 | } |
| 517 | } |
| 518 | Err(CaptureError::Temporary) => { |
| 519 | if let Ok(mut since) = gone_mark.lock() { |
| 520 | *since = None; |
| 521 | } |
| 522 | } |
| 523 | Err(CaptureError::SourceGone) => { |
| 524 | if let Ok(mut since) = gone_mark.lock() { |
| 525 | since.get_or_insert_with(Instant::now); |
| 526 | } |
| 527 | } |
| 528 | Err(error) => { |
| 529 | if let Some(stop_reason) = active_portal_error(error) |
| 530 | && let Ok(mut slot) = end_mark.lock() |
| 531 | { |
| 532 | slot.get_or_insert(stop_reason); |
| 533 | } |
| 534 | } |
| 535 | } |
| 536 | }); |
| 537 | if delegated { |
| 538 | capturer.watch_picker(move |event| { |
| 539 | let _ = sender.send(PickerOutcome::Portal(event)); |
| 540 | }); |
| 541 | capturer.ensure_picker_visible(); |
| 542 | } |
| 543 | let event = loop { |
| 544 | if stop.load(Ordering::SeqCst) { |
| 545 | return; |
| 546 | } |
| 547 | if !delegated { |
| 548 | capturer.capture_frame(); |
| 549 | } |
| 550 | match receiver.recv_timeout(Duration::from_millis(40)) { |
| 551 | Ok(event) => break event, |
| 552 | Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue, |
| 553 | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => { |
| 554 | outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)); |
| 555 | return; |
| 556 | } |
| 557 | } |
| 558 | }; |
| 559 | if stop.load(Ordering::SeqCst) { |
| 560 | return; |
| 561 | } |
| 562 | // The portal already bound this stream. Looking the source up again, or |
| 563 | // selecting that id, is what used to tear the stream down and report |
| 564 | // "the shared source is gone". |
| 565 | let source = if event == PickerOutcome::Portal(PortalPickerEvent::Selected) { |
| 566 | selected.store(true, Ordering::SeqCst); |
| 567 | Some(ShareSource { |
| 568 | id: 0, |
| 569 | kind, |
| 570 | title: String::new(), |
| 571 | }) |
| 572 | } else { |
| 573 | None |
| 574 | }; |
| 575 | let follow = picker_follow_up(event, source); |
| 576 | if !matches!(follow, PortalFollowUp::Share(_)) { |
| 577 | outcome(follow); |
| 578 | return; |
| 579 | } |
| 580 | if delegated { |
| 581 | capturer.capture_frame(); |
| 582 | } |
| 583 | outcome(follow); |
| 584 | let reason = loop { |
| 585 | if stop.load(Ordering::SeqCst) { |
| 586 | return; |
| 587 | } |
| 588 | let target_fps = fps.load(Ordering::Relaxed).max(1); |
| 589 | if target_fps != last_fps { |
| 590 | capturer.set_max_frame_rate(target_fps); |
| 591 | last_fps = target_fps; |
| 592 | } |
| 593 | capturer.capture_frame(); |
| 594 | if let Some(end) = active_end.lock().ok().and_then(|mut slot| slot.take()) { |
| 595 | break match end { |
| 596 | ActiveShareStop::Quiet => None, |
| 597 | ActiveShareStop::Notice(text) => Some(text), |
| 598 | }; |
| 599 | } |
| 600 | let gone = gone_since |
| 601 | .lock() |
| 602 | .is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER)); |
| 603 | if gone { |
| 604 | break Some("the shared source is gone"); |
| 605 | } |
| 606 | std::thread::sleep(Duration::from_secs(1) / target_fps); |
| 607 | }; |
| 608 | if !stop.load(Ordering::SeqCst) { |
| 609 | ended(reason.map(str::to_owned)); |
| 610 | } |
| 611 | }) |
| 612 | .map_err(|error| Error::Webrtc(format!("portal thread: {error}"))) |
| 613 | } |
| 614 | |
| 615 | #[cfg(test)] |
| 616 | mod tests { |
| 617 | use super::*; |
| 618 | |
| 619 | #[test] |
| 620 | fn a_wide_share_fits_the_send_budget_and_a_short_buffer_does_not() { |
| 621 | use libwebrtc::video_frame::VideoBuffer; |
| 622 | let (width, height) = fit_share_size(2560, 1440, SHARE_SEND_MAX_FS); |
| 623 | assert!(macroblocks(width, height) <= SHARE_SEND_MAX_FS); |
| 624 | let bytes = vec![0u8; 2560 * 1440 * 4]; |
| 625 | let frame = share_frame(&bytes, 2560, 1440, 2560 * 4).expect("scaled"); |
| 626 | assert!(macroblocks(frame.width(), frame.height()) <= SHARE_SEND_MAX_FS); |
| 627 | assert!(share_frame(&[0u8; 8], 4, 2, 16).is_none()); |
| 628 | } |
| 629 | |
| 630 | #[test] |
| 631 | fn sources_get_readable_labels() { |
| 632 | let screen = ShareSource { |
| 633 | id: 1, |
| 634 | kind: ShareKind::Screen, |
| 635 | title: String::new(), |
| 636 | }; |
| 637 | assert_eq!(screen.label(), "Entire screen"); |
| 638 | let window = ShareSource { |
| 639 | id: 2, |
| 640 | kind: ShareKind::Window, |
| 641 | title: " Notes ".into(), |
| 642 | }; |
| 643 | assert_eq!(window.label(), "Notes"); |
| 644 | } |
| 645 | |
| 646 | #[test] |
| 647 | fn frames_report_the_macos_picker_outcome() { |
| 648 | assert_eq!( |
| 649 | picker_event_from_frame(&Ok(())), |
| 650 | Some(PickerOutcome::Portal(PortalPickerEvent::Selected)) |
| 651 | ); |
| 652 | assert_eq!( |
| 653 | picker_event_from_frame::<()>(&Err(CaptureError::Permanent)), |
| 654 | Some(PickerOutcome::Portal(PortalPickerEvent::Cancelled)) |
| 655 | ); |
| 656 | assert_eq!( |
| 657 | picker_event_from_frame::<()>(&Err(CaptureError::StoppedByUser)), |
| 658 | Some(PickerOutcome::Portal(PortalPickerEvent::Cancelled)) |
| 659 | ); |
| 660 | assert_eq!( |
| 661 | picker_event_from_frame::<()>(&Err(CaptureError::StartFailed)), |
| 662 | Some(PickerOutcome::Portal(PortalPickerEvent::Failed)) |
| 663 | ); |
| 664 | assert_eq!( |
| 665 | picker_event_from_frame::<()>(&Err(CaptureError::SourceGone)), |
| 666 | Some(PickerOutcome::SourceGone) |
| 667 | ); |
| 668 | assert_eq!( |
| 669 | picker_follow_up(PickerOutcome::SourceGone, None), |
| 670 | PortalFollowUp::Notice(SHARE_SOURCE_GONE_NOTICE) |
| 671 | ); |
| 672 | assert_eq!( |
| 673 | picker_event_from_frame::<()>(&Err(CaptureError::Interrupted)), |
| 674 | Some(PickerOutcome::Portal(PortalPickerEvent::Failed)) |
| 675 | ); |
| 676 | assert_eq!( |
| 677 | picker_event_from_frame::<()>(&Err(CaptureError::Temporary)), |
| 678 | None |
| 679 | ); |
| 680 | } |
| 681 | |
| 682 | #[test] |
| 683 | fn active_portal_errors_separate_user_stop_from_failures() { |
| 684 | assert_eq!( |
| 685 | active_portal_error(CaptureError::StoppedByUser), |
| 686 | Some(ActiveShareStop::Quiet) |
| 687 | ); |
| 688 | assert_eq!( |
| 689 | active_portal_error(CaptureError::Interrupted), |
| 690 | Some(ActiveShareStop::Notice("macOS stopped the capture")) |
| 691 | ); |
| 692 | assert_eq!( |
| 693 | active_portal_error(CaptureError::StartFailed), |
| 694 | Some(ActiveShareStop::Notice("macOS stopped the capture")) |
| 695 | ); |
| 696 | assert_eq!( |
| 697 | active_portal_error(CaptureError::Permanent), |
| 698 | Some(ActiveShareStop::Notice("the system stopped the capture")) |
| 699 | ); |
| 700 | assert_eq!(active_portal_error(CaptureError::SourceGone), None); |
| 701 | assert_eq!(active_portal_error(CaptureError::Temporary), None); |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | #[cfg(test)] |
| 706 | mod thumbnail_tests { |
| 707 | use super::scaled_bgra; |
| 708 | |
| 709 | #[test] |
| 710 | fn a_thumbnail_keeps_the_aspect_and_drops_the_row_padding() { |
| 711 | let (width, height, stride) = (8u32, 4u32, 40u32); |
| 712 | let mut bytes = vec![0u8; (stride * height) as usize]; |
| 713 | for row in 0..height as usize { |
| 714 | for column in 0..width as usize { |
| 715 | let offset = row * stride as usize + column * 4; |
| 716 | bytes[offset..offset + 4].copy_from_slice(&[column as u8, row as u8, 7, 0]); |
| 717 | } |
| 718 | } |
| 719 | let picture = scaled_bgra(&bytes, width, height, stride, 4, 4).unwrap(); |
| 720 | assert_eq!((picture.width, picture.height), (4, 2)); |
| 721 | assert_eq!(picture.bgra.len(), 4 * 2 * 4); |
| 722 | assert_eq!(&picture.bgra[4..8], &[2, 0, 7, 255]); |
| 723 | assert!(scaled_bgra(&bytes, width, height, 8, 4, 4).is_none()); |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | #[cfg(test)] |
| 728 | mod portal_mode_tests { |
| 729 | use super::{ |
| 730 | ShareKind, SharePicker, ShareSource, share_picker_for_host, share_sources_for_menu, |
| 731 | }; |
| 732 | |
| 733 | #[test] |
| 734 | fn portal_mode_follows_wayland_display_and_skips_the_menu_list() { |
| 735 | assert_eq!(share_picker_for_host(false, None), SharePicker::List); |
| 736 | assert_eq!(share_picker_for_host(false, Some("")), SharePicker::List); |
| 737 | assert_eq!( |
| 738 | share_picker_for_host(false, Some("wayland-1")), |
| 739 | SharePicker::Portal |
| 740 | ); |
| 741 | assert_eq!(share_picker_for_host(true, None), SharePicker::Portal); |
| 742 | assert_eq!(share_picker_for_host(true, Some("")), SharePicker::Portal); |
| 743 | let sources = vec![ShareSource { |
| 744 | id: 1, |
| 745 | kind: ShareKind::Screen, |
| 746 | title: "Desk".into(), |
| 747 | }]; |
| 748 | assert!(share_sources_for_menu(SharePicker::Portal, sources.clone()).is_empty()); |
| 749 | assert_eq!( |
| 750 | share_sources_for_menu(SharePicker::List, sources.clone()), |
| 751 | sources |
| 752 | ); |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | #[cfg(test)] |
| 757 | mod portal_share_tests { |
| 758 | use libwebrtc::desktop_capturer::PortalPickerEvent; |
| 759 | |
| 760 | use super::{ |
| 761 | PORTAL_UNAVAILABLE_NOTICE, PortalFollowUp, ShareKind, ShareSource, portal_follow_up, |
| 762 | }; |
| 763 | |
| 764 | #[test] |
| 765 | fn portal_share_cancel_is_quiet_and_failure_is_a_notice() { |
| 766 | let source = ShareSource { |
| 767 | id: 7, |
| 768 | kind: ShareKind::Screen, |
| 769 | title: "Desk".into(), |
| 770 | }; |
| 771 | assert!(matches!( |
| 772 | portal_follow_up(PortalPickerEvent::Selected, Some(source.clone())), |
| 773 | PortalFollowUp::Share(chosen) if chosen == source |
| 774 | )); |
| 775 | assert!(matches!( |
| 776 | portal_follow_up(PortalPickerEvent::Selected, None), |
| 777 | PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE) |
| 778 | )); |
| 779 | assert!(matches!( |
| 780 | portal_follow_up(PortalPickerEvent::Cancelled, Some(source.clone())), |
| 781 | PortalFollowUp::Quiet |
| 782 | )); |
| 783 | assert!(matches!( |
| 784 | portal_follow_up(PortalPickerEvent::Failed, Some(source)), |
| 785 | PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE) |
| 786 | )); |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | #[cfg(all(test, target_os = "macos"))] |
| 791 | mod macos_window_capturer_tests { |
| 792 | use super::{ShareKind, capturer}; |
| 793 | |
| 794 | #[test] |
| 795 | fn macos_sck_window_capturer_creates_without_opening_picker() { |
| 796 | // Creating the window capturer on macOS 14+ binds the ScreenCaptureKit |
| 797 | // single-window backend without invoking SCContentSharingPicker until start. |
| 798 | let mut window_capturer = capturer(ShareKind::Window).expect("macOS window capturer"); |
| 799 | window_capturer.set_max_frame_rate(15); |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | #[cfg(all(test, target_os = "linux"))] |
| 804 | mod portal_loop_tests { |
| 805 | #[test] |
| 806 | fn portal_loop_stays_up_across_ensures() { |
| 807 | libwebrtc::desktop_capturer::ensure_shared_glib_loop(); |
| 808 | let id = libwebrtc::desktop_capturer::shared_glib_loop_id(); |
| 809 | assert_ne!(id, 0); |
| 810 | libwebrtc::desktop_capturer::ensure_shared_glib_loop(); |
| 811 | assert_eq!(id, libwebrtc::desktop_capturer::shared_glib_loop_id()); |
| 812 | } |
| 813 | } |
| 814 | |
| 815 | #[cfg(all(test, target_os = "linux"))] |
| 816 | mod portal_smoke { |
| 817 | use std::sync::Arc; |
| 818 | use std::sync::atomic::{AtomicU32, Ordering}; |
| 819 | use std::time::Duration; |
| 820 | |
| 821 | use super::{PortalFollowUp, ShareKind, start_portal_capture}; |
| 822 | |
| 823 | #[test] |
| 824 | fn portal_smoke_captures_after_the_dialog() { |
| 825 | if std::env::var("PORTAL_SMOKE").ok().as_deref() != Some("1") { |
| 826 | return; |
| 827 | } |
| 828 | let frames = Arc::new(AtomicU32::new(0)); |
| 829 | let counter = frames.clone(); |
| 830 | let (sender, receiver) = std::sync::mpsc::channel(); |
| 831 | let capture = start_portal_capture( |
| 832 | ShareKind::Screen, |
| 833 | Arc::new(AtomicU32::new(5)), |
| 834 | move |_| { |
| 835 | counter.fetch_add(1, Ordering::Relaxed); |
| 836 | }, |
| 837 | move |follow| { |
| 838 | eprintln!("PORTAL_FOLLOW={follow:?}"); |
| 839 | let _ = sender.send(follow); |
| 840 | }, |
| 841 | |_| {}, |
| 842 | ) |
| 843 | .expect("portal thread"); |
| 844 | let follow = receiver |
| 845 | .recv_timeout(Duration::from_secs(40)) |
| 846 | .expect("no portal result in 40s"); |
| 847 | std::thread::sleep(Duration::from_millis(700)); |
| 848 | let count = frames.load(Ordering::Relaxed); |
| 849 | eprintln!("PORTAL_FRAMES={count}"); |
| 850 | drop(capture); |
| 851 | match follow { |
| 852 | PortalFollowUp::Share(_) => { |
| 853 | assert!(count > 0, "the dialog confirmed, but no frame arrived") |
| 854 | } |
| 855 | PortalFollowUp::Quiet => panic!("the dialog was cancelled"), |
| 856 | PortalFollowUp::Notice(text) => panic!("portal notice: {text}"), |
| 857 | } |
| 858 | } |
| 859 | } |