From 79b026ebdd5de39e5757d2adc2cdd5e0fa583d0b Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 10:53:29 -0700 Subject: [PATCH 01/10] ALI-2358: Videos and songs play, in the jailed GPU helper - A video or song in the list opens in alias-playback's GPU helper: libmpv in a bubblewrap jail, drawing on the card the compositor uses (from linux-dmabuf feedback) and handing its frames over as dmabufs. They show in a subsurface above the window, so they never pass through this process. Sound goes through the session's PulseAudio socket, bound into the jail read-only. - The folder list takes videos and songs, so n, p, Page Up and Page Down move between them and pictures. - Space plays and pauses (after the end, plays from the start), Left and Right seek 5 s (seek-step), f toggles full screen and Escape leaves it. - While a file opens, the window says so; a file that can't play says why. - alias-playback is a git dependency on the branch of its PR #3 until #2 and #3 merge. --- Cargo.lock | 10 ++ Cargo.toml | 4 + src/app.rs | 159 ++++++++++++++++++++++- src/args.rs | 2 +- src/main.rs | 36 ++++-- src/player/gpu.rs | 197 +++++++++++++++++++++++++++++ src/player/mod.rs | 312 ++++++++++++++++++++++++++++++++++++++++++++++ src/wl.rs | 222 ++++++++++++++++++++++++++++++++- 8 files changed, 928 insertions(+), 14 deletions(-) create mode 100644 src/player/gpu.rs create mode 100644 src/player/mod.rs diff --git a/Cargo.lock b/Cargo.lock index e7f52ad..48bb754 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -59,12 +59,22 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "alias-playback" +version = "0.1.0" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#fd8ddc3d9bcf552af15047f37e5e46114e934f74" +dependencies = [ + "libc", + "rustix", +] + [[package]] name = "alias-view" version = "0.1.0" dependencies = [ "accesskit", "accesskit_unix", + "alias-playback", "blocking", "bytemuck", "flate2", diff --git a/Cargo.toml b/Cargo.toml index aa64ee0..0b7a8ae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,10 @@ wayland-protocols = { version = "0.32.13", features = ["client", "staging", "uns xkbcommon = { version = "0.9.0", default-features = false } swash = "0.2.10" rustix = { version = "1.1.6", features = ["fs", "event", "time", "pipe", "process"] } +# Video and music: libmpv in a jailed helper that draws on the graphics card and hands its +# frames over as dmabufs (ALI-2358). On the branch of alias-playback PR #3 (stacked on #2) +# until those merge; then this moves to main. +alias-playback = { git = "https://github.com/aliasproject/alias-playback", branch = "ali-2358-gpu-media" } [profile.release] opt-level = 3 diff --git a/src/app.rs b/src/app.rs index 0adda77..a785b92 100644 --- a/src/app.rs +++ b/src/app.rs @@ -15,6 +15,7 @@ use crate::decode::anim::{Next, Player}; use crate::decode::{Info, Want}; use crate::loader::{Done, Job, Kind, Loader}; use crate::pixels::Pixels; +use crate::player::{self, Media, Phase}; use crate::render::{self, Level}; use crate::text::{self, Text}; use crate::theme::Colors; @@ -86,6 +87,11 @@ pub struct App { pub title: String, pub focused: bool, pub cache_home: PathBuf, + /// The video or song open now, if the current file is one. + pub media: Option, + /// Carried from one video or song to the next. + pub volume: f64, + pub muted: bool, } impl App { @@ -127,6 +133,9 @@ impl App { title: String::new(), focused: false, cache_home, + media: None, + volume: 100.0, + muted: false, } } @@ -198,12 +207,94 @@ impl App { self.ask_current(); self.grid_follow(); } + let size = self.media.as_ref().map(|m| self.media_box(m.kind)); + if let (Some(m), Some(b)) = (&mut self.media, size) { + m.resize((b.w.max(1) as u32, b.h.max(1) as u32)); + } + } + + /// Where a video's frames or a song's cover art go, in physical px. + fn media_box(&self, kind: player::Kind) -> Rect { + let (w, h) = (self.win.0 as i32, self.win.1 as i32); + match kind { + player::Kind::Video => Rect::new(0, 0, w, h), + player::Kind::Music => { + let side = ui::px(crate::tokens::size::COVER_ART as f64, self.scale).min(w.min(h) / 2).max(1); + Rect::new((w - side) / 2, (h - side) / 2, side, side) + } + } + } + + /// Opens the current file in the player if it's a video or song, closes the player if + /// it isn't, and acts on what the player has said. Called on every turn of the loop. + pub fn sync_media(&mut self, wl: &mut Wl) { + let want = if self.grid.is_some() { None } else { self.path().and_then(|p| Some((p.to_path_buf(), player::kind_of(p)?))) }; + match want { + Some((path, _)) if self.media.as_ref().is_some_and(|m| m.path == path) => {} + Some((path, kind)) => { + self.close_media(wl); + let b = self.media_box(kind); + let size = (b.w.max(1) as u32, b.h.max(1) as u32); + self.media = Some(if wl.can_show_video() { + Media::open(path, kind, player::gpu::open_node(wl.render_node_path().as_deref()), size, self.volume, self.muted) + } else { + Media::failed(path, kind, "this desktop can't show video from another process (it lacks linux-dmabuf)".into()) + }); + self.all(); + self.a11y_dirty = true; + } + None => { + if self.media.is_some() { + self.close_media(wl); + self.all(); + self.a11y_dirty = true; + } + } + } + let Some(kind) = self.media.as_ref().map(|m| m.kind) else { return }; + let b = self.media_box(kind); + let scale = self.scale; + if let Some(m) = &mut self.media + && m.pump(wl, b, scale) + { + self.all(); + self.a11y_dirty = true; + } + } + + fn close_media(&mut self, wl: &mut Wl) { + if let Some(old) = self.media.take() { + if old.heard { + self.volume = old.state.volume; + self.muted = old.state.muted; + } + drop(old); + wl.video_end(); + if wl.state.fullscreen { + wl.set_fullscreen(false); + } + } + } + + /// The line drawn in the middle of the window for a video or song that isn't showing + /// a picture yet, or can't. + fn media_message(&self) -> Option { + let m = self.media.as_ref()?; + match m.phase() { + Phase::Opening => Some(format!("Opening {}", self.name())), + Phase::Failed(why) => Some(format!("Can't play {}: {why}", self.name())), + _ => None, + } } /// Asks for whatever the current picture still needs: its screen copy, a bigger one /// for zoom, and then its neighbours. pub fn ask_current(&mut self) { let Some(path) = self.path().map(|p| p.to_path_buf()) else { return }; + // Videos and songs play in the player, not the picture decoder. + if player::kind_of(&path).is_some() { + return; + } let bx = self.win; let entry = self.pictures.entry(path.clone()).or_default(); let stale = entry.screen.as_ref().is_some_and(|s| { @@ -242,7 +333,7 @@ impl App { } let bx = self.win; for i in self.neighbours() { - let Some(path) = self.files.get(i).cloned() else { continue }; + let Some(path) = self.files.get(i).cloned().filter(|p| player::kind_of(p).is_none()) else { continue }; let e = self.pictures.entry(path.clone()).or_default(); if e.screen.is_none() && e.error.is_none() && !e.asked { e.asked = true; @@ -576,6 +667,11 @@ impl App { self.drag = None; } Input::Close => self.quit = true, + Input::VideoReleased(slot) => { + if let Some(m) = &mut self.media { + m.released(slot); + } + } _ => {} } } @@ -628,6 +724,32 @@ impl App { if self.grid.is_some() && self.grid_key(sym) { return; } + if self.grid.is_none() + && let Some(m) = &mut self.media + { + match sym { + k::KEY_space => { + m.toggle(); + return; + } + // In a video or song, Left and Right seek; n, p, Page Up and Page Down still + // change file (Mike, 2026-12-02). + k::KEY_Left | k::KEY_KP_Left | k::KEY_Right | k::KEY_KP_Right => { + let step = crate::tokens::motion::SEEK_STEP.as_secs_f64(); + m.send(player::gpu::Command::SeekBy(if matches!(sym, k::KEY_Left | k::KEY_KP_Left) { -step } else { step })); + return; + } + k::KEY_f if m.kind == player::Kind::Video => { + wl.set_fullscreen(!wl.state.fullscreen); + return; + } + k::KEY_Escape if wl.state.fullscreen && !(self.show_help || self.show_info) => { + wl.set_fullscreen(false); + return; + } + _ => {} + } + } let img = self.img(); let zoomed = img.is_some_and(|img| self.view.zoomed(img, self.win)); let step = (64.0 * self.scale).max(self.win.0.min(self.win.1) as f64 / 10.0); @@ -823,6 +945,10 @@ impl App { } continue; } + // A video or song has no thumbnail yet: its tile stays empty. + if player::kind_of(path).is_some() { + continue; + } jobs.push(Job { path: path.clone(), kind: Kind::Thumb, want: Want::Fit(inner, inner) }); } self.thumbs_asked = jobs.iter().map(|j| j.path.clone()).collect(); @@ -954,13 +1080,17 @@ impl App { if damage.is_empty() || self.frame.len() < (w * h) as usize { return Rect::default(); } - let wants_text = self.show_info || self.show_help || self.toast.is_some() || self.grid.is_some() || self.current().is_some_and(|p| p.error.is_some()) || self.files.is_empty(); + let media_message = if self.grid.is_none() { self.media_message() } else { None }; + let wants_text = + self.show_info || self.show_help || self.toast.is_some() || self.grid.is_some() || self.current().is_some_and(|p| p.error.is_some()) || self.files.is_empty() || media_message.is_some(); if wants_text { self.ensure_text(); } let mut damage = damage; if self.grid.is_some() { self.paint_grid(damage); + } else if self.media.is_some() { + self.paint_media(damage, media_message.as_deref()); } else { damage = self.paint_picture(damage); } @@ -1034,6 +1164,20 @@ impl App { damage } + /// The window under a video or song: the background, and the line saying it's opening + /// or why it can't play. The frames are in the subsurface above. + fn paint_media(&mut self, damage: Rect, message: Option<&str>) { + let (w, h) = (self.win.0 as i32, self.win.1 as i32); + let mut c = Canvas::new(&mut self.frame, w, h); + c.set_clip(damage); + c.fill(damage, self.colors.base); + self.drawn = None; + let (Some(msg), Some(t)) = (message, self.text.as_mut()) else { return }; + let tw = t.measure(msg); + let x = ((w as f32 - tw) / 2.0).max(ui::px(ui::MARGIN, self.scale) as f32); + t.draw_fitted(&mut c, msg, x, h / 2, (w - ui::px(ui::MARGIN, self.scale) * 2) as f32, self.colors.foreground); + } + fn paint_grid(&mut self, damage: Rect) { let (w, h) = (self.win.0 as i32, self.win.1 as i32); let layout = self.grid_layout(); @@ -1109,6 +1253,17 @@ impl App { let title = self.window_title(); let picture = match self.current() { _ if self.files.is_empty() => "No pictures left".to_string(), + _ if self.media.is_some() => { + let state = match self.media.as_ref().map(Media::phase) { + Some(Phase::Opening) => "opening".to_string(), + Some(Phase::Playing) => "playing".to_string(), + Some(Phase::Paused) => "paused".to_string(), + Some(Phase::Ended) => "ended".to_string(), + Some(Phase::Failed(why)) => format!("can't be played: {why}"), + None => String::new(), + }; + format!("{}, {} of {}, {state}", self.name(), self.cur + 1, self.files.len()) + } Some(p) if p.error.is_some() => format!("{}, {} of {}, can't be shown: {}", self.name(), self.cur + 1, self.files.len(), p.error.as_deref().unwrap_or("")), Some(p) if p.screen.is_none() => format!("{}, {} of {}, loading", self.name(), self.cur + 1, self.files.len()), _ => format!("{}, {} of {}", self.name(), self.cur + 1, self.files.len()), diff --git a/src/args.rs b/src/args.rs index 1585047..5e493a7 100644 --- a/src/args.rs +++ b/src/args.rs @@ -157,7 +157,7 @@ pub fn list_folder(dir: &Path, include: Option<&Path>) -> Vec { let name = e.file_name(); let s = name.to_string_lossy(); let wanted = include.is_some_and(|p| p.file_name() == Some(name.as_os_str())); - wanted || (!s.starts_with('.') && is_picture_name(&s) && e.path().is_file()) + wanted || (!s.starts_with('.') && (is_picture_name(&s) || crate::player::kind_of_name(&s).is_some()) && e.path().is_file()) }) .map(|e| e.file_name()) .collect(); diff --git a/src/main.rs b/src/main.rs index d14bd64..16fd5c2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,6 +16,7 @@ mod decode; mod exif; mod loader; mod pixels; +mod player; mod render; mod sort; mod text; @@ -74,6 +75,11 @@ fn restart_with_fixed_mmap_threshold() { fn main() { restart_with_fixed_mmap_threshold(); let argv: Vec<_> = std::env::args_os().skip(1).collect(); + // The video player's helper, inside its jail (src/player/gpu.rs). + if argv.first().is_some_and(|a| a == player::gpu::HELPER_ARG) { + let rest: Vec = argv[1..].iter().map(|a| a.to_string_lossy().into_owned()).collect(); + player::gpu::helper_main(&rest); + } if argv.len() == 2 && argv[0] == decode::heif::HELPER_ARG { std::process::exit(decode::heif::helper_main(std::path::Path::new(&argv[1]))); } @@ -178,7 +184,11 @@ fn run(o: Opening) -> i32 { let (info_tx, info_rx) = channel::(); let (box_tx, box_rx) = channel::(); let asked: Arc> = Arc::new(Mutex::new(Want::Fit(1920, 1080))); - { + // A video or song opens in the player once the window is up, not in the decoder. + let first_media = player::kind_of(&first).is_some(); + if first_media { + drop(info_tx); + } else { let (done, asked, first) = (loader.sender(), asked.clone(), first.clone()); let _ = std::thread::Builder::new().name("alias-view-open".into()).spawn(move || { let result = decode::decode_with(&first, threads, |info| { @@ -209,17 +219,22 @@ fn run(o: Opening) -> i32 { let (screen, scale) = wl.likely_output().map(|o| o.logical_and_scale()).unwrap_or(((1920, 1080), 1.0)); // A broken file says nothing here and closes the channel; the window still opens // to say what's wrong. - let info = info_rx.recv_timeout(Duration::from_secs(5)).ok(); - let img = info.as_ref().map(|i| (i.width, i.height)).filter(|&(w, h)| w > 0 && h > 0).unwrap_or((1, 1)); + let info = if first_media { None } else { info_rx.recv_timeout(Duration::from_secs(5)).ok() }; + // A video's size is known only once the player has looked: its window starts at 16:9, + // as big as the screen share allows, and keeps its size, as for pictures. + let fallback = if first_media { (7680, 4320) } else { (1, 1) }; + let img = info.as_ref().map(|i| (i.width, i.height)).filter(|&(w, h)| w > 0 && h > 0).unwrap_or(fallback); let (lw, lh) = window_for(img, screen, scale); let phys = ((lw as f64 * scale).round() as u32, (lh as f64 * scale).round() as u32); let _ = box_tx.send(Want::Fit(phys.0, phys.1)); mark(stamp, "headers read"); let mut app = App::new(o.files, o.start, colors, loader, threads); - let entry = app.pictures.entry(first.clone()).or_default(); - entry.asked = true; - entry.info = info; + if !first_media { + let entry = app.pictures.entry(first.clone()).or_default(); + entry.asked = true; + entry.info = info; + } app.title = app.window_title(); wl.open(&app.title, APP_ID, lw, lh, scale); let (pw, ph) = wl.physical_size(); @@ -268,6 +283,9 @@ fn run(o: Opening) -> i32 { app.set_files(files); folder = None; } + if wl.state.configured { + app.sync_media(&mut wl); + } if let Some(a) = &a11y { let reqs: Vec<_> = a.actions.try_iter().collect(); for r in reqs { @@ -297,7 +315,7 @@ fn run(o: Opening) -> i32 { if wl.state.configured && configured_at.is_none() { configured_at = Some(now); } - let waiting_for_first = first_frame && app.current().is_some_and(|p| p.screen.is_none() && p.error.is_none()) && configured_at.is_some_and(|t| now < t + FIRST_FRAME_WAIT); + let waiting_for_first = first_frame && !first_media && app.current().is_some_and(|p| p.screen.is_none() && p.error.is_none()) && configured_at.is_some_and(|t| now < t + FIRST_FRAME_WAIT); if wl.state.configured && !waiting_for_first && (wl.must_paint() || (wl.can_paint() && !app.damage.is_empty())) { if wl.must_paint() || first_frame { app.damage = canvas::Rect::new(0, 0, app.win.0 as i32, app.win.1 as i32); @@ -384,6 +402,10 @@ fn run(o: Opening) -> i32 { fds.push(PollFd::from_borrowed_fd(w.as_fd(), PollFlags::IN)); fds.len() - 1 }); + // The player's messages: read on the next turn, by sync_media. + if let Some(f) = app.media.as_ref().and_then(|m| m.session_fd()) { + fds.push(PollFd::from_borrowed_fd(f, PollFlags::IN)); + } let _ = poll(&mut fds, timeout.as_ref()); let ready = |i: usize| fds[i].revents().intersects(PollFlags::IN | PollFlags::ERR | PollFlags::HUP); let wl_ready = ready(0); diff --git a/src/player/gpu.rs b/src/player/gpu.rs new file mode 100644 index 0000000..2df9353 --- /dev/null +++ b/src/player/gpu.rs @@ -0,0 +1,197 @@ +//! The playback helper: libmpv in a bubblewrap jail, drawing on the graphics card and +//! handing its frames over as dmabufs (`alias_playback::gpu_helper`). Untrusted video never +//! decodes in this process. This is the only file that knows the helper's protocol; the +//! rest of the player sees [`Said`] and sends [`Command`]s. +//! +//! The helper is this program, started again inside the jail with [`HELPER_ARG`]. + +use std::fs::File; +use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; +use std::path::Path; +use std::process::Child; + +use alias_playback::gpu_helper::{self, Started}; +pub use alias_playback::gpu_helper::{MetaField, Said}; +use alias_playback::helper::{EXIT_BAD_START, EXIT_CANT_PLAY, EXIT_NO_MPV}; +use alias_playback::{Audio, Hwdec, Options, RenderPath, Vendor, jail}; + +pub const HELPER_ARG: &str = "--gpu-helper"; +/// The helper's exit code when its own lock-down (Landlock, seccomp) couldn't be applied. +const EXIT_SANDBOX: i32 = 6; + +/// What the player asks of the helper. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Command { + Play, + Pause, + /// By this many seconds, back if negative. + SeekBy(f64), + /// To this many seconds from the start. + SeekTo(f64), + /// 0 to 100. + Volume(f64), + Mute(bool), + /// The frame's box, in physical pixels: the helper draws the largest frame with the + /// video's shape inside it. + Size(u32, u32), + /// The compositor is done with this buffer. + Release(usize), +} + +impl Command { + fn line(self) -> String { + match self { + Command::Play => "play".into(), + Command::Pause => "pause".into(), + Command::SeekBy(s) => format!("seek {s:.3}"), + Command::SeekTo(s) => format!("seekat {:.3}", s.max(0.0)), + Command::Volume(v) => format!("volume {:.0}", v.clamp(0.0, 100.0)), + Command::Mute(true) => "mute".into(), + Command::Mute(false) => "unmute".into(), + Command::Size(w, h) => format!("size {} {}", w.max(1), h.max(1)), + Command::Release(slot) => format!("release {slot}"), + } + } +} + +/// The render node at `path`, or the first there is when the compositor didn't say. +pub fn open_node(path: Option<&Path>) -> Result { + let opened = path.and_then(|p| std::fs::OpenOptions::new().read(true).write(true).open(p).ok()).map(OwnedFd::from); + match opened { + Some(fd) => Ok(fd), + None => alias_playback::gpu::first_render_node().map_err(|_| "no graphics card can be opened to draw it".to_string()), + } +} + +/// One file playing in one helper. +pub struct Session { + child: Child, + socket: OwnedFd, + /// The socket has closed: the helper is gone. + pub gone: bool, +} + +impl Session { + /// Starts a helper for `path` on the card at `node`, drawing into a box of `size` + /// physical pixels. `Err` says why, in words for the screen. + pub fn start(path: &Path, node: OwnedFd, size: (u32, u32)) -> Result { + let file = File::open(path).map_err(|e| match e.kind() { + std::io::ErrorKind::NotFound => "it isn't there any more".to_string(), + std::io::ErrorKind::PermissionDenied => "you don't have permission to read it".to_string(), + _ => format!("it can't be read ({e})"), + })?; + let vendor = alias_playback::gpu::vendor(&node); + let exe = jail::own_exe().map_err(|_| "Alias View's own program file is gone; was it updated? Open it again".to_string())?; + let sound = jail::sound_socket(); + let mut command = std::process::Command::new("bwrap"); + command.args(jail::gpu_arguments(&exe, vendor, sound.as_deref())).arg(HELPER_ARG).arg(vendor_word(vendor)).arg(if sound.is_some() { "sound" } else { "silent" }); + let Started { child, socket } = gpu_helper::start(command, file, node, size, false).map_err(|e| { + if e.kind() == std::io::ErrorKind::NotFound { "bubblewrap (bwrap), which keeps video in a sandbox, isn't installed".to_string() } else { format!("the player didn't start ({e})") } + })?; + rustix::io::ioctl_fionbio(&socket, true).map_err(|_| "the player didn't start".to_string())?; + Ok(Session { child, socket, gone: false }) + } + + /// For the loop's poll. + pub fn fd(&self) -> BorrowedFd<'_> { + self.socket.as_fd() + } + + /// Every message waiting, with the descriptors that came with it. A message that isn't + /// sensible is dropped, with its descriptors. Sets `gone` when the helper has gone. + pub fn read(&mut self) -> Vec<(Said, Vec)> { + let mut out = Vec::new(); + loop { + match gpu_helper::receive(&self.socket) { + Ok(Some((text, fds))) => { + if let Some(said) = gpu_helper::parse_said(&text) { + out.push((said, fds)); + } + } + Ok(None) => { + self.gone = true; + break; + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => { + self.gone = true; + break; + } + } + } + out + } + + pub fn send(&self, c: Command) { + let _ = gpu_helper::send(&self.socket, &c.line(), &[]); + } + + /// After `gone`: why, if it wasn't a clean exit. Waits for the helper, which has + /// closed its socket and so is ending. + pub fn failure(&mut self) -> Option { + let status = self.child.wait().ok()?; + match status.code() { + Some(0) => None, + Some(EXIT_NO_MPV) => Some("libmpv isn't installed".into()), + Some(EXIT_SANDBOX) => Some("the sandbox video plays in couldn't be set up".into()), + Some(EXIT_BAD_START) => Some("the player didn't start".into()), + Some(EXIT_CANT_PLAY) | None => Some("the player stopped".into()), + Some(_) => Some("the player stopped".into()), + } + } +} + +impl Drop for Session { + fn drop(&mut self) { + // Closing the socket ends the helper; bubblewrap takes the jail with it. + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn vendor_word(v: Vendor) -> &'static str { + match v { + Vendor::Nvidia => "nvidia", + Vendor::Amd => "amd", + Vendor::Intel => "intel", + Vendor::Apple => "apple", + Vendor::Other => "other", + } +} + +/// The helper's `main`, inside the jail: `HELPER_ARG VENDOR sound|silent WIDTH HEIGHT`. +/// Never returns. +pub fn helper_main(args: &[String]) -> ! { + let vendor = match args.first().map(String::as_str) { + Some("nvidia") => Vendor::Nvidia, + Some("amd") => Vendor::Amd, + Some("intel") => Vendor::Intel, + Some("apple") => Vendor::Apple, + Some("other") => Vendor::Other, + _ => std::process::exit(EXIT_BAD_START), + }; + let audio = match args.get(1).map(String::as_str) { + Some("sound") => Audio::Pulse, + Some("silent") => Audio::Off, + _ => std::process::exit(EXIT_BAD_START), + }; + // A song's cover art is drawn as its picture. + let options = Options { render: RenderPath::Gpu, hwdec: Hwdec::For(vendor), audio, cover_art: true, start_paused: true }; + gpu_helper::run(&args[2..], &options, EXIT_SANDBOX, jail::lock_down_gpu_helper) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn commands_are_the_lines_the_helper_reads() { + assert_eq!(Command::SeekBy(-5.0).line(), "seek -5.000"); + assert_eq!(Command::SeekTo(-1.0).line(), "seekat 0.000", "never before the start"); + assert_eq!(Command::Volume(130.0).line(), "volume 100"); + assert_eq!(Command::Mute(true).line(), "mute"); + assert_eq!(Command::Size(0, 720).line(), "size 1 720"); + assert_eq!(Command::Release(2).line(), "release 2"); + } +} diff --git a/src/player/mod.rs b/src/player/mod.rs new file mode 100644 index 0000000..3261085 --- /dev/null +++ b/src/player/mod.rs @@ -0,0 +1,312 @@ +//! Video and music (ALI-2358). A file the viewer recognises as video or sound plays in the +//! jailed GPU helper (`gpu`); its frames, or a song's cover art, show in a subsurface above +//! the window. The window's own surface keeps the background and whatever is drawn over it. + +pub mod gpu; + +use std::os::fd::OwnedFd; +use std::path::{Path, PathBuf}; + +use alias_playback::helper::PlayState; + +use crate::canvas::Rect; +use crate::wl::{VIDEO_SLOTS, VideoBuffer, Wl}; +use gpu::{Command, MetaField, Said, Session}; + +/// The containers aliasOS sends to a video player (`install/user/mimetypes.sh`), and their +/// usual other names. +const VIDEO: &[&str] = &["mp4", "m4v", "mkv", "webm", "mov", "avi", "flv", "wmv", "mpeg", "mpg", "ogv", "ogm", "3gp", "3g2", "asf"]; +/// Sound files. Plain `.ogg` is here: it's nearly always sound, and a video in one still +/// plays, shown as its picture. +const MUSIC: &[&str] = &["mp3", "flac", "ogg", "oga", "opus", "m4a", "aac", "wav", "wma", "aif", "aiff", "mka", "wv", "ape"]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Video, + Music, +} + +pub fn kind_of_name(name: &str) -> Option { + let (stem, ext) = name.rsplit_once('.')?; + if stem.is_empty() { + return None; + } + let is = |list: &[&str]| list.iter().any(|e| ext.eq_ignore_ascii_case(e)); + if is(VIDEO) { + Some(Kind::Video) + } else if is(MUSIC) { + Some(Kind::Music) + } else { + None + } +} + +pub fn kind_of(path: &Path) -> Option { + kind_of_name(&path.file_name()?.to_string_lossy()) +} + +/// Where the player is, in the words the screen and the screen reader use. +#[derive(Clone, Debug, PartialEq)] +pub enum Phase { + Opening, + Playing, + Paused, + /// Stopped on its last frame. + Ended, + Failed(String), +} + +/// The song's tags, as the helper said them (already cleaned). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Meta { + pub title: Option, + pub artist: Option, + pub album: Option, +} + +/// One video or song, open. +pub struct Media { + pub path: PathBuf, + pub kind: Kind, + session: Option, + pub state: PlayState, + /// The helper has said where it is at least once. + pub heard: bool, + buffers: [Option; VIDEO_SLOTS], + /// The buffer on screen. + pub shown: Option, + /// It has a picture: a video's frames or a song's cover art. `None` until known. + pub has_picture: Option, + pub meta: Meta, + pub error: Option, + /// The size asked of the helper, so it's only told of changes. + asked: (u32, u32), +} + +impl Media { + /// Opens `path` in a new helper on the card at `node`, playing from the start, with the + /// volume and mute the last file had. + pub fn open(path: PathBuf, kind: Kind, node: Result, size: (u32, u32), volume: f64, muted: bool) -> Media { + let mut m = Media { + path, + kind, + session: None, + state: PlayState { volume, muted, ..PlayState::default() }, + heard: false, + buffers: Default::default(), + shown: None, + has_picture: None, + meta: Meta::default(), + error: None, + asked: size, + }; + match node.and_then(|node| Session::start(&m.path, node, size)) { + Ok(s) => { + s.send(Command::Volume(volume)); + s.send(Command::Mute(muted)); + s.send(Command::Play); + m.session = Some(s); + } + Err(e) => m.error = Some(e), + } + m + } + + /// A media file that can't be opened at all, with why. + pub fn failed(path: PathBuf, kind: Kind, why: String) -> Media { + let mut m = Media::open(path, kind, Err(why), (1, 1), 100.0, false); + m.session = None; + m + } + + pub fn phase(&self) -> Phase { + if let Some(e) = &self.error { + Phase::Failed(e.clone()) + } else if !self.heard { + Phase::Opening + } else if self.state.ended { + Phase::Ended + } else if self.state.paused { + Phase::Paused + } else { + Phase::Playing + } + } + + pub fn session_fd(&self) -> Option> { + self.session.as_ref().filter(|s| !s.gone).map(|s| s.fd()) + } + + pub fn send(&self, c: Command) { + if let Some(s) = &self.session { + s.send(c); + } + } + + /// Play or pause. At the end, plays again from the start. + pub fn toggle(&mut self) { + match self.phase() { + Phase::Ended => { + self.send(Command::SeekTo(0.0)); + self.send(Command::Play); + } + Phase::Paused => self.send(Command::Play), + Phase::Playing | Phase::Opening => self.send(Command::Pause), + Phase::Failed(_) => {} + } + } + + /// The frame's box changed size (physical px). + pub fn resize(&mut self, size: (u32, u32)) { + if size != self.asked { + self.asked = size; + self.send(Command::Size(size.0, size.1)); + } + } + + /// The compositor let a buffer go. + pub fn released(&mut self, slot: usize) { + if self.shown != Some(slot) { + self.send(Command::Release(slot)); + } + } + + /// Reads the helper's messages and acts on them: buffers become `wl_buffer`s, frames + /// are shown centred in `frame_box` (physical px; `scale` turns them logical). Returns + /// true if what's drawn or said about it changed. + pub fn pump(&mut self, wl: &mut Wl, frame_box: Rect, scale: f64) -> bool { + let Some(session) = &mut self.session else { return false }; + let messages = session.read(); + let gone = session.gone; + let mut changed = false; + for (said, mut fds) in messages { + match said { + Said::Hello | Said::Dropped { .. } | Said::Decoder(_) => {} + Said::Buffer { slot, width, height, fourcc, modifier, stride, offset } => { + let Some(fd) = fds.pop().filter(|_| fds.is_empty()) else { continue }; + let b = VideoBuffer { width, height, fourcc, modifier, stride, offset }; + wl.video_begin(); + wl.video_buffer(slot, fd, b); + self.buffers[slot] = Some(b); + if self.shown == Some(slot) { + self.shown = None; + } + } + Said::Frame { slot } => { + let Some(b) = self.buffers[slot] else { + self.send(Command::Release(slot)); + continue; + }; + let place = centre(b.width, b.height, frame_box, scale); + // The one shown until now is given back when the compositor releases it. + if wl.video_frame(slot, place) { + self.shown = Some(slot); + if self.has_picture != Some(true) { + self.has_picture = Some(true); + changed = true; + } + } else { + self.send(Command::Release(slot)); + } + } + Said::State(s) => { + changed |= !self.heard + || s.paused != self.state.paused + || s.ended != self.state.ended + || s.muted != self.state.muted + || (s.volume - self.state.volume).abs() >= 0.5 + || (s.duration - self.state.duration).abs() >= 0.5 + || s.position.floor() != self.state.position.floor(); + self.state = s; + self.heard = true; + } + Said::Meta(field, text) => { + let slot = match field { + MetaField::Title => &mut self.meta.title, + MetaField::Artist => &mut self.meta.artist, + MetaField::Album => &mut self.meta.album, + }; + *slot = Some(text); + changed = true; + } + Said::NoVideo => { + self.has_picture = Some(false); + changed = true; + } + Said::CantPlay => { + self.error = Some(self.cant_play_reason()); + changed = true; + } + } + } + if gone { + let why = self.session.as_mut().and_then(Session::failure); + if self.error.is_none() { + self.error = Some(why.unwrap_or_else(|| "the player stopped".into())); + } + self.session = None; + changed = true; + } + changed + } + + /// Why it can't play, in the canvas's words. + fn cant_play_reason(&self) -> String { + if self.heard && self.state.position >= 1.0 { format!("it's damaged after {}", clock(self.state.position)) } else { "it's damaged or in a format that can't be played".into() } + } +} + +/// `w`×`h` physical px centred in `b`, as logical x, y, width and height. +fn centre(w: u32, h: u32, b: Rect, scale: f64) -> (i32, i32, i32, i32) { + let s = scale.max(1e-6); + let x = b.x as f64 + (b.w as f64 - w as f64) / 2.0; + let y = b.y as f64 + (b.h as f64 - h as f64) / 2.0; + ((x / s).round() as i32, (y / s).round() as i32, (w as f64 / s).round() as i32, (h as f64 / s).round() as i32) +} + +/// A time as the player writes it: 0:05, 4:56, 1:02:03. +pub fn clock(seconds: f64) -> String { + let t = if seconds.is_finite() { seconds.max(0.0) as u64 } else { 0 }; + let (h, m, s) = (t / 3600, t / 60 % 60, t % 60); + if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn files_are_told_apart_by_name() { + assert_eq!(kind_of_name("clip.MP4"), Some(Kind::Video)); + assert_eq!(kind_of_name("a.mkv"), Some(Kind::Video)); + assert_eq!(kind_of_name("song.flac"), Some(Kind::Music)); + assert_eq!(kind_of_name("song.ogg"), Some(Kind::Music)); + assert_eq!(kind_of_name("film.ogv"), Some(Kind::Video)); + assert_eq!(kind_of_name("photo.jpg"), None); + assert_eq!(kind_of_name(".mp4"), None, "a hidden name with no stem"); + assert_eq!(kind_of_name("mp4"), None); + } + + #[test] + fn no_name_is_both_a_picture_and_media() { + for ext in VIDEO.iter().chain(MUSIC) { + assert!(!crate::decode::is_picture_name(&format!("x.{ext}")), "{ext}"); + } + } + + #[test] + fn times_read_as_a_clock() { + assert_eq!(clock(0.0), "0:00"); + assert_eq!(clock(83.9), "1:23"); + assert_eq!(clock(296.0), "4:56"); + assert_eq!(clock(3723.0), "1:02:03"); + assert_eq!(clock(f64::NAN), "0:00"); + assert_eq!(clock(-4.0), "0:00"); + } + + #[test] + fn a_frame_sits_in_the_middle_of_its_box() { + assert_eq!(centre(1920, 800, Rect::new(0, 0, 1920, 1080), 1.0), (0, 140, 1920, 800)); + assert_eq!(centre(1000, 1000, Rect::new(0, 0, 2000, 1000), 2.0), (250, 0, 500, 500)); + } +} diff --git a/src/wl.rs b/src/wl.rs index 0f4a07b..01321bb 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -5,22 +5,28 @@ //! //! Buffers are memfds written with `pwrite` rather than mapped, so this file needs no //! unsafe code: the copy costs about a millisecond for a full window. +//! +//! A video or a song's cover art is a subsurface above the window, showing the playback +//! helper's dmabufs through `linux-dmabuf` (src/player/gpu.rs): the frames never pass +//! through this process. use std::collections::VecDeque; use std::fs::File; use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; use std::os::unix::fs::FileExt; +use std::path::PathBuf; use std::sync::Arc; use rustix::fs::{MemfdFlags, ftruncate, memfd_create}; use rustix::time::{Itimerspec, TimerfdClockId, TimerfdFlags, TimerfdTimerFlags, Timespec, timerfd_create, timerfd_settime}; use wayland_client::protocol::{ - wl_buffer, wl_callback, wl_compositor, wl_data_device, wl_data_device_manager, wl_data_offer, wl_data_source, wl_keyboard, wl_output, wl_pointer, wl_registry, wl_seat, wl_shm, wl_shm_pool, - wl_surface, + wl_buffer, wl_callback, wl_compositor, wl_data_device, wl_data_device_manager, wl_data_offer, wl_data_source, wl_keyboard, wl_output, wl_pointer, wl_region, wl_registry, wl_seat, wl_shm, + wl_shm_pool, wl_subcompositor, wl_subsurface, wl_surface, }; use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle, WEnum, event_created_child}; use wayland_protocols::wp::cursor_shape::v1::client::{wp_cursor_shape_device_v1 as cursor_dev, wp_cursor_shape_manager_v1 as cursor_mgr}; use wayland_protocols::wp::fractional_scale::v1::client::{wp_fractional_scale_manager_v1 as frac_mgr, wp_fractional_scale_v1 as frac}; +use wayland_protocols::wp::linux_dmabuf::zv1::client::{zwp_linux_buffer_params_v1 as dmabuf_params, zwp_linux_dmabuf_feedback_v1 as dmabuf_feedback, zwp_linux_dmabuf_v1 as dmabuf}; use wayland_protocols::wp::pointer_gestures::zv1::client::{zwp_pointer_gesture_pinch_v1 as pinch, zwp_pointer_gestures_v1 as gestures}; use wayland_protocols::wp::viewporter::client::{wp_viewport, wp_viewporter}; use wayland_protocols::xdg::decoration::zv1::client::{zxdg_decoration_manager_v1 as deco_mgr, zxdg_toplevel_decoration_v1 as deco}; @@ -78,8 +84,38 @@ pub enum Input { Resized, Close, Focus(bool), + /// The compositor is done with a video buffer: the helper may draw into it again. + VideoReleased(usize), +} + +/// How many video buffers the helper keeps in turn (`gpu_helper::SLOTS`). +pub const VIDEO_SLOTS: usize = alias_playback::gpu_helper::SLOTS; + +/// A video buffer's layout, as the helper describes it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct VideoBuffer { + pub width: u32, + pub height: u32, + pub fourcc: u32, + pub modifier: u64, + pub stride: u32, + pub offset: u32, +} + +/// The subsurface a video or cover art is shown in, above the window's own surface. +struct VideoLayer { + surface: wl_surface::WlSurface, + sub: wl_subsurface::WlSubsurface, + viewport: Option, + buffers: [Option<(wl_buffer::WlBuffer, VideoBuffer)>; VIDEO_SLOTS], + /// Where it sits, in logical px, and the buffer on it. + place: Option<(i32, i32, i32, i32)>, + shown: Option, } +/// A video buffer's slot, as its `wl_buffer`'s data. +pub struct VideoSlot(usize); + /// Makes the clipboard's data when another program asks for it, on a thread of its /// own: a picture is only encoded as PNG if something pastes it. pub type Producer = Arc Option>> + Send + Sync>; @@ -142,6 +178,14 @@ pub struct State { deco_manager: Option, xout_manager: Option, gestures: Option, + subcompositor: Option, + dmabuf: Option, + /// The compositor's main graphics device (`dev_t`), from dmabuf feedback. + main_device: Option, + video: Option, + /// In full screen, as the compositor last said. + pub fullscreen: bool, + pending_fullscreen: bool, pub outputs: Vec, /// The output the window is on, once the compositor says. pub entered: Option, @@ -222,6 +266,12 @@ impl Wl { deco_manager: None, xout_manager: None, gestures: None, + subcompositor: None, + dmabuf: None, + main_device: None, + video: None, + fullscreen: false, + pending_fullscreen: false, outputs: Vec::new(), entered: None, surface: None, @@ -327,6 +377,109 @@ impl Wl { } } + /// Asks for full screen, or back to a window. The compositor's configure says what it did. + pub fn set_fullscreen(&self, on: bool) { + if let Some(t) = &self.state.toplevel { + if on { + t.set_fullscreen(None); + } else { + t.unset_fullscreen(); + } + } + } + + /// Whether video can be shown: the compositor takes dmabufs and subsurfaces. + pub fn can_show_video(&self) -> bool { + self.state.dmabuf.is_some() && self.state.subcompositor.is_some() + } + + /// The render node of the card the compositor draws with, when it said which. The + /// playback helper draws there, so its buffers need no copy to be shown. + pub fn render_node_path(&self) -> Option { + render_node_for(self.state.main_device?) + } + + /// Makes the video subsurface, above the window and below nothing yet, if there isn't + /// one. It shows nothing until a frame arrives. + pub fn video_begin(&mut self) { + let s = &mut self.state; + if s.video.is_some() { + return; + } + let (Some(compositor), Some(subs), Some(parent)) = (&s.compositor, &s.subcompositor, &s.surface) else { return }; + let surface = compositor.create_surface(&self.qh, ()); + let sub = subs.get_subsurface(&surface, parent, &self.qh, ()); + // Frames arrive at the video's own pace, not the window's. + sub.set_desync(); + // No input: the window beneath takes the pointer, as it does for a picture. + let empty = compositor.create_region(&self.qh, ()); + surface.set_input_region(Some(&empty)); + empty.destroy(); + let viewport = s.viewporter.as_ref().map(|v| v.get_viewport(&surface, &self.qh, ())); + s.video = Some(VideoLayer { surface, sub, viewport, buffers: Default::default(), place: None, shown: None }); + } + + /// The helper described a buffer and sent its dmabuf: makes the `wl_buffer` for it. + pub fn video_buffer(&mut self, slot: usize, fd: OwnedFd, b: VideoBuffer) { + let (Some(d), Some(v)) = (&self.state.dmabuf, &mut self.state.video) else { return }; + if slot >= VIDEO_SLOTS { + return; + } + let params = d.create_params(&self.qh, ()); + params.add(fd.as_fd(), 0, b.offset, b.stride, (b.modifier >> 32) as u32, b.modifier as u32); + let wl = params.create_immed(b.width as i32, b.height as i32, b.fourcc, dmabuf_params::Flags::empty(), &self.qh, VideoSlot(slot)); + params.destroy(); + if let Some((old, _)) = v.buffers[slot].replace((wl, b)) { + // Still on screen: destroyed when the compositor lets it go (see the release). + if v.shown != Some(slot) { + old.destroy(); + } + } + if v.shown == Some(slot) { + v.shown = None; + } + } + + /// Shows the frame in `slot` at `place`: x, y, width and height in logical px. Returns + /// false if the slot has no buffer, so the caller gives it straight back. + pub fn video_frame(&mut self, slot: usize, place: (i32, i32, i32, i32)) -> bool { + let Some(v) = &mut self.state.video else { return false }; + let Some((wl, b)) = v.buffers.get(slot).and_then(|b| b.as_ref()) else { return false }; + let moved = v.place != Some(place); + if moved { + v.sub.set_position(place.0, place.1); + if let Some(vp) = &v.viewport { + vp.set_destination(place.2.max(1), place.3.max(1)); + } + v.place = Some(place); + } + v.surface.attach(Some(wl), 0, 0); + v.surface.damage_buffer(0, 0, b.width as i32, b.height as i32); + v.surface.commit(); + v.shown = Some(slot); + // A subsurface's position takes effect with its parent's next commit. + if moved && let Some(p) = &self.state.surface { + p.commit(); + } + true + } + + /// Ends the video: the subsurface and its buffers go. + pub fn video_end(&mut self) { + let Some(v) = self.state.video.take() else { return }; + for (wl, _) in v.buffers.into_iter().flatten() { + wl.destroy(); + } + if let Some(vp) = v.viewport { + vp.destroy(); + } + v.sub.destroy(); + v.surface.destroy(); + if let Some(p) = &self.state.surface { + p.commit(); + } + } + pub fn set_title(&self, title: &str) { if let Some(t) = &self.state.toplevel { t.set_title(title.to_string()); @@ -455,6 +608,16 @@ impl Wl { } } +/// The render node (`/dev/dri/renderD*`) of the graphics device `dev`, which may be its +/// primary node: both list the render node in /sys. +fn render_node_for(dev: u64) -> Option { + let (major, minor) = (rustix::fs::major(dev), rustix::fs::minor(dev)); + let drm = PathBuf::from(format!("/sys/dev/char/{major}:{minor}/device/drm")); + let mut names: Vec = std::fs::read_dir(drm).ok()?.filter_map(|e| e.ok()?.file_name().into_string().ok()).filter(|n| n.starts_with("renderD")).collect(); + names.sort(); + names.into_iter().next().map(|n| PathBuf::from("/dev/dri").join(n)) +} + fn shape_of(c: Cursor) -> cursor_dev::Shape { match c { Cursor::Default => cursor_dev::Shape::Default, @@ -526,6 +689,10 @@ impl State { } fn apply_size(&mut self) { + if self.pending_fullscreen != self.fullscreen { + self.fullscreen = self.pending_fullscreen; + self.inputs.push_back(Input::Resized); + } if let Some((w, h)) = self.pending_size.take() && w > 0 && h > 0 @@ -554,6 +721,15 @@ impl Dispatch for State { "zxdg_decoration_manager_v1" => s.deco_manager = Some(r.bind(name, 1, qh, ())), "zxdg_output_manager_v1" => s.xout_manager = Some(r.bind(name, version.min(3), qh, ())), "zwp_pointer_gestures_v1" => s.gestures = Some(r.bind(name, version.min(3), qh, ())), + "wl_subcompositor" => s.subcompositor = Some(r.bind(name, 1, qh, ())), + "zwp_linux_dmabuf_v1" if version >= 3 => { + let d: dmabuf::ZwpLinuxDmabufV1 = r.bind(name, version.min(4), qh, ()); + // Which card the compositor draws with: the helper draws on the same. + if version >= 4 { + d.get_default_feedback(qh, ()); + } + s.dmabuf = Some(d); + } "wl_output" => { let o: wl_output::WlOutput = r.bind(name, version.min(4), qh, name); let xdg = s.xout_manager.as_ref().map(|m| m.get_xdg_output(&o, qh, name)).is_some(); @@ -593,8 +769,40 @@ ignore_events!( wl_data_device_manager::WlDataDeviceManager, xout_mgr::ZxdgOutputManagerV1, gestures::ZwpPointerGesturesV1, + wl_subcompositor::WlSubcompositor, + wl_subsurface::WlSubsurface, + wl_region::WlRegion, + dmabuf::ZwpLinuxDmabufV1, + dmabuf_params::ZwpLinuxBufferParamsV1, ); +impl Dispatch for State { + fn event(s: &mut State, _: &dmabuf_feedback::ZwpLinuxDmabufFeedbackV1, e: dmabuf_feedback::Event, _: &(), _: &Connection, _: &QueueHandle) { + // The format table's descriptor is dropped with the event: formats are the + // helper's choice, and every compositor takes XRGB8888. + if let dmabuf_feedback::Event::MainDevice { device } = e + && let Ok(bytes) = <[u8; 8]>::try_from(device.as_slice()) + { + s.main_device = Some(u64::from_ne_bytes(bytes)); + } + } +} + +impl Dispatch for State { + fn event(s: &mut State, b: &wl_buffer::WlBuffer, e: wl_buffer::Event, slot: &VideoSlot, _: &Connection, _: &QueueHandle) { + if let wl_buffer::Event::Release = e { + // A buffer replaced since it was attached is destroyed once let go; the helper + // isn't told, as it holds a new one in that slot. + let current = s.video.as_ref().and_then(|v| v.buffers.get(slot.0)?.as_ref()).is_some_and(|(wl, _)| wl == b); + if current { + s.inputs.push_back(Input::VideoReleased(slot.0)); + } else { + b.destroy(); + } + } + } +} + impl Dispatch for State { fn event(s: &mut State, _: &wl_output::WlOutput, e: wl_output::Event, name: &u32, _: &Connection, _: &QueueHandle) { let Some(o) = s.outputs.iter_mut().find(|o| o.name == *name) else { return }; @@ -621,7 +829,11 @@ impl Dispatch for State { } impl Dispatch for State { - fn event(s: &mut State, _: &wl_surface::WlSurface, e: wl_surface::Event, _: &(), _: &Connection, _: &QueueHandle) { + fn event(s: &mut State, surface: &wl_surface::WlSurface, e: wl_surface::Event, _: &(), _: &Connection, _: &QueueHandle) { + // The window's own surface speaks for the window; the video's follows it. + if s.surface.as_ref() != Some(surface) { + return; + } match e { wl_surface::Event::PreferredBufferScale { factor } if s.viewport.is_none() => { s.scale_known = true; @@ -674,10 +886,12 @@ impl Dispatch for State { impl Dispatch for State { fn event(s: &mut State, _: &xdg_toplevel::XdgToplevel, e: xdg_toplevel::Event, _: &(), _: &Connection, _: &QueueHandle) { match e { - xdg_toplevel::Event::Configure { width, height, .. } => { + xdg_toplevel::Event::Configure { width, height, states } => { if width > 0 && height > 0 { s.pending_size = Some((width, height)); } + let fullscreen = xdg_toplevel::State::Fullscreen as u32; + s.pending_fullscreen = states.as_chunks::<4>().0.iter().any(|c| u32::from_ne_bytes(*c) == fullscreen); } xdg_toplevel::Event::Close => s.inputs.push_back(Input::Close), _ => {} From 013717ad59a13b842be69dc7dd3c66ce11ff0df1 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:16:56 -0700 Subject: [PATCH 02/10] alias-playback: follow #3 to 6afd318 (#2's warm start, Intel and review fixes) --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 48bb754..f994443 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -62,7 +62,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "alias-playback" version = "0.1.0" -source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#fd8ddc3d9bcf552af15047f37e5e46114e934f74" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#6afd318e86af0b294dce49af3c34b2430cab32c6" dependencies = [ "libc", "rustix", From 9ee794a21ff2feac6b70aa02c50c81fb2f18b431 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:27:55 -0700 Subject: [PATCH 03/10] Review fixes: buffers the helper sends, frames on resize, failures, FIFOs, full screen - A buffer the helper sends is checked before it reaches the compositor: its format and modifier must be one the compositor listed (dmabuf feedback's table, or v3's events) and its planes must fit in the dmabuf. A bad one was a protocol error that closed the window; now the file can't play and says why. - A buffer replaced while on screen is destroyed with the video layer if it's never let go. - A buffer the compositor lets go while still on screen goes back to the helper once the next frame replaces it; before, the slot was lost, and after three the video froze. - The frame on screen moves to the middle of the window when it changes size, even with no new frame coming (paused, ended, a song's cover). - A helper that dies mid-play takes its last frame with it, so the reason shows. - Session::failure ends the helper before waiting for it: the socket can fail with the helper still running, and the wait froze the window. - A path that isn't a regular file (a FIFO) is refused before it's opened, which waited for a writer. - Full screen carries from one video to the next, and ends for a song or a picture. - Left and Right change file when the file can't play, as for pictures. --- src/app.rs | 16 ++++++--- src/player/gpu.rs | 20 +++++++++++ src/player/mod.rs | 57 ++++++++++++++++++++++++++++--- src/wl.rs | 87 +++++++++++++++++++++++++++++++++++++++++------ 4 files changed, 162 insertions(+), 18 deletions(-) diff --git a/src/app.rs b/src/app.rs index a785b92..65ffb39 100644 --- a/src/app.rs +++ b/src/app.rs @@ -233,6 +233,10 @@ impl App { Some((path, _)) if self.media.as_ref().is_some_and(|m| m.path == path) => {} Some((path, kind)) => { self.close_media(wl); + // Full screen carries from one video to the next; a song has no full screen. + if kind != player::Kind::Video && wl.state.fullscreen { + wl.set_fullscreen(false); + } let b = self.media_box(kind); let size = (b.w.max(1) as u32, b.h.max(1) as u32); self.media = Some(if wl.can_show_video() { @@ -246,6 +250,9 @@ impl App { None => { if self.media.is_some() { self.close_media(wl); + if wl.state.fullscreen { + wl.set_fullscreen(false); + } self.all(); self.a11y_dirty = true; } @@ -254,6 +261,9 @@ impl App { let Some(kind) = self.media.as_ref().map(|m| m.kind) else { return }; let b = self.media_box(kind); let scale = self.scale; + if let Some(m) = &mut self.media { + m.replace(wl, b, scale); + } if let Some(m) = &mut self.media && m.pump(wl, b, scale) { @@ -270,9 +280,6 @@ impl App { } drop(old); wl.video_end(); - if wl.state.fullscreen { - wl.set_fullscreen(false); - } } } @@ -734,7 +741,8 @@ impl App { } // In a video or song, Left and Right seek; n, p, Page Up and Page Down still // change file (Mike, 2026-12-02). - k::KEY_Left | k::KEY_KP_Left | k::KEY_Right | k::KEY_KP_Right => { + // Seeking needs a file that's playing; otherwise they change file, as for pictures. + k::KEY_Left | k::KEY_KP_Left | k::KEY_Right | k::KEY_KP_Right if m.heard && m.error.is_none() => { let step = crate::tokens::motion::SEEK_STEP.as_secs_f64(); m.send(player::gpu::Command::SeekBy(if matches!(sym, k::KEY_Left | k::KEY_KP_Left) { -step } else { step })); return; diff --git a/src/player/gpu.rs b/src/player/gpu.rs index 2df9353..dd7b98a 100644 --- a/src/player/gpu.rs +++ b/src/player/gpu.rs @@ -75,6 +75,10 @@ impl Session { /// Starts a helper for `path` on the card at `node`, drawing into a box of `size` /// physical pixels. `Err` says why, in words for the screen. pub fn start(path: &Path, node: OwnedFd, size: (u32, u32)) -> Result { + // Only a regular file: opening a FIFO would wait for a writer, with the window stuck. + if std::fs::metadata(path).is_ok_and(|m| !m.is_file()) { + return Err("it isn't a regular file".into()); + } let file = File::open(path).map_err(|e| match e.kind() { std::io::ErrorKind::NotFound => "it isn't there any more".to_string(), std::io::ErrorKind::PermissionDenied => "you don't have permission to read it".to_string(), @@ -130,6 +134,10 @@ impl Session { /// After `gone`: why, if it wasn't a clean exit. Waits for the helper, which has /// closed its socket and so is ending. pub fn failure(&mut self) -> Option { + // Its socket can also fail with the helper still running: ended first, so this never + // waits on it. On one that has already exited, the kill does nothing and its own + // exit code is read. + let _ = self.child.kill(); let status = self.child.wait().ok()?; match status.code() { Some(0) => None, @@ -185,6 +193,18 @@ pub fn helper_main(args: &[String]) -> ! { mod tests { use super::*; + #[test] + fn a_fifo_is_refused_without_waiting_for_a_writer() { + let dir = std::env::temp_dir().join(format!("alias-view-fifo-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let fifo = dir.join("x.mp4"); + rustix::fs::mknodat(rustix::fs::CWD, &fifo, rustix::fs::FileType::Fifo, rustix::fs::Mode::from_raw_mode(0o600), 0).unwrap(); + let node = OwnedFd::from(File::open("/dev/null").unwrap()); + let started = Session::start(&fifo, node, (64, 64)); + assert_eq!(started.err().as_deref(), Some("it isn't a regular file")); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn commands_are_the_lines_the_helper_reads() { assert_eq!(Command::SeekBy(-5.0).line(), "seek -5.000"); diff --git a/src/player/mod.rs b/src/player/mod.rs index 3261085..6d96c30 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -81,6 +81,10 @@ pub struct Media { pub error: Option, /// The size asked of the helper, so it's only told of changes. asked: (u32, u32), + /// Released by the compositor while still on screen: given back once replaced. + released_early: [bool; VIDEO_SLOTS], + /// The box the frame on screen was placed in. + placed: Option, } impl Media { @@ -99,6 +103,8 @@ impl Media { meta: Meta::default(), error: None, asked: size, + released_early: [false; VIDEO_SLOTS], + placed: None, }; match node.and_then(|node| Session::start(&m.path, node, size)) { Ok(s) => { @@ -166,11 +172,27 @@ impl Media { /// The compositor let a buffer go. pub fn released(&mut self, slot: usize) { - if self.shown != Some(slot) { + if self.shown == Some(slot) { + // Some compositors let go of a buffer they've copied while it's still attached: + // it goes back once the next frame replaces it, or the slot would be lost. + self.released_early[slot] = true; + } else if slot < VIDEO_SLOTS { self.send(Command::Release(slot)); } } + /// The window or the frame's box changed: the frame on screen moves to the middle of + /// the new box, even with no new frame coming (paused, ended, a song's cover). + pub fn replace(&mut self, wl: &mut Wl, frame_box: Rect, scale: f64) { + if self.placed == Some(frame_box) { + return; + } + if let Some(b) = self.shown.and_then(|s| self.buffers[s]) { + wl.video_place(centre(b.width, b.height, frame_box, scale)); + self.placed = Some(frame_box); + } + } + /// Reads the helper's messages and acts on them: buffers become `wl_buffer`s, frames /// are shown centred in `frame_box` (physical px; `scale` turns them logical). Returns /// true if what's drawn or said about it changed. @@ -186,8 +208,13 @@ impl Media { let Some(fd) = fds.pop().filter(|_| fds.is_empty()) else { continue }; let b = VideoBuffer { width, height, fourcc, modifier, stride, offset }; wl.video_begin(); - wl.video_buffer(slot, fd, b); + if let Err(why) = wl.video_buffer(slot, fd, b) { + self.error = Some(why); + changed = true; + continue; + } self.buffers[slot] = Some(b); + self.released_early[slot] = false; if self.shown == Some(slot) { self.shown = None; } @@ -198,9 +225,15 @@ impl Media { continue; }; let place = centre(b.width, b.height, frame_box, scale); - // The one shown until now is given back when the compositor releases it. + // The one shown until now is given back when the compositor releases it, + // or now if it already has. if wl.video_frame(slot, place) { - self.shown = Some(slot); + if let Some(old) = self.shown.replace(slot).filter(|o| *o != slot) + && std::mem::take(&mut self.released_early[old]) + { + self.send(Command::Release(old)); + } + self.placed = Some(frame_box); if self.has_picture != Some(true) { self.has_picture = Some(true); changed = true; @@ -247,6 +280,12 @@ impl Media { self.session = None; changed = true; } + // A file that can't play shows its reason, not a frozen frame over it. + if self.error.is_some() && self.shown.is_some() { + self.shown = None; + self.placed = None; + wl.video_end(); + } changed } @@ -304,6 +343,16 @@ mod tests { assert_eq!(clock(-4.0), "0:00"); } + #[test] + fn a_buffer_let_go_while_on_screen_is_kept_until_replaced() { + let mut m = Media::failed("/m/clip.mp4".into(), Kind::Video, "x".into()); + m.shown = Some(1); + m.released(1); + assert!(m.released_early[1], "remembered, to give back once the next frame is up"); + m.released(2); + assert!(!m.released_early[2], "one not on screen goes straight back"); + } + #[test] fn a_frame_sits_in_the_middle_of_its_box() { assert_eq!(centre(1920, 800, Rect::new(0, 0, 1920, 1080), 1.0), (0, 140, 1920, 800)); diff --git a/src/wl.rs b/src/wl.rs index 01321bb..18f2c1b 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -111,6 +111,8 @@ struct VideoLayer { /// Where it sits, in logical px, and the buffer on it. place: Option<(i32, i32, i32, i32)>, shown: Option, + /// Buffers replaced while on screen, destroyed when let go, or with the layer. + retired: Vec, } /// A video buffer's slot, as its `wl_buffer`'s data. @@ -182,6 +184,9 @@ pub struct State { dmabuf: Option, /// The compositor's main graphics device (`dev_t`), from dmabuf feedback. main_device: Option, + /// The dmabuf formats and modifiers the compositor takes, so a buffer it would refuse + /// (a protocol error that would close the window) is refused here first. + dmabuf_formats: std::collections::HashSet<(u32, u64)>, video: Option, /// In full screen, as the compositor last said. pub fullscreen: bool, @@ -269,6 +274,7 @@ impl Wl { subcompositor: None, dmabuf: None, main_device: None, + dmabuf_formats: Default::default(), video: None, fullscreen: false, pending_fullscreen: false, @@ -416,14 +422,26 @@ impl Wl { surface.set_input_region(Some(&empty)); empty.destroy(); let viewport = s.viewporter.as_ref().map(|v| v.get_viewport(&surface, &self.qh, ())); - s.video = Some(VideoLayer { surface, sub, viewport, buffers: Default::default(), place: None, shown: None }); + s.video = Some(VideoLayer { surface, sub, viewport, buffers: Default::default(), place: None, shown: None, retired: Vec::new() }); } /// The helper described a buffer and sent its dmabuf: makes the `wl_buffer` for it. - pub fn video_buffer(&mut self, slot: usize, fd: OwnedFd, b: VideoBuffer) { - let (Some(d), Some(v)) = (&self.state.dmabuf, &mut self.state.video) else { return }; + /// `Err` says why it can't be shown. The helper isn't trusted, and a buffer the + /// compositor refuses would be a protocol error, closing the window: the format must be + /// one the compositor listed, and the planes must fit in the dmabuf. + pub fn video_buffer(&mut self, slot: usize, fd: OwnedFd, b: VideoBuffer) -> Result<(), String> { + let formats = &self.state.dmabuf_formats; + let (Some(d), Some(v)) = (&self.state.dmabuf, &mut self.state.video) else { return Err("there's no video surface".into()) }; if slot >= VIDEO_SLOTS { - return; + return Err("the player sent a buffer it shouldn't have".into()); + } + if !formats.is_empty() && !formats.contains(&(b.fourcc, b.modifier)) { + return Err("the desktop can't show frames in the form the player made them".into()); + } + let len = rustix::fs::seek(&fd, rustix::fs::SeekFrom::End(0)).unwrap_or(0); + let needs = u64::from(b.offset) + u64::from(b.stride) * u64::from(b.height); + if needs > len { + return Err("the player sent a frame smaller than it said".into()); } let params = d.create_params(&self.qh, ()); params.add(fd.as_fd(), 0, b.offset, b.stride, (b.modifier >> 32) as u32, b.modifier as u32); @@ -431,13 +449,33 @@ impl Wl { params.destroy(); if let Some((old, _)) = v.buffers[slot].replace((wl, b)) { // Still on screen: destroyed when the compositor lets it go (see the release). - if v.shown != Some(slot) { + if v.shown == Some(slot) { + v.retired.push(old); + } else { old.destroy(); } } if v.shown == Some(slot) { v.shown = None; } + Ok(()) + } + + /// Moves the frame on screen to `place`, as when the window changes size while paused. + pub fn video_place(&mut self, place: (i32, i32, i32, i32)) { + let Some(v) = &mut self.state.video else { return }; + if v.shown.is_none() || v.place == Some(place) { + return; + } + v.sub.set_position(place.0, place.1); + if let Some(vp) = &v.viewport { + vp.set_destination(place.2.max(1), place.3.max(1)); + } + v.place = Some(place); + v.surface.commit(); + if let Some(p) = &self.state.surface { + p.commit(); + } } /// Shows the frame in `slot` at `place`: x, y, width and height in logical px. Returns @@ -470,6 +508,9 @@ impl Wl { for (wl, _) in v.buffers.into_iter().flatten() { wl.destroy(); } + for wl in v.retired { + wl.destroy(); + } if let Some(vp) = v.viewport { vp.destroy(); } @@ -772,18 +813,41 @@ ignore_events!( wl_subcompositor::WlSubcompositor, wl_subsurface::WlSubsurface, wl_region::WlRegion, - dmabuf::ZwpLinuxDmabufV1, dmabuf_params::ZwpLinuxBufferParamsV1, ); +impl Dispatch for State { + fn event(s: &mut State, _: &dmabuf::ZwpLinuxDmabufV1, e: dmabuf::Event, _: &(), _: &Connection, _: &QueueHandle) { + // Version 3 lists formats as events; version 4 sends the table instead. + if let dmabuf::Event::Modifier { format, modifier_hi, modifier_lo } = e { + s.dmabuf_formats.insert((format, (u64::from(modifier_hi) << 32) | u64::from(modifier_lo))); + } + } +} + impl Dispatch for State { fn event(s: &mut State, _: &dmabuf_feedback::ZwpLinuxDmabufFeedbackV1, e: dmabuf_feedback::Event, _: &(), _: &Connection, _: &QueueHandle) { // The format table's descriptor is dropped with the event: formats are the // helper's choice, and every compositor takes XRGB8888. - if let dmabuf_feedback::Event::MainDevice { device } = e - && let Ok(bytes) = <[u8; 8]>::try_from(device.as_slice()) - { - s.main_device = Some(u64::from_ne_bytes(bytes)); + match e { + dmabuf_feedback::Event::MainDevice { device } => { + if let Ok(bytes) = <[u8; 8]>::try_from(device.as_slice()) { + s.main_device = Some(u64::from_ne_bytes(bytes)); + } + } + // Read rather than mapped, as this file has no unsafe code: 16 bytes an entry, + // the format (u32), padding, then the modifier (u64). + dmabuf_feedback::Event::FormatTable { fd, size } => { + let mut table = vec![0u8; (size as usize).min(1 << 20)]; + if File::from(fd).read_exact_at(&mut table, 0).is_ok() { + for e in table.as_chunks::<16>().0 { + let format = u32::from_ne_bytes([e[0], e[1], e[2], e[3]]); + let modifier = u64::from_ne_bytes([e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15]]); + s.dmabuf_formats.insert((format, modifier)); + } + } + } + _ => {} } } } @@ -797,6 +861,9 @@ impl Dispatch for State { if current { s.inputs.push_back(Input::VideoReleased(slot.0)); } else { + if let Some(v) = &mut s.video { + v.retired.retain(|r| r != b); + } b.destroy(); } } From 9fbe25a63c0dfde1cd760587c890c9e78e75f894 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:32:28 -0700 Subject: [PATCH 04/10] alias-playback: follow #3 to 74c8c87 (cover art always drawn, warm-load fixes) --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index f994443..430fb97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -62,7 +62,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "alias-playback" version = "0.1.0" -source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#6afd318e86af0b294dce49af3c34b2430cab32c6" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#74c8c8715ed6a1ced9d691db3caf3cf86ec7ea26" dependencies = [ "libc", "rustix", From ae63d6b37fccf17289429d3a5b2bf44703532e3c Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:40:38 -0700 Subject: [PATCH 05/10] Review round 2: a failed file's helper ends; a helper's exit code is kept - A file that can't play (a refused buffer, or the helper saying it can't) ends its helper, so no sound plays on under the reason, and frames that still arrive are given back, not shown. - A helper that closed its socket cleanly is waited for, not killed, so its exit code says why (libmpv missing, the sandbox not set up). Only after a read error is it ended first. - The format table comment says what the table is now used for. --- src/player/gpu.rs | 16 +++++++++++----- src/player/mod.rs | 7 +++++++ src/wl.rs | 4 ++-- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/player/gpu.rs b/src/player/gpu.rs index dd7b98a..3156264 100644 --- a/src/player/gpu.rs +++ b/src/player/gpu.rs @@ -69,6 +69,9 @@ pub struct Session { socket: OwnedFd, /// The socket has closed: the helper is gone. pub gone: bool, + /// It closed cleanly (end of stream), as a helper exiting does; not a read error with + /// the helper perhaps still running. + closed_cleanly: bool, } impl Session { @@ -93,7 +96,7 @@ impl Session { if e.kind() == std::io::ErrorKind::NotFound { "bubblewrap (bwrap), which keeps video in a sandbox, isn't installed".to_string() } else { format!("the player didn't start ({e})") } })?; rustix::io::ioctl_fionbio(&socket, true).map_err(|_| "the player didn't start".to_string())?; - Ok(Session { child, socket, gone: false }) + Ok(Session { child, socket, gone: false, closed_cleanly: false }) } /// For the loop's poll. @@ -114,6 +117,7 @@ impl Session { } Ok(None) => { self.gone = true; + self.closed_cleanly = true; break; } Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, @@ -134,10 +138,12 @@ impl Session { /// After `gone`: why, if it wasn't a clean exit. Waits for the helper, which has /// closed its socket and so is ending. pub fn failure(&mut self) -> Option { - // Its socket can also fail with the helper still running: ended first, so this never - // waits on it. On one that has already exited, the kill does nothing and its own - // exit code is read. - let _ = self.child.kill(); + // A clean end of the socket is the helper exiting: bubblewrap follows once it has + // reaped it, with its exit code, which says why. After a read error the helper may + // still be running, so it's ended first and never waited on. + if !self.closed_cleanly { + let _ = self.child.kill(); + } let status = self.child.wait().ok()?; match status.code() { Some(0) => None, diff --git a/src/player/mod.rs b/src/player/mod.rs index 6d96c30..1f5cb54 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -219,6 +219,8 @@ impl Media { self.shown = None; } } + // A file that can't play shows its reason; no more frames go up. + Said::Frame { slot } if self.error.is_some() => self.send(Command::Release(slot)), Said::Frame { slot } => { let Some(b) = self.buffers[slot] else { self.send(Command::Release(slot)); @@ -280,6 +282,11 @@ impl Media { self.session = None; changed = true; } + // A file that can't play stops: its helper ends (with the session), so no sound + // plays on under the reason. + if self.error.is_some() && self.session.is_some() { + self.session = None; + } // A file that can't play shows its reason, not a frozen frame over it. if self.error.is_some() && self.shown.is_some() { self.shown = None; diff --git a/src/wl.rs b/src/wl.rs index 18f2c1b..f17ead4 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -827,8 +827,8 @@ impl Dispatch for State { impl Dispatch for State { fn event(s: &mut State, _: &dmabuf_feedback::ZwpLinuxDmabufFeedbackV1, e: dmabuf_feedback::Event, _: &(), _: &Connection, _: &QueueHandle) { - // The format table's descriptor is dropped with the event: formats are the - // helper's choice, and every compositor takes XRGB8888. + // The main device says which card to draw on; the format table which buffers the + // compositor takes, so a bad one from the helper is refused before it's sent. match e { dmabuf_feedback::Event::MainDevice { device } => { if let Ok(bytes) = <[u8; 8]>::try_from(device.as_slice()) { From cdec0adb02bf09814de2e4d9a5684f1d3843cc60 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:44:11 -0700 Subject: [PATCH 06/10] Commands to the helper wait out a full socket; video needs viewporter - Session::send waited for nothing: the socket is non-blocking (for reading), so a full one dropped the command, and a lost release left the helper a buffer short for good. A full socket is now waited on briefly. - Video is shown only where the compositor has viewporter, which places a frame at any window scale; without it the frame would be drawn at the wrong size. --- src/app.rs | 2 +- src/player/gpu.rs | 15 ++++++++++++++- src/wl.rs | 5 +++-- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/app.rs b/src/app.rs index 65ffb39..2d58339 100644 --- a/src/app.rs +++ b/src/app.rs @@ -242,7 +242,7 @@ impl App { self.media = Some(if wl.can_show_video() { Media::open(path, kind, player::gpu::open_node(wl.render_node_path().as_deref()), size, self.volume, self.muted) } else { - Media::failed(path, kind, "this desktop can't show video from another process (it lacks linux-dmabuf)".into()) + Media::failed(path, kind, "this desktop can't show video from another process (it lacks linux-dmabuf or viewporter)".into()) }); self.all(); self.a11y_dirty = true; diff --git a/src/player/gpu.rs b/src/player/gpu.rs index 3156264..37017fb 100644 --- a/src/player/gpu.rs +++ b/src/player/gpu.rs @@ -131,8 +131,21 @@ impl Session { out } + /// Sends a command. The socket doesn't block (for reading), so a full one is waited on + /// briefly rather than the command dropped: a lost `release` would leave the helper a + /// buffer short for good. pub fn send(&self, c: Command) { - let _ = gpu_helper::send(&self.socket, &c.line(), &[]); + let line = c.line(); + for _ in 0..10 { + match gpu_helper::send(&self.socket, &line, &[]) { + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + let mut fds = [rustix::event::PollFd::new(&self.socket, rustix::event::PollFlags::OUT)]; + let wait = rustix::time::Timespec { tv_sec: 0, tv_nsec: 20_000_000 }; + let _ = rustix::event::poll(&mut fds, Some(&wait)); + } + _ => return, + } + } } /// After `gone`: why, if it wasn't a clean exit. Waits for the helper, which has diff --git a/src/wl.rs b/src/wl.rs index f17ead4..a9c9d2a 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -394,9 +394,10 @@ impl Wl { } } - /// Whether video can be shown: the compositor takes dmabufs and subsurfaces. + /// Whether video can be shown: the compositor takes dmabufs and subsurfaces, and can + /// scale a surface (viewporter), which places a frame at any window scale. pub fn can_show_video(&self) -> bool { - self.state.dmabuf.is_some() && self.state.subcompositor.is_some() + self.state.dmabuf.is_some() && self.state.subcompositor.is_some() && self.state.viewporter.is_some() } /// The render node of the card the compositor draws with, when it said which. The From 59235113d43cff2886dcc6d58f56904f6622cafd Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 11:55:51 -0700 Subject: [PATCH 07/10] Follow alias-playback #3 to e11d5f4; a helper's exit code survives a reset - alias-playback e11d5f4: #2's requests and reads that never wait, and #3's tags read with them (a song's cover played 12 of 12 times in the private weston, tags each time). - A helper whose socket ends in a reset rather than a clean close (it exited with commands unread) gets 100 ms to finish before it's ended, so its exit code still says why it stopped. --- Cargo.lock | 2 +- src/player/gpu.rs | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 430fb97..df9cc95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -62,7 +62,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "alias-playback" version = "0.1.0" -source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#74c8c8715ed6a1ced9d691db3caf3cf86ec7ea26" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#e11d5f479b3bd01258f356909d4d3a88e513d5e3" dependencies = [ "libc", "rustix", diff --git a/src/player/gpu.rs b/src/player/gpu.rs index 37017fb..822710a 100644 --- a/src/player/gpu.rs +++ b/src/player/gpu.rs @@ -154,7 +154,15 @@ impl Session { // A clean end of the socket is the helper exiting: bubblewrap follows once it has // reaped it, with its exit code, which says why. After a read error the helper may // still be running, so it's ended first and never waited on. + // A close can also show up as a reset (the helper left with commands unread): a + // moment's grace lets a helper that's exiting anyway finish, with its code. if !self.closed_cleanly { + for _ in 0..10 { + if matches!(self.child.try_wait(), Ok(Some(_))) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } let _ = self.child.kill(); } let status = self.child.wait().ok()?; From 56371ba854ea090f62f885499d151f135f25be2d Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 12:04:34 -0700 Subject: [PATCH 08/10] Follow alias-playback #3 to a314208 (#2's late-Loaded fixes; no picture confirmed by the loading file) --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index df9cc95..594e772 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -62,7 +62,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "alias-playback" version = "0.1.0" -source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#e11d5f479b3bd01258f356909d4d3a88e513d5e3" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#a3142084e4c63be43f140c0f32a9d4294faf43c2" dependencies = [ "libc", "rustix", From f271e0a3bd782a60529a26a80b71a3bb3fc1ed2c Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 12:08:35 -0700 Subject: [PATCH 09/10] A buffer's modifier must be one the compositor listed for its format With no list (the table couldn't be read), any modifier was taken; now nothing is, so a buffer from the helper is never one the compositor hasn't said it takes. --- src/wl.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/wl.rs b/src/wl.rs index a9c9d2a..a0eac1b 100644 --- a/src/wl.rs +++ b/src/wl.rs @@ -436,7 +436,9 @@ impl Wl { if slot >= VIDEO_SLOTS { return Err("the player sent a buffer it shouldn't have".into()); } - if !formats.is_empty() && !formats.contains(&(b.fourcc, b.modifier)) { + // Only a format and modifier the compositor listed for each other; with no list + // (it couldn't be read), nothing is taken on trust. + if !formats.contains(&(b.fourcc, b.modifier)) { return Err("the desktop can't show frames in the form the player made them".into()); } let len = rustix::fs::seek(&fd, rustix::fs::SeekFrom::End(0)).unwrap_or(0); From 2c03d01ddd0f3a91a5c84f3dfbcc19ecca2f05eb Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Wed, 2 Dec 2026 12:13:05 -0700 Subject: [PATCH 10/10] Follow alias-playback #3 to its merge of 6c0187c (GPU setup freed on failure) --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 594e772..2f25624 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -62,7 +62,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "alias-playback" version = "0.1.0" -source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#a3142084e4c63be43f140c0f32a9d4294faf43c2" +source = "git+https://github.com/aliasproject/alias-playback?branch=ali-2358-gpu-media#4a05f2ce2e59e38f901f7fdcb198557f3b48f16b" dependencies = [ "libc", "rustix",