A song is not a film to stand in for, and the cache stops at 20 GB
Browse files at this commit2c0dabd4a62eff05c70c14ef3c27b76dedd3f8c3Parent: 60ae56c- fix
- a song is not a film to stand in for, and the cache stops at 20 GB
1 changed file +148 -5
- crates/engine/src/proxy.rs +148 -5
crates/engine/src/proxy.rsmodified+148 -5
| @@ -21,7 +21,10 @@ | |||
| 21 | //! - **Derived, never authoritative.** A proxy is named after the source's | 21 | //! - **Derived, never authoritative.** A proxy is named after the source's |
| 22 | //! path, length and modification time ([`path_for`]), so a re-encoded or | 22 | //! path, length and modification time ([`path_for`]), so a re-encoded or |
| 23 | //! re-cut original simply misses the cache and a stale proxy can never be | 23 | //! re-cut original simply misses the cache and a stale proxy can never be |
| 24 | -//! found. Deleting the cache directory costs time and nothing else. | 24 | +//! found. Deleting the cache directory costs time and nothing else -- which |
| 25 | +//! is what lets this cap itself: over [`CACHE_CAP`] the least recently used | ||
| 26 | +//! stand-ins are deleted to make room ([`sweep`]), because a file written | ||
| 27 | +//! without being asked for must not be able to fill a disk. | ||
| 25 | //! | 28 | //! |
| 26 | //! Generation is [`crate::export`]'s own decode -> scale -> encode walk, given | 29 | //! Generation is [`crate::export`]'s own decode -> scale -> encode walk, given |
| 27 | //! a one-clip project and a smaller canvas: the hardware seat where the GPU has | 30 | //! a one-clip project and a smaller canvas: the hardware seat where the GPU has |
| @@ -43,6 +46,16 @@ use crate::scale::FitPolicy; | |||
| 43 | /// defaults). | 46 | /// defaults). |
| 44 | pub const LONG_EDGE: u32 = 1280; | 47 | pub const LONG_EDGE: u32 = 1280; |
| 45 | 48 | ||
| 49 | +/// How much disk the stand-ins may hold between them, in bytes: 20 GB, which | ||
| 50 | +/// is one 4K feature film and most of a second (a 2h20 one measures | ||
| 51 | +/// ~11.5 GB at ~1.37 MB per second of film), or a dozen of an ordinary length. | ||
| 52 | +/// | ||
| 53 | +/// A cap is not a nicety here. Proxies are written *without being asked for*, | ||
| 54 | +/// on import, two at a time -- so without one the answer to "how much of the | ||
| 55 | +/// disk does this take" is "all of it, eventually". Over the cap, the least | ||
| 56 | +/// recently used are deleted until it fits ([`sweep`]). | ||
| 57 | +pub const CACHE_CAP: u64 = 20 * 1024 * 1024 * 1024; | ||
| 58 | + | ||
| 46 | /// Bits per pixel per second a proxy is coded at, [`crate::export`]'s own rate | 59 | /// Bits per pixel per second a proxy is coded at, [`crate::export`]'s own rate |
| 47 | /// rule at three times the number: every frame being an IDR means no frame | 60 | /// rule at three times the number: every frame being an IDR means no frame |
| 48 | /// borrows anything from its neighbours, so the same picture at the inter rate | 61 | /// 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) { | |||
| 79 | /// cache directory at all, which is a source that gets no proxy rather than one | 92 | /// cache directory at all, which is a source that gets no proxy rather than one |
| 80 | /// littering the working directory. | 93 | /// littering the working directory. |
| 81 | /// | 94 | /// |
| 82 | -/// corner-cut: nothing evicts, exactly as the Matroska index cache beside it | 95 | +/// A re-encoded source therefore leaves its old stand-in behind, and a proxy of |
| 83 | -/// states. A proxy of a feature film is hundreds of megabytes and a re-encoded | 96 | +/// a feature film is gigabytes: [`sweep`] is what keeps that from being the |
| 84 | -/// source leaves its old one behind; the upgrade path is a size-capped sweep of | 97 | +/// whole disk, and it runs before every new one is written. |
| 85 | -/// the directory at open. It is the user's own cache to delete meanwhile. | ||
| 86 | pub fn path_for(source: &Path) -> Option<PathBuf> { | 98 | pub fn path_for(source: &Path) -> Option<PathBuf> { |
| 87 | let meta = std::fs::metadata(source).ok()?; | 99 | let meta = std::fs::metadata(source).ok()?; |
| 88 | let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) { | 100 | let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) { |
| @@ -102,6 +114,60 @@ pub fn path_for(source: &Path) -> Option<PathBuf> { | |||
| 102 | Some(dir.join(format!("{:016x}.mp4", crate::demux::fnv1a(&bytes)))) | 114 | Some(dir.join(format!("{:016x}.mp4", crate::demux::fnv1a(&bytes)))) |
| 103 | } | 115 | } |
| 104 | 116 | ||
| 117 | +/// Deletes least-recently-used stand-ins until the directory holds at most | ||
| 118 | +/// `cap` bytes, and reports what it holds afterwards. | ||
| 119 | +/// | ||
| 120 | +/// Run before a new one is written, which is the only moment this directory | ||
| 121 | +/// grows. Nothing else evicts, and nothing else can: a proxy is derived, so | ||
| 122 | +/// deleting one costs the time to make it again and no more -- which is exactly | ||
| 123 | +/// what makes a cap safe to apply behind the user's back where an eviction of | ||
| 124 | +/// anything *authored* would not be. | ||
| 125 | +/// | ||
| 126 | +/// Least recently *used* is read off the access time, with the modification | ||
| 127 | +/// time where a filesystem reports none. On a `relatime` mount -- which is the | ||
| 128 | +/// default, and is what this machine's `/home` is -- an access time moves at | ||
| 129 | +/// most once a day, so this is a daily-granularity LRU rather than an exact | ||
| 130 | +/// one. That is the right accuracy for a thing whose eviction costs a | ||
| 131 | +/// re-encode, and it is why the order is by *time* and not by a hit counter | ||
| 132 | +/// nothing would persist. | ||
| 133 | +/// | ||
| 134 | +/// A `.part` is never deleted -- it is being written right now, by this process | ||
| 135 | +/// or another -- but its bytes *are* counted: they are on the disk, and a | ||
| 136 | +/// half-written 11 GB proxy is exactly when the finished ones should make room. | ||
| 137 | +fn sweep(dir: &Path, cap: u64) -> u64 { | ||
| 138 | + let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 139 | + return 0; | ||
| 140 | + }; | ||
| 141 | + let mut total = 0u64; | ||
| 142 | + let mut evictable: Vec<(std::time::SystemTime, u64, PathBuf)> = Vec::new(); | ||
| 143 | + for entry in entries.flatten() { | ||
| 144 | + let Ok(meta) = entry.metadata() else { continue }; | ||
| 145 | + if !meta.is_file() { | ||
| 146 | + continue; | ||
| 147 | + } | ||
| 148 | + total += meta.len(); | ||
| 149 | + let path = entry.path(); | ||
| 150 | + if path.extension().is_some_and(|e| e == "mp4") { | ||
| 151 | + let used = meta.accessed().or_else(|_| meta.modified()); | ||
| 152 | + evictable.push((used.unwrap_or(UNIX_EPOCH), meta.len(), path)); | ||
| 153 | + } | ||
| 154 | + } | ||
| 155 | + if total <= cap { | ||
| 156 | + return total; | ||
| 157 | + } | ||
| 158 | + evictable.sort_by_key(|(used, ..)| *used); | ||
| 159 | + for (_, len, path) in evictable { | ||
| 160 | + if total <= cap { | ||
| 161 | + break; | ||
| 162 | + } | ||
| 163 | + if std::fs::remove_file(&path).is_ok() { | ||
| 164 | + total -= len; | ||
| 165 | + eprintln!("proxy cache: evicted {}", path.display()); | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | + total | ||
| 169 | +} | ||
| 170 | + | ||
| 105 | /// The proxy of `source` if one has already been made, `None` otherwise. The | 171 | /// The proxy of `source` if one has already been made, `None` otherwise. The |
| 106 | /// answer a session asks at open: a hit costs one `stat`. | 172 | /// answer a session asks at open: a hit costs one `stat`. |
| 107 | pub fn cached(source: &Path) -> Option<PathBuf> { | 173 | pub fn cached(source: &Path) -> Option<PathBuf> { |
| @@ -187,7 +253,16 @@ pub fn generate(source: &Path) -> crate::Result<Job> { | |||
| 187 | /// The header is read *once* for both questions: on a Matroska that read is the | 253 | /// The header is read *once* for both questions: on a Matroska that read is the |
| 188 | /// cluster walk, so asking `wanted` and then `generate` separately would pay | 254 | /// cluster walk, so asking `wanted` and then `generate` separately would pay |
| 189 | /// for it twice. | 255 | /// for it twice. |
| 256 | +/// | ||
| 257 | +/// A song and a still are not films and are answered before that read: neither | ||
| 258 | +/// has a picture stream to stand in for, and a demuxer opened on one fails -- | ||
| 259 | +/// which used to reach a front-end as "no proxy" on a `.wav`, a refusal about | ||
| 260 | +/// something nobody had asked for. `Ok(None)` is the true answer, and it is the | ||
| 261 | +/// same one a 1080p H.264 film gets. | ||
| 190 | pub fn generate_if_wanted(source: &Path) -> crate::Result<Option<Job>> { | 262 | pub fn generate_if_wanted(source: &Path) -> crate::Result<Option<Job>> { |
| 263 | + if crate::is_audio(source) || crate::is_image(source) { | ||
| 264 | + return Ok(None); | ||
| 265 | + } | ||
| 191 | started(source, wanted) | 266 | started(source, wanted) |
| 192 | } | 267 | } |
| 193 | 268 | ||
| @@ -208,6 +283,11 @@ fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result<Opti | |||
| 208 | let (width, height) = size_for(&meta); | 283 | let (width, height) = size_for(&meta); |
| 209 | if let Some(dir) = out.parent() { | 284 | if let Some(dir) = out.parent() { |
| 210 | std::fs::create_dir_all(dir)?; | 285 | std::fs::create_dir_all(dir)?; |
| 286 | + // Before the write, which is the only thing that makes this directory | ||
| 287 | + // bigger: what is already there is brought under the cap first, so the | ||
| 288 | + // disk never carries more stand-ins than [`CACHE_CAP`] plus the one | ||
| 289 | + // being written. | ||
| 290 | + sweep(dir, CACHE_CAP); | ||
| 211 | } | 291 | } |
| 212 | // What a killed editor left behind: the export worker deletes its own part | 292 | // What a killed editor left behind: the export worker deletes its own part |
| 213 | // file when it is cancelled or fails, but nothing can delete it for a | 293 | // file when it is cancelled or fails, but nothing can delete it for a |
| @@ -321,6 +401,69 @@ mod tests { | |||
| 321 | assert_eq!(size_for(&meta(1, 1, Codec::H264)), (2, 2), "never zero"); | 401 | assert_eq!(size_for(&meta(1, 1, Codec::H264)), (2, 2), "never zero"); |
| 322 | } | 402 | } |
| 323 | 403 | ||
| 404 | + /// The cap keeps the directory a cache and not a second copy of the | ||
| 405 | + /// library: over it, the least recently used go until it fits, and a | ||
| 406 | + /// half-written one is never taken (it is being written *now*) though its | ||
| 407 | + /// bytes count towards what has to be freed. | ||
| 408 | + #[test] | ||
| 409 | + fn the_cache_evicts_its_oldest_until_it_fits() { | ||
| 410 | + let dir = crate::scratch::Scratch::dir("proxy-sweep"); | ||
| 411 | + let write = |name: &str, len: usize, ago: u64| { | ||
| 412 | + let path = dir.join(name); | ||
| 413 | + std::fs::write(&path, vec![0u8; len]).expect("write"); | ||
| 414 | + // Stamped by hand: three files written in one millisecond have no | ||
| 415 | + // order of their own, and the order is what is under test. `atime` | ||
| 416 | + // is what `sweep` reads and `set_times` is the one door to it | ||
| 417 | + // without a dependency. | ||
| 418 | + let file = std::fs::File::options().write(true).open(&path).expect("open"); | ||
| 419 | + let when = std::time::SystemTime::now() - std::time::Duration::from_secs(ago); | ||
| 420 | + file.set_times(std::fs::FileTimes::new().set_accessed(when).set_modified(when)) | ||
| 421 | + .expect("stamp"); | ||
| 422 | + path | ||
| 423 | + }; | ||
| 424 | + let old = write("old.mp4", 400, 300); | ||
| 425 | + let middle = write("middle.mp4", 400, 200); | ||
| 426 | + let fresh = write("fresh.mp4", 400, 100); | ||
| 427 | + let part = write("busy.mp4.part", 400, 400); | ||
| 428 | + | ||
| 429 | + // 1600 bytes there, 900 allowed: the oldest two `.mp4`s go, and that is | ||
| 430 | + // as far as it gets -- the part file is 400 of the remaining bytes and | ||
| 431 | + // is not the sweep's to take. | ||
| 432 | + let left = sweep(&dir, 900); | ||
| 433 | + assert!(!old.exists(), "the oldest stand-in survived the sweep"); | ||
| 434 | + assert!(!middle.exists(), "the next oldest survived it"); | ||
| 435 | + assert!(fresh.exists(), "the freshest was taken"); | ||
| 436 | + assert!(part.exists(), "a half-written proxy was deleted under its writer"); | ||
| 437 | + assert_eq!(left, 800, "what is left is the fresh one and the part file"); | ||
| 438 | + | ||
| 439 | + // Under the cap, nothing is touched at all. | ||
| 440 | + assert_eq!(sweep(&dir, 900), 800); | ||
| 441 | + assert!(fresh.exists()); | ||
| 442 | + } | ||
| 443 | + | ||
| 444 | + /// A song and a still are not films: they are answered `None` -- the same | ||
| 445 | + /// answer a 1080p H.264 film gets -- rather than opened, failed on and | ||
| 446 | + /// reported. The bug this pins said "NO PROXY for tone.wav" to a person who | ||
| 447 | + /// had imported a song, and put "no proxy" on its library row. | ||
| 448 | + /// | ||
| 449 | + /// Real files, because the point is that nothing reads them: a demuxer | ||
| 450 | + /// opened on a WAV is exactly what used to raise the refusal. | ||
| 451 | + #[test] | ||
| 452 | + fn a_song_and_a_still_are_never_stood_in_for() { | ||
| 453 | + let dir = crate::scratch::Scratch::dir("proxy-not-a-film"); | ||
| 454 | + for name in ["tone.wav", "song.mp3", "track.mka", "still.png", "shot.jpg"] { | ||
| 455 | + let file = dir.join(name); | ||
| 456 | + std::fs::write(&file, b"not a film, and never read").expect("write"); | ||
| 457 | + let answer = generate_if_wanted(&file); | ||
| 458 | + assert!( | ||
| 459 | + matches!(answer, Ok(None)), | ||
| 460 | + "{name} is not a film to stand in for: {:?}", | ||
| 461 | + answer.err().map(|e| e.to_string()) | ||
| 462 | + ); | ||
| 463 | + assert_eq!(cached(&file), None, "{name} left nothing in the cache"); | ||
| 464 | + } | ||
| 465 | + } | ||
| 466 | + | ||
| 324 | /// The staleness rule *is* the name: touch the source and the old proxy is | 467 | /// The staleness rule *is* the name: touch the source and the old proxy is |
| 325 | /// unreachable rather than wrong. | 468 | /// unreachable rather than wrong. |
| 326 | #[test] | 469 | #[test] |