Skip to content
Open
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ pub fn specs() -> Vec<CommandSpec> {
"lastFallback": lightcraft_gpu::last_fallback(),
}))
}),
cmd!(query "library.memory", "Memory Usage", [], None, "{} — bytes held by each cache (decoded sources, rendered previews, GPU buffers; heap when instrumented)", always, |s, _| {
cmd!(query "library.memory", "Memory Usage", [], None, "{} — bytes held by each cache (decoded sources, rendered previews, GPU buffers; heap when instrumented), and the catalog's photo records beside them", always, |s, _| {
Ok(serde_json::to_value(s.memory_report()).unwrap_or_default())
}),
cmd!(query "app.memoryBudget", "Memory Budget", [], None, "{mb?: number} — set the memory budget shared by the caches (default: a quarter of RAM, at most 1536 MB); returns the report", always, |s, p| {
Expand Down
31 changes: 24 additions & 7 deletions crates/engine/src/memory.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! Memory accounting: what each cache holds (`library.memory`, and `ui.inspect` → `memory` with the
//! frontend's own caches added).
//! Memory accounting: what each cache holds, and what the catalog's records take beside them
//! (`library.memory`, and `ui.inspect` → `memory` with the frontend's own caches added).
//!
//! The numbers are the caches' own bookkeeping (pixels held), not the process's resident size: the
//! allocator keeps freed pages for reuse and the GPU driver maps device buffers, so `ps`/`time -l`
Expand All @@ -18,10 +18,14 @@ use serde::Serialize;
/// - a quarter for the working memory of decodes in flight ([`work_gate`]);
/// - an eighth for the GPU renderer's pool of recycled buffers (trimmed when the app is idle).
///
/// The rest is headroom for what isn't cached (renders in progress, textures, the UI). An export
/// batch may, in addition, hold up to twice the budget in photos rendering side by side
/// ([`export_gate`]): transient memory, given back when the batch ends. Default:
/// a quarter of the machine's RAM, at most 1.5 GiB (`LIGHTCRAFT_MEMORY_MB` overrides it).
/// The rest is headroom for what isn't cached (renders in progress, the UI's other memory). The
/// UI's own caches take shares of the budget on top of those, which may add up to more than the
/// budget: a quarter for the idle per-view stage caches and a quarter for the grid's thumbnail
/// textures (`ui.inspect` → `memory` reports both). The catalog is no cache: the budget doesn't
/// limit it, and [`MemoryReport::catalog`] reports it beside them. An export batch may, in
/// addition, hold up to twice the budget in photos rendering side by side ([`export_gate`]):
/// transient memory, given back when the batch ends. Default: a quarter of the machine's RAM, at
/// most 1.5 GiB (`LIGHTCRAFT_MEMORY_MB` overrides it).
pub fn default_budget() -> usize {
if let Some(mb) = std::env::var("LIGHTCRAFT_MEMORY_MB").ok().and_then(|v| v.trim().parse::<usize>().ok()).filter(|m| *m >= 64) {
return mb << 20;
Expand Down Expand Up @@ -233,7 +237,7 @@ pub struct GpuUsage {
pub retired: u64,
}

/// What the engine's caches hold.
/// What the engine's caches hold, and what the catalog's records take beside them.
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryReport {
Expand All @@ -254,6 +258,10 @@ pub struct MemoryReport {
/// Working memory of decodes / probes in flight and its limit ([`work_gate`]).
pub work_bytes: usize,
pub work_limit: usize,
/// The photos the catalog holds, and the least their records take, beside the caches: not in
/// `engine_bytes`, and no share of the budget limits it. The strings and lists a record owns
/// come on top of the fixed part counted here ([`catalog_usage`]).
pub catalog: Usage,
/// Live/peak heap when the binary counts allocations.
#[serde(skip_serializing_if = "Option::is_none")]
pub heap: Option<HeapUsage>,
Expand Down Expand Up @@ -294,6 +302,14 @@ pub fn gpu_usage() -> GpuUsage {
GpuUsage { allocated: g.allocated, pooled: g.pooled, retired: g.retired }
}

/// What the catalog's `photos` records take at least: each one's fixed part, the [`lightcraft_catalog::Photo`]
/// and the counts of the `Arc` it lives in. Counting the strings and lists they own would walk the
/// whole catalog, which takes seconds in a library of a million photos.
pub fn catalog_usage(photos: usize) -> Usage {
const RECORD: usize = std::mem::size_of::<lightcraft_catalog::Photo>() + 2 * std::mem::size_of::<usize>();
Usage::new(photos, photos.saturating_mul(RECORD))
}

impl crate::Session {
/// What the engine's caches hold now.
pub fn memory_report(&self) -> MemoryReport {
Expand All @@ -311,6 +327,7 @@ impl crate::Session {
cache_budget: self.media.budget(),
work_bytes: work_gate().usage().0,
work_limit: work_gate().usage().1,
catalog: catalog_usage(self.catalog.len()),
heap: heap_stats(),
}
}
Expand Down
18 changes: 18 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,24 @@ fn memory_report_counts_decoded_sources_and_renders() {
assert!(m.rendered.count >= 1, "the thumbnail render is cached");
}

/// The catalog is the library itself, not a cache: the memory budget doesn't hold it, however big
/// the library, so the report says what the records take beside the caches, not in their sum.
#[test]
fn memory_report_counts_the_catalog_beside_the_caches() {
let mut s = demo();
let photos = s.catalog.len();
assert!(photos > 0);
let m = s.memory_report();
assert_eq!(m.catalog.count, photos);
// at least each record's fixed part (the strings and lists a photo owns come on top)
assert!(m.catalog.bytes >= photos * std::mem::size_of::<lightcraft_catalog::Photo>(), "{:?}", m.catalog);
// outside the caches' sum
assert_eq!(m.engine_bytes, m.thumb_sources.bytes + m.preview_sources.bytes + m.full_source.bytes + m.rendered.bytes);
let r = s.execute("library.memory", &json!({})).unwrap();
assert_eq!(r["catalog"]["count"], photos);
assert_eq!(r["catalog"]["bytes"], m.catalog.bytes);
}

#[test]
fn paste_selected_settings_pastes_only_chosen_copied_groups() {
let mut s = demo();
Expand Down
3 changes: 3 additions & 0 deletions crates/ui-egui/src/app/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,9 @@ impl LightcraftApp {
self.widget_hits = std::mem::take(&mut self.next_widget_hits);
// a frame without the loupe (grid, Compare, Survey, slideshow…) ends the loupe's step timing
self.loupe_timing.end_frame(ctx.input(|i| i.time));
// what the views asked a thumbnail of in this frame is the frame before's now: aged here, once for each
// frame drawn, not in `logic`, which a hidden window gets as well, with no frame to draw
self.renderer.frame_drawn();
panels::notices::finish_ui_pass(self, ctx);
panels::library_problem::finish_ui_pass(self, ctx);
self.ui_passes = self.ui_passes.wrapping_add(1);
Expand Down
6 changes: 5 additions & 1 deletion crates/ui-egui/src/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,12 +166,16 @@ pub fn inspect(app: &LightcraftApp, ctx: &egui::Context) -> Value {
})
}

/// Bytes held by the engine's caches and the renderer's (`ui.inspect` → `memory`).
/// Bytes held by the engine's caches and the renderer's (`ui.inspect` → `memory`), and what the
/// grid's thumbnails hold against the share of the budget they are limited to.
pub fn memory(app: &LightcraftApp) -> Value {
let mut v = serde_json::to_value(app.session.memory_report()).unwrap_or_default();
if let (Some(o), Value::Object(r)) = (v.as_object_mut(), app.renderer.memory()) {
o.extend(r);
}
if let Some(o) = v.as_object_mut() {
o.insert("thumbnails".into(), app.renderer.thumbnail_memory());
}
v
}

Expand Down
25 changes: 15 additions & 10 deletions crates/ui-egui/src/dialogs/print_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -886,16 +886,8 @@ fn paint_cell(
painter.rect_filled(frame.intersect(cell), 0.0, Color32::from_rgb(c[0], c[1], c[2]));
}
let clip = painter.with_clip_rect(avail.intersect(painter.clip_rect()));
let tex = photo.and_then(|id| {
// Use the library's thumbnail when there is one. A thumbnail is kept at one size, so asking
// for another size here every frame made the preview and the grid behind the dialog
// re-render each other's thumbnail for as long as the dialog stayed open.
if app.renderer.thumb(id).is_none() {
let px = (shown.width().max(shown.height()) * 2.0).clamp(64.0, 1024.0) as usize;
crate::panels::grid::request_thumb(app, id, px, 10);
}
app.renderer.thumb(id).map(|tex| tex.id())
});
let px = (shown.width().max(shown.height()) * 2.0).clamp(64.0, 1024.0) as usize;
let tex = photo.and_then(|id| cell_thumbnail(app, id, px));
match tex {
Some(id) => {
let mut mesh = egui::Mesh::with_texture(id);
Expand Down Expand Up @@ -934,6 +926,19 @@ fn paint_cell(
Some(visible)
}

/// The library's thumbnail of `id` for a cell, asked for at `px` only while it has none. A
/// thumbnail is kept at one size, so asking for another size here every frame made the preview and
/// the grid behind the dialog re-render each other's thumbnail for as long as the dialog stayed
/// open. The photo is noted every frame the cell is drawn, though: the dialog draws after the
/// grid, whose trim keeps only what was asked for in this frame or the last.
pub(crate) fn cell_thumbnail(app: &mut LightcraftApp, id: PhotoId, px: usize) -> Option<egui::TextureId> {
app.renderer.thumb_asked(id);
if app.renderer.thumb(id).is_none() {
crate::panels::grid::request_thumb(app, id, px, 10);
}
app.renderer.thumb(id).map(|tex| tex.id())
}

/// The Page Options as the print draws them ([`compose`]): crop marks at the corners of each
/// photo, the page number at the bottom right and the print settings at the bottom left.
/// Packages draw only the crop marks, as their Cut Guides at each cell's corners
Expand Down
48 changes: 39 additions & 9 deletions crates/ui-egui/src/panels/detail/look_ahead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ const AHEAD: usize = 5;
pub(super) const BEHIND: usize = 1;
/// The look-ahead's priority: below the loupe's own render (100), above everything else.
const AHEAD_PRIORITY: u32 = 96;
/// Thumbnails the loupe keeps while stepping (as many as the grid keeps), and how many photos on
/// either side of the open one stay when it trims them.
const MAX_LOUPE_THUMBS: usize = 600;
/// How many photos on either side of the open one keep their thumbnails when the loupe trims them
/// (what the filmstrip can show): the nearest of them, as many as the thumbnails' share of the
/// memory budget holds ([`keep_window`]). It trims once the thumbnails are over what the grid keeps
/// them to, see [`crate::render::Renderer::thumbs_over_limit`].
const KEEP_AROUND: usize = 64;
/// The thumbnail size the look-ahead asks for (the filmstrip's at 2x).
const AHEAD_THUMB_EDGE: usize = 256;
Expand Down Expand Up @@ -94,6 +95,9 @@ pub(crate) fn look_ahead(app: &mut LightcraftApp, id: PhotoId, edge: usize, crop
app.look_ahead.last = Some(id);
}
let (visible_gen, ids) = app.session.visible_shared();
// before the early return below: the limit moves with the memory budget, and thumbnails arrive
// while the loupe rests on a photo, so being over it is not a matter of a step
trim_thumbs(app, &ids, id);
// (the renderer's epoch: a reset drops the stand-ins made, which are then asked for again)
let want = (id, app.look_ahead.dir, rev, visible_gen, edge, crop, prepare, app.renderer.epoch());
if app.look_ahead.made_for == Some(want) {
Expand All @@ -102,12 +106,6 @@ pub(crate) fn look_ahead(app: &mut LightcraftApp, id: PhotoId, edge: usize, crop
app.look_ahead.made_for = Some(want);
let Some(i) = ids.iter().position(|p| *p == id) else { return };
let targets = app.look_ahead.targets(app, &ids, i, prepare);
// stepping through a whole wedding in the loupe would keep every thumbnail it ever drew: keep
// the ones around the photo (what the filmstrip can show) once there are many
if app.renderer.thumb_textures() > MAX_LOUPE_THUMBS {
let keep = ids.iter().skip(i.saturating_sub(KEEP_AROUND)).take(2 * KEEP_AROUND + 1).copied().collect();
app.renderer.evict_thumbs(&keep, MAX_LOUPE_THUMBS);
}
// their thumbnails first (a small embedded JPEG each, a few ms): something to show at once
// even when a step outruns the full-size previews, and in full screen, where no filmstrip
// asks for them
Expand All @@ -117,3 +115,35 @@ pub(crate) fn look_ahead(app: &mut LightcraftApp, id: PhotoId, edge: usize, crop
let jobs = targets.into_iter().filter_map(|nid| app.session.quick_view_job(nid, edge, crop)).collect();
app.renderer.look_ahead(jobs, AHEAD_PRIORITY);
}

/// Stepping through a whole wedding in the loupe would keep every thumbnail it ever drew: once the
/// thumbnails are over their limit, keep the ones around the open photo `id` (what the filmstrip
/// can show, see [`keep_window`]) and drop the rest.
fn trim_thumbs(app: &mut LightcraftApp, ids: &[PhotoId], id: PhotoId) {
if !app.renderer.thumbs_over_limit() {
return;
}
let Some(i) = ids.iter().position(|p| *p == id) else { return };
let keep = keep_window(&app.renderer, ids, i);
app.renderer.evict_thumbs(&keep);
}

/// The photos around position `i` of `ids` whose thumbnails the loupe keeps: nearest first (the open
/// photo, then one each side of it, and so on outwards), up to [`KEEP_AROUND`] on either side and
/// no more than the thumbnails' share of the memory budget holds, so that a small budget isn't
/// held up by a window of large thumbnails the grid left. The open photo's own always stays.
fn keep_window(renderer: &crate::render::Renderer, ids: &[PhotoId], i: usize) -> std::collections::HashSet<PhotoId> {
let budget = renderer.thumb_budget();
let outwards = (1..=KEEP_AROUND).flat_map(|d| [i.checked_sub(d), i.checked_add(d)]);
let mut keep = std::collections::HashSet::new();
let mut held = 0usize;
for at in std::iter::once(Some(i)).chain(outwards).flatten() {
let Some(&id) = ids.get(at) else { continue };
held = held.saturating_add(renderer.thumb_bytes_of(id));
if held > budget && !keep.is_empty() {
break;
}
keep.insert(id);
}
keep
}
4 changes: 3 additions & 1 deletion crates/ui-egui/src/panels/grid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) {
}
});
app.caches.grid_stats.cells_visited += visited;
app.renderer.evict_thumbs(&visible_ids, 600);
app.renderer.evict_thumbs(&visible_ids);
let _ = (Color32::BLACK, StrokeKind::Inside, Stroke::NONE);
}

Expand Down Expand Up @@ -717,6 +717,8 @@ fn group_header(app: &mut LightcraftApp, ui: &mut egui::Ui, run: &DateRun, ids:
/// [`lightcraft_engine::media::Session::embedded_thumb_is_final`]), which for a folder of raws on a
/// network share is the difference between reading every file whole and reading a preview each.
pub fn request_thumb(app: &mut LightcraftApp, id: PhotoId, size: usize, priority: u32) {
// (the grid's trim keeps what any view asked for in this frame or the last, see `evict_thumbs`)
app.renderer.thumb_asked(id);
// A slider drag changes the photo every frame: its thumbnail follows once the drag ends, so its
// renders (a raw decode the first time) don't compete with the loupe's drafts.
if app.session.interaction.as_ref().is_some_and(|i| i.photo == id) && app.renderer.thumb(id).is_some() {
Expand Down
3 changes: 3 additions & 0 deletions crates/ui-egui/src/panels/second.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ fn body(app: &mut LightcraftApp, ui: &mut egui::Ui) {
);
return;
};
// (its thumbnail is the last picture below, until the render made for this window arrives: the
// grid's trim keeps the photos a view asked a thumbnail of, see `Renderer::evict_thumbs`)
app.renderer.thumb_asked(id);
// a render sized for this window
let ppp = ui.ctx().pixels_per_point();
let side = super::detail::texture_side(ui.ctx()).clamp(64, 4096);
Expand Down
Loading
Loading