Skip to main content

sew_call_client/video/
capture.rs

1//! The capture side of video (feature `video-core`): cameras and screens through a kessel-video
2//! backend, as handles the publish side and the pre-join preview take.
3//!
4//! - **[`VideoCapture`]** wraps the app's one `VideoBackend`: capabilities, cameras, the OS
5//!   permissions (asked only when not yet determined), the screen list with PNG thumbnails, the
6//!   OS screen picker, and opening a camera or a screen.
7//! - **[`CameraSource`] and [`ScreenSource`]** are running sources: frames ([`Capture::try_frame`]),
8//!   events in Sew's vocabulary ([`CaptureEvent`]), the constraints they run at, the content hint
9//!   for their encoders ([`ContentHint::Camera`] / [`ContentHint::Screen`]) and one wake-up
10//!   ([`Capture::ready`], [`Capture::wake`] for the encoders fed from them). Dropping one stops
11//!   the device (the camera light goes off).
12//! - Every refusal is a [`CaptureError`] whose [`CaptureError::code`] is the plugin's reject code
13//!   (`camera_denied`, `picker_cancelled`, `screen_unsupported`, ...).
14
15use std::sync::{Arc, Mutex, Weak};
16
17use kessel_video::{
18    CameraInfo, Capabilities, CaptureConstraints, ContentHint, EndReason, EventRx, FrameSource,
19    Interruption, Permission, PickOptions, PixelFormat, ScreenKind, ScreenSelection,
20    ScreenSourceInfo, SourceEvent, SourceStats, VideoBackend, VideoError, Wake,
21};
22use tokio::sync::{Notify, oneshot};
23
24/// The widest screen-source thumbnail (`screen_sources`), in pixels.
25pub const THUMBNAIL_MAX_WIDTH: u32 = 320;
26
27/// Why a camera or screen could not be opened. [`CaptureError::code`] is the plugin's code.
28#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
29#[non_exhaustive]
30pub enum CaptureError {
31    /// No video here (the null backend, a backend shut down, no camera API).
32    #[error("video_unsupported")]
33    VideoUnsupported,
34    /// The OS camera permission is denied or restricted.
35    #[error("camera_denied")]
36    CameraDenied,
37    /// Another app holds the camera.
38    #[error("camera_busy")]
39    CameraBusy,
40    /// No such camera (or none at all).
41    #[error("camera_not_found")]
42    CameraNotFound,
43    /// The camera went away while opening.
44    #[error("camera_lost")]
45    CameraLost,
46    /// No encoder for the codecs wanted.
47    #[error("codec_unavailable")]
48    CodecUnavailable,
49    /// No screen capture here (Linux without the portal or libpipewire, phones), or no OS
50    /// picker where one was asked for.
51    #[error("screen_unsupported")]
52    ScreenUnsupported,
53    /// The OS screen-recording permission is denied.
54    #[error("screen_denied")]
55    ScreenDenied,
56    /// The person cancelled the OS picker.
57    #[error("picker_cancelled")]
58    PickerCancelled,
59    /// The listed display or window is gone (or was never listed).
60    #[error("screen_not_found")]
61    ScreenNotFound,
62    /// An encoder failed and could not be reopened (the preview).
63    #[error("encoder_lost")]
64    EncoderLost,
65    /// Any other backend failure (`VideoError::code` says which).
66    #[error("capture_failed: {0}")]
67    Failed(VideoError),
68}
69
70impl CaptureError {
71    /// The plugin's reject code.
72    pub fn code(&self) -> &'static str {
73        match self {
74            CaptureError::VideoUnsupported => "video_unsupported",
75            CaptureError::CameraDenied => "camera_denied",
76            CaptureError::CameraBusy => "camera_busy",
77            CaptureError::CameraNotFound => "camera_not_found",
78            CaptureError::CameraLost => "camera_lost",
79            CaptureError::CodecUnavailable => "codec_unavailable",
80            CaptureError::ScreenUnsupported => "screen_unsupported",
81            CaptureError::ScreenDenied => "screen_denied",
82            CaptureError::PickerCancelled => "picker_cancelled",
83            CaptureError::ScreenNotFound => "screen_not_found",
84            CaptureError::EncoderLost => "encoder_lost",
85            CaptureError::Failed(_) => "capture_failed",
86        }
87    }
88}
89
90fn camera_error(e: VideoError) -> CaptureError {
91    match e {
92        VideoError::NoPermission => CaptureError::CameraDenied,
93        VideoError::DeviceBusy => CaptureError::CameraBusy,
94        VideoError::NotFound => CaptureError::CameraNotFound,
95        VideoError::DeviceLost => CaptureError::CameraLost,
96        VideoError::Unsupported(_) | VideoError::ShutDown => CaptureError::VideoUnsupported,
97        other => CaptureError::Failed(other),
98    }
99}
100
101fn screen_error(e: VideoError) -> CaptureError {
102    match e {
103        VideoError::NoPermission => CaptureError::ScreenDenied,
104        VideoError::NotFound | VideoError::DeviceLost => CaptureError::ScreenNotFound,
105        VideoError::Unsupported(_) | VideoError::ShutDown => CaptureError::ScreenUnsupported,
106        other => CaptureError::Failed(other),
107    }
108}
109
110fn pick_error(e: VideoError) -> CaptureError {
111    match e {
112        // kessel-video's answer to a cancelled picker.
113        VideoError::NotFound => CaptureError::PickerCancelled,
114        other => screen_error(other),
115    }
116}
117
118// ───────────────────────────── events ─────────────────────────────
119
120/// A camera or a screen.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
122#[non_exhaustive]
123pub enum CaptureKind {
124    /// A camera.
125    Camera,
126    /// A display or window.
127    Screen,
128}
129
130/// Why a source paused without ending (frames stop; the publication stays).
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
132#[non_exhaustive]
133pub enum CapturePause {
134    /// A shared window is minimised or occluded.
135    Hidden,
136    /// Phones: the app went to the background.
137    Background,
138    /// Another app took the camera.
139    InUseByAnother,
140    /// Thermal pressure: the OS stopped the camera.
141    Thermal,
142    /// A reason kessel-video added later.
143    Other,
144    /// The camera says it is suspended (macOS and iOS): a MacBook's built-in camera with its
145    /// lid closed, a shut lens cover. Frames come back when it does. (Last, so the other
146    /// variants keep their discriminants.)
147    Suspended,
148}
149
150/// Why a source ended (terminal: drop it, unpublish, release the lease).
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152#[non_exhaustive]
153pub enum CaptureEnd {
154    /// It was closed (the backend shut down).
155    Closed,
156    /// The device went away (unplugged, display disconnected).
157    DeviceLost,
158    /// The person stopped it from the OS's UI (the share bar, the portal).
159    UserStopped,
160    /// The shared window closed.
161    SourceClosed,
162    /// The OS permission was revoked while running.
163    Revoked,
164}
165
166/// A source's events, in order, in Sew's vocabulary.
167#[derive(Debug, Clone, PartialEq, Eq)]
168#[non_exhaustive]
169pub enum CaptureEvent {
170    /// The first frame, and after any change of the delivered size or rate.
171    Started {
172        /// Delivered width.
173        width: u32,
174        /// Delivered height.
175        height: u32,
176        /// Delivered rate.
177        fps: u32,
178    },
179    /// Paused by the OS: no frames until [`CaptureEvent::Resumed`].
180    Paused(CapturePause),
181    /// Back after a pause (the encoders' next frame should be a keyframe).
182    Resumed,
183    /// Terminal: no more frames.
184    Ended(CaptureEnd),
185    /// A non-terminal problem.
186    Error(VideoError),
187}
188
189impl CaptureEnd {
190    /// The `local_video.reason` for a `kind` source that ended this way: `user_stopped`,
191    /// `source_closed` (a screen's display or window gone), `camera_lost`, `camera_denied` /
192    /// `screen_denied` (the permission revoked while sending), `unpublished` (closed).
193    pub fn reason(self, kind: CaptureKind) -> &'static str {
194        let screen = kind == CaptureKind::Screen;
195        match self {
196            CaptureEnd::UserStopped => "user_stopped",
197            CaptureEnd::SourceClosed => "source_closed",
198            CaptureEnd::Revoked if screen => "screen_denied",
199            CaptureEnd::Revoked => "camera_denied",
200            CaptureEnd::DeviceLost if screen => "source_closed",
201            CaptureEnd::DeviceLost => "camera_lost",
202            CaptureEnd::Closed => "unpublished",
203        }
204    }
205}
206
207pub(crate) fn map_event(e: SourceEvent) -> Option<CaptureEvent> {
208    Some(match e {
209        SourceEvent::Started { width, height, fps } => CaptureEvent::Started { width, height, fps },
210        SourceEvent::Interrupted(i) => CaptureEvent::Paused(match i {
211            Interruption::Hidden => CapturePause::Hidden,
212            Interruption::Background => CapturePause::Background,
213            Interruption::InUseByAnother => CapturePause::InUseByAnother,
214            Interruption::Thermal => CapturePause::Thermal,
215            Interruption::Suspended => CapturePause::Suspended,
216            _ => CapturePause::Other,
217        }),
218        SourceEvent::Resumed => CaptureEvent::Resumed,
219        SourceEvent::Ended(r) => CaptureEvent::Ended(match r {
220            EndReason::Closed => CaptureEnd::Closed,
221            EndReason::DeviceLost => CaptureEnd::DeviceLost,
222            EndReason::UserStopped => CaptureEnd::UserStopped,
223            EndReason::SourceClosed => CaptureEnd::SourceClosed,
224            EndReason::Revoked => CaptureEnd::Revoked,
225            _ => CaptureEnd::DeviceLost,
226        }),
227        SourceEvent::Error(e) => CaptureEvent::Error(e),
228        _ => return None,
229    })
230}
231
232/// A [`Wake`] that wakes `n` (from any thread; cheap, never blocks).
233fn notify_wake(n: &Arc<Notify>) -> Wake {
234    let n = Arc::clone(n);
235    Arc::new(move || n.notify_one())
236}
237
238/// A source's wake: its [`Notify`] and, once the publish side takes the source, the bridge's
239/// pipeline wake as well ([`Capture::chain_wake`]).
240#[derive(Default)]
241struct WakeHub {
242    ready: Arc<Notify>,
243    chained: Mutex<Option<Wake>>,
244}
245
246impl WakeHub {
247    fn wake(self: &Arc<WakeHub>) -> Wake {
248        let hub = Arc::clone(self);
249        Arc::new(move || {
250            hub.ready.notify_one();
251            let chained = hub
252                .chained
253                .lock()
254                .unwrap_or_else(std::sync::PoisonError::into_inner)
255                .clone();
256            if let Some(w) = chained {
257                w();
258            }
259        })
260    }
261}
262
263// ───────────────────────────── sources ─────────────────────────────
264
265/// A running camera or screen source. Dropping it stops the device.
266pub struct Capture {
267    kind: CaptureKind,
268    source: Box<dyn FrameSource>,
269    hub: Arc<WakeHub>,
270    constraints: CaptureConstraints,
271    device: Option<String>,
272    ended: Option<CaptureEnd>,
273    paused: Option<CapturePause>,
274}
275
276impl std::fmt::Debug for Capture {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        f.debug_struct("Capture")
279            .field("kind", &self.kind)
280            .field("device", &self.device)
281            .field("ended", &self.ended)
282            .field("paused", &self.paused)
283            .finish_non_exhaustive()
284    }
285}
286
287impl Capture {
288    fn new(
289        kind: CaptureKind,
290        source: Box<dyn FrameSource>,
291        hub: Arc<WakeHub>,
292        constraints: CaptureConstraints,
293        device: Option<String>,
294    ) -> Capture {
295        Capture {
296            kind,
297            source,
298            hub,
299            constraints,
300            device,
301            ended: None,
302            paused: None,
303        }
304    }
305
306    /// Camera or screen.
307    pub fn kind(&self) -> CaptureKind {
308        self.kind
309    }
310
311    /// The content hint for the encoders this source feeds: [`ContentHint::Camera`] (keep the
312    /// frame rate) or [`ContentHint::Screen`] (keep the detail).
313    pub fn content_hint(&self) -> ContentHint {
314        match self.kind {
315            CaptureKind::Screen => ContentHint::Screen,
316            _ => ContentHint::Camera,
317        }
318    }
319
320    /// The camera's id as asked (`None`: the default camera), or the listed screen's id
321    /// (`None`: the OS picker's choice).
322    pub fn device(&self) -> Option<&str> {
323        self.device.as_deref()
324    }
325
326    /// What the source was last asked for.
327    pub fn constraints(&self) -> CaptureConstraints {
328        self.constraints
329    }
330
331    /// New size and rate without reopening (from the next frame; a
332    /// [`CaptureEvent::Started`] follows with the delivered values).
333    pub fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), CaptureError> {
334        let r = self.source.set_constraints(c);
335        r.map_err(|e| match self.kind {
336            CaptureKind::Camera => camera_error(e),
337            _ => screen_error(e),
338        })?;
339        self.constraints = c;
340        Ok(())
341    }
342
343    /// Stop delivering frames but keep the device open (nothing wants a layer and no
344    /// self-view is open).
345    pub fn set_paused(&mut self, paused: bool) {
346        self.source.set_paused(paused);
347    }
348
349    /// The next frame (CPU planes, or a native buffer when asked with `prefer_native`), if one
350    /// is queued. The queue is 2 deep, oldest dropped; `None` once ended.
351    pub fn try_frame(&mut self) -> Option<kessel_video::VideoFrame> {
352        if self.ended.is_some() {
353            return None;
354        }
355        self.source.try_recv()
356    }
357
358    /// The next event, if one is queued.
359    pub fn try_event(&mut self) -> Option<CaptureEvent> {
360        loop {
361            let e = map_event(self.source.try_event()?);
362            match &e {
363                Some(CaptureEvent::Ended(end)) => self.ended = Some(*end),
364                Some(CaptureEvent::Paused(p)) => self.paused = Some(*p),
365                Some(CaptureEvent::Resumed) => self.paused = None,
366                _ => {}
367            }
368            if e.is_some() {
369                return e;
370            }
371        }
372    }
373
374    /// Waits until the source (or an encoder given [`Capture::wake`]) queued something. Drain
375    /// [`Capture::try_event`] and [`Capture::try_frame`] after each wake; one wake-up is kept
376    /// when nobody waits, so none is lost between a drain and the next wait.
377    pub async fn ready(&self) {
378        self.hub.ready.notified().await;
379    }
380
381    /// The source's wake-up as a kessel-video [`Wake`], for the encoders this source feeds, so
382    /// one task waits on frames and encoded outputs alike.
383    pub fn wake(&self) -> Wake {
384        notify_wake(&self.hub.ready)
385    }
386
387    /// The source's wake-up itself.
388    pub fn notifier(&self) -> Arc<Notify> {
389        Arc::clone(&self.hub.ready)
390    }
391
392    /// From now on the source's frames and events also call `wake` (the bridge's pipeline
393    /// thread, which waits on its own wake-up rather than on [`Capture::ready`]).
394    pub(crate) fn chain_wake(&self, wake: Wake) {
395        *self
396            .hub
397            .chained
398            .lock()
399            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(wake);
400        // Anything already queued is seen at once.
401        self.hub.wake()();
402    }
403
404    /// Why it ended, once it has ([`CaptureEvent::Ended`] was read).
405    pub fn ended(&self) -> Option<CaptureEnd> {
406        self.ended
407    }
408
409    /// Why it is paused, while it is.
410    pub fn paused(&self) -> Option<CapturePause> {
411        self.paused
412    }
413
414    /// The source's counters since open.
415    pub fn stats(&self) -> SourceStats {
416        self.source.stats()
417    }
418}
419
420/// The raw source, for the publish side ([`crate::VideoBridge::publish_capture`] and
421/// [`crate::SourceFeed`]): frames and kessel-video's own events, without [`Capture`]'s
422/// bookkeeping.
423impl FrameSource for Capture {
424    fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
425        self.source.try_recv()
426    }
427
428    fn try_event(&mut self) -> Option<SourceEvent> {
429        self.source.try_event()
430    }
431
432    fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), VideoError> {
433        self.source.set_constraints(c)?;
434        self.constraints = c;
435        Ok(())
436    }
437
438    fn set_paused(&mut self, paused: bool) {
439        self.source.set_paused(paused);
440    }
441
442    fn stats(&self) -> SourceStats {
443        self.source.stats()
444    }
445}
446
447/// A running camera ([`VideoCapture::open_camera`]). Everything of [`Capture`] through `Deref`.
448#[derive(Debug)]
449pub struct CameraSource(Capture);
450
451/// A running screen or window capture ([`VideoCapture::open_screen`]), with
452/// [`ContentHint::Screen`]. Everything of [`Capture`] through `Deref`.
453#[derive(Debug)]
454pub struct ScreenSource(Capture);
455
456macro_rules! capture_handle {
457    ($t:ty) => {
458        impl std::ops::Deref for $t {
459            type Target = Capture;
460            fn deref(&self) -> &Capture {
461                &self.0
462            }
463        }
464
465        impl std::ops::DerefMut for $t {
466            fn deref_mut(&mut self) -> &mut Capture {
467                &mut self.0
468            }
469        }
470
471        impl $t {
472            /// The source as a plain [`Capture`].
473            pub fn into_capture(self) -> Capture {
474                self.0
475            }
476        }
477    };
478}
479
480capture_handle!(CameraSource);
481capture_handle!(ScreenSource);
482
483/// What to share ([`VideoCapture::open_screen`]).
484#[derive(Debug, Clone, PartialEq, Eq)]
485#[non_exhaustive]
486pub enum ScreenPick {
487    /// A display or window id from [`VideoCapture::screen_sources`].
488    Listed(String),
489    /// The OS picker. `parent_window` is the app window it opens over (Windows needs it: the
490    /// `HWND` as an integer; ignored elsewhere).
491    System {
492        /// The owning window's native handle.
493        parent_window: Option<u64>,
494    },
495}
496
497/// One display or window to share, with its thumbnail as a PNG.
498#[derive(Debug, Clone, PartialEq, Eq)]
499#[non_exhaustive]
500pub struct ScreenChoice {
501    /// The id [`ScreenPick::Listed`] takes.
502    pub id: String,
503    /// Display or window.
504    pub kind: ScreenKind,
505    /// The display's name or the window's title.
506    pub title: String,
507    /// The window's app, when known.
508    pub app: Option<String>,
509    /// Width in pixels.
510    pub width: u32,
511    /// Height in pixels.
512    pub height: u32,
513    /// A PNG at most [`THUMBNAIL_MAX_WIDTH`] wide (8-bit RGBA), when the backend gave a preview.
514    pub thumbnail_png: Option<Vec<u8>>,
515}
516
517/// Screen constraints: at most `max_width` x `max_height` at `fps`, the cursor drawn, and this
518/// app's own windows left out of display capture where the OS allows it
519/// ([`VideoCapture::open_screen`] clears that where it doesn't).
520pub fn screen_constraints(max_width: u32, max_height: u32, fps: u32) -> CaptureConstraints {
521    let mut c = CaptureConstraints::new(max_width, max_height, fps);
522    c.cursor = true;
523    c.exclude_own_windows = true;
524    c
525}
526
527// ───────────────────────────── the backend ─────────────────────────────
528
529/// The app's video capture over one kessel-video backend. Cheap to clone; clones share the
530/// camera: one opener holds it at a time (a new preview, or a camera opened for the publish,
531/// stops the running preview first).
532#[derive(Clone)]
533pub struct VideoCapture {
534    backend: Arc<dyn VideoBackend>,
535    /// The running preview, if any (it holds the camera).
536    preview: Arc<Mutex<Option<Weak<super::preview::Shared>>>>,
537    /// The open camera taps (raw frames for a native self-view).
538    taps: super::camera_tap::CameraTaps,
539}
540
541impl std::fmt::Debug for VideoCapture {
542    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
543        f.debug_struct("VideoCapture")
544            .field("backend", &self.backend.capabilities().backend)
545            .finish()
546    }
547}
548
549/// Runs `f` on the blocking pool (opening a device may block on the OS).
550async fn blocking<T: Send + 'static>(
551    f: impl FnOnce() -> Result<T, VideoError> + Send + 'static,
552) -> Result<T, VideoError> {
553    tokio::task::spawn_blocking(f)
554        .await
555        .map_err(|e| VideoError::os(0, format!("capture task: {e}")))?
556}
557
558impl VideoCapture {
559    /// Capture through `backend` (`kessel_video::system`, `null()`, a fake or a fixture).
560    pub fn new(backend: Arc<dyn VideoBackend>) -> VideoCapture {
561        VideoCapture {
562            backend,
563            preview: Arc::new(Mutex::new(None)),
564            taps: super::camera_tap::CameraTaps::default(),
565        }
566    }
567
568    /// Raw camera frames for a native self-view ([`super::CameraTap`]): the frames of the
569    /// camera open through this capture or a clone of it (the preview, the bridge's camera
570    /// publish), as captured, before any encoder, with the camera's facing; the feed first
571    /// (`Off`, `Live` or `Paused`). Never opens the camera. Each call is a new tap; dropping
572    /// it closes it.
573    pub fn camera_tap(&self) -> super::CameraTap {
574        self.taps.open()
575    }
576
577    /// The open camera taps (the preview's and the bridge's frames go to them).
578    pub(crate) fn camera_taps(&self) -> &super::camera_tap::CameraTaps {
579        &self.taps
580    }
581
582    /// Stops the running preview (its camera closes now, its channel ends).
583    pub fn stop_preview(&self) {
584        let running = self
585            .preview
586            .lock()
587            .unwrap_or_else(std::sync::PoisonError::into_inner)
588            .take()
589            .and_then(|w| w.upgrade());
590        if let Some(p) = running {
591            p.stop();
592        }
593    }
594
595    /// A preview is running (it holds the camera).
596    pub fn preview_running(&self) -> bool {
597        self.preview
598            .lock()
599            .unwrap_or_else(std::sync::PoisonError::into_inner)
600            .as_ref()
601            .and_then(Weak::upgrade)
602            .is_some_and(|p| p.running())
603    }
604
605    /// The preview that now holds the camera.
606    pub(crate) fn set_preview(&self, p: &Arc<super::preview::Shared>) {
607        *self
608            .preview
609            .lock()
610            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::downgrade(p));
611    }
612
613    /// No video: kessel-video's null backend.
614    pub fn null() -> VideoCapture {
615        VideoCapture::new(kessel_video::null())
616    }
617
618    /// The backend (for encoders and decoders).
619    pub fn backend(&self) -> &Arc<dyn VideoBackend> {
620        &self.backend
621    }
622
623    /// What this machine can do now.
624    pub fn capabilities(&self) -> Capabilities {
625        self.backend.capabilities()
626    }
627
628    /// Which way the camera `device` faces (`None`: the default one, as `open_camera` picks
629    /// it); `Unknown` when it isn't listed.
630    pub fn camera_facing(&self, device: Option<&str>) -> kessel_video::Facing {
631        let cams = self.cameras();
632        match device {
633            Some(id) => cams.iter().find(|c| c.id == id),
634            None => cams.iter().find(|c| c.is_default).or(cams.first()),
635        }
636        .map_or(kessel_video::Facing::Unknown, |c| c.facing)
637    }
638
639    /// The cameras now (opens none, never prompts).
640    pub fn cameras(&self) -> Vec<CameraInfo> {
641        self.backend.cameras()
642    }
643
644    /// The camera permission (never prompts).
645    pub fn camera_permission(&self) -> Permission {
646        self.backend.camera_permission()
647    }
648
649    /// The screen-recording permission (never prompts).
650    pub fn screen_permission(&self) -> Permission {
651        self.backend.screen_permission()
652    }
653
654    /// Machine-wide events: camera hot-plug, capability changes, thermal, background.
655    pub fn events(&self) -> EventRx {
656        self.backend.subscribe()
657    }
658
659    /// Asks the camera permission: the OS prompt when not yet determined, else the state now.
660    pub async fn request_camera_permission(&self) -> Permission {
661        let (tx, rx) = oneshot::channel();
662        self.backend.request_camera_permission(Box::new(move |p| {
663            let _ = tx.send(p);
664        }));
665        rx.await.unwrap_or(Permission::Denied)
666    }
667
668    /// Asks the screen-recording permission (macOS); `Granted` where there is nothing to ask.
669    pub async fn request_screen_permission(&self) -> Permission {
670        let (tx, rx) = oneshot::channel();
671        self.backend.request_screen_permission(Box::new(move |p| {
672            let _ = tx.send(p);
673        }));
674        rx.await.unwrap_or(Permission::Denied)
675    }
676
677    pub(crate) async fn camera_allowed(&self) -> Result<(), CaptureError> {
678        let p = match self.camera_permission() {
679            Permission::NotDetermined => self.request_camera_permission().await,
680            p => p,
681        };
682        match p {
683            Permission::Granted => Ok(()),
684            _ => Err(CaptureError::CameraDenied),
685        }
686    }
687
688    async fn screen_allowed(&self) -> Result<(), CaptureError> {
689        let p = match self.screen_permission() {
690            Permission::NotDetermined => self.request_screen_permission().await,
691            p => p,
692        };
693        match p {
694            Permission::Granted => Ok(()),
695            _ => Err(CaptureError::ScreenDenied),
696        }
697    }
698
699    /// Opens a camera (`None`: the default) at `constraints`: the permission first (the OS
700    /// prompt only when not yet determined), then the device, taken over from a running
701    /// preview (stopped first: one opener holds the camera). Returns once it is open; frames
702    /// follow on [`Capture::ready`].
703    pub async fn open_camera(
704        &self,
705        device: Option<&str>,
706        constraints: CaptureConstraints,
707    ) -> Result<CameraSource, CaptureError> {
708        if !self.capabilities().camera {
709            return Err(CaptureError::VideoUnsupported);
710        }
711        self.camera_allowed().await?;
712        self.stop_preview();
713        let hub = Arc::new(WakeHub::default());
714        let wake = hub.wake();
715        let backend = Arc::clone(&self.backend);
716        let id = device.map(str::to_owned);
717        let asked = id.clone();
718        let source = blocking(move || backend.open_camera(asked.as_deref(), constraints, wake))
719            .await
720            .map_err(camera_error)?;
721        Ok(CameraSource(Capture::new(
722            CaptureKind::Camera,
723            source,
724            hub,
725            constraints,
726            id,
727        )))
728    }
729
730    /// The displays and windows to share, each with a PNG thumbnail when the backend has one.
731    /// `[]` where only the OS picker exists; `screen_unsupported` with no screen capture.
732    pub async fn screen_sources(&self) -> Result<Vec<ScreenChoice>, CaptureError> {
733        let screen = self.capabilities().screen;
734        if !screen.supported {
735            return Err(CaptureError::ScreenUnsupported);
736        }
737        if !screen.list {
738            return Ok(Vec::new());
739        }
740        let backend = Arc::clone(&self.backend);
741        let list = blocking(move || {
742            let list = backend.screen_sources()?;
743            Ok(list.iter().map(choice).collect::<Vec<_>>())
744        })
745        .await
746        .map_err(screen_error)?;
747        Ok(list)
748    }
749
750    /// Shows the OS picker and answers the choice (`picker_cancelled` when cancelled).
751    async fn pick(&self, opts: PickOptions) -> Result<ScreenSelection, CaptureError> {
752        let (tx, rx) = oneshot::channel();
753        self.backend.pick_screen(
754            opts,
755            Box::new(move |r| {
756                let _ = tx.send(r);
757            }),
758        );
759        match rx.await {
760            Ok(r) => r.map_err(pick_error),
761            Err(_) => Err(CaptureError::ScreenUnsupported),
762        }
763    }
764
765    /// Opens a display or window: screen capture must exist here (`screen_unsupported`: Linux
766    /// without the xdg portal or libpipewire), the screen-recording permission (macOS), then the
767    /// listed source or the OS picker's choice ([`ScreenPick::System`] passes the parent window
768    /// on, which Windows needs), then capture at `constraints` (see [`screen_constraints`]).
769    /// The source's encoders take [`ContentHint::Screen`].
770    pub async fn open_screen(
771        &self,
772        pick: ScreenPick,
773        constraints: CaptureConstraints,
774    ) -> Result<ScreenSource, CaptureError> {
775        let screen = self.capabilities().screen;
776        if !screen.supported {
777            return Err(CaptureError::ScreenUnsupported);
778        }
779        self.screen_allowed().await?;
780        let (selection, device) = match pick {
781            ScreenPick::Listed(id) => {
782                if !screen.list {
783                    return Err(CaptureError::ScreenNotFound);
784                }
785                (ScreenSelection::Listed(id.clone()), Some(id))
786            }
787            ScreenPick::System { parent_window } => {
788                if !screen.system_picker {
789                    return Err(CaptureError::ScreenUnsupported);
790                }
791                let mut opts = PickOptions::new();
792                opts.displays = true;
793                opts.windows = screen.windows;
794                if let Some(h) = parent_window {
795                    opts = opts.with_parent_window(h);
796                }
797                (self.pick(opts).await?, None)
798            }
799        };
800        let mut c = constraints;
801        c.exclude_own_windows &= screen.exclude_own_windows;
802        let hub = Arc::new(WakeHub::default());
803        let wake = hub.wake();
804        let backend = Arc::clone(&self.backend);
805        let source = blocking(move || backend.open_screen(&selection, c, wake))
806            .await
807            .map_err(screen_error)?;
808        Ok(ScreenSource(Capture::new(
809            CaptureKind::Screen,
810            source,
811            hub,
812            c,
813            device,
814        )))
815    }
816}
817
818// ───────────────────────────── thumbnails ─────────────────────────────
819
820fn choice(s: &ScreenSourceInfo) -> ScreenChoice {
821    ScreenChoice {
822        id: s.id.clone(),
823        kind: s.kind,
824        title: s.title.clone(),
825        app: s.app.clone(),
826        width: s.width,
827        height: s.height,
828        thumbnail_png: thumbnail_png(s),
829    }
830}
831
832/// The thumbnail's size: kessel-video's `thumbnail_width` and `thumbnail_height`
833/// ([`ScreenSourceInfo::thumbnail_size`]), checked against its planes. `None` when the backend
834/// gave no size, or one the planes don't hold.
835fn thumbnail_size(s: &ScreenSourceInfo, p: &kessel_video::Planes) -> Option<(u32, u32)> {
836    let (w, h) = s.thumbnail_size()?;
837    p.validate(w, h).ok()?;
838    Some((w, h))
839}
840
841/// A source's thumbnail as an 8-bit RGBA PNG at most [`THUMBNAIL_MAX_WIDTH`] wide (scaled down
842/// keeping the aspect ratio, each pixel the average of its box). `None` without a thumbnail,
843/// without its size, or with one that isn't RGBA or BGRA.
844pub fn thumbnail_png(s: &ScreenSourceInfo) -> Option<Vec<u8>> {
845    let p = s.thumbnail.as_ref()?;
846    let bgra = match p.format {
847        PixelFormat::Rgba => false,
848        PixelFormat::Bgra => true,
849        _ => return None,
850    };
851    let (w, h) = thumbnail_size(s, p)?;
852    let (tw, th) = if w > THUMBNAIL_MAX_WIDTH {
853        kessel_video::fit_within(w, h, THUMBNAIL_MAX_WIDTH, h)
854    } else {
855        (w, h)
856    };
857    let rgba = shrink_rgba(p, (w, h), (tw, th), bgra);
858    encode_png(tw, th, &rgba)
859}
860
861/// `p`'s 8-bit 4-channel pixels (`from`) as tight RGBA at `to` (at most `from`): each output
862/// pixel averages its box of input pixels. Straight on the RGB values: no YUV round trip, so a
863/// thumbnail keeps its colours and alpha.
864fn shrink_rgba(p: &kessel_video::Planes, from: (u32, u32), to: (u32, u32), bgra: bool) -> Vec<u8> {
865    let (w, h) = (from.0 as usize, from.1 as usize);
866    let (tw, th) = (to.0 as usize, to.1 as usize);
867    let (stride, off) = (p.strides[0] as usize, p.offsets[0]);
868    let mut out = Vec::with_capacity(tw * th * 4);
869    for ty in 0..th {
870        let (y0, y1) = (ty * h / th, ((ty + 1) * h / th).max(ty * h / th + 1).min(h));
871        for tx in 0..tw {
872            let (x0, x1) = (tx * w / tw, ((tx + 1) * w / tw).max(tx * w / tw + 1).min(w));
873            let mut sum = [0u64; 4];
874            for y in y0..y1 {
875                let row = &p.data[off + y * stride..];
876                for x in x0..x1 {
877                    for (c, v) in sum.iter_mut().enumerate() {
878                        *v += u64::from(row[x * 4 + c]);
879                    }
880                }
881            }
882            let n = ((y1 - y0) * (x1 - x0)) as u64;
883            let avg = sum.map(|v| u8::try_from((v + n / 2) / n).unwrap_or(u8::MAX));
884            let px = if bgra {
885                [avg[2], avg[1], avg[0], avg[3]]
886            } else {
887                avg
888            };
889            out.extend_from_slice(&px);
890        }
891    }
892    out
893}
894
895/// An 8-bit RGBA PNG of `rgba` (tightly packed rows).
896fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Option<Vec<u8>> {
897    let mut out = Vec::new();
898    let mut enc = png::Encoder::new(&mut out, width, height);
899    enc.set_color(png::ColorType::Rgba);
900    enc.set_depth(png::BitDepth::Eight);
901    let mut w = enc.write_header().ok()?;
902    w.write_image_data(rgba).ok()?;
903    w.finish().ok()?;
904    Some(out)
905}
906
907#[cfg(test)]
908mod tests;