render: preserve float thumbnail precision and verify output/ICC parity (#2518)

* render: preserve float thumbnail precision and add output/ICC parity tests

* test: match integer un-premultiplication in export_output_and_icc_parity
This commit is contained in:
Dylan M. Taylor
2026-11-19 23:55:48 -05:00
committed by GitHub
parent e97b644a39
commit d4d4b5760a
3 changed files with 144 additions and 19 deletions
+13
View File
@@ -419,3 +419,16 @@ fn profile_parser_survives_junk() {
let _ = Source::of(b"");
let _ = Source::of(&[0x89, b'P', b'N', b'G']);
}
#[test]
fn f32_thumbnail_averages_before_quantizing() {
let samples = [0.0_f32, 0.0, 0.0, 1.0, 0.002, 0.002, 0.002, 1.0].repeat(2);
let raw: Vec<u8> = samples.iter().flat_map(|v| v.to_ne_bytes()).collect();
let img = craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::F32, raw).unwrap();
let exr = craft_image_codecs::encode(&img, craft_image_codecs::Format::OpenExr, &craft_image_codecs::EncodeOptions::default()).unwrap();
let (p, _) = images::decode_within(&exr, ColorProfile::Srgb, 1, u64::MAX).unwrap();
assert_eq!((p.width(), p.height()), (1, 1));
// Average 0.001 * 255 = 0.255 rounds to 0; quantizing first rounds 0.002 * 255 = 0.51 to 1,
// whose 8-bit average rounds to 1.
assert_eq!(p.data(), &[0, 0, 0, 255]);
}
+72 -19
View File
@@ -131,17 +131,31 @@ pub(crate) fn decode_within(bytes: &[u8], target: ColorProfile, max_side: u32, m
let layout = if is_gray { ChannelLayout::GrayA } else { ChannelLayout::Rgba };
let original = img.dimensions();
let (w, h) = thumbnail_size(original.0, original.1, max_side)?;
let pixels = if original != (w, h)
&& img.sample_type() == SampleType::U16
&& matches!(img.layout(), ChannelLayout::Gray | ChannelLayout::GrayA | ChannelLayout::Rgb | ChannelLayout::Rgba)
{
let thumbnail = thumbnail_u16(&img, w, h)?;
drop(img);
thumbnail.convert(layout, SampleType::U8).into_data()
} else {
let converted = img.converted(layout, SampleType::U8);
thumbnail_u8(original, (w, h), is_gray, converted.into_owned().into_data())?
};
let pixels =
if original != (w, h) && matches!(img.layout(), ChannelLayout::Gray | ChannelLayout::GrayA | ChannelLayout::Rgb | ChannelLayout::Rgba) {
match img.sample_type() {
SampleType::U16 => {
let thumbnail = thumbnail_u16(&img, w, h)?;
drop(img);
thumbnail.convert(layout, SampleType::U8).into_data()
}
SampleType::F16 | SampleType::F32 => {
let f32_img = (img.sample_type() == SampleType::F16).then(|| img.converted(img.layout(), SampleType::F32).into_owned());
let src = f32_img.as_ref().unwrap_or(&img);
let thumbnail = thumbnail_f32(src, w, h)?;
drop(f32_img);
drop(img);
thumbnail.convert(layout, SampleType::U8).into_data()
}
SampleType::U8 => {
let converted = img.converted(layout, SampleType::U8);
thumbnail_u8(original, (w, h), is_gray, converted.into_owned().into_data())?
}
}
} else {
let converted = img.converted(layout, SampleType::U8);
thumbnail_u8(original, (w, h), is_gray, converted.into_owned().into_data())?
};
if is_gray {
let rgba = source.convert_u8(w, h, true, &pixels, target)?;
return Some((premultiplied_rgba(w, h, &rgba)?, false));
@@ -180,6 +194,15 @@ fn thumbnail_u8((w, h): (u32, u32), (nw, nh): (u32, u32), is_gray: bool, pixels:
}
}
/// Keep the old thumbnail's floating-point box boundaries. Every axis scales down, so
/// a rounding edge case still needs at least one source sample.
fn source_span(index: u32, input: u32, ratio: f32) -> std::ops::Range<usize> {
let offset = index as f32 * ratio;
let start = (offset.ceil() as u32).min(input - 1);
let end = ((offset + ratio).ceil() as u32).clamp(start + 1, input);
start as usize..end as usize
}
/// Average native samples within each thumbnail pixel's source rectangle. Use wide sums
/// because a large reduction can overflow the image crate's U16 thumbnail accumulator.
fn thumbnail_u16(img: &craft_image_codecs::Image, nw: u32, nh: u32) -> Option<craft_image_codecs::Image> {
@@ -194,14 +217,6 @@ fn thumbnail_u16(img: &craft_image_codecs::Image, nw: u32, nh: u32) -> Option<cr
let rows = img.data().chunks_exact(row_bytes);
let x_ratio = w as f32 / nw as f32;
let y_ratio = h as f32 / nh as f32;
// Keep the old thumbnail's floating-point box boundaries. Every axis scales down, so
// a rounding edge case still needs at least one source sample.
let source_span = |index: u32, input: u32, ratio: f32| {
let offset = index as f32 * ratio;
let start = (offset.ceil() as u32).min(input - 1);
let end = ((offset + ratio).ceil() as u32).clamp(start + 1, input);
start as usize..end as usize
};
for y in 0..nh {
let y_span = source_span(y, h, y_ratio);
let band = rows.clone().skip(y_span.start).take(y_span.len());
@@ -226,6 +241,44 @@ fn thumbnail_u16(img: &craft_image_codecs::Image, nw: u32, nh: u32) -> Option<cr
craft_image_codecs::Image::from_raw(nw, nh, layout, SampleType::U16, data).ok()
}
/// Average native `f32` samples within each thumbnail pixel's source rectangle before
/// quantizing to 8-bit.
fn thumbnail_f32(img: &craft_image_codecs::Image, nw: u32, nh: u32) -> Option<craft_image_codecs::Image> {
let (w, h) = img.dimensions();
let layout = img.layout();
let channels = layout.channels();
let pixel_bytes = channels * 4;
let row_bytes = (w as usize).checked_mul(pixel_bytes)?;
let output_bytes = (nw as usize).checked_mul(nh as usize)?.checked_mul(pixel_bytes)?;
let mut data = Vec::new();
data.try_reserve_exact(output_bytes).ok()?;
let rows = img.data().chunks_exact(row_bytes);
let x_ratio = w as f32 / nw as f32;
let y_ratio = h as f32 / nh as f32;
for y in 0..nh {
let y_span = source_span(y, h, y_ratio);
let band = rows.clone().skip(y_span.start).take(y_span.len());
for x in 0..nw {
let x_span = source_span(x, w, x_ratio);
let bytes = x_span.start * pixel_bytes..x_span.end * pixel_bytes;
let count = (x_span.len() * y_span.len()) as f64;
let mut sums = [0.0_f64; 4];
for row in band.clone() {
for pixel in row.get(bytes.clone())?.chunks_exact(pixel_bytes) {
for (sum, sample) in sums.iter_mut().zip(pixel.as_chunks::<4>().0) {
*sum += f64::from(f32::from_ne_bytes(*sample));
}
}
}
for sum in sums.iter().take(channels) {
let sample = (sum / count) as f32;
data.extend_from_slice(&sample.to_ne_bytes());
}
}
}
craft_image_codecs::Image::from_raw(nw, nh, layout, SampleType::F32, data).ok()
}
/// Whether image `hash`, decoded as `pm`, has no transparent pixels (filters and colour profiles
/// keep alpha). Scanned once per image.
pub(crate) fn opaque(hash: &str, pm: &Pixmap) -> bool {
+59
View File
@@ -585,3 +585,62 @@ fn rect_clip_frame_matches_same_rect_fill_on_fractional_edges() {
}
}
}
#[test]
fn export_output_and_icc_parity() {
use figcraft_color::ColorProfile;
use figcraft_doc::ExportFormat;
use image::ImageDecoder;
let has_png_chunk = |bytes: &[u8], kind: &[u8; 4], payload: &[u8]| {
bytes.windows(4).enumerate().any(|(i, w)| w == kind && bytes.get(i + 4..i + 4 + payload.len()) == Some(payload))
};
let mut pix = Pixmap::new(8, 8).unwrap();
// Premultiplied 50% alpha: `(100*255+64)/128 = 199`, `(50*255+64)/128 = 100`, `(25*255+64)/128 = 50`.
let straight = [199u8, 100, 50, 128];
let pm = tiny_skia::PremultipliedColorU8::from_rgba(100, 50, 25, 128).unwrap();
pix.pixels_mut().fill(pm);
// Untagged PNG and WebP preserve alpha and carry no ICC profile.
let raw_png = encode_png(&pix).unwrap();
assert!(image::codecs::png::PngDecoder::new(std::io::Cursor::new(&raw_png)).unwrap().icc_profile().unwrap().is_none());
assert_eq!(image::load_from_memory(&raw_png).unwrap().to_rgba8().get_pixel(4, 4).0, straight);
let raw_webp = encode_webp(&pix).unwrap();
assert!(image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&raw_webp)).unwrap().icc_profile().unwrap().is_none());
assert_eq!(image::load_from_memory(&raw_webp).unwrap().to_rgba8().get_pixel(4, 4).0, straight);
// JPEG composites alpha over the given background and clamps quality to 1..=100.
let blue_bg = Color::from_hex("0000FF").unwrap();
let jpg_min = encode_jpeg(&pix, blue_bg, 0).unwrap();
assert_eq!(jpg_min, encode_jpeg(&pix, blue_bg, 1).unwrap());
let jpg_max = encode_jpeg(&pix, blue_bg, 200).unwrap();
assert_eq!(jpg_max, encode_jpeg(&pix, blue_bg, 100).unwrap());
let jpg_px = image::load_from_memory(&jpg_max).unwrap().to_rgb8().get_pixel(4, 4).0;
assert!(jpg_px[2] > 140 && jpg_px[0] > 80, "expected red+blue composite, got {jpg_px:?}");
for profile in ColorProfile::ALL {
let png = encode_export(&pix, ExportFormat::Png, profile).unwrap();
let png_icc = image::codecs::png::PngDecoder::new(std::io::Cursor::new(&png)).unwrap().icc_profile().unwrap();
if profile.is_srgb() {
assert_eq!(png_icc, None);
assert!(has_png_chunk(&png, b"sRGB", &[0]));
assert!(!has_png_chunk(&png, b"cICP", &[]));
} else {
assert_eq!(png_icc, Some(profile.icc()));
assert!(has_png_chunk(&png, b"cICP", &profile.cicp()));
assert!(!has_png_chunk(&png, b"sRGB", &[]));
}
assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(4, 4).0, straight);
let webp = encode_export(&pix, ExportFormat::Webp, profile).unwrap();
let webp_icc = image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&webp)).unwrap().icc_profile().unwrap();
assert_eq!(webp_icc, (!profile.is_srgb()).then(|| profile.icc()));
assert_eq!(image::load_from_memory(&webp).unwrap().to_rgba8().get_pixel(4, 4).0, straight);
let jpg = encode_export_with(&pix, ExportFormat::Jpg, profile, 90).unwrap();
let jpg_icc = image::codecs::jpeg::JpegDecoder::new(std::io::Cursor::new(&jpg)).unwrap().icc_profile().unwrap();
assert_eq!(jpg_icc, Some(profile.icc()));
}
}