voelin-media: capture into sinks, zero-copy conversion, scaling, pools; libvpx tuning
Screen sharing was slow mostly because every frame was copied and allocated several times on its way to the encoder: the PipeWire callback copied the mapped buffer into a new Vec, X11 copied the shared-memory segment, Windows copied twice, `to_i420` allocated fresh planes on one thread, and libvpx output was copied into Vec after Vec. Capture backends now hand each frame to a `FrameSink` on their own thread, with the pixels still in the capture buffer (`FrameRef`: borrowed planes with strides). `ScreenCapture::start_sink` is implemented by the test pattern (renders into one reused buffer), X11 (the MIT-SHM segment, cursor blended in place, monitor/window geometry looked up once a second instead of every frame), the portal and Windows Graphics Capture (the mapped staging texture with its row pitch); other backends get a forwarding default. `start` keeps working through a queue adapter. `FramePacer` caps frame rates by timestamps; sinks can change the cap while capturing (X11 and the test pattern follow, the portal renegotiates the frame rate). Portal: LINEAR DMA-BUFs are negotiated in addition to shared memory (mandatory modifier, fixated by us, `dataType` per buffer kind), mapped once per buffer and read between DMA_BUF_IOCTL_SYNC start/end. When reading them is slow (uncached VRAM), the stream renegotiates to shared memory. Tiled modifiers are not offered (needs a GPU import). The streaming path: - `workers::Workers`: a fork-join pool that allocates nothing per job. - `convert::Converter`: any stride, BGRx/BGRA/RGBx/RGBA (yuv's SIMD paths), I420 and NV12 into a caller's I420 frame, in row bands on all cores; handles buffers without padding after the last row. - `scale`: separable area-average downscaling (bilinear up), weights per size pair computed once, a 2x2 box fast path, row bands on the pool; `Pyramid` converts a capture once and derives every requested size from the nearest larger one, sharing equal sizes. - `pool::FramePool`: recycled `Arc<VideoFrame>`s; `handoff::Handoff`: a one-slot latest-wins atomic handoff that counts replaced frames. Codecs: `VideoEncoder::encode_with` hands out encoded frames borrowed from the encoder (libvpx's own buffer; OpenH264 into a reused buffer). libvpx: `cpu-used` adapts to the measured encode time against the frame interval (VP8 levels -10..-4, VP9 starting at 8 within 5..9), threads from all CPUs the frame size can use, VP8 token partitions and VP9 tile columns from the thread count and width, keyframes only on request, frame durations from timestamps (variable frame rate), `set_fps`, and `speed` for stats. A probe on the desktop test pattern showed VP8 speeds beyond -10 are no faster on screen content, only worse (about 3 dB PSNR). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
1 parent
31b138adf1
commit
bbfd9aba47
18 files changed
+2780
-271
No files matched your search
@@ -21,9 +21,9 @@ 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"]
|
||||
# Conversion between `Codec` and `str0m::format::Codec`.
|
||||
str0m = ["dep:str0m"]
|
||||
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
//! Screen and system-audio capture.
|
||||
//!
|
||||
//! Backends deliver frames on a [`FrameReceiver`] from their own thread; the
|
||||
//! queue drops the oldest frame when the consumer falls behind.
|
||||
//! Screen backends hand each frame to a [`FrameSink`] on their own thread,
|
||||
//! with the pixels still in the capture buffer (a PipeWire buffer, the X11
|
||||
//! shared-memory segment, a Windows staging texture), so the sink converts
|
||||
//! straight from it ([`ScreenCapture::start_sink`]). [`ScreenCapture::start`]
|
||||
//! instead copies frames into a [`FrameReceiver`]; the queue drops the oldest
|
||||
//! frame when the consumer falls behind. Audio backends use a
|
||||
//! [`FrameReceiver`].
|
||||
//!
|
||||
//! | Backend | Screen | System audio |
|
||||
//! |---|---|---|
|
||||
@@ -18,10 +23,12 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::frame::{AudioBuffer, VideoFrame};
|
||||
use crate::queue::FrameReceiver;
|
||||
use crate::frame::{AudioBuffer, FrameRef, VideoFrame};
|
||||
use crate::queue::{FrameReceiver, FrameSender, frame_channel};
|
||||
use crate::{Error, Result};
|
||||
|
||||
#[cfg(all(target_os = "linux", feature = "pipewire"))]
|
||||
mod dmabuf;
|
||||
pub mod external;
|
||||
#[cfg(all(target_os = "linux", feature = "pipewire"))]
|
||||
pub mod pipewire_audio;
|
||||
@@ -64,7 +71,8 @@ pub struct CaptureSource {
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CaptureOptions {
|
||||
/// Maximum frame rate.
|
||||
/// Maximum frame rate for [`ScreenCapture::start`] (with
|
||||
/// [`ScreenCapture::start_sink`], [`FrameSink::max_fps`] decides).
|
||||
pub fps: u32,
|
||||
/// Draw the mouse cursor into the frames.
|
||||
pub cursor: bool,
|
||||
@@ -78,6 +86,133 @@ impl Default for CaptureOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives captured frames on the capture backend's thread; see
|
||||
/// [`ScreenCapture::start_sink`].
|
||||
pub trait FrameSink: Send {
|
||||
/// The highest frame rate wanted now. Backends that pace themselves
|
||||
/// (X11, the test pattern) capture at this rate; it may change while
|
||||
/// capturing.
|
||||
fn max_fps(&self) -> u32;
|
||||
|
||||
/// Whether a frame captured at `timestamp` would be used. Backends that
|
||||
/// get frames pushed (PipeWire, Windows, wlroots) ask before they map or
|
||||
/// copy anything, and give unwanted buffers straight back.
|
||||
fn wants(&mut self, timestamp: Duration) -> bool {
|
||||
let _ = timestamp;
|
||||
true
|
||||
}
|
||||
|
||||
/// One frame. Its pixels are only valid during the call. Returns
|
||||
/// `false` when no more frames are wanted; the backend then stops.
|
||||
fn frame(&mut self, frame: FrameRef<'_>) -> bool;
|
||||
}
|
||||
|
||||
/// Keeps frames of a source for a frame-rate cap, by their timestamps, so
|
||||
/// the kept frames are evenly spaced at the cap (or at the source's rate if
|
||||
/// that is lower).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FramePacer {
|
||||
interval: Duration,
|
||||
next: Option<Duration>,
|
||||
}
|
||||
|
||||
impl FramePacer {
|
||||
/// At most `fps` frames per second; `None` (or 0) keeps every frame.
|
||||
pub fn new(fps: Option<u32>) -> Self {
|
||||
let mut pacer = Self { interval: Duration::ZERO, next: None };
|
||||
pacer.set_fps(fps);
|
||||
pacer
|
||||
}
|
||||
|
||||
pub fn set_fps(&mut self, fps: Option<u32>) {
|
||||
self.interval = match fps {
|
||||
Some(fps) if fps > 0 => Duration::from_secs(1) / fps,
|
||||
_ => Duration::ZERO,
|
||||
};
|
||||
}
|
||||
|
||||
/// Whether a frame at `timestamp` is due. A frame up to an eighth of
|
||||
/// the interval early still counts, so jitter does not halve the rate;
|
||||
/// a timestamp far before the expected one means the clock started
|
||||
/// over.
|
||||
pub fn due(&self, timestamp: Duration) -> bool {
|
||||
self.next.is_none_or(|next| {
|
||||
timestamp + self.interval / 8 >= next || timestamp + 2 * self.interval <= next
|
||||
})
|
||||
}
|
||||
|
||||
/// Record that the frame at `timestamp` was kept.
|
||||
pub fn keep(&mut self, timestamp: Duration) {
|
||||
let iv = self.interval;
|
||||
self.next = Some(match self.next {
|
||||
// On time: keep the average rate exact.
|
||||
Some(next) if timestamp < next + iv && timestamp + 2 * iv > next => next + iv,
|
||||
// Late (or the clock jumped): start over from this frame.
|
||||
_ => timestamp + iv,
|
||||
});
|
||||
}
|
||||
|
||||
/// [`due`](Self::due), and [`keep`](Self::keep) if so.
|
||||
pub fn take(&mut self, timestamp: Duration) -> bool {
|
||||
let due = self.due(timestamp);
|
||||
if due {
|
||||
self.keep(timestamp);
|
||||
}
|
||||
due
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies frames into a queue: [`ScreenCapture::start`] of backends that
|
||||
/// deliver into a [`FrameSink`].
|
||||
pub(crate) struct QueueSink {
|
||||
tx: FrameSender<VideoFrame>,
|
||||
fps: u32,
|
||||
pacer: FramePacer,
|
||||
}
|
||||
|
||||
impl QueueSink {
|
||||
pub fn new(options: &CaptureOptions) -> (Self, FrameReceiver<VideoFrame>) {
|
||||
let (tx, rx) = frame_channel(options.queue);
|
||||
let fps = options.fps.max(1);
|
||||
(Self { tx, fps, pacer: FramePacer::new(Some(fps)) }, rx)
|
||||
}
|
||||
}
|
||||
|
||||
impl FrameSink for QueueSink {
|
||||
fn max_fps(&self) -> u32 {
|
||||
self.fps
|
||||
}
|
||||
|
||||
fn wants(&mut self, timestamp: Duration) -> bool {
|
||||
!self.tx.is_closed() && self.pacer.due(timestamp)
|
||||
}
|
||||
|
||||
fn frame(&mut self, frame: FrameRef<'_>) -> bool {
|
||||
self.pacer.keep(frame.timestamp);
|
||||
self.tx.send(frame.to_frame())
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand frames of `frames` to `sink` on a thread of their own, until either
|
||||
/// side stops ([`ScreenCapture::start_sink`] of backends that only have
|
||||
/// [`ScreenCapture::start`]).
|
||||
pub fn forward(mut frames: FrameReceiver<VideoFrame>, mut sink: Box<dyn FrameSink>) -> Result<()> {
|
||||
std::thread::Builder::new().name("voelin-capture-forward".into()).spawn(move || {
|
||||
loop {
|
||||
match frames.recv_timeout(Duration::from_millis(100)) {
|
||||
Some(frame) => {
|
||||
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None if frames.is_closed() => break,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A screen / window capture backend.
|
||||
pub trait ScreenCapture: Send {
|
||||
/// Short name for logs (`"x11"`, `"portal"`, ...).
|
||||
@@ -87,15 +222,38 @@ pub trait ScreenCapture: Send {
|
||||
/// returns a single [`SourceId::Portal`] entry: its dialog picks.
|
||||
fn sources(&mut self) -> Result<Vec<CaptureSource>>;
|
||||
|
||||
/// Start capturing (stopping a previous capture). Async because the
|
||||
/// portal asks the user. Frames stop when [`ScreenCapture::stop`] is
|
||||
/// called, the backend is dropped, or the receiver is dropped.
|
||||
/// Start capturing (stopping a previous capture), copying every frame
|
||||
/// into a queue. Async because the portal asks the user. Frames stop
|
||||
/// when [`ScreenCapture::stop`] is called, the backend is dropped, or the
|
||||
/// receiver is dropped.
|
||||
fn start(
|
||||
&mut self,
|
||||
source: &SourceId,
|
||||
options: &CaptureOptions,
|
||||
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>>;
|
||||
|
||||
/// Start capturing into `sink` (stopping a previous capture): the
|
||||
/// backend calls it on its own thread with the pixels still in the
|
||||
/// capture buffer, and drops it when the capture ends (stopped, the
|
||||
/// source went away, or the sink returned `false`). `options.fps` is
|
||||
/// ignored in favour of [`FrameSink::max_fps`].
|
||||
///
|
||||
/// The default forwards the frames of [`ScreenCapture::start`] from a
|
||||
/// thread of its own.
|
||||
fn start_sink(
|
||||
&mut self,
|
||||
source: &SourceId,
|
||||
options: &CaptureOptions,
|
||||
sink: Box<dyn FrameSink>,
|
||||
) -> BoxFuture<'_, Result<()>> {
|
||||
let source = source.clone();
|
||||
let options = CaptureOptions { fps: sink.max_fps(), ..options.clone() };
|
||||
Box::pin(async move {
|
||||
let frames = self.start(&source, &options).await?;
|
||||
forward(frames, sink)
|
||||
})
|
||||
}
|
||||
|
||||
fn stop(&mut self);
|
||||
}
|
||||
|
||||
@@ -196,6 +354,11 @@ impl Ticker {
|
||||
Self { interval: Duration::from_secs(1) / fps.max(1), next: Instant::now() }
|
||||
}
|
||||
|
||||
/// Change the rate from the next tick on.
|
||||
pub fn set_fps(&mut self, fps: u32) {
|
||||
self.interval = Duration::from_secs(1) / fps.max(1);
|
||||
}
|
||||
|
||||
/// Sleep until the next tick. Returns `false` if `stop` got set.
|
||||
pub fn wait(&mut self, stop: &AtomicBool) -> bool {
|
||||
self.next += self.interval;
|
||||
@@ -232,4 +395,32 @@ mod tests {
|
||||
worker.stop();
|
||||
assert!(started.elapsed() < Duration::from_millis(900));
|
||||
}
|
||||
|
||||
fn kept(pacer: &mut FramePacer, source_fps: f64, jitter_ms: f64, seconds: u32) -> usize {
|
||||
let frames = (source_fps * f64::from(seconds)) as usize;
|
||||
(0..frames)
|
||||
.filter(|&n| {
|
||||
let jitter = if n % 2 == 0 { jitter_ms } else { -jitter_ms };
|
||||
let t = (n as f64 * 1000.0 / source_fps + jitter).max(0.0);
|
||||
pacer.take(Duration::from_secs_f64(t / 1000.0))
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pacer_caps_the_rate() {
|
||||
// 60 Hz source, 30 fps cap: every other frame, even with jitter.
|
||||
assert_eq!(kept(&mut FramePacer::new(Some(30)), 60.0, 1.5, 10), 300);
|
||||
// 144 Hz to 60: close to 60.
|
||||
let n = kept(&mut FramePacer::new(Some(60)), 144.0, 0.5, 10);
|
||||
assert!((580..=610).contains(&n), "{n}");
|
||||
// A cap above the source rate keeps everything.
|
||||
assert_eq!(kept(&mut FramePacer::new(Some(120)), 30.0, 2.0, 10), 300);
|
||||
assert_eq!(kept(&mut FramePacer::new(None), 60.0, 0.0, 1), 60);
|
||||
// A clock that jumps back starts over.
|
||||
let mut pacer = FramePacer::new(Some(10));
|
||||
assert!(pacer.take(Duration::from_secs(100)));
|
||||
assert!(!pacer.take(Duration::from_millis(100_050)));
|
||||
assert!(pacer.take(Duration::from_secs(1)));
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,13 @@
|
||||
//! a desktop-like picture, plus a frame counter) and a sine tone.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::capture::{
|
||||
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, Ticker, Worker,
|
||||
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture,
|
||||
SourceId, Ticker, Worker,
|
||||
};
|
||||
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame};
|
||||
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame};
|
||||
use crate::queue::{FrameReceiver, frame_channel};
|
||||
use crate::{Error, Result};
|
||||
|
||||
@@ -321,24 +322,58 @@ impl ScreenCapture for SyntheticScreen {
|
||||
source: &SourceId,
|
||||
options: &CaptureOptions,
|
||||
) -> BoxFuture<'_, Result<FrameReceiver<VideoFrame>>> {
|
||||
let (sink, rx) = QueueSink::new(options);
|
||||
let started = self.start_sink(source, options, Box::new(sink));
|
||||
Box::pin(async move {
|
||||
started.await?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
|
||||
/// Draws frame after frame into one buffer, at [`FrameSink::max_fps`];
|
||||
/// timestamps are the time since the start.
|
||||
fn start_sink(
|
||||
&mut self,
|
||||
source: &SourceId,
|
||||
_options: &CaptureOptions,
|
||||
mut sink: Box<dyn FrameSink>,
|
||||
) -> BoxFuture<'_, Result<()>> {
|
||||
let source = source.clone();
|
||||
let options = options.clone();
|
||||
Box::pin(async move {
|
||||
if source != SourceId::Synthetic {
|
||||
return Err(Error::SourceNotFound(source));
|
||||
}
|
||||
self.stop();
|
||||
let (tx, rx) = frame_channel(options.queue);
|
||||
let pattern = self.same_pattern();
|
||||
let fps = options.fps;
|
||||
self.worker = Some(Worker::spawn("voelin-synthetic-video", move |stop| {
|
||||
let (width, height) = (pattern.width, pattern.height);
|
||||
let mut fps = sink.max_fps();
|
||||
let mut ticker = Ticker::new(fps);
|
||||
let mut buffer = Vec::new();
|
||||
let started = Instant::now();
|
||||
let mut n = 0;
|
||||
while tx.send(pattern.frame(n, fps)) && ticker.wait(&stop) {
|
||||
n += 1;
|
||||
loop {
|
||||
let timestamp = started.elapsed();
|
||||
if sink.wants(timestamp) {
|
||||
pattern.render(n, &mut buffer);
|
||||
let plane = PlaneRef::new(&buffer, width as usize * 4);
|
||||
let frame =
|
||||
FrameRef { width, height, timestamp, pixels: PixelsRef::Bgra(plane) };
|
||||
if !sink.frame(frame) {
|
||||
break;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
if sink.max_fps() != fps {
|
||||
fps = sink.max_fps();
|
||||
ticker.set_fps(fps);
|
||||
}
|
||||
if !ticker.wait(&stop) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})?);
|
||||
Ok(rx)
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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(())
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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, ®ion, &mut grabber, cursor);
|
||||
if result.is_err() {
|
||||
region_at = Instant::now();
|
||||
if let Ok(r) = x.region(&source) {
|
||||
region = r;
|
||||
result = capture(&x, ®ion, &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, ®ion)?;
|
||||
/// 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)]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -128,6 +128,10 @@ pub struct EncoderConfig {
|
||||
pub content: ContentHint,
|
||||
/// Encoder threads; 0 picks a number from the resolution and CPU count.
|
||||
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 +142,34 @@ impl Default for EncoderConfig {
|
||||
keyframe_interval: None,
|
||||
content: ContentHint::Screen,
|
||||
threads: 0,
|
||||
speed: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EncoderConfig {
|
||||
/// Threads for a `width` x `height` encode (libwebrtc's heuristic).
|
||||
/// Threads for a `width` x `height` encode: all CPUs, but no more than
|
||||
/// one per 320x240 pixels (more would idle on small frames).
|
||||
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 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 +191,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.
|
||||
|
||||
@@ -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,99 @@ 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,
|
||||
}
|
||||
|
||||
// VP8 levels above 10 are no faster on screen content, only worse.
|
||||
const VP8_LEVELS: Levels = Levels { slowest: 4, 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: faster above 75 % of it, slower (better quality)
|
||||
/// below 35 %, deciding every 15 frames on a running mean of the encode
|
||||
/// time (keyframes excluded: they are always slow).
|
||||
pub struct SpeedControl {
|
||||
level: i32,
|
||||
slowest: i32,
|
||||
fastest: i32,
|
||||
/// Mean encode time in seconds.
|
||||
mean: f64,
|
||||
frames: u32,
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
let took = took.as_secs_f64();
|
||||
self.mean = if self.frames == 0 { took } else { self.mean * 0.8 + took * 0.2 };
|
||||
self.frames += 1;
|
||||
if self.frames < Self::WINDOW || interval.is_zero() {
|
||||
return None;
|
||||
}
|
||||
let load = self.mean / interval.as_secs_f64();
|
||||
let level = if load > Self::TOO_SLOW {
|
||||
(self.level + 1).min(self.fastest)
|
||||
} else if load < Self::TOO_FAST {
|
||||
(self.level - 1).max(self.slowest)
|
||||
} else {
|
||||
self.level
|
||||
};
|
||||
if level == self.level {
|
||||
return None;
|
||||
}
|
||||
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 +157,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(¶ms).map_err(|e| self.error(e))?;
|
||||
self.encoder = Some(encoder);
|
||||
@@ -87,19 +176,43 @@ 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 is the time since the previous one (rate control follows a
|
||||
// variable frame rate).
|
||||
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 duration = match self.last_pts {
|
||||
Some(last) if pts <= last => {
|
||||
pts = last + 1;
|
||||
1
|
||||
}
|
||||
Some(last) => ((pts - last) as u64).min(VIDEO_CLOCK_RATE),
|
||||
None => interval,
|
||||
};
|
||||
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 +223,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 +381,50 @@ 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);
|
||||
// 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();
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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, ©, 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> {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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,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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user