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 81ecb53100
commit cc4cb52011
14 files changed
+2923 -1

No files matched your search

Generated
+311 -1
View File
@@ -289,6 +289,16 @@ version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
[[package]]
name = "annotate-snippets"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4"
dependencies = [
"anstyle",
"unicode-width",
]
[[package]]
name = "annotate-snippets"
version = "0.12.16"
@@ -424,6 +434,21 @@ dependencies = [
"libloading",
]
[[package]]
name = "ashpd"
version = "0.13.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb8421aaa9644a5faf26735f258b669b15f063313ef8f8e2bdb28912a1a6f111"
dependencies = [
"enumflags2",
"futures-util",
"getrandom 0.4.3",
"serde",
"serde_repr",
"tokio",
"zbus",
]
[[package]]
name = "asn1-rs"
version = "0.7.2"
@@ -676,6 +701,19 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "av-data"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fca67ba5d317924c02180c576157afd54babe48a76ebc66ce6d34bb8ba08308e"
dependencies = [
"byte-slice-cast",
"bytes",
"num-derive",
"num-rational",
"num-traits",
]
[[package]]
name = "aws-lc-rs"
version = "1.18.1"
@@ -818,6 +856,7 @@ version = "0.72.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
dependencies = [
"annotate-snippets 0.11.5",
"bitflags 2.13.2",
"cexpr",
"clang-sys",
@@ -971,6 +1010,12 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"
[[package]]
name = "byte-slice-cast"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7575182f7272186991736b70173b0ea045398f984bf5ebbb3804736ce1330c9d"
[[package]]
name = "bytemuck"
version = "1.25.2"
@@ -1009,6 +1054,15 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "bzip2"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
dependencies = [
"libbz2-rs-sys",
]
[[package]]
name = "calloop"
version = "0.13.0"
@@ -1096,6 +1150,16 @@ dependencies = [
"nom 7.1.3",
]
[[package]]
name = "cfg-expr"
version = "0.20.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe4ece8474b5f766c63426647e7b4b316b67431ade1036a8313cee24a03ae917"
dependencies = [
"smallvec",
"target-lexicon",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
@@ -1369,6 +1433,12 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "cookie-factory"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2"
[[package]]
name = "core-foundation"
version = "0.9.4"
@@ -1802,6 +1872,28 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
[[package]]
name = "dav1d"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ee89cb860616069c67520dcd66cacdb900b57c799f634a0eb6d91f6e2a82b61"
dependencies = [
"av-data",
"bitflags 2.13.2",
"dav1d-sys",
"static_assertions",
]
[[package]]
name = "dav1d-sys"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3c91aea6668645415331133ed6f8ddf0e7f40160cd97a12d59e68716a58704b"
dependencies = [
"libc",
"system-deps",
]
[[package]]
name = "dbl"
version = "0.3.2"
@@ -3438,7 +3530,7 @@ version = "1.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f55d48ebef05e2bf09ba5a1fc67bcb11033b9e12a2a50ed3105c7d25e2b539d0"
dependencies = [
"annotate-snippets",
"annotate-snippets 0.12.16",
"by_address",
"data-url",
"derive_more",
@@ -4169,6 +4261,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "libbz2-rs-sys"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"
[[package]]
name = "libc"
version = "0.2.189"
@@ -4234,6 +4332,33 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "libspa"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "882f7427e7989dcc9d388b7f05c4630390a1d7696f9ffa469cd4a7a48f0b4c40"
dependencies = [
"bitflags 2.13.2",
"cc",
"cookie-factory",
"libc",
"libspa-sys",
"nom 8.0.0",
"rustix 1.1.5",
"system-deps",
]
[[package]]
name = "libspa-sys"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924"
dependencies = [
"bindgen",
"cc",
"system-deps",
]
[[package]]
name = "libsqlite3-sys"
version = "0.38.2"
@@ -4255,6 +4380,16 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "libvpx-native-sys"
version = "5.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "296dc47df55b51ac871fac5f30a61dd3c3ea3f56a076498a6785f5e6f2f6ea75"
dependencies = [
"pkg-config",
"semver-parser",
]
[[package]]
name = "linebender_resource_handle"
version = "0.1.1"
@@ -5177,6 +5312,26 @@ version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "openh264"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fcc9071a0b5f9c501ddd01066c2600d922cc799dc450a52975222bcda7755a08"
dependencies = [
"openh264-sys2",
"wide",
]
[[package]]
name = "openh264-sys2"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ada29a4cadc13d4d326737af87c13e224210d7d99fe47594e9f3f9b0102fd70"
dependencies = [
"libloading",
"sha2 0.10.9",
]
[[package]]
name = "openssl-probe"
version = "0.2.1"
@@ -5441,6 +5596,16 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pest"
version = "2.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45d3aca230fad2e6f6317ca0a72724338c4960cb97168a85cdee66df4a9a21a8"
dependencies = [
"memchr",
"ucd-trie",
]
[[package]]
name = "petgraph"
version = "0.8.3"
@@ -5560,6 +5725,31 @@ dependencies = [
"futures-io",
]
[[package]]
name = "pipewire"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bde71084c4e25959d68f1ea54daa75e5ecdb338e5caf0b5510143b79baa32d5c"
dependencies = [
"bitflags 2.13.2",
"libc",
"libspa",
"libspa-sys",
"pipewire-sys",
"rustix 1.1.5",
]
[[package]]
name = "pipewire-sys"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0"
dependencies = [
"bindgen",
"libspa-sys",
"system-deps",
]
[[package]]
name = "pkcs1"
version = "0.8.0-rc.4"
@@ -6718,6 +6908,15 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "safe_arch"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f"
dependencies = [
"bytemuck",
]
[[package]]
name = "salsa20"
version = "0.11.0"
@@ -6886,6 +7085,15 @@ version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "semver-parser"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9900206b54a3527fdc7b8a938bffd94a568bac4f4aa8113b209df75a09c0dec2"
dependencies = [
"pest",
]
[[package]]
name = "serde"
version = "1.0.229"
@@ -7699,6 +7907,19 @@ dependencies = [
"libc",
]
[[package]]
name = "system-deps"
version = "7.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7"
dependencies = [
"cfg-expr",
"heck",
"pkg-config",
"toml",
"version-compare",
]
[[package]]
name = "t4rust-derive"
version = "0.3.1"
@@ -7740,6 +7961,12 @@ dependencies = [
"xattr",
]
[[package]]
name = "target-lexicon"
version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
[[package]]
name = "task-local"
version = "0.1.1"
@@ -7952,6 +8179,7 @@ dependencies = [
"signal-hook-registry",
"socket2",
"tokio-macros",
"tracing",
"windows-sys 0.61.2",
]
@@ -8310,6 +8538,30 @@ dependencies = [
"tsproto-types",
]
[[package]]
name = "tsc-media"
version = "0.1.0"
dependencies = [
"ashpd",
"bzip2",
"dav1d",
"libvpx-native-sys",
"memmap2",
"openh264",
"pipewire",
"reqwest",
"rustix 1.1.5",
"sha2 0.10.9",
"str0m",
"thiserror 2.0.21",
"tokio",
"tracing",
"wasapi",
"windows-capture",
"x11rb",
"yuv",
]
[[package]]
name = "tsc-model"
version = "0.1.0"
@@ -8590,6 +8842,12 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "ucd-trie"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
[[package]]
name = "udev"
version = "0.9.3"
@@ -8771,6 +9029,12 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "version-compare"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
[[package]]
name = "version_check"
version = "0.9.5"
@@ -8830,6 +9094,19 @@ dependencies = [
"try-lock",
]
[[package]]
name = "wasapi"
version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee144c215d8d31e94c1a599fbaf540ca82a7017e4f1786816b179f334fac751d"
dependencies = [
"log",
"num-integer",
"thiserror 2.0.21",
"windows",
"windows-core",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
@@ -9207,6 +9484,16 @@ dependencies = [
"static_assertions",
]
[[package]]
name = "wide"
version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d920ac99c3c8edce110cb8d07dbb324d6d026011dce85b1e9355b70f0adacc4f"
dependencies = [
"bytemuck",
"safe_arch",
]
[[package]]
name = "widestring"
version = "1.2.1"
@@ -9265,6 +9552,19 @@ dependencies = [
"windows-numerics",
]
[[package]]
name = "windows-capture"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09046acbe9b6d039cde50e8c8178d95bb0f9b33ed7feccc4465dadc5404b31b4"
dependencies = [
"parking_lot",
"rayon",
"thiserror 2.0.21",
"windows",
"windows-future",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
@@ -9820,6 +10120,15 @@ dependencies = [
"synstructure 0.14.0",
]
[[package]]
name = "yuv"
version = "0.8.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a295923535c00a4e72a50a0a1130097f93160b39892dd4d2d006b1e2b90d6bf9"
dependencies = [
"num-traits",
]
[[package]]
name = "zbus"
version = "5.19.0"
@@ -9845,6 +10154,7 @@ dependencies = [
"rustix 1.1.5",
"serde",
"serde_repr",
"tokio",
"tracing",
"uds_windows",
"uuid",
+1
View File
@@ -12,6 +12,7 @@ members = [
"crates/tsc-core",
"crates/tsc-gateway",
"crates/tsc-gateway-proto",
"crates/tsc-media",
"crates/tsc-model",
"crates/tsc-observer",
"crates/tsc-query",
+58
View File
@@ -0,0 +1,58 @@
[package]
name = "tsc-media"
version = "0.1.0"
description = "Video frames, pixel conversion, video codecs (VP8/VP9, H.264, AV1) and screen / system-audio capture for streams."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[features]
default = ["vpx", "openh264", "openh264-download"]
# VP8 and VP9 through the system libvpx (pkg-config `vpx`).
vpx = ["dep:libvpx-native-sys"]
# H.264 through Cisco's prebuilt OpenH264 library, loaded at runtime. The
# OpenH264 source is never compiled in (see docs/media.md).
openh264 = ["dep:openh264"]
# Download of Cisco's OpenH264 binary over HTTPS with a SHA-256 check.
openh264-download = ["openh264", "dep:reqwest", "dep:bzip2", "dep:sha2"]
# AV1 decoding through the system libdav1d (pkg-config `dav1d` >= 1.3).
av1 = ["dep:dav1d"]
# X11 screen capture (Linux).
x11 = ["dep:x11rb", "dep:memmap2", "dep:rustix"]
# Wayland screen capture (ScreenCast portal + PipeWire) and PipeWire system
# audio (Linux).
pipewire = ["dep:ashpd", "dep:pipewire"]
# Conversion between `Codec` and `str0m::format::Codec`.
str0m = ["dep:str0m"]
[dependencies]
bzip2 = { version = "0.6.1", optional = true }
dav1d = { version = "0.11.1", optional = true }
libvpx-native-sys = { version = "5.0.17", optional = true }
openh264 = { version = "0.9.8", default-features = false, features = ["libloading"], optional = true }
reqwest = { version = "0.13.5", default-features = false, features = ["rustls"], optional = true }
sha2 = { version = "0.10.9", optional = true }
str0m = { version = "0.23.1", default-features = false, optional = true }
thiserror = "2.0.21"
tokio = { version = "1", features = ["sync"] }
tracing = "0.1.44"
yuv = "0.8.19"
[target.'cfg(target_os = "linux")'.dependencies]
ashpd = { version = "0.13.13", default-features = false, features = ["screencast", "tokio"], optional = true }
memmap2 = { version = "0.9.11", optional = true }
pipewire = { version = "0.10.1", optional = true }
rustix = { version = "1.1.5", features = ["fs"], optional = true }
x11rb = { version = "0.13.2", features = ["randr", "shm", "xfixes"], optional = true }
[target.'cfg(windows)'.dependencies]
wasapi = "0.24.0"
windows-capture = "2.0.1"
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "time"] }
[lints]
workspace = true
+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 })
}
+283
View File
@@ -0,0 +1,283 @@
//! Pixel format conversion through `yuv` (yuvutils-rs).
//!
//! All YUV data uses BT.601 limited range: WebRTC endpoints assume it for VP8,
//! VP9 and H.264 unless the stream signals something else, and libwebrtc's
//! capture pipeline produces it.
use std::borrow::Cow;
use yuv::{
BufferStoreMut, YuvBiPlanarImage, YuvConversionMode, YuvPlanarImage, YuvPlanarImageMut,
YuvRange, YuvStandardMatrix,
};
use crate::frame::{FrameData, Plane, VideoFrame, chroma_size};
use crate::{Error, Result};
const RANGE: YuvRange = YuvRange::Limited;
const MATRIX: YuvStandardMatrix = YuvStandardMatrix::Bt601;
fn error(e: yuv::YuvError) -> Error {
Error::Convert(e.to_string())
}
fn stride_u32(stride: usize) -> Result<u32> {
u32::try_from(stride).map_err(|_| Error::InvalidFrame(format!("stride {stride} too large")))
}
/// Write the frame as RGBA (alpha 255) into `out`, `out_stride` bytes per row.
///
/// Suits a Slint `SharedPixelBuffer<Rgba8Pixel>`:
/// `to_rgba(&frame, buffer.make_mut_bytes(), width as usize * 4)`.
pub fn to_rgba(frame: &VideoFrame, out: &mut [u8], out_stride: usize) -> Result<()> {
frame.validate()?;
let (w, h) = (frame.width, frame.height);
let row = w as usize * 4;
let needed = out_stride * (h as usize - 1) + row;
if out_stride < row || out.len() < needed {
return Err(Error::InvalidFrame(format!(
"RGBA output of {} bytes with stride {out_stride} is too small for {w}x{h}",
out.len()
)));
}
let out_stride_u32 = stride_u32(out_stride)?;
match &frame.data {
FrameData::I420 { y, u, v } => {
let image = YuvPlanarImage {
y_plane: &y.data,
y_stride: stride_u32(y.stride)?,
u_plane: &u.data,
u_stride: stride_u32(u.stride)?,
v_plane: &v.data,
v_stride: stride_u32(v.stride)?,
width: w,
height: h,
};
yuv::yuv420_to_rgba(&image, out, out_stride_u32, RANGE, MATRIX).map_err(error)
}
FrameData::Nv12 { y, uv } => {
let image = YuvBiPlanarImage {
y_plane: &y.data,
y_stride: stride_u32(y.stride)?,
uv_plane: &uv.data,
uv_stride: stride_u32(uv.stride)?,
width: w,
height: h,
};
yuv::yuv_nv12_to_rgba(&image, out, out_stride_u32, RANGE, MATRIX, mode()).map_err(error)
}
FrameData::Bgra(p) => {
for y in 0..h as usize {
let src = p.row(y, row);
let dst = &mut out[y * out_stride..y * out_stride + row];
for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) {
d.copy_from_slice(&[s[2], s[1], s[0], 255]);
}
}
Ok(())
}
FrameData::Rgba(p) => {
for y in 0..h as usize {
out[y * out_stride..y * out_stride + row].copy_from_slice(p.row(y, row));
}
Ok(())
}
}
}
/// The frame as tightly packed RGBA (`width * 4` bytes per row).
pub fn to_rgba_vec(frame: &VideoFrame) -> Result<Vec<u8>> {
let stride = frame.width as usize * 4;
let mut out = vec![0; stride * frame.height as usize];
to_rgba(frame, &mut out, stride)?;
Ok(out)
}
fn mode() -> YuvConversionMode {
YuvConversionMode::Balanced
}
/// The frame as I420 with equal U and V strides (what the encoders take).
/// Borrows I420 input that already has that layout.
pub fn to_i420(frame: &VideoFrame) -> Result<Cow<'_, VideoFrame>> {
frame.validate()?;
let (w, h) = (frame.width, frame.height);
let (cw, ch) = chroma_size(w, h);
let data = match &frame.data {
FrameData::I420 { u, v, .. } if u.stride == v.stride => return Ok(Cow::Borrowed(frame)),
FrameData::I420 { y, u, v } => {
FrameData::I420 { y: y.clone(), u: repack(u, cw, ch), v: repack(v, cw, ch) }
}
FrameData::Nv12 { y, uv } => {
let mut u = Plane::filled(cw, ch, 0);
let mut v = Plane::filled(cw, ch, 0);
for row in 0..ch {
let src = uv.row(row, cw * 2);
let (u_row, v_row) = (&mut u.data[row * cw..][..cw], &mut v.data[row * cw..][..cw]);
for (i, pair) in src.chunks_exact(2).enumerate() {
u_row[i] = pair[0];
v_row[i] = pair[1];
}
}
FrameData::I420 { y: y.clone(), u, v }
}
FrameData::Bgra(p) | FrameData::Rgba(p) => {
let mut image = YuvPlanarImageMut::<u8> {
y_plane: BufferStoreMut::Owned(vec![0; w as usize * h as usize]),
y_stride: w,
u_plane: BufferStoreMut::Owned(vec![0; cw * ch]),
u_stride: cw as u32,
v_plane: BufferStoreMut::Owned(vec![0; cw * ch]),
v_stride: cw as u32,
width: w,
height: h,
};
let stride = stride_u32(p.stride)?;
let convert = if matches!(frame.data, FrameData::Bgra(_)) {
yuv::bgra_to_yuv420
} else {
yuv::rgba_to_yuv420
};
convert(&mut image, &p.data, stride, RANGE, MATRIX, mode()).map_err(error)?;
FrameData::I420 {
y: Plane::new(owned(image.y_plane), w as usize),
u: Plane::new(owned(image.u_plane), cw),
v: Plane::new(owned(image.v_plane), cw),
}
}
};
Ok(Cow::Owned(VideoFrame { width: w, height: h, timestamp: frame.timestamp, data }))
}
fn owned(buffer: BufferStoreMut<'_, u8>) -> Vec<u8> {
match buffer {
BufferStoreMut::Owned(v) => v,
BufferStoreMut::Borrowed(b) => b.to_vec(),
}
}
fn repack(plane: &Plane, width: usize, rows: usize) -> Plane {
let mut out = Plane::filled(width, rows, 0);
for y in 0..rows {
out.data[y * width..(y + 1) * width].copy_from_slice(plane.row(y, width));
}
out
}
/// Peak signal-to-noise ratio in dB between two frames of the same size,
/// over the RGB channels (for tests and quality checks).
pub fn psnr(a: &VideoFrame, b: &VideoFrame) -> Result<f64> {
if (a.width, a.height) != (b.width, b.height) {
return Err(Error::InvalidFrame(format!(
"size mismatch: {}x{} vs {}x{}",
a.width, a.height, b.width, b.height
)));
}
let (a, b) = (to_rgba_vec(a)?, to_rgba_vec(b)?);
let mut sum = 0.0;
let mut n = 0.0;
for (pa, pb) in a.chunks_exact(4).zip(b.chunks_exact(4)) {
for c in 0..3 {
let d = f64::from(pa[c]) - f64::from(pb[c]);
sum += d * d;
n += 1.0;
}
}
let mse = sum / n;
Ok(if mse == 0.0 { f64::INFINITY } else { 10.0 * (255.0 * 255.0 / mse).log10() })
}
#[cfg(test)]
mod tests {
use super::*;
/// BGRA test image with flat colour blocks (conversion is exact enough
/// only away from chroma edges).
fn blocks(w: u32, h: u32) -> VideoFrame {
let colors: [[u8; 3]; 4] = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [200, 200, 40]];
let mut data = vec![0; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let c = colors[((x * 2 / w) + 2 * (y * 2 / h)) as usize];
let i = ((y * w + x) * 4) as usize;
data[i..i + 4].copy_from_slice(&[c[2], c[1], c[0], 0]);
}
}
VideoFrame::from_bgra(w, h, (w * 4) as usize, data).unwrap()
}
fn pixel(rgba: &[u8], w: u32, x: u32, y: u32) -> [u8; 4] {
let i = ((y * w + x) * 4) as usize;
rgba[i..i + 4].try_into().unwrap()
}
fn close(a: [u8; 4], b: [u8; 3], tolerance: i32) -> bool {
(0..3).all(|c| (i32::from(a[c]) - i32::from(b[c])).abs() <= tolerance)
}
#[test]
fn bgra_to_rgba_swaps_and_sets_alpha() {
let frame = VideoFrame::from_bgra(1, 1, 4, vec![1, 2, 3, 0]).unwrap();
assert_eq!(to_rgba_vec(&frame).unwrap(), [3, 2, 1, 255]);
}
#[test]
fn rgb_yuv_roundtrip() {
let src = blocks(64, 48);
let i420 = to_i420(&src).unwrap();
assert!(matches!(i420, Cow::Owned(_)));
let rgba = to_rgba_vec(&i420).unwrap();
for (x, y, c) in [(10, 10, [255, 0, 0]), (50, 10, [0, 255, 0]), (10, 40, [0, 0, 255])] {
let p = pixel(&rgba, 64, x, y);
assert!(close(p, c, 3), "pixel at {x},{y} is {p:?}, expected {c:?}");
assert_eq!(p[3], 255);
}
assert!(psnr(&src, &i420).unwrap() > 30.0);
// Already I420: borrowed.
assert!(matches!(to_i420(&i420).unwrap(), Cow::Borrowed(_)));
}
#[test]
fn limited_range_bt601_values() {
// Pure white and black map to Y 235 / 16, neutral chroma.
let frame = VideoFrame::from_rgba(
2,
2,
8,
[[255; 4], [255; 4], [0, 0, 0, 255], [0, 0, 0, 255]].concat(),
)
.unwrap();
let i420 = to_i420(&frame).unwrap();
let FrameData::I420 { y, u, v } = &i420.data else { panic!("not I420") };
assert_eq!(y.data[..2], [235, 235]);
assert_eq!(y.data[2..4], [16, 16]);
assert!((i32::from(u.data[0]) - 128).abs() <= 1);
assert!((i32::from(v.data[0]) - 128).abs() <= 1);
}
#[test]
fn nv12_matches_i420() {
let i420 = to_i420(&blocks(32, 16)).unwrap().into_owned();
let FrameData::I420 { y, u, v } = &i420.data else { panic!("not I420") };
let uv: Vec<u8> = u.data.iter().zip(&v.data).flat_map(|(&u, &v)| [u, v]).collect();
let nv12 = VideoFrame {
data: FrameData::Nv12 { y: y.clone(), uv: Plane::new(uv, 32) },
..i420.clone()
};
assert_eq!(to_i420(&nv12).unwrap().into_owned(), i420);
assert_eq!(to_rgba_vec(&nv12).unwrap(), to_rgba_vec(&i420).unwrap());
}
#[test]
fn odd_sizes_and_strides() {
let src = blocks(33, 17);
let i420 = to_i420(&src).unwrap();
let FrameData::I420 { u, .. } = &i420.data else { panic!("not I420") };
assert_eq!(u.stride, 17);
// Padded output rows.
let mut out = vec![0; 40 * 4 * 16 + 33 * 4];
to_rgba(&i420, &mut out, 40 * 4).unwrap();
assert!(close(pixel(&out, 40, 2, 2), [255, 0, 0], 3));
assert!(to_rgba(&i420, &mut out[..100], 40 * 4).is_err());
}
}
+221
View File
@@ -0,0 +1,221 @@
//! Raw video frames and audio buffers.
use std::time::Duration;
use crate::{Error, Result};
/// Sample rate of all audio in this crate (and of Opus in streams).
pub const AUDIO_SAMPLE_RATE: u32 = 48_000;
/// RTP clock rate of video.
pub const VIDEO_CLOCK_RATE: u64 = 90_000;
/// Pixel layout of a [`VideoFrame`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PixelFormat {
/// 8-bit YUV 4:2:0 in three planes.
I420,
/// 8-bit YUV 4:2:0: a Y plane and an interleaved UV plane.
Nv12,
/// 4 bytes per pixel in B, G, R, A byte order (X11, Windows, PipeWire
/// `BGRx`); alpha may be undefined.
Bgra,
/// 4 bytes per pixel in R, G, B, A byte order.
Rgba,
}
/// One image plane: `stride` bytes per row, at least `stride * rows` bytes.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Plane {
pub data: Vec<u8>,
pub stride: usize,
}
impl Plane {
pub fn new(data: Vec<u8>, stride: usize) -> Self {
Self { data, stride }
}
/// A plane filled with `value`, without padding.
pub fn filled(width: usize, rows: usize, value: u8) -> Self {
Self { data: vec![value; width * rows], stride: width }
}
/// Row `y`, `width` bytes long.
pub fn row(&self, y: usize, width: usize) -> &[u8] {
&self.data[y * self.stride..y * self.stride + width]
}
fn check(&self, name: &str, width: usize, rows: usize) -> Result<()> {
if self.stride < width {
return Err(Error::InvalidFrame(format!(
"{name} stride {} is smaller than its width {width}",
self.stride
)));
}
// The last row need not be padded.
let needed = if rows == 0 { 0 } else { self.stride * (rows - 1) + width };
if self.data.len() < needed {
return Err(Error::InvalidFrame(format!(
"{name} plane has {} bytes, needs {needed}",
self.data.len()
)));
}
Ok(())
}
}
/// The pixels of a [`VideoFrame`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FrameData {
I420 { y: Plane, u: Plane, v: Plane },
Nv12 { y: Plane, uv: Plane },
Bgra(Plane),
Rgba(Plane),
}
/// An uncompressed video frame.
///
/// YUV frames use BT.601 limited range (what WebRTC endpoints assume unless
/// told otherwise); see [`crate::convert`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VideoFrame {
pub width: u32,
pub height: u32,
/// Capture or presentation time on a monotonic clock with an arbitrary
/// origin (capture backends use the start of the capture). Decoders
/// return frames with a zero timestamp; the caller knows the RTP time.
pub timestamp: Duration,
pub data: FrameData,
}
/// Size of the chroma planes of a 4:2:0 image.
pub fn chroma_size(width: u32, height: u32) -> (usize, usize) {
(width.div_ceil(2) as usize, height.div_ceil(2) as usize)
}
impl VideoFrame {
/// A black I420 frame.
pub fn black_i420(width: u32, height: u32) -> Self {
let (cw, ch) = chroma_size(width, height);
let data = FrameData::I420 {
y: Plane::filled(width as usize, height as usize, 16),
u: Plane::filled(cw, ch, 128),
v: Plane::filled(cw, ch, 128),
};
Self { width, height, timestamp: Duration::ZERO, data }
}
/// Wrap packed BGRA / BGRx pixels.
pub fn from_bgra(width: u32, height: u32, stride: usize, data: Vec<u8>) -> Result<Self> {
let frame = Self {
width,
height,
timestamp: Duration::ZERO,
data: FrameData::Bgra(Plane::new(data, stride)),
};
frame.validate()?;
Ok(frame)
}
/// Wrap packed RGBA pixels.
pub fn from_rgba(width: u32, height: u32, stride: usize, data: Vec<u8>) -> Result<Self> {
let frame = Self {
width,
height,
timestamp: Duration::ZERO,
data: FrameData::Rgba(Plane::new(data, stride)),
};
frame.validate()?;
Ok(frame)
}
pub fn with_timestamp(mut self, timestamp: Duration) -> Self {
self.timestamp = timestamp;
self
}
pub fn format(&self) -> PixelFormat {
match self.data {
FrameData::I420 { .. } => PixelFormat::I420,
FrameData::Nv12 { .. } => PixelFormat::Nv12,
FrameData::Bgra(_) => PixelFormat::Bgra,
FrameData::Rgba(_) => PixelFormat::Rgba,
}
}
/// The timestamp on the 90 kHz RTP video clock.
pub fn pts_90khz(&self) -> u64 {
(self.timestamp.as_micros() * u128::from(VIDEO_CLOCK_RATE) / 1_000_000) as u64
}
/// Check that the planes are large enough for the frame size.
pub fn validate(&self) -> Result<()> {
if self.width == 0 || self.height == 0 {
return Err(Error::InvalidFrame(format!("empty frame {}x{}", self.width, self.height)));
}
let (w, h) = (self.width as usize, self.height as usize);
let (cw, ch) = chroma_size(self.width, self.height);
match &self.data {
FrameData::I420 { y, u, v } => {
y.check("Y", w, h)?;
u.check("U", cw, ch)?;
v.check("V", cw, ch)
}
FrameData::Nv12 { y, uv } => {
y.check("Y", w, h)?;
uv.check("UV", cw * 2, ch)
}
FrameData::Bgra(p) => p.check("BGRA", w * 4, h),
FrameData::Rgba(p) => p.check("RGBA", w * 4, h),
}
}
}
/// Interleaved 32-bit float audio at [`AUDIO_SAMPLE_RATE`].
#[derive(Clone, Debug, PartialEq)]
pub struct AudioBuffer {
pub samples: Vec<f32>,
pub channels: u16,
/// Capture time on a monotonic clock with an arbitrary origin.
pub timestamp: Duration,
}
impl AudioBuffer {
/// Samples per channel.
pub fn frames(&self) -> usize {
self.samples.len() / usize::from(self.channels.max(1))
}
pub fn duration(&self) -> Duration {
Duration::from_secs_f64(self.frames() as f64 / f64::from(AUDIO_SAMPLE_RATE))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validate_checks_planes() {
let frame = VideoFrame::black_i420(33, 17);
frame.validate().unwrap();
assert_eq!(chroma_size(33, 17), (17, 9));
let short = VideoFrame::from_bgra(4, 4, 16, vec![0; 16 * 3 + 15]);
assert!(matches!(short, Err(Error::InvalidFrame(_))));
// The last row needs no padding.
VideoFrame::from_bgra(4, 4, 20, vec![0; 20 * 3 + 16]).unwrap();
assert!(VideoFrame::from_rgba(4, 4, 8, vec![0; 64]).is_err());
assert!(VideoFrame::black_i420(0, 4).validate().is_err());
}
#[test]
fn rtp_time() {
let frame = VideoFrame::black_i420(2, 2).with_timestamp(Duration::from_millis(1500));
assert_eq!(frame.pts_90khz(), 135_000);
let audio = AudioBuffer { samples: vec![0.0; 960], channels: 2, timestamp: Duration::ZERO };
assert_eq!(audio.frames(), 480);
assert_eq!(audio.duration(), Duration::from_millis(10));
}
}
+55
View File
@@ -0,0 +1,55 @@
//! Media for TeamSpeak 6 streams: frames, pixel conversion, video codecs and
//! screen / system-audio capture.
//!
//! - [`frame`]: [`VideoFrame`] (I420, NV12, BGRA, RGBA) and [`AudioBuffer`]
//! (interleaved `f32`, 48 kHz)
//! - [`convert`]: YUV ↔ RGB conversion (BT.601 limited range, the WebRTC
//! default), e.g. RGBA for rendering and I420 for encoding
//! - [`codec`]: [`VideoEncoder`] / [`VideoDecoder`] traits, codec preference
//! and the backends: libvpx (VP8/VP9, feature `vpx`), Cisco's OpenH264
//! loaded at runtime (H.264, feature `openh264`), dav1d (AV1 decoding,
//! feature `av1`)
//! - [`queue`]: the bounded, drop-oldest channel capture backends deliver on
//!
//! Encoded frames go to `tsc_stream::Peer::write` with an RTP time of
//! [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to
//! [`VideoDecoder::decode`].
pub mod codec;
pub mod convert;
pub mod frame;
pub mod queue;
pub use codec::{
Codec, Codecs, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder,
VideoEncoder,
};
pub use frame::{AudioBuffer, FrameData, PixelFormat, Plane, VideoFrame};
pub use queue::{FrameReceiver, FrameSender, frame_channel};
/// Errors of this crate.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid frame: {0}")]
InvalidFrame(String),
#[error("pixel conversion failed: {0}")]
Convert(String),
#[error("{codec} is not available: {reason}")]
CodecUnavailable { codec: Codec, reason: String },
#[error("{codec} encoder: {message}")]
Encoder { codec: Codec, message: String },
#[error("{codec} decoder: {message}")]
Decoder { codec: Codec, message: String },
#[error("{backend} capture is not available: {reason}")]
CaptureUnavailable { backend: &'static str, reason: String },
#[error("{backend} capture: {message}")]
Capture { backend: &'static str, message: String },
#[error("the user cancelled the capture")]
Cancelled,
#[error("download failed: {0}")]
Download(String),
#[error("I/O: {0}")]
Io(#[from] std::io::Error),
}
pub type Result<T> = std::result::Result<T, Error>;
+225
View File
@@ -0,0 +1,225 @@
//! Bounded channel from capture threads to consumers.
//!
//! When the consumer falls behind, the oldest item is dropped: for screen
//! capture the newest frame is the one worth encoding, and memory stays
//! bounded. Receiving works from async code ([`FrameReceiver::recv`]) and
//! from plain threads ([`FrameReceiver::recv_timeout`]).
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use tokio::sync::Notify;
struct State<T> {
queue: VecDeque<T>,
capacity: usize,
senders: usize,
receiver: bool,
dropped: u64,
}
struct Shared<T> {
state: Mutex<State<T>>,
cond: Condvar,
notify: Notify,
}
impl<T> Shared<T> {
fn lock(&self) -> MutexGuard<'_, State<T>> {
// A panic while holding the lock cannot leave the queue inconsistent.
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
fn wake(&self) {
self.cond.notify_all();
self.notify.notify_one();
}
}
/// A channel keeping at most `capacity` (at least 1) items.
pub fn frame_channel<T>(capacity: usize) -> (FrameSender<T>, FrameReceiver<T>) {
let shared = Arc::new(Shared {
state: Mutex::new(State {
queue: VecDeque::new(),
capacity: capacity.max(1),
senders: 1,
receiver: true,
dropped: 0,
}),
cond: Condvar::new(),
notify: Notify::new(),
});
(FrameSender { shared: shared.clone() }, FrameReceiver { shared })
}
/// Sending half; cloneable. The channel closes when all senders are gone.
pub struct FrameSender<T> {
shared: Arc<Shared<T>>,
}
impl<T> FrameSender<T> {
/// Queue an item, dropping the oldest one if full. Returns `false` if the
/// receiver is gone (the producer should stop).
pub fn send(&self, item: T) -> bool {
let mut state = self.shared.lock();
if !state.receiver {
return false;
}
if state.queue.len() >= state.capacity {
state.queue.pop_front();
state.dropped += 1;
}
state.queue.push_back(item);
drop(state);
self.shared.wake();
true
}
pub fn is_closed(&self) -> bool {
!self.shared.lock().receiver
}
}
impl<T> Clone for FrameSender<T> {
fn clone(&self) -> Self {
self.shared.lock().senders += 1;
Self { shared: self.shared.clone() }
}
}
impl<T> Drop for FrameSender<T> {
fn drop(&mut self) {
self.shared.lock().senders -= 1;
self.shared.wake();
}
}
/// Receiving half.
pub struct FrameReceiver<T> {
shared: Arc<Shared<T>>,
}
impl<T> FrameReceiver<T> {
/// The next item; `None` once the channel is empty and closed.
pub async fn recv(&mut self) -> Option<T> {
loop {
{
let mut state = self.shared.lock();
if let Some(item) = state.queue.pop_front() {
return Some(item);
}
if state.senders == 0 {
return None;
}
}
// `notify_one` stores a permit when nobody waits, so a send
// between the check above and this await is not lost.
self.shared.notify.notified().await;
}
}
/// The next item if one is queued.
pub fn try_recv(&mut self) -> Option<T> {
self.shared.lock().queue.pop_front()
}
/// Block the thread until an item arrives, the channel closes or the
/// timeout passes. Do not call from async code.
pub fn recv_timeout(&mut self, timeout: Duration) -> Option<T> {
let deadline = Instant::now() + timeout;
let mut state = self.shared.lock();
loop {
if let Some(item) = state.queue.pop_front() {
return Some(item);
}
let now = Instant::now();
if state.senders == 0 || now >= deadline {
return None;
}
state = self
.shared
.cond
.wait_timeout(state, deadline - now)
.unwrap_or_else(|e| e.into_inner())
.0;
}
}
/// `true` once all senders are gone (queued items may remain).
pub fn is_closed(&self) -> bool {
self.shared.lock().senders == 0
}
/// Items dropped because the queue was full.
pub fn dropped(&self) -> u64 {
self.shared.lock().dropped
}
}
impl<T> Drop for FrameReceiver<T> {
fn drop(&mut self) {
let mut state = self.shared.lock();
state.receiver = false;
state.queue.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn drops_oldest_when_full() {
let (tx, mut rx) = frame_channel(2);
for i in 0..5 {
assert!(tx.send(i));
}
assert_eq!(rx.dropped(), 3);
assert_eq!(rx.try_recv(), Some(3));
assert_eq!(rx.recv_timeout(Duration::from_millis(1)), Some(4));
assert_eq!(rx.recv_timeout(Duration::from_millis(1)), None);
assert!(!rx.is_closed());
drop(tx);
assert!(rx.is_closed());
}
#[test]
fn sender_sees_closed_receiver() {
let (tx, rx) = frame_channel(1);
let tx2 = tx.clone();
drop(rx);
assert!(tx.is_closed());
assert!(!tx2.send(1));
}
#[test]
fn blocking_receive_across_threads() {
let (tx, mut rx) = frame_channel(4);
let t = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(20));
tx.send(7);
});
assert_eq!(rx.recv_timeout(Duration::from_secs(5)), Some(7));
t.join().unwrap();
// The sender is gone: no waiting.
assert_eq!(rx.recv_timeout(Duration::from_secs(5)), None);
}
#[tokio::test]
async fn async_receive() {
let (tx, mut rx) = frame_channel(4);
let t = std::thread::spawn(move || {
for i in 0..3 {
std::thread::sleep(Duration::from_millis(5));
tx.send(i);
}
});
let mut got = Vec::new();
while let Some(i) = rx.recv().await {
got.push(i);
}
t.join().unwrap();
assert_eq!(got, [0, 1, 2]);
}
}
+3
View File
@@ -34,6 +34,9 @@ allow = [
# use the royalty-free license, which requires the attribution shown in the
# app's About page and the README.
"LicenseRef-Slint-Royalty-free-2.0",
# Permissive BSD-style license of bzip2, kept by its pure Rust port
# (libbz2-rs-sys), which tsc-media uses to unpack Cisco's OpenH264 download.
"bzip2-1.0.6",
]
confidence-threshold = 0.9