use std::fmt;
use crate::{Error, Result};
pub const MAX_DIMENSION: u32 = 65_535;
#[must_use]
pub const fn luma_v1(red: u8, green: u8, blue: u8) -> u8 {
let weighted = 19_595 * red as u32 + 38_470 * green as u32 + 7_471 * blue as u32 + 32_768;
(weighted >> 16) as u8
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Luma<'a> {
width: u32,
height: u32,
pixels: &'a [u8],
}
impl<'a> Luma<'a> {
pub fn new(width: u32, height: u32, pixels: &'a [u8]) -> Result<Self> {
check_size(width, height, 1, pixels.len())?;
Ok(Self { width, height, pixels })
}
#[must_use]
pub const fn width(&self) -> u32 {
self.width
}
#[must_use]
pub const fn height(&self) -> u32 {
self.height
}
#[must_use]
pub const fn pixels(&self) -> &'a [u8] {
self.pixels
}
pub fn downscale_v1(&self, width: u32, height: u32) -> Result<LumaBuf> {
check_dimensions(width, height)?;
Ok(LumaBuf {
width,
height,
pixels: downscale(*self, width, height),
})
}
}
impl fmt::Debug for Luma<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Luma")
.field("width", &self.width)
.field("height", &self.height)
.finish_non_exhaustive()
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct LumaBuf {
width: u32,
height: u32,
pixels: Vec<u8>,
}
impl LumaBuf {
pub fn new(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self> {
check_size(width, height, 1, pixels.len())?;
Ok(Self { width, height, pixels })
}
pub fn from_rgb8_v1(width: u32, height: u32, rgb: &[u8]) -> Result<Self> {
Self::from_channels(width, height, rgb, 3)
}
pub fn from_rgba8_v1(width: u32, height: u32, rgba: &[u8]) -> Result<Self> {
Self::from_channels(width, height, rgba, 4)
}
fn from_channels(width: u32, height: u32, samples: &[u8], channels: usize) -> Result<Self> {
check_size(width, height, channels, samples.len())?;
let pixels = samples
.chunks_exact(channels)
.map(|pixel| luma_v1(pixel[0], pixel[1], pixel[2]))
.collect();
Ok(Self { width, height, pixels })
}
#[must_use]
pub fn view(&self) -> Luma<'_> {
Luma {
width: self.width,
height: self.height,
pixels: &self.pixels,
}
}
#[must_use]
pub const fn width(&self) -> u32 {
self.width
}
#[must_use]
pub const fn height(&self) -> u32 {
self.height
}
#[must_use]
pub fn pixels(&self) -> &[u8] {
&self.pixels
}
#[must_use]
pub fn into_pixels(self) -> Vec<u8> {
self.pixels
}
}
impl fmt::Debug for LumaBuf {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LumaBuf")
.field("width", &self.width)
.field("height", &self.height)
.finish_non_exhaustive()
}
}
fn check_dimensions(width: u32, height: u32) -> Result<()> {
if width == 0 || height == 0 {
return Err(Error::ZeroDimension { width, height });
}
if width > MAX_DIMENSION || height > MAX_DIMENSION || u64::from(width) * u64::from(height) > isize::MAX as u64 {
return Err(Error::DimensionTooLarge { width, height });
}
Ok(())
}
pub(crate) fn check_size(width: u32, height: u32, channels: usize, actual: usize) -> Result<()> {
check_dimensions(width, height)?;
let expected = (width as usize)
.checked_mul(height as usize)
.and_then(|pixels| pixels.checked_mul(channels))
.unwrap_or(usize::MAX);
if actual != expected {
return Err(Error::BufferLength { expected, actual });
}
Ok(())
}
pub(crate) fn downscale(image: Luma<'_>, width: u32, height: u32) -> Vec<u8> {
if (image.width, image.height) == (width, height) {
return image.pixels.to_vec();
}
let columns = axis_weights(image.width, width);
let rows = axis_weights(image.height, height);
let source_width = image.width as usize;
let pixel = |x: usize, y: usize| u64::from(image.pixels[y * source_width + x]);
let total = u64::from(image.width) * u64::from(image.height);
let round = |sum: u64| ((sum + total / 2) / total) as u8;
if u64::from(image.height) * u64::from(width) <= u64::from(height) * u64::from(image.width) {
let across: Vec<Vec<u64>> = (0..image.height as usize)
.map(|y| {
columns
.iter()
.map(|cell| cell.iter().map(|&(x, weight)| weight * pixel(x, y)).sum())
.collect()
})
.collect();
rows.iter()
.flat_map(|cell| {
let across = &across;
(0..width as usize).map(move |column| cell.iter().map(|&(y, weight)| weight * across[y][column]).sum())
})
.map(round)
.collect()
} else {
let down: Vec<Vec<u64>> = rows
.iter()
.map(|cell| {
(0..source_width)
.map(|x| cell.iter().map(|&(y, weight)| weight * pixel(x, y)).sum())
.collect()
})
.collect();
down.iter()
.flat_map(|row| {
columns
.iter()
.map(move |cell| cell.iter().map(|&(x, weight)| weight * row[x]).sum())
})
.map(round)
.collect()
}
}
fn axis_weights(source: u32, target: u32) -> Vec<Vec<(usize, u64)>> {
let (source, target) = (u64::from(source), u64::from(target));
(0..target)
.map(|index| {
let start = index * source;
let end = start + source;
(start / target..=(end - 1) / target)
.map(|position| {
let overlap = end.min((position + 1) * target) - start.max(position * target);
(position as usize, overlap)
})
.collect()
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_weights_of_each_target_position_cover_one_source_length() {
for source in 1..40 {
for target in 1..40 {
for weights in axis_weights(source, target) {
assert_eq!(
weights.iter().map(|&(_, weight)| weight).sum::<u64>(),
u64::from(source)
);
assert!(weights.iter().all(|&(_, weight)| weight > 0));
}
}
}
}
}