🐎 Fill a VA-API encode's input surface on the GPU

A guest's frame reached the host's VA-API encoder through the CPU: copied out
of its device caches into a staging buffer and read back, then uploaded into
a VA image by the driver. At 1080p on an Iris Xe the encode call, upload
included, took 12.3 ms of a 13.2 ms frame, and one frame is in flight at a
time, as AppleGVA schedules them.

The runtime device's GPU now copies the frame's two planes, where they lie (the
surface's pages or its device caches), into an input surface of the encoder's:
the VA crate lends the surface and exports it as dma-bufs for writing
(VideoEncoder::input_surface), and the Vulkan crate's plane copier imports
them as images and fills them from the buffer (PlaneCopier::fill), the margin
to the coded size filled as the upload fills it. Where the device takes no
such import, or a copy is declined, the frame is uploaded by the CPU as
before, said once a session at info; an input surface whose fill failed on
the GPU stays out of the encoder's pool. NVENC's arm takes the same frame
source and encoder traits and uploads from the host bytes as before.

What the guest sees: the same access units, byte for byte
(a_frame_filled_by_the_gpu_encodes_as_the_uploaded_frame_byte_for_byte, on
iHD and radeonsi, every codec and profile they encode), at a higher rate. On
a macOS 26.7.2 guest on an Iris Xe host, 300 frames of H.264: 111.5 fps at
1080p and 6 Mbit/s (76.5 before), 57.9 fps at 2160p and 30 Mbit/s (34.2
before) (m3-max-37624, m3-max-37343); a Radeon Pro 5300M Mac encodes 133 and
52.
This commit is contained in:
Anees Iqbal committed 2026-11-16 13:28:22 -08:00
1 parent 38fce265d6
commit cee727b5e2
20 files changed
+1226 -214

No files matched your search

@@ -662,12 +662,33 @@ impl<A: Accelerator> Encoder<A> {
/// several when it ends a run. `Err` is a frame not taken: one whose
/// time stamp does not follow the last, or that does not upload.
pub fn encode(&mut self, frame: &InputFrame<'_>) -> Result<Vec<Coded<A::Error>>, A::Error> {
if let Some(last) = self.last_pts {
check(frame.pts > last, || {
format!("PTS {} does not follow {last}", frame.pts)
})?;
}
self.follows(frame.pts)?;
let input = self.accelerator.upload(frame)?;
Ok(self.push(input, frame))
}
/// [`Self::encode`] of a frame another device already wrote into `input`, an input of the
/// accelerator's: `frame`'s times, key-frame demand and tag are taken, and its planes are not
/// read. `Err` is a frame not taken, whose time stamp does not follow the last.
pub fn encode_input(
&mut self,
input: A::Input,
frame: &InputFrame<'_>,
) -> Result<Vec<Coded<A::Error>>, A::Error> {
self.follows(frame.pts)?;
Ok(self.push(input, frame))
}
/// `Err` where `pts` does not follow the last frame's.
fn follows(&self, pts: i64) -> Result<(), A::Error> {
if let Some(last) = self.last_pts {
check(pts > last, || format!("PTS {pts} does not follow {last}"))?;
}
Ok(())
}
/// Takes `frame`, in `input`, and encodes what its plan gives.
fn push(&mut self, input: A::Input, frame: &InputFrame<'_>) -> Vec<Coded<A::Error>> {
self.last_pts = Some(frame.pts);
self.times.push(frame.pts);
let pending = Pending {
@@ -680,7 +701,7 @@ impl<A: Accelerator> Encoder<A> {
let planned = self
.planner
.push(pending, frame.pts, frame.force_key_frame || restart);
Ok(self.encode_all(planned))
self.encode_all(planned)
}
/// Encodes the frames still waiting and returns each with its own
+2 -2
View File
@@ -29,6 +29,6 @@ pub(crate) use va::target_probe;
pub(crate) use va::gated;
pub use va::{
EncoderCapabilities, EncoderSupport, Feature, HevcBlockSizes, HevcFeatures, UploadMethod,
VideoEncoder, encoder_support,
EncoderCapabilities, EncoderSupport, Feature, HevcBlockSizes, HevcFeatures, InputSurface,
UploadMethod, VideoEncoder, encoder_support,
};
+2 -2
View File
@@ -44,8 +44,8 @@ pub use caps::{
};
pub use display::{Display, Error};
pub use encoder::{
EncoderCapabilities, EncoderSupport, Feature, HevcBlockSizes, HevcFeatures, UploadMethod,
VideoEncoder, encoder_support,
EncoderCapabilities, EncoderSupport, Feature, HevcBlockSizes, HevcFeatures, InputSurface,
UploadMethod, VideoEncoder, encoder_support,
};
pub use export::{ExportedPlane, SurfaceExport};
pub use frame::{Frame, FrameHold, GuestWrites, PlaneRows, ReadBack};
@@ -30,6 +30,7 @@ pub use surfaces::UploadMethod;
use super::caps::{Entrypoint, Profile};
use super::display::{Display, Error};
use super::export::SurfaceExport;
use super::ffi::{self, encode as enc};
use super::wait::{self, Deadline};
use crate::codec::encode::encoder::{DriverLimits, Encoder};
@@ -308,6 +309,43 @@ impl VideoEncoder {
pub fn force_upload_method(&mut self, method: UploadMethod) {
self.inner.accelerator_mut().force_upload_method(method);
}
/// A free input surface of the coded size, for another device to write the next frame into
/// through its memory as dma-bufs ([`InputSurface::export`]), then encoded by
/// [`Self::encode_surface`]. It goes back to its pool where it is dropped instead.
pub fn input_surface(&mut self) -> Result<InputSurface, Error> {
let (lent, export) = self.inner.accelerator_mut().lend_input()?;
Ok(InputSurface { lent, export })
}
/// [`Self::encode`] of the frame written into `surface`, whose whole coded size holds it:
/// the picture's rows and columns, and the margin to the coded size filled as an upload
/// fills it, its last column and row repeated. `frame`'s times, key-frame demand and tag are
/// taken, and its planes are not read.
pub fn encode_surface(
&mut self,
surface: InputSurface,
frame: &InputFrame<'_>,
) -> Result<Vec<Coded<Error>>, Error> {
wait::by(&Deadline::default(), || {
self.inner.encode_input(surface.lent, frame)
})
}
}
/// An input surface of an encoder's, lent for another device to write a frame into
/// ([`VideoEncoder::input_surface`]).
pub struct InputSurface {
lent: surfaces::Lent,
export: Arc<SurfaceExport>,
}
impl InputSurface {
/// The surface's memory as dma-bufs, exported for writing: the encoder's coded size, its
/// planes where the export says, kept while the encoder's pool lives.
pub fn export(&self) -> &Arc<SurfaceExport> {
&self.export
}
}
#[cfg(test)]
@@ -18,12 +18,15 @@
//! followed on the VCN by that picture. radeonsi's VCN hangs otherwise
//! ([`super`]'s docs).
use std::sync::Arc;
use crate::core::runtime::MonoTime;
use crate::core::sync::Mutex;
use super::super::buffer::{Buffer, render_picture};
use super::super::caps::{Config, Context, Entrypoint, Profile};
use super::super::display::{Display, Error, check};
use super::super::export::{SurfaceExport, export_for_write};
use super::super::ffi::{self, encode as enc};
use super::super::wait::{self, Work};
use super::params;
@@ -67,6 +70,11 @@ struct Session {
/// The references held, by number.
references: Vec<(u64, Lent)>,
uploader: Uploader,
/// The input surfaces' sizes, the coded size.
coded_size: (u32, u32),
/// The input surfaces exported for another device to write a frame into, each once, at its
/// first lend so ([`VaAccelerator::lend_input`]).
exports: Vec<(ffi::VASurfaceID, Arc<SurfaceExport>)>,
/// From [`StreamParams`].
b_frames: u32,
intra_period: u32,
@@ -158,6 +166,23 @@ impl VaAccelerator {
self.session.as_ref().and_then(|s| s.uploader.method())
}
/// A free input surface of the coded size, for another device to write a frame into, with its
/// memory as dma-bufs, which it keeps while its pool lives: each surface is exported once.
pub(crate) fn lend_input(&mut self) -> Result<(Lent, Arc<SurfaceExport>), Error> {
self.unstalled()?;
let session = self.session.as_mut().ok_or_else(|| {
Error::Unsupported("a surface lent before the stream is configured".into())
})?;
let surface = session.inputs.get()?;
let id = surface.id();
if let Some((_, export)) = session.exports.iter().find(|(s, _)| *s == id) {
return Ok((surface, Arc::clone(export)));
}
let export = Arc::new(export_for_write(&self.display, id, session.coded_size)?);
session.exports.push((id, Arc::clone(&export)));
Ok((surface, export))
}
pub(crate) fn force_upload_method(&mut self, method: UploadMethod) {
self.forced_upload = Some(method);
if let Some(session) = &mut self.session {
@@ -279,6 +304,8 @@ impl Accelerator for VaAccelerator {
reconstructed,
references: Vec::new(),
uploader,
coded_size: (width, height),
exports: Vec::new(),
b_frames: stream.b_frames,
intra_period: stream.intra_period,
picture_qp: stream.picture_qp,
+34 -10
View File
@@ -1,7 +1,10 @@
//! A decode surface's memory as dma-bufs, for another device to read its planes
//! ([`super::Frame::export`]): `vaExportSurfaceHandle`, read only, each plane a layer of its
//! own, so each plane is one image of its own format (R8 and RG8 for NV12, R16 and RG16 for P010)
//! in its object, at its offset and pitch, laid out as the object's DRM format modifier says.
//! A surface's memory as dma-bufs, for another device to reach its planes: a decode surface's,
//! read only, for the device to read ([`super::Frame::export`]), and an encoder's input
//! surface's, write only, for the device to write the frame into
//! ([`super::VideoEncoder::input_surface`]). Either is `vaExportSurfaceHandle`, each plane a layer
//! of its own, so each plane is one image of its own format (R8 and RG8 for NV12, R16 and RG16 for
//! P010) in its object, at its offset and pitch, laid out as the object's DRM format modifier
//! says.
//!
//! A pool exports each of its surfaces once, at its first frame asked so, and keeps the export
//! with the surface until the pool goes: the surfaces are lent again frame after frame, and the
@@ -39,7 +42,7 @@ pub struct ExportedPlane {
pub pitch: u64,
}
/// A decode surface's memory as dma-bufs (module docs), kept while its pool lives.
/// A surface's memory as dma-bufs (module docs), kept while its pool lives.
#[derive(Debug)]
pub struct SurfaceExport {
objects: Vec<OwnedFd>,
@@ -60,7 +63,8 @@ impl SurfaceExport {
self.objects[self.plane(plane).object].as_fd()
}
/// The surface's width and height in luma samples: the decoded (coded) picture's.
/// The surface's width and height in luma samples: the decoded (coded) picture's, or the
/// encoder's coded size.
pub fn size(&self) -> (u32, u32) {
self.size
}
@@ -72,12 +76,32 @@ impl SurfaceExport {
}
}
/// Exports `surface`, of `size`, on `display` (module docs); `Err` where the driver exports none,
/// or not as one plane a layer.
/// Exports `surface`, of `size`, on `display`, for another device to read (module docs); `Err`
/// where the driver exports none, or not as one plane a layer.
pub(crate) fn export(
display: &Display,
surface: ffi::VASurfaceID,
size: (u32, u32),
) -> Result<SurfaceExport, Error> {
export_as(display, surface, size, ffi::VA_EXPORT_SURFACE_READ_ONLY)
}
/// Exports `surface`, of `size`, on `display`, for another device to write (module docs); `Err`
/// where the driver exports none, or not as one plane a layer.
pub(crate) fn export_for_write(
display: &Display,
surface: ffi::VASurfaceID,
size: (u32, u32),
) -> Result<SurfaceExport, Error> {
export_as(display, surface, size, ffi::VA_EXPORT_SURFACE_WRITE_ONLY)
}
/// Exports `surface`, of `size`, on `display`, with `access`, a `VA_EXPORT_SURFACE_*_ONLY` flag.
fn export_as(
display: &Display,
surface: ffi::VASurfaceID,
size: (u32, u32),
access: u32,
) -> Result<SurfaceExport, Error> {
let mut descriptor = ffi::VADRMPRIMESurfaceDescriptor::default();
check(
@@ -88,7 +112,7 @@ pub(crate) fn export(
raw,
surface,
ffi::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2,
ffi::VA_EXPORT_SURFACE_READ_ONLY | ffi::VA_EXPORT_SURFACE_SEPARATE_LAYERS,
access | ffi::VA_EXPORT_SURFACE_SEPARATE_LAYERS,
(&raw mut descriptor).cast(),
)
})?,
@@ -113,7 +137,7 @@ fn planes_of(descriptor: &ffi::VADRMPRIMESurfaceDescriptor) -> Result<[ExportedP
let layers =
&descriptor.layers[..usize::try_from(descriptor.num_layers).unwrap_or(0).min(4)];
Error::Unsupported(format!(
"the decode surface exported as {} objects and {} layers of {:?} planes: not a layer \
"the surface exported as {} objects and {} layers of {:?} planes: not a layer \
of one plane for each of its two planes",
descriptor.num_objects,
descriptor.num_layers,
@@ -104,6 +104,7 @@ pub(crate) const VA_SURFACE_ATTRIB_SETTABLE: u32 = 0x2;
pub(crate) const VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2: u32 = 0x4000_0000;
/// `vaExportSurfaceHandle`'s flags (va.h).
pub(crate) const VA_EXPORT_SURFACE_READ_ONLY: u32 = 0x0001;
pub(crate) const VA_EXPORT_SURFACE_WRITE_ONLY: u32 = 0x0002;
pub(crate) const VA_EXPORT_SURFACE_SEPARATE_LAYERS: u32 = 0x0004;
pub(crate) const VA_EXPORT_SURFACE_COMPOSED_LAYERS: u32 = 0x0008;
/// `DRM_FORMAT_MOD_LINEAR` (drm_fourcc.h).
@@ -1023,6 +1024,7 @@ mod tests {
VA_SURFACE_ATTRIB_SETTABLE,
VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2,
VA_EXPORT_SURFACE_READ_ONLY,
VA_EXPORT_SURFACE_WRITE_ONLY,
VA_EXPORT_SURFACE_SEPARATE_LAYERS,
VA_EXPORT_SURFACE_COMPOSED_LAYERS,
DRM_FORMAT_MOD_LINEAR,
@@ -364,6 +364,7 @@ int main(void)
C(VA_SURFACE_ATTRIB_SETTABLE);
C(VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2);
C(VA_EXPORT_SURFACE_READ_ONLY);
C(VA_EXPORT_SURFACE_WRITE_ONLY);
C(VA_EXPORT_SURFACE_SEPARATE_LAYERS);
C(VA_EXPORT_SURFACE_COMPOSED_LAYERS);
C(DRM_FORMAT_MOD_LINEAR);
+3 -2
View File
@@ -61,10 +61,11 @@ pub(crate) use host_os::{
COPIES_READ_ONLY, Drawables, ImportMade, allocate_aliasable, dma_buf_refusal, host_memory,
host_memory_vouched, import_heap_view, import_view,
};
/// Copies by the GPU of planes another driver wrote into dma-bufs into a runtime buffer, on Linux
/// Copies by the GPU of planes another driver wrote into dma-bufs into a runtime buffer, and of a
/// runtime buffer's planes into dma-bufs another driver reads, on Linux
/// (`os/linux/plane_copy.rs`).
#[cfg(target_os = "linux")]
pub use host_os::{CopyError, DmaBufPlane, PlaneCopier, PlaneCopy, PlaneFormat};
pub use host_os::{CopyError, DmaBufPlane, PlaneCopier, PlaneCopy, PlaneFill, PlaneFormat};
pub use host_os::{
GuestMemoryLease, OsClock, OsThreads, OsVm, RegionMemory, default_driver_sizes,
default_gpu_core_count, default_registry_id, install_process_services, lease_guest_memory,
+1 -1
View File
@@ -27,7 +27,7 @@ use metal2vulkan_runtime as rt;
pub use clock::LinuxClock;
pub use device_lend::{LendRefusal, LentDmaBuf, dma_buf_of_host, map_for_pointer};
pub use lease::{GuestMemoryLease, lease_guest_memory};
pub use plane_copy::{CopyError, DmaBufPlane, PlaneCopier, PlaneCopy, PlaneFormat};
pub use plane_copy::{CopyError, DmaBufPlane, PlaneCopier, PlaneCopy, PlaneFill, PlaneFormat};
pub use threads::LinuxThreads;
pub use vm::{LinuxVm, RegionMemory};
@@ -1,8 +1,10 @@
//! Copies by the GPU of planes another driver wrote into dma-bufs, a VA-API decode surface's
//! planes exported with `vaExportSurfaceHandle`, into a runtime buffer, at the rows and offset
//! the buffer's planes have ([`PlaneCopier`]): the reims-graphics device's VA-API pictures land so
//! in their output surfaces, whose planes lie 32 bytes into their pages, as CoreVideo lays them
//! out, where no driver's own video processing writes.
//! the buffer's planes have ([`PlaneCopier::copy`]): the reims-graphics device's VA-API pictures
//! land so in their output surfaces, whose planes lie 32 bytes into their pages, as CoreVideo lays
//! them out, where no driver's own video processing writes. And the other way
//! ([`PlaneCopier::fill`]): a runtime buffer's planes into dma-bufs another driver reads next, a
//! VA-API encoder's input surface's, which the reims-graphics device's encode sources reach so.
//!
//! - **The source.** Each plane is imported as a single-plane image of its own format (R8 and
//! RG8 for NV12, R16 and RG16 for P010) over its dma-buf, at its offset and pitch, tiled as the
@@ -12,6 +14,14 @@
//! gone ([`DmaBufPlane::alive`]) or the copier goes; the driver's surfaces are lent again
//! picture after picture, so each is imported once. The image is taken from the driver's queue
//! family (`VK_QUEUE_FAMILY_FOREIGN_EXT`, in `GENERAL`) for the copy and handed back after it.
//! - **A fill** ([`PlaneFill`]) is the copy the other way, `vkCmdCopyBufferToImage`: the
//! buffer's rows of the picture into the plane's image from its first texel, then the plane's
//! texels past the picture's columns and rows, to its own size, filled as the VA crate's upload
//! of a frame fills an encoder's margin, each past column with its row's last texel and each
//! past row with the picture's last row, so the driver encodes the same bytes either way. The
//! buffer is read as the destination of a copy is written: one whose pages are a copy the
//! runtime keeps is refused, since its `VkBuffer` may not hold the pages' bytes. The image is
//! imported for writes, and handed back to the driver's family with them made available.
//! - **The destination** is a runtime buffer whose bytes are its memory: one in the device's own
//! memory, or over host pages the device imported in place. A buffer whose pages are a copy the
//! runtime keeps (`copied-host-pages`), or whose GPU writes never reach its memory, is refused: a write into its `VkBuffer` would never reach the pages.
@@ -150,6 +160,23 @@ pub struct PlaneCopy<'a> {
pub bytes_per_row: u64,
}
/// One plane's fill (module docs): the picture's `extent` texels, rows `bytes_per_row` apart
/// from byte `offset` of `from`, into `into` from its first texel, and its texels past them to
/// its own size filled from the picture's last column and row.
#[derive(Clone, Debug)]
pub struct PlaneFill<'a> {
/// The plane written.
pub into: DmaBufPlane<'a>,
/// The buffer read.
pub from: &'a VulkanBuffer,
/// The byte of `from` the picture's first row starts at.
pub offset: u64,
/// The bytes from one row to the next in `from`.
pub bytes_per_row: u64,
/// The picture's texels: columns and rows, at most the plane's.
pub extent: [u32; 2],
}
/// Why a copy did not land ([`PlaneCopier::copy`]).
#[derive(Debug)]
pub enum CopyError {
@@ -172,6 +199,8 @@ impl std::fmt::Display for CopyError {
/// A kept import of one plane.
struct Import {
key: u64,
/// Imported for the copier's writes (a fill's), else for its reads.
write: bool,
alive: Weak<()>,
image: vk::Image,
memory: vk::DeviceMemory,
@@ -180,10 +209,10 @@ struct Import {
}
/// A copy whose fence answered an error, kept until its fence signals, with the caller's hold of
/// its sources and the buffers it writes.
/// its dma-bufs and the buffers it writes or reads.
struct Pending {
_hold: Box<dyn Any + Send>,
_targets: Vec<VulkanBuffer>,
_buffers: Vec<VulkanBuffer>,
}
/// The copies of one caller, a decode session's (module docs).
@@ -209,8 +238,9 @@ struct Objects {
/// nanoseconds a tick.
timestamps: Option<(vk::QueryPool, f64)>,
imports: Vec<Import>,
/// The modifiers and formats the device refused to import, with why.
refused: Vec<(u64, PlaneFormat, String)>,
/// The modifiers and formats the device refused to import, for writes or for reads, with
/// why.
refused: Vec<(u64, PlaneFormat, bool, String)>,
copies: u64,
pending: Option<Pending>,
}
@@ -240,6 +270,27 @@ impl PlaneCopier {
copies: &[PlaneCopy<'_>],
hold: Box<dyn Any + Send>,
) -> Result<Option<Duration>, CopyError> {
self.serve()?;
let objects = (self.objects.as_mut()).ok_or_else(Self::no_objects)?;
objects.copy(&self.queue, copies, hold)
}
/// Fills each of `fills` (module docs), as [`Self::copy`] copies: waits for the GPU as long
/// as it takes, keeps the fill with `hold` where its fence answers an error, and makes the
/// copier's objects again on the device's new `VkDevice` first where it recovered.
pub fn fill(
&mut self,
fills: &[PlaneFill<'_>],
hold: Box<dyn Any + Send>,
) -> Result<Option<Duration>, CopyError> {
self.serve()?;
let objects = (self.objects.as_mut()).ok_or_else(Self::no_objects)?;
objects.fill(&self.queue, fills, hold)
}
/// Makes the objects again on the generation of the device that serves where the device
/// recovered since they were made; refused where the process is exiting.
fn serve(&mut self) -> Result<(), CopyError> {
if rt::process_exiting() {
return Err(CopyError::Refused("the process is exiting".to_owned()));
}
@@ -258,10 +309,11 @@ impl PlaneCopier {
);
self.objects = Some(objects);
}
let Some(objects) = self.objects.as_mut() else {
return Err(CopyError::Refused("the copier has no objects".to_owned()));
};
objects.copy(&self.queue, copies, hold)
Ok(())
}
fn no_objects() -> CopyError {
CopyError::Refused("the copier has no objects".to_owned())
}
/// The generations of the device the copier made its objects on: 1, and one more each time
@@ -371,30 +423,7 @@ impl Objects {
let device = self.generation.device().clone();
// SAFETY: the handles are used while the generation, which `device` holds, lives.
let vk_device = unsafe { device.raw() }.device;
if self.pending.is_some() {
let fence = self.fence;
// SAFETY: the fence is this copier's.
let done = device.with_loader_word(|| unsafe { vk_device.get_fence_status(fence) });
match done {
// SAFETY: the fence is this copier's, signalled, and in no submission.
Ok(true) => {
match device.with_loader_word(|| unsafe { vk_device.reset_fences(&[fence]) }) {
Ok(()) => self.pending = None,
Err(e) => {
return Err(CopyError::Refused(format!(
"its fence's reset answered {e}"
)));
}
}
}
Ok(false) => {
return Err(CopyError::Refused(
"an earlier copy has not finished on the GPU".to_owned(),
));
}
Err(e) => return Err(CopyError::Refused(format!("its fence answered {e}"))),
}
}
self.ready(vk_device)?;
let mut targets = Vec::with_capacity(copies.len());
for copy in copies {
targets.push(destination(copy, &self.generation)?);
@@ -403,13 +432,86 @@ impl Objects {
self.copies += 1;
let mut images = Vec::with_capacity(copies.len());
for copy in copies {
images.push(self.import(vk_device, &copy.source)?);
images.push(self.import(vk_device, &copy.source, false)?);
}
device
.with_loader_word(|| self.record(vk_device, copies, &images, &targets))
.map_err(|e| CopyError::Refused(format!("its command buffer was refused ({e})")))?;
let buffers = [self.buffer];
let submit = [vk::SubmitInfo::default().command_buffers(&buffers)];
let buffers = copies.iter().map(|copy| copy.to.clone_ref()).collect();
self.run(queue, vk_device, hold, buffers)
}
/// [`PlaneCopier::fill`] with these objects, on `queue`, the copier's.
fn fill(
&mut self,
queue: &rt::CommandQueue,
fills: &[PlaneFill<'_>],
hold: Box<dyn Any + Send>,
) -> Result<Option<Duration>, CopyError> {
let device = self.generation.device().clone();
// SAFETY: the handles are used while the generation, which `device` holds, lives.
let vk_device = unsafe { device.raw() }.device;
self.ready(vk_device)?;
let mut sources = Vec::with_capacity(fills.len());
for fill in fills {
sources.push(source(fill, &self.generation)?);
}
self.let_go_of_gone(vk_device);
self.copies += 1;
let mut images = Vec::with_capacity(fills.len());
for fill in fills {
images.push(self.import(vk_device, &fill.into, true)?);
}
device
.with_loader_word(|| self.record_fill(vk_device, fills, &images, &sources))
.map_err(|e| CopyError::Refused(format!("its command buffer was refused ({e})")))?;
let buffers = fills.iter().map(|fill| fill.from.clone_ref()).collect();
self.run(queue, vk_device, hold, buffers)
}
/// `Ok` once no copy is pending: the last one kept after its fence answered an error is let
/// go where its fence has signalled since; refused where it has not.
fn ready(&mut self, vk_device: &ash::Device) -> Result<(), CopyError> {
if self.pending.is_none() {
return Ok(());
}
let device = self.generation.device().clone();
let fence = self.fence;
// SAFETY: the fence is this copier's.
let done = device.with_loader_word(|| unsafe { vk_device.get_fence_status(fence) });
match done {
// SAFETY: the fence is this copier's, signalled, and in no submission.
Ok(true) => {
match device.with_loader_word(|| unsafe { vk_device.reset_fences(&[fence]) }) {
Ok(()) => {
self.pending = None;
Ok(())
}
Err(e) => Err(CopyError::Refused(format!(
"its fence's reset answered {e}"
))),
}
}
Ok(false) => Err(CopyError::Refused(
"an earlier copy has not finished on the GPU".to_owned(),
)),
Err(e) => Err(CopyError::Refused(format!("its fence answered {e}"))),
}
}
/// Submits the recorded command buffer on `queue` and waits for it (module docs), keeping
/// `hold` and `buffers` with it where its fence answers an error; the copy's GPU time once
/// done.
fn run(
&mut self,
queue: &rt::CommandQueue,
vk_device: &ash::Device,
hold: Box<dyn Any + Send>,
buffers: Vec<VulkanBuffer>,
) -> Result<Option<Duration>, CopyError> {
let device = self.generation.device().clone();
let command_buffers = [self.buffer];
let submit = [vk::SubmitInfo::default().command_buffers(&command_buffers)];
let fence = self.fence;
// SAFETY: the submission is the closure's only call, keeps no handle and waits for
// nothing; the buffer is executable and not pending (no copy is pending), and the fence
@@ -424,10 +526,6 @@ impl Objects {
));
};
submitted.map_err(|e| CopyError::Refused(format!("its submission was refused ({e})")))?;
let pending = |hold: Box<dyn Any + Send>| Pending {
_hold: hold,
_targets: copies.iter().map(|copy| copy.to.clone_ref()).collect(),
};
// No bound of its own but the generation's park (module docs).
let look = u64::try_from(PARK_LOOK.as_nanos()).unwrap_or(u64::MAX);
let waited = loop {
@@ -444,16 +542,22 @@ impl Objects {
}
};
if let Err(why) = waited {
self.pending = Some(pending(hold));
self.pending = Some(Pending {
_hold: hold,
_buffers: buffers,
});
return Err(CopyError::Failed(why));
}
// SAFETY: the fence is this copier's, signalled.
let reset = device.with_loader_word(|| unsafe { vk_device.reset_fences(&[fence]) });
if let Err(e) = reset {
self.pending = Some(pending(hold));
self.pending = Some(Pending {
_hold: hold,
_buffers: buffers,
});
return Err(CopyError::Failed(format!("its fence's reset answered {e}")));
}
drop(hold);
drop((hold, buffers));
Ok(self.gpu_time(vk_device))
}
@@ -496,25 +600,30 @@ impl Objects {
});
}
/// The image of `plane`, imported now or kept from an earlier copy.
/// The image of `plane`, imported now or kept from an earlier copy, for the copier's writes
/// where `write` (a fill's), else for its reads.
fn import(
&mut self,
vk_device: &ash::Device,
plane: &DmaBufPlane<'_>,
write: bool,
) -> Result<vk::Image, CopyError> {
let copies = self.copies;
if let Some(kept) = self.imports.iter_mut().find(|i| i.key == plane.key) {
if let Some(kept) =
(self.imports.iter_mut()).find(|i| i.key == plane.key && i.write == write)
{
kept.used = copies;
return Ok(kept.image);
}
if let Some((.., why)) = (self.refused.iter())
.find(|(modifier, format, _)| *modifier == plane.modifier && *format == plane.format)
{
if let Some((.., why)) = self.refused.iter().find(|(modifier, format, w, _)| {
*modifier == plane.modifier && *format == plane.format && *w == write
}) {
return Err(CopyError::Refused(why.clone()));
}
if let Err(why) = self.importable(plane) {
let usage = usage_of(write);
if let Err(why) = self.importable(plane, usage) {
self.refused
.push((plane.modifier, plane.format, why.clone()));
.push((plane.modifier, plane.format, write, why.clone()));
return Err(CopyError::Refused(why));
}
if self.imports.len() >= MOST_IMPORTS
@@ -527,10 +636,11 @@ impl Objects {
}
let device = self.generation.device().clone();
let (image, memory) = device
.with_loader_word(|| self.make_import(vk_device, plane))
.with_loader_word(|| self.make_import(vk_device, plane, usage))
.map_err(|why| CopyError::Refused(format!("the plane's import: {why}")))?;
self.imports.push(Import {
key: plane.key,
write,
alive: plane.alive.clone(),
image,
memory,
@@ -540,8 +650,12 @@ impl Objects {
}
/// `Ok` where the device imports a dma-buf of `plane`'s modifier as an image of its format
/// that copies out; `Err` with why otherwise.
fn importable(&self, plane: &DmaBufPlane<'_>) -> Result<(), String> {
/// of `usage`, that copies out or in; `Err` with why otherwise.
fn importable(
&self,
plane: &DmaBufPlane<'_>,
usage: vk::ImageUsageFlags,
) -> Result<(), String> {
// SAFETY: the handles are used while the generation lives.
let handles = unsafe { self.generation.raw() };
let mut modifier = vk::PhysicalDeviceImageDrmFormatModifierInfoEXT::default()
@@ -553,7 +667,7 @@ impl Objects {
.format(plane.format.vk())
.ty(vk::ImageType::TYPE_2D)
.tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)
.usage(vk::ImageUsageFlags::TRANSFER_SRC)
.usage(usage)
.push_next(&mut modifier)
.push_next(&mut external);
let mut external_props = vk::ExternalImageFormatProperties::default();
@@ -570,8 +684,12 @@ impl Objects {
};
let format = plane.format;
let modifier = plane.modifier;
let usage = usage.as_raw();
answered.map_err(|e| {
format!("the device makes no {format:?} image of modifier {modifier:#x} from a dma-buf ({e})")
format!(
"the device makes no {format:?} image of modifier {modifier:#x} of usage \
{usage:#x} from a dma-buf ({e})"
)
})?;
let max = props.image_format_properties.max_extent;
if !(external_props
@@ -592,11 +710,12 @@ impl Objects {
Ok(())
}
/// An image over `plane`'s dma-buf, and its import (module docs).
/// An image of `usage` over `plane`'s dma-buf, and its import (module docs).
fn make_import(
&self,
vk_device: &ash::Device,
plane: &DmaBufPlane<'_>,
usage: vk::ImageUsageFlags,
) -> Result<(vk::Image, vk::DeviceMemory), String> {
let layouts = [vk::SubresourceLayout {
offset: plane.offset,
@@ -622,7 +741,7 @@ impl Objects {
.array_layers(1)
.samples(vk::SampleCountFlags::TYPE_1)
.tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)
.usage(vk::ImageUsageFlags::TRANSFER_SRC)
.usage(usage)
.sharing_mode(vk::SharingMode::EXCLUSIVE)
.initial_layout(vk::ImageLayout::UNDEFINED)
.push_next(&mut explicit)
@@ -821,6 +940,214 @@ impl Objects {
}
}
impl Objects {
/// Records the fills of `fills` from `sources` into `images` (module docs).
fn record_fill(
&self,
vk_device: &ash::Device,
fills: &[PlaneFill<'_>],
images: &[vk::Image],
sources: &[(vk::Buffer, u64)],
) -> Result<(), vk::Result> {
let color = vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
};
let (foreign, ours) = (vk::QUEUE_FAMILY_FOREIGN_EXT, self.generation.family());
let acquires: Vec<_> = (images.iter())
.map(|&image| {
vk::ImageMemoryBarrier::default()
.image(image)
.subresource_range(color)
.old_layout(vk::ImageLayout::GENERAL)
.new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
.src_queue_family_index(foreign)
.dst_queue_family_index(ours)
.dst_access_mask(vk::AccessFlags::TRANSFER_WRITE)
})
.collect();
let releases: Vec<_> = (images.iter())
.map(|&image| {
vk::ImageMemoryBarrier::default()
.image(image)
.subresource_range(color)
.old_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
.new_layout(vk::ImageLayout::GENERAL)
.src_queue_family_index(ours)
.dst_queue_family_index(foreign)
.src_access_mask(vk::AccessFlags::TRANSFER_WRITE)
})
.collect();
// The buffers' bytes as the host and the device's earlier work wrote them.
let read = [vk::MemoryBarrier::default()
.src_access_mask(vk::AccessFlags::HOST_WRITE | vk::AccessFlags::MEMORY_WRITE)
.dst_access_mask(vk::AccessFlags::TRANSFER_READ)];
let cb = self.buffer;
// SAFETY: the buffer is this copier's and not pending; every handle recorded is live
// through the fill (the images are kept, the buffers held by the caller's fills).
unsafe {
vk_device.reset_command_buffer(cb, vk::CommandBufferResetFlags::empty())?;
let begin = vk::CommandBufferBeginInfo::default()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
vk_device.begin_command_buffer(cb, &begin)?;
if let Some((pool, _)) = self.timestamps {
vk_device.cmd_reset_query_pool(cb, pool, 0, 2);
}
vk_device.cmd_pipeline_barrier(
cb,
vk::PipelineStageFlags::HOST | vk::PipelineStageFlags::ALL_COMMANDS,
vk::PipelineStageFlags::TRANSFER,
vk::DependencyFlags::empty(),
&read,
&[],
&acquires,
);
if let Some((pool, _)) = self.timestamps {
vk_device.cmd_write_timestamp(cb, vk::PipelineStageFlags::TOP_OF_PIPE, pool, 0);
}
for ((fill, &image), &(buffer, base)) in fills.iter().zip(images).zip(sources) {
let regions = fill_regions(fill, base);
vk_device.cmd_copy_buffer_to_image(
cb,
buffer,
image,
vk::ImageLayout::TRANSFER_DST_OPTIMAL,
&regions,
);
}
if let Some((pool, _)) = self.timestamps {
vk_device.cmd_write_timestamp(cb, vk::PipelineStageFlags::TRANSFER, pool, 1);
}
vk_device.cmd_pipeline_barrier(
cb,
vk::PipelineStageFlags::TRANSFER,
vk::PipelineStageFlags::BOTTOM_OF_PIPE,
vk::DependencyFlags::empty(),
&[],
&[],
&releases,
);
vk_device.end_command_buffer(cb)
}
}
}
/// The regions of `fill`, its picture at byte `base` of its `VkBuffer` (module docs): the
/// picture's texels from the plane's first; each column past them, to the plane's width, from
/// the picture's last column; and each row past them, to its height, from the picture's last
/// row, with that row's last texel in each column past the picture's.
fn fill_regions(fill: &PlaneFill<'_>, base: u64) -> Vec<vk::BufferImageCopy> {
let texel = fill.into.format.texel_bytes();
let row_length = u32::try_from(fill.bytes_per_row / texel).unwrap_or(u32::MAX);
let [width, height] = fill.extent;
let (plane_width, plane_height) = (fill.into.width, fill.into.height);
let region = |from: u64, x: u32, y: u32, w: u32, h: u32| vk::BufferImageCopy {
buffer_offset: from,
buffer_row_length: row_length,
buffer_image_height: h,
image_subresource: vk::ImageSubresourceLayers {
aspect_mask: vk::ImageAspectFlags::COLOR,
mip_level: 0,
base_array_layer: 0,
layer_count: 1,
},
image_offset: vk::Offset3D {
x: i32::try_from(x).unwrap_or(i32::MAX),
y: i32::try_from(y).unwrap_or(i32::MAX),
z: 0,
},
image_extent: vk::Extent3D {
width: w,
height: h,
depth: 1,
},
};
let last_column = base + u64::from(width - 1) * texel;
let last_row = base + u64::from(height - 1) * fill.bytes_per_row;
let mut regions = vec![region(base, 0, 0, width, height)];
for x in width..plane_width {
regions.push(region(last_column, x, 0, 1, height));
}
for y in height..plane_height {
regions.push(region(last_row, 0, y, width, 1));
for x in width..plane_width {
regions.push(region(last_row + u64::from(width - 1) * texel, x, y, 1, 1));
}
}
regions
}
/// The `VkBuffer` `fill` reads and its byte there: `Err` where its buffer is of another
/// generation of the device than the copier's `generation`, its `VkBuffer` may not hold its
/// pages' bytes, or the picture lies past the buffer, off its texels' alignment or past the
/// plane (module docs).
fn source(fill: &PlaneFill<'_>, generation: &Generation) -> Result<(vk::Buffer, u64), CopyError> {
let refused = |why: String| CopyError::Refused(why);
let buffer = &fill.from.raw;
if !generation.is_of(&buffer.device()) {
return Err(refused(
"the buffer was made on the device's VkDevice before its recovery".to_owned(),
));
}
if let Some(rt::HostBacking::Copied) = buffer.host_backing() {
return Err(refused(
"the buffer's pages are a copy the runtime keeps, which its VkBuffer may not hold"
.to_owned(),
));
}
let texel = fill.into.format.texel_bytes();
let [width, height] = fill.extent;
if width == 0 || height == 0 {
return Err(refused("an empty plane".to_owned()));
}
if !fill.bytes_per_row.is_multiple_of(texel) || !fill.offset.is_multiple_of(texel) {
return Err(refused(format!(
"a plane at {} with rows of {} bytes, not of whole {texel}-byte texels",
fill.offset, fill.bytes_per_row
)));
}
let row = u64::from(width) * texel;
let end = (fill.bytes_per_row.checked_mul(u64::from(height - 1)))
.and_then(|rows| rows.checked_add(row))
.and_then(|bytes| bytes.checked_add(fill.offset));
if row > fill.bytes_per_row || !end.is_some_and(|end| end <= buffer.length()) {
return Err(refused(format!(
"a plane of {height} rows of {row} bytes, {} apart, at {}, past its buffer's {} bytes",
fill.bytes_per_row,
fill.offset,
buffer.length()
)));
}
if width > fill.into.width || height > fill.into.height {
return Err(refused(format!(
"a {width}x{height} picture in a {}x{} plane",
fill.into.width, fill.into.height
)));
}
// SAFETY: the copier uses the `VkBuffer` only while the caller's fill holds the buffer, and
// orders its read against the runtime's work as the module docs say.
let (vk_buffer, base) = unsafe { buffer.vk_buffer() };
let at = base + fill.offset;
if !at.is_multiple_of(texel) {
return Err(refused(format!(
"a plane at byte {at} of its VkBuffer, not on a {texel}-byte texel"
)));
}
Ok((vk_buffer, at))
}
/// The usage of an import for the copier's writes (a fill's), else for its reads.
fn usage_of(write: bool) -> vk::ImageUsageFlags {
if write {
vk::ImageUsageFlags::TRANSFER_DST
} else {
vk::ImageUsageFlags::TRANSFER_SRC
}
}
/// The `VkBuffer` `copy` writes and its byte there: `Err` where its buffer is of another
/// generation of the device than the copier's `generation` (made before the device's recovery),
/// its bytes are not its memory, or the copy lies past the buffer or off its texels' alignment
@@ -40,10 +40,11 @@ use reims_vgpu_video::nvidia::{
EncodeParams, EncodeProfile, EncodeProfileSupport, EncodeRateControl, Gpu, NvencEncoder,
PictureType, RawFrame, Tuning,
};
use reims_vgpu_vulkan::core::platform::Platform;
use reims_vgpu_vulkan::core::sync::Mutex;
use super::super::video_host::{
BackendError, EncodeFrame, EncodeSource, Encoded, HostEncodedFrame, HostEncoder, SourcePlane,
BackendError, EncodeFrame, Encoded, FrameSource, HostEncodedFrame, HostEncoder, SourcePlane,
};
use super::{H264_TOP_LEVEL, HEVC_TOP_LEVEL};
@@ -322,7 +323,7 @@ impl NvencHostEncoder {
}
}
impl HostEncoder for NvencHostEncoder {
impl<P: Platform> HostEncoder<P> for NvencHostEncoder {
fn check(&self, settings: &RgfxVideoEncodeSettings) -> Result<(), BackendError> {
let codec = self.state.lock().codec;
let profile = encode_profile(codec, settings.profile)
@@ -356,7 +357,7 @@ impl HostEncoder for NvencHostEncoder {
Ok(())
}
fn encode(&mut self, frame: EncodeFrame) -> Result<Box<dyn HostEncodedFrame>, BackendError> {
fn encode(&mut self, frame: EncodeFrame) -> Result<Box<dyn HostEncodedFrame<P>>, BackendError> {
Ok(Box::new(NvencFrame {
state: Arc::clone(&self.state),
frame,
@@ -370,12 +371,13 @@ struct NvencFrame {
frame: EncodeFrame,
}
impl HostEncodedFrame for NvencFrame {
impl<P: Platform> HostEncodedFrame<P> for NvencFrame {
fn finish(
self: Box<Self>,
source: &EncodeSource,
source: &mut FrameSource<'_, P>,
out: &mut [u8],
) -> Result<Encoded, BackendError> {
let source = source.host()?;
let mut state = self.state.lock();
if let Some(settings) = &self.frame.settings {
state.apply(settings)?;
@@ -413,9 +413,12 @@ fn each_profile_encodes_through_a_session_and_decodes_back_on_nvdec() {
..s
},
] {
assert!(encoder.check(&refused).is_err(), "{what}: {refused:?}");
assert!(
HostEncoder::<FakePlatform>::check(&encoder, &refused).is_err(),
"{what}: {refused:?}"
);
}
encoder.check(&s).expect("settings NVENC takes");
HostEncoder::<FakePlatform>::check(&encoder, &s).expect("settings NVENC takes");
let session = HostEncodeSession::<FakePlatform>::new(
&p.device(),
entry.codec,
+27 -2
View File
@@ -79,7 +79,7 @@ use reims_vgpu_video::core::runtime::Runtime;
use reims_vgpu_video::core::surfaces::{PlaneLayout, SurfaceLayout};
use reims_vgpu_video::vaapi::{
Capabilities, ConfigCapabilities, Display, EncoderSupport, Entrypoint, Frame, GuestWrites,
H264_MAX_MACROBLOCKS, H264Decoder, HevcDecoder, ImportWrites, PlaneRows, Profile,
H264_MAX_MACROBLOCKS, H264Decoder, HevcDecoder, ImportWrites, InputSurface, PlaneRows, Profile,
TARGET_ALIGNMENT, Target, TargetChecks, TargetCodec, TargetFor, TargetFormat, TargetPlane,
TargetShape, encoder_support,
};
@@ -281,12 +281,17 @@ impl<P: Platform> GraphicsVideo<P> for VaapiVideo<P> {
let entry = (self.caps.iter()).find(|c| c.codec == codec && c.direction == direction)?;
if direction == RGFX_VIDEO_ENCODE {
let caps = encode::encode_caps(entry, &self.encoders);
let filler = match self.copies.as_ref() {
Some(copies) => copies.filler(),
None => Err("the platform makes no GPU copies".to_owned()),
};
let encoder = encode::VaEncoder::new(
&self.display,
codec,
Arc::clone(&self.encoders),
entry,
&caps,
filler,
);
let session = HostEncodeSession::new(&self.device, codec, NAME, Box::new(encoder))?;
return Some(Arc::new(session));
@@ -924,10 +929,30 @@ impl<P: Platform> HostPicture<P> for VaPicture<P> {
}
/// What makes the GPU copies of a video's sessions (the module doc's second way): one copier a
/// session.
/// decode session, and one filler an encode session (`encode`'s module doc).
pub(crate) trait GpuCopies<P: Platform>: Send + Sync {
/// A session's copier; `Err` with why where the device makes none.
fn copier(&self) -> Result<Box<dyn GpuCopier<P>>, String>;
/// An encode session's filler; `Err` with why where the device makes none.
fn filler(&self) -> Result<Box<dyn GpuFiller<P>>, String>;
}
/// One encode session's GPU copies of its frames into its encoder's input surfaces.
pub(crate) trait GpuFiller<P: Platform>: Send {
/// Writes the frame of `size`, of samples of `sample` bytes, in `luma` and `chroma` where they
/// lie, into `surface`, an input surface of the encoder's of its coded size, the margin past
/// the frame filled as the VA crate's upload fills it, and returns once the GPU wrote it;
/// [`DeviceWrite::Declined`] with why, nothing written, where it cannot. `Err` where the copy
/// failed once on the GPU, which may write the surface still.
fn fill(
&mut self,
surface: &InputSurface,
luma: &OutputPlane<P>,
chroma: &OutputPlane<P>,
size: (u32, u32),
sample: u32,
) -> Result<DeviceWrite, BackendError>;
}
/// One session's GPU copies of its pictures into their outputs.
+217 -63
View File
@@ -14,11 +14,16 @@
//! unit is a keyframe with its parameter sets; a change of the bitrates, QPs or frame rate goes
//! to the encoder from the next frame. `min_qp`, `max_qp` and a change of `quality` alone are
//! not taken: the VA crate's encoder has no such setting.
//! - **A frame** ([`VaFrame`]) is read on the session's encode thread from the source's host
//! bytes, uploaded and encoded by the VA crate's encoder, and its sample, NAL units behind
//! four-byte lengths, written as Annex B: a keyframe's parameter sets first, from the encoder's
//! configuration record (`avcC`, `hvcC`). One that does not fit the capacity is not written,
//! and the next frame is made a keyframe.
//! - **A frame** ([`VaFrame`]) reaches the encoder on the session's encode thread one of two
//! ways. By the runtime device's GPU, where the session has its copier (`super::gpu_copy`): a
//! copy of the source's planes, where they lie, in the surface's pages or its device caches,
//! into an input surface of the encoder's, exported as dma-bufs (the VA crate's
//! `VideoEncoder::input_surface`), its margin to the coded size filled as an upload fills it, so
//! the encoder codes the same bytes either way. Else, and where the copy is declined (said once
//! a session, with why, at info), from the source's host bytes, which the VA crate's encoder
//! uploads. Its sample, NAL units behind four-byte lengths, is written as Annex B: a keyframe's
//! parameter sets first, from the encoder's configuration record (`avcC`, `hvcC`). One that
//! does not fit the capacity is not written, and the next frame is made a keyframe.
use std::sync::Arc;
@@ -33,16 +38,19 @@ use reims_vgpu_graphics::wire::{
RGFX_VIDEO_HEVC_MAIN, RGFX_VIDEO_HEVC_MAIN_10, RgfxVideoCodecCaps, RgfxVideoEncodeCaps,
};
use reims_vgpu_video::codec::encode::{
ColourDescription, EncoderSettings, Entropy, FrameRate, FrameType, InputFrame, Plane,
Coded, ColourDescription, EncoderSettings, Entropy, FrameRate, FrameType, InputFrame, Plane,
Profile as EncodeProfile, RateControl,
};
use reims_vgpu_video::vaapi::{Capabilities, Display, EncoderSupport, VideoEncoder};
use reims_vgpu_video::core::backend::DeviceWrite;
use reims_vgpu_video::vaapi::{Capabilities, Display, EncoderSupport, InputSurface, VideoEncoder};
use reims_vgpu_vulkan::core::platform::Platform;
use reims_vgpu_vulkan::core::sync::Mutex;
use super::super::video_host::{
BackendError, EncodeFrame, EncodeSource, Encoded, HostEncodedFrame, HostEncoder, SourcePlane,
BackendError, EncodeFrame, EncodeSource, Encoded, FrameSource, HostEncodedFrame, HostEncoder,
SourcePlane,
};
use super::{H264_TOP_LEVEL, HEVC_TOP_LEVEL, MIN_SIZE};
use super::{GpuFiller, H264_TOP_LEVEL, HEVC_TOP_LEVEL, MIN_SIZE, NAME};
/// `VA_RC_CBR`, `VA_RC_VBR` and `VA_RC_CQP` (va.h): rate control bits of
/// `VAConfigAttribRateControl`.
@@ -320,9 +328,32 @@ impl State {
}
}
/// A session's GPU filler, its frames' to share, or why it has none; and the reasons a frame was
/// uploaded instead, each said once.
struct Fills<P: Platform> {
filler: Result<Box<dyn GpuFiller<P>>, String>,
said: Vec<String>,
/// The input surfaces of fills that failed on the GPU, which may write them still: kept out
/// of the encoder's pool while the session lives.
failed: Vec<InputSurface>,
}
impl<P: Platform> Fills<P> {
/// Says, once a session, and at info once per process (`kind`), why a frame was uploaded by
/// the CPU.
fn uploaded_because(&mut self, why: String) {
if !self.said.contains(&why) {
log::info!(kind:% = why; "hardware video: {NAME}: a frame uploaded by the CPU: {why}");
self.said.push(why);
}
}
}
/// A session's encoder on VA-API ([`HostEncoder`]).
pub(super) struct VaEncoder {
pub(super) struct VaEncoder<P: Platform> {
state: Arc<Mutex<State>>,
/// What writes its frames into the encoder's input surfaces on the GPU (module doc).
fills: Arc<Mutex<Fills<P>>>,
/// The profiles the driver encodes, which [`HostEncoder::check`] holds settings to.
supports: Arc<[EncoderSupport]>,
/// The sizes the codec's entry gives.
@@ -332,15 +363,17 @@ pub(super) struct VaEncoder {
rate_controls: u32,
}
impl VaEncoder {
impl<P: Platform> VaEncoder<P> {
/// An encoder of `codec` on `display`, which encodes `supports`, as its entry `entry` and
/// `encode` list them.
/// `encode` list them, its frames written into its input surfaces by `filler` where it is
/// given (or why not).
pub(super) fn new(
display: &Display,
codec: u32,
supports: Arc<[EncoderSupport]>,
entry: &RgfxVideoCodecCaps,
encode: &RgfxVideoEncodeCaps,
filler: Result<Box<dyn GpuFiller<P>>, String>,
) -> Self {
let ranges = (supports.iter())
.map(|s| (wire_profile(s.profile), s.capabilities.quality_range))
@@ -356,6 +389,11 @@ impl VaEncoder {
settings: None,
key_next: false,
})),
fills: Arc::new(Mutex::new(Fills {
filler,
said: Vec::new(),
failed: Vec::new(),
})),
supports,
min_size: entry.min_size,
max_size: entry.max_size,
@@ -364,7 +402,7 @@ impl VaEncoder {
}
}
impl HostEncoder for VaEncoder {
impl<P: Platform> HostEncoder<P> for VaEncoder<P> {
fn check(&self, settings: &RgfxVideoEncodeSettings) -> Result<(), BackendError> {
let codec = self.state.lock().codec;
let profile = encode_profile(codec, settings.profile)
@@ -398,23 +436,104 @@ impl HostEncoder for VaEncoder {
Ok(())
}
fn encode(&mut self, frame: EncodeFrame) -> Result<Box<dyn HostEncodedFrame>, BackendError> {
Ok(Box::new(VaFrame {
fn encode(&mut self, frame: EncodeFrame) -> Result<Box<dyn HostEncodedFrame<P>>, BackendError> {
Ok(Box::new(self.frame(frame)))
}
}
impl<P: Platform> VaEncoder<P> {
/// The encode of `frame` ([`HostEncoder::encode`]).
fn frame(&self, frame: EncodeFrame) -> VaFrame<P> {
VaFrame {
state: Arc::clone(&self.state),
fills: Arc::clone(&self.fills),
frame,
}))
}
}
}
/// One frame's encode on VA-API, which the session's encode thread finishes (module doc).
struct VaFrame {
struct VaFrame<P: Platform> {
state: Arc<Mutex<State>>,
fills: Arc<Mutex<Fills<P>>>,
frame: EncodeFrame,
}
impl HostEncodedFrame for VaFrame {
impl<P: Platform> HostEncodedFrame<P> for VaFrame<P> {
fn finish(
self: Box<Self>,
source: &mut FrameSource<'_, P>,
out: &mut [u8],
) -> Result<Encoded, BackendError> {
let mut state = self.state.lock();
if let Some(settings) = &self.frame.settings {
state.apply(settings)?;
}
let input = self.times(&state)?;
if let Some(encoded) = self.filled(&mut state, &input, source, out)? {
return Ok(encoded);
}
let host = source.host()?;
encode_host(&mut state, &input, &host, out)
}
}
impl<P: Platform> VaFrame<P> {
/// The frame encoded from `source`'s planes where they lie, copied by the GPU into an input
/// surface of the encoder's (module doc), into `out`; `None` where the copy was declined,
/// nothing written, which is said once a session. `Err` where the encode failed, or the copy
/// failed once on the GPU.
fn filled(
&self,
state: &mut State,
input: &InputFrame<'_>,
source: &FrameSource<'_, P>,
out: &mut [u8],
) -> Result<Option<Encoded>, BackendError> {
let mut fills = self.fills.lock();
let declined = match &mut fills.filler {
Ok(filler) => {
let encoder = state.encoder.as_mut().ok_or("an encode with no settings")?;
match encoder.input_surface() {
Ok(surface) => {
let [luma, chroma] = source.planes();
let sample = encoder.settings().input_format().bytes_per_sample();
let sample = u32::try_from(sample).unwrap_or(0);
match filler.fill(&surface, luma, chroma, source.size(), sample) {
Ok(DeviceWrite::Written) => {
drop(fills);
let coded = encoder.encode_surface(surface, input)?;
return finish_coded(state, coded, out).map(Some);
}
Ok(DeviceWrite::Declined(why)) => format!("the GPU's copy: {why}"),
// The GPU may write the surface still: it stays out of the pool, and
// the session's frames are uploaded from here on.
Err(error) => {
fills.failed.push(surface);
fills.filler = Err(format!("the GPU's copy failed: {error}"));
return Err(error);
}
}
}
// The driver's surfaces export so for none of its frames: the session's
// frames are uploaded from here on.
Err(why) => {
let why = format!("no input surface for the GPU's copy: {why}");
fills.filler = Err(why.clone());
why
}
}
}
Err(why) => why.clone(),
};
fills.uploaded_because(declined);
Ok(None)
}
/// [`HostEncodedFrame::finish`] from `source`'s host bytes, which the encoder uploads.
#[cfg(test)]
fn finish_from_host(
self,
source: &EncodeSource,
out: &mut [u8],
) -> Result<Encoded, BackendError> {
@@ -422,59 +541,94 @@ impl HostEncodedFrame for VaFrame {
if let Some(settings) = &self.frame.settings {
state.apply(settings)?;
}
let codec = state.codec;
let force_key_frame = self.frame.force_keyframe || state.key_next;
let encoder = state.encoder.as_mut().ok_or("an encode with no settings")?;
let input = self.times(&state)?;
encode_host(&mut state, &input, source, out)
}
/// The frame's times, key-frame demand and tag as the encoder takes them, with no planes.
fn times(&self, state: &State) -> Result<InputFrame<'static>, BackendError> {
let encoder = state.encoder.as_ref().ok_or("an encode with no settings")?;
let duration = i64::from(encoder.settings().frame_rate.denominator);
let index = i64::try_from(self.frame.frame_index).unwrap_or(i64::MAX);
let input = InputFrame {
planes: [plane(&source.luma)?, plane(&source.chroma)?],
let none = Plane {
data: &[],
bytes_per_row: 0,
};
Ok(InputFrame {
planes: [none, none],
pts: index.saturating_mul(duration),
duration,
force_key_frame,
force_key_frame: self.frame.force_keyframe || state.key_next,
id: self.frame.frame_index,
};
let mut coded = encoder.encode(&input)?;
let sample = match (coded.pop(), coded.len()) {
(Some(Ok(sample)), 0) => sample,
(Some(Err(failed)), 0) => {
let why = failed
.error
.map_or_else(|| "lost".to_owned(), |e| e.to_string());
return Err(format!("the frame's picture: {why}").into());
}
(None, _) => return Err("the encoder gave no sample for the frame".into()),
(Some(_), n) => return Err(format!("the encoder gave {} samples", n + 1).into()),
};
let configuration = sample.is_sync.then(|| encoder.configuration());
let au = annex_b(codec, configuration.as_deref(), &sample.data)?;
let mut encoded = Encoded {
size: au.len() as u64,
overflow: false,
keyframe: sample.is_sync,
parameter_sets: sample.is_sync,
frame_index: sample.id,
picture_type: match sample.frame_type {
FrameType::Idr => RGFX_VIDEO_PICTURE_I,
FrameType::P => RGFX_VIDEO_PICTURE_P,
FrameType::B => RGFX_VIDEO_PICTURE_B,
},
};
match out.get_mut(..au.len()) {
Some(to) => {
to.copy_from_slice(&au);
state.key_next = false;
}
None => {
// The frame is in the encoder's references: the next one starts afresh.
encoded.overflow = true;
state.key_next = true;
}
}
Ok(encoded)
})
}
}
/// Encodes the frame of `input`'s times from `source`'s host bytes, which the encoder uploads,
/// into `out`.
fn encode_host(
state: &mut State,
input: &InputFrame<'_>,
source: &EncodeSource,
out: &mut [u8],
) -> Result<Encoded, BackendError> {
let encoder = state.encoder.as_mut().ok_or("an encode with no settings")?;
let input = InputFrame {
planes: [plane(&source.luma)?, plane(&source.chroma)?],
..*input
};
let coded = encoder.encode(&input)?;
finish_coded(state, coded, out)
}
/// Writes the one sample of `coded`, the frame's, into `out` as an Annex-B access unit where it
/// fits (module doc), and answers what came of it.
fn finish_coded(
state: &mut State,
mut coded: Vec<Coded<reims_vgpu_video::vaapi::Error>>,
out: &mut [u8],
) -> Result<Encoded, BackendError> {
let codec = state.codec;
let encoder = state.encoder.as_mut().ok_or("an encode with no settings")?;
let sample = match (coded.pop(), coded.len()) {
(Some(Ok(sample)), 0) => sample,
(Some(Err(failed)), 0) => {
let why = failed
.error
.map_or_else(|| "lost".to_owned(), |e| e.to_string());
return Err(format!("the frame's picture: {why}").into());
}
(None, _) => return Err("the encoder gave no sample for the frame".into()),
(Some(_), n) => return Err(format!("the encoder gave {} samples", n + 1).into()),
};
let configuration = sample.is_sync.then(|| encoder.configuration());
let au = annex_b(codec, configuration.as_deref(), &sample.data)?;
let mut encoded = Encoded {
size: au.len() as u64,
overflow: false,
keyframe: sample.is_sync,
parameter_sets: sample.is_sync,
frame_index: sample.id,
picture_type: match sample.frame_type {
FrameType::Idr => RGFX_VIDEO_PICTURE_I,
FrameType::P => RGFX_VIDEO_PICTURE_P,
FrameType::B => RGFX_VIDEO_PICTURE_B,
},
};
match out.get_mut(..au.len()) {
Some(to) => {
to.copy_from_slice(&au);
state.key_next = false;
}
None => {
// The frame is in the encoder's references: the next one starts afresh.
encoded.overflow = true;
state.key_next = true;
}
}
Ok(encoded)
}
/// The rows of `p` as the VA crate's encoder reads a plane: from its first row's first byte to
/// its last row's last.
fn plane(p: &SourcePlane) -> Result<Plane<'_>, BackendError> {
@@ -2,6 +2,9 @@ use reims_vgpu_graphics::wire::RGFX_VIDEO_DECODE;
use reims_vgpu_video::core::runtime::StdRuntime;
use reims_vgpu_video::vaapi::{H264Decoder, HevcDecoder, encoder_support};
use reims_vgpu_vulkan::VulkanPlatform;
use reims_vgpu_vulkan::core::platform::Handle as _;
use super::*;
/// Settings of a 320x192 stream of `profile` of `codec` at a constant QP.
@@ -389,9 +392,15 @@ fn each_profile_encodes_on_the_driver_and_decodes_back() {
.filter(|b| entry.profiles & b != 0)
{
let s = settings(entry.codec, bit);
let mut encoder =
VaEncoder::new(&display, entry.codec, Arc::clone(&supports), entry, &rates);
encoder.check(&s).unwrap();
let encoder = VaEncoder::<VulkanPlatform>::new(
&display,
entry.codec,
Arc::clone(&supports),
entry,
&rates,
Err("the test copies none by the GPU".to_owned()),
);
HostEncoder::<VulkanPlatform>::check(&encoder, &s).unwrap();
let sets: &[u8] = if entry.codec == RGFX_VIDEO_CODEC_H264 {
&[7, 8]
} else {
@@ -405,7 +414,7 @@ fn each_profile_encodes_on_the_driver_and_decodes_back() {
frame_index: index,
force_keyframe: false,
};
let frame = encoder.encode(frame).unwrap();
let frame = encoder.frame(frame);
let (luma, chroma) = picture(&s, index);
let row = luma.len() / s.height as usize;
let source = EncodeSource {
@@ -425,7 +434,7 @@ fn each_profile_encodes_on_the_driver_and_decodes_back() {
height: s.height,
};
let mut out = vec![0u8; capacity(index)];
let encoded = frame.finish(&source, &mut out).unwrap();
let encoded = frame.finish_from_host(&source, &mut out).unwrap();
assert_eq!(encoded.frame_index, index);
let au = out[..encoded.size.min(out.len() as u64) as usize].to_vec();
let types = nal_types(entry.codec, &au);
@@ -480,3 +489,200 @@ fn each_profile_encodes_on_the_driver_and_decodes_back() {
}
}
}
/// A frame the runtime device's GPU copies into an input surface of the encoder's
/// (`gpu_copy`'s filler) encodes as the same frame uploaded by the CPU, byte for byte: on the
/// driver of the runtime device's GPU, for each codec and profile it encodes, 6 frames of a
/// moving picture at a constant QP, 320x192 (no margin to the coded size) and 330x202 (a margin
/// of columns and rows), each in a runtime buffer, its own memory or over host pages, by turns,
/// rows wider than the picture's (512 bytes apart for 8-bit samples, 768 or 1024 for 16-bit)
/// from byte 32. Two encoders of the same settings code the frames, one from the host bytes, one
/// from the filled surfaces; every access unit of the second is the first's.
/// A device with no GPU copier checks nothing: the test says so and ends.
#[test]
#[ignore = "needs a VA-API GPU: run on the VA-API host"]
fn a_frame_filled_by_the_gpu_encodes_as_the_uploaded_frame_byte_for_byte() {
use reims_vgpu_video::codec::encode::{InputFrame, Plane};
use reims_vgpu_vulkan::core::platform::HostRange;
use reims_vgpu_vulkan::core::platform::device::GpuDevice as _;
use reims_vgpu_vulkan::core::platform::os::vm::HostVm as _;
use reims_vgpu_vulkan::core::platform::resource::Buffer as _;
use reims_vgpu_vulkan::core::raise::OnFault;
use reims_vgpu_vulkan::remap::VulkanVm;
use super::super::super::video_host::OutputPlane;
use super::super::{GpuCopies as _, gpu_copy};
let platform = Arc::new(VulkanPlatform::new());
crate::entry::run(|_| {
let device = VulkanPlatform::system_default_device().expect("a Vulkan device");
let node = reims_vgpu_vulkan::host_gpus::render_node_of(&device.raw).expect("a node");
let runtime = crate::video::runtime::PlatformRuntime::of(&platform);
let display = Display::open(&node, runtime).expect("a VA display on the device's GPU");
let copies = gpu_copy::RuntimeCopies::new(&device);
let mut filler = match copies.filler() {
Ok(filler) => filler,
Err(why) => {
assert!(
why.starts_with("the device lists no "),
"a GPU filler: {why}"
);
eprintln!("no GPU filler on the device, so no frame to compare: {why}");
return;
}
};
let supports: Arc<[EncoderSupport]> = encoder_support(&display).into();
let entries = encode_caps_of(&supports, &display.capabilities().unwrap());
assert!(
!entries.is_empty(),
"the driver encodes neither H.264 nor HEVC"
);
let vm = VulkanVm::new();
let first = 32u64;
let mut frames = 0;
for entry in &entries {
for bit in (0..32)
.map(|b| 1u32 << b)
.filter(|b| entry.profiles & b != 0)
{
for (width, height) in [(320u32, 192u32), (330, 202)] {
let s = RgfxVideoEncodeSettings {
width,
height,
..settings(entry.codec, bit)
};
let what = format!("codec {} profile {bit:#x} {width}x{height}", entry.codec);
let made = settings_of(entry.codec, &s, None).expect("the VA settings");
let mut by_cpu = VideoEncoder::new(&display, made.clone()).expect("an encoder");
let mut by_gpu = VideoEncoder::new(&display, made).expect("an encoder");
let sample = made_sample(&s);
let row = u64::from(width) * sample;
// Rows wider than the picture's, from a byte past the buffer's start: 512
// apart for 8-bit samples, 768 or 1024 for 16-bit ones.
let pitch = (row + 128).next_multiple_of(256);
let chroma_at = first + pitch * u64::from(height);
let len = (chroma_at + pitch * u64::from(height / 2))
.next_multiple_of(vm.page_size());
for n in 0..6u64 {
let (luma, chroma) = picture(&s, n);
// The frame's bytes in a buffer: the device's own memory, or host pages.
let (buffer, at) = if n % 2 == 0 {
let buffer = (device.new_buffer_of_length(OnFault::Return, len, 0))
.expect("no raise")
.expect("a buffer");
let at = buffer.contents();
(buffer, at)
} else {
let at = vm.allocate_anywhere(len).expect("host pages");
// SAFETY: the pages stay mapped until the runtime's release of the
// buffer runs the deallocator, as `land_both_ways` keeps them.
let bytes = unsafe { HostRange::new(at, len) };
let unmap: Box<dyn FnOnce() + Send> = Box::new(move || {
let _ = VulkanVm::new().deallocate(at, len);
});
let buffer = (device.new_buffer_over_host_memory(
OnFault::Return,
bytes,
0,
Some(unmap),
))
.expect("no raise")
.expect("a buffer over the pages");
(buffer, at)
};
for (plane, from, rows) in [
(first, &luma, u64::from(height)),
(chroma_at, &chroma, u64::from(height / 2)),
] {
for r in 0..rows {
let src = &from[(r * row) as usize..((r + 1) * row) as usize];
// SAFETY: the row lies in the buffer's `len` host bytes, which no
// GPU work reaches yet.
unsafe {
std::ptr::copy_nonoverlapping(
src.as_ptr(),
at.wrapping_add(plane + r * pitch).as_ptr::<u8>(),
src.len(),
);
}
}
}
let plane = |offset: u64, rows: u64, w: u64| OutputPlane {
buffer: buffer.clone_ref(),
offset,
bytes_per_row: pitch,
row_bytes: row,
width: w,
height: rows,
rows_held: rows,
cached: n % 2 == 0,
host: Some(at.wrapping_add(offset)),
pages: None,
cache: None,
};
let luma_plane = plane(first, u64::from(height), u64::from(width));
let chroma_plane =
plane(chroma_at, u64::from(height / 2), u64::from(width / 2));
let input = InputFrame {
planes: [
Plane {
data: &luma,
bytes_per_row: row as usize,
},
Plane {
data: &chroma,
bytes_per_row: row as usize,
},
],
pts: i64::try_from(n).expect("a time"),
duration: 1,
force_key_frame: false,
id: n,
};
let uploaded = by_cpu.encode(&input).expect("the upload's encode");
let surface = by_gpu.input_surface().expect("an input surface");
let written = filler
.fill(
&surface,
&luma_plane,
&chroma_plane,
(width, height),
u32::try_from(sample).expect("a sample"),
)
.expect("the GPU's copy");
match written {
DeviceWrite::Written => {}
DeviceWrite::Declined(why) => panic!("{what}: declined: {why}"),
}
let filled = by_gpu.encode_surface(surface, &input).expect("the encode");
let data =
|coded: &[Coded<reims_vgpu_video::vaapi::Error>]| -> Vec<Vec<u8>> {
(coded.iter())
.map(|c| c.as_ref().expect("a sample").data.to_vec())
.collect()
};
let (a, b) = (data(&uploaded), data(&filled));
assert_eq!(a.len(), b.len(), "{what} frame {n}: samples");
assert!(
a == b,
"{what} frame {n}: the filled frame's access unit differs"
);
frames += 1;
drop((luma_plane, chroma_plane, buffer));
}
}
}
}
eprintln!("{frames} frames filled by the GPU encoded as uploaded");
assert!(frames > 0);
});
}
/// The bytes of a sample of `settings`' format.
fn made_sample(settings: &RgfxVideoEncodeSettings) -> u64 {
if settings.format == RGFX_VIDEO_FORMAT_P010 {
2
} else {
1
}
}
@@ -14,18 +14,27 @@
//! only where the device is lost.
//!
//! Each session logs at its end how many pictures went this way, and their GPU time.
//!
//! An encode session's frames go the other way the same way (`super::encode`'s module doc): the
//! runtime device's GPU copies the source's planes, where they lie, into an input surface of the
//! VA crate's encoder, exported as dma-bufs for writing, with the copier's fill
//! (`PlaneCopier::fill`), which fills the margin to the coded size as the VA crate's upload
//! fills it. The fill waits for the GPU as the copy does; the encode follows once it is done.
//! Each encode session logs at its end how many frames went this way, and their GPU time.
use std::sync::Arc;
use std::time::Duration;
use reims_vgpu_video::core::backend::DeviceWrite;
use reims_vgpu_video::vaapi::Frame;
use reims_vgpu_video::vaapi::{Frame, InputSurface};
use reims_vgpu_vulkan::VulkanPlatform;
use reims_vgpu_vulkan::gpu::device::VulkanDevice;
use reims_vgpu_vulkan::os::{CopyError, DmaBufPlane, PlaneCopier, PlaneCopy, PlaneFormat};
use reims_vgpu_vulkan::os::{
CopyError, DmaBufPlane, PlaneCopier, PlaneCopy, PlaneFill, PlaneFormat,
};
use super::super::video_host::{BackendError, OutputPlane};
use super::{GpuCopier, GpuCopies, NAME, Room, crop_extent};
use super::{GpuCopier, GpuCopies, GpuFiller, NAME, Room, crop_extent};
/// The copies of a runtime device's sessions.
pub(super) struct RuntimeCopies {
@@ -52,6 +61,126 @@ impl GpuCopies<VulkanPlatform> for RuntimeCopies {
longest: Duration::ZERO,
}))
}
fn filler(&self) -> Result<Box<dyn GpuFiller<VulkanPlatform>>, String> {
let copier = PlaneCopier::new(&self.device)?;
Ok(Box::new(RuntimeFiller {
copier,
times: Times::default(),
}))
}
}
/// The GPU times of a session's copies: how many, their sum over those the queue timed, and the
/// longest.
#[derive(Default)]
struct Times {
count: u64,
gpu: Duration,
timed: u64,
longest: Duration,
}
impl Times {
fn add(&mut self, gpu: Option<Duration>) {
self.count += 1;
if let Some(gpu) = gpu {
self.gpu += gpu;
self.timed += 1;
self.longest = self.longest.max(gpu);
}
}
/// Their count, mean GPU time and longest, as the log lines say them.
fn said(&self) -> String {
let ms = |d: Duration| d.as_secs_f64() * 1e3;
let mean = self.gpu / u32::try_from(self.timed.max(1)).unwrap_or(u32::MAX);
format!(
"{}, {:.3} ms of GPU time each, {:.3} ms at most ({} timed)",
self.count,
ms(mean),
ms(self.longest),
self.timed
)
}
}
/// One encode session's fills of its encoder's input surfaces, and their times.
struct RuntimeFiller {
copier: PlaneCopier,
times: Times,
}
impl GpuFiller<VulkanPlatform> for RuntimeFiller {
fn fill(
&mut self,
surface: &InputSurface,
luma: &OutputPlane<VulkanPlatform>,
chroma: &OutputPlane<VulkanPlatform>,
size: (u32, u32),
sample: u32,
) -> Result<DeviceWrite, BackendError> {
let formats = match sample {
1 => [PlaneFormat::R8, PlaneFormat::Rg8],
2 => [PlaneFormat::R16, PlaneFormat::Rg16],
bytes => return Ok(DeviceWrite::Declined(format!("samples of {bytes} bytes"))),
};
let export = surface.export();
let (coded_width, coded_height) = export.size();
let (width, height) = size;
// A key a plane of this export: its life's address, unique while it lives.
let key = u64::try_from(Arc::as_ptr(export).addr()).unwrap_or(0);
let planes = [
(luma, [width, height], [coded_width, coded_height]),
(
chroma,
[width / 2, height / 2],
[coded_width / 2, coded_height / 2],
),
];
let fills: Vec<PlaneFill<'_>> = (planes.iter().zip(formats).enumerate())
.map(|(i, (&(plane, extent, size), format))| {
let exported = export.plane(i);
PlaneFill {
into: DmaBufPlane {
key: key.wrapping_mul(2).wrapping_add(u64::from(i == 1)),
alive: export.alive(),
fd: export.fd(i),
modifier: exported.modifier,
offset: exported.offset,
pitch: exported.pitch,
format,
width: size[0],
height: size[1],
},
from: &plane.buffer,
offset: plane.offset,
bytes_per_row: plane.bytes_per_row,
extent,
}
})
.collect();
match self.copier.fill(&fills, Box::new(Arc::clone(export))) {
Ok(gpu) => {
self.times.add(gpu);
Ok(DeviceWrite::Written)
}
Err(CopyError::Refused(why)) => Ok(DeviceWrite::Declined(why)),
Err(CopyError::Failed(why)) => Err(format!("the GPU's copy of a frame: {why}").into()),
}
}
}
impl Drop for RuntimeFiller {
fn drop(&mut self) {
if self.times.count > 0 {
log::info!(
"hardware video: {NAME}: an encode session's frames copied by the GPU into the \
encoder's input surfaces: {}",
self.times.said()
);
}
}
}
/// One session's copies, and their counts.
+2 -1
View File
@@ -919,7 +919,8 @@ mod encode;
// The arms' side of an encode session, which the VA-API and NVENC arms drive.
#[cfg(target_os = "linux")]
pub(crate) use encode::{
EncodeFrame, EncodeSource, Encoded, HostEncodeSession, HostEncodedFrame, HostEncoder,
EncodeFrame, EncodeSource, Encoded, FrameSource, HostEncodeSession, HostEncodedFrame,
HostEncoder,
};
#[cfg(test)]
@@ -10,10 +10,12 @@
//! result go in. It hands the encoder the frame, and sends it to the session's encode thread
//! (`reims-vgpu.graphics-video-encode`). A refusal faults the command buffer and spends no value
//! of the event.
//! - **The encode thread** finishes each frame in the order the encodes were taken: it reads the
//! source's planes as host bytes, in the surface's pages, or, for a plane in the surface's
//! device cache, in a staging buffer the GPU copies the plane into first. The encode writes the
//! access unit into the bitstream buffer where it fits; the thread writes the frame's
//! - **The encode thread** finishes each frame in the order the encodes were taken: the backend
//! reads the source's planes where they lie, in the surface's pages or its device caches, by a
//! device of its own ([`FrameSource::planes`]), or as host bytes ([`FrameSource::host`]): in the
//! surface's pages, or, for a plane in the surface's device cache, in a staging buffer the GPU
//! copies the plane into first. The encode writes the access unit into the bitstream buffer
//! where it fits; the thread writes the frame's
//! [`RgfxVideoEncodeResult`] after it, and then signals the encode's value. An access unit
//! past the capacity is not written ([`RGFX_VIDEO_ENCODE_OVERFLOW`]), and a frame the encode
//! fails gets [`RGFX_VIDEO_ENCODE_FAILED`]: the command buffer completes as any other.
@@ -69,7 +71,7 @@ pub(crate) struct EncodeFrame {
/// A backend's encoder of one codec, whose session is a [`HostEncodeSession`]. Its calls run on
/// the thread that takes each encode's command buffer, in the order the encodes were taken.
pub(crate) trait HostEncoder: Send + 'static {
pub(crate) trait HostEncoder<P: Platform>: Send + 'static {
/// Checks settings an encode carries, beyond what the session checks of every backend's
/// (their size, format, profile, rate control and entropy): what the hardware takes of them.
/// `Err` faults the encode's command buffer.
@@ -78,23 +80,97 @@ pub(crate) trait HostEncoder: Send + 'static {
/// Takes the next frame, in display order, with the settings it carries applied from it on,
/// and answers its encode, which the session's encode thread finishes, in the order taken.
/// `Err` faults the encode's command buffer.
fn encode(&mut self, frame: EncodeFrame) -> Result<Box<dyn HostEncodedFrame>, BackendError>;
fn encode(&mut self, frame: EncodeFrame) -> Result<Box<dyn HostEncodedFrame<P>>, BackendError>;
}
/// One frame's encode, which the session's encode thread finishes.
pub(crate) trait HostEncodedFrame: Send {
pub(crate) trait HostEncodedFrame<P: Platform>: Send {
/// Encodes the frame from `source`'s planes, and writes its access unit, NAL units in
/// Annex-B form, its keyframe's parameter sets before its slices, at the front of `out`
/// where it fits there; where it does not, writes nothing of it. Answers what came of it;
/// `Err` where the hardware did not encode it, which the session logs.
fn finish(
self: Box<Self>,
source: &EncodeSource,
source: &mut FrameSource<'_, P>,
out: &mut [u8],
) -> Result<Encoded, BackendError>;
}
/// The source of one frame, as host bytes, which [`HostEncodedFrame::finish`] reads.
/// One frame's source as a backend's encode reads it ([`HostEncodedFrame::finish`]): its planes
/// where they lie, or their host bytes. Either way they hold the frame until its value is
/// signalled (the module docs).
pub(crate) struct FrameSource<'a, P: Platform> {
source: &'a Source<P>,
stage: &'a mut Stage<P>,
/// Where the planes in a device cache are staged, once [`Self::host`] staged them.
staged: Option<Staged>,
}
impl<P: Platform> FrameSource<'_, P> {
/// The luma plane and the chroma plane where they lie: in the surface's pages, or in its
/// device caches. Each holds the frame's rows from its first.
pub(crate) fn planes(&self) -> [&OutputPlane<P>; 2] {
[&self.source.luma, &self.source.chroma]
}
/// The frame's width and height, the settings'.
pub(crate) fn size(&self) -> (u32, u32) {
(self.source.width, self.source.height)
}
/// The planes' host bytes: each plane's own in the surface's pages, and, for a plane in a
/// device cache, the session's staging buffer, which the GPU copies the plane into at its own
/// pitch, once.
pub(crate) fn host(&mut self) -> Result<EncodeSource, BackendError> {
let staged = match self.staged {
Some(staged) => staged,
None => {
let staged =
(self.stage).copy_out_of_caches(&self.source.luma, &self.source.chroma)?;
self.staged = Some(staged);
staged
}
};
let stage = &*self.stage;
let plane = |p: &OutputPlane<P>, at: Option<u64>| -> Result<SourcePlane, BackendError> {
let first = match (at, p.host) {
(Some(at), _) => {
let buffer = stage.buffer.as_ref().ok_or("no staging buffer")?;
buffer.contents().wrapping_add(at)
}
(None, Some(host)) => host,
(None, None) => return Err("a source plane with no host bytes".into()),
};
let (Ok(bytes_per_row), Ok(row_bytes), Ok(rows)) = (
usize::try_from(p.bytes_per_row),
usize::try_from(p.row_bytes),
usize::try_from(p.height),
) else {
return Err("a source plane past the host's address space".into());
};
Ok(SourcePlane {
at: first.as_ptr::<u8>().cast_const(),
bytes_per_row,
row_bytes,
rows,
})
};
Ok(EncodeSource {
luma: plane(&self.source.luma, staged.luma)?,
chroma: plane(&self.source.chroma, staged.chroma)?,
width: self.source.width,
height: self.source.height,
})
}
/// Whether a plane was copied out of its device cache for [`Self::host`].
fn staged(&self) -> bool {
self.staged
.is_some_and(|staged| staged.luma.is_some() || staged.chroma.is_some())
}
}
/// The source of one frame, as host bytes ([`FrameSource::host`]).
#[derive(Clone, Copy, Debug)]
pub(crate) struct EncodeSource {
/// The luma plane: `height` rows of `width` samples.
@@ -287,7 +363,7 @@ impl<P: Platform> Out<P> {
/// One encode's work for the encode thread.
struct Job<P: Platform> {
value: u64,
frame: Box<dyn HostEncodedFrame>,
frame: Box<dyn HostEncodedFrame<P>>,
source: Source<P>,
out: Out<P>,
}
@@ -335,7 +411,7 @@ pub(crate) struct HostEncodeSession<P: Platform> {
/// A session's encoder, the encode thread's queue, the last value an encode answered, and the
/// settings in force.
struct State<P: Platform> {
encoder: Box<dyn HostEncoder>,
encoder: Box<dyn HostEncoder<P>>,
jobs: Option<mpsc::SyncSender<Job<P>>>,
value: u64,
settings: Option<RgfxVideoEncodeSettings>,
@@ -353,7 +429,7 @@ impl<P: Platform> HostEncodeSession<P> {
device: &P::Device,
codec: u32,
name: &'static str,
encoder: Box<dyn HostEncoder>,
encoder: Box<dyn HostEncoder<P>>,
) -> Option<Self> {
let Some(event) = device.new_shared_event() else {
log::warn!("hardware video: {name}: no shared event for an encode session");
@@ -563,51 +639,25 @@ fn finish_frames<P: Platform>(
}
}
/// Finishes `frame` from `source` into `out`, copying a source plane out of its device cache
/// first, and answers what came of it and whether a plane was copied so.
/// Finishes `frame` from `source` into `out`, and answers what came of it and whether a plane
/// was copied out of its device cache for its host bytes.
fn finish<P: Platform>(
frame: Box<dyn HostEncodedFrame>,
frame: Box<dyn HostEncodedFrame<P>>,
source: &Source<P>,
out: &Out<P>,
stage: &mut Stage<P>,
) -> Result<(Encoded, bool), BackendError> {
let staged = stage.copy_out_of_caches(&source.luma, &source.chroma)?;
let plane = |p: &OutputPlane<P>, at: Option<u64>| -> Result<SourcePlane, BackendError> {
let first = match (at, p.host) {
(Some(at), _) => {
let buffer = stage.buffer.as_ref().ok_or("no staging buffer")?;
buffer.contents().wrapping_add(at)
}
(None, Some(host)) => host,
(None, None) => return Err("a source plane with no host bytes".into()),
};
let (Ok(bytes_per_row), Ok(row_bytes), Ok(rows)) = (
usize::try_from(p.bytes_per_row),
usize::try_from(p.row_bytes),
usize::try_from(p.height),
) else {
return Err("a source plane past the host's address space".into());
};
Ok(SourcePlane {
at: first.as_ptr::<u8>().cast_const(),
bytes_per_row,
row_bytes,
rows,
})
};
let source = EncodeSource {
luma: plane(&source.luma, staged.luma)?,
chroma: plane(&source.chroma, staged.chroma)?,
width: source.width,
height: source.height,
let mut source = FrameSource {
source,
stage,
staged: None,
};
// SAFETY: the capacity's bytes from `at` lie in the bitstream's Shared buffer's host bytes
// (the op's check), which `out` holds until the signal, and nothing else reads or writes them
// until then: the guest's command buffer waits for the signal, and the result lies apart.
let bytes = unsafe { std::slice::from_raw_parts_mut(out.at.as_ptr::<u8>(), out.capacity) };
let encoded = frame.finish(&source, bytes)?;
let staged = staged.luma.is_some() || staged.chroma.is_some();
Ok((encoded, staged))
let encoded = frame.finish(&mut source, bytes)?;
Ok((encoded, source.staged()))
}
/// The bytes a source plane takes staged out of its device cache: its rows at its pitch.
@@ -83,7 +83,7 @@ struct Encoder {
answers: VecDeque<Answer>,
}
impl HostEncoder for Encoder {
impl HostEncoder<P> for Encoder {
fn check(&self, settings: &RgfxVideoEncodeSettings) -> Result<(), BackendError> {
if settings.width > 4096 {
return Err("past the test's largest".into());
@@ -91,7 +91,7 @@ impl HostEncoder for Encoder {
Ok(())
}
fn encode(&mut self, frame: EncodeFrame) -> Result<Box<dyn HostEncodedFrame>, BackendError> {
fn encode(&mut self, frame: EncodeFrame) -> Result<Box<dyn HostEncodedFrame<P>>, BackendError> {
self.log.lock().push(Seen::Took(
frame.frame_index,
frame.settings.is_some(),
@@ -112,12 +112,13 @@ struct Frame {
answer: Answer,
}
impl HostEncodedFrame for Frame {
impl HostEncodedFrame<P> for Frame {
fn finish(
self: Box<Self>,
source: &EncodeSource,
source: &mut FrameSource<'_, P>,
out: &mut [u8],
) -> Result<Encoded, BackendError> {
let source = source.host()?;
// SAFETY: each plane's first row lies in the source's host bytes.
let (luma, chroma) = unsafe { (*source.luma.at, *source.chroma.at) };
(self.log.lock()).push(Seen::Finished(self.index, luma, chroma, out.len()));