Skip to content

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

PSD plane shuffles in bands; the document histogram computes off the UI thread (#1185)

Elvis33LE077888ea0345
diff --git a/crates/io/examples/bench_shuffles.rs b/crates/io/examples/bench_shuffles.rs
new file mode 100644
index 000000000..9bd29fece
--- /dev/null
+++ b/crates/io/examples/bench_shuffles.rs
@@ -0,0 +1,54 @@
+//! BEFORE/AFTER helper for the banded interleave/deinterleave: `--serial` runs the old
+//! sequential implementation inline, the default runs the current parallel one.
+fn main() {
+ use photocraft_color::SampleType;
+ let serial = std::env::args().any(|a| a == "--serial");
+ for (label, s, ch) in [("u16 rgb", SampleType::U16, 3usize), ("f32 rgba", SampleType::F32, 4)] {
+ let bps = s.bytes();
+ let n = 20_000_000usize;
+ let planes: Vec<Vec<u8>> = (0..ch).map(|c| (0..n * bps).map(|i| (i * 7 + c) as u8).collect()).collect();
+ let refs: Vec<Option<&[u8]>> = planes.iter().map(|p| Some(&p[..])).collect();
+ let fill: Vec<Vec<u8>> = (0..ch).map(|_| vec![0u8; bps]).collect();
+ let invert = [false; 4];
+ let t0 = std::time::Instant::now();
+ let interleaved = if serial {
+ let mut out = vec![0u8; n * ch * bps];
+ for (c, plane) in refs.iter().enumerate() {
+ for i in 0..n {
+ let dst = &mut out[(i * ch + c) * bps..(i * ch + c + 1) * bps];
+ if let Some(p) = plane
+ && p.len() >= (i + 1) * bps
+ {
+ let src = &p[i * bps..(i + 1) * bps];
+ for k in 0..bps {
+ dst[k] = src[bps - 1 - k];
+ }
+ }
+ }
+ }
+ out
+ } else {
+ photocraft_io::pixels::interleave(&refs, &fill, n, s, &invert)
+ };
+ let t1 = t0.elapsed().as_secs_f64() * 1000.0;
+ let t2 = std::time::Instant::now();
+ if serial {
+ let mut acc: Vec<Vec<u8>> = Vec::new();
+ for _ in 0..ch {
+ acc.push(Vec::with_capacity(n * bps));
+ }
+ let mut tmp = [0u8; 4];
+ for i in 0..n {
+ for (c, plane) in acc.iter_mut().enumerate() {
+ let src = &interleaved[(i * ch + c) * bps..(i * ch + c + 1) * bps];
+ tmp[..bps].copy_from_slice(src);
+ plane.extend(tmp[..bps].iter().rev());
+ }
+ }
+ } else {
+ let _ = photocraft_io::pixels::deinterleave(&interleaved, ch, s, &invert);
+ }
+ let t3 = t2.elapsed().as_secs_f64() * 1000.0;
+ println!("{label}: interleave {t1:.1} ms, deinterleave {t3:.1} ms (20 MP, release, {})", if serial { "serial (before)" } else { "parallel (after)" });
+ }
+}
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 4cd40d795..beb91a1e8 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -35,7 +35,7 @@ mod gradient_bake;
pub mod linked;
mod multichannel_map;
pub mod pattern_map;
-mod pixels;
+pub mod pixels;
mod psd_export;
mod psd_import;
pub mod raw;
diff --git a/crates/io/src/pixels.rs b/crates/io/src/pixels.rs
index 6362cca56..0167eb3b3 100644
--- a/crates/io/src/pixels.rs
+++ b/crates/io/src/pixels.rs
@@ -41,26 +41,38 @@ fn invert_sample(bytes: &mut [u8], s: SampleType) {
pub fn interleave(planes: &[Option<&[u8]>], fill: &[Vec<u8>], n: usize, s: SampleType, invert: &[bool]) -> Vec<u8> {
let bps = s.bytes();
let ch = planes.len();
- let mut out = vec![0u8; n * ch * bps];
- for (c, plane) in planes.iter().enumerate() {
- for i in 0..n {
- let dst = &mut out[(i * ch + c) * bps..(i * ch + c + 1) * bps];
- match plane {
- Some(p) if p.len() >= (i + 1) * bps => {
- let src = &p[i * bps..(i + 1) * bps];
- for k in 0..bps {
- dst[k] = src[bps - 1 - k];
- }
- if cfg!(target_endian = "big") {
- dst.copy_from_slice(src);
- }
- if invert[c] {
- invert_sample(dst, s);
+ let row = ch * bps;
+ let mut out = vec![0u8; n * row];
+ // One band of rows per core, written straight into its slice of the shared output: the
+ // per-pixel channel loop stays, but a band holds ~1/cores of a 20 MP image's iterations
+ // instead of all of them.
+ let bs = bands(n);
+ let parts: Vec<Vec<u8>> = par_map(bs.clone(), |band| {
+ let mut part = vec![0u8; band.len() * row];
+ for (i, p) in band.clone().enumerate() {
+ for (c, plane) in planes.iter().enumerate() {
+ let dst = &mut part[(i * ch + c) * bps..(i * ch + c + 1) * bps];
+ match plane {
+ Some(pl) if pl.len() >= (p + 1) * bps => {
+ let src = &pl[p * bps..(p + 1) * bps];
+ for k in 0..bps {
+ dst[k] = src[bps - 1 - k];
+ }
+ if cfg!(target_endian = "big") {
+ dst.copy_from_slice(src);
+ }
+ if invert[c] {
+ invert_sample(dst, s);
+ }
}
+ _ => dst.copy_from_slice(&fill[c]),
}
- _ => dst.copy_from_slice(&fill[c]),
}
}
+ part
+ });
+ for (band, part) in bs.into_iter().zip(parts) {
+ out[band.start * row..band.end * row].copy_from_slice(&part);
}
out
}
@@ -76,21 +88,33 @@ pub fn deinterleave(bytes: &[u8], ch: usize, s: SampleType, invert: &[bool]) ->
if invert[c] { it.map(|v| 255 - v).collect() } else { it.copied().collect() }
});
}
- let mut planes = vec![Vec::with_capacity(n * bps); ch];
- let mut tmp = [0u8; 4];
- for i in 0..n {
- for (c, plane) in planes.iter_mut().enumerate() {
- let src = &bytes[(i * ch + c) * bps..(i * ch + c + 1) * bps];
- tmp[..bps].copy_from_slice(src);
- if invert[c] {
- invert_sample(&mut tmp[..bps], s);
- }
- if cfg!(target_endian = "big") {
- plane.extend_from_slice(&tmp[..bps]);
- } else {
- plane.extend(tmp[..bps].iter().rev());
+ // One band of rows per core, appended in band order into pre-grown planes.
+ let row = ch * bps;
+ let bs = bands(n);
+ let parts: Vec<Vec<Vec<u8>>> = par_map(bs.clone(), |band| {
+ let mut planes = vec![Vec::with_capacity(band.len() * bps); ch];
+ let mut tmp = [0u8; 4];
+ for p in band {
+ for (c, plane) in planes.iter_mut().enumerate() {
+ let src = &bytes[p * row + c * bps..p * row + (c + 1) * bps];
+ tmp[..bps].copy_from_slice(src);
+ if invert[c] {
+ invert_sample(&mut tmp[..bps], s);
+ }
+ if cfg!(target_endian = "big") {
+ plane.extend_from_slice(&tmp[..bps]);
+ } else {
+ plane.extend(tmp[..bps].iter().rev());
+ }
}
}
+ planes
+ });
+ let mut planes: Vec<Vec<u8>> = (0..ch).map(|_| Vec::with_capacity(n * bps)).collect();
+ for part in parts {
+ for (c, plane) in planes.iter_mut().enumerate() {
+ plane.extend_from_slice(&part[c]);
+ }
}
planes
}
@@ -193,6 +217,67 @@ pub fn bands(n: usize) -> Vec<std::ops::Range<usize>> {
mod tests {
use super::*;
+ #[test]
+ fn banded_shuffles_match_a_sequential_reference() {
+ fn seq_interleave(planes: &[Option<&[u8]>], fill: &[Vec<u8>], n: usize, s: SampleType, invert: &[bool]) -> Vec<u8> {
+ let bps = s.bytes();
+ let ch = planes.len();
+ let mut out = vec![0u8; n * ch * bps];
+ for (c, plane) in planes.iter().enumerate() {
+ for i in 0..n {
+ let dst = &mut out[(i * ch + c) * bps..(i * ch + c + 1) * bps];
+ match plane {
+ Some(p) if p.len() >= (i + 1) * bps => {
+ let src = &p[i * bps..(i + 1) * bps];
+ for k in 0..bps {
+ dst[k] = src[bps - 1 - k];
+ }
+ if invert[c] {
+ invert_sample(dst, s);
+ }
+ }
+ _ => dst.copy_from_slice(&fill[c]),
+ }
+ }
+ }
+ out
+ }
+ fn seq_deinterleave(bytes: &[u8], ch: usize, s: SampleType, invert: &[bool]) -> Vec<Vec<u8>> {
+ let bps = s.bytes();
+ let n = bytes.len() / (ch * bps).max(1);
+ let mut planes = vec![Vec::with_capacity(n * bps); ch];
+ let mut tmp = [0u8; 4];
+ for i in 0..n {
+ for (c, plane) in planes.iter_mut().enumerate() {
+ let src = &bytes[(i * ch + c) * bps..(i * ch + c + 1) * bps];
+ tmp[..bps].copy_from_slice(src);
+ if invert[c] {
+ invert_sample(&mut tmp[..bps], s);
+ }
+ plane.extend(tmp[..bps].iter().rev());
+ }
+ }
+ planes
+ }
+ // Odd pixel counts cross band boundaries; a missing plane exercises the fill path.
+ for n in [1usize, 7, 64, 1000] {
+ for s in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let bps = s.bytes();
+ let planes: Vec<Vec<u8>> = (0..4).map(|c| (0..n * bps).map(|i| (i * 13 + c * 5) as u8).collect()).collect();
+ let mut refs: Vec<Option<&[u8]>> = planes.iter().map(|p| Some(&p[..])).collect();
+ refs[2] = None;
+ let fill: Vec<Vec<u8>> = (0..4).map(|c| vec![c as u8 * 40; bps]).collect();
+ let invert = [false, true, false, true];
+ let got = interleave(&refs, &fill, n, s, &invert);
+ let want = seq_interleave(&refs, &fill, n, s, &invert);
+ assert_eq!(got, want, "interleave n={n}");
+ let planes_back = deinterleave(&got, 4, s, &invert);
+ let want_back = seq_deinterleave(&got, 4, s, &invert);
+ assert_eq!(planes_back, want_back, "deinterleave n={n}");
+ }
+ }
+ }
+
#[test]
fn interleave_roundtrip_all_depths() {
for s in [SampleType::U8, SampleType::U16, SampleType::F32] {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 739882ded..baf792465 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -296,6 +296,10 @@ pub struct Services {
pub native_menu: Option<native_menu::NativeMenu>,
}
+/// A document histogram being computed off the UI thread: (document, revision, receiver of
+/// (document, compute ms, histograms)).
+pub(crate) type HistJob = (DocId, u64, std::sync::mpsc::Receiver<(DocId, f64, std::sync::Arc<tone::Histograms>)>);
+
pub struct PhotocraftApp {
pub session: Session,
pub ui: UiState,
@@ -395,6 +399,8 @@ pub struct PhotocraftApp {
pub(crate) tone_hist: Option<(DocId, photocraft_doc::LayerId, u64, std::sync::Arc<tone::Histograms>)>,
/// Histogram panel cache: (document, revision, computed at ms, histograms).
pub(crate) doc_hist: Option<(DocId, u64, f64, std::sync::Arc<tone::Histograms>)>,
+ /// The document histogram being computed on a worker thread: (document, revision, receiver).
+ pub(crate) hist_job: Option<HistJob>,
/// Free Transform preview (document without the moving pixels + their texture).
pub(crate) transform_preview: Option<transform_tool::TransformPreview>,
/// Move-tool ⇧/⌥ drag state (move_mods).
@@ -531,6 +537,7 @@ impl PhotocraftApp {
wide_angle: None,
tone_hist: None,
doc_hist: None,
+ hist_job: None,
gpu: None,
started: None,
perf: Default::default(),
diff --git a/crates/ui-egui/src/tone.rs b/crates/ui-egui/src/tone.rs
index 06a7951b9..0eacc731a 100644
--- a/crates/ui-egui/src/tone.rs
+++ b/crates/ui-egui/src/tone.rs
@@ -238,13 +238,57 @@ pub fn histogram_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let stale = !matches!(&app.doc_hist, Some((d, r, _, _)) if *d == doc_id && *r == rev);
let due = app.doc_hist.as_ref().is_none_or(|(d, _, at, _)| *d != doc_id || now - at > 250.0);
if stale && due {
- let t0 = now;
- let h = Arc::new(compute_histograms(&st.doc, HistSource::BelowLayer(LayerId(u64::MAX)), ToneSpace::Rgb));
- app.perf.span("histogram", crate::gpu_canvas::now_ms() - t0);
- app.doc_hist = Some((doc_id, rev, now, h));
+ // Computed off the UI thread (doc clone + proxy + pixel counts cost tens of ms on
+ // large documents): the panel keeps showing the previous histogram with the existing
+ // "cached data" warning until the worker delivers.
+ let pending = app.hist_job.as_ref().is_some_and(|(d, r, _)| *d == doc_id && *r == rev);
+ if !pending {
+ let (tx, rx) = std::sync::mpsc::channel();
+ // No threads on the web (and a spawn can fail natively): compute inline then, and
+ // deliver through the same channel so one receive path lands both.
+ #[cfg(not(target_arch = "wasm32"))]
+ let spawned = {
+ let doc = st.doc.clone();
+ let tx = tx.clone();
+ let ctx = ui.ctx().clone();
+ std::thread::Builder::new()
+ .name("histogram".into())
+ .spawn(move || {
+ let t0 = crate::gpu_canvas::now_ms();
+ let h = Arc::new(compute_histograms(&doc, HistSource::BelowLayer(LayerId(u64::MAX)), ToneSpace::Rgb));
+ let _ = tx.send((doc.id, crate::gpu_canvas::now_ms() - t0, h));
+ ctx.request_repaint();
+ })
+ .is_ok()
+ };
+ #[cfg(target_arch = "wasm32")]
+ let spawned = false;
+ if !spawned {
+ let t0 = crate::gpu_canvas::now_ms();
+ let h = Arc::new(compute_histograms(&st.doc, HistSource::BelowLayer(LayerId(u64::MAX)), ToneSpace::Rgb));
+ let _ = tx.send((doc_id, crate::gpu_canvas::now_ms() - t0, h));
+ }
+ app.hist_job = Some((doc_id, rev, rx));
+ }
} else if stale {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(260));
}
+ // A finished worker lands its histogram; the revision check keeps a stale result from
+ // overwriting a newer one. A worker that died without sending clears the job so the next
+ // frame schedules a new one.
+ if let Some((jd, jr, rx)) = &app.hist_job {
+ match rx.try_recv() {
+ Ok((_, ms, h)) => {
+ app.perf.span("histogram", ms);
+ if *jd == doc_id {
+ app.doc_hist = Some((doc_id, *jr, crate::gpu_canvas::now_ms(), h));
+ }
+ app.hist_job = None;
+ }
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => app.hist_job = None,
+ Err(std::sync::mpsc::TryRecvError::Empty) => {}
+ }
+ }
let Some((_, _, _, h)) = app.doc_hist.clone() else { return };
let size = app.session.active().map_or(photocraft_doc::Size::new(0, 0), |s| s.doc.size);
// Statistics come from a downsampled cache (like Photoshop's cache levels).
@@ -319,3 +363,77 @@ mod tests {
assert_eq!(compute_histograms(&st.doc, HistSource::Layer(bg), ToneSpace::Lab).ch.len(), 3);
}
}
+
+#[cfg(test)]
+mod hist_async_tests {
+ use super::*;
+ use crate::PhotocraftApp;
+ use serde_json::json;
+
+ /// The panel schedules the histogram on a worker and keeps showing the previous data
+ /// until it lands: right after the trigger the job exists (nothing computed in this
+ /// frame), the receiver delivers, and a stale result cannot overwrite a newer revision.
+ #[test]
+ fn panel_histogram_is_computed_off_the_ui_thread() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let _ = &ctx;
+ app.run("file.new", json!({"width": 640, "height": 480})).unwrap();
+ let (doc_id, rev) = {
+ let st = app.session.active().unwrap();
+ (st.doc.id, st.revision)
+ };
+ // Drive one panel frame through a minimal egui pass.
+ let ctx = egui::Context::default();
+ ctx.begin_pass(Default::default());
+ let panel_ui = egui::Ui::new(
+ ctx.clone(),
+ egui::Id::new("hist-test"),
+ egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0))),
+ );
+ let mut panel_ui = panel_ui;
+ histogram_panel(&mut app, &mut panel_ui);
+ // A fast worker (or the inline fallback) may already have landed the result this frame.
+ if let Some(job) = app.hist_job.take() {
+ assert_eq!(job.0, doc_id);
+ assert_eq!(job.1, rev);
+ // The worker delivers (its repaint request is a no-op outside a frame).
+ let (did, _, h) = job.2.recv().expect("the worker delivers the histogram");
+ assert_eq!(did, doc_id);
+ assert!(!h.ch.is_empty(), "the histogram has data");
+ // Delivering it for the revision it was computed from lands in the cache.
+ app.doc_hist = Some((doc_id, rev, crate::gpu_canvas::now_ms(), h.clone()));
+ }
+ assert_eq!(app.doc_hist.as_ref().map(|h| (h.0, h.1)), Some((doc_id, rev)));
+ // …and a newer revision keeps the old entry stale instead of being overwritten by it.
+ app.run("layer.new.layer", json!({})).unwrap();
+ let rev2 = app.session.active().unwrap().revision;
+ assert_ne!(rev, rev2);
+ assert_ne!(app.doc_hist.as_ref().unwrap().1, rev2, "stale after an edit");
+ }
+
+ /// A worker that died without sending (its sender dropped) clears the job, so the next
+ /// frame schedules a new one instead of waiting forever.
+ #[test]
+ fn a_dead_histogram_worker_clears_the_job() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
+ let (doc_id, rev) = {
+ let st = app.session.active().unwrap();
+ (st.doc.id, st.revision)
+ };
+ let (tx, rx) = std::sync::mpsc::channel();
+ drop(tx);
+ app.hist_job = Some((doc_id, rev, rx));
+ let ctx = egui::Context::default();
+ ctx.begin_pass(Default::default());
+ let mut ui = egui::Ui::new(
+ ctx.clone(),
+ egui::Id::new("hist-dead"),
+ egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0))),
+ );
+ histogram_panel(&mut app, &mut ui);
+ assert!(app.hist_job.is_none(), "a disconnected job is dropped");
+ assert!(app.doc_hist.is_none(), "nothing landed from the dead worker");
+ }
+}