forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbdb07d9Tahinli3 months ago645 commits

proxy.rs865 lines, 39.7 KiBHistoryRawDownload
1//! Small stand-ins for big files: a half-size, every-frame-a-keyframe H.264
2//! copy of a source, kept in the user's cache and played instead of the
3//! original while the cut is being made.
4//!
5//! Why they exist at all: a 4K HEVC film decodes at a fraction of realtime on
6//! this machine, so scrubbing it is a slideshow and every seek is a wait. A
7//! proxy is the same film at 1280 on its long edge, coded so that **every frame
8//! is a random-access point** -- which is what makes a seek land on the frame
9//! that was asked for instead of on the nearest one a decoder can start from,
10//! and what takes the whole open-GOP class of seek faults off the table by
11//! construction.
12//!
13//! Three rules, and they are the whole contract:
14//!
15//! - **Picture only.** No sound is coded into a proxy. The mix always comes off
16//! the original file ([`crate::PlaybackSession`] opens audio by its own path,
17//! which this module never touches), so nothing a listener hears has been
18//! through a second encoder.
19//! - **Never exported.** [`crate::export`] reads the project's own sources and
20//! knows nothing of this module. Delivery is the original, always.
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
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 -- 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.
28//!
29//! Generation is [`crate::export`]'s own decode -> scale -> encode walk, given
30//! a one-clip project and a smaller canvas: the hardware seat where the GPU has
31//! one, the software encoder where it does not, the same progress and the same
32//! cancel a file export has ([`Job`]).
33
34use std::path::{Path, PathBuf};
35use std::time::UNIX_EPOCH;
36
37use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta};
38use crate::export::{ExportHandle, ExportSettings, Format};
39use crate::project::{Clip, LaneKind, Project, Source, Speed};
40use crate::scale::FitPolicy;
41
42/// The long edge of a proxy picture, in samples: 1280, so a 4K source loses
43/// nine tenths of its samples and a 1080p one a little over half. Chosen as
44/// what a cut can be judged on at editing size, in the neighbourhood of every
45/// shipped proxy preset (Resolve's half-res, kdenlive's 640/1000-wide
46/// defaults).
47pub const LONG_EDGE: u32 = 1280;
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, [`AT_ONCE`] at a time -- so without one the answer to "how much
55/// of the disk does this take" is "all of it, eventually". Over the cap, the
56/// least recently used are deleted until it fits ([`sweep`]).
57///
58/// **What this really bounds.** A sweep runs before each new stand-in and
59/// leaves room for the ones about to be written ([`reserve`]), so what is
60/// *finished* is held to `CACHE_CAP - reserve` and the encodes in flight have
61/// the reserve to grow into. The directory therefore sits at about the cap
62/// rather than at the cap plus a film per encode, which is what it did when the
63/// sweep aimed at the bare number. It can still pass the cap where an encode
64/// outruns its own estimate -- a stand-in cannot be deleted while it is being
65/// written -- and the next sweep takes that back.
66pub const CACHE_CAP: u64 = 20 * 1024 * 1024 * 1024;
67
68/// How many stand-ins may be made at once. Two, not one per core: each is a
69/// whole film through a decoder and an encoder, and the hardware seat they
70/// queue on is a single one -- more of them at once is the same work done
71/// later, with the editor slower while it happens.
72///
73/// It lives here rather than in the front-end that does the fanning out because
74/// the cache's own arithmetic needs it ([`reserve`]): the number of encodes in
75/// flight is exactly how much room the sweep has to leave, and two places
76/// holding that number separately is one place for them to disagree.
77pub const AT_ONCE: usize = 2;
78
79/// What the hardware seat really writes against what it was asked for: 1.25,
80/// measured 2026-08-13 (8.3 Mbit/s out of a 6.6 Mbit/s request on radeonsi).
81/// Folded into [`reserve`] so the room left for an encode is the room it will
82/// actually take, not the room it was told to.
83const RATE_OVERSHOOT: f64 = 1.25;
84
85/// Bits per pixel per second a proxy is coded at, [`crate::export`]'s own rate
86/// rule at three times the number: every frame being an IDR means no frame
87/// borrows anything from its neighbours, so the same picture at the inter rate
88/// would be mush -- and mush is not something a cut can be judged on.
89const BITS_PER_PIXEL: f64 = 0.3;
90
91/// Whether this is a file worth standing in for: bigger than 1080p, or coded in
92/// something this machine decodes slowly even at 1080p. H.264 at or under 1080p
93/// plays natively and a proxy of it would cost time and buy nothing.
94pub fn wanted(meta: &VideoMeta) -> bool {
95 meta.width > 1920 || meta.height > 1080 || matches!(meta.codec, Codec::Hevc | Codec::Av1)
96}
97
98/// The picture a proxy of `meta` is coded at: aspect kept, long edge at most
99/// [`LONG_EDGE`], both axes even because 4:2:0 has no half chroma samples. A
100/// source already that small is coded at its own size (rounded down to even),
101/// which is what makes [`generate`] safe to ask for on anything at all.
102pub fn size_for(meta: &VideoMeta) -> (u32, u32) {
103 let long = meta.width.max(meta.height);
104 let scale = match long > LONG_EDGE {
105 true => f64::from(LONG_EDGE) / f64::from(long),
106 false => 1.0,
107 };
108 let even = |n: u32| (((f64::from(n) * scale).round() as u32) & !1).max(2);
109 (even(meta.width), even(meta.height))
110}
111
112/// Where the proxy of `source` lives, whether or not it has been made yet.
113///
114/// The name is one hash of the source's canonical path, its length **and** its
115/// modification time, so an original that changed at all is a different name
116/// and its old proxy is simply never looked at again -- the staleness check is
117/// the lookup. `None` where the file cannot be stat'd or the machine has no
118/// cache directory at all, which is a source that gets no proxy rather than one
119/// littering the working directory.
120///
121/// A re-encoded source therefore leaves its old stand-in behind, and a proxy of
122/// a feature film is gigabytes: [`sweep`] is what keeps that from being the
123/// whole disk, and it runs before every new one is written.
124pub fn path_for(source: &Path) -> Option<PathBuf> {
125 let meta = std::fs::metadata(source).ok()?;
126 let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) {
127 Ok(d) => (d.as_secs() as i128, d.subsec_nanos()),
128 Err(e) => (-(e.duration().as_secs() as i128), e.duration().subsec_nanos()),
129 };
130 let canonical = std::fs::canonicalize(source).unwrap_or_else(|_| source.to_path_buf());
131 let mut bytes = canonical.as_os_str().as_encoded_bytes().to_vec();
132 bytes.extend_from_slice(&meta.len().to_le_bytes());
133 bytes.extend_from_slice(&mtime.0.to_le_bytes());
134 bytes.extend_from_slice(&mtime.1.to_le_bytes());
135 let dir = crate::demux::cache_dir(
136 std::env::var_os("XDG_CACHE_HOME"),
137 std::env::var_os("HOME"),
138 "proxies",
139 )?;
140 Some(dir.join(format!("{:016x}.mp4", crate::demux::fnv1a(&bytes))))
141}
142
143/// How much of [`CACHE_CAP`] the sweep leaves free for the stand-ins that are
144/// about to be written into the directory: [`AT_ONCE`] of them, each about the
145/// size of the one being started now.
146///
147/// The estimate is the file's own arithmetic and not a guess: the picture is
148/// coded at [`BITS_PER_PIXEL`] bits per pixel per second and the frame rate
149/// cancels out, so it is `width * height * frames * bpp / 8` -- times
150/// [`RATE_OVERSHOOT`], because the hardware seat writes over the rate it is
151/// asked for.
152///
153/// Held to half the cap, whatever that comes to. A single 4K feature estimates
154/// at over the whole cap, and reserving that would empty the cache to make room
155/// for one film -- deleting stand-ins that are in use, for a bound that cannot
156/// be met anyway while two of them are being written. Half is the compromise:
157/// what is *finished* stays under half the cap, so the two in flight have the
158/// other half to grow into before the disk carries more than [`CACHE_CAP`].
159fn reserve(width: u32, height: u32, frames: u32) -> u64 {
160 let bytes = f64::from(width) * f64::from(height) * f64::from(frames) * BITS_PER_PIXEL / 8.0;
161 ((bytes * RATE_OVERSHOOT) as u64)
162 .saturating_mul(AT_ONCE as u64)
163 .min(CACHE_CAP / 2)
164}
165
166/// Deletes least-recently-used stand-ins until the directory holds at most
167/// `cap` bytes, and reports what it holds afterwards.
168///
169/// Run before a new one is written, which is the only moment this directory
170/// grows. Nothing else evicts, and nothing else can: a proxy is derived, so
171/// deleting one costs the time to make it again and no more -- which is exactly
172/// what makes a cap safe to apply behind the user's back where an eviction of
173/// anything *authored* would not be.
174///
175/// Least recently *used* is read off the access time, with the modification
176/// time where a filesystem reports none. On a `relatime` mount -- which is the
177/// default, and is what this machine's `/home` is -- an access time moves at
178/// most once a day, so this is a daily-granularity LRU rather than an exact
179/// one. That is the right accuracy for a thing whose eviction costs a
180/// re-encode, and it is why the order is by *time* and not by a hit counter
181/// nothing would persist.
182///
183/// A `.part` is never deleted -- it is being written right now, by this process
184/// or another -- but its bytes *are* counted: they are on the disk, and a
185/// half-written 11 GB proxy is exactly when the finished ones should make room.
186fn sweep(dir: &Path, cap: u64) -> u64 {
187 let Ok(entries) = std::fs::read_dir(dir) else {
188 return 0;
189 };
190 let mut total = 0u64;
191 let mut evictable: Vec<(std::time::SystemTime, u64, PathBuf)> = Vec::new();
192 for entry in entries.flatten() {
193 let Ok(meta) = entry.metadata() else { continue };
194 if !meta.is_file() {
195 continue;
196 }
197 total += meta.len();
198 let path = entry.path();
199 if path.extension().is_some_and(|e| e == "mp4") {
200 let used = meta.accessed().or_else(|_| meta.modified());
201 evictable.push((used.unwrap_or(UNIX_EPOCH), meta.len(), path));
202 }
203 }
204 if total <= cap {
205 return total;
206 }
207 evictable.sort_by_key(|(used, ..)| *used);
208 for (_, len, path) in evictable {
209 if total <= cap {
210 break;
211 }
212 if std::fs::remove_file(&path).is_ok() {
213 total -= len;
214 eprintln!("proxy cache: evicted {}", path.display());
215 }
216 }
217 total
218}
219
220/// The proxy of `source` if one has already been made, `None` otherwise. The
221/// answer a session asks at open: a hit costs one `stat`.
222pub fn cached(source: &Path) -> Option<PathBuf> {
223 path_for(source).filter(|p| p.is_file())
224}
225
226/// Deletes the stand-in of `source`, if there is one, and says whether a file
227/// went. The one *by hand* eviction: [`sweep`] takes the oldest to stay under a
228/// cap, this takes the one that was asked for.
229///
230/// The source itself is never touched -- what is deleted is [`path_for`]'s
231/// answer, a name in the cache directory and nothing else -- and deleting one
232/// under a session that is playing off it costs a re-open: [`cached`] stats,
233/// finds nothing, and the film itself is what plays from the next span on
234/// ([`crate::PlaybackSession::picture_path`]).
235/// Three answers and not two, because they are three different rows: `Ok(true)`
236/// is a stand-in that went, `Ok(false)` is one that was never there (a no-op,
237/// and the switch is honestly off afterwards), and `Err` is a file that is
238/// **still on the disk** -- a read-only cache directory, a filesystem gone
239/// away. A caller that folded the last two together drew the row as OFF over a
240/// proxy [`cached`] went on handing to playback.
241pub fn delete(source: &Path) -> std::io::Result<bool> {
242 let Some(path) = path_for(source) else {
243 return Ok(false);
244 };
245 match std::fs::remove_file(&path) {
246 Ok(()) => {
247 eprintln!("proxy cache: deleted {}", path.display());
248 Ok(true)
249 }
250 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
251 Err(e) => Err(e),
252 }
253}
254
255/// The mark beside a cache entry that says its film was switched *off* by hand,
256/// and the one thing about a stand-in that outlives the window: without it the
257/// next launch's sweep re-encodes the very proxy somebody just turned off.
258///
259/// Keyed exactly as the stand-in itself is ([`path_for`]) and living beside it,
260/// which is what makes it answer for a film that is in no project at all -- the
261/// `.edith` file knows only the sources of one timeline, and the switch is on a
262/// library row that may belong to none. Derived and disposable like everything
263/// else in this directory: a re-encoded source names another key and is asked
264/// again, and deleting the cache forgets the choice, which costs one click.
265///
266/// corner-cut: the choice therefore does not survive a cache wipe or an edit to
267/// the source file. Upgrade path is a list in the `.edith`, which needs the
268/// project format to carry per-source flags.
269fn off_marker(source: &Path) -> Option<PathBuf> {
270 Some(path_for(source)?.with_extension("off"))
271}
272
273/// Whether this film's stand-in was switched off by hand ([`off_marker`]).
274pub fn is_off(source: &Path) -> bool {
275 off_marker(source).is_some_and(|p| p.exists())
276}
277
278/// Writes or clears that mark. Best effort: a cache directory that cannot be
279/// written is a choice that does not survive the session, never a refused
280/// click.
281pub fn set_off(source: &Path, off: bool) {
282 let Some(marker) = off_marker(source) else {
283 return;
284 };
285 match off {
286 true => {
287 if let Some(dir) = marker.parent() {
288 let _ = std::fs::create_dir_all(dir);
289 }
290 let _ = std::fs::write(&marker, b"");
291 }
292 false => {
293 let _ = std::fs::remove_file(&marker);
294 }
295 }
296}
297
298/// The stand-ins being written *right now*, one entry per live encoder, held
299/// for the life of the [`Job`].
300///
301/// The one-encoder-per-film rule lives here rather than only in the window that
302/// draws the switch: two starts for one film race over one `.part` path, and
303/// the second unlinks the first's file and leaves it writing into an orphaned
304/// inode with nothing left holding its handle -- an encode nobody can stop,
305/// which finishes minutes later and puts back a proxy somebody had switched
306/// off. A guarantee that lives in the caller is a guarantee every future caller
307/// has to re-make.
308static IN_FLIGHT: std::sync::Mutex<Vec<PathBuf>> = std::sync::Mutex::new(Vec::new());
309
310/// A held seat in [`IN_FLIGHT`], given up when the job that owns it is dropped.
311struct Claim(PathBuf);
312
313impl Drop for Claim {
314 fn drop(&mut self) {
315 let mut held = IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner());
316 if let Some(i) = held.iter().position(|p| *p == self.0) {
317 held.swap_remove(i);
318 }
319 }
320}
321
322/// Takes the seat for `out`, or `None` where an encoder already has it.
323fn claim(out: &Path) -> Option<Claim> {
324 let mut held = IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner());
325 match held.iter().any(|p| p == out) {
326 true => None,
327 false => {
328 held.push(out.to_path_buf());
329 Some(Claim(out.to_path_buf()))
330 }
331 }
332}
333
334/// A proxy being made -- or one that was already there, which is the same thing
335/// to whoever is waiting for a path.
336///
337/// Poll [`progress`](Job::progress) while [`is_finished`](Job::is_finished) is
338/// false and take the [`outcome`](Job::outcome) when it flips, exactly as an
339/// export is polled. Dropping the job does not stop the work;
340/// [`cancel`](Job::cancel) does.
341pub struct Job {
342 out: PathBuf,
343 /// `None` for a cache hit: there was nothing to run.
344 handle: Option<ExportHandle>,
345 /// The seat this encoder holds ([`IN_FLIGHT`]), given back when the job
346 /// goes. `None` for a cache hit, which codes nothing.
347 _claim: Option<Claim>,
348}
349
350impl Job {
351 /// Fraction of the proxy's pictures written, `0.0..=1.0`. A cache hit is
352 /// done.
353 ///
354 /// The band an export's bar reserves for its sound is taken back out: a
355 /// proxy has no sound, so that band is crossed in the first instant and
356 /// showing it would be five percent no frame earned.
357 pub fn progress(&self) -> f32 {
358 let Some(handle) = &self.handle else {
359 return 1.0;
360 };
361 let band = crate::export::AUDIO_BAND as f32 / crate::export::PROGRESS_SCALE as f32;
362 ((handle.progress() - band) / (1.0 - band)).clamp(0.0, 1.0)
363 }
364
365 /// What is coding this proxy -- the hardware seat or the software one, as
366 /// the worker really opened it. `None` before the encoder is open, and for
367 /// a cache hit, which coded nothing.
368 pub fn encoder(&self) -> Option<String> {
369 self.handle.as_ref()?.encoders()
370 }
371
372 /// Asks the worker to stop at its next frame and leave no file behind. The
373 /// outcome then reports the cancellation as an error.
374 pub fn cancel(&self) {
375 if let Some(handle) = &self.handle {
376 handle.cancel();
377 }
378 }
379
380 pub fn is_finished(&self) -> bool {
381 self.handle.as_ref().is_none_or(ExportHandle::is_finished)
382 }
383
384 /// The proxy's path once it is written, once -- taken out of the job, so a
385 /// caller that already took it sees `None`. `None` while it is still being
386 /// made.
387 pub fn outcome(&self) -> Option<crate::Result<PathBuf>> {
388 let Some(handle) = &self.handle else {
389 return Some(Ok(self.out.clone()));
390 };
391 handle.result().map(|r| r.map(|()| self.out.clone()))
392 }
393
394 /// Where the proxy will be, whether or not it is there yet -- what a caller
395 /// names in a log line while the job runs.
396 pub fn path(&self) -> &Path {
397 &self.out
398 }
399}
400
401/// Starts making the proxy of `source`, or hands back the one already in the
402/// cache. Errors are the ones that happen before a worker exists -- a file with
403/// no picture in it, nowhere to put a cache -- and everything after them comes
404/// back through [`Job::outcome`], so a caller has two places to look and not
405/// twenty.
406pub fn generate(source: &Path) -> crate::Result<Job> {
407 Ok(started(source, |_| true)?.expect("nothing was filtered out"))
408}
409
410/// The same, for a file that is worth standing in for and nobody else
411/// ([`wanted`]) -- `Ok(None)` is a film this machine already cuts at speed.
412///
413/// The header is read *once* for both questions: on a Matroska that read is the
414/// cluster walk, so asking `wanted` and then `generate` separately would pay
415/// for it twice.
416///
417/// A file with no picture in it is not a film and is answered `Ok(None)`, the
418/// same answer a 1080p H.264 film gets -- it is not a failure, and reporting it
419/// as one put "NO PROXY for tone.wav" in front of somebody who had imported a
420/// song.
421///
422/// Twice, because there are two ways to know. A name this engine already reads
423/// as sound or as a still is answered before anything is opened, which is the
424/// cheap half. The other half is the honest one: **an audio-only `.mp4`, `.mkv`
425/// or `.mov` is a video container with no video track in it**, and only its
426/// header says so -- so the demuxer's own [`NoVideoTrack`] answer is taken here
427/// as the same quiet `None`. A film that *has* a picture and will not open is a
428/// different thing and stays loud.
429pub fn generate_if_wanted(source: &Path) -> crate::Result<Option<Job>> {
430 if crate::is_audio(source) || crate::is_image(source) {
431 return Ok(None);
432 }
433 // Switched off by hand, in this session or in one last week ([`set_off`]):
434 // the sweep that runs at every launch comes through here, and without this
435 // it re-encodes the stand-in somebody just turned off. Answered before the
436 // header is read, so a library of switched-off films costs no disk at all.
437 if is_off(source) {
438 return Ok(None);
439 }
440 match started(source, wanted) {
441 Err(e) if NoVideoTrack::is_it(&e) => Ok(None),
442 other => other,
443 }
444}
445
446/// Both doors: the cache is looked at, the header is read once, and `only_if`
447/// decides off that header whether there is anything to do.
448fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result<Option<Job>> {
449 let out = path_for(source).ok_or("no cache directory to keep a proxy in")?;
450 if out.is_file() {
451 return Ok(Some(Job {
452 out,
453 handle: None,
454 _claim: None,
455 }));
456 }
457 // One encoder per film, taken before the header is read and given back when
458 // the job is dropped ([`IN_FLIGHT`]): the second start would unlink the
459 // first's `.part` below and orphan an encode nothing can stop.
460 let claim = claim(&out).ok_or("a stand-in for this film is already being made")?;
461 // The source's own header: its rate and length are the proxy's (a stand-in
462 // that ran at another rate or stopped early would put every cut on another
463 // frame), and only its picture size changes.
464 let (meta, _) = Demuxer::open(source)?;
465 if !only_if(&meta) {
466 return Ok(None);
467 }
468 let (width, height) = size_for(&meta);
469 if let Some(dir) = out.parent() {
470 std::fs::create_dir_all(dir)?;
471 // Before the write, which is the only thing that makes this directory
472 // bigger -- and with room left for what is *about* to be written into
473 // it: sweeping to the bare cap left the finished ones filling it and
474 // then [`AT_ONCE`] encodes adding gigabytes on top, which is a cap that
475 // is over by a whole film's worth by construction ([`reserve`]).
476 sweep(dir, CACHE_CAP.saturating_sub(reserve(width, height, meta.frame_count)));
477 }
478 // What a killed editor left behind: the export worker deletes its own part
479 // file when it is cancelled or fails, but nothing can delete it for a
480 // process that was killed -- and a proxy of a feature film is hundreds of
481 // megabytes of cache nothing would ever look at again. The key is the same,
482 // so this is that same film's own leftover and not somebody else's.
483 let mut part = out.clone().into_os_string();
484 part.push(".part");
485 let _ = std::fs::remove_file(PathBuf::from(part));
486 // One video lane, one clip, the whole file -- and *no* audio lane, which is
487 // what makes the proxy picture-only: the export walk codes the lanes it is
488 // given and there is no sound among them.
489 let clip = Clip {
490 fade_in: 0,
491 fade_out: 0,
492 transition_out: 0,
493 start: 0,
494 in_frame: 0,
495 out_frame: meta.frame_count.max(1),
496 source: 0,
497 link: None,
498 eq: None,
499 color: None,
500 transform: None,
501 fit: FitPolicy::default(),
502 speed: Speed::NORMAL,
503 };
504 let project = Project::from_parts(
505 vec![Source::new(source, 0)],
506 vec![(LaneKind::Video, vec![clip])],
507 Vec::new(),
508 Vec::new(),
509 Vec::new(),
510 )?;
511 let bitrate =
512 (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64;
513 let handle = crate::export::start(
514 project,
515 VideoMeta {
516 width,
517 height,
518 ..meta
519 },
520 &out,
521 &ExportSettings {
522 format: Format::Mp4,
523 // The whole point: every frame its own random-access point.
524 intra_only: true,
525 // ...and the film's own colour, carried rather than converted: the
526 // screen tone-maps the stand-in exactly as it tone-maps the film,
527 // live and at preview size.
528 keep_source_colour: true,
529 bitrate: Some(bitrate),
530 ..Default::default()
531 },
532 // A stand-in keeps its film's own rate: the override is the
533 // timeline's affair, not the proxy's.
534 None,
535 );
536 Ok(Some(Job {
537 out,
538 handle: Some(handle),
539 _claim: Some(claim),
540 }))
541}
542
543#[cfg(test)]
544mod tests {
545 use super::*;
546 use crate::colorspace::ColorDescription;
547
548 fn meta(width: u32, height: u32, codec: Codec) -> VideoMeta {
549 VideoMeta {
550 width,
551 height,
552 frame_rate: 24.0,
553 frame_count: 240,
554 codec,
555 color: ColorDescription::default(),
556 }
557 }
558
559 /// What a proxy is *for*: the files this machine cannot play at speed.
560 #[test]
561 fn only_the_files_that_need_one_get_one() {
562 assert!(wanted(&meta(3840, 2160, Codec::Hevc)), "4K HEVC");
563 assert!(wanted(&meta(3840, 2160, Codec::H264)), "4K H.264");
564 assert!(wanted(&meta(1920, 1080, Codec::Hevc)), "1080p HEVC");
565 assert!(wanted(&meta(1920, 1080, Codec::Av1)), "1080p AV1");
566 assert!(
567 !wanted(&meta(1920, 1080, Codec::H264)),
568 "1080p H.264 plays natively"
569 );
570 assert!(!wanted(&meta(1280, 720, Codec::H264)), "720p H.264");
571 }
572
573 /// Aspect kept, long edge capped, both axes even -- and a small source left
574 /// alone rather than blown up.
575 #[test]
576 fn a_proxy_is_the_same_shape_at_a_smaller_size() {
577 assert_eq!(size_for(&meta(3840, 2160, Codec::Hevc)), (1280, 720));
578 assert_eq!(size_for(&meta(1920, 1080, Codec::Hevc)), (1280, 720));
579 // A portrait source is capped on *its* long edge, which is the height.
580 assert_eq!(size_for(&meta(1080, 1920, Codec::Hevc)), (720, 1280));
581 // 1916x1080 (a real film's cropped width): even both ways, and the
582 // aspect it really has rather than the 16:9 it nearly has.
583 let (w, h) = size_for(&meta(1916, 1080, Codec::H264));
584 assert_eq!((w, h), (1280, 722), "cropped-width 1080p");
585 assert_eq!(w % 2, 0);
586 assert_eq!(h % 2, 0);
587 assert!(
588 (f64::from(w) / f64::from(h) - 1916. / 1080.).abs() < 0.005,
589 "{w}x{h} is the source's shape"
590 );
591 assert_eq!(
592 size_for(&meta(640, 360, Codec::H264)),
593 (640, 360),
594 "already small: its own size, never upscaled"
595 );
596 assert_eq!(size_for(&meta(1, 1, Codec::H264)), (2, 2), "never zero");
597 }
598
599 /// What the sweep leaves free for the encodes that are about to run: two
600 /// of them, at what this one is really going to cost. Without it the cap
601 /// was soft by a whole film per encode -- 20 GB of finished stand-ins and
602 /// then two 4K ones writing gigabytes on top of it.
603 #[test]
604 fn the_cap_keeps_room_for_what_is_about_to_be_written() {
605 // A 2h20 4K film, at the size a stand-in of it is coded: 1280x536 for
606 // 201536 frames. Its own arithmetic says ~2.6 GB, and two of them is
607 // over the cap's half, so the reserve is that half.
608 let big = reserve(1280, 536, 201_536);
609 assert_eq!(big, CACHE_CAP / 2, "a feature film asks for more than half");
610 // A short clip asks for what it costs and no more: 1280x720 for 300
611 // frames is 1280*720*300*0.3/8 * 1.25 * 2 encodes.
612 let small = reserve(1280, 720, 300);
613 let one = 1280.0 * 720.0 * 300.0 * BITS_PER_PIXEL / 8.0 * RATE_OVERSHOOT;
614 assert_eq!(small, one as u64 * AT_ONCE as u64);
615 assert!(small < CACHE_CAP / 2, "and it is nowhere near the ceiling");
616 // The reserve is what a sweep aims below, so what is *finished* is held
617 // under the cap by at least the room the encodes will take.
618 assert!(CACHE_CAP.saturating_sub(big) <= CACHE_CAP / 2);
619 // Nothing overflows on a picture nobody would code.
620 assert_eq!(reserve(0, 0, 0), 0);
621 assert_eq!(reserve(u32::MAX, u32::MAX, u32::MAX), CACHE_CAP / 2);
622 }
623
624 /// The cap keeps the directory a cache and not a second copy of the
625 /// library: over it, the least recently used go until it fits, and a
626 /// half-written one is never taken (it is being written *now*) though its
627 /// bytes count towards what has to be freed.
628 #[test]
629 fn the_cache_evicts_its_oldest_until_it_fits() {
630 let dir = crate::scratch::Scratch::dir("proxy-sweep");
631 let write = |name: &str, len: usize, ago: u64| {
632 let path = dir.join(name);
633 std::fs::write(&path, vec![0u8; len]).expect("write");
634 // Stamped by hand: three files written in one millisecond have no
635 // order of their own, and the order is what is under test. `atime`
636 // is what `sweep` reads and `set_times` is the one door to it
637 // without a dependency.
638 let file = std::fs::File::options().write(true).open(&path).expect("open");
639 let when = std::time::SystemTime::now() - std::time::Duration::from_secs(ago);
640 file.set_times(std::fs::FileTimes::new().set_accessed(when).set_modified(when))
641 .expect("stamp");
642 path
643 };
644 let old = write("old.mp4", 400, 300);
645 let middle = write("middle.mp4", 400, 200);
646 let fresh = write("fresh.mp4", 400, 100);
647 let part = write("busy.mp4.part", 400, 400);
648
649 // 1600 bytes there, 900 allowed: the oldest two `.mp4`s go, and that is
650 // as far as it gets -- the part file is 400 of the remaining bytes and
651 // is not the sweep's to take.
652 let left = sweep(&dir, 900);
653 assert!(!old.exists(), "the oldest stand-in survived the sweep");
654 assert!(!middle.exists(), "the next oldest survived it");
655 assert!(fresh.exists(), "the freshest was taken");
656 assert!(part.exists(), "a half-written proxy was deleted under its writer");
657 assert_eq!(left, 800, "what is left is the fresh one and the part file");
658
659 // Under the cap, nothing is touched at all.
660 assert_eq!(sweep(&dir, 900), 800);
661 assert!(fresh.exists());
662 }
663
664 /// A song and a still are not films: they are answered `None` -- the same
665 /// answer a 1080p H.264 film gets -- rather than opened, failed on and
666 /// reported. The bug this pins said "NO PROXY for tone.wav" to a person who
667 /// had imported a song, and put "no proxy" on its library row.
668 ///
669 /// Real files, because the point is that nothing reads them: a demuxer
670 /// opened on a WAV is exactly what used to raise the refusal.
671 ///
672 /// ...and one **audio-only mp4**, which is the same class arriving the
673 /// other way: its name says video, so no extension can answer it and the
674 /// header is what tells. That one is a real, well-formed mp4 with an AAC
675 /// track and no video track at all -- a thing a person really does hand an
676 /// editor, and what a name-shaped gate walks straight past.
677 #[test]
678 fn a_song_and_a_still_are_never_stood_in_for() {
679 let dir = crate::scratch::Scratch::dir("proxy-not-a-film");
680 for name in ["tone.wav", "song.mp3", "track.mka", "still.png", "shot.jpg"] {
681 let file = dir.join(name);
682 std::fs::write(&file, b"not a film, and never read").expect("write");
683 let answer = generate_if_wanted(&file);
684 assert!(
685 matches!(answer, Ok(None)),
686 "{name} is not a film to stand in for: {:?}",
687 answer.err().map(|e| e.to_string())
688 );
689 assert_eq!(cached(&file), None, "{name} left nothing in the cache");
690 }
691
692 let silent_film = dir.join("audio-only.mp4");
693 write_audio_only_mp4(&silent_film);
694 // It really is an mp4 nothing here finds a picture in -- the demuxer
695 // says so by name, which is what makes the answer below a *class* and
696 // not a guess about the extension.
697 let opened = Demuxer::open(&silent_film);
698 let refusal = opened.err().expect("an mp4 with no picture will not open");
699 assert!(
700 crate::demux::NoVideoTrack::is_it(&refusal),
701 "not the no-picture answer: {refusal}"
702 );
703 let answer = generate_if_wanted(&silent_film);
704 assert!(
705 matches!(answer, Ok(None)),
706 "an audio-only mp4 is not a film to stand in for: {:?}",
707 answer.err().map(|e| e.to_string())
708 );
709 assert_eq!(cached(&silent_film), None);
710 }
711
712 /// A well-formed mp4 carrying one AAC track and no video track: what an
713 /// `ffmpeg -vn` or a music file in the wrong box looks like. Written with
714 /// the same crate the exporter's muxer uses, so it is the file that reader
715 /// really parses and not a hand-made approximation.
716 fn write_audio_only_mp4(path: &Path) {
717 use mp4::{
718 AacConfig, AudioObjectType, ChannelConfig, FourCC, MediaConfig, Mp4Config, Mp4Writer,
719 SampleFreqIndex, TrackConfig, TrackType,
720 };
721 let mut writer = Mp4Writer::write_start(
722 std::io::BufWriter::new(std::fs::File::create(path).expect("create")),
723 &Mp4Config {
724 major_brand: FourCC::from(*b"isom"),
725 minor_version: 512,
726 compatible_brands: vec![FourCC::from(*b"isom"), FourCC::from(*b"mp41")],
727 timescale: 44_100,
728 },
729 )
730 .expect("start an mp4");
731 writer
732 .add_track(&TrackConfig {
733 track_type: TrackType::Audio,
734 timescale: 44_100,
735 language: "und".to_string(),
736 media_conf: MediaConfig::AacConfig(AacConfig {
737 bitrate: 0,
738 profile: AudioObjectType::AacLowComplexity,
739 freq_index: SampleFreqIndex::Freq44100,
740 chan_conf: ChannelConfig::Stereo,
741 }),
742 })
743 .expect("an audio track");
744 writer.write_end().expect("finish the mp4");
745 }
746
747 /// The staleness rule *is* the name: touch the source and the old proxy is
748 /// unreachable rather than wrong.
749 #[test]
750 fn a_changed_source_names_another_proxy() {
751 let dir = crate::scratch::Scratch::dir("proxy-key");
752 let file = dir.join("a.mp4");
753 std::fs::write(&file, b"one").expect("write");
754 let first = path_for(&file).expect("a key");
755 assert_eq!(path_for(&file).as_ref(), Some(&first), "stable for a file");
756 // Same length, later time: a re-encode that happened to land on the
757 // same byte count is still another file.
758 std::fs::write(&file, b"two").expect("rewrite");
759 filetime_bump(&file);
760 assert_ne!(path_for(&file), Some(first), "touched: another name");
761 assert_eq!(cached(&file), None, "nothing written, nothing cached");
762 }
763
764 /// Turning one off deletes the stand-in and *only* the stand-in: the film
765 /// it was made from is what plays afterwards, so it had better still be
766 /// there.
767 #[test]
768 fn delete_takes_the_proxy_and_never_the_source() {
769 let dir = crate::scratch::Scratch::dir("proxy-delete");
770 let file = dir.join("a.mp4");
771 std::fs::write(&file, b"the film itself").expect("write");
772 let proxy = path_for(&file).expect("a key");
773 std::fs::create_dir_all(proxy.parent().expect("a cache dir")).expect("cache dir");
774 std::fs::write(&proxy, b"a stand-in").expect("write the proxy");
775 assert_eq!(cached(&file).as_ref(), Some(&proxy), "one in the cache");
776 assert_eq!(delete(&file).ok(), Some(true), "the stand-in went");
777 assert_eq!(cached(&file), None, "and is gone from the cache");
778 assert!(file.is_file(), "the film itself is untouched");
779 assert_eq!(delete(&file).ok(), Some(false), "nothing left to take");
780 assert!(file.is_file(), "still untouched");
781 }
782
783 /// A delete that *failed* is not a delete: the row above it draws itself
784 /// from this answer, and folding "could not" into "was not there" drew a
785 /// switch as OFF over a proxy still on the disk and still being played.
786 #[test]
787 fn a_delete_that_could_not_happen_says_so() {
788 let dir = crate::scratch::Scratch::dir("proxy-delete-refused");
789 let file = dir.join("a.mp4");
790 std::fs::write(&file, b"the film itself").expect("write");
791 let proxy = path_for(&file).expect("a key");
792 std::fs::create_dir_all(&proxy).expect("something an unlink will refuse");
793 // An unlink that fails for anything but "it was not there" -- a
794 // read-only cache directory in the field, a directory in this test --
795 // is a stand-in still on the disk, and it is answered as one.
796 let answer = delete(&file);
797 assert!(answer.is_err(), "a refused unlink reported as a delete");
798 assert!(proxy.is_dir(), "and what could not be deleted is still there");
799 std::fs::remove_dir(&proxy).expect("clean up");
800 // ...against the honest no-op, which *is* an off switch: nothing there.
801 assert_eq!(delete(&file).ok(), Some(false), "nothing to take");
802 assert!(file.is_file(), "the film itself, throughout");
803 }
804
805 /// The switch turned off outlives the window: the mark sits beside the
806 /// cache entry, so the sweep at the next launch answers `None` for that
807 /// film instead of re-encoding the stand-in somebody just deleted.
808 #[test]
809 fn a_film_switched_off_by_hand_stays_off() {
810 let dir = crate::scratch::Scratch::dir("proxy-off-mark");
811 let file = dir.join("a.mp4");
812 std::fs::write(&file, b"the film itself").expect("write");
813 assert!(!is_off(&file), "nothing has been switched off yet");
814 set_off(&file, true);
815 assert!(is_off(&file), "the mark is beside the cache entry");
816 // Which is what the sweep asks -- and it does not even read the header.
817 assert!(
818 matches!(generate_if_wanted(&file), Ok(None)),
819 "a switched-off film was started again"
820 );
821 set_off(&file, false);
822 assert!(!is_off(&file), "switched back on, the mark is gone");
823 // The mark is keyed like the stand-in: a source that changed is a
824 // different film and is asked again.
825 set_off(&file, true);
826 // Taken back by hand before the key moves: the scratch directory takes
827 // the film with it, and a mark left in the real cache would outlive the
828 // test that wrote it.
829 let stale = off_marker(&file).expect("a key");
830 std::fs::write(&file, b"re-encoded").expect("rewrite");
831 filetime_bump(&file);
832 assert!(!is_off(&file), "a changed source kept the old answer");
833 std::fs::remove_file(stale).expect("the old mark");
834 }
835
836 /// One encoder per film, in the engine and not only in the window that
837 /// draws the switch: the seat is taken for as long as the job lives, and a
838 /// second start for the same stand-in is refused rather than allowed to
839 /// unlink the first one's half-written file.
840 #[test]
841 fn one_encoder_per_stand_in() {
842 let dir = crate::scratch::Scratch::dir("proxy-one-encoder");
843 let out = dir.join("f00d.mp4");
844 let first = claim(&out).expect("the seat was free");
845 assert!(claim(&out).is_none(), "two encoders on one path");
846 // Another film is another seat.
847 let other = claim(&dir.join("beef.mp4")).expect("a different stand-in");
848 drop(first);
849 let again = claim(&out).expect("the seat came back with the job");
850 drop((again, other));
851 assert!(claim(&out).is_some(), "the seat was never given back");
852 }
853
854 /// `std::fs` has no set-mtime, and a rewrite inside the same nanosecond is
855 /// possible on a fast machine -- so the stamp is moved by hand through the
856 /// one door that does it without a dependency.
857 fn filetime_bump(path: &Path) {
858 let now = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
859 let file = std::fs::File::options()
860 .write(true)
861 .open(path)
862 .expect("open");
863 file.set_modified(now).expect("set mtime");
864 }
865}