oxedyne/fe2o3/fe2o3_graphics/src/bmp.rs
18.0 KiB, 1 run
created by r1870400018:75654, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! Windows bitmaps and icons. |
| 2 | //! |
| 3 | //! A BMP is a header, an optional palette and rows of pixels, and the variety is all in the header: |
| 4 | //! five generations of it (the 12-byte OS/2 core, the 40-byte Windows 3 info, and the 52, 56, 108 |
| 5 | //! and 124-byte versions that added channel masks, alpha and colour spaces), depths from one to |
| 6 | //! thirty-two bits, rows stored bottom-up unless the height is negative, and three compressions -- |
| 7 | //! run-length coding of 8-bit and 4-bit indices, and channel masks, which are not compression at |
| 8 | //! all. A BMP may also carry a whole PNG or JPEG as its pixels, which is handed to that decoder. |
| 9 | //! |
| 10 | //! An ICO is a directory of the same pixel blocks without the file header, each followed by a |
| 11 | //! one-bit transparency mask, or of whole PNGs. The largest picture in it is the one decoded. |
| 12 | //! |
| 13 | //! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\ |
| 14 | //! Anthropic Claude |
| 15 | |
| 16 | use crate::{ |
| 17 | jpeg, |
| 18 | pixmap::Pixmap, |
| 19 | png, |
| 20 | }; |
| 21 | |
| 22 | use oxedyne_fe2o3_core::prelude::*; |
| 23 | |
| 24 | // Compression methods. |
| 25 | const BI_RGB: u32 = 0; |
| 26 | const BI_RLE8: u32 = 1; |
| 27 | const BI_RLE4: u32 = 2; |
| 28 | const BI_BITFIELDS: u32 = 3; |
| 29 | const BI_JPEG: u32 = 4; |
| 30 | const BI_PNG: u32 = 5; |
| 31 | const BI_ALPHABITFIELDS: u32 = 6; |
| 32 | |
| 33 | fn u16le(b: &[u8], at: usize) -> Outcome<u16> { |
| 34 | match b.get(at..at + 2) { |
| 35 | Some(s) => Ok(u16::from_le_bytes([s[0], s[1]])), |
| 36 | None => Err(err!( |
| 37 | "A bitmap needs two bytes at offset {}, but holds {}.", at, b.len(); |
| 38 | Invalid, Input, Decode)), |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | fn u32le(b: &[u8], at: usize) -> Outcome<u32> { |
| 43 | match b.get(at..at + 4) { |
| 44 | Some(s) => Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]])), |
| 45 | None => Err(err!( |
| 46 | "A bitmap needs four bytes at offset {}, but holds {}.", at, b.len(); |
| 47 | Invalid, Input, Decode)), |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | /// One channel's mask, as the shift and width that read it out of a pixel. |
| 52 | #[derive(Clone, Copy, Debug)] |
| 53 | struct Mask { |
| 54 | shift: u32, |
| 55 | bits: u32, |
| 56 | } |
| 57 | |
| 58 | impl Mask { |
| 59 | |
| 60 | fn new(m: u32) -> Self { |
| 61 | if m == 0 { |
| 62 | return Self { shift: 0, bits: 0 }; |
| 63 | } |
| 64 | let shift = m.trailing_zeros(); |
| 65 | let bits = (m >> shift).trailing_ones(); |
| 66 | Self { shift, bits } |
| 67 | } |
| 68 | |
| 69 | /// The channel scaled to eight bits, or `none` where the mask is empty. |
| 70 | fn read(&self, px: u32, none: u8) -> u8 { |
| 71 | if self.bits == 0 { |
| 72 | return none; |
| 73 | } |
| 74 | let max = if self.bits >= 32 { u32::MAX } else { (1u32 << self.bits) - 1 }; |
| 75 | let v = (px >> self.shift) & max; |
| 76 | if self.bits == 8 { |
| 77 | return v as u8; |
| 78 | } |
| 79 | ((v as u64 * 255 + max as u64 / 2) / max as u64) as u8 |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// What the header says, gathered from whichever generation of it the file carries. |
| 84 | struct Header { |
| 85 | w: usize, |
| 86 | h: usize, |
| 87 | top_down: bool, |
| 88 | bpp: u16, |
| 89 | comp: u32, |
| 90 | masks: Option<[u32; 4]>, // red, green, blue, alpha |
| 91 | palette: Vec<[u8; 4]>, // RGBA, alpha always opaque |
| 92 | end: usize, // the first byte after the header, masks and palette |
| 93 | } |
| 94 | |
| 95 | /// Reads a device-independent bitmap header starting at `dib[0]`. |
| 96 | fn header(dib: &[u8]) -> Outcome<Header> { |
| 97 | let size = res!(u32le(dib, 0)) as usize; |
| 98 | let (w, h, bpp, comp, mut at, entry, used) = match size { |
| 99 | 12 => { |
| 100 | let w = res!(u16le(dib, 4)) as i64; |
| 101 | let h = res!(u16le(dib, 6)) as i64; |
| 102 | let bpp = res!(u16le(dib, 10)); |
| 103 | (w, h, bpp, BI_RGB, 12usize, 3usize, 0u32) |
| 104 | } |
| 105 | 16 | 40 | 52 | 56 | 64 | 108 | 124 => { |
| 106 | let w = res!(u32le(dib, 4)) as i32 as i64; |
| 107 | let h = res!(u32le(dib, 8)) as i32 as i64; |
| 108 | let bpp = res!(u16le(dib, 14)); |
| 109 | let comp = if size >= 20 { res!(u32le(dib, 16)) } else { BI_RGB }; |
| 110 | let used = if size >= 36 { res!(u32le(dib, 32)) } else { 0 }; |
| 111 | (w, h, bpp, comp, size, 4usize, used) |
| 112 | } |
| 113 | _ => return Err(err!( |
| 114 | "A bitmap header of {} bytes is not one of the generations this reads \ |
| 115 | (12, 16, 40, 52, 56, 64, 108 or 124).", size; |
| 116 | Invalid, Input, Decode, Unimplemented)), |
| 117 | }; |
| 118 | // An OS/2 2.x header numbers its compressions differently past RLE4. |
| 119 | if (size == 16 || size == 64) && comp > BI_RLE4 { |
| 120 | return Err(err!( |
| 121 | "An OS/2 bitmap uses compression {}, which this does not read.", comp; |
| 122 | Invalid, Input, Decode, Unimplemented)); |
| 123 | } |
| 124 | if w <= 0 || h == 0 { |
| 125 | return Err(err!( |
| 126 | "A bitmap declares a size of {} by {}.", w, h; |
| 127 | Invalid, Input, Decode)); |
| 128 | } |
| 129 | let top_down = h < 0; |
| 130 | let masks = match comp { |
| 131 | BI_BITFIELDS | BI_ALPHABITFIELDS => { |
| 132 | let n = if comp == BI_ALPHABITFIELDS { 4 } else { 3 }; |
| 133 | // A 40-byte header puts the masks after itself; later ones hold them inside. |
| 134 | let base = if size == 40 { at } else { 40 }; |
| 135 | let mut m = [0u32; 4]; |
| 136 | for i in 0..n { |
| 137 | m[i] = res!(u32le(dib, base + 4 * i)); |
| 138 | } |
| 139 | if size >= 56 && n == 3 { |
| 140 | m[3] = res!(u32le(dib, 52)); |
| 141 | } |
| 142 | if size == 40 { |
| 143 | at += 4 * n; |
| 144 | } |
| 145 | Some(m) |
| 146 | } |
| 147 | _ if size >= 56 && (bpp == 16 || bpp == 32) => { |
| 148 | // A V4 or V5 header without BI_BITFIELDS still names an alpha mask some writers rely on. |
| 149 | let a = res!(u32le(dib, 52)); |
| 150 | if a != 0 && comp == BI_RGB { |
| 151 | let def = default_masks(bpp); |
| 152 | Some([def[0], def[1], def[2], a]) |
| 153 | } else { |
| 154 | None |
| 155 | } |
| 156 | } |
| 157 | _ => None, |
| 158 | }; |
| 159 | let mut palette = Vec::new(); |
| 160 | if bpp <= 8 { |
| 161 | let full = 1usize << bpp; |
| 162 | let n = if used == 0 || used as usize > full { full } else { used as usize }; |
| 163 | for i in 0..n { |
| 164 | let p = at + i * entry; |
| 165 | match dib.get(p..p + 3) { |
| 166 | Some(c) => palette.push([c[2], c[1], c[0], 255]), |
| 167 | None => break, // a short palette leaves the rest black |
| 168 | } |
| 169 | } |
| 170 | at += n * entry; |
| 171 | } |
| 172 | Ok(Header { |
| 173 | w: w as usize, |
| 174 | h: h.unsigned_abs() as usize, |
| 175 | top_down, |
| 176 | bpp, |
| 177 | comp, |
| 178 | masks, |
| 179 | palette, |
| 180 | end: at, |
| 181 | }) |
| 182 | } |
| 183 | |
| 184 | fn default_masks(bpp: u16) -> [u32; 4] { |
| 185 | match bpp { |
| 186 | 16 => [0x7c00, 0x03e0, 0x001f, 0], |
| 187 | _ => [0x00ff_0000, 0x0000_ff00, 0x0000_00ff, 0], |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | fn colour(palette: &[[u8; 4]], i: usize) -> [u8; 4] { |
| 192 | match palette.get(i) { |
| 193 | Some(c) => *c, |
| 194 | None => [0, 0, 0, 255], |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /// Decodes uncompressed or channel-masked rows into the pixmap. |
| 199 | fn rows(hdr: &Header, px: &[u8], pm: &mut Pixmap) -> Outcome<()> { |
| 200 | let bpp = hdr.bpp as usize; |
| 201 | if !matches!(bpp, 1 | 2 | 4 | 8 | 16 | 24 | 32) { |
| 202 | return Err(err!( |
| 203 | "A bitmap of {} bits a pixel is not one of 1, 2, 4, 8, 16, 24 or 32.", bpp; |
| 204 | Invalid, Input, Decode, Unimplemented)); |
| 205 | } |
| 206 | let stride = ((hdr.w * bpp + 31) / 32) * 4; |
| 207 | let need = match stride.checked_mul(hdr.h) { |
| 208 | Some(n) => n, |
| 209 | None => return Err(err!( |
| 210 | "A bitmap of {} rows of {} bytes overflows.", hdr.h, stride; |
| 211 | Invalid, Input, Decode, Overflow)), |
| 212 | }; |
| 213 | // The last row may lack its padding, which some writers leave off. |
| 214 | let short = stride - (hdr.w * bpp + 7) / 8; |
| 215 | if px.len() + short < need { |
| 216 | return Err(err!( |
| 217 | "A bitmap of {} by {} at {} bits needs {} bytes of pixels, but {} are present.", |
| 218 | hdr.w, hdr.h, bpp, need, px.len(); |
| 219 | Invalid, Input, Decode)); |
| 220 | } |
| 221 | let masks = match hdr.masks { |
| 222 | Some(m) => m, |
| 223 | None => default_masks(hdr.bpp), |
| 224 | }; |
| 225 | let mk = [Mask::new(masks[0]), Mask::new(masks[1]), Mask::new(masks[2]), Mask::new(masks[3])]; |
| 226 | let w = hdr.w; |
| 227 | let data = pm.data_mut(); |
| 228 | for r in 0..hdr.h { |
| 229 | let y = if hdr.top_down { r } else { hdr.h - 1 - r }; |
| 230 | let row = &px[r * stride..(r * stride + stride).min(px.len())]; |
| 231 | let out = &mut data[y * w * 4..(y + 1) * w * 4]; |
| 232 | for x in 0..w { |
| 233 | let c = match bpp { |
| 234 | 1 | 2 | 4 | 8 => { |
| 235 | let bit = x * bpp; |
| 236 | let byte = row[bit / 8]; |
| 237 | let shift = 8 - bpp - (bit % 8); |
| 238 | let i = (byte >> shift) as usize & ((1 << bpp) - 1); |
| 239 | colour(&hdr.palette, i) |
| 240 | } |
| 241 | 24 => [row[x * 3 + 2], row[x * 3 + 1], row[x * 3], 255], |
| 242 | _ => { |
| 243 | let v = if bpp == 16 { |
| 244 | u16::from_le_bytes([row[x * 2], row[x * 2 + 1]]) as u32 |
| 245 | } else { |
| 246 | u32::from_le_bytes([row[x * 4], row[x * 4 + 1], row[x * 4 + 2], row[x * 4 + 3]]) |
| 247 | }; |
| 248 | [mk[0].read(v, 0), mk[1].read(v, 0), mk[2].read(v, 0), mk[3].read(v, 255)] |
| 249 | } |
| 250 | }; |
| 251 | out[x * 4..x * 4 + 4].copy_from_slice(&c); |
| 252 | } |
| 253 | } |
| 254 | Ok(()) |
| 255 | } |
| 256 | |
| 257 | /// Decodes 8-bit or 4-bit run-length coded indices into the pixmap. |
| 258 | /// |
| 259 | /// Pixels a delta skips over are left as the palette's first colour, which is what a reader that |
| 260 | /// paints the bitmap onto a cleared surface shows. |
| 261 | fn rle(hdr: &Header, px: &[u8], pm: &mut Pixmap) -> Outcome<()> { |
| 262 | let four = hdr.comp == BI_RLE4; |
| 263 | let (w, h) = (hdr.w, hdr.h); |
| 264 | let back = colour(&hdr.palette, 0); |
| 265 | { |
| 266 | let data = pm.data_mut(); |
| 267 | for p in data.chunks_exact_mut(4) { |
| 268 | p.copy_from_slice(&back); |
| 269 | } |
| 270 | } |
| 271 | let data = pm.data_mut(); |
| 272 | let mut put = |x: usize, y: usize, i: usize| { |
| 273 | if x < w && y < h { |
| 274 | let yy = h - 1 - y; |
| 275 | let c = colour(&hdr.palette, i); |
| 276 | data[(yy * w + x) * 4..(yy * w + x) * 4 + 4].copy_from_slice(&c); |
| 277 | } |
| 278 | }; |
| 279 | let (mut x, mut y) = (0usize, 0usize); |
| 280 | let mut i = 0; |
| 281 | while i + 1 < px.len() && y < h { |
| 282 | let (n, v) = (px[i] as usize, px[i + 1]); |
| 283 | i += 2; |
| 284 | if n > 0 { |
| 285 | for k in 0..n { |
| 286 | let idx = if four { |
| 287 | if k % 2 == 0 { v >> 4 } else { v & 0x0f } |
| 288 | } else { |
| 289 | v |
| 290 | }; |
| 291 | put(x, y, idx as usize); |
| 292 | x += 1; |
| 293 | } |
| 294 | continue; |
| 295 | } |
| 296 | match v { |
| 297 | 0 => { x = 0; y += 1; } // end of line |
| 298 | 1 => break, // end of bitmap |
| 299 | 2 => { // delta |
| 300 | if i + 1 >= px.len() { |
| 301 | break; |
| 302 | } |
| 303 | x += px[i] as usize; |
| 304 | y += px[i + 1] as usize; |
| 305 | i += 2; |
| 306 | } |
| 307 | m => { // absolute run of m indices |
| 308 | let m = m as usize; |
| 309 | let bytes = if four { (m + 1) / 2 } else { m }; |
| 310 | if i + bytes > px.len() { |
| 311 | return Err(err!( |
| 312 | "A run-length bitmap's literal run of {} at offset {} passes its end.", m, i; |
| 313 | Invalid, Input, Decode)); |
| 314 | } |
| 315 | for k in 0..m { |
| 316 | let idx = if four { |
| 317 | let b = px[i + k / 2]; |
| 318 | if k % 2 == 0 { b >> 4 } else { b & 0x0f } |
| 319 | } else { |
| 320 | px[i + k] |
| 321 | }; |
| 322 | put(x, y, idx as usize); |
| 323 | x += 1; |
| 324 | } |
| 325 | // Each literal run is padded to a whole number of 16-bit words. |
| 326 | i += (bytes + 1) & !1; |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | Ok(()) |
| 331 | } |
| 332 | |
| 333 | /// Decodes a device-independent bitmap whose pixels start at `pixels`, an offset into `dib`. |
| 334 | fn dib(dib: &[u8], pixels: Option<usize>, icon: bool) -> Outcome<Pixmap> { |
| 335 | let mut hdr = res!(header(dib)); |
| 336 | if icon { |
| 337 | // An icon's height counts the transparency mask below the colour rows as well. |
| 338 | hdr.h /= 2; |
| 339 | if hdr.h == 0 { |
| 340 | return Err(err!("An icon entry is less than one row tall."; Invalid, Input, Decode)); |
| 341 | } |
| 342 | } |
| 343 | let start = pixels.unwrap_or(hdr.end); |
| 344 | let px = match dib.get(start..) { |
| 345 | Some(p) => p, |
| 346 | None => return Err(err!( |
| 347 | "A bitmap's pixels are said to start at offset {}, past its end at {}.", |
| 348 | start, dib.len(); |
| 349 | Invalid, Input, Decode)), |
| 350 | }; |
| 351 | match hdr.comp { |
| 352 | BI_JPEG => return jpeg::decode(px), |
| 353 | BI_PNG => return png::decode(px), |
| 354 | _ => (), |
| 355 | } |
| 356 | let mut pm = res!(Pixmap::new(hdr.w, hdr.h)); |
| 357 | match hdr.comp { |
| 358 | BI_RGB | BI_BITFIELDS | BI_ALPHABITFIELDS => res!(rows(&hdr, px, &mut pm)), |
| 359 | BI_RLE8 | BI_RLE4 => { |
| 360 | if hdr.top_down { |
| 361 | return Err(err!( |
| 362 | "A run-length bitmap cannot be stored top-down, but this one says it is."; |
| 363 | Invalid, Input, Decode)); |
| 364 | } |
| 365 | res!(rle(&hdr, px, &mut pm)); |
| 366 | } |
| 367 | c => return Err(err!( |
| 368 | "A bitmap uses compression {}, which this does not read.", c; |
| 369 | Invalid, Input, Decode, Unimplemented)), |
| 370 | } |
| 371 | if icon { |
| 372 | let stride = ((hdr.w * hdr.bpp as usize + 31) / 32) * 4; |
| 373 | let and_at = stride * hdr.h; |
| 374 | let and_stride = ((hdr.w + 31) / 32) * 4; |
| 375 | let w = hdr.w; |
| 376 | let h = hdr.h; |
| 377 | // A 32-bit icon carries its own alpha; the mask is used only where that alpha is empty. |
| 378 | let use_mask = hdr.bpp < 32 || pm.data().chunks_exact(4).all(|p| p[3] == 0); |
| 379 | if hdr.bpp == 32 && use_mask { |
| 380 | for p in pm.data_mut().chunks_exact_mut(4) { |
| 381 | p[3] = 255; |
| 382 | } |
| 383 | } |
| 384 | if use_mask { |
| 385 | let data = pm.data_mut(); |
| 386 | for r in 0..h { |
| 387 | let y = h - 1 - r; |
| 388 | for x in 0..w { |
| 389 | let at = and_at + r * and_stride + x / 8; |
| 390 | if let Some(b) = px.get(at) { |
| 391 | if (b >> (7 - x % 8)) & 1 == 1 { |
| 392 | data[(y * w + x) * 4 + 3] = 0; |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | } |
| 397 | } |
| 398 | } |
| 399 | Ok(pm) |
| 400 | } |
| 401 | |
| 402 | /// The width and height a bitmap declares, read from its header alone. |
| 403 | pub fn dimensions(buf: &[u8]) -> Outcome<(usize, usize)> { |
| 404 | if buf.len() < 2 || &buf[..2] != b"BM" { |
| 405 | return Err(err!("The bytes do not begin with a bitmap's 'BM'."; Invalid, Input, Decode)); |
| 406 | } |
| 407 | let hdr = res!(header(&buf[14.min(buf.len())..])); |
| 408 | Ok((hdr.w, hdr.h)) |
| 409 | } |
| 410 | |
| 411 | /// Decodes a Windows or OS/2 bitmap file. |
| 412 | pub fn decode(buf: &[u8]) -> Outcome<Pixmap> { |
| 413 | if buf.len() < 14 || &buf[..2] != b"BM" { |
| 414 | return Err(err!("The bytes do not begin with a bitmap's 'BM'."; Invalid, Input, Decode)); |
| 415 | } |
| 416 | let off = res!(u32le(buf, 10)) as usize; |
| 417 | // The pixel offset counts from the start of the file; the header from byte 14. |
| 418 | let pixels = if off >= 14 { Some(off - 14) } else { None }; |
| 419 | dib(&buf[14..], pixels, false) |
| 420 | } |
| 421 | |
| 422 | /// Decodes the largest picture in a Windows icon or cursor file. |
| 423 | pub fn decode_ico(buf: &[u8]) -> Outcome<Pixmap> { |
| 424 | let kind = res!(u16le(buf, 2)); |
| 425 | if res!(u16le(buf, 0)) != 0 || (kind != 1 && kind != 2) { |
| 426 | return Err(err!("The bytes are not an icon or cursor directory."; Invalid, Input, Decode)); |
| 427 | } |
| 428 | let n = res!(u16le(buf, 4)) as usize; |
| 429 | let mut best: Option<(usize, usize, usize, usize)> = None; // area, depth, offset, size |
| 430 | for i in 0..n { |
| 431 | let e = 6 + i * 16; |
| 432 | let w = match buf.get(e) { Some(0) => 256, Some(v) => *v as usize, None => break }; |
| 433 | let h = match buf.get(e + 1) { Some(0) => 256, Some(v) => *v as usize, None => break }; |
| 434 | let bpp = res!(u16le(buf, e + 6)) as usize; |
| 435 | let size = res!(u32le(buf, e + 8)) as usize; |
| 436 | let off = res!(u32le(buf, e + 12)) as usize; |
| 437 | let cand = (w * h, bpp, off, size); |
| 438 | best = match best { |
| 439 | Some(b) if (b.0, b.1) >= (cand.0, cand.1) => Some(b), |
| 440 | _ => Some(cand), |
| 441 | }; |
| 442 | } |
| 443 | let (_, _, off, size) = match best { |
| 444 | Some(b) => b, |
| 445 | None => return Err(err!("An icon file lists no pictures."; Invalid, Input, Decode)), |
| 446 | }; |
| 447 | let end = off.saturating_add(size).min(buf.len()); |
| 448 | let img = match buf.get(off..end) { |
| 449 | Some(s) => s, |
| 450 | None => return Err(err!( |
| 451 | "An icon's picture is said to start at offset {}, past its end at {}.", off, buf.len(); |
| 452 | Invalid, Input, Decode)), |
| 453 | }; |
| 454 | if img.starts_with(&[0x89, b'P', b'N', b'G']) { |
| 455 | return png::decode(img); |
| 456 | } |
| 457 | dib(img, None, true) |
| 458 | } |
| 459 | |
| 460 | /// Encodes a pixmap as a bitmap: 24 bits a pixel where every pixel is opaque, otherwise 32 bits |
| 461 | /// with an alpha mask in a version 4 header, which is the form every current reader takes alpha |
| 462 | /// from. |
| 463 | pub fn encode(pm: &Pixmap) -> Outcome<Vec<u8>> { |
| 464 | let (w, h) = (pm.width(), pm.height()); |
| 465 | let opaque = pm.data().chunks_exact(4).all(|p| p[3] == 255); |
| 466 | let (bpp, hsize) = if opaque { (24usize, 40usize) } else { (32, 108) }; |
| 467 | let stride = ((w * bpp + 31) / 32) * 4; |
| 468 | let off = 14 + hsize; |
| 469 | let total = off + stride * h; |
| 470 | if total > u32::MAX as usize { |
| 471 | return Err(err!( |
| 472 | "A bitmap of {} bytes is too large for the format's 32-bit size.", total; |
| 473 | Invalid, Input, Excessive)); |
| 474 | } |
| 475 | let mut out = Vec::with_capacity(total); |
| 476 | out.extend_from_slice(b"BM"); |
| 477 | out.extend_from_slice(&(total as u32).to_le_bytes()); |
| 478 | out.extend_from_slice(&[0, 0, 0, 0]); |
| 479 | out.extend_from_slice(&(off as u32).to_le_bytes()); |
| 480 | out.extend_from_slice(&(hsize as u32).to_le_bytes()); |
| 481 | out.extend_from_slice(&(w as i32).to_le_bytes()); |
| 482 | out.extend_from_slice(&(h as i32).to_le_bytes()); |
| 483 | out.extend_from_slice(&1u16.to_le_bytes()); |
| 484 | out.extend_from_slice(&(bpp as u16).to_le_bytes()); |
| 485 | let comp = if opaque { BI_RGB } else { BI_BITFIELDS }; |
| 486 | out.extend_from_slice(&comp.to_le_bytes()); |
| 487 | out.extend_from_slice(&((stride * h) as u32).to_le_bytes()); |
| 488 | out.extend_from_slice(&2835u32.to_le_bytes()); // 72 dots an inch, in dots a metre |
| 489 | out.extend_from_slice(&2835u32.to_le_bytes()); |
| 490 | out.extend_from_slice(&[0; 8]); |
| 491 | if !opaque { |
| 492 | for m in [0x00ff_0000u32, 0x0000_ff00, 0x0000_00ff, 0xff00_0000] { |
| 493 | out.extend_from_slice(&m.to_le_bytes()); |
| 494 | } |
| 495 | out.extend_from_slice(b"BGRs"); // LCS_sRGB, stored little-endian |
| 496 | out.extend_from_slice(&[0; 48]); |
| 497 | } |
| 498 | let data = pm.data(); |
| 499 | for y in (0..h).rev() { |
| 500 | let start = out.len(); |
| 501 | for x in 0..w { |
| 502 | let p = &data[(y * w + x) * 4..(y * w + x) * 4 + 4]; |
| 503 | out.extend_from_slice(&[p[2], p[1], p[0]]); |
| 504 | if !opaque { |
| 505 | out.push(p[3]); |
| 506 | } |
| 507 | } |
| 508 | out.resize(start + stride, 0); |
| 509 | } |
| 510 | Ok(out) |
| 511 | } |
| 512 | |
| 513 | #[cfg(test)] |
| 514 | mod tests { |
| 515 | use super::*; |
| 516 | use crate::colour::Rgba; |
| 517 | |
| 518 | fn sample(w: usize, h: usize, alpha: bool) -> Outcome<Pixmap> { |
| 519 | let mut pm = res!(Pixmap::new(w, h)); |
| 520 | for y in 0..h { |
| 521 | for x in 0..w { |
| 522 | let a = if alpha { ((x * 37 + y * 11) % 256) as u8 } else { 255 }; |
| 523 | pm.set_pixel(x, y, Rgba::new((x * 9) as u8, (y * 13) as u8, ((x + y) * 5) as u8, a)); |
| 524 | } |
| 525 | } |
| 526 | Ok(pm) |
| 527 | } |
| 528 | |
| 529 | #[test] |
| 530 | fn test_encode_then_decode_returns_the_pixels_00() -> Outcome<()> { |
| 531 | for &(w, h, a) in &[(1, 1, false), (17, 13, false), (5, 3, true), (31, 2, true)] { |
| 532 | let pm = res!(sample(w, h, a)); |
| 533 | let back = res!(decode(&res!(encode(&pm)))); |
| 534 | assert_eq!(back, pm, "{}x{} alpha {}", w, h, a); |
| 535 | } |
| 536 | Ok(()) |
| 537 | } |
| 538 | |
| 539 | #[test] |
| 540 | fn test_rle8_with_a_delta_and_an_absolute_run_00() -> Outcome<()> { |
| 541 | // 4 by 2, palette of three, bottom row first. |
| 542 | let mut f = Vec::new(); |
| 543 | let pal: [[u8; 4]; 3] = [[0, 0, 0, 0], [0, 0, 255, 0], [0, 255, 0, 0]]; |
| 544 | let px: Vec<u8> = vec![ |
| 545 | 2, 1, // two of index 1 |
| 546 | 0, 2, 1, 0, // delta: right one, down none |
| 547 | 1, 2, // one of index 2 |
| 548 | 0, 0, // end of line |
| 549 | 0, 3, 2, 1, 2, 0, // absolute run of three, padded to four bytes |
| 550 | 0, 1, // end of bitmap |
| 551 | ]; |
| 552 | f.extend_from_slice(b"BM"); |
| 553 | let off = 14 + 40 + 12; |
| 554 | f.extend_from_slice(&((off + px.len()) as u32).to_le_bytes()); |
| 555 | f.extend_from_slice(&[0; 4]); |
| 556 | f.extend_from_slice(&(off as u32).to_le_bytes()); |
| 557 | f.extend_from_slice(&40u32.to_le_bytes()); |
| 558 | f.extend_from_slice(&4i32.to_le_bytes()); |
| 559 | f.extend_from_slice(&2i32.to_le_bytes()); |
| 560 | f.extend_from_slice(&1u16.to_le_bytes()); |
| 561 | f.extend_from_slice(&8u16.to_le_bytes()); |
| 562 | f.extend_from_slice(&BI_RLE8.to_le_bytes()); |
| 563 | f.extend_from_slice(&[0; 12]); |
| 564 | f.extend_from_slice(&3u32.to_le_bytes()); |
| 565 | f.extend_from_slice(&[0; 4]); |
| 566 | for p in &pal { |
| 567 | f.extend_from_slice(p); |
| 568 | } |
| 569 | f.extend_from_slice(&px); |
| 570 | let pm = res!(decode(&f)); |
| 571 | let red = Rgba::new(255, 0, 0, 255); |
| 572 | let green = Rgba::new(0, 255, 0, 255); |
| 573 | let black = Rgba::new(0, 0, 0, 255); |
| 574 | // Bottom row: red, red, delta (1, 0) over x = 2, then green at x = 3. |
| 575 | assert_eq!(pm.pixel(0, 1), Some(red)); |
| 576 | assert_eq!(pm.pixel(1, 1), Some(red)); |
| 577 | assert_eq!(pm.pixel(2, 1), Some(black)); |
| 578 | assert_eq!(pm.pixel(3, 1), Some(green)); |
| 579 | // Top row: green, red, green, then nothing written. |
| 580 | assert_eq!(pm.pixel(0, 0), Some(green)); |
| 581 | assert_eq!(pm.pixel(1, 0), Some(red)); |
| 582 | assert_eq!(pm.pixel(2, 0), Some(green)); |
| 583 | assert_eq!(pm.pixel(3, 0), Some(black)); |
| 584 | Ok(()) |
| 585 | } |
| 586 | } |