Merge the faster screen-share pipeline

Capture, conversion and encoding on their own threads with latest-wins
handoffs and frame pools, one encoder per simulcast layer, portal
DMA-BUF, a wlroots capture backend, tuned libvpx, per-stage statistics,
Streamer::reconfigure and voelinctl stream bench. Conflicts: the root
manifest (dimpl patch next to the release profile) and voelinctl's
command list (probe-stream next to the stream tools).

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-28 02:21:24 +00:00
commit 5efec8c568
28 files changed
+5627 -445

No files matched your search

File diff suppressed because it is too large. Load diff
+16 -5
View File
@@ -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
@@ -21,9 +21,12 @@ openh264-download = ["openh264", "dep:reqwest", "dep:bzip2", "dep:sha2"]
av1 = ["dep:dav1d"]
# X11 screen capture (Linux).
x11 = ["dep:x11rb", "dep:memmap2", "dep:rustix"]
# Wayland screen capture (ScreenCast portal + PipeWire) and PipeWire system
# audio (Linux).
pipewire = ["dep:ashpd", "dep:pipewire"]
# 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]
@@ -55,7 +61,12 @@ wasapi = "0.24.0"
windows-capture = "2.0.1"
[dev-dependencies]
criterion = "0.8"
tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "time"] }
[[bench]]
name = "convert"
harness = false
[lints]
workspace = true
+79
View File
@@ -0,0 +1,79 @@
//! Pixel conversion and scaling of screen-sized frames:
//! `cargo bench -p voelin-media --bench convert`.
//!
//! - `to_i420`: the allocating one-thread conversion streams used before
//! - `converter/<n>`: [`Converter`] into a pooled frame on n threads (0: all)
//! - `pyramid`: conversion plus a half and a quarter size layer
//! - `scale/half`, `scale/2-3`: one luma plane, 2x2 box and area averaging
use std::hint::black_box;
use std::sync::Arc;
use std::time::Duration;
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use voelin_media::capture::synthetic::{Pattern, SyntheticScreen};
use voelin_media::convert::{self, Converter};
use voelin_media::pool::FramePool;
use voelin_media::scale::{PlaneScaler, Pyramid};
use voelin_media::workers::Workers;
use voelin_media::{FrameData, VideoFrame};
const SIZES: [(u32, u32); 3] = [(1280, 720), (1920, 1080), (2560, 1440)];
fn source(w: u32, h: u32) -> VideoFrame {
SyntheticScreen::with_pattern(w, h, Pattern::Desktop).frame(1, 30)
}
fn conversion(c: &mut Criterion) {
let mut group = c.benchmark_group("convert");
group.sample_size(30).measurement_time(Duration::from_secs(3));
for (w, h) in SIZES {
let src = source(w, h);
let size = format!("{w}x{h}");
group.throughput(Throughput::Elements(u64::from(w) * u64::from(h)));
group.bench_with_input(BenchmarkId::new("to_i420", &size), &src, |b, src| {
b.iter(|| black_box(convert::to_i420(src).unwrap()));
});
for threads in [1, 0] {
let mut converter = Converter::new(threads);
let mut pool = FramePool::new();
let id = BenchmarkId::new(format!("converter/{}", converter.threads()), &size);
group.bench_with_input(id, &src, |b, src| {
b.iter(|| {
let target = Arc::get_mut(pool.get(w, h)).unwrap();
converter.to_i420_into(&src.view(), target).unwrap();
});
});
}
let mut pyramid = Pyramid::new(0);
let sizes = [(w, h), (w / 2, h / 2), (w / 4, h / 4)];
let mut out = vec![None; 3];
group.bench_with_input(BenchmarkId::new("pyramid/1+1/2+1/4", &size), &src, |b, src| {
b.iter(|| {
pyramid.process(&src.view(), &sizes, &[true; 3], &mut out).unwrap();
out.iter_mut().for_each(|f| drop(f.take()));
});
});
}
group.finish();
}
fn scaling(c: &mut Criterion) {
let mut group = c.benchmark_group("scale");
group.sample_size(30).measurement_time(Duration::from_secs(3));
let mut workers = Workers::new("bench-scale", 0);
let i420 = convert::to_i420(&source(1920, 1080)).unwrap().into_owned();
let FrameData::I420 { y, .. } = &i420.data else { unreachable!() };
for (name, (dw, dh)) in [("half", (960, 540)), ("2-3", (1280, 720))] {
let mut scaler = PlaneScaler::new((1920, 1080), (dw, dh));
let mut out = vec![0; dw * dh];
group.throughput(Throughput::Elements((dw * dh) as u64));
group.bench_function(format!("{name}/1920x1080-luma"), |b| {
b.iter(|| scaler.scale(&mut workers, y.view(), &mut out, dw).unwrap());
});
}
group.finish();
}
criterion_group!(benches, conversion, scaling);
criterion_main!(benches);
+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());
}
}
+201 -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;
@@ -32,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;
@@ -64,7 +73,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 +88,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 +224,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 +356,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 +397,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));
}
}
+306 -41
View File
@@ -1,13 +1,15 @@
//! Synthetic sources for tests and `--synthetic` streaming: an animated test
//! pattern (a rectangle moving over a flat background, plus a frame counter)
//! and a sine tone.
//! Synthetic sources for tests, benchmarks and `--synthetic` streaming: an
//! animated test pattern (a rectangle moving over a flat background, or over
//! a desktop-like picture, plus a frame counter) and a sine tone.
use std::time::Duration;
use std::sync::Arc;
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};
@@ -32,16 +34,224 @@ const DIGITS: [[u8; 5]; 10] = [
[7, 5, 7, 1, 7],
];
/// What the test pattern shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Pattern {
/// A flat background, the moving rectangle and a frame counter: cheap to
/// encode and easy to check after decoding.
#[default]
Simple,
/// Like a desktop with a code editor: a title bar with a gradient, a side
/// bar, lines of coloured text in a document that scrolls three pixels
/// per frame, a status bar, and the moving rectangle and frame counter on
/// top. Costs an encoder about as much as real screen content (for
/// benchmarks).
Desktop,
}
/// A rectangle: `(x, y, width, height)`.
type Rect = (usize, usize, usize, usize);
fn bgra(c: [u8; 3]) -> [u8; 4] {
[c[2], c[1], c[0], 255]
}
/// Fill a rectangle of a BGRA image (`width` pixels per row), clipped.
fn fill(data: &mut [u8], width: usize, rect: Rect, color: [u8; 3]) {
let rows = data.len() / (width * 4).max(1);
let (x0, y0, w, h) = rect;
let x1 = (x0 + w).min(width);
if x0 >= x1 {
return;
}
let px = bgra(color);
for y in y0..(y0 + h).min(rows) {
for d in data[(y * width + x0) * 4..(y * width + x1) * 4].chunks_exact_mut(4) {
d.copy_from_slice(&px);
}
}
}
/// Draw one 3x5 glyph at `scale` pixels per dot.
fn glyph(
data: &mut [u8],
width: usize,
at: (usize, usize),
scale: usize,
bitmap: [u8; 5],
color: [u8; 3],
) {
for (row, bits) in bitmap.iter().enumerate() {
for col in 0..3 {
if bits & (4 >> col) != 0 {
fill(data, width, (at.0 + col * scale, at.1 + row * scale, scale, scale), color);
}
}
}
}
/// Draw the decimal digits of `n`.
fn number(data: &mut [u8], width: usize, at: (usize, usize), scale: usize, n: u64, color: [u8; 3]) {
let mut digits = [0u8; 20];
let (mut rest, mut len) = (n, 0);
loop {
digits[len] = (rest % 10) as u8;
len += 1;
rest /= 10;
if rest == 0 {
break;
}
}
for i in 0..len {
let bitmap = DIGITS[usize::from(digits[len - 1 - i])];
glyph(data, width, (at.0 + i * 4 * scale, at.1), scale, bitmap, color);
}
}
/// A small deterministic generator (xorshift64).
struct Rng(u64);
impl Rng {
fn below(&mut self, n: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % n.max(1) as u64) as usize
}
}
/// Lines of "code" in `area`: words of glyphs in the palette's colours,
/// indented, some lines empty.
fn text_lines(
data: &mut [u8],
width: usize,
area: Rect,
scale: usize,
palette: &[[u8; 3]],
rng: &mut Rng,
) {
let (ax, ay, aw, ah) = area;
let (advance, pitch) = (4 * scale, 8 * scale);
let columns = aw.saturating_sub(2 * advance) / advance;
let mut y = ay + 2 * scale;
while columns > 0 && y + pitch <= ay + ah {
let indent = rng.below(4) * 2;
let end = if rng.below(6) == 0 { 0 } else { indent + 4 + rng.below(columns) };
let mut col = indent;
while col < end.min(columns) {
let word = 2 + rng.below(8);
let color = palette[rng.below(palette.len())];
for _ in 0..word.min(columns - col) {
let x = ax + advance + col * advance;
glyph(data, width, (x, y), scale, DIGITS[rng.below(10)], color);
col += 1;
}
col += 1;
}
y += pitch;
}
}
/// The parts of [`Pattern::Desktop`] that do not change, rendered once: the
/// page, and the document that scrolls through the editor area.
struct Desktop {
page: Vec<u8>,
editor: Rect,
/// `editor.2` pixels wide, twice the editor's height (it wraps around).
document: Vec<u8>,
document_rows: usize,
}
impl Desktop {
fn render(width: usize, height: usize) -> Self {
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
let scale = (height / 540).max(1);
let mut page = vec![0; width * height * 4];
let title = (height / 20).max(4);
let status = (height / 40).max(2);
let side = width / 5;
// Title bar: a vertical gradient with tabs.
for y in 0..title {
let t = y * 255 / title;
let c = [(40 + t / 8) as u8, (60 + t / 6) as u8, (110 + t / 4) as u8];
fill(&mut page, width, (0, y, width, 1), c);
}
for tab in 0..6 {
let tab = (side + tab * width / 8, title / 3, width / 9, title - title / 3);
fill(&mut page, width, tab, [30, 30, 30]);
text_lines(&mut page, width, tab, scale, &[[200, 200, 200]], &mut rng);
}
// Side bar with a file list, status bar.
let sidebar = (0, title, side, height - title - status);
fill(&mut page, width, sidebar, [37, 37, 38]);
let palette = [[204, 204, 204], [150, 150, 150], [230, 200, 120]];
text_lines(&mut page, width, sidebar, scale, &palette, &mut rng);
fill(&mut page, width, (0, height - status, width, status), [0, 122, 204]);
// The editor's document.
let editor = (side, title, width - side, height - title - status);
let document_rows = editor.3 * 2;
let mut document = vec![0; editor.2 * document_rows * 4];
fill(&mut document, editor.2, (0, 0, editor.2, document_rows), [30, 30, 30]);
let palette =
[[212, 212, 212], [86, 156, 214], [206, 145, 120], [106, 153, 85], [197, 134, 192]];
text_lines(
&mut document,
editor.2,
(0, 0, editor.2, document_rows),
scale,
&palette,
&mut rng,
);
Self { page, editor, document, document_rows }
}
/// The page with the document scrolled by `offset` rows.
fn draw(&self, out: &mut [u8], width: usize, offset: usize) {
out[..self.page.len()].copy_from_slice(&self.page);
let (ex, ey, ew, eh) = self.editor;
for row in 0..eh {
let src = (offset + row) % self.document_rows * ew * 4;
let dst = ((ey + row) * width + ex) * 4;
out[dst..dst + ew * 4].copy_from_slice(&self.document[src..src + ew * 4]);
}
}
}
/// The test pattern as a [`ScreenCapture`] backend.
pub struct SyntheticScreen {
width: u32,
height: u32,
pattern: Pattern,
desktop: Option<Arc<Desktop>>,
worker: Option<Worker>,
}
impl SyntheticScreen {
pub fn new(width: u32, height: u32) -> Self {
Self { width: width.max(16), height: height.max(16), worker: None }
Self::with_pattern(width, height, Pattern::Simple)
}
/// A test pattern of another kind.
pub fn with_pattern(width: u32, height: u32, pattern: Pattern) -> Self {
let (width, height) = (width.max(16), height.max(16));
let desktop = (pattern == Pattern::Desktop)
.then(|| Arc::new(Desktop::render(width as usize, height as usize)));
Self { width, height, pattern, desktop, worker: None }
}
pub fn pattern(&self) -> Pattern {
self.pattern
}
/// Another source drawing the same pattern.
fn same_pattern(&self) -> Self {
Self {
width: self.width,
height: self.height,
pattern: self.pattern,
desktop: self.desktop.clone(),
worker: None,
}
}
/// The moving rectangle in frame `n`: `(x, y, width, height)`.
@@ -55,40 +265,38 @@ impl SyntheticScreen {
(x as u32, (self.height - rh) / 2, rw, rh)
}
/// Frame `n` as BGRA, stamped `n / fps` seconds.
pub fn frame(&self, n: u64, fps: u32) -> VideoFrame {
/// Draw frame `n` as BGRA (`width * 4` bytes per row) into `out`, reusing
/// its memory.
pub fn render(&self, n: u64, out: &mut Vec<u8>) {
let (w, h) = (self.width as usize, self.height as usize);
let mut data = vec![0; w * h * 4];
let bgra = |c: [u8; 3]| [c[2], c[1], c[0], 255];
for px in data.chunks_exact_mut(4) {
px.copy_from_slice(&bgra(BACKGROUND));
}
let mut fill = |x0: usize, y0: usize, rw: usize, rh: usize, c: [u8; 3]| {
for y in y0..(y0 + rh).min(h) {
for x in x0..(x0 + rw).min(w) {
data[(y * w + x) * 4..][..4].copy_from_slice(&bgra(c));
out.resize(w * h * 4, 0);
match &self.desktop {
Some(desktop) => desktop.draw(out, w, n as usize * 3),
None => {
// One row, then copies of it.
let px = bgra(BACKGROUND);
for d in out[..w * 4].chunks_exact_mut(4) {
d.copy_from_slice(&px);
}
let (first, rest) = out.split_at_mut(w * 4);
for row in rest.chunks_exact_mut(w * 4) {
row.copy_from_slice(first);
}
}
};
}
let (rx, ry, rw, rh) = self.rect(n);
fill(rx as usize, ry as usize, rw as usize, rh as usize, RECT_COLOR);
fill(out, w, (rx as usize, ry as usize, rw as usize, rh as usize), RECT_COLOR);
// Frame counter in the top-left corner.
let scale = (h / 48).max(1);
for (i, digit) in n.to_string().bytes().enumerate() {
let bitmap = DIGITS[usize::from(digit - b'0')];
let x0 = scale * 2 + i * 4 * scale;
for (row, bits) in bitmap.iter().enumerate() {
for col in 0..3 {
if bits & (4 >> col) != 0 {
let (x, y) = (x0 + col * scale, scale * 2 + row * scale);
fill(x, y, scale, scale, TEXT_COLOR);
}
}
}
}
number(out, w, (scale * 2, scale * 2), scale, n, TEXT_COLOR);
}
/// Frame `n` as BGRA, stamped `n / fps` seconds.
pub fn frame(&self, n: u64, fps: u32) -> VideoFrame {
let mut data = Vec::new();
self.render(n, &mut data);
let timestamp = Duration::from_secs(n) / fps.max(1);
VideoFrame::from_bgra(self.width, self.height, w * 4, data)
VideoFrame::from_bgra(self.width, self.height, self.width as usize * 4, data)
.expect("pattern buffer matches its size")
.with_timestamp(timestamp)
}
@@ -114,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 = SyntheticScreen::new(self.width, self.height);
let fps = options.fps;
let pattern = self.same_pattern();
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(())
})
}
@@ -225,6 +467,29 @@ mod tests {
}
}
#[test]
fn desktop_pattern_scrolls() {
let screen = SyntheticScreen::with_pattern(640, 360, Pattern::Desktop);
assert_eq!(screen.pattern(), Pattern::Desktop);
let (mut a, mut b) = (Vec::new(), Vec::new());
screen.render(1, &mut a);
screen.render(2, &mut b);
assert_eq!(a.len(), 640 * 360 * 4);
// The editor (right of the side bar, below the title bar) scrolled.
let row = |data: &[u8], y: usize| data[(y * 640 + 200) * 4..(y * 640 + 600) * 4].to_vec();
let differs = (40..340).any(|y| row(&a, y) != row(&b, y));
assert!(differs);
// Lots of detail: many distinct colours in the editor.
let mut colours: Vec<&[u8]> = a.chunks_exact(4).collect();
colours.sort_unstable();
colours.dedup();
assert!(colours.len() >= 8, "{} colours", colours.len());
// Rendering reuses the buffer.
let capacity = a.capacity();
screen.render(3, &mut a);
assert_eq!(a.capacity(), capacity);
}
#[test]
fn sine_is_continuous() {
let tone = SineSource::new(1000.0, 0.5);
+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(())
})
}
+679
View File
@@ -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<String>,
description: Option<String>,
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<wl_shm::Format>,
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<String>,
/// 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<wl_registry::WlRegistry, GlobalListContents> for State {
fn event(
_: &mut Self,
_: &wl_registry::WlRegistry,
_: wl_registry::Event,
_: &GlobalListContents,
_: &Connection,
_: &QueueHandle<Self>,
) {
}
}
impl Dispatch<wl_output::WlOutput, usize> for State {
fn event(
state: &mut Self,
_: &wl_output::WlOutput,
event: wl_output::Event,
index: &usize,
_: &Connection,
_: &QueueHandle<Self>,
) {
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<wl_shm::Format>) -> Option<wl_shm::Format> {
match format {
WEnum::Value(f) if FORMATS.iter().any(|(s, _)| *s == f) => Some(f),
_ => None,
}
}
impl Dispatch<zwlr_screencopy_frame_v1::ZwlrScreencopyFrameV1, ()> for State {
fn event(
state: &mut Self,
frame: &zwlr_screencopy_frame_v1::ZwlrScreencopyFrameV1,
event: zwlr_screencopy_frame_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
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<ext_image_copy_capture_session_v1::ExtImageCopyCaptureSessionV1, ()> for State {
fn event(
state: &mut Self,
_: &ext_image_copy_capture_session_v1::ExtImageCopyCaptureSessionV1,
event: ext_image_copy_capture_session_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
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<ext_image_copy_capture_frame_v1::ExtImageCopyCaptureFrameV1, ()> for State {
fn event(
state: &mut Self,
_: &ext_image_copy_capture_frame_v1::ExtImageCopyCaptureFrameV1,
event: ext_image_copy_capture_frame_v1::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
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<State>,
format: wl_shm::Format,
(width, height): (u32, u32),
stride: u32,
) -> Result<Self> {
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<MmapMut> {
// 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: State,
shm: wl_shm::WlShm,
capturer: Capturer,
}
impl Display {
fn connect(socket: Option<&PathBuf>) -> Result<Self> {
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::<State>(&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<Duration>,
done: impl Fn(&Frame) -> bool,
) -> Result<bool> {
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>, 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<PathBuf>,
worker: Option<Worker>,
}
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<PathBuf>) -> 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<Vec<CaptureSource>> {
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<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 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<dyn FrameSink>,
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<ShmBuffer> = None;
// Rows of a y-inverted frame, flipped.
let mut flipped: Vec<u8> = 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(())
}
+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)]
+37 -6
View File
@@ -21,7 +21,8 @@ use openh264::encoder::{
use openh264::formats::{YUVSlices, YUVSource};
use crate::codec::{
Codec, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder,
Codec, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder,
VideoEncoder,
};
use crate::convert;
use crate::frame::{FrameData, Plane, VideoFrame};
@@ -187,11 +188,19 @@ pub struct OpenH264Encoder {
config: EncoderConfig,
profile: H264Profile,
encoder: Option<Encoder>,
/// The last frame's bitstream (reused).
output: Vec<u8>,
}
impl OpenH264Encoder {
fn new(library: OpenH264, config: EncoderConfig) -> Result<Self> {
let mut encoder = Self { library, config, profile: H264Profile::default(), encoder: None };
let mut encoder = Self {
library,
config,
profile: H264Profile::default(),
encoder: None,
output: Vec::new(),
};
encoder.encoder = Some(encoder.create()?);
Ok(encoder)
}
@@ -244,6 +253,24 @@ impl VideoEncoder for OpenH264Encoder {
}
fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result<Vec<EncodedFrame>> {
let mut frames = Vec::new();
self.encode_with(frame, force_keyframe, &mut |f| {
frames.push(EncodedFrame {
data: f.data.to_vec(),
keyframe: f.keyframe,
pts_90khz: f.pts_90khz,
});
})?;
Ok(frames)
}
/// Writes the NAL units into a buffer kept across frames.
fn encode_with(
&mut self,
frame: &VideoFrame,
force_keyframe: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
let i420 = convert::to_i420(frame)?;
let FrameData::I420 { y, u, v } = &i420.data else {
unreachable!("to_i420 returns I420");
@@ -263,11 +290,15 @@ impl VideoEncoder for OpenH264Encoder {
Err(e) => return Err(Error::Encoder { codec: Codec::H264, message: e.to_string() }),
};
let keyframe = matches!(bitstream.frame_type(), FrameType::IDR | FrameType::I);
let data = bitstream.to_vec();
if data.is_empty() || matches!(bitstream.frame_type(), FrameType::Skip) {
return Ok(Vec::new());
if matches!(bitstream.frame_type(), FrameType::Skip) {
return Ok(());
}
Ok(vec![EncodedFrame { data, keyframe, pts_90khz: i420.pts_90khz() }])
self.output.clear();
bitstream.write_vec(&mut self.output);
if !self.output.is_empty() {
out(EncodedChunk { data: &self.output, keyframe, pts_90khz: i420.pts_90khz() });
}
Ok(())
}
/// The `openh264` crate has no safe way to change the bitrate of a
+65 -16
View File
@@ -126,8 +126,13 @@ pub struct EncoderConfig {
/// start and on request (PLI), like WebRTC.
pub keyframe_interval: Option<u32>,
pub content: ContentHint,
/// Encoder threads; 0 picks a number from the resolution and CPU count.
/// Most encoder threads (still no more than the frame size can use); 0:
/// all CPUs but one ([`encoder_cpus`]).
pub threads: u32,
/// A fixed speed / quality trade-off in the backend's own terms (libvpx
/// `cpu-used`); `None` lets the encoder adapt it to how long frames take
/// to encode compared to the frame interval.
pub speed: Option<i32>,
}
impl Default for EncoderConfig {
@@ -138,30 +143,46 @@ impl Default for EncoderConfig {
keyframe_interval: None,
content: ContentHint::Screen,
threads: 0,
speed: None,
}
}
}
/// CPUs encoders use by default: all but one (at least one). libvpx's
/// threads wait on each other by spinning, so an encode that wants every
/// core slows down many times over as soon as anything else runs (the
/// capture and conversion of the next frame, another layer, the desktop);
/// measured on a 4-core machine: 130-290 ms per 1080p frame with 4 threads
/// under load, against 9-17 ms with 3.
pub fn encoder_cpus() -> u32 {
let cpus = std::thread::available_parallelism().map_or(1, |n| n.get() as u32);
cpus.saturating_sub(1).max(1)
}
impl EncoderConfig {
/// Threads for a `width` x `height` encode (libwebrtc's heuristic).
/// Threads for a `width` x `height` encode: [`threads`](Self::threads)
/// (or [`encoder_cpus`]), but no more than one per 320x240 pixels: more
/// would idle on small frames and cost quality (VP8 token partitions).
pub fn threads_for(&self, width: u32, height: u32) -> u32 {
if self.threads > 0 {
return self.threads;
}
let cpus = std::thread::available_parallelism().map_or(1, |n| n.get() as u32);
let pixels = width * height;
if pixels >= 1920 * 1080 && cpus > 8 {
8
} else if pixels >= 1280 * 720 && cpus > 3 {
4
} else if pixels >= 640 * 480 && cpus > 2 {
2
} else {
1
}
let cpus = match self.threads {
0 => encoder_cpus(),
n => n,
};
let useful = (u64::from(width) * u64::from(height) / (320 * 240)).clamp(1, 64) as u32;
cpus.min(useful)
}
}
/// An encoded frame borrowed from the encoder (see
/// [`VideoEncoder::encode_with`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EncodedChunk<'a> {
pub data: &'a [u8],
pub keyframe: bool,
/// Presentation time on the 90 kHz RTP clock.
pub pts_90khz: u64,
}
/// One encoded frame, ready for `voelin_stream::Peer::write`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncodedFrame {
@@ -183,8 +204,35 @@ pub trait VideoEncoder: Send {
/// encoder skipped it (rate control), usually one.
fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result<Vec<EncodedFrame>>;
/// Like [`encode`](Self::encode), but hands each encoded frame to `out`
/// borrowed from the encoder's own buffer, so nothing is allocated or
/// copied here (libvpx does this; the default goes through `encode`).
fn encode_with(
&mut self,
frame: &VideoFrame,
force_keyframe: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
for f in self.encode(frame, force_keyframe)? {
out(EncodedChunk { data: &f.data, keyframe: f.keyframe, pts_90khz: f.pts_90khz });
}
Ok(())
}
/// Change the target bitrate (bits per second).
fn set_bitrate(&mut self, bps: u32) -> Result<()>;
/// Change the expected frame rate (rate control and speed decisions);
/// ignored by encoders that follow the frame timestamps anyway.
fn set_fps(&mut self, fps: u32) -> Result<()> {
let _ = fps;
Ok(())
}
/// The current speed setting, for statistics (libvpx `cpu-used`).
fn speed(&self) -> Option<i32> {
None
}
}
/// A video decoder.
@@ -461,6 +509,7 @@ mod tests {
fn thread_heuristic() {
let config = EncoderConfig { threads: 3, ..EncoderConfig::default() };
assert_eq!(config.threads_for(1920, 1080), 3);
assert_eq!(config.threads_for(320, 240), 1, "capped by the frame size");
assert_eq!(EncoderConfig::default().threads_for(320, 240), 1);
}
}
+240 -20
View File
@@ -1,13 +1,20 @@
//! VP8 and VP9 through the system libvpx.
//!
//! Encoder settings follow libwebrtc's realtime configuration: one pass CBR,
//! no lag, error resilient, fixed high speed (`cpu-used` 8), keyframes on
//! request, and screen-content tuning for [`ContentHint::Screen`].
//! no lag (`VPX_DL_REALTIME`), error resilient, keyframes only on request,
//! and screen-content tuning for [`ContentHint::Screen`]
//! (`VP8E_SET_SCREEN_CONTENT_MODE`, `VP9E_SET_TUNE_CONTENT`, static
//! threshold). Threads default to the CPUs the frame size can use; VP8 gets
//! as many token partitions, VP9 row multithreading and tile columns by
//! width. `cpu-used` adapts to the measured encode time (see
//! [`SpeedControl`]) unless [`EncoderConfig::speed`] fixes it. Bitrate
//! changes apply to the running encoder, without a keyframe.
use std::time::Duration;
use std::time::{Duration, Instant};
use crate::codec::{
Codec, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder,
Codec, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder,
VideoEncoder,
};
use crate::convert;
use crate::frame::{FrameData, Plane, VIDEO_CLOCK_RATE, VideoFrame};
@@ -38,18 +45,117 @@ pub fn libvpx_version() -> String {
raw::version()
}
/// Speed levels (bigger is faster): VP8 `cpu-used` is minus the level (a
/// fixed speed), VP9's is the level (realtime mode).
struct Levels {
slowest: i32,
fastest: i32,
/// Where adapting starts: fast, so the first seconds do not fall behind.
start: i32,
}
// On screen content (a probe with the desktop test pattern), VP8 levels
// above 10 were no faster, only about 3 dB worse, and levels below 6 about
// ten times slower for under 1 dB.
const VP8_LEVELS: Levels = Levels { slowest: 6, fastest: 10, start: 10 };
const VP9_LEVELS: Levels = Levels { slowest: 5, fastest: 9, start: 8 };
/// Adapts the speed level to how long frames take to encode compared to
/// the frame interval (keyframes excluded: they are always slow):
/// - faster at once when a single frame took more than the whole interval,
/// and when the running mean is above 75 % of it;
/// - slower (better quality) only when the mean stayed below 35 % for a
/// while: 15 frames, doubling (up to 16x) each time a slower level had to
/// be undone, so it does not oscillate around a level that is too slow.
pub struct SpeedControl {
level: i32,
slowest: i32,
fastest: i32,
/// Mean encode time in seconds.
mean: f64,
frames: u32,
/// Frames the mean must stay low before going slower.
patience: u32,
/// The last change went slower.
slowed: bool,
}
impl SpeedControl {
const WINDOW: u32 = 15;
const TOO_SLOW: f64 = 0.75;
const TOO_FAST: f64 = 0.35;
fn new(levels: &Levels) -> Self {
Self {
level: levels.start,
slowest: levels.slowest,
fastest: levels.fastest,
mean: 0.0,
frames: 0,
patience: Self::WINDOW,
slowed: false,
}
}
pub fn level(&self) -> i32 {
self.level
}
/// Account one encode; returns the new level if it changed.
pub fn update(&mut self, took: Duration, interval: Duration) -> Option<i32> {
if interval.is_zero() {
return None;
}
let took = took.as_secs_f64();
self.mean = if self.frames == 0 { took } else { self.mean * 0.8 + took * 0.2 };
self.frames += 1;
let budget = interval.as_secs_f64();
let load = self.mean / budget;
let faster = took > budget || (self.frames >= Self::WINDOW && load > Self::TOO_SLOW);
let level = if faster {
if self.slowed {
// Going slower was a mistake: wait longer next time.
self.patience = (self.patience * 2).min(Self::WINDOW * 16);
}
(self.level + 1).min(self.fastest)
} else if self.frames >= self.patience && load < Self::TOO_FAST {
(self.level - 1).max(self.slowest)
} else {
self.level
};
if level == self.level {
return None;
}
self.slowed = level < self.level;
self.level = level;
self.frames = 0;
Some(level)
}
}
/// libvpx VP8 / VP9 encoder.
pub struct VpxEncoder {
codec: Codec,
config: EncoderConfig,
encoder: Option<raw::Encoder>,
last_pts: Option<i64>,
speed: SpeedControl,
}
impl VpxEncoder {
pub fn new(codec: Codec, config: EncoderConfig) -> Result<Self> {
check(codec, true)?;
Ok(Self { codec, config, encoder: None, last_pts: None })
let levels = if codec == Codec::Vp9 { &VP9_LEVELS } else { &VP8_LEVELS };
Ok(Self { codec, config, encoder: None, last_pts: None, speed: SpeedControl::new(levels) })
}
/// The libvpx `cpu-used` value in use.
pub fn cpu_used(&self) -> i32 {
match (self.config.speed, self.codec) {
(Some(speed), _) => speed,
(None, Codec::Vp9) => self.speed.level(),
(None, _) => -self.speed.level(),
}
}
fn error(&self, message: String) -> Error {
@@ -69,6 +175,7 @@ impl VpxEncoder {
keyframe_interval: self.config.keyframe_interval,
screen: self.config.content == ContentHint::Screen,
threads: self.config.threads_for(width, height),
speed: self.cpu_used(),
};
let encoder = raw::Encoder::new(&params).map_err(|e| self.error(e))?;
self.encoder = Some(encoder);
@@ -87,19 +194,47 @@ impl VideoEncoder for VpxEncoder {
}
fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result<Vec<EncodedFrame>> {
let mut frames = Vec::new();
self.encode_with(frame, force_keyframe, &mut |f| {
frames.push(EncodedFrame {
data: f.data.to_vec(),
keyframe: f.keyframe,
pts_90khz: f.pts_90khz,
});
})?;
Ok(frames)
}
/// Encodes straight from the frame's planes (I420 frames are not
/// copied) and hands out libvpx's own output buffer.
fn encode_with(
&mut self,
frame: &VideoFrame,
force_keyframe: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
let i420 = convert::to_i420(frame)?;
let FrameData::I420 { y, u, v } = &i420.data else {
unreachable!("to_i420 returns I420");
};
// libvpx needs strictly increasing timestamps.
// libvpx needs strictly increasing timestamps. The duration of a
// frame, from which CBR rate control budgets its bits, is the time
// since the previous one (a variable frame rate), but at least 3/4
// of the nominal interval: a frame whose timestamp had to be bumped
// (e.g. after a keyframe re-sent while the screen was still) would
// otherwise get almost no bits and come out as a smear.
let interval = VIDEO_CLOCK_RATE / u64::from(self.config.fps.max(1));
let mut pts = i420.pts_90khz() as i64;
if let Some(last) = self.last_pts
&& pts <= last
{
pts = last + 1;
}
let elapsed = match self.last_pts {
Some(last) if pts <= last => {
pts = last + 1;
0
}
Some(last) => (pts - last) as u64,
None => interval,
};
let duration = elapsed.clamp(interval * 3 / 4, VIDEO_CLOCK_RATE);
self.last_pts = Some(pts);
let duration = VIDEO_CLOCK_RATE / u64::from(self.config.fps.max(1));
let image = raw::I420 {
width: i420.width,
height: i420.height,
@@ -110,15 +245,40 @@ impl VideoEncoder for VpxEncoder {
uv_stride: u.stride,
};
let codec = self.codec;
let encoder = self.ensure_encoder(i420.width, i420.height)?;
let packets = encoder
.encode(&image, pts, duration, force_keyframe)
self.ensure_encoder(i420.width, i420.height)?;
let encoder = self.encoder.as_mut().expect("created above");
let started = Instant::now();
let mut keyframe = force_keyframe;
encoder
.encode(&image, pts, duration, force_keyframe, &mut |p| {
keyframe |= p.keyframe;
if !p.data.is_empty() {
out(EncodedChunk {
data: p.data,
keyframe: p.keyframe,
pts_90khz: p.pts as u64,
});
}
})
.map_err(|message| Error::Encoder { codec, message })?;
Ok(packets
.into_iter()
.filter(|p| !p.data.is_empty())
.map(|p| EncodedFrame { data: p.data, keyframe: p.keyframe, pts_90khz: p.pts as u64 })
.collect())
if self.config.speed.is_none() && !keyframe {
let budget = Duration::from_secs(1) / self.config.fps.max(1);
if let Some(level) = self.speed.update(started.elapsed(), budget) {
let cpu_used = if codec == Codec::Vp9 { level } else { -level };
tracing::debug!(%codec, cpu_used, "encoder speed");
encoder.set_speed(cpu_used).map_err(|message| Error::Encoder { codec, message })?;
}
}
Ok(())
}
fn set_fps(&mut self, fps: u32) -> Result<()> {
self.config.fps = fps.max(1);
Ok(())
}
fn speed(&self) -> Option<i32> {
Some(self.cpu_used())
}
fn set_bitrate(&mut self, bps: u32) -> Result<()> {
@@ -243,6 +403,66 @@ mod tests {
assert!(!encoder.encode(&frame(3, 97, 55), false).unwrap()[0].keyframe);
}
#[test]
fn speed_follows_the_encode_time() {
let mut control = SpeedControl::new(&VP8_LEVELS);
let interval = Duration::from_millis(33);
// Fast encodes: slower levels (better quality) down to the slowest.
let mut changes = Vec::new();
for _ in 0..500 {
changes.extend(control.update(Duration::from_millis(2), interval));
}
assert_eq!(control.level(), VP8_LEVELS.slowest);
assert!(changes.windows(2).all(|w| w[1] == w[0] - 1), "{changes:?}");
// Slow encodes: faster again.
for _ in 0..500 {
control.update(Duration::from_millis(30), interval);
}
assert_eq!(control.level(), VP8_LEVELS.fastest);
// One frame over the budget: faster at once.
let mut control = SpeedControl::new(&VP9_LEVELS);
assert_eq!(control.update(Duration::from_millis(40), interval), Some(9));
// A slower level that turns out too slow makes the next try wait.
let mut control = SpeedControl::new(&VP8_LEVELS);
let mut n = 0;
while control.update(Duration::from_millis(2), interval).is_none() {
n += 1;
}
assert_eq!((n, control.level()), (14, 9));
assert_eq!(control.update(Duration::from_millis(40), interval), Some(10));
let mut n = 0;
while control.update(Duration::from_millis(2), interval).is_none() {
n += 1;
}
assert_eq!(n, 29, "patience doubled");
// In between: stays.
let level = control.level();
for _ in 0..100 {
assert!(
control.update(Duration::from_millis(18), interval).is_none()
|| level != control.level()
);
}
}
#[test]
fn borrowed_output_and_fixed_speed() {
let config = EncoderConfig { speed: Some(-6), ..EncoderConfig::default() };
let mut encoder = VpxEncoder::new(Codec::Vp8, config).unwrap();
assert_eq!(encoder.speed(), Some(-6));
let mut sizes = Vec::new();
for n in 0..3 {
encoder
.encode_with(&frame(n, 64, 48), false, &mut |f| {
sizes.push((f.data.len(), f.keyframe))
})
.unwrap();
}
assert_eq!(sizes.len(), 3);
assert!(sizes[0].1 && !sizes[1].1);
assert_eq!(VpxEncoder::new(Codec::Vp9, EncoderConfig::default()).unwrap().speed(), Some(8));
}
#[test]
fn garbage_is_an_error() {
let mut decoder = VpxDecoder::new(Codec::Vp8).unwrap();
+40 -22
View File
@@ -15,11 +15,6 @@ use vpx_sys as ffi;
pub(super) type RawResult<T> = std::result::Result<T, String>;
/// Speed for realtime encoding. VP8: negative means a fixed speed (a
/// positive value would let libvpx pick one from a CPU budget).
const VP8_CPU_USED: c_int = -8;
const VP9_CPU_USED: c_int = 8;
fn iface(vp9: bool, encoder: bool) -> *const ffi::vpx_codec_iface {
// SAFETY: these return pointers to static interface tables (or NULL if
// libvpx was built without that codec); no arguments.
@@ -109,14 +104,21 @@ pub(super) struct EncoderParams {
pub keyframe_interval: Option<u32>,
pub screen: bool,
pub threads: u32,
/// `cpu-used`: VP8 -16 (fastest) to -4 as a fixed speed (negative), VP9
/// 5 to 9 in realtime mode.
pub speed: i32,
}
pub(super) struct Packet {
pub data: Vec<u8>,
/// An encoded frame, borrowed from libvpx until the next call.
pub(super) struct Packet<'a> {
pub data: &'a [u8],
pub keyframe: bool,
pub pts: i64,
}
/// Longest keyframe distance libvpx is given with keyframes on request only.
const NO_KEYFRAMES: u32 = 1 << 30;
/// An initialised encoder context.
pub(super) struct Encoder {
// Boxed: libvpx keeps pointers to the context and the configuration.
@@ -164,7 +166,11 @@ impl Encoder {
cfg.kf_min_dist = 0;
cfg.kf_max_dist = n.max(1);
}
None => cfg.kf_mode = ffi::vpx_kf_mode::VPX_KF_DISABLED,
None => {
// Keyframes only when forced (a viewer asks for one).
cfg.kf_mode = ffi::vpx_kf_mode::VPX_KF_DISABLED;
cfg.kf_max_dist = NO_KEYFRAMES;
}
}
// SAFETY: zeroed context as libvpx expects before init.
@@ -184,10 +190,14 @@ impl Encoder {
})?;
let mut encoder = Self { ctx, cfg };
encoder.set_speed(p.speed)?;
// log2 of the thread count, for splitting the frame.
let log2_threads = 31 - p.threads.max(1).leading_zeros();
if p.vp9 {
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_CPUUSED, VP9_CPU_USED)?;
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_ROW_MT, 1)?;
let tiles = (31 - p.threads.max(1).leading_zeros()) as c_int;
// Tiles are at least 256 pixels wide.
let max_tiles = 31 - (p.width / 256).max(1).leading_zeros();
let tiles = log2_threads.min(max_tiles) as c_int;
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_TILE_COLUMNS, tiles)?;
// Cyclic refresh: realtime adaptive quantisation.
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_AQ_MODE, 3)?;
@@ -197,7 +207,9 @@ impl Encoder {
encoder.control(ffi::vp8e_enc_control_id::VP9E_SET_TUNE_CONTENT, screen)?;
}
} else {
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_CPUUSED, VP8_CPU_USED)?;
// Token partitions (1, 2, 4 or 8) let decoders use threads too.
let partitions = log2_threads.min(3) as c_int;
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_TOKEN_PARTITIONS, partitions)?;
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_NOISE_SENSITIVITY, 0)?;
if p.screen {
encoder.control(ffi::vp8e_enc_control_id::VP8E_SET_SCREEN_CONTENT_MODE, 1)?;
@@ -220,6 +232,11 @@ impl Encoder {
check(Some(&self.ctx), err).map_err(|e| format!("control {id:?}: {e}"))
}
/// Change `cpu-used` of the running encoder (see [`EncoderParams::speed`]).
pub fn set_speed(&mut self, speed: i32) -> RawResult<()> {
self.control(ffi::vp8e_enc_control_id::VP8E_SET_CPUUSED, speed as c_int)
}
/// Change the target bitrate of the running encoder.
pub fn set_bitrate(&mut self, kbps: u32) -> RawResult<()> {
self.cfg.rc_target_bitrate = kbps.max(1);
@@ -233,14 +250,16 @@ impl Encoder {
(self.cfg.g_w, self.cfg.g_h)
}
/// Encode one frame (pts and duration in 1/90000 s).
/// Encode one frame (pts and duration in 1/90000 s); `out` gets the
/// encoded frames, borrowed from libvpx.
pub fn encode(
&mut self,
img: &I420<'_>,
pts: i64,
duration: u64,
keyframe: bool,
) -> RawResult<Vec<Packet>> {
out: &mut dyn FnMut(Packet<'_>),
) -> RawResult<()> {
img.check()?;
if (img.width, img.height) != self.size() {
return Err("frame size differs from the encoder size".into());
@@ -287,16 +306,16 @@ impl Encoder {
)
};
check(Some(&self.ctx), err)?;
Ok(self.drain())
self.drain(out);
Ok(())
}
fn drain(&mut self) -> Vec<Packet> {
let mut packets = Vec::new();
fn drain(&mut self, out: &mut dyn FnMut(Packet<'_>)) {
let mut iter: ffi::vpx_codec_iter_t = ptr::null();
loop {
// SAFETY: iterates the packets of the last encode call; each
// packet and its buffer stay valid until the next libvpx call on
// this context, and are copied before that.
// this context, which `out` cannot make (it has no access to it).
let pkt = unsafe { ffi::vpx_codec_get_cx_data(&mut *self.ctx, &mut iter) };
if pkt.is_null() {
break;
@@ -307,18 +326,17 @@ impl Encoder {
}
// SAFETY: `frame` is the active union member for frame packets.
let frame = unsafe { pkt.data.frame };
let data = if frame.buf.is_null() || frame.sz == 0 {
Vec::new()
let data: &[u8] = if frame.buf.is_null() || frame.sz == 0 {
&[]
} else {
unsafe { std::slice::from_raw_parts(frame.buf.cast::<u8>(), frame.sz) }.to_vec()
unsafe { std::slice::from_raw_parts(frame.buf.cast::<u8>(), frame.sz) }
};
packets.push(Packet {
out(Packet {
data,
keyframe: frame.flags & ffi::VPX_FRAME_IS_KEY != 0,
pts: frame.pts,
});
}
packets
}
}
+189 -2
View File
@@ -1,17 +1,24 @@
//! Pixel format conversion through `yuv` (yuvutils-rs).
//! Pixel format conversion through `yuv` (yuvutils-rs, SIMD: AVX2 / SSE4.1
//! / NEON picked at runtime).
//!
//! All YUV data uses BT.601 limited range: WebRTC endpoints assume it for VP8,
//! VP9 and H.264 unless the stream signals something else, and libwebrtc's
//! capture pipeline produces it.
//!
//! [`Converter`] is the streaming path: it converts a borrowed frame (e.g. a
//! mapped capture buffer, any stride) straight into a preallocated I420
//! frame, in bands of rows on all cores, without allocating.
use std::borrow::Cow;
use std::sync::{Mutex, PoisonError};
use yuv::{
BufferStoreMut, YuvBiPlanarImage, YuvConversionMode, YuvPlanarImage, YuvPlanarImageMut,
YuvRange, YuvStandardMatrix,
};
use crate::frame::{FrameData, Plane, VideoFrame, chroma_size};
use crate::frame::{FrameData, FrameRef, PixelsRef, Plane, VideoFrame, chroma_size};
use crate::workers::{Slots, Workers};
use crate::{Error, Result};
const RANGE: YuvRange = YuvRange::Limited;
@@ -164,6 +171,186 @@ fn repack(plane: &Plane, width: usize, rows: usize) -> Plane {
out
}
/// Rows `r0 .. r0 + rows` of an I420 destination (`r0` even).
struct Band<'a> {
y: &'a mut [u8],
u: &'a mut [u8],
v: &'a mut [u8],
y_stride: usize,
u_stride: usize,
v_stride: usize,
width: usize,
r0: usize,
rows: usize,
}
impl Band<'_> {
/// Rows `from ..` of this band (`from` even).
fn skip(&mut self, from: usize) -> Band<'_> {
Band {
y: &mut self.y[from * self.y_stride..],
u: &mut self.u[from / 2 * self.u_stride..],
v: &mut self.v[from / 2 * self.v_stride..],
y_stride: self.y_stride,
u_stride: self.u_stride,
v_stride: self.v_stride,
width: self.width,
r0: self.r0 + from,
rows: self.rows - from,
}
}
/// Convert `rows` rows of packed pixels (`src` starts at the band's
/// first row) with yuv's SIMD code.
fn packed(&mut self, bgra: bool, src: &[u8], stride: usize, rows: usize) -> Result<()> {
let mut image = YuvPlanarImageMut {
y_plane: BufferStoreMut::Borrowed(&mut *self.y),
y_stride: stride_u32(self.y_stride)?,
u_plane: BufferStoreMut::Borrowed(&mut *self.u),
u_stride: stride_u32(self.u_stride)?,
v_plane: BufferStoreMut::Borrowed(&mut *self.v),
v_stride: stride_u32(self.v_stride)?,
width: self.width as u32,
height: rows as u32,
};
let convert = if bgra { yuv::bgra_to_yuv420 } else { yuv::rgba_to_yuv420 };
convert(&mut image, src, stride_u32(stride)?, RANGE, MATRIX, mode()).map_err(error)
}
}
/// Convert one band of `src` into `band`. `tail` is scratch memory for a
/// last row pair that is not padded to the stride.
fn convert_band(src: &PixelsRef<'_>, mut band: Band<'_>, tail: &Mutex<Vec<u8>>) -> Result<()> {
let (w, r0, rows) = (band.width, band.r0, band.rows);
let (c0, crows) = (r0 / 2, rows.div_ceil(2));
let cw = w.div_ceil(2);
match *src {
PixelsRef::Bgra(p) | PixelsRef::Rgba(p) => {
let bgra = matches!(src, PixelsRef::Bgra(_));
let data = &p.data[r0 * p.stride..];
let padded = rows * p.stride;
// yuv converts pairs of rows in `2 * stride` chunks, so it would
// skip a final pair whose last row ends before the stride does
// (a buffer without padding after the last row). An odd last
// row is converted on its own and needs no padding.
if data.len() >= padded || rows % 2 == 1 {
band.packed(bgra, &data[..data.len().min(padded)], p.stride, rows)
} else {
let head = rows - 2;
if head > 0 {
band.packed(bgra, &data[..head * p.stride], p.stride, head)?;
}
let mut copy = tail.lock().unwrap_or_else(PoisonError::into_inner);
copy.clear();
copy.extend_from_slice(&data[head * p.stride..][..w * 4]);
copy.extend_from_slice(&data[(head + 1) * p.stride..][..w * 4]);
band.skip(head).packed(bgra, &copy, w * 4, 2)
}
}
PixelsRef::I420 { y, u, v } => {
for r in 0..rows {
band.y[r * band.y_stride..][..w].copy_from_slice(y.row(r0 + r, w));
}
for r in 0..crows {
band.u[r * band.u_stride..][..cw].copy_from_slice(u.row(c0 + r, cw));
band.v[r * band.v_stride..][..cw].copy_from_slice(v.row(c0 + r, cw));
}
Ok(())
}
PixelsRef::Nv12 { y, uv } => {
for r in 0..rows {
band.y[r * band.y_stride..][..w].copy_from_slice(y.row(r0 + r, w));
}
for r in 0..crows {
let src = uv.row(c0 + r, cw * 2);
let u_row = &mut band.u[r * band.u_stride..][..cw];
let v_row = &mut band.v[r * band.v_stride..][..cw];
for ((pair, u), v) in src.chunks_exact(2).zip(u_row).zip(v_row) {
*u = pair[0];
*v = pair[1];
}
}
Ok(())
}
}
}
/// Converts borrowed frames of any format (any stride) into I420 frames the
/// caller provides, in bands of rows on a [`Workers`] pool. Allocates nothing
/// per frame.
pub struct Converter {
workers: Workers,
tail: Mutex<Vec<u8>>,
}
impl Converter {
/// `threads` as in [`Workers::new`] (0: one per CPU).
pub fn new(threads: usize) -> Self {
Self { workers: Workers::new("voelin-convert", threads), tail: Mutex::new(Vec::new()) }
}
/// The thread pool, for other per-frame work (e.g. scaling).
pub fn workers(&mut self) -> &mut Workers {
&mut self.workers
}
/// Threads that convert, the caller included.
pub fn threads(&self) -> usize {
self.workers.threads()
}
/// Convert `src` into `dst`, an I420 frame of the same size whose planes
/// hold `stride * rows` bytes each (e.g. from a
/// [`FramePool`](crate::pool::FramePool)). Takes the timestamp too.
pub fn to_i420_into(&mut self, src: &FrameRef<'_>, dst: &mut VideoFrame) -> Result<()> {
src.validate()?;
if (dst.width, dst.height) != (src.width, src.height) {
return Err(Error::InvalidFrame(format!(
"destination is {}x{}, source {}x{}",
dst.width, dst.height, src.width, src.height
)));
}
let (w, h) = (src.width as usize, src.height as usize);
let (_, ch) = chroma_size(src.width, src.height);
let FrameData::I420 { y, u, v } = &mut dst.data else {
return Err(Error::InvalidFrame("the destination is not I420".into()));
};
let padded = |p: &Plane, width: usize, rows: usize| {
p.stride >= width && p.data.len() >= p.stride * rows
};
if !padded(y, w, h) || !padded(u, w.div_ceil(2), ch) || !padded(v, w.div_ceil(2), ch) {
return Err(Error::InvalidFrame("destination planes are too small".into()));
}
dst.timestamp = src.timestamp;
let tasks = self.workers.tasks(ch);
let band_pairs = ch.div_ceil(tasks);
let band_rows = band_pairs * 2;
let (y_stride, u_stride, v_stride) = (y.stride, u.stride, v.stride);
let bands = y
.data
.chunks_mut(band_rows * y_stride)
.zip(u.data.chunks_mut(band_pairs * u_stride))
.zip(v.data.chunks_mut(band_pairs * v_stride))
.take(ch.div_ceil(band_pairs));
let slots = Slots::new(bands.enumerate());
let failed = Mutex::new(None);
let tail = &self.tail;
self.workers.run(slots.len(), &|task| {
let Some((i, ((y, u), v))) = slots.take(task) else { return };
let r0 = i * band_rows;
let rows = band_rows.min(h - r0);
let band = Band { y, u, v, y_stride, u_stride, v_stride, width: w, r0, rows };
if let Err(e) = convert_band(&src.pixels, band, tail) {
failed.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert(e);
}
});
match failed.into_inner().unwrap_or_else(PoisonError::into_inner) {
Some(e) => Err(e),
None => Ok(()),
}
}
}
/// Peak signal-to-noise ratio in dB between two frames of the same size,
/// over the RGB channels (for tests and quality checks).
pub fn psnr(a: &VideoFrame, b: &VideoFrame) -> Result<f64> {
+154 -18
View File
@@ -46,6 +46,29 @@ impl Plane {
&self.data[y * self.stride..y * self.stride + width]
}
/// The plane borrowed.
pub fn view(&self) -> PlaneRef<'_> {
PlaneRef { data: &self.data, stride: self.stride }
}
}
/// A borrowed image plane: `stride` bytes per row.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlaneRef<'a> {
pub data: &'a [u8],
pub stride: usize,
}
impl<'a> PlaneRef<'a> {
pub fn new(data: &'a [u8], stride: usize) -> Self {
Self { data, stride }
}
/// Row `y`, `width` bytes long.
pub fn row(&self, y: usize, width: usize) -> &'a [u8] {
&self.data[y * self.stride..y * self.stride + width]
}
fn check(&self, name: &str, width: usize, rows: usize) -> Result<()> {
if self.stride < width {
return Err(Error::InvalidFrame(format!(
@@ -63,6 +86,99 @@ impl Plane {
}
Ok(())
}
/// A tightly packed copy of `width` x `rows` bytes.
fn to_plane(self, width: usize, rows: usize) -> Plane {
let mut data = Vec::with_capacity(width * rows);
for y in 0..rows {
data.extend_from_slice(self.row(y, width));
}
Plane::new(data, width)
}
}
/// The pixels of a [`FrameRef`], borrowed (e.g. from a mapped capture
/// buffer).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PixelsRef<'a> {
I420 {
y: PlaneRef<'a>,
u: PlaneRef<'a>,
v: PlaneRef<'a>,
},
Nv12 {
y: PlaneRef<'a>,
uv: PlaneRef<'a>,
},
/// BGRA or BGRx.
Bgra(PlaneRef<'a>),
/// RGBA or RGBx.
Rgba(PlaneRef<'a>),
}
/// A video frame whose pixels are borrowed, e.g. a capture buffer that is
/// mapped only while a callback runs. Capture backends hand these to a
/// [`FrameSink`](crate::capture::FrameSink), which converts straight from
/// them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FrameRef<'a> {
pub width: u32,
pub height: u32,
/// As [`VideoFrame::timestamp`].
pub timestamp: Duration,
pub pixels: PixelsRef<'a>,
}
impl FrameRef<'_> {
pub fn format(&self) -> PixelFormat {
match self.pixels {
PixelsRef::I420 { .. } => PixelFormat::I420,
PixelsRef::Nv12 { .. } => PixelFormat::Nv12,
PixelsRef::Bgra(_) => PixelFormat::Bgra,
PixelsRef::Rgba(_) => PixelFormat::Rgba,
}
}
/// Check that the planes are large enough for the frame size.
pub fn validate(&self) -> Result<()> {
if self.width == 0 || self.height == 0 {
return Err(Error::InvalidFrame(format!("empty frame {}x{}", self.width, self.height)));
}
let (w, h) = (self.width as usize, self.height as usize);
let (cw, ch) = chroma_size(self.width, self.height);
match &self.pixels {
PixelsRef::I420 { y, u, v } => {
y.check("Y", w, h)?;
u.check("U", cw, ch)?;
v.check("V", cw, ch)
}
PixelsRef::Nv12 { y, uv } => {
y.check("Y", w, h)?;
uv.check("UV", cw * 2, ch)
}
PixelsRef::Bgra(p) => p.check("BGRA", w * 4, h),
PixelsRef::Rgba(p) => p.check("RGBA", w * 4, h),
}
}
/// An owned copy with tightly packed planes.
pub fn to_frame(&self) -> VideoFrame {
let (w, h) = (self.width as usize, self.height as usize);
let (cw, ch) = chroma_size(self.width, self.height);
let data = match self.pixels {
PixelsRef::I420 { y, u, v } => FrameData::I420 {
y: y.to_plane(w, h),
u: u.to_plane(cw, ch),
v: v.to_plane(cw, ch),
},
PixelsRef::Nv12 { y, uv } => {
FrameData::Nv12 { y: y.to_plane(w, h), uv: uv.to_plane(cw * 2, ch) }
}
PixelsRef::Bgra(p) => FrameData::Bgra(p.to_plane(w * 4, h)),
PixelsRef::Rgba(p) => FrameData::Rgba(p.to_plane(w * 4, h)),
};
VideoFrame { width: self.width, height: self.height, timestamp: self.timestamp, data }
}
}
/// The pixels of a [`VideoFrame`].
@@ -144,6 +260,19 @@ impl VideoFrame {
}
}
/// The frame with its pixels borrowed.
pub fn view(&self) -> FrameRef<'_> {
let pixels = match &self.data {
FrameData::I420 { y, u, v } => {
PixelsRef::I420 { y: y.view(), u: u.view(), v: v.view() }
}
FrameData::Nv12 { y, uv } => PixelsRef::Nv12 { y: y.view(), uv: uv.view() },
FrameData::Bgra(p) => PixelsRef::Bgra(p.view()),
FrameData::Rgba(p) => PixelsRef::Rgba(p.view()),
};
FrameRef { width: self.width, height: self.height, timestamp: self.timestamp, pixels }
}
/// The timestamp on the 90 kHz RTP video clock.
pub fn pts_90khz(&self) -> u64 {
(self.timestamp.as_micros() * u128::from(VIDEO_CLOCK_RATE) / 1_000_000) as u64
@@ -151,24 +280,7 @@ impl VideoFrame {
/// Check that the planes are large enough for the frame size.
pub fn validate(&self) -> Result<()> {
if self.width == 0 || self.height == 0 {
return Err(Error::InvalidFrame(format!("empty frame {}x{}", self.width, self.height)));
}
let (w, h) = (self.width as usize, self.height as usize);
let (cw, ch) = chroma_size(self.width, self.height);
match &self.data {
FrameData::I420 { y, u, v } => {
y.check("Y", w, h)?;
u.check("U", cw, ch)?;
v.check("V", cw, ch)
}
FrameData::Nv12 { y, uv } => {
y.check("Y", w, h)?;
uv.check("UV", cw * 2, ch)
}
FrameData::Bgra(p) => p.check("BGRA", w * 4, h),
FrameData::Rgba(p) => p.check("RGBA", w * 4, h),
}
self.view().validate()
}
}
@@ -218,4 +330,28 @@ mod tests {
assert_eq!(audio.frames(), 480);
assert_eq!(audio.duration(), Duration::from_millis(10));
}
#[test]
fn borrowed_frames() {
// 3x2 BGRA with 4 bytes of padding per row, last row unpadded.
let data: Vec<u8> = (0..16 + 12).collect();
let frame = FrameRef {
width: 3,
height: 2,
timestamp: Duration::from_millis(5),
pixels: PixelsRef::Bgra(PlaneRef::new(&data, 16)),
};
frame.validate().unwrap();
assert_eq!(frame.format(), PixelFormat::Bgra);
let owned = frame.to_frame();
let FrameData::Bgra(p) = &owned.data else { panic!("not BGRA") };
assert_eq!(p.stride, 12);
assert_eq!(p.data[..12], data[..12]);
assert_eq!(p.data[12..], data[16..]);
assert_eq!(owned.timestamp, Duration::from_millis(5));
assert_eq!(owned.view().to_frame(), owned);
let short = FrameRef { pixels: PixelsRef::Bgra(PlaneRef::new(&data[..27], 16)), ..frame };
assert!(short.validate().is_err());
assert_eq!(VideoFrame::black_i420(5, 3).view().format(), PixelFormat::I420);
}
}
+185
View File
@@ -0,0 +1,185 @@
//! A one-slot, latest-wins handoff between two threads.
//!
//! The producer [`put`](Handoff::put)s shared items (`Arc<T>`), replacing one
//! the consumer has not taken yet (a stale frame is worth nothing to an
//! encoder); the consumer [`take`](Handoff::take)s the newest. The slot is a
//! single atomic pointer, so neither side ever blocks the other or
//! allocates; a waiting consumer is parked and unparked.
#![allow(unsafe_code)]
use std::ptr;
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use std::thread::Thread;
use std::time::{Duration, Instant};
/// See the [module docs](self).
pub struct Handoff<T> {
/// Null, or an `Arc<T>` turned into a raw pointer.
slot: AtomicPtr<T>,
consumer: OnceLock<Thread>,
closed: AtomicBool,
replaced: AtomicU64,
}
// SAFETY: the slot owns an `Arc<T>`, which moves between the threads; that
// is what `Arc<T>: Send + Sync` allows.
unsafe impl<T: Send + Sync> Send for Handoff<T> {}
// SAFETY: as above; all shared access goes through atomics.
unsafe impl<T: Send + Sync> Sync for Handoff<T> {}
impl<T> Default for Handoff<T> {
fn default() -> Self {
Self {
slot: AtomicPtr::new(ptr::null_mut()),
consumer: OnceLock::new(),
closed: AtomicBool::new(false),
replaced: AtomicU64::new(0),
}
}
}
impl<T> Handoff<T> {
pub fn new() -> Self {
Self::default()
}
/// Offer `item`. Returns `true` if it replaced an item the consumer had
/// not taken (counted in [`Handoff::replaced`]).
pub fn put(&self, item: Arc<T>) -> bool {
let new = Arc::into_raw(item).cast_mut();
let old = self.slot.swap(new, Ordering::AcqRel);
if let Some(consumer) = self.consumer.get() {
consumer.unpark();
}
if old.is_null() {
return false;
}
// SAFETY: a non-null slot value always comes from `Arc::into_raw`
// in `put`, and the swap moved its ownership to us.
drop(unsafe { Arc::from_raw(old) });
self.replaced.fetch_add(1, Ordering::Relaxed);
true
}
/// The newest item, if one was put since the last take.
pub fn take(&self) -> Option<Arc<T>> {
let item = self.slot.swap(ptr::null_mut(), Ordering::AcqRel);
// SAFETY: as in `put`: the swap moved the `Arc` out of the slot.
(!item.is_null()).then(|| unsafe { Arc::from_raw(item) })
}
/// Wait up to `timeout` for an item. The first thread that waits becomes
/// the consumer that `put` wakes; there should be only one.
pub fn wait_timeout(&self, timeout: Duration) -> Option<Arc<T>> {
if let Some(item) = self.take() {
return Some(item);
}
let current = std::thread::current();
let parks = self.consumer.get_or_init(|| current.clone()).id() == current.id();
let deadline = Instant::now() + timeout;
loop {
if let Some(item) = self.take() {
return Some(item);
}
let now = Instant::now();
if now >= deadline || self.is_closed() {
return None;
}
if parks {
std::thread::park_timeout(deadline - now);
} else {
// Not the registered consumer: poll.
std::thread::sleep((deadline - now).min(Duration::from_millis(1)));
}
}
}
/// Wake the consumer and make waits return at once (items can still be
/// taken).
pub fn close(&self) {
self.closed.store(true, Ordering::Release);
if let Some(consumer) = self.consumer.get() {
consumer.unpark();
}
}
pub fn is_closed(&self) -> bool {
self.closed.load(Ordering::Acquire)
}
/// Items dropped because a newer one replaced them before the consumer
/// took them.
pub fn replaced(&self) -> u64 {
self.replaced.load(Ordering::Relaxed)
}
}
impl<T> Drop for Handoff<T> {
fn drop(&mut self) {
drop(self.take());
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn newest_wins() {
let handoff = Handoff::new();
assert!(handoff.take().is_none());
assert!(!handoff.put(Arc::new(1)));
assert!(handoff.put(Arc::new(2)));
assert_eq!(handoff.replaced(), 1);
assert_eq!(handoff.take().as_deref(), Some(&2));
assert!(handoff.take().is_none());
// Items left in the slot are dropped with it.
let item = Arc::new(3);
handoff.put(item.clone());
drop(handoff);
assert_eq!(Arc::strong_count(&item), 1);
}
#[test]
fn wakes_the_consumer() {
let handoff = Arc::new(Handoff::new());
let consumer = std::thread::spawn({
let handoff = handoff.clone();
move || {
let mut got = Vec::new();
while let Some(item) = handoff.wait_timeout(Duration::from_secs(5)) {
got.push(*item);
if *item == 99 {
break;
}
}
got
}
});
for i in 0..100 {
handoff.put(Arc::new(i));
if i % 10 == 0 {
std::thread::sleep(Duration::from_millis(1));
}
}
let got = consumer.join().unwrap();
assert_eq!(got.last(), Some(&99));
assert!(got.windows(2).all(|w| w[0] < w[1]), "in order: {got:?}");
assert_eq!(got.len() as u64 + handoff.replaced(), 100);
}
#[test]
fn close_ends_waits() {
let handoff = Arc::new(Handoff::<u8>::new());
let waiter = std::thread::spawn({
let handoff = handoff.clone();
move || handoff.wait_timeout(Duration::from_secs(10))
});
std::thread::sleep(Duration::from_millis(20));
let started = Instant::now();
handoff.close();
assert!(waiter.join().unwrap().is_none());
assert!(started.elapsed() < Duration::from_secs(5));
}
}
+14 -3
View File
@@ -14,6 +14,11 @@
//! PipeWire system audio (feature `pipewire`), and Windows Graphics Capture
//! plus WASAPI loopback on Windows
//! - [`queue`]: the bounded, drop-oldest channel capture backends deliver on
//! - the streaming path: [`workers`] (a fork-join pool that allocates
//! nothing per job), [`pool`] (recycled I420 frames), [`handoff`]
//! (one-slot latest-wins handoff between threads), [`scale`] (plane
//! scaling and the [`scale::Pyramid`] of simulcast sizes), and
//! [`convert::Converter`] (borrowed capture buffers straight to I420)
//!
//! Encoded frames go to `voelin_stream::Peer::write` with an RTP time of
//! [`EncodedFrame::pts_90khz`] (90 kHz clock); received `MediaFrame`s go to
@@ -23,14 +28,20 @@ pub mod capture;
pub mod codec;
pub mod convert;
pub mod frame;
pub mod handoff;
pub mod pool;
pub mod queue;
pub mod scale;
pub mod workers;
pub use capture::{AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId};
pub use codec::{
Codec, Codecs, ContentHint, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder,
VideoEncoder,
Codec, Codecs, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig,
VideoDecoder, VideoEncoder,
};
pub use frame::{
AudioBuffer, FrameData, FrameRef, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame,
};
pub use frame::{AudioBuffer, FrameData, PixelFormat, Plane, VideoFrame};
pub use queue::{FrameReceiver, FrameSender, frame_channel};
/// Errors of this crate.
+100
View File
@@ -0,0 +1,100 @@
//! Recycled I420 frames.
//!
//! A [`FramePool`] belongs to one producer (e.g. the capture thread). It
//! hands out frames of one size for writing; the producer shares them as
//! `Arc<VideoFrame>`, and once every consumer dropped its clone the frame is
//! free again. Frames are allocated only when all are in use or the size
//! changes, so a steady stream reuses the same few buffers.
use std::sync::Arc;
use std::time::Duration;
use crate::frame::{FrameData, Plane, VideoFrame, chroma_size};
/// Recycled I420 frames of one size (tightly packed planes).
#[derive(Default)]
pub struct FramePool {
frames: Vec<Arc<VideoFrame>>,
size: (u32, u32),
allocated: u64,
}
impl FramePool {
pub fn new() -> Self {
Self::default()
}
/// A `width` x `height` I420 frame nobody else holds, to write into.
/// Its pixels are whatever an earlier user left; clone the `Arc` to
/// share it. Changing the size drops the pool's other frames (those still
/// in use are freed by their last user).
pub fn get(&mut self, width: u32, height: u32) -> &mut Arc<VideoFrame> {
if self.size != (width, height) {
self.frames.clear();
self.size = (width, height);
}
let free = self.frames.iter_mut().position(|f| Arc::get_mut(f).is_some());
let index = match free {
Some(i) => i,
None => {
self.allocated += 1;
self.frames.push(Arc::new(blank_i420(width, height)));
self.frames.len() - 1
}
};
&mut self.frames[index]
}
/// Frames allocated since the pool was created.
pub fn allocated(&self) -> u64 {
self.allocated
}
/// Frames in the pool (free or in use).
pub fn len(&self) -> usize {
self.frames.len()
}
pub fn is_empty(&self) -> bool {
self.frames.is_empty()
}
}
/// A zeroed I420 frame with tightly packed planes.
fn blank_i420(width: u32, height: u32) -> VideoFrame {
let (cw, ch) = chroma_size(width, height);
VideoFrame {
width,
height,
timestamp: Duration::ZERO,
data: FrameData::I420 {
y: Plane::filled(width as usize, height as usize, 0),
u: Plane::filled(cw, ch, 0),
v: Plane::filled(cw, ch, 0),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reuses_released_frames() {
let mut pool = FramePool::new();
let a = pool.get(64, 48).clone();
let b = pool.get(64, 48).clone();
assert!(!Arc::ptr_eq(&a, &b), "a is still in use");
assert_eq!(pool.len(), 2);
drop(a);
let c = pool.get(64, 48).clone();
assert_eq!(pool.allocated(), 2, "the released frame came back");
assert!(Arc::get_mut(pool.get(64, 48)).is_some());
drop((b, c));
// A new size starts over.
let d = pool.get(32, 16).clone();
assert_eq!((d.width, d.height), (32, 16));
d.validate().unwrap();
assert_eq!(pool.len(), 1);
}
}
+588
View File
@@ -0,0 +1,588 @@
//! Scaling I420 frames, and the pyramid of sizes simulcast layers need.
//!
//! [`PlaneScaler`] resizes one plane with a separable filter whose weights
//! are computed once per size pair: area averaging for downscaling (every
//! source pixel counts by how much of it an output pixel covers, so text
//! and fine lines do not alias at any ratio) and bilinear interpolation for
//! upscaling; exactly half the size takes a 2x2 box fast path. Work is split
//! into bands of output rows on a [`Workers`] pool.
//!
//! [`Pyramid`] turns one captured frame into I420 frames of every size the
//! layers ask for: it converts the capture once at full size
//! ([`Converter`]), then derives each smaller size from the nearest larger
//! one, reusing pooled frames, so a steady stream allocates nothing.
use std::sync::{Arc, Mutex, PoisonError};
use crate::convert::Converter;
use crate::frame::{FrameData, FrameRef, PlaneRef, VideoFrame, chroma_size};
use crate::pool::FramePool;
use crate::workers::{Slots, Workers};
use crate::{Error, Result};
/// Fixed-point scale of filter weights.
const ONE: u32 = 1 << 14;
/// Fractional bits kept between the vertical and the horizontal pass.
const MID_BITS: u32 = 6;
/// Filter taps of one output coordinate: source index of the first tap, and
/// where its weights start.
#[derive(Clone, Copy, Debug)]
struct Taps {
start: u32,
len: u32,
weights: u32,
}
/// The filter along one axis.
#[derive(Clone, Debug, Default)]
struct Axis {
taps: Vec<Taps>,
weights: Vec<u32>,
}
impl Axis {
/// Weights (summing to [`ONE`]) mapping `src` samples to `dst`.
fn new(src: usize, dst: usize) -> Self {
let mut axis = Self { taps: Vec::with_capacity(dst), weights: Vec::new() };
let ratio = src as f64 / dst as f64;
let mut scratch: Vec<(usize, f64)> = Vec::new();
for o in 0..dst {
scratch.clear();
if ratio >= 1.0 {
// Area: source pixels overlapping [o, o + 1) * ratio.
let (lo, hi) = (o as f64 * ratio, (o as f64 + 1.0) * ratio);
let first = lo.floor() as usize;
let last = (hi.ceil() as usize).min(src);
for i in first..last {
let overlap = hi.min(i as f64 + 1.0) - lo.max(i as f64);
if overlap > 1e-9 {
scratch.push((i, overlap / ratio));
}
}
} else {
// Bilinear between the two nearest source pixels.
let s = ((o as f64 + 0.5) * ratio - 0.5).clamp(0.0, (src - 1) as f64);
let i = s.floor() as usize;
let f = s - i as f64;
scratch.push((i, 1.0 - f));
if i + 1 < src && f > 1e-9 {
scratch.push((i + 1, f));
}
}
axis.push(&scratch);
}
axis
}
/// Quantize one output's weights so they sum to exactly [`ONE`].
fn push(&mut self, taps: &[(usize, f64)]) {
let offset = self.weights.len() as u32;
let mut sum = 0;
for &(_, w) in taps {
let q = (w * f64::from(ONE)).round() as u32;
self.weights.push(q);
sum += q;
}
// Rounding error goes to the largest weight.
let slice = &mut self.weights[offset as usize..];
if let Some(largest) = slice.iter_mut().max_by_key(|w| **w) {
*largest = (*largest + ONE).saturating_sub(sum);
}
self.taps.push(Taps { start: taps[0].0 as u32, len: taps.len() as u32, weights: offset });
}
fn get(&self, o: usize) -> (usize, &[u32]) {
let t = self.taps[o];
(t.start as usize, &self.weights[t.weights as usize..(t.weights + t.len) as usize])
}
}
/// Resizes planes of one source size to one destination size.
pub struct PlaneScaler {
src: (usize, usize),
dst: (usize, usize),
x: Axis,
y: Axis,
/// Exactly half the size: 2x2 box average.
half: bool,
/// One row of vertically filtered samples per task.
scratch: Vec<Mutex<Vec<u16>>>,
}
impl PlaneScaler {
pub fn new(src: (usize, usize), dst: (usize, usize)) -> Self {
let (src, dst) = ((src.0.max(1), src.1.max(1)), (dst.0.max(1), dst.1.max(1)));
let half = src.0 == dst.0 * 2 && src.1 == dst.1 * 2;
let (x, y) = if half {
(Axis::default(), Axis::default())
} else {
(Axis::new(src.0, dst.0), Axis::new(src.1, dst.1))
};
Self { src, dst, x, y, half, scratch: Vec::new() }
}
pub fn sizes(&self) -> ((usize, usize), (usize, usize)) {
(self.src, self.dst)
}
/// Scale `src` into `dst` (`dst_stride` bytes per row).
pub fn scale(
&mut self,
workers: &mut Workers,
src: PlaneRef<'_>,
dst: &mut [u8],
dst_stride: usize,
) -> Result<()> {
let ((sw, sh), (dw, dh)) = (self.src, self.dst);
if src.stride < sw || src.data.len() < src.stride * (sh - 1) + sw {
return Err(Error::InvalidFrame("scaler source plane too small".into()));
}
if dst_stride < dw || dst.len() < dst_stride * (dh - 1) + dw {
return Err(Error::InvalidFrame("scaler destination plane too small".into()));
}
let tasks = workers.tasks(dh);
let band = dh.div_ceil(tasks);
let tasks = dh.div_ceil(band);
if !self.half {
while self.scratch.len() < tasks {
self.scratch.push(Mutex::new(vec![0; sw]));
}
}
let slots = Slots::new(dst.chunks_mut(band * dst_stride).take(tasks).enumerate());
let this = &*self;
workers.run(slots.len(), &|task| {
let Some((i, out)) = slots.take(task) else { return };
let rows = i * band..((i + 1) * band).min(dh);
if this.half {
half_rows(src, out, dst_stride, dw, rows);
} else {
let mut tmp = this.scratch[i].lock().unwrap_or_else(PoisonError::into_inner);
this.filter_rows(src, out, dst_stride, rows, &mut tmp);
}
});
Ok(())
}
fn filter_rows(
&self,
src: PlaneRef<'_>,
out: &mut [u8],
stride: usize,
rows: std::ops::Range<usize>,
tmp: &mut [u16],
) {
let (sw, dw) = (self.src.0, self.dst.0);
let first = rows.start;
for oy in rows {
// Vertical pass: tmp = weighted sum of source rows, with
// MID_BITS fractional bits.
let (start, weights) = self.y.get(oy);
const CHUNK: usize = 64;
let mut acc = [0u32; CHUNK];
let mut x0 = 0;
while x0 < sw {
let n = CHUNK.min(sw - x0);
let acc = &mut acc[..n];
acc.fill(0);
for (k, &w) in weights.iter().enumerate() {
let row = &src.row(start + k, sw)[x0..x0 + n];
for (a, &p) in acc.iter_mut().zip(row) {
*a += w * u32::from(p);
}
}
for (t, &a) in tmp[x0..x0 + n].iter_mut().zip(acc.iter()) {
*t = ((a + (1 << (13 - MID_BITS))) >> (14 - MID_BITS)) as u16;
}
x0 += n;
}
// Horizontal pass.
let line = &mut out[(oy - first) * stride..][..dw];
for (ox, px) in line.iter_mut().enumerate() {
let (start, weights) = self.x.get(ox);
let sum: u32 =
weights.iter().zip(&tmp[start..]).map(|(&w, &t)| w * u32::from(t)).sum();
*px = ((sum + (1 << (13 + MID_BITS))) >> (14 + MID_BITS)).min(255) as u8;
}
}
}
}
/// 2x2 box average of output rows `rows` (source exactly twice the size).
fn half_rows(
src: PlaneRef<'_>,
out: &mut [u8],
stride: usize,
dw: usize,
rows: std::ops::Range<usize>,
) {
let first = rows.start;
for oy in rows {
let a = src.row(oy * 2, dw * 2);
let b = src.row(oy * 2 + 1, dw * 2);
let line = &mut out[(oy - first) * stride..][..dw];
for ((px, a), b) in line.iter_mut().zip(a.chunks_exact(2)).zip(b.chunks_exact(2)) {
let sum = u16::from(a[0]) + u16::from(a[1]) + u16::from(b[0]) + u16::from(b[1]);
*px = ((sum + 2) >> 2) as u8;
}
}
}
/// Scalers for the three planes of an I420 frame (U and V share one).
struct I420Scaler {
luma: PlaneScaler,
chroma: PlaneScaler,
}
impl I420Scaler {
fn new(src: (u32, u32), dst: (u32, u32)) -> Self {
let (sc, dc) = (chroma_size(src.0, src.1), chroma_size(dst.0, dst.1));
Self {
luma: PlaneScaler::new(
(src.0 as usize, src.1 as usize),
(dst.0 as usize, dst.1 as usize),
),
chroma: PlaneScaler::new(sc, dc),
}
}
fn scale(
&mut self,
workers: &mut Workers,
src: &VideoFrame,
dst: &mut VideoFrame,
) -> Result<()> {
let (FrameData::I420 { y, u, v }, FrameData::I420 { y: dy, u: du, v: dv }) =
(&src.data, &mut dst.data)
else {
return Err(Error::InvalidFrame("scaling needs I420 frames".into()));
};
self.luma.scale(workers, y.view(), &mut dy.data, dy.stride)?;
self.chroma.scale(workers, u.view(), &mut du.data, du.stride)?;
self.chroma.scale(workers, v.view(), &mut dv.data, dv.stride)?;
dst.timestamp = src.timestamp;
Ok(())
}
}
/// Scale an I420 frame into another of a different size (allocates filter
/// tables; for repeated use see [`Pyramid`]).
pub fn scale_i420(workers: &mut Workers, src: &VideoFrame, dst: &mut VideoFrame) -> Result<()> {
src.validate()?;
dst.validate()?;
I420Scaler::new((src.width, src.height), (dst.width, dst.height)).scale(workers, src, dst)
}
/// One size of the pyramid.
struct Level {
size: (u32, u32),
/// The level this one is scaled from; `None`: from the full-size frame.
source: Option<usize>,
scaler: Option<I420Scaler>,
pool: FramePool,
/// This frame's picture at this size.
current: Option<Arc<VideoFrame>>,
/// Needed for this frame (an output is due, or a needed level is scaled
/// from it).
needed: bool,
}
/// Turns captured frames into I420 frames of several sizes; see the
/// [module docs](self).
pub struct Pyramid {
converter: Converter,
input: (u32, u32),
full: FramePool,
levels: Vec<Level>,
/// For each output: its level.
outputs: Vec<usize>,
/// The output sizes the plan was made for.
planned: Vec<(u32, u32)>,
}
impl Pyramid {
/// `threads` as in [`Workers::new`](crate::workers::Workers::new) (0:
/// one per CPU).
pub fn new(threads: usize) -> Self {
Self {
converter: Converter::new(threads),
input: (0, 0),
full: FramePool::new(),
levels: Vec::new(),
outputs: Vec::new(),
planned: Vec::new(),
}
}
/// Threads converting and scaling, the caller included.
pub fn threads(&self) -> usize {
self.converter.threads()
}
/// Plan the levels for these output sizes and this input size.
fn plan(&mut self, input: (u32, u32), sizes: &[(u32, u32)]) {
self.input = input;
self.planned.clear();
self.planned.extend_from_slice(sizes);
let mut distinct: Vec<(u32, u32)> = sizes.iter().copied().filter(|&s| s != input).collect();
distinct.sort_unstable_by_key(|&(w, h)| std::cmp::Reverse(u64::from(w) * u64::from(h)));
distinct.dedup();
self.levels.clear();
for size in distinct {
// The smallest planned level that covers this size, else the
// full frame.
let source = self
.levels
.iter()
.enumerate()
.filter(|(_, l)| l.size.0 >= size.0 && l.size.1 >= size.1)
.min_by_key(|(_, l)| u64::from(l.size.0) * u64::from(l.size.1))
.map(|(i, _)| i);
let from = source.map_or(input, |i| self.levels[i].size);
self.levels.push(Level {
size,
source,
scaler: Some(I420Scaler::new(from, size)),
pool: FramePool::new(),
current: None,
needed: false,
});
}
self.outputs.clear();
for &size in sizes {
let level = self.levels.iter().position(|l| l.size == size).unwrap_or(usize::MAX);
self.outputs.push(level);
}
}
/// Produce frames for the outputs of this capture: `sizes[i]` is output
/// `i`'s size, and `out[i]` gets its frame if `due[i]` (else `None`).
/// Outputs of the same size share one frame; the capture is converted
/// once. Allocates only when sizes change or all pooled frames are in
/// use.
pub fn process(
&mut self,
frame: &FrameRef<'_>,
sizes: &[(u32, u32)],
due: &[bool],
out: &mut [Option<Arc<VideoFrame>>],
) -> Result<()> {
let input = (frame.width, frame.height);
if input != self.input || sizes != self.planned.as_slice() {
self.plan(input, sizes);
}
for level in &mut self.levels {
level.needed = false;
level.current = None;
}
let mut full_needed = false;
for (i, &level) in self.outputs.iter().enumerate() {
if !due.get(i).copied().unwrap_or(false) {
continue;
}
let mut at = level;
if at == usize::MAX {
full_needed = true;
continue;
}
// Mark the chain of sources.
loop {
self.levels[at].needed = true;
match self.levels[at].source {
Some(s) => at = s,
None => {
full_needed = true;
break;
}
}
}
}
let full = if full_needed {
let slot = self.full.get(input.0, input.1);
let target = Arc::get_mut(slot).expect("the pool hands out unshared frames");
self.converter.to_i420_into(frame, target)?;
Some(slot.clone())
} else {
None
};
for i in 0..self.levels.len() {
if !self.levels[i].needed {
continue;
}
let source = match self.levels[i].source {
Some(s) => self.levels[s].current.clone(),
None => full.clone(),
}
.expect("sources come first and are needed");
let level = &mut self.levels[i];
let slot = level.pool.get(level.size.0, level.size.1);
let target = Arc::get_mut(slot).expect("the pool hands out unshared frames");
let scaler = level.scaler.as_mut().expect("planned");
scaler.scale(self.converter.workers(), &source, target)?;
level.current = Some(slot.clone());
}
for (i, slot) in out.iter_mut().enumerate() {
*slot = None;
if !due.get(i).copied().unwrap_or(false) {
continue;
}
*slot = match self.outputs.get(i) {
Some(&usize::MAX) => full.clone(),
Some(&level) => self.levels[level].current.clone(),
None => None,
};
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
use crate::convert;
use crate::frame::{PixelsRef, Plane};
fn gray(w: usize, h: usize, f: impl Fn(usize, usize) -> u8) -> Plane {
let mut data = vec![0; w * h];
for y in 0..h {
for x in 0..w {
data[y * w + x] = f(x, y);
}
}
Plane::new(data, w)
}
fn scale_plane(src: &Plane, sw: usize, sh: usize, dw: usize, dh: usize) -> Vec<u8> {
let mut workers = Workers::new("test-scale", 3);
let mut scaler = PlaneScaler::new((sw, sh), (dw, dh));
let mut out = vec![0; dw * dh];
scaler.scale(&mut workers, src.view(), &mut out, dw).unwrap();
out
}
#[test]
fn flat_stays_flat_at_any_ratio() {
for (sw, sh, dw, dh) in
[(64, 48, 32, 24), (1920, 1080, 1280, 720), (97, 55, 30, 17), (40, 30, 64, 45)]
{
let src = gray(sw, sh, |_, _| 77);
let out = scale_plane(&src, sw, sh, dw, dh);
assert!(out.iter().all(|&p| p == 77), "{sw}x{sh} -> {dw}x{dh}");
}
}
#[test]
fn area_average_and_half() {
// Alternating columns 0/200 average to 100 at half and a third of
// the width.
let src = gray(12, 4, |x, _| if x % 2 == 0 { 0 } else { 200 });
assert!(scale_plane(&src, 12, 4, 6, 2).iter().all(|&p| p == 100));
let third = scale_plane(&src, 12, 4, 4, 4);
// Each output covers three columns: 0,200,0 or 200,0,200.
assert_eq!(third[..4], [67, 133, 67, 133]);
// A gradient keeps its mean.
let src = gray(300, 10, |x, _| (x * 255 / 299) as u8);
let out = scale_plane(&src, 300, 10, 128, 7);
let mean = |d: &[u8]| d.iter().map(|&p| f64::from(p)).sum::<f64>() / d.len() as f64;
assert!((mean(&out) - mean(&src.data)).abs() < 1.0);
assert!(out.windows(2).take(127).all(|w| w[0] <= w[1]), "monotonic");
}
fn bgra(w: u32, h: u32, n: u32) -> VideoFrame {
let mut data = vec![0; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let i = ((y * w + x) * 4) as usize;
let inside = x / 16 % 2 == (y / 16 + n) % 2;
let c = if inside { [30, 90, 240, 255] } else { [200, 200, 200, 255] };
data[i..i + 4].copy_from_slice(&c);
}
}
VideoFrame::from_bgra(w, h, (w * 4) as usize, data)
.unwrap()
.with_timestamp(Duration::from_millis(u64::from(n)))
}
#[test]
fn pyramid_outputs_share_and_recycle() {
let mut pyramid = Pyramid::new(3);
let sizes = [(320, 240), (160, 120), (320, 240), (106, 80)];
let mut out = vec![None; 4];
let src = bgra(320, 240, 0);
pyramid.process(&src.view(), &sizes, &[true, true, true, true], &mut out).unwrap();
let frames: Vec<Arc<VideoFrame>> = out.iter().map(|f| f.clone().unwrap()).collect();
assert!(Arc::ptr_eq(&frames[0], &frames[2]), "same size, same frame");
for (f, &(w, h)) in frames.iter().zip(&sizes) {
assert_eq!((f.width, f.height), (w, h));
f.validate().unwrap();
}
// The full size matches a direct conversion.
let direct = convert::to_i420(&src).unwrap();
assert_eq!(*frames[0], *direct);
// Scaled levels look like the source scaled directly.
for i in [1, 3] {
let mut expected = VideoFrame::black_i420(sizes[i].0, sizes[i].1);
scale_i420(&mut Workers::new("test", 1), &frames[0], &mut expected).unwrap();
let psnr = convert::psnr(&frames[i], &expected).unwrap();
assert!(psnr > 35.0, "level {i}: {psnr:.1} dB");
}
// Not due: no frame. Frames still held are not reused.
pyramid
.process(&bgra(320, 240, 1).view(), &sizes, &[false, true, false, false], &mut out)
.unwrap();
assert!(out[0].is_none() && out[3].is_none());
assert!(!Arc::ptr_eq(out[1].as_ref().unwrap(), &frames[1]));
assert_eq!(out[1].as_ref().unwrap().timestamp, Duration::from_millis(1));
drop(frames);
// Steady state: the pools stop growing.
for n in 2..10 {
pyramid.process(&bgra(320, 240, n).view(), &sizes, &[true; 4], &mut out).unwrap();
}
let allocated = pyramid.full.allocated()
+ pyramid.levels.iter().map(|l| l.pool.allocated()).sum::<u64>();
for n in 10..20 {
pyramid.process(&bgra(320, 240, n).view(), &sizes, &[true; 4], &mut out).unwrap();
}
let after = pyramid.full.allocated()
+ pyramid.levels.iter().map(|l| l.pool.allocated()).sum::<u64>();
assert_eq!(allocated, after);
}
#[test]
fn converter_handles_strides_and_unpadded_last_rows() {
let src = bgra(66, 34, 3);
let FrameData::Bgra(plane) = &src.data else { unreachable!() };
// Re-pack with a 300-byte stride and no padding after the last row.
let stride = 300;
let mut data = vec![0xee; stride * 33 + 66 * 4];
for y in 0..34 {
let row = plane.row(y, 66 * 4);
data[y * stride..y * stride + 66 * 4].copy_from_slice(row);
}
let view = FrameRef {
width: 66,
height: 34,
timestamp: src.timestamp,
pixels: PixelsRef::Bgra(PlaneRef::new(&data, stride)),
};
let mut converter = Converter::new(4);
let mut pool = FramePool::new();
let target = Arc::get_mut(pool.get(66, 34)).unwrap();
converter.to_i420_into(&view, target).unwrap();
assert_eq!(*target, *convert::to_i420(&src).unwrap());
// Odd height, RGBA.
let odd = VideoFrame::from_rgba(33, 17, 33 * 4, vec![128; 33 * 17 * 4]).unwrap();
let target = Arc::get_mut(pool.get(33, 17)).unwrap();
converter.to_i420_into(&odd.view(), target).unwrap();
assert_eq!(*target, *convert::to_i420(&odd).unwrap());
// I420 and NV12 sources are copied.
let i420 = convert::to_i420(&src).unwrap().into_owned();
let target = Arc::get_mut(pool.get(66, 34)).unwrap();
converter.to_i420_into(&i420.view(), target).unwrap();
assert_eq!(*target, i420);
assert!(converter.to_i420_into(&odd.view(), target).is_err(), "size mismatch");
}
}
+316
View File
@@ -0,0 +1,316 @@
//! A small fork-join thread pool for per-frame pixel work.
//!
//! [`Workers::run`] splits a job into numbered tasks that the pool's threads
//! and the calling thread claim until none are left, and returns once all of
//! them finished. Unlike `std::thread::scope` it spawns nothing per job, and
//! unlike a general task queue it allocates nothing per job: the job is a
//! borrowed closure, published through a mutex and condition variable
//! (futexes on Linux and Android, SRW locks on Windows).
#![allow(unsafe_code)]
use std::any::Any;
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::thread::JoinHandle;
/// Most tasks one job is split into (see [`Workers::tasks`]).
pub const MAX_TASKS: usize = 64;
/// The job of one [`Workers::run`] call.
#[derive(Clone, Copy)]
struct Job {
/// The caller's closure with its lifetime erased; see [`Workers::run`]
/// for why it stays valid while a worker uses it.
f: *const (dyn Fn(usize) + Sync + 'static),
tasks: usize,
}
// SAFETY: the closure is `Sync`, so calling it from several threads through
// a shared pointer is allowed; the pointer is only dereferenced while the
// `run` call that owns the closure waits (see `Workers::run`).
unsafe impl Send for Job {}
struct State {
/// Bumped for every job.
generation: u64,
job: Option<Job>,
/// Workers that took the current job and have not given it back.
active: usize,
/// Tasks of the current job that are done.
finished: usize,
panic: Option<Box<dyn Any + Send>>,
stop: bool,
}
struct Shared {
state: Mutex<State>,
/// Workers wait here for a job.
wake: Condvar,
/// The caller waits here for the last task.
done: Condvar,
/// The next task to claim.
next: AtomicUsize,
}
impl Shared {
fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// Run tasks of `job` until none are left; returns how many this thread
/// ran.
fn claim(shared: &Shared, job: Job, panic: &mut Option<Box<dyn Any + Send>>) -> usize {
let mut count = 0;
loop {
let task = shared.next.fetch_add(1, Ordering::Relaxed);
if task >= job.tasks {
return count;
}
// SAFETY: `job.f` points to the closure of the `run` call that
// published `job`; that call does not return before every thread
// that took the job gave it back (`active`), so the closure lives.
let f = unsafe { &*job.f };
if let Err(e) = catch_unwind(AssertUnwindSafe(|| f(task))) {
panic.get_or_insert(e);
}
count += 1;
}
}
/// A pool of threads for splitting per-frame work. Stops its threads when
/// dropped.
pub struct Workers {
shared: Arc<Shared>,
threads: Vec<JoinHandle<()>>,
}
impl Workers {
/// A pool that uses `threads` threads in total, the caller of
/// [`Workers::run`] included (so `threads - 1` are spawned). 0 means one
/// per available CPU.
pub fn new(name: &str, threads: usize) -> Self {
let threads = match threads {
0 => std::thread::available_parallelism().map_or(1, |n| n.get()),
n => n,
};
let shared = Arc::new(Shared {
state: Mutex::new(State {
generation: 0,
job: None,
active: 0,
finished: 0,
panic: None,
stop: false,
}),
wake: Condvar::new(),
done: Condvar::new(),
next: AtomicUsize::new(0),
});
let mut workers = Self { shared, threads: Vec::new() };
for i in 1..threads {
let shared = workers.shared.clone();
let spawned = std::thread::Builder::new()
.name(format!("{name}-{i}"))
.spawn(move || worker(&shared));
match spawned {
Ok(thread) => workers.threads.push(thread),
Err(e) => {
tracing::warn!("cannot start a pixel worker thread: {e}");
break;
}
}
}
workers
}
/// Threads that work on a job, the caller included.
pub fn threads(&self) -> usize {
self.threads.len() + 1
}
/// A good number of tasks to split a job of `units` independent parts
/// (e.g. pairs of rows) into: a few per thread, so a thread that gets
/// descheduled does not hold everyone up.
pub fn tasks(&self, units: usize) -> usize {
(self.threads() * 3).min(MAX_TASKS).min(units).max(1)
}
/// Call `f(0)`, ..., `f(tasks - 1)` on the pool's threads and this one,
/// each exactly once, and return when all returned. A panic in `f` is
/// resumed here after the other tasks finished.
pub fn run(&mut self, tasks: usize, f: &(dyn Fn(usize) + Sync)) {
if tasks <= 1 || self.threads.is_empty() {
(0..tasks).for_each(f);
return;
}
// SAFETY: this only erases the lifetime. The pointer is published in
// `State::job` below and removed before this function returns. A
// worker copies it only while holding the lock and counts itself in
// `active` in the same critical section; it gives it back
// (`active -= 1`) after its last use. This function waits until
// `active` is zero, and takes `&mut self`, so no second job can
// overlap. Hence `f` outlives every dereference of the pointer.
let f_static: &'static (dyn Fn(usize) + Sync) = unsafe { std::mem::transmute(f) };
let job = Job { f: f_static, tasks };
{
let mut state = self.shared.lock();
self.shared.next.store(0, Ordering::Relaxed);
state.generation = state.generation.wrapping_add(1);
state.job = Some(job);
state.finished = 0;
}
self.shared.wake.notify_all();
let mut panic = None;
let count = claim(&self.shared, job, &mut panic);
let mut state = self.shared.lock();
state.finished += count;
while state.finished < tasks || state.active > 0 {
state = self.shared.done.wait(state).unwrap_or_else(PoisonError::into_inner);
}
state.job = None;
let panic = panic.or_else(|| state.panic.take());
drop(state);
if let Some(panic) = panic {
resume_unwind(panic);
}
}
}
fn worker(shared: &Shared) {
let mut seen = 0;
loop {
let job = {
let mut state = shared.lock();
loop {
if state.stop {
return;
}
if let Some(job) = state.job
&& state.generation != seen
{
seen = state.generation;
state.active += 1;
break job;
}
state = shared.wake.wait(state).unwrap_or_else(PoisonError::into_inner);
}
};
let mut panic = None;
let count = claim(shared, job, &mut panic);
let mut state = shared.lock();
state.finished += count;
state.active -= 1;
if panic.is_some() && state.panic.is_none() {
state.panic = panic;
}
if state.active == 0 && state.finished >= job.tasks {
shared.done.notify_all();
}
}
}
impl Drop for Workers {
fn drop(&mut self) {
self.shared.lock().stop = true;
self.shared.wake.notify_all();
for thread in self.threads.drain(..) {
let _ = thread.join();
}
}
}
/// Hands out the items of a slice to the tasks of a [`Workers::run`] job,
/// each item to exactly one task, without `unsafe` or allocation.
pub struct Slots<T> {
slots: [Mutex<Option<T>>; MAX_TASKS],
len: usize,
}
impl<T> Slots<T> {
/// Up to [`MAX_TASKS`] items; more panic.
pub fn new(items: impl IntoIterator<Item = T>) -> Self {
let slots = std::array::from_fn(|_| Mutex::new(None));
let mut len = 0;
for (slot, item) in slots.iter().zip(items) {
*slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(item);
len += 1;
}
Self { slots, len }
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Item `i`, once.
pub fn take(&self, i: usize) -> Option<T> {
self.slots.get(i)?.lock().unwrap_or_else(PoisonError::into_inner).take()
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::AtomicU64;
use super::*;
#[test]
fn runs_every_task_once() {
let mut workers = Workers::new("test-workers", 4);
assert_eq!(workers.threads(), 4);
for round in 0..200 {
let tasks = 1 + round % 40;
let hits: Vec<AtomicU64> = (0..tasks).map(|_| AtomicU64::new(0)).collect();
workers.run(tasks, &|i| {
hits[i].fetch_add(1, Ordering::Relaxed);
});
assert!(hits.iter().all(|h| h.load(Ordering::Relaxed) == 1), "round {round}");
}
}
#[test]
fn borrows_and_mutates_through_slots() {
let mut workers = Workers::new("test-workers", 3);
let mut data = vec![0u32; 1000];
let slots = Slots::new(data.chunks_mut(100));
assert_eq!(slots.len(), 10);
workers.run(slots.len(), &|i| {
for x in slots.take(i).unwrap() {
*x = i as u32 + 1;
}
});
assert!(data.chunks(100).enumerate().all(|(i, c)| c.iter().all(|&x| x == i as u32 + 1)));
}
#[test]
fn panics_reach_the_caller_and_the_pool_survives() {
let mut workers = Workers::new("test-workers", 2);
let result = catch_unwind(AssertUnwindSafe(|| {
workers.run(8, &|i| assert_ne!(i, 5, "task five"));
}));
assert!(result.is_err());
let count = AtomicU64::new(0);
workers.run(8, &|_| {
count.fetch_add(1, Ordering::Relaxed);
});
assert_eq!(count.load(Ordering::Relaxed), 8);
}
#[test]
fn single_thread_runs_inline() {
let mut workers = Workers::new("test-workers", 1);
assert_eq!(workers.threads(), 1);
assert_eq!(workers.tasks(100), 3);
let count = AtomicU64::new(0);
workers.run(5, &|_| {
count.fetch_add(1, Ordering::Relaxed);
});
assert_eq!(count.load(Ordering::Relaxed), 5);
}
}
@@ -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");
}