Merge the zero-copy GPU path for screen capture

A captured RGB DMA-BUF is converted to NV12 and scaled per simulcast
layer on the GPU, into surfaces the VA-API encoders take as they are;
the CPU never reads the frame. Used while every layer's encoder is
VA-API, with the unchanged CPU path otherwise, and switched on the fly.
The portal offers the GPU's tiled layout ahead of LINEAR. Measured with
the test pattern as DMA-BUFs: 1440p60 h264_vaapi at 0.10 cores instead
of 0.34-0.52; a real portal capture through this path is still to run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 11:48:21 +03:00
commit 81eca6236f
16 files changed
+1581 -449

No files matched your search

+344 -28
View File
@@ -45,7 +45,7 @@ pub use voelin_media::capture::playback::{AppMatch, AudioApp, AudioApps};
pub use voelin_media::capture::synthetic::Pattern;
use voelin_media::capture::synthetic::{SineSource, SyntheticScreen};
use voelin_media::capture::{
self, CaptureOptions, CaptureSource, FramePacer, FrameSink, ScreenCapture, SourceId,
self, CaptureOptions, CaptureSource, DmaBufRef, FramePacer, FrameSink, ScreenCapture, SourceId,
};
use voelin_media::handoff::Handoff;
use voelin_media::mix::{
@@ -55,7 +55,10 @@ pub use voelin_media::mix::{Level, SourceState};
use voelin_media::scale::Pyramid;
use voelin_media::studio::Studio;
use voelin_media::studio::output::{Packet, Track};
use voelin_media::{Codec, Codecs, ContentHint, EncoderConfig, FrameRef, VideoEncoder, VideoFrame};
use voelin_media::{
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, VideoEncoder,
VideoFrame,
};
pub use voelin_media::{EncoderBackend, EncoderPreference};
use voelin_stream::{
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
@@ -502,6 +505,11 @@ pub struct StreamerConfig {
pub synthetic_size: (u32, u32),
/// What the test pattern shows.
pub synthetic_pattern: Pattern,
/// Hand the test pattern over as DMA-BUFs of ordinary memory, as the
/// ScreenCast portal hands over the screen
/// ([`SyntheticScreen::with_dmabuf`]): drives the GPU path without a
/// portal (Linux, `/dev/udmabuf`).
pub synthetic_dmabuf: bool,
/// Portal restore token from an earlier share: the desktop may skip its
/// dialog. The new one is [`Streamer::restore_token`].
pub restore_token: Option<String>,
@@ -524,6 +532,7 @@ impl Default for StreamerConfig {
cursor: true,
synthetic_size: (1280, 720),
synthetic_pattern: Pattern::Simple,
synthetic_dmabuf: false,
restore_token: None,
layers: Vec::new(),
}
@@ -612,8 +621,16 @@ pub struct StreamerStats {
pub captured_frames: u64,
pub capture_fps: f64,
/// Mean time to convert a captured frame to I420 and scale it for every
/// layer that is due.
/// 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.
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).
pub gpu_convert_time: Duration,
/// Why the GPU path stopped (it fell back to the CPU), if it did.
pub gpu_error: Option<String>,
/// Frames dropped between conversion and the encoders, all layers.
pub dropped_frames: u64,
/// Threads converting and scaling.
@@ -636,6 +653,12 @@ struct Layer {
spec: Mutex<LayerSpec>,
/// Newest converted frame for the encoder.
inbox: Handoff<VideoFrame>,
/// Newest frame converted on the GPU, instead.
gpu_inbox: Handoff<GpuFrame>,
/// What every encoder of the layer takes GPU frames at, written by the
/// encoder thread: `width << 32 | height` alignment, 0 if one of them
/// needs frames in memory.
gpu: AtomicU64,
/// A keyframe was asked for.
keyframe: AtomicBool,
stop: AtomicBool,
@@ -669,6 +692,8 @@ impl Layer {
id: spec.id,
spec: Mutex::new(spec.clone()),
inbox: Handoff::new(),
gpu_inbox: Handoff::new(),
gpu: AtomicU64::new(0),
keyframe: AtomicBool::new(false),
stop: AtomicBool::new(false),
bitrate: AtomicU64::new(spec.bitrate.max(1)),
@@ -731,6 +756,7 @@ impl Settings {
struct Rates {
capture_fps: f64,
convert_time: Duration,
gpu_convert_time: Duration,
/// Per layer: id, fps, kbit/s, encode time.
layers: Vec<(LayerId, f64, f64, Duration)>,
}
@@ -751,6 +777,10 @@ struct Shared {
converted: AtomicU64,
convert_ns: AtomicU64,
convert_threads: AtomicUsize,
/// Frames converted on the GPU instead, and the time it took.
gpu_converted: AtomicU64,
gpu_convert_ns: AtomicU64,
gpu_error: Mutex<Option<String>>,
/// The layers being encoded, in configuration order.
layers: Mutex<Vec<Arc<Layer>>>,
/// Bumped whenever `layers` or a layer's spec changes.
@@ -959,7 +989,8 @@ impl Streamer {
let (screen, restore_token): (Box<dyn ScreenCapture>, _) = match &config.source {
SourceId::Synthetic => {
let (w, h) = config.synthetic_size;
let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern);
let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern)
.with_dmabuf(config.synthetic_dmabuf);
screen.start_sink(&SourceId::Synthetic, &options, ingest).await?;
(Box::new(screen), None)
}
@@ -1220,6 +1251,9 @@ impl Streamer {
captured_frames: shared.captured.load(Ordering::Relaxed),
capture_fps: rates.capture_fps,
convert_time: rates.convert_time,
gpu_frames: shared.gpu_converted.load(Ordering::Relaxed),
gpu_convert_time: rates.gpu_convert_time,
gpu_error: lock(&shared.gpu_error).clone(),
dropped_frames: layers.iter().map(|l| l.dropped).sum(),
convert_threads: shared.convert_threads.load(Ordering::Relaxed),
codec,
@@ -1487,6 +1521,11 @@ struct IngestLayer {
/// converts and scales them for every layer that is due, and hands each
/// layer's frame to its encoder. Allocates nothing per frame once the
/// frame pools are warm.
///
/// Frames still in a DMA-BUF (the portal's) are converted and scaled on
/// the GPU instead when every encoder of every layer takes GPU frames
/// (VA-API): the CPU never reads them, and the buffer is free again as
/// soon as the GPU is done with it.
struct Ingest {
shared: Arc<Shared>,
pyramid: Pyramid,
@@ -1497,6 +1536,19 @@ struct Ingest {
sizes: Vec<(u32, u32)>,
due: Vec<bool>,
out: Vec<Option<Arc<VideoFrame>>>,
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
gpu: GpuStage,
}
/// The GPU stage of [`Ingest`].
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
#[derive(Default)]
struct GpuStage {
/// Made for the first DMA-BUF; `Err` once it failed (the CPU converts
/// from then on).
converter: Option<Result<voelin_media::ffmpeg::GpuConverter, ()>>,
layers: Vec<voelin_media::ffmpeg::GpuLayer>,
out: Vec<Option<Arc<GpuFrame>>>,
}
impl Ingest {
@@ -1514,9 +1566,98 @@ impl Ingest {
sizes: Vec::new(),
due: Vec::new(),
out: Vec::new(),
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
gpu: GpuStage::default(),
}
}
/// Whether frames go to the GPU: every layer's encoders take GPU frames
/// and the GPU stage has not failed.
fn gpu_path(&self) -> bool {
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
{
!matches!(self.gpu.converter, Some(Err(())))
&& !self.layers.is_empty()
&& self
.layers
.iter()
.all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0)
}
#[cfg(not(all(target_os = "linux", feature = "media-desktop")))]
false
}
/// 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.pacer.keep(frame.timestamp);
shared.captured.fetch_add(1, Ordering::Relaxed);
shared
.size
.store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed);
if shared.sink().is_none() {
return Some(true);
}
let mut any = false;
self.gpu.layers.clear();
for l in &mut self.layers {
let due = !l.layer.stopped() && l.pacer.take(frame.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),
alignment: ((alignment >> 32) as u32, alignment as u32),
due,
});
}
if !any {
return Some(true);
}
self.gpu.out.clear();
self.gpu.out.resize(self.layers.len(), None);
let started = Instant::now();
if let Err(e) = converter.convert(frame, &self.gpu.layers, &mut self.gpu.out) {
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);
}
shared.gpu_convert_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
shared.gpu_converted.fetch_add(1, Ordering::Relaxed);
for (l, out) in self.layers.iter().zip(&mut self.gpu.out) {
if let Some(frame) = out.take() {
l.layer.gpu_inbox.put(frame);
}
}
Some(true)
}
/// Pick up layer and frame-rate changes.
fn refresh(&mut self) {
let fps = self.shared.fps.load(Ordering::Relaxed);
@@ -1560,14 +1701,38 @@ impl FrameSink for Ingest {
if self.shared.stopped() {
return false;
}
let fps = self.shared.fps.load(Ordering::Relaxed);
if fps != self.fps {
self.fps = fps;
self.pacer.set_fps(Some(fps));
}
// Also the layers, which `accepts_dmabuf` (asked next) looks at.
self.refresh();
self.pacer.due(timestamp)
}
fn accepts_dmabuf(&self) -> bool {
self.gpu_path()
}
/// The tiled layout the GPU's own RGB surfaces have, once the GPU stage
/// runs (its first DMA-BUF is LINEAR); none on the CPU path, which
/// cannot read tiled buffers.
fn dmabuf_modifiers(&self) -> &[u64] {
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
if self.gpu_path()
&& let Some(Ok(converter)) = &self.gpu.converter
{
return converter.modifiers();
}
&[]
}
fn dmabuf(&mut self, frame: &DmaBufRef) -> Option<bool> {
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
return self.gpu_frame(frame);
#[cfg(not(all(target_os = "linux", feature = "media-desktop")))]
{
let _ = frame;
None
}
}
fn frame(&mut self, frame: FrameRef<'_>) -> bool {
if self.shared.stopped() {
return false;
@@ -1617,6 +1782,66 @@ impl Drop for Ingest {
}
}
/// A layer's picture: in memory, or on the GPU (converted from a captured
/// DMA-BUF there).
#[derive(Clone)]
enum Picture {
Cpu(Arc<VideoFrame>),
Gpu(Arc<GpuFrame>),
}
impl Picture {
fn size(&self) -> (u32, u32) {
match self {
Self::Cpu(frame) => (frame.width, frame.height),
Self::Gpu(frame) => (frame.width, frame.height),
}
}
/// The same picture `later` after it was captured (a still screen sent
/// again; copies a frame in memory).
fn later(&self, later: Duration) -> Self {
match self {
Self::Cpu(frame) => {
let timestamp = frame.timestamp + later;
Self::Cpu(Arc::new((**frame).clone().with_timestamp(timestamp)))
}
Self::Gpu(frame) => Self::Gpu(Arc::new(frame.at(frame.timestamp + later))),
}
}
}
/// A layer's next picture, from either inbox, or `None` after [`POLL`] or
/// once the layer is closed. The encoder thread is registered with both
/// ([`Handoff::register`]), so a `put` to either wakes it.
fn next_picture(layer: &Layer) -> Option<Picture> {
let deadline = Instant::now() + POLL;
loop {
if let Some(frame) = layer.gpu_inbox.take() {
return Some(Picture::Gpu(frame));
}
if let Some(frame) = layer.inbox.take() {
return Some(Picture::Cpu(frame));
}
let now = Instant::now();
if now >= deadline || layer.inbox.is_closed() {
return None;
}
std::thread::park_timeout(deadline - now);
}
}
/// What every encoder of a layer takes GPU frames at, for [`Layer::gpu`]:
/// the largest alignment of them all, or 0 if one of them takes none.
fn gpu_alignment<'a>(encoders: impl IntoIterator<Item = &'a dyn VideoEncoder>) -> u64 {
let mut alignment = (2, 2);
for encoder in encoders {
let Some((w, h)) = encoder.gpu_alignment() else { return 0 };
alignment = (alignment.0.max(w), alignment.1.max(h));
}
u64::from(alignment.0) << 32 | u64::from(alignment.1)
}
/// One encoder of a layer: its keyframe and bitrate state.
struct LayerEncoder {
codec: Codec,
@@ -1635,7 +1860,7 @@ impl LayerEncoder {
Self { codec: encoder.codec(), encoder: Some(encoder), keyframe_due: true, bitrate: 0, fps }
}
/// Encode `frame` and hand the frames to `sink` (and `studio`'s
/// Encode `picture` and hand the frames to `sink` (and `studio`'s
/// outputs); follows the layer's target bitrate and frame rate first.
#[allow(clippy::too_many_arguments)]
fn encode(
@@ -1644,12 +1869,20 @@ impl LayerEncoder {
layer: &Layer,
sink: &dyn MediaSink,
studio: Option<&Studio>,
frame: &VideoFrame,
picture: &Picture,
requested: bool,
target: u64,
) {
let codec = self.codec;
let Some(encoder) = &mut self.encoder else { return };
if matches!(picture, Picture::Gpu(_)) && encoder.gpu_alignment().is_none() {
// The capture switches to frames in memory once it sees this
// encoder (made for a viewer just now); until then it waits, and
// its first frame then is a keyframe.
self.keyframe_due = true;
return;
}
let (width, height) = picture.size();
if target.abs_diff(self.bitrate) * 100 > self.bitrate {
match encoder.set_bitrate(target.min(u64::from(u32::MAX)) as u32) {
Ok(()) => self.bitrate = target,
@@ -1662,15 +1895,15 @@ impl LayerEncoder {
}
let force = requested || self.keyframe_due;
let mut produced_keyframe = false;
let result = encoder.encode_with(frame, force, &mut |chunk| {
let mut out = |chunk: EncodedChunk<'_>| {
produced_keyframe |= chunk.keyframe;
if let Some(studio) = studio {
studio.write_packet(&Packet {
track: Track::Video { codec, layer: u32::from(layer.id) },
pts_90khz: chunk.pts_90khz,
keyframe: chunk.keyframe,
width: frame.width,
height: frame.height,
width,
height,
data: chunk.data,
});
}
@@ -1688,7 +1921,11 @@ impl LayerEncoder {
layer.bytes.fetch_add(chunk.data.len() as u64, Ordering::Relaxed);
shared.video_frames.fetch_add(1, Ordering::Relaxed);
}
});
};
let result = match picture {
Picture::Cpu(frame) => encoder.encode_with(frame, force, &mut out),
Picture::Gpu(frame) => encoder.encode_gpu(frame, force, &mut out),
};
match result {
Ok(()) => self.keyframe_due = force && !produced_keyframe,
Err(e) => {
@@ -1736,13 +1973,17 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
let mut primary_on = true;
// The last picture, and when it came: a static screen sends no frames,
// so keyframe requests are answered by encoding it again.
let mut last: Option<(Arc<VideoFrame>, Instant)> = None;
let mut last: Option<(Picture, Instant)> = None;
layer.speed.store(
primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from),
Ordering::Relaxed,
);
// The capture may hand over GPU frames once every encoder takes them.
layer.inbox.register();
layer.gpu_inbox.register();
layer.gpu.store(gpu_alignment(primary.encoder.as_deref()), Ordering::Relaxed);
while !shared.stopped() && !layer.stopped() {
let frame = layer.inbox.wait_timeout(POLL);
let picture = next_picture(layer);
if let Some(next) = lock(&layer.next_encoder).take() {
// Another codec: its first frame is a keyframe anyway.
*lock(&layer.backend) = Some(next.backend());
@@ -1785,21 +2026,26 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
codecs.extend(primary_on.then_some(primary.codec));
codecs.extend(extra.iter().filter(|e| e.encoder.is_some()).map(|e| e.codec));
}
// The stream codec's encoder counts even while nobody takes it, so
// the capture does not switch paths as viewers come and go.
let encoders = primary.encoder.as_deref().into_iter();
let gpu = gpu_alignment(encoders.chain(extra.iter().filter_map(|e| e.encoder.as_deref())));
layer.gpu.store(gpu, Ordering::Relaxed);
let requested = layer.keyframe.swap(false, Ordering::Relaxed);
let due = primary_on && primary.keyframe_due
|| extra.iter().any(|e| e.keyframe_due && e.encoder.is_some());
let frame = match frame {
Some(frame) => {
last = Some((frame.clone(), Instant::now()));
frame
let picture = match picture {
Some(picture) => {
last = Some((picture.clone(), Instant::now()));
picture
}
None if requested || due => {
let Some((frame, at)) = &last else {
let Some((picture, at)) = &last else {
layer.keyframe.store(requested, Ordering::Relaxed);
continue;
};
// Same picture, later timestamp (rare: copies the frame).
Arc::new((**frame).clone().with_timestamp(frame.timestamp + at.elapsed()))
// Same picture, later timestamp (rare).
picture.later(at.elapsed())
}
None => continue,
};
@@ -1813,15 +2059,16 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
let started = Instant::now();
if primary_on {
let studio = shared.studio.as_deref();
primary.encode(shared, layer, &*sink, studio, &frame, requested, target);
primary.encode(shared, layer, &*sink, studio, &picture, requested, target);
layer.target.store(primary.bitrate, Ordering::Relaxed);
}
for encoder in &mut extra {
encoder.encode(shared, layer, &*sink, None, &frame, requested, target);
encoder.encode(shared, layer, &*sink, None, &picture, requested, target);
}
layer.encode_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
layer.encoded.fetch_add(1, Ordering::Relaxed);
layer.size.store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed);
let (width, height) = picture.size();
layer.size.store(u64::from(width) << 32 | u64::from(height), Ordering::Relaxed);
layer.speed.store(
primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from),
Ordering::Relaxed,
@@ -1835,6 +2082,8 @@ struct Sample {
captured: u64,
converted: u64,
convert_ns: u64,
gpu_converted: u64,
gpu_convert_ns: u64,
}
/// Once a second: rates for [`Streamer::stats`]; every five seconds a
@@ -1861,11 +2110,15 @@ fn stats_loop(shared: &Shared) {
captured: shared.captured.load(Ordering::Relaxed),
converted: shared.converted.load(Ordering::Relaxed),
convert_ns: shared.convert_ns.load(Ordering::Relaxed),
gpu_converted: shared.gpu_converted.load(Ordering::Relaxed),
gpu_convert_ns: shared.gpu_convert_ns.load(Ordering::Relaxed),
};
let mean = |ns: u64, n: u64| Duration::from_nanos(ns.checked_div(n).unwrap_or(0));
let mut rates = lock(&shared.rates);
rates.capture_fps = (now.captured - last.captured) as f64 / secs;
rates.convert_time = mean(now.convert_ns - last.convert_ns, now.converted - last.converted);
rates.gpu_convert_time =
mean(now.gpu_convert_ns - last.gpu_convert_ns, now.gpu_converted - last.gpu_converted);
rates.layers.clear();
let layers = lock(&shared.layers);
for layer in layers.iter() {
@@ -1912,9 +2165,10 @@ fn stats_loop(shared: &Shared) {
})
.collect();
debug!(
"stream: capture {:.1} fps, convert {:.1} ms, {}",
"stream: capture {:.1} fps, convert {:.1} ms (GPU {:.1} ms), {}",
rates.capture_fps,
rates.convert_time.as_secs_f64() * 1e3,
rates.gpu_convert_time.as_secs_f64() * 1e3,
summary.join(", ")
);
}
@@ -2742,6 +2996,68 @@ mod tests {
(size, first_keyframe == Some(true))
}
/// The test pattern as DMA-BUFs, as the portal hands over the screen:
/// with VA-API encoders on every layer, each frame is converted and
/// scaled on the GPU and none on the CPU; after a switch to libvpx,
/// which needs frames in memory, the CPU converts them again and the
/// stream goes on. Skipped without `h264_vaapi` or `/dev/udmabuf`.
#[cfg(target_os = "linux")]
#[tokio::test(flavor = "multi_thread")]
async fn dmabufs_take_the_gpu_path_while_every_encoder_does() {
let vaapi = voelin_media::ffmpeg::probe()
.iter()
.any(|s| s.spec.name == "h264_vaapi" && s.available.is_ok());
if !vaapi || !std::path::Path::new("/dev/udmabuf").exists() {
eprintln!("no h264_vaapi or /dev/udmabuf, skipped");
return;
}
let codecs = Codecs::new();
let vaapi = EncoderPreference { hardware: true, backend: "h264_vaapi".parse().unwrap() };
let config = StreamerConfig {
source: SourceId::Synthetic,
synthetic_size: (640, 360),
synthetic_dmabuf: true,
fps: 30,
audio: false,
codec: Codec::H264,
encoder: vaapi,
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;
for id in [0, 5] {
assert!(frames.iter().find(|f| f.layer == id).unwrap().keyframe, "layer {id}");
}
let stats = source.streamer().stats();
assert_eq!(stats.gpu_error, None);
assert!(stats.gpu_frames >= 20, "{} frames on the GPU", stats.gpu_frames);
let on_cpu = stats.captured_frames - stats.gpu_frames;
assert!(on_cpu <= 1, "{on_cpu} of {} frames on the CPU", stats.captured_frames);
let sizes: Vec<_> = stats.layers.iter().map(|l| (l.width, l.height)).collect();
assert_eq!(sizes, [(640, 360), (320, 180)]);
let libvpx = EncoderPreference { hardware: false, backend: "libvpx".parse().unwrap() };
let update = StreamerConfigUpdate {
codec: Some(Codec::Vp8),
encoder: Some(libvpx),
..StreamerConfigUpdate::default()
};
source.streamer().reconfigure(&codecs, update).unwrap();
let gpu = source.streamer().stats().gpu_frames;
let frames = collect(&mut source, |f| count(f, 0) >= 40).await;
assert_eq!(decoded_size(Codec::Vp8, &frames, 0), ((640, 360), true));
let stats = source.streamer().stats();
assert!(
stats.gpu_frames <= gpu + 2,
"{} frames on the GPU after the switch",
stats.gpu_frames - gpu
);
assert_eq!(stats.gpu_error, None, "a planned switch, not a failure");
}
/// 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")]
+90 -2
View File
@@ -1,11 +1,13 @@
//! 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).
//! read like this; they go to the GPU (`ffmpeg::GpuConverter`). Also
//! DMA-BUFs of ordinary memory ([`Udmabuf`]), to drive that path without a
//! compositor.
#![allow(unsafe_code)]
use std::io;
use std::os::fd::{BorrowedFd, RawFd};
use std::os::fd::{BorrowedFd, OwnedFd, RawFd};
use memmap2::{Mmap, MmapOptions};
@@ -21,6 +23,92 @@ 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);
/// `struct udmabuf_create` of `<linux/udmabuf.h>`; `UDMABUF_CREATE` returns
/// the new DMA-BUF.
#[repr(C)]
struct UdmabufCreate {
memfd: u32,
flags: u32,
offset: u64,
size: u64,
}
/// `UDMABUF_FLAGS_CLOEXEC`.
const UDMABUF_CLOEXEC: u32 = 1;
// SAFETY: `UDMABUF_CREATE` (`_IOW('u', 0x42, struct udmabuf_create)`) only
// reads the struct and returns a new descriptor.
unsafe impl rustix::ioctl::Ioctl for UdmabufCreate {
type Output = OwnedFd;
const IS_MUTATING: bool = false;
fn opcode(&self) -> rustix::ioctl::Opcode {
rustix::ioctl::opcode::write::<UdmabufCreate>(b'u', 0x42)
}
fn as_ptr(&mut self) -> *mut std::ffi::c_void {
(&raw mut *self).cast()
}
unsafe fn output_from_ptr(
out: rustix::ioctl::IoctlOutput,
_: *mut std::ffi::c_void,
) -> rustix::io::Result<OwnedFd> {
// SAFETY: the descriptor the kernel just made, ours to own.
Ok(unsafe { std::os::fd::FromRawFd::from_raw_fd(out) })
}
}
/// A DMA-BUF of ordinary memory that the CPU writes into: a sealed memfd
/// shared through `/dev/udmabuf` (LINEAR rows, any pitch). What a
/// compositor that renders on the CPU hands over, and the way to drive the
/// DMA-BUF path without one (the test pattern's
/// [`with_dmabuf`](super::synthetic::SyntheticScreen::with_dmabuf)). Needs
/// read and write access to `/dev/udmabuf`.
pub(crate) struct Udmabuf {
map: memmap2::MmapMut,
dmabuf: OwnedFd,
}
impl Udmabuf {
/// A buffer of at least `len` bytes (whole pages).
pub fn new(len: usize) -> io::Result<Self> {
use rustix::fs::{MemfdFlags, SealFlags};
let len = len.max(1).next_multiple_of(4096);
let flags = MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING;
let memfd = std::fs::File::from(rustix::fs::memfd_create("voelin-udmabuf", flags)?);
memfd.set_len(len as u64)?;
// udmabuf only takes memory that cannot shrink under it.
rustix::fs::fcntl_add_seals(&memfd, SealFlags::SHRINK)?;
let device = std::fs::OpenOptions::new().read(true).write(true).open("/dev/udmabuf")?;
let create = UdmabufCreate {
memfd: std::os::fd::AsRawFd::as_raw_fd(&memfd) as u32,
flags: UDMABUF_CLOEXEC,
offset: 0,
size: len as u64,
};
// SAFETY: see the `Ioctl` impl; `device` is /dev/udmabuf.
let dmabuf = unsafe { rustix::ioctl::ioctl(&device, create) }?;
// SAFETY: our own sealed memfd, which nothing else writes or
// truncates; the mapping keeps its pages after the file is closed.
let map = unsafe { memmap2::MmapOptions::new().len(len).map_mut(&memfd) }?;
Ok(Self { map, dmabuf })
}
pub fn fd(&self) -> RawFd {
std::os::fd::AsRawFd::as_raw_fd(&self.dmabuf)
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn bytes_mut(&mut self) -> &mut [u8] {
&mut self.map
}
}
/// The size of DMA-BUF `fd` in bytes (`lseek(fd, 0, SEEK_END)`, which a
/// DMA-BUF answers with its buffer object's size without moving anything).
pub(crate) fn size_of(fd: RawFd) -> Option<usize> {
+10 -1
View File
@@ -28,7 +28,7 @@ use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::{Error, Result};
#[cfg(all(target_os = "linux", feature = "pipewire"))]
mod dmabuf;
pub(crate) mod dmabuf;
pub mod external;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
pub mod pipewire_audio;
@@ -129,6 +129,15 @@ pub trait FrameSink: Send {
let _ = frame;
None
}
/// Tiled DRM format modifiers of RGB buffers the sink takes now
/// ([`accepts_dmabuf`](Self::accepts_dmabuf)), best first; backends that
/// negotiate buffers (the portal) offer them ahead of LINEAR, and offer
/// again when this changes. The CPU cannot read tiled buffers, so a sink
/// lists only what it imports.
fn dmabuf_modifiers(&self) -> &[u64] {
&[]
}
}
/// `fourcc_code(a, b, c, d)` of `drm_fourcc.h`.
+77 -24
View File
@@ -288,6 +288,8 @@ struct VideoState {
fps: u32,
/// Offer DMA-BUFs.
dmabuf: bool,
/// The sink's tiled modifiers the offer was made with (ahead of LINEAR).
modifiers: Vec<u64>,
/// Mappings of the DMA-BUFs PipeWire cycles through.
maps: Vec<DmaBufMap>,
/// Time spent handing DMA-BUF frames to the sink, and how many.
@@ -315,12 +317,15 @@ 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 modifiers = sink.dmabuf_modifiers().to_vec();
let formats = enum_formats(fps, dmabuf, &modifiers)?;
let state = VideoState {
sink,
format: None,
started: Instant::now(),
fps,
dmabuf,
modifiers,
maps: Vec::new(),
dmabuf_time: Duration::ZERO,
dmabuf_frames: 0,
@@ -359,7 +364,6 @@ fn video_stream(
.register()
.map_err(|e| format!("PipeWire listener: {e}"))?;
let formats = enum_formats(fps, dmabuf)?;
let mut pods = formats.iter().map(|f| pod(f)).collect::<std::result::Result<Vec<_>, _>>()?;
stream
.connect(
@@ -397,15 +401,24 @@ fn framerate_range(fps: u32) -> Property {
)
}
fn modifier_property(fixed: bool) -> Property {
/// The modifiers we take, best first: the sink's tiled ones, then LINEAR,
/// which the CPU can always read.
fn our_modifiers(tiled: &[u64]) -> Vec<i64> {
tiled.iter().map(|&m| m as i64).chain([MODIFIER_LINEAR]).collect()
}
/// The modifier property of a DMA-BUF format: a choice of `modifiers` the
/// producer must not fixate (we pick, see [`format_changed`]), or one fixed
/// modifier.
fn modifier_property(modifiers: &[i64], 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)
Value::Long(modifiers[0])
} else {
Value::Choice(ChoiceValue::Long(Choice(
ChoiceFlags::empty(),
ChoiceEnum::Enum { default: MODIFIER_LINEAR, alternatives: vec![MODIFIER_LINEAR] },
ChoiceEnum::Enum { default: modifiers[0], alternatives: modifiers.to_vec() },
)))
};
Property {
@@ -415,6 +428,19 @@ fn modifier_property(fixed: bool) -> Property {
}
}
/// The modifiers a producer's modifier property leaves to choose from.
fn offered_modifiers(prop: &pw::spa::pod::PodProp) -> Vec<i64> {
use pw::spa::pod::deserialize::PodDeserializer;
match PodDeserializer::deserialize_any_from(prop.value().as_bytes()).map(|(_, v)| v) {
Ok(Value::Long(m)) => vec![m],
Ok(Value::Choice(ChoiceValue::Long(Choice(
_,
ChoiceEnum::Enum { default, alternatives },
)))) => std::iter::once(default).chain(alternatives).collect(),
_ => Vec::new(),
}
}
fn format_object(properties: Vec<Property>) -> Value {
Value::Object(Object {
type_: SpaTypes::ObjectParamFormat.as_raw(),
@@ -423,9 +449,15 @@ fn format_object(properties: Vec<Property>) -> Value {
})
}
/// 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> {
/// The formats we offer: each pixel format as a DMA-BUF (if `dmabuf`) with
/// the sink's tiled modifiers ahead of LINEAR, then all of them in shared
/// memory.
fn enum_formats(
fps: u32,
dmabuf: bool,
tiled: &[u64],
) -> std::result::Result<Vec<Vec<u8>>, String> {
let modifiers = our_modifiers(tiled);
let mut formats = Vec::new();
let base = || {
vec![
@@ -437,7 +469,7 @@ fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result<Vec<Vec<u8>>, Str
for format in FORMATS {
let mut properties = base();
properties.push(property!(FormatProperties::VideoFormat, Id, format));
properties.push(modifier_property(false));
properties.push(modifier_property(&modifiers, false));
properties.push(size_range());
properties.push(framerate_range(fps));
formats.push(serialize(format_object(properties))?);
@@ -461,10 +493,10 @@ fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result<Vec<Vec<u8>>, Str
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| {
/// Offer formats again (another frame rate, other modifiers, or no
/// DMA-BUFs); PipeWire renegotiates.
fn renegotiate(stream: &pw::stream::Stream, state: &VideoState) {
let result = enum_formats(state.fps, state.dmabuf, &state.modifiers).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())
@@ -494,12 +526,17 @@ fn format_changed(
.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.
// The producer left the choice to us: the best of ours that it
// can make, else LINEAR.
let theirs = offered_modifiers(prop);
let ours = our_modifiers(&state.modifiers);
let chosen = ours.into_iter().find(|m| theirs.contains(m)).unwrap_or(MODIFIER_LINEAR);
debug!(offered = ?theirs, chosen, "screen capture modifier");
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),
modifier_property(&[chosen], true),
property!(
FormatProperties::VideoSize,
Rectangle,
@@ -539,16 +576,20 @@ fn format_changed(
}
fn process(stream: &pw::stream::Stream, state: &mut VideoState) {
// Follow the sink's frame rate: ask the compositor for another rate.
// Follow the sink: ask the compositor for another rate, or buffers with
// the modifiers the sink takes now.
let fps = state.sink.max_fps().max(1);
if fps != state.fps {
let modifiers = state.sink.dmabuf_modifiers();
if fps != state.fps || (state.dmabuf && modifiers != state.modifiers.as_slice()) {
state.fps = fps;
renegotiate(stream, fps, state.dmabuf);
state.modifiers = modifiers.to_vec();
renegotiate(stream, state);
}
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) && !state.sink.accepts_dmabuf() {
// Tiled: the CPU cannot read it (we only offer LINEAR).
// Tiled, and the sink no longer imports it: the CPU cannot read it.
// The new offer (above) brings LINEAR buffers.
return;
}
let timestamp = state.started.elapsed();
@@ -661,7 +702,7 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) {
"screen capture DMA-BUFs cannot be mapped; switching to shared memory"
);
state.dmabuf = false;
renegotiate(stream, state.fps, false);
renegotiate(stream, state);
}
return;
}
@@ -718,7 +759,7 @@ fn probe_dmabuf(
"reading DMA-BUFs takes {per_pixel:.1} ns per pixel; switching screen capture to shared memory"
);
state.dmabuf = false;
renegotiate(stream, state.fps, false);
renegotiate(stream, state);
}
}
@@ -748,20 +789,32 @@ mod tests {
/// left to us to fixate) per pixel format, then shared memory.
#[test]
fn offered_formats() {
let formats = enum_formats(60, true).unwrap();
// A sink that imports one tiled modifier (an AMD one here).
const TILED: u64 = 0x0200_0000_28a0_1f04;
let formats = enum_formats(60, true, &[TILED]).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();
let modifier = modifier.expect("a modifier");
let flags = modifier.flags();
assert!(flags.contains(PodPropFlags::MANDATORY | PodPropFlags::DONT_FIXATE));
// Read back as a producer's choice is: ours first, LINEAR last.
let offered = offered_modifiers(modifier);
assert_eq!(offered.first(), Some(&(TILED as i64)));
assert_eq!(offered.last(), Some(&MODIFIER_LINEAR));
} 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 linear_only = enum_formats(60, true, &[]).unwrap();
let object = pod(&linear_only[0]).unwrap().as_object().unwrap();
let prop = object.find_prop(Id(FormatProperties::VideoModifier.as_raw())).unwrap();
assert_eq!(offered_modifiers(prop), [MODIFIER_LINEAR, MODIFIER_LINEAR]);
assert_eq!(enum_formats(30, false, &[TILED]).unwrap().len(), 1);
let fixed =
serialize(format_object(vec![modifier_property(&[MODIFIER_LINEAR], 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);
+150 -10
View File
@@ -6,8 +6,8 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::capture::{
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture,
SourceId, Ticker, Worker,
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, DmaBufRef, FrameSink, QueueSink,
ScreenCapture, SourceId, Ticker, Worker,
};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame};
use crate::queue::{FrameReceiver, frame_channel};
@@ -224,6 +224,7 @@ pub struct SyntheticScreen {
pattern: Pattern,
desktop: Option<Arc<Desktop>>,
worker: Option<Worker>,
dmabuf: bool,
}
impl SyntheticScreen {
@@ -236,7 +237,18 @@ impl SyntheticScreen {
let (width, height) = (width.max(16), height.max(16));
let desktop = (pattern == Pattern::Desktop)
.then(|| Arc::new(Desktop::render(width as usize, height as usize)));
Self { width, height, pattern, desktop, worker: None }
Self { width, height, pattern, desktop, worker: None, dmabuf: false }
}
/// Draw into a DMA-BUF of ordinary memory and offer it to sinks that
/// take DMA-BUFs ([`FrameSink::accepts_dmabuf`]) as a LINEAR `XR24`
/// buffer, as the ScreenCast portal does; sinks that do not, or decline
/// it, get the same memory as a frame. Linux with the `pipewire`
/// feature and access to `/dev/udmabuf`; elsewhere frames are handed
/// over as before.
pub fn with_dmabuf(mut self, enabled: bool) -> Self {
self.dmabuf = enabled;
self
}
pub fn pattern(&self) -> Pattern {
@@ -251,6 +263,7 @@ impl SyntheticScreen {
pattern: self.pattern,
desktop: self.desktop.clone(),
worker: None,
dmabuf: self.dmabuf,
}
}
@@ -268,8 +281,15 @@ impl SyntheticScreen {
/// Draw frame `n` as BGRA (`width * 4` bytes per row) into `out`, reusing
/// 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);
}
/// [`render`](Self::render) into the first `width * height * 4` bytes of
/// `out`.
fn draw(&self, n: u64, out: &mut [u8]) {
let (w, h) = (self.width as usize, self.height as usize);
out.resize(w * h * 4, 0);
let out = &mut out[..w * h * 4];
match &self.desktop {
Some(desktop) => desktop.draw(out, w, n as usize * 3),
None => {
@@ -349,17 +369,28 @@ impl ScreenCapture for SyntheticScreen {
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 mut buffer = Buffer::new(&pattern);
let started = Instant::now();
let mut n = 0;
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) {
let bytes = buffer.bytes();
pattern.draw(n, bytes);
let taken = match buffer.dmabuf(&pattern, timestamp) {
Some(frame) if sink.accepts_dmabuf() => sink.dmabuf(&frame),
_ => None,
};
let more = taken.unwrap_or_else(|| {
let plane = PlaneRef::new(buffer.bytes(), width as usize * 4);
sink.frame(FrameRef {
width,
height,
timestamp,
pixels: PixelsRef::Bgra(plane),
})
});
if !more {
break;
}
n += 1;
@@ -382,6 +413,58 @@ impl ScreenCapture for SyntheticScreen {
}
}
/// Where the test pattern is drawn: plain memory, or a DMA-BUF of ordinary
/// memory ([`SyntheticScreen::with_dmabuf`]).
enum Buffer {
Memory(Vec<u8>),
#[cfg(all(target_os = "linux", feature = "pipewire"))]
Dmabuf(super::dmabuf::Udmabuf),
}
impl Buffer {
fn new(pattern: &SyntheticScreen) -> Self {
let len = pattern.width as usize * pattern.height as usize * 4;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
if pattern.dmabuf {
match super::dmabuf::Udmabuf::new(len) {
Ok(buffer) => return Self::Dmabuf(buffer),
Err(e) => tracing::warn!("test pattern without DMA-BUFs (/dev/udmabuf): {e}"),
}
}
Self::Memory(vec![0; len])
}
fn bytes(&mut self) -> &mut [u8] {
match self {
Self::Memory(bytes) => bytes,
#[cfg(all(target_os = "linux", feature = "pipewire"))]
Self::Dmabuf(buffer) => buffer.bytes_mut(),
}
}
/// The buffer as a LINEAR `XR24` DMA-BUF, if it is one.
fn dmabuf(&self, pattern: &SyntheticScreen, timestamp: Duration) -> Option<DmaBufRef> {
match self {
Self::Memory(_) => {
let _ = (pattern, timestamp);
None
}
#[cfg(all(target_os = "linux", feature = "pipewire"))]
Self::Dmabuf(buffer) => Some(DmaBufRef {
width: pattern.width,
height: pattern.height,
timestamp,
fourcc: super::drm_fourcc(b"XR24"),
modifier: super::DRM_MOD_LINEAR,
fd: buffer.fd(),
size: buffer.len(),
planes: [(0, pattern.width as usize * 4), (0, 0), (0, 0), (0, 0)],
plane_count: 1,
}),
}
}
}
/// A sine tone as an [`AudioCapture`] backend: 10 ms stereo buffers.
pub struct SineSource {
frequency: f32,
@@ -523,4 +606,61 @@ mod tests {
assert_eq!((buffer.channels, buffer.frames()), (2, 480));
tone.stop();
}
/// With DMA-BUFs, a sink that takes them gets the pattern as a LINEAR
/// `XR24` DMA-BUF that reads back as the pattern; one that declines it
/// gets the same picture as a frame.
#[cfg(all(target_os = "linux", feature = "pipewire"))]
#[tokio::test]
async fn the_pattern_as_dmabufs() {
use std::sync::mpsc;
/// Takes DMA-BUFs (or declines them) and reports what it got.
struct Sink {
take: bool,
got: mpsc::Sender<(bool, Vec<u8>)>,
}
impl FrameSink for Sink {
fn max_fps(&self) -> u32 {
50
}
fn frame(&mut self, frame: FrameRef<'_>) -> bool {
let PixelsRef::Bgra(plane) = frame.pixels else { panic!("BGRA") };
self.got.send((false, plane.row(0, 64 * 4).to_vec())).is_ok()
}
fn accepts_dmabuf(&self) -> bool {
true
}
fn dmabuf(&mut self, frame: &DmaBufRef) -> Option<bool> {
assert_eq!(frame.fourcc, crate::capture::drm_fourcc(b"XR24"));
assert_eq!((frame.width, frame.height, frame.planes[0].1), (64, 48, 256));
if !self.take {
return None;
}
let map = super::super::dmabuf::DmaBufMap::new(frame.fd, frame.size).unwrap();
let row = map.read(|bytes| bytes[..64 * 4].to_vec());
Some(self.got.send((true, row)).is_ok())
}
}
if !std::path::Path::new("/dev/udmabuf").exists() {
eprintln!("no /dev/udmabuf, skipped");
return;
}
let mut expected = Vec::new();
SyntheticScreen::new(64, 48).render(0, &mut expected);
for take in [true, false] {
let mut screen = SyntheticScreen::new(64, 48).with_dmabuf(true);
let (got, frames) = mpsc::channel();
let sink = Box::new(Sink { take, got });
screen
.start_sink(&SourceId::Synthetic, &CaptureOptions::default(), sink)
.await
.unwrap();
let (dmabuf, row) = frames.recv_timeout(Duration::from_secs(5)).unwrap();
screen.stop();
assert_eq!(dmabuf, take, "taken as a DMA-BUF");
assert_eq!(row, expected[..64 * 4], "the first row of frame 0");
}
}
}
+26
View File
@@ -257,6 +257,32 @@ pub trait VideoEncoder: Send {
fn speed(&self) -> Option<i32> {
None
}
/// Whether this encoder takes [`GpuFrame`](crate::GpuFrame)s
/// ([`encode_gpu`](Self::encode_gpu)), and then the multiple their
/// width and height must be of (a size it encodes exactly; GPU frames
/// are made at that size instead of being cropped here). `None` for
/// encoders that need the pixels in memory: all but VA-API.
fn gpu_alignment(&self) -> Option<(u32, u32)> {
None
}
/// Encode a frame that is in GPU memory, like
/// [`encode_with`](Self::encode_with). Only for encoders with a
/// [`gpu_alignment`](Self::gpu_alignment), and frames of a size that is a
/// multiple of it; the rest fail with `Error::CodecUnavailable`.
fn encode_gpu(
&mut self,
frame: &crate::GpuFrame,
force_keyframe: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
let _ = (frame, force_keyframe, out);
Err(Error::CodecUnavailable {
codec: self.codec(),
reason: format!("{} takes no frames in GPU memory", self.backend()),
})
}
}
/// A video decoder.
+291 -325
View File
@@ -15,6 +15,7 @@ use std::ffi::c_int;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use super::gpu::{self, GpuConverter, GpuLayer, RGB_FOURCCS};
use super::layout::{self, HwFramesFields};
use super::sys::{self, FrameHead, PacketHead, Ptr, Rational, cstr};
use super::{Ffmpeg, take_log, vpp};
@@ -25,7 +26,7 @@ use crate::codec::{
VideoEncoder,
};
use crate::convert;
use crate::frame::{FrameData, VideoFrame};
use crate::frame::{FrameData, GpuFrame, VideoFrame};
use crate::{Error, Result};
/// How a backend takes frames.
@@ -454,7 +455,7 @@ fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result<Ptr, String> {
/// The `VADisplay` of the process's VA-API device (the first field of its
/// `AVVAAPIDeviceContext`).
fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result<vpp::Display, String> {
pub(crate) fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result<vpp::Display, String> {
let device = vaapi_device(ffmpeg)?;
let name = cstr("vaapi");
// SAFETY: a C string; `device` is a live VA-API device reference, whose
@@ -466,6 +467,56 @@ fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result<vpp::Display, String> {
}
}
/// A pool of VA-API surfaces of `sw_format` (an `AVPixelFormat`) and
/// `width` x `height` on the process's device (an `AVHWFramesContext`
/// reference); surfaces are made on demand and recycled.
pub(crate) fn vaapi_pool(
ffmpeg: &Ffmpeg,
width: u32,
height: u32,
sw_format: c_int,
) -> std::result::Result<Ptr, String> {
let api = &ffmpeg.api;
let device = vaapi_device(ffmpeg)?;
let vaapi = ffmpeg.pix.vaapi.ok_or("no VA-API pixel format")?;
// SAFETY: `device` is a live device reference.
let mut pool = unsafe { (api.av_hwframe_ctx_alloc)(device) };
if pool.is_null() {
return Err("av_hwframe_ctx_alloc failed".into());
}
// SAFETY: `pool` was just allocated on `device`.
let fields: HwFramesFields = match unsafe { layout::hw_frames_fields(pool, device) } {
Ok(f) => f,
Err(e) => {
// SAFETY: allocated above.
unsafe { (api.av_buffer_unref)(&mut pool) };
return Err(e);
}
};
// SAFETY: the fields were located and checked on this very context;
// setting them before av_hwframe_ctx_init is what FFmpeg expects.
let ret = unsafe {
let ctx = (*pool.cast::<sys::BufferRefHead>()).data.cast::<std::ffi::c_void>();
layout::write::<c_int>(ctx, fields.format, vaapi);
layout::write::<c_int>(ctx, fields.sw_format, sw_format);
layout::write::<c_int>(ctx, fields.width, width as c_int);
layout::write::<c_int>(ctx, fields.height, height as c_int);
// Surfaces are allocated on demand and recycled by the pool.
layout::write::<c_int>(ctx, fields.initial_pool_size, 0);
(api.av_hwframe_ctx_init)(pool)
};
if ret < 0 {
// SAFETY: allocated above.
unsafe { (api.av_buffer_unref)(&mut pool) };
return Err(format!(
"VA-API surface pool: {}{}",
api.error_text(ret),
log_suffix("AVHWFramesContext")
));
}
Ok(pool)
}
/// FFmpeg's recent messages, appended to an error.
fn log_suffix(context: &str) -> String {
let log = take_log(context);
@@ -527,8 +578,6 @@ struct Session {
opened: Instant,
timestamps: Timestamps,
nv12: bool,
/// RGB DMA-BUFs: made on the first one; why not, if they cannot be.
rgb: Option<std::result::Result<RgbImport, String>>,
/// An AMF encoder: opened and closed under [`amf_lock`].
amf: bool,
}
@@ -552,47 +601,6 @@ fn amf_lock() -> std::sync::MutexGuard<'static, ()> {
AMF.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// What RGB DMA-BUFs need on their way into the session's NV12 surfaces:
/// a frames context of their own size to be mapped onto (FFmpeg gives an
/// imported surface the size of the destination's frames context, and the
/// session's has the coded size), the frame that holds the mapping, and
/// the GPU colour conversion.
struct RgbImport {
pool: Ptr,
mapped: Ptr,
size: (u32, u32),
converter: vpp::Converter,
}
// SAFETY: as `Session`, which owns it.
unsafe impl Send for RgbImport {}
impl Drop for RgbImport {
fn drop(&mut self) {
let api = &Ffmpeg::get().expect("an import exists only with FFmpeg").api;
// SAFETY: both are NULL or ours.
unsafe {
(api.av_frame_free)(&mut self.mapped);
(api.av_buffer_unref)(&mut self.pool);
}
}
}
/// The VA-API surface of a VA-API frame (`data[3]`, `hwcontext_vaapi.h`).
///
/// # Safety
/// `frame` must be a live frame of format `AV_PIX_FMT_VAAPI` holding a
/// surface.
unsafe fn surface_id(frame: Ptr) -> std::ffi::c_uint {
// SAFETY: guaranteed by the caller.
unsafe { (*frame.cast::<FrameHead>()).data[3] as usize as std::ffi::c_uint }
}
/// The DRM formats of RGB buffers the conversion takes (8 bits per
/// channel, 4 bytes per pixel; what screen capture offers).
const RGB_FOURCCS: [u32; 4] =
[drm_fourcc(b"XR24"), drm_fourcc(b"AR24"), drm_fourcc(b"XB24"), drm_fourcc(b"AB24")];
impl Drop for Session {
fn drop(&mut self) {
let api = &Ffmpeg::get().expect("a session exists only with FFmpeg").api;
@@ -640,6 +648,19 @@ pub struct FfmpegEncoder {
/// Sizes it encodes exactly are multiples of these
/// ([`BackendStatus::alignment`]).
alignment: (u32, u32),
/// For RGB DMA-BUFs ([`encode_dmabuf`](Self::encode_dmabuf)): made on
/// the first one; why not, if it cannot be.
gpu: Option<std::result::Result<GpuConverter, String>>,
}
/// `size` cropped to a multiple of `alignment` (even at least, for 4:2:0
/// chroma; at least 2x2): what an encoder of that alignment encodes exactly.
pub(crate) fn exact_size(size: (u32, u32), alignment: (u32, u32)) -> (u32, u32) {
let crop = |v: u32, a: u32| {
let a = a.max(2);
if v >= a { v / a * a } else { (v & !1).max(2) }
};
(crop(size.0, alignment.0), crop(size.1, alignment.1))
}
impl FfmpegEncoder {
@@ -670,6 +691,7 @@ impl FfmpegEncoder {
low_power: false,
dmabuf_checked: false,
alignment,
gpu: None,
})
}
@@ -735,11 +757,10 @@ impl FfmpegEncoder {
}
/// The encoder size: the frame cropped to a multiple of the backend's
/// alignment (even at least, for 4:2:0 chroma), so that the stream
/// declares exactly the picture it carries; at least 2x2.
/// alignment, so that the stream declares exactly the picture it
/// carries ([`exact_size`]).
fn coded_size(&self, width: u32, height: u32) -> (u32, u32) {
let crop = |v: u32, a: u32| if v >= a { v / a * a } else { (v & !1).max(2) };
(crop(width, self.alignment.0), crop(height, self.alignment.1))
exact_size((width, height), self.alignment)
}
/// Open a session for `width` x `height`.
@@ -791,7 +812,7 @@ impl FfmpegEncoder {
opened: Instant::now(),
timestamps: Timestamps::new(),
nv12: self.spec.input != Input::Yuv420p,
rgb: None,
amf: false,
};
// SAFETY: `ctx` is a live codec context; the first child is its
@@ -863,7 +884,8 @@ impl FfmpegEncoder {
self.apply(ctx, private, setting)?;
}
if self.spec.is_vaapi() {
session.pool = self.vaapi_pool(width, height, self.ffmpeg.pix.nv12)?;
session.pool = vaapi_pool(self.ffmpeg, width, height, self.ffmpeg.pix.nv12)
.map_err(|e| self.unavailable(e))?;
let offset = self.ffmpeg.codec_hw_frames.clone().map_err(|e| self.unavailable(e))?;
// SAFETY: `offset` is AVCodecContext.hw_frames_ctx (checked at
// load); the context takes the new reference and frees it.
@@ -919,45 +941,6 @@ impl FfmpegEncoder {
/// A VA-API surface pool of `sw_format` (an `AVPixelFormat`) for `width`
/// x `height`.
fn vaapi_pool(&self, width: u32, height: u32, sw_format: c_int) -> Result<Ptr> {
let api = &self.ffmpeg.api;
let device = vaapi_device(self.ffmpeg).map_err(|e| self.unavailable(e))?;
let vaapi =
self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API format".into()))?;
// SAFETY: `device` is a live device reference.
let mut pool = unsafe { (api.av_hwframe_ctx_alloc)(device) };
if pool.is_null() {
return Err(self.unavailable("av_hwframe_ctx_alloc failed".into()));
}
// SAFETY: `pool` was just allocated on `device`.
let fields: HwFramesFields = match unsafe { layout::hw_frames_fields(pool, device) } {
Ok(f) => f,
Err(e) => {
// SAFETY: allocated above.
unsafe { (api.av_buffer_unref)(&mut pool) };
return Err(self.unavailable(e));
}
};
// SAFETY: the fields were located and checked on this very context;
// setting them before av_hwframe_ctx_init is what FFmpeg expects.
let ret = unsafe {
let ctx = (*pool.cast::<sys::BufferRefHead>()).data.cast::<std::ffi::c_void>();
layout::write::<c_int>(ctx, fields.format, vaapi);
layout::write::<c_int>(ctx, fields.sw_format, sw_format);
layout::write::<c_int>(ctx, fields.width, width as c_int);
layout::write::<c_int>(ctx, fields.height, height as c_int);
// Surfaces are allocated on demand and recycled by the pool.
layout::write::<c_int>(ctx, fields.initial_pool_size, 0);
(api.av_hwframe_ctx_init)(pool)
};
if ret < 0 {
// SAFETY: allocated above.
unsafe { (api.av_buffer_unref)(&mut pool) };
return Err(self.error("VA-API surface pool", ret));
}
Ok(pool)
}
/// Copy the I420 picture into the session's frame (cropped to the coded
/// size; NV12 interleaved where the backend wants it).
fn fill(&self, session: &Session, frame: &VideoFrame) -> Result<()> {
@@ -1132,9 +1115,8 @@ impl FfmpegEncoder {
/// (their size must be one it encodes exactly), and stay in use until
/// this frame's packet came out (the encoder reads them one frame deep).
/// RGB buffers (`XR24`, `AR24`, `XB24`, `AB24`: what screen capture
/// delivers) are converted into the session's NV12 surfaces on the GPU
/// (VA-API video processing), cropped to the coded size, and
/// are no longer read when this returns.
/// delivers) are converted to NV12 on the GPU ([`GpuConverter`]), cropped
/// to the coded size, and are no longer read when this returns.
///
/// Anything else fails with `Error::CodecUnavailable`; callers then map
/// the buffer and use [`encode_with`](VideoEncoder::encode_with).
@@ -1147,11 +1129,35 @@ impl FfmpegEncoder {
if !self.spec.is_vaapi() {
return Err(self.unavailable(format!("{} does not import DMA-BUFs", self.spec.name)));
}
let rgb = RGB_FOURCCS.contains(&frame.fourcc) && frame.plane_count == 1;
if !rgb && (frame.fourcc != drm_fourcc(b"NV12") || frame.plane_count != 2) {
if RGB_FOURCCS.contains(&frame.fourcc) && frame.plane_count == 1 {
let converter = match self
.gpu
.get_or_insert_with(|| GpuConverter::new().map_err(|e| e.to_string()))
{
Ok(converter) => converter,
Err(e) => {
return Err(Error::CodecUnavailable {
codec: self.spec.codec,
reason: e.clone(),
});
}
};
let layer = GpuLayer {
size: (frame.width, frame.height),
alignment: self.alignment,
due: true,
};
let mut converted = [None];
if let Err(e) = converter.convert(frame, &[layer], &mut converted) {
return Err(self.unavailable(e.to_string()));
}
let gpu = converted[0].take().expect("a due layer gets a frame");
return self.encode_gpu(&gpu, force_keyframe, out);
}
if frame.fourcc != drm_fourcc(b"NV12") || frame.plane_count != 2 {
return Err(self.unavailable("only NV12 and RGB DMA-BUFs are imported".into()));
}
if !rgb && self.coded_size(frame.width, frame.height) != (frame.width, frame.height) {
if self.coded_size(frame.width, frame.height) != (frame.width, frame.height) {
return Err(self.unavailable(format!(
"{}x{} is not a size {} encodes exactly",
frame.width, frame.height, self.spec.name
@@ -1159,16 +1165,16 @@ impl FfmpegEncoder {
}
let refs = self.ffmpeg.frame_refs.clone().map_err(|e| self.unavailable(e))?;
let (mut session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?;
let result = self.import_and_send(&mut session, frame, rgb, force, refs, out);
let result = self.import_and_send(&mut session, frame, force, refs, out);
self.session = Some(session);
result
}
/// Map an NV12 DMA-BUF onto a surface of the session and encode it.
fn import_and_send(
&mut self,
session: &mut Session,
frame: &DmaBufRef,
rgb: bool,
force: bool,
refs: layout::FrameRefs,
out: &mut dyn FnMut(EncodedChunk<'_>),
@@ -1189,35 +1195,25 @@ impl FfmpegEncoder {
}
self.dmabuf_checked = true;
}
let (pool, hw) = (session.pool, session.hw);
if rgb {
let import = self.rgb_import(session, frame)?;
self.map_dmabuf(frame, import.pool, import.mapped, refs)?;
// SAFETY: `hw` is our frame (unreferenced after each frame), the
// pool the session's; both surfaces belong to the process's
// device, the converter's display.
let converted = unsafe {
let ret = (api.av_hwframe_get_buffer)(pool, hw, 0);
let converted = if ret < 0 {
Err(self.error("VA-API surface", ret))
} else {
let done = import.converter.convert(surface_id(import.mapped), surface_id(hw));
done.map_err(|e| self.unavailable(e))
};
// The buffer has been read: the mapping can go.
(api.av_frame_unref)(import.mapped);
converted
};
if let Err(e) = converted {
// SAFETY: our frame.
unsafe { (api.av_frame_unref)(hw) };
return Err(e);
}
} else {
self.map_dmabuf(frame, pool, hw, refs)?;
}
let hw = session.hw;
gpu::map_dmabuf(self.ffmpeg, frame, session.pool, hw, refs).map_err(|e| {
Error::Encoder { codec: self.spec.codec, message: format!("{}: {e}", self.spec.name) }
})?;
let pts =
self.stamp(session, frame.timestamp, (frame.timestamp.as_micros() * 9 / 100) as u64);
self.send_surface(session, pts, force, out)
}
/// Encode the surface in `session.hw` (taken from the session's frame
/// afterwards; the encoder keeps its own reference while it needs it).
fn send_surface(
&self,
session: &mut Session,
pts: i64,
force: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
let hw = session.hw;
let pict_type = if force { sys::PICTURE_TYPE_I } else { sys::PICTURE_TYPE_NONE };
// SAFETY: offsets checked at load for this release's AVFrame; `hw`
// holds a surface until the unref.
@@ -1226,103 +1222,11 @@ impl FfmpegEncoder {
layout::write::<c_int>(hw, self.ffmpeg.frame.pict_type, pict_type);
}
let result = self.send(session, hw, out);
// SAFETY: our frame; the encoder holds its own reference.
unsafe { (api.av_frame_unref)(hw) };
// SAFETY: our frame.
unsafe { (self.ffmpeg.api.av_frame_unref)(hw) };
result.map(|_| ())
}
/// The session's [`RgbImport`] for `frame`, made on first use (again
/// when the buffers change size within the session's coded size).
fn rgb_import<'s>(&self, session: &'s mut Session, frame: &DmaBufRef) -> Result<&'s RgbImport> {
let size = (frame.width, frame.height);
let stale = match &session.rgb {
None => true,
Some(Ok(import)) => import.size != size,
Some(Err(_)) => false,
};
if stale {
session.rgb = None;
session.rgb = Some(self.new_rgb_import(size, (session.width, session.height)));
}
match session.rgb.as_ref().expect("made above") {
Ok(import) => Ok(import),
Err(e) => Err(self.unavailable(e.clone())),
}
}
fn new_rgb_import(
&self,
size: (u32, u32),
coded: (u32, u32),
) -> std::result::Result<RgbImport, String> {
let bgr0 = self.ffmpeg.pix.bgr0.ok_or("no bgr0 pixel format")?;
let display = vaapi_display(self.ffmpeg)?;
let converter = vpp::Converter::new(display, coded.0, coded.1)?;
let pool = self.vaapi_pool(size.0, size.1, bgr0).map_err(|e| e.to_string())?;
// SAFETY: an allocation (NULL is freed as nothing by the drop).
let mapped = unsafe { (self.ffmpeg.api.av_frame_alloc)() };
let import = RgbImport { pool, mapped, size, converter };
if import.mapped.is_null() { Err("out of memory".into()) } else { Ok(import) }
}
/// Map DMA-BUF `frame` onto a VA-API surface in `dst` (one of our
/// frames), which gets a reference to `pool`: the import takes that
/// frames context's size and device.
fn map_dmabuf(
&self,
frame: &DmaBufRef,
pool: Ptr,
dst: Ptr,
refs: layout::FrameRefs,
) -> Result<()> {
let api = &self.ffmpeg.api;
let drm_prime =
self.ffmpeg.pix.drm_prime.ok_or_else(|| self.unavailable("no DRM PRIME".into()))?;
let vaapi = self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API".into()))?;
let mut descriptor =
sys::DrmFrameDescriptor { nb_objects: 1, nb_layers: 1, ..Default::default() };
descriptor.objects[0] =
sys::DrmObject { fd: frame.fd, size: frame.size, format_modifier: frame.modifier };
descriptor.layers[0].format = frame.fourcc;
descriptor.layers[0].nb_planes = frame.plane_count as c_int;
for (plane, &(offset, pitch)) in
descriptor.layers[0].planes.iter_mut().zip(&frame.planes[..frame.plane_count])
{
*plane =
sys::DrmPlane { object_index: 0, offset: offset as isize, pitch: pitch as isize };
}
// SAFETY: the descriptor lives in a buffer the source frame owns
// (buf[0], checked offset), so FFmpeg can keep it while mapped; the
// destination frame gets a reference to the pool at the checked
// hw_frames_ctx offset; av_frame_free / av_frame_unref release both.
unsafe {
let mut buffer = (api.av_buffer_allocz)(std::mem::size_of::<sys::DrmFrameDescriptor>());
let mut src = (api.av_frame_alloc)();
if buffer.is_null() || src.is_null() {
(api.av_buffer_unref)(&mut buffer);
(api.av_frame_free)(&mut src);
return Err(self.unavailable("out of memory".into()));
}
let data = (*buffer.cast::<sys::BufferRefHead>()).data;
data.cast::<sys::DrmFrameDescriptor>().write(descriptor);
let head = src.cast::<FrameHead>();
(*head).format = drm_prime;
(*head).width = frame.width as c_int;
(*head).height = frame.height as c_int;
(*head).data[0] = data;
layout::write::<Ptr>(src, refs.buf, buffer);
(*dst.cast::<FrameHead>()).format = vaapi;
layout::write::<Ptr>(dst, refs.hw_frames_ctx, (api.av_buffer_ref)(pool));
let ret = (api.av_hwframe_map)(dst, src, sys::HWFRAME_MAP_READ);
(api.av_frame_free)(&mut src);
if ret < 0 {
(api.av_frame_unref)(dst);
return Err(self.error("DMA-BUF import", ret));
}
}
Ok(())
}
/// The pts of a frame taken at `timestamp`: frame numbers at the
/// session's rate (its time base), strictly increasing; remembered with
/// the 90 kHz time for the packets.
@@ -1508,6 +1412,45 @@ impl VideoEncoder for FfmpegEncoder {
}
Ok(())
}
/// VA-API encoders take NV12 surfaces of the sizes they encode exactly.
fn gpu_alignment(&self) -> Option<(u32, u32)> {
self.spec.is_vaapi().then_some(self.alignment)
}
/// The surface goes to the encoder as it is: the encoder takes a
/// reference, so it stays out of its pool until the encoder is done.
fn encode_gpu(
&mut self,
frame: &GpuFrame,
force_keyframe: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
if !self.spec.is_vaapi() {
return Err(self.unavailable(format!("{} takes no VA-API surfaces", self.spec.name)));
}
if frame.surface.0.is_null() {
return Err(self.unavailable("a GPU frame without a surface (out of memory)".into()));
}
if self.coded_size(frame.width, frame.height) != (frame.width, frame.height) {
return Err(self.unavailable(format!(
"{}x{} is not a size {} encodes exactly",
frame.width, frame.height, self.spec.name
)));
}
let (mut session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?;
let pts = self.stamp(&mut session, frame.timestamp, frame.pts_90khz());
// SAFETY: `hw` is our frame, unreferenced after each frame;
// `surface` is a live VA-API frame of the same device.
let ret = unsafe { (self.ffmpeg.api.av_frame_ref)(session.hw, frame.surface.0) };
let result = if ret < 0 {
Err(self.error("GPU frame", ret))
} else {
self.send_surface(&mut session, pts, force, out)
};
self.session = Some(session);
result
}
}
/// A gradient test picture.
@@ -2102,8 +2045,7 @@ mod tests {
) -> Self {
let ffmpeg = Ffmpeg::get().unwrap();
let api = &ffmpeg.api;
let encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap();
let pool = encoder.vaapi_pool(width, height, sw_format).expect("a VA-API surface pool");
let pool = vaapi_pool(ffmpeg, width, height, sw_format).expect("a VA-API surface pool");
// SAFETY: `pool` is a live frames context of this process's
// VA-API device; the frames are ours and freed by the drop. The
// exported frame's `data[0]` is the AVDRMFrameDescriptor FFmpeg
@@ -2190,6 +2132,113 @@ mod tests {
}
}
/// The picture of a GPU frame, read back into memory as I420.
fn download(frame: &GpuFrame) -> VideoFrame {
let ffmpeg = Ffmpeg::get().unwrap();
let api = &ffmpeg.api;
let (w, h) = (frame.width as usize, frame.height as usize);
let mut out = VideoFrame::black_i420(frame.width, frame.height);
let FrameData::I420 { y, u, v } = &mut out.data else { unreachable!() };
// SAFETY: `sw` is ours and freed below; a downloaded plane holds
// `linesize * rows` bytes.
unsafe {
let mut sw = (api.av_frame_alloc)();
(*sw.cast::<FrameHead>()).format = ffmpeg.pix.nv12;
assert!((api.av_hwframe_transfer_data)(sw, frame.surface.0, 0) >= 0, "download");
let head = &*sw.cast::<FrameHead>();
let rows = |i: usize, rows: usize| {
let stride = head.linesize[i] as usize;
std::slice::from_raw_parts(head.data[i], stride * rows).chunks_exact(stride)
};
for (row, src) in rows(0, h).enumerate() {
y.data[row * w..][..w].copy_from_slice(&src[..w]);
}
let cw = w / 2;
for (row, src) in rows(1, h / 2).enumerate() {
for (i, pair) in src[..cw * 2].chunks_exact(2).enumerate() {
u.data[row * u.stride + i] = pair[0];
v.data[row * v.stride + i] = pair[1];
}
}
(api.av_frame_free)(&mut sw);
}
out
}
/// One captured RGB DMA-BUF made into a GPU frame per simulcast layer:
/// full size, half and a fixed 640x360 at AV1's alignment, each the
/// whole picture scaled (cropped to the alignment) as the CPU pyramid
/// does it, and each encoded by `h264_vaapi` straight from its surface
/// and decoded. The frames are recycled once nothing holds them.
#[test]
fn gpu_frames_for_every_layer() {
const SIZE: (u32, u32) = (1280, 720);
if !usable("h264_vaapi") {
eprintln!("no usable h264_vaapi, skipped");
return;
}
let ffmpeg = Ffmpeg::get().unwrap();
let screen = crate::capture::synthetic::SyntheticScreen::with_pattern(
SIZE.0,
SIZE.1,
crate::capture::synthetic::Pattern::Desktop,
);
let picture = screen.frame(5, 30);
let rgb =
Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture));
let mut converter = GpuConverter::new().expect("VA-API video processing");
eprintln!("tiled RGB modifiers the import takes: {:x?}", converter.modifiers());
let layers = [
GpuLayer { size: SIZE, alignment: (2, 2), due: true },
GpuLayer { size: (640, 360), alignment: (64, 16), due: true },
GpuLayer { size: (320, 180), alignment: (2, 2), due: false },
];
let mut out = [None, None, None];
converter.convert(&rgb.frame, &layers, &mut out).expect("converted");
assert!(out[2].is_none(), "a layer that is not due gets nothing");
let sizes: Vec<_> = out.iter().flatten().map(|f| (f.width, f.height)).collect();
assert_eq!(sizes, [SIZE, (640, 352)], "cropped to the alignment");
let cpu = convert::to_i420(&picture).unwrap().into_owned();
let mut half = VideoFrame::black_i420(640, 360);
let mut workers = crate::workers::Workers::new("voelin-test-scale", 1);
crate::scale::scale_i420(&mut workers, &cpu, &mut half).unwrap();
for frame in out.iter().flatten() {
// The CPU's picture at the layer's size, cropped the same way.
let reference = if (frame.width, frame.height) == SIZE { &cpu } else { &half };
let mut cropped = reference.view();
(cropped.width, cropped.height) = (frame.width, frame.height);
let gpu = download(frame);
let psnr = convert::psnr(&cropped.to_frame(), &gpu).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);
let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap();
let mut decoder = decoder(Codec::H264);
let mut packets = 0;
encoder
.encode_gpu(frame, true, &mut |chunk| {
packets += 1;
if let Some(decoder) = &mut decoder {
let decoded = decoder.decode(chunk.data).unwrap().expect("a picture");
assert_eq!((decoded.width, decoded.height), (frame.width, frame.height));
let psnr = convert::psnr(&gpu, &decoded).unwrap();
assert!(psnr > 30.0, "decoded at {psnr:.1} dB");
}
})
.expect("encoded from the surface");
assert!(packets > 0);
}
// Once nothing holds them, the same frames come back.
let first: Vec<*const GpuFrame> =
out.iter().flatten().map(std::sync::Arc::as_ptr).collect();
out = [None, None, None];
converter.convert(&rgb.frame, &layers, &mut out).expect("converted again");
let again: Vec<*const GpuFrame> =
out.iter().flatten().map(std::sync::Arc::as_ptr).collect();
assert_eq!(first, again, "recycled");
}
/// Our decoder for `codec`, if this build and machine have one: OpenH264
/// with `VOELIN_OPENH264_LIB`, dav1d with `--features av1`.
fn decoder(codec: Codec) -> Option<Box<dyn crate::codec::VideoDecoder>> {
@@ -2255,7 +2304,6 @@ mod tests {
return;
}
let ffmpeg = Ffmpeg::get().unwrap();
let api = &ffmpeg.api;
let screen = crate::capture::synthetic::SyntheticScreen::with_pattern(
SIZE.0,
SIZE.1,
@@ -2267,45 +2315,21 @@ mod tests {
assert_eq!(rgb.frame.plane_count, 1);
// The conversion alone: the GPU's NV12 against the CPU's I420.
let converter =
vpp::Converter::new(vaapi_display(ffmpeg).unwrap(), SIZE.0, SIZE.1).unwrap();
let encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap();
let mut pool = encoder.vaapi_pool(SIZE.0, SIZE.1, ffmpeg.pix.nv12).unwrap();
let mut converter = GpuConverter::new().expect("VA-API video processing");
let layer = GpuLayer { size: SIZE, alignment: (2, 2), due: true };
let mut converted = [None];
converter.convert(&rgb.frame, &[layer], &mut converted).expect("converted");
let downloaded = download(converted[0].as_ref().unwrap());
drop((converted, converter));
let cpu = convert::to_i420(&picture).unwrap();
let FrameData::I420 { y, u, v } = &cpu.data else { unreachable!() };
let FrameData::I420 { y: gy, u: gu, v: gv } = &downloaded.data else { unreachable!() };
let (w, h, cw, ch) =
(SIZE.0 as usize, SIZE.1 as usize, SIZE.0 as usize / 2, SIZE.1 as usize / 2);
let mut gpu = [Vec::new(), Vec::new(), Vec::new()];
// SAFETY: frames and pool are ours and freed below; the downloaded
// planes hold `linesize * rows` bytes.
unsafe {
let (mut out, mut sw) = ((api.av_frame_alloc)(), (api.av_frame_alloc)());
assert!((api.av_hwframe_get_buffer)(pool, out, 0) >= 0);
converter.convert(surface_id(rgb.surface), surface_id(out)).expect("converted");
(*sw.cast::<FrameHead>()).format = ffmpeg.pix.nv12;
assert!((api.av_hwframe_transfer_data)(sw, out, 0) >= 0, "download");
let head = &*sw.cast::<FrameHead>();
let plane = |i: usize, rows: usize| {
let stride = head.linesize[i] as usize;
std::slice::from_raw_parts(head.data[i], stride * rows).chunks_exact(stride)
};
for row in plane(0, h) {
gpu[0].extend_from_slice(&row[..w]);
}
for row in plane(1, ch) {
for pair in row[..cw * 2].chunks_exact(2) {
gpu[1].push(pair[0]);
gpu[2].push(pair[1]);
}
}
(api.av_frame_free)(&mut sw);
(api.av_frame_free)(&mut out);
(api.av_buffer_unref)(&mut pool);
}
drop(converter);
for (name, gpu, cpu, width, rows) in
[("Y", &gpu[0], y, w, h), ("U", &gpu[1], u, cw, ch), ("V", &gpu[2], v, cw, ch)]
[("Y", gy, y, w, h), ("U", gu, u, cw, ch), ("V", gv, v, cw, ch)]
{
let gpu: Vec<u8> = (0..rows).flat_map(|r| gpu.row(r, width).to_vec()).collect();
let cpu: Vec<u8> = (0..rows).flat_map(|r| cpu.row(r, width).to_vec()).collect();
let mean = gpu.iter().zip(&cpu).map(|(a, b)| u64::from(a.abs_diff(*b))).sum::<u64>()
as f64 / cpu.len() as f64;
@@ -2317,9 +2341,9 @@ mod tests {
// The buffers: the driver's own (tiled), and a LINEAR one with a
// padded pitch in system memory, which is what the portal negotiates.
#[cfg(target_os = "linux")]
#[cfg(all(target_os = "linux", feature = "pipewire"))]
let linear = linear_dmabuf(&picture, (SIZE.0 as usize * 4).next_multiple_of(256));
#[cfg(not(target_os = "linux"))]
#[cfg(not(all(target_os = "linux", feature = "pipewire")))]
let linear: Option<((), DmaBufRef)> = None;
if linear.is_none() {
eprintln!("no /dev/udmabuf: the LINEAR buffer is skipped");
@@ -2384,91 +2408,33 @@ mod tests {
}
}
/// `struct udmabuf_create` of `<linux/udmabuf.h>`, and `UDMABUF_CREATE`
/// returning the new DMA-BUF.
#[cfg(target_os = "linux")]
#[repr(C)]
struct UdmabufCreate {
memfd: u32,
flags: u32,
offset: u64,
size: u64,
}
// SAFETY: `UDMABUF_CREATE` (`_IOW('u', 0x42, struct udmabuf_create)`)
// only reads the struct and returns a new descriptor.
#[cfg(target_os = "linux")]
unsafe impl rustix::ioctl::Ioctl for UdmabufCreate {
type Output = std::os::fd::OwnedFd;
const IS_MUTATING: bool = false;
fn opcode(&self) -> rustix::ioctl::Opcode {
rustix::ioctl::opcode::write::<UdmabufCreate>(b'u', 0x42)
}
fn as_ptr(&mut self) -> *mut std::ffi::c_void {
(&raw mut *self).cast()
}
unsafe fn output_from_ptr(
out: rustix::ioctl::IoctlOutput,
_: *mut std::ffi::c_void,
) -> rustix::io::Result<Self::Output> {
// SAFETY: the descriptor the kernel just made, ours to own.
Ok(unsafe { std::os::fd::FromRawFd::from_raw_fd(out) })
}
}
/// `picture` (BGRA) in a LINEAR DMA-BUF of system memory, rows `stride`
/// bytes apart: `/dev/udmabuf` over a sealed memfd. The descriptor has
/// to outlive the returned buffer. `None` without access to
/// `picture` (BGRA) in a LINEAR DMA-BUF of ordinary memory, rows
/// `stride` bytes apart ([`Udmabuf`](crate::capture::dmabuf::Udmabuf));
/// the buffer has to outlive the reference. `None` without access to
/// `/dev/udmabuf`.
#[cfg(target_os = "linux")]
#[cfg(all(target_os = "linux", feature = "pipewire"))]
fn linear_dmabuf(
picture: &VideoFrame,
stride: usize,
) -> Option<(std::os::fd::OwnedFd, DmaBufRef)> {
use rustix::fs::{MemfdFlags, SealFlags};
use std::io::Write;
use std::os::fd::AsRawFd;
) -> Option<(crate::capture::dmabuf::Udmabuf, DmaBufRef)> {
let FrameData::Bgra(pixels) = &picture.data else { return None };
let (w, h) = (picture.width as usize, picture.height as usize);
let size = (stride * h).next_multiple_of(4096);
let memfd = rustix::fs::memfd_create(
"voelin-linear-dmabuf",
MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING,
)
.ok()?;
let mut bytes = vec![0; size];
for (y, row) in bytes.chunks_exact_mut(stride).take(h).enumerate() {
let mut buffer = crate::capture::dmabuf::Udmabuf::new(stride * h).ok()?;
for (y, row) in buffer.bytes_mut().chunks_exact_mut(stride).take(h).enumerate() {
row[..w * 4].copy_from_slice(pixels.row(y, w * 4));
}
let mut file = std::fs::File::from(memfd);
file.write_all(&bytes).ok()?;
rustix::fs::fcntl_add_seals(&file, SealFlags::SHRINK).ok()?;
let device =
std::fs::OpenOptions::new().read(true).write(true).open("/dev/udmabuf").ok()?;
let create = UdmabufCreate {
memfd: file.as_raw_fd() as u32,
flags: 1,
offset: 0,
size: size as u64,
};
// SAFETY: see the `Ioctl` impl; `device` is /dev/udmabuf.
let fd = unsafe { rustix::ioctl::ioctl(&device, create) }.ok()?;
let frame = DmaBufRef {
width: picture.width,
height: picture.height,
timestamp: Duration::ZERO,
fourcc: drm_fourcc(b"XR24"),
modifier: crate::capture::DRM_MOD_LINEAR,
fd: fd.as_raw_fd(),
size,
fd: buffer.fd(),
size: buffer.len(),
planes: [(0, stride), (0, 0), (0, 0), (0, 0)],
plane_count: 1,
};
Some((fd, frame))
Some((buffer, frame))
}
/// What the CPU spends per frame on its way into a VA-API encoder at
+385
View File
@@ -0,0 +1,385 @@
//! Captured RGB DMA-BUFs converted and scaled into NV12 VA-API surfaces on
//! the GPU, for VA-API encoders: screen sharing without the CPU reading a
//! pixel.
//!
//! A DMA-BUF (what the ScreenCast portal hands over) is mapped onto a VA-API
//! surface ([`map_dmabuf`]), and VA-API video processing ([`super::vpp`])
//! converts it to NV12 at the size of every layer that wants a frame, into
//! surfaces from pools of our own. The buffer is free again once
//! [`GpuConverter::convert`] returns; the surfaces travel to the encoders as
//! [`GpuFrame`]s ([`VideoEncoder::encode_gpu`](crate::VideoEncoder::encode_gpu))
//! and go back to their pools when the last reference is dropped. The
//! frames are recycled, so nothing is allocated per frame once the pools
//! are warm.
#![allow(unsafe_code)]
use std::ffi::{c_int, c_uint};
use std::sync::Arc;
use std::time::Duration;
use super::encoder::{exact_size, vaapi_display, vaapi_pool};
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::{Error, Result};
/// The DRM formats of RGB buffers the conversion takes (8 bits per
/// channel, 4 bytes per pixel, one plane; what screen capture offers).
pub(crate) const RGB_FOURCCS: [u32; 4] =
[drm_fourcc(b"XR24"), drm_fourcc(b"AR24"), drm_fourcc(b"XB24"), drm_fourcc(b"AB24")];
/// An `AVFrame` that holds a VA-API surface (or nothing yet). Freeing it
/// gives the surface back to its pool.
pub(crate) struct Surface(pub(crate) Ptr);
// SAFETY: the frame is ours. Once it holds a surface it is only read: its
// surface id, and as the source of `av_frame_ref`, which takes references
// of its own (FFmpeg's buffer references are thread-safe).
unsafe impl Send for Surface {}
unsafe impl Sync for Surface {}
impl Surface {
fn alloc(ffmpeg: &Ffmpeg) -> Result<Self> {
// SAFETY: an allocation; NULL is checked.
let frame = unsafe { (ffmpeg.api.av_frame_alloc)() };
if frame.is_null() {
return Err(Error::Convert("out of memory".into()));
}
Ok(Self(frame))
}
/// Another frame of the same surface (NULL, which encoders refuse, if
/// memory runs out).
pub(crate) fn new_ref(&self) -> Self {
let api = &Ffmpeg::get().expect("a surface exists only with FFmpeg").api;
// SAFETY: a new frame takes a reference to ours; freed on failure.
unsafe {
let mut frame = (api.av_frame_alloc)();
if !frame.is_null() && (api.av_frame_ref)(frame, self.0) < 0 {
(api.av_frame_free)(&mut frame);
}
Self(frame)
}
}
/// The VA-API surface id (`data[3]` of an `AV_PIX_FMT_VAAPI` frame,
/// `hwcontext_vaapi.h`).
pub(crate) fn id(&self) -> c_uint {
// SAFETY: a live frame; `data` is its leading field.
unsafe { (*self.0.cast::<FrameHead>()).data[3] as usize as c_uint }
}
}
impl Drop for Surface {
fn drop(&mut self) {
if let Ok(ffmpeg) = Ffmpeg::get() {
// SAFETY: our frame (or NULL).
unsafe { (ffmpeg.api.av_frame_free)(&mut self.0) };
}
}
}
/// Map DMA-BUF `frame` onto a VA-API surface in `dst` (an unreferenced frame
/// of ours), which takes a reference to `pool`: the surface gets that frames
/// context's device. The surface reads the buffer itself, without a copy;
/// unreferencing `dst` lets the buffer go.
pub(crate) fn map_dmabuf(
ffmpeg: &Ffmpeg,
frame: &DmaBufRef,
pool: Ptr,
dst: Ptr,
refs: FrameRefs,
) -> std::result::Result<(), String> {
let api = &ffmpeg.api;
let drm_prime = ffmpeg.pix.drm_prime.ok_or("no DRM PRIME pixel format")?;
let vaapi = ffmpeg.pix.vaapi.ok_or("no VA-API pixel format")?;
let mut descriptor =
sys::DrmFrameDescriptor { nb_objects: 1, nb_layers: 1, ..Default::default() };
descriptor.objects[0] =
sys::DrmObject { fd: frame.fd, size: frame.size, format_modifier: frame.modifier };
descriptor.layers[0].format = frame.fourcc;
descriptor.layers[0].nb_planes = frame.plane_count as c_int;
for (plane, &(offset, pitch)) in
descriptor.layers[0].planes.iter_mut().zip(&frame.planes[..frame.plane_count])
{
*plane = sys::DrmPlane { object_index: 0, offset: offset as isize, pitch: pitch as isize };
}
// SAFETY: the descriptor lives in a buffer the source frame owns (buf[0],
// checked offset), so FFmpeg can keep it while mapped; the destination
// gets a reference to the pool at the checked hw_frames_ctx offset;
// av_frame_free / av_frame_unref release both.
unsafe {
let mut buffer = (api.av_buffer_allocz)(size_of::<sys::DrmFrameDescriptor>());
let mut src = (api.av_frame_alloc)();
if buffer.is_null() || src.is_null() {
(api.av_buffer_unref)(&mut buffer);
(api.av_frame_free)(&mut src);
return Err("out of memory".into());
}
let data = (*buffer.cast::<sys::BufferRefHead>()).data;
data.cast::<sys::DrmFrameDescriptor>().write(descriptor);
let head = src.cast::<FrameHead>();
(*head).format = drm_prime;
(*head).width = frame.width as c_int;
(*head).height = frame.height as c_int;
(*head).data[0] = data;
layout::write::<Ptr>(src, refs.buf, buffer);
(*dst.cast::<FrameHead>()).format = vaapi;
layout::write::<Ptr>(dst, refs.hw_frames_ctx, (api.av_buffer_ref)(pool));
let ret = (api.av_hwframe_map)(dst, src, sys::HWFRAME_MAP_READ);
(api.av_frame_free)(&mut src);
if ret < 0 {
(api.av_frame_unref)(dst);
return Err(format!("DMA-BUF import: {}", api.error_text(ret)));
}
}
Ok(())
}
/// One output of [`GpuConverter::convert`]: a layer's size, the multiple
/// its encoder takes, and whether it wants this frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GpuLayer {
/// The size the whole picture is scaled to.
pub size: (u32, u32),
/// What the encoded width and height must be a multiple of
/// ([`VideoEncoder::gpu_alignment`](crate::VideoEncoder::gpu_alignment)):
/// the scaled picture is cropped to it at the right and bottom, as
/// encoders crop frames in memory.
pub alignment: (u32, u32),
pub due: bool,
}
/// NV12 surfaces of one size, and the frames that hold them, reused once
/// nothing else does.
struct Output {
size: (u32, u32),
pool: Ptr,
frames: Vec<Arc<GpuFrame>>,
}
impl Drop for Output {
fn drop(&mut self) {
// Frames still held elsewhere keep their surfaces and the pool.
self.frames.clear();
if let Ok(ffmpeg) = Ffmpeg::get() {
// SAFETY: our reference.
unsafe { (ffmpeg.api.av_buffer_unref)(&mut self.pool) };
}
}
}
/// See the [module docs](self). One per capture, used from one thread.
pub struct GpuConverter {
ffmpeg: &'static Ffmpeg,
refs: FrameRefs,
display: vpp::Display,
/// Video processing, and the source size it was made for.
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.
mapped: Surface,
outputs: Vec<Output>,
modifiers: Vec<u64>,
}
// SAFETY: the FFmpeg and libva objects are ours and used from one thread
// at a time (`&mut self`).
unsafe impl Send for GpuConverter {}
impl GpuConverter {
/// A converter on the process's VA-API device, or why there is none (no
/// FFmpeg, no VA-API device, no video processing).
pub fn new() -> Result<Self> {
let ffmpeg = Ffmpeg::get().map_err(|e| Error::Convert(e.into()))?;
let refs = ffmpeg.frame_refs.clone().map_err(Error::Convert)?;
let display = vaapi_display(ffmpeg).map_err(Error::Convert)?;
// Fail now rather than on the first frame.
vpp::Converter::new(display, 64, 64).map_err(Error::Convert)?;
let mut converter = Self {
ffmpeg,
refs,
display,
vpp: None,
import: None,
mapped: Surface::alloc(ffmpeg)?,
outputs: Vec::new(),
modifiers: Vec::new(),
};
converter.modifiers.extend(converter.tiled_modifier());
Ok(converter)
}
/// The tiled DRM format modifiers RGB buffers may have besides LINEAR:
/// the one this GPU's driver gives RGB surfaces of its own (it imports
/// what it makes), if that is tiled and needs a single plane (no
/// compression metadata). Empty if there is none.
pub fn modifiers(&self) -> &[u64] {
&self.modifiers
}
fn tiled_modifier(&self) -> Option<u64> {
let ffmpeg = self.ffmpeg;
let api = &ffmpeg.api;
let drm_prime = ffmpeg.pix.drm_prime?;
// The size of a typical screen: drivers may lay out small surfaces
// differently.
let mut pool = vaapi_pool(ffmpeg, 1920, 1080, ffmpeg.pix.bgr0?).ok()?;
let (surface, drm) = (Surface::alloc(ffmpeg).ok()?, Surface::alloc(ffmpeg).ok()?);
// SAFETY: frames and pool are ours; the exported frame's data[0] is
// the descriptor FFmpeg filled, read while the mapping lives (`drm`
// goes before `surface`).
let modifier = unsafe {
let mut modifier = None;
if (api.av_hwframe_get_buffer)(pool, surface.0, 0) >= 0 {
(*drm.0.cast::<FrameHead>()).format = drm_prime;
let flags = sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT;
if (api.av_hwframe_map)(drm.0, surface.0, flags) >= 0 {
let d = *(*drm.0.cast::<FrameHead>()).data[0].cast::<sys::DrmFrameDescriptor>();
let layers = &d.layers[..(d.nb_layers.max(0) as usize).min(d.layers.len())];
let planes: c_int = layers.iter().map(|l| l.nb_planes).sum();
let m = d.objects[0].format_modifier;
let tiled = m != DRM_MOD_LINEAR && m != DRM_MOD_INVALID;
modifier = (d.nb_objects == 1 && planes == 1 && tiled).then_some(m);
}
}
modifier
};
drop(drm);
drop(surface);
// SAFETY: our reference.
unsafe { (api.av_buffer_unref)(&mut pool) };
modifier
}
/// Convert `frame`, an RGB DMA-BUF (`XR24`, `AR24`, `XB24` or `AB24` in
/// one plane, LINEAR or one of [`modifiers`](Self::modifiers)), for every
/// due layer: each gets an NV12 [`GpuFrame`] in `out` (same index), the
/// whole picture scaled to the layer's size and cropped to its alignment.
/// The buffer is no longer read when this returns. On an error nothing
/// in `out` is valid for this frame.
pub fn convert(
&mut self,
frame: &DmaBufRef,
layers: &[GpuLayer],
out: &mut [Option<Arc<GpuFrame>>],
) -> Result<()> {
if !RGB_FOURCCS.contains(&frame.fourcc) || frame.plane_count != 1 {
return Err(Error::Convert("not an RGB DMA-BUF of one plane".into()));
}
let source = (frame.width, frame.height);
self.outputs.retain(|o| layers.iter().any(|l| exact_size(l.size, l.alignment) == o.size));
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);
// SAFETY: our frame; this lets the buffer go.
unsafe { (self.ffmpeg.api.av_frame_unref)(self.mapped.0) };
result
}
/// The import pool and the video processing for buffers of `source`'s
/// size.
fn prepare(&mut self, source: (u32, u32)) -> Result<()> {
if self.import.as_ref().is_none_or(|(_, size)| *size != source) {
if let Some((mut pool, _)) = self.import.take() {
// SAFETY: our reference.
unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) };
}
let bgr0 = self.ffmpeg.pix.bgr0.ok_or(Error::Convert("no bgr0 pixel format".into()))?;
let pool = vaapi_pool(self.ffmpeg, source.0, source.1, bgr0).map_err(Error::Convert)?;
self.import = Some((pool, source));
}
if self.vpp.as_ref().is_none_or(|(_, size)| *size != source) {
self.vpp = None;
let converter =
vpp::Converter::new(self.display, source.0, source.1).map_err(Error::Convert)?;
self.vpp = Some((converter, source));
}
Ok(())
}
fn convert_mapped(
&mut self,
frame: &DmaBufRef,
layers: &[GpuLayer],
out: &mut [Option<Arc<GpuFrame>>],
) -> Result<()> {
let input = self.mapped.id();
for (layer, slot) in layers.iter().zip(out.iter_mut()) {
if !layer.due {
continue;
}
let exact = exact_size(layer.size, layer.alignment);
// The part of the picture that scales to `exact`: all of it
// scales to `size`, the rest is cropped.
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 (vpp, _) = self.vpp.as_ref().expect("prepared");
vpp.convert(input, src, gpu.surface.id(), exact).map_err(Error::Convert)?;
*slot = Some(gpu);
}
Ok(())
}
/// A frame with a fresh NV12 surface of `size`: one that nothing else
/// holds any more, else a new one.
fn output(&mut self, size: (u32, u32), timestamp: Duration) -> Result<Arc<GpuFrame>> {
let ffmpeg = self.ffmpeg;
let index = match self.outputs.iter().position(|o| o.size == size) {
Some(i) => i,
None => {
let pool =
vaapi_pool(ffmpeg, size.0, size.1, ffmpeg.pix.nv12).map_err(Error::Convert)?;
self.outputs.push(Output { size, pool, frames: Vec::new() });
self.outputs.len() - 1
}
};
let output = &mut self.outputs[index];
let free = match output.frames.iter_mut().position(|f| Arc::get_mut(f).is_some()) {
Some(free) => free,
None => {
let surface = Surface::alloc(ffmpeg)?;
output.frames.push(Arc::new(GpuFrame {
width: size.0,
height: size.1,
timestamp,
surface,
}));
output.frames.len() - 1
}
};
let frame = Arc::get_mut(&mut output.frames[free]).expect("nothing else holds it");
frame.timestamp = timestamp;
let api = &ffmpeg.api;
// SAFETY: our frame; unreferencing gives its old surface back (once
// the encoder that referenced it is done), then it takes a new one.
let ret = unsafe {
(api.av_frame_unref)(frame.surface.0);
(api.av_hwframe_get_buffer)(output.pool, frame.surface.0, 0)
};
if ret < 0 {
return Err(Error::Convert(format!("VA-API surface: {}", api.error_text(ret))));
}
Ok(output.frames[free].clone())
}
}
impl Drop for GpuConverter {
fn drop(&mut self) {
self.outputs.clear();
if let Some((mut pool, _)) = self.import.take() {
// SAFETY: our reference.
unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) };
}
}
}
+4
View File
@@ -19,10 +19,14 @@ use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
pub mod encoder;
mod gpu;
mod layout;
pub mod sys;
mod vpp;
pub(crate) use gpu::Surface;
pub use gpu::{GpuConverter, GpuLayer};
pub use encoder::{
BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe,
};
+1
View File
@@ -199,6 +199,7 @@ api! {
fn av_frame_get_buffer(frame: Ptr, align: c_int) -> c_int;
fn av_frame_make_writable(frame: Ptr) -> c_int;
fn av_frame_unref(frame: Ptr);
fn av_frame_ref(dst: Ptr, src: Ptr) -> c_int;
fn av_opt_set(obj: Ptr, name: *const c_char, val: *const c_char, flags: c_int) -> c_int;
fn av_opt_set_int(obj: Ptr, name: *const c_char, val: i64, flags: c_int) -> c_int;
fn av_opt_set_q(obj: Ptr, name: *const c_char, val: Rational, flags: c_int) -> c_int;
+24 -14
View File
@@ -171,14 +171,12 @@ impl Va {
}
/// A VA-API video processing context that converts RGB surfaces into NV12
/// ones of `width` x `height`.
/// ones, cropping and scaling on the way.
pub struct Converter {
va: &'static Va,
display: Display,
config: c_uint,
context: c_uint,
width: u32,
height: u32,
}
// SAFETY: libva serialises calls per display; the context is used from one
@@ -187,8 +185,8 @@ unsafe impl Send for Converter {}
impl Converter {
/// A context on `display` (FFmpeg's, see
/// [`layout::device_hwctx`](super::layout::device_hwctx)) for output
/// surfaces of `width` x `height`.
/// [`layout::device_hwctx`](super::layout::device_hwctx)) for pictures of
/// up to `width` x `height`.
pub fn new(display: Display, width: u32, height: u32) -> Result<Self, String> {
let va = Va::get()?;
let mut config = 0;
@@ -224,24 +222,36 @@ impl Converter {
unsafe { (va.destroy_config)(display, config) };
return Err(e);
}
Ok(Self { va, display, config, context, width, height })
Ok(Self { va, display, config, context })
}
/// Convert the top-left `width` x `height` of RGB surface `input` into
/// NV12 surface `output` (both of this display): BT.601, limited range,
/// what the encoders signal and the CPU path ([`crate::convert`])
/// produces.
/// Convert the top-left `src` (width, height) of RGB surface `input`
/// into the top-left `dst` of NV12 surface `output` (both of this
/// display), scaled if the two differ: BT.601, limited range, what the
/// encoders signal and the CPU path ([`crate::convert`]) produces.
///
/// Returns once the GPU has read `input`, so a captured buffer can go
/// back to the compositor; `output` is ready for an encoder of the same
/// display, which orders its reads after this.
pub fn convert(&self, input: c_uint, output: c_uint) -> Result<(), String> {
pub fn convert(
&self,
input: c_uint,
src: (u32, u32),
output: c_uint,
dst: (u32, u32),
) -> Result<(), String> {
let va = self.va;
let region = Rectangle { x: 0, y: 0, width: self.width as u16, height: self.height as u16 };
let rect = |(width, height): (u32, u32)| Rectangle {
x: 0,
y: 0,
width: width.min(u32::from(u16::MAX)) as u16,
height: height.min(u32::from(u16::MAX)) as u16,
};
let (src, dst) = (rect(src), rect(dst));
let mut parameters = PipelineParameters {
surface: input,
surface_region: &region,
output_region: &region,
surface_region: &src,
output_region: &dst,
output_background_color: 0xff00_0000,
output_color_standard: COLOR_STANDARD_BT601,
pipeline_flags: 0,
+41
View File
@@ -284,6 +284,47 @@ impl VideoFrame {
}
}
/// A picture in GPU memory: an NV12 VA-API surface, converted and scaled
/// from a captured DMA-BUF on the GPU (`ffmpeg::GpuConverter`, Linux) so
/// that no CPU reads its pixels, for the encoders that take one
/// ([`VideoEncoder::gpu_alignment`](crate::VideoEncoder::gpu_alignment)).
/// Dropping it gives the surface back to its pool. Only this crate makes
/// them.
#[non_exhaustive]
pub struct GpuFrame {
pub width: u32,
pub height: u32,
/// As [`VideoFrame::timestamp`].
pub timestamp: Duration,
#[cfg(feature = "ffmpeg")]
pub(crate) surface: crate::ffmpeg::Surface,
}
impl GpuFrame {
/// 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
}
/// The same picture at another time (another reference to the same
/// surface), e.g. to send a still screen again.
pub fn at(&self, timestamp: Duration) -> Self {
Self {
width: self.width,
height: self.height,
timestamp,
#[cfg(feature = "ffmpeg")]
surface: self.surface.new_ref(),
}
}
}
impl std::fmt::Debug for GpuFrame {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "GpuFrame({}x{} at {:?})", self.width, self.height, self.timestamp)
}
}
/// Interleaved 32-bit float audio at [`AUDIO_SAMPLE_RATE`].
#[derive(Clone, Debug, PartialEq)]
pub struct AudioBuffer {
+8
View File
@@ -95,6 +95,14 @@ impl<T> Handoff<T> {
}
}
/// Make the calling thread the consumer that [`put`](Self::put) wakes
/// (what the first [`wait_timeout`](Self::wait_timeout) does), for a
/// thread that waits on several handoffs itself
/// (`std::thread::park_timeout`, then [`take`](Self::take) from each).
pub fn register(&self) {
self.consumer.get_or_init(std::thread::current);
}
/// Wake the consumer and make waits return at once (items can still be
/// taken).
pub fn close(&self) {
+1 -1
View File
@@ -49,7 +49,7 @@ pub use codec::{
VideoEncoder,
};
pub use frame::{
AudioBuffer, FrameData, FrameRef, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame,
AudioBuffer, FrameData, FrameRef, GpuFrame, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame,
};
pub use queue::{FrameReceiver, FrameSender, frame_channel};