use crate::luminance::{
BT601_LUMA_WEIGHTS, BT709_LUMA_WEIGHTS, BT2020_LUMA_WEIGHTS, LUMA_FIX, LUMA_ONE,
};
use crate::{
ColorModel, Dimensions, Error, ImageBuf, ImageRef, Pixel, PixelFormat, Result, Sample,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
#[repr(u32)]
pub enum AlphaPolicy {
#[default]
Reject = 0,
Drop = 1,
CompositeOver = 2,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
#[repr(u32)]
pub enum DepthPolicy {
#[default]
Reject = 0,
Rescale = 1,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
#[repr(u32)]
pub enum LumaPolicy {
#[default]
Reject = 0,
Bt601 = 1,
Bt709 = 2,
Bt2020 = 3,
}
impl LumaPolicy {
fn weights(self) -> Option<[u32; 3]> {
match self {
LumaPolicy::Reject => None,
LumaPolicy::Bt601 => Some(BT601_LUMA_WEIGHTS),
LumaPolicy::Bt709 => Some(BT709_LUMA_WEIGHTS),
LumaPolicy::Bt2020 => Some(BT2020_LUMA_WEIGHTS),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[must_use]
pub struct ConvertPolicy {
alpha: AlphaPolicy,
depth: DepthPolicy,
luma: LumaPolicy,
background: [u16; 3],
threshold: u16,
}
impl Default for ConvertPolicy {
fn default() -> Self {
Self::lossless()
}
}
impl ConvertPolicy {
const DEFAULT_THRESHOLD: u16 = 32_768;
pub const fn lossless() -> Self {
Self {
alpha: AlphaPolicy::Reject,
depth: DepthPolicy::Reject,
luma: LumaPolicy::Reject,
background: [0; 3],
threshold: Self::DEFAULT_THRESHOLD,
}
}
pub const fn permissive() -> Self {
Self {
alpha: AlphaPolicy::Drop,
depth: DepthPolicy::Rescale,
luma: LumaPolicy::Bt709,
background: [0; 3],
threshold: Self::DEFAULT_THRESHOLD,
}
}
pub const fn with_alpha(mut self, policy: AlphaPolicy) -> Self {
self.alpha = policy;
self
}
pub const fn with_depth(mut self, policy: DepthPolicy) -> Self {
self.depth = policy;
self
}
pub const fn with_luma(mut self, policy: LumaPolicy) -> Self {
self.luma = policy;
self
}
pub const fn with_background(mut self, rgb: [u16; 3]) -> Self {
self.background = rgb;
self
}
pub const fn with_threshold(mut self, threshold: u16) -> Self {
self.threshold = threshold;
self
}
#[must_use]
pub const fn alpha(self) -> AlphaPolicy {
self.alpha
}
#[must_use]
pub const fn depth(self) -> DepthPolicy {
self.depth
}
#[must_use]
pub const fn luma(self) -> LumaPolicy {
self.luma
}
#[must_use]
pub const fn background(self) -> [u16; 3] {
self.background
}
#[must_use]
pub const fn threshold(self) -> u16 {
self.threshold
}
}
#[derive(Debug, Clone, Copy)]
#[must_use]
pub struct RawImage<'a, S: Sample> {
samples: &'a [S],
format: PixelFormat,
dims: Dimensions,
}
impl<'a, S: Sample> RawImage<'a, S> {
pub fn new(samples: &'a [S], format: PixelFormat, dims: Dimensions) -> Result<Self> {
if format.bytes_per_sample() != core::mem::size_of::<S>() {
return Err(Error::invalid_input(
env!("CARGO_PKG_NAME"),
"convert: sample type does not match the pixel format's sample width",
));
}
if dims.is_empty() {
return Err(Error::invalid_input(
env!("CARGO_PKG_NAME"),
"convert: zero-sized image",
));
}
let want = dims.sample_count(format.channels()).ok_or_else(|| {
Error::invalid_input(
env!("CARGO_PKG_NAME"),
"convert: image dimensions overflow usize",
)
})?;
if samples.len() != want {
return Err(Error::invalid_input(
env!("CARGO_PKG_NAME"),
"convert: sample count does not match dimensions",
));
}
Ok(Self {
samples,
format,
dims,
})
}
pub(crate) fn from_branded(samples: &'a [S], format: PixelFormat, dims: Dimensions) -> Self {
Self {
samples,
format,
dims,
}
}
#[must_use]
pub fn as_samples(self) -> &'a [S] {
self.samples
}
#[must_use]
pub fn format(self) -> PixelFormat {
self.format
}
#[must_use]
pub fn dimensions(self) -> Dimensions {
self.dims
}
}
fn colour_channels(model: ColorModel) -> Option<usize> {
match model {
ColorModel::Gray | ColorModel::GrayAlpha | ColorModel::Bilevel => Some(1),
ColorModel::Rgb | ColorModel::Rgba => Some(3),
ColorModel::Cmyk | ColorModel::Indexed => None,
}
}
fn has_alpha(model: ColorModel) -> bool {
match model {
ColorModel::GrayAlpha | ColorModel::Rgba => true,
ColorModel::Gray
| ColorModel::Bilevel
| ColorModel::Rgb
| ColorModel::Cmyk
| ColorModel::Indexed => false,
}
}
fn opaque_model(model: ColorModel) -> Error {
let message = match model {
ColorModel::Indexed => {
"convert: palette indices cannot be converted without the palette table"
}
_ => "convert: CMYK conversion needs a colour-management transform, not a layout change",
};
Error::unsupported(env!("CARGO_PKG_NAME"), message)
}
#[derive(Debug, Clone, Copy)]
struct Plan {
src_channels: usize,
dst_channels: usize,
src_colour: usize,
dst_colour: usize,
src_alpha: bool,
dst_alpha: bool,
src_bilevel: bool,
dst_bilevel: bool,
identity: bool,
composite: bool,
weights: [u32; 3],
background: [u16; 3],
threshold: u16,
}
impl Plan {
fn identity(format: PixelFormat) -> Self {
Self {
src_channels: format.channels(),
dst_channels: format.channels(),
src_colour: 0,
dst_colour: 0,
src_alpha: false,
dst_alpha: false,
src_bilevel: false,
dst_bilevel: false,
identity: true,
composite: false,
weights: BT709_LUMA_WEIGHTS,
background: [0; 3],
threshold: 0,
}
}
fn derive(src: PixelFormat, dst: PixelFormat, policy: ConvertPolicy) -> Result<Self> {
if src == dst {
return Ok(Self::identity(src));
}
let (src_model, dst_model) = (src.color_model(), dst.color_model());
let src_colour = colour_channels(src_model).ok_or_else(|| opaque_model(src_model))?;
let dst_colour = colour_channels(dst_model).ok_or_else(|| opaque_model(dst_model))?;
let src_alpha = has_alpha(src_model);
let dst_alpha = has_alpha(dst_model);
let src_bilevel = src_model == ColorModel::Bilevel;
let dst_bilevel = dst_model == ColorModel::Bilevel;
let drops_alpha = src_alpha && !dst_alpha;
if drops_alpha && policy.alpha == AlphaPolicy::Reject {
return Err(Error::unsupported(
env!("CARGO_PKG_NAME"),
"convert: target layout cannot hold the source's alpha channel; set an AlphaPolicy",
));
}
if src_colour == 3 && dst_colour == 1 && policy.luma == LumaPolicy::Reject {
return Err(Error::unsupported(
env!("CARGO_PKG_NAME"),
"convert: target layout cannot hold colour; set a LumaPolicy",
));
}
let narrows_samples = src.bytes_per_sample() > dst.bytes_per_sample();
let narrows_to_bilevel = dst_bilevel && !src_bilevel;
if (narrows_samples || narrows_to_bilevel) && policy.depth == DepthPolicy::Reject {
return Err(Error::unsupported(
env!("CARGO_PKG_NAME"),
"convert: target layout is narrower than the source; set a DepthPolicy",
));
}
Ok(Self {
src_channels: src.channels(),
dst_channels: dst.channels(),
src_colour,
dst_colour,
src_alpha,
dst_alpha,
src_bilevel,
dst_bilevel,
identity: false,
composite: drops_alpha && policy.alpha == AlphaPolicy::CompositeOver,
weights: policy.luma.weights().unwrap_or(BT709_LUMA_WEIGHTS),
background: policy.background,
threshold: policy.threshold,
})
}
}
fn read<S: Sample>(sample: S, bilevel: bool) -> u16 {
if bilevel {
if sample == S::default() { 0 } else { u16::MAX }
} else {
sample.to_full_range_u16()
}
}
fn write<T: Sample>(value: u16, bilevel: bool, threshold: u16) -> T {
if bilevel {
if value >= threshold {
T::MAX_VALUE
} else {
T::default()
}
} else {
T::from_full_range_u16(value)
}
}
fn composite(value: u16, alpha: u16, background: u16) -> u16 {
let inverse = u32::from(u16::MAX - alpha);
let blended = u64::from(value) * u64::from(alpha) + u64::from(background) * u64::from(inverse);
((blended + 32_767) / 65_535) as u16
}
fn luma(rgb: [u16; 3], weights: [u32; 3]) -> u16 {
let sum: u64 = weights
.iter()
.zip(rgb)
.map(|(&weight, channel)| u64::from(weight) * u64::from(channel))
.sum();
((sum + u64::from(LUMA_ONE / 2)) >> LUMA_FIX) as u16
}
fn run<S: Sample, T: Sample>(src: &[S], dst: &mut [T], plan: &Plan) {
if plan.identity {
for (target, source) in dst.iter_mut().zip(src) {
*target = T::from_full_range_u16(source.to_full_range_u16());
}
return;
}
let pixels = src.chunks_exact(plan.src_channels);
let targets = dst.chunks_exact_mut(plan.dst_channels);
for (source, target) in pixels.zip(targets) {
let mut rgb = [0u16; 3];
if plan.src_colour == 1 {
let grey = read(source[0], plan.src_bilevel);
rgb = [grey; 3];
} else {
for (channel, sample) in rgb.iter_mut().zip(source) {
*channel = read(*sample, plan.src_bilevel);
}
}
let alpha = if plan.src_alpha {
read(source[plan.src_colour], false)
} else {
u16::MAX
};
if plan.composite {
for (channel, background) in rgb.iter_mut().zip(plan.background) {
*channel = composite(*channel, alpha, background);
}
}
if plan.dst_colour == 1 {
target[0] = write(luma(rgb, plan.weights), plan.dst_bilevel, plan.threshold);
} else {
for (sample, channel) in target.iter_mut().zip(rgb) {
*sample = write(channel, plan.dst_bilevel, plan.threshold);
}
}
if plan.dst_alpha {
target[plan.dst_colour] = write(alpha, false, plan.threshold);
}
}
}
pub fn convert_from_raw<S: Sample, Q: Pixel>(
src: RawImage<'_, S>,
policy: ConvertPolicy,
) -> Result<ImageBuf<Q>> {
let plan = Plan::derive(src.format, Q::FORMAT, policy)?;
let mut out = ImageBuf::<Q>::zeroed(src.dims)?;
run(src.samples, out.as_mut_samples(), &plan);
Ok(out)
}
pub fn convert_from_raw_into<S: Sample, Q: Pixel>(
src: RawImage<'_, S>,
policy: ConvertPolicy,
dst: &mut [Q::Sample],
) -> Result<()> {
let plan = Plan::derive(src.format, Q::FORMAT, policy)?;
let want = src.dims.sample_count(Q::CHANNELS).ok_or_else(|| {
Error::invalid_input(
env!("CARGO_PKG_NAME"),
"convert: image dimensions overflow usize",
)
})?;
if dst.len() != want {
return Err(Error::invalid_input(
env!("CARGO_PKG_NAME"),
"convert: destination length does not match dimensions",
));
}
run(src.samples, dst, &plan);
Ok(())
}
pub fn convert<P: Pixel, Q: Pixel>(
src: ImageRef<'_, P>,
policy: ConvertPolicy,
) -> Result<ImageBuf<Q>> {
convert_from_raw(src.as_raw(), policy)
}
fn code_max<S: Sample>() -> u64 {
(1 << (8 * core::mem::size_of::<S>())) - 1
}
fn to_code<S: Sample>(sample: S, max: u64) -> u64 {
u64::from(sample.to_full_range_u16()) * max / 65_535
}
fn from_code<S: Sample>(code: u64, max: u64) -> S {
S::from_full_range_u16((code * 65_535 / max) as u16)
}
fn premultiply_code(colour: u64, alpha: u64, max: u64) -> u64 {
(colour * alpha + max / 2) / max
}
fn unpremultiply_code(colour: u64, alpha: u64, max: u64) -> u64 {
if alpha == 0 {
return 0;
}
((colour * max + alpha / 2) / alpha).min(max)
}
fn apply_alpha<P: Pixel>(image: &mut ImageBuf<P>, op: fn(u64, u64, u64) -> u64) {
if !has_alpha(P::MODEL) {
return;
}
let max = code_max::<P::Sample>();
let alpha_index = P::CHANNELS - 1;
for pixel in image.as_mut_samples().chunks_exact_mut(P::CHANNELS) {
let (colour, alpha) = pixel.split_at_mut(alpha_index);
let alpha = to_code(alpha[0], max);
for sample in colour {
*sample = from_code(op(to_code(*sample, max), alpha, max), max);
}
}
}
pub fn premultiply_alpha<P: Pixel>(image: &mut ImageBuf<P>) {
apply_alpha(image, premultiply_code);
}
pub fn unpremultiply_alpha<P: Pixel>(image: &mut ImageBuf<P>) {
apply_alpha(image, unpremultiply_code);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
Bilevel, Cmyk8, ErrorKind, Gray8, Gray16, GrayAlpha8, GrayAlpha16, Indexed8, Rgb8, Rgb16,
Rgba8, Rgba16,
};
fn dims(w: u32, h: u32) -> Dimensions {
Dimensions {
width: w,
height: h,
}
}
fn raw<S: Sample>(samples: &[S], format: PixelFormat) -> RawImage<'_, S> {
RawImage::new(samples, format, dims(1, 1)).unwrap()
}
#[test]
fn lossless_widening_needs_no_policy() {
let strict = ConvertPolicy::lossless();
let grey = raw(&[7u8], PixelFormat::Gray8);
let rgb = convert_from_raw::<_, Rgb8>(grey, strict).unwrap();
assert_eq!(rgb.as_samples(), &[7, 7, 7]);
let rgba = convert_from_raw::<_, Rgba8>(grey, strict).unwrap();
assert_eq!(rgba.as_samples(), &[7, 7, 7, 255]);
let white = raw(&[255u8, 128, 0], PixelFormat::Rgb8);
let wide = convert_from_raw::<_, Rgb16>(white, strict).unwrap();
assert_eq!(wide.as_samples(), &[0xFFFF, 0x8080, 0]);
}
#[test]
fn dropping_alpha_needs_an_alpha_policy() {
let src = raw(&[10u8, 20, 30, 128], PixelFormat::Rgba8);
let refused = convert_from_raw::<_, Rgb8>(src, ConvertPolicy::lossless()).unwrap_err();
assert_eq!(refused.kind(), ErrorKind::Unsupported);
assert_eq!(refused.origin(), Some("gamut-core"));
let dropped = convert_from_raw::<_, Rgb8>(
src,
ConvertPolicy::lossless().with_alpha(AlphaPolicy::Drop),
)
.unwrap();
assert_eq!(dropped.as_samples(), &[10, 20, 30]);
}
#[test]
fn compositing_blends_against_the_background() {
let src = raw(&[128u8, 128, 128, 128], PixelFormat::Rgba8);
let over_black = ConvertPolicy::lossless()
.with_alpha(AlphaPolicy::CompositeOver)
.with_background([0; 3]);
let over_white = ConvertPolicy::lossless()
.with_alpha(AlphaPolicy::CompositeOver)
.with_background([u16::MAX; 3]);
let dark = convert_from_raw::<_, Rgb8>(src, over_black).unwrap();
let light = convert_from_raw::<_, Rgb8>(src, over_white).unwrap();
assert!(dark.as_samples()[0] < 128, "{:?}", dark.as_samples());
assert!(light.as_samples()[0] > 128, "{:?}", light.as_samples());
let opaque = raw(&[200u8, 100, 50, 255], PixelFormat::Rgba8);
assert_eq!(
convert_from_raw::<_, Rgb8>(opaque, over_white)
.unwrap()
.as_samples(),
&[200, 100, 50]
);
let clear = raw(&[200u8, 100, 50, 0], PixelFormat::Rgba8);
assert_eq!(
convert_from_raw::<_, Rgb8>(clear, over_white)
.unwrap()
.as_samples(),
&[255, 255, 255]
);
}
#[test]
fn compositing_rounds_to_nearest_at_full_precision() {
let src = raw(&[1u16, 1, 1, u16::MAX], PixelFormat::Rgba16);
let policy = ConvertPolicy::lossless()
.with_alpha(AlphaPolicy::CompositeOver)
.with_background([0; 3]);
assert_eq!(
convert_from_raw::<_, Rgb16>(src, policy)
.unwrap()
.as_samples(),
&[1, 1, 1]
);
}
#[test]
fn reducing_colour_needs_a_luma_policy_and_honours_the_standard() {
let src = raw(&[255u8, 0, 0], PixelFormat::Rgb8);
assert_eq!(
convert_from_raw::<_, Gray8>(src, ConvertPolicy::lossless())
.unwrap_err()
.kind(),
ErrorKind::Unsupported
);
let bt601 = convert_from_raw::<_, Gray8>(
src,
ConvertPolicy::lossless().with_luma(LumaPolicy::Bt601),
)
.unwrap();
let bt709 = convert_from_raw::<_, Gray8>(
src,
ConvertPolicy::lossless().with_luma(LumaPolicy::Bt709),
)
.unwrap();
assert_eq!(bt601.as_samples(), &[76]); assert_eq!(bt709.as_samples(), &[54]); assert_ne!(bt601.as_samples(), bt709.as_samples());
}
#[test]
fn luma_rounds_to_nearest_rather_than_truncating() {
let src = raw(&[3u16, 0, 0], PixelFormat::Rgb16);
let policy = ConvertPolicy::lossless().with_luma(LumaPolicy::Bt709);
assert_eq!(
convert_from_raw::<_, Gray16>(src, policy)
.unwrap()
.as_samples(),
&[1]
);
}
#[test]
fn a_grey_source_reaches_a_grey_target_unchanged() {
let policy = ConvertPolicy::lossless().with_alpha(AlphaPolicy::Drop);
for value in 0..=u8::MAX {
let samples = [value, 255];
let src = raw(&samples, PixelFormat::GrayAlpha8);
let out = convert_from_raw::<_, Gray8>(src, policy).unwrap();
assert_eq!(out.as_samples(), &[value]);
}
}
#[test]
fn narrowing_samples_needs_a_depth_policy() {
let src = raw(&[0xFFFFu16, 0x8080, 0], PixelFormat::Rgb16);
assert_eq!(
convert_from_raw::<_, Rgb8>(src, ConvertPolicy::lossless())
.unwrap_err()
.kind(),
ErrorKind::Unsupported
);
let narrowed = convert_from_raw::<_, Rgb8>(
src,
ConvertPolicy::lossless().with_depth(DepthPolicy::Rescale),
)
.unwrap();
assert_eq!(narrowed.as_samples(), &[255, 128, 0]);
}
#[test]
fn bilevel_expands_losslessly_and_thresholds_on_the_way_back() {
for white in [1u8, 255] {
let samples = [white];
let src = raw(&samples, PixelFormat::Bilevel);
let grey = convert_from_raw::<_, Gray8>(src, ConvertPolicy::lossless()).unwrap();
assert_eq!(grey.as_samples(), &[255]);
}
let black = raw(&[0u8], PixelFormat::Bilevel);
assert_eq!(
convert_from_raw::<_, Gray8>(black, ConvertPolicy::lossless())
.unwrap()
.as_samples(),
&[0]
);
let mid = raw(&[128u8], PixelFormat::Gray8);
assert_eq!(
convert_from_raw::<_, Bilevel>(mid, ConvertPolicy::lossless())
.unwrap_err()
.kind(),
ErrorKind::Unsupported
);
let rescale = ConvertPolicy::lossless().with_depth(DepthPolicy::Rescale);
assert_eq!(
convert_from_raw::<_, Bilevel>(mid, rescale)
.unwrap()
.as_samples(),
&[255]
);
assert_eq!(
convert_from_raw::<_, Bilevel>(mid, rescale.with_threshold(0x8081))
.unwrap()
.as_samples(),
&[0]
);
}
#[test]
fn palette_and_cmyk_convert_only_to_themselves() {
let strict = ConvertPolicy::lossless();
let permissive = ConvertPolicy::permissive();
let indexed = raw(&[5u8], PixelFormat::Indexed8);
let cmyk = raw(&[1u8, 2, 3, 4], PixelFormat::Cmyk8);
for policy in [strict, permissive] {
assert_eq!(
convert_from_raw::<_, Rgb8>(indexed, policy)
.unwrap_err()
.kind(),
ErrorKind::Unsupported
);
assert_eq!(
convert_from_raw::<_, Rgb8>(cmyk, policy)
.unwrap_err()
.kind(),
ErrorKind::Unsupported
);
let rgb = raw(&[1u8, 2, 3], PixelFormat::Rgb8);
assert_eq!(
convert_from_raw::<_, Cmyk8>(rgb, policy)
.unwrap_err()
.kind(),
ErrorKind::Unsupported
);
assert_eq!(
convert_from_raw::<_, Indexed8>(rgb, policy)
.unwrap_err()
.kind(),
ErrorKind::Unsupported
);
}
let indexed_err = convert_from_raw::<_, Rgb8>(indexed, strict).unwrap_err();
let cmyk_err = convert_from_raw::<_, Rgb8>(cmyk, strict).unwrap_err();
let indexed_msg = indexed_err.static_message().unwrap();
let cmyk_msg = cmyk_err.static_message().unwrap();
assert_ne!(indexed_msg, cmyk_msg);
assert!(indexed_msg.contains("palette"), "{indexed_msg}");
assert!(cmyk_msg.contains("colour-management"), "{cmyk_msg}");
assert_eq!(
convert_from_raw::<_, Indexed8>(indexed, strict)
.unwrap()
.as_samples(),
&[5]
);
assert_eq!(
convert_from_raw::<_, Cmyk8>(cmyk, strict)
.unwrap()
.as_samples(),
&[1, 2, 3, 4]
);
}
#[test]
fn typed_convert_matches_the_raw_engine() {
let dimensions = dims(2, 1);
let rgba = [10u8, 20, 30, 255, 40, 50, 60, 255];
let image = ImageRef::<Rgba8>::new(&rgba, dimensions).unwrap();
let policy = ConvertPolicy::lossless().with_alpha(AlphaPolicy::Drop);
let typed = convert::<Rgba8, Rgb8>(image, policy).unwrap();
let via_raw = convert_from_raw::<_, Rgb8>(
RawImage::new(&rgba, PixelFormat::Rgba8, dimensions).unwrap(),
policy,
)
.unwrap();
assert_eq!(typed, via_raw);
assert_eq!(typed.as_samples(), &[10, 20, 30, 40, 50, 60]);
assert_eq!(typed.dimensions(), dimensions);
}
#[test]
fn convert_into_reuses_storage_and_validates_length() {
let dimensions = dims(2, 1);
let grey = [1u8, 2];
let src = RawImage::new(&grey, PixelFormat::Gray8, dimensions).unwrap();
let mut dst = ImageBuf::<Rgb8>::zeroed(dimensions).unwrap();
convert_from_raw_into::<_, Rgb8>(src, ConvertPolicy::lossless(), dst.as_mut_samples())
.unwrap();
assert_eq!(dst.as_samples(), &[1, 1, 1, 2, 2, 2]);
let mut short = [0u8; 5];
let err = convert_from_raw_into::<_, Rgb8>(src, ConvertPolicy::lossless(), &mut short)
.unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
assert_eq!(short, [0; 5]);
let alpha_src = RawImage::new(&[1u8, 2, 3, 4], PixelFormat::Rgba8, dims(1, 1)).unwrap();
let mut target = [9u8; 3];
assert!(
convert_from_raw_into::<_, Rgb8>(alpha_src, ConvertPolicy::lossless(), &mut target)
.is_err()
);
assert_eq!(target, [9; 3]);
}
#[test]
fn raw_image_validates_its_description() {
let samples = [0u8; 6];
assert!(RawImage::new(&samples, PixelFormat::Rgb8, dims(2, 1)).is_ok());
assert!(RawImage::new(&samples, PixelFormat::Rgb8, dims(3, 1)).is_err());
assert!(RawImage::new(&[] as &[u8], PixelFormat::Rgb8, dims(0, 1)).is_err());
assert!(RawImage::new(&samples, PixelFormat::Rgb16, dims(2, 1)).is_err());
assert!(RawImage::new(&[0u16; 6], PixelFormat::Rgb8, dims(2, 1)).is_err());
let image = RawImage::new(&samples, PixelFormat::Rgb8, dims(2, 1)).unwrap();
assert_eq!(image.format(), PixelFormat::Rgb8);
assert_eq!(image.dimensions(), dims(2, 1));
assert_eq!(image.as_samples().len(), 6);
}
fn sample_pixel(format: PixelFormat) -> Vec<u8> {
(0..format.channels()).map(|i| (i as u8 + 1) * 17).collect()
}
fn expected_supported(src: PixelFormat, dst: PixelFormat) -> bool {
let opaque =
|f: PixelFormat| matches!(f.color_model(), ColorModel::Cmyk | ColorModel::Indexed);
if opaque(src) || opaque(dst) {
return src == dst;
}
true
}
#[test]
fn every_layout_pair_is_either_supported_or_refused() {
for &src in PixelFormat::ALL {
for &dst in PixelFormat::ALL {
let bytes = sample_pixel(src);
let result = if src.bytes_per_sample() == 1 {
run_pair(RawImage::new(&bytes, src, dims(1, 1)).unwrap(), dst)
} else {
let widened: Vec<u16> = bytes.iter().map(|&b| u16::from(b) * 257).collect();
run_pair(RawImage::new(&widened, src, dims(1, 1)).unwrap(), dst)
};
assert_eq!(
result.is_ok(),
expected_supported(src, dst),
"{src:?} -> {dst:?} disagreed with the documented contract"
);
if let Ok(len) = result {
assert_eq!(
len,
dst.channels(),
"{src:?} -> {dst:?} wrote a short pixel"
);
}
}
}
}
fn run_pair<S: Sample>(src: RawImage<'_, S>, dst: PixelFormat) -> Result<usize> {
let policy = ConvertPolicy::permissive();
macro_rules! go {
($marker:ty) => {
convert_from_raw::<S, $marker>(src, policy).map(|b| b.as_samples().len())
};
}
match dst {
PixelFormat::Gray8 => go!(Gray8),
PixelFormat::Bilevel => go!(Bilevel),
PixelFormat::Indexed8 => go!(Indexed8),
PixelFormat::Rgb8 => go!(Rgb8),
PixelFormat::Rgba8 => go!(Rgba8),
PixelFormat::Cmyk8 => go!(Cmyk8),
PixelFormat::GrayAlpha8 => go!(GrayAlpha8),
PixelFormat::Gray16 => go!(Gray16),
PixelFormat::Rgb16 => go!(Rgb16),
PixelFormat::Rgba16 => go!(Rgba16),
PixelFormat::GrayAlpha16 => go!(GrayAlpha16),
}
}
#[test]
fn policy_defaults_and_setters_are_independent() {
assert_eq!(ConvertPolicy::default(), ConvertPolicy::lossless());
assert_ne!(ConvertPolicy::lossless(), ConvertPolicy::permissive());
let base = ConvertPolicy::lossless();
assert_eq!(
base.with_alpha(AlphaPolicy::Drop).depth,
DepthPolicy::Reject
);
assert_eq!(
base.with_depth(DepthPolicy::Rescale).alpha,
AlphaPolicy::Reject
);
assert_eq!(base.with_luma(LumaPolicy::Bt601).luma, LumaPolicy::Bt601);
assert_eq!(base.with_background([1, 2, 3]).background, [1, 2, 3]);
assert_eq!(base.with_threshold(7).threshold, 7);
assert_eq!(base.with_threshold(7).background, [0; 3]);
}
fn row<P: Pixel>(samples: Vec<P::Sample>) -> ImageBuf<P> {
let width = u32::try_from(samples.len() / P::CHANNELS).unwrap();
ImageBuf::new(samples, dims(width, 1)).unwrap()
}
#[test]
fn code_values_round_trip_through_the_full_range_scale_at_both_widths() {
assert_eq!(code_max::<u8>(), 255);
assert_eq!(code_max::<u16>(), 65_535);
for code in [0u8, 1, 128, 254, 255] {
assert_eq!(to_code(code, 255), u64::from(code));
assert_eq!(from_code::<u8>(u64::from(code), 255), code);
}
for code in [0u16, 1, 0x8000, 0xFFFE, 0xFFFF] {
assert_eq!(to_code(code, 65_535), u64::from(code));
assert_eq!(from_code::<u16>(u64::from(code), 65_535), code);
}
}
#[test]
fn premultiply_rounds_to_nearest() {
assert_eq!(premultiply_code(1, 128, 255), 1);
assert_eq!(premultiply_code(1, 127, 255), 0);
assert_eq!(premultiply_code(200, 128, 255), 100); assert_eq!(premultiply_code(255, 0, 255), 0);
assert_eq!(premultiply_code(77, 255, 255), 77);
assert_eq!(premultiply_code(1, 32_768, 65_535), 1);
assert_eq!(premultiply_code(1, 32_767, 65_535), 0);
}
#[test]
fn unpremultiply_rounds_to_nearest_and_clamps() {
assert_eq!(unpremultiply_code(1, 4, 255), 64);
assert_eq!(unpremultiply_code(1, 2, 255), 128);
assert_eq!(unpremultiply_code(3, 7, 255), 109);
assert_eq!(unpremultiply_code(100, 128, 255), 199); assert_eq!(unpremultiply_code(77, 255, 255), 77);
assert_eq!(unpremultiply_code(200, 100, 255), 255);
assert_eq!(unpremultiply_code(2, 1, 65_535), 65_535);
assert_eq!(unpremultiply_code(9, 0, 255), 0);
assert_eq!(unpremultiply_code(1, 2, 65_535), 32_768);
}
#[test]
fn premultiplying_rewrites_colour_and_keeps_alpha() {
let mut rgba = row::<Rgba8>(vec![200, 100, 50, 128, 9, 9, 9, 0, 1, 2, 3, 255]);
premultiply_alpha(&mut rgba);
assert_eq!(
rgba.as_samples(),
&[100, 50, 25, 128, 0, 0, 0, 0, 1, 2, 3, 255]
);
unpremultiply_alpha(&mut rgba);
assert_eq!(
rgba.as_samples(),
&[199, 100, 50, 128, 0, 0, 0, 0, 1, 2, 3, 255]
);
let mut wide = row::<Rgba16>(vec![0xFFFF, 0x8000, 1, 0x8000]);
premultiply_alpha(&mut wide);
assert_eq!(wide.as_samples(), &[0x8000, 0x4000, 1, 0x8000]);
}
#[test]
fn grey_alpha_layouts_carry_alpha_in_their_second_channel() {
let mut narrow = row::<GrayAlpha8>(vec![200, 128, 255, 0]);
premultiply_alpha(&mut narrow);
assert_eq!(narrow.as_samples(), &[100, 128, 0, 0]);
let mut wide = row::<GrayAlpha16>(vec![0x8000, 0x8000]);
unpremultiply_alpha(&mut wide);
assert_eq!(wide.as_samples(), &[0xFFFF, 0x8000]);
}
#[test]
fn a_layout_without_alpha_is_opaque_and_left_unchanged() {
let mut rgb = row::<Rgb8>(vec![200, 100, 0]);
premultiply_alpha(&mut rgb);
assert_eq!(rgb.as_samples(), &[200, 100, 0]);
unpremultiply_alpha(&mut rgb);
assert_eq!(rgb.as_samples(), &[200, 100, 0]);
}
#[test]
fn luma_policies_select_distinct_weights() {
assert_eq!(LumaPolicy::Reject.weights(), None);
assert_eq!(LumaPolicy::Bt601.weights(), Some(BT601_LUMA_WEIGHTS));
assert_eq!(LumaPolicy::Bt709.weights(), Some(BT709_LUMA_WEIGHTS));
assert_eq!(LumaPolicy::Bt2020.weights(), Some(BT2020_LUMA_WEIGHTS));
}
}