diff --git a/crates/sidestep-engine/Cargo.toml b/crates/sidestep-engine/Cargo.toml index f29af36..f4a2e56 100644 --- a/crates/sidestep-engine/Cargo.toml +++ b/crates/sidestep-engine/Cargo.toml @@ -24,7 +24,7 @@ kbvm = { version = "0.2", default-features = false, features = ["compose"] } wayland-cursor = "0.31" # Non-blocking clipboard pipes, and faulting in window memory ahead # (madvise); already built for the Wayland crates. -rustix = { version = "1", default-features = false, features = ["std", "mm", "param"] } +rustix = { version = "1", default-features = false, features = ["std", "mm", "param", "time"] } # Loads fontconfig from where it's found when the dynamic linker can't # find it by name (NixOS; see src/system.rs). fontique's loader uses it. libloading = "0.8" diff --git a/crates/sidestep-engine/src/backend/mod.rs b/crates/sidestep-engine/src/backend/mod.rs index 1bba076..5edf2ec 100644 --- a/crates/sidestep-engine/src/backend/mod.rs +++ b/crates/sidestep-engine/src/backend/mod.rs @@ -48,6 +48,7 @@ mod selection; mod sheet; mod textinput; mod tiles; +mod video; pub use decor::{HEADER, TITLE_SIZE, explicit_theme}; @@ -167,6 +168,7 @@ impl Drop for MainSender { /// it drops the `Backend` the render thread ends (its channel closes), so /// another may start after it. pub fn start(wake: Waker) -> Backend { + crate::video::render_started(); let backend = if null::chosen() { null::start(wake) } else { @@ -271,6 +273,7 @@ fn run(channel: Channel, to_main: MainSender) { } else { globals.bind::(&qh, 1..=1, ()).ok() }; + let videos = video::Videos::new(&globals, &qh); let mut state = State { registry: RegistryState::new(&globals), outputs: OutputState::new(&globals, &qh), @@ -300,10 +303,12 @@ fn run(channel: Channel, to_main: MainSender) { // The environment isn't changed: other threads may be reading it. startup_token: std::env::var("XDG_ACTIVATION_TOKEN").ok().filter(|t| !t.is_empty()), empty_region: None, + videos, ca: crate::ca::tree::Compositor::default(), exit: false, }; seat::bind_existing(&mut state, &globals); + state.videos.ask_caps(&state.conn, &state.qh); outputs::started(&state, &globals); while !state.exit { // While tiles have paints to rasterize, look for events without @@ -372,6 +377,8 @@ pub struct State { /// An input region with nothing in it, made the first time a window /// lets pointer input through. empty_region: Option, + /// Video subsurfaces and the buffers their frames show (see `video`). + videos: video::Videos, /// Core Animation's layer trees, animated here (see `ca::tree`). ca: crate::ca::tree::Compositor, exit: bool, @@ -1110,6 +1117,9 @@ impl State { // Pixel capture is a null-backend diagnostic only. let _ = reply.send(None); } + ToRender::PlaceVideo { window, video, place } => video::place(self, window, video, place), + ToRender::ShowVideo { window, video, frame } => video::show(self, window, video, *frame), + ToRender::ClearVideo { window, video } => video::clear(self, window, video), ToRender::SetSelection { contents } => selection::set(self, contents), ToRender::ReadSelection { mime, token, source, drag } => selection::read(self, mime, token, source, drag), ToRender::SelectionData { token, data } => selection::provided(self, token, data), @@ -1400,7 +1410,9 @@ impl State { if let Some(i) = &win.foreign_parent { i.destroy(); } - // Tiles and decorations go first: they're subsurfaces of the root. + // Tiles, videos and decorations go first: they're subsurfaces of + // the root. + self.videos.window_closed(window); drop(win.layers); drop(win.decor); drop(win.menubar); @@ -1824,9 +1836,11 @@ impl State { self.draw_frame(window, rgba); } self.place_decorations(window); + let placed = video::before_commit(self, window); let Some(win) = self.windows.get(&window) else { return }; win.surface().frame(&self.qh, FrameTag { window, seq }); win.commit(); + video::after_commit(self, placed); } /// Draw the paints since the last present straight into a buffer, and diff --git a/crates/sidestep-engine/src/backend/null.rs b/crates/sidestep-engine/src/backend/null.rs index fc5b8f7..b504e0c 100644 --- a/crates/sidestep-engine/src/backend/null.rs +++ b/crates/sidestep-engine/src/backend/null.rs @@ -111,6 +111,19 @@ pub enum Seen { window: u32, rects: Option>, }, + /// A video of the window was placed there, or taken away. + VideoPlaced { + window: u32, + video: u32, + place: Option, + }, + /// A frame of a video showed (at once, as presented), so big in + /// pixels; or the video was cleared (none). + VideoShown { + window: u32, + video: u32, + size: Option<(u32, u32)>, + }, } /// A run of text the main thread asked the null render thread to paint. @@ -242,6 +255,17 @@ pub fn chosen() -> bool { pub fn start(wake: Waker) -> Backend { RUNNING.store(true, Ordering::Relaxed); + // A compositor that takes shared memory and dmabufs of nothing, and + // shows frames at the times they ask for. + crate::video::publish_caps(crate::video::VideoCaps { + known: true, + dmabuf: Vec::new(), + shm: vec![0, 1], + commit_timing: true, + presentation: true, + monotonic: true, + main_device: 0, + }); let (tx, channel) = channel::channel(); let (to_main, rx) = mpsc::channel(); let to_main = MainSender::new(to_main, wake); @@ -482,6 +506,17 @@ fn run(channel: Channel, to_main: MainSender) { }), ToRender::SelectionData { token, data } => note(Seen::Provided { token, data: data.map(|d| d.to_vec()) }), ToRender::SetOpaqueRegion { window, rects } => note(Seen::OpaqueRegion { window, rects }), + ToRender::PlaceVideo { window, video, place } => note(Seen::VideoPlaced { window, video, place }), + ToRender::ShowVideo { window, video, mut frame } => { + // Shown at once, as a compositor always ready for a frame + // would, and released at once. + let size = Some(frame.buffer.size()); + let time = crate::video::monotonic_now(); + frame.report(crate::video::Shown::Presented { time, refresh: 16_666_667 }); + drop(frame); + note(Seen::VideoShown { window, video, size }); + } + ToRender::ClearVideo { window, video } => note(Seen::VideoShown { window, video, size: None }), ToRender::Paint { window: _, target: crate::protocol::Target::Content(layer), rects, ops } => { with_ca(|ca| ca.paint_content(layer, &rects, &ops, &mut glyphs)); } diff --git a/crates/sidestep-engine/src/backend/video.rs b/crates/sidestep-engine/src/backend/video.rs new file mode 100644 index 0000000..1afa6cd --- /dev/null +++ b/crates/sidestep-engine/src/backend/video.rs @@ -0,0 +1,639 @@ +//! Video on the render thread (see `crate::video`): each video is a +//! subsurface of its window's main surface, a sibling of the content +//! like the decorations and tiles, cropped and scaled by its viewport. +//! +//! **Frames.** A frame's buffer becomes a compositor buffer the first +//! time it shows (linux-dmabuf `create_immed`, or a wl_shm pool on the +//! producer's memfd) and stays one while the producer keeps the buffer, +//! so a decoder's surfaces, shown in turn, are imported once. A frame is +//! attached, damaged and committed on its own: the subsurface is +//! desynchronized, so frames don't wait for the window. With +//! wp_commit_timing_v1 a frame carries the time it is for; with +//! wp_presentation it hears whether it reached the screen. A frame is +//! kept, holding the decoder's surface, until the compositor releases +//! its buffer. +//! +//! **Placing.** Where the video is, its size and whether it's over or +//! under the content belong to the window's frame (subsurface position +//! and stacking are its parent's state), so a new place is applied at +//! the window's next present, together with the content it goes with: +//! the subsurface is made synchronized, its viewport and regions set and +//! committed, the window committed, and the subsurface desynchronized +//! again. A video takes no pointer input (its input region is empty), so +//! what's over it in the window gets the pointer, and says it's opaque +//! and a video (wp_content_type_v1). + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, Weak}; + +use smithay_client_toolkit::compositor::Region; +use smithay_client_toolkit::dmabuf::{DmabufFeedback, DmabufHandler, DmabufState}; +use smithay_client_toolkit::reexports::client::globals::GlobalList; +use smithay_client_toolkit::reexports::client::protocol::wl_buffer::{self, WlBuffer}; +use smithay_client_toolkit::reexports::client::protocol::wl_callback::{self, WlCallback}; +use smithay_client_toolkit::reexports::client::protocol::wl_shm_pool::{self, WlShmPool}; +use smithay_client_toolkit::reexports::client::protocol::wl_subsurface::WlSubsurface; +use smithay_client_toolkit::reexports::client::protocol::wl_surface::WlSurface; +use smithay_client_toolkit::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, WEnum}; +use smithay_client_toolkit::reexports::protocols::wp::commit_timing::v1::client::{ + wp_commit_timer_v1::{self, WpCommitTimerV1}, + wp_commit_timing_manager_v1::{self, WpCommitTimingManagerV1}, +}; +use smithay_client_toolkit::reexports::protocols::wp::content_type::v1::client::{ + wp_content_type_manager_v1::{self, WpContentTypeManagerV1}, + wp_content_type_v1::{self, WpContentTypeV1}, +}; +use smithay_client_toolkit::reexports::protocols::wp::idle_inhibit::zv1::client::{ + zwp_idle_inhibit_manager_v1::{self, ZwpIdleInhibitManagerV1}, + zwp_idle_inhibitor_v1::{self, ZwpIdleInhibitorV1}, +}; +use smithay_client_toolkit::reexports::protocols::wp::linux_dmabuf::zv1::client::{ + zwp_linux_buffer_params_v1, zwp_linux_dmabuf_feedback_v1, +}; +use smithay_client_toolkit::reexports::protocols::wp::presentation_time::client::{ + wp_presentation::{self, WpPresentation}, + wp_presentation_feedback::{self, WpPresentationFeedback}, +}; +use smithay_client_toolkit::reexports::protocols::wp::viewporter::client::wp_viewport::WpViewport; +use smithay_client_toolkit::shm::Shm; + +use super::{Shell, State}; +use crate::protocol::WindowId; +use crate::video::{Shown, VideoBuffer, VideoCaps, VideoFrame, VideoId, VideoPlace}; + +/// CLOCK_MONOTONIC, as wp_presentation names clocks. +const CLOCK_MONOTONIC: u32 = 1; + +/// The render thread's videos, the compositor buffers made for frames, +/// and the globals they use. +pub struct Videos { + surfaces: HashMap<(WindowId, VideoId), VideoSurface>, + buffers: HashMap, + dmabuf: DmabufState, + presentation: Option, + timing: Option, + content_type: Option, + idle: Option, + caps: VideoCaps, + /// Frames shown since the cache of buffers was last swept. + since_sweep: u32, +} + +/// A compositor buffer made for a frame's buffer, kept while the +/// producer keeps the buffer, and the frames shown with it that the +/// compositor may still be reading. +struct Cached { + buffer: Weak, + wl: WlBuffer, + pool: Option, + in_flight: Vec, +} + +impl Drop for Cached { + fn drop(&mut self) { + self.wl.destroy(); + if let Some(p) = &self.pool { + p.destroy(); + } + } +} + +struct VideoSurface { + surface: WlSurface, + subsurface: WlSubsurface, + viewport: WpViewport, + timer: Option, + content_type: Option, + inhibitor: Option, + /// Where it was asked to be. + place: VideoPlace, + /// Where it is, as last applied: x, y, width and height in the + /// parent's points, and under the content. + applied: Option<(i32, i32, i32, i32, bool)>, + /// The crop last given the viewport. + crop: Option<[f32; 4]>, + /// The subsurface is synchronized (new, or being placed). + synced: bool, +} + +impl Drop for VideoSurface { + fn drop(&mut self) { + if let Some(i) = self.inhibitor.take() { + i.destroy(); + } + if let Some(c) = self.content_type.take() { + c.destroy(); + } + if let Some(t) = self.timer.take() { + t.destroy(); + } + self.viewport.destroy(); + self.subsurface.destroy(); + self.surface.destroy(); + } +} + +/// Where a frame hears whether it reached the screen. +type Report = Box; + +/// What a presentation feedback reports to: the frame's `shown`. +pub struct Feedback(Mutex>); + +impl Feedback { + fn report(&self, shown: Shown) { + if let Some(f) = self.0.lock().unwrap_or_else(|e| e.into_inner()).take() { + f(shown); + } + } +} + +/// A wl_shm pool or buffer made for a frame's buffer. +pub struct ShmTag; + +/// The callback after the globals' first events: what the compositor +/// takes is known then. +pub struct CapsKnown; + +impl Videos { + pub fn new(globals: &GlobalList, qh: &QueueHandle) -> Videos { + let dmabuf = DmabufState::new(globals, qh); + // Version 4 tells formats through feedback, asked for once. + if dmabuf.version().is_some_and(|v| v >= 4) { + let _ = dmabuf.get_default_feedback(qh); + } + let presentation = globals.bind::(qh, 1..=2, ()).ok(); + let timing = globals.bind::(qh, 1..=1, ()).ok(); + let content_type = globals.bind::(qh, 1..=1, ()).ok(); + let idle = globals.bind::(qh, 1..=1, ()).ok(); + let caps = VideoCaps { + known: false, + commit_timing: timing.is_some(), + presentation: presentation.is_some(), + ..VideoCaps::default() + }; + Videos { + surfaces: HashMap::new(), + buffers: HashMap::new(), + dmabuf, + presentation, + timing, + content_type, + idle, + caps, + since_sweep: 0, + } + } + + /// Ask for a callback after the events the globals send at once. + pub fn ask_caps(&self, conn: &Connection, qh: &QueueHandle) { + conn.display().sync(qh, CapsKnown); + } + + /// The videos of a window that goes. + pub fn window_closed(&mut self, window: WindowId) { + self.surfaces.retain(|(w, _), _| *w != window); + } +} + +impl VideoSurface { + /// Where its place puts it. + fn target(&self) -> (i32, i32, i32, i32, bool) { + let r = self.place.rect.round_out(); + (r.x0 as i32, r.y0 as i32, (r.x1 - r.x0).max(1.0) as i32, (r.y1 - r.y0).max(1.0) as i32, self.place.below) + } +} + +/// Show video `video` of `window` at `place`, or take it away. +pub fn place(state: &mut State, window: WindowId, video: VideoId, place: Option) { + let key = (window, video); + let Some(place) = place else { + state.videos.surfaces.remove(&key); + return; + }; + if !state.videos.surfaces.contains_key(&key) { + let Some(win) = state.windows.get(&window) else { return }; + let parent = win.main_surface().clone(); + let (subsurface, surface) = state.subcompositor.create_subsurface(parent, &state.qh); + let viewport = state.viewporter.get().expect("wp_viewporter").get_viewport(&surface, &state.qh, ()); + let empty = state.empty_region(); + surface.set_input_region(Some(&empty)); + let content_type = state.videos.content_type.as_ref().map(|m| { + let c = m.get_surface_content_type(&surface, &state.qh, ()); + c.set_content_type(wp_content_type_v1::Type::Video); + c + }); + let timer = state.videos.timing.as_ref().map(|m| m.get_timer(&surface, &state.qh, ())); + state.videos.surfaces.insert( + key, + VideoSurface { + surface, + subsurface, + viewport, + timer, + content_type, + inhibitor: None, + place, + applied: None, + crop: None, + // New subsurfaces are synchronized. + synced: true, + }, + ); + } + let idle = state.videos.idle.clone(); + let qh = state.qh.clone(); + let Some(v) = state.videos.surfaces.get_mut(&key) else { return }; + v.place = place; + match (&v.inhibitor, place.inhibit_idle, &idle) { + (None, true, Some(m)) => v.inhibitor = Some(m.create_inhibitor(&v.surface, &qh, ())), + (Some(i), false, _) => { + i.destroy(); + v.inhibitor = None; + } + _ => {} + } +} + +/// Before the window's commit at a present: put its videos where they +/// were asked to be, to show with what it presents. Returns the +/// subsurfaces to desynchronize after the commit. +pub fn before_commit(state: &mut State, window: WindowId) -> Vec<(WindowId, VideoId)> { + let Some(win) = state.windows.get(&window) else { return Vec::new() }; + let content = win.surface().clone(); + let top = match &win.shell { + Shell::Toplevel(_) => win.titlebar() as i32, + _ => 0, + }; + let toplevel = matches!(win.shell, Shell::Toplevel(_)); + let mut placed = Vec::new(); + let compositor = &state.compositor; + for (&key, v) in state.videos.surfaces.iter_mut().filter(|((w, _), _)| *w == window) { + let target = v.target(); + if v.applied == Some(target) && !v.synced { + continue; + } + let (x, y, w, h, below) = target; + if !v.synced { + v.subsurface.set_sync(); + v.synced = true; + } + v.subsurface.set_position(x, y + top); + // A sibling of the content where the content is the frame's + // subsurface; under or over the content itself otherwise. + if toplevel { + if below { v.subsurface.place_below(&content) } else { v.subsurface.place_above(&content) } + } else if below { + v.subsurface.place_below(&content); + } + v.viewport.set_destination(w, h); + if let Ok(region) = Region::new(compositor) { + region.add(0, 0, w, h); + v.surface.set_opaque_region(Some(region.wl_region())); + } + v.surface.commit(); + v.applied = Some(target); + placed.push(key); + } + placed +} + +/// After the window's commit: the videos placed go back to showing frames +/// as they come. +pub fn after_commit(state: &mut State, placed: Vec<(WindowId, VideoId)>) { + for key in placed { + if let Some(v) = state.videos.surfaces.get_mut(&key) { + v.subsurface.set_desync(); + v.synced = false; + } + } +} + +/// Show `frame` in video `video` of `window`. +pub fn show(state: &mut State, window: WindowId, video: VideoId, mut frame: VideoFrame) { + let key = (window, video); + if !state.videos.surfaces.contains_key(&key) { + return; // dropped, as discarded + } + let Some(slot) = cached(state, &frame.buffer) else { + eprintln!("sidestep: a video frame's buffer couldn't be made for the compositor"); + return; + }; + let qh = state.qh.clone(); + let monotonic = state.videos.caps.monotonic; + let presentation = state.videos.presentation.clone(); + let Some(entry) = state.videos.buffers.get_mut(&slot) else { return }; + let Some(v) = state.videos.surfaces.get_mut(&key) else { return }; + v.surface.attach(Some(&entry.wl), 0, 0); + v.surface.damage_buffer(0, 0, i32::MAX, i32::MAX); + if v.crop != Some(frame.crop) { + let [x, y, w, h] = frame.crop; + v.viewport.set_source(f64::from(x), f64::from(y), f64::from(w), f64::from(h)); + v.crop = Some(frame.crop); + } + if let (Some(at), Some(timer), true) = (frame.at, &v.timer, monotonic) { + let secs = at / 1_000_000_000; + timer.set_timestamp((secs >> 32) as u32, secs as u32, (at % 1_000_000_000) as u32); + } + match (&presentation, frame.shown.take()) { + (Some(p), Some(shown)) => { + p.feedback(&v.surface, &qh, Feedback(Mutex::new(Some(shown)))); + } + // Without wp_presentation it showed as far as anyone can tell. + (None, Some(shown)) => shown(Shown::Presented { time: 0, refresh: 0 }), + _ => {} + } + v.surface.commit(); + entry.in_flight.push(frame); + state.videos.since_sweep += 1; + if state.videos.since_sweep >= 64 { + sweep(state); + } +} + +/// Show nothing in a video until its next frame. +pub fn clear(state: &mut State, window: WindowId, video: VideoId) { + if let Some(v) = state.videos.surfaces.get_mut(&(window, video)) { + v.surface.attach(None, 0, 0); + v.surface.commit(); + } +} + +/// The cache key of a frame's buffer, made for the compositor if it isn't +/// yet. +fn cached(state: &mut State, buffer: &Arc) -> Option { + let key = Arc::as_ptr(buffer) as usize; + if let Some(c) = state.videos.buffers.get(&key) { + if c.buffer.upgrade().is_some_and(|b| Arc::ptr_eq(&b, buffer)) { + return Some(key); + } + // Another buffer at a freed one's address: the freed one's frames + // are all released (they kept it), so its compositor buffer goes. + state.videos.buffers.remove(&key); + } + let (wl, pool) = match &**buffer { + VideoBuffer::Dmabuf(d) => { + let params = state.videos.dmabuf.create_params(&state.qh).ok()?; + for (i, p) in d.planes.iter().enumerate() { + use std::os::fd::AsFd; + params.add(p.fd.as_fd(), i as u32, p.offset, p.stride, d.modifier); + } + let (wl, _params) = params.create_immed( + d.width as i32, + d.height as i32, + d.fourcc, + zwp_linux_buffer_params_v1::Flags::empty(), + &state.qh, + ); + (wl, None) + } + VideoBuffer::Shm(s) => { + use std::os::fd::AsFd; + let shm: &Shm = &state.shm; + let pool = shm.wl_shm().create_pool(s.fd.as_fd(), s.size as i32, &state.qh, ShmTag); + let format = WEnum::::from(s.format); + let WEnum::Value(format) = format else { return None }; + let wl = pool.create_buffer( + s.offset as i32, + s.width as i32, + s.height as i32, + s.stride as i32, + format, + &state.qh, + ShmTag, + ); + (wl, Some(pool)) + } + }; + state.videos.buffers.insert(key, Cached { buffer: Arc::downgrade(buffer), wl, pool, in_flight: Vec::new() }); + Some(key) +} + +/// Destroy the compositor buffers whose frames' buffers the producer let +/// go of and the compositor has released. +fn sweep(state: &mut State) { + state.videos.since_sweep = 0; + // Frames in flight keep their buffers. + state.videos.buffers.retain(|_, c| c.buffer.strong_count() > 0); +} + +/// The compositor is done reading a buffer: its frames go, and with them +/// what they kept. +fn released(state: &mut State, wl: &WlBuffer) { + let id = wl.id(); + let mut gone = None; + for (k, c) in &mut state.videos.buffers { + if c.wl.id() == id { + c.in_flight.clear(); + if c.buffer.strong_count() == 0 { + gone = Some(*k); + } + break; + } + } + if let Some(k) = gone { + state.videos.buffers.remove(&k); + } +} + +impl DmabufHandler for State { + fn dmabuf_state(&mut self) -> &mut DmabufState { + &mut self.videos.dmabuf + } + + fn dmabuf_feedback( + &mut self, + _: &Connection, + _: &QueueHandle, + proxy: &zwp_linux_dmabuf_feedback_v1::ZwpLinuxDmabufFeedbackV1, + feedback: DmabufFeedback, + ) { + let table = feedback.format_table(); + let mut formats: Vec<(u32, u64)> = feedback + .tranches() + .iter() + .flat_map(|t| t.formats.iter()) + .filter_map(|&i| table.get(usize::from(i))) + .map(|f| (f.format, f.modifier)) + .collect(); + formats.sort_unstable(); + formats.dedup(); + self.videos.caps.dmabuf = formats; + self.videos.caps.main_device = feedback.main_device(); + proxy.destroy(); + if self.videos.caps.known { + crate::video::publish_caps(self.videos.caps.clone()); + } + } + + fn created( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &zwp_linux_buffer_params_v1::ZwpLinuxBufferParamsV1, + _: WlBuffer, + ) { + } + + fn failed( + &mut self, + _: &Connection, + _: &QueueHandle, + _: &zwp_linux_buffer_params_v1::ZwpLinuxBufferParamsV1, + ) { + } + + fn released(&mut self, _: &Connection, _: &QueueHandle, buffer: &WlBuffer) { + released(self, buffer); + } +} + +smithay_client_toolkit::delegate_dmabuf!(State); + +impl Dispatch for State { + fn event( + state: &mut State, + _: &WlCallback, + event: wl_callback::Event, + _: &CapsKnown, + _: &Connection, + _: &QueueHandle, + ) { + let wl_callback::Event::Done { .. } = event else { return }; + let v = &mut state.videos; + if v.dmabuf.version().is_some_and(|ver| ver < 4) { + let mut formats: Vec<(u32, u64)> = v.dmabuf.modifiers().iter().map(|f| (f.format, f.modifier)).collect(); + formats.sort_unstable(); + formats.dedup(); + v.caps.dmabuf = formats; + } + v.caps.shm = state.shm.formats().iter().map(|f| u32::from(*f)).collect(); + v.caps.known = true; + crate::video::publish_caps(v.caps.clone()); + } +} + +impl Dispatch for State { + fn event(_: &mut State, _: &WlShmPool, _: wl_shm_pool::Event, _: &ShmTag, _: &Connection, _: &QueueHandle) {} +} + +impl Dispatch for State { + fn event( + state: &mut State, + buffer: &WlBuffer, + event: wl_buffer::Event, + _: &ShmTag, + _: &Connection, + _: &QueueHandle, + ) { + if let wl_buffer::Event::Release = event { + released(state, buffer); + } + } +} + +impl Dispatch for State { + fn event( + state: &mut State, + _: &WpPresentation, + event: wp_presentation::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + if let wp_presentation::Event::ClockId { clk_id } = event { + state.videos.caps.monotonic = clk_id == CLOCK_MONOTONIC; + } + } +} + +impl Dispatch for State { + fn event( + _: &mut State, + _: &WpPresentationFeedback, + event: wp_presentation_feedback::Event, + feedback: &Feedback, + _: &Connection, + _: &QueueHandle, + ) { + match event { + wp_presentation_feedback::Event::Presented { tv_sec_hi, tv_sec_lo, tv_nsec, refresh, .. } => { + let secs = (u64::from(tv_sec_hi) << 32) | u64::from(tv_sec_lo); + feedback.report(Shown::Presented { time: secs * 1_000_000_000 + u64::from(tv_nsec), refresh }); + } + wp_presentation_feedback::Event::Discarded => feedback.report(Shown::Discarded), + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + _: &mut State, + _: &WpCommitTimingManagerV1, + _: wp_commit_timing_manager_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch for State { + fn event( + _: &mut State, + _: &WpCommitTimerV1, + _: wp_commit_timer_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch for State { + fn event( + _: &mut State, + _: &WpContentTypeManagerV1, + _: wp_content_type_manager_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch for State { + fn event( + _: &mut State, + _: &WpContentTypeV1, + _: wp_content_type_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch for State { + fn event( + _: &mut State, + _: &ZwpIdleInhibitManagerV1, + _: zwp_idle_inhibit_manager_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch for State { + fn event( + _: &mut State, + _: &ZwpIdleInhibitorV1, + _: zwp_idle_inhibitor_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + } +} diff --git a/crates/sidestep-engine/src/lib.rs b/crates/sidestep-engine/src/lib.rs index e223368..49ffb02 100644 --- a/crates/sidestep-engine/src/lib.rs +++ b/crates/sidestep-engine/src/lib.rs @@ -41,3 +41,4 @@ pub mod stats; pub mod system; pub mod text; pub mod trace; +pub mod video; diff --git a/crates/sidestep-engine/src/protocol.rs b/crates/sidestep-engine/src/protocol.rs index 58779f7..da7ecd3 100644 --- a/crates/sidestep-engine/src/protocol.rs +++ b/crates/sidestep-engine/src/protocol.rs @@ -897,6 +897,25 @@ pub enum ToRender { request: u64, app_id: Option, }, + /// Show video `video` of the window there (see `crate::video`), or + /// none: in order with the paints, so it moves with the next present. + PlaceVideo { + window: WindowId, + video: crate::video::VideoId, + place: Option, + }, + /// A frame for video `video` to show (from a player's thread, sent + /// straight here): dropped, as discarded, if the video isn't placed. + ShowVideo { + window: WindowId, + video: crate::video::VideoId, + frame: Box, + }, + /// Show nothing in video `video` until its next frame. + ClearVideo { + window: WindowId, + video: crate::video::VideoId, + }, /// Composite and copy a crop on the null render thread, then answer /// without involving the main thread. Other backends answer `None`. CaptureWindow { diff --git a/crates/sidestep-engine/src/video.rs b/crates/sidestep-engine/src/video.rs new file mode 100644 index 0000000..978426c --- /dev/null +++ b/crates/sidestep-engine/src/video.rs @@ -0,0 +1,283 @@ +//! Video in a window: frames a decoder made, shown as they are. +//! +//! A video is a subsurface of its window (see `backend::video`), placed +//! in the content in whole points and scaled by the compositor +//! (wp_viewporter), so the frames are never copied or drawn here: a +//! hardware decoder's dmabufs go to the compositor as they are, which can +//! put them on a display plane of their own, and a software decoder's +//! pixels go once into shared memory. Nothing of the window's own drawing +//! is involved, and a frame costs the render thread an attach and a +//! commit. +//! +//! The thread that has the frames (a player's) shows them through a +//! [`VideoSink`](crate::protocol::ToRender::ShowVideo) straight to the +//! render thread, each with the time it is for: with wp_commit_timing_v1 +//! the compositor shows it at the first refresh at or after that time, +//! else as soon as it can. Each frame hears once whether it reached the +//! screen ([`Shown`]), from wp_presentation, which is how a player knows +//! its window is out of sight (frames discarded) and may stop decoding. +//! +//! Over the window's content the compositor can scan the video out +//! without composing it; under it (`VideoPlace::below`), what the content +//! draws over the video (controls, subtitles) shows where the content is +//! see-through. + +use std::os::fd::OwnedFd; +use std::sync::Arc; + +use crate::protocol::Rect; + +/// A video of a window, as the window names it. +pub type VideoId = u32; + +/// Where a video shows in its window. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct VideoPlace { + /// In the window's content, in whole points. + pub rect: Rect, + /// Under the content's surface, which shows it where it is see-through + /// (and draws over it elsewhere); else over the content. + pub below: bool, + /// Keep the screen from dimming, blanking and locking. + pub inhibit_idle: bool, +} + +impl VideoPlace { + /// A video at `x`, `y`, `width` × `height` points of the content. + pub fn new(x: f64, y: f64, width: f64, height: f64, below: bool, inhibit_idle: bool) -> VideoPlace { + let rect = Rect::new(x as f32, y as f32, (x + width) as f32, (y + height) as f32); + VideoPlace { rect, below, inhibit_idle } + } + + /// Where it is: x, y, width and height in points. + pub fn bounds(&self) -> [f64; 4] { + let r = &self.rect; + [f64::from(r.x0), f64::from(r.y0), f64::from(r.x1 - r.x0), f64::from(r.y1 - r.y0)] + } +} + +/// A buffer of memory frames show: the same memory shown again is the same +/// buffer (the same `Arc`), which the render thread keeps its compositor +/// buffer for while the producer keeps the `Arc`. +#[derive(Debug)] +pub enum VideoBuffer { + Dmabuf(Dmabuf), + Shm(ShmBuffer), +} + +impl VideoBuffer { + /// Its size in pixels. + pub fn size(&self) -> (u32, u32) { + match self { + VideoBuffer::Dmabuf(d) => (d.width, d.height), + VideoBuffer::Shm(s) => (s.width, s.height), + } + } +} + +/// A linux-dmabuf buffer: its planes' memory, in a DRM format and layout. +#[derive(Debug)] +pub struct Dmabuf { + pub width: u32, + pub height: u32, + /// The DRM fourcc (`NV12`, `P010`, …). + pub fourcc: u32, + /// The DRM format modifier of every plane. + pub modifier: u64, + pub planes: Vec, +} + +#[derive(Debug)] +pub struct DmabufPlane { + pub fd: OwnedFd, + pub offset: u32, + pub stride: u32, +} + +/// Pixels in shared memory (a memfd the producer writes), in a wl_shm +/// format. +#[derive(Debug)] +pub struct ShmBuffer { + pub fd: OwnedFd, + /// The file's size, all of which the compositor maps. + pub size: usize, + pub offset: u32, + pub width: u32, + pub height: u32, + pub stride: u32, + /// The wl_shm format code (XRGB8888 is 1). + pub format: u32, +} + +/// What became of a frame shown. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Shown { + /// On the screen at `time` (nanoseconds of the presentation clock, + /// CLOCK_MONOTONIC), the display refreshing every `refresh` + /// nanoseconds (0 if it doesn't say). + Presented { time: u64, refresh: u32 }, + /// Never reached the screen: replaced first, or its window out of + /// sight. + Discarded, +} + +/// A frame to show. +pub struct VideoFrame { + pub buffer: Arc, + /// The part of the buffer that is the picture, in its pixels: x, y, + /// width, height (a decoder's surfaces are often taller than the + /// picture). + pub crop: [f32; 4], + /// When it should show, in nanoseconds of CLOCK_MONOTONIC; none for + /// as soon as it can. + pub at: Option, + /// What the compositor did with it: called once. + pub shown: Option>, + /// Kept until the compositor is done reading the buffer (dropped on + /// its release): what keeps a decoder from writing into it meanwhile. + pub keep: Option>, +} + +impl VideoFrame { + pub fn new(buffer: Arc) -> VideoFrame { + let (w, h) = buffer.size(); + VideoFrame { buffer, crop: [0.0, 0.0, w as f32, h as f32], at: None, shown: None, keep: None } + } + + /// Say what became of it, once. + pub fn report(&mut self, shown: Shown) { + if let Some(f) = self.shown.take() { + f(shown); + } + } +} + +impl Drop for VideoFrame { + fn drop(&mut self) { + // A frame dropped unshown (its window gone, or never placed). + self.report(Shown::Discarded); + } +} + +impl std::fmt::Debug for VideoFrame { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VideoFrame") + .field("buffer", &self.buffer) + .field("crop", &self.crop) + .field("at", &self.at) + .finish() + } +} + +/// What the compositor takes, known once the render thread has asked. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct VideoCaps { + /// The render thread has heard from the compositor. + pub known: bool, + /// linux-dmabuf formats and modifiers it imports (none without the + /// protocol: a compositor rendering in software). + pub dmabuf: Vec<(u32, u64)>, + /// wl_shm formats. + pub shm: Vec, + /// wp_commit_timing_v1: frames show at the time they ask for. + pub commit_timing: bool, + /// wp_presentation: frames hear when they showed. + pub presentation: bool, + /// The presentation clock is CLOCK_MONOTONIC (the clock frames' times + /// count in); else their times are ignored. + pub monotonic: bool, + /// The device the compositor renders with (a dev_t; 0 if it doesn't + /// say): a decoder there makes buffers it imports best. + pub main_device: u64, +} + +impl VideoCaps { + /// Whether dmabufs of `fourcc` with `modifier` can be shown. + pub fn takes_dmabuf(&self, fourcc: u32, modifier: u64) -> bool { + self.dmabuf.iter().any(|&(f, m)| f == fourcc && m == modifier) + } +} + +/// A render thread has started (and will publish what it takes). +static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// A render thread starts: `caps` waits for what it takes. +pub fn render_started() { + STARTED.store(true, std::sync::atomic::Ordering::Release); +} + +static CAPS: std::sync::RwLock> = std::sync::RwLock::new(None); +static CAPS_KNOWN: std::sync::Condvar = std::sync::Condvar::new(); +static CAPS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// What the running render thread's compositor takes for video, waiting up +/// to `wait` for it to have asked; none if it hasn't (no window shown yet, +/// or no display). +pub fn caps(wait: std::time::Duration) -> Option { + if !STARTED.load(std::sync::atomic::Ordering::Acquire) { + return None; + } + let deadline = std::time::Instant::now() + wait; + let mut guard = CAPS_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(c) = CAPS.read().unwrap_or_else(|e| e.into_inner()).clone().filter(|c| c.known) { + return Some(c); + } + let now = std::time::Instant::now(); + if now >= deadline { + return None; + } + guard = CAPS_KNOWN.wait_timeout(guard, deadline - now).unwrap_or_else(|e| e.into_inner()).0; + } +} + +/// Publish what the compositor takes (the render thread, once it knows). +pub fn publish_caps(caps: VideoCaps) { + let _guard = CAPS_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + *CAPS.write().unwrap_or_else(|e| e.into_inner()) = Some(caps); + CAPS_KNOWN.notify_all(); +} + +/// Now on CLOCK_MONOTONIC, in nanoseconds: the clock frames are timed by. +pub fn monotonic_now() -> u64 { + let t = rustix::time::clock_gettime(rustix::time::ClockId::Monotonic); + t.tv_sec as u64 * 1_000_000_000 + t.tv_nsec as u64 +} + +/// DRM fourcc codes. +pub const fn fourcc(code: &[u8; 4]) -> u32 { + u32::from_le_bytes(*code) +} + +pub const NV12: u32 = fourcc(b"NV12"); +pub const P010: u32 = fourcc(b"P010"); +pub const XRGB8888: u32 = fourcc(b"XR24"); +/// DRM_FORMAT_MOD_LINEAR. +pub const MOD_LINEAR: u64 = 0; +/// DRM_FORMAT_MOD_INVALID: the implicit modifier. +pub const MOD_INVALID: u64 = 0x00ff_ffff_ffff_ffff; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fourccs_are_drms() { + assert_eq!(NV12, 0x3231_564e); + assert_eq!(P010, 0x3031_3050); + assert_eq!(XRGB8888, 0x3432_5258); + } + + #[test] + fn a_frame_dropped_unshown_says_so_once() { + let fd: OwnedFd = std::fs::File::open("/dev/null").expect("/dev/null").into(); + let buffer = + Arc::new(VideoBuffer::Shm(ShmBuffer { fd, size: 4, offset: 0, width: 1, height: 1, stride: 4, format: 1 })); + let (tx, rx) = std::sync::mpsc::channel(); + let mut frame = VideoFrame::new(buffer); + frame.shown = Some(Box::new(move |s| tx.send(s).expect("receiver"))); + assert_eq!(frame.crop, [0.0, 0.0, 1.0, 1.0]); + drop(frame); + assert_eq!(rx.try_iter().collect::>(), vec![Shown::Discarded]); + } +} diff --git a/crates/sidestep-ui/src/app.rs b/crates/sidestep-ui/src/app.rs index 6c5fe27..38c978b 100644 --- a/crates/sidestep-ui/src/app.rs +++ b/crates/sidestep-ui/src/app.rs @@ -875,6 +875,42 @@ impl Cx { } } + /// The types the clipboard holds (MIME types): this program's text, or + /// what another program offers (a screenshot as `image/png`, files as + /// `text/uri-list`). + pub fn clipboard_types(&self) -> Vec { + let shared = clipboard::shared(); + match &self.clipboard { + Some((generation, _)) if shared.change_count() == *generation => { + clipboard::TEXT_MIMES.iter().map(|m| (*m).to_owned()).collect() + } + _ => shared.foreign_mimes(), + } + } + + /// The clipboard's contents as `mime` (one of [`clipboard_types`]), + /// which may take a moment to arrive from another program, as + /// [`clipboard_text`](App::clipboard_text) may. + pub fn clipboard_data(&self, mime: &str) -> Option> { + self.clipboard_reader()(mime) + } + + /// [`clipboard_data`], to call on another thread: a picture another + /// program offers can take a while to arrive, and the windows needn't + /// wait for it. It reads what the clipboard holds when it's called. + pub fn clipboard_reader(&self) -> impl Fn(&str) -> Option> + Send + Sync + 'static { + let own = self.clipboard.clone(); + move |mime| { + let shared = clipboard::shared(); + match &own { + Some((generation, text)) if shared.change_count() == *generation => { + clipboard::TEXT_MIMES.contains(&mime).then(|| text.clone().into_bytes()) + } + _ => shared.read_foreign(mime), + } + } + } + /// The data a drag over one of the windows offers as `mime`, while the /// handler hears of it (most useful in [`Handler::dropped`]). pub fn drag_data(&self, mime: &str) -> Option> { diff --git a/crates/sidestep-ui/src/lib.rs b/crates/sidestep-ui/src/lib.rs index 3ac0d6a..38a7076 100644 --- a/crates/sidestep-ui/src/lib.rs +++ b/crates/sidestep-ui/src/lib.rs @@ -81,6 +81,7 @@ mod image; pub mod layer_shell; pub mod offscreen; mod text; +pub mod video; mod window; #[doc(hidden)] @@ -100,6 +101,7 @@ pub use event::{ pub use image::Image; pub use kurbo; pub use text::{ - Alignment, Caret, Font, FontMetrics, Hit, LineMetrics, TextLayout, TextLayoutBuilder, TextStyle, Wrap, measure, + Alignment, Caret, Font, FontMetrics, Hit, LineMetrics, TextAttachment, TextLayout, TextLayoutBuilder, TextStyle, + Wrap, measure, }; pub use window::{Background, Corner, Cursor, PopupPosition, Window, WindowId, WindowOptions, gather_damage}; diff --git a/crates/sidestep-ui/src/text.rs b/crates/sidestep-ui/src/text.rs index bf70534..81078d8 100644 --- a/crates/sidestep-ui/src/text.rs +++ b/crates/sidestep-ui/src/text.rs @@ -208,6 +208,22 @@ pub struct TextStyle { pub letter_spacing: f64, /// Points to raise the text by (negative lowers it). pub baseline_offset: f64, + /// The box each U+FFFC the style covers is laid out as, if any. + pub attachment: Option, +} + +/// Room in a line for something drawn there that isn't text (a formula in +/// a sentence, a chip): a box laid out in place of a U+FFFC, wrapping with +/// the words around it, as an `NSTextAttachment` is. The text doesn't draw +/// it: [`TextLayout::attachments`] says where each went, for whoever drew +/// the text to fill. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TextAttachment { + /// Its size, in points. + pub width: f64, + pub height: f64, + /// Where its bottom is from the baseline: below it when negative. + pub y: f64, } impl TextStyle { @@ -220,9 +236,16 @@ impl TextStyle { strikethrough: false, letter_spacing: 0.0, baseline_offset: 0.0, + attachment: None, } } + /// Lay each U+FFFC it covers out as `attachment`. + pub fn with_attachment(mut self, attachment: TextAttachment) -> TextStyle { + self.attachment = Some(attachment); + self + } + pub fn underlined(mut self) -> TextStyle { self.underline = true; self @@ -243,6 +266,11 @@ impl TextStyle { attrs.strikethrough = single(self.strikethrough); attrs.kern = (self.letter_spacing != 0.0).then_some(self.letter_spacing as f32); attrs.baseline_offset = self.baseline_offset as f32; + attrs.attachment = self.attachment.map(|a| layout::Attachment { + width: a.width as f32, + height: a.height as f32, + y: a.y as f32, + }); attrs.paragraph = paragraph.clone(); attrs } @@ -597,6 +625,21 @@ impl TextLayout { }) } + /// Where the attachments' boxes went: the byte of each one's U+FFFC, + /// and its rectangle from the layout's top left. + pub fn attachments(&self) -> Vec<(usize, Rect)> { + let mut placed = Vec::new(); + for l in self.frame.lines() { + let (start, top) = (l.range().start, l.top()); + for a in l.line.attachments.iter() { + let [x0, y0, x1, y1] = a.rect; + let rect = Rect::new(f64::from(x0), f64::from(top + y0), f64::from(x1), f64::from(top + y1)); + placed.push((self.byte(start + a.index), rect)); + } + } + placed + } + /// The rectangles that show bytes `range` selected, line by line. pub fn selection_rects(&self, range: Range) -> Vec { let range = self.utf16(range.start)..self.utf16(range.end); @@ -695,6 +738,30 @@ mod tests { assert!((rects[0].x1 - caret.x).abs() < 0.5); } + #[test] + fn attachments_take_their_room_and_say_where_they_went() { + let text = "x = \u{FFFC} here, and on"; + let at = text.find('\u{FFFC}').unwrap(); + let boxed = style().with_attachment(TextAttachment { width: 40.0, height: 30.0, y: -8.0 }); + let plain = TextLayout::new("x = here, and on", &style()); + let layout = TextLayout::builder(text, &style()).style(at..at + 3, boxed).build(); + let placed = layout.attachments(); + assert_eq!(placed.len(), 1); + let (byte, rect) = placed[0]; + assert_eq!(byte, at); + assert!((rect.width() - 40.0).abs() < 0.01 && (rect.height() - 30.0).abs() < 0.01, "{rect:?}"); + assert!(rect.x0 > 0.0 && (layout.size().width - plain.size().width - 40.0).abs() < 0.5, "{rect:?}"); + assert!((rect.y1 - layout.first_baseline() - 8.0).abs() < 0.01, "8 below the baseline: {rect:?}"); + assert!(layout.size().height >= 30.0); + // Wrapped onto a second line, it goes there. + let narrow = TextLayout::builder(text, &style()) + .style(at..at + 3, style().with_attachment(TextAttachment { width: 40.0, height: 30.0, y: -8.0 })); + let narrow = narrow.width(plain.size().width / 2.0).build(); + let (_, rect) = narrow.attachments()[0]; + let lines = narrow.lines(); + assert!(lines.len() > 1 && lines.iter().any(|l| l.top <= rect.y0 && rect.y1 <= l.top + l.height + 0.01)); + } + #[test] fn wrapped_lines_end_in_an_ellipsis() { let text = "A notification's body, long enough to need several lines at this width, cut at two."; diff --git a/crates/sidestep-ui/src/video.rs b/crates/sidestep-ui/src/video.rs new file mode 100644 index 0000000..5f3bd2b --- /dev/null +++ b/crates/sidestep-ui/src/video.rs @@ -0,0 +1,143 @@ +//! Video in a window: a player's frames, shown by the compositor as they +//! are, never drawn on a [`Canvas`](crate::Canvas). +//! +//! A window places a video ([`Window::place_video`](crate::Window::place_video)) +//! in its content, in whole points, over what it draws or under it; it +//! shows there the frames a [`VideoSink`] is given, from any thread, +//! scaled to the place by the compositor. Over the content the compositor +//! can scan the video out on a display plane of its own, composing +//! nothing; under it, the window draws over the video wherever it leaves +//! its pixels clear (a window with [`Background::Transparent`](crate::Background)), +//! for controls and subtitles. The window's place goes with its next +//! frame; frames go as they come. See `sidestep_engine::video`. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; + +use sidestep_engine::protocol::ToRender; +use smithay_client_toolkit::reexports::calloop::channel::Sender; + +pub use sidestep_engine::video::{ + Dmabuf, DmabufPlane, MOD_INVALID, MOD_LINEAR, NV12, P010, ShmBuffer, Shown, VideoBuffer, VideoCaps, VideoFrame, + VideoId, VideoPlace, XRGB8888, fourcc, monotonic_now, +}; + +/// What the compositor takes for video, once the toolkit has heard (it +/// asks as it starts): waits up to `wait`. None where no display was +/// reached. +pub fn caps(wait: std::time::Duration) -> Option { + sidestep_engine::video::caps(wait) +} + +/// Where a video's frames go: to the render thread, for its window's +/// current showing (nowhere while the window is hidden, where frames are +/// discarded), or, detached, to no window at all. +#[derive(Clone)] +pub struct VideoSink { + to: To, + video: VideoId, +} + +#[derive(Clone)] +enum To { + Window { tx: Sender, showing: Arc }, + Detached(Arc), +} + +/// A detached sink's account of what it was given, for tests. +#[derive(Default)] +pub struct Detached { + shown: AtomicU64, + hidden: AtomicBool, + cleared: AtomicU64, + last_size: AtomicU64, +} + +impl Detached { + /// Frames shown (presented). + pub fn shown(&self) -> u64 { + self.shown.load(Ordering::Relaxed) + } + + /// Times it was cleared. + pub fn cleared(&self) -> u64 { + self.cleared.load(Ordering::Relaxed) + } + + /// The size of the last frame shown, in pixels. + pub fn last_size(&self) -> Option<(u32, u32)> { + let v = self.last_size.load(Ordering::Relaxed); + (v != 0).then_some(((v >> 32) as u32, v as u32)) + } + + /// Play a window out of sight: frames are discarded until it's back. + pub fn set_hidden(&self, hidden: bool) { + self.hidden.store(hidden, Ordering::Relaxed); + } +} + +impl VideoSink { + pub(crate) fn new(tx: Sender, showing: Arc, video: VideoId) -> VideoSink { + VideoSink { to: To::Window { tx, showing }, video } + } + + /// A sink for no window: every frame is presented at once (or, while + /// [`Detached::set_hidden`], discarded), and released. For tests and + /// for playing with nothing to show. + pub fn detached() -> (VideoSink, Arc) { + let d = Arc::new(Detached::default()); + (VideoSink { to: To::Detached(d.clone()), video: 0 }, d) + } + + /// Show `frame` as soon as it can, or at its time (`VideoFrame::at`). + /// It hears what became of it; while the window is hidden, it's + /// discarded. + pub fn show(&self, mut frame: VideoFrame) { + match &self.to { + To::Window { tx, showing } => { + let window = showing.load(Ordering::Acquire); + if window == 0 { + return; // dropped: discarded + } + sidestep_engine::backend::null::sending(); + let _ = tx.send(ToRender::ShowVideo { window, video: self.video, frame: Box::new(frame) }); + } + To::Detached(d) => { + if d.hidden.load(Ordering::Relaxed) { + frame.report(Shown::Discarded); + return; + } + let (w, h) = frame.buffer.size(); + d.last_size.store((u64::from(w) << 32) | u64::from(h), Ordering::Relaxed); + d.shown.fetch_add(1, Ordering::Relaxed); + frame.report(Shown::Presented { time: monotonic_now(), refresh: 16_666_667 }); + } + } + } + + /// Show nothing until the next frame. + pub fn clear(&self) { + match &self.to { + To::Window { tx, showing } => { + let window = showing.load(Ordering::Acquire); + if window != 0 { + sidestep_engine::backend::null::sending(); + let _ = tx.send(ToRender::ClearVideo { window, video: self.video }); + } + } + To::Detached(d) => { + d.cleared.fetch_add(1, Ordering::Relaxed); + } + } + } +} + +impl std::fmt::Debug for VideoSink { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let to = match &self.to { + To::Window { showing, .. } => format!("window showing {}", showing.load(Ordering::Relaxed)), + To::Detached(_) => "detached".into(), + }; + f.debug_struct("VideoSink").field("to", &to).field("video", &self.video).finish() + } +} diff --git a/crates/sidestep-ui/src/window.rs b/crates/sidestep-ui/src/window.rs index b3ab0e6..ecdcfb4 100644 --- a/crates/sidestep-ui/src/window.rs +++ b/crates/sidestep-ui/src/window.rs @@ -395,6 +395,12 @@ pub(crate) struct WindowData { /// Rectangles of the content to move at the next pass (points), and by /// how much, in order. pub scrolls: Vec<(Rect, Vec2)>, + /// Videos placed in the content (see `video`), placed again at each + /// showing. + pub videos: Vec<(crate::video::VideoId, crate::video::VideoPlace)>, + /// The current showing for video sinks on other threads (0 while + /// hidden). + pub shared_showing: std::sync::Arc, } /// The most rectangles a window's damage keeps; past them, the two that @@ -478,6 +484,8 @@ impl WindowData { layer_size: options.size, popup_size: None, scrolls: Vec::new(), + videos: Vec::new(), + shared_showing: Default::default(), } } @@ -569,6 +577,10 @@ impl WindowData { if self.opaque_region.is_some() { send(tx, ToRender::SetOpaqueRegion { window: showing, rects: regions(&self.opaque_region) }); } + for &(video, place) in &self.videos { + send(tx, ToRender::PlaceVideo { window: showing, video, place: Some(place) }); + } + self.shared_showing.store(showing, std::sync::atomic::Ordering::Release); self.text_input = (false, None); self.showing = Some(showing); self.configured = false; @@ -582,6 +594,7 @@ impl WindowData { /// Take the window off the screen. pub fn hide(&mut self, tx: &Sender) { + self.shared_showing.store(0, std::sync::atomic::Ordering::Release); if let Some(showing) = self.showing.take() { send(tx, ToRender::CloseWindow { window: showing }); } @@ -762,6 +775,32 @@ impl Window<'_> { } } + /// Show video `video` at `place` in the content, or take it away + /// (`None`); see [`video`](crate::video). The place goes with the + /// window's next frame, so it moves with what's drawn around it; a + /// new place is a frame's change, and the window redraws (the rect of + /// an under video, at least, which it draws clear). + pub fn place_video(&mut self, video: crate::video::VideoId, place: Option) { + let old = self.data.videos.iter().position(|(v, _)| *v == video); + let same = old.map(|i| self.data.videos[i].1) == place; + match (old, place) { + (Some(i), Some(p)) => self.data.videos[i].1 = p, + (Some(i), None) => { + self.data.videos.remove(i); + } + (None, Some(p)) => self.data.videos.push((video, p)), + (None, None) => {} + } + if !same && let Some(showing) = self.data.showing { + send(self.tx, ToRender::PlaceVideo { window: showing, video, place }); + } + } + + /// Where video `video`'s frames go, from any thread. + pub fn video_sink(&self, video: crate::video::VideoId) -> crate::video::VideoSink { + crate::video::VideoSink::new(self.tx.clone(), self.data.shared_showing.clone(), video) + } + /// Scroll `rect` (content points) by `delta`, as a list or an editor /// scrolls: at the next pass the window's pixels there move by `delta` /// (what moves out of `rect` is dropped), and only the strips they diff --git a/docs/architecture.md b/docs/architecture.md index 87ad3a3..fc318d9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1417,6 +1417,29 @@ otherwise): an item per window after the menu's own items and a separator, sorted by title ignoring case, sending `makeKeyAndOrderFront:` to its window; a represented file's window is listed by the file's name. +### Video + +The native toolkit shows a player's frames without drawing them +(`sidestep_engine::video`, `sidestep_ui::video`). A window places a video +in its content (`Window::place_video`): a subsurface of the window's main +surface, beside the content like the tiles and decorations, over the +content or under it, scaled by its viewport. Its frames come from any +thread through a `VideoSink`, straight to the render thread +(`ToRender::ShowVideo`): a linux-dmabuf buffer (a hardware decoder's +surface) or a wl_shm buffer on the producer's memfd, each made into a +compositor buffer the first time it shows and kept while the producer +keeps it, so a decoder's surfaces are imported once. Each frame is +attached and committed on its own (the subsurface is desynchronized), +with the time it's for (wp_commit_timing_v1), asks wp_presentation +whether it reached the screen, and is kept until the compositor releases +its buffer. A new place is applied with the window's next present: the +subsurface is synchronized, placed, committed with the window, and +desynchronized again. Videos take no pointer input, say they're opaque +and a video (wp_content_type_v1), and can hold an idle inhibitor. +`video::caps` says what the compositor takes (dmabuf formats and +modifiers, its render device, commit timing, the presentation clock). The +null render thread presents every frame at once (`Seen::VideoShown`). + ### The clipboard The general `NSPasteboard` is the Wayland selection. Writes never wait: the