use std::fmt;
use crate::RGBA;
use crate::attr::{Attributes, Profile};
use crate::error::Error;
use crate::hist::{WEIGHT_UNITS, color_key, count_image_colors, make_histogram, remove_fixed_colors_from_histogram};
use crate::image::Image;
use crate::pal::{ColorLut, FPixel, cmax};
use crate::quant::{QuantizationResult, pngquant_quantize};
const SRGB_GAMMA: f64 = 0.45455;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct HistogramEntry {
pub color: RGBA,
pub count: u32,
}
#[derive(Clone)]
pub struct Histogram {
colors: Vec<(u32, u64)>,
fixed: Vec<RGBA>,
gamma: Option<f64>,
profile: Profile,
}
impl fmt::Debug for Histogram {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Histogram")
.field("colors", &self.colors.len())
.field("fixed_colors", &self.fixed)
.field("gamma", &self.gamma)
.field("profile", &self.profile)
.finish()
}
}
fn normalize_gamma(gamma: f64) -> Result<f64, Error> {
match gamma {
0.0 => Ok(SRGB_GAMMA),
g if g > 0.0 && g <= 1.0 => Ok(g),
_ => Err(Error::ValueOutOfRange),
}
}
fn merge(a: &[(u32, u64)], b: &[(u32, u64)]) -> Vec<(u32, u64)> {
let mut out = Vec::with_capacity(a.len() + b.len());
let (mut i, mut j) = (0, 0);
while i < a.len() && j < b.len() {
let (x, y) = (a[i], b[j]);
match x.0.cmp(&y.0) {
std::cmp::Ordering::Less => {
out.push(x);
i += 1;
}
std::cmp::Ordering::Greater => {
out.push(y);
j += 1;
}
std::cmp::Ordering::Equal => {
out.push((x.0, x.1.saturating_add(y.1)));
i += 1;
j += 1;
}
}
}
out.extend_from_slice(&a[i..]);
out.extend_from_slice(&b[j..]);
out
}
fn sort_and_sum(mut colors: Vec<(u32, u64)>) -> Vec<(u32, u64)> {
colors.sort_unstable_by_key(|&(color, _)| color);
colors.dedup_by(|next, kept| {
if next.0 == kept.0 {
kept.1 = kept.1.saturating_add(next.1);
true
} else {
false
}
});
colors
}
impl Histogram {
#[must_use]
pub fn new(attr: &Attributes) -> Self {
Self {
colors: Vec::new(),
fixed: Vec::new(),
gamma: None,
profile: attr.profile,
}
}
fn check(&self, attr: &Attributes, gamma: f64) -> Result<(), Error> {
if attr.profile != self.profile {
attr.log_error("the histogram was created with another profile");
return Err(Error::ValueOutOfRange);
}
if self.gamma.is_some_and(|g| g != gamma) {
attr.log_error("all images of a histogram must have the same gamma");
return Err(Error::ValueOutOfRange);
}
Ok(())
}
pub fn add_image(&mut self, attr: &Attributes, image: &mut Image<'_>) -> Result<(), Error> {
self.check(attr, image.gamma)?;
let new_fixed: Vec<RGBA> = image
.fixed_rgba
.iter()
.copied()
.filter(|c| !self.fixed.contains(c))
.collect();
if self.fixed.len() + new_fixed.len() > 256 {
return Err(Error::BufferTooSmall);
}
image.ensure_color_space(self.profile.color_space());
let counts = count_image_colors(image, attr);
attr.verbose_print(&format!(" added image to histogram...{} colors", counts.len()));
self.colors = merge(&self.colors, &counts);
for c in new_fixed {
if !self.fixed.contains(&c) {
self.fixed.push(c);
}
}
self.gamma = Some(image.gamma);
Ok(())
}
pub fn add_colors(&mut self, entries: &[HistogramEntry], gamma: f64) -> Result<(), Error> {
let gamma = normalize_gamma(gamma)?;
if self.gamma.is_some_and(|g| g != gamma) {
return Err(Error::ValueOutOfRange);
}
let counts: Vec<(u32, u64)> = entries
.iter()
.filter(|e| e.count > 0)
.map(|e| (color_key(e.color, 0), u64::from(e.count) * WEIGHT_UNITS))
.collect();
self.colors = merge(&self.colors, &sort_and_sum(counts));
self.gamma = Some(gamma);
Ok(())
}
pub fn add_fixed_color(&mut self, color: RGBA, gamma: f64) -> Result<(), Error> {
let gamma = normalize_gamma(gamma)?;
if self.gamma.is_some_and(|g| g != gamma) {
return Err(Error::ValueOutOfRange);
}
if !self.fixed.contains(&color) {
if self.fixed.len() >= 256 {
return Err(Error::BufferTooSmall);
}
self.fixed.push(color);
}
self.gamma = Some(gamma);
Ok(())
}
pub fn quantize(&mut self, attr: &Attributes) -> Result<QuantizationResult, Error> {
let gamma = self.gamma.unwrap_or(SRGB_GAMMA);
self.check(attr, gamma)?;
let lut = ColorLut::new(gamma, self.profile.color_space());
let mut ignorebits = u32::from(cmax(attr.min_posterization_output, attr.min_posterization_input));
let colors = loop {
let colors = if ignorebits == 0 {
self.colors.clone()
} else {
let posterized = self.colors.iter().map(|&(key, w)| {
let [r, g, b, a] = key.to_le_bytes();
(color_key(RGBA::new(r, g, b, a), ignorebits), w)
});
sort_and_sum(posterized.collect())
};
if colors.len() <= attr.max_histogram_entries as usize {
break colors;
}
if ignorebits >= 7 {
return Err(Error::OutOfMemory);
}
ignorebits += 1;
attr.verbose_print(&format!(
" too many colors! Scaling colors to improve clustering... {ignorebits}"
));
};
let len = colors.len();
let weights = colors
.into_iter()
.map(|(key, w)| (key, (w as f64 / WEIGHT_UNITS as f64) as f32));
let mut hist = make_histogram(weights, len, &lut, f32::INFINITY, ignorebits);
attr.verbose_print(&format!(" made histogram...{len} colors found"));
let fixed: Vec<FPixel> = self.fixed.iter().map(|&c| FPixel::from_rgba(&lut, c)).collect();
remove_fixed_colors_from_histogram(&mut hist, &fixed, attr.target_mse as f32);
let mut result = pngquant_quantize(&mut hist, attr, &fixed, gamma)?;
result.set_shared_palette();
Ok(result)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn merge_adds_equal_colors() {
let a = [(1, 10), (5, 1), (9, 2)];
let b = [(0, 3), (5, 4), (10, 1)];
assert_eq!(merge(&a, &b), [(0, 3), (1, 10), (5, 5), (9, 2), (10, 1)]);
assert_eq!(merge(&[], &b), b);
assert_eq!(
sort_and_sum(vec![(4, 1), (2, 2), (4, 3), (2, u64::MAX)]),
[(2, u64::MAX), (4, 4)]
);
}
#[test]
fn transparent_colors_are_one_color() {
let attr = crate::new();
let mut h = Histogram::new(&attr);
let entries = [
HistogramEntry {
color: RGBA::new(1, 2, 3, 0),
count: 2,
},
HistogramEntry {
color: RGBA::new(9, 9, 9, 0),
count: 3,
},
];
h.add_colors(&entries, 0.0).unwrap();
assert_eq!(h.colors, [(0, 5 * WEIGHT_UNITS)]);
}
#[test]
fn image_weights_are_limited_to_a_tenth_of_the_area() {
let mut attr = crate::new();
attr.set_speed(10).unwrap();
let mut pixels = vec![RGBA::new(10, 20, 30, 255); 100];
pixels[0] = RGBA::new(200, 0, 0, 255);
let mut image = attr.new_image(pixels, 10, 10, 0.0).unwrap();
let mut h = Histogram::new(&attr);
h.add_image(&attr, &mut image).unwrap();
h.add_image(&attr, &mut image).unwrap();
let weight = |c: RGBA| h.colors.iter().find(|e| e.0 == color_key(c, 0)).unwrap().1;
assert_eq!(weight(RGBA::new(10, 20, 30, 255)), 2 * 10 * WEIGHT_UNITS);
assert_eq!(weight(RGBA::new(200, 0, 0, 255)), 2 * WEIGHT_UNITS);
}
}