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)); }