From e66ca23a722fe8b874bb85e52afa7159942cfa1c Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Thu, 29 Oct 2026 18:53:32 +0530 Subject: [PATCH] Resizing can run in resumable steps of 64 output rows --- crates/algo/src/resample.rs | 241 +++++++++++++++++++++++------- crates/algo/src/resample/tests.rs | 97 ++++++++++++ 2 files changed, 284 insertions(+), 54 deletions(-) diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs index a0c363732a..110339cfad 100644 --- a/crates/algo/src/resample.rs +++ b/crates/algo/src/resample.rs @@ -393,62 +393,105 @@ 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 = cur.unwrap_or_else(|| s.clone()); + let mut out = preserve_details(cur.unwrap_or_else(|| s.clone()), filter, sx, sy); + 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) { 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); out = crate::apply(&out, &p, area, dst, None); } - out.prune(); out } -/// One pass. With `canvas`, the content and the canvas repeat their edge outwards (see -/// [`resize_surface_in_canvas`]). -fn resize_pass(s: &Surface, pass: Pass, canvas: Option, budget: usize, ctl: &photocraft_raster::Interrupt) -> Surface { - let Pass { sx, sy, kx, ky } = pass; - let edge = canvas.map(|c| s.content_bounds().union(&c)).filter(|a| !a.is_empty()); - let fmt = s.format(); - let mut out = Surface::with_default(fmt, &s.default_pixel()); - let src = s.content_bounds(); - let dst = scaled_rect(src, sx, sy); - if dst.is_empty() { - return out; +/// Output rows computed together by [`PassState::band`]. +const BAND: usize = 64; + +/// One pass prepared: its taps and the constants every band needs. [`PassState::band`] computes +/// one band of output rows from the source, so the parallel loop of [`resize_pass`] and +/// [`ResizeSteps`] run the same code and give the same pixels. +struct PassState { + n: usize, + alpha: bool, + /// The output extent. + dst: Rect, + /// The area every tap is clamped into (the source's content, or with a canvas that and the canvas). + area: Rect, + hx: Vec, + vy: Vec, + x_lo: i32, + x_hi: i32, + def: Vec, + /// A source row of nothing but the default pixel, after the horizontal pass. + def_row: Vec, + rows_per_read: i32, +} + +impl PassState { + /// Prepares `pass` over `s`; `None` when the output is empty. With `canvas`, the content and + /// the canvas repeat their edge outwards (see [`resize_surface_in_canvas`]). + fn new(s: &Surface, pass: Pass, canvas: Option, budget: usize) -> Option { + let Pass { sx, sy, kx, ky } = pass; + let edge = canvas.map(|c| s.content_bounds().union(&c)).filter(|a| !a.is_empty()); + let fmt = s.format(); + let src = s.content_bounds(); + let dst = scaled_rect(src, sx, sy); + if dst.is_empty() { + return None; + } + let n = fmt.channels(); + let alpha = fmt.alpha; + // With `edge`, every tap is clamped into the edge area, which holds the content. + let area = edge.unwrap_or(src); + let hx = taps(dst.x0, dst.x1, sx, kx, edge.map(|r| (r.x0, r.x1 - 1)), (area.x0, area.x1 - 1)); + let vy = taps(dst.y0, dst.y1, sy, ky, edge.map(|r| (r.y0, r.y1 - 1)), (area.y0, area.y1 - 1)); + let x_lo = hx.iter().filter(|t| !t.weights.is_empty()).map(|t| t.start).min().unwrap_or(area.x0); + let x_hi = hx.iter().map(|t| t.start + t.weights.len() as i32).max().unwrap_or(area.x0).max(x_lo); + let mut def = s.default_pixel(); + premultiply(&mut def, n, alpha); + let dw = dst.width() as usize; + let mut st = Self { n, alpha, dst, area, hx, vy, x_lo, x_hi, def, def_row: Vec::new(), rows_per_read: 1 }; + st.def_row = { + let row: Vec = st.def.iter().copied().cycle().take((x_hi - x_lo) as usize * n).collect(); + let mut out = vec![0.0f32; dw * n]; + st.horizontal(&row, &mut out); + out + }; + // At most one tile row per read anyway, so this always fits an `i32`. + st.rows_per_read = (budget / ((x_hi - x_lo).max(1) as usize * n).max(dw * n)).clamp(1, TILE_SIZE as usize) as i32; + Some(st) } - let n = fmt.channels(); - let alpha = fmt.alpha; - // With `edge`, every tap is clamped into the edge area, which holds the content. - let area = edge.unwrap_or(src); - let hx = taps(dst.x0, dst.x1, sx, kx, edge.map(|r| (r.x0, r.x1 - 1)), (area.x0, area.x1 - 1)); - let vy = taps(dst.y0, dst.y1, sy, ky, edge.map(|r| (r.y0, r.y1 - 1)), (area.y0, area.y1 - 1)); - let x_lo = hx.iter().filter(|t| !t.weights.is_empty()).map(|t| t.start).min().unwrap_or(area.x0); - let x_hi = hx.iter().map(|t| t.start + t.weights.len() as i32).max().unwrap_or(area.x0).max(x_lo); - let mut def = s.default_pixel(); - premultiply(&mut def, n, alpha); - let dw = dst.width() as usize; - const BAND: usize = 64; - let bands: Vec<(usize, usize)> = (0..vy.len()).step_by(BAND).map(|b| (b, (b + BAND).min(vy.len()))).collect(); - // Horizontal pass of one source row (`row` spans `x_lo..x_hi`) into `dw` samples. - let horizontal = |row: &[f32], out: &mut [f32]| match n { - 1 => horizontal_fixed::<1>(row, out, &hx, x_lo, &def), - 2 => horizontal_fixed::<2>(row, out, &hx, x_lo, &def), - 3 => horizontal_fixed::<3>(row, out, &hx, x_lo, &def), - 4 => horizontal_fixed::<4>(row, out, &hx, x_lo, &def), - 5 => horizontal_fixed::<5>(row, out, &hx, x_lo, &def), - _ => horizontal_dynamic(row, out, &hx, x_lo, &def, n), - }; - // A source row of nothing but the default pixel, after the horizontal pass. - let def_row = { - let row: Vec = def.iter().copied().cycle().take((x_hi - x_lo) as usize * n).collect(); - let mut out = vec![0.0f32; dw * n]; - horizontal(&row, &mut out); - out - }; - // At most one tile row per read anyway, so this always fits an `i32`. - let rows_per_read = (budget / ((x_hi - x_lo).max(1) as usize * n).max(dw * n)).clamp(1, TILE_SIZE as usize) as i32; - let run = |&(b0, b1): &(usize, usize)| -> (Rect, Vec) { - let band = vy.get(b0..b1).unwrap_or(&[]); + + /// How many bands of [`BAND`] output rows the pass has. + fn bands(&self) -> usize { + self.vy.len().div_ceil(BAND) + } + + /// Horizontal pass of one source row (`row` spans `x_lo..x_hi`) into `dw` samples. + fn horizontal(&self, row: &[f32], out: &mut [f32]) { + let (hx, x_lo, def) = (&self.hx, self.x_lo, &self.def); + match self.n { + 1 => horizontal_fixed::<1>(row, out, hx, x_lo, def), + 2 => horizontal_fixed::<2>(row, out, hx, x_lo, def), + 3 => horizontal_fixed::<3>(row, out, hx, x_lo, def), + 4 => horizontal_fixed::<4>(row, out, hx, x_lo, def), + 5 => horizontal_fixed::<5>(row, out, hx, x_lo, def), + _ => horizontal_dynamic(row, out, hx, x_lo, def, self.n), + } + } + + /// Band `b` of the output: its rectangle and samples, from the pass's source `s`. + fn band(&self, s: &Surface, b: usize) -> (Rect, Vec) { + let (n, alpha, area, dst, x_lo, x_hi) = (self.n, self.alpha, self.area, self.dst, self.x_lo, self.x_hi); + let dw = dst.width() as usize; + let (b0, b1) = (b * BAND, ((b + 1) * BAND).min(self.vy.len())); + let band = self.vy.get(b0..b1).unwrap_or(&[]); let y_lo = band.iter().filter(|t| !t.weights.is_empty()).map(|t| t.start).min().unwrap_or(area.y0); let y_hi = band.iter().map(|t| t.start + t.weights.len() as i32).max().unwrap_or(area.y0).max(y_lo); let mut res = vec![0.0f32; band.len() * dw * n]; @@ -472,7 +515,7 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option, budget: usize, ctl if s.has_tiles_in(Rect::new(x_lo, y, x_hi, y1)) { let mut c0 = y; while c0 < y1 { - let c1 = (c0 + rows_per_read).min(y1); + let c1 = (c0 + self.rows_per_read).min(y1); let read = Rect::new(x_lo, c0, x_hi, c1); s.read_region_into(read, &mut rows); premultiply(&mut rows, n, alpha); @@ -480,7 +523,7 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option, budget: usize, ctl hrows.resize((c1 - c0) as usize * dw * n, 0.0); let rw = read.width() as usize * n; for (row, out) in rows.chunks_exact(rw.max(1)).zip(hrows.chunks_exact_mut(dw * n)) { - horizontal(row, out); + self.horizontal(row, out); } for (r, h) in (c0..c1).zip(hrows.chunks_exact(dw * n)) { add(&mut res, r, h); @@ -494,7 +537,7 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option, budget: usize, ctl let (a, b) = ((y - t.start).max(0) as usize, (y1 - t.start).max(0) as usize); let w: f32 = t.weights.get(a.min(t.weights.len())..b.min(t.weights.len())).unwrap_or(&[]).iter().sum(); if w != 0.0 { - for (dv, sv) in d.iter_mut().zip(&def_row) { + for (dv, sv) in d.iter_mut().zip(&self.def_row) { *dv += sv * w; } } @@ -503,7 +546,7 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option, budget: usize, ctl y = y1; } for (t, d) in band.iter().zip(res.chunks_exact_mut(dw * n)) { - for (dv, sv) in d.iter_mut().zip(&def_row) { + for (dv, sv) in d.iter_mut().zip(&self.def_row) { *dv += sv * t.outside; } } @@ -514,7 +557,15 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option, budget: usize, ctl } unpremultiply(&mut res, n, alpha); (Rect::new(dst.x0, dst.y0 + b0 as i32, dst.x1, dst.y0 + b1 as i32), res) - }; + } +} + +/// One pass. With `canvas`, the content and the canvas repeat their edge outwards (see +/// [`resize_surface_in_canvas`]). +fn resize_pass(s: &Surface, pass: Pass, canvas: Option, budget: usize, ctl: &photocraft_raster::Interrupt) -> Surface { + let mut out = Surface::with_default(s.format(), &s.default_pixel()); + let Some(st) = PassState::new(s, pass, canvas, budget) else { return out }; + let bands: Vec = (0..st.bands()).collect(); // Bands go into the output a group at a time, so the `f32` rows held at once are bounded by // the group, not by the whole destination (#1544). #[cfg(not(target_arch = "wasm32"))] @@ -523,15 +574,15 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option, budget: usize, ctl let group = 1; for chunk in bands.chunks(group) { if ctl.cancelled() { - return Surface::new(fmt); + return Surface::new(s.format()); } #[cfg(not(target_arch = "wasm32"))] let parts: Vec<(Rect, Vec)> = { use rayon::prelude::*; - chunk.par_iter().map(run).collect() + chunk.par_iter().map(|&b| st.band(s, b)).collect() }; #[cfg(target_arch = "wasm32")] - let parts: Vec<(Rect, Vec)> = chunk.iter().map(run).collect(); + let parts: Vec<(Rect, Vec)> = chunk.iter().map(|&b| st.band(s, b)).collect(); for (r, d) in parts { out.write_region(r, &d); } @@ -539,6 +590,88 @@ fn resize_pass(s: &Surface, pass: Pass, canvas: Option, budget: usize, ctl out } +/// [`resize_surface`] (or, with a canvas, [`resize_surface_in_canvas`]) in resumable steps, for a +/// caller that cannot block, such as the web build with no threads: [`ResizeSteps::step`] computes +/// bands of output rows until the caller says to stop, and returns the surface once they are all +/// done. It runs [`resize_with_budget`]'s passes and [`resize_pass`]'s bands through the same +/// code, so its result equals [`resize_surface`]'s. +pub struct ResizeSteps { + /// The current pass's source: the input, then each pass's output. + src: Surface, + passes: std::vec::IntoIter, + total: usize, + canvas: Option, + filter: Resample, + scale: (f64, f64), + run: Option, +} + +/// The pass being computed by [`ResizeSteps`]. +struct PassRun { + pass: Pass, + state: PassState, + out: Surface, + next: usize, +} + +impl ResizeSteps { + /// Resizes `src` by `(sx, sy)` about the document origin, as [`resize_surface`] (no `canvas`) + /// 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 } + } + + /// How far along it is, `0.0..=1.0`: whole passes plus the bands done of the current one. + pub fn progress(&self) -> f32 { + let done = self.total.saturating_sub(self.passes.len() + usize::from(self.run.is_some())); + let part = self.run.as_ref().map_or(0.0, |r| r.next as f32 / r.state.bands().max(1) as f32); + ((done as f32 + part) / self.total.max(1) as f32).clamp(0.0, 1.0) + } + + /// Does at least one unit of work (planning a pass, one band of 64 output rows, or the + /// closing step) and goes on while `more()` returns true. `Some` once the resize is done. + pub fn step(&mut self, more: &mut dyn FnMut() -> bool) -> Option { + loop { + match self.run.take() { + None => { + let Some(pass) = self.passes.next() else { return Some(self.finish()) }; + let out = Surface::with_default(self.src.format(), &self.src.default_pixel()); + match PassState::new(&self.src, pass, self.canvas, READ_BUDGET) { + Some(state) => self.run = Some(PassRun { pass, state, out, next: 0 }), + None => self.advance(out, pass), + } + } + Some(mut run) if run.next < run.state.bands() => { + let (r, data) = run.state.band(&self.src, run.next); + run.out.write_region(r, &data); + run.next += 1; + self.run = Some(run); + } + Some(run) => self.advance(run.out, run.pass), + } + if !more() { + return None; + } + } + } + + /// The next pass reads this one's output. + fn advance(&mut self, out: Surface, pass: Pass) { + self.canvas = self.canvas.map(|c| scaled_rect(c, pass.sx, pass.sy)); + self.src = out; + } + + /// The last pass's output, finished as [`resize_with_budget`] finishes it. + fn finish(&mut self) -> Surface { + let placeholder = Surface::new(self.src.format()); + let mut out = std::mem::replace(&mut self.src, placeholder); + out = preserve_details(out, self.filter, self.scale.0, self.scale.1); + out.prune(); + out + } +} + /// Moves a surface by whole pixels (default pixel kept). pub fn translate_surface(s: &Surface, dx: i32, dy: i32) -> Surface { s.translated(dx, dy, s.content_bounds()) diff --git a/crates/algo/src/resample/tests.rs b/crates/algo/src/resample/tests.rs index 2407457a2d..61245f87e7 100644 --- a/crates/algo/src/resample/tests.rs +++ b/crates/algo/src/resample/tests.rs @@ -434,3 +434,100 @@ fn controlled_resize_matches_pixels_and_discards_cancelled_work() { assert!(resize_surface_with_interrupt(&src, 1.7, 0.6, Resample::Bicubic, &ctl).is_err()); } } + +/// A pseudo-random surface of `w`×`h` in a format of `mode`, `sample` and `alpha`. +fn noisy(w: i32, h: i32, mode: ColorMode, sample: SampleType, alpha: bool) -> Surface { + let fmt = PixelFormat::new(mode, sample, alpha); + let n = fmt.channels(); + let mut seed = 0x2545_f491u32; + let v: Vec = (0..w as usize * h as usize * n) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 + }) + .collect(); + let mut s = Surface::new(fmt); + s.write_region(Rect::new(0, 0, w, h), &v); + s +} + +/// Drives `steps` to the end, `per_call` units of work at a time (0: unlimited); returns the +/// surface and how many calls it took. +fn drive(mut steps: ResizeSteps, per_call: usize) -> (Surface, usize) { + let mut calls = 0; + loop { + calls += 1; + let mut left = per_call; + let mut more = || { + left = left.wrapping_sub(1); + per_call == 0 || left > 0 + }; + if let Some(s) = steps.step(&mut more) { + return (s, calls); + } + assert!(calls < 10_000, "the resize never finished"); + } +} + +#[test] +fn steps_equal_resize_surface() { + let cases = [ + (SampleType::U8, ColorMode::Rgb, true), + (SampleType::U16, ColorMode::Rgb, false), + (SampleType::F32, ColorMode::Rgb, true), + (SampleType::U8, ColorMode::Grayscale, true), + ]; + for (sample, mode, alpha) in cases { + let src = noisy(150, 130, mode, sample, alpha); + // Up, down, one axis each way, and enough output rows for several bands. + for (sx, sy) in [(0.6, 0.6), (1.7, 1.7), (0.4, 2.2), (1.0, 0.5)] { + for filter in [Resample::Bicubic, Resample::Lanczos, Resample::BicubicAutomatic, Resample::Nearest] { + let expected = resize_surface(&src, sx, sy, filter); + for per_call in [0, 1, 7] { + let (got, _) = drive(ResizeSteps::new(src.clone(), sx, sy, filter, None), per_call); + assert!(got == expected, "{sample:?} {mode:?} alpha={alpha} scale=({sx}, {sy}) {filter:?} per_call={per_call}"); + } + } + } + } +} + +#[test] +fn steps_equal_resize_surface_in_canvas() { + let src = noisy(90, 70, ColorMode::Rgb, SampleType::U8, true); + let canvas = Rect::new(0, 0, 90, 70); + for (sx, sy) in [(0.7, 0.7), (1.9, 1.3)] { + let expected = resize_surface_in_canvas(&src, sx, sy, Resample::Bicubic, canvas); + let (got, _) = drive(ResizeSteps::new(src.clone(), sx, sy, Resample::Bicubic, Some(canvas)), 1); + assert!(got == expected, "scale=({sx}, {sy})"); + } +} + +#[test] +fn steps_take_several_calls_and_report_progress() { + let src = noisy(120, 300, ColorMode::Rgb, SampleType::U8, true); + let mut steps = ResizeSteps::new(src, 0.9, 0.9, Resample::Bicubic, None); + assert_eq!(steps.progress(), 0.0); + let mut seen = Vec::new(); + let mut calls = 0; + let out = loop { + calls += 1; + if let Some(s) = steps.step(&mut || false) { + break s; + } + seen.push(steps.progress()); + }; + // Planning, one call per 64-row band (270 rows: five), and the closing call. + assert!(calls >= 6, "{calls}"); + assert!(seen.windows(2).all(|w| w[0] <= w[1]), "progress goes back: {seen:?}"); + assert!(seen.iter().all(|p| (0.0..=1.0).contains(p))); + assert_eq!(out.content_bounds(), Rect::new(0, 0, 108, 270)); +} + +#[test] +fn steps_of_an_empty_surface_are_empty() { + let src = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); + let expected = resize_surface(&src, 0.5, 0.5, Resample::Bicubic); + let (got, _) = drive(ResizeSteps::new(src, 0.5, 0.5, Resample::Bicubic, None), 1); + assert!(got == expected); +}