🐛 Fail a VT picture whose GPU copy failed once committed

The Mac host's VideoToolbox arm copies each picture into the guest's surface on
the GPU, and fell back to the CPU's copy on any failure of that copy, a failed
wait or an errored command buffer among them. Where the wait failed (on the rt
platform, a lost device), the GPU may run the copy still, so the CPU's copy and
the late GPU copy could both write the guest's surface.

gpu_copy now answers Uncopied::Declined before anything is committed, which the
CPU's copy follows as before, and Uncopied::Failed once committed, which fails
the picture as a malfunction.

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

Test: a_picture_whose_copy_fails_once_committed_fails_with_no_copy_of_the_cpus
(ignored: VideoToolbox's decoder and a stream), on the stand-in device with a
scripted failed wait.
This commit is contained in:
Anees Iqbal committed 2026-12-03 07:28:47 -08:00
1 parent 06cdbdc075
commit b13fe6059b
2 files changed
+174 -26

No files matched your search

+52 -26
View File
@@ -26,7 +26,11 @@
//! whether [`IMPORTS_KEPT`] holds the surfaces VideoToolbox's pool lends.
//! - **The CPU's copy is the fallback**, through the host's view of the guest's pages, where
//! the session hands no buffer or the platform takes no import: counted
//! ([`CPU_COPIED`], logged once a reason), so that a run that takes it shows.
//! ([`CPU_COPIED`], logged once a reason), so that a run that takes it shows. It follows only a
//! GPU copy refused before anything was committed ([`Uncopied::Declined`]): a copy that fails
//! once committed fails the picture ([`Uncopied::Failed`]), since where its wait failed (on the
//! rt platform, a lost device) the GPU may write the guest's surface still. On a live device
//! the wait returns once the copy is done, and a guest sees none of this.
use std::sync::Arc;
@@ -433,18 +437,25 @@ impl<P: Platform> GuestDecoder<P> for VtGuestDecoder<P> {
.map_err(VideoError::Unsupported)?;
let _lock = surface.lock_read().map_err(decode_error)?;
let by_gpu = match output.buffer {
None => Err("the session handed no buffer over the guest's surface".to_owned()),
Some(buffer) => (self.imports.of(&self.device, &surface, length)).and_then(|source| {
let queue = match &self.queue {
Some(queue) => queue,
None => {
let made = self.device.new_command_queue();
self.queue
.insert(made.ok_or("the pictures' copies: no command queue")?)
}
};
gpu_copy::<P>(queue, &source, buffer, &copies)
}),
None => Err(Uncopied::Declined(
"the session handed no buffer over the guest's surface".to_owned(),
)),
Some(buffer) => (self.imports.of(&self.device, &surface, length))
.map_err(Uncopied::Declined)
.and_then(|source| {
let queue = match &self.queue {
Some(queue) => queue,
None => {
let made = self.device.new_command_queue().ok_or_else(|| {
Uncopied::Declined(
"the pictures' copies: no command queue".to_owned(),
)
})?;
self.queue.insert(made)
}
};
gpu_copy::<P>(queue, &source, buffer, &copies)
}),
};
match by_gpu {
Ok(()) => {
@@ -454,11 +465,12 @@ impl<P: Platform> GuestDecoder<P> for VtGuestDecoder<P> {
reims_vgpu_vulkan::answer::count_kind_by(GPU_COPIED_KIB, kib);
Ok(true)
}
Err(why) => {
Err(Uncopied::Declined(why)) => {
self.copied_by_cpu(why);
cpu_copy(&surface, output, &copies)?;
Ok(true)
}
Err(Uncopied::Failed(why)) => Err(VideoError::Malfunction(why)),
}
}
@@ -576,20 +588,31 @@ impl<P: Platform> Imports<P> {
}
}
/// Why a picture's GPU copy did not land it (module doc).
#[derive(Debug, PartialEq, Eq)]
enum Uncopied {
/// Nothing was committed: the CPU copies the picture.
Declined(String),
/// The copy failed once committed, and the GPU may write the guest's surface still: the
/// picture fails, with no copy of the CPU's.
Failed(String),
}
/// Copies `copies` from `source` into `destination` on `queue`, and waits for the copy.
fn gpu_copy<P: Platform>(
queue: &P::CommandQueue,
source: &P::Buffer,
destination: &P::Buffer,
copies: &[PlaneCopy],
) -> Result<(), String> {
) -> Result<(), Uncopied> {
let fault = |what: &str, raise| format!("the picture's copy: {what}: {raise:?}");
let declined = |why: &str| Uncopied::Declined(why.to_owned());
let cb = (queue.command_buffer(OnFault::Return))
.map_err(|r| fault("its command buffer", r))?
.ok_or("the picture's copy: no command buffer")?;
.map_err(|r| Uncopied::Declined(fault("its command buffer", r)))?
.ok_or_else(|| declined("the picture's copy: no command buffer"))?;
let blit = (cb.blit_encoder(OnFault::Return))
.map_err(|r| fault("its blit encoder", r))?
.ok_or("the picture's copy: no blit encoder")?;
.map_err(|r| Uncopied::Declined(fault("its blit encoder", r)))?
.ok_or_else(|| declined("the picture's copy: no blit encoder"))?;
for copy in copies {
for (from, to, size) in copy.runs() {
let recorded = (blit.encode(
@@ -602,25 +625,28 @@ fn gpu_copy<P: Platform>(
size: size as u64,
},
))
.map_err(|r| fault("a copy", r))?
.map_err(|r| Uncopied::Declined(fault("a copy", r)))?
.recorded();
if !recorded {
(blit.encode(OnFault::Return, BlitCmd::EndEncoding))
.map_err(|r| fault("its end", r))?
.map_err(|r| Uncopied::Declined(fault("its end", r)))?
.go_on();
return Err("the platform refused the picture's copy".to_owned());
return Err(declined("the platform refused the picture's copy"));
}
}
}
(blit.encode(OnFault::Return, BlitCmd::EndEncoding))
.map_err(|r| fault("its end", r))?
.map_err(|r| Uncopied::Declined(fault("its end", r)))?
.go_on();
cb.commit(OnFault::Return)
.map_err(|r| fault("its commit", r))?;
(cb.wait_until_completed(OnFault::Return)).map_err(|r| fault("its wait", r))?;
.map_err(|r| Uncopied::Declined(fault("its commit", r)))?;
(cb.wait_until_completed(OnFault::Return))
.map_err(|r| Uncopied::Failed(fault("its wait", r)))?;
if cb.status() != CommandBufferStatus::COMPLETED {
let error = cb.error().map(|e| format!("{e:?}")).unwrap_or_default();
return Err(format!("the picture's copy failed {error}"));
return Err(Uncopied::Failed(format!(
"the picture's copy failed {error}"
)));
}
Ok(())
}
@@ -695,3 +695,125 @@ fn a_session_not_made_is_made_at_the_next_picture_from_the_kept_sets() {
"the next picture, its session made from the kept sets"
);
}
/// A picture whose GPU copy into the guest's surface fails once committed (its wait answers an
/// error, as a lost device's does on the rt platform, the copy perhaps still running) fails as a
/// malfunction, with no copy of the CPU's into the surface; the next picture is copied by the GPU
/// as any. The first two pictures of the stream `RVG_VT_STREAM` names (Annex B: H.264 for a name
/// ending `.264`, else HEVC; 8-bit 4:2:0) in a `420v` surface at VideoToolbox's layout, over
/// whose pages the stand-in device's buffer lies.
#[test]
#[ignore = "needs VideoToolbox's hardware decoder and a stream: run on a Mac host"]
fn a_picture_whose_copy_fails_once_committed_fails_with_no_copy_of_the_cpus() {
use reims_vgpu_video::core::backend::BackendError;
use reims_vgpu_vulkan::core::testkit::{CompleteOn, Step};
let path = std::env::var("RVG_VT_STREAM").expect("RVG_VT_STREAM names a stream");
let codec = if path.ends_with(".264") {
Codec::H264
} else {
Codec::Hevc
};
let stream = std::fs::read(&path).expect("the stream");
let sets: Vec<&[u8]> = (split_annex_b(&stream).into_iter())
.filter(|unit| parameter_set(codec, unit))
.collect();
let aus: Vec<Vec<&[u8]>> = match codec {
Codec::H264 => h264::nal::access_units(&stream),
Codec::Hevc => hevc::nal::access_units(&stream),
}
.into_iter()
.map(|au| {
(split_annex_b(au).into_iter())
.filter(|unit| !parameter_set(codec, unit))
.collect::<Vec<_>>()
})
.filter(|units| !units.is_empty())
.take(2)
.collect();
assert_eq!(aus.len(), 2, "two pictures");
let destination = Destination {
pixel_format: FourCc::new(*b"420v"),
width: 0,
height: 0,
bytes_per_row_alignment: 64,
plane_alignment: 256,
};
let mut reference = Decoder::new(codec, &sets, &destination, true).expect("a session");
let picture = (reference.decode(&aus[0]))
.expect("a decode")
.expect("a picture");
let size = picture.size();
let (planes, _) = rows_of(&picture);
let own: Vec<_> = (planes.iter())
.map(|p| (p.offset, p.bytes_per_row, p))
.collect();
let layout = guest_layout(FourCc::new(*b"420v"), size, &own);
let end = (own.iter())
.map(|&(offset, pitch, p)| offset + pitch * p.height)
.max()
.expect("planes");
let len = end.next_multiple_of(TEST_PAGE);
let memory = PagesMemory {
life: MemoryLife::new(),
pages: Pages::new(len),
};
let platform = FakePlatform::new();
platform.world().set_auto_complete(Some(CompleteOn::Caller));
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 buffer = (platform.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::<FakePlatform> {
layout,
memory: &memory,
buffer: Some(&buffer),
};
let mut guest = VtGuestDecoder::<FakePlatform> {
codec,
device: platform.device().clone_ref(),
parameter_sets: Vec::new(),
session: None,
imports: Imports::default(),
queue: None,
said: Vec::new(),
fail_makes: 0,
};
let count = |code| {
(reims_vgpu_vulkan::answer::counted_kinds().into_iter())
.find(|&(c, _)| c == code)
.map_or(0, |(_, n)| n)
};
let sets = annex_b(&sets);
platform.script().push(
"waitUntilCompleted",
Step::Raise {
name: "NSInternalInconsistencyException".to_owned(),
reason: "the device is lost".to_owned(),
},
);
let failed = guest.decode(&sets, &annex_b(&aus[0]), &output);
assert!(
matches!(&failed, Err(BackendError::Malfunction(why)) if why.contains("its wait")),
"the first picture: {failed:?}"
);
assert_eq!(platform.call_log().count("commit"), 1, "the copy committed");
assert_eq!(guest.said, Vec::<String>::new(), "no copy of the CPU's");
assert_eq!(count(CPU_COPIED), 0, "none counted");
assert_eq!(count(GPU_COPIED), 0);
let landed = guest.decode(&[], &annex_b(&aus[1]), &output);
assert_eq!(landed, Ok(true), "the next picture");
assert_eq!(platform.call_log().count("commit"), 2);
assert_eq!(count(GPU_COPIED), 1, "copied by the GPU");
assert_eq!(count(CPU_COPIED), 0);
assert_eq!(guest.said, Vec::<String>::new());
}