Merge wip/media: tsc-media frames, codecs and capture

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-26 05:03:31 +00:00
commit ed8cad9a2e
26 files changed
+5620 -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", "x11", "pipewire"]
# 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
+225
View File
@@ -0,0 +1,225 @@
//! Screen and system-audio capture.
//!
//! Backends deliver frames on a [`FrameReceiver`] from their own thread; the
//! queue drops the oldest frame when the consumer falls behind.
//!
//! | Backend | Screen | System audio |
//! |---|---|---|
//! | [`synthetic`] | test pattern | sine tone |
//! | `x11` (Linux, feature `x11`) | MIT-SHM / GetImage, XFixes cursor | |
//! | `portal` / `pipewire_audio` (Linux, feature `pipewire`) | ScreenCast portal + PipeWire | default sink monitor |
//! | `windows` | Windows Graphics Capture | WASAPI process loopback |
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use crate::frame::{AudioBuffer, VideoFrame};
use crate::queue::FrameReceiver;
use crate::{Error, Result};
#[cfg(all(target_os = "linux", feature = "pipewire"))]
pub mod pipewire_audio;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
pub mod portal;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
mod pw;
pub mod synthetic;
#[cfg(windows)]
pub mod windows;
#[cfg(all(target_os = "linux", feature = "x11"))]
pub mod x11;
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
/// What to capture.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum SourceId {
/// A monitor, by the backend's index (see [`ScreenCapture::sources`]).
Monitor(u32),
/// A top-level window by native handle (X11 window id, Windows `HWND`).
Window(u64),
/// Whatever the user picks in the desktop portal's dialog.
Portal,
/// The synthetic test pattern.
Synthetic,
}
/// A source as shown in a picker.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CaptureSource {
pub id: SourceId,
pub name: String,
/// Current size; 0 if unknown (portal).
pub width: u32,
pub height: u32,
/// The primary monitor.
pub primary: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CaptureOptions {
/// Maximum frame rate.
pub fps: u32,
/// Draw the mouse cursor into the frames.
pub cursor: bool,
/// Frames queued before the oldest is dropped.
pub queue: usize,
}
impl Default for CaptureOptions {
fn default() -> Self {
Self { fps: 30, cursor: true, queue: 2 }
}
}
/// A screen / window capture backend.
pub trait ScreenCapture: Send {
/// Short name for logs (`"x11"`, `"portal"`, ...).
fn backend(&self) -> &'static str;
/// Monitors and windows that can be captured. The portal backend
/// returns a single [`SourceId::Portal`] entry: its dialog picks.
fn sources(&mut self) -> Result<Vec<CaptureSource>>;
/// Start capturing (stopping a previous capture). Async because the
/// portal asks the user. Frames stop when [`ScreenCapture::stop`] is
/// called, the backend is dropped, or the receiver is dropped.
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>>;
fn stop(&mut self);
}
/// A system-audio capture backend: 48 kHz stereo `f32` buffers.
pub trait AudioCapture: Send {
fn backend(&self) -> &'static str;
fn start(&mut self) -> Result<FrameReceiver<AudioBuffer>>;
fn stop(&mut self);
}
/// The screen capture backend for this session: the ScreenCast portal on
/// Wayland, X11 otherwise on Linux, Windows Graphics Capture on Windows.
pub fn default_screen_capture() -> Result<Box<dyn ScreenCapture>> {
#[cfg(target_os = "linux")]
{
let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|t| t == "wayland");
#[cfg(feature = "pipewire")]
if wayland {
return Ok(Box::new(portal::PortalCapture::new()));
}
#[cfg(feature = "x11")]
if std::env::var_os("DISPLAY").is_some() {
return Ok(Box::new(x11::X11Capture::new()));
}
let _ = wayland;
}
#[cfg(windows)]
return Ok(Box::new(windows::WindowsCapture::new()));
#[allow(unreachable_code)]
Err(Error::CaptureUnavailable {
backend: "screen",
reason: "no screen capture backend for this session in this build".into(),
})
}
/// The system-audio backend: PipeWire on Linux, WASAPI loopback on Windows.
pub fn default_audio_capture() -> Result<Box<dyn AudioCapture>> {
#[cfg(all(target_os = "linux", feature = "pipewire"))]
return Ok(Box::new(pipewire_audio::PipeWireAudioCapture::new()));
#[cfg(windows)]
return Ok(Box::new(windows::WasapiLoopback::new()));
#[allow(unreachable_code)]
Err(Error::CaptureUnavailable {
backend: "audio",
reason: "no system audio capture backend in this build".into(),
})
}
/// A capture thread that is stopped and joined on drop.
pub(crate) struct Worker {
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
}
impl Worker {
/// Run `f` on a named thread; it should return once the flag is set.
pub fn spawn(name: &str, f: impl FnOnce(Arc<AtomicBool>) + Send + 'static) -> Result<Self> {
let stop = Arc::new(AtomicBool::new(false));
let flag = stop.clone();
let thread = std::thread::Builder::new().name(name.to_owned()).spawn(move || f(flag))?;
Ok(Self { stop, thread: Some(thread) })
}
pub fn stop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(thread) = self.thread.take() {
thread.thread().unpark();
let _ = thread.join();
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
self.stop();
}
}
/// Paces a capture loop at a fixed rate.
pub(crate) struct Ticker {
interval: Duration,
next: Instant,
}
impl Ticker {
pub fn new(fps: u32) -> Self {
Self { interval: Duration::from_secs(1) / fps.max(1), next: Instant::now() }
}
/// Sleep until the next tick. Returns `false` if `stop` got set.
pub fn wait(&mut self, stop: &AtomicBool) -> bool {
self.next += self.interval;
let now = Instant::now();
if self.next < now {
// Fell behind: skip ticks instead of bursting.
self.next = now;
}
while !stop.load(Ordering::Relaxed) {
let now = Instant::now();
if now >= self.next {
return true;
}
// Woken early by `Worker::stop`.
std::thread::park_timeout(self.next - now);
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn worker_stops_promptly() {
let started = Instant::now();
let mut worker = Worker::spawn("test", |stop| {
let mut ticker = Ticker::new(1);
while ticker.wait(&stop) {}
})
.unwrap();
std::thread::sleep(Duration::from_millis(20));
worker.stop();
assert!(started.elapsed() < Duration::from_millis(900));
}
}
@@ -0,0 +1,178 @@
//! System audio on Linux: a PipeWire capture stream on the monitor of the
//! default sink (`stream.capture.sink = true`), converted by PipeWire to
//! 48 kHz stereo `f32`.
//!
//! The monitor carries everything the sink plays, including this app's own
//! playback (TeamSpeak voices). PipeWire has no "all but this process"
//! monitor; excluding our nodes would need a private null sink with links from
//! every other application's output node (tracked through the registry).
//! TODO; until then, the engine should play voices to a different sink or
//! accept that viewers hear them.
use std::time::Instant;
use pipewire as pw;
use pw::spa::param::audio::{AudioFormat, AudioInfoRaw};
use pw::spa::pod::{Object, Value};
use pw::spa::utils::SpaTypes;
use tracing::warn;
use crate::capture::AudioCapture;
use crate::capture::pw::{PwThread, pod, serialize};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer};
use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::{Error, Result};
const BACKEND: &str = "pipewire";
/// Name of our capture node in PipeWire.
pub const NODE_NAME: &str = "tsc-system-audio";
/// Captures the default sink's monitor through PipeWire.
#[derive(Default)]
pub struct PipeWireAudioCapture {
thread: Option<PwThread>,
}
impl PipeWireAudioCapture {
pub fn new() -> Self {
Self::default()
}
}
impl AudioCapture for PipeWireAudioCapture {
fn backend(&self) -> &'static str {
BACKEND
}
fn start(&mut self) -> Result<FrameReceiver<AudioBuffer>> {
self.stop();
// Half a second at PipeWire's usual 10-20 ms quantum.
let (tx, rx) = frame_channel(50);
let thread = PwThread::spawn("tsc-pipewire-audio", None, move |core, mainloop| {
audio_stream(core, mainloop, tx)
})
.map_err(|reason| Error::CaptureUnavailable { backend: BACKEND, reason })?;
self.thread = Some(thread);
Ok(rx)
}
fn stop(&mut self) {
self.thread = None;
}
}
struct AudioState {
tx: FrameSender<AudioBuffer>,
channels: u16,
started: Instant,
mainloop: pw::main_loop::MainLoopWeak,
}
fn audio_stream(
core: &pw::core::CoreRc,
mainloop: &pw::main_loop::MainLoopRc,
tx: FrameSender<AudioBuffer>,
) -> std::result::Result<(pw::stream::StreamRc, pw::stream::StreamListener<AudioState>), String> {
let props = pw::properties::properties! {
*pw::keys::MEDIA_TYPE => "Audio",
*pw::keys::MEDIA_CATEGORY => "Capture",
*pw::keys::MEDIA_ROLE => "Music",
*pw::keys::STREAM_CAPTURE_SINK => "true",
*pw::keys::NODE_NAME => NODE_NAME,
*pw::keys::NODE_DESCRIPTION => "TeamSpeak stream system audio",
};
let stream = pw::stream::StreamRc::new(core.clone(), NODE_NAME, props)
.map_err(|e| format!("PipeWire stream: {e}"))?;
let state =
AudioState { tx, channels: 2, started: Instant::now(), mainloop: mainloop.downgrade() };
let listener = stream
.add_local_listener_with_user_data(state)
.state_changed(|_, state, _, new| {
if let pw::stream::StreamState::Error(e) = &new {
warn!("system audio stream failed: {e}");
if let Some(mainloop) = state.mainloop.upgrade() {
mainloop.quit();
}
}
})
.param_changed(|_, state, id, param| {
let Some(param) = param else { return };
if id != pw::spa::param::ParamType::Format.as_raw() {
return;
}
let mut info = AudioInfoRaw::new();
if info.parse(param).is_ok() && info.channels() > 0 {
state.channels = info.channels() as u16;
}
})
.process(|stream, state| {
let Some(mut buffer) = stream.dequeue_buffer() else { return };
let Some(data) = buffer.datas_mut().first_mut() else { return };
let chunk = data.chunk();
let (offset, size) = (chunk.offset() as usize, chunk.size() as usize);
let Some(bytes) = data.data() else { return };
let Some(bytes) = bytes.get(offset..offset + size) else { return };
let samples: Vec<f32> = bytes
.chunks_exact(4)
.map(|b| f32::from_le_bytes(b.try_into().expect("4 bytes")))
.collect();
if samples.is_empty() {
return;
}
let buffer = AudioBuffer {
samples,
channels: state.channels,
timestamp: state.started.elapsed(),
};
if !state.tx.send(buffer)
&& let Some(mainloop) = state.mainloop.upgrade()
{
mainloop.quit();
}
})
.register()
.map_err(|e| format!("PipeWire listener: {e}"))?;
let mut info = AudioInfoRaw::new();
info.set_format(AudioFormat::F32LE);
info.set_rate(AUDIO_SAMPLE_RATE);
info.set_channels(2);
let format = serialize(Value::Object(Object {
type_: SpaTypes::ObjectParamFormat.as_raw(),
id: pw::spa::param::ParamType::EnumFormat.as_raw(),
properties: info.into(),
}))?;
stream
.connect(
pw::spa::utils::Direction::Input,
None,
pw::stream::StreamFlags::AUTOCONNECT
| pw::stream::StreamFlags::MAP_BUFFERS
| pw::stream::StreamFlags::RT_PROCESS,
&mut [pod(&format)?],
)
.map_err(|e| format!("cannot connect the system audio stream: {e}"))?;
Ok((stream, listener))
}
#[cfg(test)]
mod tests {
use super::*;
/// Without a PipeWire daemon, start fails with a clear error instead of
/// hanging. Skipped where a daemon socket exists.
#[test]
fn unavailable_without_daemon() {
let socket = std::env::var_os("XDG_RUNTIME_DIR")
.is_some_and(|d| std::path::Path::new(&d).join("pipewire-0").exists());
if socket || std::env::var_os("PIPEWIRE_REMOTE").is_some() {
eprintln!("skipped: a PipeWire daemon is running");
return;
}
let mut capture = PipeWireAudioCapture::new();
let err = capture.start().err().expect("no daemon");
assert!(matches!(err, Error::CaptureUnavailable { backend: "pipewire", .. }), "{err}");
assert!(err.to_string().contains("PipeWire"), "{err}");
}
}
+380
View File
@@ -0,0 +1,380 @@
//! Wayland screen capture: the xdg-desktop-portal ScreenCast interface
//! (`ashpd`) picks the source and hands over a PipeWire remote; frames come
//! through a PipeWire video stream.
//!
//! The portal can remember the user's choice: pass the token from
//! [`PortalCapture::restore_token`] to [`PortalCapture::with_restore_token`]
//! next time (it persists until the user revokes it). Only shared-memory
//! buffers (`BGRx` / `RGBx` family) are negotiated; DMA-BUF import is a TODO.
use std::time::{Duration, Instant};
use ashpd::desktop::PersistMode;
use ashpd::desktop::screencast::{CursorMode, Screencast, SelectSourcesOptions, SourceType};
use pipewire as pw;
use pw::spa::param::format::{FormatProperties, MediaSubtype, MediaType};
use pw::spa::param::video::{VideoFormat, VideoInfoRaw};
use pw::spa::pod::{Value, object, property};
use pw::spa::utils::{Fraction, Rectangle, SpaTypes};
use tracing::{debug, warn};
use crate::capture::pw::{PwThread, pod, serialize};
use crate::capture::{BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId};
use crate::frame::VideoFrame;
use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::{Error, Result};
const BACKEND: &str = "portal";
fn portal_error(e: ashpd::Error) -> Error {
match e {
ashpd::Error::Response(ashpd::desktop::ResponseError::Cancelled)
| ashpd::Error::Portal(ashpd::PortalError::Cancelled(_)) => Error::Cancelled,
// No bus, no portal service, or no ScreenCast interface.
ashpd::Error::Zbus(_)
| ashpd::Error::Portal(ashpd::PortalError::ZBus(_))
| ashpd::Error::PortalNotFound(_) => Error::CaptureUnavailable {
backend: BACKEND,
reason: format!("the ScreenCast portal is not available: {e}"),
},
other => Error::Capture { backend: BACKEND, message: other.to_string() },
}
}
/// A portal session kept open while capturing.
struct Session {
proxy: Screencast,
session: ashpd::desktop::Session<Screencast>,
}
/// ScreenCast portal + PipeWire backend (Wayland, also works on X11 desktops
/// that run xdg-desktop-portal).
#[derive(Default)]
pub struct PortalCapture {
restore_token: Option<String>,
session: Option<Session>,
thread: Option<PwThread>,
}
impl PortalCapture {
pub fn new() -> Self {
Self::default()
}
/// Reuse an earlier choice without asking (a token from
/// [`PortalCapture::restore_token`]).
pub fn with_restore_token(token: Option<String>) -> Self {
Self { restore_token: token, session: None, thread: None }
}
/// Token to persist after a successful start; `None` before that or if
/// the portal did not grant persistence.
pub fn restore_token(&self) -> Option<&str> {
self.restore_token.as_deref()
}
/// Whether the ScreenCast portal answers on the session bus.
pub async fn is_available() -> bool {
match Screencast::new().await {
// Reading a property needs the service to exist.
Ok(proxy) => proxy.available_source_types().await.is_ok(),
Err(_) => false,
}
}
async fn open(&mut self, options: &CaptureOptions) -> Result<(std::os::fd::OwnedFd, u32)> {
let proxy = Screencast::new().await.map_err(portal_error)?;
let session = proxy.create_session(Default::default()).await.map_err(portal_error)?;
let modes = proxy.available_cursor_modes().await.unwrap_or_default();
let cursor = if !options.cursor {
CursorMode::Hidden
} else if modes.contains(CursorMode::Embedded) {
CursorMode::Embedded
} else {
// Metadata cursors would need drawing; fall back to none.
CursorMode::Hidden
};
let select = SelectSourcesOptions::default()
.set_cursor_mode(cursor)
.set_sources(SourceType::Monitor | SourceType::Window)
.set_multiple(false)
.set_restore_token(self.restore_token.as_deref())
.set_persist_mode(PersistMode::ExplicitlyRevoked);
proxy
.select_sources(&session, select)
.await
.map_err(portal_error)?
.response()
.map_err(portal_error)?;
let streams = proxy
.start(&session, None, Default::default())
.await
.map_err(portal_error)?
.response()
.map_err(portal_error)?;
if let Some(token) = streams.restore_token() {
self.restore_token = Some(token.to_owned());
}
let stream = streams.streams().first().ok_or(Error::Cancelled)?;
let node = stream.pipe_wire_node_id();
debug!(node, size = ?stream.size(), "portal stream started");
let fd = proxy
.open_pipe_wire_remote(&session, Default::default())
.await
.map_err(portal_error)?;
self.session = Some(Session { proxy, session });
Ok((fd, node))
}
}
impl ScreenCapture for PortalCapture {
fn backend(&self) -> &'static str {
BACKEND
}
fn sources(&mut self) -> Result<Vec<CaptureSource>> {
Ok(vec![CaptureSource {
id: SourceId::Portal,
name: "Choose a screen or window".into(),
width: 0,
height: 0,
primary: true,
}])
}
/// Asks the user through the portal dialog (unless a restore token
/// applies). Needs a tokio runtime (the D-Bus connection runs on it).
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
if source != SourceId::Portal {
return Err(Error::SourceNotFound(source));
}
self.stop();
let (fd, node) = self.open(&options).await?;
let (tx, rx) = frame_channel(options.queue);
let fps = options.fps.max(1);
let thread = PwThread::spawn("tsc-portal-capture", Some(fd), move |core, mainloop| {
video_stream(core, mainloop, node, fps, tx)
})
.map_err(|e| Error::Capture { backend: BACKEND, message: e })?;
self.thread = Some(thread);
Ok(rx)
})
}
fn stop(&mut self) {
self.thread = None;
if let Some(s) = self.session.take() {
// Closing needs the async runtime; do it in the background if there
// is one, else the portal closes the session with the connection.
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
let _ = s.session.close().await;
drop(s.proxy);
});
}
}
}
}
impl Drop for PortalCapture {
fn drop(&mut self) {
self.stop();
}
}
struct VideoState {
tx: FrameSender<VideoFrame>,
format: Option<(VideoFormat, u32, u32)>,
started: Instant,
interval: Duration,
last: Option<Instant>,
mainloop: pw::main_loop::MainLoopWeak,
}
fn video_stream(
core: &pw::core::CoreRc,
mainloop: &pw::main_loop::MainLoopRc,
node: u32,
fps: u32,
tx: FrameSender<VideoFrame>,
) -> std::result::Result<(pw::stream::StreamRc, pw::stream::StreamListener<VideoState>), String> {
let props = pw::properties::properties! {
*pw::keys::MEDIA_TYPE => "Video",
*pw::keys::MEDIA_CATEGORY => "Capture",
*pw::keys::MEDIA_ROLE => "Screen",
};
let stream = pw::stream::StreamRc::new(core.clone(), "tsc-screen-capture", props)
.map_err(|e| format!("PipeWire stream: {e}"))?;
let state = VideoState {
tx,
format: None,
started: Instant::now(),
// Accept frames slightly early so rounding does not halve the rate.
interval: Duration::from_secs(1) / fps * 9 / 10,
last: None,
mainloop: mainloop.downgrade(),
};
let listener = stream
.add_local_listener_with_user_data(state)
.state_changed(|_, state, _, new| {
if let pw::stream::StreamState::Error(e) = &new {
warn!("screen capture stream failed: {e}");
}
if matches!(
new,
pw::stream::StreamState::Error(_) | pw::stream::StreamState::Unconnected
) && let Some(mainloop) = state.mainloop.upgrade()
{
mainloop.quit();
}
})
.param_changed(|_, state, id, param| {
let Some(param) = param else { return };
if id != pw::spa::param::ParamType::Format.as_raw() {
return;
}
let Ok((MediaType::Video, MediaSubtype::Raw)) =
pw::spa::param::format_utils::parse_format(param)
else {
return;
};
let mut info = VideoInfoRaw::new();
if info.parse(param).is_ok() {
let size = info.size();
debug!(format = ?info.format(), size.width, size.height, "screen capture format");
state.format = Some((info.format(), size.width, size.height));
}
})
.process(|stream, state| {
let Some(mut buffer) = stream.dequeue_buffer() else { return };
let Some((format, width, height)) = state.format else { return };
let now = Instant::now();
if state.last.is_some_and(|last| now - last < state.interval) {
return;
}
let Some(data) = buffer.datas_mut().first_mut() else { return };
let Some(frame) = copy_frame(data, format, width, height) else { return };
state.last = Some(now);
if !state.tx.send(frame.with_timestamp(now - state.started))
&& let Some(mainloop) = state.mainloop.upgrade()
{
// Nobody receives frames anymore.
mainloop.quit();
}
})
.register()
.map_err(|e| format!("PipeWire listener: {e}"))?;
let format = serialize(Value::Object(object!(
SpaTypes::ObjectParamFormat,
pw::spa::param::ParamType::EnumFormat,
property!(FormatProperties::MediaType, Id, MediaType::Video),
property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw),
property!(
FormatProperties::VideoFormat,
Choice,
Enum,
Id,
VideoFormat::BGRx,
VideoFormat::BGRx,
VideoFormat::BGRA,
VideoFormat::RGBx,
VideoFormat::RGBA
),
property!(
FormatProperties::VideoSize,
Choice,
Range,
Rectangle,
Rectangle { width: 1920, height: 1080 },
Rectangle { width: 1, height: 1 },
Rectangle { width: 8192, height: 8192 }
),
property!(
FormatProperties::VideoFramerate,
Choice,
Range,
Fraction,
Fraction { num: fps, denom: 1 },
Fraction { num: 0, denom: 1 },
Fraction { num: fps, denom: 1 }
),
)))?;
stream
.connect(
pw::spa::utils::Direction::Input,
Some(node),
pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS,
&mut [pod(&format)?],
)
.map_err(|e| format!("cannot connect to the screen cast node {node}: {e}"))?;
Ok((stream, listener))
}
/// Copy one shared-memory buffer into a frame. `None` for buffers without
/// mapped data (DMA-BUF), empty or corrupted chunks, and unknown formats.
fn copy_frame(
data: &mut pw::spa::buffer::Data,
format: VideoFormat,
width: u32,
height: u32,
) -> Option<VideoFrame> {
let bgra = match format {
VideoFormat::BGRx | VideoFormat::BGRA => true,
VideoFormat::RGBx | VideoFormat::RGBA => false,
_ => return None,
};
let chunk = data.chunk();
if chunk.size() == 0 || chunk.flags().contains(pw::spa::buffer::ChunkFlags::CORRUPTED) {
return None;
}
let offset = chunk.offset() as usize;
let row = width as usize * 4;
let stride = usize::try_from(chunk.stride()).ok().filter(|&s| s >= row).unwrap_or(row);
let bytes = data.data()?;
let bytes = bytes.get(offset..)?;
let needed = stride * (height as usize).checked_sub(1)? + row;
if bytes.len() < needed {
return None;
}
let mut pixels = Vec::with_capacity(row * height as usize);
for y in 0..height as usize {
pixels.extend_from_slice(&bytes[y * stride..y * stride + row]);
}
let frame = if bgra {
VideoFrame::from_bgra(width, height, row, pixels)
} else {
VideoFrame::from_rgba(width, height, row, pixels)
};
frame.ok()
}
#[cfg(test)]
mod tests {
use super::*;
/// Without a session bus the portal must fail cleanly, not hang or
/// panic. Skipped where a bus exists (it could open a real dialog).
#[tokio::test]
async fn unavailable_without_session_bus() {
let runtime_bus = std::env::var_os("XDG_RUNTIME_DIR")
.is_some_and(|d| std::path::Path::new(&d).join("bus").exists());
if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_some() || runtime_bus {
eprintln!("skipped: a D-Bus session bus is configured");
return;
}
let mut capture = PortalCapture::new();
assert_eq!(capture.sources().unwrap()[0].id, SourceId::Portal);
let err = capture.start(&SourceId::Portal, &CaptureOptions::default()).await.err().unwrap();
assert!(matches!(err, Error::CaptureUnavailable { backend: "portal", .. }), "{err}");
assert!(!PortalCapture::is_available().await);
assert!(capture.restore_token().is_none());
}
}
+103
View File
@@ -0,0 +1,103 @@
//! Shared PipeWire plumbing: a thread running a main loop.
use std::os::fd::OwnedFd;
use std::thread::JoinHandle;
use pipewire as pw;
use pw::spa::pod::{Pod, Value, serialize::PodSerializer};
/// A thread with a PipeWire main loop; quits and joins on drop.
pub(crate) struct PwThread {
quit: pw::channel::Sender<()>,
thread: Option<JoinHandle<()>>,
}
impl PwThread {
/// Connect to PipeWire on a new thread (through `fd`, e.g. a portal
/// remote, or to the user's daemon), let `setup` create the streams, and
/// run the loop until stopped. Setup errors are returned here.
///
/// `setup` returns what must stay alive while the loop runs (streams,
/// listeners); it can stop the loop itself through the main loop.
pub fn spawn<S, K>(name: &str, fd: Option<OwnedFd>, setup: S) -> Result<Self, String>
where
S: FnOnce(&pw::core::CoreRc, &pw::main_loop::MainLoopRc) -> Result<K, String>
+ Send
+ 'static,
K: 'static,
{
let (quit, quit_rx) = pw::channel::channel::<()>();
let (init_tx, init_rx) = std::sync::mpsc::channel::<Result<(), String>>();
let thread = std::thread::Builder::new()
.name(name.to_owned())
.spawn(move || {
pw::init();
let started = (|| {
let mainloop = pw::main_loop::MainLoopRc::new(None)
.map_err(|e| format!("PipeWire main loop: {e}"))?;
let context = pw::context::ContextRc::new(&mainloop, None)
.map_err(|e| format!("PipeWire context: {e}"))?;
let core = match fd {
Some(fd) => context.connect_fd_rc(fd, None),
None => context.connect_rc(None),
}
.map_err(|e| format!("cannot connect to PipeWire: {e}"))?;
let keep = setup(&core, &mainloop)?;
Ok::<_, String>((mainloop, context, core, keep))
})();
let (mainloop, _context, _core, keep) = match started {
Ok(parts) => parts,
Err(e) => {
let _ = init_tx.send(Err(e));
return;
}
};
let weak = mainloop.downgrade();
let _quit = quit_rx.attach(mainloop.loop_(), move |()| {
if let Some(mainloop) = weak.upgrade() {
mainloop.quit();
}
});
let _ = init_tx.send(Ok(()));
mainloop.run();
drop(keep);
})
.map_err(|e| e.to_string())?;
let mut this = Self { quit, thread: Some(thread) };
match init_rx.recv() {
Ok(Ok(())) => Ok(this),
Ok(Err(e)) => {
this.stop();
Err(e)
}
Err(_) => {
this.stop();
Err("the PipeWire thread ended during setup".into())
}
}
}
pub fn stop(&mut self) {
let _ = self.quit.send(());
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
impl Drop for PwThread {
fn drop(&mut self) {
self.stop();
}
}
/// Serialize a format object for `Stream::connect`.
pub(crate) fn serialize(value: Value) -> Result<Vec<u8>, String> {
PodSerializer::serialize(std::io::Cursor::new(Vec::new()), &value)
.map(|(cursor, _)| cursor.into_inner())
.map_err(|e| format!("cannot build the PipeWire format: {e:?}"))
}
pub(crate) fn pod(bytes: &[u8]) -> Result<&Pod, String> {
Pod::from_bytes(bytes).ok_or_else(|| "invalid PipeWire format pod".to_owned())
}
+261
View File
@@ -0,0 +1,261 @@
//! Synthetic sources for tests and `--synthetic` streaming: an animated test
//! pattern (a rectangle moving over a flat background, plus a frame counter)
//! and a sine tone.
use std::time::Duration;
use crate::capture::{
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Ticker, Worker,
};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame};
use crate::queue::{FrameReceiver, frame_channel};
use crate::{Error, Result};
/// Background colour of the pattern (RGB).
pub const BACKGROUND: [u8; 3] = [24, 40, 72];
/// Colour of the moving rectangle (RGB).
pub const RECT_COLOR: [u8; 3] = [240, 90, 30];
/// Colour of the frame counter (RGB).
pub const TEXT_COLOR: [u8; 3] = [255, 255, 255];
/// 3x5 bitmaps of the digits 0-9, one row per 3 bits.
const DIGITS: [[u8; 5]; 10] = [
[7, 5, 5, 5, 7],
[2, 6, 2, 2, 7],
[7, 1, 7, 4, 7],
[7, 1, 7, 1, 7],
[5, 5, 7, 1, 1],
[7, 4, 7, 1, 7],
[7, 4, 7, 5, 7],
[7, 1, 2, 2, 2],
[7, 5, 7, 5, 7],
[7, 5, 7, 1, 7],
];
/// The test pattern as a [`ScreenCapture`] backend.
pub struct SyntheticScreen {
width: u32,
height: u32,
worker: Option<Worker>,
}
impl SyntheticScreen {
pub fn new(width: u32, height: u32) -> Self {
Self { width: width.max(16), height: height.max(16), worker: None }
}
/// The moving rectangle in frame `n`: `(x, y, width, height)`.
pub fn rect(&self, n: u64) -> (u32, u32, u32, u32) {
let (rw, rh) = ((self.width / 5).max(8), (self.height / 5).max(8));
let range = u64::from(self.width - rw);
let step = u64::from((self.width / 60).max(1));
// Back and forth across the frame.
let pos = (n * step) % (2 * range.max(1));
let x = if pos > range { 2 * range - pos } else { pos };
(x as u32, (self.height - rh) / 2, rw, rh)
}
/// Frame `n` as BGRA, stamped `n / fps` seconds.
pub fn frame(&self, n: u64, fps: u32) -> VideoFrame {
let (w, h) = (self.width as usize, self.height as usize);
let mut data = vec![0; w * h * 4];
let bgra = |c: [u8; 3]| [c[2], c[1], c[0], 255];
for px in data.chunks_exact_mut(4) {
px.copy_from_slice(&bgra(BACKGROUND));
}
let mut fill = |x0: usize, y0: usize, rw: usize, rh: usize, c: [u8; 3]| {
for y in y0..(y0 + rh).min(h) {
for x in x0..(x0 + rw).min(w) {
data[(y * w + x) * 4..][..4].copy_from_slice(&bgra(c));
}
}
};
let (rx, ry, rw, rh) = self.rect(n);
fill(rx as usize, ry as usize, rw as usize, rh as usize, RECT_COLOR);
// Frame counter in the top-left corner.
let scale = (h / 48).max(1);
for (i, digit) in n.to_string().bytes().enumerate() {
let bitmap = DIGITS[usize::from(digit - b'0')];
let x0 = scale * 2 + i * 4 * scale;
for (row, bits) in bitmap.iter().enumerate() {
for col in 0..3 {
if bits & (4 >> col) != 0 {
let (x, y) = (x0 + col * scale, scale * 2 + row * scale);
fill(x, y, scale, scale, TEXT_COLOR);
}
}
}
}
let timestamp = Duration::from_secs(n) / fps.max(1);
VideoFrame::from_bgra(self.width, self.height, w * 4, data)
.expect("pattern buffer matches its size")
.with_timestamp(timestamp)
}
}
impl ScreenCapture for SyntheticScreen {
fn backend(&self) -> &'static str {
"synthetic"
}
fn sources(&mut self) -> Result<Vec<CaptureSource>> {
Ok(vec![CaptureSource {
id: SourceId::Synthetic,
name: "Test pattern".into(),
width: self.width,
height: self.height,
primary: true,
}])
}
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
if source != SourceId::Synthetic {
return Err(Error::SourceNotFound(source));
}
self.stop();
let (tx, rx) = frame_channel(options.queue);
let pattern = SyntheticScreen::new(self.width, self.height);
let fps = options.fps;
self.worker = Some(Worker::spawn("tsc-synthetic-video", move |stop| {
let mut ticker = Ticker::new(fps);
let mut n = 0;
while tx.send(pattern.frame(n, fps)) && ticker.wait(&stop) {
n += 1;
}
})?);
Ok(rx)
})
}
fn stop(&mut self) {
self.worker = None;
}
}
/// A sine tone as an [`AudioCapture`] backend: 10 ms stereo buffers.
pub struct SineSource {
frequency: f32,
amplitude: f32,
worker: Option<Worker>,
}
impl SineSource {
/// Samples per channel in one buffer (10 ms).
pub const BUFFER_FRAMES: usize = AUDIO_SAMPLE_RATE as usize / 100;
pub fn new(frequency: f32, amplitude: f32) -> Self {
Self { frequency, amplitude, worker: None }
}
/// Buffer `n` of the tone (continuous across buffers).
pub fn buffer(&self, n: u64) -> AudioBuffer {
let start = n * Self::BUFFER_FRAMES as u64;
let mut samples = Vec::with_capacity(Self::BUFFER_FRAMES * 2);
for i in 0..Self::BUFFER_FRAMES as u64 {
let t = (start + i) as f64 / f64::from(AUDIO_SAMPLE_RATE);
let s = f64::from(self.amplitude)
* (2.0 * std::f64::consts::PI * f64::from(self.frequency) * t).sin();
samples.extend([s as f32; 2]);
}
AudioBuffer { samples, channels: 2, timestamp: Duration::from_millis(n * 10) }
}
}
impl AudioCapture for SineSource {
fn backend(&self) -> &'static str {
"synthetic"
}
fn start(&mut self) -> Result<FrameReceiver<AudioBuffer>> {
self.stop();
// Half a second of audio before the oldest is dropped.
let (tx, rx) = frame_channel(50);
let tone = SineSource::new(self.frequency, self.amplitude);
self.worker = Some(Worker::spawn("tsc-synthetic-audio", move |stop| {
let mut ticker = Ticker::new(100);
let mut n = 0;
while tx.send(tone.buffer(n)) && ticker.wait(&stop) {
n += 1;
}
})?);
Ok(rx)
}
fn stop(&mut self) {
self.worker = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::convert;
fn rgb_at(frame: &VideoFrame, x: u32, y: u32) -> [u8; 3] {
let rgba = convert::to_rgba_vec(frame).unwrap();
let i = ((y * frame.width + x) * 4) as usize;
[rgba[i], rgba[i + 1], rgba[i + 2]]
}
#[test]
fn pattern_moves_and_counts() {
let screen = SyntheticScreen::new(320, 240);
let (x0, y0, w, h) = screen.rect(0);
let (x1, ..) = screen.rect(10);
assert_ne!(x0, x1);
let frame = screen.frame(10, 30);
assert_eq!(frame.timestamp, Duration::from_secs(10) / 30);
assert_eq!(rgb_at(&frame, x1 + w / 2, y0 + h / 2), RECT_COLOR);
assert_eq!(rgb_at(&frame, 319, 239), BACKGROUND);
// The "1" of "10" lights its middle column at the top.
let scale = 240 / 48;
assert_eq!(rgb_at(&frame, (scale * 2 + scale) as u32, (scale * 2) as u32), TEXT_COLOR);
// The rectangle bounces within the frame.
for n in 0..500 {
let (x, _, w, _) = screen.rect(n);
assert!(x + w <= 320);
}
}
#[test]
fn sine_is_continuous() {
let tone = SineSource::new(1000.0, 0.5);
let a = tone.buffer(0);
let b = tone.buffer(1);
assert_eq!(a.frames(), 480);
let last = a.samples[a.samples.len() - 2];
let next = b.samples[0];
// Adjacent samples of a 1 kHz tone differ by at most 2*pi*f/rate*amp.
assert!((last - next).abs() < 0.07, "{last} -> {next}");
assert!(a.samples.iter().all(|s| s.abs() <= 0.5));
}
#[tokio::test]
async fn capture_runs_until_stopped() {
let mut screen = SyntheticScreen::new(64, 48);
let options = CaptureOptions { fps: 50, ..CaptureOptions::default() };
assert!(screen.start(&SourceId::Monitor(0), &options).await.is_err());
let mut frames = screen.start(&SourceId::Synthetic, &options).await.unwrap();
let first = frames.recv().await.unwrap();
let second = frames.recv().await.unwrap();
assert_eq!((first.width, first.height), (64, 48));
assert!(second.timestamp > first.timestamp);
screen.stop();
// The worker is gone: the channel closes after the queued frames.
while frames.recv().await.is_some() {}
let mut tone = SineSource::new(440.0, 0.25);
let mut audio = tone.start().unwrap();
let buffer = audio.recv_timeout(Duration::from_secs(2)).unwrap();
assert_eq!((buffer.channels, buffer.frames()), (2, 480));
tone.stop();
}
}
+306
View File
@@ -0,0 +1,306 @@
//! Windows capture: Windows Graphics Capture (`windows-capture`) for monitors
//! and windows, WASAPI loopback (`wasapi`) for system audio.
//!
//! System audio uses process loopback in exclude mode with our own process
//! id, so our own playback (TeamSpeak voices) is not captured (Windows 10
//! 2004 or later). Older systems fall back to plain loopback of the default
//! output device, which includes our playback.
//!
//! Type-checked on Linux (`--target x86_64-pc-windows-gnu`), not run yet.
use std::collections::VecDeque;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use tracing::warn;
use windows_capture::capture::{CaptureControl, Context, GraphicsCaptureApiHandler};
use windows_capture::frame::Frame;
use windows_capture::graphics_capture_api::InternalCaptureControl;
use windows_capture::monitor::Monitor;
use windows_capture::settings::{
ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings,
GraphicsCaptureItemType, MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings,
};
use windows_capture::window::Window;
use crate::capture::{
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Worker,
};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame};
use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::{Error, Result};
const BACKEND: &str = "wgc";
fn failed(e: impl std::fmt::Display) -> Error {
Error::Capture { backend: BACKEND, message: e.to_string() }
}
/// Receives frames on the capture thread.
struct Handler {
tx: FrameSender<VideoFrame>,
started: Instant,
scratch: Vec<u8>,
}
impl GraphicsCaptureApiHandler for Handler {
type Flags = (FrameSender<VideoFrame>, Instant);
type Error = String;
fn new(ctx: Context<Self::Flags>) -> std::result::Result<Self, Self::Error> {
let (tx, started) = ctx.flags;
Ok(Self { tx, started, scratch: Vec::new() })
}
fn on_frame_arrived(
&mut self,
frame: &mut Frame,
control: InternalCaptureControl,
) -> std::result::Result<(), Self::Error> {
let buffer = frame.buffer().map_err(|e| e.to_string())?;
let (w, h) = (buffer.width(), buffer.height());
let pixels = buffer.as_nopadding_buffer(&mut self.scratch).to_vec();
let frame =
VideoFrame::from_bgra(w, h, w as usize * 4, pixels).map_err(|e| e.to_string())?;
if !self.tx.send(frame.with_timestamp(self.started.elapsed())) {
control.stop();
}
Ok(())
}
}
/// Windows Graphics Capture backend.
#[derive(Default)]
pub struct WindowsCapture {
control: Option<CaptureControl<Handler, String>>,
}
impl WindowsCapture {
pub fn new() -> Self {
Self::default()
}
}
fn start_item<T>(
item: T,
options: &CaptureOptions,
) -> Result<(CaptureControl<Handler, String>, FrameReceiver<VideoFrame>)>
where
T: TryInto<GraphicsCaptureItemType> + Send + 'static,
{
let (tx, rx) = frame_channel(options.queue);
let cursor = if options.cursor {
CursorCaptureSettings::WithCursor
} else {
CursorCaptureSettings::WithoutCursor
};
let settings = Settings::new(
item,
cursor,
DrawBorderSettings::WithoutBorder,
SecondaryWindowSettings::Default,
MinimumUpdateIntervalSettings::Custom(Duration::from_secs(1) / options.fps.max(1)),
DirtyRegionSettings::Default,
ColorFormat::Bgra8,
(tx, Instant::now()),
);
let control = Handler::start_free_threaded(settings).map_err(failed)?;
Ok((control, rx))
}
impl ScreenCapture for WindowsCapture {
fn backend(&self) -> &'static str {
BACKEND
}
fn sources(&mut self) -> Result<Vec<CaptureSource>> {
let primary = Monitor::primary().ok();
let mut sources = Vec::new();
for monitor in Monitor::enumerate().map_err(failed)? {
let Ok(index) = monitor.index() else { continue };
sources.push(CaptureSource {
id: SourceId::Monitor(index as u32),
name: monitor.name().or_else(|_| monitor.device_name()).unwrap_or_default(),
width: monitor.width().unwrap_or(0),
height: monitor.height().unwrap_or(0),
primary: primary == Some(monitor),
});
}
for window in Window::enumerate().map_err(failed)? {
let Ok(title) = window.title() else { continue };
if title.trim().is_empty() {
continue;
}
sources.push(CaptureSource {
id: SourceId::Window(window.as_raw_hwnd() as usize as u64),
name: title,
width: window.width().unwrap_or(0).max(0) as u32,
height: window.height().unwrap_or(0).max(0) as u32,
primary: false,
});
}
Ok(sources)
}
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
self.stop();
let not_found = || Error::SourceNotFound(source.clone());
let (control, rx) = match source {
SourceId::Monitor(index) => {
let monitor = Monitor::from_index(index as usize).map_err(|_| not_found())?;
start_item(monitor, &options)?
}
SourceId::Window(hwnd) => {
let window = Window::from_raw_hwnd(hwnd as usize as *mut std::ffi::c_void);
if !window.is_valid() {
return Err(not_found());
}
start_item(window, &options)?
}
_ => return Err(not_found()),
};
self.control = Some(control);
Ok(rx)
})
}
fn stop(&mut self) {
if let Some(control) = self.control.take()
&& let Err(e) = control.stop()
{
warn!("stopping Windows Graphics Capture: {e}");
}
}
}
impl Drop for WindowsCapture {
fn drop(&mut self) {
self.stop();
}
}
/// WASAPI loopback of everything except this process (see the module docs).
#[derive(Default)]
pub struct WasapiLoopback {
worker: Option<Worker>,
}
impl WasapiLoopback {
pub fn new() -> Self {
Self::default()
}
}
impl AudioCapture for WasapiLoopback {
fn backend(&self) -> &'static str {
"wasapi"
}
fn start(&mut self) -> Result<FrameReceiver<AudioBuffer>> {
self.stop();
let (tx, rx) = frame_channel(50);
let (init_tx, init_rx) = std::sync::mpsc::channel();
self.worker = Some(Worker::spawn("tsc-wasapi-loopback", move |stop| {
if let Err(e) = loopback(&tx, &stop, &init_tx) {
// After a successful start the receiver just sees the end.
let _ = init_tx.send(Err(e.clone()));
warn!("system audio capture ended: {e}");
}
})?);
match init_rx.recv() {
Ok(Ok(())) => Ok(rx),
Ok(Err(reason)) => {
self.stop();
Err(Error::CaptureUnavailable { backend: "wasapi", reason })
}
Err(_) => {
self.stop();
Err(Error::CaptureUnavailable {
backend: "wasapi",
reason: "capture thread ended".into(),
})
}
}
}
fn stop(&mut self) {
self.worker = None;
}
}
fn open_client() -> std::result::Result<wasapi::AudioClient, String> {
let format = wasapi::WaveFormat::new(
32,
32,
&wasapi::SampleType::Float,
AUDIO_SAMPLE_RATE as usize,
2,
None,
);
let mode = wasapi::StreamMode::EventsShared { autoconvert: true, buffer_duration_hns: 200_000 };
// Everything but our own process tree.
match wasapi::AudioClient::new_application_loopback_client(std::process::id(), false) {
Ok(mut client) => {
match client.initialize_client(&format, &wasapi::Direction::Capture, &mode) {
Ok(()) => return Ok(client),
Err(e) => warn!("process loopback unavailable ({e}), capturing all system audio"),
}
}
Err(e) => warn!("process loopback unavailable ({e}), capturing all system audio"),
}
let enumerator = wasapi::DeviceEnumerator::new().map_err(|e| e.to_string())?;
let device =
enumerator.get_default_device(&wasapi::Direction::Render).map_err(|e| e.to_string())?;
let mut client = device.get_iaudioclient().map_err(|e| e.to_string())?;
// Capture on a render device is loopback.
client
.initialize_client(&format, &wasapi::Direction::Capture, &mode)
.map_err(|e| e.to_string())?;
Ok(client)
}
fn loopback(
tx: &FrameSender<AudioBuffer>,
stop: &std::sync::atomic::AtomicBool,
init: &std::sync::mpsc::Sender<std::result::Result<(), String>>,
) -> std::result::Result<(), String> {
// COM for this thread; "already initialised" is fine.
let _ = wasapi::initialize_mta();
let client = open_client()?;
let event = client.set_get_eventhandle().map_err(|e| e.to_string())?;
let capture = client.get_audiocaptureclient().map_err(|e| e.to_string())?;
client.start_stream().map_err(|e| e.to_string())?;
let _ = init.send(Ok(()));
const FRAME_BYTES: usize = 2 * 4;
let chunk = AUDIO_SAMPLE_RATE as usize / 100 * FRAME_BYTES;
let started = Instant::now();
let mut queue = VecDeque::new();
while !stop.load(Ordering::Relaxed) {
// No events arrive while nothing plays.
if event.wait_for_event(100).is_err() {
continue;
}
capture.read_from_device_to_deque(&mut queue).map_err(|e| e.to_string())?;
while queue.len() >= chunk {
let bytes: Vec<u8> = queue.drain(..chunk).collect();
let samples = bytes
.chunks_exact(4)
.map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
.collect();
let buffer = AudioBuffer { samples, channels: 2, timestamp: started.elapsed() };
if !tx.send(buffer) {
stop.store(true, Ordering::Relaxed);
break;
}
}
}
client.stop_stream().map_err(|e| e.to_string())
}
+593
View File
@@ -0,0 +1,593 @@
//! X11 screen and window capture through x11rb.
//!
//! Pixels come through MIT-SHM (a memfd passed to the server, MIT-SHM 1.2)
//! or, for remote displays and old servers, plain GetImage. XFixes provides
//! the cursor image, which is blended into the frame. Supports 24/32-bit
//! TrueColor visuals (BGRx in memory).
//!
//! Window capture reads the window's own contents, clipped to the screen.
//! Without a compositor, parts covered by other windows may be stale.
mod shm;
use std::fmt::Display;
use std::os::fd::OwnedFd;
use std::time::Instant;
use memmap2::MmapMut;
use tracing::{debug, warn};
use x11rb::connection::Connection;
use x11rb::protocol::randr::ConnectionExt as _;
use x11rb::protocol::shm::ConnectionExt as _;
use x11rb::protocol::xfixes::ConnectionExt as _;
use x11rb::protocol::xproto::{
AtomEnum, ConnectionExt as _, ImageFormat, ImageOrder, MapState, Window, WindowClass,
};
use x11rb::rust_connection::RustConnection;
use crate::capture::{
BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Ticker, Worker,
};
use crate::frame::VideoFrame;
use crate::queue::{FrameReceiver, frame_channel};
use crate::{Error, Result};
const BACKEND: &str = "x11";
fn unavailable(e: impl Display) -> Error {
Error::CaptureUnavailable { backend: BACKEND, reason: e.to_string() }
}
fn failed(e: impl Display) -> Error {
Error::Capture { backend: BACKEND, message: e.to_string() }
}
/// X11 capture backend.
pub struct X11Capture {
display: Option<String>,
use_shm: bool,
worker: Option<Worker>,
}
impl Default for X11Capture {
fn default() -> Self {
Self::new()
}
}
impl X11Capture {
/// Capture from `$DISPLAY`.
pub fn new() -> Self {
Self { display: None, use_shm: true, worker: None }
}
/// Capture from another display (e.g. `":101"`).
pub fn with_display(display: impl Into<String>) -> Self {
Self { display: Some(display.into()), ..Self::new() }
}
/// Use MIT-SHM when the server supports it (default). Off forces
/// GetImage.
pub fn use_shm(mut self, enabled: bool) -> Self {
self.use_shm = enabled;
self
}
}
impl ScreenCapture for X11Capture {
fn backend(&self) -> &'static str {
BACKEND
}
fn sources(&mut self) -> Result<Vec<CaptureSource>> {
let x = Display11::connect(self.display.as_deref())?;
let mut sources: Vec<CaptureSource> = x
.monitors()?
.into_iter()
.enumerate()
.map(|(i, m)| CaptureSource {
id: SourceId::Monitor(i as u32),
name: m.name,
width: m.rect.width.into(),
height: m.rect.height.into(),
primary: m.primary,
})
.collect();
sources.extend(x.windows()?);
Ok(sources)
}
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
self.stop();
let x = Display11::connect(self.display.as_deref())?;
// Fail here, not in the thread, if the source does not exist.
x.region(&source)?;
let (tx, rx) = frame_channel(options.queue);
let use_shm = self.use_shm;
self.worker = Some(Worker::spawn("tsc-x11-capture", move |stop| {
let mut grabber = Grabber::new(&x, use_shm);
let cursor = options.cursor && x.xfixes;
let started = Instant::now();
let mut ticker = Ticker::new(options.fps);
loop {
match capture(&x, &source, &mut grabber, cursor) {
Ok(frame) => {
if !tx.send(frame.with_timestamp(started.elapsed())) {
break;
}
}
Err(e) => {
// E.g. the window was closed: end the stream.
warn!("X11 capture stopped: {e}");
break;
}
}
if !ticker.wait(&stop) {
break;
}
}
})?);
Ok(rx)
})
}
fn stop(&mut self) {
self.worker = None;
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Rect {
x: i16,
y: i16,
width: u16,
height: u16,
}
struct Monitor {
name: String,
rect: Rect,
primary: bool,
}
/// Part of a drawable to read, and where it is on the root window.
struct Region {
drawable: Window,
rect: Rect,
root_x: i32,
root_y: i32,
}
struct Atoms {
net_client_list: u32,
net_wm_name: u32,
utf8_string: u32,
}
struct Display11 {
conn: RustConnection,
root: Window,
screen: Rect,
shm: bool,
xfixes: bool,
atoms: Atoms,
}
impl Display11 {
fn connect(display: Option<&str>) -> Result<Self> {
let (conn, screen_num) = RustConnection::connect(display).map_err(unavailable)?;
let setup = conn.setup();
if setup.image_byte_order != ImageOrder::LSB_FIRST {
return Err(unavailable("MSB-first X servers are not supported"));
}
let screen = &setup.roots[screen_num];
let (root, root_depth) = (screen.root, screen.root_depth);
let screen_rect =
Rect { x: 0, y: 0, width: screen.width_in_pixels, height: screen.height_in_pixels };
let bpp =
setup.pixmap_formats.iter().find(|f| f.depth == root_depth).map(|f| f.bits_per_pixel);
if bpp != Some(32) {
return Err(unavailable(format!(
"unsupported screen depth {root_depth} ({bpp:?} bits per pixel), need 24/32-bit TrueColor"
)));
}
// MIT-SHM 1.2 is needed to pass a memfd.
let shm = conn
.shm_query_version()
.ok()
.and_then(|c| c.reply().ok())
.is_some_and(|v| (v.major_version, v.minor_version) >= (1, 2));
let xfixes = conn
.xfixes_query_version(4, 0)
.ok()
.and_then(|c| c.reply().ok())
.is_some_and(|v| v.major_version >= 1);
let intern = |name: &[u8]| -> Result<u32> {
Ok(conn.intern_atom(false, name).map_err(failed)?.reply().map_err(failed)?.atom)
};
let atoms = Atoms {
net_client_list: intern(b"_NET_CLIENT_LIST")?,
net_wm_name: intern(b"_NET_WM_NAME")?,
utf8_string: intern(b"UTF8_STRING")?,
};
debug!(shm, xfixes, "connected to X11 display");
Ok(Self { conn, root, screen: screen_rect, shm, xfixes, atoms })
}
/// RandR 1.5 monitors, or the whole screen.
fn monitors(&self) -> Result<Vec<Monitor>> {
let randr = self
.conn
.randr_query_version(1, 5)
.ok()
.and_then(|c| c.reply().ok())
.is_some_and(|v| (v.major_version, v.minor_version) >= (1, 5));
let mut monitors = Vec::new();
if randr
&& let Ok(reply) =
self.conn.randr_get_monitors(self.root, true).map_err(failed)?.reply()
{
for m in reply.monitors {
let name = self
.conn
.get_atom_name(m.name)
.ok()
.and_then(|c| c.reply().ok())
.map(|r| String::from_utf8_lossy(&r.name).into_owned())
.unwrap_or_else(|| "Monitor".into());
let rect = Rect { x: m.x, y: m.y, width: m.width, height: m.height };
if let Some(rect) = clip(rect, self.screen) {
monitors.push(Monitor { name, rect, primary: m.primary });
}
}
}
if monitors.is_empty() {
monitors.push(Monitor { name: "Screen".into(), rect: self.screen, primary: true });
}
Ok(monitors)
}
fn property(&self, window: Window, property: u32, type_: u32) -> Option<Vec<u8>> {
let reply = self
.conn
.get_property(false, window, property, type_, 0, 1 << 16)
.ok()?
.reply()
.ok()?;
(reply.type_ != u32::from(AtomEnum::NONE)).then_some(reply.value)
}
fn window_name(&self, window: Window) -> Option<String> {
let name = self
.property(window, self.atoms.net_wm_name, self.atoms.utf8_string)
.or_else(|| self.property(window, AtomEnum::WM_NAME.into(), AtomEnum::STRING.into()))?;
let name = String::from_utf8_lossy(&name).trim().to_owned();
(!name.is_empty()).then_some(name)
}
/// Named top-level windows: the window manager's client list, or mapped
/// children of the root when there is no window manager.
fn windows(&self) -> Result<Vec<CaptureSource>> {
let clients: Vec<Window> =
match self.property(self.root, self.atoms.net_client_list, AtomEnum::WINDOW.into()) {
Some(v) if !v.is_empty() => {
v.chunks_exact(4).map(|c| u32::from_ne_bytes(c.try_into().unwrap())).collect()
}
_ => {
let tree =
self.conn.query_tree(self.root).map_err(failed)?.reply().map_err(failed)?;
tree.children
.into_iter()
.filter(|&w| {
self.conn
.get_window_attributes(w)
.ok()
.and_then(|c| c.reply().ok())
.is_some_and(|a| {
a.map_state == MapState::VIEWABLE
&& a.class == WindowClass::INPUT_OUTPUT
&& !a.override_redirect
})
})
.collect()
}
};
let mut windows = Vec::new();
for window in clients {
let Some(name) = self.window_name(window) else { continue };
let Ok(geometry) = self.conn.get_geometry(window).map_err(failed)?.reply() else {
continue;
};
windows.push(CaptureSource {
id: SourceId::Window(window.into()),
name,
width: geometry.width.into(),
height: geometry.height.into(),
primary: false,
});
}
Ok(windows)
}
/// What to read for `source` right now.
fn region(&self, source: &SourceId) -> Result<Region> {
match *source {
SourceId::Monitor(i) => {
let monitors = self.monitors()?;
let m = monitors.get(i as usize).ok_or(Error::SourceNotFound(source.clone()))?;
Ok(Region {
drawable: self.root,
rect: m.rect,
root_x: m.rect.x.into(),
root_y: m.rect.y.into(),
})
}
SourceId::Window(id) => {
let window =
Window::try_from(id).map_err(|_| Error::SourceNotFound(source.clone()))?;
let not_found = || Error::SourceNotFound(source.clone());
let geometry = self
.conn
.get_geometry(window)
.map_err(failed)?
.reply()
.map_err(|_| not_found())?;
let bpp = self
.conn
.setup()
.pixmap_formats
.iter()
.find(|f| f.depth == geometry.depth)
.map(|f| f.bits_per_pixel);
if bpp != Some(32) {
return Err(failed(format!(
"window depth {} is not supported",
geometry.depth
)));
}
let origin = self
.conn
.translate_coordinates(window, self.root, 0, 0)
.map_err(failed)?
.reply()
.map_err(|_| not_found())?;
let on_root = Rect {
x: origin.dst_x,
y: origin.dst_y,
width: geometry.width,
height: geometry.height,
};
// GetImage fails for parts of a window outside the screen.
let visible =
clip(on_root, self.screen).ok_or_else(|| failed("the window is off screen"))?;
Ok(Region {
drawable: window,
rect: Rect {
x: visible.x - on_root.x,
y: visible.y - on_root.y,
width: visible.width,
height: visible.height,
},
root_x: visible.x.into(),
root_y: visible.y.into(),
})
}
_ => Err(Error::SourceNotFound(source.clone())),
}
}
}
/// Intersection of two rectangles.
fn clip(a: Rect, b: Rect) -> Option<Rect> {
let x0 = i32::from(a.x).max(b.x.into());
let y0 = i32::from(a.y).max(b.y.into());
let x1 = (i32::from(a.x) + i32::from(a.width)).min(i32::from(b.x) + i32::from(b.width));
let y1 = (i32::from(a.y) + i32::from(a.height)).min(i32::from(b.y) + i32::from(b.height));
(x1 > x0 && y1 > y0).then(|| Rect {
x: x0 as i16,
y: y0 as i16,
width: (x1 - x0) as u16,
height: (y1 - y0) as u16,
})
}
struct Segment {
id: u32,
map: MmapMut,
}
/// Reads regions through MIT-SHM, falling back to GetImage.
struct Grabber {
shm: bool,
segment: Option<Segment>,
}
impl Grabber {
fn new(x: &Display11, want_shm: bool) -> Self {
Self { shm: want_shm && x.shm, segment: None }
}
/// Tightly packed BGRx pixels of the region.
fn grab(&mut self, x: &Display11, r: &Region) -> Result<Vec<u8>> {
let size = usize::from(r.rect.width) * usize::from(r.rect.height) * 4;
if self.shm {
match self.grab_shm(x, r, size) {
Ok(pixels) => return Ok(pixels),
Err(e) => {
debug!("MIT-SHM capture failed, using GetImage: {e}");
self.shm = false;
self.release(x);
}
}
}
let reply = x
.conn
.get_image(
ImageFormat::Z_PIXMAP,
r.drawable,
r.rect.x,
r.rect.y,
r.rect.width,
r.rect.height,
!0,
)
.map_err(failed)?
.reply()
.map_err(failed)?;
let mut data = reply.data;
if data.len() < size {
return Err(failed(format!("GetImage returned {} bytes, expected {size}", data.len())));
}
data.truncate(size);
Ok(data)
}
fn grab_shm(&mut self, x: &Display11, r: &Region, size: usize) -> Result<Vec<u8>> {
if self.segment.as_ref().is_none_or(|s| s.map.len() < size) {
self.release(x);
self.segment = Some(Self::attach(x, size)?);
}
let segment = self.segment.as_ref().expect("attached above");
x.conn
.shm_get_image(
r.drawable,
r.rect.x,
r.rect.y,
r.rect.width,
r.rect.height,
!0,
ImageFormat::Z_PIXMAP.into(),
segment.id,
0,
)
.map_err(failed)?
.reply()
.map_err(failed)?;
Ok(segment.map[..size].to_vec())
}
fn attach(x: &Display11, size: usize) -> Result<Segment> {
let fd = rustix::fs::memfd_create("tsc-x11-capture", rustix::fs::MemfdFlags::CLOEXEC)
.map_err(|e| failed(format!("memfd_create: {e}")))?;
let file = std::fs::File::from(fd);
file.set_len(size as u64)?;
let map = shm::map(&file)?;
let id = x.conn.generate_id().map_err(failed)?;
x.conn
.shm_attach_fd(id, OwnedFd::from(file), false)
.map_err(failed)?
.check()
.map_err(failed)?;
Ok(Segment { id, map })
}
fn release(&mut self, x: &Display11) {
if let Some(segment) = self.segment.take() {
let _ = x.conn.shm_detach(segment.id);
let _ = x.conn.flush();
}
}
}
/// A cursor image: premultiplied ARGB, top-left corner in frame coordinates.
struct Cursor<'a> {
left: i32,
top: i32,
width: usize,
height: usize,
argb: &'a [u32],
}
/// Blend a premultiplied ARGB cursor onto packed BGRx pixels.
fn blend_cursor(bgrx: &mut [u8], width: usize, height: usize, cursor: &Cursor<'_>) {
for cy in 0..cursor.height {
let py = cursor.top + cy as i32;
if py < 0 || py >= height as i32 {
continue;
}
for cx in 0..cursor.width {
let px = cursor.left + cx as i32;
if px < 0 || px >= width as i32 {
continue;
}
let argb = cursor.argb[cy * cursor.width + cx];
let alpha = argb >> 24;
if alpha == 0 {
continue;
}
let i = (py as usize * width + px as usize) * 4;
for (c, shift) in [(0, 0), (1, 8), (2, 16)] {
let src = (argb >> shift) & 0xff;
let dst = u32::from(bgrx[i + c]);
bgrx[i + c] = (src + dst * (255 - alpha) / 255).min(255) as u8;
}
}
}
}
fn capture(
x: &Display11,
source: &SourceId,
grabber: &mut Grabber,
cursor: bool,
) -> Result<VideoFrame> {
let region = x.region(source)?;
let mut pixels = grabber.grab(x, &region)?;
let (w, h) = (usize::from(region.rect.width), usize::from(region.rect.height));
if cursor && let Ok(image) = x.conn.xfixes_get_cursor_image().map_err(failed)?.reply() {
let cursor = Cursor {
left: i32::from(image.x) - i32::from(image.xhot) - region.root_x,
top: i32::from(image.y) - i32::from(image.yhot) - region.root_y,
width: image.width.into(),
height: image.height.into(),
argb: &image.cursor_image,
};
if cursor.argb.len() >= cursor.width * cursor.height {
blend_cursor(&mut pixels, w, h, &cursor);
}
}
VideoFrame::from_bgra(region.rect.width.into(), region.rect.height.into(), w * 4, pixels)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clipping() {
let screen = Rect { x: 0, y: 0, width: 100, height: 50 };
let inside = Rect { x: 10, y: 10, width: 20, height: 20 };
assert_eq!(clip(inside, screen), Some(inside));
let partly = Rect { x: -5, y: 40, width: 20, height: 20 };
assert_eq!(clip(partly, screen), Some(Rect { x: 0, y: 40, width: 15, height: 10 }));
assert_eq!(clip(Rect { x: 100, y: 0, width: 5, height: 5 }, screen), None);
}
#[test]
fn cursor_blending() {
let (w, h) = (4, 3);
let mut pixels = vec![100; w * h * 4];
// Opaque red, half-transparent white (premultiplied), transparent.
let argb = [0xffff0000, 0x80808080, 0x00000000, 0xff00ff00];
let cursor = Cursor { left: 3, top: 2, width: 2, height: 2, argb: &argb };
blend_cursor(&mut pixels, w, h, &cursor);
// Only the top-left cursor pixel lands inside the frame, at (3, 2).
let at = |x: usize, y: usize| pixels[(y * w + x) * 4..][..3].to_vec();
assert_eq!(at(3, 2), [0, 0, 255]);
assert_eq!(at(2, 2), [100, 100, 100]);
let mut pixels = vec![100; 4];
let cursor = Cursor { left: 0, top: 0, width: 1, height: 1, argb: &argb[1..2] };
blend_cursor(&mut pixels, 1, 1, &cursor);
// 128 + 100 * 127 / 255 = 177
assert_eq!(pixels[..3], [177, 177, 177]);
}
}
+18
View File
@@ -0,0 +1,18 @@
//! Shared memory mapping for MIT-SHM captures (the only `unsafe` in X11
//! capture).
#![allow(unsafe_code)]
use std::fs::File;
use memmap2::MmapMut;
/// Map our memfd read-write.
pub(super) fn map(file: &File) -> std::io::Result<MmapMut> {
// SAFETY: memmap2 needs the file not to be truncated, and not to be
// written by others while Rust reads the mapping. The file is an
// anonymous memfd we created and never resize after mapping; the only
// other party is the X server, which writes into it while it executes a
// ShmGetImage request. The capture loop waits for that request's reply
// before reading, and issues no other request on the segment meanwhile.
unsafe { MmapMut::map_mut(file) }
}
+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());
}
}
}
+412
View File
@@ -0,0 +1,412 @@
//! 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)
// Rate control only holds the bitrate if it may skip frames.
.skip_frames(true)
// Not supported for screen content; OpenH264 would warn and drop them.
.adaptive_quantization(self.config.content == ContentHint::Motion)
.background_detection(self.config.content == ContentHint::Motion)
.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));
}
}
+63
View File
@@ -0,0 +1,63 @@
//! 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`)
//! - [`capture`]: [`ScreenCapture`] and [`AudioCapture`] with a synthetic
//! test source, X11 (feature `x11`), the Wayland ScreenCast portal and
//! PipeWire system audio (feature `pipewire`), and Windows Graphics Capture
//! plus WASAPI loopback on Windows
//! - [`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 capture;
pub mod codec;
pub mod convert;
pub mod frame;
pub mod queue;
pub use capture::{AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId};
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("capture source not found: {0:?}")]
SourceNotFound(SourceId),
#[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]);
}
}
+101
View File
@@ -0,0 +1,101 @@
//! Synthetic capture -> encoder -> decoder, through the public API.
#![cfg(feature = "vpx")]
use std::time::Duration;
use tsc_media::capture::synthetic::{BACKGROUND, RECT_COLOR, SyntheticScreen, TEXT_COLOR};
use tsc_media::{
CaptureOptions, Codec, Codecs, EncoderBackend, EncoderConfig, ScreenCapture, SourceId,
VideoFrame, convert,
};
const W: u32 = 320;
const H: u32 = 240;
const FPS: u32 = 30;
fn rgb_at(frame: &VideoFrame, x: u32, y: u32) -> [u8; 3] {
let rgba = convert::to_rgba_vec(frame).unwrap();
let i = ((y * frame.width + x) * 4) as usize;
[rgba[i], rgba[i + 1], rgba[i + 2]]
}
fn assert_close(actual: [u8; 3], expected: [u8; 3], tolerance: i32, what: &str) {
let ok = (0..3).all(|c| (i32::from(actual[c]) - i32::from(expected[c])).abs() <= tolerance);
assert!(ok, "{what}: got {actual:?}, expected {expected:?} ±{tolerance}");
}
/// Encode 30 frames of the pattern, force a keyframe midway, lower the
/// bitrate, and check every decoded frame.
fn roundtrip(codec: Codec) {
let codecs = Codecs::new();
let screen = SyntheticScreen::new(W, H);
let config = EncoderConfig { fps: FPS, bitrate_bps: 1_500_000, ..EncoderConfig::default() };
let mut encoder = codecs.new_encoder(codec, config).unwrap();
assert_eq!(encoder.backend(), EncoderBackend::Libvpx);
let mut decoder = codecs.new_decoder(codec).unwrap();
let mut worst = f64::INFINITY;
for n in 0..30 {
if n == 20 {
encoder.set_bitrate(600_000).unwrap();
}
let source = screen.frame(n, FPS);
let encoded = encoder.encode(&source, n == 15).unwrap();
assert_eq!(encoded.len(), 1, "{codec} frame {n}");
let encoded = &encoded[0];
assert_eq!(encoded.keyframe, n == 0 || n == 15, "{codec} frame {n}");
assert_eq!(encoded.pts_90khz, source.pts_90khz());
let decoded = decoder.decode(&encoded.data).unwrap().expect("a picture per frame");
assert_eq!((decoded.width, decoded.height), (W, H));
worst = worst.min(convert::psnr(&source, &decoded).unwrap());
// The rectangle is where the pattern put it, in its colour.
let (x, y, w, h) = screen.rect(n);
assert_close(rgb_at(&decoded, x + w / 2, y + h / 2), RECT_COLOR, 16, "rectangle");
assert_close(rgb_at(&decoded, W - 10, H - 10), BACKGROUND, 16, "background");
}
assert!(worst > 30.0, "{codec}: worst PSNR {worst:.1} dB");
}
#[test]
fn vp8_synthetic_roundtrip() {
roundtrip(Codec::Vp8);
}
#[test]
fn vp9_synthetic_roundtrip() {
roundtrip(Codec::Vp9);
}
/// Frames from the capture thread go through encode / decode in order.
#[tokio::test]
async fn capture_thread_to_decoder() {
let codecs = Codecs::new();
let mut screen = SyntheticScreen::new(W, H);
let options = CaptureOptions { fps: 60, cursor: false, queue: 8 };
let mut frames = screen.start(&SourceId::Synthetic, &options).await.unwrap();
let config = EncoderConfig { fps: 60, bitrate_bps: 1_000_000, ..EncoderConfig::default() };
let mut encoder = codecs.new_encoder(Codec::Vp8, config).unwrap();
let mut decoder = codecs.new_decoder(Codec::Vp8).unwrap();
let mut last_pts = None;
for _ in 0..10 {
let frame =
tokio::time::timeout(Duration::from_secs(5), frames.recv()).await.unwrap().unwrap();
let encoded = encoder.encode(&frame, false).unwrap();
for e in &encoded {
assert!(last_pts.is_none_or(|p| e.pts_90khz > p));
last_pts = Some(e.pts_90khz);
let decoded = decoder.decode(&e.data).unwrap().unwrap();
// The counter's first digit (3x5 cells of 5 px) sits at (10, 10).
let rgba = convert::to_rgba_vec(&decoded).unwrap();
let lit = (10..25u32)
.flat_map(|x| (10..35u32).map(move |y| (x, y)))
.filter(|&(x, y)| {
let p = &rgba[((y * W + x) * 4) as usize..][..3];
(0..3).all(|c| (i32::from(p[c]) - i32::from(TEXT_COLOR[c])).abs() < 60)
})
.count();
assert!(lit >= 25, "counter digit missing ({lit} lit pixels)");
}
}
screen.stop();
}
+126
View File
@@ -0,0 +1,126 @@
//! H.264 through Cisco's OpenH264, loaded at runtime.
//!
//! Without the library only the "unavailable" paths run. To test encoding
//! and decoding, point `TSC_OPENH264_LIB` at Cisco's library (for example the
//! file the ignored `download_and_roundtrip` test fetches:
//! `cargo test -p tsc-media --test openh264 -- --ignored`).
#![cfg(feature = "openh264")]
use std::path::PathBuf;
use tsc_media::capture::synthetic::{RECT_COLOR, SyntheticScreen};
use tsc_media::codec::h264::{H264Profile, OpenH264};
use tsc_media::{
Codec, Codecs, EncoderBackend, EncoderConfig, Error, VideoEncoder, VideoFrame, convert,
};
#[test]
fn missing_library_is_a_clear_error() {
let err = OpenH264::load("/nonexistent/dir/libopenh264.so").unwrap_err();
assert!(matches!(err, Error::CodecUnavailable { codec: Codec::H264, .. }), "{err}");
assert!(err.to_string().contains("OpenH264 library not found"), "{err}");
// Without a library, H.264 is neither decodable nor encodable.
let codecs = Codecs::new();
assert!(!codecs.decoders().contains(&Codec::H264));
assert!(!codecs.encoder_codecs().contains(&Codec::H264));
let err = codecs.new_decoder(Codec::H264).err().unwrap();
assert!(err.to_string().contains("OpenH264 library is not loaded"), "{err}");
assert!(codecs.new_encoder(Codec::H264, EncoderConfig::default()).is_err());
}
fn rgb_at(frame: &VideoFrame, x: u32, y: u32) -> [u8; 3] {
let rgba = convert::to_rgba_vec(frame).unwrap();
let i = ((y * frame.width + x) * 4) as usize;
[rgba[i], rgba[i + 1], rgba[i + 2]]
}
/// `profile_idc` of the first SPS in an Annex B stream.
fn sps_profile(data: &[u8]) -> Option<u8> {
let mut i = 0;
while i + 4 < data.len() {
if data[i..i + 3] == [0, 0, 1] {
if data[i + 3] & 0x1f == 7 {
return data.get(i + 4).copied();
}
i += 3;
} else {
i += 1;
}
}
None
}
fn roundtrip(library: OpenH264) {
let codecs = Codecs::new().with_openh264(library.clone());
assert_eq!(codecs.decoders().last(), Some(&Codec::H264));
assert!(codecs.encoders().contains(&(Codec::H264, EncoderBackend::OpenH264)));
let screen = SyntheticScreen::new(320, 240);
let config = EncoderConfig { fps: 30, bitrate_bps: 1_500_000, ..EncoderConfig::default() };
let mut encoder = codecs.new_encoder(Codec::H264, config.clone()).unwrap();
let mut decoder = codecs.new_decoder(Codec::H264).unwrap();
let mut decoded_frames = 0;
let mut worst = f64::INFINITY;
for n in 0..20 {
if n == 12 {
encoder.set_bitrate(800_000).unwrap();
}
let source = screen.frame(n, 30);
let encoded = encoder.encode(&source, n == 6).unwrap();
for e in &encoded {
if n == 0 {
assert!(e.keyframe);
// Constrained High: profile_idc 100.
assert_eq!(sps_profile(&e.data), Some(100));
}
if n == 6 {
assert!(e.keyframe);
}
if let Some(picture) = decoder.decode(&e.data).unwrap() {
decoded_frames += 1;
worst = worst.min(convert::psnr(&source, &picture).unwrap());
let (x, y, w, h) = screen.rect(n);
let rect = rgb_at(&picture, x + w / 2, y + h / 2);
let close =
(0..3).all(|c| (i32::from(rect[c]) - i32::from(RECT_COLOR[c])).abs() <= 16);
assert!(close, "frame {n}: rectangle {rect:?}");
}
}
}
assert!(decoded_frames >= 18, "only {decoded_frames} frames decoded");
assert!(worst > 30.0, "worst PSNR {worst:.1} dB");
// Constrained Baseline on request: profile_idc 66.
let mut baseline = library.encoder(config).unwrap();
baseline.set_profile(H264Profile::ConstrainedBaseline).unwrap();
let encoded = baseline.encode(&screen.frame(0, 30), true).unwrap();
assert_eq!(sps_profile(&encoded[0].data), Some(66));
}
#[test]
fn roundtrip_with_library_from_env() {
let Some(path) = std::env::var_os("TSC_OPENH264_LIB") else {
eprintln!("skipped: TSC_OPENH264_LIB is not set");
return;
};
roundtrip(OpenH264::load(PathBuf::from(path)).unwrap());
}
/// Downloads Cisco's binary (network access needed).
#[cfg(feature = "openh264-download")]
#[tokio::test]
#[ignore = "downloads from ciscobinary.openh264.org"]
async fn download_and_roundtrip() {
if tsc_media::codec::h264::platform_library_name().is_none() {
return;
}
let dir = std::env::temp_dir().join(format!("tsc-media-openh264-{}", std::process::id()));
let library = tsc_media::codec::h264::download_openh264(&dir).await.unwrap();
assert!(library.path().starts_with(&dir));
// A second call reuses the verified file.
let again = tsc_media::codec::h264::download_openh264(&dir).await.unwrap();
assert_eq!(again, library);
tokio::task::spawn_blocking(move || roundtrip(library)).await.unwrap();
std::fs::remove_dir_all(&dir).unwrap();
}
+221
View File
@@ -0,0 +1,221 @@
//! X11 capture against a real X server: draws known windows, captures them
//! (MIT-SHM and GetImage), checks pixels, and sends a window capture through
//! VP8 and back.
//!
//! Needs `DISPLAY` (e.g. `Xvfb :101 -screen 0 1280x720x24 & DISPLAY=:101
//! cargo test -p tsc-media --test x11_capture`); skipped without it.
#![cfg(all(target_os = "linux", feature = "x11", feature = "vpx"))]
use std::time::Duration;
use tsc_media::capture::x11::X11Capture;
use tsc_media::{
CaptureOptions, Codec, Codecs, EncoderConfig, FrameReceiver, ScreenCapture, SourceId,
VideoFrame, convert,
};
use x11rb::connection::Connection;
use x11rb::protocol::xproto::{
AtomEnum, ConnectionExt as _, CreateWindowAux, PropMode, Window, WindowClass,
};
use x11rb::rust_connection::RustConnection;
use x11rb::wrapper::ConnectionExt as _;
const TITLE: &str = "tsc-media-x11-test";
const BACKGROUND: u32 = 0x202020;
const WINDOW: u32 = 0x3060c0;
const INNER: u32 = 0xf08020;
/// Test window: position and size on the root window.
const WX: i16 = 160;
const WY: i16 = 120;
const WW: u16 = 320;
const WH: u16 = 240;
/// Inner child window, relative to the test window.
const IX: i16 = 80;
const IY: i16 = 60;
const IW: u16 = 160;
const IH: u16 = 120;
fn rgb(pixel: u32) -> [u8; 3] {
[(pixel >> 16) as u8, (pixel >> 8) as u8, pixel as u8]
}
/// Windows drawn for the test, destroyed on drop.
struct Scene {
conn: RustConnection,
root: Window,
windows: Vec<Window>,
test_window: Window,
screen: (u16, u16),
}
impl Scene {
fn create(display: &str) -> Self {
let (conn, screen_num) = RustConnection::connect(Some(display)).expect("connect");
let screen = &conn.setup().roots[screen_num];
let (root, depth, visual) = (screen.root, screen.root_depth, screen.root_visual);
let size = (screen.width_in_pixels, screen.height_in_pixels);
let mut windows = Vec::new();
let mut create = |parent, x, y, w, h, pixel, override_redirect| {
let id = conn.generate_id().unwrap();
let aux = CreateWindowAux::new()
.background_pixel(pixel)
.override_redirect(u32::from(override_redirect));
conn.create_window(
depth,
id,
parent,
x,
y,
w,
h,
0,
WindowClass::INPUT_OUTPUT,
visual,
&aux,
)
.unwrap();
windows.push(id);
id
};
// A flat background over the whole screen (not a listed window),
// then the test window with a child on top.
let background = create(root, 0, 0, size.0, size.1, BACKGROUND, true);
let test_window = create(root, WX, WY, WW, WH, WINDOW, false);
let inner = create(test_window, IX, IY, IW, IH, INNER, false);
conn.change_property8(
PropMode::REPLACE,
test_window,
AtomEnum::WM_NAME,
AtomEnum::STRING,
TITLE.as_bytes(),
)
.unwrap();
for w in [background, test_window, inner] {
conn.map_window(w).unwrap();
}
conn.sync().unwrap();
// Backgrounds are painted when the exposures are processed.
std::thread::sleep(Duration::from_millis(200));
Self { conn, root, windows, test_window, screen: size }
}
fn warp_pointer(&self, x: i16, y: i16) {
self.conn.warp_pointer(x11rb::NONE, self.root, 0, 0, 0, 0, x, y).unwrap();
self.conn.sync().unwrap();
}
}
impl Drop for Scene {
fn drop(&mut self) {
for &w in self.windows.iter().rev() {
let _ = self.conn.destroy_window(w);
}
let _ = self.conn.flush();
}
}
async fn first_frame(frames: &mut FrameReceiver<VideoFrame>) -> VideoFrame {
tokio::time::timeout(Duration::from_secs(10), frames.recv())
.await
.expect("a frame within 10 s")
.expect("capture ended")
}
fn pixel(rgba: &[u8], width: u32, x: u32, y: u32) -> [u8; 3] {
let i = ((y * width + x) * 4) as usize;
[rgba[i], rgba[i + 1], rgba[i + 2]]
}
fn assert_close(actual: [u8; 3], expected: [u8; 3], tolerance: i32, what: &str) {
let ok = (0..3).all(|c| (i32::from(actual[c]) - i32::from(expected[c])).abs() <= tolerance);
assert!(ok, "{what}: got {actual:?}, expected {expected:?} ±{tolerance}");
}
/// Capture monitor 0 and check the drawn windows' pixels exactly.
async fn check_monitor(capture: &mut X11Capture, scene: &Scene) {
let options = CaptureOptions { fps: 10, cursor: false, queue: 2 };
let mut frames = capture.start(&SourceId::Monitor(0), &options).await.unwrap();
let frame = first_frame(&mut frames).await;
capture.stop();
assert_eq!((frame.width, frame.height), (u32::from(scene.screen.0), u32::from(scene.screen.1)));
let rgba = convert::to_rgba_vec(&frame).unwrap();
let w = frame.width;
assert_eq!(pixel(&rgba, w, 20, 20), rgb(BACKGROUND), "background");
let (wx, wy) = (WX as u32, WY as u32);
assert_eq!(pixel(&rgba, w, wx + 10, wy + 10), rgb(WINDOW), "test window");
let inner = (wx + IX as u32 + 10, wy + IY as u32 + 10);
assert_eq!(pixel(&rgba, w, inner.0, inner.1), rgb(INNER), "inner window");
assert_eq!(pixel(&rgba, w, wx + WW as u32 + 5, wy), rgb(BACKGROUND), "right of the window");
}
#[tokio::test(flavor = "multi_thread")]
async fn x11_capture_end_to_end() {
let Some(display) = std::env::var("DISPLAY").ok().filter(|d| !d.is_empty()) else {
eprintln!("skipped: DISPLAY is not set");
return;
};
let scene = Scene::create(&display);
// Sources: the whole screen (or RandR monitors) and our named window.
let mut capture = X11Capture::with_display(display.clone());
let sources = capture.sources().unwrap();
let monitor = sources.iter().find(|s| s.id == SourceId::Monitor(0)).expect("monitor 0");
assert!(monitor.width > 0 && monitor.height > 0);
let window = sources
.iter()
.find(|s| s.name == TITLE)
.unwrap_or_else(|| panic!("test window not listed in {sources:?}"));
assert_eq!(window.id, SourceId::Window(scene.test_window.into()));
assert_eq!((window.width, window.height), (u32::from(WW), u32::from(WH)));
// Same pixels through MIT-SHM and through GetImage.
check_monitor(&mut capture, &scene).await;
let mut get_image = X11Capture::with_display(display.clone()).use_shm(false);
check_monitor(&mut get_image, &scene).await;
// Unknown sources fail at start.
let options = CaptureOptions { fps: 10, cursor: false, queue: 2 };
assert!(capture.start(&SourceId::Monitor(99), &options).await.is_err());
assert!(capture.start(&SourceId::Window(0x7fff_fff0), &options).await.is_err());
// Window capture -> VP8 -> decode: the colours survive.
let mut frames = capture.start(&window.id, &options).await.unwrap();
let codecs = Codecs::new();
let config = EncoderConfig { fps: 10, bitrate_bps: 1_000_000, ..EncoderConfig::default() };
let mut encoder = codecs.new_encoder(Codec::Vp8, config).unwrap();
let mut decoder = codecs.new_decoder(Codec::Vp8).unwrap();
let mut decoded = None;
let mut source = None;
for i in 0..4 {
let frame = first_frame(&mut frames).await;
assert_eq!((frame.width, frame.height), (u32::from(WW), u32::from(WH)));
let encoded = encoder.encode(&frame, false).unwrap();
assert_eq!(encoded.len(), 1);
assert_eq!(encoded[0].keyframe, i == 0);
decoded = decoder.decode(&encoded[0].data).unwrap();
source = Some(frame);
}
capture.stop();
let (decoded, source) = (decoded.expect("decoded frame"), source.unwrap());
let psnr = convert::psnr(&source, &decoded).unwrap();
assert!(psnr > 30.0, "PSNR {psnr:.1} dB");
let rgba = convert::to_rgba_vec(&decoded).unwrap();
let w = decoded.width;
assert_close(pixel(&rgba, w, 20, 20), rgb(WINDOW), 12, "decoded window corner");
let center = (IX as u32 + IW as u32 / 2, IY as u32 + IH as u32 / 2);
assert_close(pixel(&rgba, w, center.0, center.1), rgb(INNER), 12, "decoded inner window");
// The cursor is drawn when asked for.
scene.warp_pointer(40, 40);
let with_cursor = CaptureOptions { fps: 10, cursor: true, queue: 2 };
let mut frames = capture.start(&SourceId::Monitor(0), &with_cursor).await.unwrap();
let frame = first_frame(&mut frames).await;
capture.stop();
let rgba = convert::to_rgba_vec(&frame).unwrap();
let background = rgb(BACKGROUND);
let changed = (24..72)
.flat_map(|y| (24..72).map(move |x| (x, y)))
.filter(|&(x, y)| pixel(&rgba, frame.width, x, y) != background)
.count();
assert!(changed > 10, "no cursor drawn near (40, 40): {changed} pixels differ");
}
+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
+173
View File
@@ -0,0 +1,173 @@
# Media: frames, codecs and capture (`tsc-media`)
`crates/tsc-media` turns screens and system audio into frames, encodes and
decodes video, and converts pixels for rendering. It does no networking:
`tsc-stream` carries the encoded frames (`Peer::write(MediaKind::Video,
MediaTime::new(frame.pts_90khz, Frequency::NINETY_KHZ), data)`), and received
`MediaFrame`s go to `VideoDecoder::decode`.
## API overview
| Item | What it is |
|---|---|
| `VideoFrame { width, height, timestamp, data: FrameData }` | `FrameData::I420 { y, u, v }`, `Nv12 { y, uv }`, `Bgra(Plane)`, `Rgba(Plane)`; `Plane { data, stride }` |
| `AudioBuffer { samples, channels, timestamp }` | interleaved `f32`, 48 kHz |
| `convert::to_rgba(&frame, out, stride)`, `to_rgba_vec`, `to_i420`, `psnr` | BT.601 limited range (the WebRTC default). `to_rgba` writes straight into a Slint `SharedPixelBuffer<Rgba8Pixel>` (`make_mut_bytes()`, stride `width * 4`) |
| `Codec` | `Vp8`, `Vp9`, `H264`, `Av1`; `FromStr` for SDP/MIME names; `From`/`TryFrom` `str0m::format::Codec` with feature `str0m` |
| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec<EncodedFrame>`, `set_bitrate(bps)`, `codec()`, `backend()` |
| `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` |
| `VideoDecoder` | `decode(&[u8]) -> Option<VideoFrame>` (timestamp zero; the caller knows the RTP time) |
| `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads }` | resolution follows the frames; a size change restarts with a keyframe |
| `Codecs` | `new()`, `with_openh264(lib)`, `decoders()` (viewer order), `encoders()` / `encoder_codecs()` (streamer order), `new_decoder(codec)`, `new_encoder(codec, config)`, `pick_encoder(&accepted)` |
| `ScreenCapture` | `sources()`, `start(&SourceId, &CaptureOptions)` (async: the portal asks the user), `stop()` |
| `AudioCapture` | `start() -> FrameReceiver<AudioBuffer>`, `stop()` |
| `FrameReceiver<T>` | bounded queue that drops the oldest item; `recv().await`, `try_recv()`, `recv_timeout()` |
| `capture::default_screen_capture()`, `default_audio_capture()` | the backend for this session |
| `capture::synthetic::{SyntheticScreen, SineSource}` | test pattern (moving rectangle, frame counter) and sine tone |
```rust
let codecs = Codecs::new().with_openh264(OpenH264::find_in(&data_dir)?); // H.264 optional
let mut capture = tsc_media::capture::default_screen_capture()?;
let mut frames = capture.start(&SourceId::Monitor(0), &CaptureOptions::default()).await?;
let codec = codecs.pick_encoder(&viewer_codecs).unwrap();
let mut encoder = codecs.new_encoder(codec, EncoderConfig::default())?;
while let Some(frame) = frames.recv().await {
for f in encoder.encode(&frame, keyframe_requested)? {
peer.write(MediaKind::Video, MediaTime::new(f.pts_90khz, Frequency::NINETY_KHZ), f.data);
}
}
```
## Codecs
Preference: a viewer accepts VP9 > VP8 > AV1 > H.264; a streamer encodes with
hardware > VP8 (libvpx) > H.264 (OpenH264) > VP9 (libvpx, expensive in
software). `Codecs` filters both lists by what is compiled in and loaded.
| Backend | Feature | Encode | Decode | Library |
|---|---|---|---|---|
| libvpx | `vpx` (default) | VP8, VP9 | VP8, VP9 | system libvpx (1.14 tested), dynamically linked; bindings from `libvpx-native-sys` (pre-generated, no bindgen) |
| OpenH264 | `openh264` (default) | H.264 Constrained High / Baseline | H.264 | Cisco's prebuilt binary, loaded at runtime |
| dav1d | `av1` | – | AV1 | system libdav1d >= 1.3 (1.4.1 tested) |
| hardware | – | not yet | – | `codec::hw::HardwareEncoderFactory`; VA-API and Media Foundation stubs report nothing (TODO) |
libvpx settings follow libwebrtc's realtime setup: one pass CBR, no lag,
`VPX_DL_REALTIME`, error resilient, `cpu-used` 8 (VP8: fixed speed −8), keyframes
only at start and on request unless `keyframe_interval` is set, screen content
tuning (`VP8E_SET_SCREEN_CONTENT_MODE`, `VP9E_SET_TUNE_CONTENT`, static
threshold), VP9 row-mt, tiles and cyclic-refresh AQ. `set_bitrate` reconfigures
the running encoder (`vpx_codec_enc_config_set`). The C API is wrapped in
`codec/vpx/raw.rs`, one of the two modules with `unsafe` code; existing safe
wrappers either encode only or cannot change the bitrate at runtime.
The OpenH264 encoder has no safe runtime bitrate change in the `openh264`
crate, so `set_bitrate` recreates it (the next frame is an IDR). It enables
frame skipping so rate control can hold the bitrate (`encode` may then return
no frame).
### OpenH264 and Cisco's license
H.264 is patent-encumbered. Cisco pays the MPEG LA royalties for its own
OpenH264 binaries, but only when every user downloads the binary from Cisco
themselves. Therefore:
- The OpenH264 source is never compiled (the `openh264` crate is used with
`default-features = false, features = ["libloading"]`; its bundled sources
stay unused in the registry).
- `codec::h264::download_openh264(dir)` (feature `openh264-download`) fetches
`https://ciscobinary.openh264.org/<file>.bz2` for this platform (OpenH264
2.6.0), unpacks it, checks the SHA-256 against a pinned table, and stores it
in `dir`. Call it only after the user opted in.
- `OpenH264::load(path)` / `find_in(dir)` load only files whose SHA-256 matches
a known Cisco build, so no other code gets executed.
- The app must show `codec::h264::OPENH264_ATTRIBUTION` ("OpenH264 Video Codec
provided by Cisco Systems, Inc.") next to the switch that enables it and in
its About page / notices, must let the user disable it, and must not ship
the binary in its packages. Cisco's binary is BSD-2-Clause licensed; its
license text belongs in the notices shipped with the app.
Without the library, `Codecs` neither offers nor accepts H.264, and
`OpenH264::load` fails with `Error::CodecUnavailable` ("OpenH264 library not
found at ...").
## Capture
| Platform | Screen | System audio |
|---|---|---|
| any | `SyntheticScreen` | `SineSource` |
| Linux X11 (`x11`, default) | `X11Capture`: MIT-SHM 1.2 (memfd passed to the server) or GetImage; RandR 1.5 monitors; windows from `_NET_CLIENT_LIST` (root children without a WM); XFixes cursor blended in | |
| Linux Wayland (`pipewire`, default) | `PortalCapture`: xdg-desktop-portal ScreenCast via `ashpd`, frames from a PipeWire video stream | `PipeWireAudioCapture`: default sink monitor (`stream.capture.sink = true`) |
| Windows | `WindowsCapture`: Windows Graphics Capture (`windows-capture`), monitors and windows | `WasapiLoopback`: process loopback excluding our own process tree, falling back to plain loopback |
`default_screen_capture()` picks the portal when `WAYLAND_DISPLAY` is set (or
`XDG_SESSION_TYPE=wayland`), X11 when `DISPLAY` is set, WGC on Windows.
Notes:
- X11 needs a 24/32-bit TrueColor visual (BGRx in memory). Window capture
reads the window itself, clipped to the screen; without a compositor, parts
covered by other windows may be stale. MIT-SHM needs a local server with
MIT-SHM 1.2; otherwise GetImage is used. The only `unsafe` here is mapping
our memfd (`capture/x11/shm.rs`).
- Portal: `start` needs a tokio runtime (zbus runs on it) and may show the
desktop's picker. Choices persist with `PersistMode::ExplicitlyRevoked`: store
`PortalCapture::restore_token()` (e.g. in `tsc-store` settings) and pass it to
`PortalCapture::with_restore_token` next time. The cursor is embedded when
the portal supports it. Only shared-memory buffers (BGRx/BGRA/RGBx/RGBA) are
negotiated; DMA-BUF import is a TODO. Without a session bus or portal,
`start` returns `Error::CaptureUnavailable`; a cancelled dialog returns
`Error::Cancelled`.
- PipeWire system audio captures everything the default sink plays, including
our own playback (TeamSpeak voices): PipeWire has no "all but this process"
monitor. Excluding our nodes needs a private null sink with links from every
other application's output (via the registry); TODO. Until then, play voices
on another sink or accept that viewers hear them. Without a PipeWire daemon,
`start` returns `Error::CaptureUnavailable`.
- Windows process loopback needs Windows 10 2004 or later.
## Build requirements
Linux (Debian/Ubuntu packages): `libvpx-dev` (feature `vpx`),
`libpipewire-0.3-dev libspa-0.2-dev libclang-dev` (feature `pipewire`; the
PipeWire bindings run bindgen), `pkg-config`, and `libdav1d-dev` for
`--features av1`. X11 capture is pure Rust (x11rb) and needs no packages.
Tests of X11 capture need an X server: `xvfb`, run with `xvfb-run -a cargo
test -p tsc-media` (skipped without `DISPLAY`).
Windows: libvpx is not found through pkg-config there. Install it (e.g.
`vcpkg install libvpx:x64-windows`) and set `VPX_LIB_DIR`, `VPX_INCLUDE_DIR`
and `VPX_VERSION`, or build without the `vpx` feature. The Windows capture
code is type-checked on Linux (`cargo clippy -p tsc-media --target
x86_64-pc-windows-gnu --no-default-features --features openh264`) but has not
run on Windows yet.
## Licenses
| Component | License | How it is used |
|---|---|---|
| libvpx | BSD-3-Clause | system library, dynamic |
| `libvpx-native-sys` | MPL-2.0 | unmodified bindings |
| `yuv` (yuvutils-rs) | BSD-3-Clause OR Apache-2.0 | |
| `openh264` / `openh264-sys2` | BSD-2-Clause | bindings, `libloading` only |
| Cisco OpenH264 binary | BSD-2-Clause + Cisco's royalty coverage | downloaded by the user, see above |
| `dav1d` crate / libdav1d | MIT / BSD-2-Clause | optional, system library |
| `x11rb`, `memmap2`, `rustix` | MIT OR Apache-2.0 (rustix also Apache-2.0 WITH LLVM-exception) | |
| `ashpd`, `pipewire`, `libspa` / libpipewire | MIT | libpipewire is dynamic |
| `windows-capture`, `wasapi`, `windows` | MIT (`windows`: MIT OR Apache-2.0) | Windows only |
| `bzip2` / `libbz2-rs-sys` | MIT OR Apache-2.0 / bzip2-1.0.6 | unpacks the OpenH264 download; `bzip2-1.0.6` is allowed in `deny.toml` |
## Verification status
| What | How | Status |
|---|---|---|
| Frame validation, YUV ↔ RGB (values, NV12, odd sizes, strides) | unit tests | tested |
| VP8 / VP9 encode → decode (PSNR > 30 dB, rectangle colour, forced keyframes, bitrate change, resolution change) | unit tests, `tests/codec_roundtrip.rs` | tested |
| H.264 with Cisco's 2.6.0 library (PSNR, Constrained High `profile_idc` 100, Baseline 66) | `tests/openh264.rs` with `TSC_OPENH264_LIB` | tested locally, skipped without the library |
| OpenH264 download, SHA-256 check, reuse | `tests/openh264.rs -- --ignored` | tested locally (network) |
| H.264 library missing / unknown file | unit + integration tests | tested |
| AV1 decoder construction, garbage input | unit test (`--features av1`) | tested; no AV1 stream decoded (no encoder available) |
| X11 capture (MIT-SHM and GetImage), sources, window capture → VP8 → decode, cursor | `tests/x11_capture.rs` under Xvfb | tested |
| Portal / PipeWire error paths (no bus, bus without portal, no daemon) | unit tests, manual probe | tested |
| Portal capture, PipeWire video and audio streams | – | compiles only (no portal or PipeWire daemon here) |
| Windows Graphics Capture, WASAPI | – | type-checked for `x86_64-pc-windows-gnu` only |
| Hardware encoders | – | stubs |