diff --git a/crates/reims-vgpu/src/graphics/gather.rs b/crates/reims-vgpu/src/graphics/gather.rs index 0126291d2..629fd691c 100644 --- a/crates/reims-vgpu/src/graphics/gather.rs +++ b/crates/reims-vgpu/src/graphics/gather.rs @@ -25,13 +25,16 @@ //! 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 pass that fails once submitted** fails the picture: no copy of the CPU's follows it. +//! Where its wait returned and it ended in an error ([`Ungathered::Failed`]), the GPU is done +//! with it, and the next pass takes the same arguments and source. Where its wait failed +//! ([`Ungathered::Running`]; 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 (`super::video_host::OutOfUse`). +//! At a second such pass the gatherer ends ([`Ungathered::Ended`]): it keeps no second, takes +//! no later picture, and its caller's route ends, its later pictures going the CPU's way. 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 @@ -53,6 +56,8 @@ use reims_vgpu_vulkan::core::platform::types::{CommandBufferStatus, MtlSize, NsR use reims_vgpu_vulkan::core::platform::{Encoded, Platform}; use reims_vgpu_vulkan::core::raise::OnFault; +use super::video_host::OutOfUse; + /// The platform library's kernel that writes a plane of the surface (`shaders.metal`). const GATHER_KERNEL: &str = "videoGather444"; @@ -270,14 +275,18 @@ pub(crate) struct Gatherer { pipeline: Arc>, queue: Option, /// 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. + /// gather: the last one was waited for, or ended in an error. arguments: Option, - /// 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, + /// The arguments of a pass whose wait failed, which the GPU may read still, kept out of use + /// while the gatherer lives, and whether it ended at a second (module doc). + out_of_use: OutOfUse, /// The waits the test fails, each once its pass is done (`fail_next_wait`). #[cfg(test)] fail_waits: usize, + /// The passes the test fails, each once it is done, as one that ended in an error + /// (`fail_next_pass`). + #[cfg(test)] + fail_passes: usize, } impl Gatherer

{ @@ -287,9 +296,11 @@ impl Gatherer

{ pipeline, queue: None, arguments: None, - failed: Vec::new(), + out_of_use: OutOfUse::new(), #[cfg(test)] fail_waits: 0, + #[cfg(test)] + fail_passes: 0, } } @@ -301,6 +312,14 @@ impl Gatherer

{ self.fail_waits += 1; } + /// Fails the next gather's pass, once it is done, as one whose wait returned and which ended + /// in an error would: the test's stand-in for a pass the GPU failed and is done with. Its + /// callers' tests, the Linux arms', are its only users. + #[cfg(all(test, target_os = "linux"))] + pub(crate) fn fail_next_pass(&mut self) { + self.fail_passes += 1; + } + /// The device its passes run on. pub(crate) fn device(&self) -> &P::Device { &self.pipeline.device @@ -330,40 +349,68 @@ impl Gatherer

{ /// 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, for the CPU to - /// copy the picture, or a pass that failed once submitted, which fails it. + /// copy the picture, or a pass that failed once submitted, which fails it ([`Ungathered`]). pub(crate) fn gather( &mut self, source: &P::Buffer, destination: &P::Buffer, planes: &[GatherPlane; 2], ) -> Result<(), Ungathered> { + if let Some(why) = self.out_of_use.ended() { + return Err(Ungathered::Declined(format!( + "the GPU's passes ended: {why}" + ))); + } 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}")), + let waited = cb.wait_until_completed(OnFault::Return); + let failed = match waited.map_err(|raise| format!("its wait: {raise}")) { + Err(why) => Some(Err(why)), 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}")) + Some(Ok(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)); + match failed { + None => {} + // Its wait returned: the GPU is done with the pass, and the next takes its arguments. + Some(Ok(why)) => return Err(Ungathered::Failed(why)), + Some(Err(why)) => { + return Err(match self.out_of_use.park(&mut self.arguments, &why) { + Ok(()) => Ungathered::Running(why), + Err(_) => Ungathered::Ended(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 { + /// The failure the test asked for (`fail_next_wait`, `fail_next_pass`, in a test), if any: + /// `Err` a failed wait's, `Ok` a failed pass's, as [`Self::gather`] tells them. + fn failed_by_test(&mut self) -> Option> { #[cfg(test)] if self.fail_waits > 0 { self.fail_waits -= 1; - return Some("its wait: a wait the test failed".to_owned()); + return Some(Err("its wait: a wait the test failed".to_owned())); + } + #[cfg(test)] + if self.fail_passes > 0 { + self.fail_passes -= 1; + return Some(Ok( + "the GPU's pass failed: a pass the test failed".to_owned() + )); } None } + /// Whether it keeps the arguments of a pass whose wait failed out of use, and why it ended, + /// if it did (module doc). + #[cfg(test)] + pub(crate) fn out_of_use(&self) -> (bool, Option<&str>) { + (self.out_of_use.keeps(), self.out_of_use.ended()) + } + /// Encodes the pass of `planes` from `source` into `destination` and commits it, answering /// its command buffer; `Err` says why nothing was submitted. fn submit( @@ -395,7 +442,8 @@ impl Gatherer

{ 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, or failed once submitted and took its arguments out of use. + // waited for or ended in an error, or its wait failed and it took its arguments out of + // use (a second such ended the gatherer, which then submits nothing). unsafe { std::ptr::copy_nonoverlapping( bytes.as_ptr(), @@ -457,15 +505,23 @@ impl Gatherer

{ 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. + /// The pass's wait returned, and it ended in an error: the GPU is done with it, the picture + /// fails, and the caller uses the pass's source again. Failed(String), + /// The pass's wait failed, and the GPU may run it still: the picture fails, the gatherer keeps + /// its arguments out of use, and the caller keeps the pass's source out of use. + Running(String), + /// As [`Self::Running`], at a second such pass: the picture fails, the gatherer ends, keeping + /// its arguments where they lie, and the caller's route ends, its source kept where it lies. + Ended(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), + Self::Declined(why) | Self::Failed(why) | Self::Running(why) | Self::Ended(why) => { + f.write_str(why) + } } } } diff --git a/crates/reims-vgpu/src/graphics/gather/tests.rs b/crates/reims-vgpu/src/graphics/gather/tests.rs index c846cecd2..4bf4dc7c4 100644 --- a/crates/reims-vgpu/src/graphics/gather/tests.rs +++ b/crates/reims-vgpu/src/graphics/gather/tests.rs @@ -282,17 +282,17 @@ 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:"; +/// A rig of the gatherer's tests of a pass that fails once submitted: the stand-in device, a +/// source, a destination, the planes of a picture between them, and a gatherer. +#[allow(clippy::type_complexity)] // the rig's parts +fn failing_rig() -> ( + FakePlatform, + ::Buffer, + ::Buffer, + [GatherPlane; 2], + Gatherer, +) { let platform = FakePlatform::new(); - platform.world().set_auto_complete(Some(CompleteOn::Caller)); let (source, destination) = ( fake_buffer(&platform, 0x10000), fake_buffer(&platform, 0x3000), @@ -300,25 +300,42 @@ fn a_pass_whose_wait_fails_keeps_its_arguments_out_of_use() { 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::::new(&platform.device()); - let mut gatherer = Gatherer::new(Arc::new(pipeline)); + let gatherer = Gatherer::new(Arc::new(pipeline)); + (platform, source, destination, planes, gatherer) +} + +/// The stand-in device's answer to a wait on a lost device. +fn lost_wait() -> reims_vgpu_vulkan::core::testkit::Step { + reims_vgpu_vulkan::core::testkit::Step::Raise { + name: "NSInternalInconsistencyException".to_owned(), + reason: "the device is lost".to_owned(), + } +} + +const NEW_BUFFER: &str = "newBufferWithLength:options:"; + +/// 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 running, 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; + let (platform, source, destination, planes, mut gatherer) = failing_rig(); + platform.world().set_auto_complete(Some(CompleteOn::Caller)); 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(), - }, - ); + platform.script().push("waitUntilCompleted", lost_wait()); let failed = gatherer.gather(&source, &destination, &planes); assert!( - matches!(&failed, Err(Ungathered::Failed(why)) if why.starts_with("its wait: ")), + matches!(&failed, Err(Ungathered::Running(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, + gatherer.out_of_use(), + (true, None), "and kept while the gatherer lives" ); @@ -332,6 +349,93 @@ fn a_pass_whose_wait_fails_keeps_its_arguments_out_of_use() { assert_eq!(platform.call_log().count("waitUntilCompleted"), 2); } +/// A second pass whose wait fails ends the gatherer (module doc): it answers ended, for its +/// caller's route to end, keeps the one arguments buffer it kept out of use and the second where +/// it lies, and submits no later pass, answering each declined, saying why, with no buffer made: +/// passes whose waits keep failing hold two arguments buffers, however many come. +#[test] +fn a_second_pass_whose_wait_fails_ends_the_gatherer() { + use reims_vgpu_vulkan::core::testkit::CompleteOn; + let (platform, source, destination, planes, mut gatherer) = failing_rig(); + platform.world().set_auto_complete(Some(CompleteOn::Caller)); + let made = platform.call_log().count(NEW_BUFFER); + platform.script().push("waitUntilCompleted", lost_wait()); + platform.script().push("waitUntilCompleted", lost_wait()); + let first = gatherer.gather(&source, &destination, &planes); + assert!(matches!(&first, Err(Ungathered::Running(_))), "{first:?}"); + + let second = gatherer.gather(&source, &destination, &planes); + let Err(Ungathered::Ended(why)) = second else { + panic!("the second: {second:?}"); + }; + assert!(why.starts_with("its wait: "), "{why}"); + assert!( + gatherer.arguments.is_some(), + "the second's arguments where they lie" + ); + assert_eq!(gatherer.out_of_use(), (true, Some(why.as_str()))); + assert_eq!(platform.call_log().count("commit"), 2); + + for _ in 0..4 { + assert_eq!( + gatherer.gather(&source, &destination, &planes), + Err(Ungathered::Declined(format!( + "the GPU's passes ended: {why}" + ))) + ); + } + assert_eq!(platform.call_log().count("commit"), 2, "nothing submitted"); + assert_eq!( + platform.call_log().count(NEW_BUFFER) - made, + 2, + "two arguments buffers in all" + ); + assert_eq!(gatherer.out_of_use(), (true, Some(why.as_str()))); +} + +/// A pass whose wait returns and which ended in an error (the GPU failed it and is done with +/// it) answers failed, for its picture to fail with no copy of the CPU's, and keeps nothing out +/// of use: the next pass writes the same arguments buffer. Passes that fail so in a row keep +/// nothing and end nothing, and the next pass that completes writes its picture. +#[test] +fn a_pass_that_ends_in_an_error_takes_its_arguments_again() { + use crate::graphics::tests::completing; + let (platform, source, destination, planes, mut gatherer) = failing_rig(); + let made = platform.call_log().count(NEW_BUFFER); + completing( + &platform, + |_| true, + || { + for n in 0..3 { + let failed = gatherer.gather(&source, &destination, &planes); + assert!( + matches!(&failed, Err(Ungathered::Failed(why)) + if why.starts_with("the GPU's pass failed")), + "pass {n}: {failed:?}" + ); + assert!(gatherer.arguments.is_some(), "pass {n}: its arguments kept"); + assert_eq!(gatherer.out_of_use(), (false, None), "pass {n}"); + } + }, + ); + assert_eq!(platform.call_log().count("commit"), 3, "each submitted"); + assert_eq!(platform.call_log().count("waitUntilCompleted"), 3); + assert_eq!( + completing( + &platform, + |_| false, + || gatherer.gather(&source, &destination, &planes) + ), + Ok(()) + ); + assert_eq!(platform.call_log().count("commit"), 4); + assert_eq!( + platform.call_log().count(NEW_BUFFER) - made, + 1, + "one arguments buffer, written for each pass" + ); +} + /// 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. diff --git a/crates/reims-vgpu/src/graphics/nvidia.rs b/crates/reims-vgpu/src/graphics/nvidia.rs index 53157f172..56f56be33 100644 --- a/crates/reims-vgpu/src/graphics/nvidia.rs +++ b/crates/reims-vgpu/src/graphics/nvidia.rs @@ -91,8 +91,13 @@ //! 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. 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`). +//! still. Where its wait returned and it ended in an error, the GPU is done with it, and the +//! next 4:4:4 picture takes the same scratch (`gather::Ungathered::Failed`). Where its wait +//! failed, 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::Running`); at a second +//! such pass the decoder's GPU writes end, as at the scratch's refusal, its scratches kept +//! while it lives and its later 4:4:4 pictures copied by the CPU (`video_host::OutOfUse`), +//! counted as [`GATHERS_ENDED_CODE`]. //! - **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 @@ -136,7 +141,7 @@ use super::decode_sizes::DecodeSizes; 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, + HostPicture, HostVideoSession, Landing, OutOfUse, OutputPlane, SourcePlane, picture_error, }; mod encode; @@ -170,6 +175,12 @@ const MOST_IMPORTS: usize = 64; /// width rounded up to a multiple of this, as a cache's rows are where the driver writes them. const SCRATCH_PITCH: u64 = 256; +/// The code of a VideoToolbox decoder whose 4:4:4 writes by the GPU ended at a second pass whose +/// wait failed (module doc; on the rt platform, a lost device), its later 4:4:4 pictures copied +/// by the CPU. A failure path: counted, its first logged (docs/conventions.md, "Each degradation +/// is logged once per boot, then counted"). +pub(crate) const GATHERS_ENDED_CODE: &str = "video-nvdec-gathers-ended"; + /// The video of each platform device, by its registry ID, while one lives: an `NvidiaVideo` of /// the device's platform. type MadeVideos = Vec<(u64, Weak)>; @@ -791,7 +802,7 @@ impl GraphicsVideo

for Shared

{ gpu: Arc::clone(&video.gpu), gatherer: Gatherer::new(Arc::clone(&video.gathers)), scratch: None, - failed: Vec::new(), + out_of_use: OutOfUse::new(), }), None => Err("CUDA imports no exportable buffer of the device".to_owned()), }; @@ -1136,8 +1147,9 @@ struct NvGuestDecoder { decoder: AnnexBDecoder, /// The reasons its pictures were copied by the CPU, each logged once. said: Vec, - /// Its GPU writes of 4:4:4 pictures; `Err` says why it has none: CUDA imports no exportable - /// buffer of the device, or its scratch was refused. + /// Its GPU writes of 4:4:4 pictures, which end where its scratch is refused or a second pass's + /// wait fails (`Gathers::out_of_use`); `Err` says why it has none: CUDA imports no + /// exportable buffer of the device. gathers: Result, String>, /// Its 4:4:4 pictures the GPU wrote so. gathered: u64, @@ -1149,9 +1161,10 @@ struct Gathers { gpu: Arc, gatherer: Gatherer

, scratch: Option>, - /// 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>, + /// The scratch of a picture whose pass's wait failed, which the GPU may read still, kept out + /// of use while the decoder lives, and why its GPU writes ended, if they did: at the + /// scratch's refusal, or at a second such pass (module doc). + out_of_use: OutOfUse>, } /// A decoder's scratch of 4:4:4 pictures (module doc): an exportable buffer of the device's that @@ -1178,6 +1191,29 @@ impl Scratch

{ } impl Gathers

{ + /// Keeps the scratch out of use for `why`, a pass whose wait failed, which the GPU may run + /// still; or, where one is kept already or the gatherer `ended`, ends the decoder's GPU + /// writes, the scratch kept where it lies (module doc): counted ([`GATHERS_ENDED_CODE`]), the + /// first logged. Ended writes keep and end nothing more. + fn park(&mut self, why: &str, ended: bool) { + if self.out_of_use.ended().is_some() { + return; + } + let parked = match ended { + true => Err(self.out_of_use.end(why.to_owned()).to_owned()), + false => self.out_of_use.park(&mut self.scratch, why), + }; + if let Err(why) = parked { + reims_vgpu_vulkan::answer::count_kind(GATHERS_ENDED_CODE); + log::warn!( + kind:% = GATHERS_ENDED_CODE; + "hardware video: {NAME}: a second 4:4:4 pass whose wait failed: a VideoToolbox \ + decoder's 4:4:4 pictures are copied by the CPU from now on \ + ({GATHERS_ENDED_CODE}; the rest are counted): {why}" + ); + } + } + /// Makes the decoder's scratch for a picture of `width` by `height`, where it has none as /// large (module doc): `Ok(Some)` says why the platform refused its zeros, none kept, for the /// next picture's ask to make one again; `Err` says why none is made. @@ -1246,9 +1282,9 @@ impl GuestDecoder

for NvGuestDecoder

{ self.land(parameter_sets, au, output, None) } - /// Where CUDA imports the device's exportable buffers, and its scratch was not refused. + /// Where CUDA imports the device's exportable buffers, and its GPU writes have not ended. fn lands_4_4_4_by_gpu(&self) -> bool { - self.gathers.is_ok() + (self.gathers.as_ref()).is_ok_and(|route| route.out_of_use.ended().is_none()) } /// The picture's crop narrows to the region, which then lands as a whole picture does, by @@ -1359,8 +1395,9 @@ impl NvGuestDecoder

{ /// (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: /// `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. + /// scratch is then kept out of use where its wait failed, or the GPU writes end at a second + /// (module doc). The inner says why it was not written so, for the CPU to copy it: a refusal + /// before the pass was submitted, or the GPU writes' end. fn gather( &mut self, picture: &AnnexBPicture, @@ -1372,6 +1409,9 @@ impl NvGuestDecoder

{ Ok(route) => route, Err(why) => return Ok(Err(why.clone())), }; + if let Some(why) = route.out_of_use.ended() { + return Ok(Err(format!("the GPU's writes ended: {why}"))); + } let Some(surface) = buffer else { return Ok(Err("no buffer of the device's over the surface".to_owned())); }; @@ -1386,7 +1426,7 @@ impl NvGuestDecoder

{ Ok(None) => {} Ok(Some(refused)) => return Ok(Err(refused)), Err(why) => { - self.gathers = Err(why.clone()); + route.out_of_use.end(why.clone()); return Ok(Err(why)); } } @@ -1413,8 +1453,9 @@ impl NvGuestDecoder

{ }; // SAFETY: the scratch's planes lie apart, `pitch` times `rows` bytes each, in the // 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. + // kernel's last pass that read it was waited for or ended in an error (one whose wait + // failed took it out of use, or ended the GPU writes); 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(())) } .map_err(video_error)?; if let Err(why) = written { @@ -1424,15 +1465,24 @@ impl NvGuestDecoder

{ return Ok(Err(format!("the scratch's acquire: {why}"))); } let source = scratch.buffer.clone_ref(); - match route.gatherer.gather(&source, surface, &passes) { - Ok(()) => {} + let failed = match route.gatherer.gather(&source, surface, &passes) { + Ok(()) => None, 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}" - ))); + // The GPU is done with the pass: the next picture takes the scratch. + Err(Ungathered::Failed(why)) => Some(why), + Err(Ungathered::Running(why)) => { + route.park(&why, false); + Some(why) } + Err(Ungathered::Ended(why)) => { + route.park(&why, true); + Some(why) + } + }; + if let Some(why) = failed { + return Err(VideoError::Malfunction(format!( + "the GPU's write of a 4:4:4 picture into its surface: {why}" + ))); } self.gathered += 1; Ok(Ok(())) diff --git a/crates/reims-vgpu/src/graphics/nvidia/tests.rs b/crates/reims-vgpu/src/graphics/nvidia/tests.rs index c4ca31e36..b533f2af3 100644 --- a/crates/reims-vgpu/src/graphics/nvidia/tests.rs +++ b/crates/reims-vgpu/src/graphics/nvidia/tests.rs @@ -924,15 +924,26 @@ 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() { +/// The pictures a process counted under `code`, so far. +fn counted(code: &str) -> u64 { + (reims_vgpu_vulkan::answer::counted_kinds().into_iter()) + .find(|(counted, _)| *counted == code) + .map_or(0, |(_, n)| n) +} + +/// Runs `test` on a VideoToolbox decoder of the arm on the rt device's NVIDIA GPU, whose 4:4:4 +/// pictures the GPU writes, and `next`, which decodes the next picture of the 8-bit 4:4:4 stream +/// `main444-360p` of the card test's ([`CARD_STREAMS`], in `RVG_NV_STREAMS`) into a `444v` +/// surface's pages, which a Shared buffer of the device's lies over, the pages filled with +/// [`UNTOUCHED`] first, and answers how it landed. The stream holds as many pictures as `next` +/// is asked for. +#[allow(clippy::type_complexity)] // the decoder and its next picture's decode +fn with_a_4_4_4_decoder( + test: impl FnOnce( + &mut NvGuestDecoder, + &mut dyn FnMut(&mut NvGuestDecoder) -> Result, + ), +) { use reims_vgpu_video::codec::hevc; use reims_vgpu_vulkan::core::host::HostPtr; use reims_vgpu_vulkan::core::platform::HostRange; @@ -985,27 +996,43 @@ fn a_4_4_4_picture_whose_pass_fails_once_submitted_fails_and_its_scratch_goes() gpu: Arc::clone(&video.gpu), gatherer: Gatherer::new(Arc::clone(&video.gathers)), scratch: None, - failed: Vec::new(), + out_of_use: OutOfUse::new(), }), gathered: 0, }; let mut units = hevc::nal::access_units(&file).into_iter(); let mut next = |guest: &mut NvGuestDecoder| loop { memory.pages.fill(UNTOUCHED); - let unit = units.next().expect("three pictures in the stream"); + let unit = units.next().expect("a picture more in the stream"); match guest.decode(&[], unit, &output) { Ok(false) => continue, landed => return landed, } }; - assert_eq!(next(&mut guest), Ok(true), "the first picture"); + test(&mut guest, &mut next); + }); +} + +/// A 4:4:4 picture whose pass into the surface fails once submitted, its wait failing (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. At a +/// second such pass the decoder's GPU writes end: that picture fails as the first did, the one +/// scratch kept out of use stays the one, the second stays where it lies, the ending is counted +/// (`video-nvdec-gathers-ended`), the decoder no longer asks for a buffer over its 4:4:4 +/// surfaces, and its later pictures are copied by the CPU, saying why. +#[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_wait_fails_fails_and_a_second_ends_the_gpu_s_writes() { + with_a_4_4_4_decoder(|guest, next| { + assert_eq!(next(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); + let failed = next(guest); assert!( matches!(&failed, Err(VideoError::Malfunction(why)) if why.contains("its wait")), "the second picture: {failed:?}" @@ -1014,13 +1041,94 @@ fn a_4_4_4_picture_whose_pass_fails_once_submitted_fails_and_its_scratch_goes() 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!(route.out_of_use.keeps(), "kept while the decoder lives"); + assert_eq!(route.out_of_use.ended(), None); + assert!(guest.lands_4_4_4_by_gpu()); - assert_eq!(next(&mut guest), Ok(true), "the third picture"); + assert_eq!(next(guest), Ok(true), "the third picture"); assert_eq!(guest.gathered, 2, "written by the GPU"); - let route = guest.gathers.as_ref().expect("the route"); + let route = guest.gathers.as_mut().expect("the route"); assert!(route.scratch.is_some(), "a new scratch"); assert_eq!(guest.said, Vec::::new()); + route.gatherer.fail_next_wait(); + + let ended = counted(GATHERS_ENDED_CODE); + let failed = next(guest); + assert!( + matches!(&failed, Err(VideoError::Malfunction(why)) if why.contains("its wait")), + "the fourth picture: {failed:?}" + ); + assert_eq!(guest.said, Vec::::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, ended"); + assert!(route.scratch.is_some(), "the second scratch where it lies"); + assert!(route.out_of_use.keeps(), "one kept out of use"); + assert_eq!( + route.out_of_use.ended(), + Some("its wait: a wait the test failed") + ); + assert_eq!(counted(GATHERS_ENDED_CODE), ended + 1, "the ending counted"); + assert!( + !guest.lands_4_4_4_by_gpu(), + "no buffer over a 4:4:4 surface" + ); + + for n in 5..=6 { + assert_eq!(next(guest), Ok(true), "picture {n}"); + assert_eq!(guest.gathered, 2, "picture {n}: not by the GPU"); + } + assert_eq!(converted(), before + 2, "interleaved by the CPU"); + assert_eq!( + guest.said, + ["the GPU's writes ended: its wait: a wait the test failed"] + ); + let route = guest.gathers.as_ref().expect("the route, ended"); + assert!(route.scratch.is_some() && route.out_of_use.keeps()); + assert_eq!(counted(GATHERS_ENDED_CODE), ended + 1, "counted once"); + }); +} + +/// A 4:4:4 picture whose pass into the surface ends in an error once submitted, its wait +/// returning (the test fails the pass once it is done, as the GPU fails one it is done with), +/// fails, with no copy of the CPU's into the surface, and keeps nothing out of use: the GPU is +/// done with the pass, and the next picture is written through the same scratch. Failures so in +/// a row keep nothing, and end nothing. +#[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_ends_in_an_error_fails_and_its_scratch_is_taken_again() { + with_a_4_4_4_decoder(|guest, next| { + assert_eq!(next(guest), Ok(true), "the first picture"); + assert_eq!(guest.gathered, 1, "written by the GPU"); + let route = guest.gathers.as_ref().expect("the GPU's route"); + let made = Arc::clone(&route.scratch.as_ref().expect("the scratch it made").import); + let before = converted(); + for n in 2..=4 { + let route = guest.gathers.as_mut().expect("the route"); + route.gatherer.fail_next_pass(); + let failed = next(guest); + assert!( + matches!(&failed, Err(VideoError::Malfunction(why)) + if why.contains("the GPU's pass failed")), + "picture {n}: {failed:?}" + ); + let route = guest.gathers.as_ref().expect("the route goes on"); + let scratch = route.scratch.as_ref().expect("the scratch"); + assert!(Arc::ptr_eq(&scratch.import, &made), "picture {n}: the same"); + assert!(!route.out_of_use.keeps(), "picture {n}: nothing kept"); + assert_eq!(route.out_of_use.ended(), None, "picture {n}: nothing ended"); + assert!(guest.lands_4_4_4_by_gpu()); + } + assert_eq!(guest.said, Vec::::new(), "no copy of the CPU's"); + assert_eq!(converted(), before, "no interleave of the CPU's"); + + assert_eq!(next(guest), Ok(true), "the fifth picture"); + assert_eq!(guest.gathered, 2, "written by the GPU"); + let route = guest.gathers.as_ref().expect("the route"); + let scratch = route.scratch.as_ref().expect("the scratch"); + assert!( + Arc::ptr_eq(&scratch.import, &made), + "through the same scratch" + ); }); } diff --git a/crates/reims-vgpu/src/graphics/tests.rs b/crates/reims-vgpu/src/graphics/tests.rs index 305f1f4a9..12f98b613 100644 --- a/crates/reims-vgpu/src/graphics/tests.rs +++ b/crates/reims-vgpu/src/graphics/tests.rs @@ -7507,6 +7507,56 @@ pub(crate) fn eventually(mut done: impl FnMut() -> bool) -> bool { done() } +/// Runs `run` while a thread of the test's completes each command buffer committed on `p` +/// meanwhile, in commit order, as a GPU done with its work: the `n`th it completes (from 0) with +/// status Error and Metal's internal error (`MTLCommandBufferErrorInternal`, 1) where `errs(n)`, +/// else Completed, its wait returning either way. `p`'s world completes no buffer at its commit +/// (no auto-complete). The thread stops once `run` returns or panics. The video arms' tests of a +/// pass or copy that ended in an error use it. +pub(crate) fn completing( + p: &FakePlatform, + errs: impl Fn(usize) -> bool + Sync, + run: impl FnOnce() -> T, +) -> T { + use reims_vgpu_vulkan::core::platform::types::NsErrorText; + /// Stops the thread as `run` ends, a panic of its included: the scope joins the thread + /// before it hands the panic on. + struct Stop<'a>(&'a std::sync::atomic::AtomicBool); + impl Drop for Stop<'_> { + fn drop(&mut self) { + self.0.store(true, Ordering::SeqCst); + } + } + let world = Arc::clone(p.world()); + let done = std::sync::atomic::AtomicBool::new(false); + std::thread::scope(|scope| { + scope.spawn(|| { + let mut n = 0; + while !done.load(Ordering::SeqCst) { + for id in world.committed() { + let (status, error) = match errs(n) { + true => { + let error = NsErrorText { + domain: "MTLCommandBufferErrorDomain".to_owned(), + code: 1, + description: "Internal Error".to_owned(), + }; + (CommandBufferStatus::ERROR, Some(error)) + } + false => (CommandBufferStatus::COMPLETED, None), + }; + if world.complete(id, status, error, CompleteOn::Caller) { + n += 1; + } + } + std::thread::sleep(Duration::from_millis(1)); + } + }); + let _stop = Stop(&done); + run() + }) +} + unsafe extern "C" { /// The C library's `exit`, which runs the exit handlers ([`host_exit`]). #[link_name = "exit"] diff --git a/crates/reims-vgpu/src/graphics/vaapi/xyuv.rs b/crates/reims-vgpu/src/graphics/vaapi/xyuv.rs index f4eb96ff8..1e7e2287a 100644 --- a/crates/reims-vgpu/src/graphics/vaapi/xyuv.rs +++ b/crates/reims-vgpu/src/graphics/vaapi/xyuv.rs @@ -29,9 +29,17 @@ //! [`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`). +//! of the CPU's into the surface the GPU may write still. Where its wait returned and it ended +//! in an error, the GPU is done with it, and the next picture takes the same scratch +//! (`gather::Ungathered::Failed`). Where its wait failed, its scratch, which the GPU may read +//! still, is kept out of use while the decoder lives, the next picture making another +//! (`gather::Ungathered::Running`). So is the scratch of a driver's write that stalled past +//! its deadline, which the driver may finish still (the VA crate's `Error::Stalled`); a write +//! that failed otherwise has stopped, and the next picture takes its scratch. +//! - **One scratch at most is kept out of use** (`video_host::OutOfUse`): at a second pass whose +//! wait failed, or a second stalled write, the route ends for the decoder as at the scratch's +//! refusal, its picture failing all the same, and its later 4:4:4 surfaces handed with no +//! buffer over them, for the CPU's split: counted as [`ENDED_CODE`]. //! //! 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 @@ -54,8 +62,15 @@ use reims_vgpu_vulkan::core::raise::OnFault; use reims_vgpu_vulkan::core::sync::Mutex; use super::super::gather::{GatherPipeline, Gatherer, Planar, Ungathered, Unzeroed, gathers}; +use super::super::video_host::OutOfUse; use super::{CacheBytes, CacheMemory, CacheOf, NAME, STORAGE_PRIVATE}; +/// The code of a VideoToolbox decoder whose 4:4:4 writes by the GPU ended at a second scratch +/// kept out of use (module doc): a second pass whose wait failed (on the rt platform, a lost +/// device), or a second driver's write that stalled. A failure path: counted, its first logged +/// (docs/conventions.md, "Each degradation is logged once per boot, then counted"). +pub(crate) const ENDED_CODE: &str = "video-xyuv-gathers-ended"; + /// A decoder's route for its 4:4:4 pictures by the GPU, where the display's import check passed /// XYUV (module doc): the trial's own answer decides. `Err` says why there is none, for the log of /// the CPU's splits. @@ -83,7 +98,8 @@ pub(super) enum Gathered { /// 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. + /// still (module doc). The picture fails, with no split of the CPU's; at a second pass whose + /// wait failed, the route ends too ([`XyuvGathers::takes_pictures`]). Failed(String), } @@ -124,12 +140,11 @@ struct Scratch { pub(super) struct XyuvGathers { gatherer: Gatherer

, scratch: Option>, - /// 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>, - /// Why the route ended ([`Gathered::Ended`]), after which it takes no picture. - ended: Option, + /// The scratch of a picture whose driver's write stalled, which the driver may write still, + /// or whose pass's wait failed, which the GPU may read still, kept out of use while the + /// decoder lives; and why the route ended ([`Gathered::Ended`]), after which it takes no + /// picture: at the scratch's refusal, or at a second such picture (module doc). + out_of_use: OutOfUse>, /// Pictures written, and the time from the driver's write to the pass's end, on `runtime`'s /// clock (the video's runtime's). gathered: u64, @@ -145,8 +160,7 @@ impl XyuvGathers

{ Self { gatherer: Gatherer::new(pipeline), scratch: None, - failed: Vec::new(), - ended: None, + out_of_use: OutOfUse::new(), gathered: 0, runtime, total: Duration::ZERO, @@ -155,9 +169,9 @@ impl XyuvGathers

{ } /// Whether it takes the decoder's 4:4:4 pictures: until the device refuses its scratch - /// ([`Gathered::Ended`]). + /// ([`Gathered::Ended`]), or a second scratch would be kept out of use (module doc). pub(super) fn takes_pictures(&self) -> bool { - self.ended.is_none() + self.out_of_use.ended().is_none() } /// Writes `frame`, a 4:4:4 one, into `planes`, the luma and chroma planes of the surface @@ -171,7 +185,7 @@ impl XyuvGathers

{ surface: Option<&P::Buffer>, ) -> Result { let declined = |why: &str| Ok(Gathered::Declined(why.to_owned())); - if let Some(why) = &self.ended { + if let Some(why) = self.out_of_use.ended() { return Ok(Gathered::Declined(format!("the GPU's writes ended: {why}"))); } let Some(surface) = surface else { @@ -216,7 +230,11 @@ impl XyuvGathers

{ ))); } Err(error) => { - self.failed.extend(self.scratch.take()); + // A write past its deadline may still write the scratch; one that failed + // otherwise has stopped (`super::work_ended`). + if matches!(error, VaError::Stalled(_)) { + self.park(&error.to_string(), false); + } return Err(error); } } @@ -227,8 +245,14 @@ impl XyuvGathers

{ 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()); + // The GPU is done with the pass: the next picture takes the scratch. + Err(Ungathered::Failed(why)) => return Ok(Gathered::Failed(why)), + Err(Ungathered::Running(why)) => { + self.park(&why, false); + return Ok(Gathered::Failed(why)); + } + Err(Ungathered::Ended(why)) => { + self.park(&why, true); return Ok(Gathered::Failed(why)); } } @@ -239,10 +263,32 @@ impl XyuvGathers

{ Ok(Gathered::Written) } + /// Keeps the scratch out of use for `why`, a pass whose wait failed or a driver's write that + /// stalled, either perhaps running still; or, where one is kept already or the gatherer + /// `ended`, ends the route, the scratch kept where it lies (module doc): counted + /// ([`ENDED_CODE`]), the first logged. An ended route keeps and ends nothing more. + fn park(&mut self, why: &str, ended: bool) { + if self.out_of_use.ended().is_some() { + return; + } + let parked = match ended { + true => Err(self.out_of_use.end(why.to_owned()).to_owned()), + false => self.out_of_use.park(&mut self.scratch, why), + }; + if let Err(why) = parked { + reims_vgpu_vulkan::answer::count_kind(ENDED_CODE); + log::warn!( + kind:% = ENDED_CODE; + "hardware video: {NAME}: a second 4:4:4 picture whose write may run still: a \ + VideoToolbox decoder's 4:4:4 pictures are split by the CPU from now on \ + ({ENDED_CODE}; the rest are counted): {why}" + ); + } + } + /// Ends the route, for `why` ([`Gathered::Ended`]): its scratches are kept while it lives. fn end(&mut self, why: String) -> Gathered { - self.ended = Some(why.clone()); - Gathered::Ended(why) + Gathered::Ended(self.out_of_use.end(why).to_owned()) } /// Makes the decoder's scratch for a picture of an even `size`, where it has none as large diff --git a/crates/reims-vgpu/src/graphics/vaapi/xyuv/tests.rs b/crates/reims-vgpu/src/graphics/vaapi/xyuv/tests.rs index 65eea729d..f6e312eed 100644 --- a/crates/reims-vgpu/src/graphics/vaapi/xyuv/tests.rs +++ b/crates/reims-vgpu/src/graphics/vaapi/xyuv/tests.rs @@ -307,16 +307,117 @@ fn a_4_4_4_picture_written_by_the_gpu_is_the_cpus_split() { }); } -/// 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. +/// A scratch of the route's on the stand-in device, which no picture is written into: its +/// buffer the device's, its memory's descriptor `/dev/null`'s. +fn stand_in_scratch(platform: &FakePlatform) -> Scratch { + let buffer = (platform.device()) + .new_buffer_of_length(OnFault::Return, 256 * 2, STORAGE_PRIVATE) + .expect("no raise") + .expect("a buffer"); + let file = std::fs::File::open("/dev/null").expect("/dev/null"); + let life = MemoryLife::new(); + let bytes = CacheBytes { + memory: Arc::new(CacheMemory { + dma_buf: file.into(), + size: 256 * 2, + offset: 0, + cache: CacheOf::Buffer(buffer.clone_ref()), + last: Mutex::new(None), + }), + identity: life.identity(), + }; + Scratch { + pitch: 256, + rows: 2, + buffer, + bytes, + _life: life, + } +} + +/// The pictures a process counted under the route's ending ([`ENDED_CODE`]), so far. +fn ended_count() -> u64 { + (reims_vgpu_vulkan::answer::counted_kinds().into_iter()) + .find(|&(code, _)| code == ENDED_CODE) + .map_or(0, |(_, n)| n) +} + +/// The route keeps one scratch out of use at most (module doc): the first whose pass's wait +/// failed or whose driver's write stalled is kept, the route going on with no scratch; at a +/// second the route ends, the second scratch kept where it lies, the ending counted +/// ([`ENDED_CODE`]), and the decoder takes no later 4:4:4 picture by the GPU, as where the +/// device refused its scratch. Later failures end nothing more and keep nothing more. The +/// gatherer's own end ends the route at once. #[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() { +fn a_second_scratch_out_of_use_ends_the_route() { + let platform = Arc::new(FakePlatform::new()); + let mut gathers = route_on(&platform, Ok(WHOLE_ROWS)).expect("a route"); + let before = ended_count(); + gathers.scratch = Some(stand_in_scratch(&platform)); + gathers.park("its wait: lost", false); + assert!(gathers.scratch.is_none(), "the scratch out of use"); + assert!(gathers.out_of_use.keeps(), "kept while the decoder lives"); + assert!(gathers.takes_pictures(), "the route goes on"); + assert_eq!(ended_count(), before); + + gathers.scratch = Some(stand_in_scratch(&platform)); + gathers.park("its wait: lost again", false); + assert!( + gathers.scratch.is_some(), + "the second scratch where it lies" + ); + assert!(gathers.out_of_use.keeps(), "one kept"); + assert!(!gathers.takes_pictures(), "the route ended"); + assert_eq!(gathers.out_of_use.ended(), Some("its wait: lost again")); + assert_eq!(ended_count(), before + 1, "the ending counted"); + + for _ in 0..3 { + gathers.park("its wait: lost later", false); + gathers.park("the GPU's passes ended", true); + } + assert!(gathers.scratch.is_some() && gathers.out_of_use.keeps()); + assert_eq!(gathers.out_of_use.ended(), Some("its wait: lost again")); + assert_eq!(ended_count(), before + 1, "counted once"); + + let mut gathers = route_on(&platform, Ok(WHOLE_ROWS)).expect("a route"); + gathers.scratch = Some(stand_in_scratch(&platform)); + gathers.park("its wait: the gatherer's second", true); + assert!(gathers.scratch.is_some(), "the scratch where it lies"); + assert!(!gathers.out_of_use.keeps()); + assert!( + !gathers.takes_pictures(), + "the gatherer's end ends the route" + ); +} + +/// How the GPU tests below fail a picture's pass: not, at its wait, once the pass is done, as a +/// lost device's wait fails, the pass perhaps still running (`Gatherer::fail_next_wait`), or as +/// a pass that ended in an error, its wait returning (`Gatherer::fail_next_pass`). +#[derive(Clone, Copy, Debug)] +enum Fail { + Not, + Wait, + Pass, +} + +/// What a picture offered to the route came to, as the GPU tests below read it: its stream and +/// access unit, its answer, the route's scratch after it (its memory's address), whether a +/// scratch was kept out of use, and whether the route took pictures still. +#[derive(Debug)] +struct Offered { + at: String, + gathered: Gathered, + scratch: Option, + keeps: bool, + takes: bool, +} + +/// Offers a route on the rt device's GPU the first `fails.len()` 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, its pass failed as `fails` says; answers what each came to, and the +/// route's endings counted ([`ENDED_CODE`]) meanwhile. `None` where the import check refused +/// XYUV: no route, which it says. +fn offer_4_4_4(fails: &[Fail]) -> Option<(Vec, u64)> { use reims_vgpu_video::vaapi::Display; use reims_vgpu_vulkan::RtPlatform; @@ -340,14 +441,15 @@ fn a_picture_whose_pass_fails_once_submitted_fails_and_its_scratch_goes() { Ok(gathers) => gathers, Err(why) => { eprintln!("no route by the GPU: {why}"); - return; + return None; } }; let writes = GuestWrites::new(&display); - let mut seen = Vec::new(); + let before = ended_count(); + let mut seen: Vec = 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; + if !frame.is_xyuv() || seen.len() == fails.len() { + return seen.len() == fails.len(); } let (width, height) = (u64::from(frame.width()), u64::from(frame.height())); let (luma_pitch, chroma_pitch) = @@ -373,52 +475,136 @@ fn a_picture_whose_pass_fails_once_submitted_fails_and_its_scratch_goes() { plane(luma_at, luma_pitch, width), plane(chroma_at, chroma_pitch, 2 * width), ]; - if seen.len() == 1 { - gathers.gatherer.fail_next_wait(); + match fails[seen.len()] { + Fail::Not => {} + Fail::Wait => gathers.gatherer.fail_next_wait(), + Fail::Pass => gathers.gatherer.fail_next_pass(), } let gathered = (gathers.land(frame, &writes, &planes, Some(&surface))).expect("the frame's write"); - let at = format!("{} picture {id}", stream.display()); - seen.push(( - at, + seen.push(Offered { + at: format!("{} picture {id}", stream.display()), gathered, - gathers.scratch.is_some(), - gathers.failed.len(), - )); + scratch: (gathers.scratch.as_ref()).map(|s| Arc::as_ptr(&s.bytes.memory).addr()), + keeps: gathers.out_of_use.keeps(), + takes: gathers.takes_pictures(), + }); 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"); + let refused = each_picture(&display, &streams, fails.len(), true, &mut each); + for offered in &seen { + eprintln!("{}: {offered:?}", offered.at); + } + eprintln!("refused: {refused:?}"); + assert_eq!(seen.len(), fails.len(), "{} XYUV pictures", fails.len()); + Some((seen, ended_count() - before)) + }) +} + +/// A 4:4:4 picture whose pass into the surface fails once submitted, its wait failing (on the +/// rt platform, a lost device; the test fails the wait once the pass is done, 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. At a second such pass the route ends: that picture fails as the first did, +/// the scratch kept out of use stays the one, the second stays where it lies, the ending is +/// counted ([`ENDED_CODE`]), and the next picture is declined, for the CPU's split, saying why. +/// 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_wait_fails_fails_and_a_second_ends_the_route() { + use Fail::{Not, Wait}; + let Some((seen, ended)) = offer_4_4_4(&[Not, Wait, Not, Wait, Not]) else { + return; + }; + let failed = + |n: usize| matches!(&seen[n].gathered, Gathered::Failed(why) if why.contains("its wait")); + assert!( + matches!(&seen[0].gathered, Gathered::Written), + "{:?}", + seen[0] + ); + assert!( + seen[0].scratch.is_some() && !seen[0].keeps && seen[0].takes, + "{:?}", + seen[0] + ); + assert!(failed(1), "{:?}", seen[1]); + assert!( + seen[1].scratch.is_none() && seen[1].keeps && seen[1].takes, + "the scratch out of use, kept while the decoder lives: {:?}", + seen[1] + ); + assert!( + matches!(&seen[2].gathered, Gathered::Written), + "{:?}", + seen[2] + ); + assert!( + seen[2].scratch.is_some() && seen[2].keeps, + "a new scratch: {:?}", + seen[2] + ); + assert_ne!( + seen[2].scratch, seen[0].scratch, + "a new scratch: {:?}", + seen[2] + ); + assert!(failed(3), "{:?}", seen[3]); + assert!( + seen[3].scratch == seen[2].scratch && seen[3].keeps && !seen[3].takes, + "the route ended, its scratch where it lies, one kept: {:?}", + seen[3] + ); + assert!( + matches!(&seen[4].gathered, Gathered::Declined(why) + if why == "the GPU's writes ended: its wait: a wait the test failed"), + "{:?}", + seen[4] + ); + assert!(seen[4].scratch == seen[2].scratch && seen[4].keeps && !seen[4].takes); + assert_eq!(ended, 1, "the ending counted once"); +} + +/// A 4:4:4 picture whose pass into the surface ends in an error once submitted, its wait +/// returning (the test fails the pass once it is done, as the GPU fails one it is done with), is +/// answered failed, for the picture to fail with no split of the CPU's, and keeps nothing out of +/// use: the GPU is done with the pass, and the next picture takes the same scratch. Failures so +/// in a row keep nothing, and end nothing. 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_ends_in_an_error_fails_and_its_scratch_is_taken_again() { + use Fail::{Not, Pass}; + let Some((seen, ended)) = offer_4_4_4(&[Not, Pass, Pass, Not]) else { + return; + }; + assert!( + matches!(&seen[0].gathered, Gathered::Written), + "{:?}", + seen[0] + ); + let scratch = seen[0].scratch; + assert!(scratch.is_some(), "{:?}", seen[0]); + for picture in &seen[1..3] { assert!( - matches!(&seen[0].1, Gathered::Written), - "{}: {:?}", - seen[0].0, - seen[0].1 + matches!(&picture.gathered, Gathered::Failed(why) + if why.contains("the GPU's pass failed")), + "{picture:?}" ); assert!( - matches!(&seen[1].1, Gathered::Failed(why) if why.contains("its wait")), - "{}: {:?}", - seen[1].0, - seen[1].1 + picture.scratch == scratch && !picture.keeps && picture.takes, + "the same scratch, nothing kept, the route going on: {picture:?}" ); - 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 - ); - }); + } + assert!( + matches!(&seen[3].gathered, Gathered::Written), + "{:?}", + seen[3] + ); + assert!( + seen[3].scratch == scratch && !seen[3].keeps && seen[3].takes, + "{:?}", + seen[3] + ); + assert_eq!(ended, 0, "nothing ended"); } diff --git a/crates/reims-vgpu/src/graphics/video_host.rs b/crates/reims-vgpu/src/graphics/video_host.rs index 65189d945..88e8682d0 100644 --- a/crates/reims-vgpu/src/graphics/video_host.rs +++ b/crates/reims-vgpu/src/graphics/video_host.rs @@ -153,6 +153,13 @@ pub(crate) const TEARDOWN_WAIT: Duration = Duration::from_secs(10); #[cfg(unix)] pub(crate) const STALL_HOLD: Duration = Duration::from_secs(10); +/// The code of a host video session whose staging ended (`Stage::copy_with_caches`): a second +/// copy into or out of its device caches whose wait failed (on the rt platform, a lost device), +/// after which each later picture or frame that stages a plane fails. A failure path: counted, +/// its first logged (docs/conventions.md, "Each degradation is logged once per boot, then +/// counted"). +pub(crate) const STAGING_ENDED_CODE: &str = "video-staging-ended"; + /// `MTLResourceStorageModeShared`: the staging buffers' storage, host bytes the GPU reads. const STORAGE_SHARED: u64 = 0; @@ -784,15 +791,71 @@ fn staged_len(p: &OutputPlane

) -> u64 { plane_end(0, p.bytes_per_row, p.rows_held, p.row_bytes).unwrap_or(0) } +/// What a route of GPU work keeps out of use of work that may run still: the buffer of a pass or +/// copy whose wait failed once it was committed (on the rt platform, a lost device), which the +/// GPU may read or write still, so that nothing else writes or reads it meanwhile. It keeps one +/// such buffer at most, while the route's owner lives; at a second, the route ends instead +/// ([`Self::park`]), the second buffer left where the route holds it and used no more. A GPU +/// that keeps failing so holds two such buffers, not one more a picture. A pass or copy whose +/// wait returned and which ended in an error is done: its buffer is used again, and nothing is +/// kept. The staging buffers of the host's video sessions ([`Stage`]), the 4:4:4 gatherer's +/// arguments (`super::gather`) and the decoders' 4:4:4 scratches (`super::nvidia`, +/// `super::vaapi`'s `xyuv`) are kept so. +pub(crate) struct OutOfUse { + /// The buffer kept out of use. + kept: Option, + /// Why the route ended, after which it takes no work. + ended: Option, +} + +impl OutOfUse { + /// Nothing kept, the route going on. + pub(crate) const fn new() -> Self { + Self { + kept: None, + ended: None, + } + } + + /// Takes `slot`'s buffer out of use for `why`, its work perhaps running still: kept, where + /// none is kept yet; else the route ends for `why` ([`Self::end`]), the buffer left in `slot`, + /// which the route uses no more, and `Err` says why the route ended. + pub(crate) fn park(&mut self, slot: &mut Option, why: &str) -> Result<(), String> { + if self.kept.is_none() && self.ended.is_none() { + self.kept = slot.take(); + return Ok(()); + } + Err(self.end(why.to_owned()).to_owned()) + } + + /// Ends the route for `why`, where it has not ended (the first reason stays); answers why it + /// ended. What it keeps, and what its owner holds, stay while the owner lives. + pub(crate) fn end(&mut self, why: String) -> &str { + self.ended.get_or_insert(why) + } + + /// Why the route ended, if it did. + pub(crate) fn ended(&self) -> Option<&str> { + self.ended.as_deref() + } + + /// Whether a buffer is kept out of use. + #[cfg(test)] + pub(crate) fn keeps(&self) -> bool { + self.kept.is_some() + } +} + /// What the landing thread keeps from one picture to the next: the staging buffer and the queue /// its copies into device caches go on, each made at the first picture that needs it. struct Stage { device: P::Device, queue: Option, buffer: Option, - /// Staging buffers whose copy failed once committed, which the GPU may read or write still: - /// kept out of use while the session lives ([`Self::copy_with_caches`]). - failed: Vec, + /// The staging buffer of a copy whose wait failed once committed, which the GPU may read or + /// write still, and whether the session's staging ended at a second + /// ([`Self::copy_with_caches`]). + out_of_use: OutOfUse, /// A copy of a picture into its output's caches was not made since the landing last took it /// ([`Self::take_unmade`]): the platform made no blit encoder for it, or refused a staging /// copy ([`Self::copy_with_caches`]). @@ -889,8 +952,11 @@ impl Stage

{ } /// The staging buffer, of at least `len` bytes: the last one where it is that long, else a - /// new one. + /// new one; none once the session's staging ended ([`Self::copy_with_caches`]). fn buffer_of(&mut self, len: u64) -> Result<&P::Buffer, BackendError> { + if let Some(why) = self.out_of_use.ended() { + return Err(format!("no staging buffer: the session's staging ended: {why}").into()); + } let kept = self.buffer.take().filter(|b| b.length() >= len); let buffer = match kept { Some(buffer) => buffer, @@ -934,12 +1000,17 @@ impl Stage

{ /// the command buffer is not committed, and the picture fails to land, or the frame fails. /// The process's first refused copy into the caches is logged at warn, as a staging copy's. /// - /// **A copy that fails once committed**, whose wait failed or which ended in an error, answers - /// an error too, and its staging buffer is kept out of use while the session lives, the next - /// copy staging in a new one: where the wait failed (on the rt platform, a lost device), the - /// GPU may run the copy still, reading the staging buffer into the caches or writing it out - /// of them, so no later picture or frame stages its bytes there. On a live device the wait - /// returns once the copy is done, and a guest sees none of this. + /// **A copy that fails once committed** answers an error too. Where its wait returned and it + /// ended in an error, the GPU is done with it, and the next copy stages in the same buffer. + /// Where its wait failed (on the rt platform, a lost device), the GPU may run the copy still, + /// reading the staging buffer into the caches or writing it out of them, so no later picture + /// or frame stages its bytes there: the buffer is kept out of use while the session lives, + /// the next copy staging in a new one ([`OutOfUse`]). At a second such copy the session's + /// staging ends: its buffer is kept where it lies, no new one is made, and each later picture + /// or frame that stages a plane fails ([`Self::buffer_of`]), a picture counted as a failure + /// to land, as it would fail on the lost device; the ending is counted + /// ([`STAGING_ENDED_CODE`]). On a live device the wait returns once the copy is done, and a + /// guest sees none of this. fn copy_with_caches( &mut self, luma: &OutputPlane

, @@ -948,6 +1019,9 @@ impl Stage

{ into: bool, ) -> Result<(), BackendError> { let way = if into { "into" } else { "out of" }; + if let Some(why) = self.out_of_use.ended() { + return Err(format!("the copy {way} a device cache: the staging ended: {why}").into()); + } let fault = |what: &str, raise: Raise| format!("the copy {way} a device cache: {what}: {raise}"); let queue = (self.queue()) @@ -1091,18 +1165,23 @@ impl Stage

{ .go_on(); cb.commit(OnFault::Return) .map_err(|r| fault("its commit", r))?; - let failed = match cb.wait_until_completed(OnFault::Return) { - Err(raise) => Some(fault("its wait", raise)), - Ok(()) if cb.status() != CommandBufferStatus::COMPLETED => { - let error = cb.error().map(|e| format!("{e:?}")).unwrap_or_default(); - Some(format!("the copy {way} a device cache failed {error}")) + if let Err(raise) = cb.wait_until_completed(OnFault::Return) { + let failed = fault("its wait", raise); + if let Err(why) = self.out_of_use.park(&mut self.buffer, &failed) { + reims_vgpu_vulkan::answer::count_kind(STAGING_ENDED_CODE); + log::warn!( + kind:% = STAGING_ENDED_CODE; + "hardware video: a second copy {way} a device cache whose wait failed: the \ + session stages no more pictures or frames ({STAGING_ENDED_CODE}; the rest \ + are counted): {why}" + ); } - Ok(()) => None, - }; - if let Some(failed) = failed { - self.failed.extend(self.buffer.take()); return Err(failed.into()); } + if cb.status() != CommandBufferStatus::COMPLETED { + let error = cb.error().map(|e| format!("{e:?}")).unwrap_or_default(); + return Err(format!("the copy {way} a device cache failed {error}").into()); + } Ok(()) } } @@ -1513,7 +1592,7 @@ impl HostVideoSession

{ device: device.clone_ref(), queue: None, buffer: None, - failed: Vec::new(), + out_of_use: OutOfUse::new(), unmade: false, }; let landing = { diff --git a/crates/reims-vgpu/src/graphics/video_host/encode.rs b/crates/reims-vgpu/src/graphics/video_host/encode.rs index bd444ed4e..16cc61350 100644 --- a/crates/reims-vgpu/src/graphics/video_host/encode.rs +++ b/crates/reims-vgpu/src/graphics/video_host/encode.rs @@ -53,8 +53,8 @@ use zerocopy::IntoBytes; use super::super::decode::{Decoded, GraphicsVideoSession, VideoDecode, VideoEncode, op_fault}; use super::{ - BackendError, FAILURES_LOGGED, OutputPlane, SourcePlane, Stage, Staged, TEARDOWN_WAIT, - output_plane_of, plane_end, + BackendError, FAILURES_LOGGED, OutOfUse, OutputPlane, SourcePlane, Stage, Staged, + TEARDOWN_WAIT, output_plane_of, plane_end, }; /// One frame a backend's encoder takes ([`HostEncoder::encode`]). @@ -445,7 +445,7 @@ impl HostEncodeSession

{ device: device.clone_ref(), queue: None, buffer: None, - failed: Vec::new(), + out_of_use: OutOfUse::new(), unmade: false, }; let thread = { diff --git a/crates/reims-vgpu/src/graphics/video_host/tests.rs b/crates/reims-vgpu/src/graphics/video_host/tests.rs index 2e4ec0aa1..d64cb4c13 100644 --- a/crates/reims-vgpu/src/graphics/video_host/tests.rs +++ b/crates/reims-vgpu/src/graphics/video_host/tests.rs @@ -964,6 +964,225 @@ fn a_copy_into_caches_whose_wait_fails_keeps_its_staging_buffer_out_of_use() { drop(s); } +/// What a route keeps out of use ([`OutOfUse`]) is one buffer at most: the first parked is kept, +/// taken from its slot; at a second the route ends, for that one's reason, the buffer left in +/// its slot; later parks end nothing more and keep nothing more, the first reason staying, and +/// an end of another kind keeps the first reason too. +#[test] +fn a_route_keeps_one_buffer_out_of_use_and_ends_at_a_second() { + let mut out = OutOfUse::new(); + assert_eq!((out.keeps(), out.ended()), (false, None)); + let mut slot = Some(1); + assert_eq!(out.park(&mut slot, "its wait: lost"), Ok(())); + assert_eq!(slot, None, "taken out of use"); + assert_eq!((out.keeps(), out.ended()), (true, None)); + + let mut slot = Some(2); + assert_eq!( + out.park(&mut slot, "its wait: lost again"), + Err("its wait: lost again".to_owned()) + ); + assert_eq!(slot, Some(2), "left where the route holds it"); + assert_eq!(out.ended(), Some("its wait: lost again")); + for n in 3..8 { + let mut slot = Some(n); + assert_eq!( + out.park(&mut slot, "its wait: lost later"), + Err("its wait: lost again".to_owned()) + ); + assert_eq!(slot, Some(n)); + } + assert_eq!(out.end("refused".to_owned()), "its wait: lost again"); + assert_eq!(out.kept, Some(1), "the first alone kept"); + + let mut refused = OutOfUse::::new(); + assert_eq!(refused.end("no scratch".to_owned()), "no scratch"); + let mut slot = Some(1); + assert_eq!( + refused.park(&mut slot, "its wait: lost"), + Err("no scratch".to_owned()) + ); + assert_eq!( + (slot, refused.keeps()), + (Some(1), false), + "an ended route keeps none" + ); +} + +/// A stage on the stand-in device, its auto-completion `auto`, and an output of two planes in a +/// device cache, which a picture lands in staged. +fn staging_rig(auto: Option) -> (FakePlatform, Stage

, DecodeOutput

, Log) { + let p = FakePlatform::new(); + p.world().set_auto_complete(auto); + let stage = Stage { + device: p.device(), + queue: None, + buffer: None, + out_of_use: OutOfUse::new(), + unmade: false, + }; + let bitstream = buffer(&p, 4096, STORAGE_SHARED); + let cache = buffer(&p, 16384, PRIVATE); + let output = DecodeOutput::of(&decode(&bitstream, &[], planes(&cache, &cache, 128))).unwrap(); + (p, stage, output, Log::default()) +} + +/// The stand-in device's answer to a wait on a lost device. +fn lost_wait() -> reims_vgpu_vulkan::core::testkit::Step { + reims_vgpu_vulkan::core::testkit::Step::Raise { + name: "NSInternalInconsistencyException".to_owned(), + reason: "the device is lost".to_owned(), + } +} + +const NEW_BUFFER: &str = "newBufferWithLength:options:"; + +/// A second copy into the caches whose wait fails ends the session's staging +/// (`Stage::copy_with_caches`): the first's staging buffer is kept out of use, the second's +/// stays where it lies, the ending is counted (`video-staging-ended`), and each later picture +/// that stages a plane fails at once, with no staging buffer made and no copy: copies whose +/// waits keep failing hold two staging buffers, however many pictures come. +#[test] +fn a_second_copy_into_caches_whose_wait_fails_ends_the_staging() { + let (p, mut stage, output, log) = staging_rig(Some(CompleteOn::Caller)); + let counted = || { + (reims_vgpu_vulkan::answer::counted_kinds().into_iter()) + .find(|&(code, _)| code == STAGING_ENDED_CODE) + .map_or(0, |(_, n)| n) + }; + let (made, ended) = (p.call_log().count(NEW_BUFFER), counted()); + p.script().push("waitUntilCompleted", lost_wait()); + p.script().push("waitUntilCompleted", lost_wait()); + let first = land_in(Picture::Fill(1, Arc::clone(&log)), &output, &mut stage); + assert!( + first + .as_ref() + .is_err_and(|e| e.to_string().contains("its wait")), + "{first:?}" + ); + assert!(stage.buffer.is_none(), "its staging buffer out of use"); + assert!(stage.out_of_use.keeps()); + assert_eq!(stage.out_of_use.ended(), None); + assert_eq!(counted(), ended); + + let second = land_in(Picture::Fill(2, Arc::clone(&log)), &output, &mut stage); + assert!( + second + .as_ref() + .is_err_and(|e| e.to_string().contains("its wait")), + "{second:?}" + ); + assert!(stage.buffer.is_some(), "the second's where it lies"); + assert!(stage.out_of_use.keeps(), "one kept"); + let why = stage + .out_of_use + .ended() + .expect("the staging ended") + .to_owned(); + assert!(why.contains("its wait"), "{why}"); + assert_eq!(counted(), ended + 1, "the ending counted"); + let copies = p.call_log().calls_to(COPY).len(); + assert_eq!(copies, 4, "two pictures' copies, committed"); + + for n in 3..6 { + let later = land_in(Picture::Fill(n, Arc::clone(&log)), &output, &mut stage); + let said = format!("no staging buffer: the session's staging ended: {why}"); + assert!( + later.as_ref().is_err_and(|e| e.to_string() == said), + "picture {n}: {later:?}" + ); + } + assert_eq!(p.call_log().calls_to(COPY).len(), copies, "no copy"); + assert_eq!(p.call_log().count("commit"), 2, "nothing committed"); + assert_eq!( + p.call_log().count(NEW_BUFFER) - made, + 2, + "two staging buffers in all" + ); + assert_eq!(counted(), ended + 1, "counted once"); +} + +/// A copy into the caches whose wait returns and which ended in an error (the GPU failed it and +/// is done with it) fails its picture's landing and keeps nothing out of use: the next picture +/// stages in the same buffer. Copies that fail so in a row keep nothing and end nothing, and the +/// next copy that completes lands its picture. +#[test] +fn a_copy_into_caches_that_ends_in_an_error_stages_in_its_buffer_again() { + use crate::graphics::tests::completing; + let (p, mut stage, output, log) = staging_rig(None); + let made = p.call_log().count(NEW_BUFFER); + completing( + &p, + |_| true, + || { + for n in 1..4 { + let failed = land_in(Picture::Fill(n, Arc::clone(&log)), &output, &mut stage); + assert!( + failed + .as_ref() + .is_err_and(|e| e.to_string().contains("failed")), + "picture {n}: {failed:?}" + ); + assert!( + stage.buffer.is_some(), + "picture {n}: its staging buffer kept" + ); + assert!(!stage.out_of_use.keeps(), "picture {n}: nothing out of use"); + assert_eq!(stage.out_of_use.ended(), None, "picture {n}"); + } + }, + ); + let landed = completing( + &p, + |_| false, + || land_in(Picture::Fill(4, Arc::clone(&log)), &output, &mut stage), + ); + assert_eq!(landed.unwrap(), Way::Staged); + let copies = p.call_log().calls_to(COPY); + assert_eq!(copies.len(), 8, "four pictures' copies"); + assert!( + copies.iter().all(|c| c.args[0] == copies[0].args[0]), + "each staged in one buffer" + ); + assert_eq!( + p.call_log().count(NEW_BUFFER) - made, + 1, + "one staging buffer" + ); +} + +/// What the guest sees of a session whose staging ended: each later picture that stages a plane +/// fails to land, its value signalled with its command buffer failing, as a picture whose copy +/// failed does, counted as a failure to land and handed failed; the session goes on. +#[test] +fn a_session_whose_staging_ended_fails_each_later_staged_picture() { + let p = FakePlatform::new(); + p.world().set_auto_complete(Some(CompleteOn::Caller)); + let log = Log::default(); + let s = session(&p, vec![], &log); + let bitstream = buffer(&p, 4096, STORAGE_SHARED); + let cache = buffer(&p, 16384, PRIVATE); + p.script().push("waitUntilCompleted", lost_wait()); + p.script().push("waitUntilCompleted", lost_wait()); + for value in 1..=4 { + let failed = (s.decode(&decode(&bitstream, &[], planes(&cache, &cache, 128)))).unwrap(); + assert_eq!(failed.value, value); + assert!(event_of(&s).wait_until_signaled_value(value, 10_000)); + assert!( + failed.landed.as_deref().is_some_and(Landed::failed), + "picture {value}: its command buffer completes as a picture's that did not land" + ); + } + assert_eq!(s.counts.lock().failed, 4); + assert_eq!(s.counts.lock().unmade, 0, "none counted as unmade"); + assert_eq!( + p.call_log().calls_to(COPY).len(), + 4, + "the first two pictures' copies" + ); + drop(s); +} + /// Values are signalled in decode order, each once its picture landed: a decode that answers no /// picture is signalled in its turn, behind a picture still landing. #[test] @@ -1538,7 +1757,7 @@ fn a_pictures_coded_rows_below_its_crop_are_staged_for_its_caches() { device: p.device(), queue: None, buffer: None, - failed: Vec::new(), + out_of_use: OutOfUse::new(), unmade: false, }; let bitstream = buffer(&p, 4096, STORAGE_SHARED); @@ -1659,7 +1878,7 @@ fn a_short_picture_staged_for_a_cache_lands_over_zeros() { device: p.device(), queue: None, buffer: None, - failed: Vec::new(), + out_of_use: OutOfUse::new(), unmade: false, }; let bitstream = buffer(&p, 4096, STORAGE_SHARED); @@ -1741,7 +1960,7 @@ fn a_short_picture_the_hardware_writes_in_a_cache_has_the_plane_cleared_first() device: p.device(), queue: None, buffer: None, - failed: Vec::new(), + out_of_use: OutOfUse::new(), unmade: false, }; let bitstream = buffer(&p, 4096, STORAGE_SHARED); @@ -1829,7 +2048,7 @@ fn a_short_picture_in_a_cache_s_surface_has_its_images_cleared_first() { device: p.device(), queue: None, buffer: None, - failed: Vec::new(), + out_of_use: OutOfUse::new(), unmade: false, }; let bitstream = buffer(&p, 4096, STORAGE_SHARED); diff --git a/docs/conventions.md b/docs/conventions.md index fcdf906c4..9e35de57c 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -230,7 +230,16 @@ repeats the ones code cites. `video-pictures-handed-landed`, one that landed in its output, `video-pictures-handed-failed`, one that failed to land or whose decode was refused at its take, and `video-pictures-handed-undecoded`, - one that no decode ran for), its VA-API encodes' + one that no decode ran for), its video's GPU work whose wait failed + (on the rt platform, a lost device), each a failure path + (`video_host::OutOfUse`: `video-staging-ended`, a host video session + whose staging ended at a second copy into or out of its device caches + whose wait failed, each later picture or frame that stages a plane + failing; `video-nvdec-gathers-ended` and `video-xyuv-gathers-ended`, a + VideoToolbox decoder whose 4:4:4 writes by the GPU ended at a second + pass whose wait failed, or on the XYUV route a second driver's write + that stalled, its later 4:4:4 pictures copied by the CPU), its VA-API + encodes' (`video-encode-quality-level-adjusted`, a session whose driver refused the quality level asked and coded at the nearest it takes, or at its own: one a session), VideoToolbox's paravirtual path's (`vt-lends`,