voelin-media: capture into sinks, zero-copy conversion, scaling, pools; libvpx tuning

Screen sharing was slow mostly because every frame was copied and
allocated several times on its way to the encoder: the PipeWire callback
copied the mapped buffer into a new Vec, X11 copied the shared-memory
segment, Windows copied twice, `to_i420` allocated fresh planes on one
thread, and libvpx output was copied into Vec after Vec.

Capture backends now hand each frame to a `FrameSink` on their own
thread, with the pixels still in the capture buffer (`FrameRef`: borrowed
planes with strides). `ScreenCapture::start_sink` is implemented by the
test pattern (renders into one reused buffer), X11 (the MIT-SHM segment,
cursor blended in place, monitor/window geometry looked up once a second
instead of every frame), the portal and Windows Graphics Capture (the
mapped staging texture with its row pitch); other backends get a
forwarding default. `start` keeps working through a queue adapter.
`FramePacer` caps frame rates by timestamps; sinks can change the cap
while capturing (X11 and the test pattern follow, the portal renegotiates
the frame rate).

Portal: LINEAR DMA-BUFs are negotiated in addition to shared memory
(mandatory modifier, fixated by us, `dataType` per buffer kind), mapped
once per buffer and read between DMA_BUF_IOCTL_SYNC start/end. When
reading them is slow (uncached VRAM), the stream renegotiates to shared
memory. Tiled modifiers are not offered (needs a GPU import).

The streaming path:
- `workers::Workers`: a fork-join pool that allocates nothing per job.
- `convert::Converter`: any stride, BGRx/BGRA/RGBx/RGBA (yuv's SIMD
  paths), I420 and NV12 into a caller's I420 frame, in row bands on all
  cores; handles buffers without padding after the last row.
- `scale`: separable area-average downscaling (bilinear up), weights per
  size pair computed once, a 2x2 box fast path, row bands on the pool;
  `Pyramid` converts a capture once and derives every requested size
  from the nearest larger one, sharing equal sizes.
- `pool::FramePool`: recycled `Arc<VideoFrame>`s; `handoff::Handoff`: a
  one-slot latest-wins atomic handoff that counts replaced frames.

Codecs: `VideoEncoder::encode_with` hands out encoded frames borrowed
from the encoder (libvpx's own buffer; OpenH264 into a reused buffer).
libvpx: `cpu-used` adapts to the measured encode time against the frame
interval (VP8 levels -10..-4, VP9 starting at 8 within 5..9), threads from
all CPUs the frame size can use, VP8 token partitions and VP9 tile
columns from the thread count and width, keyframes only on request,
frame durations from timestamps (variable frame rate), `set_fps`, and
`speed` for stats. A probe on the desktop test pattern showed VP8 speeds
beyond -10 are no faster on screen content, only worse (about 3 dB PSNR).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-27 08:35:57 +00:00
1 parent 31b138adf1
commit bbfd9aba47
18 files changed
+2780 -271

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
//! CPU access to LINEAR DMA-BUFs (screen capture buffers a compositor
//! shares): a read-only mapping, and `DMA_BUF_IOCTL_SYNC` around each read
//! so caches are coherent with what the GPU wrote. Tiled buffers cannot be
//! read like this; they need a GPU import (not done here).
#![allow(unsafe_code)]
use std::io;
use std::os::fd::{BorrowedFd, RawFd};
use memmap2::{Mmap, MmapOptions};
/// `struct dma_buf_sync` of `<linux/dma-buf.h>`.
#[repr(C)]
struct DmaBufSync {
flags: u64,
}
const DMA_BUF_SYNC_READ: u64 = 1 << 0;
const DMA_BUF_SYNC_START: u64 = 0 << 2;
const DMA_BUF_SYNC_END: u64 = 1 << 2;
/// `DMA_BUF_IOCTL_SYNC`: `_IOW('b', 0, struct dma_buf_sync)`.
const SYNC: rustix::ioctl::Opcode = rustix::ioctl::opcode::write::<DmaBufSync>(b'b', 0);
/// A read-only mapping of a DMA-BUF.
pub(crate) struct DmaBufMap {
fd: RawFd,
map: Mmap,
}
impl DmaBufMap {
/// Map the first `len` bytes of the DMA-BUF `fd`. The caller keeps `fd`
/// open while the mapping is used (the mapping itself keeps the buffer
/// alive, but [`DmaBufMap::read`] syncs through the descriptor).
pub fn new(fd: RawFd, len: usize) -> io::Result<Self> {
if fd < 0 || len == 0 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "no DMA-BUF to map"));
}
// SAFETY: memmap2 requires that the mapped object is not truncated
// or changed by others while Rust reads it. A DMA-BUF cannot be
// truncated; the compositor writes into a buffer only while it is
// not handed to us (PipeWire queues it back after our callback), and
// `read` brackets every access with DMA_BUF_IOCTL_SYNC so the CPU
// sees the GPU's writes. We only read.
let map = unsafe { MmapOptions::new().len(len).map(fd) }?;
Ok(Self { fd, map })
}
pub fn fd(&self) -> RawFd {
self.fd
}
pub fn len(&self) -> usize {
self.map.len()
}
/// Run `f` on the mapped bytes between the start and end of a read
/// access.
pub fn read<R>(&self, f: impl FnOnce(&[u8]) -> R) -> R {
self.sync(DMA_BUF_SYNC_START);
let result = f(&self.map);
self.sync(DMA_BUF_SYNC_END);
result
}
fn sync(&self, when: u64) {
// SAFETY: `fd` is the open DMA-BUF this mapping was made from (see
// `new`); borrowing it for the call does not close it.
let fd = unsafe { BorrowedFd::borrow_raw(self.fd) };
let sync = DmaBufSync { flags: DMA_BUF_SYNC_READ | when };
// SAFETY: DMA_BUF_IOCTL_SYNC takes a pointer to a `dma_buf_sync`,
// which is what `Setter` passes; it only reads it. A failure (e.g. a
// kernel without the ioctl) leaves the data as coherent as the
// mapping is anyway, so it is ignored.
let _ = unsafe {
rustix::ioctl::ioctl(fd, rustix::ioctl::Setter::<SYNC, DmaBufSync>::new(sync))
};
}
}
#[cfg(test)]
mod tests {
use std::io::Write;
use std::os::fd::AsRawFd;
use super::*;
/// A memfd maps like a DMA-BUF; the sync ioctl fails on it and is
/// ignored.
#[test]
fn maps_and_reads() {
let fd = rustix::fs::memfd_create("voelin-dmabuf-test", rustix::fs::MemfdFlags::CLOEXEC)
.unwrap();
let mut file = std::fs::File::from(fd);
file.write_all(&[7; 8192]).unwrap();
let map = DmaBufMap::new(file.as_raw_fd(), 8192).unwrap();
assert_eq!(map.len(), 8192);
assert_eq!(map.fd(), file.as_raw_fd());
assert_eq!(map.read(|b| b.iter().map(|&x| u64::from(x)).sum::<u64>()), 7 * 8192);
assert!(DmaBufMap::new(-1, 10).is_err());
}
}
+199 -8
View File
@@ -1,7 +1,12 @@
//! Screen and system-audio capture.
//!
//! Backends deliver frames on a [`FrameReceiver`] from their own thread; the
//! queue drops the oldest frame when the consumer falls behind.
//! Screen backends hand each frame to a [`FrameSink`] on their own thread,
//! with the pixels still in the capture buffer (a PipeWire buffer, the X11
//! shared-memory segment, a Windows staging texture), so the sink converts
//! straight from it ([`ScreenCapture::start_sink`]). [`ScreenCapture::start`]
//! instead copies frames into a [`FrameReceiver`]; the queue drops the oldest
//! frame when the consumer falls behind. Audio backends use a
//! [`FrameReceiver`].
//!
//! | Backend | Screen | System audio |
//! |---|---|---|
@@ -18,10 +23,12 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use crate::frame::{AudioBuffer, VideoFrame};
use crate::queue::FrameReceiver;
use crate::frame::{AudioBuffer, FrameRef, VideoFrame};
use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::{Error, Result};
#[cfg(all(target_os = "linux", feature = "pipewire"))]
mod dmabuf;
pub mod external;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
pub mod pipewire_audio;
@@ -64,7 +71,8 @@ pub struct CaptureSource {
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CaptureOptions {
/// Maximum frame rate.
/// Maximum frame rate for [`ScreenCapture::start`] (with
/// [`ScreenCapture::start_sink`], [`FrameSink::max_fps`] decides).
pub fps: u32,
/// Draw the mouse cursor into the frames.
pub cursor: bool,
@@ -78,6 +86,133 @@ impl Default for CaptureOptions {
}
}
/// Receives captured frames on the capture backend's thread; see
/// [`ScreenCapture::start_sink`].
pub trait FrameSink: Send {
/// The highest frame rate wanted now. Backends that pace themselves
/// (X11, the test pattern) capture at this rate; it may change while
/// capturing.
fn max_fps(&self) -> u32;
/// Whether a frame captured at `timestamp` would be used. Backends that
/// get frames pushed (PipeWire, Windows, wlroots) ask before they map or
/// copy anything, and give unwanted buffers straight back.
fn wants(&mut self, timestamp: Duration) -> bool {
let _ = timestamp;
true
}
/// One frame. Its pixels are only valid during the call. Returns
/// `false` when no more frames are wanted; the backend then stops.
fn frame(&mut self, frame: FrameRef<'_>) -> bool;
}
/// Keeps frames of a source for a frame-rate cap, by their timestamps, so
/// the kept frames are evenly spaced at the cap (or at the source's rate if
/// that is lower).
#[derive(Clone, Debug)]
pub struct FramePacer {
interval: Duration,
next: Option<Duration>,
}
impl FramePacer {
/// At most `fps` frames per second; `None` (or 0) keeps every frame.
pub fn new(fps: Option<u32>) -> Self {
let mut pacer = Self { interval: Duration::ZERO, next: None };
pacer.set_fps(fps);
pacer
}
pub fn set_fps(&mut self, fps: Option<u32>) {
self.interval = match fps {
Some(fps) if fps > 0 => Duration::from_secs(1) / fps,
_ => Duration::ZERO,
};
}
/// Whether a frame at `timestamp` is due. A frame up to an eighth of
/// the interval early still counts, so jitter does not halve the rate;
/// a timestamp far before the expected one means the clock started
/// over.
pub fn due(&self, timestamp: Duration) -> bool {
self.next.is_none_or(|next| {
timestamp + self.interval / 8 >= next || timestamp + 2 * self.interval <= next
})
}
/// Record that the frame at `timestamp` was kept.
pub fn keep(&mut self, timestamp: Duration) {
let iv = self.interval;
self.next = Some(match self.next {
// On time: keep the average rate exact.
Some(next) if timestamp < next + iv && timestamp + 2 * iv > next => next + iv,
// Late (or the clock jumped): start over from this frame.
_ => timestamp + iv,
});
}
/// [`due`](Self::due), and [`keep`](Self::keep) if so.
pub fn take(&mut self, timestamp: Duration) -> bool {
let due = self.due(timestamp);
if due {
self.keep(timestamp);
}
due
}
}
/// Copies frames into a queue: [`ScreenCapture::start`] of backends that
/// deliver into a [`FrameSink`].
pub(crate) struct QueueSink {
tx: FrameSender<VideoFrame>,
fps: u32,
pacer: FramePacer,
}
impl QueueSink {
pub fn new(options: &CaptureOptions) -> (Self, FrameReceiver<VideoFrame>) {
let (tx, rx) = frame_channel(options.queue);
let fps = options.fps.max(1);
(Self { tx, fps, pacer: FramePacer::new(Some(fps)) }, rx)
}
}
impl FrameSink for QueueSink {
fn max_fps(&self) -> u32 {
self.fps
}
fn wants(&mut self, timestamp: Duration) -> bool {
!self.tx.is_closed() && self.pacer.due(timestamp)
}
fn frame(&mut self, frame: FrameRef<'_>) -> bool {
self.pacer.keep(frame.timestamp);
self.tx.send(frame.to_frame())
}
}
/// Hand frames of `frames` to `sink` on a thread of their own, until either
/// side stops ([`ScreenCapture::start_sink`] of backends that only have
/// [`ScreenCapture::start`]).
pub fn forward(mut frames: FrameReceiver<VideoFrame>, mut sink: Box<dyn FrameSink>) -> Result<()> {
std::thread::Builder::new().name("voelin-capture-forward".into()).spawn(move || {
loop {
match frames.recv_timeout(Duration::from_millis(100)) {
Some(frame) => {
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
break;
}
}
None if frames.is_closed() => break,
None => {}
}
}
})?;
Ok(())
}
/// A screen / window capture backend.
pub trait ScreenCapture: Send {
/// Short name for logs (`"x11"`, `"portal"`, ...).
@@ -87,15 +222,38 @@ pub trait ScreenCapture: Send {
/// returns a single [`SourceId::Portal`] entry: its dialog picks.
fn sources(&mut self) -> Result<Vec<CaptureSource>>;
/// Start capturing (stopping a previous capture). Async because the
/// portal asks the user. Frames stop when [`ScreenCapture::stop`] is
/// called, the backend is dropped, or the receiver is dropped.
/// Start capturing (stopping a previous capture), copying every frame
/// into a queue. Async because the portal asks the user. Frames stop
/// when [`ScreenCapture::stop`] is called, the backend is dropped, or the
/// receiver is dropped.
fn start(
&mut self,
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>>;
/// Start capturing into `sink` (stopping a previous capture): the
/// backend calls it on its own thread with the pixels still in the
/// capture buffer, and drops it when the capture ends (stopped, the
/// source went away, or the sink returned `false`). `options.fps` is
/// ignored in favour of [`FrameSink::max_fps`].
///
/// The default forwards the frames of [`ScreenCapture::start`] from a
/// thread of its own.
fn start_sink(
&mut self,
source: &SourceId,
options: &CaptureOptions,
sink: Box<dyn FrameSink>,
) -> BoxFuture<'_, Result<()>> {
let source = source.clone();
let options = CaptureOptions { fps: sink.max_fps(), ..options.clone() };
Box::pin(async move {
let frames = self.start(&source, &options).await?;
forward(frames, sink)
})
}
fn stop(&mut self);
}
@@ -196,6 +354,11 @@ impl Ticker {
Self { interval: Duration::from_secs(1) / fps.max(1), next: Instant::now() }
}
/// Change the rate from the next tick on.
pub fn set_fps(&mut self, fps: u32) {
self.interval = Duration::from_secs(1) / fps.max(1);
}
/// Sleep until the next tick. Returns `false` if `stop` got set.
pub fn wait(&mut self, stop: &AtomicBool) -> bool {
self.next += self.interval;
@@ -232,4 +395,32 @@ mod tests {
worker.stop();
assert!(started.elapsed() < Duration::from_millis(900));
}
fn kept(pacer: &mut FramePacer, source_fps: f64, jitter_ms: f64, seconds: u32) -> usize {
let frames = (source_fps * f64::from(seconds)) as usize;
(0..frames)
.filter(|&n| {
let jitter = if n % 2 == 0 { jitter_ms } else { -jitter_ms };
let t = (n as f64 * 1000.0 / source_fps + jitter).max(0.0);
pacer.take(Duration::from_secs_f64(t / 1000.0))
})
.count()
}
#[test]
fn pacer_caps_the_rate() {
// 60 Hz source, 30 fps cap: every other frame, even with jitter.
assert_eq!(kept(&mut FramePacer::new(Some(30)), 60.0, 1.5, 10), 300);
// 144 Hz to 60: close to 60.
let n = kept(&mut FramePacer::new(Some(60)), 144.0, 0.5, 10);
assert!((580..=610).contains(&n), "{n}");
// A cap above the source rate keeps everything.
assert_eq!(kept(&mut FramePacer::new(Some(120)), 30.0, 2.0, 10), 300);
assert_eq!(kept(&mut FramePacer::new(None), 60.0, 0.0, 1), 60);
// A clock that jumps back starts over.
let mut pacer = FramePacer::new(Some(10));
assert!(pacer.take(Duration::from_secs(100)));
assert!(!pacer.take(Duration::from_millis(100_050)));
assert!(pacer.take(Duration::from_secs(1)));
}
}
+411 -110
View File
@@ -4,24 +4,40 @@
//!
//! The portal can remember the user's choice: pass the token from
//! [`PortalCapture::restore_token`] to [`PortalCapture::with_restore_token`]
//! next time (it persists until the user revokes it). Only shared-memory
//! buffers (`BGRx` / `RGBx` family) are negotiated; DMA-BUF import is a TODO.
//! next time (it persists until the user revokes it).
//!
//! Buffers: LINEAR DMA-BUFs (mapped and read by the CPU, with
//! `DMA_BUF_IOCTL_SYNC` around each read) are offered first, shared memory
//! (`BGRx` / `BGRA` / `RGBx` / `RGBA`) second, so compositors without
//! DMA-BUF support use shared memory. When reading DMA-BUFs turns out slow
//! (buffers in memory the CPU reads uncached, e.g. a discrete GPU's VRAM),
//! the stream switches to shared memory. Tiled DMA-BUFs would need a GPU
//! import and are not offered. Frames go to the [`FrameSink`] while the
//! buffer is dequeued; nothing is copied before conversion. The frame rate
//! follows the sink's cap: the compositor is asked for up to that rate and
//! sends frames when the screen changes.
use std::time::{Duration, Instant};
use ashpd::desktop::PersistMode;
use ashpd::desktop::screencast::{CursorMode, Screencast, SelectSourcesOptions, SourceType};
use pipewire as pw;
use pw::spa::buffer::DataType;
use pw::spa::param::format::{FormatProperties, MediaSubtype, MediaType};
use pw::spa::param::video::{VideoFormat, VideoInfoRaw};
use pw::spa::pod::{Value, object, property};
use pw::spa::utils::{Fraction, Rectangle, SpaTypes};
use pw::spa::pod::{
ChoiceValue, Object, Pod, PodPropFlags, Property, PropertyFlags, Value, property,
};
use pw::spa::utils::{Choice, ChoiceEnum, ChoiceFlags, Fraction, Id, Rectangle, SpaTypes};
use tracing::{debug, warn};
use crate::capture::dmabuf::DmaBufMap;
use crate::capture::pw::{PwThread, pod, serialize};
use crate::capture::{BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId};
use crate::frame::VideoFrame;
use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::capture::{
BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, SourceId,
};
use crate::frame::{FrameRef, PixelsRef, PlaneRef, VideoFrame};
use crate::queue::FrameReceiver;
use crate::{Error, Result};
const BACKEND: &str = "portal";
@@ -49,13 +65,21 @@ struct Session {
/// ScreenCast portal + PipeWire backend (Wayland, also works on X11 desktops
/// that run xdg-desktop-portal).
#[derive(Default)]
pub struct PortalCapture {
restore_token: Option<String>,
dmabuf: bool,
session: Option<Session>,
thread: Option<PwThread>,
}
impl Default for PortalCapture {
fn default() -> Self {
// VOELIN_PORTAL_DMABUF=0 offers shared memory only.
let dmabuf = std::env::var("VOELIN_PORTAL_DMABUF").map_or(true, |v| v != "0");
Self { restore_token: None, dmabuf, session: None, thread: None }
}
}
impl PortalCapture {
pub fn new() -> Self {
Self::default()
@@ -64,7 +88,16 @@ impl PortalCapture {
/// Reuse an earlier choice without asking (a token from
/// [`PortalCapture::restore_token`]).
pub fn with_restore_token(token: Option<String>) -> Self {
Self { restore_token: token, session: None, thread: None }
let mut capture = Self::default();
capture.restore_token = token;
capture
}
/// Offer LINEAR DMA-BUFs (default, unless `VOELIN_PORTAL_DMABUF=0`), or
/// shared memory only.
pub fn with_dmabuf(mut self, enabled: bool) -> Self {
self.dmabuf = enabled;
self
}
/// Token to persist after a successful start; `None` before that or if
@@ -149,6 +182,22 @@ impl ScreenCapture for PortalCapture {
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
let (sink, rx) = QueueSink::new(options);
let started = self.start_sink(source, options, Box::new(sink));
Box::pin(async move {
started.await?;
Ok(rx)
})
}
/// The sink reads the PipeWire buffer itself (shared memory, or a
/// LINEAR DMA-BUF mapped for reading) while the buffer is dequeued.
fn start_sink(
&mut self,
source: &SourceId,
options: &CaptureOptions,
sink: Box<dyn FrameSink>,
) -> BoxFuture<'_, Result<()>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
@@ -157,15 +206,14 @@ impl ScreenCapture for PortalCapture {
}
self.stop();
let (fd, node) = self.open(&options).await?;
let (tx, rx) = frame_channel(options.queue);
let fps = options.fps.max(1);
let dmabuf = self.dmabuf;
let thread =
PwThread::spawn("voelin-portal-capture", Some(fd), move |core, mainloop| {
video_stream(core, mainloop, node, fps, tx)
video_stream(core, mainloop, node, dmabuf, sink)
})
.map_err(|e| Error::Capture { backend: BACKEND, message: e })?;
self.thread = Some(thread);
Ok(rx)
Ok(())
})
}
@@ -190,12 +238,43 @@ impl Drop for PortalCapture {
}
}
/// Pixel formats we take, in order of preference (all 4 bytes per pixel;
/// `x` and `A` are ignored).
const FORMATS: [VideoFormat; 4] =
[VideoFormat::BGRx, VideoFormat::BGRA, VideoFormat::RGBx, VideoFormat::RGBA];
/// DRM_FORMAT_MOD_LINEAR: rows of pixels, readable by the CPU once mapped.
const MODIFIER_LINEAR: i64 = 0;
/// Reading DMA-BUFs slower than this (per pixel, conversion included) means
/// the buffers live in memory the CPU reads uncached (e.g. a discrete GPU's
/// VRAM); shared memory is faster then.
const SLOW_DMABUF_NS_PER_PIXEL: f64 = 6.0;
/// DMA-BUF frames timed before deciding.
const DMABUF_PROBE_FRAMES: u32 = 30;
/// What was negotiated.
#[derive(Clone, Copy, Debug)]
struct Negotiated {
format: VideoFormat,
width: u32,
height: u32,
/// DMA-BUF modifier; `None`: shared memory.
modifier: Option<i64>,
}
struct VideoState {
tx: FrameSender<VideoFrame>,
format: Option<(VideoFormat, u32, u32)>,
sink: Box<dyn FrameSink>,
format: Option<Negotiated>,
started: Instant,
interval: Duration,
last: Option<Instant>,
/// Frame rate the offered formats ask for.
fps: u32,
/// Offer DMA-BUFs.
dmabuf: bool,
/// Mappings of the DMA-BUFs PipeWire cycles through.
maps: Vec<DmaBufMap>,
/// Time spent handing DMA-BUF frames to the sink, and how many.
dmabuf_time: Duration,
dmabuf_frames: u32,
logged: Option<bool>,
mainloop: pw::main_loop::MainLoopWeak,
}
@@ -203,8 +282,8 @@ fn video_stream(
core: &pw::core::CoreRc,
mainloop: &pw::main_loop::MainLoopRc,
node: u32,
fps: u32,
tx: FrameSender<VideoFrame>,
dmabuf: bool,
sink: Box<dyn FrameSink>,
) -> std::result::Result<(pw::stream::StreamRc, pw::stream::StreamListener<VideoState>), String> {
let props = pw::properties::properties! {
*pw::keys::MEDIA_TYPE => "Video",
@@ -213,13 +292,17 @@ fn video_stream(
};
let stream = pw::stream::StreamRc::new(core.clone(), "voelin-screen-capture", props)
.map_err(|e| format!("PipeWire stream: {e}"))?;
let fps = sink.max_fps().max(1);
let state = VideoState {
tx,
sink,
format: None,
started: Instant::now(),
// Accept frames slightly early so rounding does not halve the rate.
interval: Duration::from_secs(1) / fps * 9 / 10,
last: None,
fps,
dmabuf,
maps: Vec::new(),
dmabuf_time: Duration::ZERO,
dmabuf_frames: 0,
logged: None,
mainloop: mainloop.downgrade(),
};
let listener = stream
@@ -236,125 +319,319 @@ fn video_stream(
mainloop.quit();
}
})
.param_changed(|_, state, id, param| {
.param_changed(|stream, state, id, param| {
let Some(param) = param else { return };
if id != pw::spa::param::ParamType::Format.as_raw() {
return;
}
let Ok((MediaType::Video, MediaSubtype::Raw)) =
pw::spa::param::format_utils::parse_format(param)
else {
return;
};
let mut info = VideoInfoRaw::new();
if info.parse(param).is_ok() {
let size = info.size();
debug!(format = ?info.format(), size.width, size.height, "screen capture format");
state.format = Some((info.format(), size.width, size.height));
if let Err(e) = format_changed(stream, state, param) {
warn!("screen capture format: {e}");
}
})
.process(|stream, state| {
let Some(mut buffer) = stream.dequeue_buffer() else { return };
let Some((format, width, height)) = state.format else { return };
let now = Instant::now();
if state.last.is_some_and(|last| now - last < state.interval) {
return;
}
let Some(data) = buffer.datas_mut().first_mut() else { return };
let Some(frame) = copy_frame(data, format, width, height) else { return };
state.last = Some(now);
if !state.tx.send(frame.with_timestamp(now - state.started))
&& let Some(mainloop) = state.mainloop.upgrade()
{
// Nobody receives frames anymore.
mainloop.quit();
}
.remove_buffer(|_, state, _| {
// PipeWire is replacing its buffers: map the new ones.
state.maps.clear();
})
.process(process)
.register()
.map_err(|e| format!("PipeWire listener: {e}"))?;
let format = serialize(Value::Object(object!(
SpaTypes::ObjectParamFormat,
pw::spa::param::ParamType::EnumFormat,
property!(FormatProperties::MediaType, Id, MediaType::Video),
property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw),
property!(
FormatProperties::VideoFormat,
Choice,
Enum,
Id,
VideoFormat::BGRx,
VideoFormat::BGRx,
VideoFormat::BGRA,
VideoFormat::RGBx,
VideoFormat::RGBA
),
property!(
FormatProperties::VideoSize,
Choice,
Range,
Rectangle,
Rectangle { width: 1920, height: 1080 },
Rectangle { width: 1, height: 1 },
Rectangle { width: 8192, height: 8192 }
),
property!(
FormatProperties::VideoFramerate,
Choice,
Range,
Fraction,
Fraction { num: fps, denom: 1 },
Fraction { num: 0, denom: 1 },
Fraction { num: fps, denom: 1 }
),
)))?;
let formats = enum_formats(fps, dmabuf)?;
let mut pods = formats.iter().map(|f| pod(f)).collect::<std::result::Result<Vec<_>, _>>()?;
stream
.connect(
pw::spa::utils::Direction::Input,
Some(node),
pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS,
&mut [pod(&format)?],
&mut pods,
)
.map_err(|e| format!("cannot connect to the screen cast node {node}: {e}"))?;
Ok((stream, listener))
}
/// Copy one shared-memory buffer into a frame. `None` for buffers without
/// mapped data (DMA-BUF), empty or corrupted chunks, and unknown formats.
fn copy_frame(
data: &mut pw::spa::buffer::Data,
format: VideoFormat,
width: u32,
height: u32,
) -> Option<VideoFrame> {
let bgra = match format {
fn size_range() -> Property {
property!(
FormatProperties::VideoSize,
Choice,
Range,
Rectangle,
Rectangle { width: 1920, height: 1080 },
Rectangle { width: 1, height: 1 },
Rectangle { width: 16384, height: 16384 }
)
}
/// Up to `fps`, as the compositor can (it sends frames on damage only).
fn framerate_range(fps: u32) -> Property {
property!(
FormatProperties::VideoFramerate,
Choice,
Range,
Fraction,
Fraction { num: fps, denom: 1 },
Fraction { num: 0, denom: 1 },
Fraction { num: fps, denom: 1 }
)
}
fn modifier_property(fixed: bool) -> Property {
let flags = pw::spa::sys::SPA_POD_PROP_FLAG_MANDATORY
| if fixed { 0 } else { pw::spa::sys::SPA_POD_PROP_FLAG_DONT_FIXATE };
let value = if fixed {
Value::Long(MODIFIER_LINEAR)
} else {
Value::Choice(ChoiceValue::Long(Choice(
ChoiceFlags::empty(),
ChoiceEnum::Enum { default: MODIFIER_LINEAR, alternatives: vec![MODIFIER_LINEAR] },
)))
};
Property {
key: FormatProperties::VideoModifier.as_raw(),
flags: PropertyFlags::from_bits_retain(flags),
value,
}
}
fn format_object(properties: Vec<Property>) -> Value {
Value::Object(Object {
type_: SpaTypes::ObjectParamFormat.as_raw(),
id: pw::spa::param::ParamType::EnumFormat.as_raw(),
properties,
})
}
/// The formats we offer: each pixel format as a LINEAR DMA-BUF (if
/// `dmabuf`), then all of them in shared memory.
fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result<Vec<Vec<u8>>, String> {
let mut formats = Vec::new();
let base = || {
vec![
property!(FormatProperties::MediaType, Id, MediaType::Video),
property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw),
]
};
if dmabuf {
for format in FORMATS {
let mut properties = base();
properties.push(property!(FormatProperties::VideoFormat, Id, format));
properties.push(modifier_property(false));
properties.push(size_range());
properties.push(framerate_range(fps));
formats.push(serialize(format_object(properties))?);
}
}
let mut properties = base();
properties.push(property!(
FormatProperties::VideoFormat,
Choice,
Enum,
Id,
FORMATS[0],
FORMATS[0],
FORMATS[1],
FORMATS[2],
FORMATS[3]
));
properties.push(size_range());
properties.push(framerate_range(fps));
formats.push(serialize(format_object(properties))?);
Ok(formats)
}
/// Offer formats again (another frame rate, or no DMA-BUFs); PipeWire
/// renegotiates.
fn renegotiate(stream: &pw::stream::Stream, fps: u32, dmabuf: bool) {
let result = enum_formats(fps, dmabuf).and_then(|formats| {
let mut pods =
formats.iter().map(|f| pod(f)).collect::<std::result::Result<Vec<_>, _>>()?;
stream.update_params(&mut pods).map_err(|e| e.to_string())
});
if let Err(e) = result {
warn!("cannot renegotiate the screen capture format: {e}");
}
}
fn format_changed(
stream: &pw::stream::Stream,
state: &mut VideoState,
param: &Pod,
) -> std::result::Result<(), String> {
let Ok((MediaType::Video, MediaSubtype::Raw)) =
pw::spa::param::format_utils::parse_format(param)
else {
return Ok(());
};
let mut info = VideoInfoRaw::new();
info.parse(param).map_err(|e| format!("cannot parse the video format: {e}"))?;
let size = info.size();
state.maps.clear();
let modifier = param
.as_object()
.ok()
.and_then(|o| o.find_prop(Id(FormatProperties::VideoModifier.as_raw())));
let modifier = match modifier {
Some(prop) if prop.flags().contains(PodPropFlags::DONT_FIXATE) => {
// The producer left the choice to us; we only take LINEAR.
let mut properties = vec![
property!(FormatProperties::MediaType, Id, MediaType::Video),
property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw),
property!(FormatProperties::VideoFormat, Id, info.format()),
modifier_property(true),
property!(
FormatProperties::VideoSize,
Rectangle,
Rectangle { width: size.width, height: size.height }
),
];
properties.push(framerate_range(state.fps));
let fixed = serialize(format_object(properties))?;
stream.update_params(&mut [pod(&fixed)?]).map_err(|e| e.to_string())?;
return Ok(());
}
Some(prop) => Some(prop.value().get_long().unwrap_or(MODIFIER_LINEAR)),
None => None,
};
debug!(format = ?info.format(), size.width, size.height, ?modifier, "screen capture format");
state.format = Some(Negotiated {
format: info.format(),
width: size.width,
height: size.height,
modifier,
});
let types = if modifier.is_some() {
1 << pw::spa::sys::SPA_DATA_DmaBuf
} else {
(1 << pw::spa::sys::SPA_DATA_MemPtr) | (1 << pw::spa::sys::SPA_DATA_MemFd)
};
let buffers = serialize(Value::Object(Object {
type_: SpaTypes::ObjectParamBuffers.as_raw(),
id: pw::spa::param::ParamType::Buffers.as_raw(),
properties: vec![Property {
key: pw::spa::sys::SPA_PARAM_BUFFERS_dataType,
flags: PropertyFlags::empty(),
value: Value::Int(types as i32),
}],
}))?;
stream.update_params(&mut [pod(&buffers)?]).map_err(|e| e.to_string())
}
fn process(stream: &pw::stream::Stream, state: &mut VideoState) {
// Follow the sink's frame rate: ask the compositor for another rate.
let fps = state.sink.max_fps().max(1);
if fps != state.fps {
state.fps = fps;
renegotiate(stream, fps, state.dmabuf);
}
let Some(mut buffer) = stream.dequeue_buffer() else { return };
let Some(format) = state.format else { return };
if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) {
// Tiled: the CPU cannot read it (we never offer that).
return;
}
let timestamp = state.started.elapsed();
if !state.sink.wants(timestamp) {
// Dropping the buffer queues it back.
return;
}
let Some(data) = buffer.datas_mut().first_mut() else { return };
let bgra = match format.format {
VideoFormat::BGRx | VideoFormat::BGRA => true,
VideoFormat::RGBx | VideoFormat::RGBA => false,
_ => return None,
_ => return,
};
let chunk = data.chunk();
if chunk.size() == 0 || chunk.flags().contains(pw::spa::buffer::ChunkFlags::CORRUPTED) {
return None;
return;
}
let offset = chunk.offset() as usize;
let row = width as usize * 4;
let row = format.width as usize * 4;
let stride = usize::try_from(chunk.stride()).ok().filter(|&s| s >= row).unwrap_or(row);
let bytes = data.data()?;
let bytes = bytes.get(offset..)?;
let needed = stride * (height as usize).checked_sub(1)? + row;
if bytes.len() < needed {
return None;
let needed = offset + stride * (format.height as usize).saturating_sub(1) + row;
fn view(
bytes: &[u8],
at: (usize, usize, bool),
format: Negotiated,
t: Duration,
) -> Option<FrameRef<'_>> {
let (offset, stride, bgra) = at;
let plane = PlaneRef::new(bytes.get(offset..)?, stride);
let pixels = if bgra { PixelsRef::Bgra(plane) } else { PixelsRef::Rgba(plane) };
Some(FrameRef { width: format.width, height: format.height, timestamp: t, pixels })
}
let mut pixels = Vec::with_capacity(row * height as usize);
for y in 0..height as usize {
pixels.extend_from_slice(&bytes[y * stride..y * stride + row]);
let at = (offset, stride, bgra);
let is_dmabuf = data.type_() == DataType::DmaBuf;
if state.logged != Some(is_dmabuf) {
state.logged = Some(is_dmabuf);
debug!(dmabuf = is_dmabuf, "screen capture buffers");
}
let frame = if bgra {
VideoFrame::from_bgra(width, height, row, pixels)
let started = Instant::now();
let more = if is_dmabuf {
let raw = data.as_raw();
let len = (raw.mapoffset + raw.maxsize) as usize;
let fd = data.fd();
if !state.maps.iter().any(|m| m.fd() == fd && m.len() >= len) {
state.maps.retain(|m| m.fd() != fd);
match DmaBufMap::new(fd, len) {
Ok(map) => state.maps.push(map),
Err(e) => {
warn!("cannot map a screen capture DMA-BUF: {e}");
return;
}
}
}
let map = state.maps.iter().find(|m| m.fd() == fd).expect("mapped above");
let base = raw.mapoffset as usize;
map.read(|bytes| {
match bytes
.get(base..)
.filter(|b| b.len() >= needed)
.and_then(|b| view(b, at, format, timestamp))
{
Some(frame) => state.sink.frame(frame),
None => true,
}
})
} else {
VideoFrame::from_rgba(width, height, row, pixels)
match data.data().filter(|b| b.len() >= needed).and_then(|b| view(b, at, format, timestamp))
{
Some(frame) => state.sink.frame(frame),
None => true,
}
};
frame.ok()
if is_dmabuf && state.dmabuf {
probe_dmabuf(stream, state, started.elapsed(), format);
}
if !more && let Some(mainloop) = state.mainloop.upgrade() {
// Nobody takes frames any more.
mainloop.quit();
}
}
/// Time the first DMA-BUF frames; if reading them is slow, offer shared
/// memory only.
fn probe_dmabuf(
stream: &pw::stream::Stream,
state: &mut VideoState,
took: Duration,
format: Negotiated,
) {
if state.dmabuf_frames >= DMABUF_PROBE_FRAMES {
return;
}
state.dmabuf_frames += 1;
state.dmabuf_time += took;
if state.dmabuf_frames < DMABUF_PROBE_FRAMES {
return;
}
let pixels = f64::from(format.width) * f64::from(format.height);
let per_pixel = state.dmabuf_time.as_secs_f64() * 1e9 / f64::from(DMABUF_PROBE_FRAMES) / pixels;
if per_pixel > SLOW_DMABUF_NS_PER_PIXEL {
tracing::info!(
"reading DMA-BUFs takes {per_pixel:.1} ns per pixel; switching screen capture to shared memory"
);
state.dmabuf = false;
renegotiate(stream, state.fps, false);
}
}
#[cfg(test)]
@@ -378,4 +655,28 @@ mod tests {
assert!(!PortalCapture::is_available().await);
assert!(capture.restore_token().is_none());
}
/// The offered formats parse back: DMA-BUF (mandatory LINEAR modifier,
/// left to us to fixate) per pixel format, then shared memory.
#[test]
fn offered_formats() {
let formats = enum_formats(60, true).unwrap();
assert_eq!(formats.len(), FORMATS.len() + 1);
for (i, bytes) in formats.iter().enumerate() {
let object = pod(bytes).unwrap().as_object().unwrap();
let modifier = object.find_prop(Id(FormatProperties::VideoModifier.as_raw()));
if i < FORMATS.len() {
let flags = modifier.expect("a modifier").flags();
assert!(flags.contains(PodPropFlags::MANDATORY | PodPropFlags::DONT_FIXATE));
} else {
assert!(modifier.is_none(), "shared memory has no modifier");
}
}
assert_eq!(enum_formats(30, false).unwrap().len(), 1);
let fixed = serialize(format_object(vec![modifier_property(true)])).unwrap();
let object = pod(&fixed).unwrap().as_object().unwrap();
let prop = object.find_prop(Id(FormatProperties::VideoModifier.as_raw())).unwrap();
assert_eq!(prop.value().get_long().unwrap(), MODIFIER_LINEAR);
assert!(!prop.flags().contains(PodPropFlags::DONT_FIXATE));
}
}
+44 -9
View File
@@ -3,12 +3,13 @@
//! a desktop-like picture, plus a frame counter) and a sine tone.
use std::sync::Arc;
use std::time::Duration;
use std::time::{Duration, Instant};
use crate::capture::{
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Ticker, Worker,
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture,
SourceId, Ticker, Worker,
};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame};
use crate::queue::{FrameReceiver, frame_channel};
use crate::{Error, Result};
@@ -321,24 +322,58 @@ impl ScreenCapture for SyntheticScreen {
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
let (sink, rx) = QueueSink::new(options);
let started = self.start_sink(source, options, Box::new(sink));
Box::pin(async move {
started.await?;
Ok(rx)
})
}
/// Draws frame after frame into one buffer, at [`FrameSink::max_fps`];
/// timestamps are the time since the start.
fn start_sink(
&mut self,
source: &SourceId,
_options: &CaptureOptions,
mut sink: Box<dyn FrameSink>,
) -> BoxFuture<'_, Result<()>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
if source != SourceId::Synthetic {
return Err(Error::SourceNotFound(source));
}
self.stop();
let (tx, rx) = frame_channel(options.queue);
let pattern = self.same_pattern();
let fps = options.fps;
self.worker = Some(Worker::spawn("voelin-synthetic-video", move |stop| {
let (width, height) = (pattern.width, pattern.height);
let mut fps = sink.max_fps();
let mut ticker = Ticker::new(fps);
let mut buffer = Vec::new();
let started = Instant::now();
let mut n = 0;
while tx.send(pattern.frame(n, fps)) && ticker.wait(&stop) {
n += 1;
loop {
let timestamp = started.elapsed();
if sink.wants(timestamp) {
pattern.render(n, &mut buffer);
let plane = PlaneRef::new(&buffer, width as usize * 4);
let frame =
FrameRef { width, height, timestamp, pixels: PixelsRef::Bgra(plane) };
if !sink.frame(frame) {
break;
}
n += 1;
}
if sink.max_fps() != fps {
fps = sink.max_fps();
ticker.set_fps(fps);
}
if !ticker.wait(&stop) {
break;
}
}
})?);
Ok(rx)
Ok(())
})
}
+46 -25
View File
@@ -10,7 +10,7 @@
use std::collections::VecDeque;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use std::time::Instant;
use tracing::warn;
use windows_capture::capture::{CaptureControl, Context, GraphicsCaptureApiHandler};
@@ -24,9 +24,10 @@ use windows_capture::settings::{
use windows_capture::window::Window;
use crate::capture::{
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Worker,
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture,
SourceId, Worker,
};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame};
use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::{Error, Result};
@@ -36,20 +37,20 @@ fn failed(e: impl std::fmt::Display) -> Error {
Error::Capture { backend: BACKEND, message: e.to_string() }
}
/// Receives frames on the capture thread.
/// Receives frames on the capture thread and hands the mapped staging
/// texture (with its row pitch) to the sink.
struct Handler {
tx: FrameSender<VideoFrame>,
sink: Box<dyn FrameSink>,
started: Instant,
scratch: Vec<u8>,
}
impl GraphicsCaptureApiHandler for Handler {
type Flags = (FrameSender<VideoFrame>, Instant);
type Flags = (Box<dyn FrameSink>, Instant);
type Error = String;
fn new(ctx: Context<Self::Flags>) -> std::result::Result<Self, Self::Error> {
let (tx, started) = ctx.flags;
Ok(Self { tx, started, scratch: Vec::new() })
let (sink, started) = ctx.flags;
Ok(Self { sink, started })
}
fn on_frame_arrived(
@@ -57,12 +58,18 @@ impl GraphicsCaptureApiHandler for Handler {
frame: &mut Frame,
control: InternalCaptureControl,
) -> std::result::Result<(), Self::Error> {
let buffer = frame.buffer().map_err(|e| e.to_string())?;
let (w, h) = (buffer.width(), buffer.height());
let pixels = buffer.as_nopadding_buffer(&mut self.scratch).to_vec();
let frame =
VideoFrame::from_bgra(w, h, w as usize * 4, pixels).map_err(|e| e.to_string())?;
if !self.tx.send(frame.with_timestamp(self.started.elapsed())) {
let timestamp = self.started.elapsed();
// Frames come as the screen changes, up to its refresh rate; the
// sink's cap decides before anything is copied off the GPU.
if !self.sink.wants(timestamp) {
return Ok(());
}
let mut buffer = frame.buffer().map_err(|e| e.to_string())?;
let (width, height) = (buffer.width(), buffer.height());
let pitch = buffer.row_pitch() as usize;
let plane = PlaneRef::new(buffer.as_raw_buffer(), pitch);
let frame = FrameRef { width, height, timestamp, pixels: PixelsRef::Bgra(plane) };
if !self.sink.frame(frame) {
control.stop();
}
Ok(())
@@ -84,11 +91,11 @@ impl WindowsCapture {
fn start_item<T>(
item: T,
options: &CaptureOptions,
) -> Result<(CaptureControl<Handler, String>, FrameReceiver<VideoFrame>)>
sink: Box<dyn FrameSink>,
) -> Result<CaptureControl<Handler, String>>
where
T: TryInto<GraphicsCaptureItemType> + Send + 'static,
{
let (tx, rx) = frame_channel(options.queue);
let cursor = if options.cursor {
CursorCaptureSettings::WithCursor
} else {
@@ -99,13 +106,13 @@ where
cursor,
DrawBorderSettings::WithoutBorder,
SecondaryWindowSettings::Default,
MinimumUpdateIntervalSettings::Custom(Duration::from_secs(1) / options.fps.max(1)),
// No minimum: the frame rate can change while capturing.
MinimumUpdateIntervalSettings::Default,
DirtyRegionSettings::Default,
ColorFormat::Bgra8,
(tx, Instant::now()),
(sink, Instant::now()),
);
let control = Handler::start_free_threaded(settings).map_err(failed)?;
Ok((control, rx))
Handler::start_free_threaded(settings).map_err(failed)
}
impl ScreenCapture for WindowsCapture {
@@ -147,27 +154,41 @@ impl ScreenCapture for WindowsCapture {
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
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<dyn FrameSink>,
) -> BoxFuture<'_, Result<()>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
self.stop();
let not_found = || Error::SourceNotFound(source.clone());
let (control, rx) = match source {
let control = match source {
SourceId::Monitor(index) => {
let monitor = Monitor::from_index(index as usize).map_err(|_| not_found())?;
start_item(monitor, &options)?
start_item(monitor, &options, sink)?
}
SourceId::Window(hwnd) => {
let window = Window::from_raw_hwnd(hwnd as usize as *mut std::ffi::c_void);
if !window.is_valid() {
return Err(not_found());
}
start_item(window, &options)?
start_item(window, &options, sink)?
}
_ => return Err(not_found()),
};
self.control = Some(control);
Ok(rx)
Ok(())
})
}
+105 -34
View File
@@ -12,7 +12,7 @@ mod shm;
use std::fmt::Display;
use std::os::fd::OwnedFd;
use std::time::Instant;
use std::time::{Duration, Instant};
use memmap2::MmapMut;
use tracing::{debug, warn};
@@ -26,13 +26,16 @@ use x11rb::protocol::xproto::{
use x11rb::rust_connection::RustConnection;
use crate::capture::{
BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Ticker, Worker,
BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, SourceId,
Ticker, Worker,
};
use crate::frame::VideoFrame;
use crate::queue::{FrameReceiver, frame_channel};
use crate::frame::{FrameRef, PixelsRef, PlaneRef, VideoFrame};
use crate::queue::FrameReceiver;
use crate::{Error, Result};
const BACKEND: &str = "x11";
/// How often the monitor or window position is looked up again.
const REGION_REFRESH: Duration = Duration::from_secs(1);
fn unavailable(e: impl Display) -> Error {
Error::CaptureUnavailable { backend: BACKEND, reason: e.to_string() }
@@ -102,39 +105,88 @@ impl ScreenCapture for X11Capture {
source: &SourceId,
options: &CaptureOptions,
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
let (sink, rx) = QueueSink::new(options);
let started = self.start_sink(source, options, Box::new(sink));
Box::pin(async move {
started.await?;
Ok(rx)
})
}
/// The sink reads the MIT-SHM segment itself (or the GetImage reply);
/// the cursor is blended into it first.
fn start_sink(
&mut self,
source: &SourceId,
options: &CaptureOptions,
mut sink: Box<dyn FrameSink>,
) -> BoxFuture<'_, Result<()>> {
let source = source.clone();
let options = options.clone();
Box::pin(async move {
self.stop();
let x = Display11::connect(self.display.as_deref())?;
// Fail here, not in the thread, if the source does not exist.
x.region(&source)?;
let (tx, rx) = frame_channel(options.queue);
let mut region = x.region(&source)?;
let use_shm = self.use_shm;
self.worker = Some(Worker::spawn("voelin-x11-capture", move |stop| {
let mut grabber = Grabber::new(&x, use_shm);
let cursor = options.cursor && x.xfixes;
let started = Instant::now();
let mut ticker = Ticker::new(options.fps);
let mut fps = sink.max_fps();
let mut ticker = Ticker::new(fps);
let mut region_at = Instant::now();
loop {
match capture(&x, &source, &mut grabber, cursor) {
Ok(frame) => {
if !tx.send(frame.with_timestamp(started.elapsed())) {
break;
let timestamp = started.elapsed();
if sink.wants(timestamp) {
// Monitors and windows move rarely: look them up once a
// second, and again when a grab fails (e.g. a window
// shrank).
if region_at.elapsed() >= REGION_REFRESH {
region_at = Instant::now();
match x.region(&source) {
Ok(r) => region = r,
Err(e) => {
warn!("X11 capture stopped: {e}");
break;
}
}
}
Err(e) => {
let mut result = capture(&x, &region, &mut grabber, cursor);
if result.is_err() {
region_at = Instant::now();
if let Ok(r) = x.region(&source) {
region = r;
result = capture(&x, &region, &mut grabber, cursor);
}
}
if let Err(e) = result {
// E.g. the window was closed: end the stream.
warn!("X11 capture stopped: {e}");
break;
}
let (width, height) = (region.rect.width, region.rect.height);
let plane = PlaneRef::new(grabber.pixels(), usize::from(width) * 4);
let frame = FrameRef {
width: width.into(),
height: height.into(),
timestamp,
pixels: PixelsRef::Bgra(plane),
};
if !sink.frame(frame) {
break;
}
}
if sink.max_fps() != fps {
fps = sink.max_fps();
ticker.set_fps(fps);
}
if !ticker.wait(&stop) {
break;
}
}
})?);
Ok(rx)
Ok(())
})
}
@@ -408,19 +460,28 @@ struct Segment {
struct Grabber {
shm: bool,
segment: Option<Segment>,
/// The last GetImage reply.
image: Vec<u8>,
/// Where the last grab is: the segment (`true`) or `image`, and its
/// length.
last: (bool, usize),
}
impl Grabber {
fn new(x: &Display11, want_shm: bool) -> Self {
Self { shm: want_shm && x.shm, segment: None }
Self { shm: want_shm && x.shm, segment: None, image: Vec::new(), last: (false, 0) }
}
/// Tightly packed BGRx pixels of the region.
fn grab(&mut self, x: &Display11, r: &Region) -> Result<Vec<u8>> {
/// Read the region's pixels (tightly packed BGRx) into the shared memory
/// segment, or with GetImage; [`Grabber::pixels`] has them.
fn grab(&mut self, x: &Display11, r: &Region) -> Result<()> {
let size = usize::from(r.rect.width) * usize::from(r.rect.height) * 4;
if self.shm {
match self.grab_shm(x, r, size) {
Ok(pixels) => return Ok(pixels),
Ok(()) => {
self.last = (true, size);
return Ok(());
}
Err(e) => {
debug!("MIT-SHM capture failed, using GetImage: {e}");
self.shm = false;
@@ -442,15 +503,29 @@ impl Grabber {
.map_err(failed)?
.reply()
.map_err(failed)?;
let mut data = reply.data;
if data.len() < size {
return Err(failed(format!("GetImage returned {} bytes, expected {size}", data.len())));
self.image = reply.data;
if self.image.len() < size {
return Err(failed(format!(
"GetImage returned {} bytes, expected {size}",
self.image.len()
)));
}
data.truncate(size);
Ok(data)
self.last = (false, size);
Ok(())
}
fn grab_shm(&mut self, x: &Display11, r: &Region, size: usize) -> Result<Vec<u8>> {
/// The pixels of the last grab.
fn pixels(&mut self) -> &mut [u8] {
match (self.last, &mut self.segment) {
((true, size), Some(segment)) => &mut segment.map[..size],
((_, size), _) => {
let len = size.min(self.image.len());
&mut self.image[..len]
}
}
}
fn grab_shm(&mut self, x: &Display11, r: &Region, size: usize) -> Result<()> {
if self.segment.as_ref().is_none_or(|s| s.map.len() < size) {
self.release(x);
self.segment = Some(Self::attach(x, size)?);
@@ -471,7 +546,7 @@ impl Grabber {
.map_err(failed)?
.reply()
.map_err(failed)?;
Ok(segment.map[..size].to_vec())
Ok(())
}
fn attach(x: &Display11, size: usize) -> Result<Segment> {
@@ -533,14 +608,10 @@ fn blend_cursor(bgrx: &mut [u8], width: usize, height: usize, cursor: &Cursor<'_
}
}
fn capture(
x: &Display11,
source: &SourceId,
grabber: &mut Grabber,
cursor: bool,
) -> Result<VideoFrame> {
let region = x.region(source)?;
let mut pixels = grabber.grab(x, &region)?;
/// Grab the region and blend the cursor into it; the pixels are then in
/// [`Grabber::pixels`].
fn capture(x: &Display11, region: &Region, grabber: &mut Grabber, cursor: bool) -> Result<()> {
grabber.grab(x, region)?;
let (w, h) = (usize::from(region.rect.width), usize::from(region.rect.height));
if cursor && let Ok(image) = x.conn.xfixes_get_cursor_image().map_err(failed)?.reply() {
let cursor = Cursor {
@@ -551,10 +622,10 @@ fn capture(
argb: &image.cursor_image,
};
if cursor.argb.len() >= cursor.width * cursor.height {
blend_cursor(&mut pixels, w, h, &cursor);
blend_cursor(grabber.pixels(), w, h, &cursor);
}
}
VideoFrame::from_bgra(region.rect.width.into(), region.rect.height.into(), w * 4, pixels)
Ok(())
}
#[cfg(test)]