Skip to main content

pltrs_codec/png/
encoder.rs

1//! The PNG encoder.
2
3use super::chunk::{ChunkType, SIGNATURE, write_chunk};
4use super::error::EncodeError;
5use super::filter::{FilterStrategy, FilteredRows};
6use super::header::Header;
7use super::image::ImageRef;
8use super::metadata::{PhysicalDimensions, TextEntry};
9use super::text;
10use crate::CompressionLevel;
11use crate::deflate::encode::{self, Rows};
12use crate::deflate::{MemoryLevel, Options, Strategy};
13use pltrs_core::alloc::{self, OutOfMemory};
14
15/// The smallest output buffer Pillow compresses into (`MAXBLOCK`); each
16/// buffer becomes one `IDAT` chunk.
17const MIN_BUFFER: usize = 1 << 16;
18
19/// The filtered, zlib-compressed scanlines of `image` (the contents of
20/// its `IDAT` chunks), filtered as they are compressed, and where Pillow
21/// would end each chunk: rows compressed one at a time with zlib's
22/// memory level 9 into buffers of 64 KiB or four bytes per pixel of a
23/// row, whichever is more.
24///
25/// # Errors
26///
27/// When the memory for the compressor or the compressed scanlines cannot
28/// be allocated.
29pub(super) fn compress_image(
30    image: &ImageRef<'_>,
31    filter: FilterStrategy,
32    level: CompressionLevel,
33    strategy: Strategy,
34) -> Result<Rows, OutOfMemory> {
35    let mut rows = FilteredRows::new(
36        image.data(),
37        image.row_bytes(),
38        image.format().filter_stride(),
39        filter,
40    )?;
41    let options = Options::new(level)
42        .strategy(strategy)
43        .memory_level(MemoryLevel::MAX);
44    let buffer = MIN_BUFFER.max(4 * image.width() as usize);
45    encode::rows(&mut rows, options, buffer)
46}
47
48/// The pieces of a compressed image as Pillow cuts them into chunks.
49pub(super) fn chunks(rows: &Rows) -> impl Iterator<Item = &[u8]> {
50    let starts = std::iter::once(0).chain(rows.ends.iter().copied());
51    starts
52        .zip(&rows.ends)
53        .map(|(start, &end)| &rows.stream[start..end])
54}
55
56/// How the `pHYs` chunk was requested.
57#[derive(Clone, Copy, Debug, PartialEq)]
58enum Resolution {
59    Dimensions(PhysicalDimensions),
60    Dpi(f64),
61}
62
63/// Configures and runs PNG encoding.
64///
65/// The defaults match what matplotlib gets from Pillow: zlib level 6 and
66/// [`Strategy::Filtered`] with Pillow's adaptive filtering, and no
67/// ancillary chunks.
68///
69/// ```
70/// use pltrs_codec::CompressionLevel;
71/// use pltrs_codec::png::{Encoder, FilterStrategy, FilterType, ImageRef};
72///
73/// let pixels = vec![255u8; 64 * 48 * 4];
74/// let png = Encoder::new()
75///     .compression(CompressionLevel::BEST)
76///     .filter(FilterStrategy::Fixed(FilterType::Up))
77///     .dpi(72.0)
78///     .text("Software", "pltrs")
79///     .encode(ImageRef::rgba8(64, 48, &pixels)?)?;
80/// assert!(png.starts_with(&pltrs_codec::png::SIGNATURE));
81/// # Ok::<(), pltrs_codec::png::EncodeError>(())
82/// ```
83#[derive(Clone, Debug, PartialEq)]
84pub struct Encoder {
85    level: CompressionLevel,
86    strategy: Strategy,
87    filter: FilterStrategy,
88    resolution: Option<Resolution>,
89    text: Vec<TextEntry>,
90}
91
92impl Default for Encoder {
93    fn default() -> Self {
94        Self {
95            level: CompressionLevel::DEFAULT,
96            strategy: Strategy::Filtered,
97            filter: FilterStrategy::Adaptive,
98            resolution: None,
99            text: Vec::new(),
100        }
101    }
102}
103
104impl Encoder {
105    /// An encoder with default settings.
106    pub fn new() -> Self {
107        Self::default()
108    }
109
110    /// Sets the zlib compression level.
111    #[must_use]
112    pub fn compression(mut self, level: CompressionLevel) -> Self {
113        self.level = level;
114        self
115    }
116
117    /// Sets the zlib strategy (Pillow's `compress_type`;
118    /// [`Strategy::Filtered`] by default).
119    #[must_use]
120    pub fn strategy(mut self, strategy: Strategy) -> Self {
121        self.strategy = strategy;
122        self
123    }
124
125    /// Sets how scanline filters are chosen.
126    #[must_use]
127    pub fn filter(mut self, strategy: FilterStrategy) -> Self {
128        self.filter = strategy;
129        self
130    }
131
132    /// Writes a `pHYs` chunk with these dimensions.
133    #[must_use]
134    pub fn physical_dimensions(mut self, dimensions: PhysicalDimensions) -> Self {
135        self.resolution = Some(Resolution::Dimensions(dimensions));
136        self
137    }
138
139    /// Writes a `pHYs` chunk for `dpi` dots per inch, as matplotlib does with
140    /// the figure's dpi. An invalid value (see
141    /// [`PhysicalDimensions::from_dpi`]) makes [`encode`](Self::encode) fail
142    /// with [`EncodeError::InvalidDpi`].
143    #[must_use]
144    pub fn dpi(mut self, dpi: f64) -> Self {
145        self.resolution = Some(Resolution::Dpi(dpi));
146        self
147    }
148
149    /// Adds a text entry, written as `tEXt` when the text is Latin-1 and as
150    /// `iTXt` (UTF-8) otherwise. Keywords are validated by
151    /// [`encode`](Self::encode).
152    #[must_use]
153    pub fn text(mut self, keyword: impl Into<String>, text: impl Into<String>) -> Self {
154        self.text.push(TextEntry::new(keyword, text));
155        self
156    }
157
158    /// Encodes `image` into a complete PNG file.
159    pub fn encode(&self, image: ImageRef<'_>) -> Result<Vec<u8>, EncodeError> {
160        let physical = match self.resolution {
161            None => None,
162            Some(Resolution::Dimensions(dimensions)) => Some(dimensions),
163            Some(Resolution::Dpi(dpi)) => {
164                Some(PhysicalDimensions::from_dpi(dpi).ok_or(EncodeError::InvalidDpi(dpi))?)
165            }
166        };
167        let text_chunks = self
168            .text
169            .iter()
170            .map(text::encode)
171            .collect::<Result<Vec<_>, _>>()?;
172
173        let format = image.format();
174        let compressed = compress_image(&image, self.filter, self.level, self.strategy)?;
175
176        let text_len: usize = text_chunks.iter().map(|(_, data)| data.len() + 12).sum();
177        let idat_len = compressed.stream.len() + 12 * compressed.ends.len();
178        let mut png = alloc::try_with_capacity(idat_len + text_len + 128)?;
179        png.extend_from_slice(&SIGNATURE);
180        let header = Header {
181            width: image.width(),
182            height: image.height(),
183            format,
184            interlaced: false,
185        };
186        write_chunk(&mut png, ChunkType::IHDR, &header.to_bytes());
187        // Text before the resolution, in the order Pillow writes them.
188        for (kind, data) in &text_chunks {
189            write_chunk(&mut png, *kind, data);
190        }
191        if let Some(physical) = physical {
192            write_chunk(&mut png, ChunkType::PHYS, &physical.to_bytes());
193        }
194        for part in chunks(&compressed) {
195            write_chunk(&mut png, ChunkType::IDAT, part);
196        }
197        write_chunk(&mut png, ChunkType::IEND, &[]);
198        Ok(png)
199    }
200}