diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5cadaea --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,54 @@ +# Runs on GitHub's hosted runners, as the org's other open-source repositories do (the home +# runners take private ones only), in an Arch container, where aliasOS's packages are built: +# the libmpv and FFmpeg here are the ones aliasOS ships. +# +# 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 jobs run pull request code: the token reads only. +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + check: + name: fmt, clippy, tests and colour tests + runs-on: ubuntu-24.04 + 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 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..e1fa1d5 --- /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"] } + +# 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..57d3598 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,134 @@ # 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, 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. + 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..7d47279 --- /dev/null +++ b/examples/colour-gpu.rs @@ -0,0 +1,280 @@ +//! 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 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}: this machine can't make it: {e}"); + continue; + } + Err(e) => { + failed += 1; + println!("FAIL {name}: {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..a91fb40 --- /dev/null +++ b/src/helper.rs @@ -0,0 +1,857 @@ +//! 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`. +/// +/// 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)?; + // 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(_) => { + stop(&mut child); + 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..cabaaf9 --- /dev/null +++ b/src/jail.rs @@ -0,0 +1,122 @@ +//! 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'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 { + 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) -> 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)] +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_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(); + 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/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..9e5b768 --- /dev/null +++ b/src/options.rs @@ -0,0 +1,206 @@ +//! 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"), + // 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"), + ("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), 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")], + // 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"), ("ordered-chapters", "no"), ("access-references", "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..b75bdf5 --- /dev/null +++ b/src/player.rs @@ -0,0 +1,395 @@ +//! 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, or 0 while it isn't 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. 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()]) + } + + /// 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) }; + 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, 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, + }; + } + 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, + } + } +} + +/// `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))() }; +} + +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(()) + } +} + +#[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/src/render.rs b/src/render.rs new file mode 100644 index 0000000..7fa0960 --- /dev/null +++ b/src/render.rs @@ -0,0 +1,242 @@ +//! 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, 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 { + /// # 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)?, _same_thread: std::marker::PhantomData }) + } + + /// 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..2284558 --- /dev/null +++ b/tests/helper.rs @@ -0,0 +1,249 @@ +//! 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; 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 { + 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(())); +} + +/// 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"); + // 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.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); + 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, + _ => {} + } + } +}