| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels}; |
| 20 | use ec_core::{Error, Result}; |
| 21 | |
| 22 | |
| 23 | struct Header { |
| 24 | width: u32, |
| 25 | height: u32, |
| 26 | |
| 27 | top_down: bool, |
| 28 | bits: u16, |
| 29 | compression: u32, |
| 30 | |
| 31 | colours: usize, |
| 32 | |
| 33 | palette_stride: usize, |
| 34 | |
| 35 | palette_at: usize, |
| 36 | |
| 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 | |
| 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 | |
| 67 | |
| 68 | |
| 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 | |
| 80 | |
| 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 | |
| 111 | |
| 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 | |
| 125 | |
| 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 | |
| 148 | |
| 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 | |
| 155 | |
| 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 | |
| 166 | |
| 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 | |
| 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 | |
| 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 | |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 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 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | |
| 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 | |
| 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 | |
| 288 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 409 | out.push([entry[2], entry[1], entry[0]]); |
| 410 | } |
| 411 | Ok(out) |
| 412 | } |
| 413 | |
| 414 | |
| 415 | |
| 416 | |
| 417 | |
| 418 | |
| 419 | |
| 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 | |
| 450 | 0 => { |
| 451 | x = 0; |
| 452 | y += 1; |
| 453 | } |
| 454 | |
| 455 | 1 => break, |
| 456 | |
| 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 | |
| 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 | } |