use std::io::Cursor;
use image::{DynamicImage, ImageReader, Limits};
use crate::{Error, LumaBuf, Result, RgbaBuf};
pub const DECODE_MAX_DIMENSION: u32 = 16_384;
pub const DECODE_MAX_ALLOC: u64 = 256 * 1024 * 1024;
pub const DECODE_MAX_INPUT: usize = 64 * 1024 * 1024;
pub fn decode_luma_v1(bytes: &[u8]) -> Result<LumaBuf> {
let rgb = decode(bytes)?.into_rgb8();
LumaBuf::from_rgb8_v1(rgb.width(), rgb.height(), rgb.as_raw())
}
pub fn decode_rgba_v1(bytes: &[u8]) -> Result<RgbaBuf> {
let image = decode(bytes)?;
let (width, height) = (image.width(), image.height());
let pixels: Vec<u8> = match image {
DynamicImage::ImageRgba8(image) => image.into_raw(),
DynamicImage::ImageRgb8(image) => expand(&image.into_raw(), 3, |&[r, g, b, ..]| [r, g, b, u8::MAX]),
DynamicImage::ImageLuma8(image) => expand(&image.into_raw(), 1, |&[v, ..]| [v, v, v, u8::MAX]),
DynamicImage::ImageLumaA8(image) => expand(&image.into_raw(), 2, |&[v, a, ..]| [v, v, v, a]),
DynamicImage::ImageRgba16(image) => image.into_raw().into_iter().map(narrow).collect(),
DynamicImage::ImageRgb16(image) => expand_wide(&image.into_raw(), 3, |&[r, g, b, ..]| [r, g, b, u8::MAX]),
DynamicImage::ImageLuma16(image) => expand_wide(&image.into_raw(), 1, |&[v, ..]| [v, v, v, u8::MAX]),
DynamicImage::ImageLumaA16(image) => expand_wide(&image.into_raw(), 2, |&[v, a, ..]| [v, v, v, a]),
other => {
return Err(Error::Decode(format!(
"the file's `{:?}` samples aren't 8 or 16-bit integers",
other.color()
)));
}
};
RgbaBuf::new(width, height, pixels)
}
fn expand(samples: &[u8], channels: usize, pixel: impl Fn(&[u8; 4]) -> [u8; 4]) -> Vec<u8> {
samples
.chunks_exact(channels)
.flat_map(|chunk| {
let mut padded = [0; 4];
padded[..channels].copy_from_slice(chunk);
pixel(&padded)
})
.collect()
}
fn expand_wide(samples: &[u16], channels: usize, pixel: impl Fn(&[u8; 4]) -> [u8; 4]) -> Vec<u8> {
let narrowed: Vec<u8> = samples.iter().copied().map(narrow).collect();
expand(&narrowed, channels, pixel)
}
fn narrow(sample: u16) -> u8 {
((u32::from(sample) + 128) / 257) as u8
}
fn decode(bytes: &[u8]) -> Result<DynamicImage> {
if bytes.len() > DECODE_MAX_INPUT {
return Err(Error::Decode(format!(
"the file is `{}` bytes; at most `{DECODE_MAX_INPUT}` are read",
bytes.len()
)));
}
let mut reader = ImageReader::new(Cursor::new(bytes))
.with_guessed_format()
.map_err(|error| Error::Decode(error.to_string()))?;
let mut limits = Limits::default();
limits.max_image_width = Some(DECODE_MAX_DIMENSION);
limits.max_image_height = Some(DECODE_MAX_DIMENSION);
limits.max_alloc = Some(DECODE_MAX_ALLOC);
reader.limits(limits);
reader.decode().map_err(|error| Error::Decode(error.to_string()))
}