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    /// A camera's generation for the camera taps' preview items: after `source`, so it goes
275    /// (its `PreviewGone`) once the source has.
276    #[cfg(any(sew_preview_events, test))]
277    _preview: Option<super::camera_tap::PreviewLease>,
278}
279
280impl std::fmt::Debug for Capture {
281    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
282        f.debug_struct("Capture")
283            .field("kind", &self.kind)
284            .field("device", &self.device)
285            .field("ended", &self.ended)
286            .field("paused", &self.paused)
287            .finish_non_exhaustive()
288    }
289}
290
291impl Capture {
292    fn new(
293        kind: CaptureKind,
294        source: Box<dyn FrameSource>,
295        hub: Arc<WakeHub>,
296        constraints: CaptureConstraints,
297        device: Option<String>,
298    ) -> Capture {
299        Capture {
300            kind,
301            source,
302            hub,
303            constraints,
304            device,
305            ended: None,
306            paused: None,
307            #[cfg(any(sew_preview_events, test))]
308            _preview: None,
309        }
310    }
311
312    /// Camera or screen.
313    pub fn kind(&self) -> CaptureKind {
314        self.kind
315    }
316
317    /// The content hint for the encoders this source feeds: [`ContentHint::Camera`] (keep the
318    /// frame rate) or [`ContentHint::Screen`] (keep the detail).
319    pub fn content_hint(&self) -> ContentHint {
320        match self.kind {
321            CaptureKind::Screen => ContentHint::Screen,
322            _ => ContentHint::Camera,
323        }
324    }
325
326    /// The camera's id as asked (`None`: the default camera), or the listed screen's id
327    /// (`None`: the OS picker's choice).
328    pub fn device(&self) -> Option<&str> {
329        self.device.as_deref()
330    }
331
332    /// What the source was last asked for.
333    pub fn constraints(&self) -> CaptureConstraints {
334        self.constraints
335    }
336
337    /// New size and rate without reopening (from the next frame; a
338    /// [`CaptureEvent::Started`] follows with the delivered values).
339    pub fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), CaptureError> {
340        let r = self.source.set_constraints(c);
341        r.map_err(|e| match self.kind {
342            CaptureKind::Camera => camera_error(e),
343            _ => screen_error(e),
344        })?;
345        self.constraints = c;
346        Ok(())
347    }
348
349    /// Stop delivering frames but keep the device open (nothing wants a layer and no
350    /// self-view is open).
351    pub fn set_paused(&mut self, paused: bool) {
352        self.source.set_paused(paused);
353    }
354
355    /// The next frame (CPU planes, or a native buffer when asked with `prefer_native`), if one
356    /// is queued. The queue is 2 deep, oldest dropped; `None` once ended.
357    pub fn try_frame(&mut self) -> Option<kessel_video::VideoFrame> {
358        if self.ended.is_some() {
359            return None;
360        }
361        self.source.try_recv()
362    }
363
364    /// The next event, if one is queued.
365    pub fn try_event(&mut self) -> Option<CaptureEvent> {
366        loop {
367            let e = map_event(self.source.try_event()?);
368            match &e {
369                Some(CaptureEvent::Ended(end)) => self.ended = Some(*end),
370                Some(CaptureEvent::Paused(p)) => self.paused = Some(*p),
371                Some(CaptureEvent::Resumed) => self.paused = None,
372                _ => {}
373            }
374            if e.is_some() {
375                return e;
376            }
377        }
378    }
379
380    /// Waits until the source (or an encoder given [`Capture::wake`]) queued something. Drain
381    /// [`Capture::try_event`] and [`Capture::try_frame`] after each wake; one wake-up is kept
382    /// when nobody waits, so none is lost between a drain and the next wait.
383    pub async fn ready(&self) {
384        self.hub.ready.notified().await;
385    }
386
387    /// The source's wake-up as a kessel-video [`Wake`], for the encoders this source feeds, so
388    /// one task waits on frames and encoded outputs alike.
389    pub fn wake(&self) -> Wake {
390        notify_wake(&self.hub.ready)
391    }
392
393    /// The source's wake-up itself.
394    pub fn notifier(&self) -> Arc<Notify> {
395        Arc::clone(&self.hub.ready)
396    }
397
398    /// From now on the source's frames and events also call `wake` (the bridge's pipeline
399    /// thread, which waits on its own wake-up rather than on [`Capture::ready`]).
400    pub(crate) fn chain_wake(&self, wake: Wake) {
401        *self
402            .hub
403            .chained
404            .lock()
405            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(wake);
406        // Anything already queued is seen at once.
407        self.hub.wake()();
408    }
409
410    /// Why it ended, once it has ([`CaptureEvent::Ended`] was read).
411    pub fn ended(&self) -> Option<CaptureEnd> {
412        self.ended
413    }
414
415    /// Why it is paused, while it is.
416    pub fn paused(&self) -> Option<CapturePause> {
417        self.paused
418    }
419
420    /// The source's counters since open.
421    pub fn stats(&self) -> SourceStats {
422        self.source.stats()
423    }
424}
425
426/// The raw source, for the publish side ([`crate::VideoBridge::publish_capture`] and
427/// [`crate::SourceFeed`]): frames and kessel-video's own events, without [`Capture`]'s
428/// bookkeeping.
429impl FrameSource for Capture {
430    fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
431        self.source.try_recv()
432    }
433
434    fn try_event(&mut self) -> Option<SourceEvent> {
435        self.source.try_event()
436    }
437
438    fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), VideoError> {
439        self.source.set_constraints(c)?;
440        self.constraints = c;
441        Ok(())
442    }
443
444    fn set_paused(&mut self, paused: bool) {
445        self.source.set_paused(paused);
446    }
447
448    fn stats(&self) -> SourceStats {
449        self.source.stats()
450    }
451
452    #[cfg(sew_apple_preview)]
453    fn apple_preview(&self) -> Option<kessel_video::ApplePreview> {
454        self.source.apple_preview()
455    }
456}
457
458/// A running camera ([`VideoCapture::open_camera`]). Everything of [`Capture`] through `Deref`.
459#[derive(Debug)]
460pub struct CameraSource(Capture);
461
462/// A running screen or window capture ([`VideoCapture::open_screen`]), with
463/// [`ContentHint::Screen`]. Everything of [`Capture`] through `Deref`.
464#[derive(Debug)]
465pub struct ScreenSource(Capture);
466
467macro_rules! capture_handle {
468    ($t:ty) => {
469        impl std::ops::Deref for $t {
470            type Target = Capture;
471            fn deref(&self) -> &Capture {
472                &self.0
473            }
474        }
475
476        impl std::ops::DerefMut for $t {
477            fn deref_mut(&mut self) -> &mut Capture {
478                &mut self.0
479            }
480        }
481
482        impl $t {
483            /// The source as a plain [`Capture`].
484            pub fn into_capture(self) -> Capture {
485                self.0
486            }
487        }
488    };
489}
490
491capture_handle!(CameraSource);
492capture_handle!(ScreenSource);
493
494/// What to share ([`VideoCapture::open_screen`]).
495#[derive(Debug, Clone, PartialEq, Eq)]
496#[non_exhaustive]
497pub enum ScreenPick {
498    /// A display or window id from [`VideoCapture::screen_sources`].
499    Listed(String),
500    /// The OS picker. `parent_window` is the app window it opens over (Windows needs it: the
501    /// `HWND` as an integer; ignored elsewhere).
502    System {
503        /// The owning window's native handle.
504        parent_window: Option<u64>,
505    },
506}
507
508/// One display or window to share, with its thumbnail as a PNG.
509#[derive(Debug, Clone, PartialEq, Eq)]
510#[non_exhaustive]
511pub struct ScreenChoice {
512    /// The id [`ScreenPick::Listed`] takes.
513    pub id: String,
514    /// Display or window.
515    pub kind: ScreenKind,
516    /// The display's name or the window's title.
517    pub title: String,
518    /// The window's app, when known.
519    pub app: Option<String>,
520    /// Width in pixels.
521    pub width: u32,
522    /// Height in pixels.
523    pub height: u32,
524    /// A PNG at most [`THUMBNAIL_MAX_WIDTH`] wide (8-bit RGBA), when the backend gave a preview.
525    pub thumbnail_png: Option<Vec<u8>>,
526}
527
528/// Screen constraints: at most `max_width` x `max_height` at `fps`, the cursor drawn, and this
529/// app's own windows left out of display capture where the OS allows it
530/// ([`VideoCapture::open_screen`] clears that where it doesn't).
531pub fn screen_constraints(max_width: u32, max_height: u32, fps: u32) -> CaptureConstraints {
532    let mut c = CaptureConstraints::new(max_width, max_height, fps);
533    c.cursor = true;
534    c.exclude_own_windows = true;
535    c
536}
537
538// ───────────────────────────── the backend ─────────────────────────────
539
540/// The app's video capture over one kessel-video backend. Cheap to clone; clones share the
541/// camera: one opener holds it at a time (a new preview, or a camera opened for the publish,
542/// stops the running preview first).
543#[derive(Clone)]
544pub struct VideoCapture {
545    backend: Arc<dyn VideoBackend>,
546    /// The running preview, if any (it holds the camera).
547    preview: Arc<Mutex<Option<Weak<super::preview::Shared>>>>,
548    /// The open camera taps (raw frames for a native self-view).
549    taps: super::camera_tap::CameraTaps,
550    /// TEST ONLY, off Apple: the stand-in preview the next camera opened gets
551    /// (`FakePreview(n)`, then `n + 1` for the one after); `0`: none.
552    #[cfg(all(not(sew_apple_preview), any(test, feature = "testing")))]
553    fake_previews: Arc<Mutex<u64>>,
554}
555
556impl std::fmt::Debug for VideoCapture {
557    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
558        f.debug_struct("VideoCapture")
559            .field("backend", &self.backend.capabilities().backend)
560            .finish()
561    }
562}
563
564/// Runs `f` on the blocking pool (opening a device may block on the OS).
565async fn blocking<T: Send + 'static>(
566    f: impl FnOnce() -> Result<T, VideoError> + Send + 'static,
567) -> Result<T, VideoError> {
568    tokio::task::spawn_blocking(f)
569        .await
570        .map_err(|e| VideoError::os(0, format!("capture task: {e}")))?
571}
572
573impl VideoCapture {
574    /// Capture through `backend` (`kessel_video::system`, `null()`, a fake or a fixture).
575    pub fn new(backend: Arc<dyn VideoBackend>) -> VideoCapture {
576        VideoCapture {
577            backend,
578            preview: Arc::new(Mutex::new(None)),
579            taps: super::camera_tap::CameraTaps::default(),
580            #[cfg(all(not(sew_apple_preview), any(test, feature = "testing")))]
581            fake_previews: Arc::default(),
582        }
583    }
584
585    /// TEST ONLY: the cameras opened from now on get stand-in previews `FakePreview(from)`,
586    /// `FakePreview(from + 1)`, …; `0`: none.
587    #[cfg(all(test, not(sew_apple_preview)))]
588    pub(crate) fn fake_previews(&self, from: u64) {
589        *self
590            .fake_previews
591            .lock()
592            .unwrap_or_else(std::sync::PoisonError::into_inner) = from;
593    }
594
595    /// The camera source's own zero-hop preview, if it has one, and its facing: kessel-video's
596    /// `ApplePreview`, taken from the backend's source itself before anything wraps it.
597    #[cfg(sew_apple_preview)]
598    fn preview_of(
599        &self,
600        source: &dyn FrameSource,
601        _device: Option<&str>,
602    ) -> (
603        Option<super::camera_tap::PreviewHandle>,
604        kessel_video::Facing,
605    ) {
606        match source.apple_preview() {
607            Some(p) => {
608                let facing = p.facing();
609                (Some(p), facing)
610            }
611            None => (None, kessel_video::Facing::Unknown),
612        }
613    }
614
615    /// TEST ONLY, off Apple: the stand-in preview set with `fake_previews`, if any.
616    #[cfg(all(not(sew_apple_preview), any(test, feature = "testing")))]
617    fn preview_of(
618        &self,
619        _source: &dyn FrameSource,
620        device: Option<&str>,
621    ) -> (
622        Option<super::camera_tap::PreviewHandle>,
623        kessel_video::Facing,
624    ) {
625        let next = {
626            let mut n = self
627                .fake_previews
628                .lock()
629                .unwrap_or_else(std::sync::PoisonError::into_inner);
630            let this = *n;
631            if this != 0 {
632                *n += 1;
633            }
634            (this != 0).then_some(this)
635        };
636        match next {
637            Some(n) => (
638                Some(super::camera_tap::FakePreview(n)),
639                self.camera_facing(device),
640            ),
641            None => (None, kessel_video::Facing::Unknown),
642        }
643    }
644
645    /// Raw camera frames for a native self-view ([`super::CameraTap`]): the frames of the
646    /// camera open through this capture or a clone of it (the preview, the bridge's camera
647    /// publish), as captured, before any encoder, with the camera's facing; the feed first
648    /// (`Off`, `Live` or `Paused`). Never opens the camera. Each call is a new tap; dropping
649    /// it closes it.
650    pub fn camera_tap(&self) -> super::CameraTap {
651        self.taps.open()
652    }
653
654    /// The open camera taps (the preview's and the bridge's frames go to them).
655    pub(crate) fn camera_taps(&self) -> &super::camera_tap::CameraTaps {
656        &self.taps
657    }
658
659    /// Stops the running preview (its camera closes now, its channel ends).
660    pub fn stop_preview(&self) {
661        let running = self
662            .preview
663            .lock()
664            .unwrap_or_else(std::sync::PoisonError::into_inner)
665            .take()
666            .and_then(|w| w.upgrade());
667        if let Some(p) = running {
668            p.stop();
669        }
670    }
671
672    /// A preview is running (it holds the camera).
673    pub fn preview_running(&self) -> bool {
674        self.preview
675            .lock()
676            .unwrap_or_else(std::sync::PoisonError::into_inner)
677            .as_ref()
678            .and_then(Weak::upgrade)
679            .is_some_and(|p| p.running())
680    }
681
682    /// The preview that now holds the camera.
683    pub(crate) fn set_preview(&self, p: &Arc<super::preview::Shared>) {
684        *self
685            .preview
686            .lock()
687            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::downgrade(p));
688    }
689
690    /// No video: kessel-video's null backend.
691    pub fn null() -> VideoCapture {
692        VideoCapture::new(kessel_video::null())
693    }
694
695    /// The backend (for encoders and decoders).
696    pub fn backend(&self) -> &Arc<dyn VideoBackend> {
697        &self.backend
698    }
699
700    /// What this machine can do now.
701    pub fn capabilities(&self) -> Capabilities {
702        self.backend.capabilities()
703    }
704
705    /// Which way the camera `device` faces (`None`: the default one, as `open_camera` picks
706    /// it); `Unknown` when it isn't listed.
707    pub fn camera_facing(&self, device: Option<&str>) -> kessel_video::Facing {
708        let cams = self.cameras();
709        match device {
710            Some(id) => cams.iter().find(|c| c.id == id),
711            None => cams.iter().find(|c| c.is_default).or(cams.first()),
712        }
713        .map_or(kessel_video::Facing::Unknown, |c| c.facing)
714    }
715
716    /// The cameras now (opens none, never prompts).
717    pub fn cameras(&self) -> Vec<CameraInfo> {
718        self.backend.cameras()
719    }
720
721    /// The camera permission (never prompts).
722    pub fn camera_permission(&self) -> Permission {
723        self.backend.camera_permission()
724    }
725
726    /// The screen-recording permission (never prompts).
727    pub fn screen_permission(&self) -> Permission {
728        self.backend.screen_permission()
729    }
730
731    /// Machine-wide events: camera hot-plug, capability changes, thermal, background.
732    pub fn events(&self) -> EventRx {
733        self.backend.subscribe()
734    }
735
736    /// Asks the camera permission: the OS prompt when not yet determined, else the state now.
737    pub async fn request_camera_permission(&self) -> Permission {
738        let (tx, rx) = oneshot::channel();
739        self.backend.request_camera_permission(Box::new(move |p| {
740            let _ = tx.send(p);
741        }));
742        rx.await.unwrap_or(Permission::Denied)
743    }
744
745    /// Asks the screen-recording permission (macOS); `Granted` where there is nothing to ask.
746    pub async fn request_screen_permission(&self) -> Permission {
747        let (tx, rx) = oneshot::channel();
748        self.backend.request_screen_permission(Box::new(move |p| {
749            let _ = tx.send(p);
750        }));
751        rx.await.unwrap_or(Permission::Denied)
752    }
753
754    pub(crate) async fn camera_allowed(&self) -> Result<(), CaptureError> {
755        let p = match self.camera_permission() {
756            Permission::NotDetermined => self.request_camera_permission().await,
757            p => p,
758        };
759        match p {
760            Permission::Granted => Ok(()),
761            _ => Err(CaptureError::CameraDenied),
762        }
763    }
764
765    async fn screen_allowed(&self) -> Result<(), CaptureError> {
766        let p = match self.screen_permission() {
767            Permission::NotDetermined => self.request_screen_permission().await,
768            p => p,
769        };
770        match p {
771            Permission::Granted => Ok(()),
772            _ => Err(CaptureError::ScreenDenied),
773        }
774    }
775
776    /// Opens a camera (`None`: the default) at `constraints`: the permission first (the OS
777    /// prompt only when not yet determined), then the device, taken over from a running
778    /// preview (stopped first: one opener holds the camera). Returns once it is open; frames
779    /// follow on [`Capture::ready`].
780    pub async fn open_camera(
781        &self,
782        device: Option<&str>,
783        constraints: CaptureConstraints,
784    ) -> Result<CameraSource, CaptureError> {
785        if !self.capabilities().camera {
786            return Err(CaptureError::VideoUnsupported);
787        }
788        self.camera_allowed().await?;
789        self.stop_preview();
790        let hub = Arc::new(WakeHub::default());
791        let wake = hub.wake();
792        let backend = Arc::clone(&self.backend);
793        let id = device.map(str::to_owned);
794        let asked = id.clone();
795        let source = blocking(move || backend.open_camera(asked.as_deref(), constraints, wake))
796            .await
797            .map_err(camera_error)?;
798        // A new generation for the camera taps' preview items, with the source's own preview
799        // (taken here, from the backend's source, before anything wraps it).
800        #[cfg(any(sew_preview_events, test))]
801        let lease = {
802            let (preview, facing) = self.preview_of(&*source, device);
803            self.taps.preview_open(preview, facing)
804        };
805        let capture = Capture::new(CaptureKind::Camera, source, hub, constraints, id);
806        #[cfg(any(sew_preview_events, test))]
807        let capture = Capture {
808            _preview: Some(lease),
809            ..capture
810        };
811        Ok(CameraSource(capture))
812    }
813
814    /// The displays and windows to share, each with a PNG thumbnail when the backend has one.
815    /// `[]` where only the OS picker exists; `screen_unsupported` with no screen capture.
816    pub async fn screen_sources(&self) -> Result<Vec<ScreenChoice>, CaptureError> {
817        let screen = self.capabilities().screen;
818        if !screen.supported {
819            return Err(CaptureError::ScreenUnsupported);
820        }
821        if !screen.list {
822            return Ok(Vec::new());
823        }
824        let backend = Arc::clone(&self.backend);
825        let list = blocking(move || {
826            let list = backend.screen_sources()?;
827            Ok(list.iter().map(choice).collect::<Vec<_>>())
828        })
829        .await
830        .map_err(screen_error)?;
831        Ok(list)
832    }
833
834    /// Shows the OS picker and answers the choice (`picker_cancelled` when cancelled).
835    async fn pick(&self, opts: PickOptions) -> Result<ScreenSelection, CaptureError> {
836        let (tx, rx) = oneshot::channel();
837        self.backend.pick_screen(
838            opts,
839            Box::new(move |r| {
840                let _ = tx.send(r);
841            }),
842        );
843        match rx.await {
844            Ok(r) => r.map_err(pick_error),
845            Err(_) => Err(CaptureError::ScreenUnsupported),
846        }
847    }
848
849    /// Opens a display or window: screen capture must exist here (`screen_unsupported`: Linux
850    /// without the xdg portal or libpipewire), the screen-recording permission (macOS), then the
851    /// listed source or the OS picker's choice ([`ScreenPick::System`] passes the parent window
852    /// on, which Windows needs), then capture at `constraints` (see [`screen_constraints`]).
853    /// The source's encoders take [`ContentHint::Screen`].
854    pub async fn open_screen(
855        &self,
856        pick: ScreenPick,
857        constraints: CaptureConstraints,
858    ) -> Result<ScreenSource, CaptureError> {
859        let screen = self.capabilities().screen;
860        if !screen.supported {
861            return Err(CaptureError::ScreenUnsupported);
862        }
863        self.screen_allowed().await?;
864        let (selection, device) = match pick {
865            ScreenPick::Listed(id) => {
866                if !screen.list {
867                    return Err(CaptureError::ScreenNotFound);
868                }
869                (ScreenSelection::Listed(id.clone()), Some(id))
870            }
871            ScreenPick::System { parent_window } => {
872                if !screen.system_picker {
873                    return Err(CaptureError::ScreenUnsupported);
874                }
875                let mut opts = PickOptions::new();
876                opts.displays = true;
877                opts.windows = screen.windows;
878                if let Some(h) = parent_window {
879                    opts = opts.with_parent_window(h);
880                }
881                (self.pick(opts).await?, None)
882            }
883        };
884        let mut c = constraints;
885        c.exclude_own_windows &= screen.exclude_own_windows;
886        let hub = Arc::new(WakeHub::default());
887        let wake = hub.wake();
888        let backend = Arc::clone(&self.backend);
889        let source = blocking(move || backend.open_screen(&selection, c, wake))
890            .await
891            .map_err(screen_error)?;
892        Ok(ScreenSource(Capture::new(
893            CaptureKind::Screen,
894            source,
895            hub,
896            c,
897            device,
898        )))
899    }
900}
901
902// ───────────────────────────── thumbnails ─────────────────────────────
903
904fn choice(s: &ScreenSourceInfo) -> ScreenChoice {
905    ScreenChoice {
906        id: s.id.clone(),
907        kind: s.kind,
908        title: s.title.clone(),
909        app: s.app.clone(),
910        width: s.width,
911        height: s.height,
912        thumbnail_png: thumbnail_png(s),
913    }
914}
915
916/// The thumbnail's size: kessel-video's `thumbnail_width` and `thumbnail_height`
917/// ([`ScreenSourceInfo::thumbnail_size`]), checked against its planes. `None` when the backend
918/// gave no size, or one the planes don't hold.
919fn thumbnail_size(s: &ScreenSourceInfo, p: &kessel_video::Planes) -> Option<(u32, u32)> {
920    let (w, h) = s.thumbnail_size()?;
921    p.validate(w, h).ok()?;
922    Some((w, h))
923}
924
925/// A source's thumbnail as an 8-bit RGBA PNG at most [`THUMBNAIL_MAX_WIDTH`] wide (scaled down
926/// keeping the aspect ratio, each pixel the average of its box). `None` without a thumbnail,
927/// without its size, or with one that isn't RGBA or BGRA.
928pub fn thumbnail_png(s: &ScreenSourceInfo) -> Option<Vec<u8>> {
929    let p = s.thumbnail.as_ref()?;
930    let bgra = match p.format {
931        PixelFormat::Rgba => false,
932        PixelFormat::Bgra => true,
933        _ => return None,
934    };
935    let (w, h) = thumbnail_size(s, p)?;
936    let (tw, th) = if w > THUMBNAIL_MAX_WIDTH {
937        kessel_video::fit_within(w, h, THUMBNAIL_MAX_WIDTH, h)
938    } else {
939        (w, h)
940    };
941    let rgba = shrink_rgba(p, (w, h), (tw, th), bgra);
942    encode_png(tw, th, &rgba)
943}
944
945/// `p`'s 8-bit 4-channel pixels (`from`) as tight RGBA at `to` (at most `from`): each output
946/// pixel averages its box of input pixels. Straight on the RGB values: no YUV round trip, so a
947/// thumbnail keeps its colours and alpha.
948fn shrink_rgba(p: &kessel_video::Planes, from: (u32, u32), to: (u32, u32), bgra: bool) -> Vec<u8> {
949    let (w, h) = (from.0 as usize, from.1 as usize);
950    let (tw, th) = (to.0 as usize, to.1 as usize);
951    let (stride, off) = (p.strides[0] as usize, p.offsets[0]);
952    let mut out = Vec::with_capacity(tw * th * 4);
953    for ty in 0..th {
954        let (y0, y1) = (ty * h / th, ((ty + 1) * h / th).max(ty * h / th + 1).min(h));
955        for tx in 0..tw {
956            let (x0, x1) = (tx * w / tw, ((tx + 1) * w / tw).max(tx * w / tw + 1).min(w));
957            let mut sum = [0u64; 4];
958            for y in y0..y1 {
959                let row = &p.data[off + y * stride..];
960                for x in x0..x1 {
961                    for (c, v) in sum.iter_mut().enumerate() {
962                        *v += u64::from(row[x * 4 + c]);
963                    }
964                }
965            }
966            let n = ((y1 - y0) * (x1 - x0)) as u64;
967            let avg = sum.map(|v| u8::try_from((v + n / 2) / n).unwrap_or(u8::MAX));
968            let px = if bgra {
969                [avg[2], avg[1], avg[0], avg[3]]
970            } else {
971                avg
972            };
973            out.extend_from_slice(&px);
974        }
975    }
976    out
977}
978
979/// An 8-bit RGBA PNG of `rgba` (tightly packed rows).
980fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Option<Vec<u8>> {
981    let mut out = Vec::new();
982    let mut enc = png::Encoder::new(&mut out, width, height);
983    enc.set_color(png::ColorType::Rgba);
984    enc.set_depth(png::BitDepth::Eight);
985    let mut w = enc.write_header().ok()?;
986    w.write_image_data(rgba).ok()?;
987    w.finish().ok()?;
988    Some(out)
989}
990
991#[cfg(test)]
992mod tests;