Skip to main content

kessel_video/
types.rs

1//! The API's data types: codecs and capabilities, capture, encoder and
2//! decoder settings, and events.
3//!
4//! Every struct is `#[non_exhaustive]`, so a caller in another crate can't
5//! build one with a struct literal: each has a constructor (or `Default`)
6//! and public fields to set afterwards.
7
8use crate::error::{invalid, VideoError};
9use crate::frame::{PixelFormat, Planes};
10use bytes::Bytes;
11use std::any::Any;
12use std::sync::Arc;
13
14// ───────────────────────────── codecs and capabilities ─────────────────────────────
15
16/// A video codec. More variants (VP9, AV1) are added as minor versions.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
18#[non_exhaustive]
19pub enum VideoCodec {
20    /// VP8 (RFC 6386). Encoded frames are raw VP8 frames: the frame tag
21    /// first, no IVF/WebM container, one frame per [`EncodedFrame`].
22    Vp8,
23    /// H.264 / AVC. Encoded frames are one Annex B access unit with 4-byte
24    /// start codes, SPS and PPS before every IDR.
25    H264,
26}
27
28impl VideoCodec {
29    /// The SDP / RTP name: `VP8`, `H264`.
30    pub fn sdp_name(&self) -> &'static str {
31        match self {
32            VideoCodec::Vp8 => "VP8",
33            VideoCodec::H264 => "H264",
34        }
35    }
36}
37
38/// Encode or decode.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40#[non_exhaustive]
41pub enum CodecDirection {
42    /// Encode.
43    Encode,
44    /// Decode.
45    Decode,
46}
47
48/// Who runs the codec.
49///
50/// An open encoder or decoder reports what the OS actually created
51/// ([`EncoderInfo::implementation`], [`DecoderStats::implementation`]), read
52/// back from the session, never what was asked for or listed.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54#[non_exhaustive]
55pub enum Implementation {
56    /// A GPU / media engine.
57    Hardware,
58    /// The CPU.
59    Software,
60    /// The OS doesn't say which (an iOS before 17.4, an Android before
61    /// API 28). Only an open session reports it; capability entries are
62    /// always `Hardware` or `Software`. Treat it as not known to be
63    /// hardware.
64    Unknown,
65}
66
67/// The caller's preference when creating a codec.
68#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
69#[non_exhaustive]
70pub enum ImplPreference {
71    /// Hardware if one is free, else software.
72    #[default]
73    PreferHardware,
74    /// Hardware or [`VideoError::Unsupported`].
75    HardwareOnly,
76    /// Software only.
77    SoftwareOnly,
78}
79
80/// H.264 profiles. Never with B-frames.
81#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
82#[non_exhaustive]
83pub enum H264Profile {
84    /// `profile_idc` 66 with constraint_set1 (`42e0`). Every browser decodes
85    /// it.
86    #[default]
87    ConstrainedBaseline,
88    /// `profile_idc` 100 with constraint_set4 and 5 (`640c`): High with no
89    /// B-frames.
90    ConstrainedHigh,
91}
92
93/// An H.264 `level_idc` (31 = 3.1, 40 = 4.0).
94#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
95pub struct H264Level(pub u8);
96
97impl H264Level {
98    /// Level 3.1: up to 1280x720 at 30 fps.
99    pub const L3_1: H264Level = H264Level(31);
100    /// Level 4.0: up to 1920x1080 at 30 fps.
101    pub const L4_0: H264Level = H264Level(40);
102    /// Level 5.1: up to 4096x2304 at 30 fps.
103    pub const L5_1: H264Level = H264Level(51);
104
105    /// The lowest level whose macroblock rate and frame size cover
106    /// `width` x `height` at `fps` (Table A-1), at most 5.2.
107    pub fn for_size(width: u32, height: u32, fps: u32) -> H264Level {
108        let mbs = (width.div_ceil(16) * height.div_ceil(16)) as u64;
109        let rate = mbs * fps.max(1) as u64;
110        const TABLE: [(u8, u64, u64); 12] = [
111            (10, 1_485, 99),
112            (11, 3_000, 396),
113            (12, 6_000, 396),
114            (13, 11_880, 396),
115            (20, 11_880, 396),
116            (21, 19_800, 792),
117            (22, 20_250, 1_620),
118            (30, 40_500, 1_620),
119            (31, 108_000, 3_600),
120            (32, 216_000, 5_120),
121            (40, 245_760, 8_192),
122            (51, 983_040, 36_864),
123        ];
124        for (level, max_rate, max_fs) in TABLE {
125            if rate <= max_rate && mbs <= max_fs {
126                return H264Level(level);
127            }
128        }
129        H264Level(52)
130    }
131}
132
133/// H.264 abilities of one codec entry.
134#[derive(Clone, Debug, PartialEq, Eq)]
135#[non_exhaustive]
136pub struct H264Capability {
137    /// The profiles it does.
138    pub profiles: Vec<H264Profile>,
139    /// The highest level.
140    pub max_level: H264Level,
141}
142
143impl H264Capability {
144    /// Profiles and the highest level.
145    pub fn new(profiles: Vec<H264Profile>, max_level: H264Level) -> H264Capability {
146        H264Capability {
147            profiles,
148            max_level,
149        }
150    }
151}
152
153/// What one backend can do with one codec in one direction. One entry per
154/// (codec, direction, implementation).
155#[derive(Clone, Debug, PartialEq, Eq)]
156#[non_exhaustive]
157pub struct CodecCapability {
158    /// The codec.
159    pub codec: VideoCodec,
160    /// Encode or decode.
161    pub direction: CodecDirection,
162    /// Hardware or software.
163    pub implementation: Implementation,
164    /// For logs and stats: "VideoToolbox", "kessel-vp8 0.1", ...
165    pub name: String,
166    /// The largest coded width.
167    pub max_width: u32,
168    /// The largest coded height.
169    pub max_height: u32,
170    /// The highest frame rate at `max_width` x `max_height`.
171    pub max_fps: u32,
172    /// How many may be open at once on this machine, if known. `None`: no
173    /// known limit.
174    pub max_instances: Option<u32>,
175    /// Encode: the most temporal layers it can mark. 1 = none. Decode: 1.
176    pub max_temporal_layers: u8,
177    /// H.264 only: profiles and the highest level.
178    pub h264: Option<H264Capability>,
179    /// Encode: accepted input formats. Decode: formats it can output.
180    pub formats: Vec<PixelFormat>,
181    /// Decode: [`DecodeMode::File`] works here (access units in decode
182    /// order in, frames in presentation order out). Encode: false.
183    pub file_mode: bool,
184}
185
186impl CodecCapability {
187    /// An entry with no instance limit, no temporal layers, no H.264
188    /// details and no formats; set the rest on the result.
189    pub fn new(
190        codec: VideoCodec,
191        direction: CodecDirection,
192        implementation: Implementation,
193        name: impl Into<String>,
194        max_width: u32,
195        max_height: u32,
196        max_fps: u32,
197    ) -> CodecCapability {
198        CodecCapability {
199            codec,
200            direction,
201            implementation,
202            name: name.into(),
203            max_width,
204            max_height,
205            max_fps,
206            max_instances: None,
207            max_temporal_layers: 1,
208            h264: None,
209            formats: Vec::new(),
210            file_mode: false,
211        }
212    }
213}
214
215/// Screen capture support.
216#[derive(Clone, Debug, Default, PartialEq, Eq)]
217#[non_exhaustive]
218pub struct ScreenCapability {
219    /// Any screen capture at all.
220    pub supported: bool,
221    /// `pick_screen` shows the OS picker.
222    pub system_picker: bool,
223    /// `screen_sources` lists displays and windows.
224    pub list: bool,
225    /// Single windows, not only displays.
226    pub windows: bool,
227    /// The cursor can be drawn into frames.
228    pub cursor: bool,
229    /// [`CaptureConstraints::exclude_own_windows`] works here.
230    pub exclude_own_windows: bool,
231    /// Screen frames come from outside the backend, through a source the
232    /// app feeds ([`crate::frame_in()`]): on iOS, from the app's broadcast
233    /// upload extension. `pick_screen` and `open_screen` answer
234    /// `Unsupported`; wait for the app's frames instead of opening a picker.
235    pub frame_in: bool,
236}
237
238/// The whole capability answer of a backend.
239#[derive(Clone, Debug, PartialEq, Eq)]
240#[non_exhaustive]
241pub struct Capabilities {
242    /// "apple", "windows", "linux", "android", "fake", "null".
243    pub backend: &'static str,
244    /// The OS and version, for logs.
245    pub os: String,
246    /// Codec entries.
247    pub codecs: Vec<CodecCapability>,
248    /// A camera API is present (cameras may still be zero).
249    pub camera: bool,
250    /// Screen capture.
251    pub screen: ScreenCapability,
252}
253
254impl Capabilities {
255    /// No codecs, no camera, no screen.
256    pub fn new(backend: &'static str, os: impl Into<String>) -> Capabilities {
257        Capabilities {
258            backend,
259            os: os.into(),
260            codecs: Vec::new(),
261            camera: false,
262            screen: ScreenCapability::default(),
263        }
264    }
265
266    /// The best entry for `codec` in `dir` (hardware first, then the largest
267    /// max size).
268    pub fn best(&self, codec: VideoCodec, dir: CodecDirection) -> Option<&CodecCapability> {
269        self.codecs
270            .iter()
271            .filter(|c| c.codec == codec && c.direction == dir)
272            .max_by_key(|c| {
273                (
274                    c.implementation == Implementation::Hardware,
275                    c.max_width as u64 * c.max_height as u64,
276                )
277            })
278    }
279}
280
281// ───────────────────────────── permissions and capture ─────────────────────────────
282
283/// The state of an OS permission.
284#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
285#[non_exhaustive]
286pub enum Permission {
287    /// Allowed.
288    Granted,
289    /// Refused (or the app can't ask: no usage description).
290    Denied,
291    /// Policy forbids it.
292    Restricted,
293    /// Never asked.
294    NotDetermined,
295}
296
297/// Which way a camera faces.
298#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
299#[non_exhaustive]
300pub enum Facing {
301    /// The person's side (phones, laptops' built-in cameras).
302    Front,
303    /// The far side (phones).
304    Back,
305    /// A plugged-in camera.
306    External,
307    /// The OS doesn't say.
308    Unknown,
309}
310
311/// One mode a camera offers.
312#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
313#[non_exhaustive]
314pub struct CaptureMode {
315    /// Width in pixels.
316    pub width: u32,
317    /// Height in pixels.
318    pub height: u32,
319    /// The highest frame rate.
320    pub max_fps: u32,
321    /// What the device delivers in this mode.
322    pub format: PixelFormat,
323}
324
325impl CaptureMode {
326    /// A mode.
327    pub fn new(width: u32, height: u32, max_fps: u32, format: PixelFormat) -> CaptureMode {
328        CaptureMode {
329            width,
330            height,
331            max_fps,
332            format,
333        }
334    }
335}
336
337/// A camera.
338#[derive(Clone, Debug, PartialEq, Eq)]
339#[non_exhaustive]
340pub struct CameraInfo {
341    /// Stable across runs where the OS allows, and the same when a camera
342    /// goes away and comes back: `AVCaptureDevice.uniqueID` on macOS and
343    /// iOS, the device's symbolic link on Windows, its `/dev/v4l/by-id`
344    /// name on Linux when there is one (else its `/dev/videoN` path), the
345    /// Camera2 id on Android. Pass it to `open_camera` to open this camera.
346    pub id: String,
347    /// Display name.
348    pub name: String,
349    /// Which way it faces.
350    pub facing: Facing,
351    /// The system default, suspended or not. An open with no id skips it
352    /// while it is suspended (see `VideoBackend::open_camera`).
353    pub is_default: bool,
354    /// Its modes.
355    pub modes: Vec<CaptureMode>,
356    /// The OS lists the camera but says it can't deliver frames now. macOS
357    /// reports this for a MacBook's built-in camera while the lid is closed
358    /// and for a camera whose lens cover is shut
359    /// (`AVCaptureDevice.isSuspended`, read on iOS too). Opening it works
360    /// but gives no frames until it comes back; an open source reports
361    /// [`Interruption::Suspended`] meanwhile. An open with no id passes
362    /// over it for the first camera that isn't suspended. A change shows in
363    /// [`BackendEvent::Cameras`]. Always `false` where the OS doesn't
364    /// report it: Windows, Linux and Android (and the fake backend, unless
365    /// its script sets it).
366    pub suspended: bool,
367}
368
369/// The camera an open with no id takes from a listing: the default (else
370/// the first) unless it is suspended, then the first camera in the list's
371/// order that isn't; when every one is suspended, the default.
372pub(crate) fn default_camera(cams: &[CameraInfo]) -> Option<&CameraInfo> {
373    let def = cams.iter().find(|c| c.is_default).or(cams.first())?;
374    if !def.suspended {
375        return Some(def);
376    }
377    Some(cams.iter().find(|c| !c.suspended).unwrap_or(def))
378}
379
380impl CameraInfo {
381    /// A camera with no modes listed, not suspended.
382    pub fn new(
383        id: impl Into<String>,
384        name: impl Into<String>,
385        facing: Facing,
386        is_default: bool,
387    ) -> CameraInfo {
388        CameraInfo {
389            id: id.into(),
390            name: name.into(),
391            facing,
392            is_default,
393            modes: Vec::new(),
394            suspended: false,
395        }
396    }
397}
398
399/// What to ask of a capture source. The backend picks the nearest mode at
400/// or above the size (then scales down) and at or above `fps` (then drops
401/// frames evenly). `None`: the device's default.
402#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
403#[non_exhaustive]
404pub struct CaptureConstraints {
405    /// The widest frame wanted.
406    pub max_width: Option<u32>,
407    /// The tallest frame wanted.
408    pub max_height: Option<u32>,
409    /// Frames per second.
410    pub fps: Option<u32>,
411    /// Phones: prefer this camera when no id is given.
412    pub facing: Option<Facing>,
413    /// Prefer native buffers when an encoder of this backend will take them.
414    pub prefer_native: bool,
415    /// Screen only: draw the cursor.
416    pub cursor: bool,
417    /// Display capture only: leave this app's own windows out, where the OS
418    /// allows it ([`ScreenCapability::exclude_own_windows`]); otherwise
419    /// ignored.
420    pub exclude_own_windows: bool,
421}
422
423impl CaptureConstraints {
424    /// At most `max_width` x `max_height` at `fps`.
425    pub fn new(max_width: u32, max_height: u32, fps: u32) -> CaptureConstraints {
426        CaptureConstraints {
427            max_width: Some(max_width),
428            max_height: Some(max_height),
429            fps: Some(fps),
430            ..CaptureConstraints::default()
431        }
432    }
433
434    pub(crate) fn validate(&self) -> Result<(), VideoError> {
435        for v in [self.max_width, self.max_height].into_iter().flatten() {
436            if !(16..=8192).contains(&v) {
437                return Err(invalid(format!("a capture size of {v}")));
438            }
439        }
440        if let Some(f) = self.fps {
441            if !(1..=240).contains(&f) {
442                return Err(invalid(format!("{f} fps")));
443            }
444        }
445        Ok(())
446    }
447}
448
449/// Pick the mode for `c`: the smallest at or above the wanted size and rate,
450/// else the largest. Ties go to the higher rate.
451pub fn nearest_mode(modes: &[CaptureMode], c: &CaptureConstraints) -> Option<CaptureMode> {
452    let (w, h, fps) = (
453        c.max_width.unwrap_or(1280),
454        c.max_height.unwrap_or(720),
455        c.fps.unwrap_or(30),
456    );
457    let area = |m: &CaptureMode| m.width as u64 * m.height as u64;
458    modes
459        .iter()
460        .filter(|m| m.width >= w && m.height >= h && m.max_fps >= fps)
461        .min_by_key(|m| (area(m), std::cmp::Reverse(m.max_fps)))
462        .or_else(|| {
463            // Nothing covers it: the largest at the rate, else the largest.
464            modes
465                .iter()
466                .filter(|m| m.max_fps >= fps)
467                .max_by_key(|m| (area(m), m.max_fps))
468                .or_else(|| modes.iter().max_by_key(|m| (area(m), m.max_fps)))
469        })
470        .copied()
471}
472
473/// Why a source ended.
474#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
475#[non_exhaustive]
476pub enum EndReason {
477    /// The caller dropped or closed it.
478    Closed,
479    /// The device went away, or the OS stopped capturing from it for good:
480    /// unplugged, a Continuity Camera that disconnected, a capture session
481    /// that died with a runtime error, a read the OS refused. Drop the
482    /// source and open a camera again: another one, or this one once
483    /// [`cameras`](crate::VideoBackend::cameras) lists it again (by the
484    /// same [`CameraInfo::id`]). A pause the OS will undo is never this: a
485    /// phone call or the app in the background is
486    /// [`SourceEvent::Interrupted`], then [`SourceEvent::Resumed`].
487    DeviceLost,
488    /// The person stopped it from OS UI.
489    UserStopped,
490    /// The shared window closed.
491    SourceClosed,
492    /// The permission was revoked while running.
493    Revoked,
494}
495
496/// Why a source paused without ending.
497#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
498#[non_exhaustive]
499pub enum Interruption {
500    /// Phones: the app went to the background.
501    Background,
502    /// Another app took the camera.
503    InUseByAnother,
504    /// Thermal pressure: the OS stopped the camera.
505    Thermal,
506    /// A screen source is minimised or occluded.
507    Hidden,
508    /// The camera says it is suspended (macOS and iOS): a MacBook's
509    /// built-in camera while its lid is closed, a shut lens cover. See
510    /// [`CameraInfo::suspended`].
511    Suspended,
512}
513
514/// A source's events, in order.
515#[derive(Clone, Debug, PartialEq, Eq)]
516#[non_exhaustive]
517pub enum SourceEvent {
518    /// First frame, and after any change of the delivered size or rate.
519    Started {
520        /// Delivered width.
521        width: u32,
522        /// Delivered height.
523        height: u32,
524        /// Delivered rate.
525        fps: u32,
526    },
527    /// Paused by the OS.
528    Interrupted(Interruption),
529    /// Back after an interruption.
530    Resumed,
531    /// Terminal: no more frames; drop the source.
532    Ended(EndReason),
533    /// A non-terminal problem.
534    Error(VideoError),
535}
536
537/// A source's counters since open.
538#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
539#[non_exhaustive]
540pub struct SourceStats {
541    /// Frames queued.
542    pub frames: u64,
543    /// Frames dropped (queue full, or skipped to keep the rate).
544    pub dropped: u64,
545    /// The delivered width.
546    pub width: u32,
547    /// The delivered height.
548    pub height: u32,
549    /// The delivered rate.
550    pub fps: u32,
551}
552
553/// Display or window.
554#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
555#[non_exhaustive]
556pub enum ScreenKind {
557    /// A whole display.
558    Display,
559    /// One window.
560    Window,
561}
562
563/// A display or window from `screen_sources`.
564#[derive(Clone, Debug, PartialEq, Eq)]
565#[non_exhaustive]
566pub struct ScreenSourceInfo {
567    /// For [`ScreenSelection::Listed`].
568    pub id: String,
569    /// Display or window.
570    pub kind: ScreenKind,
571    /// Display name or window title.
572    pub title: String,
573    /// The owning app, when known.
574    pub app: Option<String>,
575    /// Width in pixels.
576    pub width: u32,
577    /// Height in pixels.
578    pub height: u32,
579    /// A small preview, if cheap (at most 320 px wide, RGBA). Its size is
580    /// in `thumbnail_width` and `thumbnail_height`
581    /// ([`ScreenSourceInfo::thumbnail_size`]); set all three with
582    /// [`ScreenSourceInfo::with_thumbnail`].
583    pub thumbnail: Option<Planes>,
584    /// The thumbnail's width in pixels, 0 with no thumbnail.
585    pub thumbnail_width: u32,
586    /// The thumbnail's height in pixels, 0 with no thumbnail.
587    pub thumbnail_height: u32,
588}
589
590impl ScreenSourceInfo {
591    /// A source with no app and no thumbnail.
592    pub fn new(
593        id: impl Into<String>,
594        kind: ScreenKind,
595        title: impl Into<String>,
596        width: u32,
597        height: u32,
598    ) -> ScreenSourceInfo {
599        ScreenSourceInfo {
600            id: id.into(),
601            kind,
602            title: title.into(),
603            app: None,
604            width,
605            height,
606            thumbnail: None,
607            thumbnail_width: 0,
608            thumbnail_height: 0,
609        }
610    }
611
612    /// The same source with a `width` x `height` RGBA thumbnail, at most 320
613    /// px wide. Errors if the planes aren't RGBA, are wider than that, or
614    /// don't hold a frame of that size.
615    pub fn with_thumbnail(
616        mut self,
617        planes: Planes,
618        width: u32,
619        height: u32,
620    ) -> Result<ScreenSourceInfo, VideoError> {
621        if planes.format != PixelFormat::Rgba {
622            return Err(invalid(format!(
623                "a thumbnail is RGBA, not {:?}",
624                planes.format
625            )));
626        }
627        if width > 320 {
628            return Err(invalid(format!(
629                "a thumbnail is at most 320 px wide, not {width}"
630            )));
631        }
632        planes.validate(width, height)?;
633        self.thumbnail = Some(planes);
634        self.thumbnail_width = width;
635        self.thumbnail_height = height;
636        Ok(self)
637    }
638
639    /// The thumbnail's width and height, when there is a thumbnail and its
640    /// size is set.
641    pub fn thumbnail_size(&self) -> Option<(u32, u32)> {
642        let sized = self.thumbnail_width > 0 && self.thumbnail_height > 0;
643        (self.thumbnail.is_some() && sized).then_some((self.thumbnail_width, self.thumbnail_height))
644    }
645}
646
647/// A chosen screen source: from the list, or the OS picker's opaque handle.
648#[derive(Clone)]
649#[non_exhaustive]
650pub enum ScreenSelection {
651    /// An id from `screen_sources`.
652    Listed(String),
653    /// What the system picker or portal returned.
654    Picked(Arc<dyn Any + Send + Sync>),
655}
656
657impl std::fmt::Debug for ScreenSelection {
658    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
659        match self {
660            ScreenSelection::Listed(id) => f.debug_tuple("Listed").field(id).finish(),
661            ScreenSelection::Picked(_) => f.write_str("Picked(..)"),
662        }
663    }
664}
665
666/// Options for the OS picker.
667#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
668#[non_exhaustive]
669pub struct PickOptions {
670    /// Offer displays.
671    pub displays: bool,
672    /// Offer windows.
673    pub windows: bool,
674    /// The app window that owns the picker. Windows needs it (an `HWND`,
675    /// as an integer): the system picker opens over it. Ignored elsewhere.
676    pub parent_window: Option<u64>,
677}
678
679impl PickOptions {
680    /// Displays and windows, no owner window.
681    pub fn new() -> PickOptions {
682        PickOptions::default()
683    }
684
685    /// The window that owns the picker (an `HWND` on Windows).
686    pub fn with_parent_window(mut self, handle: u64) -> PickOptions {
687        self.parent_window = Some(handle);
688        self
689    }
690}
691
692// ───────────────────────────── encoder ─────────────────────────────
693
694/// What the content is.
695#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
696#[non_exhaustive]
697pub enum ContentHint {
698    /// Motion: keep the frame rate, lower detail first.
699    #[default]
700    Camera,
701    /// Text and UI: keep detail, lower the frame rate first.
702    Screen,
703}
704
705/// Per-codec settings.
706#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
707#[non_exhaustive]
708pub enum CodecConfig {
709    /// VP8.
710    Vp8,
711    /// H.264.
712    H264 {
713        /// The profile.
714        profile: H264Profile,
715        /// The level.
716        level: H264Level,
717    },
718}
719
720impl CodecConfig {
721    /// The codec.
722    pub fn codec(&self) -> VideoCodec {
723        match self {
724            CodecConfig::Vp8 => VideoCodec::Vp8,
725            CodecConfig::H264 { .. } => VideoCodec::H264,
726        }
727    }
728}
729
730/// One encoder instance, one simulcast layer.
731#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
732#[non_exhaustive]
733pub struct EncoderConfig {
734    /// Codec settings.
735    pub codec: CodecConfig,
736    /// The coded width. Input frames of any size are scaled to it. Even.
737    pub width: u32,
738    /// The coded height. Even.
739    pub height: u32,
740    /// The target frame rate.
741    pub fps: u32,
742    /// Target bitrate, bits per second.
743    pub bitrate_bps: u32,
744    /// Hard ceiling for any one second. At least `bitrate_bps`.
745    pub max_bitrate_bps: u32,
746    /// Keyframe every N frames; `None`: only on `request_keyframe`.
747    pub keyframe_interval: Option<u32>,
748    /// 1 = no temporal layers; 2 or 3 = L1T2 / L1T3 (VP8 only in v1).
749    pub temporal_layers: u8,
750    /// Camera or screen.
751    pub content: ContentHint,
752    /// Hardware or software.
753    pub implementation: ImplPreference,
754}
755
756impl EncoderConfig {
757    /// `codec` at `width` x `height`, `fps`, `bitrate_bps` (max 1.5x),
758    /// keyframes on request, one temporal layer, camera, hardware preferred.
759    pub fn new(
760        codec: CodecConfig,
761        width: u32,
762        height: u32,
763        fps: u32,
764        bitrate_bps: u32,
765    ) -> EncoderConfig {
766        EncoderConfig {
767            codec,
768            width,
769            height,
770            fps,
771            bitrate_bps,
772            max_bitrate_bps: bitrate_bps.saturating_add(bitrate_bps / 2),
773            keyframe_interval: None,
774            temporal_layers: 1,
775            content: ContentHint::default(),
776            implementation: ImplPreference::default(),
777        }
778    }
779
780    /// H.264 Constrained Baseline at the level the size and rate need.
781    pub fn h264(width: u32, height: u32, fps: u32, bitrate_bps: u32) -> EncoderConfig {
782        let level = H264Level::for_size(width, height, fps).max(H264Level::L3_1);
783        EncoderConfig::new(
784            CodecConfig::H264 {
785                profile: H264Profile::ConstrainedBaseline,
786                level,
787            },
788            width,
789            height,
790            fps,
791            bitrate_bps,
792        )
793    }
794
795    /// Check the configuration on its own (backends check what they can do).
796    pub fn validate(&self) -> Result<(), VideoError> {
797        validate_size(self.width, self.height)?;
798        if !(1..=240).contains(&self.fps) {
799            return Err(invalid(format!("{} fps", self.fps)));
800        }
801        if self.bitrate_bps < 10_000 {
802            return Err(invalid(format!("{} bit/s", self.bitrate_bps)));
803        }
804        if self.max_bitrate_bps < self.bitrate_bps {
805            return Err(invalid(format!(
806                "max_bitrate_bps {} is below bitrate_bps {}",
807                self.max_bitrate_bps, self.bitrate_bps
808            )));
809        }
810        if self.keyframe_interval == Some(0) {
811            return Err(invalid("a keyframe interval of 0 frames"));
812        }
813        let max_tl = if self.codec.codec() == VideoCodec::H264 {
814            1
815        } else {
816            3
817        };
818        if self.temporal_layers == 0 || self.temporal_layers > max_tl {
819            return Err(invalid(format!(
820                "{} temporal layers for {:?}",
821                self.temporal_layers,
822                self.codec.codec()
823            )));
824        }
825        Ok(())
826    }
827}
828
829pub(crate) fn validate_size(width: u32, height: u32) -> Result<(), VideoError> {
830    if width < 16
831        || height < 16
832        || width > 8192
833        || height > 8192
834        || !width.is_multiple_of(2)
835        || !height.is_multiple_of(2)
836    {
837        return Err(invalid(format!(
838            "coded size {width}x{height} (even, 16 to 8192)"
839        )));
840    }
841    Ok(())
842}
843
844/// A runtime rate change. Never causes a keyframe.
845#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
846#[non_exhaustive]
847pub struct Rates {
848    /// Bits per second.
849    pub bitrate_bps: u32,
850    /// Frames per second.
851    pub fps: u32,
852}
853
854impl Rates {
855    /// Bitrate and frame rate.
856    pub fn new(bitrate_bps: u32, fps: u32) -> Rates {
857        Rates { bitrate_bps, fps }
858    }
859
860    pub(crate) fn validate(&self) -> Result<(), VideoError> {
861        if self.bitrate_bps < 10_000 || !(1..=240).contains(&self.fps) {
862            return Err(invalid(format!(
863                "rates {} bit/s at {} fps",
864                self.bitrate_bps, self.fps
865            )));
866        }
867        Ok(())
868    }
869}
870
871/// Options for one `submit`.
872#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
873#[non_exhaustive]
874pub struct EncodeOptions {
875    /// Encode this frame as a keyframe.
876    pub keyframe: bool,
877}
878
879impl EncodeOptions {
880    /// A keyframe.
881    pub fn keyframe() -> EncodeOptions {
882        EncodeOptions { keyframe: true }
883    }
884}
885
886/// Where an encoded frame sits in the temporal and spatial structure.
887#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
888#[non_exhaustive]
889pub struct LayerInfo {
890    /// 0 = base.
891    pub temporal_id: u8,
892    /// RFC 7741's Y bit: depends only on the base layer, or a keyframe.
893    pub layer_sync: bool,
894    /// Reserved for VP9/AV1 SVC: always 0 in v1.
895    pub spatial_id: u8,
896}
897
898impl LayerInfo {
899    /// A layer.
900    pub fn new(temporal_id: u8, layer_sync: bool) -> LayerInfo {
901        LayerInfo {
902            temporal_id,
903            layer_sync,
904            spatial_id: 0,
905        }
906    }
907}
908
909/// One encoded frame, plaintext.
910#[derive(Clone, Debug, PartialEq, Eq)]
911#[non_exhaustive]
912pub struct EncodedFrame {
913    /// The codec.
914    pub codec: VideoCodec,
915    /// VP8: one raw VP8 frame. H.264: one Annex B access unit.
916    pub data: Bytes,
917    /// A keyframe.
918    pub keyframe: bool,
919    /// The input frame's `capture_us`, unchanged.
920    pub capture_us: u64,
921    /// The coded width.
922    pub width: u32,
923    /// The coded height.
924    pub height: u32,
925    /// Temporal layer.
926    pub layer: LayerInfo,
927    /// Encode time in µs (stats only).
928    pub encode_us: u32,
929}
930
931impl EncodedFrame {
932    /// A frame in the base layer with no encode time.
933    pub fn new(
934        codec: VideoCodec,
935        data: impl Into<Bytes>,
936        keyframe: bool,
937        capture_us: u64,
938        width: u32,
939        height: u32,
940    ) -> EncodedFrame {
941        EncodedFrame {
942            codec,
943            data: data.into(),
944            keyframe,
945            capture_us,
946            width,
947            height,
948            layer: LayerInfo::new(0, true),
949            encode_us: 0,
950        }
951    }
952}
953
954/// What an encoder actually runs.
955#[derive(Clone, Debug, PartialEq, Eq)]
956#[non_exhaustive]
957pub struct EncoderInfo {
958    /// What the open session runs, read back from the OS: `Hardware`,
959    /// `Software`, or `Unknown` when the OS doesn't say. Follows a
960    /// `set_size` that reopens the session.
961    pub implementation: Implementation,
962    /// For logs.
963    pub name: String,
964    /// The configuration, with the latest rates and size.
965    pub config: EncoderConfig,
966}
967
968impl EncoderInfo {
969    /// Info.
970    pub fn new(
971        implementation: Implementation,
972        name: impl Into<String>,
973        config: EncoderConfig,
974    ) -> EncoderInfo {
975        EncoderInfo {
976            implementation,
977            name: name.into(),
978            config,
979        }
980    }
981}
982
983/// An encoder's counters.
984#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
985#[non_exhaustive]
986pub struct EncoderStats {
987    /// Frames accepted by `submit`.
988    pub frames_in: u64,
989    /// Frames out.
990    pub frames_out: u64,
991    /// Keyframes out.
992    pub keyframes: u64,
993    /// Inputs rate control skipped.
994    pub dropped_by_rc: u64,
995    /// `submit` calls answered `Busy`.
996    pub busy: u64,
997    /// Bytes out.
998    pub bytes_out: u64,
999}
1000
1001// ───────────────────────────── decoder ─────────────────────────────
1002
1003/// How a decoder treats its input and output.
1004#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1005#[non_exhaustive]
1006pub enum DecodeMode {
1007    /// A live track (the default): each input decodes at once and its frame
1008    /// comes out at once, in submit order, stamped with the input's
1009    /// `capture_us`. No reordering, so no B-frames. The output queue holds
1010    /// 2 and drops the oldest: a late frame is worth less than the next.
1011    #[default]
1012    Realtime,
1013    /// A file: access units go in in **decode order**, each with its
1014    /// presentation time in [`EncodedInput::capture_us`] (µs) and, when
1015    /// the container has one, its decode time in [`EncodedInput::dts_us`].
1016    /// The OS session may reorder (B-frames), and frames come out in
1017    /// **presentation order**, each stamped with its own pts.
1018    ///
1019    /// - Nothing is dropped: up to [`DecoderConfig::output_queue`] frames
1020    ///   wait for `poll`, and `submit` answers `Busy` while that many do.
1021    /// - The decoder holds frames back for reordering, as the stream's SPS
1022    ///   says it may need. [`VideoDecoder::flush`] at the end of the stream
1023    ///   (or before a seek) gives every frame still inside, then
1024    ///   [`DecodeError::EndOfStream`].
1025    /// - H.264 streams the OS decoder here can't decode to 8-bit 4:2:0
1026    ///   (10-bit, 4:2:2, 4:4:4, monochrome) are refused with
1027    ///   `Unsupported`, never decoded wrong.
1028    ///
1029    /// [`VideoDecoder::flush`]: crate::VideoDecoder::flush
1030    /// [`DecodeError::EndOfStream`]: crate::DecodeError::EndOfStream
1031    File,
1032}
1033
1034/// One decoder per remote track (or per file, in [`DecodeMode::File`]).
1035#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1036#[non_exhaustive]
1037pub struct DecoderConfig {
1038    /// The codec.
1039    pub codec: VideoCodec,
1040    /// Hardware or software.
1041    pub implementation: ImplPreference,
1042    /// Output CPU planes in this format, or `Native` to keep OS buffers.
1043    pub output: PixelFormat,
1044    /// Scale outputs to fit this box, keeping the aspect ratio; `None`: the
1045    /// coded size.
1046    pub fit: Option<(u32, u32)>,
1047    /// Real time (the default) or a file.
1048    pub mode: DecodeMode,
1049    /// [`DecodeMode::File`] only: how many decoded frames may wait for
1050    /// `poll` before `submit` answers `Busy`, 1 to
1051    /// [`FILE_OUTPUT_QUEUE_MAX`](crate::kit::FILE_OUTPUT_QUEUE_MAX)
1052    /// (anything else is `Invalid` at open). Real time ignores it: its
1053    /// queue is always 2, oldest dropped.
1054    pub output_queue: usize,
1055}
1056
1057impl DecoderConfig {
1058    /// `codec`, hardware preferred, I420 out at the coded size, real time.
1059    pub fn new(codec: VideoCodec) -> DecoderConfig {
1060        DecoderConfig {
1061            codec,
1062            implementation: ImplPreference::default(),
1063            output: PixelFormat::I420,
1064            fit: None,
1065            mode: DecodeMode::Realtime,
1066            output_queue: crate::kit::FILE_OUTPUT_QUEUE,
1067        }
1068    }
1069
1070    /// `codec` for a file ([`DecodeMode::File`]): hardware preferred, I420
1071    /// out at the coded size, an output queue of
1072    /// [`FILE_OUTPUT_QUEUE`](crate::kit::FILE_OUTPUT_QUEUE).
1073    pub fn file(codec: VideoCodec) -> DecoderConfig {
1074        DecoderConfig {
1075            mode: DecodeMode::File,
1076            ..DecoderConfig::new(codec)
1077        }
1078    }
1079
1080    /// `Invalid` for a File-mode output queue outside 1 to
1081    /// [`FILE_OUTPUT_QUEUE_MAX`](crate::kit::FILE_OUTPUT_QUEUE_MAX).
1082    pub fn validate(&self) -> Result<(), VideoError> {
1083        let max = crate::kit::FILE_OUTPUT_QUEUE_MAX;
1084        if self.mode == DecodeMode::File && !(1..=max).contains(&self.output_queue) {
1085            return Err(invalid(format!(
1086                "a File-mode output queue of {} (1 to {max})",
1087                self.output_queue
1088            )));
1089        }
1090        Ok(())
1091    }
1092}
1093
1094/// One complete, decrypted, verified frame from the depacketiser.
1095#[derive(Clone, Debug, PartialEq, Eq)]
1096#[non_exhaustive]
1097pub struct EncodedInput {
1098    /// The codec.
1099    pub codec: VideoCodec,
1100    /// VP8: raw frame. H.264: Annex B access unit.
1101    pub data: Bytes,
1102    /// The caller's reading of the bitstream (VP8 P bit; an H.264 IDR).
1103    pub keyframe: bool,
1104    /// Real time: passed through to the output `VideoFrame::capture_us`.
1105    /// [`DecodeMode::File`]: the access unit's presentation time (pts) in
1106    /// µs, which its frame comes out with. At most `i64::MAX`.
1107    pub capture_us: u64,
1108    /// [`DecodeMode::File`]: the access unit's decode time (dts) in µs,
1109    /// when the container has one. Each must be later than the one before
1110    /// (until a flush or reset). Real time ignores it.
1111    pub dts_us: Option<u64>,
1112}
1113
1114impl EncodedInput {
1115    /// An input.
1116    pub fn new(
1117        codec: VideoCodec,
1118        data: impl Into<Bytes>,
1119        keyframe: bool,
1120        capture_us: u64,
1121    ) -> EncodedInput {
1122        EncodedInput {
1123            codec,
1124            data: data.into(),
1125            keyframe,
1126            capture_us,
1127            dts_us: None,
1128        }
1129    }
1130
1131    /// An access unit from a file ([`DecodeMode::File`]), in decode order:
1132    /// its presentation and decode times in µs (a container's times on
1133    /// its own timescale convert as `t * 1_000_000 / timescale`).
1134    pub fn file(
1135        codec: VideoCodec,
1136        data: impl Into<Bytes>,
1137        keyframe: bool,
1138        pts_us: u64,
1139        dts_us: Option<u64>,
1140    ) -> EncodedInput {
1141        EncodedInput {
1142            dts_us,
1143            ..EncodedInput::new(codec, data, keyframe, pts_us)
1144        }
1145    }
1146}
1147
1148/// A decoder's counters.
1149#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1150#[non_exhaustive]
1151pub struct DecoderStats {
1152    /// Inputs accepted.
1153    pub frames_in: u64,
1154    /// Frames out.
1155    pub frames_out: u64,
1156    /// Decoded frames dropped: real time, because the output queue was
1157    /// full; [`DecodeMode::File`] (which never drops for room), a frame the
1158    /// OS gave after a later one had already come out, or twice (a broken
1159    /// stream).
1160    pub dropped_out: u64,
1161    /// Errors (including inputs refused for want of a keyframe).
1162    pub errors: u64,
1163    /// What the open session runs, read back from the OS (`Unknown` when
1164    /// the OS doesn't say). `None` until a session is open: a decoder that
1165    /// opens on its first keyframe.
1166    pub implementation: Option<Implementation>,
1167}
1168
1169// ───────────────────────────── backend events ─────────────────────────────
1170
1171/// Thermal pressure.
1172#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
1173#[non_exhaustive]
1174pub enum ThermalLevel {
1175    /// Normal.
1176    Nominal,
1177    /// Slightly raised.
1178    Fair,
1179    /// High: shed load.
1180    Serious,
1181    /// Critical: shed everything that can go.
1182    Critical,
1183}
1184
1185/// Machine-wide events.
1186#[derive(Clone, Debug, PartialEq, Eq)]
1187#[non_exhaustive]
1188pub enum BackendEvent {
1189    /// The camera list changed. The full new list.
1190    Cameras(Vec<CameraInfo>),
1191    /// Codecs or screen support changed.
1192    CapabilitiesChanged,
1193    /// Thermal pressure.
1194    Thermal(ThermalLevel),
1195    /// Low-power mode on or off.
1196    LowPower(bool),
1197    /// Phones: the app went to the background (`true`) or came back.
1198    Background(bool),
1199}
1200
1201#[cfg(test)]
1202mod tests {
1203    use super::*;
1204
1205    #[test]
1206    fn levels_follow_table_a1() {
1207        assert_eq!(H264Level::for_size(320, 180, 30), H264Level(13));
1208        assert_eq!(H264Level::for_size(640, 360, 30), H264Level(30));
1209        assert_eq!(H264Level::for_size(1280, 720, 30), H264Level(31));
1210        assert_eq!(H264Level::for_size(1280, 720, 60), H264Level(32));
1211        assert_eq!(H264Level::for_size(1920, 1080, 30), H264Level(40));
1212        assert_eq!(H264Level::for_size(3840, 2160, 30), H264Level(51));
1213    }
1214
1215    #[test]
1216    fn encoder_configs_are_checked() {
1217        let c = EncoderConfig::h264(1280, 720, 30, 1_500_000);
1218        assert!(c.validate().is_ok());
1219        assert_eq!(c.max_bitrate_bps, 2_250_000);
1220        assert_eq!(
1221            c.codec,
1222            CodecConfig::H264 {
1223                profile: H264Profile::ConstrainedBaseline,
1224                level: H264Level(31)
1225            }
1226        );
1227        let mut odd = c;
1228        odd.width = 1281;
1229        assert!(matches!(odd.validate(), Err(VideoError::Invalid(_))));
1230        let mut tl = c;
1231        tl.temporal_layers = 2;
1232        assert!(tl.validate().is_err(), "H.264 has one temporal layer");
1233        let mut vp8 = EncoderConfig::new(CodecConfig::Vp8, 640, 360, 30, 500_000);
1234        vp8.temporal_layers = 3;
1235        assert!(vp8.validate().is_ok());
1236        vp8.max_bitrate_bps = 1;
1237        assert!(vp8.validate().is_err());
1238        let mut k = c;
1239        k.keyframe_interval = Some(0);
1240        assert!(k.validate().is_err());
1241        assert!(Rates::new(5_000, 30).validate().is_err());
1242    }
1243
1244    #[test]
1245    fn best_prefers_hardware_then_size() {
1246        let mut caps = Capabilities::new("fake", "test");
1247        caps.codecs.push(CodecCapability::new(
1248            VideoCodec::H264,
1249            CodecDirection::Encode,
1250            Implementation::Software,
1251            "sw",
1252            3840,
1253            2160,
1254            30,
1255        ));
1256        caps.codecs.push(CodecCapability::new(
1257            VideoCodec::H264,
1258            CodecDirection::Encode,
1259            Implementation::Hardware,
1260            "hw",
1261            1920,
1262            1080,
1263            30,
1264        ));
1265        caps.codecs.push(CodecCapability::new(
1266            VideoCodec::H264,
1267            CodecDirection::Decode,
1268            Implementation::Software,
1269            "dec",
1270            1920,
1271            1080,
1272            30,
1273        ));
1274        assert_eq!(
1275            caps.best(VideoCodec::H264, CodecDirection::Encode)
1276                .map(|c| c.name.as_str()),
1277            Some("hw")
1278        );
1279        assert_eq!(
1280            caps.best(VideoCodec::H264, CodecDirection::Decode)
1281                .map(|c| c.name.as_str()),
1282            Some("dec")
1283        );
1284        assert!(caps.best(VideoCodec::Vp8, CodecDirection::Encode).is_none());
1285    }
1286
1287    #[test]
1288    fn nearest_mode_covers_the_ask() {
1289        let f = PixelFormat::Nv12;
1290        let ms = [
1291            CaptureMode::new(1920, 1080, 30, f),
1292            CaptureMode::new(1280, 720, 60, f),
1293            CaptureMode::new(640, 480, 30, f),
1294        ];
1295        let at = |w, h, fps| nearest_mode(&ms, &CaptureConstraints::new(w, h, fps)).expect("one");
1296        assert_eq!(
1297            (at(1280, 720, 30).width, at(1280, 720, 30).max_fps),
1298            (1280, 60)
1299        );
1300        assert_eq!(at(640, 360, 30).width, 640);
1301        assert_eq!(
1302            at(1920, 1080, 60).width,
1303            1280,
1304            "nothing covers 1080p60: the largest at 60"
1305        );
1306        assert_eq!(at(4000, 3000, 30).width, 1920);
1307        assert_eq!(nearest_mode(&[], &CaptureConstraints::default()), None);
1308        assert!(CaptureConstraints::new(8, 8, 30).validate().is_err());
1309    }
1310
1311    #[test]
1312    fn a_thumbnail_carries_its_size() {
1313        let info = ScreenSourceInfo::new("d1", ScreenKind::Display, "Main", 2560, 1440);
1314        assert_eq!(info.thumbnail_size(), None);
1315        // 160x90 RGBA with rows padded to 768 bytes: the stride alone would
1316        // say 192 px wide.
1317        let planes = Planes::new(
1318            PixelFormat::Rgba,
1319            160,
1320            90,
1321            vec![0u8; 768 * 90],
1322            [768, 0, 0],
1323            [0, 0, 0],
1324        )
1325        .expect("padded planes");
1326        let info = info.with_thumbnail(planes, 160, 90).expect("thumbnail");
1327        assert_eq!(info.thumbnail_size(), Some((160, 90)));
1328        assert_eq!((info.thumbnail_width, info.thumbnail_height), (160, 90));
1329
1330        let base = ScreenSourceInfo::new("d1", ScreenKind::Display, "Main", 2560, 1440);
1331        let bgra = Planes::tight(PixelFormat::Bgra, 4, 4, vec![0u8; 64]).expect("bgra");
1332        assert!(base.clone().with_thumbnail(bgra, 4, 4).is_err());
1333        let wide = Planes::tight(PixelFormat::Rgba, 321, 1, vec![0u8; 321 * 4]).expect("wide");
1334        assert!(base.clone().with_thumbnail(wide, 321, 1).is_err());
1335        let small = Planes::tight(PixelFormat::Rgba, 4, 4, vec![0u8; 64]).expect("small");
1336        assert!(base.with_thumbnail(small, 8, 8).is_err());
1337    }
1338}