Skip to main content

pltrs_codec/png/
decoder.rs

1//! The PNG decoder.
2
3use super::decoded::DecodedImage;
4use super::error::DecodeError;
5use super::interlace::StreamLayout;
6use super::parse;
7use crate::deflate::InflateError;
8use crate::zlib::{self, ZlibError};
9
10/// DEFLATE cannot expand data by more than about 1032:1, so a decoder never
11/// needs to reserve more than this multiple of the compressed size up front.
12const MAX_DEFLATE_RATIO: usize = 1032;
13
14/// Decodes PNG files, with a configurable size limit.
15///
16/// ```
17/// use pltrs_codec::png::{self, ColorType, Decoder, ImageRef};
18///
19/// let gray = [0u8, 64, 128, 255];
20/// let file = png::encode(ImageRef::new(2, 2, ColorType::Gray, png::BitDepth::Eight, &gray)?)?;
21///
22/// let image = Decoder::new().max_image_bytes(1 << 20).decode(&file)?;
23/// assert_eq!((image.width(), image.height()), (2, 2));
24/// assert_eq!(image.data(), gray);
25/// assert_eq!(&image.to_rgba8()[4..8], [64, 64, 64, 255]);
26///
27/// let tiny_limit = Decoder::new().max_image_bytes(3);
28/// assert!(tiny_limit.decode(&file).is_err());
29/// # Ok::<(), Box<dyn std::error::Error>>(())
30/// ```
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub struct Decoder {
33    max_image_bytes: usize,
34}
35
36impl Decoder {
37    /// The default limit on decoded pixel data: 1 GiB.
38    pub const DEFAULT_MAX_IMAGE_BYTES: usize = 1 << 30;
39
40    /// A decoder with the default limit.
41    pub const fn new() -> Self {
42        Self {
43            max_image_bytes: Self::DEFAULT_MAX_IMAGE_BYTES,
44        }
45    }
46
47    /// Sets the largest pixel buffer (in PNG layout, see
48    /// [`DecodedImage::data`]) the decoder will produce; larger images fail
49    /// with [`DecodeError::ImageTooLarge`] before any pixel memory is
50    /// allocated.
51    #[must_use]
52    pub const fn max_image_bytes(self, limit: usize) -> Self {
53        Self {
54            max_image_bytes: limit,
55        }
56    }
57
58    /// Decodes a complete PNG file.
59    pub fn decode(&self, png: &[u8]) -> Result<DecodedImage, DecodeError> {
60        let parts = parse::read_parts(png)?;
61        let header = parts.header;
62        let too_large = || DecodeError::ImageTooLarge {
63            limit: self.max_image_bytes,
64        };
65        let row_bytes = header
66            .format
67            .row_bytes(header.width)
68            .ok_or_else(too_large)?;
69        let image_bytes = header
70            .format
71            .image_bytes(header.width, header.height)
72            .filter(|&bytes| bytes <= self.max_image_bytes)
73            .ok_or_else(too_large)?;
74        let layout = StreamLayout::new(&header).ok_or_else(too_large)?;
75        let stream = inflate_image_data(&parts.image_data, layout.len())?;
76        drop(parts.image_data);
77        let data = layout.reconstruct(&stream, header.format, row_bytes, image_bytes)?;
78        Ok(DecodedImage::new(
79            header,
80            data,
81            parts.palette,
82            parts.color_key,
83            parts.metadata,
84        ))
85    }
86}
87
88impl Default for Decoder {
89    fn default() -> Self {
90        Self::new()
91    }
92}
93
94/// Decompresses the concatenated `IDAT` data, which must yield at least
95/// `expected` bytes. Like libpng, surplus data after the image is ignored.
96fn inflate_image_data(compressed: &[u8], expected: usize) -> Result<Vec<u8>, DecodeError> {
97    let capacity = expected.min(compressed.len().saturating_mul(MAX_DEFLATE_RATIO));
98    let mut stream = Vec::with_capacity(capacity);
99    match zlib::decompress_into(compressed, &mut stream, expected) {
100        Ok(_) | Err(ZlibError::Inflate(InflateError::OutputLimitExceeded { .. })) => {}
101        Err(error) => return Err(error.into()),
102    }
103    if stream.len() < expected {
104        return Err(DecodeError::ImageDataTooShort {
105            expected,
106            actual: stream.len(),
107        });
108    }
109    Ok(stream)
110}