forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBeef3d5dTahinli3 months ago444 commits

proxy.rs640 lines, 29.3 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/// A proxy being made -- or one that was already there, which is the same thing
227/// to whoever is waiting for a path.
228///
229/// Poll [`progress`](Job::progress) while [`is_finished`](Job::is_finished) is
230/// false and take the [`outcome`](Job::outcome) when it flips, exactly as an
231/// export is polled. Dropping the job does not stop the work;
232/// [`cancel`](Job::cancel) does.
233pub struct Job {
234 out: PathBuf,
235 /// `None` for a cache hit: there was nothing to run.
236 handle: Option<ExportHandle>,
237}
238
239impl Job {
240 /// Fraction of the proxy's pictures written, `0.0..=1.0`. A cache hit is
241 /// done.
242 ///
243 /// The band an export's bar reserves for its sound is taken back out: a
244 /// proxy has no sound, so that band is crossed in the first instant and
245 /// showing it would be five percent no frame earned.
246 pub fn progress(&self) -> f32 {
247 let Some(handle) = &self.handle else {
248 return 1.0;
249 };
250 let band = crate::export::AUDIO_BAND as f32 / crate::export::PROGRESS_SCALE as f32;
251 ((handle.progress() - band) / (1.0 - band)).clamp(0.0, 1.0)
252 }
253
254 /// What is coding this proxy -- the hardware seat or the software one, as
255 /// the worker really opened it. `None` before the encoder is open, and for
256 /// a cache hit, which coded nothing.
257 pub fn encoder(&self) -> Option<String> {
258 self.handle.as_ref()?.encoders()
259 }
260
261 /// Asks the worker to stop at its next frame and leave no file behind. The
262 /// outcome then reports the cancellation as an error.
263 pub fn cancel(&self) {
264 if let Some(handle) = &self.handle {
265 handle.cancel();
266 }
267 }
268
269 pub fn is_finished(&self) -> bool {
270 self.handle.as_ref().is_none_or(ExportHandle::is_finished)
271 }
272
273 /// The proxy's path once it is written, once -- taken out of the job, so a
274 /// caller that already took it sees `None`. `None` while it is still being
275 /// made.
276 pub fn outcome(&self) -> Option<crate::Result<PathBuf>> {
277 let Some(handle) = &self.handle else {
278 return Some(Ok(self.out.clone()));
279 };
280 handle.result().map(|r| r.map(|()| self.out.clone()))
281 }
282
283 /// Where the proxy will be, whether or not it is there yet -- what a caller
284 /// names in a log line while the job runs.
285 pub fn path(&self) -> &Path {
286 &self.out
287 }
288}
289
290/// Starts making the proxy of `source`, or hands back the one already in the
291/// cache. Errors are the ones that happen before a worker exists -- a file with
292/// no picture in it, nowhere to put a cache -- and everything after them comes
293/// back through [`Job::outcome`], so a caller has two places to look and not
294/// twenty.
295pub fn generate(source: &Path) -> crate::Result<Job> {
296 Ok(started(source, |_| true)?.expect("nothing was filtered out"))
297}
298
299/// The same, for a file that is worth standing in for and nobody else
300/// ([`wanted`]) -- `Ok(None)` is a film this machine already cuts at speed.
301///
302/// The header is read *once* for both questions: on a Matroska that read is the
303/// cluster walk, so asking `wanted` and then `generate` separately would pay
304/// for it twice.
305///
306/// A file with no picture in it is not a film and is answered `Ok(None)`, the
307/// same answer a 1080p H.264 film gets -- it is not a failure, and reporting it
308/// as one put "NO PROXY for tone.wav" in front of somebody who had imported a
309/// song.
310///
311/// Twice, because there are two ways to know. A name this engine already reads
312/// as sound or as a still is answered before anything is opened, which is the
313/// cheap half. The other half is the honest one: **an audio-only `.mp4`, `.mkv`
314/// or `.mov` is a video container with no video track in it**, and only its
315/// header says so -- so the demuxer's own [`NoVideoTrack`] answer is taken here
316/// as the same quiet `None`. A film that *has* a picture and will not open is a
317/// different thing and stays loud.
318pub fn generate_if_wanted(source: &Path) -> crate::Result<Option<Job>> {
319 if crate::is_audio(source) || crate::is_image(source) {
320 return Ok(None);
321 }
322 match started(source, wanted) {
323 Err(e) if NoVideoTrack::is_it(&e) => Ok(None),
324 other => other,
325 }
326}
327
328/// Both doors: the cache is looked at, the header is read once, and `only_if`
329/// decides off that header whether there is anything to do.
330fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result<Option<Job>> {
331 let out = path_for(source).ok_or("no cache directory to keep a proxy in")?;
332 if out.is_file() {
333 return Ok(Some(Job { out, handle: None }));
334 }
335 // The source's own header: its rate and length are the proxy's (a stand-in
336 // that ran at another rate or stopped early would put every cut on another
337 // frame), and only its picture size changes.
338 let (meta, _) = Demuxer::open(source)?;
339 if !only_if(&meta) {
340 return Ok(None);
341 }
342 let (width, height) = size_for(&meta);
343 if let Some(dir) = out.parent() {
344 std::fs::create_dir_all(dir)?;
345 // Before the write, which is the only thing that makes this directory
346 // bigger -- and with room left for what is *about* to be written into
347 // it: sweeping to the bare cap left the finished ones filling it and
348 // then [`AT_ONCE`] encodes adding gigabytes on top, which is a cap that
349 // is over by a whole film's worth by construction ([`reserve`]).
350 sweep(dir, CACHE_CAP.saturating_sub(reserve(width, height, meta.frame_count)));
351 }
352 // What a killed editor left behind: the export worker deletes its own part
353 // file when it is cancelled or fails, but nothing can delete it for a
354 // process that was killed -- and a proxy of a feature film is hundreds of
355 // megabytes of cache nothing would ever look at again. The key is the same,
356 // so this is that same film's own leftover and not somebody else's.
357 let mut part = out.clone().into_os_string();
358 part.push(".part");
359 let _ = std::fs::remove_file(PathBuf::from(part));
360 // One video lane, one clip, the whole file -- and *no* audio lane, which is
361 // what makes the proxy picture-only: the export walk codes the lanes it is
362 // given and there is no sound among them.
363 let clip = Clip {
364 start: 0,
365 in_frame: 0,
366 out_frame: meta.frame_count.max(1),
367 source: 0,
368 link: None,
369 eq: None,
370 color: None,
371 fit: FitPolicy::default(),
372 speed: Speed::NORMAL,
373 };
374 let project = Project::from_parts(
375 vec![Source::new(source, 0)],
376 vec![(LaneKind::Video, vec![clip])],
377 Vec::new(),
378 Vec::new(),
379 )?;
380 let bitrate =
381 (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64;
382 let handle = crate::export::start(
383 project,
384 VideoMeta {
385 width,
386 height,
387 ..meta
388 },
389 &out,
390 &ExportSettings {
391 format: Format::Mp4,
392 // The whole point: every frame its own random-access point.
393 intra_only: true,
394 // ...and the film's own colour, carried rather than converted: the
395 // screen tone-maps the stand-in exactly as it tone-maps the film,
396 // live and at preview size.
397 keep_source_colour: true,
398 bitrate: Some(bitrate),
399 ..Default::default()
400 },
401 );
402 Ok(Some(Job {
403 out,
404 handle: Some(handle),
405 }))
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411 use crate::colorspace::ColorDescription;
412
413 fn meta(width: u32, height: u32, codec: Codec) -> VideoMeta {
414 VideoMeta {
415 width,
416 height,
417 frame_rate: 24.0,
418 frame_count: 240,
419 codec,
420 color: ColorDescription::default(),
421 }
422 }
423
424 /// What a proxy is *for*: the files this machine cannot play at speed.
425 #[test]
426 fn only_the_files_that_need_one_get_one() {
427 assert!(wanted(&meta(3840, 2160, Codec::Hevc)), "4K HEVC");
428 assert!(wanted(&meta(3840, 2160, Codec::H264)), "4K H.264");
429 assert!(wanted(&meta(1920, 1080, Codec::Hevc)), "1080p HEVC");
430 assert!(wanted(&meta(1920, 1080, Codec::Av1)), "1080p AV1");
431 assert!(
432 !wanted(&meta(1920, 1080, Codec::H264)),
433 "1080p H.264 plays natively"
434 );
435 assert!(!wanted(&meta(1280, 720, Codec::H264)), "720p H.264");
436 }
437
438 /// Aspect kept, long edge capped, both axes even -- and a small source left
439 /// alone rather than blown up.
440 #[test]
441 fn a_proxy_is_the_same_shape_at_a_smaller_size() {
442 assert_eq!(size_for(&meta(3840, 2160, Codec::Hevc)), (1280, 720));
443 assert_eq!(size_for(&meta(1920, 1080, Codec::Hevc)), (1280, 720));
444 // A portrait source is capped on *its* long edge, which is the height.
445 assert_eq!(size_for(&meta(1080, 1920, Codec::Hevc)), (720, 1280));
446 // 1916x1080 (a real film's cropped width): even both ways, and the
447 // aspect it really has rather than the 16:9 it nearly has.
448 let (w, h) = size_for(&meta(1916, 1080, Codec::H264));
449 assert_eq!((w, h), (1280, 722), "cropped-width 1080p");
450 assert_eq!(w % 2, 0);
451 assert_eq!(h % 2, 0);
452 assert!(
453 (f64::from(w) / f64::from(h) - 1916. / 1080.).abs() < 0.005,
454 "{w}x{h} is the source's shape"
455 );
456 assert_eq!(
457 size_for(&meta(640, 360, Codec::H264)),
458 (640, 360),
459 "already small: its own size, never upscaled"
460 );
461 assert_eq!(size_for(&meta(1, 1, Codec::H264)), (2, 2), "never zero");
462 }
463
464 /// What the sweep leaves free for the encodes that are about to run: two
465 /// of them, at what this one is really going to cost. Without it the cap
466 /// was soft by a whole film per encode -- 20 GB of finished stand-ins and
467 /// then two 4K ones writing gigabytes on top of it.
468 #[test]
469 fn the_cap_keeps_room_for_what_is_about_to_be_written() {
470 // A 2h20 4K film, at the size a stand-in of it is coded: 1280x536 for
471 // 201536 frames. Its own arithmetic says ~2.6 GB, and two of them is
472 // over the cap's half, so the reserve is that half.
473 let big = reserve(1280, 536, 201_536);
474 assert_eq!(big, CACHE_CAP / 2, "a feature film asks for more than half");
475 // A short clip asks for what it costs and no more: 1280x720 for 300
476 // frames is 1280*720*300*0.3/8 * 1.25 * 2 encodes.
477 let small = reserve(1280, 720, 300);
478 let one = 1280.0 * 720.0 * 300.0 * BITS_PER_PIXEL / 8.0 * RATE_OVERSHOOT;
479 assert_eq!(small, one as u64 * AT_ONCE as u64);
480 assert!(small < CACHE_CAP / 2, "and it is nowhere near the ceiling");
481 // The reserve is what a sweep aims below, so what is *finished* is held
482 // under the cap by at least the room the encodes will take.
483 assert!(CACHE_CAP.saturating_sub(big) <= CACHE_CAP / 2);
484 // Nothing overflows on a picture nobody would code.
485 assert_eq!(reserve(0, 0, 0), 0);
486 assert_eq!(reserve(u32::MAX, u32::MAX, u32::MAX), CACHE_CAP / 2);
487 }
488
489 /// The cap keeps the directory a cache and not a second copy of the
490 /// library: over it, the least recently used go until it fits, and a
491 /// half-written one is never taken (it is being written *now*) though its
492 /// bytes count towards what has to be freed.
493 #[test]
494 fn the_cache_evicts_its_oldest_until_it_fits() {
495 let dir = crate::scratch::Scratch::dir("proxy-sweep");
496 let write = |name: &str, len: usize, ago: u64| {
497 let path = dir.join(name);
498 std::fs::write(&path, vec![0u8; len]).expect("write");
499 // Stamped by hand: three files written in one millisecond have no
500 // order of their own, and the order is what is under test. `atime`
501 // is what `sweep` reads and `set_times` is the one door to it
502 // without a dependency.
503 let file = std::fs::File::options().write(true).open(&path).expect("open");
504 let when = std::time::SystemTime::now() - std::time::Duration::from_secs(ago);
505 file.set_times(std::fs::FileTimes::new().set_accessed(when).set_modified(when))
506 .expect("stamp");
507 path
508 };
509 let old = write("old.mp4", 400, 300);
510 let middle = write("middle.mp4", 400, 200);
511 let fresh = write("fresh.mp4", 400, 100);
512 let part = write("busy.mp4.part", 400, 400);
513
514 // 1600 bytes there, 900 allowed: the oldest two `.mp4`s go, and that is
515 // as far as it gets -- the part file is 400 of the remaining bytes and
516 // is not the sweep's to take.
517 let left = sweep(&dir, 900);
518 assert!(!old.exists(), "the oldest stand-in survived the sweep");
519 assert!(!middle.exists(), "the next oldest survived it");
520 assert!(fresh.exists(), "the freshest was taken");
521 assert!(part.exists(), "a half-written proxy was deleted under its writer");
522 assert_eq!(left, 800, "what is left is the fresh one and the part file");
523
524 // Under the cap, nothing is touched at all.
525 assert_eq!(sweep(&dir, 900), 800);
526 assert!(fresh.exists());
527 }
528
529 /// A song and a still are not films: they are answered `None` -- the same
530 /// answer a 1080p H.264 film gets -- rather than opened, failed on and
531 /// reported. The bug this pins said "NO PROXY for tone.wav" to a person who
532 /// had imported a song, and put "no proxy" on its library row.
533 ///
534 /// Real files, because the point is that nothing reads them: a demuxer
535 /// opened on a WAV is exactly what used to raise the refusal.
536 ///
537 /// ...and one **audio-only mp4**, which is the same class arriving the
538 /// other way: its name says video, so no extension can answer it and the
539 /// header is what tells. That one is a real, well-formed mp4 with an AAC
540 /// track and no video track at all -- a thing a person really does hand an
541 /// editor, and what a name-shaped gate walks straight past.
542 #[test]
543 fn a_song_and_a_still_are_never_stood_in_for() {
544 let dir = crate::scratch::Scratch::dir("proxy-not-a-film");
545 for name in ["tone.wav", "song.mp3", "track.mka", "still.png", "shot.jpg"] {
546 let file = dir.join(name);
547 std::fs::write(&file, b"not a film, and never read").expect("write");
548 let answer = generate_if_wanted(&file);
549 assert!(
550 matches!(answer, Ok(None)),
551 "{name} is not a film to stand in for: {:?}",
552 answer.err().map(|e| e.to_string())
553 );
554 assert_eq!(cached(&file), None, "{name} left nothing in the cache");
555 }
556
557 let silent_film = dir.join("audio-only.mp4");
558 write_audio_only_mp4(&silent_film);
559 // It really is an mp4 nothing here finds a picture in -- the demuxer
560 // says so by name, which is what makes the answer below a *class* and
561 // not a guess about the extension.
562 let opened = Demuxer::open(&silent_film);
563 let refusal = opened.err().expect("an mp4 with no picture will not open");
564 assert!(
565 crate::demux::NoVideoTrack::is_it(&refusal),
566 "not the no-picture answer: {refusal}"
567 );
568 let answer = generate_if_wanted(&silent_film);
569 assert!(
570 matches!(answer, Ok(None)),
571 "an audio-only mp4 is not a film to stand in for: {:?}",
572 answer.err().map(|e| e.to_string())
573 );
574 assert_eq!(cached(&silent_film), None);
575 }
576
577 /// A well-formed mp4 carrying one AAC track and no video track: what an
578 /// `ffmpeg -vn` or a music file in the wrong box looks like. Written with
579 /// the same crate the exporter's muxer uses, so it is the file that reader
580 /// really parses and not a hand-made approximation.
581 fn write_audio_only_mp4(path: &Path) {
582 use mp4::{
583 AacConfig, AudioObjectType, ChannelConfig, FourCC, MediaConfig, Mp4Config, Mp4Writer,
584 SampleFreqIndex, TrackConfig, TrackType,
585 };
586 let mut writer = Mp4Writer::write_start(
587 std::io::BufWriter::new(std::fs::File::create(path).expect("create")),
588 &Mp4Config {
589 major_brand: FourCC::from(*b"isom"),
590 minor_version: 512,
591 compatible_brands: vec![FourCC::from(*b"isom"), FourCC::from(*b"mp41")],
592 timescale: 44_100,
593 },
594 )
595 .expect("start an mp4");
596 writer
597 .add_track(&TrackConfig {
598 track_type: TrackType::Audio,
599 timescale: 44_100,
600 language: "und".to_string(),
601 media_conf: MediaConfig::AacConfig(AacConfig {
602 bitrate: 0,
603 profile: AudioObjectType::AacLowComplexity,
604 freq_index: SampleFreqIndex::Freq44100,
605 chan_conf: ChannelConfig::Stereo,
606 }),
607 })
608 .expect("an audio track");
609 writer.write_end().expect("finish the mp4");
610 }
611
612 /// The staleness rule *is* the name: touch the source and the old proxy is
613 /// unreachable rather than wrong.
614 #[test]
615 fn a_changed_source_names_another_proxy() {
616 let dir = crate::scratch::Scratch::dir("proxy-key");
617 let file = dir.join("a.mp4");
618 std::fs::write(&file, b"one").expect("write");
619 let first = path_for(&file).expect("a key");
620 assert_eq!(path_for(&file).as_ref(), Some(&first), "stable for a file");
621 // Same length, later time: a re-encode that happened to land on the
622 // same byte count is still another file.
623 std::fs::write(&file, b"two").expect("rewrite");
624 filetime_bump(&file);
625 assert_ne!(path_for(&file), Some(first), "touched: another name");
626 assert_eq!(cached(&file), None, "nothing written, nothing cached");
627 }
628
629 /// `std::fs` has no set-mtime, and a rewrite inside the same nanosecond is
630 /// possible on a fast machine -- so the stamp is moved by hand through the
631 /// one door that does it without a dependency.
632 fn filetime_bump(path: &Path) {
633 let now = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
634 let file = std::fs::File::options()
635 .write(true)
636 .open(path)
637 .expect("open");
638 file.set_modified(now).expect("set mtime");
639 }
640}