🐛 Fail a 4:4:4 picture whose GPU pass failed once submitted

A VideoToolbox decoder's 4:4:4 picture lands in the guest's surface through the
videoGather444 pass, on the NVIDIA arm and on the VA-API arm's XYUV route. The
gatherer answered a pass that failed once submitted as it answered a refusal
before anything was submitted. The caller then copied the picture into the
surface by the CPU, and the next picture's pass rewrote the same arguments
buffer and read the same scratch. Where the pass's wait failed (on the rt
platform, a lost device), the GPU may run the pass still: the CPU's copy and the
late pass could both write the surface, and a later picture's bytes could reach
it.

Gatherer::gather now answers Ungathered::Declined before anything is submitted,
and Ungathered::Failed after. A failed pass fails the picture as a malfunction,
with no copy of the CPU's. The gatherer keeps its arguments out of use, and the
decoder its scratch, while it lives, as gpu_copy and the VA-API fill keep
theirs; the next picture makes new ones.

What the guest sees: nothing on a live device, where the wait returns once the
pass is done. After a lost device, the picture's decode answers
kVTVideoDecoderMalfunctionErr, where a CPU copy raced the pass before.

Tests: a_pass_whose_wait_fails_keeps_its_arguments_out_of_use, on the stand-in
device with a scripted failed wait; and, ignored, for the NVIDIA arm
a_4_4_4_picture_whose_pass_fails_once_submitted_fails_and_its_scratch_goes and
for the XYUV route a_picture_whose_pass_fails_once_submitted_fails_and_its_
scratch_goes, through the gatherer's test hook, which fails a wait once its
pass is done.
This commit is contained in:
Anees Iqbal committed 2026-12-03 07:28:47 -08:00
1 parent 2c6ed20a20
commit 06cdbdc075
7 files changed
+424 -45

No files matched your search

+83 -12
View File
@@ -19,12 +19,19 @@
//! CPU's interleave of the picture read back writes (`nvidia`'s `interleave_planes`): each
//! plane's rows as far as both the picture's crop and the plane hold them, the chroma's in
//! whole Cb/Cr pairs, and nothing else of the surface. Then it is waited for.
//! - **Refusals** ([`gathers`]) come before anything is submitted, and the picture is then copied
//! by the CPU: a picture past 8 bits, a plane off a 32-bit word, a plane whose rows lie past the
//! - **Refusals** ([`gathers`], [`Ungathered::Declined`]) come before anything is submitted, and
//! the picture is then copied by the CPU: a picture past 8 bits, a plane off a 32-bit word, a plane whose rows lie past the
//! surface or the source, a value past 32 bits; the device's refusal of the kernel's pipeline,
//! a queue, a command buffer or a buffer of its arguments; and the platform's refusal of a
//! command of the pass (on the rt platform, metal2vulkan-runtime's refusal, counted under its
//! kind), which records nothing, its command buffer then never committed.
//! - **A pass that fails once submitted** ([`Ungathered::Failed`]), whose wait failed or which
//! ended in an error, fails the picture: no copy of the CPU's follows it. Where its wait failed
//! (on the rt platform, a lost device), the GPU may run the pass still, reading the source and
//! the arguments and writing the destination, so nothing else writes them meanwhile: the
//! gatherer keeps those arguments out of use while it lives, its next pass taking new ones, and
//! its caller keeps the source out of use. On a live device the wait returns once the pass is
//! done, and a guest sees none of this.
//! - **A new scratch's zeros** ([`zero_fill`]), which the decoders' scratches are made as: a fill
//! whose command the platform refuses commits nothing and leaves the buffer unzeroed
//! ([`Unzeroed::Refused`]), so the decoder keeps no scratch, the picture goes the CPU's way, and
@@ -265,6 +272,12 @@ pub(crate) struct Gatherer<P: Platform> {
/// The kernel's arguments, the luma plane's and the chroma's, which the CPU writes before each
/// gather: the last one was waited for.
arguments: Option<P::Buffer>,
/// The arguments of passes that failed once submitted, which the GPU may read still: kept out
/// of use while the gatherer lives (module doc).
failed: Vec<P::Buffer>,
/// The waits the test fails, each once its pass is done (`fail_next_wait`).
#[cfg(test)]
fail_waits: usize,
}
impl<P: Platform> Gatherer<P> {
@@ -274,9 +287,20 @@ impl<P: Platform> Gatherer<P> {
pipeline,
queue: None,
arguments: None,
failed: Vec::new(),
#[cfg(test)]
fail_waits: 0,
}
}
/// Fails the next gather's wait, once its pass is done, as a failed wait would: the test's
/// stand-in for a wait the platform answers with an error, its pass perhaps still running.
/// Its callers' tests, the Linux arms', are its only users.
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn fail_next_wait(&mut self) {
self.fail_waits += 1;
}
/// The device its passes run on.
pub(crate) fn device(&self) -> &P::Device {
&self.pipeline.device
@@ -305,14 +329,49 @@ impl<P: Platform> Gatherer<P> {
/// Writes `planes` from `source` into `destination`, both bound from their first byte, by the
/// kernel, and waits for it, on the gatherer's queue (module doc), counting the picture
/// ([`GATHERED_CODE`]). `Err` says why it was not written: nothing submitted, or a pass that
/// failed, after which the destination may hold part of the picture.
/// ([`GATHERED_CODE`]). `Err` says why it was not written: nothing submitted, for the CPU to
/// copy the picture, or a pass that failed once submitted, which fails it.
pub(crate) fn gather(
&mut self,
source: &P::Buffer,
destination: &P::Buffer,
planes: &[GatherPlane; 2],
) -> Result<(), String> {
) -> Result<(), Ungathered> {
let cb = (self.submit(source, destination, planes)).map_err(Ungathered::Declined)?;
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 GPU's pass failed {error}"))
}
Ok(()) => self.failed_by_test(),
};
if let Some(why) = failed {
self.failed.extend(self.arguments.take());
return Err(Ungathered::Failed(why));
}
reims_vgpu_vulkan::answer::count_kind(GATHERED_CODE);
Ok(())
}
/// The failure of its wait the test asked for (`fail_next_wait`, in a test), if any.
fn failed_by_test(&mut self) -> Option<String> {
#[cfg(test)]
if self.fail_waits > 0 {
self.fail_waits -= 1;
return Some("its wait: a wait the test failed".to_owned());
}
None
}
/// Encodes the pass of `planes` from `source` into `destination` and commits it, answering
/// its command buffer; `Err` says why nothing was submitted.
fn submit(
&mut self,
source: &P::Buffer,
destination: &P::Buffer,
planes: &[GatherPlane; 2],
) -> Result<P::CommandBuffer, String> {
let pipeline = self.pipeline.get()?;
if self.arguments.is_none() {
let device = &self.pipeline.device;
@@ -336,7 +395,7 @@ impl<P: Platform> Gatherer<P> {
let bytes = plane.bytes();
// SAFETY: the buffer's host bytes, two planes' arguments apart at least, hold each
// plane's 40 at its multiple of 256; and no GPU work reads them: the gather before was
// waited for.
// waited for, or failed once submitted and took its arguments out of use.
unsafe {
std::ptr::copy_nonoverlapping(
bytes.as_ptr(),
@@ -389,13 +448,25 @@ impl<P: Platform> Gatherer<P> {
.and_then(|encoded| recorded(encoded, "its compute end"))?;
cb.commit(OnFault::Return)
.map_err(|raise| format!("its commit: {raise}"))?;
(cb.wait_until_completed(OnFault::Return)).map_err(|raise| format!("its wait: {raise}"))?;
if cb.status() != CommandBufferStatus::COMPLETED {
let error = cb.error().map(|e| format!("{e:?}")).unwrap_or_default();
return Err(format!("the GPU's pass failed {error}"));
Ok(cb)
}
}
/// Why [`Gatherer::gather`] did not write its picture (module doc).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Ungathered {
/// Nothing was submitted: the caller copies the picture by the CPU.
Declined(String),
/// The pass failed once submitted, and the GPU may run it still: the picture fails, and the
/// caller keeps the pass's source out of use.
Failed(String),
}
impl std::fmt::Display for Ungathered {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Declined(why) | Self::Failed(why) => f.write_str(why),
}
reims_vgpu_vulkan::answer::count_kind(GATHERED_CODE);
Ok(())
}
}
+53 -1
View File
@@ -262,7 +262,9 @@ fn a_command_of_the_pass_the_platform_refuses_gathers_nothing() {
platform.script().push(DISPATCH, Step::Nil);
assert_eq!(
gatherer.gather(&source, &destination, &planes),
Err("a plane's dispatch: refused by the platform".to_owned())
Err(Ungathered::Declined(
"a plane's dispatch: refused by the platform".to_owned()
))
);
assert_eq!(
platform.call_log().count(DISPATCH),
@@ -280,6 +282,56 @@ fn a_command_of_the_pass_the_platform_refuses_gathers_nothing() {
assert_eq!(platform.call_log().count("commit"), 1);
}
/// A pass whose wait fails once it was submitted (on the rt platform, a lost device), which the
/// GPU may run still, reading its arguments, answers failed, apart from a refusal before
/// anything was submitted, for its picture to fail with no copy of the CPU's; its arguments are
/// kept out of use while the gatherer lives, and the next pass writes new ones and is waited for
/// as any.
#[test]
fn a_pass_whose_wait_fails_keeps_its_arguments_out_of_use() {
use reims_vgpu_vulkan::core::testkit::{CompleteOn, Step};
const NEW_BUFFER: &str = "newBufferWithLength:options:";
let platform = FakePlatform::new();
platform.world().set_auto_complete(Some(CompleteOn::Caller));
let (source, destination) = (
fake_buffer(&platform, 0x10000),
fake_buffer(&platform, 0x3000),
);
let good = [target(0, 64, 64, 48), target(0x1000, 128, 128, 48)];
let planes = gathers(planar(256, 48), (64, 48), &good, 0x3000).expect("the planes");
let pipeline = GatherPipeline::<FakePlatform>::new(&platform.device());
let mut gatherer = Gatherer::new(Arc::new(pipeline));
let made = platform.call_log().count(NEW_BUFFER);
platform.script().push(
"waitUntilCompleted",
Step::Raise {
name: "NSInternalInconsistencyException".to_owned(),
reason: "the device is lost".to_owned(),
},
);
let failed = gatherer.gather(&source, &destination, &planes);
assert!(
matches!(&failed, Err(Ungathered::Failed(why)) if why.starts_with("its wait: ")),
"{failed:?}"
);
assert_eq!(platform.call_log().count("commit"), 1, "the pass submitted");
assert!(gatherer.arguments.is_none(), "its arguments out of use");
assert_eq!(
gatherer.failed.len(),
1,
"and kept while the gatherer lives"
);
assert_eq!(gatherer.gather(&source, &destination, &planes), Ok(()));
assert_eq!(platform.call_log().count("commit"), 2);
assert_eq!(
platform.call_log().count(NEW_BUFFER) - made,
2,
"the first pass's arguments, then the next's"
);
assert_eq!(platform.call_log().count("waitUntilCompleted"), 2);
}
/// A new scratch's zero fill whose fill or end the platform refuses, recording nothing, commits
/// nothing and answers refused ([`Unzeroed::Refused`]), so that its caller keeps no unzeroed
/// scratch and asks again at the next picture; the next fill is made as any.
+28 -12
View File
@@ -89,7 +89,10 @@
//! scratch the device or CUDA does not make, which the decoder does not ask again, no buffer
//! over the surface, a plane off a 32-bit word, the kernel's pipeline refused, a command of
//! the pass or of a new scratch's zero fill that the platform refused (`gather::zero_fill`),
//! which keeps no scratch, for the next picture to make one again.
//! which keeps no scratch, for the next picture to make one again. A pass that fails once
//! submitted fails the picture, with no copy of the CPU's into the surface the GPU may write
//! still, and its scratch, which the GPU may read still, is kept out of use while the decoder
//! lives, the next 4:4:4 picture making another (`gather::Ungathered::Failed`).
//! - **VideoToolbox's paravirtual encoders** (`encode`'s `guest`): an arm64 guest's encode, of
//! each codec NVENC encodes a profile of, on an NVENC encoder of its own, each source frame read
//! from the IOSurface its kext lent: copied by the GPU into memory NVENC reads, as an x86
@@ -130,7 +133,7 @@ use super::decode::{
GraphicsVideo, GraphicsVideoSession, GuestDecoder, GuestEncoder, GuestOutput, PlanePages,
};
use super::decode_sizes::DecodeSizes;
use super::gather::{GatherPipeline, Gatherer, Planar, Unzeroed, gathers};
use super::gather::{GatherPipeline, Gatherer, Planar, Ungathered, Unzeroed, gathers};
use super::video_host::{
BackendError, CONVERTED_CODE, DecodeOutput, Extent, Failed, HostDecoder, HostEncodeSession,
HostPicture, HostVideoSession, Landing, OutputPlane, SourcePlane, picture_error,
@@ -788,6 +791,7 @@ impl<P: Platform> GraphicsVideo<P> for Shared<P> {
gpu: Arc::clone(&video.gpu),
gatherer: Gatherer::new(Arc::clone(&video.gathers)),
scratch: None,
failed: Vec::new(),
}),
None => Err("CUDA imports no exportable buffer of the device".to_owned()),
};
@@ -1145,6 +1149,9 @@ struct Gathers<P: Platform> {
gpu: Arc<Gpu>,
gatherer: Gatherer<P>,
scratch: Option<Scratch<P>>,
/// Scratches whose picture's pass failed once submitted, which the GPU may read still: kept
/// out of use while the decoder lives (module doc).
failed: Vec<Scratch<P>>,
}
/// A decoder's scratch of 4:4:4 pictures (module doc): an exportable buffer of the device's that
@@ -1303,7 +1310,7 @@ impl<P: Platform> NvGuestDecoder<P> {
let size = (target.width(), target.height());
let planes = target.planes();
let written = if four_four_four {
self.gather(&picture, size, &planes, output.buffer)
self.gather(&picture, size, &planes, output.buffer)?
} else {
let [luma, chroma] = planes.map(|plane| MemoryPlane {
memory: target.memory(),
@@ -1316,9 +1323,9 @@ impl<P: Platform> NvGuestDecoder<P> {
// inside its memory), which the guest's kext holds lent, its pages wired, until the
// host's `rels`, sent once this returns, and which nothing of the host's writes
// meanwhile; the registration the write keeps holds the view of its pages mapped.
unsafe { picture.write_into(size, luma, chroma, Box::new(())) }
unsafe { picture.write_into(size, luma, chroma, Box::new(())) }.map_err(video_error)?
};
match written.map_err(video_error)? {
match written {
Ok(()) => return Ok(true),
Err(why) => self.copied_because(why),
}
@@ -1350,16 +1357,17 @@ impl<P: Platform> NvGuestDecoder<P> {
/// Writes `picture`, a 4:4:4 one, into `planes` of the surface `buffer` lies over, by the GPU
/// (module doc): `size` of its crop copied within the GPU into the decoder's scratch, then
/// the kernel's pass from there into the surface. The outer `Err` is the picture's, as
/// `AnnexBPicture::write_4_4_4_into_device`'s; the inner says why it was not written so, for
/// the CPU to copy it: a refusal before anything was written, or a pass that failed.
/// the kernel's pass from there into the surface. The outer `Err` is the picture's:
/// `AnnexBPicture::write_4_4_4_into_device`'s, or a pass that failed once submitted, whose
/// scratch is then kept out of use (module doc). The inner says why it was not written so,
/// for the CPU to copy it: a refusal before the pass was submitted.
fn gather(
&mut self,
picture: &AnnexBPicture,
size: (u32, u32),
planes: &[TargetPlane; 2],
buffer: Option<&P::Buffer>,
) -> Result<Result<(), String>, reims_vgpu_video::nvidia::Error> {
) -> Result<Result<(), String>, VideoError> {
let route = match &mut self.gathers {
Ok(route) => route,
Err(why) => return Ok(Err(why.clone())),
@@ -1407,7 +1415,8 @@ impl<P: Platform> NvGuestDecoder<P> {
// decoder's own buffer, which nothing else writes: no guest message names it, and the
// kernel's last pass that read it was waited for; the import, which a late copy keeps,
// holds its memory.
let written = unsafe { picture.write_4_4_4_into_device(size, [y, cb, cr], Box::new(())) }?;
let written = unsafe { picture.write_4_4_4_into_device(size, [y, cb, cr], Box::new(())) }
.map_err(video_error)?;
if let Err(why) = written {
return Ok(Err(why));
}
@@ -1415,8 +1424,15 @@ impl<P: Platform> NvGuestDecoder<P> {
return Ok(Err(format!("the scratch's acquire: {why}")));
}
let source = scratch.buffer.clone_ref();
if let Err(why) = route.gatherer.gather(&source, surface, &passes) {
return Ok(Err(why));
match route.gatherer.gather(&source, surface, &passes) {
Ok(()) => {}
Err(Ungathered::Declined(why)) => return Ok(Err(why)),
Err(Ungathered::Failed(why)) => {
route.failed.extend(route.scratch.take());
return Err(VideoError::Malfunction(format!(
"the GPU's write of a 4:4:4 picture into its surface: {why}"
)));
}
}
self.gathered += 1;
Ok(Ok(()))
@@ -924,6 +924,106 @@ fn an_hevc_picture_lands_in_its_guest_format_as_the_software_decode_has_it() {
});
}
/// A 4:4:4 picture whose pass into the surface fails once submitted (the test fails the pass's
/// wait once it is done, as a lost device's wait fails, the pass perhaps still running) fails,
/// with no copy of the CPU's into the surface, and its scratch, which the pass read, is kept out
/// of use: the next picture is written by the GPU through a new one. The 8-bit 4:4:4 stream
/// `main444-360p` of the card test's ([`CARD_STREAMS`], in `RVG_NV_STREAMS`), in a `444v`
/// surface's pages, which a Shared buffer of the device's lies over.
#[test]
#[ignore = "needs an NVIDIA GPU and the card test's streams in RVG_NV_STREAMS: run on the NVIDIA host"]
fn a_4_4_4_picture_whose_pass_fails_once_submitted_fails_and_its_scratch_goes() {
use reims_vgpu_video::codec::hevc;
use reims_vgpu_vulkan::core::host::HostPtr;
use reims_vgpu_vulkan::core::platform::HostRange;
let dir = std::env::var_os("RVG_NV_STREAMS").expect("RVG_NV_STREAMS, the streams' directory");
let file = std::fs::read(std::path::Path::new(&dir).join("main444-360p.265"))
.expect("the 8-bit 4:4:4 stream");
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::Nvidia);
let runtime = crate::video::runtime::PlatformRuntime::of(&platform);
let gpu = super::super::video_choice::rt_nvidia_gpu(&device);
let video = NvidiaVideo::<RtPlatform>::new(&device, gpu, &runtime);
let video = Arc::new(video.expect("NVDEC on the device's GPU"));
assert!(video.imports.is_some(), "CUDA imports the device's buffers");
let (width, height) = (640, 360);
let format = PixelFormat::of(Chroma::Yuv444, 8, false).expect("a guest format");
let layout = pool_layout(format, (width, height), 0x400);
let rows = usize::try_from(height).expect("rows");
let end = layout.planes[1].offset + layout.planes[1].bytes_per_row * rows;
let len = (end + 1).next_multiple_of(PAGE);
let memory = PagesMemory {
life: MemoryLife::new(),
pages: Pages::new(len),
};
let keep = Arc::clone(&memory.pages);
// SAFETY: the pages stay allocated while the buffer's deallocator holds them.
let bytes =
unsafe { HostRange::new(HostPtr::from_ptr(memory.pages.first.as_ptr()), len as u64) };
let surface = (device.new_buffer_over_host_memory(
OnFault::Return,
bytes,
0,
Some(Box::new(move || drop(keep))),
))
.expect("no raise")
.expect("a buffer over the pages");
let output = GuestOutput {
layout,
memory: &memory,
buffer: Some(&surface),
};
let mut decoder = AnnexBDecoder::new(&video.gpu, AnnexBCodec::Hevc, &runtime);
decoder.lands_range_extensions();
let mut guest = NvGuestDecoder::<RtPlatform> {
decoder,
said: Vec::new(),
gathers: Ok(Gathers {
gpu: Arc::clone(&video.gpu),
gatherer: Gatherer::new(Arc::clone(&video.gathers)),
scratch: None,
failed: Vec::new(),
}),
gathered: 0,
};
let mut units = hevc::nal::access_units(&file).into_iter();
let mut next = |guest: &mut NvGuestDecoder<RtPlatform>| loop {
memory.pages.fill(UNTOUCHED);
let unit = units.next().expect("three pictures in the stream");
match guest.decode(&[], unit, &output) {
Ok(false) => continue,
landed => return landed,
}
};
assert_eq!(next(&mut guest), Ok(true), "the first picture");
assert_eq!(guest.gathered, 1, "written by the GPU");
let route = guest.gathers.as_mut().expect("the GPU's route");
assert!(route.scratch.is_some(), "the scratch it made");
route.gatherer.fail_next_wait();
let before = converted();
let failed = next(&mut guest);
assert!(
matches!(&failed, Err(VideoError::Malfunction(why)) if why.contains("its wait")),
"the second picture: {failed:?}"
);
assert_eq!(guest.said, Vec::<String>::new(), "no copy of the CPU's");
assert_eq!(converted(), before, "no interleave of the CPU's");
let route = guest.gathers.as_ref().expect("the route goes on");
assert!(route.scratch.is_none(), "the scratch out of use");
assert_eq!(route.failed.len(), 1, "kept while the decoder lives");
assert_eq!(next(&mut guest), Ok(true), "the third picture");
assert_eq!(guest.gathered, 2, "written by the GPU");
let route = guest.gathers.as_ref().expect("the route");
assert!(route.scratch.is_some(), "a new scratch");
assert_eq!(guest.said, Vec::<String>::new());
});
}
/// The CPU's copy of a picture read back lands each plane's rows at the surface's offset and
/// pitch, as many of each row's bytes as the plane's rows hold, and as many rows as both have,
/// leaving the bytes past each row as they were; a plane whose rows lie past the surface is
+3 -2
View File
@@ -1850,7 +1850,8 @@ impl<P: Platform> VaGuestDecoder<P> {
}
/// Writes `frame`, a 4:4:4 one, into `output`'s surface by the GPU (`xyuv`). The outer `Err`
/// is the frame's; the inner says why it was not written so, for the CPU's split.
/// is the frame's, or a pass that failed once submitted (`xyuv::Gathered::Failed`); the inner
/// says why it was not written so, for the CPU's split.
#[cfg(unix)]
fn gather(
&mut self,
@@ -1867,7 +1868,7 @@ impl<P: Platform> VaGuestDecoder<P> {
};
let gathered =
(route.land(frame, &self.imports, &planes, output.buffer)).map_err(video_error)?;
Ok(gathered.written())
gathered.written().map_err(VideoError::Malfunction)
}
/// On Windows, which makes no dma-buf of the driver's to write: the CPU splits each picture.
+31 -14
View File
@@ -22,12 +22,16 @@
//! back and split by the CPU, the reason logged once a decoder: no buffer over the surface, a
//! crop the kernel does not write (`gather::gathers`), the driver's decline of the scratch
//! (rows of a width whose bytes are not whole alignments, where it writes those alone; an odd
//! size past the decoded picture), a pass that failed or whose command the platform refused,
//! and the platform's refusal of a command of a new scratch's zero fill (`gather::zero_fill`),
//! which keeps no scratch, for the next picture to make one again. The device's refusal to make
//! the scratch, or to acquire it, ends the route for the decoder ([`Gathered::Ended`],
//! size past the decoded picture), a pass whose command the platform refused, and the
//! platform's refusal of a command of a new scratch's zero fill (`gather::zero_fill`), which
//! keeps no scratch, for the next picture to make one again. The device's refusal to make the
//! scratch, or to acquire it, ends the route for the decoder ([`Gathered::Ended`],
//! [`XyuvGathers::takes_pictures`]), whose later 4:4:4 surfaces are then handed with no buffer
//! over them.
//! - **A pass that fails once submitted** fails the picture ([`Gathered::Failed`]), with no split
//! of the CPU's into the surface the GPU may write still, and its scratch, which the GPU may
//! read still, is kept out of use while the decoder lives, the next picture making another
//! (`gather::Ungathered::Failed`).
//!
//! Each picture written so is counted (`video-pictures-gpu-gathered`, the gatherer's), and each
//! decoder logs at its end how many went so, and the time from the driver's write to the pass's
@@ -49,7 +53,7 @@ use reims_vgpu_vulkan::core::platform::resource::Buffer as _;
use reims_vgpu_vulkan::core::raise::OnFault;
use reims_vgpu_vulkan::core::sync::Mutex;
use super::super::gather::{GatherPipeline, Gatherer, Planar, Unzeroed, gathers};
use super::super::gather::{GatherPipeline, Gatherer, Planar, Ungathered, Unzeroed, gathers};
use super::{CacheBytes, CacheMemory, CacheOf, NAME, STORAGE_PRIVATE};
/// A decoder's route for its 4:4:4 pictures by the GPU, where the display's import check passed
@@ -78,15 +82,22 @@ pub(super) enum Gathered {
/// Not written, with why, nor any later picture of the decoder: the device refused the
/// scratch.
Ended(String),
/// Not written, with why: the pass failed once submitted, and the GPU may write the surface
/// still (module doc). The picture fails, with no split of the CPU's.
Failed(String),
}
impl Gathered {
/// `Ok` where the picture was written, else why not, for the log of the CPU's split.
pub(super) fn written(self) -> Result<(), String> {
/// `Ok(Ok)` where the picture was written; `Ok(Err)` says why not, for the log of the CPU's
/// split; `Err` says why the picture fails.
pub(super) fn written(self) -> Result<Result<(), String>, String> {
match self {
Self::Written => Ok(()),
Self::Declined(why) => Err(why),
Self::Ended(why) => Err(format!("the GPU's writes ended: {why}")),
Self::Written => Ok(Ok(())),
Self::Declined(why) => Ok(Err(why)),
Self::Ended(why) => Ok(Err(format!("the GPU's writes ended: {why}"))),
Self::Failed(why) => Err(format!(
"the GPU's write of a 4:4:4 picture into its surface: {why}"
)),
}
}
}
@@ -113,8 +124,9 @@ struct Scratch<P: Platform> {
pub(super) struct XyuvGathers<P: Platform> {
gatherer: Gatherer<P>,
scratch: Option<Scratch<P>>,
/// Scratches whose picture's write failed, which the driver may write still: kept out of use
/// while the decoder lives.
/// Scratches whose picture's write failed, which the driver may write still, or whose pass
/// failed once submitted, which the GPU may read still: kept out of use while the decoder
/// lives.
failed: Vec<Scratch<P>>,
/// Why the route ended ([`Gathered::Ended`]), after which it takes no picture.
ended: Option<String>,
@@ -212,8 +224,13 @@ impl<P: Platform> XyuvGathers<P> {
return Ok(self.end(format!("the scratch's acquire: {why}")));
}
let source = scratch.buffer.clone_ref();
if let Err(why) = self.gatherer.gather(&source, surface, &passes) {
return Ok(Gathered::Declined(why));
match self.gatherer.gather(&source, surface, &passes) {
Ok(()) => {}
Err(Ungathered::Declined(why)) => return Ok(Gathered::Declined(why)),
Err(Ungathered::Failed(why)) => {
self.failed.extend(self.scratch.take());
return Ok(Gathered::Failed(why));
}
}
let took = self.runtime.elapsed_since(start);
self.gathered += 1;
@@ -77,17 +77,22 @@ fn a_scratch_s_rows_are_its_pixels_on_the_target_alignment() {
}
/// A picture written by the GPU goes no further; one declined or ended is split by the CPU, its
/// reason logged, an ended route's saying so.
/// reason logged, an ended route's saying so; one whose pass failed once submitted fails, with
/// no split of the CPU's.
#[test]
fn a_picture_the_gpu_did_not_write_is_split_by_the_cpu_with_why() {
assert_eq!(Gathered::Written.written(), Ok(()));
assert_eq!(Gathered::Written.written(), Ok(Ok(())));
assert_eq!(
Gathered::Declined("an odd crop".to_owned()).written(),
Err("an odd crop".to_owned())
Ok(Err("an odd crop".to_owned()))
);
assert_eq!(
Gathered::Ended("no scratch".to_owned()).written(),
Err("the GPU's writes ended: no scratch".to_owned())
Ok(Err("the GPU's writes ended: no scratch".to_owned()))
);
assert_eq!(
Gathered::Failed("its wait: lost".to_owned()).written(),
Err("the GPU's write of a 4:4:4 picture into its surface: its wait: lost".to_owned())
);
}
@@ -242,6 +247,7 @@ fn a_4_4_4_picture_written_by_the_gpu_is_the_cpus_split() {
return false;
}
Gathered::Ended(why) => panic!("the route ended: {why}"),
Gathered::Failed(why) => panic!("the pass failed: {why}"),
}
let mut cpu = vec![UNTOUCHED; usize_of(len)];
let (y, uv) = cpu.split_at_mut(usize_of(chroma_at));
@@ -300,3 +306,119 @@ fn a_4_4_4_picture_written_by_the_gpu_is_the_cpus_split() {
assert_eq!(counted(), before + pictures as u64);
});
}
/// A 4:4:4 picture whose pass into the surface fails once submitted (the test fails the pass's
/// wait once it is done, as a lost device's wait fails, the pass perhaps still running) is
/// answered failed, for the picture to fail with no split of the CPU's, and its scratch, which
/// the pass read, is kept out of use: the next picture is written by the GPU through a new one.
/// The first three XYUV pictures of the HEVC 4:4:4 streams in `RVG_VA_STREAMS`'s directories, each
/// into a '444v' surface laid out as the test above lays it out. Where the import check refused
/// XYUV, the route is none and the test says so.
#[test]
#[ignore = "needs a VA-API GPU and HEVC 4:4:4 streams: run on the VA-API host"]
fn a_picture_whose_pass_fails_once_submitted_fails_and_its_scratch_goes() {
use reims_vgpu_video::vaapi::Display;
use reims_vgpu_vulkan::RtPlatform;
use super::super::tests::{UNTOUCHED, each_picture, usize_of, va_streams};
let streams = va_streams();
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,
crate::graphics::video_choice::tested_gpu::Arm::VaApi,
);
let gpu = device.host_gpu();
let node = reims_vgpu_vulkan::host_gpus::render_node_at(gpu.render, gpu.pci);
let node = node.expect("a render node");
let runtime = crate::video::runtime::PlatformRuntime::of(&platform);
let display = Display::open(&node, Arc::clone(&runtime)).expect("a VA display");
let pipeline = Arc::new(GatherPipeline::<RtPlatform>::new(&device));
let mut gathers = match route(&display.import_writes(), &pipeline, &runtime) {
Ok(gathers) => gathers,
Err(why) => {
eprintln!("no route by the GPU: {why}");
return;
}
};
let writes = GuestWrites::new(&display);
let mut seen = Vec::new();
let mut each = |stream: &std::path::Path, id: u64, frame: &Frame| -> bool {
if !frame.is_xyuv() || seen.len() == 3 {
return seen.len() == 3;
}
let (width, height) = (u64::from(frame.width()), u64::from(frame.height()));
let (luma_pitch, chroma_pitch) =
(width.next_multiple_of(16), (2 * width).next_multiple_of(16));
let luma_at = 32;
let chroma_at = (luma_at + luma_pitch * height).next_multiple_of(64);
let len = chroma_at + chroma_pitch * height;
let surface = (device.new_buffer_of_length(OnFault::Return, len, 0))
.expect("no raise")
.expect("a Shared buffer for the surface");
// SAFETY: the surface's `len` bytes, Shared, which no GPU work reaches yet.
unsafe {
std::slice::from_raw_parts_mut(surface.contents().as_ptr::<u8>(), usize_of(len))
}
.fill(UNTOUCHED);
let plane = |offset: u64, pitch: u64, row_bytes: u64| TargetPlane {
offset: usize_of(offset),
bytes_per_row: usize_of(pitch),
rows: u32::try_from(height).expect("rows"),
row_bytes: usize_of(row_bytes),
};
let planes = [
plane(luma_at, luma_pitch, width),
plane(chroma_at, chroma_pitch, 2 * width),
];
if seen.len() == 1 {
gathers.gatherer.fail_next_wait();
}
let gathered =
(gathers.land(frame, &writes, &planes, Some(&surface))).expect("the frame's write");
let at = format!("{} picture {id}", stream.display());
seen.push((
at,
gathered,
gathers.scratch.is_some(),
gathers.failed.len(),
));
true
};
let refused = each_picture(&display, &streams, 3, true, &mut each);
eprintln!("the pictures: {seen:?}; refused: {refused:?}");
assert_eq!(seen.len(), 3, "three XYUV pictures");
assert!(
matches!(&seen[0].1, Gathered::Written),
"{}: {:?}",
seen[0].0,
seen[0].1
);
assert!(
matches!(&seen[1].1, Gathered::Failed(why) if why.contains("its wait")),
"{}: {:?}",
seen[1].0,
seen[1].1
);
assert_eq!(
(seen[1].2, seen[1].3),
(false, 1),
"{}: the scratch out of use, kept while the decoder lives",
seen[1].0
);
assert!(
matches!(&seen[2].1, Gathered::Written),
"{}: {:?}",
seen[2].0,
seen[2].1
);
assert_eq!(
(seen[2].2, seen[2].3),
(true, 1),
"{}: a new scratch",
seen[2].0
);
});
}