diff --git a/Cargo.lock b/Cargo.lock index e7f52ad..2f25624 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#4a05f2ce2e59e38f901f7fdcb198557f3b48f16b" +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..2d58339 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,101 @@ 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); + // 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() { + 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 or viewporter)".into()) + }); + self.all(); + self.a11y_dirty = true; + } + None => { + if self.media.is_some() { + self.close_media(wl); + if wl.state.fullscreen { + wl.set_fullscreen(false); + } + 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.replace(wl, b, 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(); + } + } + + /// 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 +340,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 +674,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 +731,33 @@ 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). + // 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; + } + 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 +953,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 +1088,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 +1172,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 +1261,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..822710a --- /dev/null +++ b/src/player/gpu.rs @@ -0,0 +1,244 @@ +//! 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, + /// 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 { + /// 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(), + _ => 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, closed_cleanly: 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; + self.closed_cleanly = 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 + } + + /// 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 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 + /// closed its socket and so is ending. + pub fn failure(&mut self) -> Option { + // 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()?; + 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 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"); + 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..1f5cb54 --- /dev/null +++ b/src/player/mod.rs @@ -0,0 +1,368 @@ +//! 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), + /// 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 { + /// 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, + released_early: [false; VIDEO_SLOTS], + placed: None, + }; + 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) { + // 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. + 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(); + 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; + } + } + // 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)); + continue; + }; + let place = centre(b.width, b.height, frame_box, scale); + // 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) { + 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; + } + } 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; + } + // 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; + self.placed = None; + wl.video_end(); + } + 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_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)); + 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..a0eac1b 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,40 @@ 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, + /// 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. +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 +180,17 @@ 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, + /// 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, + pending_fullscreen: bool, pub outputs: Vec, /// The output the window is on, once the compositor says. pub entered: Option, @@ -222,6 +271,13 @@ impl Wl { deco_manager: None, xout_manager: None, gestures: None, + subcompositor: None, + dmabuf: None, + main_device: None, + dmabuf_formats: Default::default(), + video: None, + fullscreen: false, + pending_fullscreen: false, outputs: Vec::new(), entered: None, surface: None, @@ -327,6 +383,147 @@ 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, 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.viewporter.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, retired: Vec::new() }); + } + + /// The helper described a buffer and sent its dmabuf: makes the `wl_buffer` for it. + /// `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 Err("the player sent a buffer it shouldn't have".into()); + } + // 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); + 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); + 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) { + 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 + /// 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(); + } + for wl in v.retired { + 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 +652,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 +733,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 +765,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 +813,66 @@ ignore_events!( wl_data_device_manager::WlDataDeviceManager, xout_mgr::ZxdgOutputManagerV1, gestures::ZwpPointerGesturesV1, + wl_subcompositor::WlSubcompositor, + wl_subsurface::WlSubsurface, + wl_region::WlRegion, + 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 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()) { + 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)); + } + } + } + _ => {} + } + } +} + +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 { + if let Some(v) = &mut s.video { + v.retired.retain(|r| r != b); + } + 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 +899,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 +956,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), _ => {}