Skip to main content

vp8_encoder/
lib.rs

1//! A real-time VP8 video encoder in pure, safe Rust.
2//!
3//! It turns I420 pictures into raw VP8 frames (RFC 6386) for live video:
4//! camera and screen sharing over WebRTC. No look-ahead and no reordering:
5//! one frame in, at most one frame out.
6//!
7//! - Rate control to a target bitrate, changeable at any time with
8//!   [`Encoder::set_rates`]; frames are skipped when the stream runs far
9//!   over budget.
10//! - Keyframes on request ([`Encoder::request_keyframe`] or the
11//!   `force_keyframe` flag), for PLI and FIR.
12//! - Optional temporal layers (L1T2, L1T3) in the usual WebRTC pattern.
13//! - Simulcast: run one encoder per layer, each at its own size;
14//!   [`scale_i420`] makes the smaller pictures.
15//!
16//! Every frame's probability updates apply to that frame only, so a lost or
17//! dropped frame never leaves a receiver with the wrong probabilities.
18//!
19//! ```no_run
20//! use vp8_encoder::{Encoder, EncoderConfig, Picture};
21//! let mut enc = Encoder::new(EncoderConfig::new(1280, 720, 30, 2_000_000)).unwrap();
22//! let i420 = vec![128u8; 1280 * 720 * 3 / 2];
23//! let picture = Picture::from_i420(&i420, 1280, 720).unwrap();
24//! if let Some(frame) = enc.encode(&picture, false).unwrap() {
25//!     // frame.data is one raw VP8 frame, ready for an RTP packetiser.
26//!     let _ = (frame.keyframe, frame.temporal_id, frame.layer_sync);
27//! }
28//! ```
29//!
30//! See PROVENANCE.md for how this crate was written.
31
32#![forbid(unsafe_code)]
33
34mod encoder;
35mod rate;
36mod scale;
37mod tokens;
38mod transform;
39
40use std::fmt;
41
42pub use scale::scale_i420;
43pub use vp8_decoder::Picture;
44
45/// Temporal layering.
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
47#[non_exhaustive]
48pub enum TemporalLayers {
49    /// One layer: every frame predicts from the previous one.
50    #[default]
51    L1T1,
52    /// Two layers: 0, 1, 0, 1... Layer 1 frames are never referenced, so a
53    /// receiver can drop them for half the frame rate.
54    L1T2,
55    /// Three layers: 0, 2, 1, 2... Drop layer 2 for half the frame rate, and
56    /// layers 1 and 2 for a quarter.
57    L1T3,
58}
59
60impl TemporalLayers {
61    /// How many layers.
62    pub fn count(self) -> u8 {
63        match self {
64            TemporalLayers::L1T1 => 1,
65            TemporalLayers::L1T2 => 2,
66            TemporalLayers::L1T3 => 3,
67        }
68    }
69}
70
71/// Encoder settings.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73#[non_exhaustive]
74pub struct EncoderConfig {
75    /// Coded width in pixels (1 to 16383).
76    pub width: u32,
77    /// Coded height in pixels (1 to 16383).
78    pub height: u32,
79    /// The frame rate the input arrives at (for rate control).
80    pub fps: u32,
81    /// Target bitrate in bits per second.
82    pub bitrate_bps: u32,
83    /// Ceiling the encoder skips frames to stay under, in bits per second.
84    /// Raised to `bitrate_bps` if lower.
85    pub max_bitrate_bps: u32,
86    /// A keyframe every this many frames; `None`, only on request.
87    pub keyframe_interval: Option<u32>,
88    /// Temporal layering.
89    pub temporal_layers: TemporalLayers,
90}
91
92impl EncoderConfig {
93    /// Settings for `width` x `height` at `fps` and `bitrate_bps`, with a
94    /// 1.5x ceiling, keyframes on request only and no temporal layers.
95    pub fn new(width: u32, height: u32, fps: u32, bitrate_bps: u32) -> Self {
96        EncoderConfig {
97            width,
98            height,
99            fps,
100            bitrate_bps,
101            max_bitrate_bps: bitrate_bps.saturating_add(bitrate_bps / 2),
102            keyframe_interval: None,
103            temporal_layers: TemporalLayers::L1T1,
104        }
105    }
106
107    /// The same settings with temporal layering.
108    pub fn with_temporal_layers(mut self, layers: TemporalLayers) -> Self {
109        self.temporal_layers = layers;
110        self
111    }
112
113    /// The same settings with a keyframe interval.
114    pub fn with_keyframe_interval(mut self, frames: Option<u32>) -> Self {
115        self.keyframe_interval = frames;
116        self
117    }
118}
119
120/// One encoded frame.
121#[derive(Clone, Debug, PartialEq, Eq)]
122#[non_exhaustive]
123pub struct EncodedFrame {
124    /// One raw VP8 frame, starting at the frame tag.
125    pub data: Vec<u8>,
126    /// A keyframe.
127    pub keyframe: bool,
128    /// The temporal layer, 0 for the base.
129    pub temporal_id: u8,
130    /// RFC 7741's Y bit: the frame depends only on the base layer (or is a
131    /// keyframe).
132    pub layer_sync: bool,
133    /// The quantizer index used (0 to 127), for statistics.
134    pub q_index: u8,
135}
136
137/// Why a frame could not be encoded.
138#[derive(Clone, Debug, PartialEq, Eq)]
139#[non_exhaustive]
140pub enum EncodeError {
141    /// The configuration is unusable.
142    InvalidConfig(&'static str),
143    /// The picture's size differs from the configured size.
144    SizeMismatch {
145        /// The configured size.
146        expected: (u32, u32),
147        /// The picture's size.
148        got: (u32, u32),
149    },
150    /// The picture's planes are shorter than its size and strides need.
151    InvalidPicture,
152    /// A bug: the encoder's own output did not decode.
153    Internal(String),
154}
155
156impl fmt::Display for EncodeError {
157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158        match self {
159            EncodeError::InvalidConfig(why) => write!(f, "invalid encoder config: {why}"),
160            EncodeError::SizeMismatch { expected, got } => {
161                write!(f, "picture is {}x{}, the encoder is {}x{}", got.0, got.1, expected.0, expected.1)
162            }
163            EncodeError::InvalidPicture => f.write_str("picture planes are too short for its size"),
164            EncodeError::Internal(why) => write!(f, "internal encoder error: {why}"),
165        }
166    }
167}
168
169impl std::error::Error for EncodeError {}
170
171/// A real-time VP8 encoder for one stream (one simulcast layer).
172pub struct Encoder {
173    core: encoder::Core,
174}
175
176impl Encoder {
177    /// An encoder; its first frame is a keyframe.
178    pub fn new(config: EncoderConfig) -> Result<Self, EncodeError> {
179        Ok(Encoder {
180            core: encoder::Core::new(config)?,
181        })
182    }
183
184    /// Encodes one picture, which must be the configured size. Returns
185    /// `None` when rate control skips the frame. `force_keyframe` (or an
186    /// earlier [`request_keyframe`](Self::request_keyframe)) makes this
187    /// frame a keyframe.
188    pub fn encode(&mut self, picture: &Picture<'_>, force_keyframe: bool) -> Result<Option<EncodedFrame>, EncodeError> {
189        self.core.encode(picture, force_keyframe)
190    }
191
192    /// The next encoded frame is a keyframe. Repeated calls coalesce.
193    pub fn request_keyframe(&mut self) {
194        self.core.request_keyframe();
195    }
196
197    /// Changes the target bitrate and frame rate, without a keyframe.
198    pub fn set_rates(&mut self, bitrate_bps: u32, fps: u32) {
199        self.core.set_rates(bitrate_bps, fps);
200    }
201
202    /// The current settings.
203    pub fn config(&self) -> &EncoderConfig {
204        &self.core.cfg
205    }
206}
207
208// The README's examples are compiled as doc tests.
209#[cfg(doctest)]
210#[doc = include_str!("../README.md")]
211struct ReadmeDoctests;