From 98bcbfab9005b4915b3143b4daed91df365db107 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Thu, 5 Nov 2026 15:03:29 +0530 Subject: [PATCH] perf(io): build JPEG/PNG tiles straight from the decoded rows, in parallel (#10259) (#10281) * perf(io): build JPEG/PNG tiles straight from the decoded rows, in parallel (#10259) Surface::try_write_rows_with fills tiles row by row on all cores; image_surface converts from the borrowed decoded rows into it (no per-band copy, no staging Image). Opaque sources skip the prune scan. import_flat_with checks cancel after the decode and the tile build and reports progress. * fix(io): store an F16 target as F32 so its opaque alpha is 1.0 An image without alpha converted to an F16 target got the alpha 0.0: the opaque-alpha path copied two bytes of 1.0f32. The surface keeps 16-bit float as 32-bit float anyway, so image_surface now converts an F16 target to F32. * Format fused tile import integration * Route default flat imports through interrupt wrapper * Remove unused flat import cancellation wrapper * Exercise options import API in cancellation tests * Stop flat image tile construction on cancellation --------- Co-authored-by: FredApps --- crates/codecs/src/image.rs | 181 +++++++++++-------- crates/codecs/src/lib.rs | 2 +- crates/io/src/flat.rs | 357 ++++++++++++++++++++++++++++++++++--- crates/raster/src/lib.rs | 134 ++++++++++++++ crates/raster/src/tests.rs | 121 +++++++++++++ 5 files changed, 699 insertions(+), 96 deletions(-) diff --git a/crates/codecs/src/image.rs b/crates/codecs/src/image.rs index aba9e3b2f0..d17182bdcc 100644 --- a/crates/codecs/src/image.rs +++ b/crates/codecs/src/image.rs @@ -656,31 +656,7 @@ impl Image { if layout == self.layout && sample == self.sample { return self.clone(); } - let data = if sample == self.sample && !self.layout.has_alpha() && layout == self.layout.with_alpha() { - // Fast path (opening any opaque file): copy the samples, append an opaque alpha. - let bps = sample.bytes(); - let src = self.layout.channels() * bps; - let one: Vec = match sample { - SampleType::U8 => vec![u8::MAX], - SampleType::U16 => u16::MAX.to_ne_bytes().to_vec(), - SampleType::F16 => f16::ONE.to_bits().to_ne_bytes().to_vec(), - SampleType::F32 => 1.0f32.to_ne_bytes().to_vec(), - }; - let mut out = Vec::with_capacity(self.data.len() / src * (src + bps)); - for px in self.data.chunks_exact(src) { - out.extend_from_slice(px); - out.extend_from_slice(&one); - } - out - } else if let Some(fast) = self.convert_int_direct(layout, sample) { - fast - } else if layout == self.layout { - quantize(&self.to_normalized(), sample) - } else { - let src = self.to_normalized(); - let values = convert_layout(&src, self.layout, layout); - quantize(&values, sample) - }; + let data = convert_data(&self.data, self.layout, self.sample, layout, sample); let mut meta = self.meta.clone(); if sample != self.sample { // Extra samples are stored in the image's sample type, so they convert with it. A @@ -705,55 +681,6 @@ impl Image { } } - /// Integer fast path of [`Image::convert`] for U8/U16 sources and targets whose result is - /// a pure channel copy: same colour model (alpha added as opaque, or dropped) or gray to - /// RGB. Bit-identical to the generic f32 route (see the equivalence tests) but without - /// the two intermediate f32 buffers. Returns `None` for everything else. - fn convert_int_direct(&self, layout: ChannelLayout, sample: SampleType) -> Option> { - let int = |s: SampleType| matches!(s, SampleType::U8 | SampleType::U16); - if !int(self.sample) || !int(sample) { - return None; - } - let gray_to_rgb = self.layout.is_gray() && layout.is_rgb(); - if !gray_to_rgb && !layout.same_model(self.layout) { - return None; - } - let one: &[u8] = match sample { - SampleType::U8 => &[u8::MAX], - _ => &u16::MAX.to_ne_bytes(), - }; - let (fc, tc) = (self.layout.channels(), layout.channels()); - let (sb, db) = (self.sample.bytes(), sample.bytes()); - let (src_color, dst_color) = (self.layout.color_channels(), layout.color_channels()); - let n = self.data.len() / (fc * sb); - let mut out = Vec::with_capacity(n.checked_mul(tc)?.checked_mul(db)?); - macro_rules! run { - ($conv:expr) => {{ - let conv = $conv; - for px in self.data.chunks_exact(fc * sb) { - for j in 0..dst_color { - let c = if src_color == 1 { 0 } else { j }; - conv(&px[c * sb..(c + 1) * sb], &mut out); - } - if layout.has_alpha() { - if self.layout.has_alpha() { - conv(&px[src_color * sb..(src_color + 1) * sb], &mut out); - } else { - out.extend_from_slice(one); - } - } - } - }}; - } - match (self.sample, sample) { - (SampleType::U8, SampleType::U8) => run!(|s: &[u8], o: &mut Vec| o.push(s[0])), - (SampleType::U16, SampleType::U16) => run!(|s: &[u8], o: &mut Vec| o.extend_from_slice(s)), - (SampleType::U8, SampleType::U16) => run!(|s: &[u8], o: &mut Vec| o.extend_from_slice(&(u16::from(s[0]) * 257).to_ne_bytes())), - _ => run!(|s: &[u8], o: &mut Vec| o.push(((u32::from(u16::from_ne_bytes([s[0], s[1]])) + 128) / 257) as u8)), - } - Some(out) - } - /// [`Image::convert`], borrowing `self` when it already has that layout and sample type /// (encoders use it so a full-size image isn't copied for nothing). pub fn converted(&self, layout: ChannelLayout, sample: SampleType) -> std::borrow::Cow<'_, Image> { @@ -776,6 +703,98 @@ impl Image { } } +/// The samples of `data` (`from` layout and sample type) in the `layout` and `sample` type: the +/// arithmetic of [`Image::convert`], on borrowed bytes. +fn convert_data(data: &[u8], from: ChannelLayout, from_sample: SampleType, layout: ChannelLayout, sample: SampleType) -> Vec { + if layout == from && sample == from_sample { + data.to_vec() + } else if sample == from_sample && !from.has_alpha() && layout == from.with_alpha() { + // Fast path (opening any opaque file): copy the samples, append an opaque alpha. + let bps = sample.bytes(); + let src = from.channels() * bps; + let one: Vec = match sample { + SampleType::U8 => vec![u8::MAX], + SampleType::U16 => u16::MAX.to_ne_bytes().to_vec(), + SampleType::F16 => f16::ONE.to_bits().to_ne_bytes().to_vec(), + SampleType::F32 => 1.0f32.to_ne_bytes().to_vec(), + }; + let mut out = Vec::with_capacity(data.len() / src * (src + bps)); + for px in data.chunks_exact(src) { + out.extend_from_slice(px); + out.extend_from_slice(&one); + } + out + } else if let Some(fast) = convert_int_direct(data, from, from_sample, layout, sample) { + fast + } else if layout == from { + quantize(&to_normalized(data, from_sample), sample) + } else { + let src = to_normalized(data, from_sample); + let values = convert_layout(&src, from, layout); + quantize(&values, sample) + } +} + +/// [`Image::convert`] on borrowed pixels: `rows` rows of `width` pixels in `from` (layout, sample +/// type) become the same pixels in `to`, bit for bit what the image conversion gives. Lets a +/// caller convert a band of a decoded image without copying it into an [`Image`] first. +pub fn convert_samples(src: &[u8], width: u32, rows: u32, from: (ChannelLayout, SampleType), to: (ChannelLayout, SampleType)) -> Result, CodecError> { + let expected = byte_len(width, rows, from.0, from.1).ok_or_else(|| CodecError::InvalidImage("image size overflows usize".into()))?; + if src.len() != expected { + return Err(CodecError::InvalidImage(format!("buffer has {} bytes, expected {expected} for {width}x{rows} {:?} {:?}", src.len(), from.0, from.1))); + } + Ok(convert_data(src, from.0, from.1, to.0, to.1)) +} + +/// Integer fast path of [`Image::convert`] for U8/U16 sources and targets whose result is +/// a pure channel copy: same colour model (alpha added as opaque, or dropped) or gray to +/// RGB. Bit-identical to the generic f32 route (see the equivalence tests) but without +/// the two intermediate f32 buffers. Returns `None` for everything else. +fn convert_int_direct(data: &[u8], from: ChannelLayout, from_sample: SampleType, layout: ChannelLayout, sample: SampleType) -> Option> { + let int = |s: SampleType| matches!(s, SampleType::U8 | SampleType::U16); + if !int(from_sample) || !int(sample) { + return None; + } + let gray_to_rgb = from.is_gray() && layout.is_rgb(); + if !gray_to_rgb && !layout.same_model(from) { + return None; + } + let one: &[u8] = match sample { + SampleType::U8 => &[u8::MAX], + _ => &u16::MAX.to_ne_bytes(), + }; + let (fc, tc) = (from.channels(), layout.channels()); + let (sb, db) = (from_sample.bytes(), sample.bytes()); + let (src_color, dst_color) = (from.color_channels(), layout.color_channels()); + let n = data.len() / (fc * sb); + let mut out = Vec::with_capacity(n.checked_mul(tc)?.checked_mul(db)?); + macro_rules! run { + ($conv:expr) => {{ + let conv = $conv; + for px in data.chunks_exact(fc * sb) { + for j in 0..dst_color { + let c = if src_color == 1 { 0 } else { j }; + conv(&px[c * sb..(c + 1) * sb], &mut out); + } + if layout.has_alpha() { + if from.has_alpha() { + conv(&px[src_color * sb..(src_color + 1) * sb], &mut out); + } else { + out.extend_from_slice(one); + } + } + } + }}; + } + match (from_sample, sample) { + (SampleType::U8, SampleType::U8) => run!(|s: &[u8], o: &mut Vec| o.push(s[0])), + (SampleType::U16, SampleType::U16) => run!(|s: &[u8], o: &mut Vec| o.extend_from_slice(s)), + (SampleType::U8, SampleType::U16) => run!(|s: &[u8], o: &mut Vec| o.extend_from_slice(&(u16::from(s[0]) * 257).to_ne_bytes())), + _ => run!(|s: &[u8], o: &mut Vec| o.push(((u32::from(u16::from_ne_bytes([s[0], s[1]])) + 128) / 257) as u8)), + } + Some(out) +} + // --------------------------------------------------------------------------- // Sample conversion helpers // --------------------------------------------------------------------------- @@ -886,6 +905,20 @@ mod tests { use super::*; + #[test] + fn convert_samples_matches_image_convert_and_rejects_a_wrong_length() { + for sample in SampleType::ALL { + let vals: Vec = (0..5 * 2 * 3).map(|i| (i as f32 * 0.31) % 1.0).collect(); + let img = Image::from_normalized(5, 2, ChannelLayout::Rgb, sample, &vals).unwrap(); + for (layout, to) in [(ChannelLayout::Rgba, sample), (ChannelLayout::Gray, SampleType::F32), (ChannelLayout::Rgb, SampleType::U8)] { + let want = img.convert(layout, to); + let got = convert_samples(img.data(), 5, 2, (ChannelLayout::Rgb, sample), (layout, to)).unwrap(); + assert_eq!(got, want.data(), "{sample:?} to {layout:?} {to:?}"); + } + assert!(convert_samples(img.data().get(1..).unwrap_or_default(), 5, 2, (ChannelLayout::Rgb, sample), (ChannelLayout::Rgba, sample)).is_err()); + } + } + /// The generic f32 route `convert` used before the integer fast paths (the reference). fn convert_via_f32(img: &Image, layout: ChannelLayout, sample: SampleType) -> Vec { quantize(&convert_layout(&img.to_normalized(), img.layout, layout), sample) diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index ec9f0995de..7aa48dfbc7 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -42,7 +42,7 @@ pub use crate::fidelity::{FidelityWarning, fidelity_warnings, fidelity_warnings_ pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Format, FormatCaps, caps, detect, from_extension}; pub use crate::image::{ ChannelLayout, CryptomatteBuffer, CryptomatteLayer, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, ExtraSample, Image, - MAX_EXTRA_SAMPLES, Metadata, SampleType, + MAX_EXTRA_SAMPLES, Metadata, SampleType, convert_samples, }; pub use crate::options::{ DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, JpegFormat, Limits, PngCompression, PngStereo, TIFF_PYRAMID_MIN, diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 3d3f95b30b..505c07b92c 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -6,7 +6,7 @@ use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{AlphaChannel, Document, Layer, LayerContent}; use photocraft_geom::{Rect, Size, TILE_SIZE}; -use photocraft_raster::{Interrupt, Surface}; +use photocraft_raster::{AllocationError, Interrupt, RowWriteError, Surface}; use crate::renderer::{BandRenderer, RenderError}; use crate::{ExportOptions, ExportResult, ImportResult, IoError, TgaBits, XmpEmbed}; @@ -91,7 +91,9 @@ pub(crate) fn import_flat_with_options( Some(Format::Gif) => codecs::gif_palette(bytes), _ => None, }; - let mut r = image_to_document(name, &img)?; + ctl.check().map_err(|_| IoError::Cancelled)?; + ctl.progress(0.6); + let mut r = image_to_document_with(name, &img, ctl)?; if let Some((colors, transparent)) = palette.filter(|(c, _)| !c.is_empty()) && r.document.mode == ColorMode::Rgb { @@ -573,12 +575,21 @@ fn document_format(layout: ChannelLayout, sample: CSample) -> DocumentFormat { /// A decoded flat image as a single-layer document: a locked "Background" when it is opaque, a /// normal "Layer 0" when it has transparency. pub(crate) fn image_to_document(name: &str, img: &Image) -> Result { + image_to_document_with(name, img, &Interrupt::NONE) +} + +fn image_to_document_with(name: &str, img: &Image, ctl: &Interrupt) -> Result { // What the decoder noticed (frames or pages left out, data ending early) comes first. let mut warnings: Vec = img.warnings.iter().map(ToString::to_string).collect(); let f = document_format(img.layout(), img.sample_type()); warnings.extend(f.warning.clone()); - let mut s = image_surface(img, f.layout, f.sample)?; - s.prune(); + ctl.check().map_err(|_| IoError::Cancelled)?; + let mut s = image_surface_with(img, f.layout, f.sample, ctl)?; + ctl.check().map_err(|_| IoError::Cancelled)?; + ctl.progress(0.95); + if img.layout().has_alpha() { + s.prune(); + } let mut r = single_layer_document(name, img.dimensions(), f, img.layout().has_alpha(), s, img.icc.clone(), img.meta.clone(), warnings); r.warnings.extend(crate::tiff_layers::channels_from_extras(&mut r.document, img)); Ok(r) @@ -628,12 +639,19 @@ fn single_layer_document( /// The pixels of a decoded image as a surface of `fmt`, converting layout and sample type a /// band of rows at a time so no second full-size copy of the image is made. pub(crate) fn image_surface(img: &Image, target_layout: ChannelLayout, csample: CSample) -> Result { + image_surface_with(img, target_layout, csample, &Interrupt::NONE) +} + +fn image_surface_with(img: &Image, target_layout: ChannelLayout, csample: CSample, ctl: &Interrupt) -> Result { let mode = match target_layout { ChannelLayout::Gray | ChannelLayout::GrayA => ColorMode::Grayscale, ChannelLayout::Cmyk | ChannelLayout::CmykA => ColorMode::Cmyk, ChannelLayout::Lab | ChannelLayout::LabA => ColorMode::Lab, _ => ColorMode::Rgb, }; + // The surface stores 16-bit float as 32-bit float, so an F16 target converts to F32 (copying + // two-byte samples, or a two-byte opaque alpha, into it would be wrong). + let csample = if csample == CSample::F16 { CSample::F32 } else { csample }; let depth = match csample { CSample::U8 => SampleType::U8, CSample::U16 => SampleType::U16, @@ -642,28 +660,74 @@ pub(crate) fn image_surface(img: &Image, target_layout: ChannelLayout, csample: let fmt = PixelFormat::new(mode, depth, true); let (w, h) = img.dimensions(); let mut s = Surface::new(fmt); - if img.layout() == target_layout && img.sample_type() == csample { - s.write_interleaved(Rect::new(0, 0, w as i32, h as i32), img.data()); - } else { - let row = img.data().len() / (h.max(1) as usize); - let band = (BAND_BYTES / row.max(1)).max(1); - for (i, rows) in img.data().chunks(row.max(1) * band).enumerate() { - let n = (rows.len() / row.max(1)) as u32; - // Band buffers cycle through the scratch pool: at this size each fresh one is an - // mmap that gets page-faulted in. - let mut src = photocraft_raster::scratch::take_cap::(rows.len()); - src.extend_from_slice(rows); - let src = Image::from_raw(w, n, img.layout(), img.sample_type(), src)?; - let part = src.convert(target_layout, csample); - let y0 = (i * band) as i32; - s.write_interleaved(Rect::new(0, y0, w as i32, y0 + n as i32), part.data()); - photocraft_raster::scratch::give(src.into_data()); - photocraft_raster::scratch::give(part.into_data()); + let (from, to) = ((img.layout(), img.sample_type()), (target_layout, csample)); + let (sb, db) = (from.1.bytes(), to.1.bytes()); + let (src_px, dst_px) = (from.0.channels() * sb, to.0.channels() * db); + let data = img.data(); + // The opaque alpha an image without one gets, when only that differs. + let one: Option<([u8; 4], usize)> = (from.1 == to.1 && !from.0.has_alpha() && to.0 == from.0.with_alpha()).then(|| { + let mut one = [0u8; 4]; + match to.1 { + CSample::U8 => one[0] = u8::MAX, + CSample::U16 => one[..2].copy_from_slice(&u16::MAX.to_ne_bytes()), + _ => one.copy_from_slice(&1.0f32.to_ne_bytes()), } + (one, db) + }); + let failed = std::sync::atomic::AtomicBool::new(false); + let (Ok(cw), Ok(ch)) = (i32::try_from(w), i32::try_from(h)) else { return Err(IoError::Unsupported("image too large".into())) }; + let written = s.try_write_rows_with_interrupt(Rect::new(0, 0, cw, ch), ctl, |y, x0, dst| { + let n = dst.len() / dst_px.max(1); + let span = usize::try_from(y) + .ok() + .zip(usize::try_from(x0).ok()) + .and_then(|(y, x)| (y.checked_mul(w as usize)?.checked_add(x)?).checked_mul(src_px)) + .and_then(|o| data.get(o..o.checked_add(n.checked_mul(src_px)?)?)); + let Some(src) = span else { return failed.store(true, std::sync::atomic::Ordering::Relaxed) }; + if from == to { + dst.copy_from_slice(src); + } else if let Some((one, bytes)) = one { + if (src_px, bytes, one[0]) == (3, 1, u8::MAX) { + // RGB8 to RGBA8, what nearly every JPEG and many PNGs are. + for (d, p) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src.as_chunks::<3>().0) { + *d = [p[0], p[1], p[2], u8::MAX]; + } + } else { + for (d, p) in dst.chunks_exact_mut(dst_px).zip(src.chunks_exact(src_px)) { + if let Some((color, alpha)) = d.split_at_mut_checked(src_px) { + color.copy_from_slice(p); + alpha.copy_from_slice(one.get(..bytes).unwrap_or_default()); + } + } + } + } else { + // Everything else (16-bit float to 32-bit float): the codec's own conversion of this row span. + match codecs::convert_samples(src, n as u32, 1, from, to) { + Ok(out) if out.len() == dst.len() => dst.copy_from_slice(&out), + _ => failed.store(true, std::sync::atomic::Ordering::Relaxed), + } + } + }); + written.map_err(|error| match error { + RowWriteError::Allocation(error) => alloc_error(error), + RowWriteError::Cancelled(_) => IoError::Cancelled, + })?; + if failed.load(std::sync::atomic::Ordering::Relaxed) { + return Err(IoError::Unsupported("the decoded image does not match its size".into())); } Ok(s) } +/// The error an out-of-memory or oversized surface allocation is reported as. +fn alloc_error(e: AllocationError) -> IoError { + match e { + AllocationError::LengthMismatch { .. } => IoError::Unsupported("the decoded image does not match its size".into()), + AllocationError::SizeOverflow => IoError::Unsupported("image too large".into()), + AllocationError::NotEnoughMemory { .. } => IoError::OutOfMemory("opening this image".into()), + AllocationError::ScratchRead(error) => IoError::Unsupported(format!("could not read tile from scratch: {error}")), + } +} + /// `Some(surface)` when the document is exactly one visible, unmasked, /// normal, fully opaque raster layer: its pixels can be written natively /// (keeping CMYK / depth exactly) instead of going through the compositor. @@ -2224,3 +2288,254 @@ mod streamed_png_tests { }); } } + +#[cfg(test)] +mod fused_tile_tests { + use super::*; + use std::collections::BTreeMap; + use std::sync::atomic::{AtomicU32, Ordering}; + + /// The band-at-a-time conversion `image_surface` used before it wrote straight into the + /// tiles, kept as the oracle. `band_bytes` is [`BAND_BYTES`] in production; the test makes it + /// small so the bands are crossed at test sizes. + fn banded_surface(img: &Image, target_layout: ChannelLayout, csample: CSample, band_bytes: usize) -> Surface { + let mode = match target_layout { + ChannelLayout::Gray | ChannelLayout::GrayA => ColorMode::Grayscale, + ChannelLayout::Cmyk | ChannelLayout::CmykA => ColorMode::Cmyk, + ChannelLayout::Lab | ChannelLayout::LabA => ColorMode::Lab, + _ => ColorMode::Rgb, + }; + let depth = match csample { + CSample::U8 => SampleType::U8, + CSample::U16 => SampleType::U16, + _ => SampleType::F32, + }; + let (w, h) = img.dimensions(); + let mut s = Surface::new(PixelFormat::new(mode, depth, true)); + if img.layout() == target_layout && img.sample_type() == csample { + s.write_interleaved(Rect::new(0, 0, w as i32, h as i32), img.data()); + } else { + let row = img.data().len() / (h.max(1) as usize); + let band = (band_bytes / row.max(1)).max(1); + for (i, rows) in img.data().chunks(row.max(1) * band).enumerate() { + let n = (rows.len() / row.max(1)) as u32; + let part = Image::from_raw(w, n, img.layout(), img.sample_type(), rows.to_vec()).unwrap().convert(target_layout, csample); + let y0 = (i * band) as i32; + s.write_interleaved(Rect::new(0, y0, w as i32, y0 + n as i32), part.data()); + } + } + s + } + + /// Deterministic samples with the extremes (0, max, 1.0, negatives, out of range floats) mixed in. + fn sample_bytes(sample: CSample, n: usize) -> Vec { + let mut out = Vec::new(); + for i in 0..n { + let h = (i as u32).wrapping_mul(2_654_435_761) >> 7; + match sample { + CSample::U8 => out.push(match i % 11 { + 0 => 0, + 1 => u8::MAX, + _ => h as u8, + }), + CSample::U16 => out.extend_from_slice( + &(match i % 11 { + 0 => 0, + 1 => u16::MAX, + _ => h as u16, + }) + .to_ne_bytes(), + ), + CSample::F16 => out.extend_from_slice( + &(match i % 11 { + 0 => 0x0000, + 1 => 0x3c00, // 1.0 + 2 => 0xbc00, // -1.0 + 3 => 0x4000, // 2.0 + _ => (h as u16) & 0x7bff, + }) + .to_ne_bytes(), + ), + CSample::F32 => out.extend_from_slice( + &(match i % 11 { + 0 => 0.0, + 1 => 1.0, + 2 => -0.5, + 3 => 3.0, + _ => (h % 1024) as f32 / 1023.0, + }) + .to_ne_bytes(), + ), + } + } + out + } + + fn image(w: u32, h: u32, layout: ChannelLayout, sample: CSample) -> Image { + let n = w as usize * h as usize * layout.channels(); + Image::from_raw(w, h, layout, sample, sample_bytes(sample, n)).unwrap() + } + + fn target(layout: ChannelLayout, sample: CSample) -> (ChannelLayout, CSample) { + let layout = match layout { + ChannelLayout::Gray | ChannelLayout::GrayA => ChannelLayout::GrayA, + ChannelLayout::Rgb | ChannelLayout::Rgba => ChannelLayout::Rgba, + ChannelLayout::Cmyk | ChannelLayout::CmykA => ChannelLayout::CmykA, + ChannelLayout::Lab | ChannelLayout::LabA => ChannelLayout::LabA, + }; + (layout, if sample == CSample::F16 { CSample::F32 } else { sample }) + } + + fn assert_same(a: &Surface, b: &Surface, what: &str) { + assert_eq!(a.format(), b.format(), "{what}: format"); + assert_eq!(a.default_bytes(), b.default_bytes(), "{what}: default pixel"); + let tiles = |s: &Surface| s.tiles().map(|(c, t)| ((c.tx, c.ty), t.clone())).collect::>(); + let (ta, tb) = (tiles(a), tiles(b)); + assert_eq!(ta.keys().collect::>(), tb.keys().collect::>(), "{what}: tile set"); + assert!(ta == tb, "{what}: tile bytes"); + } + + #[test] + fn fused_write_equals_the_banded_conversion() { + let layouts = [ + ChannelLayout::Gray, + ChannelLayout::GrayA, + ChannelLayout::Rgb, + ChannelLayout::Rgba, + ChannelLayout::Cmyk, + ChannelLayout::CmykA, + ChannelLayout::Lab, + ChannelLayout::LabA, + ]; + let samples = [CSample::U8, CSample::U16, CSample::F16, CSample::F32]; + for &(w, h) in &[(1, 1), (1, 300), (255, 3), (257, 257), (513, 260)] { + for &layout in &layouts { + for &sample in &samples { + let img = image(w, h, layout, sample); + let (tl, ts) = target(layout, sample); + let fused = image_surface(&img, tl, ts).unwrap(); + // The band sizes: a band per row, a few rows, and the whole image. + for band in [1, 5000, BAND_BYTES] { + assert_same(&fused, &banded_surface(&img, tl, ts, band), &format!("{w}x{h} {layout:?} {sample:?} band {band}")); + } + } + } + } + } + + #[test] + fn allocation_failure_reports_out_of_memory() { + assert!(matches!(alloc_error(AllocationError::NotEnoughMemory { bytes: 1 }), IoError::OutOfMemory(_))); + } + + #[test] + fn an_f16_target_is_stored_as_f32_with_opaque_alpha() { + for &layout in &[ChannelLayout::Rgb, ChannelLayout::Rgba] { + for &sample in &[CSample::F16, CSample::F32] { + let img = image(257, 3, layout, sample); + let f16 = image_surface(&img, ChannelLayout::Rgba, CSample::F16).unwrap(); + let f32 = image_surface(&img, ChannelLayout::Rgba, CSample::F32).unwrap(); + assert_same(&f16, &f32, &format!("{layout:?} {sample:?} to an F16 target")); + } + } + let img = image(2, 2, ChannelLayout::Rgb, CSample::F32); + let s = image_surface(&img, ChannelLayout::Rgba, CSample::F16).unwrap(); + let (_, tile) = s.tiles().next().unwrap(); + let alpha = f32::from_ne_bytes(tile.bytes()[12..16].try_into().unwrap()); + assert_eq!(alpha, 1.0); + } + + #[test] + fn zero_sized_images_give_an_empty_surface() { + for &(w, h) in &[(0, 0), (0, 5), (5, 0)] { + let img = image(w, h, ChannelLayout::Rgb, CSample::U8); + let s = image_surface(&img, ChannelLayout::Rgba, CSample::U8).unwrap(); + assert_eq!(s.tile_count(), 0); + } + } + + fn pixels(w: u32, h: u32, alpha: bool) -> Image { + let layout = if alpha { ChannelLayout::Rgba } else { ChannelLayout::Rgb }; + let mut data = sample_bytes(CSample::U8, w as usize * h as usize * layout.channels()); + if alpha { + data.as_chunks_mut::<4>().0.iter_mut().enumerate().for_each(|(i, p)| p[3] = if i % 3 == 0 { 0 } else { 200 }); + } + Image::from_raw(w, h, layout, CSample::U8, data).unwrap() + } + + fn doc_pixels(r: &ImportResult) -> Vec { + let LayerContent::Raster(s) = &r.document.layers[0].content else { panic!("not a raster layer") }; + s.to_interleaved(r.document.bounds()) + } + + #[test] + fn opaque_and_alpha_files_open_as_background_and_layer_0() { + for format in [Format::Png, Format::Jpeg] { + for alpha in [false, true] { + if alpha && format == Format::Jpeg { + continue; + } + let img = pixels(300, 270, alpha); + let bytes = codecs::encode(&img, format, &codecs::EncodeOptions::default()).unwrap(); + let r = import_flat("t", &bytes).unwrap(); + let layer = &r.document.layers[0]; + assert_eq!(layer.name, if alpha { "Layer 0" } else { "Background" }, "{format:?}"); + assert_eq!(layer.locks.transparency, !alpha); + // The pixels are the decoded ones with an opaque alpha added. + let decoded = codecs::decode(&bytes).unwrap(); + let want = banded_surface(&decoded, ChannelLayout::Rgba, CSample::U8, BAND_BYTES).to_interleaved(r.document.bounds()); + assert_eq!(doc_pixels(&r), want, "{format:?} alpha {alpha}"); + if format == Format::Png && alpha { + assert_eq!(decoded.data(), img.data(), "lossless"); + } + } + } + } + + #[test] + fn a_cancelled_open_fails_with_cancelled() { + let img = pixels(64, 64, false); + let bytes = codecs::encode(&img, Format::Png, &codecs::EncodeOptions::default()).unwrap(); + let yes = || true; + let r = import_flat_with_options("t", &bytes, &crate::ImportOptions::default(), &Interrupt::cancel_only(&yes)); + assert!(matches!(r, Err(IoError::Cancelled)), "{:?}", r.map(|_| ())); + // Cancelled on a later poll, after the decode has run. + let calls = AtomicU32::new(0); + let after_decode = || calls.fetch_add(1, Ordering::Relaxed) >= 1; + let r = import_flat_with_options("t", &bytes, &crate::ImportOptions::default(), &Interrupt::cancel_only(&after_decode)); + assert!(matches!(r, Err(IoError::Cancelled)), "{:?}", r.map(|_| ())); + } + + #[test] + fn document_import_cancels_during_surface_construction() { + let img = pixels(64, 64, false); + let calls = AtomicU32::new(0); + // One document check, one tile check, then row checks. Cancel after two rows. + let cancel = || calls.fetch_add(1, Ordering::SeqCst) >= 4; + let result = image_to_document_with("t", &img, &Interrupt::cancel_only(&cancel)); + assert!(matches!(result, Err(IoError::Cancelled))); + assert_eq!(calls.load(Ordering::SeqCst), 5); + } + + #[test] + fn progress_is_reported_and_never_goes_backwards() { + let bytes = codecs::encode(&pixels(64, 64, false), Format::Png, &codecs::EncodeOptions::default()).unwrap(); + let seen = std::sync::Mutex::new(Vec::new()); + let no = || false; + let progress = |f: f32| seen.lock().unwrap().push(f); + import_flat_with_options("t", &bytes, &crate::ImportOptions::default(), &Interrupt::new(&no, &progress)).unwrap(); + let seen = seen.into_inner().unwrap(); + assert!(seen.len() >= 2 && seen.windows(2).all(|w| w[0] <= w[1]), "{seen:?}"); + } + + #[test] + fn truncated_files_still_fail_or_warn_without_panicking() { + let png = codecs::encode(&pixels(40, 40, false), Format::Png, &codecs::EncodeOptions::default()).unwrap(); + let jpeg = codecs::encode(&pixels(40, 40, false), Format::Jpeg, &codecs::EncodeOptions::default()).unwrap(); + assert!(import_flat("t", png.get(..20).unwrap_or_default()).is_err(), "header-only PNG"); + assert!(import_flat("t", jpeg.get(..8).unwrap_or_default()).is_err(), "short JPEG"); + for cut in [png.len() / 2, png.len() - 5] { + let _ = import_flat("t", png.get(..cut).unwrap_or_default()); + } + } +} diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 77121d0e7d..01b8c7d504 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -46,6 +46,30 @@ impl fmt::Display for AllocationError { } impl std::error::Error for AllocationError {} + +/// Failure to prepare an interruptible row write. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RowWriteError { + Allocation(AllocationError), + Cancelled(Cancelled), +} + +impl From for RowWriteError { + fn from(error: AllocationError) -> Self { + Self::Allocation(error) + } +} + +impl fmt::Display for RowWriteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Allocation(error) => write!(f, "{error}"), + Self::Cancelled(error) => write!(f, "{error}"), + } + } +} + +impl std::error::Error for RowWriteError {} pub mod memory; mod scratch_file; pub mod spill; @@ -400,6 +424,61 @@ fn copy_tiles(tiles: &mut [(TileCoord, Arc)], r: Rect, bytes: &[u8], w: us tiles.iter_mut().try_for_each(|(tc, t)| copy_tile(*tc, t, r, bytes, w, bpp)) } +/// Fills one tile of [`Surface::try_write_rows_with`]: makes it writable, then calls `fill` for +/// each row of `r` inside it. +fn fill_tile(slot: &mut (TileCoord, Option>), r: Rect, format: &PixelFormat, default_pixel: &[u8], fill: &F, check: &C) -> Result<(), E> +where + F: Fn(i32, i32, &mut [u8]) + Sync, + C: Fn() -> Result<(), E> + Sync, + E: From + Send, +{ + check()?; + let (tc, tile) = slot; + match tile { + None => *tile = Some(Arc::new(Tile::try_filled(format, default_pixel)?)), + Some(t) => { + if Arc::get_mut(t).is_none() { + *t = Arc::new(t.try_clone()?); + } + } + } + let data = tile.as_mut().and_then(Arc::get_mut).ok_or(AllocationError::SizeOverflow)?; + let mut data = data.bytes_mut(); + let bpp = format.bytes_per_pixel(); + let tr = tc.rect().intersect(&r); + let span = tr.width() as usize * bpp; + for y in tr.y0..tr.y1 { + check()?; + let row = (y - tc.ty * TILE_SIZE) as usize * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize; + if let Some(dst) = row.checked_mul(bpp).and_then(|o| data.get_mut(o..o.checked_add(span)?)) { + fill(y, tr.x0, dst); + } + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn fill_tiles(tiles: &mut [(TileCoord, Option>)], r: Rect, format: &PixelFormat, default_pixel: &[u8], fill: &F, check: &C) -> Result<(), E> +where + F: Fn(i32, i32, &mut [u8]) + Sync, + C: Fn() -> Result<(), E> + Sync, + E: From + Send, +{ + use rayon::prelude::*; + tiles.par_iter_mut().try_for_each(|slot| fill_tile(slot, r, format, default_pixel, fill, check)) +} + +/// Serial counterpart, for the web build. +#[cfg(target_arch = "wasm32")] +fn fill_tiles(tiles: &mut [(TileCoord, Option>)], r: Rect, format: &PixelFormat, default_pixel: &[u8], fill: &F, check: &C) -> Result<(), E> +where + F: Fn(i32, i32, &mut [u8]) + Sync, + C: Fn() -> Result<(), E> + Sync, + E: From + Send, +{ + tiles.iter_mut().try_for_each(|slot| fill_tile(slot, r, format, default_pixel, fill, check)) +} + fn decode_tile_row_rgba(fmt: &PixelFormat, t: &[u8], base: usize, dst: &mut [[f32; 4]], row: &mut Vec) { let n = fmt.channels(); match (fmt.mode, fmt.sample, fmt.alpha) { @@ -1086,6 +1165,61 @@ impl Surface { written } + /// Fills `r` row by row, straight into the tiles: `fill(y, x0, dst)` writes the pixels of row + /// `y` from column `x0` into `dst`, the tile's bytes for that span (`dst.len()` is a whole + /// number of pixels in the surface's format). Lets a caller convert from its own buffer + /// without staging a copy of the region first. + /// + /// Tiles are filled on all cores (serially on the web), so `fill` must not depend on call + /// order. Missing tiles start as the default pixel; existing tiles are copied fallibly so + /// the surface is unchanged if preparation fails. An empty `r` writes nothing. + /// + /// Like [`Surface::write_region_par`] this enters Rayon, so don't call it from a `OnceLock` + /// initializer. + pub fn try_write_rows_with(&mut self, r: Rect, fill: F) -> Result<(), AllocationError> + where + F: Fn(i32, i32, &mut [u8]) + Sync, + { + self.try_prepare_rows(r, |tiles, format, default_pixel| fill_tiles(tiles, r, format, default_pixel, &fill, &|| Ok(()))) + } + + /// Interruptible row write. Cancellation or allocation failure leaves the surface unchanged. + /// Checks run before each tile and row; already running callbacks may finish after cancellation. + pub fn try_write_rows_with_interrupt(&mut self, r: Rect, ctl: &Interrupt, fill: F) -> Result<(), RowWriteError> + where + F: Fn(i32, i32, &mut [u8]) + Sync, + { + self.try_prepare_rows(r, |tiles, format, default_pixel| { + fill_tiles(tiles, r, format, default_pixel, &fill, &|| ctl.check().map_err(RowWriteError::Cancelled)) + }) + } + + fn try_prepare_rows(&mut self, r: Rect, prepare: F) -> Result<(), E> + where + F: FnOnce(&mut [(TileCoord, Option>)], &PixelFormat, &[u8]) -> Result<(), E>, + E: From, + { + if r.is_empty() { + return Ok(()); + } + let count = usize::try_from(r.tile_count()).map_err(|_| AllocationError::SizeOverflow)?; + let bytes = count.checked_mul(std::mem::size_of::<(TileCoord, Option>)>()).ok_or(AllocationError::SizeOverflow)?; + let mut tiles: Vec<(TileCoord, Option>)> = Vec::new(); + tiles.try_reserve_exact(count).map_err(|_| AllocationError::NotEnoughMemory { bytes })?; + tiles.extend(r.tiles().map(|c| (c, self.tiles.get(&c).cloned()))); + prepare(&mut tiles, &self.format, &self.default_pixel)?; + for (c, tile) in tiles { + if let Some(tile) = tile { + if let Some(existing) = self.tiles.get_mut(&c) { + *existing = tile; + } else { + self.tiles.insert(c, tile); + } + } + } + Ok(()) + } + /// Read `r` as interleaved encoded bytes in the surface's format. pub fn to_interleaved(&self, r: Rect) -> Vec { let bpp = self.format.bytes_per_pixel(); diff --git a/crates/raster/src/tests.rs b/crates/raster/src/tests.rs index 472849c977..2910a5cdd8 100644 --- a/crates/raster/src/tests.rs +++ b/crates/raster/src/tests.rs @@ -853,3 +853,124 @@ fn fallible_interleaved_writes_match_encoded_pixels_and_reject_bad_lengths() { assert_eq!(shared.to_interleaved(rect), replacement); } } + +/// The byte a row-callback test writes at pixel (x, y). +fn row_byte(x: i32, y: i32) -> u8 { + (x.wrapping_mul(7).wrapping_add(y.wrapping_mul(13)) & 0xff) as u8 +} + +fn fill_row_bytes(y: i32, x0: i32, dst: &mut [u8]) { + for (i, b) in dst.iter_mut().enumerate() { + *b = row_byte(x0 + i as i32, y); + } +} + +#[test] +fn write_rows_empty_rect_writes_nothing() { + let mut s = Surface::new(PixelFormat::GRAY8); + let called = std::sync::atomic::AtomicBool::new(false); + for r in [Rect::new(5, 5, 5, 9), Rect::new(0, 0, 10, 0), Rect::new(10, 10, 2, 2), Rect::EMPTY] { + s.try_write_rows_with(r, |_, _, _| called.store(true, std::sync::atomic::Ordering::Relaxed)).expect("empty is fine"); + } + assert!(!called.load(std::sync::atomic::Ordering::Relaxed), "no rows in an empty rect"); + assert_eq!(s.tile_count(), 0); +} + +#[test] +fn write_rows_overflowing_rect_is_an_error_not_a_panic() { + let mut s = Surface::new(PixelFormat::GRAY8); + let r = Rect::new(0, 0, 1, 1); + s.try_write_rows_with(r, |_, _, dst| dst.fill(42)).unwrap(); + let before = s.clone(); + let huge = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); + assert!(s.try_write_rows_with(huge, |_, _, _| {}).is_err()); + assert_eq!(s.tile_count(), 1); + assert_eq!(s.to_interleaved(r), vec![42]); + assert!(std::sync::Arc::ptr_eq(s.tiles.values().next().unwrap(), before.tiles.values().next().unwrap())); +} + +#[test] +fn write_rows_negative_origin_and_unaligned_rect() { + let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.5]); + let r = Rect::new(-300, -5, 270, 260); + s.try_write_rows_with(r, fill_row_bytes).expect("memory"); + let got = s.to_interleaved(Rect::new(-320, -10, 300, 270)); + let w = 620; + for (i, &b) in got.iter().enumerate() { + let (x, y) = (-320 + (i % w) as i32, -10 + (i / w) as i32); + let want = if x >= r.x0 && x < r.x1 && y >= r.y0 && y < r.y1 { row_byte(x, y) } else { 128 }; + assert_eq!(b, want, "({x}, {y})"); + } +} + +#[test] +fn write_rows_matches_write_interleaved_at_every_depth() { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { + let bpp = fmt.bytes_per_pixel(); + let r = Rect::new(3, 2, 520, 300); + let w = r.width() as usize; + let bytes: Vec = (0..w * r.height() as usize * bpp).map(|i| (i % 251) as u8).collect(); + let mut a = Surface::new(fmt); + a.write_interleaved(r, &bytes); + let mut b = Surface::new(fmt); + b.try_write_rows_with(r, |y, x0, dst| { + let o = (((y - r.y0) as usize) * w + (x0 - r.x0) as usize) * bpp; + dst.copy_from_slice(&bytes[o..o + dst.len()]); + }) + .expect("memory"); + assert_eq!(a.tile_count(), b.tile_count()); + for (c, t) in a.tiles() { + assert!(b.tiles().any(|(c2, t2)| c2 == c && t2 == t), "{fmt:?}: tile {c:?} differs"); + } + } +} + +#[test] +fn write_rows_copies_tiles_a_clone_still_shares() { + let mut s = Surface::new(PixelFormat::GRAY8); + s.try_write_rows_with(Rect::new(0, 0, 300, 300), |_, _, dst| dst.fill(9)).expect("memory"); + let before = s.clone(); + let snapshot = before.to_interleaved(Rect::new(0, 0, 300, 300)); + s.try_write_rows_with(Rect::new(100, 100, 280, 290), fill_row_bytes).expect("memory"); + assert_eq!(before.to_interleaved(Rect::new(0, 0, 300, 300)), snapshot, "the clone is unchanged"); + assert_eq!(s.to_interleaved(Rect::new(150, 150, 151, 151)), vec![row_byte(150, 150)]); + assert_eq!(s.to_interleaved(Rect::new(10, 10, 11, 11)), vec![9], "pixels outside the rect keep their value"); +} + +#[test] +fn failed_row_preparation_preserves_existing_tiles() { + let mut surface = Surface::new(PixelFormat::GRAY8); + let r = Rect::new(0, 0, 300, 1); + surface.try_write_rows_with(Rect::new(0, 0, 1, 1), |_, _, dst| dst.fill(42)).unwrap(); + let before = surface.clone(); + let result = surface.try_prepare_rows(r, |tiles, _, _| { + fill_tile(&mut tiles[0], r, &PixelFormat::GRAY8, &[0], &|_, _, dst: &mut [u8]| dst.fill(7), &|| Ok::<(), AllocationError>(()))?; + Err(AllocationError::NotEnoughMemory { bytes: 1 }) + }); + assert!(matches!(result, Err(AllocationError::NotEnoughMemory { .. }))); + assert_eq!(surface.tile_count(), 1); + assert_eq!(surface.to_interleaved(Rect::new(0, 0, 1, 1)), vec![42]); + assert!(std::sync::Arc::ptr_eq(surface.tiles.values().next().unwrap(), before.tiles.values().next().unwrap())); +} + +#[test] +fn cancelled_row_write_stops_during_tile_and_preserves_surface() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + + let mut surface = Surface::new(PixelFormat::GRAY8); + let r = Rect::new(0, 0, 1, 100); + surface.try_write_rows_with(r, |_, _, dst| dst.fill(42)).unwrap(); + let before = surface.clone(); + let cancelled = AtomicBool::new(false); + let rows = AtomicUsize::new(0); + let check = || cancelled.load(Ordering::SeqCst); + let result = surface.try_write_rows_with_interrupt(r, &Interrupt::cancel_only(&check), |_, _, dst| { + dst.fill(7); + rows.fetch_add(1, Ordering::SeqCst); + cancelled.store(true, Ordering::SeqCst); + }); + assert_eq!(result, Err(RowWriteError::Cancelled(Cancelled))); + assert_eq!(rows.load(Ordering::SeqCst), 1); + assert_eq!(surface.to_interleaved(r), before.to_interleaved(r)); + assert!(std::sync::Arc::ptr_eq(surface.tiles.values().next().unwrap(), before.tiles.values().next().unwrap())); +}