forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-image-bmp': a BMP decoder for the gpui surface

Browse files at this commit

463079bf14432ff4dee575684f513afd9feb8d94Ahmet Kaan GümüşParent: c6f0f87f1f296e
crates/ec-image/src/bmp.rsadded+496 -0
@@ -0,0 +1,496 @@
1+//! BMP: the Windows device-independent bitmap, as `image` and every screenshot
2+//! tool on Windows write it.
3+//!
4+//! One file header, one info header, an optional palette and then rows, and
5+//! almost all of the difficulty is in how many shapes those four things take:
6+//! headers of five different lengths, samples 1, 2, 4, 8, 16, 24 or 32 bits
7+//! wide, palettes with three-byte or four-byte entries, rows stored bottom-up
8+//! or top-down, run-length encoding for the 4- and 8-bit forms, and arbitrary
9+//! channel masks under `BI_BITFIELDS`.
10+//!
11+//! `BI_PNG` and `BI_JPEG` files are a BMP header wrapped around a whole PNG or
12+//! JPEG file, so they are handed to those decoders rather than refused.
13+//!
14+//! An OS/2 v2 header is read through its first 16 bytes, which is where it
15+//! stops agreeing with the Windows one; the fields past that describe halftoning
16+//! and a colour table format no writer emits. ICC profiles in a v5 header are
17+//! metadata this crate does not carry, so they are ignored rather than refused.
18+
19+use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels};
20+use ec_core::{Error, Result};
21+
22+/// Fields of the info header this decoder acts on.
23+struct Header {
24+ width: u32,
25+ height: u32,
26+ /// Rows are stored bottom-up unless the height was negative.
27+ top_down: bool,
28+ bits: u16,
29+ compression: u32,
30+ /// Palette entries actually present in the file.
31+ colours: usize,
32+ /// Bytes per palette entry: 4 in a Windows header, 3 in an OS/2 one.
33+ palette_stride: usize,
34+ /// Where the info header ends and the palette begins.
35+ palette_at: usize,
36+ /// Channel masks, present under `BI_BITFIELDS` and defaulted otherwise.
37+ masks: [u32; 4],
38+}
39+
40+const BI_RGB: u32 = 0;
41+const BI_RLE8: u32 = 1;
42+const BI_RLE4: u32 = 2;
43+const BI_BITFIELDS: u32 = 3;
44+const BI_JPEG: u32 = 4;
45+const BI_PNG: u32 = 5;
46+const BI_ALPHABITFIELDS: u32 = 6;
47+
48+fn u16_at(data: &[u8], at: usize) -> Result<u16> {
49+ data.get(at..at + 2)
50+ .map(|b| u16::from_le_bytes([b[0], b[1]]))
51+ .ok_or_else(|| Error::corrupt("BMP: header runs past the file"))
52+}
53+
54+fn u32_at(data: &[u8], at: usize) -> Result<u32> {
55+ data.get(at..at + 4)
56+ .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
57+ .ok_or_else(|| Error::corrupt("BMP: header runs past the file"))
58+}
59+
60+/// Parse the file and info headers.
61+fn header(data: &[u8]) -> Result<Header> {
62+ if !data.starts_with(b"BM") {
63+ return Err(Error::corrupt("BMP: no BM signature"));
64+ }
65+ let info_size = u32_at(data, 14)? as usize;
66+ // 12 is the OS/2 v1 header (BITMAPCOREHEADER), 40 the Windows v3 one, and
67+ // 52/56/108/124 are v3 plus masks, v4 and v5. Everything past the first 40
68+ // bytes is colour-space description this crate does not carry.
69+ let (width, height, top_down, bits, compression, declared_colours) = if info_size == 12 {
70+ (
71+ u32::from(u16_at(data, 18)?),
72+ u32::from(u16_at(data, 20)?),
73+ false,
74+ u16_at(data, 24)?,
75+ BI_RGB,
76+ 0usize,
77+ )
78+ } else if (16..40).contains(&info_size) {
79+ // An OS/2 v2 header, whose first 16 bytes are the Windows layout: the
80+ // dimensions are 32-bit and there is no compression field at all.
81+ let raw_height = u32_at(data, 22)? as i32;
82+ (
83+ u32_at(data, 18)?,
84+ raw_height.unsigned_abs(),
85+ raw_height < 0,
86+ u16_at(data, 28)?,
87+ BI_RGB,
88+ 0usize,
89+ )
90+ } else if info_size >= 40 {
91+ let raw_height = u32_at(data, 22)? as i32;
92+ (
93+ u32_at(data, 18)?,
94+ raw_height.unsigned_abs(),
95+ raw_height < 0,
96+ u16_at(data, 28)?,
97+ u32_at(data, 30)?,
98+ u32_at(data, 46)? as usize,
99+ )
100+ } else {
101+ return Err(Error::corrupt(format!(
102+ "BMP: a {info_size}-byte info header, shorter than any the format defines"
103+ )));
104+ };
105+
106+ if !matches!(bits, 1 | 2 | 4 | 8 | 16 | 24 | 32) {
107+ return Err(Error::corrupt(format!("BMP: {bits} bits per pixel")));
108+ }
109+ match compression {
110+ // Handled before the header is read; reaching here means the caller
111+ // asked for the fields of a file that has none of them.
112+ BI_JPEG | BI_PNG => {}
113+ BI_RGB | BI_RLE8 | BI_RLE4 | BI_BITFIELDS | BI_ALPHABITFIELDS => {}
114+ other => {
115+ return Err(Error::corrupt(format!("BMP: compression {other}")));
116+ }
117+ }
118+ if (compression == BI_RLE8 && bits != 8) || (compression == BI_RLE4 && bits != 4) {
119+ return Err(Error::corrupt(format!(
120+ "BMP: run-length encoding with {bits} bits per pixel"
121+ )));
122+ }
123+
124+ // Under BI_BITFIELDS the masks follow the 40-byte header in a v3 file and
125+ // live inside a v4/v5 one; either way they start at offset 54.
126+ let bitfields = compression == BI_BITFIELDS || compression == BI_ALPHABITFIELDS;
127+ let mut masks = [0u32; 4];
128+ let mut palette_at = 14 + info_size;
129+ if bitfields && info_size == 40 {
130+ for (i, mask) in masks.iter_mut().enumerate().take(3) {
131+ *mask = u32_at(data, 54 + i * 4)?;
132+ }
133+ if compression == BI_ALPHABITFIELDS {
134+ masks[3] = u32_at(data, 66)?;
135+ }
136+ palette_at += 12
137+ + if compression == BI_ALPHABITFIELDS {
138+ 4
139+ } else {
140+ 0
141+ };
142+ } else if bitfields {
143+ for (i, mask) in masks.iter_mut().enumerate() {
144+ *mask = u32_at(data, 54 + i * 4)?;
145+ }
146+ } else if info_size >= 108 {
147+ // A v4 header carries masks whether or not BI_BITFIELDS is set; they
148+ // are only meaningful for the 16- and 32-bit forms.
149+ for (i, mask) in masks.iter_mut().enumerate() {
150+ *mask = u32_at(data, 54 + i * 4)?;
151+ }
152+ }
153+ if masks[..3].iter().all(|&m| m == 0) {
154+ // The defaults the format documents: 5-5-5 at 16 bits, 8-8-8 at 24 and
155+ // 32, with the top eight bits of a 32-bit sample unused.
156+ masks = match bits {
157+ 16 => [0x7c00, 0x03e0, 0x001f, 0],
158+ _ => [0x00ff_0000, 0x0000_ff00, 0x0000_00ff, 0],
159+ };
160+ }
161+
162+ let palette_stride = if info_size == 12 { 3 } else { 4 };
163+ let colours = if bits <= 8 {
164+ let max = 1usize << bits;
165+ // Zero means "as many as the depth allows"; a larger claim than the
166+ // depth allows is the file lying about itself.
167+ if declared_colours == 0 || declared_colours > max {
168+ max
169+ } else {
170+ declared_colours
171+ }
172+ } else {
173+ 0
174+ };
175+
176+ Ok(Header {
177+ width,
178+ height,
179+ top_down,
180+ bits,
181+ compression,
182+ colours,
183+ palette_stride,
184+ palette_at,
185+ masks,
186+ })
187+}
188+
189+/// Dimensions from the headers alone.
190+pub fn info(data: &[u8]) -> Result<Info> {
191+ if let Some(embedded) = embedded(data)? {
192+ let mut info = match embedded.0 {
193+ ImageFormat::Png => crate::png::info(embedded.1)?,
194+ _ => crate::jpeg::info(embedded.1)?,
195+ };
196+ // The wrapper is what the caller opened, so it is what they are told.
197+ info.format = ImageFormat::Bmp;
198+ return Ok(info);
199+ }
200+ let header = header(data)?;
201+ Ok(Info {
202+ format: ImageFormat::Bmp,
203+ width: header.width,
204+ height: header.height,
205+ })
206+}
207+
208+/// The payload of a `BI_PNG` or `BI_JPEG` file, which is a whole file of that
209+/// other format rather than any arrangement of BMP rows.
210+///
211+/// `biSizeImage` is the payload's length; a zero there means the writer left it
212+/// out, and the rest of the file is the payload.
213+fn embedded(data: &[u8]) -> Result<Option<(ImageFormat, &[u8])>> {
214+ if !data.starts_with(b"BM") || u32_at(data, 14)? < 40 {
215+ return Ok(None);
216+ }
217+ let format = match u32_at(data, 30)? {
218+ BI_PNG => ImageFormat::Png,
219+ BI_JPEG => ImageFormat::Jpeg,
220+ _ => return Ok(None),
221+ };
222+ let offset = u32_at(data, 10)? as usize;
223+ let payload = data
224+ .get(offset..)
225+ .ok_or_else(|| Error::corrupt("BMP: the payload offset is past the file"))?;
226+ let declared = u32_at(data, 34)? as usize;
227+ let payload = if declared == 0 || declared > payload.len() {
228+ payload
229+ } else {
230+ &payload[..declared]
231+ };
232+ Ok(Some((format, payload)))
233+}
234+
235+/// A channel mask reduced to a shift and a scale.
236+///
237+/// Masks are arbitrary -- a 16-bit file may carry 5-6-5, 5-5-5 or anything
238+/// else -- so each channel is read as a field and stretched to eight bits so
239+/// that a full-scale field becomes 255 rather than 248.
240+struct Field {
241+ shift: u32,
242+ max: u32,
243+}
244+
245+impl Field {
246+ fn new(mask: u32) -> Option<Field> {
247+ if mask == 0 {
248+ return None;
249+ }
250+ let shift = mask.trailing_zeros();
251+ Some(Field {
252+ shift,
253+ max: mask >> shift,
254+ })
255+ }
256+
257+ fn sample(&self, raw: u32, mask: u32) -> u8 {
258+ let value = (raw & mask) >> self.shift;
259+ if self.max == 0 {
260+ return 0;
261+ }
262+ ((value * 255 + self.max / 2) / self.max) as u8
263+ }
264+}
265+
266+/// Decode a BMP file.
267+pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
268+ if let Some((format, payload)) = embedded(data)? {
269+ return match format {
270+ ImageFormat::Png => crate::png::decode(payload, limits),
271+ _ => crate::jpeg::decode(payload, limits),
272+ };
273+ }
274+ let header = header(data)?;
275+ limits.check(header.width, header.height)?;
276+ let (width, height) = (header.width as usize, header.height as usize);
277+ if width == 0 || height == 0 {
278+ return Err(Error::corrupt("BMP: a zero-sized picture"));
279+ }
280+
281+ let palette = palette(data, &header)?;
282+ let offset = u32_at(data, 10)? as usize;
283+ let body = data
284+ .get(offset..)
285+ .ok_or_else(|| Error::corrupt("BMP: the pixel offset is past the file"))?;
286+
287+ // Indices first, then colour: every form below produces either palette
288+ // indices or direct samples, and the bottom-up flip is the same either way.
289+ let has_alpha = header.masks[3] != 0
290+ || (header.bits == 32 && header.compression == BI_RGB && palette.is_empty());
291+ let mut out = vec![0u8; width * height * if has_alpha { 4 } else { 3 }];
292+ let channels = if has_alpha { 4 } else { 3 };
293+ let row_of = |y: usize| if header.top_down { y } else { height - 1 - y };
294+
295+ match header.compression {
296+ BI_RLE8 | BI_RLE4 => {
297+ let indices = rle(body, &header)?;
298+ for y in 0..height {
299+ for x in 0..width {
300+ let index = indices[y * width + x] as usize;
301+ let rgb = *palette
302+ .get(index)
303+ .ok_or_else(|| Error::corrupt("BMP: palette index past the table"))?;
304+ let at = (row_of(y) * width + x) * channels;
305+ out[at..at + 3].copy_from_slice(&rgb);
306+ if has_alpha {
307+ out[at + 3] = 255;
308+ }
309+ }
310+ }
311+ }
312+ _ => {
313+ // Rows are padded to a four-byte boundary.
314+ let stride = (width * usize::from(header.bits))
315+ .div_ceil(8)
316+ .next_multiple_of(4);
317+ if body.len() < stride * height {
318+ return Err(Error::corrupt(format!(
319+ "BMP: {} bytes of pixels, {} rows of {stride} needed",
320+ body.len(),
321+ height
322+ )));
323+ }
324+ let fields = [
325+ Field::new(header.masks[0]),
326+ Field::new(header.masks[1]),
327+ Field::new(header.masks[2]),
328+ Field::new(header.masks[3]),
329+ ];
330+ for y in 0..height {
331+ let row = &body[y * stride..y * stride + stride];
332+ for x in 0..width {
333+ let at = (row_of(y) * width + x) * channels;
334+ let (rgb, alpha) = match header.bits {
335+ 1 | 2 | 4 | 8 => {
336+ let bits = usize::from(header.bits);
337+ let bit = x * bits;
338+ let byte = row[bit / 8];
339+ let shift = 8 - bits - (bit % 8);
340+ let index = usize::from((byte >> shift) & ((1 << bits) - 1) as u8);
341+ let rgb = *palette.get(index).ok_or_else(|| {
342+ Error::corrupt("BMP: palette index past the table")
343+ })?;
344+ (rgb, 255)
345+ }
346+ 16 => {
347+ let raw = u32::from(u16::from_le_bytes([row[x * 2], row[x * 2 + 1]]));
348+ sample(raw, &header.masks, &fields)
349+ }
350+ 24 => ([row[x * 3 + 2], row[x * 3 + 1], row[x * 3]], 255),
351+ _ => {
352+ let raw = u32::from_le_bytes([
353+ row[x * 4],
354+ row[x * 4 + 1],
355+ row[x * 4 + 2],
356+ row[x * 4 + 3],
357+ ]);
358+ sample(raw, &header.masks, &fields)
359+ }
360+ };
361+ out[at..at + 3].copy_from_slice(&rgb);
362+ if has_alpha {
363+ out[at + 3] = alpha;
364+ }
365+ }
366+ }
367+ }
368+ }
369+
370+ Ok(Image {
371+ width: header.width,
372+ height: header.height,
373+ pixels: if has_alpha {
374+ Pixels::Rgba8(out)
375+ } else {
376+ Pixels::Rgb8(out)
377+ },
378+ meta: Metadata::default(),
379+ })
380+}
381+
382+/// One direct-colour pixel through the channel masks.
383+fn sample(raw: u32, masks: &[u32; 4], fields: &[Option<Field>; 4]) -> ([u8; 3], u8) {
384+ let mut rgb = [0u8; 3];
385+ for c in 0..3 {
386+ if let Some(field) = &fields[c] {
387+ rgb[c] = field.sample(raw, masks[c]);
388+ }
389+ }
390+ let alpha = match &fields[3] {
391+ Some(field) => field.sample(raw, masks[3]),
392+ None => 255,
393+ };
394+ (rgb, alpha)
395+}
396+
397+/// The palette, as RGB triples in file order.
398+fn palette(data: &[u8], header: &Header) -> Result<Vec<[u8; 3]>> {
399+ if header.colours == 0 {
400+ return Ok(Vec::new());
401+ }
402+ let mut out = Vec::with_capacity(header.colours);
403+ for i in 0..header.colours {
404+ let at = header.palette_at + i * header.palette_stride;
405+ let entry = data
406+ .get(at..at + 3)
407+ .ok_or_else(|| Error::corrupt("BMP: the palette runs past the file"))?;
408+ // Entries are stored blue first.
409+ out.push([entry[2], entry[1], entry[0]]);
410+ }
411+ Ok(out)
412+}
413+
414+/// Expand `BI_RLE8` or `BI_RLE4` into one palette index per pixel.
415+///
416+/// The two forms share a structure: a non-zero first byte is a run, a zero
417+/// introduces an escape -- end of line, end of file, a delta, or a literal run
418+/// padded to an even number of bytes. Pixels the encoding never reaches keep
419+/// index zero, which is what the format means by a sparse image.
420+fn rle(body: &[u8], header: &Header) -> Result<Vec<u8>> {
421+ let (width, height) = (header.width as usize, header.height as usize);
422+ let mut out = vec![0u8; width * height];
423+ let (mut x, mut y) = (0usize, 0usize);
424+ let mut at = 0usize;
425+ let four_bit = header.compression == BI_RLE4;
426+
427+ let put = |out: &mut Vec<u8>, x: &mut usize, y: usize, index: u8| {
428+ if *x < width && y < height {
429+ out[y * width + *x] = index;
430+ }
431+ *x += 1;
432+ };
433+
434+ while at + 1 < body.len() {
435+ let (count, value) = (body[at], body[at + 1]);
436+ at += 2;
437+ if count > 0 {
438+ for i in 0..usize::from(count) {
439+ let index = if four_bit {
440+ if i % 2 == 0 { value >> 4 } else { value & 0x0f }
441+ } else {
442+ value
443+ };
444+ put(&mut out, &mut x, y, index);
445+ }
446+ continue;
447+ }
448+ match value {
449+ // End of line.
450+ 0 => {
451+ x = 0;
452+ y += 1;
453+ }
454+ // End of the bitmap; anything after it is padding.
455+ 1 => break,
456+ // A delta: move right and down by the next two bytes.
457+ 2 => {
458+ let delta = body
459+ .get(at..at + 2)
460+ .ok_or_else(|| Error::corrupt("BMP: a truncated RLE delta"))?;
461+ x += usize::from(delta[0]);
462+ y += usize::from(delta[1]);
463+ at += 2;
464+ }
465+ // A literal run of `value` pixels, padded to an even byte count.
466+ literal => {
467+ let literal = usize::from(literal);
468+ let bytes = if four_bit {
469+ literal.div_ceil(2)
470+ } else {
471+ literal
472+ };
473+ let run = body
474+ .get(at..at + bytes)
475+ .ok_or_else(|| Error::corrupt("BMP: a truncated RLE literal"))?;
476+ for i in 0..literal {
477+ let index = if four_bit {
478+ if i % 2 == 0 {
479+ run[i / 2] >> 4
480+ } else {
481+ run[i / 2] & 0x0f
482+ }
483+ } else {
484+ run[i]
485+ };
486+ put(&mut out, &mut x, y, index);
487+ }
488+ at += bytes + (bytes & 1);
489+ }
490+ }
491+ if y > height {
492+ return Err(Error::corrupt("BMP: RLE runs past the last row"));
493+ }
494+ }
495+ Ok(out)
496+}
crates/ec-image/src/lib.rsmodified+28 -3
@@ -1,4 +1,4 @@
1-//! Still-image decoding: PNG, JPEG, WebP and GIF.
1+//! Still-image decoding: PNG, JPEG, WebP, GIF and BMP.
22 //!
33 //! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the
44 //! format from the leading bytes and hands back an [`Image`]: dimensions, a
@@ -31,6 +31,7 @@
3131 // what keeps the code readable against the text it comes from.
3232 #![allow(clippy::needless_range_loop)]
3333
34+pub mod bmp;
3435 pub mod gif;
3536 pub mod jpeg;
3637 pub mod png;
@@ -54,6 +55,8 @@ pub enum ImageFormat {
5455 WebP,
5556 /// GIF, still or animated (GIF87a and GIF89a).
5657 Gif,
58+ /// Windows BMP (device-independent bitmap).
59+ Bmp,
5760 }
5861
5962 impl ImageFormat {
@@ -69,6 +72,8 @@ impl ImageFormat {
6972 Some(ImageFormat::WebP)
7073 } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
7174 Some(ImageFormat::Gif)
75+ } else if is_bmp(data) {
76+ Some(ImageFormat::Bmp)
7277 } else {
7378 None
7479 }
@@ -81,10 +86,28 @@ impl ImageFormat {
8186 ImageFormat::Jpeg => "jpg",
8287 ImageFormat::WebP => "webp",
8388 ImageFormat::Gif => "gif",
89+ ImageFormat::Bmp => "bmp",
8490 }
8591 }
8692 }
8793
94+/// Whether `data` opens like a BMP.
95+///
96+/// "BM" is two bytes, which half the files on a disk could start with by
97+/// accident, so the guess also asks the file header to agree with itself: the
98+/// declared info-header length must be one the format defines, and the pixel
99+/// data must start after the headers.
100+fn is_bmp(data: &[u8]) -> bool {
101+ if !data.starts_with(b"BM") || data.len() < 18 {
102+ return false;
103+ }
104+ let u32_at =
105+ |at: usize| u32::from_le_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]);
106+ let offset = u32_at(10) as usize;
107+ let info_size = u32_at(14) as usize;
108+ matches!(info_size, 12 | 16 | 40 | 52 | 56 | 64 | 108 | 124) && offset >= 14 + info_size
109+}
110+
88111 /// Bounds applied before any buffer is sized from a header field.
89112 ///
90113 /// 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<Image> {
349372 Some(ImageFormat::Jpeg) => jpeg::decode(data, limits),
350373 Some(ImageFormat::WebP) => webp::decode(data, limits),
351374 Some(ImageFormat::Gif) => gif::decode(data, limits),
375+ Some(ImageFormat::Bmp) => bmp::decode(data, limits),
352376 None => Err(Error::unsupported(
353377 "image",
354- "no PNG, JPEG, WebP or GIF signature at the start of the data",
378+ "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data",
355379 )),
356380 }
357381 }
@@ -363,9 +387,10 @@ pub fn info(data: &[u8]) -> Result<Info> {
363387 Some(ImageFormat::Jpeg) => jpeg::info(data),
364388 Some(ImageFormat::WebP) => webp::info(data),
365389 Some(ImageFormat::Gif) => gif::info(data),
390+ Some(ImageFormat::Bmp) => bmp::info(data),
366391 None => Err(Error::unsupported(
367392 "image",
368- "no PNG, JPEG, WebP or GIF signature at the start of the data",
393+ "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data",
369394 )),
370395 }
371396 }
crates/ec-image/tests/differential.rsmodified+90 -0
@@ -540,3 +540,93 @@ fn webp_disposal_and_blending_match_libwebp() {
540540 let delays: Vec<u32> = ours.iter().map(|f| f.delay_num).collect();
541541 assert_eq!(delays, vec![60, 90, 30], "per-frame durations in ms");
542542 }
543+
544+/// BMP is a lossless container of raw samples, so the only question is whether
545+/// the two decoders read the same header the same way.
546+#[test]
547+fn bmp_decodes_pixel_exactly() {
548+ let files = corpus("bmp");
549+ if files.is_empty() && skip("bmp") {
550+ return;
551+ }
552+ for path in files {
553+ let name = path.file_name().unwrap().to_string_lossy().to_string();
554+ if name.starts_with("embedded-") || name == "os2v2.bmp" {
555+ continue; // the incumbent refuses both; their own tests cover them
556+ }
557+ let data = std::fs::read(&path).unwrap();
558+ let ours = ec_image::decode(&data).unwrap_or_else(|e| panic!("{name}: {e}"));
559+ let theirs = image::load_from_memory(&data).unwrap_or_else(|e| panic!("{name}: {e}"));
560+ assert_eq!(
561+ (ours.width, ours.height),
562+ theirs.dimensions(),
563+ "{name}: dimensions differ"
564+ );
565+ let (max, corr) = compare(&ours.to_rgba8(), &theirs.to_rgba8().into_raw());
566+ println!("{name:>16} max {max} corr {corr:.6}");
567+ assert_eq!(max, 0, "{name}: samples differ from the incumbent");
568+ }
569+}
570+
571+/// `BI_PNG` and `BI_JPEG` are a BMP header wrapped around a whole file of
572+/// another format. The incumbent refuses both, so the oracle is the incumbent
573+/// decoding the *payload* directly: reading the wrapper must reach the same
574+/// picture as reading what it wraps.
575+#[test]
576+fn a_bmp_wrapping_another_format_decodes_to_that_format() {
577+ // The JPEG bar is the same 5 the plain JPEG comparison uses: the IDCT is
578+ // implementation-defined, so the two decoders round differently.
579+ for (fixture, bar) in [("embedded-png.bmp", 0u32), ("embedded-jpeg.bmp", 5)] {
580+ let path = fixtures().join(fixture);
581+ let Ok(data) = std::fs::read(&path) else {
582+ if skip(fixture) {
583+ return;
584+ }
585+ unreachable!()
586+ };
587+ // The payload starts where the file header says the pixels do.
588+ let offset = u32::from_le_bytes([data[10], data[11], data[12], data[13]]) as usize;
589+ let payload = &data[offset..];
590+ let ours = ec_image::decode(&data).unwrap_or_else(|e| panic!("{fixture}: {e}"));
591+ let theirs = image::load_from_memory(payload).unwrap();
592+ assert_eq!(
593+ (ours.width, ours.height),
594+ theirs.dimensions(),
595+ "{fixture}: dimensions differ"
596+ );
597+ let (max, corr) = compare(&ours.to_rgba8(), &theirs.to_rgba8().into_raw());
598+ println!("{fixture:>20} max {max} corr {corr:.6}");
599+ assert!(max <= bar, "{fixture}: max delta {max} over the bar {bar}");
600+ assert_eq!(
601+ ec_image::info(&data).unwrap().width,
602+ theirs.dimensions().0,
603+ "{fixture}: the header-only path disagrees with the pixels"
604+ );
605+ }
606+}
607+
608+/// The 16-byte OS/2 v2 header, which the incumbent refuses outright
609+/// ("Unknown bitmap header type (size=16)") and ffmpeg reads. The oracle is
610+/// therefore the same picture in a header both decoders read: the two files
611+/// carry identical rows, so the pixels must come out identical too.
612+#[test]
613+fn an_os2_v2_header_reads_as_the_same_picture() {
614+ let short = fixtures().join("os2v2.bmp");
615+ let long = fixtures().join("os2v1.bmp");
616+ let (Ok(short), Ok(long)) = (std::fs::read(&short), std::fs::read(&long)) else {
617+ skip("os2v2.bmp");
618+ return;
619+ };
620+ assert!(
621+ image::load_from_memory(&short).is_err(),
622+ "the incumbent now reads a 16-byte header; this test's premise is stale"
623+ );
624+ let ours = ec_image::decode(&short).unwrap();
625+ let reference = image::load_from_memory(&long).unwrap();
626+ assert_eq!((ours.width, ours.height), reference.dimensions());
627+ let (max, _) = compare(&ours.to_rgba8(), &reference.to_rgba8().into_raw());
628+ assert_eq!(
629+ max, 0,
630+ "os2v2.bmp: samples differ from the same picture in a v1 header"
631+ );
632+}
crates/ec-image/tests/fuzz.rsmodified+21 -1
@@ -197,13 +197,33 @@ fn an_animated_webp_survives_mutation() {
197197 eprintln!("webp-animation: {ROUNDS} mutations, {decoded} still decoded");
198198 }
199199
200+/// BMP sizes three separate things from header fields -- a palette, a row
201+/// stride and, for the run-length compressions, a decoded row buffer -- so a
202+/// mutation can put any two of them in disagreement.
203+#[test]
204+fn bmp_survives_mutation() {
205+ sweep("bmp", "tiny.bmp");
206+}
207+
208+/// The run-length path is the one that writes at a position the *file* chooses
209+/// (delta codes move the cursor), so it gets its own seed.
210+#[test]
211+fn a_run_length_bmp_survives_mutation() {
212+ sweep("bmp-rle", "rle8.bmp");
213+}
214+
200215 #[test]
201216 fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() {
202- let signatures: [&[u8]; 4] = [
217+ let signatures: [&[u8]; 5] = [
203218 &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
204219 &[0xff, 0xd8, 0xff, 0xe0],
205220 b"RIFF\x40\x00\x00\x00WEBPVP8 ",
206221 b"GIF89a",
222+ // "BM" alone is two bytes anything could start with, so the guess also
223+ // asks the file header to agree with itself: this prefix declares a
224+ // 40-byte info header and pixels at 54, which is what makes the bytes
225+ // behind it reach the decoder at all.
226+ b"BM\x00\x10\x00\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00",
207227 ];
208228 let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
209229 for signature in signatures {
lanes/image-bmp-r1.report.mdadded+113 -0
@@ -0,0 +1,113 @@
1+# lane-image-bmp r1 — a BMP decoder for the gpui surface
2+
3+`gpui` names `ImageFormat::Bmp`, so the shim needs a decoder behind it. This
4+lane adds `crates/ec-image/src/bmp.rs`, wires the format through `ec_image`'s
5+guess/decode/info dispatch, generates a fourteen-file BMP corpus and gates it
6+against the incumbent `image` 0.25.10.
7+
8+## What the decoder reads
9+
10+| shape | fixture | source |
11+| --- | --- | --- |
12+| 1-bit palette | `mono.bmp` | ImageMagick |
13+| 4-bit palette | `pal4.bmp` | ImageMagick |
14+| 8-bit palette | `pal8.bmp` | ImageMagick |
15+| RLE8 | `rle8.bmp` | ImageMagick |
16+| RLE4 | `rle4.bmp` | helper (ImageMagick's RLE switch always picks 8-bit) |
17+| 16-bit 5-5-5, `BI_RGB` | `rgb555.bmp` | helper |
18+| 16-bit 5-6-5, `BI_BITFIELDS` | `bf565.bmp` | helper |
19+| 24-bit | `rgb24.bmp`, `odd24.bmp` (37x29) | ImageMagick |
20+| 32-bit + alpha, `BITMAPV4HEADER` | `alpha32.bmp` | helper |
21+| 32-bit + alpha, `BITMAPV5HEADER` | `v5alpha.bmp` | ImageMagick |
22+| top-down rows (negative height) | `topdown24.bmp` | helper |
23+| 12-byte OS/2 v1 header | `os2v1.bmp` | helper |
24+| 16-byte OS/2 v2 header | `os2v2.bmp` | helper |
25+| `BI_PNG` / `BI_JPEG` wrappers | `embedded-png.bmp`, `embedded-jpeg.bmp` | helper |
26+
27+The helper is `scripts/lib/gen-bmp-shapes.py`, called from
28+`scripts/gen-still-fixtures.sh`; it writes from the same raw RGBA dump the
29+ImageMagick files come from, so every fixture is the same picture.
30+
31+## Gate
32+
33+`cargo test -p ec-image --test differential bmp`
34+
35+| fixture | max sample delta vs incumbent | corr |
36+| --- | --- | --- |
37+| alpha32.bmp | 0 | 1.000000 |
38+| bf565.bmp | 0 | 1.000000 |
39+| mono.bmp | 0 | 1.000000 |
40+| odd24.bmp | 0 | 1.000000 |
41+| os2v1.bmp | 0 | 1.000000 |
42+| pal4.bmp | 0 | 1.000000 |
43+| pal8.bmp | 0 | 1.000000 |
44+| rgb24.bmp | 0 | 1.000000 |
45+| rgb555.bmp | 0 | 1.000000 |
46+| rle4.bmp | 0 | 1.000000 |
47+| rle8.bmp | 0 | 1.000000 |
48+| tiny.bmp | 0 | 1.000000 |
49+| topdown24.bmp | 0 | 1.000000 |
50+| v5alpha.bmp | 0 | 1.000000 |
51+
52+Fourteen of fourteen pixel-exact. BMP is a lossless container of raw samples,
53+so anything else would be a header read differently.
54+
55+Three fixtures the incumbent cannot arbitrate, each with its own test:
56+
57+- `embedded-png.bmp` / `embedded-jpeg.bmp` — `image` refuses `BI_PNG` and
58+ `BI_JPEG` outright. The oracle is the incumbent decoding the *payload*
59+ directly: max delta 0 for the PNG wrapper, 3 for the JPEG one (bar 5, the
60+ same bar the plain JPEG comparison uses — the IDCT is implementation-defined).
61+ `a_bmp_wrapping_another_format_decodes_to_that_format` also checks the
62+ header-only path agrees with the pixels.
63+- `os2v2.bmp` — `image` answers "Unknown bitmap header type (size=16)";
64+ ffmpeg's BMP decoder reads 16-byte headers, so the format is read here too.
65+ The oracle is the same picture in a v1 header:
66+ `an_os2_v2_header_reads_as_the_same_picture` asserts pixel equality, and
67+ asserts the incumbent still refuses, so the test fails loudly if that premise
68+ goes stale.
69+
70+## Fuzz
71+
72+`cargo test -p ec-image --test fuzz --release`, 10 000 mutations each from a
73+fixed seed:
74+
75+| sweep | seed file | decoded | panics |
76+| --- | --- | --- | --- |
77+| `bmp_survives_mutation` | `tiny.bmp` | 2557 | 0 |
78+| `a_run_length_bmp_survives_mutation` | `rle8.bmp` | 4730 | 0 |
79+
80+The run-length path gets its own sweep because it is the one that writes at a
81+position the *file* chooses — RLE delta codes move the cursor. A fifth
82+signature was added to
83+`arbitrary_bytes_behind_a_signature_are_refused_not_believed`: "BM" alone is
84+two bytes anything could start with, so `ImageFormat::guess` also requires the
85+file header to agree with itself (a defined info-header length, pixels after
86+the headers) before the bytes reach the decoder.
87+
88+## Refusals
89+
90+None left in `bmp.rs`. The two shapes first written as refusals — embedded
91+PNG/JPEG payloads and the short OS/2 v2 header — are decoded instead:
92+the payloads by delegating to this crate's own PNG and JPEG decoders, the
93+short header by reading its first 16 bytes, which are the Windows layout.
94+What remains rejected is corrupt input, not an absent capability: an info
95+header shorter than 12 bytes, a bit depth the format does not define, a
96+run-length compression at the wrong depth, a zero-sized picture.
97+
98+## Shim
99+
100+`shims/image` maps `ec_image::ImageFormat::Bmp` to its own `ImageFormat::Bmp`,
101+which — like `Gif` and `Tiff` — exists only behind the `gpui` feature, since
102+gpui is the only consumer that names it. `cargo test -p image --features gpui`
103+is 9/9; the default build is 4/4.
104+
105+## His library
106+
107+No BMP files exist under `~/Downloads`, `~/Videos` or `~/Pictures` (`find -iname
108+'*.bmp'` returns nothing), so there is no real-library sweep to run for this
109+format. Fixture-verified only, and that is the whole population.
110+
111+## Left
112+
113+TIFF, the third format `gpui` names, is not started.
scripts/gen-still-fixtures.shmodified+28 -0
@@ -136,6 +136,33 @@ magick -delay 7 "$out/source.png" -delay 13 "$out/source-flat.png" \
136136 -delay 4 "$out/source-odd.png" -dispose Background -loop 0 -colors 64 \
137137 "$out/animated.gif"
138138
139+# --- BMP: every depth, both compressions, both row orders ------------------
140+# ImageMagick writes the ordinary files; the shapes it has no switch for (16-bit
141+# bitfields, top-down rows, a 32-bit alpha channel, the 12-byte OS/2 header,
142+# and RLE4, which its RLE switch never chooses) are written by the helper.
143+magick "$out/source.png" -resize 64x48! "$out/bmp-source.png"
144+magick "$out/source-alpha.png" -resize 64x48! "$out/bmp-source-alpha.png"
145+magick "$out/bmp-source.png" -monochrome -type bilevel BMP3:"$out/mono.bmp"
146+magick "$out/bmp-source.png" -colors 16 -type palette -depth 4 -compress None \
147+ BMP3:"$out/pal4.bmp"
148+magick "$out/bmp-source.png" -colors 256 -type palette -compress None \
149+ BMP3:"$out/pal8.bmp"
150+magick "$out/bmp-source.png" -colors 256 -type palette -compress RLE \
151+ BMP3:"$out/rle8.bmp"
152+magick "$out/bmp-source.png" BMP3:"$out/rgb24.bmp"
153+magick "$out/source-odd.png" -resize 37x29! BMP3:"$out/odd24.bmp"
154+# A BITMAPV5HEADER, whose 124 bytes carry the colour space fields a v3 file
155+# has no room for; ImageMagick writes one when asked for alpha.
156+magick "$out/bmp-source-alpha.png" -define bmp:format=bmp5 BMP:"$out/v5alpha.bmp"
157+magick "$out/bmp-source.png" rgba:"$out/bmp-source.rgba"
158+magick "$out/bmp-source-alpha.png" rgba:"$out/bmp-source-alpha.rgba"
159+magick "$out/bmp-source.png" "$out/bmp-embed.png"
160+magick "$out/bmp-source.png" -quality 85 "$out/bmp-embed.jpg"
161+python3 "$(dirname "$0")/lib/gen-bmp-shapes.py" "$out" "$out/bmp-source.rgba" 64 48 \
162+ "$out/bmp-source-alpha.rgba" "$out/bmp-embed.png" "$out/bmp-embed.jpg"
163+rm -f "$out/bmp-source.png" "$out/bmp-source-alpha.png" "$out/bmp-source.rgba" \
164+ "$out/bmp-source-alpha.rgba" "$out/bmp-embed.png" "$out/bmp-embed.jpg"
165+
139166 # Small versions of each format, for the fuzz sweep: ten thousand mutations
140167 # per format is only affordable on a picture that decodes in microseconds.
141168 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
144171 "$out/tiny-lossy.webp"
145172 ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 1 "$out/tiny-lossless.webp"
146173 magick "$out/tiny.png" -colors 64 "$out/tiny.gif"
174+magick "$out/tiny.png" -colors 64 -type palette -compress None BMP3:"$out/tiny.bmp"
147175
148176 echo "wrote $(ls "$out" | wc -l) files to $out"
scripts/lib/gen-bmp-shapes.pyadded+168 -0
@@ -0,0 +1,168 @@
1+"""Write the BMP shapes ImageMagick will not emit.
2+
3+ImageMagick covers the ordinary files (1/4/8-bit palettes, RLE8, 24-bit), but
4+it has no switch for a 16-bit bitfield file, a top-down row order, a 32-bit
5+file with an alpha channel, or the 12-byte OS/2 header -- all of which are
6+shapes a decoder meets in the wild. Each is written here from a raw RGBA dump
7+so the pixels are the same picture as the rest of the corpus.
8+"""
9+
10+import struct
11+import sys
12+
13+out, raw, width, height = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])
14+rgba = open(raw, "rb").read()
15+rgba_alpha = open(sys.argv[5], "rb").read()
16+
17+
18+def pixel(source, x, y):
19+ at = (y * width + x) * 4
20+ return source[at], source[at + 1], source[at + 2], source[at + 3]
21+
22+
23+def rows(top_down, source=None):
24+ source = rgba if source is None else source
25+ order = range(height) if top_down else range(height - 1, -1, -1)
26+ return [[pixel(source, x, y) for x in range(width)] for y in order]
27+
28+
29+def file_header(offset, size):
30+ return b"BM" + struct.pack("<IHHI", size, 0, 0, offset)
31+
32+
33+def info_v3(bits, compression, masks=()):
34+ header = struct.pack(
35+ "<IiiHHIIiiII", 40, width, -height if masks == "topdown" else height,
36+ 1, bits, compression, 0, 2835, 2835, 0, 0,
37+ )
38+ return header
39+
40+
41+def write(name, info, body, extra=b""):
42+ offset = 14 + len(info) + len(extra)
43+ blob = file_header(offset, offset + len(body)) + info + extra + body
44+ open(f"{out}/{name}", "wb").write(blob)
45+
46+
47+def packed(bits_per_pixel, encode, top_down=False, source=None):
48+ """Pack rows to the format's four-byte row alignment."""
49+ stride = ((width * bits_per_pixel + 31) // 32) * 4
50+ body = bytearray()
51+ for row in rows(top_down, source):
52+ line = bytearray()
53+ for pix in row:
54+ line += encode(pix)
55+ line += b"\0" * (stride - len(line))
56+ body += line
57+ return bytes(body)
58+
59+
60+# 16-bit, 5-6-5, declared through BI_BITFIELDS masks.
61+masks565 = struct.pack("<III", 0xF800, 0x07E0, 0x001F)
62+body = packed(16, lambda p: struct.pack(
63+ "<H", ((p[0] >> 3) << 11) | ((p[1] >> 2) << 5) | (p[2] >> 3)))
64+write("bf565.bmp", info_v3(16, 3), body, masks565)
65+
66+# 16-bit, 5-5-5, the layout BI_RGB implies at this depth (no mask block).
67+body = packed(16, lambda p: struct.pack(
68+ "<H", ((p[0] >> 3) << 10) | ((p[1] >> 3) << 5) | (p[2] >> 3)))
69+write("rgb555.bmp", info_v3(16, 0), body)
70+
71+# 32-bit with an alpha channel: the fourth mask only has a home in the
72+# BITMAPV4HEADER, whose 108 bytes carry all four masks plus a colour space.
73+body = packed(32, lambda p: bytes([p[2], p[1], p[0], p[3]]), source=rgba_alpha)
74+v4 = struct.pack(
75+ "<IiiHHIIiiII", 108, width, height, 1, 32, 3, len(body), 2835, 2835, 0, 0,
76+) + struct.pack(
77+ "<IIII", 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000,
78+) + b"BGRs" + b"\0" * 48
79+write("alpha32.bmp", v4, body)
80+
81+# Top-down rows: a negative height, first row stored first.
82+body = packed(24, lambda p: bytes([p[2], p[1], p[0]]), top_down=True)
83+info = struct.pack("<IiiHHIIiiII", 40, width, -height, 1, 24, 0, 0, 2835, 2835, 0, 0)
84+write("topdown24.bmp", info, body)
85+
86+# RLE4, from the 4-bit palette file ImageMagick wrote: same palette, same
87+# indices, only the run encoding differs -- ImageMagick's RLE switch produces
88+# an 8-bit file whatever the colour count, so the 4-bit run path has no other
89+# source.
90+def rle4(source_name, name):
91+ src = open(f"{out}/{source_name}", "rb").read()
92+ offset, = struct.unpack_from("<I", src, 10)
93+ w, h = struct.unpack_from("<ii", src, 18)
94+ colours, = struct.unpack_from("<I", src, 46)
95+ colours = colours or 16
96+ palette = src[14 + 40:14 + 40 + colours * 4]
97+ stride = ((w * 4 + 31) // 32) * 4
98+ body = bytearray()
99+ for y in range(h):
100+ line = src[offset + y * stride:offset + (y + 1) * stride]
101+ indices = []
102+ for x in range(w):
103+ byte = line[x // 2]
104+ indices.append(byte >> 4 if x % 2 == 0 else byte & 0x0F)
105+ x = 0
106+ while x < w:
107+ run = 1
108+ while x + run < w and run < 254 and indices[x + run] == indices[x]:
109+ run += 1
110+ if run >= 2:
111+ body += bytes([run, indices[x] << 4 | indices[x]])
112+ x += run
113+ continue
114+ # A literal run needs at least three pixels to be legal; below that
115+ # the encoded form is a run of one.
116+ end = x
117+ while end < w and end - x < 254:
118+ same = 1
119+ while end + same < w and indices[end + same] == indices[end]:
120+ same += 1
121+ if same >= 3:
122+ break
123+ end += same
124+ count = end - x
125+ if count < 3:
126+ body += bytes([1, indices[x] << 4])
127+ x += 1
128+ continue
129+ nibbles = bytearray()
130+ for i in range(0, count, 2):
131+ high = indices[x + i] << 4
132+ low = indices[x + i + 1] if i + 1 < count else 0
133+ nibbles.append(high | low)
134+ while len(nibbles) % 2:
135+ nibbles.append(0)
136+ body += bytes([0, count]) + nibbles
137+ x = end
138+ body += b"\x00\x00"
139+ body = body[:-2] + b"\x00\x01"
140+ info = struct.pack("<IiiHHIIiiII", 40, w, h, 1, 4, 2, len(body), 2835, 2835,
141+ colours, 0)
142+ write(name, info, bytes(body), palette)
143+
144+
145+rle4("pal4.bmp", "rle4.bmp")
146+
147+# BI_PNG and BI_JPEG: a BMP file header and info header wrapped around a whole
148+# file of another format, which is what a printer driver or a clipboard writes.
149+def wrap(name, payload_path, compression):
150+ payload = open(payload_path, "rb").read()
151+ info = struct.pack(
152+ "<IiiHHIIiiII", 40, width, height, 1, 0, compression, len(payload),
153+ 2835, 2835, 0, 0,
154+ )
155+ write(name, info, payload)
156+
157+
158+wrap("embedded-png.bmp", sys.argv[6], 5)
159+wrap("embedded-jpeg.bmp", sys.argv[7], 4)
160+
161+# The OS/2 v2 header, in the 16-byte form writers actually emit: 32-bit
162+# dimensions like a Windows header, and nothing after them.
163+body = packed(24, lambda p: bytes([p[2], p[1], p[0]]))
164+write("os2v2.bmp", struct.pack("<IiiHH", 16, width, height, 1, 24), body)
165+
166+# The 12-byte OS/2 v1 header, whose dimensions are 16-bit and unsigned.
167+body = packed(24, lambda p: bytes([p[2], p[1], p[0]]))
168+write("os2v1.bmp", struct.pack("<IhhHH", 12, width, height, 1, 24), body)
shims/image/src/lib.rsmodified+6 -2
@@ -382,12 +382,16 @@ fn format_of(data: &[u8]) -> Option<ImageFormat> {
382382 ec_image::ImageFormat::Png => Some(ImageFormat::Png),
383383 ec_image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg),
384384 ec_image::ImageFormat::WebP => Some(ImageFormat::WebP),
385- // Only the gpui half of this shim names the animated formats; a build
386- // without it has no variant to answer with.
385+ // Only the gpui half of this shim names the formats gpui asks for; a
386+ // build without it has no variant to answer with.
387387 #[cfg(feature = "gpui")]
388388 ec_image::ImageFormat::Gif => Some(ImageFormat::Gif),
389389 #[cfg(not(feature = "gpui"))]
390390 ec_image::ImageFormat::Gif => None,
391+ #[cfg(feature = "gpui")]
392+ ec_image::ImageFormat::Bmp => Some(ImageFormat::Bmp),
393+ #[cfg(not(feature = "gpui"))]
394+ ec_image::ImageFormat::Bmp => None,
391395 }
392396 }
393397