From 6e6e954685509434169bdf3fb0c619817406576a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 27 Sep 2026 09:04:05 +0000 Subject: [PATCH] wlroots capture backend; portal and wlroots as streamer backends `capture::wlroots::WlrootsCapture` captures outputs of wlroots compositors (Sway, Hyprland, river, labwc, ...) directly over Wayland, for sessions without a working portal or to skip its dialog. It uses `ext-image-copy-capture-v1` with `ext-output-image-capture-source-v1` where the compositor has them, else `wlr-screencopy-unstable-v1` (`copy_with_damage` from version 2). Both only complete a frame once the screen changed, so a still screen costs nothing. The compositor copies into shared-memory buffers allocated once per size (memfd, mapped once); the sink reads straight from the mapping (y-inverted frames are flipped into a reused buffer first). XRGB/ARGB (BGRx in memory) and XBGR/ABGR are read. Events are dispatched with a poll timeout so stopping is prompt. Feature `wlroots` (default; Linux), using the wayland-client, wayland-protocols and wayland-protocols-wlr versions already in the lock file; `with_display` connects to another socket. Tested against a headless sway 1.9 (wlr-screencopy v3, pixman renderer): outputs, the captured background colour, a colour change through sway's IPC arriving as a new frame, and the queue API (`tests/wlroots_capture.rs`, skipped without VOELIN_WLROOTS_TEST_DISPLAY). The ext-image-copy-capture path is untested: sway 1.9 predates it. `CaptureBackend` gains `Portal` and `Wlroots` (names `auto`, `portal`, `x11`, `wlroots` with `name()` / `FromStr`, as the stream settings spell them); `Auto` stays the session default (the portal on Wayland). `EncodedSource` passes `FrameSource::set_layer_bitrate` to the encoders (`MediaSink::layer_bitrate`). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- Cargo.lock | 3 + crates/voelin-core/src/media.rs | 66 +- crates/voelin-media/Cargo.toml | 10 +- crates/voelin-media/src/capture/mod.rs | 2 + crates/voelin-media/src/capture/wlroots.rs | 679 +++++++++++++++++++ crates/voelin-media/tests/wlroots_capture.rs | 97 +++ 6 files changed, 854 insertions(+), 3 deletions(-) create mode 100644 crates/voelin-media/src/capture/wlroots.rs create mode 100644 crates/voelin-media/tests/wlroots_capture.rs diff --git a/Cargo.lock b/Cargo.lock index 4525066..5bb3c80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9175,6 +9175,9 @@ dependencies = [ "tokio", "tracing", "wasapi", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", "windows-capture", "x11rb", "yuv", diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index d05fd83..50b609b 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -193,8 +193,44 @@ pub enum CaptureBackend { /// the ScreenCast portal on Wayland, X11, Windows Graphics Capture). #[default] Auto, + /// The xdg-desktop-portal ScreenCast dialog (Wayland; also X11 desktops + /// that run the portal). Monitor and window ids are ignored: the + /// dialog picks. + Portal, /// X11, also under Wayland through XWayland (Linux). X11, + /// wlroots compositors (Sway, Hyprland, river, ...) directly, without + /// the portal: `ext-image-copy-capture-v1`, or `wlr-screencopy-unstable-v1` + /// where that is missing (Linux). + Wlroots, +} + +impl CaptureBackend { + /// Names as in settings: `auto`, `portal`, `x11`, `wlroots`. + pub fn name(&self) -> &'static str { + match self { + CaptureBackend::Auto => "auto", + CaptureBackend::Portal => "portal", + CaptureBackend::X11 => "x11", + CaptureBackend::Wlroots => "wlroots", + } + } +} + +impl std::str::FromStr for CaptureBackend { + type Err = MediaError; + + fn from_str(s: &str) -> Result { + match s.trim().to_ascii_lowercase().as_str() { + "auto" | "" => Ok(CaptureBackend::Auto), + "portal" => Ok(CaptureBackend::Portal), + "x11" => Ok(CaptureBackend::X11), + "wlroots" | "wlr" => Ok(CaptureBackend::Wlroots), + other => Err(MediaError::Config(format!( + "unknown capture backend {other:?}: auto, portal, x11 or wlroots" + ))), + } + } } /// What and how to stream. @@ -588,7 +624,7 @@ impl Streamer { (Box::new(screen), None) } #[cfg(all(target_os = "linux", feature = "media-desktop"))] - SourceId::Portal => { + _ if config.source == SourceId::Portal || config.backend == CaptureBackend::Portal => { use voelin_media::capture::portal::PortalCapture; let mut portal = PortalCapture::with_restore_token(config.restore_token.clone()); portal.start_sink(&SourceId::Portal, &options, ingest).await?; @@ -859,6 +895,19 @@ fn screen_backend(backend: &CaptureBackend) -> Result, Me CaptureBackend::X11 => { return Err(unavailable("x11", "X11 capture is only in Linux desktop builds")); } + #[cfg(all(target_os = "linux", feature = "media-desktop"))] + CaptureBackend::Wlroots => Box::new(voelin_media::capture::wlroots::WlrootsCapture::new()), + #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] + CaptureBackend::Wlroots => { + return Err(unavailable("wlroots", "wlroots capture is only in Linux desktop builds")); + } + // Only reached where the portal is not built in. + CaptureBackend::Portal => { + return Err(unavailable( + "portal", + "the ScreenCast portal is only in Linux desktop builds", + )); + } }) } @@ -1271,6 +1320,8 @@ struct ChannelSink { keyframe: AtomicBool, /// Layers a keyframe was asked for. layers: Mutex, + /// What the viewers' bandwidth estimates allow, per layer. + bitrates: Mutex>, shared: Arc, } @@ -1293,6 +1344,10 @@ impl MediaSink for ChannelSink { layers.union_with(&requested); requested.clear(); } + + fn layer_bitrate(&self, layer: LayerId) -> Option { + lock(&self.bitrates).iter().find(|(id, _)| *id == layer).map(|(_, bps)| *bps) + } } /// A [`Streamer`] as a [`FrameSource`], for code that runs @@ -1310,6 +1365,7 @@ impl EncodedSource { tx, keyframe: AtomicBool::new(true), layers: Mutex::new(LayerSet::new()), + bitrates: Mutex::new(Vec::new()), shared: streamer.shared.clone(), }); streamer.attach(sink.clone()); @@ -1333,6 +1389,14 @@ impl FrameSource for EncodedSource { fn request_layer_keyframe(&mut self, layer: LayerId) { lock(&self.sink.layers).insert(layer); } + + fn set_layer_bitrate(&mut self, layer: LayerId, bitrate: u64) { + let mut bitrates = lock(&self.sink.bitrates); + match bitrates.iter_mut().find(|(id, _)| *id == layer) { + Some(entry) => entry.1 = bitrate, + None => bitrates.push((layer, bitrate)), + } + } } /// Whether `data` (one depacketized frame) starts a picture that decodes on diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index 0e51e32..fd6de10 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -9,7 +9,7 @@ repository.workspace = true publish.workspace = true [features] -default = ["vpx", "openh264", "openh264-download", "x11", "pipewire"] +default = ["vpx", "openh264", "openh264-download", "x11", "pipewire", "wlroots"] # VP8 and VP9 through the system libvpx (pkg-config `vpx`). vpx = ["dep:libvpx-native-sys"] # H.264 through Cisco's prebuilt OpenH264 library, loaded at runtime. The @@ -24,6 +24,9 @@ x11 = ["dep:x11rb", "dep:memmap2", "dep:rustix"] # Wayland screen capture (ScreenCast portal + PipeWire, shared memory or # LINEAR DMA-BUFs) and PipeWire system audio (Linux). pipewire = ["dep:ashpd", "dep:pipewire", "dep:memmap2", "dep:rustix"] +# Screen capture on wlroots compositors (Sway, Hyprland, river, ...) without +# the portal: ext-image-copy-capture-v1 or wlr-screencopy-unstable-v1 (Linux). +wlroots = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols-wlr", "dep:memmap2", "dep:rustix"] # Conversion between `Codec` and `str0m::format::Codec`. str0m = ["dep:str0m"] @@ -44,7 +47,10 @@ yuv = "0.8.19" ashpd = { version = "0.13.13", default-features = false, features = ["screencast", "tokio"], optional = true } memmap2 = { version = "0.9.11", optional = true } pipewire = { version = "0.10.1", optional = true } -rustix = { version = "1.1.5", features = ["fs"], optional = true } +rustix = { version = "1.1.5", features = ["event", "fs"], optional = true } +wayland-client = { version = "0.31.15", optional = true } +wayland-protocols = { version = "0.32.13", features = ["client", "staging"], optional = true } +wayland-protocols-wlr = { version = "0.3.12", features = ["client"], optional = true } x11rb = { version = "0.13.2", features = ["randr", "shm", "xfixes"], optional = true } [target.'cfg(target_os = "android")'.dependencies] diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index 2bc26b5..4bfaf85 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -39,6 +39,8 @@ mod pw; pub mod synthetic; #[cfg(windows)] pub mod windows; +#[cfg(all(target_os = "linux", feature = "wlroots"))] +pub mod wlroots; #[cfg(all(target_os = "linux", feature = "x11"))] pub mod x11; diff --git a/crates/voelin-media/src/capture/wlroots.rs b/crates/voelin-media/src/capture/wlroots.rs new file mode 100644 index 0000000..00fd467 --- /dev/null +++ b/crates/voelin-media/src/capture/wlroots.rs @@ -0,0 +1,679 @@ +//! Screen capture on wlroots compositors (Sway, Hyprland, river, labwc, ...) +//! straight through Wayland, without the portal: `ext-image-copy-capture-v1` +//! with `ext-output-image-capture-source-v1` where the compositor has it, +//! else `wlr-screencopy-unstable-v1`. +//! +//! Frames are copied by the compositor into shared-memory buffers we +//! allocate once (a memfd per buffer size) and handed to the +//! [`FrameSink`] straight from that mapping. Both protocols wait for the +//! screen to change before they complete a frame (`copy_with_damage`), so a +//! still screen costs nothing; the frame rate is capped by +//! [`FrameSink::max_fps`]. Monitors only (window capture needs +//! `ext-foreign-toplevel-list`, not done). DMA-BUF capture is not done: +//! frames are always in shared memory. + +use std::os::fd::AsFd; +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use memmap2::MmapMut; +use tracing::{debug, warn}; +use wayland_client::globals::{GlobalList, GlobalListContents, registry_queue_init}; +use wayland_client::protocol::{wl_buffer, wl_output, wl_registry, wl_shm, wl_shm_pool}; +use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle, WEnum, delegate_noop}; +use wayland_protocols::ext::image_capture_source::v1::client::{ + ext_image_capture_source_v1, ext_output_image_capture_source_manager_v1, +}; +use wayland_protocols::ext::image_copy_capture::v1::client::{ + ext_image_copy_capture_frame_v1, ext_image_copy_capture_manager_v1, + ext_image_copy_capture_session_v1, +}; +use wayland_protocols_wlr::screencopy::v1::client::{ + zwlr_screencopy_frame_v1, zwlr_screencopy_manager_v1, +}; + +use crate::capture::{ + BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, SourceId, Worker, +}; +use crate::frame::{FrameRef, PixelsRef, PlaneRef, VideoFrame}; +use crate::queue::FrameReceiver; +use crate::{Error, Result}; + +const BACKEND: &str = "wlroots"; +/// How long the compositor may take to describe buffers. +const SETUP_TIMEOUT: Duration = Duration::from_secs(5); +/// How often waits check whether to stop. +const POLL: Duration = Duration::from_millis(100); +/// Failed frames in a row before the capture gives up. +const MAX_FAILURES: u32 = 20; + +fn unavailable(e: impl std::fmt::Display) -> Error { + Error::CaptureUnavailable { backend: BACKEND, reason: e.to_string() } +} + +fn failed(e: impl std::fmt::Display) -> Error { + Error::Capture { backend: BACKEND, message: e.to_string() } +} + +/// A monitor as the compositor describes it. +#[derive(Clone, Debug, Default)] +struct Output { + name: Option, + description: Option, + mode: (i32, i32), +} + +/// What the compositor said about the frame being captured. +#[derive(Debug, Default)] +struct Frame { + /// Offered shared-memory formats we can read. + formats: Vec, + size: (u32, u32), + /// wlr-screencopy tells the stride; ext-image-copy-capture leaves it to + /// us. + stride: u32, + /// The buffer description is complete. + described: bool, + y_invert: bool, + ready: bool, + failed: Option, + /// The capture session ended (ext): the output went away. + stopped: bool, +} + +#[derive(Default)] +struct State { + outputs: Vec<(wl_output::WlOutput, Output)>, + frame: Frame, +} + +impl Dispatch for State { + fn event( + _: &mut Self, + _: &wl_registry::WlRegistry, + _: wl_registry::Event, + _: &GlobalListContents, + _: &Connection, + _: &QueueHandle, + ) { + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &wl_output::WlOutput, + event: wl_output::Event, + index: &usize, + _: &Connection, + _: &QueueHandle, + ) { + let Some((_, output)) = state.outputs.get_mut(*index) else { return }; + match event { + wl_output::Event::Mode { flags: WEnum::Value(flags), width, height, .. } + if flags.contains(wl_output::Mode::Current) => + { + output.mode = (width, height); + } + wl_output::Event::Name { name } => output.name = Some(name), + wl_output::Event::Description { description } => { + output.description = Some(description); + } + _ => {} + } + } +} + +delegate_noop!(State: ignore wl_shm::WlShm); +delegate_noop!(State: ignore wl_shm_pool::WlShmPool); +delegate_noop!(State: ignore wl_buffer::WlBuffer); +delegate_noop!(State: ignore zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1); +delegate_noop!(State: ignore ext_image_copy_capture_manager_v1::ExtImageCopyCaptureManagerV1); +delegate_noop!(State: ignore ext_output_image_capture_source_manager_v1::ExtOutputImageCaptureSourceManagerV1); +delegate_noop!(State: ignore ext_image_capture_source_v1::ExtImageCaptureSourceV1); + +/// Shared-memory formats we read, best first, and whether they are BGRA in +/// memory (else RGBA). +const FORMATS: [(wl_shm::Format, bool); 4] = [ + (wl_shm::Format::Xrgb8888, true), + (wl_shm::Format::Argb8888, true), + (wl_shm::Format::Xbgr8888, false), + (wl_shm::Format::Abgr8888, false), +]; + +fn supported(format: WEnum) -> Option { + match format { + WEnum::Value(f) if FORMATS.iter().any(|(s, _)| *s == f) => Some(f), + _ => None, + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + frame: &zwlr_screencopy_frame_v1::ZwlrScreencopyFrameV1, + event: zwlr_screencopy_frame_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + use zwlr_screencopy_frame_v1::Event; + let f = &mut state.frame; + match event { + Event::Buffer { format, width, height, stride } => { + if let Some(format) = supported(format) { + f.formats.push(format); + f.size = (width, height); + f.stride = stride; + } + // Before version 3 there is exactly one buffer event. + if frame.version() < 3 { + f.described = true; + } + } + Event::BufferDone => f.described = true, + Event::Flags { flags } => { + f.y_invert = matches!(flags, WEnum::Value(v) if v.contains(zwlr_screencopy_frame_v1::Flags::YInvert)); + } + Event::Ready { .. } => f.ready = true, + Event::Failed => f.failed = Some("the compositor could not copy the frame".into()), + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &ext_image_copy_capture_session_v1::ExtImageCopyCaptureSessionV1, + event: ext_image_copy_capture_session_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + use ext_image_copy_capture_session_v1::Event; + let f = &mut state.frame; + match event { + Event::BufferSize { width, height } => { + // A new description starts (e.g. the output was resized). + f.described = false; + f.formats.clear(); + f.size = (width, height); + f.stride = width * 4; + } + Event::ShmFormat { format } => { + if let Some(format) = supported(format) { + f.formats.push(format); + } + } + Event::Done => f.described = true, + Event::Stopped => f.stopped = true, + _ => {} + } + } +} + +impl Dispatch for State { + fn event( + state: &mut Self, + _: &ext_image_copy_capture_frame_v1::ExtImageCopyCaptureFrameV1, + event: ext_image_copy_capture_frame_v1::Event, + _: &(), + _: &Connection, + _: &QueueHandle, + ) { + use ext_image_copy_capture_frame_v1::{Event, FailureReason}; + let f = &mut state.frame; + match event { + Event::Ready => f.ready = true, + Event::Failed { reason } => { + f.failed = Some(match reason { + WEnum::Value(FailureReason::BufferConstraints) => "buffer constraints".into(), + WEnum::Value(FailureReason::Stopped) => { + f.stopped = true; + "the session stopped".into() + } + _ => "the compositor could not copy the frame".into(), + }); + } + _ => {} + } + } +} + +/// A shared-memory buffer the compositor copies frames into. +struct ShmBuffer { + map: MmapMut, + pool: wl_shm_pool::WlShmPool, + buffer: wl_buffer::WlBuffer, + key: (wl_shm::Format, u32, u32, u32), +} + +impl ShmBuffer { + fn new( + shm: &wl_shm::WlShm, + qh: &QueueHandle, + format: wl_shm::Format, + (width, height): (u32, u32), + stride: u32, + ) -> Result { + let size = stride as usize * height as usize; + let fd = + rustix::fs::memfd_create("voelin-wlroots-capture", rustix::fs::MemfdFlags::CLOEXEC) + .map_err(|e| failed(format!("memfd_create: {e}")))?; + let file = std::fs::File::from(fd); + file.set_len(size as u64)?; + let map = map_shared(&file)?; + let len = i32::try_from(size).map_err(|_| failed("frame too large"))?; + let pool = shm.create_pool(file.as_fd(), len, qh, ()); + let buffer = + pool.create_buffer(0, width as i32, height as i32, stride as i32, format, qh, ()); + Ok(Self { map, pool, buffer, key: (format, width, height, stride) }) + } +} + +impl Drop for ShmBuffer { + fn drop(&mut self) { + self.buffer.destroy(); + self.pool.destroy(); + } +} + +/// Map our memfd. +#[allow(unsafe_code)] +fn map_shared(file: &std::fs::File) -> Result { + // SAFETY: memmap2 needs the file not to be truncated, and not to be + // written by others while Rust reads the mapping. The file is an + // anonymous memfd we created and never resize after mapping; the only + // other party is the compositor, which writes into it only between our + // copy request and its `ready` / `failed` event. The capture loop reads + // the mapping only after `ready`, and requests the next copy only after + // reading. + Ok(unsafe { MmapMut::map_mut(file) }?) +} + +/// The protocol the compositor offers. +enum Capturer { + Ext { + manager: ext_image_copy_capture_manager_v1::ExtImageCopyCaptureManagerV1, + sources: ext_output_image_capture_source_manager_v1::ExtOutputImageCaptureSourceManagerV1, + }, + Wlr(zwlr_screencopy_manager_v1::ZwlrScreencopyManagerV1), +} + +/// A connection with the globals we need. +struct Display { + conn: Connection, + queue: EventQueue, + state: State, + shm: wl_shm::WlShm, + capturer: Capturer, +} + +impl Display { + fn connect(socket: Option<&PathBuf>) -> Result { + let conn = match socket { + Some(path) => { + let stream = UnixStream::connect(path) + .map_err(|e| unavailable(format!("{}: {e}", path.display())))?; + Connection::from_socket(stream).map_err(unavailable)? + } + None => Connection::connect_to_env().map_err(unavailable)?, + }; + let (globals, mut queue) = registry_queue_init::(&conn).map_err(unavailable)?; + let qh = queue.handle(); + let shm: wl_shm::WlShm = globals.bind(&qh, 1..=1, ()).map_err(unavailable)?; + let capturer = match (globals.bind(&qh, 1..=1, ()), globals.bind(&qh, 1..=1, ())) { + (Ok(manager), Ok(sources)) => Capturer::Ext { manager, sources }, + _ => Capturer::Wlr(globals.bind(&qh, 1..=3, ()).map_err(|_| { + unavailable( + "the compositor has neither ext-image-copy-capture-v1 nor \ + wlr-screencopy-unstable-v1", + ) + })?), + }; + let mut state = State::default(); + bind_outputs(&globals, &qh, &mut state); + // Outputs describe themselves after binding. + queue.roundtrip(&mut state).map_err(unavailable)?; + Ok(Self { conn, queue, state, shm, capturer }) + } + + fn protocol(&self) -> &'static str { + match self.capturer { + Capturer::Ext { .. } => "ext-image-copy-capture-v1", + Capturer::Wlr(_) => "wlr-screencopy-unstable-v1", + } + } + + /// Dispatch events for up to `timeout`. + fn dispatch(&mut self, timeout: Duration) -> Result<()> { + self.queue.dispatch_pending(&mut self.state).map_err(failed)?; + self.queue.flush().map_err(failed)?; + if let Some(guard) = self.queue.prepare_read() { + let readable = { + let fd = guard.connection_fd(); + let mut fds = [rustix::event::PollFd::new(&fd, rustix::event::PollFlags::IN)]; + let timeout = rustix::event::Timespec { + tv_sec: timeout.as_secs() as _, + tv_nsec: timeout.subsec_nanos() as _, + }; + match rustix::event::poll(&mut fds, Some(&timeout)) { + Ok(n) => n > 0, + Err(rustix::io::Errno::INTR) => false, + Err(e) => return Err(failed(format!("poll: {e}"))), + } + }; + if readable { + guard.read().map_err(failed)?; + } + } + self.queue.dispatch_pending(&mut self.state).map_err(failed)?; + Ok(()) + } + + /// Dispatch until `done` holds; `false` if `stop` got set or `timeout` + /// passed first. + fn wait( + &mut self, + stop: &AtomicBool, + timeout: Option, + done: impl Fn(&Frame) -> bool, + ) -> Result { + let deadline = timeout.map(|t| Instant::now() + t); + while !done(&self.state.frame) { + if stop.load(Ordering::Relaxed) || deadline.is_some_and(|d| Instant::now() >= d) { + return Ok(false); + } + self.dispatch(POLL)?; + } + Ok(true) + } +} + +fn bind_outputs(globals: &GlobalList, qh: &QueueHandle, state: &mut State) { + let outputs: Vec<(u32, u32)> = globals.contents().with_list(|list| { + list.iter().filter(|g| g.interface == "wl_output").map(|g| (g.name, g.version)).collect() + }); + for (name, version) in outputs { + let index = state.outputs.len(); + let output: wl_output::WlOutput = globals.registry().bind(name, version.min(4), qh, index); + state.outputs.push((output, Output::default())); + } +} + +/// wlroots capture backend. Sources are the compositor's outputs, as +/// [`SourceId::Monitor`] by their order. +#[derive(Default)] +pub struct WlrootsCapture { + socket: Option, + worker: Option, +} + +impl WlrootsCapture { + /// Capture from `$WAYLAND_DISPLAY`. + pub fn new() -> Self { + Self::default() + } + + /// Capture from another Wayland display: a socket name in + /// `$XDG_RUNTIME_DIR` (`"wayland-1"`) or a path. + pub fn with_display(display: impl Into) -> Self { + let display = display.into(); + let socket = if display.is_absolute() { + display + } else { + std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).unwrap_or_default().join(display) + }; + Self { socket: Some(socket), worker: None } + } + + /// Whether the compositor offers one of the capture protocols. + pub fn is_available(&self) -> bool { + Display::connect(self.socket.as_ref()).is_ok() + } +} + +impl ScreenCapture for WlrootsCapture { + fn backend(&self) -> &'static str { + BACKEND + } + + fn sources(&mut self) -> Result> { + let display = Display::connect(self.socket.as_ref())?; + Ok(display + .state + .outputs + .iter() + .enumerate() + .map(|(i, (_, o))| CaptureSource { + id: SourceId::Monitor(i as u32), + name: o + .description + .clone() + .or_else(|| o.name.clone()) + .unwrap_or_else(|| format!("Output {}", i + 1)), + width: o.mode.0.max(0) as u32, + height: o.mode.1.max(0) as u32, + primary: i == 0, + }) + .collect()) + } + + fn start( + &mut self, + source: &SourceId, + options: &CaptureOptions, + ) -> BoxFuture<'_, Result>> { + let (sink, rx) = QueueSink::new(options); + let started = self.start_sink(source, options, Box::new(sink)); + Box::pin(async move { + started.await?; + Ok(rx) + }) + } + + fn start_sink( + &mut self, + source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'_, Result<()>> { + let source = source.clone(); + let cursor = options.cursor; + Box::pin(async move { + self.stop(); + let SourceId::Monitor(index) = source else { + return Err(Error::SourceNotFound(source)); + }; + let socket = self.socket.clone(); + let (init_tx, init_rx) = mpsc::channel(); + self.worker = Some(Worker::spawn("voelin-wlroots-capture", move |stop| { + let display = Display::connect(socket.as_ref()).and_then(|d| { + if (index as usize) < d.state.outputs.len() { + Ok(d) + } else { + Err(Error::SourceNotFound(SourceId::Monitor(index))) + } + }); + let mut display = match display { + Ok(d) => d, + Err(e) => { + let _ = init_tx.send(Err(e)); + return; + } + }; + let protocol = display.protocol(); + debug!(protocol, output = index, "wlroots capture"); + let _ = init_tx.send(Ok(())); + if let Err(e) = capture_loop(&mut display, index as usize, cursor, sink, &stop) { + warn!("wlroots capture stopped: {e}"); + } + })?); + match init_rx.recv() { + Ok(result) => result, + Err(_) => Err(failed("the capture thread ended during setup")), + } + }) + } + + fn stop(&mut self) { + self.worker = None; + } +} + +/// Sleep until `until`, or until `stop` is set. `false` if stopped. +fn sleep_until(until: Instant, stop: &AtomicBool) -> bool { + while !stop.load(Ordering::Relaxed) { + let now = Instant::now(); + if now >= until { + return true; + } + // Woken early by `Worker::stop`. + std::thread::park_timeout(until - now); + } + false +} + +fn capture_loop( + display: &mut Display, + output: usize, + cursor: bool, + mut sink: Box, + stop: &AtomicBool, +) -> Result<()> { + let qh = display.queue.handle(); + let wl_output = display.state.outputs[output].0.clone(); + let session = match &display.capturer { + Capturer::Ext { manager, sources } => { + let source = sources.create_source(&wl_output, &qh, ()); + let options = if cursor { + ext_image_copy_capture_manager_v1::Options::PaintCursors + } else { + ext_image_copy_capture_manager_v1::Options::empty() + }; + Some((manager.create_session(&source, options, &qh, ()), source)) + } + Capturer::Wlr(_) => None, + }; + let started = Instant::now(); + let mut buffer: Option = None; + // Rows of a y-inverted frame, flipped. + let mut flipped: Vec = Vec::new(); + let mut next_due = Instant::now(); + let mut failures = 0; + loop { + if !sleep_until(next_due, stop) { + break; + } + // Describe the buffer: per frame (wlr), or per session (ext). + let frame = &mut display.state.frame; + frame.ready = false; + frame.failed = None; + frame.y_invert = false; + let wlr_frame = match &display.capturer { + Capturer::Wlr(manager) => { + frame.formats.clear(); + frame.described = false; + Some(manager.capture_output(i32::from(cursor), &wl_output, &qh, ())) + } + Capturer::Ext { .. } => None, + }; + let described = display.wait(stop, Some(SETUP_TIMEOUT), |f| f.described || f.stopped)?; + if !described || display.state.frame.stopped { + if let Some(f) = wlr_frame { + f.destroy(); + } + if stop.load(Ordering::Relaxed) || display.state.frame.stopped { + break; + } + return Err(failed("the compositor did not describe the frame buffer")); + } + let frame = &display.state.frame; + let Some(format) = FORMATS.iter().map(|(f, _)| *f).find(|f| frame.formats.contains(f)) + else { + return Err(failed(format!("no readable shared-memory format in {:?}", frame.formats))); + }; + let key = (format, frame.size.0, frame.size.1, frame.stride); + if buffer.as_ref().is_none_or(|b| b.key != key) { + // The old buffer goes before the new one is allocated. + drop(buffer.take()); + buffer = Some(ShmBuffer::new(&display.shm, &qh, format, frame.size, frame.stride)?); + } + let shm = buffer.as_ref().expect("created above"); + let ext_frame = match (&wlr_frame, &session) { + (Some(f), _) => { + if f.version() >= 2 { + f.copy_with_damage(&shm.buffer); + } else { + f.copy(&shm.buffer); + } + None + } + (None, Some((session, _))) => { + let f = session.create_frame(&qh, ()); + f.attach_buffer(&shm.buffer); + // Everything may have changed since the buffer was used. + f.damage_buffer(0, 0, i32::MAX, i32::MAX); + f.capture(); + Some(f) + } + (None, None) => unreachable!("one of the protocols is bound"), + }; + let done = display.wait(stop, None, |f| f.ready || f.failed.is_some())?; + if let Some(f) = wlr_frame { + f.destroy(); + } + if let Some(f) = ext_frame { + f.destroy(); + } + if !done { + break; + } + if let Some(reason) = display.state.frame.failed.take() { + if display.state.frame.stopped { + break; + } + failures += 1; + if failures > MAX_FAILURES { + return Err(failed(reason)); + } + // Buffer constraints changed (ext): the session describes the + // new ones. + buffer = None; + continue; + } + failures = 0; + let timestamp = started.elapsed(); + let fps = sink.max_fps().max(1); + next_due = Instant::now() + Duration::from_secs(1) / fps * 7 / 8; + if !sink.wants(timestamp) { + continue; + } + let (width, height, stride) = (key.1, key.2, key.3 as usize); + let bgra = FORMATS.iter().any(|(f, bgra)| *f == format && *bgra); + let mut bytes: &[u8] = &shm.map; + if display.state.frame.y_invert { + // Rare (some renderers read back bottom-up): flip into a buffer. + flipped.clear(); + for row in shm.map.chunks_exact(stride).take(height as usize).rev() { + flipped.extend_from_slice(row); + } + bytes = &flipped; + } + let plane = PlaneRef::new(bytes, stride); + let pixels = if bgra { PixelsRef::Bgra(plane) } else { PixelsRef::Rgba(plane) }; + if !sink.frame(FrameRef { width, height, timestamp, pixels }) { + break; + } + } + if let Some((session, source)) = session { + session.destroy(); + source.destroy(); + } + let _ = display.conn.flush(); + Ok(()) +} diff --git a/crates/voelin-media/tests/wlroots_capture.rs b/crates/voelin-media/tests/wlroots_capture.rs new file mode 100644 index 0000000..d0edba4 --- /dev/null +++ b/crates/voelin-media/tests/wlroots_capture.rs @@ -0,0 +1,97 @@ +//! wlroots capture against a real compositor: lists outputs, captures the +//! background colour, changes it through sway's IPC and sees the change. +//! +//! Needs a headless sway and its sockets, e.g. +//! +//! ```sh +//! printf 'output HEADLESS-1 resolution 640x480 bg #204080 solid_color\n' > /tmp/sway.conf +//! XDG_RUNTIME_DIR=/tmp/vsw WLR_BACKENDS=headless WLR_LIBINPUT_NO_DEVICES=1 \ +//! WLR_RENDERER=pixman sway -c /tmp/sway.conf & +//! VOELIN_WLROOTS_TEST_DISPLAY=/tmp/vsw/wayland-1 \ +//! VOELIN_WLROOTS_TEST_SWAYSOCK=$(ls /tmp/vsw/sway-ipc.*.sock) \ +//! cargo test -p voelin-media --test wlroots_capture +//! ``` +//! +//! Skipped without `VOELIN_WLROOTS_TEST_DISPLAY`. +#![cfg(all(target_os = "linux", feature = "wlroots"))] + +use std::sync::mpsc; +use std::time::Duration; + +use voelin_media::capture::wlroots::WlrootsCapture; +use voelin_media::capture::{FrameSink, ScreenCapture}; +use voelin_media::{CaptureOptions, FrameRef, PixelsRef, SourceId}; + +/// Sends the centre pixel (RGB) and size of each frame. +struct Probe(mpsc::Sender<([u8; 3], u32, u32)>); + +impl FrameSink for Probe { + fn max_fps(&self) -> u32 { + 30 + } + + fn frame(&mut self, frame: FrameRef<'_>) -> bool { + let (x, y) = (frame.width as usize / 2, frame.height as usize / 2); + let rgb = match frame.pixels { + PixelsRef::Bgra(p) => { + let px = &p.row(y, frame.width as usize * 4)[x * 4..x * 4 + 4]; + [px[2], px[1], px[0]] + } + PixelsRef::Rgba(p) => { + let px = &p.row(y, frame.width as usize * 4)[x * 4..x * 4 + 4]; + [px[0], px[1], px[2]] + } + _ => panic!("unexpected format {:?}", frame.format()), + }; + self.0.send((rgb, frame.width, frame.height)).is_ok() + } +} + +fn sway_background(color: &str) { + let Some(sock) = std::env::var_os("VOELIN_WLROOTS_TEST_SWAYSOCK") else { return }; + let status = std::process::Command::new("swaymsg") + .env("SWAYSOCK", sock) + .args(["output", "*", "bg", color, "solid_color"]) + .status() + .expect("swaymsg"); + assert!(status.success()); +} + +#[tokio::test] +async fn captures_outputs() { + let Some(display) = std::env::var_os("VOELIN_WLROOTS_TEST_DISPLAY") else { + eprintln!("skipped: VOELIN_WLROOTS_TEST_DISPLAY is not set"); + return; + }; + sway_background("#204080"); + let mut capture = WlrootsCapture::with_display(&display); + assert!(capture.is_available()); + let sources = capture.sources().unwrap(); + assert!(!sources.is_empty(), "no outputs"); + eprintln!("outputs: {sources:?}"); + assert_eq!(sources[0].id, SourceId::Monitor(0)); + assert!(capture.start(&SourceId::Monitor(99), &CaptureOptions::default()).await.is_err()); + + let (tx, rx) = mpsc::channel(); + let options = CaptureOptions { cursor: false, ..CaptureOptions::default() }; + capture.start_sink(&SourceId::Monitor(0), &options, Box::new(Probe(tx))).await.unwrap(); + let (rgb, w, h) = rx.recv_timeout(Duration::from_secs(5)).expect("a first frame"); + assert_eq!((w, h), (sources[0].width, sources[0].height)); + assert_eq!(rgb, [0x20, 0x40, 0x80]); + if std::env::var_os("VOELIN_WLROOTS_TEST_SWAYSOCK").is_some() { + // New content: a new frame with the new colour. + sway_background("#c04020"); + let changed = (0..20).any(|_| { + rx.recv_timeout(Duration::from_secs(5)).is_ok_and(|(rgb, ..)| rgb == [0xc0, 0x40, 0x20]) + }); + assert!(changed, "the background change was not captured"); + } + capture.stop(); + + // The queue API copies frames out. + let mut frames = capture.start(&SourceId::Monitor(0), &options).await.unwrap(); + let frame = frames.recv_timeout(Duration::from_secs(5)).expect("a queued frame"); + assert_eq!((frame.width, frame.height), (w, h)); + capture.stop(); + sway_background("#204080"); +}