Streamer: convert pictures in memory on the GPU too, for VA-API encoders
Measured at 7680x4320@60 with av1_vaapi at 60 Mbit/s, the CPU path made 27 fps: the pyramid converted each frame to I420 on every core (4.6 ms), then the encoder thread interleaved it to NV12 and uploaded it into a VA-API surface on one thread (`encode_with`), 20 ms of its 36.7 ms per frame, so 81 frames in 5 s were dropped. 3840x2160@120 with h264_vaapi made 84 fps the same way. While every encoder takes GPU frames, a picture in memory (shared memory from the portal, X11, wlroots, the studio's composite, the test pattern) now takes the GPU path the DMA-BUFs take: `GpuConverter::convert_memory` copies it as it is (BGRx or RGBx) into a VA-API surface of its own and converts and scales that for every layer. That copy is all the CPU does: 5.7 ms of the 11.9 a 7680x4320 frame takes (the rest is the GPU's upload and conversion), one thread, because eight copying threads saved 2 ms for four times the CPU. Not waiting for the GPU was tried and was slower (36 fps at 8K60 against 42: the encoder then waited instead). The test pattern drew a 7680x4320 frame on one thread (230 MB of copies), which alone kept the bench under 40 fps; it now draws in bands on four threads, which the memory bandwidth limits anyway. Tests: a BGRx and an RGBx picture through the GPU match the CPU's conversion (40.4 dB at full size, 48.7 at half), and a streamer on the test pattern in memory with two `h264_vaapi` layers sends every frame through the GPU and decodes in the right colours (a red-blue swap fails it). The bench's GPU count now covers both kinds of frame. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1f7c16ab27
commit
69152a8ae1
8 files changed
+349
-70
No files matched your search
+121
-28
@@ -707,11 +707,13 @@ pub struct StreamerStats {
|
||||
/// Mean time to convert a captured frame to I420 and scale it for every
|
||||
/// layer that is due, on the CPU.
|
||||
pub convert_time: Duration,
|
||||
/// Captured frames that never reached the CPU: DMA-BUFs converted to
|
||||
/// NV12 and scaled for every layer on the GPU, for VA-API encoders.
|
||||
/// Captured frames converted to NV12 and scaled for every layer on the
|
||||
/// GPU, for VA-API encoders: DMA-BUFs, which the CPU never reads, and
|
||||
/// pictures in memory, which it copies into a surface first.
|
||||
pub gpu_frames: u64,
|
||||
/// Mean time the capture thread spends on such a frame (it waits for
|
||||
/// the GPU, so the buffer can go back to the compositor).
|
||||
/// Mean time the capture thread spends on such a frame (the copy, if
|
||||
/// any, and the wait for the GPU, so the buffer can go back to the
|
||||
/// compositor).
|
||||
pub gpu_convert_time: Duration,
|
||||
/// Why the GPU path stopped (it fell back to the CPU), if it did.
|
||||
pub gpu_error: Option<String>,
|
||||
@@ -1646,6 +1648,15 @@ struct Ingest {
|
||||
gpu: GpuStage,
|
||||
}
|
||||
|
||||
/// What the GPU stage converts: a DMA-BUF, or a picture in memory, which
|
||||
/// it copies into a surface first.
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
#[derive(Clone, Copy)]
|
||||
enum GpuInput<'a, 'b> {
|
||||
Dmabuf(&'a DmaBufRef),
|
||||
Memory(&'a FrameRef<'b>),
|
||||
}
|
||||
|
||||
/// The GPU stage of [`Ingest`].
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
#[derive(Default)]
|
||||
@@ -1705,33 +1716,36 @@ impl Ingest {
|
||||
false
|
||||
}
|
||||
|
||||
/// The GPU stage's converter, made for the first frame; `None` once
|
||||
/// making it (or a conversion) failed.
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
fn gpu_converter(&mut self) -> Option<&mut voelin_media::ffmpeg::GpuConverter> {
|
||||
if self.gpu.converter.is_none() {
|
||||
match voelin_media::ffmpeg::GpuConverter::new() {
|
||||
Ok(converter) => self.gpu.converter = Some(Ok(converter)),
|
||||
Err(e) => {
|
||||
warn!("no GPU conversion of captured frames, the CPU converts them: {e}");
|
||||
*lock(&self.shared.gpu_error) = Some(e.to_string());
|
||||
self.gpu.converter = Some(Err(()));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.gpu.converter.as_mut()?.as_mut().ok()
|
||||
}
|
||||
|
||||
/// Convert DMA-BUF `frame` on the GPU for every layer that is due; `None`
|
||||
/// if it is not taken (the backend maps it for [`FrameSink::frame`]).
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
fn gpu_frame(&mut self, frame: &DmaBufRef) -> Option<bool> {
|
||||
use voelin_media::ffmpeg::{GpuConverter, GpuLayer};
|
||||
|
||||
if self.shared.stopped() {
|
||||
return Some(false);
|
||||
}
|
||||
if !self.gpu_path() {
|
||||
return None;
|
||||
}
|
||||
let shared = self.shared.clone();
|
||||
let converter = match &mut self.gpu.converter {
|
||||
Some(Ok(converter)) => converter,
|
||||
Some(Err(())) => return None,
|
||||
None => match GpuConverter::new() {
|
||||
Ok(converter) => self.gpu.converter.insert(Ok(converter)).as_mut().ok()?,
|
||||
Err(e) => {
|
||||
warn!("no GPU conversion of captured frames, the CPU converts them: {e}");
|
||||
*lock(&shared.gpu_error) = Some(e.to_string());
|
||||
self.gpu.converter = Some(Err(()));
|
||||
return None;
|
||||
}
|
||||
},
|
||||
};
|
||||
self.gpu_converter()?;
|
||||
self.pacer.keep(frame.timestamp);
|
||||
let shared = &self.shared;
|
||||
shared.captured.fetch_add(1, Ordering::Relaxed);
|
||||
shared
|
||||
.size
|
||||
@@ -1739,32 +1753,55 @@ impl Ingest {
|
||||
if shared.sink().is_none() {
|
||||
return Some(true);
|
||||
}
|
||||
self.gpu_convert(GpuInput::Dmabuf(frame));
|
||||
Some(true)
|
||||
}
|
||||
|
||||
/// Convert `input` on the GPU for every layer that is due, into their
|
||||
/// GPU inboxes. A failure turns the GPU stage off: the frame is dropped
|
||||
/// (its layers' pacing taken) and the next one takes the CPU path.
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
fn gpu_convert(&mut self, input: GpuInput<'_, '_>) {
|
||||
use voelin_media::ffmpeg::GpuLayer;
|
||||
|
||||
let ((width, height), timestamp) = match input {
|
||||
GpuInput::Dmabuf(f) => ((f.width, f.height), f.timestamp),
|
||||
GpuInput::Memory(f) => ((f.width, f.height), f.timestamp),
|
||||
};
|
||||
let mut any = false;
|
||||
self.gpu.layers.clear();
|
||||
for l in &mut self.layers {
|
||||
let due = !l.layer.stopped() && l.pacer.take(frame.timestamp);
|
||||
let due = !l.layer.stopped() && l.pacer.take(timestamp);
|
||||
any |= due;
|
||||
let alignment = l.layer.gpu.load(Ordering::Relaxed);
|
||||
self.gpu.layers.push(GpuLayer {
|
||||
size: l.spec.output_size(frame.width, frame.height),
|
||||
size: l.spec.output_size(width, height),
|
||||
alignment: ((alignment >> 32) as u32, alignment as u32),
|
||||
due,
|
||||
});
|
||||
}
|
||||
if !any {
|
||||
return Some(true);
|
||||
return;
|
||||
}
|
||||
self.gpu.out.clear();
|
||||
self.gpu.out.resize(self.layers.len(), None);
|
||||
let Some(Ok(converter)) = &mut self.gpu.converter else { return };
|
||||
let started = Instant::now();
|
||||
if let Err(e) = converter.convert(frame, &self.gpu.layers, &mut self.gpu.out) {
|
||||
let result = match input {
|
||||
GpuInput::Dmabuf(frame) => {
|
||||
converter.convert(frame, &self.gpu.layers, &mut self.gpu.out)
|
||||
}
|
||||
GpuInput::Memory(frame) => {
|
||||
converter.convert_memory(frame, &self.gpu.layers, &mut self.gpu.out)
|
||||
}
|
||||
};
|
||||
let shared = &self.shared;
|
||||
if let Err(e) = result {
|
||||
warn!("GPU conversion failed, the CPU converts captured frames from now on: {e}");
|
||||
*lock(&shared.gpu_error) = Some(e.to_string());
|
||||
self.gpu.converter = Some(Err(()));
|
||||
self.gpu.out.clear();
|
||||
// This frame is counted and its layers' pacing taken: it is
|
||||
// dropped, and the next one takes the CPU path.
|
||||
return Some(true);
|
||||
return;
|
||||
}
|
||||
shared.gpu_convert_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
|
||||
shared.gpu_converted.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -1773,7 +1810,6 @@ impl Ingest {
|
||||
l.layer.gpu_inbox.put(frame);
|
||||
}
|
||||
}
|
||||
Some(true)
|
||||
}
|
||||
|
||||
/// Pick up layer and frame-rate changes.
|
||||
@@ -1896,6 +1932,15 @@ impl FrameSink for Ingest {
|
||||
if shared.sink().is_none() {
|
||||
return true;
|
||||
}
|
||||
// While every encoder takes GPU frames, a picture in memory is
|
||||
// copied into a surface and converted and scaled there.
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
if self.gpu_path()
|
||||
&& self.gpu_converter().is_some_and(|converter| converter.takes(&frame.pixels))
|
||||
{
|
||||
self.gpu_convert(GpuInput::Memory(&frame));
|
||||
return true;
|
||||
}
|
||||
let mut any = false;
|
||||
for (i, l) in self.layers.iter_mut().enumerate() {
|
||||
self.sizes[i] = l.spec.output_size(frame.width, frame.height);
|
||||
@@ -1906,6 +1951,7 @@ impl FrameSink for Ingest {
|
||||
return true;
|
||||
}
|
||||
let started = Instant::now();
|
||||
let shared = &self.shared;
|
||||
if let Err(e) = self.pyramid.process(&frame, &self.sizes, &self.due, &mut self.out) {
|
||||
warn!("cannot convert a captured frame: {e}");
|
||||
shared.set_error(e);
|
||||
@@ -3855,6 +3901,53 @@ mod tests {
|
||||
assert_eq!(stats.gpu_error, None, "a planned switch, not a failure");
|
||||
}
|
||||
|
||||
/// Pictures in memory take the GPU path too while every encoder takes
|
||||
/// GPU frames: copied into a surface and converted and scaled there, in
|
||||
/// the right colours (a red-blue swap would turn the orange rectangle
|
||||
/// blue). Skipped without `h264_vaapi` or an H.264 decoder.
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn memory_frames_take_the_gpu_path_too() {
|
||||
let vaapi = voelin_media::ffmpeg::probe()
|
||||
.iter()
|
||||
.any(|s| s.spec.name == "h264_vaapi" && s.available.is_ok());
|
||||
let codecs = Codecs::new();
|
||||
if !vaapi || codecs.new_decoder(Codec::H264).is_err() {
|
||||
eprintln!("no h264_vaapi or H.264 decoder, skipped");
|
||||
return;
|
||||
}
|
||||
let config = StreamerConfig {
|
||||
source: SourceId::Synthetic,
|
||||
synthetic_size: (640, 360),
|
||||
fps: 30,
|
||||
audio: false,
|
||||
codec: Codec::H264,
|
||||
encoder: EncoderPreference { hardware: true, backend: "h264_vaapi".parse().unwrap() },
|
||||
layers: vec![layer(0, 1.0, None, 1_000_000), layer(5, 0.5, Some(15), 300_000)],
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
let mut source = EncodedSource::new(streamer);
|
||||
let count = |frames: &[EncodedFrame], id| frames.iter().filter(|f| f.layer == id).count();
|
||||
let frames = collect(&mut source, |f| count(f, 0) >= 20 && count(f, 5) >= 5).await;
|
||||
let stats = source.streamer().stats();
|
||||
assert_eq!(stats.gpu_error, None);
|
||||
let on_cpu = stats.captured_frames - stats.gpu_frames;
|
||||
assert!(on_cpu <= 1, "{on_cpu} of {} frames on the CPU", stats.captured_frames);
|
||||
assert_eq!(decoded_size(Codec::H264, &frames, 5), ((320, 180), true));
|
||||
let mut decoder = codecs.new_decoder(Codec::H264).unwrap();
|
||||
let mut picture = None;
|
||||
for f in frames.iter().filter(|f| f.layer == 0) {
|
||||
picture = decoder.decode(&f.data).unwrap().or(picture);
|
||||
}
|
||||
let picture = picture.expect("pictures of layer 0");
|
||||
assert_eq!((picture.width, picture.height), (640, 360));
|
||||
let rgba = voelin_media::convert::to_rgba_vec(&picture).unwrap();
|
||||
let middle = &rgba[180 * 640 * 4..181 * 640 * 4];
|
||||
let orange = middle.chunks_exact(4).any(|p| p[0] > 180 && p[2] < 100);
|
||||
assert!(orange, "no orange rectangle in the middle row");
|
||||
}
|
||||
|
||||
/// Two layers at their own sizes and frame rates, keyframes per layer,
|
||||
/// then a new codec and another layer set while streaming.
|
||||
#[cfg(feature = "media-desktop")]
|
||||
|
||||
@@ -11,6 +11,7 @@ use crate::capture::{
|
||||
};
|
||||
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame};
|
||||
use crate::queue::{FrameReceiver, frame_channel};
|
||||
use crate::workers::{Slots, Workers};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Background colour of the pattern (RGB).
|
||||
@@ -205,13 +206,16 @@ impl Desktop {
|
||||
Self { page, editor, document, document_rows }
|
||||
}
|
||||
|
||||
/// The page with the document scrolled by `offset` rows.
|
||||
fn draw(&self, out: &mut [u8], width: usize, offset: usize) {
|
||||
out[..self.page.len()].copy_from_slice(&self.page);
|
||||
/// Rows `first..` of the page with the document scrolled by `offset`
|
||||
/// rows, into `out` (whole rows).
|
||||
fn draw(&self, out: &mut [u8], width: usize, first: usize, offset: usize) {
|
||||
let start = first * width * 4;
|
||||
out.copy_from_slice(&self.page[start..start + out.len()]);
|
||||
let (ex, ey, ew, eh) = self.editor;
|
||||
for row in 0..eh {
|
||||
let src = (offset + row) % self.document_rows * ew * 4;
|
||||
let dst = ((ey + row) * width + ex) * 4;
|
||||
let rows = first..first + out.len() / (width * 4);
|
||||
for y in rows.start.max(ey)..rows.end.min(ey + eh) {
|
||||
let src = (offset + y - ey) % self.document_rows * ew * 4;
|
||||
let dst = ((y - first) * width + ex) * 4;
|
||||
out[dst..dst + ew * 4].copy_from_slice(&self.document[src..src + ew * 4]);
|
||||
}
|
||||
}
|
||||
@@ -298,28 +302,30 @@ impl SyntheticScreen {
|
||||
/// its memory.
|
||||
pub fn render(&self, n: u64, out: &mut Vec<u8>) {
|
||||
out.resize(self.width as usize * self.height as usize * 4, 0);
|
||||
self.draw(n, out);
|
||||
self.draw(n, out, &mut Workers::new("voelin-synthetic", 1));
|
||||
}
|
||||
|
||||
/// [`render`](Self::render) into the first `width * height * 4` bytes of
|
||||
/// `out`.
|
||||
fn draw(&self, n: u64, out: &mut [u8]) {
|
||||
/// `out`, the background in bands of rows on `workers` (a 7680x4320
|
||||
/// frame is 130 MB to write).
|
||||
fn draw(&self, n: u64, out: &mut [u8], workers: &mut Workers) {
|
||||
let (w, h) = (self.width as usize, self.height as usize);
|
||||
let out = &mut out[..w * h * 4];
|
||||
match &self.desktop {
|
||||
Some(desktop) => desktop.draw(out, w, n as usize * 3),
|
||||
None => {
|
||||
// One row, then copies of it.
|
||||
let px = bgra(BACKGROUND);
|
||||
for d in out[..w * 4].chunks_exact_mut(4) {
|
||||
d.copy_from_slice(&px);
|
||||
}
|
||||
let (first, rest) = out.split_at_mut(w * 4);
|
||||
for row in rest.chunks_exact_mut(w * 4) {
|
||||
row.copy_from_slice(first);
|
||||
let tasks = workers.tasks(h);
|
||||
let band = h.div_ceil(tasks);
|
||||
let bands = Slots::new(out.chunks_mut(band * w * 4).enumerate());
|
||||
let background = bgra(BACKGROUND);
|
||||
workers.run(bands.len(), &|i| {
|
||||
let Some((i, rows)) = bands.take(i) else { return };
|
||||
match &self.desktop {
|
||||
Some(desktop) => desktop.draw(rows, w, i * band, n as usize * 3),
|
||||
None => {
|
||||
for px in rows.chunks_exact_mut(4) {
|
||||
px.copy_from_slice(&background);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let (rx, ry, rw, rh) = self.rect(n);
|
||||
fill(out, w, (rx as usize, ry as usize, rw as usize, rh as usize), RECT_COLOR);
|
||||
// Frame counter in the top-left corner.
|
||||
@@ -386,6 +392,9 @@ impl ScreenCapture for SyntheticScreen {
|
||||
let mut fps = sink.max_fps();
|
||||
let mut ticker = Ticker::new(fps);
|
||||
let mut buffer = Buffer::new(&pattern);
|
||||
// A few threads: drawing is memory-bound, and many threads
|
||||
// cost far more CPU for little time.
|
||||
let mut workers = Workers::new("voelin-synthetic", 4);
|
||||
let started = Instant::now();
|
||||
let mut n = 0;
|
||||
loop {
|
||||
@@ -394,7 +403,7 @@ impl ScreenCapture for SyntheticScreen {
|
||||
// Buffers in video memory are drawn in advance; memory
|
||||
// only for a sink that declines them.
|
||||
if !buffer.drawn_in_advance() {
|
||||
pattern.draw(n, buffer.bytes());
|
||||
pattern.draw(n, buffer.bytes(), &mut workers);
|
||||
}
|
||||
let taken = match buffer.dmabuf(&pattern, n, timestamp) {
|
||||
Some(frame) if sink.accepts_dmabuf() => sink.dmabuf(&frame),
|
||||
@@ -402,7 +411,7 @@ impl ScreenCapture for SyntheticScreen {
|
||||
};
|
||||
let more = taken.unwrap_or_else(|| {
|
||||
if buffer.drawn_in_advance() {
|
||||
pattern.draw(n, buffer.bytes());
|
||||
pattern.draw(n, buffer.bytes(), &mut workers);
|
||||
}
|
||||
let plane = PlaneRef::new(buffer.bytes(), width as usize * 4);
|
||||
sink.frame(FrameRef {
|
||||
|
||||
@@ -2513,6 +2513,52 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
/// A picture in memory, BGRx (a screen) or RGBx (the studio's
|
||||
/// composite), copied into a surface and converted on the GPU: the same
|
||||
/// picture as the CPU's conversion, at full and half size.
|
||||
#[test]
|
||||
fn memory_pictures_are_converted_on_the_gpu() {
|
||||
const SIZE: (u32, u32) = (1280, 720);
|
||||
if !usable("h264_vaapi") {
|
||||
eprintln!("no usable h264_vaapi, skipped");
|
||||
return;
|
||||
}
|
||||
let screen = crate::capture::synthetic::SyntheticScreen::with_pattern(
|
||||
SIZE.0,
|
||||
SIZE.1,
|
||||
crate::capture::synthetic::Pattern::Desktop,
|
||||
);
|
||||
let bgra = screen.frame(7, 30);
|
||||
let FrameData::Bgra(pixels) = &bgra.data else { unreachable!() };
|
||||
let mut swapped = pixels.data.clone();
|
||||
for px in swapped.chunks_exact_mut(4) {
|
||||
px.swap(0, 2);
|
||||
}
|
||||
let rgba = VideoFrame::from_rgba(SIZE.0, SIZE.1, pixels.stride, swapped).unwrap();
|
||||
let cpu = convert::to_i420(&bgra).unwrap().into_owned();
|
||||
let mut half = VideoFrame::black_i420(SIZE.0 / 2, SIZE.1 / 2);
|
||||
let mut workers = crate::workers::Workers::new("voelin-test-scale", 1);
|
||||
crate::scale::scale_i420(&mut workers, &cpu, &mut half).unwrap();
|
||||
let mut converter = GpuConverter::new().expect("VA-API video processing");
|
||||
let layers = [
|
||||
GpuLayer { size: SIZE, alignment: (2, 2), due: true },
|
||||
GpuLayer { size: (SIZE.0 / 2, SIZE.1 / 2), alignment: (2, 2), due: true },
|
||||
];
|
||||
for picture in [&bgra, &rgba] {
|
||||
let mut out = [None, None];
|
||||
assert!(converter.takes(&picture.view().pixels));
|
||||
converter.convert_memory(&picture.view(), &layers, &mut out).expect("converted");
|
||||
for (frame, reference) in out.iter().flatten().zip([&cpu, &half]) {
|
||||
let psnr = convert::psnr(reference, &download(frame)).unwrap();
|
||||
eprintln!("{}x{}: PSNR {psnr:.1} dB against the CPU's", frame.width, frame.height);
|
||||
assert!(psnr > 30.0, "{}x{}: {psnr:.1} dB", frame.width, frame.height);
|
||||
}
|
||||
}
|
||||
// Not RGB: the caller converts it.
|
||||
let i420 = VideoFrame::black_i420(64, 64);
|
||||
assert!(!converter.takes(&i420.view().pixels));
|
||||
}
|
||||
|
||||
/// What the GPU path costs per captured frame: the DMA-BUF import alone,
|
||||
/// and the whole conversion (import, VPP to NV12, the wait for the GPU),
|
||||
/// from a buffer of the driver's own (video memory, tiled) and from a
|
||||
@@ -2527,6 +2573,15 @@ mod tests {
|
||||
eprintln!("no usable h264_vaapi, skipped");
|
||||
return;
|
||||
}
|
||||
// CPU time of every thread of the process.
|
||||
let cpu_time = || -> Duration {
|
||||
let tasks = std::fs::read_dir("/proc/self/task").unwrap().flatten();
|
||||
tasks
|
||||
.filter_map(|t| std::fs::read_to_string(t.path().join("schedstat")).ok())
|
||||
.filter_map(|s| s.split_whitespace().next()?.parse().ok())
|
||||
.map(Duration::from_nanos)
|
||||
.sum()
|
||||
};
|
||||
let ffmpeg = Ffmpeg::get().unwrap();
|
||||
for size in [(1920, 1080), (3840, 2160), (7680, 4320)] {
|
||||
let screen = crate::capture::synthetic::SyntheticScreen::with_pattern(
|
||||
@@ -2579,6 +2634,21 @@ mod tests {
|
||||
convert.as_secs_f64() * 1e3
|
||||
);
|
||||
}
|
||||
// The same picture in memory, copied into a surface.
|
||||
let view = picture.view();
|
||||
converter.convert_memory(&view, &layer, &mut out).unwrap();
|
||||
let (cpu, started) = (cpu_time(), Instant::now());
|
||||
for _ in 0..50 {
|
||||
converter.convert_memory(&view, &layer, &mut out).unwrap();
|
||||
}
|
||||
let (wall, cpu) = (started.elapsed() / 50, (cpu_time() - cpu) / 50);
|
||||
eprintln!(
|
||||
"{}x{} memory: {:.2} ms, {:.2} ms CPU per frame",
|
||||
size.0,
|
||||
size.1,
|
||||
wall.as_secs_f64() * 1e3,
|
||||
cpu.as_secs_f64() * 1e3
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ use super::layout::{self, FrameRefs};
|
||||
use super::sys::{self, FrameHead, Ptr};
|
||||
use super::{Ffmpeg, vpp};
|
||||
use crate::capture::{DRM_MOD_INVALID, DRM_MOD_LINEAR, DmaBufRef, drm_fourcc};
|
||||
use crate::frame::GpuFrame;
|
||||
use crate::frame::{FrameRef, GpuFrame, PixelsRef, PlaneRef};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// The DRM formats of RGB buffers the conversion takes (8 bits per
|
||||
@@ -316,8 +316,12 @@ pub struct GpuConverter {
|
||||
vpp: Option<(vpp::Converter, (u32, u32))>,
|
||||
/// The frames context DMA-BUFs of this size are mapped onto.
|
||||
import: Option<(Ptr, (u32, u32))>,
|
||||
/// Holds a mapping while it is converted.
|
||||
/// Surfaces pictures in memory of this size and format are copied into.
|
||||
upload: Option<(Ptr, (u32, u32), c_int)>,
|
||||
/// Holds a mapping (or an uploaded surface) while it is converted.
|
||||
mapped: Surface,
|
||||
/// An uploaded surface mapped into memory while its rows are written.
|
||||
writable: Surface,
|
||||
outputs: Vec<Output>,
|
||||
modifiers: Vec<u64>,
|
||||
}
|
||||
@@ -341,7 +345,9 @@ impl GpuConverter {
|
||||
display,
|
||||
vpp: None,
|
||||
import: None,
|
||||
upload: None,
|
||||
mapped: Surface::alloc(ffmpeg)?,
|
||||
writable: Surface::alloc(ffmpeg)?,
|
||||
outputs: Vec::new(),
|
||||
modifiers: Vec::new(),
|
||||
};
|
||||
@@ -411,12 +417,96 @@ impl GpuConverter {
|
||||
self.prepare(source)?;
|
||||
let pool = self.import.as_ref().expect("prepared").0;
|
||||
map_dmabuf(self.ffmpeg, frame, pool, self.mapped.0, self.refs).map_err(Error::Convert)?;
|
||||
let result = self.convert_mapped(frame, layers, out);
|
||||
let result = self.convert_mapped(source, frame.timestamp, layers, out);
|
||||
// SAFETY: our frame; this lets the buffer go.
|
||||
unsafe { (self.ffmpeg.api.av_frame_unref)(self.mapped.0) };
|
||||
result
|
||||
}
|
||||
|
||||
/// Whether [`convert_memory`](Self::convert_memory) takes pictures like
|
||||
/// `pixels`: BGRx or RGBx (alpha is ignored).
|
||||
pub fn takes(&self, pixels: &PixelsRef<'_>) -> bool {
|
||||
self.upload_format(pixels).is_some()
|
||||
}
|
||||
|
||||
fn upload_format<'a>(&self, pixels: &PixelsRef<'a>) -> Option<(PlaneRef<'a>, c_int)> {
|
||||
match *pixels {
|
||||
PixelsRef::Bgra(plane) => Some((plane, self.ffmpeg.pix.bgr0?)),
|
||||
PixelsRef::Rgba(plane) => Some((plane, self.ffmpeg.pix.rgb0?)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `frame`, an RGB picture in memory ([`takes`](Self::takes)),
|
||||
/// like [`convert`](Self::convert): it is copied into a surface of its
|
||||
/// own, which the GPU converts and scales for every due layer. That copy
|
||||
/// is all the CPU does, where converting the picture to I420 and scaling
|
||||
/// it on every core, then uploading each layer from its encoder's
|
||||
/// thread, cost several times as much. Measured on a Radeon RX 7900
|
||||
/// GRE: 11.9 ms a 7680x4320 frame, 5.7 ms of it the copy on the CPU and
|
||||
/// the rest the GPU's upload and conversion, waited for. More threads
|
||||
/// copying gained little (9.9 ms with eight) for several times the CPU
|
||||
/// (26 ms), so it is one. Not waiting for the GPU (only before the next
|
||||
/// copy into the same surface) was slower in the streamer: 36 fps at
|
||||
/// 7680x4320 against 42, the encoder then waiting for the conversion.
|
||||
pub fn convert_memory(
|
||||
&mut self,
|
||||
frame: &FrameRef<'_>,
|
||||
layers: &[GpuLayer],
|
||||
out: &mut [Option<Arc<GpuFrame>>],
|
||||
) -> Result<()> {
|
||||
let Some((plane, format)) = self.upload_format(&frame.pixels) else {
|
||||
return Err(Error::Convert("not an RGB picture".into()));
|
||||
};
|
||||
let source = (frame.width, frame.height);
|
||||
let (row, rows) = (frame.width as usize * 4, frame.height as usize);
|
||||
if rows == 0 || plane.stride < row || plane.data.len() < plane.stride * (rows - 1) + row {
|
||||
return Err(Error::InvalidFrame("the picture is smaller than its size".into()));
|
||||
}
|
||||
self.outputs.retain(|o| layers.iter().any(|l| exact_size(l.size, l.alignment) == o.size));
|
||||
self.prepare(source)?;
|
||||
if self.upload.as_ref().is_none_or(|&(_, size, f)| (size, f) != (source, format)) {
|
||||
if let Some((mut pool, ..)) = self.upload.take() {
|
||||
// SAFETY: our reference.
|
||||
unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) };
|
||||
}
|
||||
let pool =
|
||||
vaapi_pool(self.ffmpeg, source.0, source.1, format).map_err(Error::Convert)?;
|
||||
self.upload = Some((pool, source, format));
|
||||
}
|
||||
let pool = self.upload.as_ref().expect("made above").0;
|
||||
let api = &self.ffmpeg.api;
|
||||
let (surface, writable) = (self.mapped.0, self.writable.0);
|
||||
// SAFETY: our frames; `surface` takes a surface of our pool and
|
||||
// `writable` maps it (`format` is the pool's), so its first plane
|
||||
// is `linesize[0]` bytes per row for `height` rows until the unref,
|
||||
// which writes it to the surface (`vaPutImage`).
|
||||
let mapped = unsafe {
|
||||
let ret = (api.av_hwframe_get_buffer)(pool, surface, 0);
|
||||
if ret < 0 {
|
||||
return Err(Error::Convert(format!("VA-API surface: {}", api.error_text(ret))));
|
||||
}
|
||||
(*writable.cast::<FrameHead>()).format = format;
|
||||
let flags = sys::HWFRAME_MAP_WRITE | sys::HWFRAME_MAP_OVERWRITE;
|
||||
let ret = (api.av_hwframe_map)(writable, surface, flags);
|
||||
if ret < 0 {
|
||||
(api.av_frame_unref)(surface);
|
||||
return Err(Error::Convert(format!("mapping a surface: {}", api.error_text(ret))));
|
||||
}
|
||||
let head = &*writable.cast::<FrameHead>();
|
||||
std::slice::from_raw_parts_mut(head.data[0], head.linesize[0] as usize * rows)
|
||||
};
|
||||
for (y, out) in mapped.chunks_exact_mut(mapped.len() / rows).enumerate() {
|
||||
out[..row].copy_from_slice(plane.row(y, row));
|
||||
}
|
||||
// SAFETY: our mapping; unmapping uploads it.
|
||||
unsafe { (api.av_frame_unref)(writable) };
|
||||
let result = self.convert_mapped(source, frame.timestamp, layers, out);
|
||||
// SAFETY: our frame; the surface goes back to the pool.
|
||||
unsafe { (api.av_frame_unref)(surface) };
|
||||
result
|
||||
}
|
||||
|
||||
/// Map `frame` and let it go again: the import alone, for measuring.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn import_only(&mut self, frame: &DmaBufRef) -> Result<()> {
|
||||
@@ -449,9 +539,12 @@ impl GpuConverter {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convert and scale the picture in `mapped`, `size` large, taken at
|
||||
/// `timestamp`, for every due layer.
|
||||
fn convert_mapped(
|
||||
&mut self,
|
||||
frame: &DmaBufRef,
|
||||
size: (u32, u32),
|
||||
timestamp: Duration,
|
||||
layers: &[GpuLayer],
|
||||
out: &mut [Option<Arc<GpuFrame>>],
|
||||
) -> Result<()> {
|
||||
@@ -466,11 +559,8 @@ impl GpuConverter {
|
||||
let part = |full: u32, kept: u32, of: u32| {
|
||||
(u64::from(full) * u64::from(kept) / u64::from(of.max(1))).max(1) as u32
|
||||
};
|
||||
let src = (
|
||||
part(frame.width, exact.0, layer.size.0),
|
||||
part(frame.height, exact.1, layer.size.1),
|
||||
);
|
||||
let gpu = self.output(exact, frame.timestamp)?;
|
||||
let src = (part(size.0, exact.0, layer.size.0), part(size.1, exact.1, layer.size.1));
|
||||
let gpu = self.output(exact, timestamp)?;
|
||||
let (vpp, _) = self.vpp.as_ref().expect("prepared");
|
||||
vpp.convert(input, src, gpu.surface.id(), exact).map_err(Error::Convert)?;
|
||||
*slot = Some(gpu);
|
||||
@@ -528,5 +618,9 @@ impl Drop for GpuConverter {
|
||||
// SAFETY: our reference.
|
||||
unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) };
|
||||
}
|
||||
if let Some((mut pool, ..)) = self.upload.take() {
|
||||
// SAFETY: our reference.
|
||||
unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,8 @@ pub(crate) struct PixFmts {
|
||||
pub drm_prime: Option<c_int>,
|
||||
/// `bgr0`: B, G, R, x in memory, the DRM `XR24` of captured screens.
|
||||
pub bgr0: Option<c_int>,
|
||||
/// `rgb0`: R, G, B, x in memory (`XB24`), the studio's composite.
|
||||
pub rgb0: Option<c_int>,
|
||||
}
|
||||
|
||||
/// libavformat's I/O functions and where a write error lands
|
||||
@@ -130,6 +132,7 @@ impl Ffmpeg {
|
||||
vaapi: api.pix_fmt("vaapi").or_else(|| api.pix_fmt("vaapi_vld")),
|
||||
drm_prime: api.pix_fmt("drm_prime"),
|
||||
bgr0: api.pix_fmt("bgr0"),
|
||||
rgb0: api.pix_fmt("rgb0"),
|
||||
};
|
||||
let hw_fields = layout::codec_hw_fields(&api);
|
||||
let codec_hw_frames = hw_fields.clone().map(|(frames, _)| frames);
|
||||
|
||||
@@ -150,8 +150,10 @@ pub const LOG_QUIET: c_int = -8;
|
||||
pub const LOG_ERROR: c_int = 16;
|
||||
pub const LOG_WARNING: c_int = 24;
|
||||
|
||||
/// `AV_HWFRAME_MAP_READ` and `AV_HWFRAME_MAP_DIRECT`.
|
||||
/// `AV_HWFRAME_MAP_READ`, `_WRITE`, `_OVERWRITE` and `_DIRECT`.
|
||||
pub const HWFRAME_MAP_READ: c_int = 1;
|
||||
pub const HWFRAME_MAP_WRITE: c_int = 2;
|
||||
pub const HWFRAME_MAP_OVERWRITE: c_int = 4;
|
||||
pub const HWFRAME_MAP_DIRECT: c_int = 8;
|
||||
|
||||
/// `AVERROR(EAGAIN)`: FFmpeg errors are negated `errno` values of the C
|
||||
|
||||
+14
-7
@@ -111,13 +111,20 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder
|
||||
the buffer goes straight back to the compositor; the CPU never reads it.
|
||||
Each layer's surface reaches its encoder thread through a second
|
||||
handoff (the thread waits on both) and is encoded as it is
|
||||
(`encode_gpu`). Anything else takes the CPU path as before, and the
|
||||
capture switches between the two by itself: an encoder that needs frames
|
||||
in memory (libvpx, x264, or one made for a viewer of another codec)
|
||||
makes the sink decline the next DMA-BUF, so the portal maps it, and a
|
||||
conversion that fails turns the GPU path off for the capture
|
||||
(`StreamerStats::gpu_error`). Nothing is allocated per frame on this
|
||||
path either (the surfaces' frames are recycled).
|
||||
(`encode_gpu`). A picture in memory (shared memory from the portal, X11,
|
||||
wlroots, the studio's composite, the test pattern) takes the same path
|
||||
while the encoders do: `GpuConverter::convert_memory` copies it into a
|
||||
VA-API surface of its own (one copy on the capture thread, BGRx or RGBx
|
||||
as it is) and converts and scales that, instead of converting it to
|
||||
I420 on every core, scaling it, and uploading each layer on its encoder
|
||||
thread. At 7680x4320 that was more than a frame at 30 fps has (see [the
|
||||
measurements](#60-mbits-up-to-8k-and-320-fps-measured)). Anything else takes the
|
||||
CPU path as before, and the capture switches between the two by itself:
|
||||
an encoder that needs frames in memory (libvpx, x264, or one made for a
|
||||
viewer of another codec) makes the sink decline the next DMA-BUF, so the
|
||||
portal maps it, and a conversion that fails turns the GPU path off for
|
||||
the capture (`StreamerStats::gpu_error`). Nothing is allocated per frame
|
||||
on this path either (the surfaces' frames are recycled).
|
||||
- Simulcast: `StreamerConfig::layers` (`voelin_stream::LayerSpec`; empty:
|
||||
one layer 0 at `bitrate_kbps`) are all encoded, each with its own encoder
|
||||
at `output_size()` of the source, its own frame-rate cap (`max_fps`,
|
||||
|
||||
@@ -340,7 +340,8 @@ struct Sample {
|
||||
layers: Vec<(LayerId, LayerSnapshot)>,
|
||||
sent: u64,
|
||||
captured: u64,
|
||||
/// Captured frames converted on the GPU (never read by the CPU).
|
||||
/// Captured frames converted on the GPU (DMA-BUFs, or pictures in memory
|
||||
/// copied into a surface).
|
||||
gpu: u64,
|
||||
/// Frames the handoffs to the encoders dropped, per layer.
|
||||
dropped: Vec<(LayerId, u64)>,
|
||||
@@ -467,7 +468,7 @@ fn bench(args: BenchArgs) -> Result<()> {
|
||||
let ms = |d: Duration| d.as_secs_f64() * 1000.0;
|
||||
println!(
|
||||
"capture: {:.1} fps; convert + scale: CPU {} frames, {:.2} ms per frame on {} threads; \
|
||||
GPU (DMA-BUF, never read by the CPU) {gpu} frames, {:.2} ms per frame",
|
||||
GPU {gpu} frames, {:.2} ms per frame",
|
||||
captured as f64 / secs,
|
||||
captured - gpu.min(captured),
|
||||
ms(stats.convert_time),
|
||||
|
||||
Reference in new issue
Block a user