diff --git a/Cargo.lock b/Cargo.lock index abdd65c..7121623 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,6 +8,8 @@ version = "0.1.0" dependencies = [ "libc", "rustix", + "wayland-client", + "wayland-protocols", ] [[package]] @@ -16,6 +18,22 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + [[package]] name = "errno" version = "0.3.15" @@ -26,6 +44,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + [[package]] name = "libc" version = "0.2.191" @@ -38,6 +62,45 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + [[package]] name = "rustix" version = "1.1.6" @@ -51,6 +114,81 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags", + "rustix", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "pkg-config", +] + [[package]] name = "windows-link" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index e1fa1d5..feb7468 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,9 @@ harness = false [dev-dependencies] # The helper test's cancel signal, an eventfd, as an app's would be. -rustix = { version = "1.1.6", features = ["event"] } +rustix = { version = "1.1.6", features = ["event", "pipe"] } # The GPU colour bench opens EGL at run time, as the crate opens libmpv. libc = "0.2.191" +# The GPU helper prototype's Wayland app (examples/gpu-show.rs), as Alias View uses them. +wayland-client = "0.31.15" +wayland-protocols = { version = "0.32.13", features = ["client", "unstable", "staging"] } diff --git a/examples/colour-gpu.rs b/examples/colour-gpu.rs index 7d47279..87eaadd 100644 --- a/examples/colour-gpu.rs +++ b/examples/colour-gpu.rs @@ -21,7 +21,7 @@ use std::process::ExitCode; use std::sync::OnceLock; use std::time::{Duration, Instant}; -use alias_playback::{Event, GlRender, Hwdec, Options, Player, RenderPath}; +use alias_playback::{Event, GlRender, Hwdec, Native, Options, Player, RenderPath}; use clips::{HEIGHT, TOLERANCE, WIDTH, cases, check_the_maths, decoder, make_clip, misses, play_cpu}; type EglDisplay = *mut c_void; @@ -181,7 +181,7 @@ fn play(gl: &Gl, clip: &Path, hwdec: Hwdec) -> Result<(Vec, String), String let player = Player::new(&options).map_err(|e| e.to_string())?; // SAFETY: the context is current on this thread for as long as the renderer lives, and the // lookup finds its functions. - let mut render = unsafe { GlRender::new(&player, get_proc_address, std::ptr::null_mut(), None) }.map_err(|e| e.to_string())?; + let mut render = unsafe { GlRender::new(&player, get_proc_address, std::ptr::null_mut(), Native::None) }.map_err(|e| e.to_string())?; // `COLOUR_GPU_LOG=FILE` keeps libmpv's log of the last case run, for a case that fails. if let Some(log) = std::env::var_os("COLOUR_GPU_LOG") { use std::os::unix::ffi::OsStrExt; @@ -206,7 +206,53 @@ fn play(gl: &Gl, clip: &Path, hwdec: Hwdec) -> Result<(Vec, String), String Err("no frame within 20 seconds".into()) } +const HELPER_ARG: &str = "--gpu-helper"; + +/// The first frame of `clip` as the jailed GPU helper draws it into a dmabuf, read back by +/// `reader` on this side, as Alias View will show it, and the decoder it used. +fn play_helper(reader: &alias_playback::gpu::Gpu, clip: &Path, vendor: alias_playback::Vendor, hwdec: bool) -> Result<(Vec, String), String> { + use alias_playback::gpu_helper::{self, Said}; + let exe = alias_playback::jail::own_exe().map_err(|e| e.to_string())?; + let mut command = std::process::Command::new("bwrap"); + command.args(alias_playback::jail::gpu_arguments(&exe, vendor)).arg(HELPER_ARG).arg(if hwdec { format!("{vendor:?}") } else { "software".into() }); + let node = alias_playback::gpu::first_render_node()?; + let file = std::fs::File::open(clip).map_err(|e| e.to_string())?; + let mut started = gpu_helper::start(command, file, node, (WIDTH as u32, HEIGHT as u32), false).map_err(|e| e.to_string())?; + let mut buffers: Vec> = vec![None, None, None]; + let mut pixels = None; + let result = loop { + let Ok(Some((text, mut fds))) = gpu_helper::receive(&started.socket) else { break Err("the helper stopped".to_owned()) }; + match gpu_helper::parse_said(&text) { + Some(said @ Said::Buffer { slot, .. }) if fds.len() == 1 => buffers[slot] = Some((said, fds.remove(0))), + Some(Said::Frame { slot }) if pixels.is_none() => { + let Some((Said::Buffer { width, height, modifier, stride, offset, .. }, fd)) = &buffers[slot] else { break Err("a frame in no buffer".into()) }; + let planes = [alias_playback::gpu::Plane { fd: fd.try_clone().map_err(|e| e.to_string())?, stride: *stride, offset: *offset }]; + pixels = Some(reader.read_dmabuf(*width, *height, *modifier, &planes)?); + } + Some(Said::Decoder(name)) => break pixels.take().map(|p| (p, name)).ok_or_else(|| "no frame".to_owned()), + Some(Said::CantPlay | Said::NoVideo) => break Err(text), + _ => {} + } + }; + drop(started.socket); + let _ = started.child.wait(); + result +} + fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + if args.first().map(String::as_str) == Some(HELPER_ARG) { + let hwdec = match args.get(1).map(String::as_str) { + Some("Nvidia") => Hwdec::For(alias_playback::Vendor::Nvidia), + Some("Amd") => Hwdec::For(alias_playback::Vendor::Amd), + Some("Intel") => Hwdec::For(alias_playback::Vendor::Intel), + Some("Apple") => Hwdec::For(alias_playback::Vendor::Apple), + Some("Other") => Hwdec::For(alias_playback::Vendor::Other), + _ => Hwdec::Off, + }; + let options = Options { render: RenderPath::Gpu, hwdec, ..Options::cpu() }; + alias_playback::gpu_helper::run(&args[2..], &options, 6, alias_playback::jail::lock_down_gpu_helper); + } check_the_maths(); let filters: Vec = std::env::args().skip(1).filter(|a| !a.starts_with('-')).collect(); // SAFETY: this thread keeps the context current until the process ends. @@ -223,8 +269,25 @@ fn main() -> ExitCode { eprintln!("can't make {}: {e}", dir.display()); return ExitCode::FAILURE; } - println!("\n{} colour cases, GPU renderer on {}, tolerance {TOLERANCE} steps:\n", cases.len(), gl.renderer); + let vendor = alias_playback::gpu::first_render_node().map_or(alias_playback::Vendor::Other, |node| alias_playback::gpu::vendor(&node)); + println!("\n{} colour cases, GPU renderer on {} ({vendor:?}), tolerance {TOLERANCE} steps:\n", cases.len(), gl.renderer); let (mut failed, mut skipped) = (0, 0); + // The jailed helper's frames are read back on a thread of their own, with an OpenGL + // context of its own on the same card. + let (to_reader, clips) = std::sync::mpsc::channel::<(std::path::PathBuf, bool)>(); + let (to_main, read) = std::sync::mpsc::channel::, String), String>>(); + std::thread::spawn(move || { + let reader = alias_playback::gpu::first_render_node().and_then(alias_playback::gpu::Gpu::new); + for (clip, hwdec) in clips { + let result = match &reader { + Ok(reader) => play_helper(reader, &clip, vendor, hwdec), + Err(e) => Err(e.clone()), + }; + if to_main.send(result).is_err() { + break; + } + } + }); for case in &cases { let name = case.name(); let clip = match make_clip(case, &dir) { @@ -249,10 +312,21 @@ fn main() -> ExitCode { let mut problems = Vec::new(); // The GPU renderer with and without hardware decoding, and the software renderer with // it, which CI can't try. - for (mode, render, hwdec) in [("GPU", RenderPath::Gpu, Hwdec::Off), ("GPU hwdec", RenderPath::Gpu, Hwdec::Auto), ("CPU hwdec", RenderPath::Cpu, Hwdec::Auto)] { + // Hardware decoding the way this card's maker does it, as a jailed player would. + let hwdec = Hwdec::For(vendor); + let modes = [ + ("GPU", Some(RenderPath::Gpu), Hwdec::Off), + ("GPU hwdec", Some(RenderPath::Gpu), hwdec), + ("CPU hwdec", Some(RenderPath::Cpu), hwdec), + ("jailed helper", None, Hwdec::Off), + ("jailed helper hwdec", None, hwdec), + ]; + for (mode, render, hwdec) in modes { let played = match render { - RenderPath::Gpu => play(&gl, &clip, hwdec), - RenderPath::Cpu => play_cpu(&clip, (WIDTH, HEIGHT), hwdec, true), + Some(RenderPath::Gpu) => play(&gl, &clip, hwdec), + Some(RenderPath::Cpu) => play_cpu(&clip, (WIDTH, HEIGHT), hwdec, true), + // Alias View's own path: a jailed helper's dmabuf, read back on this side. + None => to_reader.send((clip.clone(), hwdec != Hwdec::Off)).map_err(|e| e.to_string()).and_then(|()| read.recv().map_err(|e| e.to_string())?), }; match played { Ok((pixels, decoder)) => { diff --git a/examples/gpu-play.rs b/examples/gpu-play.rs new file mode 100644 index 0000000..688d190 --- /dev/null +++ b/examples/gpu-play.rs @@ -0,0 +1,177 @@ +//! The GPU helper prototype's measuring app (ALI-2358): plays a file through a GPU helper +//! player, jailed or not, takes its dmabufs as a compositor would (holding the newest frame, +//! giving the one before back), and prints what it cost. +//! +//! ```sh +//! cargo run --release --example gpu-play -- FILE [--jail] [--hwdec] [--size WxH] [--check] [--warm] +//! ``` +//! +//! `--warm` starts the helper with no file, waits until it says it's ready, and only then +//! gives it the file: the first frame is timed from then, as if the app had started the +//! player before the user chose a file. +//! +//! `--check` reads the first frame back from its dmabuf and prints the middle pixel, which +//! shows the frames cross the processes whole and in the right colours. + +use std::fs::File; +use std::os::fd::OwnedFd; +use std::process::Command; +use std::time::Instant; + +use alias_playback::gpu::{Gpu, Plane, first_render_node}; +use alias_playback::gpu_helper::{self, SLOTS, Said}; +use alias_playback::{Audio, Hwdec, Options, RenderPath, Vendor, jail}; + +const HELPER_ARG: &str = "--gpu-helper"; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.first().map(String::as_str) == Some(HELPER_ARG) { + // The decoding choice, then the size `start` adds. + let hwdec = match args.get(1).map(String::as_str) { + Some("nvidia") => Hwdec::For(Vendor::Nvidia), + Some("amd") => Hwdec::For(Vendor::Amd), + Some("intel") => Hwdec::For(Vendor::Intel), + Some("apple") => Hwdec::For(Vendor::Apple), + Some("other") => Hwdec::For(Vendor::Other), + _ => Hwdec::Off, + }; + let options = Options { render: RenderPath::Gpu, hwdec, audio: Audio::Off, cover_art: false, start_paused: true }; + gpu_helper::run(&args[2..], &options, 6, jail::lock_down_gpu_helper); + } + let file = args.first().expect("a file to play").clone(); + let flag = |name: &str| args.iter().any(|a| a == name); + let size = args.iter().position(|a| a == "--size").and_then(|i| args.get(i + 1)).and_then(|s| s.split_once('x')).map_or((1920, 1080), |(w, h)| (w.parse().unwrap(), h.parse().unwrap())); + + let node = first_render_node().expect("a render node"); + let vendor = alias_playback::gpu::vendor(&node); + let checker = flag("--check").then(|| Gpu::new(node.try_clone().expect("a copy")).expect("OpenGL for the check")); + let exe = jail::own_exe().expect("own path"); + let mut command = if flag("--jail") { + let mut command = Command::new("bwrap"); + command.args(jail::gpu_arguments(&exe, vendor)).arg(HELPER_ARG); + command + } else { + let mut command = Command::new(&exe); + command.arg(HELPER_ARG); + command + }; + // The card's maker, found at run time: the helper decodes the way that maker's cards do, + // and its jail lets through only that maker's devices. + let name = match vendor { + Vendor::Nvidia => "nvidia", + Vendor::Amd => "amd", + Vendor::Intel => "intel", + Vendor::Apple => "apple", + Vendor::Other => "other", + }; + command.arg(if flag("--hwdec") { name } else { "software" }); + let debug = std::env::var_os("GPU_PLAY_DEBUG").is_some(); + let mut start = Instant::now(); + let mut started = if flag("--warm") { + let started = gpu_helper::start_warm(command, node, size, debug).expect("the helper"); + loop { + match gpu_helper::receive(&started.socket) { + Ok(Some((text, _))) if text == "hello" => break, + Ok(Some(_)) => {} + _ => panic!("the helper ended while warming up"), + } + } + println!("warm after {:.0} ms", start.elapsed().as_secs_f64() * 1000.0); + start = Instant::now(); + gpu_helper::load(&started.socket, &File::open(&file).expect("the file")).expect("load"); + started + } else { + gpu_helper::start(command, File::open(&file).expect("the file"), node, size, debug).expect("the helper") + }; + if gpu_helper::send(&started.socket, "play", &[]).is_err() { + // Gone before it could be told to play: say how it ended. + println!("the helper ended at once: {:?}", started.child.wait()); + return; + } + let mut buffers: [Option<(Said, Vec)>; SLOTS] = [None, None, None]; + let (mut frames, mut first_frame, mut shown): (u64, Option, Option) = (0, None, None); + let (mut dropped, mut state, mut decoder) = ((0, 0), None, String::from("?")); + while let Ok(Some((text, fds))) = gpu_helper::receive(&started.socket) { + if std::env::var_os("GPU_PLAY_DEBUG").is_some() { + eprintln!("{:6.0} ms < {text}", start.elapsed().as_secs_f64() * 1000.0); + } + match gpu_helper::parse_said(&text) { + Some(said @ Said::Buffer { slot, .. }) if fds.len() == 1 => buffers[slot] = Some((said, fds)), + Some(Said::Buffer { .. }) => {} + Some(Said::Frame { slot }) if buffers[slot].is_some() => { + frames += 1; + if first_frame.is_none() { + first_frame = Some(start.elapsed().as_secs_f64() * 1000.0); + if let (Some(gpu), Some((Said::Buffer { width, height, modifier, stride, offset, .. }, fds))) = (&checker, &buffers[slot]) { + let planes = [Plane { fd: fds[0].try_clone().expect("a copy"), stride: *stride, offset: *offset }]; + let pixels = gpu.read_dmabuf(*width, *height, *modifier, &planes).expect("read back"); + let middle = pixels[(*height / 2 * *width + *width / 2) as usize]; + println!("first frame {width}x{height}, modifier {modifier:#x}, middle #{middle:06X}"); + } + } + // A compositor gives the last buffer back once the new one is on screen. + if let Some(old) = shown.replace(slot) { + let _ = gpu_helper::send(&started.socket, &format!("release {old}"), &[]); + } + } + Some(Said::Dropped { decoder, late }) => dropped = (decoder, late), + Some(Said::Decoder(name)) => decoder = name, + Some(Said::State(s)) => { + state = Some(s); + if s.ended { + break; + } + } + Some(Said::CantPlay) | Some(Said::NoVideo) => { + println!("{text}"); + break; + } + _ => {} + } + } + let wall = start.elapsed().as_secs_f64(); + // The helper and anything under it (bubblewrap's own processes when jailed), read from + // /proc before it goes: a jailed helper isn't this process's child to wait for. + let (cpu, rss_kb) = usage_below(started.child.id()); + drop(buffers); + drop(started.socket); + let status = started.child.wait(); + if state.is_none_or(|s| !s.ended) { + println!("the helper ended before the clip did: {status:?}"); + } + let duration = state.map_or(0.0, |s| s.duration); + println!( + "{file}: {decoder}, {frames} frames in {wall:.2} s (clip {duration:.2} s), first frame {:.0} ms, dropped {} decoder + {} late, helper CPU {cpu:.2} s, helper peak RSS {} MB", + first_frame.unwrap_or(f64::NAN), + dropped.0, + dropped.1, + rss_kb / 1024 + ); +} + +/// CPU seconds and the largest peak RSS (KB) of `pid` and every process below it. +fn usage_below(pid: u32) -> (f64, u64) { + // SAFETY: a plain query. + let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) } as f64; + let (mut cpu, mut rss) = (0.0, 0); + let mut queue = vec![pid]; + while let Some(pid) = queue.pop() { + if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) { + let fields: Vec<&str> = stat.rsplit_once(')').map_or("", |r| r.1).split_whitespace().collect(); + let n = |i: usize| fields.get(i).and_then(|f| f.parse::().ok()).unwrap_or(0.0); + // utime, stime, cutime, cstime: fields 14 to 17, here 11 to 14 after the name. + cpu += (n(11) + n(12) + n(13) + n(14)) / ticks; + } + if let Ok(status) = std::fs::read_to_string(format!("/proc/{pid}/status")) { + let hwm = status.lines().find_map(|l| l.strip_prefix("VmHWM:")).and_then(|v| v.trim().trim_end_matches(" kB").parse::().ok()).unwrap_or(0); + rss = rss.max(hwm); + } + for task in std::fs::read_dir(format!("/proc/{pid}/task")).into_iter().flatten().flatten() { + if let Ok(children) = std::fs::read_to_string(task.path().join("children")) { + queue.extend(children.split_whitespace().filter_map(|c| c.parse::().ok())); + } + } + } + (cpu, rss) +} diff --git a/examples/gpu-show.rs b/examples/gpu-show.rs new file mode 100644 index 0000000..39113b9 --- /dev/null +++ b/examples/gpu-show.rs @@ -0,0 +1,263 @@ +//! The GPU helper prototype shown on a real compositor (ALI-2358): a window whose frames are +//! the helper's dmabufs, attached through `linux-dmabuf`, given back to the helper when the +//! compositor releases them. Measures what `gpu-play` does, end to end. +//! +//! ```sh +//! WAYLAND_DISPLAY=... cargo run --release --example gpu-show -- FILE [--jail] [--hwdec] [--size WxH] +//! ``` +//! +//! Run it in a private headless weston for measuring, never on someone's live session. + +use std::fs::File; +use std::os::fd::{AsFd, AsRawFd, OwnedFd}; +use std::process::Command; +use std::sync::mpsc; +use std::time::Instant; + +use alias_playback::gpu::first_render_node; +use alias_playback::gpu_helper::{self, SLOTS, Said}; +use alias_playback::{Audio, Hwdec, Options, RenderPath, Vendor, jail}; +use rustix::event::{PollFd, PollFlags, poll}; +use wayland_client::protocol::{wl_buffer, wl_compositor, wl_registry, wl_surface}; +use wayland_client::{Connection, Dispatch, QueueHandle, delegate_noop}; +use wayland_protocols::wp::linux_dmabuf::zv1::client::{zwp_linux_buffer_params_v1, zwp_linux_dmabuf_v1}; +use wayland_protocols::xdg::shell::client::{xdg_surface, xdg_toplevel, xdg_wm_base}; + +const HELPER_ARG: &str = "--gpu-helper"; + +#[derive(Default)] +struct App { + compositor: Option, + dmabuf: Option, + wm: Option, + configured: bool, + released: Vec, +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.first().map(String::as_str) == Some(HELPER_ARG) { + let hwdec = match args.get(1).map(String::as_str) { + Some("nvidia") => Hwdec::For(Vendor::Nvidia), + Some("amd") => Hwdec::For(Vendor::Amd), + Some("intel") => Hwdec::For(Vendor::Intel), + Some("apple") => Hwdec::For(Vendor::Apple), + Some("other") => Hwdec::For(Vendor::Other), + _ => Hwdec::Off, + }; + let options = Options { render: RenderPath::Gpu, hwdec, audio: Audio::Off, cover_art: false, start_paused: true }; + gpu_helper::run(&args[2..], &options, 6, jail::lock_down_gpu_helper); + } + let file = args.first().expect("a file to play").clone(); + let flag = |name: &str| args.iter().any(|a| a == name); + let size: (u32, u32) = + args.iter().position(|a| a == "--size").and_then(|i| args.get(i + 1)).and_then(|s| s.split_once('x')).map_or((1920, 1080), |(w, h)| (w.parse().unwrap(), h.parse().unwrap())); + let start = Instant::now(); + + let connection = Connection::connect_to_env().expect("a Wayland compositor"); + let mut queue = connection.new_event_queue(); + let qh = queue.handle(); + connection.display().get_registry(&qh, ()); + let mut app = App::default(); + queue.roundtrip(&mut app).expect("globals"); + let (compositor, dmabuf, wm) = (app.compositor.clone().expect("wl_compositor"), app.dmabuf.clone().expect("linux-dmabuf v3+"), app.wm.clone().expect("xdg_wm_base")); + let surface = compositor.create_surface(&qh, ()); + let toplevel = wm.get_xdg_surface(&surface, &qh, ()).get_toplevel(&qh, ()); + toplevel.set_title("gpu-show".into()); + surface.commit(); + while !app.configured { + queue.blocking_dispatch(&mut app).expect("configure"); + } + + let node = first_render_node().expect("a render node"); + let vendor = alias_playback::gpu::vendor(&node); + let exe = jail::own_exe().expect("own path"); + let mut command = if flag("--jail") { + let mut command = Command::new("bwrap"); + command.args(jail::gpu_arguments(&exe, vendor)).arg(HELPER_ARG); + command + } else { + let mut command = Command::new(&exe); + command.arg(HELPER_ARG); + command + }; + // The card's maker, found at run time: the helper decodes the way that maker's cards do, + // and its jail lets through only that maker's devices. + let name = match vendor { + Vendor::Nvidia => "nvidia", + Vendor::Amd => "amd", + Vendor::Intel => "intel", + Vendor::Apple => "apple", + Vendor::Other => "other", + }; + command.arg(if flag("--hwdec") { name } else { "software" }); + let started = gpu_helper::start(command, File::open(&file).expect("the file"), node, size, false).expect("the helper"); + let helper_pid = started.child.id(); + let socket = started.socket; + gpu_helper::send(&socket, "play", &[]).expect("play"); + + // The helper's messages, read on their own thread and handed over with a wake-up. + // `None` once the helper is gone, said or not, so a silent death doesn't hang this. + let (tx, rx) = mpsc::channel::)>>(); + let (wake_read, wake_write) = rustix::pipe::pipe().expect("pipe"); + let reading = socket.try_clone().expect("a copy"); + std::thread::spawn(move || { + while let Ok(Some(message)) = gpu_helper::receive(&reading) { + if tx.send(Some(message)).is_err() { + break; + } + let _ = rustix::io::write(&wake_write, &[1]); + } + let _ = tx.send(None); + let _ = rustix::io::write(&wake_write, &[1]); + }); + + let mut buffers: [Option; SLOTS] = [None, None, None]; + let (mut frames, mut first_frame, mut dropped, mut decoder, mut duration) = (0u64, None, (0, 0), String::from("?"), 0.0); + let mut done = false; + let mut scratch = [0u8; 64]; + while !done { + queue.flush().expect("flush"); + queue.dispatch_pending(&mut app).expect("dispatch"); + for slot in app.released.drain(..) { + let _ = gpu_helper::send(&socket, &format!("release {slot}"), &[]); + } + let read_guard = queue.prepare_read(); + let wayland_fd = read_guard.as_ref().map(|g| g.connection_fd().as_raw_fd()); + let mut fds = vec![PollFd::new(&wake_read, PollFlags::IN)]; + // SAFETY: the connection's descriptor lives as long as the connection. + let borrowed = wayland_fd.map(|fd| unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) }); + if let Some(fd) = &borrowed { + fds.push(PollFd::new(fd, PollFlags::IN)); + } + let _ = poll(&mut fds, None); + let wayland_ready = fds.get(1).is_some_and(|f| !f.revents().is_empty()); + if let Some(guard) = read_guard { + if wayland_ready { + guard.read().ok() + } else { + drop(guard); + None + }; + } + let _ = rustix::io::read(&wake_read, &mut scratch); + for message in rx.try_iter() { + let Some((text, fds)) = message else { + done = true; + break; + }; + match gpu_helper::parse_said(&text) { + Some(Said::Buffer { slot, width, height, fourcc, modifier, stride, offset }) if fds.len() == 1 => { + let params = dmabuf.create_params(&qh, ()); + params.add(fds[0].as_fd(), 0, offset, stride, (modifier >> 32) as u32, modifier as u32); + let buffer = params.create_immed(width as i32, height as i32, fourcc, zwp_linux_buffer_params_v1::Flags::empty(), &qh, slot); + params.destroy(); + if let Some(old) = buffers[slot].replace(buffer) { + old.destroy(); + } + } + Some(Said::Frame { slot }) => { + if let Some(buffer) = &buffers[slot] { + surface.attach(Some(buffer), 0, 0); + surface.damage_buffer(0, 0, i32::MAX, i32::MAX); + surface.commit(); + frames += 1; + first_frame.get_or_insert(start.elapsed().as_secs_f64() * 1000.0); + } + } + Some(Said::Dropped { decoder, late }) => dropped = (decoder, late), + Some(Said::Decoder(name)) => decoder = name, + Some(Said::State(state)) => { + duration = state.duration; + done |= state.ended; + } + Some(Said::CantPlay | Said::NoVideo) => done = true, + _ => {} + } + } + } + let wall = start.elapsed().as_secs_f64(); + let (cpu, rss) = usage_below(helper_pid); + // SAFETY: a zeroed rusage is valid for this query. + let mut own: libc::rusage = unsafe { std::mem::zeroed() }; + unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut own) }; + let own_cpu = own.ru_utime.tv_sec as f64 + own.ru_utime.tv_usec as f64 / 1e6 + own.ru_stime.tv_sec as f64 + own.ru_stime.tv_usec as f64 / 1e6; + println!( + "{file}: {decoder}, {frames} frames shown in {wall:.2} s (clip {duration:.2} s), first frame {:.0} ms, dropped {} decoder + {} late, CPU {:.2} s (helper {cpu:.2} + app {own_cpu:.2}), peak RSS helper {} MB + app {} MB", + first_frame.unwrap_or(f64::NAN), + dropped.0, + dropped.1, + cpu + own_cpu, + rss / 1024, + own.ru_maxrss / 1024 + ); +} + +/// CPU seconds and the largest peak RSS (KB) of `pid` and every process below it. +fn usage_below(pid: u32) -> (f64, u64) { + // SAFETY: a plain query. + let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) } as f64; + let (mut cpu, mut rss) = (0.0, 0); + let mut queue = vec![pid]; + while let Some(pid) = queue.pop() { + if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) { + let fields: Vec<&str> = stat.rsplit_once(')').map_or("", |r| r.1).split_whitespace().collect(); + let n = |i: usize| fields.get(i).and_then(|f| f.parse::().ok()).unwrap_or(0.0); + cpu += (n(11) + n(12) + n(13) + n(14)) / ticks; + } + if let Ok(status) = std::fs::read_to_string(format!("/proc/{pid}/status")) { + let hwm = status.lines().find_map(|l| l.strip_prefix("VmHWM:")).and_then(|v| v.trim().trim_end_matches(" kB").parse::().ok()).unwrap_or(0); + rss = rss.max(hwm); + } + for task in std::fs::read_dir(format!("/proc/{pid}/task")).into_iter().flatten().flatten() { + if let Ok(children) = std::fs::read_to_string(task.path().join("children")) { + queue.extend(children.split_whitespace().filter_map(|c| c.parse::().ok())); + } + } + } + (cpu, rss) +} + +impl Dispatch for App { + fn event(app: &mut Self, registry: &wl_registry::WlRegistry, event: wl_registry::Event, _: &(), _: &Connection, qh: &QueueHandle) { + if let wl_registry::Event::Global { name, interface, version } = event { + match interface.as_str() { + "wl_compositor" => app.compositor = Some(registry.bind(name, version.min(4), qh, ())), + "zwp_linux_dmabuf_v1" if version >= 3 => app.dmabuf = Some(registry.bind(name, 3, qh, ())), + "xdg_wm_base" => app.wm = Some(registry.bind(name, 1, qh, ())), + _ => {} + } + } + } +} + +impl Dispatch for App { + fn event(_: &mut Self, wm: &xdg_wm_base::XdgWmBase, event: xdg_wm_base::Event, _: &(), _: &Connection, _: &QueueHandle) { + if let xdg_wm_base::Event::Ping { serial } = event { + wm.pong(serial); + } + } +} + +impl Dispatch for App { + fn event(app: &mut Self, surface: &xdg_surface::XdgSurface, event: xdg_surface::Event, _: &(), _: &Connection, _: &QueueHandle) { + if let xdg_surface::Event::Configure { serial } = event { + surface.ack_configure(serial); + app.configured = true; + } + } +} + +impl Dispatch for App { + fn event(app: &mut Self, _: &wl_buffer::WlBuffer, event: wl_buffer::Event, slot: &usize, _: &Connection, _: &QueueHandle) { + if let wl_buffer::Event::Release = event { + app.released.push(*slot); + } + } +} + +delegate_noop!(App: ignore wl_compositor::WlCompositor); +delegate_noop!(App: ignore wl_surface::WlSurface); +delegate_noop!(App: ignore xdg_toplevel::XdgToplevel); +delegate_noop!(App: ignore zwp_linux_dmabuf_v1::ZwpLinuxDmabufV1); +delegate_noop!(App: ignore zwp_linux_buffer_params_v1::ZwpLinuxBufferParamsV1); diff --git a/src/ffi.rs b/src/ffi.rs index 2682c7b..6a6799d 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -54,17 +54,41 @@ pub struct OpenGlFbo { pub internal_format: c_int, } +/// `mpv_opengl_drm_params_v2`. Only `render_fd` is used here: it lets libmpv's VA-API +/// decoding share frames with OpenGL with no display connection at all. +#[repr(C)] +pub struct OpenGlDrmParamsV2 { + pub fd: c_int, + pub crtc_id: c_int, + pub connector_id: c_int, + pub atomic_request_ptr: *mut c_void, + pub render_fd: c_int, +} + pub const FORMAT_NONE: c_int = 0; +pub const FORMAT_STRING: c_int = 1; 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_GET_PROPERTY_REPLY: c_int = 3; +pub const EVENT_SET_PROPERTY_REPLY: c_int = 4; +pub const EVENT_COMMAND_REPLY: c_int = 5; pub const EVENT_END_FILE: c_int = 7; pub const EVENT_FILE_LOADED: c_int = 8; pub const EVENT_VIDEO_RECONFIG: c_int = 17; pub const EVENT_PLAYBACK_RESTART: c_int = 21; pub const EVENT_PROPERTY_CHANGE: c_int = 22; +pub const EVENT_LOG_MESSAGE: c_int = 2; + +#[repr(C)] +pub struct EventLogMessage { + pub prefix: *const c_char, + pub level: *const c_char, + pub text: *const c_char, + pub log_level: c_int, +} pub const END_FILE_ERROR: c_int = 4; @@ -74,6 +98,7 @@ pub const RENDER_OPENGL_INIT_PARAMS: c_int = 2; pub const RENDER_OPENGL_FBO: c_int = 3; pub const RENDER_FLIP_Y: c_int = 4; pub const RENDER_WL_DISPLAY: c_int = 9; +pub const RENDER_DRM_DISPLAY_V2: c_int = 16; pub const RENDER_SW_SIZE: c_int = 17; pub const RENDER_SW_FORMAT: c_int = 18; pub const RENDER_SW_STRIDE: c_int = 19; @@ -114,6 +139,9 @@ pub struct Library { pub error_string: unsafe extern "C" fn(c_int) -> *const c_char, pub set_option_string: unsafe extern "C" fn(Handle, *const c_char, *const c_char) -> c_int, pub command: unsafe extern "C" fn(Handle, *mut *const c_char) -> c_int, + pub command_async: unsafe extern "C" fn(Handle, u64, *mut *const c_char) -> c_int, + pub set_property_async: unsafe extern "C" fn(Handle, u64, *const c_char, c_int, *mut c_void) -> c_int, + pub get_property_async: unsafe extern "C" fn(Handle, u64, *const c_char, c_int) -> c_int, pub set_property: unsafe extern "C" fn(Handle, *const c_char, c_int, *mut c_void) -> c_int, pub get_property: unsafe extern "C" fn(Handle, *const c_char, c_int, *mut c_void) -> c_int, pub get_property_string: unsafe extern "C" fn(Handle, *const c_char) -> *mut c_char, @@ -127,6 +155,7 @@ pub struct Library { pub render: unsafe extern "C" fn(Handle, *mut RenderParam) -> c_int, pub render_report_swap: unsafe extern "C" fn(Handle), pub render_free: unsafe extern "C" fn(Handle), + pub request_log_messages: unsafe extern "C" fn(Handle, *const c_char) -> c_int, } // SAFETY: a table of function pointers into a library that stays loaded for the process. @@ -175,6 +204,9 @@ impl Library { error_string: sym!("mpv_error_string"), set_option_string: sym!("mpv_set_option_string"), command: sym!("mpv_command"), + command_async: sym!("mpv_command_async"), + set_property_async: sym!("mpv_set_property_async"), + get_property_async: sym!("mpv_get_property_async"), set_property: sym!("mpv_set_property"), get_property: sym!("mpv_get_property"), get_property_string: sym!("mpv_get_property_string"), @@ -188,6 +220,7 @@ impl Library { render: sym!("mpv_render_context_render"), render_report_swap: sym!("mpv_render_context_report_swap"), render_free: sym!("mpv_render_context_free"), + request_log_messages: sym!("mpv_request_log_messages"), }) } diff --git a/src/gpu.rs b/src/gpu.rs new file mode 100644 index 0000000..3cc5e9c --- /dev/null +++ b/src/gpu.rs @@ -0,0 +1,568 @@ +//! OpenGL on a graphics card with no window, drawing into dmabufs another process can show. +//! +//! A GPU helper player draws with libmpv's OpenGL renderer into buffers allocated with GBM +//! on the card the app's compositor uses, and hands their dmabufs to the app, which gives +//! them to the compositor through `linux-dmabuf`. The frame never leaves the card, and the +//! player never sees the app's Wayland connection. +//! +//! Everything is looked up at run time, as libmpv is: libgbm, libEGL and the GL functions +//! EGL finds. The types and numbers are from `gbm.h`, `EGL/egl.h`, `EGL/eglext.h` and the +//! GL headers. + +use std::ffi::{CStr, c_char, c_int, c_void}; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; + +/// `XRGB8888`: what `wl_shm` frames use too, and every compositor takes. +pub const FOURCC_XRGB8888: u32 = u32::from_le_bytes(*b"XR24"); +/// The driver's own choice of layout, said without naming one. +pub const MOD_INVALID: u64 = 0x00ff_ffff_ffff_ffff; + +const EGL_NONE: i32 = 0x3038; +const EGL_EXTENSIONS: i32 = 0x3055; +const EGL_RENDERABLE_TYPE: i32 = 0x3040; +const EGL_OPENGL_BIT: i32 = 0x0008; +const EGL_SURFACE_TYPE: i32 = 0x3033; +const EGL_OPENGL_API: u32 = 0x30A2; +const EGL_PLATFORM_GBM_KHR: u32 = 0x31D7; +const EGL_LINUX_DMA_BUF_EXT: u32 = 0x3270; +const EGL_WIDTH: i32 = 0x3057; +const EGL_HEIGHT: i32 = 0x3056; +const EGL_LINUX_DRM_FOURCC_EXT: i32 = 0x3271; +const EGL_DMA_BUF_PLANE0_FD_EXT: i32 = 0x3272; +const EGL_DMA_BUF_PLANE0_OFFSET_EXT: i32 = 0x3273; +const EGL_DMA_BUF_PLANE0_PITCH_EXT: i32 = 0x3274; +const EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT: i32 = 0x3443; +const EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT: i32 = 0x3444; +const EGL_CONTEXT_MAJOR_VERSION: i32 = 0x3098; +const EGL_CONTEXT_MINOR_VERSION: i32 = 0x30FB; +const EGL_CONTEXT_OPENGL_PROFILE_MASK: i32 = 0x30FD; + +const GBM_BO_USE_RENDERING: u32 = 1 << 2; + +const GL_TEXTURE_2D: u32 = 0x0DE1; +const GL_FRAMEBUFFER: u32 = 0x8D40; +const GL_COLOR_ATTACHMENT0: u32 = 0x8CE0; +const GL_FRAMEBUFFER_COMPLETE: u32 = 0x8CD5; +const GL_RGBA: u32 = 0x1908; +const GL_UNSIGNED_BYTE: u32 = 0x1401; +const GL_PACK_ALIGNMENT: u32 = 0x0D05; +const GL_RENDERER: u32 = 0x1F01; +pub const GL_RGBA8: i32 = 0x8058; + +type Ptr = *mut c_void; + +#[derive(Clone, Copy)] +struct Gbm { + create_device: unsafe extern "C" fn(c_int) -> Ptr, + device_destroy: unsafe extern "C" fn(Ptr), + bo_create: unsafe extern "C" fn(Ptr, u32, u32, u32, u32) -> Ptr, + bo_create_with_modifiers2: unsafe extern "C" fn(Ptr, u32, u32, u32, *const u64, u32, u32) -> Ptr, + bo_destroy: unsafe extern "C" fn(Ptr), + bo_get_plane_count: unsafe extern "C" fn(Ptr) -> c_int, + bo_get_fd_for_plane: unsafe extern "C" fn(Ptr, c_int) -> c_int, + bo_get_stride_for_plane: unsafe extern "C" fn(Ptr, c_int) -> u32, + bo_get_offset: unsafe extern "C" fn(Ptr, c_int) -> u32, + bo_get_modifier: unsafe extern "C" fn(Ptr) -> u64, +} + +#[derive(Clone, Copy)] +struct Egl { + get_proc_address: unsafe extern "C" fn(*const c_char) -> Ptr, + get_platform_display: unsafe extern "C" fn(u32, Ptr, *const isize) -> Ptr, + initialize: unsafe extern "C" fn(Ptr, *mut i32, *mut i32) -> u32, + terminate: unsafe extern "C" fn(Ptr) -> u32, + bind_api: unsafe extern "C" fn(u32) -> u32, + query_string: unsafe extern "C" fn(Ptr, i32) -> *const c_char, + choose_config: unsafe extern "C" fn(Ptr, *const i32, *mut Ptr, i32, *mut i32) -> u32, + create_context: unsafe extern "C" fn(Ptr, Ptr, Ptr, *const i32) -> Ptr, + destroy_context: unsafe extern "C" fn(Ptr, Ptr) -> u32, + make_current: unsafe extern "C" fn(Ptr, Ptr, Ptr, Ptr) -> u32, + create_image: unsafe extern "C" fn(Ptr, Ptr, u32, Ptr, *const i32) -> Ptr, + query_modifiers: unsafe extern "C" fn(Ptr, i32, i32, *mut u64, *mut u32, *mut i32) -> u32, + destroy_image: unsafe extern "C" fn(Ptr, Ptr) -> u32, +} + +struct Gl { + gen_textures: unsafe extern "C" fn(i32, *mut u32), + delete_textures: unsafe extern "C" fn(i32, *const u32), + bind_texture: unsafe extern "C" fn(u32, u32), + image_target_texture: unsafe extern "C" fn(u32, Ptr), + gen_framebuffers: unsafe extern "C" fn(i32, *mut u32), + delete_framebuffers: unsafe extern "C" fn(i32, *const u32), + bind_framebuffer: unsafe extern "C" fn(u32, u32), + framebuffer_texture: unsafe extern "C" fn(u32, u32, u32, u32, i32), + check_framebuffer: unsafe extern "C" fn(u32) -> u32, + finish: unsafe extern "C" fn(), + flush: unsafe extern "C" fn(), + read_pixels: unsafe extern "C" fn(i32, i32, i32, i32, u32, u32, Ptr), + pixel_store: unsafe extern "C" fn(u32, i32), + get_string: unsafe extern "C" fn(u32) -> *const c_char, +} + +/// Opens a library for good, or says which. +fn open(name: &CStr) -> Result { + // SAFETY: opening a system library by name. It's never closed. + let library = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; + if library.is_null() { Err(format!("no {}", name.to_string_lossy())) } else { Ok(library) } +} + +/// Looks up `$name` with `$find` as the type it's assigned to, or returns an error. +macro_rules! lookup { + ($find:expr, $name:literal) => {{ + // The finders are closures around dlsym or eglGetProcAddress, given a terminated name. + let found = $find(concat!($name, "\0").as_ptr() as *const c_char); + if found.is_null() { + return Err(concat!("no ", $name).to_owned()); + } + // SAFETY: the type assigned to is the function's type in its header. + #[allow(clippy::missing_transmute_annotations)] + unsafe { + std::mem::transmute(found) + } + }}; +} + +/// What `Gpu::new` has made so far, released on any early return. Disarmed with `into_parts` +/// once `new` has nothing left that can fail. +struct Setup { + gbm: Gbm, + egl: Egl, + device: Ptr, + /// Null until `eglInitialize` has succeeded. + display: Ptr, + /// Null until a context exists. + context: Ptr, +} + +impl Setup { + fn into_parts(self) -> (Ptr, Ptr, Ptr) { + let parts = (self.device, self.display, self.context); + std::mem::forget(self); + parts + } +} + +impl Drop for Setup { + fn drop(&mut self) { + // SAFETY: whatever of this device, display and context was made, released once, in + // the reverse order of making. + unsafe { + if !self.display.is_null() { + (self.egl.make_current)(self.display, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()); + if !self.context.is_null() { + (self.egl.destroy_context)(self.display, self.context); + } + (self.egl.terminate)(self.display); + } + (self.gbm.device_destroy)(self.device); + } + } +} + +/// A card, with an OpenGL context current on the thread that made it. +pub struct Gpu { + gbm: Gbm, + egl: Egl, + gl: Gl, + device: Ptr, + display: Ptr, + context: Ptr, + /// The render node, kept open for the device's life. + _node: OwnedFd, + pub renderer: String, +} + +/// One plane of a dmabuf, as `linux-dmabuf` takes it. +#[derive(Debug)] +pub struct Plane { + pub fd: OwnedFd, + pub stride: u32, + pub offset: u32, +} + +/// A buffer libmpv draws into: the GBM buffer, its dmabuf planes, and the framebuffer on it. +pub struct Target { + pub width: u32, + pub height: u32, + pub fourcc: u32, + pub modifier: u64, + pub planes: Vec, + pub fbo: u32, + texture: u32, + image: Ptr, + bo: Ptr, +} + +impl Gpu { + /// OpenGL on the card behind `node`, a DRM render node such as `/dev/dri/renderD128`, + /// made current on this thread. Stays on this thread: it isn't `Send`. + pub fn new(node: OwnedFd) -> Result { + let gbm_lib = open(c"libgbm.so.1")?; + let egl_lib = open(c"libEGL.so.1")?; + // SAFETY (all three finders): lookups in libraries kept open, by terminated name. + let gbm_sym = |name: *const c_char| unsafe { libc::dlsym(gbm_lib, name) }; + let egl_sym = |name: *const c_char| unsafe { libc::dlsym(egl_lib, name) }; + let gbm = Gbm { + create_device: lookup!(gbm_sym, "gbm_create_device"), + device_destroy: lookup!(gbm_sym, "gbm_device_destroy"), + bo_create: lookup!(gbm_sym, "gbm_bo_create"), + bo_create_with_modifiers2: lookup!(gbm_sym, "gbm_bo_create_with_modifiers2"), + bo_destroy: lookup!(gbm_sym, "gbm_bo_destroy"), + bo_get_plane_count: lookup!(gbm_sym, "gbm_bo_get_plane_count"), + bo_get_fd_for_plane: lookup!(gbm_sym, "gbm_bo_get_fd_for_plane"), + bo_get_stride_for_plane: lookup!(gbm_sym, "gbm_bo_get_stride_for_plane"), + bo_get_offset: lookup!(gbm_sym, "gbm_bo_get_offset"), + bo_get_modifier: lookup!(gbm_sym, "gbm_bo_get_modifier"), + }; + let get_proc_address: unsafe extern "C" fn(*const c_char) -> Ptr = lookup!(egl_sym, "eglGetProcAddress"); + let proc = |name: *const c_char| unsafe { get_proc_address(name) }; + let egl = Egl { + get_proc_address, + get_platform_display: lookup!(egl_sym, "eglGetPlatformDisplay"), + initialize: lookup!(egl_sym, "eglInitialize"), + terminate: lookup!(egl_sym, "eglTerminate"), + bind_api: lookup!(egl_sym, "eglBindAPI"), + query_string: lookup!(egl_sym, "eglQueryString"), + choose_config: lookup!(egl_sym, "eglChooseConfig"), + create_context: lookup!(egl_sym, "eglCreateContext"), + destroy_context: lookup!(egl_sym, "eglDestroyContext"), + make_current: lookup!(egl_sym, "eglMakeCurrent"), + create_image: lookup!(proc, "eglCreateImageKHR"), + destroy_image: lookup!(proc, "eglDestroyImageKHR"), + query_modifiers: lookup!(proc, "eglQueryDmaBufModifiersEXT"), + }; + // SAFETY of the block: EGL and GBM calls with their headers' types, results checked. + // `setup` frees what's made if a step fails, here or in the lookups below. + let mut setup = unsafe { + let device = (gbm.create_device)(node.as_raw_fd()); + if device.is_null() { + return Err("GBM can't open the card".into()); + } + Setup { gbm, egl, device, display: std::ptr::null_mut(), context: std::ptr::null_mut() } + }; + // SAFETY of the block: as above. + unsafe { + let display = (egl.get_platform_display)(EGL_PLATFORM_GBM_KHR, setup.device, [EGL_NONE as isize].as_ptr()); + let (mut major, mut minor) = (0, 0); + if display.is_null() || (egl.initialize)(display, &mut major, &mut minor) == 0 { + return Err("EGL can't use the card".into()); + } + setup.display = display; + let extensions = CStr::from_ptr((egl.query_string)(display, EGL_EXTENSIONS)).to_string_lossy().into_owned(); + for needed in ["EGL_EXT_image_dma_buf_import", "EGL_EXT_image_dma_buf_import_modifiers", "EGL_KHR_surfaceless_context"] { + if !extensions.split(' ').any(|e| e == needed) { + return Err(format!("EGL lacks {needed}")); + } + } + (egl.bind_api)(EGL_OPENGL_API); + let mut config: Ptr = std::ptr::null_mut(); + let mut count = 0; + let wanted = [EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_SURFACE_TYPE, 0, EGL_NONE]; + if (egl.choose_config)(display, wanted.as_ptr(), &mut config, 1, &mut count) == 0 || count == 0 { + return Err("EGL has no OpenGL config".into()); + } + // The newest compatibility context the driver gives, or core 3.3. + let core = [EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3, EGL_CONTEXT_OPENGL_PROFILE_MASK, 1, EGL_NONE]; + let mut context = std::ptr::null_mut(); + for attributes in [&[EGL_NONE][..], &core[..]] { + context = (egl.create_context)(display, config, std::ptr::null_mut(), attributes.as_ptr()); + if !context.is_null() { + break; + } + } + if context.is_null() { + return Err("EGL won't make an OpenGL context".into()); + } + setup.context = context; + if (egl.make_current)(display, std::ptr::null_mut(), std::ptr::null_mut(), context) == 0 { + return Err("EGL won't make an OpenGL context".into()); + } + } + let gl = Gl { + gen_textures: lookup!(proc, "glGenTextures"), + delete_textures: lookup!(proc, "glDeleteTextures"), + bind_texture: lookup!(proc, "glBindTexture"), + image_target_texture: lookup!(proc, "glEGLImageTargetTexture2DOES"), + gen_framebuffers: lookup!(proc, "glGenFramebuffers"), + delete_framebuffers: lookup!(proc, "glDeleteFramebuffers"), + bind_framebuffer: lookup!(proc, "glBindFramebuffer"), + framebuffer_texture: lookup!(proc, "glFramebufferTexture2D"), + check_framebuffer: lookup!(proc, "glCheckFramebufferStatus"), + finish: lookup!(proc, "glFinish"), + flush: lookup!(proc, "glFlush"), + read_pixels: lookup!(proc, "glReadPixels"), + pixel_store: lookup!(proc, "glPixelStorei"), + get_string: lookup!(proc, "glGetString"), + }; + // SAFETY: the context is current. + let renderer = unsafe { + let name = (gl.get_string)(GL_RENDERER); + if name.is_null() { "unknown".into() } else { CStr::from_ptr(name).to_string_lossy().into_owned() } + }; + let (device, display, context) = setup.into_parts(); + Ok(Self { gbm, egl, gl, device, display, context, _node: node, renderer }) + } + + /// For libmpv's OpenGL renderer: looks up GL functions in this context. + pub fn proc_address(&self) -> (crate::ffi::GetProcAddress, *mut c_void) { + (find_proc, self.egl.get_proc_address as *mut c_void) + } + + /// A buffer `width` by `height` in `XRGB8888`, in one of `modifiers` (the compositor's, + /// for this format), or in the driver's own layout if the list is empty. + pub fn target(&self, width: u32, height: u32, modifiers: &[u64]) -> Result { + // Only layouts OpenGL can draw into, not just sample from, and of those the + // compositor's if it said. + let drawable = self.drawable_modifiers(); + let mut usable: Vec = if modifiers.is_empty() { drawable } else { modifiers.iter().copied().filter(|m| drawable.contains(m)).collect() }; + // SAFETY of the block: GBM, EGL and GL calls on a live device and current context, + // with results checked and everything made here freed on failure or in `drop_target`. + unsafe { + // One plane only, for now: a layout with a second (a compression plane, as Intel's + // CCS layouts have) is left out and GBM asked again. + let bo = loop { + let bo = if usable.is_empty() { + (self.gbm.bo_create)(self.device, width, height, FOURCC_XRGB8888, GBM_BO_USE_RENDERING) + } else { + (self.gbm.bo_create_with_modifiers2)(self.device, width, height, FOURCC_XRGB8888, usable.as_ptr(), usable.len() as u32, GBM_BO_USE_RENDERING) + }; + if bo.is_null() { + return Err(format!("GBM won't make a {width}x{height} buffer")); + } + if (self.gbm.bo_get_plane_count)(bo) <= 1 || usable.is_empty() { + break bo; + } + let taken = (self.gbm.bo_get_modifier)(bo); + (self.gbm.bo_destroy)(bo); + usable.retain(|m| *m != taken); + }; + let modifier = (self.gbm.bo_get_modifier)(bo); + let mut planes = Vec::new(); + for plane in 0..(self.gbm.bo_get_plane_count)(bo).max(1) { + let fd = (self.gbm.bo_get_fd_for_plane)(bo, plane); + if fd < 0 { + (self.gbm.bo_destroy)(bo); + return Err("GBM won't export the buffer".into()); + } + planes.push(Plane { fd: OwnedFd::from_raw_fd(fd), stride: (self.gbm.bo_get_stride_for_plane)(bo, plane), offset: (self.gbm.bo_get_offset)(bo, plane) }); + } + let image = self.import(width, height, modifier, &planes); + if image.is_null() { + (self.gbm.bo_destroy)(bo); + return Err("EGL won't take the buffer".into()); + } + let (mut texture, mut fbo) = (0, 0); + (self.gl.gen_textures)(1, &mut texture); + (self.gl.bind_texture)(GL_TEXTURE_2D, texture); + (self.gl.image_target_texture)(GL_TEXTURE_2D, image); + (self.gl.gen_framebuffers)(1, &mut fbo); + (self.gl.bind_framebuffer)(GL_FRAMEBUFFER, fbo); + (self.gl.framebuffer_texture)(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); + let complete = (self.gl.check_framebuffer)(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; + let target = Target { width, height, fourcc: FOURCC_XRGB8888, modifier, planes, fbo, texture, image, bo }; + if !complete { + self.drop_target(target); + return Err("the buffer can't be drawn into".into()); + } + Ok(target) + } + } + + /// The layouts of `XRGB8888` OpenGL on this card can draw into. + pub fn drawable_modifiers(&self) -> Vec { + // SAFETY: a live display; the arrays are sized to the count asked for. + unsafe { + let mut count = 0; + if (self.egl.query_modifiers)(self.display, FOURCC_XRGB8888 as i32, 0, std::ptr::null_mut(), std::ptr::null_mut(), &mut count) == 0 || count <= 0 { + return Vec::new(); + } + let (mut modifiers, mut external) = (vec![0u64; count as usize], vec![0u32; count as usize]); + (self.egl.query_modifiers)(self.display, FOURCC_XRGB8888 as i32, count, modifiers.as_mut_ptr(), external.as_mut_ptr(), &mut count); + modifiers.into_iter().zip(external).take(count as usize).filter(|(_, external)| *external == 0).map(|(m, _)| m).collect() + } + } + + /// An EGL image of a dmabuf's first plane (`XRGB8888` has one). + /// + /// # Safety + /// The context must be current, and `planes` a live dmabuf of that size and layout. + unsafe fn import(&self, width: u32, height: u32, modifier: u64, planes: &[Plane]) -> Ptr { + let plane = &planes[0]; + let mut attributes = vec![ + EGL_WIDTH, + width as i32, + EGL_HEIGHT, + height as i32, + EGL_LINUX_DRM_FOURCC_EXT, + FOURCC_XRGB8888 as i32, + EGL_DMA_BUF_PLANE0_FD_EXT, + plane.fd.as_raw_fd(), + EGL_DMA_BUF_PLANE0_OFFSET_EXT, + plane.offset as i32, + EGL_DMA_BUF_PLANE0_PITCH_EXT, + plane.stride as i32, + ]; + if modifier != MOD_INVALID { + attributes.extend([EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT, modifier as u32 as i32, EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, (modifier >> 32) as u32 as i32]); + } + attributes.push(EGL_NONE); + // SAFETY: as the caller says; EGL takes its own reference to the dmabuf. + unsafe { (self.egl.create_image)(self.display, std::ptr::null_mut(), EGL_LINUX_DMA_BUF_EXT, std::ptr::null_mut(), attributes.as_ptr()) } + } + + pub fn drop_target(&self, target: Target) { + // SAFETY: the target's own objects, made by this context, freed once. + unsafe { + (self.gl.delete_framebuffers)(1, &target.fbo); + (self.gl.delete_textures)(1, &target.texture); + (self.egl.destroy_image)(self.display, target.image); + (self.gbm.bo_destroy)(target.bo); + } + } + + /// Waits until everything drawn so far is in memory, so a frame is whole before another + /// process shows it. + pub fn finish(&self) { + // SAFETY: the context is current. + unsafe { (self.gl.finish)() }; + } + + pub fn flush(&self) { + // SAFETY: the context is current. + unsafe { (self.gl.flush)() }; + } + + /// A dmabuf another process made, as `0x00RRGGBB` words, top row first: how the app's side + /// checks what it was given. + pub fn read_dmabuf(&self, width: u32, height: u32, modifier: u64, planes: &[Plane]) -> Result, String> { + // SAFETY: the context is current, the attributes describe the dmabuf as sent, and the + // read fits the buffer. + unsafe { + let image = self.import(width, height, modifier, planes); + if image.is_null() { + return Err("EGL won't take the dmabuf".into()); + } + let (mut texture, mut fbo) = (0, 0); + (self.gl.gen_textures)(1, &mut texture); + (self.gl.bind_texture)(GL_TEXTURE_2D, texture); + (self.gl.image_target_texture)(GL_TEXTURE_2D, image); + (self.gl.gen_framebuffers)(1, &mut fbo); + (self.gl.bind_framebuffer)(GL_FRAMEBUFFER, fbo); + (self.gl.framebuffer_texture)(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); + // An incomplete framebuffer reads nothing, and the zeroed buffer would pass for black. + let complete = (self.gl.check_framebuffer)(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; + let mut rgba = vec![0u8; width as usize * height as usize * 4]; + if complete { + (self.gl.pixel_store)(GL_PACK_ALIGNMENT, 1); + (self.gl.read_pixels)(0, 0, width as i32, height as i32, GL_RGBA, GL_UNSIGNED_BYTE, rgba.as_mut_ptr() as Ptr); + } + (self.gl.delete_framebuffers)(1, &fbo); + (self.gl.delete_textures)(1, &texture); + (self.egl.destroy_image)(self.display, image); + if !complete { + return Err("the dmabuf can't be read from".into()); + } + Ok(rgba.as_chunks::<4>().0.iter().map(|p| u32::from(p[0]) << 16 | u32::from(p[1]) << 8 | u32::from(p[2])).collect()) + } + } +} + +impl Drop for Gpu { + fn drop(&mut self) { + // SAFETY: this context and display, made by `new`, released once. + unsafe { + (self.egl.make_current)(self.display, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()); + (self.egl.destroy_context)(self.display, self.context); + (self.egl.terminate)(self.display); + (self.gbm.device_destroy)(self.device); + } + } +} + +unsafe extern "C" fn find_proc(get_proc_address: *mut c_void, name: *const c_char) -> *mut c_void { + // SAFETY: `get_proc_address` is EGL's lookup, passed by `Gpu::proc_address`. + unsafe { + let find: unsafe extern "C" fn(*const c_char) -> Ptr = std::mem::transmute(get_proc_address); + find(name) + } +} + +/// Opens the first render node there is, for when the app has no compositor to ask. +pub fn first_render_node() -> Result { + for n in 128..192 { + let path = format!("/dev/dri/renderD{n}"); + if let Ok(file) = std::fs::OpenOptions::new().read(true).write(true).open(&path) { + return Ok(file.into()); + } + } + Err("no render node".into()) +} + +/// The same card's node opened again: a file description of its own, so GEM buffer handles +/// made through it are its own too. Each driver on a card needs one: handles belong to the +/// open file, so two drivers sharing one alias each other's buffers, and when one closes a +/// handle, the other's buffer is gone with it. libmpv's VA-API decoder and OpenGL (Mesa) are +/// two such drivers on Intel and AMD. Only the node's own name under /dev/dri is tried. +pub fn reopen(node: &OwnedFd) -> Option { + let rdev = |fd: RawFd| { + // SAFETY: a zeroed stat is valid, and the descriptor is live. + let mut stat: libc::stat = unsafe { std::mem::zeroed() }; + (unsafe { libc::fstat(fd, &mut stat) } == 0 && stat.st_mode & libc::S_IFMT == libc::S_IFCHR).then_some(stat.st_rdev) + }; + let device = rdev(node.as_raw_fd())?; + let minor = libc::minor(device); + let path = if minor >= 128 { format!("/dev/dri/renderD{minor}") } else { format!("/dev/dri/card{minor}") }; + let file: OwnedFd = std::fs::OpenOptions::new().read(true).write(true).open(path).ok()?.into(); + (rdev(file.as_raw_fd()) == Some(device)).then_some(file) +} + +/// Who made the card behind a render node, from /sys. +pub fn vendor(node: &OwnedFd) -> crate::options::Vendor { + // SAFETY: a zeroed stat is valid, and the descriptor is live. + let mut stat: libc::stat = unsafe { std::mem::zeroed() }; + if unsafe { libc::fstat(node.as_raw_fd(), &mut stat) } != 0 { + return crate::options::Vendor::Other; + } + let (major, minor) = (libc::major(stat.st_rdev), libc::minor(stat.st_rdev)); + let device = format!("/sys/dev/char/{major}:{minor}/device"); + let pci = std::fs::read_to_string(format!("{device}/vendor")).ok().and_then(|v| u32::from_str_radix(v.trim().trim_start_matches("0x"), 16).ok()); + let driver = std::fs::read_link(format!("{device}/driver")).ok().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_default(); + crate::options::Vendor::from_sys(pci, &driver) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A file description of its own: status flags set on one don't show on the other. + /// Skipped with no card (CI). + #[test] + fn a_reopened_node_is_the_same_card_opened_again() { + let Ok(node) = first_render_node() else { + eprintln!("skipped: no render node here"); + return; + }; + let again = reopen(&node).expect("opened again"); + assert_ne!(node.as_raw_fd(), again.as_raw_fd()); + // SAFETY: plain fcntl calls on live descriptors. + unsafe { + let flags = libc::fcntl(node.as_raw_fd(), libc::F_GETFL); + assert_eq!(libc::fcntl(node.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK), 0); + assert_eq!(libc::fcntl(again.as_raw_fd(), libc::F_GETFL) & libc::O_NONBLOCK, 0, "a description of its own, not a dup"); + } + let not_a_card: OwnedFd = std::fs::File::open("/dev/null").unwrap().into(); + assert!(reopen(¬_a_card).is_none(), "/dev/null is a character device, but not this card"); + } + + /// Needs a graphics card, so it's left out of CI: `cargo test -- --ignored`. + #[test] + #[ignore] + fn a_target_is_one_dmabuf_plane_that_draws() { + let gpu = Gpu::new(first_render_node().unwrap()).unwrap(); + let target = gpu.target(1920, 1080, &[]).unwrap(); + assert_eq!(target.planes.len(), 1, "{:?}", target.planes); + assert!(target.planes[0].stride >= 1920 * 4); + println!("modifier {:#x}, drawable {:x?}", target.modifier, gpu.drawable_modifiers()); + gpu.drop_target(target); + } +} diff --git a/src/gpu_helper.rs b/src/gpu_helper.rs new file mode 100644 index 0000000..9e2806b --- /dev/null +++ b/src/gpu_helper.rs @@ -0,0 +1,691 @@ +//! A player in another process that draws on the graphics card and hands its frames over as +//! dmabufs: the GPU counterpart of `helper`, for an app that shows video with `linux-dmabuf`. +//! +//! The app gives the player the file (descriptor 3), one end of a `SOCK_SEQPACKET` socket +//! (4) and the render node of the card its compositor uses (5). The player decodes, on the +//! card where it can, draws each frame with libmpv's OpenGL renderer into one of a few GBM +//! buffers, and says which buffer holds the new frame. A buffer's dmabuf goes to the app once, +//! with the message that first describes it; after that only its number does. The app +//! attaches the buffers to a surface and says when the compositor has let one go. Frames never +//! leave the card, and the player never sees the app's Wayland connection. +//! +//! Every message is one packet of text, so none can be split or run together. Descriptors +//! ride on the `buffer` message only, and the app checks each message before believing it. + +use std::ffi::c_int; +use std::fs::File; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; +use std::os::unix::process::CommandExt; +use std::process::{Child, Command, Stdio}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use crate::gpu::{GL_RGBA8, Gpu, Target}; +use crate::helper::{EXIT_BAD_START, EXIT_CANT_PLAY, EXIT_NO_MPV, PlayState}; +use crate::options::{Options, RenderPath}; +use crate::player::{Event, Player, Request}; +use crate::render::{GlRender, Native}; + +pub const FD_FILE: c_int = 3; +pub const FD_SOCKET: c_int = 4; +pub const FD_NODE: c_int = 5; +/// Buffers in turn: one on screen, one waiting for the compositor, one being drawn. +pub const SLOTS: usize = 3; +/// The largest frame drawn. A bigger window scales it up. +pub const MAX_W: u32 = 7680; +pub const MAX_H: u32 = 4320; +const MAX_MESSAGE: usize = 256; +/// The most a driver pads a buffer's row by: tiled layouts round rows up to their tile's +/// width, a few KiB at most. +const MAX_ROW_PADDING: u64 = 64 * 1024; +const REPORT_EVERY: Duration = Duration::from_millis(100); + +/// What the player says. +#[derive(Clone, Debug, PartialEq)] +pub enum Said { + Hello, + /// A buffer's layout. Its dmabuf came with this message. + Buffer { + slot: usize, + width: u32, + height: u32, + fourcc: u32, + modifier: u64, + stride: u32, + offset: u32, + }, + /// The newest frame is in this buffer, finished drawing. + Frame { + slot: usize, + }, + State(PlayState), + /// Frames libmpv dropped or showed late, so far. + Dropped { + decoder: u64, + late: u64, + }, + /// How it's decoding, once the first frame is drawn: a libmpv hardware decoder's name, + /// such as `nvdec` or `vaapi`, or `software`. + Decoder(String), + NoVideo, + CantPlay, +} + +/// A message from the player, or `None` if it isn't a sensible one. +pub fn parse_said(line: &str) -> Option { + let words: Vec<&str> = line.split_ascii_whitespace().collect(); + let n = |i: usize| words.get(i)?.parse::().ok(); + let small = |i: usize| u32::try_from(n(i)?).ok(); + let slot = |i: usize| n(i).map(|s| s as usize).filter(|s| *s < SLOTS); + match (words.first().copied()?, words.len()) { + ("hello", 1) => Some(Said::Hello), + ("novideo", 1) => Some(Said::NoVideo), + ("cantplay", 1) => Some(Said::CantPlay), + ("frame", 2) => Some(Said::Frame { slot: slot(1)? }), + ("decoder", 2) => { + let name = words[1]; + (name.len() <= 32 && name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')).then(|| Said::Decoder(name.to_owned())) + } + ("dropped", 3) => Some(Said::Dropped { decoder: n(1)?, late: n(2)? }), + ("buffer", 8) => { + let (width, height, stride) = (small(2)?, small(3)?, small(6)?); + // Only the one format the player makes, and a row no longer than a padded one. + let row = u64::from(width) * 4; + if width == 0 || height == 0 || width > MAX_W || height > MAX_H || u64::from(stride) < row || u64::from(stride) > row + MAX_ROW_PADDING || small(4)? != crate::gpu::FOURCC_XRGB8888 { + return None; + } + Some(Said::Buffer { slot: slot(1)?, width, height, fourcc: small(4)?, modifier: n(5)?, stride, offset: small(7)? }) + } + ("state", 7) => match crate::helper::parse_said(line)? { + crate::helper::Said::State(state) => Some(Said::State(state)), + _ => None, + }, + _ => None, + } +} + +// ---- Packets with descriptors ---- + +/// Sends one packet, with `fds` attached if there are any. +pub fn send(socket: &OwnedFd, text: &str, fds: &[RawFd]) -> std::io::Result<()> { + let mut iov = libc::iovec { iov_base: text.as_ptr() as *mut _, iov_len: text.len() }; + // SAFETY: a zeroed msghdr is valid; the buffers below outlive the call. + let mut msg: libc::msghdr = unsafe { std::mem::zeroed() }; + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + // SAFETY: arithmetic on a length. + let space = unsafe { libc::CMSG_SPACE(std::mem::size_of_val(fds) as u32) } as usize; + let mut control = vec![0u8; space]; + if !fds.is_empty() { + msg.msg_control = control.as_mut_ptr() as *mut _; + msg.msg_controllen = space; + // SAFETY: the control buffer is sized for one header with these descriptors. + unsafe { + let header = libc::CMSG_FIRSTHDR(&msg); + (*header).cmsg_level = libc::SOL_SOCKET; + (*header).cmsg_type = libc::SCM_RIGHTS; + (*header).cmsg_len = libc::CMSG_LEN(std::mem::size_of_val(fds) as u32) as usize; + std::ptr::copy_nonoverlapping(fds.as_ptr(), libc::CMSG_DATA(header) as *mut RawFd, fds.len()); + } + } + // SAFETY: a valid socket and message. + let sent = unsafe { libc::sendmsg(socket.as_raw_fd(), &msg, libc::MSG_NOSIGNAL) }; + if sent < 0 { Err(std::io::Error::last_os_error()) } else { Ok(()) } +} + +/// Receives one packet and any descriptors with it. `None` at the end. A packet too long, +/// or with more descriptors than one, is cut short and marked so the caller drops it. +pub fn receive(socket: &OwnedFd) -> std::io::Result)>> { + let mut buf = [0u8; MAX_MESSAGE]; + let mut iov = libc::iovec { iov_base: buf.as_mut_ptr() as *mut _, iov_len: buf.len() }; + let space = unsafe { libc::CMSG_SPACE((4 * size_of::()) as u32) } as usize; + let mut control = vec![0u8; space]; + // SAFETY: a zeroed msghdr is valid; the buffers outlive the call. + let mut msg: libc::msghdr = unsafe { std::mem::zeroed() }; + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + msg.msg_control = control.as_mut_ptr() as *mut _; + msg.msg_controllen = space; + // SAFETY: a valid socket and message. Received descriptors are close-on-exec. + let got = unsafe { libc::recvmsg(socket.as_raw_fd(), &mut msg, libc::MSG_CMSG_CLOEXEC) }; + if got < 0 { + return Err(std::io::Error::last_os_error()); + } + if got == 0 { + return Ok(None); + } + let mut fds = Vec::new(); + // SAFETY: walking the control messages the kernel just wrote, taking ownership of each + // descriptor it passed, so none leak even if the message is then refused. + unsafe { + let mut header = libc::CMSG_FIRSTHDR(&msg); + while !header.is_null() { + if (*header).cmsg_level == libc::SOL_SOCKET && (*header).cmsg_type == libc::SCM_RIGHTS { + let count = ((*header).cmsg_len - libc::CMSG_LEN(0) as usize) / size_of::(); + let data = libc::CMSG_DATA(header) as *const RawFd; + for i in 0..count { + fds.push(OwnedFd::from_raw_fd(std::ptr::read_unaligned(data.add(i)))); + } + } + header = libc::CMSG_NXTHDR(&msg, header); + } + } + let cut = msg.msg_flags & (libc::MSG_TRUNC | libc::MSG_CTRUNC) != 0; + let text = if cut { String::new() } else { String::from_utf8_lossy(&buf[..got as usize]).into_owned() }; + Ok(Some((text, fds))) +} + +// ---- The app's side ---- + +pub struct Started { + pub child: Child, + pub socket: OwnedFd, +} + +/// Starts a player, as `helper::start` does, with `node` the render node of the compositor's +/// card. `command` is the app's helper command, jailed or not, with its helper argument. +/// With `debug`, the player sends libmpv's log as `log` messages. +pub fn start(command: Command, file: File, node: OwnedFd, size: (u32, u32), debug: bool) -> std::io::Result { + start_with(command, Some(file), node, size, debug) +} + +/// Starts a player with no file yet, warming up: OpenGL, libmpv and its renderer start now, +/// so a file given later with `load` shows sooner. It says `hello` once it's ready. +pub fn start_warm(command: Command, node: OwnedFd, size: (u32, u32), debug: bool) -> std::io::Result { + start_with(command, None, node, size, debug) +} + +/// Gives a player started warm its file. +pub fn load(socket: &OwnedFd, file: &File) -> std::io::Result<()> { + send(socket, "load", &[file.as_raw_fd()]) +} + +fn start_with(mut command: Command, file: Option, node: OwnedFd, size: (u32, u32), debug: bool) -> std::io::Result { + let warm = file.is_none(); + // Descriptor 3 is always something: the file, or nothing to read for a warm start. + let file = match file { + Some(file) => file, + None => File::open("/dev/null")?, + }; + let (ours, theirs) = socketpair()?; + let high = |fd: RawFd| -> std::io::Result { + // SAFETY: duplicating a descriptor we hold, taking ownership of a good result. + let copy = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 64) }; + if copy < 0 { Err(std::io::Error::last_os_error()) } else { Ok(unsafe { OwnedFd::from_raw_fd(copy) }) } + }; + let (file, theirs, node) = (high(file.as_raw_fd())?, high(theirs.as_raw_fd())?, high(node.as_raw_fd())?); + let fds = [file.as_raw_fd(), theirs.as_raw_fd(), node.as_raw_fd()]; + command.arg(size.0.clamp(1, MAX_W).to_string()).arg(size.1.clamp(1, MAX_H).to_string()); + if debug { + command.arg("debug"); + } + if warm { + command.arg("warm"); + } + command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); + // SAFETY: only async-signal-safe calls. + unsafe { + command.pre_exec(move || { + for (from, to) in fds.iter().zip([FD_FILE, FD_SOCKET, FD_NODE]) { + if libc::dup2(*from, to) < 0 { + return Err(std::io::Error::last_os_error()); + } + } + if libc::close_range((FD_NODE + 1) as libc::c_uint, libc::c_uint::MAX, libc::CLOSE_RANGE_CLOEXEC as libc::c_int) != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let child = command.spawn()?; + drop(command); + Ok(Started { child, socket: ours }) +} + +fn socketpair() -> std::io::Result<(OwnedFd, OwnedFd)> { + let mut pair = [0; 2]; + // SAFETY: a valid array for the two descriptors. + if unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC, 0, pair.as_mut_ptr()) } != 0 { + return Err(std::io::Error::last_os_error()); + } + // SAFETY: two new descriptors, owned by nothing else. + Ok(unsafe { (OwnedFd::from_raw_fd(pair[0]), OwnedFd::from_raw_fd(pair[1])) }) +} + +// ---- The player's side ---- + +#[derive(Default)] +struct Shared { + /// Woken for libmpv's events and frames, and for the app's messages. + pending: bool, + /// Buffers the app has, and hasn't given back. + held: [bool; SLOTS], + size: (u32, u32), + commands: Vec, + /// A file to play from a `load` message, for a player started warm. + file: Option, + gone: bool, +} + +struct Wake { + shared: Mutex, + ready: Condvar, +} + +impl Wake { + fn with(&self, f: impl FnOnce(&mut Shared) -> T) -> T { + let mut shared = self.shared.lock().unwrap_or_else(|e| e.into_inner()); + let result = f(&mut shared); + shared.pending = true; + self.ready.notify_one(); + result + } + + fn wait(&self, deadline: Option) -> Shared { + let shared = self.shared.lock().unwrap_or_else(|e| e.into_inner()); + let mut shared = match deadline { + Some(at) => self.ready.wait_timeout_while(shared, at.saturating_duration_since(Instant::now()), |s| !s.pending).unwrap_or_else(|e| e.into_inner()).0, + None => self.ready.wait_while(shared, |s| !s.pending).unwrap_or_else(|e| e.into_inner()), + }; + shared.pending = false; + Shared { pending: false, held: shared.held, size: shared.size, commands: std::mem::take(&mut shared.commands), file: shared.file.take(), gone: shared.gone } + } +} + +/// Runs a GPU player, and never returns. As `helper::run`, with `options` on the GPU path, +/// except that `lock_down` runs first, before any other thread exists (see +/// `jail::lock_down_gpu_helper`). +pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: impl FnOnce() -> bool) -> ! { + let parse = |i: usize| args.get(i).and_then(|a| a.parse::().ok()); + let (Some(w), Some(h)) = (parse(0), parse(1)) else { std::process::exit(EXIT_BAD_START) }; + // `debug` after the size: libmpv's log goes to the app as `log` messages, for a player + // that can't write a log file anywhere. + let debug = args.get(2..).is_some_and(|rest| rest.iter().any(|a| a == "debug")); + // `warm`: no file yet; it comes with a `load` message. + let warm = args.get(2..).is_some_and(|rest| rest.iter().any(|a| a == "warm")); + if options.render != RenderPath::Gpu { + std::process::exit(EXIT_BAD_START); + } + // SAFETY: plain integers. + unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL as libc::c_ulong, 0, 0, 0) }; + // SAFETY: descriptors `start` put there, owned by nothing else in this process. + let (socket, node) = unsafe { (OwnedFd::from_raw_fd(FD_SOCKET), OwnedFd::from_raw_fd(FD_NODE)) }; + // libmpv's VA-API decoder gets the card opened again, not OpenGL's descriptor: sharing + // one, Mesa and iHD closed each other's buffers, and Intel stopped decoding 1080p after + // a few frames ("Failed to end picture decode issue: 23"). As the jail grants only the + // card's node, the old one stays as the fallback. + let decoder_node = crate::gpu::reopen(&node); + let node_fd = decoder_node.as_ref().map_or(node.as_raw_fd(), |n| n.as_raw_fd()); + // First, while this is the only thread, so every thread libmpv and the drivers start + // inherits it. + if !lock_down() { + std::process::exit(sandbox_code); + } + // libmpv starts while the card's OpenGL does: the two take about 50 and 110 ms. + let began = Instant::now(); + let options = Options { start_paused: true, ..*options }; + // The hardware decoding asked for, to go back to after a file falls back to software. + let hwdec = options.pairs().into_iter().find(|(name, _)| *name == "hwdec").map_or("no", |(_, value)| value); + let starting = std::thread::spawn(move || Player::new(&options)); + let Ok(gpu) = Gpu::new(node) else { std::process::exit(EXIT_CANT_PLAY) }; + let gpu_ready = began.elapsed(); + let player = match starting.join() { + Ok(Ok(player)) => player, + Ok(Err(crate::player::Error::Load(_))) => std::process::exit(EXIT_NO_MPV), + _ => std::process::exit(EXIT_CANT_PLAY), + }; + let (find, context) = gpu.proc_address(); + // SAFETY: the context is current on this thread for the life of the process, and the + // render node stays open, inside `gpu` or in `decoder_node`, until it exits. + let mpv_ready = began.elapsed(); + let Ok(mut render) = (unsafe { GlRender::new(&player, find, context, Native::RenderNode(node_fd)) }) else { std::process::exit(EXIT_CANT_PLAY) }; + let render_ready = began.elapsed(); + // Where start-up and each frame's finish go, for `debug`. + let mut finishing = (Duration::ZERO, 0u32); + let wake = Arc::new(Wake { shared: Mutex::new(Shared { size: (w.clamp(1, MAX_W), h.clamp(1, MAX_H)), ..Shared::default() }), ready: Condvar::new() }); + let (for_events, for_frames) = (wake.clone(), wake.clone()); + player.on_wakeup(move || for_events.with(|_| ())); + if debug && let Ok(logs) = socket.try_clone() { + player.on_log(c"v", move |module, text| { + let mut line: String = format!("log {module}: {text}").chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); + // In bytes, as a packet is: a longer one would be cut and dropped. + line.truncate(line.floor_char_boundary(MAX_MESSAGE - 1)); + let _ = send(&logs, &line, &[]); + }); + } + render.on_update(move || for_frames.with(|_| ())); + let say = |text: &str| { + if send(&socket, text, &[]).is_err() { + std::process::exit(0); + } + }; + say("hello"); + if debug { + say(&format!("log timing: OpenGL {} ms, libmpv {} ms, its renderer {} ms", gpu_ready.as_millis(), mpv_ready.as_millis(), render_ready.as_millis())); + } + let reading = socket.try_clone().unwrap_or_else(|_| std::process::exit(EXIT_CANT_PLAY)); + let for_reader = wake.clone(); + let spawned = std::thread::Builder::new().name("app".into()).spawn(move || { + while let Ok(Some((text, mut fds))) = receive(&reading) { + for_reader.with(|shared| { + let mut words = text.split_ascii_whitespace(); + match words.next() { + Some("release") => { + if let Some(slot) = words.next().and_then(|s| s.parse::().ok()).filter(|s| *s < SLOTS) { + shared.held[slot] = false; + } + } + Some("size") => { + let mut n = || words.next().and_then(|s| s.parse::().ok()); + if let (Some(w), Some(h)) = (n(), n()) { + shared.size = (w.clamp(1, MAX_W), h.clamp(1, MAX_H)); + } + } + // The newest file chosen: one still waiting to be loaded is dropped for it. + Some("load") if fds.len() == 1 => shared.file = fds.pop(), + _ => shared.commands.push(text.clone()), + } + }); + } + for_reader.with(|shared| shared.gone = true); + }); + if spawned.is_err() { + std::process::exit(EXIT_CANT_PLAY); + } + if !warm && player.load_fd(FD_FILE).is_err() { + std::process::exit(EXIT_CANT_PLAY); + } + // The file loaded last, open for as long as libmpv may read it, and the one before, which + // libmpv may still be closing. + let mut files: [Option; 2] = [None, None]; + + let mut targets: [Option; SLOTS] = [None, None, None]; + let mut next = 0usize; + let mut state = PlayState { volume: 100.0, paused: true, ..PlayState::default() }; + let (mut reported, mut last_report) = (String::new(), Instant::now() - REPORT_EVERY); + let mut dropped_reported = String::new(); + let mut natural: Option<(f64, f64)> = None; + // The picture's size, decoder and dropped frames, as libmpv reports them. Never asked for + // on this thread: asking waits on libmpv's core, which may be waiting for this thread to + // draw, and then a frame is lost (a cover's only one, for a start). + let mut shown_size = (0.0, 0.0); + let mut decoder: Option<&'static str> = None; + let (mut decoder_drops, mut late_frames) = (0u64, 0u64); + let mut first_drawn = false; + let mut wanted_paused = true; + let mut told_decoder = false; + // Hardware decoding in use, and whether this file has already fallen back from it. + let (mut hardware, mut fell_back) = (false, false); + // A new frame not drawn yet, as every buffer was held; and the size of the last drawn. + let (mut owed, mut drawn_size) = (false, None); + // A restart whose draw waits for the picture's size. + let mut pending_restart = false; + loop { + let deadline = (state.line() != reported).then_some(last_report + REPORT_EVERY); + let woken = wake.wait(deadline); + if woken.gone { + std::process::exit(0); + } + if let Some(file) = woken.file { + // Hardware decoding again, if the last file fell back to software. + if fell_back { + let _ = player.command(&[b"set", b"hwdec", hwdec.as_bytes()]); + } + // A new file: its own decoder, frames and fallback. The last file's frame may still + // be drawn before this one is loaded; that only starts this one a moment early. + (fell_back, first_drawn, told_decoder, hardware, decoder, owed, drawn_size) = (false, false, false, false, None, false, None); + pending_restart = false; + if player.load_fd(file.as_raw_fd()).is_err() { + say("cantplay"); + } + files = [Some(file), files[0].take()]; + } + for command in &woken.commands { + let mut words = command.split_ascii_whitespace(); + let number = |w: Option<&str>| w.and_then(|w| w.parse::().ok()).filter(|n| n.is_finite()); + let _ = match words.next() { + Some("pause") => { + wanted_paused = true; + player.set_paused(true) + } + Some("play") => { + wanted_paused = false; + // Before the first frame is drawn, it starts once that's on screen. + if first_drawn { player.play() } else { Ok(()) } + } + Some("seek") => number(words.next()).map_or(Ok(()), |by| player.seek_by(by)), + Some("seekat") => number(words.next()).map_or(Ok(()), |at| player.seek_to(at)), + Some("volume") => number(words.next()).map_or(Ok(()), |v| player.set_volume(v.clamp(0.0, 100.0))), + Some("mute") => player.set_muted(true), + Some("unmute") => player.set_muted(false), + _ => Ok(()), + }; + } + let (mut urgent, mut restarted) = (false, false); + while let Some(event) = player.next_event() { + match event { + Event::Shutdown => std::process::exit(0), + Event::Loaded { video } => { + if !video { + say("novideo"); + } + } + Event::Failed | Event::Refused(Request::Load) => say("cantplay"), + Event::Refused(_) | Event::Answered(_) => {} + Event::VideoChanged => {} + // Width and height come one at a time: the size is settled after the batch. + Event::Width(w) => shown_size.0 = w, + Event::Height(h) => shown_size.1 = h, + Event::Decoder(name) => decoder = name, + Event::DecoderDrops(n) => decoder_drops = n, + Event::LateFrames(n) => late_frames = n, + Event::Position(at) => state.position = at, + Event::Duration(d) => (state.duration, urgent) = (d, true), + Event::Paused(p) => (state.paused, urgent) = (p, true), + Event::Volume(v) => (state.volume, urgent) = (v, true), + Event::Muted(m) => (state.muted, urgent) = (m, true), + // A hardware decoder that stops giving frames without an error ends the file + // early (Intel's iHD did, at 1080p). libmpv falls back to the CPU only on an + // error, so this does: the decoder starts again in software where the picture + // stopped, and the video plays on. + Event::Ended(true) if falls_back(hardware && !fell_back, state.position, state.duration) => { + (hardware, fell_back, told_decoder, decoder) = (false, true, false, None); + let _ = player.command(&[b"set", b"hwdec", b"no"]); + if !wanted_paused { + let _ = player.set_paused(false); + } + if debug { + say(&format!("log fallback: hardware decoding ended at {:.3} s of {:.3} s; on in software", state.position, state.duration)); + } + } + Event::Ended(e) => { + (state.ended, urgent) = (e, true); + if debug && e && finishing.1 > 0 { + say(&format!("log timing: finishing a frame took {:.2} ms on average over {} frames", finishing.0.as_secs_f64() * 1000.0 / f64::from(finishing.1), finishing.1)); + } + } + // libmpv gives up waiting for a frame to be drawn after a while (200 ms) and + // stops flagging it as new, though it's still the one on screen. That happens + // when this thread is held up in a call that waits on libmpv's core while the + // core waits on this thread: a cover's one frame comes at once, while + // `VideoChanged` asks for the size. Once playback (re)starts, the current + // frame is drawn whatever the flag says, so a lost wake-up can't leave the + // picture undrawn and the player paused for good. + Event::Restarted => (urgent, restarted) = (true, true), + } + } + let now = Some(shown_size).filter(|n| n.0 > 0.0 && n.1 > 0.0); + if now != natural { + natural = now; + // The buffers are made now, before the first frame is drawn, so making them isn't + // in the way of showing it. + if let Some(natural) = natural { + let size = fit(natural, woken.size); + for (slot, _) in woken.held.iter().enumerate().filter(|(_, held)| !**held) { + prepare(&gpu, &socket, &mut targets, slot, size); + } + } + } + // After the size is settled, which may have come in the same batch. + // A restart while the size is still unknown is kept until it's known. + pending_restart |= restarted; + if natural.is_some() { + owed |= std::mem::take(&mut pending_restart); + } + // Drawn before the state is reported, so the last frame reaches the app before it + // hears the video has ended. + 'draw: { + owed |= render.new_frame(); + // libmpv tells the picture's size only once its core is free, and the core waits + // for a new frame to be drawn: without the size yet, the frame is drawn at the + // window's size (libmpv keeps its shape, with borders), and again at its own + // size once that comes. + let (fw, fh) = match natural { + Some(natural) => fit(natural, woken.size), + None if owed => woken.size, + None => break 'draw, + }; + // A new size draws the frame again, paused or stopped too. + let resized = drawn_size.is_some_and(|size| size != (fw, fh)); + if !owed && !resized { + break 'draw; + } + // The next buffer the app isn't holding. With none free, the frame waits for one: + // the app giving one back wakes this loop. + let Some(slot) = (0..SLOTS).map(|i| (next + i) % SLOTS).find(|s| !woken.held[*s]) else { break 'draw }; + prepare(&gpu, &socket, &mut targets, slot, (fw, fh)); + let target = targets[slot].as_ref().expect("made above"); + // SAFETY: the context is current and the framebuffer is this size. + if unsafe { render.render(target.fbo as i32, fw as i32, fh as i32, GL_RGBA8, false) }.is_ok() { + // Whole before the app shows it. An explicit fence would let the card run ahead. + let finish = Instant::now(); + gpu.finish(); + finishing = (finishing.0 + finish.elapsed(), finishing.1 + 1); + render.report_swap(); + (owed, drawn_size) = (false, Some((fw, fh))); + wake.with(|shared| shared.held[slot] = true); + say(&format!("frame {slot}")); + // Held paused until now, so the first frame is drawn without hurrying and none is + // dropped while the decoder and the card warm up. + if !first_drawn { + first_drawn = true; + if !wanted_paused { + let _ = player.set_paused(false); + } + } + next = (slot + 1) % SLOTS; + } + } + // Once a frame is on screen and libmpv has said how it's decoding. + if first_drawn + && !told_decoder + && let Some(name) = decoder + { + told_decoder = true; + hardware = name != "software"; + say(&format!("decoder {name}")); + } + let line = state.line(); + if line != reported && (urgent || last_report.elapsed() >= REPORT_EVERY) { + say(&line); + let dropped = format!("dropped {decoder_drops} {late_frames}"); + if dropped != dropped_reported && parse_said(&dropped).is_some() { + say(&dropped); + dropped_reported = dropped; + } + reported = line; + last_report = Instant::now(); + } + } +} + +/// Whether a file that ended at `position` of `duration` seconds stopped early, and should +/// go on in software: only with hardware decoding that hasn't fallen back already, and +/// more than a second short of a known length. A file that really is shorter than it says +/// (cut off while it was copied) costs one start in software before it ends there too. +fn falls_back(hardware: bool, position: f64, duration: f64) -> bool { + hardware && duration > 0.0 && position + 1.0 < duration +} + +/// Makes sure `slot` has a buffer of `size`, making and announcing a new one if not. +fn prepare(gpu: &Gpu, socket: &OwnedFd, targets: &mut [Option; SLOTS], slot: usize, size: (u32, u32)) { + if targets[slot].as_ref().is_some_and(|t| (t.width, t.height) != size) { + gpu.drop_target(targets[slot].take().expect("checked")); + } + if targets[slot].is_some() { + return; + } + let Ok(target) = gpu.target(size.0, size.1, &[]) else { std::process::exit(EXIT_CANT_PLAY) }; + let plane = &target.planes[0]; + let text = format!("buffer {slot} {} {} {} {} {} {}", size.0, size.1, target.fourcc, target.modifier, plane.stride, plane.offset); + if target.planes.len() != 1 || send(socket, &text, &[plane.fd.as_raw_fd()]).is_err() { + std::process::exit(EXIT_CANT_PLAY); + } + targets[slot] = Some(target); +} + +/// The largest size with the picture's shape that fits in `wanted`, at least one pixel. +fn fit(natural: (f64, f64), wanted: (u32, u32)) -> (u32, u32) { + let scale = (wanted.0 as f64 / natural.0).min(wanted.1 as f64 / natural.1); + (((natural.0 * scale).round() as u32).clamp(1, MAX_W), ((natural.1 * scale).round() as u32).clamp(1, MAX_H)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hardware_decoding_that_ends_early_falls_back_once() { + assert!(falls_back(true, 0.233, 5.0), "Intel's iHD stopped after 7 frames of 150"); + assert!(!falls_back(true, 4.967, 5.0), "the real end"); + assert!(!falls_back(false, 0.233, 5.0), "software, or fallen back already"); + assert!(!falls_back(true, 0.0, 0.0), "no known length"); + } + + #[test] + fn sensible_messages_parse() { + assert_eq!(parse_said("hello"), Some(Said::Hello)); + assert_eq!(parse_said("frame 2"), Some(Said::Frame { slot: 2 })); + assert_eq!(parse_said("dropped 3 4"), Some(Said::Dropped { decoder: 3, late: 4 })); + assert_eq!(parse_said("decoder nvdec"), Some(Said::Decoder("nvdec".into()))); + assert_eq!(parse_said("decoder ../../x"), None); + let buffer = Said::Buffer { slot: 1, width: 1920, height: 1080, fourcc: crate::gpu::FOURCC_XRGB8888, modifier: 0, stride: 7680, offset: 0 }; + assert_eq!(parse_said(&format!("buffer 1 1920 1080 {} 0 7680 0", crate::gpu::FOURCC_XRGB8888)), Some(buffer)); + assert!(matches!(parse_said("state 1 2 0 100 0 0"), Some(Said::State(_)))); + } + + #[test] + fn nonsense_is_refused() { + let xr24 = crate::gpu::FOURCC_XRGB8888; + for line in [ + "".to_owned(), + "frame 3".into(), + "frame".into(), + "frame 1 2".into(), + format!("buffer 3 10 10 {xr24} 0 40 0"), + format!("buffer 0 10 10 {xr24} 0 39 0"), + format!("buffer 0 0 10 {xr24} 0 40 0"), + format!("buffer 0 7681 10 {xr24} 0 30724 0"), + format!("buffer 0 10 10 {xr24} 0 40"), + "buffer 0 10 10 1 0 40 0".into(), + format!("buffer 0 10 10 {xr24} 0 {} 0", 40 + 64 * 1024 + 1), + "dropped 1".into(), + "hello again".into(), + "exec sh".into(), + ] { + assert_eq!(parse_said(&line), None, "{line}"); + } + } + + #[test] + fn descriptors_cross_the_socket() { + let (a, b) = socketpair().unwrap(); + let file = File::open("/dev/null").unwrap(); + send(&a, "buffer 0 1 1 1 0 4 0", &[file.as_raw_fd()]).unwrap(); + let (text, fds) = receive(&b).unwrap().unwrap(); + assert_eq!(text, "buffer 0 1 1 1 0 4 0"); + assert_eq!(fds.len(), 1); + drop(a); + assert!(receive(&b).unwrap().is_none(), "the end of the other side"); + } +} diff --git a/src/helper.rs b/src/helper.rs index a91fb40..2086ad6 100644 --- a/src/helper.rs +++ b/src/helper.rs @@ -25,7 +25,7 @@ use rustix::mm::{MapFlags, ProtFlags, mmap, munmap}; use rustix::pipe::{PipeFlags, pipe_with}; use crate::options::{Options, RenderPath}; -use crate::player::{Event, Player}; +use crate::player::{Event, Player, Request}; use crate::render::{SwFormat, SwRender}; /// How a player ended, besides the codes the app's own sandbox uses. @@ -84,7 +84,7 @@ pub struct PlayState { } impl PlayState { - fn line(&self) -> String { + pub(crate) fn line(&self) -> String { format!("state {:.3} {:.3} {} {:.0} {} {}", self.position, self.duration, u8::from(self.paused), self.volume, u8::from(self.muted), u8::from(self.ended)) } } @@ -598,6 +598,9 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp let mut last_size = (0, 0); let mut have_video = false; let mut natural: Option<(f64, f64)> = None; + // The picture's size as libmpv reports it, never asked for: asking waits on libmpv's core, + // which may be waiting for this thread to draw. + let mut shown_size = (0.0, 0.0); loop { // Waits with no timer unless a position change is waiting to be reported. let line = state.line(); @@ -618,11 +621,11 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp 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::Failed | Event::Refused(Request::Load) => said("cantplay"), + // Width and height come one at a time: the size is settled after the batch. + Event::Width(w) => shown_size.0 = w, + Event::Height(h) => shown_size.1 = h, + Event::VideoChanged | Event::Decoder(_) | Event::DecoderDrops(_) | Event::LateFrames(_) | Event::Refused(_) | Event::Answered(_) => {} Event::Position(at) => state.position = at, Event::Duration(d) => (state.duration, urgent) = (d, true), Event::Paused(p) => (state.paused, urgent) = (p, true), @@ -639,6 +642,11 @@ pub fn run(args: &[String], options: &Options, sandbox_code: i32, lock_down: imp reported = line; last_report = Instant::now(); } + let now = Some(shown_size).filter(|n| n.0 > 0.0 && n.1 > 0.0); + if now != natural { + natural = now; + last_size = (0, 0); + } let new_frame = render.new_frame(); let wanted = (size.0.load(Ordering::Relaxed), size.1.load(Ordering::Relaxed)); let Some(natural) = natural.filter(|_| have_video) else { continue }; diff --git a/src/jail.rs b/src/jail.rs index cabaaf9..a02d22c 100644 --- a/src/jail.rs +++ b/src/jail.rs @@ -7,6 +7,7 @@ //! clients record too, so with sound on that can include the microphone. use std::ffi::OsStr; +use std::os::fd::{AsRawFd, FromRawFd}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use std::process::Command; @@ -26,6 +27,9 @@ pub const RULES: &[(&str, &[&str])] = &[ ("--symlink", &["usr/lib", "/lib64"]), // Finding libraries without this works, but searches every folder for each one. ("--ro-bind-try", &["/etc/ld.so.cache", "/etc/ld.so.cache"]), + // Debian's alternatives: some libraries are links through here (libblas, which libmpv + // needs there). Links only, no settings. + ("--ro-bind-try", &["/etc/alternatives", "/etc/alternatives"]), ("--dev", &["/dev"]), ("--tmpfs", &["/tmp"]), // An environment with nothing of the user's in it. @@ -47,6 +51,12 @@ pub fn arguments(executable: &Path, sound_socket: Option<&Path>) -> Vec args.extend(values.iter().map(|value| (*value).to_owned())); }; for (option, values) in RULES { + // Debian and Fedora keep the 64-bit loader in /usr/lib64 (or a link there); Arch keeps + // everything in /usr/lib. Point /lib64 at whichever this system has. + if *values == ["usr/lib", "/lib64"] && Path::new("/usr/lib64").is_dir() { + rule(option, &["usr/lib64", "/lib64"]); + continue; + } rule(option, values); } rule("--ro-bind", &[&executable.to_string_lossy(), JAILED_SELF]); @@ -58,6 +68,145 @@ pub fn arguments(executable: &Path, sound_socket: Option<&Path>) -> Vec args } +/// bubblewrap's arguments for a GPU helper on a card made by `vendor`: the jail every player +/// gets, plus that card's device files, which drawing and decoding on it need, and nothing +/// for any other maker. That's the drivers' attack surface too, which Mike accepted for this +/// (2026-12-02). +pub fn gpu_arguments(executable: &Path, vendor: crate::options::Vendor) -> Vec { + let mut args = arguments(executable, None); + let run = args.len() - 2; + // A user namespace of the jail's own. The helper's seccomp filter (`forbid_memory_writes`) + // keeps it from making another inside: one would give back the privileges the jail drops, + // enough to mount a procfs of its own and reach /proc/self/mem with no /proc granted. + // bubblewrap's `--disable-userns` would do the same, but it writes + // /proc/sys/user/max_user_namespaces, which is read-only in an LXC container, so the jail + // wouldn't start in one. + let mut grants = vec!["--unshare-user".to_owned()]; + grants.extend(["--dev-bind".to_owned(), "/dev/dri".to_owned(), "/dev/dri".to_owned()]); + // Drivers find the card's details in /sys. + grants.extend(["--ro-bind".to_owned(), "/sys".to_owned(), "/sys".to_owned()]); + if vendor == crate::options::Vendor::Nvidia { + // NVIDIA's driver has its own device files beside the DRM ones. + for name in ["nvidiactl", "nvidia0", "nvidia-modeset", "nvidia-uvm", "nvidia-uvm-tools"] { + grants.extend(["--dev-bind-try".to_owned(), format!("/dev/{name}"), format!("/dev/{name}")]); + } + // NVDEC (CUDA) won't start without /proc. It's a fresh one for the jail's own process + // namespace (`--unshare-all` includes PIDs), so it shows only the jail. The helper's + // `lock_down_gpu_helper` keeps /proc/self/mem from being written. + grants.extend(["--proc".to_owned(), "/proc".to_owned()]); + } + args.splice(run..run, grants); + args +} + +/// What a GPU helper's `lock_down` should do, before it has any other threads (Landlock +/// applies to the calling thread and the ones it starts later, not to those already running): Landlock lets it open files for writing only +/// under /dev, and seccomp refuses the system calls that write another process's or its own +/// memory from outside (`ptrace`, `process_vm_writev` and their kin). With /proc in the jail +/// for NVIDIA, that keeps code from being changed through /proc/self/mem or those calls. +/// +/// Landlock is required only when the jail has /proc (NVIDIA), which is what it guards. Some +/// kernels leave Landlock out (Proxmox's, for one); without /proc the helper still runs there, +/// with Landlock tried and the seccomp filter required. +pub fn lock_down_gpu_helper() -> bool { + let landlock = forbid_writes_outside(&[Path::new("/dev")]); + let needs_landlock = Path::new("/proc/self/mem").exists(); + (landlock || !needs_landlock) && forbid_memory_writes() +} + +/// A seccomp filter that refuses, with `EPERM`, the system calls that reach into a process's +/// memory (`ptrace`, `process_vm_readv`, `process_vm_writev`, `pidfd_getfd`, `kcmp`) and those +/// that make or join namespaces or mount (`mount` and the newer mount API, `umount2`, +/// `unshare`, `setns`, `pivot_root`, and `clone` with any `CLONE_NEW*` flag). `clone3` gets `ENOSYS`, as under +/// Flatpak: its flags are in memory, where seccomp can't look, and libc then falls back to +/// `clone`. On x86-64, x32 system calls are refused too, as they'd get past the numbers here. +/// Everything else is allowed: libmpv and the drivers need a lot. +pub fn forbid_memory_writes() -> bool { + #[cfg(target_arch = "x86_64")] + const ARCH: u32 = 0xC000_003E; + #[cfg(target_arch = "aarch64")] + const ARCH: u32 = 0xC000_00B7; + const LD_W_ABS: u16 = 0x20; + const JEQ_K: u16 = 0x15; + const JGE_K: u16 = 0x35; + const JSET_K: u16 = 0x45; + const RET_K: u16 = 0x06; + const ALLOW: u32 = 0x7fff_0000; + const KILL: u32 = 0x8000_0000; + const ERRNO: u32 = 0x0005_0000; + const NR: u32 = 0; + const ARCH_OFFSET: u32 = 4; + // The low half of the first argument, `clone`'s flags, on a little-endian machine. + const ARG0_LOW: u32 = 16; + // x32's system calls share x86-64's architecture number, with this bit set. + const X32_BIT: u32 = 0x4000_0000; + let x32 = cfg!(target_arch = "x86_64"); + // Every namespace `clone` can make. CLONE_NEWTIME is left out: in `clone` that bit is part + // of the exit signal, and only `unshare` and `clone3` take it, which are refused whole. + const NEW_NAMESPACES: u32 = (libc::CLONE_NEWNS | libc::CLONE_NEWCGROUP | libc::CLONE_NEWUTS | libc::CLONE_NEWIPC | libc::CLONE_NEWUSER | libc::CLONE_NEWPID | libc::CLONE_NEWNET) as u32; + // Writing a process's memory from outside, and the ways to a filesystem of one's own + // (a procfs with /proc/self/mem in it), as Gannet's player filter refuses. + let refused = [ + libc::SYS_ptrace, + libc::SYS_process_vm_readv, + libc::SYS_process_vm_writev, + libc::SYS_pidfd_getfd, + libc::SYS_kcmp, + libc::SYS_mount, + libc::SYS_umount2, + libc::SYS_unshare, + libc::SYS_setns, + libc::SYS_pivot_root, + // The newer mount API, which makes a filesystem (a procfs too) with no `mount` call. + libc::SYS_fsopen, + libc::SYS_fsconfig, + libc::SYS_fsmount, + libc::SYS_fspick, + libc::SYS_move_mount, + libc::SYS_open_tree, + libc::SYS_mount_setattr, + // open_tree_attr (Linux 6.15), which libc doesn't name yet: the same number on x86-64 + // and aarch64, as every call from 424 on is. + 467, + ]; + let stmt = |code: u16, k: u32| libc::sock_filter { code, jt: 0, jf: 0, k }; + let jump = |code: u16, k: u32, jt: usize, jf: usize| libc::sock_filter { code, jt: jt as u8, jf: jf as u8, k }; + let mut program = vec![stmt(LD_W_ABS, ARCH_OFFSET), jump(JEQ_K, ARCH, 1, 0), stmt(RET_K, KILL), stmt(LD_W_ABS, NR)]; + // The checks, then the endings they jump to: allow, ENOSYS, clone's flags, and EPERM. + let checks = usize::from(x32) + refused.len() + 2; + let allow = program.len() + checks; + let (no_such_call, clone_flags, eperm) = (allow + 1, allow + 2, allow + 5); + // A jump's targets count from the instruction after it. + let to = |target: usize, from: usize| target - from - 1; + if x32 { + let at = program.len(); + program.push(jump(JGE_K, X32_BIT, to(eperm, at), 0)); + } + for call in refused { + let at = program.len(); + program.push(jump(JEQ_K, call as u32, to(eperm, at), 0)); + } + let at = program.len(); + program.push(jump(JEQ_K, libc::SYS_clone3 as u32, to(no_such_call, at), 0)); + let at = program.len(); + program.push(jump(JEQ_K, libc::SYS_clone as u32, to(clone_flags, at), 0)); + debug_assert_eq!(program.len(), allow); + program.push(stmt(RET_K, ALLOW)); + program.push(stmt(RET_K, ERRNO | libc::ENOSYS as u32)); + program.push(stmt(LD_W_ABS, ARG0_LOW)); + program.push(jump(JSET_K, NEW_NAMESPACES, 1, 0)); + program.push(stmt(RET_K, ALLOW)); + debug_assert_eq!(program.len(), eperm); + program.push(stmt(RET_K, ERRNO | libc::EPERM as u32)); + let filter = libc::sock_fprog { len: program.len() as u16, filter: program.as_mut_ptr() }; + // Every thread the process already has gets it too (TSYNC), not just this one. + const SET_MODE_FILTER: libc::c_ulong = 1; + const FILTER_FLAG_TSYNC: libc::c_ulong = 1; + // SAFETY: no new privileges, as seccomp asks of an unprivileged process, and a valid + // program that outlives the call; the kernel copies it. + unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == 0 && libc::syscall(libc::SYS_seccomp, SET_MODE_FILTER, FILTER_FLAG_TSYNC, &filter as *const libc::sock_fprog) == 0 } +} + /// The command that runs this program jailed with `helper_arg`, ready for `helper::start`. /// With `sound`, the session's PulseAudio socket goes in too, if there is one. pub fn command(helper_arg: &str, sound: bool) -> std::io::Result { @@ -88,6 +237,53 @@ fn undeleted(exe: PathBuf) -> Option { path.is_file().then(|| path.to_path_buf()) } +/// Lets this process open files for writing only under `allowed` from now on, with Landlock. +/// For a GPU helper, whose jail has /proc for NVIDIA's decoder: `/proc/self/mem` can't be +/// opened for writing, so code can't be changed through it, while the card's device files +/// under /dev still can. Returns false if the kernel has no Landlock or refuses. +pub fn forbid_writes_outside(allowed: &[&Path]) -> bool { + const CREATE_RULESET: libc::c_long = 444; + const ADD_RULE: libc::c_long = 445; + const RESTRICT_SELF: libc::c_long = 446; + const RULE_PATH_BENEATH: libc::c_int = 1; + const ACCESS_WRITE_FILE: u64 = 1 << 1; + const ACCESS_TRUNCATE: u64 = 1 << 14; + #[repr(C)] + struct Ruleset { + handled_access_fs: u64, + } + #[repr(C, packed)] + struct PathBeneath { + allowed_access: u64, + parent_fd: i32, + } + // Truncating is writing too, from Landlock ABI 3; older kernels handle only the first. + // SAFETY: asking for the ABI version, with no ruleset. + let abi = unsafe { libc::syscall(CREATE_RULESET, std::ptr::null::(), 0usize, 1u32) }; + if abi < 1 { + return false; + } + let handled = if abi >= 3 { ACCESS_WRITE_FILE | ACCESS_TRUNCATE } else { ACCESS_WRITE_FILE }; + let ruleset = Ruleset { handled_access_fs: handled }; + // SAFETY: a valid ruleset of the size given. + let fd = unsafe { libc::syscall(CREATE_RULESET, &ruleset as *const Ruleset, size_of::(), 0u32) }; + if fd < 0 { + return false; + } + // SAFETY: a new descriptor, owned here. + let ruleset_fd = unsafe { std::os::fd::OwnedFd::from_raw_fd(fd as i32) }; + for path in allowed { + let Ok(dir) = std::fs::File::open(path) else { continue }; + let rule = PathBeneath { allowed_access: handled, parent_fd: dir.as_raw_fd() }; + // SAFETY: a live ruleset and a valid rule. + if unsafe { libc::syscall(ADD_RULE, ruleset_fd.as_raw_fd(), RULE_PATH_BENEATH, &rule as *const PathBeneath, 0u32) } != 0 { + return false; + } + } + // SAFETY: plain integers and a live ruleset. No new privileges is what Landlock asks for. + unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == 0 && libc::syscall(RESTRICT_SELF, ruleset_fd.as_raw_fd(), 0u32) == 0 } +} + #[cfg(test)] mod tests { use super::*; @@ -119,4 +315,135 @@ mod tests { assert_eq!(undeleted(new.clone()), Some(new)); std::fs::remove_dir_all(dir).unwrap(); } + + #[test] + fn only_nvidia_gets_proc_and_its_devices() { + use crate::options::Vendor; + for vendor in [Vendor::Nvidia, Vendor::Amd, Vendor::Intel, Vendor::Apple, Vendor::Other] { + let text = gpu_arguments(Path::new("/opt/app"), vendor).join(" "); + let nvidia = vendor == Vendor::Nvidia; + assert_eq!(text.contains("--proc /proc"), nvidia, "{vendor:?}"); + assert_eq!(text.contains("/dev/nvidia"), nvidia, "{vendor:?}"); + assert!(text.contains("--dev-bind /dev/dri /dev/dri") && text.contains("--unshare-all"), "{vendor:?}"); + assert!(text.contains("--unshare-user") && !text.contains("--disable-userns"), "--disable-userns can't start in an LXC container"); + assert!(!text.contains("/dev/video"), "no camera or other V4L2 devices"); + assert!(text.ends_with("-- /playback-helper"), "{vendor:?}"); + } + } + + /// The GPU jail with the helper's filter on, with this test program standing in for the + /// helper: `in_the_gpu_jail` below runs inside it. Skipped where bubblewrap or user + /// namespaces aren't available (CI's containers), as it says. + #[test] + fn the_gpu_jail_cant_make_a_user_namespace() { + let can_jail = Command::new("bwrap").args(["--unshare-user", "--ro-bind", "/", "/", "true"]).status().is_ok_and(|s| s.success()); + // The GPU jail binds /dev/dri, so it can't start where there's no card (CI). + if !can_jail || !Path::new("/usr/bin/unshare").exists() || !Path::new("/dev/dri").is_dir() { + eprintln!("skipped: no bubblewrap with user namespaces, or no /dev/dri, here"); + return; + } + let args = gpu_arguments(&std::env::current_exe().expect("own path"), crate::options::Vendor::Other); + let inside = Command::new("bwrap").args(&args).args(["--ignored", "--exact", "jail::tests::in_the_gpu_jail", "--test-threads=1", "--nocapture"]).output().expect("bubblewrap"); + let said = String::from_utf8_lossy(&inside.stdout); + assert!(inside.status.success() && said.contains("1 passed"), "inside the jail:\n{said}{}", String::from_utf8_lossy(&inside.stderr)); + } + + /// Run inside the GPU jail by `the_gpu_jail_cant_make_a_user_namespace`. The jail alone lets + /// a user namespace be made (since it can't use `--disable-userns`); the filter stops it, + /// whichever way it's asked for. + #[test] + #[ignore = "runs inside the GPU jail, from the_gpu_jail_cant_make_a_user_namespace"] + fn in_the_gpu_jail() { + assert!(Path::new(JAILED_SELF).exists(), "only inside the jail"); + let unshare_user = || Command::new("/usr/bin/unshare").args(["--user", "true"]).status().expect("unshare").success(); + assert!(unshare_user(), "before the filter, the jail itself allows a user namespace"); + assert!(forbid_memory_writes(), "the filter went on"); + assert!(!unshare_user(), "unshare --user refused"); + let errno = || std::io::Error::last_os_error().raw_os_error(); + // SAFETY: clone with no stack works as fork does; a child, if the call isn't refused, + // leaves at once. + let cloned = unsafe { libc::syscall(libc::SYS_clone, (libc::CLONE_NEWUSER | libc::SIGCHLD) as libc::c_ulong, 0usize, 0usize, 0usize, 0usize) }; + if cloned == 0 { + // SAFETY: leaving the child without running the parent's destructors. + unsafe { libc::_exit(0) }; + } + assert!(cloned == -1 && errno() == Some(libc::EPERM), "clone with CLONE_NEWUSER refused"); + // struct clone_args: flags, pidfd, child_tid, parent_tid, exit_signal, stack, + // stack_size, tls. + let mut clone_args = [0u64; 8]; + clone_args[0] = libc::CLONE_NEWUSER as u64; + clone_args[4] = libc::SIGCHLD as u64; + // SAFETY: a valid clone_args of the size given; a child leaves at once, as above. + let cloned = unsafe { libc::syscall(libc::SYS_clone3, clone_args.as_ptr(), size_of_val(&clone_args)) }; + if cloned == 0 { + // SAFETY: as above. + unsafe { libc::_exit(0) }; + } + assert!(cloned == -1 && errno() == Some(libc::ENOSYS), "clone3 says it doesn't exist"); + // libc falls back from clone3 to clone, so new processes and threads still start. + assert!(Command::new("/usr/bin/true").status().expect("true").success(), "processes still start"); + assert!(std::thread::spawn(|| 1).join().is_ok(), "threads still start"); + } + + /// In a child process, as seccomp can't be lifted once on. + #[test] + fn after_the_filter_memory_writing_calls_are_refused() { + // SAFETY: the child only makes system calls and exits. + let pid = unsafe { libc::fork() }; + if pid == 0 { + let on = forbid_memory_writes(); + let errno = || std::io::Error::last_os_error().raw_os_error(); + // SAFETY: calls that must fail; their arguments are never used if refused. + let ptrace = unsafe { libc::ptrace(libc::PTRACE_TRACEME, 0, 0, 0) } == -1 && errno() == Some(libc::EPERM); + let mut byte = 0u8; + let local = libc::iovec { iov_base: &mut byte as *mut u8 as *mut _, iov_len: 1 }; + let remote = libc::iovec { iov_base: &mut byte as *mut u8 as *mut _, iov_len: 1 }; + // SAFETY: as above; writing this process's own byte to itself if it weren't refused. + let vm_write = unsafe { libc::process_vm_writev(libc::getpid(), &local, 1, &remote, 1, 0) } == -1 && errno() == Some(libc::EPERM); + // SAFETY: calls that must be refused before they do anything. + let unshare = unsafe { libc::unshare(libc::CLONE_NEWUSER) } == -1 && errno() == Some(libc::EPERM); + // SAFETY: as unshare; a child, if the call isn't refused, leaves at once. + let cloned = unsafe { libc::syscall(libc::SYS_clone, (libc::CLONE_NEWNET | libc::SIGCHLD) as libc::c_ulong, 0usize, 0usize, 0usize, 0usize) }; + if cloned == 0 { + // SAFETY: leaving the child without running the parent's destructors. + unsafe { libc::_exit(0) }; + } + let unshare = unshare && cloned == -1 && errno() == Some(libc::EPERM); + let mount = unsafe { libc::mount(c"none".as_ptr(), c"/".as_ptr(), c"tmpfs".as_ptr(), 0, std::ptr::null()) } == -1 && errno() == Some(libc::EPERM); + let still_works = unsafe { libc::getpid() } > 0 && unshare && mount; + // SAFETY: leaving the forked child without running the parent's destructors. + unsafe { libc::_exit(i32::from(on) | i32::from(ptrace) << 1 | i32::from(vm_write) << 2 | i32::from(still_works) << 3) }; + } + let mut status = 0; + // SAFETY: waiting for our own child. + unsafe { libc::waitpid(pid, &mut status, 0) }; + let bits = libc::WEXITSTATUS(status); + assert_eq!(bits & 1, 1, "the filter went on"); + assert_eq!(bits & 2, 2, "ptrace refused"); + assert_eq!(bits & 4, 4, "process_vm_writev refused"); + assert_eq!(bits & 8, 8, "unshare, clone with CLONE_NEWNET and mount refused, and other calls still allowed"); + } + + /// In a child process, as Landlock can't be lifted once on. + #[test] + fn after_landlock_proc_self_mem_cant_be_written_but_dev_can() { + // SAFETY: the child only makes system calls and exits. + let pid = unsafe { libc::fork() }; + if pid == 0 { + let on = forbid_writes_outside(&[Path::new("/dev")]); + let mem = std::fs::OpenOptions::new().write(true).open("/proc/self/mem").is_err(); + let null = std::fs::OpenOptions::new().write(true).open("/dev/null").is_ok(); + let tmp = std::fs::OpenOptions::new().write(true).create(true).truncate(true).open(std::env::temp_dir().join(format!("landlock-{}", std::process::id()))).is_err(); + // SAFETY: leaving the forked child without running the parent's destructors. + unsafe { libc::_exit(i32::from(on) | i32::from(mem) << 1 | i32::from(null) << 2 | i32::from(tmp) << 3) }; + } + let mut status = 0; + // SAFETY: waiting for our own child. + unsafe { libc::waitpid(pid, &mut status, 0) }; + let bits = libc::WEXITSTATUS(status); + assert_eq!(bits & 1, 1, "Landlock went on"); + assert_eq!(bits & 2, 2, "/proc/self/mem refused for writing"); + assert_eq!(bits & 4, 4, "/dev/null still writable"); + assert_eq!(bits & 8, 8, "nothing else writable"); + } } diff --git a/src/lib.rs b/src/lib.rs index 316bdf3..10eb101 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,12 +15,14 @@ //! playback. pub mod ffi; +pub mod gpu; +pub mod gpu_helper; pub mod helper; pub mod jail; pub mod options; pub mod player; pub mod render; -pub use options::{Audio, Hwdec, Options, RenderPath}; +pub use options::{Audio, Hwdec, Options, RenderPath, Vendor}; pub use player::{Error, Event, Player}; -pub use render::{GlRender, SwFormat, SwRender}; +pub use render::{GlRender, Native, SwFormat, SwRender}; diff --git a/src/options.rs b/src/options.rs index 9e5b768..7fe2c57 100644 --- a/src/options.rs +++ b/src/options.rs @@ -3,6 +3,36 @@ //! The apps differ in only a few choices (where frames are drawn, hardware decoding, sound, //! cover art), so those are fields, and everything else is the same for all of them. +/// Who made a graphics card, which decides how it decodes video and what a jail must let +/// through for that. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Vendor { + /// NVDEC, through CUDA. + Nvidia, + /// VA-API, through the render node. + Amd, + Intel, + /// The M1's decoder is a V4L2 device; FFmpeg can't use it yet, so this decodes on the CPU. + Apple, + Other, +} + +impl Vendor { + /// From the PCI vendor number and the kernel driver's name in /sys. + pub fn from_sys(pci_vendor: Option, driver: &str) -> Self { + match (pci_vendor, driver) { + // nouveau has no NVDEC, and its jail mustn't get /proc. An NVIDIA card whose driver + // can't be read is taken to run NVIDIA's own. + (Some(0x10de), "nouveau") => Self::Other, + (Some(0x10de), _) | (_, "nvidia") => Self::Nvidia, + (Some(0x1002), _) | (_, "amdgpu" | "radeon") => Self::Amd, + (Some(0x8086), _) | (_, "i915" | "xe") => Self::Intel, + (_, "asahi") => Self::Apple, + _ => Self::Other, + } + } +} + /// Where frames are drawn. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RenderPath { @@ -18,6 +48,9 @@ pub enum Hwdec { Off, /// NVDEC, VA-API or V4L2 where the card and the file allow, and the CPU where they don't. Auto, + /// Only the method for this card's maker, and the CPU where it can't: what a jailed + /// player uses, since its jail only has that maker's devices. + For(Vendor), } /// Where sound goes. @@ -73,6 +106,11 @@ fn hwdec_value(render: RenderPath, hwdec: Hwdec) -> &'static str { (Hwdec::Off, _) => "no", (Hwdec::Auto, RenderPath::Cpu) => "nvdec-copy,vaapi-copy,v4l2m2m-copy", (Hwdec::Auto, RenderPath::Gpu) => "nvdec,vaapi,nvdec-copy,vaapi-copy,v4l2m2m-copy", + (Hwdec::For(Vendor::Nvidia), RenderPath::Cpu) => "nvdec-copy", + (Hwdec::For(Vendor::Nvidia), RenderPath::Gpu) => "nvdec,nvdec-copy", + (Hwdec::For(Vendor::Amd | Vendor::Intel), RenderPath::Cpu) => "vaapi-copy", + (Hwdec::For(Vendor::Amd | Vendor::Intel), RenderPath::Gpu) => "vaapi,vaapi-copy", + (Hwdec::For(Vendor::Apple | Vendor::Other), _) => "v4l2m2m-copy", } } @@ -176,6 +214,24 @@ mod tests { assert!(value(&cpu, "hwdec").unwrap().split(',').all(|method| method.ends_with("-copy"))); let gpu = Options { render: RenderPath::Gpu, ..cpu }; assert!(value(&gpu, "hwdec").unwrap().starts_with("nvdec,vaapi,")); + for vendor in [Vendor::Nvidia, Vendor::Amd, Vendor::Intel, Vendor::Apple, Vendor::Other] { + let one = Options { hwdec: Hwdec::For(vendor), ..Options::cpu() }; + let methods = value(&one, "hwdec").unwrap(); + let expected = match vendor { + Vendor::Nvidia => "nvdec", + Vendor::Amd | Vendor::Intel => "vaapi", + Vendor::Apple | Vendor::Other => "v4l2m2m", + }; + assert!(methods.split(',').all(|m| m.starts_with(expected)), "{vendor:?}: {methods}"); + assert!(methods.split(',').all(|m| m.ends_with("-copy")), "the CPU path copies back"); + } + assert_eq!(Vendor::from_sys(Some(0x10de), "nvidia"), Vendor::Nvidia); + assert_eq!(Vendor::from_sys(Some(0x10de), "nouveau"), Vendor::Other, "no NVDEC, no /proc"); + assert_eq!(Vendor::from_sys(Some(0x10de), ""), Vendor::Nvidia, "driver not readable"); + assert_eq!(Vendor::from_sys(Some(0x1002), "amdgpu"), Vendor::Amd); + assert_eq!(Vendor::from_sys(Some(0x8086), "i915"), Vendor::Intel); + assert_eq!(Vendor::from_sys(None, "asahi"), Vendor::Apple); + assert_eq!(Vendor::from_sys(None, "virtio_gpu"), Vendor::Other); for options in [cpu, gpu] { assert!(!value(&options, "hwdec").unwrap().contains("vdpau"), "VDPAU stalls on what it can't decode"); } diff --git a/src/player.rs b/src/player.rs index b75bdf5..457f320 100644 --- a/src/player.rs +++ b/src/player.rs @@ -1,9 +1,11 @@ //! A libmpv player: setting it up, telling it what to do, and hearing what it does. +use std::collections::HashMap; use std::ffi::{CStr, CString, c_char, c_int, c_void}; use std::os::fd::RawFd; use std::os::unix::ffi::OsStrExt; use std::path::Path; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -69,10 +71,54 @@ pub enum Event { VideoChanged, /// Playing again after loading or a seek. Restarted, + /// The picture's width and height as shown, each on its own, or 0 while there's none. + /// Watched rather than asked for: asking waits on libmpv's core, which a render thread + /// mustn't do while the core may be waiting for it to draw. + Width(f64), + Height(f64), + /// How the video is being decoded: a hardware decoder's name, such as `nvdec` or `vaapi`, + /// `software`, or `None` while nothing is decoding. + Decoder(Option<&'static str>), + /// Frames dropped by the decoder, and frames the video output showed late. + DecoderDrops(u64), + LateFrames(u64), + /// libmpv turned down something it was asked to do. Requests return before libmpv has + /// done them, so a refusal comes here. + Refused(Request), + /// The answer to `Player::ask` with this id is ready: take it with `Player::answer`. + Answered(u32), /// The player is shutting down. Shutdown, } +/// What a refused request was. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Request { + Command, + Load, + Pause, + Seek, + Volume, + Mute, +} + +impl Request { + const ALL: [Request; 6] = [Request::Command, Request::Load, Request::Pause, Request::Seek, Request::Volume, Request::Mute]; +} + +/// The number libmpv hands back with a reply. The watched properties use 1 and up. Replies +/// carry a kind in the top 4 bits: a request's has its `Request` below; an `ask`'s has the +/// file's generation (bits 32 to 59) and the caller's id (the low 32). +const TAG_SHIFT: u32 = 60; +const REQUEST: u64 = 1 << TAG_SHIFT; +const ASK: u64 = 2 << TAG_SHIFT; +/// The internal ask for `vid`, which says whether a loaded file has a picture. +const ASK_VIDEO: u64 = 3 << TAG_SHIFT; +const GENERATION_MASK: u64 = (1 << 28) - 1; +/// The most answers kept untaken: beyond this, an answer is dropped and `answer` gives +/// `None`. +const MAX_ANSWERS: usize = 64; + /// The properties every app watches, by the number libmpv hands back with each change. const WATCHED: &[(&CStr, c_int)] = &[ (c"time-pos", ffi::FORMAT_DOUBLE), @@ -81,9 +127,24 @@ const WATCHED: &[(&CStr, c_int)] = &[ (c"volume", ffi::FORMAT_DOUBLE), (c"mute", ffi::FORMAT_FLAG), (c"eof-reached", ffi::FORMAT_FLAG), + (c"dwidth", ffi::FORMAT_DOUBLE), + (c"dheight", ffi::FORMAT_DOUBLE), + (c"hwdec-current", ffi::FORMAT_STRING), + (c"frame-drop-count", ffi::FORMAT_DOUBLE), + (c"vo-delayed-frame-count", ffi::FORMAT_DOUBLE), ]; +/// libmpv's decoder names, as names that last: one not listed is still hardware decoding. +fn decoder_name(name: &str) -> &'static str { + const KNOWN: &[&str] = &["nvdec", "nvdec-copy", "cuda", "cuda-copy", "vaapi", "vaapi-copy", "v4l2m2m", "v4l2m2m-copy", "vulkan", "vulkan-copy", "drm", "drm-copy", "vdpau", "vdpau-copy"]; + match name { + "" | "no" => "software", + _ => KNOWN.iter().find(|known| **known == name).copied().unwrap_or("hardware"), + } +} + type Wakeup = Box; +type LogSink = Box; /// The handle itself. It's destroyed when the last owner goes, so a render context, which /// holds one, is always freed before it. @@ -98,6 +159,16 @@ pub(crate) struct Core { /// put when the list grows. #[allow(clippy::vec_box)] wakeups: Mutex>>, + /// Where libmpv's own log lines go, once asked for: for diagnosing a player that can't + /// write a log file anywhere, such as a jailed one. + log: Mutex>, + /// Answers to `ask`, until they're taken. + answers: Mutex>>, + /// Counts load requests. An answer asked for before the latest load request is turned + /// away. Changed only with `answers` locked, so a load and an answer don't interleave. + generation: AtomicU64, + /// Whether the file has stopped on its last frame, as last watched, for `play`. + ended: AtomicBool, } // SAFETY: libmpv's client API may be called from any thread, and the one call that mustn't @@ -131,7 +202,16 @@ impl Player { if handle.is_null() { return Err(Error::Mpv { doing: "starting libmpv".into(), reason: "out of memory".into() }); } - let core = Core { lib, handle, events: Mutex::new(()), wakeups: Mutex::new(Vec::new()) }; + let core = Core { + lib, + handle, + events: Mutex::new(()), + wakeups: Mutex::new(Vec::new()), + log: Mutex::new(None), + answers: Mutex::new(HashMap::new()), + generation: AtomicU64::new(0), + ended: AtomicBool::new(false), + }; for (name, value) in options.pairs() { core.set_option(name, value)?; } @@ -159,11 +239,27 @@ impl Player { /// Runs a command, such as `["seek", "5", "relative"]`. Each word is passed as it is, /// so a file name needs no quoting. + /// + /// Requests (this, loading, pause, seeking, volume and mute) return once libmpv has them, + /// without waiting for libmpv's core: a thread that draws can't wait on the core, which + /// may be waiting for it to draw. One libmpv then turns down comes as `Event::Refused`. pub fn command(&self, words: &[&[u8]]) -> Result<(), Error> { + self.request(Request::Command, words) + } + + fn request(&self, kind: Request, words: &[&[u8]]) -> Result<(), Error> { + // A new file: answers about the last one, taken or not, are gone, and late ones are + // turned away. + if kind == Request::Load { + let mut answers = self.core.answers.lock().unwrap_or_else(|e| e.into_inner()); + self.core.generation.fetch_add(1, Ordering::Relaxed); + answers.clear(); + } let owned = words.iter().map(|w| CString::new(*w).map_err(|_| Error::Nul)).collect::, _>>()?; let mut pointers: Vec<*const c_char> = owned.iter().map(|w| w.as_ptr()).chain([std::ptr::null()]).collect(); - // SAFETY: a live handle and a null-terminated list of strings that outlive the call. - let code = unsafe { (self.core.lib.command)(self.core.handle, pointers.as_mut_ptr()) }; + // SAFETY: a live handle and a null-terminated list of strings that outlive the call; + // libmpv copies them. + let code = unsafe { (self.core.lib.command_async)(self.core.handle, REQUEST + kind as u64, pointers.as_mut_ptr()) }; if code < 0 { let doing = words.iter().map(|w| String::from_utf8_lossy(w)).collect::>().join(" "); return Err(Error::Mpv { doing, reason: self.core.lib.describe(code) }); @@ -171,53 +267,76 @@ impl Player { Ok(()) } + /// Asks for a property as text without waiting: `Event::Answered(id)` says the answer is + /// ready, and `answer(id)` takes it. For a thread that draws, which mustn't wait on + /// libmpv's core. + /// + /// An answer asked for before a later load request is turned away. One asked for after a + /// load request but before libmpv has opened that file can still be about the last + /// file: ask about a file once `Event::Loaded` has come. + pub fn ask(&self, name: &CStr, id: u32) -> Result<(), Error> { + // SAFETY: a live handle and a terminated name; libmpv copies it. + let generation = self.core.generation.load(Ordering::Relaxed) & GENERATION_MASK; + let code = unsafe { (self.core.lib.get_property_async)(self.core.handle, ASK | generation << 32 | u64::from(id), name.as_ptr(), ffi::FORMAT_STRING) }; + self.check(code, name) + } + + /// The answer to `ask` with `id`, once `Event::Answered(id)` has come: `None` if the + /// property wasn't available, or it was already taken. + pub fn answer(&self, id: u32) -> Option { + self.core.answers.lock().unwrap_or_else(|e| e.into_inner()).remove(&id).flatten() + } + /// Opens a file, in place of whatever was playing. Always as a file: a relative path /// such as `http://host/x` or `edl://...` is a file of that name in the current folder, /// not something for libmpv to fetch or build. pub fn load(&self, path: &Path) -> Result<(), Error> { - self.command(&[b"loadfile", as_file(path).as_os_str().as_bytes()]) + self.request(Request::Load, &[b"loadfile", as_file(path).as_os_str().as_bytes()]) } /// Opens a file this process has open, for a player that can't see the file system. pub fn load_fd(&self, fd: RawFd) -> Result<(), Error> { - self.command(&[b"loadfile", format!("fd://{fd}").as_bytes()]) + self.request(Request::Load, &[b"loadfile", format!("fd://{fd}").as_bytes()]) } pub fn set_paused(&self, paused: bool) -> Result<(), Error> { - self.set_flag(c"pause", paused) + self.request(Request::Pause, &[b"set", b"pause", if paused { b"yes" } else { b"no" }]) } /// Plays, from the start if it had stopped on its last frame: what a play button does. pub fn play(&self) -> Result<(), Error> { - if self.flag(c"eof-reached") == Some(true) { - self.command(&[b"seek", b"0", b"absolute"])?; + // As last watched: asking would wait on the core. Requests run in order, so the + // seek comes before the unpause. + if self.core.ended.load(Ordering::Relaxed) { + self.request(Request::Seek, &[b"seek", b"0", b"absolute"])?; } self.set_paused(false) } pub fn seek_by(&self, seconds: f64) -> Result<(), Error> { - self.command(&[b"seek", format!("{seconds:.3}").as_bytes(), b"relative"]) + self.request(Request::Seek, &[b"seek", format!("{seconds:.3}").as_bytes(), b"relative"]) } pub fn seek_to(&self, seconds: f64) -> Result<(), Error> { - self.command(&[b"seek", format!("{:.3}", seconds.max(0.0)).as_bytes(), b"absolute"]) + self.request(Request::Seek, &[b"seek", format!("{:.3}", seconds.max(0.0)).as_bytes(), b"absolute"]) } /// To a share of the way through, from 0 to 1. pub fn seek_to_fraction(&self, fraction: f64) -> Result<(), Error> { - self.command(&[b"seek", format!("{:.3}", fraction.clamp(0.0, 1.0) * 100.0).as_bytes(), b"absolute-percent"]) + self.request(Request::Seek, &[b"seek", format!("{:.3}", fraction.clamp(0.0, 1.0) * 100.0).as_bytes(), b"absolute-percent"]) } /// 0 to 100. pub fn set_volume(&self, volume: f64) -> Result<(), Error> { - self.set_double(c"volume", volume.clamp(0.0, 100.0)) + self.request(Request::Volume, &[b"set", b"volume", format!("{:.3}", volume.clamp(0.0, 100.0)).as_bytes()]) } pub fn set_muted(&self, muted: bool) -> Result<(), Error> { - self.set_flag(c"mute", muted) + self.request(Request::Mute, &[b"set", b"mute", if muted { b"yes" } else { b"no" }]) } - /// A property as text, or `None` if it isn't available now. + /// A property as text, or `None` if it isn't available now. This waits on libmpv's core: + /// a thread that draws uses `ask` instead. pub fn get(&self, name: &CStr) -> Option { // SAFETY: a live handle and a terminated name. libmpv's string is copied, then freed // as it asks. @@ -246,22 +365,9 @@ impl Player { (code >= 0).then_some(value != 0) } - fn set_flag(&self, name: &CStr, value: bool) -> Result<(), Error> { - let mut value = c_int::from(value); - // SAFETY: a live handle, and an int for a flag. - let code = unsafe { (self.core.lib.set_property)(self.core.handle, name.as_ptr(), ffi::FORMAT_FLAG, &mut value as *mut c_int as *mut c_void) }; - self.check(code, name) - } - - fn set_double(&self, name: &CStr, mut value: f64) -> Result<(), Error> { - // SAFETY: a live handle, and a double for a double. - let code = unsafe { (self.core.lib.set_property)(self.core.handle, name.as_ptr(), ffi::FORMAT_DOUBLE, &mut value as *mut f64 as *mut c_void) }; - self.check(code, name) - } - fn check(&self, code: c_int, name: &CStr) -> Result<(), Error> { if code < 0 { - return Err(Error::Mpv { doing: format!("setting {}", name.to_string_lossy()), reason: self.core.lib.describe(code) }); + return Err(Error::Mpv { doing: format!("asking for {}", name.to_string_lossy()), reason: self.core.lib.describe(code) }); } Ok(()) } @@ -277,6 +383,14 @@ impl Player { wakeups.push(boxed); } + /// Hands libmpv's log lines at `level` and above (`"warn"`, `"info"`, `"v"`) to `sink`, as + /// its module and text, from the thread that reads events. + pub fn on_log(&self, level: &CStr, sink: impl Fn(&str, &str) + Send + Sync + 'static) { + *self.core.log.lock().unwrap_or_else(|e| e.into_inner()) = Some(Box::new(sink)); + // SAFETY: a live handle and a terminated level name. + unsafe { (self.core.lib.request_log_messages)(self.core.handle, level.as_ptr()) }; + } + /// The next event if there is one, without waiting. pub fn next_event(&self) -> Option { self.wait_event(Duration::ZERO) @@ -308,13 +422,53 @@ impl Player { unsafe fn translate(&self, event: &ffi::Event) -> Option { match event.id { ffi::EVENT_SHUTDOWN => Some(Event::Shutdown), - ffi::EVENT_FILE_LOADED => Some(Event::Loaded { video: self.get(c"vid").is_some_and(|v| v != "no") }), + // Whether it has a picture is asked for without waiting, and `Loaded` comes with + // the answer. + ffi::EVENT_FILE_LOADED => { + // SAFETY: a live handle and a terminated name. + let generation = self.core.generation.load(Ordering::Relaxed) & GENERATION_MASK; + let code = unsafe { (self.core.lib.get_property_async)(self.core.handle, ASK_VIDEO | generation << 32, c"vid".as_ptr(), ffi::FORMAT_STRING) }; + (code < 0).then_some(Event::Loaded { video: false }) + } + ffi::EVENT_GET_PROPERTY_REPLY => { + // SAFETY: a reply's data is a property struct, as the caller says. + let text = unsafe { reply_text(event) }; + let mut answers = self.core.answers.lock().unwrap_or_else(|e| e.into_inner()); + // Asked for before the latest load request: about a file that's going. + if (event.userdata >> 32) & GENERATION_MASK != self.core.generation.load(Ordering::Relaxed) & GENERATION_MASK { + return None; + } + match event.userdata >> TAG_SHIFT { + tag if tag == ASK_VIDEO >> TAG_SHIFT => return Some(Event::Loaded { video: text.is_some_and(|v| v != "no") }), + tag if tag == ASK >> TAG_SHIFT => {} + _ => return None, + } + let id = event.userdata as u32; + if answers.len() < MAX_ANSWERS || answers.contains_key(&id) { + answers.insert(id, text); + } + Some(Event::Answered(id)) + } + ffi::EVENT_COMMAND_REPLY | ffi::EVENT_SET_PROPERTY_REPLY => { + let kind = (event.userdata >> TAG_SHIFT == REQUEST >> TAG_SHIFT).then(|| Request::ALL.get((event.userdata & 0xff) as usize).copied()).flatten()?; + (event.error < 0).then_some(Event::Refused(kind)) + } ffi::EVENT_END_FILE => { // 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_LOG_MESSAGE => { + // SAFETY: a log event's data is a log struct with terminated strings, as the + // caller says. + let message = unsafe { &*(event.data as *const ffi::EventLogMessage) }; + if let Some(sink) = self.core.log.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + let text = |p: *const c_char| if p.is_null() { String::new() } else { unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned() }; + sink(&text(message.prefix), text(message.text).trim_end()); + } + None + } ffi::EVENT_PLAYBACK_RESTART => Some(Event::Restarted), ffi::EVENT_PROPERTY_CHANGE => { // SAFETY: a property event's data is a property struct, as the caller says. @@ -328,7 +482,15 @@ impl Player { return match index { 0 => Some(Event::Position(0.0)), 1 => Some(Event::Duration(0.0)), - 5 => Some(Event::Ended(false)), + 5 => { + self.core.ended.store(false, Ordering::Relaxed); + Some(Event::Ended(false)) + } + 6 => Some(Event::Width(0.0)), + 7 => Some(Event::Height(0.0)), + 8 => Some(Event::Decoder(None)), + 9 => Some(Event::DecoderDrops(0)), + 10 => Some(Event::LateFrames(0)), _ => None, }; } @@ -336,6 +498,13 @@ impl Player { if property.format != *format { return None; } + if *format == ffi::FORMAT_STRING { + // SAFETY: a string property's data points at a terminated string, libmpv's + // until the next wait. + let text = unsafe { *(property.data as *const *const c_char) }; + let name = if text.is_null() { String::new() } else { unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned() }; + return (index == 8).then(|| Event::Decoder(Some(decoder_name(&name)))); + } // SAFETY: the format says what the data is, and it was checked above. let (double, flag) = unsafe { match *format { @@ -350,7 +519,14 @@ impl Player { 2 => Some(Event::Paused(flag)), 3 => number().map(|v| Event::Volume(v.min(100.0))), 4 => Some(Event::Muted(flag)), - 5 => Some(Event::Ended(flag)), + 5 => { + self.core.ended.store(flag, Ordering::Relaxed); + Some(Event::Ended(flag)) + } + 6 => number().map(Event::Width), + 7 => number().map(Event::Height), + 9 => number().map(|n| Event::DecoderDrops(n as u64)), + 10 => number().map(|n| Event::LateFrames(n as u64)), _ => None, } } @@ -359,6 +535,26 @@ impl Player { } } +/// A property reply's value as text: `None` if it failed or the property wasn't available. +/// +/// # Safety +/// `event` must be a get-property reply libmpv just returned, read before the next wait. +unsafe fn reply_text(event: &ffi::Event) -> Option { + if event.error < 0 || event.data.is_null() { + return None; + } + // SAFETY: a reply's data is a property struct; a string's data points at a pointer to a + // terminated string, libmpv's until the next wait. It's copied here. + unsafe { + let property = &*(event.data as *const ffi::EventProperty); + if property.format != ffi::FORMAT_STRING || property.data.is_null() { + return None; + } + let text = *(property.data as *const *const c_char); + (!text.is_null()).then(|| CStr::from_ptr(text).to_string_lossy().into_owned()) + } +} + /// `path`, starting with `/` or `./`, which libmpv only ever reads as a file. fn as_file(path: &Path) -> std::borrow::Cow<'_, Path> { if path.is_absolute() { std::borrow::Cow::Borrowed(path) } else { std::borrow::Cow::Owned(Path::new(".").join(path)) } diff --git a/src/render.rs b/src/render.rs index 7fa0960..313bb18 100644 --- a/src/render.rs +++ b/src/render.rs @@ -155,6 +155,16 @@ fn fits(width: u32, height: u32, stride: usize, pixels: &[u8]) -> bool { && stride.checked_mul(height as usize).is_some_and(|bytes| bytes <= pixels.len()) } +/// What libmpv's OpenGL renderer may use for hardware decoding besides OpenGL itself. +#[derive(Clone, Copy, Debug)] +pub enum Native { + None, + /// The app's live `wl_display`. + Wayland(*mut c_void), + /// A DRM render node, for a player with no display connection, such as a GPU helper. + RenderNode(std::os::fd::RawFd), +} + /// libmpv's OpenGL renderer. The app owns the GL context, and makes it current on the /// thread that creates, uses and drops this, which is why it can't move to another thread. pub struct GlRender { @@ -168,16 +178,22 @@ impl GlRender { /// # Safety /// An OpenGL context must be current on this thread, and stay current whenever this is /// used or dropped. `get_proc_address` must find that context's functions given - /// `proc_context`. `wl_display`, if given, must be the app's live `wl_display`, which lets - /// libmpv use hardware decoding without copying frames back. - pub unsafe fn new(player: &Player, get_proc_address: GetProcAddress, proc_context: *mut c_void, wl_display: Option<*mut c_void>) -> Result { + /// `proc_context`. `native` must be live for as long as this is; it's what lets libmpv + /// decode on the card without copying frames back (NVDEC needs nothing). + pub unsafe fn new(player: &Player, get_proc_address: GetProcAddress, proc_context: *mut c_void, native: Native) -> Result { let mut init = ffi::OpenGlInitParams { get_proc_address: Some(get_proc_address), get_proc_address_ctx: proc_context }; let mut params = vec![ ffi::RenderParam { kind: ffi::RENDER_API_TYPE, data: c"opengl".as_ptr() as *mut c_void }, ffi::RenderParam { kind: ffi::RENDER_OPENGL_INIT_PARAMS, data: &mut init as *mut _ as *mut c_void }, ]; - if let Some(display) = wl_display { - params.push(ffi::RenderParam { kind: ffi::RENDER_WL_DISPLAY, data: display }); + let mut drm = ffi::OpenGlDrmParamsV2 { fd: -1, crtc_id: 0, connector_id: 0, atomic_request_ptr: std::ptr::null_mut(), render_fd: -1 }; + match native { + Native::None => {} + Native::Wayland(display) => params.push(ffi::RenderParam { kind: ffi::RENDER_WL_DISPLAY, data: display }), + Native::RenderNode(fd) => { + drm.render_fd = fd; + params.push(ffi::RenderParam { kind: ffi::RENDER_DRM_DISPLAY_V2, data: &mut drm as *mut _ as *mut c_void }); + } } params.push(ffi::RenderParam { kind: ffi::RENDER_INVALID, data: std::ptr::null_mut() }); Ok(Self { context: Context::create(player, &mut params)?, _same_thread: std::marker::PhantomData }) diff --git a/tests/helper.rs b/tests/helper.rs index 2284558..ac9afde 100644 --- a/tests/helper.rs +++ b/tests/helper.rs @@ -26,13 +26,14 @@ fn main() -> ExitCode { if args.first().map(String::as_str) == Some(HELPER_ARG) { helper::run(&args[1..], &Options::cpu(), SANDBOX_CODE, || true); } - let tests: [Test; 6] = [ + let tests: [Test; 7] = [ ("a_video_draws_its_frames_and_stops_on_the_last", a_video_draws_its_frames_and_stops_on_the_last), ("play_after_the_end_starts_again", play_after_the_end_starts_again), ("a_new_size_redraws_the_frame_even_when_stopped", a_new_size_redraws_the_frame_even_when_stopped), ("sound_only_files_say_so_or_play_when_allowed", sound_only_files_say_so_or_play_when_allowed), ("a_file_that_isnt_media_cant_play", a_file_that_isnt_media_cant_play), ("the_last_files_position_and_duration_dont_linger", the_last_files_position_and_duration_dont_linger), + ("an_answer_is_for_the_file_it_was_asked_about", an_answer_is_for_the_file_it_was_asked_about), ]; if args.iter().any(|a| a == "--list") { for (name, _) in tests { @@ -247,3 +248,33 @@ fn the_last_files_position_and_duration_dont_linger(dir: &Path) { } } } + +/// `ask` answers without waiting, and an answer about one file is never taken for the next: +/// loading another turns late answers away and drops untaken ones. +fn an_answer_is_for_the_file_it_was_asked_about(dir: &Path) { + use alias_playback::{Event, Player}; + let player = Player::new(&Options::cpu()).expect("libmpv"); + let answered = |id: u32| { + let deadline = Instant::now() + Duration::from_secs(2); + while Instant::now() < deadline { + if player.wait_event(Duration::from_millis(50)) == Some(Event::Answered(id)) { + return true; + } + } + false + }; + player.ask(c"volume", 1).expect("ask"); + assert!(answered(1), "an answer came"); + assert!(player.answer(1).is_some_and(|v| v.starts_with("100")), "the volume"); + assert_eq!(player.answer(1), None, "taken once"); + // Asked, then another file loaded before the answer is read: it's turned away. + player.ask(c"volume", 2).expect("ask"); + player.load(&sound(dir)).expect("load"); + assert!(!answered(2), "a late answer about the last file"); + assert_eq!(player.answer(2), None); + // Answered but never taken, then a load: dropped. + player.ask(c"volume", 3).expect("ask"); + assert!(answered(3)); + player.load(&sound(dir)).expect("load"); + assert_eq!(player.answer(3), None, "dropped on load"); +}