diff --git a/apps/effectcraft-web/src/diskcache.rs b/apps/effectcraft-web/src/diskcache.rs index 5ac655cb0..72e9a9e11 100644 --- a/apps/effectcraft-web/src/diskcache.rs +++ b/apps/effectcraft-web/src/diskcache.rs @@ -21,9 +21,11 @@ //! back their layer caches with a `PrefetchStore`. They report each frame's layer-cache //! misses; before the next request the page names the recent misses that are on disk //! ([`layer_prefetch`], `disk_cache::LayerPrefetch`), and the worker reads those entries -//! into memory before rendering, so the lookups find them. Slow buffers are written by the -//! worker after its frame and indexed here like frames (one least-recently-used order for -//! both kinds). +//! into memory before rendering, so the lookups find them; an entry is used only while the +//! files it lists (the file table's size and content hash) are unchanged, and a buffer whose +//! files can't all be named is not written (#3184). Slow buffers are written by the worker +//! after its frame and indexed here like frames (one least-recently-used order for both +//! kinds). use std::cell::RefCell; diff --git a/apps/effectcraft/src/main.rs b/apps/effectcraft/src/main.rs index 07d327a21..5350addbe 100644 --- a/apps/effectcraft/src/main.rs +++ b/apps/effectcraft/src/main.rs @@ -276,9 +276,6 @@ fn main() -> eframe::Result { // written on background threads (M13.14). session.check_footage_on_open = true; session.autosave.background = true; - // The disk cache's footage stamps too: an imported or opened project with thousands of - // sequence frames on a network share took half a minute to stamp. - session.disk_salt_background = true; // Settings, shortcut presets and the crash-recovery sentinel live in the platform // config directory. Agent-driven runs (`--control`) skip crash recovery. if let Some(dir) = effectcraft_host::config_dir() { diff --git a/crates/engine/src/background/remote.rs b/crates/engine/src/background/remote.rs index ca11d8220..153bb324b 100644 --- a/crates/engine/src/background/remote.rs +++ b/crates/engine/src/background/remote.rs @@ -27,8 +27,9 @@ //! - Layer buffers on disk: with `layers`, the server's layer cache is backed by a //! [`PrefetchStore`] ([`FrameServer::set_layer_store`]): before the request the transport //! fetches the entries named in `prefetch` (recent misses that are on disk, chosen by the -//! page, `disk_cache::LayerPrefetch`), so the lookups in the middle of the render find them; -//! the reply lists the layer keys that missed and those served from the store +//! page, `disk_cache::LayerPrefetch`), so the lookups in the middle of the render find them +//! (each entry keeps the source files its buffer was made of and is used only while they are +//! unchanged, #3184); the reply lists the layer keys that missed and those served from the store //! ([`FrameReply::Frame`] `layer_misses` / `layer_hits`), and slow buffers queue up for the //! transport to write after the frame ([`PrefetchStore::take_writes`], reported as //! [`FrameReply::Stored`] with `layer`). @@ -180,7 +181,7 @@ pub enum FrameReply { passes: u32, #[serde(default)] gpu: bool, - /// Layer-cache lookups that missed the store (salted keys, 32 hex digits). + /// Layer-cache lookups that missed the store (disk keys, 32 hex digits). #[serde(default, rename = "layerMisses", skip_serializing_if = "Vec::is_empty")] layer_misses: Vec, /// Layer buffers served from the store (fetched from disk). @@ -263,9 +264,8 @@ pub struct FrameServer { revision: Option, /// The frame being rendered in passes. pending: Option, - /// The disk cache's layer buffers (see the module docs) and the project's salt. + /// The disk cache's layer buffers (see the module docs). layer_store: Option>, - salt: u64, /// Size and content hash for footage paths with no native metadata (the browser file table). virtual_id: Option Option<(u64, u64)> + Send + Sync>>, /// The source files the last finished frame read ([`FrameServer::take_files`]). @@ -300,15 +300,15 @@ impl FrameServer { revision: None, pending: None, layer_store: None, - salt: 0, virtual_id: None, files: None, } } - /// Identity of virtual footage files, used when native metadata cannot describe the path. - /// Called from `FrameServer::load`, not from the UI thread's cache lookup. + /// Identity of virtual footage files, used when native metadata cannot describe the path: + /// what the disk entries of frames and layer buffers keep for them and are checked against. pub fn set_virtual_id(&mut self, id: Option Option<(u64, u64)> + Send + Sync>>) { + self.cache.set_virtual_id(id.clone()); self.virtual_id = id; } @@ -334,11 +334,6 @@ impl FrameServer { self.layer_store.as_ref() } - /// The salt of the replica's layer keys on disk (keys are `(salt, key)`). - pub fn salt(&self) -> u64 { - self.salt - } - /// Render with `accel` when the request's backend asks for it (the worker's GPU). Its miss /// gate keeps placeholder buffers of unfinished passes out of the layer cache. pub fn set_accel(&mut self, accel: Option>) { @@ -365,8 +360,6 @@ impl FrameServer { fn load(&mut self, revision: u64) -> Result<(), String> { let p = Project::from_json(&self.doc.to_string()).map_err(|e| e.to_string())?; - self.salt = effectcraft_render::disk_cache::footage_salt_with(&p, self.virtual_id.as_deref()); - self.cache.set_store_salt(self.salt); self.project = Some(Arc::new(p)); self.revision = Some(revision); Ok(()) @@ -410,7 +403,7 @@ impl FrameServer { } FrameMsg::Render { id, revision, comp, time, opts, layers, .. } => { let store = self.layer_store.clone().filter(|_| layers); - self.cache.set_store(store.map(|s| (s as Arc, self.salt))); + self.cache.set_store(store.map(|s| s as Arc)); let fail = |error: String, stale: bool| vec![(FrameReply::Failed { id, error, stale }, None)]; if self.revision != Some(revision) { return fail(format!("the replica is at {:?}, not {revision}", self.revision), true); diff --git a/crates/engine/src/background/remote/tests.rs b/crates/engine/src/background/remote/tests.rs index 7a7a59f3f..c35d7a717 100644 --- a/crates/engine/src/background/remote/tests.rs +++ b/crates/engine/src/background/remote/tests.rs @@ -69,7 +69,8 @@ fn layer_buffers_go_through_the_disk_store() { assert!(!layer_misses.is_empty() && layer_hits.is_empty()); let writes = store_a.take_writes(); assert!(!writes.is_empty()); - assert!(writes.iter().all(|(k, _)| (*k >> 64) as u64 == a.salt()), "keys are salted per project"); + // Sealed with the files each buffer was made of (none here: the demo reads no footage). + assert!(writes.iter().all(|(_, e)| effectcraft_render::disk_cache::read_layer_entry(e).is_some_and(|(_, f)| f.is_empty()))); let mut index = DiskIndex::default(); let mut disk = std::collections::HashMap::new(); for (k, e) in writes { diff --git a/crates/engine/src/footage/availability.rs b/crates/engine/src/footage/availability.rs index 7ad2bc03f..75e2a1e1c 100644 --- a/crates/engine/src/footage/availability.rs +++ b/crates/engine/src/footage/availability.rs @@ -215,20 +215,18 @@ impl Scanner { } } -/// A disk observation prepared entirely by the existing worker, including the potentially -/// expensive sequence stamps used for disk-cache keys. The UI only swaps a current snapshot. +/// A disk observation prepared entirely by the existing worker. The UI only swaps a current +/// snapshot (the disk cache needs nothing: its entries check their own files when read, #3184). pub(crate) struct Update { before: Arc, after: Arc, paths: BTreeSet, newly_missing: usize, - cache_enabled: bool, - salt: Option<(u64, u64)>, } -/// Prepare a replacement only when availability changed. Project cloning and optional disk -/// salt computation belong on the worker; apply later rejects an outdated project snapshot. -pub(crate) fn prepare(project: &Arc, sources: &[Source], missing: &[bool], cache_enabled: bool) -> Option { +/// Prepare a replacement only when availability changed. Project cloning belongs on the +/// worker; apply later rejects an outdated project snapshot. +pub(crate) fn prepare(project: &Arc, sources: &[Source], missing: &[bool]) -> Option { let mut after = project.clone(); let mut paths = BTreeSet::new(); let mut newly_missing = 0; @@ -245,22 +243,17 @@ pub(crate) fn prepare(project: &Arc, sources: &[Source], missing: &[boo if paths.is_empty() { return None; } - let salt = cache_enabled.then(|| (Session::footage_fingerprint(&after), crate::render::disk_cache::footage_salt(&after))); - Some(Update { before: project.clone(), after, paths, newly_missing, cache_enabled, salt }) + Some(Update { before: project.clone(), after, paths, newly_missing }) } impl Update { - /// False means a newer project or cache configuration needs a fresh observation. + /// False means a newer project needs a fresh observation. pub fn apply(self, s: &mut Session) -> bool { - if !Arc::ptr_eq(&s.project, &self.before) || s.disk_cache.is_some() != self.cache_enabled { + if !Arc::ptr_eq(&s.project, &self.before) { return false; } let dirty = s.is_dirty(); s.project = self.after; - if let Some((fingerprint, salt)) = self.salt { - s.disk_salt = Some((fingerprint, salt)); - s.layer_cache.set_disk_salt(salt); - } s.bump(); if !dirty { s.mark_saved(); @@ -371,7 +364,7 @@ mod tests { fn stale_observation_cannot_mark_a_replacement_missing() { let (mut s, id) = session(Arc::new(Disk::default())); let old = sources(&s); - let update = prepare(&s.project, &old, &[true, true], false).unwrap(); + let update = prepare(&s.project, &old, &[true, true]).unwrap(); if let ItemKind::Footage(f) = &mut Arc::make_mut(&mut s.project).item_mut(id).unwrap().kind { f.path = "/new.png".into(); } @@ -398,9 +391,12 @@ mod tests { assert_eq!(disk.looks.load(Ordering::Relaxed), 2, "one file per source, no scan of an unmounted folder"); } + /// An availability change does no disk-cache work (#3184): the cache stays attached and + /// no file is looked at for it, on the worker or when the UI applies the observation (it + /// used to stamp every footage file for a new layer salt). #[test] - fn applying_prepared_cache_salt_does_not_restat_files_on_the_ui_thread() { - let dir = std::env::temp_dir().join(format!("ec-availability-salt-{}", std::process::id())); + fn applying_an_availability_change_does_no_disk_cache_work() { + let dir = std::env::temp_dir().join(format!("ec-availability-cache-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("plate.png"); std::fs::write(&file, b"plate").unwrap(); @@ -413,16 +409,13 @@ mod tests { ); let cache = crate::render::disk_cache::DiskCache::open(dir.join("cache"), 1 << 20).unwrap(); s.disk_cache = Some(cache.clone()); - s.layer_cache.set_disk(Some((cache, 0))); + s.layer_cache.set_disk(Some(cache.clone())); s.mark_saved(); - let update = prepare(&s.project, &sources(&s), &[false], true).unwrap(); - let expected = update.salt.unwrap().1; - // The filesystem can change again after the worker's observation. Applying it must - // retain that observation's salt, rather than scan the disk a second time on the UI. + let update = prepare(&s.project, &sources(&s), &[false]).unwrap(); std::fs::remove_file(file).unwrap(); - assert_ne!(crate::render::disk_cache::footage_salt(&update.after), expected); assert!(update.apply(&mut s)); - assert_eq!(s.disk_salt.map(|(_, salt)| salt), Some(expected)); + assert!(s.layer_cache.disk().is_some_and(|d| Arc::ptr_eq(&d, &cache)), "still attached"); + assert_eq!(cache.file_checks(), 0, "no file looked at for the disk cache"); assert!(!s.is_dirty()); drop(s); std::fs::remove_dir_all(dir).unwrap(); diff --git a/crates/engine/src/footage/footage_check.rs b/crates/engine/src/footage/footage_check.rs index 9e941a6ed..42401d195 100644 --- a/crates/engine/src/footage/footage_check.rs +++ b/crates/engine/src/footage/footage_check.rs @@ -272,7 +272,7 @@ mod tests { let id = source.id; let mut recovered = source.footage.clone(); recovered.path = "/new/project/plate.png".into(); - let observed = super::super::availability::prepare(&s.project, std::slice::from_ref(&source), &[true], false).unwrap(); + let observed = super::super::availability::prepare(&s.project, std::slice::from_ref(&source), &[true]).unwrap(); assert!(observed.apply(&mut s)); assert!(matches!(&s.project.item(id).unwrap().kind, ItemKind::Footage(f) if f.missing)); let result = apply(&mut s, vec![(source, Found::Moved(Box::new(recovered)))]); diff --git a/crates/engine/src/footage/footage_reload.rs b/crates/engine/src/footage/footage_reload.rs index 7065620af..4232e1d11 100644 --- a/crates/engine/src/footage/footage_reload.rs +++ b/crates/engine/src/footage/footage_reload.rs @@ -76,7 +76,6 @@ pub struct Watched { reload: BTreeSet, sources: Arc>, project: Option>, - cache_enabled: bool, reload_mode: String, stored_paths: crate::doc_path::StoredPaths, } @@ -85,8 +84,7 @@ impl PartialEq for Watched { /// Compare watched inputs, excluding unrelated project edits whose latest Arc is refreshed /// separately without waking the worker or restarting partial sequence scans. fn eq(&self, other: &Self) -> bool { - self.cache_enabled == other.cache_enabled - && self.stored_paths == other.stored_paths + self.stored_paths == other.stored_paths && self.reload_mode == other.reload_mode && self.reload == other.reload && (Arc::ptr_eq(&self.sources, &other.sources) || self.sources == other.sources) @@ -100,7 +98,6 @@ pub fn watched(s: &Session) -> Watched { reload: automatic_paths(s), sources: Arc::new(if s.check_footage_on_open { availability::sources(s) } else { Vec::new() }), project: Some(s.project.clone()), - cache_enabled: s.disk_cache.is_some(), reload_mode: s.prefs.import.auto_reload_footage.clone(), stored_paths: s.stored_paths.clone(), } @@ -139,10 +136,10 @@ pub struct Scan { } impl Scan { - /// Prepare availability and cache state before the session applies the observation. + /// Prepare the availability change before the session applies the observation. /// Automatic callers construct this result on the worker; explicit commands run inline. fn new(watched: Watched, observation: Observation, policy: ReloadPolicy) -> Self { - let update = watched.project.as_ref().and_then(|p| availability::prepare(p, &watched.sources, &observation.missing, watched.cache_enabled)); + let update = watched.project.as_ref().and_then(|p| availability::prepare(p, &watched.sources, &observation.missing)); Self { watched, observation, update, policy } } @@ -281,7 +278,7 @@ fn reload(s: &mut Session, ids: &[ItemId], undoable: bool) -> crate::Result<(usi } let n = updates.len(); apply_reloads(s, updates, undoable)?; - forget(s, &paths); + forget_media(s, &paths); Ok((n, failed)) } @@ -320,14 +317,8 @@ fn apply_reloads(s: &mut Session, updates: Vec<(ItemId, Footage)>, undoable: boo Ok(()) } -/// Make the media layer and the layer cache let go of `paths`, so renders read them again. -fn forget(s: &mut Session, paths: &BTreeSet) { - forget_media(s, paths); - s.refresh_disk_salt(true); -} - -/// Invalidate decoded and rendered buffers without probing the disk for a new salt. -/// Availability updates already carry their worker-computed salt; content reload refreshes it. +/// Make the media layer and the layer cache let go of `paths`, so renders read them again. The +/// disk cache needs nothing: its entries check the files they were made of when read (#3184). pub(crate) fn forget_media(s: &mut Session, paths: &BTreeSet) { for p in paths { s.footage.forget(p); @@ -374,7 +365,7 @@ pub fn apply_stamps(s: &mut Session, now: Vec<(String, Option)>) -> crate return Ok(json!({"files": 0, "reloaded": 0})); } // Changed frames of image sequences (their items keep their metadata). - forget(s, &changed); + forget_media(s, &changed); let files = changed.len(); s.toast(if reloaded > 0 { format!("Reloaded {reloaded} footage item(s) changed on disk") @@ -391,7 +382,6 @@ pub(crate) fn command(s: &mut Session, _: &Value) -> crate::Result { reload: reload_paths(s), sources: Arc::new(availability::sources(s)), project: Some(s.project.clone()), - cache_enabled: s.disk_cache.is_some(), reload_mode: s.prefs.import.auto_reload_footage.clone(), stored_paths: s.stored_paths.clone(), }; @@ -452,12 +442,7 @@ impl Watcher { pub fn update(&mut self, s: &Session) { let same_sources = availability::sources_match(s, &self.paths.sources); let same_data = self.paths.project.as_ref().is_some_and(|before| data_paths(before).eq(data_paths(&s.project))); - if same_sources - && same_data - && self.paths.stored_paths == s.stored_paths - && self.paths.reload_mode == s.prefs.import.auto_reload_footage - && self.paths.cache_enabled == s.disk_cache.is_some() - { + if same_sources && same_data && self.paths.stored_paths == s.stored_paths && self.paths.reload_mode == s.prefs.import.auto_reload_footage { let project = Some(s.project.clone()); self.paths.project = project.clone(); self.pending.lock().unwrap_or_else(PoisonError::into_inner).paths.project = project; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e50b15d04..69d1f9e1b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -97,7 +97,7 @@ pub use error::{EngineError, Result}; pub use event::Event; pub use fonts::{FontRow, font_features, font_menu, font_preview, font_styles, text_families}; pub use services::{FsServices, Importer, Services}; -pub use session::{DiskSaltJob, upgrade_effects}; +pub use session::upgrade_effects; pub struct Session { pub project: Arc, @@ -254,14 +254,6 @@ pub struct Session { /// Each footage file's size and modification time when last seen (Settings ▸ Import ▸ /// Reload Footage Changed on Disk, [`footage_reload`]). pub footage_stamps: std::collections::HashMap, - /// The disk cache's footage salt and the footage it was taken for ([`Session::refresh_disk_salt`]). - pub disk_salt: Option<(u64, u64)>, - /// Take the disk cache's footage salt on a worker thread ([`Session::refresh_disk_salt`]): - /// frontends with an event loop (the desktop app) turn this on and call - /// [`Session::poll_disk_salt`] each frame; headless sessions take it at once. - pub disk_salt_background: bool, - /// The footage salt being taken in the background. - pub disk_salt_job: Option, /// The footage files effects read the channels of, as last given to the footage source /// ([`Session::refresh_aux_footage`]); `None` = not given yet. pub aux_footage: Option>, @@ -391,9 +383,6 @@ impl Default for Session { check_footage_on_open: false, stored_paths: Default::default(), footage_stamps: Default::default(), - disk_salt: None, - disk_salt_background: false, - disk_salt_job: None, aux_footage: None, script_calls: ScriptCalls::default(), } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 31ed40c1d..18b0ff4cf 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -10,4 +10,4 @@ mod dispatch; mod edit; mod render; -pub use edit::{DiskSaltJob, upgrade_effects}; +pub use edit::upgrade_effects; diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 28813e2ec..67a8e4dcb 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -97,114 +97,10 @@ impl Session { if Arc::ptr_eq(&self.project, &self.saved_project) { self.saved_revision = self.revision; } - self.refresh_disk_salt(false); self.refresh_aux_footage(); self.events.push(Event::ProjectChanged { revision: self.revision }); } - /// Salt the disk cache's layer keys with the project's footage files - /// ([`effectcraft_render::disk_cache::footage_salt`]) and attach the disk cache to the layer - /// cache with it. Taking it reads the size and time of every file, every frame of an image - /// sequence included, so it is taken again only when the footage items changed, or with - /// `force` (a project opened, footage reloaded, the disk cache attached), not at every edit: - /// with a few large sequences that cost each keystroke in a text field over half a second - /// (#1926). - /// - /// With [`Session::disk_salt_background`] the files are read on a worker thread: an imported - /// or opened project with thousands of sequence frames on a network share took half a minute - /// to stamp, all of it on the UI thread. Until [`Session::poll_disk_salt`] picks the salt up, - /// renders use the memory cache only (keys under the old salt may name other files, or - /// another project's items) and this returns `None`. - pub fn refresh_disk_salt(&mut self, force: bool) -> Option { - let Some(dc) = self.disk_cache.clone() else { - self.disk_salt = None; - self.disk_salt_job = None; - return None; - }; - self.poll_disk_salt(); - let footage = Self::footage_fingerprint(&self.project); - if !force { - if let Some((seen, salt)) = self.disk_salt - && seen == footage - { - return Some(salt); - } - if self.disk_salt_job.as_ref().is_some_and(|j| j.footage == footage) { - return None; - } - } - if self.disk_salt_background && !cfg!(target_arch = "wasm32") { - let project = self.project.clone(); - let slot: Arc>> = Arc::default(); - let out = slot.clone(); - let spawned = std::thread::Builder::new().name("ec-disk-salt".into()).spawn(move || { - let salt = effectcraft_render::disk_cache::footage_salt(&project); - if let Ok(mut s) = out.lock() { - *s = Some(salt); - } - }); - // Without a thread the salt is taken here, as before. - if let Ok(thread) = spawned { - self.disk_salt = None; - self.disk_salt_job = Some(DiskSaltJob { footage, slot, thread }); - self.layer_cache.set_disk(None); - return None; - } - } - self.disk_salt_job = None; - let salt = effectcraft_render::disk_cache::footage_salt(&self.project); - self.disk_salt = Some((footage, salt)); - self.layer_cache.set_disk(Some((dc, salt))); - Some(salt) - } - - /// Pick up a footage salt taken in the background ([`Session::refresh_disk_salt`]) and attach - /// the disk cache with it. Returns whether one is still being taken (frontends call this each - /// frame while it is). - pub fn poll_disk_salt(&mut self) -> bool { - let Some(job) = &self.disk_salt_job else { return false }; - // (looked at first: a worker that has finished has left its salt in the slot) - let finished = job.thread.is_finished(); - let salt = job.slot.lock().ok().and_then(|mut s| s.take()); - let footage = job.footage; - match salt { - Some(salt) => { - self.disk_salt_job = None; - if let Some(dc) = self.disk_cache.clone() { - self.disk_salt = Some((footage, salt)); - self.layer_cache.set_disk(Some((dc, salt))); - } - false - } - None if finished => { - // The worker stopped without a salt: the disk cache stays off until the next - // edit takes it again. - log::warn!("disk cache: the footage files could not be stamped; the disk cache is off until the next edit"); - self.disk_salt_job = None; - false - } - None => true, - } - } - - /// In-memory identity of the footage settings represented by a disk salt. Workers use the - /// same fingerprint when preparing availability changes without disk access on the UI. - pub(crate) fn footage_fingerprint(project: &effectcraft_project::Project) -> u64 { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - for (id, item) in &project.items { - if let effectcraft_project::ItemKind::Footage(f) = &item.kind { - id.hash(&mut h); - format!("{f:?}").hash(&mut h); - } - if let Some(proxy) = &item.proxy { - id.hash(&mut h); - format!("{proxy:?}").hash(&mut h); - } - } - h.finish() - } - /// Set a comp's Resolution. As in After Effects it is saved with the project (which becomes /// modified) but is no undo step, and it changes no pixels: the comp's cached frames stay /// valid ([`effectcraft_project::Comp::same_pixels`]). @@ -322,11 +218,6 @@ impl Session { } self.layer_cache.clear(); self.project = Arc::new(p); - // Its files may have changed since they were last stamped. - self.disk_salt = None; - // A salt still being taken is for the old project's files: dropped, so that the next refresh - // stamps the new project anew (a matching fingerprint would otherwise keep the stale job). - self.disk_salt_job = None; // The set of footage effects read the channels of is sent again, even when it is empty. self.aux_footage = None; self.history = History::default(); @@ -389,11 +280,3 @@ pub fn upgrade_effects(p: &mut Project) { p.next_id = next; p.schema = effectcraft_project::SCHEMA_VERSION; } - -/// A footage salt being taken on a worker thread ([`Session::refresh_disk_salt`]). -pub struct DiskSaltJob { - /// The footage it is taken for ([`Session::footage_fingerprint`]). - footage: u64, - slot: Arc>>, - thread: std::thread::JoinHandle<()>, -} diff --git a/crates/engine/src/settings/session_settings.rs b/crates/engine/src/settings/session_settings.rs index 056616201..b479963ed 100644 --- a/crates/engine/src/settings/session_settings.rs +++ b/crates/engine/src/settings/session_settings.rs @@ -137,10 +137,6 @@ impl Session { // over the store of a roto test running beside it. Serialise them with the roto tests. #[cfg(test)] crate::tests::roto::hold_roto_cache_test_lock(); - // Another setting changed (the disk cache stays as it is): its salt still holds, and - // stamping every footage file again would cost each settings change seconds with large - // sequences. - let kept = self.disk_cache.as_ref().is_some_and(|c| c.folder() == folder.as_path()); let dc = match &self.disk_cache { Some(c) if c.folder() == folder.as_path() => { c.set_max_bytes(max); @@ -165,8 +161,9 @@ impl Session { self.disk_cache = Some(dc.clone()); // The reserve applies from the start (a new folder's watcher is idle). self.poll_disk_space(); - // Attaches the disk cache to the layer cache once the footage salt is known. - self.refresh_disk_salt(!kept); + // Used at once (no file is looked at first: each entry checks the source files it lists + // when it is read, #3184). + self.layer_cache.set_disk(Some(dc.clone())); // Roto Brush / Object Matte segmentations persist there too (held weakly: switching the // disk cache off drops it). let store: std::sync::Arc = dc.clone(); diff --git a/crates/engine/src/tests/disk_cache.rs b/crates/engine/src/tests/disk_cache.rs index 4805d68fe..e2b1544b3 100644 --- a/crates/engine/src/tests/disk_cache.rs +++ b/crates/engine/src/tests/disk_cache.rs @@ -76,11 +76,13 @@ fn disk_cache_settings_persistence_and_invalidation() { assert!(s2.layer_cache.disk().is_none()); } +/// The comp key comes from the project in memory: a footage file that changes on disk doesn't +/// change it (the entries check their own files, #3184); edits that change pixels do. #[test] -fn footage_changes_change_the_salt() { - let dir = folder("salt"); +fn comp_content_keys_come_from_memory() { + let dir = folder("keys"); let mut s = session(&dir); - let foot = std::env::temp_dir().join(format!("effectcraft-salt-{}.png", std::process::id())); + let foot = std::env::temp_dir().join(format!("effectcraft-keys-{}.png", std::process::id())); std::fs::write(&foot, b"one").unwrap(); s.edit("add", None, |p, _| { let f = effectcraft_project::Footage { @@ -108,12 +110,10 @@ fn footage_changes_change_the_salt() { Ok(()) }) .unwrap(); - let a = effectcraft_render::disk_cache::footage_salt(&s.project); - std::fs::write(&foot, b"two, longer").unwrap(); - let b = effectcraft_render::disk_cache::footage_salt(&s.project); - assert_ne!(a, b); let cid = project(&mut s); let k1 = effectcraft_render::disk_cache::comp_content_key(&s.project, cid); + std::fs::write(&foot, b"two, longer").unwrap(); + assert_eq!(effectcraft_render::disk_cache::comp_content_key(&s.project, cid), k1, "no file is looked at"); s.execute("prop.set", json!({"layer": "#1", "path": "transform/opacity", "value": 50})).unwrap(); let k2 = effectcraft_render::disk_cache::comp_content_key(&s.project, cid); assert_ne!(k1, k2); @@ -137,66 +137,51 @@ fn footage_changes_change_the_salt() { assert_ne!(set_proxy(&mut s, false), k3); } -/// The desktop app stamps footage files for the disk cache's salt on a worker thread: importing an -/// After Effects project with thousands of sequence frames on a network share stamped them all -/// inside the import's edit, freezing the UI for half a minute. Until the salt lands the disk -/// cache sits out (keys under the old salt may name other files); a newer footage change -/// supersedes a salt still being taken; a settings change keeps the salt. +/// No salt and no scan (#3184, replacing the background footage salt of #3106): the disk cache +/// is attached to the layer cache as soon as it is switched on, and stays attached through +/// edits that add footage (a large image sequence included), settings changes and opening a +/// project, none of which looks at a single file for it. The first render may use it at once. #[test] -fn footage_salt_is_taken_off_the_ui_thread_and_the_disk_cache_waits_for_it() { - let dir = folder("bg-salt"); +fn the_disk_cache_is_attached_at_once_and_edits_do_no_file_work() { + let dir = folder("attach"); let mut s = session(&dir); - s.disk_salt_background = true; - let at = |n: &str| std::env::temp_dir().join(format!("effectcraft-bg-salt-{}-{n}.png", std::process::id())); - let add = |s: &mut Session, path: &std::path::Path| { - let f = effectcraft_project::Footage { - path: path.to_string_lossy().to_string(), - kind: effectcraft_project::FootageKind::Still, - width: 1, - height: 1, - has_video: true, - ..Default::default() - }; - s.edit("add", None, |p, _| { - p.add_item("f.png", effectcraft_color::Label::None, None, effectcraft_project::ItemKind::Footage(f)); - Ok(()) - }) - .unwrap(); + let dc = s.disk_cache.clone().unwrap(); + let attached = |s: &Session| s.layer_cache.disk().is_some_and(|d| std::sync::Arc::ptr_eq(&d, &dc)); + assert!(attached(&s), "attached at once"); + // A sequence of 5000 frames that don't even exist. + let seq_dir = std::env::temp_dir().join(format!("effectcraft-no-scan-{}", std::process::id())); + let f = effectcraft_project::Footage { + path: seq_dir.join("f_00000.exr").to_string_lossy().to_string(), + kind: effectcraft_project::FootageKind::Sequence, + sequence: (0..5000).map(|i| seq_dir.join(format!("f_{i:05}.exr")).to_string_lossy().to_string()).collect(), + width: 8, + height: 8, + has_video: true, + ..Default::default() }; - let wait = |s: &mut Session| { - let t0 = std::time::Instant::now(); - while s.poll_disk_salt() { - assert!(t0.elapsed().as_secs() < 20, "the salt never landed"); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - }; - assert!(s.layer_cache.disk().is_some(), "attached with its salt"); - std::fs::write(at("a"), b"one").unwrap(); - add(&mut s, &at("a")); - // The edit returned before the files were stamped, and the disk cache waits for the salt. - assert!(s.disk_salt.is_none() && s.layer_cache.disk().is_none()); - // Edits that leave the footage alone don't start over (and may pick up the salt meanwhile). - s.execute("comp.new", json!({"name": "C", "width": 8, "height": 8, "frameRate": 30, "duration": 1})).unwrap(); - let r = s.refresh_disk_salt(false); - assert!(r.is_none() || r == Some(effectcraft_render::disk_cache::footage_salt(&s.project)), "{r:?}"); - // New footage while it is taken: the salt for the newest footage lands. - std::fs::write(at("b"), b"two").unwrap(); - add(&mut s, &at("b")); - wait(&mut s); - let salt = effectcraft_render::disk_cache::footage_salt(&s.project); - assert_eq!(s.disk_salt.map(|(_, salt)| salt), Some(salt)); - assert_eq!(s.refresh_disk_salt(false), Some(salt)); - assert!(s.layer_cache.disk().is_some(), "attached again"); - // Another setting keeps the salt and the disk cache attached. + s.edit("add", None, |p, _| { + p.add_item("seq", effectcraft_color::Label::None, None, effectcraft_project::ItemKind::Footage(f)); + Ok(()) + }) + .unwrap(); + assert!(attached(&s), "an import keeps it attached"); + let cid = project(&mut s); + s.execute("prop.set", json!({"layer": "#1", "path": "transform/opacity", "value": 50})).unwrap(); s.execute_checked("prefs.set", json!({"key": "disk.diskCacheMaxGb", "value": 30})).unwrap(); - assert!(s.layer_cache.disk().is_some() && s.disk_salt.map(|(_, salt)| salt) == Some(salt)); - // Turned off and on again: stamped anew, in the background. + assert!(attached(&s), "edits and other settings keep it attached"); + let same = (*s.project).clone(); + s.replace_project(same, None); + assert!(attached(&s), "opening a project keeps it attached"); + // The first render uses it: a solid reads no file, so nothing is checked either. + s.render(cid, s.time(), RenderOpts::default()); + dc.flush(); + assert!(dc.stats().entries > 0, "written by the first render"); + assert_eq!(dc.file_checks(), 0, "no file looked at for the disk cache"); + // Switched off and on: attached again at once. s.execute_checked("prefs.set", json!({"key": "disk.diskCacheEnabled", "value": false})).unwrap(); + assert!(s.layer_cache.disk().is_none()); s.execute_checked("prefs.set", json!({"key": "disk.diskCacheEnabled", "value": true})).unwrap(); - wait(&mut s); - assert_eq!(s.refresh_disk_salt(false), Some(salt)); - let _ = std::fs::remove_file(at("a")); - let _ = std::fs::remove_file(at("b")); + assert!(s.layer_cache.disk().is_some()); } /// Marker edits keep the disk key (the sound of a playing preview must not wait for frames to @@ -257,39 +242,3 @@ fn protected_markers_with_a_duration_change_the_content_key() { s.execute("markers.set", json!({"comp": inner.0, "index": index, "duration": 2.0})).unwrap(); assert_ne!(key(&s), k1, "its duration"); } - -/// A project opened while a footage salt is still being taken must not keep that salt when it -/// names the same footage: its files may have changed since the worker read them. -#[test] -fn opening_a_project_drops_the_footage_salt_being_taken() { - let dir = folder("bg-salt-open"); - let mut s = session(&dir); - s.disk_salt_background = true; - let path = std::env::temp_dir().join(format!("effectcraft-bg-salt-open-{}.png", std::process::id())); - std::fs::write(&path, b"one").unwrap(); - let f = effectcraft_project::Footage { - path: path.to_string_lossy().to_string(), - kind: effectcraft_project::FootageKind::Still, - width: 1, - height: 1, - has_video: true, - ..Default::default() - }; - s.edit("add", None, |p, _| { - p.add_item("f.png", effectcraft_color::Label::None, None, effectcraft_project::ItemKind::Footage(f)); - Ok(()) - }) - .unwrap(); - // The file changes after the edit started the salt, before the same footage is opened again. - std::fs::write(&path, b"a longer content").unwrap(); - let same = (*s.project).clone(); - s.replace_project(same, None); - let t0 = std::time::Instant::now(); - while s.poll_disk_salt() { - assert!(t0.elapsed().as_secs() < 20, "the salt never landed"); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - let now = effectcraft_render::disk_cache::footage_salt(&s.project); - assert_eq!(s.disk_salt.map(|(_, salt)| salt), Some(now), "the salt reflects the file as it is now"); - let _ = std::fs::remove_file(&path); -} diff --git a/crates/engine/src/tests/sequence.rs b/crates/engine/src/tests/sequence.rs index cf6968e3f..2189a36a8 100644 --- a/crates/engine/src/tests/sequence.rs +++ b/crates/engine/src/tests/sequence.rs @@ -268,30 +268,31 @@ fn dpx_and_cineon_runs_import_as_sequences() { assert_eq!(got, [("plate.[0001-0003].dpx".to_string(), 3), ("scan_[01-02].cin".to_string(), 2)], "{r}"); } -/// #1926: an edit that leaves the footage alone doesn't stamp every frame of its image sequences -/// again for the disk cache's salt (with large sequences each keystroke in a text field took over -/// half a second); Reload Footage does, and so does new footage. +/// #1926, #3184: an edit does no file work at all for the disk cache (it used to stamp every +/// frame of the project's image sequences for a salt; with large sequences each keystroke in a +/// text field took over half a second): the cache stays attached and no file is looked at, after +/// edits, after a frame of the sequence was rewritten, after Reload Footage and new footage. +/// Entries check the files they list when they are read instead. #[test] -fn edits_keep_the_disk_salt_and_reload_stamps_the_files_again() { +fn edits_do_no_disk_cache_file_work() { let dir = folder(&RUN); - let cache = std::env::temp_dir().join(format!("ec-seq-salt-{}", std::process::id())); + let cache = std::env::temp_dir().join(format!("ec-seq-nofiles-{}", std::process::id())); let _ = std::fs::remove_dir_all(&cache); let mut s = session(); s.execute_checked("prefs.set", json!({"values": {"disk.diskCacheFolder": cache.to_string_lossy(), "disk.diskCacheEnabled": true}})).unwrap(); + let dc = s.disk_cache.clone().expect("a disk cache"); + let attached = |s: &Session| s.layer_cache.disk().is_some_and(|d| std::sync::Arc::ptr_eq(&d, &dc)); s.execute("comp.new", json!({"name": "C", "width": 64, "height": 32, "frameRate": 30, "duration": 1})).unwrap(); let r = s.execute("file.import", json!({"paths": [at(&dir, "shot_0002.png")], "sequence": true, "addToComp": true})).unwrap(); let item = r["items"][0].clone(); - let salt = s.refresh_disk_salt(false).expect("a disk cache"); // A frame rewritten in place: same footage settings, another size on disk. std::fs::write(at(&dir, "shot_0004.png"), b"a new render of this frame").unwrap(); s.execute("layer.newText", json!({"text": "title"})).unwrap(); s.execute("layer.setText", json!({"text": "title 2"})).unwrap(); - assert_eq!(s.refresh_disk_salt(false), Some(salt), "edits don't stamp the files again"); s.execute("file.reloadFootage", json!({"items": [item]})).unwrap(); - let reloaded = s.refresh_disk_salt(false).unwrap(); - assert_ne!(reloaded, salt, "Reload Footage stamps them again"); std::fs::write(at(&dir, "extra.png"), b"").unwrap(); s.execute("file.import", json!({"paths": [at(&dir, "extra.png")]})).unwrap(); - assert_ne!(s.refresh_disk_salt(false), Some(reloaded), "new footage counts"); + assert!(attached(&s), "attached all along"); + assert_eq!(dc.file_checks(), 0, "no file looked at for the disk cache"); let _ = std::fs::remove_dir_all(&cache); } diff --git a/crates/media/src/reads/tests.rs b/crates/media/src/reads/tests.rs index 8fee7d211..5dae8415a 100644 --- a/crates/media/src/reads/tests.rs +++ b/crates/media/src/reads/tests.rs @@ -189,3 +189,202 @@ fn a_frame_served_from_memory_reports_its_files_without_touching_them() { assert_eq!(from_pool, first); assert_eq!(crate::opens_under(&dir), opened, "nothing was opened on disk"); } + +// ---------------------------------------------------------------- layer entries on disk (#3184) + +use std::sync::Arc; + +use effectcraft_render::disk_cache::{DiskCache, Kind}; + +/// A "session": a new media pool and layer cache over the disk cache in `cache` (opened anew, +/// as after a restart), writing every layer buffer however quick to render. +fn session(cache: &Path) -> (MediaPool, LayerCache, Arc) { + let dc = DiskCache::open(cache, 1 << 30).unwrap(); + dc.set_min_layer_ms(0); + let lc = LayerCache::default(); + lc.set_disk(Some(dc.clone())); + (MediaPool::new(), lc, dc) +} + +/// Give `path` a later modification time, so a rewrite within the clock's resolution counts. +fn touch_later(path: &Path) { + let t = std::fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(7); + std::fs::File::options().append(true).open(path).unwrap().set_modified(t).unwrap(); +} + +/// Two still plates (the upper one at half opacity, so both show), and a 5000-frame sequence +/// in the project that no layer uses (its files don't even exist). +fn plates(dir: &Path) -> (Project, ItemId, PathBuf) { + let mut p = Project::default(); + let c = comp(); + let a = dir.join("a.png"); + let mut top = footage_layer(&mut p, &c, "A", still(&a, 60)); + top.props.prop_mut("transform/opacity").unwrap().value = Value::Scalar(50.0); + let bottom = footage_layer(&mut p, &c, "B", still(&dir.join("b.png"), 200)); + let unused = dir.join("unused"); + let seq = Footage { + kind: FootageKind::Sequence, + sequence: (0..5000).map(|i| unused.join(format!("big_{i:05}.exr")).to_string_lossy().to_string()).collect(), + frame_rate: RATE, + width: SIZE.0, + height: SIZE.1, + has_video: true, + ..Default::default() + }; + p.add_item("Unused", Label::Aqua, None, ItemKind::Footage(seq)); + let cid = add_comp(&mut p, "C", c, vec![top, bottom]); + (p, cid, a) +} + +/// Correct and no scan: after a restart, only the layer buffer whose source file changed is +/// rendered again (only that file is opened); the other comes from disk with its file list, so +/// the frame's list is complete again (its frame entry can be stored). The disk cache checks +/// exactly the files its entries list, never the unused sequence. The re-rendered buffer +/// replaces its entry: the next restart opens nothing. +#[test] +fn a_changed_file_renders_only_the_layer_buffers_that_read_it_again() { + let dir = folder("layer-disk"); + let (src, cache) = (dir.join("src"), dir.join("cache")); + std::fs::create_dir_all(&src).unwrap(); + let (p, cid, a) = plates(&src); + let (pool, lc, dc) = session(&cache); + let (px, files) = render(&p, &pool, &lc, cid, 0); + assert!(files.is_complete() && files.len() == 2, "{:?}", paths(&files)); + dc.flush(); + let entries = dc.keys(Kind::Layer).len(); + assert!(entries >= 2, "both plates' buffers are on disk: {entries}"); + drop((pool, lc, dc)); + + // Restart without a change: everything from disk, nothing opened, a complete list. + let (pool, lc, dc) = session(&cache); + let opened = crate::opens_under(&src); + let (again, files_again) = render(&p, &pool, &lc, cid, 0); + assert_eq!(again, px); + assert_eq!(files_again, files, "the files of the entries, as they were read"); + assert!(files_again.is_complete(), "a frame made of buffers from disk can be stored"); + assert_eq!(crate::opens_under(&src), opened, "nothing opened"); + let checks = dc.file_checks(); + assert!(checks >= 2 && checks as usize <= entries, "one check per entry used: {checks} of {entries}"); + drop((pool, lc, dc)); + + // a.png gets new pixels: only the top plate renders again. + png(&a, 120); + touch_later(&a); + let (pool, lc, dc) = session(&cache); + let opened = crate::opens_under(&src); + let (changed, files_changed) = render(&p, &pool, &lc, cid, 0); + assert_ne!(changed, px, "the new pixels show"); + assert_eq!(crate::opens_under(&src) - opened, 1, "only the changed file is read"); + assert!(files_changed.is_complete() && files_changed.len() == 2); + assert_stamps_match_disk(&files_changed); + assert!(dc.file_checks() as usize <= entries, "only listed files are checked"); + assert_eq!(crate::opens_under(&src.join("unused")), 0); + dc.flush(); + drop((pool, lc, dc)); + + // Its entry was replaced: the next restart opens nothing and shows the new pixels. + let (pool, lc, _dc) = session(&cache); + let opened = crate::opens_under(&src); + let (last, _) = render(&p, &pool, &lc, cid, 0); + assert_eq!(last, changed); + assert_eq!(crate::opens_under(&src), opened, "both from disk"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Two projects whose footage items have the same ids but name different files never share a +/// layer entry: the layer key names the item's path and settings. +#[test] +fn projects_with_the_same_item_ids_never_share_a_layer_entry() { + let dir = folder("layer-disk-projects"); + let (src, cache) = (dir.join("src"), dir.join("cache")); + std::fs::create_dir_all(&src).unwrap(); + let mut p = Project::default(); + let c = comp(); + let layer = footage_layer(&mut p, &c, "Plate", still(&src.join("one.png"), 40)); + let LayerSource::Footage { item } = layer.source else { panic!("a footage layer") }; + let cid = add_comp(&mut p, "C", c, vec![layer]); + let mut other = p.clone(); + other.item_mut(item).unwrap().kind = ItemKind::Footage(still(&src.join("two.png"), 220)); + let (pool, lc, dc) = session(&cache); + let (one, _) = render(&p, &pool, &lc, cid, 0); + dc.flush(); + drop((pool, lc, dc)); + let (pool, lc, dc) = session(&cache); + let hits = dc.stats().hits; + let (two, files) = render(&other, &pool, &lc, cid, 0); + assert!((two[0] - 220.0 / 255.0).abs() < 0.01, "the other project's own file shows: {two:?}"); + assert_ne!(two, one); + assert_eq!(dc.stats().hits, hits, "no entry of the first project is used"); + assert_eq!(paths(&files), [src.join("two.png").to_string_lossy().to_string()]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Safe: a damaged layer entry, a source file that is missing, one replaced by something +/// unreadable (a folder), and one back with other pixels never serve a stale buffer after a +/// restart; the damaged entry is rendered again, replaced and then used. +#[test] +fn missing_unreadable_files_and_damaged_layer_entries_never_serve_stale_buffers() { + let dir = folder("layer-disk-safe"); + let (src, cache) = (dir.join("src"), dir.join("cache")); + std::fs::create_dir_all(&src).unwrap(); + let mut p = Project::default(); + let c = comp(); + let path = src.join("plate.png"); + let layer = footage_layer(&mut p, &c, "Plate", still(&path, 90)); + let cid = add_comp(&mut p, "C", c, vec![layer]); + let (pool, lc, dc) = session(&cache); + let (shown, _) = render(&p, &pool, &lc, cid, 0); + assert!(shown[3] > 0.99, "the plate shows: {shown:?}"); + dc.flush(); + drop((pool, lc, dc)); + + // A damaged entry: a miss, deleted, rendered again and stored anew. + let layers = cache.join("v1").join(Kind::Layer.dir()); + for shard in std::fs::read_dir(&layers).unwrap().flatten() { + for f in std::fs::read_dir(shard.path()).unwrap().flatten() { + let mut d = std::fs::read(f.path()).unwrap(); + let n = d.len() / 2; + d[n] ^= 0x5a; + std::fs::write(f.path(), d).unwrap(); + } + } + let (pool, lc, dc) = session(&cache); + let opened = crate::opens_under(&src); + let (again, files) = render(&p, &pool, &lc, cid, 0); + assert_eq!(again, shown); + assert_eq!(crate::opens_under(&src) - opened, 1, "read again, not served from the damaged entry"); + assert!(files.is_complete()); + dc.flush(); + drop((pool, lc, dc)); + let (pool, lc, dc) = session(&cache); + let hits = dc.stats().hits; + assert_eq!(render(&p, &pool, &lc, cid, 0).0, shown); + assert!(dc.stats().hits > hits, "the rewritten entry is used"); + drop((pool, lc, dc)); + + // The file is gone: not the old plate. + std::fs::remove_file(&path).unwrap(); + let (pool, lc, dc) = session(&cache); + let hits = dc.stats().hits; + let (gone, files) = render(&p, &pool, &lc, cid, 0); + assert!(gone[3] < 0.01, "a missing file shows nothing, never the cached plate: {gone:?}"); + assert_eq!(dc.stats().hits, hits); + assert!(files.files().iter().all(|f| f.stamp == FileStamp::Missing), "{files:?}"); + dc.flush(); + drop((pool, lc, dc)); + + // Something unreadable at its path (a folder): still not the old plate. + std::fs::create_dir(&path).unwrap(); + let (pool, lc, _dc) = session(&cache); + let (unreadable, _) = render(&p, &pool, &lc, cid, 0); + assert!(unreadable[3] < 0.01, "{unreadable:?}"); + std::fs::remove_dir(&path).unwrap(); + + // Back with other pixels: those show, not the entry made of the old file. + png(&path, 240); + touch_later(&path); + let (pool, lc, _dc) = session(&cache); + let (back, _) = render(&p, &pool, &lc, cid, 0); + assert!((back[0] - 240.0 / 255.0).abs() < 0.01, "{back:?}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index 79b948b89..22c0ebf7f 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -24,6 +24,7 @@ use std::sync::{Arc, Mutex}; use effectcraft_effects::Buf; use effectcraft_project::{FootageKind, ItemKind, Layer, LayerSource, Node, PropGroup}; +use crate::disk_cache::{EntryFiles, SharedVirtualFileId, VirtualFileId, layer_disk_key}; use crate::eval::EvalCtx; use crate::reads::ReadFiles; @@ -31,13 +32,17 @@ mod dependencies; /// Thread-safe, memory-budgeted cache of processed layer buffers, optionally backed by the /// persistent [`DiskCache`](crate::disk_cache::DiskCache): a memory miss reads the disk, and -/// buffers that were slow to render are written there (keys salted per project, see -/// [`LayerCache::set_disk`]). +/// buffers that were slow to render are written there with the source files they were made of +/// (keys: [`crate::disk_cache::layer_disk_key`]; an entry is used only while its files are +/// unchanged, #3184). pub struct LayerCache { inner: Mutex, - disk: Mutex, u64)>>, + disk: Mutex>>, /// Another persistent store when there is no disk cache (the browser's, [`PrefetchStore`]). - store: Mutex, u64)>>, + store: Mutex>>, + /// Size and content hash of files served from memory (the browser file table), to store + /// and check the source files of persistent entries. + virtual_id: Mutex>, /// While set, inserts are dropped (see [`LayerCache::set_gate`]). gate: Mutex>>, } @@ -83,6 +88,7 @@ impl LayerCache { inner: Mutex::new(Inner { map: HashMap::new(), bytes: 0, budget, clock: 0, hits: 0, misses: 0, missed_at: HashMap::new() }), disk: Mutex::new(None), store: Mutex::new(None), + virtual_id: Mutex::new(None), gate: Mutex::new(None), } } @@ -101,58 +107,49 @@ impl LayerCache { self.gate.lock().ok().and_then(|g| g.as_ref().map(|g| g.load(std::sync::atomic::Ordering::Relaxed))).unwrap_or(false) } - /// Attach (or detach) the disk cache. `salt` separates projects and footage versions (see - /// `footage_salt`); keys on disk are `(salt, key)`. - pub fn set_disk(&self, disk: Option<(Arc, u64)>) { + /// Attach (or detach) the disk cache. It is used at once: its entries check their own + /// source files when read, so nothing has to be looked at first. + pub fn set_disk(&self, disk: Option>) { if let Ok(mut d) = self.disk.lock() { *d = disk; } } - /// Change the disk salt (after footage changed) keeping the attached disk cache. - pub fn set_disk_salt(&self, salt: u64) { - if let Ok(mut d) = self.disk.lock() - && let Some((_, s)) = d.as_mut() - { - *s = salt; - } - } - pub fn disk(&self) -> Option> { - self.disk.lock().ok()?.as_ref().map(|d| d.0.clone()) + self.disk.lock().ok()?.clone() } /// Attach (or detach) a [`LayerStore`] used when no disk cache is attached (the browser's - /// Origin Private File System through a [`PrefetchStore`]); `salt` as in - /// [`LayerCache::set_disk`]. - pub fn set_store(&self, store: Option<(Arc, u64)>) { + /// Origin Private File System through a [`PrefetchStore`]). + pub fn set_store(&self, store: Option>) { if let Ok(mut s) = self.store.lock() { *s = store; } } - /// Change the store's salt (a new project or footage), keeping the store. - pub fn set_store_salt(&self, salt: u64) { - if let Ok(mut d) = self.store.lock() - && let Some((_, s)) = d.as_mut() - { - *s = salt; + /// Size and content hash of files served from memory (the browser file table): what a + /// persistent entry keeps for them and checks them against. + pub fn set_virtual_id(&self, id: Option) { + if let Ok(mut v) = self.virtual_id.lock() { + *v = id; } } - fn disk_key(&self, key: u64) -> Option<(Arc, u128)> { - let salted = |salt: u64| ((salt as u128) << 64) | key as u128; - if let Some((dc, salt)) = self.disk.lock().ok()?.as_ref() { - return Some((dc.clone() as Arc, salted(*salt))); + fn virtual_id(&self) -> Option { + self.virtual_id.lock().ok()?.clone() + } + + /// The persistent store behind the memory: the disk cache, else the other store. + fn persistent(&self) -> Option> { + if let Some(dc) = self.disk.lock().ok()?.as_ref() { + return Some(dc.clone() as Arc); } - let s = self.store.lock().ok()?; - let (st, salt) = s.as_ref()?; - Some((st.clone(), salted(*salt))) + self.store.lock().ok()?.clone() } /// The buffer kept under `key` and the source files it was made of (see [`crate::reads`]). - /// A buffer from the disk cache or another store doesn't know its files: its list is - /// incomplete. + /// A buffer from the disk cache or another store comes with the files its entry lists, after + /// they were found unchanged. pub fn get(&self, key: u64) -> Option<(Arc, Arc)> { let mut g = self.inner.lock().ok()?; g.clock += 1; @@ -172,10 +169,9 @@ impl LayerCache { g.missed_at.insert(key, web_time::Instant::now()); drop(g); // Disk cache: a hit comes back into memory. - let (dc, dk) = self.disk_key(key)?; - let buf = dc.get_layer(dk)?; - let mut files = ReadFiles::default(); - files.mark_incomplete(); + let store = self.persistent()?; + let id = self.virtual_id(); + let (buf, files) = store.get_layer(layer_disk_key(key), id.as_deref())?; let files = Arc::new(files); Some((self.insert_mem(key, buf, files.clone()), files)) } @@ -188,7 +184,7 @@ impl LayerCache { /// and packs it once instead of once per worker, which ran it out of memory). Renders don't /// wait for each other: on the frame workers' shared thread pool a wait can end up under /// the very work it waits for. `files`: the source files `buf` was made of (see - /// [`crate::reads`]). + /// [`crate::reads`]); a buffer whose files can't all be named stays in memory. pub fn insert(&self, key: u64, buf: Arc, files: Arc) -> Arc { if self.gated() { return buf; @@ -197,10 +193,12 @@ impl LayerCache { return kept; } let started = self.inner.lock().ok().and_then(|mut g| g.missed_at.remove(&key)); - if let Some((dc, dk)) = self.disk_key(key) { - let slow = started.is_some_and(|t| t.elapsed().as_secs_f64() * 1e3 >= dc.min_layer_ms() as f64); - if slow { - dc.put_layer(dk, &buf); + if let Some(store) = self.persistent() { + let slow = started.is_some_and(|t| t.elapsed().as_secs_f64() * 1e3 >= store.min_layer_ms() as f64); + let id = self.virtual_id(); + // (an incomplete list, or a file from memory without its identity: not stored) + if slow && let Some(entry) = EntryFiles::of(&files, id.as_deref()) { + store.put_layer(layer_disk_key(key), &buf, &entry); } } self.insert_mem(key, buf, files) @@ -274,12 +272,16 @@ impl LayerCache { } } -/// Persistent storage of layer buffers behind a [`LayerCache`] (keys salted per project). +/// Persistent storage of layer buffers behind a [`LayerCache`] (keys: +/// [`crate::disk_cache::layer_disk_key`]). Every entry keeps the source files its buffer was made +/// of and is used only while they are unchanged (#3184). pub trait LayerStore: Send + Sync { - /// A stored buffer (synchronous: mid-render). - fn get_layer(&self, key: u128) -> Option>; - /// Keep a buffer that was slow to render. - fn put_layer(&self, key: u128, buf: &Buf); + /// A stored buffer whose source files are unchanged, with those files (synchronous: + /// mid-render). An entry whose files changed, or damaged, is a miss and is dropped, so the + /// buffer rendered again replaces it. `virtual_id` names files served from memory. + fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)>; + /// Keep a buffer that was slow to render, with the source files it was made of. + fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles); /// Buffers faster to render than this (ms) are not stored. fn min_layer_ms(&self) -> u64 { 0 @@ -291,9 +293,10 @@ pub const PREFETCH_MIN_LAYER_MS: u64 = 20; /// A [`LayerStore`] over storage that can't be read in the middle of a render (the browser's /// Origin Private File System, read asynchronously). Lookups are served from buffers fetched -/// before the frame ([`PrefetchStore::provide`]); the keys a render looked up and didn't find -/// are recorded ([`PrefetchStore::take_misses`]) so the transport can fetch them before the next -/// frame; buffers to store queue up as sealed entries ([`PrefetchStore::take_writes`]) for the +/// before the frame ([`PrefetchStore::provide`]), once the files their entries list are found +/// unchanged; the keys a render looked up and didn't find are recorded +/// ([`PrefetchStore::take_misses`]) so the transport can fetch them before the next frame; +/// buffers to store queue up as sealed entries ([`PrefetchStore::take_writes`]) for the /// transport to write after the frame. Fetched buffers are kept least recently used first, up /// to a byte budget. pub struct PrefetchStore { @@ -302,9 +305,20 @@ pub struct PrefetchStore { min_ms: u64, } +/// A fetched entry: the buffer, the source files it was made of, its last use. +struct Fetched { + buf: Arc, + files: Arc, + used: u64, +} + +fn buf_bytes(b: &Buf) -> usize { + b.img.data.len().saturating_mul(std::mem::size_of::()) +} + #[derive(Default)] struct Prefetched { - ready: HashMap, u64)>, + ready: HashMap, bytes: usize, clock: u64, misses: Vec, @@ -314,6 +328,20 @@ struct Prefetched { known: std::collections::HashSet, } +impl Prefetched { + fn note_miss(&mut self, key: u128) { + if !self.misses.contains(&key) && self.misses.len() < 1024 { + self.misses.push(key); + } + } + + fn remove(&mut self, key: u128) { + if let Some(f) = self.ready.remove(&key) { + self.bytes = self.bytes.saturating_sub(buf_bytes(&f.buf)); + } + } +} + impl Default for PrefetchStore { fn default() -> Self { PrefetchStore::new(256 << 20) @@ -337,23 +365,21 @@ impl PrefetchStore { } /// A fetched entry (sealed bytes, [`crate::disk_cache::layer_entry`]) for `key`; `false` - /// when damaged. + /// when damaged or of another format. Its files are checked when the buffer is used. pub fn provide(&self, key: u128, entry: &[u8]) -> bool { - let Some(buf) = crate::disk_cache::read_layer_entry(entry) else { return false }; - let bytes = buf.img.data.len() * std::mem::size_of::(); + let Some((buf, files)) = crate::disk_cache::read_layer_entry(entry) else { return false }; + let buf = Arc::new(buf); + let bytes = buf_bytes(&buf); let Ok(mut s) = self.st.lock() else { return false }; s.clock += 1; - let now = s.clock; - if let Some((old, _)) = s.ready.insert(key, (Arc::new(buf), now)) { - s.bytes -= old.img.data.len() * std::mem::size_of::(); - } - s.bytes += bytes; + let used = s.clock; + s.remove(key); + s.ready.insert(key, Fetched { buf, files: Arc::new(files), used }); + s.bytes = s.bytes.saturating_add(bytes); s.known.insert(key); while s.bytes > self.budget { - let Some((&k, _)) = s.ready.iter().min_by_key(|(_, (_, t))| *t) else { break }; - if let Some((b, _)) = s.ready.remove(&k) { - s.bytes -= b.img.data.len() * std::mem::size_of::(); - } + let Some(oldest) = s.ready.iter().min_by_key(|(_, f)| f.used).map(|(k, _)| *k) else { break }; + s.remove(oldest); } true } @@ -382,32 +408,44 @@ impl PrefetchStore { } impl LayerStore for PrefetchStore { - fn get_layer(&self, key: u128) -> Option> { + fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)> { + let found = { + let mut s = self.st.lock().ok()?; + s.clock += 1; + let now = s.clock; + match s.ready.get_mut(&key) { + Some(f) => { + f.used = now; + Some((f.buf.clone(), f.files.clone())) + } + None => { + s.note_miss(key); + None + } + } + }; + let (buf, files) = found?; + // (looked at without the lock: one call of the hook, or one `metadata`, per file) + let unchanged = files.unchanged(virtual_id); let mut s = self.st.lock().ok()?; - s.clock += 1; - let now = s.clock; - match s.ready.get_mut(&key) { - Some((b, t)) => { - *t = now; - let b = b.clone(); - if !s.hits.contains(&key) { - s.hits.push(key); - } - Some(b) - } - None => { - if !s.misses.contains(&key) && s.misses.len() < 1024 { - s.misses.push(key); - } - None - } + if !unchanged { + // Made of files that changed since: forgotten, so the buffer rendered again is + // written over its entry. + s.remove(key); + s.known.remove(&key); + s.note_miss(key); + return None; } + if !s.hits.contains(&key) { + s.hits.push(key); + } + Some((buf, files.to_read_files())) } - fn put_layer(&self, key: u128, buf: &Buf) { + fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles) { let Ok(mut s) = self.st.lock() else { return }; if s.known.insert(key) { - s.writes.push((key, crate::disk_cache::layer_entry(buf))); + s.writes.push((key, crate::disk_cache::layer_entry(buf, files))); } } @@ -800,4 +838,47 @@ mod shared_insert_tests { assert!(Arc::ptr_eq(&cache.insert(3, b, Default::default()), &a), "the later render gets the first buffer"); assert!(Arc::ptr_eq(&cache.get(3).unwrap().0, &a)); } + + /// The browser's store (#3184): a fetched entry is used only while the files it lists are + /// unchanged (here from memory, through the hook), and comes with them; one made of files + /// that changed is dropped and counts as a miss, so the buffer rendered again is queued over + /// it. A buffer whose files can't all be named is not queued at all. + #[test] + fn the_prefetch_store_checks_the_files_of_its_entries() { + use super::{LayerStore, PrefetchStore}; + use crate::disk_cache::{EntryFiles, layer_disk_key, layer_entry}; + use crate::reads::{FileStamp, ReadFile, ReadFiles}; + let buf = || Buf { img: Image::new(2, 2), offset: [0.0; 2], scale: 1.0 }; + let files: ReadFiles = [ReadFile::new("/v.png", FileStamp::Virtual)].into_iter().collect(); + let (one, two) = (|_: &str| Some((3, 1)), |_: &str| Some((3, 2))); + let entry = layer_entry(&buf(), &EntryFiles::of(&files, Some(&one)).unwrap()); + let store = PrefetchStore::new(1 << 20).with_min_ms(0); + assert!(store.provide(5, &entry)); + assert!(!store.provide(6, b"damaged")); + let (_, got) = store.get_layer(5, Some(&one)).unwrap(); + assert_eq!(got, files); + assert_eq!(store.take_hits(), [5]); + // The file changed: a miss, forgotten, and the new buffer is queued over it. + assert!(store.get_layer(5, Some(&two)).is_none()); + assert!(!store.has(5)); + assert_eq!(store.take_misses(), [5]); + store.put_layer(5, &buf(), &EntryFiles::of(&files, Some(&two)).unwrap()); + assert_eq!(store.take_writes().len(), 1, "written over the changed entry"); + // Through the layer cache: a hit reports its files; incomplete lists are not queued. + let cache = LayerCache::default(); + let store = Arc::new(PrefetchStore::new(1 << 20).with_min_ms(0)); + cache.set_store(Some(store.clone())); + cache.set_virtual_id(Some(Arc::new(one))); + assert!(store.provide(layer_disk_key(9), &entry)); + let (_, from_store) = cache.get(9).unwrap(); + assert!(*from_store == files && from_store.is_complete()); + let mut incomplete = files.clone(); + incomplete.mark_incomplete(); + assert!(cache.get(10).is_none()); + cache.insert(10, Arc::new(buf()), Arc::new(incomplete)); + assert!(cache.get(11).is_none()); + cache.insert(11, Arc::new(buf()), Arc::new(files.clone())); + let written: Vec = store.take_writes().into_iter().map(|w| w.0).collect(); + assert_eq!(written, [layer_disk_key(11)], "only the buffer whose files are all named"); + } } diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 0a91f11ac..93c949ff2 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -4,18 +4,19 @@ //! * Entries are files keyed by a 128-bit content hash (`/v1//<2 hex>/<32 hex>.ecc`): //! frames by the hash of the composition's content as it is in memory (the comp and everything //! it uses, footage items with their settings and paths; no file is looked at) plus frame, -//! scale and view; layer buffers by the layer cache's content key salted with the project's -//! footage fingerprint. A changed project therefore never reads stale pixels: its keys simply +//! scale and view; layer buffers by the layer cache's content key (which names the footage +//! items a buffer uses with their settings and paths) and the renderer version +//! ([`layer_disk_key`]). A changed project therefore never reads stale pixels: its keys simply //! change. -//! * A frame entry keeps the source files the frame was made of, each with the size and +//! * Frame and layer entries keep the source files they were made of, each with the size and //! modification time it was read with ([`EntryFiles`], #3184). An entry is used only while -//! those files are unchanged: a handful of `metadata` calls when the frame is read, never a -//! scan of the project's files. A frame whose files can't all be named is not stored. +//! those files are unchanged: a handful of `metadata` calls when it is read, never a scan of +//! the project's files. A frame or buffer whose files can't all be named is not stored. //! * Payloads are LZ4-compressed (`lz4_flex`, MIT): frames as 8-bit premultiplied RGBA (or, for //! 32 bpc viewer frames, half-float RGBA with the bytes shuffled into planes; the entry //! header's format byte tells them apart: 2 and 3, both with their source files first), layer -//! buffers as `f32` RGBA with the bytes shuffled into planes (exact, so cached and fresh -//! renders are bit-identical), Roto Brush / Object Matte segmentations as +//! buffers (format 4, their source files first) as `f32` RGBA with the bytes shuffled into +//! planes (exact, so cached and fresh renders are bit-identical), Roto Brush / Object Matte segmentations as //! `FrameSeg::to_bytes` (keyed by their content-keyed chain key and scale, so they are //! reused whenever the same frames, settings and prompt come back, also after a restart). Every file ends in a checksum; damaged files read as misses and //! are deleted. @@ -97,13 +98,16 @@ pub struct FrameF16 { pub rgba: Vec, } -/// The entry header's format byte: layer buffers and segmentations (and 8-bit frames before +/// The entry header's format byte: segmentations (and 8-bit frames and layer buffers before /// #3184). const FORMAT_RGBA8: u8 = 0; /// Frame entries: their source files ([`EntryFiles`]), then 8-bit or half-float pixels. The /// formats before them (0: 8-bit, 1: half float, without files) read as misses and are deleted. const FORMAT_RGBA8_FILES: u8 = 2; const FORMAT_F16_FILES: u8 = 3; +/// Layer entries: their source files ([`EntryFiles`]), then the buffer. The format before it +/// (0, without files) reads as a miss and is deleted. +const FORMAT_LAYER_FILES: u8 = 4; /// Counters for tests, the Info panel and `cache.diskStats`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -234,7 +238,7 @@ pub struct LayerPrefetch { const PREFETCH_RECENT: usize = 512; impl LayerPrefetch { - /// A frame's layer-cache misses (salted keys). + /// A frame's layer-cache misses (disk keys, [`layer_disk_key`]). pub fn note_misses(&mut self, keys: impl IntoIterator) { for k in keys { self.recent.retain(|x| *x != k); @@ -300,7 +304,7 @@ pub struct DiskCache { evictions: AtomicU64, dropped: AtomicU64, failed: AtomicU64, - /// Source files looked at to check frame entries ([`DiskCache::file_checks`]). + /// Source files looked at to check frame and layer entries ([`DiskCache::file_checks`]). file_checks: AtomicU64, tmp_counter: AtomicU64, queue: Arc<(Mutex, Condvar)>, @@ -597,41 +601,50 @@ impl DiskCache { } } - /// A frame entry of `format` whose source files are unchanged, decoded by `decode`, with - /// those files. An entry whose files changed, of the format before #3184, or damaged, is a - /// miss and is deleted (the frame renders again and is stored anew). An entry of the other - /// current format (8-bit and half-float frames have keys of their own) is a miss and stays. - fn get_checked(&self, key: u128, format: u8, virtual_id: Option>, decode: impl FnOnce(&[u8]) -> Option) -> Option<(T, ReadFiles)> { + /// An entry of `kind` and `format` whose source files are unchanged, decoded by `decode`, + /// with those files. An entry whose files changed, of the format before #3184, or damaged, + /// is a miss and is deleted (it renders again and is stored anew). A frame entry of the + /// other current frame format (8-bit and half-float frames have keys of their own) is a miss + /// and stays. + fn get_checked( + &self, + kind: Kind, + key: u128, + format: u8, + virtual_id: Option>, + decode: impl FnOnce(&[u8]) -> Option, + ) -> Option<(T, ReadFiles)> { let miss = || { self.misses.fetch_add(1, Ordering::Relaxed); None }; - let Some((found, payload)) = self.load(Kind::Frame, key) else { return miss() }; + let Some((found, payload)) = self.load(kind, key) else { return miss() }; if found != format { - if found != FORMAT_RGBA8_FILES && found != FORMAT_F16_FILES { - self.discard(Kind::Frame, key); + let other_frame_format = kind == Kind::Frame && (found == FORMAT_RGBA8_FILES || found == FORMAT_F16_FILES); + if !other_frame_format { + self.discard(kind, key); } return miss(); } - let Some((files, pixels)) = EntryFiles::decode(&payload) else { - self.discard(Kind::Frame, key); + let Some((files, body)) = EntryFiles::decode(&payload) else { + self.discard(kind, key); return miss(); }; self.file_checks.fetch_add(files.len() as u64, Ordering::Relaxed); if !files.unchanged(virtual_id) { - self.discard(Kind::Frame, key); + self.discard(kind, key); return miss(); } - let Some(frame) = decode(pixels) else { - self.discard(Kind::Frame, key); + let Some(value) = decode(body) else { + self.discard(kind, key); return miss(); }; - self.hit(Kind::Frame, key); - Some((frame, files.to_read_files())) + self.hit(kind, key); + Some((value, files.to_read_files())) } - /// Source files looked at so far to check frame entries before using them (one per file a - /// read frame lists; tests). + /// Source files looked at so far to check frame and layer entries before using them (one per + /// file a read entry lists; tests). pub fn file_checks(&self) -> u64 { self.file_checks.load(Ordering::Relaxed) } @@ -685,10 +698,6 @@ impl DiskCache { } /// Write an entry now (atomic rename), then evict down to the limit. - fn write_now(&self, kind: Kind, key: u128, payload: &[u8]) { - self.write_format(kind, key, FORMAT_RGBA8, payload); - } - fn write_format(&self, kind: Kind, key: u128, format: u8, payload: &[u8]) { if self.contains(kind, key) { return; @@ -749,12 +758,12 @@ impl DiskCache { /// those files; `None` for a half-float entry of that key, which /// [`DiskCache::get_frame_f16`] reads. `virtual_id` names files served from memory. pub fn get_frame(&self, key: u128, virtual_id: Option>) -> Option<(Frame8, ReadFiles)> { - self.get_checked(key, FORMAT_RGBA8_FILES, virtual_id, decode_frame) + self.get_checked(Kind::Frame, key, FORMAT_RGBA8_FILES, virtual_id, decode_frame) } /// A half-float frame (32 bpc viewer frames), as [`DiskCache::get_frame`]. pub fn get_frame_f16(&self, key: u128, virtual_id: Option>) -> Option<(FrameF16, ReadFiles)> { - self.get_checked(key, FORMAT_F16_FILES, virtual_id, decode_frame_f16) + self.get_checked(Kind::Frame, key, FORMAT_F16_FILES, virtual_id, decode_frame_f16) } /// Queue a half-float frame for writing (`width * height * 4` binary16 values) with the @@ -786,22 +795,28 @@ impl DiskCache { self.contains(Kind::Frame, key) || self.enqueue_format(Kind::Frame, key, FORMAT_RGBA8_FILES, with_files(&files, encode_frame(width, height, rgba))) } - pub fn get_layer(&self, key: u128) -> Option { - let p = self.read(Kind::Layer, key)?; - decode_layer(&p) + /// A layer buffer (key: [`layer_disk_key`]) whose source files are unchanged, with those + /// files, as [`DiskCache::get_checked`]: an entry whose files changed, damaged, or of the + /// format before #3184 is a miss and is deleted, so the buffer renders again and replaces it. + /// `virtual_id` names files served from memory. + pub fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Buf, ReadFiles)> { + self.get_checked(Kind::Layer, key, FORMAT_LAYER_FILES, virtual_id, decode_layer) } - /// Queue a layer buffer for writing. - pub fn put_layer(&self, key: u128, buf: &Buf) { + /// Queue a layer buffer for writing with the source files it was made of (see + /// [`EntryFiles::of`]: a buffer whose files can't all be named must not be stored). + pub fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles) { if self.contains(Kind::Layer, key) { return; } - let _ = self.enqueue(Kind::Layer, key, encode_layer(buf)); + let _ = self.enqueue_format(Kind::Layer, key, FORMAT_LAYER_FILES, with_files(files, encode_layer(buf))); } - /// Write a layer buffer synchronously (tests). - pub fn put_layer_now(&self, key: u128, buf: &Buf) { - self.write_now(Kind::Layer, key, &encode_layer(buf)); + /// Write a layer buffer synchronously (tests); a list that can't be stored is not. + pub fn put_layer_now(&self, key: u128, buf: &Buf, files: &ReadFiles) { + if let Some(files) = EntryFiles::of(files, None) { + self.write_format(Kind::Layer, key, FORMAT_LAYER_FILES, &with_files(&files, encode_layer(buf))); + } } /// A segmentation (chain key, scale) written by [`DiskCache::put_seg`]. @@ -860,7 +875,7 @@ impl DiskCache { } } -/// A frame entry's payload: its source files, then its pixels. +/// A frame or layer entry's payload: its source files, then its pixels. fn with_files(files: &EntryFiles, pixels: Vec) -> Vec { let mut out = Vec::with_capacity(pixels.len() + 64); files.encode(&mut out); @@ -953,15 +968,22 @@ pub fn read_frame_entry(data: &[u8], virtual_id: Option>) -> O decode_frame(pixels) } -/// A sealed layer-buffer entry: what the browser's frame workers write to the Origin Private -/// File System (`layers/<32 hex>.ecc`). -pub fn layer_entry(buf: &Buf) -> Vec { - seal(Kind::Layer, &encode_layer(buf)) +/// A sealed layer-buffer entry with the source files it was made of: what the browser's frame +/// workers write to the Origin Private File System (`layers/<32 hex>.ecc`). +pub fn layer_entry(buf: &Buf, files: &EntryFiles) -> Vec { + seal_format(Kind::Layer, FORMAT_LAYER_FILES, &with_files(files, encode_layer(buf))) } -/// A layer buffer from a sealed entry's bytes (`None` when damaged). -pub fn read_layer_entry(data: &[u8]) -> Option { - decode_layer(verify(data, Kind::Layer)?) +/// A layer buffer and its source files from a sealed entry's bytes (`None` when damaged or of +/// another format). The files are not looked at here: the store checks them when the buffer is +/// used ([`EntryFiles::unchanged`]). +pub fn read_layer_entry(data: &[u8]) -> Option<(Buf, EntryFiles)> { + let payload = verify(data, Kind::Layer)?; + if data.get(5) != Some(&FORMAT_LAYER_FILES) { + return None; + } + let (files, body) = EntryFiles::decode(payload)?; + Some((decode_layer(body)?, files)) } /// The disk key of a segmentation: its chain key and scale. @@ -983,11 +1005,11 @@ impl effectcraft_effects::roto::SegStore for DiskCache { } impl crate::cache::LayerStore for DiskCache { - fn get_layer(&self, key: u128) -> Option> { - DiskCache::get_layer(self, key).map(Arc::new) + fn get_layer(&self, key: u128, virtual_id: Option>) -> Option<(Arc, ReadFiles)> { + DiskCache::get_layer(self, key, virtual_id).map(|(b, f)| (Arc::new(b), f)) } - fn put_layer(&self, key: u128, buf: &Buf) { - DiskCache::put_layer(self, key, buf); + fn put_layer(&self, key: u128, buf: &Buf, files: &EntryFiles) { + DiskCache::put_layer(self, key, buf, files); } fn min_layer_ms(&self) -> u64 { DiskCache::min_layer_ms(self) @@ -1107,8 +1129,8 @@ fn decode_layer(p: &[u8]) -> Option { let offset = [f(8)?, f(16)?]; let scale = f(24)?; let planes = lz4_flex::decompress_size_prepended(&p[32..]).ok()?; - let n = w as usize * h as usize; - if planes.len() != n * 16 { + let n = (w as usize).checked_mul(h as usize)?; + if planes.len() != n.checked_mul(16)? { return None; } let mut img = Image::new(w, h); @@ -1137,75 +1159,26 @@ fn hash_debug(h: &mut Hash128, v: &impl std::fmt::Debug) { /// Size and content hash of a path that has no native metadata (the browser file table). pub type VirtualFileId<'a> = &'a (dyn Fn(&str) -> Option<(u64, u64)> + Send + Sync); -/// A file's size and modification time (so edited footage gets a new layer salt): the identity a -/// render records for the files it reads ([`crate::reads::FileStamp`]). When the path has no -/// native metadata, `virtual_id` supplies a durable size and content hash instead. -fn file_stamp(h: &mut Hash128, path: &str, virtual_id: Option>) { - if path.is_empty() { - return; - } - if let Some(crate::reads::FileStamp::Native { len, modified }) = crate::reads::FileStamp::native(path) { - h.write_u64(len); - if let Some(t) = modified { - h.write_u64(t); - } - return; - } - if let Some((len, hash)) = virtual_id.and_then(|id| id(path)) { - h.write_u64(len); - h.write_u64(hash); - } -} +/// A [`VirtualFileId`] a cache can keep (the browser file table's identities). +pub type SharedVirtualFileId = Arc Option<(u64, u64)> + Send + Sync>; -fn footage_stamp(h: &mut Hash128, f: &effectcraft_project::Footage, virtual_id: Option>) { - file_stamp(h, &f.path, virtual_id); - for p in &f.sequence { - file_stamp(h, p, virtual_id); - } -} +/// Layer entries with their source files (#3184), part of every layer disk key: entries of the +/// earlier format (keyed by a project-wide footage salt instead) are never looked up again; +/// least recently used, they are evicted. +const LAYER_ENTRY_VERSION: &[u8] = b"layer-entry-files-1"; -/// Salt for layer cache keys on disk: the renderer version and every footage file's identity -/// (layer keys name footage items, not file contents). -pub fn footage_salt(project: &effectcraft_project::Project) -> u64 { - footage_salt_with(project, None) -} - -/// [`footage_salt`] with [`VirtualFileId`] for paths `std::fs::metadata` cannot describe. -pub fn footage_salt_with(project: &effectcraft_project::Project, virtual_id: Option>) -> u64 { +/// Disk key of a layer buffer: the layer cache's content key ([`crate::cache::layer_key`] and +/// the keys derived from it), the layer entry format and the renderer version. The content key +/// comes from memory alone: it names the footage items the buffer uses with their settings and +/// paths, so two projects only share an entry for the same pixels of the same files; whether +/// those files still hold what the buffer was made of is checked when the entry is read +/// ([`EntryFiles`]). No file is looked at here. +pub fn layer_disk_key(key: u64) -> u128 { let mut h = Hash128::default(); + h.write(LAYER_ENTRY_VERSION); h.write(RENDER_VERSION.as_bytes()); - // Footage another layer reads (Audio Spectrum's Audio Layer); a read precomp can hold any. - let mut read = std::collections::BTreeSet::new(); - let mut read_comp = false; - for (_, c) in project.comps() { - for l in c.layers.iter() { - for r in l.referenced_layers().into_iter().filter(|r| *r != l.id) { - match c.layer(r).map(|x| &x.source) { - Some(effectcraft_project::LayerSource::Footage { item }) => _ = read.insert(*item), - Some(effectcraft_project::LayerSource::Comp { .. }) => read_comp = true, - _ => {} - } - } - } - } - for (id, it) in &project.items { - // (files without video make layer buffers only through a layer that reads them: - // importing music keeps the keys) - if let effectcraft_project::ItemKind::Footage(f) = &it.kind - && (f.has_video || read_comp || read.contains(id)) - { - h.write_u64(id.0); - hash_debug(&mut h, f); - footage_stamp(&mut h, f, virtual_id); - } - if let Some(proxy) = it.proxy.as_ref().filter(|p| p.enabled) { - h.write_u64(id.0); - hash_debug(&mut h, proxy); - footage_stamp(&mut h, &proxy.footage, virtual_id); - } - } - let v = h.finish(); - (v as u64) ^ ((v >> 64) as u64) + h.write_u64(key); + h.finish() } /// Content key of a composition's pixels, from the project in memory alone (no file is looked @@ -1443,11 +1416,12 @@ mod tests { fn hit_miss_and_exact_round_trip() { let dir = tmpdir("hit"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); - assert!(dc.get_layer(42).is_none()); + assert!(dc.get_layer(42, None).is_none()); let b = buf(1, 33, 17); - dc.put_layer(42, &b); + dc.put_layer(42, &b, &EntryFiles::default()); dc.flush(); - let back = dc.get_layer(42).unwrap(); + let (back, files) = dc.get_layer(42, None).unwrap(); + assert!(files.is_empty() && files.is_complete()); assert_eq!(back.img, b.img); assert_eq!((back.offset, back.scale), (b.offset, b.scale)); let rgba: Vec = (0..20 * 10 * 4).map(|i| (i % 251) as u8).collect(); @@ -1462,7 +1436,7 @@ mod tests { } /// Music doesn't change a comp's disk keys (adding it to the timeline kept no blue frame); - /// hiding a clip does. Importing music keeps the layer-cache salt. + /// hiding a clip does. Importing music keeps them too. #[test] fn music_keeps_the_disk_keys() { use effectcraft_project::{Comp, Footage, FootageKind, ItemKind, LayerSource, Project, Solid, build}; @@ -1474,14 +1448,14 @@ mod tests { let clip = build::layer(&mut p, &comp, "Clip", LayerSource::Solid { item: sid }, (64, 64), None); let clip_id = clip.id; p.comp_mut(cid).unwrap().layers.push(clip); - let (key, salt) = (comp_content_key(&p, cid), footage_salt(&p)); + let key = comp_content_key(&p, cid); let song = p.add_item( "song.wav", Default::default(), None, ItemKind::Footage(Footage { kind: FootageKind::Audio, has_video: false, has_audio: true, ..Default::default() }), ); - assert_eq!(footage_salt(&p), salt, "importing music"); + assert_eq!(comp_content_key(&p, cid), key, "importing music"); let music = build::layer(&mut p, &comp, "Music", LayerSource::Footage { item: song }, (64, 64), None); p.comp_mut(cid).unwrap().layers.insert(0, music); assert_eq!(comp_content_key(&p, cid), key, "music on the timeline"); @@ -1496,7 +1470,7 @@ mod tests { let dir = tmpdir("burst"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); for k in 0..300 { - dc.put_layer(10_000 + k, &buf(1, 64, 64)); + dc.put_layer(10_000 + k, &buf(1, 64, 64), &EntryFiles::default()); } let rgba = vec![7u8; 32 * 32 * 4]; for k in 0..300 { @@ -1533,7 +1507,7 @@ mod tests { let dir = tmpdir("persist"); { let dc = DiskCache::open(&dir, 1 << 30).unwrap(); - dc.put_layer_now(1, &buf(1, 8, 8)); + dc.put_layer_now(1, &buf(1, 8, 8), &ReadFiles::default()); dc.put_frame_now(2, 2, 2, &[9; 16], &ReadFiles::default()); } let dc = DiskCache::open(&dir, 1 << 30).unwrap(); @@ -1552,11 +1526,11 @@ mod tests { let dir = tmpdir("lru"); let dc = DiskCache::open(&dir, u64::MAX).unwrap(); for k in 0..6u128 { - dc.put_layer_now(k, &buf(k as u32, 64, 64)); + dc.put_layer_now(k, &buf(k as u32, 64, 64), &ReadFiles::default()); } let per = dc.stats().bytes / 6; // Touch 0 so it is the most recently used. - assert!(dc.get_layer(0).is_some()); + assert!(dc.get_layer(0, None).is_some()); dc.set_max_bytes(per * 3 + per * 3 / 4); let st = dc.stats(); assert!(st.bytes <= per * 3 + per * 3 / 4, "{st:?}"); @@ -1568,7 +1542,7 @@ mod tests { let files = walk(&dir); assert_eq!(files, 3); // New writes keep evicting. - dc.put_layer_now(99, &buf(9, 64, 64)); + dc.put_layer_now(99, &buf(9, 64, 64), &ReadFiles::default()); assert!(dc.stats().bytes <= per * 3 + per * 3 / 4); } @@ -1593,7 +1567,7 @@ mod tests { let dir = tmpdir("space"); let dc = DiskCache::open(&dir, 1 << 30).unwrap(); for k in 0..4u128 { - dc.put_layer_now(k, &buf(k as u32, 64, 64)); + dc.put_layer_now(k, &buf(k as u32, 64, 64), &ReadFiles::default()); } let used = dc.stats().bytes; // Unknown space: the setting alone. @@ -1606,13 +1580,13 @@ mod tests { dc.set_disk_space(Some((100 << 30, 5 << 30))); let st = dc.stats(); assert_eq!((st.max_bytes, st.limit_bytes), (1 << 30, used)); - dc.put_layer_now(9, &buf(9, 64, 64)); + dc.put_layer_now(9, &buf(9, 64, 64), &ReadFiles::default()); let st = dc.stats(); assert!(st.bytes <= st.limit_bytes && st.bytes <= used - used / 10 && st.evictions > 0, "{st:?}"); assert!(dc.contains(Kind::Layer, 9), "the new entry is the most recently used"); // Below the reserve the cache gives its space back, and skips writes that can't fit. dc.set_disk_space(Some((100 << 30, 4 << 30))); - dc.put_layer_now(10, &buf(10, 64, 64)); + dc.put_layer_now(10, &buf(10, 64, 64), &ReadFiles::default()); let st = dc.stats(); assert_eq!((st.limit_bytes, st.entries, st.bytes), (0, 0, 0), "{st:?}"); // Plenty of space again: back to the setting. @@ -1627,8 +1601,8 @@ mod tests { let dc = DiskCache::open(&dir, 1 << 30).unwrap(); // A file where the layers folder should be: every layer write fails. std::fs::write(dir.join(VERSION).join(Kind::Layer.dir()), b"x").unwrap(); - dc.put_layer_now(1, &buf(1, 8, 8)); - dc.put_layer_now(2, &buf(2, 8, 8)); + dc.put_layer_now(1, &buf(1, 8, 8), &ReadFiles::default()); + dc.put_layer_now(2, &buf(2, 8, 8), &ReadFiles::default()); let st = dc.stats(); assert_eq!((st.failed, st.writes, st.entries), (2, 0, 0)); let _ = std::fs::remove_dir_all(&dir); @@ -1677,8 +1651,8 @@ mod tests { for i in 0..20u128 { let k = i % 5; let w = if t % 2 == 0 { &a } else { &b }; - w.put_layer_now(k, &buf(k as u32, 16, 16)); - if let Some(x) = w.get_layer(k) { + w.put_layer_now(k, &buf(k as u32, 16, 16), &ReadFiles::default()); + if let Some((x, _)) = w.get_layer(k, None) { assert_eq!(x.img, buf(k as u32, 16, 16).img); } } @@ -1687,41 +1661,16 @@ mod tests { }); b.rescan(); for k in 0..5u128 { - assert_eq!(b.get_layer(k).unwrap().img, buf(k as u32, 16, 16).img); + assert_eq!(b.get_layer(k, None).unwrap().0.img, buf(k as u32, 16, 16).img); } } - /// An audio file nothing reads stays out of the layer salt; one a layer reads (Audio - /// Spectrum) is in it, so overwriting it doesn't reuse that layer's buffers. + /// Replaced bytes of a path with no native metadata (the browser file table) change neither + /// the comp key nor a layer's disk key (both from memory): the frame and layer entries made + /// of them check the hook's size and content hash when read and are misses, deleted (#1253, + /// #3184). #[test] - fn read_audio_counts_in_the_footage_salt() { - use effectcraft_project::build; - use effectcraft_project::{Comp, Footage, FootageKind, ItemKind, LayerSource, MatteKind, Project, TrackMatte}; - use effectcraft_time::{FrameRate, Tick}; - - let mut p = Project::default(); - let f = Footage { path: "/song.wav".into(), kind: FootageKind::Audio, has_video: false, has_audio: true, ..Default::default() }; - let song = p.add_item("song.wav", effectcraft_color::Label::None, None, ItemKind::Footage(f)); - let mut comp = Comp::new(16, 9, FrameRate::FPS_30, Tick::from_seconds_f64(1.0)); - let music = build::layer(&mut p, &comp, "music", LayerSource::Footage { item: song }, (16, 9), None); - let mut reader = build::layer(&mut p, &comp, "reader", LayerSource::Null, (16, 9), None); - let music_id = music.id; - comp.layers = vec![reader.clone(), music].into(); - let cid = p.add_item("C", effectcraft_color::Label::None, None, ItemKind::Comp(comp.into())); - - let id = |mark: u64| move |path: &str| (path == "/song.wav").then_some((8, mark)); - let (one, two) = (id(1), id(2)); - assert_eq!(footage_salt_with(&p, Some(&one)), footage_salt_with(&p, Some(&two)), "unread music stays out"); - reader.track_matte = Some(TrackMatte { layer: music_id, kind: MatteKind::Alpha }); - *p.comp_mut(cid).unwrap().layers.first_mut().unwrap() = reader; - assert_ne!(footage_salt_with(&p, Some(&one)), footage_salt_with(&p, Some(&two)), "read audio counts"); - } - - /// A path with no native metadata takes the layer salt from the caller's size and content hash - /// (#1253). The comp key is from memory: replaced bytes are caught by the frame entries' - /// check instead (#3184). - #[test] - fn virtual_file_bytes_change_the_salt_not_the_comp_key() { + fn virtual_file_bytes_are_checked_by_the_entries_not_the_keys() { use effectcraft_project::build; use effectcraft_project::{Comp, Footage, ItemKind, LayerSource, Project}; use effectcraft_time::{FrameRate, Tick}; @@ -1735,10 +1684,6 @@ mod tests { let id = |mark: u64| move |path: &str| (path == "/virtual.mov").then_some((8, mark)); let (one, two) = (id(1), id(2)); - let a = footage_salt_with(&p, Some(&one)); - let b = footage_salt_with(&p, Some(&two)); - assert_ne!(a, b, "replaced virtual media must not reuse the salt"); - // The frame entry of replaced virtual media is a miss. let dc = DiskCache::open(tmpdir("virtual"), 1 << 30).unwrap(); let k = frame_key(comp_content_key(&p, cid), 0, 1000, 0); let files: ReadFiles = [crate::reads::ReadFile::new("/virtual.mov", crate::reads::FileStamp::Virtual)].into_iter().collect(); @@ -1746,6 +1691,113 @@ mod tests { dc.flush(); assert!(dc.get_frame(k, Some(&one)).is_some_and(|(_, f)| f == files)); assert!(dc.get_frame(k, Some(&two)).is_none() && !dc.contains(Kind::Frame, k), "replaced: a miss, deleted"); + // A layer buffer made of it. + let lk = layer_disk_key(7); + dc.put_layer(lk, &buf(1, 4, 4), &EntryFiles::of(&files, Some(&one)).unwrap()); + dc.flush(); + assert!(dc.get_layer(lk, Some(&one)).is_some_and(|(b, f)| b.img == buf(1, 4, 4).img && f == files && f.is_complete())); + assert!(dc.get_layer(lk, None).is_none() && !dc.contains(Kind::Layer, lk), "no identity: a miss, deleted"); + dc.put_layer(lk, &buf(1, 4, 4), &EntryFiles::of(&files, Some(&one)).unwrap()); + dc.flush(); + assert!(dc.get_layer(lk, Some(&two)).is_none() && !dc.contains(Kind::Layer, lk), "replaced: a miss, deleted"); + // The browser's sealed layer entries carry the same list. + let e = layer_entry(&buf(2, 3, 2), &EntryFiles::of(&files, Some(&one)).unwrap()); + let (b, list) = read_layer_entry(&e).unwrap(); + assert!(b.img == buf(2, 3, 2).img && list.unchanged(Some(&one)) && !list.unchanged(Some(&two))); + assert!(read_layer_entry(&seal(Kind::Layer, &encode_layer(&buf(2, 3, 2)))).is_none(), "the format before #3184"); + let mut bad = e.clone(); + bad[12] ^= 1; + assert!(read_layer_entry(&bad).is_none(), "damaged"); + } + + /// Layer disk keys come from the layer cache's key alone (no file, no project-wide salt) and + /// differ per key. + #[test] + fn layer_disk_keys_need_no_files() { + assert_eq!(layer_disk_key(1), layer_disk_key(1)); + assert_ne!(layer_disk_key(1), layer_disk_key(2)); + // Not the layout of the salted keys before #3184 (`salt << 64 | key`). + assert_ne!(layer_disk_key(1) as u64, 1); + } + + /// A layer entry is used only while the files it lists are what the buffer was made of: a + /// new size, a new time, a missing file that is back, a file replaced by a folder, a damaged + /// files section and the format before #3184 are misses, and the entry is deleted so the + /// buffer is rendered and stored again. A buffer whose files can't all be named is not + /// stored. Only the listed files are looked at. + #[test] + fn layer_entries_check_their_files() { + use crate::reads::{FileStamp, ReadFile}; + let dir = tmpdir("layer-check"); + let src = dir.join("src"); + std::fs::create_dir_all(&src).unwrap(); + let file = |name: &str, bytes: &[u8]| { + let p = src.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().to_string() + }; + let (a, b) = (file("a.png", b"aa"), file("b.png", b"bb")); + let gone = src.join("gone.png").to_string_lossy().to_string(); + let read = |paths: &[&str]| -> ReadFiles { paths.iter().map(|p| ReadFile::new(*p, FileStamp::native(p).unwrap_or(FileStamp::Missing))).collect() }; + let dc = DiskCache::open(&dir, 1 << 30).unwrap(); + dc.put_layer_now(1, &buf(1, 4, 4), &read(&[&a])); + dc.put_layer_now(2, &buf(2, 4, 4), &read(&[&b, &gone])); + dc.put_layer_now(3, &buf(3, 4, 4), &read(&[&b])); + let (one, files) = dc.get_layer(1, None).unwrap(); + assert!(one.img == buf(1, 4, 4).img && files == read(&[&a]) && files.is_complete()); + assert_eq!(dc.file_checks(), 1, "only the file of that buffer"); + // a.png gets a new size: entry 1 is a miss and deleted, the others stay. + std::fs::write(&a, b"aaa").unwrap(); + assert!(dc.get_layer(1, None).is_none() && !dc.contains(Kind::Layer, 1)); + assert!(dc.get_layer(2, None).is_some() && dc.get_layer(3, None).is_some()); + // b.png gets a new time only. + let t = std::fs::metadata(&b).unwrap().modified().unwrap() + std::time::Duration::from_secs(7); + std::fs::File::options().append(true).open(&b).unwrap().set_modified(t).unwrap(); + assert!(dc.get_layer(3, None).is_none() && !dc.contains(Kind::Layer, 3)); + assert!(dc.get_layer(2, None).is_none(), "b.png is listed there too"); + // A missing file that is back. + dc.put_layer_now(4, &buf(4, 4, 4), &read(&[&gone])); + assert!(dc.get_layer(4, None).is_some(), "missing, still missing"); + file("gone.png", b"g"); + assert!(dc.get_layer(4, None).is_none() && !dc.contains(Kind::Layer, 4), "back"); + // A file replaced by a folder (unreadable). + let c = file("c.png", b"cc"); + dc.put_layer_now(5, &buf(5, 4, 4), &read(&[&c])); + std::fs::remove_file(&c).unwrap(); + std::fs::create_dir(&c).unwrap(); + assert!(dc.get_layer(5, None).is_none() && !dc.contains(Kind::Layer, 5)); + // Written again after the miss: a hit with the new identity. + dc.put_layer_now(1, &buf(9, 4, 4), &read(&[&a])); + assert_eq!(dc.get_layer(1, None).map(|l| l.0.img), Some(buf(9, 4, 4).img)); + // The format before #3184 (no files): a miss, deleted. + dc.write_format(Kind::Layer, 6, FORMAT_RGBA8, &encode_layer(&buf(6, 4, 4))); + assert!(dc.contains(Kind::Layer, 6)); + assert!(dc.get_layer(6, None).is_none() && !dc.contains(Kind::Layer, 6)); + // A valid checksum over a damaged files section, or over a cut buffer: misses, deleted. + let mut payload = vec![]; + payload.extend_from_slice(&3u32.to_le_bytes()); + payload.extend_from_slice(&encode_layer(&buf(7, 4, 4))); + dc.write_format(Kind::Layer, 7, FORMAT_LAYER_FILES, &payload); + assert!(dc.get_layer(7, None).is_none() && !dc.contains(Kind::Layer, 7)); + let mut cut = vec![]; + EntryFiles::default().encode(&mut cut); + cut.extend_from_slice(&encode_layer(&buf(8, 4, 4))[..40]); + dc.write_format(Kind::Layer, 8, FORMAT_LAYER_FILES, &cut); + assert!(dc.get_layer(8, None).is_none() && !dc.contains(Kind::Layer, 8)); + // A damaged file on disk. + dc.put_layer_now(9, &buf(9, 4, 4), &ReadFiles::default()); + let p = dc.path(Kind::Layer, 9); + let mut d = std::fs::read(&p).unwrap(); + let n = d.len(); + d[n / 2] ^= 0xff; + std::fs::write(&p, d).unwrap(); + assert!(dc.get_layer(9, None).is_none() && !dc.contains(Kind::Layer, 9) && !p.exists()); + // Buffers whose files can't all be named are not stored. + let mut incomplete = read(&[&a]); + incomplete.mark_incomplete(); + dc.put_layer_now(10, &buf(10, 4, 4), &incomplete); + assert!(!dc.contains(Kind::Layer, 10)); + let _ = std::fs::remove_dir_all(&dir); } /// A frame entry is used only while the files it lists are what it was made of: a new size, diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs index 162c04862..7f65a0110 100644 --- a/crates/render/src/reads.rs +++ b/crates/render/src/reads.rs @@ -12,8 +12,8 @@ use std::sync::{Arc, Mutex, PoisonError}; -/// The identity of a file as a render read it (see [`file_stamp`](crate::disk_cache) for the -/// same identity in the layer-cache salt; frame entries store it, see `disk_cache::EntryFiles`). +/// The identity of a file as a render read it (frame and layer entries on disk store it, see +/// [`EntryFiles`](crate::disk_cache::EntryFiles)). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum FileStamp { /// A file on disk: its size in bytes and its modification time (nanoseconds since the Unix diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index e77f07840..8ebea08fc 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -170,10 +170,6 @@ impl EffectcraftApp { self.session.poll_jobs(); ctx.request_repaint_after(std::time::Duration::from_millis(100)); } - // The disk cache's footage salt, taken off the UI thread after footage changed. - if self.session.poll_disk_salt() { - ctx.request_repaint_after(std::time::Duration::from_millis(100)); - } // Analyses running in a worker (the web app). if !self.session.offloaded.is_empty() { self.session.poll_offload(); diff --git a/crates/ui-egui/tests/it/ui_unreadable_footage.rs b/crates/ui-egui/tests/it/ui_unreadable_footage.rs index f1c9707ba..21ca1e7c9 100644 --- a/crates/ui-egui/tests/it/ui_unreadable_footage.rs +++ b/crates/ui-egui/tests/it/ui_unreadable_footage.rs @@ -175,8 +175,7 @@ fn restored_original_and_active_proxy_render_new_pixels_through_media_and_disk_c let cache = effectcraft_render::disk_cache::DiskCache::open(dir.join("cache"), 1 << 20).unwrap(); cache.set_min_layer_ms(0); s.disk_cache = Some(cache.clone()); - let salt = s.refresh_disk_salt(true).unwrap(); - s.layer_cache.set_disk(Some((cache.clone(), salt))); + s.layer_cache.set_disk(Some(cache.clone())); let before = s.render(comp, Tick::ZERO, RenderOpts::default()); assert_eq!(before.data[8 * 16 + 8], if proxy { [0.0, 1.0, 0.0, 1.0] } else { [1.0, 0.0, 0.0, 1.0] }); cache.flush(); diff --git a/docs/architecture.md b/docs/architecture.md index 48413d1c1..213aaaf57 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -242,9 +242,14 @@ frame's float values. The browser keeps 8-bit frames for now (its frame workers A persistent **disk cache** (`render::disk_cache`, Settings ▸ Media & Disk Cache) backs both the layer cache and the viewer's RAM preview: layer buffers that were slow to render and every preview frame are written (LZ4, atomic rename, checksummed) under 128-bit content keys — the -comp's content hash (the comp, what it uses, footage file size and time) plus frame, scale and -view for frames; the layer key salted with the footage fingerprint for layers — so entries -survive restarts and never go stale. Frame entries are 8-bit RGBA, or for 32 bpc viewer frames +comp's content hash (the comp and what it uses, footage items with their settings and paths, +from memory alone) plus frame, scale and view for frames; the layer cache's content key (which +names the footage items a buffer uses with their paths) and the renderer version for layers. +Every frame and layer entry keeps the source files it was made of, with the size and +modification time they were read with, and is used only while they are unchanged: a handful of +`metadata` calls when an entry is read, never a scan of the project's files (#3184). Entries +survive restarts and never go stale; frames and buffers whose files can't all be named are not +written. Frame entries are 8-bit RGBA, or for 32 bpc viewer frames half floats with their bytes shuffled into planes before LZ4 (the entry header's format byte tells them apart; the render options in the key keep the two kinds apart). LRU eviction keeps it under the size limit; Edit ▸ Purge empties it, `cache.diskStats` reports it, and the timeline draws disk-only frames in blue. In the diff --git a/docs/web.md b/docs/web.md index 832aa86fe..4f43b753e 100644 --- a/docs/web.md +++ b/docs/web.md @@ -354,8 +354,9 @@ frame whose files can't all be named is not stored. Cache / `edit.purge {what: "disk"}` clears it. `effectcraft.info().diskCache` has the same. **Layer buffers (M13.30).** Slow layer buffers (≥ 20 ms to render) go to the disk cache too -(`effectcraft-cache/v1/layers/<32 hex>.ecc`, `disk_cache::layer_entry`, keys salted per project -and footage as on the desktop). A layer lookup happens in the middle of a synchronous render, +(`effectcraft-cache/v1/layers/<32 hex>.ecc`, `disk_cache::layer_entry`, keyed as on the desktop: +`disk_cache::layer_disk_key`; each entry keeps the source files its buffer was made of, with +the file table's size and content hash, and is used only while they are unchanged). A layer lookup happens in the middle of a synchronous render, where the browser's file system can't be read, so it is made synchronous by fetching first: 1. Each frame worker backs its layer cache with a `PrefetchStore` (`effectcraft_render::cache`):