Skip to main content

videocall_cli/
video_encoder.rs

1/*
2 * Copyright 2025 Security Union LLC
3 *
4 * Licensed under either of
5 *
6 * * Apache License, Version 2.0
7 *   (http://www.apache.org/licenses/LICENSE-2.0)
8 * * MIT license
9 *   (http://opensource.org/licenses/MIT)
10 *
11 * at your option.
12 *
13 * Unless you explicitly state otherwise, any contribution intentionally
14 * submitted for inclusion in the work by you, as defined in the Apache-2.0
15 * license, shall be dual licensed as above, without any additional terms or
16 * conditions.
17 */
18
19//! VP9 video encoder adapter.
20//!
21//! This is a thin, backend-generic wrapper over a [`videocall_codecs`] encoder
22//! that implements the [`Encodable`] trait. The concrete backend is chosen at
23//! compile time:
24//!
25//! - Default build (no `libvpx` feature): the pure-Rust
26//!   [`videocall_codecs::vp9::Vp9Encoder`] — zero C dependencies.
27//! - `--features libvpx`: the C libvpx-backed encoder, opt-in for comparison.
28//!
29//! The public API (`VideoEncoderBuilder`, `VideoEncoder`, `Frame`, `Frames`) is
30//! identical across both backends, so downstream code (`encoder_thread`,
31//! `camera`) is unaffected by the choice.
32
33use anyhow::{anyhow, Result};
34use videocall_codecs::encoder::{Encodable, EncodedFrame, EncoderConfig};
35
36/// Maximum distance between keyframes, in frames (`kf_max_dist`/`kf_min_dist` = 150).
37const KEYFRAME_INTERVAL: u32 = 150;
38
39// Backend selection. The default (C-free) path uses the pure-Rust encoder; the
40// `libvpx` feature swaps in the C wrapper. Both are used through the
41// `Encodable` trait, so the rest of this file is backend-agnostic.
42#[cfg(feature = "libvpx")]
43use videocall_codecs::encoder::Vp9Encoder as Inner;
44#[cfg(not(feature = "libvpx"))]
45use videocall_codecs::vp9::Vp9Encoder as Inner;
46
47pub struct VideoEncoderBuilder {
48    pub min_quantizer: u32,
49    pub max_quantizer: u32,
50    pub bitrate_kbps: u32,
51    pub fps: u32,
52    pub resolution: (u32, u32),
53    pub cpu_used: u32,
54    pub profile: u32,
55}
56
57impl VideoEncoderBuilder {
58    pub fn new(fps: u32, cpu_used: u8) -> Self {
59        Self {
60            bitrate_kbps: 500,
61            max_quantizer: 60,
62            min_quantizer: 40,
63            resolution: (640, 480),
64            fps,
65            cpu_used: cpu_used as u32,
66            profile: 0,
67        }
68    }
69}
70
71impl VideoEncoderBuilder {
72    pub fn set_resolution(mut self, width: u32, height: u32) -> Self {
73        self.resolution = (width, height);
74        self
75    }
76
77    pub fn build(&self) -> Result<VideoEncoder> {
78        let (width, height) = self.resolution;
79        if width % 2 != 0 || width == 0 {
80            return Err(anyhow!("Width must be divisible by 2"));
81        }
82        if height % 2 != 0 || height == 0 {
83            return Err(anyhow!("Height must be divisible by 2"));
84        }
85        // The encoder backends only implement VP9 profile 0 (8-bit 4:2:0).
86        // `EncoderConfig` has no profile field, so a non-zero `profile` here
87        // would be silently dropped and produce profile-0 output. Reject it
88        // loudly instead of misleading the caller.
89        if self.profile != 0 {
90            return Err(anyhow!(
91                "Unsupported VP9 profile {}: only profile 0 (8-bit 4:2:0) is supported",
92                self.profile
93            ));
94        }
95
96        let config = EncoderConfig {
97            width,
98            height,
99            framerate: self.fps,
100            bitrate_kbps: self.bitrate_kbps,
101            keyframe_interval: KEYFRAME_INTERVAL,
102            min_quantizer: self.min_quantizer,
103            max_quantizer: self.max_quantizer,
104            cpu_used: self.cpu_used as u8,
105        };
106
107        // Fully-qualified so we always hit the `Encodable` trait method: the
108        // libvpx backend also has an inherent `new`/`encode` with a
109        // different signature that would otherwise shadow the trait.
110        let inner = <Inner as Encodable>::new(config)?;
111        Ok(VideoEncoder {
112            inner,
113            pending: None,
114        })
115    }
116}
117
118pub struct VideoEncoder {
119    inner: Inner,
120    /// Owns the most recently encoded frame so [`Frames`] can borrow it. Some
121    /// backends buffer (libvpx `lag_in_frames`), so this may be `None` for a
122    /// call that produced no output yet.
123    pending: Option<EncodedFrame>,
124}
125
126impl VideoEncoder {
127    pub fn update_bitrate_kbps(&mut self, bitrate: u32) -> anyhow::Result<()> {
128        Encodable::update_bitrate_kbps(&mut self.inner, bitrate)
129    }
130
131    pub fn encode(&mut self, pts: i64, data: &[u8]) -> anyhow::Result<Frames<'_>> {
132        self.pending = Encodable::encode(&mut self.inner, pts, data)?;
133        Ok(Frames {
134            frame: self.pending.as_ref().map(|f| Frame {
135                data: &f.data,
136                key: f.is_keyframe,
137                pts: f.pts,
138            }),
139        })
140    }
141}
142
143#[derive(Clone, Copy, Debug)]
144pub struct Frame<'a> {
145    /// Compressed data.
146    pub data: &'a [u8],
147    /// Whether the frame is a keyframe.
148    pub key: bool,
149    /// Presentation timestamp (in timebase units).
150    pub pts: i64,
151}
152
153/// Iterator over the frames produced by a single [`VideoEncoder::encode`] call.
154///
155/// The backend emits at most one compressed frame per input frame, so this
156/// yields either zero or one [`Frame`]. Downstream code already tolerates a
157/// zero-frame result (the libvpx backend buffers with `lag_in_frames = 1`).
158pub struct Frames<'a> {
159    frame: Option<Frame<'a>>,
160}
161
162impl<'a> Iterator for Frames<'a> {
163    type Item = Frame<'a>;
164    fn next(&mut self) -> Option<Self::Item> {
165        self.frame.take()
166    }
167}