Skip to main content

sew_call_client/video/
camera_tap.rs

1//! Raw camera frames for a native self-view (feature `video-core`):
2//! [`VideoCapture::camera_tap`](super::VideoCapture::camera_tap).
3//!
4//! A tap gets the camera's own frames as kessel-video captured them, before any encoder: no
5//! encode, no decode and no copy (each frame is the capture's, shared). What a frame holds is
6//! what the backend gives:
7//! - **macOS and iOS**: the OS's buffer (`FrameBuffer::Native`, a `CVPixelBuffer`, NV12) while
8//!   a call publishes the camera and during the pre-join preview;
9//! - **Android**: CPU planes (I420), which the backend already turned upright;
10//! - **Linux and Windows**: CPU planes as the camera delivers them.
11//!
12//! Frames come upright (the backend turns them; [`CameraFrame::rotation`] says what turn is
13//! still left to the host, `0` with every kessel-video backend) and never mirrored: a host
14//! mirrors a front camera's frames itself ([`CameraFrame::facing`], [`CameraFrame::mirror`]),
15//! frame by frame, so a camera switch lands on the new camera's first frame.
16//!
17//! **No queue.** A tap holds at most one frame: a newer frame replaces one not yet taken (it
18//! counts in [`CameraTap::dropped`]), so a slow reader always gets the newest frame, and the
19//! camera's thread never waits for a reader. Keep a frame no longer than it is shown: on Apple
20//! it is one of the camera's own pool of buffers.
21//!
22//! **The feed** ([`CameraFeed`]): `Live` while frames come, `Paused` while the camera is
23//! paused (the app in the background, another app holding the camera, a hidden window), `Off`
24//! while no camera is open. A change comes before any frame after it; a frame waiting when the
25//! feed pauses or goes off is dropped.
26//!
27//! A tap never opens the camera: frames come while a camera is open through the same
28//! [`VideoCapture`](super::VideoCapture) (the pre-join preview, or the
29//! [`VideoBridge`](super::VideoBridge)'s camera publish). While a tap is open, a published
30//! camera keeps capturing even when no subscriber wants a layer (as with the self-view), and
31//! nothing more is encoded for it.
32
33use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
34use std::time::{Duration, Instant};
35
36use kessel_video::{Facing, VideoFrame};
37use serde::Serialize;
38
39fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
40    m.lock().unwrap_or_else(PoisonError::into_inner)
41}
42
43/// One raw camera frame for a native self-view.
44#[derive(Clone, Debug)]
45#[non_exhaustive]
46pub struct CameraFrame {
47    /// The frame as the backend captured it (shared, not copied): on macOS and iOS an OS
48    /// buffer (`FrameBuffer::Native`, a `CVPixelBuffer`), elsewhere CPU planes. Its `width` and
49    /// `height` are as shown (portrait or landscape), its `capture_us` the backend's clock.
50    pub frame: VideoFrame,
51    /// Which way the camera that captured it faces (`Unknown` when the OS doesn't say).
52    pub facing: Facing,
53    /// Degrees clockwise (0, 90, 180 or 270) the host still has to turn the frame to show it
54    /// upright: `0` with every kessel-video backend, which turns frames upright itself.
55    pub rotation: u32,
56}
57
58impl CameraFrame {
59    /// `frame` from a camera facing `facing`, upright.
60    pub fn new(frame: VideoFrame, facing: Facing) -> CameraFrame {
61        CameraFrame {
62            frame,
63            facing,
64            rotation: 0,
65        }
66    }
67
68    /// Whether a self-view shows this frame mirrored: a front camera's (as a mirror does). The
69    /// pixels are never mirrored; the host mirrors its view.
70    pub fn mirror(&self) -> bool {
71        self.facing == Facing::Front
72    }
73}
74
75/// Whether a tap's camera gives frames ([`CameraTap`]).
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
77#[serde(rename_all = "snake_case")]
78#[non_exhaustive]
79pub enum CameraFeed {
80    /// No camera is open (or it closed).
81    #[default]
82    Off,
83    /// Frames come.
84    Live,
85    /// The camera is open but paused (the app in the background, another app holding the
86    /// camera, a hidden window): no frames until it runs again.
87    Paused,
88}
89
90/// What a [`CameraTap`] gives.
91#[derive(Clone, Debug)]
92#[non_exhaustive]
93pub enum CameraTapItem {
94    /// The feed changed (also the first item of a new tap: the feed then).
95    Feed(CameraFeed),
96    /// The newest frame.
97    Frame(CameraFrame),
98}
99
100struct Slot {
101    feed: CameraFeed,
102    /// The feed changed since the reader last took it.
103    feed_new: bool,
104    frame: Option<CameraFrame>,
105    closed: bool,
106    taken: u64,
107    dropped: u64,
108}
109
110struct Shared {
111    slot: Mutex<Slot>,
112    ready: Condvar,
113}
114
115/// The reading end of a camera tap ([`VideoCapture::camera_tap`](super::VideoCapture::camera_tap)
116/// or [`CameraTap::channel`]): the feed, then the newest frame each time one is taken. Dropping
117/// it (or [`CameraTap::close`]) closes it; the camera side then forgets it.
118pub struct CameraTap {
119    shared: Arc<Shared>,
120}
121
122/// The feeding end of a [`CameraTap`]. Never blocks: a frame replaces one not yet taken.
123#[derive(Clone)]
124pub struct CameraTapSender {
125    shared: Arc<Shared>,
126}
127
128impl std::fmt::Debug for CameraTap {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        let s = lock(&self.shared.slot);
131        f.debug_struct("CameraTap")
132            .field("feed", &s.feed)
133            .field("closed", &s.closed)
134            .finish_non_exhaustive()
135    }
136}
137
138impl std::fmt::Debug for CameraTapSender {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        f.debug_struct("CameraTapSender").finish_non_exhaustive()
141    }
142}
143
144impl CameraTap {
145    /// A tap fed by the caller (a host's own camera, tests): its feed starts `Off`.
146    pub fn channel() -> (CameraTapSender, CameraTap) {
147        let shared = Arc::new(Shared {
148            slot: Mutex::new(Slot {
149                feed: CameraFeed::Off,
150                feed_new: true,
151                frame: None,
152                closed: false,
153                taken: 0,
154                dropped: 0,
155            }),
156            ready: Condvar::new(),
157        });
158        (
159            CameraTapSender {
160                shared: Arc::clone(&shared),
161            },
162            CameraTap { shared },
163        )
164    }
165
166    fn take(s: &mut Slot) -> Option<CameraTapItem> {
167        if s.closed {
168            return None;
169        }
170        if std::mem::take(&mut s.feed_new) {
171            return Some(CameraTapItem::Feed(s.feed));
172        }
173        let f = s.frame.take()?;
174        s.taken += 1;
175        Some(CameraTapItem::Frame(f))
176    }
177
178    /// The feed change or the frame waiting now, if any (`None` once closed).
179    pub fn try_recv(&self) -> Option<CameraTapItem> {
180        Self::take(&mut lock(&self.shared.slot))
181    }
182
183    /// The next feed change or frame, waiting at most `wait` (`None`: nothing came, or the
184    /// tap is closed).
185    pub fn recv_timeout(&self, wait: Duration) -> Option<CameraTapItem> {
186        let until = Instant::now() + wait;
187        let mut s = lock(&self.shared.slot);
188        loop {
189            if let Some(item) = Self::take(&mut s) {
190                return Some(item);
191            }
192            if s.closed {
193                return None;
194            }
195            let left = until.saturating_duration_since(Instant::now());
196            if left.is_zero() {
197                return None;
198            }
199            s = self
200                .shared
201                .ready
202                .wait_timeout(s, left)
203                .unwrap_or_else(PoisonError::into_inner)
204                .0;
205        }
206    }
207
208    /// The feed now.
209    pub fn feed(&self) -> CameraFeed {
210        lock(&self.shared.slot).feed
211    }
212
213    /// Frames taken from the tap so far.
214    pub fn taken(&self) -> u64 {
215        lock(&self.shared.slot).taken
216    }
217
218    /// Frames a newer frame replaced before they were taken (the reader was slower than the
219    /// camera).
220    pub fn dropped(&self) -> u64 {
221        lock(&self.shared.slot).dropped
222    }
223
224    /// Closes the tap: a waiting [`CameraTap::recv_timeout`] returns `None` at once, and no
225    /// frame comes any more.
226    pub fn close(&self) {
227        let stale = {
228            let mut s = lock(&self.shared.slot);
229            s.closed = true;
230            s.frame.take()
231        };
232        drop(stale);
233        self.shared.ready.notify_all();
234    }
235
236    /// The tap is closed.
237    pub fn is_closed(&self) -> bool {
238        lock(&self.shared.slot).closed
239    }
240}
241
242impl Drop for CameraTap {
243    fn drop(&mut self) {
244        self.close();
245    }
246}
247
248impl CameraTapSender {
249    /// Hands `frame` over (the feed turns `Live`), replacing a frame not yet taken. Never
250    /// blocks; `false` once the tap is closed.
251    pub fn send(&self, frame: CameraFrame) -> bool {
252        let stale = {
253            let mut s = lock(&self.shared.slot);
254            if s.closed {
255                return false;
256            }
257            if s.feed != CameraFeed::Live {
258                s.feed = CameraFeed::Live;
259                s.feed_new = true;
260            }
261            let stale = s.frame.replace(frame);
262            if stale.is_some() {
263                s.dropped += 1;
264            }
265            stale
266        };
267        // The replaced frame (an OS buffer on Apple) goes back outside the lock.
268        drop(stale);
269        self.shared.ready.notify_one();
270        true
271    }
272
273    /// The feed is now `feed` (a frame waiting is dropped unless it is `Live`). Never blocks;
274    /// `false` once the tap is closed.
275    pub fn set_feed(&self, feed: CameraFeed) -> bool {
276        let stale = {
277            let mut s = lock(&self.shared.slot);
278            if s.closed {
279                return false;
280            }
281            if s.feed == feed {
282                return true;
283            }
284            s.feed = feed;
285            s.feed_new = true;
286            if feed == CameraFeed::Live {
287                None
288            } else {
289                s.frame.take()
290            }
291        };
292        drop(stale);
293        self.shared.ready.notify_one();
294        true
295    }
296
297    /// The tap's reader closed it.
298    pub fn is_closed(&self) -> bool {
299        lock(&self.shared.slot).closed
300    }
301}
302
303/// Every open tap of one [`VideoCapture`](super::VideoCapture) (shared by its clones and the
304/// bridge built on it), and the feed now.
305#[derive(Clone, Default)]
306pub(crate) struct CameraTaps(Arc<Mutex<Hub>>);
307
308#[derive(Default)]
309struct Hub {
310    taps: Vec<CameraTapSender>,
311    feed: CameraFeed,
312}
313
314impl CameraTaps {
315    /// A new tap; its first item is the feed now.
316    pub(crate) fn open(&self) -> CameraTap {
317        let (tx, rx) = CameraTap::channel();
318        let mut h = lock(&self.0);
319        tx.set_feed(h.feed);
320        h.taps.retain(|t| !t.is_closed());
321        h.taps.push(tx);
322        rx
323    }
324
325    /// A tap is open.
326    pub(crate) fn any(&self) -> bool {
327        let mut h = lock(&self.0);
328        h.taps.retain(|t| !t.is_closed());
329        !h.taps.is_empty()
330    }
331
332    /// A captured frame to every open tap (the feed turns `Live`). Never blocks on a reader.
333    pub(crate) fn frame(&self, frame: &VideoFrame, facing: Facing) {
334        let mut h = lock(&self.0);
335        h.feed = CameraFeed::Live;
336        if h.taps.is_empty() {
337            return;
338        }
339        h.taps
340            .retain(|t| t.send(CameraFrame::new(frame.clone(), facing)));
341    }
342
343    /// The feed is now `feed`, for every open tap.
344    pub(crate) fn feed(&self, feed: CameraFeed) {
345        let mut h = lock(&self.0);
346        h.feed = feed;
347        h.taps.retain(|t| t.set_feed(feed));
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    #![allow(clippy::expect_used, clippy::unwrap_used)]
354    use super::*;
355
356    fn frame(n: u32) -> VideoFrame {
357        kessel_video::fake::pattern_frame(16, 16, n, u64::from(n)).expect("a frame")
358    }
359
360    fn capture_us(item: Option<CameraTapItem>) -> u64 {
361        match item {
362            Some(CameraTapItem::Frame(f)) => f.frame.capture_us,
363            other => panic!("a frame, got {other:?}"),
364        }
365    }
366
367    #[test]
368    fn a_slow_reader_gets_the_newest_frame_and_the_rest_are_counted_dropped() {
369        let taps = CameraTaps::default();
370        let tap = taps.open();
371        assert!(matches!(
372            tap.try_recv(),
373            Some(CameraTapItem::Feed(CameraFeed::Off))
374        ));
375        assert!(tap.try_recv().is_none());
376        for n in 1..=5 {
377            taps.frame(&frame(n), Facing::Front);
378        }
379        assert!(matches!(
380            tap.try_recv(),
381            Some(CameraTapItem::Feed(CameraFeed::Live))
382        ));
383        assert_eq!(capture_us(tap.try_recv()), 5, "the newest frame");
384        assert!(tap.try_recv().is_none(), "never a queue");
385        assert_eq!(tap.dropped(), 4);
386        assert_eq!(tap.taken(), 1);
387    }
388
389    #[test]
390    fn a_pause_drops_the_waiting_frame_and_comes_first() {
391        let taps = CameraTaps::default();
392        taps.frame(&frame(1), Facing::Back);
393        let tap = taps.open();
394        assert!(matches!(
395            tap.try_recv(),
396            Some(CameraTapItem::Feed(CameraFeed::Live))
397        ));
398        taps.frame(&frame(2), Facing::Back);
399        taps.feed(CameraFeed::Paused);
400        assert!(matches!(
401            tap.try_recv(),
402            Some(CameraTapItem::Feed(CameraFeed::Paused))
403        ));
404        assert!(
405            tap.try_recv().is_none(),
406            "the frame before the pause is gone"
407        );
408        taps.frame(&frame(3), Facing::Back);
409        assert!(matches!(
410            tap.try_recv(),
411            Some(CameraTapItem::Feed(CameraFeed::Live))
412        ));
413        match tap.try_recv() {
414            Some(CameraTapItem::Frame(f)) => {
415                assert_eq!(f.facing, Facing::Back);
416                assert_eq!(f.rotation, 0);
417                assert!(!f.mirror());
418            }
419            other => panic!("a frame, got {other:?}"),
420        }
421    }
422
423    #[test]
424    fn a_closed_tap_is_forgotten_and_wakes_its_reader() {
425        let taps = CameraTaps::default();
426        let tap = Arc::new(taps.open());
427        assert!(taps.any());
428        let _ = tap.try_recv();
429        let reader = {
430            let tap = Arc::clone(&tap);
431            std::thread::spawn(move || tap.recv_timeout(Duration::from_secs(30)))
432        };
433        std::thread::sleep(Duration::from_millis(50));
434        tap.close();
435        assert!(
436            reader.join().expect("the reader").is_none(),
437            "closed: nothing"
438        );
439        assert!(!taps.any(), "forgotten");
440        taps.frame(&frame(1), Facing::Front);
441        assert!(tap.try_recv().is_none());
442    }
443
444    #[test]
445    fn a_waiting_reader_wakes_on_a_frame() {
446        let (tx, tap) = CameraTap::channel();
447        assert!(matches!(
448            tap.recv_timeout(Duration::from_millis(1)),
449            Some(CameraTapItem::Feed(CameraFeed::Off))
450        ));
451        let sender = std::thread::spawn(move || {
452            std::thread::sleep(Duration::from_millis(50));
453            tx.send(CameraFrame::new(frame(7), Facing::Front))
454        });
455        assert!(matches!(
456            tap.recv_timeout(Duration::from_secs(10)),
457            Some(CameraTapItem::Feed(CameraFeed::Live))
458        ));
459        assert_eq!(capture_us(tap.recv_timeout(Duration::from_secs(10))), 7);
460        assert!(sender.join().expect("the sender"));
461        drop(tap);
462    }
463}