From 72ea9614a537614b5990510217745bfd3f0f24cb Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 05:34:06 -0700 Subject: [PATCH 01/25] ALI-2420: The shared libmpv playback crate, with colour tests One crate for Alias View, Gannet and Nitrate to play through libmpv: - Player: libmpv opened at run time, the shared options, commands, and events for position, duration, pause, volume, mute, end and failure. - SwRender and GlRender: libmpv's CPU and OpenGL render APIs. - options::colour: the colour settings for each render path in one place. The CPU path keeps Gannet's BT.1886 relabel (ALI-2418). - helper and jail: Gannet's jailed CPU player, with frames in shared memory, moved here so any app can use it. Every app stops on a video's last frame instead of closing. Hardware decoding tries NVDEC, VA-API and V4L2 by name. VDPAU is left out because it stalls on H.264 4:4:4 on NVIDIA. The colour tests play 51 clips of solid patches, made from Y'CbCr worked out from source RGB and encoded losslessly. The clips cover range, matrix, transfer tag, bit depth, chroma and codec. CI runs them on the CPU renderer, and examples/colour-gpu.rs runs them on a graphics card. --- .github/workflows/ci.yml | 60 +++ .gitignore | 2 + Cargo.lock | 67 +++ Cargo.toml | 29 ++ Makefile | 11 + README.md | 132 +++++- examples/colour-gpu.rs | 273 +++++++++++++ src/ffi.rs | 204 ++++++++++ src/helper.rs | 850 +++++++++++++++++++++++++++++++++++++++ src/jail.rs | 121 ++++++ src/lib.rs | 26 ++ src/options.rs | 199 +++++++++ src/player.rs | 368 +++++++++++++++++ src/render.rs | 239 +++++++++++ tests/clips/mod.rs | 370 +++++++++++++++++ tests/colour.rs | 76 ++++ tests/helper.rs | 214 ++++++++++ 17 files changed, 3240 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 Makefile create mode 100644 examples/colour-gpu.rs create mode 100644 src/ffi.rs create mode 100644 src/helper.rs create mode 100644 src/jail.rs create mode 100644 src/lib.rs create mode 100644 src/options.rs create mode 100644 src/player.rs create mode 100644 src/render.rs create mode 100644 tests/clips/mod.rs create mode 100644 tests/colour.rs create mode 100644 tests/helper.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8ffdd93 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,60 @@ +# Runs on the org's self-hosted home runners, which take private repositories (GitHub's +# hosted runners are for the open-source ones). Their host has no Rust and no sudo, so the +# job runs in an Arch container, where aliasOS's packages are built: the libmpv and FFmpeg +# here are the ones aliasOS ships. The runner runs as uid 1001 and cleans the workspace +# before the next job; it can't remove what root left there, so the job ends by handing it +# back. +# +# The colour tests run on libmpv's software renderer, which needs no graphics card. The GPU +# renderer's run (`examples/colour-gpu.rs`) is a bench step on the desktop and the M1. +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +# A PR's runs share a group, so a new push cancels the one it supersedes. +# Each push to main has a group of its own, so every commit gets a result. +concurrency: + group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +# The job runs pull request code as root on shared runners: the token reads only. +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + check: + name: fmt, clippy, tests and colour tests + runs-on: [self-hosted, home] + container: archlinux:latest + timeout-minutes: 30 + steps: + # git before checkout, or checkout falls back to a tarball. FFmpeg makes the test clips + # (libx264, libx265, libvpx and libaom come with Arch's), and mpv brings libmpv. + - name: Install build dependencies + run: pacman -Syu --noconfirm --needed git rust gcc pkgconf mpv ffmpeg >/dev/null + - uses: actions/checkout@v5 + with: + persist-credentials: false + - uses: actions/cache@v4 + with: + path: | + .ci/cargo/registry + target + key: check-${{ hashFiles('Cargo.lock') }} + restore-keys: check- + - name: cargo fmt + run: cargo fmt --check + - name: cargo clippy + run: CARGO_HOME="$PWD/.ci/cargo" cargo clippy --all-targets --locked -- -D warnings + - name: cargo test (the colour tests print a table of every case) + run: CARGO_HOME="$PWD/.ci/cargo" cargo test --locked + - name: Hand the workspace back to the runner user + if: always() + run: chown -R 1001:1001 "$GITHUB_WORKSPACE" "$RUNNER_TEMP" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8db94aa --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/.ci diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..abdd65c --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,67 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "alias-playback" +version = "0.1.0" +dependencies = [ + "libc", + "rustix", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..99f952c --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "alias-playback" +version = "0.1.0" +edition = "2024" +license = "MIT" +description = "libmpv playback for Alias View, Gannet and Nitrate: one wrapper, one set of colour settings, and tests that prove the colours" +publish = false + +[dependencies] +# dlopen for libmpv, and the system calls a helper player needs (dup2, close_range, prctl). +libc = "0.2.191" +# memfd, mmap, pipes and poll for a helper player's frames and messages. +rustix = { version = "1.1.6", features = ["fs", "mm", "pipe", "event", "process"] } + +# The colour tests and the helper test pick their own main, so they can run a copy of +# themselves as a helper player. +[[test]] +name = "colour" +harness = false + +[[test]] +name = "helper" +harness = false + +[dev-dependencies] +# The helper test's cancel signal, an eventfd, as an app's would be. +rustix = { version = "1.1.6", features = ["event"] } +# The GPU colour bench opens EGL at run time, as the crate opens libmpv. +libc = "0.2.191" diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ef46ced --- /dev/null +++ b/Makefile @@ -0,0 +1,11 @@ +.PHONY: check colour-gpu + +check: + cargo fmt --check + cargo clippy --all-targets --locked -- -D warnings + cargo test --locked + +# The colour tests on a graphics card. CI has none, so this is a bench step on the desktop +# and the M1 before a release. +colour-gpu: + cargo run --release --locked --example colour-gpu diff --git a/README.md b/README.md index 9d68e93..c5e74b1 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,133 @@ # alias-playback -One libmpv playback crate for Alias View, Gannet and Nitrate (ALI-2420). +One libmpv playback crate for Alias View, Gannet and Nitrate (ALI-2420). It wraps libmpv +once, keeps the colour settings in one place so a fix reaches every app at once, and proves +the colours with tests. + +libmpv stays the decoder and player (decided 2026-11-30). This crate doesn't decode anything +itself. + +## What's in it + +| Module | What it does | +| --- | --- | +| `Player` (`player.rs`) | One libmpv player, set up from `Options`. Commands (load, play, pause, seek, volume, mute) and the events every app needs: position, duration, pause, volume, mute, end, failure. | +| `SwRender`, `GlRender` (`render.rs`) | Drawing frames on the CPU into memory (Wayland's `XRGB8888`, ready for `wl_shm`), or with OpenGL into the app's framebuffer. | +| `Options`, `options::colour` (`options.rs`) | The setup every app shares, the few choices that differ (render path, hardware decoding, sound, cover art), and the colour settings for each render path. | +| `helper` (`helper.rs`) | A player in another process, drawing on the CPU into shared memory, with its state as short lines of text. Both sides: the app's (`start`, `watch`, `Frames`, `Remote`) and the player's (`run`). Moved here from Gannet's preview. | +| `jail` (`jail.rs`) | The bubblewrap jail for that process, as Gannet's preview uses it. The app adds its own seccomp filter through `helper::run`'s `lock_down`. | + +### The same in every app + +- A video stops on its last frame, paused, instead of closing (`keep-open`). Play after the + end starts again from the beginning. +- Nothing of the user's own mpv setup is read: no `mpv.conf`, scripts, profiles or saved + positions. Nothing beside the file is looked for (subtitles, sound, cover art), and nothing + is fetched online. +- No on-screen display or key bindings: the app draws the controls. +- Hardware decoding, when on, tries NVDEC, VA-API, then V4L2, and falls back to the CPU. + VDPAU is left out: on NVIDIA it takes H.264 4:4:4, fails every frame, and never falls back, + so the video never starts. The software renderer gets the copy-back methods only. + +libmpv is opened at run time (`libmpv.so.2`, client API 2.x), so an app using this starts +without it and only loses playback. + +## Colour + +`options::colour` holds the colour settings for each render path: + +| Path | Setting | Why | +| --- | --- | --- | +| CPU | `vf=format=gamma=bt.1886` | The software renderer's converter, zimg, lifts the darks of video tagged with the sRGB transfer (ALI-2418). It also lifts full-range video with no transfer tag, which the colour tests found. Labelling every picture BT.1886 first fixes both; the other SDR tags come out the same either way. | +| GPU | none | The OpenGL renderer draws every SDR tag correctly as it is. | + +### The colour tests + +`tests/colour.rs` (CPU, in CI) and `examples/colour-gpu.rs` (GPU, a bench step) play the +same 51 clips. Each clip is a 4x4 grid of solid patches: black, white, greys, the +primaries and secondaries, three skin tones, and Tarnished's `#121C24`. + +- **Cases:** all 27 combinations of range (limited, full, full as `yuvj`), matrix (BT.601, + BT.709, BT.2020) and transfer tag (BT.709, sRGB, none) on H.264; H.264, HEVC, VP9 and AV1 + each at 8 and 10 bits, 4:2:0 and 4:4:4; and each codec with full range and with the sRGB + tag. +- **Expected values come from the source RGB.** The test works out each clip's Y'CbCr itself + (ITU-T H.273) and FFmpeg encodes it losslessly, converting nothing. Before a clip is + played, ffprobe must read back the case's tags, and FFmpeg must decode it back to that + Y'CbCr exactly. A failure is then the player's, never the clip's. +- **Pass:** every pixel inside every patch (16 px in from the edges) within 2 steps per + channel of its source colour. +- The CPU run draws each clip at full and half size, and once more without the colour + settings, printing what they fix. +- The GPU run draws each clip with OpenGL (no hardware decoding, then hardware decoding) and + with the software renderer plus hardware decoding. It runs off-screen on EGL's device + platform, with no window or compositor. It reports which decoder libmpv used. + +Not covered yet: HDR (PQ, HLG), which tone-maps by design and needs its own reference with a +wider tolerance; real recordings from wf-recorder (M1) and gpu-screen-recorder (desktop) +checked against screenshots taken at the same moment; and primaries other than BT.709. + +### Results, 2026-12-02 (libmpv 0.42.0, FFmpeg 9.1) + +| Machine | Renderer | Result | +| --- | --- | --- | +| Desktop, x86_64 | CPU, no hardware decoding (as CI runs it) | 51 of 51 | +| Desktop, RTX 4090 | GPU, no hardware decoding | 51 of 51 | +| Desktop, RTX 4090 | GPU, hardware decoding (NVDEC for 44 clips, the CPU for 7 it can't take) | 51 of 51 | +| Desktop, RTX 4090 | CPU, hardware decoding (NVDEC copy-back) | 51 of 51 | +| M1 Max, Asahi | GPU, with and without hardware decoding; CPU with it (all decoded on the CPU) | 49 of 49; 2 skipped | + +The M1's 2 skipped clips are 10-bit HEVC: its libx265 is 8-bit only, so it can't make them. +Without the CPU colour setting, the sRGB-tagged clips and the full-range clips with no +transfer tag draw up to 13 steps too light (`#121C24` as `#1E2831`). + +## Using it + +```rust +use alias_playback::{Event, Options, Player, SwFormat, SwRender}; + +let player = Player::new(&Options::cpu())?; +let mut render = SwRender::new(&player)?; +player.on_wakeup(|| { /* wake the thread that reads events */ }); +render.on_update(|| { /* wake the thread that draws */ }); +player.load(path)?; +player.set_paused(false)?; +// On the drawing thread, when woken: +if render.new_frame() { + render.render(width, height, stride, SwFormat::Bgr0, buffer)?; +} +// On the event thread, when woken: +while let Some(event) = player.next_event() { + match event { + Event::Position(seconds) => { /* … */ } + Event::Ended(true) => { /* stopped on its last frame */ } + _ => {} + } +} +``` + +A jailed player: the app's `main` calls `helper::run(args, &options, SANDBOX_CODE, +lock_down)` when started with its helper argument, and starts one with +`helper::start(jail::command(HELPER_ARG, sound)?, file, size, sound)`. + +## Checks + +```sh +make check # fmt, clippy, unit tests, the helper test and the CPU colour tests +make colour-gpu # the GPU bench, on a machine with a graphics card +``` + +Both need `ffmpeg` and `ffprobe` (with libx264, libx265, libvpx and libaom) and libmpv. The +helper test runs a real player in another process, without the jail: bubblewrap needs user +namespaces, which CI's containers don't give. + +## Dependencies + +| Crate | Why | +| --- | --- | +| `libc` | `dlopen` for libmpv, and the calls a helper needs: `dup2`, `close_range`, `prctl`. | +| `rustix` | Shared memory (`memfd`, `mmap`), pipes and `poll` for a helper's frames and messages. | + +## Licence + +MIT. Copyright (c) 2026 Alias Project, Inc. diff --git a/examples/colour-gpu.rs b/examples/colour-gpu.rs new file mode 100644 index 0000000..373d325 --- /dev/null +++ b/examples/colour-gpu.rs @@ -0,0 +1,273 @@ +//! The colour tests on a graphics card (ALI-2420): the same clips as `tests/colour.rs`, drawn +//! by libmpv's OpenGL renderer into an off-screen framebuffer and read back, with and without +//! hardware decoding, and by the software renderer with hardware decoding. CI's runners have +//! no graphics card, so this is a bench step, run on the desktop (NVIDIA) and the M1 (Asahi) +//! before a release: +//! +//! ```sh +//! cargo run --release --example colour-gpu [NAME...] +//! ``` +//! +//! It needs no window or compositor: OpenGL runs on EGL's device platform, straight on the +//! card. With hardware decoding on, each case says which decoder libmpv actually used, since a +//! card can't decode every lossless clip and falls back to the CPU. + +#[path = "../tests/clips/mod.rs"] +mod clips; + +use std::ffi::{CStr, c_char, c_void}; +use std::path::Path; +use std::process::ExitCode; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +use alias_playback::{Event, GlRender, Hwdec, Options, Player, RenderPath}; +use clips::{HEIGHT, TOLERANCE, WIDTH, cases, check_the_maths, decoder, make_clip, misses, play_cpu}; + +type EglDisplay = *mut c_void; +type EglFn = *mut c_void; + +const EGL_NONE: i32 = 0x3038; +const EGL_SURFACE_TYPE: i32 = 0x3033; +const EGL_PBUFFER_BIT: i32 = 0x0001; +const EGL_RENDERABLE_TYPE: i32 = 0x3040; +const EGL_OPENGL_BIT: i32 = 0x0008; +const EGL_OPENGL_API: u32 = 0x30A2; +const EGL_PLATFORM_DEVICE_EXT: u32 = 0x313F; +const EGL_CONTEXT_MAJOR_VERSION: i32 = 0x3098; +const EGL_CONTEXT_MINOR_VERSION: i32 = 0x30FB; +const EGL_CONTEXT_OPENGL_PROFILE_MASK: i32 = 0x30FD; +const EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT: i32 = 0x0001; + +const GL_FRAMEBUFFER: u32 = 0x8D40; +const GL_FRAMEBUFFER_COMPLETE: u32 = 0x8CD5; +const GL_COLOR_ATTACHMENT0: u32 = 0x8CE0; +const GL_TEXTURE_2D: u32 = 0x0DE1; +const GL_RGBA8: i32 = 0x8058; +const GL_RGBA: u32 = 0x1908; +const GL_UNSIGNED_BYTE: u32 = 0x1401; +const GL_PACK_ALIGNMENT: u32 = 0x0D05; + +static GET_PROC: OnceLock EglFn> = OnceLock::new(); + +unsafe extern "C" fn get_proc_address(_: *mut c_void, name: *const c_char) -> *mut c_void { + // SAFETY: set before any renderer exists, and EGL's lookup takes a terminated name. + unsafe { GET_PROC.get().map_or(std::ptr::null_mut(), |find| find(name)) } +} + +/// An OpenGL context with a framebuffer to draw in, current on this thread. +struct Gl { + fbo: u32, + bind_framebuffer: unsafe extern "C" fn(u32, u32), + pixel_store: unsafe extern "C" fn(u32, i32), + read_pixels: unsafe extern "C" fn(i32, i32, i32, i32, u32, u32, *mut c_void), + finish: unsafe extern "C" fn(), + renderer: String, +} + +/// Looks up a function by name, as the type it's assigned to. +macro_rules! lookup { + ($find:expr, $name:literal) => {{ + let found = $find(concat!($name, "\0").as_ptr() as *const c_char); + if found.is_null() { + return Err(concat!("no ", $name).to_owned()); + } + #[allow(clippy::missing_transmute_annotations)] + std::mem::transmute(found) + }}; +} + +impl Gl { + // SAFETY of everything here: EGL and GL calls with the types from their headers, on one + // thread, with results checked. + unsafe fn new() -> Result { + unsafe { + let library = libc::dlopen(c"libEGL.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_GLOBAL); + if library.is_null() { + return Err("no libEGL.so.1".into()); + } + let dlsym = |name: *const c_char| libc::dlsym(library, name); + let get_proc: unsafe extern "C" fn(*const c_char) -> EglFn = lookup!(dlsym, "eglGetProcAddress"); + let _ = GET_PROC.set(get_proc); + let query_devices: unsafe extern "C" fn(i32, *mut EglFn, *mut i32) -> u32 = lookup!(get_proc, "eglQueryDevicesEXT"); + let platform_display: unsafe extern "C" fn(u32, EglFn, *const i32) -> EglDisplay = lookup!(get_proc, "eglGetPlatformDisplayEXT"); + let initialize: unsafe extern "C" fn(EglDisplay, *mut i32, *mut i32) -> u32 = lookup!(dlsym, "eglInitialize"); + let bind_api: unsafe extern "C" fn(u32) -> u32 = lookup!(dlsym, "eglBindAPI"); + let choose_config: unsafe extern "C" fn(EglDisplay, *const i32, *mut EglFn, i32, *mut i32) -> u32 = lookup!(dlsym, "eglChooseConfig"); + let create_context: unsafe extern "C" fn(EglDisplay, EglFn, EglFn, *const i32) -> EglFn = lookup!(dlsym, "eglCreateContext"); + let make_current: unsafe extern "C" fn(EglDisplay, EglFn, EglFn, EglFn) -> u32 = lookup!(dlsym, "eglMakeCurrent"); + + let mut devices = [std::ptr::null_mut(); 8]; + let mut count = 0; + if query_devices(devices.len() as i32, devices.as_mut_ptr(), &mut count) == 0 || count == 0 { + return Err("EGL found no devices".into()); + } + // The first device that gives a context: on a desktop with one card, that card. + let mut context = None; + for &device in &devices[..count as usize] { + let display = platform_display(EGL_PLATFORM_DEVICE_EXT, device, [EGL_NONE].as_ptr()); + let (mut major, mut minor) = (0, 0); + if display.is_null() || initialize(display, &mut major, &mut minor) == 0 || bind_api(EGL_OPENGL_API) == 0 { + continue; + } + let mut config = std::ptr::null_mut(); + let mut configs = 0; + let wanted = [EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_NONE]; + if choose_config(display, wanted.as_ptr(), &mut config, 1, &mut configs) == 0 || configs == 0 { + continue; + } + // A compatibility context first, as most drivers give the newest that way; + // core 3.3 where they don't. + let core = [EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3, EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL_NONE]; + for attributes in [&[EGL_NONE][..], &core[..]] { + let made = create_context(display, config, std::ptr::null_mut(), attributes.as_ptr()); + if !made.is_null() && make_current(display, std::ptr::null_mut(), std::ptr::null_mut(), made) != 0 { + context = Some(made); + break; + } + } + if context.is_some() { + break; + } + } + if context.is_none() { + return Err("no EGL device gave an OpenGL context".into()); + } + + let get_string: unsafe extern "C" fn(u32) -> *const c_char = lookup!(get_proc, "glGetString"); + let renderer = get_string(0x1F01); + let renderer = if renderer.is_null() { "unknown".into() } else { CStr::from_ptr(renderer).to_string_lossy().into_owned() }; + let gen_framebuffers: unsafe extern "C" fn(i32, *mut u32) = lookup!(get_proc, "glGenFramebuffers"); + let bind_framebuffer: unsafe extern "C" fn(u32, u32) = lookup!(get_proc, "glBindFramebuffer"); + let gen_textures: unsafe extern "C" fn(i32, *mut u32) = lookup!(get_proc, "glGenTextures"); + let bind_texture: unsafe extern "C" fn(u32, u32) = lookup!(get_proc, "glBindTexture"); + let tex_image: unsafe extern "C" fn(u32, i32, i32, i32, i32, i32, u32, u32, *const c_void) = lookup!(get_proc, "glTexImage2D"); + let attach: unsafe extern "C" fn(u32, u32, u32, u32, i32) = lookup!(get_proc, "glFramebufferTexture2D"); + let status: unsafe extern "C" fn(u32) -> u32 = lookup!(get_proc, "glCheckFramebufferStatus"); + let pixel_store: unsafe extern "C" fn(u32, i32) = lookup!(get_proc, "glPixelStorei"); + let (mut fbo, mut texture) = (0, 0); + gen_framebuffers(1, &mut fbo); + gen_textures(1, &mut texture); + bind_texture(GL_TEXTURE_2D, texture); + tex_image(GL_TEXTURE_2D, 0, GL_RGBA8, WIDTH as i32, HEIGHT as i32, 0, GL_RGBA, GL_UNSIGNED_BYTE, std::ptr::null()); + bind_framebuffer(GL_FRAMEBUFFER, fbo); + attach(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); + if status(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE { + return Err("the framebuffer isn't complete".into()); + } + Ok(Self { fbo, bind_framebuffer, pixel_store, read_pixels: lookup!(get_proc, "glReadPixels"), finish: lookup!(get_proc, "glFinish"), renderer }) + } + } + + /// The framebuffer as `0x00RRGGBB` words, top row first. + fn read(&self) -> Vec { + let mut rgba = vec![0u8; WIDTH * HEIGHT * 4]; + // SAFETY: the context is current, and the buffer fits the framebuffer. libmpv leaves + // its own state behind, so the framebuffer and packing are set again first. + unsafe { + (self.finish)(); + (self.bind_framebuffer)(GL_FRAMEBUFFER, self.fbo); + (self.pixel_store)(GL_PACK_ALIGNMENT, 1); + (self.read_pixels)(0, 0, WIDTH as i32, HEIGHT as i32, GL_RGBA, GL_UNSIGNED_BYTE, rgba.as_mut_ptr() as *mut c_void); + } + // libmpv draws an off-screen framebuffer with its first row at the top, as read back. + rgba.as_chunks::<4>().0.iter().map(|p| u32::from(p[0]) << 16 | u32::from(p[1]) << 8 | u32::from(p[2])).collect() + } +} + +/// The first frame, drawn by the GPU renderer, and the decoder libmpv used. +fn play(gl: &Gl, clip: &Path, hwdec: Hwdec) -> Result<(Vec, String), String> { + let options = Options { render: RenderPath::Gpu, hwdec, ..Options::cpu() }; + let player = Player::new(&options).map_err(|e| e.to_string())?; + // SAFETY: the context is current on this thread for as long as the renderer lives, and the + // lookup finds its functions. + let mut render = unsafe { GlRender::new(&player, get_proc_address, std::ptr::null_mut(), None) }.map_err(|e| e.to_string())?; + // `COLOUR_GPU_LOG=FILE` keeps libmpv's log of the last case run, for a case that fails. + if let Some(log) = std::env::var_os("COLOUR_GPU_LOG") { + use std::os::unix::ffi::OsStrExt; + let _ = player.command(&[b"set", b"log-file", log.as_bytes()]); + } + player.load(clip).map_err(|e| e.to_string())?; + let deadline = Instant::now() + Duration::from_secs(20); + let mut restarted = false; + while Instant::now() < deadline { + match player.wait_event(Duration::from_millis(5)) { + Some(Event::Failed) => return Err("libmpv couldn't play it".into()), + Some(Event::Loaded { video: false }) => return Err("libmpv found no picture".into()), + Some(Event::Restarted) => restarted = true, + _ => {} + } + if restarted && render.new_frame() { + // SAFETY: as above, and the framebuffer is the context's, this size. + unsafe { render.render(gl.fbo as i32, WIDTH as i32, HEIGHT as i32, GL_RGBA8, false) }.map_err(|e| e.to_string())?; + return Ok((gl.read(), decoder(&player))); + } + } + Err("no frame within 20 seconds".into()) +} + +fn main() -> ExitCode { + check_the_maths(); + let filters: Vec = std::env::args().skip(1).filter(|a| !a.starts_with('-')).collect(); + // SAFETY: this thread keeps the context current until the process ends. + let gl = match unsafe { Gl::new() } { + Ok(gl) => gl, + Err(e) => { + eprintln!("no OpenGL: {e}"); + return ExitCode::FAILURE; + } + }; + let cases: Vec<_> = cases().into_iter().filter(|c| filters.is_empty() || filters.iter().any(|f| c.name().contains(f.as_str()))).collect(); + let dir = std::env::temp_dir().join(format!("alias-playback-colour-gpu-{}", std::process::id())); + if let Err(e) = std::fs::create_dir_all(&dir) { + eprintln!("can't make {}: {e}", dir.display()); + return ExitCode::FAILURE; + } + println!("\n{} colour cases, GPU renderer on {}, tolerance {TOLERANCE} steps:\n", cases.len(), gl.renderer); + let (mut failed, mut skipped) = (0, 0); + for case in &cases { + let name = case.name(); + let clip = match make_clip(case, &dir) { + Ok(clip) => clip, + // This machine's FFmpeg couldn't make it (the M1's libx265 is 8-bit only, for + // one): the player wasn't tried, so it hasn't failed, but it isn't a pass either. + Err(e) => { + skipped += 1; + println!("SKIP {name}: no clip: {e}"); + continue; + } + }; + let mut bad = false; + let mut decoders = Vec::new(); + let mut problems = Vec::new(); + // The GPU renderer with and without hardware decoding, and the software renderer with + // it, which CI can't try. + for (mode, render, hwdec) in [("GPU", RenderPath::Gpu, Hwdec::Off), ("GPU hwdec", RenderPath::Gpu, Hwdec::Auto), ("CPU hwdec", RenderPath::Cpu, Hwdec::Auto)] { + let played = match render { + RenderPath::Gpu => play(&gl, &clip, hwdec), + RenderPath::Cpu => play_cpu(&clip, (WIDTH, HEIGHT), hwdec, true), + }; + match played { + Ok((pixels, decoder)) => { + let missed = misses(&pixels, (WIDTH, HEIGHT)); + bad |= !missed.is_empty(); + decoders.push(format!("{mode}: {decoder}")); + problems.extend(missed.into_iter().map(|m| format!("{mode}: {m}"))); + } + Err(e) => { + bad = true; + decoders.push(format!("{mode}: failed")); + problems.push(format!("{mode}: {e}")); + } + } + } + failed += usize::from(bad); + println!("{} {name} ({})", if bad { "FAIL" } else { "ok " }, decoders.join(", ")); + for problem in problems { + println!(" {problem}"); + } + } + let _ = std::fs::remove_dir_all(&dir); + println!("\n{} passed, {failed} failed, {skipped} skipped\n", cases.len() - failed - skipped); + if failed == 0 { ExitCode::SUCCESS } else { ExitCode::FAILURE } +} diff --git a/src/ffi.rs b/src/ffi.rs new file mode 100644 index 0000000..2682c7b --- /dev/null +++ b/src/ffi.rs @@ -0,0 +1,204 @@ +//! libmpv's C API: the calls this crate makes, looked up at run time. +//! +//! The library is opened with `dlopen` rather than linked, so an app that uses this crate +//! still starts on a system without libmpv and only loses playback. It also lets a jailed +//! helper load libmpv before its sandbox goes on. The types and numbers come from libmpv's +//! stable public headers (`mpv/client.h`, `mpv/render.h`), client API 2.x. + +use std::ffi::{CStr, c_char, c_int, c_ulong, c_void}; +use std::sync::OnceLock; + +pub type Handle = *mut c_void; +pub type Callback = unsafe extern "C" fn(*mut c_void); +pub type GetProcAddress = unsafe extern "C" fn(*mut c_void, *const c_char) -> *mut c_void; + +#[repr(C)] +pub struct Event { + pub id: c_int, + pub error: c_int, + pub userdata: u64, + pub data: *mut c_void, +} + +#[repr(C)] +pub struct EventProperty { + pub name: *const c_char, + pub format: c_int, + pub data: *mut c_void, +} + +/// The start of `mpv_event_end_file`. Later fields exist, but only these two are read. +#[repr(C)] +pub struct EventEndFile { + pub reason: c_int, + pub error: c_int, +} + +#[repr(C)] +pub struct RenderParam { + pub kind: c_int, + pub data: *mut c_void, +} + +#[repr(C)] +pub struct OpenGlInitParams { + pub get_proc_address: Option, + pub get_proc_address_ctx: *mut c_void, +} + +#[repr(C)] +pub struct OpenGlFbo { + pub fbo: c_int, + pub w: c_int, + pub h: c_int, + pub internal_format: c_int, +} + +pub const FORMAT_NONE: c_int = 0; +pub const FORMAT_FLAG: c_int = 3; +pub const FORMAT_DOUBLE: c_int = 5; + +pub const EVENT_NONE: c_int = 0; +pub const EVENT_SHUTDOWN: c_int = 1; +pub const EVENT_END_FILE: c_int = 7; +pub const EVENT_FILE_LOADED: c_int = 8; +pub const EVENT_VIDEO_RECONFIG: c_int = 17; +pub const EVENT_PLAYBACK_RESTART: c_int = 21; +pub const EVENT_PROPERTY_CHANGE: c_int = 22; + +pub const END_FILE_ERROR: c_int = 4; + +pub const RENDER_INVALID: c_int = 0; +pub const RENDER_API_TYPE: c_int = 1; +pub const RENDER_OPENGL_INIT_PARAMS: c_int = 2; +pub const RENDER_OPENGL_FBO: c_int = 3; +pub const RENDER_FLIP_Y: c_int = 4; +pub const RENDER_WL_DISPLAY: c_int = 9; +pub const RENDER_SW_SIZE: c_int = 17; +pub const RENDER_SW_FORMAT: c_int = 18; +pub const RENDER_SW_STRIDE: c_int = 19; +pub const RENDER_SW_POINTER: c_int = 20; + +pub const RENDER_UPDATE_FRAME: u64 = 1; + +/// The only major version of the client API whose layout this file matches. +const API_MAJOR: c_ulong = 2; + +/// Why libmpv couldn't be used. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LoadError { + /// `libmpv.so.2` isn't installed. + Missing, + /// It's there, but its client API isn't 2.x. + WrongVersion(u32, u32), + /// It's there, but lacks a function this crate calls. + MissingFunction(&'static str), +} + +impl std::fmt::Display for LoadError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Missing => write!(f, "libmpv isn't installed"), + Self::WrongVersion(major, minor) => write!(f, "libmpv's client API is {major}.{minor}, and {API_MAJOR}.x is needed"), + Self::MissingFunction(name) => write!(f, "libmpv has no {name}"), + } + } +} + +impl std::error::Error for LoadError {} + +pub struct Library { + pub create: unsafe extern "C" fn() -> Handle, + pub initialize: unsafe extern "C" fn(Handle) -> c_int, + pub terminate_destroy: unsafe extern "C" fn(Handle), + pub error_string: unsafe extern "C" fn(c_int) -> *const c_char, + pub set_option_string: unsafe extern "C" fn(Handle, *const c_char, *const c_char) -> c_int, + pub command: unsafe extern "C" fn(Handle, *mut *const c_char) -> c_int, + pub set_property: unsafe extern "C" fn(Handle, *const c_char, c_int, *mut c_void) -> c_int, + pub get_property: unsafe extern "C" fn(Handle, *const c_char, c_int, *mut c_void) -> c_int, + pub get_property_string: unsafe extern "C" fn(Handle, *const c_char) -> *mut c_char, + pub free: unsafe extern "C" fn(*mut c_void), + pub observe_property: unsafe extern "C" fn(Handle, u64, *const c_char, c_int) -> c_int, + pub wait_event: unsafe extern "C" fn(Handle, f64) -> *mut Event, + pub set_wakeup_callback: unsafe extern "C" fn(Handle, Option, *mut c_void), + pub render_create: unsafe extern "C" fn(*mut Handle, Handle, *mut RenderParam) -> c_int, + pub render_set_update_callback: unsafe extern "C" fn(Handle, Option, *mut c_void), + pub render_update: unsafe extern "C" fn(Handle) -> u64, + pub render: unsafe extern "C" fn(Handle, *mut RenderParam) -> c_int, + pub render_report_swap: unsafe extern "C" fn(Handle), + pub render_free: unsafe extern "C" fn(Handle), +} + +// SAFETY: a table of function pointers into a library that stays loaded for the process. +unsafe impl Send for Library {} +// SAFETY: as above. +unsafe impl Sync for Library {} + +static LIBRARY: OnceLock> = OnceLock::new(); + +impl Library { + /// libmpv, opened the first time it's asked for and kept for the life of the process. + pub fn get() -> Result<&'static Library, LoadError> { + LIBRARY.get_or_init(Self::open).as_ref().map_err(Clone::clone) + } + + // Each lookup's type comes from the field it fills, which is the point of the struct. + #[allow(clippy::missing_transmute_annotations)] + fn open() -> Result { + // SAFETY: opening a system library by its versioned name. It's never closed, so the + // pointers below stay good. + let library = unsafe { libc::dlopen(c"libmpv.so.2".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; + if library.is_null() { + return Err(LoadError::Missing); + } + macro_rules! sym { + ($name:literal) => {{ + // SAFETY: looking up a name in the library opened above. + let found = unsafe { libc::dlsym(library, concat!($name, "\0").as_ptr() as *const c_char) }; + if found.is_null() { + return Err(LoadError::MissingFunction($name)); + } + // SAFETY: the field's type is the function's type in libmpv's public headers. + unsafe { std::mem::transmute(found) } + }}; + } + let version: unsafe extern "C" fn() -> c_ulong = sym!("mpv_client_api_version"); + // SAFETY: takes nothing and returns a number. + let version = unsafe { version() }; + if version >> 16 != API_MAJOR { + return Err(LoadError::WrongVersion((version >> 16) as u32, (version & 0xffff) as u32)); + } + Ok(Self { + create: sym!("mpv_create"), + initialize: sym!("mpv_initialize"), + terminate_destroy: sym!("mpv_terminate_destroy"), + error_string: sym!("mpv_error_string"), + set_option_string: sym!("mpv_set_option_string"), + command: sym!("mpv_command"), + set_property: sym!("mpv_set_property"), + get_property: sym!("mpv_get_property"), + get_property_string: sym!("mpv_get_property_string"), + free: sym!("mpv_free"), + observe_property: sym!("mpv_observe_property"), + wait_event: sym!("mpv_wait_event"), + set_wakeup_callback: sym!("mpv_set_wakeup_callback"), + render_create: sym!("mpv_render_context_create"), + render_set_update_callback: sym!("mpv_render_context_set_update_callback"), + render_update: sym!("mpv_render_context_update"), + render: sym!("mpv_render_context_render"), + render_report_swap: sym!("mpv_render_context_report_swap"), + render_free: sym!("mpv_render_context_free"), + }) + } + + /// libmpv's own words for an error code. + pub fn describe(&self, code: c_int) -> String { + // SAFETY: returns a static string for any code, unknown ones included. + let text = unsafe { (self.error_string)(code) }; + if text.is_null() { + return format!("error {code}"); + } + // SAFETY: a static, terminated string, as above. + unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned() + } +} diff --git a/src/helper.rs b/src/helper.rs new file mode 100644 index 0000000..e035599 --- /dev/null +++ b/src/helper.rs @@ -0,0 +1,850 @@ +//! A player in another process, drawing on the CPU into shared memory. +//! +//! libmpv isn't memory-safe and plays whatever files people have, so an app can run it in a +//! copy of itself, inside a jail (`crate::jail`), with a seccomp filter of the app's own on +//! top. The app gives the player one file on a descriptor and a block of shared memory; frames +//! come back in that memory, and everything else as short lines of text on two pipes. +//! Everything the player says is checked before it's believed. +//! +//! The app's side is `start`, `watch`, `Frames` and `Remote`. The player's side is `run`, +//! which the app calls when it's started with its helper argument. + +use std::ffi::c_int; +use std::fs::File; +use std::io::{BufRead, BufReader, Write}; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::os::unix::process::{CommandExt, ExitStatusExt}; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use rustix::event::{PollFd, PollFlags, Timespec, poll}; +use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create}; +use rustix::mm::{MapFlags, ProtFlags, mmap, munmap}; +use rustix::pipe::{PipeFlags, pipe_with}; + +use crate::options::{Options, RenderPath}; +use crate::player::{Event, Player}; +use crate::render::{SwFormat, SwRender}; + +/// How a player ended, besides the codes the app's own sandbox uses. +pub const EXIT_NO_MPV: i32 = 7; +pub const EXIT_CANT_PLAY: i32 = 8; +/// The helper's arguments or setup were wrong: it was started by something other than `start`. +pub const EXIT_BAD_START: i32 = 9; +/// After the size: a file with no picture plays as sound. +const SOUND_ARG: &str = "sound"; + +/// The largest frame the player draws. A bigger window scales it up. +pub const MAX_W: u32 = 3840; +pub const MAX_H: u32 = 2160; +const FRAME_BYTES: usize = MAX_W as usize * MAX_H as usize * 4; +/// Two frames, one being drawn and one showing. Memory only gets used once it's touched. +const SHARED_BYTES: usize = FRAME_BYTES * 2; + +/// Where the file and the frame memory are in the player. +pub const FD_FILE: c_int = 3; +pub const FD_FRAMES: c_int = 4; +/// Longer than any line the player has a reason to say. +const MAX_LINE: usize = 128; +const EXIT_GRACE: Duration = Duration::from_millis(500); +/// A little under one frame at 120 fps. +const DELIVER_GAP: Duration = Duration::from_millis(7); +/// How often the position is reported while it plays. Every other change goes at once. +const REPORT_EVERY: Duration = Duration::from_millis(100); + +// ---- What the two sides say ---- + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Said { + /// It got as far as running, so a failure after this isn't the jail's. + Hello, + Frame { + index: usize, + w: u32, + h: u32, + }, + State(PlayState), + NoVideo, + /// It has no picture, and it's playing as sound, as it was told it could. + Sound, + CantPlay, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct PlayState { + pub position: f64, + pub duration: f64, + pub paused: bool, + pub volume: f64, + pub muted: bool, + /// Stopped on its last frame. + pub ended: bool, +} + +impl PlayState { + fn line(&self) -> String { + format!("state {:.3} {:.3} {} {:.0} {} {}", self.position, self.duration, u8::from(self.paused), self.volume, u8::from(self.muted), u8::from(self.ended)) + } +} + +/// A line from the player, or `None` if it isn't a sensible one. +pub fn parse_said(line: &str) -> Option { + let mut words = line.split_ascii_whitespace(); + let said = match words.next()? { + "hello" => Said::Hello, + "novideo" => Said::NoVideo, + "sound" => Said::Sound, + "cantplay" => Said::CantPlay, + "frame" => { + let index: usize = words.next()?.parse().ok()?; + let w: u32 = words.next()?.parse().ok()?; + let h: u32 = words.next()?.parse().ok()?; + if index > 1 || w == 0 || h == 0 || w > MAX_W || h > MAX_H { + return None; + } + Said::Frame { index, w, h } + } + "state" => { + let number = |word: Option<&str>| word?.parse::().ok().filter(|n| n.is_finite() && *n >= 0.0); + let flag = |word: Option<&str>| match word? { + "0" => Some(false), + "1" => Some(true), + _ => None, + }; + Said::State(PlayState { + position: number(words.next())?, + duration: number(words.next())?, + paused: flag(words.next())?, + volume: number(words.next())?.min(100.0), + muted: flag(words.next())?, + ended: flag(words.next())?, + }) + } + _ => return None, + }; + words.next().is_none().then_some(said) +} + +// ---- The app's side ---- + +/// The frames another process draws. Dropping this hands the memory back. +pub struct Frames { + ptr: *mut std::ffi::c_void, +} + +// SAFETY: mapped read-only here and sealed against resizing, and only `Drop` unmaps it. The +// player can write these pages at any time, so what's read can change mid-frame, and any bytes +// are valid pixels. The worst it can do is a torn or nonsense picture. +unsafe impl Send for Frames {} +// SAFETY: as above. +unsafe impl Sync for Frames {} + +impl Frames { + fn map(fd: &OwnedFd) -> Option { + // SAFETY: a new read-only mapping at an address the kernel chooses, of a file that's + // already that size and can't change size. + let ptr = unsafe { mmap(std::ptr::null_mut(), SHARED_BYTES, ProtFlags::READ, MapFlags::SHARED, fd, 0) }.ok()?; + Some(Self { ptr }) + } + + /// One frame as `0x00RRGGBB` words, Wayland's `XRGB8888`, `w` to a row. `parse_said` has + /// checked the sizes. + pub fn frame(&self, index: usize, w: u32, h: u32) -> &[u32] { + let (w, h) = (w.min(MAX_W) as usize, h.min(MAX_H) as usize); + // SAFETY: two frames of `FRAME_BYTES` are mapped until drop, page-aligned, and any + // bytes are valid `u32`s. The sizes are clamped to one frame. + unsafe { std::slice::from_raw_parts((self.ptr as *const u8).add(index.min(1) * FRAME_BYTES) as *const u32, w * h) } + } +} + +impl Drop for Frames { + fn drop(&mut self) { + // SAFETY: this is the mapping from `map`, and nothing can still borrow it. + let _ = unsafe { munmap(self.ptr, SHARED_BYTES) }; + } +} + +/// Telling a running player what to do. +pub struct Remote { + commands: File, +} + +impl Remote { + /// Never waits: a player too busy to read just misses this one. + pub fn say(&mut self, line: &str) { + let _ = self.commands.write_all(format!("{line}\n").as_bytes()); + } + pub fn set_paused(&mut self, paused: bool) { + self.say(if paused { "pause" } else { "play" }); + } + pub fn seek_by(&mut self, seconds: f64) { + self.say(&format!("seek {seconds:.3}")); + } + /// To a share of the way through, from 0 to 1. + pub fn seek_to_fraction(&mut self, fraction: f64) { + self.say(&format!("seekto {:.3}", fraction.clamp(0.0, 1.0) * 100.0)); + } + pub fn seek_to(&mut self, seconds: f64) { + self.say(&format!("seekat {:.3}", seconds.max(0.0))); + } + pub fn set_volume(&mut self, volume: f64) { + self.say(&format!("volume {:.0}", volume.clamp(0.0, 100.0))); + } + pub fn set_muted(&mut self, muted: bool) { + self.say(if muted { "mute" } else { "unmute" }); + } + /// The size to draw at, in pixels. The frame fits inside it, keeping its shape. + pub fn set_size(&mut self, w: u32, h: u32) { + self.say(&format!("size {} {}", w.clamp(1, MAX_W), h.clamp(1, MAX_H))); + } +} + +/// A player's handles with nothing on the other end, for tests of what an app does with them. +pub fn parts_for_test() -> (Remote, Frames) { + let shared = memfd_create("test", MemfdFlags::CLOEXEC).expect("memfd"); + rustix::fs::ftruncate(&shared, SHARED_BYTES as u64).expect("size"); + let (_read, write) = pipe_with(PipeFlags::CLOEXEC | PipeFlags::NONBLOCK).expect("pipe"); + (Remote { commands: File::from(write) }, Frames::map(&shared).expect("map")) +} + +#[derive(Debug)] +pub enum StartError { + /// The program in `command` isn't there, such as bubblewrap not being installed. + NotFound, + Other(std::io::Error), +} + +impl From for StartError { + fn from(e: std::io::Error) -> Self { + Self::Other(e) + } +} + +impl From for StartError { + fn from(e: rustix::io::Errno) -> Self { + Self::Other(e.into()) + } +} + +/// A player that's been started, for the thread that looks after it. +pub struct Started { + pub child: Child, + pub said: File, + pub remote: Remote, + pub frames: Frames, +} + +/// Starts a player. `command` is how the app runs its helper, ready for this to add the +/// size: its own program with its helper argument, inside `bwrap` if it's jailed. The file +/// goes to the player as descriptor 3 and the frame memory as 4, and nothing else this +/// process has open goes with them. With `sound`, a file with no picture plays, rather than +/// stopping at `Said::NoVideo`. +pub fn start(mut command: Command, file: File, size: (u32, u32), sound: bool) -> Result { + let shared = memfd_create("alias-playback-frames", MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING)?; + rustix::fs::ftruncate(&shared, SHARED_BYTES as u64)?; + // Without this, a player shrinking it would fault the app when it read a frame. + fcntl_add_seals(&shared, SealFlags::SHRINK | SealFlags::GROW | SealFlags::SEAL)?; + let frames = Frames::map(&shared).ok_or_else(|| StartError::Other(std::io::Error::other("can't map the frames")))?; + let (their_commands, our_commands) = pipe_with(PipeFlags::CLOEXEC)?; + let (our_said, their_said) = pipe_with(PipeFlags::CLOEXEC)?; + rustix::io::ioctl_fionbio(&our_commands, true)?; + // Well away from the numbers they're about to be given, so neither lands on the other. + let (file_copy, shared_copy) = (high(&file)?, high(&shared)?); + let (file_fd, shared_fd) = (file_copy.as_raw_fd(), shared_copy.as_raw_fd()); + command.arg(size.0.clamp(1, MAX_W).to_string()).arg(size.1.clamp(1, MAX_H).to_string()); + if sound { + command.arg(SOUND_ARG); + } + command.stdin(Stdio::from(their_commands)).stdout(Stdio::from(their_said)).stderr(Stdio::null()); + // SAFETY: only async-signal-safe calls. + unsafe { + command.pre_exec(move || { + if libc::dup2(file_fd, FD_FILE) < 0 || libc::dup2(shared_fd, FD_FRAMES) < 0 { + return Err(std::io::Error::last_os_error()); + } + // Refusing beats handing the player whatever else this process has open. + if libc::close_range((FD_FRAMES + 1) as libc::c_uint, libc::c_uint::MAX, libc::CLOSE_RANGE_CLOEXEC as libc::c_int) != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let child = command.spawn().map_err(|e| if e.kind() == std::io::ErrorKind::NotFound { StartError::NotFound } else { StartError::Other(e) })?; + drop(command); + Ok(Started { child, said: File::from(our_said), remote: Remote { commands: File::from(our_commands) }, frames }) +} + +/// A copy of `fd` numbered 64 or above, closed on exec. +fn high(fd: &impl AsRawFd) -> std::io::Result { + // SAFETY: duplicating a descriptor we hold, and only taking ownership of a good result. + let copy = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 64) }; + if copy < 0 { + return Err(std::io::Error::last_os_error()); + } + // SAFETY: a new descriptor from the call above, owned by nothing else. + Ok(unsafe { OwnedFd::from_raw_fd(copy) }) +} + +/// What the player has said since it was last asked. Only the latest frame and state matter, +/// so a player talking faster than anyone's listening costs nothing. +#[derive(Default)] +struct Inbox { + hello: bool, + no_video: bool, + sound: bool, + cant_play: bool, + frame: Option, + state: Option, +} + +impl Inbox { + fn hear(&mut self, said: Said) { + match said { + Said::Hello => self.hello = true, + Said::NoVideo => self.no_video = true, + Said::Sound => self.sound = true, + Said::CantPlay => self.cant_play = true, + Said::Frame { .. } => self.frame = Some(said), + Said::State(_) => self.state = Some(said), + } + } + + fn deliver(&mut self, on_said: &mut impl FnMut(Said)) -> bool { + let inbox = std::mem::take(self); + let singles = [(inbox.hello, Said::Hello), (inbox.no_video, Said::NoVideo), (inbox.sound, Said::Sound), (inbox.cant_play, Said::CantPlay)]; + let mut any = false; + for said in singles.into_iter().filter(|s| s.0).map(|s| s.1).chain(inbox.state).chain(inbox.frame) { + on_said(said); + any = true; + } + any + } +} + +/// Reads lines, sorting them into the inbox. Lines come out whole or not at all: one that's +/// too long or not text is skipped, and goes no further than this buffer. +fn read_lines(said: File, inbox: &Mutex, ready: &OwnedFd) { + let mut reader = BufReader::with_capacity(4096, said); + let mut line = Vec::with_capacity(MAX_LINE); + let mut too_long = false; + loop { + let available = match reader.fill_buf() { + Ok(available) => available, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => return, + }; + if available.is_empty() { + return; + } + let (part, had_newline) = match available.iter().position(|&b| b == b'\n') { + Some(at) => (&available[..at], true), + None => (available, false), + }; + too_long |= line.len() + part.len() > MAX_LINE; + if !too_long { + line.extend_from_slice(part); + } + let used = part.len() + usize::from(had_newline); + if had_newline { + if !too_long && let Some(said) = std::str::from_utf8(&line).ok().and_then(parse_said) { + inbox.lock().unwrap_or_else(|e| e.into_inner()).hear(said); + // A full pipe already says there's something to read. + let _ = rustix::io::write(ready, &[1u8]); + } + line.clear(); + too_long = false; + } + reader.consume(used); + } +} + +/// Watches a running player until `cancel` is readable or it stops, passing on what it says. +/// Returns its exit status, or `None` if cancelled. Either way the player is gone afterwards, +/// whatever it does with its pipes, and how much it says makes no difference to how often +/// `on_said` runs. +pub fn watch(mut child: Child, said: File, cancel: &OwnedFd, mut on_said: impl FnMut(Said)) -> Option { + let stop = |child: &mut Child| { + let _ = child.kill(); + let _ = child.wait(); + }; + let Ok((lines_ready, line_written)) = pipe_with(PipeFlags::CLOEXEC | PipeFlags::NONBLOCK) else { + stop(&mut child); + return None; + }; + let inbox = Arc::new(Mutex::new(Inbox::default())); + let reading = inbox.clone(); + // It ends when the pipe does, and it isn't waited for: the player might have passed its + // end on. + let reader = std::thread::Builder::new().name("playback-read".into()).spawn(move || read_lines(said, &reading, &line_written)); + if reader.is_err() { + stop(&mut child); + return None; + } + let mut buf = [0u8; 4096]; + let mut pipe_ended_at: Option = None; + loop { + let mut fds = [PollFd::new(cancel, PollFlags::IN), PollFd::new(&lines_ready, PollFlags::IN)]; + // Waits for as long as it takes while the player runs: no timer at rest. + let (watching, timeout) = match pipe_ended_at { + Some(_) => (1, Some(Timespec { tv_sec: 0, tv_nsec: 5_000_000 })), + None => (2, None), + }; + let _ = poll(&mut fds[..watching], timeout.as_ref()); + if !fds[0].revents().is_empty() { + stop(&mut child); + return None; + } + if pipe_ended_at.is_none() && !fds[1].revents().is_empty() && matches!(rustix::io::read(&lines_ready, &mut buf), Ok(0)) { + pipe_ended_at = Some(Instant::now()); + } + let any = inbox.lock().unwrap_or_else(|e| e.into_inner()).deliver(&mut on_said); + if let Some(ended) = pipe_ended_at { + match child.try_wait() { + Ok(Some(status)) => return Some(status), + // A player with no way to report anything has nothing left to do. + Ok(None) if ended.elapsed() >= EXIT_GRACE => stop(&mut child), + Ok(None) => {} + Err(_) => return None, + } + } else if any { + // However fast the player talks, the app hears about it at this rate at most. + let pause = Timespec { tv_sec: 0, tv_nsec: DELIVER_GAP.subsec_nanos() as _ }; + let mut cancel_only = [PollFd::new(cancel, PollFlags::IN)]; + let _ = poll(&mut cancel_only, Some(&pause)); + } + } +} + +/// How a player ended, read through bubblewrap, which reports a child's signal as 128 and +/// the number. `sandbox_code` is the code the app's helper exits with when its sandbox +/// can't go on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ending { + NoMpv, + NoSandbox, + /// mpv is there, but it wouldn't start, or the file wouldn't play. + PlayerFailed, + SandboxStopped, + JailFailed, + Other, +} + +pub fn ending(status: ExitStatus, said_hello: bool, sandbox_code: i32) -> Ending { + let by_sandbox = status.signal() == Some(libc::SIGSYS) || status.code() == Some(128 + libc::SIGSYS); + match status.code() { + _ if by_sandbox => Ending::SandboxStopped, + Some(EXIT_NO_MPV) => Ending::NoMpv, + Some(code) if code == sandbox_code => Ending::NoSandbox, + Some(EXIT_CANT_PLAY) => Ending::PlayerFailed, + // Bubblewrap's own failures, before the player was ever running. + Some(1) if !said_hello => Ending::JailFailed, + // Something crashed loading libmpv. + _ if !said_hello => Ending::PlayerFailed, + _ => Ending::Other, + } +} + +/// Whether a file is worth trying as a video, from how it starts. Containers that hold only +/// sound get told apart once the player has looked. Ogg is left out, as it's nearly always +/// just sound. +pub fn looks_like_video(head: &[u8]) -> bool { + let at = |offset: usize, magic: &[u8]| head.get(offset..offset + magic.len()) == Some(magic); + // The same container holds photos. + const STILL_BRANDS: [&[u8]; 12] = [b"heic", b"heix", b"heim", b"heis", b"hevc", b"hevm", b"hevs", b"avif", b"mif1", b"mif2", b"msf1", b"crx "]; + if at(4, b"ftyp") { + return !STILL_BRANDS.iter().any(|brand| at(8, brand)); + } + // A packet every 188 bytes, three in a row. + let packets = |first: usize| (0..3).all(|i| at(first + i * 188, &[0x47])); + // These words start plenty of text, so the size before them has to look like one. Text + // never starts with a zero byte, and an atom this early isn't 16 MB. + let padding = at(0, &[0]) && [&b"wide"[..], b"free", b"skip"].iter().any(|atom| at(4, atom)); + padding + || at(4, b"moov") + || at(4, b"mdat") + || at(0, &[0x1a, 0x45, 0xdf, 0xa3]) + || (at(0, b"RIFF") && at(8, b"AVI ")) + || at(0, b"FLV\x01") + || at(0, &[0, 0, 1, 0xba]) + || at(0, &[0x30, 0x26, 0xb2, 0x75]) + || packets(0) + || packets(4) +} + +// ---- The player's side ---- + +/// Wakes the player's loop: from libmpv's threads, and from the thread reading commands. +struct Wake { + pending: Mutex, + ready: Condvar, +} + +impl Wake { + fn signal(&self) { + *self.pending.lock().unwrap_or_else(|e| e.into_inner()) = true; + self.ready.notify_one(); + } + + /// Waits for a signal, or until `deadline` if there is one. + fn wait(&self, deadline: Option) { + let pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + let mut pending = match deadline { + Some(at) => self.ready.wait_timeout_while(pending, at.saturating_duration_since(Instant::now()), |p| !*p).unwrap_or_else(|e| e.into_inner()).0, + None => self.ready.wait_while(pending, |p| !*p).unwrap_or_else(|e| e.into_inner()), + }; + *pending = false; + } +} + +/// The player starts paused until it knows there's a picture, and a press in that time +/// mustn't be forgotten or get ahead of that. +#[derive(Default)] +struct StartGate { + /// Whether it has loaded, and whether it was last asked to pause. + state: Mutex<(bool, bool)>, +} + +impl StartGate { + /// Records what was asked for, and returns whether it can happen now. + fn asked(&self, paused: bool) -> bool { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + state.1 = paused; + state.0 + } + + fn loaded(&self, player: &Player) { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + state.0 = true; + if !state.1 { + let _ = player.set_paused(false); + } + } +} + +/// Runs a player, and never returns. `args` are what follow the app's helper argument; +/// `options` must use the CPU path. `lock_down` runs once libmpv is loaded and started and +/// before the file is opened: the place for limits and a seccomp filter. If it says no, the +/// player exits with `sandbox_code`. +pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: impl FnOnce() -> bool) -> ! { + let parse = |i: usize| args.get(i).and_then(|a| a.parse::().ok()); + let (Some(w), Some(h)) = (parse(0), parse(1)) else { std::process::exit(EXIT_BAD_START) }; + if options.render != RenderPath::Cpu { + std::process::exit(EXIT_BAD_START); + } + let sound_only_plays = args.get(2).is_some_and(|a| a == SOUND_ARG); + // SAFETY: plain integers. + unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL as libc::c_ulong, 0, 0, 0) }; + // Starting paused whatever the app asked: it plays once it's known what it has. + let options = Options { start_paused: true, ..*options }; + let player = match Player::new(&options) { + Ok(player) => player, + Err(crate::player::Error::Load(_)) => std::process::exit(EXIT_NO_MPV), + Err(_) => std::process::exit(EXIT_CANT_PLAY), + }; + let Ok(mut render) = SwRender::new(&player) else { std::process::exit(EXIT_CANT_PLAY) }; + let wake: Arc = Arc::new(Wake { pending: Mutex::new(false), ready: Condvar::new() }); + let (for_events, for_frames) = (wake.clone(), wake.clone()); + player.on_wakeup(move || for_events.signal()); + render.on_update(move || for_frames.signal()); + // SAFETY: the app put memory of this size on this descriptor, sealed against resizing, + // and only this process writes it. + let shared = unsafe { mmap(std::ptr::null_mut(), SHARED_BYTES, ProtFlags::READ | ProtFlags::WRITE, MapFlags::SHARED, std::os::fd::BorrowedFd::borrow_raw(FD_FRAMES), 0) }; + let Ok(shared) = shared else { std::process::exit(EXIT_BAD_START) }; + // SAFETY: the mapping above, kept for the life of the process, and written only through + // this slice. + let shared: &mut [u8] = unsafe { std::slice::from_raw_parts_mut(shared as *mut u8, SHARED_BYTES) }; + if !lock_down() { + std::process::exit(sandbox_code); + } + let said = |line: &str| { + let mut out = std::io::stdout().lock(); + if out.write_all(line.as_bytes()).is_err() || out.write_all(b"\n").is_err() || out.flush().is_err() { + std::process::exit(0); + } + }; + said("hello"); + let size = Arc::new((AtomicU32::new(w.clamp(1, MAX_W)), AtomicU32::new(h.clamp(1, MAX_H)))); + let start = Arc::new(StartGate::default()); + let reader = (player.clone(), size.clone(), start.clone(), wake.clone()); + // The app going away closes this, and the player goes too. + let spawned = std::thread::Builder::new().name("commands".into()).spawn(move || { + for line in std::io::stdin().lock().lines() { + let Ok(line) = line else { break }; + obey(&reader.0, &reader.1, &reader.2, &line); + reader.3.signal(); + } + std::process::exit(0); + }); + if spawned.is_err() { + std::process::exit(EXIT_CANT_PLAY); + } + if player.load_fd(FD_FILE).is_err() { + std::process::exit(EXIT_CANT_PLAY); + } + + let mut next = 0usize; + let mut state = PlayState { volume: 100.0, paused: true, ..PlayState::default() }; + let mut reported = String::new(); + let mut last_report = Instant::now() - REPORT_EVERY; + let mut last_size = (0, 0); + let mut have_video = false; + let mut natural: Option<(f64, f64)> = None; + loop { + // Waits with no timer unless a position change is waiting to be reported. + let line = state.line(); + let deadline = (line != reported).then_some(last_report + REPORT_EVERY); + wake.wait(deadline); + let mut urgent = false; + while let Some(event) = player.next_event() { + match event { + Event::Shutdown => std::process::exit(0), + Event::Loaded { video } => { + have_video = video; + if video { + start.loaded(&player); + } else if sound_only_plays { + said("sound"); + start.loaded(&player); + } else { + said("novideo"); + } + } + Event::Failed => said("cantplay"), + Event::VideoChanged => { + natural = player.double(c"dwidth").zip(player.double(c"dheight")).filter(|n| n.0 > 0.0 && n.1 > 0.0); + last_size = (0, 0); + } + Event::Position(at) => state.position = at, + Event::Duration(d) => (state.duration, urgent) = (d, true), + Event::Paused(p) => (state.paused, urgent) = (p, true), + Event::Volume(v) => (state.volume, urgent) = (v, true), + Event::Muted(m) => (state.muted, urgent) = (m, true), + Event::Ended(e) => (state.ended, urgent) = (e, true), + Event::Restarted => urgent = true, + } + } + // The position goes at most every `REPORT_EVERY`; anything a person did goes at once. + let line = state.line(); + if line != reported && (urgent || last_report.elapsed() >= REPORT_EVERY) { + said(&line); + reported = line; + last_report = Instant::now(); + } + let new_frame = render.new_frame(); + let wanted = (size.0.load(Ordering::Relaxed), size.1.load(Ordering::Relaxed)); + let Some(natural) = natural.filter(|_| have_video) else { continue }; + if new_frame || wanted != last_size { + let (fw, fh) = fit(natural, wanted); + let frame = &mut shared[next * FRAME_BYTES..(next + 1) * FRAME_BYTES]; + if render.render(fw, fh, fw as usize * 4, SwFormat::Bgr0, frame).is_ok() { + said(&format!("frame {next} {fw} {fh}")); + next = 1 - next; + last_size = wanted; + } + } + } +} + +/// The largest size with the picture's shape that fits in `wanted`, at least one pixel. +fn fit(natural: (f64, f64), wanted: (u32, u32)) -> (u32, u32) { + let scale = (wanted.0 as f64 / natural.0).min(wanted.1 as f64 / natural.1); + (((natural.0 * scale).round() as u32).clamp(1, MAX_W), ((natural.1 * scale).round() as u32).clamp(1, MAX_H)) +} + +/// Only ever these. Anything else from the pipe is ignored. +fn obey(player: &Player, size: &(AtomicU32, AtomicU32), start: &StartGate, line: &str) { + let mut words = line.split_ascii_whitespace(); + let number = |word: Option<&str>| word.and_then(|w| w.parse::().ok()).filter(|n| n.is_finite()); + let _ = match words.next() { + Some("pause") if start.asked(true) => player.set_paused(true), + Some("play") if start.asked(false) => player.play(), + Some("mute") => player.set_muted(true), + Some("unmute") => player.set_muted(false), + Some("seek") => number(words.next()).map_or(Ok(()), |by| player.seek_by(by)), + Some("seekto") => number(words.next()).map_or(Ok(()), |to| player.seek_to_fraction(to / 100.0)), + Some("seekat") => number(words.next()).map_or(Ok(()), |at| player.seek_to(at)), + Some("volume") => number(words.next()).map_or(Ok(()), |v| player.set_volume(v)), + Some("size") => { + if let (Some(w), Some(h)) = (number(words.next()), number(words.next())) { + size.0.store((w as u32).clamp(1, MAX_W), Ordering::Relaxed); + size.1.store((h as u32).clamp(1, MAX_H), Ordering::Relaxed); + } + Ok(()) + } + _ => Ok(()), + }; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sensible_lines_parse() { + assert_eq!(parse_said("hello"), Some(Said::Hello)); + assert_eq!(parse_said("frame 1 640 360"), Some(Said::Frame { index: 1, w: 640, h: 360 })); + let state = PlayState { position: 1.5, duration: 10.0, paused: true, volume: 50.0, muted: false, ended: true }; + assert_eq!(parse_said("state 1.5 10 1 50 0 1"), Some(Said::State(state))); + assert_eq!(parse_said(&state.line()), Some(Said::State(state)), "what the player says, the app reads"); + assert_eq!(parse_said("novideo"), Some(Said::NoVideo)); + assert_eq!(parse_said("sound"), Some(Said::Sound)); + } + + #[test] + fn a_player_cant_make_the_app_read_past_its_frames() { + for line in ["frame 2 10 10", "frame 0 3841 10", "frame 0 10 2161", "frame 0 0 10", "frame 0 10 0", "frame 0 4294967295 4294967295", "frame -1 10 10", "frame 0 10"] { + assert_eq!(parse_said(line), None, "{line}"); + } + } + + #[test] + fn nonsense_from_a_player_is_ignored() { + for line in + ["", "exec /bin/sh", "hello there", "state nan 1 0 1 0 0", "state inf 1 0 1 0 0", "state -1 1 0 1 0 0", "state 1 1 0", "state 1 1 2 1 0 0", "frame 0 10 10 extra", "state 1 1 0 1 0 0 0"] + { + assert_eq!(parse_said(line), None, "{line}"); + } + } + + #[test] + fn volume_from_a_player_stays_in_range() { + let Some(Said::State(state)) = parse_said("state 0 0 0 900 0 0") else { panic!() }; + assert_eq!(state.volume, 100.0); + } + + #[test] + fn frames_keep_their_shape_and_fit() { + assert_eq!(fit((1920.0, 1080.0), (640, 640)), (640, 360)); + assert_eq!(fit((1080.0, 1920.0), (640, 640)), (360, 640)); + assert_eq!(fit((7680.0, 4320.0), (7680, 4320)), (MAX_W, MAX_H), "never past the shared memory"); + assert_eq!(fit((10000.0, 1.0), (100, 100)), (100, 1), "never zero"); + } + + #[test] + fn video_files_are_told_from_other_things() { + assert!(looks_like_video(b"\0\0\0\x20ftypisom")); + assert!(looks_like_video(&[0x1a, 0x45, 0xdf, 0xa3, 0])); + assert!(looks_like_video(b"RIFF\0\0\0\0AVI LIST")); + assert!(!looks_like_video(b"RIFF\0\0\0\0WAVEfmt ")); + assert!(looks_like_video(b"\0\0\0\x14ftypqt "), "a .mov"); + assert!(looks_like_video(b"\0\0\0\x08wide\0\0\0\0mdat"), "an old .mov"); + assert!(!looks_like_video(b"\0\0\0\x18ftypheic"), "a phone photo"); + assert!(!looks_like_video(b"\0\0\0\x18ftypavif")); + assert!(!looks_like_video(b"\0\0\0\x18ftypmif1")); + assert!(!looks_like_video(b"FLV is a format, says this note")); + assert!(!looks_like_video(b"The free software movement"), "words that look like atoms"); + assert!(!looks_like_video(b"Our wide range of goods")); + assert!(!looks_like_video(b"\0\0\0\x18ftypcrx "), "a Canon raw photo"); + let mut stream = vec![0u8; 400]; + (stream[0], stream[188], stream[376]) = (0x47, 0x47, 0x47); + assert!(looks_like_video(&stream), "a transport stream"); + stream[376] = 0; + assert!(!looks_like_video(&stream), "a G here and there isn't one"); + assert!(!looks_like_video(b"just some words")); + assert!(!looks_like_video(b"")); + } + + fn player(script: &str) -> (Child, File) { + let (read, write) = pipe_with(PipeFlags::CLOEXEC).unwrap(); + let child = Command::new("sh").args(["-c", script]).stdout(Stdio::from(write)).stdin(Stdio::null()).stderr(Stdio::null()).spawn().unwrap(); + (child, File::from(read)) + } + + fn cancel_fd() -> OwnedFd { + rustix::event::eventfd(0, rustix::event::EventfdFlags::CLOEXEC | rustix::event::EventfdFlags::NONBLOCK).unwrap() + } + + fn cancel_after(cancel: &OwnedFd, wait: Duration) { + let cancel = cancel.try_clone().unwrap(); + std::thread::spawn(move || { + std::thread::sleep(wait); + rustix::io::write(&cancel, &1u64.to_ne_bytes()).unwrap(); + }); + } + + /// Fails rather than hangs the test run if `watch` never returns. + fn watched(script: &str, cancel: Option) -> (Option, Vec, Duration) { + let (tx, rx) = std::sync::mpsc::channel(); + let (child, said) = player(script); + let token = cancel_fd(); + if let Some(wait) = cancel { + cancel_after(&token, wait); + } + std::thread::spawn(move || { + let start = Instant::now(); + let mut heard = Vec::new(); + let status = watch(child, said, &token, |s| heard.push(s)); + let _ = tx.send((status, heard, start.elapsed())); + }); + rx.recv_timeout(Duration::from_secs(20)).expect("watch came back") + } + + #[test] + fn a_normal_exit_is_seen_with_its_code_and_everything_said() { + let (status, heard, _) = watched("echo hello; echo frame 0 10 10; exit 8", None); + assert_eq!(status.unwrap().code(), Some(8)); + assert!(heard.contains(&Said::Hello) && heard.contains(&Said::Frame { index: 0, w: 10, h: 10 }), "{heard:?}"); + } + + #[test] + fn closing_its_output_and_carrying_on_doesnt_hide_a_player() { + let (status, _, took) = watched("exec 1>&-; exec sleep 30", None); + assert_eq!(status.unwrap().signal(), Some(libc::SIGKILL), "it has nothing left to do"); + assert!(took < Duration::from_secs(5)); + } + + #[test] + fn cancelling_works_after_its_output_has_closed() { + let (status, _, took) = watched("exec 1>&-; exec sleep 30", Some(Duration::from_millis(50))); + assert!(status.is_none()); + assert!(took < Duration::from_secs(5)); + } + + #[test] + fn cancelling_works_while_it_says_nothing() { + let (status, _, took) = watched("exec sleep 30", Some(Duration::from_millis(50))); + assert!(status.is_none()); + assert!(took < Duration::from_secs(5)); + } + + #[test] + fn bytes_that_arent_text_are_skipped_and_it_keeps_listening() { + let (status, heard, _) = watched("printf '\\377\\376\\n'; echo hello; exit 3", None); + assert_eq!(status.unwrap().code(), Some(3)); + assert_eq!(heard, [Said::Hello]); + } + + #[test] + fn a_line_with_no_end_costs_nothing_and_later_lines_still_count() { + // Half a gigabyte with no newline, then a real line. Memory is limited so this can't + // pass by luck. + let script = "ulimit -v 200000; head -c 500000000 /dev/zero; echo; echo hello; exit 3"; + let (status, heard, _) = watched(script, None); + assert_eq!(status.unwrap().code(), Some(3)); + assert_eq!(heard, [Said::Hello]); + } + + #[test] + fn a_flood_is_cut_down_to_a_steady_rate_and_can_still_be_cancelled() { + let (status, heard, took) = watched("yes 'frame 0 1 1'", Some(Duration::from_millis(500))); + assert!(status.is_none()); + assert!(took < Duration::from_secs(5), "{took:?}"); + assert!(!heard.is_empty() && heard.len() < 150, "{} deliveries in half a second", heard.len()); + } + + #[test] + fn endings_are_told_apart_even_through_bubblewrap() { + const SANDBOX: i32 = 6; + let exit = |code: i32| ExitStatus::from_raw(code << 8); + assert_eq!(ending(exit(128 + libc::SIGSYS), true, SANDBOX), Ending::SandboxStopped, "how bubblewrap reports it"); + assert_eq!(ending(ExitStatus::from_raw(libc::SIGSYS), false, SANDBOX), Ending::SandboxStopped); + assert_eq!(ending(exit(EXIT_NO_MPV), false, SANDBOX), Ending::NoMpv); + assert_eq!(ending(exit(EXIT_CANT_PLAY), false, SANDBOX), Ending::PlayerFailed, "not the jail's fault"); + assert_eq!(ending(exit(SANDBOX), false, SANDBOX), Ending::NoSandbox); + assert_eq!(ending(exit(1), false, SANDBOX), Ending::JailFailed); + assert_eq!(ending(exit(128 + libc::SIGSEGV), false, SANDBOX), Ending::PlayerFailed, "a crash isn't the jail's fault"); + assert_eq!(ending(exit(0), true, SANDBOX), Ending::Other); + } +} diff --git a/src/jail.rs b/src/jail.rs new file mode 100644 index 0000000..bf66d7e --- /dev/null +++ b/src/jail.rs @@ -0,0 +1,121 @@ +//! The bubblewrap jail a helper player runs in: no home, no network, no other processes, +//! read-only system files, and only the descriptors `helper::start` hands it. An app adds a +//! seccomp filter of its own inside, through `helper::run`'s `lock_down`. +//! +//! What this doesn't stop: code that took over the player can read the one file and system +//! files, draw into its frames, and use the sound socket. A sound server normally lets its +//! clients record too, so with sound on that can include the microphone. + +use std::ffi::OsStr; +use std::os::unix::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// The jail every player gets, whatever the file: each bubblewrap option with its values. +pub const RULES: &[(&str, &[&str])] = &[ + // The process: alone, without privileges, and gone when the app is. + ("--unshare-all", &[]), + ("--cap-drop", &["ALL"]), + ("--new-session", &[]), + ("--die-with-parent", &[]), + // System files, read-only. No /proc: /proc/self/mem would write to code pages without + // asking for executable memory. + ("--ro-bind", &["/usr", "/usr"]), + ("--symlink", &["usr/bin", "/bin"]), + ("--symlink", &["usr/lib", "/lib"]), + ("--symlink", &["usr/lib", "/lib64"]), + // Finding libraries without this works, but searches every folder for each one. + ("--ro-bind-try", &["/etc/ld.so.cache", "/etc/ld.so.cache"]), + ("--dev", &["/dev"]), + ("--tmpfs", &["/tmp"]), + // An environment with nothing of the user's in it. + ("--clearenv", &[]), + ("--setenv", &["HOME", "/tmp"]), + ("--setenv", &["LC_ALL", "C"]), +]; + +/// Where the app's own program and the sound socket appear inside the jail. +pub const JAILED_SELF: &str = "/playback-helper"; +const JAILED_SOUND: &str = "/sound-server"; + +/// bubblewrap's arguments for running `executable` jailed, up to and including the program +/// to run. The helper's own arguments go after. +pub fn arguments(executable: &Path, sound_socket: Option<&Path>) -> Vec { + let mut args = Vec::new(); + let mut rule = |option: &str, values: &[&str]| { + args.push(option.to_owned()); + args.extend(values.iter().map(|value| (*value).to_owned())); + }; + for (option, values) in RULES { + rule(option, values); + } + rule("--ro-bind", &[&executable.to_string_lossy(), JAILED_SELF]); + if let Some(socket) = sound_socket { + rule("--ro-bind", &[&socket.to_string_lossy(), JAILED_SOUND]); + rule("--setenv", &["PULSE_SERVER", &format!("unix:{JAILED_SOUND}")]); + } + rule("--", &[JAILED_SELF]); + args +} + +/// The command that runs this program jailed with `helper_arg`, ready for `helper::start`. +/// With `sound`, the session's PulseAudio socket goes in too, if there is one. +pub fn command(helper_arg: &str, sound: bool) -> std::io::Result { + let mut command = Command::new("bwrap"); + let socket = if sound { sound_socket() } else { None }; + command.args(arguments(&own_exe()?, socket.as_deref())).arg(helper_arg); + Ok(command) +} + +/// The session's sound server, where PulseAudio clients look for it. PipeWire serves this +/// socket too. +pub fn sound_socket() -> Option { + let runtime_dir = PathBuf::from(std::env::var_os("XDG_RUNTIME_DIR")?); + Some(runtime_dir.join("pulse/native")).filter(|path| path.exists()) +} + +/// This program, to start again as a helper. After a package upgrade replaces the running +/// file, `current_exe` names ".../app (deleted)", which can't be started: the new file at the +/// same path is used then. Without one, `/proc/self/exe` still reaches the running file. +pub fn own_exe() -> std::io::Result { + Ok(undeleted(std::env::current_exe()?, Path::new("/proc/self/exe"))) +} + +fn undeleted(exe: PathBuf, running: &Path) -> PathBuf { + let Some(path) = exe.as_os_str().as_bytes().strip_suffix(b" (deleted)").map(|b| Path::new(OsStr::from_bytes(b))) else { return exe }; + if path.is_file() { path.to_path_buf() } else { running.to_path_buf() } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_jail_shows_what_it_should_and_no_more() { + let words = arguments(Path::new("/opt/app"), None); + let text = words.join(" "); + assert!(text.contains("--unshare-all") && text.contains("--die-with-parent") && text.contains("--clearenv") && text.contains("--cap-drop ALL")); + assert!(text.contains("--ro-bind /opt/app /playback-helper")); + assert!(!text.contains("PULSE_SERVER"), "no socket, no sound"); + assert!(!text.contains(" /home") && !text.contains("/run/user") && !text.contains("/proc")); + assert_eq!(words.last().unwrap(), JAILED_SELF); + let position = |word: &str| words.iter().position(|w| w == word).unwrap(); + assert!(position("--clearenv") < position("--setenv"), "clearing the environment after setting it would undo it"); + let with_sound = arguments(Path::new("/opt/app"), Some(Path::new("/run/user/1000/pulse/native"))).join(" "); + assert!(with_sound.contains("--ro-bind /run/user/1000/pulse/native /sound-server")); + assert!(with_sound.contains("--setenv PULSE_SERVER unix:/sound-server")); + } + + #[test] + fn an_upgraded_program_is_started_from_its_new_file() { + let dir = std::env::temp_dir().join(format!("alias-playback-exe-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let new = dir.join("app"); + std::fs::write(&new, b"").unwrap(); + let running = Path::new("/proc/self/exe"); + assert_eq!(undeleted(dir.join("app (deleted)"), running), new); + assert_eq!(undeleted(dir.join("gone (deleted)"), running), running, "no new file: the running one"); + assert_eq!(undeleted(new.clone(), running), new); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..316bdf3 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,26 @@ +//! libmpv playback for Alias Project's apps: Alias View, Gannet and Nitrate. +//! +//! - [`Player`]: one libmpv player, set up from [`Options`], with the events every app needs +//! (position, duration, pause, volume, mute, end). +//! - [`SwRender`] and [`GlRender`]: drawing its frames on the CPU into memory, or with OpenGL. +//! - [`options::colour`]: the colour settings for each way of drawing, in one place, proved +//! by the colour tests in `tests/colour.rs`. +//! - [`helper`] and [`jail`]: a player in another process, jailed, with frames in shared +//! memory, for files nobody has vouched for. +//! +//! Every app behaves the same where it should: a video stops on its last frame instead of +//! closing, and nothing of the user's own mpv setup is read. +//! +//! libmpv is opened at run time, so an app using this starts without it and only loses +//! playback. + +pub mod ffi; +pub mod helper; +pub mod jail; +pub mod options; +pub mod player; +pub mod render; + +pub use options::{Audio, Hwdec, Options, RenderPath}; +pub use player::{Error, Event, Player}; +pub use render::{GlRender, SwFormat, SwRender}; diff --git a/src/options.rs b/src/options.rs new file mode 100644 index 0000000..bdf84a4 --- /dev/null +++ b/src/options.rs @@ -0,0 +1,199 @@ +//! How every app's player is set up, and the colour settings for each way of drawing. +//! +//! The apps differ in only a few choices (where frames are drawn, hardware decoding, sound, +//! cover art), so those are fields, and everything else is the same for all of them. + +/// Where frames are drawn. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RenderPath { + /// libmpv's software renderer, into memory the app gives it: Gannet's jailed preview. + Cpu, + /// libmpv's OpenGL renderer, into the app's framebuffer: Nitrate. + Gpu, +} + +/// Whether to decode on the graphics card. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Hwdec { + Off, + /// NVDEC, VA-API or V4L2 where the card and the file allow, and the CPU where they don't. + Auto, +} + +/// Where sound goes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Audio { + /// Sound is decoded and thrown away, so timing is the same, and no sound server is opened. + Off, + PipeWire, + /// PipeWire's PulseAudio socket, or PulseAudio itself. A jail can hand a player this one + /// socket and nothing else. + Pulse, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Options { + pub render: RenderPath, + pub hwdec: Hwdec, + pub audio: Audio, + /// Show a music file's embedded cover art as its picture. Pictures in files beside it are + /// never looked for: a jailed player can't see them, and the rest shouldn't differ. + pub cover_art: bool, + /// Start paused. Gannet's preview starts paused until it knows the file has a picture, so + /// a sound-only file doesn't play for a moment first. + pub start_paused: bool, +} + +impl Options { + /// A software-rendered player with no hardware decoding: Gannet's preview. + pub const fn cpu() -> Self { + Self { render: RenderPath::Cpu, hwdec: Hwdec::Off, audio: Audio::Off, cover_art: false, start_paused: true } + } + + /// Every option, name and value, in the order they're set. + pub fn pairs(&self) -> Vec<(&'static str, &'static str)> { + let mut pairs = BASE.to_vec(); + pairs.push(("hwdec", hwdec_value(self.render, self.hwdec))); + pairs.push(("ao", audio_value(self.audio))); + pairs.push(("audio-display", if self.cover_art { "embedded-first" } else { "no" })); + pairs.push(("pause", if self.start_paused { "yes" } else { "no" })); + pairs + } +} + +/// The value of `hwdec` for a path: the methods to try, in order, before the CPU. The +/// software renderer can only draw frames that are in memory, so it gets the copy-back ones. +/// +/// Named rather than libmpv's `auto-safe`, which also tries VDPAU. On NVIDIA, VDPAU accepts +/// H.264 4:4:4, which the card can't decode, then fails every frame without falling back to +/// the CPU, so the video never starts (the GPU colour bench found it). NVDEC turns it down +/// properly. Vulkan decoding is left out as libmpv's `auto-safe` leaves it out. +fn hwdec_value(render: RenderPath, hwdec: Hwdec) -> &'static str { + match (hwdec, render) { + (Hwdec::Off, _) => "no", + (Hwdec::Auto, RenderPath::Cpu) => "nvdec-copy,vaapi-copy,v4l2m2m-copy", + (Hwdec::Auto, RenderPath::Gpu) => "nvdec,vaapi,nvdec-copy,vaapi-copy,v4l2m2m-copy", + } +} + +fn audio_value(audio: Audio) -> &'static str { + match audio { + Audio::Off => "null", + Audio::PipeWire => "pipewire", + Audio::Pulse => "pulse", + } +} + +/// The same for every app. +const BASE: &[(&str, &str)] = &[ + // Nothing of the user's mpv setup, or left over from last time. + ("config", "no"), + ("load-scripts", "no"), + ("load-auto-profiles", "no"), + ("resume-playback", "no"), + ("save-position-on-quit", "no"), + // Only the one file: no looking for files beside it, or for streams online. + ("sub-auto", "no"), + ("sid", "no"), + ("audio-file-auto", "no"), + ("cover-art-auto", "no"), + ("ytdl", "no"), + // The app has the controls, so no terminal, key bindings or on-screen display. + ("terminal", "no"), + ("input-default-bindings", "no"), + ("input-builtin-bindings", "no"), + ("osc", "no"), + ("osd-level", "0"), + ("vo", "libmpv"), + // A video ends on its last frame, paused, instead of closing, in every app. The player + // stays alive with nothing loaded too, so the app's controls keep working. + ("idle", "yes"), + ("keep-open", "yes"), + ("keep-open-pause", "yes"), + ("volume-max", "100"), +]; + +/// mpv's built-in scripts, for a window and an on-screen display these players don't have. +/// Each is an interpreter they have no use for, and Lua's compiler asks for executable +/// memory, which a jail's filter rightly refuses. Not every version has all of them, so an +/// unknown one is skipped. +pub const BUILT_IN_SCRIPTS: &[&str] = &["load-stats-overlay", "load-console", "load-osd-console", "load-commands", "load-select", "load-positioning", "load-context-menu"]; + +/// The colour settings, for every app at once. The colour tests (`tests/colour.rs`) prove +/// each path draws a clip's patches within two steps of the colours they were made from. +/// +/// These are set after the rest, and a libmpv that doesn't know one only loses that fix. +pub fn colour(render: RenderPath) -> &'static [(&'static str, &'static str)] { + match render { + // The software renderer's converter, zimg, lifts the darks of a video tagged with the + // sRGB transfer (ALI-2418: Tarnished's #121C24 drew as #1D282F). Labelling every + // picture BT.1886 before it's converted fixes that, and the other SDR tags come out + // the same either way, which the colour tests check. Turning zimg off would fix it + // too, but swscale works on one thread: about ten times as long a frame on x86_64 + // and two to three times on an M1, too slow for 4K. + RenderPath::Cpu => &[("vf", "format=gamma=bt.1886")], + // The GPU renderer draws every SDR tag correctly as it is. + RenderPath::Gpu => &[], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn value(options: &Options, name: &str) -> Option<&'static str> { + options.pairs().into_iter().rev().find(|(n, _)| *n == name).map(|(_, v)| v) + } + + #[test] + fn every_app_stops_on_the_last_frame() { + for render in [RenderPath::Cpu, RenderPath::Gpu] { + let options = Options { render, ..Options::cpu() }; + assert_eq!(value(&options, "keep-open"), Some("yes")); + assert_eq!(value(&options, "keep-open-pause"), Some("yes")); + assert_eq!(value(&options, "idle"), Some("yes")); + } + } + + #[test] + fn nothing_of_the_users_mpv_is_read() { + let options = Options::cpu(); + for (name, expected) in [("config", "no"), ("load-scripts", "no"), ("ytdl", "no"), ("sub-auto", "no"), ("cover-art-auto", "no"), ("audio-file-auto", "no")] { + assert_eq!(value(&options, name), Some(expected), "{name}"); + } + } + + #[test] + fn the_software_renderer_only_gets_frames_in_memory() { + let cpu = Options { hwdec: Hwdec::Auto, ..Options::cpu() }; + assert!(value(&cpu, "hwdec").unwrap().split(',').all(|method| method.ends_with("-copy"))); + let gpu = Options { render: RenderPath::Gpu, ..cpu }; + assert!(value(&gpu, "hwdec").unwrap().starts_with("nvdec,vaapi,")); + for options in [cpu, gpu] { + assert!(!value(&options, "hwdec").unwrap().contains("vdpau"), "VDPAU stalls on what it can't decode"); + } + assert_eq!(value(&Options::cpu(), "hwdec"), Some("no")); + } + + #[test] + fn no_sound_opens_no_sound_server() { + let options = Options::cpu(); + assert_eq!(value(&options, "ao"), Some("null")); + let pipewire = Options { audio: Audio::PipeWire, ..options }; + assert_eq!(value(&pipewire, "ao"), Some("pipewire")); + } + + #[test] + fn cover_art_only_when_asked_and_only_from_the_file() { + assert_eq!(value(&Options::cpu(), "audio-display"), Some("no")); + let music = Options { cover_art: true, ..Options::cpu() }; + assert_eq!(value(&music, "audio-display"), Some("embedded-first")); + assert_eq!(value(&music, "cover-art-auto"), Some("no")); + } + + #[test] + fn the_srgb_fix_is_only_on_the_software_path() { + assert_eq!(colour(RenderPath::Cpu), &[("vf", "format=gamma=bt.1886")]); + assert!(colour(RenderPath::Gpu).is_empty()); + } +} diff --git a/src/player.rs b/src/player.rs new file mode 100644 index 0000000..6ddc05c --- /dev/null +++ b/src/player.rs @@ -0,0 +1,368 @@ +//! A libmpv player: setting it up, telling it what to do, and hearing what it does. + +use std::ffi::{CStr, CString, c_char, c_int, c_void}; +use std::os::fd::RawFd; +use std::os::unix::ffi::OsStrExt; +use std::path::Path; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use crate::ffi::{self, Library}; +use crate::options::{self, Options}; + +/// What went wrong, in libmpv's words where it gave some. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + Load(ffi::LoadError), + /// A libmpv call failed: what was being done, and libmpv's reason. + Mpv { + doing: String, + reason: String, + }, + /// A name or value had a zero byte in it, which C strings can't hold. + Nul, + /// A frame buffer too small for the size asked for, or not aligned as libmpv needs. + Buffer, +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Load(e) => e.fmt(f), + Self::Mpv { doing, reason } => write!(f, "{doing}: {reason}"), + Self::Nul => write!(f, "a zero byte in a name or value"), + Self::Buffer => write!(f, "the frame buffer doesn't fit the size asked for"), + } + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(e: ffi::LoadError) -> Self { + Self::Load(e) + } +} + +/// Something the player did. Property changes arrive once on starting to watch them and then +/// whenever they change, so an app that applies each one is always in step. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Event { + /// A file has been opened. `video` says whether it has a picture to draw: a music file's + /// cover art counts when cover art is on. + Loaded { + video: bool, + }, + /// The file couldn't be played. + Failed, + /// Seconds from the start. + Position(f64), + /// Seconds, once it's known. + Duration(f64), + Paused(bool), + /// 0 to 100. + Volume(f64), + Muted(bool), + /// `true` once it has stopped on its last frame, and `false` when it leaves it. + Ended(bool), + /// The picture's size or format changed, the first frame included. + VideoChanged, + /// Playing again after loading or a seek. + Restarted, + /// The player is shutting down. + Shutdown, +} + +/// The properties every app watches, by the number libmpv hands back with each change. +const WATCHED: &[(&CStr, c_int)] = &[ + (c"time-pos", ffi::FORMAT_DOUBLE), + (c"duration", ffi::FORMAT_DOUBLE), + (c"pause", ffi::FORMAT_FLAG), + (c"volume", ffi::FORMAT_DOUBLE), + (c"mute", ffi::FORMAT_FLAG), + (c"eof-reached", ffi::FORMAT_FLAG), +]; + +type Wakeup = Box; + +/// The handle itself. It's destroyed when the last owner goes, so a render context, which +/// holds one, is always freed before it. +pub(crate) struct Core { + pub(crate) lib: &'static Library, + pub(crate) handle: ffi::Handle, + /// Only one thread may wait for events at a time, and an event's data lasts until the + /// next wait, so waiting and reading happen under this. + events: Mutex<()>, + /// Every wakeup callback ever set, kept until the handle is gone, as libmpv may still be + /// running one when it's replaced. Boxed twice so libmpv's pointer, to the inner box, stays + /// put when the list grows. + #[allow(clippy::vec_box)] + wakeups: Mutex>>, +} + +// SAFETY: libmpv's client API may be called from any thread, and the one call that mustn't +// run on two at once, waiting for events, is behind `events`. +unsafe impl Send for Core {} +// SAFETY: as above. +unsafe impl Sync for Core {} + +impl Drop for Core { + fn drop(&mut self) { + // SAFETY: the handle is live and nothing else owns it. Every render context held an + // `Arc` of this, so they've all been freed. After this, no callback runs. + unsafe { (self.lib.terminate_destroy)(self.handle) }; + } +} + +/// A libmpv player. Cheap to clone: every clone is the same player, and it stops when the +/// last one is dropped. +#[derive(Clone)] +pub struct Player { + pub(crate) core: Arc, +} + +impl Player { + /// A player set up with `options` and the colour settings for its path, watching the + /// properties behind `Event`. Nothing is loaded yet. + pub fn new(options: &Options) -> Result { + let lib = Library::get()?; + // SAFETY: no preconditions, and the result is checked. + let handle = unsafe { (lib.create)() }; + if handle.is_null() { + return Err(Error::Mpv { doing: "starting libmpv".into(), reason: "out of memory".into() }); + } + let core = Core { lib, handle, events: Mutex::new(()), wakeups: Mutex::new(Vec::new()) }; + for (name, value) in options.pairs() { + core.set_option(name, value)?; + } + // Best effort from here: each of these only matters on a libmpv that has it. + for (name, value) in options::colour(options.render) { + let _ = core.set_option(name, value); + } + for name in options::BUILT_IN_SCRIPTS { + let _ = core.set_option(name, "no"); + } + // SAFETY: a live handle, initialized once. + let code = unsafe { (lib.initialize)(handle) }; + if code < 0 { + return Err(Error::Mpv { doing: "starting libmpv".into(), reason: lib.describe(code) }); + } + for (i, (name, format)) in WATCHED.iter().enumerate() { + // SAFETY: a live handle, a terminated name and a format libmpv knows. + let code = unsafe { (lib.observe_property)(handle, i as u64 + 1, name.as_ptr(), *format) }; + if code < 0 { + return Err(Error::Mpv { doing: format!("watching {}", name.to_string_lossy()), reason: lib.describe(code) }); + } + } + Ok(Self { core: Arc::new(core) }) + } + + /// Runs a command, such as `["seek", "5", "relative"]`. Each word is passed as it is, + /// so a file name needs no quoting. + pub fn command(&self, words: &[&[u8]]) -> Result<(), Error> { + let owned = words.iter().map(|w| CString::new(*w).map_err(|_| Error::Nul)).collect::, _>>()?; + let mut pointers: Vec<*const c_char> = owned.iter().map(|w| w.as_ptr()).chain([std::ptr::null()]).collect(); + // SAFETY: a live handle and a null-terminated list of strings that outlive the call. + let code = unsafe { (self.core.lib.command)(self.core.handle, pointers.as_mut_ptr()) }; + if code < 0 { + let doing = words.iter().map(|w| String::from_utf8_lossy(w)).collect::>().join(" "); + return Err(Error::Mpv { doing, reason: self.core.lib.describe(code) }); + } + Ok(()) + } + + /// Opens a file, in place of whatever was playing. + pub fn load(&self, path: &Path) -> Result<(), Error> { + self.command(&[b"loadfile", path.as_os_str().as_bytes()]) + } + + /// Opens a file this process has open, for a player that can't see the file system. + pub fn load_fd(&self, fd: RawFd) -> Result<(), Error> { + self.command(&[b"loadfile", format!("fd://{fd}").as_bytes()]) + } + + pub fn set_paused(&self, paused: bool) -> Result<(), Error> { + self.set_flag(c"pause", paused) + } + + /// Plays, from the start if it had stopped on its last frame: what a play button does. + pub fn play(&self) -> Result<(), Error> { + if self.flag(c"eof-reached") == Some(true) { + self.command(&[b"seek", b"0", b"absolute"])?; + } + self.set_paused(false) + } + + pub fn seek_by(&self, seconds: f64) -> Result<(), Error> { + self.command(&[b"seek", format!("{seconds:.3}").as_bytes(), b"relative"]) + } + + pub fn seek_to(&self, seconds: f64) -> Result<(), Error> { + self.command(&[b"seek", format!("{:.3}", seconds.max(0.0)).as_bytes(), b"absolute"]) + } + + /// To a share of the way through, from 0 to 1. + pub fn seek_to_fraction(&self, fraction: f64) -> Result<(), Error> { + self.command(&[b"seek", format!("{:.3}", fraction.clamp(0.0, 1.0) * 100.0).as_bytes(), b"absolute-percent"]) + } + + /// 0 to 100. + pub fn set_volume(&self, volume: f64) -> Result<(), Error> { + self.set_double(c"volume", volume.clamp(0.0, 100.0)) + } + + pub fn set_muted(&self, muted: bool) -> Result<(), Error> { + self.set_flag(c"mute", muted) + } + + /// A property as text, or `None` if it isn't available now. + pub fn get(&self, name: &CStr) -> Option { + // SAFETY: a live handle and a terminated name. libmpv's string is copied, then freed + // as it asks. + unsafe { + let raw = (self.core.lib.get_property_string)(self.core.handle, name.as_ptr()); + if raw.is_null() { + return None; + } + let text = CStr::from_ptr(raw).to_string_lossy().into_owned(); + (self.core.lib.free)(raw as *mut c_void); + Some(text) + } + } + + pub fn double(&self, name: &CStr) -> Option { + let mut value = 0.0f64; + // SAFETY: a live handle, and a double for a double. + let code = unsafe { (self.core.lib.get_property)(self.core.handle, name.as_ptr(), ffi::FORMAT_DOUBLE, &mut value as *mut f64 as *mut c_void) }; + (code >= 0).then_some(value) + } + + pub fn flag(&self, name: &CStr) -> Option { + let mut value: c_int = 0; + // SAFETY: a live handle, and an int for a flag. + let code = unsafe { (self.core.lib.get_property)(self.core.handle, name.as_ptr(), ffi::FORMAT_FLAG, &mut value as *mut c_int as *mut c_void) }; + (code >= 0).then_some(value != 0) + } + + fn set_flag(&self, name: &CStr, value: bool) -> Result<(), Error> { + let mut value = c_int::from(value); + // SAFETY: a live handle, and an int for a flag. + let code = unsafe { (self.core.lib.set_property)(self.core.handle, name.as_ptr(), ffi::FORMAT_FLAG, &mut value as *mut c_int as *mut c_void) }; + self.check(code, name) + } + + fn set_double(&self, name: &CStr, mut value: f64) -> Result<(), Error> { + // SAFETY: a live handle, and a double for a double. + let code = unsafe { (self.core.lib.set_property)(self.core.handle, name.as_ptr(), ffi::FORMAT_DOUBLE, &mut value as *mut f64 as *mut c_void) }; + self.check(code, name) + } + + fn check(&self, code: c_int, name: &CStr) -> Result<(), Error> { + if code < 0 { + return Err(Error::Mpv { doing: format!("setting {}", name.to_string_lossy()), reason: self.core.lib.describe(code) }); + } + Ok(()) + } + + /// Calls `wake` whenever there are events to read, from one of libmpv's threads. It + /// should only wake the thread that reads them. It replaces any earlier one. + pub fn on_wakeup(&self, wake: impl Fn() + Send + Sync + 'static) { + let boxed: Box = Box::new(Box::new(wake)); + let data = &*boxed as *const Wakeup as *mut c_void; + let mut wakeups = self.core.wakeups.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: a live handle. `data` points into a box kept until the handle is destroyed. + unsafe { (self.core.lib.set_wakeup_callback)(self.core.handle, Some(call_wakeup), data) }; + wakeups.push(boxed); + } + + /// The next event if there is one, without waiting. + pub fn next_event(&self) -> Option { + self.wait_event(Duration::ZERO) + } + + /// The next event, waiting up to `timeout` for one. Events this crate has no use for are + /// skipped. + pub fn wait_event(&self, timeout: Duration) -> Option { + let _reading = self.core.events.lock().unwrap_or_else(|e| e.into_inner()); + let mut wait = timeout.as_secs_f64(); + loop { + // SAFETY: a live handle, and only this thread is waiting, by the lock. + let event = unsafe { &*(self.core.lib.wait_event)(self.core.handle, wait) }; + if event.id == ffi::EVENT_NONE { + return None; + } + // An event was there, so anything after it is already queued. + wait = 0.0; + // SAFETY: the event and its data are libmpv's until the next wait, and are only + // read here, under the lock. + if let Some(found) = unsafe { self.translate(event) } { + return Some(found); + } + } + } + + /// # Safety + /// `event` must be the one libmpv just returned, read before the next wait. + unsafe fn translate(&self, event: &ffi::Event) -> Option { + match event.id { + ffi::EVENT_SHUTDOWN => Some(Event::Shutdown), + ffi::EVENT_FILE_LOADED => Some(Event::Loaded { video: self.get(c"vid").is_some_and(|v| v != "no") }), + ffi::EVENT_END_FILE => { + // SAFETY: an end-file event's data is an end-file struct, as the caller says. + let end = unsafe { &*(event.data as *const ffi::EventEndFile) }; + (end.reason == ffi::END_FILE_ERROR).then_some(Event::Failed) + } + ffi::EVENT_VIDEO_RECONFIG => Some(Event::VideoChanged), + ffi::EVENT_PLAYBACK_RESTART => Some(Event::Restarted), + ffi::EVENT_PROPERTY_CHANGE => { + // SAFETY: a property event's data is a property struct, as the caller says. + let property = unsafe { &*(event.data as *const ffi::EventProperty) }; + // `None` while a property isn't available, such as the duration before a file + // is open. That's left as it was. + if property.data.is_null() || property.format == ffi::FORMAT_NONE { + return None; + } + let index = usize::try_from(event.userdata).ok()?.checked_sub(1)?; + let (_, format) = WATCHED.get(index)?; + if property.format != *format { + return None; + } + // SAFETY: the format says what the data is, and it was checked above. + let (double, flag) = unsafe { + match *format { + ffi::FORMAT_DOUBLE => (*(property.data as *const f64), false), + _ => (0.0, *(property.data as *const c_int) != 0), + } + }; + let number = || double.is_finite().then_some(double.max(0.0)); + match index { + 0 => number().map(Event::Position), + 1 => number().map(Event::Duration), + 2 => Some(Event::Paused(flag)), + 3 => number().map(|v| Event::Volume(v.min(100.0))), + 4 => Some(Event::Muted(flag)), + 5 => Some(Event::Ended(flag)), + _ => None, + } + } + _ => None, + } + } +} + +unsafe extern "C" fn call_wakeup(data: *mut c_void) { + // SAFETY: `data` is a `Wakeup` that `on_wakeup` keeps alive until the handle is destroyed. + unsafe { (*(data as *const Wakeup))() }; +} + +impl Core { + pub(crate) fn set_option(&self, name: &str, value: &str) -> Result<(), Error> { + let (cname, cvalue) = (CString::new(name).map_err(|_| Error::Nul)?, CString::new(value).map_err(|_| Error::Nul)?); + // SAFETY: a live handle that hasn't been initialized, which is when mpv takes options. + let code = unsafe { (self.lib.set_option_string)(self.handle, cname.as_ptr(), cvalue.as_ptr()) }; + if code < 0 { + return Err(Error::Mpv { doing: format!("setting {name}={value}"), reason: self.lib.describe(code) }); + } + Ok(()) + } +} diff --git a/src/render.rs b/src/render.rs new file mode 100644 index 0000000..bc4bb1a --- /dev/null +++ b/src/render.rs @@ -0,0 +1,239 @@ +//! Drawing a player's frames: on the CPU into memory, or with OpenGL into a framebuffer. + +use std::ffi::{c_int, c_void}; +use std::sync::{Arc, Mutex}; + +use crate::ffi::{self, GetProcAddress}; +use crate::player::{Core, Error, Player}; + +type Update = Box; + +/// What both renderers share: the context, the player it draws, and its callbacks. +struct Context { + core: Arc, + handle: ffi::Handle, + /// Every update callback ever set, kept until the context is freed, as libmpv may still + /// be running one when it's replaced. Boxed twice so libmpv's pointer, to the inner box, + /// stays put when the list grows. + #[allow(clippy::vec_box)] + updates: Mutex>>, +} + +impl Context { + fn create(player: &Player, params: &mut [ffi::RenderParam]) -> Result { + debug_assert_eq!(params.last().map(|p| p.kind), Some(ffi::RENDER_INVALID)); + let core = player.core.clone(); + let mut handle: ffi::Handle = std::ptr::null_mut(); + // SAFETY: a live player and a list that ends as the API asks, whose data outlives the + // call. + let code = unsafe { (core.lib.render_create)(&mut handle, core.handle, params.as_mut_ptr()) }; + if code < 0 || handle.is_null() { + return Err(Error::Mpv { doing: "starting the renderer".into(), reason: core.lib.describe(code) }); + } + Ok(Self { core, handle, updates: Mutex::new(Vec::new()) }) + } + + fn on_update(&self, update: impl Fn() + Send + Sync + 'static) { + let boxed: Box = Box::new(Box::new(update)); + let data = &*boxed as *const Update as *mut c_void; + let mut updates = self.updates.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: a live context. `data` points into a box kept until the context is freed. + unsafe { (self.core.lib.render_set_update_callback)(self.handle, Some(call_update), data) }; + updates.push(boxed); + } + + fn new_frame(&self) -> bool { + // SAFETY: a live context. + unsafe { (self.core.lib.render_update)(self.handle) & ffi::RENDER_UPDATE_FRAME != 0 } + } + + fn render(&self, params: &mut [ffi::RenderParam]) -> Result<(), Error> { + debug_assert_eq!(params.last().map(|p| p.kind), Some(ffi::RENDER_INVALID)); + // SAFETY: a live context and a list that ends as the API asks. The callers check what + // the data points at. + let code = unsafe { (self.core.lib.render)(self.handle, params.as_mut_ptr()) }; + if code < 0 { + return Err(Error::Mpv { doing: "drawing a frame".into(), reason: self.core.lib.describe(code) }); + } + Ok(()) + } +} + +impl Drop for Context { + fn drop(&mut self) { + // SAFETY: a live context, freed once. After this no update callback runs, and the + // player it holds is destroyed only after it. + unsafe { (self.core.lib.render_free)(self.handle) }; + } +} + +// SAFETY: libmpv's render API may be used from any one thread at a time, and every method +// here takes `&mut self` except the callback setter and the update check, which libmpv allows +// from any thread. +unsafe impl Send for Context {} + +unsafe extern "C" fn call_update(data: *mut c_void) { + // SAFETY: `data` is an `Update` kept alive until the context is freed. + unsafe { (*(data as *const Update))() }; +} + +/// The pixel layouts the software renderer draws, four bytes a pixel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SwFormat { + /// Blue, green, red, then a byte to ignore: Wayland's `XRGB8888` on a little-endian + /// machine, so a frame can go straight into a `wl_shm` buffer. + Bgr0, + /// Red, green, blue, then a byte to ignore. + Rgb0, +} + +impl SwFormat { + fn name(self) -> &'static std::ffi::CStr { + match self { + Self::Bgr0 => c"bgr0", + Self::Rgb0 => c"rgb0", + } + } +} + +/// libmpv's software renderer. Slower than the GPU one, but it needs no graphics card and its +/// frames can be handed between processes as plain memory, which is how a jailed player works. +pub struct SwRender { + context: Context, +} + +impl SwRender { + pub fn new(player: &Player) -> Result { + let mut params = [ffi::RenderParam { kind: ffi::RENDER_API_TYPE, data: c"sw".as_ptr() as *mut c_void }, ffi::RenderParam { kind: ffi::RENDER_INVALID, data: std::ptr::null_mut() }]; + Ok(Self { context: Context::create(player, &mut params)? }) + } + + /// Calls `update` from one of libmpv's threads when there's something new to draw. It + /// should only wake the thread that draws. It replaces any earlier one. + pub fn on_update(&self, update: impl Fn() + Send + Sync + 'static) { + self.context.on_update(update); + } + + /// Whether there's a new frame to draw since this was last asked. Ask before every + /// `render`, as libmpv expects. + pub fn new_frame(&self) -> bool { + self.context.new_frame() + } + + /// Draws the current frame into `pixels`, scaled to fit `width` by `height` and + /// letterboxed in black. `stride` is the bytes from one row to the next. + pub fn render(&mut self, width: u32, height: u32, stride: usize, format: SwFormat, pixels: &mut [u8]) -> Result<(), Error> { + if !fits(width, height, stride, pixels) { + return Err(Error::Buffer); + } + let mut size = [width as c_int, height as c_int]; + let mut stride = stride; + let mut params = [ + ffi::RenderParam { kind: ffi::RENDER_SW_SIZE, data: size.as_mut_ptr() as *mut c_void }, + ffi::RenderParam { kind: ffi::RENDER_SW_FORMAT, data: format.name().as_ptr() as *mut c_void }, + ffi::RenderParam { kind: ffi::RENDER_SW_STRIDE, data: &mut stride as *mut usize as *mut c_void }, + ffi::RenderParam { kind: ffi::RENDER_SW_POINTER, data: pixels.as_mut_ptr() as *mut c_void }, + ffi::RenderParam { kind: ffi::RENDER_INVALID, data: std::ptr::null_mut() }, + ]; + // libmpv writes every byte from the pointer to `stride * height`, padding included, + // which `fits` checked is inside `pixels`. + self.context.render(&mut params) + } +} + +/// Whether libmpv can draw a `width` by `height` frame into `pixels` with `stride`: it +/// writes `stride * height` bytes, and needs rows and the start aligned to whole pixels. +fn fits(width: u32, height: u32, stride: usize, pixels: &[u8]) -> bool { + let row = width as usize * 4; + width > 0 + && height > 0 + && width <= c_int::MAX as u32 + && height <= c_int::MAX as u32 + && stride >= row + && stride.is_multiple_of(4) + && (pixels.as_ptr() as usize).is_multiple_of(4) + && stride.checked_mul(height as usize).is_some_and(|bytes| bytes <= pixels.len()) +} + +/// libmpv's OpenGL renderer. The app owns the GL context, and makes it current on the +/// thread that creates and uses this. +pub struct GlRender { + context: Context, +} + +impl GlRender { + /// # Safety + /// An OpenGL context must be current on this thread, and stay current whenever this is + /// used or dropped. `get_proc_address` must find that context's functions given + /// `proc_context`. `wl_display`, if given, must be the app's live `wl_display`, which lets + /// libmpv use hardware decoding without copying frames back. + pub unsafe fn new(player: &Player, get_proc_address: GetProcAddress, proc_context: *mut c_void, wl_display: Option<*mut c_void>) -> Result { + let mut init = ffi::OpenGlInitParams { get_proc_address: Some(get_proc_address), get_proc_address_ctx: proc_context }; + let mut params = vec![ + ffi::RenderParam { kind: ffi::RENDER_API_TYPE, data: c"opengl".as_ptr() as *mut c_void }, + ffi::RenderParam { kind: ffi::RENDER_OPENGL_INIT_PARAMS, data: &mut init as *mut _ as *mut c_void }, + ]; + if let Some(display) = wl_display { + params.push(ffi::RenderParam { kind: ffi::RENDER_WL_DISPLAY, data: display }); + } + params.push(ffi::RenderParam { kind: ffi::RENDER_INVALID, data: std::ptr::null_mut() }); + Ok(Self { context: Context::create(player, &mut params)? }) + } + + /// As for `SwRender::on_update`. + pub fn on_update(&self, update: impl Fn() + Send + Sync + 'static) { + self.context.on_update(update); + } + + pub fn new_frame(&self) -> bool { + self.context.new_frame() + } + + /// Draws the current frame into framebuffer `fbo` (0 for the window's own), `width` by + /// `height`. `internal_format` is the framebuffer's, such as `GL_RGBA8`, or 0 if unknown. + /// `flip_y` for a framebuffer whose rows run bottom to top, as the window's own does. + /// + /// # Safety + /// The context this was made with must be current, and `fbo` must be one of its + /// framebuffers of that size. + pub unsafe fn render(&mut self, fbo: i32, width: i32, height: i32, internal_format: i32, flip_y: bool) -> Result<(), Error> { + let mut target = ffi::OpenGlFbo { fbo, w: width, h: height, internal_format }; + let mut flip: c_int = c_int::from(flip_y); + let mut params = [ + ffi::RenderParam { kind: ffi::RENDER_OPENGL_FBO, data: &mut target as *mut _ as *mut c_void }, + ffi::RenderParam { kind: ffi::RENDER_FLIP_Y, data: &mut flip as *mut c_int as *mut c_void }, + ffi::RenderParam { kind: ffi::RENDER_INVALID, data: std::ptr::null_mut() }, + ]; + self.context.render(&mut params) + } + + /// Tells libmpv a frame reached the screen, which it uses for timing. Optional. + pub fn report_swap(&self) { + // SAFETY: a live context. + unsafe { (self.context.core.lib.render_report_swap)(self.context.handle) }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_buffer_has_to_hold_every_row_with_its_padding() { + let buffer = vec![0u32; 64]; + let bytes: &[u8] = bytemuck_bytes(&buffer); + assert!(fits(8, 8, 32, bytes)); + assert!(!fits(8, 9, 32, bytes), "one row too many"); + assert!(!fits(9, 8, 32, bytes), "a row wider than its stride"); + assert!(!fits(8, 4, 34, bytes), "a stride that isn't whole pixels"); + assert!(!fits(0, 8, 32, bytes)); + assert!(!fits(8, 0, 32, bytes)); + assert!(!fits(4, 4, usize::MAX / 2, bytes), "a stride that overflows"); + assert!(!fits(4, 4, 16, &bytes[1..]), "a start that isn't aligned"); + } + + fn bytemuck_bytes(words: &[u32]) -> &[u8] { + // SAFETY: any u32s are valid bytes, and the length covers exactly those words. + unsafe { std::slice::from_raw_parts(words.as_ptr() as *const u8, words.len() * 4) } + } +} diff --git a/tests/clips/mod.rs b/tests/clips/mod.rs new file mode 100644 index 0000000..e4b19d1 --- /dev/null +++ b/tests/clips/mod.rs @@ -0,0 +1,370 @@ +//! The colour test clips (ALI-2420), shared by the CPU tests (`tests/colour.rs`) and the GPU +//! bench (`examples/colour-gpu.rs`): the cases, the clips made from them, and the check. +//! +//! The expected colours come from the source RGB, not from another player. Each clip's Y'CbCr +//! is worked out here, from the source RGB with the case's matrix, range and bit depth, and +//! handed to FFmpeg as raw frames to encode losslessly with the case's tags. FFmpeg converts +//! nothing. Each clip is then checked before it's played: its tags, read back with ffprobe, +//! must be the case's, and FFmpeg must decode it back to the Y'CbCr made here. So a failure is +//! the player's, never the clip's. +//! +//! Primaries are BT.709 throughout, so a case tests the matrix alone and the right answer +//! needs no gamut conversion. SDR transfer tags change nothing: a player shows the coded +//! values as they are, which is what mpv's window does for each of them. +//! +//! Needs `ffmpeg` and `ffprobe` with libx264, libx265, libvpx and libaom. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use alias_playback::{Event, Hwdec, Options, Player, SwFormat, SwRender}; + +/// Steps per channel, 8-bit, for SDR (ALI-2420). +pub const TOLERANCE: i32 = 2; +/// Each patch is a square this size, and only its middle, `INSET` in from each edge, is +/// checked, well clear of chroma shared with its neighbours. +pub const PATCH: usize = 64; +pub const INSET: usize = 16; +pub const COLUMNS: usize = 4; +pub const ROWS: usize = 4; +pub const WIDTH: usize = PATCH * COLUMNS; +pub const HEIGHT: usize = PATCH * ROWS; +pub const FRAMES: usize = 2; + +/// The source colours: black, white and greys, the primaries and secondaries, skin tones, and +/// aliasOS theme colours. +pub const PATCHES: [(&str, [u8; 3]); COLUMNS * ROWS] = [ + ("black", [0x00, 0x00, 0x00]), + ("near black", [0x10, 0x10, 0x10]), + ("Tarnished background", [0x12, 0x1c, 0x24]), + ("dark grey", [0x40, 0x40, 0x40]), + ("middle grey", [0x80, 0x80, 0x80]), + ("light grey", [0xc0, 0xc0, 0xc0]), + ("white", [0xff, 0xff, 0xff]), + ("red", [0xff, 0x00, 0x00]), + ("green", [0x00, 0xff, 0x00]), + ("blue", [0x00, 0x00, 0xff]), + ("cyan", [0x00, 0xff, 0xff]), + ("magenta", [0xff, 0x00, 0xff]), + ("yellow", [0xff, 0xff, 0x00]), + ("light skin", [0xf1, 0xc2, 0x7d]), + ("medium skin", [0xc6, 0x86, 0x42]), + ("dark skin", [0x8d, 0x55, 0x24]), +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Codec { + H264, + Hevc, + Vp9, + Av1, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Range { + Limited, + Full, + /// Full range said by FFmpeg's old `yuvj` pixel formats, as MJPEG and some phones' H.264 + /// still are. + Yuvj, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Matrix { + Bt601, + Bt709, + Bt2020, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Transfer { + Bt709, + Srgb, + Unspecified, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Case { + pub codec: Codec, + pub range: Range, + pub matrix: Matrix, + pub transfer: Transfer, + pub depth: u32, + /// 4:4:4 rather than 4:2:0. + pub full_chroma: bool, +} + +impl Case { + pub fn name(&self) -> String { + let codec = match self.codec { + Codec::H264 => "h264", + Codec::Hevc => "hevc", + Codec::Vp9 => "vp9", + Codec::Av1 => "av1", + }; + let range = match self.range { + Range::Limited => "limited", + Range::Full => "full", + Range::Yuvj => "yuvj", + }; + let matrix = match self.matrix { + Matrix::Bt601 => "601", + Matrix::Bt709 => "709", + Matrix::Bt2020 => "2020", + }; + let transfer = match self.transfer { + Transfer::Bt709 => "trc709", + Transfer::Srgb => "srgb", + Transfer::Unspecified => "notrc", + }; + let chroma = if self.full_chroma { "444" } else { "420" }; + format!("{codec}-{range}-{matrix}-{transfer}-{}bit-{chroma}", self.depth) + } + + pub fn pix_fmt(&self) -> String { + let chroma = if self.full_chroma { "444" } else { "420" }; + match (self.range, self.depth) { + (Range::Yuvj, _) => format!("yuvj{chroma}p"), + (_, 8) => format!("yuv{chroma}p"), + (_, depth) => format!("yuv{chroma}p{depth}le"), + } + } + + pub fn full_range(&self) -> bool { + self.range != Range::Limited + } + + /// FFmpeg's names for the tags, which ffprobe reports back. An unspecified transfer is + /// left out when encoding. + pub fn tags(&self) -> (&'static str, &'static str, Option<&'static str>) { + let range = if self.full_range() { "pc" } else { "tv" }; + let matrix = match self.matrix { + Matrix::Bt601 => "smpte170m", + Matrix::Bt709 => "bt709", + Matrix::Bt2020 => "bt2020nc", + }; + let transfer = match self.transfer { + Transfer::Bt709 => Some("bt709"), + Transfer::Srgb => Some("iec61966-2-1"), + Transfer::Unspecified => None, + }; + (range, matrix, transfer) + } + + /// Lossless settings, and the container each codec usually comes in. + pub fn encoder(&self) -> (&'static [&'static str], &'static str) { + match self.codec { + Codec::H264 => (&["-c:v", "libx264", "-qp", "0", "-preset", "ultrafast"], "mp4"), + Codec::Hevc => (&["-c:v", "libx265", "-x265-params", "lossless=1:log-level=error", "-tag:v", "hvc1"], "mp4"), + Codec::Vp9 => (&["-c:v", "libvpx-vp9", "-lossless", "1", "-deadline", "realtime", "-cpu-used", "8"], "webm"), + Codec::Av1 => (&["-c:v", "libaom-av1", "-aom-params", "lossless=1", "-cpu-used", "8", "-row-mt", "1"], "mkv"), + } + } +} + +/// Every case. Not every combination of six axes (there would be hundreds), but every value +/// of each, and the combinations that have gone wrong or could: +/// +/// - the tags (range, matrix and transfer, all 27 together) on H.264, 8-bit 4:2:0; +/// - every codec at 8 and 10 bits, 4:2:0 and 4:4:4; +/// - every codec with full range and with the sRGB transfer, which each codec signals its +/// own way. +pub fn cases() -> Vec { + let base = Case { codec: Codec::H264, range: Range::Limited, matrix: Matrix::Bt709, transfer: Transfer::Bt709, depth: 8, full_chroma: false }; + let mut cases = Vec::new(); + for range in [Range::Limited, Range::Full, Range::Yuvj] { + for matrix in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020] { + for transfer in [Transfer::Bt709, Transfer::Srgb, Transfer::Unspecified] { + cases.push(Case { range, matrix, transfer, ..base }); + } + } + } + for codec in [Codec::H264, Codec::Hevc, Codec::Vp9, Codec::Av1] { + for depth in [8, 10] { + for full_chroma in [false, true] { + cases.push(Case { codec, depth, full_chroma, ..base }); + } + } + cases.push(Case { codec, range: Range::Full, ..base }); + cases.push(Case { codec, transfer: Transfer::Srgb, ..base }); + cases.push(Case { codec, range: Range::Full, transfer: Transfer::Srgb, ..base }); + } + let mut seen = std::collections::HashSet::new(); + cases.retain(|case| seen.insert(*case)); + cases +} + +/// One source colour as the case codes it: Y', Cb, Cr at the case's depth (ITU-T H.273). +pub fn ycbcr(rgb: [u8; 3], case: &Case) -> [u16; 3] { + let (kr, kb) = match case.matrix { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020 => (0.2627, 0.0593), + }; + let [r, g, b] = rgb.map(|v| f64::from(v) / 255.0); + let y = kr * r + (1.0 - kr - kb) * g + kb * b; + let pb = (b - y) / (2.0 * (1.0 - kb)); + let pr = (r - y) / (2.0 * (1.0 - kr)); + let n = case.depth; + let max = f64::from((1u32 << n) - 1); + let (y, pb, pr) = if case.full_range() { + let mid = f64::from(1u32 << (n - 1)); + (max * y, max * pb + mid, max * pr + mid) + } else { + let scale = f64::from(1u32 << (n - 8)); + ((219.0 * y + 16.0) * scale, (224.0 * pb + 128.0) * scale, (224.0 * pr + 128.0) * scale) + }; + [y, pb, pr].map(|v| v.round().clamp(0.0, max) as u16) +} + +/// One frame's planes, as raw bytes in the case's pixel format. +pub fn frame(case: &Case) -> Vec { + let (cw, ch) = if case.full_chroma { (WIDTH, HEIGHT) } else { (WIDTH / 2, HEIGHT / 2) }; + let patch_at = |x: usize, y: usize, w: usize, h: usize| (y * ROWS / h) * COLUMNS + x * COLUMNS / w; + let mut out = Vec::new(); + let mut put = |v: u16| { + if case.depth == 8 { + out.push(v as u8); + } else { + out.extend_from_slice(&v.to_le_bytes()); + } + }; + for plane in 0..3 { + let (w, h) = if plane == 0 { (WIDTH, HEIGHT) } else { (cw, ch) }; + for y in 0..h { + for x in 0..w { + put(ycbcr(PATCHES[patch_at(x, y, w, h)].1, case)[plane]); + } + } + } + out +} + +pub fn run(command: &mut Command) -> Result, String> { + let output = command.stderr(Stdio::piped()).output().map_err(|e| format!("{command:?}: {e}"))?; + if !output.status.success() { + return Err(format!("{command:?}: {}", String::from_utf8_lossy(&output.stderr).trim())); + } + Ok(output.stdout) +} + +/// Encodes the case's clip, and checks it's what it should be before anything plays it. +pub fn make_clip(case: &Case, dir: &Path) -> Result { + let (encoder, container) = case.encoder(); + let clip = dir.join(format!("{}.{container}", case.name())); + let raw = dir.join(format!("{}.yuv", case.name())); + std::fs::write(&raw, frame(case).repeat(FRAMES)).map_err(|e| e.to_string())?; + let (range, matrix, transfer) = case.tags(); + let pix_fmt = case.pix_fmt(); + let size = format!("{WIDTH}x{HEIGHT}"); + let mut tags = vec!["-color_range", range, "-colorspace", matrix, "-color_primaries", "bt709"]; + if let Some(transfer) = transfer { + tags.extend(["-color_trc", transfer]); + } + let mut ffmpeg = Command::new("ffmpeg"); + ffmpeg.args(["-nostdin", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", &pix_fmt, "-s", &size, "-r", "10"]).args(&tags).arg("-i").arg(&raw); + ffmpeg.args(encoder).args(["-pix_fmt", &pix_fmt]).args(&tags).arg(&clip); + run(&mut ffmpeg)?; + let _ = std::fs::remove_file(&raw); + + let probed = run(Command::new("ffprobe") + .args(["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=pix_fmt,color_range,color_space,color_transfer,color_primaries", "-of", "default=nw=1"]) + .arg(&clip))?; + let probed = String::from_utf8_lossy(&probed); + let expected = [format!("color_range={range}"), format!("color_space={matrix}"), "color_primaries=bt709".to_owned(), format!("color_transfer={}", transfer.unwrap_or("unknown"))]; + for line in &expected { + if !probed.lines().any(|l| l == line) { + return Err(format!("the clip's tags aren't the case's: wanted {line}, ffprobe says {}", probed.trim().replace('\n', ", "))); + } + } + // FFmpeg's H.264 and HEVC decoders still say `yuvj` for any full-range 8-bit picture, + // however it was made: the same bits either way. + let decoded_format = probed.lines().find_map(|l| l.strip_prefix("pix_fmt=")).unwrap_or_default().to_owned(); + if (decoded_format != pix_fmt && decoded_format != pix_fmt.replacen("yuv", "yuvj", 1)) || (decoded_format.starts_with("yuvj") && !case.full_range()) { + return Err(format!("the clip decodes as {decoded_format}, not {pix_fmt}")); + } + + // Decoded by FFmpeg as it's stored, with no conversion, it must be the Y'CbCr made here. + let decoded = run(Command::new("ffmpeg").args(["-nostdin", "-v", "error", "-i"]).arg(&clip).args(["-frames:v", "1", "-f", "rawvideo", "-pix_fmt", &decoded_format, "-"]))?; + if decoded != frame(case) { + return Err("the clip doesn't decode to the Y'CbCr it was made from".into()); + } + Ok(clip) +} + +/// The patches that missed: each with the colour expected, and the furthest pixel from it. +pub fn misses(pixels: &[u32], size: (usize, usize)) -> Vec { + let mut found = Vec::new(); + for (i, (name, rgb)) in PATCHES.iter().enumerate() { + let (scale_x, scale_y) = (size.0 as f64 / WIDTH as f64, size.1 as f64 / HEIGHT as f64); + let (px, py) = ((i % COLUMNS) * PATCH, (i / COLUMNS) * PATCH); + let x_range = ((px + INSET) as f64 * scale_x).ceil() as usize..((px + PATCH - INSET) as f64 * scale_x).floor() as usize; + let y_range = ((py + INSET) as f64 * scale_y).ceil() as usize..((py + PATCH - INSET) as f64 * scale_y).floor() as usize; + let mut worst = (0, [0u8; 3]); + for y in y_range { + for x in x_range.clone() { + let p = pixels[y * size.0 + x]; + let got = [(p >> 16) as u8, (p >> 8) as u8, p as u8]; + let off = (0..3).map(|c| (i32::from(got[c]) - i32::from(rgb[c])).abs()).max().unwrap_or(0); + if off > worst.0 { + worst = (off, got); + } + } + } + if worst.0 > TOLERANCE { + let hex = |c: [u8; 3]| format!("#{:02X}{:02X}{:02X}", c[0], c[1], c[2]); + found.push(format!("{name} {} drew {} ({} steps)", hex(*rgb), hex(worst.1), worst.0)); + } + } + found +} + +/// The Y'CbCr maths against values from the standards, so the expected colours rest on it. +pub fn check_the_maths() { + let case = |range, matrix, depth| Case { codec: Codec::H264, range, matrix, transfer: Transfer::Bt709, depth, full_chroma: false }; + let limited = case(Range::Limited, Matrix::Bt709, 8); + assert_eq!(ycbcr([0, 0, 0], &limited), [16, 128, 128]); + assert_eq!(ycbcr([255, 255, 255], &limited), [235, 128, 128]); + assert_eq!(ycbcr([255, 0, 0], &limited), [63, 102, 240], "BT.709 red"); + assert_eq!(ycbcr([255, 0, 0], &case(Range::Limited, Matrix::Bt601, 8)), [81, 90, 240], "BT.601 red"); + assert_eq!(ycbcr([255, 255, 255], &case(Range::Limited, Matrix::Bt709, 10)), [940, 512, 512]); + assert_eq!(ycbcr([0, 0, 0], &case(Range::Limited, Matrix::Bt2020, 10)), [64, 512, 512]); + assert_eq!(ycbcr([255, 255, 255], &case(Range::Full, Matrix::Bt709, 8)), [255, 128, 128]); + assert_eq!(ycbcr([255, 255, 255], &case(Range::Full, Matrix::Bt709, 10)), [1023, 512, 512]); +} + +/// The first frame of `clip`, as the apps' software renderer draws it at `size`, as +/// `0x00RRGGBB` words, and the decoder libmpv used. `colour_fix: false` draws it without the +/// crate's colour settings, to show what they change. +pub fn play_cpu(clip: &Path, size: (usize, usize), hwdec: Hwdec, colour_fix: bool) -> Result<(Vec, String), String> { + let player = Player::new(&Options { hwdec, ..Options::cpu() }).map_err(|e| e.to_string())?; + if !colour_fix { + player.command(&[b"set", b"vf", b""]).map_err(|e| e.to_string())?; + } + let mut render = SwRender::new(&player).map_err(|e| e.to_string())?; + player.load(clip).map_err(|e| e.to_string())?; + let deadline = Instant::now() + Duration::from_secs(20); + let mut restarted = false; + while Instant::now() < deadline { + match player.wait_event(Duration::from_millis(5)) { + Some(Event::Failed) => return Err("libmpv couldn't play it".into()), + Some(Event::Loaded { video: false }) => return Err("libmpv found no picture".into()), + Some(Event::Restarted) => restarted = true, + _ => {} + } + if restarted && render.new_frame() { + let mut pixels = vec![0u32; size.0 * size.1]; + // SAFETY: any bytes are valid u32s, and the slice covers exactly these words. + let bytes = unsafe { std::slice::from_raw_parts_mut(pixels.as_mut_ptr() as *mut u8, pixels.len() * 4) }; + render.render(size.0 as u32, size.1 as u32, size.0 * 4, SwFormat::Bgr0, bytes).map_err(|e| e.to_string())?; + return Ok((pixels, decoder(&player))); + } + } + Err("no frame within 20 seconds".into()) +} + +/// The hardware decoder libmpv is using, or "software". +pub fn decoder(player: &Player) -> String { + player.get(c"hwdec-current").filter(|d| !d.is_empty() && d != "no").unwrap_or_else(|| "software".into()) +} diff --git a/tests/colour.rs b/tests/colour.rs new file mode 100644 index 0000000..00e57c6 --- /dev/null +++ b/tests/colour.rs @@ -0,0 +1,76 @@ +//! The colour tests (ALI-2420): the clips in `clips/mod.rs`, played through libmpv's software +//! renderer exactly as the apps set it up. A clip passes when every pixel inside every patch +//! lands within two steps per channel of the colour it was made from. This is the renderer +//! CI can run: it needs no graphics card. The GPU renderer's run is `examples/colour-gpu.rs`. +//! +//! Each clip is drawn at its own size and at half size, as a window would shrink it, and once +//! more without the crate's colour settings, for the record of what they change. +//! +//! Not yet covered: HDR (PQ, HLG), which tone-maps by design and needs its own reference, and +//! real screen recordings checked against screenshots. +//! +//! Needs `ffmpeg` and `ffprobe` with libx264, libx265, libvpx and libaom, and libmpv. +//! `cargo test --test colour -- --list` names the cases; a name after `--` runs the cases +//! whose names contain it. + +mod clips; + +use std::process::ExitCode; + +use alias_playback::Hwdec; +use clips::{Case, HEIGHT, TOLERANCE, WIDTH, cases, check_the_maths, make_clip, misses, play_cpu}; + +fn main() -> ExitCode { + check_the_maths(); + let args: Vec = std::env::args().skip(1).collect(); + let cases = cases(); + if args.iter().any(|a| a == "--list") { + for case in &cases { + println!("{}: test", case.name()); + } + return ExitCode::SUCCESS; + } + let filters: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect(); + let cases: Vec = cases.into_iter().filter(|c| filters.is_empty() || filters.iter().any(|f| c.name().contains(f.as_str()))).collect(); + let dir = std::env::temp_dir().join(format!("alias-playback-colour-{}", std::process::id())); + if let Err(e) = std::fs::create_dir_all(&dir) { + eprintln!("can't make {}: {e}", dir.display()); + return ExitCode::FAILURE; + } + println!("\n{} colour cases, software renderer, tolerance {TOLERANCE} steps:\n", cases.len()); + let mut failed = 0; + for case in &cases { + let name = case.name(); + let result = make_clip(case, &dir).and_then(|clip| { + let mut problems = Vec::new(); + // At its own size, and shrunk as a window would draw it. + for size in [(WIDTH, HEIGHT), (WIDTH / 2, HEIGHT / 2)] { + let (drawn, _) = play_cpu(&clip, size, Hwdec::Off, true)?; + problems.extend(misses(&drawn, size).into_iter().map(|m| format!("at {}x{}: {m}", size.0, size.1))); + } + // Without the colour settings, for the record: what they're there for. + let unfixed = misses(&play_cpu(&clip, (WIDTH, HEIGHT), Hwdec::Off, false)?.0, (WIDTH, HEIGHT)); + Ok((problems, unfixed)) + }); + match result { + Ok((problems, unfixed)) if problems.is_empty() => { + let note = if unfixed.is_empty() { String::new() } else { format!(" (without the colour settings: {})", unfixed.join("; ")) }; + println!("ok {name}{note}"); + } + Ok((problems, _)) => { + failed += 1; + println!("FAIL {name}"); + for problem in problems { + println!(" {problem}"); + } + } + Err(e) => { + failed += 1; + println!("FAIL {name}: {e}"); + } + } + } + let _ = std::fs::remove_dir_all(&dir); + println!("\n{} passed, {failed} failed\n", cases.len() - failed); + if failed == 0 { ExitCode::SUCCESS } else { ExitCode::FAILURE } +} diff --git a/tests/helper.rs b/tests/helper.rs new file mode 100644 index 0000000..06c80a9 --- /dev/null +++ b/tests/helper.rs @@ -0,0 +1,214 @@ +//! A real player in another process: this test program runs a copy of itself as the helper, +//! the way an app does, without the jail (bubblewrap needs user namespaces, which CI's +//! containers don't give). It checks what the app sees: frames in shared memory, the state, +//! stopping on the last frame, playing again from the start, sound-only files, and files that +//! won't play. +//! +//! Needs `ffmpeg` to make the clips, and libmpv. + +use std::fs::File; +use std::os::fd::OwnedFd; +use std::path::{Path, PathBuf}; +use std::process::{Command, ExitCode}; +use std::sync::mpsc::{Receiver, channel}; +use std::time::{Duration, Instant}; + +use alias_playback::Options; +use alias_playback::helper::{self, PlayState, Remote, Said}; + +const HELPER_ARG: &str = "--playback-helper"; +const SANDBOX_CODE: i32 = 6; + +type Test = (&'static str, fn(&Path)); + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + if args.first().map(String::as_str) == Some(HELPER_ARG) { + helper::run(&args[1..], &Options::cpu(), SANDBOX_CODE, || true); + } + let tests: [Test; 5] = [ + ("a_video_draws_its_frames_and_stops_on_the_last", a_video_draws_its_frames_and_stops_on_the_last), + ("play_after_the_end_starts_again", play_after_the_end_starts_again), + ("a_new_size_redraws_the_frame_even_when_stopped", a_new_size_redraws_the_frame_even_when_stopped), + ("sound_only_files_say_so_or_play_when_allowed", sound_only_files_say_so_or_play_when_allowed), + ("a_file_that_isnt_media_cant_play", a_file_that_isnt_media_cant_play), + ]; + if args.iter().any(|a| a == "--list") { + for (name, _) in tests { + println!("{name}: test"); + } + return ExitCode::SUCCESS; + } + let filters: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect(); + let dir = std::env::temp_dir().join(format!("alias-playback-helper-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("a temporary folder"); + let mut failed = 0; + for (name, test) in tests { + if !filters.is_empty() && !filters.iter().any(|f| name.contains(f.as_str())) { + continue; + } + let dir = dir.clone(); + match std::panic::catch_unwind(move || test(&dir)) { + Ok(()) => println!("test {name} ... ok"), + Err(_) => { + println!("test {name} ... FAILED"); + failed += 1; + } + } + } + let _ = std::fs::remove_dir_all(&dir); + if failed == 0 { ExitCode::SUCCESS } else { ExitCode::FAILURE } +} + +/// A clip made with FFmpeg from `source`, once per name. +fn clip(dir: &Path, name: &str, source: &[&str]) -> PathBuf { + let path = dir.join(name); + if !path.exists() { + let status = Command::new("ffmpeg").args(["-nostdin", "-v", "error", "-y"]).args(source).arg(&path).status().expect("ffmpeg"); + assert!(status.success(), "ffmpeg made {name}"); + } + path +} + +/// Half a second of one colour, #208080, 10 frames a second, 64x36: about as short as a video +/// gets. Made from its own Y'CbCr (full range, BT.709), as the colour tests do, since FFmpeg's +/// conversion from RGB is a step or two out. +fn video(dir: &Path) -> PathBuf { + let raw = dir.join("teal.yuv"); + let plane = |v: u8| vec![v; 64 * 36]; + std::fs::write(&raw, [plane(108), plane(139), plane(80)].concat().repeat(5)).expect("write"); + let raw = raw.to_string_lossy().into_owned(); + let tags = ["-color_range", "pc", "-colorspace", "bt709", "-color_trc", "bt709", "-color_primaries", "bt709"]; + let source = [&["-f", "rawvideo", "-pix_fmt", "yuv444p", "-s", "64x36", "-r", "10"][..], &tags, &["-i", &raw, "-c:v", "libx264", "-qp", "0", "-pix_fmt", "yuv444p"], &tags].concat(); + clip(dir, "teal.mp4", &source) +} + +fn sound(dir: &Path) -> PathBuf { + clip(dir, "tone.wav", &["-f", "lavfi", "-i", "sine=f=440:d=0.4"]) +} + +/// A started player, and everything it says as it says it. +struct Running { + remote: Remote, + frames: helper::Frames, + heard: Receiver, + cancel: OwnedFd, + watcher: Option>>, +} + +impl Running { + fn start(file: &Path, size: (u32, u32), sound: bool) -> Self { + let mut command = Command::new(std::env::current_exe().expect("own path")); + command.arg(HELPER_ARG); + let started = helper::start(command, File::open(file).expect("the clip"), size, sound).unwrap_or_else(|e| panic!("started: {e:?}")); + let cancel = rustix::event::eventfd(0, rustix::event::EventfdFlags::CLOEXEC).expect("eventfd"); + let watching = cancel.try_clone().expect("a copy"); + let (tx, heard) = channel(); + let (child, said) = (started.child, started.said); + let watcher = std::thread::spawn(move || { + helper::watch(child, said, &watching, |s| { + let _ = tx.send(s); + }) + }); + Self { remote: started.remote, frames: started.frames, heard, cancel, watcher: Some(watcher) } + } + + /// Waits for something `wanted` picks, failing after five seconds. + fn wait_for(&self, what: &str, mut wanted: impl FnMut(Said) -> Option) -> T { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let left = deadline.saturating_duration_since(Instant::now()); + match self.heard.recv_timeout(left) { + Ok(said) => { + if let Some(found) = wanted(said) { + return found; + } + } + Err(_) => panic!("never heard {what}"), + } + } + } + + fn wait_for_state(&self, what: &str, wanted: impl Fn(&PlayState) -> bool) -> PlayState { + self.wait_for(what, |s| match s { + Said::State(state) if wanted(&state) => Some(state), + _ => None, + }) + } + + fn wait_for_frame(&self) -> (usize, u32, u32) { + self.wait_for("a frame", |s| match s { + Said::Frame { index, w, h } => Some((index, w, h)), + _ => None, + }) + } +} + +impl Drop for Running { + fn drop(&mut self) { + let _ = rustix::io::write(&self.cancel, &1u64.to_ne_bytes()); + if let Some(watcher) = self.watcher.take() { + let _ = watcher.join(); + } + } +} + +fn a_video_draws_its_frames_and_stops_on_the_last(dir: &Path) { + let mut player = Running::start(&video(dir), (320, 320), false); + player.wait_for("hello", |s| (s == Said::Hello).then_some(())); + player.remote.set_paused(false); + let (index, w, h) = player.wait_for_frame(); + assert_eq!((w, h), (320, 180), "fitted to the size asked for, keeping its shape"); + let middle = player.frames.frame(index, w, h)[(h / 2 * w + w / 2) as usize] & 0xffffff; + let channels = [(middle >> 16) as i32, (middle >> 8 & 0xff) as i32, (middle & 0xff) as i32]; + for (got, want) in channels.into_iter().zip([0x20, 0x80, 0x80]) { + assert!((got - want).abs() <= 2, "the middle drew #{middle:06X}, not #208080"); + } + let ended = player.wait_for_state("the end", |s| s.ended); + assert!(ended.paused, "stopped, not closed"); + assert!(ended.duration > 0.4 && ended.duration < 0.6, "{ended:?}"); + // Still there to draw from: the player hasn't gone. + std::thread::sleep(Duration::from_millis(300)); + while let Ok(said) = player.heard.try_recv() { + assert!(!matches!(said, Said::CantPlay | Said::NoVideo), "{said:?}"); + } + let _ = player.frames.frame(index, w, h); +} + +fn play_after_the_end_starts_again(dir: &Path) { + let mut player = Running::start(&video(dir), (64, 36), false); + player.remote.set_paused(false); + player.wait_for_state("the end", |s| s.ended); + player.remote.set_paused(false); + let again = player.wait_for_state("playing again", |s| !s.ended && !s.paused); + assert!(again.position < 0.3, "from the start: {again:?}"); + player.wait_for_state("the end again", |s| s.ended); +} + +fn a_new_size_redraws_the_frame_even_when_stopped(dir: &Path) { + let mut player = Running::start(&video(dir), (64, 36), false); + player.remote.set_paused(false); + player.wait_for_state("the end", |s| s.ended); + player.remote.set_size(128, 128); + player.wait_for("a frame at the new size", |s| matches!(s, Said::Frame { w: 128, h: 72, .. }).then_some(())); +} + +fn sound_only_files_say_so_or_play_when_allowed(dir: &Path) { + let tone = sound(dir); + let refused = Running::start(&tone, (64, 36), false); + refused.wait_for("no video", |s| (s == Said::NoVideo).then_some(())); + drop(refused); + + let mut player = Running::start(&tone, (64, 36), true); + player.wait_for("sound", |s| (s == Said::Sound).then_some(())); + player.remote.set_paused(false); + let ended = player.wait_for_state("the end", |s| s.ended); + assert!(ended.duration > 0.3, "{ended:?}"); +} + +fn a_file_that_isnt_media_cant_play(dir: &Path) { + let junk = dir.join("junk.mp4"); + std::fs::write(&junk, b"\0\0\0\x20ftypisom but nothing after it").expect("write"); + let player = Running::start(&junk, (64, 36), false); + player.wait_for("can't play", |s| (s == Said::CantPlay).then_some(())); +} From 24c2c60cde874a371d89bf2fc087e709d81ba52c Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 05:47:55 -0700 Subject: [PATCH 02/25] Review fixes: jailed exe, hidden file reads, stale duration, GL thread - jail::own_exe no longer falls back to /proc/self/exe. bubblewrap resolves that path in its own process and binds itself, so a video opened after the app's file was removed ran bwrap as the helper and failed as a jail error. It now fails plainly instead. - ordered-chapters and access-references are off. A Matroska file could otherwise make an unjailed player read other files for its chapters, and a playlist could name anything. - When a file closes, the position and duration go back to 0 rather than keeping the last file's values (new helper test, which fails without this change). - GlRender can't move between threads. Dropping it frees libmpv's GL state, which needs its context current. - watch stops the player when try_wait fails, as its documentation says. - start's documentation says the player dies with the thread that started it. - The GPU bench skips a case only when the machine's encoder can't make it. A missing FFmpeg or a clip that fails its check is now a failure. - The CPU colour setting's comment covers full-range video with no transfer tag too. - The unused rustix process feature is removed. --- Cargo.toml | 2 +- README.md | 3 ++- examples/colour-gpu.rs | 15 +++++++++++---- src/helper.rs | 9 ++++++++- src/jail.rs | 25 +++++++++++++------------ src/options.rs | 15 +++++++++++---- src/player.rs | 15 ++++++++++----- src/render.rs | 7 +++++-- tests/helper.rs | 31 ++++++++++++++++++++++++++++++- 9 files changed, 91 insertions(+), 31 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 99f952c..e1fa1d5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ publish = false # dlopen for libmpv, and the system calls a helper player needs (dup2, close_range, prctl). libc = "0.2.191" # memfd, mmap, pipes and poll for a helper player's frames and messages. -rustix = { version = "1.1.6", features = ["fs", "mm", "pipe", "event", "process"] } +rustix = { version = "1.1.6", features = ["fs", "mm", "pipe", "event"] } # The colour tests and the helper test pick their own main, so they can run a copy of # themselves as a helper player. diff --git a/README.md b/README.md index c5e74b1..57d3598 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,8 @@ itself. - A video stops on its last frame, paused, instead of closing (`keep-open`). Play after the end starts again from the beginning. - Nothing of the user's own mpv setup is read: no `mpv.conf`, scripts, profiles or saved - positions. Nothing beside the file is looked for (subtitles, sound, cover art), and nothing + positions. Nothing beside the file is looked for (subtitles, sound, cover art, the chapters a Matroska + file can borrow from others, the files a playlist names), and nothing is fetched online. - No on-screen display or key bindings: the app draws the controls. - Hardware decoding, when on, tries NVDEC, VA-API, then V4L2, and falls back to the CPU. diff --git a/examples/colour-gpu.rs b/examples/colour-gpu.rs index 373d325..7d47279 100644 --- a/examples/colour-gpu.rs +++ b/examples/colour-gpu.rs @@ -229,11 +229,18 @@ fn main() -> ExitCode { let name = case.name(); let clip = match make_clip(case, &dir) { Ok(clip) => clip, - // This machine's FFmpeg couldn't make it (the M1's libx265 is 8-bit only, for - // one): the player wasn't tried, so it hasn't failed, but it isn't a pass either. - Err(e) => { + // This machine's encoder can't make that format (the M1's libx265 is 8-bit only, + // and FFmpeg quietly makes an 8-bit clip instead): the player wasn't tried, so it + // hasn't failed, but it isn't a pass either. Anything else, such as no FFmpeg or a + // clip that doesn't hold what it was made from, is a failure. + Err(e) if e.starts_with("the clip decodes as") => { skipped += 1; - println!("SKIP {name}: no clip: {e}"); + println!("SKIP {name}: this machine can't make it: {e}"); + continue; + } + Err(e) => { + failed += 1; + println!("FAIL {name}: {e}"); continue; } }; diff --git a/src/helper.rs b/src/helper.rs index e035599..a91fb40 100644 --- a/src/helper.rs +++ b/src/helper.rs @@ -241,6 +241,10 @@ pub struct Started { /// goes to the player as descriptor 3 and the frame memory as 4, and nothing else this /// process has open goes with them. With `sound`, a file with no picture plays, rather than /// stopping at `Said::NoVideo`. +/// +/// The player is killed when the thread that calls this ends, not just the process: that's +/// how `PR_SET_PDEATHSIG` and bubblewrap's `--die-with-parent` work. Call it from a thread +/// that lives as long as the player should, such as the one that runs `watch`. pub fn start(mut command: Command, file: File, size: (u32, u32), sound: bool) -> Result { let shared = memfd_create("alias-playback-frames", MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING)?; rustix::fs::ftruncate(&shared, SHARED_BYTES as u64)?; @@ -406,7 +410,10 @@ pub fn watch(mut child: Child, said: File, cancel: &OwnedFd, mut on_said: impl F // A player with no way to report anything has nothing left to do. Ok(None) if ended.elapsed() >= EXIT_GRACE => stop(&mut child), Ok(None) => {} - Err(_) => return None, + Err(_) => { + stop(&mut child); + return None; + } } } else if any { // However fast the player talks, the app hears about it at this rate at most. diff --git a/src/jail.rs b/src/jail.rs index bf66d7e..cabaaf9 100644 --- a/src/jail.rs +++ b/src/jail.rs @@ -74,16 +74,18 @@ pub fn sound_socket() -> Option { Some(runtime_dir.join("pulse/native")).filter(|path| path.exists()) } -/// This program, to start again as a helper. After a package upgrade replaces the running -/// file, `current_exe` names ".../app (deleted)", which can't be started: the new file at the -/// same path is used then. Without one, `/proc/self/exe` still reaches the running file. +/// This program's file, to bind into the jail and start again as a helper. After a package +/// upgrade replaces the running file, `current_exe` names ".../app (deleted)": the new file +/// at the same path is used then. With no file there (the app was removed while running), +/// this fails. `/proc/self/exe` can't stand in: bubblewrap would resolve it in its own +/// process, and bind itself. pub fn own_exe() -> std::io::Result { - Ok(undeleted(std::env::current_exe()?, Path::new("/proc/self/exe"))) + undeleted(std::env::current_exe()?).ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "this program's file was removed while it ran")) } -fn undeleted(exe: PathBuf, running: &Path) -> PathBuf { - let Some(path) = exe.as_os_str().as_bytes().strip_suffix(b" (deleted)").map(|b| Path::new(OsStr::from_bytes(b))) else { return exe }; - if path.is_file() { path.to_path_buf() } else { running.to_path_buf() } +fn undeleted(exe: PathBuf) -> Option { + let Some(path) = exe.as_os_str().as_bytes().strip_suffix(b" (deleted)").map(|b| Path::new(OsStr::from_bytes(b))) else { return Some(exe) }; + path.is_file().then(|| path.to_path_buf()) } #[cfg(test)] @@ -107,15 +109,14 @@ mod tests { } #[test] - fn an_upgraded_program_is_started_from_its_new_file() { + fn an_upgraded_program_is_started_from_its_new_file_and_a_removed_one_not_at_all() { let dir = std::env::temp_dir().join(format!("alias-playback-exe-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let new = dir.join("app"); std::fs::write(&new, b"").unwrap(); - let running = Path::new("/proc/self/exe"); - assert_eq!(undeleted(dir.join("app (deleted)"), running), new); - assert_eq!(undeleted(dir.join("gone (deleted)"), running), running, "no new file: the running one"); - assert_eq!(undeleted(new.clone(), running), new); + assert_eq!(undeleted(dir.join("app (deleted)")), Some(new.clone())); + assert_eq!(undeleted(dir.join("gone (deleted)")), None, "no new file: nothing bubblewrap can bind"); + assert_eq!(undeleted(new.clone()), Some(new)); std::fs::remove_dir_all(dir).unwrap(); } } diff --git a/src/options.rs b/src/options.rs index bdf84a4..9e5b768 100644 --- a/src/options.rs +++ b/src/options.rs @@ -97,6 +97,10 @@ const BASE: &[(&str, &str)] = &[ ("sid", "no"), ("audio-file-auto", "no"), ("cover-art-auto", "no"), + // A Matroska file can name other files to play its chapters from, and a playlist or EDL + // file can name anything. Neither is followed. + ("ordered-chapters", "no"), + ("access-references", "no"), ("ytdl", "no"), // The app has the controls, so no terminal, key bindings or on-screen display. ("terminal", "no"), @@ -126,9 +130,10 @@ pub const BUILT_IN_SCRIPTS: &[&str] = &["load-stats-overlay", "load-console", "l pub fn colour(render: RenderPath) -> &'static [(&'static str, &'static str)] { match render { // The software renderer's converter, zimg, lifts the darks of a video tagged with the - // sRGB transfer (ALI-2418: Tarnished's #121C24 drew as #1D282F). Labelling every - // picture BT.1886 before it's converted fixes that, and the other SDR tags come out - // the same either way, which the colour tests check. Turning zimg off would fix it + // sRGB transfer (ALI-2418: Tarnished's #121C24 drew as #1D282F), and of full-range + // video with no transfer tag, which it takes for sRGB. Labelling every picture BT.1886 + // before it's converted fixes both, and the other SDR tags come out the same either + // way, which the colour tests check. Turning zimg off would fix it // too, but swscale works on one thread: about ten times as long a frame on x86_64 // and two to three times on an M1, too slow for 4K. RenderPath::Cpu => &[("vf", "format=gamma=bt.1886")], @@ -158,7 +163,9 @@ mod tests { #[test] fn nothing_of_the_users_mpv_is_read() { let options = Options::cpu(); - for (name, expected) in [("config", "no"), ("load-scripts", "no"), ("ytdl", "no"), ("sub-auto", "no"), ("cover-art-auto", "no"), ("audio-file-auto", "no")] { + for (name, expected) in + [("config", "no"), ("load-scripts", "no"), ("ytdl", "no"), ("sub-auto", "no"), ("cover-art-auto", "no"), ("audio-file-auto", "no"), ("ordered-chapters", "no"), ("access-references", "no")] + { assert_eq!(value(&options, name), Some(expected), "{name}"); } } diff --git a/src/player.rs b/src/player.rs index 6ddc05c..3239581 100644 --- a/src/player.rs +++ b/src/player.rs @@ -57,7 +57,7 @@ pub enum Event { Failed, /// Seconds from the start. Position(f64), - /// Seconds, once it's known. + /// Seconds, or 0 while it isn't known. Duration(f64), Paused(bool), /// 0 to 100. @@ -317,12 +317,17 @@ impl Player { ffi::EVENT_PROPERTY_CHANGE => { // SAFETY: a property event's data is a property struct, as the caller says. let property = unsafe { &*(event.data as *const ffi::EventProperty) }; - // `None` while a property isn't available, such as the duration before a file - // is open. That's left as it was. + let index = usize::try_from(event.userdata).ok()?.checked_sub(1)?; + // No data while a property isn't available: no file open, or a file whose + // length isn't known. The position and duration go back to 0 then, so the last + // file's don't linger; the rest keep their values, which libmpv still has. if property.data.is_null() || property.format == ffi::FORMAT_NONE { - return None; + return match index { + 0 => Some(Event::Position(0.0)), + 1 => Some(Event::Duration(0.0)), + _ => None, + }; } - let index = usize::try_from(event.userdata).ok()?.checked_sub(1)?; let (_, format) = WATCHED.get(index)?; if property.format != *format { return None; diff --git a/src/render.rs b/src/render.rs index bc4bb1a..7fa0960 100644 --- a/src/render.rs +++ b/src/render.rs @@ -156,9 +156,12 @@ fn fits(width: u32, height: u32, stride: usize, pixels: &[u8]) -> bool { } /// libmpv's OpenGL renderer. The app owns the GL context, and makes it current on the -/// thread that creates and uses this. +/// thread that creates, uses and drops this, which is why it can't move to another thread. pub struct GlRender { context: Context, + /// Not `Send`: freeing it needs its OpenGL context current, which is only known on the + /// thread that made it. + _same_thread: std::marker::PhantomData<*const ()>, } impl GlRender { @@ -177,7 +180,7 @@ impl GlRender { params.push(ffi::RenderParam { kind: ffi::RENDER_WL_DISPLAY, data: display }); } params.push(ffi::RenderParam { kind: ffi::RENDER_INVALID, data: std::ptr::null_mut() }); - Ok(Self { context: Context::create(player, &mut params)? }) + Ok(Self { context: Context::create(player, &mut params)?, _same_thread: std::marker::PhantomData }) } /// As for `SwRender::on_update`. diff --git a/tests/helper.rs b/tests/helper.rs index 06c80a9..bd0ac6e 100644 --- a/tests/helper.rs +++ b/tests/helper.rs @@ -26,12 +26,13 @@ fn main() -> ExitCode { if args.first().map(String::as_str) == Some(HELPER_ARG) { helper::run(&args[1..], &Options::cpu(), SANDBOX_CODE, || true); } - let tests: [Test; 5] = [ + let tests: [Test; 6] = [ ("a_video_draws_its_frames_and_stops_on_the_last", a_video_draws_its_frames_and_stops_on_the_last), ("play_after_the_end_starts_again", play_after_the_end_starts_again), ("a_new_size_redraws_the_frame_even_when_stopped", a_new_size_redraws_the_frame_even_when_stopped), ("sound_only_files_say_so_or_play_when_allowed", sound_only_files_say_so_or_play_when_allowed), ("a_file_that_isnt_media_cant_play", a_file_that_isnt_media_cant_play), + ("the_last_files_position_and_duration_dont_linger", the_last_files_position_and_duration_dont_linger), ]; if args.iter().any(|a| a == "--list") { for (name, _) in tests { @@ -212,3 +213,31 @@ fn a_file_that_isnt_media_cant_play(dir: &Path) { let player = Running::start(&junk, (64, 36), false); player.wait_for("can't play", |s| (s == Said::CantPlay).then_some(())); } + +/// After a file is closed there's no position or duration, and the app hears they're back to +/// 0 rather than keeping the last file's. +fn the_last_files_position_and_duration_dont_linger(dir: &Path) { + use alias_playback::{Event, Player, SwRender}; + let player = Player::new(&Options::cpu()).expect("libmpv"); + // libmpv's video output waits for a renderer before it opens a file with a picture. + let _render = SwRender::new(&player).expect("a renderer"); + let mut duration = 0.0; + player.load(&video(dir)).expect("load"); + let deadline = Instant::now() + Duration::from_secs(5); + while duration == 0.0 && Instant::now() < deadline { + if let Some(Event::Duration(d)) = player.wait_event(Duration::from_millis(50)) { + duration = d; + } + } + assert!(duration > 0.4, "the clip's duration arrived: {duration}"); + player.command(&[b"stop"]).expect("stop"); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + assert!(Instant::now() < deadline, "never heard the duration go back to 0"); + if let Some(Event::Duration(d)) = player.wait_event(Duration::from_millis(50)) + && d == 0.0 + { + break; + } + } +} From 827a83ca233d26030098e441b22683dc8f83e098 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 05:56:38 -0700 Subject: [PATCH 03/25] Review fixes: clear the end with the file, and always load a file - When a file closes, the end also goes back to not reached (Ended(false)), as the position and duration already do. Before, an app that had shown "ended" kept showing it with nothing loaded. The helper test now checks it, and fails without this. - Player::load always passes a path libmpv reads as a file: a relative one gets "./" in front. A relative path shaped like "http://host/x" or "edl://..." would otherwise be fetched or built by libmpv. --- src/player.rs | 30 ++++++++++++++++++++++++++---- tests/helper.rs | 22 ++++++++++++++-------- 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/src/player.rs b/src/player.rs index 3239581..b75bdf5 100644 --- a/src/player.rs +++ b/src/player.rs @@ -171,9 +171,11 @@ impl Player { Ok(()) } - /// Opens a file, in place of whatever was playing. + /// Opens a file, in place of whatever was playing. Always as a file: a relative path + /// such as `http://host/x` or `edl://...` is a file of that name in the current folder, + /// not something for libmpv to fetch or build. pub fn load(&self, path: &Path) -> Result<(), Error> { - self.command(&[b"loadfile", path.as_os_str().as_bytes()]) + self.command(&[b"loadfile", as_file(path).as_os_str().as_bytes()]) } /// Opens a file this process has open, for a player that can't see the file system. @@ -319,12 +321,14 @@ impl Player { let property = unsafe { &*(event.data as *const ffi::EventProperty) }; let index = usize::try_from(event.userdata).ok()?.checked_sub(1)?; // No data while a property isn't available: no file open, or a file whose - // length isn't known. The position and duration go back to 0 then, so the last - // file's don't linger; the rest keep their values, which libmpv still has. + // length isn't known. The position and duration go back to 0 then, and the end + // to not reached, so the last file's don't linger. Pause, volume and mute are + // always available. if property.data.is_null() || property.format == ffi::FORMAT_NONE { return match index { 0 => Some(Event::Position(0.0)), 1 => Some(Event::Duration(0.0)), + 5 => Some(Event::Ended(false)), _ => None, }; } @@ -355,6 +359,11 @@ impl Player { } } +/// `path`, starting with `/` or `./`, which libmpv only ever reads as a file. +fn as_file(path: &Path) -> std::borrow::Cow<'_, Path> { + if path.is_absolute() { std::borrow::Cow::Borrowed(path) } else { std::borrow::Cow::Owned(Path::new(".").join(path)) } +} + unsafe extern "C" fn call_wakeup(data: *mut c_void) { // SAFETY: `data` is a `Wakeup` that `on_wakeup` keeps alive until the handle is destroyed. unsafe { (*(data as *const Wakeup))() }; @@ -371,3 +380,16 @@ impl Core { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_path_is_always_read_as_a_file() { + assert_eq!(as_file(Path::new("/v/a.mkv")), Path::new("/v/a.mkv")); + assert_eq!(as_file(Path::new("http://host/x")).as_os_str(), "./http://host/x"); + assert_eq!(as_file(Path::new("edl://a;b")).as_os_str(), "./edl://a;b"); + assert_eq!(as_file(Path::new("a.mkv")).as_os_str(), "./a.mkv"); + } +} diff --git a/tests/helper.rs b/tests/helper.rs index bd0ac6e..2284558 100644 --- a/tests/helper.rs +++ b/tests/helper.rs @@ -214,8 +214,8 @@ fn a_file_that_isnt_media_cant_play(dir: &Path) { player.wait_for("can't play", |s| (s == Said::CantPlay).then_some(())); } -/// After a file is closed there's no position or duration, and the app hears they're back to -/// 0 rather than keeping the last file's. +/// After a file is closed there's no position, duration or end, and the app hears they're +/// cleared rather than keeping the last file's. fn the_last_files_position_and_duration_dont_linger(dir: &Path) { use alias_playback::{Event, Player, SwRender}; let player = Player::new(&Options::cpu()).expect("libmpv"); @@ -230,14 +230,20 @@ fn the_last_files_position_and_duration_dont_linger(dir: &Path) { } } assert!(duration > 0.4, "the clip's duration arrived: {duration}"); + player.set_paused(false).expect("play"); + let deadline = Instant::now() + Duration::from_secs(5); + while player.wait_event(Duration::from_millis(50)) != Some(Event::Ended(true)) { + assert!(Instant::now() < deadline, "never reached the end"); + } player.command(&[b"stop"]).expect("stop"); let deadline = Instant::now() + Duration::from_secs(5); - loop { - assert!(Instant::now() < deadline, "never heard the duration go back to 0"); - if let Some(Event::Duration(d)) = player.wait_event(Duration::from_millis(50)) - && d == 0.0 - { - break; + let (mut duration_cleared, mut end_cleared) = (false, false); + while !(duration_cleared && end_cleared) { + assert!(Instant::now() < deadline, "duration back to 0: {duration_cleared}, end cleared: {end_cleared}"); + match player.wait_event(Duration::from_millis(50)) { + Some(Event::Duration(0.0)) => duration_cleared = true, + Some(Event::Ended(false)) => end_cleared = true, + _ => {} } } } From 823293b2f0e465984944f3f4ab52bde8ad587075 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 06:15:00 -0700 Subject: [PATCH 04/25] GPU helper prototype: libmpv on the card, frames handed over as dmabufs A jailed helper draws with libmpv's OpenGL renderer into GBM buffers on the compositor's card and passes their dmabufs to the app over a SOCK_SEQPACKET socket. The buffers use layouts OpenGL can draw into, which EGL reports. Hardware decoding gets the render node (VA-API) or CUDA (NVDEC). The GPU jail adds the card's device files and /sys. On NVIDIA it also adds /proc, which CUDA needs. Landlock then refuses opening anything outside /dev for writing, so /proc/self/mem can't change code. examples/gpu-play plays a file through the helper and prints frames, first frame, dropped frames, CPU and memory. Prototype for ALI-2358; not for merging as it is. --- examples/colour-gpu.rs | 4 +- examples/gpu-play.rs | 133 +++++++++++ src/ffi.rs | 12 + src/gpu.rs | 451 ++++++++++++++++++++++++++++++++++++++ src/gpu_helper.rs | 486 +++++++++++++++++++++++++++++++++++++++++ src/helper.rs | 2 +- src/jail.rs | 94 ++++++++ src/lib.rs | 4 +- src/render.rs | 26 ++- 9 files changed, 1203 insertions(+), 9 deletions(-) create mode 100644 examples/gpu-play.rs create mode 100644 src/gpu.rs create mode 100644 src/gpu_helper.rs diff --git a/examples/colour-gpu.rs b/examples/colour-gpu.rs index 7d47279..d178511 100644 --- a/examples/colour-gpu.rs +++ b/examples/colour-gpu.rs @@ -21,7 +21,7 @@ use std::process::ExitCode; use std::sync::OnceLock; use std::time::{Duration, Instant}; -use alias_playback::{Event, GlRender, Hwdec, Options, Player, RenderPath}; +use alias_playback::{Event, GlRender, Hwdec, Native, Options, Player, RenderPath}; use clips::{HEIGHT, TOLERANCE, WIDTH, cases, check_the_maths, decoder, make_clip, misses, play_cpu}; type EglDisplay = *mut c_void; @@ -181,7 +181,7 @@ fn play(gl: &Gl, clip: &Path, hwdec: Hwdec) -> Result<(Vec, String), String let player = Player::new(&options).map_err(|e| e.to_string())?; // SAFETY: the context is current on this thread for as long as the renderer lives, and the // lookup finds its functions. - let mut render = unsafe { GlRender::new(&player, get_proc_address, std::ptr::null_mut(), None) }.map_err(|e| e.to_string())?; + let mut render = unsafe { GlRender::new(&player, get_proc_address, std::ptr::null_mut(), Native::None) }.map_err(|e| e.to_string())?; // `COLOUR_GPU_LOG=FILE` keeps libmpv's log of the last case run, for a case that fails. if let Some(log) = std::env::var_os("COLOUR_GPU_LOG") { use std::os::unix::ffi::OsStrExt; diff --git a/examples/gpu-play.rs b/examples/gpu-play.rs new file mode 100644 index 0000000..a7f3796 --- /dev/null +++ b/examples/gpu-play.rs @@ -0,0 +1,133 @@ +//! The GPU helper prototype's measuring app (ALI-2358): plays a file through a GPU helper +//! player, jailed or not, takes its dmabufs as a compositor would (holding the newest frame, +//! giving the one before back), and prints what it cost. +//! +//! ```sh +//! cargo run --release --example gpu-play -- FILE [--jail] [--hwdec] [--size WxH] [--check] +//! ``` +//! +//! `--check` reads the first frame back from its dmabuf and prints the middle pixel, which +//! shows the frames cross the processes whole and in the right colours. + +use std::fs::File; +use std::os::fd::OwnedFd; +use std::process::Command; +use std::time::Instant; + +use alias_playback::gpu::{Gpu, Plane, first_render_node}; +use alias_playback::gpu_helper::{self, SLOTS, Said}; +use alias_playback::{Audio, Hwdec, Options, RenderPath, jail}; + +const HELPER_ARG: &str = "--gpu-helper"; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.first().map(String::as_str) == Some(HELPER_ARG) { + // The decoding choice, then the size `start` adds. + let hwdec = if args.get(1).map(String::as_str) == Some("hwdec") { Hwdec::Auto } else { Hwdec::Off }; + let options = Options { render: RenderPath::Gpu, hwdec, audio: Audio::Off, cover_art: false, start_paused: true }; + gpu_helper::run(&args[2..], &options, 6, || jail::forbid_writes_outside(&[std::path::Path::new("/dev")])); + } + let file = args.first().expect("a file to play").clone(); + let flag = |name: &str| args.iter().any(|a| a == name); + let size = args.iter().position(|a| a == "--size").and_then(|i| args.get(i + 1)).and_then(|s| s.split_once('x')).map_or((1920, 1080), |(w, h)| (w.parse().unwrap(), h.parse().unwrap())); + + let node = first_render_node().expect("a render node"); + let checker = flag("--check").then(|| Gpu::new(node.try_clone().expect("a copy")).expect("OpenGL for the check")); + let exe = jail::own_exe().expect("own path"); + let mut command = if flag("--jail") { + let mut command = Command::new("bwrap"); + command.args(jail::gpu_arguments(&exe)).arg(HELPER_ARG); + command + } else { + let mut command = Command::new(&exe); + command.arg(HELPER_ARG); + command + }; + command.arg(if flag("--hwdec") { "hwdec" } else { "software" }); + let start = Instant::now(); + let mut started = gpu_helper::start(command, File::open(&file).expect("the file"), node, size).expect("the helper"); + gpu_helper::send(&started.socket, "play", &[]).expect("play"); + let mut buffers: [Option<(Said, Vec)>; SLOTS] = [None, None, None]; + let (mut frames, mut first_frame, mut shown): (u64, Option, Option) = (0, None, None); + let (mut dropped, mut state, mut decoder) = ((0, 0), None, String::from("?")); + while let Ok(Some((text, fds))) = gpu_helper::receive(&started.socket) { + if std::env::var_os("GPU_PLAY_DEBUG").is_some() { + eprintln!("< {text}"); + } + match gpu_helper::parse_said(&text) { + Some(said @ Said::Buffer { slot, .. }) if fds.len() == 1 => buffers[slot] = Some((said, fds)), + Some(Said::Buffer { .. }) => {} + Some(Said::Frame { slot }) if buffers[slot].is_some() => { + frames += 1; + if first_frame.is_none() { + first_frame = Some(start.elapsed().as_secs_f64() * 1000.0); + if let (Some(gpu), Some((Said::Buffer { width, height, modifier, stride, offset, .. }, fds))) = (&checker, &buffers[slot]) { + let planes = [Plane { fd: fds[0].try_clone().expect("a copy"), stride: *stride, offset: *offset }]; + let pixels = gpu.read_dmabuf(*width, *height, *modifier, &planes).expect("read back"); + let middle = pixels[(*height / 2 * *width + *width / 2) as usize]; + println!("first frame {width}x{height}, modifier {modifier:#x}, middle #{middle:06X}"); + } + } + // A compositor gives the last buffer back once the new one is on screen. + if let Some(old) = shown.replace(slot) { + let _ = gpu_helper::send(&started.socket, &format!("release {old}"), &[]); + } + } + Some(Said::Dropped { decoder, late }) => dropped = (decoder, late), + Some(Said::Decoder(name)) => decoder = name, + Some(Said::State(s)) => { + state = Some(s); + if s.ended { + break; + } + } + Some(Said::CantPlay) | Some(Said::NoVideo) => { + println!("{text}"); + break; + } + _ => {} + } + } + let wall = start.elapsed().as_secs_f64(); + // The helper and anything under it (bubblewrap's own processes when jailed), read from + // /proc before it goes: a jailed helper isn't this process's child to wait for. + let (cpu, rss_kb) = usage_below(started.child.id()); + drop(buffers); + drop(started.socket); + let _ = started.child.wait(); + let duration = state.map_or(0.0, |s| s.duration); + println!( + "{file}: {decoder}, {frames} frames in {wall:.2} s (clip {duration:.2} s), first frame {:.0} ms, dropped {} decoder + {} late, helper CPU {cpu:.2} s, helper peak RSS {} MB", + first_frame.unwrap_or(f64::NAN), + dropped.0, + dropped.1, + rss_kb / 1024 + ); +} + +/// CPU seconds and the largest peak RSS (KB) of `pid` and every process below it. +fn usage_below(pid: u32) -> (f64, u64) { + // SAFETY: a plain query. + let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) } as f64; + let (mut cpu, mut rss) = (0.0, 0); + let mut queue = vec![pid]; + while let Some(pid) = queue.pop() { + if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) { + let fields: Vec<&str> = stat.rsplit_once(')').map_or("", |r| r.1).split_whitespace().collect(); + let n = |i: usize| fields.get(i).and_then(|f| f.parse::().ok()).unwrap_or(0.0); + // utime, stime, cutime, cstime: fields 14 to 17, here 11 to 14 after the name. + cpu += (n(11) + n(12) + n(13) + n(14)) / ticks; + } + if let Ok(status) = std::fs::read_to_string(format!("/proc/{pid}/status")) { + let hwm = status.lines().find_map(|l| l.strip_prefix("VmHWM:")).and_then(|v| v.trim().trim_end_matches(" kB").parse::().ok()).unwrap_or(0); + rss = rss.max(hwm); + } + for task in std::fs::read_dir(format!("/proc/{pid}/task")).into_iter().flatten().flatten() { + if let Ok(children) = std::fs::read_to_string(task.path().join("children")) { + queue.extend(children.split_whitespace().filter_map(|c| c.parse::().ok())); + } + } + } + (cpu, rss) +} diff --git a/src/ffi.rs b/src/ffi.rs index 2682c7b..3d46370 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -54,6 +54,17 @@ pub struct OpenGlFbo { pub internal_format: c_int, } +/// `mpv_opengl_drm_params_v2`. Only `render_fd` is used here: it lets libmpv's VA-API +/// decoding share frames with OpenGL with no display connection at all. +#[repr(C)] +pub struct OpenGlDrmParamsV2 { + pub fd: c_int, + pub crtc_id: c_int, + pub connector_id: c_int, + pub atomic_request_ptr: *mut c_void, + pub render_fd: c_int, +} + pub const FORMAT_NONE: c_int = 0; pub const FORMAT_FLAG: c_int = 3; pub const FORMAT_DOUBLE: c_int = 5; @@ -74,6 +85,7 @@ pub const RENDER_OPENGL_INIT_PARAMS: c_int = 2; pub const RENDER_OPENGL_FBO: c_int = 3; pub const RENDER_FLIP_Y: c_int = 4; pub const RENDER_WL_DISPLAY: c_int = 9; +pub const RENDER_DRM_DISPLAY_V2: c_int = 16; pub const RENDER_SW_SIZE: c_int = 17; pub const RENDER_SW_FORMAT: c_int = 18; pub const RENDER_SW_STRIDE: c_int = 19; diff --git a/src/gpu.rs b/src/gpu.rs new file mode 100644 index 0000000..011f5b3 --- /dev/null +++ b/src/gpu.rs @@ -0,0 +1,451 @@ +//! OpenGL on a graphics card with no window, drawing into dmabufs another process can show. +//! +//! A GPU helper player draws with libmpv's OpenGL renderer into buffers allocated with GBM +//! on the card the app's compositor uses, and hands their dmabufs to the app, which gives +//! them to the compositor through `linux-dmabuf`. The frame never leaves the card, and the +//! player never sees the app's Wayland connection. +//! +//! Everything is looked up at run time, as libmpv is: libgbm, libEGL and the GL functions +//! EGL finds. The types and numbers are from `gbm.h`, `EGL/egl.h`, `EGL/eglext.h` and the +//! GL headers. + +use std::ffi::{CStr, c_char, c_int, c_void}; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + +/// `XRGB8888`: what `wl_shm` frames use too, and every compositor takes. +pub const FOURCC_XRGB8888: u32 = u32::from_le_bytes(*b"XR24"); +/// The driver's own choice of layout, said without naming one. +pub const MOD_INVALID: u64 = 0x00ff_ffff_ffff_ffff; + +const EGL_NONE: i32 = 0x3038; +const EGL_EXTENSIONS: i32 = 0x3055; +const EGL_RENDERABLE_TYPE: i32 = 0x3040; +const EGL_OPENGL_BIT: i32 = 0x0008; +const EGL_SURFACE_TYPE: i32 = 0x3033; +const EGL_OPENGL_API: u32 = 0x30A2; +const EGL_PLATFORM_GBM_KHR: u32 = 0x31D7; +const EGL_LINUX_DMA_BUF_EXT: u32 = 0x3270; +const EGL_WIDTH: i32 = 0x3057; +const EGL_HEIGHT: i32 = 0x3056; +const EGL_LINUX_DRM_FOURCC_EXT: i32 = 0x3271; +const EGL_DMA_BUF_PLANE0_FD_EXT: i32 = 0x3272; +const EGL_DMA_BUF_PLANE0_OFFSET_EXT: i32 = 0x3273; +const EGL_DMA_BUF_PLANE0_PITCH_EXT: i32 = 0x3274; +const EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT: i32 = 0x3443; +const EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT: i32 = 0x3444; +const EGL_CONTEXT_MAJOR_VERSION: i32 = 0x3098; +const EGL_CONTEXT_MINOR_VERSION: i32 = 0x30FB; +const EGL_CONTEXT_OPENGL_PROFILE_MASK: i32 = 0x30FD; + +const GBM_BO_USE_RENDERING: u32 = 1 << 2; + +const GL_TEXTURE_2D: u32 = 0x0DE1; +const GL_FRAMEBUFFER: u32 = 0x8D40; +const GL_COLOR_ATTACHMENT0: u32 = 0x8CE0; +const GL_FRAMEBUFFER_COMPLETE: u32 = 0x8CD5; +const GL_RGBA: u32 = 0x1908; +const GL_UNSIGNED_BYTE: u32 = 0x1401; +const GL_PACK_ALIGNMENT: u32 = 0x0D05; +const GL_RENDERER: u32 = 0x1F01; +pub const GL_RGBA8: i32 = 0x8058; + +type Ptr = *mut c_void; + +struct Gbm { + create_device: unsafe extern "C" fn(c_int) -> Ptr, + device_destroy: unsafe extern "C" fn(Ptr), + bo_create: unsafe extern "C" fn(Ptr, u32, u32, u32, u32) -> Ptr, + bo_create_with_modifiers2: unsafe extern "C" fn(Ptr, u32, u32, u32, *const u64, u32, u32) -> Ptr, + bo_destroy: unsafe extern "C" fn(Ptr), + bo_get_plane_count: unsafe extern "C" fn(Ptr) -> c_int, + bo_get_fd_for_plane: unsafe extern "C" fn(Ptr, c_int) -> c_int, + bo_get_stride_for_plane: unsafe extern "C" fn(Ptr, c_int) -> u32, + bo_get_offset: unsafe extern "C" fn(Ptr, c_int) -> u32, + bo_get_modifier: unsafe extern "C" fn(Ptr) -> u64, +} + +struct Egl { + get_proc_address: unsafe extern "C" fn(*const c_char) -> Ptr, + get_platform_display: unsafe extern "C" fn(u32, Ptr, *const isize) -> Ptr, + initialize: unsafe extern "C" fn(Ptr, *mut i32, *mut i32) -> u32, + terminate: unsafe extern "C" fn(Ptr) -> u32, + bind_api: unsafe extern "C" fn(u32) -> u32, + query_string: unsafe extern "C" fn(Ptr, i32) -> *const c_char, + choose_config: unsafe extern "C" fn(Ptr, *const i32, *mut Ptr, i32, *mut i32) -> u32, + create_context: unsafe extern "C" fn(Ptr, Ptr, Ptr, *const i32) -> Ptr, + destroy_context: unsafe extern "C" fn(Ptr, Ptr) -> u32, + make_current: unsafe extern "C" fn(Ptr, Ptr, Ptr, Ptr) -> u32, + create_image: unsafe extern "C" fn(Ptr, Ptr, u32, Ptr, *const i32) -> Ptr, + query_modifiers: unsafe extern "C" fn(Ptr, i32, i32, *mut u64, *mut u32, *mut i32) -> u32, + destroy_image: unsafe extern "C" fn(Ptr, Ptr) -> u32, +} + +struct Gl { + gen_textures: unsafe extern "C" fn(i32, *mut u32), + delete_textures: unsafe extern "C" fn(i32, *const u32), + bind_texture: unsafe extern "C" fn(u32, u32), + image_target_texture: unsafe extern "C" fn(u32, Ptr), + gen_framebuffers: unsafe extern "C" fn(i32, *mut u32), + delete_framebuffers: unsafe extern "C" fn(i32, *const u32), + bind_framebuffer: unsafe extern "C" fn(u32, u32), + framebuffer_texture: unsafe extern "C" fn(u32, u32, u32, u32, i32), + check_framebuffer: unsafe extern "C" fn(u32) -> u32, + finish: unsafe extern "C" fn(), + flush: unsafe extern "C" fn(), + read_pixels: unsafe extern "C" fn(i32, i32, i32, i32, u32, u32, Ptr), + pixel_store: unsafe extern "C" fn(u32, i32), + get_string: unsafe extern "C" fn(u32) -> *const c_char, +} + +/// Opens a library for good, or says which. +fn open(name: &CStr) -> Result { + // SAFETY: opening a system library by name. It's never closed. + let library = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; + if library.is_null() { Err(format!("no {}", name.to_string_lossy())) } else { Ok(library) } +} + +/// Looks up `$name` with `$find` as the type it's assigned to, or returns an error. +macro_rules! lookup { + ($find:expr, $name:literal) => {{ + // The finders are closures around dlsym or eglGetProcAddress, given a terminated name. + let found = $find(concat!($name, "\0").as_ptr() as *const c_char); + if found.is_null() { + return Err(concat!("no ", $name).to_owned()); + } + // SAFETY: the type assigned to is the function's type in its header. + #[allow(clippy::missing_transmute_annotations)] + unsafe { + std::mem::transmute(found) + } + }}; +} + +/// A card, with an OpenGL context current on the thread that made it. +pub struct Gpu { + gbm: Gbm, + egl: Egl, + gl: Gl, + device: Ptr, + display: Ptr, + context: Ptr, + /// The render node, kept open for the device's life. + _node: OwnedFd, + pub renderer: String, +} + +/// One plane of a dmabuf, as `linux-dmabuf` takes it. +#[derive(Debug)] +pub struct Plane { + pub fd: OwnedFd, + pub stride: u32, + pub offset: u32, +} + +/// A buffer libmpv draws into: the GBM buffer, its dmabuf planes, and the framebuffer on it. +pub struct Target { + pub width: u32, + pub height: u32, + pub fourcc: u32, + pub modifier: u64, + pub planes: Vec, + pub fbo: u32, + texture: u32, + image: Ptr, + bo: Ptr, +} + +impl Gpu { + /// OpenGL on the card behind `node`, a DRM render node such as `/dev/dri/renderD128`, + /// made current on this thread. Stays on this thread: it isn't `Send`. + pub fn new(node: OwnedFd) -> Result { + let gbm_lib = open(c"libgbm.so.1")?; + let egl_lib = open(c"libEGL.so.1")?; + // SAFETY (all three finders): lookups in libraries kept open, by terminated name. + let gbm_sym = |name: *const c_char| unsafe { libc::dlsym(gbm_lib, name) }; + let egl_sym = |name: *const c_char| unsafe { libc::dlsym(egl_lib, name) }; + let gbm = Gbm { + create_device: lookup!(gbm_sym, "gbm_create_device"), + device_destroy: lookup!(gbm_sym, "gbm_device_destroy"), + bo_create: lookup!(gbm_sym, "gbm_bo_create"), + bo_create_with_modifiers2: lookup!(gbm_sym, "gbm_bo_create_with_modifiers2"), + bo_destroy: lookup!(gbm_sym, "gbm_bo_destroy"), + bo_get_plane_count: lookup!(gbm_sym, "gbm_bo_get_plane_count"), + bo_get_fd_for_plane: lookup!(gbm_sym, "gbm_bo_get_fd_for_plane"), + bo_get_stride_for_plane: lookup!(gbm_sym, "gbm_bo_get_stride_for_plane"), + bo_get_offset: lookup!(gbm_sym, "gbm_bo_get_offset"), + bo_get_modifier: lookup!(gbm_sym, "gbm_bo_get_modifier"), + }; + let get_proc_address: unsafe extern "C" fn(*const c_char) -> Ptr = lookup!(egl_sym, "eglGetProcAddress"); + let proc = |name: *const c_char| unsafe { get_proc_address(name) }; + let egl = Egl { + get_proc_address, + get_platform_display: lookup!(egl_sym, "eglGetPlatformDisplay"), + initialize: lookup!(egl_sym, "eglInitialize"), + terminate: lookup!(egl_sym, "eglTerminate"), + bind_api: lookup!(egl_sym, "eglBindAPI"), + query_string: lookup!(egl_sym, "eglQueryString"), + choose_config: lookup!(egl_sym, "eglChooseConfig"), + create_context: lookup!(egl_sym, "eglCreateContext"), + destroy_context: lookup!(egl_sym, "eglDestroyContext"), + make_current: lookup!(egl_sym, "eglMakeCurrent"), + create_image: lookup!(proc, "eglCreateImageKHR"), + destroy_image: lookup!(proc, "eglDestroyImageKHR"), + query_modifiers: lookup!(proc, "eglQueryDmaBufModifiersEXT"), + }; + // SAFETY of the block: EGL and GBM calls with their headers' types, results checked. + let (device, display, context) = unsafe { + let device = (gbm.create_device)(node.as_raw_fd()); + if device.is_null() { + return Err("GBM can't open the card".into()); + } + let display = (egl.get_platform_display)(EGL_PLATFORM_GBM_KHR, device, [EGL_NONE as isize].as_ptr()); + let (mut major, mut minor) = (0, 0); + if display.is_null() || (egl.initialize)(display, &mut major, &mut minor) == 0 { + (gbm.device_destroy)(device); + return Err("EGL can't use the card".into()); + } + let extensions = CStr::from_ptr((egl.query_string)(display, EGL_EXTENSIONS)).to_string_lossy().into_owned(); + for needed in ["EGL_EXT_image_dma_buf_import", "EGL_EXT_image_dma_buf_import_modifiers", "EGL_KHR_surfaceless_context"] { + if !extensions.split(' ').any(|e| e == needed) { + return Err(format!("EGL lacks {needed}")); + } + } + (egl.bind_api)(EGL_OPENGL_API); + let mut config: Ptr = std::ptr::null_mut(); + let mut count = 0; + let wanted = [EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_SURFACE_TYPE, 0, EGL_NONE]; + if (egl.choose_config)(display, wanted.as_ptr(), &mut config, 1, &mut count) == 0 || count == 0 { + return Err("EGL has no OpenGL config".into()); + } + // The newest compatibility context the driver gives, or core 3.3. + let core = [EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3, EGL_CONTEXT_OPENGL_PROFILE_MASK, 1, EGL_NONE]; + let mut context = std::ptr::null_mut(); + for attributes in [&[EGL_NONE][..], &core[..]] { + context = (egl.create_context)(display, config, std::ptr::null_mut(), attributes.as_ptr()); + if !context.is_null() { + break; + } + } + if context.is_null() || (egl.make_current)(display, std::ptr::null_mut(), std::ptr::null_mut(), context) == 0 { + return Err("EGL won't make an OpenGL context".into()); + } + (device, display, context) + }; + let gl = Gl { + gen_textures: lookup!(proc, "glGenTextures"), + delete_textures: lookup!(proc, "glDeleteTextures"), + bind_texture: lookup!(proc, "glBindTexture"), + image_target_texture: lookup!(proc, "glEGLImageTargetTexture2DOES"), + gen_framebuffers: lookup!(proc, "glGenFramebuffers"), + delete_framebuffers: lookup!(proc, "glDeleteFramebuffers"), + bind_framebuffer: lookup!(proc, "glBindFramebuffer"), + framebuffer_texture: lookup!(proc, "glFramebufferTexture2D"), + check_framebuffer: lookup!(proc, "glCheckFramebufferStatus"), + finish: lookup!(proc, "glFinish"), + flush: lookup!(proc, "glFlush"), + read_pixels: lookup!(proc, "glReadPixels"), + pixel_store: lookup!(proc, "glPixelStorei"), + get_string: lookup!(proc, "glGetString"), + }; + // SAFETY: the context is current. + let renderer = unsafe { + let name = (gl.get_string)(GL_RENDERER); + if name.is_null() { "unknown".into() } else { CStr::from_ptr(name).to_string_lossy().into_owned() } + }; + Ok(Self { gbm, egl, gl, device, display, context, _node: node, renderer }) + } + + /// For libmpv's OpenGL renderer: looks up GL functions in this context. + pub fn proc_address(&self) -> (crate::ffi::GetProcAddress, *mut c_void) { + (find_proc, self.egl.get_proc_address as *mut c_void) + } + + /// A buffer `width` by `height` in `XRGB8888`, in one of `modifiers` (the compositor's, + /// for this format), or in the driver's own layout if the list is empty. + pub fn target(&self, width: u32, height: u32, modifiers: &[u64]) -> Result { + // Only layouts OpenGL can draw into, not just sample from, and of those the + // compositor's if it said. + let drawable = self.drawable_modifiers(); + let usable: Vec = if modifiers.is_empty() { drawable } else { modifiers.iter().copied().filter(|m| drawable.contains(m)).collect() }; + // SAFETY of the block: GBM, EGL and GL calls on a live device and current context, + // with results checked and everything made here freed on failure or in `drop_target`. + unsafe { + let bo = if usable.is_empty() { + (self.gbm.bo_create)(self.device, width, height, FOURCC_XRGB8888, GBM_BO_USE_RENDERING) + } else { + (self.gbm.bo_create_with_modifiers2)(self.device, width, height, FOURCC_XRGB8888, usable.as_ptr(), usable.len() as u32, GBM_BO_USE_RENDERING) + }; + if bo.is_null() { + return Err(format!("GBM won't make a {width}x{height} buffer")); + } + let modifier = (self.gbm.bo_get_modifier)(bo); + let mut planes = Vec::new(); + for plane in 0..(self.gbm.bo_get_plane_count)(bo).max(1) { + let fd = (self.gbm.bo_get_fd_for_plane)(bo, plane); + if fd < 0 { + (self.gbm.bo_destroy)(bo); + return Err("GBM won't export the buffer".into()); + } + planes.push(Plane { fd: OwnedFd::from_raw_fd(fd), stride: (self.gbm.bo_get_stride_for_plane)(bo, plane), offset: (self.gbm.bo_get_offset)(bo, plane) }); + } + let image = self.import(width, height, modifier, &planes); + if image.is_null() { + (self.gbm.bo_destroy)(bo); + return Err("EGL won't take the buffer".into()); + } + let (mut texture, mut fbo) = (0, 0); + (self.gl.gen_textures)(1, &mut texture); + (self.gl.bind_texture)(GL_TEXTURE_2D, texture); + (self.gl.image_target_texture)(GL_TEXTURE_2D, image); + (self.gl.gen_framebuffers)(1, &mut fbo); + (self.gl.bind_framebuffer)(GL_FRAMEBUFFER, fbo); + (self.gl.framebuffer_texture)(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); + let complete = (self.gl.check_framebuffer)(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; + let target = Target { width, height, fourcc: FOURCC_XRGB8888, modifier, planes, fbo, texture, image, bo }; + if !complete { + self.drop_target(target); + return Err("the buffer can't be drawn into".into()); + } + Ok(target) + } + } + + /// The layouts of `XRGB8888` OpenGL on this card can draw into. + pub fn drawable_modifiers(&self) -> Vec { + // SAFETY: a live display; the arrays are sized to the count asked for. + unsafe { + let mut count = 0; + if (self.egl.query_modifiers)(self.display, FOURCC_XRGB8888 as i32, 0, std::ptr::null_mut(), std::ptr::null_mut(), &mut count) == 0 || count <= 0 { + return Vec::new(); + } + let (mut modifiers, mut external) = (vec![0u64; count as usize], vec![0u32; count as usize]); + (self.egl.query_modifiers)(self.display, FOURCC_XRGB8888 as i32, count, modifiers.as_mut_ptr(), external.as_mut_ptr(), &mut count); + modifiers.into_iter().zip(external).take(count as usize).filter(|(_, external)| *external == 0).map(|(m, _)| m).collect() + } + } + + /// An EGL image of a dmabuf's first plane (`XRGB8888` has one). + /// + /// # Safety + /// The context must be current, and `planes` a live dmabuf of that size and layout. + unsafe fn import(&self, width: u32, height: u32, modifier: u64, planes: &[Plane]) -> Ptr { + let plane = &planes[0]; + let mut attributes = vec![ + EGL_WIDTH, + width as i32, + EGL_HEIGHT, + height as i32, + EGL_LINUX_DRM_FOURCC_EXT, + FOURCC_XRGB8888 as i32, + EGL_DMA_BUF_PLANE0_FD_EXT, + plane.fd.as_raw_fd(), + EGL_DMA_BUF_PLANE0_OFFSET_EXT, + plane.offset as i32, + EGL_DMA_BUF_PLANE0_PITCH_EXT, + plane.stride as i32, + ]; + if modifier != MOD_INVALID { + attributes.extend([EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT, modifier as u32 as i32, EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, (modifier >> 32) as u32 as i32]); + } + attributes.push(EGL_NONE); + // SAFETY: as the caller says; EGL takes its own reference to the dmabuf. + unsafe { (self.egl.create_image)(self.display, std::ptr::null_mut(), EGL_LINUX_DMA_BUF_EXT, std::ptr::null_mut(), attributes.as_ptr()) } + } + + pub fn drop_target(&self, target: Target) { + // SAFETY: the target's own objects, made by this context, freed once. + unsafe { + (self.gl.delete_framebuffers)(1, &target.fbo); + (self.gl.delete_textures)(1, &target.texture); + (self.egl.destroy_image)(self.display, target.image); + (self.gbm.bo_destroy)(target.bo); + } + } + + /// Waits until everything drawn so far is in memory, so a frame is whole before another + /// process shows it. + pub fn finish(&self) { + // SAFETY: the context is current. + unsafe { (self.gl.finish)() }; + } + + pub fn flush(&self) { + // SAFETY: the context is current. + unsafe { (self.gl.flush)() }; + } + + /// A dmabuf another process made, as `0x00RRGGBB` words, top row first: how the app's side + /// checks what it was given. + pub fn read_dmabuf(&self, width: u32, height: u32, modifier: u64, planes: &[Plane]) -> Result, String> { + // SAFETY: the context is current, the attributes describe the dmabuf as sent, and the + // read fits the buffer. + unsafe { + let image = self.import(width, height, modifier, planes); + if image.is_null() { + return Err("EGL won't take the dmabuf".into()); + } + let (mut texture, mut fbo) = (0, 0); + (self.gl.gen_textures)(1, &mut texture); + (self.gl.bind_texture)(GL_TEXTURE_2D, texture); + (self.gl.image_target_texture)(GL_TEXTURE_2D, image); + (self.gl.gen_framebuffers)(1, &mut fbo); + (self.gl.bind_framebuffer)(GL_FRAMEBUFFER, fbo); + (self.gl.framebuffer_texture)(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); + let mut rgba = vec![0u8; width as usize * height as usize * 4]; + (self.gl.pixel_store)(GL_PACK_ALIGNMENT, 1); + (self.gl.read_pixels)(0, 0, width as i32, height as i32, GL_RGBA, GL_UNSIGNED_BYTE, rgba.as_mut_ptr() as Ptr); + (self.gl.delete_framebuffers)(1, &fbo); + (self.gl.delete_textures)(1, &texture); + (self.egl.destroy_image)(self.display, image); + Ok(rgba.as_chunks::<4>().0.iter().map(|p| u32::from(p[0]) << 16 | u32::from(p[1]) << 8 | u32::from(p[2])).collect()) + } + } +} + +impl Drop for Gpu { + fn drop(&mut self) { + // SAFETY: this context and display, made by `new`, released once. + unsafe { + (self.egl.make_current)(self.display, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()); + (self.egl.destroy_context)(self.display, self.context); + (self.egl.terminate)(self.display); + (self.gbm.device_destroy)(self.device); + } + } +} + +unsafe extern "C" fn find_proc(get_proc_address: *mut c_void, name: *const c_char) -> *mut c_void { + // SAFETY: `get_proc_address` is EGL's lookup, passed by `Gpu::proc_address`. + unsafe { + let find: unsafe extern "C" fn(*const c_char) -> Ptr = std::mem::transmute(get_proc_address); + find(name) + } +} + +/// Opens the first render node there is, for when the app has no compositor to ask. +pub fn first_render_node() -> Result { + for n in 128..192 { + let path = format!("/dev/dri/renderD{n}"); + if let Ok(file) = std::fs::OpenOptions::new().read(true).write(true).open(&path) { + return Ok(file.into()); + } + } + Err("no render node".into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Needs a graphics card, so it's left out of CI: `cargo test -- --ignored`. + #[test] + #[ignore] + fn a_target_is_one_dmabuf_plane_that_draws() { + let gpu = Gpu::new(first_render_node().unwrap()).unwrap(); + let target = gpu.target(1920, 1080, &[]).unwrap(); + assert_eq!(target.planes.len(), 1, "{:?}", target.planes); + assert!(target.planes[0].stride >= 1920 * 4); + println!("modifier {:#x}, drawable {:x?}", target.modifier, gpu.drawable_modifiers()); + gpu.drop_target(target); + } +} diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs new file mode 100644 index 0000000..b498c1d --- /dev/null +++ b/src/gpu_helper.rs @@ -0,0 +1,486 @@ +//! A player in another process that draws on the graphics card and hands its frames over as +//! dmabufs: the GPU counterpart of `helper`, for an app that shows video with `linux-dmabuf`. +//! +//! The app gives the player the file (descriptor 3), one end of a `SOCK_SEQPACKET` socket +//! (4) and the render node of the card its compositor uses (5). The player decodes, on the +//! card where it can, draws each frame with libmpv's OpenGL renderer into one of a few GBM +//! buffers, and says which buffer holds the new frame. A buffer's dmabuf goes to the app once, +//! with the message that first describes it; after that only its number does. The app +//! attaches the buffers to a surface and says when the compositor has let one go. Frames never +//! leave the card, and the player never sees the app's Wayland connection. +//! +//! Every message is one packet of text, so none can be split or run together. Descriptors +//! ride on the `buffer` message only, and the app checks each message before believing it. + +use std::ffi::c_int; +use std::fs::File; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; +use std::os::unix::process::CommandExt; +use std::process::{Child, Command, Stdio}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use crate::gpu::{GL_RGBA8, Gpu, Target}; +use crate::helper::{EXIT_BAD_START, EXIT_CANT_PLAY, EXIT_NO_MPV, PlayState}; +use crate::options::{Options, RenderPath}; +use crate::player::{Event, Player}; +use crate::render::{GlRender, Native}; + +pub const FD_FILE: c_int = 3; +pub const FD_SOCKET: c_int = 4; +pub const FD_NODE: c_int = 5; +/// Buffers in turn: one on screen, one waiting for the compositor, one being drawn. +pub const SLOTS: usize = 3; +/// The largest frame drawn. A bigger window scales it up. +pub const MAX_W: u32 = 7680; +pub const MAX_H: u32 = 4320; +const MAX_MESSAGE: usize = 256; +const REPORT_EVERY: Duration = Duration::from_millis(100); + +/// What the player says. +#[derive(Clone, Debug, PartialEq)] +pub enum Said { + Hello, + /// A buffer's layout. Its dmabuf came with this message. + Buffer { + slot: usize, + width: u32, + height: u32, + fourcc: u32, + modifier: u64, + stride: u32, + offset: u32, + }, + /// The newest frame is in this buffer, finished drawing. + Frame { + slot: usize, + }, + State(PlayState), + /// Frames libmpv dropped or showed late, so far. + Dropped { + decoder: u64, + late: u64, + }, + /// How it's decoding, once the first frame is drawn: a libmpv hardware decoder's name, + /// such as `nvdec` or `vaapi`, or `software`. + Decoder(String), + NoVideo, + CantPlay, +} + +/// A message from the player, or `None` if it isn't a sensible one. +pub fn parse_said(line: &str) -> Option { + let words: Vec<&str> = line.split_ascii_whitespace().collect(); + let n = |i: usize| words.get(i)?.parse::().ok(); + let small = |i: usize| u32::try_from(n(i)?).ok(); + let slot = |i: usize| n(i).map(|s| s as usize).filter(|s| *s < SLOTS); + match (words.first().copied()?, words.len()) { + ("hello", 1) => Some(Said::Hello), + ("novideo", 1) => Some(Said::NoVideo), + ("cantplay", 1) => Some(Said::CantPlay), + ("frame", 2) => Some(Said::Frame { slot: slot(1)? }), + ("decoder", 2) => { + let name = words[1]; + (name.len() <= 32 && name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')).then(|| Said::Decoder(name.to_owned())) + } + ("dropped", 3) => Some(Said::Dropped { decoder: n(1)?, late: n(2)? }), + ("buffer", 8) => { + let (width, height, stride) = (small(2)?, small(3)?, small(6)?); + if width == 0 || height == 0 || width > MAX_W || height > MAX_H || u64::from(stride) < u64::from(width) * 4 { + return None; + } + Some(Said::Buffer { slot: slot(1)?, width, height, fourcc: small(4)?, modifier: n(5)?, stride, offset: small(7)? }) + } + ("state", 7) => match crate::helper::parse_said(line)? { + crate::helper::Said::State(state) => Some(Said::State(state)), + _ => None, + }, + _ => None, + } +} + +// ---- Packets with descriptors ---- + +/// Sends one packet, with `fds` attached if there are any. +pub fn send(socket: &OwnedFd, text: &str, fds: &[RawFd]) -> std::io::Result<()> { + let mut iov = libc::iovec { iov_base: text.as_ptr() as *mut _, iov_len: text.len() }; + // SAFETY: a zeroed msghdr is valid; the buffers below outlive the call. + let mut msg: libc::msghdr = unsafe { std::mem::zeroed() }; + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + // SAFETY: arithmetic on a length. + let space = unsafe { libc::CMSG_SPACE(std::mem::size_of_val(fds) as u32) } as usize; + let mut control = vec![0u8; space]; + if !fds.is_empty() { + msg.msg_control = control.as_mut_ptr() as *mut _; + msg.msg_controllen = space; + // SAFETY: the control buffer is sized for one header with these descriptors. + unsafe { + let header = libc::CMSG_FIRSTHDR(&msg); + (*header).cmsg_level = libc::SOL_SOCKET; + (*header).cmsg_type = libc::SCM_RIGHTS; + (*header).cmsg_len = libc::CMSG_LEN(std::mem::size_of_val(fds) as u32) as usize; + std::ptr::copy_nonoverlapping(fds.as_ptr(), libc::CMSG_DATA(header) as *mut RawFd, fds.len()); + } + } + // SAFETY: a valid socket and message. + let sent = unsafe { libc::sendmsg(socket.as_raw_fd(), &msg, libc::MSG_NOSIGNAL) }; + if sent < 0 { Err(std::io::Error::last_os_error()) } else { Ok(()) } +} + +/// Receives one packet and any descriptors with it. `None` at the end. A packet too long, +/// or with more descriptors than one, is cut short and marked so the caller drops it. +pub fn receive(socket: &OwnedFd) -> std::io::Result)>> { + let mut buf = [0u8; MAX_MESSAGE]; + let mut iov = libc::iovec { iov_base: buf.as_mut_ptr() as *mut _, iov_len: buf.len() }; + let space = unsafe { libc::CMSG_SPACE((4 * size_of::()) as u32) } as usize; + let mut control = vec![0u8; space]; + // SAFETY: a zeroed msghdr is valid; the buffers outlive the call. + let mut msg: libc::msghdr = unsafe { std::mem::zeroed() }; + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + msg.msg_control = control.as_mut_ptr() as *mut _; + msg.msg_controllen = space; + // SAFETY: a valid socket and message. Received descriptors are close-on-exec. + let got = unsafe { libc::recvmsg(socket.as_raw_fd(), &mut msg, libc::MSG_CMSG_CLOEXEC) }; + if got < 0 { + return Err(std::io::Error::last_os_error()); + } + if got == 0 { + return Ok(None); + } + let mut fds = Vec::new(); + // SAFETY: walking the control messages the kernel just wrote, taking ownership of each + // descriptor it passed, so none leak even if the message is then refused. + unsafe { + let mut header = libc::CMSG_FIRSTHDR(&msg); + while !header.is_null() { + if (*header).cmsg_level == libc::SOL_SOCKET && (*header).cmsg_type == libc::SCM_RIGHTS { + let count = ((*header).cmsg_len - libc::CMSG_LEN(0) as usize) / size_of::(); + let data = libc::CMSG_DATA(header) as *const RawFd; + for i in 0..count { + fds.push(OwnedFd::from_raw_fd(std::ptr::read_unaligned(data.add(i)))); + } + } + header = libc::CMSG_NXTHDR(&msg, header); + } + } + let cut = msg.msg_flags & (libc::MSG_TRUNC | libc::MSG_CTRUNC) != 0; + let text = if cut { String::new() } else { String::from_utf8_lossy(&buf[..got as usize]).into_owned() }; + Ok(Some((text, fds))) +} + +// ---- The app's side ---- + +pub struct Started { + pub child: Child, + pub socket: OwnedFd, +} + +/// Starts a player, as `helper::start` does, with `node` the render node of the compositor's +/// card. `command` is the app's helper command, jailed or not, with its helper argument. +pub fn start(mut command: Command, file: File, node: OwnedFd, size: (u32, u32)) -> std::io::Result { + let (ours, theirs) = socketpair()?; + let high = |fd: RawFd| -> std::io::Result { + // SAFETY: duplicating a descriptor we hold, taking ownership of a good result. + let copy = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 64) }; + if copy < 0 { Err(std::io::Error::last_os_error()) } else { Ok(unsafe { OwnedFd::from_raw_fd(copy) }) } + }; + let (file, theirs, node) = (high(file.as_raw_fd())?, high(theirs.as_raw_fd())?, high(node.as_raw_fd())?); + let fds = [file.as_raw_fd(), theirs.as_raw_fd(), node.as_raw_fd()]; + command.arg(size.0.clamp(1, MAX_W).to_string()).arg(size.1.clamp(1, MAX_H).to_string()); + command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); + // SAFETY: only async-signal-safe calls. + unsafe { + command.pre_exec(move || { + for (from, to) in fds.iter().zip([FD_FILE, FD_SOCKET, FD_NODE]) { + if libc::dup2(*from, to) < 0 { + return Err(std::io::Error::last_os_error()); + } + } + if libc::close_range((FD_NODE + 1) as libc::c_uint, libc::c_uint::MAX, libc::CLOSE_RANGE_CLOEXEC as libc::c_int) != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let child = command.spawn()?; + drop(command); + Ok(Started { child, socket: ours }) +} + +fn socketpair() -> std::io::Result<(OwnedFd, OwnedFd)> { + let mut pair = [0; 2]; + // SAFETY: a valid array for the two descriptors. + if unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC, 0, pair.as_mut_ptr()) } != 0 { + return Err(std::io::Error::last_os_error()); + } + // SAFETY: two new descriptors, owned by nothing else. + Ok(unsafe { (OwnedFd::from_raw_fd(pair[0]), OwnedFd::from_raw_fd(pair[1])) }) +} + +// ---- The player's side ---- + +#[derive(Default)] +struct Shared { + /// Woken for libmpv's events and frames, and for the app's messages. + pending: bool, + /// Buffers the app has, and hasn't given back. + held: [bool; SLOTS], + size: (u32, u32), + commands: Vec, + gone: bool, +} + +struct Wake { + shared: Mutex, + ready: Condvar, +} + +impl Wake { + fn with(&self, f: impl FnOnce(&mut Shared) -> T) -> T { + let mut shared = self.shared.lock().unwrap_or_else(|e| e.into_inner()); + let result = f(&mut shared); + shared.pending = true; + self.ready.notify_one(); + result + } + + fn wait(&self, deadline: Option) -> Shared { + let shared = self.shared.lock().unwrap_or_else(|e| e.into_inner()); + let mut shared = match deadline { + Some(at) => self.ready.wait_timeout_while(shared, at.saturating_duration_since(Instant::now()), |s| !s.pending).unwrap_or_else(|e| e.into_inner()).0, + None => self.ready.wait_while(shared, |s| !s.pending).unwrap_or_else(|e| e.into_inner()), + }; + shared.pending = false; + Shared { pending: false, held: shared.held, size: shared.size, commands: std::mem::take(&mut shared.commands), gone: shared.gone } + } +} + +/// Runs a GPU player, and never returns. As `helper::run`, with `options` on the GPU path. +pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: impl FnOnce() -> bool) -> ! { + let parse = |i: usize| args.get(i).and_then(|a| a.parse::().ok()); + let (Some(w), Some(h)) = (parse(0), parse(1)) else { std::process::exit(EXIT_BAD_START) }; + if options.render != RenderPath::Gpu { + std::process::exit(EXIT_BAD_START); + } + // SAFETY: plain integers. + unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL as libc::c_ulong, 0, 0, 0) }; + // SAFETY: descriptors `start` put there, owned by nothing else in this process. + let (socket, node) = unsafe { (OwnedFd::from_raw_fd(FD_SOCKET), OwnedFd::from_raw_fd(FD_NODE)) }; + let node_fd = node.as_raw_fd(); + let Ok(gpu) = Gpu::new(node) else { std::process::exit(EXIT_CANT_PLAY) }; + let player = match Player::new(&Options { start_paused: true, ..*options }) { + Ok(player) => player, + Err(crate::player::Error::Load(_)) => std::process::exit(EXIT_NO_MPV), + Err(_) => std::process::exit(EXIT_CANT_PLAY), + }; + let (find, context) = gpu.proc_address(); + // SAFETY: the context is current on this thread for the life of the process, and the + // render node stays open inside `gpu`. + let Ok(mut render) = (unsafe { GlRender::new(&player, find, context, Native::RenderNode(node_fd)) }) else { std::process::exit(EXIT_CANT_PLAY) }; + if !lock_down() { + std::process::exit(sandbox_code); + } + let wake = Arc::new(Wake { shared: Mutex::new(Shared { size: (w.clamp(1, MAX_W), h.clamp(1, MAX_H)), ..Shared::default() }), ready: Condvar::new() }); + let (for_events, for_frames) = (wake.clone(), wake.clone()); + player.on_wakeup(move || for_events.with(|_| ())); + render.on_update(move || for_frames.with(|_| ())); + let say = |text: &str| { + if send(&socket, text, &[]).is_err() { + std::process::exit(0); + } + }; + say("hello"); + let reading = socket.try_clone().unwrap_or_else(|_| std::process::exit(EXIT_CANT_PLAY)); + let for_reader = wake.clone(); + let spawned = std::thread::Builder::new().name("app".into()).spawn(move || { + while let Ok(Some((text, _))) = receive(&reading) { + for_reader.with(|shared| { + let mut words = text.split_ascii_whitespace(); + match words.next() { + Some("release") => { + if let Some(slot) = words.next().and_then(|s| s.parse::().ok()).filter(|s| *s < SLOTS) { + shared.held[slot] = false; + } + } + Some("size") => { + let mut n = || words.next().and_then(|s| s.parse::().ok()); + if let (Some(w), Some(h)) = (n(), n()) { + shared.size = (w.clamp(1, MAX_W), h.clamp(1, MAX_H)); + } + } + _ => shared.commands.push(text.clone()), + } + }); + } + for_reader.with(|shared| shared.gone = true); + }); + if spawned.is_err() { + std::process::exit(EXIT_CANT_PLAY); + } + if player.load_fd(FD_FILE).is_err() { + std::process::exit(EXIT_CANT_PLAY); + } + + let mut targets: [Option; SLOTS] = [None, None, None]; + let mut next = 0usize; + let mut state = PlayState { volume: 100.0, paused: true, ..PlayState::default() }; + let (mut reported, mut last_report) = (String::new(), Instant::now() - REPORT_EVERY); + let mut dropped_reported = String::new(); + let mut natural: Option<(f64, f64)> = None; + let mut loaded = false; + let mut wanted_paused = true; + let mut told_decoder = false; + loop { + let deadline = (state.line() != reported).then_some(last_report + REPORT_EVERY); + let woken = wake.wait(deadline); + if woken.gone { + std::process::exit(0); + } + for command in &woken.commands { + let mut words = command.split_ascii_whitespace(); + let number = |w: Option<&str>| w.and_then(|w| w.parse::().ok()).filter(|n| n.is_finite()); + let _ = match words.next() { + Some("pause") => { + wanted_paused = true; + player.set_paused(true) + } + Some("play") => { + wanted_paused = false; + if loaded { player.play() } else { Ok(()) } + } + Some("seek") => number(words.next()).map_or(Ok(()), |by| player.seek_by(by)), + Some("seekat") => number(words.next()).map_or(Ok(()), |at| player.seek_to(at)), + Some("volume") => number(words.next()).map_or(Ok(()), |v| player.set_volume(v)), + Some("mute") => player.set_muted(true), + Some("unmute") => player.set_muted(false), + _ => Ok(()), + }; + } + let mut urgent = false; + while let Some(event) = player.next_event() { + match event { + Event::Shutdown => std::process::exit(0), + Event::Loaded { video } => { + loaded = true; + if !video { + say("novideo"); + } + if !wanted_paused { + let _ = player.set_paused(false); + } + } + Event::Failed => say("cantplay"), + Event::VideoChanged => natural = player.double(c"dwidth").zip(player.double(c"dheight")).filter(|n| n.0 > 0.0 && n.1 > 0.0), + Event::Position(at) => state.position = at, + Event::Duration(d) => (state.duration, urgent) = (d, true), + Event::Paused(p) => (state.paused, urgent) = (p, true), + Event::Volume(v) => (state.volume, urgent) = (v, true), + Event::Muted(m) => (state.muted, urgent) = (m, true), + Event::Ended(e) => (state.ended, urgent) = (e, true), + Event::Restarted => urgent = true, + } + } + let line = state.line(); + if line != reported && (urgent || last_report.elapsed() >= REPORT_EVERY) { + say(&line); + let dropped = format!("dropped {} {}", player.get(c"frame-drop-count").unwrap_or_default(), player.get(c"vo-delayed-frame-count").unwrap_or_default()); + if dropped != dropped_reported && parse_said(&dropped).is_some() { + say(&dropped); + dropped_reported = dropped; + } + reported = line; + last_report = Instant::now(); + } + if !render.new_frame() { + continue; + } + let Some(natural) = natural else { continue }; + let (fw, fh) = fit(natural, woken.size); + // The next buffer the app isn't holding. With none free, this frame is skipped and + // libmpv counts it as late. + let Some(slot) = (0..SLOTS).map(|i| (next + i) % SLOTS).find(|s| !woken.held[*s]) else { continue }; + if targets[slot].as_ref().is_some_and(|t| (t.width, t.height) != (fw, fh)) { + gpu.drop_target(targets[slot].take().expect("checked")); + } + if targets[slot].is_none() { + let Ok(target) = gpu.target(fw, fh, &[]) else { std::process::exit(EXIT_CANT_PLAY) }; + let plane = &target.planes[0]; + let text = format!("buffer {slot} {fw} {fh} {} {} {} {}", target.fourcc, target.modifier, plane.stride, plane.offset); + if target.planes.len() != 1 || send(&socket, &text, &[plane.fd.as_raw_fd()]).is_err() { + std::process::exit(EXIT_CANT_PLAY); + } + targets[slot] = Some(target); + } + let target = targets[slot].as_ref().expect("made above"); + // SAFETY: the context is current and the framebuffer is this size. + if unsafe { render.render(target.fbo as i32, fw as i32, fh as i32, GL_RGBA8, false) }.is_ok() { + // Whole before the app shows it. An explicit fence would let the card run ahead. + gpu.finish(); + wake.with(|shared| shared.held[slot] = true); + say(&format!("frame {slot}")); + if !told_decoder { + told_decoder = true; + let decoder = player.get(c"hwdec-current").filter(|d| !d.is_empty() && d != "no").unwrap_or_else(|| "software".into()); + say(&format!("decoder {decoder}")); + } + next = (slot + 1) % SLOTS; + } + } +} + +/// The largest size with the picture's shape that fits in `wanted`, at least one pixel. +fn fit(natural: (f64, f64), wanted: (u32, u32)) -> (u32, u32) { + let scale = (wanted.0 as f64 / natural.0).min(wanted.1 as f64 / natural.1); + (((natural.0 * scale).round() as u32).clamp(1, MAX_W), ((natural.1 * scale).round() as u32).clamp(1, MAX_H)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sensible_messages_parse() { + assert_eq!(parse_said("hello"), Some(Said::Hello)); + assert_eq!(parse_said("frame 2"), Some(Said::Frame { slot: 2 })); + assert_eq!(parse_said("dropped 3 4"), Some(Said::Dropped { decoder: 3, late: 4 })); + assert_eq!(parse_said("decoder nvdec"), Some(Said::Decoder("nvdec".into()))); + assert_eq!(parse_said("decoder ../../x"), None); + let buffer = Said::Buffer { slot: 1, width: 1920, height: 1080, fourcc: crate::gpu::FOURCC_XRGB8888, modifier: 0, stride: 7680, offset: 0 }; + assert_eq!(parse_said(&format!("buffer 1 1920 1080 {} 0 7680 0", crate::gpu::FOURCC_XRGB8888)), Some(buffer)); + assert!(matches!(parse_said("state 1 2 0 100 0 0"), Some(Said::State(_)))); + } + + #[test] + fn nonsense_is_refused() { + for line in [ + "", + "frame 3", + "frame", + "frame 1 2", + "buffer 3 10 10 1 0 40 0", + "buffer 0 10 10 1 0 39 0", + "buffer 0 0 10 1 0 40 0", + "buffer 0 7681 10 1 0 30724 0", + "buffer 0 10 10 1 0 40", + "dropped 1", + "hello again", + "exec sh", + ] { + assert_eq!(parse_said(line), None, "{line}"); + } + } + + #[test] + fn descriptors_cross_the_socket() { + let (a, b) = socketpair().unwrap(); + let file = File::open("/dev/null").unwrap(); + send(&a, "buffer 0 1 1 1 0 4 0", &[file.as_raw_fd()]).unwrap(); + let (text, fds) = receive(&b).unwrap().unwrap(); + assert_eq!(text, "buffer 0 1 1 1 0 4 0"); + assert_eq!(fds.len(), 1); + drop(a); + assert!(receive(&b).unwrap().is_none(), "the end of the other side"); + } +} diff --git a/src/helper.rs b/src/helper.rs index a91fb40..7b2585b 100644 --- a/src/helper.rs +++ b/src/helper.rs @@ -84,7 +84,7 @@ pub struct PlayState { } impl PlayState { - fn line(&self) -> String { + pub(crate) fn line(&self) -> String { format!("state {:.3} {:.3} {} {:.0} {} {}", self.position, self.duration, u8::from(self.paused), self.volume, u8::from(self.muted), u8::from(self.ended)) } } diff --git a/src/jail.rs b/src/jail.rs index cabaaf9..444f91e 100644 --- a/src/jail.rs +++ b/src/jail.rs @@ -7,6 +7,7 @@ //! clients record too, so with sound on that can include the microphone. use std::ffi::OsStr; +use std::os::fd::{AsRawFd, FromRawFd}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use std::process::Command; @@ -58,6 +59,29 @@ pub fn arguments(executable: &Path, sound_socket: Option<&Path>) -> Vec args } +/// bubblewrap's arguments for a GPU helper: the jail every player gets, plus the graphics +/// card's device files, which drawing and decoding on it need. That's the drivers' attack +/// surface too, which Mike accepted for this (2026-12-02). +pub fn gpu_arguments(executable: &Path) -> Vec { + let mut args = arguments(executable, None); + let run = args.len() - 2; + let mut devices = vec!["--dev-bind".to_owned(), "/dev/dri".to_owned(), "/dev/dri".to_owned()]; + // NVIDIA's driver has its own device files beside the DRM ones. + for name in ["nvidiactl", "nvidia0", "nvidia-modeset", "nvidia-uvm", "nvidia-uvm-tools"] { + devices.extend(["--dev-bind-try".to_owned(), format!("/dev/{name}"), format!("/dev/{name}")]); + } + // Drivers find the card's details in /sys. + devices.extend(["--ro-bind".to_owned(), "/sys".to_owned(), "/sys".to_owned()]); + // NVIDIA's decoder (CUDA) won't start without /proc. The jail leaves /proc out because + // writing /proc/self/mem changes code without asking for executable memory; with it in, + // the helper's Landlock rules refuse opening anything outside /dev for writing. + if Path::new("/dev/nvidiactl").exists() { + devices.extend(["--proc".to_owned(), "/proc".to_owned()]); + } + args.splice(run..run, devices); + args +} + /// The command that runs this program jailed with `helper_arg`, ready for `helper::start`. /// With `sound`, the session's PulseAudio socket goes in too, if there is one. pub fn command(helper_arg: &str, sound: bool) -> std::io::Result { @@ -88,6 +112,53 @@ fn undeleted(exe: PathBuf) -> Option { path.is_file().then(|| path.to_path_buf()) } +/// Lets this process open files for writing only under `allowed` from now on, with Landlock. +/// For a GPU helper, whose jail has /proc for NVIDIA's decoder: `/proc/self/mem` can't be +/// opened for writing, so code can't be changed through it, while the card's device files +/// under /dev still can. Returns false if the kernel has no Landlock or refuses. +pub fn forbid_writes_outside(allowed: &[&Path]) -> bool { + const CREATE_RULESET: libc::c_long = 444; + const ADD_RULE: libc::c_long = 445; + const RESTRICT_SELF: libc::c_long = 446; + const RULE_PATH_BENEATH: libc::c_int = 1; + const ACCESS_WRITE_FILE: u64 = 1 << 1; + const ACCESS_TRUNCATE: u64 = 1 << 14; + #[repr(C)] + struct Ruleset { + handled_access_fs: u64, + } + #[repr(C, packed)] + struct PathBeneath { + allowed_access: u64, + parent_fd: i32, + } + // Truncating is writing too, from Landlock ABI 3; older kernels handle only the first. + // SAFETY: asking for the ABI version, with no ruleset. + let abi = unsafe { libc::syscall(CREATE_RULESET, std::ptr::null::(), 0usize, 1u32) }; + if abi < 1 { + return false; + } + let handled = if abi >= 3 { ACCESS_WRITE_FILE | ACCESS_TRUNCATE } else { ACCESS_WRITE_FILE }; + let ruleset = Ruleset { handled_access_fs: handled }; + // SAFETY: a valid ruleset of the size given. + let fd = unsafe { libc::syscall(CREATE_RULESET, &ruleset as *const Ruleset, size_of::(), 0u32) }; + if fd < 0 { + return false; + } + // SAFETY: a new descriptor, owned here. + let ruleset_fd = unsafe { std::os::fd::OwnedFd::from_raw_fd(fd as i32) }; + for path in allowed { + let Ok(dir) = std::fs::File::open(path) else { continue }; + let rule = PathBeneath { allowed_access: handled, parent_fd: dir.as_raw_fd() }; + // SAFETY: a live ruleset and a valid rule. + if unsafe { libc::syscall(ADD_RULE, ruleset_fd.as_raw_fd(), RULE_PATH_BENEATH, &rule as *const PathBeneath, 0u32) } != 0 { + return false; + } + } + // SAFETY: plain integers and a live ruleset. No new privileges is what Landlock asks for. + unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == 0 && libc::syscall(RESTRICT_SELF, ruleset_fd.as_raw_fd(), 0u32) == 0 } +} + #[cfg(test)] mod tests { use super::*; @@ -119,4 +190,27 @@ mod tests { assert_eq!(undeleted(new.clone()), Some(new)); std::fs::remove_dir_all(dir).unwrap(); } + + /// In a child process, as Landlock can't be lifted once on. + #[test] + fn after_landlock_proc_self_mem_cant_be_written_but_dev_can() { + // SAFETY: the child only makes system calls and exits. + let pid = unsafe { libc::fork() }; + if pid == 0 { + let on = forbid_writes_outside(&[Path::new("/dev")]); + let mem = std::fs::OpenOptions::new().write(true).open("/proc/self/mem").is_err(); + let null = std::fs::OpenOptions::new().write(true).open("/dev/null").is_ok(); + let tmp = std::fs::OpenOptions::new().write(true).create(true).truncate(true).open(std::env::temp_dir().join(format!("landlock-{}", std::process::id()))).is_err(); + // SAFETY: leaving the forked child without running the parent's destructors. + unsafe { libc::_exit(i32::from(on) | i32::from(mem) << 1 | i32::from(null) << 2 | i32::from(tmp) << 3) }; + } + let mut status = 0; + // SAFETY: waiting for our own child. + unsafe { libc::waitpid(pid, &mut status, 0) }; + let bits = libc::WEXITSTATUS(status); + assert_eq!(bits & 1, 1, "Landlock went on"); + assert_eq!(bits & 2, 2, "/proc/self/mem refused for writing"); + assert_eq!(bits & 4, 4, "/dev/null still writable"); + assert_eq!(bits & 8, 8, "nothing else writable"); + } } diff --git a/src/lib.rs b/src/lib.rs index 316bdf3..80b7852 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,6 +15,8 @@ //! playback. pub mod ffi; +pub mod gpu; +pub mod gpu_helper; pub mod helper; pub mod jail; pub mod options; @@ -23,4 +25,4 @@ pub mod render; pub use options::{Audio, Hwdec, Options, RenderPath}; pub use player::{Error, Event, Player}; -pub use render::{GlRender, SwFormat, SwRender}; +pub use render::{GlRender, Native, SwFormat, SwRender}; diff --git a/src/render.rs b/src/render.rs index 7fa0960..313bb18 100644 --- a/src/render.rs +++ b/src/render.rs @@ -155,6 +155,16 @@ fn fits(width: u32, height: u32, stride: usize, pixels: &[u8]) -> bool { && stride.checked_mul(height as usize).is_some_and(|bytes| bytes <= pixels.len()) } +/// What libmpv's OpenGL renderer may use for hardware decoding besides OpenGL itself. +#[derive(Clone, Copy, Debug)] +pub enum Native { + None, + /// The app's live `wl_display`. + Wayland(*mut c_void), + /// A DRM render node, for a player with no display connection, such as a GPU helper. + RenderNode(std::os::fd::RawFd), +} + /// libmpv's OpenGL renderer. The app owns the GL context, and makes it current on the /// thread that creates, uses and drops this, which is why it can't move to another thread. pub struct GlRender { @@ -168,16 +178,22 @@ impl GlRender { /// # Safety /// An OpenGL context must be current on this thread, and stay current whenever this is /// used or dropped. `get_proc_address` must find that context's functions given - /// `proc_context`. `wl_display`, if given, must be the app's live `wl_display`, which lets - /// libmpv use hardware decoding without copying frames back. - pub unsafe fn new(player: &Player, get_proc_address: GetProcAddress, proc_context: *mut c_void, wl_display: Option<*mut c_void>) -> Result { + /// `proc_context`. `native` must be live for as long as this is; it's what lets libmpv + /// decode on the card without copying frames back (NVDEC needs nothing). + pub unsafe fn new(player: &Player, get_proc_address: GetProcAddress, proc_context: *mut c_void, native: Native) -> Result { let mut init = ffi::OpenGlInitParams { get_proc_address: Some(get_proc_address), get_proc_address_ctx: proc_context }; let mut params = vec![ ffi::RenderParam { kind: ffi::RENDER_API_TYPE, data: c"opengl".as_ptr() as *mut c_void }, ffi::RenderParam { kind: ffi::RENDER_OPENGL_INIT_PARAMS, data: &mut init as *mut _ as *mut c_void }, ]; - if let Some(display) = wl_display { - params.push(ffi::RenderParam { kind: ffi::RENDER_WL_DISPLAY, data: display }); + let mut drm = ffi::OpenGlDrmParamsV2 { fd: -1, crtc_id: 0, connector_id: 0, atomic_request_ptr: std::ptr::null_mut(), render_fd: -1 }; + match native { + Native::None => {} + Native::Wayland(display) => params.push(ffi::RenderParam { kind: ffi::RENDER_WL_DISPLAY, data: display }), + Native::RenderNode(fd) => { + drm.render_fd = fd; + params.push(ffi::RenderParam { kind: ffi::RENDER_DRM_DISPLAY_V2, data: &mut drm as *mut _ as *mut c_void }); + } } params.push(ffi::RenderParam { kind: ffi::RENDER_INVALID, data: std::ptr::null_mut() }); Ok(Self { context: Context::create(player, &mut params)?, _same_thread: std::marker::PhantomData }) From a14457120e5f7a498cab21d6979325b0ffaabf82 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 06:19:10 -0700 Subject: [PATCH 05/25] GPU helper prototype: show its dmabufs on a compositor examples/gpu-show opens a window and attaches each frame's dmabuf with linux-dmabuf. When the compositor releases a buffer, it goes back to the helper. It measures what gpu-play does, end to end, for comparison with mpv's own window in the same private headless weston. --- Cargo.lock | 138 +++++++++++++++++++++++++ Cargo.toml | 5 +- examples/gpu-show.rs | 239 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 381 insertions(+), 1 deletion(-) create mode 100644 examples/gpu-show.rs diff --git a/Cargo.lock b/Cargo.lock index abdd65c..7121623 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,6 +8,8 @@ version = "0.1.0" dependencies = [ "libc", "rustix", + "wayland-client", + "wayland-protocols", ] [[package]] @@ -16,6 +18,22 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + [[package]] name = "errno" version = "0.3.15" @@ -26,6 +44,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + [[package]] name = "libc" version = "0.2.191" @@ -38,6 +62,45 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + [[package]] name = "rustix" version = "1.1.6" @@ -51,6 +114,81 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags", + "rustix", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "pkg-config", +] + [[package]] name = "windows-link" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index e1fa1d5..feb7468 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,9 @@ harness = false [dev-dependencies] # The helper test's cancel signal, an eventfd, as an app's would be. -rustix = { version = "1.1.6", features = ["event"] } +rustix = { version = "1.1.6", features = ["event", "pipe"] } # The GPU colour bench opens EGL at run time, as the crate opens libmpv. libc = "0.2.191" +# The GPU helper prototype's Wayland app (examples/gpu-show.rs), as Alias View uses them. +wayland-client = "0.31.15" +wayland-protocols = { version = "0.32.13", features = ["client", "unstable", "staging"] } diff --git a/examples/gpu-show.rs b/examples/gpu-show.rs new file mode 100644 index 0000000..d76bd28 --- /dev/null +++ b/examples/gpu-show.rs @@ -0,0 +1,239 @@ +//! The GPU helper prototype shown on a real compositor (ALI-2358): a window whose frames are +//! the helper's dmabufs, attached through `linux-dmabuf`, given back to the helper when the +//! compositor releases them. Measures what `gpu-play` does, end to end. +//! +//! ```sh +//! WAYLAND_DISPLAY=... cargo run --release --example gpu-show -- FILE [--jail] [--hwdec] [--size WxH] +//! ``` +//! +//! Run it in a private headless weston for measuring, never on someone's live session. + +use std::fs::File; +use std::os::fd::{AsFd, AsRawFd, OwnedFd}; +use std::process::Command; +use std::sync::mpsc; +use std::time::Instant; + +use alias_playback::gpu::first_render_node; +use alias_playback::gpu_helper::{self, SLOTS, Said}; +use alias_playback::{Audio, Hwdec, Options, RenderPath, jail}; +use rustix::event::{PollFd, PollFlags, poll}; +use wayland_client::protocol::{wl_buffer, wl_compositor, wl_registry, wl_surface}; +use wayland_client::{Connection, Dispatch, QueueHandle, delegate_noop}; +use wayland_protocols::wp::linux_dmabuf::zv1::client::{zwp_linux_buffer_params_v1, zwp_linux_dmabuf_v1}; +use wayland_protocols::xdg::shell::client::{xdg_surface, xdg_toplevel, xdg_wm_base}; + +const HELPER_ARG: &str = "--gpu-helper"; + +#[derive(Default)] +struct App { + compositor: Option, + dmabuf: Option, + wm: Option, + configured: bool, + released: Vec, +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.first().map(String::as_str) == Some(HELPER_ARG) { + let hwdec = if args.get(1).map(String::as_str) == Some("hwdec") { Hwdec::Auto } else { Hwdec::Off }; + let options = Options { render: RenderPath::Gpu, hwdec, audio: Audio::Off, cover_art: false, start_paused: true }; + gpu_helper::run(&args[2..], &options, 6, || jail::forbid_writes_outside(&[std::path::Path::new("/dev")])); + } + let file = args.first().expect("a file to play").clone(); + let flag = |name: &str| args.iter().any(|a| a == name); + let size: (u32, u32) = + args.iter().position(|a| a == "--size").and_then(|i| args.get(i + 1)).and_then(|s| s.split_once('x')).map_or((1920, 1080), |(w, h)| (w.parse().unwrap(), h.parse().unwrap())); + let start = Instant::now(); + + let connection = Connection::connect_to_env().expect("a Wayland compositor"); + let mut queue = connection.new_event_queue(); + let qh = queue.handle(); + connection.display().get_registry(&qh, ()); + let mut app = App::default(); + queue.roundtrip(&mut app).expect("globals"); + let (compositor, dmabuf, wm) = (app.compositor.clone().expect("wl_compositor"), app.dmabuf.clone().expect("linux-dmabuf v3+"), app.wm.clone().expect("xdg_wm_base")); + let surface = compositor.create_surface(&qh, ()); + let toplevel = wm.get_xdg_surface(&surface, &qh, ()).get_toplevel(&qh, ()); + toplevel.set_title("gpu-show".into()); + surface.commit(); + while !app.configured { + queue.blocking_dispatch(&mut app).expect("configure"); + } + + let exe = jail::own_exe().expect("own path"); + let mut command = if flag("--jail") { + let mut command = Command::new("bwrap"); + command.args(jail::gpu_arguments(&exe)).arg(HELPER_ARG); + command + } else { + let mut command = Command::new(&exe); + command.arg(HELPER_ARG); + command + }; + command.arg(if flag("--hwdec") { "hwdec" } else { "software" }); + let node = first_render_node().expect("a render node"); + let started = gpu_helper::start(command, File::open(&file).expect("the file"), node, size).expect("the helper"); + let helper_pid = started.child.id(); + let socket = started.socket; + gpu_helper::send(&socket, "play", &[]).expect("play"); + + // The helper's messages, read on their own thread and handed over with a wake-up. + let (tx, rx) = mpsc::channel::<(String, Vec)>(); + let (wake_read, wake_write) = rustix::pipe::pipe().expect("pipe"); + let reading = socket.try_clone().expect("a copy"); + std::thread::spawn(move || { + while let Ok(Some(message)) = gpu_helper::receive(&reading) { + if tx.send(message).is_err() { + break; + } + let _ = rustix::io::write(&wake_write, &[1]); + } + }); + + let mut buffers: [Option; SLOTS] = [None, None, None]; + let (mut frames, mut first_frame, mut dropped, mut decoder, mut duration) = (0u64, None, (0, 0), String::from("?"), 0.0); + let mut done = false; + let mut scratch = [0u8; 64]; + while !done { + queue.flush().expect("flush"); + queue.dispatch_pending(&mut app).expect("dispatch"); + for slot in app.released.drain(..) { + let _ = gpu_helper::send(&socket, &format!("release {slot}"), &[]); + } + let read_guard = queue.prepare_read(); + let wayland_fd = read_guard.as_ref().map(|g| g.connection_fd().as_raw_fd()); + let mut fds = vec![PollFd::new(&wake_read, PollFlags::IN)]; + // SAFETY: the connection's descriptor lives as long as the connection. + let borrowed = wayland_fd.map(|fd| unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) }); + if let Some(fd) = &borrowed { + fds.push(PollFd::new(fd, PollFlags::IN)); + } + let _ = poll(&mut fds, None); + let wayland_ready = fds.get(1).is_some_and(|f| !f.revents().is_empty()); + if let Some(guard) = read_guard { + if wayland_ready { + guard.read().ok() + } else { + drop(guard); + None + }; + } + let _ = rustix::io::read(&wake_read, &mut scratch); + for (text, fds) in rx.try_iter() { + match gpu_helper::parse_said(&text) { + Some(Said::Buffer { slot, width, height, fourcc, modifier, stride, offset }) if fds.len() == 1 => { + let params = dmabuf.create_params(&qh, ()); + params.add(fds[0].as_fd(), 0, offset, stride, (modifier >> 32) as u32, modifier as u32); + let buffer = params.create_immed(width as i32, height as i32, fourcc, zwp_linux_buffer_params_v1::Flags::empty(), &qh, slot); + params.destroy(); + if let Some(old) = buffers[slot].replace(buffer) { + old.destroy(); + } + } + Some(Said::Frame { slot }) => { + if let Some(buffer) = &buffers[slot] { + surface.attach(Some(buffer), 0, 0); + surface.damage_buffer(0, 0, i32::MAX, i32::MAX); + surface.commit(); + frames += 1; + first_frame.get_or_insert(start.elapsed().as_secs_f64() * 1000.0); + } + } + Some(Said::Dropped { decoder, late }) => dropped = (decoder, late), + Some(Said::Decoder(name)) => decoder = name, + Some(Said::State(state)) => { + duration = state.duration; + done |= state.ended; + } + Some(Said::CantPlay | Said::NoVideo) => done = true, + _ => {} + } + } + } + let wall = start.elapsed().as_secs_f64(); + let (cpu, rss) = usage_below(helper_pid); + // SAFETY: a zeroed rusage is valid for this query. + let mut own: libc::rusage = unsafe { std::mem::zeroed() }; + unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut own) }; + let own_cpu = own.ru_utime.tv_sec as f64 + own.ru_utime.tv_usec as f64 / 1e6 + own.ru_stime.tv_sec as f64 + own.ru_stime.tv_usec as f64 / 1e6; + println!( + "{file}: {decoder}, {frames} frames shown in {wall:.2} s (clip {duration:.2} s), first frame {:.0} ms, dropped {} decoder + {} late, CPU {:.2} s (helper {cpu:.2} + app {own_cpu:.2}), peak RSS helper {} MB + app {} MB", + first_frame.unwrap_or(f64::NAN), + dropped.0, + dropped.1, + cpu + own_cpu, + rss / 1024, + own.ru_maxrss / 1024 + ); +} + +/// CPU seconds and the largest peak RSS (KB) of `pid` and every process below it. +fn usage_below(pid: u32) -> (f64, u64) { + // SAFETY: a plain query. + let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) } as f64; + let (mut cpu, mut rss) = (0.0, 0); + let mut queue = vec![pid]; + while let Some(pid) = queue.pop() { + if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) { + let fields: Vec<&str> = stat.rsplit_once(')').map_or("", |r| r.1).split_whitespace().collect(); + let n = |i: usize| fields.get(i).and_then(|f| f.parse::().ok()).unwrap_or(0.0); + cpu += (n(11) + n(12) + n(13) + n(14)) / ticks; + } + if let Ok(status) = std::fs::read_to_string(format!("/proc/{pid}/status")) { + let hwm = status.lines().find_map(|l| l.strip_prefix("VmHWM:")).and_then(|v| v.trim().trim_end_matches(" kB").parse::().ok()).unwrap_or(0); + rss = rss.max(hwm); + } + for task in std::fs::read_dir(format!("/proc/{pid}/task")).into_iter().flatten().flatten() { + if let Ok(children) = std::fs::read_to_string(task.path().join("children")) { + queue.extend(children.split_whitespace().filter_map(|c| c.parse::().ok())); + } + } + } + (cpu, rss) +} + +impl Dispatch for App { + fn event(app: &mut Self, registry: &wl_registry::WlRegistry, event: wl_registry::Event, _: &(), _: &Connection, qh: &QueueHandle) { + if let wl_registry::Event::Global { name, interface, version } = event { + match interface.as_str() { + "wl_compositor" => app.compositor = Some(registry.bind(name, version.min(4), qh, ())), + "zwp_linux_dmabuf_v1" if version >= 3 => app.dmabuf = Some(registry.bind(name, 3, qh, ())), + "xdg_wm_base" => app.wm = Some(registry.bind(name, 1, qh, ())), + _ => {} + } + } + } +} + +impl Dispatch for App { + fn event(_: &mut Self, wm: &xdg_wm_base::XdgWmBase, event: xdg_wm_base::Event, _: &(), _: &Connection, _: &QueueHandle) { + if let xdg_wm_base::Event::Ping { serial } = event { + wm.pong(serial); + } + } +} + +impl Dispatch for App { + fn event(app: &mut Self, surface: &xdg_surface::XdgSurface, event: xdg_surface::Event, _: &(), _: &Connection, _: &QueueHandle) { + if let xdg_surface::Event::Configure { serial } = event { + surface.ack_configure(serial); + app.configured = true; + } + } +} + +impl Dispatch for App { + fn event(app: &mut Self, _: &wl_buffer::WlBuffer, event: wl_buffer::Event, slot: &usize, _: &Connection, _: &QueueHandle) { + if let wl_buffer::Event::Release = event { + app.released.push(*slot); + } + } +} + +delegate_noop!(App: ignore wl_compositor::WlCompositor); +delegate_noop!(App: ignore wl_surface::WlSurface); +delegate_noop!(App: ignore xdg_toplevel::XdgToplevel); +delegate_noop!(App: ignore zwp_linux_dmabuf_v1::ZwpLinuxDmabufV1); +delegate_noop!(App: ignore zwp_linux_buffer_params_v1::ZwpLinuxBufferParamsV1); From 356a4bc9718fcd23011d4e3e01fc3c9cec9088ce Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 06:38:31 -0700 Subject: [PATCH 06/25] GPU helper: hardware decoding and jail grants chosen per card maker The card's maker is read from /sys for the compositor's render node: - NVIDIA decodes with NVDEC and gets its device files and /proc; - AMD and Intel decode with VA-API on the render node; - Apple and others try V4L2; - every maker falls back to the CPU. No maker gets another's devices. On NVIDIA, /proc is a fresh one for the jail's own PID namespace. lock_down_gpu_helper adds two locks on top: Landlock (writes only under /dev) and a seccomp filter that refuses ptrace, process_vm_readv/writev, pidfd_getfd and kcmp with EPERM. Tests show /proc/self/mem, ptrace and process_vm_writev are refused, and that only NVIDIA gets /proc. The GPU colour bench decodes the same way, for the card it runs on. --- examples/colour-gpu.rs | 7 ++- examples/gpu-play.rs | 27 ++++++++-- examples/gpu-show.rs | 29 +++++++--- src/gpu.rs | 14 +++++ src/jail.rs | 117 +++++++++++++++++++++++++++++++++++------ src/lib.rs | 2 +- src/options.rs | 51 ++++++++++++++++++ 7 files changed, 217 insertions(+), 30 deletions(-) diff --git a/examples/colour-gpu.rs b/examples/colour-gpu.rs index d178511..188d784 100644 --- a/examples/colour-gpu.rs +++ b/examples/colour-gpu.rs @@ -223,7 +223,8 @@ fn main() -> ExitCode { eprintln!("can't make {}: {e}", dir.display()); return ExitCode::FAILURE; } - println!("\n{} colour cases, GPU renderer on {}, tolerance {TOLERANCE} steps:\n", cases.len(), gl.renderer); + let vendor = alias_playback::gpu::first_render_node().map_or(alias_playback::Vendor::Other, |node| alias_playback::gpu::vendor(&node)); + println!("\n{} colour cases, GPU renderer on {} ({vendor:?}), tolerance {TOLERANCE} steps:\n", cases.len(), gl.renderer); let (mut failed, mut skipped) = (0, 0); for case in &cases { let name = case.name(); @@ -249,7 +250,9 @@ fn main() -> ExitCode { let mut problems = Vec::new(); // The GPU renderer with and without hardware decoding, and the software renderer with // it, which CI can't try. - for (mode, render, hwdec) in [("GPU", RenderPath::Gpu, Hwdec::Off), ("GPU hwdec", RenderPath::Gpu, Hwdec::Auto), ("CPU hwdec", RenderPath::Cpu, Hwdec::Auto)] { + // Hardware decoding the way this card's maker does it, as a jailed player would. + let hwdec = Hwdec::For(vendor); + for (mode, render, hwdec) in [("GPU", RenderPath::Gpu, Hwdec::Off), ("GPU hwdec", RenderPath::Gpu, hwdec), ("CPU hwdec", RenderPath::Cpu, hwdec)] { let played = match render { RenderPath::Gpu => play(&gl, &clip, hwdec), RenderPath::Cpu => play_cpu(&clip, (WIDTH, HEIGHT), hwdec, true), diff --git a/examples/gpu-play.rs b/examples/gpu-play.rs index a7f3796..ec377ed 100644 --- a/examples/gpu-play.rs +++ b/examples/gpu-play.rs @@ -16,7 +16,7 @@ use std::time::Instant; use alias_playback::gpu::{Gpu, Plane, first_render_node}; use alias_playback::gpu_helper::{self, SLOTS, Said}; -use alias_playback::{Audio, Hwdec, Options, RenderPath, jail}; +use alias_playback::{Audio, Hwdec, Options, RenderPath, Vendor, jail}; const HELPER_ARG: &str = "--gpu-helper"; @@ -24,27 +24,44 @@ fn main() { let args: Vec = std::env::args().skip(1).collect(); if args.first().map(String::as_str) == Some(HELPER_ARG) { // The decoding choice, then the size `start` adds. - let hwdec = if args.get(1).map(String::as_str) == Some("hwdec") { Hwdec::Auto } else { Hwdec::Off }; + let hwdec = match args.get(1).map(String::as_str) { + Some("nvidia") => Hwdec::For(Vendor::Nvidia), + Some("amd") => Hwdec::For(Vendor::Amd), + Some("intel") => Hwdec::For(Vendor::Intel), + Some("apple") => Hwdec::For(Vendor::Apple), + Some("other") => Hwdec::For(Vendor::Other), + _ => Hwdec::Off, + }; let options = Options { render: RenderPath::Gpu, hwdec, audio: Audio::Off, cover_art: false, start_paused: true }; - gpu_helper::run(&args[2..], &options, 6, || jail::forbid_writes_outside(&[std::path::Path::new("/dev")])); + gpu_helper::run(&args[2..], &options, 6, jail::lock_down_gpu_helper); } let file = args.first().expect("a file to play").clone(); let flag = |name: &str| args.iter().any(|a| a == name); let size = args.iter().position(|a| a == "--size").and_then(|i| args.get(i + 1)).and_then(|s| s.split_once('x')).map_or((1920, 1080), |(w, h)| (w.parse().unwrap(), h.parse().unwrap())); let node = first_render_node().expect("a render node"); + let vendor = alias_playback::gpu::vendor(&node); let checker = flag("--check").then(|| Gpu::new(node.try_clone().expect("a copy")).expect("OpenGL for the check")); let exe = jail::own_exe().expect("own path"); let mut command = if flag("--jail") { let mut command = Command::new("bwrap"); - command.args(jail::gpu_arguments(&exe)).arg(HELPER_ARG); + command.args(jail::gpu_arguments(&exe, vendor)).arg(HELPER_ARG); command } else { let mut command = Command::new(&exe); command.arg(HELPER_ARG); command }; - command.arg(if flag("--hwdec") { "hwdec" } else { "software" }); + // The card's maker, found at run time: the helper decodes the way that maker's cards do, + // and its jail lets through only that maker's devices. + let name = match vendor { + Vendor::Nvidia => "nvidia", + Vendor::Amd => "amd", + Vendor::Intel => "intel", + Vendor::Apple => "apple", + Vendor::Other => "other", + }; + command.arg(if flag("--hwdec") { name } else { "software" }); let start = Instant::now(); let mut started = gpu_helper::start(command, File::open(&file).expect("the file"), node, size).expect("the helper"); gpu_helper::send(&started.socket, "play", &[]).expect("play"); diff --git a/examples/gpu-show.rs b/examples/gpu-show.rs index d76bd28..eb04c2a 100644 --- a/examples/gpu-show.rs +++ b/examples/gpu-show.rs @@ -16,7 +16,7 @@ use std::time::Instant; use alias_playback::gpu::first_render_node; use alias_playback::gpu_helper::{self, SLOTS, Said}; -use alias_playback::{Audio, Hwdec, Options, RenderPath, jail}; +use alias_playback::{Audio, Hwdec, Options, RenderPath, Vendor, jail}; use rustix::event::{PollFd, PollFlags, poll}; use wayland_client::protocol::{wl_buffer, wl_compositor, wl_registry, wl_surface}; use wayland_client::{Connection, Dispatch, QueueHandle, delegate_noop}; @@ -37,9 +37,16 @@ struct App { fn main() { let args: Vec = std::env::args().skip(1).collect(); if args.first().map(String::as_str) == Some(HELPER_ARG) { - let hwdec = if args.get(1).map(String::as_str) == Some("hwdec") { Hwdec::Auto } else { Hwdec::Off }; + let hwdec = match args.get(1).map(String::as_str) { + Some("nvidia") => Hwdec::For(Vendor::Nvidia), + Some("amd") => Hwdec::For(Vendor::Amd), + Some("intel") => Hwdec::For(Vendor::Intel), + Some("apple") => Hwdec::For(Vendor::Apple), + Some("other") => Hwdec::For(Vendor::Other), + _ => Hwdec::Off, + }; let options = Options { render: RenderPath::Gpu, hwdec, audio: Audio::Off, cover_art: false, start_paused: true }; - gpu_helper::run(&args[2..], &options, 6, || jail::forbid_writes_outside(&[std::path::Path::new("/dev")])); + gpu_helper::run(&args[2..], &options, 6, jail::lock_down_gpu_helper); } let file = args.first().expect("a file to play").clone(); let flag = |name: &str| args.iter().any(|a| a == name); @@ -62,18 +69,28 @@ fn main() { queue.blocking_dispatch(&mut app).expect("configure"); } + let node = first_render_node().expect("a render node"); + let vendor = alias_playback::gpu::vendor(&node); let exe = jail::own_exe().expect("own path"); let mut command = if flag("--jail") { let mut command = Command::new("bwrap"); - command.args(jail::gpu_arguments(&exe)).arg(HELPER_ARG); + command.args(jail::gpu_arguments(&exe, vendor)).arg(HELPER_ARG); command } else { let mut command = Command::new(&exe); command.arg(HELPER_ARG); command }; - command.arg(if flag("--hwdec") { "hwdec" } else { "software" }); - let node = first_render_node().expect("a render node"); + // The card's maker, found at run time: the helper decodes the way that maker's cards do, + // and its jail lets through only that maker's devices. + let name = match vendor { + Vendor::Nvidia => "nvidia", + Vendor::Amd => "amd", + Vendor::Intel => "intel", + Vendor::Apple => "apple", + Vendor::Other => "other", + }; + command.arg(if flag("--hwdec") { name } else { "software" }); let started = gpu_helper::start(command, File::open(&file).expect("the file"), node, size).expect("the helper"); let helper_pid = started.child.id(); let socket = started.socket; diff --git a/src/gpu.rs b/src/gpu.rs index 011f5b3..20c537a 100644 --- a/src/gpu.rs +++ b/src/gpu.rs @@ -433,6 +433,20 @@ pub fn first_render_node() -> Result { Err("no render node".into()) } +/// Who made the card behind a render node, from /sys. +pub fn vendor(node: &OwnedFd) -> crate::options::Vendor { + // SAFETY: a zeroed stat is valid, and the descriptor is live. + let mut stat: libc::stat = unsafe { std::mem::zeroed() }; + if unsafe { libc::fstat(node.as_raw_fd(), &mut stat) } != 0 { + return crate::options::Vendor::Other; + } + let (major, minor) = (libc::major(stat.st_rdev), libc::minor(stat.st_rdev)); + let device = format!("/sys/dev/char/{major}:{minor}/device"); + let pci = std::fs::read_to_string(format!("{device}/vendor")).ok().and_then(|v| u32::from_str_radix(v.trim().trim_start_matches("0x"), 16).ok()); + let driver = std::fs::read_link(format!("{device}/driver")).ok().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_default(); + crate::options::Vendor::from_sys(pci, &driver) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/jail.rs b/src/jail.rs index 444f91e..4bc2a0e 100644 --- a/src/jail.rs +++ b/src/jail.rs @@ -59,29 +59,71 @@ pub fn arguments(executable: &Path, sound_socket: Option<&Path>) -> Vec args } -/// bubblewrap's arguments for a GPU helper: the jail every player gets, plus the graphics -/// card's device files, which drawing and decoding on it need. That's the drivers' attack -/// surface too, which Mike accepted for this (2026-12-02). -pub fn gpu_arguments(executable: &Path) -> Vec { +/// bubblewrap's arguments for a GPU helper on a card made by `vendor`: the jail every player +/// gets, plus that card's device files, which drawing and decoding on it need, and nothing +/// for any other maker. That's the drivers' attack surface too, which Mike accepted for this +/// (2026-12-02). +pub fn gpu_arguments(executable: &Path, vendor: crate::options::Vendor) -> Vec { let mut args = arguments(executable, None); let run = args.len() - 2; - let mut devices = vec!["--dev-bind".to_owned(), "/dev/dri".to_owned(), "/dev/dri".to_owned()]; - // NVIDIA's driver has its own device files beside the DRM ones. - for name in ["nvidiactl", "nvidia0", "nvidia-modeset", "nvidia-uvm", "nvidia-uvm-tools"] { - devices.extend(["--dev-bind-try".to_owned(), format!("/dev/{name}"), format!("/dev/{name}")]); - } + let mut grants = vec!["--dev-bind".to_owned(), "/dev/dri".to_owned(), "/dev/dri".to_owned()]; // Drivers find the card's details in /sys. - devices.extend(["--ro-bind".to_owned(), "/sys".to_owned(), "/sys".to_owned()]); - // NVIDIA's decoder (CUDA) won't start without /proc. The jail leaves /proc out because - // writing /proc/self/mem changes code without asking for executable memory; with it in, - // the helper's Landlock rules refuse opening anything outside /dev for writing. - if Path::new("/dev/nvidiactl").exists() { - devices.extend(["--proc".to_owned(), "/proc".to_owned()]); + grants.extend(["--ro-bind".to_owned(), "/sys".to_owned(), "/sys".to_owned()]); + if vendor == crate::options::Vendor::Nvidia { + // NVIDIA's driver has its own device files beside the DRM ones. + for name in ["nvidiactl", "nvidia0", "nvidia-modeset", "nvidia-uvm", "nvidia-uvm-tools"] { + grants.extend(["--dev-bind-try".to_owned(), format!("/dev/{name}"), format!("/dev/{name}")]); + } + // NVDEC (CUDA) won't start without /proc. It's a fresh one for the jail's own process + // namespace (`--unshare-all` includes PIDs), so it shows only the jail. The helper's + // `lock_down_gpu_helper` keeps /proc/self/mem from being written. + grants.extend(["--proc".to_owned(), "/proc".to_owned()]); } - args.splice(run..run, devices); + args.splice(run..run, grants); args } +/// What a GPU helper's `lock_down` should do: Landlock lets it open files for writing only +/// under /dev, and seccomp refuses the system calls that write another process's or its own +/// memory from outside (`ptrace`, `process_vm_writev` and their kin). With /proc in the jail +/// for NVIDIA, that keeps code from being changed through /proc/self/mem or those calls. +pub fn lock_down_gpu_helper() -> bool { + forbid_writes_outside(&[Path::new("/dev")]) && forbid_memory_writes() +} + +/// A seccomp filter that refuses, with `EPERM`, the system calls that reach into a process's +/// memory: `ptrace`, `process_vm_readv`, `process_vm_writev`, `pidfd_getfd` and `kcmp`. +/// Everything else is allowed: libmpv and the drivers need a lot. +pub fn forbid_memory_writes() -> bool { + #[cfg(target_arch = "x86_64")] + const ARCH: u32 = 0xC000_003E; + #[cfg(target_arch = "aarch64")] + const ARCH: u32 = 0xC000_00B7; + const LD_W_ABS: u16 = 0x20; + const JEQ_K: u16 = 0x15; + const RET_K: u16 = 0x06; + const ALLOW: u32 = 0x7fff_0000; + const KILL: u32 = 0x8000_0000; + const ERRNO: u32 = 0x0005_0000; + const NR: u32 = 0; + const ARCH_OFFSET: u32 = 4; + let refused = [libc::SYS_ptrace, libc::SYS_process_vm_readv, libc::SYS_process_vm_writev, libc::SYS_pidfd_getfd, libc::SYS_kcmp]; + let stmt = |code: u16, k: u32| libc::sock_filter { code, jt: 0, jf: 0, k }; + let jump = |k: u32, jt: u8, jf: u8| libc::sock_filter { code: JEQ_K, jt, jf, k }; + let mut program = vec![stmt(LD_W_ABS, ARCH_OFFSET), jump(ARCH, 1, 0), stmt(RET_K, KILL), stmt(LD_W_ABS, NR)]; + let count = refused.len(); + for (i, call) in refused.iter().enumerate() { + // To the refusal after the rest of the checks, or on to the next. + program.push(jump(*call as u32, (count - i) as u8, 0)); + } + program.push(stmt(RET_K, ALLOW)); + program.push(stmt(RET_K, ERRNO | libc::EPERM as u32)); + let filter = libc::sock_fprog { len: program.len() as u16, filter: program.as_mut_ptr() }; + // SAFETY: no new privileges, as seccomp asks of an unprivileged process, and a valid + // program that outlives the call. + unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == 0 && libc::prctl(libc::PR_SET_SECCOMP, libc::SECCOMP_MODE_FILTER, &filter as *const libc::sock_fprog) == 0 } +} + /// The command that runs this program jailed with `helper_arg`, ready for `helper::start`. /// With `sound`, the session's PulseAudio socket goes in too, if there is one. pub fn command(helper_arg: &str, sound: bool) -> std::io::Result { @@ -191,6 +233,49 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn only_nvidia_gets_proc_and_its_devices() { + use crate::options::Vendor; + for vendor in [Vendor::Nvidia, Vendor::Amd, Vendor::Intel, Vendor::Apple, Vendor::Other] { + let text = gpu_arguments(Path::new("/opt/app"), vendor).join(" "); + let nvidia = vendor == Vendor::Nvidia; + assert_eq!(text.contains("--proc /proc"), nvidia, "{vendor:?}"); + assert_eq!(text.contains("/dev/nvidia"), nvidia, "{vendor:?}"); + assert!(text.contains("--dev-bind /dev/dri /dev/dri") && text.contains("--unshare-all"), "{vendor:?}"); + assert!(!text.contains("/dev/video"), "no camera or other V4L2 devices"); + assert!(text.ends_with("-- /playback-helper"), "{vendor:?}"); + } + } + + /// In a child process, as seccomp can't be lifted once on. + #[test] + fn after_the_filter_memory_writing_calls_are_refused() { + // SAFETY: the child only makes system calls and exits. + let pid = unsafe { libc::fork() }; + if pid == 0 { + let on = forbid_memory_writes(); + let errno = || std::io::Error::last_os_error().raw_os_error(); + // SAFETY: calls that must fail; their arguments are never used if refused. + let ptrace = unsafe { libc::ptrace(libc::PTRACE_TRACEME, 0, 0, 0) } == -1 && errno() == Some(libc::EPERM); + let mut byte = 0u8; + let local = libc::iovec { iov_base: &mut byte as *mut u8 as *mut _, iov_len: 1 }; + let remote = libc::iovec { iov_base: &mut byte as *mut u8 as *mut _, iov_len: 1 }; + // SAFETY: as above; writing this process's own byte to itself if it weren't refused. + let vm_write = unsafe { libc::process_vm_writev(libc::getpid(), &local, 1, &remote, 1, 0) } == -1 && errno() == Some(libc::EPERM); + let still_works = unsafe { libc::getpid() } > 0; + // SAFETY: leaving the forked child without running the parent's destructors. + unsafe { libc::_exit(i32::from(on) | i32::from(ptrace) << 1 | i32::from(vm_write) << 2 | i32::from(still_works) << 3) }; + } + let mut status = 0; + // SAFETY: waiting for our own child. + unsafe { libc::waitpid(pid, &mut status, 0) }; + let bits = libc::WEXITSTATUS(status); + assert_eq!(bits & 1, 1, "the filter went on"); + assert_eq!(bits & 2, 2, "ptrace refused"); + assert_eq!(bits & 4, 4, "process_vm_writev refused"); + assert_eq!(bits & 8, 8, "other calls still allowed"); + } + /// In a child process, as Landlock can't be lifted once on. #[test] fn after_landlock_proc_self_mem_cant_be_written_but_dev_can() { diff --git a/src/lib.rs b/src/lib.rs index 80b7852..10eb101 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,6 +23,6 @@ pub mod options; pub mod player; pub mod render; -pub use options::{Audio, Hwdec, Options, RenderPath}; +pub use options::{Audio, Hwdec, Options, RenderPath, Vendor}; pub use player::{Error, Event, Player}; pub use render::{GlRender, Native, SwFormat, SwRender}; diff --git a/src/options.rs b/src/options.rs index 9e5b768..bee9cec 100644 --- a/src/options.rs +++ b/src/options.rs @@ -3,6 +3,33 @@ //! The apps differ in only a few choices (where frames are drawn, hardware decoding, sound, //! cover art), so those are fields, and everything else is the same for all of them. +/// Who made a graphics card, which decides how it decodes video and what a jail must let +/// through for that. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Vendor { + /// NVDEC, through CUDA. + Nvidia, + /// VA-API, through the render node. + Amd, + Intel, + /// The M1's decoder is a V4L2 device; FFmpeg can't use it yet, so this decodes on the CPU. + Apple, + Other, +} + +impl Vendor { + /// From the PCI vendor number and the kernel driver's name in /sys. + pub fn from_sys(pci_vendor: Option, driver: &str) -> Self { + match (pci_vendor, driver) { + (Some(0x10de), _) | (_, "nvidia") => Self::Nvidia, + (Some(0x1002), _) | (_, "amdgpu" | "radeon") => Self::Amd, + (Some(0x8086), _) | (_, "i915" | "xe") => Self::Intel, + (_, "asahi") => Self::Apple, + _ => Self::Other, + } + } +} + /// Where frames are drawn. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RenderPath { @@ -18,6 +45,9 @@ pub enum Hwdec { Off, /// NVDEC, VA-API or V4L2 where the card and the file allow, and the CPU where they don't. Auto, + /// Only the method for this card's maker, and the CPU where it can't: what a jailed + /// player uses, since its jail only has that maker's devices. + For(Vendor), } /// Where sound goes. @@ -73,6 +103,11 @@ fn hwdec_value(render: RenderPath, hwdec: Hwdec) -> &'static str { (Hwdec::Off, _) => "no", (Hwdec::Auto, RenderPath::Cpu) => "nvdec-copy,vaapi-copy,v4l2m2m-copy", (Hwdec::Auto, RenderPath::Gpu) => "nvdec,vaapi,nvdec-copy,vaapi-copy,v4l2m2m-copy", + (Hwdec::For(Vendor::Nvidia), RenderPath::Cpu) => "nvdec-copy", + (Hwdec::For(Vendor::Nvidia), RenderPath::Gpu) => "nvdec,nvdec-copy", + (Hwdec::For(Vendor::Amd | Vendor::Intel), RenderPath::Cpu) => "vaapi-copy", + (Hwdec::For(Vendor::Amd | Vendor::Intel), RenderPath::Gpu) => "vaapi,vaapi-copy", + (Hwdec::For(Vendor::Apple | Vendor::Other), _) => "v4l2m2m-copy", } } @@ -176,6 +211,22 @@ mod tests { assert!(value(&cpu, "hwdec").unwrap().split(',').all(|method| method.ends_with("-copy"))); let gpu = Options { render: RenderPath::Gpu, ..cpu }; assert!(value(&gpu, "hwdec").unwrap().starts_with("nvdec,vaapi,")); + for vendor in [Vendor::Nvidia, Vendor::Amd, Vendor::Intel, Vendor::Apple, Vendor::Other] { + let one = Options { hwdec: Hwdec::For(vendor), ..Options::cpu() }; + let methods = value(&one, "hwdec").unwrap(); + let expected = match vendor { + Vendor::Nvidia => "nvdec", + Vendor::Amd | Vendor::Intel => "vaapi", + Vendor::Apple | Vendor::Other => "v4l2m2m", + }; + assert!(methods.split(',').all(|m| m.starts_with(expected)), "{vendor:?}: {methods}"); + assert!(methods.split(',').all(|m| m.ends_with("-copy")), "the CPU path copies back"); + } + assert_eq!(Vendor::from_sys(Some(0x10de), "nvidia"), Vendor::Nvidia); + assert_eq!(Vendor::from_sys(Some(0x1002), "amdgpu"), Vendor::Amd); + assert_eq!(Vendor::from_sys(Some(0x8086), "i915"), Vendor::Intel); + assert_eq!(Vendor::from_sys(None, "asahi"), Vendor::Apple); + assert_eq!(Vendor::from_sys(None, "virtio_gpu"), Vendor::Other); for options in [cpu, gpu] { assert!(!value(&options, "hwdec").unwrap().contains("vdpau"), "VDPAU stalls on what it can't decode"); } From 6206e152fccd3faf3bce1387e1320812cf9e9e92 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 06:41:49 -0700 Subject: [PATCH 07/25] GPU helper: lock down first, start libmpv beside OpenGL, buffers ready early - lock_down now runs before the helper has any other thread. Landlock applies only to the thread that turns it on and the ones it starts later, and libmpv and the drivers start threads of their own. - The seccomp filter is synced to every thread (TSYNC), like Gannet's. - libmpv starts on its own thread while OpenGL starts on the card. - The buffers are made when the video's size is known, before its first frame, so making them doesn't delay that frame. - The player stays paused until the first frame is drawn, then plays. - Each frame sent counts as presented (report_swap), for libmpv's timing. --- examples/gpu-play.rs | 2 +- src/gpu_helper.rs | 86 ++++++++++++++++++++++++++++++-------------- src/jail.rs | 10 ++++-- 3 files changed, 67 insertions(+), 31 deletions(-) diff --git a/examples/gpu-play.rs b/examples/gpu-play.rs index ec377ed..5971ac8 100644 --- a/examples/gpu-play.rs +++ b/examples/gpu-play.rs @@ -70,7 +70,7 @@ fn main() { let (mut dropped, mut state, mut decoder) = ((0, 0), None, String::from("?")); while let Ok(Some((text, fds))) = gpu_helper::receive(&started.socket) { if std::env::var_os("GPU_PLAY_DEBUG").is_some() { - eprintln!("< {text}"); + eprintln!("{:6.0} ms < {text}", start.elapsed().as_secs_f64() * 1000.0); } match gpu_helper::parse_said(&text) { Some(said @ Said::Buffer { slot, .. }) if fds.len() == 1 => buffers[slot] = Some((said, fds)), diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index b498c1d..7be36f5 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -257,7 +257,9 @@ impl Wake { } } -/// Runs a GPU player, and never returns. As `helper::run`, with `options` on the GPU path. +/// Runs a GPU player, and never returns. As `helper::run`, with `options` on the GPU path, +/// except that `lock_down` runs first, before any other thread exists (see +/// `jail::lock_down_gpu_helper`). pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: impl FnOnce() -> bool) -> ! { let parse = |i: usize| args.get(i).and_then(|a| a.parse::().ok()); let (Some(w), Some(h)) = (parse(0), parse(1)) else { std::process::exit(EXIT_BAD_START) }; @@ -269,19 +271,24 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp // SAFETY: descriptors `start` put there, owned by nothing else in this process. let (socket, node) = unsafe { (OwnedFd::from_raw_fd(FD_SOCKET), OwnedFd::from_raw_fd(FD_NODE)) }; let node_fd = node.as_raw_fd(); + // First, while this is the only thread, so every thread libmpv and the drivers start + // inherits it. + if !lock_down() { + std::process::exit(sandbox_code); + } + // libmpv starts while the card's OpenGL does: the two take about 50 and 110 ms. + let options = Options { start_paused: true, ..*options }; + let starting = std::thread::spawn(move || Player::new(&options)); let Ok(gpu) = Gpu::new(node) else { std::process::exit(EXIT_CANT_PLAY) }; - let player = match Player::new(&Options { start_paused: true, ..*options }) { - Ok(player) => player, - Err(crate::player::Error::Load(_)) => std::process::exit(EXIT_NO_MPV), - Err(_) => std::process::exit(EXIT_CANT_PLAY), + let player = match starting.join() { + Ok(Ok(player)) => player, + Ok(Err(crate::player::Error::Load(_))) => std::process::exit(EXIT_NO_MPV), + _ => std::process::exit(EXIT_CANT_PLAY), }; let (find, context) = gpu.proc_address(); // SAFETY: the context is current on this thread for the life of the process, and the // render node stays open inside `gpu`. let Ok(mut render) = (unsafe { GlRender::new(&player, find, context, Native::RenderNode(node_fd)) }) else { std::process::exit(EXIT_CANT_PLAY) }; - if !lock_down() { - std::process::exit(sandbox_code); - } let wake = Arc::new(Wake { shared: Mutex::new(Shared { size: (w.clamp(1, MAX_W), h.clamp(1, MAX_H)), ..Shared::default() }), ready: Condvar::new() }); let (for_events, for_frames) = (wake.clone(), wake.clone()); player.on_wakeup(move || for_events.with(|_| ())); @@ -329,7 +336,7 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp let (mut reported, mut last_report) = (String::new(), Instant::now() - REPORT_EVERY); let mut dropped_reported = String::new(); let mut natural: Option<(f64, f64)> = None; - let mut loaded = false; + let mut first_drawn = false; let mut wanted_paused = true; let mut told_decoder = false; loop { @@ -348,7 +355,8 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp } Some("play") => { wanted_paused = false; - if loaded { player.play() } else { Ok(()) } + // Before the first frame is drawn, it starts once that's on screen. + if first_drawn { player.play() } else { Ok(()) } } Some("seek") => number(words.next()).map_or(Ok(()), |by| player.seek_by(by)), Some("seekat") => number(words.next()).map_or(Ok(()), |at| player.seek_to(at)), @@ -363,16 +371,25 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp match event { Event::Shutdown => std::process::exit(0), Event::Loaded { video } => { - loaded = true; + first_drawn = false; if !video { say("novideo"); } - if !wanted_paused { - let _ = player.set_paused(false); - } } Event::Failed => say("cantplay"), - Event::VideoChanged => natural = player.double(c"dwidth").zip(player.double(c"dheight")).filter(|n| n.0 > 0.0 && n.1 > 0.0), + Event::VideoChanged => { + natural = player.double(c"dwidth").zip(player.double(c"dheight")).filter(|n| n.0 > 0.0 && n.1 > 0.0); + // The buffers are made now, before the first frame is decoded, so making + // them isn't in the way of showing it. + if let Some(natural) = natural { + let size = fit(natural, woken.size); + for slot in 0..SLOTS { + if !woken.held[slot] { + prepare(&gpu, &socket, &mut targets, slot, size); + } + } + } + } Event::Position(at) => state.position = at, Event::Duration(d) => (state.duration, urgent) = (d, true), Event::Paused(p) => (state.paused, urgent) = (p, true), @@ -401,25 +418,23 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp // The next buffer the app isn't holding. With none free, this frame is skipped and // libmpv counts it as late. let Some(slot) = (0..SLOTS).map(|i| (next + i) % SLOTS).find(|s| !woken.held[*s]) else { continue }; - if targets[slot].as_ref().is_some_and(|t| (t.width, t.height) != (fw, fh)) { - gpu.drop_target(targets[slot].take().expect("checked")); - } - if targets[slot].is_none() { - let Ok(target) = gpu.target(fw, fh, &[]) else { std::process::exit(EXIT_CANT_PLAY) }; - let plane = &target.planes[0]; - let text = format!("buffer {slot} {fw} {fh} {} {} {} {}", target.fourcc, target.modifier, plane.stride, plane.offset); - if target.planes.len() != 1 || send(&socket, &text, &[plane.fd.as_raw_fd()]).is_err() { - std::process::exit(EXIT_CANT_PLAY); - } - targets[slot] = Some(target); - } + prepare(&gpu, &socket, &mut targets, slot, (fw, fh)); let target = targets[slot].as_ref().expect("made above"); // SAFETY: the context is current and the framebuffer is this size. if unsafe { render.render(target.fbo as i32, fw as i32, fh as i32, GL_RGBA8, false) }.is_ok() { // Whole before the app shows it. An explicit fence would let the card run ahead. gpu.finish(); + render.report_swap(); wake.with(|shared| shared.held[slot] = true); say(&format!("frame {slot}")); + // Held paused until now, so the first frame is drawn without hurrying and none is + // dropped while the decoder and the card warm up. + if !first_drawn { + first_drawn = true; + if !wanted_paused { + let _ = player.set_paused(false); + } + } if !told_decoder { told_decoder = true; let decoder = player.get(c"hwdec-current").filter(|d| !d.is_empty() && d != "no").unwrap_or_else(|| "software".into()); @@ -430,6 +445,23 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp } } +/// Makes sure `slot` has a buffer of `size`, making and announcing a new one if not. +fn prepare(gpu: &Gpu, socket: &OwnedFd, targets: &mut [Option; SLOTS], slot: usize, size: (u32, u32)) { + if targets[slot].as_ref().is_some_and(|t| (t.width, t.height) != size) { + gpu.drop_target(targets[slot].take().expect("checked")); + } + if targets[slot].is_some() { + return; + } + let Ok(target) = gpu.target(size.0, size.1, &[]) else { std::process::exit(EXIT_CANT_PLAY) }; + let plane = &target.planes[0]; + let text = format!("buffer {slot} {} {} {} {} {} {}", size.0, size.1, target.fourcc, target.modifier, plane.stride, plane.offset); + if target.planes.len() != 1 || send(socket, &text, &[plane.fd.as_raw_fd()]).is_err() { + std::process::exit(EXIT_CANT_PLAY); + } + targets[slot] = Some(target); +} + /// The largest size with the picture's shape that fits in `wanted`, at least one pixel. fn fit(natural: (f64, f64), wanted: (u32, u32)) -> (u32, u32) { let scale = (wanted.0 as f64 / natural.0).min(wanted.1 as f64 / natural.1); diff --git a/src/jail.rs b/src/jail.rs index 4bc2a0e..ba16cf6 100644 --- a/src/jail.rs +++ b/src/jail.rs @@ -83,7 +83,8 @@ pub fn gpu_arguments(executable: &Path, vendor: crate::options::Vendor) -> Vec bool { program.push(stmt(RET_K, ALLOW)); program.push(stmt(RET_K, ERRNO | libc::EPERM as u32)); let filter = libc::sock_fprog { len: program.len() as u16, filter: program.as_mut_ptr() }; + // Every thread the process already has gets it too (TSYNC), not just this one. + const SET_MODE_FILTER: libc::c_ulong = 1; + const FILTER_FLAG_TSYNC: libc::c_ulong = 1; // SAFETY: no new privileges, as seccomp asks of an unprivileged process, and a valid - // program that outlives the call. - unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == 0 && libc::prctl(libc::PR_SET_SECCOMP, libc::SECCOMP_MODE_FILTER, &filter as *const libc::sock_fprog) == 0 } + // program that outlives the call; the kernel copies it. + unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == 0 && libc::syscall(libc::SYS_seccomp, SET_MODE_FILTER, FILTER_FLAG_TSYNC, &filter as *const libc::sock_fprog) == 0 } } /// The command that runs this program jailed with `helper_arg`, ready for `helper::start`. From 65507db174b8079e40452a9b7fc92821700ba393 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 06:42:37 -0700 Subject: [PATCH 08/25] GPU colour bench: Alias View's own path, the jailed helper's dmabufs Each clip also goes through the jailed GPU helper, with and without the card's hardware decoding. Its first frame is read back from the dmabuf on this side, as Alias View will show it. The bench checks it against the source colours like every other path. --- examples/colour-gpu.rs | 77 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 3 deletions(-) diff --git a/examples/colour-gpu.rs b/examples/colour-gpu.rs index 188d784..73d1935 100644 --- a/examples/colour-gpu.rs +++ b/examples/colour-gpu.rs @@ -206,7 +206,53 @@ fn play(gl: &Gl, clip: &Path, hwdec: Hwdec) -> Result<(Vec, String), String Err("no frame within 20 seconds".into()) } +const HELPER_ARG: &str = "--gpu-helper"; + +/// The first frame of `clip` as the jailed GPU helper draws it into a dmabuf, read back by +/// `reader` on this side, as Alias View will show it, and the decoder it used. +fn play_helper(reader: &alias_playback::gpu::Gpu, clip: &Path, vendor: alias_playback::Vendor, hwdec: bool) -> Result<(Vec, String), String> { + use alias_playback::gpu_helper::{self, Said}; + let exe = alias_playback::jail::own_exe().map_err(|e| e.to_string())?; + let mut command = std::process::Command::new("bwrap"); + command.args(alias_playback::jail::gpu_arguments(&exe, vendor)).arg(HELPER_ARG).arg(if hwdec { format!("{vendor:?}") } else { "software".into() }); + let node = alias_playback::gpu::first_render_node()?; + let file = std::fs::File::open(clip).map_err(|e| e.to_string())?; + let mut started = gpu_helper::start(command, file, node, (WIDTH as u32, HEIGHT as u32)).map_err(|e| e.to_string())?; + let mut buffers: Vec> = vec![None, None, None]; + let mut pixels = None; + let result = loop { + let Ok(Some((text, mut fds))) = gpu_helper::receive(&started.socket) else { break Err("the helper stopped".to_owned()) }; + match gpu_helper::parse_said(&text) { + Some(said @ Said::Buffer { slot, .. }) if fds.len() == 1 => buffers[slot] = Some((said, fds.remove(0))), + Some(Said::Frame { slot }) if pixels.is_none() => { + let Some((Said::Buffer { width, height, modifier, stride, offset, .. }, fd)) = &buffers[slot] else { break Err("a frame in no buffer".into()) }; + let planes = [alias_playback::gpu::Plane { fd: fd.try_clone().map_err(|e| e.to_string())?, stride: *stride, offset: *offset }]; + pixels = Some(reader.read_dmabuf(*width, *height, *modifier, &planes)?); + } + Some(Said::Decoder(name)) => break pixels.take().map(|p| (p, name)).ok_or_else(|| "no frame".to_owned()), + Some(Said::CantPlay | Said::NoVideo) => break Err(text), + _ => {} + } + }; + drop(started.socket); + let _ = started.child.wait(); + result +} + fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + if args.first().map(String::as_str) == Some(HELPER_ARG) { + let hwdec = match args.get(1).map(String::as_str) { + Some("Nvidia") => Hwdec::For(alias_playback::Vendor::Nvidia), + Some("Amd") => Hwdec::For(alias_playback::Vendor::Amd), + Some("Intel") => Hwdec::For(alias_playback::Vendor::Intel), + Some("Apple") => Hwdec::For(alias_playback::Vendor::Apple), + Some("Other") => Hwdec::For(alias_playback::Vendor::Other), + _ => Hwdec::Off, + }; + let options = Options { render: RenderPath::Gpu, hwdec, ..Options::cpu() }; + alias_playback::gpu_helper::run(&args[2..], &options, 6, alias_playback::jail::lock_down_gpu_helper); + } check_the_maths(); let filters: Vec = std::env::args().skip(1).filter(|a| !a.starts_with('-')).collect(); // SAFETY: this thread keeps the context current until the process ends. @@ -226,6 +272,22 @@ fn main() -> ExitCode { let vendor = alias_playback::gpu::first_render_node().map_or(alias_playback::Vendor::Other, |node| alias_playback::gpu::vendor(&node)); println!("\n{} colour cases, GPU renderer on {} ({vendor:?}), tolerance {TOLERANCE} steps:\n", cases.len(), gl.renderer); let (mut failed, mut skipped) = (0, 0); + // The jailed helper's frames are read back on a thread of their own, with an OpenGL + // context of its own on the same card. + let (to_reader, clips) = std::sync::mpsc::channel::<(std::path::PathBuf, bool)>(); + let (to_main, read) = std::sync::mpsc::channel::, String), String>>(); + std::thread::spawn(move || { + let reader = alias_playback::gpu::first_render_node().and_then(alias_playback::gpu::Gpu::new); + for (clip, hwdec) in clips { + let result = match &reader { + Ok(reader) => play_helper(reader, &clip, vendor, hwdec), + Err(e) => Err(e.clone()), + }; + if to_main.send(result).is_err() { + break; + } + } + }); for case in &cases { let name = case.name(); let clip = match make_clip(case, &dir) { @@ -252,10 +314,19 @@ fn main() -> ExitCode { // it, which CI can't try. // Hardware decoding the way this card's maker does it, as a jailed player would. let hwdec = Hwdec::For(vendor); - for (mode, render, hwdec) in [("GPU", RenderPath::Gpu, Hwdec::Off), ("GPU hwdec", RenderPath::Gpu, hwdec), ("CPU hwdec", RenderPath::Cpu, hwdec)] { + let modes = [ + ("GPU", Some(RenderPath::Gpu), Hwdec::Off), + ("GPU hwdec", Some(RenderPath::Gpu), hwdec), + ("CPU hwdec", Some(RenderPath::Cpu), hwdec), + ("jailed helper", None, Hwdec::Off), + ("jailed helper hwdec", None, hwdec), + ]; + for (mode, render, hwdec) in modes { let played = match render { - RenderPath::Gpu => play(&gl, &clip, hwdec), - RenderPath::Cpu => play_cpu(&clip, (WIDTH, HEIGHT), hwdec, true), + Some(RenderPath::Gpu) => play(&gl, &clip, hwdec), + Some(RenderPath::Cpu) => play_cpu(&clip, (WIDTH, HEIGHT), hwdec, true), + // Alias View's own path: a jailed helper's dmabuf, read back on this side. + None => to_reader.send((clip.clone(), hwdec != Hwdec::Off)).map_err(|e| e.to_string()).and_then(|()| read.recv().map_err(|e| e.to_string())?), }; match played { Ok((pixels, decoder)) => { From 708d7ddd9409dda82ca877143aae56808b2e5a21 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 06:43:30 -0700 Subject: [PATCH 09/25] GPU helper: draw before reporting the state, so the last frame isn't lost The end of a video was reported before that loop drew its last frame. The measuring apps stop at the end, so they missed the final frame (149 of 150 at 4K). The frame now goes first. --- src/gpu_helper.rs | 68 +++++++++++++++++++++++++---------------------- 1 file changed, 36 insertions(+), 32 deletions(-) diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index 7be36f5..7f45b69 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -399,6 +399,42 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp Event::Restarted => urgent = true, } } + // Drawn before the state is reported, so the last frame reaches the app before it + // hears the video has ended. + 'draw: { + if !render.new_frame() { + break 'draw; + } + let Some(natural) = natural else { break 'draw }; + let (fw, fh) = fit(natural, woken.size); + // The next buffer the app isn't holding. With none free, this frame is skipped and + // libmpv counts it as late. + let Some(slot) = (0..SLOTS).map(|i| (next + i) % SLOTS).find(|s| !woken.held[*s]) else { break 'draw }; + prepare(&gpu, &socket, &mut targets, slot, (fw, fh)); + let target = targets[slot].as_ref().expect("made above"); + // SAFETY: the context is current and the framebuffer is this size. + if unsafe { render.render(target.fbo as i32, fw as i32, fh as i32, GL_RGBA8, false) }.is_ok() { + // Whole before the app shows it. An explicit fence would let the card run ahead. + gpu.finish(); + render.report_swap(); + wake.with(|shared| shared.held[slot] = true); + say(&format!("frame {slot}")); + // Held paused until now, so the first frame is drawn without hurrying and none is + // dropped while the decoder and the card warm up. + if !first_drawn { + first_drawn = true; + if !wanted_paused { + let _ = player.set_paused(false); + } + } + if !told_decoder { + told_decoder = true; + let decoder = player.get(c"hwdec-current").filter(|d| !d.is_empty() && d != "no").unwrap_or_else(|| "software".into()); + say(&format!("decoder {decoder}")); + } + next = (slot + 1) % SLOTS; + } + } let line = state.line(); if line != reported && (urgent || last_report.elapsed() >= REPORT_EVERY) { say(&line); @@ -410,38 +446,6 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp reported = line; last_report = Instant::now(); } - if !render.new_frame() { - continue; - } - let Some(natural) = natural else { continue }; - let (fw, fh) = fit(natural, woken.size); - // The next buffer the app isn't holding. With none free, this frame is skipped and - // libmpv counts it as late. - let Some(slot) = (0..SLOTS).map(|i| (next + i) % SLOTS).find(|s| !woken.held[*s]) else { continue }; - prepare(&gpu, &socket, &mut targets, slot, (fw, fh)); - let target = targets[slot].as_ref().expect("made above"); - // SAFETY: the context is current and the framebuffer is this size. - if unsafe { render.render(target.fbo as i32, fw as i32, fh as i32, GL_RGBA8, false) }.is_ok() { - // Whole before the app shows it. An explicit fence would let the card run ahead. - gpu.finish(); - render.report_swap(); - wake.with(|shared| shared.held[slot] = true); - say(&format!("frame {slot}")); - // Held paused until now, so the first frame is drawn without hurrying and none is - // dropped while the decoder and the card warm up. - if !first_drawn { - first_drawn = true; - if !wanted_paused { - let _ = player.set_paused(false); - } - } - if !told_decoder { - told_decoder = true; - let decoder = player.get(c"hwdec-current").filter(|d| !d.is_empty() && d != "no").unwrap_or_else(|| "software".into()); - say(&format!("decoder {decoder}")); - } - next = (slot + 1) % SLOTS; - } } } From 5cb98b270dc1a50e4b284483ddce8cf61bfcee6c Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 10:38:17 -0700 Subject: [PATCH 10/25] GPU helper: run on Debian and on Intel (found on the Proxmox UHD 770) - The jail points /lib64 at /usr/lib64 where a system has it (Debian, Fedora), not only at /usr/lib (Arch). - The jail includes /etc/alternatives, which Debian's libraries link through (libmpv needs libblas there). - Landlock is required only when the jail has /proc (NVIDIA). Proxmox's kernel has no Landlock. The seccomp filter is still required. - GBM buffers with a second plane (Intel's compressed CCS layouts) are skipped, and GBM is asked again. - gpu-play says how the helper ended when it ends before the clip does. --- examples/gpu-play.rs | 11 +++++++++-- src/gpu.rs | 26 ++++++++++++++++++-------- src/jail.rs | 17 ++++++++++++++++- 3 files changed, 43 insertions(+), 11 deletions(-) diff --git a/examples/gpu-play.rs b/examples/gpu-play.rs index 5971ac8..11a937e 100644 --- a/examples/gpu-play.rs +++ b/examples/gpu-play.rs @@ -64,7 +64,11 @@ fn main() { command.arg(if flag("--hwdec") { name } else { "software" }); let start = Instant::now(); let mut started = gpu_helper::start(command, File::open(&file).expect("the file"), node, size).expect("the helper"); - gpu_helper::send(&started.socket, "play", &[]).expect("play"); + if gpu_helper::send(&started.socket, "play", &[]).is_err() { + // Gone before it could be told to play: say how it ended. + println!("the helper ended at once: {:?}", started.child.wait()); + return; + } let mut buffers: [Option<(Said, Vec)>; SLOTS] = [None, None, None]; let (mut frames, mut first_frame, mut shown): (u64, Option, Option) = (0, None, None); let (mut dropped, mut state, mut decoder) = ((0, 0), None, String::from("?")); @@ -112,7 +116,10 @@ fn main() { let (cpu, rss_kb) = usage_below(started.child.id()); drop(buffers); drop(started.socket); - let _ = started.child.wait(); + let status = started.child.wait(); + if state.is_none_or(|s| !s.ended) { + println!("the helper ended before the clip did: {status:?}"); + } let duration = state.map_or(0.0, |s| s.duration); println!( "{file}: {decoder}, {frames} frames in {wall:.2} s (clip {duration:.2} s), first frame {:.0} ms, dropped {} decoder + {} late, helper CPU {cpu:.2} s, helper peak RSS {} MB", diff --git a/src/gpu.rs b/src/gpu.rs index 20c537a..858b724 100644 --- a/src/gpu.rs +++ b/src/gpu.rs @@ -266,18 +266,28 @@ impl Gpu { // Only layouts OpenGL can draw into, not just sample from, and of those the // compositor's if it said. let drawable = self.drawable_modifiers(); - let usable: Vec = if modifiers.is_empty() { drawable } else { modifiers.iter().copied().filter(|m| drawable.contains(m)).collect() }; + let mut usable: Vec = if modifiers.is_empty() { drawable } else { modifiers.iter().copied().filter(|m| drawable.contains(m)).collect() }; // SAFETY of the block: GBM, EGL and GL calls on a live device and current context, // with results checked and everything made here freed on failure or in `drop_target`. unsafe { - let bo = if usable.is_empty() { - (self.gbm.bo_create)(self.device, width, height, FOURCC_XRGB8888, GBM_BO_USE_RENDERING) - } else { - (self.gbm.bo_create_with_modifiers2)(self.device, width, height, FOURCC_XRGB8888, usable.as_ptr(), usable.len() as u32, GBM_BO_USE_RENDERING) + // One plane only, for now: a layout with a second (a compression plane, as Intel's + // CCS layouts have) is left out and GBM asked again. + let bo = loop { + let bo = if usable.is_empty() { + (self.gbm.bo_create)(self.device, width, height, FOURCC_XRGB8888, GBM_BO_USE_RENDERING) + } else { + (self.gbm.bo_create_with_modifiers2)(self.device, width, height, FOURCC_XRGB8888, usable.as_ptr(), usable.len() as u32, GBM_BO_USE_RENDERING) + }; + if bo.is_null() { + return Err(format!("GBM won't make a {width}x{height} buffer")); + } + if (self.gbm.bo_get_plane_count)(bo) <= 1 || usable.is_empty() { + break bo; + } + let taken = (self.gbm.bo_get_modifier)(bo); + (self.gbm.bo_destroy)(bo); + usable.retain(|m| *m != taken); }; - if bo.is_null() { - return Err(format!("GBM won't make a {width}x{height} buffer")); - } let modifier = (self.gbm.bo_get_modifier)(bo); let mut planes = Vec::new(); for plane in 0..(self.gbm.bo_get_plane_count)(bo).max(1) { diff --git a/src/jail.rs b/src/jail.rs index ba16cf6..c6acd39 100644 --- a/src/jail.rs +++ b/src/jail.rs @@ -27,6 +27,9 @@ pub const RULES: &[(&str, &[&str])] = &[ ("--symlink", &["usr/lib", "/lib64"]), // Finding libraries without this works, but searches every folder for each one. ("--ro-bind-try", &["/etc/ld.so.cache", "/etc/ld.so.cache"]), + // Debian's alternatives: some libraries are links through here (libblas, which libmpv + // needs there). Links only, no settings. + ("--ro-bind-try", &["/etc/alternatives", "/etc/alternatives"]), ("--dev", &["/dev"]), ("--tmpfs", &["/tmp"]), // An environment with nothing of the user's in it. @@ -48,6 +51,12 @@ pub fn arguments(executable: &Path, sound_socket: Option<&Path>) -> Vec args.extend(values.iter().map(|value| (*value).to_owned())); }; for (option, values) in RULES { + // Debian and Fedora keep the 64-bit loader in /usr/lib64 (or a link there); Arch keeps + // everything in /usr/lib. Point /lib64 at whichever this system has. + if *values == ["usr/lib", "/lib64"] && Path::new("/usr/lib64").is_dir() { + rule(option, &["usr/lib64", "/lib64"]); + continue; + } rule(option, values); } rule("--ro-bind", &[&executable.to_string_lossy(), JAILED_SELF]); @@ -88,8 +97,14 @@ pub fn gpu_arguments(executable: &Path, vendor: crate::options::Vendor) -> Vec bool { - forbid_writes_outside(&[Path::new("/dev")]) && forbid_memory_writes() + let landlock = forbid_writes_outside(&[Path::new("/dev")]); + let needs_landlock = Path::new("/proc/self/mem").exists(); + (landlock || !needs_landlock) && forbid_memory_writes() } /// A seccomp filter that refuses, with `EPERM`, the system calls that reach into a process's From 8bd9374692e9538be7a19d585f882604cd2f1191 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 10:41:08 -0700 Subject: [PATCH 11/25] GPU jail: no new user namespaces, no mounts A helper that has been taken over could make a user namespace inside the jail, get privileges back there, and mount a procfs of its own to reach /proc/self/mem, even with no /proc granted. The GPU jail now runs with bubblewrap's --unshare-user --disable-userns. The helper's seccomp filter also refuses mount, umount2, unshare, setns and pivot_root, as Gannet's player filter does. New tests show both refusals, and each fails without its change: - unshare --user fails inside the jail but works outside it; - unshare and mount return EPERM under the filter. NVDEC still plays inside the jail. --- src/jail.rs | 50 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/src/jail.rs b/src/jail.rs index c6acd39..b00e7cf 100644 --- a/src/jail.rs +++ b/src/jail.rs @@ -75,7 +75,10 @@ pub fn arguments(executable: &Path, sound_socket: Option<&Path>) -> Vec pub fn gpu_arguments(executable: &Path, vendor: crate::options::Vendor) -> Vec { let mut args = arguments(executable, None); let run = args.len() - 2; - let mut grants = vec!["--dev-bind".to_owned(), "/dev/dri".to_owned(), "/dev/dri".to_owned()]; + // No new user namespaces inside: one would give back the privileges the jail drops, enough + // to mount a procfs of its own and reach /proc/self/mem with no /proc granted. + let mut grants = vec!["--unshare-user".to_owned(), "--disable-userns".to_owned()]; + grants.extend(["--dev-bind".to_owned(), "/dev/dri".to_owned(), "/dev/dri".to_owned()]); // Drivers find the card's details in /sys. grants.extend(["--ro-bind".to_owned(), "/sys".to_owned(), "/sys".to_owned()]); if vendor == crate::options::Vendor::Nvidia { @@ -108,7 +111,9 @@ pub fn lock_down_gpu_helper() -> bool { } /// A seccomp filter that refuses, with `EPERM`, the system calls that reach into a process's -/// memory: `ptrace`, `process_vm_readv`, `process_vm_writev`, `pidfd_getfd` and `kcmp`. +/// memory (`ptrace`, `process_vm_readv`, `process_vm_writev`, `pidfd_getfd`, `kcmp`) and those +/// that make or join namespaces or mount (`mount`, `umount2`, `unshare`, `setns`, +/// `pivot_root`). /// Everything else is allowed: libmpv and the drivers need a lot. pub fn forbid_memory_writes() -> bool { #[cfg(target_arch = "x86_64")] @@ -123,7 +128,20 @@ pub fn forbid_memory_writes() -> bool { const ERRNO: u32 = 0x0005_0000; const NR: u32 = 0; const ARCH_OFFSET: u32 = 4; - let refused = [libc::SYS_ptrace, libc::SYS_process_vm_readv, libc::SYS_process_vm_writev, libc::SYS_pidfd_getfd, libc::SYS_kcmp]; + // Writing a process's memory from outside, and the ways to a filesystem of one's own + // (a procfs with /proc/self/mem in it), as Gannet's player filter refuses. + let refused = [ + libc::SYS_ptrace, + libc::SYS_process_vm_readv, + libc::SYS_process_vm_writev, + libc::SYS_pidfd_getfd, + libc::SYS_kcmp, + libc::SYS_mount, + libc::SYS_umount2, + libc::SYS_unshare, + libc::SYS_setns, + libc::SYS_pivot_root, + ]; let stmt = |code: u16, k: u32| libc::sock_filter { code, jt: 0, jf: 0, k }; let jump = |k: u32, jt: u8, jf: u8| libc::sock_filter { code: JEQ_K, jt, jf, k }; let mut program = vec![stmt(LD_W_ABS, ARCH_OFFSET), jump(ARCH, 1, 0), stmt(RET_K, KILL), stmt(LD_W_ABS, NR)]; @@ -266,6 +284,25 @@ mod tests { } } + /// The GPU jail itself, with `unshare` standing in for the helper: it can't make a user + /// namespace. Skipped where bubblewrap or user namespaces aren't available (CI's + /// containers), as it says. + #[test] + fn the_gpu_jail_cant_make_a_user_namespace() { + let unshare = Path::new("/usr/bin/unshare"); + let can_jail = Command::new("bwrap").args(["--unshare-user", "--ro-bind", "/", "/", "true"]).status().is_ok_and(|s| s.success()); + if !can_jail || !unshare.exists() { + eprintln!("skipped: no bubblewrap with user namespaces here"); + return; + } + let args = gpu_arguments(unshare, crate::options::Vendor::Other); + let inside = Command::new("bwrap").args(&args).args(["--user", "true"]).status().expect("bubblewrap"); + assert!(!inside.success(), "a new user namespace was made inside the jail"); + // The same command outside the jail works, so the refusal is the jail's. + let outside = Command::new(unshare).args(["--user", "true"]).status().expect("unshare"); + assert!(outside.success()); + } + /// In a child process, as seccomp can't be lifted once on. #[test] fn after_the_filter_memory_writing_calls_are_refused() { @@ -281,7 +318,10 @@ mod tests { let remote = libc::iovec { iov_base: &mut byte as *mut u8 as *mut _, iov_len: 1 }; // SAFETY: as above; writing this process's own byte to itself if it weren't refused. let vm_write = unsafe { libc::process_vm_writev(libc::getpid(), &local, 1, &remote, 1, 0) } == -1 && errno() == Some(libc::EPERM); - let still_works = unsafe { libc::getpid() } > 0; + // SAFETY: calls that must be refused before they do anything. + let unshare = unsafe { libc::unshare(libc::CLONE_NEWUSER) } == -1 && errno() == Some(libc::EPERM); + let mount = unsafe { libc::mount(c"none".as_ptr(), c"/".as_ptr(), c"tmpfs".as_ptr(), 0, std::ptr::null()) } == -1 && errno() == Some(libc::EPERM); + let still_works = unsafe { libc::getpid() } > 0 && unshare && mount; // SAFETY: leaving the forked child without running the parent's destructors. unsafe { libc::_exit(i32::from(on) | i32::from(ptrace) << 1 | i32::from(vm_write) << 2 | i32::from(still_works) << 3) }; } @@ -292,7 +332,7 @@ mod tests { assert_eq!(bits & 1, 1, "the filter went on"); assert_eq!(bits & 2, 2, "ptrace refused"); assert_eq!(bits & 4, 4, "process_vm_writev refused"); - assert_eq!(bits & 8, 8, "other calls still allowed"); + assert_eq!(bits & 8, 8, "unshare and mount refused, and other calls still allowed"); } /// In a child process, as Landlock can't be lifted once on. From 9e283a36d5f89ac215f57ace39954e1cc512758f Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 10:44:40 -0700 Subject: [PATCH 12/25] GPU helper: a debug mode that sends libmpv's log and start-up timings A jailed helper can't write a log file anywhere. With debug (gpu_helper:: start's new flag, GPU_PLAY_DEBUG=1 in gpu-play), it sends libmpv's log lines as log messages. It also reports how long OpenGL, libmpv and libmpv's renderer took to start, and the average time to finish a frame. Player gains on_log for the log lines. --- examples/colour-gpu.rs | 2 +- examples/gpu-play.rs | 2 +- examples/gpu-show.rs | 2 +- src/ffi.rs | 11 +++++++++++ src/gpu_helper.rs | 33 +++++++++++++++++++++++++++++++-- src/player.rs | 24 +++++++++++++++++++++++- 6 files changed, 68 insertions(+), 6 deletions(-) diff --git a/examples/colour-gpu.rs b/examples/colour-gpu.rs index 73d1935..87eaadd 100644 --- a/examples/colour-gpu.rs +++ b/examples/colour-gpu.rs @@ -217,7 +217,7 @@ fn play_helper(reader: &alias_playback::gpu::Gpu, clip: &Path, vendor: alias_pla command.args(alias_playback::jail::gpu_arguments(&exe, vendor)).arg(HELPER_ARG).arg(if hwdec { format!("{vendor:?}") } else { "software".into() }); let node = alias_playback::gpu::first_render_node()?; let file = std::fs::File::open(clip).map_err(|e| e.to_string())?; - let mut started = gpu_helper::start(command, file, node, (WIDTH as u32, HEIGHT as u32)).map_err(|e| e.to_string())?; + let mut started = gpu_helper::start(command, file, node, (WIDTH as u32, HEIGHT as u32), false).map_err(|e| e.to_string())?; let mut buffers: Vec> = vec![None, None, None]; let mut pixels = None; let result = loop { diff --git a/examples/gpu-play.rs b/examples/gpu-play.rs index 11a937e..fe65327 100644 --- a/examples/gpu-play.rs +++ b/examples/gpu-play.rs @@ -63,7 +63,7 @@ fn main() { }; command.arg(if flag("--hwdec") { name } else { "software" }); let start = Instant::now(); - let mut started = gpu_helper::start(command, File::open(&file).expect("the file"), node, size).expect("the helper"); + let mut started = gpu_helper::start(command, File::open(&file).expect("the file"), node, size, std::env::var_os("GPU_PLAY_DEBUG").is_some()).expect("the helper"); if gpu_helper::send(&started.socket, "play", &[]).is_err() { // Gone before it could be told to play: say how it ended. println!("the helper ended at once: {:?}", started.child.wait()); diff --git a/examples/gpu-show.rs b/examples/gpu-show.rs index eb04c2a..cc03f77 100644 --- a/examples/gpu-show.rs +++ b/examples/gpu-show.rs @@ -91,7 +91,7 @@ fn main() { Vendor::Other => "other", }; command.arg(if flag("--hwdec") { name } else { "software" }); - let started = gpu_helper::start(command, File::open(&file).expect("the file"), node, size).expect("the helper"); + let started = gpu_helper::start(command, File::open(&file).expect("the file"), node, size, false).expect("the helper"); let helper_pid = started.child.id(); let socket = started.socket; gpu_helper::send(&socket, "play", &[]).expect("play"); diff --git a/src/ffi.rs b/src/ffi.rs index 3d46370..3935fdb 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -76,6 +76,15 @@ pub const EVENT_FILE_LOADED: c_int = 8; pub const EVENT_VIDEO_RECONFIG: c_int = 17; pub const EVENT_PLAYBACK_RESTART: c_int = 21; pub const EVENT_PROPERTY_CHANGE: c_int = 22; +pub const EVENT_LOG_MESSAGE: c_int = 2; + +#[repr(C)] +pub struct EventLogMessage { + pub prefix: *const c_char, + pub level: *const c_char, + pub text: *const c_char, + pub log_level: c_int, +} pub const END_FILE_ERROR: c_int = 4; @@ -139,6 +148,7 @@ pub struct Library { pub render: unsafe extern "C" fn(Handle, *mut RenderParam) -> c_int, pub render_report_swap: unsafe extern "C" fn(Handle), pub render_free: unsafe extern "C" fn(Handle), + pub request_log_messages: unsafe extern "C" fn(Handle, *const c_char) -> c_int, } // SAFETY: a table of function pointers into a library that stays loaded for the process. @@ -200,6 +210,7 @@ impl Library { render: sym!("mpv_render_context_render"), render_report_swap: sym!("mpv_render_context_report_swap"), render_free: sym!("mpv_render_context_free"), + request_log_messages: sym!("mpv_request_log_messages"), }) } diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index 7f45b69..8b58a4d 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -179,7 +179,8 @@ pub struct Started { /// Starts a player, as `helper::start` does, with `node` the render node of the compositor's /// card. `command` is the app's helper command, jailed or not, with its helper argument. -pub fn start(mut command: Command, file: File, node: OwnedFd, size: (u32, u32)) -> std::io::Result { +/// With `debug`, the player sends libmpv's log as `log` messages. +pub fn start(mut command: Command, file: File, node: OwnedFd, size: (u32, u32), debug: bool) -> std::io::Result { let (ours, theirs) = socketpair()?; let high = |fd: RawFd| -> std::io::Result { // SAFETY: duplicating a descriptor we hold, taking ownership of a good result. @@ -189,6 +190,9 @@ pub fn start(mut command: Command, file: File, node: OwnedFd, size: (u32, u32)) let (file, theirs, node) = (high(file.as_raw_fd())?, high(theirs.as_raw_fd())?, high(node.as_raw_fd())?); let fds = [file.as_raw_fd(), theirs.as_raw_fd(), node.as_raw_fd()]; command.arg(size.0.clamp(1, MAX_W).to_string()).arg(size.1.clamp(1, MAX_H).to_string()); + if debug { + command.arg("debug"); + } command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); // SAFETY: only async-signal-safe calls. unsafe { @@ -263,6 +267,9 @@ impl Wake { pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: impl FnOnce() -> bool) -> ! { let parse = |i: usize| args.get(i).and_then(|a| a.parse::().ok()); let (Some(w), Some(h)) = (parse(0), parse(1)) else { std::process::exit(EXIT_BAD_START) }; + // `debug` after the size: libmpv's log goes to the app as `log` messages, for a player + // that can't write a log file anywhere. + let debug = args.get(2).is_some_and(|a| a == "debug"); if options.render != RenderPath::Gpu { std::process::exit(EXIT_BAD_START); } @@ -277,9 +284,11 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp std::process::exit(sandbox_code); } // libmpv starts while the card's OpenGL does: the two take about 50 and 110 ms. + let began = Instant::now(); let options = Options { start_paused: true, ..*options }; let starting = std::thread::spawn(move || Player::new(&options)); let Ok(gpu) = Gpu::new(node) else { std::process::exit(EXIT_CANT_PLAY) }; + let gpu_ready = began.elapsed(); let player = match starting.join() { Ok(Ok(player)) => player, Ok(Err(crate::player::Error::Load(_))) => std::process::exit(EXIT_NO_MPV), @@ -288,10 +297,20 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp let (find, context) = gpu.proc_address(); // SAFETY: the context is current on this thread for the life of the process, and the // render node stays open inside `gpu`. + let mpv_ready = began.elapsed(); let Ok(mut render) = (unsafe { GlRender::new(&player, find, context, Native::RenderNode(node_fd)) }) else { std::process::exit(EXIT_CANT_PLAY) }; + let render_ready = began.elapsed(); + // Where start-up and each frame's finish go, for `debug`. + let mut finishing = (Duration::ZERO, 0u32); let wake = Arc::new(Wake { shared: Mutex::new(Shared { size: (w.clamp(1, MAX_W), h.clamp(1, MAX_H)), ..Shared::default() }), ready: Condvar::new() }); let (for_events, for_frames) = (wake.clone(), wake.clone()); player.on_wakeup(move || for_events.with(|_| ())); + if debug && let Ok(logs) = socket.try_clone() { + player.on_log(c"v", move |module, text| { + let line: String = format!("log {module}: {text}").chars().map(|c| if c.is_control() { ' ' } else { c }).take(MAX_MESSAGE - 1).collect(); + let _ = send(&logs, &line, &[]); + }); + } render.on_update(move || for_frames.with(|_| ())); let say = |text: &str| { if send(&socket, text, &[]).is_err() { @@ -299,6 +318,9 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp } }; say("hello"); + if debug { + say(&format!("log timing: OpenGL {} ms, libmpv {} ms, its renderer {} ms", gpu_ready.as_millis(), mpv_ready.as_millis(), render_ready.as_millis())); + } let reading = socket.try_clone().unwrap_or_else(|_| std::process::exit(EXIT_CANT_PLAY)); let for_reader = wake.clone(); let spawned = std::thread::Builder::new().name("app".into()).spawn(move || { @@ -395,7 +417,12 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp Event::Paused(p) => (state.paused, urgent) = (p, true), Event::Volume(v) => (state.volume, urgent) = (v, true), Event::Muted(m) => (state.muted, urgent) = (m, true), - Event::Ended(e) => (state.ended, urgent) = (e, true), + Event::Ended(e) => { + (state.ended, urgent) = (e, true); + if debug && e && finishing.1 > 0 { + say(&format!("log timing: finishing a frame took {:.2} ms on average over {} frames", finishing.0.as_secs_f64() * 1000.0 / f64::from(finishing.1), finishing.1)); + } + } Event::Restarted => urgent = true, } } @@ -415,7 +442,9 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp // SAFETY: the context is current and the framebuffer is this size. if unsafe { render.render(target.fbo as i32, fw as i32, fh as i32, GL_RGBA8, false) }.is_ok() { // Whole before the app shows it. An explicit fence would let the card run ahead. + let finish = Instant::now(); gpu.finish(); + finishing = (finishing.0 + finish.elapsed(), finishing.1 + 1); render.report_swap(); wake.with(|shared| shared.held[slot] = true); say(&format!("frame {slot}")); diff --git a/src/player.rs b/src/player.rs index b75bdf5..75eca9a 100644 --- a/src/player.rs +++ b/src/player.rs @@ -84,6 +84,7 @@ const WATCHED: &[(&CStr, c_int)] = &[ ]; type Wakeup = Box; +type LogSink = Box; /// The handle itself. It's destroyed when the last owner goes, so a render context, which /// holds one, is always freed before it. @@ -98,6 +99,9 @@ pub(crate) struct Core { /// put when the list grows. #[allow(clippy::vec_box)] wakeups: Mutex>>, + /// Where libmpv's own log lines go, once asked for: for diagnosing a player that can't + /// write a log file anywhere, such as a jailed one. + log: Mutex>, } // SAFETY: libmpv's client API may be called from any thread, and the one call that mustn't @@ -131,7 +135,7 @@ impl Player { if handle.is_null() { return Err(Error::Mpv { doing: "starting libmpv".into(), reason: "out of memory".into() }); } - let core = Core { lib, handle, events: Mutex::new(()), wakeups: Mutex::new(Vec::new()) }; + let core = Core { lib, handle, events: Mutex::new(()), wakeups: Mutex::new(Vec::new()), log: Mutex::new(None) }; for (name, value) in options.pairs() { core.set_option(name, value)?; } @@ -277,6 +281,14 @@ impl Player { wakeups.push(boxed); } + /// Hands libmpv's log lines at `level` and above (`"warn"`, `"info"`, `"v"`) to `sink`, as + /// its module and text, from the thread that reads events. + pub fn on_log(&self, level: &CStr, sink: impl Fn(&str, &str) + Send + Sync + 'static) { + *self.core.log.lock().unwrap_or_else(|e| e.into_inner()) = Some(Box::new(sink)); + // SAFETY: a live handle and a terminated level name. + unsafe { (self.core.lib.request_log_messages)(self.core.handle, level.as_ptr()) }; + } + /// The next event if there is one, without waiting. pub fn next_event(&self) -> Option { self.wait_event(Duration::ZERO) @@ -315,6 +327,16 @@ impl Player { (end.reason == ffi::END_FILE_ERROR).then_some(Event::Failed) } ffi::EVENT_VIDEO_RECONFIG => Some(Event::VideoChanged), + ffi::EVENT_LOG_MESSAGE => { + // SAFETY: a log event's data is a log struct with terminated strings, as the + // caller says. + let message = unsafe { &*(event.data as *const ffi::EventLogMessage) }; + if let Some(sink) = self.core.log.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + let text = |p: *const c_char| if p.is_null() { String::new() } else { unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned() }; + sink(&text(message.prefix), text(message.text).trim_end()); + } + None + } ffi::EVENT_PLAYBACK_RESTART => Some(Event::Restarted), ffi::EVENT_PROPERTY_CHANGE => { // SAFETY: a property event's data is a property struct, as the caller says. From da3be7f2b126f55da2507ba91ab6fd5c20d1e212 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 10:51:34 -0700 Subject: [PATCH 13/25] GPU jail: seccomp instead of --disable-userns, so it starts in LXC bubblewrap's --disable-userns writes /proc/sys/user/max_user_namespaces, which is read-only in an LXC container, so the GPU jail wouldn't start in one. The jail keeps --unshare-user and drops --disable-userns. The helper's seccomp filter now does that job: - clone with any CLONE_NEW* flag gets EPERM; - clone3 gets ENOSYS, as under Flatpak, so libc falls back to clone; - on x86-64, x32 system calls get EPERM, as they'd get past the numbers; - mount, umount2, unshare, setns and pivot_root stay refused. A new test runs the test program inside the GPU jail. There, before the filter, unshare --user works; after it, unshare --user, clone with CLONE_NEWUSER and clone3 are refused, and processes and threads still start. The test fails with the clone rules removed, and with the filter removed. NVDEC still plays inside the jail. --- src/jail.rs | 121 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 99 insertions(+), 22 deletions(-) diff --git a/src/jail.rs b/src/jail.rs index b00e7cf..3670808 100644 --- a/src/jail.rs +++ b/src/jail.rs @@ -75,9 +75,13 @@ pub fn arguments(executable: &Path, sound_socket: Option<&Path>) -> Vec pub fn gpu_arguments(executable: &Path, vendor: crate::options::Vendor) -> Vec { let mut args = arguments(executable, None); let run = args.len() - 2; - // No new user namespaces inside: one would give back the privileges the jail drops, enough - // to mount a procfs of its own and reach /proc/self/mem with no /proc granted. - let mut grants = vec!["--unshare-user".to_owned(), "--disable-userns".to_owned()]; + // A user namespace of the jail's own. The helper's seccomp filter (`forbid_memory_writes`) + // keeps it from making another inside: one would give back the privileges the jail drops, + // enough to mount a procfs of its own and reach /proc/self/mem with no /proc granted. + // bubblewrap's `--disable-userns` would do the same, but it writes + // /proc/sys/user/max_user_namespaces, which is read-only in an LXC container, so the jail + // wouldn't start in one. + let mut grants = vec!["--unshare-user".to_owned()]; grants.extend(["--dev-bind".to_owned(), "/dev/dri".to_owned(), "/dev/dri".to_owned()]); // Drivers find the card's details in /sys. grants.extend(["--ro-bind".to_owned(), "/sys".to_owned(), "/sys".to_owned()]); @@ -113,7 +117,9 @@ pub fn lock_down_gpu_helper() -> bool { /// A seccomp filter that refuses, with `EPERM`, the system calls that reach into a process's /// memory (`ptrace`, `process_vm_readv`, `process_vm_writev`, `pidfd_getfd`, `kcmp`) and those /// that make or join namespaces or mount (`mount`, `umount2`, `unshare`, `setns`, -/// `pivot_root`). +/// `pivot_root`, and `clone` with any `CLONE_NEW*` flag). `clone3` gets `ENOSYS`, as under +/// Flatpak: its flags are in memory, where seccomp can't look, and libc then falls back to +/// `clone`. On x86-64, x32 system calls are refused too, as they'd get past the numbers here. /// Everything else is allowed: libmpv and the drivers need a lot. pub fn forbid_memory_writes() -> bool { #[cfg(target_arch = "x86_64")] @@ -122,12 +128,22 @@ pub fn forbid_memory_writes() -> bool { const ARCH: u32 = 0xC000_00B7; const LD_W_ABS: u16 = 0x20; const JEQ_K: u16 = 0x15; + const JGE_K: u16 = 0x35; + const JSET_K: u16 = 0x45; const RET_K: u16 = 0x06; const ALLOW: u32 = 0x7fff_0000; const KILL: u32 = 0x8000_0000; const ERRNO: u32 = 0x0005_0000; const NR: u32 = 0; const ARCH_OFFSET: u32 = 4; + // The low half of the first argument, `clone`'s flags, on a little-endian machine. + const ARG0_LOW: u32 = 16; + // x32's system calls share x86-64's architecture number, with this bit set. + const X32_BIT: u32 = 0x4000_0000; + let x32 = cfg!(target_arch = "x86_64"); + // Every namespace `clone` can make. CLONE_NEWTIME is left out: in `clone` that bit is part + // of the exit signal, and only `unshare` and `clone3` take it, which are refused whole. + const NEW_NAMESPACES: u32 = (libc::CLONE_NEWNS | libc::CLONE_NEWCGROUP | libc::CLONE_NEWUTS | libc::CLONE_NEWIPC | libc::CLONE_NEWUSER | libc::CLONE_NEWPID | libc::CLONE_NEWNET) as u32; // Writing a process's memory from outside, and the ways to a filesystem of one's own // (a procfs with /proc/self/mem in it), as Gannet's player filter refuses. let refused = [ @@ -143,14 +159,33 @@ pub fn forbid_memory_writes() -> bool { libc::SYS_pivot_root, ]; let stmt = |code: u16, k: u32| libc::sock_filter { code, jt: 0, jf: 0, k }; - let jump = |k: u32, jt: u8, jf: u8| libc::sock_filter { code: JEQ_K, jt, jf, k }; - let mut program = vec![stmt(LD_W_ABS, ARCH_OFFSET), jump(ARCH, 1, 0), stmt(RET_K, KILL), stmt(LD_W_ABS, NR)]; - let count = refused.len(); - for (i, call) in refused.iter().enumerate() { - // To the refusal after the rest of the checks, or on to the next. - program.push(jump(*call as u32, (count - i) as u8, 0)); + let jump = |code: u16, k: u32, jt: usize, jf: usize| libc::sock_filter { code, jt: jt as u8, jf: jf as u8, k }; + let mut program = vec![stmt(LD_W_ABS, ARCH_OFFSET), jump(JEQ_K, ARCH, 1, 0), stmt(RET_K, KILL), stmt(LD_W_ABS, NR)]; + // The checks, then the endings they jump to: allow, ENOSYS, clone's flags, and EPERM. + let checks = usize::from(x32) + refused.len() + 2; + let allow = program.len() + checks; + let (no_such_call, clone_flags, eperm) = (allow + 1, allow + 2, allow + 5); + // A jump's targets count from the instruction after it. + let to = |target: usize, from: usize| target - from - 1; + if x32 { + let at = program.len(); + program.push(jump(JGE_K, X32_BIT, to(eperm, at), 0)); } + for call in refused { + let at = program.len(); + program.push(jump(JEQ_K, call as u32, to(eperm, at), 0)); + } + let at = program.len(); + program.push(jump(JEQ_K, libc::SYS_clone3 as u32, to(no_such_call, at), 0)); + let at = program.len(); + program.push(jump(JEQ_K, libc::SYS_clone as u32, to(clone_flags, at), 0)); + debug_assert_eq!(program.len(), allow); + program.push(stmt(RET_K, ALLOW)); + program.push(stmt(RET_K, ERRNO | libc::ENOSYS as u32)); + program.push(stmt(LD_W_ABS, ARG0_LOW)); + program.push(jump(JSET_K, NEW_NAMESPACES, 1, 0)); program.push(stmt(RET_K, ALLOW)); + debug_assert_eq!(program.len(), eperm); program.push(stmt(RET_K, ERRNO | libc::EPERM as u32)); let filter = libc::sock_fprog { len: program.len() as u16, filter: program.as_mut_ptr() }; // Every thread the process already has gets it too (TSYNC), not just this one. @@ -279,28 +314,63 @@ mod tests { assert_eq!(text.contains("--proc /proc"), nvidia, "{vendor:?}"); assert_eq!(text.contains("/dev/nvidia"), nvidia, "{vendor:?}"); assert!(text.contains("--dev-bind /dev/dri /dev/dri") && text.contains("--unshare-all"), "{vendor:?}"); + assert!(text.contains("--unshare-user") && !text.contains("--disable-userns"), "--disable-userns can't start in an LXC container"); assert!(!text.contains("/dev/video"), "no camera or other V4L2 devices"); assert!(text.ends_with("-- /playback-helper"), "{vendor:?}"); } } - /// The GPU jail itself, with `unshare` standing in for the helper: it can't make a user - /// namespace. Skipped where bubblewrap or user namespaces aren't available (CI's - /// containers), as it says. + /// The GPU jail with the helper's filter on, with this test program standing in for the + /// helper: `in_the_gpu_jail` below runs inside it. Skipped where bubblewrap or user + /// namespaces aren't available (CI's containers), as it says. #[test] fn the_gpu_jail_cant_make_a_user_namespace() { - let unshare = Path::new("/usr/bin/unshare"); let can_jail = Command::new("bwrap").args(["--unshare-user", "--ro-bind", "/", "/", "true"]).status().is_ok_and(|s| s.success()); - if !can_jail || !unshare.exists() { + if !can_jail || !Path::new("/usr/bin/unshare").exists() { eprintln!("skipped: no bubblewrap with user namespaces here"); return; } - let args = gpu_arguments(unshare, crate::options::Vendor::Other); - let inside = Command::new("bwrap").args(&args).args(["--user", "true"]).status().expect("bubblewrap"); - assert!(!inside.success(), "a new user namespace was made inside the jail"); - // The same command outside the jail works, so the refusal is the jail's. - let outside = Command::new(unshare).args(["--user", "true"]).status().expect("unshare"); - assert!(outside.success()); + let args = gpu_arguments(&std::env::current_exe().expect("own path"), crate::options::Vendor::Other); + let inside = Command::new("bwrap").args(&args).args(["--ignored", "--exact", "jail::tests::in_the_gpu_jail", "--test-threads=1", "--nocapture"]).output().expect("bubblewrap"); + let said = String::from_utf8_lossy(&inside.stdout); + assert!(inside.status.success() && said.contains("1 passed"), "inside the jail:\n{said}{}", String::from_utf8_lossy(&inside.stderr)); + } + + /// Run inside the GPU jail by `the_gpu_jail_cant_make_a_user_namespace`. The jail alone lets + /// a user namespace be made (since it can't use `--disable-userns`); the filter stops it, + /// whichever way it's asked for. + #[test] + #[ignore = "runs inside the GPU jail, from the_gpu_jail_cant_make_a_user_namespace"] + fn in_the_gpu_jail() { + assert!(Path::new(JAILED_SELF).exists(), "only inside the jail"); + let unshare_user = || Command::new("/usr/bin/unshare").args(["--user", "true"]).status().expect("unshare").success(); + assert!(unshare_user(), "before the filter, the jail itself allows a user namespace"); + assert!(forbid_memory_writes(), "the filter went on"); + assert!(!unshare_user(), "unshare --user refused"); + let errno = || std::io::Error::last_os_error().raw_os_error(); + // SAFETY: clone with no stack works as fork does; a child, if the call isn't refused, + // leaves at once. + let cloned = unsafe { libc::syscall(libc::SYS_clone, (libc::CLONE_NEWUSER | libc::SIGCHLD) as libc::c_ulong, 0usize, 0usize, 0usize, 0usize) }; + if cloned == 0 { + // SAFETY: leaving the child without running the parent's destructors. + unsafe { libc::_exit(0) }; + } + assert!(cloned == -1 && errno() == Some(libc::EPERM), "clone with CLONE_NEWUSER refused"); + // struct clone_args: flags, pidfd, child_tid, parent_tid, exit_signal, stack, + // stack_size, tls. + let mut clone_args = [0u64; 8]; + clone_args[0] = libc::CLONE_NEWUSER as u64; + clone_args[4] = libc::SIGCHLD as u64; + // SAFETY: a valid clone_args of the size given; a child leaves at once, as above. + let cloned = unsafe { libc::syscall(libc::SYS_clone3, clone_args.as_ptr(), size_of_val(&clone_args)) }; + if cloned == 0 { + // SAFETY: as above. + unsafe { libc::_exit(0) }; + } + assert!(cloned == -1 && errno() == Some(libc::ENOSYS), "clone3 says it doesn't exist"); + // libc falls back from clone3 to clone, so new processes and threads still start. + assert!(Command::new("/usr/bin/true").status().expect("true").success(), "processes still start"); + assert!(std::thread::spawn(|| 1).join().is_ok(), "threads still start"); } /// In a child process, as seccomp can't be lifted once on. @@ -320,6 +390,13 @@ mod tests { let vm_write = unsafe { libc::process_vm_writev(libc::getpid(), &local, 1, &remote, 1, 0) } == -1 && errno() == Some(libc::EPERM); // SAFETY: calls that must be refused before they do anything. let unshare = unsafe { libc::unshare(libc::CLONE_NEWUSER) } == -1 && errno() == Some(libc::EPERM); + // SAFETY: as unshare; a child, if the call isn't refused, leaves at once. + let cloned = unsafe { libc::syscall(libc::SYS_clone, (libc::CLONE_NEWNET | libc::SIGCHLD) as libc::c_ulong, 0usize, 0usize, 0usize, 0usize) }; + if cloned == 0 { + // SAFETY: leaving the child without running the parent's destructors. + unsafe { libc::_exit(0) }; + } + let unshare = unshare && cloned == -1 && errno() == Some(libc::EPERM); let mount = unsafe { libc::mount(c"none".as_ptr(), c"/".as_ptr(), c"tmpfs".as_ptr(), 0, std::ptr::null()) } == -1 && errno() == Some(libc::EPERM); let still_works = unsafe { libc::getpid() } > 0 && unshare && mount; // SAFETY: leaving the forked child without running the parent's destructors. @@ -332,7 +409,7 @@ mod tests { assert_eq!(bits & 1, 1, "the filter went on"); assert_eq!(bits & 2, 2, "ptrace refused"); assert_eq!(bits & 4, 4, "process_vm_writev refused"); - assert_eq!(bits & 8, 8, "unshare and mount refused, and other calls still allowed"); + assert_eq!(bits & 8, 8, "unshare, clone with CLONE_NEWNET and mount refused, and other calls still allowed"); } /// In a child process, as Landlock can't be lifted once on. From de0ac55481a9925d4d05d9823c6e629bdd83a153 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 10:56:13 -0700 Subject: [PATCH 14/25] GPU helper: hardware decoding that ends a file early falls back to software libmpv falls back to the CPU only when the hardware decoder reports an error. On the Proxmox box's Intel UHD 770, iHD stopped giving 1080p frames after 5 to 8 without one, and libmpv reported the end of the file. When a file ends more than a second short of its known length while hardware decoding is in use, the helper now sets hwdec to no. libmpv then starts the decoder again in software where the picture stopped, and the video plays on. This happens once per file, and the helper says "decoder software" again. A file that really is shorter than its stated length costs one start in software before it ends there too. A unit test covers when it falls back. The fallback itself was checked on the desktop by forcing it at the real end of the 1080p clip with a seek back to 1 s: NVDEC played to the end, then software played on from 1 s to the end (272 frames), with no end reported in between. --- src/gpu_helper.rs | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index 8b58a4d..538d591 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -361,6 +361,8 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp let mut first_drawn = false; let mut wanted_paused = true; let mut told_decoder = false; + // Hardware decoding in use, and whether this file has already fallen back from it. + let (mut hardware, mut fell_back) = (false, false); loop { let deadline = (state.line() != reported).then_some(last_report + REPORT_EVERY); let woken = wake.wait(deadline); @@ -417,6 +419,20 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp Event::Paused(p) => (state.paused, urgent) = (p, true), Event::Volume(v) => (state.volume, urgent) = (v, true), Event::Muted(m) => (state.muted, urgent) = (m, true), + // A hardware decoder that stops giving frames without an error ends the file + // early (Intel's iHD did, at 1080p). libmpv falls back to the CPU only on an + // error, so this does: the decoder starts again in software where the picture + // stopped, and the video plays on. + Event::Ended(true) if falls_back(hardware && !fell_back, state.position, state.duration) => { + (hardware, fell_back, told_decoder) = (false, true, false); + let _ = player.command(&[b"set", b"hwdec", b"no"]); + if !wanted_paused { + let _ = player.set_paused(false); + } + if debug { + say(&format!("log fallback: hardware decoding ended at {:.3} s of {:.3} s; on in software", state.position, state.duration)); + } + } Event::Ended(e) => { (state.ended, urgent) = (e, true); if debug && e && finishing.1 > 0 { @@ -458,8 +474,9 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp } if !told_decoder { told_decoder = true; - let decoder = player.get(c"hwdec-current").filter(|d| !d.is_empty() && d != "no").unwrap_or_else(|| "software".into()); - say(&format!("decoder {decoder}")); + let current = player.get(c"hwdec-current").filter(|d| !d.is_empty() && d != "no"); + hardware = current.is_some(); + say(&format!("decoder {}", current.as_deref().unwrap_or("software"))); } next = (slot + 1) % SLOTS; } @@ -478,6 +495,14 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp } } +/// Whether a file that ended at `position` of `duration` seconds stopped early, and should +/// go on in software: only with hardware decoding that hasn't fallen back already, and +/// more than a second short of a known length. A file that really is shorter than it says +/// (cut off while it was copied) costs one start in software before it ends there too. +fn falls_back(hardware: bool, position: f64, duration: f64) -> bool { + hardware && duration > 0.0 && position + 1.0 < duration +} + /// Makes sure `slot` has a buffer of `size`, making and announcing a new one if not. fn prepare(gpu: &Gpu, socket: &OwnedFd, targets: &mut [Option; SLOTS], slot: usize, size: (u32, u32)) { if targets[slot].as_ref().is_some_and(|t| (t.width, t.height) != size) { @@ -505,6 +530,14 @@ fn fit(natural: (f64, f64), wanted: (u32, u32)) -> (u32, u32) { mod tests { use super::*; + #[test] + fn hardware_decoding_that_ends_early_falls_back_once() { + assert!(falls_back(true, 0.233, 5.0), "Intel's iHD stopped after 7 frames of 150"); + assert!(!falls_back(true, 4.967, 5.0), "the real end"); + assert!(!falls_back(false, 0.233, 5.0), "software, or fallen back already"); + assert!(!falls_back(true, 0.0, 0.0), "no known length"); + } + #[test] fn sensible_messages_parse() { assert_eq!(parse_said("hello"), Some(Said::Hello)); From cead2472a7d0d783f88828110535d26911e69e40 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 10:58:05 -0700 Subject: [PATCH 15/25] GPU helper: VA-API gets the card opened again, not OpenGL's descriptor The helper passed one render node descriptor to both GBM/EGL and libmpv, whose VA-API interop calls vaGetDisplayDRM on it. GEM buffer handles belong to the open file, so Mesa and iHD shared one handle table: a handle one closes is gone for the other. That fits the Intel UHD 770 run, where 1080p H.264 stopped after a few frames with iHD's "Failed to end picture decode issue: 23" (VA_STATUS_ERROR_DECODING_ERROR) inside the helper only. Plain mpv in the same container uses vaGetDisplayWl, which opens the node itself, so its decoder has a file of its own. The helper now opens the node again by name, under /dev/dri, before it locks down, and gives that to libmpv; OpenGL keeps the app's descriptor. If that open fails, the shared one is used as before. Not yet confirmed on Intel: that needs another Proxmox run. NVDEC and software playback are unchanged on the desktop. A new test checks the reopened node is the same card with a file description of its own. --- src/gpu.rs | 40 +++++++++++++++++++++++++++++++++++++++- src/gpu_helper.rs | 9 +++++++-- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/gpu.rs b/src/gpu.rs index 858b724..6d54e4a 100644 --- a/src/gpu.rs +++ b/src/gpu.rs @@ -10,7 +10,7 @@ //! GL headers. use std::ffi::{CStr, c_char, c_int, c_void}; -use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; /// `XRGB8888`: what `wl_shm` frames use too, and every compositor takes. pub const FOURCC_XRGB8888: u32 = u32::from_le_bytes(*b"XR24"); @@ -443,6 +443,24 @@ pub fn first_render_node() -> Result { Err("no render node".into()) } +/// The same card's node opened again: a file description of its own, so GEM buffer handles +/// made through it are its own too. Each driver on a card needs one: handles belong to the +/// open file, so two drivers sharing one alias each other's buffers, and when one closes a +/// handle, the other's buffer is gone with it. libmpv's VA-API decoder and OpenGL (Mesa) are +/// two such drivers on Intel and AMD. Only the node's own name under /dev/dri is tried. +pub fn reopen(node: &OwnedFd) -> Option { + let rdev = |fd: RawFd| { + // SAFETY: a zeroed stat is valid, and the descriptor is live. + let mut stat: libc::stat = unsafe { std::mem::zeroed() }; + (unsafe { libc::fstat(fd, &mut stat) } == 0 && stat.st_mode & libc::S_IFMT == libc::S_IFCHR).then_some(stat.st_rdev) + }; + let device = rdev(node.as_raw_fd())?; + let minor = libc::minor(device); + let path = if minor >= 128 { format!("/dev/dri/renderD{minor}") } else { format!("/dev/dri/card{minor}") }; + let file: OwnedFd = std::fs::OpenOptions::new().read(true).write(true).open(path).ok()?.into(); + (rdev(file.as_raw_fd()) == Some(device)).then_some(file) +} + /// Who made the card behind a render node, from /sys. pub fn vendor(node: &OwnedFd) -> crate::options::Vendor { // SAFETY: a zeroed stat is valid, and the descriptor is live. @@ -461,6 +479,26 @@ pub fn vendor(node: &OwnedFd) -> crate::options::Vendor { mod tests { use super::*; + /// A file description of its own: status flags set on one don't show on the other. + /// Skipped with no card (CI). + #[test] + fn a_reopened_node_is_the_same_card_opened_again() { + let Ok(node) = first_render_node() else { + eprintln!("skipped: no render node here"); + return; + }; + let again = reopen(&node).expect("opened again"); + assert_ne!(node.as_raw_fd(), again.as_raw_fd()); + // SAFETY: plain fcntl calls on live descriptors. + unsafe { + let flags = libc::fcntl(node.as_raw_fd(), libc::F_GETFL); + assert_eq!(libc::fcntl(node.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK), 0); + assert_eq!(libc::fcntl(again.as_raw_fd(), libc::F_GETFL) & libc::O_NONBLOCK, 0, "a description of its own, not a dup"); + } + let not_a_card: OwnedFd = std::fs::File::open("/dev/null").unwrap().into(); + assert!(reopen(¬_a_card).is_none(), "/dev/null is a character device, but not this card"); + } + /// Needs a graphics card, so it's left out of CI: `cargo test -- --ignored`. #[test] #[ignore] diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index 538d591..824a24b 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -277,7 +277,12 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL as libc::c_ulong, 0, 0, 0) }; // SAFETY: descriptors `start` put there, owned by nothing else in this process. let (socket, node) = unsafe { (OwnedFd::from_raw_fd(FD_SOCKET), OwnedFd::from_raw_fd(FD_NODE)) }; - let node_fd = node.as_raw_fd(); + // libmpv's VA-API decoder gets the card opened again, not OpenGL's descriptor: sharing + // one, Mesa and iHD closed each other's buffers, and Intel stopped decoding 1080p after + // a few frames ("Failed to end picture decode issue: 23"). As the jail grants only the + // card's node, the old one stays as the fallback. + let decoder_node = crate::gpu::reopen(&node); + let node_fd = decoder_node.as_ref().map_or(node.as_raw_fd(), |n| n.as_raw_fd()); // First, while this is the only thread, so every thread libmpv and the drivers start // inherits it. if !lock_down() { @@ -296,7 +301,7 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp }; let (find, context) = gpu.proc_address(); // SAFETY: the context is current on this thread for the life of the process, and the - // render node stays open inside `gpu`. + // render node stays open, inside `gpu` or in `decoder_node`, until it exits. let mpv_ready = began.elapsed(); let Ok(mut render) = (unsafe { GlRender::new(&player, find, context, Native::RenderNode(node_fd)) }) else { std::process::exit(EXIT_CANT_PLAY) }; let render_ready = began.elapsed(); From 06114d8a98ecff69915a407e1c770abadab5e268 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:07:57 -0700 Subject: [PATCH 16/25] GPU helper: fixes from #3's review - A new size draws the frame again while paused or stopped, as the CPU helper does. Checked on the desktop: paused, then sent a new size, and a 960x540 buffer and frame followed. - A frame that comes while the app holds every buffer is drawn once one is given back, instead of being lost. - nouveau is no longer taken for NVIDIA: only NVIDIA's own driver gets NVDEC and the jail's /proc. A card with NVIDIA's PCI number on another driver decodes in software. - The app's `buffer` check takes only XRGB8888, and a row at most 64 KiB longer than its pixels. - Volume from the app is kept within 0 to 100. - A debug log line is cut to the packet size in bytes, not characters, so a long line with non-ASCII text isn't dropped. - The GPU jail test skips where there's no /dev/dri, which the jail binds. - gpu-show stops when the helper goes without a word. Killing the helper's bubblewrap mid-clip now ends gpu-show at once; before, it waited until it was killed. --- examples/gpu-show.rs | 13 +++++++--- src/gpu_helper.rs | 58 ++++++++++++++++++++++++++++---------------- src/jail.rs | 5 ++-- src/options.rs | 5 +++- 4 files changed, 54 insertions(+), 27 deletions(-) diff --git a/examples/gpu-show.rs b/examples/gpu-show.rs index cc03f77..39113b9 100644 --- a/examples/gpu-show.rs +++ b/examples/gpu-show.rs @@ -97,16 +97,19 @@ fn main() { gpu_helper::send(&socket, "play", &[]).expect("play"); // The helper's messages, read on their own thread and handed over with a wake-up. - let (tx, rx) = mpsc::channel::<(String, Vec)>(); + // `None` once the helper is gone, said or not, so a silent death doesn't hang this. + let (tx, rx) = mpsc::channel::)>>(); let (wake_read, wake_write) = rustix::pipe::pipe().expect("pipe"); let reading = socket.try_clone().expect("a copy"); std::thread::spawn(move || { while let Ok(Some(message)) = gpu_helper::receive(&reading) { - if tx.send(message).is_err() { + if tx.send(Some(message)).is_err() { break; } let _ = rustix::io::write(&wake_write, &[1]); } + let _ = tx.send(None); + let _ = rustix::io::write(&wake_write, &[1]); }); let mut buffers: [Option; SLOTS] = [None, None, None]; @@ -138,7 +141,11 @@ fn main() { }; } let _ = rustix::io::read(&wake_read, &mut scratch); - for (text, fds) in rx.try_iter() { + for message in rx.try_iter() { + let Some((text, fds)) = message else { + done = true; + break; + }; match gpu_helper::parse_said(&text) { Some(Said::Buffer { slot, width, height, fourcc, modifier, stride, offset }) if fds.len() == 1 => { let params = dmabuf.create_params(&qh, ()); diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index 824a24b..73f24ba 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -35,6 +35,9 @@ pub const SLOTS: usize = 3; pub const MAX_W: u32 = 7680; pub const MAX_H: u32 = 4320; const MAX_MESSAGE: usize = 256; +/// The most a driver pads a buffer's row by: tiled layouts round rows up to their tile's +/// width, a few KiB at most. +const MAX_ROW_PADDING: u64 = 64 * 1024; const REPORT_EVERY: Duration = Duration::from_millis(100); /// What the player says. @@ -86,7 +89,9 @@ pub fn parse_said(line: &str) -> Option { ("dropped", 3) => Some(Said::Dropped { decoder: n(1)?, late: n(2)? }), ("buffer", 8) => { let (width, height, stride) = (small(2)?, small(3)?, small(6)?); - if width == 0 || height == 0 || width > MAX_W || height > MAX_H || u64::from(stride) < u64::from(width) * 4 { + // Only the one format the player makes, and a row no longer than a padded one. + let row = u64::from(width) * 4; + if width == 0 || height == 0 || width > MAX_W || height > MAX_H || u64::from(stride) < row || u64::from(stride) > row + MAX_ROW_PADDING || small(4)? != crate::gpu::FOURCC_XRGB8888 { return None; } Some(Said::Buffer { slot: slot(1)?, width, height, fourcc: small(4)?, modifier: n(5)?, stride, offset: small(7)? }) @@ -312,7 +317,9 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp player.on_wakeup(move || for_events.with(|_| ())); if debug && let Ok(logs) = socket.try_clone() { player.on_log(c"v", move |module, text| { - let line: String = format!("log {module}: {text}").chars().map(|c| if c.is_control() { ' ' } else { c }).take(MAX_MESSAGE - 1).collect(); + let mut line: String = format!("log {module}: {text}").chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); + // In bytes, as a packet is: a longer one would be cut and dropped. + line.truncate(line.floor_char_boundary(MAX_MESSAGE - 1)); let _ = send(&logs, &line, &[]); }); } @@ -368,6 +375,8 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp let mut told_decoder = false; // Hardware decoding in use, and whether this file has already fallen back from it. let (mut hardware, mut fell_back) = (false, false); + // A new frame not drawn yet, as every buffer was held; and the size of the last drawn. + let (mut owed, mut drawn_size) = (false, None); loop { let deadline = (state.line() != reported).then_some(last_report + REPORT_EVERY); let woken = wake.wait(deadline); @@ -389,7 +398,7 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp } Some("seek") => number(words.next()).map_or(Ok(()), |by| player.seek_by(by)), Some("seekat") => number(words.next()).map_or(Ok(()), |at| player.seek_to(at)), - Some("volume") => number(words.next()).map_or(Ok(()), |v| player.set_volume(v)), + Some("volume") => number(words.next()).map_or(Ok(()), |v| player.set_volume(v.clamp(0.0, 100.0))), Some("mute") => player.set_muted(true), Some("unmute") => player.set_muted(false), _ => Ok(()), @@ -450,13 +459,16 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp // Drawn before the state is reported, so the last frame reaches the app before it // hears the video has ended. 'draw: { - if !render.new_frame() { - break 'draw; - } + owed |= render.new_frame(); let Some(natural) = natural else { break 'draw }; let (fw, fh) = fit(natural, woken.size); - // The next buffer the app isn't holding. With none free, this frame is skipped and - // libmpv counts it as late. + // A new size draws the frame again, paused or stopped too. + let resized = drawn_size.is_some_and(|size| size != (fw, fh)); + if !owed && !resized { + break 'draw; + } + // The next buffer the app isn't holding. With none free, the frame waits for one: + // the app giving one back wakes this loop. let Some(slot) = (0..SLOTS).map(|i| (next + i) % SLOTS).find(|s| !woken.held[*s]) else { break 'draw }; prepare(&gpu, &socket, &mut targets, slot, (fw, fh)); let target = targets[slot].as_ref().expect("made above"); @@ -467,6 +479,7 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp gpu.finish(); finishing = (finishing.0 + finish.elapsed(), finishing.1 + 1); render.report_swap(); + (owed, drawn_size) = (false, Some((fw, fh))); wake.with(|shared| shared.held[slot] = true); say(&format!("frame {slot}")); // Held paused until now, so the first frame is drawn without hurrying and none is @@ -557,21 +570,24 @@ mod tests { #[test] fn nonsense_is_refused() { + let xr24 = crate::gpu::FOURCC_XRGB8888; for line in [ - "", - "frame 3", - "frame", - "frame 1 2", - "buffer 3 10 10 1 0 40 0", - "buffer 0 10 10 1 0 39 0", - "buffer 0 0 10 1 0 40 0", - "buffer 0 7681 10 1 0 30724 0", - "buffer 0 10 10 1 0 40", - "dropped 1", - "hello again", - "exec sh", + "".to_owned(), + "frame 3".into(), + "frame".into(), + "frame 1 2".into(), + format!("buffer 3 10 10 {xr24} 0 40 0"), + format!("buffer 0 10 10 {xr24} 0 39 0"), + format!("buffer 0 0 10 {xr24} 0 40 0"), + format!("buffer 0 7681 10 {xr24} 0 30724 0"), + format!("buffer 0 10 10 {xr24} 0 40"), + "buffer 0 10 10 1 0 40 0".into(), + format!("buffer 0 10 10 {xr24} 0 {} 0", 40 + 64 * 1024 + 1), + "dropped 1".into(), + "hello again".into(), + "exec sh".into(), ] { - assert_eq!(parse_said(line), None, "{line}"); + assert_eq!(parse_said(&line), None, "{line}"); } } diff --git a/src/jail.rs b/src/jail.rs index 3670808..173b3a1 100644 --- a/src/jail.rs +++ b/src/jail.rs @@ -326,8 +326,9 @@ mod tests { #[test] fn the_gpu_jail_cant_make_a_user_namespace() { let can_jail = Command::new("bwrap").args(["--unshare-user", "--ro-bind", "/", "/", "true"]).status().is_ok_and(|s| s.success()); - if !can_jail || !Path::new("/usr/bin/unshare").exists() { - eprintln!("skipped: no bubblewrap with user namespaces here"); + // The GPU jail binds /dev/dri, so it can't start where there's no card (CI). + if !can_jail || !Path::new("/usr/bin/unshare").exists() || !Path::new("/dev/dri").is_dir() { + eprintln!("skipped: no bubblewrap with user namespaces, or no /dev/dri, here"); return; } let args = gpu_arguments(&std::env::current_exe().expect("own path"), crate::options::Vendor::Other); diff --git a/src/options.rs b/src/options.rs index bee9cec..00b0ec3 100644 --- a/src/options.rs +++ b/src/options.rs @@ -21,7 +21,9 @@ impl Vendor { /// From the PCI vendor number and the kernel driver's name in /sys. pub fn from_sys(pci_vendor: Option, driver: &str) -> Self { match (pci_vendor, driver) { - (Some(0x10de), _) | (_, "nvidia") => Self::Nvidia, + // NVIDIA's own driver only. nouveau has no NVDEC, and its jail mustn't get /proc. + (_, "nvidia") => Self::Nvidia, + (Some(0x10de), _) => Self::Other, (Some(0x1002), _) | (_, "amdgpu" | "radeon") => Self::Amd, (Some(0x8086), _) | (_, "i915" | "xe") => Self::Intel, (_, "asahi") => Self::Apple, @@ -223,6 +225,7 @@ mod tests { assert!(methods.split(',').all(|m| m.ends_with("-copy")), "the CPU path copies back"); } assert_eq!(Vendor::from_sys(Some(0x10de), "nvidia"), Vendor::Nvidia); + assert_eq!(Vendor::from_sys(Some(0x10de), "nouveau"), Vendor::Other, "no NVDEC, no /proc"); assert_eq!(Vendor::from_sys(Some(0x1002), "amdgpu"), Vendor::Amd); assert_eq!(Vendor::from_sys(Some(0x8086), "i915"), Vendor::Intel); assert_eq!(Vendor::from_sys(None, "asahi"), Vendor::Apple); From ecae01707c63e20a3754796b4e4929f5b245c64e Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:09:48 -0700 Subject: [PATCH 17/25] GPU helper prototype: start warm, before a file is chosen `gpu_helper::start_warm` starts a player with no file: OpenGL, libmpv and its renderer start at once, and it says `hello` when they're ready. `gpu_helper::load` then gives it the file, as a descriptor on a `load` message. `start` is unchanged. A player started warm keeps the file loaded last, and the one before, open while libmpv may read them. gpu-play's `--warm` times the first frame from when the file is given. No shader cache is added to the jail. --- examples/gpu-play.rs | 26 ++++++++++++++++++++--- src/gpu_helper.rs | 50 +++++++++++++++++++++++++++++++++++++++----- 2 files changed, 68 insertions(+), 8 deletions(-) diff --git a/examples/gpu-play.rs b/examples/gpu-play.rs index fe65327..688d190 100644 --- a/examples/gpu-play.rs +++ b/examples/gpu-play.rs @@ -3,9 +3,13 @@ //! giving the one before back), and prints what it cost. //! //! ```sh -//! cargo run --release --example gpu-play -- FILE [--jail] [--hwdec] [--size WxH] [--check] +//! cargo run --release --example gpu-play -- FILE [--jail] [--hwdec] [--size WxH] [--check] [--warm] //! ``` //! +//! `--warm` starts the helper with no file, waits until it says it's ready, and only then +//! gives it the file: the first frame is timed from then, as if the app had started the +//! player before the user chose a file. +//! //! `--check` reads the first frame back from its dmabuf and prints the middle pixel, which //! shows the frames cross the processes whole and in the right colours. @@ -62,8 +66,24 @@ fn main() { Vendor::Other => "other", }; command.arg(if flag("--hwdec") { name } else { "software" }); - let start = Instant::now(); - let mut started = gpu_helper::start(command, File::open(&file).expect("the file"), node, size, std::env::var_os("GPU_PLAY_DEBUG").is_some()).expect("the helper"); + let debug = std::env::var_os("GPU_PLAY_DEBUG").is_some(); + let mut start = Instant::now(); + let mut started = if flag("--warm") { + let started = gpu_helper::start_warm(command, node, size, debug).expect("the helper"); + loop { + match gpu_helper::receive(&started.socket) { + Ok(Some((text, _))) if text == "hello" => break, + Ok(Some(_)) => {} + _ => panic!("the helper ended while warming up"), + } + } + println!("warm after {:.0} ms", start.elapsed().as_secs_f64() * 1000.0); + start = Instant::now(); + gpu_helper::load(&started.socket, &File::open(&file).expect("the file")).expect("load"); + started + } else { + gpu_helper::start(command, File::open(&file).expect("the file"), node, size, debug).expect("the helper") + }; if gpu_helper::send(&started.socket, "play", &[]).is_err() { // Gone before it could be told to play: say how it ended. println!("the helper ended at once: {:?}", started.child.wait()); diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index 73f24ba..dfdf232 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -185,7 +185,28 @@ pub struct Started { /// Starts a player, as `helper::start` does, with `node` the render node of the compositor's /// card. `command` is the app's helper command, jailed or not, with its helper argument. /// With `debug`, the player sends libmpv's log as `log` messages. -pub fn start(mut command: Command, file: File, node: OwnedFd, size: (u32, u32), debug: bool) -> std::io::Result { +pub fn start(command: Command, file: File, node: OwnedFd, size: (u32, u32), debug: bool) -> std::io::Result { + start_with(command, Some(file), node, size, debug) +} + +/// Starts a player with no file yet, warming up: OpenGL, libmpv and its renderer start now, +/// so a file given later with `load` shows sooner. It says `hello` once it's ready. +pub fn start_warm(command: Command, node: OwnedFd, size: (u32, u32), debug: bool) -> std::io::Result { + start_with(command, None, node, size, debug) +} + +/// Gives a player started warm its file. +pub fn load(socket: &OwnedFd, file: &File) -> std::io::Result<()> { + send(socket, "load", &[file.as_raw_fd()]) +} + +fn start_with(mut command: Command, file: Option, node: OwnedFd, size: (u32, u32), debug: bool) -> std::io::Result { + let warm = file.is_none(); + // Descriptor 3 is always something: the file, or nothing to read for a warm start. + let file = match file { + Some(file) => file, + None => File::open("/dev/null")?, + }; let (ours, theirs) = socketpair()?; let high = |fd: RawFd| -> std::io::Result { // SAFETY: duplicating a descriptor we hold, taking ownership of a good result. @@ -198,6 +219,9 @@ pub fn start(mut command: Command, file: File, node: OwnedFd, size: (u32, u32), if debug { command.arg("debug"); } + if warm { + command.arg("warm"); + } command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); // SAFETY: only async-signal-safe calls. unsafe { @@ -238,6 +262,8 @@ struct Shared { held: [bool; SLOTS], size: (u32, u32), commands: Vec, + /// A file to play from a `load` message, for a player started warm. + file: Option, gone: bool, } @@ -262,7 +288,7 @@ impl Wake { None => self.ready.wait_while(shared, |s| !s.pending).unwrap_or_else(|e| e.into_inner()), }; shared.pending = false; - Shared { pending: false, held: shared.held, size: shared.size, commands: std::mem::take(&mut shared.commands), gone: shared.gone } + Shared { pending: false, held: shared.held, size: shared.size, commands: std::mem::take(&mut shared.commands), file: shared.file.take(), gone: shared.gone } } } @@ -274,7 +300,9 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp let (Some(w), Some(h)) = (parse(0), parse(1)) else { std::process::exit(EXIT_BAD_START) }; // `debug` after the size: libmpv's log goes to the app as `log` messages, for a player // that can't write a log file anywhere. - let debug = args.get(2).is_some_and(|a| a == "debug"); + let debug = args.get(2..).is_some_and(|rest| rest.iter().any(|a| a == "debug")); + // `warm`: no file yet; it comes with a `load` message. + let warm = args.get(2..).is_some_and(|rest| rest.iter().any(|a| a == "warm")); if options.render != RenderPath::Gpu { std::process::exit(EXIT_BAD_START); } @@ -336,7 +364,7 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp let reading = socket.try_clone().unwrap_or_else(|_| std::process::exit(EXIT_CANT_PLAY)); let for_reader = wake.clone(); let spawned = std::thread::Builder::new().name("app".into()).spawn(move || { - while let Ok(Some((text, _))) = receive(&reading) { + while let Ok(Some((text, mut fds))) = receive(&reading) { for_reader.with(|shared| { let mut words = text.split_ascii_whitespace(); match words.next() { @@ -351,6 +379,8 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp shared.size = (w.clamp(1, MAX_W), h.clamp(1, MAX_H)); } } + // Only the first: a second file before the first is loaded waits its turn. + Some("load") if fds.len() == 1 && shared.file.is_none() => shared.file = fds.pop(), _ => shared.commands.push(text.clone()), } }); @@ -360,9 +390,12 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp if spawned.is_err() { std::process::exit(EXIT_CANT_PLAY); } - if player.load_fd(FD_FILE).is_err() { + if !warm && player.load_fd(FD_FILE).is_err() { std::process::exit(EXIT_CANT_PLAY); } + // The file loaded last, open for as long as libmpv may read it, and the one before, which + // libmpv may still be closing. + let mut files: [Option; 2] = [None, None]; let mut targets: [Option; SLOTS] = [None, None, None]; let mut next = 0usize; @@ -383,6 +416,13 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp if woken.gone { std::process::exit(0); } + if let Some(file) = woken.file { + if player.load_fd(file.as_raw_fd()).is_err() { + say("cantplay"); + } + (hardware, fell_back) = (false, false); + files = [Some(file), files[0].take()]; + } for command in &woken.commands { let mut words = command.split_ascii_whitespace(); let number = |w: Option<&str>| w.and_then(|w| w.parse::().ok()).filter(|n| n.is_finite()); From 2e9495da29127471811757db745add576e41b522 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:10:56 -0700 Subject: [PATCH 18/25] GPU helper: make buffers with an iterator, for Rust 1.100's clippy CI's clippy (Rust 1.100) refuses the indexed loop over the slots as needless_range_loop. The loop now walks the held flags with enumerate. --- src/gpu_helper.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index dfdf232..00ebe29 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -461,10 +461,8 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp // them isn't in the way of showing it. if let Some(natural) = natural { let size = fit(natural, woken.size); - for slot in 0..SLOTS { - if !woken.held[slot] { - prepare(&gpu, &socket, &mut targets, slot, size); - } + for (slot, _) in woken.held.iter().enumerate().filter(|(_, held)| !**held) { + prepare(&gpu, &socket, &mut targets, slot, size); } } } From 237de759639185385f182a65a3f0bc1a2a06484f Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:24:02 -0700 Subject: [PATCH 19/25] GPU helper: fixes from the first review round of #2 - A second file loaded into a warm helper starts afresh. Its decoder is announced again, and its size and frames don't carry over from the last file; these reset when libmpv says the file is loaded, as the last file's frame can still be drawn until then. Hardware decoding comes back if the last file fell back to software. Checked by loading the clip twice into one warm helper: both said "decoder nvdec" and played every frame. - A `load` while another waits replaces it, so the newest file chosen plays. Before, it was dropped with no answer. - The seccomp filter also refuses the newer mount API (fsopen, fsconfig, fsmount, fspick, move_mount, open_tree, mount_setattr, open_tree_attr), which can make a procfs without `mount`. - An NVIDIA card whose driver can't be read is taken to run NVIDIA's own again; only nouveau decodes in software without the NVIDIA grants. --- src/gpu_helper.rs | 16 ++++++++++++---- src/jail.rs | 15 +++++++++++++-- src/options.rs | 8 +++++--- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index 00ebe29..66d1294 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -324,6 +324,8 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp // libmpv starts while the card's OpenGL does: the two take about 50 and 110 ms. let began = Instant::now(); let options = Options { start_paused: true, ..*options }; + // The hardware decoding asked for, to go back to after a file falls back to software. + let hwdec = options.pairs().into_iter().find(|(name, _)| *name == "hwdec").map_or("no", |(_, value)| value); let starting = std::thread::spawn(move || Player::new(&options)); let Ok(gpu) = Gpu::new(node) else { std::process::exit(EXIT_CANT_PLAY) }; let gpu_ready = began.elapsed(); @@ -379,8 +381,8 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp shared.size = (w.clamp(1, MAX_W), h.clamp(1, MAX_H)); } } - // Only the first: a second file before the first is loaded waits its turn. - Some("load") if fds.len() == 1 && shared.file.is_none() => shared.file = fds.pop(), + // The newest file chosen: one still waiting to be loaded is dropped for it. + Some("load") if fds.len() == 1 => shared.file = fds.pop(), _ => shared.commands.push(text.clone()), } }); @@ -417,10 +419,14 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp std::process::exit(0); } if let Some(file) = woken.file { + // Hardware decoding again, if the last file fell back to software. + if fell_back { + let _ = player.command(&[b"set", b"hwdec", hwdec.as_bytes()]); + } + fell_back = false; if player.load_fd(file.as_raw_fd()).is_err() { say("cantplay"); } - (hardware, fell_back) = (false, false); files = [Some(file), files[0].take()]; } for command in &woken.commands { @@ -449,7 +455,9 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp match event { Event::Shutdown => std::process::exit(0), Event::Loaded { video } => { - first_drawn = false; + // A new file: its own decoder, size and frames. Not reset at `load`, as the + // last file's frame can still be drawn until this one is loaded. + (first_drawn, told_decoder, hardware, natural, owed, drawn_size) = (false, false, false, None, false, None); if !video { say("novideo"); } diff --git a/src/jail.rs b/src/jail.rs index 173b3a1..a02d22c 100644 --- a/src/jail.rs +++ b/src/jail.rs @@ -116,8 +116,8 @@ pub fn lock_down_gpu_helper() -> bool { /// A seccomp filter that refuses, with `EPERM`, the system calls that reach into a process's /// memory (`ptrace`, `process_vm_readv`, `process_vm_writev`, `pidfd_getfd`, `kcmp`) and those -/// that make or join namespaces or mount (`mount`, `umount2`, `unshare`, `setns`, -/// `pivot_root`, and `clone` with any `CLONE_NEW*` flag). `clone3` gets `ENOSYS`, as under +/// that make or join namespaces or mount (`mount` and the newer mount API, `umount2`, +/// `unshare`, `setns`, `pivot_root`, and `clone` with any `CLONE_NEW*` flag). `clone3` gets `ENOSYS`, as under /// Flatpak: its flags are in memory, where seccomp can't look, and libc then falls back to /// `clone`. On x86-64, x32 system calls are refused too, as they'd get past the numbers here. /// Everything else is allowed: libmpv and the drivers need a lot. @@ -157,6 +157,17 @@ pub fn forbid_memory_writes() -> bool { libc::SYS_unshare, libc::SYS_setns, libc::SYS_pivot_root, + // The newer mount API, which makes a filesystem (a procfs too) with no `mount` call. + libc::SYS_fsopen, + libc::SYS_fsconfig, + libc::SYS_fsmount, + libc::SYS_fspick, + libc::SYS_move_mount, + libc::SYS_open_tree, + libc::SYS_mount_setattr, + // open_tree_attr (Linux 6.15), which libc doesn't name yet: the same number on x86-64 + // and aarch64, as every call from 424 on is. + 467, ]; let stmt = |code: u16, k: u32| libc::sock_filter { code, jt: 0, jf: 0, k }; let jump = |code: u16, k: u32, jt: usize, jf: usize| libc::sock_filter { code, jt: jt as u8, jf: jf as u8, k }; diff --git a/src/options.rs b/src/options.rs index 00b0ec3..7fe2c57 100644 --- a/src/options.rs +++ b/src/options.rs @@ -21,9 +21,10 @@ impl Vendor { /// From the PCI vendor number and the kernel driver's name in /sys. pub fn from_sys(pci_vendor: Option, driver: &str) -> Self { match (pci_vendor, driver) { - // NVIDIA's own driver only. nouveau has no NVDEC, and its jail mustn't get /proc. - (_, "nvidia") => Self::Nvidia, - (Some(0x10de), _) => Self::Other, + // nouveau has no NVDEC, and its jail mustn't get /proc. An NVIDIA card whose driver + // can't be read is taken to run NVIDIA's own. + (Some(0x10de), "nouveau") => Self::Other, + (Some(0x10de), _) | (_, "nvidia") => Self::Nvidia, (Some(0x1002), _) | (_, "amdgpu" | "radeon") => Self::Amd, (Some(0x8086), _) | (_, "i915" | "xe") => Self::Intel, (_, "asahi") => Self::Apple, @@ -226,6 +227,7 @@ mod tests { } assert_eq!(Vendor::from_sys(Some(0x10de), "nvidia"), Vendor::Nvidia); assert_eq!(Vendor::from_sys(Some(0x10de), "nouveau"), Vendor::Other, "no NVDEC, no /proc"); + assert_eq!(Vendor::from_sys(Some(0x10de), ""), Vendor::Nvidia, "driver not readable"); assert_eq!(Vendor::from_sys(Some(0x1002), "amdgpu"), Vendor::Amd); assert_eq!(Vendor::from_sys(Some(0x8086), "i915"), Vendor::Intel); assert_eq!(Vendor::from_sys(None, "asahi"), Vendor::Apple); From 7f6a58d42714aff1dc3f7a6b95489bcfc63daf70 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:27:36 -0700 Subject: [PATCH 20/25] GPU helper: draw the current frame when playback starts, so covers show About half of songs with cover art never started: no frame was drawn, so the helper never unpaused. A cover is one frame, queued as soon as the video is set up. The helper's `VideoChanged` handling asks libmpv for the size, which waits on libmpv's core, while the core waits for this thread to draw the frame. libmpv gives up after 200 ms, keeps the frame on screen, and stops flagging it as new, so the draw was skipped and nothing woke the loop again. When playback starts or restarts, the helper now draws the current frame whatever the flag says. With cover art on (in a local test build of gpu-play, jailed, on NVIDIA), a FLAC with a 600x600 PNG cover showed its frame in 2 of 10 runs before and 12 of 12 after. 1080p video plays as before. --- src/gpu_helper.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index 66d1294..4ee3243 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -499,7 +499,17 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp say(&format!("log timing: finishing a frame took {:.2} ms on average over {} frames", finishing.0.as_secs_f64() * 1000.0 / f64::from(finishing.1), finishing.1)); } } - Event::Restarted => urgent = true, + // libmpv gives up waiting for a frame to be drawn after a while (200 ms) and + // stops flagging it as new, though it's still the one on screen. That happens + // when this thread is held up in a call that waits on libmpv's core while the + // core waits on this thread: a cover's one frame comes at once, while + // `VideoChanged` asks for the size. Once playback (re)starts, the current + // frame is drawn whatever the flag says, so a lost wake-up can't leave the + // picture undrawn and the player paused for good. + Event::Restarted => { + urgent = true; + owed |= natural.is_some(); + } } } // Drawn before the state is reported, so the last frame reaches the app before it From a8024d8d35d57cbad4c830f55e4bf5af85ae1e85 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:33:53 -0700 Subject: [PATCH 21/25] Player: watch the picture's size, decoder and dropped frames The helpers read the picture's size, and the GPU helper its decoder and dropped-frame counts, with blocking gets on their render thread. A get waits on libmpv's core, and the core can be waiting in the video output for that same thread to draw. libmpv gives up after 200 ms and drops the frame's "new" flag. A song's cover lost its only frame that way, and the same could happen to a video that changes size mid-stream. The player now watches dwidth, dheight, hwdec-current, frame-drop-count and vo-delayed-frame-count, as new events: Width, Height, Decoder, DecoderDrops and LateFrames. The CPU and GPU helpers use them and no longer ask for them. The GPU helper settles the size once per batch of events, as width and height arrive separately, so no buffers are made for a half-changed size. It names the decoder once a frame is drawn and libmpv has said which decoder it is. The draw on every playback start (7f6a58d) stays as a second guard. Checked on the desktop (NVIDIA, jailed): - A FLAC with a cover (cover art on, in a local test build of gpu-play) showed its frame in 12 of 12 runs. The stall before its first frame went from about 400 ms to about 200 ms. - A clip that changes from 640x360 to 1280x720 mid-stream played all 120 frames. It makes no buffers at an in-between size. - The 1080p clip's first frame is unchanged (652 to 681 ms). --- src/ffi.rs | 1 + src/gpu_helper.rs | 57 ++++++++++++++++++++++++++++++----------------- src/helper.rs | 14 ++++++++++-- src/player.rs | 41 ++++++++++++++++++++++++++++++++++ 4 files changed, 91 insertions(+), 22 deletions(-) diff --git a/src/ffi.rs b/src/ffi.rs index 3935fdb..58da4b0 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -66,6 +66,7 @@ pub struct OpenGlDrmParamsV2 { } pub const FORMAT_NONE: c_int = 0; +pub const FORMAT_STRING: c_int = 1; pub const FORMAT_FLAG: c_int = 3; pub const FORMAT_DOUBLE: c_int = 5; diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index 4ee3243..06878f8 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -405,6 +405,12 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp let (mut reported, mut last_report) = (String::new(), Instant::now() - REPORT_EVERY); let mut dropped_reported = String::new(); let mut natural: Option<(f64, f64)> = None; + // The picture's size, decoder and dropped frames, as libmpv reports them. Never asked for + // on this thread: asking waits on libmpv's core, which may be waiting for this thread to + // draw, and then a frame is lost (a cover's only one, for a start). + let mut shown_size = (0.0, 0.0); + let mut decoder: Option<&'static str> = None; + let (mut decoder_drops, mut late_frames) = (0u64, 0u64); let mut first_drawn = false; let mut wanted_paused = true; let mut told_decoder = false; @@ -457,23 +463,19 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp Event::Loaded { video } => { // A new file: its own decoder, size and frames. Not reset at `load`, as the // last file's frame can still be drawn until this one is loaded. - (first_drawn, told_decoder, hardware, natural, owed, drawn_size) = (false, false, false, None, false, None); + (first_drawn, told_decoder, hardware, owed, drawn_size) = (false, false, false, false, None); if !video { say("novideo"); } } Event::Failed => say("cantplay"), - Event::VideoChanged => { - natural = player.double(c"dwidth").zip(player.double(c"dheight")).filter(|n| n.0 > 0.0 && n.1 > 0.0); - // The buffers are made now, before the first frame is decoded, so making - // them isn't in the way of showing it. - if let Some(natural) = natural { - let size = fit(natural, woken.size); - for (slot, _) in woken.held.iter().enumerate().filter(|(_, held)| !**held) { - prepare(&gpu, &socket, &mut targets, slot, size); - } - } - } + Event::VideoChanged => {} + // Width and height come one at a time: the size is settled after the batch. + Event::Width(w) => shown_size.0 = w, + Event::Height(h) => shown_size.1 = h, + Event::Decoder(name) => decoder = name, + Event::DecoderDrops(n) => decoder_drops = n, + Event::LateFrames(n) => late_frames = n, Event::Position(at) => state.position = at, Event::Duration(d) => (state.duration, urgent) = (d, true), Event::Paused(p) => (state.paused, urgent) = (p, true), @@ -484,7 +486,7 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp // error, so this does: the decoder starts again in software where the picture // stopped, and the video plays on. Event::Ended(true) if falls_back(hardware && !fell_back, state.position, state.duration) => { - (hardware, fell_back, told_decoder) = (false, true, false); + (hardware, fell_back, told_decoder, decoder) = (false, true, false, None); let _ = player.command(&[b"set", b"hwdec", b"no"]); if !wanted_paused { let _ = player.set_paused(false); @@ -512,6 +514,18 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp } } } + let now = Some(shown_size).filter(|n| n.0 > 0.0 && n.1 > 0.0); + if now != natural { + natural = now; + // The buffers are made now, before the first frame is drawn, so making them isn't + // in the way of showing it. + if let Some(natural) = natural { + let size = fit(natural, woken.size); + for (slot, _) in woken.held.iter().enumerate().filter(|(_, held)| !**held) { + prepare(&gpu, &socket, &mut targets, slot, size); + } + } + } // Drawn before the state is reported, so the last frame reaches the app before it // hears the video has ended. 'draw: { @@ -546,19 +560,22 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp let _ = player.set_paused(false); } } - if !told_decoder { - told_decoder = true; - let current = player.get(c"hwdec-current").filter(|d| !d.is_empty() && d != "no"); - hardware = current.is_some(); - say(&format!("decoder {}", current.as_deref().unwrap_or("software"))); - } next = (slot + 1) % SLOTS; } } + // Once a frame is on screen and libmpv has said how it's decoding. + if first_drawn + && !told_decoder + && let Some(name) = decoder + { + told_decoder = true; + hardware = name != "software"; + say(&format!("decoder {name}")); + } let line = state.line(); if line != reported && (urgent || last_report.elapsed() >= REPORT_EVERY) { say(&line); - let dropped = format!("dropped {} {}", player.get(c"frame-drop-count").unwrap_or_default(), player.get(c"vo-delayed-frame-count").unwrap_or_default()); + let dropped = format!("dropped {decoder_drops} {late_frames}"); if dropped != dropped_reported && parse_said(&dropped).is_some() { say(&dropped); dropped_reported = dropped; diff --git a/src/helper.rs b/src/helper.rs index 7b2585b..6511c0d 100644 --- a/src/helper.rs +++ b/src/helper.rs @@ -598,6 +598,9 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp let mut last_size = (0, 0); let mut have_video = false; let mut natural: Option<(f64, f64)> = None; + // The picture's size as libmpv reports it, never asked for: asking waits on libmpv's core, + // which may be waiting for this thread to draw. + let mut shown_size = (0.0, 0.0); loop { // Waits with no timer unless a position change is waiting to be reported. let line = state.line(); @@ -619,10 +622,17 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp } } Event::Failed => said("cantplay"), - Event::VideoChanged => { - natural = player.double(c"dwidth").zip(player.double(c"dheight")).filter(|n| n.0 > 0.0 && n.1 > 0.0); + Event::Width(w) => { + shown_size.0 = w; + natural = Some(shown_size).filter(|n| n.0 > 0.0 && n.1 > 0.0); last_size = (0, 0); } + Event::Height(h) => { + shown_size.1 = h; + natural = Some(shown_size).filter(|n| n.0 > 0.0 && n.1 > 0.0); + last_size = (0, 0); + } + Event::VideoChanged | Event::Decoder(_) | Event::DecoderDrops(_) | Event::LateFrames(_) => {} Event::Position(at) => state.position = at, Event::Duration(d) => (state.duration, urgent) = (d, true), Event::Paused(p) => (state.paused, urgent) = (p, true), diff --git a/src/player.rs b/src/player.rs index 75eca9a..e3b1d06 100644 --- a/src/player.rs +++ b/src/player.rs @@ -69,6 +69,17 @@ pub enum Event { VideoChanged, /// Playing again after loading or a seek. Restarted, + /// The picture's width and height as shown, each on its own, or 0 while there's none. + /// Watched rather than asked for: asking waits on libmpv's core, which a render thread + /// mustn't do while the core may be waiting for it to draw. + Width(f64), + Height(f64), + /// How the video is being decoded: a hardware decoder's name, such as `nvdec` or `vaapi`, + /// `software`, or `None` while nothing is decoding. + Decoder(Option<&'static str>), + /// Frames dropped by the decoder, and frames the video output showed late. + DecoderDrops(u64), + LateFrames(u64), /// The player is shutting down. Shutdown, } @@ -81,8 +92,22 @@ const WATCHED: &[(&CStr, c_int)] = &[ (c"volume", ffi::FORMAT_DOUBLE), (c"mute", ffi::FORMAT_FLAG), (c"eof-reached", ffi::FORMAT_FLAG), + (c"dwidth", ffi::FORMAT_DOUBLE), + (c"dheight", ffi::FORMAT_DOUBLE), + (c"hwdec-current", ffi::FORMAT_STRING), + (c"frame-drop-count", ffi::FORMAT_DOUBLE), + (c"vo-delayed-frame-count", ffi::FORMAT_DOUBLE), ]; +/// libmpv's decoder names, as names that last: one not listed is still hardware decoding. +fn decoder_name(name: &str) -> &'static str { + const KNOWN: &[&str] = &["nvdec", "nvdec-copy", "cuda", "cuda-copy", "vaapi", "vaapi-copy", "v4l2m2m", "v4l2m2m-copy", "vulkan", "vulkan-copy", "drm", "drm-copy", "vdpau", "vdpau-copy"]; + match name { + "" | "no" => "software", + _ => KNOWN.iter().find(|known| **known == name).copied().unwrap_or("hardware"), + } +} + type Wakeup = Box; type LogSink = Box; @@ -351,6 +376,11 @@ impl Player { 0 => Some(Event::Position(0.0)), 1 => Some(Event::Duration(0.0)), 5 => Some(Event::Ended(false)), + 6 => Some(Event::Width(0.0)), + 7 => Some(Event::Height(0.0)), + 8 => Some(Event::Decoder(None)), + 9 => Some(Event::DecoderDrops(0)), + 10 => Some(Event::LateFrames(0)), _ => None, }; } @@ -358,6 +388,13 @@ impl Player { if property.format != *format { return None; } + if *format == ffi::FORMAT_STRING { + // SAFETY: a string property's data points at a terminated string, libmpv's + // until the next wait. + let text = unsafe { *(property.data as *const *const c_char) }; + let name = if text.is_null() { String::new() } else { unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned() }; + return (index == 8).then(|| Event::Decoder(Some(decoder_name(&name)))); + } // SAFETY: the format says what the data is, and it was checked above. let (double, flag) = unsafe { match *format { @@ -373,6 +410,10 @@ impl Player { 3 => number().map(|v| Event::Volume(v.min(100.0))), 4 => Some(Event::Muted(flag)), 5 => Some(Event::Ended(flag)), + 6 => number().map(Event::Width), + 7 => number().map(Event::Height), + 9 => number().map(|n| Event::DecoderDrops(n as u64)), + 10 => number().map(|n| Event::LateFrames(n as u64)), _ => None, } } From 893785308f339d85f2228d7e45a286d033e886b3 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:48:59 -0700 Subject: [PATCH 22/25] Player: requests and reads that never wait on libmpv's core A thread that draws for libmpv can't wait on libmpv's core: the core may be waiting in the video output for that thread to draw. libmpv then gives up after 200 ms and drops the frame's "new" flag. Every start had that stall, and a cover could lose its only frame to it. - Requests are now async. command, load, load_fd, set_paused, play, the seeks, set_volume and set_muted return once libmpv has the request, through mpv_command_async. A request libmpv turns down comes back as Event::Refused(Request), where Request is Command, Load, Pause, Seek, Volume or Mute. The helpers say `cantplay` for a refused load. - play() reads the end from the last watched eof-reached, not with a get. - Player::ask(name, id) reads a property as text without waiting. Event::Answered(id) says the answer is ready, and Player::answer(id) takes it as an Option. Event stays Copy. - Loaded { video } keeps its shape. It now comes when libmpv answers an async read of `vid`, a moment after the file is loaded, so it can arrive after the first Width and Height. - The GPU helper resets each file's decoder, frames and fallback when it asks libmpv to load the file, no longer on Loaded. - libmpv reports the picture's size only once its core is free, and the core waits for the first frame to be drawn. So while the size isn't known yet, the GPU helper draws a new frame at the window's size (libmpv keeps the picture's shape, with borders), then again at the picture's own size once that arrives. - Fixes from review round 2: - A restart owes a draw once the size is settled in the same batch, not before it. - The CPU helper settles the size once per batch too. Measured on the desktop (NVIDIA, jailed). The "render() not being called or stuck" stall is gone from every run, and no first frame is dropped. - First frame, cold: 1080p H.264 472-530 ms (was 652-714), 4K HEVC 493-537 ms (was 669-754). - First frame, warm: 72 ms at 1080p. - A FLAC with a cover: shown in 12 of 12 runs, first frame 446-509 ms (was 651-787). - Pause and seek during playback are as before: pause 0-67 ms, seek 63-100 ms to the reported state. - A clip that changes size mid-stream plays every frame. --- src/ffi.rs | 9 +++ src/gpu_helper.rs | 32 ++++++---- src/helper.rs | 24 ++++--- src/player.rs | 155 ++++++++++++++++++++++++++++++++++++---------- 4 files changed, 163 insertions(+), 57 deletions(-) diff --git a/src/ffi.rs b/src/ffi.rs index 58da4b0..6a6799d 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -72,6 +72,9 @@ pub const FORMAT_DOUBLE: c_int = 5; pub const EVENT_NONE: c_int = 0; pub const EVENT_SHUTDOWN: c_int = 1; +pub const EVENT_GET_PROPERTY_REPLY: c_int = 3; +pub const EVENT_SET_PROPERTY_REPLY: c_int = 4; +pub const EVENT_COMMAND_REPLY: c_int = 5; pub const EVENT_END_FILE: c_int = 7; pub const EVENT_FILE_LOADED: c_int = 8; pub const EVENT_VIDEO_RECONFIG: c_int = 17; @@ -136,6 +139,9 @@ pub struct Library { pub error_string: unsafe extern "C" fn(c_int) -> *const c_char, pub set_option_string: unsafe extern "C" fn(Handle, *const c_char, *const c_char) -> c_int, pub command: unsafe extern "C" fn(Handle, *mut *const c_char) -> c_int, + pub command_async: unsafe extern "C" fn(Handle, u64, *mut *const c_char) -> c_int, + pub set_property_async: unsafe extern "C" fn(Handle, u64, *const c_char, c_int, *mut c_void) -> c_int, + pub get_property_async: unsafe extern "C" fn(Handle, u64, *const c_char, c_int) -> c_int, pub set_property: unsafe extern "C" fn(Handle, *const c_char, c_int, *mut c_void) -> c_int, pub get_property: unsafe extern "C" fn(Handle, *const c_char, c_int, *mut c_void) -> c_int, pub get_property_string: unsafe extern "C" fn(Handle, *const c_char) -> *mut c_char, @@ -198,6 +204,9 @@ impl Library { error_string: sym!("mpv_error_string"), set_option_string: sym!("mpv_set_option_string"), command: sym!("mpv_command"), + command_async: sym!("mpv_command_async"), + set_property_async: sym!("mpv_set_property_async"), + get_property_async: sym!("mpv_get_property_async"), set_property: sym!("mpv_set_property"), get_property: sym!("mpv_get_property"), get_property_string: sym!("mpv_get_property_string"), diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index 06878f8..bacb46e 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -23,7 +23,7 @@ use std::time::{Duration, Instant}; use crate::gpu::{GL_RGBA8, Gpu, Target}; use crate::helper::{EXIT_BAD_START, EXIT_CANT_PLAY, EXIT_NO_MPV, PlayState}; use crate::options::{Options, RenderPath}; -use crate::player::{Event, Player}; +use crate::player::{Event, Player, Request}; use crate::render::{GlRender, Native}; pub const FD_FILE: c_int = 3; @@ -429,7 +429,9 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp if fell_back { let _ = player.command(&[b"set", b"hwdec", hwdec.as_bytes()]); } - fell_back = false; + // A new file: its own decoder, frames and fallback. The last file's frame may still + // be drawn before this one is loaded; that only starts this one a moment early. + (fell_back, first_drawn, told_decoder, hardware, decoder, owed, drawn_size) = (false, false, false, false, None, false, None); if player.load_fd(file.as_raw_fd()).is_err() { say("cantplay"); } @@ -456,19 +458,17 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp _ => Ok(()), }; } - let mut urgent = false; + let (mut urgent, mut restarted) = (false, false); while let Some(event) = player.next_event() { match event { Event::Shutdown => std::process::exit(0), Event::Loaded { video } => { - // A new file: its own decoder, size and frames. Not reset at `load`, as the - // last file's frame can still be drawn until this one is loaded. - (first_drawn, told_decoder, hardware, owed, drawn_size) = (false, false, false, false, None); if !video { say("novideo"); } } - Event::Failed => say("cantplay"), + Event::Failed | Event::Refused(Request::Load) => say("cantplay"), + Event::Refused(_) | Event::Answered(_) => {} Event::VideoChanged => {} // Width and height come one at a time: the size is settled after the batch. Event::Width(w) => shown_size.0 = w, @@ -508,10 +508,7 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp // `VideoChanged` asks for the size. Once playback (re)starts, the current // frame is drawn whatever the flag says, so a lost wake-up can't leave the // picture undrawn and the player paused for good. - Event::Restarted => { - urgent = true; - owed |= natural.is_some(); - } + Event::Restarted => (urgent, restarted) = (true, true), } } let now = Some(shown_size).filter(|n| n.0 > 0.0 && n.1 > 0.0); @@ -526,12 +523,21 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp } } } + // After the size is settled, which may have come in the same batch. + owed |= restarted && natural.is_some(); // Drawn before the state is reported, so the last frame reaches the app before it // hears the video has ended. 'draw: { owed |= render.new_frame(); - let Some(natural) = natural else { break 'draw }; - let (fw, fh) = fit(natural, woken.size); + // libmpv tells the picture's size only once its core is free, and the core waits + // for a new frame to be drawn: without the size yet, the frame is drawn at the + // window's size (libmpv keeps its shape, with borders), and again at its own + // size once that comes. + let (fw, fh) = match natural { + Some(natural) => fit(natural, woken.size), + None if owed => woken.size, + None => break 'draw, + }; // A new size draws the frame again, paused or stopped too. let resized = drawn_size.is_some_and(|size| size != (fw, fh)); if !owed && !resized { diff --git a/src/helper.rs b/src/helper.rs index 6511c0d..2086ad6 100644 --- a/src/helper.rs +++ b/src/helper.rs @@ -25,7 +25,7 @@ use rustix::mm::{MapFlags, ProtFlags, mmap, munmap}; use rustix::pipe::{PipeFlags, pipe_with}; use crate::options::{Options, RenderPath}; -use crate::player::{Event, Player}; +use crate::player::{Event, Player, Request}; use crate::render::{SwFormat, SwRender}; /// How a player ended, besides the codes the app's own sandbox uses. @@ -621,18 +621,11 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp said("novideo"); } } - Event::Failed => said("cantplay"), - Event::Width(w) => { - shown_size.0 = w; - natural = Some(shown_size).filter(|n| n.0 > 0.0 && n.1 > 0.0); - last_size = (0, 0); - } - Event::Height(h) => { - shown_size.1 = h; - natural = Some(shown_size).filter(|n| n.0 > 0.0 && n.1 > 0.0); - last_size = (0, 0); - } - Event::VideoChanged | Event::Decoder(_) | Event::DecoderDrops(_) | Event::LateFrames(_) => {} + Event::Failed | Event::Refused(Request::Load) => said("cantplay"), + // Width and height come one at a time: the size is settled after the batch. + Event::Width(w) => shown_size.0 = w, + Event::Height(h) => shown_size.1 = h, + Event::VideoChanged | Event::Decoder(_) | Event::DecoderDrops(_) | Event::LateFrames(_) | Event::Refused(_) | Event::Answered(_) => {} Event::Position(at) => state.position = at, Event::Duration(d) => (state.duration, urgent) = (d, true), Event::Paused(p) => (state.paused, urgent) = (p, true), @@ -649,6 +642,11 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp reported = line; last_report = Instant::now(); } + let now = Some(shown_size).filter(|n| n.0 > 0.0 && n.1 > 0.0); + if now != natural { + natural = now; + last_size = (0, 0); + } let new_frame = render.new_frame(); let wanted = (size.0.load(Ordering::Relaxed), size.1.load(Ordering::Relaxed)); let Some(natural) = natural.filter(|_| have_video) else { continue }; diff --git a/src/player.rs b/src/player.rs index e3b1d06..bff8235 100644 --- a/src/player.rs +++ b/src/player.rs @@ -1,9 +1,11 @@ //! A libmpv player: setting it up, telling it what to do, and hearing what it does. +use std::collections::HashMap; use std::ffi::{CStr, CString, c_char, c_int, c_void}; use std::os::fd::RawFd; use std::os::unix::ffi::OsStrExt; use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -80,10 +82,37 @@ pub enum Event { /// Frames dropped by the decoder, and frames the video output showed late. DecoderDrops(u64), LateFrames(u64), + /// libmpv turned down something it was asked to do. Requests return before libmpv has + /// done them, so a refusal comes here. + Refused(Request), + /// The answer to `Player::ask` with this id is ready: take it with `Player::answer`. + Answered(u32), /// The player is shutting down. Shutdown, } +/// What a refused request was. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Request { + Command, + Load, + Pause, + Seek, + Volume, + Mute, +} + +impl Request { + const ALL: [Request; 6] = [Request::Command, Request::Load, Request::Pause, Request::Seek, Request::Volume, Request::Mute]; +} + +/// The number libmpv hands back with a reply: the watched properties use 1 and up; a request +/// is `REQUEST` plus its kind, and an `ask` is `ASK` plus its id. +const REQUEST: u64 = 1 << 32; +const ASK: u64 = 2 << 32; +/// The internal ask for `vid`, which says whether a loaded file has a picture. +const ASK_VIDEO: u64 = 3 << 32; + /// The properties every app watches, by the number libmpv hands back with each change. const WATCHED: &[(&CStr, c_int)] = &[ (c"time-pos", ffi::FORMAT_DOUBLE), @@ -127,6 +156,10 @@ pub(crate) struct Core { /// Where libmpv's own log lines go, once asked for: for diagnosing a player that can't /// write a log file anywhere, such as a jailed one. log: Mutex>, + /// Answers to `ask`, until they're taken. + answers: Mutex>>, + /// Whether the file has stopped on its last frame, as last watched, for `play`. + ended: AtomicBool, } // SAFETY: libmpv's client API may be called from any thread, and the one call that mustn't @@ -160,7 +193,7 @@ impl Player { if handle.is_null() { return Err(Error::Mpv { doing: "starting libmpv".into(), reason: "out of memory".into() }); } - let core = Core { lib, handle, events: Mutex::new(()), wakeups: Mutex::new(Vec::new()), log: Mutex::new(None) }; + let core = Core { lib, handle, events: Mutex::new(()), wakeups: Mutex::new(Vec::new()), log: Mutex::new(None), answers: Mutex::new(HashMap::new()), ended: AtomicBool::new(false) }; for (name, value) in options.pairs() { core.set_option(name, value)?; } @@ -188,11 +221,20 @@ impl Player { /// Runs a command, such as `["seek", "5", "relative"]`. Each word is passed as it is, /// so a file name needs no quoting. + /// + /// Requests (this, loading, pause, seeking, volume and mute) return once libmpv has them, + /// without waiting for libmpv's core: a thread that draws can't wait on the core, which + /// may be waiting for it to draw. One libmpv then turns down comes as `Event::Refused`. pub fn command(&self, words: &[&[u8]]) -> Result<(), Error> { + self.request(Request::Command, words) + } + + fn request(&self, kind: Request, words: &[&[u8]]) -> Result<(), Error> { let owned = words.iter().map(|w| CString::new(*w).map_err(|_| Error::Nul)).collect::, _>>()?; let mut pointers: Vec<*const c_char> = owned.iter().map(|w| w.as_ptr()).chain([std::ptr::null()]).collect(); - // SAFETY: a live handle and a null-terminated list of strings that outlive the call. - let code = unsafe { (self.core.lib.command)(self.core.handle, pointers.as_mut_ptr()) }; + // SAFETY: a live handle and a null-terminated list of strings that outlive the call; + // libmpv copies them. + let code = unsafe { (self.core.lib.command_async)(self.core.handle, REQUEST + kind as u64, pointers.as_mut_ptr()) }; if code < 0 { let doing = words.iter().map(|w| String::from_utf8_lossy(w)).collect::>().join(" "); return Err(Error::Mpv { doing, reason: self.core.lib.describe(code) }); @@ -200,53 +242,71 @@ impl Player { Ok(()) } + /// Asks for a property as text without waiting: `Event::Answered(id)` says the answer is + /// ready, and `answer(id)` takes it. For a thread that draws, which mustn't wait on + /// libmpv's core. + pub fn ask(&self, name: &CStr, id: u32) -> Result<(), Error> { + // SAFETY: a live handle and a terminated name; libmpv copies it. + let code = unsafe { (self.core.lib.get_property_async)(self.core.handle, ASK + u64::from(id), name.as_ptr(), ffi::FORMAT_STRING) }; + self.check(code, name) + } + + /// The answer to `ask` with `id`, once `Event::Answered(id)` has come: `None` if the + /// property wasn't available, or it was already taken. + pub fn answer(&self, id: u32) -> Option { + self.core.answers.lock().unwrap_or_else(|e| e.into_inner()).remove(&id).flatten() + } + /// Opens a file, in place of whatever was playing. Always as a file: a relative path /// such as `http://host/x` or `edl://...` is a file of that name in the current folder, /// not something for libmpv to fetch or build. pub fn load(&self, path: &Path) -> Result<(), Error> { - self.command(&[b"loadfile", as_file(path).as_os_str().as_bytes()]) + self.request(Request::Load, &[b"loadfile", as_file(path).as_os_str().as_bytes()]) } /// Opens a file this process has open, for a player that can't see the file system. pub fn load_fd(&self, fd: RawFd) -> Result<(), Error> { - self.command(&[b"loadfile", format!("fd://{fd}").as_bytes()]) + self.request(Request::Load, &[b"loadfile", format!("fd://{fd}").as_bytes()]) } pub fn set_paused(&self, paused: bool) -> Result<(), Error> { - self.set_flag(c"pause", paused) + self.request(Request::Pause, &[b"set", b"pause", if paused { b"yes" } else { b"no" }]) } /// Plays, from the start if it had stopped on its last frame: what a play button does. pub fn play(&self) -> Result<(), Error> { - if self.flag(c"eof-reached") == Some(true) { - self.command(&[b"seek", b"0", b"absolute"])?; + // As last watched: asking would wait on the core. Requests run in order, so the + // seek comes before the unpause. + if self.core.ended.load(Ordering::Relaxed) { + self.request(Request::Seek, &[b"seek", b"0", b"absolute"])?; } self.set_paused(false) } pub fn seek_by(&self, seconds: f64) -> Result<(), Error> { - self.command(&[b"seek", format!("{seconds:.3}").as_bytes(), b"relative"]) + self.request(Request::Seek, &[b"seek", format!("{seconds:.3}").as_bytes(), b"relative"]) } pub fn seek_to(&self, seconds: f64) -> Result<(), Error> { - self.command(&[b"seek", format!("{:.3}", seconds.max(0.0)).as_bytes(), b"absolute"]) + self.request(Request::Seek, &[b"seek", format!("{:.3}", seconds.max(0.0)).as_bytes(), b"absolute"]) } /// To a share of the way through, from 0 to 1. pub fn seek_to_fraction(&self, fraction: f64) -> Result<(), Error> { - self.command(&[b"seek", format!("{:.3}", fraction.clamp(0.0, 1.0) * 100.0).as_bytes(), b"absolute-percent"]) + self.request(Request::Seek, &[b"seek", format!("{:.3}", fraction.clamp(0.0, 1.0) * 100.0).as_bytes(), b"absolute-percent"]) } /// 0 to 100. pub fn set_volume(&self, volume: f64) -> Result<(), Error> { - self.set_double(c"volume", volume.clamp(0.0, 100.0)) + self.request(Request::Volume, &[b"set", b"volume", format!("{:.3}", volume.clamp(0.0, 100.0)).as_bytes()]) } pub fn set_muted(&self, muted: bool) -> Result<(), Error> { - self.set_flag(c"mute", muted) + self.request(Request::Mute, &[b"set", b"mute", if muted { b"yes" } else { b"no" }]) } - /// A property as text, or `None` if it isn't available now. + /// A property as text, or `None` if it isn't available now. This waits on libmpv's core: + /// a thread that draws uses `ask` instead. pub fn get(&self, name: &CStr) -> Option { // SAFETY: a live handle and a terminated name. libmpv's string is copied, then freed // as it asks. @@ -275,22 +335,9 @@ impl Player { (code >= 0).then_some(value != 0) } - fn set_flag(&self, name: &CStr, value: bool) -> Result<(), Error> { - let mut value = c_int::from(value); - // SAFETY: a live handle, and an int for a flag. - let code = unsafe { (self.core.lib.set_property)(self.core.handle, name.as_ptr(), ffi::FORMAT_FLAG, &mut value as *mut c_int as *mut c_void) }; - self.check(code, name) - } - - fn set_double(&self, name: &CStr, mut value: f64) -> Result<(), Error> { - // SAFETY: a live handle, and a double for a double. - let code = unsafe { (self.core.lib.set_property)(self.core.handle, name.as_ptr(), ffi::FORMAT_DOUBLE, &mut value as *mut f64 as *mut c_void) }; - self.check(code, name) - } - fn check(&self, code: c_int, name: &CStr) -> Result<(), Error> { if code < 0 { - return Err(Error::Mpv { doing: format!("setting {}", name.to_string_lossy()), reason: self.core.lib.describe(code) }); + return Err(Error::Mpv { doing: format!("asking for {}", name.to_string_lossy()), reason: self.core.lib.describe(code) }); } Ok(()) } @@ -345,7 +392,27 @@ impl Player { unsafe fn translate(&self, event: &ffi::Event) -> Option { match event.id { ffi::EVENT_SHUTDOWN => Some(Event::Shutdown), - ffi::EVENT_FILE_LOADED => Some(Event::Loaded { video: self.get(c"vid").is_some_and(|v| v != "no") }), + // Whether it has a picture is asked for without waiting, and `Loaded` comes with + // the answer. + ffi::EVENT_FILE_LOADED => { + // SAFETY: a live handle and a terminated name. + let code = unsafe { (self.core.lib.get_property_async)(self.core.handle, ASK_VIDEO, c"vid".as_ptr(), ffi::FORMAT_STRING) }; + (code < 0).then_some(Event::Loaded { video: false }) + } + ffi::EVENT_GET_PROPERTY_REPLY => { + // SAFETY: a reply's data is a property struct, as the caller says. + let text = unsafe { reply_text(event) }; + if event.userdata == ASK_VIDEO { + return Some(Event::Loaded { video: text.is_some_and(|v| v != "no") }); + } + let id = u32::try_from(event.userdata.checked_sub(ASK)?).ok()?; + self.core.answers.lock().unwrap_or_else(|e| e.into_inner()).insert(id, text); + Some(Event::Answered(id)) + } + ffi::EVENT_COMMAND_REPLY | ffi::EVENT_SET_PROPERTY_REPLY => { + let kind = event.userdata.checked_sub(REQUEST).and_then(|k| Request::ALL.get(usize::try_from(k).ok()?).copied())?; + (event.error < 0).then_some(Event::Refused(kind)) + } ffi::EVENT_END_FILE => { // SAFETY: an end-file event's data is an end-file struct, as the caller says. let end = unsafe { &*(event.data as *const ffi::EventEndFile) }; @@ -375,7 +442,10 @@ impl Player { return match index { 0 => Some(Event::Position(0.0)), 1 => Some(Event::Duration(0.0)), - 5 => Some(Event::Ended(false)), + 5 => { + self.core.ended.store(false, Ordering::Relaxed); + Some(Event::Ended(false)) + } 6 => Some(Event::Width(0.0)), 7 => Some(Event::Height(0.0)), 8 => Some(Event::Decoder(None)), @@ -409,7 +479,10 @@ impl Player { 2 => Some(Event::Paused(flag)), 3 => number().map(|v| Event::Volume(v.min(100.0))), 4 => Some(Event::Muted(flag)), - 5 => Some(Event::Ended(flag)), + 5 => { + self.core.ended.store(flag, Ordering::Relaxed); + Some(Event::Ended(flag)) + } 6 => number().map(Event::Width), 7 => number().map(Event::Height), 9 => number().map(|n| Event::DecoderDrops(n as u64)), @@ -422,6 +495,26 @@ impl Player { } } +/// A property reply's value as text: `None` if it failed or the property wasn't available. +/// +/// # Safety +/// `event` must be a get-property reply libmpv just returned, read before the next wait. +unsafe fn reply_text(event: &ffi::Event) -> Option { + if event.error < 0 || event.data.is_null() { + return None; + } + // SAFETY: a reply's data is a property struct; a string's data points at a pointer to a + // terminated string, libmpv's until the next wait. It's copied here. + unsafe { + let property = &*(event.data as *const ffi::EventProperty); + if property.format != ffi::FORMAT_STRING || property.data.is_null() { + return None; + } + let text = *(property.data as *const *const c_char); + (!text.is_null()).then(|| CStr::from_ptr(text).to_string_lossy().into_owned()) + } +} + /// `path`, starting with `/` or `./`, which libmpv only ever reads as a file. fn as_file(path: &Path) -> std::borrow::Cow<'_, Path> { if path.is_absolute() { std::borrow::Cow::Borrowed(path) } else { std::borrow::Cow::Owned(Path::new(".").join(path)) } From df646d283846188cf907bf17a6daf5bbd07c54b9 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:51:13 -0700 Subject: [PATCH 23/25] Player: answers belong to the file they were asked about Answers to `ask` waited in a map until taken, with nothing to stop the map growing, or to stop a late answer about the last file being taken for the next one under a reused id. Each load now starts a new generation and drops untaken answers. An answer carries the generation it was asked in, and one from an earlier generation is turned away with no Answered event. At most 64 answers wait untaken; beyond that, answer() gives None. Reply ids now keep their kind in the top 4 bits, then the generation, then the caller's id. A new test asks for a property, loads another file before reading the answer, and checks that the late answer is turned away and an untaken one is dropped on load. It fails without the generation and the clearing. --- src/player.rs | 52 ++++++++++++++++++++++++++++++++++++++----------- tests/helper.rs | 33 ++++++++++++++++++++++++++++++- 2 files changed, 73 insertions(+), 12 deletions(-) diff --git a/src/player.rs b/src/player.rs index bff8235..dae1ac9 100644 --- a/src/player.rs +++ b/src/player.rs @@ -5,7 +5,7 @@ use std::ffi::{CStr, CString, c_char, c_int, c_void}; use std::os::fd::RawFd; use std::os::unix::ffi::OsStrExt; use std::path::Path; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -106,12 +106,18 @@ impl Request { const ALL: [Request; 6] = [Request::Command, Request::Load, Request::Pause, Request::Seek, Request::Volume, Request::Mute]; } -/// The number libmpv hands back with a reply: the watched properties use 1 and up; a request -/// is `REQUEST` plus its kind, and an `ask` is `ASK` plus its id. -const REQUEST: u64 = 1 << 32; -const ASK: u64 = 2 << 32; +/// The number libmpv hands back with a reply. The watched properties use 1 and up. Replies +/// carry a kind in the top 4 bits: a request's has its `Request` below; an `ask`'s has the +/// file's generation (bits 32 to 59) and the caller's id (the low 32). +const TAG_SHIFT: u32 = 60; +const REQUEST: u64 = 1 << TAG_SHIFT; +const ASK: u64 = 2 << TAG_SHIFT; /// The internal ask for `vid`, which says whether a loaded file has a picture. -const ASK_VIDEO: u64 = 3 << 32; +const ASK_VIDEO: u64 = 3 << TAG_SHIFT; +const GENERATION_MASK: u64 = (1 << 28) - 1; +/// The most answers kept untaken: beyond this, an answer is dropped and `answer` gives +/// `None`. +const MAX_ANSWERS: usize = 64; /// The properties every app watches, by the number libmpv hands back with each change. const WATCHED: &[(&CStr, c_int)] = &[ @@ -158,6 +164,8 @@ pub(crate) struct Core { log: Mutex>, /// Answers to `ask`, until they're taken. answers: Mutex>>, + /// Counts loads, so an answer about the last file isn't taken for this one. + generation: AtomicU64, /// Whether the file has stopped on its last frame, as last watched, for `play`. ended: AtomicBool, } @@ -193,7 +201,16 @@ impl Player { if handle.is_null() { return Err(Error::Mpv { doing: "starting libmpv".into(), reason: "out of memory".into() }); } - let core = Core { lib, handle, events: Mutex::new(()), wakeups: Mutex::new(Vec::new()), log: Mutex::new(None), answers: Mutex::new(HashMap::new()), ended: AtomicBool::new(false) }; + let core = Core { + lib, + handle, + events: Mutex::new(()), + wakeups: Mutex::new(Vec::new()), + log: Mutex::new(None), + answers: Mutex::new(HashMap::new()), + generation: AtomicU64::new(0), + ended: AtomicBool::new(false), + }; for (name, value) in options.pairs() { core.set_option(name, value)?; } @@ -230,6 +247,12 @@ impl Player { } fn request(&self, kind: Request, words: &[&[u8]]) -> Result<(), Error> { + // A new file: answers about the last one, taken or not, are gone, and late ones are + // turned away. + if kind == Request::Load { + self.core.generation.fetch_add(1, Ordering::Relaxed); + self.core.answers.lock().unwrap_or_else(|e| e.into_inner()).clear(); + } let owned = words.iter().map(|w| CString::new(*w).map_err(|_| Error::Nul)).collect::, _>>()?; let mut pointers: Vec<*const c_char> = owned.iter().map(|w| w.as_ptr()).chain([std::ptr::null()]).collect(); // SAFETY: a live handle and a null-terminated list of strings that outlive the call; @@ -247,7 +270,8 @@ impl Player { /// libmpv's core. pub fn ask(&self, name: &CStr, id: u32) -> Result<(), Error> { // SAFETY: a live handle and a terminated name; libmpv copies it. - let code = unsafe { (self.core.lib.get_property_async)(self.core.handle, ASK + u64::from(id), name.as_ptr(), ffi::FORMAT_STRING) }; + let generation = self.core.generation.load(Ordering::Relaxed) & GENERATION_MASK; + let code = unsafe { (self.core.lib.get_property_async)(self.core.handle, ASK | generation << 32 | u64::from(id), name.as_ptr(), ffi::FORMAT_STRING) }; self.check(code, name) } @@ -405,12 +429,18 @@ impl Player { if event.userdata == ASK_VIDEO { return Some(Event::Loaded { video: text.is_some_and(|v| v != "no") }); } - let id = u32::try_from(event.userdata.checked_sub(ASK)?).ok()?; - self.core.answers.lock().unwrap_or_else(|e| e.into_inner()).insert(id, text); + if event.userdata >> TAG_SHIFT != ASK >> TAG_SHIFT || (event.userdata >> 32) & GENERATION_MASK != self.core.generation.load(Ordering::Relaxed) & GENERATION_MASK { + return None; + } + let id = event.userdata as u32; + let mut answers = self.core.answers.lock().unwrap_or_else(|e| e.into_inner()); + if answers.len() < MAX_ANSWERS || answers.contains_key(&id) { + answers.insert(id, text); + } Some(Event::Answered(id)) } ffi::EVENT_COMMAND_REPLY | ffi::EVENT_SET_PROPERTY_REPLY => { - let kind = event.userdata.checked_sub(REQUEST).and_then(|k| Request::ALL.get(usize::try_from(k).ok()?).copied())?; + let kind = (event.userdata >> TAG_SHIFT == REQUEST >> TAG_SHIFT).then(|| Request::ALL.get((event.userdata & 0xff) as usize).copied()).flatten()?; (event.error < 0).then_some(Event::Refused(kind)) } ffi::EVENT_END_FILE => { diff --git a/tests/helper.rs b/tests/helper.rs index 2284558..ac9afde 100644 --- a/tests/helper.rs +++ b/tests/helper.rs @@ -26,13 +26,14 @@ fn main() -> ExitCode { if args.first().map(String::as_str) == Some(HELPER_ARG) { helper::run(&args[1..], &Options::cpu(), SANDBOX_CODE, || true); } - let tests: [Test; 6] = [ + let tests: [Test; 7] = [ ("a_video_draws_its_frames_and_stops_on_the_last", a_video_draws_its_frames_and_stops_on_the_last), ("play_after_the_end_starts_again", play_after_the_end_starts_again), ("a_new_size_redraws_the_frame_even_when_stopped", a_new_size_redraws_the_frame_even_when_stopped), ("sound_only_files_say_so_or_play_when_allowed", sound_only_files_say_so_or_play_when_allowed), ("a_file_that_isnt_media_cant_play", a_file_that_isnt_media_cant_play), ("the_last_files_position_and_duration_dont_linger", the_last_files_position_and_duration_dont_linger), + ("an_answer_is_for_the_file_it_was_asked_about", an_answer_is_for_the_file_it_was_asked_about), ]; if args.iter().any(|a| a == "--list") { for (name, _) in tests { @@ -247,3 +248,33 @@ fn the_last_files_position_and_duration_dont_linger(dir: &Path) { } } } + +/// `ask` answers without waiting, and an answer about one file is never taken for the next: +/// loading another turns late answers away and drops untaken ones. +fn an_answer_is_for_the_file_it_was_asked_about(dir: &Path) { + use alias_playback::{Event, Player}; + let player = Player::new(&Options::cpu()).expect("libmpv"); + let answered = |id: u32| { + let deadline = Instant::now() + Duration::from_secs(2); + while Instant::now() < deadline { + if player.wait_event(Duration::from_millis(50)) == Some(Event::Answered(id)) { + return true; + } + } + false + }; + player.ask(c"volume", 1).expect("ask"); + assert!(answered(1), "an answer came"); + assert!(player.answer(1).is_some_and(|v| v.starts_with("100")), "the volume"); + assert_eq!(player.answer(1), None, "taken once"); + // Asked, then another file loaded before the answer is read: it's turned away. + player.ask(c"volume", 2).expect("ask"); + player.load(&sound(dir)).expect("load"); + assert!(!answered(2), "a late answer about the last file"); + assert_eq!(player.answer(2), None); + // Answered but never taken, then a load: dropped. + player.ask(c"volume", 3).expect("ask"); + assert!(answered(3)); + player.load(&sound(dir)).expect("load"); + assert_eq!(player.answer(3), None, "dropped on load"); +} From 15e5e9e3d45d30d4f4664f45ef9de61e6aa50cce Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:59:50 -0700 Subject: [PATCH 24/25] Player and GPU helper: fixes from review round 3 - The internal `vid` read behind Loaded now carries the load generation too. Its answer is turned away if another load was asked for since, so a late "no picture" about the last file isn't reported for the new one. - A load request bumps the generation and clears the answers under the answers lock, and an answer is checked and stored under it. An `ask` on another thread can't land between the two. - `ask`'s documentation now says what the generation covers. An answer asked for before a later load request is turned away. One asked for after the request but before libmpv opens the file can still be about the last file, so ask once Loaded has come. - A restart that comes while the picture's size is still unknown is kept until the size is known, so its draw isn't lost across batches. --- src/gpu_helper.rs | 9 ++++++++- src/player.rs | 26 ++++++++++++++++++-------- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs index bacb46e..9e2806b 100644 --- a/src/gpu_helper.rs +++ b/src/gpu_helper.rs @@ -418,6 +418,8 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp let (mut hardware, mut fell_back) = (false, false); // A new frame not drawn yet, as every buffer was held; and the size of the last drawn. let (mut owed, mut drawn_size) = (false, None); + // A restart whose draw waits for the picture's size. + let mut pending_restart = false; loop { let deadline = (state.line() != reported).then_some(last_report + REPORT_EVERY); let woken = wake.wait(deadline); @@ -432,6 +434,7 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp // A new file: its own decoder, frames and fallback. The last file's frame may still // be drawn before this one is loaded; that only starts this one a moment early. (fell_back, first_drawn, told_decoder, hardware, decoder, owed, drawn_size) = (false, false, false, false, None, false, None); + pending_restart = false; if player.load_fd(file.as_raw_fd()).is_err() { say("cantplay"); } @@ -524,7 +527,11 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp } } // After the size is settled, which may have come in the same batch. - owed |= restarted && natural.is_some(); + // A restart while the size is still unknown is kept until it's known. + pending_restart |= restarted; + if natural.is_some() { + owed |= std::mem::take(&mut pending_restart); + } // Drawn before the state is reported, so the last frame reaches the app before it // hears the video has ended. 'draw: { diff --git a/src/player.rs b/src/player.rs index dae1ac9..457f320 100644 --- a/src/player.rs +++ b/src/player.rs @@ -164,7 +164,8 @@ pub(crate) struct Core { log: Mutex>, /// Answers to `ask`, until they're taken. answers: Mutex>>, - /// Counts loads, so an answer about the last file isn't taken for this one. + /// Counts load requests. An answer asked for before the latest load request is turned + /// away. Changed only with `answers` locked, so a load and an answer don't interleave. generation: AtomicU64, /// Whether the file has stopped on its last frame, as last watched, for `play`. ended: AtomicBool, @@ -250,8 +251,9 @@ impl Player { // A new file: answers about the last one, taken or not, are gone, and late ones are // turned away. if kind == Request::Load { + let mut answers = self.core.answers.lock().unwrap_or_else(|e| e.into_inner()); self.core.generation.fetch_add(1, Ordering::Relaxed); - self.core.answers.lock().unwrap_or_else(|e| e.into_inner()).clear(); + answers.clear(); } let owned = words.iter().map(|w| CString::new(*w).map_err(|_| Error::Nul)).collect::, _>>()?; let mut pointers: Vec<*const c_char> = owned.iter().map(|w| w.as_ptr()).chain([std::ptr::null()]).collect(); @@ -268,6 +270,10 @@ impl Player { /// Asks for a property as text without waiting: `Event::Answered(id)` says the answer is /// ready, and `answer(id)` takes it. For a thread that draws, which mustn't wait on /// libmpv's core. + /// + /// An answer asked for before a later load request is turned away. One asked for after a + /// load request but before libmpv has opened that file can still be about the last + /// file: ask about a file once `Event::Loaded` has come. pub fn ask(&self, name: &CStr, id: u32) -> Result<(), Error> { // SAFETY: a live handle and a terminated name; libmpv copies it. let generation = self.core.generation.load(Ordering::Relaxed) & GENERATION_MASK; @@ -420,20 +426,24 @@ impl Player { // the answer. ffi::EVENT_FILE_LOADED => { // SAFETY: a live handle and a terminated name. - let code = unsafe { (self.core.lib.get_property_async)(self.core.handle, ASK_VIDEO, c"vid".as_ptr(), ffi::FORMAT_STRING) }; + let generation = self.core.generation.load(Ordering::Relaxed) & GENERATION_MASK; + let code = unsafe { (self.core.lib.get_property_async)(self.core.handle, ASK_VIDEO | generation << 32, c"vid".as_ptr(), ffi::FORMAT_STRING) }; (code < 0).then_some(Event::Loaded { video: false }) } ffi::EVENT_GET_PROPERTY_REPLY => { // SAFETY: a reply's data is a property struct, as the caller says. let text = unsafe { reply_text(event) }; - if event.userdata == ASK_VIDEO { - return Some(Event::Loaded { video: text.is_some_and(|v| v != "no") }); - } - if event.userdata >> TAG_SHIFT != ASK >> TAG_SHIFT || (event.userdata >> 32) & GENERATION_MASK != self.core.generation.load(Ordering::Relaxed) & GENERATION_MASK { + let mut answers = self.core.answers.lock().unwrap_or_else(|e| e.into_inner()); + // Asked for before the latest load request: about a file that's going. + if (event.userdata >> 32) & GENERATION_MASK != self.core.generation.load(Ordering::Relaxed) & GENERATION_MASK { return None; } + match event.userdata >> TAG_SHIFT { + tag if tag == ASK_VIDEO >> TAG_SHIFT => return Some(Event::Loaded { video: text.is_some_and(|v| v != "no") }), + tag if tag == ASK >> TAG_SHIFT => {} + _ => return None, + } let id = event.userdata as u32; - let mut answers = self.core.answers.lock().unwrap_or_else(|e| e.into_inner()); if answers.len() < MAX_ANSWERS || answers.contains_key(&id) { answers.insert(id, text); } From 6c0187ca1440dc96f61831b4c6a047e162b075dc Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 12:09:23 -0700 Subject: [PATCH 25/25] Release GPU setup on every error path and check the framebuffer when reading a dmabuf Gpu::new now holds the GBM device, EGL display and context in a guard that frees them if a later step or lookup fails. read_dmabuf checks glCheckFramebufferStatus and returns an error instead of a zeroed buffer. --- src/gpu.rs | 71 ++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 63 insertions(+), 8 deletions(-) diff --git a/src/gpu.rs b/src/gpu.rs index 6d54e4a..3cc5e9c 100644 --- a/src/gpu.rs +++ b/src/gpu.rs @@ -51,6 +51,7 @@ pub const GL_RGBA8: i32 = 0x8058; type Ptr = *mut c_void; +#[derive(Clone, Copy)] struct Gbm { create_device: unsafe extern "C" fn(c_int) -> Ptr, device_destroy: unsafe extern "C" fn(Ptr), @@ -64,6 +65,7 @@ struct Gbm { bo_get_modifier: unsafe extern "C" fn(Ptr) -> u64, } +#[derive(Clone, Copy)] struct Egl { get_proc_address: unsafe extern "C" fn(*const c_char) -> Ptr, get_platform_display: unsafe extern "C" fn(u32, Ptr, *const isize) -> Ptr, @@ -120,6 +122,43 @@ macro_rules! lookup { }}; } +/// What `Gpu::new` has made so far, released on any early return. Disarmed with `into_parts` +/// once `new` has nothing left that can fail. +struct Setup { + gbm: Gbm, + egl: Egl, + device: Ptr, + /// Null until `eglInitialize` has succeeded. + display: Ptr, + /// Null until a context exists. + context: Ptr, +} + +impl Setup { + fn into_parts(self) -> (Ptr, Ptr, Ptr) { + let parts = (self.device, self.display, self.context); + std::mem::forget(self); + parts + } +} + +impl Drop for Setup { + fn drop(&mut self) { + // SAFETY: whatever of this device, display and context was made, released once, in + // the reverse order of making. + unsafe { + if !self.display.is_null() { + (self.egl.make_current)(self.display, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()); + if !self.context.is_null() { + (self.egl.destroy_context)(self.display, self.context); + } + (self.egl.terminate)(self.display); + } + (self.gbm.device_destroy)(self.device); + } + } +} + /// A card, with an OpenGL context current on the thread that made it. pub struct Gpu { gbm: Gbm, @@ -193,17 +232,22 @@ impl Gpu { query_modifiers: lookup!(proc, "eglQueryDmaBufModifiersEXT"), }; // SAFETY of the block: EGL and GBM calls with their headers' types, results checked. - let (device, display, context) = unsafe { + // `setup` frees what's made if a step fails, here or in the lookups below. + let mut setup = unsafe { let device = (gbm.create_device)(node.as_raw_fd()); if device.is_null() { return Err("GBM can't open the card".into()); } - let display = (egl.get_platform_display)(EGL_PLATFORM_GBM_KHR, device, [EGL_NONE as isize].as_ptr()); + Setup { gbm, egl, device, display: std::ptr::null_mut(), context: std::ptr::null_mut() } + }; + // SAFETY of the block: as above. + unsafe { + let display = (egl.get_platform_display)(EGL_PLATFORM_GBM_KHR, setup.device, [EGL_NONE as isize].as_ptr()); let (mut major, mut minor) = (0, 0); if display.is_null() || (egl.initialize)(display, &mut major, &mut minor) == 0 { - (gbm.device_destroy)(device); return Err("EGL can't use the card".into()); } + setup.display = display; let extensions = CStr::from_ptr((egl.query_string)(display, EGL_EXTENSIONS)).to_string_lossy().into_owned(); for needed in ["EGL_EXT_image_dma_buf_import", "EGL_EXT_image_dma_buf_import_modifiers", "EGL_KHR_surfaceless_context"] { if !extensions.split(' ').any(|e| e == needed) { @@ -226,11 +270,14 @@ impl Gpu { break; } } - if context.is_null() || (egl.make_current)(display, std::ptr::null_mut(), std::ptr::null_mut(), context) == 0 { + if context.is_null() { return Err("EGL won't make an OpenGL context".into()); } - (device, display, context) - }; + setup.context = context; + if (egl.make_current)(display, std::ptr::null_mut(), std::ptr::null_mut(), context) == 0 { + return Err("EGL won't make an OpenGL context".into()); + } + } let gl = Gl { gen_textures: lookup!(proc, "glGenTextures"), delete_textures: lookup!(proc, "glDeleteTextures"), @@ -252,6 +299,7 @@ impl Gpu { let name = (gl.get_string)(GL_RENDERER); if name.is_null() { "unknown".into() } else { CStr::from_ptr(name).to_string_lossy().into_owned() } }; + let (device, display, context) = setup.into_parts(); Ok(Self { gbm, egl, gl, device, display, context, _node: node, renderer }) } @@ -401,12 +449,19 @@ impl Gpu { (self.gl.gen_framebuffers)(1, &mut fbo); (self.gl.bind_framebuffer)(GL_FRAMEBUFFER, fbo); (self.gl.framebuffer_texture)(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); + // An incomplete framebuffer reads nothing, and the zeroed buffer would pass for black. + let complete = (self.gl.check_framebuffer)(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; let mut rgba = vec![0u8; width as usize * height as usize * 4]; - (self.gl.pixel_store)(GL_PACK_ALIGNMENT, 1); - (self.gl.read_pixels)(0, 0, width as i32, height as i32, GL_RGBA, GL_UNSIGNED_BYTE, rgba.as_mut_ptr() as Ptr); + if complete { + (self.gl.pixel_store)(GL_PACK_ALIGNMENT, 1); + (self.gl.read_pixels)(0, 0, width as i32, height as i32, GL_RGBA, GL_UNSIGNED_BYTE, rgba.as_mut_ptr() as Ptr); + } (self.gl.delete_framebuffers)(1, &fbo); (self.gl.delete_textures)(1, &texture); (self.egl.destroy_image)(self.display, image); + if !complete { + return Err("the dmabuf can't be read from".into()); + } Ok(rgba.as_chunks::<4>().0.iter().map(|p| u32::from(p[0]) << 16 | u32::from(p[1]) << 8 | u32::from(p[2])).collect()) } }