🆕 Write encode sessions' frames into VA inputs on the rt GPU
On Linux the rt platform's VA-API arm made no GPU filler, so an encode
session's frames could only be uploaded by the CPU, and the arm answered no
encoder (f716a52d2a: "rt releases no encoder's sources to the driver yet").
The arm's GPU copies on rt (`fill::DeviceFills`) now give each encode session
a filler. Its input is a dma-buf block of the device's, made when no input of
the shape is free and imported on the encoder's display; a frame's two planes
are read where they lie, in the surface's pages or its device caches, and
written into it by videoEncodeFill, margin included, so the encoder codes the
bytes the upload would have given it. A blit hands the block to the driver
(`release_to_external`) behind the kernel, and the frame is coded once the
GPU's write is waited for; no B pictures are coded, so the driver has read the
input before the next frame's write. An input the driver still holds is not
written; a plane in its cache's surface, or one the input cannot hold, is
declined and that frame uploaded, said once a session. A write that fails on
the GPU keeps its filler and input for the session's life, and the session's
later frames are uploaded. Decodes are unchanged: the copies make no copier,
for the same reason as before.
The session's end logs how many frames went each way. The arm still answers no
encoder here; the next commit turns them on.
New tests: the input's planes and the kernel's arguments on the testkit; the
kernel on the rt device writes frames of NV12 and P010, with and without
margins, at odd offsets and pitches, as the upload writes them, and nothing
past the coded rows; on the VA-API host, frames written by the GPU code byte
for byte as the uploaded ones, an x86 guest's session's and an arm64 guest's
paravirtual encoder's.
This commit is contained in:
1 parent
6340e2d4dc
commit
13fb154934
7 files changed
+1410
-142
No files matched your search
@@ -63,9 +63,9 @@
|
||||
//! run declines.
|
||||
//! 2. **By the device's GPU** ([`GpuCopies`]): each plane copied into the plane's buffer, the
|
||||
//! guest's pages or the surface's device cache, at its own rows and offset, the crop alone as
|
||||
//! the CPU's copy writes it, where the open made a copier. On Linux the open
|
||||
//! makes none; on Windows the rt platform's copier declines each picture, counted, so that
|
||||
//! each lands by the CPU (`rt_windows`).
|
||||
//! the CPU's copy writes it, where the open made a copier. On Linux the rt platform's
|
||||
//! copies make none, only encode sessions' fillers (`fill`); on Windows the rt platform's
|
||||
//! copier declines each picture, counted, so that each lands by the CPU (`rt_windows`).
|
||||
//! 3. **By the CPU**: the frame read back (staged, or `vaGetImage`, the VA crate's way back),
|
||||
//! and copied into the planes' host bytes, or into the session's staging for a plane in a
|
||||
//! device cache.
|
||||
@@ -77,10 +77,10 @@
|
||||
//! (`Frame::write_to_guest`, the first way above) where the import check takes the surface's
|
||||
//! layout and memory, else read back and copied by the CPU into the surface's pages.
|
||||
//! - **VideoToolbox's paravirtual encoders** (`encode::VaGuestEncoder`, `super::vt`): an arm64
|
||||
//! guest's encoder reads each source frame from the IOSurface its kext lent: copied by the
|
||||
//! runtime device's GPU from a buffer over its pages into an input surface of the encoder's,
|
||||
//! as an x86 guest's frames are (`encode`'s module doc), else through the host's view of its
|
||||
//! pages, which the VA crate's encoder uploads.
|
||||
//! guest's encoder reads each source frame from the IOSurface its kext lent: written by the
|
||||
//! runtime device's GPU from a buffer over its pages into an input of the encoder's, as an x86
|
||||
//! guest's frames are (`encode`'s module doc), else through the host's view of its pages, which
|
||||
//! the VA crate's encoder uploads.
|
||||
//! - **The layout** ([`layout`]) is granularity [2, 2], so that each plane holds the crop's
|
||||
//! even rows and columns, and the alignment the import check found for the codec's formats;
|
||||
//! all zero where it found none.
|
||||
@@ -110,11 +110,11 @@ 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, InputSurface, PlaneRows, Profile,
|
||||
TargetCodec, TargetFor, encoder_support,
|
||||
H264_MAX_MACROBLOCKS, H264Decoder, HevcDecoder, ImportWrites, PlaneRows, Profile, Target,
|
||||
TargetCodec, TargetFor, VideoEncoder, encoder_support,
|
||||
};
|
||||
#[cfg(unix)]
|
||||
use reims_vgpu_video::vaapi::{TARGET_ALIGNMENT, Target, TargetChecks, TargetPlane, TargetShape};
|
||||
use reims_vgpu_video::vaapi::{TARGET_ALIGNMENT, TargetChecks, TargetPlane, TargetShape};
|
||||
#[cfg(unix)]
|
||||
use reims_vgpu_vulkan::core::num::ToU64 as _;
|
||||
use reims_vgpu_vulkan::core::num::ToUsize as _;
|
||||
@@ -139,6 +139,8 @@ use super::video_host::{
|
||||
};
|
||||
|
||||
mod encode;
|
||||
#[cfg(unix)]
|
||||
mod fill;
|
||||
#[cfg(windows)]
|
||||
mod rt_windows;
|
||||
|
||||
@@ -224,9 +226,10 @@ impl std::fmt::Display for DisplayAt<'_> {
|
||||
|
||||
/// The VA-API video of the rt platform's `device`, on its GPU's render node
|
||||
/// (`host_gpus::render_node_at`), as [`open`] opens it; `None`, logged, where its GPU has none.
|
||||
/// Its pictures land by the driver's video processing or the CPU's copy, as no GPU copier is
|
||||
/// given; a reference picture is not decoded into its cache ([`CachedReferences::Apart`]), and no
|
||||
/// encoder is answered: the platform does not yet release an encoder's sources to the driver.
|
||||
/// Its pictures land by the driver's video processing or the CPU's copy, as its GPU copies
|
||||
/// ([`fill::DeviceFills`]) make no copier; a reference picture is not decoded into its cache
|
||||
/// ([`CachedReferences::Apart`]); and no encoder is answered yet, though the GPU copies give an
|
||||
/// encode session a filler (`fill`).
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn open_on_rt(
|
||||
device: &RtDevice,
|
||||
@@ -243,12 +246,14 @@ pub(crate) fn open_on_rt(
|
||||
references: CachedReferences::Apart,
|
||||
encodes: false,
|
||||
};
|
||||
let copies: Arc<dyn GpuCopies<reims_vgpu_vulkan::RtPlatform>> =
|
||||
Arc::new(fill::DeviceFills::new(device, &runtime));
|
||||
open::<reims_vgpu_vulkan::RtPlatform>(
|
||||
device,
|
||||
device.facts().registry_id,
|
||||
DisplayAt::Node(&node),
|
||||
runtime,
|
||||
None,
|
||||
Some(copies),
|
||||
checks,
|
||||
rules,
|
||||
)
|
||||
@@ -258,7 +263,8 @@ pub(crate) fn open_on_rt(
|
||||
/// the LUID Vulkan answers for it (`rt_platform::HostGpu`), over Mesa's VA-on-D3D12 driver, as
|
||||
/// [`open`] opens it; `None`, logged, where its GPU names none. Its pictures land by the CPU's
|
||||
/// copy, at the GPU's copy's refusal of each, counted (`rt_windows`); a reference picture is not
|
||||
/// decoded into its cache ([`CachedReferences::Apart`]), and no encoder is answered, as on Linux.
|
||||
/// decoded into its cache ([`CachedReferences::Apart`]), and no encoder is answered: rt imports
|
||||
/// no shared Direct3D 12 texture, which an encoder's input would be written through.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn open_on_rt(
|
||||
device: &RtDevice,
|
||||
@@ -1561,21 +1567,29 @@ pub(crate) trait GpuCopies<P: Platform>: Send + Sync {
|
||||
}
|
||||
}
|
||||
|
||||
/// One encode session's GPU copies of its frames into its encoder's input surfaces.
|
||||
/// One encode session's GPU writes of its frames into its encoder's inputs.
|
||||
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.
|
||||
/// Writes the frame `encoder` codes, of its settings' size and its input's samples, from
|
||||
/// `luma` and `chroma` where they lie, into an input of `encoder`'s shape, the margin past the
|
||||
/// frame filled as the VA crate's upload fills it, and returns once the GPU wrote it;
|
||||
/// [`Filled::Declined`] with why, nothing written, where it cannot. `Err` where the write
|
||||
/// failed once on the GPU, which may write the input still.
|
||||
fn fill(
|
||||
&mut self,
|
||||
surface: &InputSurface,
|
||||
encoder: &VideoEncoder,
|
||||
luma: &OutputPlane<P>,
|
||||
chroma: &OutputPlane<P>,
|
||||
size: (u32, u32),
|
||||
sample: u32,
|
||||
) -> Result<DeviceWrite, BackendError>;
|
||||
) -> Result<Filled, BackendError>;
|
||||
}
|
||||
|
||||
/// What came of an encode session's fill of a frame ([`GpuFiller::fill`]). On Windows no filler
|
||||
/// makes one: rt imports no shared Direct3D 12 texture there (`rt_windows`).
|
||||
#[cfg_attr(windows, allow(dead_code))]
|
||||
pub(crate) enum Filled {
|
||||
/// The frame lies in this input of the encoder's, written and waited for.
|
||||
Written(Target),
|
||||
/// Nothing was written, for the reason given: the frame is uploaded.
|
||||
Declined(String),
|
||||
}
|
||||
|
||||
/// One session's GPU copies of its pictures into their outputs.
|
||||
|
||||
@@ -15,23 +15,25 @@
|
||||
//! 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`]) reaches the encoder on the session's encode thread one of two
|
||||
//! ways. By the device's GPU, where the session's copier gives a filler (`super::GpuCopies`;
|
||||
//! the rt platform's gives none, so a frame reaches the encoder the other way): 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.
|
||||
//! ways. By the device's GPU, where the session's copies give a filler (`super::GpuCopies`; on
|
||||
//! Linux the rt platform's, `super::fill`, and on Windows none, as rt imports no shared
|
||||
//! Direct3D 12 texture): the source's planes, read where they lie, in the surface's pages or its
|
||||
//! device caches, written into an input of the encoder's, a buffer of the device's that the
|
||||
//! encoder's display imports (the VA crate's `VideoEncoder::import_input`), its margin to the
|
||||
//! coded size filled as an upload fills it, so the encoder codes the same bytes either way
|
||||
//! (`VideoEncoder::encode_target`). Else, and where the write is declined (said once a
|
||||
//! session, with why, at info), from the source's host bytes, which the VA crate's encoder
|
||||
//! uploads. The session logs at its end how many frames went each way. 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.
|
||||
//! - **VideoToolbox's paravirtual encoders** (`VaGuestEncoder`, `super::super::vt`): an arm64
|
||||
//! guest's encoders, one for each codec the driver encodes a profile of ([`guest_encoders`]),
|
||||
//! whose settings the guest's session properties make, `Quality` onto the quality levels as
|
||||
//! `quality` maps. Each source frame reaches the encoder as an x86 guest's frame does: copied by
|
||||
//! the runtime device's GPU from a Shared buffer over the IOSurface's pages, which the guest
|
||||
//! lent, into an input surface of the encoder's; else, and where the copy is declined (said
|
||||
//! once a session), from the host's view of the pages, which the VA crate's encoder uploads.
|
||||
//! `quality` maps. Each source frame reaches the encoder as an x86 guest's frame does: written
|
||||
//! by the runtime device's GPU from a Shared buffer over the IOSurface's pages, which the guest
|
||||
//! lent, into an input of the encoder's; else, and where the write is declined (said once a
|
||||
//! session), from the host's view of the pages, which the VA crate's encoder uploads.
|
||||
//! A change of the bitrate, frame rate or key-frame interval goes to the encoder from the next
|
||||
//! frame; one that makes a new sequence, or changes the rate control's mode, makes a new
|
||||
//! encoder before the first frame, and after it is answered as taken and left out, the running
|
||||
@@ -56,22 +58,21 @@ use reims_vgpu_video::codec::encode::{
|
||||
InputFrame, Plane, Profile as EncodeProfile, RateControl,
|
||||
};
|
||||
use reims_vgpu_video::core::backend::BackendError as VideoError;
|
||||
use reims_vgpu_video::core::backend::DeviceWrite;
|
||||
use reims_vgpu_video::core::surfaces::PlaneLayout;
|
||||
use reims_vgpu_video::paravirt::{Encoder, EncoderConfig, SourceFrame};
|
||||
use reims_vgpu_video::vaapi::{Capabilities, Display, EncoderSupport, InputSurface, VideoEncoder};
|
||||
use reims_vgpu_video::vaapi::{Capabilities, Display, EncoderSupport, Target, VideoEncoder};
|
||||
use reims_vgpu_vulkan::core::platform::Platform;
|
||||
use reims_vgpu_vulkan::core::sync::Mutex;
|
||||
|
||||
use super::super::decode::{GuestEncoder, GuestSource, rate_past_first_frame, same_rate_mode};
|
||||
use super::super::video_host::{
|
||||
BackendError, EncodeFrame, EncodeSource, Encoded, FrameSource, HostEncodedFrame, HostEncoder,
|
||||
SourcePlane,
|
||||
OutputPlane, SourcePlane,
|
||||
};
|
||||
use super::super::vt_encode::{
|
||||
buffer_planes, encoders_of, host_planes, quality_percent, source_planes,
|
||||
};
|
||||
use super::{GpuFiller, H264_TOP_LEVEL, HEVC_TOP_LEVEL, MIN_SIZE, NAME};
|
||||
use super::{Filled, 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`.
|
||||
@@ -349,17 +350,31 @@ 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.
|
||||
/// A session's GPU filler, its frames' to share, or why it has none; the reasons a frame was
|
||||
/// uploaded instead, each said once; and how many frames went each way, which the session logs
|
||||
/// at its end.
|
||||
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>,
|
||||
/// Fillers whose write failed on the GPU, which may write their inputs still: kept, and their
|
||||
/// inputs with them, while the session lives.
|
||||
failed: Vec<Box<dyn GpuFiller<P>>>,
|
||||
filled: u64,
|
||||
uploaded: u64,
|
||||
}
|
||||
|
||||
impl<P: Platform> Fills<P> {
|
||||
/// A session's fills by `filler` where it is given (or why not).
|
||||
fn new(filler: Result<Box<dyn GpuFiller<P>>, String>) -> Self {
|
||||
Self {
|
||||
filler,
|
||||
said: Vec::new(),
|
||||
failed: Vec::new(),
|
||||
filled: 0,
|
||||
uploaded: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
@@ -368,12 +383,62 @@ impl<P: Platform> Fills<P> {
|
||||
self.said.push(why);
|
||||
}
|
||||
}
|
||||
|
||||
/// The input of `encoder`'s that the session's filler wrote the frame into from `luma` and
|
||||
/// `chroma` where they lie (module doc); `None` where the write was declined, nothing
|
||||
/// written, which is said once a session. `Err` where it failed once on the GPU: the
|
||||
/// filler is kept, and the session's frames are uploaded from here on.
|
||||
fn fill(
|
||||
&mut self,
|
||||
encoder: &VideoEncoder,
|
||||
luma: &OutputPlane<P>,
|
||||
chroma: &OutputPlane<P>,
|
||||
) -> Result<Option<Target>, BackendError> {
|
||||
let filled = match &mut self.filler {
|
||||
Ok(filler) => filler.fill(encoder, luma, chroma),
|
||||
Err(why) => {
|
||||
let why = why.clone();
|
||||
self.uploaded_because(why);
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
match filled {
|
||||
Ok(Filled::Written(target)) => {
|
||||
self.filled += 1;
|
||||
Ok(Some(target))
|
||||
}
|
||||
Ok(Filled::Declined(why)) => {
|
||||
self.uploaded_because(format!("the GPU's copy: {why}"));
|
||||
Ok(None)
|
||||
}
|
||||
Err(error) => {
|
||||
let why = format!("the GPU's copy failed: {error}");
|
||||
if let Ok(filler) = std::mem::replace(&mut self.filler, Err(why)) {
|
||||
self.failed.push(filler);
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> Drop for Fills<P> {
|
||||
fn drop(&mut self) {
|
||||
if self.filled + self.uploaded > 0 {
|
||||
log::info!(
|
||||
"hardware video: {NAME}: an encode session's frames: {} written by the GPU, {} \
|
||||
uploaded by the CPU",
|
||||
self.filled,
|
||||
self.uploaded
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's encoder on VA-API ([`HostEncoder`]).
|
||||
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).
|
||||
/// What writes its frames into the encoder's inputs on the GPU (module doc).
|
||||
fills: Arc<Mutex<Fills<P>>>,
|
||||
/// The profiles the driver encodes, which [`HostEncoder::check`] holds settings to.
|
||||
supports: Arc<[EncoderSupport]>,
|
||||
@@ -386,7 +451,7 @@ pub(super) struct VaEncoder<P: Platform> {
|
||||
|
||||
impl<P: Platform> VaEncoder<P> {
|
||||
/// An encoder of `codec` on `display`, which encodes `supports`, as its entry `entry` and
|
||||
/// `encode` list them, its frames written into its input surfaces by `filler` where it is
|
||||
/// `encode` list them, its frames written into its inputs by `filler` where it is
|
||||
/// given (or why not).
|
||||
pub(super) fn new(
|
||||
display: &Display,
|
||||
@@ -410,11 +475,7 @@ impl<P: Platform> VaEncoder<P> {
|
||||
settings: None,
|
||||
key_next: false,
|
||||
})),
|
||||
fills: Arc::new(Mutex::new(Fills {
|
||||
filler,
|
||||
said: Vec::new(),
|
||||
failed: Vec::new(),
|
||||
})),
|
||||
fills: Arc::new(Mutex::new(Fills::new(filler))),
|
||||
supports,
|
||||
min_size: entry.min_size,
|
||||
max_size: entry.max_size,
|
||||
@@ -494,15 +555,16 @@ impl<P: Platform> HostEncodedFrame<P> for VaFrame<P> {
|
||||
if let Some(encoded) = self.filled(&mut state, &input, source, out)? {
|
||||
return Ok(encoded);
|
||||
}
|
||||
self.fills.lock().uploaded += 1;
|
||||
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
|
||||
/// The frame encoded from `source`'s planes where they lie, written by the GPU into an input
|
||||
/// of the encoder's (module doc), into `out`; `None` where the write was declined, nothing
|
||||
/// written, which is said once a session. `Err` where the encode failed, or the write
|
||||
/// failed once on the GPU.
|
||||
fn filled(
|
||||
&self,
|
||||
@@ -511,44 +573,13 @@ impl<P: Platform> VaFrame<P> {
|
||||
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(),
|
||||
let encoder = state.encoder.as_mut().ok_or("an encode with no settings")?;
|
||||
let [luma, chroma] = source.planes();
|
||||
let Some(target) = self.fills.lock().fill(encoder, luma, chroma)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
fills.uploaded_because(declined);
|
||||
Ok(None)
|
||||
let coded = encoder.encode_target(&target, input)?;
|
||||
finish_coded(state, coded, out).map(Some)
|
||||
}
|
||||
|
||||
/// [`HostEncodedFrame::finish`] from `source`'s host bytes, which the encoder uploads.
|
||||
@@ -727,13 +758,13 @@ pub(super) struct VaGuestEncoder<P: Platform> {
|
||||
/// Whether a frame was encoded: until then, settings that make a new sequence make a new
|
||||
/// encoder.
|
||||
encoded: bool,
|
||||
/// What writes its source frames into the encoder's input surfaces on the GPU (module doc).
|
||||
/// What writes its source frames into the encoder's inputs on the GPU (module doc).
|
||||
fills: Fills<P>,
|
||||
}
|
||||
|
||||
impl<P: Platform> VaGuestEncoder<P> {
|
||||
/// An encoder of `config` on `display`, whose driver encodes `supports`, its frames written
|
||||
/// into its input surfaces by `filler` where it is given (or why not).
|
||||
/// into its inputs by `filler` where it is given (or why not).
|
||||
pub(super) fn new(
|
||||
display: &Display,
|
||||
supports: &[EncoderSupport],
|
||||
@@ -755,59 +786,31 @@ impl<P: Platform> VaGuestEncoder<P> {
|
||||
encoder,
|
||||
settings,
|
||||
encoded: false,
|
||||
fills: Fills {
|
||||
filler,
|
||||
said: Vec::new(),
|
||||
failed: Vec::new(),
|
||||
},
|
||||
fills: Fills::new(filler),
|
||||
})
|
||||
}
|
||||
|
||||
/// The frame of `times` encoded from `planes`, the source surface's luma and chroma in
|
||||
/// `buffer`, over its pages, copied by the GPU into an input surface of the encoder's
|
||||
/// (module doc); `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.
|
||||
/// `buffer`, over its pages, written by the GPU into an input of the encoder's (module doc);
|
||||
/// `None` where the write was declined, nothing written, which is said once a session. `Err`
|
||||
/// where the encode failed, or the write failed once on the GPU.
|
||||
fn filled(
|
||||
&mut self,
|
||||
buffer: &P::Buffer,
|
||||
planes: &[PlaneLayout; 2],
|
||||
times: &InputFrame<'_>,
|
||||
) -> Result<Option<Vec<Coded<reims_vgpu_video::vaapi::Error>>>, VideoError> {
|
||||
let declined = match &mut self.fills.filler {
|
||||
Ok(filler) => match self.encoder.input_surface() {
|
||||
Ok(surface) => {
|
||||
let (width, height) = (self.settings.width, self.settings.height);
|
||||
let sample = self.settings.input_format().bytes_per_sample();
|
||||
let sample = u32::try_from(sample).unwrap_or(0);
|
||||
let [luma, chroma] = buffer_planes(buffer, planes, (width, height), sample);
|
||||
match filler.fill(&surface, &luma, &chroma, (width, height), sample) {
|
||||
Ok(DeviceWrite::Written) => {
|
||||
let coded = (self.encoder.encode_surface(surface, times))
|
||||
.map_err(super::video_error)?;
|
||||
return Ok(Some(coded));
|
||||
}
|
||||
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) => {
|
||||
self.fills.failed.push(surface);
|
||||
self.fills.filler = Err(format!("the GPU's copy failed: {error}"));
|
||||
return Err(VideoError::Malfunction(error.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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}");
|
||||
self.fills.filler = Err(why.clone());
|
||||
why
|
||||
}
|
||||
},
|
||||
Err(why) => why.clone(),
|
||||
let (width, height) = (self.settings.width, self.settings.height);
|
||||
let sample = self.settings.input_format().bytes_per_sample();
|
||||
let sample = u32::try_from(sample).unwrap_or(0);
|
||||
let [luma, chroma] = buffer_planes(buffer, planes, (width, height), sample);
|
||||
let filled = self.fills.fill(&self.encoder, &luma, &chroma);
|
||||
let Some(target) = filled.map_err(|error| VideoError::Malfunction(error.to_string()))?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.fills.uploaded_because(declined);
|
||||
Ok(None)
|
||||
let coded = (self.encoder.encode_target(&target, times)).map_err(super::video_error)?;
|
||||
Ok(Some(coded))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -875,6 +878,7 @@ impl<P: Platform> GuestEncoder<P> for VaGuestEncoder<P> {
|
||||
self.encoded = true;
|
||||
return Ok(guest_coded(coded));
|
||||
}
|
||||
self.fills.uploaded += 1;
|
||||
let view = (source.memory.host_view())
|
||||
.map_err(|error| VideoError::Malfunction(error.to_string()))?;
|
||||
let [y, uv] = host_planes(&view, &[luma, chroma])?;
|
||||
|
||||
@@ -10,6 +10,7 @@ use reims_vgpu_video::vaapi::{H264Decoder, HevcDecoder, encoder_support};
|
||||
use reims_vgpu_vulkan::RtPlatform;
|
||||
|
||||
use super::*;
|
||||
use crate::graphics::video_choice::tested_gpu::Arm;
|
||||
|
||||
/// Settings of a 320x192 stream of `profile` of `codec` at a constant QP.
|
||||
fn settings(codec: u32, profile: u32) -> RgfxVideoEncodeSettings {
|
||||
@@ -494,6 +495,189 @@ fn each_profile_encodes_on_the_driver_and_decodes_back() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame the runtime device's GPU writes into an input of the encoder's (`fill`'s filler)
|
||||
/// encodes as the same frame uploaded by the CPU, byte for byte: on the driver of the rt device's
|
||||
/// GPU, which the arm runs on (`video_choice::tested_gpu::check_rt`), 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 buffer of the device's, 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 inputs; every access unit of the second
|
||||
/// is the first's.
|
||||
#[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::Handle as _;
|
||||
use reims_vgpu_vulkan::core::platform::HostRange;
|
||||
use reims_vgpu_vulkan::core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_vulkan::core::platform::resource::Buffer as _;
|
||||
use reims_vgpu_vulkan::core::raise::OnFault;
|
||||
|
||||
use super::super::super::video_host::OutputPlane;
|
||||
use super::super::{GpuCopies as _, fill};
|
||||
|
||||
let platform = crate::rt_test_end::platform();
|
||||
crate::entry::run(|_| {
|
||||
let device = platform.system_default_device().expect("an rt device");
|
||||
crate::graphics::video_choice::tested_gpu::check_rt(&device, Arm::VaApi);
|
||||
let gpu = device.host_gpu();
|
||||
let node = reims_vgpu_vulkan::host_gpus::render_node_at(gpu.render, gpu.pci);
|
||||
let runtime = crate::video::runtime::PlatformRuntime::of(&platform);
|
||||
let display = Display::open(node.expect("a render node"), Arc::clone(&runtime))
|
||||
.expect("a VA display on the device's GPU");
|
||||
let copies = fill::DeviceFills::<RtPlatform>::new(&device, &runtime);
|
||||
let mut filler = copies.filler().expect("a filler");
|
||||
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 = platform.vm();
|
||||
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");
|
||||
let keep = Arc::clone(&platform);
|
||||
// SAFETY: the pages stay mapped until the platform's release of the
|
||||
// buffer runs the deallocator.
|
||||
let bytes = unsafe { HostRange::new(at, len) };
|
||||
let unmap: Box<dyn FnOnce() + Send> = Box::new(move || {
|
||||
let _ = keep.vm().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: false,
|
||||
host: Some(at.wrapping_add(offset)),
|
||||
pages: None,
|
||||
cache: None,
|
||||
surface: 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 written = (filler.fill(&by_gpu, &luma_plane, &chroma_plane))
|
||||
.expect("the GPU's write");
|
||||
let target = match written {
|
||||
Filled::Written(target) => target,
|
||||
Filled::Declined(why) => panic!("{what}: declined: {why}"),
|
||||
};
|
||||
let filled = by_gpu.encode_target(&target, &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((target, 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
|
||||
}
|
||||
}
|
||||
|
||||
/// A guest surface's memory in host bytes, which a [`HostView`] reaches.
|
||||
struct HostSurface {
|
||||
life: MemoryLife,
|
||||
@@ -680,6 +864,121 @@ fn a_guest_encoder_encodes_the_frames_of_the_surfaces_it_is_lent() {
|
||||
}
|
||||
}
|
||||
|
||||
/// On the driver of the rt device's GPU, which the arm runs on
|
||||
/// (`video_choice::tested_gpu::check_rt`), each guest encoder it answers, at each 8-bit profile
|
||||
/// it encodes, at a constant QP: 6 frames of a 64x48 stream read from guest surfaces wider and
|
||||
/// taller than it, written by the GPU (`fill`'s filler) from a buffer of the device's that holds
|
||||
/// the surface's bytes, code as the same frames read by the CPU from the surface's host bytes,
|
||||
/// sample for sample and byte for byte; and each of the six went by the GPU.
|
||||
#[test]
|
||||
#[ignore = "needs a VA-API GPU: run on the VA-API host"]
|
||||
fn a_guest_encoders_frames_filled_by_the_gpu_code_as_read_by_the_cpu() {
|
||||
use reims_vgpu_vulkan::core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_vulkan::core::platform::resource::Buffer as _;
|
||||
use reims_vgpu_vulkan::core::raise::OnFault;
|
||||
|
||||
use super::super::{GpuCopies as _, fill};
|
||||
|
||||
let platform = crate::rt_test_end::platform();
|
||||
crate::entry::run(|_| {
|
||||
let device = platform.system_default_device().expect("an rt device");
|
||||
crate::graphics::video_choice::tested_gpu::check_rt(&device, Arm::VaApi);
|
||||
let gpu = device.host_gpu();
|
||||
let node = reims_vgpu_vulkan::host_gpus::render_node_at(gpu.render, gpu.pci);
|
||||
let runtime = crate::video::runtime::PlatformRuntime::of(&platform);
|
||||
let display = Display::open(node.expect("a render node"), Arc::clone(&runtime))
|
||||
.expect("a VA display on the device's GPU");
|
||||
let copies = fill::DeviceFills::<RtPlatform>::new(&device, &runtime);
|
||||
let supports: Arc<[EncoderSupport]> = encoder_support(&display).into();
|
||||
let encoders = guest_encoders(&supports);
|
||||
assert!(
|
||||
!encoders.is_empty(),
|
||||
"the driver encodes neither H.264 nor HEVC"
|
||||
);
|
||||
let mut frames = 0;
|
||||
for encoder in &encoders {
|
||||
for &profile in &encoder.profiles {
|
||||
if profile.bit_depth() != 8 {
|
||||
continue;
|
||||
}
|
||||
let mut settings = EncoderSettings::new(profile, 64, 48);
|
||||
settings.timescale = 90_000;
|
||||
settings.rate_control = RateControl::ConstantQp {
|
||||
intra: 26,
|
||||
predicted: 28,
|
||||
bidirectional: 30,
|
||||
};
|
||||
let config = EncoderConfig {
|
||||
settings,
|
||||
quality: Some(0.5),
|
||||
};
|
||||
let open = |filler| {
|
||||
VaGuestEncoder::<RtPlatform>::new(&display, &supports, &config, filler)
|
||||
.expect("a guest encoder")
|
||||
};
|
||||
let mut by_cpu = open(Err("read by the CPU in this test".to_owned()));
|
||||
let mut by_gpu = open(copies.filler());
|
||||
let (mut read, mut filled) = (Vec::new(), Vec::new());
|
||||
for index in 0..6 {
|
||||
let (layout, memory) = guest_surface(index);
|
||||
let length = memory.bytes.len() as u64;
|
||||
let buffer = (device.new_buffer_of_length(OnFault::Return, length, 0))
|
||||
.expect("no raise")
|
||||
.expect("a buffer");
|
||||
// SAFETY: the buffer's `length` host bytes, which no GPU work reaches yet.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(
|
||||
memory.bytes.as_ptr(),
|
||||
buffer.contents().as_ptr::<u8>(),
|
||||
memory.bytes.len(),
|
||||
);
|
||||
}
|
||||
let frame = SourceFrame {
|
||||
id: index as u64,
|
||||
pts: index as i64 * 3000,
|
||||
duration: 3000,
|
||||
force_key_frame: false,
|
||||
};
|
||||
let from_host = GuestSource::<RtPlatform> {
|
||||
layout: layout.clone(),
|
||||
memory: &memory,
|
||||
buffer: None,
|
||||
};
|
||||
let from_buffer = GuestSource {
|
||||
layout,
|
||||
memory: &memory,
|
||||
buffer: Some(&buffer),
|
||||
};
|
||||
read.extend(by_cpu.encode(&from_host, &frame).unwrap());
|
||||
filled.extend(by_gpu.encode(&from_buffer, &frame).unwrap());
|
||||
frames += 1;
|
||||
}
|
||||
read.extend(by_cpu.flush().unwrap());
|
||||
filled.extend(by_gpu.flush().unwrap());
|
||||
assert!(
|
||||
by_gpu.fills.said.is_empty(),
|
||||
"{profile:?}: frames uploaded by the CPU: {:?}",
|
||||
by_gpu.fills.said
|
||||
);
|
||||
assert_eq!(
|
||||
(by_gpu.fills.filled, by_gpu.fills.uploaded),
|
||||
(6, 0),
|
||||
"{profile:?}"
|
||||
);
|
||||
let data = |coded: Vec<Coded<VideoError>>| -> Vec<Vec<u8>> {
|
||||
let samples = coded.into_iter().map(|c| c.expect("a sample").data);
|
||||
samples.collect()
|
||||
};
|
||||
let (a, b) = (data(read), data(filled));
|
||||
assert_eq!(a.len(), 6, "{profile:?}: samples");
|
||||
assert!(a == b, "{profile:?}: a filled frame's sample differs");
|
||||
}
|
||||
}
|
||||
eprintln!("{frames} guest frames filled by the GPU coded as read by the CPU");
|
||||
assert!(frames > 0);
|
||||
});
|
||||
}
|
||||
|
||||
/// A driver's answer for `profile` up to `max_width` by `max_height`, with no attribute but its
|
||||
/// quality range.
|
||||
fn support(profile: EncodeProfile, max_width: u32, max_height: u32) -> EncoderSupport {
|
||||
|
||||
@@ -0,0 +1,628 @@
|
||||
//! An encode session's frames written by the runtime device's GPU into inputs of the VA crate's
|
||||
//! encoder, on Linux ([`DeviceFills`], the arm's [`GpuCopies`]): each input is a buffer of the
|
||||
//! device's whose memory the encoder's display imports, and the encoder codes the frame from it
|
||||
//! (`VideoEncoder::encode_target`), as NVENC's filler writes NVENC's input
|
||||
//! (`nvidia::encode::fill`).
|
||||
//!
|
||||
//! - **The input** is a buffer in a dma-buf block of its own
|
||||
//! (`new_dma_buf_buffer_of_length_padding_unobserved`), made on a session's first frame, its
|
||||
//! memory exported once and imported on the encoder's display as a linear surface of the
|
||||
//! encoder's input shape, its format and coded size (`VideoEncoder::import_input`): the luma
|
||||
//! plane's coded rows from its first byte, then the chroma plane's, half as many, at one pitch,
|
||||
//! the coded row's bytes rounded up to [`TARGET_ALIGNMENT`], as the arm's imports of device
|
||||
//! caches lie (the VA crate's `target`). The import holds the buffer. The session keeps its
|
||||
//! input while the encoder's shape stays and the encoder no longer holds it, and makes another
|
||||
//! otherwise: an encoder made for a new sequence of another shape, or a stalled picture's,
|
||||
//! which the encoder keeps while the GPU may read it.
|
||||
//! - **A frame** is written by the platform library's `videoEncodeFill` kernel (`shaders.metal`),
|
||||
//! on a queue of the filler's own: one dispatch a plane, a thread a 32-bit word of the input.
|
||||
//! Each word holds the source's bytes, read where they lie, in the surface's pages or its device
|
||||
//! caches, by 32-bit loads, the source bound from its plane's first byte rounded down to 256. The
|
||||
//! kernel reads the rows the VA crate's upload reads: `height` luma rows and `height / 2`
|
||||
//! chroma rows, `width` samples' bytes of each. It fills the margin to the coded size as the
|
||||
//! upload fills it: each row past the frame's repeats its last, and each byte past a row's bytes
|
||||
//! repeats the row's last sample, or Cb/Cr pair. So the encoder codes the same bytes either way.
|
||||
//! A blit then hands the input to the driver (`BlitEncoder::release_to_external`, rt's release
|
||||
//! of its block), and the fill is waited for before the encoder reads the input. The driver never
|
||||
//! writes the input, and nothing reads it through the device, so the next frame's fill writes it
|
||||
//! anew with no acquire, as rt's release lets it (`rt_platform::export`, "The release").
|
||||
//! - **Refusals** ([`Filled::Declined`]) come before anything is submitted, and the frame is
|
||||
//! uploaded instead. The device or the driver may refuse to make an input, or the device the
|
||||
//! kernel's pipeline; neither is tried again in the session. A plane in its cache's surface,
|
||||
//! which no encode's source plane is, is declined too. A fill that failed once
|
||||
//! submitted is an error: its input is kept out of use while the session lives, as the GPU may
|
||||
//! write it still.
|
||||
//!
|
||||
//! Each session logs at its end how many frames went this way, and the fills' times.
|
||||
|
||||
use std::os::fd::AsFd as _;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use reims_vgpu_video::core::runtime::Runtime;
|
||||
use reims_vgpu_video::vaapi::{TARGET_ALIGNMENT, Target, TargetPlane, TargetShape, VideoEncoder};
|
||||
use reims_vgpu_vulkan::core::platform::Handle as _;
|
||||
use reims_vgpu_vulkan::core::platform::Platform;
|
||||
use reims_vgpu_vulkan::core::platform::blit::{BlitCmd, BlitEncoder as _};
|
||||
use reims_vgpu_vulkan::core::platform::command::{CommandBuffer as _, CommandQueue as _};
|
||||
use reims_vgpu_vulkan::core::platform::compute::{ComputeCmd, ComputeEncoder as _};
|
||||
use reims_vgpu_vulkan::core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_vulkan::core::platform::resource::{Buffer as _, Library as _};
|
||||
use reims_vgpu_vulkan::core::platform::types::{CommandBufferStatus, MtlSize, NsRange};
|
||||
use reims_vgpu_vulkan::core::raise::OnFault;
|
||||
|
||||
use super::super::video_host::{BackendError, OutputPlane};
|
||||
use super::{Filled, GpuCopier, GpuCopies, GpuFiller, NAME, STORAGE_PRIVATE};
|
||||
|
||||
/// The platform library's kernel that writes a plane of the encoder's input (`shaders.metal`).
|
||||
const FILL_KERNEL: &str = "videoEncodeFill";
|
||||
|
||||
/// The threads of a fill's threadgroup, along a row.
|
||||
const GROUP_WIDTH: u64 = 64;
|
||||
|
||||
/// Where a plane's source is bound: its first byte rounded down to a multiple of this, which a
|
||||
/// buffer binding's offset takes on any device.
|
||||
const BINDING_ALIGNMENT: u64 = 256;
|
||||
|
||||
/// The bytes between the chroma plane's arguments and the luma's in the arguments' buffer: a
|
||||
/// constant buffer's binding offset is a multiple of 256 on any device.
|
||||
const ARGUMENTS_APART: u64 = 256;
|
||||
|
||||
/// What `videoEncodeFill` takes of a plane (`shaders.metal`'s `VideoFillPlane`): where the plane
|
||||
/// lies in its source buffer as bound, its rows and the bytes its margin repeats, and the input's
|
||||
/// words a row, its rows and its words from one row to the next.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct FillPlane {
|
||||
first: u32,
|
||||
source_pitch: u32,
|
||||
row_bytes: u32,
|
||||
rows: u32,
|
||||
unit: u32,
|
||||
coded_words: u32,
|
||||
coded_rows: u32,
|
||||
pitch_words: u32,
|
||||
}
|
||||
|
||||
impl FillPlane {
|
||||
/// Its bytes, as the kernel reads them.
|
||||
fn bytes(&self) -> [u8; 32] {
|
||||
let words = [
|
||||
self.first,
|
||||
self.source_pitch,
|
||||
self.row_bytes,
|
||||
self.rows,
|
||||
self.unit,
|
||||
self.coded_words,
|
||||
self.coded_rows,
|
||||
self.pitch_words,
|
||||
];
|
||||
let mut bytes = [0; 32];
|
||||
for (to, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) {
|
||||
*to = word.to_le_bytes();
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// The threadgroups of its dispatch: a thread a word of the input.
|
||||
fn threadgroups(&self) -> MtlSize {
|
||||
let across = u64::from(self.coded_words).div_ceil(GROUP_WIDTH);
|
||||
MtlSize::new(across, u64::from(self.coded_rows), 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a source plane lies: its buffer's bytes, its first byte, the bytes from one of its rows
|
||||
/// to the next, the bytes of a row, and the rows it holds.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Source {
|
||||
length: u64,
|
||||
offset: u64,
|
||||
bytes_per_row: u64,
|
||||
row_bytes: u64,
|
||||
height: u64,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
fn of<P: Platform>(plane: &OutputPlane<P>) -> Self {
|
||||
Self {
|
||||
length: plane.buffer.length(),
|
||||
offset: plane.offset,
|
||||
bytes_per_row: plane.bytes_per_row,
|
||||
row_bytes: plane.row_bytes,
|
||||
height: plane.height,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One plane's dispatch: its source bound from byte `bound`, the input's bytes from `at`, and
|
||||
/// what the kernel takes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct PlaneFill {
|
||||
bound: u64,
|
||||
at: u64,
|
||||
plane: FillPlane,
|
||||
}
|
||||
|
||||
/// The pitch of an input of `shape` (module doc).
|
||||
fn pitch_of(shape: TargetShape) -> u64 {
|
||||
(u64::from(shape.coded.0) * shape.format.bytes_per_sample()).next_multiple_of(TARGET_ALIGNMENT)
|
||||
}
|
||||
|
||||
/// The bytes of an input of `shape` at `pitch`, and its chroma plane's first byte.
|
||||
fn input_bytes(shape: TargetShape, pitch: u64) -> (u64, u64) {
|
||||
let rows = u64::from(shape.coded.1);
|
||||
let chroma_at = pitch * rows;
|
||||
(chroma_at + pitch * (rows / 2), chroma_at)
|
||||
}
|
||||
|
||||
/// The dispatches that write a frame of `size` (luma samples) from `sources`, its luma and chroma
|
||||
/// planes, into an input of `shape` (module doc): `Err` says why none can. The rows read are the
|
||||
/// upload's: `height` of luma and `height / 2` of chroma, each `width` samples' bytes, its margin
|
||||
/// repeating a sample, or a Cb/Cr pair.
|
||||
fn plane_fills(
|
||||
sources: [Source; 2],
|
||||
(width, height): (u32, u32),
|
||||
shape: TargetShape,
|
||||
) -> Result<[PlaneFill; 2], String> {
|
||||
let (coded_width, coded_height) = shape.coded;
|
||||
if width < 2 || height < 2 || coded_width < width || coded_height < height {
|
||||
return Err(format!(
|
||||
"a frame of {width}x{height} for an input of {coded_width}x{coded_height}"
|
||||
));
|
||||
}
|
||||
let sample = shape.format.bytes_per_sample();
|
||||
let row_bytes = u64::from(width) * sample;
|
||||
let coded_bytes = u64::from(coded_width) * sample;
|
||||
let pitch = pitch_of(shape);
|
||||
if coded_bytes % 4 != 0 {
|
||||
return Err(format!(
|
||||
"coded rows of {coded_bytes} bytes, not whole words"
|
||||
));
|
||||
}
|
||||
let (_, chroma_at) = input_bytes(shape, pitch);
|
||||
let narrow = |v: u64, what: &str| u32::try_from(v).map_err(|_| format!("{what} of {v}"));
|
||||
// A plane's dispatch: `rows` of the source's rows into the input's `coded_rows` from its byte
|
||||
// `at`, its margin repeating `unit` bytes.
|
||||
let plane = |source: Source, rows: u64, coded_rows: u64, unit: u64, at: u64, which: &str| {
|
||||
if source.row_bytes < row_bytes || source.bytes_per_row < row_bytes || source.height < rows
|
||||
{
|
||||
return Err(format!(
|
||||
"a {which} plane of {} rows of {} bytes, {} apart, for a frame of {rows} of \
|
||||
{row_bytes}",
|
||||
source.height, source.row_bytes, source.bytes_per_row
|
||||
));
|
||||
}
|
||||
let bound = source.offset - source.offset % BINDING_ALIGNMENT;
|
||||
let first = source.offset - bound;
|
||||
// The kernel reads whole words: the word that holds the last byte lies in the buffer.
|
||||
let reach = (first + (rows - 1) * source.bytes_per_row + row_bytes).next_multiple_of(4);
|
||||
if bound + reach > source.length {
|
||||
return Err(format!(
|
||||
"a {which} plane whose last row's word ends at byte {} of a buffer of {}",
|
||||
bound + reach,
|
||||
source.length
|
||||
));
|
||||
}
|
||||
let pitch_words = pitch / 4;
|
||||
narrow(reach, "a source plane's reach")?;
|
||||
narrow(pitch_words * coded_rows, "an input plane's words")?;
|
||||
Ok(PlaneFill {
|
||||
bound,
|
||||
at,
|
||||
plane: FillPlane {
|
||||
first: narrow(first, "a first byte")?,
|
||||
source_pitch: narrow(source.bytes_per_row, "a pitch")?,
|
||||
row_bytes: narrow(row_bytes, "a row's bytes")?,
|
||||
rows: narrow(rows, "rows")?,
|
||||
unit: narrow(unit, "a unit")?,
|
||||
coded_words: narrow(coded_bytes / 4, "a coded row's words")?,
|
||||
coded_rows: narrow(coded_rows, "coded rows")?,
|
||||
pitch_words: narrow(pitch_words, "a pitch's words")?,
|
||||
},
|
||||
})
|
||||
};
|
||||
let (height, coded_height) = (u64::from(height), u64::from(coded_height));
|
||||
Ok([
|
||||
plane(sources[0], height, coded_height, sample, 0, "luma")?,
|
||||
plane(
|
||||
sources[1],
|
||||
height / 2,
|
||||
coded_height / 2,
|
||||
2 * sample,
|
||||
chroma_at,
|
||||
"chroma",
|
||||
)?,
|
||||
])
|
||||
}
|
||||
|
||||
/// The kernel's pipeline on a device, made at a session's first fill and kept for the device's
|
||||
/// sessions.
|
||||
struct Pipeline<P: Platform> {
|
||||
device: P::Device,
|
||||
made: OnceLock<Result<P::ComputePipeline, String>>,
|
||||
}
|
||||
|
||||
impl<P: Platform> Pipeline<P> {
|
||||
/// The pipeline; `Err` says why the device makes none.
|
||||
fn get(&self) -> Result<P::ComputePipeline, String> {
|
||||
let made = self.made.get_or_init(|| {
|
||||
let library = match self.device.new_shader_library() {
|
||||
Ok(Some(library)) => library,
|
||||
Ok(None) => return Err("the platform's library is not made".to_owned()),
|
||||
Err(error) => return Err(format!("the platform's library: {error}")),
|
||||
};
|
||||
let function = match library.new_function(OnFault::Return, FILL_KERNEL) {
|
||||
Ok(Some(function)) => function,
|
||||
Ok(None) => return Err(format!("the platform's library holds no {FILL_KERNEL}")),
|
||||
Err(raise) => return Err(format!("{FILL_KERNEL}: {raise}")),
|
||||
};
|
||||
match self
|
||||
.device
|
||||
.new_compute_pipeline_state_for_function(Some(&function))
|
||||
{
|
||||
Ok(Some(pipeline)) => Ok(pipeline),
|
||||
Ok(None) => Err(format!("{FILL_KERNEL}'s pipeline is refused")),
|
||||
Err(error) => Err(format!("{FILL_KERNEL}'s pipeline: {error}")),
|
||||
}
|
||||
});
|
||||
made.as_ref().map(|p| p.clone_ref()).map_err(Clone::clone)
|
||||
}
|
||||
}
|
||||
|
||||
/// The GPU fills of a device's encode sessions (module doc), and no GPU copies of decoded
|
||||
/// pictures: a decode's picture lands by the driver's video processing or the CPU's copy, as it
|
||||
/// does with no `GpuCopies` at all.
|
||||
pub(super) struct DeviceFills<P: Platform> {
|
||||
pipeline: Arc<Pipeline<P>>,
|
||||
runtime: Arc<dyn Runtime>,
|
||||
}
|
||||
|
||||
impl<P: Platform> DeviceFills<P> {
|
||||
/// The fills of `device`'s sessions, timed on `runtime`'s clock.
|
||||
pub(super) fn new(device: &P::Device, runtime: &Arc<dyn Runtime>) -> Self {
|
||||
Self {
|
||||
pipeline: Arc::new(Pipeline {
|
||||
device: device.clone_ref(),
|
||||
made: OnceLock::new(),
|
||||
}),
|
||||
runtime: Arc::clone(runtime),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> GpuCopies<P> for DeviceFills<P> {
|
||||
fn copier(&self) -> Result<Box<dyn GpuCopier<P>>, String> {
|
||||
Err("the platform makes no GPU copies".to_owned())
|
||||
}
|
||||
|
||||
fn filler(&self) -> Result<Box<dyn GpuFiller<P>>, String> {
|
||||
Ok(Box::new(DeviceFiller {
|
||||
pipeline: Arc::clone(&self.pipeline),
|
||||
queue: None,
|
||||
arguments: None,
|
||||
inputs: Vec::new(),
|
||||
refused: None,
|
||||
failed: Vec::new(),
|
||||
filled: 0,
|
||||
runtime: Arc::clone(&self.runtime),
|
||||
total: Duration::ZERO,
|
||||
longest: Duration::ZERO,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// An input of the session's (module doc).
|
||||
struct Input<P: Platform> {
|
||||
buffer: P::Buffer,
|
||||
/// Its import on the encoder's display, which holds the buffer.
|
||||
target: Target,
|
||||
shape: TargetShape,
|
||||
}
|
||||
|
||||
/// One encode session's fills of its frames into its encoder's inputs (module doc).
|
||||
struct DeviceFiller<P: Platform> {
|
||||
pipeline: Arc<Pipeline<P>>,
|
||||
queue: Option<P::CommandQueue>,
|
||||
/// The kernel's arguments, the luma plane's and the chroma's, which the CPU writes before each
|
||||
/// fill: the last fill was waited for.
|
||||
arguments: Option<P::Buffer>,
|
||||
inputs: Vec<Input<P>>,
|
||||
/// Why no input or pipeline is made, once one was refused: the session's later frames are
|
||||
/// declined with it, and no make is tried again.
|
||||
refused: Option<String>,
|
||||
/// Inputs whose fill failed on the GPU, which may write them still.
|
||||
failed: Vec<Input<P>>,
|
||||
/// Frames filled, and the time of their fills from submission to their wait's end.
|
||||
filled: u64,
|
||||
/// The clock the fills are timed on: the video's runtime's.
|
||||
runtime: Arc<dyn Runtime>,
|
||||
total: Duration,
|
||||
longest: Duration,
|
||||
}
|
||||
|
||||
impl<P: Platform> GpuFiller<P> for DeviceFiller<P> {
|
||||
fn fill(
|
||||
&mut self,
|
||||
encoder: &VideoEncoder,
|
||||
luma: &OutputPlane<P>,
|
||||
chroma: &OutputPlane<P>,
|
||||
) -> Result<Filled, BackendError> {
|
||||
if luma.in_surface() || chroma.in_surface() {
|
||||
return Ok(Filled::Declined(
|
||||
"a plane in its cache's surface".to_owned(),
|
||||
));
|
||||
}
|
||||
let shape = encoder.input_shape();
|
||||
let settings = encoder.settings();
|
||||
let size = (settings.width, settings.height);
|
||||
let fills = match plane_fills([Source::of(luma), Source::of(chroma)], size, shape) {
|
||||
Ok(fills) => fills,
|
||||
Err(why) => return Ok(Filled::Declined(why)),
|
||||
};
|
||||
if let Some(why) = &self.refused {
|
||||
return Ok(Filled::Declined(why.clone()));
|
||||
}
|
||||
let pipeline = match self.pipeline.get() {
|
||||
Ok(pipeline) => pipeline,
|
||||
Err(why) => return Ok(Filled::Declined(self.refused.insert(why).clone())),
|
||||
};
|
||||
let index = match self.input_for(encoder, shape) {
|
||||
Ok(index) => index,
|
||||
Err(why) => return Ok(Filled::Declined(self.refused.insert(why).clone())),
|
||||
};
|
||||
let (destination, target) = {
|
||||
let input = &self.inputs[index];
|
||||
(input.buffer.clone_ref(), input.target.clone())
|
||||
};
|
||||
let start = self.runtime.now();
|
||||
let sources = [&luma.buffer, &chroma.buffer];
|
||||
match self.write(&pipeline, &destination, sources, &fills) {
|
||||
Ok(None) => {
|
||||
let took = self.runtime.elapsed_since(start);
|
||||
self.filled += 1;
|
||||
self.total += took;
|
||||
self.longest = self.longest.max(took);
|
||||
Ok(Filled::Written(target))
|
||||
}
|
||||
Ok(Some(why)) => Ok(Filled::Declined(why)),
|
||||
Err(error) => {
|
||||
self.failed.push(self.inputs.swap_remove(index));
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> DeviceFiller<P> {
|
||||
/// The index of the session's input of `shape` that `encoder` no longer holds, made where
|
||||
/// there is none (module doc); the others are let go of. `Err` says why none is made.
|
||||
fn input_for(&mut self, encoder: &VideoEncoder, shape: TargetShape) -> Result<usize, String> {
|
||||
self.inputs
|
||||
.retain(|input| input.shape == shape && !input.target.is_held());
|
||||
if self.inputs.is_empty() {
|
||||
let input = self.make_input(encoder, shape)?;
|
||||
self.inputs.push(input);
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// A new input of `shape`, imported on `encoder`'s display.
|
||||
fn make_input(&self, encoder: &VideoEncoder, shape: TargetShape) -> Result<Input<P>, String> {
|
||||
let pitch = pitch_of(shape);
|
||||
let (length, chroma_at) = input_bytes(shape, pitch);
|
||||
let made = self
|
||||
.pipeline
|
||||
.device
|
||||
.new_dma_buf_buffer_of_length_padding_unobserved(
|
||||
OnFault::Return,
|
||||
length,
|
||||
STORAGE_PRIVATE,
|
||||
Some(0),
|
||||
);
|
||||
let buffer = match made {
|
||||
Ok(Some(buffer)) => buffer,
|
||||
Ok(None) => return Err("the device makes no buffer of a dma-buf".to_owned()),
|
||||
Err(raise) => return Err(format!("a buffer of a dma-buf's make: {raise}")),
|
||||
};
|
||||
let exported = buffer.export_dma_buf()?;
|
||||
if exported.offset % TARGET_ALIGNMENT != 0 {
|
||||
return Err(format!(
|
||||
"an input at byte {} of its dma-buf, not on {TARGET_ALIGNMENT}",
|
||||
exported.offset
|
||||
));
|
||||
}
|
||||
let planes = [
|
||||
TargetPlane {
|
||||
offset: exported.offset,
|
||||
bytes_per_row: pitch,
|
||||
},
|
||||
TargetPlane {
|
||||
offset: exported.offset + chroma_at,
|
||||
bytes_per_row: pitch,
|
||||
},
|
||||
];
|
||||
let target = encoder
|
||||
.import_input(
|
||||
exported.fd.as_fd(),
|
||||
exported.allocation_size,
|
||||
planes,
|
||||
Box::new(buffer.clone_ref()),
|
||||
)
|
||||
.map_err(|error| format!("the import of an input: {error}"))?;
|
||||
Ok(Input {
|
||||
buffer,
|
||||
target,
|
||||
shape,
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes `fills` from `sources`, the luma plane's buffer and the chroma's, into
|
||||
/// `destination` by the kernel's `pipeline`, releases it to the driver and waits for it, on
|
||||
/// the filler's queue. `Some` says why nothing was submitted; `Err` is a fill that failed once
|
||||
/// submitted.
|
||||
fn write(
|
||||
&mut self,
|
||||
pipeline: &P::ComputePipeline,
|
||||
destination: &P::Buffer,
|
||||
sources: [&P::Buffer; 2],
|
||||
fills: &[PlaneFill; 2],
|
||||
) -> Result<Option<String>, BackendError> {
|
||||
let device = &self.pipeline.device;
|
||||
if self.queue.is_none() {
|
||||
let Some(queue) = device.new_command_queue() else {
|
||||
return Ok(Some("no command queue".to_owned()));
|
||||
};
|
||||
queue.set_label("reims-vgpu.graphics-video-fill");
|
||||
self.queue = Some(queue);
|
||||
}
|
||||
if self.arguments.is_none() {
|
||||
let made = device.new_buffer_of_length(OnFault::Return, 2 * ARGUMENTS_APART, 0);
|
||||
match made {
|
||||
Ok(Some(buffer)) => self.arguments = Some(buffer),
|
||||
Ok(None) => return Ok(Some("no buffer for the kernel's arguments".to_owned())),
|
||||
Err(raise) => return Ok(Some(format!("the arguments' buffer: {raise}"))),
|
||||
}
|
||||
}
|
||||
let (Some(queue), Some(arguments)) = (self.queue.as_ref(), self.arguments.as_ref()) else {
|
||||
return Ok(Some("no command queue".to_owned()));
|
||||
};
|
||||
let cb = match queue.command_buffer(OnFault::Return) {
|
||||
Ok(Some(cb)) => cb,
|
||||
Ok(None) => return Ok(Some("no command buffer".to_owned())),
|
||||
Err(raise) => return Ok(Some(format!("its command buffer: {raise}"))),
|
||||
};
|
||||
let planes = Planes {
|
||||
pipeline,
|
||||
arguments,
|
||||
destination,
|
||||
sources,
|
||||
};
|
||||
if let Some(why) = encode_planes::<P>(&cb, &planes, fills) {
|
||||
return Ok(Some(why));
|
||||
}
|
||||
let blit = match cb.blit_encoder(OnFault::Return) {
|
||||
Ok(Some(blit)) => blit,
|
||||
Ok(None) => return Ok(Some("no blit encoder".to_owned())),
|
||||
Err(raise) => return Ok(Some(format!("its blit encoder: {raise}"))),
|
||||
};
|
||||
if let Err(why) = blit.release_to_external(destination) {
|
||||
return Ok(Some(format!("its release to the driver: {why}")));
|
||||
}
|
||||
if let Err(raise) = blit.encode(OnFault::Return, BlitCmd::EndEncoding) {
|
||||
return Ok(Some(format!("its end: {raise}")));
|
||||
}
|
||||
if let Err(raise) = cb.commit(OnFault::Return) {
|
||||
return Ok(Some(format!("its commit: {raise}")));
|
||||
}
|
||||
let failed = match cb.wait_until_completed(OnFault::Return) {
|
||||
Err(raise) => Some(format!("its wait: {raise}")),
|
||||
Ok(()) if cb.status() != CommandBufferStatus::COMPLETED => {
|
||||
let error = cb.error().map(|e| format!("{e:?}")).unwrap_or_default();
|
||||
Some(format!("the fill failed {error}"))
|
||||
}
|
||||
Ok(()) => None,
|
||||
};
|
||||
match failed {
|
||||
Some(failed) => {
|
||||
Err(format!("the GPU's fill of a frame into the encoder's input: {failed}").into())
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a fill's dispatches bind: the kernel's pipeline, the buffer of its arguments, the input
|
||||
/// they write, and the luma plane's buffer and the chroma's they read.
|
||||
struct Planes<'a, P: Platform> {
|
||||
pipeline: &'a P::ComputePipeline,
|
||||
arguments: &'a P::Buffer,
|
||||
destination: &'a P::Buffer,
|
||||
sources: [&'a P::Buffer; 2],
|
||||
}
|
||||
|
||||
/// Writes each of `fills`' arguments into `planes.arguments`, 256 bytes apart, and encodes into
|
||||
/// `cb` the pass that writes them (module doc): one dispatch a plane. `Some` says why it could
|
||||
/// not, with nothing committed.
|
||||
fn encode_planes<P: Platform>(
|
||||
cb: &P::CommandBuffer,
|
||||
planes: &Planes<'_, P>,
|
||||
fills: &[PlaneFill; 2],
|
||||
) -> Option<String> {
|
||||
let contents = planes.arguments.contents();
|
||||
if contents.is_null() || planes.arguments.length() < 2 * ARGUMENTS_APART {
|
||||
return Some("the arguments' buffer has no host bytes for both planes".to_owned());
|
||||
}
|
||||
let contents = contents.as_ptr::<u8>();
|
||||
for (n, fill) in fills.iter().enumerate() {
|
||||
let bytes = fill.plane.bytes();
|
||||
// SAFETY: the buffer's host bytes, two planes' arguments apart at least, hold each plane's
|
||||
// 32 at its multiple of 256; and no GPU work reads them: the fill before was waited for.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(
|
||||
bytes.as_ptr(),
|
||||
contents.add(n * ARGUMENTS_APART as usize),
|
||||
bytes.len(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let compute = match cb.compute_encoder(OnFault::Return) {
|
||||
Ok(Some(compute)) => compute,
|
||||
Ok(None) => return Some("no compute encoder".to_owned()),
|
||||
Err(raise) => return Some(format!("its compute encoder: {raise}")),
|
||||
};
|
||||
let state = ComputeCmd::SetComputePipelineState {
|
||||
state: Some(planes.pipeline),
|
||||
};
|
||||
if let Err(raise) = compute.encode(OnFault::Return, state) {
|
||||
return Some(format!("its pipeline: {raise}"));
|
||||
}
|
||||
for ((n, fill), source) in fills.iter().enumerate().zip(planes.sources) {
|
||||
let commands = [
|
||||
ComputeCmd::SetBuffers {
|
||||
buffers: &[
|
||||
Some(source),
|
||||
Some(planes.destination),
|
||||
Some(planes.arguments),
|
||||
],
|
||||
offsets: &[fill.bound, fill.at, n as u64 * ARGUMENTS_APART],
|
||||
range: NsRange {
|
||||
location: 0,
|
||||
length: 3,
|
||||
},
|
||||
},
|
||||
ComputeCmd::DispatchThreadgroups {
|
||||
threadgroups_per_grid: fill.plane.threadgroups(),
|
||||
threads_per_threadgroup: MtlSize::new(GROUP_WIDTH, 1, 1),
|
||||
},
|
||||
];
|
||||
for command in commands {
|
||||
if let Err(raise) = compute.encode(OnFault::Return, command) {
|
||||
return Some(format!("a plane's dispatch: {raise}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(raise) = compute.encode(OnFault::Return, ComputeCmd::EndEncoding) {
|
||||
return Some(format!("its compute end: {raise}"));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl<P: Platform> Drop for DeviceFiller<P> {
|
||||
fn drop(&mut self) {
|
||||
if self.filled == 0 {
|
||||
return;
|
||||
}
|
||||
let ms = |d: Duration| d.as_secs_f64() * 1e3;
|
||||
let mean = self.total / u32::try_from(self.filled).unwrap_or(u32::MAX);
|
||||
log::info!(
|
||||
"hardware video: {NAME}: an encode session's frames written by the GPU into the \
|
||||
encoder's inputs: {}, {:.3} ms each from submission to the wait's end, {:.3} ms at \
|
||||
most",
|
||||
self.filled,
|
||||
ms(mean),
|
||||
ms(self.longest)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,320 @@
|
||||
use reims_vgpu_video::vaapi::TargetFormat;
|
||||
use reims_vgpu_vulkan::core::testkit::FakePlatform;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A frame's shape: NV12 or P010, coded at `coded`.
|
||||
fn shape(format: TargetFormat, coded: (u32, u32)) -> TargetShape {
|
||||
TargetShape { format, coded }
|
||||
}
|
||||
|
||||
/// A plane of `height` rows of `row_bytes`, `bytes_per_row` apart from `offset`, in a buffer of
|
||||
/// `length` bytes.
|
||||
fn source(length: u64, offset: u64, bytes_per_row: u64, row_bytes: u64, height: u64) -> Source {
|
||||
Source {
|
||||
length,
|
||||
offset,
|
||||
bytes_per_row,
|
||||
row_bytes,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes the VA crate's upload writes into a plane of the input from `bytes` (its
|
||||
/// `copy_planes`): `coded_rows` rows of `coded_bytes`, each the source's row `fill.first` and on,
|
||||
/// the last row repeated past the frame's rows, each row's bytes past `row_bytes` its last `unit`
|
||||
/// bytes repeated.
|
||||
fn uploaded(bytes: &[u8], fill: &PlaneFill, coded_bytes: usize) -> Vec<u8> {
|
||||
let p = &fill.plane;
|
||||
let (row_bytes, unit) = (p.row_bytes as usize, p.unit as usize);
|
||||
let mut plane = Vec::new();
|
||||
for row in 0..p.coded_rows {
|
||||
let from = fill.bound as usize
|
||||
+ p.first as usize
|
||||
+ row.min(p.rows - 1) as usize * p.source_pitch as usize;
|
||||
let source = &bytes[from..from + row_bytes];
|
||||
plane.extend_from_slice(source);
|
||||
let last = &source[row_bytes - unit..];
|
||||
plane.extend((0..coded_bytes - row_bytes).map(|m| last[m % unit]));
|
||||
}
|
||||
plane
|
||||
}
|
||||
|
||||
/// An input's rows lie a pitch apart, the coded row's bytes rounded up to 256, and its chroma
|
||||
/// plane's coded rows, half as many, right after the luma plane's.
|
||||
#[test]
|
||||
fn an_inputs_planes_lie_one_pitch_on_256_apart() {
|
||||
for (format, coded, pitch) in [
|
||||
(TargetFormat::Nv12, (336, 208), 512),
|
||||
(TargetFormat::P010, (336, 208), 768),
|
||||
(TargetFormat::Nv12, (1920, 1088), 2048),
|
||||
(TargetFormat::P010, (3840, 2160), 7680),
|
||||
] {
|
||||
let shape = shape(format, coded);
|
||||
assert_eq!(pitch_of(shape), pitch, "{shape:?}");
|
||||
let rows = u64::from(coded.1);
|
||||
assert_eq!(
|
||||
input_bytes(shape, pitch),
|
||||
(pitch * rows * 3 / 2, pitch * rows),
|
||||
"{shape:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A 330x202 frame into an input coded 336x208: each plane bound from its first byte rounded
|
||||
/// down to 256, the rows and units the upload reads, the coded rows' words, and the chroma
|
||||
/// plane's from the luma plane's coded rows on.
|
||||
#[test]
|
||||
fn a_frames_planes_fill_the_input_as_the_upload_does() {
|
||||
let luma_at = 800;
|
||||
let chroma_at = luma_at + 512 * 202;
|
||||
let length = chroma_at + 512 * 101;
|
||||
let sources = [
|
||||
source(length, luma_at, 512, 330, 202),
|
||||
source(length, chroma_at, 512, 330, 101),
|
||||
];
|
||||
let nv12 = plane_fills(sources, (330, 202), shape(TargetFormat::Nv12, (336, 208)));
|
||||
let expected = |bound, first, rows, unit, coded_rows, at| PlaneFill {
|
||||
bound,
|
||||
at,
|
||||
plane: FillPlane {
|
||||
first,
|
||||
source_pitch: 512,
|
||||
row_bytes: 330,
|
||||
rows,
|
||||
unit,
|
||||
coded_words: 84,
|
||||
coded_rows,
|
||||
pitch_words: 128,
|
||||
},
|
||||
};
|
||||
assert_eq!(
|
||||
nv12,
|
||||
Ok([
|
||||
expected(768, 32, 202, 1, 208, 0),
|
||||
expected(chroma_at - 32, 32, 101, 2, 104, 512 * 208),
|
||||
])
|
||||
);
|
||||
// P010's samples are two bytes: rows of 660 of 672 coded, 768 apart in the input.
|
||||
let sources = [
|
||||
source(1 << 20, 0, 1024, 660, 202),
|
||||
source(1 << 20, 1024 * 202, 1024, 660, 101),
|
||||
];
|
||||
let p010 =
|
||||
plane_fills(sources, (330, 202), shape(TargetFormat::P010, (336, 208))).expect("the fills");
|
||||
assert_eq!(
|
||||
p010.map(|f| (
|
||||
f.plane.row_bytes,
|
||||
f.plane.unit,
|
||||
f.plane.coded_words,
|
||||
f.plane.pitch_words
|
||||
)),
|
||||
[(660, 2, 168, 192), (660, 4, 168, 192)]
|
||||
);
|
||||
assert_eq!(p010.map(|f| f.at), [0, 768 * 208]);
|
||||
}
|
||||
|
||||
/// A frame is declined, with why, where the input does not hold it or its coded rows are not
|
||||
/// whole words, and where a plane holds fewer rows, or narrower ones, than the frame, or its last
|
||||
/// row's last word lies past its buffer; a plane whose last word ends at its buffer's end is
|
||||
/// taken.
|
||||
#[test]
|
||||
fn a_frame_the_input_or_its_planes_cannot_hold_is_declined() {
|
||||
let nv12 = shape(TargetFormat::Nv12, (336, 208));
|
||||
let fits = |luma: Source, chroma: Source, size: (u32, u32), shape: TargetShape| {
|
||||
plane_fills([luma, chroma], size, shape)
|
||||
};
|
||||
// Luma: 202 rows of 330 from byte 0, 512 apart; its last word ends at byte 202 * 512 - 180.
|
||||
let luma_end = 201 * 512 + 332;
|
||||
let luma = source(luma_end, 0, 512, 330, 202);
|
||||
let chroma = source(1 << 20, 0, 512, 330, 101);
|
||||
assert!(fits(luma, chroma, (330, 202), nv12).is_ok());
|
||||
let declined = |r: Result<[PlaneFill; 2], String>, what: &str| match r {
|
||||
Ok(fills) => panic!("{what}: taken: {fills:?}"),
|
||||
Err(why) => why,
|
||||
};
|
||||
let why = declined(fits(luma, chroma, (340, 202), nv12), "a frame wider");
|
||||
assert!(why.starts_with("a frame of 340x202"), "{why}");
|
||||
let why = declined(
|
||||
fits(
|
||||
luma,
|
||||
chroma,
|
||||
(330, 202),
|
||||
shape(TargetFormat::Nv12, (330, 208)),
|
||||
),
|
||||
"coded rows of 330 bytes",
|
||||
);
|
||||
assert!(why.contains("not whole words"), "{why}");
|
||||
let short = source(1 << 20, 0, 512, 330, 201);
|
||||
let why = declined(fits(short, chroma, (330, 202), nv12), "a luma plane short");
|
||||
assert!(why.starts_with("a luma plane of 201 rows"), "{why}");
|
||||
let narrow = source(1 << 20, 0, 512, 328, 101);
|
||||
let why = declined(
|
||||
fits(luma, narrow, (330, 202), nv12),
|
||||
"a chroma plane narrow",
|
||||
);
|
||||
assert!(
|
||||
why.starts_with("a chroma plane of 101 rows of 328 bytes"),
|
||||
"{why}"
|
||||
);
|
||||
let close = source(luma_end - 1, 0, 512, 330, 202);
|
||||
let why = declined(fits(close, chroma, (330, 202), nv12), "a last word past");
|
||||
assert!(why.contains(&format!("ends at byte {luma_end}")), "{why}");
|
||||
}
|
||||
|
||||
/// A plane's arguments are `shaders.metal`'s `VideoFillPlane`, eight 32-bit words in its order,
|
||||
/// and its dispatch a threadgroup of 64 threads a 64 words of a row, a row of threadgroups each
|
||||
/// coded row.
|
||||
#[test]
|
||||
fn a_planes_arguments_are_the_kernels_and_its_grid_covers_its_words() {
|
||||
let plane = FillPlane {
|
||||
first: 1,
|
||||
source_pitch: 2,
|
||||
row_bytes: 3,
|
||||
rows: 4,
|
||||
unit: 5,
|
||||
coded_words: 130,
|
||||
coded_rows: 7,
|
||||
pitch_words: 8,
|
||||
};
|
||||
let bytes = plane.bytes();
|
||||
let words: Vec<u32> = (bytes.as_chunks::<4>().0.iter())
|
||||
.map(|w| u32::from_le_bytes(*w))
|
||||
.collect();
|
||||
assert_eq!(words, [1, 2, 3, 4, 5, 130, 7, 8]);
|
||||
assert_eq!(plane.threadgroups(), MtlSize::new(3, 7, 1));
|
||||
}
|
||||
|
||||
/// The device's GPU copies make no copier, so a decode's pictures land as with none, its reason
|
||||
/// the same; and a filler each encode session.
|
||||
#[test]
|
||||
fn the_devices_fills_make_no_copier_and_a_filler_each_session() {
|
||||
let platform = FakePlatform::new();
|
||||
let runtime: Arc<dyn Runtime> = Arc::new(reims_vgpu_video::core::runtime::StdRuntime);
|
||||
let fills = DeviceFills::<FakePlatform>::new(&platform.device(), &runtime);
|
||||
match fills.copier() {
|
||||
Ok(_) => panic!("a copier"),
|
||||
Err(why) => assert_eq!(why, "the platform makes no GPU copies"),
|
||||
}
|
||||
assert!(fills.filler().is_ok());
|
||||
assert!(fills.filler().is_ok());
|
||||
}
|
||||
|
||||
/// `length` bytes, each a pattern of its index that no two nearby bytes share.
|
||||
fn pattern(length: usize) -> Vec<u8> {
|
||||
(0..length)
|
||||
.map(|i| (i.wrapping_mul(131) ^ (i >> 8).wrapping_mul(29)) as u8)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// On the host's GPU, the kernel writes each plane of a frame into an input as the VA crate's
|
||||
/// upload writes it, byte for byte: every coded row's bytes, the frame's rows and the margin past
|
||||
/// them, and nothing past each coded row's bytes. NV12 and P010, frames with a margin of columns
|
||||
/// and rows and with none, from planes at offsets and pitches on 256 bytes and off them, odd
|
||||
/// among them.
|
||||
#[test]
|
||||
fn on_rt_the_kernel_writes_a_frame_as_the_upload_writes_it() {
|
||||
use reims_vgpu_vulkan::RtPlatform;
|
||||
|
||||
const UNTOUCHED: u8 = 0xa5;
|
||||
let platform = crate::rt_test_end::platform();
|
||||
crate::entry::run(|_| {
|
||||
let device = platform.system_default_device().expect("an rt device");
|
||||
let pipeline = Pipeline::<RtPlatform> {
|
||||
device: device.clone_ref(),
|
||||
made: OnceLock::new(),
|
||||
};
|
||||
let pipeline = pipeline.get().expect("the kernel's pipeline");
|
||||
let queue = device.new_command_queue().expect("a queue");
|
||||
let shared = |length: u64| {
|
||||
(device.new_buffer_of_length(OnFault::Return, length, 0))
|
||||
.expect("no raise")
|
||||
.expect("a buffer")
|
||||
};
|
||||
let arguments = shared(2 * ARGUMENTS_APART);
|
||||
let cases = [
|
||||
(TargetFormat::Nv12, (330, 202), (336, 208), 32, 512),
|
||||
(TargetFormat::Nv12, (320, 192), (320, 192), 0, 320),
|
||||
(TargetFormat::Nv12, (330, 202), (336, 208), 35, 333),
|
||||
(TargetFormat::Nv12, (64, 48), (64, 64), 258, 700),
|
||||
(TargetFormat::P010, (330, 202), (336, 208), 32, 768),
|
||||
(TargetFormat::P010, (330, 202), (352, 224), 2, 662),
|
||||
];
|
||||
for (format, (width, height), coded, first, pitch) in cases {
|
||||
let what = format!("{format:?} {width}x{height} in {coded:?} from {first} at {pitch}");
|
||||
let shape = shape(format, coded);
|
||||
let sample = format.bytes_per_sample();
|
||||
let row_bytes = u64::from(width) * sample;
|
||||
let chroma_first = first + pitch * u64::from(height) + 3;
|
||||
let length = (chroma_first + pitch * u64::from(height / 2) + 64).next_multiple_of(4);
|
||||
let bytes = pattern(length as usize);
|
||||
let source_buffer = shared(length);
|
||||
// SAFETY: the buffer's `length` host bytes, which no GPU work reaches yet.
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(
|
||||
bytes.as_ptr(),
|
||||
source_buffer.contents().as_ptr::<u8>(),
|
||||
bytes.len(),
|
||||
);
|
||||
}
|
||||
let sources = [
|
||||
source(length, first, pitch, row_bytes, u64::from(height)),
|
||||
source(
|
||||
length,
|
||||
chroma_first,
|
||||
pitch,
|
||||
row_bytes,
|
||||
u64::from(height / 2),
|
||||
),
|
||||
];
|
||||
let fills = plane_fills(sources, (width, height), shape).expect(&what);
|
||||
let input_pitch = pitch_of(shape);
|
||||
let (input_length, _) = input_bytes(shape, input_pitch);
|
||||
let input = shared(input_length);
|
||||
// SAFETY: the input's host bytes, which no GPU work reaches yet.
|
||||
unsafe {
|
||||
std::ptr::write_bytes(
|
||||
input.contents().as_ptr::<u8>(),
|
||||
UNTOUCHED,
|
||||
input_length as usize,
|
||||
);
|
||||
}
|
||||
let cb = (queue.command_buffer(OnFault::Return))
|
||||
.expect("no raise")
|
||||
.expect("a command buffer");
|
||||
let planes = Planes::<RtPlatform> {
|
||||
pipeline: &pipeline,
|
||||
arguments: &arguments,
|
||||
destination: &input,
|
||||
sources: [&source_buffer, &source_buffer],
|
||||
};
|
||||
assert_eq!(
|
||||
encode_planes::<RtPlatform>(&cb, &planes, &fills),
|
||||
None,
|
||||
"{what}"
|
||||
);
|
||||
cb.commit(OnFault::Return).expect("the commit");
|
||||
cb.wait_until_completed(OnFault::Return).expect("the wait");
|
||||
assert_eq!(cb.status(), CommandBufferStatus::COMPLETED, "{what}");
|
||||
// SAFETY: the input's host bytes, which the GPU wrote and the wait saw done.
|
||||
let written = unsafe {
|
||||
std::slice::from_raw_parts(input.contents().as_ptr::<u8>(), input_length as usize)
|
||||
};
|
||||
let coded_bytes = (u64::from(coded.0) * sample) as usize;
|
||||
for (fill, which) in fills.iter().zip(["luma", "chroma"]) {
|
||||
let expected = uploaded(&bytes, fill, coded_bytes);
|
||||
for row in 0..fill.plane.coded_rows as usize {
|
||||
let at = fill.at as usize + row * input_pitch as usize;
|
||||
let got = &written[at..at + coded_bytes];
|
||||
let want = &expected[row * coded_bytes..(row + 1) * coded_bytes];
|
||||
assert!(got == want, "{what}: {which} row {row}");
|
||||
let past = &written[at + coded_bytes..at + input_pitch as usize];
|
||||
assert!(
|
||||
past.iter().all(|&b| b == UNTOUCHED),
|
||||
"{what}: {which} row {row} past its coded bytes"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -14,7 +14,7 @@ crate, the traits between them, and how each is tested.
|
||||
| `codec` (`src/codec.rs`) | The codecs above the hardware, in plain Rust: H.264's and HEVC's syntax, order counts and DPB over an `Accelerator` that decodes the slice data, and the encoders' portable half: settings, GOP, parameter sets, slice headers and configuration records |
|
||||
| `vaapi` (`src/vaapi.rs`, Linux) | VA-API through libva, loaded at run time: the decoders and encoders on the codec module, the import check and zero copy ([vaapi.md](vaapi.md)) |
|
||||
| `nvidia` (`src/nvidia.rs`, Linux) | NVDEC and NVENC over the CUDA driver API, loaded at run time: the decoder of whole access units and the encoder ([nvidia.md](nvidia.md)) |
|
||||
| `paravirt` (`src/paravirt.rs`) | VideoToolbox's paravirtual protocol, the host's side: the `vtpv` messages an arm64 guest's VideoToolbox sends through the device's `VT_MESSAGE`, the decoder list and capabilities answered from the arm's decoders, the decoder sessions, each on a thread of its own over a backend that lands its pictures in the buffers the guest lends, and the encoder sessions, over a backend that encodes the source frames the guest lends (on VA-API, copied by the GPU from a buffer over their pages into the encoder's input surfaces, on NVENC into memory CUDA imported, which NVENC registers as input, else read through the host's view of the pages and uploaded), whose samples the session emits ([design.md](../graphics-kext/design.md), "Decided", 17) |
|
||||
| `paravirt` (`src/paravirt.rs`) | VideoToolbox's paravirtual protocol, the host's side: the `vtpv` messages an arm64 guest's VideoToolbox sends through the device's `VT_MESSAGE`, the decoder list and capabilities answered from the arm's decoders, the decoder sessions, each on a thread of its own over a backend that lands its pictures in the buffers the guest lends, and the encoder sessions, over a backend that encodes the source frames the guest lends (on VA-API, written by the GPU from a buffer over their pages into an input of the encoder's, memory of the runtime device's that the encoder's display imports, on NVENC into memory CUDA imported, which NVENC registers as input, else read through the host's view of the pages and uploaded), whose samples the session emits ([design.md](../graphics-kext/design.md), "Decided", 17) |
|
||||
|
||||
Its subcrate `crates/reims-vgpu-video/conformance` (`reims-vgpu-video-conformance`) is the test
|
||||
streams' readers and writers, which the examples use: an MP4 track's configuration record and
|
||||
|
||||
@@ -216,8 +216,11 @@ buffer of an encode session's process (reims-vgpu's `graphics/video_host/encode.
|
||||
- **The frame is encoded** on the session's encode thread (`reims-vgpu.graphics-video-encode`),
|
||||
in the order the encodes were taken, once the command buffer's waits are done. The runtime
|
||||
device's GPU copies its two planes, where they lie, in the surface's pages or its device
|
||||
caches, into the encoder's own input: a VA-API input surface exported as dma-bufs, or an
|
||||
exportable buffer CUDA imported, which NVENC registers and maps for the frame. Where the arm
|
||||
caches, into the encoder's own input: on VA-API a buffer of the runtime device's, a dma-buf
|
||||
the encoder's display imports as an input surface (on Linux; on Windows the arm answers no
|
||||
encoder, as the runtime imports no shared Direct3D 12 texture), or on NVENC an exportable
|
||||
buffer CUDA imported, which NVENC registers and maps for the frame. The margin past the
|
||||
picture to the coded size is written as the upload writes it. Where the arm
|
||||
declines that copy (said once a session), the planes are read as host bytes, in the surface's
|
||||
pages, or, for a plane in a device cache, in a staging buffer the GPU copies it into first, and
|
||||
the encoder's upload copies them. The encoder codes the same bytes either way.
|
||||
|
||||
Reference in new issue
Block a user