M7/M8 (part 1): tsc-media frames, conversion and video codecs

New crate tsc-media:
- VideoFrame (I420, NV12, BGRA, RGBA with strides) and AudioBuffer
  (interleaved f32, 48 kHz)
- YUV <-> RGB conversion with yuvutils-rs (BT.601 limited range), RGBA
  output for Slint pixel buffers, PSNR helper
- Bounded drop-oldest frame channel with async and blocking receive
- VideoEncoder / VideoDecoder traits, Codec (VP8, VP9, H.264, AV1) with an
  optional str0m mapping, codec preference (viewer VP9 > VP8 > AV1 > H.264,
  streamer hardware > VP8 > OpenH264 > VP9) and backend selection
- libvpx VP8/VP9 encoder and decoder over libvpx-native-sys (small unsafe
  wrapper: realtime CBR, cpu-used 8, error resilient, screen content,
  runtime bitrate changes)
- H.264 through Cisco's OpenH264 loaded at runtime (hash-checked), with an
  HTTPS + SHA-256 download helper
- AV1 decoding through dav1d (feature av1)
- Hardware encoder factory trait with VA-API / Media Foundation stubs

deny.toml: allow the bzip2-1.0.6 license (pure Rust bzip2 used to unpack
the OpenH264 download).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-25 19:53:13 +00:00
1 parent 0b1aa5664e
commit 3ec9d6611c
14 files changed
+2923 -1

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
//! AV1 decoding through the system libdav1d (`dav1d` crate).
use std::time::Duration;
use dav1d::{PixelLayout, PlanarImageComponent, Settings};
use crate::codec::{Codec, VideoDecoder};
use crate::frame::{FrameData, Plane, VideoFrame};
use crate::{Error, Result};
fn error(e: impl std::fmt::Display) -> Error {
Error::Decoder { codec: Codec::Av1, message: e.to_string() }
}
/// dav1d decoder tuned for low latency (one frame of delay).
pub struct Dav1dDecoder {
decoder: dav1d::Decoder,
}
impl Dav1dDecoder {
pub fn new() -> Result<Self> {
let mut settings = Settings::new();
settings.set_max_frame_delay(1);
settings.set_n_threads(
std::thread::available_parallelism().map_or(1, |n| n.get().min(4) as u32),
);
let decoder = dav1d::Decoder::with_settings(&settings).map_err(|e| {
Error::CodecUnavailable { codec: Codec::Av1, reason: format!("dav1d: {e}") }
})?;
Ok(Self { decoder })
}
fn drain(&mut self, last: &mut Option<dav1d::Picture>) -> Result<()> {
loop {
match self.decoder.get_picture() {
Ok(p) => *last = Some(p),
Err(e) if e.is_again() => return Ok(()),
Err(e) => return Err(error(e)),
}
}
}
}
impl VideoDecoder for Dav1dDecoder {
fn codec(&self) -> Codec {
Codec::Av1
}
fn decode(&mut self, data: &[u8]) -> Result<Option<VideoFrame>> {
if data.is_empty() {
return Ok(None);
}
let mut last = None;
// `Again` from send: pictures must be taken out before the rest of the
// data is accepted.
let mut result = self.decoder.send_data(data.to_vec(), None, None, None);
loop {
match result {
Ok(()) => break,
Err(e) if e.is_again() => {
self.drain(&mut last)?;
result = self.decoder.send_pending_data();
}
Err(e) => return Err(error(e)),
}
}
self.drain(&mut last)?;
last.map(|p| to_frame(&p)).transpose()
}
}
fn to_frame(picture: &dav1d::Picture) -> Result<VideoFrame> {
if picture.bit_depth() != 8 || picture.pixel_layout() != PixelLayout::I420 {
return Err(error(format!(
"unsupported picture format {:?} {} bit",
picture.pixel_layout(),
picture.bit_depth()
)));
}
let (w, h) = (picture.width() as usize, picture.height() as usize);
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
let copy = |component: PlanarImageComponent, width: usize, rows: usize| {
let stride = picture.stride(component) as usize;
let plane = picture.plane(component);
let mut out = Vec::with_capacity(width * rows);
for row in 0..rows {
out.extend_from_slice(&plane[row * stride..row * stride + width]);
}
Plane::new(out, width)
};
Ok(VideoFrame {
width: w as u32,
height: h as u32,
timestamp: Duration::ZERO,
data: FrameData::I420 {
y: copy(PlanarImageComponent::Y, w, h),
u: copy(PlanarImageComponent::U, cw, ch),
v: copy(PlanarImageComponent::V, cw, ch),
},
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decoder_constructs_and_rejects_garbage() {
let mut decoder = Dav1dDecoder::new().unwrap();
assert_eq!(decoder.codec(), Codec::Av1);
assert!(decoder.decode(&[]).unwrap().is_none());
// Not an OBU stream: an error or no picture, never a panic.
if let Ok(p) = decoder.decode(&[0xff; 32]) {
assert!(p.is_none());
}
}
}
+408
View File
@@ -0,0 +1,408 @@
//! H.264 through Cisco's prebuilt OpenH264 library, loaded at runtime.
//!
//! Cisco pays the MPEG LA H.264 royalties only for its own binaries, and only
//! if each user downloads the binary themselves (not shipped with the app).
//! So the library is never compiled in: [`download_openh264`] fetches the
//! official build on the user's machine (feature `openh264-download`), and
//! [`OpenH264::load`] only accepts files whose SHA-256 matches a known Cisco
//! release. Apps using it must show [`OPENH264_ATTRIBUTION`] and let the user
//! disable it (see docs/media.md).
//!
//! TeamSpeak clients only decode H.264 Constrained High; OpenH264 encodes
//! without B-frames, so its High profile output qualifies.
use std::path::{Path, PathBuf};
use openh264::OpenH264API;
use openh264::decoder::{Decoder, DecoderConfig};
use openh264::encoder::{
BitRate, Encoder, FrameRate, FrameType, IntraFramePeriod, Profile, RateControlMode, UsageType,
};
use openh264::formats::{YUVSlices, YUVSource};
use crate::codec::{
Codec, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder,
};
use crate::convert;
use crate::frame::{FrameData, Plane, VideoFrame};
use crate::{Error, Result};
/// The notice Cisco's binary license requires in the app (e.g. the About
/// page).
pub const OPENH264_ATTRIBUTION: &str = "OpenH264 Video Codec provided by Cisco Systems, Inc.";
/// The OpenH264 release we download and accept.
pub const OPENH264_VERSION: &str = "2.6.0";
/// Where Cisco publishes its binaries (bzip2 compressed, `<file>.bz2`).
pub const OPENH264_BASE_URL: &str = "https://ciscobinary.openh264.org/";
/// Cisco's OpenH264 2.6.0 builds: file name and SHA-256 of the decompressed
/// library (the list `openh264-sys2` also checks before loading).
#[cfg_attr(not(feature = "openh264-download"), allow(dead_code))]
const KNOWN_BUILDS: &[(&str, &str)] = &[
(
"libopenh264-2.6.0-linux64.8.so",
"2f0cde7c6a6abcf5cae76942894ea42897fa677bce4ed6c91a24dd1b041d5f04",
),
(
"libopenh264-2.6.0-linux32.8.so",
"a46589ccc95df7565ff8b1722d3dead29c0809be28322dc763767e0aa35a6443",
),
(
"libopenh264-2.6.0-linux-arm64.8.so",
"12e7b33623667cdab0e575170c147b1b36eadb77d0d2aa7ceb5afd3e58902140",
),
(
"libopenh264-2.6.0-linux-arm.8.so",
"df91866de0e93773019e30a8f2bdee8b15de4abe2bf89a228ae9f064ff1e85bb",
),
(
"libopenh264-2.6.0-android-arm64.8.so",
"4d9bc54d2d38e53eb7bd551ec61acb8ad8320d8b957bda751cfdbdcbfabc3b07",
),
(
"libopenh264-2.6.0-android-arm.8.so",
"45d8d77c119a488cad42549987a4a1ac50f634cfd6b08454c5565652e482022c",
),
(
"libopenh264-2.6.0-android-x64.8.so",
"548fa57935ff0eaf0a1d44c7963c1681daa5bf4cef2b34029fcd20a1e71adf81",
),
(
"openh264-2.6.0-win64.dll",
"2076cb5675ec6c1a4c70e7a2a322552f547b6eeed649d6dfcd9e02a543b24691",
),
(
"openh264-2.6.0-win32.dll",
"b0098db6acbd290a1fe13997d61d461e7327e39b42bf868db41faf498b7621a2",
),
(
"openh264-2.6.0-win-arm64.dll",
"fb75103938f4f47d119b983e06334df41a803bc72fb5c46e3623f6fea5782732",
),
(
"libopenh264-2.6.0-mac-arm64.dylib",
"052e98bfcf7a9167d22f3bbb3f5988ef79065591f36af8b52924b22b13624551",
),
(
"libopenh264-2.6.0-mac-x64.dylib",
"e3dc8bc01fe69363f61fd3c02fd27798537a585eadd38cd808f303d1ee505a19",
),
];
/// Cisco's file name for this platform, if Cisco builds one.
pub fn platform_library_name() -> Option<&'static str> {
let name = match (std::env::consts::OS, std::env::consts::ARCH) {
("linux", "x86_64") => "libopenh264-2.6.0-linux64.8.so",
("linux", "x86") => "libopenh264-2.6.0-linux32.8.so",
("linux", "aarch64") => "libopenh264-2.6.0-linux-arm64.8.so",
("linux", "arm") => "libopenh264-2.6.0-linux-arm.8.so",
("android", "aarch64") => "libopenh264-2.6.0-android-arm64.8.so",
("android", "arm") => "libopenh264-2.6.0-android-arm.8.so",
("android", "x86_64") => "libopenh264-2.6.0-android-x64.8.so",
("windows", "x86_64") => "openh264-2.6.0-win64.dll",
("windows", "x86") => "openh264-2.6.0-win32.dll",
("windows", "aarch64") => "openh264-2.6.0-win-arm64.dll",
("macos", "aarch64") => "libopenh264-2.6.0-mac-arm64.dylib",
("macos", "x86_64") => "libopenh264-2.6.0-mac-x64.dylib",
_ => return None,
};
Some(name)
}
#[cfg_attr(not(feature = "openh264-download"), allow(dead_code))]
fn expected_sha256(file_name: &str) -> Option<&'static str> {
KNOWN_BUILDS.iter().find(|(name, _)| *name == file_name).map(|(_, sha)| *sha)
}
fn unavailable(reason: impl Into<String>) -> Error {
Error::CodecUnavailable { codec: Codec::H264, reason: reason.into() }
}
/// A verified OpenH264 library on disk. Cheap to clone; each encoder and
/// decoder loads it (the OS shares the mapping).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OpenH264 {
path: PathBuf,
}
impl OpenH264 {
/// Use the library at `path`. Fails if it is missing, is not a known
/// Cisco build, or cannot be loaded.
pub fn load(path: impl Into<PathBuf>) -> Result<Self> {
let path = path.into();
if !path.is_file() {
return Err(unavailable(format!("OpenH264 library not found at {}", path.display())));
}
let library = Self { path };
// Load once to verify the hash and the symbols.
library.api()?;
Ok(library)
}
/// Look for this platform's library in `dir` (where
/// [`download_openh264`] puts it).
pub fn find_in(dir: &Path) -> Result<Self> {
let name = platform_library_name()
.ok_or_else(|| unavailable("Cisco provides no OpenH264 build for this platform"))?;
Self::load(dir.join(name))
}
pub fn path(&self) -> &Path {
&self.path
}
fn api(&self) -> Result<OpenH264API> {
// `from_blob_path` checks the SHA-256 against the known Cisco builds
// before loading, so arbitrary files are never executed.
OpenH264API::from_blob_path(&self.path).map_err(|e| {
unavailable(format!("cannot load OpenH264 from {}: {e}", self.path.display()))
})
}
pub fn encoder(&self, config: EncoderConfig) -> Result<OpenH264Encoder> {
OpenH264Encoder::new(self.clone(), config)
}
pub fn decoder(&self) -> Result<OpenH264Decoder> {
let decoder = Decoder::with_api_config(self.api()?, DecoderConfig::new())
.map_err(|e| Error::Decoder { codec: Codec::H264, message: e.to_string() })?;
Ok(OpenH264Decoder { decoder })
}
}
/// H.264 profile of the encoder output.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum H264Profile {
/// Constrained High (what TeamSpeak clients decode).
#[default]
ConstrainedHigh,
ConstrainedBaseline,
}
/// OpenH264 encoder.
pub struct OpenH264Encoder {
library: OpenH264,
config: EncoderConfig,
profile: H264Profile,
encoder: Option<Encoder>,
}
impl OpenH264Encoder {
fn new(library: OpenH264, config: EncoderConfig) -> Result<Self> {
let mut encoder = Self { library, config, profile: H264Profile::default(), encoder: None };
encoder.encoder = Some(encoder.create()?);
Ok(encoder)
}
pub fn set_profile(&mut self, profile: H264Profile) -> Result<()> {
self.profile = profile;
self.encoder = Some(self.create()?);
Ok(())
}
fn create(&self) -> Result<Encoder> {
let usage = match self.config.content {
ContentHint::Screen => UsageType::ScreenContentRealTime,
ContentHint::Motion => UsageType::CameraVideoRealTime,
};
let profile = match self.profile {
H264Profile::ConstrainedHigh => Profile::High,
H264Profile::ConstrainedBaseline => Profile::Baseline,
};
let config = openh264::encoder::EncoderConfig::new()
.bitrate(BitRate::from_bps(self.config.bitrate_bps))
.max_frame_rate(FrameRate::from_hz(self.config.fps as f32))
.rate_control_mode(RateControlMode::Bitrate)
.usage_type(usage)
.profile(profile)
.skip_frames(false)
.intra_frame_period(IntraFramePeriod::from_num_frames(
self.config.keyframe_interval.unwrap_or(0),
))
.num_threads(self.config.threads.min(u32::from(u16::MAX)) as u16);
Encoder::with_api_config(self.library.api()?, config).map_err(|e| self.error(e))
}
fn error(&self, e: openh264::Error) -> Error {
Error::Encoder { codec: Codec::H264, message: e.to_string() }
}
}
impl VideoEncoder for OpenH264Encoder {
fn codec(&self) -> Codec {
Codec::H264
}
fn backend(&self) -> EncoderBackend {
EncoderBackend::OpenH264
}
fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result<Vec<EncodedFrame>> {
let i420 = convert::to_i420(frame)?;
let FrameData::I420 { y, u, v } = &i420.data else {
unreachable!("to_i420 returns I420");
};
let source = YUVSlices::new(
(&y.data, &u.data, &v.data),
(i420.width as usize, i420.height as usize),
(y.stride, u.stride, v.stride),
);
let encoder = self.encoder.as_mut().expect("created in new");
if force_keyframe {
encoder.force_intra_frame();
}
let timestamp = openh264::Timestamp::from_millis(i420.timestamp.as_millis() as u64);
let bitstream = match encoder.encode_at(&source, timestamp) {
Ok(b) => b,
Err(e) => return Err(Error::Encoder { codec: Codec::H264, message: e.to_string() }),
};
let keyframe = matches!(bitstream.frame_type(), FrameType::IDR | FrameType::I);
let data = bitstream.to_vec();
if data.is_empty() || matches!(bitstream.frame_type(), FrameType::Skip) {
return Ok(Vec::new());
}
Ok(vec![EncodedFrame { data, keyframe, pts_90khz: i420.pts_90khz() }])
}
/// The `openh264` crate has no safe way to change the bitrate of a
/// running encoder, so this recreates it (the next frame is an IDR).
fn set_bitrate(&mut self, bps: u32) -> Result<()> {
if bps == self.config.bitrate_bps {
return Ok(());
}
self.config.bitrate_bps = bps;
self.encoder = Some(self.create()?);
Ok(())
}
}
/// OpenH264 decoder (Annex B input, as depacketized by str0m).
pub struct OpenH264Decoder {
decoder: Decoder,
}
impl VideoDecoder for OpenH264Decoder {
fn codec(&self) -> Codec {
Codec::H264
}
fn decode(&mut self, data: &[u8]) -> Result<Option<VideoFrame>> {
let picture = self
.decoder
.decode(data)
.map_err(|e| Error::Decoder { codec: Codec::H264, message: e.to_string() })?;
let Some(picture) = picture else { return Ok(None) };
let (w, h) = picture.dimensions();
let (sy, su, sv) = picture.strides();
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
let copy = |data: &[u8], stride: usize, width: usize, rows: usize| {
let mut out = Vec::with_capacity(width * rows);
for row in 0..rows {
out.extend_from_slice(&data[row * stride..row * stride + width]);
}
Plane::new(out, width)
};
Ok(Some(VideoFrame {
width: w as u32,
height: h as u32,
timestamp: std::time::Duration::ZERO,
data: FrameData::I420 {
y: copy(picture.y(), sy, w, h),
u: copy(picture.u(), su, cw, ch),
v: copy(picture.v(), sv, cw, ch),
},
}))
}
}
/// Download Cisco's OpenH264 build for this platform into `dir` (created if
/// needed) over HTTPS, check its SHA-256, and load it. Reuses a verified
/// file that is already there.
///
/// Call this only after the user agreed (e.g. a settings switch that shows
/// [`OPENH264_ATTRIBUTION`]); Cisco's license requires the download to happen
/// on the user's machine.
#[cfg(feature = "openh264-download")]
pub async fn download_openh264(dir: &Path) -> Result<OpenH264> {
download_from(OPENH264_BASE_URL, dir).await
}
/// [`download_openh264`] from another base URL (a mirror, or a local server
/// in tests). The SHA-256 check is the same.
#[cfg(feature = "openh264-download")]
pub async fn download_from(base_url: &str, dir: &Path) -> Result<OpenH264> {
use std::io::Read;
use sha2::Digest;
let name = platform_library_name()
.ok_or_else(|| unavailable("Cisco provides no OpenH264 build for this platform"))?;
let expected = expected_sha256(name).expect("every platform name has a hash");
let target = dir.join(name);
if target.is_file() {
match OpenH264::load(&target) {
Ok(library) => return Ok(library),
Err(e) => tracing::info!("replacing {}: {e}", target.display()),
}
}
let url = format!("{}/{name}.bz2", base_url.trim_end_matches('/'));
let download = |e: &dyn std::fmt::Display| Error::Download(format!("{url}: {e}"));
let response = reqwest::get(&url).await.map_err(|e| download(&e))?;
let response = response.error_for_status().map_err(|e| download(&e))?;
let compressed = response.bytes().await.map_err(|e| download(&e))?;
// The libraries are about 1-2 MB; refuse anything absurd.
let mut library = Vec::new();
bzip2::read::BzDecoder::new(&compressed[..])
.take(64 << 20)
.read_to_end(&mut library)
.map_err(|e| download(&format!("bad bzip2 data: {e}")))?;
let actual: String =
sha2::Sha256::digest(&library).iter().map(|b| format!("{b:02x}")).collect();
if actual != expected {
return Err(download(&format!("SHA-256 mismatch: got {actual}, expected {expected}")));
}
std::fs::create_dir_all(dir)?;
let partial = dir.join(format!("{name}.part"));
std::fs::write(&partial, &library)?;
std::fs::rename(&partial, &target)?;
OpenH264::load(target)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_library_is_unavailable() {
let err = OpenH264::load("/nonexistent/libopenh264.so").unwrap_err();
assert!(matches!(err, Error::CodecUnavailable { codec: Codec::H264, .. }), "{err}");
assert!(err.to_string().contains("not found"), "{err}");
let dir = std::env::temp_dir().join(format!("tsc-media-h264-{}", std::process::id()));
assert!(OpenH264::find_in(&dir).is_err());
}
#[test]
fn unknown_file_is_rejected() {
let dir = std::env::temp_dir().join(format!("tsc-media-h264-bad-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let fake = dir.join(platform_library_name().unwrap_or("libopenh264.so"));
std::fs::write(&fake, b"not a library").unwrap();
let err = OpenH264::load(&fake).unwrap_err();
std::fs::remove_dir_all(&dir).unwrap();
assert!(matches!(err, Error::CodecUnavailable { .. }), "{err}");
assert!(err.to_string().to_lowercase().contains("hash"), "{err}");
}
#[test]
fn platform_names_have_hashes() {
if let Some(name) = platform_library_name() {
assert!(expected_sha256(name).is_some());
}
assert!(KNOWN_BUILDS.iter().all(|(_, sha)| sha.len() == 64));
}
}
+99
View File
@@ -0,0 +1,99 @@
//! Hardware video encoders.
//!
//! The streamer prefers a GPU encoder over software VP8 / OpenH264. None is
//! implemented yet; the factories below mark where they plug in:
//!
//! - Linux: VA-API (H.264 Constrained High / VP8 / VP9 on Intel and AMD), e.g.
//! through `cros-libva`. TODO.
//! - Windows: Media Foundation H.264 encoder MFT (NVENC / QuickSync / AMF
//! behind it). TODO.
use crate::Result;
use crate::codec::{Codec, EncoderConfig, VideoEncoder};
/// Creates encoders of one hardware API.
pub trait HardwareEncoderFactory: Send + Sync {
/// Short name for logs and settings (`"vaapi"`, `"mediafoundation"`).
fn name(&self) -> &'static str;
/// Codecs this device can encode, best first.
fn codecs(&self) -> Vec<Codec>;
fn create(&self, codec: Codec, config: &EncoderConfig) -> Result<Box<dyn VideoEncoder>>;
}
/// Hardware encoders usable on this machine (none yet).
pub fn probe() -> Vec<Box<dyn HardwareEncoderFactory>> {
let mut found: Vec<Box<dyn HardwareEncoderFactory>> = Vec::new();
#[cfg(target_os = "linux")]
if let Some(f) = vaapi::probe() {
found.push(Box::new(f));
}
#[cfg(windows)]
if let Some(f) = media_foundation::probe() {
found.push(Box::new(f));
}
found
}
#[cfg(target_os = "linux")]
mod vaapi {
use super::*;
use crate::Error;
pub struct Vaapi;
/// TODO: open the DRM render node, query VAProfileH264ConstrainedBaseline /
/// VAProfileH264High / VP8 / VP9 encode entrypoints.
pub fn probe() -> Option<Vaapi> {
None
}
impl HardwareEncoderFactory for Vaapi {
fn name(&self) -> &'static str {
"vaapi"
}
fn codecs(&self) -> Vec<Codec> {
Vec::new()
}
fn create(&self, codec: Codec, _: &EncoderConfig) -> Result<Box<dyn VideoEncoder>> {
Err(Error::CodecUnavailable {
codec,
reason: "VA-API encoding is not implemented".into(),
})
}
}
}
#[cfg(windows)]
mod media_foundation {
use super::*;
use crate::Error;
pub struct MediaFoundation;
/// TODO: enumerate hardware H.264 encoder MFTs (`MFTEnumEx` with
/// `MFT_ENUM_FLAG_HARDWARE`).
pub fn probe() -> Option<MediaFoundation> {
None
}
impl HardwareEncoderFactory for MediaFoundation {
fn name(&self) -> &'static str {
"mediafoundation"
}
fn codecs(&self) -> Vec<Codec> {
Vec::new()
}
fn create(&self, codec: Codec, _: &EncoderConfig) -> Result<Box<dyn VideoEncoder>> {
Err(Error::CodecUnavailable {
codec,
reason: "Media Foundation encoding is not implemented".into(),
})
}
}
}
+453
View File
@@ -0,0 +1,453 @@
//! Video codecs: common types, the encoder/decoder traits, codec preference
//! and backend selection.
//!
//! Backends:
//! - [`vpx`] (feature `vpx`): VP8 and VP9 encoding and decoding with the
//! system libvpx
//! - [`h264`] (feature `openh264`): H.264 with Cisco's prebuilt OpenH264,
//! loaded at runtime
//! - [`av1`] (feature `av1`): AV1 decoding with the system libdav1d
//! - [`hw`]: hardware encoders (VA-API, Media Foundation); not implemented yet
use std::fmt;
use std::str::FromStr;
use crate::frame::VideoFrame;
use crate::{Error, Result};
#[cfg(feature = "av1")]
pub mod av1;
#[cfg(feature = "openh264")]
pub mod h264;
pub mod hw;
#[cfg(feature = "vpx")]
pub mod vpx;
/// Video codecs TeamSpeak 6 streams use.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Codec {
Vp8,
Vp9,
H264,
Av1,
}
impl Codec {
pub const ALL: [Codec; 4] = [Codec::Vp8, Codec::Vp9, Codec::H264, Codec::Av1];
/// Name as in SDP (`a=rtpmap:<pt> <name>/90000`).
pub fn name(self) -> &'static str {
match self {
Codec::Vp8 => "VP8",
Codec::Vp9 => "VP9",
Codec::H264 => "H264",
Codec::Av1 => "AV1",
}
}
}
impl fmt::Display for Codec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl FromStr for Codec {
type Err = Error;
/// Accepts SDP names and MIME types (`vp8`, `H264`, `video/AV1`, `h.264`).
fn from_str(s: &str) -> Result<Self> {
let name = s.trim();
let name = name.strip_prefix("video/").unwrap_or(name);
match name.to_ascii_lowercase().as_str() {
"vp8" => Ok(Codec::Vp8),
"vp9" => Ok(Codec::Vp9),
"h264" | "h.264" | "avc" => Ok(Codec::H264),
"av1" | "av1x" => Ok(Codec::Av1),
_ => Err(Error::Convert(format!("unknown codec {s:?}"))),
}
}
}
#[cfg(feature = "str0m")]
impl From<Codec> for str0m::format::Codec {
fn from(c: Codec) -> Self {
match c {
Codec::Vp8 => str0m::format::Codec::Vp8,
Codec::Vp9 => str0m::format::Codec::Vp9,
Codec::H264 => str0m::format::Codec::H264,
Codec::Av1 => str0m::format::Codec::Av1,
}
}
}
#[cfg(feature = "str0m")]
impl TryFrom<str0m::format::Codec> for Codec {
type Error = Error;
fn try_from(c: str0m::format::Codec) -> Result<Self> {
match c {
str0m::format::Codec::Vp8 => Ok(Codec::Vp8),
str0m::format::Codec::Vp9 => Ok(Codec::Vp9),
str0m::format::Codec::H264 => Ok(Codec::H264),
str0m::format::Codec::Av1 => Ok(Codec::Av1),
other => Err(Error::Convert(format!("not a video codec: {other:?}"))),
}
}
}
/// Order in which a viewer accepts codecs: VP9 > VP8 > AV1 > H.264.
pub const VIEWER_PREFERENCE: [Codec; 4] = [Codec::Vp9, Codec::Vp8, Codec::Av1, Codec::H264];
/// What the encoder should optimise for.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ContentHint {
/// Screen content: sharp text, mostly static.
#[default]
Screen,
/// Camera-like content with motion.
Motion,
}
/// Encoder settings. The resolution follows the frames: the first frame and
/// every size change start a new keyframe.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncoderConfig {
/// Expected frame rate (rate control; timestamps come from the frames).
pub fps: u32,
/// Target bitrate in bits per second. TeamSpeak caps streams at 10 Mbit/s.
pub bitrate_bps: u32,
/// Maximum frames between keyframes; `None` sends keyframes only at the
/// start and on request (PLI), like WebRTC.
pub keyframe_interval: Option<u32>,
pub content: ContentHint,
/// Encoder threads; 0 picks a number from the resolution and CPU count.
pub threads: u32,
}
impl Default for EncoderConfig {
fn default() -> Self {
Self {
fps: 30,
bitrate_bps: 2_500_000,
keyframe_interval: None,
content: ContentHint::Screen,
threads: 0,
}
}
}
impl EncoderConfig {
/// Threads for a `width` x `height` encode (libwebrtc's heuristic).
pub fn threads_for(&self, width: u32, height: u32) -> u32 {
if self.threads > 0 {
return self.threads;
}
let cpus = std::thread::available_parallelism().map_or(1, |n| n.get() as u32);
let pixels = width * height;
if pixels >= 1920 * 1080 && cpus > 8 {
8
} else if pixels >= 1280 * 720 && cpus > 3 {
4
} else if pixels >= 640 * 480 && cpus > 2 {
2
} else {
1
}
}
}
/// One encoded frame, ready for `tsc_stream::Peer::write`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncodedFrame {
pub data: Vec<u8>,
pub keyframe: bool,
/// Presentation time on the 90 kHz RTP clock.
pub pts_90khz: u64,
}
/// A video encoder. Encoders are created per stream and used from one thread
/// at a time.
pub trait VideoEncoder: Send {
fn codec(&self) -> Codec;
/// Which implementation encodes (for logs and settings).
fn backend(&self) -> EncoderBackend;
/// Encode one frame of any pixel format. Returns no frame when the
/// encoder skipped it (rate control), usually one.
fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result<Vec<EncodedFrame>>;
/// Change the target bitrate (bits per second).
fn set_bitrate(&mut self, bps: u32) -> Result<()>;
}
/// A video decoder.
pub trait VideoDecoder: Send {
fn codec(&self) -> Codec;
/// Decode one complete frame (a depacketized RTP frame). Returns the
/// picture if one is ready; its timestamp is zero.
fn decode(&mut self, data: &[u8]) -> Result<Option<VideoFrame>>;
}
/// Implementations behind [`VideoEncoder`], in the streamer's order of
/// preference.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EncoderBackend {
/// An OS / GPU encoder (see [`hw`]).
Hardware(&'static str),
Libvpx,
OpenH264,
}
fn unavailable(codec: Codec, reason: impl Into<String>) -> Error {
Error::CodecUnavailable { codec, reason: reason.into() }
}
/// The codecs this build and machine can use, and factories for them.
///
/// Viewer order ([`Codecs::decoders`]): VP9 > VP8 > AV1 > H.264. Streamer
/// order ([`Codecs::encoders`]): hardware > VP8 (libvpx) > H.264 (OpenH264)
/// > VP9 (libvpx, costly in software).
pub struct Codecs {
hardware: Vec<Box<dyn hw::HardwareEncoderFactory>>,
#[cfg(feature = "openh264")]
openh264: Option<h264::OpenH264>,
}
impl Default for Codecs {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for Codecs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Codecs")
.field("decoders", &self.decoders())
.field("encoders", &self.encoders())
.finish()
}
}
impl Codecs {
/// Software codecs compiled in, plus whatever hardware encoders
/// [`hw::probe`] finds. H.264 needs [`Codecs::with_openh264`].
pub fn new() -> Self {
Self {
hardware: hw::probe(),
#[cfg(feature = "openh264")]
openh264: None,
}
}
/// Enable H.264 through a loaded OpenH264 library.
#[cfg(feature = "openh264")]
pub fn with_openh264(mut self, library: h264::OpenH264) -> Self {
self.openh264 = Some(library);
self
}
#[cfg(feature = "openh264")]
pub fn openh264(&self) -> Option<&h264::OpenH264> {
self.openh264.as_ref()
}
fn has_openh264(&self) -> bool {
#[cfg(feature = "openh264")]
return self.openh264.is_some();
#[cfg(not(feature = "openh264"))]
return false;
}
/// Whether `codec` can be decoded, or why not.
pub fn check_decoder(&self, codec: Codec) -> Result<()> {
match codec {
Codec::Vp8 | Codec::Vp9 => {
#[cfg(feature = "vpx")]
return vpx::check(codec, false);
#[cfg(not(feature = "vpx"))]
return Err(unavailable(codec, "built without the `vpx` feature"));
}
Codec::H264 if self.has_openh264() => Ok(()),
Codec::H264 => Err(unavailable(codec, "the OpenH264 library is not loaded")),
Codec::Av1 => {
#[cfg(feature = "av1")]
return Ok(());
#[cfg(not(feature = "av1"))]
return Err(unavailable(codec, "built without the `av1` feature"));
}
}
}
/// Decodable codecs in the viewer's order of preference.
pub fn decoders(&self) -> Vec<Codec> {
VIEWER_PREFERENCE.into_iter().filter(|&c| self.check_decoder(c).is_ok()).collect()
}
/// Encoders in the streamer's order of preference.
pub fn encoders(&self) -> Vec<(Codec, EncoderBackend)> {
let mut list = Vec::new();
for factory in &self.hardware {
for codec in factory.codecs() {
list.push((codec, EncoderBackend::Hardware(factory.name())));
}
}
#[cfg(feature = "vpx")]
if vpx::check(Codec::Vp8, true).is_ok() {
list.push((Codec::Vp8, EncoderBackend::Libvpx));
}
if self.has_openh264() {
list.push((Codec::H264, EncoderBackend::OpenH264));
}
#[cfg(feature = "vpx")]
if vpx::check(Codec::Vp9, true).is_ok() {
list.push((Codec::Vp9, EncoderBackend::Libvpx));
}
list
}
/// Encodable codecs in the streamer's order of preference, without
/// duplicates (for the offer).
pub fn encoder_codecs(&self) -> Vec<Codec> {
let mut codecs = Vec::new();
for (codec, _) in self.encoders() {
if !codecs.contains(&codec) {
codecs.push(codec);
}
}
codecs
}
pub fn new_decoder(&self, codec: Codec) -> Result<Box<dyn VideoDecoder>> {
self.check_decoder(codec)?;
match codec {
#[cfg(feature = "vpx")]
Codec::Vp8 | Codec::Vp9 => Ok(Box::new(vpx::VpxDecoder::new(codec)?)),
#[cfg(feature = "openh264")]
Codec::H264 => match &self.openh264 {
Some(lib) => Ok(Box::new(lib.decoder()?)),
None => Err(unavailable(codec, "the OpenH264 library is not loaded")),
},
#[cfg(feature = "av1")]
Codec::Av1 => Ok(Box::new(av1::Dav1dDecoder::new()?)),
#[allow(unreachable_patterns)]
_ => Err(unavailable(codec, "no decoder in this build")),
}
}
/// An encoder for `codec` from the most preferred backend that works.
pub fn new_encoder(
&self,
codec: Codec,
config: EncoderConfig,
) -> Result<Box<dyn VideoEncoder>> {
let mut last_error = None;
for (c, backend) in self.encoders() {
if c != codec {
continue;
}
match self.new_encoder_with(codec, backend, config.clone()) {
Ok(encoder) => return Ok(encoder),
Err(e) => {
tracing::warn!(%codec, ?backend, "encoder backend failed: {e}");
last_error = Some(e);
}
}
}
Err(last_error.unwrap_or_else(|| unavailable(codec, "no encoder in this build")))
}
/// An encoder from a specific backend.
pub fn new_encoder_with(
&self,
codec: Codec,
backend: EncoderBackend,
config: EncoderConfig,
) -> Result<Box<dyn VideoEncoder>> {
match backend {
EncoderBackend::Hardware(name) => {
let factory = self
.hardware
.iter()
.find(|f| f.name() == name)
.ok_or_else(|| unavailable(codec, format!("no hardware encoder {name}")))?;
factory.create(codec, &config)
}
#[cfg(feature = "vpx")]
EncoderBackend::Libvpx => Ok(Box::new(vpx::VpxEncoder::new(codec, config)?)),
#[cfg(feature = "openh264")]
EncoderBackend::OpenH264 if codec == Codec::H264 => match &self.openh264 {
Some(lib) => Ok(Box::new(lib.encoder(config)?)),
None => Err(unavailable(codec, "the OpenH264 library is not loaded")),
},
#[allow(unreachable_patterns)]
_ => Err(unavailable(codec, format!("{backend:?} cannot encode it in this build"))),
}
}
/// The first codec in our encoder preference that the viewer accepts.
pub fn pick_encoder(&self, accepted: &[Codec]) -> Option<Codec> {
self.encoder_codecs().into_iter().find(|c| accepted.contains(c))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codec_names() {
for c in Codec::ALL {
assert_eq!(c.name().parse::<Codec>().unwrap(), c);
}
assert_eq!("video/h264".parse::<Codec>().unwrap(), Codec::H264);
assert_eq!(" vp9 ".parse::<Codec>().unwrap(), Codec::Vp9);
assert!("opus".parse::<Codec>().is_err());
assert_eq!(Codec::Av1.to_string(), "AV1");
}
#[cfg(feature = "str0m")]
#[test]
fn str0m_mapping() {
for c in Codec::ALL {
let s: str0m::format::Codec = c.into();
assert_eq!(Codec::try_from(s).unwrap(), c);
}
assert!(Codec::try_from(str0m::format::Codec::Opus).is_err());
}
#[test]
fn preference_order() {
let codecs = Codecs::new();
// Without OpenH264, H.264 is neither offered nor accepted.
assert!(!codecs.decoders().contains(&Codec::H264));
assert!(codecs.new_decoder(Codec::H264).is_err());
let err = codecs.new_encoder(Codec::H264, EncoderConfig::default()).err().unwrap();
assert!(matches!(err, Error::CodecUnavailable { codec: Codec::H264, .. }), "{err}");
#[cfg(feature = "vpx")]
{
assert_eq!(codecs.decoders()[..2], [Codec::Vp9, Codec::Vp8]);
assert_eq!(codecs.encoder_codecs()[0], Codec::Vp8);
assert_eq!(codecs.pick_encoder(&[Codec::H264, Codec::Vp9]), Some(Codec::Vp9));
assert_eq!(codecs.pick_encoder(&[Codec::Vp8, Codec::Vp9]), Some(Codec::Vp8));
}
#[cfg(feature = "av1")]
assert!(codecs.decoders().contains(&Codec::Av1));
// Decoders keep the viewer order.
let order: Vec<usize> = codecs
.decoders()
.iter()
.map(|c| VIEWER_PREFERENCE.iter().position(|p| p == c).unwrap())
.collect();
assert!(order.windows(2).all(|w| w[0] < w[1]));
}
#[test]
fn thread_heuristic() {
let config = EncoderConfig { threads: 3, ..EncoderConfig::default() };
assert_eq!(config.threads_for(1920, 1080), 3);
assert_eq!(EncoderConfig::default().threads_for(320, 240), 1);
}
}
+254
View File
@@ -0,0 +1,254 @@
//! VP8 and VP9 through the system libvpx.
//!
//! Encoder settings follow libwebrtc's realtime configuration: one pass CBR,
//! no lag, error resilient, fixed high speed (`cpu-used` 8), keyframes on
//! request, and screen-content tuning for [`ContentHint::Screen`].
use std::time::Duration;
use crate::codec::{
Codec, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder,
};
use crate::convert;
use crate::frame::{FrameData, Plane, VIDEO_CLOCK_RATE, VideoFrame};
use crate::{Error, Result};
mod raw;
fn is_vp9(codec: Codec) -> Result<bool> {
match codec {
Codec::Vp8 => Ok(false),
Codec::Vp9 => Ok(true),
_ => Err(Error::CodecUnavailable { codec, reason: "not a libvpx codec".into() }),
}
}
/// Whether the linked libvpx can encode (or decode) `codec`.
pub fn check(codec: Codec, encoder: bool) -> Result<()> {
if raw::available(is_vp9(codec)?, encoder) {
Ok(())
} else {
let what = if encoder { "encoder" } else { "decoder" };
Err(Error::CodecUnavailable { codec, reason: format!("libvpx has no {codec} {what}") })
}
}
/// Version of the linked libvpx (`v1.14.0`).
pub fn libvpx_version() -> String {
raw::version()
}
/// libvpx VP8 / VP9 encoder.
pub struct VpxEncoder {
codec: Codec,
config: EncoderConfig,
encoder: Option<raw::Encoder>,
last_pts: Option<i64>,
}
impl VpxEncoder {
pub fn new(codec: Codec, config: EncoderConfig) -> Result<Self> {
check(codec, true)?;
Ok(Self { codec, config, encoder: None, last_pts: None })
}
fn error(&self, message: String) -> Error {
Error::Encoder { codec: self.codec, message }
}
/// (Re)create the libvpx context for this frame size.
fn ensure_encoder(&mut self, width: u32, height: u32) -> Result<&mut raw::Encoder> {
if self.encoder.as_ref().is_none_or(|e| e.size() != (width, height)) {
// Drop the old context first: only one lives at a time.
self.encoder = None;
let params = raw::EncoderParams {
vp9: self.codec == Codec::Vp9,
width,
height,
bitrate_kbps: self.config.bitrate_bps / 1000,
keyframe_interval: self.config.keyframe_interval,
screen: self.config.content == ContentHint::Screen,
threads: self.config.threads_for(width, height),
};
let encoder = raw::Encoder::new(&params).map_err(|e| self.error(e))?;
self.encoder = Some(encoder);
}
Ok(self.encoder.as_mut().expect("encoder was just created"))
}
}
impl VideoEncoder for VpxEncoder {
fn codec(&self) -> Codec {
self.codec
}
fn backend(&self) -> EncoderBackend {
EncoderBackend::Libvpx
}
fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result<Vec<EncodedFrame>> {
let i420 = convert::to_i420(frame)?;
let FrameData::I420 { y, u, v } = &i420.data else {
unreachable!("to_i420 returns I420");
};
// libvpx needs strictly increasing timestamps.
let mut pts = i420.pts_90khz() as i64;
if let Some(last) = self.last_pts
&& pts <= last
{
pts = last + 1;
}
self.last_pts = Some(pts);
let duration = VIDEO_CLOCK_RATE / u64::from(self.config.fps.max(1));
let image = raw::I420 {
width: i420.width,
height: i420.height,
y: &y.data,
u: &u.data,
v: &v.data,
y_stride: y.stride,
uv_stride: u.stride,
};
let codec = self.codec;
let encoder = self.ensure_encoder(i420.width, i420.height)?;
let packets = encoder
.encode(&image, pts, duration, force_keyframe)
.map_err(|message| Error::Encoder { codec, message })?;
Ok(packets
.into_iter()
.filter(|p| !p.data.is_empty())
.map(|p| EncodedFrame { data: p.data, keyframe: p.keyframe, pts_90khz: p.pts as u64 })
.collect())
}
fn set_bitrate(&mut self, bps: u32) -> Result<()> {
self.config.bitrate_bps = bps;
if let Some(encoder) = &mut self.encoder {
encoder
.set_bitrate(bps / 1000)
.map_err(|message| Error::Encoder { codec: self.codec, message })?;
}
Ok(())
}
}
/// libvpx VP8 / VP9 decoder.
pub struct VpxDecoder {
codec: Codec,
decoder: raw::Decoder,
}
impl VpxDecoder {
pub fn new(codec: Codec) -> Result<Self> {
let vp9 = is_vp9(codec)?;
check(codec, false)?;
let threads = std::thread::available_parallelism().map_or(1, |n| n.get().min(4) as u32);
let decoder =
raw::Decoder::new(vp9, threads).map_err(|message| Error::Decoder { codec, message })?;
Ok(Self { codec, decoder })
}
}
impl VideoDecoder for VpxDecoder {
fn codec(&self) -> Codec {
self.codec
}
fn decode(&mut self, data: &[u8]) -> Result<Option<VideoFrame>> {
let picture = self
.decoder
.decode(data)
.map_err(|message| Error::Decoder { codec: self.codec, message })?;
Ok(picture.map(|p| {
let chroma = p.width.div_ceil(2) as usize;
VideoFrame {
width: p.width,
height: p.height,
timestamp: Duration::ZERO,
data: FrameData::I420 {
y: Plane::new(p.y, p.width as usize),
u: Plane::new(p.u, chroma),
v: Plane::new(p.v, chroma),
},
}
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A gradient with a bright square that moves per frame.
fn frame(n: u32, w: u32, h: u32) -> VideoFrame {
let mut data = vec![0; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let inside = (x + 64 - n * 4 % 64) % w < 48 && y > h / 4 && y < h / 2;
let px = if inside {
[40, 220, 250, 255]
} else {
[(x % 256) as u8, (y % 256) as u8, 90, 255]
};
let i = ((y * w + x) * 4) as usize;
data[i..i + 4].copy_from_slice(&px);
}
}
VideoFrame::from_bgra(w, h, (w * 4) as usize, data)
.unwrap()
.with_timestamp(Duration::from_millis(u64::from(n) * 33))
}
fn roundtrip(codec: Codec) {
let config = EncoderConfig { fps: 30, bitrate_bps: 1_500_000, ..EncoderConfig::default() };
let mut encoder = VpxEncoder::new(codec, config).unwrap();
let mut decoder = VpxDecoder::new(codec).unwrap();
let mut decoded = 0;
for n in 0..12 {
let src = frame(n, 160, 120);
let out = encoder.encode(&src, n == 8).unwrap();
assert_eq!(out.len(), 1, "frame {n}");
assert_eq!(out[0].keyframe, n == 0 || n == 8, "frame {n}");
assert_eq!(out[0].pts_90khz, src.pts_90khz());
let picture = decoder.decode(&out[0].data).unwrap().expect("a picture");
assert_eq!((picture.width, picture.height), (160, 120));
let psnr = convert::psnr(&src, &picture).unwrap();
assert!(psnr > 28.0, "{codec} frame {n}: PSNR {psnr:.1} dB");
decoded += 1;
}
assert_eq!(decoded, 12);
}
#[test]
fn vp8_roundtrip() {
roundtrip(Codec::Vp8);
}
#[test]
fn vp9_roundtrip() {
roundtrip(Codec::Vp9);
}
#[test]
fn resolution_change_restarts_with_keyframe() {
let mut encoder = VpxEncoder::new(Codec::Vp8, EncoderConfig::default()).unwrap();
let mut decoder = VpxDecoder::new(Codec::Vp8).unwrap();
for (n, (w, h)) in [(64, 48), (64, 48), (97, 55)].into_iter().enumerate() {
let out = encoder.encode(&frame(n as u32, w, h), false).unwrap();
assert_eq!(out[0].keyframe, n != 1);
let picture = decoder.decode(&out[0].data).unwrap().unwrap();
assert_eq!((picture.width, picture.height), (w, h));
}
encoder.set_bitrate(300_000).unwrap();
assert!(!encoder.encode(&frame(3, 97, 55), false).unwrap()[0].keyframe);
}
#[test]
fn garbage_is_an_error() {
let mut decoder = VpxDecoder::new(Codec::Vp8).unwrap();
assert!(decoder.decode(&[0x42; 64]).is_err());
assert!(decoder.decode(&[]).unwrap().is_none());
assert!(VpxEncoder::new(Codec::H264, EncoderConfig::default()).is_err());
assert!(libvpx_version().starts_with('v'));
}
}
+435
View File
@@ -0,0 +1,435 @@
//! Minimal safe wrapper around the libvpx C API (`libvpx-native-sys`).
//!
//! The only `unsafe` code for VP8 / VP9. Existing safe wrappers either cover
//! encoding only or cannot change the bitrate of a running encoder, which
//! congestion control needs, so the few calls used are wrapped here. Every
//! pointer handed to libvpx comes from a checked slice or a boxed context
//! that outlives the call.
#![allow(unsafe_code)]
use std::ffi::{CStr, c_int, c_uint, c_ulong};
use std::mem::MaybeUninit;
use std::ptr;
use vpx_sys as ffi;
pub(super) type RawResult<T> = std::result::Result<T, String>;
/// Speed for realtime encoding. VP8: negative means a fixed speed (a
/// positive value would let libvpx pick one from a CPU budget).
const VP8_CPU_USED: c_int = -8;
const VP9_CPU_USED: c_int = 8;
fn iface(vp9: bool, encoder: bool) -> *const ffi::vpx_codec_iface {
// SAFETY: these return pointers to static interface tables (or NULL if
// libvpx was built without that codec); no arguments.
unsafe {
match (vp9, encoder) {
(false, true) => ffi::vpx_codec_vp8_cx(),
(true, true) => ffi::vpx_codec_vp9_cx(),
(false, false) => ffi::vpx_codec_vp8_dx(),
(true, false) => ffi::vpx_codec_vp9_dx(),
}
}
}
/// Whether the linked libvpx has this codec.
pub(super) fn available(vp9: bool, encoder: bool) -> bool {
!iface(vp9, encoder).is_null()
}
/// The libvpx version string, e.g. `v1.14.0`.
pub(super) fn version() -> String {
// SAFETY: returns a pointer to a static NUL-terminated string.
unsafe { CStr::from_ptr(ffi::vpx_codec_version_str()) }.to_string_lossy().into_owned()
}
fn error_text(ctx: Option<&ffi::vpx_codec_ctx_t>, err: ffi::vpx_codec_err_t) -> String {
// SAFETY: vpx_codec_err_to_string returns a static string for any code.
let mut text =
unsafe { CStr::from_ptr(ffi::vpx_codec_err_to_string(err)) }.to_string_lossy().into_owned();
if let Some(ctx) = ctx {
// SAFETY: the context is initialised; the detail is NULL or a string
// owned by the context, copied before the next libvpx call.
let detail = unsafe { ffi::vpx_codec_error_detail(ctx) };
if !detail.is_null() {
let detail = unsafe { CStr::from_ptr(detail) }.to_string_lossy();
text.push_str(": ");
text.push_str(&detail);
}
}
text
}
fn check(ctx: Option<&ffi::vpx_codec_ctx_t>, err: ffi::vpx_codec_err_t) -> RawResult<()> {
if err == ffi::vpx_codec_err_t::VPX_CODEC_OK { Ok(()) } else { Err(error_text(ctx, err)) }
}
/// Borrowed I420 planes (U and V share a stride).
pub(super) struct I420<'a> {
pub width: u32,
pub height: u32,
pub y: &'a [u8],
pub u: &'a [u8],
pub v: &'a [u8],
pub y_stride: usize,
pub uv_stride: usize,
}
impl I420<'_> {
/// libvpx reads `width` x `height` luma and the rounded-up half size of
/// chroma through the plane pointers, so the slices must cover that.
fn check(&self) -> RawResult<()> {
let (w, h) = (self.width as usize, self.height as usize);
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
let fits = |len: usize, stride: usize, width: usize, rows: usize| {
stride >= width && rows > 0 && len >= stride * (rows - 1) + width
};
if w == 0 || h == 0 || w > 16384 || h > 16384 {
return Err(format!("unsupported size {w}x{h}"));
}
if !fits(self.y.len(), self.y_stride, w, h)
|| !fits(self.u.len(), self.uv_stride, cw, ch)
|| !fits(self.v.len(), self.uv_stride, cw, ch)
{
return Err("I420 planes are too small".into());
}
if c_int::try_from(self.y_stride).is_err() || c_int::try_from(self.uv_stride).is_err() {
return Err("stride too large".into());
}
Ok(())
}
}
pub(super) struct EncoderParams {
pub vp9: bool,
pub width: u32,
pub height: u32,
pub bitrate_kbps: u32,
pub keyframe_interval: Option<u32>,
pub screen: bool,
pub threads: u32,
}
pub(super) struct Packet {
pub data: Vec<u8>,
pub keyframe: bool,
pub pts: i64,
}
/// An initialised encoder context.
pub(super) struct Encoder {
// Boxed: libvpx keeps pointers to the context and the configuration.
ctx: Box<ffi::vpx_codec_ctx_t>,
cfg: Box<ffi::vpx_codec_enc_cfg_t>,
}
// SAFETY: the context is only used through `&mut self`; libvpx contexts have
// no thread affinity.
unsafe impl Send for Encoder {}
impl Encoder {
pub fn new(p: &EncoderParams) -> RawResult<Self> {
let iface = iface(p.vp9, true);
if iface.is_null() {
return Err("libvpx was built without this encoder".into());
}
// SAFETY: zeroed is a valid initial state for this plain C struct;
// vpx_codec_enc_config_default fills it.
let mut cfg: Box<ffi::vpx_codec_enc_cfg_t> =
Box::new(unsafe { MaybeUninit::zeroed().assume_init() });
check(None, unsafe { ffi::vpx_codec_enc_config_default(iface, &mut *cfg, 0) })?;
cfg.g_w = p.width;
cfg.g_h = p.height;
cfg.g_timebase = ffi::vpx_rational { num: 1, den: 90_000 };
cfg.g_threads = p.threads;
cfg.g_error_resilient = ffi::VPX_ERROR_RESILIENT_DEFAULT;
cfg.g_lag_in_frames = 0;
cfg.g_pass = ffi::vpx_enc_pass::VPX_RC_ONE_PASS;
cfg.rc_end_usage = ffi::vpx_rc_mode::VPX_CBR;
cfg.rc_target_bitrate = p.bitrate_kbps.max(1);
cfg.rc_min_quantizer = 2;
cfg.rc_max_quantizer = if p.vp9 { 52 } else { 56 };
cfg.rc_undershoot_pct = if p.vp9 { 50 } else { 100 };
cfg.rc_overshoot_pct = 15;
cfg.rc_buf_initial_sz = 500;
cfg.rc_buf_optimal_sz = 600;
cfg.rc_buf_sz = 1000;
cfg.rc_dropframe_thresh = 0;
cfg.rc_resize_allowed = 0;
match p.keyframe_interval {
Some(n) => {
cfg.kf_mode = ffi::vpx_kf_mode::VPX_KF_AUTO;
cfg.kf_min_dist = 0;
cfg.kf_max_dist = n.max(1);
}
None => cfg.kf_mode = ffi::vpx_kf_mode::VPX_KF_DISABLED,
}
// SAFETY: zeroed context as libvpx expects before init.
let mut ctx: Box<ffi::vpx_codec_ctx_t> =
Box::new(unsafe { MaybeUninit::zeroed().assume_init() });
// SAFETY: ctx and cfg are valid and boxed (stable addresses) for the
// life of the encoder; the ABI version comes from the same headers
// as the struct layouts.
check(None, unsafe {
ffi::vpx_codec_enc_init_ver(
&mut *ctx,
iface,
&*cfg,
0,
ffi::VPX_ENCODER_ABI_VERSION as c_int,
)
})?;
let mut encoder = Self { ctx, cfg };
if p.vp9 {
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_CPUUSED, VP9_CPU_USED)?;
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_ROW_MT, 1)?;
let tiles = (31 - p.threads.max(1).leading_zeros()) as c_int;
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_TILE_COLUMNS, tiles)?;
// Cyclic refresh: realtime adaptive quantisation.
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_AQ_MODE, 3)?;
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_NOISE_SENSITIVITY, 0)?;
if p.screen {
let screen = ffi::vp9e_tune_content::VP9E_CONTENT_SCREEN as c_int;
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_TUNE_CONTENT, screen)?;
}
} else {
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_CPUUSED, VP8_CPU_USED)?;
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_NOISE_SENSITIVITY, 0)?;
if p.screen {
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_SCREEN_CONTENT_MODE, 1)?;
}
}
if p.screen {
// Skip unchanged blocks.
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_STATIC_THRESHOLD, 1)?;
} else {
// Keep keyframes near 3x an average frame to avoid bursts.
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_MAX_INTRA_BITRATE_PCT, 300)?;
}
Ok(encoder)
}
fn control(&mut self, id: ffi::vp8e_enc_control_id, value: c_int) -> RawResult<()> {
// SAFETY: every control used here takes one int / unsigned int
// argument (same size and promotion through varargs).
let err = unsafe { ffi::vpx_codec_control_(&mut *self.ctx, id as c_int, value) };
check(Some(&self.ctx), err).map_err(|e| format!("control {id:?}: {e}"))
}
/// Change the target bitrate of the running encoder.
pub fn set_bitrate(&mut self, kbps: u32) -> RawResult<()> {
self.cfg.rc_target_bitrate = kbps.max(1);
// SAFETY: ctx is initialised; cfg is the boxed configuration it was
// created with, still valid after the call.
let err = unsafe { ffi::vpx_codec_enc_config_set(&mut *self.ctx, &*self.cfg) };
check(Some(&self.ctx), err)
}
pub fn size(&self) -> (u32, u32) {
(self.cfg.g_w, self.cfg.g_h)
}
/// Encode one frame (pts and duration in 1/90000 s).
pub fn encode(
&mut self,
img: &I420<'_>,
pts: i64,
duration: u64,
keyframe: bool,
) -> RawResult<Vec<Packet>> {
img.check()?;
if (img.width, img.height) != self.size() {
return Err("frame size differs from the encoder size".into());
}
// SAFETY: zeroed vpx_image_t is valid; vpx_img_wrap fills the derived
// fields (chroma shifts, bps) for I420 at this size and points plane
// 0 at the Y data. The other planes and strides are then set to the
// checked slices. libvpx only reads through them during
// vpx_codec_encode (it copies into its own buffers), and the slices
// outlive the call.
let mut image: ffi::vpx_image_t = unsafe { MaybeUninit::zeroed().assume_init() };
let wrapped = unsafe {
ffi::vpx_img_wrap(
&mut image,
ffi::vpx_img_fmt::VPX_IMG_FMT_I420,
img.width,
img.height,
1,
img.y.as_ptr().cast_mut(),
)
};
if wrapped.is_null() {
return Err("vpx_img_wrap failed".into());
}
image.planes[0] = img.y.as_ptr().cast_mut();
image.planes[1] = img.u.as_ptr().cast_mut();
image.planes[2] = img.v.as_ptr().cast_mut();
image.planes[3] = ptr::null_mut();
image.stride = [img.y_stride as c_int, img.uv_stride as c_int, img.uv_stride as c_int, 0];
image.cs = ffi::vpx_color_space::VPX_CS_BT_601;
image.range = ffi::vpx_color_range::VPX_CR_STUDIO_RANGE;
let flags =
if keyframe { ffi::VPX_EFLAG_FORCE_KF as ffi::vpx_enc_frame_flags_t } else { 0 };
// SAFETY: see above; ctx is initialised and exclusively borrowed.
let err = unsafe {
ffi::vpx_codec_encode(
&mut *self.ctx,
&image,
pts,
duration as c_ulong,
flags,
ffi::VPX_DL_REALTIME as c_ulong,
)
};
check(Some(&self.ctx), err)?;
Ok(self.drain())
}
fn drain(&mut self) -> Vec<Packet> {
let mut packets = Vec::new();
let mut iter: ffi::vpx_codec_iter_t = ptr::null();
loop {
// SAFETY: iterates the packets of the last encode call; each
// packet and its buffer stay valid until the next libvpx call on
// this context, and are copied before that.
let pkt = unsafe { ffi::vpx_codec_get_cx_data(&mut *self.ctx, &mut iter) };
if pkt.is_null() {
break;
}
let pkt = unsafe { &*pkt };
if pkt.kind != ffi::vpx_codec_cx_pkt_kind::VPX_CODEC_CX_FRAME_PKT {
continue;
}
// SAFETY: `frame` is the active union member for frame packets.
let frame = unsafe { pkt.data.frame };
let data = if frame.buf.is_null() || frame.sz == 0 {
Vec::new()
} else {
unsafe { std::slice::from_raw_parts(frame.buf.cast::<u8>(), frame.sz) }.to_vec()
};
packets.push(Packet {
data,
keyframe: frame.flags & ffi::VPX_FRAME_IS_KEY != 0,
pts: frame.pts,
});
}
packets
}
}
impl Drop for Encoder {
fn drop(&mut self) {
// SAFETY: the context was initialised in `new` and is destroyed once.
unsafe { ffi::vpx_codec_destroy(&mut *self.ctx) };
}
}
/// A decoded picture, copied out of libvpx, planes without padding.
pub(super) struct Picture {
pub width: u32,
pub height: u32,
pub y: Vec<u8>,
pub u: Vec<u8>,
pub v: Vec<u8>,
}
pub(super) struct Decoder {
ctx: Box<ffi::vpx_codec_ctx_t>,
}
// SAFETY: as for `Encoder`.
unsafe impl Send for Decoder {}
impl Decoder {
pub fn new(vp9: bool, threads: u32) -> RawResult<Self> {
let iface = iface(vp9, false);
if iface.is_null() {
return Err("libvpx was built without this decoder".into());
}
let cfg = ffi::vpx_codec_dec_cfg_t { threads: threads as c_uint, w: 0, h: 0 };
// SAFETY: zeroed context before init; cfg is only read during init.
let mut ctx: Box<ffi::vpx_codec_ctx_t> =
Box::new(unsafe { MaybeUninit::zeroed().assume_init() });
check(None, unsafe {
ffi::vpx_codec_dec_init_ver(
&mut *ctx,
iface,
&cfg,
0,
ffi::VPX_DECODER_ABI_VERSION as c_int,
)
})?;
Ok(Self { ctx })
}
/// Decode one frame; returns the last picture it produced.
pub fn decode(&mut self, data: &[u8]) -> RawResult<Option<Picture>> {
if data.is_empty() {
return Ok(None);
}
let len = c_uint::try_from(data.len()).map_err(|_| "frame too large".to_owned())?;
// SAFETY: data is a valid slice for the duration of the call.
let err = unsafe {
ffi::vpx_codec_decode(&mut *self.ctx, data.as_ptr(), len, ptr::null_mut(), 0)
};
check(Some(&self.ctx), err)?;
let mut picture = None;
let mut iter: ffi::vpx_codec_iter_t = ptr::null();
loop {
// SAFETY: the image stays valid until the next decode call; its
// planes are copied out below.
let img = unsafe { ffi::vpx_codec_get_frame(&mut *self.ctx, &mut iter) };
if img.is_null() {
break;
}
picture = Some(copy_image(unsafe { &*img })?);
}
Ok(picture)
}
}
impl Drop for Decoder {
fn drop(&mut self) {
// SAFETY: initialised in `new`, destroyed once.
unsafe { ffi::vpx_codec_destroy(&mut *self.ctx) };
}
}
fn copy_image(img: &ffi::vpx_image_t) -> RawResult<Picture> {
let (swap_uv, supported) = match img.fmt {
ffi::vpx_img_fmt::VPX_IMG_FMT_I420 => (false, true),
ffi::vpx_img_fmt::VPX_IMG_FMT_YV12 => (true, true),
_ => (false, false),
};
if !supported || img.bit_depth != 8 {
return Err(format!("unsupported decoded format {:?} ({} bit)", img.fmt, img.bit_depth));
}
let (w, h) = (img.d_w as usize, img.d_h as usize);
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
let plane = |i: usize, width: usize, rows: usize| -> RawResult<Vec<u8>> {
let stride = usize::try_from(img.stride[i]).map_err(|_| "negative stride".to_owned())?;
if img.planes[i].is_null() || stride < width {
return Err("invalid decoded plane".into());
}
let mut out = Vec::with_capacity(width * rows);
for row in 0..rows {
// SAFETY: libvpx guarantees `rows` rows of `stride` bytes
// (at least `width` used) behind each plane pointer of a
// decoded image of this display size.
let src = unsafe { std::slice::from_raw_parts(img.planes[i].add(row * stride), width) };
out.extend_from_slice(src);
}
Ok(out)
};
let y = plane(0, w, h)?;
let (mut u, mut v) = (plane(1, cw, ch)?, plane(2, cw, ch)?);
if swap_uv {
std::mem::swap(&mut u, &mut v);
}
Ok(Picture { width: img.d_w, height: img.d_h, y, u, v })
}