forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB892f813Tahinli3 months ago398 commits

proxy.rs352 lines, 14.9 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.
25//!
26//! Generation is [`crate::export`]'s own decode -> scale -> encode walk, given
27//! a one-clip project and a smaller canvas: the hardware seat where the GPU has
28//! one, the software encoder where it does not, the same progress and the same
29//! cancel a file export has ([`Job`]).
30
31use std::path::{Path, PathBuf};
32use std::time::UNIX_EPOCH;
33
34use crate::demux::{Codec, Demuxer, VideoMeta};
35use crate::export::{ExportHandle, ExportSettings, Format};
36use crate::project::{Clip, LaneKind, Project, Source, Speed};
37use crate::scale::FitPolicy;
38
39/// The long edge of a proxy picture, in samples: 1280, so a 4K source loses
40/// nine tenths of its samples and a 1080p one a little over half. Chosen as
41/// what a cut can be judged on at editing size, in the neighbourhood of every
42/// shipped proxy preset (Resolve's half-res, kdenlive's 640/1000-wide
43/// defaults).
44pub const LONG_EDGE: u32 = 1280;
45
46/// Bits per pixel per second a proxy is coded at, [`crate::export`]'s own rate
47/// rule at three times the number: every frame being an IDR means no frame
48/// borrows anything from its neighbours, so the same picture at the inter rate
49/// would be mush -- and mush is not something a cut can be judged on.
50const BITS_PER_PIXEL: f64 = 0.3;
51
52/// Whether this is a file worth standing in for: bigger than 1080p, or coded in
53/// something this machine decodes slowly even at 1080p. H.264 at or under 1080p
54/// plays natively and a proxy of it would cost time and buy nothing.
55pub fn wanted(meta: &VideoMeta) -> bool {
56 meta.width > 1920 || meta.height > 1080 || matches!(meta.codec, Codec::Hevc | Codec::Av1)
57}
58
59/// The picture a proxy of `meta` is coded at: aspect kept, long edge at most
60/// [`LONG_EDGE`], both axes even because 4:2:0 has no half chroma samples. A
61/// source already that small is coded at its own size (rounded down to even),
62/// which is what makes [`generate`] safe to ask for on anything at all.
63pub fn size_for(meta: &VideoMeta) -> (u32, u32) {
64 let long = meta.width.max(meta.height);
65 let scale = match long > LONG_EDGE {
66 true => f64::from(LONG_EDGE) / f64::from(long),
67 false => 1.0,
68 };
69 let even = |n: u32| (((f64::from(n) * scale).round() as u32) & !1).max(2);
70 (even(meta.width), even(meta.height))
71}
72
73/// Where the proxy of `source` lives, whether or not it has been made yet.
74///
75/// The name is one hash of the source's canonical path, its length **and** its
76/// modification time, so an original that changed at all is a different name
77/// and its old proxy is simply never looked at again -- the staleness check is
78/// the lookup. `None` where the file cannot be stat'd or the machine has no
79/// cache directory at all, which is a source that gets no proxy rather than one
80/// littering the working directory.
81///
82/// corner-cut: nothing evicts, exactly as the Matroska index cache beside it
83/// states. A proxy of a feature film is hundreds of megabytes and a re-encoded
84/// source leaves its old one behind; the upgrade path is a size-capped sweep of
85/// the directory at open. It is the user's own cache to delete meanwhile.
86pub fn path_for(source: &Path) -> Option<PathBuf> {
87 let meta = std::fs::metadata(source).ok()?;
88 let mtime = match meta.modified().ok()?.duration_since(UNIX_EPOCH) {
89 Ok(d) => (d.as_secs() as i128, d.subsec_nanos()),
90 Err(e) => (-(e.duration().as_secs() as i128), e.duration().subsec_nanos()),
91 };
92 let canonical = std::fs::canonicalize(source).unwrap_or_else(|_| source.to_path_buf());
93 let mut bytes = canonical.as_os_str().as_encoded_bytes().to_vec();
94 bytes.extend_from_slice(&meta.len().to_le_bytes());
95 bytes.extend_from_slice(&mtime.0.to_le_bytes());
96 bytes.extend_from_slice(&mtime.1.to_le_bytes());
97 let dir = crate::demux::cache_dir(
98 std::env::var_os("XDG_CACHE_HOME"),
99 std::env::var_os("HOME"),
100 "proxies",
101 )?;
102 Some(dir.join(format!("{:016x}.mp4", crate::demux::fnv1a(&bytes))))
103}
104
105/// The proxy of `source` if one has already been made, `None` otherwise. The
106/// answer a session asks at open: a hit costs one `stat`.
107pub fn cached(source: &Path) -> Option<PathBuf> {
108 path_for(source).filter(|p| p.is_file())
109}
110
111/// A proxy being made -- or one that was already there, which is the same thing
112/// to whoever is waiting for a path.
113///
114/// Poll [`progress`](Job::progress) while [`is_finished`](Job::is_finished) is
115/// false and take the [`outcome`](Job::outcome) when it flips, exactly as an
116/// export is polled. Dropping the job does not stop the work;
117/// [`cancel`](Job::cancel) does.
118pub struct Job {
119 out: PathBuf,
120 /// `None` for a cache hit: there was nothing to run.
121 handle: Option<ExportHandle>,
122}
123
124impl Job {
125 /// Fraction of the proxy's pictures written, `0.0..=1.0`. A cache hit is
126 /// done.
127 ///
128 /// The band an export's bar reserves for its sound is taken back out: a
129 /// proxy has no sound, so that band is crossed in the first instant and
130 /// showing it would be five percent no frame earned.
131 pub fn progress(&self) -> f32 {
132 let Some(handle) = &self.handle else {
133 return 1.0;
134 };
135 let band = crate::export::AUDIO_BAND as f32 / crate::export::PROGRESS_SCALE as f32;
136 ((handle.progress() - band) / (1.0 - band)).clamp(0.0, 1.0)
137 }
138
139 /// What is coding this proxy -- the hardware seat or the software one, as
140 /// the worker really opened it. `None` before the encoder is open, and for
141 /// a cache hit, which coded nothing.
142 pub fn encoder(&self) -> Option<String> {
143 self.handle.as_ref()?.encoders()
144 }
145
146 /// Asks the worker to stop at its next frame and leave no file behind. The
147 /// outcome then reports the cancellation as an error.
148 pub fn cancel(&self) {
149 if let Some(handle) = &self.handle {
150 handle.cancel();
151 }
152 }
153
154 pub fn is_finished(&self) -> bool {
155 self.handle.as_ref().is_none_or(ExportHandle::is_finished)
156 }
157
158 /// The proxy's path once it is written, once -- taken out of the job, so a
159 /// caller that already took it sees `None`. `None` while it is still being
160 /// made.
161 pub fn outcome(&self) -> Option<crate::Result<PathBuf>> {
162 let Some(handle) = &self.handle else {
163 return Some(Ok(self.out.clone()));
164 };
165 handle.result().map(|r| r.map(|()| self.out.clone()))
166 }
167
168 /// Where the proxy will be, whether or not it is there yet -- what a caller
169 /// names in a log line while the job runs.
170 pub fn path(&self) -> &Path {
171 &self.out
172 }
173}
174
175/// Starts making the proxy of `source`, or hands back the one already in the
176/// cache. Errors are the ones that happen before a worker exists -- a file with
177/// no picture in it, nowhere to put a cache -- and everything after them comes
178/// back through [`Job::outcome`], so a caller has two places to look and not
179/// twenty.
180pub fn generate(source: &Path) -> crate::Result<Job> {
181 Ok(started(source, |_| true)?.expect("nothing was filtered out"))
182}
183
184/// The same, for a file that is worth standing in for and nobody else
185/// ([`wanted`]) -- `Ok(None)` is a film this machine already cuts at speed.
186///
187/// The header is read *once* for both questions: on a Matroska that read is the
188/// cluster walk, so asking `wanted` and then `generate` separately would pay
189/// for it twice.
190pub fn generate_if_wanted(source: &Path) -> crate::Result<Option<Job>> {
191 started(source, wanted)
192}
193
194/// Both doors: the cache is looked at, the header is read once, and `only_if`
195/// decides off that header whether there is anything to do.
196fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result<Option<Job>> {
197 let out = path_for(source).ok_or("no cache directory to keep a proxy in")?;
198 if out.is_file() {
199 return Ok(Some(Job { out, handle: None }));
200 }
201 // The source's own header: its rate and length are the proxy's (a stand-in
202 // that ran at another rate or stopped early would put every cut on another
203 // frame), and only its picture size changes.
204 let (meta, _) = Demuxer::open(source)?;
205 if !only_if(&meta) {
206 return Ok(None);
207 }
208 let (width, height) = size_for(&meta);
209 if let Some(dir) = out.parent() {
210 std::fs::create_dir_all(dir)?;
211 }
212 // What a killed editor left behind: the export worker deletes its own part
213 // file when it is cancelled or fails, but nothing can delete it for a
214 // process that was killed -- and a proxy of a feature film is hundreds of
215 // megabytes of cache nothing would ever look at again. The key is the same,
216 // so this is that same film's own leftover and not somebody else's.
217 let mut part = out.clone().into_os_string();
218 part.push(".part");
219 let _ = std::fs::remove_file(PathBuf::from(part));
220 // One video lane, one clip, the whole file -- and *no* audio lane, which is
221 // what makes the proxy picture-only: the export walk codes the lanes it is
222 // given and there is no sound among them.
223 let clip = Clip {
224 start: 0,
225 in_frame: 0,
226 out_frame: meta.frame_count.max(1),
227 source: 0,
228 link: None,
229 eq: None,
230 color: None,
231 fit: FitPolicy::default(),
232 speed: Speed::NORMAL,
233 };
234 let project = Project::from_parts(
235 vec![Source::new(source, 0)],
236 vec![(LaneKind::Video, vec![clip])],
237 Vec::new(),
238 Vec::new(),
239 )?;
240 let bitrate =
241 (f64::from(width) * f64::from(height) * meta.frame_rate * BITS_PER_PIXEL) as u64;
242 let handle = crate::export::start(
243 project,
244 VideoMeta {
245 width,
246 height,
247 ..meta
248 },
249 &out,
250 &ExportSettings {
251 format: Format::Mp4,
252 // The whole point: every frame its own random-access point.
253 intra_only: true,
254 // ...and the film's own colour, carried rather than converted: the
255 // screen tone-maps the stand-in exactly as it tone-maps the film,
256 // live and at preview size.
257 keep_source_colour: true,
258 bitrate: Some(bitrate),
259 ..Default::default()
260 },
261 );
262 Ok(Some(Job {
263 out,
264 handle: Some(handle),
265 }))
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271 use crate::colorspace::ColorDescription;
272
273 fn meta(width: u32, height: u32, codec: Codec) -> VideoMeta {
274 VideoMeta {
275 width,
276 height,
277 frame_rate: 24.0,
278 frame_count: 240,
279 codec,
280 color: ColorDescription::default(),
281 }
282 }
283
284 /// What a proxy is *for*: the files this machine cannot play at speed.
285 #[test]
286 fn only_the_files_that_need_one_get_one() {
287 assert!(wanted(&meta(3840, 2160, Codec::Hevc)), "4K HEVC");
288 assert!(wanted(&meta(3840, 2160, Codec::H264)), "4K H.264");
289 assert!(wanted(&meta(1920, 1080, Codec::Hevc)), "1080p HEVC");
290 assert!(wanted(&meta(1920, 1080, Codec::Av1)), "1080p AV1");
291 assert!(
292 !wanted(&meta(1920, 1080, Codec::H264)),
293 "1080p H.264 plays natively"
294 );
295 assert!(!wanted(&meta(1280, 720, Codec::H264)), "720p H.264");
296 }
297
298 /// Aspect kept, long edge capped, both axes even -- and a small source left
299 /// alone rather than blown up.
300 #[test]
301 fn a_proxy_is_the_same_shape_at_a_smaller_size() {
302 assert_eq!(size_for(&meta(3840, 2160, Codec::Hevc)), (1280, 720));
303 assert_eq!(size_for(&meta(1920, 1080, Codec::Hevc)), (1280, 720));
304 // A portrait source is capped on *its* long edge, which is the height.
305 assert_eq!(size_for(&meta(1080, 1920, Codec::Hevc)), (720, 1280));
306 // 1916x1080 (a real film's cropped width): even both ways, and the
307 // aspect it really has rather than the 16:9 it nearly has.
308 let (w, h) = size_for(&meta(1916, 1080, Codec::H264));
309 assert_eq!((w, h), (1280, 722), "cropped-width 1080p");
310 assert_eq!(w % 2, 0);
311 assert_eq!(h % 2, 0);
312 assert!(
313 (f64::from(w) / f64::from(h) - 1916. / 1080.).abs() < 0.005,
314 "{w}x{h} is the source's shape"
315 );
316 assert_eq!(
317 size_for(&meta(640, 360, Codec::H264)),
318 (640, 360),
319 "already small: its own size, never upscaled"
320 );
321 assert_eq!(size_for(&meta(1, 1, Codec::H264)), (2, 2), "never zero");
322 }
323
324 /// The staleness rule *is* the name: touch the source and the old proxy is
325 /// unreachable rather than wrong.
326 #[test]
327 fn a_changed_source_names_another_proxy() {
328 let dir = crate::scratch::Scratch::dir("proxy-key");
329 let file = dir.join("a.mp4");
330 std::fs::write(&file, b"one").expect("write");
331 let first = path_for(&file).expect("a key");
332 assert_eq!(path_for(&file).as_ref(), Some(&first), "stable for a file");
333 // Same length, later time: a re-encode that happened to land on the
334 // same byte count is still another file.
335 std::fs::write(&file, b"two").expect("rewrite");
336 filetime_bump(&file);
337 assert_ne!(path_for(&file), Some(first), "touched: another name");
338 assert_eq!(cached(&file), None, "nothing written, nothing cached");
339 }
340
341 /// `std::fs` has no set-mtime, and a rewrite inside the same nanosecond is
342 /// possible on a fast machine -- so the stamp is moved by hand through the
343 /// one door that does it without a dependency.
344 fn filetime_bump(path: &Path) {
345 let now = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
346 let file = std::fs::File::options()
347 .write(true)
348 .open(path)
349 .expect("open");
350 file.set_modified(now).expect("set mtime");
351 }
352}