craft-gpu-yuv: allocation failures, internal device errors and the rounding check

- `cpu::convert` and the device read-back reserve the frame (and the I420
  Cr plane) with `try_reserve_exact`; a failed reservation is the new
  `Error::Memory`, which a job reports as `GpuFault::Operation`.
- A device job also pushes an `Internal` error scope, and the three scopes
  are popped in the reverse of the order they were pushed.
- `record` makes the output planes before it uploads the source, so a job
  the device's limits reject queues no upload.
- The equation tests accept only the floor or the ceiling of a value near a
  half, instead of anything within one code of the rounded value.
This commit is contained in:
dotCooCoo committed 2026-11-18 18:56:58 -08:00
1 parent 571ad821c5
commit 2f1b129d07
5 files changed
+56 -14

No files matched your search

+11 -3
View File
@@ -80,6 +80,14 @@ impl Image<'_> {
}
}
/// An empty vector with room for `len` values, or [`Error::Memory`] when the room cannot be
/// allocated.
pub(crate) fn reserve<T>(len: usize) -> Result<Vec<T>, Error> {
let mut v = Vec::new();
v.try_reserve_exact(len).map_err(|_| Error::Memory { bytes: len.saturating_mul(size_of::<T>()) })?;
Ok(v)
}
/// `rgba` (`src_width × src_height`, 4 bytes per pixel; alpha is ignored, so premultiplied
/// pixels convert as if over black) scaled to `width × height` and converted, as one tightly
/// packed frame in [`FrameLayout`] order.
@@ -95,7 +103,9 @@ pub fn convert(rgba: &[u8], src_width: u32, src_height: u32, conversion: Convers
let image = Image { rgba, width: src_width as usize, height: src_height as usize };
let c = Coefficients::of(conversion);
let (shift, wide) = (conversion.format.shift(), conversion.format.sample_bytes() == 2);
let mut out = Vec::with_capacity(layout.frame_bytes());
let (cw, ch) = (width / 2, height / 2);
let mut out = reserve(layout.frame_bytes())?;
let mut cr: Vec<u16> = if conversion.format == crate::Format::I420 { reserve(cw as usize * ch as usize)? } else { Vec::new() };
let mut put = |v: u16| {
let v = v << shift;
if wide {
@@ -112,7 +122,6 @@ pub fn convert(rgba: &[u8], src_width: u32, src_height: u32, conversion: Convers
}
}
};
let (cw, ch) = (width / 2, height / 2);
plane(width, height, &mut |v| put(v[0]));
match conversion.format {
crate::Format::Nv12 | crate::Format::P010 => plane(cw, ch, &mut |v| {
@@ -120,7 +129,6 @@ pub fn convert(rgba: &[u8], src_width: u32, src_height: u32, conversion: Convers
put(v[2]);
}),
crate::Format::I420 => {
let mut cr = Vec::with_capacity(cw as usize * ch as usize);
plane(cw, ch, &mut |v| {
put(v[1]);
cr.push(v[2]);
+16 -8
View File
@@ -40,11 +40,12 @@ fn invalid(message: impl std::fmt::Display) -> GpuFault {
GpuFault::InvalidJob(format!("{PROVIDER_ID}: {message}"))
}
/// A conversion error as a fault: device errors are [`GpuFault::Operation`], the rest describe a
/// job that cannot run and are [`GpuFault::InvalidJob`].
/// A conversion error as a fault: device errors and allocation failures are
/// [`GpuFault::Operation`], the rest describe a job that cannot run and are
/// [`GpuFault::InvalidJob`].
fn fault(e: Error) -> GpuFault {
match e {
Error::Device(_) => GpuFault::Operation(format!("{PROVIDER_ID}: {e}")),
Error::Device(_) | Error::Memory { .. } => GpuFault::Operation(format!("{PROVIDER_ID}: {e}")),
_ => invalid(e),
}
}
@@ -256,7 +257,8 @@ mod device {
}
/// `rgba` converted on the device, as one packed frame. Errors the device reports go to
/// error scopes and come back as [`Error::Device`].
/// error scopes and come back as [`Error::Device`]; a frame that cannot be allocated is
/// [`Error::Memory`].
pub(super) fn convert(&self, rgba: &[u8], job: &YuvJob) -> Result<Vec<u8>, Error> {
let (sw, sh) = (job.src_width, job.src_height);
let limit = self.device.limits().max_texture_dimension_2d;
@@ -270,10 +272,12 @@ mod device {
drop(converters);
let oom = self.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
let validation = self.device.push_error_scope(wgpu::ErrorFilter::Validation);
let internal = self.device.push_error_scope(wgpu::ErrorFilter::Internal);
let converter = cached.unwrap_or_else(|| Converter::new(&self.device, job.conversion));
let recorded = self.record(&converter, rgba, job);
// Both scopes are popped on every path, so that none stays open on the device.
let errors = [pollster::block_on(validation.pop()), pollster::block_on(oom.pop())];
// The scopes are popped on every path, in the reverse of the order they were pushed,
// so that none stays open on the device.
let errors = [pollster::block_on(internal.pop()), pollster::block_on(validation.pop()), pollster::block_on(oom.pop())];
if let Some(e) = errors.into_iter().flatten().next() {
return Err(device_error(e));
}
@@ -288,7 +292,9 @@ mod device {
self.device.poll(wgpu::PollType::wait_indefinitely()).map_err(device_error)?;
rx.try_recv().map_err(|_| device_error("the read-back map did not complete"))?.map_err(device_error)?;
let mapped = buffer.get_mapped_range(..).map_err(device_error)?;
let mut frame = vec![0u8; planes.layout().frame_bytes()];
let bytes = planes.layout().frame_bytes();
let mut frame = crate::cpu::reserve(bytes)?;
frame.resize(bytes, 0u8);
let unpacked = planes.layout().unpack(&mapped, &mut frame);
drop(mapped);
buffer.unmap();
@@ -297,6 +303,9 @@ mod device {
/// Upload `rgba` and record and submit the passes and the copy into a read-back buffer.
fn record(&self, converter: &Converter, rgba: &[u8], job: &YuvJob) -> Result<(Planes, wgpu::Buffer), Error> {
// The output size is checked against the device before the source is uploaded, so a
// rejected job queues no upload.
let planes = converter.planes(&self.device, job.width, job.height)?;
let (sw, sh) = (job.src_width, job.src_height);
let size = wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 };
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
@@ -312,7 +321,6 @@ mod device {
let layout = wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(sw * 4), rows_per_image: Some(sh) };
self.queue.write_texture(texture.as_image_copy(), rgba, layout, size);
let source = converter.bind(&self.device, &texture.create_view(&wgpu::TextureViewDescriptor::default()));
let planes = converter.planes(&self.device, job.width, job.height)?;
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("craft.yuv read-back"),
size: planes.layout().buffer_size,
+15 -3
View File
@@ -59,11 +59,23 @@ fn round(x: f64, bits: u32) -> u16 {
}
/// Whether `got` is the rounded `exact` value. A value within 0.001 of a half may round either
/// way in `f32`, so either neighbor passes there.
/// way in `f32`, so there the floor and the ceiling of `exact`, clamped to the codes, both pass.
fn rounds_to(got: u16, exact: f64, bits: u32) -> bool {
let want = round(exact, bits);
let near_half = ((exact - exact.floor()) - 0.5).abs() < 1e-3;
got == want || near_half && got.abs_diff(want) <= 1
let code = |v: f64| v.clamp(0.0, f64::from((1u32 << bits) - 1)) as u16;
got == round(exact, bits) || near_half && (got == code(exact.floor()) || got == code(exact.ceil()))
}
#[test]
fn a_value_near_a_half_passes_only_as_its_floor_or_ceiling() {
assert!(rounds_to(128, 128.5, 8));
assert!(rounds_to(129, 128.5, 8));
assert!(!rounds_to(130, 128.5, 8));
assert!(!rounds_to(127, 128.5, 8));
assert!(rounds_to(255, 254.9995, 8));
assert!(!rounds_to(254, 254.9, 8));
assert!(rounds_to(0, -0.5, 8));
assert!(!rounds_to(1, -0.5, 8));
}
/// Every sample of a frame as its value (P010 words shifted down by 6).
+3
View File
@@ -164,6 +164,8 @@ pub enum Error {
/// A frame layout's fields are not what [`crate::FrameLayout::new`] gives for its format and
/// size.
Layout,
/// A buffer of `bytes` bytes for the frame could not be allocated.
Memory { bytes: usize },
/// The device reported an error (validation, out of memory, a failed map or poll) while
/// [`crate::YuvProvider`] ran a job on it.
Device(String),
@@ -181,6 +183,7 @@ impl fmt::Display for Error {
Error::Offset(offset) => write!(f, "buffer offset {offset} is not a multiple of {}", wgpu::COPY_BYTES_PER_ROW_ALIGNMENT),
Error::Mismatch { converter, planes } => write!(f, "{planes} planes given to a {converter} converter"),
Error::Layout => f.write_str("the frame layout does not match its format and size"),
Error::Memory { bytes } => write!(f, "a buffer of {bytes} bytes could not be allocated"),
Error::Device(message) => write!(f, "the device reported an error: {message}"),
}
}
+11
View File
@@ -121,6 +121,17 @@ fn bad_sizes_are_errors() {
assert_eq!(Error::OutputSize { width: 3, height: 2 }.to_string(), "a 4:2:0 picture of 3×2 needs both sides even and not zero");
}
#[test]
fn a_frame_buffer_that_cannot_be_allocated_is_an_error() {
// A request past `isize::MAX` bytes fails on every allocator, so the failure path runs
// without exhausting memory.
assert_eq!(cpu::reserve::<u8>(usize::MAX).unwrap_err(), Error::Memory { bytes: usize::MAX });
assert_eq!(cpu::reserve::<u16>(usize::MAX / 2).unwrap_err(), Error::Memory { bytes: usize::MAX - 1 });
let room = cpu::reserve::<u8>(4096).unwrap();
assert!(room.is_empty() && room.capacity() >= 4096);
assert_eq!(Error::Memory { bytes: 16 }.to_string(), "a buffer of 16 bytes could not be allocated");
}
#[test]
fn layouts_pad_rows_for_copies_and_unpack_without_the_padding() {
let l = FrameLayout::new(Format::Nv12, 1920, 1080).unwrap();