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
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user