use std::time::Duration;
use clap::ValueEnum;
use image::DynamicImage;
use crate::Error;
use crate::converter::png::{CompressionType, FilterType, encode_png};
use crate::format::ImageFormat;
use crate::input::{ImageContent, SourceImage};
#[cfg(feature = "exif")]
use crate::metadata::policy::ExifPolicy;
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum, serde::Serialize, serde::Deserialize,
)]
pub enum OxipngLevel {
Zero,
One,
#[default]
Two,
Three,
Four,
Five,
Six,
Max,
}
impl OxipngLevel {
#[must_use]
pub fn preset(self) -> Option<u8> {
match self {
OxipngLevel::Zero => Some(0),
OxipngLevel::One => Some(1),
OxipngLevel::Two => Some(2),
OxipngLevel::Three => Some(3),
OxipngLevel::Four => Some(4),
OxipngLevel::Five => Some(5),
OxipngLevel::Six => Some(6),
OxipngLevel::Max => None,
}
}
}
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum, serde::Serialize, serde::Deserialize,
)]
pub enum OxipngInterlace {
Keep,
#[default]
None,
Adam7,
}
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum, serde::Serialize, serde::Deserialize,
)]
pub enum OxipngStrip {
#[default]
None,
Safe,
All,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum, serde::Serialize, serde::Deserialize)]
pub enum OxipngFilter {
None,
Sub,
Up,
Avg,
Paeth,
MinSum,
Entropy,
Bigrams,
BigEnt,
Brute,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum, serde::Serialize, serde::Deserialize)]
pub enum OxipngReduction {
BitDepth,
ColorType,
Palette,
Grayscale,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct OxipngOptions {
pub level: OxipngLevel,
pub zopfli: bool,
pub zopfli_iterations: u32,
pub interlace: OxipngInterlace,
pub strip: OxipngStrip,
pub filters: Vec<OxipngFilter>,
pub optimize_alpha: bool,
pub no_reduction: Vec<OxipngReduction>,
pub scale_16: bool,
pub fix_errors: bool,
pub timeout: Option<Duration>,
pub strip_explicit: bool,
#[cfg(feature = "exif")]
pub exif_policy: ExifPolicy,
}
impl Default for OxipngOptions {
fn default() -> Self {
OxipngOptions {
level: OxipngLevel::Two,
zopfli: false,
zopfli_iterations: 15,
interlace: OxipngInterlace::None,
strip: OxipngStrip::None,
filters: Vec::new(),
optimize_alpha: false,
no_reduction: Vec::new(),
scale_16: false,
fix_errors: false,
timeout: None,
strip_explicit: false,
#[cfg(feature = "exif")]
exif_policy: ExifPolicy::Strip,
}
}
}
impl OxipngOptions {
#[must_use]
pub fn to_oxipng(&self) -> oxipng::Options {
let mut opts = match self.level.preset() {
Some(preset) => oxipng::Options::from_preset(preset),
None => oxipng::Options::max_compression(),
};
if !self.filters.is_empty() {
opts.filters = self.filters.iter().map(|f| f.to_strategy()).collect();
}
opts.interlace = match self.interlace {
OxipngInterlace::Keep => None,
OxipngInterlace::None => Some(false),
OxipngInterlace::Adam7 => Some(true),
};
opts.strip = match self.strip {
OxipngStrip::None => oxipng::StripChunks::None,
OxipngStrip::Safe => oxipng::StripChunks::Safe,
OxipngStrip::All => oxipng::StripChunks::All,
};
#[cfg(feature = "exif")]
match self.exif_policy {
ExifPolicy::Strip => {
if !self.strip_explicit {
opts.strip = oxipng::StripChunks::Safe;
}
}
ExifPolicy::Keep | ExifPolicy::FilterExcept(_) | ExifPolicy::KeepOnly(_) => {
opts.strip = oxipng::StripChunks::None;
}
}
opts.optimize_alpha = self.optimize_alpha;
for reduction in &self.no_reduction {
match reduction {
OxipngReduction::BitDepth => opts.bit_depth_reduction = false,
OxipngReduction::ColorType => opts.color_type_reduction = false,
OxipngReduction::Palette => opts.palette_reduction = false,
OxipngReduction::Grayscale => opts.grayscale_reduction = false,
}
}
opts.scale_16 = self.scale_16;
opts.fix_errors = self.fix_errors;
opts.timeout = self.timeout;
if self.zopfli {
let mut zopfli = oxipng::ZopfliOptions::default();
if let Ok(iterations) = u64::from(self.zopfli_iterations).try_into() {
zopfli.iteration_count = iterations;
}
opts.deflater = oxipng::Deflater::Zopfli(zopfli);
}
opts
}
}
impl OxipngFilter {
fn name(self) -> &'static str {
match self {
OxipngFilter::None => "none",
OxipngFilter::Sub => "sub",
OxipngFilter::Up => "up",
OxipngFilter::Avg => "avg",
OxipngFilter::Paeth => "paeth",
OxipngFilter::MinSum => "minsum",
OxipngFilter::Entropy => "entropy",
OxipngFilter::Bigrams => "bigrams",
OxipngFilter::BigEnt => "bigent",
OxipngFilter::Brute => "brute",
}
}
#[must_use]
pub fn to_strategy(self) -> oxipng::FilterStrategy {
match self {
OxipngFilter::None => oxipng::FilterStrategy::NONE,
OxipngFilter::Sub => oxipng::FilterStrategy::SUB,
OxipngFilter::Up => oxipng::FilterStrategy::UP,
OxipngFilter::Avg => oxipng::FilterStrategy::AVERAGE,
OxipngFilter::Paeth => oxipng::FilterStrategy::PAETH,
OxipngFilter::MinSum => oxipng::FilterStrategy::MinSum,
OxipngFilter::Entropy => oxipng::FilterStrategy::Entropy,
OxipngFilter::Bigrams => oxipng::FilterStrategy::Bigrams,
OxipngFilter::BigEnt => oxipng::FilterStrategy::BigEnt,
OxipngFilter::Brute => oxipng::FilterStrategy::Brute {
num_lines: 8,
level: 5,
},
}
}
}
impl std::fmt::Display for OxipngOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let level = self
.level
.preset()
.map_or_else(|| "max".to_string(), |p| p.to_string());
let mut reductions = vec!["bit-depth", "color-type", "palette", "grayscale"];
for reduction in &self.no_reduction {
let name = match reduction {
OxipngReduction::BitDepth => "bit-depth",
OxipngReduction::ColorType => "color-type",
OxipngReduction::Palette => "palette",
OxipngReduction::Grayscale => "grayscale",
};
reductions.retain(|r| *r != name);
}
write!(
f,
"level={} zopfli={} zopfli-iterations={} interlace={:?} strip={:?} \
optimize-alpha={} reductions=[{}] scale-16={} fix-errors={} timeout={:?}",
level,
self.zopfli,
self.zopfli_iterations,
self.interlace,
self.strip,
self.optimize_alpha,
reductions.join(","),
self.scale_16,
self.fix_errors,
self.timeout,
)?;
if !self.filters.is_empty() {
let filters = self
.filters
.iter()
.map(|f| f.name())
.collect::<Vec<_>>()
.join(",");
write!(f, " filters=[{filters}]")?;
}
Ok(())
}
}
pub struct OxipngEncoder {
pub options: OxipngOptions,
}
impl OxipngEncoder {
pub fn new(options: OxipngOptions) -> Self {
OxipngEncoder { options }
}
fn transcode(
&self,
image: &DynamicImage,
exif_payload: Option<&[u8]>,
) -> Result<Vec<u8>, Error> {
let baseline = encode_png(
image,
Some(CompressionType::Fast),
Some(FilterType::Adaptive),
exif_payload,
)?;
optimize_bytes(&baseline, &self.options)
}
}
impl super::ImageEncoder for OxipngEncoder {
fn format(&self) -> ImageFormat {
ImageFormat::Png
}
fn extension(&self) -> &'static str {
"png"
}
fn describe(&self) -> String {
format!(
"lossless PNG re-optimizer (oxipng {})",
super::dependency_version("oxipng")
)
}
fn describe_options(&self) -> String {
format!(
"Using \"oxipng\" ({}) with options: {}",
super::dependency_version("oxipng"),
self.options
)
}
fn encode_still_image(&self, image: &DynamicImage) -> Result<Vec<u8>, Error> {
self.transcode(image, None)
}
fn encode(&self, input: &SourceImage) -> Result<Vec<u8>, Error> {
if input.source_format == ImageFormat::Png {
let original = std::fs::read(&input.source_path)?;
return optimize_bytes(&original, &self.options);
}
match &input.content {
ImageContent::Still(image) => {
#[cfg(feature = "exif")]
let payload =
crate::metadata::exif::resolve(&self.options.exif_policy, &input.metadata);
#[cfg(not(feature = "exif"))]
let payload = None;
self.transcode(image, payload.as_deref())
}
ImageContent::Animated(animation) => {
let first = animation.first_frame().ok_or_else(|| {
Error::from_string("Animation does not contain any frames".to_string())
})?;
println!(
"Warning: {} does not support animated input yet; encoding the first frame only",
self.describe()
);
self.encode_still_image(&DynamicImage::ImageRgba8(first.buffer.clone()))
}
}
}
fn huge_image_hint(&self) -> Option<&'static str> {
Some(
"the oxipng target can take very long on huge images; \
consider a lower --level (<= 2) or --timeout-secs",
)
}
}
pub fn optimize_bytes(png_bytes: &[u8], options: &OxipngOptions) -> Result<Vec<u8>, Error> {
oxipng::optimize_from_memory(png_bytes, &options.to_oxipng())
.map_err(|e| Error::from_string(format!("oxipng optimization failed: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::converter::ImageEncoder as _;
#[test]
fn default_options_map_to_level_two_preset() {
let opts = OxipngOptions::default().to_oxipng();
let expected = oxipng::Options::default();
assert_eq!(opts.filters, expected.filters);
assert_eq!(opts.deflater, expected.deflater);
assert_eq!(opts.interlace, Some(false));
#[cfg(feature = "exif")]
assert_eq!(opts.strip, oxipng::StripChunks::Safe);
#[cfg(not(feature = "exif"))]
assert_eq!(opts.strip, oxipng::StripChunks::None);
assert!(!opts.optimize_alpha);
assert!(opts.bit_depth_reduction);
assert!(opts.color_type_reduction);
assert!(opts.palette_reduction);
assert!(opts.grayscale_reduction);
assert!(!opts.scale_16);
assert!(!opts.fix_errors);
assert_eq!(opts.timeout, None);
}
#[test]
fn max_level_maps_to_max_compression() {
let opts = OxipngOptions {
level: OxipngLevel::Max,
..OxipngOptions::default()
}
.to_oxipng();
let expected = oxipng::Options::max_compression();
assert_eq!(opts.filters, expected.filters);
assert_eq!(opts.deflater, expected.deflater);
assert!(!opts.fast_evaluation);
}
#[test]
fn explicit_flags_override_preset() {
let opts = OxipngOptions {
level: OxipngLevel::Max,
zopfli: true,
zopfli_iterations: 8,
interlace: OxipngInterlace::Adam7,
strip: OxipngStrip::Safe,
filters: vec![OxipngFilter::None, OxipngFilter::Paeth],
optimize_alpha: true,
no_reduction: vec![
OxipngReduction::BitDepth,
OxipngReduction::ColorType,
OxipngReduction::Palette,
OxipngReduction::Grayscale,
],
scale_16: true,
fix_errors: true,
timeout: Some(Duration::from_secs(30)),
strip_explicit: true,
#[cfg(feature = "exif")]
exif_policy: ExifPolicy::Strip,
}
.to_oxipng();
assert_eq!(opts.filters.len(), 2);
assert!(
opts.filters
.contains(&oxipng::FilterStrategy::Basic(oxipng::RowFilter::Paeth))
);
assert_eq!(opts.interlace, Some(true));
assert_eq!(opts.strip, oxipng::StripChunks::Safe);
assert!(opts.optimize_alpha);
assert!(!opts.bit_depth_reduction);
assert!(!opts.color_type_reduction);
assert!(!opts.palette_reduction);
assert!(!opts.grayscale_reduction);
assert!(opts.scale_16);
assert!(opts.fix_errors);
assert_eq!(opts.timeout, Some(Duration::from_secs(30)));
match opts.deflater {
oxipng::Deflater::Zopfli(zopfli) => {
assert_eq!(zopfli.iteration_count.get(), 8);
}
other => panic!("expected zopfli deflater, got {other:?}"),
}
}
#[test]
fn interlace_keep_maps_to_none() {
let opts = OxipngOptions {
interlace: OxipngInterlace::Keep,
..OxipngOptions::default()
}
.to_oxipng();
assert_eq!(opts.interlace, None);
}
#[test]
fn zopfli_iteration_zero_falls_back_to_default() {
let opts = OxipngOptions {
zopfli: true,
zopfli_iterations: 0,
..OxipngOptions::default()
}
.to_oxipng();
match opts.deflater {
oxipng::Deflater::Zopfli(zopfli) => {
assert_eq!(zopfli.iteration_count.get(), 15);
}
other => panic!("expected zopfli deflater, got {other:?}"),
}
}
#[test]
fn describe_is_identity_only_and_options_carry_the_detail() {
let encoder = OxipngEncoder::new(OxipngOptions::default());
let description = encoder.describe();
assert!(description.contains("oxipng"), "{description}");
assert!(description.contains("10.2"), "{description}");
assert!(!description.contains("level="), "{description}");
let options = encoder.describe_options();
assert!(options.contains("oxipng"), "{options}");
assert!(options.contains("10.2"), "{options}");
assert!(options.contains("level=2"), "{options}");
}
}