From 2f1b129d07e94cf94ab2ec7202270e7ea420bbbd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 18:56:58 -0800 Subject: [PATCH] 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. --- crates/gpu-yuv/src/cpu.rs | 14 +++++++++++--- crates/gpu-yuv/src/job.rs | 24 ++++++++++++++++-------- crates/gpu-yuv/src/oracle_tests.rs | 18 +++++++++++++++--- crates/gpu-yuv/src/spec.rs | 3 +++ crates/gpu-yuv/src/tests.rs | 11 +++++++++++ 5 files changed, 56 insertions(+), 14 deletions(-) diff --git a/crates/gpu-yuv/src/cpu.rs b/crates/gpu-yuv/src/cpu.rs index c7afe643f2..b96bc90ed3 100644 --- a/crates/gpu-yuv/src/cpu.rs +++ b/crates/gpu-yuv/src/cpu.rs @@ -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(len: usize) -> Result, Error> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| Error::Memory { bytes: len.saturating_mul(size_of::()) })?; + 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 = 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]); diff --git a/crates/gpu-yuv/src/job.rs b/crates/gpu-yuv/src/job.rs index 3534816000..b37e346f92 100644 --- a/crates/gpu-yuv/src/job.rs +++ b/crates/gpu-yuv/src/job.rs @@ -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, 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, diff --git a/crates/gpu-yuv/src/oracle_tests.rs b/crates/gpu-yuv/src/oracle_tests.rs index 2b277805f4..354426a4e0 100644 --- a/crates/gpu-yuv/src/oracle_tests.rs +++ b/crates/gpu-yuv/src/oracle_tests.rs @@ -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). diff --git a/crates/gpu-yuv/src/spec.rs b/crates/gpu-yuv/src/spec.rs index 0ee3f5ba6b..cff46fe1a8 100644 --- a/crates/gpu-yuv/src/spec.rs +++ b/crates/gpu-yuv/src/spec.rs @@ -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}"), } } diff --git a/crates/gpu-yuv/src/tests.rs b/crates/gpu-yuv/src/tests.rs index 68e3a84a8f..157398ce26 100644 --- a/crates/gpu-yuv/src/tests.rs +++ b/crates/gpu-yuv/src/tests.rs @@ -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::(usize::MAX).unwrap_err(), Error::Memory { bytes: usize::MAX }); + assert_eq!(cpu::reserve::(usize::MAX / 2).unwrap_err(), Error::Memory { bytes: usize::MAX - 1 }); + let room = cpu::reserve::(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();