use std::fmt;
use std::sync::Arc;
use crate::RGBA;
use crate::error::Error;
use crate::hist::get_histogram;
use crate::image::{Image, PixelData, Source};
use crate::pal::{ColorSpace, MAX_DIFF, cmax, cmin};
use crate::quant::{QuantizationResult, pngquant_quantize};
type LogCallback = Arc<dyn Fn(&Attributes, &str) + Send + Sync>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Profile {
Compat,
#[default]
Improved,
}
impl Profile {
pub(crate) fn color_space(self) -> ColorSpace {
match self {
Self::Compat => ColorSpace::Rgb,
Self::Improved => ColorSpace::Opponent,
}
}
}
type LogFlushCallback = Arc<dyn Fn(&Attributes) + Send + Sync>;
#[derive(Clone)]
pub struct Attributes {
pub(crate) target_mse: f64,
pub(crate) max_mse: f64,
pub(crate) voronoi_iteration_limit: f64,
pub(crate) min_opaque_val: f32,
pub(crate) max_colors: u32,
pub(crate) max_histogram_entries: u32,
pub(crate) min_posterization_output: u8,
pub(crate) min_posterization_input: u8,
pub(crate) voronoi_iterations: u32,
pub(crate) hartigan_passes: u32,
pub(crate) reorder_palette: bool,
pub(crate) feedback_loop_trials: u32,
pub(crate) last_index_transparent: bool,
pub(crate) use_contrast_maps: bool,
pub(crate) use_dither_map: bool,
pub(crate) fast_palette: bool,
pub(crate) profile: Profile,
speed: u8,
log_callback: Option<LogCallback>,
log_flush_callback: Option<LogFlushCallback>,
}
pub(crate) fn quality_to_mse(quality: u32) -> f64 {
if quality == 0 {
return MAX_DIFF;
}
if quality == 100 {
return 0.0;
}
let quality = f64::from(quality);
let extra_low_quality_fudge = cmax(0.0, 0.016 / (0.001 + quality) - 0.001);
extra_low_quality_fudge + 2.5 / (210.0 + quality).powf(1.2) * (100.1 - quality) / 100.0
}
pub(crate) fn mse_to_quality(mse: f64) -> u32 {
(1..=100)
.rev()
.find(|&q| mse <= quality_to_mse(q) + 0.000_001)
.unwrap_or(0)
}
impl Default for Attributes {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for Attributes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Attributes")
.field("max_colors", &self.max_colors)
.field("speed", &self.speed)
.field("quality", &self.quality())
.field("min_opacity", &self.min_opacity())
.field("min_posterization", &self.min_posterization_output)
.field("last_index_transparent", &self.last_index_transparent)
.finish_non_exhaustive()
}
}
impl Attributes {
#[must_use]
pub fn new() -> Self {
let mut attr = Self {
target_mse: 0.0,
max_mse: MAX_DIFF,
voronoi_iteration_limit: 0.0,
min_opaque_val: 1.0,
max_colors: 256,
max_histogram_entries: 0,
min_posterization_output: 0,
min_posterization_input: 0,
voronoi_iterations: 0,
hartigan_passes: 0,
reorder_palette: false,
feedback_loop_trials: 0,
last_index_transparent: false,
use_contrast_maps: false,
use_dither_map: false,
fast_palette: false,
profile: Profile::default(),
speed: 0,
log_callback: None,
log_flush_callback: None,
};
attr.set_speed(3).expect("valid speed");
attr
}
pub fn set_max_colors(&mut self, colors: u32) -> Result<(), Error> {
if !(2..=256).contains(&colors) {
return Err(Error::ValueOutOfRange);
}
self.max_colors = colors;
Ok(())
}
#[must_use]
pub fn max_colors(&self) -> u32 {
self.max_colors
}
pub fn set_quality(&mut self, minimum: u8, target: u8) -> Result<(), Error> {
if target > 100 || target < minimum {
return Err(Error::ValueOutOfRange);
}
self.target_mse = quality_to_mse(target.into());
self.max_mse = quality_to_mse(minimum.into());
Ok(())
}
#[must_use]
pub fn quality(&self) -> (u8, u8) {
(
mse_to_quality(self.max_mse) as u8,
mse_to_quality(self.target_mse) as u8,
)
}
pub fn set_speed(&mut self, speed: i32) -> Result<(), Error> {
if !(1..=10).contains(&speed) {
return Err(Error::ValueOutOfRange);
}
let mut iterations = cmax(8 - speed, 0);
iterations += iterations * iterations / 2;
let mut trials = cmax(56 - 9 * speed, 0);
self.hartigan_passes = 0;
if self.profile == Profile::Improved {
(trials, iterations, self.hartigan_passes) = match speed {
..=2 => (1, 2, 3),
3..=6 => (0, 1, 2),
_ => (0, 1, 0),
};
}
self.reorder_palette = self.profile == Profile::Improved && speed <= 7;
self.voronoi_iterations = iterations as u32;
self.voronoi_iteration_limit = 1.0 / f64::from(1u32 << (23 - speed));
self.feedback_loop_trials = trials as u32;
self.max_histogram_entries = (1 << 17) + (1 << 18) * (10 - speed) as u32;
self.min_posterization_input = u8::from(speed >= 8);
self.fast_palette = speed >= 7;
self.use_dither_map = speed <= 5;
self.use_contrast_maps = speed <= 7 || self.use_dither_map;
self.speed = speed as u8;
Ok(())
}
pub fn set_profile(&mut self, profile: Profile) {
self.profile = profile;
self.set_speed(self.speed.into()).expect("current speed is valid");
}
#[must_use]
pub fn profile(&self) -> Profile {
self.profile
}
#[must_use]
pub fn speed(&self) -> u32 {
self.speed.into()
}
pub fn set_min_opacity(&mut self, min: u8) -> Result<(), Error> {
self.min_opaque_val = (f64::from(min) / 255.0) as f32;
Ok(())
}
#[must_use]
pub fn min_opacity(&self) -> u8 {
cmin(255.0, 256.0 * f64::from(self.min_opaque_val)) as u8
}
pub fn set_min_posterization(&mut self, bits: u8) -> Result<(), Error> {
if bits > 4 {
return Err(Error::ValueOutOfRange);
}
self.min_posterization_output = bits;
Ok(())
}
#[must_use]
pub fn min_posterization(&self) -> u8 {
self.min_posterization_output
}
pub fn set_last_index_transparent(&mut self, is_last: bool) {
self.last_index_transparent = is_last;
}
pub fn set_log_callback<F: Fn(&Self, &str) + Send + Sync + 'static>(&mut self, callback: F) {
self.flush_log();
self.log_callback = Some(Arc::new(callback));
}
pub fn clear_log_callback(&mut self) {
self.flush_log();
self.log_callback = None;
}
pub fn set_log_flush_callback<F: Fn(&Self) + Send + Sync + 'static>(&mut self, callback: F) {
self.log_flush_callback = Some(Arc::new(callback));
}
pub fn clear_log_flush_callback(&mut self) {
self.log_flush_callback = None;
}
pub(crate) fn verbose_print(&self, message: &str) {
if let Some(cb) = &self.log_callback {
cb(self, message);
}
}
pub(crate) fn log_error(&self, message: &str) {
if self.log_callback.is_some() {
self.verbose_print(&format!(" error: {message}"));
}
}
fn flush_log(&self) {
if let Some(cb) = &self.log_flush_callback {
cb(self);
}
}
pub fn new_image(
&self,
pixels: impl Into<Box<[RGBA]>>,
width: usize,
height: usize,
gamma: f64,
) -> Result<Image<'static>, Error> {
self.new_image_stride(pixels, width, height, width, gamma)
}
pub fn new_image_stride(
&self,
pixels: impl Into<Box<[RGBA]>>,
width: usize,
height: usize,
stride: usize,
gamma: f64,
) -> Result<Image<'static>, Error> {
let source = Source::Contiguous {
data: PixelData::Owned(pixels.into()),
stride,
};
Image::new_internal(self, source, width, height, gamma)
}
pub fn new_image_borrowed<'a>(
&self,
pixels: &'a [RGBA],
width: usize,
height: usize,
gamma: f64,
) -> Result<Image<'a>, Error> {
self.new_image_stride_borrowed(pixels, width, height, width, gamma)
}
pub fn new_image_stride_borrowed<'a>(
&self,
pixels: &'a [RGBA],
width: usize,
height: usize,
stride: usize,
gamma: f64,
) -> Result<Image<'a>, Error> {
let source = Source::Contiguous {
data: PixelData::Borrowed(pixels),
stride,
};
Image::new_internal(self, source, width, height, gamma)
}
pub fn new_image_rows<'a>(
&self,
rows: impl Into<Box<[&'a [RGBA]]>>,
width: usize,
height: usize,
gamma: f64,
) -> Result<Image<'a>, Error> {
Image::new_internal(self, Source::Rows(rows.into()), width, height, gamma)
}
pub fn new_image_fn<'a, F>(&self, callback: F, width: usize, height: usize, gamma: f64) -> Result<Image<'a>, Error>
where
F: Fn(&mut [RGBA], usize) + Send + Sync + 'a,
{
Image::new_internal(self, Source::Callback(Box::new(callback)), width, height, gamma)
}
pub fn quantize(&self, image: &mut Image<'_>) -> Result<QuantizationResult, Error> {
image.ensure_color_space(self.profile.color_space());
let mut hist = get_histogram(image, self)?;
pngquant_quantize(&mut hist, self, &image.fixed_colors, image.gamma)
}
}
impl Drop for Attributes {
fn drop(&mut self) {
self.flush_log();
}
}