Skip to main content

sew_call_client/video/
bridge.rs

1//! `VideoBridge` (feature `video-core`): a kessel-video backend's cameras, screens and encoders
2//! feeding a call's video publications, as `AudioBridge` connects kessel-audio.
3//!
4//! [`VideoBridge::set_camera`] turns the camera on in the order Sew's side asks:
5//! 1. the join's policy (`video_enabled`, `camera_allowed`), else `video_not_allowed`;
6//! 2. the OS permission (prompting once), else `camera_denied`;
7//! 3. the camera lease ([`crate::Call::set_video_lease`]);
8//! 4. the camera, at the policy's camera hints (`camera_busy`, `camera_not_found`), opened
9//!    through the bridge's [`VideoCapture`] (the same device rules as the pre-join preview,
10//!    which it takes the camera over from: one opener holds the camera);
11//! 5. the codec ([`choose_codecs`]: VP8 when the policy lists it and an encoder exists, else
12//!    H.264 from the OS's hardware encoder; never H.264 on Linux, and never from a software
13//!    H.264 encoder) and one encoder per layer of [`crate::plan_layers`] (a screen share's of
14//!    [`crate::plan_screen_layers`]: its top layer at the capture's own size), opened from the top
15//!    down (H.264 hardware-only, each session checked to run on the hardware): a
16//!    `NoResources` (or the codec's `max_instances`) drops the top layer and tries again, down
17//!    to one; nothing opens: `codec_unavailable`, the camera closed and the lease released;
18//! 6. the publication ([`crate::Call::publish_video`]) with the layers that opened, and, when
19//!    the plan has one, the VP8 backup's layers (the same rids and sizes; a phone's stop at
20//!    360p). An H.264 encoder that doesn't open hardware-only, or whose session isn't the
21//!    hardware's, makes it a VP8 publication without a backup.
22//!
23//! **The backup** runs on demand: its encoders open on the engine's `BackupStart` (the first
24//! frame a keyframe) and close on `BackupStop`; each captured frame goes to the backup's
25//! active encoders too. A backup encoder that doesn't open is tried again once after a second;
26//! failing again, the publication is published again in VP8 alone (the same lease), and with
27//! no VP8 encoder either it ends with `encoder_lost`. A hardware H.264 encoder lost mid-call
28//! (its session lost and the reopen failing) publishes again in VP8 alone too, and H.264 isn't
29//! tried again for the rest of that call.
30//!
31//! One capture feeds both: the primary's encoders take the frame as it comes (a native buffer
32//! for a hardware encoder), and the backup's take CPU planes converted once per frame, at its
33//! largest running layer's size, each encoder scaling from there; nothing is converted while
34//! the backup doesn't run. On a phone the backup stops at 360p, and the OS's thermal pressure
35//! caps it further: `Serious` keeps only its lowest layer, `Critical` that layer at 15 fps. Heat
36//! never stops the backup: its lowest layer stays while a subscriber needs it.
37//!
38//! A screen ([`VideoBridge::publish_capture`] with a [`crate::ScreenSource`], or
39//! [`VideoBridge::publish_source`] with a source the host opened) takes the same steps under
40//! the `self_stream` lease with the screen content hint.
41//!
42//! Then one thread per publication: each captured frame goes to every active layer's encoder
43//! (a native buffer another encoder can't take is converted to CPU planes), each encoded frame
44//! to the engine, and the engine's controls back: keyframes, rates and which layers run
45//! (with none running and no self-view the source pauses), a republish's new layers, the end.
46//! A lost encoder session is reopened with a keyframe. A device switch closes the old camera
47//! first (a phone runs one camera at a time), then feeds the new camera's frames to the same
48//! encoders (resized if the aspect changed), a keyframe first; a new layer set republishes. A
49//! new camera that doesn't open brings the old one back; neither: `camera_lost`.
50//!
51//! The source's own events ([`VideoBridge::events`]): `Paused` (a hidden window, another app
52//! took the camera) stops the frames but keeps the publication; `Resumed` asks every layer for
53//! a keyframe; `Ended` unpublishes, releases the lease, and the engine's `LocalVideo` says why
54//! (`user_stopped`, `source_closed`, `camera_lost`, `screen_denied`, …).
55//!
56//! **Self-view** ([`VideoBridge::self_view`]): the plaintext output of one layer per
57//! publication (the camera's `h`, else its lowest layer at 360p or more; the screen's `q`,
58//! else its lowest) goes to this device's own view as well. No second encoder; nothing of it
59//! leaves the process.
60//!
61//! **Camera taps** ([`VideoCapture::camera_tap`] on the bridge's capture): the published
62//! camera's raw frames, as captured and before any encoder, with the camera's facing; the
63//! tap's feed is `Paused` while the camera pauses (the background, another app holding it)
64//! and `Off` when the publication ends. While a tap is open the camera keeps capturing even
65//! when no layer is wanted; nothing more is encoded for it.
66
67use std::collections::{BTreeMap, HashMap};
68use std::sync::atomic::{AtomicBool, Ordering};
69use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
70use std::time::Duration;
71
72use kessel_video::{
73    Capabilities, CaptureConstraints, CodecCapability, CodecConfig, CodecDirection, ContentHint,
74    EncodeOptions, EncoderConfig, Facing, FrameBuffer, FrameSource, ImplPreference, Implementation,
75    PixelFormat, Rates, SourceEvent, VideoBackend, VideoEncoder, VideoError as KError, Wake,
76};
77use serde::Serialize;
78use tokio::sync::{broadcast, mpsc};
79
80use super::camera_tap::{CameraFeed, CameraTaps};
81use super::capture::{
82    Capture, CaptureEnd, CaptureError, CaptureEvent, CaptureKind, CapturePause, VideoCapture,
83    map_event,
84};
85use super::codec_pref::{
86    H264Detection, VideoCodecPreference as CodecPreference, effective_publish_codec_under_policy,
87    h264_encode_detection,
88};
89use super::preview::LocalFrame;
90use super::publish::{
91    BackupCaps, BackupSpec, EncodedVideo, LayerRate, LayerSpec, VideoControl, VideoCtl, VideoError,
92    VideoPublication, VideoPublish, VideoSender, backup_layers_for, plan_source_layers,
93};
94use super::types::{VideoCodec, VideoSource};
95use crate::call::Call;
96
97/// `local_video`'s reason for a camera switch that publishes again (a new layer set).
98pub(crate) const CAMERA_SWITCH: &str = "camera_switch";
99/// `local_video`'s reason when the publication's encoders all failed and none reopened.
100pub(crate) const ENCODER_LOST: &str = "encoder_lost";
101
102/// How long a backup encoder that didn't open waits before its one retry.
103const BACKUP_RETRY: Duration = Duration::from_secs(1);
104/// How long the bridge waits for a source's first `Started`.
105const START_WAIT: Duration = Duration::from_secs(3);
106/// How long an opened camera has to give its first frame before it is refused with
107/// `no_frames` (a camera the OS opens but feeds nothing: a lid-closed MacBook camera, a
108/// Continuity Camera that went away while opening). Nothing is published before that frame.
109const FIRST_FRAME_WAIT: Duration = Duration::from_millis(2500);
110/// How long a pipeline gets to stop (its source and encoders dropped on its own thread); one
111/// that takes longer is left to finish on its own, so no stop ever waits on a device.
112const STOP_WAIT: Duration = Duration::from_secs(2);
113/// Items the self-view channel holds (a full channel drops the frame and asks a keyframe).
114const SELF_VIEW_QUEUE: usize = 8;
115/// Source events kept for a slow reader of [`VideoBridge::events`].
116const EVENT_QUEUE: usize = 32;
117
118/// What to do with the camera ([`VideoBridge::set_camera`]).
119#[derive(Clone, Debug, Default, PartialEq, Eq)]
120#[non_exhaustive]
121pub struct CameraRequest {
122    /// On or off.
123    pub on: bool,
124    /// The camera (`None`: the default). With the camera on, another id switches to it.
125    pub device: Option<String>,
126    /// At most this many VP8 temporal layers (`None`: what the encoder offers, up to 3).
127    pub temporal_layers: Option<u8>,
128    /// With the camera off: `local_video`'s reason (`None`: `unpublished`), so a log tells who
129    /// turned it off (the app's button, the system's call UI, …).
130    pub reason: Option<String>,
131}
132
133impl CameraRequest {
134    /// The default camera on.
135    pub fn on() -> CameraRequest {
136        CameraRequest {
137            on: true,
138            device: None,
139            temporal_layers: None,
140            reason: None,
141        }
142    }
143
144    /// The camera off.
145    pub fn off() -> CameraRequest {
146        CameraRequest::default()
147    }
148
149    /// With camera `device`.
150    pub fn with_device(mut self, device: &str) -> CameraRequest {
151        self.device = Some(device.to_owned());
152        self
153    }
154
155    /// With `reason` as `local_video`'s reason for an off.
156    pub fn with_reason(mut self, reason: &str) -> CameraRequest {
157        self.reason = Some(reason.to_owned());
158        self
159    }
160
161    /// With at most `n` VP8 temporal layers.
162    pub fn with_temporal_layers(mut self, n: u8) -> CameraRequest {
163        self.temporal_layers = Some(n);
164        self
165    }
166}
167
168/// The camera's state after [`VideoBridge::set_camera`].
169#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
170#[serde(tag = "camera", rename_all = "snake_case")]
171#[non_exhaustive]
172pub enum CameraState {
173    /// Off.
174    Off,
175    /// Published.
176    On {
177        /// The codec.
178        codec: VideoCodec,
179        /// The layers that opened, lowest first.
180        layers: Vec<LayerSpec>,
181        /// The camera's delivered size.
182        width: u32,
183        /// Its height.
184        height: u32,
185    },
186}
187
188/// A published source's event ([`VideoBridge::events`]), in capture's vocabulary.
189#[derive(Clone, Debug, PartialEq, Eq)]
190#[non_exhaustive]
191pub struct SourceNote {
192    /// The camera or the screen.
193    pub source: VideoSource,
194    /// What happened: `Paused` (frames stopped, the publication kept), `Resumed` (a keyframe
195    /// was asked of every layer), `Ended` (unpublished, the lease released).
196    pub event: CaptureEvent,
197}
198
199/// What the self-view channel carries ([`VideoBridge::self_view`]).
200#[derive(Clone, Debug, PartialEq, Eq)]
201#[non_exhaustive]
202pub enum SelfViewItem {
203    /// One plaintext frame of the source's self-view layer (the first a keyframe).
204    Frame {
205        /// The camera or the screen.
206        source: VideoSource,
207        /// The frame.
208        frame: LocalFrame,
209    },
210    /// The publication ended: the self-view of that source resets.
211    Ended {
212        /// The camera or the screen.
213        source: VideoSource,
214    },
215}
216
217/// This device's own camera and screen frames while they are published.
218pub type SelfViewFrames = mpsc::Receiver<SelfViewItem>;
219
220fn our_codec(c: kessel_video::VideoCodec) -> Option<VideoCodec> {
221    match c {
222        kessel_video::VideoCodec::Vp8 => Some(VideoCodec::Vp8),
223        kessel_video::VideoCodec::H264 => Some(VideoCodec::H264),
224        _ => None,
225    }
226}
227
228fn their_codec(c: VideoCodec) -> kessel_video::VideoCodec {
229    match c {
230        VideoCodec::Vp8 => kessel_video::VideoCodec::Vp8,
231        VideoCodec::H264 => kessel_video::VideoCodec::H264,
232    }
233}
234
235/// The codec a native sender publishes in: VP8 when the policy lists it and the backend has a
236/// VP8 encoder (kessel-video's pure-Rust one, or the OS's), else H.264 when the policy lists it
237/// and an H.264 encoder exists; `None`: `codec_unavailable`.
238///
239/// Deprecated: it takes any H.264 encoder, a software one too, and never plans a backup. The
240/// bridge uses [`choose_codecs`].
241#[deprecated(
242    note = "use choose_codecs: it takes only usable (hardware) OS H.264 and plans the VP8 backup"
243)]
244pub fn choose_codec(
245    policy: &[sew_proto::voice::VideoCodec],
246    caps: &Capabilities,
247) -> Option<(VideoCodec, CodecCapability)> {
248    for want in [VideoCodec::Vp8, VideoCodec::H264] {
249        let listed = policy
250            .iter()
251            .any(|c| super::publish::codec_of_policy(*c) == Some(want));
252        if !listed {
253            continue;
254        }
255        if let Some(cap) = caps.best(their_codec(want), CodecDirection::Encode) {
256            return Some((want, cap.clone()));
257        }
258    }
259    None
260}
261
262/// One codec of a [`CodecPlan`]: the codec and the backend's encoder entry for it.
263#[derive(Clone, Debug, PartialEq, Eq)]
264#[non_exhaustive]
265pub struct PlannedCodec {
266    /// The codec.
267    pub codec: VideoCodec,
268    /// The backend's encoder entry the encoders open from.
269    pub capability: CodecCapability,
270}
271
272/// What a native sender publishes in ([`choose_codecs`]).
273#[derive(Clone, Debug, PartialEq, Eq)]
274#[non_exhaustive]
275pub struct CodecPlan {
276    /// The codec every subscriber that can decode it gets.
277    pub primary: PlannedCodec,
278    /// The VP8 backup negotiated beside an H.264 primary, whose encoders run only while some
279    /// subscriber is on it; `None`: one codec.
280    pub backup: Option<PlannedCodec>,
281    /// Why this plan, for logs and the host's readback: `h264_detected`, `preferred_h264`,
282    /// `preferred_vp8`, `h264_not_detected`, `backup_off` (the policy's `backup_codec` or
283    /// `dynacast` is off, or it doesn't list both codecs), `no_h264_decode`, `h264_lost`.
284    pub reason: &'static str,
285}
286
287/// Whether this platform may publish OS H.264 at all. Only macOS and iOS for now: Linux has no
288/// OS H.264 and never publishes it; Android and Windows publish VP8 only until their backends
289/// probe the hardware encoder (a static capability entry is an assumption, not a detection).
290/// The `testing` fixture backend (its backend name `fixture`) stands in for an OS backend in
291/// the loopback lanes.
292fn platform_h264(caps: &Capabilities) -> bool {
293    const OS: bool = cfg!(any(target_os = "macos", target_os = "ios"));
294    OS || (cfg!(feature = "testing") && caps.backend == "fixture")
295}
296
297/// The first half of the usable-H.264 test, on the capability list: this platform may publish
298/// OS H.264 ([`platform_h264`]) and the backend lists an H.264 encoder run by the hardware. A
299/// software entry (the OS's software encoder) is never usable. The other two checks run when
300/// the encoders open: they open hardware-only, and each opened session must report hardware
301/// (an OS that can't tell, an iOS before 17.4, counts as not hardware).
302fn usable_h264(caps: &Capabilities) -> Option<&CodecCapability> {
303    if !platform_h264(caps) {
304        return None;
305    }
306    caps.codecs
307        .iter()
308        .filter(|c| {
309            c.codec == kessel_video::VideoCodec::H264
310                && c.direction == CodecDirection::Encode
311                && c.implementation == Implementation::Hardware
312        })
313        .max_by_key(|c| u64::from(c.max_width) * u64::from(c.max_height))
314}
315
316/// What a native sender publishes in, on `caps`, under the call's `policy`, with the
317/// automatic codec preference, on a device that decodes H.264 where its platform does
318/// ([`crate::default_video_h264`]):
319/// 1. **H.264 with a VP8 backup** when the policy has `backup_codec` and `dynacast` on and
320///    lists both codecs (in either order), this device has usable OS H.264 (hardware, detected
321///    from the backend, never assumed; the encoders' open checks the session too), a VP8
322///    encoder exists, and the device decodes H.264;
323/// 2. else **one codec**: VP8 when listed and an encoder exists; else H.264 when listed and
324///    usable (as above);
325/// 3. else `None`: `codec_unavailable`.
326///
327/// Linux never publishes H.264.
328pub fn choose_codecs(
329    policy: &sew_proto::voice::MediaPolicy,
330    caps: &Capabilities,
331) -> Option<CodecPlan> {
332    choose_codecs_with(
333        policy,
334        caps,
335        crate::default_video_h264(),
336        CodecPreference::default(),
337        false,
338    )
339}
340
341/// [`choose_codecs`] with what the call knows: `decodes_h264` (the call's media connection
342/// negotiates H.264), the device's preference, and `h264_lost` (the hardware encoder was lost
343/// earlier in this call: H.264 isn't tried again).
344pub(crate) fn choose_codecs_with(
345    policy: &sew_proto::voice::MediaPolicy,
346    caps: &Capabilities,
347    decodes_h264: bool,
348    pref: CodecPreference,
349    h264_lost: bool,
350) -> Option<CodecPlan> {
351    let listed = |want: VideoCodec| {
352        policy
353            .codecs
354            .iter()
355            .any(|c| super::publish::codec_of_policy(*c) == Some(want))
356    };
357    let vp8 = caps
358        .best(kessel_video::VideoCodec::Vp8, CodecDirection::Encode)
359        .cloned();
360    // The run-time detection on the backend's listing (the encoders' open checks the session).
361    let detected = if platform_h264(caps) {
362        h264_encode_detection(caps)
363    } else {
364        H264Detection::NoPlatformCheck
365    };
366    let h264 = if h264_lost || !decodes_h264 || !detected.is_usable() {
367        None
368    } else {
369        usable_h264(caps).cloned()
370    };
371    let planned = |codec, capability| PlannedCodec { codec, capability };
372    let both = policy.backup_codec
373        && policy.dynacast
374        && listed(VideoCodec::Vp8)
375        && listed(VideoCodec::H264);
376    // Step 1: H.264 with the VP8 backup, as the preference allows.
377    let ready = if h264.is_some() && vp8.is_some() {
378        H264Detection::Usable
379    } else if detected.is_usable() {
380        H264Detection::NotDetected
381    } else {
382        detected
383    };
384    let (pick, _) = effective_publish_codec_under_policy(pref, ready, both);
385    if pick == VideoCodec::H264
386        && let (Some(h), Some(v)) = (h264.clone(), vp8.clone())
387    {
388        return Some(CodecPlan {
389            primary: planned(VideoCodec::H264, h),
390            backup: Some(planned(VideoCodec::Vp8, v)),
391            reason: if pref == CodecPreference::PreferH264 {
392                "preferred_h264"
393            } else {
394                "h264_detected"
395            },
396        });
397    }
398    let reason = if pref == CodecPreference::PreferVp8 {
399        "preferred_vp8"
400    } else if h264_lost {
401        "h264_lost"
402    } else if !both {
403        "backup_off"
404    } else if !decodes_h264 {
405        "no_h264_decode"
406    } else {
407        "h264_not_detected"
408    };
409    // Step 2: one codec, VP8 first; H.264 only when usable.
410    if listed(VideoCodec::Vp8)
411        && let Some(v) = vp8
412    {
413        return Some(CodecPlan {
414            primary: planned(VideoCodec::Vp8, v),
415            backup: None,
416            reason,
417        });
418    }
419    if listed(VideoCodec::H264)
420        && let Some(h) = h264
421    {
422        return Some(CodecPlan {
423            primary: planned(VideoCodec::H264, h),
424            backup: None,
425            reason,
426        });
427    }
428    None
429}
430
431fn camera_error(e: &KError) -> VideoError {
432    match e {
433        KError::NoPermission => VideoError::CameraDenied,
434        KError::DeviceBusy => VideoError::CameraBusy,
435        KError::NotFound | KError::DeviceLost => VideoError::CameraNotFound,
436        other => VideoError::PublishFailed(format!("camera: {}", other.code())),
437    }
438}
439
440/// A capture refusal of the camera as the publish side's error (the same codes).
441fn capture_error(e: &CaptureError) -> VideoError {
442    match e {
443        CaptureError::CameraDenied => VideoError::CameraDenied,
444        CaptureError::CameraBusy => VideoError::CameraBusy,
445        CaptureError::CameraNotFound | CaptureError::CameraLost => VideoError::CameraNotFound,
446        CaptureError::CodecUnavailable => VideoError::CodecUnavailable,
447        CaptureError::Failed(k) => camera_error(k),
448        other => VideoError::PublishFailed(format!("camera: {}", other.code())),
449    }
450}
451
452fn capture_kind(kind: VideoSource) -> CaptureKind {
453    match kind {
454        VideoSource::Camera => CaptureKind::Camera,
455        VideoSource::ScreenShare => CaptureKind::Screen,
456    }
457}
458
459/// The layer whose output is the self-view: the camera's `h` (else its lowest layer at 360p
460/// or more, else its top), the screen's `q` (else its lowest). `layers` lowest first.
461fn self_view_rid(kind: VideoSource, layers: &[LayerSpec]) -> Option<String> {
462    let want = match kind {
463        VideoSource::Camera => "h",
464        VideoSource::ScreenShare => "q",
465    };
466    if let Some(l) = layers.iter().find(|l| l.rid == want) {
467        return Some(l.rid.clone());
468    }
469    let pick = match kind {
470        VideoSource::Camera => layers
471            .iter()
472            .find(|l| l.height >= 360)
473            .or_else(|| layers.last()),
474        VideoSource::ScreenShare => layers.first(),
475    };
476    pick.map(|l| l.rid.clone())
477}
478
479/// Whether this device is a phone (its backup stops at 360p).
480const PHONE: bool = cfg!(any(target_os = "ios", target_os = "android"));
481
482/// The backup's layers for the primary's opened `layers`: on a desktop the same rids and
483/// sizes; on a `phone` only those at most 360p on their short side (the lowest when none is).
484/// Each with `temporal` VP8 temporal layers.
485fn backup_ladder(layers: &[LayerSpec], phone: bool, temporal: u8) -> Vec<LayerSpec> {
486    let mut out: Vec<LayerSpec> = layers
487        .iter()
488        .filter(|l| !phone || l.width.min(l.height) <= 360)
489        .cloned()
490        .collect();
491    if out.is_empty()
492        && let Some(l) = layers.first()
493    {
494        out.push(l.clone());
495    }
496    for l in &mut out {
497        l.temporal_layers = temporal;
498    }
499    out
500}
501
502/// The backup's caps for a phone at thermal `level`: `Serious` only its lowest layer;
503/// `Critical` that layer at 15 fps; below, none. Never fewer than one layer.
504fn thermal_backup_caps(level: kessel_video::ThermalLevel) -> BackupCaps {
505    use kessel_video::ThermalLevel as T;
506    match level {
507        T::Critical => BackupCaps {
508            max_layers: Some(1),
509            max_fps: Some(15),
510        },
511        T::Serious => BackupCaps {
512            max_layers: Some(1),
513            max_fps: None,
514        },
515        _ => BackupCaps::default(),
516    }
517}
518
519/// The VP8 temporal layers for `cap` and the host's ask.
520fn vp8_temporal(cap: &CodecCapability, asked: Option<u8>) -> u8 {
521    let offered = cap.max_temporal_layers.clamp(1, 3);
522    asked.map_or(offered, |t| t.clamp(1, offered))
523}
524
525fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
526    m.lock().unwrap_or_else(PoisonError::into_inner)
527}
528
529/// The camera's capture box: the policy's, and on a phone at most 720p (1280 × 720 either way
530/// round; the thermal and power caps, `Call::set_video_caps`, work below it).
531fn camera_box(max_width: u32, max_height: u32, phone: bool) -> (u32, u32) {
532    if !phone {
533        return (max_width, max_height);
534    }
535    if max_width >= max_height {
536        (max_width.min(1280), max_height.min(720))
537    } else {
538        (max_width.min(720), max_height.min(1280))
539    }
540}
541
542/// A wake that sets a flag and notifies the pipeline thread.
543#[derive(Default)]
544struct Bell {
545    rung: Mutex<bool>,
546    cv: Condvar,
547}
548
549impl Bell {
550    fn ring(&self) {
551        *self.rung.lock().unwrap_or_else(PoisonError::into_inner) = true;
552        self.cv.notify_one();
553    }
554
555    fn wait(&self, at_most: Duration) {
556        let g = self.rung.lock().unwrap_or_else(PoisonError::into_inner);
557        let (mut g, _) = self
558            .cv
559            .wait_timeout_while(g, at_most, |r| !*r)
560            .unwrap_or_else(PoisonError::into_inner);
561        *g = false;
562    }
563
564    fn wake(self: &Arc<Bell>) -> Wake {
565        let b = self.clone();
566        Arc::new(move || b.ring())
567    }
568}
569
570fn content_of(kind: VideoSource) -> ContentHint {
571    match kind {
572        VideoSource::Camera => ContentHint::Camera,
573        VideoSource::ScreenShare => ContentHint::Screen,
574    }
575}
576
577fn encoder_config(codec: VideoCodec, l: &LayerSpec, content: ContentHint) -> EncoderConfig {
578    let bps = l.max_kbps.saturating_mul(1000).max(10_000);
579    let mut cfg = match codec {
580        VideoCodec::Vp8 => EncoderConfig::new(CodecConfig::Vp8, l.width, l.height, l.fps, bps),
581        VideoCodec::H264 => EncoderConfig::h264(l.width, l.height, l.fps, bps),
582    };
583    cfg.temporal_layers = if codec == VideoCodec::Vp8 {
584        l.temporal_layers.clamp(1, 3)
585    } else {
586        1
587    };
588    cfg.content = content;
589    if codec == VideoCodec::H264 {
590        // H.264 only from the OS's hardware encoder: a software session is refused at the open.
591        cfg.implementation = ImplPreference::HardwareOnly;
592    }
593    cfg
594}
595
596/// Opens one layer's encoder. An H.264 session must report that the hardware runs it (the
597/// third check of the usable-H.264 test): one that says software, or can't say, is closed and
598/// refused. On Apple's backend the session's name must also name a hardware encoder
599/// ([`apple_h264_name_is_hardware`]).
600fn open_encoder(
601    backend: &Arc<dyn VideoBackend>,
602    codec: VideoCodec,
603    l: &LayerSpec,
604    content: ContentHint,
605    wake: &Wake,
606) -> Result<Box<dyn VideoEncoder>, KError> {
607    let enc = backend.encoder(encoder_config(codec, l, content), wake.clone())?;
608    if codec == VideoCodec::H264 {
609        let got = enc.implementation();
610        let name = enc.info().name;
611        tracing::info!(target: "sew_call_client", rid = %l.rid, implementation = ?got, encoder = %name, "H.264 session opened");
612        if got != Implementation::Hardware {
613            tracing::info!(target: "sew_call_client", rid = %l.rid, implementation = ?got, encoder = %name, "the H.264 session is not run by the hardware: refused");
614            return Err(KError::Unsupported(
615                "the H.264 session is not hardware".to_owned(),
616            ));
617        }
618        if backend.capabilities().backend == "apple" && !apple_h264_name_is_hardware(&name) {
619            tracing::info!(target: "sew_call_client", rid = %l.rid, implementation = ?got, encoder = %name, "the H.264 session says hardware but its encoder isn't named as hardware: refused");
620            return Err(KError::Unsupported(
621                "the H.264 session's encoder is not named as hardware".to_owned(),
622            ));
623        }
624    }
625    Ok(enc)
626}
627
628/// Whether an Apple (VideoToolbox) H.264 session's name, kessel-video's
629/// `EncoderInfo::name`, names a hardware encoder. A session asked for hardware with
630/// low-latency rate control can run on VideoToolbox's software encoder while it reports
631/// hardware, so such a session counts only when its name carries the hardware encoder's id
632/// (`…ave.avc…`); any other session needs the name to say hardware.
633fn apple_h264_name_is_hardware(name: &str) -> bool {
634    let name = name.to_ascii_lowercase();
635    if name.contains("ave.avc") {
636        return true;
637    }
638    if name.contains("rtvc") || name.contains("software") || name.contains("low-latency") {
639        return false;
640    }
641    name.contains("hardware")
642}
643
644/// One layer's encoder in the pipeline.
645struct Enc {
646    spec: LayerSpec,
647    enc: Box<dyn VideoEncoder>,
648    active: bool,
649    /// The next frame submitted is a keyframe (a new source's first frame). A threaded
650    /// encoder's `request_keyframe` marks whatever input it takes next, which may still be the
651    /// old source's last frame; this rides on the new source's frame itself.
652    key_owed: bool,
653}
654
655impl Enc {
656    /// Submits `frame` with a keyframe if one is owed (cleared once the encoder took it).
657    fn submit(&mut self, frame: &kessel_video::VideoFrame) -> Result<(), KError> {
658        let opts = if self.key_owed {
659            EncodeOptions::keyframe()
660        } else {
661            EncodeOptions::default()
662        };
663        self.enc.submit(frame, opts)?;
664        self.key_owed = false;
665        Ok(())
666    }
667}
668
669/// Opens one encoder per layer, from the top down: `NoResources` (or `max_instances`) drops
670/// the top layer and tries again, down to one layer.
671fn open_encoders(
672    backend: &Arc<dyn VideoBackend>,
673    codec: VideoCodec,
674    cap: &CodecCapability,
675    mut plan: Vec<LayerSpec>,
676    content: ContentHint,
677    wake: &Wake,
678) -> Vec<Enc> {
679    if let Some(m) = cap.max_instances {
680        plan.truncate(usize::try_from(m.max(1)).unwrap_or(1));
681    }
682    while !plan.is_empty() {
683        let mut opened = Vec::new();
684        let mut failed = false;
685        for l in plan.iter().rev() {
686            match open_encoder(backend, codec, l, content, wake) {
687                Ok(enc) => opened.push(Enc {
688                    spec: l.clone(),
689                    enc,
690                    active: true,
691                    key_owed: false,
692                }),
693                Err(e) => {
694                    tracing::info!(target: "sew_call_client", rid = %l.rid, error = %e, "an encoder did not open; one layer fewer");
695                    failed = true;
696                    break;
697                }
698            }
699        }
700        if !failed {
701            opened.reverse();
702            return opened;
703        }
704        drop(opened);
705        plan.pop();
706    }
707    Vec::new()
708}
709
710/// Waits (on the blocking pool) for a source's first `Started` and answers its delivered size
711/// (even), or `fallback` when none came within [`START_WAIT`]. A source that ends first is
712/// `ended`; a camera's error is its code.
713async fn wait_started(
714    mut src: Box<dyn FrameSource>,
715    fallback: (u32, u32),
716    camera: bool,
717    ended: VideoError,
718) -> Result<(Box<dyn FrameSource>, (u32, u32)), VideoError> {
719    tokio::task::spawn_blocking(move || {
720        let until = std::time::Instant::now() + START_WAIT;
721        let size = loop {
722            match src.try_event() {
723                Some(SourceEvent::Started { width, height, .. }) => break (width, height),
724                Some(SourceEvent::Ended(_)) => return Err(ended),
725                Some(SourceEvent::Error(e)) if camera => return Err(camera_error(&e)),
726                Some(_) => {}
727                None if std::time::Instant::now() >= until => break fallback,
728                None => std::thread::sleep(Duration::from_millis(5)),
729            }
730        };
731        Ok((src, (size.0 & !1, size.1 & !1)))
732    })
733    .await
734    .map_err(|_| VideoError::PublishFailed("source thread".to_owned()))?
735}
736
737/// Waits (on the blocking pool) for an opened camera's first frame, at most
738/// [`FIRST_FRAME_WAIT`], and answers the camera with that frame still to come (after the
739/// events seen meanwhile, a suspension and its resume among them) and its delivered size
740/// (even). None in time: [`VideoError::NoFrames`], the camera dropped (closed) there, on the
741/// blocking thread. A camera that ends first is `camera_not_found`; its error is its code.
742async fn wait_first_frame(
743    mut src: Box<dyn FrameSource>,
744) -> Result<(Box<dyn FrameSource>, (u32, u32)), VideoError> {
745    tokio::task::spawn_blocking(move || {
746        let until = std::time::Instant::now() + FIRST_FRAME_WAIT;
747        let mut started = None;
748        let mut events = std::collections::VecDeque::new();
749        loop {
750            while let Some(ev) = src.try_event() {
751                match ev {
752                    SourceEvent::Started { width, height, .. } => started = Some((width, height)),
753                    SourceEvent::Ended(_) => return Err(VideoError::CameraNotFound),
754                    SourceEvent::Error(e) => return Err(camera_error(&e)),
755                    other => events.push_back(other),
756                }
757            }
758            if let Some(frame) = src.try_recv() {
759                let size = started.unwrap_or((frame.width, frame.height));
760                let primed: Box<dyn FrameSource> = Box::new(Primed {
761                    first: Some(frame),
762                    events,
763                    inner: src,
764                });
765                return Ok((primed, (size.0 & !1, size.1 & !1)));
766            }
767            if std::time::Instant::now() >= until {
768                tracing::info!(target: "sew_call_client", waited_ms = FIRST_FRAME_WAIT.as_millis() as u64, "the camera gave no frame: no_frames");
769                return Err(VideoError::NoFrames);
770            }
771            std::thread::sleep(Duration::from_millis(5));
772        }
773    })
774    .await
775    .map_err(|_| VideoError::PublishFailed("source thread".to_owned()))?
776}
777
778/// A camera whose first frame (and the events before it) [`wait_first_frame`] already took:
779/// the events come first, then that frame, then the camera's own.
780struct Primed {
781    first: Option<kessel_video::VideoFrame>,
782    events: std::collections::VecDeque<SourceEvent>,
783    inner: Box<dyn FrameSource>,
784}
785
786impl FrameSource for Primed {
787    fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
788        if !self.events.is_empty() {
789            // The events seen before the first frame are read before it.
790            return None;
791        }
792        self.first.take().or_else(|| self.inner.try_recv())
793    }
794    fn try_event(&mut self) -> Option<SourceEvent> {
795        self.events.pop_front().or_else(|| self.inner.try_event())
796    }
797    fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), KError> {
798        self.inner.set_constraints(c)
799    }
800    fn set_paused(&mut self, paused: bool) {
801        self.inner.set_paused(paused);
802    }
803    fn stats(&self) -> kessel_video::SourceStats {
804        self.inner.stats()
805    }
806}
807
808/// An open source and what the pipeline needs to know of it.
809struct Feed {
810    src: Box<dyn FrameSource>,
811    size: (u32, u32),
812    facing: Facing,
813}
814
815/// Messages from the bridge to its pipeline thread.
816enum ToPipe {
817    /// A device switch: frames now come from this source (a camera facing this way), with the
818    /// encoders at these sizes.
819    Source(Box<dyn FrameSource>, Vec<LayerSpec>, Facing),
820    /// A device switch begins: the current source is dropped (its camera closed) and the
821    /// pipeline holds, the publication and the lease kept, until the next `Source`. Phones
822    /// can't run two cameras at once: the old one closes before the new one opens. The pipeline
823    /// answers once the source is gone.
824    Release(std::sync::mpsc::Sender<()>),
825    /// The app went to the background (`true`) or came back: no frame is captured or encoded
826    /// while paused; on the return every encoder makes a keyframe first.
827    Pause(bool),
828}
829
830/// The pipeline's source between a [`ToPipe::Release`] and the next [`ToPipe::Source`]: no
831/// frames, no events.
832struct Released;
833
834impl FrameSource for Released {
835    fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
836        None
837    }
838    fn try_event(&mut self) -> Option<SourceEvent> {
839        None
840    }
841    fn set_constraints(&mut self, _c: CaptureConstraints) -> Result<(), KError> {
842        Ok(())
843    }
844    fn set_paused(&mut self, _paused: bool) {}
845    fn stats(&self) -> kessel_video::SourceStats {
846        kessel_video::SourceStats::default()
847    }
848}
849
850/// How long a switch waits for the pipeline to drop the old source.
851const RELEASE_WAIT: Duration = Duration::from_secs(3);
852
853struct Running {
854    /// The call it publishes for ([`Call::local_id`]).
855    call: u64,
856    stop: Arc<AtomicBool>,
857    /// The pipeline thread is over (the source or the publication ended).
858    ended: Arc<AtomicBool>,
859    bell: Arc<Bell>,
860    to_pipe: std::sync::mpsc::Sender<ToPipe>,
861    thread: Option<std::thread::JoinHandle<()>>,
862    codec: VideoCodec,
863    /// The codec the pipeline publishes in now (VP8 after a fall back).
864    live: Arc<Mutex<VideoCodec>>,
865    cap: CodecCapability,
866    layers: Vec<LayerSpec>,
867    size: (u32, u32),
868    device: Option<String>,
869    /// The temporal layers asked for.
870    temporal: Option<u8>,
871    /// The pipeline's word: the app is in front, yet the source is still paused by a
872    /// background pause and no frame came since ([`VideoBridge::reopen_held_camera`]).
873    held: Arc<AtomicBool>,
874}
875
876impl Running {
877    fn state(&self) -> CameraState {
878        CameraState::On {
879            codec: *lock(&self.live),
880            layers: self.layers.clone(),
881            width: self.size.0,
882            height: self.size.1,
883        }
884    }
885
886    fn alive(&self) -> bool {
887        !self.ended.load(Ordering::SeqCst)
888    }
889
890    /// Stops the pipeline, waiting at most [`STOP_WAIT`]: a pipeline still stopping then (its
891    /// source's close waiting on the OS) finishes on its own thread.
892    fn stop(mut self) {
893        self.stop.store(true, Ordering::SeqCst);
894        self.bell.ring();
895        let Some(t) = self.thread.take() else { return };
896        let until = std::time::Instant::now() + STOP_WAIT;
897        while !t.is_finished() {
898            if std::time::Instant::now() >= until {
899                tracing::warn!(target: "sew_call_client", waited_ms = STOP_WAIT.as_millis() as u64, "a video pipeline is still stopping (its source closes slowly); it finishes on its own");
900                return;
901            }
902            std::thread::sleep(Duration::from_millis(5));
903        }
904        let _ = t.join();
905    }
906}
907
908async fn stop_running(r: Running) {
909    tokio::task::spawn_blocking(move || r.stop()).await.ok();
910}
911
912/// The two plans have the same layers (by rid, in order).
913fn same_rids(a: &[LayerSpec], b: &[LayerSpec]) -> bool {
914    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.rid == y.rid)
915}
916
917/// Has `r`'s pipeline drop its source ([`ToPipe::Release`]) and waits until it did.
918async fn release_source(r: &Running) -> Result<(), VideoError> {
919    let (tx, rx) = std::sync::mpsc::channel();
920    if r.to_pipe.send(ToPipe::Release(tx)).is_err() {
921        return Err(VideoError::Ended);
922    }
923    r.bell.ring();
924    match tokio::task::spawn_blocking(move || rx.recv_timeout(RELEASE_WAIT)).await {
925        Ok(Ok(())) => Ok(()),
926        _ => Err(VideoError::Ended),
927    }
928}
929
930/// What every pipeline reports to: the source events and the self-view.
931#[derive(Clone)]
932struct Taps {
933    events: broadcast::Sender<SourceNote>,
934    self_view: Arc<Mutex<Option<mpsc::Sender<SelfViewItem>>>>,
935    /// The call ([`Call::local_id`]) whose hardware H.264 encoder was lost: no H.264 again in
936    /// it.
937    h264_lost: Arc<Mutex<Option<u64>>>,
938    /// The capture's camera taps (a camera publication's raw frames).
939    camera: CameraTaps,
940}
941
942/// A publication's self-view keyframe flag and its pipeline's wake.
943type SelfKey = (Arc<AtomicBool>, Arc<Bell>);
944
945/// The video bridge of one app: a kessel-video backend into the current call.
946pub struct VideoBridge {
947    capture: VideoCapture,
948    camera: tokio::sync::Mutex<Option<Running>>,
949    /// Publications from sources opened outside [`VideoBridge::set_camera`]
950    /// ([`VideoBridge::publish_source`], [`VideoBridge::publish_capture`]).
951    feeds: tokio::sync::Mutex<HashMap<VideoSource, Running>>,
952    taps: Taps,
953    /// Each publication's self-view keyframe flag and its pipeline's wake.
954    self_keys: Mutex<HashMap<VideoSource, SelfKey>>,
955}
956
957/// A frame source a host opened itself (a screen or window from its picker, a camera with its
958/// own preview), handed to [`VideoBridge::publish_source`]: any kessel-video [`FrameSource`]
959/// and the size it delivers.
960pub struct SourceFeed {
961    /// The frames.
962    pub frames: Box<dyn FrameSource>,
963    /// Its delivered width.
964    pub width: u32,
965    /// Its delivered height.
966    pub height: u32,
967}
968
969impl std::fmt::Debug for SourceFeed {
970    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
971        f.debug_struct("SourceFeed")
972            .field("width", &self.width)
973            .field("height", &self.height)
974            .finish_non_exhaustive()
975    }
976}
977
978impl SourceFeed {
979    /// `frames` delivering `width × height`.
980    pub fn new(frames: Box<dyn FrameSource>, width: u32, height: u32) -> SourceFeed {
981        SourceFeed {
982            frames,
983            width,
984            height,
985        }
986    }
987}
988
989impl std::fmt::Debug for VideoBridge {
990    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
991        f.debug_struct("VideoBridge").finish_non_exhaustive()
992    }
993}
994
995impl VideoBridge {
996    /// A bridge over `backend` (one per app).
997    pub fn new(backend: Arc<dyn VideoBackend>) -> VideoBridge {
998        VideoBridge::with_capture(VideoCapture::new(backend))
999    }
1000
1001    /// A bridge over the app's `capture` (its clones share the camera with the bridge: a
1002    /// preview opened through one of them hands the camera over to the camera publish).
1003    pub fn with_capture(capture: VideoCapture) -> VideoBridge {
1004        let camera = capture.camera_taps().clone();
1005        VideoBridge {
1006            capture,
1007            camera: tokio::sync::Mutex::new(None),
1008            feeds: tokio::sync::Mutex::new(HashMap::new()),
1009            taps: Taps {
1010                events: broadcast::channel(EVENT_QUEUE).0,
1011                self_view: Arc::new(Mutex::new(None)),
1012                h264_lost: Arc::new(Mutex::new(None)),
1013                camera,
1014            },
1015            self_keys: Mutex::new(HashMap::new()),
1016        }
1017    }
1018
1019    /// The capture the bridge opens its cameras through.
1020    pub fn capture(&self) -> &VideoCapture {
1021        &self.capture
1022    }
1023
1024    /// The backend.
1025    pub fn backend(&self) -> &Arc<dyn VideoBackend> {
1026        self.capture.backend()
1027    }
1028
1029    /// The published sources' events (pauses, resumes, ends), from now on.
1030    pub fn events(&self) -> broadcast::Receiver<SourceNote> {
1031        self.taps.events.subscribe()
1032    }
1033
1034    /// The self-view from now on: each publication's self-view layer (see the module docs),
1035    /// until the receiver is dropped or a newer one is asked for. While one is open the
1036    /// source never pauses, even with no layer wanted by anyone.
1037    pub fn self_view(&self) -> SelfViewFrames {
1038        let (tx, rx) = mpsc::channel(SELF_VIEW_QUEUE);
1039        *lock(&self.taps.self_view) = Some(tx);
1040        for (key, bell) in lock(&self.self_keys).values() {
1041            key.store(true, Ordering::Release);
1042            bell.ring();
1043        }
1044        rx
1045    }
1046
1047    /// The self-view of `source` needs a keyframe (a sink opened, became visible or failed).
1048    /// Never blocks.
1049    pub fn self_view_keyframe(&self, source: VideoSource) {
1050        if let Some((key, bell)) = lock(&self.self_keys).get(&source) {
1051            key.store(true, Ordering::Release);
1052            bell.ring();
1053        }
1054    }
1055
1056    /// The camera now: [`CameraState::On`] while [`VideoBridge::set_camera`] publishes it.
1057    pub async fn camera_state(&self) -> CameraState {
1058        match self.camera.lock().await.as_ref() {
1059            Some(r) if r.alive() => r.state(),
1060            _ => CameraState::Off,
1061        }
1062    }
1063
1064    /// The camera device [`VideoBridge::set_camera`] publishes (`None`: the default, or off).
1065    pub async fn camera_device(&self) -> Option<String> {
1066        self.camera
1067            .lock()
1068            .await
1069            .as_ref()
1070            .filter(|r| r.alive())
1071            .and_then(|r| r.device.clone())
1072    }
1073
1074    /// Publishes `kind` from a source the host opened (see [`SourceFeed`]): the policy (video
1075    /// on, the source allowed), the lease (`self_video` or `self_stream`), the codec and one
1076    /// encoder per layer of the policy's hints for that source, the publication and the
1077    /// pipeline. The bridge owns the source from here; [`VideoBridge::stop_source`] ends it,
1078    /// and so does the source's own end.
1079    pub async fn publish_source(
1080        &self,
1081        call: &Call,
1082        kind: VideoSource,
1083        feed: SourceFeed,
1084        temporal_layers: Option<u8>,
1085    ) -> Result<CameraState, VideoError> {
1086        let size = (feed.width & !1, feed.height & !1);
1087        let bell = Arc::new(Bell::default());
1088        let feed_in = Feed {
1089            src: feed.frames,
1090            size,
1091            facing: Facing::Unknown,
1092        };
1093        self.publish_frames(call, kind, feed_in, temporal_layers, bell)
1094            .await
1095    }
1096
1097    /// Publishes `kind` from a camera or screen opened through [`VideoCapture`] (a
1098    /// [`crate::ScreenSource`] with [`crate::ScreenSource::into_capture`]): its size from its
1099    /// first `Started` (at most its constraints), then as [`VideoBridge::publish_source`].
1100    pub async fn publish_capture(
1101        &self,
1102        call: &Call,
1103        kind: VideoSource,
1104        capture: Capture,
1105        temporal_layers: Option<u8>,
1106    ) -> Result<CameraState, VideoError> {
1107        let bell = Arc::new(Bell::default());
1108        capture.chain_wake(bell.wake());
1109        let facing = match kind {
1110            VideoSource::Camera => self.capture.camera_facing(capture.device()),
1111            VideoSource::ScreenShare => Facing::Unknown,
1112        };
1113        let c = capture.constraints();
1114        let fallback = (c.max_width.unwrap_or(1280), c.max_height.unwrap_or(720));
1115        let ended = match kind {
1116            VideoSource::Camera => VideoError::CameraNotFound,
1117            VideoSource::ScreenShare => VideoError::PublishFailed("screen: ended".to_owned()),
1118        };
1119        let (src, size) = wait_started(
1120            Box::new(capture),
1121            fallback,
1122            kind == VideoSource::Camera,
1123            ended,
1124        )
1125        .await?;
1126        let feed = Feed { src, size, facing };
1127        self.publish_frames(call, kind, feed, temporal_layers, bell)
1128            .await
1129    }
1130
1131    async fn publish_frames(
1132        &self,
1133        call: &Call,
1134        kind: VideoSource,
1135        feed: Feed,
1136        temporal_layers: Option<u8>,
1137        bell: Arc<Bell>,
1138    ) -> Result<CameraState, VideoError> {
1139        let mut feeds = self.feeds.lock().await;
1140        if feeds
1141            .get(&kind)
1142            .is_some_and(|r| !r.alive() || r.call != call.local_id())
1143            && let Some(r) = feeds.remove(&kind)
1144        {
1145            stop_running(r).await;
1146        }
1147        if feeds.contains_key(&kind) {
1148            return Err(VideoError::AlreadyPublished);
1149        }
1150        let policy = call.media_policy().ok_or(VideoError::NotAllowed)?;
1151        let allowed = match kind {
1152            VideoSource::Camera => policy.camera_allowed,
1153            VideoSource::ScreenShare => policy.screen_allowed,
1154        };
1155        if !policy.video_enabled || !allowed {
1156            return Err(VideoError::NotAllowed);
1157        }
1158        call.set_video_lease(kind, true).await?;
1159        let started = self
1160            .start_from(call, &policy, kind, feed, temporal_layers, None, bell)
1161            .await;
1162        match started {
1163            Ok(r) => {
1164                let state = r.state();
1165                feeds.insert(kind, r);
1166                Ok(state)
1167            }
1168            Err(e) => {
1169                let _ = call.set_video_lease(kind, false).await;
1170                Err(e)
1171            }
1172        }
1173    }
1174
1175    /// Ends a [`VideoBridge::publish_source`] or [`VideoBridge::publish_capture`] publication:
1176    /// the track unpublished, the source dropped (closed), the lease released.
1177    pub async fn stop_source(&self, call: &Call, kind: VideoSource) -> Result<(), VideoError> {
1178        let running = self.feeds.lock().await.remove(&kind);
1179        if let Some(r) = running {
1180            stop_running(r).await;
1181        }
1182        match call.unpublish_video(kind, true).await {
1183            Ok(()) | Err(VideoError::NotPublished) => Ok(()),
1184            Err(e) => Err(e),
1185        }
1186    }
1187
1188    /// Turns the camera on (see the module docs), switches it to another device, or turns it
1189    /// off (the track unpublished, the camera closed, the lease released).
1190    pub async fn set_camera(
1191        &self,
1192        call: &Call,
1193        req: CameraRequest,
1194    ) -> Result<CameraState, VideoError> {
1195        let mut slot = self.camera.lock().await;
1196        if slot
1197            .as_ref()
1198            .is_some_and(|r| !r.alive() || r.call != call.local_id())
1199            && let Some(r) = slot.take()
1200        {
1201            // Its source or publication ended (unpublished already), or it was an earlier
1202            // call's.
1203            stop_running(r).await;
1204        }
1205        if !req.on {
1206            if let Some(r) = slot.take() {
1207                stop_running(r).await;
1208            }
1209            let reason = req.reason.as_deref().unwrap_or(super::publish::UNPUBLISHED);
1210            tracing::info!(target: "sew_call_client", %reason, "the camera turns off");
1211            return match call
1212                .unpublish_video_because(VideoSource::Camera, true, reason)
1213                .await
1214            {
1215                Ok(()) | Err(VideoError::NotPublished) => Ok(CameraState::Off),
1216                Err(e) => Err(e),
1217            };
1218        }
1219        let policy = call.media_policy().ok_or(VideoError::NotAllowed)?;
1220        if !policy.video_enabled || !policy.camera_allowed {
1221            return Err(VideoError::NotAllowed);
1222        }
1223        // A camera opens (or reopens on another device): the device is busy for a moment, so
1224        // the call's noise removal stage holds its timing rules back.
1225        if slot.as_ref().is_none_or(|r| r.device != req.device) {
1226            call.noise_grace();
1227        }
1228        if let Some(r) = slot.as_ref() {
1229            if r.device == req.device {
1230                return Ok(r.state());
1231            }
1232            return self.switch(call, &mut slot, &policy, req).await;
1233        }
1234        self.capture
1235            .camera_allowed()
1236            .await
1237            .map_err(|e| capture_error(&e))?;
1238        call.set_video_lease(VideoSource::Camera, true).await?;
1239        match self.start(call, &policy, &req).await {
1240            Ok(r) => {
1241                let state = r.state();
1242                *slot = Some(r);
1243                Ok(state)
1244            }
1245            Err(e) => {
1246                let _ = call.set_video_lease(VideoSource::Camera, false).await;
1247                Err(e)
1248            }
1249        }
1250    }
1251
1252    /// Switches the published camera to `device` (`None`: the default) when the camera is on;
1253    /// [`CameraState::Off`] and nothing opened when it is off (a host's camera choice between
1254    /// `set_camera` calls).
1255    pub async fn switch_camera(
1256        &self,
1257        call: &Call,
1258        device: Option<String>,
1259    ) -> Result<CameraState, VideoError> {
1260        let mut slot = self.camera.lock().await;
1261        let Some(r) = slot
1262            .as_ref()
1263            .filter(|r| r.alive() && r.call == call.local_id())
1264        else {
1265            return Ok(CameraState::Off);
1266        };
1267        if r.device == device {
1268            return Ok(r.state());
1269        }
1270        let mut req = CameraRequest::on();
1271        req.device = device;
1272        req.temporal_layers = r.temporal;
1273        let policy = call.media_policy().ok_or(VideoError::NotAllowed)?;
1274        call.noise_grace();
1275        self.switch(call, &mut slot, &policy, req).await
1276    }
1277
1278    /// Opens the camera through the capture (taking it over from a running preview); waits
1279    /// for its delivered size.
1280    async fn open(
1281        &self,
1282        device: Option<String>,
1283        policy: &sew_proto::voice::MediaPolicy,
1284        bell: &Arc<Bell>,
1285    ) -> Result<(Box<dyn FrameSource>, (u32, u32)), VideoError> {
1286        let hint = &policy.camera;
1287        let phone = cfg!(any(target_os = "ios", target_os = "android"));
1288        let (w, h) = camera_box(hint.max_width, hint.max_height, phone);
1289        let mut c = CaptureConstraints::new(w.max(16), h.max(16), hint.max_fps.clamp(1, 240));
1290        c.prefer_native = true;
1291        let cam = self
1292            .capture
1293            .open_camera(device.as_deref(), c)
1294            .await
1295            .map_err(|e| capture_error(&e))?
1296            .into_capture();
1297        cam.chain_wake(bell.wake());
1298        // Nothing is published before the camera's first frame.
1299        wait_first_frame(Box::new(cam)).await
1300    }
1301
1302    fn plan(
1303        policy: &sew_proto::voice::MediaPolicy,
1304        kind: VideoSource,
1305        codec: VideoCodec,
1306        cap: &CodecCapability,
1307        temporal_layers: Option<u8>,
1308        size: (u32, u32),
1309    ) -> Vec<LayerSpec> {
1310        let tl = if codec == VideoCodec::Vp8 {
1311            let offered = cap.max_temporal_layers.clamp(1, 3);
1312            temporal_layers.map_or(offered, |t| t.clamp(1, offered))
1313        } else {
1314            1
1315        };
1316        let mut plan =
1317            plan_source_layers(kind, super::publish::hint_of(kind, policy), size.0, size.1);
1318        for l in &mut plan {
1319            l.temporal_layers = tl;
1320        }
1321        plan
1322    }
1323
1324    async fn start(
1325        &self,
1326        call: &Call,
1327        policy: &sew_proto::voice::MediaPolicy,
1328        req: &CameraRequest,
1329    ) -> Result<Running, VideoError> {
1330        let bell = Arc::new(Bell::default());
1331        let (src, size) = self.open(req.device.clone(), policy, &bell).await?;
1332        let facing = self.capture.camera_facing(req.device.as_deref());
1333        self.start_from(
1334            call,
1335            policy,
1336            VideoSource::Camera,
1337            Feed { src, size, facing },
1338            req.temporal_layers,
1339            req.device.clone(),
1340            bell,
1341        )
1342        .await
1343    }
1344
1345    /// The codec, the encoders, the publication and the pipeline for an open source.
1346    #[allow(clippy::too_many_arguments)]
1347    async fn start_from(
1348        &self,
1349        call: &Call,
1350        policy: &sew_proto::voice::MediaPolicy,
1351        kind: VideoSource,
1352        feed: Feed,
1353        temporal_layers: Option<u8>,
1354        device: Option<String>,
1355        bell: Arc<Bell>,
1356    ) -> Result<Running, VideoError> {
1357        let Feed { src, size, facing } = feed;
1358        let backend = Arc::clone(self.backend());
1359        let caps = backend.capabilities();
1360        let lost = *lock(&self.taps.h264_lost) == Some(call.local_id());
1361        // The device's setting (Automatic until the host sets one).
1362        let pref = call.video_codec_preference();
1363        let Some(mut plan) = choose_codecs_with(policy, &caps, call.decodes_h264(), pref, lost)
1364        else {
1365            return Err(VideoError::CodecUnavailable);
1366        };
1367        tracing::info!(target: "sew_call_client", source = ?kind, codec = plan.primary.codec.as_str(), backup = plan.backup.as_ref().map(|b| b.codec.as_str()), reason = plan.reason, "the codec plan");
1368        let content = content_of(kind);
1369        let open = |codec: VideoCodec, cap: CodecCapability| {
1370            let layers = VideoBridge::plan(policy, kind, codec, &cap, temporal_layers, size);
1371            let wake = bell.wake();
1372            let b2 = Arc::clone(&backend);
1373            async move {
1374                tokio::task::spawn_blocking(move || {
1375                    open_encoders(&b2, codec, &cap, layers, content, &wake)
1376                })
1377                .await
1378                .map_err(|_| VideoError::PublishFailed("encoder thread".to_owned()))
1379            }
1380        };
1381        let mut encs = open(plan.primary.codec, plan.primary.capability.clone()).await?;
1382        if encs.is_empty() && plan.primary.codec == VideoCodec::H264 {
1383            // The hardware-only open, or the session's own report, said no: one codec, VP8.
1384            tracing::info!(target: "sew_call_client", source = ?kind, "the H.264 encoder did not open on the hardware: VP8 only");
1385            match choose_codecs_with(policy, &caps, false, pref, true) {
1386                Some(p) if p.primary.codec == VideoCodec::Vp8 => {
1387                    plan = p;
1388                    plan.reason = "h264_open_failed";
1389                    encs = open(VideoCodec::Vp8, plan.primary.capability.clone()).await?;
1390                }
1391                _ => {}
1392            }
1393        }
1394        if encs.is_empty() {
1395            return Err(VideoError::CodecUnavailable);
1396        }
1397        let (codec, cap) = (plan.primary.codec, plan.primary.capability.clone());
1398        let layers: Vec<LayerSpec> = encs.iter().map(|e| e.spec.clone()).collect();
1399        let vp8 = match &plan.backup {
1400            Some(b) => Some(b.capability.clone()),
1401            None if codec == VideoCodec::Vp8 => Some(cap.clone()),
1402            None => caps
1403                .best(kessel_video::VideoCodec::Vp8, CodecDirection::Encode)
1404                .cloned(),
1405        };
1406        let backup = plan.backup.as_ref().map(|b| {
1407            let ladder =
1408                backup_ladder(&layers, PHONE, vp8_temporal(&b.capability, temporal_layers));
1409            BackupPipe::new(b.codec, ladder)
1410        });
1411        let mut req = VideoPublish::new(kind, codec, layers.clone(), size.0, size.1);
1412        if let Some(b) = &backup {
1413            req = req.with_backup(BackupSpec::new(b.codec, b.ladder.clone()));
1414        }
1415        let publication = call.publish_video(req).await?;
1416        tracing::info!(target: "sew_call_client", source = ?kind, codec = codec.as_str(), layers = layers.len(), backup = backup.as_ref().map(|b| b.ladder.len()), width = size.0, height = size.1, "video source on");
1417        let live = Arc::new(Mutex::new(codec));
1418        let stop = Arc::new(AtomicBool::new(false));
1419        let ended = Arc::new(AtomicBool::new(false));
1420        let self_key = Arc::new(AtomicBool::new(false));
1421        lock(&self.self_keys).insert(kind, (Arc::clone(&self_key), Arc::clone(&bell)));
1422        let held = Arc::new(AtomicBool::new(false));
1423        let (to_pipe, from_bridge) = std::sync::mpsc::channel();
1424        let mut pipe = Pipe {
1425            backend,
1426            kind,
1427            codec,
1428            content,
1429            src,
1430            facing,
1431            was_facing: facing,
1432            facing_since_us: 0,
1433            released_us: None,
1434            self_rid: self_view_rid(kind, &layers),
1435            encs: encs.into_iter().map(|e| (e.spec.rid.clone(), e)).collect(),
1436            publication,
1437            ctl: call.video_ctl(),
1438            taps: self.taps.clone(),
1439            stop: stop.clone(),
1440            ended: ended.clone(),
1441            self_key,
1442            bell: bell.clone(),
1443            from_bridge,
1444            paused: false,
1445            hidden: false,
1446            hidden_why: None,
1447            fresh_since_us: 0,
1448            held: Arc::clone(&held),
1449            scene_paused: false,
1450            end_asked: false,
1451            call: call.local_id(),
1452            backup,
1453            vp8,
1454            temporal: temporal_layers,
1455            live: live.clone(),
1456            phone: PHONE,
1457            machine: self.backend().subscribe(),
1458            thermal: kessel_video::ThermalLevel::Nominal,
1459            backup_converts: Arc::default(),
1460        };
1461        let name = match kind {
1462            VideoSource::Camera => "sew-video-camera",
1463            VideoSource::ScreenShare => "sew-video-screen",
1464        };
1465        let thread = std::thread::Builder::new()
1466            .name(name.to_owned())
1467            .spawn(move || pipe.run())
1468            .map_err(|e| VideoError::PublishFailed(format!("spawn: {e}")))?;
1469        Ok(Running {
1470            call: call.local_id(),
1471            stop,
1472            ended,
1473            bell,
1474            to_pipe,
1475            thread: Some(thread),
1476            codec,
1477            live,
1478            cap,
1479            layers,
1480            size,
1481            device,
1482            temporal: temporal_layers,
1483            held,
1484        })
1485    }
1486
1487    /// A device switch: the old camera closes first (the publication and the lease kept, the
1488    /// frames held), then the new camera's frames feed the same encoders (resized for its
1489    /// aspect, a keyframe first); a different layer set publishes again with it. The new camera
1490    /// not opening: the old one again and the error; that failing too: the camera ends with
1491    /// `camera_lost`.
1492    async fn switch(
1493        &self,
1494        call: &Call,
1495        slot: &mut Option<Running>,
1496        policy: &sew_proto::voice::MediaPolicy,
1497        req: CameraRequest,
1498    ) -> Result<CameraState, VideoError> {
1499        let Some(r) = slot.as_mut() else {
1500            return Err(VideoError::NotPublished);
1501        };
1502        let bell = Arc::clone(&r.bell);
1503        let began = std::time::Instant::now();
1504        // One camera at a time (iOS has no multi-cam session; opening the second camera
1505        // interrupts the first): the old source closes before the new one opens.
1506        release_source(r).await?;
1507        let (src, size) = match self.open(req.device.clone(), policy, &bell).await {
1508            Ok(v) => v,
1509            Err(e) => {
1510                tracing::warn!(target: "sew_call_client", code = e.code(), device = ?req.device, "the new camera did not open: back to the old one");
1511                match self.open(r.device.clone(), policy, &bell).await {
1512                    Ok((src, size)) => {
1513                        let plan = VideoBridge::plan(
1514                            policy,
1515                            VideoSource::Camera,
1516                            r.codec,
1517                            &r.cap,
1518                            r.temporal,
1519                            size,
1520                        );
1521                        let plan = if same_rids(&plan, &r.layers) {
1522                            plan
1523                        } else {
1524                            r.layers.clone()
1525                        };
1526                        let facing = self.capture.camera_facing(r.device.as_deref());
1527                        if r.to_pipe
1528                            .send(ToPipe::Source(src, plan.clone(), facing))
1529                            .is_err()
1530                        {
1531                            return Err(VideoError::Ended);
1532                        }
1533                        r.bell.ring();
1534                        r.layers = plan;
1535                        r.size = size;
1536                        tracing::info!(target: "sew_call_client", gap_ms = began.elapsed().as_millis() as u64, "the old camera is back");
1537                    }
1538                    Err(e2) => {
1539                        tracing::warn!(target: "sew_call_client", code = e2.code(), "the old camera did not open again: camera_lost");
1540                        if let Some(r) = slot.take() {
1541                            stop_running(r).await;
1542                        }
1543                        let reason = CaptureEnd::DeviceLost.reason(CaptureKind::Camera);
1544                        let _ = self.taps.events.send(SourceNote {
1545                            source: VideoSource::Camera,
1546                            event: CaptureEvent::Ended(CaptureEnd::DeviceLost),
1547                        });
1548                        let _ = call
1549                            .unpublish_video_because(VideoSource::Camera, true, reason)
1550                            .await;
1551                    }
1552                }
1553                return Err(e);
1554            }
1555        };
1556        let plan = VideoBridge::plan(
1557            policy,
1558            VideoSource::Camera,
1559            r.codec,
1560            &r.cap,
1561            req.temporal_layers,
1562            size,
1563        );
1564        if same_rids(&plan, &r.layers) {
1565            let facing = self.capture.camera_facing(req.device.as_deref());
1566            if r.to_pipe
1567                .send(ToPipe::Source(src, plan.clone(), facing))
1568                .is_err()
1569            {
1570                return Err(VideoError::Ended);
1571            }
1572            r.bell.ring();
1573            r.layers = plan;
1574            r.size = size;
1575            r.device = req.device.clone();
1576            tracing::info!(target: "sew_call_client", device = ?req.device, gap_ms = began.elapsed().as_millis() as u64, "the camera switched");
1577            return Ok(r.state());
1578        }
1579        if let Some(r) = slot.take() {
1580            stop_running(r).await;
1581        }
1582        tracing::info!(target: "sew_call_client", "the camera switches with a new layer set: published again");
1583        call.unpublish_video_because(VideoSource::Camera, false, CAMERA_SWITCH)
1584            .await?;
1585        let r = self
1586            .start_from(
1587                call,
1588                policy,
1589                VideoSource::Camera,
1590                Feed {
1591                    src,
1592                    size,
1593                    facing: self.capture.camera_facing(req.device.as_deref()),
1594                },
1595                req.temporal_layers,
1596                req.device.clone(),
1597                bell,
1598            )
1599            .await?;
1600        let state = r.state();
1601        *slot = Some(r);
1602        Ok(state)
1603    }
1604
1605    /// Pauses (`true`) or resumes the camera's pipeline, keeping its publication and lease (a
1606    /// phone app in the background): no frame is captured (the source is paused) or encoded
1607    /// while paused, and on the return every encoder is asked for a keyframe before the first
1608    /// frame is encoded. [`crate::Call::set_video_muted`] tells subscribers. `false`: no camera
1609    /// runs.
1610    pub async fn pause_camera(&self, paused: bool) -> bool {
1611        let slot = self.camera.lock().await;
1612        let Some(r) = slot.as_ref() else {
1613            return false;
1614        };
1615        if r.to_pipe.send(ToPipe::Pause(paused)).is_err() {
1616            return false;
1617        }
1618        r.bell.ring();
1619        true
1620    }
1621
1622    /// Opens the camera again (the same device; the publication and the lease kept, a
1623    /// keyframe first) when the app is in front yet the camera is still paused by a background
1624    /// pause that the OS never ended and no frame came since. `false`: nothing to do (no
1625    /// camera, not held), or it did not open again; then the camera stays paused as it was
1626    /// (published, the lease kept, no frames) and a later call may try again. It never turns
1627    /// the camera off.
1628    pub async fn reopen_held_camera(&self, call: &Call) -> bool {
1629        let mut slot = self.camera.lock().await;
1630        let Some(r) = slot
1631            .as_mut()
1632            .filter(|r| r.alive() && r.call == call.local_id() && r.held.load(Ordering::SeqCst))
1633        else {
1634            return false;
1635        };
1636        let Some(policy) = call.media_policy() else {
1637            return false;
1638        };
1639        tracing::info!(target: "sew_call_client", "the camera opens again: still paused by the background after the app came back");
1640        let began = std::time::Instant::now();
1641        // One camera at a time (as in a switch): the old source closes first.
1642        if release_source(r).await.is_err() {
1643            return false;
1644        }
1645        let bell = Arc::clone(&r.bell);
1646        let (src, size) = match self.open(r.device.clone(), &policy, &bell).await {
1647            Ok(v) => v,
1648            Err(e) => {
1649                // Still paused (the pipeline holds without a source, as it did without frames).
1650                tracing::info!(target: "sew_call_client", code = e.code(), "the camera did not open again: it stays paused");
1651                r.held.store(true, Ordering::SeqCst);
1652                return false;
1653            }
1654        };
1655        let plan = VideoBridge::plan(
1656            &policy,
1657            VideoSource::Camera,
1658            r.codec,
1659            &r.cap,
1660            r.temporal,
1661            size,
1662        );
1663        let plan = if same_rids(&plan, &r.layers) {
1664            plan
1665        } else {
1666            r.layers.clone()
1667        };
1668        let facing = self.capture.camera_facing(r.device.as_deref());
1669        if r.to_pipe
1670            .send(ToPipe::Source(src, plan.clone(), facing))
1671            .is_err()
1672        {
1673            return false;
1674        }
1675        r.bell.ring();
1676        r.layers = plan;
1677        r.size = size;
1678        tracing::info!(target: "sew_call_client", gap_ms = began.elapsed().as_millis() as u64, "the camera is back after the background");
1679        true
1680    }
1681
1682    /// Stops the pipelines of one call (its [`Call::local_id`]) without touching the call (it
1683    /// ended): a later call's keep running. Each stop waits a short while at most; a pipeline
1684    /// whose source closes slowly finishes on its own.
1685    pub async fn close_call(&self, call: u64) {
1686        let mut all: Vec<Running> = {
1687            let mut feeds = self.feeds.lock().await;
1688            let kinds: Vec<VideoSource> = feeds
1689                .iter()
1690                .filter(|(_, r)| r.call == call)
1691                .map(|(k, _)| *k)
1692                .collect();
1693            kinds.iter().filter_map(|k| feeds.remove(k)).collect()
1694        };
1695        {
1696            let mut cam = self.camera.lock().await;
1697            if cam.as_ref().is_some_and(|r| r.call == call) {
1698                all.extend(cam.take());
1699            }
1700        }
1701        for r in all {
1702            stop_running(r).await;
1703        }
1704    }
1705
1706    /// Stops every pipeline without touching the call (the call ended).
1707    pub async fn close(&self) {
1708        let mut all: Vec<Running> = self.feeds.lock().await.drain().map(|(_, r)| r).collect();
1709        all.extend(self.camera.lock().await.take());
1710        for r in all {
1711            stop_running(r).await;
1712        }
1713    }
1714}
1715
1716/// The pipeline of one publication (its own thread).
1717struct Pipe {
1718    backend: Arc<dyn VideoBackend>,
1719    kind: VideoSource,
1720    codec: VideoCodec,
1721    content: ContentHint,
1722    src: Box<dyn FrameSource>,
1723    /// Which way the source's camera faces (`Unknown`: a screen, a host's source).
1724    facing: Facing,
1725    /// The camera's before the last switch, for frames captured before `facing_since_us`.
1726    was_facing: Facing,
1727    facing_since_us: u64,
1728    /// When the last [`ToPipe::Release`] dropped the source (the backend clock).
1729    released_us: Option<u64>,
1730    encs: BTreeMap<String, Enc>,
1731    /// The layer whose output is the self-view.
1732    self_rid: Option<String>,
1733    publication: VideoPublication,
1734    ctl: VideoCtl,
1735    taps: Taps,
1736    stop: Arc<AtomicBool>,
1737    ended: Arc<AtomicBool>,
1738    /// The self-view needs a keyframe.
1739    self_key: Arc<AtomicBool>,
1740    bell: Arc<Bell>,
1741    from_bridge: std::sync::mpsc::Receiver<ToPipe>,
1742    /// The source is paused by the pipeline (nothing wants a frame, or the app in the
1743    /// background).
1744    paused: bool,
1745    /// The source is paused by the OS (a hidden window, another app took the camera).
1746    hidden: bool,
1747    /// Why the OS paused the source (while `hidden`).
1748    hidden_why: Option<CapturePause>,
1749    /// Frames captured from this moment on (the backend clock) show that a background pause
1750    /// is over although the source never said so: the last background pause seen, or the
1751    /// app's return, whichever came later.
1752    fresh_since_us: u64,
1753    /// The app is in front, yet the source is still paused by a background pause and no frame
1754    /// came since (shared with [`Running`]).
1755    held: Arc<AtomicBool>,
1756    /// The app is in the background ([`ToPipe::Pause`]).
1757    scene_paused: bool,
1758    /// The pipeline asked the engine to end the publication (all its encoders lost).
1759    end_asked: bool,
1760    /// The call it publishes for ([`Call::local_id`]).
1761    call: u64,
1762    /// The backup's encoders (a publication with a backup codec).
1763    backup: Option<BackupPipe>,
1764    /// The VP8 encoder entry, for a fall back to VP8 alone.
1765    vp8: Option<CodecCapability>,
1766    /// The VP8 temporal layers the host asked for.
1767    temporal: Option<u8>,
1768    /// The codec published now (shared with [`Running`]).
1769    live: Arc<Mutex<VideoCodec>>,
1770    /// A phone: the backup follows the thermal steps.
1771    phone: bool,
1772    /// The backend's machine-wide events (thermal pressure).
1773    machine: kessel_video::EventRx,
1774    /// The last thermal level seen.
1775    thermal: kessel_video::ThermalLevel,
1776    /// Frames converted for the backup (once per captured frame while it runs).
1777    backup_converts: Arc<std::sync::atomic::AtomicU64>,
1778}
1779
1780/// The backup's side of a pipeline: its layers, and its encoders while it runs.
1781struct BackupPipe {
1782    codec: VideoCodec,
1783    /// Every layer the backup may run (the engine's `BackupStart` names the ones it opens).
1784    ladder: Vec<LayerSpec>,
1785    encs: BTreeMap<String, Enc>,
1786    /// Between `BackupStart` and `BackupStop`.
1787    on: bool,
1788    /// Layers whose encoder didn't open, tried again at `retry_at`.
1789    pending: Vec<LayerSpec>,
1790    retry_at: Option<std::time::Instant>,
1791    /// The retry is spent: the next failure publishes VP8 alone.
1792    retried: bool,
1793    /// The engine's last `BackupRates` (an encoder that opens later runs at its rate).
1794    last_rates: Vec<LayerRate>,
1795}
1796
1797impl BackupPipe {
1798    fn new(codec: VideoCodec, ladder: Vec<LayerSpec>) -> BackupPipe {
1799        BackupPipe {
1800            codec,
1801            ladder,
1802            encs: BTreeMap::new(),
1803            on: false,
1804            pending: Vec::new(),
1805            retry_at: None,
1806            retried: false,
1807            last_rates: Vec::new(),
1808        }
1809    }
1810
1811    fn any_active(&self) -> bool {
1812        self.on && self.encs.values().any(|e| e.active)
1813    }
1814
1815    /// Closes every backup encoder (on this pipeline's thread).
1816    fn close(&mut self) {
1817        self.on = false;
1818        self.encs.clear();
1819        self.pending.clear();
1820        self.retry_at = None;
1821        self.last_rates.clear();
1822    }
1823}
1824
1825impl Pipe {
1826    fn run(&mut self) {
1827        self.pump();
1828        self.ended.store(true, Ordering::SeqCst);
1829        self.to_self_view(SelfViewItem::Ended { source: self.kind });
1830        self.tap_feed(CameraFeed::Off);
1831    }
1832
1833    fn pump(&mut self) {
1834        let sender = self.publication.sender();
1835        while !self.stop.load(Ordering::SeqCst) {
1836            if !self.controls() {
1837                return;
1838            }
1839            while let Ok(m) = self.from_bridge.try_recv() {
1840                match m {
1841                    ToPipe::Source(src, sizes, facing) => {
1842                        self.src = src;
1843                        // Frames captured from the release on (else from now) are the new
1844                        // camera's.
1845                        self.was_facing = self.facing;
1846                        self.facing = facing;
1847                        self.facing_since_us = self
1848                            .released_us
1849                            .take()
1850                            .unwrap_or_else(|| self.backend.now_us());
1851                        self.hidden_why = None;
1852                        if std::mem::take(&mut self.hidden) {
1853                            // The old source's pause ended with it: this one runs.
1854                            let _ = self.taps.events.send(SourceNote {
1855                                source: self.kind,
1856                                event: CaptureEvent::Resumed,
1857                            });
1858                        }
1859                        self.src.set_paused(self.paused);
1860                        // The new camera's first frame is a keyframe on every layer: owed to
1861                        // that frame, not asked of the encoder now (its pending input may
1862                        // still be the old camera's last frame).
1863                        for e in self.encs.values_mut() {
1864                            e.key_owed = true;
1865                        }
1866                        for l in sizes {
1867                            if let Some(e) = self.encs.get_mut(&l.rid)
1868                                && (e.spec.width, e.spec.height) != (l.width, l.height)
1869                            {
1870                                let _ = e.enc.set_size(l.width, l.height);
1871                                e.spec.width = l.width;
1872                                e.spec.height = l.height;
1873                            }
1874                            if let Some(b) = self.backup.as_mut() {
1875                                // The backup's layers follow the camera's aspect too.
1876                                if let Some(r) = b.ladder.iter_mut().find(|r| r.rid == l.rid) {
1877                                    r.width = l.width;
1878                                    r.height = l.height;
1879                                }
1880                                if let Some(e) = b.encs.get_mut(&l.rid) {
1881                                    e.key_owed = true;
1882                                    if (e.spec.width, e.spec.height) != (l.width, l.height) {
1883                                        let _ = e.enc.set_size(l.width, l.height);
1884                                        e.spec.width = l.width;
1885                                        e.spec.height = l.height;
1886                                    }
1887                                }
1888                            }
1889                        }
1890                    }
1891                    ToPipe::Release(done) => {
1892                        self.src = Box::new(Released);
1893                        self.released_us = Some(self.backend.now_us());
1894                        let _ = done.send(());
1895                    }
1896                    ToPipe::Pause(p) => self.scene(p),
1897                }
1898            }
1899            if !self.source_events() {
1900                return;
1901            }
1902            self.backup_retry();
1903            if self.end_asked {
1904                return;
1905            }
1906            self.machine_events();
1907            let self_view = self.self_view_open();
1908            self.repause(self_view || self.tapped());
1909            if self.self_key.swap(false, Ordering::AcqRel)
1910                && let Some(e) = self.self_rid.as_ref().and_then(|r| self.encs.get_mut(r))
1911            {
1912                e.enc.request_keyframe();
1913            }
1914            if self.background_held() {
1915                // The OS paused the source for the background and never said the pause is
1916                // over: a frame captured since then (or since the app came back) says so.
1917                if let Some(frame) = self.latest()
1918                    && frame.capture_us >= self.fresh_since_us
1919                {
1920                    tracing::info!(target: "sew_call_client", source = ?self.kind, "the video source runs again after a background pause it never ended");
1921                    self.resume_hidden();
1922                    let _ = self.taps.events.send(SourceNote {
1923                        source: self.kind,
1924                        event: CaptureEvent::Resumed,
1925                    });
1926                    self.to_taps(&frame);
1927                    self.submit(&frame, self_view);
1928                }
1929            } else if !self.hidden
1930                && !self.scene_paused
1931                && let Some(frame) = self.latest()
1932            {
1933                self.to_taps(&frame);
1934                self.submit(&frame, self_view);
1935            }
1936            self.held.store(self.background_held(), Ordering::SeqCst);
1937            self.drain(&sender);
1938            self.bell.wait(Duration::from_millis(20));
1939        }
1940    }
1941
1942    /// The source's events; `false` once it ended (unpublished with its reason).
1943    fn source_events(&mut self) -> bool {
1944        while let Some(ev) = self.src.try_event() {
1945            let Some(ev) = map_event(ev) else { continue };
1946            let mut over = false;
1947            match &ev {
1948                CaptureEvent::Paused(why) => {
1949                    tracing::info!(target: "sew_call_client", source = ?self.kind, ?why, "the video source paused");
1950                    self.tap_feed(CameraFeed::Paused);
1951                    self.hidden = true;
1952                    self.hidden_why = Some(*why);
1953                    if *why == CapturePause::Background {
1954                        // Frames already queued were captured before it.
1955                        self.fresh_since_us = self.fresh_since_us.max(self.backend.now_us());
1956                    }
1957                }
1958                CaptureEvent::Resumed => {
1959                    // A resume after the frames already ended the pause needs no keyframe.
1960                    if self.hidden {
1961                        self.resume_hidden();
1962                    }
1963                }
1964                CaptureEvent::Ended(end) => {
1965                    let reason = end.reason(capture_kind(self.kind));
1966                    tracing::info!(target: "sew_call_client", source = ?self.kind, reason, "the video source ended");
1967                    self.ctl.end(self.kind, reason);
1968                    over = true;
1969                }
1970                _ => {}
1971            }
1972            let _ = self.taps.events.send(SourceNote {
1973                source: self.kind,
1974                event: ev,
1975            });
1976            if over {
1977                return false;
1978            }
1979        }
1980        true
1981    }
1982
1983    fn self_view_open(&self) -> bool {
1984        lock(&self.taps.self_view)
1985            .as_ref()
1986            .is_some_and(|tx| !tx.is_closed())
1987    }
1988
1989    /// A camera publication with a camera tap open (its source keeps capturing).
1990    fn tapped(&self) -> bool {
1991        self.kind == VideoSource::Camera && self.taps.camera.any()
1992    }
1993
1994    /// A camera publication's captured frame to the camera taps, with the facing of the camera
1995    /// that captured it. Never blocks.
1996    fn to_taps(&self, frame: &kessel_video::VideoFrame) {
1997        if self.kind != VideoSource::Camera {
1998            return;
1999        }
2000        let facing = if frame.capture_us >= self.facing_since_us {
2001            self.facing
2002        } else {
2003            self.was_facing
2004        };
2005        self.taps.camera.frame(frame, facing);
2006    }
2007
2008    /// A camera publication's feed to the camera taps.
2009    fn tap_feed(&self, feed: CameraFeed) {
2010        if self.kind == VideoSource::Camera {
2011            self.taps.camera.feed(feed);
2012        }
2013    }
2014
2015    fn to_self_view(&self, item: SelfViewItem) {
2016        let full = match lock(&self.taps.self_view).as_ref() {
2017            Some(tx) => matches!(tx.try_send(item), Err(mpsc::error::TrySendError::Full(_))),
2018            None => false,
2019        };
2020        if full {
2021            // A dropped frame breaks the self-view's decoder: the next one is a keyframe.
2022            self.self_key.store(true, Ordering::Release);
2023        }
2024    }
2025
2026    /// Nobody wants any layer and no self-view is open, or the app is in the background: the
2027    /// source pauses.
2028    fn repause(&mut self, self_view: bool) {
2029        let want = !self.scene_paused
2030            && (self_view
2031                || self.encs.values().any(|e| e.active)
2032                || self.backup.as_ref().is_some_and(BackupPipe::any_active));
2033        if want == self.paused {
2034            self.paused = !want;
2035            self.src.set_paused(self.paused);
2036        }
2037    }
2038
2039    /// The engine's controls; `false` once the publication ended.
2040    fn controls(&mut self) -> bool {
2041        while let Some(c) = self.publication.try_control() {
2042            match c {
2043                VideoControl::Keyframe { rid } => {
2044                    if let Some(e) = self.encs.get_mut(&rid) {
2045                        e.enc.request_keyframe();
2046                    }
2047                }
2048                VideoControl::Rates(rates) => {
2049                    for r in rates {
2050                        if let Some(e) = self.encs.get_mut(&r.rid) {
2051                            e.active = r.active;
2052                            if r.active {
2053                                let _ = e
2054                                    .enc
2055                                    .set_rates(Rates::new(r.bitrate_bps.max(10_000), r.fps.max(1)));
2056                            }
2057                        }
2058                    }
2059                }
2060                VideoControl::Republish(layers) => self.relayer(layers),
2061                VideoControl::Ended { reason } => {
2062                    tracing::info!(target: "sew_call_client", source = ?self.kind, %reason, "the video publication ended");
2063                    return false;
2064                }
2065                VideoControl::BackupStart(layers) => self.backup_start(layers),
2066                VideoControl::BackupRates(rates) => self.backup_rates(rates),
2067                VideoControl::BackupKeyframe { rid } => {
2068                    if let Some(e) = self.backup.as_mut().and_then(|b| b.encs.get_mut(&rid)) {
2069                        e.enc.request_keyframe();
2070                    }
2071                }
2072                VideoControl::BackupStop => {
2073                    if let Some(b) = self.backup.as_mut() {
2074                        tracing::info!(target: "sew_call_client", source = ?self.kind, encoders = b.encs.len(), "the backup stops: its encoders close");
2075                        b.close();
2076                    }
2077                }
2078            }
2079            if self.end_asked {
2080                return true;
2081            }
2082        }
2083        true
2084    }
2085
2086    /// The app is in front, yet the source is still paused by the OS for the background.
2087    fn background_held(&self) -> bool {
2088        self.hidden && !self.scene_paused && self.hidden_why == Some(CapturePause::Background)
2089    }
2090
2091    /// The OS's pause is over: every encoder makes a keyframe first.
2092    fn resume_hidden(&mut self) {
2093        self.hidden = false;
2094        self.hidden_why = None;
2095        for e in self.encs.values_mut() {
2096            e.enc.request_keyframe();
2097        }
2098        for e in self.backup.iter_mut().flat_map(|b| b.encs.values_mut()) {
2099            e.enc.request_keyframe();
2100        }
2101    }
2102
2103    /// The app's scene: paused in the background; back in front, every encoder makes a
2104    /// keyframe before the first frame it encodes (frames captured before the pause are
2105    /// dropped).
2106    fn scene(&mut self, paused: bool) {
2107        if paused == self.scene_paused {
2108            return;
2109        }
2110        self.scene_paused = paused;
2111        if paused {
2112            tracing::info!(target: "sew_call_client", "the camera pauses (background)");
2113            self.tap_feed(CameraFeed::Paused);
2114        } else {
2115            tracing::info!(target: "sew_call_client", "the camera resumes with a keyframe");
2116            self.fresh_since_us = self.fresh_since_us.max(self.backend.now_us());
2117            while self.src.try_recv().is_some() {}
2118            for e in self.encs.values_mut() {
2119                e.enc.request_keyframe();
2120            }
2121            for e in self.backup.iter_mut().flat_map(|b| b.encs.values_mut()) {
2122                e.enc.request_keyframe();
2123            }
2124        }
2125        let self_view = self.self_view_open();
2126        self.repause(self_view || self.tapped());
2127    }
2128
2129    /// A republish's layers: existing encoders resized, new ones opened, gone ones closed.
2130    fn relayer(&mut self, layers: Vec<LayerSpec>) {
2131        self.self_rid = self_view_rid(self.kind, &layers);
2132        if let Some(b) = self.backup.as_mut() {
2133            // The engine stopped the backup for the republish; its layers follow the new set.
2134            b.close();
2135            b.ladder = backup_layers_for(&layers, &b.ladder);
2136        }
2137        let wake = self.bell.wake();
2138        let mut next = BTreeMap::new();
2139        for l in layers {
2140            match self.encs.remove(&l.rid) {
2141                Some(mut e) => {
2142                    if (e.spec.width, e.spec.height) != (l.width, l.height) {
2143                        let _ = e.enc.set_size(l.width, l.height);
2144                    }
2145                    let _ = e.enc.set_rates(Rates::new(
2146                        l.max_kbps.saturating_mul(1000).max(10_000),
2147                        l.fps.max(1),
2148                    ));
2149                    e.spec = l.clone();
2150                    next.insert(l.rid.clone(), e);
2151                }
2152                None => match open_encoder(&self.backend, self.codec, &l, self.content, &wake) {
2153                    Ok(enc) => {
2154                        next.insert(
2155                            l.rid.clone(),
2156                            Enc {
2157                                spec: l,
2158                                enc,
2159                                active: true,
2160                                key_owed: false,
2161                            },
2162                        );
2163                    }
2164                    Err(e) => {
2165                        tracing::info!(target: "sew_call_client", rid = %l.rid, error = %e, "a republished layer's encoder did not open");
2166                    }
2167                },
2168            }
2169        }
2170        self.encs = next;
2171    }
2172
2173    /// The backend's machine-wide events: on a phone with a backup, a thermal level change
2174    /// caps the backup ([`thermal_backup_caps`]) in the engine.
2175    fn machine_events(&mut self) {
2176        while let Some(ev) = self.machine.try_recv() {
2177            let kessel_video::BackendEvent::Thermal(level) = ev else {
2178                continue;
2179            };
2180            if !self.phone || self.backup.is_none() || level == self.thermal {
2181                continue;
2182            }
2183            self.thermal = level;
2184            let caps = thermal_backup_caps(level);
2185            tracing::info!(target: "sew_call_client", ?level, max_layers = ?caps.max_layers, max_fps = ?caps.max_fps, "thermal pressure: the backup's caps");
2186            self.ctl.backup_caps(caps);
2187        }
2188    }
2189
2190    /// `BackupStart`: the backup runs; its encoders open for `layers` (each a keyframe first).
2191    fn backup_start(&mut self, layers: Vec<LayerSpec>) {
2192        let Some(b) = self.backup.as_mut() else {
2193            return;
2194        };
2195        b.on = true;
2196        for l in &layers {
2197            match b.ladder.iter_mut().find(|r| r.rid == l.rid) {
2198                Some(r) => *r = l.clone(),
2199                None => b.ladder.push(l.clone()),
2200            }
2201        }
2202        tracing::info!(target: "sew_call_client", source = ?self.kind, layers = layers.len(), "the backup starts: its encoders open");
2203        self.backup_open(layers);
2204    }
2205
2206    /// `BackupRates`: which backup layers run; an active one without an encoder opens.
2207    fn backup_rates(&mut self, rates: Vec<LayerRate>) {
2208        let Some(b) = self.backup.as_mut() else {
2209            return;
2210        };
2211        if !b.on {
2212            return;
2213        }
2214        let open: Vec<LayerSpec> = rates
2215            .iter()
2216            .filter(|r| r.active && !b.encs.contains_key(&r.rid))
2217            .filter(|r| !b.pending.iter().any(|p| p.rid == r.rid))
2218            .filter_map(|r| b.ladder.iter().find(|l| l.rid == r.rid).cloned())
2219            .collect();
2220        if !open.is_empty() {
2221            self.backup_open(open);
2222        }
2223        let Some(b) = self.backup.as_mut() else {
2224            return;
2225        };
2226        b.last_rates.clone_from(&rates);
2227        for r in rates {
2228            if let Some(e) = b.encs.get_mut(&r.rid) {
2229                e.active = r.active;
2230                if r.active {
2231                    let _ = e
2232                        .enc
2233                        .set_rates(Rates::new(r.bitrate_bps.max(10_000), r.fps.max(1)));
2234                }
2235            }
2236        }
2237    }
2238
2239    /// Opens the backup's encoders for `layers` (each starts at a keyframe, inactive until its
2240    /// rate comes). One that doesn't open is tried again once after [`BACKUP_RETRY`]; failing
2241    /// then, the publication goes to VP8 alone ([`Pipe::fall_back_to_vp8`]).
2242    fn backup_open(&mut self, layers: Vec<LayerSpec>) {
2243        let wake = self.bell.wake();
2244        let Some(b) = self.backup.as_mut() else {
2245            return;
2246        };
2247        let mut failed = Vec::new();
2248        for l in layers {
2249            if b.encs.contains_key(&l.rid) {
2250                continue;
2251            }
2252            match open_encoder(&self.backend, b.codec, &l, self.content, &wake) {
2253                Ok(mut enc) => {
2254                    enc.request_keyframe();
2255                    // Its rate if one came already (else inactive until it does).
2256                    let r = b.last_rates.iter().find(|r| r.rid == l.rid && r.active);
2257                    if let Some(r) = r {
2258                        let _ = enc.set_rates(Rates::new(r.bitrate_bps.max(10_000), r.fps.max(1)));
2259                    }
2260                    b.encs.insert(
2261                        l.rid.clone(),
2262                        Enc {
2263                            spec: l,
2264                            enc,
2265                            active: r.is_some(),
2266                            key_owed: false,
2267                        },
2268                    );
2269                }
2270                Err(e) => {
2271                    tracing::info!(target: "sew_call_client", rid = %l.rid, error = %e, "a backup encoder did not open");
2272                    failed.push(l);
2273                }
2274            }
2275        }
2276        if failed.is_empty() {
2277            if b.pending.is_empty() {
2278                b.retried = false;
2279            }
2280            return;
2281        }
2282        if b.retried {
2283            self.fall_back_to_vp8("the backup's encoder did not open again");
2284            return;
2285        }
2286        b.pending.extend(failed);
2287        b.retry_at = Some(std::time::Instant::now() + BACKUP_RETRY);
2288    }
2289
2290    /// The backup's one retry, when due.
2291    fn backup_retry(&mut self) {
2292        let Some(b) = self.backup.as_mut() else {
2293            return;
2294        };
2295        if b.retry_at.is_none_or(|t| std::time::Instant::now() < t) {
2296            return;
2297        }
2298        b.retry_at = None;
2299        b.retried = true;
2300        let pending = std::mem::take(&mut b.pending);
2301        if b.on {
2302            tracing::info!(target: "sew_call_client", layers = pending.len(), "the backup's encoders: the one retry");
2303            self.backup_open(pending);
2304        }
2305    }
2306
2307    /// The publication in VP8 alone (the backup can't run, or the hardware H.264 encoder is
2308    /// gone): the backup closes, VP8 encoders open for the primary's layers, and the engine
2309    /// publishes the track again in VP8 (the same lease). No VP8 encoder opens: the
2310    /// publication ends with `encoder_lost`.
2311    fn fall_back_to_vp8(&mut self, why: &str) {
2312        if let Some(mut b) = self.backup.take() {
2313            b.close();
2314        }
2315        let Some(cap) = self.vp8.clone() else {
2316            tracing::info!(target: "sew_call_client", source = ?self.kind, why, "no VP8 encoder to fall back to: unpublishing");
2317            self.end_asked = true;
2318            self.ctl.end(self.kind, ENCODER_LOST);
2319            return;
2320        };
2321        let tl = vp8_temporal(&cap, self.temporal);
2322        let mut plan: Vec<LayerSpec> = self
2323            .encs
2324            .values()
2325            .map(|e| {
2326                let mut l = e.spec.clone();
2327                l.temporal_layers = tl;
2328                l
2329            })
2330            .collect();
2331        plan.sort_by_key(|l| (l.width.min(l.height), l.width.max(l.height)));
2332        // The old encoders close first (a phone's hardware session among them).
2333        self.encs.clear();
2334        let wake = self.bell.wake();
2335        let encs = open_encoders(
2336            &self.backend,
2337            VideoCodec::Vp8,
2338            &cap,
2339            plan,
2340            self.content,
2341            &wake,
2342        );
2343        if encs.is_empty() {
2344            tracing::info!(target: "sew_call_client", source = ?self.kind, why, "no VP8 encoder opened: unpublishing");
2345            self.end_asked = true;
2346            self.ctl.end(self.kind, ENCODER_LOST);
2347            return;
2348        }
2349        let layers: Vec<LayerSpec> = encs.iter().map(|e| e.spec.clone()).collect();
2350        tracing::info!(target: "sew_call_client", source = ?self.kind, why, layers = layers.len(), "published again in VP8 alone");
2351        self.codec = VideoCodec::Vp8;
2352        *lock(&self.live) = VideoCodec::Vp8;
2353        self.self_rid = self_view_rid(self.kind, &layers);
2354        self.encs = encs.into_iter().map(|e| (e.spec.rid.clone(), e)).collect();
2355        for e in self.encs.values_mut() {
2356            e.enc.request_keyframe();
2357        }
2358        self.publication
2359            .republish_without_backup(VideoCodec::Vp8, layers);
2360    }
2361
2362    /// The newest captured frame (older ones are dropped).
2363    fn latest(&mut self) -> Option<kessel_video::VideoFrame> {
2364        let mut last = None;
2365        while let Some(f) = self.src.try_recv() {
2366            last = Some(f);
2367        }
2368        last
2369    }
2370
2371    /// To every active layer's encoder, and to the self-view layer's while a self-view is
2372    /// open.
2373    fn submit(&mut self, frame: &kessel_video::VideoFrame, self_view: bool) {
2374        let mut planes: Option<kessel_video::VideoFrame> = None;
2375        for (rid, e) in &mut self.encs {
2376            let for_self = self_view && self.self_rid.as_ref() == Some(rid);
2377            if !e.active && !for_self {
2378                continue;
2379            }
2380            match e.submit(frame) {
2381                Ok(()) => {}
2382                Err(KError::Unsupported(_)) if matches!(frame.buffer, FrameBuffer::Native(_)) => {
2383                    // A native buffer this encoder can't take: CPU planes instead.
2384                    if planes.is_none() {
2385                        planes = self
2386                            .backend
2387                            .convert(frame, frame.width, frame.height, PixelFormat::I420)
2388                            .ok();
2389                    }
2390                    if let Some(p) = &planes {
2391                        let _ = e.submit(p);
2392                    }
2393                }
2394                // Busy: this frame is dropped for that layer (counted by the encoder).
2395                Err(_) => {}
2396            }
2397        }
2398        self.submit_backup(frame);
2399    }
2400
2401    /// The backup's active encoders get the frame as CPU planes converted once, at the largest
2402    /// running backup layer's size (each encoder scales from it): a native buffer always, CPU
2403    /// planes when larger. Nothing is converted while the backup doesn't run.
2404    fn submit_backup(&mut self, frame: &kessel_video::VideoFrame) {
2405        let Some(b) = self.backup.as_mut().filter(|b| b.any_active()) else {
2406            return;
2407        };
2408        let area = |w: u32, h: u32| u64::from(w) * u64::from(h);
2409        let Some((tw, th)) = b
2410            .encs
2411            .values()
2412            .filter(|e| e.active)
2413            .map(|e| (e.spec.width, e.spec.height))
2414            .max_by_key(|(w, h)| area(*w, *h))
2415        else {
2416            return;
2417        };
2418        let native = matches!(frame.buffer, FrameBuffer::Native(_));
2419        let converted = if native || area(frame.width, frame.height) > area(tw, th) {
2420            match self.backend.convert(frame, tw, th, PixelFormat::I420) {
2421                Ok(f) => {
2422                    self.backup_converts.fetch_add(1, Ordering::Relaxed);
2423                    Some(f)
2424                }
2425                // A frame the backend can't convert: the backup skips it.
2426                Err(_) if native => return,
2427                Err(_) => None,
2428            }
2429        } else {
2430            None
2431        };
2432        let input = converted.as_ref().unwrap_or(frame);
2433        for e in b.encs.values_mut().filter(|e| e.active) {
2434            // Busy: this frame is dropped for that layer (counted by the encoder).
2435            let _ = e.submit(input);
2436        }
2437    }
2438
2439    /// The backup's encoded frames to the engine (in the backup's codec); a lost backup
2440    /// encoder opens again (its retry rules).
2441    fn drain_backup(&mut self, sender: &VideoSender) {
2442        let Some(b) = self.backup.as_mut() else {
2443            return;
2444        };
2445        let mut dead = Vec::new();
2446        for (rid, e) in &mut b.encs {
2447            while let Some(r) = e.enc.poll() {
2448                match r {
2449                    Ok(f) => {
2450                        let Some(codec) = our_codec(f.codec) else {
2451                            continue;
2452                        };
2453                        if !e.active || !b.on {
2454                            continue;
2455                        }
2456                        sender.push(
2457                            EncodedVideo::new(
2458                                rid,
2459                                codec,
2460                                f.data,
2461                                f.keyframe,
2462                                f.capture_us,
2463                                f.width,
2464                                f.height,
2465                            )
2466                            .with_layer(f.layer.temporal_id, f.layer.layer_sync),
2467                        );
2468                    }
2469                    Err(err) => {
2470                        tracing::info!(target: "sew_call_client", rid = %rid, error = %err, "a backup encoder session was lost; reopening");
2471                        dead.push(e.spec.clone());
2472                        break;
2473                    }
2474                }
2475            }
2476        }
2477        if dead.is_empty() {
2478            return;
2479        }
2480        for l in &dead {
2481            b.encs.remove(&l.rid);
2482        }
2483        self.backup_open(dead);
2484    }
2485
2486    fn drain(&mut self, sender: &VideoSender) {
2487        let mut dead = Vec::new();
2488        let mut local = Vec::new();
2489        for (rid, e) in &mut self.encs {
2490            let for_self = self.self_rid.as_ref() == Some(rid);
2491            while let Some(r) = e.enc.poll() {
2492                match r {
2493                    Ok(f) => {
2494                        let Some(codec) = our_codec(f.codec) else {
2495                            continue;
2496                        };
2497                        if for_self {
2498                            local.push(LocalFrame {
2499                                codec,
2500                                data: f.data.clone(),
2501                                keyframe: f.keyframe,
2502                                capture_us: f.capture_us,
2503                                facing: if f.capture_us >= self.facing_since_us {
2504                                    self.facing
2505                                } else {
2506                                    self.was_facing
2507                                },
2508                                width: f.width,
2509                                height: f.height,
2510                            });
2511                        }
2512                        if !e.active {
2513                            // Encoded for the self-view only: the engine doesn't want it.
2514                            continue;
2515                        }
2516                        sender.push(
2517                            EncodedVideo::new(
2518                                rid,
2519                                codec,
2520                                f.data,
2521                                f.keyframe,
2522                                f.capture_us,
2523                                f.width,
2524                                f.height,
2525                            )
2526                            .with_layer(f.layer.temporal_id, f.layer.layer_sync),
2527                        );
2528                    }
2529                    Err(err) => {
2530                        tracing::info!(target: "sew_call_client", rid = %rid, error = %err, "an encoder session was lost; reopening");
2531                        dead.push(rid.clone());
2532                        break;
2533                    }
2534                }
2535            }
2536        }
2537        for frame in local {
2538            self.to_self_view(SelfViewItem::Frame {
2539                source: self.kind,
2540                frame,
2541            });
2542        }
2543        let wake = self.bell.wake();
2544        let any_dead = !dead.is_empty();
2545        for rid in dead {
2546            let Some(e) = self.encs.get_mut(&rid) else {
2547                continue;
2548            };
2549            match open_encoder(&self.backend, self.codec, &e.spec, self.content, &wake) {
2550                Ok(mut enc) => {
2551                    enc.request_keyframe();
2552                    e.enc = enc;
2553                }
2554                Err(err) if self.codec == VideoCodec::H264 => {
2555                    // The hardware is gone (a GPU reset, the media engine taken): VP8 alone,
2556                    // and no H.264 again in this call.
2557                    tracing::info!(target: "sew_call_client", rid = %rid, error = %err, "the hardware H.264 encoder was lost and did not reopen");
2558                    *lock(&self.taps.h264_lost) = Some(self.call);
2559                    self.fall_back_to_vp8("the hardware H.264 encoder was lost");
2560                    return;
2561                }
2562                Err(err) => {
2563                    tracing::info!(target: "sew_call_client", rid = %rid, error = %err, "a lost encoder did not reopen: its layer stops");
2564                    self.encs.remove(&rid);
2565                }
2566            }
2567        }
2568        self.drain_backup(sender);
2569        if any_dead && self.encs.is_empty() && !self.end_asked {
2570            tracing::info!(target: "sew_call_client", source = ?self.kind, "no encoder left: unpublishing");
2571            self.end_asked = true;
2572            self.ctl.end(self.kind, ENCODER_LOST);
2573        }
2574    }
2575}
2576
2577#[cfg(test)]
2578mod tests {
2579    use super::*;
2580    use kessel_video::{CodecCapability, Implementation};
2581
2582    fn caps(codecs: &[kessel_video::VideoCodec]) -> Capabilities {
2583        let mut c = Capabilities::new("test", "test");
2584        for k in codecs {
2585            c.codecs.push(CodecCapability::new(
2586                *k,
2587                CodecDirection::Encode,
2588                Implementation::Software,
2589                "enc",
2590                1280,
2591                720,
2592                30,
2593            ));
2594        }
2595        c
2596    }
2597
2598    #[test]
2599    #[allow(deprecated)]
2600    fn vp8_first_then_h264_and_only_what_the_policy_lists() {
2601        use sew_proto::voice::VideoCodec as P;
2602        let both = caps(&[
2603            kessel_video::VideoCodec::H264,
2604            kessel_video::VideoCodec::Vp8,
2605        ]);
2606        let pick = |policy: &[P], c: &Capabilities| choose_codec(policy, c).map(|(c, _)| c);
2607        assert_eq!(pick(&[P::Vp8, P::H264], &both), Some(VideoCodec::Vp8));
2608        assert_eq!(pick(&[P::H264, P::Vp8], &both), Some(VideoCodec::Vp8));
2609        assert_eq!(pick(&[P::H264], &both), Some(VideoCodec::H264));
2610        let h264_only = caps(&[kessel_video::VideoCodec::H264]);
2611        assert_eq!(pick(&[P::Vp8, P::H264], &h264_only), Some(VideoCodec::H264));
2612        assert_eq!(pick(&[P::Vp8], &h264_only), None, "codec_unavailable");
2613        assert_eq!(pick(&[], &both), None);
2614    }
2615
2616    /// Capabilities of backend `backend` with encoders `(codec, implementation)`.
2617    fn caps_of(
2618        backend: &'static str,
2619        encoders: &[(kessel_video::VideoCodec, Implementation)],
2620    ) -> Capabilities {
2621        let mut c = Capabilities::new(backend, "test");
2622        for (k, i) in encoders {
2623            c.codecs.push(CodecCapability::new(
2624                *k,
2625                CodecDirection::Encode,
2626                *i,
2627                "enc",
2628                1920,
2629                1080,
2630                30,
2631            ));
2632        }
2633        c
2634    }
2635
2636    pub(super) fn media_policy(
2637        codecs: &[sew_proto::voice::VideoCodec],
2638        backup: bool,
2639    ) -> sew_proto::voice::MediaPolicy {
2640        let hint = sew_proto::voice::TrackHint {
2641            max_width: 1280,
2642            max_height: 720,
2643            max_fps: 30,
2644            layers: Vec::new(),
2645        };
2646        {
2647            let mut media_policy = sew_proto::voice::MediaPolicy::new(
2648                sew_proto::voice::MediaTier::Normal,
2649                hint.clone(),
2650                hint,
2651            );
2652            media_policy.video_enabled = true;
2653            media_policy.e2ee = "required".to_owned();
2654            media_policy.audio_codecs = vec!["opus".to_owned()];
2655            media_policy.codecs = codecs.to_vec();
2656            media_policy.backup_codec = backup;
2657            media_policy.vp9 = None;
2658            media_policy.dynacast = true;
2659            media_policy.adaptive_stream = true;
2660            media_policy.camera_allowed = true;
2661            media_policy.screen_allowed = true;
2662            media_policy.relay_only = false;
2663            media_policy
2664        }
2665    }
2666
2667    /// `(primary, backup, reason)` of a plan.
2668    fn shape(p: Option<CodecPlan>) -> Option<(VideoCodec, Option<VideoCodec>, &'static str)> {
2669        p.map(|p| (p.primary.codec, p.backup.map(|b| b.codec), p.reason))
2670    }
2671
2672    #[test]
2673    #[cfg(feature = "testing")]
2674    fn h264_with_a_vp8_backup_only_when_every_rule_holds() {
2675        use kessel_video::VideoCodec as K;
2676        use sew_proto::voice::VideoCodec as P;
2677        let hw = caps_of(
2678            "fixture",
2679            &[
2680                (K::Vp8, Implementation::Software),
2681                (K::H264, Implementation::Hardware),
2682            ],
2683        );
2684        let auto = CodecPreference::Automatic;
2685        let plan =
2686            |pol: &sew_proto::voice::MediaPolicy,
2687             c: &Capabilities,
2688             dec: bool,
2689             pref: CodecPreference,
2690             lost: bool| shape(choose_codecs_with(pol, c, dec, pref, lost));
2691        let both = media_policy(&[P::Vp8, P::H264], true);
2692        // Every rule holds, in either order of the policy's list.
2693        let want = Some((VideoCodec::H264, Some(VideoCodec::Vp8), "h264_detected"));
2694        assert_eq!(plan(&both, &hw, true, auto, false), want);
2695        let h264_first = media_policy(&[P::H264, P::Vp8], true);
2696        assert_eq!(plan(&h264_first, &hw, true, auto, false), want);
2697        // backup_codec off, dynacast off, or one codec listed: one codec, VP8 first.
2698        let vp8 = Some((VideoCodec::Vp8, None, "backup_off"));
2699        let off = media_policy(&[P::Vp8, P::H264], false);
2700        assert_eq!(plan(&off, &hw, true, auto, false), vp8);
2701        let mut no_dyn = both.clone();
2702        no_dyn.dynacast = false;
2703        assert_eq!(plan(&no_dyn, &hw, true, auto, false), vp8);
2704        assert_eq!(
2705            plan(&media_policy(&[P::Vp8], true), &hw, true, auto, false),
2706            vp8
2707        );
2708        // An H.264-only policy with usable H.264: one codec.
2709        let only = media_policy(&[P::H264], true);
2710        assert_eq!(
2711            plan(&only, &hw, true, auto, false),
2712            Some((VideoCodec::H264, None, "backup_off"))
2713        );
2714        // The device doesn't decode H.264 (one codec set per PC): VP8 only.
2715        assert_eq!(
2716            plan(&both, &hw, false, auto, false),
2717            Some((VideoCodec::Vp8, None, "no_h264_decode"))
2718        );
2719        assert_eq!(plan(&only, &hw, false, auto, false), None);
2720        // The hardware was lost earlier in the call: never again in it.
2721        assert_eq!(
2722            plan(&both, &hw, true, auto, true),
2723            Some((VideoCodec::Vp8, None, "h264_lost"))
2724        );
2725        // The preference: VP8 always honoured; H.264 only where detected.
2726        assert_eq!(
2727            plan(&both, &hw, true, CodecPreference::PreferVp8, false),
2728            Some((VideoCodec::Vp8, None, "preferred_vp8"))
2729        );
2730        assert_eq!(
2731            plan(&both, &hw, true, CodecPreference::PreferH264, false),
2732            Some((VideoCodec::H264, Some(VideoCodec::Vp8), "preferred_h264"))
2733        );
2734        let sw = caps_of(
2735            "fixture",
2736            &[
2737                (K::Vp8, Implementation::Software),
2738                (K::H264, Implementation::Software),
2739            ],
2740        );
2741        assert_eq!(
2742            plan(&both, &sw, true, CodecPreference::PreferH264, false),
2743            Some((VideoCodec::Vp8, None, "h264_not_detected"))
2744        );
2745        // No VP8 encoder: no backup can run, so no H.264 primary with one either.
2746        let h264_only = caps_of("fixture", &[(K::H264, Implementation::Hardware)]);
2747        assert_eq!(
2748            plan(&both, &h264_only, true, auto, false),
2749            Some((VideoCodec::H264, None, "h264_not_detected"))
2750        );
2751    }
2752
2753    #[test]
2754    fn a_software_h264_encoder_is_never_usable() {
2755        use kessel_video::VideoCodec as K;
2756        use sew_proto::voice::VideoCodec as P;
2757        // The OS's software encoder (macOS's software VideoToolbox entry, Microsoft's MFT,
2758        // Android's platform AVC) is never usable: VP8 only, and an H.264-only policy is
2759        // codec_unavailable (phase 1 took any H.264 encoder).
2760        for backend in ["fixture", "apple", "android", "windows", "linux"] {
2761            let sw = caps_of(
2762                backend,
2763                &[
2764                    (K::Vp8, Implementation::Software),
2765                    (K::H264, Implementation::Software),
2766                ],
2767            );
2768            let both = media_policy(&[P::Vp8, P::H264], true);
2769            let p = choose_codecs_with(&both, &sw, true, CodecPreference::Automatic, false);
2770            assert_eq!(
2771                shape(p),
2772                Some((VideoCodec::Vp8, None, "h264_not_detected")),
2773                "{backend}"
2774            );
2775            let only = media_policy(&[P::H264], true);
2776            let p = choose_codecs_with(&only, &sw, true, CodecPreference::Automatic, false);
2777            assert_eq!(shape(p), None, "{backend}: codec_unavailable");
2778        }
2779        let vp8 = caps_of("apple", &[(K::Vp8, Implementation::Software)]);
2780        // (Its reason follows this platform's H.264 decode: `no_h264_decode` on Linux.)
2781        assert_eq!(
2782            shape(choose_codecs(&media_policy(&[P::Vp8, P::H264], true), &vp8))
2783                .map(|(c, b, _)| (c, b)),
2784            Some((VideoCodec::Vp8, None))
2785        );
2786        assert_eq!(
2787            choose_codecs(&media_policy(&[], true), &caps_of("apple", &[])),
2788            None
2789        );
2790    }
2791
2792    #[test]
2793    fn only_macos_and_ios_publish_os_h264() {
2794        use kessel_video::VideoCodec as K;
2795        use sew_proto::voice::VideoCodec as P;
2796        // A backend listing a hardware H.264 encoder: on Linux (never), Android and Windows
2797        // (not until their backends probe the hardware) the plan is VP8 only.
2798        let os_allowed = cfg!(any(target_os = "macos", target_os = "ios"));
2799        for backend in ["apple", "android", "windows", "linux"] {
2800            let hw = caps_of(
2801                backend,
2802                &[
2803                    (K::Vp8, Implementation::Software),
2804                    (K::H264, Implementation::Hardware),
2805                ],
2806            );
2807            let both = media_policy(&[P::Vp8, P::H264], true);
2808            let got = shape(choose_codecs_with(
2809                &both,
2810                &hw,
2811                true,
2812                CodecPreference::Automatic,
2813                false,
2814            ));
2815            if os_allowed {
2816                assert_eq!(got.map(|g| g.1), Some(Some(VideoCodec::Vp8)), "{backend}");
2817            } else {
2818                assert_eq!(
2819                    got,
2820                    Some((VideoCodec::Vp8, None, "h264_not_detected")),
2821                    "{backend}"
2822                );
2823            }
2824        }
2825        #[cfg(target_os = "linux")]
2826        {
2827            let hw = caps_of("linux", &[(K::H264, Implementation::Hardware)]);
2828            let only = media_policy(&[P::H264], true);
2829            for pref in [
2830                CodecPreference::Automatic,
2831                CodecPreference::PreferH264,
2832                CodecPreference::PreferVp8,
2833            ] {
2834                assert_eq!(
2835                    choose_codecs_with(&only, &hw, true, pref, false),
2836                    None,
2837                    "Linux never publishes H.264"
2838                );
2839            }
2840        }
2841    }
2842
2843    #[test]
2844    #[cfg(all(feature = "testing", sew_fixtures))]
2845    fn an_h264_session_opens_hardware_only_and_must_report_hardware() {
2846        use super::super::fixture::{FixtureBackend, FixtureH264, FixtureOptions};
2847        let dir = concat!(
2848            env!("CARGO_MANIFEST_DIR"),
2849            "/../sew-media-testclient/fixtures"
2850        );
2851        let wake: Wake = Arc::new(|| {});
2852        let l = LayerSpec::new("q", 320, 180, 150, 30);
2853        let cfg = encoder_config(VideoCodec::H264, &l, ContentHint::Camera);
2854        assert_eq!(cfg.implementation, ImplPreference::HardwareOnly);
2855        let cfg = encoder_config(VideoCodec::Vp8, &l, ContentHint::Camera);
2856        assert_eq!(cfg.implementation, ImplPreference::PreferHardware);
2857        let cap = CodecCapability::new(
2858            kessel_video::VideoCodec::H264,
2859            CodecDirection::Encode,
2860            Implementation::Hardware,
2861            "hw",
2862            1280,
2863            720,
2864            30,
2865        );
2866        let plan = vec![
2867            LayerSpec::new("q", 320, 180, 150, 30),
2868            LayerSpec::new("h", 640, 360, 500, 30),
2869        ];
2870        // Software (refuses hardware-only), a hardware open that fails, a session that says
2871        // software, a session that can't tell (an iOS before 17.4): nothing opens. Hardware:
2872        // every layer.
2873        for (mode, ok) in [
2874            (FixtureH264::Software, false),
2875            (FixtureH264::HardwareOpenFails, false),
2876            (FixtureH264::HardwareReportsSoftware, false),
2877            (FixtureH264::HardwareReportsUnknown, false),
2878            (FixtureH264::Hardware, true),
2879        ] {
2880            let fx = FixtureBackend::load_with(dir, FixtureOptions::new().with_h264(mode))
2881                .expect("the fixtures");
2882            let b: Arc<dyn VideoBackend> = fx.clone();
2883            let one = open_encoder(&b, VideoCodec::H264, &l, ContentHint::Camera, &wake);
2884            assert_eq!(one.is_ok(), ok, "{mode:?}");
2885            drop(one);
2886            let encs = open_encoders(
2887                &b,
2888                VideoCodec::H264,
2889                &cap,
2890                plan.clone(),
2891                ContentHint::Camera,
2892                &wake,
2893            );
2894            assert_eq!(encs.len(), if ok { 2 } else { 0 }, "{mode:?}");
2895            drop(encs);
2896            assert_eq!(
2897                fx.encoders_open(kessel_video::VideoCodec::H264),
2898                0,
2899                "{mode:?}"
2900            );
2901            // VP8 is kessel-vp8's software encoder, opened with the default preference.
2902            assert!(open_encoder(&b, VideoCodec::Vp8, &l, ContentHint::Camera, &wake).is_ok());
2903        }
2904    }
2905
2906    /// Apple's H.264 sessions: a low-latency session counts as hardware only when its name
2907    /// carries the hardware encoder's id; the software encoder's id never does.
2908    #[test]
2909    fn apple_h264_names() {
2910        for (name, hw) in [
2911            ("VideoToolbox H.264 (hardware)", true),
2912            (
2913                "VideoToolbox H.264 (hardware, low-latency rate control)",
2914                false,
2915            ),
2916            ("VideoToolbox H.264 (software)", false),
2917            (
2918                "VideoToolbox H.264 (hardware or software: the OS doesn't say)",
2919                false,
2920            ),
2921            (
2922                "VideoToolbox H.264 (hardware, low-latency rate control, encoder com.apple.videotoolbox.videoencoder.ave.avc)",
2923                true,
2924            ),
2925            (
2926                "VideoToolbox H.264 (hardware, low-latency rate control, encoder com.apple.videotoolbox.videoencoder.h264.rtvc)",
2927                false,
2928            ),
2929            // kessel-video 0.1.6's names: the encoder id and the profile, then the rate control.
2930            (
2931                "VideoToolbox H.264 (hardware, encoder com.apple.videotoolbox.videoencoder.ave.avc, Constrained High)",
2932                true,
2933            ),
2934            (
2935                "VideoToolbox H.264 (hardware, encoder com.apple.videotoolbox.videoencoder.ave.avc, Constrained High, low-latency rate control)",
2936                true,
2937            ),
2938            (
2939                "VideoToolbox H.264 (software, encoder com.apple.videotoolbox.videoencoder.h264.rtvc, Constrained High, low-latency rate control)",
2940                false,
2941            ),
2942            (
2943                "VideoToolbox H.264 (hardware, encoder com.apple.videotoolbox.videoencoder.h264.rtvc, High)",
2944                false,
2945            ),
2946            (
2947                "VideoToolbox H.264 (hardware, encoder not named, High)",
2948                true,
2949            ),
2950            (
2951                "VideoToolbox H.264 (hardware, encoder not named, High, low-latency rate control)",
2952                false,
2953            ),
2954            ("", false),
2955        ] {
2956            assert_eq!(apple_h264_name_is_hardware(name), hw, "{name}");
2957        }
2958    }
2959
2960    /// The keyframe flags of the frames queued now.
2961    fn queued(rx: &mut mpsc::Receiver<super::super::publish::VideoIn>) -> Vec<bool> {
2962        let mut out = Vec::new();
2963        while let Ok(f) = rx.try_recv() {
2964            out.push(f.frame.keyframe);
2965        }
2966        out
2967    }
2968
2969    fn collect_until(
2970        rx: &mut mpsc::Receiver<super::super::publish::VideoIn>,
2971        what: &str,
2972        n: usize,
2973    ) -> Vec<bool> {
2974        let until = std::time::Instant::now() + Duration::from_secs(10);
2975        let mut got = Vec::new();
2976        while got.len() < n {
2977            assert!(
2978                std::time::Instant::now() < until,
2979                "timed out waiting for {what}"
2980            );
2981            got.extend(queued(rx));
2982            std::thread::sleep(Duration::from_millis(5));
2983        }
2984        got
2985    }
2986
2987    #[test]
2988    fn a_background_pause_stops_capture_and_encoding_and_the_return_starts_at_a_keyframe() {
2989        let backend: Arc<dyn VideoBackend> = HwFake::new(kessel_video::fake::FakeConfig::default());
2990        let bell = Arc::new(Bell::default());
2991        let src = backend
2992            .open_camera(None, CaptureConstraints::new(640, 360, 30), bell.wake())
2993            .expect("the fake camera opens");
2994        let cap = backend
2995            .capabilities()
2996            .best(kessel_video::VideoCodec::H264, CodecDirection::Encode)
2997            .expect("the fake's H.264")
2998            .clone();
2999        let encs = open_encoders(
3000            &backend,
3001            VideoCodec::H264,
3002            &cap,
3003            vec![LayerSpec::new("q", 320, 180, 150, 30)],
3004            ContentHint::Camera,
3005            &bell.wake(),
3006        );
3007        assert_eq!(encs.len(), 1);
3008        let (publication, mut rx, _ctl) = VideoPublication::for_test(VideoSource::Camera);
3009        let stop = Arc::new(AtomicBool::new(false));
3010        let (to_pipe, from_bridge) = std::sync::mpsc::channel();
3011        let (cmd, _cmds) = mpsc::unbounded_channel();
3012        let mut pipe = Pipe {
3013            backend: backend.clone(),
3014            kind: VideoSource::Camera,
3015            codec: VideoCodec::H264,
3016            content: ContentHint::Camera,
3017            src,
3018            facing: Facing::Unknown,
3019            was_facing: Facing::Unknown,
3020            facing_since_us: 0,
3021            released_us: None,
3022            encs: encs.into_iter().map(|e| (e.spec.rid.clone(), e)).collect(),
3023            self_rid: None,
3024            publication,
3025            ctl: VideoCtl::new(cmd),
3026            taps: Taps {
3027                events: broadcast::channel(EVENT_QUEUE).0,
3028                self_view: Arc::new(Mutex::new(None)),
3029                h264_lost: Arc::new(Mutex::new(None)),
3030                camera: CameraTaps::default(),
3031            },
3032            stop: stop.clone(),
3033            ended: Arc::new(AtomicBool::new(false)),
3034            self_key: Arc::new(AtomicBool::new(false)),
3035            bell: bell.clone(),
3036            from_bridge,
3037            paused: false,
3038            hidden: false,
3039            hidden_why: None,
3040            fresh_since_us: 0,
3041            held: Arc::default(),
3042            scene_paused: false,
3043            end_asked: false,
3044            call: 1,
3045            backup: None,
3046            vp8: None,
3047            temporal: None,
3048            live: Arc::new(Mutex::new(VideoCodec::H264)),
3049            phone: false,
3050            machine: backend.subscribe(),
3051            thermal: kessel_video::ThermalLevel::Nominal,
3052            backup_converts: Arc::default(),
3053        };
3054        let thread = std::thread::spawn(move || pipe.run());
3055
3056        // Sending: a keyframe, then deltas.
3057        let first = collect_until(&mut rx, "the first frames", 5);
3058        assert!(first[0], "the first frame is a keyframe");
3059        assert!(first[1..].iter().all(|k| !k), "then deltas only: {first:?}");
3060
3061        // The background: nothing is encoded (frames already queued may still drain).
3062        to_pipe.send(ToPipe::Pause(true)).expect("pause");
3063        bell.ring();
3064        std::thread::sleep(Duration::from_millis(100));
3065        let _ = queued(&mut rx);
3066        std::thread::sleep(Duration::from_millis(300));
3067        assert_eq!(queued(&mut rx), Vec::<bool>::new(), "no frame while paused");
3068        // A repeat changes nothing.
3069        to_pipe.send(ToPipe::Pause(true)).expect("pause");
3070        bell.ring();
3071        std::thread::sleep(Duration::from_millis(100));
3072        assert!(queued(&mut rx).is_empty());
3073
3074        // The return: the first frame is a keyframe, then deltas again.
3075        to_pipe.send(ToPipe::Pause(false)).expect("resume");
3076        bell.ring();
3077        let back = collect_until(&mut rx, "frames after the return", 4);
3078        assert!(back[0], "the return starts at a keyframe: {back:?}");
3079        assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
3080
3081        stop.store(true, Ordering::SeqCst);
3082        bell.ring();
3083        thread.join().expect("the pipeline ends");
3084    }
3085
3086    #[test]
3087    fn a_source_that_ends_asks_the_engine_to_unpublish_with_its_reason() {
3088        let mut cfg = kessel_video::fake::FakeConfig::default();
3089        cfg.source_events = vec![(
3090            Duration::from_millis(300),
3091            SourceEvent::Ended(kessel_video::EndReason::DeviceLost),
3092        )];
3093        let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
3094        let bell = Arc::new(Bell::default());
3095        let src = backend
3096            .open_camera(None, CaptureConstraints::new(640, 360, 30), bell.wake())
3097            .expect("the fake camera opens");
3098        let cap = backend
3099            .capabilities()
3100            .best(kessel_video::VideoCodec::H264, CodecDirection::Encode)
3101            .expect("the fake's H.264")
3102            .clone();
3103        let encs = open_encoders(
3104            &backend,
3105            VideoCodec::H264,
3106            &cap,
3107            vec![LayerSpec::new("q", 320, 180, 150, 30)],
3108            ContentHint::Camera,
3109            &bell.wake(),
3110        );
3111        let (publication, mut rx, _ctl) = VideoPublication::for_test(VideoSource::Camera);
3112        let (cmd, mut cmds) = mpsc::unbounded_channel();
3113        let (_to_pipe, from_bridge) = std::sync::mpsc::channel();
3114        let mut pipe = Pipe {
3115            backend: backend.clone(),
3116            kind: VideoSource::Camera,
3117            codec: VideoCodec::H264,
3118            content: ContentHint::Camera,
3119            src,
3120            facing: Facing::Unknown,
3121            was_facing: Facing::Unknown,
3122            facing_since_us: 0,
3123            released_us: None,
3124            encs: encs.into_iter().map(|e| (e.spec.rid.clone(), e)).collect(),
3125            self_rid: None,
3126            publication,
3127            ctl: VideoCtl::new(cmd),
3128            taps: Taps {
3129                events: broadcast::channel(EVENT_QUEUE).0,
3130                self_view: Arc::new(Mutex::new(None)),
3131                h264_lost: Arc::new(Mutex::new(None)),
3132                camera: CameraTaps::default(),
3133            },
3134            stop: Arc::new(AtomicBool::new(false)),
3135            ended: Arc::new(AtomicBool::new(false)),
3136            self_key: Arc::new(AtomicBool::new(false)),
3137            bell: bell.clone(),
3138            from_bridge,
3139            paused: false,
3140            hidden: false,
3141            hidden_why: None,
3142            fresh_since_us: 0,
3143            held: Arc::default(),
3144            scene_paused: false,
3145            end_asked: false,
3146            call: 1,
3147            backup: None,
3148            vp8: None,
3149            temporal: None,
3150            live: Arc::new(Mutex::new(VideoCodec::H264)),
3151            phone: false,
3152            machine: backend.subscribe(),
3153            thermal: kessel_video::ThermalLevel::Nominal,
3154            backup_converts: Arc::default(),
3155        };
3156        let thread = std::thread::spawn(move || pipe.run());
3157        let _ = collect_until(&mut rx, "frames before the end", 2);
3158        let until = std::time::Instant::now() + Duration::from_secs(10);
3159        while !thread.is_finished() {
3160            assert!(
3161                std::time::Instant::now() < until,
3162                "the pipeline ends with its source"
3163            );
3164            std::thread::sleep(Duration::from_millis(10));
3165        }
3166        thread.join().expect("the pipeline ends");
3167        match cmds.try_recv().expect("the engine is asked to unpublish") {
3168            crate::call::Cmd::Publish(super::super::publish::VideoCmd::Unpublish {
3169                source,
3170                release,
3171                reason,
3172                ..
3173            }) => {
3174                assert_eq!(source, VideoSource::Camera);
3175                assert!(release, "the lease is released");
3176                assert_eq!(reason, "camera_lost");
3177            }
3178            _ => panic!("not an unpublish"),
3179        }
3180        assert!(cmds.try_recv().is_err(), "once");
3181    }
3182
3183    /// A camera pipeline on its own thread, and what a test holds of it.
3184    struct TestPipe {
3185        to_pipe: std::sync::mpsc::Sender<ToPipe>,
3186        rx: mpsc::Receiver<super::super::publish::VideoIn>,
3187        notes: broadcast::Receiver<SourceNote>,
3188        stop: Arc<AtomicBool>,
3189        bell: Arc<Bell>,
3190        thread: Option<std::thread::JoinHandle<()>>,
3191        ctl: mpsc::UnboundedSender<VideoControl>,
3192        cmds: mpsc::UnboundedReceiver<crate::call::Cmd>,
3193        fallbacks: mpsc::UnboundedReceiver<super::super::publish::ProducerFallback>,
3194        h264_lost: Arc<Mutex<Option<u64>>>,
3195        converts: Arc<std::sync::atomic::AtomicU64>,
3196        /// The pipeline's `held` word.
3197        held: Arc<AtomicBool>,
3198        /// The pipeline's camera taps.
3199        camera_taps: CameraTaps,
3200    }
3201
3202    impl TestPipe {
3203        /// The pipeline over `src`: one H.264 q layer on `backend`.
3204        fn start(
3205            backend: &Arc<dyn VideoBackend>,
3206            src: Box<dyn FrameSource>,
3207            bell: &Arc<Bell>,
3208        ) -> TestPipe {
3209            TestPipe::start_with(backend, src, bell, None)
3210        }
3211
3212        /// [`TestPipe::start`] with a VP8 backup of `backup` layers (and the backend's VP8 for
3213        /// a fall back).
3214        fn start_with(
3215            backend: &Arc<dyn VideoBackend>,
3216            src: Box<dyn FrameSource>,
3217            bell: &Arc<Bell>,
3218            backup: Option<Vec<LayerSpec>>,
3219        ) -> TestPipe {
3220            TestPipe::start_full(backend, src, bell, backup, false)
3221        }
3222
3223        /// [`TestPipe::start_with`] on a `phone` (thermal steps), or not.
3224        fn start_full(
3225            backend: &Arc<dyn VideoBackend>,
3226            src: Box<dyn FrameSource>,
3227            bell: &Arc<Bell>,
3228            backup: Option<Vec<LayerSpec>>,
3229            phone: bool,
3230        ) -> TestPipe {
3231            let converts: Arc<std::sync::atomic::AtomicU64> = Arc::default();
3232            let vp8 = backend
3233                .capabilities()
3234                .best(kessel_video::VideoCodec::Vp8, CodecDirection::Encode)
3235                .cloned();
3236            let backup = backup.map(|l| BackupPipe::new(VideoCodec::Vp8, l));
3237            let h264_lost = Arc::new(Mutex::new(None));
3238            let cap = backend
3239                .capabilities()
3240                .best(kessel_video::VideoCodec::H264, CodecDirection::Encode)
3241                .expect("the fake's H.264")
3242                .clone();
3243            let encs = open_encoders(
3244                backend,
3245                VideoCodec::H264,
3246                &cap,
3247                vec![LayerSpec::new("q", 320, 180, 150, 30)],
3248                ContentHint::Camera,
3249                &bell.wake(),
3250            );
3251            assert_eq!(encs.len(), 1);
3252            let (publication, rx, ctl, _ends, fallbacks) =
3253                VideoPublication::for_test_with_fallbacks(VideoSource::Camera);
3254            let (cmd, cmds) = mpsc::unbounded_channel();
3255            let events = broadcast::channel(EVENT_QUEUE).0;
3256            let notes = events.subscribe();
3257            let stop = Arc::new(AtomicBool::new(false));
3258            let held = Arc::new(AtomicBool::new(false));
3259            let camera_taps = CameraTaps::default();
3260            let (to_pipe, from_bridge) = std::sync::mpsc::channel();
3261            let mut pipe = Pipe {
3262                backend: backend.clone(),
3263                kind: VideoSource::Camera,
3264                codec: VideoCodec::H264,
3265                content: ContentHint::Camera,
3266                src,
3267                facing: Facing::Front,
3268                was_facing: Facing::Front,
3269                facing_since_us: 0,
3270                released_us: None,
3271                encs: encs.into_iter().map(|e| (e.spec.rid.clone(), e)).collect(),
3272                self_rid: None,
3273                publication,
3274                ctl: VideoCtl::new(cmd),
3275                taps: Taps {
3276                    events,
3277                    self_view: Arc::new(Mutex::new(None)),
3278                    h264_lost: h264_lost.clone(),
3279                    camera: camera_taps.clone(),
3280                },
3281                stop: stop.clone(),
3282                ended: Arc::new(AtomicBool::new(false)),
3283                self_key: Arc::new(AtomicBool::new(false)),
3284                bell: bell.clone(),
3285                from_bridge,
3286                paused: false,
3287                hidden: false,
3288                hidden_why: None,
3289                fresh_since_us: 0,
3290                held: held.clone(),
3291                scene_paused: false,
3292                end_asked: false,
3293                call: 1,
3294                backup,
3295                vp8,
3296                temporal: None,
3297                live: Arc::new(Mutex::new(VideoCodec::H264)),
3298                phone,
3299                machine: backend.subscribe(),
3300                thermal: kessel_video::ThermalLevel::Nominal,
3301                backup_converts: converts.clone(),
3302            };
3303            let thread = std::thread::spawn(move || pipe.run());
3304            TestPipe {
3305                to_pipe,
3306                rx,
3307                notes,
3308                stop,
3309                bell: bell.clone(),
3310                thread: Some(thread),
3311                ctl,
3312                cmds,
3313                fallbacks,
3314                h264_lost,
3315                converts,
3316                held,
3317                camera_taps,
3318            }
3319        }
3320
3321        /// Sends the engine's control `c`.
3322        fn control(&self, c: VideoControl) {
3323            self.ctl.send(c).expect("the pipeline runs");
3324            self.bell.ring();
3325        }
3326
3327        /// The frames queued within `within`: `(rid, codec, keyframe)`.
3328        fn frames_for(&mut self, within: Duration) -> Vec<(String, VideoCodec, bool)> {
3329            let until = std::time::Instant::now() + within;
3330            let mut out = Vec::new();
3331            while std::time::Instant::now() < until {
3332                while let Ok(f) = self.rx.try_recv() {
3333                    out.push((f.frame.rid.clone(), f.frame.codec, f.frame.keyframe));
3334                }
3335                std::thread::sleep(Duration::from_millis(5));
3336            }
3337            out
3338        }
3339
3340        /// The frames queued until `enough` holds of them (at most 20 s: a slow host only takes
3341        /// longer, it never starves the count): `(rid, codec, keyframe)`.
3342        fn frames_until(
3343            &mut self,
3344            what: &str,
3345            enough: impl Fn(&[(String, VideoCodec, bool)]) -> bool,
3346        ) -> Vec<(String, VideoCodec, bool)> {
3347            let until = std::time::Instant::now() + Duration::from_secs(20);
3348            let mut out = Vec::new();
3349            while !enough(&out) {
3350                assert!(
3351                    std::time::Instant::now() < until,
3352                    "{what} within 20 s: {out:?}"
3353                );
3354                while let Ok(f) = self.rx.try_recv() {
3355                    out.push((f.frame.rid.clone(), f.frame.codec, f.frame.keyframe));
3356                }
3357                std::thread::sleep(Duration::from_millis(5));
3358            }
3359            out
3360        }
3361
3362        /// Drains the frames until `done` holds (at most 5 s).
3363        fn drain_until(&mut self, what: &str, done: impl Fn() -> bool) {
3364            let until = std::time::Instant::now() + Duration::from_secs(5);
3365            while !done() {
3366                assert!(std::time::Instant::now() < until, "{what} within 5 s");
3367                while self.rx.try_recv().is_ok() {}
3368                std::thread::sleep(Duration::from_millis(5));
3369            }
3370        }
3371
3372        /// Waits (at most 5 s) for the pipeline's fall back to one codec, then 500 ms more: the
3373        /// fall back and every frame queued meanwhile.
3374        fn until_fallback(
3375            &mut self,
3376        ) -> (
3377            super::super::publish::ProducerFallback,
3378            Vec<(String, VideoCodec, bool)>,
3379        ) {
3380            let until = std::time::Instant::now() + Duration::from_secs(5);
3381            let mut seen = Vec::new();
3382            let f = loop {
3383                if let Ok(f) = self.fallbacks.try_recv() {
3384                    break f;
3385                }
3386                assert!(
3387                    std::time::Instant::now() < until,
3388                    "no fall back to VP8 alone"
3389                );
3390                seen.extend(self.frames_for(Duration::from_millis(20)));
3391            };
3392            seen.extend(self.frames_for(Duration::from_millis(500)));
3393            (f, seen)
3394        }
3395
3396        fn send(&self, m: ToPipe) {
3397            self.to_pipe.send(m).expect("the pipeline runs");
3398            self.bell.ring();
3399        }
3400
3401        /// The next pause, resume or end note within 10 s (a loud failure naming `what`
3402        /// otherwise; `Started` and errors skipped).
3403        fn next_note(&mut self, what: &str) -> CaptureEvent {
3404            let until = std::time::Instant::now() + Duration::from_secs(10);
3405            loop {
3406                match self.notes.try_recv() {
3407                    Ok(n) if is_state(&n.event) => return n.event,
3408                    Ok(_) => {}
3409                    Err(broadcast::error::TryRecvError::Empty) => {}
3410                    Err(e) => panic!("{what}: the notes failed: {e}"),
3411                }
3412                assert!(
3413                    std::time::Instant::now() < until,
3414                    "timed out waiting for {what}"
3415                );
3416                std::thread::sleep(Duration::from_millis(5));
3417            }
3418        }
3419
3420        /// Nothing is encoded for a while (frames already queued drain first).
3421        fn assert_quiet(&mut self, what: &str) {
3422            std::thread::sleep(Duration::from_millis(100));
3423            let _ = queued(&mut self.rx);
3424            std::thread::sleep(Duration::from_millis(300));
3425            assert_eq!(queued(&mut self.rx), Vec::<bool>::new(), "{what}");
3426        }
3427
3428        fn finish(mut self) {
3429            self.stop.store(true, Ordering::SeqCst);
3430            self.bell.ring();
3431            if let Some(t) = self.thread.take() {
3432                t.join().expect("the pipeline ends");
3433            }
3434        }
3435    }
3436
3437    /// A pause, a resume or an end.
3438    /// kessel-video's fake backend with its structural H.264 as a hardware encoder (listed
3439    /// as one, opened hardware-only, each session reporting the hardware), with faults: VP8
3440    /// opens that fail, H.264 sessions lost (and their reopens refused).
3441    struct HwFake {
3442        inner: Arc<dyn VideoBackend>,
3443        vp8_failures: std::sync::atomic::AtomicU32,
3444        vp8_live: Arc<std::sync::atomic::AtomicU64>,
3445        h264_epoch: Arc<std::sync::atomic::AtomicU64>,
3446        h264_refused: AtomicBool,
3447        /// Encoders opened from now on lag one frame ([`Lag`]).
3448        lag: AtomicBool,
3449    }
3450
3451    impl HwFake {
3452        fn new(cfg: kessel_video::fake::FakeConfig) -> Arc<HwFake> {
3453            let mut cfg = cfg;
3454            cfg.codec = kessel_video::fake::FakeCodec::Structural;
3455            Arc::new(HwFake {
3456                inner: kessel_video::fake::FakeBackend::new(cfg),
3457                vp8_failures: Default::default(),
3458                vp8_live: Default::default(),
3459                h264_epoch: Default::default(),
3460                h264_refused: AtomicBool::new(false),
3461                lag: AtomicBool::new(false),
3462            })
3463        }
3464
3465        fn fail_vp8_opens(&self, n: u32) {
3466            self.vp8_failures.store(n, Ordering::SeqCst);
3467        }
3468
3469        fn vp8_open(&self) -> u64 {
3470            self.vp8_live.load(Ordering::SeqCst)
3471        }
3472
3473        fn lose_h264(&self) {
3474            self.h264_refused.store(true, Ordering::SeqCst);
3475            self.h264_epoch.fetch_add(1, Ordering::SeqCst);
3476        }
3477    }
3478
3479    /// A wrapped encoder: an H.264 one reports the hardware and is lost with its epoch; a VP8
3480    /// one is counted while open.
3481    struct Wrapped {
3482        inner: Box<dyn VideoEncoder>,
3483        lost: Option<(Arc<std::sync::atomic::AtomicU64>, u64)>,
3484        live: Option<Arc<std::sync::atomic::AtomicU64>>,
3485        lag: Option<Lag>,
3486    }
3487
3488    /// An encoder one frame behind, as a threaded one whose worker hasn't taken its input yet:
3489    /// a submitted frame waits for the next submit, and a `request_keyframe` marks the input
3490    /// it takes next (the one waiting), not the next one submitted.
3491    #[derive(Default)]
3492    struct Lag {
3493        held: Option<(kessel_video::VideoFrame, EncodeOptions)>,
3494        key_asked: bool,
3495    }
3496
3497    impl Drop for Wrapped {
3498        fn drop(&mut self) {
3499            if let Some(l) = &self.live {
3500                l.fetch_sub(1, Ordering::SeqCst);
3501            }
3502        }
3503    }
3504
3505    impl VideoEncoder for Wrapped {
3506        fn submit(
3507            &mut self,
3508            frame: &kessel_video::VideoFrame,
3509            opts: EncodeOptions,
3510        ) -> Result<(), KError> {
3511            let Some(lag) = self.lag.as_mut() else {
3512                return self.inner.submit(frame, opts);
3513            };
3514            if let Some((f, o)) = lag.held.replace((frame.clone(), opts)) {
3515                let key = o.keyframe || std::mem::take(&mut lag.key_asked);
3516                let o = if key {
3517                    EncodeOptions::keyframe()
3518                } else {
3519                    EncodeOptions::default()
3520                };
3521                self.inner.submit(&f, o)?;
3522            }
3523            Ok(())
3524        }
3525        fn poll(&mut self) -> Option<Result<kessel_video::EncodedFrame, KError>> {
3526            if let Some((epoch, at)) = &self.lost
3527                && epoch.load(Ordering::SeqCst) != *at
3528            {
3529                return Some(Err(KError::DeviceLost));
3530            }
3531            self.inner.poll()
3532        }
3533        fn request_keyframe(&mut self) {
3534            match self.lag.as_mut() {
3535                Some(lag) => lag.key_asked = true,
3536                None => self.inner.request_keyframe(),
3537            }
3538        }
3539        fn set_rates(&mut self, rates: Rates) -> Result<(), KError> {
3540            self.inner.set_rates(rates)
3541        }
3542        fn set_size(&mut self, width: u32, height: u32) -> Result<(), KError> {
3543            self.inner.set_size(width, height)
3544        }
3545        fn info(&self) -> kessel_video::EncoderInfo {
3546            self.inner.info()
3547        }
3548        fn stats(&self) -> kessel_video::EncoderStats {
3549            self.inner.stats()
3550        }
3551        fn implementation(&self) -> Implementation {
3552            if self.lost.is_some() {
3553                Implementation::Hardware
3554            } else {
3555                self.inner.implementation()
3556            }
3557        }
3558    }
3559
3560    impl VideoBackend for HwFake {
3561        fn capabilities(&self) -> Capabilities {
3562            let mut c = self.inner.capabilities();
3563            for e in &mut c.codecs {
3564                if e.codec == kessel_video::VideoCodec::H264 {
3565                    e.implementation = Implementation::Hardware;
3566                }
3567            }
3568            c
3569        }
3570        fn now_us(&self) -> u64 {
3571            self.inner.now_us()
3572        }
3573        fn cameras(&self) -> Vec<kessel_video::CameraInfo> {
3574            self.inner.cameras()
3575        }
3576        fn camera_permission(&self) -> kessel_video::Permission {
3577            self.inner.camera_permission()
3578        }
3579        fn request_camera_permission(&self, done: kessel_video::Done<kessel_video::Permission>) {
3580            self.inner.request_camera_permission(done);
3581        }
3582        fn open_camera(
3583            &self,
3584            id: Option<&str>,
3585            constraints: CaptureConstraints,
3586            wake: Wake,
3587        ) -> Result<Box<dyn FrameSource>, KError> {
3588            self.inner.open_camera(id, constraints, wake)
3589        }
3590        fn screen_permission(&self) -> kessel_video::Permission {
3591            self.inner.screen_permission()
3592        }
3593        fn request_screen_permission(&self, done: kessel_video::Done<kessel_video::Permission>) {
3594            self.inner.request_screen_permission(done);
3595        }
3596        fn screen_sources(&self) -> Result<Vec<kessel_video::ScreenSourceInfo>, KError> {
3597            self.inner.screen_sources()
3598        }
3599        fn pick_screen(
3600            &self,
3601            opts: kessel_video::PickOptions,
3602            done: kessel_video::Done<Result<kessel_video::ScreenSelection, KError>>,
3603        ) {
3604            self.inner.pick_screen(opts, done);
3605        }
3606        fn open_screen(
3607            &self,
3608            source: &kessel_video::ScreenSelection,
3609            constraints: CaptureConstraints,
3610            wake: Wake,
3611        ) -> Result<Box<dyn FrameSource>, KError> {
3612            self.inner.open_screen(source, constraints, wake)
3613        }
3614        fn encoder(
3615            &self,
3616            mut config: EncoderConfig,
3617            wake: Wake,
3618        ) -> Result<Box<dyn VideoEncoder>, KError> {
3619            if config.codec.codec() == kessel_video::VideoCodec::H264 {
3620                if self.h264_refused.load(Ordering::SeqCst) {
3621                    return Err(KError::NoResources);
3622                }
3623                // The fake has no hardware: the adapter stands in for one.
3624                config.implementation = ImplPreference::PreferHardware;
3625                let at = self.h264_epoch.load(Ordering::SeqCst);
3626                let inner = self.inner.encoder(config, wake)?;
3627                return Ok(Box::new(Wrapped {
3628                    inner,
3629                    lost: Some((self.h264_epoch.clone(), at)),
3630                    live: None,
3631                    lag: self.lag.load(Ordering::SeqCst).then(Lag::default),
3632                }));
3633            }
3634            let fail = self
3635                .vp8_failures
3636                .try_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
3637                .is_ok();
3638            if fail {
3639                return Err(KError::NoResources);
3640            }
3641            let inner = self.inner.encoder(config, wake)?;
3642            self.vp8_live.fetch_add(1, Ordering::SeqCst);
3643            Ok(Box::new(Wrapped {
3644                inner,
3645                lost: None,
3646                live: Some(self.vp8_live.clone()),
3647                lag: self.lag.load(Ordering::SeqCst).then(Lag::default),
3648            }))
3649        }
3650        fn decoder(
3651            &self,
3652            config: kessel_video::DecoderConfig,
3653            wake: Wake,
3654        ) -> Result<Box<dyn kessel_video::VideoDecoder>, KError> {
3655            self.inner.decoder(config, wake)
3656        }
3657        fn convert(
3658            &self,
3659            frame: &kessel_video::VideoFrame,
3660            width: u32,
3661            height: u32,
3662            format: PixelFormat,
3663        ) -> Result<kessel_video::VideoFrame, KError> {
3664            self.inner.convert(frame, width, height, format)
3665        }
3666        fn subscribe(&self) -> kessel_video::EventRx {
3667            self.inner.subscribe()
3668        }
3669        fn shutdown(&self) {
3670            self.inner.shutdown();
3671        }
3672    }
3673
3674    fn rate(rid: &str, active: bool) -> LayerRate {
3675        LayerRate {
3676            rid: rid.to_owned(),
3677            active,
3678            bitrate_bps: if active { 150_000 } else { 0 },
3679            fps: 30,
3680        }
3681    }
3682
3683    #[test]
3684    fn the_backup_runs_between_its_start_and_stop_from_the_same_capture() {
3685        let fake = HwFake::new(kessel_video::fake::FakeConfig::default());
3686        let backend: Arc<dyn VideoBackend> = fake.clone();
3687        let bell = Arc::new(Bell::default());
3688        let src = fake_camera(&backend, &bell);
3689        let q = LayerSpec::new("q", 320, 180, 150, 30);
3690        let mut p = TestPipe::start_with(&backend, src, &bell, Some(vec![q.clone()]));
3691        let count = |fs: &[(String, VideoCodec, bool)], c: VideoCodec| {
3692            fs.iter().filter(|f| f.1 == c).count()
3693        };
3694        // Before any start: H.264 only, no VP8 encoder open.
3695        let before = p.frames_until("3 H.264 frames", |fs| count(fs, VideoCodec::H264) >= 3);
3696        assert!(before.iter().all(|f| f.1 == VideoCodec::H264), "{before:?}");
3697        assert_eq!(
3698            fake.vp8_open(),
3699            0,
3700            "the backup's encoders open only on demand"
3701        );
3702        // BackupStart, then its rates: VP8 frames of q, the first a keyframe.
3703        p.control(VideoControl::BackupStart(vec![q.clone()]));
3704        p.control(VideoControl::BackupRates(vec![rate("q", true)]));
3705        let on = p.frames_until("3 VP8 frames and the primary's", |fs| {
3706            count(fs, VideoCodec::Vp8) >= 3 && count(fs, VideoCodec::H264) >= 1
3707        });
3708        let vp8: Vec<&(String, VideoCodec, bool)> =
3709            on.iter().filter(|f| f.1 == VideoCodec::Vp8).collect();
3710        assert!(vp8[0].2, "the backup's first frame is a keyframe: {vp8:?}");
3711        assert!(vp8.iter().all(|f| f.0 == "q"));
3712        assert!(
3713            on.iter().any(|f| f.1 == VideoCodec::H264),
3714            "the primary goes on"
3715        );
3716        assert_eq!(fake.vp8_open(), 1);
3717        // A backup keyframe on request.
3718        p.control(VideoControl::BackupKeyframe { rid: "q".into() });
3719        let _ = p.frames_until("a backup keyframe", |fs| {
3720            fs.iter().any(|f| f.1 == VideoCodec::Vp8 && f.2)
3721        });
3722        // BackupStop: its encoder closed, then no more VP8.
3723        p.control(VideoControl::BackupStop);
3724        p.drain_until("the backup's encoder closed", || fake.vp8_open() == 0);
3725        // What the closed encoder had queued is out by now.
3726        let _ = p.frames_for(Duration::from_millis(200));
3727        let after = p.frames_until("3 H.264 frames", |fs| count(fs, VideoCodec::H264) >= 3);
3728        assert!(after.iter().all(|f| f.1 == VideoCodec::H264), "{after:?}");
3729        assert_eq!(fake.vp8_open(), 0, "the backup's encoder closed");
3730        assert!(p.fallbacks.try_recv().is_err(), "nothing fell back");
3731        p.finish();
3732    }
3733
3734    #[test]
3735    fn a_backup_that_does_not_open_is_tried_once_then_the_publication_goes_vp8_alone() {
3736        let fake = HwFake::new(kessel_video::fake::FakeConfig::default());
3737        let backend: Arc<dyn VideoBackend> = fake.clone();
3738        let bell = Arc::new(Bell::default());
3739        let src = fake_camera(&backend, &bell);
3740        let q = LayerSpec::new("q", 320, 180, 150, 30);
3741        let mut p = TestPipe::start_with(&backend, src, &bell, Some(vec![q.clone()]));
3742        // One failure: the retry after a second opens it.
3743        fake.fail_vp8_opens(1);
3744        p.control(VideoControl::BackupStart(vec![q.clone()]));
3745        p.control(VideoControl::BackupRates(vec![rate("q", true)]));
3746        let early = p.frames_for(Duration::from_millis(600));
3747        assert!(early.iter().all(|f| f.1 == VideoCodec::H264), "{early:?}");
3748        let later = p.frames_for(Duration::from_millis(900));
3749        assert!(
3750            later.iter().any(|f| f.1 == VideoCodec::Vp8 && f.2),
3751            "the retry opened the backup: {later:?}"
3752        );
3753        assert!(p.fallbacks.try_recv().is_err());
3754        // Stopped, then started again with two failures: the retry fails too, and the
3755        // publication is published again in VP8 alone (its own q, a keyframe first).
3756        p.control(VideoControl::BackupStop);
3757        let _ = p.frames_for(Duration::from_millis(200));
3758        fake.fail_vp8_opens(2);
3759        p.control(VideoControl::BackupStart(vec![q.clone()]));
3760        p.control(VideoControl::BackupRates(vec![rate("q", true)]));
3761        let (f, seen) = p.until_fallback();
3762        assert_eq!(f.codec, VideoCodec::Vp8);
3763        let rids: Vec<&str> = f.layers.iter().map(|l| l.rid.as_str()).collect();
3764        assert_eq!(rids, vec!["q"]);
3765        assert_vp8_alone_from_a_keyframe(&seen);
3766        p.finish();
3767    }
3768
3769    /// From the first VP8 frame on: VP8 only, the first a keyframe, and some frames.
3770    fn assert_vp8_alone_from_a_keyframe(seen: &[(String, VideoCodec, bool)]) {
3771        let at = seen
3772            .iter()
3773            .position(|f| f.1 == VideoCodec::Vp8)
3774            .unwrap_or_else(|| panic!("no VP8 frame after the fall back: {seen:?}"));
3775        assert!(seen[at].2, "a keyframe first: {seen:?}");
3776        let rest = &seen[at..];
3777        assert!(rest.len() >= 3, "{seen:?}");
3778        assert!(
3779            rest.iter().all(|f| f.1 == VideoCodec::Vp8),
3780            "VP8 alone: {seen:?}"
3781        );
3782    }
3783
3784    #[test]
3785    fn a_lost_hardware_encoder_publishes_vp8_alone_and_h264_is_not_tried_again() {
3786        let fake = HwFake::new(kessel_video::fake::FakeConfig::default());
3787        let backend: Arc<dyn VideoBackend> = fake.clone();
3788        let bell = Arc::new(Bell::default());
3789        let src = fake_camera(&backend, &bell);
3790        let q = LayerSpec::new("q", 320, 180, 150, 30);
3791        let mut p = TestPipe::start_with(&backend, src, &bell, Some(vec![q]));
3792        let before = p.frames_for(Duration::from_millis(300));
3793        assert!(before.iter().any(|f| f.1 == VideoCodec::H264));
3794        fake.lose_h264();
3795        let (f, seen) = p.until_fallback();
3796        assert_eq!(f.codec, VideoCodec::Vp8);
3797        assert_eq!(*lock(&p.h264_lost), Some(1), "no H.264 again in this call");
3798        assert_vp8_alone_from_a_keyframe(&seen);
3799        assert!(
3800            p.cmds.try_recv().is_err(),
3801            "not unpublished: the lease is kept"
3802        );
3803        p.finish();
3804    }
3805
3806    #[test]
3807    fn the_backups_ladder_is_the_primarys_and_a_phones_stops_at_360p() {
3808        let layers = vec![
3809            LayerSpec::new("q", 320, 180, 150, 30),
3810            LayerSpec::new("h", 640, 360, 500, 30),
3811            LayerSpec::new("f", 1280, 720, 1700, 30),
3812        ];
3813        let rids = |l: &[LayerSpec]| l.iter().map(|x| x.rid.clone()).collect::<Vec<_>>();
3814        let desk = backup_ladder(&layers, false, 3);
3815        assert_eq!(rids(&desk), vec!["q", "h", "f"]);
3816        assert!(desk.iter().all(|l| l.temporal_layers == 3));
3817        assert_eq!(rids(&backup_ladder(&layers, true, 2)), vec!["q", "h"]);
3818        // A portrait phone camera: 360 × 640 is 360p.
3819        let portrait = vec![
3820            LayerSpec::new("q", 180, 320, 150, 30),
3821            LayerSpec::new("h", 360, 640, 500, 30),
3822            LayerSpec::new("f", 720, 1280, 1700, 30),
3823        ];
3824        assert_eq!(rids(&backup_ladder(&portrait, true, 1)), vec!["q", "h"]);
3825        // Only a 720p layer: the phone keeps it (a backup always has a layer).
3826        let big = vec![LayerSpec::new("f", 1280, 720, 1700, 30)];
3827        assert_eq!(rids(&backup_ladder(&big, true, 1)), vec!["f"]);
3828    }
3829
3830    #[test]
3831    fn one_capture_feeds_both_codecs_and_the_backup_converts_once_per_frame() {
3832        let fake = HwFake::new(kessel_video::fake::FakeConfig::default());
3833        let backend: Arc<dyn VideoBackend> = fake.clone();
3834        let bell = Arc::new(Bell::default());
3835        // A 1280 × 720 camera; the backup runs q and h (640 × 360 the largest).
3836        let src = backend
3837            .open_camera(None, CaptureConstraints::new(1280, 720, 30), bell.wake())
3838            .expect("the fake camera opens");
3839        let q = LayerSpec::new("q", 320, 180, 150, 30);
3840        let h = LayerSpec::new("h", 640, 360, 500, 30);
3841        let mut p = TestPipe::start_with(&backend, src, &bell, Some(vec![q.clone(), h.clone()]));
3842        let _ = p.frames_until("3 frames", |fs| fs.len() >= 3);
3843        assert_eq!(
3844            p.converts.load(Ordering::SeqCst),
3845            0,
3846            "nothing is converted while the backup doesn't run"
3847        );
3848        p.control(VideoControl::BackupStart(vec![q, h]));
3849        p.control(VideoControl::BackupRates(vec![
3850            rate("q", true),
3851            rate("h", true),
3852        ]));
3853        let n = |fs: &[(String, VideoCodec, bool)], c: VideoCodec, rid: Option<&str>| {
3854            fs.iter()
3855                .filter(|f| f.1 == c && rid.is_none_or(|r| f.0 == r))
3856                .count() as u64
3857        };
3858        // Both codecs from the one capture: 20 frames of the primary, 5 of each backup layer.
3859        let on = p.frames_until("both codecs", |fs| {
3860            n(fs, VideoCodec::Vp8, Some("q")) >= 5
3861                && n(fs, VideoCodec::Vp8, Some("h")) >= 5
3862                && n(fs, VideoCodec::H264, None) >= 20
3863        });
3864        let converts = p.converts.load(Ordering::SeqCst);
3865        let (nq, nh) = (
3866            n(&on, VideoCodec::Vp8, Some("q")),
3867            n(&on, VideoCodec::Vp8, Some("h")),
3868        );
3869        let primary = n(&on, VideoCodec::H264, None);
3870        // Once per captured frame (the primary's H.264 makes one frame per capture), not once
3871        // per backup layer (q and h come from one conversion: once per layer would be about
3872        // twice the primary's frames).
3873        assert!(
3874            converts >= primary / 2 && converts <= primary + 5,
3875            "{converts} conversions for {primary} captured frames ({nq} q, {nh} h)"
3876        );
3877        p.control(VideoControl::BackupStop);
3878        p.drain_until("the backup's encoders closed", || fake.vp8_open() == 0);
3879        let _ = p.frames_for(Duration::from_millis(200));
3880        let c0 = p.converts.load(Ordering::SeqCst);
3881        let _ = p.frames_for(Duration::from_millis(400));
3882        assert_eq!(
3883            p.converts.load(Ordering::SeqCst),
3884            c0,
3885            "no conversion after the stop"
3886        );
3887        p.finish();
3888    }
3889
3890    #[test]
3891    fn heat_caps_a_phones_backup_but_never_stops_it() {
3892        use kessel_video::ThermalLevel as T;
3893        assert_eq!(thermal_backup_caps(T::Nominal), BackupCaps::default());
3894        assert_eq!(thermal_backup_caps(T::Fair), BackupCaps::default());
3895        assert_eq!(
3896            thermal_backup_caps(T::Serious),
3897            BackupCaps {
3898                max_layers: Some(1),
3899                max_fps: None
3900            }
3901        );
3902        assert_eq!(
3903            thermal_backup_caps(T::Critical),
3904            BackupCaps {
3905                max_layers: Some(1),
3906                max_fps: Some(15)
3907            }
3908        );
3909        // The pipeline on a phone sends the engine each new level's caps.
3910        let mut cfg = kessel_video::fake::FakeConfig::default();
3911        cfg.backend_events = vec![
3912            (
3913                Duration::from_millis(400),
3914                kessel_video::BackendEvent::Thermal(T::Serious),
3915            ),
3916            (
3917                Duration::from_millis(700),
3918                kessel_video::BackendEvent::Thermal(T::Critical),
3919            ),
3920            (
3921                Duration::from_millis(1000),
3922                kessel_video::BackendEvent::Thermal(T::Nominal),
3923            ),
3924        ];
3925        let fake = HwFake::new(cfg);
3926        let backend: Arc<dyn VideoBackend> = fake.clone();
3927        let bell = Arc::new(Bell::default());
3928        let src = fake_camera(&backend, &bell);
3929        let q = LayerSpec::new("q", 320, 180, 150, 30);
3930        let mut p = TestPipe::start_full(&backend, src, &bell, Some(vec![q]), true);
3931        let until = std::time::Instant::now() + Duration::from_secs(5);
3932        let mut got = Vec::new();
3933        while got.len() < 3 {
3934            assert!(std::time::Instant::now() < until, "caps so far: {got:?}");
3935            while let Ok(c) = p.cmds.try_recv() {
3936                if let crate::call::Cmd::Publish(super::super::publish::VideoCmd::BackupCaps(c)) = c
3937                {
3938                    got.push(c);
3939                }
3940            }
3941            let _ = p.frames_for(Duration::from_millis(20));
3942        }
3943        assert_eq!(
3944            got,
3945            vec![
3946                thermal_backup_caps(T::Serious),
3947                thermal_backup_caps(T::Critical),
3948                BackupCaps::default()
3949            ]
3950        );
3951        p.finish();
3952    }
3953
3954    fn is_state(e: &CaptureEvent) -> bool {
3955        matches!(
3956            e,
3957            CaptureEvent::Paused(_) | CaptureEvent::Resumed | CaptureEvent::Ended(_)
3958        )
3959    }
3960
3961    fn fake_camera(backend: &Arc<dyn VideoBackend>, bell: &Arc<Bell>) -> Box<dyn FrameSource> {
3962        backend
3963            .open_camera(None, CaptureConstraints::new(640, 360, 30), bell.wake())
3964            .expect("the fake camera opens")
3965    }
3966
3967    /// Another app takes the camera (`camera_busy`): no frame is encoded while it holds it,
3968    /// and when it gives it back the pipeline resumes on its own, a keyframe first.
3969    #[test]
3970    fn a_camera_busy_pause_resumes_with_a_keyframe_when_it_ends() {
3971        let mut cfg = kessel_video::fake::FakeConfig::default();
3972        cfg.source_events = vec![
3973            (
3974                Duration::from_millis(400),
3975                SourceEvent::Interrupted(kessel_video::Interruption::InUseByAnother),
3976            ),
3977            (Duration::from_millis(1200), SourceEvent::Resumed),
3978        ];
3979        let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
3980        let bell = Arc::new(Bell::default());
3981        let src = fake_camera(&backend, &bell);
3982        let mut p = TestPipe::start(&backend, src, &bell);
3983        let first = collect_until(&mut p.rx, "the first frames", 3);
3984        assert!(first[0], "the first frame is a keyframe");
3985
3986        assert_eq!(
3987            p.next_note("the camera_busy pause"),
3988            CaptureEvent::Paused(CapturePause::InUseByAnother)
3989        );
3990        p.assert_quiet("no frame while another app holds the camera");
3991
3992        assert_eq!(p.next_note("the resume"), CaptureEvent::Resumed);
3993        let back = collect_until(&mut p.rx, "frames after the resume", 4);
3994        assert!(back[0], "the resume starts at a keyframe: {back:?}");
3995        assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
3996        p.finish();
3997    }
3998
3999    /// A source paused for the background whose end never comes (iOS's interruption-ended
4000    /// notice missing) while its frames run again: in the background nothing is sent; back
4001    /// in front, the first frame captured since says the pause is over (a keyframe first,
4002    /// `Resumed` for `local_video`), and the camera is not held.
4003    #[test]
4004    fn a_background_pause_that_never_ends_resumes_on_the_frames_after_the_return() {
4005        let mut cfg = kessel_video::fake::FakeConfig::default();
4006        cfg.source_events = vec![(
4007            Duration::from_millis(400),
4008            SourceEvent::Interrupted(kessel_video::Interruption::Background),
4009        )];
4010        let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4011        let bell = Arc::new(Bell::default());
4012        let src = fake_camera(&backend, &bell);
4013        let mut p = TestPipe::start(&backend, src, &bell);
4014        let _ = collect_until(&mut p.rx, "the first frames", 3);
4015        p.send(ToPipe::Pause(true));
4016        assert_eq!(
4017            p.next_note("the background pause"),
4018            CaptureEvent::Paused(CapturePause::Background)
4019        );
4020        p.assert_quiet("nothing sent in the background");
4021        assert!(
4022            !p.held.load(Ordering::SeqCst),
4023            "not held while the app is in the background"
4024        );
4025        p.send(ToPipe::Pause(false));
4026        assert_eq!(
4027            p.next_note("the pause over on the frames"),
4028            CaptureEvent::Resumed
4029        );
4030        let back = collect_until(&mut p.rx, "frames after the return", 4);
4031        assert!(back[0], "the return starts at a keyframe: {back:?}");
4032        assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
4033        assert!(!p.held.load(Ordering::SeqCst), "not held once frames run");
4034        p.finish();
4035    }
4036
4037    /// The background pause ends (the source's `Resumed`) before the app comes back: still
4038    /// nothing sent until the return, then one keyframe and no second resume.
4039    #[test]
4040    fn a_background_pause_ended_before_the_return_waits_for_the_return() {
4041        let mut cfg = kessel_video::fake::FakeConfig::default();
4042        cfg.source_events = vec![
4043            (
4044                Duration::from_millis(400),
4045                SourceEvent::Interrupted(kessel_video::Interruption::Background),
4046            ),
4047            (Duration::from_millis(700), SourceEvent::Resumed),
4048        ];
4049        let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4050        let bell = Arc::new(Bell::default());
4051        let src = fake_camera(&backend, &bell);
4052        let mut p = TestPipe::start(&backend, src, &bell);
4053        let _ = collect_until(&mut p.rx, "the first frames", 3);
4054        p.send(ToPipe::Pause(true));
4055        assert!(matches!(
4056            p.next_note("the background pause"),
4057            CaptureEvent::Paused(_)
4058        ));
4059        assert_eq!(p.next_note("the pause's end"), CaptureEvent::Resumed);
4060        p.assert_quiet("the app is still in the background");
4061        p.send(ToPipe::Pause(false));
4062        let back = collect_until(&mut p.rx, "frames after the return", 4);
4063        assert!(back[0], "the return starts at a keyframe: {back:?}");
4064        assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
4065        let mut notes = Vec::new();
4066        while let Ok(n) = p.notes.try_recv() {
4067            notes.push(n.event);
4068        }
4069        assert!(!notes.iter().any(is_state), "no second resume: {notes:?}");
4070        p.finish();
4071    }
4072
4073    /// The background pause ends after the app came back: the frames end it first; the
4074    /// source's late `Resumed` adds no keyframe.
4075    #[test]
4076    fn a_background_pause_ended_after_the_return_adds_no_keyframe() {
4077        let mut cfg = kessel_video::fake::FakeConfig::default();
4078        cfg.source_events = vec![
4079            (
4080                Duration::from_millis(400),
4081                SourceEvent::Interrupted(kessel_video::Interruption::Background),
4082            ),
4083            (Duration::from_millis(2500), SourceEvent::Resumed),
4084        ];
4085        let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4086        let bell = Arc::new(Bell::default());
4087        let src = fake_camera(&backend, &bell);
4088        let mut p = TestPipe::start(&backend, src, &bell);
4089        let _ = collect_until(&mut p.rx, "the first frames", 3);
4090        p.send(ToPipe::Pause(true));
4091        assert!(matches!(
4092            p.next_note("the background pause"),
4093            CaptureEvent::Paused(_)
4094        ));
4095        p.send(ToPipe::Pause(false));
4096        assert_eq!(p.next_note("the frames' resume"), CaptureEvent::Resumed);
4097        // Every frame from the return until four after the source's late resume (2.5 s from
4098        // the open): one keyframe, the first.
4099        let mut back = Vec::new();
4100        let until = std::time::Instant::now() + Duration::from_secs(10);
4101        loop {
4102            back.extend(queued(&mut p.rx));
4103            match p.notes.try_recv() {
4104                Ok(n) if is_state(&n.event) => {
4105                    assert_eq!(n.event, CaptureEvent::Resumed, "the source's late resume");
4106                    break;
4107                }
4108                _ => {}
4109            }
4110            assert!(
4111                std::time::Instant::now() < until,
4112                "timed out waiting for the late resume"
4113            );
4114            std::thread::sleep(Duration::from_millis(5));
4115        }
4116        back.extend(collect_until(&mut p.rx, "frames after the late resume", 4));
4117        assert!(back[0], "the return starts at a keyframe: {back:?}");
4118        assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
4119        p.finish();
4120    }
4121
4122    /// A pause for another reason never ends on frames alone (another app holds the camera
4123    /// until the source says so).
4124    #[test]
4125    fn only_a_background_pause_ends_on_frames() {
4126        let mut cfg = kessel_video::fake::FakeConfig::default();
4127        cfg.source_events = vec![(
4128            Duration::from_millis(400),
4129            SourceEvent::Interrupted(kessel_video::Interruption::InUseByAnother),
4130        )];
4131        let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4132        let bell = Arc::new(Bell::default());
4133        let src = fake_camera(&backend, &bell);
4134        let mut p = TestPipe::start(&backend, src, &bell);
4135        let _ = collect_until(&mut p.rx, "the first frames", 3);
4136        assert!(matches!(p.next_note("the pause"), CaptureEvent::Paused(_)));
4137        p.send(ToPipe::Pause(true));
4138        p.send(ToPipe::Pause(false));
4139        p.assert_quiet("another app still holds the camera");
4140        assert!(!p.held.load(Ordering::SeqCst));
4141        p.finish();
4142    }
4143
4144    /// A source paused for the background that sends no frame after the app's return is
4145    /// held (the bridge then opens the camera again); back in the background it is not.
4146    #[test]
4147    fn a_silent_background_pause_after_the_return_is_held() {
4148        let backend: Arc<dyn VideoBackend> = HwFake::new(kessel_video::fake::FakeConfig::default());
4149        let bell = Arc::new(Bell::default());
4150        let src: Box<dyn FrameSource> = Box::new(Silent(vec![SourceEvent::Interrupted(
4151            kessel_video::Interruption::Background,
4152        )]));
4153        let mut p = TestPipe::start(&backend, src, &bell);
4154        p.send(ToPipe::Pause(true));
4155        assert!(matches!(
4156            p.next_note("the background pause"),
4157            CaptureEvent::Paused(_)
4158        ));
4159        std::thread::sleep(Duration::from_millis(200));
4160        assert!(
4161            !p.held.load(Ordering::SeqCst),
4162            "the app is in the background"
4163        );
4164        p.send(ToPipe::Pause(false));
4165        wait_held(&p.held, true, "held after the return");
4166        p.send(ToPipe::Pause(true));
4167        wait_held(&p.held, false, "not held in the background again");
4168        p.finish();
4169    }
4170
4171    fn wait_held(held: &AtomicBool, want: bool, what: &str) {
4172        let until = std::time::Instant::now() + Duration::from_secs(10);
4173        while held.load(Ordering::SeqCst) != want {
4174            assert!(std::time::Instant::now() < until, "timed out: {what}");
4175            std::thread::sleep(Duration::from_millis(5));
4176        }
4177    }
4178
4179    /// A source with only these events, then nothing (no frames).
4180    struct Silent(Vec<SourceEvent>);
4181
4182    impl FrameSource for Silent {
4183        fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
4184            None
4185        }
4186        fn try_event(&mut self) -> Option<SourceEvent> {
4187            (!self.0.is_empty()).then(|| self.0.remove(0))
4188        }
4189        fn set_constraints(&mut self, _c: CaptureConstraints) -> Result<(), KError> {
4190            Ok(())
4191        }
4192        fn set_paused(&mut self, _paused: bool) {}
4193        fn stats(&self) -> kessel_video::SourceStats {
4194            kessel_video::SourceStats::default()
4195        }
4196    }
4197
4198    /// A switch on a phone: the old camera, interrupted when another opener took it, is
4199    /// released (dropped: no frames, the publication kept); the new source's first frame is a
4200    /// keyframe and the old pause is reported over (`Resumed`): what is sent is what
4201    /// `local_video` says.
4202    #[test]
4203    fn a_released_source_holds_the_pipeline_and_the_next_one_starts_at_a_keyframe() {
4204        let mut cfg = kessel_video::fake::FakeConfig::default();
4205        cfg.source_events = vec![(
4206            Duration::from_millis(400),
4207            SourceEvent::Interrupted(kessel_video::Interruption::InUseByAnother),
4208        )];
4209        let old_backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4210        let backend: Arc<dyn VideoBackend> = HwFake::new(kessel_video::fake::FakeConfig::default());
4211        let bell = Arc::new(Bell::default());
4212        let src = fake_camera(&old_backend, &bell);
4213        let mut p = TestPipe::start(&backend, src, &bell);
4214        let _ = collect_until(&mut p.rx, "the first frames", 3);
4215        assert!(matches!(
4216            p.next_note("the old camera's pause"),
4217            CaptureEvent::Paused(_)
4218        ));
4219
4220        let (tx, done) = std::sync::mpsc::channel();
4221        p.send(ToPipe::Release(tx));
4222        done.recv_timeout(Duration::from_secs(5))
4223            .expect("the pipeline drops the source and says so");
4224        p.assert_quiet("no frame while released");
4225        assert!(
4226            p.thread.as_ref().is_some_and(|t| !t.is_finished()),
4227            "the publication is kept"
4228        );
4229
4230        let next = fake_camera(&backend, &bell);
4231        p.send(ToPipe::Source(
4232            next,
4233            vec![LayerSpec::new("q", 320, 180, 150, 30)],
4234            Facing::Back,
4235        ));
4236        assert_eq!(
4237            p.next_note("the pause reported over"),
4238            CaptureEvent::Resumed
4239        );
4240        let back = collect_until(&mut p.rx, "the new camera's frames", 4);
4241        assert!(back[0], "the new camera starts at a keyframe: {back:?}");
4242        assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
4243        p.finish();
4244    }
4245
4246    /// A switch to a running source (no pause before): its first frame is a keyframe too,
4247    /// and no note is sent.
4248    #[test]
4249    fn a_switched_source_starts_at_a_keyframe() {
4250        let backend: Arc<dyn VideoBackend> = HwFake::new(kessel_video::fake::FakeConfig::default());
4251        let bell = Arc::new(Bell::default());
4252        let src = fake_camera(&backend, &bell);
4253        let mut p = TestPipe::start(&backend, src, &bell);
4254        let first = collect_until(&mut p.rx, "the first frames", 6);
4255        assert!(first[0] && first[1..].iter().all(|k| !k), "{first:?}");
4256        let (tx, done) = std::sync::mpsc::channel();
4257        p.send(ToPipe::Release(tx));
4258        done.recv_timeout(Duration::from_secs(5)).expect("released");
4259        p.assert_quiet("no frame while released");
4260        let next = fake_camera(&backend, &bell);
4261        p.send(ToPipe::Source(
4262            next,
4263            vec![LayerSpec::new("q", 320, 180, 150, 30)],
4264            Facing::Back,
4265        ));
4266        let back = collect_until(&mut p.rx, "the new camera's frames", 4);
4267        assert!(back[0], "the switch starts at a keyframe: {back:?}");
4268        let mut notes = Vec::new();
4269        while let Ok(n) = p.notes.try_recv() {
4270            notes.push(n.event);
4271        }
4272        assert!(
4273            !notes.iter().any(is_state),
4274            "no pause, no resume: {notes:?}"
4275        );
4276        p.finish();
4277    }
4278
4279    /// A switch while the encoder still holds the old camera's last frame (a threaded encoder's
4280    /// pending input): the keyframe goes on the new camera's first frame, not on that old
4281    /// frame (which would leave the new camera's frames as deltas on another picture).
4282    #[test]
4283    fn a_switch_keys_the_new_cameras_first_frame_not_a_pending_old_one() {
4284        let fake = HwFake::new(kessel_video::fake::FakeConfig::default());
4285        fake.lag.store(true, Ordering::SeqCst);
4286        let backend: Arc<dyn VideoBackend> = fake.clone();
4287        let bell = Arc::new(Bell::default());
4288        let src = fake_camera(&backend, &bell);
4289        let mut p = TestPipe::start(&backend, src, &bell);
4290        let _ = timed_until(&mut p.rx, "the first frames", 4);
4291        let (tx, done) = std::sync::mpsc::channel();
4292        p.send(ToPipe::Release(tx));
4293        done.recv_timeout(Duration::from_secs(5)).expect("released");
4294        let released = backend.now_us();
4295        let next = fake_camera(&backend, &bell);
4296        p.send(ToPipe::Source(
4297            next,
4298            vec![LayerSpec::new("q", 320, 180, 150, 30)],
4299            Facing::Back,
4300        ));
4301        let mut got = Vec::new();
4302        let until = std::time::Instant::now() + Duration::from_secs(10);
4303        while got.iter().filter(|(t, _)| *t >= released).count() < 3 {
4304            assert!(
4305                std::time::Instant::now() < until,
4306                "the new camera's frames: {got:?}"
4307            );
4308            got.extend(timed(&mut p.rx));
4309            std::thread::sleep(Duration::from_millis(5));
4310        }
4311        let old: Vec<bool> = got
4312            .iter()
4313            .filter(|(t, _)| *t < released)
4314            .map(|f| f.1)
4315            .collect();
4316        let new: Vec<bool> = got
4317            .iter()
4318            .filter(|(t, _)| *t >= released)
4319            .map(|f| f.1)
4320            .collect();
4321        assert!(
4322            !old.is_empty(),
4323            "the old camera's last frame came out after the switch (the lag): {got:?}"
4324        );
4325        assert!(
4326            new[0],
4327            "the new camera's first frame is a keyframe: {got:?}"
4328        );
4329        assert!(new[1..].iter().all(|k| !k), "one keyframe: {got:?}");
4330        assert!(
4331            !old.iter().any(|k| *k),
4332            "no keyframe on the old camera's last frame: {got:?}"
4333        );
4334        p.finish();
4335    }
4336
4337    /// The frames queued for the engine: `(capture_us, keyframe)`.
4338    fn timed(rx: &mut mpsc::Receiver<super::super::publish::VideoIn>) -> Vec<(u64, bool)> {
4339        let mut out = Vec::new();
4340        while let Ok(f) = rx.try_recv() {
4341            out.push((f.frame.capture_us, f.frame.keyframe));
4342        }
4343        out
4344    }
4345
4346    fn timed_until(
4347        rx: &mut mpsc::Receiver<super::super::publish::VideoIn>,
4348        what: &str,
4349        n: usize,
4350    ) -> Vec<(u64, bool)> {
4351        let until = std::time::Instant::now() + Duration::from_secs(10);
4352        let mut got = Vec::new();
4353        while got.len() < n {
4354            assert!(
4355                std::time::Instant::now() < until,
4356                "timed out waiting for {what}"
4357            );
4358            got.extend(timed(rx));
4359            std::thread::sleep(Duration::from_millis(5));
4360        }
4361        got
4362    }
4363
4364    #[test]
4365    fn phones_capture_at_most_720p() {
4366        assert_eq!(camera_box(1920, 1080, true), (1280, 720));
4367        assert_eq!(camera_box(1080, 1920, true), (720, 1280));
4368        assert_eq!(camera_box(640, 360, true), (640, 360));
4369        assert_eq!(camera_box(1920, 1080, false), (1920, 1080));
4370    }
4371
4372    #[test]
4373    fn encoders_open_from_the_top_and_drop_layers_at_the_instance_limit() {
4374        let mut cfg = kessel_video::fake::FakeConfig::default();
4375        cfg.max_instances = Some(2);
4376        let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4377        let mut cap = caps(&[kessel_video::VideoCodec::H264]).codecs.remove(0);
4378        let plan = vec![
4379            LayerSpec::new("q", 320, 180, 150, 30),
4380            LayerSpec::new("h", 640, 360, 500, 30),
4381            LayerSpec::new("f", 1280, 720, 1700, 30),
4382        ];
4383        let wake = kessel_video::no_wake();
4384        // The backend's limit: f opens, h opens, q fails: drop f and try again (q, h).
4385        let encs = open_encoders(
4386            &backend,
4387            VideoCodec::H264,
4388            &cap,
4389            plan.clone(),
4390            ContentHint::Camera,
4391            &wake,
4392        );
4393        let rids: Vec<&str> = encs.iter().map(|e| e.spec.rid.as_str()).collect();
4394        assert_eq!(rids, vec!["q", "h"]);
4395        drop(encs);
4396        // The capability's limit cuts the plan first.
4397        cap.max_instances = Some(1);
4398        let encs = open_encoders(
4399            &backend,
4400            VideoCodec::H264,
4401            &cap,
4402            plan,
4403            ContentHint::Camera,
4404            &wake,
4405        );
4406        assert_eq!(encs.len(), 1);
4407        assert_eq!(encs[0].spec.rid, "q");
4408    }
4409
4410    /// The next camera tap item within 10 s (a loud failure naming `what` otherwise).
4411    fn tap_item(tap: &super::super::CameraTap, what: &str) -> super::super::CameraTapItem {
4412        tap.recv_timeout(Duration::from_secs(10))
4413            .unwrap_or_else(|| panic!("timed out waiting for {what}"))
4414    }
4415
4416    /// Takes tap items until `n` frames came (within 10 s each): their facings, and every
4417    /// feed seen.
4418    fn tap_frames(
4419        tap: &super::super::CameraTap,
4420        what: &str,
4421        n: usize,
4422    ) -> (Vec<Facing>, Vec<CameraFeed>) {
4423        let mut facings = Vec::new();
4424        let mut feeds = Vec::new();
4425        while facings.len() < n {
4426            match tap_item(tap, what) {
4427                super::super::CameraTapItem::Frame(f) => {
4428                    assert_eq!(f.rotation, 0, "frames come upright");
4429                    facings.push(f.facing);
4430                }
4431                super::super::CameraTapItem::Feed(f) => feeds.push(f),
4432            }
4433        }
4434        (facings, feeds)
4435    }
4436
4437    /// Only feed changes come on the tap for a while: those.
4438    fn tap_quiet(tap: &super::super::CameraTap, what: &str) -> Vec<CameraFeed> {
4439        let until = std::time::Instant::now() + Duration::from_millis(400);
4440        let mut feeds = Vec::new();
4441        while let Some(item) =
4442            tap.recv_timeout(until.saturating_duration_since(std::time::Instant::now()))
4443        {
4444            match item {
4445                super::super::CameraTapItem::Feed(f) => feeds.push(f),
4446                super::super::CameraTapItem::Frame(_) => panic!("{what}: a frame came"),
4447            }
4448        }
4449        feeds
4450    }
4451
4452    /// A camera tap on a published camera: the raw frames with the camera's facing (a switch
4453    /// lands on the new camera's frames), `Paused` and no frame through a background pause,
4454    /// `Live` again after it; with no layer wanted the camera keeps capturing for the tap and
4455    /// nothing is encoded; a closed tap leaves the encoder running; the publication's end is
4456    /// `Off`.
4457    #[test]
4458    fn a_camera_tap_gets_the_published_cameras_raw_frames_and_its_feed() {
4459        let backend: Arc<dyn VideoBackend> = HwFake::new(kessel_video::fake::FakeConfig::default());
4460        let bell = Arc::new(Bell::default());
4461        let src = fake_camera(&backend, &bell);
4462        let mut p = TestPipe::start(&backend, src, &bell);
4463        let _ = collect_until(&mut p.rx, "the first frames", 3);
4464        let tap = p.camera_taps.open();
4465        assert!(matches!(
4466            tap_item(&tap, "the feed"),
4467            super::super::CameraTapItem::Feed(CameraFeed::Live)
4468        ));
4469        let (facings, _) = tap_frames(&tap, "the front camera's frames", 3);
4470        assert!(facings.iter().all(|f| *f == Facing::Front), "{facings:?}");
4471
4472        // The background: Paused, and no frame until the return (a frame taken before the
4473        // pause may still be waiting: it is dropped with the pause).
4474        p.send(ToPipe::Pause(true));
4475        std::thread::sleep(Duration::from_millis(100));
4476        let mut feeds = Vec::new();
4477        while let Some(item) = tap.try_recv() {
4478            if let super::super::CameraTapItem::Feed(f) = item {
4479                feeds.push(f);
4480            }
4481        }
4482        feeds.extend(tap_quiet(&tap, "paused"));
4483        assert_eq!(feeds, vec![CameraFeed::Paused]);
4484        p.send(ToPipe::Pause(false));
4485        let (_, feeds) = tap_frames(&tap, "frames after the return", 2);
4486        assert_eq!(feeds, vec![CameraFeed::Live]);
4487
4488        // A switch to the back camera: its frames say so.
4489        let (tx, done) = std::sync::mpsc::channel();
4490        p.send(ToPipe::Release(tx));
4491        done.recv_timeout(Duration::from_secs(5)).expect("released");
4492        let next = fake_camera(&backend, &bell);
4493        p.send(ToPipe::Source(
4494            next,
4495            vec![LayerSpec::new("q", 320, 180, 150, 30)],
4496            Facing::Back,
4497        ));
4498        let deadline = std::time::Instant::now() + Duration::from_secs(10);
4499        loop {
4500            assert!(std::time::Instant::now() < deadline, "no back camera frame");
4501            let (f, _) = tap_frames(&tap, "the back camera's frames", 1);
4502            if f[0] == Facing::Back {
4503                break;
4504            }
4505        }
4506
4507        // No layer wanted: the tap keeps the camera capturing; nothing is encoded.
4508        p.control(VideoControl::Rates(vec![rate("q", false)]));
4509        p.assert_quiet("no layer wanted: nothing encoded");
4510        let _ = tap_frames(&tap, "frames for the tap alone", 3);
4511
4512        // The tap closes; wanted again, the encoder runs on.
4513        drop(tap);
4514        p.control(VideoControl::Rates(vec![rate("q", true)]));
4515        let _ = collect_until(&mut p.rx, "frames after the tap closed", 3);
4516
4517        // The publication ends: Off.
4518        let last = p.camera_taps.open();
4519        let taps = p.camera_taps.clone();
4520        p.finish();
4521        let mut feeds = Vec::new();
4522        while let Some(item) = last.try_recv() {
4523            if let super::super::CameraTapItem::Feed(f) = item {
4524                feeds.push(f);
4525            }
4526        }
4527        assert_eq!(feeds.last(), Some(&CameraFeed::Off), "{feeds:?}");
4528        drop(last);
4529        assert!(!taps.any());
4530    }
4531
4532    #[test]
4533    fn the_self_view_layer_is_the_cameras_h_and_the_screens_q() {
4534        let q = LayerSpec::new("q", 320, 180, 150, 30);
4535        let h = LayerSpec::new("h", 640, 360, 500, 30);
4536        let f = LayerSpec::new("f", 1280, 720, 1700, 30);
4537        let cam = VideoSource::Camera;
4538        let scr = VideoSource::ScreenShare;
4539        let all = vec![q.clone(), h.clone(), f.clone()];
4540        assert_eq!(self_view_rid(cam, &all).as_deref(), Some("h"));
4541        assert_eq!(self_view_rid(scr, &all).as_deref(), Some("q"));
4542        // No h: the camera's lowest layer at 360p or more; the screen's lowest.
4543        let qf = vec![q.clone(), f.clone()];
4544        assert_eq!(self_view_rid(cam, &qf).as_deref(), Some("f"));
4545        let hf = vec![h.clone(), f];
4546        assert_eq!(self_view_rid(scr, &hf).as_deref(), Some("h"));
4547        // A camera below 360p: its top layer.
4548        assert_eq!(self_view_rid(cam, &[q]).as_deref(), Some("q"));
4549        assert_eq!(self_view_rid(cam, &[]), None);
4550    }
4551
4552    #[test]
4553    fn capture_refusals_keep_the_publish_codes() {
4554        for (e, code) in [
4555            (CaptureError::CameraDenied, "camera_denied"),
4556            (CaptureError::CameraBusy, "camera_busy"),
4557            (CaptureError::CameraNotFound, "camera_not_found"),
4558            (CaptureError::CameraLost, "camera_not_found"),
4559            (CaptureError::CodecUnavailable, "codec_unavailable"),
4560            (CaptureError::Failed(KError::DeviceBusy), "camera_busy"),
4561            (CaptureError::VideoUnsupported, "publish_failed"),
4562        ] {
4563            assert_eq!(capture_error(&e).code(), code, "{e:?}");
4564        }
4565        assert_eq!(VideoError::NoFrames.code(), "no_frames");
4566    }
4567
4568    /// A test camera: its scripted events, frames from `frames_from` on (never with `None`),
4569    /// and a drop that takes `drop_takes` (an OS slow to close the device).
4570    struct Scripted {
4571        events: std::collections::VecDeque<SourceEvent>,
4572        frames_from: Option<std::time::Instant>,
4573        drop_takes: Duration,
4574    }
4575
4576    impl Scripted {
4577        fn new(events: Vec<SourceEvent>, frames_after: Option<Duration>) -> Scripted {
4578            Scripted {
4579                events: events.into(),
4580                frames_from: frames_after.map(|d| std::time::Instant::now() + d),
4581                drop_takes: Duration::ZERO,
4582            }
4583        }
4584    }
4585
4586    impl Drop for Scripted {
4587        fn drop(&mut self) {
4588            std::thread::sleep(self.drop_takes);
4589        }
4590    }
4591
4592    impl FrameSource for Scripted {
4593        fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
4594            if self
4595                .frames_from
4596                .is_some_and(|t| std::time::Instant::now() >= t)
4597            {
4598                kessel_video::VideoFrame::filled(PixelFormat::I420, 64, 36, [16, 128, 128], 0).ok()
4599            } else {
4600                None
4601            }
4602        }
4603        fn try_event(&mut self) -> Option<SourceEvent> {
4604            self.events.pop_front()
4605        }
4606        fn set_constraints(&mut self, _c: CaptureConstraints) -> Result<(), KError> {
4607            Ok(())
4608        }
4609        fn set_paused(&mut self, _paused: bool) {}
4610        fn stats(&self) -> kessel_video::SourceStats {
4611            kessel_video::SourceStats::default()
4612        }
4613    }
4614
4615    /// A camera the OS opens but feeds nothing (a lid-closed MacBook's, suspended): refused
4616    /// with `no_frames` after the watchdog's time, never later.
4617    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4618    async fn a_camera_without_frames_is_no_frames_after_the_watchdog() {
4619        let began = std::time::Instant::now();
4620        let src = Scripted::new(
4621            vec![SourceEvent::Interrupted(
4622                kessel_video::Interruption::Suspended,
4623            )],
4624            None,
4625        );
4626        let r = wait_first_frame(Box::new(src)).await;
4627        assert!(
4628            matches!(r, Err(VideoError::NoFrames)),
4629            "{:?}",
4630            r.as_ref().map(|(_, s)| s)
4631        );
4632        let took = began.elapsed();
4633        assert!(
4634            took >= FIRST_FRAME_WAIT && took < FIRST_FRAME_WAIT + Duration::from_secs(2),
4635            "the watchdog's time: {took:?}"
4636        );
4637    }
4638
4639    /// The first frame is kept for the pipeline, after the events seen before it (a suspension
4640    /// and its resume), and the size is the frame's when no `Started` came.
4641    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4642    async fn the_first_frame_comes_after_the_events_seen_before_it() {
4643        let src = Scripted::new(
4644            vec![
4645                SourceEvent::Interrupted(kessel_video::Interruption::Suspended),
4646                SourceEvent::Resumed,
4647            ],
4648            Some(Duration::from_millis(300)),
4649        );
4650        let (mut primed, size) = wait_first_frame(Box::new(src)).await.expect("a frame");
4651        assert_eq!(size, (64, 36));
4652        assert!(primed.try_recv().is_none(), "the events first");
4653        assert_eq!(
4654            primed.try_event(),
4655            Some(SourceEvent::Interrupted(
4656                kessel_video::Interruption::Suspended
4657            ))
4658        );
4659        assert_eq!(primed.try_event(), Some(SourceEvent::Resumed));
4660        assert_eq!(primed.try_event(), None);
4661        let f = primed.try_recv().expect("the kept first frame");
4662        assert_eq!((f.width, f.height), (64, 36));
4663        // A source that ends before its first frame is `camera_not_found`.
4664        let ended = Scripted::new(
4665            vec![SourceEvent::Ended(kessel_video::EndReason::DeviceLost)],
4666            None,
4667        );
4668        assert!(matches!(
4669            wait_first_frame(Box::new(ended)).await,
4670            Err(VideoError::CameraNotFound)
4671        ));
4672    }
4673
4674    /// A pipeline whose camera closes slowly (its drop waits on the OS) stops within
4675    /// [`STOP_WAIT`]: the stop never waits on the device; the close finishes on its own thread.
4676    #[test]
4677    fn a_pipeline_whose_camera_closes_slowly_stops_within_the_bound() {
4678        let stop = Arc::new(AtomicBool::new(false));
4679        let s2 = Arc::clone(&stop);
4680        let thread = std::thread::spawn(move || {
4681            let mut src = Scripted::new(Vec::new(), None);
4682            src.drop_takes = Duration::from_secs(8);
4683            while !s2.load(Ordering::SeqCst) {
4684                std::thread::sleep(Duration::from_millis(5));
4685            }
4686            drop(src);
4687        });
4688        let (to_pipe, _from) = std::sync::mpsc::channel();
4689        let cap = caps(&[kessel_video::VideoCodec::Vp8]).codecs[0].clone();
4690        let r = Running {
4691            call: 1,
4692            stop,
4693            ended: Arc::new(AtomicBool::new(false)),
4694            bell: Arc::new(Bell::default()),
4695            to_pipe,
4696            thread: Some(thread),
4697            codec: VideoCodec::Vp8,
4698            live: Arc::new(Mutex::new(VideoCodec::Vp8)),
4699            cap,
4700            layers: Vec::new(),
4701            size: (640, 360),
4702            device: None,
4703            temporal: None,
4704            held: Arc::default(),
4705        };
4706        let began = std::time::Instant::now();
4707        r.stop();
4708        let took = began.elapsed();
4709        assert!(
4710            took >= STOP_WAIT && took < STOP_WAIT + Duration::from_secs(1),
4711            "the stop waited {took:?}"
4712        );
4713    }
4714}