use super::chunk::{ChunkType, SIGNATURE, write_chunk};
use super::error::EncodeError;
use super::filter::{FilterStrategy, FilteredRows};
use super::header::Header;
use super::image::ImageRef;
use super::metadata::{PhysicalDimensions, TextEntry};
use super::text;
use crate::CompressionLevel;
use crate::deflate::encode::{self, Rows};
use crate::deflate::{MemoryLevel, Options, Strategy};
use pltrs_core::alloc::{self, OutOfMemory};
const MIN_BUFFER: usize = 1 << 16;
pub(super) fn compress_image(
image: &ImageRef<'_>,
filter: FilterStrategy,
level: CompressionLevel,
strategy: Strategy,
) -> Result<Rows, OutOfMemory> {
let mut rows = FilteredRows::new(
image.data(),
image.row_bytes(),
image.format().filter_stride(),
filter,
)?;
let options = Options::new(level)
.strategy(strategy)
.memory_level(MemoryLevel::MAX);
let buffer = MIN_BUFFER.max(4 * image.width() as usize);
encode::rows(&mut rows, options, buffer)
}
pub(super) fn chunks(rows: &Rows) -> impl Iterator<Item = &[u8]> {
let starts = std::iter::once(0).chain(rows.ends.iter().copied());
starts
.zip(&rows.ends)
.map(|(start, &end)| &rows.stream[start..end])
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Resolution {
Dimensions(PhysicalDimensions),
Dpi(f64),
}
#[derive(Clone, Debug, PartialEq)]
pub struct Encoder {
level: CompressionLevel,
strategy: Strategy,
filter: FilterStrategy,
resolution: Option<Resolution>,
text: Vec<TextEntry>,
}
impl Default for Encoder {
fn default() -> Self {
Self {
level: CompressionLevel::DEFAULT,
strategy: Strategy::Filtered,
filter: FilterStrategy::Adaptive,
resolution: None,
text: Vec::new(),
}
}
}
impl Encoder {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn compression(mut self, level: CompressionLevel) -> Self {
self.level = level;
self
}
#[must_use]
pub fn strategy(mut self, strategy: Strategy) -> Self {
self.strategy = strategy;
self
}
#[must_use]
pub fn filter(mut self, strategy: FilterStrategy) -> Self {
self.filter = strategy;
self
}
#[must_use]
pub fn physical_dimensions(mut self, dimensions: PhysicalDimensions) -> Self {
self.resolution = Some(Resolution::Dimensions(dimensions));
self
}
#[must_use]
pub fn dpi(mut self, dpi: f64) -> Self {
self.resolution = Some(Resolution::Dpi(dpi));
self
}
#[must_use]
pub fn text(mut self, keyword: impl Into<String>, text: impl Into<String>) -> Self {
self.text.push(TextEntry::new(keyword, text));
self
}
pub fn encode(&self, image: ImageRef<'_>) -> Result<Vec<u8>, EncodeError> {
let physical = match self.resolution {
None => None,
Some(Resolution::Dimensions(dimensions)) => Some(dimensions),
Some(Resolution::Dpi(dpi)) => {
Some(PhysicalDimensions::from_dpi(dpi).ok_or(EncodeError::InvalidDpi(dpi))?)
}
};
let text_chunks = self
.text
.iter()
.map(text::encode)
.collect::<Result<Vec<_>, _>>()?;
let format = image.format();
let compressed = compress_image(&image, self.filter, self.level, self.strategy)?;
let text_len: usize = text_chunks.iter().map(|(_, data)| data.len() + 12).sum();
let idat_len = compressed.stream.len() + 12 * compressed.ends.len();
let mut png = alloc::try_with_capacity(idat_len + text_len + 128)?;
png.extend_from_slice(&SIGNATURE);
let header = Header {
width: image.width(),
height: image.height(),
format,
interlaced: false,
};
write_chunk(&mut png, ChunkType::IHDR, &header.to_bytes());
for (kind, data) in &text_chunks {
write_chunk(&mut png, *kind, data);
}
if let Some(physical) = physical {
write_chunk(&mut png, ChunkType::PHYS, &physical.to_bytes());
}
for part in chunks(&compressed) {
write_chunk(&mut png, ChunkType::IDAT, part);
}
write_chunk(&mut png, ChunkType::IEND, &[]);
Ok(png)
}
}