perf(codec): passer l'image capturée au GPU sans la recopier
CI / Formatting, tests and builds (push) Failing after 1m22s

L'encodeur matériel recopiait chaque image dans un tampon neuf de 8 Mo
(allocation, défauts de page, copie) avant de la donner à GStreamer.
Le trait VideoEncoder gagne encode_shared, qui reçoit aussi le tampon
partagé de la capture: l'encodeur matériel l'enveloppe tel quel, libvpx
garde son chemin. 2,2 à 3,3 ms de processeur par image 1080p au lieu de
3,7 à 5,8, et l'image encodée sort 2 ms plus tôt.

Hôte entier en 1080p30 H.264: 11 à 13 % d'un cœur au lieu de 17 %,
latence médiane 25 ms. 1080p60: 26 à 27 % au lieu de 35 %.

Refs #57

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guillaume ASSIERandClaude Opus 5.5 committed 2026-10-30 17:46:54 +01:00
1 parent b98640721d
commit fdc180543c
5 files changed
+94 -32

No files matched your search

+9 -4
View File
@@ -28,15 +28,16 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
bitrate_kbps: 6000,
codec,
})?;
let frames: Vec<Vec<u8>> = (0..8)
let frames: Vec<std::sync::Arc<Vec<u8>>> = (0..8)
.map(|n| {
let mut data = vec![235u8; (width * height * 4) as usize];
for (i, b) in data.iter_mut().enumerate().step_by(4 * 7) {
*b = ((i / 4 + n * 3) % 255) as u8;
}
data
std::sync::Arc::new(data)
})
.collect();
let shared = std::env::args().any(|a| a == "--shared");
let cpu = || {
let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default();
let fields: Vec<u64> = stat
@@ -56,12 +57,16 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
for i in 0..count {
let data = &frames[i % frames.len()];
let frame = BgraFrame {
data,
data: &data[..],
width: width as usize,
height: height as usize,
};
let start = Instant::now();
let _ = encoder.encode(&frame);
let _ = if shared {
encoder.encode_shared(&frame, data)
} else {
encoder.encode(&frame)
};
times.push(start.elapsed().as_secs_f64() * 1000.0);
}
let ticks = cpu() - cpu_before;
+19
View File
@@ -85,6 +85,17 @@ pub enum EncodeError {
pub trait VideoEncoder: Send {
/// Encodes a BGRA image and returns the packets produced.
fn encode(&mut self, frame: &BgraFrame) -> Result<Vec<Vec<u8>>, EncodeError>;
/// The same, when the image is a shared buffer (the capture's): an
/// encoder that hands the image to another component, like the GPU's,
/// can keep a reference instead of copying 8 MB per 1080p image (#57).
fn encode_shared(
&mut self,
frame: &BgraFrame,
shared: &std::sync::Arc<Vec<u8>>,
) -> Result<Vec<Vec<u8>>, EncodeError> {
let _ = shared;
self.encode(frame)
}
/// Forces a keyframe on the next frame (new viewer, resume).
fn request_keyframe(&mut self);
fn config(&self) -> EncodeConfig;
@@ -100,6 +111,14 @@ impl VideoEncoder for Box<dyn VideoEncoder> {
(**self).encode(frame)
}
fn encode_shared(
&mut self,
frame: &BgraFrame,
shared: &std::sync::Arc<Vec<u8>>,
) -> Result<Vec<Vec<u8>>, EncodeError> {
(**self).encode_shared(frame, shared)
}
fn request_keyframe(&mut self) {
(**self).request_keyframe();
}
+56 -21
View File
@@ -12,6 +12,7 @@
//! VA-API driver. [`HardwareEncoder::new`] fails cleanly without them, and the
//! caller falls back on libvpx.
use std::sync::Arc;
use std::time::Duration;
use gstreamer as gst;
@@ -120,8 +121,62 @@ impl HardwareEncoder {
}
}
/// A shared image, as GStreamer memory: the buffer keeps the reference, the
/// capture keeps its own, nobody copies.
struct SharedImage(Arc<Vec<u8>>);
impl AsRef<[u8]> for SharedImage {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl VideoEncoder for HardwareEncoder {
fn encode(&mut self, frame: &BgraFrame) -> Result<Vec<Vec<u8>>, EncodeError> {
self.push_and_pull(frame, || gst::Buffer::from_mut_slice(frame.data.to_vec()))
}
fn encode_shared(
&mut self,
frame: &BgraFrame,
shared: &Arc<Vec<u8>>,
) -> Result<Vec<Vec<u8>>, EncodeError> {
if shared.len() != frame.data.len() {
return self.encode(frame);
}
let image = SharedImage(shared.clone());
self.push_and_pull(frame, move || gst::Buffer::from_slice(image))
}
fn request_keyframe(&mut self) {
self.keyframe_requested = true;
}
fn config(&self) -> EncodeConfig {
self.config
}
fn reconfigure(&mut self, width: u32, height: u32) -> Result<(), EncodeError> {
// A new pipeline at the new size, opened before the old one goes: a
// failure leaves the stream as it was. Its first image is a keyframe.
let config = EncodeConfig {
width,
height,
..self.config
};
*self = Self::new(config)?;
Ok(())
}
}
impl HardwareEncoder {
/// Pushes one image, made into a buffer by `buffer`, and takes the access
/// unit it gives.
fn push_and_pull(
&mut self,
frame: &BgraFrame,
buffer: impl FnOnce() -> gst::Buffer,
) -> Result<Vec<Vec<u8>>, EncodeError> {
let expected = self.config.width as usize * self.config.height as usize * 4;
if frame.data.len() != expected {
return Err(EncodeError::Encode(format!(
@@ -138,7 +193,7 @@ impl VideoEncoder for HardwareEncoder {
.build();
self.source.send_event(event);
}
let mut buffer = gst::Buffer::from_mut_slice(frame.data.to_vec());
let mut buffer = buffer();
{
let buffer = buffer.get_mut().ok_or(EncodeError::NoFrame)?;
let pts = self.timestamp();
@@ -172,26 +227,6 @@ impl VideoEncoder for HardwareEncoder {
}
Ok(packets)
}
fn request_keyframe(&mut self) {
self.keyframe_requested = true;
}
fn config(&self) -> EncodeConfig {
self.config
}
fn reconfigure(&mut self, width: u32, height: u32) -> Result<(), EncodeError> {
// A new pipeline at the new size, opened before the old one goes: a
// failure leaves the stream as it was. Its first image is a keyframe.
let config = EncodeConfig {
width,
height,
..self.config
};
*self = Self::new(config)?;
Ok(())
}
}
impl Drop for HardwareEncoder {
+1 -1
View File
@@ -297,7 +297,7 @@ impl LiveSource {
}
};
let encoded = encoder.encode(&view);
let encoded = encoder.encode_shared(&view, &frame.bgra);
if let Some(fps) = cadence.record(work_started.elapsed()) {
tracing::info!(
event = "cadence_changed",
+9 -6
View File
@@ -244,16 +244,19 @@ pourcentage d'un cœur, pour tout le processus: mire peinte, copie, encodage, r
| 1920x1080 | Images affichées | Latence médiane / p95 | Processeur de l'hôte |
| --- | --- | --- | --- |
| VP8 logiciel, 30 i/s (`saver`) | 30 | 39 / 41 ms | 80 % |
| **H.264 matériel**, 30 i/s | 30 | **27 / 29 ms** | **17 %** |
| **H.264 matériel**, 30 i/s | 30 | **25 / 26 ms** | **11 à 13 %** |
| VP9 matériel, 30 i/s | 30 | 31 / 34 ms | 17 % |
| VP9 logiciel, 60 i/s (`balanced`) | 60 | 33 / 49 ms | 112 % |
| **H.264 matériel**, 60 i/s | 60 | 36 / 52 ms | **35 %** |
| **H.264 matériel**, 60 i/s | 60 | 34 à 37 / 37 à 50 ms | **26 à 27 %** |
| VP9 matériel, 60 i/s | 60 | 41 à 54 / 42 à 54 ms | 26 % |
L'encodeur seul (`examples/bench_hardware.rs`): un appel rend l'image encodée en 9,2 ms
(médiane, p95 11,3 ms) en H.264 et 12,6 ms en VP9, pour 4,6 à 5,0 ms de processeur, surtout la
copie de l'image (8 Mo) et son envoi au GPU. À 30 i/s, c'est 14 % d'un cœur: le critère « sous
5 % » de #57 demande de passer les tampons PipeWire au GPU sans copie (DMA-BUF), non fait.
L'encodeur seul (`examples/bench_hardware.rs`): un appel rend l'image encodée en 7 à 9 ms en H.264
(médiane) et 12,6 ms en VP9. Le processeur consommé tombe de 3,7-5,8 ms à 2,2-3,3 ms par image
quand l'image capturée est passée à GStreamer par référence (`encode_shared`) au lieu d'être
recopiée dans un tampon neuf de 8 Mo. Reste l'envoi de l'image au GPU par `vapostproc`: à 30 i/s,
7 à 10 % d'un cœur. Le critère « sous 5 % » de #57 demande d'importer les tampons PipeWire dans
VA-API sans aucune copie (DMA-BUF), non fait. Les chiffres de l'hôte entier comprennent aussi la
mire synthétique, peinte en 1080p à chaque image.
Dans Chromium 155 sans écran (`scripts/bench/chromium.mjs`, qui pilote Chromium par le protocole
DevTools), 1080p60 équilibré: H.264 matériel affiché à 45 i/s (médiane), latence médiane 43 ms;