PhotoCraft: An open-source, photo editor written by scratch in pure Rust
perf(compose): stop sweeping the bounds cache on every call once it is large (#4415)
SckraTbe43d58f1a1c
diff --git a/crates/compose/src/bounds.rs b/crates/compose/src/bounds.rsindex 1055487f1..985a400e0 100644--- a/crates/compose/src/bounds.rs+++ b/crates/compose/src/bounds.rs@@ -5,7 +5,7 @@use std::collections::HashMap;use std::sync::{Arc, Mutex, Weak};-use photocraft_geom::{Rect, TILE_SIZE};+use photocraft_geom::Rect;use photocraft_raster::{Surface, Tile};struct Entry {@@ -15,25 +15,23 @@ struct Entry {bounds: Option<(u16, u16, u16, u16)>,}-fn cache() -> &'static Mutex<HashMap<usize, Entry>> {- static C: std::sync::OnceLock<Mutex<HashMap<usize, Entry>>> = std::sync::OnceLock::new();- C.get_or_init(Default::default)+/// The entries, and the size past which dead ones are dropped (see [`next_sweep`]).+struct Cache {+ entries: HashMap<usize, Entry>,+ sweep_at: usize,}-/// Pixels of `t` that differ from `dp` (tile-local half-open bounds).-fn scan(t: &Tile, dp: &[u8]) -> Option<(u16, u16, u16, u16)> {- let bpp = dp.len();- let ts = TILE_SIZE as usize;- let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize);- for (y, row) in t.bytes().chunks_exact(ts * bpp).enumerate() {- let Some(first) = row.chunks_exact(bpp).position(|px| px != dp) else { continue };- let last = ts - 1 - row.chunks_exact(bpp).rev().position(|px| px != dp).unwrap_or(0);- x0 = x0.min(first);- x1 = x1.max(last + 1);- y0 = y0.min(y);- y1 = y + 1;- }- (x0 != usize::MAX).then_some((x0 as u16, y0 as u16, x1 as u16, y1 as u16))+const MIN_SWEEP: usize = 1 << 16;++/// The size at which to sweep again after a sweep left `survivors` live entries: twice that (at+/// least [`MIN_SWEEP`]), so a cache full of live tiles isn't swept again on every call.+fn next_sweep(survivors: usize) -> usize {+ survivors.saturating_mul(2).max(MIN_SWEEP)+}++fn cache() -> &'static Mutex<Cache> {+ static C: std::sync::OnceLock<Mutex<Cache>> = std::sync::OnceLock::new();+ C.get_or_init(|| Mutex::new(Cache { entries: HashMap::new(), sweep_at: MIN_SWEEP }))}/// `Surface::content_bounds`, cached per tile.@@ -45,18 +43,19 @@ pub fn content_bounds(s: &Surface) -> Rect {let mut dp = vec![0u8; fmt.bytes_per_pixel()];photocraft_raster::encode_pixel(&fmt, &s.default_pixel(), &mut dp);let mut c = cache().lock().unwrap_or_else(|e| e.into_inner());- if c.len() > 1 << 16 {- c.retain(|_, e| e.tile.strong_count() > 0);+ if c.entries.len() > c.sweep_at {+ c.entries.retain(|_, e| e.tile.strong_count() > 0);+ c.sweep_at = next_sweep(c.entries.len());}let mut out = Rect::EMPTY;for (coord, t) in s.tiles() {let key = Arc::as_ptr(t) as usize;- let hit = c.get(&key).filter(|e| e.tile.upgrade().is_some_and(|u| Arc::ptr_eq(&u, t)) && *e.default == *dp).map(|e| e.bounds);+ let hit = c.entries.get(&key).filter(|e| e.tile.upgrade().is_some_and(|u| Arc::ptr_eq(&u, t)) && *e.default == *dp).map(|e| e.bounds);let b = match hit {Some(b) => b,None => {- let b = scan(t, &dp);- c.insert(key, Entry { tile: Arc::downgrade(t), default: dp.clone().into_boxed_slice(), bounds: b });+ let b = t.content_bounds(&dp);+ c.entries.insert(key, Entry { tile: Arc::downgrade(t), default: dp.clone().into_boxed_slice(), bounds: b });b}};@@ -68,3 +67,25 @@ pub fn content_bounds(s: &Surface) -> Rect {}out}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn sweeps_again_only_past_twice_the_survivors() {+ // A cache of live tiles past the minimum isn't swept on every call (it used to be).+ assert_eq!(next_sweep(0), MIN_SWEEP);+ assert_eq!(next_sweep(MIN_SWEEP / 2), MIN_SWEEP);+ assert_eq!(next_sweep(MIN_SWEEP), 2 * MIN_SWEEP);+ assert_eq!(next_sweep(usize::MAX), usize::MAX);+ }++ #[test]+ fn a_shared_tile_reads_the_same_bounds_at_every_coordinate() {+ let mut s = Surface::new(photocraft_color::PixelFormat::RGBA8);+ s.fill_rect(Rect::new(-300, 10, 1300, 900), &[0.2, 0.4, 0.6, 1.0]);+ assert_eq!(content_bounds(&s), Rect::new(-300, 10, 1300, 900));+ assert_eq!(content_bounds(&s), s.content_bounds(), "cached");+ }+}diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rsindex 74a587012..2d2d26b2d 100644--- a/crates/raster/src/lib.rs+++ b/crates/raster/src/lib.rs@@ -81,6 +81,27 @@ impl Tile {pub fn bytes_mut(&mut self) -> &mut [u8] {&mut self.data}++ /// Tile-local half-open bounds `(x0, y0, x1, y1)` of the pixels that differ from the encoded+ /// pixel `dp` (one pixel of the tile's format), or `None` when every pixel equals it (or `dp`+ /// is empty).+ pub fn content_bounds(&self, dp: &[u8]) -> Option<(u16, u16, u16, u16)> {+ let bpp = dp.len();+ if bpp == 0 {+ return None;+ }+ let ts = TILE_SIZE as usize;+ let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize);+ for (y, row) in self.data.chunks_exact(ts * bpp).enumerate() {+ let Some(first) = row.chunks_exact(bpp).position(|px| px != dp) else { continue };+ let last = ts - 1 - row.chunks_exact(bpp).rev().position(|px| px != dp).unwrap_or(0);+ x0 = x0.min(first);+ x1 = x1.max(last + 1);+ y0 = y0.min(y);+ y1 = y + 1;+ }+ (x0 != usize::MAX).then_some((x0 as u16, y0 as u16, x1 as u16, y1 as u16))+ }}#[derive(Clone, Debug)]@@ -265,7 +286,6 @@ impl Surface {/// Exact bounds of pixels that differ from the default pixel.pub fn content_bounds(&self) -> Rect {- let bpp = self.format.bytes_per_pixel();if self.tiles.is_empty() {return Rect::EMPTY;}@@ -278,25 +298,14 @@ impl Surface {}let mut order: Vec<(&TileCoord, &Arc<Tile>)> = self.tiles.iter().collect();order.sort_by_key(|(c, _)| (c.tx - gx0).min(gx1 - c.tx).min(c.ty - gy0).min(gy1 - c.ty));- let dp = &*self.default_pixel;- let ts = TILE_SIZE as usize;let mut out = Rect::EMPTY;for (c, t) in order {let origin = c.rect();if !out.is_empty() && out.contains_rect(&origin) {continue;}- let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize);- for (y, row) in t.data.chunks_exact(ts * bpp).enumerate() {- let Some(first) = row.chunks_exact(bpp).position(|px| px != dp) else { continue };- let last = ts - 1 - row.chunks_exact(bpp).rev().position(|px| px != dp).unwrap_or(0);- x0 = x0.min(first);- x1 = x1.max(last + 1);- y0 = y0.min(y);- y1 = y + 1;- }- if x0 != usize::MAX {- out = out.union(&Rect::new(x0 as i32, y0 as i32, x1 as i32, y1 as i32).translate(origin.x0, origin.y0));+ if let Some((x0, y0, x1, y1)) = t.content_bounds(&self.default_pixel) {+ out = out.union(&Rect::new(x0.into(), y0.into(), x1.into(), y1.into()).translate(origin.x0, origin.y0));}}out@@ -1246,6 +1255,18 @@ mod tests {}}+ #[test]+ fn tile_content_bounds_scans_against_the_given_pixel() {+ let mut s = Surface::new(PixelFormat::GRAY8);+ s.write_pixel(3, 4, &[1.0]);+ s.write_pixel(200, 9, &[1.0]);+ let t = s.tile(TileCoord::new(0, 0)).expect("written tile");+ assert_eq!(t.content_bounds(&[0]), Some((3, 4, 201, 10)));+ assert_eq!(t.content_bounds(&[255]).map(|b| (b.0, b.1)), Some((0, 0)));+ // A malformed pixel is no content, not a panic.+ assert_eq!(t.content_bounds(&[]), None);+ }+#[test]fn translated_matches_reading_the_moved_pixels() {// Any offset (whole tiles, negative, across tile edges), every depth, a non-zero default.