render: use shared raster decoding and export (#2501)

* render: use shared raster decoding and export

* render: fix Cow<Image> ownership and run cargo fmt
This commit is contained in:
Dylan M. Taylor
2026-11-19 14:00:49 -05:00
committed by GitHub
parent b45255bb6f
commit 4e35fb9cea
6 changed files with 213 additions and 84 deletions
Generated
+80 -5
View File
@@ -1069,6 +1069,14 @@ dependencies = [
"rayon",
]
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"rayon",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
@@ -1152,6 +1160,15 @@ name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=453b0da782ccef39be9a6dac8d27c80b553ef1cc#453b0da782ccef39be9a6dac8d27c80b553ef1cc"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"gif",
"image",
]
[[package]]
name = "craft-i18n"
version = "0.1.0"
@@ -1180,10 +1197,37 @@ name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-dds",
"craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-metadata",
"craft-tiff",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"crc32fast",
"exr",
"flate2",
"half",
"hayro-jpeg2000",
"image",
"image-webp",
"jpeg-encoder",
"png",
"rayon",
"serde_json",
"thiserror 2.0.21",
"tiff",
"zune-core",
"zune-jpeg",
"zune-jpegxl",
]
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
"crc32fast",
"exr",
"flate2",
@@ -1210,6 +1254,14 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
@@ -1253,7 +1305,19 @@ source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c85293
dependencies = [
"brotli-decompressor",
"chrono",
"craft-tiff",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"brotli-decompressor",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
"quick-xml 0.41.0",
"serde",
]
@@ -1317,7 +1381,7 @@ name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-image-codecs",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"data-url",
"flate2",
@@ -1339,6 +1403,15 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -2312,6 +2385,8 @@ dependencies = [
name = "figcraft-render"
version = "0.18.1"
dependencies = [
"craft-gif",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
"crc32fast",
"figcraft-color",
"figcraft-doc",
+2
View File
@@ -69,6 +69,8 @@ craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782
craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["frames"] }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
+2
View File
@@ -16,6 +16,8 @@ figcraft-format = { workspace = true }
figcraft-text = { workspace = true }
figcraft-pathops = { workspace = true }
tiny-skia = { workspace = true }
craft-image-codecs = { workspace = true }
craft-gif = { workspace = true }
image = { workspace = true }
moxcms = { workspace = true }
png = { workspace = true }
+34 -7
View File
@@ -7,7 +7,7 @@
use std::io::Cursor;
use figcraft_color::ColorProfile;
use image::{DynamicImage, ImageDecoder, ImageFormat, RgbaImage};
use image::{ImageDecoder, ImageFormat};
use moxcms::{Chromaticity, ColorPrimaries, DataColorSpace, Layout, ParsingOptions, ProfileText, ToneReprCurve, TransformOptions, XyY};
/// The most bytes an embedded profile may have; bigger ones are ignored.
@@ -55,16 +55,43 @@ impl Source {
}
}
/// `img` (decoded from this source) converted into `target`; `None` when it's taken as sRGB.
pub(crate) fn convert(&self, img: &DynamicImage, target: ColorProfile) -> Option<RgbaImage> {
/// The colour space of `bytes` given the ICC profile returned by `craft-image-codecs`.
/// shortcut: GIF and BMP profiles and a PNG `cICP` without `iCCP` are ignored (taken as sRGB);
/// read them if such files turn up.
pub(crate) fn from_decoded(bytes: &[u8], icc: Option<&[u8]>) -> Source {
let Some(format) = craft_image_codecs::detect(bytes) else {
return Source::default();
};
if !matches!(
format,
craft_image_codecs::Format::Png | craft_image_codecs::Format::Jpeg | craft_image_codecs::Format::WebP | craft_image_codecs::Format::Tiff
) {
return Source::default();
}
match icc {
Some(icc) => from_icc(icc),
None if format == craft_image_codecs::Format::Png => png_chunks(bytes),
None => Source::default(),
}
}
/// Whether this source uses a greyscale ICC profile.
pub(crate) fn is_gray(&self) -> bool {
self.profile.as_ref().is_some_and(|p| p.color_space == DataColorSpace::Gray)
}
/// `pixels` (8-bit `GrayAlpha` when `is_gray`, else `Rgba`) converted into `target`; `None`
/// when it's taken as sRGB.
pub(crate) fn convert_u8(&self, w: u32, h: u32, is_gray: bool, pixels: &[u8], target: ColorProfile) -> Option<Vec<u8>> {
let src = self.profile.as_ref()?;
let grey = src.color_space == DataColorSpace::Gray;
if grey && img.color().has_color() {
if grey && !is_gray {
return None;
}
let (layout, pixels) = if grey { (Layout::GrayAlpha, img.to_luma_alpha8().into_raw()) } else { (Layout::Rgba, img.to_rgba8().into_raw()) };
let mut out = RgbaImage::new(img.width(), img.height());
src.create_transform_8bit(layout, &working(target), Layout::Rgba, TransformOptions::default()).ok()?.transform(&pixels, &mut out).ok()?;
let layout = if grey { Layout::GrayAlpha } else { Layout::Rgba };
let len = usize::try_from(w).ok()?.checked_mul(usize::try_from(h).ok()?)?.checked_mul(4)?;
let mut out = vec![0u8; len];
src.create_transform_8bit(layout, &working(target), Layout::Rgba, TransformOptions::default()).ok()?.transform(pixels, &mut out).ok()?;
Some(out)
}
}
+48 -45
View File
@@ -117,27 +117,45 @@ fn decode_in(bytes: &[u8], target: ColorProfile) -> Option<(Pixmap, bool)> {
/// from their header, before any pixels are decoded), scaled down to at most `max_side` wide and
/// tall.
pub(crate) fn decode_within(bytes: &[u8], target: ColorProfile, max_side: u32, max_bytes: u64) -> Option<(Pixmap, bool)> {
use image::ImageDecoder;
if figcraft_format::jpeg::finer_than_first(bytes) {
return None;
}
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(max_bytes);
reader.limits(limits);
let mut dec = reader.into_decoder().ok()?;
if dec.total_bytes() > max_bytes {
let opts =
craft_image_codecs::DecodeOptions { limits: craft_image_codecs::Limits::new(u32::MAX, u32::MAX, u64::MAX, max_bytes), ..Default::default() };
let img = craft_image_codecs::decode_with(bytes, &opts).ok()?;
let source = crate::image_profile::Source::from_decoded(bytes, img.icc.as_deref());
let is_gray = source.is_gray() && img.layout().is_gray();
let layout = if is_gray { craft_image_codecs::ChannelLayout::GrayA } else { craft_image_codecs::ChannelLayout::Rgba };
let converted = img.converted(layout, craft_image_codecs::SampleType::U8);
let (w, h, pixels) = thumbnail_u8(converted.width(), converted.height(), max_side, 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));
}
match source.convert_u8(w, h, false, &pixels, target) {
Some(rgba) => Some((premultiplied_rgba(w, h, &rgba)?, false)),
None => Some((premultiplied_rgba(w, h, &pixels)?, true)),
}
}
/// Scale `pixels` (`GrayA` when `is_gray`, else `Rgba`) down to fit within `max_side` per side,
/// keeping aspect ratio.
fn thumbnail_u8(w: u32, h: u32, max_side: u32, is_gray: bool, pixels: Vec<u8>) -> Option<(u32, u32, Vec<u8>)> {
if w == 0 || h == 0 {
return None;
}
let source = crate::image_profile::Source::read(bytes, &mut dec);
let mut img = image::DynamicImage::from_decoder(dec).ok()?;
if img.width() > max_side || img.height() > max_side {
// `thumbnail` keeps the aspect ratio and works in integers (no float copy of the pixels).
img = img.thumbnail(max_side, max_side);
if w <= max_side && h <= max_side {
return Some((w, h, pixels));
}
match source.convert(&img, target) {
Some(rgba) => Some((premultiplied(&rgba)?, false)),
None => Some((premultiplied(&img.to_rgba8())?, true)),
let ratio = (f64::from(max_side) / f64::from(w)).min(f64::from(max_side) / f64::from(h));
let nw = (f64::from(w) * ratio).round().max(1.0) as u32;
let nh = (f64::from(h) * ratio).round().max(1.0) as u32;
if is_gray {
let buf = image::ImageBuffer::<image::LumaA<u8>, _>::from_raw(w, h, pixels)?;
Some((nw, nh, image::imageops::thumbnail(&buf, nw, nh).into_raw()))
} else {
let buf = image::RgbaImage::from_raw(w, h, pixels)?;
Some((nw, nh, image::imageops::thumbnail(&buf, nw, nh).into_raw()))
}
}
@@ -178,14 +196,13 @@ pub fn profile_name(hash: &str, data: Option<&ImageData>) -> Option<String> {
name
}
/// Straight RGBA → a premultiplied pixmap (max 16k per side).
fn premultiplied(rgba: &image::RgbaImage) -> Option<Pixmap> {
let (w, h) = rgba.dimensions();
/// Straight RGBA8 → a premultiplied pixmap (max 16k per side).
fn premultiplied_rgba(w: u32, h: u32, rgba: &[u8]) -> Option<Pixmap> {
if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE {
return None;
}
let mut p = Pixmap::new(w, h)?;
for (dst, src) in p.data_mut().as_chunks_mut::<4>().0.iter_mut().zip(rgba.as_raw().chunks_exact(4)) {
for (dst, src) in p.data_mut().as_chunks_mut::<4>().0.iter_mut().zip(rgba.chunks_exact(4)) {
let a = u32::from(src.get(3).copied().unwrap_or(255));
let pm = |c: u8| ((u32::from(c) * a + 127) / 255) as u8;
dst.copy_from_slice(&[
@@ -289,33 +306,20 @@ pub fn frame_secs(numer: u32, denom: u32) -> f64 {
/// big for one frame within [`MAX_ANIMATION_BYTES`]. A damaged frame ends the animation there.
/// shortcut: GIFs always loop (their repeat count is ignored); read it if a one-shot GIF matters.
pub fn decode_frames(bytes: &[u8]) -> Option<Vec<(Pixmap, f64)>> {
use image::{AnimationDecoder, ImageDecoder};
if image::guess_format(bytes).ok()? != image::ImageFormat::Gif {
let mut limits = craft_gif::frames::FrameLimits::default();
limits.max_frames = MAX_FRAMES;
limits.max_bytes = MAX_ANIMATION_BYTES;
limits.max_canvas_bytes = MAX_ANIMATION_BYTES;
let anim = craft_gif::frames::read_frames(bytes, &limits).ok()?;
if anim.frames.len() <= 1 || anim.width > MAX_SIDE || anim.height > MAX_SIDE {
return None;
}
let mut dec = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(bytes)).ok()?;
let (w, h) = dec.dimensions();
let frame_bytes = u64::from(w) * u64::from(h) * 4;
if frame_bytes == 0 || w > MAX_SIDE || h > MAX_SIDE {
return None;
let mut out = Vec::with_capacity(anim.frames.len());
for f in anim.frames {
let pm = premultiplied_rgba(anim.width, anim.height, &f.rgba)?;
out.push((pm, frame_secs(f.delay_ms, 1)));
}
// A frame's own descriptor can ask for a far larger buffer than the canvas: the decoder
// reserves each frame and canvas buffer against these limits before allocating it.
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_SIDE);
limits.max_image_height = Some(MAX_SIDE);
// The decoder charges its canvas, its composited output and the partial frame against this
// together, besides the frames kept (capped by `most` below): one frame of working room.
limits.max_alloc = Some(MAX_ANIMATION_BYTES.saturating_add(frame_bytes));
dec.set_limits(limits).ok()?;
let most = (MAX_ANIMATION_BYTES / frame_bytes).min(MAX_FRAMES as u64) as usize;
let mut out = Vec::new();
for f in dec.into_frames().take(most) {
let Ok(f) = f else { break };
let (n, d) = f.delay().numer_denom_ms();
out.push((premultiplied(f.buffer())?, frame_secs(n, d)));
}
(out.len() > 1).then_some(out)
Some(out)
}
type AnimKey = (String, [i32; 7], ColorProfile);
@@ -432,8 +436,7 @@ pub fn apply_filters(p: &mut Pixmap, f: &ImageFilters) {
/// Read an image's pixel size without keeping the decode.
pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
let reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
reader.into_dimensions().ok()
craft_image_codecs::probe_size(bytes).ok()
}
/// `pm` with a transparent 1-pixel border.
+47 -27
View File
@@ -490,25 +490,35 @@ pub fn to_srgb(pix: &mut Pixmap, profile: ColorProfile) {
profile.conversion_to(ColorProfile::Srgb).apply_pixels(pix.data_mut());
}
/// Write `pixels` with `enc`, embedding `icc` when given.
fn write_encoded(
mut enc: impl image::ImageEncoder,
pixels: &[u8],
p: &Pixmap,
kind: image::ExtendedColorType,
icc: Option<Vec<u8>>,
) -> Result<(), String> {
if let Some(icc) = icc {
enc.set_icc_profile(icc).map_err(|e| e.to_string())?;
}
enc.write_image(pixels, p.width(), p.height(), kind).map_err(|e| e.to_string())
/// Encode `img` with `craft_image_codecs` into `format`.
fn encode_with_codec(
img: &craft_image_codecs::Image,
format: craft_image_codecs::Format,
opts: &craft_image_codecs::EncodeOptions,
) -> Result<Vec<u8>, String> {
craft_image_codecs::encode(img, format, opts).map_err(|e| e.to_string())
}
/// Encode as PNG, with an `iCCP` chunk when `icc` is given.
fn png_with(p: &Pixmap, icc: Option<Vec<u8>>) -> Result<Vec<u8>, String> {
let mut out = Vec::new();
write_encoded(image::codecs::png::PngEncoder::new(&mut out), &to_rgba8(p), p, image::ExtendedColorType::Rgba8, icc)?;
Ok(out)
/// Build a `craft_image_codecs::Image` from straight RGBA8 or RGB8 bytes.
fn codec_image(
p: &Pixmap,
layout: craft_image_codecs::ChannelLayout,
data: Vec<u8>,
icc: Option<Vec<u8>>,
cicp: Option<craft_image_codecs::Cicp>,
) -> Result<craft_image_codecs::Image, String> {
let mut img = craft_image_codecs::Image::from_u8(p.width(), p.height(), layout, data).map_err(|e| e.to_string())?;
img.icc = icc;
img.cicp = cicp;
Ok(img)
}
/// Encode as PNG, with an `iCCP` chunk (and optional `cICP` chunk) when given.
fn png_with(p: &Pixmap, icc: Option<Vec<u8>>, cicp: Option<craft_image_codecs::Cicp>) -> Result<Vec<u8>, String> {
let embed_icc = icc.is_some();
let img = codec_image(p, craft_image_codecs::ChannelLayout::Rgba, to_rgba8(p), icc, cicp)?;
let opts = craft_image_codecs::EncodeOptions { embed_icc, embed_metadata: false, ..Default::default() };
encode_with_codec(&img, craft_image_codecs::Format::Png, &opts)
}
/// Encode as JPEG over `background` (JPEG has no alpha), with an ICC profile when given.
@@ -524,22 +534,23 @@ fn jpeg_with(p: &Pixmap, background: Color, quality: u8, icc: Option<Vec<u8>>) -
rgb.push(((s * a + b * (255 - a) + 127) / 255) as u8);
}
}
let mut out = Vec::new();
let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100));
write_encoded(enc, &rgb, p, image::ExtendedColorType::Rgb8, icc)?;
Ok(out)
let embed_icc = icc.is_some();
let img = codec_image(p, craft_image_codecs::ChannelLayout::Rgb, rgb, icc, None)?;
let opts = craft_image_codecs::EncodeOptions { jpeg_quality: quality.clamp(1, 100), embed_icc, embed_metadata: false, ..Default::default() };
encode_with_codec(&img, craft_image_codecs::Format::Jpeg, &opts)
}
/// Encode as lossless WebP, with an ICC profile when given.
fn webp_with(p: &Pixmap, icc: Option<Vec<u8>>) -> Result<Vec<u8>, String> {
let mut out = Vec::new();
write_encoded(image::codecs::webp::WebPEncoder::new_lossless(&mut out), &to_rgba8(p), p, image::ExtendedColorType::Rgba8, icc)?;
Ok(out)
let embed_icc = icc.is_some();
let img = codec_image(p, craft_image_codecs::ChannelLayout::Rgba, to_rgba8(p), icc, None)?;
let opts = craft_image_codecs::EncodeOptions { webp_lossless: true, embed_icc, embed_metadata: false, ..Default::default() };
encode_with_codec(&img, craft_image_codecs::Format::WebP, &opts)
}
/// Encode as PNG (untagged).
pub fn encode_png(p: &Pixmap) -> Result<Vec<u8>, String> {
png_with(p, None)
png_with(p, None, None)
}
/// Encode as JPEG over `background` (JPEG has no alpha).
@@ -566,8 +577,17 @@ pub fn encode_export_with(p: &Pixmap, format: ExportFormat, profile: ColorProfil
let icc = (!profile.is_srgb()).then(|| profile.icc());
match format {
ExportFormat::Png => {
let png = png_with(p, icc)?;
Ok(if profile.is_srgb() { png_insert_chunk(png, b"sRGB", &[0]) } else { png_insert_chunk(png, b"cICP", &profile.cicp()) })
let cicp = (!profile.is_srgb()).then(|| {
let [primaries, transfer, matrix, full_range] = profile.cicp();
craft_image_codecs::Cicp {
primaries: u16::from(primaries),
transfer: u16::from(transfer),
matrix: u16::from(matrix),
full_range: full_range != 0,
}
});
let png = png_with(p, icc, cicp)?;
Ok(if profile.is_srgb() { png_insert_chunk(png, b"sRGB", &[0]) } else { png })
}
ExportFormat::Jpg => jpeg_with(p, Color::WHITE, quality, Some(profile.icc())),
ExportFormat::Webp => webp_with(p, icc),