forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

render_cache.rs350 lines, 13.4 KiBHistoryRawDownload
1//! Render preview: a stretch of the timeline pre-rendered once into a picture
2//! file at preview size, so that playback over it reads frames instead of
3//! compositing them -- the heavy sections (stacked effects, titles over video,
4//! colour, speed, multicam) are the ones that drop frames live.
5//!
6//! The rules, and they are the whole contract:
7//!
8//! - **Content-keyed, never stale.** A segment is named by a hash of everything
9//! that can change its pixels in its range: the clips that overlap it (and the
10//! neighbours either side, whose transitions reach into it), their sources'
11//! files, the titles and captions over it, the lanes' visibility, the tone and
12//! the frame rate. Any edit that changes those drops the segment by name: a
13//! changed hash is a file nothing looks for. Nothing is ever compared by time.
14//! - **Derived, never authoritative.** Deleting the render directory costs the
15//! time to render again and nothing else. Nothing in a project file names a
16//! segment; the directory is scanned and each file is checked against the
17//! hash of the timeline as it is now ([`segments`]).
18//! - **Picture at preview size.** Rendered through [`crate::export`] over the
19//! range, at [`crate::proxy::size_for`] of the project, every frame a random
20//! access point. Playback scales it to the viewer like any other picture.
21//! Sound is not used from here; the live mix always plays.
22//!
23//! Files are named `{from}-{to}-{width}x{height}-{key:016x}.mp4` in the user's
24//! cache under `edith/renders`. The `.part` while it is written is what an
25//! export writes beside its output, and the rename is the finish.
26
27use std::path::{Path, PathBuf};
28use std::time::UNIX_EPOCH;
29
30use crate::demux::{VideoMeta, fnv1a};
31use crate::export::{ExportHandle, ExportSettings, Format};
32use crate::project::{Clip, Project};
33
34/// One rendered stretch that still matches the timeline: frames `from..to`.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Segment {
37 pub from: u32,
38 pub to: u32,
39 /// The picture size the frames are at.
40 pub size: (u32, u32),
41 pub path: PathBuf,
42}
43
44/// Where renders live, or `None` where the machine has no cache directory.
45pub fn dir() -> Option<PathBuf> {
46 crate::demux::cache_dir(
47 crate::envcfg::var_os("XDG_CACHE_HOME"),
48 std::env::var_os("HOME"),
49 "renders",
50 )
51}
52
53/// What a file on disk says about itself, for the content key: its path, its
54/// length and its modification time. A source that moved or changed is a
55/// different key.
56fn file_stamp(path: &Path) -> String {
57 match std::fs::metadata(path) {
58 Ok(meta) => {
59 let mtime = meta
60 .modified()
61 .ok()
62 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
63 .map(|d| (d.as_secs(), d.subsec_nanos()));
64 format!("{path:?} {} {mtime:?}\n", meta.len())
65 }
66 Err(_) => format!("{path:?} missing\n"),
67 }
68}
69
70/// The hash of everything that can change the pixels of `from..to` at `size`.
71///
72/// Each clip that overlaps the range is hashed whole (its effects, keys, colour,
73/// transform, fades and transitions are all in its `Debug`), and so is the one
74/// clip either side of the range in every lane: a transition out of the clip
75/// before reaches into the range, and the clip after is what it blends into.
76/// Captions and titles are hashed whole when they overlap, and so is the tone.
77/// Over-keying is safe here -- an extra hash change only costs a re-render --
78/// so the rule is kept simple rather than exact.
79fn content_key(project: &Project, meta: &VideoMeta, from: u32, to: u32, size: (u32, u32)) -> u64 {
80 let (near_from, near_to) = (from.saturating_sub(1), to.saturating_add(1));
81 let mut text = format!(
82 "{from} {to} {}x{} {:?} {:?}\n",
83 size.0,
84 size.1,
85 meta.frame_rate,
86 project.tone()
87 );
88 let sources = project.sources();
89 for lane in project.lanes() {
90 text.push_str(&format!("lane {lane:?} hidden {}\n", project.lane_hidden(lane)));
91 let clips = project.lane(lane);
92 for (i, clip) in clips.iter().enumerate() {
93 let overlaps = clip.start < near_to && clip.end() > near_from;
94 let next = clip.start >= to && !clips[..i].iter().any(|c| c.start >= to);
95 let prev = clip.end() <= from && clips.get(i + 1).is_none_or(|c| c.end() <= from);
96 if !(overlaps || next || prev) {
97 continue;
98 }
99 text.push_str(&format!("{clip:?}\n"));
100 if let Some(source) = sources.get(clip.source) {
101 text.push_str(&file_stamp(&source.path));
102 }
103 }
104 }
105 for title in project.titles() {
106 if title.start < near_to && title.start + title.frames > near_from {
107 text.push_str(&format!("{title:?}\n"));
108 }
109 }
110 text.push_str(&format!("{:?}\n", project.subtitles()));
111 fnv1a(text.as_bytes())
112}
113
114fn name(from: u32, to: u32, size: (u32, u32), key: u64) -> String {
115 format!("{from}-{to}-{}x{}-{key:016x}.mp4", size.0, size.1)
116}
117
118/// The inverse of [`name`]: `None` for anything else in the directory.
119fn parse(name: &str) -> Option<(u32, u32, (u32, u32), u64)> {
120 let mut parts = name.strip_suffix(".mp4")?.split('-');
121 let from = parts.next()?.parse().ok()?;
122 let to = parts.next()?.parse().ok()?;
123 let (w, h) = parts.next()?.split_once('x')?;
124 let key = u64::from_str_radix(parts.next()?, 16).ok()?;
125 match parts.next() {
126 None => Some((from, to, (w.parse().ok()?, h.parse().ok()?), key)),
127 Some(_) => None,
128 }
129}
130
131/// Every rendered segment that still matches `project` as it is now, in
132/// timeline order. A file whose hash no longer matches is simply not returned;
133/// it is left for [`delete_all`] to take.
134pub fn segments(project: &Project, meta: &VideoMeta) -> Vec<Segment> {
135 let Some(dir) = dir() else {
136 return Vec::new();
137 };
138 let Ok(entries) = std::fs::read_dir(&dir) else {
139 return Vec::new();
140 };
141 let mut found = Vec::new();
142 for entry in entries.flatten() {
143 let path = entry.path();
144 let Some(file) = path.file_name().and_then(|n| n.to_str()) else {
145 continue;
146 };
147 let Some((from, to, size, key)) = parse(file) else {
148 continue;
149 };
150 if to > from && content_key(project, meta, from, to, size) == key {
151 found.push(Segment { from, to, size, path });
152 }
153 }
154 found.sort_by_key(|s| s.from);
155 found
156}
157
158/// The segment that holds timeline frame `frame`, if one matches now.
159pub fn at(project: &Project, meta: &VideoMeta, frame: u32) -> Option<Segment> {
160 segments(project, meta)
161 .into_iter()
162 .find(|s| s.from <= frame && frame < s.to)
163}
164
165/// A render being made, or one that was already there. Poll
166/// [`progress`](Job::progress) while [`is_finished`](Job::is_finished) is false
167/// and take the [`outcome`](Job::outcome) when it flips, as a proxy is polled.
168pub struct Job {
169 out: PathBuf,
170 /// `None` for a segment that already exists: there is nothing to run.
171 handle: Option<ExportHandle>,
172}
173
174impl Job {
175 /// Fraction of the render written, `0.0..=1.0`. An existing segment is done.
176 pub fn progress(&self) -> f32 {
177 self.handle.as_ref().map_or(1.0, |h| h.progress().clamp(0.0, 1.0))
178 }
179
180 /// Asks the encoder to stop at its next frame and leave no file behind.
181 pub fn cancel(&self) {
182 if let Some(handle) = &self.handle {
183 handle.cancel();
184 }
185 }
186
187 /// Whether [`cancel`](Job::cancel) was asked of this render.
188 pub fn is_cancelled(&self) -> bool {
189 self.handle.as_ref().is_some_and(ExportHandle::is_cancelling)
190 }
191
192 pub fn is_finished(&self) -> bool {
193 self.handle.as_ref().is_none_or(ExportHandle::is_finished)
194 }
195
196 /// The segment's path once it is written, once. `None` while it is still
197 /// being made.
198 pub fn outcome(&self) -> Option<crate::Result<PathBuf>> {
199 let Some(handle) = &self.handle else {
200 return Some(Ok(self.out.clone()));
201 };
202 handle.result().map(|r| r.map(|()| self.out.clone()))
203 }
204}
205
206/// Starts rendering `from..to` of `project` (clamped to its end), or hands back
207/// the segment already there. The frames are the ones the project plays: the
208/// render is an export of the range at [`crate::proxy::size_for`] the project.
209pub fn start(project: Project, meta: VideoMeta, from: u32, to: u32) -> crate::Result<Job> {
210 let to = to.min(project.media_frames());
211 if from >= to {
212 return Err("there is nothing between the in and out points to render".into());
213 }
214 let size = crate::proxy::size_for(&meta);
215 let dir = dir().ok_or("no cache directory to keep a render in")?;
216 std::fs::create_dir_all(&dir)?;
217 let out = dir.join(name(from, to, size, content_key(&project, &meta, from, to, size)));
218 if out.is_file() {
219 return Ok(Job { out, handle: None });
220 }
221 // What a killed render left behind, under the same name: the same range of
222 // the same timeline, so it is nobody else's to keep.
223 let mut part = out.clone().into_os_string();
224 part.push(".part");
225 let _ = std::fs::remove_file(PathBuf::from(part));
226 let handle = crate::export::start(
227 project,
228 meta,
229 &out,
230 &ExportSettings {
231 format: Format::Mp4,
232 // Every frame its own random-access point: a seek into a render
233 // lands on the frame asked for, the way it does in a proxy.
234 intra_only: true,
235 range: Some((from, to)),
236 size: Some(size),
237 ..Default::default()
238 },
239 None,
240 );
241 Ok(Job {
242 out,
243 handle: Some(handle),
244 })
245}
246
247/// Deletes every render, finished or half written, and says how many files went.
248/// Nothing else in the cache directory is ever named by this module.
249pub fn delete_all() -> std::io::Result<usize> {
250 let Some(dir) = dir() else {
251 return Ok(0);
252 };
253 let entries = match std::fs::read_dir(&dir) {
254 Ok(entries) => entries,
255 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),
256 Err(e) => return Err(e),
257 };
258 let mut removed = 0;
259 for entry in entries.flatten() {
260 let path = entry.path();
261 let ours = path
262 .file_name()
263 .and_then(|n| n.to_str())
264 .is_some_and(|n| parse(n).is_some() || n.ends_with(".mp4.part"));
265 if ours && path.is_file() {
266 std::fs::remove_file(&path)?;
267 removed += 1;
268 }
269 }
270 Ok(removed)
271}
272
273/// Whether a clip carries anything that a render would be paying for: an effect,
274/// a colour or transform, a key, a fade or a transition, or a speed change.
275/// Used by the bar that marks the stretches worth rendering.
276pub fn clip_has_work(clip: &Clip) -> bool {
277 !clip.effects.is_empty()
278 || clip.color.is_some()
279 || clip.transform.is_some()
280 || !clip.color_keys.is_empty()
281 || !clip.transform_keys.is_empty()
282 || !clip.opacity_keys.is_empty()
283 || !clip.speed_keys.is_empty()
284 || clip.speed != crate::project::Speed::NORMAL
285 || clip.fade_in > 0
286 || clip.fade_out > 0
287 || clip.transition_out > 0
288 || clip.reversed
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294 use crate::color::ColorParams;
295 use crate::playback::PlaybackSession;
296 use crate::project::Lane;
297 use crate::scratch::Scratch;
298
299 fn asset(name: &str) -> PathBuf {
300 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
301 }
302
303 fn grade(brightness: f32) -> Option<ColorParams> {
304 Some(ColorParams {
305 brightness,
306 ..Default::default()
307 })
308 }
309
310 /// A render of frames 0..10 is what a seek into it plays from, and changing
311 /// the grade on its clip drops it: the one test this module carries.
312 #[test]
313 fn a_render_serves_its_frames_until_an_effect_changes() {
314 let dir = Scratch::dir("render-cache");
315 crate::envcfg::set("XDG_CACHE_HOME", &dir);
316 let mut session = PlaybackSession::open(asset("test_25fps.mp4")).expect("open the fixture");
317 assert!(session.set_color(Lane::V1, 0, grade(0.2)));
318 let (project, meta) = session.export_snapshot();
319 let job = start(project, meta, 0, 10).expect("a render starts");
320 for _ in 0..1200 {
321 if job.is_finished() {
322 break;
323 }
324 std::thread::sleep(std::time::Duration::from_millis(100));
325 }
326 let rendered = job.outcome().expect("finished").expect("rendered");
327 assert!(rendered.is_file(), "the render is on disk");
328
329 let fps = session.meta().frame_rate;
330 let mut served = false;
331 session.seek(2.0 / fps);
332 for _ in 0..400 {
333 if session.try_frame().is_some() {
334 served = true;
335 break;
336 }
337 std::thread::sleep(std::time::Duration::from_millis(5));
338 }
339 assert!(served, "a frame inside the render arrives");
340 assert!(session.playing_from_cache(), "the frame is read off the render");
341
342 assert!(session.set_color(Lane::V1, 0, grade(-0.2)));
343 let (project, meta) = session.export_snapshot();
344 assert!(at(&project, &meta, 2).is_none(), "the changed grade drops the render");
345 session.seek(2.0 / fps);
346 std::thread::sleep(std::time::Duration::from_millis(50));
347 session.try_frame();
348 assert!(!session.playing_from_cache(), "and playback composes live again");
349 }
350}