diff --git a/crates/raster-codecs/src/dds.rs b/crates/raster-codecs/src/dds.rs index 1249cb5b7..0f848e38c 100644 --- a/crates/raster-codecs/src/dds.rs +++ b/crates/raster-codecs/src/dds.rs @@ -91,6 +91,7 @@ impl Field { } } +#[derive(Clone, Copy)] enum Encoding { /// Uncompressed: bytes per pixel, then red (or luminance), green, blue and alpha. Masks { @@ -202,7 +203,25 @@ fn dx10_encoding(b: &[u8]) -> Result { } } -pub fn decode(b: &[u8], limits: &Limits) -> Result { +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DdsInfo { + pub width: u32, + pub height: u32, + pub levels: u32, + pub alpha: bool, + pub compression: Option, +} + +struct Parsed<'a> { + encoding: Encoding, + data: &'a [u8], + width: u32, + height: u32, + levels: u32, + pitch: Option, +} + +fn parse(b: &[u8]) -> Result, CodecError> { if !b.starts_with(b"DDS ") { return Err(bad("missing the `DDS ` signature")); } @@ -218,17 +237,63 @@ pub fn decode(b: &[u8], limits: &Limits) -> Result { } let dx10 = le32(b, 80)? & DDPF_FOURCC != 0 && &le32(b, 84)?.to_le_bytes() == b"DX10"; let (encoding, start) = if dx10 { (dx10_encoding(b)?, HEADER + DX10_HEADER) } else { (legacy_encoding(b)?, HEADER) }; - let layout = encoding.layout(); - limits.check(width, height, layout, SampleType::U8)?; + let declared = le32(b, 28)?.max(1); + let levels = declared.min(mip_levels(width, height)); // The same header field is a total level size for BC, but a row stride when DDSD_PITCH is set. let pitch = if flags & DDSD_PITCH != 0 { Some(le32(b, 20)?) } else { None }; + Ok(Parsed { encoding, data: b.get(start..).unwrap_or_default(), width, height, levels, pitch }) +} + +pub fn info(b: &[u8]) -> Result { + let p = parse(b)?; + let compression = match p.encoding { + Encoding::Masks { .. } => DdsCompression::None, + Encoding::Bc1 => DdsCompression::Bc1, + Encoding::Bc2 => DdsCompression::Bc2, + Encoding::Bc3 => DdsCompression::Bc3, + }; + let alpha = match p.encoding { + Encoding::Masks { fields, .. } => fields[3].is_some(), + _ => true, + }; + Ok(DdsInfo { width: p.width, height: p.height, levels: p.levels, alpha, compression: Some(compression) }) +} + +pub fn decode(b: &[u8], limits: &Limits) -> Result { + let p = parse(b)?; + level_image(p.encoding, p.data, p.width, p.height, p.pitch, limits).map(|(img, _)| img) +} + +pub fn decode_levels(b: &[u8], limits: &Limits, cancel: &dyn Fn() -> bool) -> Result, CodecError> { + let p = parse(b)?; + let (mut data, mut width, mut height, mut remaining) = (p.data, p.width, p.height, limits.max_alloc); + let mut levels = Vec::with_capacity(p.levels as usize); + for i in 0..p.levels { + if cancel() { + return Err(bad("DDS import cancelled")); + } + let level_limits = Limits { max_alloc: remaining, ..*limits }; + let (img, size) = level_image(p.encoding, data, width, height, if i == 0 { p.pitch } else { None }, &level_limits)?; + remaining = + remaining.checked_sub(img.data().len() as u64).ok_or_else(|| CodecError::LimitExceeded("DDS mip chain exceeds max_alloc".into()))?; + levels.push(img); + data = data.get(size..).ok_or_else(|| bad("truncated mip data"))?; + width = (width / 2).max(1); + height = (height / 2).max(1); + } + Ok(levels) +} + +fn level_image(encoding: Encoding, data: &[u8], width: u32, height: u32, pitch: Option, limits: &Limits) -> Result<(Image, usize), CodecError> { + let layout = encoding.layout(); + limits.check(width, height, layout, SampleType::U8)?; let (row_pitch, size) = encoding.level_layout(width, height, pitch)?; - let data = b.get(start..).and_then(|d| d.get(..size)).ok_or_else(|| bad(format!("truncated pixel data: {size} bytes needed")))?; + let data = data.get(..size).ok_or_else(|| bad(format!("truncated pixel data: {size} bytes needed")))?; let (w, h) = (width as usize, height as usize); let channels = layout.channels(); let row_size = w.checked_mul(channels).ok_or_else(|| bad("pixel size overflow"))?; let total = row_size.checked_mul(h).ok_or_else(|| bad("pixel size overflow"))?; - let mut pixels = vec![0u8; total]; + let mut pixels = crate::alloc_zeroed::(total)?; match encoding { Encoding::Masks { bytes, gray, fields } => { for (src_row, dst_row) in data.chunks_exact(row_pitch).zip(pixels.chunks_exact_mut(row_size)) { @@ -263,7 +328,7 @@ pub fn decode(b: &[u8], limits: &Limits) -> Result { } } } - Image::from_u8(width, height, layout, pixels) + Ok((Image::from_u8(width, height, layout, pixels)?, size)) } /// A BC1 colour block. BC2 and BC3 colour blocks always have four colours; only BC1's diff --git a/crates/raster-codecs/tests/dds.rs b/crates/raster-codecs/tests/dds.rs index afb9066aa..60fe1366d 100644 --- a/crates/raster-codecs/tests/dds.rs +++ b/crates/raster-codecs/tests/dds.rs @@ -410,3 +410,79 @@ fn rejects_bogus_sizes_and_pixel_formats() { no_format.extend([0; 4]); assert!(matches!(decode(&no_format), Err(CodecError::Unsupported { .. }))); } + +fn mip_chain() -> Vec { + let mut b = compressed(4, 4, b"DXT1"); + b[8..12].copy_from_slice(&(0x1007u32 | 0x2_0000).to_le_bytes()); + b[28..32].copy_from_slice(&3u32.to_le_bytes()); + for c in [RED, GREEN, BLUE] { + b.extend(bc1_block(c, c, [0; 4])); + } + b +} + +#[test] +fn import_info_and_all_mips_use_the_shared_decoder() { + let b = mip_chain(); + let info = dds::info(&b[..128]).unwrap(); + assert_eq!((info.width, info.height, info.levels, info.alpha), (4, 4, 3, true)); + assert_eq!(info.compression, Some(dds::DdsCompression::Bc1)); + let levels = dds::decode_levels(&b, &Limits::default(), &|| false).unwrap(); + assert_eq!(levels.iter().map(Image::dimensions).collect::>(), [(4, 4), (2, 2), (1, 1)]); + for (img, color) in levels.iter().zip([[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]]) { + assert!(img.data().as_chunks::<4>().0.iter().all(|p| *p == color)); + } + assert_eq!(decode(&b).unwrap().data(), levels[0].data()); +} + +#[test] +fn mip_chain_charges_the_combined_allocation() { + for (budget, accepted) in [(63, false), (64, false), (80, false), (83, false), (84, true)] { + let result = dds::decode_levels(&mip_chain(), &Limits { max_alloc: budget, ..Default::default() }, &|| false); + if accepted { + assert_eq!(result.unwrap().len(), 3); + } else { + assert!(matches!(result, Err(CodecError::LimitExceeded(_)))); + } + } +} + +#[test] +fn cancellation_is_checked_after_a_level_was_decoded() { + let calls = std::cell::Cell::new(0); + let result = dds::decode_levels(&mip_chain(), &Limits::default(), &|| { + let n = calls.get(); + calls.set(n + 1); + n == 1 + }); + assert!(matches!(result, Err(CodecError::Malformed { message, .. }) if message.contains("cancelled"))); + assert_eq!(calls.get(), 2); +} + +#[test] +fn mip_import_rejects_truncation_and_bounds_declared_count() { + let mut b = mip_chain(); + for n in 0..b.len() { + assert!(dds::decode_levels(&b[..n], &Limits::default(), &|| false).is_err(), "length {n}"); + } + b[28..32].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(dds::decode_levels(&b, &Limits::default(), &|| false).unwrap().len(), 3); + b[8..12].copy_from_slice(&0x1007u32.to_le_bytes()); + assert_eq!(dds::info(&b).unwrap().levels, 3); + assert_eq!(dds::decode_levels(&b, &Limits::default(), &|| false).unwrap().len(), 3); + b[28..32].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(dds::info(&b).unwrap().levels, 1); + assert_eq!(dds::decode_levels(&b, &Limits::default(), &|| false).unwrap().len(), 1); +} + +#[test] +fn lower_mips_do_not_inherit_top_level_pitch() { + let mut b = header(2, 2, DDPF_LUMINANCE, &[0; 4], 8, [0xff, 0, 0, 0]); + set_pitch(&mut b, 4); + b[8..12].copy_from_slice(&(0x1007u32 | DDSD_PITCH | 0x2_0000).to_le_bytes()); + b[28..32].copy_from_slice(&2u32.to_le_bytes()); + b.extend([1, 2, 99, 99, 3, 4, 99, 99, 5]); + let levels = dds::decode_levels(&b, &Limits::default(), &|| false).unwrap(); + assert_eq!(levels[0].data(), [1, 2, 3, 4]); + assert_eq!(levels[1].data(), [5]); +}