1 use std::convert::TryFrom;
2 use std::io::{self, Cursor, Read, Seek, SeekFrom};
3 use std::iter::{repeat, Iterator, Rev};
4 use std::marker::PhantomData;
5 use std::slice::ChunksMut;
6 use std::{error, fmt, mem};
7 use std::cmp::{self, Ordering};
8 
9 use byteorder::{LittleEndian, ReadBytesExt};
10 
11 use crate::color::ColorType;
12 use crate::error::{
13     DecodingError, ImageError, ImageResult, UnsupportedError, UnsupportedErrorKind,
14 };
15 use crate::image::{self, ImageDecoder, ImageDecoderExt, ImageFormat, Progress};
16 
17 const BITMAPCOREHEADER_SIZE: u32 = 12;
18 const BITMAPINFOHEADER_SIZE: u32 = 40;
19 const BITMAPV2HEADER_SIZE: u32 = 52;
20 const BITMAPV3HEADER_SIZE: u32 = 56;
21 const BITMAPV4HEADER_SIZE: u32 = 108;
22 const BITMAPV5HEADER_SIZE: u32 = 124;
23 
24 static LOOKUP_TABLE_3_BIT_TO_8_BIT: [u8; 8] = [0, 36, 73, 109, 146, 182, 219, 255];
25 static LOOKUP_TABLE_4_BIT_TO_8_BIT: [u8; 16] = [
26     0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255,
27 ];
28 static LOOKUP_TABLE_5_BIT_TO_8_BIT: [u8; 32] = [
29     0, 8, 16, 25, 33, 41, 49, 58, 66, 74, 82, 90, 99, 107, 115, 123, 132, 140, 148, 156, 165, 173,
30     181, 189, 197, 206, 214, 222, 230, 239, 247, 255,
31 ];
32 static LOOKUP_TABLE_6_BIT_TO_8_BIT: [u8; 64] = [
33     0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93,
34     97, 101, 105, 109, 113, 117, 121, 125, 130, 134, 138, 142, 146, 150, 154, 158, 162, 166, 170,
35     174, 178, 182, 186, 190, 194, 198, 202, 206, 210, 215, 219, 223, 227, 231, 235, 239, 243, 247,
36     251, 255,
37 ];
38 
39 static R5_G5_B5_COLOR_MASK: Bitfields = Bitfields {
40     r: Bitfield { len: 5, shift: 10 },
41     g: Bitfield { len: 5, shift: 5 },
42     b: Bitfield { len: 5, shift: 0 },
43     a: Bitfield { len: 0, shift: 0 },
44 };
45 const R8_G8_B8_COLOR_MASK: Bitfields = Bitfields {
46     r: Bitfield { len: 8, shift: 24 },
47     g: Bitfield { len: 8, shift: 16 },
48     b: Bitfield { len: 8, shift: 8 },
49     a: Bitfield { len: 0, shift: 0 },
50 };
51 
52 const RLE_ESCAPE: u8 = 0;
53 const RLE_ESCAPE_EOL: u8 = 0;
54 const RLE_ESCAPE_EOF: u8 = 1;
55 const RLE_ESCAPE_DELTA: u8 = 2;
56 
57 /// The maximum width/height the decoder will process.
58 const MAX_WIDTH_HEIGHT: i32 = 0xFFFF;
59 
60 #[derive(PartialEq, Copy, Clone)]
61 enum ImageType {
62     Palette,
63     RGB16,
64     RGB24,
65     RGB32,
66     RGBA32,
67     RLE8,
68     RLE4,
69     Bitfields16,
70     Bitfields32,
71 }
72 
73 #[derive(PartialEq)]
74 enum BMPHeaderType {
75     Core,
76     Info,
77     V2,
78     V3,
79     V4,
80     V5,
81 }
82 
83 #[derive(PartialEq)]
84 enum FormatFullBytes {
85     RGB24,
86     RGB32,
87     RGBA32,
88     Format888,
89 }
90 
91 enum Chunker<'a> {
92     FromTop(ChunksMut<'a, u8>),
93     FromBottom(Rev<ChunksMut<'a, u8>>),
94 }
95 
96 pub(crate) struct RowIterator<'a> {
97     chunks: Chunker<'a>,
98 }
99 
100 impl<'a> Iterator for RowIterator<'a> {
101     type Item = &'a mut [u8];
102 
103     #[inline(always)]
next(&mut self) -> Option<&'a mut [u8]>104     fn next(&mut self) -> Option<&'a mut [u8]> {
105         match self.chunks {
106             Chunker::FromTop(ref mut chunks) => chunks.next(),
107             Chunker::FromBottom(ref mut chunks) => chunks.next(),
108         }
109     }
110 }
111 
112 /// All errors that can occur when attempting to parse a BMP
113 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
114 enum DecoderError {
115     // We ran out of data while we still had rows to fill in.
116     RleDataTooShort,
117 
118     /// The bitfield mask interleaves set and unset bits
119     BitfieldMaskNonContiguous,
120     /// Bitfield mask invalid (e.g. too long for specified type)
121     BitfieldMaskInvalid,
122     /// Bitfield (of the specified width – 16- or 32-bit) mask not present
123     BitfieldMaskMissing(u32),
124     /// Bitfield (of the specified width – 16- or 32-bit) masks not present
125     BitfieldMasksMissing(u32),
126 
127     /// BMP's "BM" signature wrong or missing
128     BmpSignatureInvalid,
129     /// More than the exactly one allowed plane specified by the format
130     MoreThanOnePlane,
131     /// Invalid amount of bits per channel for the specified image type
132     InvalidChannelWidth(ChannelWidthError, u16),
133 
134     /// The width is negative
135     NegativeWidth(i32),
136     /// One of the dimensions is larger than a soft limit
137     ImageTooLarge(i32, i32),
138     /// The height is `i32::min_value()`
139     ///
140     /// General negative heights specify top-down DIBs
141     InvalidHeight,
142 
143     /// Specified image type is invalid for top-down BMPs (i.e. is compressed)
144     ImageTypeInvalidForTopDown(u32),
145     /// Image type not currently recognized by the decoder
146     ImageTypeUnknown(u32),
147 
148     /// Bitmap header smaller than the core header
149     HeaderTooSmall(u32),
150 
151     /// The palette is bigger than allowed by the bit count of the BMP
152     PaletteSizeExceeded {
153         colors_used: u32,
154         bit_count: u16,
155     }
156 }
157 
158 impl fmt::Display for DecoderError {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result159     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160         match self {
161             DecoderError::RleDataTooShort =>
162                 f.write_str("Not enough RLE data"),
163             DecoderError::BitfieldMaskNonContiguous =>
164                 f.write_str("Non-contiguous bitfield mask"),
165             DecoderError::BitfieldMaskInvalid =>
166                 f.write_str("Invalid bitfield mask"),
167             DecoderError::BitfieldMaskMissing(bb) =>
168                 f.write_fmt(format_args!("Missing {}-bit bitfield mask", bb)),
169             DecoderError::BitfieldMasksMissing(bb) =>
170                 f.write_fmt(format_args!("Missing {}-bit bitfield masks", bb)),
171             DecoderError::BmpSignatureInvalid =>
172                 f.write_str("BMP signature not found"),
173             DecoderError::MoreThanOnePlane =>
174                 f.write_str("More than one plane"),
175             DecoderError::InvalidChannelWidth(tp, n) =>
176                 f.write_fmt(format_args!("Invalid channel bit count for {}: {}", tp, n)),
177             DecoderError::NegativeWidth(w) =>
178                 f.write_fmt(format_args!("Negative width ({})", w)),
179             DecoderError::ImageTooLarge(w, h) =>
180                 f.write_fmt(format_args!("Image too large (one of ({}, {}) > soft limit of {})", w, h, MAX_WIDTH_HEIGHT)),
181             DecoderError::InvalidHeight =>
182                 f.write_str("Invalid height"),
183             DecoderError::ImageTypeInvalidForTopDown(tp) =>
184                 f.write_fmt(format_args!("Invalid image type {} for top-down image.", tp)),
185             DecoderError::ImageTypeUnknown(tp) =>
186                 f.write_fmt(format_args!("Unknown image compression type {}", tp)),
187             DecoderError::HeaderTooSmall(s) =>
188                 f.write_fmt(format_args!("Bitmap header too small ({} bytes)", s)),
189             DecoderError::PaletteSizeExceeded { colors_used, bit_count } =>
190                 f.write_fmt(format_args!("Palette size {} exceeds maximum size for BMP with bit count of {}", colors_used, bit_count)),
191         }
192     }
193 }
194 
195 impl From<DecoderError> for ImageError {
from(e: DecoderError) -> ImageError196     fn from(e: DecoderError) -> ImageError {
197         ImageError::Decoding(DecodingError::new(ImageFormat::Bmp.into(), e))
198     }
199 }
200 
201 impl error::Error for DecoderError {}
202 
203 /// Distinct image types whose saved channel width can be invalid
204 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
205 enum ChannelWidthError {
206     /// RGB
207     Rgb,
208     /// 8-bit run length encoding
209     Rle8,
210     /// 4-bit run length encoding
211     Rle4,
212     /// Bitfields (16- or 32-bit)
213     Bitfields,
214 }
215 
216 impl fmt::Display for ChannelWidthError {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result217     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218         f.write_str(match self {
219             ChannelWidthError::Rgb => "RGB",
220             ChannelWidthError::Rle8 => "RLE8",
221             ChannelWidthError::Rle4 => "RLE4",
222             ChannelWidthError::Bitfields => "bitfields",
223         })
224     }
225 }
226 
227 /// Convenience function to check if the combination of width, length and number of
228 /// channels would result in a buffer that would overflow.
check_for_overflow(width: i32, length: i32, channels: usize) -> ImageResult<()>229 fn check_for_overflow(width: i32, length: i32, channels: usize) -> ImageResult<()> {
230     num_bytes(width, length, channels)
231         .map(|_| ())
232         .ok_or_else(||
233             ImageError::Unsupported(UnsupportedError::from_format_and_kind(
234                 ImageFormat::Bmp.into(),
235                 UnsupportedErrorKind::GenericFeature(format!("Image dimensions ({}x{} w/{} channels) are too large",
236                     width, length, channels)))))
237 }
238 
239 /// Calculate how many many bytes a buffer holding a decoded image with these properties would
240 /// require. Returns `None` if the buffer size would overflow or if one of the sizes are negative.
num_bytes(width: i32, length: i32, channels: usize) -> Option<usize>241 fn num_bytes(width: i32, length: i32, channels: usize) -> Option<usize> {
242     if width <= 0 || length <= 0 {
243         None
244     } else {
245         match channels.checked_mul(width as usize) {
246             Some(n) => n.checked_mul(length as usize),
247             None => None,
248         }
249     }
250 }
251 
252 /// The maximum starting number of pixels in the pixel buffer, might want to tweak this.
253 ///
254 /// For images that specify large sizes, we don't allocate the full buffer right away
255 /// to somewhat mitigate trying to make the decoder run out of memory by sending a bogus image.
256 /// This is somewhat of a workaroud as ideally we would check against the expected file size
257 /// but that's not possible through the Read and Seek traits alone and would require the encoder
258 /// to provided with it from the caller.
259 ///
260 /// NOTE: This is multiplied by 3 or 4 depending on the number of channels to get the maximum
261 /// starting buffer size. This amounts to about 134 mb for a buffer with 4 channels.
262 const MAX_INITIAL_PIXELS: usize = 8192 * 4096;
263 
264 /// Sets all bytes in an mutable iterator over slices of bytes to 0.
blank_bytes<'a, T: Iterator<Item = &'a mut [u8]>>(iterator: T)265 fn blank_bytes<'a, T: Iterator<Item = &'a mut [u8]>>(iterator: T) {
266     for chunk in iterator {
267         for b in chunk {
268             *b = 0;
269         }
270     }
271 }
272 
273 /// Extend the buffer to `full_size`, copying existing data to the end of the buffer. Returns slice
274 /// pointing to the part of the buffer that is not yet filled in.
275 ///
276 /// If blank is true, the bytes in the new buffer that are not filled in are set to 0.
277 /// This is used for rle-encoded images as the decoding process for these may not fill in all the
278 /// pixels.
279 ///
280 /// As BMP images are usually stored with the rows upside-down we have to write the image data
281 /// starting at the end of the buffer and thus we have to make sure the existing data is put at the
282 /// end of the buffer.
283 #[inline(never)]
284 #[cold]
extend_buffer(buffer: &mut Vec<u8>, full_size: usize, blank: bool) -> &mut [u8]285 fn extend_buffer(buffer: &mut Vec<u8>, full_size: usize, blank: bool) -> &mut [u8] {
286     let old_size = buffer.len();
287     let extend = full_size - buffer.len();
288 
289     buffer.extend(repeat(0xFF).take(extend));
290     assert_eq!(buffer.len(), full_size);
291 
292     let ret = if extend >= old_size {
293         // If the full buffer length is more or equal to twice the initial one, we can simply
294         // copy the data in the lower part of the buffer to the end of it and input from there.
295         let (new, old) = buffer.split_at_mut(extend);
296         old.copy_from_slice(&new[..old_size]);
297         new
298     } else {
299         // If the full size is less than twice the initial buffer, we have to
300         // copy in two steps
301         let overlap = old_size - extend;
302 
303         // First we copy the data that fits into the bit we extended.
304         let (lower, upper) = buffer.split_at_mut(old_size);
305         upper.copy_from_slice(&lower[overlap..]);
306 
307         // Then we slide the data that hasn't been copied yet to the top of the buffer
308         let (new, old) = lower.split_at_mut(extend);
309         old[..overlap].copy_from_slice(&new[..overlap]);
310         new
311     };
312     if blank {
313         for b in ret.iter_mut() {
314             *b = 0;
315         }
316     };
317     ret
318 }
319 
320 /// Call the provided function on each row of the provided buffer, returning Err if the provided
321 /// function returns an error, extends the buffer if it's not large enough.
with_rows<F>( buffer: &mut Vec<u8>, width: i32, height: i32, channels: usize, top_down: bool, mut func: F, ) -> io::Result<()> where F: FnMut(&mut [u8]) -> io::Result<()>,322 fn with_rows<F>(
323     buffer: &mut Vec<u8>,
324     width: i32,
325     height: i32,
326     channels: usize,
327     top_down: bool,
328     mut func: F,
329 ) -> io::Result<()>
330 where
331     F: FnMut(&mut [u8]) -> io::Result<()>,
332 {
333     // An overflow should already have been checked for when this is called,
334     // though we check anyhow, as it somehow seems to increase performance slightly.
335     let row_width = channels.checked_mul(width as usize).unwrap();
336     let full_image_size = row_width.checked_mul(height as usize).unwrap();
337 
338     if !top_down {
339         for row in buffer.chunks_mut(row_width).rev() {
340             func(row)?;
341         }
342 
343         // If we need more space, extend the buffer.
344         if buffer.len() < full_image_size {
345             let new_space = extend_buffer(buffer, full_image_size, false);
346             for row in new_space.chunks_mut(row_width).rev() {
347                 func(row)?;
348             }
349         }
350     } else {
351         for row in buffer.chunks_mut(row_width) {
352             func(row)?;
353         }
354         if buffer.len() < full_image_size {
355             // If the image is stored in top-down order, we can simply use the extend function
356             // from vec to extend the buffer..
357             let extend = full_image_size - buffer.len();
358             buffer.extend(repeat(0xFF).take(extend));
359             let len = buffer.len();
360             for row in buffer[len - row_width..].chunks_mut(row_width) {
361                 func(row)?;
362             }
363         };
364     }
365     Ok(())
366 }
367 
set_8bit_pixel_run<'a, T: Iterator<Item = &'a u8>>( pixel_iter: &mut ChunksMut<u8>, palette: &[(u8, u8, u8)], indices: T, n_pixels: usize, ) -> bool368 fn set_8bit_pixel_run<'a, T: Iterator<Item = &'a u8>>(
369     pixel_iter: &mut ChunksMut<u8>,
370     palette: &[(u8, u8, u8)],
371     indices: T,
372     n_pixels: usize,
373 ) -> bool {
374     for idx in indices.take(n_pixels) {
375         if let Some(pixel) = pixel_iter.next() {
376             let (r, g, b) = palette[*idx as usize];
377             pixel[0] = r;
378             pixel[1] = g;
379             pixel[2] = b;
380         } else {
381             return false;
382         }
383     }
384     true
385 }
386 
set_4bit_pixel_run<'a, T: Iterator<Item = &'a u8>>( pixel_iter: &mut ChunksMut<u8>, palette: &[(u8, u8, u8)], indices: T, mut n_pixels: usize, ) -> bool387 fn set_4bit_pixel_run<'a, T: Iterator<Item = &'a u8>>(
388     pixel_iter: &mut ChunksMut<u8>,
389     palette: &[(u8, u8, u8)],
390     indices: T,
391     mut n_pixels: usize,
392 ) -> bool {
393     for idx in indices {
394         macro_rules! set_pixel {
395             ($i:expr) => {
396                 if n_pixels == 0 {
397                     break;
398                 }
399                 if let Some(pixel) = pixel_iter.next() {
400                     let (r, g, b) = palette[$i as usize];
401                     pixel[0] = r;
402                     pixel[1] = g;
403                     pixel[2] = b;
404                 } else {
405                     return false;
406                 }
407                 n_pixels -= 1;
408             };
409         }
410         set_pixel!(idx >> 4);
411         set_pixel!(idx & 0xf);
412     }
413     true
414 }
415 
416 #[rustfmt::skip]
set_2bit_pixel_run<'a, T: Iterator<Item = &'a u8>>( pixel_iter: &mut ChunksMut<u8>, palette: &[(u8, u8, u8)], indices: T, mut n_pixels: usize, ) -> bool417 fn set_2bit_pixel_run<'a, T: Iterator<Item = &'a u8>>(
418     pixel_iter: &mut ChunksMut<u8>,
419     palette: &[(u8, u8, u8)],
420     indices: T,
421     mut n_pixels: usize,
422 ) -> bool {
423     for idx in indices {
424         macro_rules! set_pixel {
425             ($i:expr) => {
426                 if n_pixels == 0 {
427                     break;
428                 }
429                 if let Some(pixel) = pixel_iter.next() {
430                     let (r, g, b) = palette[$i as usize];
431                     pixel[0] = r;
432                     pixel[1] = g;
433                     pixel[2] = b;
434                 } else {
435                     return false;
436                 }
437                 n_pixels -= 1;
438             };
439         }
440         set_pixel!((idx >> 6) & 0x3u8);
441         set_pixel!((idx >> 4) & 0x3u8);
442         set_pixel!((idx >> 2) & 0x3u8);
443         set_pixel!( idx       & 0x3u8);
444     }
445     true
446 }
447 
set_1bit_pixel_run<'a, T: Iterator<Item = &'a u8>>( pixel_iter: &mut ChunksMut<u8>, palette: &[(u8, u8, u8)], indices: T, )448 fn set_1bit_pixel_run<'a, T: Iterator<Item = &'a u8>>(
449     pixel_iter: &mut ChunksMut<u8>,
450     palette: &[(u8, u8, u8)],
451     indices: T,
452 ) {
453     for idx in indices {
454         let mut bit = 0x80;
455         loop {
456             if let Some(pixel) = pixel_iter.next() {
457                 let (r, g, b) = palette[((idx & bit) != 0) as usize];
458                 pixel[0] = r;
459                 pixel[1] = g;
460                 pixel[2] = b;
461             } else {
462                 return;
463             }
464 
465             bit >>= 1;
466             if bit == 0 {
467                 break;
468             }
469         }
470     }
471 }
472 
473 #[derive(PartialEq, Eq)]
474 struct Bitfield {
475     shift: u32,
476     len: u32,
477 }
478 
479 impl Bitfield {
from_mask(mask: u32, max_len: u32) -> ImageResult<Bitfield>480     fn from_mask(mask: u32, max_len: u32) -> ImageResult<Bitfield> {
481         if mask == 0 {
482             return Ok(Bitfield { shift: 0, len: 0 });
483         }
484         let mut shift = mask.trailing_zeros();
485         let mut len = (!(mask >> shift)).trailing_zeros();
486         if len != mask.count_ones() {
487             return Err(DecoderError::BitfieldMaskNonContiguous.into());
488         }
489         if len + shift > max_len {
490             return Err(DecoderError::BitfieldMaskInvalid.into());
491         }
492         if len > 8 {
493             shift += len - 8;
494             len = 8;
495         }
496         Ok(Bitfield { shift, len })
497     }
498 
read(&self, data: u32) -> u8499     fn read(&self, data: u32) -> u8 {
500         let data = data >> self.shift;
501         match self.len {
502             1 => ((data & 0b1) * 0xff) as u8,
503             2 => ((data & 0b11) * 0x55) as u8,
504             3 => LOOKUP_TABLE_3_BIT_TO_8_BIT[(data & 0b00_0111) as usize],
505             4 => LOOKUP_TABLE_4_BIT_TO_8_BIT[(data & 0b00_1111) as usize],
506             5 => LOOKUP_TABLE_5_BIT_TO_8_BIT[(data & 0b01_1111) as usize],
507             6 => LOOKUP_TABLE_6_BIT_TO_8_BIT[(data & 0b11_1111) as usize],
508             7 => ((data & 0x7f) << 1 | (data & 0x7f) >> 6) as u8,
509             8 => (data & 0xff) as u8,
510             _ => panic!(),
511         }
512     }
513 }
514 
515 #[derive(PartialEq, Eq)]
516 struct Bitfields {
517     r: Bitfield,
518     g: Bitfield,
519     b: Bitfield,
520     a: Bitfield,
521 }
522 
523 impl Bitfields {
from_mask( r_mask: u32, g_mask: u32, b_mask: u32, a_mask: u32, max_len: u32, ) -> ImageResult<Bitfields>524     fn from_mask(
525         r_mask: u32,
526         g_mask: u32,
527         b_mask: u32,
528         a_mask: u32,
529         max_len: u32,
530     ) -> ImageResult<Bitfields> {
531         let bitfields = Bitfields {
532             r: Bitfield::from_mask(r_mask, max_len)?,
533             g: Bitfield::from_mask(g_mask, max_len)?,
534             b: Bitfield::from_mask(b_mask, max_len)?,
535             a: Bitfield::from_mask(a_mask, max_len)?,
536         };
537         if bitfields.r.len == 0 || bitfields.g.len == 0 || bitfields.b.len == 0 {
538             return Err(DecoderError::BitfieldMaskMissing(max_len).into());
539         }
540         Ok(bitfields)
541     }
542 }
543 
544 /// A bmp decoder
545 pub struct BmpDecoder<R> {
546     reader: R,
547 
548     bmp_header_type: BMPHeaderType,
549 
550     width: i32,
551     height: i32,
552     data_offset: u64,
553     top_down: bool,
554     no_file_header: bool,
555     add_alpha_channel: bool,
556     has_loaded_metadata: bool,
557     image_type: ImageType,
558 
559     bit_count: u16,
560     colors_used: u32,
561     palette: Option<Vec<(u8, u8, u8)>>,
562     bitfields: Option<Bitfields>,
563 }
564 
565 enum RLEInsn {
566     EndOfFile,
567     EndOfRow,
568     Delta(u8, u8),
569     Absolute(u8, Vec<u8>),
570     PixelRun(u8, u8),
571 }
572 
573 struct RLEInsnIterator<'a, R: 'a + Read> {
574     r: &'a mut R,
575     image_type: ImageType,
576 }
577 
578 impl<'a, R: Read> Iterator for RLEInsnIterator<'a, R> {
579     type Item = RLEInsn;
580 
next(&mut self) -> Option<RLEInsn>581     fn next(&mut self) -> Option<RLEInsn> {
582         let control_byte = match self.r.read_u8() {
583             Ok(b) => b,
584             Err(_) => return None,
585         };
586 
587         match control_byte {
588             RLE_ESCAPE => {
589                 let op = match self.r.read_u8() {
590                     Ok(b) => b,
591                     Err(_) => return None,
592                 };
593 
594                 match op {
595                     RLE_ESCAPE_EOL => Some(RLEInsn::EndOfRow),
596                     RLE_ESCAPE_EOF => Some(RLEInsn::EndOfFile),
597                     RLE_ESCAPE_DELTA => {
598                         let xdelta = match self.r.read_u8() {
599                             Ok(n) => n,
600                             Err(_) => return None,
601                         };
602                         let ydelta = match self.r.read_u8() {
603                             Ok(n) => n,
604                             Err(_) => return None,
605                         };
606                         Some(RLEInsn::Delta(xdelta, ydelta))
607                     }
608                     _ => {
609                         let mut length = op as usize;
610                         if self.image_type == ImageType::RLE4 {
611                             length = (length + 1) / 2;
612                         }
613                         length += length & 1;
614                         let mut buffer = vec![0; length];
615                         match self.r.read_exact(&mut buffer) {
616                             Ok(()) => Some(RLEInsn::Absolute(op, buffer)),
617                             Err(_) => None,
618                         }
619                     }
620                 }
621             }
622             _ => match self.r.read_u8() {
623                 Ok(palette_index) => Some(RLEInsn::PixelRun(control_byte, palette_index)),
624                 Err(_) => None,
625             },
626         }
627     }
628 }
629 
630 impl<R: Read + Seek> BmpDecoder<R> {
631     /// Create a new decoder that decodes from the stream ```r```
new(reader: R) -> ImageResult<BmpDecoder<R>>632     pub fn new(reader: R) -> ImageResult<BmpDecoder<R>> {
633         let mut decoder = BmpDecoder {
634             reader,
635 
636             bmp_header_type: BMPHeaderType::Info,
637 
638             width: 0,
639             height: 0,
640             data_offset: 0,
641             top_down: false,
642             no_file_header: false,
643             add_alpha_channel: false,
644             has_loaded_metadata: false,
645             image_type: ImageType::Palette,
646 
647             bit_count: 0,
648             colors_used: 0,
649             palette: None,
650             bitfields: None,
651         };
652 
653         decoder.read_metadata()?;
654         Ok(decoder)
655     }
656 
657     #[cfg(feature = "ico")]
new_with_ico_format(reader: R) -> ImageResult<BmpDecoder<R>>658     pub(crate) fn new_with_ico_format(reader: R) -> ImageResult<BmpDecoder<R>> {
659         let mut decoder = BmpDecoder {
660             reader,
661 
662             bmp_header_type: BMPHeaderType::Info,
663 
664             width: 0,
665             height: 0,
666             data_offset: 0,
667             top_down: false,
668             no_file_header: false,
669             add_alpha_channel: false,
670             has_loaded_metadata: false,
671             image_type: ImageType::Palette,
672 
673             bit_count: 0,
674             colors_used: 0,
675             palette: None,
676             bitfields: None,
677         };
678 
679         decoder.read_metadata_in_ico_format()?;
680         Ok(decoder)
681     }
682 
683     #[cfg(feature = "ico")]
reader(&mut self) -> &mut R684     pub(crate) fn reader(&mut self) -> &mut R {
685         &mut self.reader
686     }
687 
read_file_header(&mut self) -> ImageResult<()>688     fn read_file_header(&mut self) -> ImageResult<()> {
689         if self.no_file_header {
690             return Ok(());
691         }
692         let mut signature = [0; 2];
693         self.reader.read_exact(&mut signature)?;
694 
695         if signature != b"BM"[..] {
696             return Err(DecoderError::BmpSignatureInvalid.into());
697         }
698 
699         // The next 8 bytes represent file size, followed the 4 reserved bytes
700         // We're not interesting these values
701         self.reader.read_u32::<LittleEndian>()?;
702         self.reader.read_u32::<LittleEndian>()?;
703 
704         self.data_offset = u64::from(self.reader.read_u32::<LittleEndian>()?);
705 
706         Ok(())
707     }
708 
709     /// Read BITMAPCOREHEADER https://msdn.microsoft.com/en-us/library/vs/alm/dd183372(v=vs.85).aspx
710     ///
711     /// returns Err if any of the values are invalid.
read_bitmap_core_header(&mut self) -> ImageResult<()>712     fn read_bitmap_core_header(&mut self) -> ImageResult<()> {
713         // As height/width values in BMP files with core headers are only 16 bits long,
714         // they won't be larger than `MAX_WIDTH_HEIGHT`.
715         self.width = i32::from(self.reader.read_u16::<LittleEndian>()?);
716         self.height = i32::from(self.reader.read_u16::<LittleEndian>()?);
717 
718         check_for_overflow(self.width, self.height, self.num_channels())?;
719 
720         // Number of planes (format specifies that this should be 1).
721         if self.reader.read_u16::<LittleEndian>()? != 1 {
722             return Err(DecoderError::MoreThanOnePlane.into());
723         }
724 
725         self.bit_count = self.reader.read_u16::<LittleEndian>()?;
726         self.image_type = match self.bit_count {
727             1 | 4 | 8 => ImageType::Palette,
728             24 => ImageType::RGB24,
729             _ => return Err(DecoderError::InvalidChannelWidth(ChannelWidthError::Rgb, self.bit_count).into()),
730         };
731 
732         Ok(())
733     }
734 
735     /// Read BITMAPINFOHEADER https://msdn.microsoft.com/en-us/library/vs/alm/dd183376(v=vs.85).aspx
736     /// or BITMAPV{2|3|4|5}HEADER.
737     ///
738     /// returns Err if any of the values are invalid.
read_bitmap_info_header(&mut self) -> ImageResult<()>739     fn read_bitmap_info_header(&mut self) -> ImageResult<()> {
740         self.width = self.reader.read_i32::<LittleEndian>()?;
741         self.height = self.reader.read_i32::<LittleEndian>()?;
742 
743         // Width can not be negative
744         if self.width < 0 {
745             return Err(DecoderError::NegativeWidth(self.width).into());
746         } else if self.width > MAX_WIDTH_HEIGHT || self.height > MAX_WIDTH_HEIGHT {
747             // Limit very large image sizes to avoid OOM issues. Images with these sizes are
748             // unlikely to be valid anyhow.
749             return Err(DecoderError::ImageTooLarge(self.width, self.height).into());
750         }
751 
752         if self.height == i32::min_value() {
753             return Err(DecoderError::InvalidHeight.into());
754         }
755 
756         // A negative height indicates a top-down DIB.
757         if self.height < 0 {
758             self.height *= -1;
759             self.top_down = true;
760         }
761 
762         check_for_overflow(self.width, self.height, self.num_channels())?;
763 
764         // Number of planes (format specifies that this should be 1).
765         if self.reader.read_u16::<LittleEndian>()? != 1 {
766             return Err(DecoderError::MoreThanOnePlane.into());
767         }
768 
769         self.bit_count = self.reader.read_u16::<LittleEndian>()?;
770         let image_type_u32 = self.reader.read_u32::<LittleEndian>()?;
771 
772         // Top-down dibs can not be compressed.
773         if self.top_down && image_type_u32 != 0 && image_type_u32 != 3 {
774             return Err(DecoderError::ImageTypeInvalidForTopDown(image_type_u32).into());
775         }
776         self.image_type = match image_type_u32 {
777             0 => match self.bit_count {
778                 1 | 2 | 4 | 8 => ImageType::Palette,
779                 16 => ImageType::RGB16,
780                 24 => ImageType::RGB24,
781                 32 if self.add_alpha_channel => ImageType::RGBA32,
782                 32 => ImageType::RGB32,
783                 _ => return Err(DecoderError::InvalidChannelWidth(ChannelWidthError::Rgb, self.bit_count).into()),
784             },
785             1 => match self.bit_count {
786                 8 => ImageType::RLE8,
787                 _ => return Err(DecoderError::InvalidChannelWidth(ChannelWidthError::Rle8, self.bit_count).into()),
788             },
789             2 => match self.bit_count {
790                 4 => ImageType::RLE4,
791                 _ => return Err(DecoderError::InvalidChannelWidth(ChannelWidthError::Rle4, self.bit_count).into()),
792             },
793             3 => match self.bit_count {
794                 16 => ImageType::Bitfields16,
795                 32 => ImageType::Bitfields32,
796                 _ => return Err(DecoderError::InvalidChannelWidth(ChannelWidthError::Bitfields, self.bit_count).into()),
797             },
798             4 => {
799                 // JPEG compression is not implemented yet.
800                 return Err(ImageError::Unsupported(
801                     UnsupportedError::from_format_and_kind(
802                         ImageFormat::Bmp.into(),
803                         UnsupportedErrorKind::GenericFeature("JPEG compression".to_owned()),
804                     ),
805                 ));
806             }
807             5 => {
808                 // PNG compression is not implemented yet.
809                 return Err(ImageError::Unsupported(
810                     UnsupportedError::from_format_and_kind(
811                         ImageFormat::Bmp.into(),
812                         UnsupportedErrorKind::GenericFeature("PNG compression".to_owned()),
813                     ),
814                 ));
815             }
816             11 | 12 | 13 => {
817                 // CMYK types are not implemented yet.
818                 return Err(ImageError::Unsupported(
819                     UnsupportedError::from_format_and_kind(
820                         ImageFormat::Bmp.into(),
821                         UnsupportedErrorKind::GenericFeature("CMYK format".to_owned()),
822                     ),
823                 ));
824             }
825             _ => {
826                 // Unknown compression type.
827                 return Err(DecoderError::ImageTypeUnknown(image_type_u32).into())
828             }
829         };
830 
831         // The next 12 bytes represent data array size in bytes,
832         // followed the horizontal and vertical printing resolutions
833         // We will calculate the pixel array size using width & height of image
834         // We're not interesting the horz or vert printing resolutions
835         self.reader.read_u32::<LittleEndian>()?;
836         self.reader.read_u32::<LittleEndian>()?;
837         self.reader.read_u32::<LittleEndian>()?;
838 
839         self.colors_used = self.reader.read_u32::<LittleEndian>()?;
840 
841         // The next 4 bytes represent number of "important" colors
842         // We're not interested in this value, so we'll skip it
843         self.reader.read_u32::<LittleEndian>()?;
844 
845         Ok(())
846     }
847 
read_bitmasks(&mut self) -> ImageResult<()>848     fn read_bitmasks(&mut self) -> ImageResult<()> {
849         let r_mask = self.reader.read_u32::<LittleEndian>()?;
850         let g_mask = self.reader.read_u32::<LittleEndian>()?;
851         let b_mask = self.reader.read_u32::<LittleEndian>()?;
852 
853         let a_mask = match self.bmp_header_type {
854             BMPHeaderType::V3 | BMPHeaderType::V4 | BMPHeaderType::V5 => {
855                 self.reader.read_u32::<LittleEndian>()?
856             }
857             _ => 0,
858         };
859 
860         self.bitfields = match self.image_type {
861             ImageType::Bitfields16 => {
862                 Some(Bitfields::from_mask(r_mask, g_mask, b_mask, a_mask, 16)?)
863             }
864             ImageType::Bitfields32 => {
865                 Some(Bitfields::from_mask(r_mask, g_mask, b_mask, a_mask, 32)?)
866             }
867             _ => None,
868         };
869 
870         if self.bitfields.is_some() && a_mask != 0 {
871             self.add_alpha_channel = true;
872         }
873 
874         Ok(())
875     }
876 
read_metadata(&mut self) -> ImageResult<()>877     fn read_metadata(&mut self) -> ImageResult<()> {
878         if !self.has_loaded_metadata {
879             self.read_file_header()?;
880             let bmp_header_offset = self.reader.seek(SeekFrom::Current(0))?;
881             let bmp_header_size = self.reader.read_u32::<LittleEndian>()?;
882             let bmp_header_end = bmp_header_offset + u64::from(bmp_header_size);
883 
884             self.bmp_header_type = match bmp_header_size {
885                 BITMAPCOREHEADER_SIZE => BMPHeaderType::Core,
886                 BITMAPINFOHEADER_SIZE => BMPHeaderType::Info,
887                 BITMAPV2HEADER_SIZE => BMPHeaderType::V2,
888                 BITMAPV3HEADER_SIZE => BMPHeaderType::V3,
889                 BITMAPV4HEADER_SIZE => BMPHeaderType::V4,
890                 BITMAPV5HEADER_SIZE => BMPHeaderType::V5,
891                 _ if bmp_header_size < BITMAPCOREHEADER_SIZE => {
892                     // Size of any valid header types won't be smaller than core header type.
893                     return Err(DecoderError::HeaderTooSmall(bmp_header_size).into());
894                 }
895                 _ => {
896                     return Err(ImageError::Unsupported(
897                         UnsupportedError::from_format_and_kind(
898                             ImageFormat::Bmp.into(),
899                             UnsupportedErrorKind::GenericFeature(format!(
900                                 "Unknown bitmap header type (size={})",
901                                 bmp_header_size
902                             )),
903                         ),
904                     ))
905                 }
906             };
907 
908             match self.bmp_header_type {
909                 BMPHeaderType::Core => {
910                     self.read_bitmap_core_header()?;
911                 }
912                 BMPHeaderType::Info
913                 | BMPHeaderType::V2
914                 | BMPHeaderType::V3
915                 | BMPHeaderType::V4
916                 | BMPHeaderType::V5 => {
917                     self.read_bitmap_info_header()?;
918                 }
919             };
920 
921             match self.image_type {
922                 ImageType::Bitfields16 | ImageType::Bitfields32 => self.read_bitmasks()?,
923                 _ => {}
924             };
925 
926             self.reader.seek(SeekFrom::Start(bmp_header_end))?;
927 
928             match self.image_type {
929                 ImageType::Palette | ImageType::RLE4 | ImageType::RLE8 => self.read_palette()?,
930                 _ => {}
931             };
932 
933             if self.no_file_header {
934                 // Use the offset of the end of metadata instead of reading a BMP file header.
935                 self.data_offset = self.reader.seek(SeekFrom::Current(0))?;
936             }
937 
938             self.has_loaded_metadata = true;
939         }
940         Ok(())
941     }
942 
943     #[cfg(feature = "ico")]
944     #[doc(hidden)]
read_metadata_in_ico_format(&mut self) -> ImageResult<()>945     pub fn read_metadata_in_ico_format(&mut self) -> ImageResult<()> {
946         self.no_file_header = true;
947         self.add_alpha_channel = true;
948         self.read_metadata()?;
949 
950         // The height field in an ICO file is doubled to account for the AND mask
951         // (whether or not an AND mask is actually present).
952         self.height /= 2;
953         Ok(())
954     }
955 
get_palette_size(&mut self) -> ImageResult<usize>956     fn get_palette_size(&mut self) -> ImageResult<usize> {
957         match self.colors_used {
958             0 => Ok(1 << self.bit_count),
959             _ => {
960                 if self.colors_used > 1 << self.bit_count {
961                     return Err(DecoderError::PaletteSizeExceeded {
962                         colors_used: self.colors_used,
963                         bit_count: self.bit_count
964                     }.into());
965                 }
966                 Ok(self.colors_used as usize)
967             }
968         }
969     }
970 
bytes_per_color(&self) -> usize971     fn bytes_per_color(&self) -> usize {
972         match self.bmp_header_type {
973             BMPHeaderType::Core => 3,
974             _ => 4,
975         }
976     }
977 
read_palette(&mut self) -> ImageResult<()>978     fn read_palette(&mut self) -> ImageResult<()> {
979         const MAX_PALETTE_SIZE: usize = 256; // Palette indices are u8.
980 
981         let bytes_per_color = self.bytes_per_color();
982         let palette_size = self.get_palette_size()?;
983         let max_length = MAX_PALETTE_SIZE * bytes_per_color;
984 
985         let length = palette_size * bytes_per_color;
986         let mut buf = Vec::with_capacity(max_length);
987 
988         // Resize and read the palette entries to the buffer.
989         // We limit the buffer to at most 256 colours to avoid any oom issues as
990         // 8-bit images can't reference more than 256 indexes anyhow.
991         buf.resize(cmp::min(length, max_length), 0);
992         self.reader.by_ref().read_exact(&mut buf)?;
993 
994         // Allocate 256 entries even if palette_size is smaller, to prevent corrupt files from
995         // causing an out-of-bounds array access.
996         match length.cmp(&max_length) {
997             Ordering::Greater => {
998                 self.reader
999                     .seek(SeekFrom::Current((length - max_length) as i64))?;
1000             }
1001             Ordering::Less => buf.resize(max_length, 0),
1002             Ordering::Equal => (),
1003         }
1004 
1005         let p: Vec<(u8, u8, u8)> = (0..MAX_PALETTE_SIZE)
1006             .map(|i| {
1007                 let b = buf[bytes_per_color * i];
1008                 let g = buf[bytes_per_color * i + 1];
1009                 let r = buf[bytes_per_color * i + 2];
1010                 (r, g, b)
1011             })
1012             .collect();
1013 
1014         self.palette = Some(p);
1015 
1016         Ok(())
1017     }
1018 
num_channels(&self) -> usize1019     fn num_channels(&self) -> usize {
1020         if self.add_alpha_channel {
1021             4
1022         } else {
1023             3
1024         }
1025     }
1026 
1027     /// Create a buffer to hold the decoded pixel data.
1028     ///
1029     /// The buffer will be large enough to hold the whole image if it requires less than
1030     /// `MAX_INITIAL_PIXELS` times the number of channels bytes (adjusted to line up with the
1031     /// width of a row).
create_pixel_data(&self) -> Vec<u8>1032     fn create_pixel_data(&self) -> Vec<u8> {
1033         let row_width = self.num_channels() * self.width as usize;
1034         let max_pixels = self.num_channels() * MAX_INITIAL_PIXELS;
1035         // Make sure the maximum size is whole number of rows.
1036         let max_starting_size = max_pixels + row_width - (max_pixels % row_width);
1037         // The buffer has its bytes initially set to 0xFF as the ICO decoder relies on it.
1038         vec![0xFF; cmp::min(row_width * self.height as usize, max_starting_size)]
1039     }
1040 
rows<'a>(&self, pixel_data: &'a mut [u8]) -> RowIterator<'a>1041     fn rows<'a>(&self, pixel_data: &'a mut [u8]) -> RowIterator<'a> {
1042         let stride = self.width as usize * self.num_channels();
1043         if self.top_down {
1044             RowIterator {
1045                 chunks: Chunker::FromTop(pixel_data.chunks_mut(stride)),
1046             }
1047         } else {
1048             RowIterator {
1049                 chunks: Chunker::FromBottom(pixel_data.chunks_mut(stride).rev()),
1050             }
1051         }
1052     }
1053 
read_palettized_pixel_data(&mut self) -> ImageResult<Vec<u8>>1054     fn read_palettized_pixel_data(&mut self) -> ImageResult<Vec<u8>> {
1055         let mut pixel_data = self.create_pixel_data();
1056         let num_channels = self.num_channels();
1057         let row_byte_length = ((i32::from(self.bit_count) * self.width + 31) / 32 * 4) as usize;
1058         let mut indices = vec![0; row_byte_length];
1059         let palette = self.palette.as_ref().unwrap();
1060         let bit_count = self.bit_count;
1061         let reader = &mut self.reader;
1062         let width = self.width as usize;
1063 
1064         reader.seek(SeekFrom::Start(self.data_offset))?;
1065 
1066         with_rows(
1067             &mut pixel_data,
1068             self.width,
1069             self.height,
1070             num_channels,
1071             self.top_down,
1072             |row| {
1073                 reader.read_exact(&mut indices)?;
1074                 let mut pixel_iter = row.chunks_mut(num_channels);
1075                 match bit_count {
1076                     1 => {
1077                         set_1bit_pixel_run(&mut pixel_iter, palette, indices.iter());
1078                     }
1079                     2 => {
1080                         set_2bit_pixel_run(&mut pixel_iter, palette, indices.iter(), width);
1081                     }
1082                     4 => {
1083                         set_4bit_pixel_run(&mut pixel_iter, palette, indices.iter(), width);
1084                     }
1085                     8 => {
1086                         set_8bit_pixel_run(&mut pixel_iter, palette, indices.iter(), width);
1087                     }
1088                     _ => panic!(),
1089                 };
1090                 Ok(())
1091             },
1092         )?;
1093 
1094         Ok(pixel_data)
1095     }
1096 
read_16_bit_pixel_data(&mut self, bitfields: Option<&Bitfields>) -> ImageResult<Vec<u8>>1097     fn read_16_bit_pixel_data(&mut self, bitfields: Option<&Bitfields>) -> ImageResult<Vec<u8>> {
1098         let mut pixel_data = self.create_pixel_data();
1099         let num_channels = self.num_channels();
1100         let row_padding_len = self.width as usize % 2 * 2;
1101         let row_padding = &mut [0; 2][..row_padding_len];
1102         let bitfields = match bitfields {
1103             Some(b) => b,
1104             None => self.bitfields.as_ref().unwrap(),
1105         };
1106         let reader = &mut self.reader;
1107 
1108         reader.seek(SeekFrom::Start(self.data_offset))?;
1109 
1110         with_rows(
1111             &mut pixel_data,
1112             self.width,
1113             self.height,
1114             num_channels,
1115             self.top_down,
1116             |row| {
1117                 for pixel in row.chunks_mut(num_channels) {
1118                     let data = u32::from(reader.read_u16::<LittleEndian>()?);
1119 
1120                     pixel[0] = bitfields.r.read(data);
1121                     pixel[1] = bitfields.g.read(data);
1122                     pixel[2] = bitfields.b.read(data);
1123                     if num_channels == 4 {
1124                         pixel[3] = bitfields.a.read(data);
1125                     }
1126                 }
1127                 reader.read_exact(row_padding)
1128             },
1129         )?;
1130 
1131         Ok(pixel_data)
1132     }
1133 
1134     /// Read image data from a reader in 32-bit formats that use bitfields.
read_32_bit_pixel_data(&mut self) -> ImageResult<Vec<u8>>1135     fn read_32_bit_pixel_data(&mut self) -> ImageResult<Vec<u8>> {
1136         let mut pixel_data = self.create_pixel_data();
1137         let num_channels = self.num_channels();
1138 
1139         let bitfields = self.bitfields.as_ref().unwrap();
1140 
1141         let reader = &mut self.reader;
1142         reader.seek(SeekFrom::Start(self.data_offset))?;
1143 
1144         with_rows(
1145             &mut pixel_data,
1146             self.width,
1147             self.height,
1148             num_channels,
1149             self.top_down,
1150             |row| {
1151                 for pixel in row.chunks_mut(num_channels) {
1152                     let data = reader.read_u32::<LittleEndian>()?;
1153 
1154                     pixel[0] = bitfields.r.read(data);
1155                     pixel[1] = bitfields.g.read(data);
1156                     pixel[2] = bitfields.b.read(data);
1157                     if num_channels == 4 {
1158                         pixel[3] = bitfields.a.read(data);
1159                     }
1160                 }
1161                 Ok(())
1162             },
1163         )?;
1164 
1165         Ok(pixel_data)
1166     }
1167 
1168     /// Read image data from a reader where the colours are stored as 8-bit values (24 or 32-bit).
read_full_byte_pixel_data(&mut self, format: &FormatFullBytes) -> ImageResult<Vec<u8>>1169     fn read_full_byte_pixel_data(&mut self, format: &FormatFullBytes) -> ImageResult<Vec<u8>> {
1170         let mut pixel_data = self.create_pixel_data();
1171         let num_channels = self.num_channels();
1172         let row_padding_len = match *format {
1173             FormatFullBytes::RGB24 => (4 - (self.width as usize * 3) % 4) % 4,
1174             _ => 0,
1175         };
1176         let row_padding = &mut [0; 4][..row_padding_len];
1177 
1178         self.reader.seek(SeekFrom::Start(self.data_offset))?;
1179 
1180         let reader = &mut self.reader;
1181 
1182         with_rows(
1183             &mut pixel_data,
1184             self.width,
1185             self.height,
1186             num_channels,
1187             self.top_down,
1188             |row| {
1189                 for pixel in row.chunks_mut(num_channels) {
1190                     if *format == FormatFullBytes::Format888 {
1191                         reader.read_u8()?;
1192                     }
1193 
1194                     // Read the colour values (b, g, r).
1195                     // Reading 3 bytes and reversing them is significantly faster than reading one
1196                     // at a time.
1197                     reader.read_exact(&mut pixel[0..3])?;
1198                     pixel[0..3].reverse();
1199 
1200                     if *format == FormatFullBytes::RGB32 {
1201                         reader.read_u8()?;
1202                     }
1203 
1204                     // Read the alpha channel if present
1205                     if *format == FormatFullBytes::RGBA32 {
1206                         reader.read_exact(&mut pixel[3..4])?;
1207                     }
1208                 }
1209                 reader.read_exact(row_padding)
1210             },
1211         )?;
1212 
1213         Ok(pixel_data)
1214     }
1215 
read_rle_data(&mut self, image_type: ImageType) -> ImageResult<Vec<u8>>1216     fn read_rle_data(&mut self, image_type: ImageType) -> ImageResult<Vec<u8>> {
1217         // Seek to the start of the actual image data.
1218         self.reader.seek(SeekFrom::Start(self.data_offset))?;
1219 
1220         let full_image_size =
1221             num_bytes(self.width, self.height, self.num_channels()).ok_or_else(|| {
1222                 ImageError::Unsupported(UnsupportedError::from_format_and_kind(
1223                     ImageFormat::Bmp.into(),
1224                     UnsupportedErrorKind::GenericFeature(format!("Image dimensions ({}x{} w/{} channels) are too large",
1225                         self.width, self.height, self.num_channels()))))
1226             })?;
1227         let mut pixel_data = self.create_pixel_data();
1228         let (skip_pixels, skip_rows, eof_hit) =
1229             self.read_rle_data_step(&mut pixel_data, image_type, 0, 0)?;
1230         // Extend the buffer if there is still data left.
1231         // If eof_hit is true, it means that we hit an end-of-file marker in the last step and
1232         // we won't extend the buffer further to avoid small files with a large specified size causing memory issues.
1233         // This is only a rudimentary check, a file could still create a large buffer, but the
1234         // file would now have to at least have some data in it.
1235         if pixel_data.len() < full_image_size && !eof_hit {
1236             let new = extend_buffer(&mut pixel_data, full_image_size, true);
1237             self.read_rle_data_step(new, image_type, skip_pixels, skip_rows)?;
1238         }
1239         Ok(pixel_data)
1240     }
1241 
read_rle_data_step( &mut self, mut pixel_data: &mut [u8], image_type: ImageType, skip_pixels: u8, skip_rows: u8, ) -> ImageResult<(u8, u8, bool)>1242     fn read_rle_data_step(
1243         &mut self,
1244         mut pixel_data: &mut [u8],
1245         image_type: ImageType,
1246         skip_pixels: u8,
1247         skip_rows: u8,
1248     ) -> ImageResult<(u8, u8, bool)> {
1249         let num_channels = self.num_channels();
1250 
1251         let mut delta_rows_left = 0;
1252         let mut delta_pixels_left = skip_pixels;
1253         let mut eof_hit = false;
1254 
1255         // Scope the borrowing of pixel_data by the row iterator.
1256         {
1257             // Handling deltas in the RLE scheme means that we need to manually
1258             // iterate through rows and pixels.  Even if we didn't have to handle
1259             // deltas, we have to ensure that a single runlength doesn't straddle
1260             // two rows.
1261             let mut row_iter = self.rows(&mut pixel_data);
1262             // If we have previously hit a delta value,
1263             // blank the rows that are to be skipped.
1264             blank_bytes((&mut row_iter).take(skip_rows.into()));
1265             let mut insns_iter = RLEInsnIterator {
1266                 r: &mut self.reader,
1267                 image_type,
1268             };
1269             let p = self.palette.as_ref().unwrap();
1270 
1271             'row_loop: while let Some(row) = row_iter.next() {
1272                 let mut pixel_iter = row.chunks_mut(num_channels);
1273                 // Blank delta skipped pixels if any.
1274                 blank_bytes((&mut pixel_iter).take(delta_pixels_left.into()));
1275                 delta_pixels_left = 0;
1276 
1277                 'rle_loop: loop {
1278                     if let Some(insn) = insns_iter.next() {
1279                         match insn {
1280                             RLEInsn::EndOfFile => {
1281                                 blank_bytes(pixel_iter);
1282                                 blank_bytes(row_iter);
1283                                 eof_hit = true;
1284                                 break 'row_loop;
1285                             }
1286                             RLEInsn::EndOfRow => {
1287                                 blank_bytes(pixel_iter);
1288                                 break 'rle_loop;
1289                             }
1290                             RLEInsn::Delta(x_delta, y_delta) => {
1291                                 if y_delta > 0 {
1292                                     for n in 1..y_delta {
1293                                         if let Some(row) = row_iter.next() {
1294                                             // The msdn site on bitmap compression doesn't specify
1295                                             // what happens to the values skipped when encountering
1296                                             // a delta code, however IE and the windows image
1297                                             // preview seems to replace them with black pixels,
1298                                             // so we stick to that.
1299                                             for b in row {
1300                                                 *b = 0;
1301                                             }
1302                                         } else {
1303                                             delta_pixels_left = x_delta;
1304                                             // We've reached the end of the buffer.
1305                                             delta_rows_left = y_delta - n;
1306                                             break 'row_loop;
1307                                         }
1308                                     }
1309                                 }
1310 
1311                                 for _ in 0..x_delta {
1312                                     if let Some(pixel) = pixel_iter.next() {
1313                                         for b in pixel {
1314                                             *b = 0;
1315                                         }
1316                                     } else {
1317                                         // We can't go any further in this row.
1318                                         break;
1319                                     }
1320                                 }
1321                             }
1322                             RLEInsn::Absolute(length, indices) => {
1323                                 // Absolute mode cannot span rows, so if we run
1324                                 // out of pixels to process, we should stop
1325                                 // processing the image.
1326                                 match image_type {
1327                                     ImageType::RLE8 => {
1328                                         if !set_8bit_pixel_run(
1329                                             &mut pixel_iter,
1330                                             p,
1331                                             indices.iter(),
1332                                             length as usize,
1333                                         ) {
1334                                             break 'row_loop;
1335                                         }
1336                                     }
1337                                     ImageType::RLE4 => {
1338                                         if !set_4bit_pixel_run(
1339                                             &mut pixel_iter,
1340                                             p,
1341                                             indices.iter(),
1342                                             length as usize,
1343                                         ) {
1344                                             break 'row_loop;
1345                                         }
1346                                     }
1347                                     _ => panic!(),
1348                                 }
1349                             }
1350                             RLEInsn::PixelRun(n_pixels, palette_index) => {
1351                                 // A pixel run isn't allowed to span rows, but we
1352                                 // simply continue on to the next row if we run
1353                                 // out of pixels to set.
1354                                 match image_type {
1355                                     ImageType::RLE8 => {
1356                                         if !set_8bit_pixel_run(
1357                                             &mut pixel_iter,
1358                                             p,
1359                                             repeat(&palette_index),
1360                                             n_pixels as usize,
1361                                         ) {
1362                                             break 'rle_loop;
1363                                         }
1364                                     }
1365                                     ImageType::RLE4 => {
1366                                         if !set_4bit_pixel_run(
1367                                             &mut pixel_iter,
1368                                             p,
1369                                             repeat(&palette_index),
1370                                             n_pixels as usize,
1371                                         ) {
1372                                             break 'rle_loop;
1373                                         }
1374                                     }
1375                                     _ => panic!(),
1376                                 }
1377                             }
1378                         }
1379                     } else {
1380                         // We ran out of data while we still had rows to fill in.
1381                         return Err(DecoderError::RleDataTooShort.into());
1382                     }
1383                 }
1384             }
1385         }
1386         Ok((delta_pixels_left, delta_rows_left, eof_hit))
1387     }
1388 
1389     /// Read the actual data of the image. This function is deliberately not public because it
1390     /// cannot be called multiple times without seeking back the underlying reader in between.
read_image_data(&mut self, buf: &mut [u8]) -> ImageResult<()>1391     pub(crate) fn read_image_data(&mut self, buf: &mut [u8]) -> ImageResult<()> {
1392         let data = match self.image_type {
1393             ImageType::Palette => self.read_palettized_pixel_data(),
1394             ImageType::RGB16 => self.read_16_bit_pixel_data(Some(&R5_G5_B5_COLOR_MASK)),
1395             ImageType::RGB24 => self.read_full_byte_pixel_data(&FormatFullBytes::RGB24),
1396             ImageType::RGB32 => self.read_full_byte_pixel_data(&FormatFullBytes::RGB32),
1397             ImageType::RGBA32 => self.read_full_byte_pixel_data(&FormatFullBytes::RGBA32),
1398             ImageType::RLE8 => self.read_rle_data(ImageType::RLE8),
1399             ImageType::RLE4 => self.read_rle_data(ImageType::RLE4),
1400             ImageType::Bitfields16 => match self.bitfields {
1401                 Some(_) => self.read_16_bit_pixel_data(None),
1402                 None => Err(DecoderError::BitfieldMasksMissing(16).into()),
1403             },
1404             ImageType::Bitfields32 => match self.bitfields {
1405                 Some(R8_G8_B8_COLOR_MASK) => {
1406                     self.read_full_byte_pixel_data(&FormatFullBytes::Format888)
1407                 }
1408                 Some(_) => self.read_32_bit_pixel_data(),
1409                 None => Err(DecoderError::BitfieldMasksMissing(32).into()),
1410             },
1411         }?;
1412 
1413         buf.copy_from_slice(&data);
1414         Ok(())
1415     }
1416 }
1417 
1418 /// Wrapper struct around a `Cursor<Vec<u8>>`
1419 pub struct BmpReader<R>(Cursor<Vec<u8>>, PhantomData<R>);
1420 impl<R> Read for BmpReader<R> {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>1421     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1422         self.0.read(buf)
1423     }
read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize>1424     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
1425         if self.0.position() == 0 && buf.is_empty() {
1426             mem::swap(buf, self.0.get_mut());
1427             Ok(buf.len())
1428         } else {
1429             self.0.read_to_end(buf)
1430         }
1431     }
1432 }
1433 
1434 impl<'a, R: 'a + Read + Seek> ImageDecoder<'a> for BmpDecoder<R> {
1435     type Reader = BmpReader<R>;
1436 
dimensions(&self) -> (u32, u32)1437     fn dimensions(&self) -> (u32, u32) {
1438         (self.width as u32, self.height as u32)
1439     }
1440 
color_type(&self) -> ColorType1441     fn color_type(&self) -> ColorType {
1442         if self.add_alpha_channel {
1443             ColorType::Rgba8
1444         } else {
1445             ColorType::Rgb8
1446         }
1447     }
1448 
into_reader(self) -> ImageResult<Self::Reader>1449     fn into_reader(self) -> ImageResult<Self::Reader> {
1450         Ok(BmpReader(Cursor::new(image::decoder_to_vec(self)?), PhantomData))
1451     }
1452 
read_image(mut self, buf: &mut [u8]) -> ImageResult<()>1453     fn read_image(mut self, buf: &mut [u8]) -> ImageResult<()> {
1454         assert_eq!(u64::try_from(buf.len()), Ok(self.total_bytes()));
1455         self.read_image_data(buf)
1456     }
1457 }
1458 
1459 impl<'a, R: 'a + Read + Seek> ImageDecoderExt<'a> for BmpDecoder<R> {
read_rect_with_progress<F: Fn(Progress)>( &mut self, x: u32, y: u32, width: u32, height: u32, buf: &mut [u8], progress_callback: F, ) -> ImageResult<()>1460     fn read_rect_with_progress<F: Fn(Progress)>(
1461         &mut self,
1462         x: u32,
1463         y: u32,
1464         width: u32,
1465         height: u32,
1466         buf: &mut [u8],
1467         progress_callback: F,
1468     ) -> ImageResult<()> {
1469         let start = self.reader.seek(SeekFrom::Current(0))?;
1470         image::load_rect(x, y, width, height, buf, progress_callback, self, |_, _| Ok(()),
1471                          |s, buf| s.read_image_data(buf))?;
1472         self.reader.seek(SeekFrom::Start(start))?;
1473         Ok(())
1474     }
1475 }
1476 
1477 #[cfg(test)]
1478 mod test {
1479     use super::*;
1480 
1481     #[test]
test_bitfield_len()1482     fn test_bitfield_len() {
1483         for len in 1..9 {
1484             let bitfield = Bitfield { shift: 0, len };
1485             for i in 0..(1 << len) {
1486                 let read = bitfield.read(i);
1487                 let calc = (i as f64 / ((1 << len) - 1) as f64 * 255f64).round() as u8;
1488                 if read != calc {
1489                     println!("len:{} i:{} read:{} calc:{}", len, i, read, calc);
1490                 }
1491                 assert_eq!(read, calc);
1492             }
1493         }
1494     }
1495 
1496     #[test]
read_rect()1497     fn read_rect() {
1498         let f = std::fs::File::open("tests/images/bmp/images/Core_8_Bit.bmp").unwrap();
1499         let mut decoder = super::BmpDecoder::new(f).unwrap();
1500 
1501         let mut buf: Vec<u8> = vec![0; 8 * 8 * 3];
1502         decoder.read_rect(0, 0, 8, 8, &mut *buf).unwrap();
1503     }
1504 }
1505