forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

proxy.rs1102 lines, 50.1 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::sync::Arc;
36use std::sync::atomic::AtomicBool;
37use std::time::UNIX_EPOCH;
38
39use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta};
40use crate::export::{ExportHandle, ExportSettings, Format};
41use crate::project::{Clip, LaneKind, Project, Source, Speed};
42use crate::scale::FitPolicy;
43
44/// The long edge of a proxy picture, in samples: 1280, so a 4K source loses
45/// nine tenths of its samples and a 1080p one a little over half. Chosen as
46/// what a cut can be judged on at editing size, in the neighbourhood of every
47/// shipped proxy preset (Resolve's half-res, kdenlive's 640/1000-wide
48/// defaults).
49pub const LONG_EDGE: u32 = 1280;
50
51/// How much disk the stand-ins may hold between them, in bytes: 20 GB, which
52/// is one 4K feature film and most of a second (a 2h20 one measures
53/// ~11.5 GB at ~1.37 MB per second of film), or a dozen of an ordinary length.
54///
55/// A cap is not a nicety here. Proxies are written *without being asked for*,
56/// on import, [`AT_ONCE`] at a time -- so without one the answer to "how much
57/// of the disk does this take" is "all of it, eventually". Over the cap, the
58/// least recently used are deleted until it fits ([`sweep`]).
59///
60/// **What this really bounds.** A sweep runs before each new stand-in and
61/// leaves room for the ones about to be written ([`reserve`]), so what is
62/// *finished* is held to `CACHE_CAP - reserve` and the encodes in flight have
63/// the reserve to grow into. The directory therefore sits at about the cap
64/// rather than at the cap plus a film per encode, which is what it did when the
65/// sweep aimed at the bare number. It can still pass the cap where an encode
66/// outruns its own estimate -- a stand-in cannot be deleted while it is being
67/// written -- and the next sweep takes that back.
68pub const CACHE_CAP: u64 = 20 * 1024 * 1024 * 1024;
69
70/// How many stand-ins may be made at once. Two, not one per core: each is a
71/// whole film through a decoder and an encoder, and the hardware seat they
72/// queue on is a single one -- more of them at once is the same work done
73/// later, with the editor slower while it happens.
74///
75/// It lives here rather than in the front-end that does the fanning out because
76/// the cache's own arithmetic needs it ([`reserve`]): the number of encodes in
77/// flight is exactly how much room the sweep has to leave, and two places
78/// holding that number separately is one place for them to disagree.
79pub const AT_ONCE: usize = 2;
80
81/// What the hardware seat really writes against what it was asked for: 1.25,
82/// measured 2026-08-13 (8.3 Mbit/s out of a 6.6 Mbit/s request on radeonsi).
83/// Folded into [`reserve`] so the room left for an encode is the room it will
84/// actually take, not the room it was told to.
85const RATE_OVERSHOOT: f64 = 1.25;
86
87/// Bits per pixel per second a proxy is coded at, [`crate::export`]'s own rate
88/// rule at three times the number: every frame being an IDR means no frame
89/// borrows anything from its neighbours, so the same picture at the inter rate
90/// would be mush -- and mush is not something a cut can be judged on.
91const BITS_PER_PIXEL: f64 = 0.3;
92
93/// Whether this is a file worth standing in for: bigger than 1080p, or coded in
94/// something this machine decodes slowly even at 1080p. H.264 at or under 1080p
95/// plays natively and a proxy of it would cost time and buy nothing.
96///
97/// The size test reads the **coded** pair, not the displayed one
98/// ([`VideoMeta::coded_width`]): those differ wherever the file carries a
99/// display matrix or a non-square pixel, and a 1920x1080 H.264 phone clip with
100/// a 90-degree turn *displays* as 1080x1920 -- so judging the displayed pair
101/// called a clip that plays natively proxy-worthy and put a whole film through
102/// a decoder and an encoder to stand in for something already at speed. What a
103/// decoder is asked to chew through is the stored raster, so the stored raster
104/// is what this is about; the codec test is not a size question and is
105/// unchanged.
106pub fn wanted(meta: &VideoMeta) -> bool {
107 meta.coded_width > 1920
108 || meta.coded_height > 1080
109 || matches!(meta.codec, Codec::Hevc | Codec::Av1)
110}
111
112/// The picture a proxy of `meta` is coded at: aspect kept, long edge at most
113/// [`LONG_EDGE`], both axes even because 4:2:0 has no half chroma samples. A
114/// source already that small is coded at its own size (rounded down to even),
115/// which is what makes [`generate`] safe to ask for on anything at all.
116pub fn size_for(meta: &VideoMeta) -> (u32, u32) {
117 let long = meta.width.max(meta.height);
118 let scale = match long > LONG_EDGE {
119 true => f64::from(LONG_EDGE) / f64::from(long),
120 false => 1.0,
121 };
122 let even = |n: u32| (((f64::from(n) * scale).round() as u32) & !1).max(2);
123 (even(meta.width), even(meta.height))
124}
125
126/// Where the proxy of `source` lives, whether or not it has been made yet.
127///
128/// The name is one hash of the source's canonical path, its length **and** its
129/// modification time, so an original that changed at all is a different name
130/// and its old proxy is simply never looked at again -- the staleness check is
131/// the lookup. `None` where the file cannot be stat'd or the machine has no
132/// cache directory at all, which is a source that gets no proxy rather than one
133/// littering the working directory.
134///
135/// A re-encoded source therefore leaves its old stand-in behind, and a proxy of
136/// a feature film is gigabytes: [`sweep`] is what keeps that from being the
137/// whole disk, and it runs before every new one is written.
138pub fn path_for(source: &Path) -> Option<PathBuf> {
139 let meta = std::fs::metadata(source).ok()?;
140 let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) {
141 Ok(d) => (d.as_secs() as i128, d.subsec_nanos()),
142 Err(e) => (
143 -(e.duration().as_secs() as i128),
144 e.duration().subsec_nanos(),
145 ),
146 };
147 let canonical = std::fs::canonicalize(source).unwrap_or_else(|_| source.to_path_buf());
148 let mut bytes = canonical.as_os_str().as_encoded_bytes().to_vec();
149 bytes.extend_from_slice(&meta.len().to_le_bytes());
150 bytes.extend_from_slice(&mtime.0.to_le_bytes());
151 bytes.extend_from_slice(&mtime.1.to_le_bytes());
152 let dir = crate::demux::cache_dir(
153 crate::envcfg::var_os("XDG_CACHE_HOME"),
154 std::env::var_os("HOME"),
155 "proxies",
156 )?;
157 Some(dir.join(format!("{:016x}.mp4", crate::demux::fnv1a(&bytes))))
158}
159
160/// How much of [`CACHE_CAP`] the sweep leaves free for the stand-ins that are
161/// about to be written into the directory: [`AT_ONCE`] of them, each about the
162/// size of the one being started now.
163///
164/// The estimate is the file's own arithmetic and not a guess: the picture is
165/// coded at [`BITS_PER_PIXEL`] bits per pixel per second and the frame rate
166/// cancels out, so it is `width * height * frames * bpp / 8` -- times
167/// [`RATE_OVERSHOOT`], because the hardware seat writes over the rate it is
168/// asked for.
169///
170/// Held to half the cap, whatever that comes to. A single 4K feature estimates
171/// at over the whole cap, and reserving that would empty the cache to make room
172/// for one film -- deleting stand-ins that are in use, for a bound that cannot
173/// be met anyway while two of them are being written. Half is the compromise:
174/// what is *finished* stays under half the cap, so the two in flight have the
175/// other half to grow into before the disk carries more than [`CACHE_CAP`].
176fn reserve(width: u32, height: u32, frames: u32) -> u64 {
177 let bytes = f64::from(width) * f64::from(height) * f64::from(frames) * BITS_PER_PIXEL / 8.0;
178 ((bytes * RATE_OVERSHOOT) as u64)
179 .saturating_mul(AT_ONCE as u64)
180 .min(CACHE_CAP / 2)
181}
182
183/// Deletes least-recently-used stand-ins until the directory holds at most
184/// `cap` bytes, and reports what it holds afterwards.
185///
186/// Run before a new one is written, which is the only moment this directory
187/// grows. Nothing else evicts, and nothing else can: a proxy is derived, so
188/// deleting one costs the time to make it again and no more -- which is exactly
189/// what makes a cap safe to apply behind the user's back where an eviction of
190/// anything *authored* would not be.
191///
192/// Least recently *used* is read off the access time, with the modification
193/// time where a filesystem reports none. On a `relatime` mount -- which is the
194/// default, and is what this machine's `/home` is -- an access time moves at
195/// most once a day, so this is a daily-granularity LRU rather than an exact
196/// one. That is the right accuracy for a thing whose eviction costs a
197/// re-encode, and it is why the order is by *time* and not by a hit counter
198/// nothing would persist.
199///
200/// A `.part` is never deleted -- it is being written right now, by this process
201/// or another -- but its bytes *are* counted: they are on the disk, and a
202/// half-written 11 GB proxy is exactly when the finished ones should make room.
203fn sweep(dir: &Path, cap: u64) -> u64 {
204 let Ok(entries) = std::fs::read_dir(dir) else {
205 return 0;
206 };
207 let mut total = 0u64;
208 let mut evictable: Vec<(std::time::SystemTime, u64, PathBuf)> = Vec::new();
209 for entry in entries.flatten() {
210 let Ok(meta) = entry.metadata() else { continue };
211 if !meta.is_file() {
212 continue;
213 }
214 total += meta.len();
215 let path = entry.path();
216 if path.extension().is_some_and(|e| e == "mp4") {
217 let used = meta.accessed().or_else(|_| meta.modified());
218 evictable.push((used.unwrap_or(UNIX_EPOCH), meta.len(), path));
219 }
220 }
221 if total <= cap {
222 return total;
223 }
224 evictable.sort_by_key(|(used, ..)| *used);
225 for (_, len, path) in evictable {
226 if total <= cap {
227 break;
228 }
229 if std::fs::remove_file(&path).is_ok() {
230 total -= len;
231 eprintln!("proxy cache: evicted {}", path.display());
232 }
233 }
234 total
235}
236
237/// Deletes every `.part` in `dir`: the leftover of an encoder that never got
238/// to unlink its own half-written file, because the process holding it was
239/// killed rather than let finish or cancel cleanly.
240///
241/// Unlike the one removal in [`started`], which clears only *this film's* own
242/// `.part` right before a new encode of it starts, this clears everyone
243/// else's too -- which is safe to do only because nothing in this process has
244/// claimed a `.part` yet at the point it runs ([`sweep_stale_parts`]).
245fn sweep_parts(dir: &Path) {
246 let Ok(entries) = std::fs::read_dir(dir) else {
247 return;
248 };
249 for entry in entries.flatten() {
250 let path = entry.path();
251 if path.extension().is_some_and(|e| e == "part") && std::fs::remove_file(&path).is_ok() {
252 eprintln!("proxy cache: swept stale {}", path.display());
253 }
254 }
255}
256
257/// Run once, at launch, ahead of anything that could claim a stand-in for
258/// itself: clears every orphan `.part` a killed editor left in the proxy
259/// cache. "Stale" needs no age check here -- at launch [`IN_FLIGHT`] is empty
260/// by construction, so *every* `.part` on disk belongs to nobody still
261/// running. A no-op where the machine has no cache directory at all.
262pub fn sweep_stale_parts() {
263 if let Some(dir) = crate::demux::cache_dir(
264 crate::envcfg::var_os("XDG_CACHE_HOME"),
265 std::env::var_os("HOME"),
266 "proxies",
267 ) {
268 sweep_parts(&dir);
269 }
270}
271
272/// The proxy of `source` if one has already been made, `None` otherwise. The
273/// answer a session asks at open: a hit costs one `stat`.
274pub fn cached(source: &Path) -> Option<PathBuf> {
275 path_for(source).filter(|p| p.is_file())
276}
277
278/// Deletes the stand-in of `source`, if there is one, and says whether a file
279/// went. The one *by hand* eviction: [`sweep`] takes the oldest to stay under a
280/// cap, this takes the one that was asked for.
281///
282/// The source itself is never touched -- what is deleted is [`path_for`]'s
283/// answer, a name in the cache directory and nothing else -- and deleting one
284/// under a session that is playing off it costs a re-open: [`cached`] stats,
285/// finds nothing, and the film itself is what plays from the next span on
286/// ([`crate::PlaybackSession::picture_path`]).
287/// Three answers and not two, because they are three different rows: `Ok(true)`
288/// is a stand-in that went, `Ok(false)` is one that was never there (a no-op,
289/// and the switch is honestly off afterwards), and `Err` is a file that is
290/// **still on the disk** -- a read-only cache directory, a filesystem gone
291/// away. A caller that folded the last two together drew the row as OFF over a
292/// proxy [`cached`] went on handing to playback.
293pub fn delete(source: &Path) -> std::io::Result<bool> {
294 let Some(path) = path_for(source) else {
295 return Ok(false);
296 };
297 match std::fs::remove_file(&path) {
298 Ok(()) => {
299 eprintln!("proxy cache: deleted {}", path.display());
300 Ok(true)
301 }
302 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
303 Err(e) => Err(e),
304 }
305}
306
307/// The mark beside a cache entry that says its film was switched *off* by hand,
308/// and the one thing about a stand-in that outlives the window: without it the
309/// next launch's sweep re-encodes the very proxy somebody just turned off.
310///
311/// Keyed exactly as the stand-in itself is ([`path_for`]) and living beside it,
312/// which is what makes it answer for a film that is in no project at all -- the
313/// `.edith` file knows only the sources of one timeline, and the switch is on a
314/// library row that may belong to none. Derived and disposable like everything
315/// else in this directory: a re-encoded source names another key and is asked
316/// again, and deleting the cache forgets the choice, which costs one click.
317///
318/// corner-cut: the choice therefore does not survive a cache wipe or an edit to
319/// the source file. Upgrade path is a list in the `.edith`, which needs the
320/// project format to carry per-source flags.
321fn off_marker(source: &Path) -> Option<PathBuf> {
322 Some(path_for(source)?.with_extension("off"))
323}
324
325/// Whether this film's stand-in was switched off by hand ([`off_marker`]).
326pub fn is_off(source: &Path) -> bool {
327 off_marker(source).is_some_and(|p| p.exists())
328}
329
330/// Writes or clears that mark. Best effort: a cache directory that cannot be
331/// written is a choice that does not survive the session, never a refused
332/// click.
333pub fn set_off(source: &Path, off: bool) {
334 let Some(marker) = off_marker(source) else {
335 return;
336 };
337 match off {
338 true => {
339 if let Some(dir) = marker.parent() {
340 let _ = std::fs::create_dir_all(dir);
341 }
342 let _ = std::fs::write(&marker, b"");
343 }
344 false => {
345 let _ = std::fs::remove_file(&marker);
346 }
347 }
348}
349
350/// The stand-ins being written *right now*, one entry per live encoder, held
351/// for the life of the [`Job`].
352///
353/// The one-encoder-per-film rule lives here rather than only in the window that
354/// draws the switch: two starts for one film race over one `.part` path, and
355/// the second unlinks the first's file and leaves it writing into an orphaned
356/// inode with nothing left holding its handle -- an encode nobody can stop,
357/// which finishes minutes later and puts back a proxy somebody had switched
358/// off. A guarantee that lives in the caller is a guarantee every future caller
359/// has to re-make.
360static IN_FLIGHT: std::sync::Mutex<Vec<PathBuf>> = std::sync::Mutex::new(Vec::new());
361
362/// A held seat in [`IN_FLIGHT`], given up when the job that owns it is dropped.
363struct Claim(PathBuf);
364
365impl Drop for Claim {
366 fn drop(&mut self) {
367 let mut held = IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner());
368 if let Some(i) = held.iter().position(|p| *p == self.0) {
369 held.swap_remove(i);
370 }
371 }
372}
373
374/// Takes the seat for `out`, or `None` where an encoder already has it.
375fn claim(out: &Path) -> Option<Claim> {
376 let mut held = IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner());
377 match held.iter().any(|p| p == out) {
378 true => None,
379 false => {
380 held.push(out.to_path_buf());
381 Some(Claim(out.to_path_buf()))
382 }
383 }
384}
385
386/// A proxy being made -- or one that was already there, which is the same thing
387/// to whoever is waiting for a path.
388///
389/// Poll [`progress`](Job::progress) while [`is_finished`](Job::is_finished) is
390/// false and take the [`outcome`](Job::outcome) when it flips, exactly as an
391/// export is polled. Dropping the job does not stop the work;
392/// [`cancel`](Job::cancel) does.
393pub struct Job {
394 out: PathBuf,
395 /// `None` for a cache hit: there was nothing to run.
396 handle: Option<ExportHandle>,
397 /// The seat this encoder holds ([`IN_FLIGHT`]), given back when the job
398 /// goes. `None` for a cache hit, which codes nothing.
399 _claim: Option<Claim>,
400}
401
402impl Job {
403 /// Fraction of the proxy's pictures written, `0.0..=1.0`. A cache hit is
404 /// done.
405 ///
406 /// The band an export's bar reserves for its sound is taken back out: a
407 /// proxy has no sound, so that band is crossed in the first instant and
408 /// showing it would be five percent no frame earned.
409 pub fn progress(&self) -> f32 {
410 let Some(handle) = &self.handle else {
411 return 1.0;
412 };
413 let band = crate::export::AUDIO_BAND as f32 / crate::export::PROGRESS_SCALE as f32;
414 ((handle.progress() - band) / (1.0 - band)).clamp(0.0, 1.0)
415 }
416
417 /// What is coding this proxy -- the hardware seat or the software one, as
418 /// the worker really opened it. `None` before the encoder is open, and for
419 /// a cache hit, which coded nothing.
420 pub fn encoder(&self) -> Option<String> {
421 self.handle.as_ref()?.encoders()
422 }
423
424 /// Asks the worker to stop at its next frame and leave no file behind. The
425 /// outcome then reports the cancellation as an error.
426 pub fn cancel(&self) {
427 if let Some(handle) = &self.handle {
428 handle.cancel();
429 }
430 }
431
432 pub fn is_finished(&self) -> bool {
433 self.handle.as_ref().is_none_or(ExportHandle::is_finished)
434 }
435
436 /// The proxy's path once it is written, once -- taken out of the job, so a
437 /// caller that already took it sees `None`. `None` while it is still being
438 /// made.
439 pub fn outcome(&self) -> Option<crate::Result<PathBuf>> {
440 let Some(handle) = &self.handle else {
441 return Some(Ok(self.out.clone()));
442 };
443 handle.result().map(|r| r.map(|()| self.out.clone()))
444 }
445
446 /// Where the proxy will be, whether or not it is there yet -- what a caller
447 /// names in a log line while the job runs.
448 pub fn path(&self) -> &Path {
449 &self.out
450 }
451}
452
453/// Starts making the proxy of `source`, or hands back the one already in the
454/// cache. Errors are the ones that happen before a worker exists -- a file with
455/// no picture in it, nowhere to put a cache -- and everything after them comes
456/// back through [`Job::outcome`], so a caller has two places to look and not
457/// twenty.
458pub fn generate(source: &Path) -> crate::Result<Job> {
459 // Nothing here has anything to cancel a header read with -- a flag that is
460 // never set is the same as the read never checking one at all.
461 let uncancelled = Arc::new(AtomicBool::new(false));
462 Ok(started(source, |_| true, &uncancelled)?.expect("nothing was filtered out"))
463}
464
465/// The same, for a file that is worth standing in for and nobody else
466/// ([`wanted`]) -- `Ok(None)` is a film this machine already cuts at speed.
467///
468/// The header is read *once* for both questions: on a Matroska that read is the
469/// cluster walk, so asking `wanted` and then `generate` separately would pay
470/// for it twice.
471///
472/// A file with no picture in it is not a film and is answered `Ok(None)`, the
473/// same answer a 1080p H.264 film gets -- it is not a failure, and reporting it
474/// as one put "NO PROXY for tone.wav" in front of somebody who had imported a
475/// song.
476///
477/// Twice, because there are two ways to know. A name this engine already reads
478/// as sound or as a still is answered before anything is opened, which is the
479/// cheap half. The other half is the honest one: **an audio-only `.mp4`, `.mkv`
480/// or `.mov` is a video container with no video track in it**, and only its
481/// header says so -- so the demuxer's own [`NoVideoTrack`] answer is taken here
482/// as the same quiet `None`. A film that *has* a picture and will not open is a
483/// different thing and stays loud.
484///
485/// `cancel` is polled through the whole Asked phase, the same flag the caller
486/// hands the [`Job`] once one exists: a click to stop this file's stand-in
487/// while the header is still being read (a Matroska's is a cluster walk, not
488/// a stat) used to have nothing to set, since there was no [`Job`] yet to
489/// [`cancel`](Job::cancel) -- so the read ran to completion regardless, and a
490/// stop landed only once an encoder was already open. Set before this is
491/// called or at any point while it runs, it is read at the door and again
492/// wrapped around the header read itself ([`crate::demux::with_cancel`]), so a
493/// cancelled read unwinds at its next element instead of finishing.
494pub fn generate_if_wanted(source: &Path, cancel: &Arc<AtomicBool>) -> crate::Result<Option<Job>> {
495 if crate::is_audio(source) || crate::is_image(source) {
496 return Ok(None);
497 }
498 // Switched off by hand, in this session or in one last week ([`set_off`]):
499 // the sweep that runs at every launch comes through here, and without this
500 // it re-encodes the stand-in somebody just turned off. Answered before the
501 // header is read, so a library of switched-off films costs no disk at all.
502 if is_off(source) {
503 return Ok(None);
504 }
505 match started(source, wanted, cancel) {
506 Err(e) if NoVideoTrack::is_it(&e) => Ok(None),
507 other => other,
508 }
509}
510
511/// Both doors: the cache is looked at, the header is read once, and `only_if`
512/// decides off that header whether there is anything to do.
513///
514/// `cancel` is checked the moment the seat is claimed and again around the
515/// header read: a cancel that lands before either point is answered without
516/// spending a read nobody wants the result of, with [`crate::demux::is_cancelled`]
517/// true of the error -- and the seat this claimed is given back the same way
518/// a cancelled encode's is, [`Claim`]'s own `Drop`, run on the early return
519/// exactly as it is on the ordinary one.
520fn started(
521 source: &Path,
522 only_if: fn(&VideoMeta) -> bool,
523 cancel: &Arc<AtomicBool>,
524) -> crate::Result<Option<Job>> {
525 // A film that is not on the disk (moved, drive unplugged) has nothing to
526 // make a stand-in of: that is the media list's "missing" badge, not a failure here.
527 if std::fs::metadata(source).is_err() {
528 return Ok(None);
529 }
530 let out = path_for(source).ok_or("no cache directory to keep a proxy in")?;
531 if out.is_file() {
532 return Ok(Some(Job {
533 out,
534 handle: None,
535 _claim: None,
536 }));
537 }
538 // One encoder per film, taken before the header is read and given back when
539 // the job is dropped ([`IN_FLIGHT`]): the second start would unlink the
540 // first's `.part` below and orphan an encode nothing can stop.
541 let claim = claim(&out).ok_or("a stand-in for this film is already being made")?;
542 // A cancel that landed before this ran at all, or while it queued behind
543 // another film's seat: answered here, before a byte of the header is read,
544 // rather than starting a read that would only be thrown away.
545 if cancel.load(std::sync::atomic::Ordering::Acquire) {
546 return Err(crate::demux::cancelled_read_error());
547 }
548 // The source's own header: its rate and length are the proxy's (a stand-in
549 // that ran at another rate or stopped early would put every cut on another
550 // frame), and only its picture size changes. Wrapped in the same cancel an
551 // encode itself is polled with, so a stop asked for mid-walk unwinds the
552 // walk instead of waiting it out.
553 let (meta, _) = crate::demux::with_cancel(cancel, || Demuxer::open(source))?;
554 if !only_if(&meta) {
555 return Ok(None);
556 }
557 let (width, height) = size_for(&meta);
558 if let Some(dir) = out.parent() {
559 std::fs::create_dir_all(dir)?;
560 // Before the write, which is the only thing that makes this directory
561 // bigger -- and with room left for what is *about* to be written into
562 // it: sweeping to the bare cap left the finished ones filling it and
563 // then [`AT_ONCE`] encodes adding gigabytes on top, which is a cap that
564 // is over by a whole film's worth by construction ([`reserve`]).
565 sweep(
566 dir,
567 CACHE_CAP.saturating_sub(reserve(width, height, meta.frame_count)),
568 );
569 }
570 // What a killed editor left behind: the export worker deletes its own part
571 // file when it is cancelled or fails, but nothing can delete it for a
572 // process that was killed -- and a proxy of a feature film is hundreds of
573 // megabytes of cache nothing would ever look at again. The key is the same,
574 // so this is that same film's own leftover and not somebody else's.
575 let mut part = out.clone().into_os_string();
576 part.push(".part");
577 let _ = std::fs::remove_file(PathBuf::from(part));
578 // One video lane, one clip, the whole file -- and *no* audio lane, which is
579 // what makes the proxy picture-only: the export walk codes the lanes it is
580 // given and there is no sound among them.
581 let clip = Clip {
582 speed_keys: Vec::new(),
583 reversed: false,
584 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
585 angle: Default::default(),
586 fade_in: 0,
587 fade_out: 0,
588 transition_out: 0,
589 transition_kind: Default::default(),
590 visualizer: 0,
591 viz_paint: 0,
592 gain_db: 0.0,
593 gain_keys: Vec::new(),
594 pan: 0,
595 transform_keys: Vec::new(),
596 opacity_keys: Vec::new(),
597 color_keys: Vec::new(),
598 effects: Vec::new(),
599 start: 0,
600 in_frame: 0,
601 out_frame: meta.frame_count.max(1),
602 source: 0,
603 link: None,
604 eq: None,
605 color: None,
606 transform: None,
607 fit: FitPolicy::default(),
608 speed: Speed::NORMAL,
609 pitch: 0,
610 };
611 let project = Project::from_parts(
612 vec![Source::new(source, 0)],
613 vec![(LaneKind::Video, vec![clip])],
614 Vec::new(),
615 Vec::new(),
616 Vec::new(),
617 )?;
618 let bitrate = (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64;
619 let handle = crate::export::start(
620 project,
621 VideoMeta {
622 width,
623 height,
624 ..meta
625 },
626 &out,
627 &ExportSettings {
628 format: Format::Mp4,
629 // The whole point: every frame its own random-access point.
630 intra_only: true,
631 // ...and the film's own colour, carried rather than converted: the
632 // screen tone-maps the stand-in exactly as it tone-maps the film,
633 // live and at preview size.
634 keep_source_colour: true,
635 bitrate: Some(bitrate),
636 ..Default::default()
637 },
638 // A stand-in keeps its film's own rate: the override is the
639 // timeline's affair, not the proxy's.
640 None,
641 );
642 Ok(Some(Job {
643 out,
644 handle: Some(handle),
645 _claim: Some(claim),
646 }))
647}
648
649#[cfg(test)]
650mod tests {
651 use super::*;
652 use crate::colorspace::ColorDescription;
653 use crate::demux::Rotation;
654
655 /// A cancel flag no test in this file is exercising, for the calls that
656 /// have nothing to cancel.
657 fn uncancelled() -> Arc<AtomicBool> {
658 Arc::new(AtomicBool::new(false))
659 }
660
661 /// A meta as no container wrote it: square pixels, no turn, the displayed
662 /// pair the same pair the samples are stored at.
663 fn meta(coded_width: u32, coded_height: u32, codec: Codec) -> VideoMeta {
664 turned_meta(coded_width, coded_height, Rotation::None, codec)
665 }
666
667 /// The same, but with the display pair built the way `demux` builds it for
668 /// a file carrying a display matrix: the stored pair with its axes swapped
669 /// where the turn says they are. A phone clip shot 1920x1080 and turned to
670 /// portrait is the case that matters -- it *displays* 1080x1920, and a
671 /// predicate that reads the displayed pair calls it a tall 1080p film.
672 fn turned_meta(
673 coded_width: u32,
674 coded_height: u32,
675 rotation: Rotation,
676 codec: Codec,
677 ) -> VideoMeta {
678 let (width, height) = match rotation.swaps_axes() {
679 true => (coded_height, coded_width),
680 false => (coded_width, coded_height),
681 };
682 VideoMeta {
683 width,
684 height,
685 frame_rate: 24.0,
686 frame_count: 240,
687 codec,
688 color: ColorDescription::default(),
689 matrix_assumed: false,
690 rotation,
691 coded_width,
692 coded_height,
693 pixel_aspect: crate::demux::PixelAspect::SQUARE,
694 }
695 }
696
697 /// What a proxy is *for*: the files this machine cannot play at speed.
698 #[test]
699 fn only_the_files_that_need_one_get_one() {
700 assert!(wanted(&meta(3840, 2160, Codec::Hevc)), "4K HEVC");
701 assert!(wanted(&meta(3840, 2160, Codec::H264)), "4K H.264");
702 assert!(wanted(&meta(1920, 1080, Codec::Hevc)), "1080p HEVC");
703 assert!(wanted(&meta(1920, 1080, Codec::Av1)), "1080p AV1");
704 assert!(
705 !wanted(&meta(1920, 1080, Codec::H264)),
706 "1080p H.264 plays natively"
707 );
708 assert!(!wanted(&meta(1280, 720, Codec::H264)), "720p H.264");
709
710 // A turn must not turn a native file into a proxy job. What a decoder
711 // is handed is the stored raster -- 1920x1080 of H.264 -- and that is
712 // what plays at speed; the 1080x1920 the file *displays* is a metadata
713 // turn, not a bigger picture. Judged on the displayed pair this file
714 // was handed to a background decoder and an encoder to be stood in for,
715 // which is a whole film of CPU and cache for a clip already at rate.
716 let phone = turned_meta(1920, 1080, Rotation::Cw90, Codec::H264);
717 assert_eq!(
718 (phone.coded_width, phone.coded_height),
719 (1920, 1080),
720 "the samples are stored landscape"
721 );
722 assert_eq!(
723 (phone.width, phone.height),
724 (1080, 1920),
725 "and the file only claims to display portrait"
726 );
727 assert!(
728 !wanted(&phone),
729 "a rotated 1080p H.264 clip plays natively: the turn is not height"
730 );
731 // ...while the same turn on a codec this machine decodes slowly is
732 // still wanted, and so is a genuinely tall stored raster: the two
733 // tests are about the stored pair, not about `rotation` itself.
734 assert!(
735 wanted(&turned_meta(1920, 1080, Rotation::Cw90, Codec::Hevc)),
736 "1080p HEVC is wanted whatever turn it carries"
737 );
738 assert!(
739 wanted(&turned_meta(1080, 1920, Rotation::None, Codec::H264)),
740 "a stored 1080x1920 raster is a big one, turn or not"
741 );
742 }
743
744 /// Aspect kept, long edge capped, both axes even -- and a small source left
745 /// alone rather than blown up.
746 #[test]
747 fn a_proxy_is_the_same_shape_at_a_smaller_size() {
748 assert_eq!(size_for(&meta(3840, 2160, Codec::Hevc)), (1280, 720));
749 assert_eq!(size_for(&meta(1920, 1080, Codec::Hevc)), (1280, 720));
750 // A portrait source is capped on *its* long edge, which is the height.
751 assert_eq!(size_for(&meta(1080, 1920, Codec::Hevc)), (720, 1280));
752 // 1916x1080 (a real film's cropped width): even both ways, and the
753 // aspect it really has rather than the 16:9 it nearly has.
754 let (w, h) = size_for(&meta(1916, 1080, Codec::H264));
755 assert_eq!((w, h), (1280, 722), "cropped-width 1080p");
756 assert_eq!(w % 2, 0);
757 assert_eq!(h % 2, 0);
758 assert!(
759 (f64::from(w) / f64::from(h) - 1916. / 1080.).abs() < 0.005,
760 "{w}x{h} is the source's shape"
761 );
762 assert_eq!(
763 size_for(&meta(640, 360, Codec::H264)),
764 (640, 360),
765 "already small: its own size, never upscaled"
766 );
767 assert_eq!(size_for(&meta(1, 1, Codec::H264)), (2, 2), "never zero");
768 }
769
770 /// What the sweep leaves free for the encodes that are about to run: two
771 /// of them, at what this one is really going to cost. Without it the cap
772 /// was soft by a whole film per encode -- 20 GB of finished stand-ins and
773 /// then two 4K ones writing gigabytes on top of it.
774 #[test]
775 fn the_cap_keeps_room_for_what_is_about_to_be_written() {
776 // A 2h20 4K film, at the size a stand-in of it is coded: 1280x536 for
777 // 201536 frames. Its own arithmetic says ~2.6 GB, and two of them is
778 // over the cap's half, so the reserve is that half.
779 let big = reserve(1280, 536, 201_536);
780 assert_eq!(big, CACHE_CAP / 2, "a feature film asks for more than half");
781 // A short clip asks for what it costs and no more: 1280x720 for 300
782 // frames is 1280*720*300*0.3/8 * 1.25 * 2 encodes.
783 let small = reserve(1280, 720, 300);
784 let one = 1280.0 * 720.0 * 300.0 * BITS_PER_PIXEL / 8.0 * RATE_OVERSHOOT;
785 assert_eq!(small, one as u64 * AT_ONCE as u64);
786 assert!(small < CACHE_CAP / 2, "and it is nowhere near the ceiling");
787 // The reserve is what a sweep aims below, so what is *finished* is held
788 // under the cap by at least the room the encodes will take.
789 assert!(CACHE_CAP.saturating_sub(big) <= CACHE_CAP / 2);
790 // Nothing overflows on a picture nobody would code.
791 assert_eq!(reserve(0, 0, 0), 0);
792 assert_eq!(reserve(u32::MAX, u32::MAX, u32::MAX), CACHE_CAP / 2);
793 }
794
795 /// The cap keeps the directory a cache and not a second copy of the
796 /// library: over it, the least recently used go until it fits, and a
797 /// half-written one is never taken (it is being written *now*) though its
798 /// bytes count towards what has to be freed.
799 #[test]
800 fn the_cache_evicts_its_oldest_until_it_fits() {
801 let dir = crate::scratch::Scratch::dir("proxy-sweep");
802 let write = |name: &str, len: usize, ago: u64| {
803 let path = dir.join(name);
804 std::fs::write(&path, vec![0u8; len]).expect("write");
805 // Stamped by hand: three files written in one millisecond have no
806 // order of their own, and the order is what is under test. `atime`
807 // is what `sweep` reads and `set_times` is the one door to it
808 // without a dependency.
809 let file = std::fs::File::options()
810 .write(true)
811 .open(&path)
812 .expect("open");
813 let when = std::time::SystemTime::now() - std::time::Duration::from_secs(ago);
814 file.set_times(
815 std::fs::FileTimes::new()
816 .set_accessed(when)
817 .set_modified(when),
818 )
819 .expect("stamp");
820 path
821 };
822 let old = write("old.mp4", 400, 300);
823 let middle = write("middle.mp4", 400, 200);
824 let fresh = write("fresh.mp4", 400, 100);
825 let part = write("busy.mp4.part", 400, 400);
826
827 // 1600 bytes there, 900 allowed: the oldest two `.mp4`s go, and that is
828 // as far as it gets -- the part file is 400 of the remaining bytes and
829 // is not the sweep's to take.
830 let left = sweep(&dir, 900);
831 assert!(!old.exists(), "the oldest stand-in survived the sweep");
832 assert!(!middle.exists(), "the next oldest survived it");
833 assert!(fresh.exists(), "the freshest was taken");
834 assert!(
835 part.exists(),
836 "a half-written proxy was deleted under its writer"
837 );
838 assert_eq!(left, 800, "what is left is the fresh one and the part file");
839
840 // Under the cap, nothing is touched at all.
841 assert_eq!(sweep(&dir, 900), 800);
842 assert!(fresh.exists());
843 }
844
845 /// What a killed editor leaves behind piles up as `.part` files nothing
846 /// ever revisits (nothing but the one film's own next start clears its
847 /// own, [`started`]) -- the launch-time sweep takes every one of them,
848 /// and leaves the finished stand-ins beside them alone.
849 #[test]
850 fn the_launch_sweep_takes_every_orphan_part() {
851 let dir = crate::scratch::Scratch::dir("proxy-part-sweep");
852 let write = |name: &str| {
853 let path = dir.join(name);
854 std::fs::write(&path, b"orphaned mid-encode").expect("write");
855 path
856 };
857 let orphan_a = write("aaaa.mp4.part");
858 let orphan_b = write("bbbb.mp4.part");
859 let finished = write("cccc.mp4");
860
861 sweep_parts(&dir);
862
863 assert!(!orphan_a.exists(), "one orphan part survived the sweep");
864 assert!(!orphan_b.exists(), "the other orphan part survived it");
865 assert!(finished.exists(), "a finished stand-in was swept too");
866 }
867
868 /// A song and a still are not films: they are answered `None` -- the same
869 /// answer a 1080p H.264 film gets -- rather than opened, failed on and
870 /// reported. The bug this pins said "NO PROXY for tone.wav" to a person who
871 /// had imported a song, and put "no proxy" on its library row.
872 ///
873 /// Real files, because the point is that nothing reads them: a demuxer
874 /// opened on a WAV is exactly what used to raise the refusal.
875 ///
876 /// ...and one **audio-only mp4**, which is the same class arriving the
877 /// other way: its name says video, so no extension can answer it and the
878 /// header is what tells. That one is a real, well-formed mp4 with an AAC
879 /// track and no video track at all -- a thing a person really does hand an
880 /// editor, and what a name-shaped gate walks straight past.
881 #[test]
882 fn a_song_and_a_still_are_never_stood_in_for() {
883 let dir = crate::scratch::Scratch::dir("proxy-not-a-film");
884 for name in ["tone.wav", "song.mp3", "track.mka", "still.png", "shot.jpg"] {
885 let file = dir.join(name);
886 std::fs::write(&file, b"not a film, and never read").expect("write");
887 let answer = generate_if_wanted(&file, &uncancelled());
888 assert!(
889 matches!(answer, Ok(None)),
890 "{name} is not a film to stand in for: {:?}",
891 answer.err().map(|e| e.to_string())
892 );
893 assert_eq!(cached(&file), None, "{name} left nothing in the cache");
894 }
895
896 let silent_film = dir.join("audio-only.mp4");
897 write_audio_only_mp4(&silent_film);
898 // It really is an mp4 nothing here finds a picture in -- the demuxer
899 // says so by name, which is what makes the answer below a *class* and
900 // not a guess about the extension.
901 let opened = Demuxer::open(&silent_film);
902 let refusal = opened.err().expect("an mp4 with no picture will not open");
903 assert!(
904 crate::demux::NoVideoTrack::is_it(&refusal),
905 "not the no-picture answer: {refusal}"
906 );
907 let answer = generate_if_wanted(&silent_film, &uncancelled());
908 assert!(
909 matches!(answer, Ok(None)),
910 "an audio-only mp4 is not a film to stand in for: {:?}",
911 answer.err().map(|e| e.to_string())
912 );
913 assert_eq!(cached(&silent_film), None);
914 }
915
916 /// A well-formed mp4 carrying one AAC track and no video track: what an
917 /// `ffmpeg -vn` or a music file in the wrong box looks like. Written with
918 /// the same muxer the exporter uses, so it is the file that reader really
919 /// parses and not a hand-made approximation.
920 fn write_audio_only_mp4(path: &Path) {
921 use ec_core::{
922 AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, MediaParameters,
923 Muxer as _, Packet, StreamInfo, TimeBase,
924 };
925 // AAC-LC at 44.1 kHz, stereo: the `AudioSpecificConfig` says so.
926 let mut params = CodecParameters::new(CodecId::Aac);
927 params.extradata = Some(Buf::from(vec![0x12, 0x10]));
928 params.media = MediaParameters::Audio(AudioParameters {
929 sample_rate: 44_100,
930 layout: ChannelLayout::from_count(2),
931 ..Default::default()
932 });
933 let mut writer = ec_mp4::Mp4Muxer::new(std::io::BufWriter::new(
934 std::fs::File::create(path).expect("create"),
935 ))
936 .expect("start an mp4");
937 writer
938 .add_stream(StreamInfo::new(0, TimeBase::from_rate(44_100), params))
939 .expect("an audio track");
940 let mut packet = Packet::new(0, TimeBase::from_rate(44_100), vec![0x21, 0x10]);
941 packet.dts = Some(0);
942 packet.duration = Some(1024);
943 packet.flags.keyframe = true;
944 writer.write_packet(&packet).expect("an audio packet");
945 ec_core::Muxer::finish(&mut writer).expect("finish the mp4");
946 }
947
948 /// The staleness rule *is* the name: touch the source and the old proxy is
949 /// unreachable rather than wrong.
950 #[test]
951 fn a_changed_source_names_another_proxy() {
952 let dir = crate::scratch::Scratch::dir("proxy-key");
953 let file = dir.join("a.mp4");
954 std::fs::write(&file, b"one").expect("write");
955 let first = path_for(&file).expect("a key");
956 assert_eq!(path_for(&file).as_ref(), Some(&first), "stable for a file");
957 // Same length, later time: a re-encode that happened to land on the
958 // same byte count is still another file.
959 std::fs::write(&file, b"two").expect("rewrite");
960 filetime_bump(&file);
961 assert_ne!(path_for(&file), Some(first), "touched: another name");
962 assert_eq!(cached(&file), None, "nothing written, nothing cached");
963 }
964
965 /// Turning one off deletes the stand-in and *only* the stand-in: the film
966 /// it was made from is what plays afterwards, so it had better still be
967 /// there.
968 #[test]
969 fn delete_takes_the_proxy_and_never_the_source() {
970 let dir = crate::scratch::Scratch::dir("proxy-delete");
971 let file = dir.join("a.mp4");
972 std::fs::write(&file, b"the film itself").expect("write");
973 let proxy = path_for(&file).expect("a key");
974 std::fs::create_dir_all(proxy.parent().expect("a cache dir")).expect("cache dir");
975 std::fs::write(&proxy, b"a stand-in").expect("write the proxy");
976 assert_eq!(cached(&file).as_ref(), Some(&proxy), "one in the cache");
977 assert_eq!(delete(&file).ok(), Some(true), "the stand-in went");
978 assert_eq!(cached(&file), None, "and is gone from the cache");
979 assert!(file.is_file(), "the film itself is untouched");
980 assert_eq!(delete(&file).ok(), Some(false), "nothing left to take");
981 assert!(file.is_file(), "still untouched");
982 }
983
984 /// A delete that *failed* is not a delete: the row above it draws itself
985 /// from this answer, and folding "could not" into "was not there" drew a
986 /// switch as OFF over a proxy still on the disk and still being played.
987 #[test]
988 fn a_delete_that_could_not_happen_says_so() {
989 let dir = crate::scratch::Scratch::dir("proxy-delete-refused");
990 let file = dir.join("a.mp4");
991 std::fs::write(&file, b"the film itself").expect("write");
992 let proxy = path_for(&file).expect("a key");
993 std::fs::create_dir_all(&proxy).expect("something an unlink will refuse");
994 // An unlink that fails for anything but "it was not there" -- a
995 // read-only cache directory in the field, a directory in this test --
996 // is a stand-in still on the disk, and it is answered as one.
997 let answer = delete(&file);
998 assert!(answer.is_err(), "a refused unlink reported as a delete");
999 assert!(
1000 proxy.is_dir(),
1001 "and what could not be deleted is still there"
1002 );
1003 std::fs::remove_dir(&proxy).expect("clean up");
1004 // ...against the honest no-op, which *is* an off switch: nothing there.
1005 assert_eq!(delete(&file).ok(), Some(false), "nothing to take");
1006 assert!(file.is_file(), "the film itself, throughout");
1007 }
1008
1009 /// The switch turned off outlives the window: the mark sits beside the
1010 /// cache entry, so the sweep at the next launch answers `None` for that
1011 /// film instead of re-encoding the stand-in somebody just deleted.
1012 #[test]
1013 fn a_film_switched_off_by_hand_stays_off() {
1014 let dir = crate::scratch::Scratch::dir("proxy-off-mark");
1015 let file = dir.join("a.mp4");
1016 std::fs::write(&file, b"the film itself").expect("write");
1017 assert!(!is_off(&file), "nothing has been switched off yet");
1018 set_off(&file, true);
1019 assert!(is_off(&file), "the mark is beside the cache entry");
1020 // Which is what the sweep asks -- and it does not even read the header.
1021 assert!(
1022 matches!(generate_if_wanted(&file, &uncancelled()), Ok(None)),
1023 "a switched-off film was started again"
1024 );
1025 set_off(&file, false);
1026 assert!(!is_off(&file), "switched back on, the mark is gone");
1027 // The mark is keyed like the stand-in: a source that changed is a
1028 // different film and is asked again.
1029 set_off(&file, true);
1030 // Taken back by hand before the key moves: the scratch directory takes
1031 // the film with it, and a mark left in the real cache would outlive the
1032 // test that wrote it.
1033 let stale = off_marker(&file).expect("a key");
1034 std::fs::write(&file, b"re-encoded").expect("rewrite");
1035 filetime_bump(&file);
1036 assert!(!is_off(&file), "a changed source kept the old answer");
1037 std::fs::remove_file(stale).expect("the old mark");
1038 }
1039
1040 /// DEBT #91: a cancel already up when the Asked phase starts must answer
1041 /// promptly and never touch the header at all -- before this, the flag
1042 /// [`generate_if_wanted`] takes did not exist, so nothing here could be
1043 /// cancelled before a [`Job`] existed to call [`Job::cancel`] on, and the
1044 /// only way to see this pass on old code was to change the signature.
1045 ///
1046 /// The file is never a real film: the cancel is answered at the door,
1047 /// before [`Demuxer::open`] is ever reached, which is what "promptly"
1048 /// means here and what proves the header was never read.
1049 #[test]
1050 fn a_cancel_set_before_the_ask_stops_it_at_the_door() {
1051 let dir = crate::scratch::Scratch::dir("proxy-cancel-at-door");
1052 let file = dir.join("a.mp4");
1053 std::fs::write(&file, b"not a real film, and never read").expect("write");
1054 let cancel = Arc::new(AtomicBool::new(true));
1055
1056 let answer = generate_if_wanted(&file, &cancel);
1057 let err = answer
1058 .err()
1059 .expect("a pre-cancelled ask must not hand back a job");
1060 assert!(
1061 crate::demux::is_cancelled(&err),
1062 "not the cancelled answer: {err}"
1063 );
1064 assert_eq!(cached(&file), None, "no proxy was produced");
1065
1066 // Settled the same way a cancelled `Making` is: the seat this claimed
1067 // is given back, so the very next ask -- uncancelled -- is free to take
1068 // it rather than being told one is "already being made".
1069 let out = path_for(&file).expect("a key");
1070 assert!(claim(&out).is_some(), "the door-cancel left the seat held");
1071 }
1072
1073 /// One encoder per film, in the engine and not only in the window that
1074 /// draws the switch: the seat is taken for as long as the job lives, and a
1075 /// second start for the same stand-in is refused rather than allowed to
1076 /// unlink the first one's half-written file.
1077 #[test]
1078 fn one_encoder_per_stand_in() {
1079 let dir = crate::scratch::Scratch::dir("proxy-one-encoder");
1080 let out = dir.join("f00d.mp4");
1081 let first = claim(&out).expect("the seat was free");
1082 assert!(claim(&out).is_none(), "two encoders on one path");
1083 // Another film is another seat.
1084 let other = claim(&dir.join("beef.mp4")).expect("a different stand-in");
1085 drop(first);
1086 let again = claim(&out).expect("the seat came back with the job");
1087 drop((again, other));
1088 assert!(claim(&out).is_some(), "the seat was never given back");
1089 }
1090
1091 /// `std::fs` has no set-mtime, and a rewrite inside the same nanosecond is
1092 /// possible on a fast machine -- so the stamp is moved by hand through the
1093 /// one door that does it without a dependency.
1094 fn filetime_bump(path: &Path) {
1095 let now = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
1096 let file = std::fs::File::options()
1097 .write(true)
1098 .open(path)
1099 .expect("open");
1100 file.set_modified(now).expect("set mtime");
1101 }
1102}