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 ///
83 /// Easy content can come in under it: rate control never goes below
84 /// quantizer index 4, its best quality, so a mostly flat or static
85 /// picture (a test pattern, an idle slide) uses fewer bits than a high
86 /// target allows. Camera content lands on the target.
87 pub bitrate_bps: u32,
88 /// Ceiling the encoder skips frames to stay under, in bits per second.
89 /// Raised to `bitrate_bps` if lower.
90 pub max_bitrate_bps: u32,
91 /// A keyframe every this many frames; `None`, only on request.
92 pub keyframe_interval: Option<u32>,
93 /// Temporal layering.
94 pub temporal_layers: TemporalLayers,
95}
96
97impl EncoderConfig {
98 /// Settings for `width` x `height` at `fps` and `bitrate_bps`, with a
99 /// 1.5x ceiling, keyframes on request only and no temporal layers.
100 pub fn new(width: u32, height: u32, fps: u32, bitrate_bps: u32) -> Self {
101 EncoderConfig {
102 width,
103 height,
104 fps,
105 bitrate_bps,
106 max_bitrate_bps: bitrate_bps.saturating_add(bitrate_bps / 2),
107 keyframe_interval: None,
108 temporal_layers: TemporalLayers::L1T1,
109 }
110 }
111
112 /// The same settings with temporal layering.
113 pub fn with_temporal_layers(mut self, layers: TemporalLayers) -> Self {
114 self.temporal_layers = layers;
115 self
116 }
117
118 /// The same settings with a keyframe interval.
119 pub fn with_keyframe_interval(mut self, frames: Option<u32>) -> Self {
120 self.keyframe_interval = frames;
121 self
122 }
123}
124
125/// One encoded frame.
126#[derive(Clone, Debug, PartialEq, Eq)]
127#[non_exhaustive]
128pub struct EncodedFrame {
129 /// One raw VP8 frame, starting at the frame tag.
130 pub data: Vec<u8>,
131 /// A keyframe.
132 pub keyframe: bool,
133 /// The temporal layer, 0 for the base.
134 pub temporal_id: u8,
135 /// RFC 7741's Y bit: the frame depends only on the base layer (or is a
136 /// keyframe).
137 pub layer_sync: bool,
138 /// The quantizer index used (0 to 127), for statistics.
139 pub q_index: u8,
140}
141
142/// Why a frame could not be encoded.
143#[derive(Clone, Debug, PartialEq, Eq)]
144#[non_exhaustive]
145pub enum EncodeError {
146 /// The configuration is unusable.
147 InvalidConfig(&'static str),
148 /// The picture's size differs from the configured size.
149 SizeMismatch {
150 /// The configured size.
151 expected: (u32, u32),
152 /// The picture's size.
153 got: (u32, u32),
154 },
155 /// The picture's planes are shorter than its size and strides need.
156 InvalidPicture,
157 /// A bug: the encoder's own output did not decode.
158 Internal(String),
159}
160
161impl fmt::Display for EncodeError {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 match self {
164 EncodeError::InvalidConfig(why) => write!(f, "invalid encoder config: {why}"),
165 EncodeError::SizeMismatch { expected, got } => {
166 write!(
167 f,
168 "picture is {}x{}, the encoder is {}x{}",
169 got.0, got.1, expected.0, expected.1
170 )
171 }
172 EncodeError::InvalidPicture => f.write_str("picture planes are too short for its size"),
173 EncodeError::Internal(why) => write!(f, "internal encoder error: {why}"),
174 }
175 }
176}
177
178impl std::error::Error for EncodeError {}
179
180/// A real-time VP8 encoder for one stream (one simulcast layer).
181pub struct Encoder {
182 core: encoder::Core,
183}
184
185impl Encoder {
186 /// An encoder; its first frame is a keyframe.
187 pub fn new(config: EncoderConfig) -> Result<Self, EncodeError> {
188 Ok(Encoder {
189 core: encoder::Core::new(config)?,
190 })
191 }
192
193 /// Encodes one picture, which must be the configured size. Returns
194 /// `None` when rate control skips the frame. `force_keyframe` (or an
195 /// earlier [`request_keyframe`](Self::request_keyframe)) makes this
196 /// frame a keyframe.
197 pub fn encode(
198 &mut self,
199 picture: &Picture<'_>,
200 force_keyframe: bool,
201 ) -> Result<Option<EncodedFrame>, EncodeError> {
202 self.core.encode(picture, force_keyframe)
203 }
204
205 /// The next encoded frame is a keyframe. Repeated calls coalesce.
206 pub fn request_keyframe(&mut self) {
207 self.core.request_keyframe();
208 }
209
210 /// Changes the target bitrate and frame rate, without a keyframe.
211 pub fn set_rates(&mut self, bitrate_bps: u32, fps: u32) {
212 self.core.set_rates(bitrate_bps, fps);
213 }
214
215 /// The current settings.
216 pub fn config(&self) -> &EncoderConfig {
217 &self.core.cfg
218 }
219}
220
221// The README's examples are compiled as doc tests.
222#[cfg(doctest)]
223#[doc = include_str!("../README.md")]
224struct ReadmeDoctests;