Skip to content

Commit b86fd52

Browse files
authored
Merge pull request #1932 from RAD-Films/pr/sched-rank
Issue #1898: the photo on screen and the user's own work first, background scans on spare capacity
2 parents 6d280a4 + f6e0722 commit b86fd52

13 files changed

Lines changed: 435 additions & 8 deletions

File tree

‎crates/engine/src/activity.rs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,11 @@ impl Activity {
465465
lock(&self.inner.tasks).iter().any(|e| e.parent.is_none() && e.kind == kind)
466466
}
467467

468+
/// The kind of the first top-level task in flight whose kind is one of `kinds`, or `None` ([`crate::sched`]).
469+
pub fn running_kind(&self, kinds: &[&str]) -> Option<&'static str> {
470+
lock(&self.inner.tasks).iter().find(|e| e.parent.is_none() && kinds.contains(&e.kind)).map(|e| e.kind)
471+
}
472+
468473
/// Register a task; it is listed until the returned guard is dropped. `label` is English (the frontend
469474
/// translates it).
470475
pub fn start(&self, kind: &'static str, label: &str, cancel: Cancel) -> TaskGuard {

‎crates/engine/src/cmd/face_recognize.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2719,9 +2719,10 @@ mod imp {
27192719
const C: &str = "faces.pump";
27202720
// how hard the scan may work now, from what the user is doing (the app says); nothing new is started while paused,
27212721
// and what is already running finishes
2722-
// paused by the user (`faces.pause`): nothing new is started until `faces.resume`
2722+
// paused by the user (`faces.pause`): nothing new is started until `faces.resume`; and (rank 3) while an
2723+
// export, an import or the photo on screen needs the machine (`crate::sched`)
27232724
let (enabled, paused) = switches_cached(s);
2724-
let pace = if paused { Pace::Pause } else { Pace::parse(p.get("pace").and_then(Value::as_str)) };
2725+
let pace = if paused { Pace::Pause } else { Pace::parse(s.spare_pace(p)) };
27252726
let target = target_workers(pace);
27262727
// a model that has finished downloading is installed and chosen here, whether or not recognition was on
27272728
finish_downloads(s);

‎crates/engine/src/cmd/previews.rs‎

Lines changed: 124 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,11 @@ fn run_all(state: &PreviewBuild, task: &TaskGuard, lanes: usize, force: bool, ac
502502
if state.background && (wait_for_user_work(activity, &state.cancel, task) || wait_on_screen(&state.cancel)) {
503503
break;
504504
}
505+
// a build that was asked for (an import's, Build Previews) waits while an export runs (the export ranks
506+
// higher, `crate::sched`) and gives the photo on screen a moment
507+
if !state.background && (wait_for_export(activity, &state.cancel, task) || give_way_to_screen(&state.cancel)) {
508+
break;
509+
}
505510
let next = {
506511
let mut q = queue.lock();
507512
match state.next_index(&q) {
@@ -587,6 +592,49 @@ fn wait_for_user_work(activity: &crate::activity::Activity, cancel: &AtomicBool,
587592
cancel.load(Ordering::Relaxed)
588593
}
589594

595+
/// Wait while an export runs, saying so in the build's row (a build that was asked for: rank 2 below the export,
596+
/// `crate::sched`). `true`: cancelled meanwhile.
597+
fn wait_for_export(activity: &crate::activity::Activity, cancel: &AtomicBool, task: &TaskGuard) -> bool {
598+
let mut paused = false;
599+
while activity.running_kind(&["export"]).is_some() {
600+
if cancel.load(Ordering::Relaxed) {
601+
return true;
602+
}
603+
if !paused {
604+
paused = true;
605+
task.detail("Paused while exporting");
606+
}
607+
#[cfg(not(target_arch = "wasm32"))]
608+
std::thread::sleep(std::time::Duration::from_millis(100));
609+
#[cfg(target_arch = "wasm32")]
610+
break;
611+
}
612+
if paused {
613+
task.detail("");
614+
}
615+
cancel.load(Ordering::Relaxed)
616+
}
617+
618+
/// How long a build that was asked for waits for the photo on screen before its next photo (ms): the loupe's own render
619+
/// goes first, and the build never stalls behind a user who keeps stepping.
620+
#[cfg(not(target_arch = "wasm32"))]
621+
const SCREEN_WAIT_MS: u64 = 600;
622+
623+
/// Wait while the photo on screen is being made, at most [`SCREEN_WAIT_MS`]. `true`: cancelled meanwhile.
624+
fn give_way_to_screen(cancel: &AtomicBool) -> bool {
625+
#[cfg(not(target_arch = "wasm32"))]
626+
{
627+
let t0 = web_time::Instant::now();
628+
while crate::prep::foreground_busy() && t0.elapsed() < std::time::Duration::from_millis(SCREEN_WAIT_MS) {
629+
if cancel.load(Ordering::Relaxed) {
630+
return true;
631+
}
632+
std::thread::sleep(std::time::Duration::from_millis(15));
633+
}
634+
}
635+
cancel.load(Ordering::Relaxed)
636+
}
637+
590638
/// The long edge the background preparation builds standard previews at: the library's standard
591639
/// size, or what the loupe asks for on this screen when that is more ([`Session::loupe_edge`]), so
592640
/// the loupe finds what was built.
@@ -630,7 +678,9 @@ fn build(s: &mut Session, p: &Value) -> Result<Value> {
630678
let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32");
631679
// `feed`: the caller makes the jobs a few photos a frame ([`feed`]), nearest the user first;
632680
// making all of them here froze the UI for 1.3 s at every build of a 2,597-photo folder (2026-11-10)
633-
let lazy = background && !wait && p.get("feed").and_then(Value::as_bool).unwrap_or(false);
681+
// (an import's build is fed too once the app ticks the preparation: its jobs then carry the photo's path when they
682+
// are made, nearest the user first, not when the import's batch came in)
683+
let lazy = (background || s.prep.ticking()) && !wait && p.get("feed").and_then(Value::as_bool).unwrap_or(false);
634684
let (order, slots): (Vec<u64>, Vec<Slot>) = if lazy {
635685
(ids.iter().map(|id| id.0).collect(), ids.iter().map(|_| Some(None)).collect())
636686
} else {
@@ -819,12 +869,84 @@ pub fn build_after_import(s: &mut Session, ids: &[lcc_catalog::PhotoId]) {
819869
if ids.is_empty() {
820870
return;
821871
}
872+
// An import commits its photos a batch at a time: while the build of an earlier batch runs, these photos wait and
873+
// the next frame after it builds all that waited ([`build_owed_import`]). Before, every batch after the first
874+
// was dropped ("a preview build is already running"): 16 of 261 photos got their previews.
875+
if s.prep.ticking() && s.preview_build.as_ref().is_some_and(|b| b.running() && !b.background) {
876+
s.prep.owed_import.extend(ids.iter().copied());
877+
return;
878+
}
879+
start_import_build(s, size, ids);
880+
}
881+
882+
/// Start the build of an import's previews (`size` as `library.buildPreviews`), from the photo the user is on.
883+
fn start_import_build(s: &mut Session, size: &str, ids: &[lcc_catalog::PhotoId]) {
822884
let ids: Vec<u64> = ids.iter().map(|id| id.0).collect();
823-
if let Err(e) = build(s, &json!({"size": size, "ids": ids})) {
885+
let mut p = json!({"size": size, "ids": ids, "feed": true});
886+
if let Some(at) = s.active() {
887+
p["from"] = json!(at.0);
888+
}
889+
if let Err(e) = build(s, &p) {
824890
log::warn!("previews at import: {e}");
825891
}
826892
}
827893

894+
/// The photos of an import whose previews wait for the build before them ([`build_after_import`]): built once that
895+
/// build has ended. Cheap; called every frame ([`Session::prep_tick`]).
896+
pub(crate) fn build_owed_import(s: &mut Session) {
897+
if s.prep.owed_import.is_empty() || s.preview_build.as_ref().is_some_and(|b| b.running() && !b.background) {
898+
return;
899+
}
900+
let size = match s.preview_prefs.at_import {
901+
ImportPreviews::Minimal => {
902+
s.prep.owed_import.clear();
903+
return;
904+
}
905+
ImportPreviews::Standard => "standard",
906+
ImportPreviews::Full => "full",
907+
};
908+
let mut seen = std::collections::HashSet::new();
909+
let ids: Vec<lcc_catalog::PhotoId> = std::mem::take(&mut s.prep.owed_import).into_iter().filter(|id| seen.insert(*id)).collect();
910+
start_import_build(s, size, &ids);
911+
}
912+
913+
/// The photos of `ids` whose file moved (Rename Photos, a move, a relink, their undo): the running build's jobs made
914+
/// for them are made again, with the photo's path now. A build queued just before a rename kept the old paths and
915+
/// failed 84 photos with "cannot find the file".
916+
pub(crate) fn refresh_jobs_of(s: &mut Session, ids: &[lcc_catalog::PhotoId]) {
917+
let Some(b) = s.preview_build.clone().filter(|b| b.running()) else { return };
918+
let moved: std::collections::HashSet<u64> = ids.iter().map(|id| id.0).collect();
919+
let stale: Vec<usize> = {
920+
let mut q = b.queue.lock();
921+
b.order
922+
.iter()
923+
.enumerate()
924+
.filter(|(_, id)| moved.contains(*id))
925+
.filter_map(|(i, _)| {
926+
let slot = q.get_mut(i)?;
927+
matches!(slot, Some(Some(_))).then(|| {
928+
*slot = Some(None);
929+
i
930+
})
931+
})
932+
.collect()
933+
};
934+
for i in stale {
935+
let Some(id) = b.order.get(i).copied() else { continue };
936+
let jobs = jobs_for(s, lcc_catalog::PhotoId(id), b.edge);
937+
let mut q = b.queue.lock();
938+
if let Some(slot) = q.get_mut(i).filter(|s| matches!(s, Some(None))) {
939+
if jobs.is_empty() {
940+
*slot = None;
941+
b.skipped.fetch_add(1, Ordering::Relaxed);
942+
b.done.fetch_add(1, Ordering::Relaxed);
943+
} else {
944+
*slot = Some(Some(jobs));
945+
}
946+
}
947+
}
948+
}
949+
828950
/// One photo's smart preview to build or discard: (photo, its file in the smart previews folder,
829951
/// how to load the original at preview size, whether the photo can take a preview-fitted look:
830952
/// vendor raws and DNGs (whose tone can come from their preview); only those proxies go stale when

‎crates/engine/src/focus_scan.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,8 @@ fn status(s: &Session) -> Value {
370370
/// `focus.pump {pace?}`: cheap to call every frame.
371371
pub(crate) fn pump(s: &mut Session, p: &Value) -> Result<Value> {
372372
follow_library(s);
373-
let pace = Pace::parse(p.get("pace").and_then(Value::as_str));
373+
// (rank 3: paused while an export, an import or the photo on screen needs the machine, `crate::sched`)
374+
let pace = Pace::parse(s.spare_pace(p));
374375
s.focus_scan.pace = pace;
375376
if !step(s, pace) && !s.focus_scan.auto_checked {
376377
// once per library opening: start by itself when photos are left to look at (a few KB each)

‎crates/engine/src/lib.rs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ pub mod rename;
156156
pub mod render_dng;
157157
pub mod run_presets;
158158
pub mod scene_disk;
159+
pub mod sched;
159160
pub mod segment;
160161
pub mod sensor_maps;
161162
pub mod sidecar;
@@ -1396,14 +1397,20 @@ impl Session {
13961397
// photos whose file was replaced: the faces and ML embeddings made from the old pixels go too (issue #1524)
13971398
let mut replaced = Vec::new();
13981399
let mut added_photo = false;
1400+
// photos whose file moved: a preview build's jobs for them are made again with the new path
1401+
let mut moved = Vec::new();
13991402
let mut pending = vec![&op];
14001403
while let Some(op) = pending.pop() {
14011404
match op {
14021405
Op::SetContent { id, .. } => {
14031406
invalidated.push(*id);
14041407
replaced.push(*id);
14051408
}
1406-
Op::SetFile { id, .. } | Op::Relink { id, .. } | Op::RemovePhoto { id } => invalidated.push(*id),
1409+
Op::SetFile { id, .. } | Op::Relink { id, .. } => {
1410+
invalidated.push(*id);
1411+
moved.push(*id);
1412+
}
1413+
Op::RemovePhoto { id } => invalidated.push(*id),
14071414
// a video's decoded source is its poster frame: a new poster time (or new stream facts) needs a new one
14081415
Op::SetVideoPoster { id, .. } | Op::SetVideoMeta { id, .. } => invalidated.push(*id),
14091416
Op::AddPhoto { photo } => {
@@ -1418,6 +1425,9 @@ impl Session {
14181425
for id in invalidated {
14191426
self.media.forget(id);
14201427
}
1428+
if !moved.is_empty() {
1429+
crate::cmd::previews::refresh_jobs_of(self, &moved);
1430+
}
14211431
if added_photo {
14221432
self.ml.photo_added();
14231433
}
@@ -3203,6 +3213,8 @@ mod tests_reload_sha1;
32033213
#[cfg(test)]
32043214
mod tests_retouch;
32053215
#[cfg(test)]
3216+
mod tests_sched;
3217+
#[cfg(test)]
32063218
mod tests_segment;
32073219
#[cfg(test)]
32083220
mod tests_select_menu;

‎crates/engine/src/ml.rs‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1764,11 +1764,23 @@ impl Session {
17641764
submitted
17651765
}
17661766

1767+
/// The pace `ml.pump` last set (tests).
1768+
#[cfg(test)]
1769+
pub(crate) fn ml_pace_name(&self) -> &'static str {
1770+
match Pace::from_u8(self.ml.pace.load(Ordering::Relaxed)) {
1771+
Pace::Pause => "pause",
1772+
Pace::Light => "light",
1773+
Pace::Normal => "normal",
1774+
Pace::Full => "full",
1775+
}
1776+
}
1777+
17671778
/// `ml.pump {pace?: pause | light | normal | full}`.
17681779
pub(crate) fn ml_pump(&mut self, p: &Value) -> crate::Result<Value> {
17691780
self.ml_enabled();
1770-
// paused by the user (`ml.pause`): the photos being embedded wait, nothing new is queued
1771-
let pace = if self.ml.paused { Pace::Pause } else { Pace::parse(p.get("pace").and_then(Value::as_str)) };
1781+
// paused by the user (`ml.pause`): the photos being embedded wait, nothing new is queued; and
1782+
// (rank 3) while an export, an import or the photo on screen needs the machine (`crate::sched`)
1783+
let pace = if self.ml.paused { Pace::Pause } else { Pace::parse(self.spare_pace(p)) };
17721784
self.ml.pace.store(pace as u8, Ordering::Relaxed);
17731785
let (added, _) = self.drain_ml_results();
17741786

‎crates/engine/src/prep.rs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,11 @@ pub struct PrepState {
256256
/// It says "ask again", not what is left: the build that follows skips every photo whose
257257
/// previews are on disk. A view with nothing to build (no marked photo) leaves it as it is.
258258
pub unfinished: bool,
259+
/// An import's photos whose previews wait for the build before them to end
260+
/// ([`crate::cmd::previews::build_after_import`]).
261+
pub(crate) owed_import: Vec<PhotoId>,
262+
/// [`Session::prep_tick`] has run (the app ticks it every frame): a build may then leave making its jobs to it.
263+
ticked: bool,
259264
/// Before when an unfinished build is not taken up again: [`SETTLE_AFTER`] after the view shown
260265
/// last changed (`None`: no change seen yet). The first build of a library with nothing owed
261266
/// doesn't wait for it (the steps in the loupe are its guard).
@@ -309,6 +314,11 @@ impl std::fmt::Debug for PrepState {
309314
}
310315

311316
impl PrepState {
317+
/// Whether [`Session::prep_tick`] runs (the desktop app): builds fed a frame at a time are fed.
318+
pub fn ticking(&self) -> bool {
319+
self.ticked
320+
}
321+
312322
/// Forget the view state a library that was open before left behind, when a library opens: the
313323
/// view guards (`started_for`, `declined_for`, the view last seen), the settle wait and the
314324
/// step count were earned in that library's views, and a view signature is only its photos'
@@ -598,6 +608,13 @@ impl Session {
598608
/// updated look, even after 15 min"). In a library the rest is prepared around the photo on screen
599609
/// ([`AROUND`]), not the whole view; a folder being culled is prepared whole.
600610
pub fn prep_tick(&mut self, mode: Mode, at: Option<PhotoId>, backward: bool) {
611+
self.prep.ticked = true;
612+
// an import's photos whose previews waited for the build before them ([`crate::cmd::previews::build_after_import`])
613+
crate::cmd::previews::build_owed_import(self);
614+
// a build that was asked for (an import's) builds from the photo the user is on first, as the preparation does
615+
if let (Some(id), Some(b)) = (at, self.preview_build.as_ref().filter(|b| b.running() && !b.background)) {
616+
b.focus_on(id, backward);
617+
}
601618
self.prep_tick_inner(mode, at, backward);
602619
// the build's render jobs, a few photos a tick, nearest the user first (making all of them
603620
// when it started froze the UI for 1.3 s in a 2,597-photo folder, 2026-11-10)

0 commit comments

Comments
 (0)