Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(capture): give the Linux helper a hardware H.264 encoder

Etienne Lescotd07b8e973c04
diff --git a/electron/native/pipewire-capture/Cargo.lock b/electron/native/pipewire-capture/Cargo.lock
index fccd2359d..f8fa27a58 100644
--- a/electron/native/pipewire-capture/Cargo.lock
+++ b/electron/native/pipewire-capture/Cargo.lock
@@ -8,6 +8,15 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "aho-corasick"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "ashpd"
version = "0.9.3"
@@ -197,6 +206,26 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+[[package]]
+name = "bindgen"
+version = "0.70.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f"
+dependencies = [
+ "bitflags 2.13.1",
+ "cexpr",
+ "clang-sys",
+ "itertools",
+ "log",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "rustc-hash",
+ "shlex 1.3.0",
+ "syn 2.0.119",
+]
+
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -238,7 +267,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"
dependencies = [
"find-msvc-tools",
- "shlex",
+ "shlex 2.0.1",
+]
+
+[[package]]
+name = "cexpr"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
+dependencies = [
+ "nom",
]
[[package]]
@@ -253,6 +291,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+[[package]]
+name = "clang-sys"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
+dependencies = [
+ "glob",
+ "libc",
+ "libloading",
+]
+
[[package]]
name = "concurrent-queue"
version = "2.5.0"
@@ -317,6 +366,12 @@ dependencies = [
"syn 3.0.3",
]
+[[package]]
+name = "either"
+version = "1.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"
+
[[package]]
name = "endi"
version = "1.1.1"
@@ -525,6 +580,12 @@ dependencies = [
"r-efi",
]
+[[package]]
+name = "glob"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
+
[[package]]
name = "hashbrown"
version = "0.17.1"
@@ -656,6 +717,15 @@ dependencies = [
"hashbrown",
]
+[[package]]
+name = "itertools"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itoa"
version = "1.0.18"
@@ -668,6 +738,16 @@ version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+[[package]]
+name = "libloading"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
+dependencies = [
+ "cfg-if",
+ "windows-link",
+]
+
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -680,6 +760,12 @@ version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
+[[package]]
+name = "log"
+version = "0.4.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -695,6 +781,12 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -718,6 +810,16 @@ dependencies = [
"memoffset",
]
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -730,6 +832,7 @@ version = "0.0.0"
dependencies = [
"ashpd",
"base64",
+ "bindgen",
"cc",
"png",
"pollster",
@@ -828,6 +931,16 @@ dependencies = [
"zerocopy",
]
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn 2.0.119",
+]
+
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
@@ -891,6 +1004,41 @@ dependencies = [
"getrandom 0.2.17",
]
+[[package]]
+name = "regex"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "rustc-hash"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
+
[[package]]
name = "rustix"
version = "1.1.4"
@@ -980,6 +1128,12 @@ dependencies = [
"digest",
]
+[[package]]
+name = "shlex"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+
[[package]]
name = "shlex"
version = "2.0.1"
diff --git a/electron/native/pipewire-capture/Cargo.toml b/electron/native/pipewire-capture/Cargo.toml
index d412fe1ab..604da16af 100644
--- a/electron/native/pipewire-capture/Cargo.toml
+++ b/electron/native/pipewire-capture/Cargo.toml
@@ -6,12 +6,19 @@
# the app links, sharing wgpu/ffmpeg/windows dependencies and a French comment
# convention. This is not that. It is a sidecar executable spawned over stdio,
# exactly like `electron/native/screencapturekit/` (Swift) and
-# `electron/native/wgc-capture/` (C++), and it shares nothing with the
-# compositor — no wgpu, no ffmpeg, no napi. Putting it in the compositor
-# workspace would drag its dependency tree (ashpd/zbus, cc, png) into every
+# `electron/native/wgc-capture/` (C++). Putting it in the compositor workspace
+# would drag its dependency tree (ashpd/zbus, cc, png) into every
# `cargo build -p compositor-view-napi` resolution for no benefit, and would put
# a Linux-only binary behind a workspace whose default member is a Windows POC.
#
+# IT DOES SHARE FFMPEG — and only ffmpeg. Stage 2 encodes H.264 here, against the
+# same vendored tree the compositor uses (crates/thirdparty/). The crucial
+# difference from the addon is that this is a separate PROCESS: it never enters
+# Electron's address space, so the flat-namespace collision with Chromium's
+# `libffmpeg.so` (see scripts/build-linux-compositor-addon.mjs) does not apply
+# and no symbol prefixing is needed. Linking it normally is safe HERE and only
+# here.
+#
# It is therefore a standalone package. `[workspace]` below makes that explicit
# so that a future root Cargo.toml cannot silently adopt it.
@@ -46,6 +53,10 @@ sha2 = "0.10"
[build-dependencies]
cc = "1"
+# Same generator the compositor uses on its copy of these headers. Hand-writing
+# AVCodecContext/AVFrame layouts is the one thing guaranteed to break silently on
+# an ffmpeg bump, so the layouts are always generated, never typed out.
+bindgen = "0.70"
[profile.release]
opt-level = 2
diff --git a/electron/native/pipewire-capture/build.rs b/electron/native/pipewire-capture/build.rs
index 2b850214a..30f572aa6 100644
--- a/electron/native/pipewire-capture/build.rs
+++ b/electron/native/pipewire-capture/build.rs
@@ -1,15 +1,28 @@
-// Compiles csrc/pw_shim.c against the vendored PipeWire headers.
+// Two build inputs, with deliberately different linkage strategies.
//
-// There is deliberately no pkg-config probe and no `println!("cargo:rustc-link-lib=…")`:
-// the shim resolves every libpipewire symbol with dlsym at runtime, so the only
-// build input is a C compiler and the header tree under vendor/. That is what
-// makes this crate buildable on a machine with no libpipewire-0.3-dev, which is
-// most machines — Ubuntu ships only the runtime .so.0.
+// PIPEWIRE is compiled from csrc/pw_shim.c against the vendored headers and NOT
+// linked: the shim resolves every libpipewire symbol with dlsym at runtime, so
+// the only build requirement is a C compiler. That is what makes this crate
+// buildable on a machine with no libpipewire-0.3-dev, which is most machines —
+// Ubuntu ships only the runtime .so.0.
+//
+// FFMPEG is linked normally against the tree the app already vendors for the
+// compositor. See Cargo.toml for why that is safe here and nowhere else: this is
+// a separate process, so Chromium's `libffmpeg.so` is not in its address space
+// and the symbol collision that forces the addon's `osff_` renaming cannot
+// happen. RUNPATH points at $ORIGIN so the packaged binary finds the .so files
+// staged beside it, and at the vendored lib dir so a dev build runs from the
+// repo without LD_LIBRARY_PATH.
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
fn main() {
let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
+ build_pipewire_shim(&root);
+ link_ffmpeg(&root);
+}
+
+fn build_pipewire_shim(root: &Path) {
let vendor = root.join("vendor/pipewire-1.0.5/include");
let shim = root.join("csrc/pw_shim.c");
@@ -34,3 +47,124 @@ fn main() {
// dlopen/dlsym.
println!("cargo:rustc-link-lib=dl");
}
+
+/// Extra `-I` flags so clang can find the freestanding headers it normally ships
+/// with itself (`stddef.h`, `limits.h`, `stdint.h`).
+///
+/// Ubuntu splits libclang: `libclang.so.1` comes from the runtime package while
+/// the builtin header directory comes from `libclang-N-dev`. With only the
+/// former installed — the common case — parsing any real header fails on
+/// `/usr/include/limits.h: 'limits.h' file not found`, because glibc's copy
+/// `#include_next`s the compiler's and there is none. gcc's copies are
+/// interchangeable for this purpose, so point clang at those instead of making
+/// every contributor install a second toolchain. Mirrors `bindgenClangArgs()` in
+/// scripts/build-linux-compositor-addon.mjs, but lives here so that a bare
+/// `cargo build` in this directory works too.
+fn freestanding_header_args() -> Vec<String> {
+ if let Ok(extra) = std::env::var("BINDGEN_EXTRA_CLANG_ARGS") {
+ // Already configured by the caller; bindgen picks that up on its own.
+ if !extra.trim().is_empty() {
+ return Vec::new();
+ }
+ }
+ let gcc_root = Path::new("/usr/lib/gcc/x86_64-linux-gnu");
+ let Ok(entries) = std::fs::read_dir(gcc_root) else {
+ return Vec::new();
+ };
+ let mut dirs: Vec<PathBuf> = entries
+ .filter_map(|entry| entry.ok())
+ .map(|entry| entry.path().join("include"))
+ .filter(|dir| dir.join("limits.h").is_file() && dir.join("stddef.h").is_file())
+ .collect();
+ // Highest gcc version first, so a machine with several picks the newest.
+ dirs.sort();
+ dirs.reverse();
+ dirs.into_iter()
+ .take(1)
+ .map(|dir| format!("-I{}", dir.display()))
+ .collect()
+}
+
+/// The vendored ffmpeg tree, five directories up from this crate. `FFMPEG_DIR`
+/// overrides it for CI or a cross build.
+fn ffmpeg_dir(root: &Path) -> PathBuf {
+ if let Some(dir) = std::env::var_os("FFMPEG_DIR") {
+ return PathBuf::from(dir);
+ }
+ root.join("../../../crates/thirdparty/ffmpeg-linux64-lgpl-shared")
+}
+
+fn link_ffmpeg(root: &Path) {
+ let dir = ffmpeg_dir(root);
+ let include = dir.join("include");
+ let lib = dir.join("lib");
+
+ assert!(
+ include.join("libavcodec/avcodec.h").is_file(),
+ "vendored ffmpeg headers are missing at {} — run `npm run fetch:ffmpeg` or set FFMPEG_DIR",
+ include.display()
+ );
+
+ println!("cargo:rustc-link-search=native={}", lib.display());
+ for name in ["avcodec", "avformat", "avutil", "swscale", "swresample"] {
+ println!("cargo:rustc-link-lib={name}");
+ }
+ // `-rpath` twice: `$ORIGIN` for the packaged layout (the .so files sit next
+ // to the binary in electron/native/bin/linux-x64), the absolute vendored
+ // path so `cargo run` works straight out of the repo. `--disable-new-dtags`
+ // is what makes these RUNPATH entries apply to the transitive ffmpeg libs
+ // too; with the default DT_RUNPATH they would not.
+ println!("cargo:rustc-link-arg=-Wl,--disable-new-dtags");
+ println!("cargo:rustc-link-arg=-Wl,-rpath,$ORIGIN");
+ println!("cargo:rustc-link-arg=-Wl,-rpath,{}", lib.display());
+
+ let mut builder = bindgen::Builder::default();
+ for arg in freestanding_header_args() {
+ builder = builder.clang_arg(arg);
+ }
+ let bindings = builder
+ .header_contents(
+ "ffmpeg.h",
+ r#"
+ #include <libavcodec/avcodec.h>
+ #include <libavformat/avformat.h>
+ #include <libavutil/avutil.h>
+ #include <libavutil/hwcontext.h>
+ #include <libavutil/imgutils.h>
+ #include <libavutil/opt.h>
+ #include <libswresample/swresample.h>
+ #include <libswscale/swscale.h>
+ "#,
+ )
+ .clang_arg(format!("-I{}", include.display()))
+ // An allowlist rather than the whole tree: it keeps the generated file
+ // to what this helper calls, and keeps `cargo build` from regenerating
+ // thousands of items nothing references.
+ .allowlist_function("av_.*")
+ .allowlist_function("avcodec_.*")
+ .allowlist_function("avformat_.*")
+ .allowlist_function("avio_.*")
+ .allowlist_function("sws_.*")
+ .allowlist_function("swr_.*")
+ .allowlist_type("AV.*")
+ .allowlist_type("Sws.*")
+ .allowlist_type("SwrContext")
+ .allowlist_var("AV_.*")
+ .allowlist_var("AVERROR.*")
+ .allowlist_var("FF_.*")
+ .allowlist_var("SWS_.*")
+ .derive_default(true)
+ .prepend_enum_name(false)
+ .layout_tests(false)
+ // ffmpeg's headers are riddled with doc comments that are not valid
+ // rustdoc; without this every build emits hundreds of warnings.
+ .generate_comments(false)
+ .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
+ .generate()
+ .expect("bindgen failed on the ffmpeg headers");
+
+ let out = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR")).join("ffmpeg_sys.rs");
+ bindings.write_to_file(&out).expect("could not write ffmpeg bindings");
+
+ println!("cargo:rerun-if-env-changed=FFMPEG_DIR");
+}
diff --git a/electron/native/pipewire-capture/src/bitmap.rs b/electron/native/pipewire-capture/src/bitmap.rs
index ea8a10791..f7d6e43da 100644
--- a/electron/native/pipewire-capture/src/bitmap.rs
+++ b/electron/native/pipewire-capture/src/bitmap.rs
@@ -5,12 +5,12 @@
//! `data:image/png` string, keyed by the SHA-256 of the PNG bytes so the same
//! shape is only ever serialised once.
//!
-//! UNVERIFIED: Wayland cursor buffers are conventionally PREMULTIPLIED alpha,
-//! and PNG expects straight alpha. No sprite has been observed on real hardware
-//! yet (Stage 1's `debug` instrumentation exists to find out whether GNOME even
-//! sends one), so the channels are copied through unchanged rather than
-//! un-premultiplied on a guess. If sprites come back with dark fringes on their
-//! antialiased edges, that is the bug, and the fix belongs here.
+//! VERIFIED PREMULTIPLIED. Wayland cursor buffers carry premultiplied alpha and
+//! PNG expects straight alpha, so the channels have to be divided back out. This
+//! was a guess in Stage 1 and is now a measurement: a captured GNOME sprite had
+//! 126 semi-transparent pixels and not one where any colour channel exceeded its
+//! own alpha, which is only true of premultiplied data. Copying the channels
+//! through unchanged darkened every antialiased edge.
use base64::Engine;
use sha2::{Digest, Sha256};
@@ -53,6 +53,23 @@ fn channel_order(constants: &Constants, format: u32) -> Option<[usize; 4]> {
.map(|(_, order)| *order)
}
+/// Divides a premultiplied colour channel back out by its alpha.
+///
+/// `+ alpha / 2` rounds to nearest instead of truncating, which matters at the
+/// low alphas that make up an antialiased edge: at a=8 the truncating form loses
+/// up to 6% of the recovered channel. The `min` is not defensive noise — a
+/// producer that sends c > a (or a colour-keyed sprite) would otherwise overflow
+/// past 255 and wrap when cast back to u8.
+fn unpremultiply(channel: u8, alpha: u8) -> u8 {
+ if alpha == 0 {
+ // Fully transparent: the colour carries no information, and every value
+ // is equally "correct". Zero keeps identical sprites hashing alike.
+ return 0;
+ }
+ let alpha = u16::from(alpha);
+ (((u16::from(channel) * 255 + alpha / 2) / alpha).min(255)) as u8
+}
+
/// True when the format has no alpha channel, so the 4th byte is padding and
/// must be replaced by opaque rather than copied.
fn is_opaque(constants: &Constants, format: u32) -> bool {
@@ -103,10 +120,20 @@ pub fn encode(constants: &Constants, bitmap: &CursorBitmap) -> Result<EncodedCur
for row in 0..height as usize {
let line = &bitmap.pixels[row * stride..row * stride + row_bytes];
for pixel in line.chunks_exact(4) {
- rgba.push(pixel[order[0]]);
- rgba.push(pixel[order[1]]);
- rgba.push(pixel[order[2]]);
- rgba.push(if opaque { 0xff } else { pixel[order[3]] });
+ // An opaque format's 4th byte is padding, so there is nothing to
+ // divide by and the channels are already straight.
+ if opaque {
+ rgba.push(pixel[order[0]]);
+ rgba.push(pixel[order[1]]);
+ rgba.push(pixel[order[2]]);
+ rgba.push(0xff);
+ continue;
+ }
+ let alpha = pixel[order[3]];
+ rgba.push(unpremultiply(pixel[order[0]], alpha));
+ rgba.push(unpremultiply(pixel[order[1]], alpha));
+ rgba.push(unpremultiply(pixel[order[2]], alpha));
+ rgba.push(alpha);
}
}
@@ -204,22 +231,64 @@ mod tests {
#[test]
fn bgra_channels_are_reordered_to_rgba() {
let c = constants();
- // One pixel: B=1, G=2, R=3, A=4.
- let encoded = encode(&c, &bitmap(c.video_format_bgra, 1, 1, 4, vec![1, 2, 3, 4]))
+ // Opaque on purpose: un-premultiplying by a=255 is the identity, so this
+ // test stays about channel ORDER and nothing else.
+ let encoded = encode(&c, &bitmap(c.video_format_bgra, 1, 1, 4, vec![1, 2, 3, 0xff]))
.expect("encode");
let (info, pixels) = decode(&encoded.image_data_url);
assert_eq!((info.width, info.height), (1, 1));
- assert_eq!(&pixels[..4], &[3, 2, 1, 4]);
+ assert_eq!(&pixels[..4], &[3, 2, 1, 0xff]);
}
#[test]
fn argb_channels_are_reordered_to_rgba() {
let c = constants();
- // One pixel: A=9, R=1, G=2, B=3.
- let encoded = encode(&c, &bitmap(c.video_format_argb, 1, 1, 4, vec![9, 1, 2, 3]))
+ // One pixel: A=255, R=1, G=2, B=3.
+ let encoded = encode(&c, &bitmap(c.video_format_argb, 1, 1, 4, vec![0xff, 1, 2, 3]))
+ .expect("encode");
+ let (_, pixels) = decode(&encoded.image_data_url);
+ assert_eq!(&pixels[..4], &[1, 2, 3, 0xff]);
+ }
+
+ #[test]
+ fn premultiplied_channels_are_divided_back_out() {
+ let c = constants();
+ // A half-transparent white pixel arrives premultiplied as 128/128/128
+ // at a=128. Straight alpha puts the channels back at ~255.
+ let encoded = encode(&c, &bitmap(c.video_format_bgra, 1, 1, 4, vec![128, 128, 128, 128]))
+ .expect("encode");
+ let (_, pixels) = decode(&encoded.image_data_url);
+ assert_eq!(&pixels[..4], &[255, 255, 255, 128]);
+ }
+
+ #[test]
+ fn fully_transparent_pixels_keep_no_colour() {
+ let c = constants();
+ // a=0 leaves the colour undefined; zeroing it is what makes two visually
+ // identical sprites hash to the same asset id.
+ let encoded = encode(&c, &bitmap(c.video_format_bgra, 1, 1, 4, vec![9, 9, 9, 0]))
.expect("encode");
let (_, pixels) = decode(&encoded.image_data_url);
- assert_eq!(&pixels[..4], &[1, 2, 3, 9]);
+ assert_eq!(&pixels[..4], &[0, 0, 0, 0]);
+ }
+
+ #[test]
+ fn unpremultiply_cannot_exceed_opaque() {
+ // A producer that sends c > a would wrap past 255 without the clamp.
+ assert_eq!(unpremultiply(200, 100), 255);
+ assert_eq!(unpremultiply(0, 0), 0);
+ assert_eq!(unpremultiply(37, 255), 37);
+ }
+
+ #[test]
+ fn opaque_formats_are_not_divided() {
+ let c = constants();
+ // BGRx: the 4th byte is padding, not alpha. Dividing by it — or by the
+ // 0xff we substitute — must leave the colours untouched.
+ let encoded = encode(&c, &bitmap(c.video_format_bgrx, 1, 1, 4, vec![10, 20, 30, 0]))
+ .expect("encode");
+ let (_, pixels) = decode(&encoded.image_data_url);
+ assert_eq!(&pixels[..4], &[30, 20, 10, 0xff]);
}
#[test]
@@ -234,12 +303,15 @@ mod tests {
#[test]
fn row_padding_is_skipped() {
let c = constants();
- // 1px wide, 2 rows, stride 8: bytes 4..8 and 12..16 are padding.
- let pixels = vec![1, 2, 3, 4, 0xaa, 0xaa, 0xaa, 0xaa, 5, 6, 7, 8, 0xbb, 0xbb, 0xbb, 0xbb];
+ // 1px wide, 2 rows, stride 8: bytes 4..8 and 12..16 are padding. Both
+ // pixels are opaque so the assertion is about stride, not alpha.
+ let pixels = vec![
+ 1, 2, 3, 0xff, 0xaa, 0xaa, 0xaa, 0xaa, 5, 6, 7, 0xff, 0xbb, 0xbb, 0xbb, 0xbb,
+ ];
let encoded =
encode(&c, &bitmap(c.video_format_bgra, 1, 2, 8, pixels)).expect("encode");
let (_, decoded) = decode(&encoded.image_data_url);
- assert_eq!(&decoded[..8], &[3, 2, 1, 4, 7, 6, 5, 8]);
+ assert_eq!(&decoded[..8], &[3, 2, 1, 0xff, 7, 6, 5, 0xff]);
}
#[test]
diff --git a/electron/native/pipewire-capture/src/encoder.rs b/electron/native/pipewire-capture/src/encoder.rs
new file mode 100644
index 000000000..3db307ba8
--- /dev/null
+++ b/electron/native/pipewire-capture/src/encoder.rs
@@ -0,0 +1,993 @@
+//! H.264 encoding and MP4 muxing for the captured screen.
+//!
+//! THE LADDER. Three backends are tried in order and the first one that actually
+//! opens wins. "Actually opens" is the whole point: `avcodec_find_encoder_by_name`
+//! succeeds for every encoder compiled into the library, including ones this
+//! machine's GPU cannot run, so the only honest capability probe is to open the
+//! encoder with the real parameters and see what happens.
+//!
+//! 1. VAAPI — the broadest hardware path on Linux (AMD, Intel, and NVIDIA
+//! through nvidia-vaapi-driver).
+//! 2. Vulkan — VK_KHR_video_encode_queue. Newer, and on RADV it needs
+//! `RADV_PERFTEST=video_encode`; see [`prepare_environment`].
+//! 3. libopenh264 — software. Always available, always last.
+//!
+//! WHY VAAPI IS GUARDED BY A dlsym. The vendored ffmpeg 8.1 calls `vaMapBuffer2`,
+//! which libva only grew in 2.22. On a system with an older libva (Ubuntu 24.04
+//! ships 2.20) the call goes through an implib-generated trampoline that does not
+//! return an error — it calls `assert(0)` and the process dumps core. A probe
+//! that crashes the helper is worse than no probe, so the symbol is checked
+//! before libavutil is ever allowed to touch VA-API.
+
+use std::ffi::{CStr, CString};
+use std::path::Path;
+use std::ptr;
+
+use crate::ffmpeg as ff;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Backend {
+ Vaapi,
+ Vulkan,
+ Software,
+}
+
+impl Backend {
+ /// The name the app reports and the tests match on. Kept in the same
+ /// vocabulary as the Windows helper's `encoder-selection` event.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Vaapi => "vaapi",
+ Self::Vulkan => "vulkan",
+ Self::Software => "software",
+ }
+ }
+
+ fn codec_name(self) -> &'static CStr {
+ match self {
+ Self::Vaapi => c"h264_vaapi",
+ Self::Vulkan => c"h264_vulkan",
+ Self::Software => c"libopenh264",
+ }
+ }
+
+ fn hw_device_type(self) -> Option<ff::AVHWDeviceType> {
+ match self {
+ Self::Vaapi => Some(ff::AV_HWDEVICE_TYPE_VAAPI),
+ Self::Vulkan => Some(ff::AV_HWDEVICE_TYPE_VULKAN),
+ Self::Software => None,
+ }
+ }
+
+ /// The pixel format the codec context takes. Hardware encoders take an
+ /// opaque handle; the real pixels live in [`Self::upload_format`].
+ fn codec_pixel_format(self) -> ff::AVPixelFormat {
+ match self {
+ Self::Vaapi => ff::AV_PIX_FMT_VAAPI,
+ Self::Vulkan => ff::AV_PIX_FMT_VULKAN,
+ Self::Software => ff::AV_PIX_FMT_YUV420P,
+ }
+ }
+
+ /// What swscale converts the captured RGB into.
+ fn upload_format(self) -> ff::AVPixelFormat {
+ match self {
+ // Every VCN/QuickSync/NVENC block wants NV12; YUV420P would force
+ // ffmpeg into an extra internal conversion on upload.
+ Self::Vaapi | Self::Vulkan => ff::AV_PIX_FMT_NV12,
+ Self::Software => ff::AV_PIX_FMT_YUV420P,
+ }
+ }
+}
+
+/// Order of preference. Public so the probe can be driven from a test or from
+/// `OPENSCREEN_LINUX_ENCODER` without duplicating the list.
+pub const LADDER: [Backend; 3] = [Backend::Vaapi, Backend::Vulkan, Backend::Software];
+
+/// Must run before anything creates a Vulkan instance — which, in this process,
+/// means before the first `av_hwdevice_ctx_create`.
+///
+/// Mesa gates RADV's video encode queues behind a perf-test flag; without it
+/// `h264_vulkan` fails with "Device does not support the VK_KHR_video_encode_queue
+/// extension" on hardware that supports it perfectly well. Setting the variable
+/// only affects this process, and drivers that do not know it ignore it. An
+/// existing value is left alone so a developer can experiment.
+pub fn prepare_environment() {
+ const KEY: &str = "RADV_PERFTEST";
+ match std::env::var(KEY) {
+ Ok(existing) if existing.split(',').any(|flag| flag.trim() == "video_encode") => {}
+ Ok(existing) if !existing.is_empty() => {
+ std::env::set_var(KEY, format!("{existing},video_encode"));
+ }
+ _ => std::env::set_var(KEY, "video_encode"),
+ }
+}
+
+/// True when libva is new enough that libavutil's VA-API code will not abort.
+///
+/// See the module header. This deliberately checks the SYMBOL rather than a
+/// version string: the version macro reflects the headers ffmpeg was built
+/// against, and what matters is what is loadable here and now.
+fn vaapi_is_safe_to_probe() -> bool {
+ // SAFETY: dlopen/dlsym with a literal name; every pointer is checked before
+ // use and the handle is closed on both paths.
+ unsafe {
+ let handle = dlopen(c"libva.so.2".as_ptr(), RTLD_LAZY | RTLD_LOCAL);
+ if handle.is_null() {
+ return false;
+ }
+ let symbol = dlsym(handle, c"vaMapBuffer2".as_ptr());
+ dlclose(handle);
+ !symbol.is_null()
+ }
+}
+
+const RTLD_LAZY: i32 = 1;
+const RTLD_LOCAL: i32 = 0;
+
+extern "C" {
+ fn dlopen(filename: *const std::ffi::c_char, flags: i32) -> *mut std::ffi::c_void;
+ fn dlsym(
+ handle: *mut std::ffi::c_void,
+ symbol: *const std::ffi::c_char,
+ ) -> *mut std::ffi::c_void;
+ fn dlclose(handle: *mut std::ffi::c_void) -> i32;
+}
+
+pub struct VideoParams {
+ pub width: i32,
+ pub height: i32,
+ pub fps: i32,
+ pub bitrate: i64,
+}
+
+/// Where the per-frame time actually goes.
+///
+/// Not debug scaffolding: the capture loop has a hard real-time budget (16.7 ms
+/// at 60 fps) and when it is missed the useful question is always *which* of the
+/// three stages missed it. Reported on `capture-stopped` so a slow recording on
+/// a user's machine is diagnosable without a rebuild. Three `Instant::now()`
+/// calls per frame is about 60 ns against a budget four orders of magnitude
+/// larger.
+#[derive(Debug, Default, Clone, Copy)]
+pub struct EncodeStats {
+ pub frames: u64,
+ /// swscale: captured RGB → NV12/YUV420P in system memory.
+ pub convert_ns: u128,
+ /// `av_hwframe_transfer_data`: system memory → GPU. Zero for software.
+ pub upload_ns: u128,
+ /// `avcodec_send_frame` plus draining whatever packets came back.
+ pub encode_ns: u128,
+}
+
+impl EncodeStats {
+ fn mean_ms(total_ns: u128, frames: u64) -> f64 {
+ if frames == 0 {
+ return 0.0;
+ }
+ total_ns as f64 / frames as f64 / 1_000_000.0
+ }
+
+ pub fn convert_ms(&self) -> f64 {
+ Self::mean_ms(self.convert_ns, self.frames)
+ }
+
+ pub fn upload_ms(&self) -> f64 {
+ Self::mean_ms(self.upload_ns, self.frames)
+ }
+
+ pub fn encode_ms(&self) -> f64 {
+ Self::mean_ms(self.encode_ns, self.frames)
+ }
+}
+
+/// Everything the encoder owns, freed in reverse order of acquisition by `Drop`.
+pub struct VideoEncoder {
+ backend: Backend,
+ codec_ctx: *mut ff::AVCodecContext,
+ hw_device: *mut ff::AVBufferRef,
+ hw_frames: *mut ff::AVBufferRef,
+ /// NV12/YUV420P staging in system memory; the target of swscale and the
+ /// source of the hardware upload.
+ sw_frame: *mut ff::AVFrame,
+ /// The GPU-side frame handed to a hardware encoder. Null for software.
+ hw_frame: *mut ff::AVFrame,
+ sws: *mut ff::SwsContext,
+ sws_src_format: ff::AVPixelFormat,
+ packet: *mut ff::AVPacket,
+ params: VideoParams,
+ stats: EncodeStats,
+ /// What libswscale reported back after `sws_init_context`, not what we asked
+ /// for. Requesting threads and silently getting one is indistinguishable
+ /// from threading not helping.
+ sws_threads: i64,
+}
+
+impl VideoEncoder {
+ /// Walks [`LADDER`] and returns the first backend that opens, or every
+ /// backend's error if none does.
+ ///
+ /// `forced` short-circuits the walk — it is how the verification step
+ /// compares backends on the same machine, and how a user works around a
+ /// driver that opens successfully and then produces garbage.
+ pub fn open(
+ params: VideoParams,
+ forced: Option<Backend>,
+ mut on_attempt: impl FnMut(Backend, &str),
+ ) -> Result<Self, String> {
+ prepare_environment();
+
+ let candidates: Vec<Backend> = match forced {
+ Some(backend) => vec![backend],
+ None => LADDER.to_vec(),
+ };
+
+ let mut failures = Vec::new();
+ for backend in candidates {
+ if backend == Backend::Vaapi && forced.is_none() && !vaapi_is_safe_to_probe() {
+ let reason = "libva.so.2 does not export vaMapBuffer2, so this ffmpeg build \
+ would abort inside VA-API rather than fail cleanly"
+ .to_owned();
+ on_attempt(backend, &reason);
+ failures.push(format!("{}: {reason}", backend.as_str()));
+ continue;
+ }
+ match Self::open_backend(backend, &params) {
+ Ok(encoder) => return Ok(encoder),
+ Err(error) => {
+ on_attempt(backend, &error);
+ failures.push(format!("{}: {error}", backend.as_str()));
+ }
+ }
+ }
+
+ Err(format!(
+ "no H.264 encoder could be opened at {}x{}. Attempts: {}",
+ params.width,
+ params.height,
+ failures.join(" | ")
+ ))
+ }
+
+ fn open_backend(backend: Backend, params: &VideoParams) -> Result<Self, String> {
+ // SAFETY: this whole function is a single ffmpeg setup sequence. Every
+ // allocation is stored in `encoder` as soon as it succeeds, so the Drop
+ // impl frees whatever was reached if a later step fails.
+ unsafe {
+ let codec = ff::avcodec_find_encoder_by_name(backend.codec_name().as_ptr());
+ if codec.is_null() {
+ return Err(format!(
+ "{} is not compiled into this ffmpeg build",
+ backend.codec_name().to_string_lossy()
+ ));
+ }
+
+ let codec_ctx = ff::avcodec_alloc_context3(codec);
+ if codec_ctx.is_null() {
+ return Err("avcodec_alloc_context3 returned null".to_owned());
+ }
+
+ let mut encoder = Self {
+ backend,
+ codec_ctx,
+ hw_device: ptr::null_mut(),
+ hw_frames: ptr::null_mut(),
+ sw_frame: ptr::null_mut(),
+ hw_frame: ptr::null_mut(),
+ sws: ptr::null_mut(),
+ sws_src_format: ff::AV_PIX_FMT_NONE,
+ packet: ptr::null_mut(),
+ params: VideoParams {
+ width: params.width,
+ height: params.height,
+ fps: params.fps,
+ bitrate: params.bitrate,
+ },
+ stats: EncodeStats::default(),
+ sws_threads: 0,
+ };
+
+ (*codec_ctx).width = params.width;
+ (*codec_ctx).height = params.height;
+ // Constant frame rate: `time_base` is one frame, so a PTS is simply
+ // a frame index. Everything downstream — the muxer, the editor's
+ // timeline, the audio interleave — is easier to reason about than it
+ // would be with wall-clock timestamps, and duplicated frames of a
+ // static screen cost a few hundred bytes each.
+ (*codec_ctx).time_base = ff::AVRational { num: 1, den: params.fps };
+ (*codec_ctx).framerate = ff::AVRational { num: params.fps, den: 1 };
+ (*codec_ctx).pix_fmt = backend.codec_pixel_format();
+ (*codec_ctx).bit_rate = params.bitrate;
+ (*codec_ctx).gop_size = params.fps * 2;
+ // No B-frames. A screen recording has no use for them, they add
+ // reorder delay, and they force DTS bookkeeping the muxer would
+ // otherwise not need.
+ (*codec_ctx).max_b_frames = 0;
+ // The muxer needs an extradata-carrying global header for MP4.
+ (*codec_ctx).flags |= ff::AV_CODEC_FLAG_GLOBAL_HEADER as i32;
+
+ if let Some(device_type) = backend.hw_device_type() {
+ encoder.attach_hardware(device_type, params)?;
+ }
+
+ let opened = ff::avcodec_open2(codec_ctx, codec, ptr::null_mut());
+ if opened < 0 {
+ return Err(format!("avcodec_open2: {}", ff::err_to_string(opened)));
+ }
+
+ encoder.packet = ff::av_packet_alloc();
+ if encoder.packet.is_null() {
+ return Err("av_packet_alloc returned null".to_owned());
+ }
+
+ encoder.alloc_software_frame(backend, params)?;
+ if backend.hw_device_type().is_some() {
+ encoder.hw_frame = ff::av_frame_alloc();
+ if encoder.hw_frame.is_null() {
+ return Err("av_frame_alloc returned null".to_owned());
+ }
+ }
+
+ Ok(encoder)
+ }
+ }
+
+ /// SAFETY: called only from `open_backend`, with `self.codec_ctx` valid.
+ unsafe fn attach_hardware(
+ &mut self,
+ device_type: ff::AVHWDeviceType,
+ params: &VideoParams,
+ ) -> Result<(), String> {
+ let created = ff::av_hwdevice_ctx_create(
+ &mut self.hw_device,
+ device_type,
+ ptr::null(),
+ ptr::null_mut(),
+ 0,
+ );
+ if created < 0 {
+ return Err(format!(
+ "av_hwdevice_ctx_create: {}",
+ ff::err_to_string(created)
+ ));
+ }
+
+ self.hw_frames = ff::av_hwframe_ctx_alloc(self.hw_device);
+ if self.hw_frames.is_null() {
+ return Err("av_hwframe_ctx_alloc returned null".to_owned());
+ }
+ let frames_ctx = (*self.hw_frames).data as *mut ff::AVHWFramesContext;
+ (*frames_ctx).format = self.backend.codec_pixel_format();
+ (*frames_ctx).sw_format = self.backend.upload_format();
+ (*frames_ctx).width = params.width;
+ (*frames_ctx).height = params.height;
+ // Enough surfaces that the encoder can hold a few references while we
+ // are filling the next one. Too small a pool stalls; too large just
+ // wastes VRAM.
+ (*frames_ctx).initial_pool_size = 8;
+
+ let initialised = ff::av_hwframe_ctx_init(self.hw_frames);
+ if initialised < 0 {
+ return Err(format!(
+ "av_hwframe_ctx_init: {}",
+ ff::err_to_string(initialised)
+ ));
+ }
+
+ (*self.codec_ctx).hw_frames_ctx = ff::av_buffer_ref(self.hw_frames);
+ if (*self.codec_ctx).hw_frames_ctx.is_null() {
+ return Err("av_buffer_ref on the frames context returned null".to_owned());
+ }
+ Ok(())
+ }
+
+ /// SAFETY: called only from `open_backend`.
+ unsafe fn alloc_software_frame(
+ &mut self,
+ backend: Backend,
+ params: &VideoParams,
+ ) -> Result<(), String> {
+ self.sw_frame = ff::av_frame_alloc();
+ if self.sw_frame.is_null() {
+ return Err("av_frame_alloc returned null".to_owned());
+ }
+ (*self.sw_frame).format = backend.upload_format();
+ (*self.sw_frame).width = params.width;
+ (*self.sw_frame).height = params.height;
+ let allocated = ff::av_frame_get_buffer(self.sw_frame, 0);
+ if allocated < 0 {
+ return Err(format!(
+ "av_frame_get_buffer: {}",
+ ff::err_to_string(allocated)
+ ));
+ }
+ Ok(())
+ }
+
+ pub fn backend(&self) -> Backend {
+ self.backend
+ }
+
+ /// Borrows the opened codec context so the muxer can copy its parameters.
+ pub fn codec_context(&self) -> *mut ff::AVCodecContext {
+ self.codec_ctx
+ }
+
+ /// Converts one captured RGB frame and submits it at `pts` (a frame index).
+ ///
+ /// `src_format` is whatever PipeWire negotiated; the swscale context is
+ /// rebuilt if it ever changes, which it should not mid-stream.
+ pub fn submit(
+ &mut self,
+ pixels: &[u8],
+ stride: usize,
+ src_format: ff::AVPixelFormat,
+ pts: i64,
+ mut on_packet: impl FnMut(*mut ff::AVPacket) -> Result<(), String>,
+ ) -> Result<(), String> {
+ let needed = stride
+ .checked_mul(self.params.height as usize)
+ .ok_or_else(|| "frame size overflows".to_owned())?;
+ if pixels.len() < needed {
+ return Err(format!(
+ "captured frame is truncated: {} bytes for {} rows at stride {stride}",
+ pixels.len(),
+ self.params.height
+ ));
+ }
+
+ // SAFETY: the slice was just bounds-checked against the geometry we hand
+ // to swscale, and every ffmpeg pointer below is owned by `self`.
+ unsafe {
+ self.ensure_sws(src_format)?;
+
+ // The staging frame is reused every frame; ffmpeg requires it be
+ // writable before we scribble into it, which matters once the
+ // encoder starts holding references to earlier frames.
+ let writable = ff::av_frame_make_writable(self.sw_frame);
+ if writable < 0 {
+ return Err(format!(
+ "av_frame_make_writable: {}",
+ ff::err_to_string(writable)
+ ));
+ }
+
+ let src_data = [pixels.as_ptr(), ptr::null(), ptr::null(), ptr::null()];
+ let src_stride = [stride as i32, 0, 0, 0];
+ let convert_started = std::time::Instant::now();
+ let scaled = ff::sws_scale(
+ self.sws,
+ src_data.as_ptr(),
+ src_stride.as_ptr(),
+ 0,
+ self.params.height,
+ (*self.sw_frame).data.as_mut_ptr(),
+ (*self.sw_frame).linesize.as_mut_ptr(),
+ );
+ self.stats.convert_ns += convert_started.elapsed().as_nanos();
+ if scaled < 0 {
+ return Err(format!("sws_scale: {}", ff::err_to_string(scaled)));
+ }
+
+ let upload_started = std::time::Instant::now();
+ let frame = if self.hw_frames.is_null() {
+ (*self.sw_frame).pts = pts;
+ self.sw_frame
+ } else {
+ let got = ff::av_hwframe_get_buffer(self.hw_frames, self.hw_frame, 0);
+ if got < 0 {
+ return Err(format!(
+ "av_hwframe_get_buffer: {}",
+ ff::err_to_string(got)
+ ));
+ }
+ let transferred = ff::av_hwframe_transfer_data(self.hw_frame, self.sw_frame, 0);
+ if transferred < 0 {
+ return Err(format!(
+ "av_hwframe_transfer_data: {}",
+ ff::err_to_string(transferred)
+ ));
+ }
+ (*self.hw_frame).pts = pts;
+ self.hw_frame
+ };
+ self.stats.upload_ns += upload_started.elapsed().as_nanos();
+
+ let encode_started = std::time::Instant::now();
+ self.send_and_drain(frame, &mut on_packet)?;
+ self.stats.encode_ns += encode_started.elapsed().as_nanos();
+ self.stats.frames += 1;
+
+ if !self.hw_frame.is_null() {
+ // Release our reference to the GPU surface; the encoder keeps
+ // its own for as long as it needs one. Without this the pool
+ // drains after `initial_pool_size` frames and every subsequent
+ // av_hwframe_get_buffer blocks.
+ ff::av_frame_unref(self.hw_frame);
+ }
+ }
+ Ok(())
+ }
+
+ /// Flushes the encoder. Call once, at stop.
+ pub fn finish(
+ &mut self,
+ mut on_packet: impl FnMut(*mut ff::AVPacket) -> Result<(), String>,
+ ) -> Result<(), String> {
+ // SAFETY: a null frame is how ffmpeg is told to drain.
+ unsafe { self.send_and_drain(ptr::null_mut(), &mut on_packet) }
+ }
+
+ /// SAFETY: `frame` is either null (drain) or a frame this encoder owns.
+ unsafe fn send_and_drain(
+ &mut self,
+ frame: *mut ff::AVFrame,
+ on_packet: &mut impl FnMut(*mut ff::AVPacket) -> Result<(), String>,
+ ) -> Result<(), String> {
+ let sent = ff::avcodec_send_frame(self.codec_ctx, frame);
+ if sent < 0 && sent != ff::AVERROR_EOF {
+ return Err(format!("avcodec_send_frame: {}", ff::err_to_string(sent)));
+ }
+
+ loop {
+ let received = ff::avcodec_receive_packet(self.codec_ctx, self.packet);
+ if received == ff::AVERROR_EAGAIN || received == ff::AVERROR_EOF {
+ return Ok(());
+ }
+ if received < 0 {
+ return Err(format!(
+ "avcodec_receive_packet: {}",
+ ff::err_to_string(received)
+ ));
+ }
+ let result = on_packet(self.packet);
+ ff::av_packet_unref(self.packet);
+ result?;
+ }
+ }
+
+ /// SAFETY: called with `self` valid; rebuilds `self.sws` when the source
+ /// format changes.
+ unsafe fn ensure_sws(&mut self, src_format: ff::AVPixelFormat) -> Result<(), String> {
+ if !self.sws.is_null() && self.sws_src_format == src_format {
+ return Ok(());
+ }
+ if !self.sws.is_null() {
+ ff::sws_freeContext(self.sws);
+ self.sws = ptr::null_mut();
+ }
+ // Built through the option API rather than `sws_getContext` so that
+ // `threads` can be set at all — `sws_getContext` has no way to express
+ // it. It is set to 1 by default; see [`sws_thread_count`] for the
+ // measurement behind that.
+ //
+ // Source and destination are the same size, so no resampling filter is
+ // involved and the cheapest kernel is the right one: this is a pure
+ // colour-space conversion, and a bilinear kernel would cost more for
+ // pixels it never moves.
+ self.sws = ff::sws_alloc_context();
+ if self.sws.is_null() {
+ return Err("sws_alloc_context returned null".to_owned());
+ }
+ let dst_format = self.backend.upload_format();
+ let options: [(&CStr, i64); 8] = [
+ (c"srcw", self.params.width as i64),
+ (c"srch", self.params.height as i64),
+ (c"src_format", src_format as i64),
+ (c"dstw", self.params.width as i64),
+ (c"dsth", self.params.height as i64),
+ (c"dst_format", dst_format as i64),
+ (c"sws_flags", ff::SWS_POINT as i64),
+ (c"threads", sws_thread_count() as i64),
+ ];
+ for (name, value) in options {
+ let set = ff::av_opt_set_int(self.sws.cast(), name.as_ptr(), value, 0);
+ if set < 0 {
+ return Err(format!(
+ "av_opt_set_int({}, {value}): {}",
+ name.to_string_lossy(),
+ ff::err_to_string(set)
+ ));
+ }
+ }
+ let initialised = ff::sws_init_context(self.sws, ptr::null_mut(), ptr::null_mut());
+ if initialised < 0 {
+ return Err(format!(
+ "sws_init_context could not convert pixel format {src_format} to {dst_format}: {}",
+ ff::err_to_string(initialised)
+ ));
+ }
+ // Read back rather than assume: libswscale is free to ignore a thread
+ // count it cannot use for a given conversion, and a request that was
+ // silently dropped looks exactly like threading that did not help.
+ let mut granted = 0i64;
+ if ff::av_opt_get_int(self.sws.cast(), c"threads".as_ptr(), 0, &mut granted) >= 0 {
+ self.sws_threads = granted;
+ }
+ self.sws_src_format = src_format;
+ Ok(())
+ }
+
+ pub fn stats(&self) -> EncodeStats {
+ self.stats
+ }
+
+ /// Threads libswscale actually granted, once a frame has been submitted.
+ pub fn sws_threads(&self) -> i64 {
+ self.sws_threads
+ }
+}
+
+impl Drop for VideoEncoder {
+ fn drop(&mut self) {
+ // SAFETY: every pointer is either null or owned by this struct, and each
+ // free function tolerates a pointer-to-null.
+ unsafe {
+ if !self.sws.is_null() {
+ ff::sws_freeContext(self.sws);
+ }
+ if !self.packet.is_null() {
+ ff::av_packet_free(&mut self.packet);
+ }
+ if !self.hw_frame.is_null() {
+ ff::av_frame_free(&mut self.hw_frame);
+ }
+ if !self.sw_frame.is_null() {
+ ff::av_frame_free(&mut self.sw_frame);
+ }
+ if !self.codec_ctx.is_null() {
+ ff::avcodec_free_context(&mut self.codec_ctx);
+ }
+ if !self.hw_frames.is_null() {
+ ff::av_buffer_unref(&mut self.hw_frames);
+ }
+ if !self.hw_device.is_null() {
+ ff::av_buffer_unref(&mut self.hw_device);
+ }
+ }
+ }
+}
+
+/// A single-video-stream MP4 writer.
+///
+/// `+faststart` is not used: it rewrites the whole file on close, which on a
+/// long recording means copying gigabytes. The moov atom is written at the end
+/// as usual, and the app reads these files locally, where a trailing moov costs
+/// nothing. This is the difference from the WebM path, which had NO index at all
+/// and could not be seeked even locally (see electron/recording/webm-seek-index.ts).
+pub struct Muxer {
+ fmt: *mut ff::AVFormatContext,
+ stream_index: i32,
+ stream_time_base: ff::AVRational,
+ encoder_time_base: ff::AVRational,
+ header_written: bool,
+}
+
+impl Muxer {
+ pub fn create(path: &Path, encoder: &VideoEncoder) -> Result<Self, String> {
+ let path_c = CString::new(path.as_os_str().as_encoded_bytes())
+ .map_err(|_| "output path contains a NUL byte".to_owned())?;
+
+ // SAFETY: standard libavformat output setup; `fmt` is stored before any
+ // fallible step so Drop can clean up.
+ unsafe {
+ let mut fmt: *mut ff::AVFormatContext = ptr::null_mut();
+ let allocated = ff::avformat_alloc_output_context2(
+ &mut fmt,
+ ptr::null_mut(),
+ c"mp4".as_ptr(),
+ path_c.as_ptr(),
+ );
+ if allocated < 0 || fmt.is_null() {
+ return Err(format!(
+ "avformat_alloc_output_context2: {}",
+ ff::err_to_string(allocated)
+ ));
+ }
+
+ let mut muxer = Self {
+ fmt,
+ stream_index: -1,
+ stream_time_base: ff::AVRational { num: 0, den: 1 },
+ encoder_time_base: (*encoder.codec_context()).time_base,
+ header_written: false,
+ };
+
+ let stream = ff::avformat_new_stream(fmt, ptr::null());
+ if stream.is_null() {
+ return Err("avformat_new_stream returned null".to_owned());
+ }
+ (*stream).time_base = muxer.encoder_time_base;
+ let copied =
+ ff::avcodec_parameters_from_context((*stream).codecpar, encoder.codec_context());
+ if copied < 0 {
+ return Err(format!(
+ "avcodec_parameters_from_context: {}",
+ ff::err_to_string(copied)
+ ));
+ }
+ muxer.stream_index = (*stream).index;
+
+ let opened = ff::avio_open(&mut (*fmt).pb, path_c.as_ptr(), ff::AVIO_FLAG_WRITE as i32);
+ if opened < 0 {
+ return Err(format!(
+ "avio_open({}): {}",
+ path.display(),
+ ff::err_to_string(opened)
+ ));
+ }
+
+ let header = ff::avformat_write_header(fmt, ptr::null_mut());
+ if header < 0 {
+ return Err(format!(
+ "avformat_write_header: {}",
+ ff::err_to_string(header)
+ ));
+ }
+ muxer.header_written = true;
+ // libavformat may have rewritten the stream's time base while
+ // writing the header (MP4 prefers 1/90000-style bases). Everything
+ // after this must rescale into the value it CHOSE, not the value we
+ // asked for — using ours produces a file whose duration is wrong by
+ // the ratio between them.
+ muxer.stream_time_base = (*stream).time_base;
+
+ Ok(muxer)
+ }
+ }
+
+ /// Writes one encoded packet, rescaling it out of the encoder's time base.
+ pub fn write(&mut self, packet: *mut ff::AVPacket) -> Result<(), String> {
+ // SAFETY: `packet` comes from the encoder that this muxer was created
+ // for, and is valid until the caller unrefs it.
+ unsafe {
+ (*packet).stream_index = self.stream_index;
+ ff::av_packet_rescale_ts(packet, self.encoder_time_base, self.stream_time_base);
+ let written = ff::av_interleaved_write_frame(self.fmt, packet);
+ if written < 0 {
+ return Err(format!(
+ "av_interleaved_write_frame: {}",
+ ff::err_to_string(written)
+ ));
+ }
+ }
+ Ok(())
+ }
+
+ /// Writes the trailer and closes the file. Consuming `self` makes it a
+ /// compile error to write another packet afterwards.
+ pub fn finish(mut self) -> Result<(), String> {
+ // SAFETY: `fmt` is valid and the header was written, which is what
+ // av_write_trailer requires.
+ unsafe {
+ let written = ff::av_write_trailer(self.fmt);
+ self.header_written = false;
+ if written < 0 {
+ return Err(format!("av_write_trailer: {}", ff::err_to_string(written)));
+ }
+ }
+ Ok(())
+ }
+}
+
+impl Drop for Muxer {
+ fn drop(&mut self) {
+ // SAFETY: `fmt` is either null or ours. `header_written` is still true
+ // only on the error path — `finish` clears it — and a file left without
+ // its trailer would be unplayable, so write one on the way out.
+ unsafe {
+ if self.fmt.is_null() {
+ return;
+ }
+ if self.header_written {
+ ff::av_write_trailer(self.fmt);
+ }
+ if !(*self.fmt).pb.is_null() {
+ ff::avio_closep(&mut (*self.fmt).pb);
+ }
+ ff::avformat_free_context(self.fmt);
+ self.fmt = ptr::null_mut();
+ }
+ }
+}
+
+/// Threads to give libswscale. One, by measurement.
+///
+/// BGRA→NV12 at 1920×1080 was timed at 3.80 ms/frame with one thread and
+/// 3.84 ms with eight, on an 8-thread Radeon 610M APU. The request is not being
+/// ignored — [`VideoEncoder::sws_threads`] reads the granted count back out of
+/// libswscale and it matches — the conversion is simply memory-bandwidth bound,
+/// and extra threads contend for the same bandwidth instead of adding any.
+/// Spawning eight threads per recording to gain 1% of nothing is not worth the
+/// scheduler churn on a machine that is simultaneously compositing the screen
+/// being captured.
+///
+/// The override exists because that measurement is one machine at one
+/// resolution; a 4K capture on a many-core desktop with more memory channels may
+/// well behave differently, and this makes checking it a one-liner.
+fn sws_thread_count() -> usize {
+ if let Ok(raw) = std::env::var("OPENSCREEN_LINUX_SWS_THREADS") {
+ if let Ok(count) = raw.trim().parse::<usize>() {
+ return count.clamp(1, 32);
+ }
+ }
+ 1
+}
+
+/// Parses `OPENSCREEN_LINUX_ENCODER`. Returns `None` when unset, which means
+/// "walk the ladder".
+pub fn forced_backend_from_env() -> Result<Option<Backend>, String> {
+ let Ok(raw) = std::env::var("OPENSCREEN_LINUX_ENCODER") else {
+ return Ok(None);
+ };
+ match raw.trim().to_ascii_lowercase().as_str() {
+ "" | "auto" => Ok(None),
+ "vaapi" => Ok(Some(Backend::Vaapi)),
+ "vulkan" => Ok(Some(Backend::Vulkan)),
+ "software" | "openh264" | "libopenh264" => Ok(Some(Backend::Software)),
+ other => Err(format!(
+ "OPENSCREEN_LINUX_ENCODER={other} is not one of auto, vaapi, vulkan, software"
+ )),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_ladder_entry_names_a_codec_this_build_has() {
+ // Catches a vendored-ffmpeg swap that drops an encoder we depend on:
+ // without this the loss shows up only as a silent fall through to
+ // software on a user's machine.
+ for backend in LADDER {
+ // SAFETY: a lookup by name against a static string.
+ let codec = unsafe { ff::avcodec_find_encoder_by_name(backend.codec_name().as_ptr()) };
+ assert!(
+ !codec.is_null(),
+ "{} is missing from the vendored ffmpeg",
+ backend.codec_name().to_string_lossy()
+ );
+ }
+ }
+
+ #[test]
+ fn software_always_opens() {
+ // The bottom of the ladder is the one rung that must never fail, on any
+ // machine, with no GPU at all.
+ let encoder = VideoEncoder::open(
+ VideoParams { width: 320, height: 240, fps: 30, bitrate: 1_000_000 },
+ Some(Backend::Software),
+ |_, _| {},
+ )
+ .expect("libopenh264 must open");
+ assert_eq!(encoder.backend(), Backend::Software);
+ }
+
+ #[test]
+ fn software_encodes_a_frame_into_packets() {
+ let mut encoder = VideoEncoder::open(
+ VideoParams { width: 320, height: 240, fps: 30, bitrate: 1_000_000 },
+ Some(Backend::Software),
+ |_, _| {},
+ )
+ .expect("open");
+ let stride = 320 * 4;
+ let pixels = vec![0x40u8; stride * 240];
+ let mut packets = 0;
+ for pts in 0..10 {
+ encoder
+ .submit(&pixels, stride, ff::AV_PIX_FMT_BGRA, pts, |_| {
+ packets += 1;
+ Ok(())
+ })
+ .expect("submit");
+ }
+ encoder
+ .finish(|_| {
+ packets += 1;
+ Ok(())
+ })
+ .expect("finish");
+ assert!(packets > 0, "encoder produced no packets at all");
+ }
+
+ #[test]
+ fn a_truncated_frame_is_refused_rather_than_read_past() {
+ let mut encoder = VideoEncoder::open(
+ VideoParams { width: 320, height: 240, fps: 30, bitrate: 1_000_000 },
+ Some(Backend::Software),
+ |_, _| {},
+ )
+ .expect("open");
+ let error = encoder
+ .submit(&[0u8; 16], 320 * 4, ff::AV_PIX_FMT_BGRA, 0, |_| Ok(()))
+ .expect_err("must refuse");
+ assert!(error.contains("truncated"), "{error}");
+ }
+
+ #[test]
+ fn forced_backend_parsing_rejects_typos_instead_of_falling_back() {
+ std::env::set_var("OPENSCREEN_LINUX_ENCODER", "vulcan");
+ let error = forced_backend_from_env().expect_err("must reject");
+ assert!(error.contains("vulcan"), "{error}");
+ std::env::set_var("OPENSCREEN_LINUX_ENCODER", "vaapi");
+ assert_eq!(forced_backend_from_env().unwrap(), Some(Backend::Vaapi));
+ std::env::remove_var("OPENSCREEN_LINUX_ENCODER");
+ assert_eq!(forced_backend_from_env().unwrap(), None);
+ }
+
+ /// The whole pipeline — ladder, encode, mux — against a real file, with no
+ /// portal and no compositor involved.
+ ///
+ /// Opt-in via `OPENSCREEN_LINUX_ENCODE_TEST=1` because it depends on the
+ /// GPU: on this hardware it selects Vulkan, on a headless CI box it falls
+ /// through to software, and both are correct. Run it after any change to the
+ /// ladder, and read the printed backend — that line is the measurement.
+ #[test]
+ fn ladder_encodes_a_playable_mp4() {
+ if std::env::var("OPENSCREEN_LINUX_ENCODE_TEST").is_err() {
+ eprintln!("skipped: set OPENSCREEN_LINUX_ENCODE_TEST=1 to run");
+ return;
+ }
+ let (width, height, fps) = (1920, 1080, 60);
+ let output = std::env::temp_dir().join("openscreen-encoder-smoke.mp4");
+ let _ = std::fs::remove_file(&output);
+
+ let mut encoder = VideoEncoder::open(
+ VideoParams { width, height, fps, bitrate: 8_000_000 },
+ forced_backend_from_env().expect("valid encoder override"),
+ |backend, error| eprintln!(" {} unavailable: {error}", backend.as_str()),
+ )
+ .expect("some backend must open");
+ eprintln!("selected backend: {}", encoder.backend().as_str());
+
+ let mut muxer = Muxer::create(&output, &encoder).expect("muxer");
+ let stride = width as usize * 4;
+ let mut frame = vec![0u8; stride * height as usize];
+ let started = std::time::Instant::now();
+ const FRAMES: i64 = 120;
+ for pts in 0..FRAMES {
+ // Vary the content so the encoder cannot collapse the whole clip
+ // into one keyframe plus 119 skip frames, which would make the
+ // timing meaningless.
+ for (index, byte) in frame.iter_mut().enumerate() {
+ *byte = ((index as i64 + pts * 7919) % 251) as u8;
+ }
+ encoder
+ .submit(&frame, stride, ff::AV_PIX_FMT_BGRA, pts, |packet| muxer.write(packet))
+ .expect("submit");
+ }
+ encoder.finish(|packet| muxer.write(packet)).expect("finish");
+ let elapsed = started.elapsed();
+ muxer.finish().expect("trailer");
+
+ let stats = encoder.stats();
+ eprintln!(
+ "{FRAMES} frames of {width}x{height} in {:.2}s = {:.0} fps\n \
+ convert {:.2} ms/frame ({} swscale threads) | upload {:.2} ms | encode {:.2} ms",
+ elapsed.as_secs_f64(),
+ FRAMES as f64 / elapsed.as_secs_f64(),
+ stats.convert_ms(),
+ encoder.sws_threads(),
+ stats.upload_ms(),
+ stats.encode_ms(),
+ );
+
+ let size = std::fs::metadata(&output).expect("output exists").len();
+ assert!(size > 1024, "the muxed file is {size} bytes, which cannot be 120 frames");
+ }
+
+ #[test]
+ fn radv_perftest_is_added_without_clobbering_an_existing_value() {
+ std::env::set_var("RADV_PERFTEST", "gpl");
+ prepare_environment();
+ let value = std::env::var("RADV_PERFTEST").unwrap();
+ assert!(value.contains("gpl"), "existing flags must survive: {value}");
+ assert!(value.contains("video_encode"), "{value}");
+ // Idempotent: a second call must not append a duplicate.
+ prepare_environment();
+ assert_eq!(std::env::var("RADV_PERFTEST").unwrap(), value);
+ std::env::remove_var("RADV_PERFTEST");
+ }
+}
diff --git a/electron/native/pipewire-capture/src/ffmpeg.rs b/electron/native/pipewire-capture/src/ffmpeg.rs
new file mode 100644
index 000000000..1a7103416
--- /dev/null
+++ b/electron/native/pipewire-capture/src/ffmpeg.rs
@@ -0,0 +1,88 @@
+//! Raw ffmpeg bindings, plus the handful of constants bindgen cannot produce.
+//!
+//! The generated half comes from build.rs. The hand-written half below exists
+//! because ffmpeg expresses these as FUNCTION-LIKE macros (`AVERROR(e)`,
+//! `MKTAG`, `FFERRTAG`) or as bit flags inside a comment block, and bindgen
+//! emits neither. The compositor crate hit the same wall — see the
+//! `AVERROR_INVALIDDATA` constant in crates/compositor/src/ffi.rs, which was
+//! wrong for months because someone guessed at it instead of deriving it.
+//!
+//! Every value here is therefore derived, with the derivation shown, and pinned
+//! by a test at the bottom of the file rather than trusted.
+
+#![allow(non_upper_case_globals, non_camel_case_types, non_snake_case, dead_code)]
+
+include!(concat!(env!("OUT_DIR"), "/ffmpeg_sys.rs"));
+
+/// `MKTAG(a,b,c,d)` — a FourCC packed little-endian, as libavutil defines it.
+const fn mktag(a: u8, b: u8, c: u8, d: u8) -> i32 {
+ (a as i32) | ((b as i32) << 8) | ((c as i32) << 16) | ((d as i32) << 24)
+}
+
+/// `FFERRTAG` — the negated FourCC ffmpeg uses for its own error codes.
+const fn fferrtag(a: u8, b: u8, c: u8, d: u8) -> i32 {
+ -mktag(a, b, c, d)
+}
+
+/// `AVERROR(EAGAIN)`. The encoder returns this to mean "I have no packet for you
+/// yet, send another frame", which is the normal steady state, not a failure.
+pub const AVERROR_EAGAIN: i32 = -libc_EAGAIN;
+/// Linux's `EAGAIN`. Hardcoded rather than pulled from libc: this crate has no
+/// libc dependency, and the value is fixed by the kernel ABI on every Linux
+/// architecture this ships to.
+const libc_EAGAIN: i32 = 11;
+
+pub const AVERROR_EOF: i32 = fferrtag(b'E', b'O', b'F', b' ');
+pub const AVERROR_INVALIDDATA: i32 = fferrtag(b'I', b'N', b'D', b'A');
+pub const AVERROR_ENOMEM: i32 = -12;
+
+/// `AVIO_FLAG_WRITE` from libavformat/avio.h:618. A plain `#define` in a block
+/// bindgen skips, unlike the `SWS_*` flags below.
+pub const AVIO_FLAG_WRITE: i32 = 2;
+
+// The `SWS_*` rescaler flags are NOT redeclared here. They used to need it — the
+// compositor still carries its own copies (crates/compositor/src/linux_frames.rs)
+// because on its pinned headers they were plain `#define`s that bindgen skipped.
+// ffmpeg 8.1 made them an `enum SwsFlags`, so bindgen emits them and a
+// hand-written copy is now a hard compile error rather than a silent duplicate.
+
+/// Formats an ffmpeg return code the way `av_err2str` would, since that too is a
+/// macro and needs a caller-supplied buffer.
+pub fn err_to_string(code: i32) -> String {
+ let mut buffer = [0i8; 256];
+ // SAFETY: the buffer is the size we tell av_strerror it is, and ffmpeg
+ // always NUL-terminates within it.
+ let ok = unsafe { av_strerror(code, buffer.as_mut_ptr(), buffer.len()) } == 0;
+ if !ok {
+ return format!("unknown ffmpeg error {code}");
+ }
+ let bytes: Vec<u8> = buffer
+ .iter()
+ .take_while(|byte| **byte != 0)
+ .map(|byte| *byte as u8)
+ .collect();
+ String::from_utf8_lossy(&bytes).into_owned()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn error_constants_match_what_ffmpeg_itself_reports() {
+ // The point of this test: it does not check the constants against other
+ // hardcoded numbers, it checks them against the linked libavutil. A
+ // wrong FourCC derivation shows up here as a mismatched message.
+ assert_eq!(err_to_string(AVERROR_EOF), "End of file");
+ assert_eq!(err_to_string(AVERROR_INVALIDDATA), "Invalid data found when processing input");
+ assert_eq!(AVERROR_EAGAIN, -11);
+ }
+
+ #[test]
+ fn mktag_packs_little_endian() {
+ // 'a' = 0x61 lands in the LOW byte. Getting this backwards silently
+ // produces plausible-looking but wrong error codes.
+ assert_eq!(mktag(b'a', 0, 0, 0), 0x61);
+ assert_eq!(mktag(0, 0, 0, b'a'), 0x6100_0000);
+ }
+}
diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rs
index 6ef169078..e025fc75a 100644
--- a/electron/native/pipewire-capture/src/main.rs
+++ b/electron/native/pipewire-capture/src/main.rs
@@ -17,7 +17,9 @@
//! "move"; there is no click detection to be had here at any effort level.
mod bitmap;
+mod encoder;
mod events;
+mod ffmpeg;
mod portal;
mod shim;