Files
VoelinClient/crates/voelin-media/src/pool.rs
T
Claude bbfd9aba47 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
2026-09-27 08:35:57 +00:00

101 lines
2.6 KiB
Rust

//! 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);
}
}