forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB231663eTahinli3 months ago1475 commits

bmp.rs496 lines, 17.4 KiBHistoryRawDownload
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
19use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels};
20use ec_core::{Error, Result};
21
22/// Fields of the info header this decoder acts on.
23struct 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
40const BI_RGB: u32 = 0;
41const BI_RLE8: u32 = 1;
42const BI_RLE4: u32 = 2;
43const BI_BITFIELDS: u32 = 3;
44const BI_JPEG: u32 = 4;
45const BI_PNG: u32 = 5;
46const BI_ALPHABITFIELDS: u32 = 6;
47
48fn 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
54fn 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.
61fn 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.
190pub 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.
213fn 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.
240struct Field {
241 shift: u32,
242 max: u32,
243}
244
245impl 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.
267pub 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.
383fn 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.
398fn 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.
420fn 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}