Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

perf(compose): reuse bounded scratch and tone tables

Rene Leonhardta686a932c063
diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs
index f91e7779d..38e34fcd1 100644
--- a/crates/compose/src/adjust.rs
+++ b/crates/compose/src/adjust.rs
@@ -138,12 +138,12 @@ pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth
}
}
Adjustment::Levels { space, .. } | Adjustment::Curves { space, .. } => {
- let luts = tone_luts_depth(adj, depth);
let identity = float_tone_identity(adj, depth);
- match space {
- ToneSpace::Rgb => map_rgb(buf, |c| std::array::from_fn(|i| if identity[i] { c[i] } else { lut(&luts[i], c[i]) })),
- ToneSpace::Cmyk | ToneSpace::Lab => map_rgb(buf, |c| tone_in_space(*space, &luts, c)),
+ if identity == [true; 3] {
+ return;
}
+ let luts = tone_luts_depth(adj, depth);
+ apply_tone(buf, *space, &luts, identity);
}
Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges } => {
let table = (!*colorize && ranges.iter().any(|r| !r.is_neutral())).then(|| hue_range_tables(ranges));
@@ -572,6 +572,13 @@ pub fn float_tone_identity(adj: &Adjustment, depth: Option<SampleType>) -> [bool
}
}
+pub(crate) fn apply_tone(buf: &mut Buffer, space: ToneSpace, luts: &[Vec<f32>; 4], identity: [bool; 3]) {
+ match space {
+ ToneSpace::Rgb => map_rgb(buf, |c| std::array::from_fn(|i| if identity[i] { c[i] } else { lut(&luts[i], c[i]) })),
+ ToneSpace::Cmyk | ToneSpace::Lab => map_rgb(buf, |c| tone_in_space(space, luts, c)),
+ }
+}
+
/// Per-channel LUTs of a Levels or Curves adjustment: each channel's record first, then the
/// master (composite) record, as Photoshop does (psd-tools levels_rgb.psd and curves_rgb.psd,
/// #975). Four rows: the three `per_channel` channels then black
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 3cf2f1dc1..ae47c8435 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -96,6 +96,59 @@ impl Buffer {
/// Tile size for parallel rendering (tile results are independent).
pub const RENDER_TILE: i32 = 256;
+// One tile of scratch per worker; nested rendering takes its own buffer.
+thread_local! {
+ static SCRATCH: std::cell::RefCell<Vec<[f32; 4]>> = const { std::cell::RefCell::new(Vec::new()) };
+}
+
+fn scratch_buffer(rect: Rect) -> Buffer {
+ if rect.width() as usize * rect.height() as usize > (RENDER_TILE * RENDER_TILE) as usize {
+ return Buffer::transparent(rect);
+ }
+ let mut px = SCRATCH.with(|slot| std::mem::take(&mut *slot.borrow_mut()));
+ px.resize(rect.width() as usize * rect.height() as usize, [0.0; 4]);
+ Buffer { rect, px }
+}
+
+fn recycle_buffer(buf: Buffer) {
+ if buf.px.capacity() <= (RENDER_TILE * RENDER_TILE) as usize {
+ SCRATCH.with(|slot| {
+ let mut slot = slot.borrow_mut();
+ if slot.capacity() < buf.px.capacity() {
+ *slot = buf.px;
+ }
+ });
+ }
+}
+
+#[cfg(test)]
+#[test]
+fn scratch_reuse_preserves_pixels_and_bounds_retention() {
+ SCRATCH.with(|slot| slot.borrow_mut().clear());
+ let rect = Rect::new(-2, -3, 18, 11);
+ for fmt in [photocraft_color::PixelFormat::RGBA8, photocraft_color::PixelFormat::RGBA16, photocraft_color::PixelFormat::RGBA32F] {
+ let s = Surface::with_default(fmt, &[0.2, 0.4, 0.6, 0.8]);
+ let buf = surface_to_scratch(&s, rect);
+ assert_eq!(buf, surface_to_buffer(&s, rect));
+ let ptr = buf.px.as_ptr();
+ recycle_buffer(buf);
+ let reused = surface_to_scratch(&Surface::new(fmt), rect);
+ assert_eq!(reused.px.as_ptr(), ptr);
+ assert!(reused.px.iter().all(|p| p == &[0.0; 4]));
+ let nested = scratch_buffer(rect);
+ assert_ne!(nested.px.as_ptr(), reused.px.as_ptr());
+ recycle_buffer(nested);
+ recycle_buffer(reused);
+ }
+ let cached = SCRATCH.with(|slot| slot.borrow().as_ptr());
+ let huge = scratch_buffer(Rect::new(0, 0, RENDER_TILE + 1, RENDER_TILE));
+ recycle_buffer(huge);
+ SCRATCH.with(|slot| {
+ assert_eq!(slot.borrow().as_ptr(), cached);
+ assert!(slot.borrow().capacity() <= (RENDER_TILE * RENDER_TILE) as usize);
+ });
+}
+
/// Composite the whole document over `rect`, in parallel 256² tiles on
/// native targets (single-threaded on wasm).
pub fn render(doc: &Document, rect: Rect) -> Buffer {
@@ -341,6 +394,7 @@ pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer {
vector_masks: RenderVectorMasks::default(),
fx_maps: Default::default(),
fx_clip: Default::default(),
+ tone_luts: prepare_tones(std::slice::from_ref(layer), 0),
doc: None,
layer_keys: Default::default(),
},
@@ -531,6 +585,8 @@ struct Ctx<'a> {
/// The document's colour mode (channel restrictions name its channels).
mode: photocraft_color::ColorMode,
depth: photocraft_color::SampleType,
+ /// At most 1 MiB of tone tables, initialized once and shared by this render's tiles and bands.
+ tone_luts: Vec<(&'a photocraft_doc::Adjustment, std::sync::OnceLock<[Vec<f32>; 4]>)>,
vector_masks: RenderVectorMasks,
/// Effect maps used by this render, by cache key: built before the parallel tiles (see
/// [`prepare_effects`]) and held for the whole render (or band, for maps clipped to it: the
@@ -610,6 +666,7 @@ impl<'a> Ctx<'a> {
fx_maps: Default::default(),
fx_clip: Default::default(),
layer_keys: Default::default(),
+ tone_luts: prepare_tones(&doc.layers, 0),
}
}
@@ -621,9 +678,41 @@ impl<'a> Ctx<'a> {
self.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (_, clipped)| !*clipped);
}
}
+
+ fn apply_adjustment(&self, adj: &photocraft_doc::Adjustment, buf: &mut Buffer) {
+ if let photocraft_doc::Adjustment::Levels { space, .. } | photocraft_doc::Adjustment::Curves { space, .. } = adj
+ && !matches!(adj, photocraft_doc::Adjustment::Levels { space: photocraft_doc::adjust::ToneSpace::Rgb, .. } if self.depth == photocraft_color::SampleType::F32)
+ && let Some((_, luts)) = self.tone_luts.iter().find(|(a, _)| std::ptr::eq(*a, adj))
+ {
+ let identity = adjust::float_tone_identity(adj, Some(self.depth));
+ if identity == [true; 3] {
+ return;
+ }
+ adjust::apply_tone(buf, *space, luts.get_or_init(|| adjust::tone_luts_depth(adj, Some(self.depth))), identity);
+ } else {
+ adjust::apply_in(adj, buf, self.transfer, Some(self.depth), self.mode);
+ }
+ }
}
-/// Deepest group nesting [`prepare_effects`] walks (deeper layers build their maps on demand).
+fn prepare_tones(layers: &[Layer], depth: u32) -> Vec<(&photocraft_doc::Adjustment, std::sync::OnceLock<[Vec<f32>; 4]>)> {
+ let mut out = Vec::new();
+ for layer in layers.iter().filter(|l| l.visible) {
+ if out.len() == 16 {
+ break;
+ }
+ match &layer.content {
+ LayerContent::Adjustment(a @ (photocraft_doc::Adjustment::Levels { .. } | photocraft_doc::Adjustment::Curves { .. })) => {
+ out.push((a, Default::default()))
+ }
+ LayerContent::Group(g) if depth < PREPARE_DEPTH => out.extend(prepare_tones(&g.children, depth + 1).into_iter().take(16 - out.len())),
+ _ => {}
+ }
+ }
+ out
+}
+
+/// Deepest group nesting preparation walks (deeper layers prepare on demand).
const PREPARE_DEPTH: u32 = 64;
/// Build the effect maps of every visible layer in `layers` (groups included) that can reach
@@ -915,7 +1004,7 @@ fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Buffer> {
}
LayerContent::Fill(f) => match &layer.fill_cache {
// Photoshop's own rendering, valid while the fill is unchanged.
- Some(c) if c.fill == *f => surface_to_buffer(&c.surface, rect),
+ Some(c) if c.fill == *f => surface_to_scratch(&c.surface, rect),
_ if cx.mode == photocraft_color::ColorMode::Cmyk => {
let frame = fill_frame(layer, cx.canvas);
let native_rect = if matches!(f, Fill::Solid(_)) { Rect::new(0, 0, 1, 1) } else { rect };
@@ -929,7 +1018,7 @@ fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Buffer> {
},
LayerContent::Adjustment(_) => return None,
_ => match layer.surface() {
- Some(s) => surface_to_buffer(s, rect),
+ Some(s) => surface_to_scratch(s, rect),
None => Buffer::transparent(rect),
},
};
@@ -970,6 +1059,12 @@ pub fn surface_to_buffer(s: &Surface, rect: Rect) -> Buffer {
Buffer { rect, px }
}
+fn surface_to_scratch(s: &Surface, rect: Rect) -> Buffer {
+ let mut buf = scratch_buffer(rect);
+ s.read_rgba_into(rect, &mut buf.px);
+ buf
+}
+
/// The frame a fill layer's gradient is laid out in ("Align with layer", Photoshop's default):
/// the layer's bounds, i.e. the area its masks reveal: a hide-all pixel mask's painted area, or
/// the vector mask's path; otherwise the canvas.
@@ -1425,11 +1520,15 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer
// Adjustment layers transform the backdrop, then blend the result back in.
if let LayerContent::Adjustment(adj) = &layer.content {
- let mut adjusted = backdrop.clone();
- adjust::apply_in(adj, &mut adjusted, cx.transfer, Some(cx.depth), cx.mode);
+ let mv = mask_vals(layer, rect, cx);
+ if mv.as_ref().is_some_and(|values| values.iter().all(|&value| opacity * value <= 0.0)) {
+ return;
+ }
+ let mut adjusted = scratch_buffer(rect);
+ adjusted.px.copy_from_slice(&backdrop.px);
+ cx.apply_adjustment(adj, &mut adjusted);
// Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result.
advanced::composite_clipped(clipped, &mut adjusted, cx);
- let mv = mask_vals(layer, rect, cx);
for y in rect.y0..rect.y1 {
for x in rect.x0..rect.x1 {
let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize;
@@ -1444,6 +1543,7 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer
backdrop.px[i] = [b[0] + (blended[0] - b[0]) * k, b[1] + (blended[1] - b[1]) * k, b[2] + (blended[2] - b[2]) * k, b[3]];
}
}
+ recycle_buffer(adjusted);
return;
}
@@ -1471,6 +1571,7 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer
let Some(mut content) = render_content(layer, rect, cx) else { return };
advanced::composite_clipped(clipped, &mut content, cx);
blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, text_gamma(layer));
+ recycle_buffer(content);
}
/// A layer with effects (and its clipping group) onto `backdrop`.
@@ -1780,7 +1881,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
let rect = base.rect;
if let LayerContent::Adjustment(adj) = &layer.content {
let mut adjusted = base.clone();
- adjust::apply_in(adj, &mut adjusted, cx.transfer, Some(cx.depth), cx.mode);
+ cx.apply_adjustment(adj, &mut adjusted);
let mv = mask_vals(layer, rect, cx);
for (i, p) in base.px.iter_mut().enumerate() {
let k = layer.opacity * layer.fill_opacity * mask_k(&mv, i);
diff --git a/crates/compose/src/psblend.rs b/crates/compose/src/psblend.rs
index 4cff6f308..fa20eee8f 100644
--- a/crates/compose/src/psblend.rs
+++ b/crates/compose/src/psblend.rs
@@ -193,6 +193,7 @@ pub fn composite_fill(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opa
/// Straight-alpha source over straight-alpha backdrop (W3C/PDF general
/// formula) using [`blend_rgb`].
+#[inline]
pub fn composite(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opacity: f32) -> [f32; 4] {
let ab = backdrop[3];
let as_ = source[3] * opacity;
@@ -293,6 +294,7 @@ pub fn text_decode(v: f32, gamma: f32) -> f32 {
/// [`composite`] with the coverage mix done in the text blending space of `gamma`
/// ([`text_encode`]; `gamma == 1` is [`composite`], the setting switched off).
+#[inline]
pub fn composite_gamma(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opacity: f32, gamma: f32) -> [f32; 4] {
if gamma == 1.0 {
return composite(mode, backdrop, source, opacity);
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index ddd487154..cdc3acfda 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -14,6 +14,93 @@ fn doc_white(w: u32, h: u32) -> Document {
Document::with_background("t", Size::new(w, h), ColorMode::Rgb, SampleType::U8, Color::WHITE)
}
+#[test]
+fn prepared_tones_match_fresh_tables_and_stay_bounded() {
+ use photocraft_doc::adjust::ToneSpace;
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ for space in [ToneSpace::Rgb, ToneSpace::Cmyk, ToneSpace::Lab] {
+ for (mut adj, edited) in [
+ (Adjustment::identity_levels(), false),
+ (Adjustment::identity_levels(), true),
+ (Adjustment::identity_curves(), false),
+ (Adjustment::identity_curves(), true),
+ ] {
+ match &mut adj {
+ Adjustment::Levels { master, space: s, .. } => {
+ if edited {
+ master.gamma = 1.4;
+ }
+ *s = space;
+ }
+ Adjustment::Curves { master, space: s, .. } => {
+ if edited {
+ master[1].output = 0.8;
+ }
+ *s = space;
+ }
+ _ => {}
+ }
+ let mut doc = Document::new("tones", Size::new(3, 1), ColorMode::Rgb, depth);
+ doc.layers.push(Layer::group("group", vec![Layer::new("tone", LayerContent::Adjustment(adj.clone()))]));
+ let patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
+ let cx = Ctx::for_doc(&doc, &patterns);
+ let cached_adj = cx.tone_luts[0].0;
+ let input = Buffer { rect: doc.bounds(), px: vec![[0.2, 0.4, 0.7, 0.6], [2.0, -0.2, 0.5, 0.5], [2.0, -0.2, 0.5, 0.0]] };
+ let mut expected = input.clone();
+ adjust::apply_depth(&adj, &mut expected, cx.transfer, Some(depth));
+ for a in [cached_adj, cached_adj, &adj] {
+ let mut actual = input.clone();
+ cx.apply_adjustment(a, &mut actual);
+ assert_eq!(actual.px, expected.px);
+ }
+ let direct = depth == SampleType::F32 && matches!(adj, Adjustment::Levels { space: ToneSpace::Rgb, .. });
+ let identity = adjust::float_tone_identity(&adj, Some(depth)) == [true; 3];
+ assert_eq!(cx.tone_luts[0].1.get().is_none(), direct || identity);
+ }
+ }
+ }
+ let mut layers: Vec<_> = (0..20).map(|_| Layer::new("tone", LayerContent::Adjustment(Adjustment::identity_levels()))).collect();
+ layers[0].visible = false;
+ let tables = prepare_tones(&layers, 0);
+ assert_eq!(tables.len(), 16);
+ assert!(tables.iter().all(|(_, cell)| cell.get().is_none()));
+ assert!(matches!(&layers[1].content, LayerContent::Adjustment(a) if std::ptr::eq(tables[0].0, a)));
+ assert!(prepare_tones(&[Layer::group("deep", layers)], PREPARE_DEPTH).is_empty());
+}
+
+#[test]
+fn prepared_adjustments_keep_document_channel_semantics() {
+ for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let doc = Document::new("channels", Size::new(1, 1), mode, depth);
+ let patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
+ let cx = Ctx::for_doc(&doc, &patterns);
+ for adj in [Adjustment::Invert, Adjustment::BrightnessContrast { brightness: 20.0, contrast: 30.0, legacy: false }] {
+ let mut actual = Buffer::filled(doc.bounds(), [0.2, 0.4, 0.7, 0.6]);
+ let mut expected = actual.clone();
+ adjust::apply_in(&adj, &mut expected, cx.transfer, Some(depth), mode);
+ cx.apply_adjustment(&adj, &mut actual);
+ assert_eq!(actual.px, expected.px);
+ }
+ }
+ }
+}
+
+#[test]
+fn identity_float_curves_match_previous_mapping_bits() {
+ let adj = Adjustment::identity_curves();
+ let input = Buffer {
+ rect: Rect::new(0, 0, 4, 1),
+ px: vec![[2.0, -0.0, -0.2, 1.0], [f32::from_bits(0x7fc01234), f32::INFINITY, f32::NEG_INFINITY, 0.6], [0.7, -0.0, 1.5, 0.0], [0.1; 4]],
+ };
+ let mut previous = input.clone();
+ adjust::apply_tone(&mut previous, ToneSpace::Rgb, &adjust::tone_luts_depth(&adj, Some(SampleType::F32)), [true; 3]);
+ let mut actual = input.clone();
+ adjust::apply_depth(&adj, &mut actual, adjust::Transfer::Gamma(1.0), Some(SampleType::F32));
+ assert_buffer_bits(&actual, &previous);
+ assert_buffer_bits(&actual, &input);
+}
+
fn solid_layer(name: &str, rect: Rect, rgba: [f32; 4]) -> Layer {
let mut l = Layer::raster(name, PixelFormat::RGBA8);
l.surface_mut().unwrap().fill_rect(rect, &rgba);
@@ -3214,3 +3301,94 @@ fn concurrent_effect_identity_misses_compute_once() {
});
assert_eq!(keys.built.load(std::sync::atomic::Ordering::Relaxed), 1, "concurrent cache misses must compute one memoized identity");
}
+
+#[test]
+fn reused_render_matches_previous_allocating_stack() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let mut doc = Document::new("equivalence", Size::new(513, 7), ColorMode::Rgb, depth);
+ let rect = doc.bounds();
+ for (name, color) in [("bottom", [0.2, 0.4, 0.8, 1.0]), ("top", [1.5, -0.25, 0.6, 0.5])] {
+ let mut layer = Layer::raster(name, doc.pixel_format());
+ layer.surface_mut().unwrap().fill_rect(rect, &color);
+ doc.layers.push(layer);
+ }
+ let mut levels = Adjustment::identity_levels();
+ if let Adjustment::Levels { master, .. } = &mut levels {
+ master.gamma = 1.4;
+ }
+ for adj in [levels, Adjustment::identity_curves()] {
+ let mut layer = Layer::new("tone", LayerContent::Adjustment(adj));
+ layer.opacity = 0.6;
+ doc.layers.push(layer);
+ }
+ let mut previous = Buffer::transparent(rect);
+ in_blend_space(false, depth == SampleType::F32, || {
+ for layer in &doc.layers {
+ if let LayerContent::Adjustment(adj) = &layer.content {
+ let mut adjusted = previous.clone();
+ adjust::apply_in(adj, &mut adjusted, adjust::Transfer::for_document(doc.mode, depth), Some(depth), doc.mode);
+ for (b, a) in previous.px.iter_mut().zip(&adjusted.px) {
+ let blended = blend::blend_rgb(layer.blend, [b[0], b[1], b[2]], [a[0], a[1], a[2]]);
+ *b = [
+ b[0] + (blended[0] - b[0]) * layer.opacity,
+ b[1] + (blended[1] - b[1]) * layer.opacity,
+ b[2] + (blended[2] - b[2]) * layer.opacity,
+ b[3],
+ ];
+ }
+ if let Some(q) = adjustment_quantum(depth) {
+ quantize(&mut previous, q);
+ }
+ } else {
+ let content = surface_to_buffer(layer.surface().unwrap(), rect);
+ blend_into_fill(&mut previous, &content, layer.blend, layer.opacity, layer.fill_opacity, 1.0);
+ }
+ }
+ });
+ for tile in [1, 127, 256, 1024] {
+ assert_buffer_bits(&render_tiled(&doc, rect, tile), &previous);
+ }
+ }
+}
+
+#[test]
+fn fully_masked_adjustment_tiles_preserve_output_and_skip_tone_work() {
+ let rect = Rect::new(-1, -1, 2, 1);
+ for depth in SampleType::ALL {
+ for partial in [false, true] {
+ let mut doc = Document::new("masked", Size::new(3, 2), ColorMode::Rgb, depth);
+ let mut adj = Adjustment::identity_curves();
+ if let Adjustment::Curves { master, .. } = &mut adj {
+ master[1].output = 0.8;
+ }
+ let mut layer = Layer::new("curves", LayerContent::Adjustment(adj.clone()));
+ layer.opacity = 0.6;
+ let mut mask = LayerMask::hide_all();
+ if partial {
+ mask.surface.write_pixel(0, 0, &[0.75]);
+ }
+ layer.mask = Some(mask);
+ doc.layers.push(layer);
+ let patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
+ let cx = Ctx::for_doc(&doc, &patterns);
+ let before = Buffer::filled(rect, [0.2, -0.0, 0.7, 0.6]);
+ let mut adjusted = before.clone();
+ adjust::apply_in(&adj, &mut adjusted, cx.transfer, Some(depth), doc.mode);
+ let mv = mask_vals(&doc.layers[0], rect, &cx);
+ let mut expected = before.clone();
+ for (i, (b, a)) in expected.px.iter_mut().zip(&adjusted.px).enumerate() {
+ let k = 0.6 * mask_k(&mv, i);
+ if k > 0.0 {
+ for c in 0..3 {
+ b[c] += (a[c] - b[c]) * k;
+ }
+ }
+ }
+ let clipped = if partial { vec![] } else { vec![solid_layer("clipped", rect, [0.9, 0.1, 0.2, 1.0])] };
+ let mut actual = before;
+ composite_layer_plain(&doc.layers[0], &clipped, &mut actual, &cx, advanced::Scope::ROOT);
+ assert_buffer_bits(&actual, &expected);
+ assert_eq!(cx.tone_luts[0].1.get().is_some(), partial);
+ }
+ }
+}