diff --git a/crates/engine/src/proxy.rs b/crates/engine/src/proxy.rs index eada5cf..1cb6fc4 100644 --- a/crates/engine/src/proxy.rs +++ b/crates/engine/src/proxy.rs @@ -21,7 +21,10 @@ //! - **Derived, never authoritative.** A proxy is named after the source's //! path, length and modification time ([`path_for`]), so a re-encoded or //! re-cut original simply misses the cache and a stale proxy can never be -//! found. Deleting the cache directory costs time and nothing else. +//! found. Deleting the cache directory costs time and nothing else -- which +//! is what lets this cap itself: over [`CACHE_CAP`] the least recently used +//! stand-ins are deleted to make room ([`sweep`]), because a file written +//! without being asked for must not be able to fill a disk. //! //! Generation is [`crate::export`]'s own decode -> scale -> encode walk, given //! a one-clip project and a smaller canvas: the hardware seat where the GPU has @@ -43,6 +46,16 @@ use crate::scale::FitPolicy; /// defaults). pub const LONG_EDGE: u32 = 1280; +/// How much disk the stand-ins may hold between them, in bytes: 20 GB, which +/// is one 4K feature film and most of a second (a 2h20 one measures +/// ~11.5 GB at ~1.37 MB per second of film), or a dozen of an ordinary length. +/// +/// A cap is not a nicety here. Proxies are written *without being asked for*, +/// on import, two at a time -- so without one the answer to "how much of the +/// disk does this take" is "all of it, eventually". Over the cap, the least +/// recently used are deleted until it fits ([`sweep`]). +pub const CACHE_CAP: u64 = 20 * 1024 * 1024 * 1024; + /// Bits per pixel per second a proxy is coded at, [`crate::export`]'s own rate /// rule at three times the number: every frame being an IDR means no frame /// borrows anything from its neighbours, so the same picture at the inter rate @@ -79,10 +92,9 @@ pub fn size_for(meta: &VideoMeta) -> (u32, u32) { /// cache directory at all, which is a source that gets no proxy rather than one /// littering the working directory. /// -/// corner-cut: nothing evicts, exactly as the Matroska index cache beside it -/// states. A proxy of a feature film is hundreds of megabytes and a re-encoded -/// source leaves its old one behind; the upgrade path is a size-capped sweep of -/// the directory at open. It is the user's own cache to delete meanwhile. +/// A re-encoded source therefore leaves its old stand-in behind, and a proxy of +/// a feature film is gigabytes: [`sweep`] is what keeps that from being the +/// whole disk, and it runs before every new one is written. pub fn path_for(source: &Path) -> Option { let meta = std::fs::metadata(source).ok()?; let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) { @@ -102,6 +114,60 @@ pub fn path_for(source: &Path) -> Option { Some(dir.join(format!("{:016x}.mp4", crate::demux::fnv1a(&bytes)))) } +/// Deletes least-recently-used stand-ins until the directory holds at most +/// `cap` bytes, and reports what it holds afterwards. +/// +/// Run before a new one is written, which is the only moment this directory +/// grows. Nothing else evicts, and nothing else can: a proxy is derived, so +/// deleting one costs the time to make it again and no more -- which is exactly +/// what makes a cap safe to apply behind the user's back where an eviction of +/// anything *authored* would not be. +/// +/// Least recently *used* is read off the access time, with the modification +/// time where a filesystem reports none. On a `relatime` mount -- which is the +/// default, and is what this machine's `/home` is -- an access time moves at +/// most once a day, so this is a daily-granularity LRU rather than an exact +/// one. That is the right accuracy for a thing whose eviction costs a +/// re-encode, and it is why the order is by *time* and not by a hit counter +/// nothing would persist. +/// +/// A `.part` is never deleted -- it is being written right now, by this process +/// or another -- but its bytes *are* counted: they are on the disk, and a +/// half-written 11 GB proxy is exactly when the finished ones should make room. +fn sweep(dir: &Path, cap: u64) -> u64 { + let Ok(entries) = std::fs::read_dir(dir) else { + return 0; + }; + let mut total = 0u64; + let mut evictable: Vec<(std::time::SystemTime, u64, PathBuf)> = Vec::new(); + for entry in entries.flatten() { + let Ok(meta) = entry.metadata() else { continue }; + if !meta.is_file() { + continue; + } + total += meta.len(); + let path = entry.path(); + if path.extension().is_some_and(|e| e == "mp4") { + let used = meta.accessed().or_else(|_| meta.modified()); + evictable.push((used.unwrap_or(UNIX_EPOCH), meta.len(), path)); + } + } + if total <= cap { + return total; + } + evictable.sort_by_key(|(used, ..)| *used); + for (_, len, path) in evictable { + if total <= cap { + break; + } + if std::fs::remove_file(&path).is_ok() { + total -= len; + eprintln!("proxy cache: evicted {}", path.display()); + } + } + total +} + /// The proxy of `source` if one has already been made, `None` otherwise. The /// answer a session asks at open: a hit costs one `stat`. pub fn cached(source: &Path) -> Option { @@ -187,7 +253,16 @@ pub fn generate(source: &Path) -> crate::Result { /// The header is read *once* for both questions: on a Matroska that read is the /// cluster walk, so asking `wanted` and then `generate` separately would pay /// for it twice. +/// +/// A song and a still are not films and are answered before that read: neither +/// has a picture stream to stand in for, and a demuxer opened on one fails -- +/// which used to reach a front-end as "no proxy" on a `.wav`, a refusal about +/// something nobody had asked for. `Ok(None)` is the true answer, and it is the +/// same one a 1080p H.264 film gets. pub fn generate_if_wanted(source: &Path) -> crate::Result> { + if crate::is_audio(source) || crate::is_image(source) { + return Ok(None); + } started(source, wanted) } @@ -208,6 +283,11 @@ fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result