Skip to main content

sew_call_client/video/
preview.rs

1//! The pre-join camera preview (feature `video-core`): the camera outside a call, one 360p
2//! encoder (VP8, kessel-video's pure-Rust `vp8-encoder`; H.264 only on a backend without VP8),
3//! no lease and nothing sent. Its encoded **plaintext** frames are for this device's own
4//! self-view sink (`local:camera`) and never leave the process.
5//!
6//! The camera opens only on [`VideoCapture::preview`] and closes the moment the [`Preview`] is
7//! stopped or dropped (the light goes off then, not when a task gets round to it).
8//!
9//! Its raw frames go to the capture's camera taps as well ([`VideoCapture::camera_tap`]), before
10//! the encoder, with the camera's facing: the tap's feed is `Live` while it runs, `Paused` while
11//! the OS pauses the camera, `Off` once it stops.
12
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::{Arc, Mutex, MutexGuard};
15use std::time::Duration;
16
17use bytes::Bytes;
18use kessel_video::{
19    Capabilities, CaptureConstraints, CodecConfig, CodecDirection, EncodeOptions, EncoderConfig,
20    Facing, PixelFormat, VideoBackend, VideoEncoder, VideoError,
21};
22use tokio::sync::{Notify, mpsc};
23
24use super::camera_tap::{CameraFeed, CameraTaps};
25use super::capture::{CameraSource, CaptureEnd, CaptureError, CaptureEvent, VideoCapture};
26use super::types::VideoCodec;
27
28/// The preview's largest coded size (the camera's aspect ratio is kept inside it).
29pub const PREVIEW_WIDTH: u32 = 640;
30/// The preview's largest coded height.
31pub const PREVIEW_HEIGHT: u32 = 360;
32/// The preview's frame rate.
33pub const PREVIEW_FPS: u32 = 30;
34/// The preview encoder's bitrate (it is never sent; enough for a clean self-view).
35pub const PREVIEW_BITRATE_BPS: u32 = 800_000;
36/// Items the preview's channel holds; when the reader falls behind, the camera's own 2-deep
37/// queue drops raw frames (never an encoded one, so the stream stays decodable).
38pub const PREVIEW_QUEUE: usize = 8;
39/// Encoder failures in a row before the preview gives up (`encoder_lost`).
40const MAX_ENCODER_FAILURES: u32 = 3;
41
42/// One encoded plaintext frame of this device's own camera or screen (self-view).
43#[derive(Debug, Clone, PartialEq, Eq)]
44#[non_exhaustive]
45pub struct LocalFrame {
46    /// The codec.
47    pub codec: VideoCodec,
48    /// A raw VP8 frame, or one H.264 Annex B access unit with 4-byte start codes.
49    pub data: Bytes,
50    /// A keyframe.
51    pub keyframe: bool,
52    /// The capture time (kessel-video's clock, µs).
53    pub capture_us: u64,
54    /// The coded width.
55    pub width: u32,
56    /// The coded height.
57    pub height: u32,
58    /// Which way the camera that captured it faces (a host mirrors a front camera's
59    /// self-view frame by frame: a switch lands on the new camera's first frame); `Unknown`
60    /// for a screen.
61    pub facing: Facing,
62}
63
64/// What the preview's channel carries.
65#[derive(Debug, Clone, PartialEq, Eq)]
66#[non_exhaustive]
67pub enum PreviewItem {
68    /// An encoded frame for the self-view sink. The first is a keyframe.
69    Frame(LocalFrame),
70    /// The camera ended (unplugged, permission revoked, the backend shut down): the preview is
71    /// over.
72    Ended(CaptureEnd),
73    /// The preview failed (`encoder_lost`) and is over.
74    Failed(CaptureError),
75}
76
77/// The preview's frames.
78pub type PreviewFrames = mpsc::Receiver<PreviewItem>;
79
80/// The codec the preview encodes with on these capabilities: VP8 when the backend has a VP8
81/// encoder (every backend with kessel-video's `vp8`), else H.264, else none.
82pub fn preview_codec(caps: &Capabilities) -> Option<VideoCodec> {
83    if caps
84        .best(kessel_video::VideoCodec::Vp8, CodecDirection::Encode)
85        .is_some()
86    {
87        Some(VideoCodec::Vp8)
88    } else if caps
89        .best(kessel_video::VideoCodec::H264, CodecDirection::Encode)
90        .is_some()
91    {
92        Some(VideoCodec::H264)
93    } else {
94        None
95    }
96}
97
98fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
99    m.lock().unwrap_or_else(|p| p.into_inner())
100}
101
102/// A running preview. Dropping it (or [`Preview::stop`]) closes the camera at once.
103pub struct Preview {
104    shared: Arc<Shared>,
105    codec: VideoCodec,
106    device: Option<String>,
107    task: Option<tokio::task::JoinHandle<()>>,
108}
109
110impl std::fmt::Debug for Preview {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        f.debug_struct("Preview")
113            .field("codec", &self.codec)
114            .field("device", &self.device)
115            .field("running", &self.is_running())
116            .finish()
117    }
118}
119
120pub(crate) struct Shared {
121    state: Mutex<Option<State>>,
122    keyframe: AtomicBool,
123    ready: Arc<Notify>,
124}
125
126impl Shared {
127    /// Closes the camera and the encoder now; the channel ends.
128    pub(crate) fn stop(&self) {
129        let state = lock(&self.state).take();
130        drop(state);
131        self.ready.notify_one();
132    }
133
134    pub(crate) fn running(&self) -> bool {
135        lock(&self.state).is_some()
136    }
137}
138
139struct State {
140    camera: CameraSource,
141    /// The capture's camera taps (the raw frames, before the encoder).
142    taps: CameraTaps,
143    backend: Arc<dyn VideoBackend>,
144    codec: VideoCodec,
145    facing: Facing,
146    encoder: Option<Box<dyn VideoEncoder>>,
147    /// The encoder's coded size.
148    size: (u32, u32),
149    failures: u32,
150}
151
152impl Preview {
153    /// The codec of its frames.
154    pub fn codec(&self) -> VideoCodec {
155        self.codec
156    }
157
158    /// The camera it was opened on (`None`: the default camera).
159    pub fn device(&self) -> Option<&str> {
160        self.device.as_deref()
161    }
162
163    /// The next frame is a keyframe (a self-view sink opened, became visible or failed).
164    /// Never blocks.
165    pub fn request_keyframe(&self) {
166        self.shared.keyframe.store(true, Ordering::Release);
167        self.shared.ready.notify_one();
168    }
169
170    /// The camera and the encoder are open.
171    pub fn is_running(&self) -> bool {
172        self.shared.running()
173    }
174
175    /// Closes the camera and the encoder now; the channel ends.
176    pub fn stop(&self) {
177        self.shared.stop();
178    }
179}
180
181impl Drop for Preview {
182    fn drop(&mut self) {
183        self.stop();
184        if let Some(t) = self.task.take() {
185            t.abort();
186        }
187    }
188}
189
190impl VideoCapture {
191    /// The camera outside a call (`device`: `None` for the default): the permission (the OS
192    /// prompt only when not yet determined), the camera at up to 640x360 and 30 fps, and one
193    /// encoder at that size (the camera's aspect ratio kept). Its frames come on the returned
194    /// channel; nothing is sent anywhere and no lease is taken. Needs a tokio runtime. One
195    /// opener holds the camera: a running preview stops first, and a camera opened later
196    /// through this `VideoCapture` (the bridge's camera publish) stops this one.
197    pub async fn preview(
198        &self,
199        device: Option<&str>,
200    ) -> Result<(Preview, PreviewFrames), CaptureError> {
201        let caps = self.capabilities();
202        if !caps.camera {
203            return Err(CaptureError::VideoUnsupported);
204        }
205        let codec = preview_codec(&caps).ok_or(CaptureError::CodecUnavailable)?;
206        let mut c = CaptureConstraints::new(PREVIEW_WIDTH, PREVIEW_HEIGHT, PREVIEW_FPS);
207        // The OS's own buffers where the backend has them (macOS and iOS), as for a call's
208        // camera: the camera taps get them as captured, and the encoder reads them (an encoder
209        // that can't gets CPU planes converted once).
210        c.prefer_native = true;
211        let camera = self.open_camera(device, c).await?;
212        let facing = self.camera_facing(device);
213        let ready = camera.notifier();
214        let shared = Arc::new(Shared {
215            state: Mutex::new(Some(State {
216                camera,
217                taps: self.camera_taps().clone(),
218                backend: Arc::clone(self.backend()),
219                codec,
220                facing,
221                encoder: None,
222                size: (0, 0),
223                failures: 0,
224            })),
225            keyframe: AtomicBool::new(false),
226            ready,
227        });
228        self.set_preview(&shared);
229        let (tx, rx) = mpsc::channel(PREVIEW_QUEUE);
230        let task = tokio::spawn(run(Arc::clone(&shared), tx));
231        Ok((
232            Preview {
233                shared,
234                codec,
235                device: device.map(str::to_owned),
236                task: Some(task),
237            },
238            rx,
239        ))
240    }
241}
242
243/// Camera → encoder → channel, until the preview stops, the camera ends or the reader goes.
244async fn run(shared: Arc<Shared>, tx: mpsc::Sender<PreviewItem>) {
245    loop {
246        // A wake from the camera or the encoder; the timeout only guards a lost wake.
247        let _ = tokio::time::timeout(Duration::from_millis(250), shared.ready.notified()).await;
248        let key = shared.keyframe.swap(false, Ordering::AcqRel);
249        let (items, over) = {
250            let mut g = lock(&shared.state);
251            let Some(st) = g.as_mut() else { return };
252            st.step(key)
253        };
254        for item in items {
255            if tx.send(item).await.is_err() {
256                lock(&shared.state).take();
257                return;
258            }
259        }
260        if over {
261            lock(&shared.state).take();
262            return;
263        }
264    }
265}
266
267impl Drop for State {
268    fn drop(&mut self) {
269        // The camera closes with it.
270        self.taps.feed(CameraFeed::Off);
271    }
272}
273
274impl State {
275    fn open_encoder(&mut self, w: u32, h: u32) -> Result<(), VideoError> {
276        let mut cfg = match self.codec {
277            VideoCodec::H264 => EncoderConfig::h264(w, h, PREVIEW_FPS, PREVIEW_BITRATE_BPS),
278            _ => EncoderConfig::new(CodecConfig::Vp8, w, h, PREVIEW_FPS, PREVIEW_BITRATE_BPS),
279        };
280        cfg.content = self.camera.content_hint();
281        self.encoder = Some(self.backend.encoder(cfg, self.camera.wake())?);
282        self.size = (w, h);
283        Ok(())
284    }
285
286    /// One pass: the camera's events and frames into the encoder, its outputs out. Answers the
287    /// items to send and whether the preview is over.
288    fn step(&mut self, keyframe: bool) -> (Vec<PreviewItem>, bool) {
289        let mut out = Vec::new();
290        let mut keyframe = keyframe;
291        while let Some(e) = self.camera.try_event() {
292            match e {
293                CaptureEvent::Ended(end) => {
294                    out.push(PreviewItem::Ended(end));
295                    return (out, true);
296                }
297                CaptureEvent::Resumed => keyframe = true,
298                CaptureEvent::Paused(_) => self.taps.feed(CameraFeed::Paused),
299                _ => {}
300            }
301        }
302        if keyframe && let Some(enc) = self.encoder.as_mut() {
303            enc.request_keyframe();
304        }
305        while let Some(frame) = self.camera.try_frame() {
306            self.taps.frame(&frame, self.facing);
307            let fit =
308                kessel_video::fit_within(frame.width, frame.height, PREVIEW_WIDTH, PREVIEW_HEIGHT);
309            if self.encoder.is_some() && self.size != fit {
310                let resized = self.encoder.as_mut().map(|e| e.set_size(fit.0, fit.1));
311                match resized {
312                    Some(Ok(())) => self.size = fit,
313                    _ => self.encoder = None,
314                }
315            }
316            if self.encoder.is_none() && self.open_encoder(fit.0, fit.1).is_err() {
317                self.failures += 1;
318                break;
319            }
320            let Some(enc) = self.encoder.as_mut() else {
321                break;
322            };
323            let submitted = match enc.submit(&frame, EncodeOptions::default()) {
324                Err(VideoError::Unsupported(_))
325                    if matches!(frame.buffer, kessel_video::FrameBuffer::Native(_)) =>
326                {
327                    // An OS buffer this encoder can't take: CPU planes instead.
328                    match self
329                        .backend
330                        .convert(&frame, frame.width, frame.height, PixelFormat::I420)
331                    {
332                        Ok(planes) => enc.submit(&planes, EncodeOptions::default()),
333                        Err(e) => Err(e),
334                    }
335                }
336                other => other,
337            };
338            match submitted {
339                Ok(()) | Err(VideoError::Busy) => {}
340                Err(_) => {
341                    self.encoder = None;
342                    self.failures += 1;
343                }
344            }
345        }
346        if let Some(enc) = self.encoder.as_mut() {
347            while let Some(r) = enc.poll() {
348                match r {
349                    Ok(f) => {
350                        self.failures = 0;
351                        out.push(PreviewItem::Frame(LocalFrame {
352                            codec: self.codec,
353                            data: f.data,
354                            keyframe: f.keyframe,
355                            capture_us: f.capture_us,
356                            width: f.width,
357                            height: f.height,
358                            facing: self.facing,
359                        }));
360                    }
361                    Err(_) => {
362                        // A dead encoder: a new one opens on the next frame (a keyframe first).
363                        self.encoder = None;
364                        self.failures += 1;
365                        break;
366                    }
367                }
368            }
369        }
370        if self.failures >= MAX_ENCODER_FAILURES {
371            out.push(PreviewItem::Failed(CaptureError::EncoderLost));
372            return (out, true);
373        }
374        (out, false)
375    }
376}