forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

bmp.rs501 lines, 17.7 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 // BMP has no EXIF; the orientation is the identity.
206 orientation: 1,
207 })
208}
209
210/// The payload of a `BI_PNG` or `BI_JPEG` file, which is a whole file of that
211/// other format rather than any arrangement of BMP rows.
212///
213/// `biSizeImage` is the payload's length; a zero there means the writer left it
214/// out, and the rest of the file is the payload.
215fn embedded(data: &[u8]) -> Result<Option<(ImageFormat, &[u8])>> {
216 if !data.starts_with(b"BM") || u32_at(data, 14)? < 40 {
217 return Ok(None);
218 }
219 let format = match u32_at(data, 30)? {
220 BI_PNG => ImageFormat::Png,
221 BI_JPEG => ImageFormat::Jpeg,
222 _ => return Ok(None),
223 };
224 let offset = u32_at(data, 10)? as usize;
225 let payload = data
226 .get(offset..)
227 .ok_or_else(|| Error::corrupt("BMP: the payload offset is past the file"))?;
228 let declared = u32_at(data, 34)? as usize;
229 let payload = if declared == 0 || declared > payload.len() {
230 payload
231 } else {
232 &payload[..declared]
233 };
234 Ok(Some((format, payload)))
235}
236
237/// A channel mask reduced to a shift and a scale.
238///
239/// Masks are arbitrary -- a 16-bit file may carry 5-6-5, 5-5-5 or anything
240/// else -- so each channel is read as a field and stretched to eight bits so
241/// that a full-scale field becomes 255 rather than 248.
242struct Field {
243 shift: u32,
244 max: u32,
245}
246
247impl Field {
248 fn new(mask: u32) -> Option<Field> {
249 if mask == 0 {
250 return None;
251 }
252 let shift = mask.trailing_zeros();
253 Some(Field {
254 shift,
255 max: mask >> shift,
256 })
257 }
258
259 fn sample(&self, raw: u32, mask: u32) -> u8 {
260 let value = (raw & mask) >> self.shift;
261 if self.max == 0 {
262 return 0;
263 }
264 ((value * 255 + self.max / 2) / self.max) as u8
265 }
266}
267
268/// Decode a BMP file.
269pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
270 if let Some((format, payload)) = embedded(data)? {
271 return match format {
272 ImageFormat::Png => crate::png::decode(payload, limits),
273 _ => crate::jpeg::decode(payload, limits),
274 };
275 }
276 let header = header(data)?;
277 limits.check(header.width, header.height)?;
278 let (width, height) = (header.width as usize, header.height as usize);
279 if width == 0 || height == 0 {
280 return Err(Error::corrupt("BMP: a zero-sized picture"));
281 }
282
283 let palette = palette(data, &header)?;
284 let offset = u32_at(data, 10)? as usize;
285 let body = data
286 .get(offset..)
287 .ok_or_else(|| Error::corrupt("BMP: the pixel offset is past the file"))?;
288
289 // Indices first, then colour: every form below produces either palette
290 // indices or direct samples, and the bottom-up flip is the same either way.
291 let has_alpha = header.masks[3] != 0
292 || (header.bits == 32 && header.compression == BI_RGB && palette.is_empty());
293 let channels = if has_alpha { 4 } else { 3 };
294 // The output is checked before anything else sizes from the header; the RLE index buffer
295 // below is width * height, which this bound already covers.
296 let out_len = limits.check_output(header.width, header.height, channels)?;
297 let mut out = vec![0u8; out_len];
298 let row_of = |y: usize| if header.top_down { y } else { height - 1 - y };
299
300 match header.compression {
301 BI_RLE8 | BI_RLE4 => {
302 let indices = rle(body, &header)?;
303 for y in 0..height {
304 for x in 0..width {
305 let index = indices[y * width + x] as usize;
306 let rgb = *palette
307 .get(index)
308 .ok_or_else(|| Error::corrupt("BMP: palette index past the table"))?;
309 let at = (row_of(y) * width + x) * channels;
310 out[at..at + 3].copy_from_slice(&rgb);
311 if has_alpha {
312 out[at + 3] = 255;
313 }
314 }
315 }
316 }
317 _ => {
318 // Rows are padded to a four-byte boundary.
319 let stride = (width * usize::from(header.bits))
320 .div_ceil(8)
321 .next_multiple_of(4);
322 if body.len() < stride * height {
323 return Err(Error::corrupt(format!(
324 "BMP: {} bytes of pixels, {} rows of {stride} needed",
325 body.len(),
326 height
327 )));
328 }
329 let fields = [
330 Field::new(header.masks[0]),
331 Field::new(header.masks[1]),
332 Field::new(header.masks[2]),
333 Field::new(header.masks[3]),
334 ];
335 for y in 0..height {
336 let row = &body[y * stride..y * stride + stride];
337 for x in 0..width {
338 let at = (row_of(y) * width + x) * channels;
339 let (rgb, alpha) = match header.bits {
340 1 | 2 | 4 | 8 => {
341 let bits = usize::from(header.bits);
342 let bit = x * bits;
343 let byte = row[bit / 8];
344 let shift = 8 - bits - (bit % 8);
345 let index = usize::from((byte >> shift) & ((1 << bits) - 1) as u8);
346 let rgb = *palette.get(index).ok_or_else(|| {
347 Error::corrupt("BMP: palette index past the table")
348 })?;
349 (rgb, 255)
350 }
351 16 => {
352 let raw = u32::from(u16::from_le_bytes([row[x * 2], row[x * 2 + 1]]));
353 sample(raw, &header.masks, &fields)
354 }
355 24 => ([row[x * 3 + 2], row[x * 3 + 1], row[x * 3]], 255),
356 _ => {
357 let raw = u32::from_le_bytes([
358 row[x * 4],
359 row[x * 4 + 1],
360 row[x * 4 + 2],
361 row[x * 4 + 3],
362 ]);
363 sample(raw, &header.masks, &fields)
364 }
365 };
366 out[at..at + 3].copy_from_slice(&rgb);
367 if has_alpha {
368 out[at + 3] = alpha;
369 }
370 }
371 }
372 }
373 }
374
375 Ok(Image {
376 width: header.width,
377 height: header.height,
378 pixels: if has_alpha {
379 Pixels::Rgba8(out)
380 } else {
381 Pixels::Rgb8(out)
382 },
383 meta: Metadata::default(),
384 })
385}
386
387/// One direct-colour pixel through the channel masks.
388fn sample(raw: u32, masks: &[u32; 4], fields: &[Option<Field>; 4]) -> ([u8; 3], u8) {
389 let mut rgb = [0u8; 3];
390 for c in 0..3 {
391 if let Some(field) = &fields[c] {
392 rgb[c] = field.sample(raw, masks[c]);
393 }
394 }
395 let alpha = match &fields[3] {
396 Some(field) => field.sample(raw, masks[3]),
397 None => 255,
398 };
399 (rgb, alpha)
400}
401
402/// The palette, as RGB triples in file order.
403fn palette(data: &[u8], header: &Header) -> Result<Vec<[u8; 3]>> {
404 if header.colours == 0 {
405 return Ok(Vec::new());
406 }
407 let mut out = Vec::with_capacity(header.colours);
408 for i in 0..header.colours {
409 let at = header.palette_at + i * header.palette_stride;
410 let entry = data
411 .get(at..at + 3)
412 .ok_or_else(|| Error::corrupt("BMP: the palette runs past the file"))?;
413 // Entries are stored blue first.
414 out.push([entry[2], entry[1], entry[0]]);
415 }
416 Ok(out)
417}
418
419/// Expand `BI_RLE8` or `BI_RLE4` into one palette index per pixel.
420///
421/// The two forms share a structure: a non-zero first byte is a run, a zero
422/// introduces an escape -- end of line, end of file, a delta, or a literal run
423/// padded to an even number of bytes. Pixels the encoding never reaches keep
424/// index zero, which is what the format means by a sparse image.
425fn rle(body: &[u8], header: &Header) -> Result<Vec<u8>> {
426 let (width, height) = (header.width as usize, header.height as usize);
427 let mut out = vec![0u8; width * height];
428 let (mut x, mut y) = (0usize, 0usize);
429 let mut at = 0usize;
430 let four_bit = header.compression == BI_RLE4;
431
432 let put = |out: &mut Vec<u8>, x: &mut usize, y: usize, index: u8| {
433 if *x < width && y < height {
434 out[y * width + *x] = index;
435 }
436 *x += 1;
437 };
438
439 while at + 1 < body.len() {
440 let (count, value) = (body[at], body[at + 1]);
441 at += 2;
442 if count > 0 {
443 for i in 0..usize::from(count) {
444 let index = if four_bit {
445 if i % 2 == 0 { value >> 4 } else { value & 0x0f }
446 } else {
447 value
448 };
449 put(&mut out, &mut x, y, index);
450 }
451 continue;
452 }
453 match value {
454 // End of line.
455 0 => {
456 x = 0;
457 y += 1;
458 }
459 // End of the bitmap; anything after it is padding.
460 1 => break,
461 // A delta: move right and down by the next two bytes.
462 2 => {
463 let delta = body
464 .get(at..at + 2)
465 .ok_or_else(|| Error::corrupt("BMP: a truncated RLE delta"))?;
466 x += usize::from(delta[0]);
467 y += usize::from(delta[1]);
468 at += 2;
469 }
470 // A literal run of `value` pixels, padded to an even byte count.
471 literal => {
472 let literal = usize::from(literal);
473 let bytes = if four_bit {
474 literal.div_ceil(2)
475 } else {
476 literal
477 };
478 let run = body
479 .get(at..at + bytes)
480 .ok_or_else(|| Error::corrupt("BMP: a truncated RLE literal"))?;
481 for i in 0..literal {
482 let index = if four_bit {
483 if i % 2 == 0 {
484 run[i / 2] >> 4
485 } else {
486 run[i / 2] & 0x0f
487 }
488 } else {
489 run[i]
490 };
491 put(&mut out, &mut x, y, index);
492 }
493 at += bytes + (bytes & 1);
494 }
495 }
496 if y > height {
497 return Err(Error::corrupt("BMP: RLE runs past the last row"));
498 }
499 }
500 Ok(out)
501}