pltrs_codec/png/
encoder.rs1use 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
15const MIN_BUFFER: usize = 1 << 16;
18
19pub(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
48pub(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#[derive(Clone, Copy, Debug, PartialEq)]
58enum Resolution {
59 Dimensions(PhysicalDimensions),
60 Dpi(f64),
61}
62
63#[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 pub fn new() -> Self {
107 Self::default()
108 }
109
110 #[must_use]
112 pub fn compression(mut self, level: CompressionLevel) -> Self {
113 self.level = level;
114 self
115 }
116
117 #[must_use]
120 pub fn strategy(mut self, strategy: Strategy) -> Self {
121 self.strategy = strategy;
122 self
123 }
124
125 #[must_use]
127 pub fn filter(mut self, strategy: FilterStrategy) -> Self {
128 self.filter = strategy;
129 self
130 }
131
132 #[must_use]
134 pub fn physical_dimensions(mut self, dimensions: PhysicalDimensions) -> Self {
135 self.resolution = Some(Resolution::Dimensions(dimensions));
136 self
137 }
138
139 #[must_use]
144 pub fn dpi(mut self, dpi: f64) -> Self {
145 self.resolution = Some(Resolution::Dpi(dpi));
146 self
147 }
148
149 #[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 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 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}