From a49f739ed567a17dead9645eedcd49b8b4cb7621 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:55:35 +0100 Subject: [PATCH 1/3] Enlarge with Preserve Details without ringing at hard edges Preserve Details (and Automatic when it enlarges) sharpened Lanczos's output with a light Unsharp Mask, which kept Lanczos's overshoot and added its own halo: the issue's red/white edge came out as 9,0,0,43,212,255,255,246,253 against the reference 0,0,0,8,247,255,255,255,255. Each sample is now kept within the two by two source pixels around it before and after the sharpening, and the Unsharp Mask amount is fitted to the measured edge (127 %, radius still 0.6 x scale), giving 0,0,0,8,247,255,255,255,255 at 8 bits. Reductions and the other methods are unchanged. Fixes #14794. --- crates/algo/src/resample.rs | 126 +++++++++++++++-- .../resample/preserve_details_edge_tests.rs | 131 ++++++++++++++++++ crates/algo/src/sharpen/tests.rs | 11 +- 3 files changed, 257 insertions(+), 11 deletions(-) create mode 100644 crates/algo/src/resample/preserve_details_edge_tests.rs diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs index d153b78cb0..d2154c2ed8 100644 --- a/crates/algo/src/resample.rs +++ b/crates/algo/src/resample.rs @@ -388,6 +388,7 @@ pub fn resize_surface_with_interrupt( fn resize_controlled(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option, budget: usize, ctl: &photocraft_raster::Interrupt) -> Surface { let mut cur: Option = None; + let canvas_in = canvas; let mut canvas = canvas; for p in plan(filter, sx, sy) { if ctl.cancelled() { @@ -397,23 +398,124 @@ fn resize_controlled(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Op canvas = canvas.map(|c| scaled_rect(c, p.sx, p.sy)); cur = Some(next); } - let mut out = preserve_details(cur.unwrap_or_else(|| s.clone()), filter, sx, sy); + let mut out = preserve_details(cur.unwrap_or_else(|| s.clone()), s, filter, sx, sy, canvas_in); out.prune(); out } -/// Preserve Details' light sharpening of an enlargement (Lanczos's output, for the other filters -/// nothing). -fn preserve_details(mut out: Surface, filter: Resample, sx: f64, sy: f64) -> Surface { - if filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0) { +/// Whether `filter` at `(sx, sy)` ends with Preserve Details' sharpening of an enlargement. +fn sharpens(filter: Resample, sx: f64, sy: f64) -> bool { + filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0) +} + +/// Preserve Details' sharpening of an enlargement (Lanczos's output `out` of `src`; for the other +/// filters nothing): an Unsharp Mask that steepens edges, with every sample kept within the +/// source pixels around it before and after, so the edges get no ringing halo and the result is +/// the same at every depth (32 bits doesn't clip Lanczos's overshoot) (#14794). +fn preserve_details(mut out: Surface, src: &Surface, filter: Resample, sx: f64, sy: f64, canvas: Option) -> Surface { + if sharpens(filter, sx, sy) { + dering(&mut out, src, sx, sy, canvas); let dst = out.content_bounds(); - let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 }; + let p = crate::FilterParams::UnsharpMask { amount: PD_AMOUNT, radius: (PD_RADIUS * sx.max(sy)) as f32, threshold: 0.0 }; let area = crate::output_area(&p, dst, dst, None); out = crate::apply(&out, &p, area, dst, None); + dering(&mut out, src, sx, sy, canvas); } out } +/// Preserve Details' Unsharp Mask amount (%) and radius (per unit of scale), fitted to the +/// reference application's 2x enlargement of a hard edge (#14794). +pub(crate) const PD_AMOUNT: f32 = 127.0; +pub(crate) const PD_RADIUS: f64 = 0.6; + +/// Keeps each sample of `out` (a resize of `src` by `(sx, sy)`) within the range of the two by +/// two source pixels around its source position, channel by channel. Colour channels only count +/// the source pixels that are not fully transparent. Source positions are clamped into the area +/// the resize reads (the content, or with `canvas` that and the canvas). +pub(crate) fn dering(out: &mut Surface, src: &Surface, sx: f64, sy: f64, canvas: Option) { + let dst = out.content_bounds(); + let content = src.content_bounds(); + let area = canvas.map_or(content, |c| content.union(&c)); + if dst.is_empty() || area.is_empty() || !(sx > 0.0 && sy > 0.0) { + return; + } + let fmt = out.format(); + let n = fmt.channels(); + let alpha = fmt.alpha; + // The two source samples around output sample `o`, as indices into `lo..=hi`. + let pair = |o: i32, scale: f64, lo: i32, hi: i32| -> (usize, usize) { + let u = ((o as f64 + 0.5) / scale - 0.5).floor(); + let i0 = (u.clamp(f64::from(lo), f64::from(hi)) as i32 - lo) as usize; + let i1 = ((u + 1.0).clamp(f64::from(lo), f64::from(hi)) as i32 - lo) as usize; + (i0, i1) + }; + let xs: Vec<(usize, usize)> = (dst.x0..dst.x1).map(|o| pair(o, sx, area.x0, area.x1 - 1)).collect(); + let band = |b: i32| -> (Rect, Vec) { + let r = Rect::new(dst.x0, dst.y0 + b * BAND as i32, dst.x1, (dst.y0 + (b + 1) * BAND as i32).min(dst.y1)); + let ys: Vec<(usize, usize)> = (r.y0..r.y1).map(|o| pair(o, sy, area.y0, area.y1 - 1)).collect(); + let sy0 = ys.iter().map(|p| p.0.min(p.1)).min().unwrap_or(0); + let sy1 = ys.iter().map(|p| p.0.max(p.1)).max().unwrap_or(0) + 1; + let read = Rect::new(area.x0, area.y0 + sy0 as i32, area.x1, area.y0 + sy1 as i32); + let source = src.read_region(read); + let sw = read.width() as usize * n; + let mut data = out.read_region(r); + // The range of each source column over the current pair of rows: colour channels of + // transparent pixels count as nothing (an empty range, `lo > hi`). + let (mut vlo, mut vhi) = (vec![0.0f32; sw], vec![0.0f32; sw]); + let mut rows = None; + for (&(y0, y1), row) in ys.iter().zip(data.chunks_exact_mut(dst.width() as usize * n)) { + if rows != Some((y0, y1)) { + rows = Some((y0, y1)); + let a = source.get((y0 - sy0) * sw..(y0 - sy0 + 1) * sw).unwrap_or(&[]); + let b = source.get((y1 - sy0) * sw..(y1 - sy0 + 1) * sw).unwrap_or(&[]); + for (((pa, pb), lo), hi) in a.chunks_exact(n).zip(b.chunks_exact(n)).zip(vlo.chunks_exact_mut(n)).zip(vhi.chunks_exact_mut(n)) { + let seen = |p: &[f32]| !alpha || p.last().is_some_and(|&v| v > 0.0); + let (sa, sb) = (seen(pa), seen(pb)); + for (c, (((&va, &vb), l), h)) in pa.iter().zip(pb).zip(lo.iter_mut()).zip(hi.iter_mut()).enumerate() { + let all = alpha && c == n - 1; + let (ia, ib) = (sa || all, sb || all); + *l = match (ia, ib) { + (true, true) => va.min(vb), + (true, false) => va, + (false, true) => vb, + (false, false) => f32::INFINITY, + }; + *h = match (ia, ib) { + (true, true) => va.max(vb), + (true, false) => va, + (false, true) => vb, + (false, false) => f32::NEG_INFINITY, + }; + } + } + } + for (&(x0, x1), px) in xs.iter().zip(row.chunks_exact_mut(n)) { + let (l0, l1, h0, h1) = (vlo.get(x0 * n..), vlo.get(x1 * n..), vhi.get(x0 * n..), vhi.get(x1 * n..)); + let (Some(l0), Some(l1), Some(h0), Some(h1)) = (l0, l1, h0, h1) else { continue }; + for ((((v, &l0), &l1), &h0), &h1) in px.iter_mut().zip(l0).zip(l1).zip(h0).zip(h1) { + let (lo, hi) = (l0.min(l1), h0.max(h1)); + if lo <= hi { + *v = v.clamp(lo, hi); + } + } + } + } + (r, data) + }; + let bands: Vec = (0..(dst.height() as usize).div_ceil(BAND) as i32).collect(); + #[cfg(not(target_arch = "wasm32"))] + let parts: Vec<(Rect, Vec)> = { + use rayon::prelude::*; + bands.par_iter().map(|&b| band(b)).collect() + }; + #[cfg(target_arch = "wasm32")] + let parts: Vec<(Rect, Vec)> = bands.iter().map(|&b| band(b)).collect(); + for (r, d) in parts { + out.write_region(r, &d); + } +} + /// Output rows computed together by [`PassState::band`]. const BAND: usize = 64; @@ -607,6 +709,8 @@ pub struct ResizeSteps { canvas: Option, filter: Resample, scale: (f64, f64), + /// The input and its canvas, kept for Preserve Details' closing sharpening. + orig: Option<(Surface, Option)>, run: Option, /// Final pruning must yield too: sparse output can contain many default-filled tiles. prune: Option, @@ -625,7 +729,8 @@ impl ResizeSteps { /// or [`resize_surface_in_canvas`] does. pub fn new(src: Surface, sx: f64, sy: f64, filter: Resample, canvas: Option) -> Self { let passes = plan(filter, sx, sy); - Self { src, total: passes.len(), passes: passes.into_iter(), canvas, filter, scale: (sx, sy), run: None, prune: None } + let orig = sharpens(filter, sx, sy).then(|| (src.clone(), canvas)); + Self { src, total: passes.len(), passes: passes.into_iter(), canvas, filter, scale: (sx, sy), orig, run: None, prune: None } } /// How far along it is, `0.0..=1.0`: whole passes plus the bands done of the current one. @@ -677,7 +782,10 @@ impl ResizeSteps { if self.prune.is_none() { let placeholder = Surface::new(self.src.format()); let out = std::mem::replace(&mut self.src, placeholder); - self.src = preserve_details(out, self.filter, self.scale.0, self.scale.1); + self.src = match self.orig.take() { + Some((orig, canvas)) => preserve_details(out, &orig, self.filter, self.scale.0, self.scale.1, canvas), + None => out, + }; self.prune = Some(self.src.prune_cursor()); } let cursor = self.prune.as_mut()?; @@ -704,5 +812,7 @@ pub fn crop_surface(s: &Surface, keep: Rect) -> Surface { out } +#[cfg(test)] +mod preserve_details_edge_tests; #[cfg(test)] mod tests; diff --git a/crates/algo/src/resample/preserve_details_edge_tests.rs b/crates/algo/src/resample/preserve_details_edge_tests.rs new file mode 100644 index 0000000000..fe467274a7 --- /dev/null +++ b/crates/algo/src/resample/preserve_details_edge_tests.rs @@ -0,0 +1,131 @@ +//! Preserve Details enlarges hard edges without a ringing halo (#14794). + +use super::*; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; + +const CANVAS: Rect = Rect { x0: 0, y0: 0, x1: 400, y1: 300 }; + +/// The issue's flattened document: white, a red square at (0,0), a blue one at (300,200) and a +/// green one at (175,125), each opaque. +fn document(sample: SampleType, alpha: bool) -> Surface { + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, alpha)); + let px = |r: f32, g: f32, b: f32| if alpha { vec![r, g, b, 1.0] } else { vec![r, g, b] }; + s.fill_rect(CANVAS, &px(1.0, 1.0, 1.0)); + s.fill_rect(Rect::new(0, 0, 100, 100), &px(1.0, 0.0, 0.0)); + s.fill_rect(Rect::new(300, 200, 400, 300), &px(0.0, 0.0, 1.0)); + s.fill_rect(Rect::new(175, 125, 225, 175), &px(0.0, 1.0, 0.0)); + s +} + +/// The green channel at y, x in `xs`, in 8-bit levels. +fn green(s: &Surface, y: i32, xs: std::ops::Range) -> Vec { + xs.map(|x| (s.pixel(x, y)[1] * 255.0).round() as i32).collect() +} + +fn within(actual: &[i32], expected: &[i32], tol: i32) -> bool { + actual.len() == expected.len() && actual.iter().zip(expected).all(|(a, e)| (a - e).abs() <= tol) +} + +/// The reference application enlarges the red/white edge 2x to `0,0,0,8,247,255,255,255,255` +/// (green channel, y=20, x 196..204) with Preserve Details: no overshoot on either side, a +/// steep edge. Measured at 8 bits; the same edge holds at 16 and 32 bits. +#[test] +fn enlarging_a_hard_edge_does_not_ring() { + let reference = [0, 0, 0, 8, 247, 255, 255, 255, 255]; + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + for alpha in [false, true] { + let o = resize_surface_in_canvas(&document(sample, alpha), 2.0, 2.0, Resample::PreserveDetails, CANVAS); + let row = green(&o, 20, 196..205); + assert!(within(&row, &reference, 2), "{sample:?} alpha={alpha}: {row:?}, reference {reference:?}"); + } + } +} + +/// Reducing with Preserve Details stays Bicubic Sharper: `0,0,0,13,242,255,255,255` at 200x150. +#[test] +fn reducing_stays_bicubic_sharper() { + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let s = document(sample, false); + let pd = resize_surface_in_canvas(&s, 0.5, 0.5, Resample::PreserveDetails, CANVAS); + let sharper = resize_surface_in_canvas(&s, 0.5, 0.5, Resample::BicubicSharper, CANVAS); + let r = Rect::new(0, 0, 200, 150); + assert_eq!(pd.read_region(r), sharper.read_region(r), "{sample:?}"); + if sample == SampleType::U8 { + assert_eq!(green(&pd, 10, 46..54), [0, 0, 0, 13, 242, 255, 255, 255]); + } + } +} + +/// The other methods enlarge the edge as before (#14794 changes Preserve Details only). +#[test] +fn other_methods_keep_their_edge() { + let s = document(SampleType::U8, false); + let cases: [(Resample, [i32; 9]); 7] = [ + (Resample::Nearest, ROWS[0]), + (Resample::Bilinear, ROWS[1]), + (Resample::Bicubic, ROWS[2]), + (Resample::BicubicSmoother, ROWS[3]), + (Resample::BicubicSharper, ROWS[4]), + (Resample::BicubicAutomatic, ROWS[5]), + (Resample::Lanczos, ROWS[6]), + ]; + for (f, expected) in cases { + let o = resize_surface_in_canvas(&s, 2.0, 2.0, f, CANVAS); + assert_eq!(green(&o, 20, 196..205), expected, "{f:?}"); + } +} + +/// The rows main 406ac677e1 gives, for [`other_methods_keep_their_edge`]. +const ROWS: [[i32; 9]; 7] = [ + [0, 0, 0, 0, 255, 255, 255, 255, 255], + [0, 0, 0, 64, 191, 255, 255, 255, 255], + [0, 0, 0, 58, 197, 255, 255, 255, 255], + [0, 0, 0, 66, 189, 255, 255, 255, 255], + [0, 0, 0, 66, 189, 255, 255, 255, 255], + [0, 0, 0, 66, 189, 255, 255, 255, 255], + [8, 0, 0, 54, 201, 255, 255, 247, 253], +]; + +/// At any scale and depth the enlargement stays within the source's levels: no halo darker than +/// the red or brighter than the white, and flat areas stay flat. +#[test] +fn enlargements_never_overshoot() { + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let s = document(sample, true); + for k in [1.37, 2.0, 3.0] { + let o = resize_surface_in_canvas(&s, k, k, Resample::PreserveDetails, CANVAS); + let dst = scaled_rect(CANVAS, k, k); + assert_eq!(o.content_bounds(), dst, "{sample:?} {k}"); + for v in o.read_region(dst) { + assert!((0.0..=1.0).contains(&v), "{sample:?} {k}: {v}"); + } + // Inside the red square, away from its edge. + let p = o.pixel((50.0 * k) as i32, (50.0 * k) as i32); + assert_eq!(p, vec![1.0, 0.0, 0.0, 1.0], "{sample:?} {k}"); + } + } +} + +/// A layer smaller than the canvas, on transparency: the clamp doesn't pull its colour towards +/// the transparent pixels, and the stepped resize gives the same pixels as the one-shot one. +#[test] +fn transparent_surroundings_and_steps_match() { + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true)); + s.fill_rect(Rect::new(10, 10, 30, 30), &[0.2, 0.6, 1.0, 1.0]); + let o = resize_surface_in_canvas(&s, 2.5, 2.5, Resample::PreserveDetails, CANVAS); + // On the layer's edge the colour stays the layer's. + let edge = o.pixel(25, 50); + assert!(edge[3] > 0.0 && edge[3] < 1.0, "{sample:?} {edge:?}"); + let off = edge.iter().take(3).zip([0.2, 0.6, 1.0]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(off < 0.01, "{sample:?} {edge:?}"); + let mut steps = ResizeSteps::new(s.clone(), 2.5, 2.5, Resample::PreserveDetails, Some(CANVAS)); + let stepped = loop { + if let Some(out) = steps.step(&mut || true) { + break out; + } + }; + let r = o.content_bounds().union(&stepped.content_bounds()); + assert_eq!(stepped.read_region(r), o.read_region(r), "{sample:?}"); + } +} diff --git a/crates/algo/src/sharpen/tests.rs b/crates/algo/src/sharpen/tests.rs index f491c14f18..1d641f9a75 100644 --- a/crates/algo/src/sharpen/tests.rs +++ b/crates/algo/src/sharpen/tests.rs @@ -218,10 +218,15 @@ fn preserve_details_resampling_keeps_the_same_sharpening() { for depth in SampleType::ALL { for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] { let s = source(src, PixelFormat::new(mode, depth, true)); - let resized = resize_surface(&s, sx, sy, Resample::Lanczos); - let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 }; + // Lanczos, kept within the source pixels around each sample (#14794), sharpened and kept + // within them again. + let mut resized = resize_surface(&s, sx, sy, Resample::Lanczos); + crate::resample::dering(&mut resized, &s, sx, sy, None); + let radius = (crate::resample::PD_RADIUS * sx.max(sy)) as f32; + let p = crate::FilterParams::UnsharpMask { amount: crate::resample::PD_AMOUNT, radius, threshold: 0.0 }; let area = crate::output_area(&p, resized.content_bounds(), dst, None); - let expected = apply_reference(&resized, &p, area, dst, None, None, crate::auto_tile(&p, dst)); + let mut expected = apply_reference(&resized, &p, area, dst, None, None, crate::auto_tile(&p, dst)); + crate::resample::dering(&mut expected, &s, sx, sy, None); let actual = resize_surface(&s, sx, sy, Resample::PreserveDetails); assert_eq!(actual.to_interleaved(area), expected.to_interleaved(area)); } From e6035facfd3f1803b3c2e885df7cb61bc03eb5c2 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:35:51 +0100 Subject: [PATCH 2/3] Limit Preserve Details deringing to the measured case and bound its memory Issue #14794 measured only the 8-bit 2x enlargement and asks that every unmeasured case keep today's behaviour, so the clamp and the 127 % Unsharp Mask now run only for 8-bit images enlarged 2x on both axes. Other scales, mixed-axis resizes and 16/32-bit documents are back to Lanczos plus the 30 % mask, which also keeps the detail a reducing axis averages in. dering now reads source rows one at a time and writes its bands a group at a time, like resize_pass, so neither the source read nor the buffered output grows with the scale or the image size. --- crates/algo/src/resample.rs | 131 +++++++++++----- .../resample/preserve_details_edge_tests.rs | 148 +++++++++++++----- crates/algo/src/sharpen/tests.rs | 11 +- 3 files changed, 209 insertions(+), 81 deletions(-) diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs index d2154c2ed8..b38e14ad4e 100644 --- a/crates/algo/src/resample.rs +++ b/crates/algo/src/resample.rs @@ -1,5 +1,6 @@ //! High-quality separable resampling of surfaces (Image Size). +use photocraft_color::{PixelFormat, SampleType}; use photocraft_geom::{Rect, TILE_SIZE}; use photocraft_raster::Surface; use serde::{Deserialize, Serialize}; @@ -398,7 +399,7 @@ fn resize_controlled(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Op canvas = canvas.map(|c| scaled_rect(c, p.sx, p.sy)); cur = Some(next); } - let mut out = preserve_details(cur.unwrap_or_else(|| s.clone()), s, filter, sx, sy, canvas_in); + let mut out = preserve_details(cur.unwrap_or_else(|| s.clone()), Some((s, canvas_in)), filter, sx, sy); out.prune(); out } @@ -408,24 +409,43 @@ fn sharpens(filter: Resample, sx: f64, sy: f64) -> bool { filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0) } -/// Preserve Details' sharpening of an enlargement (Lanczos's output `out` of `src`; for the other -/// filters nothing): an Unsharp Mask that steepens edges, with every sample kept within the -/// source pixels around it before and after, so the edges get no ringing halo and the result is -/// the same at every depth (32 bits doesn't clip Lanczos's overshoot) (#14794). -fn preserve_details(mut out: Surface, src: &Surface, filter: Resample, sx: f64, sy: f64, canvas: Option) -> Surface { - if sharpens(filter, sx, sy) { +/// Whether Preserve Details' enlargement of `fmt` at `(sx, sy)` is the case #14794 measured +/// against the reference application, an 8-bit image enlarged 2x on both axes, and so gets +/// [`dering`] and the fitted sharpening. The issue keeps every case it didn't measure (other +/// scales, 16 and 32 bits) as it was. +fn derings(fmt: PixelFormat, filter: Resample, sx: f64, sy: f64) -> bool { + sharpens(filter, sx, sy) && fmt.sample == SampleType::U8 && sx == 2.0 && sy == 2.0 +} + +/// Preserve Details' sharpening of an enlargement (Lanczos's output `out` of `src`, read with +/// `canvas`; for the other filters nothing): an Unsharp Mask that steepens edges. In the measured +/// case (see [`derings`]) every sample is kept within the source pixels around it before and after +/// it, so the edges get no ringing halo (#14794); elsewhere it is the light 30 % mask as before. +/// `src` is only needed in the measured case. +fn preserve_details(mut out: Surface, src: Option<(&Surface, Option)>, filter: Resample, sx: f64, sy: f64) -> Surface { + if !sharpens(filter, sx, sy) { + return out; + } + let dering_src = src.filter(|_| derings(out.format(), filter, sx, sy)); + if let Some((src, canvas)) = dering_src { dering(&mut out, src, sx, sy, canvas); - let dst = out.content_bounds(); - let p = crate::FilterParams::UnsharpMask { amount: PD_AMOUNT, radius: (PD_RADIUS * sx.max(sy)) as f32, threshold: 0.0 }; - let area = crate::output_area(&p, dst, dst, None); - out = crate::apply(&out, &p, area, dst, None); + } + let (amount, radius) = match dering_src { + Some(_) => (PD_AMOUNT, (PD_RADIUS * sx.max(sy)) as f32), + None => (30.0, 0.6 * sx.max(sy) as f32), + }; + let dst = out.content_bounds(); + let p = crate::FilterParams::UnsharpMask { amount, radius, threshold: 0.0 }; + let area = crate::output_area(&p, dst, dst, None); + out = crate::apply(&out, &p, area, dst, None); + if let Some((src, canvas)) = dering_src { dering(&mut out, src, sx, sy, canvas); } out } -/// Preserve Details' Unsharp Mask amount (%) and radius (per unit of scale), fitted to the -/// reference application's 2x enlargement of a hard edge (#14794). +/// Preserve Details' Unsharp Mask amount (%) in the measured case and radius (per unit of +/// scale), fitted to the reference application's 2x enlargement of a hard edge (#14794). pub(crate) const PD_AMOUNT: f32 = 127.0; pub(crate) const PD_RADIUS: f64 = 0.6; @@ -433,6 +453,9 @@ pub(crate) const PD_RADIUS: f64 = 0.6; /// two source pixels around its source position, channel by channel. Colour channels only count /// the source pixels that are not fully transparent. Source positions are clamped into the area /// the resize reads (the content, or with `canvas` that and the canvas). +/// +/// Source rows are read one at a time, whatever the scale, and bands of output rows are written +/// a group at a time, like [`resize_pass`], so memory stays bounded. pub(crate) fn dering(out: &mut Surface, src: &Surface, sx: f64, sy: f64, canvas: Option) { let dst = out.content_bounds(); let content = src.content_bounds(); @@ -451,15 +474,23 @@ pub(crate) fn dering(out: &mut Surface, src: &Surface, sx: f64, sy: f64, canvas: (i0, i1) }; let xs: Vec<(usize, usize)> = (dst.x0..dst.x1).map(|o| pair(o, sx, area.x0, area.x1 - 1)).collect(); - let band = |b: i32| -> (Rect, Vec) { - let r = Rect::new(dst.x0, dst.y0 + b * BAND as i32, dst.x1, (dst.y0 + (b + 1) * BAND as i32).min(dst.y1)); + let sw = area.width() as usize * n; + // Source row `k` of the area (as `pair` indexes it) into `buf`. + let read_row = |k: usize, buf: &mut Vec| { + let y = area.y0.saturating_add(i32::try_from(k).unwrap_or(i32::MAX)); + let r = Rect::new(area.x0, y, area.x1, y.saturating_add(1)); + #[cfg(test)] + DERING_MAX_READ_ROWS.fetch_max(r.height() as usize, std::sync::atomic::Ordering::Relaxed); + src.read_region_into(r, buf); + }; + let band = |out: &Surface, b: usize| -> (Rect, Vec) { + let y0 = dst.y0.saturating_add(i32::try_from(b * BAND).unwrap_or(i32::MAX)).min(dst.y1); + let r = Rect::new(dst.x0, y0, dst.x1, y0.saturating_add(BAND as i32).min(dst.y1)); let ys: Vec<(usize, usize)> = (r.y0..r.y1).map(|o| pair(o, sy, area.y0, area.y1 - 1)).collect(); - let sy0 = ys.iter().map(|p| p.0.min(p.1)).min().unwrap_or(0); - let sy1 = ys.iter().map(|p| p.0.max(p.1)).max().unwrap_or(0) + 1; - let read = Rect::new(area.x0, area.y0 + sy0 as i32, area.x1, area.y0 + sy1 as i32); - let source = src.read_region(read); - let sw = read.width() as usize * n; let mut data = out.read_region(r); + // The two source rows of the current pair, with their indices: a row shared with the + // previous pair is kept instead of read again. + let (mut ra, mut rb): (SourceRow, SourceRow) = ((None, Vec::new()), (None, Vec::new())); // The range of each source column over the current pair of rows: colour channels of // transparent pixels count as nothing (an empty range, `lo > hi`). let (mut vlo, mut vhi) = (vec![0.0f32; sw], vec![0.0f32; sw]); @@ -467,9 +498,18 @@ pub(crate) fn dering(out: &mut Surface, src: &Surface, sx: f64, sy: f64, canvas: for (&(y0, y1), row) in ys.iter().zip(data.chunks_exact_mut(dst.width() as usize * n)) { if rows != Some((y0, y1)) { rows = Some((y0, y1)); - let a = source.get((y0 - sy0) * sw..(y0 - sy0 + 1) * sw).unwrap_or(&[]); - let b = source.get((y1 - sy0) * sw..(y1 - sy0 + 1) * sw).unwrap_or(&[]); - for (((pa, pb), lo), hi) in a.chunks_exact(n).zip(b.chunks_exact(n)).zip(vlo.chunks_exact_mut(n)).zip(vhi.chunks_exact_mut(n)) { + if rb.0 == Some(y0) { + std::mem::swap(&mut ra, &mut rb); + } + if ra.0 != Some(y0) { + read_row(y0, &mut ra.1); + ra.0 = Some(y0); + } + if rb.0 != Some(y1) { + read_row(y1, &mut rb.1); + rb.0 = Some(y1); + } + for (((pa, pb), lo), hi) in ra.1.chunks_exact(n).zip(rb.1.chunks_exact(n)).zip(vlo.chunks_exact_mut(n)).zip(vhi.chunks_exact_mut(n)) { let seen = |p: &[f32]| !alpha || p.last().is_some_and(|&v| v > 0.0); let (sa, sb) = (seen(pa), seen(pb)); for (c, (((&va, &vb), l), h)) in pa.iter().zip(pb).zip(lo.iter_mut()).zip(hi.iter_mut()).enumerate() { @@ -503,19 +543,40 @@ pub(crate) fn dering(out: &mut Surface, src: &Surface, sx: f64, sy: f64, canvas: } (r, data) }; - let bands: Vec = (0..(dst.height() as usize).div_ceil(BAND) as i32).collect(); + let bands: Vec = (0..(dst.height() as usize).div_ceil(BAND)).collect(); + // Bands read disjoint output rows, so each group is written before the next is computed, and + // the `f32` rows held at once are bounded by the group (#1544). #[cfg(not(target_arch = "wasm32"))] - let parts: Vec<(Rect, Vec)> = { - use rayon::prelude::*; - bands.par_iter().map(|&b| band(b)).collect() - }; + let group = rayon::current_num_threads().max(1) * 2; #[cfg(target_arch = "wasm32")] - let parts: Vec<(Rect, Vec)> = bands.iter().map(|&b| band(b)).collect(); - for (r, d) in parts { - out.write_region(r, &d); + let group = 1; + for chunk in bands.chunks(group) { + #[cfg(not(target_arch = "wasm32"))] + let parts: Vec<(Rect, Vec)> = { + use rayon::prelude::*; + let o: &Surface = out; + chunk.par_iter().map(|&b| band(o, b)).collect() + }; + #[cfg(target_arch = "wasm32")] + let parts: Vec<(Rect, Vec)> = chunk.iter().map(|&b| band(out, b)).collect(); + #[cfg(test)] + DERING_MAX_HELD_BANDS.fetch_max(parts.len(), std::sync::atomic::Ordering::Relaxed); + for (r, d) in parts { + out.write_region(r, &d); + } } } +/// A source row read by [`dering`]: its index (if any yet) and samples. +type SourceRow = (Option, Vec); + +/// The most source rows one read of [`dering`] has spanned, and the most bands it has held +/// before writing them, so tests can check both stay bounded. +#[cfg(test)] +pub(crate) static DERING_MAX_READ_ROWS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +#[cfg(test)] +pub(crate) static DERING_MAX_HELD_BANDS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + /// Output rows computed together by [`PassState::band`]. const BAND: usize = 64; @@ -729,7 +790,7 @@ impl ResizeSteps { /// or [`resize_surface_in_canvas`] does. pub fn new(src: Surface, sx: f64, sy: f64, filter: Resample, canvas: Option) -> Self { let passes = plan(filter, sx, sy); - let orig = sharpens(filter, sx, sy).then(|| (src.clone(), canvas)); + let orig = derings(src.format(), filter, sx, sy).then(|| (src.clone(), canvas)); Self { src, total: passes.len(), passes: passes.into_iter(), canvas, filter, scale: (sx, sy), orig, run: None, prune: None } } @@ -782,10 +843,8 @@ impl ResizeSteps { if self.prune.is_none() { let placeholder = Surface::new(self.src.format()); let out = std::mem::replace(&mut self.src, placeholder); - self.src = match self.orig.take() { - Some((orig, canvas)) => preserve_details(out, &orig, self.filter, self.scale.0, self.scale.1, canvas), - None => out, - }; + let orig = self.orig.take(); + self.src = preserve_details(out, orig.as_ref().map(|(o, c)| (o, *c)), self.filter, self.scale.0, self.scale.1); self.prune = Some(self.src.prune_cursor()); } let cursor = self.prune.as_mut()?; diff --git a/crates/algo/src/resample/preserve_details_edge_tests.rs b/crates/algo/src/resample/preserve_details_edge_tests.rs index fe467274a7..f043199cd1 100644 --- a/crates/algo/src/resample/preserve_details_edge_tests.rs +++ b/crates/algo/src/resample/preserve_details_edge_tests.rs @@ -28,16 +28,15 @@ fn within(actual: &[i32], expected: &[i32], tol: i32) -> bool { /// The reference application enlarges the red/white edge 2x to `0,0,0,8,247,255,255,255,255` /// (green channel, y=20, x 196..204) with Preserve Details: no overshoot on either side, a -/// steep edge. Measured at 8 bits; the same edge holds at 16 and 32 bits. +/// steep edge. Measured at 8 bits only (16 and 32 bits keep the previous result, see +/// [`unmeasured_enlargements_keep_the_previous_sharpening`]). #[test] fn enlarging_a_hard_edge_does_not_ring() { let reference = [0, 0, 0, 8, 247, 255, 255, 255, 255]; - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - for alpha in [false, true] { - let o = resize_surface_in_canvas(&document(sample, alpha), 2.0, 2.0, Resample::PreserveDetails, CANVAS); - let row = green(&o, 20, 196..205); - assert!(within(&row, &reference, 2), "{sample:?} alpha={alpha}: {row:?}, reference {reference:?}"); - } + for alpha in [false, true] { + let o = resize_surface_in_canvas(&document(SampleType::U8, alpha), 2.0, 2.0, Resample::PreserveDetails, CANVAS); + let row = green(&o, 20, 196..205); + assert!(within(&row, &reference, 2), "alpha={alpha}: {row:?}, reference {reference:?}"); } } @@ -86,46 +85,121 @@ const ROWS: [[i32; 9]; 7] = [ [8, 0, 0, 54, 201, 255, 255, 247, 253], ]; -/// At any scale and depth the enlargement stays within the source's levels: no halo darker than +/// The measured enlargement (8 bits, 2x) stays within the source's levels: no halo darker than /// the red or brighter than the white, and flat areas stay flat. #[test] -fn enlargements_never_overshoot() { - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - let s = document(sample, true); - for k in [1.37, 2.0, 3.0] { - let o = resize_surface_in_canvas(&s, k, k, Resample::PreserveDetails, CANVAS); - let dst = scaled_rect(CANVAS, k, k); - assert_eq!(o.content_bounds(), dst, "{sample:?} {k}"); - for v in o.read_region(dst) { - assert!((0.0..=1.0).contains(&v), "{sample:?} {k}: {v}"); - } - // Inside the red square, away from its edge. - let p = o.pixel((50.0 * k) as i32, (50.0 * k) as i32); - assert_eq!(p, vec![1.0, 0.0, 0.0, 1.0], "{sample:?} {k}"); - } +fn the_measured_enlargement_never_overshoots() { + let s = document(SampleType::U8, true); + let o = resize_surface_in_canvas(&s, 2.0, 2.0, Resample::PreserveDetails, CANVAS); + let dst = scaled_rect(CANVAS, 2.0, 2.0); + assert_eq!(o.content_bounds(), dst); + for v in o.read_region(dst) { + assert!((0.0..=1.0).contains(&v), "{v}"); } + // Inside the red square, away from its edge. + assert_eq!(o.pixel(100, 100), vec![1.0, 0.0, 0.0, 1.0]); } -/// A layer smaller than the canvas, on transparency: the clamp doesn't pull its colour towards -/// the transparent pixels, and the stepped resize gives the same pixels as the one-shot one. +/// A layer smaller than the canvas, on transparency: in the measured case the clamp doesn't pull +/// its colour towards the transparent pixels, and at any scale and depth the stepped resize gives +/// the same pixels as the one-shot one. #[test] fn transparent_surroundings_and_steps_match() { for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true)); s.fill_rect(Rect::new(10, 10, 30, 30), &[0.2, 0.6, 1.0, 1.0]); - let o = resize_surface_in_canvas(&s, 2.5, 2.5, Resample::PreserveDetails, CANVAS); - // On the layer's edge the colour stays the layer's. - let edge = o.pixel(25, 50); - assert!(edge[3] > 0.0 && edge[3] < 1.0, "{sample:?} {edge:?}"); - let off = edge.iter().take(3).zip([0.2, 0.6, 1.0]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(off < 0.01, "{sample:?} {edge:?}"); - let mut steps = ResizeSteps::new(s.clone(), 2.5, 2.5, Resample::PreserveDetails, Some(CANVAS)); - let stepped = loop { - if let Some(out) = steps.step(&mut || true) { - break out; + for k in [2.0, 2.5] { + let o = resize_surface_in_canvas(&s, k, k, Resample::PreserveDetails, CANVAS); + if sample == SampleType::U8 && k == 2.0 { + // On the layer's edge the colour stays the layer's. + let edge = o.pixel(20, 40); + assert!(edge[3] > 0.0 && edge[3] < 1.0, "{edge:?}"); + let off = edge.iter().take(3).zip([0.2, 0.6, 1.0]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(off < 0.01, "{edge:?}"); } - }; - let r = o.content_bounds().union(&stepped.content_bounds()); - assert_eq!(stepped.read_region(r), o.read_region(r), "{sample:?}"); + let mut steps = ResizeSteps::new(s.clone(), k, k, Resample::PreserveDetails, Some(CANVAS)); + let stepped = loop { + if let Some(out) = steps.step(&mut || true) { + break out; + } + }; + let r = o.content_bounds().union(&stepped.content_bounds()); + assert_eq!(stepped.read_region(r), o.read_region(r), "{sample:?} {k}"); + } } } + +/// Preserve Details before #14794: Lanczos, then an Unsharp Mask of 30 % at radius 0.6 x scale. +fn lanczos_and_unsharp_mask(s: &Surface, sx: f64, sy: f64) -> Surface { + let out = resize_surface(s, sx, sy, Resample::Lanczos); + let dst = out.content_bounds(); + let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 }; + let area = crate::output_area(&p, dst, dst, None); + let mut out = crate::apply(&out, &p, area, dst, None); + out.prune(); + out +} + +/// The issue measured only 8-bit 2x enlargements; other scales and 16/32-bit documents keep +/// Preserve Details' previous result (#14794, "not measured ... keep today's behaviour"). +#[test] +fn unmeasured_enlargements_keep_the_previous_sharpening() { + let cases = [ + (SampleType::U8, 1.37, 1.37), + (SampleType::U8, 3.0, 3.0), + (SampleType::U8, 2.0, 1.5), + (SampleType::U8, 1.0, 2.0), + (SampleType::U16, 2.0, 2.0), + (SampleType::F32, 2.0, 2.0), + ]; + for (sample, sx, sy) in cases { + let s = document(sample, false); + let actual = resize_surface(&s, sx, sy, Resample::PreserveDetails); + let expected = lanczos_and_unsharp_mask(&s, sx, sy); + let r = actual.content_bounds().union(&expected.content_bounds()); + assert!(actual.read_region(r) == expected.read_region(r), "{sample:?} {sx}x{sy}: differs from Lanczos + Unsharp Mask 30 %"); + } +} + +/// One axis shrinking and the other growing: the columns black, black, black, white reduced to a +/// quarter keep the white averaged in by the reduction instead of being clamped back to black. +#[test] +fn mixed_axis_resize_keeps_reduced_detail() { + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true)); + for x in 0..64 { + let v = if x % 4 == 3 { 1.0 } else { 0.0 }; + s.fill_rect(Rect::new(x, 0, x + 1, 16), &[v, v, v, 1.0]); + } + let o = resize_surface(&s, 0.25, 2.0, Resample::PreserveDetails); + let v = o.pixel(8, 16)[1]; + assert!(v > 0.1, "{sample:?}: green {v} at (8,16), the white columns were clamped away"); + let expected = lanczos_and_unsharp_mask(&s, 0.25, 2.0); + let r = o.content_bounds().union(&expected.content_bounds()); + assert!(o.read_region(r) == expected.read_region(r), "{sample:?}: differs from Lanczos + Unsharp Mask 30 %"); + } +} + +/// A band of output rows that spans thousands of source rows (6000x4000 at 2 x 0.01 spans about +/// 3900 per band) reads them a row at a time, so a read stays within the read budget. +#[test] +fn dering_reads_a_bounded_number_of_source_rows() { + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, false)); + s.fill_rect(Rect::new(0, 0, 8, 4000), &[0.5, 0.5, 0.5]); + let mut o = resize_surface(&s, 2.0, 0.01, Resample::Lanczos); + dering(&mut o, &s, 2.0, 0.01, None); + let rows = DERING_MAX_READ_ROWS.load(std::sync::atomic::Ordering::Relaxed); + assert!(rows <= 1, "one dering read spanned {rows} source rows"); +} + +/// Dering writes its bands a group at a time, like `resize_pass`, instead of holding them all. +#[test] +fn dering_holds_a_bounded_group_of_bands() { + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, false)); + s.fill_rect(Rect::new(0, 0, 2, 6400), &[0.5, 0.5, 0.5]); + let mut o = resize_surface(&s, 2.0, 2.0, Resample::Lanczos); + dering(&mut o, &s, 2.0, 2.0, None); + let held = DERING_MAX_HELD_BANDS.load(std::sync::atomic::Ordering::Relaxed); + let group = rayon::current_num_threads().max(1) * 2; + assert!(held <= group, "dering held {held} of {} bands at once (group {group})", 12800usize.div_ceil(BAND)); +} diff --git a/crates/algo/src/sharpen/tests.rs b/crates/algo/src/sharpen/tests.rs index 1d641f9a75..f491c14f18 100644 --- a/crates/algo/src/sharpen/tests.rs +++ b/crates/algo/src/sharpen/tests.rs @@ -218,15 +218,10 @@ fn preserve_details_resampling_keeps_the_same_sharpening() { for depth in SampleType::ALL { for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] { let s = source(src, PixelFormat::new(mode, depth, true)); - // Lanczos, kept within the source pixels around each sample (#14794), sharpened and kept - // within them again. - let mut resized = resize_surface(&s, sx, sy, Resample::Lanczos); - crate::resample::dering(&mut resized, &s, sx, sy, None); - let radius = (crate::resample::PD_RADIUS * sx.max(sy)) as f32; - let p = crate::FilterParams::UnsharpMask { amount: crate::resample::PD_AMOUNT, radius, threshold: 0.0 }; + let resized = resize_surface(&s, sx, sy, Resample::Lanczos); + let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 }; let area = crate::output_area(&p, resized.content_bounds(), dst, None); - let mut expected = apply_reference(&resized, &p, area, dst, None, None, crate::auto_tile(&p, dst)); - crate::resample::dering(&mut expected, &s, sx, sy, None); + let expected = apply_reference(&resized, &p, area, dst, None, None, crate::auto_tile(&p, dst)); let actual = resize_surface(&s, sx, sy, Resample::PreserveDetails); assert_eq!(actual.to_interleaved(area), expected.to_interleaved(area)); } From 4a8374298acda0ca6907f8b120198507bd964de2 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:07:47 +0100 Subject: [PATCH 3/3] Dering only the columns read, and read beyond the content as the default pixel Preserve Details' deringing (#14794) now reads only the source columns the output samples use instead of the whole canvas width, so a small layer on a wide canvas no longer pays for every canvas column; results are unchanged. Without a canvas, positions just outside the content read the default pixel, as the resize does, so an opaque layer's partly transparent fringe is no longer forced opaque. --- crates/algo/src/resample.rs | 34 +++++++++++++++---- .../resample/preserve_details_edge_tests.rs | 34 +++++++++++++++++++ 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs index b38e14ad4e..cd3f67250e 100644 --- a/crates/algo/src/resample.rs +++ b/crates/algo/src/resample.rs @@ -452,14 +452,20 @@ pub(crate) const PD_RADIUS: f64 = 0.6; /// Keeps each sample of `out` (a resize of `src` by `(sx, sy)`) within the range of the two by /// two source pixels around its source position, channel by channel. Colour channels only count /// the source pixels that are not fully transparent. Source positions are clamped into the area -/// the resize reads (the content, or with `canvas` that and the canvas). +/// the resize reads: with `canvas` the content and the canvas, whose edges repeat outwards; +/// without, the content and one pixel around it, since beyond the content the resize reads the +/// default pixel (so an opaque layer's partly transparent fringe stays so). /// /// Source rows are read one at a time, whatever the scale, and bands of output rows are written /// a group at a time, like [`resize_pass`], so memory stays bounded. pub(crate) fn dering(out: &mut Surface, src: &Surface, sx: f64, sy: f64, canvas: Option) { let dst = out.content_bounds(); let content = src.content_bounds(); - let area = canvas.map_or(content, |c| content.union(&c)); + let area = match canvas { + Some(c) => content.union(&c), + None if content.is_empty() => content, + None => content.inflate(1), + }; if dst.is_empty() || area.is_empty() || !(sx > 0.0 && sy > 0.0) { return; } @@ -473,14 +479,25 @@ pub(crate) fn dering(out: &mut Surface, src: &Surface, sx: f64, sy: f64, canvas: let i1 = ((u + 1.0).clamp(f64::from(lo), f64::from(hi)) as i32 - lo) as usize; (i0, i1) }; - let xs: Vec<(usize, usize)> = (dst.x0..dst.x1).map(|o| pair(o, sx, area.x0, area.x1 - 1)).collect(); - let sw = area.width() as usize * n; - // Source row `k` of the area (as `pair` indexes it) into `buf`. + let mut xs: Vec<(usize, usize)> = (dst.x0..dst.x1).map(|o| pair(o, sx, area.x0, area.x1 - 1)).collect(); + // Only the source columns the output reads (a small layer on a wide canvas reads a few), with + // `xs` rebased to them. + let c0 = xs.iter().map(|&(a, _)| a).min().unwrap_or(0); + let c1 = xs.iter().map(|&(_, b)| b + 1).max().unwrap_or(c0); + for (a, b) in &mut xs { + (*a, *b) = (*a - c0, *b - c0); + } + let sw = (c1 - c0) * n; + let x0 = area.x0.saturating_add(i32::try_from(c0).unwrap_or(i32::MAX)); + let x1 = area.x0.saturating_add(i32::try_from(c1).unwrap_or(i32::MAX)); + // Source row `k` of the area (as `pair` indexes it), columns `c0..c1`, into `buf`. let read_row = |k: usize, buf: &mut Vec| { let y = area.y0.saturating_add(i32::try_from(k).unwrap_or(i32::MAX)); - let r = Rect::new(area.x0, y, area.x1, y.saturating_add(1)); + let r = Rect::new(x0, y, x1, y.saturating_add(1)); #[cfg(test)] DERING_MAX_READ_ROWS.fetch_max(r.height() as usize, std::sync::atomic::Ordering::Relaxed); + #[cfg(test)] + DERING_READ_COLUMNS.with(|c| c.set(c.get().max(r.width() as usize))); src.read_region_into(r, buf); }; let band = |out: &Surface, b: usize| -> (Rect, Vec) { @@ -575,6 +592,11 @@ type SourceRow = (Option, Vec); #[cfg(test)] pub(crate) static DERING_MAX_READ_ROWS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); #[cfg(test)] +thread_local! { + /// The most source columns one read of [`dering`] has spanned on this thread. + pub(crate) static DERING_READ_COLUMNS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} +#[cfg(test)] pub(crate) static DERING_MAX_HELD_BANDS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// Output rows computed together by [`PassState::band`]. diff --git a/crates/algo/src/resample/preserve_details_edge_tests.rs b/crates/algo/src/resample/preserve_details_edge_tests.rs index f043199cd1..463d0aede7 100644 --- a/crates/algo/src/resample/preserve_details_edge_tests.rs +++ b/crates/algo/src/resample/preserve_details_edge_tests.rs @@ -203,3 +203,37 @@ fn dering_holds_a_bounded_group_of_bands() { let group = rayon::current_num_threads().max(1) * 2; assert!(held <= group, "dering held {held} of {} bands at once (group {group})", 12800usize.div_ceil(BAND)); } + +/// Without a canvas, positions outside the content read the default pixel, as the resize does: +/// an opaque square on transparency keeps its partly transparent fringe instead of the clamp +/// making it opaque, and the result equals the one in a canvas of transparency around it. +#[test] +fn enlarging_without_a_canvas_keeps_the_transparent_fringe() { + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); + s.fill_rect(Rect::new(10, 10, 30, 30), &[0.2, 0.6, 1.0, 1.0]); + let o = resize_surface(&s, 2.0, 2.0, Resample::PreserveDetails); + // The square's first output column: Lanczos leaves it partly transparent (about 0.79). + let fringe = o.pixel(20, 40)[3]; + assert!(fringe > 0.0 && fringe < 1.0, "alpha {fringe} on the square's edge"); + let framed = resize_surface_in_canvas(&s, 2.0, 2.0, Resample::PreserveDetails, CANVAS); + let r = o.content_bounds().union(&framed.content_bounds()); + assert!(o.read_region(r) == framed.read_region(r), "differs from the same square in a transparent canvas"); +} + +/// With a canvas much wider than the layer, dering reads only the source columns the output +/// samples use, not the whole canvas width. +#[test] +fn dering_reads_only_the_columns_it_uses() { + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); + s.fill_rect(Rect::new(1000, 10, 1020, 30), &[0.2, 0.6, 1.0, 1.0]); + let canvas = Rect::new(0, 0, 20_000, 40); + let mut o = resize_surface_in_canvas(&s, 2.0, 2.0, Resample::Lanczos, canvas); + // One worker thread, so the thread-local counter sees every read. + let pool = rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap(); + let cols = pool.install(|| { + DERING_READ_COLUMNS.with(|c| c.set(0)); + dering(&mut o, &s, 2.0, 2.0, Some(canvas)); + DERING_READ_COLUMNS.with(std::cell::Cell::get) + }); + assert!(cols <= 40, "one dering read spanned {cols} source columns"); +}