Skip to main content

sew_call_client/video/
publish.rs

1//! Publishing video: the camera (and later the screen share) as the engine sends it.
2//!
3//! The engine core never names kessel-video. A producer (the `VideoBridge`, or a host with its
4//! own codecs) hands it encoded plaintext frames, one per simulcast layer
5//! ([`VideoPublication::push`]), and follows the engine's [`VideoControl`]s: keyframes the SFU
6//! asks for, which layers run at what rate (dynacast and the bandwidth split), a republish
7//! after a policy change, and the end of the publication.
8//!
9//! In order, for one publication:
10//! 1. **The lease** ([`crate::Call::set_video_lease`]): `POST /api/v1/me/voice/state` with
11//!    `self_video` (camera) or `self_stream` (screen share). Sew's refusals map to the
12//!    [`VideoError`] codes (`video_slots_full`, `media_busy` with its `Retry-After`,
13//!    `media_capacity`, `video_disabled`).
14//! 2. **The publication** ([`crate::Call::publish_video`]): an `AddTrackRequest` with the
15//!    layers that opened (`VideoLayer` q/h/f as LOW/MEDIUM/HIGH, bitrate = the layer's cap),
16//!    `simulcast_codecs` naming the codec (receivers learn it from there) and GCM, through the
17//!    publish check (`e2ee::check_publish`: no lease, no video). On `TrackPublished` the keys
18//!    must confirm GCM (else `e2ee_downgraded`); then a sendonly `m=video` with
19//!    `a=rid:<rid> send` and `a=simulcast:send` for those layers, and a renegotiation.
20//! 3. **Frames:** for each layer's encoded frame: H.264 normalised (4-byte start codes, no AUD)
21//!    and checked (an IDR has SPS and PPS before it; a violation is logged once and the frame
22//!    dropped), the RTP timestamp from the capture time (`capture_us × 90 / 1000` from a random
23//!    base, the same on every layer), encrypted with LkGcm under the layer's SSRC, packetised
24//!    (VP8 RFC 7741 with the T field always written, H.264 mode 1 at MTU 1200), a Dependency
25//!    Descriptor on every packet, written nackable (str0m answers NACKs over RTX).
26//! 4. **Keyframes:** the SFU's PLI or FIR for a layer, at most one per 300 ms; also for a layer
27//!    that starts again (dynacast, the split) and after a renegotiated send section.
28//! 5. **Dynacast:** `SubscribedQualityUpdate` sets which layers anyone wants; the others get no
29//!    frames (their encoders stay open). Ignored with the policy's `dynacast: false`.
30//! 6. **The split** (`video/alloc.rs`): str0m's estimate over the layers, with hysteresis; the
31//!    desired bitrate (str0m probes up to it) is the estimate at which every wanted layer runs
32//!    at its cap with the raise margin. A layer never runs below its size's floor.
33//! 7. **Policy updates:** new caps for the same layers apply in place; a new layer set (a tier
34//!    change) republishes the track with the new layers, keeping the lease; video turned off
35//!    unpublishes and releases the lease.
36//! 8. **The end:** [`crate::Call::unpublish_video`] makes the send section inactive (the SFU
37//!    unpublishes the track) and releases the lease when asked. A full reconnect publishes
38//!    again on the new PC; a re-join takes the lease again first.
39//!
40//! **A backup codec** ([`VideoPublish::with_backup`]: an H.264 publication with a VP8 backup):
41//! one `AddTrackRequest` with two `simulcast_codecs` entries, each on its own cid, and two
42//! sendonly `m=video` sections in the same offer (each with its own msid track, rids and
43//! simulcast). Each codec is a lane with its own layers, SSRCs, packetisers and keyframe
44//! state; a frame goes to the lane of its codec. The SFU gives each subscriber the codec its
45//! answer decodes and asks for the backup only while someone gets it: the backup lane reads
46//! only its own `subscribed_codecs` entry, and the producer hears
47//! [`VideoControl::BackupStart`] (open the backup's encoders, the first frame a keyframe),
48//! [`VideoControl::BackupRates`], [`VideoControl::BackupKeyframe`] and
49//! [`VideoControl::BackupStop`] (close them; the section stays negotiated, without RTP). Both
50//! lanes share one bandwidth budget; the backup's lowest layer starts without the raise
51//! hysteresis. One GCM check of the track covers both sections; the same keys seal both lanes
52//! (distinct SSRCs, so no IV repeats). A producer that can't run its backup, or lost its
53//! primary codec, publishes again in one codec ([`VideoPublication::republish_without_backup`]).
54
55use std::collections::BTreeMap;
56use std::sync::{Arc, Mutex};
57use std::time::{Duration, Instant};
58
59use bytes::Bytes;
60use serde::Serialize;
61use sew_lk_compat::Session;
62use sew_lkproto::livekit::{
63    AddTrackRequest, SimulcastCodec, SubscribedQualityUpdate, TrackInfo, TrackSource, TrackType,
64    VideoLayer,
65};
66use sew_proto::voice::{MediaPolicy, TrackHint};
67use tokio::sync::{broadcast, mpsc, oneshot};
68
69use super::alloc::{AllocLayer, Allocator};
70use super::rtp::MTU;
71use super::rtp::h264::H264Sender;
72use super::rtp::normalise::{check, normalise};
73use super::rtp::vp8::{FrameLayer, Vp8Sender, Vp8Starts};
74use super::types::{VideoCodec, VideoSource};
75use crate::call::CallEvent;
76use crate::e2ee::{KeySession, Leases, PublishRefused, VideoFrameCodec, check_publish};
77use crate::pc::{BWE_INITIAL_BPS, Pc};
78
79/// Encoded frames the engine's video queue holds (all layers of all publications).
80pub(crate) const VIDEO_QUEUE: usize = 96;
81/// `local_video`'s reason when the app unpublished ([`crate::Call::unpublish_video`]).
82pub(crate) const UNPUBLISHED: &str = "unpublished";
83/// `local_video`'s reason when the publication's `TrackPublished` came with nobody waiting for
84/// its handle (the caller of [`crate::Call::publish_video`] gave up).
85pub(crate) const PUBLISHER_GONE: &str = "publisher_gone";
86/// How long a publication waits for the SFU's `TrackPublished`.
87const PUBLISH_TIMEOUT: Duration = Duration::from_secs(10);
88/// Keyframe requests for one layer closer than this coalesce while the keyframe asked for
89/// hasn't gone out yet.
90const KEYFRAME_EVERY: Duration = Duration::from_millis(300);
91
92/// LiveKit's mime type of a codec (`video/VP8`, `video/H264`).
93fn mime(c: VideoCodec) -> &'static str {
94    match c {
95        VideoCodec::Vp8 => "video/VP8",
96        VideoCodec::H264 => "video/H264",
97    }
98}
99
100fn frame_codec(c: VideoCodec) -> VideoFrameCodec {
101    match c {
102        VideoCodec::Vp8 => VideoFrameCodec::Vp8,
103        VideoCodec::H264 => VideoFrameCodec::H264,
104    }
105}
106
107/// The codec of Sew's policy value, if the engine sends it (VP8, H.264).
108pub(crate) fn codec_of_policy(c: sew_proto::voice::VideoCodec) -> Option<VideoCodec> {
109    match c {
110        sew_proto::voice::VideoCodec::Vp8 => Some(VideoCodec::Vp8),
111        sew_proto::voice::VideoCodec::H264 => Some(VideoCodec::H264),
112        _ => None,
113    }
114}
115
116fn track_source(s: VideoSource) -> TrackSource {
117    match s {
118        VideoSource::Camera => TrackSource::Camera,
119        VideoSource::ScreenShare => TrackSource::ScreenShare,
120    }
121}
122
123fn track_name(s: VideoSource) -> &'static str {
124    match s {
125        VideoSource::Camera => "camera",
126        VideoSource::ScreenShare => "screen",
127    }
128}
129
130/// The policy's hints for a source.
131pub(crate) fn hint_of(s: VideoSource, policy: &MediaPolicy) -> &TrackHint {
132    match s {
133        VideoSource::Camera => &policy.camera,
134        VideoSource::ScreenShare => &policy.screen,
135    }
136}
137
138fn allowed(s: VideoSource, policy: &MediaPolicy) -> bool {
139    match s {
140        VideoSource::Camera => policy.camera_allowed,
141        VideoSource::ScreenShare => policy.screen_allowed,
142    }
143}
144
145/// One simulcast layer of a publication.
146#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
147#[non_exhaustive]
148pub struct LayerSpec {
149    /// `q`, `h` or `f`.
150    pub rid: String,
151    /// Coded width (even).
152    pub width: u32,
153    /// Coded height (even).
154    pub height: u32,
155    /// The layer's cap, kbit/s.
156    pub max_kbps: u32,
157    /// Frame rate.
158    pub fps: u32,
159    /// Temporal layers the encoder makes (1 to 3; VP8 only above 1).
160    pub temporal_layers: u8,
161}
162
163impl LayerSpec {
164    /// A layer with one temporal layer.
165    pub fn new(rid: &str, width: u32, height: u32, max_kbps: u32, fps: u32) -> LayerSpec {
166        LayerSpec {
167            rid: rid.to_owned(),
168            width,
169            height,
170            max_kbps,
171            fps,
172            temporal_layers: 1,
173        }
174    }
175}
176
177fn even(v: u64) -> u32 {
178    u32::try_from(v & !1).unwrap_or(u32::MAX - 1)
179}
180
181/// The layers of `hint` for a capture of `capture_width × capture_height`, lowest first. A
182/// hint layer's `height` is its short side (`180p`, `360p`, `720p`): each layer whose short side
183/// is at most the capture's, the long side scaled to the capture's aspect (even), in the
184/// capture's orientation (a portrait phone camera gets portrait layers, 180 × 320 rather than
185/// 100 × 180), at the hint's frame rate. A capture smaller than every layer gets the lowest one
186/// at the capture's size.
187pub fn plan_layers(hint: &TrackHint, capture_width: u32, capture_height: u32) -> Vec<LayerSpec> {
188    let (cw, ch) = (capture_width.max(2), capture_height.max(2));
189    let portrait = ch > cw;
190    let (short, long) = if portrait { (cw, ch) } else { (ch, cw) };
191    let fps = hint.max_fps.max(1);
192    let mut out: Vec<LayerSpec> = hint
193        .layers
194        .iter()
195        .filter(|l| l.height <= short && l.height > 0)
196        .map(|l| {
197            let s = even(u64::from(l.height));
198            let g = even(u64::from(l.height) * u64::from(long) / u64::from(short)).max(2);
199            let (width, height) = if portrait { (s, g) } else { (g, s) };
200            LayerSpec::new(&l.rid, width, height, l.max_kbps, fps)
201        })
202        .collect();
203    if out.is_empty()
204        && let Some(l) = hint.layers.first()
205    {
206        out.push(LayerSpec::new(
207            &l.rid,
208            even(cw.into()),
209            even(ch.into()),
210            l.max_kbps,
211            fps,
212        ));
213    }
214    out
215}
216
217/// The layers of a screen share for a capture of `capture_width × capture_height`, lowest
218/// first: [`plan_layers`], and on top the capture's own size when the hint has a layer above
219/// the top one that fits (a 1366×768 or 1440×900 display under a 1080p hint), so that a viewer
220/// who zooms in gets the screen's real pixels rather than a downscaled copy. That layer takes
221/// the larger hint layer's rid and frame rate, and its cap scaled to the capture's pixels
222/// (never below the layer under it). A capture within a quarter of the top fitting layer's
223/// short side keeps [`plan_layers`]' layers (a near copy would spend the uplink for nothing);
224/// so does a capture smaller than every layer (its one layer is already the capture's size).
225/// The capture is within the hint's `max_width × max_height` already (the capture
226/// constraints).
227pub fn plan_screen_layers(
228    hint: &TrackHint,
229    capture_width: u32,
230    capture_height: u32,
231) -> Vec<LayerSpec> {
232    let mut out = plan_layers(hint, capture_width, capture_height);
233    let (cw, ch) = (
234        even(capture_width.max(2).into()),
235        even(capture_height.max(2).into()),
236    );
237    let short = cw.min(ch);
238    let Some(top) = out.last() else {
239        return out;
240    };
241    let top_short = top.width.min(top.height);
242    if u64::from(short) * 4 <= u64::from(top_short) * 5 {
243        return out;
244    }
245    // The lowest hint layer the capture is too small for.
246    let Some(next) = hint.layers.iter().find(|l| l.height > short) else {
247        return out;
248    };
249    let hint_short = u64::from(next.height);
250    let scaled =
251        u64::from(next.max_kbps) * u64::from(short) * u64::from(short) / (hint_short * hint_short);
252    let max_kbps = u32::try_from(scaled)
253        .unwrap_or(next.max_kbps)
254        .max(top.max_kbps);
255    let fps = top.fps;
256    out.push(LayerSpec::new(&next.rid, cw, ch, max_kbps, fps));
257    out
258}
259
260/// The layers of `source` for a capture of `width × height`: [`plan_screen_layers`] for a
261/// screen share, [`plan_layers`] for a camera.
262pub(crate) fn plan_source_layers(
263    source: VideoSource,
264    hint: &TrackHint,
265    width: u32,
266    height: u32,
267) -> Vec<LayerSpec> {
268    match source {
269        VideoSource::Camera => plan_layers(hint, width, height),
270        VideoSource::ScreenShare => plan_screen_layers(hint, width, height),
271    }
272}
273
274/// What to publish ([`crate::Call::publish_video`]).
275#[derive(Clone, Debug, PartialEq, Eq)]
276#[non_exhaustive]
277pub struct VideoPublish {
278    /// Camera or screen.
279    pub source: VideoSource,
280    /// The codec of every layer.
281    pub codec: VideoCodec,
282    /// The layers whose encoders opened, lowest first ([`plan_layers`]).
283    pub layers: Vec<LayerSpec>,
284    /// The capture's size (a policy update plans new layers from it).
285    pub capture_width: u32,
286    /// The capture's height.
287    pub capture_height: u32,
288    /// A backup codec beside the primary ([`VideoPublish::with_backup`]); `None`: one codec.
289    pub backup: Option<BackupSpec>,
290}
291
292/// A publication's backup codec ([`VideoPublish::with_backup`]): VP8 beside an H.264 primary,
293/// negotiated at publish and run only while some subscriber needs it.
294#[derive(Clone, Debug, PartialEq, Eq)]
295#[non_exhaustive]
296pub struct BackupSpec {
297    /// The backup's codec (VP8).
298    pub codec: VideoCodec,
299    /// Its layers, lowest first (the primary's rids and sizes, or fewer: a phone's stop at
300    /// 360p). Quality LOW/MEDIUM/HIGH by position, as the primary's.
301    pub layers: Vec<LayerSpec>,
302}
303
304impl BackupSpec {
305    /// A backup of `layers` in `codec`.
306    pub fn new(codec: VideoCodec, layers: Vec<LayerSpec>) -> BackupSpec {
307        BackupSpec { codec, layers }
308    }
309}
310
311impl VideoPublish {
312    /// A publication of `layers` in `codec` from a capture of `capture_width × capture_height`.
313    pub fn new(
314        source: VideoSource,
315        codec: VideoCodec,
316        layers: Vec<LayerSpec>,
317        capture_width: u32,
318        capture_height: u32,
319    ) -> VideoPublish {
320        VideoPublish {
321            source,
322            codec,
323            layers,
324            capture_width,
325            capture_height,
326            backup: None,
327        }
328    }
329
330    /// With a backup codec: its section is negotiated with the primary's, and the producer
331    /// runs it only between [`VideoControl::BackupStart`] and [`VideoControl::BackupStop`]. A
332    /// backup in the primary's codec, or without layers, is ignored.
333    pub fn with_backup(mut self, backup: BackupSpec) -> VideoPublish {
334        self.backup = Some(backup);
335        self
336    }
337}
338
339/// One encoded plaintext frame of one layer (the engine encrypts it).
340#[derive(Clone, Debug, PartialEq, Eq)]
341#[non_exhaustive]
342pub struct EncodedVideo {
343    /// The layer.
344    pub rid: String,
345    /// The codec.
346    pub codec: VideoCodec,
347    /// VP8: one frame; H.264: one access unit (normalised by the engine).
348    pub data: Bytes,
349    /// A keyframe.
350    pub keyframe: bool,
351    /// The capture time, µs (the same for every layer of one capture).
352    pub capture_us: u64,
353    /// VP8: the temporal layer (0 = base).
354    pub temporal_id: u8,
355    /// VP8: RFC 7741's Y bit.
356    pub layer_sync: bool,
357    /// Coded width.
358    pub width: u32,
359    /// Coded height.
360    pub height: u32,
361}
362
363impl EncodedVideo {
364    /// A frame of layer `rid` on the base temporal layer.
365    pub fn new(
366        rid: &str,
367        codec: VideoCodec,
368        data: Bytes,
369        keyframe: bool,
370        capture_us: u64,
371        width: u32,
372        height: u32,
373    ) -> EncodedVideo {
374        EncodedVideo {
375            rid: rid.to_owned(),
376            codec,
377            data,
378            keyframe,
379            capture_us,
380            temporal_id: 0,
381            layer_sync: keyframe,
382            width,
383            height,
384        }
385    }
386
387    /// With its temporal layer (VP8).
388    pub fn with_layer(mut self, temporal_id: u8, layer_sync: bool) -> EncodedVideo {
389        self.temporal_id = temporal_id;
390        self.layer_sync = layer_sync;
391        self
392    }
393}
394
395/// One layer's run state ([`VideoControl::Rates`]).
396#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
397#[non_exhaustive]
398pub struct LayerRate {
399    /// The layer.
400    pub rid: String,
401    /// Frames are sent: someone wants it (dynacast) and the estimate covers it.
402    pub active: bool,
403    /// Its encoder's bitrate, bit/s (0 when inactive).
404    pub bitrate_bps: u32,
405    /// Its frame rate.
406    pub fps: u32,
407}
408
409/// What the engine tells the producer of a publication.
410#[derive(Clone, Debug, PartialEq, Eq)]
411#[non_exhaustive]
412pub enum VideoControl {
413    /// The next frame of this layer must be a keyframe.
414    Keyframe {
415        /// The layer.
416        rid: String,
417    },
418    /// Which layers run, at what rates (only active layers need frames).
419    Rates(Vec<LayerRate>),
420    /// The policy changed the layer set: the producer moves its encoders to these layers (the
421    /// engine republishes the track; the lease is kept).
422    Republish(Vec<LayerSpec>),
423    /// The publication ended (`unpublished`, `video_disabled`, `server_unpublished`,
424    /// `lease_lost`, …): close the source and the encoders.
425    Ended {
426        /// Why.
427        reason: String,
428    },
429    /// The backup is needed (a subscriber gets it): open its encoders for these layers and send
430    /// its frames (in its codec), the first a keyframe. Only for a publication with a backup.
431    BackupStart(Vec<LayerSpec>),
432    /// Which backup layers run, at what rates (a layer active without an encoder yet: open it,
433    /// from the backup's layers, the first frame a keyframe).
434    BackupRates(Vec<LayerRate>),
435    /// The next frame of this backup layer must be a keyframe.
436    BackupKeyframe {
437        /// The backup layer.
438        rid: String,
439    },
440    /// Nobody needs the backup now: stop its frames and close its encoders.
441    BackupStop,
442}
443
444/// Why a lease or a publication failed: [`VideoError::code`] is the plugin's error code.
445#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
446#[non_exhaustive]
447pub enum VideoError {
448    /// The join's policy has video off, or this session may not hold the lease
449    /// (`camera_allowed` / `screen_allowed`).
450    #[error("video_not_allowed")]
451    NotAllowed,
452    /// Sew refused: `[voice.video] enabled = false` (`403 policy_denied video_disabled`).
453    #[error("video_disabled")]
454    Disabled,
455    /// The room's camera cap (`422 video_slots_full`).
456    #[error("video_slots_full")]
457    VideoSlotsFull,
458    /// The room's screen-share cap (`422 screen_slots_full`).
459    #[error("screen_slots_full")]
460    ScreenSlotsFull,
461    /// The media budget refuses new video now (`503 media_busy`).
462    #[error("media_busy")]
463    MediaBusy {
464        /// `Retry-After`, seconds.
465        retry_after: Option<u64>,
466    },
467    /// The install's video publisher cap (`503 media_capacity`).
468    #[error("media_capacity")]
469    MediaCapacity,
470    /// No lease for the source (the publish check).
471    #[error("no_lease")]
472    NoLease,
473    /// The SFU answered the publication without GCM: refused for the rest of the call.
474    #[error("e2ee_downgraded")]
475    Downgraded,
476    /// No encoder for any codec the policy allows (or no layer opened).
477    #[error("codec_unavailable")]
478    CodecUnavailable,
479    /// The camera permission is denied or restricted.
480    #[error("camera_denied")]
481    CameraDenied,
482    /// Another app holds the camera.
483    #[error("camera_busy")]
484    CameraBusy,
485    /// No such camera.
486    #[error("camera_not_found")]
487    CameraNotFound,
488    /// The camera opened but gave no frame in time (2.5 s): nothing was published, the camera
489    /// closed and the lease released.
490    #[error("no_frames")]
491    NoFrames,
492    /// The source already has a publication.
493    #[error("already_published")]
494    AlreadyPublished,
495    /// The source has no publication.
496    #[error("not_published")]
497    NotPublished,
498    /// The SFU refused the publication or did not answer in time.
499    #[error("publish_failed: {0}")]
500    PublishFailed(String),
501    /// Sew refused the lease for another reason (`code`, the HTTP status), or the door could
502    /// not be reached (status 0).
503    #[error("lease_failed: {status} {code}")]
504    Lease {
505        /// The HTTP status.
506        status: u16,
507        /// Sew's `error.code` (or the transport's failure).
508        code: String,
509    },
510    /// The call is over.
511    #[error("ended")]
512    Ended,
513}
514
515impl VideoError {
516    /// The stable code (the plugin's `{code}`).
517    pub fn code(&self) -> &'static str {
518        match self {
519            VideoError::NotAllowed => "video_not_allowed",
520            VideoError::Disabled => "video_disabled",
521            VideoError::VideoSlotsFull => "video_slots_full",
522            VideoError::ScreenSlotsFull => "screen_slots_full",
523            VideoError::MediaBusy { .. } => "media_busy",
524            VideoError::MediaCapacity => "media_capacity",
525            VideoError::NoLease => "no_lease",
526            VideoError::Downgraded => "e2ee_downgraded",
527            VideoError::CodecUnavailable => "codec_unavailable",
528            VideoError::CameraDenied => "camera_denied",
529            VideoError::CameraBusy => "camera_busy",
530            VideoError::CameraNotFound => "camera_not_found",
531            VideoError::NoFrames => "no_frames",
532            VideoError::AlreadyPublished => "already_published",
533            VideoError::NotPublished => "not_published",
534            VideoError::PublishFailed(_) => "publish_failed",
535            VideoError::Lease { .. } => "lease_failed",
536            VideoError::Ended => "ended",
537        }
538    }
539
540    /// Sew's refusal of a lease as the error a host shows.
541    pub(crate) fn from_lease(r: &crate::api::LeaseRefused) -> VideoError {
542        use sew_proto::voice::reasons as vr;
543        match (r.status, r.reason.as_deref()) {
544            (_, Some(vr::VIDEO_SLOTS_FULL)) => VideoError::VideoSlotsFull,
545            (_, Some(vr::SCREEN_SLOTS_FULL)) => VideoError::ScreenSlotsFull,
546            (_, Some(vr::MEDIA_BUSY)) => VideoError::MediaBusy {
547                retry_after: r.retry_after,
548            },
549            (_, Some(vr::MEDIA_CAPACITY)) => VideoError::MediaCapacity,
550            (_, Some(vr::VIDEO_DISABLED)) => VideoError::Disabled,
551            (status, _) => VideoError::Lease {
552                status,
553                code: r
554                    .code
555                    .clone()
556                    .unwrap_or_else(|| r.detail.clone())
557                    .chars()
558                    .take(64)
559                    .collect(),
560            },
561        }
562    }
563}
564
565/// The local video's state ([`CallEvent::LocalVideo`]).
566#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
567#[non_exhaustive]
568pub struct LocalVideo {
569    /// Camera or screen.
570    pub source: VideoSource,
571    /// Published now.
572    pub on: bool,
573    /// Why it went off (`video_disabled`, `server_unpublished`, `lease_lost`, …).
574    pub reason: Option<String>,
575}
576
577impl LocalVideo {
578    /// `source` on or off, and why.
579    pub fn new(source: VideoSource, on: bool, reason: Option<String>) -> LocalVideo {
580        LocalVideo { source, on, reason }
581    }
582}
583
584/// The send-side video counters ([`crate::Call::video_stats`]).
585#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
586#[non_exhaustive]
587pub struct VideoSendStats {
588    /// Frames encrypted and sent, per `source/rid`.
589    pub frames_sent: BTreeMap<String, u64>,
590    /// Packets written.
591    pub packets_sent: u64,
592    /// Keyframes sent.
593    pub keyframes_sent: u64,
594    /// Frames not sent: the layer paused (dynacast or the split), no send path yet, no key,
595    /// waiting for a keyframe, or the producer's queue full.
596    pub frames_not_sent: u64,
597    /// H.264 access units that broke the bitstream rules (dropped).
598    pub malformed: u64,
599    /// Keyframes asked of the producer (the SFU's requests, resumes).
600    pub keyframes_asked: u64,
601    /// The SFU's keyframe requests (PLI and FIR).
602    pub sfu_keyframe_requests: u64,
603    /// The SFU's keyframe requests per `source/rid` (`source/backup/rid` for a backup's layer;
604    /// a request naming no layer counts on each of its section's layers).
605    pub sfu_keyframe_requests_by_layer: BTreeMap<String, u64>,
606    /// Republications after a policy change (or a fall back to one codec).
607    pub republishes: u64,
608    /// The latest send-side estimate, bit/s.
609    pub estimate_bps: u64,
610    /// Frames sent per codec (`vp8`, `h264`), every source and layer (`frames_sent` keys a
611    /// backup's layers `source/backup/rid`).
612    pub frames_by_codec: BTreeMap<String, u64>,
613    /// Keyframes sent per codec.
614    pub keyframes_by_codec: BTreeMap<String, u64>,
615    /// Times a backup started (some subscriber needed it).
616    pub backup_starts: u64,
617    /// Times a backup stopped (nobody needed it, a republish).
618    pub backup_stops: u64,
619    /// How long the backups have run in all, ms.
620    pub backup_ms: u64,
621}
622
623/// One frame for the engine (the queue between producers and the engine).
624#[derive(Debug)]
625pub(crate) struct VideoIn {
626    pub(crate) publication: u64,
627    pub(crate) frame: EncodedVideo,
628}
629
630/// A live publication's handle ([`crate::Call::publish_video`]): push frames, follow controls.
631#[derive(Debug)]
632pub struct VideoPublication {
633    source: VideoSource,
634    id: u64,
635    track_sid: String,
636    published_mime: String,
637    frames: mpsc::Sender<VideoIn>,
638    control: mpsc::UnboundedReceiver<VideoControl>,
639    stats: Arc<Mutex<VideoSendStats>>,
640    ends: mpsc::UnboundedSender<ProducerEnd>,
641    fallbacks: mpsc::UnboundedSender<ProducerFallback>,
642}
643
644impl VideoPublication {
645    /// Camera or screen.
646    pub fn source(&self) -> VideoSource {
647        self.source
648    }
649
650    /// The SFU's track sid.
651    pub fn track_sid(&self) -> &str {
652        &self.track_sid
653    }
654
655    /// The codec the SFU confirmed in its `TrackPublished` (the track's mime type, e.g.
656    /// `video/H264`; its first simulcast codec's when the track's own is empty; empty when
657    /// the SFU named none).
658    pub fn published_mime(&self) -> &str {
659        &self.published_mime
660    }
661
662    /// Queues one encoded frame. Never blocks: a full queue drops it (and counts it).
663    pub fn push(&self, frame: EncodedVideo) {
664        self.sender().push(frame);
665    }
666
667    /// A cloneable frame sender (for an encoder thread).
668    pub fn sender(&self) -> VideoSender {
669        VideoSender {
670            id: self.id,
671            frames: self.frames.clone(),
672            stats: self.stats.clone(),
673        }
674    }
675
676    /// The next control, if one is queued.
677    pub fn try_control(&mut self) -> Option<VideoControl> {
678        self.control.try_recv().ok()
679    }
680
681    /// The next control (`None`: the call is gone).
682    pub async fn control(&mut self) -> Option<VideoControl> {
683        self.control.recv().await
684    }
685
686    /// The producer can't go on (its source ended, its encoders are gone): the engine
687    /// unpublishes the track, releases its lease and says `local_video` off with `reason`
688    /// (`source_ended:<why>`, `encoder_failed:<code>`, …). The producer then gets
689    /// [`VideoControl::Ended`].
690    pub fn end(&self, reason: &str) {
691        let _ = self.ends.send(ProducerEnd {
692            publication: self.id,
693            reason: reason.to_owned(),
694        });
695    }
696
697    /// The producer can't run its backup (its encoders don't open), or lost its primary
698    /// codec's encoder (the hardware went): the engine publishes the track again in `codec`
699    /// alone with `layers`, under the same lease, so no subscriber is promised a codec that
700    /// never comes. The producer then gets [`VideoControl::Republish`] with those layers and
701    /// sends frames in `codec`.
702    pub fn republish_without_backup(&self, codec: VideoCodec, layers: Vec<LayerSpec>) {
703        let _ = self.fallbacks.send(ProducerFallback {
704            publication: self.id,
705            codec,
706            layers,
707        });
708    }
709}
710
711/// A producer's [`VideoPublication::end`], for the engine.
712#[derive(Debug)]
713pub(crate) struct ProducerEnd {
714    pub(crate) publication: u64,
715    pub(crate) reason: String,
716}
717
718/// A producer's [`VideoPublication::republish_without_backup`], for the engine.
719#[derive(Debug)]
720pub(crate) struct ProducerFallback {
721    pub(crate) publication: u64,
722    pub(crate) codec: VideoCodec,
723    pub(crate) layers: Vec<LayerSpec>,
724}
725
726#[cfg(all(test, feature = "video-core"))]
727impl VideoPublication {
728    /// A publication outside an engine: its frames on the receiver, its controls from the
729    /// sender (the bridge's pipeline tests).
730    pub(crate) fn for_test(
731        source: VideoSource,
732    ) -> (
733        VideoPublication,
734        mpsc::Receiver<VideoIn>,
735        mpsc::UnboundedSender<VideoControl>,
736    ) {
737        let (p, rx, ctl, _) = VideoPublication::for_test_with_ends(source);
738        (p, rx, ctl)
739    }
740
741    /// [`VideoPublication::for_test`] with the producer's [`VideoPublication::end`]s, as
742    /// `(publication id, reason)`.
743    #[allow(clippy::type_complexity)]
744    pub(crate) fn for_test_with_ends(
745        source: VideoSource,
746    ) -> (
747        VideoPublication,
748        mpsc::Receiver<VideoIn>,
749        mpsc::UnboundedSender<VideoControl>,
750        mpsc::UnboundedReceiver<ProducerEnd>,
751    ) {
752        let (p, rx, ctl, ends, _) = VideoPublication::for_test_with_fallbacks(source);
753        (p, rx, ctl, ends)
754    }
755
756    /// [`VideoPublication::for_test_with_ends`] with the producer's
757    /// [`VideoPublication::republish_without_backup`]s.
758    #[allow(clippy::type_complexity)]
759    pub(crate) fn for_test_with_fallbacks(
760        source: VideoSource,
761    ) -> (
762        VideoPublication,
763        mpsc::Receiver<VideoIn>,
764        mpsc::UnboundedSender<VideoControl>,
765        mpsc::UnboundedReceiver<ProducerEnd>,
766        mpsc::UnboundedReceiver<ProducerFallback>,
767    ) {
768        let (frames, rx) = mpsc::channel(VIDEO_QUEUE);
769        let (ctl, control) = mpsc::unbounded_channel();
770        let (ends, ends_rx) = mpsc::unbounded_channel();
771        let (fallbacks, fallbacks_rx) = mpsc::unbounded_channel();
772        let p = VideoPublication {
773            source,
774            id: 1,
775            track_sid: "TR_test".to_owned(),
776            published_mime: "video/VP8".to_owned(),
777            frames,
778            control,
779            stats: Arc::default(),
780            ends,
781            fallbacks,
782        };
783        (p, rx, ctl, ends_rx, fallbacks_rx)
784    }
785}
786
787/// The frame half of a [`VideoPublication`], cloneable.
788#[derive(Clone)]
789pub struct VideoSender {
790    id: u64,
791    frames: mpsc::Sender<VideoIn>,
792    stats: Arc<Mutex<VideoSendStats>>,
793}
794
795impl std::fmt::Debug for VideoSender {
796    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
797        f.debug_struct("VideoSender").finish_non_exhaustive()
798    }
799}
800
801impl VideoSender {
802    /// Queues one encoded frame (see [`VideoPublication::push`]).
803    pub fn push(&self, frame: EncodedVideo) {
804        if self
805            .frames
806            .try_send(VideoIn {
807                publication: self.id,
808                frame,
809            })
810            .is_err()
811            && let Ok(mut s) = self.stats.lock()
812        {
813            s.frames_not_sent += 1;
814        }
815    }
816}
817
818/// Send caps on top of the policy (thermal pressure, low power): applied before the split.
819#[derive(Clone, Copy, Debug, PartialEq, Eq)]
820#[non_exhaustive]
821pub struct VideoCaps {
822    /// Each layer's cap, percent of the policy's (1 to 100); a publication's lowest wanted
823    /// layer keeps at least its size's floor (or the policy's cap, if lower).
824    pub bitrate_pct: u8,
825    /// At most this many layers, from the lowest (`None`: all; never fewer than one).
826    pub max_layers: Option<u8>,
827    /// At most this frame rate (`None`: the layers').
828    pub max_fps: Option<u32>,
829}
830
831impl Default for VideoCaps {
832    fn default() -> VideoCaps {
833        VideoCaps {
834            bitrate_pct: 100,
835            max_layers: None,
836            max_fps: None,
837        }
838    }
839}
840
841impl VideoCaps {
842    /// No caps.
843    pub fn none() -> VideoCaps {
844        VideoCaps::default()
845    }
846
847    /// Caps of `bitrate_pct` percent, at most `max_layers` layers and `max_fps`.
848    pub fn new(bitrate_pct: u8, max_layers: Option<u8>, max_fps: Option<u32>) -> VideoCaps {
849        VideoCaps {
850            bitrate_pct: bitrate_pct.clamp(1, 100),
851            max_layers,
852            max_fps,
853        }
854    }
855}
856
857/// The backup lanes' own caps, on top of [`VideoCaps`] (a phone's thermal steps): at most
858/// this many backup layers (never fewer than one) and this frame rate.
859#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
860pub(crate) struct BackupCaps {
861    pub(crate) max_layers: Option<u8>,
862    pub(crate) max_fps: Option<u32>,
863}
864
865/// The engine's video commands (from the `Call` handle).
866pub(crate) enum VideoCmd {
867    Lease {
868        source: VideoSource,
869        on: bool,
870        reply: oneshot::Sender<Result<(), VideoError>>,
871    },
872    Publish {
873        req: VideoPublish,
874        reply: oneshot::Sender<Result<VideoPublication, VideoError>>,
875    },
876    Unpublish {
877        source: VideoSource,
878        release: bool,
879        /// `local_video`'s reason for the off.
880        reason: String,
881        reply: oneshot::Sender<Result<(), VideoError>>,
882    },
883    Caps(VideoCaps),
884    /// The bridge's caps for the backup lanes (a phone's thermal steps).
885    #[cfg_attr(not(feature = "video-core"), allow(dead_code))]
886    BackupCaps(BackupCaps),
887    /// The source's track muted or unmuted at the SFU (`MuteTrackRequest`), keeping the
888    /// publication and its lease (a phone app in the background).
889    Mute {
890        source: VideoSource,
891        muted: bool,
892    },
893}
894
895impl VideoCmd {
896    /// Answers the command without running it (a held join: no media).
897    pub(crate) fn refuse(self) {
898        match self {
899            VideoCmd::Lease { reply, .. } | VideoCmd::Unpublish { reply, .. } => {
900                let _ = reply.send(Err(VideoError::Ended));
901            }
902            VideoCmd::Publish { reply, .. } => {
903                let _ = reply.send(Err(VideoError::Ended));
904            }
905            VideoCmd::Caps(_) | VideoCmd::BackupCaps(_) | VideoCmd::Mute { .. } => {}
906        }
907    }
908}
909
910/// Ends a call's publication from any thread, without waiting (the bridge's pipeline, when
911/// its camera or screen ended).
912#[cfg(feature = "video-core")]
913#[derive(Clone)]
914pub(crate) struct VideoCtl {
915    cmd: mpsc::UnboundedSender<crate::call::Cmd>,
916}
917
918#[cfg(feature = "video-core")]
919impl VideoCtl {
920    pub(crate) fn new(cmd: mpsc::UnboundedSender<crate::call::Cmd>) -> VideoCtl {
921        VideoCtl { cmd }
922    }
923
924    /// The backup lanes' caps (a phone's thermal steps).
925    pub(crate) fn backup_caps(&self, caps: BackupCaps) {
926        let _ = self
927            .cmd
928            .send(crate::call::Cmd::Publish(VideoCmd::BackupCaps(caps)));
929    }
930
931    /// Unpublishes `source` with `reason` and releases its lease.
932    pub(crate) fn end(&self, source: VideoSource, reason: &'static str) {
933        let (reply, _) = oneshot::channel();
934        let _ = self
935            .cmd
936            .send(crate::call::Cmd::Publish(VideoCmd::Unpublish {
937                source,
938                release: true,
939                reason: reason.to_owned(),
940                reply,
941            }));
942    }
943}
944
945/// A lease call's answer, back on the engine task.
946pub(crate) struct LeaseDone {
947    source: VideoSource,
948    on: bool,
949    result: Result<(), VideoError>,
950    reply: Option<oneshot::Sender<Result<(), VideoError>>>,
951    /// A re-join's lease for a live publication: publish it again on success.
952    relink: bool,
953}
954
955/// What the publisher's queues deliver to the engine loop.
956pub(crate) enum VideoStep {
957    Frame(VideoIn),
958    Lease(LeaseDone),
959    /// A producer ended its publication ([`VideoPublication::end`]).
960    End(ProducerEnd),
961    /// A producer publishes again in one codec ([`VideoPublication::republish_without_backup`]).
962    Fallback(ProducerFallback),
963}
964
965/// The engine's state the publisher works with, borrowed for one call.
966pub(crate) struct Ctx<'a> {
967    pub(crate) pc: Option<&'a mut Pc>,
968    pub(crate) session: &'a mut Session,
969    pub(crate) keys: Option<&'a Arc<dyn KeySession>>,
970    /// Our participant sid (the msid stream of our send sections).
971    pub(crate) stream: &'a str,
972    pub(crate) media_up: bool,
973    /// The session has joined (an `AddTrackRequest` can go).
974    pub(crate) joined: bool,
975    pub(crate) now: Instant,
976    pub(crate) events: &'a broadcast::Sender<CallEvent>,
977}
978
979/// The HTTP side of a lease call.
980#[derive(Clone)]
981pub(crate) struct LeaseApi {
982    pub(crate) http: reqwest::Client,
983    pub(crate) base: url::Url,
984    pub(crate) token: Option<String>,
985}
986
987enum Packetiser {
988    Vp8(Vp8Sender),
989    H264(H264Sender),
990}
991
992struct Layer {
993    spec: LayerSpec,
994    ssrc: Option<u32>,
995    seq: u64,
996    pack: Packetiser,
997    /// Someone subscribes to it (dynacast).
998    wanted: bool,
999    /// The split runs it, at this rate (bit/s).
1000    rate: Option<u64>,
1001    /// Frames are dropped until a keyframe (a start, a resume, a new send path).
1002    need_key: bool,
1003    last_key_ask: Option<Instant>,
1004    /// A keyframe went out since `last_key_ask`: a request now is someone who missed it (a
1005    /// subscriber that joined after it), not one more ask for the same keyframe.
1006    key_sent_since_ask: bool,
1007    /// What the producer was told last.
1008    told: Option<LayerRate>,
1009}
1010
1011impl Layer {
1012    fn new(spec: LayerSpec, codec: VideoCodec, first_seq: u64, wanted: bool) -> Layer {
1013        let size = (
1014            u16::try_from(spec.width).unwrap_or(u16::MAX),
1015            u16::try_from(spec.height).unwrap_or(u16::MAX),
1016        );
1017        let pack = match codec {
1018            VideoCodec::Vp8 => Packetiser::Vp8(Vp8Sender::new(
1019                MTU,
1020                spec.temporal_layers,
1021                Vp8Starts {
1022                    picture_id: rand::random::<u16>() & 0x7fff,
1023                    tl0_pic_idx: rand::random(),
1024                    frame_number: rand::random(),
1025                },
1026                size,
1027            )),
1028            VideoCodec::H264 => Packetiser::H264(H264Sender::new(MTU, rand::random(), size)),
1029        };
1030        Layer {
1031            spec,
1032            ssrc: None,
1033            seq: first_seq,
1034            pack,
1035            wanted,
1036            rate: None,
1037            need_key: true,
1038            last_key_ask: None,
1039            key_sent_since_ask: false,
1040            told: None,
1041        }
1042    }
1043
1044    fn active(&self) -> bool {
1045        self.wanted && self.rate.is_some()
1046    }
1047}
1048
1049/// One codec of a publication and its send section: the primary (lane 0, every layer wanted
1050/// unless dynacast says otherwise) or the backup (lane 1, VP8, nothing wanted unless its own
1051/// `subscribed_codecs` entry enables it; its encoders run only while it is on).
1052struct Lane {
1053    codec: VideoCodec,
1054    /// Its `simulcast_codecs` cid and its send section's msid track.
1055    cid: String,
1056    mid: Option<String>,
1057    pt: Option<u8>,
1058    layers: Vec<Layer>,
1059    backup: bool,
1060    /// The backup runs (`BackupStart` told, no `BackupStop` since).
1061    on: bool,
1062    /// The backup just started: its lowest wanted layer skips the raise hysteresis until it
1063    /// runs.
1064    exempt: bool,
1065    /// When the backup started.
1066    since: Option<Instant>,
1067}
1068
1069impl Lane {
1070    fn new(codec: VideoCodec, specs: Vec<LayerSpec>, cid: String, backup: bool) -> Lane {
1071        Lane {
1072            codec,
1073            cid,
1074            mid: None,
1075            pt: None,
1076            layers: specs
1077                .into_iter()
1078                .map(|l| Layer::new(l, codec, first_seq(), !backup))
1079                .collect(),
1080            backup,
1081            on: false,
1082            exempt: false,
1083            since: None,
1084        }
1085    }
1086
1087    fn rids(&self) -> Vec<String> {
1088        self.layers.iter().map(|l| l.spec.rid.clone()).collect()
1089    }
1090
1091    fn video_layers(&self) -> Vec<VideoLayer> {
1092        self.layers
1093            .iter()
1094            .enumerate()
1095            .map(|(k, l)| VideoLayer {
1096                quality: quality(k),
1097                width: l.spec.width,
1098                height: l.spec.height,
1099                bitrate: l.spec.max_kbps.saturating_mul(1000),
1100                rid: l.spec.rid.clone(),
1101                ..VideoLayer::default()
1102            })
1103            .collect()
1104    }
1105
1106    /// No send path (a new publication, a new PC): the next answer sets it.
1107    fn reset_send(&mut self) {
1108        self.mid = None;
1109        self.pt = None;
1110        for l in &mut self.layers {
1111            l.ssrc = None;
1112        }
1113    }
1114}
1115
1116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1117enum State {
1118    /// Waiting for a PC and a joined session (or a re-join's lease).
1119    Pending,
1120    /// The `AddTrackRequest` is out.
1121    Requested { since: Instant },
1122    /// `TrackPublished` came: the send section is negotiating.
1123    Published,
1124    /// The send section is negotiated: frames flow.
1125    Live,
1126}
1127
1128/// The caller's answer channel and the publication's control queue, until `TrackPublished`.
1129type Reply = (
1130    oneshot::Sender<Result<VideoPublication, VideoError>>,
1131    mpsc::UnboundedReceiver<VideoControl>,
1132);
1133
1134struct Publication {
1135    id: u64,
1136    source: VideoSource,
1137    capture: (u32, u32),
1138    state: State,
1139    track_sid: Option<String>,
1140    /// The primary codec's lane, then the backup's (if any).
1141    lanes: Vec<Lane>,
1142    rtp_base: u32,
1143    control: mpsc::UnboundedSender<VideoControl>,
1144    /// The caller's handle, until `TrackPublished` (or a refusal).
1145    reply: Option<Reply>,
1146    /// A republication's old send sections, made inactive once the new ones are published.
1147    replaces: Vec<String>,
1148    /// The SFU's record of the track, published before the keys started: the keys confirm it
1149    /// when they do.
1150    unconfirmed: Option<TrackInfo>,
1151    /// Muted at the SFU ([`VideoCmd::Mute`]); sent again after a republish or a reconnect.
1152    muted: bool,
1153}
1154
1155impl Publication {
1156    fn tell(&self, c: VideoControl) {
1157        let _ = self.control.send(c);
1158    }
1159
1160    fn rtp_ts(&self, capture_us: u64) -> u32 {
1161        // 90 kHz from the capture clock, from a random base; the same on every layer and lane.
1162        let ticks = capture_us.wrapping_mul(90) / 1000;
1163        self.rtp_base.wrapping_add(ticks as u32)
1164    }
1165
1166    /// The track's cid (the primary's).
1167    fn cid(&self) -> &str {
1168        &self.lanes[0].cid
1169    }
1170
1171    /// The primary codec.
1172    fn codec(&self) -> VideoCodec {
1173        self.lanes[0].codec
1174    }
1175
1176    /// The send sections of every lane.
1177    fn take_mids(&mut self) -> Vec<String> {
1178        self.lanes.iter_mut().filter_map(|l| l.mid.take()).collect()
1179    }
1180
1181    /// The `AddTrackRequest` before the publish check: the primary's layers, and one
1182    /// `simulcast_codecs` entry per lane, each on its own cid (the primary's is the track's).
1183    fn add_track(&self) -> AddTrackRequest {
1184        let layers = self.lanes[0].video_layers();
1185        let (w, h) = self.lanes[0]
1186            .layers
1187            .last()
1188            .map_or((0, 0), |l| (l.spec.width, l.spec.height));
1189        AddTrackRequest {
1190            cid: self.cid().to_owned(),
1191            name: track_name(self.source).to_owned(),
1192            r#type: TrackType::Video as i32,
1193            source: track_source(self.source) as i32,
1194            width: w,
1195            height: h,
1196            layers,
1197            simulcast_codecs: self
1198                .lanes
1199                .iter()
1200                .map(|l| SimulcastCodec {
1201                    codec: mime(l.codec).to_owned(),
1202                    cid: l.cid.clone(),
1203                    layers: l.video_layers(),
1204                    ..SimulcastCodec::default()
1205                })
1206                .collect(),
1207            ..AddTrackRequest::default()
1208        }
1209    }
1210}
1211
1212fn new_cid(source: VideoSource) -> String {
1213    let p = match source {
1214        VideoSource::Camera => "cam",
1215        VideoSource::ScreenShare => "scr",
1216    };
1217    format!("{p}-{:08x}", rand::random::<u32>())
1218}
1219
1220fn first_seq() -> u64 {
1221    u64::from(rand::random::<u16>() & 0x7fff)
1222}
1223
1224/// LiveKit's quality of the `i`th layer from the lowest (q/h/f = LOW/MEDIUM/HIGH).
1225fn quality(i: usize) -> i32 {
1226    i.min(2) as i32
1227}
1228
1229/// Whether a `subscribed_codecs` entry's name (`vp8`, `video/VP8`, …) is `codec`.
1230fn names_codec(name: &str, codec: VideoCodec) -> bool {
1231    let n = name.rsplit('/').next().unwrap_or(name);
1232    n.eq_ignore_ascii_case(codec.as_str())
1233}
1234
1235/// Dynacast for one lane: which of its `n` layers anyone wants. The primary reads its own
1236/// codec's entry (the deprecated flat list when there is none); a quality not listed counts as
1237/// wanted. The backup reads only its own entry: a missing entry or quality is not wanted, and
1238/// the flat list is ignored.
1239#[allow(deprecated)]
1240fn lane_wanted(
1241    u: &SubscribedQualityUpdate,
1242    codec: VideoCodec,
1243    backup: bool,
1244    n: usize,
1245) -> Vec<bool> {
1246    let named = u
1247        .subscribed_codecs
1248        .iter()
1249        .find(|c| names_codec(&c.codec, codec))
1250        .map(|c| c.qualities.as_slice());
1251    let qualities = match named {
1252        Some(q) => q,
1253        None if backup => &[],
1254        None => u.subscribed_qualities.as_slice(),
1255    };
1256    (0..n)
1257        .map(|k| {
1258            let q = qualities.iter().find(|q| q.quality == quality(k));
1259            if backup {
1260                q.is_some_and(|q| q.enabled)
1261            } else {
1262                q.is_none_or(|q| q.enabled)
1263            }
1264        })
1265        .collect()
1266}
1267
1268/// The backup's layers for a new primary plan (a tier change): the plan's layers whose rid the
1269/// old backup had (a phone's backup stays at its capped rungs), with the old backup's temporal
1270/// layers; none left: the plan's lowest.
1271pub(crate) fn backup_layers_for(plan: &[LayerSpec], old: &[LayerSpec]) -> Vec<LayerSpec> {
1272    let tl = old.first().map_or(1, |l| l.temporal_layers);
1273    let mut out: Vec<LayerSpec> = plan
1274        .iter()
1275        .filter_map(|n| {
1276            let o = old.iter().find(|o| o.rid == n.rid)?;
1277            let mut l = n.clone();
1278            l.temporal_layers = o.temporal_layers;
1279            Some(l)
1280        })
1281        .collect();
1282    if out.is_empty()
1283        && let Some(l) = plan.first()
1284    {
1285        let mut l = l.clone();
1286        l.temporal_layers = tl;
1287        out.push(l);
1288    }
1289    out
1290}
1291
1292/// The engine's video publications.
1293pub(crate) struct Publisher {
1294    frames_tx: mpsc::Sender<VideoIn>,
1295    frames_rx: mpsc::Receiver<VideoIn>,
1296    lease_tx: mpsc::UnboundedSender<LeaseDone>,
1297    lease_rx: mpsc::UnboundedReceiver<LeaseDone>,
1298    ends_tx: mpsc::UnboundedSender<ProducerEnd>,
1299    ends_rx: mpsc::UnboundedReceiver<ProducerEnd>,
1300    fallback_tx: mpsc::UnboundedSender<ProducerFallback>,
1301    fallback_rx: mpsc::UnboundedReceiver<ProducerFallback>,
1302    pubs: Vec<Publication>,
1303    next_id: u64,
1304    leases: Leases,
1305    /// Sources whose publication ended with its lease released (an unpublish-and-release, the
1306    /// producer's end, video turned off), until the lease is taken again: a later
1307    /// unpublish-and-release of the same source (the source's own end and the app's stop can
1308    /// both ask) finds the release already sent and does not send it again.
1309    released_on_end: Leases,
1310    /// The current policy (the join answer's, then updates).
1311    policy: Option<MediaPolicy>,
1312    /// The join answer's `camera_allowed` and `screen_allowed` (kept for the whole join).
1313    allowed: (bool, bool),
1314    alloc: Allocator,
1315    estimate: Option<u64>,
1316    desired: u64,
1317    caps: VideoCaps,
1318    /// The bridge's caps for the backup lanes (a phone's thermal steps).
1319    backup_caps: BackupCaps,
1320    pub(crate) stats: Arc<Mutex<VideoSendStats>>,
1321    malformed_logged: bool,
1322    /// The run time of backups that stopped, ms.
1323    backup_done_ms: u64,
1324}
1325
1326impl std::fmt::Debug for Publisher {
1327    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1328        f.debug_struct("Publisher")
1329            .field("publications", &self.pubs.len())
1330            .field("leases", &self.leases)
1331            .finish_non_exhaustive()
1332    }
1333}
1334
1335/// `leases` with `source` set to `on`.
1336fn with(leases: Leases, source: VideoSource, on: bool) -> Leases {
1337    let (c, s) = (leases.camera, leases.screen);
1338    match source {
1339        VideoSource::Camera => Leases::new(on, s),
1340        VideoSource::ScreenShare => Leases::new(c, on),
1341    }
1342}
1343
1344/// Whether `leases` has `source`.
1345fn has(leases: Leases, source: VideoSource) -> bool {
1346    match source {
1347        VideoSource::Camera => leases.camera,
1348        VideoSource::ScreenShare => leases.screen,
1349    }
1350}
1351
1352impl Publisher {
1353    pub(crate) fn new(stats: Arc<Mutex<VideoSendStats>>) -> Publisher {
1354        let (frames_tx, frames_rx) = mpsc::channel(VIDEO_QUEUE);
1355        let (lease_tx, lease_rx) = mpsc::unbounded_channel();
1356        let (ends_tx, ends_rx) = mpsc::unbounded_channel();
1357        let (fallback_tx, fallback_rx) = mpsc::unbounded_channel();
1358        Publisher {
1359            frames_tx,
1360            frames_rx,
1361            lease_tx,
1362            lease_rx,
1363            ends_tx,
1364            ends_rx,
1365            fallback_tx,
1366            fallback_rx,
1367            pubs: Vec::new(),
1368            next_id: 1,
1369            leases: Leases::none(),
1370            released_on_end: Leases::none(),
1371            policy: None,
1372            allowed: (false, false),
1373            alloc: Allocator::default(),
1374            estimate: None,
1375            desired: 0,
1376            caps: VideoCaps::default(),
1377            backup_caps: BackupCaps::default(),
1378            stats,
1379            malformed_logged: false,
1380            backup_done_ms: 0,
1381        }
1382    }
1383
1384    /// The next frame or lease answer (cancel-safe).
1385    pub(crate) async fn recv(&mut self) -> VideoStep {
1386        tokio::select! {
1387            Some(f) = self.frames_rx.recv() => VideoStep::Frame(f),
1388            Some(l) = self.lease_rx.recv() => VideoStep::Lease(l),
1389            Some(e) = self.ends_rx.recv() => VideoStep::End(e),
1390            Some(b) = self.fallback_rx.recv() => VideoStep::Fallback(b),
1391        }
1392    }
1393
1394    /// A join answer's policy (the first join, a re-join): its `camera_allowed` and
1395    /// `screen_allowed` hold for the whole join.
1396    pub(crate) fn joined_with(&mut self, policy: Option<&MediaPolicy>) {
1397        self.allowed = policy.map_or((false, false), |p| (p.camera_allowed, p.screen_allowed));
1398        self.policy = policy.cloned();
1399    }
1400
1401    /// Whether a new PC needs the video codecs (video on, and a camera or screen allowed).
1402    pub(crate) fn may_send(&self) -> bool {
1403        // Like receive, video is negotiated only in a `video-core` build.
1404        cfg!(feature = "video-core")
1405            && self
1406                .policy
1407                .as_ref()
1408                .is_some_and(|p| p.video_enabled && (self.allowed.0 || self.allowed.1))
1409    }
1410
1411    fn set_lease(&mut self, source: VideoSource, on: bool) {
1412        self.leases = with(self.leases, source, on);
1413    }
1414
1415    fn effective_policy(&self) -> Option<MediaPolicy> {
1416        let mut p = self.policy.clone()?;
1417        p.camera_allowed = self.allowed.0;
1418        p.screen_allowed = self.allowed.1;
1419        Some(p)
1420    }
1421
1422    fn stat(&self, f: impl FnOnce(&mut VideoSendStats)) {
1423        if let Ok(mut s) = self.stats.lock() {
1424            f(&mut s);
1425        }
1426    }
1427
1428    /// How long the backups have run in all, up to `now`, ms.
1429    fn backup_ms(&self, now: Instant) -> u64 {
1430        let running: u64 = self
1431            .pubs
1432            .iter()
1433            .flat_map(|p| &p.lanes)
1434            .filter_map(|l| l.since.filter(|_| l.on))
1435            .map(|t| now.saturating_duration_since(t).as_millis() as u64)
1436            .sum();
1437        self.backup_done_ms + running
1438    }
1439
1440    // -------------------------------------------------------------------------- commands
1441
1442    pub(crate) fn command(&mut self, cx: &mut Ctx<'_>, api: LeaseApi, cmd: VideoCmd) {
1443        match cmd {
1444            VideoCmd::Lease { source, on, reply } => {
1445                if on {
1446                    match self.effective_policy() {
1447                        Some(p) if p.video_enabled && allowed(source, &p) => {}
1448                        _ => {
1449                            let _ = reply.send(Err(VideoError::NotAllowed));
1450                            return;
1451                        }
1452                    }
1453                }
1454                if on {
1455                    self.released_on_end = with(self.released_on_end, source, false);
1456                }
1457                self.lease(api, source, on, Some(reply), false);
1458            }
1459            VideoCmd::Publish { req, reply } => self.publish(cx, req, reply),
1460            VideoCmd::Unpublish {
1461                source,
1462                release,
1463                reason,
1464                reply,
1465            } => {
1466                let found = self.pubs.iter().position(|p| p.source == source);
1467                match found {
1468                    Some(i) => {
1469                        let p = self.pubs.remove(i);
1470                        tracing::info!(target: "sew_call_client", source = ?source, %reason, release, "video unpublished by the app");
1471                        self.end(cx, p, &reason);
1472                    }
1473                    None if !release => {
1474                        let _ = reply.send(Err(VideoError::NotPublished));
1475                        return;
1476                    }
1477                    None => {}
1478                }
1479                if release && found.is_none() && has(self.released_on_end, source) {
1480                    // The publication had already ended and its lease was released then.
1481                    let _ = reply.send(Ok(()));
1482                } else if release {
1483                    self.released_on_end = with(self.released_on_end, source, true);
1484                    self.lease(api, source, false, Some(reply), false);
1485                } else {
1486                    let _ = reply.send(Ok(()));
1487                }
1488            }
1489            VideoCmd::Caps(c) => {
1490                self.caps = c;
1491                self.reallocate(cx);
1492            }
1493            VideoCmd::BackupCaps(c) => {
1494                if c != self.backup_caps {
1495                    self.backup_caps = c;
1496                    self.reallocate(cx);
1497                }
1498            }
1499            VideoCmd::Mute { source, muted } => {
1500                for p in self.pubs.iter_mut().filter(|p| p.source == source) {
1501                    if p.muted == muted {
1502                        continue;
1503                    }
1504                    p.muted = muted;
1505                    if p.state == State::Published
1506                        && let Some(sid) = &p.track_sid
1507                    {
1508                        cx.session.mute(sid, muted);
1509                    }
1510                    tracing::info!(target: "sew_call_client", source = ?source, muted, "video muted");
1511                }
1512            }
1513        }
1514    }
1515
1516    fn lease(
1517        &mut self,
1518        api: LeaseApi,
1519        source: VideoSource,
1520        on: bool,
1521        reply: Option<oneshot::Sender<Result<(), VideoError>>>,
1522        relink: bool,
1523    ) {
1524        let Some(token) = api.token else {
1525            if let Some(r) = reply {
1526                let _ = r.send(Err(VideoError::Lease {
1527                    status: 0,
1528                    code: "no_call_credential".to_owned(),
1529                }));
1530            }
1531            return;
1532        };
1533        let tx = self.lease_tx.clone();
1534        let (video, stream) = match source {
1535            VideoSource::Camera => (Some(on), None),
1536            VideoSource::ScreenShare => (None, Some(on)),
1537        };
1538        tokio::spawn(async move {
1539            let result = crate::api::video_state(&api.http, &api.base, &token, video, stream)
1540                .await
1541                .map_err(|r| VideoError::from_lease(&r));
1542            let _ = tx.send(LeaseDone {
1543                source,
1544                on,
1545                result,
1546                reply,
1547                relink,
1548            });
1549        });
1550    }
1551
1552    /// A producer ended its publication ([`VideoPublication::end`]): unpublished, the lease
1553    /// released.
1554    pub(crate) fn on_producer_end(&mut self, cx: &mut Ctx<'_>, api: LeaseApi, e: ProducerEnd) {
1555        let Some(i) = self.pubs.iter().position(|p| p.id == e.publication) else {
1556            return;
1557        };
1558        let p = self.pubs.remove(i);
1559        let source = p.source;
1560        tracing::info!(target: "sew_call_client", source = ?source, reason = %e.reason, "the producer ended its video");
1561        self.end(cx, p, &e.reason);
1562        self.released_on_end = with(self.released_on_end, source, true);
1563        self.lease(api, source, false, None, false);
1564    }
1565
1566    /// A producer can't send its backup, or lost its primary codec
1567    /// ([`VideoPublication::republish_without_backup`]): the publication is published again in
1568    /// one codec with its new layers, under the same lease (the tier-change path).
1569    pub(crate) fn on_producer_fallback(&mut self, cx: &mut Ctx<'_>, f: ProducerFallback) {
1570        let Some(i) = self.pubs.iter().position(|p| p.id == f.publication) else {
1571            return;
1572        };
1573        if f.layers.is_empty() {
1574            return;
1575        }
1576        let now = cx.now;
1577        self.backup_stop(i, now);
1578        let p = &mut self.pubs[i];
1579        tracing::info!(target: "sew_call_client", source = ?p.source, from = p.codec().as_str(), to = f.codec.as_str(), "video published again in one codec");
1580        p.lanes.truncate(1);
1581        p.lanes[0].codec = f.codec;
1582        self.republish(cx, i, f.layers);
1583    }
1584
1585    pub(crate) fn on_lease(&mut self, cx: &mut Ctx<'_>, d: LeaseDone) {
1586        if d.result.is_ok() {
1587            self.set_lease(d.source, d.on);
1588            tracing::info!(target: "sew_call_client", source = ?d.source, on = d.on, "video lease");
1589        } else if d.on {
1590            tracing::info!(target: "sew_call_client", source = ?d.source, error = ?d.result, "video lease refused");
1591        }
1592        if d.relink {
1593            match &d.result {
1594                Ok(()) => {
1595                    for i in 0..self.pubs.len() {
1596                        if self.pubs[i].source == d.source && self.pubs[i].state == State::Pending {
1597                            self.request(cx, i);
1598                        }
1599                    }
1600                }
1601                Err(e) => {
1602                    let reason = e.code().to_owned();
1603                    let gone: Vec<Publication> = {
1604                        let (gone, keep) = std::mem::take(&mut self.pubs)
1605                            .into_iter()
1606                            .partition(|p| p.source == d.source);
1607                        self.pubs = keep;
1608                        gone
1609                    };
1610                    for p in gone {
1611                        self.end(cx, p, &reason);
1612                    }
1613                }
1614            }
1615        }
1616        if let Some(r) = d.reply {
1617            let _ = r.send(d.result);
1618        }
1619    }
1620
1621    fn publish(
1622        &mut self,
1623        cx: &mut Ctx<'_>,
1624        req: VideoPublish,
1625        reply: oneshot::Sender<Result<VideoPublication, VideoError>>,
1626    ) {
1627        match self.effective_policy() {
1628            // Without `video-core` the PC carries no video codecs (voice-only signalling).
1629            Some(p)
1630                if cfg!(feature = "video-core") && p.video_enabled && allowed(req.source, &p) => {}
1631            _ => {
1632                let _ = reply.send(Err(VideoError::NotAllowed));
1633                return;
1634            }
1635        }
1636        if self.pubs.iter().any(|p| p.source == req.source) {
1637            let _ = reply.send(Err(VideoError::AlreadyPublished));
1638            return;
1639        }
1640        if req.layers.is_empty() {
1641            let _ = reply.send(Err(VideoError::CodecUnavailable));
1642            return;
1643        }
1644        let id = self.next_id;
1645        self.next_id += 1;
1646        let (control, control_rx) = mpsc::unbounded_channel();
1647        let mut lanes = vec![Lane::new(req.codec, req.layers, new_cid(req.source), false)];
1648        // A backup only in another codec, with layers.
1649        if let Some(b) = req
1650            .backup
1651            .filter(|b| b.codec != req.codec && !b.layers.is_empty())
1652        {
1653            lanes.push(Lane::new(b.codec, b.layers, new_cid(req.source), true));
1654        }
1655        self.pubs.push(Publication {
1656            id,
1657            source: req.source,
1658            capture: (req.capture_width, req.capture_height),
1659            state: State::Pending,
1660            track_sid: None,
1661            lanes,
1662            rtp_base: rand::random(),
1663            control,
1664            reply: Some((reply, control_rx)),
1665            replaces: Vec::new(),
1666            unconfirmed: None,
1667            muted: false,
1668        });
1669        let i = self.pubs.len() - 1;
1670        self.request(cx, i);
1671    }
1672
1673    /// The `AddTrackRequest` of publication `i`, through the publish check, if the session can
1674    /// take it now (else it waits in `Pending`).
1675    fn request(&mut self, cx: &mut Ctx<'_>, i: usize) {
1676        if !cx.joined || cx.pc.is_none() {
1677            self.pubs[i].state = State::Pending;
1678            return;
1679        }
1680        let leases = self.leases;
1681        let p = &mut self.pubs[i];
1682        let mut add = p.add_track();
1683        match check_publish(&mut add, leases) {
1684            Ok(()) => {
1685                cx.session.add_track(add);
1686                p.state = State::Requested { since: cx.now };
1687            }
1688            Err(e) => {
1689                let p = self.pubs.remove(i);
1690                let err = match e {
1691                    PublishRefused::NoLease => VideoError::NoLease,
1692                    PublishRefused::Downgraded => VideoError::Downgraded,
1693                    other => VideoError::PublishFailed(other.to_string()),
1694                };
1695                self.fail(cx, p, err);
1696            }
1697        }
1698    }
1699
1700    /// A publication that never went live: the caller hears why.
1701    fn fail(&mut self, cx: &mut Ctx<'_>, mut p: Publication, err: VideoError) {
1702        self.alloc.forget(p.id);
1703        let code = err.code().to_owned();
1704        match p.reply.take() {
1705            Some((reply, _)) => {
1706                let _ = reply.send(Err(err));
1707            }
1708            None => self.end(cx, p, &code),
1709        }
1710    }
1711
1712    /// The end of a publication: its send sections go inactive, the producer is told.
1713    fn end(&mut self, cx: &mut Ctx<'_>, mut p: Publication, reason: &str) {
1714        self.alloc.forget(p.id);
1715        for l in p.lanes.iter_mut().filter(|l| l.on) {
1716            l.on = false;
1717            if let Some(t) = l.since.take() {
1718                self.backup_done_ms += cx.now.saturating_duration_since(t).as_millis() as u64;
1719            }
1720        }
1721        if let Some(pc) = cx.pc.as_deref_mut() {
1722            for mid in p.take_mids() {
1723                pc.stop_send(&mid);
1724            }
1725            for mid in std::mem::take(&mut p.replaces) {
1726                pc.stop_send(&mid);
1727            }
1728        }
1729        if let Some((reply, _)) = p.reply.take() {
1730            let _ = reply.send(Err(VideoError::PublishFailed(reason.to_owned())));
1731        }
1732        p.tell(VideoControl::Ended {
1733            reason: reason.to_owned(),
1734        });
1735        let _ = cx.events.send(CallEvent::LocalVideo(LocalVideo {
1736            source: p.source,
1737            on: false,
1738            reason: Some(reason.to_owned()),
1739        }));
1740        self.reallocate(cx);
1741    }
1742
1743    // -------------------------------------------------------------------------- the backup
1744
1745    /// The backup of publication `i` starts when some layer of it is wanted (the producer
1746    /// opens its encoders, the first frame a keyframe; no signalling) and stops when none is
1747    /// (the producer closes them; the section stays negotiated, without RTP).
1748    fn backup_transitions(&mut self, i: usize, now: Instant) {
1749        let p = &mut self.pubs[i];
1750        let Some(b) = p.lanes.get_mut(1) else {
1751            return;
1752        };
1753        let any = b.layers.iter().any(|l| l.wanted);
1754        if any && !b.on {
1755            b.on = true;
1756            b.exempt = true;
1757            b.since = Some(now);
1758            let mut start = Vec::new();
1759            for l in &mut b.layers {
1760                l.need_key = true;
1761                l.rate = None;
1762                l.told = None;
1763                if l.wanted {
1764                    start.push(l.spec.clone());
1765                }
1766            }
1767            tracing::info!(target: "sew_call_client", source = ?p.source, codec = b.codec.as_str(), layers = start.len(), "the backup starts");
1768            p.tell(VideoControl::BackupStart(start));
1769            self.stat(|s| s.backup_starts += 1);
1770        } else if !any && b.on {
1771            self.backup_stop(i, now);
1772        }
1773    }
1774
1775    /// The backup of publication `i` stops (if it runs): its encoders close.
1776    fn backup_stop(&mut self, i: usize, now: Instant) {
1777        let p = &mut self.pubs[i];
1778        let Some(b) = p.lanes.get_mut(1).filter(|b| b.on) else {
1779            return;
1780        };
1781        b.on = false;
1782        b.exempt = false;
1783        for l in &mut b.layers {
1784            l.rate = None;
1785            l.told = None;
1786        }
1787        let ran = b
1788            .since
1789            .take()
1790            .map_or(0, |t| now.saturating_duration_since(t).as_millis() as u64);
1791        tracing::info!(target: "sew_call_client", source = ?p.source, ran_ms = ran, "the backup stops");
1792        p.tell(VideoControl::BackupStop);
1793        self.backup_done_ms += ran;
1794        let total = self.backup_ms(now);
1795        self.stat(|s| {
1796            s.backup_stops += 1;
1797            s.backup_ms = total;
1798        });
1799    }
1800
1801    /// The backup of publication `i` off and not wanted (a new PC, a teardown, a republish):
1802    /// dynacast turns it on again.
1803    fn backup_reset(&mut self, i: usize, now: Instant) {
1804        self.backup_stop(i, now);
1805        if let Some(b) = self.pubs[i].lanes.get_mut(1) {
1806            for l in &mut b.layers {
1807                l.wanted = false;
1808            }
1809        }
1810    }
1811
1812    // -------------------------------------------------------------------------- signalling
1813
1814    /// `TrackPublished` for `cid`: `true` if it was one of ours.
1815    pub(crate) fn on_track_published(
1816        &mut self,
1817        cx: &mut Ctx<'_>,
1818        cid: &str,
1819        track: &TrackInfo,
1820    ) -> bool {
1821        let Some(i) = self.pubs.iter().position(|p| p.cid() == cid) else {
1822            return false;
1823        };
1824        if !matches!(self.pubs[i].state, State::Requested { .. }) {
1825            return true;
1826        }
1827        let gcm = track.encryption == sew_lkproto::livekit::encryption::Type::Gcm as i32;
1828        let confirmed = match cx.keys {
1829            Some(k) => k.published(track),
1830            // The keys confirm it once they start (`on_keys`); until then no frame can be
1831            // sealed, and a track without GCM is refused here already.
1832            None => gcm,
1833        };
1834        if !confirmed {
1835            // One check for the track covers both codecs: neither section is ever added.
1836            let p = self.pubs.remove(i);
1837            self.fail(cx, p, VideoError::Downgraded);
1838            return true;
1839        }
1840        let p = &mut self.pubs[i];
1841        if p.lanes.len() > 1
1842            && !track.codecs.is_empty()
1843            && !track
1844                .codecs
1845                .iter()
1846                .any(|c| names_codec(&c.mime_type, p.lanes[1].codec))
1847        {
1848            // The SFU kept one codec (a room without backup codecs): no backup section.
1849            tracing::info!(target: "sew_call_client", source = ?p.source, "the SFU took no backup codec: one codec");
1850            p.lanes.truncate(1);
1851        }
1852        p.unconfirmed = cx.keys.is_none().then(|| track.clone());
1853        p.track_sid = Some(track.sid.clone());
1854        p.state = State::Published;
1855        for l in &mut p.lanes {
1856            l.reset_send();
1857        }
1858        if let Some(pc) = cx.pc.as_deref_mut() {
1859            // Every lane's section in the same offer.
1860            for l in &p.lanes {
1861                pc.add_send_video(cx.stream, &l.cid, &l.rids());
1862            }
1863        }
1864        tracing::info!(target: "sew_call_client", source = ?p.source, codec = p.codec().as_str(), backup = p.lanes.get(1).map(|l| l.codec.as_str()), layers = p.lanes[0].layers.len(), "video published");
1865        if p.muted {
1866            // Muted before this (re)publication: the SFU hears it again.
1867            cx.session.mute(&track.sid, true);
1868        }
1869        if let Some((reply, control)) = p.reply.take() {
1870            let handle = VideoPublication {
1871                source: p.source,
1872                id: p.id,
1873                track_sid: track.sid.clone(),
1874                published_mime: if track.mime_type.is_empty() {
1875                    track
1876                        .codecs
1877                        .first()
1878                        .map(|c| c.mime_type.clone())
1879                        .unwrap_or_default()
1880                } else {
1881                    track.mime_type.clone()
1882                },
1883                frames: self.frames_tx.clone(),
1884                control,
1885                stats: self.stats.clone(),
1886                ends: self.ends_tx.clone(),
1887                fallbacks: self.fallback_tx.clone(),
1888            };
1889            if reply.send(Ok(handle)).is_err() {
1890                // The caller is gone: nobody produces frames.
1891                let p = self.pubs.remove(i);
1892                tracing::info!(target: "sew_call_client", source = ?p.source, "video published with nobody to produce it");
1893                self.end(cx, p, PUBLISHER_GONE);
1894                return true;
1895            }
1896        }
1897        let p = &self.pubs[i];
1898        let _ = cx.events.send(CallEvent::LocalVideo(LocalVideo {
1899            source: p.source,
1900            on: true,
1901            reason: None,
1902        }));
1903        true
1904    }
1905
1906    /// After an answer: the send paths of publications whose sections are now negotiated.
1907    pub(crate) fn on_answer(&mut self, cx: &mut Ctx<'_>) {
1908        let Some(pc) = cx.pc.as_deref_mut() else {
1909            return;
1910        };
1911        // A lane's section: its mid, payload type and one SSRC per layer, once negotiated.
1912        let resolve = |pc: &mut Pc, l: &Lane| -> Option<(String, u8, Vec<u32>)> {
1913            let mid = pc.mid_for_track(&l.cid)?;
1914            let pt = pc.video_pt(&mid, l.codec)?;
1915            let ssrcs: Option<Vec<u32>> = l
1916                .layers
1917                .iter()
1918                .map(|x| pc.tx_ssrc_rid(&mid, &x.spec.rid))
1919                .collect();
1920            Some((mid, pt, ssrcs?))
1921        };
1922        let mut live = false;
1923        for p in &mut self.pubs {
1924            if p.state != State::Published {
1925                continue;
1926            }
1927            let Some(primary) = resolve(pc, &p.lanes[0]) else {
1928                continue;
1929            };
1930            let backup = p.lanes.get(1).map(|l| resolve(pc, l));
1931            if let Some(None) = backup {
1932                // The backup's section was refused (or lost its codec): one codec.
1933                tracing::warn!(target: "sew_call_client", source = ?p.source, "the backup's send section was not negotiated: one codec");
1934                if let Some(mid) = pc.mid_for_track(&p.lanes[1].cid) {
1935                    pc.stop_send(&mid);
1936                }
1937                if p.lanes[1].on {
1938                    p.tell(VideoControl::BackupStop);
1939                }
1940                p.lanes.truncate(1);
1941            }
1942            let found = std::iter::once(primary).chain(backup.flatten());
1943            for (l, (mid, pt, ssrcs)) in p.lanes.iter_mut().zip(found) {
1944                for (x, s) in l.layers.iter_mut().zip(ssrcs) {
1945                    x.ssrc = Some(s);
1946                    x.need_key = true;
1947                }
1948                l.mid = Some(mid);
1949                l.pt = Some(pt);
1950            }
1951            p.state = State::Live;
1952            for old in std::mem::take(&mut p.replaces) {
1953                pc.stop_send(&old);
1954            }
1955            live = true;
1956        }
1957        if live {
1958            self.reallocate(cx);
1959            for i in 0..self.pubs.len() {
1960                if self.pubs[i].state != State::Live {
1961                    continue;
1962                }
1963                for n in 0..self.pubs[i].lanes.len() {
1964                    let rids = self.pubs[i].lanes[n].rids();
1965                    for rid in rids {
1966                        self.ask_keyframe(i, n, &rid, cx.now, true);
1967                    }
1968                }
1969            }
1970        }
1971    }
1972
1973    /// The keys started: they confirm the publications the SFU confirmed before (a downgrade
1974    /// ends the publication, both codecs).
1975    pub(crate) fn on_keys(&mut self, cx: &mut Ctx<'_>) {
1976        let Some(k) = cx.keys else { return };
1977        let refused: Vec<usize> = self
1978            .pubs
1979            .iter_mut()
1980            .enumerate()
1981            .filter_map(|(i, p)| {
1982                let t = p.unconfirmed.take()?;
1983                (!k.published(&t)).then_some(i)
1984            })
1985            .collect();
1986        for i in refused.into_iter().rev() {
1987            let p = self.pubs.remove(i);
1988            self.end(cx, p, VideoError::Downgraded.code());
1989        }
1990    }
1991
1992    /// The server unpublished one of our tracks (a lease it took back, a revoked permission).
1993    pub(crate) fn on_track_unpublished(&mut self, cx: &mut Ctx<'_>, sid: &str) {
1994        let Some(i) = self
1995            .pubs
1996            .iter()
1997            .position(|p| p.track_sid.as_deref() == Some(sid))
1998        else {
1999            return;
2000        };
2001        let p = self.pubs.remove(i);
2002        tracing::info!(target: "sew_call_client", source = ?p.source, "the SFU unpublished our video");
2003        self.end(cx, p, "server_unpublished");
2004    }
2005
2006    /// Dynacast: the qualities anyone subscribes to, each lane from its own codec's entry
2007    /// ([`lane_wanted`]); the backup starts or stops with it.
2008    pub(crate) fn on_subscribed_quality(&mut self, cx: &mut Ctx<'_>, u: &SubscribedQualityUpdate) {
2009        if self.policy.as_ref().is_some_and(|p| !p.dynacast) {
2010            return;
2011        }
2012        let Some(i) = self
2013            .pubs
2014            .iter()
2015            .position(|p| p.track_sid.as_deref() == Some(u.track_sid.as_str()))
2016        else {
2017            return;
2018        };
2019        let mut changed = false;
2020        for lane in &mut self.pubs[i].lanes {
2021            let wanted = lane_wanted(u, lane.codec, lane.backup, lane.layers.len());
2022            for (l, w) in lane.layers.iter_mut().zip(wanted) {
2023                if w != l.wanted {
2024                    l.wanted = w;
2025                    changed = true;
2026                }
2027            }
2028        }
2029        if changed {
2030            tracing::debug!(target: "sew_call_client", track = %u.track_sid, "dynacast");
2031            self.backup_transitions(i, cx.now);
2032            self.reallocate(cx);
2033        }
2034    }
2035
2036    /// The SFU's PLI or FIR for one of our layers, matched to the lane by its section's mid,
2037    /// then to the layer by rid.
2038    pub(crate) fn on_keyframe_request(&mut self, now: Instant, mid: &str, rid: Option<&str>) {
2039        let Some((i, n)) = self.pubs.iter().enumerate().find_map(|(i, p)| {
2040            p.lanes
2041                .iter()
2042                .position(|l| l.mid.as_deref() == Some(mid))
2043                .map(|n| (i, n))
2044        }) else {
2045            return;
2046        };
2047        self.stat(|s| s.sfu_keyframe_requests += 1);
2048        let rids: Vec<String> = match rid {
2049            Some(r) => vec![r.to_owned()],
2050            None => self.pubs[i].lanes[n].rids(),
2051        };
2052        let (source, backup) = (self.pubs[i].source, self.pubs[i].lanes[n].backup);
2053        for r in &rids {
2054            let key = if backup {
2055                format!("{}/backup/{r}", source_name(source))
2056            } else {
2057                format!("{}/{r}", source_name(source))
2058            };
2059            self.stat(|s| *s.sfu_keyframe_requests_by_layer.entry(key).or_default() += 1);
2060        }
2061        for r in rids {
2062            self.ask_keyframe(i, n, &r, now, false);
2063        }
2064    }
2065
2066    fn ask_keyframe(&mut self, i: usize, n: usize, rid: &str, now: Instant, force: bool) {
2067        let p = &mut self.pubs[i];
2068        let Some(lane) = p.lanes.get_mut(n) else {
2069            return;
2070        };
2071        if lane.backup && !lane.on {
2072            // No encoder runs: its start makes a keyframe anyway.
2073            return;
2074        }
2075        let backup = lane.backup;
2076        let Some(l) = lane.layers.iter_mut().find(|l| l.spec.rid == rid) else {
2077            return;
2078        };
2079        if !force
2080            && !l.key_sent_since_ask
2081            && l.last_key_ask
2082                .is_some_and(|t| now.saturating_duration_since(t) < KEYFRAME_EVERY)
2083        {
2084            return;
2085        }
2086        l.last_key_ask = Some(now);
2087        l.key_sent_since_ask = false;
2088        let rid = rid.to_owned();
2089        p.tell(if backup {
2090            VideoControl::BackupKeyframe { rid }
2091        } else {
2092            VideoControl::Keyframe { rid }
2093        });
2094        self.stat(|s| s.keyframes_asked += 1);
2095    }
2096
2097    /// str0m's new estimate.
2098    pub(crate) fn on_estimate(&mut self, cx: &mut Ctx<'_>, bps: u64) {
2099        self.estimate = Some(bps);
2100        self.stat(|s| s.estimate_bps = bps);
2101        self.reallocate(cx);
2102    }
2103
2104    /// A policy update (`media_policy_updated`, a move's `voice_server_updated`).
2105    pub(crate) fn on_policy(&mut self, cx: &mut Ctx<'_>, api: &LeaseApi, policy: MediaPolicy) {
2106        let enabled = policy.video_enabled;
2107        self.policy = Some(policy);
2108        if !enabled {
2109            let gone = std::mem::take(&mut self.pubs);
2110            let sources: Vec<VideoSource> = gone.iter().map(|p| p.source).collect();
2111            for p in gone {
2112                self.end(cx, p, sew_proto::voice::reasons::VIDEO_DISABLED);
2113            }
2114            for s in sources {
2115                self.released_on_end = with(self.released_on_end, s, true);
2116                self.lease(api.clone(), s, false, None, false);
2117            }
2118            return;
2119        }
2120        let Some(policy) = self.policy.clone() else {
2121            return;
2122        };
2123        // The backup only while the policy allows one (`backup_codec`, dynacast, its codec
2124        // listed): otherwise the track is published again without it.
2125        let backup_allowed = |c: VideoCodec| {
2126            policy.backup_codec
2127                && policy.dynacast
2128                && policy.codecs.iter().any(|p| codec_of_policy(*p) == Some(c))
2129        };
2130        for i in 0..self.pubs.len() {
2131            let p = &self.pubs[i];
2132            let mut plan = plan_source_layers(
2133                p.source,
2134                hint_of(p.source, &policy),
2135                p.capture.0,
2136                p.capture.1,
2137            );
2138            for l in &mut plan {
2139                if let Some(old) = p.lanes[0].layers.iter().find(|o| o.spec.rid == l.rid) {
2140                    l.temporal_layers = old.spec.temporal_layers;
2141                }
2142            }
2143            let drop_backup = p.lanes.get(1).is_some_and(|b| !backup_allowed(b.codec));
2144            let same = plan.len() == p.lanes[0].layers.len()
2145                && plan.iter().zip(&p.lanes[0].layers).all(|(n, o)| {
2146                    n.rid == o.spec.rid && n.width == o.spec.width && n.height == o.spec.height
2147                });
2148            if same && !drop_backup {
2149                // New caps (and frame rate) in place, on both lanes.
2150                let p = &mut self.pubs[i];
2151                for lane in &mut p.lanes {
2152                    for o in &mut lane.layers {
2153                        if let Some(n) = plan.iter().find(|n| n.rid == o.spec.rid) {
2154                            o.spec.max_kbps = n.max_kbps;
2155                            o.spec.fps = n.fps;
2156                        }
2157                    }
2158                }
2159                continue;
2160            }
2161            if drop_backup {
2162                tracing::info!(target: "sew_call_client", source = ?p.source, "the policy no longer allows the backup: one codec");
2163                self.backup_stop(i, cx.now);
2164                self.pubs[i].lanes.truncate(1);
2165            }
2166            self.republish(cx, i, plan);
2167        }
2168        self.reallocate(cx);
2169    }
2170
2171    /// A tier change (or a fall back to one codec): the track again with the new layers, under
2172    /// the same lease. The old send sections go inactive once the new ones are negotiated;
2173    /// until then the old layers stop. The backup (if any) starts off again.
2174    fn republish(&mut self, cx: &mut Ctx<'_>, i: usize, plan: Vec<LayerSpec>) {
2175        if plan.is_empty() {
2176            return;
2177        }
2178        self.stat(|s| s.republishes += 1);
2179        self.backup_reset(i, cx.now);
2180        let p = &mut self.pubs[i];
2181        tracing::info!(target: "sew_call_client", source = ?p.source, layers = plan.len(), "video republished");
2182        self.alloc.forget(p.id);
2183        p.tell(VideoControl::Republish(plan.clone()));
2184        let mids = p.take_mids();
2185        if !mids.is_empty() {
2186            // The sections before the last republish's (never negotiated) go now.
2187            if let Some(pc) = cx.pc.as_deref_mut() {
2188                for old in std::mem::take(&mut p.replaces) {
2189                    pc.stop_send(&old);
2190                }
2191            }
2192            p.replaces = mids;
2193        }
2194        let source = p.source;
2195        let backup = p.lanes.get(1).map(|b| {
2196            let old: Vec<LayerSpec> = b.layers.iter().map(|l| l.spec.clone()).collect();
2197            (b.codec, backup_layers_for(&plan, &old))
2198        });
2199        if let Some((codec, layers)) = backup {
2200            p.lanes[1] = Lane::new(codec, layers, new_cid(source), true);
2201        }
2202        let codec = p.lanes[0].codec;
2203        p.lanes[0] = Lane::new(codec, plan, new_cid(source), false);
2204        p.track_sid = None;
2205        self.request(cx, i);
2206    }
2207
2208    /// A new PC (the first, a full reconnect's): every publication again on it.
2209    pub(crate) fn on_new_pc(&mut self, cx: &mut Ctx<'_>) {
2210        for i in 0..self.pubs.len() {
2211            self.backup_reset(i, cx.now);
2212            let p = &mut self.pubs[i];
2213            p.replaces.clear();
2214            p.track_sid = None;
2215            for lane in &mut p.lanes {
2216                lane.reset_send();
2217                lane.cid = new_cid(p.source);
2218                for l in &mut lane.layers {
2219                    l.seq = first_seq();
2220                    l.need_key = true;
2221                }
2222            }
2223            p.state = State::Pending;
2224            self.alloc.forget(p.id);
2225            self.request(cx, i);
2226        }
2227    }
2228
2229    /// The PC went (teardown): nothing is sent until a new one.
2230    pub(crate) fn on_teardown(&mut self) {
2231        let now = Instant::now();
2232        for i in 0..self.pubs.len() {
2233            self.backup_reset(i, now);
2234            let p = &mut self.pubs[i];
2235            p.replaces.clear();
2236            p.state = State::Pending;
2237            for lane in &mut p.lanes {
2238                lane.reset_send();
2239            }
2240        }
2241    }
2242
2243    /// A re-join (a new voice entry): the leases are gone; each publication takes its lease
2244    /// again, then publishes again.
2245    pub(crate) fn on_rejoined(&mut self, policy: Option<&MediaPolicy>, api: &LeaseApi) {
2246        self.joined_with(policy);
2247        self.leases = Leases::none();
2248        let now = Instant::now();
2249        let mut sources: Vec<VideoSource> = Vec::new();
2250        for i in 0..self.pubs.len() {
2251            self.backup_reset(i, now);
2252            let p = &mut self.pubs[i];
2253            p.state = State::Pending;
2254            p.replaces.clear();
2255            for lane in &mut p.lanes {
2256                lane.mid = None;
2257            }
2258            if !sources.contains(&p.source) {
2259                sources.push(p.source);
2260            }
2261        }
2262        for s in sources {
2263            self.lease(api.clone(), s, true, None, true);
2264        }
2265    }
2266
2267    /// Everything stops (the call ends or is held): the producers are told.
2268    pub(crate) fn close(&mut self, reason: &str) {
2269        for mut p in std::mem::take(&mut self.pubs) {
2270            if let Some((reply, _)) = p.reply.take() {
2271                let _ = reply.send(Err(VideoError::Ended));
2272            }
2273            p.tell(VideoControl::Ended {
2274                reason: reason.to_owned(),
2275            });
2276        }
2277        self.leases = Leases::none();
2278    }
2279
2280    // -------------------------------------------------------------------------- timers
2281
2282    pub(crate) fn deadline(&self) -> Option<Instant> {
2283        let publishing = self
2284            .pubs
2285            .iter()
2286            .filter_map(|p| match p.state {
2287                State::Requested { since } => Some(since + PUBLISH_TIMEOUT),
2288                _ => None,
2289            })
2290            .min();
2291        match (publishing, self.alloc.deadline()) {
2292            (Some(a), Some(b)) => Some(a.min(b)),
2293            (a, b) => a.or(b),
2294        }
2295    }
2296
2297    pub(crate) fn on_timeout(&mut self, cx: &mut Ctx<'_>) {
2298        let late: Vec<usize> = self
2299            .pubs
2300            .iter()
2301            .enumerate()
2302            .filter(|(_, p)| {
2303                matches!(p.state, State::Requested { since } if cx.now >= since + PUBLISH_TIMEOUT)
2304            })
2305            .map(|(i, _)| i)
2306            .collect();
2307        for i in late.into_iter().rev() {
2308            let p = self.pubs.remove(i);
2309            tracing::info!(target: "sew_call_client", source = ?p.source, "no TrackPublished for the video");
2310            self.fail(
2311                cx,
2312                p,
2313                VideoError::PublishFailed("no answer from the media server".to_owned()),
2314            );
2315        }
2316        if self.alloc.deadline().is_some_and(|d| cx.now >= d) {
2317            self.reallocate(cx);
2318        }
2319    }
2320
2321    // -------------------------------------------------------------------------- the split
2322
2323    /// Every running lane's layers under the caps (the policy's, the host's thermal and power
2324    /// caps on both lanes; the backup's own caps on top). Each lane keeps at least its lowest
2325    /// layer whatever the caps, and its lowest wanted layer is kept (runs whatever the estimate,
2326    /// a bitrate cap never taking it below its floor): the primary's is its subscribers' only
2327    /// video, the backup's a VP8-only subscriber's.
2328    fn capped_layers(&self) -> Vec<AllocLayer> {
2329        let mut out = Vec::new();
2330        for p in &self.pubs {
2331            if p.state != State::Live {
2332                continue;
2333            }
2334            for (n, lane) in p.lanes.iter().enumerate() {
2335                if lane.backup && !lane.on {
2336                    continue;
2337                }
2338                let max_layers = if lane.backup {
2339                    let caps = [self.caps.max_layers, self.backup_caps.max_layers];
2340                    caps.into_iter().flatten().min()
2341                } else {
2342                    self.caps.max_layers
2343                }
2344                .map(|m| m.max(1));
2345                let lowest_wanted = lane.layers.iter().position(|l| l.wanted);
2346                for (k, l) in lane.layers.iter().enumerate() {
2347                    if max_layers.is_some_and(|m| k >= usize::from(m)) {
2348                        continue;
2349                    }
2350                    let policy_max = u64::from(l.spec.max_kbps) * 1000;
2351                    let mut max = policy_max * u64::from(self.caps.bitrate_pct) / 100;
2352                    let min_bps = super::alloc::min_bitrate_bps(l.spec.height.min(l.spec.width));
2353                    let lowest = lowest_wanted == Some(k);
2354                    if lowest {
2355                        // A bitrate cap (heat, low power) never takes a lane's lowest wanted
2356                        // layer below its floor: it would pause its subscribers' only video.
2357                        max = max.max(policy_max.min(min_bps));
2358                    }
2359                    out.push(AllocLayer {
2360                        key: (p.id, n, k),
2361                        screen: p.source == VideoSource::ScreenShare,
2362                        max_bps: max.max(10_000),
2363                        wanted: l.wanted,
2364                        min_bps,
2365                        exempt: lane.backup && lane.exempt && lowest,
2366                        kept: lowest,
2367                    });
2368                }
2369            }
2370        }
2371        out
2372    }
2373
2374    /// The frame rate a layer of `lane` runs at under the caps.
2375    fn fps_of(&self, lane: &Lane, spec: &LayerSpec) -> u32 {
2376        let mut fps = spec.fps;
2377        if let Some(m) = self.caps.max_fps {
2378            fps = fps.min(m.max(1));
2379        }
2380        if lane.backup
2381            && let Some(m) = self.backup_caps.max_fps
2382        {
2383            fps = fps.min(m.max(1));
2384        }
2385        fps
2386    }
2387
2388    /// Runs the split and tells each producer which layers run at what rate (the backup's in
2389    /// `BackupRates`, while it runs); a layer that starts again needs a keyframe.
2390    fn reallocate(&mut self, cx: &mut Ctx<'_>) {
2391        let layers = self.capped_layers();
2392        let est = self.estimate.unwrap_or(BWE_INITIAL_BPS);
2393        let grants = self.alloc.update(cx.now, est, &layers);
2394        let desired: u64 = layers.iter().filter(|l| l.wanted).map(|l| l.max_bps).sum();
2395        if desired != self.desired {
2396            self.desired = desired;
2397            if let Some(pc) = cx.pc.as_deref_mut() {
2398                pc.set_desired_bitrate(desired);
2399            }
2400        }
2401        let mut resumed: Vec<(usize, usize, String)> = Vec::new();
2402        let mut tells: Vec<(usize, VideoControl)> = Vec::new();
2403        for i in 0..self.pubs.len() {
2404            if self.pubs[i].state != State::Live {
2405                continue;
2406            }
2407            let id = self.pubs[i].id;
2408            for n in 0..self.pubs[i].lanes.len() {
2409                let fps: Vec<u32> = {
2410                    let lane = &self.pubs[i].lanes[n];
2411                    lane.layers
2412                        .iter()
2413                        .map(|l| self.fps_of(lane, &l.spec))
2414                        .collect()
2415                };
2416                let lane = &mut self.pubs[i].lanes[n];
2417                if lane.backup && !lane.on {
2418                    continue;
2419                }
2420                let mut rates = Vec::new();
2421                let mut changed = false;
2422                for (k, l) in lane.layers.iter_mut().enumerate() {
2423                    let was = l.active();
2424                    l.rate = grants.get(&(id, n, k)).copied();
2425                    let rate = LayerRate {
2426                        rid: l.spec.rid.clone(),
2427                        active: l.active(),
2428                        bitrate_bps: l.rate.map_or(0, |r| u32::try_from(r).unwrap_or(u32::MAX)),
2429                        fps: fps[k],
2430                    };
2431                    if l.active() && !was {
2432                        l.need_key = true;
2433                        resumed.push((i, n, l.spec.rid.clone()));
2434                    }
2435                    if l.told.as_ref() != Some(&rate) {
2436                        changed = true;
2437                        l.told = Some(rate.clone());
2438                    }
2439                    rates.push(rate);
2440                }
2441                if lane.exempt && lane.layers.iter().any(Layer::active) {
2442                    // Its lowest layer runs: the rest follow the hysteresis.
2443                    lane.exempt = false;
2444                }
2445                if changed {
2446                    tells.push((
2447                        i,
2448                        if lane.backup {
2449                            VideoControl::BackupRates(rates)
2450                        } else {
2451                            VideoControl::Rates(rates)
2452                        },
2453                    ));
2454                }
2455            }
2456        }
2457        for (i, c) in tells {
2458            self.pubs[i].tell(c);
2459        }
2460        for (i, n, rid) in resumed {
2461            self.ask_keyframe(i, n, &rid, cx.now, true);
2462        }
2463    }
2464
2465    // -------------------------------------------------------------------------- frames
2466
2467    /// One encoded frame from a producer, to the lane of its codec: normalised, encrypted,
2468    /// packetised and written on that lane's section.
2469    pub(crate) fn on_frame(&mut self, cx: &mut Ctx<'_>, v: VideoIn) {
2470        let not_sent = |s: &mut VideoSendStats| s.frames_not_sent += 1;
2471        let Some(i) = self.pubs.iter().position(|p| p.id == v.publication) else {
2472            self.stat(not_sent);
2473            return;
2474        };
2475        let f = v.frame;
2476        let (Some(pc), Some(keys)) = (cx.pc.as_deref_mut(), cx.keys) else {
2477            self.stat(not_sent);
2478            return;
2479        };
2480        let p = &mut self.pubs[i];
2481        if p.state != State::Live || !cx.media_up || f.data.is_empty() {
2482            self.stat(not_sent);
2483            return;
2484        }
2485        let ts = p.rtp_ts(f.capture_us);
2486        let source = p.source;
2487        let Some(lane) = p.lanes.iter_mut().find(|l| l.codec == f.codec) else {
2488            self.stat(not_sent);
2489            return;
2490        };
2491        if lane.backup && !lane.on {
2492            // Not asked for (or stopped): nothing on the backup's section.
2493            self.stat(not_sent);
2494            return;
2495        }
2496        let (Some(mid), Some(pt)) = (lane.mid.clone(), lane.pt) else {
2497            self.stat(not_sent);
2498            return;
2499        };
2500        let codec = lane.codec;
2501        let backup = lane.backup;
2502        let Some(l) = lane.layers.iter_mut().find(|l| l.spec.rid == f.rid) else {
2503            self.stat(not_sent);
2504            return;
2505        };
2506        let Some(ssrc) = l.ssrc else {
2507            self.stat(not_sent);
2508            return;
2509        };
2510        if !l.active() || (l.need_key && !f.keyframe) {
2511            self.stat(not_sent);
2512            return;
2513        }
2514        let plain: Vec<u8> = match codec {
2515            VideoCodec::H264 => {
2516                let au = normalise(&f.data);
2517                if let Err(e) = check(&au) {
2518                    if !self.malformed_logged {
2519                        self.malformed_logged = true;
2520                        tracing::warn!(target: "sew_call_client", error = %e, "an H.264 access unit broke the bitstream rules; dropped");
2521                    }
2522                    if let Ok(mut s) = self.stats.lock() {
2523                        s.malformed += 1;
2524                        s.frames_not_sent += 1;
2525                    }
2526                    return;
2527                }
2528                au
2529            }
2530            VideoCodec::Vp8 => f.data.to_vec(),
2531        };
2532        let mut sealed = Vec::with_capacity(plain.len() + 64);
2533        if keys
2534            .encrypt_video(frame_codec(codec), &plain, ssrc, ts, &mut sealed)
2535            .is_err()
2536            || sealed.is_empty()
2537        {
2538            // No send key (or the frame did not encrypt): dropped, never sent in the clear.
2539            self.stat(not_sent);
2540            return;
2541        }
2542        let packets = match &mut l.pack {
2543            Packetiser::Vp8(s) => s.packetize(
2544                &sealed,
2545                FrameLayer {
2546                    keyframe: f.keyframe,
2547                    temporal_id: f.temporal_id,
2548                    layer_sync: f.layer_sync,
2549                },
2550            ),
2551            Packetiser::H264(s) => match s.packetize(&sealed, f.keyframe) {
2552                Ok(p) => p,
2553                Err(_) => {
2554                    self.stat(not_sent);
2555                    return;
2556                }
2557            },
2558        };
2559        let n = packets.len() as u64;
2560        let mut ok = true;
2561        for pk in packets {
2562            let seq = l.seq;
2563            l.seq += 1;
2564            if pc
2565                .write_video(
2566                    &mid, &f.rid, pt, seq, ts, cx.now, pk.payload, pk.marker, pk.dd,
2567                )
2568                .is_err()
2569            {
2570                ok = false;
2571            }
2572        }
2573        if f.keyframe {
2574            l.need_key = false;
2575            l.key_sent_since_ask = true;
2576        }
2577        let key = if backup {
2578            format!("{}/backup/{}", source_name(source), f.rid)
2579        } else {
2580            format!("{}/{}", source_name(source), f.rid)
2581        };
2582        let backup_ms = backup.then(|| self.backup_ms(cx.now));
2583        if let Ok(mut s) = self.stats.lock() {
2584            if ok {
2585                *s.frames_sent.entry(key).or_default() += 1;
2586                *s.frames_by_codec
2587                    .entry(codec.as_str().to_owned())
2588                    .or_default() += 1;
2589                s.packets_sent += n;
2590                s.keyframes_sent += u64::from(f.keyframe);
2591                if f.keyframe {
2592                    *s.keyframes_by_codec
2593                        .entry(codec.as_str().to_owned())
2594                        .or_default() += 1;
2595                }
2596            } else {
2597                s.frames_not_sent += 1;
2598            }
2599            if let Some(ms) = backup_ms {
2600                s.backup_ms = ms;
2601            }
2602        }
2603    }
2604}
2605
2606fn source_name(s: VideoSource) -> &'static str {
2607    match s {
2608        VideoSource::Camera => "camera",
2609        VideoSource::ScreenShare => "screen",
2610    }
2611}
2612
2613#[cfg(test)]
2614mod tests {
2615    use super::*;
2616    use sew_proto::voice::LayerHint;
2617
2618    fn hint() -> TrackHint {
2619        TrackHint {
2620            max_width: 1280,
2621            max_height: 720,
2622            max_fps: 30,
2623            layers: vec![
2624                LayerHint {
2625                    rid: "q".into(),
2626                    height: 180,
2627                    max_kbps: 150,
2628                },
2629                LayerHint {
2630                    rid: "h".into(),
2631                    height: 360,
2632                    max_kbps: 500,
2633                },
2634                LayerHint {
2635                    rid: "f".into(),
2636                    height: 720,
2637                    max_kbps: 1700,
2638                },
2639            ],
2640        }
2641    }
2642
2643    #[test]
2644    fn layers_follow_the_hints_up_to_the_capture() {
2645        let l = plan_layers(&hint(), 1280, 720);
2646        let got: Vec<(&str, u32, u32, u32)> = l
2647            .iter()
2648            .map(|l| (l.rid.as_str(), l.width, l.height, l.max_kbps))
2649            .collect();
2650        assert_eq!(
2651            got,
2652            vec![
2653                ("q", 320, 180, 150),
2654                ("h", 640, 360, 500),
2655                ("f", 1280, 720, 1700)
2656            ]
2657        );
2658        assert!(l.iter().all(|l| l.fps == 30 && l.temporal_layers == 1));
2659        // A 640×480 capture: q and h only, at 4:3 and even widths.
2660        let l = plan_layers(&hint(), 640, 480);
2661        let got: Vec<(&str, u32, u32)> = l
2662            .iter()
2663            .map(|l| (l.rid.as_str(), l.width, l.height))
2664            .collect();
2665        assert_eq!(got, vec![("q", 240, 180), ("h", 480, 360)]);
2666        // Smaller than every layer: the lowest at the capture's size.
2667        let l = plan_layers(&hint(), 160, 90);
2668        assert_eq!((l.len(), l[0].width, l[0].height), (1, 160, 90));
2669        // A portrait phone camera (720 × 1280): portrait layers on the short side.
2670        let l = plan_layers(&hint(), 720, 1280);
2671        let got: Vec<(&str, u32, u32)> = l
2672            .iter()
2673            .map(|l| (l.rid.as_str(), l.width, l.height))
2674            .collect();
2675        assert_eq!(
2676            got,
2677            vec![("q", 180, 320), ("h", 360, 640), ("f", 720, 1280)]
2678        );
2679    }
2680
2681    /// Sew's screen hint for a `normal` room: h (540p, 600 kbit/s) and f (1080p, 2500), at
2682    /// most 1920×1080 at 15 fps.
2683    fn screen_hint() -> TrackHint {
2684        TrackHint {
2685            max_width: 1920,
2686            max_height: 1080,
2687            max_fps: 15,
2688            layers: vec![
2689                LayerHint {
2690                    rid: "h".into(),
2691                    height: 540,
2692                    max_kbps: 600,
2693                },
2694                LayerHint {
2695                    rid: "f".into(),
2696                    height: 1080,
2697                    max_kbps: 2500,
2698                },
2699            ],
2700        }
2701    }
2702
2703    #[test]
2704    fn a_screen_shares_top_layer_is_the_captures_own_size() {
2705        let plan = |w, h| -> Vec<(String, u32, u32, u32, u32)> {
2706            plan_screen_layers(&screen_hint(), w, h)
2707                .into_iter()
2708                .map(|l| (l.rid, l.width, l.height, l.max_kbps, l.fps))
2709                .collect()
2710        };
2711        let l = |rid: &str, w, h, kbps| (rid.to_owned(), w, h, kbps, 15);
2712        // 1080p: the hint's own layers, f at the capture's size.
2713        assert_eq!(
2714            plan(1920, 1080),
2715            vec![l("h", 960, 540, 600), l("f", 1920, 1080, 2500)]
2716        );
2717        // A 1920×1200 display, captured into the 1920×1080 box.
2718        assert_eq!(
2719            plan(1728, 1080),
2720            vec![l("h", 864, 540, 600), l("f", 1728, 1080, 2500)]
2721        );
2722        // Laptop displays between 540p and 1080p: f at their native size, its cap scaled by
2723        // pixels (plan_layers alone would stop at h, a downscaled copy).
2724        assert_eq!(
2725            plan(1366, 768),
2726            vec![l("h", 960, 540, 600), l("f", 1366, 768, 1264)]
2727        );
2728        assert_eq!(
2729            plan(1440, 900),
2730            vec![l("h", 864, 540, 600), l("f", 1440, 900, 1736)]
2731        );
2732        assert_eq!(
2733            plan(1280, 800),
2734            vec![l("h", 864, 540, 600), l("f", 1280, 800, 1371)]
2735        );
2736        assert_eq!(
2737            plan(1680, 1050),
2738            vec![l("h", 864, 540, 600), l("f", 1680, 1050, 2363)]
2739        );
2740        // An odd-sized window: even sizes.
2741        assert_eq!(
2742            plan(1201, 801),
2743            vec![l("h", 808, 540, 600), l("f", 1200, 800, 1371)]
2744        );
2745        // Within a quarter of h: h only (576 * 4 <= 540 * 5).
2746        assert_eq!(plan(1024, 576), vec![l("h", 960, 540, 600)]);
2747        // Smaller than every layer: the capture's size, once.
2748        assert_eq!(plan(640, 360), vec![l("h", 640, 360, 600)]);
2749        // A camera keeps plan_layers' rule.
2750        assert_eq!(
2751            plan_source_layers(VideoSource::Camera, &screen_hint(), 1366, 768),
2752            plan_layers(&screen_hint(), 1366, 768)
2753        );
2754        // A tier whose hint has no larger layer (constrained: h only) is never raised.
2755        let constrained = TrackHint {
2756            max_width: 1280,
2757            max_height: 720,
2758            max_fps: 15,
2759            layers: vec![screen_hint().layers[0].clone()],
2760        };
2761        let got = plan_screen_layers(&constrained, 1280, 720);
2762        assert_eq!(
2763            got.iter()
2764                .map(|l| (l.rid.as_str(), l.width, l.height))
2765                .collect::<Vec<_>>(),
2766            vec![("h", 960, 540)]
2767        );
2768    }
2769
2770    #[test]
2771    fn lease_refusals_map_to_the_plugin_codes() {
2772        let r = |status, reason: Option<&str>, retry| crate::api::LeaseRefused {
2773            status,
2774            code: Some("x".to_owned()),
2775            reason: reason.map(str::to_owned),
2776            retry_after: retry,
2777            detail: String::new(),
2778        };
2779        assert_eq!(
2780            VideoError::from_lease(&r(422, Some("video_slots_full"), None)).code(),
2781            "video_slots_full"
2782        );
2783        assert_eq!(
2784            VideoError::from_lease(&r(503, Some("media_busy"), Some(30))),
2785            VideoError::MediaBusy {
2786                retry_after: Some(30)
2787            }
2788        );
2789        assert_eq!(
2790            VideoError::from_lease(&r(503, Some("media_capacity"), None)).code(),
2791            "media_capacity"
2792        );
2793        assert_eq!(
2794            VideoError::from_lease(&r(403, Some("video_disabled"), None)).code(),
2795            "video_disabled"
2796        );
2797        assert_eq!(
2798            VideoError::from_lease(&r(422, Some("screen_slots_full"), None)).code(),
2799            "screen_slots_full"
2800        );
2801        assert_eq!(
2802            VideoError::from_lease(&r(403, None, None)),
2803            VideoError::Lease {
2804                status: 403,
2805                code: "x".to_owned()
2806            }
2807        );
2808    }
2809
2810    #[test]
2811    fn the_rtp_clock_is_the_capture_clock_at_90_khz() {
2812        let (control, _rx) = mpsc::unbounded_channel();
2813        let p = Publication {
2814            id: 1,
2815            source: VideoSource::Camera,
2816            capture: (1280, 720),
2817            state: State::Pending,
2818            track_sid: None,
2819            lanes: vec![Lane::new(VideoCodec::Vp8, Vec::new(), "c".into(), false)],
2820            rtp_base: u32::MAX - 10,
2821            control,
2822            reply: None,
2823            replaces: Vec::new(),
2824            unconfirmed: None,
2825            muted: false,
2826        };
2827        assert_eq!(p.rtp_ts(0), u32::MAX - 10);
2828        assert_eq!(p.rtp_ts(1_000_000), (u32::MAX - 10).wrapping_add(90_000));
2829        assert_eq!(p.rtp_ts(33_333), (u32::MAX - 10).wrapping_add(2_999));
2830        assert_eq!(quality(0), 0);
2831        assert_eq!(quality(2), 2);
2832        assert_eq!(quality(5), 2);
2833    }
2834
2835    fn three() -> Vec<LayerSpec> {
2836        vec![
2837            LayerSpec::new("q", 320, 180, 150, 30),
2838            LayerSpec::new("h", 640, 360, 500, 30),
2839            LayerSpec::new("f", 1280, 720, 1700, 30),
2840        ]
2841    }
2842
2843    /// A camera publication of H.264 q/h/f with a VP8 backup of `backup` layers.
2844    fn with_backup(backup: Vec<LayerSpec>) -> Publication {
2845        let (control, _rx) = mpsc::unbounded_channel();
2846        Publication {
2847            id: 7,
2848            source: VideoSource::Camera,
2849            capture: (1280, 720),
2850            state: State::Pending,
2851            track_sid: None,
2852            lanes: vec![
2853                Lane::new(VideoCodec::H264, three(), "cam-a".into(), false),
2854                Lane::new(VideoCodec::Vp8, backup, "cam-b".into(), true),
2855            ],
2856            rtp_base: 0,
2857            control,
2858            reply: None,
2859            replaces: Vec::new(),
2860            unconfirmed: None,
2861            muted: false,
2862        }
2863    }
2864
2865    #[test]
2866    fn a_backup_is_one_add_track_with_two_codecs_on_their_own_cids_under_gcm() {
2867        let mut b = three();
2868        b.truncate(2);
2869        let p = with_backup(b);
2870        let mut add = p.add_track();
2871        check_publish(&mut add, Leases::new(true, false)).expect("leased");
2872        assert_eq!(add.cid, "cam-a");
2873        assert_eq!(
2874            add.encryption,
2875            sew_lkproto::livekit::encryption::Type::Gcm as i32,
2876            "one GCM request covers both codecs"
2877        );
2878        assert_eq!((add.width, add.height), (1280, 720));
2879        assert_eq!(add.layers.len(), 3);
2880        let codecs: Vec<(&str, &str, Vec<&str>)> = add
2881            .simulcast_codecs
2882            .iter()
2883            .map(|c| {
2884                (
2885                    c.codec.as_str(),
2886                    c.cid.as_str(),
2887                    c.layers.iter().map(|l| l.rid.as_str()).collect(),
2888                )
2889            })
2890            .collect();
2891        assert_eq!(
2892            codecs,
2893            vec![
2894                ("video/H264", "cam-a", vec!["q", "h", "f"]),
2895                ("video/VP8", "cam-b", vec!["q", "h"]),
2896            ]
2897        );
2898        assert_eq!(add.simulcast_codecs[1].layers[1].quality, 1);
2899        // The backup starts with nothing wanted; the primary with everything.
2900        assert!(p.lanes[1].layers.iter().all(|l| !l.wanted));
2901        assert!(p.lanes[0].layers.iter().all(|l| l.wanted));
2902        // Without the lease: refused, both codecs.
2903        let mut add = p.add_track();
2904        assert_eq!(
2905            check_publish(&mut add, Leases::none()),
2906            Err(PublishRefused::NoLease)
2907        );
2908    }
2909
2910    #[test]
2911    #[allow(deprecated)]
2912    fn each_lane_reads_its_own_codecs_entry() {
2913        use sew_lkproto::livekit::{SubscribedCodec, SubscribedQuality};
2914        let q = |quality: i32, enabled: bool| SubscribedQuality { quality, enabled };
2915        let entry = |codec: &str, qs: Vec<SubscribedQuality>| SubscribedCodec {
2916            codec: codec.to_owned(),
2917            qualities: qs,
2918        };
2919        let update =
2920            |codecs: Vec<SubscribedCodec>, flat: Vec<SubscribedQuality>| SubscribedQualityUpdate {
2921                track_sid: "TR_x".to_owned(),
2922                subscribed_qualities: flat,
2923                subscribed_codecs: codecs,
2924            };
2925        // H.264 subscribers only: the backup stays off; the primary runs what is asked.
2926        let u = update(
2927            vec![entry("h264", vec![q(0, true), q(1, true), q(2, false)])],
2928            vec![],
2929        );
2930        assert_eq!(
2931            lane_wanted(&u, VideoCodec::H264, false, 3),
2932            vec![true, true, false]
2933        );
2934        assert_eq!(
2935            lane_wanted(&u, VideoCodec::Vp8, true, 2),
2936            vec![false, false]
2937        );
2938        // A VP8-only subscriber at LOW: the backup's q, named as a mime, any case.
2939        let u = update(
2940            vec![
2941                entry("h264", vec![q(0, false), q(1, false), q(2, false)]),
2942                entry("video/vp8", vec![q(0, true), q(1, false)]),
2943            ],
2944            vec![q(0, true), q(1, true), q(2, true)],
2945        );
2946        assert_eq!(
2947            lane_wanted(&u, VideoCodec::H264, false, 3),
2948            vec![false, false, false],
2949            "the primary never takes the backup's entry"
2950        );
2951        assert_eq!(lane_wanted(&u, VideoCodec::Vp8, true, 2), vec![true, false]);
2952        // A quality the backup's entry leaves out is not wanted; the primary's counts as wanted.
2953        let u = update(
2954            vec![
2955                entry("H264", vec![q(0, true)]),
2956                entry("VP8", vec![q(1, true)]),
2957            ],
2958            vec![],
2959        );
2960        assert_eq!(
2961            lane_wanted(&u, VideoCodec::H264, false, 3),
2962            vec![true, true, true]
2963        );
2964        assert_eq!(
2965            lane_wanted(&u, VideoCodec::Vp8, true, 3),
2966            vec![false, true, false]
2967        );
2968        // No entry for a codec: the primary reads the flat list; the backup ignores it.
2969        let u = update(vec![], vec![q(0, true), q(1, false)]);
2970        assert_eq!(
2971            lane_wanted(&u, VideoCodec::H264, false, 3),
2972            vec![true, false, true]
2973        );
2974        assert_eq!(
2975            lane_wanted(&u, VideoCodec::Vp8, true, 3),
2976            vec![false, false, false]
2977        );
2978        assert!(names_codec("video/H264", VideoCodec::H264));
2979        assert!(!names_codec("video/VP8", VideoCodec::H264));
2980    }
2981
2982    #[test]
2983    fn caps_reach_both_lanes_and_heat_never_stops_a_lanes_lowest_layer() {
2984        let mut pb = Publisher::new(Arc::default());
2985        let mut b = three();
2986        b.truncate(2);
2987        let mut p = with_backup(b);
2988        p.state = State::Live;
2989        pb.pubs.push(p);
2990        let keys = |pb: &Publisher| -> Vec<(u64, usize, usize)> {
2991            pb.capped_layers().iter().map(|l| l.key).collect()
2992        };
2993        // The backup off: only the primary's layers.
2994        assert_eq!(keys(&pb), vec![(7, 0, 0), (7, 0, 1), (7, 0, 2)]);
2995        pb.pubs[0].lanes[1].on = true;
2996        for l in &mut pb.pubs[0].lanes[1].layers {
2997            l.wanted = true;
2998        }
2999        assert_eq!(pb.capped_layers().len(), 5);
3000        // The host's caps (heat, low power) on both lanes: one layer each at half the rate,
3001        // but neither lane's lowest wanted layer below its floor (q's cap is its floor here).
3002        pb.caps = VideoCaps::new(50, Some(1), Some(20));
3003        let l = pb.capped_layers();
3004        let got: Vec<((u64, usize, usize), u64)> = l.iter().map(|l| (l.key, l.max_bps)).collect();
3005        assert_eq!(got, vec![((7, 0, 0), 150_000), ((7, 1, 0), 150_000)]);
3006        // Only h wanted on the primary: h is its lowest wanted, kept at its floor (400k of its
3007        // 500k), q (not wanted) at half its rate.
3008        pb.caps = VideoCaps::new(50, None, None);
3009        pb.pubs[0].lanes[0].layers[0].wanted = false;
3010        let l = pb.capped_layers();
3011        let got: Vec<((u64, usize, usize), u64)> = l.iter().map(|l| (l.key, l.max_bps)).collect();
3012        assert_eq!(
3013            &got[..3],
3014            &[
3015                ((7, 0, 0), 75_000),
3016                ((7, 0, 1), 400_000),
3017                ((7, 0, 2), 850_000)
3018            ]
3019        );
3020        pb.pubs[0].lanes[0].layers[0].wanted = true;
3021        pb.caps = VideoCaps::new(50, Some(1), Some(20));
3022        let (prim, backup) = (&pb.pubs[0].lanes[0], &pb.pubs[0].lanes[1]);
3023        assert_eq!(pb.fps_of(prim, &prim.layers[0].spec), 20);
3024        assert_eq!(pb.fps_of(backup, &backup.layers[0].spec), 20);
3025        // Caps asking for no layer at all: each lane keeps one.
3026        pb.caps = VideoCaps::new(100, Some(0), None);
3027        assert_eq!(keys(&pb), vec![(7, 0, 0), (7, 1, 0)]);
3028        // A phone's thermal steps for the backup alone: Serious one layer, Critical at 15 fps.
3029        pb.caps = VideoCaps::none();
3030        pb.backup_caps = BackupCaps {
3031            max_layers: Some(1),
3032            max_fps: Some(15),
3033        };
3034        assert_eq!(keys(&pb), vec![(7, 0, 0), (7, 0, 1), (7, 0, 2), (7, 1, 0)]);
3035        let (prim, backup) = (&pb.pubs[0].lanes[0], &pb.pubs[0].lanes[1]);
3036        assert_eq!(pb.fps_of(prim, &prim.layers[0].spec), 30);
3037        assert_eq!(pb.fps_of(backup, &backup.layers[0].spec), 15);
3038        pb.backup_caps = BackupCaps {
3039            max_layers: Some(0),
3040            max_fps: None,
3041        };
3042        assert_eq!(keys(&pb).last(), Some(&(7, 1, 0)), "never zero layers");
3043        // Just started: its lowest wanted layer is exempt from the hysteresis.
3044        pb.pubs[0].lanes[1].exempt = true;
3045        pb.pubs[0].lanes[1].layers[0].wanted = false;
3046        pb.backup_caps = BackupCaps::default();
3047        let ex: Vec<(u64, usize, usize)> = pb
3048            .capped_layers()
3049            .iter()
3050            .filter(|l| l.exempt)
3051            .map(|l| l.key)
3052            .collect();
3053        assert_eq!(ex, vec![(7, 1, 1)], "the lowest wanted, h here");
3054        // Kept (runs whatever the estimate): each running lane's lowest wanted layer, the
3055        // backup's exempt or not.
3056        pb.pubs[0].lanes[1].exempt = false;
3057        let kept = |pb: &Publisher| -> Vec<(u64, usize, usize)> {
3058            pb.capped_layers()
3059                .iter()
3060                .filter(|l| l.kept)
3061                .map(|l| l.key)
3062                .collect()
3063        };
3064        assert_eq!(kept(&pb), vec![(7, 0, 0), (7, 1, 1)]);
3065        pb.pubs[0].lanes[1].layers[0].wanted = true;
3066        assert_eq!(kept(&pb), vec![(7, 0, 0), (7, 1, 0)]);
3067        pb.pubs[0].lanes[1].on = false;
3068        assert_eq!(
3069            kept(&pb),
3070            vec![(7, 0, 0)],
3071            "the backup off: the primary's q"
3072        );
3073        // The primary's lowest wanted layer moves with dynacast; nothing wanted, nothing kept.
3074        pb.pubs[0].lanes[0].layers[0].wanted = false;
3075        assert_eq!(kept(&pb), vec![(7, 0, 1)]);
3076        for l in &mut pb.pubs[0].lanes[0].layers {
3077            l.wanted = false;
3078        }
3079        assert!(
3080            kept(&pb).is_empty(),
3081            "nobody wants the primary: nothing kept"
3082        );
3083    }
3084
3085    #[test]
3086    fn a_tier_change_keeps_the_backups_rungs() {
3087        // A phone's backup (q and h, three temporal layers) after a change to 360p hints.
3088        let mut old = three();
3089        old.truncate(2);
3090        for l in &mut old {
3091            l.temporal_layers = 3;
3092        }
3093        let p = with_backup(old);
3094        let old: Vec<LayerSpec> = p.lanes[1].layers.iter().map(|l| l.spec.clone()).collect();
3095        let plan = vec![
3096            LayerSpec::new("q", 320, 180, 120, 24),
3097            LayerSpec::new("h", 640, 360, 400, 24),
3098        ];
3099        let got = backup_layers_for(&plan, &old);
3100        assert_eq!(got.len(), 2);
3101        assert!(got.iter().all(|l| l.temporal_layers == 3 && l.fps == 24));
3102        // A 720p plan for a backup capped at q and h keeps q and h.
3103        let got = backup_layers_for(&three(), &old);
3104        let rids: Vec<&str> = got.iter().map(|l| l.rid.as_str()).collect();
3105        assert_eq!(rids, vec!["q", "h"]);
3106        // None of the old rungs left: the plan's lowest.
3107        let only_f = vec![LayerSpec::new("f", 1280, 720, 1700, 30)];
3108        let got = backup_layers_for(&only_f, &old);
3109        assert_eq!(
3110            (got.len(), got[0].rid.as_str(), got[0].temporal_layers),
3111            (1, "f", 3)
3112        );
3113    }
3114}