From f1f296e27c82692e48e39651317dc030b6f5b2d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 07:52:36 +0300 Subject: [PATCH] feat(image): decode BMP, including the shapes ImageMagick will not write gpui names ImageFormat::Bmp, so the shim needed a decoder behind it. This reads every shape the format defines: 1/2/4/8/16/24/32-bit samples, palettes with three- or four-byte entries, BI_RLE4 and BI_RLE8, arbitrary BI_BITFIELDS masks, bottom-up and top-down rows, and headers of every defined length from the 12-byte OS/2 v1 to the 124-byte BITMAPV5HEADER. Two shapes that started as refusals are decoded instead. BI_PNG and BI_JPEG files are a BMP header wrapped around a whole file of another format, so they are handed to this crate's own PNG and JPEG decoders. The 16-byte OS/2 v2 header is the Windows layout truncated where the two stop agreeing, so it is read through those 16 bytes -- which is what ffmpeg does, and what the incumbent image crate refuses. Gate: fourteen fixtures pixel-exact against image 0.25.10, the two wrapper files exact against the incumbent decoding their payloads directly, and the OS/2 v2 file exact against the same picture in a header the incumbent reads. Twenty thousand fuzz mutations across the plain and run-length paths, no panics. Full report in lanes/image-bmp-r1.report.md. --- crates/ec-image/src/bmp.rs | 496 ++++++++++++++++++++++++++ crates/ec-image/src/lib.rs | 31 +- crates/ec-image/tests/differential.rs | 90 +++++ crates/ec-image/tests/fuzz.rs | 22 +- lanes/image-bmp-r1.report.md | 113 ++++++ scripts/gen-still-fixtures.sh | 28 ++ scripts/lib/gen-bmp-shapes.py | 168 +++++++++ shims/image/src/lib.rs | 8 +- 8 files changed, 950 insertions(+), 6 deletions(-) create mode 100644 crates/ec-image/src/bmp.rs create mode 100644 lanes/image-bmp-r1.report.md create mode 100644 scripts/lib/gen-bmp-shapes.py diff --git a/crates/ec-image/src/bmp.rs b/crates/ec-image/src/bmp.rs new file mode 100644 index 00000000..d67cd909 --- /dev/null +++ b/crates/ec-image/src/bmp.rs @@ -0,0 +1,496 @@ +//! BMP: the Windows device-independent bitmap, as `image` and every screenshot +//! tool on Windows write it. +//! +//! One file header, one info header, an optional palette and then rows, and +//! almost all of the difficulty is in how many shapes those four things take: +//! headers of five different lengths, samples 1, 2, 4, 8, 16, 24 or 32 bits +//! wide, palettes with three-byte or four-byte entries, rows stored bottom-up +//! or top-down, run-length encoding for the 4- and 8-bit forms, and arbitrary +//! channel masks under `BI_BITFIELDS`. +//! +//! `BI_PNG` and `BI_JPEG` files are a BMP header wrapped around a whole PNG or +//! JPEG file, so they are handed to those decoders rather than refused. +//! +//! An OS/2 v2 header is read through its first 16 bytes, which is where it +//! stops agreeing with the Windows one; the fields past that describe halftoning +//! and a colour table format no writer emits. ICC profiles in a v5 header are +//! metadata this crate does not carry, so they are ignored rather than refused. + +use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels}; +use ec_core::{Error, Result}; + +/// Fields of the info header this decoder acts on. +struct Header { + width: u32, + height: u32, + /// Rows are stored bottom-up unless the height was negative. + top_down: bool, + bits: u16, + compression: u32, + /// Palette entries actually present in the file. + colours: usize, + /// Bytes per palette entry: 4 in a Windows header, 3 in an OS/2 one. + palette_stride: usize, + /// Where the info header ends and the palette begins. + palette_at: usize, + /// Channel masks, present under `BI_BITFIELDS` and defaulted otherwise. + masks: [u32; 4], +} + +const BI_RGB: u32 = 0; +const BI_RLE8: u32 = 1; +const BI_RLE4: u32 = 2; +const BI_BITFIELDS: u32 = 3; +const BI_JPEG: u32 = 4; +const BI_PNG: u32 = 5; +const BI_ALPHABITFIELDS: u32 = 6; + +fn u16_at(data: &[u8], at: usize) -> Result { + data.get(at..at + 2) + .map(|b| u16::from_le_bytes([b[0], b[1]])) + .ok_or_else(|| Error::corrupt("BMP: header runs past the file")) +} + +fn u32_at(data: &[u8], at: usize) -> Result { + data.get(at..at + 4) + .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .ok_or_else(|| Error::corrupt("BMP: header runs past the file")) +} + +/// Parse the file and info headers. +fn header(data: &[u8]) -> Result
{ + if !data.starts_with(b"BM") { + return Err(Error::corrupt("BMP: no BM signature")); + } + let info_size = u32_at(data, 14)? as usize; + // 12 is the OS/2 v1 header (BITMAPCOREHEADER), 40 the Windows v3 one, and + // 52/56/108/124 are v3 plus masks, v4 and v5. Everything past the first 40 + // bytes is colour-space description this crate does not carry. + let (width, height, top_down, bits, compression, declared_colours) = if info_size == 12 { + ( + u32::from(u16_at(data, 18)?), + u32::from(u16_at(data, 20)?), + false, + u16_at(data, 24)?, + BI_RGB, + 0usize, + ) + } else if (16..40).contains(&info_size) { + // An OS/2 v2 header, whose first 16 bytes are the Windows layout: the + // dimensions are 32-bit and there is no compression field at all. + let raw_height = u32_at(data, 22)? as i32; + ( + u32_at(data, 18)?, + raw_height.unsigned_abs(), + raw_height < 0, + u16_at(data, 28)?, + BI_RGB, + 0usize, + ) + } else if info_size >= 40 { + let raw_height = u32_at(data, 22)? as i32; + ( + u32_at(data, 18)?, + raw_height.unsigned_abs(), + raw_height < 0, + u16_at(data, 28)?, + u32_at(data, 30)?, + u32_at(data, 46)? as usize, + ) + } else { + return Err(Error::corrupt(format!( + "BMP: a {info_size}-byte info header, shorter than any the format defines" + ))); + }; + + if !matches!(bits, 1 | 2 | 4 | 8 | 16 | 24 | 32) { + return Err(Error::corrupt(format!("BMP: {bits} bits per pixel"))); + } + match compression { + // Handled before the header is read; reaching here means the caller + // asked for the fields of a file that has none of them. + BI_JPEG | BI_PNG => {} + BI_RGB | BI_RLE8 | BI_RLE4 | BI_BITFIELDS | BI_ALPHABITFIELDS => {} + other => { + return Err(Error::corrupt(format!("BMP: compression {other}"))); + } + } + if (compression == BI_RLE8 && bits != 8) || (compression == BI_RLE4 && bits != 4) { + return Err(Error::corrupt(format!( + "BMP: run-length encoding with {bits} bits per pixel" + ))); + } + + // Under BI_BITFIELDS the masks follow the 40-byte header in a v3 file and + // live inside a v4/v5 one; either way they start at offset 54. + let bitfields = compression == BI_BITFIELDS || compression == BI_ALPHABITFIELDS; + let mut masks = [0u32; 4]; + let mut palette_at = 14 + info_size; + if bitfields && info_size == 40 { + for (i, mask) in masks.iter_mut().enumerate().take(3) { + *mask = u32_at(data, 54 + i * 4)?; + } + if compression == BI_ALPHABITFIELDS { + masks[3] = u32_at(data, 66)?; + } + palette_at += 12 + + if compression == BI_ALPHABITFIELDS { + 4 + } else { + 0 + }; + } else if bitfields { + for (i, mask) in masks.iter_mut().enumerate() { + *mask = u32_at(data, 54 + i * 4)?; + } + } else if info_size >= 108 { + // A v4 header carries masks whether or not BI_BITFIELDS is set; they + // are only meaningful for the 16- and 32-bit forms. + for (i, mask) in masks.iter_mut().enumerate() { + *mask = u32_at(data, 54 + i * 4)?; + } + } + if masks[..3].iter().all(|&m| m == 0) { + // The defaults the format documents: 5-5-5 at 16 bits, 8-8-8 at 24 and + // 32, with the top eight bits of a 32-bit sample unused. + masks = match bits { + 16 => [0x7c00, 0x03e0, 0x001f, 0], + _ => [0x00ff_0000, 0x0000_ff00, 0x0000_00ff, 0], + }; + } + + let palette_stride = if info_size == 12 { 3 } else { 4 }; + let colours = if bits <= 8 { + let max = 1usize << bits; + // Zero means "as many as the depth allows"; a larger claim than the + // depth allows is the file lying about itself. + if declared_colours == 0 || declared_colours > max { + max + } else { + declared_colours + } + } else { + 0 + }; + + Ok(Header { + width, + height, + top_down, + bits, + compression, + colours, + palette_stride, + palette_at, + masks, + }) +} + +/// Dimensions from the headers alone. +pub fn info(data: &[u8]) -> Result { + if let Some(embedded) = embedded(data)? { + let mut info = match embedded.0 { + ImageFormat::Png => crate::png::info(embedded.1)?, + _ => crate::jpeg::info(embedded.1)?, + }; + // The wrapper is what the caller opened, so it is what they are told. + info.format = ImageFormat::Bmp; + return Ok(info); + } + let header = header(data)?; + Ok(Info { + format: ImageFormat::Bmp, + width: header.width, + height: header.height, + }) +} + +/// The payload of a `BI_PNG` or `BI_JPEG` file, which is a whole file of that +/// other format rather than any arrangement of BMP rows. +/// +/// `biSizeImage` is the payload's length; a zero there means the writer left it +/// out, and the rest of the file is the payload. +fn embedded(data: &[u8]) -> Result> { + if !data.starts_with(b"BM") || u32_at(data, 14)? < 40 { + return Ok(None); + } + let format = match u32_at(data, 30)? { + BI_PNG => ImageFormat::Png, + BI_JPEG => ImageFormat::Jpeg, + _ => return Ok(None), + }; + let offset = u32_at(data, 10)? as usize; + let payload = data + .get(offset..) + .ok_or_else(|| Error::corrupt("BMP: the payload offset is past the file"))?; + let declared = u32_at(data, 34)? as usize; + let payload = if declared == 0 || declared > payload.len() { + payload + } else { + &payload[..declared] + }; + Ok(Some((format, payload))) +} + +/// A channel mask reduced to a shift and a scale. +/// +/// Masks are arbitrary -- a 16-bit file may carry 5-6-5, 5-5-5 or anything +/// else -- so each channel is read as a field and stretched to eight bits so +/// that a full-scale field becomes 255 rather than 248. +struct Field { + shift: u32, + max: u32, +} + +impl Field { + fn new(mask: u32) -> Option { + if mask == 0 { + return None; + } + let shift = mask.trailing_zeros(); + Some(Field { + shift, + max: mask >> shift, + }) + } + + fn sample(&self, raw: u32, mask: u32) -> u8 { + let value = (raw & mask) >> self.shift; + if self.max == 0 { + return 0; + } + ((value * 255 + self.max / 2) / self.max) as u8 + } +} + +/// Decode a BMP file. +pub fn decode(data: &[u8], limits: Limits) -> Result { + if let Some((format, payload)) = embedded(data)? { + return match format { + ImageFormat::Png => crate::png::decode(payload, limits), + _ => crate::jpeg::decode(payload, limits), + }; + } + let header = header(data)?; + limits.check(header.width, header.height)?; + let (width, height) = (header.width as usize, header.height as usize); + if width == 0 || height == 0 { + return Err(Error::corrupt("BMP: a zero-sized picture")); + } + + let palette = palette(data, &header)?; + let offset = u32_at(data, 10)? as usize; + let body = data + .get(offset..) + .ok_or_else(|| Error::corrupt("BMP: the pixel offset is past the file"))?; + + // Indices first, then colour: every form below produces either palette + // indices or direct samples, and the bottom-up flip is the same either way. + let has_alpha = header.masks[3] != 0 + || (header.bits == 32 && header.compression == BI_RGB && palette.is_empty()); + let mut out = vec![0u8; width * height * if has_alpha { 4 } else { 3 }]; + let channels = if has_alpha { 4 } else { 3 }; + let row_of = |y: usize| if header.top_down { y } else { height - 1 - y }; + + match header.compression { + BI_RLE8 | BI_RLE4 => { + let indices = rle(body, &header)?; + for y in 0..height { + for x in 0..width { + let index = indices[y * width + x] as usize; + let rgb = *palette + .get(index) + .ok_or_else(|| Error::corrupt("BMP: palette index past the table"))?; + let at = (row_of(y) * width + x) * channels; + out[at..at + 3].copy_from_slice(&rgb); + if has_alpha { + out[at + 3] = 255; + } + } + } + } + _ => { + // Rows are padded to a four-byte boundary. + let stride = (width * usize::from(header.bits)) + .div_ceil(8) + .next_multiple_of(4); + if body.len() < stride * height { + return Err(Error::corrupt(format!( + "BMP: {} bytes of pixels, {} rows of {stride} needed", + body.len(), + height + ))); + } + let fields = [ + Field::new(header.masks[0]), + Field::new(header.masks[1]), + Field::new(header.masks[2]), + Field::new(header.masks[3]), + ]; + for y in 0..height { + let row = &body[y * stride..y * stride + stride]; + for x in 0..width { + let at = (row_of(y) * width + x) * channels; + let (rgb, alpha) = match header.bits { + 1 | 2 | 4 | 8 => { + let bits = usize::from(header.bits); + let bit = x * bits; + let byte = row[bit / 8]; + let shift = 8 - bits - (bit % 8); + let index = usize::from((byte >> shift) & ((1 << bits) - 1) as u8); + let rgb = *palette.get(index).ok_or_else(|| { + Error::corrupt("BMP: palette index past the table") + })?; + (rgb, 255) + } + 16 => { + let raw = u32::from(u16::from_le_bytes([row[x * 2], row[x * 2 + 1]])); + sample(raw, &header.masks, &fields) + } + 24 => ([row[x * 3 + 2], row[x * 3 + 1], row[x * 3]], 255), + _ => { + let raw = u32::from_le_bytes([ + row[x * 4], + row[x * 4 + 1], + row[x * 4 + 2], + row[x * 4 + 3], + ]); + sample(raw, &header.masks, &fields) + } + }; + out[at..at + 3].copy_from_slice(&rgb); + if has_alpha { + out[at + 3] = alpha; + } + } + } + } + } + + Ok(Image { + width: header.width, + height: header.height, + pixels: if has_alpha { + Pixels::Rgba8(out) + } else { + Pixels::Rgb8(out) + }, + meta: Metadata::default(), + }) +} + +/// One direct-colour pixel through the channel masks. +fn sample(raw: u32, masks: &[u32; 4], fields: &[Option; 4]) -> ([u8; 3], u8) { + let mut rgb = [0u8; 3]; + for c in 0..3 { + if let Some(field) = &fields[c] { + rgb[c] = field.sample(raw, masks[c]); + } + } + let alpha = match &fields[3] { + Some(field) => field.sample(raw, masks[3]), + None => 255, + }; + (rgb, alpha) +} + +/// The palette, as RGB triples in file order. +fn palette(data: &[u8], header: &Header) -> Result> { + if header.colours == 0 { + return Ok(Vec::new()); + } + let mut out = Vec::with_capacity(header.colours); + for i in 0..header.colours { + let at = header.palette_at + i * header.palette_stride; + let entry = data + .get(at..at + 3) + .ok_or_else(|| Error::corrupt("BMP: the palette runs past the file"))?; + // Entries are stored blue first. + out.push([entry[2], entry[1], entry[0]]); + } + Ok(out) +} + +/// Expand `BI_RLE8` or `BI_RLE4` into one palette index per pixel. +/// +/// The two forms share a structure: a non-zero first byte is a run, a zero +/// introduces an escape -- end of line, end of file, a delta, or a literal run +/// padded to an even number of bytes. Pixels the encoding never reaches keep +/// index zero, which is what the format means by a sparse image. +fn rle(body: &[u8], header: &Header) -> Result> { + let (width, height) = (header.width as usize, header.height as usize); + let mut out = vec![0u8; width * height]; + let (mut x, mut y) = (0usize, 0usize); + let mut at = 0usize; + let four_bit = header.compression == BI_RLE4; + + let put = |out: &mut Vec, x: &mut usize, y: usize, index: u8| { + if *x < width && y < height { + out[y * width + *x] = index; + } + *x += 1; + }; + + while at + 1 < body.len() { + let (count, value) = (body[at], body[at + 1]); + at += 2; + if count > 0 { + for i in 0..usize::from(count) { + let index = if four_bit { + if i % 2 == 0 { value >> 4 } else { value & 0x0f } + } else { + value + }; + put(&mut out, &mut x, y, index); + } + continue; + } + match value { + // End of line. + 0 => { + x = 0; + y += 1; + } + // End of the bitmap; anything after it is padding. + 1 => break, + // A delta: move right and down by the next two bytes. + 2 => { + let delta = body + .get(at..at + 2) + .ok_or_else(|| Error::corrupt("BMP: a truncated RLE delta"))?; + x += usize::from(delta[0]); + y += usize::from(delta[1]); + at += 2; + } + // A literal run of `value` pixels, padded to an even byte count. + literal => { + let literal = usize::from(literal); + let bytes = if four_bit { + literal.div_ceil(2) + } else { + literal + }; + let run = body + .get(at..at + bytes) + .ok_or_else(|| Error::corrupt("BMP: a truncated RLE literal"))?; + for i in 0..literal { + let index = if four_bit { + if i % 2 == 0 { + run[i / 2] >> 4 + } else { + run[i / 2] & 0x0f + } + } else { + run[i] + }; + put(&mut out, &mut x, y, index); + } + at += bytes + (bytes & 1); + } + } + if y > height { + return Err(Error::corrupt("BMP: RLE runs past the last row")); + } + } + Ok(out) +} diff --git a/crates/ec-image/src/lib.rs b/crates/ec-image/src/lib.rs index 36f0ee35..6175377e 100644 --- a/crates/ec-image/src/lib.rs +++ b/crates/ec-image/src/lib.rs @@ -1,4 +1,4 @@ -//! Still-image decoding: PNG, JPEG, WebP and GIF. +//! Still-image decoding: PNG, JPEG, WebP, GIF and BMP. //! //! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the //! format from the leading bytes and hands back an [`Image`]: dimensions, a @@ -31,6 +31,7 @@ // what keeps the code readable against the text it comes from. #![allow(clippy::needless_range_loop)] +pub mod bmp; pub mod gif; pub mod jpeg; pub mod png; @@ -54,6 +55,8 @@ pub enum ImageFormat { WebP, /// GIF, still or animated (GIF87a and GIF89a). Gif, + /// Windows BMP (device-independent bitmap). + Bmp, } impl ImageFormat { @@ -69,6 +72,8 @@ impl ImageFormat { Some(ImageFormat::WebP) } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") { Some(ImageFormat::Gif) + } else if is_bmp(data) { + Some(ImageFormat::Bmp) } else { None } @@ -81,10 +86,28 @@ impl ImageFormat { ImageFormat::Jpeg => "jpg", ImageFormat::WebP => "webp", ImageFormat::Gif => "gif", + ImageFormat::Bmp => "bmp", } } } +/// Whether `data` opens like a BMP. +/// +/// "BM" is two bytes, which half the files on a disk could start with by +/// accident, so the guess also asks the file header to agree with itself: the +/// declared info-header length must be one the format defines, and the pixel +/// data must start after the headers. +fn is_bmp(data: &[u8]) -> bool { + if !data.starts_with(b"BM") || data.len() < 18 { + return false; + } + let u32_at = + |at: usize| u32::from_le_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]); + let offset = u32_at(10) as usize; + let info_size = u32_at(14) as usize; + matches!(info_size, 12 | 16 | 40 | 52 | 56 | 64 | 108 | 124) && offset >= 14 + info_size +} + /// Bounds applied before any buffer is sized from a header field. /// /// A three-byte dimension field can ask for a 68-gigapixel allocation; this is @@ -349,9 +372,10 @@ pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result { Some(ImageFormat::Jpeg) => jpeg::decode(data, limits), Some(ImageFormat::WebP) => webp::decode(data, limits), Some(ImageFormat::Gif) => gif::decode(data, limits), + Some(ImageFormat::Bmp) => bmp::decode(data, limits), None => Err(Error::unsupported( "image", - "no PNG, JPEG, WebP or GIF signature at the start of the data", + "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data", )), } } @@ -363,9 +387,10 @@ pub fn info(data: &[u8]) -> Result { Some(ImageFormat::Jpeg) => jpeg::info(data), Some(ImageFormat::WebP) => webp::info(data), Some(ImageFormat::Gif) => gif::info(data), + Some(ImageFormat::Bmp) => bmp::info(data), None => Err(Error::unsupported( "image", - "no PNG, JPEG, WebP or GIF signature at the start of the data", + "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data", )), } } diff --git a/crates/ec-image/tests/differential.rs b/crates/ec-image/tests/differential.rs index d6059bae..4b8d6a63 100644 --- a/crates/ec-image/tests/differential.rs +++ b/crates/ec-image/tests/differential.rs @@ -540,3 +540,93 @@ fn webp_disposal_and_blending_match_libwebp() { let delays: Vec = ours.iter().map(|f| f.delay_num).collect(); assert_eq!(delays, vec![60, 90, 30], "per-frame durations in ms"); } + +/// BMP is a lossless container of raw samples, so the only question is whether +/// the two decoders read the same header the same way. +#[test] +fn bmp_decodes_pixel_exactly() { + let files = corpus("bmp"); + if files.is_empty() && skip("bmp") { + return; + } + for path in files { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + if name.starts_with("embedded-") || name == "os2v2.bmp" { + continue; // the incumbent refuses both; their own tests cover them + } + let data = std::fs::read(&path).unwrap(); + let ours = ec_image::decode(&data).unwrap_or_else(|e| panic!("{name}: {e}")); + let theirs = image::load_from_memory(&data).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!( + (ours.width, ours.height), + theirs.dimensions(), + "{name}: dimensions differ" + ); + let (max, corr) = compare(&ours.to_rgba8(), &theirs.to_rgba8().into_raw()); + println!("{name:>16} max {max} corr {corr:.6}"); + assert_eq!(max, 0, "{name}: samples differ from the incumbent"); + } +} + +/// `BI_PNG` and `BI_JPEG` are a BMP header wrapped around a whole file of +/// another format. The incumbent refuses both, so the oracle is the incumbent +/// decoding the *payload* directly: reading the wrapper must reach the same +/// picture as reading what it wraps. +#[test] +fn a_bmp_wrapping_another_format_decodes_to_that_format() { + // The JPEG bar is the same 5 the plain JPEG comparison uses: the IDCT is + // implementation-defined, so the two decoders round differently. + for (fixture, bar) in [("embedded-png.bmp", 0u32), ("embedded-jpeg.bmp", 5)] { + let path = fixtures().join(fixture); + let Ok(data) = std::fs::read(&path) else { + if skip(fixture) { + return; + } + unreachable!() + }; + // The payload starts where the file header says the pixels do. + let offset = u32::from_le_bytes([data[10], data[11], data[12], data[13]]) as usize; + let payload = &data[offset..]; + let ours = ec_image::decode(&data).unwrap_or_else(|e| panic!("{fixture}: {e}")); + let theirs = image::load_from_memory(payload).unwrap(); + assert_eq!( + (ours.width, ours.height), + theirs.dimensions(), + "{fixture}: dimensions differ" + ); + let (max, corr) = compare(&ours.to_rgba8(), &theirs.to_rgba8().into_raw()); + println!("{fixture:>20} max {max} corr {corr:.6}"); + assert!(max <= bar, "{fixture}: max delta {max} over the bar {bar}"); + assert_eq!( + ec_image::info(&data).unwrap().width, + theirs.dimensions().0, + "{fixture}: the header-only path disagrees with the pixels" + ); + } +} + +/// The 16-byte OS/2 v2 header, which the incumbent refuses outright +/// ("Unknown bitmap header type (size=16)") and ffmpeg reads. The oracle is +/// therefore the same picture in a header both decoders read: the two files +/// carry identical rows, so the pixels must come out identical too. +#[test] +fn an_os2_v2_header_reads_as_the_same_picture() { + let short = fixtures().join("os2v2.bmp"); + let long = fixtures().join("os2v1.bmp"); + let (Ok(short), Ok(long)) = (std::fs::read(&short), std::fs::read(&long)) else { + skip("os2v2.bmp"); + return; + }; + assert!( + image::load_from_memory(&short).is_err(), + "the incumbent now reads a 16-byte header; this test's premise is stale" + ); + let ours = ec_image::decode(&short).unwrap(); + let reference = image::load_from_memory(&long).unwrap(); + assert_eq!((ours.width, ours.height), reference.dimensions()); + let (max, _) = compare(&ours.to_rgba8(), &reference.to_rgba8().into_raw()); + assert_eq!( + max, 0, + "os2v2.bmp: samples differ from the same picture in a v1 header" + ); +} diff --git a/crates/ec-image/tests/fuzz.rs b/crates/ec-image/tests/fuzz.rs index 55efc4c7..ac637aae 100644 --- a/crates/ec-image/tests/fuzz.rs +++ b/crates/ec-image/tests/fuzz.rs @@ -197,13 +197,33 @@ fn an_animated_webp_survives_mutation() { eprintln!("webp-animation: {ROUNDS} mutations, {decoded} still decoded"); } +/// BMP sizes three separate things from header fields -- a palette, a row +/// stride and, for the run-length compressions, a decoded row buffer -- so a +/// mutation can put any two of them in disagreement. +#[test] +fn bmp_survives_mutation() { + sweep("bmp", "tiny.bmp"); +} + +/// The run-length path is the one that writes at a position the *file* chooses +/// (delta codes move the cursor), so it gets its own seed. +#[test] +fn a_run_length_bmp_survives_mutation() { + sweep("bmp-rle", "rle8.bmp"); +} + #[test] fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() { - let signatures: [&[u8]; 4] = [ + let signatures: [&[u8]; 5] = [ &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a], &[0xff, 0xd8, 0xff, 0xe0], b"RIFF\x40\x00\x00\x00WEBPVP8 ", b"GIF89a", + // "BM" alone is two bytes anything could start with, so the guess also + // asks the file header to agree with itself: this prefix declares a + // 40-byte info header and pixels at 54, which is what makes the bytes + // behind it reach the decoder at all. + b"BM\x00\x10\x00\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00", ]; let mut rng = Rng(0x9e37_79b9_7f4a_7c15); for signature in signatures { diff --git a/lanes/image-bmp-r1.report.md b/lanes/image-bmp-r1.report.md new file mode 100644 index 00000000..4f65c5fb --- /dev/null +++ b/lanes/image-bmp-r1.report.md @@ -0,0 +1,113 @@ +# lane-image-bmp r1 — a BMP decoder for the gpui surface + +`gpui` names `ImageFormat::Bmp`, so the shim needs a decoder behind it. This +lane adds `crates/ec-image/src/bmp.rs`, wires the format through `ec_image`'s +guess/decode/info dispatch, generates a fourteen-file BMP corpus and gates it +against the incumbent `image` 0.25.10. + +## What the decoder reads + +| shape | fixture | source | +| --- | --- | --- | +| 1-bit palette | `mono.bmp` | ImageMagick | +| 4-bit palette | `pal4.bmp` | ImageMagick | +| 8-bit palette | `pal8.bmp` | ImageMagick | +| RLE8 | `rle8.bmp` | ImageMagick | +| RLE4 | `rle4.bmp` | helper (ImageMagick's RLE switch always picks 8-bit) | +| 16-bit 5-5-5, `BI_RGB` | `rgb555.bmp` | helper | +| 16-bit 5-6-5, `BI_BITFIELDS` | `bf565.bmp` | helper | +| 24-bit | `rgb24.bmp`, `odd24.bmp` (37x29) | ImageMagick | +| 32-bit + alpha, `BITMAPV4HEADER` | `alpha32.bmp` | helper | +| 32-bit + alpha, `BITMAPV5HEADER` | `v5alpha.bmp` | ImageMagick | +| top-down rows (negative height) | `topdown24.bmp` | helper | +| 12-byte OS/2 v1 header | `os2v1.bmp` | helper | +| 16-byte OS/2 v2 header | `os2v2.bmp` | helper | +| `BI_PNG` / `BI_JPEG` wrappers | `embedded-png.bmp`, `embedded-jpeg.bmp` | helper | + +The helper is `scripts/lib/gen-bmp-shapes.py`, called from +`scripts/gen-still-fixtures.sh`; it writes from the same raw RGBA dump the +ImageMagick files come from, so every fixture is the same picture. + +## Gate + +`cargo test -p ec-image --test differential bmp` + +| fixture | max sample delta vs incumbent | corr | +| --- | --- | --- | +| alpha32.bmp | 0 | 1.000000 | +| bf565.bmp | 0 | 1.000000 | +| mono.bmp | 0 | 1.000000 | +| odd24.bmp | 0 | 1.000000 | +| os2v1.bmp | 0 | 1.000000 | +| pal4.bmp | 0 | 1.000000 | +| pal8.bmp | 0 | 1.000000 | +| rgb24.bmp | 0 | 1.000000 | +| rgb555.bmp | 0 | 1.000000 | +| rle4.bmp | 0 | 1.000000 | +| rle8.bmp | 0 | 1.000000 | +| tiny.bmp | 0 | 1.000000 | +| topdown24.bmp | 0 | 1.000000 | +| v5alpha.bmp | 0 | 1.000000 | + +Fourteen of fourteen pixel-exact. BMP is a lossless container of raw samples, +so anything else would be a header read differently. + +Three fixtures the incumbent cannot arbitrate, each with its own test: + +- `embedded-png.bmp` / `embedded-jpeg.bmp` — `image` refuses `BI_PNG` and + `BI_JPEG` outright. The oracle is the incumbent decoding the *payload* + directly: max delta 0 for the PNG wrapper, 3 for the JPEG one (bar 5, the + same bar the plain JPEG comparison uses — the IDCT is implementation-defined). + `a_bmp_wrapping_another_format_decodes_to_that_format` also checks the + header-only path agrees with the pixels. +- `os2v2.bmp` — `image` answers "Unknown bitmap header type (size=16)"; + ffmpeg's BMP decoder reads 16-byte headers, so the format is read here too. + The oracle is the same picture in a v1 header: + `an_os2_v2_header_reads_as_the_same_picture` asserts pixel equality, and + asserts the incumbent still refuses, so the test fails loudly if that premise + goes stale. + +## Fuzz + +`cargo test -p ec-image --test fuzz --release`, 10 000 mutations each from a +fixed seed: + +| sweep | seed file | decoded | panics | +| --- | --- | --- | --- | +| `bmp_survives_mutation` | `tiny.bmp` | 2557 | 0 | +| `a_run_length_bmp_survives_mutation` | `rle8.bmp` | 4730 | 0 | + +The run-length path gets its own sweep because it is the one that writes at a +position the *file* chooses — RLE delta codes move the cursor. A fifth +signature was added to +`arbitrary_bytes_behind_a_signature_are_refused_not_believed`: "BM" alone is +two bytes anything could start with, so `ImageFormat::guess` also requires the +file header to agree with itself (a defined info-header length, pixels after +the headers) before the bytes reach the decoder. + +## Refusals + +None left in `bmp.rs`. The two shapes first written as refusals — embedded +PNG/JPEG payloads and the short OS/2 v2 header — are decoded instead: +the payloads by delegating to this crate's own PNG and JPEG decoders, the +short header by reading its first 16 bytes, which are the Windows layout. +What remains rejected is corrupt input, not an absent capability: an info +header shorter than 12 bytes, a bit depth the format does not define, a +run-length compression at the wrong depth, a zero-sized picture. + +## Shim + +`shims/image` maps `ec_image::ImageFormat::Bmp` to its own `ImageFormat::Bmp`, +which — like `Gif` and `Tiff` — exists only behind the `gpui` feature, since +gpui is the only consumer that names it. `cargo test -p image --features gpui` +is 9/9; the default build is 4/4. + +## His library + +No BMP files exist under `~/Downloads`, `~/Videos` or `~/Pictures` (`find -iname +'*.bmp'` returns nothing), so there is no real-library sweep to run for this +format. Fixture-verified only, and that is the whole population. + +## Left + +TIFF, the third format `gpui` names, is not started. diff --git a/scripts/gen-still-fixtures.sh b/scripts/gen-still-fixtures.sh index 5fde0342..ec9b76aa 100755 --- a/scripts/gen-still-fixtures.sh +++ b/scripts/gen-still-fixtures.sh @@ -136,6 +136,33 @@ magick -delay 7 "$out/source.png" -delay 13 "$out/source-flat.png" \ -delay 4 "$out/source-odd.png" -dispose Background -loop 0 -colors 64 \ "$out/animated.gif" +# --- BMP: every depth, both compressions, both row orders ------------------ +# ImageMagick writes the ordinary files; the shapes it has no switch for (16-bit +# bitfields, top-down rows, a 32-bit alpha channel, the 12-byte OS/2 header, +# and RLE4, which its RLE switch never chooses) are written by the helper. +magick "$out/source.png" -resize 64x48! "$out/bmp-source.png" +magick "$out/source-alpha.png" -resize 64x48! "$out/bmp-source-alpha.png" +magick "$out/bmp-source.png" -monochrome -type bilevel BMP3:"$out/mono.bmp" +magick "$out/bmp-source.png" -colors 16 -type palette -depth 4 -compress None \ + BMP3:"$out/pal4.bmp" +magick "$out/bmp-source.png" -colors 256 -type palette -compress None \ + BMP3:"$out/pal8.bmp" +magick "$out/bmp-source.png" -colors 256 -type palette -compress RLE \ + BMP3:"$out/rle8.bmp" +magick "$out/bmp-source.png" BMP3:"$out/rgb24.bmp" +magick "$out/source-odd.png" -resize 37x29! BMP3:"$out/odd24.bmp" +# A BITMAPV5HEADER, whose 124 bytes carry the colour space fields a v3 file +# has no room for; ImageMagick writes one when asked for alpha. +magick "$out/bmp-source-alpha.png" -define bmp:format=bmp5 BMP:"$out/v5alpha.bmp" +magick "$out/bmp-source.png" rgba:"$out/bmp-source.rgba" +magick "$out/bmp-source-alpha.png" rgba:"$out/bmp-source-alpha.rgba" +magick "$out/bmp-source.png" "$out/bmp-embed.png" +magick "$out/bmp-source.png" -quality 85 "$out/bmp-embed.jpg" +python3 "$(dirname "$0")/lib/gen-bmp-shapes.py" "$out" "$out/bmp-source.rgba" 64 48 \ + "$out/bmp-source-alpha.rgba" "$out/bmp-embed.png" "$out/bmp-embed.jpg" +rm -f "$out/bmp-source.png" "$out/bmp-source-alpha.png" "$out/bmp-source.rgba" \ + "$out/bmp-source-alpha.rgba" "$out/bmp-embed.png" "$out/bmp-embed.jpg" + # Small versions of each format, for the fuzz sweep: ten thousand mutations # per format is only affordable on a picture that decodes in microseconds. magick "$out/source.png" -resize 32x24! "$out/tiny.png" @@ -144,5 +171,6 @@ ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 0 -quality 7 "$out/tiny-lossy.webp" ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 1 "$out/tiny-lossless.webp" magick "$out/tiny.png" -colors 64 "$out/tiny.gif" +magick "$out/tiny.png" -colors 64 -type palette -compress None BMP3:"$out/tiny.bmp" echo "wrote $(ls "$out" | wc -l) files to $out" diff --git a/scripts/lib/gen-bmp-shapes.py b/scripts/lib/gen-bmp-shapes.py new file mode 100644 index 00000000..4ea963f4 --- /dev/null +++ b/scripts/lib/gen-bmp-shapes.py @@ -0,0 +1,168 @@ +"""Write the BMP shapes ImageMagick will not emit. + +ImageMagick covers the ordinary files (1/4/8-bit palettes, RLE8, 24-bit), but +it has no switch for a 16-bit bitfield file, a top-down row order, a 32-bit +file with an alpha channel, or the 12-byte OS/2 header -- all of which are +shapes a decoder meets in the wild. Each is written here from a raw RGBA dump +so the pixels are the same picture as the rest of the corpus. +""" + +import struct +import sys + +out, raw, width, height = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4]) +rgba = open(raw, "rb").read() +rgba_alpha = open(sys.argv[5], "rb").read() + + +def pixel(source, x, y): + at = (y * width + x) * 4 + return source[at], source[at + 1], source[at + 2], source[at + 3] + + +def rows(top_down, source=None): + source = rgba if source is None else source + order = range(height) if top_down else range(height - 1, -1, -1) + return [[pixel(source, x, y) for x in range(width)] for y in order] + + +def file_header(offset, size): + return b"BM" + struct.pack("> 3) << 11) | ((p[1] >> 2) << 5) | (p[2] >> 3))) +write("bf565.bmp", info_v3(16, 3), body, masks565) + +# 16-bit, 5-5-5, the layout BI_RGB implies at this depth (no mask block). +body = packed(16, lambda p: struct.pack( + "> 3) << 10) | ((p[1] >> 3) << 5) | (p[2] >> 3))) +write("rgb555.bmp", info_v3(16, 0), body) + +# 32-bit with an alpha channel: the fourth mask only has a home in the +# BITMAPV4HEADER, whose 108 bytes carry all four masks plus a colour space. +body = packed(32, lambda p: bytes([p[2], p[1], p[0], p[3]]), source=rgba_alpha) +v4 = struct.pack( + "> 4 if x % 2 == 0 else byte & 0x0F) + x = 0 + while x < w: + run = 1 + while x + run < w and run < 254 and indices[x + run] == indices[x]: + run += 1 + if run >= 2: + body += bytes([run, indices[x] << 4 | indices[x]]) + x += run + continue + # A literal run needs at least three pixels to be legal; below that + # the encoded form is a run of one. + end = x + while end < w and end - x < 254: + same = 1 + while end + same < w and indices[end + same] == indices[end]: + same += 1 + if same >= 3: + break + end += same + count = end - x + if count < 3: + body += bytes([1, indices[x] << 4]) + x += 1 + continue + nibbles = bytearray() + for i in range(0, count, 2): + high = indices[x + i] << 4 + low = indices[x + i + 1] if i + 1 < count else 0 + nibbles.append(high | low) + while len(nibbles) % 2: + nibbles.append(0) + body += bytes([0, count]) + nibbles + x = end + body += b"\x00\x00" + body = body[:-2] + b"\x00\x01" + info = struct.pack(" Option { ec_image::ImageFormat::Png => Some(ImageFormat::Png), ec_image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg), ec_image::ImageFormat::WebP => Some(ImageFormat::WebP), - // Only the gpui half of this shim names the animated formats; a build - // without it has no variant to answer with. + // Only the gpui half of this shim names the formats gpui asks for; a + // build without it has no variant to answer with. #[cfg(feature = "gpui")] ec_image::ImageFormat::Gif => Some(ImageFormat::Gif), #[cfg(not(feature = "gpui"))] ec_image::ImageFormat::Gif => None, + #[cfg(feature = "gpui")] + ec_image::ImageFormat::Bmp => Some(ImageFormat::Bmp), + #[cfg(not(feature = "gpui"))] + ec_image::ImageFormat::Bmp => None, } }