Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion crates/catalog/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,10 @@ impl Photo {
pub fn relative_wb(&self) -> bool {
self.develops_raw() && relative_wb_camera_as(&self.format, &self.meta.camera, &self.develop.profile.camera)
}
/// What [`Self::relative_wb`] depends on: photos with equal keys have the same answer.
pub fn relative_wb_key(&self) -> (bool, &str, &str, &str) {
(self.develops_raw(), &self.format, &self.meta.camera, &self.develop.profile.camera)
}
/// The settings the Before view starts from: the one set by the user, else the photo as it
/// came into the library (its import state), else its import defaults.
pub fn before_base(&self) -> DevelopSettings {
Expand All @@ -717,7 +721,12 @@ impl Photo {
/// process a photo renders with is not an edit, so comparisons with its defaults (edited?
/// still as imported?) don't change when a newer process exists. A new photo has the latest.
pub fn camera_defaults(&self) -> DevelopSettings {
let relative = self.relative_wb();
self.camera_defaults_as(self.relative_wb())
}
/// [`Self::camera_defaults`] of a photo whose [`Self::relative_wb`] is `relative`: that looks the
/// camera up by name in the camera tables and profiles, so a pass over many photos asks it once
/// per camera ([`Self::relative_wb_key`]) instead of once per photo (issue #979).
pub fn camera_defaults_as(&self, relative: bool) -> DevelopSettings {
let wb = if relative { Some((6500.0, 0.0)) } else { self.as_shot_wb };
let mut d = match wb {
Some((t, tint)) => DevelopSettings::for_raw(t, tint),
Expand Down
68 changes: 63 additions & 5 deletions crates/engine/examples/open_bench.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,29 @@
//! How long opening a large library takes, stage by stage (issue #979). Makes a library of N
//! photos in `<dir>` (when it has none), then opens it twice and prints the stages.
//!
//! `<PREFIX>_PROFILE=1 cargo run --release -p lcc-engine --example open_bench -- <dir> [photos]`
//! `<PREFIX>_PROFILE=1 cargo run --release -p lcc-engine --example open_bench -- <dir> [photos] [thumb KB]`
//!
//! The photos are raws of a few camera bodies with an as-shot white balance, a third of them
//! edited, like a library brought over from another program. With `thumb KB` above 0 the
//! library also gets a thumbnail cache of one file of that size per photo (a reporter's
//! 328 000-photo library had 18 GB of them, some 55 KB each), so a stage that reads the cache
//! shows.
use std::time::Instant;

use lcc_catalog::{Op, Photo, Source};
use lcc_catalog::{MediaKind, Op, Photo, Source};
use lcc_engine::Session;

const BODIES: [(&str, &str); 4] =
[("Canon EOS R5", "CR3"), ("SONY ILCE-7M4", "ARW"), ("NIKON CORPORATION NIKON Z 6_2", "NEF"), ("FUJIFILM X-T4", "RAF")];

fn main() {
let _ = env_logger_lite();
let Some(dir) = std::env::args().nth(1) else {
eprintln!("usage: open_bench <dir> [photos]");
eprintln!("usage: open_bench <dir> [photos] [thumb KB]");
return;
};
let n: u32 = std::env::args().nth(2).and_then(|a| a.parse().ok()).unwrap_or(300_000);
let thumb_kb: usize = std::env::args().nth(3).and_then(|a| a.parse().ok()).unwrap_or(0);
if !lcc_engine::library::is_library(std::path::Path::new(&dir)) {
let mut s = Session::new().with_fs();
if let Err(e) = s.open_library(&dir, false) {
Expand All @@ -22,19 +32,35 @@ fn main() {
}
for i in 0..n {
let id = s.catalog.alloc_photo_id();
let path = format!("/photos/{}/{}/IMG_{i:06}.CR2", 2000 + i % 25, i % 365);
let mut p = Photo::new(id, Source::File { path }, &format!("IMG_{i:06}.CR2"), "CR2", 6000, 4000, "2026-01-01T00:00:00");
let (camera, ext) = BODIES[i as usize % BODIES.len()];
let path = format!("/photos/{}/{}/IMG_{i:06}.{ext}", 2000 + i % 25, i % 365);
let mut p = Photo::new(id, Source::File { path }, &format!("IMG_{i:06}.{ext}"), ext, 6000, 4000, "2026-01-01T00:00:00");
p.kind = MediaKind::Raw;
p.meta.camera = camera.into();
p.as_shot_wb = Some((5000.0 + f64::from(i % 1500), f64::from(i % 7)));
p.develop = std::sync::Arc::new(p.camera_defaults());
p.file_size = 30_000_000 + u64::from(i);
p.captured = Some(format!("{}-{:02}-{:02}T10:00:00", 2000 + i % 25, 1 + i % 12, 1 + i % 28));
p.meta.keywords = vec![format!("kw{}", i % 500), format!("place{}", i % 50)];
p.rating = (i % 6) as u8;
if i % 3 == 0 {
p.edited = Some("2026-01-02T00:00:00".into());
let mut d = (*p.develop).clone();
d.light.exposure = 0.3;
p.develop = std::sync::Arc::new(d);
}
let _ = s.catalog.apply(Op::AddPhoto { photo: Box::new(p) });
}
let t = Instant::now();
let _ = s.close_library();
println!("made {n} photos, closed in {:.1} s", t.elapsed().as_secs_f64());
if thumb_kb > 0 {
let t = Instant::now();
match write_thumbs(&std::path::Path::new(&dir).join("thumbs"), n as usize, thumb_kb << 10) {
Ok(()) => println!("wrote {n} thumbnails of {thumb_kb} KB in {:.1} s", t.elapsed().as_secs_f64()),
Err(e) => eprintln!("thumbnails: {e}"),
}
}
}
for run in 0..2 {
let mut s = Session::new().with_fs();
Expand All @@ -46,9 +72,41 @@ fn main() {
let t = Instant::now();
let _ = s.visible();
println!("run {run}: first visible list {:.1} ms", t.elapsed().as_secs_f64() * 1000.0);
// the edited photos' previews are found in the background after a large library opens
let t = Instant::now();
while s.media.rendered.disk().is_some_and(|d| d.is_keep_last_pending()) && t.elapsed().as_secs() < 600 {
std::thread::sleep(std::time::Duration::from_millis(5));
}
println!("run {run}: edited photos found in the background {:.1} ms later", t.elapsed().as_secs_f64() * 1000.0);
}
}

/// `count` cache files of `bytes` each under `dir`, in the cache's own layout
/// (`<2 hex>/<32 hex>.lcthumb`), written on all cores.
fn write_thumbs(dir: &std::path::Path, count: usize, bytes: usize) -> std::io::Result<()> {
let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
let body = vec![0x5au8; bytes];
std::thread::scope(|sc| {
let jobs: Vec<_> = (0..threads)
.map(|t| {
let body = &body;
sc.spawn(move || -> std::io::Result<()> {
for i in (t..count).step_by(threads) {
// (a key spread over all 256 shards like the cache's hashes)
let key = (i as u128).wrapping_mul(0x9e37_79b9_7f4a_7c15_f39c_c060_5ced_c835);
let hex = format!("{key:032x}");
let shard = dir.join(hex.get(..2).unwrap_or("00"));
std::fs::create_dir_all(&shard)?;
std::fs::write(shard.join(format!("{hex}.lcthumb")), body)?;
}
Ok(())
})
})
.collect();
jobs.into_iter().try_for_each(|j| j.join().unwrap_or_else(|_| Err(std::io::Error::other("writer panicked"))))
})
}

/// Print `log` records to stderr (the stage timings are logged).
fn env_logger_lite() -> Result<(), log::SetLoggerError> {
struct L;
Expand Down
14 changes: 10 additions & 4 deletions crates/engine/src/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,16 +351,22 @@ pub fn has_import_look(p: &Photo) -> bool {
/// the photo as framed and exposed, a fair stand-in until the render arrives (labelled "Camera
/// preview" in the loupe). Any other edit is never shown as the camera JPEG.
pub fn looks_as_shot(p: &Photo) -> bool {
if has_import_look(p) {
return true;
}
looks_as_shot_given(p, p.camera_defaults())
}

/// [`looks_as_shot`] of a photo whose camera defaults ([`Photo::camera_defaults`]) are `defaults`.
pub fn looks_as_shot_given(p: &Photo, defaults: lcc_develop::DevelopSettings) -> bool {
let neutral = |d: &lcc_develop::DevelopSettings| {
let mut d = d.clone();
d.profile.camera.clear();
d.profile.id = lcc_develop::Profile::default().id;
d
};
neutral(&p.develop) == neutral(&p.camera_defaults())
// (has_import_look)
if p.develop_matches(defaults.clone()) {
return true;
}
neutral(&p.develop) == neutral(&defaults)
}

/// The name `library.setImportDefault` saves its preset under when the caller doesn't name one
Expand Down
97 changes: 87 additions & 10 deletions crates/engine/src/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,49 @@ impl SettingsLoad {
}
}

/// The activity-stack row of [`Session::keep_edited_previews_last`]'s work.
pub const EDITED_PREVIEWS_LABEL: &str = "Finding edited photos";

/// Most photos [`Session::keep_edited_previews_last`] looks through as the library opens (some
/// 3 µs each, so under 10 ms; issue #979); a larger library is looked through in the background.
pub const INLINE_EDITED_PHOTOS: usize = 2_000;

#[cfg(test)]
thread_local! {
/// Photos [`edited_preview_keys`] looked at on this thread (tests: opening a library looks at
/// none on the thread that opens it).
pub(crate) static EDITED_LOOKED_AT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// The latest-preview keys of the edited photos among `photos` ([`Session::keep_edited_previews_last`]):
/// `None` when `stop` said so. `stop` is asked, and `progress` told (done, of), every few thousand photos.
fn edited_preview_keys(
photos: &[std::sync::Arc<lcc_catalog::Photo>],
stop: &dyn Fn() -> bool,
progress: &dyn Fn(usize, usize),
) -> Option<Vec<lcc_preview::Hash128>> {
const STEP: usize = 4096;
let mut keys = Vec::new();
// (a camera is looked up by name once, not once per photo: most of the time this took)
let mut relative: std::collections::HashMap<(bool, &str, &str, &str), bool> = std::collections::HashMap::new();
for (i, p) in photos.iter().enumerate() {
if i % STEP == 0 {
if stop() {
return None;
}
progress(i, photos.len());
}
#[cfg(test)]
EDITED_LOOKED_AT.with(|n| n.set(n.get().saturating_add(1)));
let rel = *relative.entry(p.relative_wb_key()).or_insert_with(|| p.relative_wb());
if !crate::import::looks_as_shot_given(p, p.camera_defaults_as(rel)) {
keys.extend([crate::media::latest_view_key(p, true), crate::media::latest_thumb_key(p)]);
}
}
progress(photos.len(), photos.len());
Some(keys)
}

/// How long each stage of opening a library took: logged when the whole took a while (issue
/// #979: a large catalog spent a minute between being read and the library opening, with no
/// timings for that part), and always with `<PREFIX>_PROFILE` set.
Expand Down Expand Up @@ -900,10 +943,12 @@ impl Session {
self.media.clear_sources();
if on_disk {
self.media.attach_disk_cache(&dir.join("thumbs"), self.cache_bytes_in(&dir.join("thumbs")));
stages.mark("thumbnail cache");
self.keep_edited_previews_last();
stages.mark("edited previews");
self.tidy_thumbnail_cache();
}
stages.mark("thumbnail cache");
stages.mark("thumbnail cache tidy");
let view_written = self.view_json();
let store_with_library = prefs.store_with_library;
let own_store = store_with_library || self.app_store.is_none();
Expand Down Expand Up @@ -1369,22 +1414,54 @@ impl Session {
out
}

/// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default, which
/// grows with the library: [`crate::media::default_disk_cache_bytes`]).
/// The edited photos' latest previews (their last loupe view and grid thumbnail) are the last
/// pictures a full disk cache lets go: the only pictures of their edits (a photo as shot has its
/// camera JPEG). A full cache otherwise lost every rendered edit, and the loupe had nothing but
/// the unedited camera JPEG.
///
/// Telling which photos are edited asks each photo's camera defaults, which look its camera up
/// by name in the camera tables and profiles: most of a minute for 300 000 photos, which every
/// opening of the library waited for (issue #979). It is worked out on a thread of its own with
/// a row in the activity stack that can stop it; the cache prunes nothing until it is known.
/// A library of up to [`INLINE_EDITED_PHOTOS`] photos is looked through at once (a moment).
pub fn keep_edited_previews_last(&self) {
let Some(d) = self.media.rendered.disk() else { return };
let keys = self
.catalog
.photos()
.filter(|p| !crate::import::looks_as_shot(p))
.flat_map(|p| [crate::media::latest_view_key(p, true), crate::media::latest_thumb_key(p)]);
d.keep_last(keys);
let cache = self.media.rendered.clone();
let Some(d) = cache.disk() else { return };
// (shared, not copied: the photos are reference-counted)
let photos: Vec<std::sync::Arc<lcc_catalog::Photo>> = self.catalog.photos().cloned().collect();
if cfg!(target_arch = "wasm32") || photos.len() <= INLINE_EDITED_PHOTOS {
d.keep_last(edited_preview_keys(&photos, &|| false, &|_, _| ()).unwrap_or_default());
return;
}
d.keep_last_pending();
#[cfg(not(target_arch = "wasm32"))]
{
use std::sync::atomic::{AtomicBool, Ordering};
let stop = std::sync::Arc::new(AtomicBool::new(false));
let task = self.activity.start("cache", EDITED_PREVIEWS_LABEL, crate::activity::Cancel::Flag(stop.clone()));
let worker = cache.clone();
let spawned = std::thread::Builder::new().name("lc-keep-edited".into()).spawn(move || {
// the row stays while this runs (it is dropped with the closure, however that ends)
let row = task;
// (also given up when the library is closed or another is opened: the cache is retired then)
let stopped = || stop.load(Ordering::Relaxed) || worker.generation() == u64::MAX;
let Some(d) = worker.disk() else { return };
match edited_preview_keys(&photos, &stopped, &|done, of| row.progress(done as u64, of as u64)) {
Some(keys) => d.keep_last(keys),
None => d.keep_last_unknown(),
}
});
// (not started: worked out here, as before)
if let Err(e) = spawned {
log::warn!("thumbnail cache: edited photos looked through on this thread: {e}");
let photos: Vec<std::sync::Arc<lcc_catalog::Photo>> = self.catalog.photos().cloned().collect();
d.keep_last(edited_preview_keys(&photos, &|| false, &|_, _| ()).unwrap_or_default());
}
}
}

/// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default, which
/// grows with the library: [`crate::media::default_disk_cache_bytes`]).
pub fn cache_bytes(&self) -> u64 {
match (self.cache_mb, self.media.rendered.disk()) {
(0, Some(d)) => self.cache_bytes_in(d.dir()),
Expand Down
Loading