forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(engine): the stand-in decides one path, and the intra file keeps its marks

Browse files at this commit

eff035eeabe37912a07d63269c3c8dd22d627033Ahmet Kaan GümüşParent: 9717151627d623
Lane P's proxy workflow meets a main that had taken S's persistent decode
workers, E's pipelined export and E4's zero-copy encode.

* `start_span` keeps S's reuse door and P's single substitution point at
  once: `picture_path(source)` is resolved *before* the door and handed to
  both halves of it. A worker holding the film is then asked for a span of
  the stand-in, declines on the path it already has (`Worker::reseek`),
  and `set_proxies`' seek becomes a respawn on the other file -- while a
  span that did not change files still costs no thread and no VA-API init.
  Asking the project for the path at the door, as main did, would have
  left every proxied span opening a worker from scratch.
* `Enc::encode_dma` takes P's `intra` flag, which is not symmetry: a proxy
  of a file already small enough is coded at that file's own size
  (`proxy::size_for` -- `wanted` is true for HEVC and AV1 at any size), so
  an intraframe export's decoder and encoder can agree on a surface and
  the buffer goes straight across. Marked `false` there, an all-intra
  stand-in would have carried no sync point at all, which is the exact
  bug `gop_limit` was written against, reached by the other door.
* The five other conflicts were both sides adding a field: `drop_late`
  and `proxies` next to each other, in the struct and in all three opens.
* `enc_depth` is keyed by codec, so the intra seat takes H.264's two. Said
  in its doc rather than left to be re-derived: that seat is the same
  entrypoint with every inter dependency removed, so a picture there is
  finished no later than one on the seat the two was measured on.

`nm -D libengine_hw.so` lists sixteen: P's `vh_enc_open_intra` beside
E4's `vh_next_frame_dma`, `vh_enc_dma_geometry`, `vh_enc_frame_dma` and
main's `vh_seek`. `picture_path` still has exactly one call site outside
the tests, and it is in `playback` -- an export reads the film.

The intra seat and the zero-copy path are read, not run: every test that
would reach either is hardware-gated and the GPU is wedged.
crates/app/src/export_ui.rsmodified+7 -0
@@ -645,6 +645,13 @@ pub(crate) fn export_settings(
645 // caller that writes a file; the rest of them are asking about the645 // caller that writes a file; the rest of them are asking about the
646 // bitrate and the format.646 // bitrate and the format.
647 subtitles: Vec::new(),647 subtitles: Vec::new(),
648+ // Neither is a delivery setting: both belong to the stand-ins
649+ // [`engine::proxy`] writes -- every frame a key frame costs bits
650+ // nobody delivering wants, and a file kept in its source's colour
651+ // space is one for this editor to read back rather than to hand
652+ // anybody.
653+ intra_only: false,
654+ keep_source_colour: false,
648 }655 }
649 }656 }
650 657
crates/app/src/importing.rsmodified+37 -0
@@ -62,6 +62,43 @@ pub(crate) enum Wave {
62 Peaks(Arc<Vec<(f32, f32)>>),62 Peaks(Arc<Vec<(f32, f32)>>),
63 }63 }
64 64
65+/// What a source's stand-in is up to ([`engine::proxy`]). Kept per file and
66+/// filled like every other library fact -- presence means "asked", so a repaint
67+/// mid-encode cannot start a second one.
68+pub(crate) enum Proxy {
69+ /// The header is being read to find out whether this file wants one. Its
70+ /// own state because it is what makes "how many are in flight" a number:
71+ /// the answer comes back on a worker, and until it does this file may still
72+ /// turn into an encode.
73+ Asked,
74+ /// A file this machine cuts at speed as it is: no stand-in, and none
75+ /// wanted ([`engine::proxy::wanted`]).
76+ Native,
77+ /// Being made, in the background, while the film keeps playing.
78+ Making(engine::proxy::Job),
79+ /// There is one in the cache. What the switch actually plays.
80+ Ready,
81+ /// It could not be made: the film itself is what plays, and the row says
82+ /// so rather than leaving a bar that never fills.
83+ Failed,
84+}
85+
86+impl Proxy {
87+ /// What the library row says about it, or nothing at all for a file that
88+ /// never wanted one -- a row per source is not the place to announce that
89+ /// nothing is happening.
90+ pub(crate) fn detail(&self) -> String {
91+ match self {
92+ Self::Asked | Self::Native => String::new(),
93+ // Rounded down: a bar that says 100% while the encoder is still
94+ // writing is the one number a progress line must never show.
95+ Self::Making(job) => format!("proxy {}%", (job.progress() * 100.) as u32),
96+ Self::Ready => "proxy".to_string(),
97+ Self::Failed => "no proxy".to_string(),
98+ }
99+ }
100+}
101+
65 /// The import a worker is reading, as the line above the panel shows it. No102 /// The import a worker is reading, as the line above the panel shows it. No
66 /// fraction anywhere: neither read reports how far into the file it has come,103 /// fraction anywhere: neither read reports how far into the file it has come,
67 /// so what is honest is the file's name, the stage, and two clocks -- one that104 /// so what is honest is the file's name, the stage, and two clocks -- one that
crates/app/src/keymap.rsmodified+18 -1
@@ -110,6 +110,11 @@ actions! {
110 Mix,110 Mix,
111 ToggleSnap,111 ToggleSnap,
112 ToggleSubtitles,112 ToggleSubtitles,
113+ /// Cut on the stand-ins or on the films themselves
114+ /// ([`engine::proxy`]): what the picture is decoded from, and nothing
115+ /// else -- the sound and every export stay the film's whichever way it
116+ /// is set.
117+ ToggleProxies,
113 /// The window's own colours, which belong to the person looking at them and118 /// The window's own colours, which belong to the person looking at them and
114 /// not to the project: a list of the palettes, opened here and from the119 /// not to the project: a list of the palettes, opened here and from the
115 /// toolbar's Theme button. It was a build feature once, which made it a120 /// toolbar's Theme button. It was a build feature once, which made it a
@@ -173,6 +178,7 @@ impl ActionId {
173 ActionId::Mix => "Mix: track volumes and the limiter…",178 ActionId::Mix => "Mix: track volumes and the limiter…",
174 ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)",179 ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)",
175 ActionId::ToggleSubtitles => "Subtitles on / off over the picture",180 ActionId::ToggleSubtitles => "Subtitles on / off over the picture",
181+ ActionId::ToggleProxies => "Proxies on / off for the picture",
176 ActionId::Theme => "Theme: the window's colours…",182 ActionId::Theme => "Theme: the window's colours…",
177 ActionId::CancelExport => "Cancel export",183 ActionId::CancelExport => "Cancel export",
178 ActionId::ShowActions => "All actions and their keys…",184 ActionId::ShowActions => "All actions and their keys…",
@@ -227,6 +233,7 @@ impl ActionId {
227 ActionId::Mix => "mix",233 ActionId::Mix => "mix",
228 ActionId::ToggleSnap => "toggle-snap",234 ActionId::ToggleSnap => "toggle-snap",
229 ActionId::ToggleSubtitles => "toggle-subtitles",235 ActionId::ToggleSubtitles => "toggle-subtitles",
236+ ActionId::ToggleProxies => "toggle-proxies",
230 ActionId::Theme => "theme",237 ActionId::Theme => "theme",
231 ActionId::CancelExport => "cancel-export",238 ActionId::CancelExport => "cancel-export",
232 ActionId::ShowActions => "show-actions",239 ActionId::ShowActions => "show-actions",
@@ -279,6 +286,10 @@ impl ActionId {
279 | ActionId::ZoomOut286 | ActionId::ZoomOut
280 | ActionId::ZoomFit287 | ActionId::ZoomFit
281 | ActionId::ToggleSubtitles288 | ActionId::ToggleSubtitles
289+ // ...and which file the picture is decoded from, which changes
290+ // nothing that is saved and nothing that is exported: a stand-in
291+ // is what one watches while cutting, not what one delivers.
292+ | ActionId::ToggleProxies
282 // ...and what the whole window is painted in: it edits nothing at293 // ...and what the whole window is painted in: it edits nothing at
283 // all, it is what one is looking *with*.294 // all, it is what one is looking *with*.
284 | ActionId::Theme => Category::View,295 | ActionId::Theme => Category::View,
@@ -811,6 +822,11 @@ impl Keymap {
811 // the rest of the things one *looks* at, and nowhere near the822 // the rest of the things one *looks* at, and nowhere near the
812 // two keys that delete.823 // two keys that delete.
813 b(ActionId::ToggleSubtitles, "t", false),824 b(ActionId::ToggleSubtitles, "t", false),
825+ // The stand-ins take ctrl+p, the p of the word: the unshifted
826+ // one is the fit policy, and a ctrl chord is right for a switch
827+ // thrown once for a whole session rather than one wanted under
828+ // a hand -- the theme takes ctrl+h for that reason.
829+ b(ActionId::ToggleProxies, "p", true),
814 // The theme takes ctrl+h -- the h of the word, since "t" is the830 // The theme takes ctrl+h -- the h of the word, since "t" is the
815 // subtitles and ctrl+t takes one off -- and a ctrl chord because831 // subtitles and ctrl+t takes one off -- and a ctrl chord because
816 // it is a preference set once, not a stroke wanted under a hand832 // it is a preference set once, not a stroke wanted under a hand
@@ -1085,7 +1101,8 @@ mod tests {
1085 #[test]1101 #[test]
1086 fn every_default_stroke_reaches_its_action() {1102 fn every_default_stroke_reaches_its_action() {
1087 let k = Keymap::defaults();1103 let k = Keymap::defaults();
1088- assert_eq!(k.entries().len(), 49);1104+ assert_eq!(k.entries().len(), 50);
1105+ assert_eq!(k.lookup("p", true), Some(ActionId::ToggleProxies));
1089 assert_eq!(k.lookup("f1", false), Some(ActionId::ShowActions));1106 assert_eq!(k.lookup("f1", false), Some(ActionId::ShowActions));
1090 assert_eq!(k.lookup("h", true), Some(ActionId::Theme));1107 assert_eq!(k.lookup("h", true), Some(ActionId::Theme));
1091 assert_eq!(k.lookup("space", false), Some(ActionId::Play));1108 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
crates/app/src/layout.rsmodified+5 -0
@@ -38,6 +38,11 @@ pub(crate) const LABEL_MIN_W: f32 = 36.;
38 /// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade38 /// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade
39 /// is a second, finer pass over the visible span only, cached like `waves` is.39 /// is a second, finer pass over the visible span only, cached like `waves` is.
40 pub(crate) const WAVE_BPS: u32 = 40;40 pub(crate) const WAVE_BPS: u32 = 40;
41+/// How many stand-ins may be in flight at once -- the engine's own number, not
42+/// a second one that happens to agree: the proxy cache sweeps with room left
43+/// for exactly this many encodes ([`engine::proxy::reserve`]), so a front-end
44+/// that started more would put the disk past the cap by whatever it added.
45+pub(crate) const PROXIES_AT_ONCE: usize = engine::proxy::AT_ONCE;
41 /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,46 /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
42 /// and a path with a point per pixel is a path per repaint.47 /// and a path with a point per pixel is a path per repaint.
43 pub(crate) const WAVE_COL: f32 = 2.;48 pub(crate) const WAVE_COL: f32 = 2.;
crates/app/src/main.rsmodified+7 -0
@@ -149,6 +149,12 @@ struct Player {
149 /// the key is inserted the moment the decode is *started*: presence means149 /// the key is inserted the moment the decode is *started*: presence means
150 /// "asked", so a repaint mid-decode cannot ask again.150 /// "asked", so a repaint mid-decode cannot ask again.
151 waves: HashMap<(PathBuf, usize), Wave>,151 waves: HashMap<(PathBuf, usize), Wave>,
152+ /// What each source's stand-in is up to ([`engine::proxy`]), filled like
153+ /// `waves`: presence means "asked", so the encode is started once per file
154+ /// however many times the library is drawn. The switch that decides whether
155+ /// they are *played* is the session's own -- it is the project's and is
156+ /// saved with it, where this map is this window's view of the cache.
157+ proxies: HashMap<PathBuf, Proxy>,
152 /// Which audio streams each imported file has, as its header describes158 /// Which audio streams each imported file has, as its header describes
153 /// them: one library row per entry. Keyed and filled like `waves` --159 /// them: one library row per entry. Keyed and filled like `waves` --
154 /// presence means "asked" -- and an empty list is a silent file, which is160 /// presence means "asked" -- and an empty list is a silent file, which is
@@ -602,6 +608,7 @@ fn main() {
602 selected_asset: None,608 selected_asset: None,
603 library_tab: LibraryTab::Media,609 library_tab: LibraryTab::Media,
604 waves: HashMap::new(),610 waves: HashMap::new(),
611+ proxies: HashMap::new(),
605 streams: HashMap::new(),612 streams: HashMap::new(),
606 bitrates: HashMap::new(),613 bitrates: HashMap::new(),
607 sizes: HashMap::new(),614 sizes: HashMap::new(),
crates/app/src/player/actions.rsmodified+1 -0
@@ -87,6 +87,7 @@ impl Player {
87 ActionId::Mix => self.open_mix(None, cx),87 ActionId::Mix => self.open_mix(None, cx),
88 ActionId::ToggleSnap => self.toggle_snap(cx),88 ActionId::ToggleSnap => self.toggle_snap(cx),
89 ActionId::ToggleSubtitles => self.toggle_subtitles(cx),89 ActionId::ToggleSubtitles => self.toggle_subtitles(cx),
90+ ActionId::ToggleProxies => self.toggle_proxies(cx),
90 // The keyboard's door to the same list the toolbar button opens.91 // The keyboard's door to the same list the toolbar button opens.
91 // At the window's corner, since a stroke names no place -- and92 // At the window's corner, since a stroke names no place -- and
92 // [`menu_at`] keeps it on screen from there.93 // [`menu_at`] keeps it on screen from there.
crates/app/src/player/export.rsmodified+45 -0
@@ -111,6 +111,51 @@ impl Player {
111 })111 })
112 .detach();112 .detach();
113 }113 }
114+ // A stand-in for every film this machine cannot cut at speed, started
115+ // the moment the file arrives and made while the editor keeps running
116+ // ([`engine::proxy`]). Off the render thread for the reason the sync
117+ // walk above is -- the decision reads the same header -- and the encode
118+ // itself is the engine's own worker, so what comes back here is a
119+ // handle to poll and not a wait.
120+ for path in unseen_paths(session.sources(), &self.proxies) {
121+ // Two at a time, and the rest at the next repaint: a stand-in is a
122+ // whole film re-encoded, and a library of ten dropped at once would
123+ // otherwise start ten encodes fighting over the one hardware seat.
124+ // The unstarted ones simply stay out of the map, which is what
125+ // brings them back here ([`unseen_paths`]).
126+ if self.in_flight_proxies() >= PROXIES_AT_ONCE {
127+ break;
128+ }
129+ self.proxies.insert(path.clone(), Proxy::Asked);
130+ let started = cx.background_executor().spawn({
131+ let path = path.clone();
132+ async move { engine::proxy::generate_if_wanted(&path) }
133+ });
134+ cx.spawn(async move |this, cx| {
135+ let started = started.await;
136+ this.update(cx, |this, cx| {
137+ let state = match started {
138+ Ok(Some(job)) => Proxy::Making(job),
139+ // A film that needs none keeps the state it was
140+ // inserted with, which is what it is.
141+ Ok(None) => Proxy::Native,
142+ Err(e) => {
143+ let text = format!(
144+ "NO PROXY for {} — {e} — the film itself is what plays",
145+ file_name(&path)
146+ );
147+ eprintln!("{text}");
148+ this.notify_user(text.into());
149+ Proxy::Failed
150+ }
151+ };
152+ this.proxies.insert(path, state);
153+ cx.notify();
154+ })
155+ .ok();
156+ })
157+ .detach();
158+ }
114 for key in unseen_sources(session.sources(), &self.waves) {159 for key in unseen_sources(session.sources(), &self.waves) {
115 self.waves.insert(key.clone(), Wave::Loading);160 self.waves.insert(key.clone(), Wave::Loading);
116 let decoded = cx.background_executor().spawn({161 let decoded = cx.background_executor().spawn({
crates/app/src/player/library.rsmodified+111 -0
@@ -303,6 +303,117 @@ impl Player {
303 /// ...and starts whatever is queued behind it, which is the one place the303 /// ...and starts whatever is queued behind it, which is the one place the
304 /// files argv named can begin: they are put in the queue before there is a304 /// files argv named can begin: they are put in the queue before there is a
305 /// context to spawn a worker from.305 /// context to spawn a worker from.
306+ /// Takes each finished stand-in's verdict, once. Sampled here rather than
307+ /// while drawing, for [`Player::poll_export`]'s reason -- and it is the one
308+ /// place a proxy job's outcome is read, so "ready" on a row and the file in
309+ /// the cache are the same fact.
310+ ///
311+ /// Nothing waits for it: until a proxy is ready the film itself is what
312+ /// plays, switch or no switch ([`engine::PlaybackSession::picture_path`]),
313+ /// so a failure costs a line and no more.
314+ pub(crate) fn poll_proxies(&mut self, cx: &mut Context<Self>) {
315+ let done: Vec<(PathBuf, engine::Result<PathBuf>)> = self
316+ .proxies
317+ .iter()
318+ .filter_map(|(path, state)| match state {
319+ Proxy::Making(job) => Some((path.clone(), job.outcome()?)),
320+ _ => None,
321+ })
322+ .collect();
323+ for (path, outcome) in done {
324+ let text = match &outcome {
325+ Ok(_) => format!(
326+ "PROXY READY for {} — Proxies on cuts on it",
327+ file_name(&path)
328+ ),
329+ Err(e) => format!(
330+ "PROXY FAILED for {} — {e} — the film itself is what plays",
331+ file_name(&path)
332+ ),
333+ };
334+ eprintln!("{text}");
335+ self.notify_user(text.into());
336+ let state = match outcome {
337+ Ok(_) => Proxy::Ready,
338+ Err(_) => Proxy::Failed,
339+ };
340+ self.proxies.insert(path, state);
341+ cx.notify();
342+ }
343+ }
344+
345+ /// What the Proxies button says after the state: how far the stand-ins
346+ /// have got, since "on" with nothing made yet and "on" with the whole
347+ /// library standing in are two different things to be looking at. Empty
348+ /// where no film here wants one, which is the ordinary case.
349+ pub(crate) fn proxy_tail(&self) -> String {
350+ let making = self.proxies.values().filter_map(|p| match p {
351+ Proxy::Making(job) => Some(job.progress()),
352+ _ => None,
353+ });
354+ // The one furthest along would read as done while three others sit at
355+ // nothing: the *least* finished is what the button reports.
356+ match making.fold(f32::INFINITY, f32::min) {
357+ least if least.is_finite() => format!(" · {}%", (least * 100.) as u32),
358+ _ => String::new(),
359+ }
360+ }
361+
362+ /// Whether any stand-in is still being made -- what keeps the frame loop
363+ /// alive while one is, so its percentage moves on screen.
364+ pub(crate) fn making_proxies(&self) -> bool {
365+ self.proxies
366+ .values()
367+ .any(|p| matches!(p, Proxy::Making(_)))
368+ }
369+
370+ /// How many films are between "shall we?" and "done": the number the start
371+ /// of another is held against ([`PROXIES_AT_ONCE`]). A header being read
372+ /// counts, because the answer may be an encode.
373+ pub(crate) fn in_flight_proxies(&self) -> usize {
374+ self.proxies
375+ .values()
376+ .filter(|p| matches!(p, Proxy::Asked | Proxy::Making(_)))
377+ .count()
378+ }
379+
380+ /// Cuts on the stand-ins, or on the films themselves. The picture and only
381+ /// the picture: the sound is the film's either way, and so is every frame
382+ /// an export writes.
383+ pub(crate) fn toggle_proxies(&mut self, cx: &mut Context<Self>) {
384+ let Some(session) = &mut self.session else {
385+ return;
386+ };
387+ let on = !session.proxies();
388+ session.set_proxies(on);
389+ // What is really under the switch, said in the same breath: a project
390+ // whose films have no stand-in yet would otherwise read as a switch
391+ // that does nothing.
392+ let ready = self
393+ .proxies
394+ .values()
395+ .filter(|p| matches!(p, Proxy::Ready))
396+ .count();
397+ let making = self
398+ .proxies
399+ .values()
400+ .filter(|p| matches!(p, Proxy::Making(_)))
401+ .count();
402+ let text = match (on, ready, making) {
403+ (false, ..) => "PROXIES OFF — the films themselves are what play".to_string(),
404+ (true, 0, 0) => {
405+ "PROXIES ON — no film here has one, so the films themselves play".to_string()
406+ }
407+ (true, 0, n) => format!("PROXIES ON — {n} still being made; the films play until then"),
408+ (true, n, 0) => format!("PROXIES ON — cutting on {n}"),
409+ (true, n, m) => format!("PROXIES ON — cutting on {n}, {m} still being made"),
410+ };
411+ eprintln!("{text}");
412+ self.notify_user(text.into());
413+ self.reset_after_reseek();
414+ cx.notify();
415+ }
416+
306 pub(crate) fn poll_import(&mut self, cx: &mut Context<Self>) {417 pub(crate) fn poll_import(&mut self, cx: &mut Context<Self>) {
307 match &mut self.importing {418 match &mut self.importing {
308 Some(import) => {419 Some(import) => {
crates/app/src/render.rsmodified+5 -0
@@ -23,6 +23,7 @@ impl Render for Player {
23 self.poll_export();23 self.poll_export();
24 self.poll_import(cx);24 self.poll_import(cx);
25 self.poll_silence();25 self.poll_silence();
26+ self.poll_proxies(cx);
26 // Every way a source can arrive -- argv, an import, a project load --27 // Every way a source can arrive -- argv, an import, a project load --
27 // has been through a repaint by the time its clips are drawn, so this28 // has been through a repaint by the time its clips are drawn, so this
28 // is the one place that has to notice a new one.29 // is the one place that has to notice a new one.
@@ -57,6 +58,10 @@ impl Render for Player {
57 // the screen on a repaint, and a still line is the very thing this58 // the screen on a repaint, and a still line is the very thing this
58 // card was rewritten to disprove.59 // card was rewritten to disprove.
59 || self.silence_scan.is_some()60 || self.silence_scan.is_some()
61+ // ...and a stand-in being made: its percentage on the library row
62+ // only reaches the screen on a repaint, and a bar that never moves
63+ // is exactly what a person reads as a hung encode.
64+ || self.making_proxies()
60 {65 {
61 window.request_animation_frame();66 window.request_animation_frame();
62 }67 }
crates/app/src/ui/inspector.rsmodified+18 -0
@@ -284,6 +284,24 @@ impl Player {
284 this.open_picker(Pick::Tone, event.position(), cx)284 this.open_picker(Pick::Tone, event.position(), cx)
285 }),285 }),
286 ))286 ))
287+ // Its own rect and a label that *is* the state, the rule
288+ // the snap toggle writes down: a button that resized itself
289+ // on every press made the row shuffle under the pointer.
290+ .child(self.action_control(
291+ "proxies",
292+ TONE_SLOT_W,
293+ BG_RAISED(),
294+ None,
295+ match self.session.as_ref().map(PlaybackSession::proxies) {
296+ Some(true) => format!("Proxies on{}", self.proxy_tail()),
297+ Some(false) => format!("Proxies off{}", self.proxy_tail()),
298+ None => "Proxies".to_string(),
299+ },
300+ "cuts on small stand-ins of the big films; the sound and every export \
301+ stay the film's own",
302+ ActionId::ToggleProxies,
303+ cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_proxies(cx)),
304+ ))
287 .child(self.action_control(305 .child(self.action_control(
288 "inspect-mix",306 "inspect-mix",
289 0.,307 0.,
crates/app/src/ui/library.rsmodified+10 -0
@@ -112,6 +112,16 @@ impl Player {
112 &timecode(f64::from(row.frames) / self.fps, self.fps),112 &timecode(f64::from(row.frames) / self.fps, self.fps),
113 ),113 ),
114 };114 };
115+ // ...and what this file's stand-in is up to, after its length: a
116+ // percentage while one is being made, the word while there is one,
117+ // and nothing at all for a film that wants none ([`Proxy::detail`]).
118+ let under = join_detail(
119+ &under,
120+ &self
121+ .proxies
122+ .get(&row.path)
123+ .map_or_else(String::new, Proxy::detail),
124+ );
115 let usable = row.unusable.is_none();125 let usable = row.unusable.is_none();
116 let (path, stream) = (row.path.clone(), row.stream);126 let (path, stream) = (row.path.clone(), row.stream);
117 let dragged = (path.clone(), stream);127 let dragged = (path.clone(), stream);
crates/engine-hw/src/lib.rsmodified+125 -1
@@ -975,6 +975,30 @@ pub unsafe extern "C" fn vh_caps(out: *mut VhCaps) -> i32 {
975 .unwrap_or(-1)975 .unwrap_or(-1)
976 }976 }
977 977
978+/// How many pictures a group of them holds -- the low-delay predictor's
979+/// `limit`, which is the *only* thing that decides whether a picture is an IDR.
980+///
981+/// One for an intra-only seat, and that is not a tuning: the predictor counts
982+/// `counter % limit`, so a limit of one pins the counter at zero, every picture
983+/// takes the keyframe branch with `idr` set, and every access unit carries a
984+/// fresh SPS and PPS
985+/// (`cros-codecs/encoder/stateless/predictor.rs:107`, `h264/predictor.rs:139`).
986+/// Two seconds otherwise, which is what a seek may land on in an ordinary file.
987+///
988+/// Forcing a key frame per picture is a different thing and does *not* make an
989+/// intra file: that path passes `idr = false`, writes no parameter sets, and
990+/// [`fix_slice_nal_headers`] then marks the slice non-IDR -- how a 60-picture
991+/// "all-intra" hardware proxy came out with one sync point in it.
992+fn gop_limit(framerate: u32, intra_only: bool) -> u16 {
993+ match intra_only {
994+ true => 1,
995+ // Saturating and clamped: the caller pins the rate to 1..240 before it
996+ // gets here, and a limit that wrapped to zero would divide by zero in
997+ // the predictor -- a guard costs nothing next to that.
998+ false => framerate.saturating_mul(2).clamp(1, u16::MAX as u32) as u16,
999+ }
1000+}
1001+
978 fn align16(v: u32) -> u32 {1002 fn align16(v: u32) -> u32 {
979 v.div_ceil(16) * 161003 v.div_ceil(16) * 16
980 }1004 }
@@ -1096,6 +1120,11 @@ const ENC_DEPTH: usize = 2;
1096 /// the GPU has been unavailable since the measurement was possible. They keep1120 /// the GPU has been unavailable since the measurement was possible. They keep
1097 /// the old one-buffer behaviour -- the picture coded before the next is1121 /// the old one-buffer behaviour -- the picture coded before the next is
1098 /// written, exactly as every seat did before -- until someone measures them.1122 /// written, exactly as every seat did before -- until someone measures them.
1123+///
1124+/// The intra-only seat ([`vh_enc_open_intra`]) is keyed by codec like any other
1125+/// and therefore takes the two, which is the answer and not an oversight: it is
1126+/// the same H.264 entrypoint with every inter dependency removed, so a picture
1127+/// there is finished no later than one on the seat the two was measured on.
1099 fn enc_depth(codec: EncCodec) -> usize {1128 fn enc_depth(codec: EncCodec) -> usize {
1100 match codec {1129 match codec {
1101 EncCodec::H264 => ENC_DEPTH,1130 EncCodec::H264 => ENC_DEPTH,
@@ -1124,6 +1153,19 @@ impl EncSession {
1124 fps_den: u32,1153 fps_den: u32,
1125 bitrate: u64,1154 bitrate: u64,
1126 codec: EncCodec,1155 codec: EncCodec,
1156+ ) -> Option<Self> {
1157+ Self::open_seat(width, height, fps_num, fps_den, bitrate, codec, false)
1158+ }
1159+
1160+ #[allow(clippy::too_many_arguments)]
1161+ fn open_seat(
1162+ width: u32,
1163+ height: u32,
1164+ fps_num: u32,
1165+ fps_den: u32,
1166+ bitrate: u64,
1167+ codec: EncCodec,
1168+ intra_only: bool,
1127 ) -> Option<Self> {1169 ) -> Option<Self> {
1128 // NV12 chroma is half resolution, so odd dimensions have no packing;1170 // NV12 chroma is half resolution, so odd dimensions have no packing;
1129 // and radeonsi refuses encode contexts below 64x64 (measured).1171 // and radeonsi refuses encode contexts below 64x64 (measured).
@@ -1173,8 +1215,21 @@ impl EncSession {
1173 let low_power = entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP);1215 let low_power = entrypoints.contains(&VAEntrypoint::VAEntrypointEncSliceLP);
1174 // No B-frames on either codec: coded order stays display order, which is1216 // No B-frames on either codec: coded order stays display order, which is
1175 // what both muxers' duration-only timing assumes.1217 // what both muxers' duration-only timing assumes.
1218+ //
1219+ // A limit of **1** is what makes a seat intra-only, and it is the whole
1220+ // mechanism: the low-delay predictor counts `counter % limit`, so with a
1221+ // limit of one that counter is always zero, every picture takes the
1222+ // keyframe branch *with `idr` set*, and each access unit is therefore an
1223+ // IDR carrying a fresh SPS and PPS
1224+ // (`cros-codecs/encoder/stateless/predictor.rs:107` and
1225+ // `h264/predictor.rs:139-163`). Forcing a key frame per picture is not
1226+ // the same thing and does not do it: `force_keyframe` takes the same
1227+ // branch with `idr` **false**, so no parameter sets are written, and a
1228+ // driver that leaves the NAL header byte at zero then gets its slices
1229+ // marked non-IDR by [`fix_slice_nal_headers`] -- which is exactly how a
1230+ // 60-frame "all-intra" hardware proxy came out with one sync point in it.
1176 let pred_structure = PredictionStructure::LowDelay {1231 let pred_structure = PredictionStructure::LowDelay {
1177- limit: (framerate * 2) as u16,1232+ limit: gop_limit(framerate, intra_only),
1178 };1233 };
1179 let encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>> = match codec {1234 let encoder: Box<dyn VideoEncoder<GenericDmaVideoFrame>> = match codec {
1180 EncCodec::Av1 => {1235 EncCodec::Av1 => {
@@ -1543,6 +1598,41 @@ pub extern "C" fn vh_enc_open(
1543 .unwrap_or(std::ptr::null_mut())1598 .unwrap_or(std::ptr::null_mut())
1544 }1599 }
1545 1600
1601+/// The same H.264 seat, **intra-only**: every access unit it hands back is an
1602+/// IDR carrying its own SPS and PPS, so every frame of the file is a frame a
1603+/// decoder may be started from. What a proxy is coded with
1604+/// (`engine::proxy`), and never a delivery -- the file is much bigger for it.
1605+///
1606+/// A symbol of its own rather than a flag on [`vh_enc_open`], so that a plugin
1607+/// built before this existed simply has no intra seat and the caller falls back
1608+/// to the software encoder (whose `gop_size = 1` says the same thing) instead of
1609+/// being handed a long-GOP file that claims to be all-intra. The session it
1610+/// returns is fed, drained and closed through the very same three entry points.
1611+#[unsafe(no_mangle)]
1612+pub extern "C" fn vh_enc_open_intra(
1613+ width: u32,
1614+ height: u32,
1615+ fps_num: u32,
1616+ fps_den: u32,
1617+ bitrate: u64,
1618+) -> *mut c_void {
1619+ catch_unwind(AssertUnwindSafe(|| {
1620+ match EncSession::open_seat(
1621+ width,
1622+ height,
1623+ fps_num,
1624+ fps_den,
1625+ bitrate,
1626+ EncCodec::H264,
1627+ true,
1628+ ) {
1629+ Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
1630+ None => std::ptr::null_mut(),
1631+ }
1632+ }))
1633+ .unwrap_or(std::ptr::null_mut())
1634+}
1635+
1546 /// The same, coding AV1 instead of H.264: null unless this GPU has an AV11636 /// The same, coding AV1 instead of H.264: null unless this GPU has an AV1
1547 /// encode entrypoint, which is recent hardware -- the caller then encodes AV1 in1637 /// encode entrypoint, which is recent hardware -- the caller then encodes AV1 in
1548 /// software instead. `bitrate` is not used by this codec (see `EncSession::open`:1638 /// software instead. `bitrate` is not used by this codec (see `EncSession::open`:
@@ -1758,6 +1848,40 @@ pub unsafe extern "C" fn vh_enc_close(session: *mut c_void) {
1758 mod tests {1848 mod tests {
1759 use super::*;1849 use super::*;
1760 1850
1851+ /// The one number that decides whether a hardware file is intra-only, and
1852+ /// the one this seat got wrong: a proxy asks for a group of one picture, so
1853+ /// every picture is an IDR with its own parameter sets. Needs no GPU --
1854+ /// which is the point, since the seat itself cannot be opened without one.
1855+ #[test]
1856+ fn an_intra_seat_asks_for_a_group_of_one_picture() {
1857+ assert_eq!(gop_limit(30, true), 1, "a proxy is every frame a start");
1858+ assert_eq!(gop_limit(24, true), 1);
1859+ // ...and an ordinary export keeps its two seconds between them.
1860+ assert_eq!(gop_limit(30, false), 60);
1861+ assert_eq!(gop_limit(24, false), 48);
1862+ // A rate no file has, and the clamp that keeps the limit a `u16`
1863+ // rather than a wrapped one: `0` would divide by zero in the predictor.
1864+ assert_eq!(gop_limit(0, false), 1);
1865+ assert_eq!(gop_limit(u32::MAX, false), u16::MAX);
1866+ }
1867+
1868+ /// The other half of the same fault: a slice is marked IDR only where the
1869+ /// access unit carries an SPS, so a "forced key frame" that writes no
1870+ /// parameter sets reads back as an ordinary I picture -- no decoder starts
1871+ /// there, and `sync_points` does not count it.
1872+ #[test]
1873+ fn only_a_unit_carrying_parameter_sets_is_marked_idr() {
1874+ // SPS (0x67) + PPS (0x68) + a slice the driver left at zero.
1875+ let mut with_sets = vec![0, 0, 1, 0x67, 9, 0, 0, 1, 0x68, 9, 0, 0, 1, 0x00, 9];
1876+ fix_slice_nal_headers(&mut with_sets);
1877+ assert_eq!(with_sets[13], 0x65, "IDR slice after an SPS");
1878+ // The same unit without them: a key frame the encoder was merely asked
1879+ // for, which is what the hardware proxy used to be full of.
1880+ let mut bare = vec![0, 0, 1, 0x00, 9];
1881+ fix_slice_nal_headers(&mut bare);
1882+ assert_eq!(bare[3], 0x41, "no parameter sets, no IDR");
1883+ }
1884+
1761 /// Runs against whatever GPU this machine has -- and passes on one with no1885 /// Runs against whatever GPU this machine has -- and passes on one with no
1762 /// VA-API at all, which is exactly what `None` means here. What it pins is1886 /// VA-API at all, which is exactly what `None` means here. What it pins is
1763 /// the *shape* of the answer, the contents being the driver's: nothing may1887 /// the *shape* of the answer, the contents being the driver's: nothing may
crates/engine/src/demux.rsmodified+103 -22
@@ -180,6 +180,40 @@ fn mp4_codec(fourcc: &[u8; 4]) -> Option<Codec> {
180 .map(|&(codec, ..)| codec)180 .map(|&(codec, ..)| codec)
181 }181 }
182 182
183+/// The one refusal that is an **answer**: this file carries no picture at all
184+/// that this engine reads -- a song in a video container, an audio-only mp4 or
185+/// Matroska, a `.mka` under any name.
186+///
187+/// A type rather than a sentence, because two callers want two different things
188+/// from it. A front-end shows its `Display`, which is the words it always was,
189+/// and refuses the import by them. [`crate::proxy`] wants to tell it from *"this
190+/// file is broken"*: a song is not a film to stand in for and saying "NO PROXY"
191+/// about one is a refusal nobody asked for, while a film that will not open is
192+/// worth a line. Neither could tell them apart by matching on prose, and prose
193+/// is the one thing in this engine that is free to be reworded.
194+///
195+/// A file whose picture is in a codec nothing here decodes is **not** this: it
196+/// has a video track, the refusal names the codec, and that stays loud.
197+#[derive(Debug)]
198+pub struct NoVideoTrack(String);
199+
200+impl std::fmt::Display for NoVideoTrack {
201+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202+ f.write_str(&self.0)
203+ }
204+}
205+
206+impl std::error::Error for NoVideoTrack {}
207+
208+impl NoVideoTrack {
209+ /// Whether `error` is one of these, however deep in a `Box` it is: the
210+ /// question [`crate::proxy`] asks, in one place so no caller downcasts by
211+ /// hand.
212+ pub fn is_it(error: &crate::Error) -> bool {
213+ error.downcast_ref::<Self>().is_some()
214+ }
215+}
216+
183 #[derive(Debug, Clone, Copy, PartialEq)]217 #[derive(Debug, Clone, Copy, PartialEq)]
184 pub struct VideoMeta {218 pub struct VideoMeta {
185 pub width: u32,219 pub width: u32,
@@ -822,6 +856,31 @@ impl Mp4Demuxer {
822 self.next_sample = chosen;856 self.next_sample = chosen;
823 i64::from(chosen) - i64::from(self.first_sample)857 i64::from(chosen) - i64::from(self.first_sample)
824 }858 }
859+
860+ /// Every frame a decoder may be started from, by the index this engine
861+ /// counts a source's frames in -- the sample table's own answer, which is
862+ /// why an mp4 costs no walk to ask ([`sync_points`]). A track with no `stss`
863+ /// box is every frame, which is what the box's absence means.
864+ fn sync_frames(&self) -> Vec<u32> {
865+ let frames = self.sample_count.saturating_sub(self.first_sample - 1);
866+ if self.sync_samples.is_empty() {
867+ return (0..frames).collect();
868+ }
869+ // With composition offsets in play a sample id is not a frame index, and
870+ // the display-order table beside it is the one that answers -- the split
871+ // [`Self::seek_to_sync_at_or_before`] makes, for its reason.
872+ if !self.sync_display.is_empty() {
873+ return self
874+ .sync_display
875+ .iter()
876+ .filter_map(|&(display, _)| display.checked_sub(self.first_display))
877+ .collect();
878+ }
879+ self.sync_samples
880+ .iter()
881+ .filter_map(|&id| id.checked_sub(self.first_sample))
882+ .collect()
883+ }
825 }884 }
826 885
827 /// One Matroska block of an indexed track: where its bytes are, whether a886 /// One Matroska block of an indexed track: where its bytes are, whether a
@@ -969,10 +1028,14 @@ impl MkvDemuxer {
969 None => format!(1028 None => format!(
970 "{codec} video in a Matroska file is not supported — AV1, HEVC, H.264 and VP9 are"1029 "{codec} video in a Matroska file is not supported — AV1, HEVC, H.264 and VP9 are"
971 ),1030 ),
972- },1031+ }
973- None => "this Matroska file has no video track".to_string(),1032+ .into(),
974- }1033+ // No picture in it *at all*, which is a fact about the file
975- .into());1034+ // and not a fault: [`NoVideoTrack`] says why that is a type.
1035+ None => crate::Error::from(NoVideoTrack(
1036+ "this Matroska file has no video track".to_string(),
1037+ )),
1038+ });
976 }1039 }
977 };1040 };
978 // A picture nothing here can put back together is a refusal at the door,1041 // A picture nothing here can put back together is a refusal at the door,
@@ -1555,15 +1618,18 @@ pub struct CodedBlock<'a> {
1555 /// ([`crate::export::planned_seats`] is the same question asked of a whole1618 /// ([`crate::export::planned_seats`] is the same question asked of a whole
1556 /// timeline).1619 /// timeline).
1557 ///1620 ///
1558-/// Empty for anything that is not Matroska, which is exactly the set of files1621+/// Empty for a file that will not open, and for a Matroska one whose clusters
1559-/// the copy path refuses anyway, and for a file whose clusters cannot be walked.1622+/// cannot be walked.
1560 ///1623 ///
1561-/// Costs that walk, once per file (6.7 s on a 12.9 GB film, then a sidecar read1624+/// An mp4 answers off its `stss` table for nothing; Matroska costs the walk,
1562-/// of a few milliseconds -- [`MkvDemuxer::is_sync`]): ask it off a render1625+/// once per file (6.7 s on a 12.9 GB film, then a sidecar read of a few
1563-/// thread.1626+/// milliseconds -- [`MkvDemuxer::is_sync`]): ask it off a render thread.
1564 pub fn sync_points(path: &Path) -> Vec<u32> {1627 pub fn sync_points(path: &Path) -> Vec<u32> {
1565 if !is_matroska(path) {1628 if !is_matroska(path) {
1566- return Vec::new();1629+ return match Demuxer::open(path) {
1630+ Ok((_, Demuxer::Mp4(mp4))) => mp4.sync_frames(),
1631+ _ => Vec::new(),
1632+ };
1567 }1633 }
1568 let Ok((_, Demuxer::Mkv(mut demuxer))) = Demuxer::open(path) else {1634 let Ok((_, Demuxer::Mkv(mut demuxer))) = Demuxer::open(path) else {
1569 return Vec::new();1635 return Vec::new();
@@ -2395,10 +2461,15 @@ fn mp4_no_video<R>(path: &Path, reader: &Mp4Reader<R>) -> crate::Error {
2395 None => {2461 None => {
2396 format!("{kind} video in this mp4 is not supported — H.264, HEVC, VP9 and AV1 are")2462 format!("{kind} video in this mp4 is not supported — H.264, HEVC, VP9 and AV1 are")
2397 }2463 }
2398- },2464+ }
2399- None => "no H.264, HEVC, VP9 or AV1 video track in file".to_string(),2465+ .into(),
2466+ // Nothing with a picture in it that this reads -- an audio-only mp4,
2467+ // which is a thing a person really does hand an editor. The Matroska
2468+ // door's own answer, and the same type for the same reason.
2469+ None => crate::Error::from(NoVideoTrack(
2470+ "no H.264, HEVC, VP9 or AV1 video track in file".to_string(),
2471+ )),
2400 }2472 }
2401- .into()
2402 }2473 }
2403 2474
2404 /// Bits per luma sample out of a VP9 keyframe's uncompressed header (VP92475 /// Bits per luma sample out of a VP9 keyframe's uncompressed header (VP9
@@ -2897,7 +2968,11 @@ impl IndexKey {
2897 /// picture track) and the directory is the user's own cache to delete, but a2968 /// picture track) and the directory is the user's own cache to delete, but a
2898 /// size-capped LRU sweep at open is the upgrade path if it ever matters.2969 /// size-capped LRU sweep at open is the upgrade path if it ever matters.
2899 fn sidecar(&self) -> Option<PathBuf> {2970 fn sidecar(&self) -> Option<PathBuf> {
2900- let dir = index_dir(std::env::var_os("XDG_CACHE_HOME"), std::env::var_os("HOME"))?;2971+ let dir = cache_dir(
2972+ std::env::var_os("XDG_CACHE_HOME"),
2973+ std::env::var_os("HOME"),
2974+ "mkvindex",
2975+ )?;
2901 Some(dir.join(format!(2976 Some(dir.join(format!(
2902 "{:016x}-{}.idx",2977 "{:016x}-{}.idx",
2903 fnv1a(self.path.as_os_str().as_encoded_bytes()),2978 fnv1a(self.path.as_os_str().as_encoded_bytes()),
@@ -2906,25 +2981,31 @@ impl IndexKey {
2906 }2981 }
2907 }2982 }
2908 2983
2909-/// The path rule, with the environment handed in so it can be checked, as2984+/// The path rule for one of this engine's cache directories -- `sub` names
2910-/// `keymap::config_path_in` is on the config side. An empty `XDG_CACHE_HOME` is2985+/// which (`mkvindex` here, `proxies` for [`crate::proxy`]) -- with the
2911-/// one the spec says to ignore; with no `HOME` either there is nowhere to put a2986+/// environment handed in so it can be checked, as `keymap::config_path_in` is
2912-/// cache, and `None` -- always walk -- beats littering the working directory.2987+/// on the config side. An empty `XDG_CACHE_HOME` is one the spec says to
2913-fn index_dir(xdg: Option<OsString>, home: Option<OsString>) -> Option<PathBuf> {2988+/// ignore; with no `HOME` either there is nowhere to put a cache, and `None` --
2989+/// always walk -- beats littering the working directory.
2990+pub(crate) fn cache_dir(
2991+ xdg: Option<OsString>,
2992+ home: Option<OsString>,
2993+ sub: &str,
2994+) -> Option<PathBuf> {
2914 xdg.filter(|v| !v.is_empty())2995 xdg.filter(|v| !v.is_empty())
2915 .map(PathBuf::from)2996 .map(PathBuf::from)
2916 .or_else(|| {2997 .or_else(|| {
2917 home.filter(|v| !v.is_empty())2998 home.filter(|v| !v.is_empty())
2918 .map(|h| PathBuf::from(h).join(".cache"))2999 .map(|h| PathBuf::from(h).join(".cache"))
2919 })3000 })
2920- .map(|dir| dir.join("edith").join("mkvindex"))3001+ .map(|dir| dir.join("edith").join(sub))
2921 }3002 }
2922 3003
2923 /// FNV-1a, 64-bit: what names a sidecar and what checks it. Not a cryptographic3004 /// FNV-1a, 64-bit: what names a sidecar and what checks it. Not a cryptographic
2924 /// hash and not asked to be -- nothing here is adversarial. It is the guard that3005 /// hash and not asked to be -- nothing here is adversarial. It is the guard that
2925 /// turns a half-written or scrambled file into a miss; a *name* collision is3006 /// turns a half-written or scrambled file into a miss; a *name* collision is
2926 /// caught by the key inside the file, which is compared field by field.3007 /// caught by the key inside the file, which is compared field by field.
2927-fn fnv1a(bytes: &[u8]) -> u64 {3008+pub(crate) fn fnv1a(bytes: &[u8]) -> u64 {
2928 let mut hash = 0xcbf2_9ce4_8422_2325u64;3009 let mut hash = 0xcbf2_9ce4_8422_2325u64;
2929 for &b in bytes {3010 for &b in bytes {
2930 hash ^= u64::from(b);3011 hash ^= u64::from(b);
@@ -4457,7 +4538,7 @@ mod tests {
4457 #[test]4538 #[test]
4458 fn the_index_directory_follows_xdg() {4539 fn the_index_directory_follows_xdg() {
4459 let dir = |xdg: Option<&str>, home: Option<&str>| {4540 let dir = |xdg: Option<&str>, home: Option<&str>| {
4460- index_dir(xdg.map(OsString::from), home.map(OsString::from))4541+ cache_dir(xdg.map(OsString::from), home.map(OsString::from), "mkvindex")
4461 };4542 };
4462 assert_eq!(4543 assert_eq!(
4463 dir(Some("/x/cache"), Some("/home/u")),4544 dir(Some("/x/cache"), Some("/home/u")),
crates/engine/src/edith.rsmodified+131 -22
@@ -1,11 +1,12 @@
1 //! The project file: a line of text per thing, and nothing else.1 //! The project file: a line of text per thing, and nothing else.
2 //!2 //!
3 //! ```text3 //! ```text
4-//! edith 114+//! edith 12
5 //! playhead 905 //! playhead 90
6 //! resolution 1920 10806 //! resolution 1920 1080
7 //! fps 30.07 //! fps 30.0
8 //! tonemap vivid8 //! tonemap vivid
9+//! proxy on
9 //! limiter -1.0 on10 //! limiter -1.0 on
10 //! source 0 test_av.mp411 //! source 0 test_av.mp4
11 //! source 1 /elsewhere/test_av2.mp412 //! source 1 /elsewhere/test_av2.mp4
@@ -44,6 +45,13 @@
44 //! project holding no HDR media, and one whose owner never picked, are the bytes45 //! project holding no HDR media, and one whose owner never picked, are the bytes
45 //! they were.46 //! they were.
46 //!47 //!
48+//! The `proxy` line is whether this project is cut on the stand-ins
49+//! ([`crate::proxy`]) rather than on the films themselves, spelled `on` or
50+//! `off`. Left out when it is off, which is what every dialect before v12 was.
51+//! *Which* sources have a stand-in is not written: a proxy is found by the
52+//! film's own path, length and modification time, so the cache is the only
53+//! answer and a project file cannot go stale about it.
54+//!
47 //! The `limiter` line is the master limiter over the whole mix55 //! The `limiter` line is the master limiter over the whole mix
48 //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit,56 //! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit,
49 //! spelled `on` or `off`. Left out when it is the default, which is off.57 //! spelled `on` or `off`. Left out when it is the default, which is off.
@@ -100,7 +108,9 @@
100 //! is the only way an empty lane could still be there on the way back. A lane108 //! is the only way an empty lane could still be there on the way back. A lane
101 //! number may not skip one of its kind.109 //! number may not skip one of its kind.
102 //!110 //!
103-//! **Version 10** was this without the `tonemap` line: such a project is shown111+//! **Version 11** was this without the `proxy` line: such a project is cut on
112+//! its films themselves, which is all any project could do.
113+//! **Version 10** was that without the `tonemap` line: such a project is shown
104 //! in the reference rendition, which is the only one there was.114 //! in the reference rendition, which is the only one there was.
105 //! **Version 9** was that without the `subtitle` lines: such a project shows no115 //! **Version 9** was that without the `subtitle` lines: such a project shows no
106 //! subtitles, which is all any project could do.116 //! subtitles, which is all any project could do.
@@ -159,7 +169,8 @@ use crate::subtitle::SubtitleTrack;
159 169
160 /// What [`save`] writes. Read support goes back to `edith 1`; see the module170 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
161 /// docs for what those dialects looked like.171 /// docs for what those dialects looked like.
162-const MAGIC: &[u8] = b"edith 11";172+const MAGIC: &[u8] = b"edith 12";
173+const MAGIC_V11: &[u8] = b"edith 11";
163 const MAGIC_V10: &[u8] = b"edith 10";174 const MAGIC_V10: &[u8] = b"edith 10";
164 const MAGIC_V9: &[u8] = b"edith 9";175 const MAGIC_V9: &[u8] = b"edith 9";
165 const MAGIC_V8: &[u8] = b"edith 8";176 const MAGIC_V8: &[u8] = b"edith 8";
@@ -214,6 +225,11 @@ pub struct Document {
214 /// for a v11 file that leaves the line out, which both mean the published225 /// for a v11 file that leaves the line out, which both mean the published
215 /// conversion -- the only one those projects had.226 /// conversion -- the only one those projects had.
216 pub tone: crate::tonemap::Preset,227 pub tone: crate::tonemap::Preset,
228+ /// Whether the films are cut on their stand-ins ([`crate::proxy`]). `false`
229+ /// for every dialect before v12 and for a v12 file that leaves the line
230+ /// out, which both mean the films themselves -- the only thing those
231+ /// projects could do.
232+ pub proxy: bool,
217 pub playhead: u32,233 pub playhead: u32,
218 }234 }
219 235
@@ -233,6 +249,7 @@ pub fn save(
233 resolution: (u32, u32),249 resolution: (u32, u32),
234 fps: Option<f64>,250 fps: Option<f64>,
235 tone: crate::tonemap::Preset,251 tone: crate::tonemap::Preset,
252+ proxy: bool,
236 limiter: Limiter,253 limiter: Limiter,
237 playhead: u32,254 playhead: u32,
238 ) -> crate::Result<()> {255 ) -> crate::Result<()> {
@@ -247,7 +264,7 @@ pub fn save(
247 let result = std::fs::File::create(&part)264 let result = std::fs::File::create(&part)
248 .and_then(|mut f| {265 .and_then(|mut f| {
249 f.write_all(&emit(266 f.write_all(&emit(
250- &dir, sources, lanes, gains, subtitles, eq, color, resolution, fps, tone,267+ &dir, sources, lanes, gains, subtitles, eq, color, resolution, fps, tone, proxy,
251 limiter, playhead,268 limiter, playhead,
252 ))?;269 ))?;
253 f.sync_all()270 f.sync_all()
@@ -291,6 +308,7 @@ fn emit(
291 resolution: (u32, u32),308 resolution: (u32, u32),
292 fps: Option<f64>,309 fps: Option<f64>,
293 tone: crate::tonemap::Preset,310 tone: crate::tonemap::Preset,
311+ proxy: bool,
294 limiter: Limiter,312 limiter: Limiter,
295 playhead: u32,313 playhead: u32,
296 ) -> Vec<u8> {314 ) -> Vec<u8> {
@@ -310,6 +328,11 @@ fn emit(
310 if tone != crate::tonemap::Preset::default() {328 if tone != crate::tonemap::Preset::default() {
311 out.extend_from_slice(format!("tonemap {}\n", tone.name()).as_bytes());329 out.extend_from_slice(format!("tonemap {}\n", tone.name()).as_bytes());
312 }330 }
331+ // Beside it and by the same rule: a project cut on the films themselves --
332+ // every project before there were stand-ins -- says nothing here.
333+ if proxy {
334+ out.extend_from_slice(b"proxy on\n");
335+ }
313 // Written only when it is not the default, so a project nobody has limited336 // Written only when it is not the default, so a project nobody has limited
314 // is the same bytes it was in v8 bar the version line.337 // is the same bytes it was in v8 bar the version line.
315 if limiter != Limiter::default() {338 if limiter != Limiter::default() {
@@ -439,8 +462,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
439 // The dialects that wrote a source line without its stream field. Reading462 // The dialects that wrote a source line without its stream field. Reading
440 // one is the whole of what "an old project still opens" means here.463 // one is the whole of what "an old project still opens" means here.
441 let streamless = v1 || first == MAGIC_V2;464 let streamless = v1 || first == MAGIC_V2;
442- // The one that carries an HDR rendition...465+ // The one that says whether it is cut on stand-ins...
443- let v11 = first == MAGIC;466+ let v12 = first == MAGIC;
467+ // ...the ones that carry an HDR rendition...
468+ let v11 = v12 || first == MAGIC_V11;
444 // ...the ones that carry subtitle tracks...469 // ...the ones that carry subtitle tracks...
445 let v10 = v11 || first == MAGIC_V10;470 let v10 = v11 || first == MAGIC_V10;
446 // ...the ones that carry the mix -- lane volumes, the master limiter and471 // ...the ones that carry the mix -- lane volumes, the master limiter and
@@ -487,6 +512,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
487 subtitles: Vec::new(),512 subtitles: Vec::new(),
488 limiter: Limiter::default(),513 limiter: Limiter::default(),
489 tone: crate::tonemap::Preset::default(),514 tone: crate::tonemap::Preset::default(),
515+ proxy: false,
490 fps: None,516 fps: None,
491 playhead: 0,517 playhead: 0,
492 };518 };
@@ -557,6 +583,25 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
557 )583 )
558 })?;584 })?;
559 }585 }
586+ b"proxy" if v12 => {
587+ if !doc.sources.is_empty() {
588+ return Err(
589+ format!("line {n}: proxy belongs once, before the sources").into()
590+ );
591+ }
592+ let f = fields(rest, 1, "proxy", n)?;
593+ doc.proxy = match f[0] {
594+ b"on" => true,
595+ b"off" => false,
596+ other => {
597+ return Err(format!(
598+ "line {n}: proxy is on or off, not {:?}",
599+ String::from_utf8_lossy(other)
600+ )
601+ .into());
602+ }
603+ };
604+ }
560 b"limiter" if v9 => {605 b"limiter" if v9 => {
561 if !doc.sources.is_empty() {606 if !doc.sources.is_empty() {
562 return Err(607 return Err(
@@ -1076,6 +1121,7 @@ mod tests {
1076 resolution,1121 resolution,
1077 None,1122 None,
1078 crate::tonemap::Preset::default(),1123 crate::tonemap::Preset::default(),
1124+ false,
1079 Limiter::default(),1125 Limiter::default(),
1080 playhead,1126 playhead,
1081 )1127 )
@@ -1119,6 +1165,7 @@ mod tests {
1119 (1280, 720),1165 (1280, 720),
1120 None,1166 None,
1121 crate::tonemap::Preset::default(),1167 crate::tonemap::Preset::default(),
1168+ false,
1122 Limiter::default(),1169 Limiter::default(),
1123 0,1170 0,
1124 );1171 );
@@ -1147,7 +1194,7 @@ mod tests {
1147 video 1 0 0 30 0 - - - fit 1000\n";1194 video 1 0 0 30 0 - - - fit 1000\n";
1148 let old = parse(v9, &dir).expect("v9 still loads");1195 let old = parse(v9, &dir).expect("v9 still loads");
1149 assert_eq!(old.subtitles, Vec::new());1196 assert_eq!(old.subtitles, Vec::new());
1150- assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 11\n"));1197+ assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 12\n"));
1151 // ...and the line itself is not a v9 line: a dialect may not be mixed.1198 // ...and the line itself is not a v9 line: a dialect may not be mixed.
1152 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)1199 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)
1153 .unwrap_err()1200 .unwrap_err()
@@ -1163,6 +1210,65 @@ mod tests {
1163 }1210 }
1164 }1211 }
1165 1212
1213+ /// The v12 line: whether the project is cut on the stand-ins, written only
1214+ /// when it is -- and the dialect before it, which had no stand-ins and
1215+ /// whose bytes are therefore unchanged bar the version.
1216+ #[test]
1217+ fn the_proxy_switch_round_trips_and_a_v11_file_is_cut_on_its_films() {
1218+ let dir = PathBuf::from("/proj");
1219+ let (_, sources, lanes) = doc();
1220+ let bytes = |proxy| {
1221+ super::emit(
1222+ &dir,
1223+ &sources,
1224+ &lanes,
1225+ &[],
1226+ &[],
1227+ &[],
1228+ &[],
1229+ (1280, 720),
1230+ None,
1231+ crate::tonemap::Preset::default(),
1232+ proxy,
1233+ Limiter::default(),
1234+ 0,
1235+ )
1236+ };
1237+ let on = bytes(true);
1238+ assert!(
1239+ String::from_utf8_lossy(&on).contains("proxy on\n"),
1240+ "{}",
1241+ String::from_utf8_lossy(&on)
1242+ );
1243+ assert!(parse(&on, &dir).expect("v12 parses").proxy);
1244+ let off = bytes(false);
1245+ assert!(
1246+ !String::from_utf8_lossy(&off).contains("proxy"),
1247+ "off is the line left out"
1248+ );
1249+ assert!(!parse(&off, &dir).expect("v12 parses").proxy);
1250+
1251+ // A v11 project is one cut on the films themselves, and it still loads.
1252+ let v11 = b"edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1253+ video 1 0 0 30 0 - - - fit 1000\n";
1254+ let old = parse(v11, &dir).expect("v11 still loads");
1255+ assert!(!old.proxy);
1256+ assert_eq!(old.sources.len(), 1, "the rest of it came back too");
1257+ // ...and the line is not a v11 line: a dialect may not be mixed.
1258+ let mixed = parse(b"edith 11\nsource 0 a.mp4\nproxy on\n", &dir)
1259+ .unwrap_err()
1260+ .to_string();
1261+ assert_eq!(mixed, "line 3: unknown keyword \"proxy\"");
1262+ // Anything but on or off is a corrupt line, by name.
1263+ for line in ["proxy\n", "proxy yes\n", "proxy On\n"] {
1264+ let file = format!("edith 12\nsource 0 a.mp4\n{line}");
1265+ assert!(
1266+ parse(file.as_bytes(), &dir).is_err(),
1267+ "{line:?} is not a proxy line"
1268+ );
1269+ }
1270+ }
1271+
1166 /// The v11 line: the HDR rendition, written by name, read back as the very1272 /// The v11 line: the HDR rendition, written by name, read back as the very
1167 /// preset -- and the dialect before it, which had no way to say one and1273 /// preset -- and the dialect before it, which had no way to say one and
1168 /// meant the published conversion.1274 /// meant the published conversion.
@@ -1182,6 +1288,7 @@ mod tests {
1182 (1280, 720),1288 (1280, 720),
1183 None,1289 None,
1184 preset,1290 preset,
1291+ false,
1185 Limiter::default(),1292 Limiter::default(),
1186 0,1293 0,
1187 );1294 );
@@ -1276,7 +1383,7 @@ mod tests {
1276 let bytes = flat(&dir, &sources, &lanes, 12);1383 let bytes = flat(&dir, &sources, &lanes, 12);
1277 assert_eq!(1384 assert_eq!(
1278 String::from_utf8_lossy(&bytes),1385 String::from_utf8_lossy(&bytes),
1279- "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\1386+ "edith 12\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1280 source 2 /elsewhere/b.mp4\n\1387 source 2 /elsewhere/b.mp4\n\
1281 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\1388 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1282 audio 1 0 0 30 0 0 - - fit 1000\n",1389 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -1313,7 +1420,7 @@ mod tests {
1313 let bytes = flat(&dir, &sources, &lanes, 7);1420 let bytes = flat(&dir, &sources, &lanes, 7);
1314 assert_eq!(1421 assert_eq!(
1315 String::from_utf8_lossy(&bytes),1422 String::from_utf8_lossy(&bytes),
1316- "edith 11\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\1423+ "edith 12\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
1317 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\1424 video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\
1318 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",1425 video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n",
1319 "an empty lane is a line of its own; everything else is its clips"1426 "an empty lane is a line of its own; everything else is its clips"
@@ -1421,7 +1528,7 @@ mod tests {
1421 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);1528 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
1422 assert_eq!(1529 assert_eq!(
1423 String::from_utf8_lossy(&bytes),1530 String::from_utf8_lossy(&bytes),
1424- "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\1531+ "edith 12\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1425 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\1532 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
1426 eq 16777215.0:-0.1:3.918315e-39:hs\n\1533 eq 16777215.0:-0.1:3.918315e-39:hs\n\
1427 eq\n\1534 eq\n\
@@ -1525,7 +1632,7 @@ mod tests {
1525 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);1632 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
1526 assert_eq!(1633 assert_eq!(
1527 String::from_utf8_lossy(&bytes),1634 String::from_utf8_lossy(&bytes),
1528- "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\1635+ "edith 12\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1529 color 0.1:1.2:0.9:-0.3\n\1636 color 0.1:1.2:0.9:-0.3\n\
1530 color -1e-7:16777215.0:3.918315e-39:-0.0\n\1637 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
1531 color 0.0:1.0:1.0:0.0\n\1638 color 0.0:1.0:1.0:0.0\n\
@@ -1590,7 +1697,7 @@ mod tests {
1590 (1280, 720),1697 (1280, 720),
1591 old.playhead1698 old.playhead
1592 )),1699 )),
1593- "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\1700+ "edith 12\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1594 eq 80.0:-3.0:0.707:ls\n\1701 eq 80.0:-3.0:0.707:ls\n\
1595 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"1702 video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1596 );1703 );
@@ -1628,7 +1735,7 @@ mod tests {
1628 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);1735 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
1629 assert_eq!(1736 assert_eq!(
1630 String::from_utf8_lossy(&bytes),1737 String::from_utf8_lossy(&bytes),
1631- "edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\1738+ "edith 12\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
1632 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\1739 video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\
1633 audio 1 0 0 30 0 - - - fit 2000\n",1740 audio 1 0 0 30 0 - - - fit 2000\n",
1634 "the rate is the clip line's last field, in thousandths"1741 "the rate is the clip line's last field, in thousandths"
@@ -1657,7 +1764,7 @@ mod tests {
1657 (1280, 720),1764 (1280, 720),
1658 old.playhead1765 old.playhead
1659 )),1766 )),
1660- "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\1767+ "edith 12\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1661 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"1768 video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n"
1662 );1769 );
1663 // A rate outside what the editor can set is a corrupt line, by name.1770 // A rate outside what the editor can set is a corrupt line, by name.
@@ -1698,12 +1805,13 @@ mod tests {
1698 (1280, 720),1805 (1280, 720),
1699 Some(23.976023976023978),1806 Some(23.976023976023978),
1700 crate::tonemap::Preset::default(),1807 crate::tonemap::Preset::default(),
1808+ false,
1701 limiter,1809 limiter,
1702 0,1810 0,
1703 );1811 );
1704 assert_eq!(1812 assert_eq!(
1705 String::from_utf8_lossy(&bytes),1813 String::from_utf8_lossy(&bytes),
1706- "edith 11\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\1814+ "edith 12\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\
1707 limiter -1.5 on\nsource 0 a.mp4\n\1815 limiter -1.5 on\nsource 0 a.mp4\n\
1708 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\1816 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\
1709 audio 2 0 0 30 0 - - - fit 1000\n\1817 audio 2 0 0 30 0 - - - fit 1000\n\
@@ -1735,7 +1843,7 @@ mod tests {
1735 (1280, 720),1843 (1280, 720),
1736 old.playhead1844 old.playhead
1737 )),1845 )),
1738- "edith 11\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\1846+ "edith 12\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
1739 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"1847 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
1740 );1848 );
1741 1849
@@ -1899,7 +2007,7 @@ mod tests {
1899 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");2007 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
1900 assert_eq!(2008 assert_eq!(
1901 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),2009 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
1902- "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\2010+ "edith 12\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1903 source 2 /elsewhere/b.mp4\n\2011 source 2 /elsewhere/b.mp4\n\
1904 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\2012 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1905 audio 1 0 0 30 0 0 - - fit 1000\n"2013 audio 1 0 0 30 0 0 - - fit 1000\n"
@@ -1952,7 +2060,7 @@ mod tests {
1952 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);2060 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1953 assert_eq!(2061 assert_eq!(
1954 String::from_utf8_lossy(&v5),2062 String::from_utf8_lossy(&v5),
1955- "edith 11\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\2063+ "edith 12\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
1956 source 0 /elsewhere/b.mp4\n\2064 source 0 /elsewhere/b.mp4\n\
1957 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\2065 video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\
1958 audio 1 0 0 30 0 0 - - fit 1000\n",2066 audio 1 0 0 30 0 0 - - fit 1000\n",
@@ -1984,7 +2092,7 @@ mod tests {
1984 // Saved again it is the current version, which round-trips to the2092 // Saved again it is the current version, which round-trips to the
1985 // same document.2093 // same document.
1986 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);2094 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
1987- assert!(v5.starts_with(b"edith 11\n"));2095+ assert!(v5.starts_with(b"edith 12\n"));
1988 let again = parse(&v5, &dir).expect("v5 parses");2096 let again = parse(&v5, &dir).expect("v5 parses");
1989 assert_eq!(again.lanes, back.lanes);2097 assert_eq!(again.lanes, back.lanes);
1990 // A dialect may not be mixed: lane lines under v1, `clip` under v2.2098 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
@@ -2082,6 +2190,7 @@ mod tests {
2082 (1280, 720),2190 (1280, 720),
2083 None,2191 None,
2084 crate::tonemap::Preset::default(),2192 crate::tonemap::Preset::default(),
2193+ false,
2085 Limiter::default(),2194 Limiter::default(),
2086 0,2195 0,
2087 )2196 )
@@ -2089,7 +2198,7 @@ mod tests {
2089 let bytes = std::fs::read(&path).expect("read back");2198 let bytes = std::fs::read(&path).expect("read back");
2090 assert_eq!(2199 assert_eq!(
2091 String::from_utf8_lossy(&bytes),2200 String::from_utf8_lossy(&bytes),
2092- "edith 11\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\2201+ "edith 12\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
2093 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"2202 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"
2094 );2203 );
2095 // Loading rejoins the *given* directory, so the file is reached by the2204 // Loading rejoins the *given* directory, so the file is reached by the
@@ -2134,10 +2243,10 @@ mod tests {
2134 #[test]2243 #[test]
2135 fn a_wrong_first_line_is_refused_by_name() {2244 fn a_wrong_first_line_is_refused_by_name() {
2136 let dir = PathBuf::from("/proj");2245 let dir = PathBuf::from("/proj");
2137- let err = parse(b"edith 12\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)2246+ let err = parse(b"edith 13\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
2138 .unwrap_err()2247 .unwrap_err()
2139 .to_string();2248 .to_string();
2140- assert_eq!(err, "line 1: unsupported version 12");2249+ assert_eq!(err, "line 1: unsupported version 13");
2141 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {2250 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
2142 assert_eq!(2251 assert_eq!(
2143 parse(junk, &dir).unwrap_err().to_string(),2252 parse(junk, &dir).unwrap_err().to_string(),
crates/engine/src/export.rsmodified+107 -12
@@ -85,14 +85,14 @@ use crate::tonemap::{self, ToneMapper};
85 85
86 /// Progress is reported in permille: an atomic integer the render loop can read86 /// Progress is reported in permille: an atomic integer the render loop can read
87 /// without a lock, fine enough for any progress bar.87 /// without a lock, fine enough for any progress bar.
88-const PROGRESS_SCALE: u32 = 1_000;88+pub(crate) const PROGRESS_SCALE: u32 = 1_000;
89 89
90 /// The head of the bar the *sound* owns, before a picture is written at all.90 /// The head of the bar the *sound* owns, before a picture is written at all.
91 /// The mix is decoded, encoded and measured before the muxer exists ([`run`]91 /// The mix is decoded, encoded and measured before the muxer exists ([`run`]
92 /// says why), and on a feature film that is a minute or two in which a bar92 /// says why), and on a feature film that is a minute or two in which a bar
93 /// pinned at zero is the only thing on screen -- which reads as an export that93 /// pinned at zero is the only thing on screen -- which reads as an export that
94 /// has hung. Small, because the picture is still nearly all of the work.94 /// has hung. Small, because the picture is still nearly all of the work.
95-const AUDIO_BAND: u32 = PROGRESS_SCALE / 20;95+pub(crate) const AUDIO_BAND: u32 = PROGRESS_SCALE / 20;
96 96
97 /// Where the bar stands with `done` of `total` pictures written: the sound's97 /// Where the bar stands with `done` of `total` pictures written: the sound's
98 /// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is98 /// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is
@@ -300,6 +300,29 @@ pub struct ExportSettings {
300 /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has300 /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has
301 /// no such ceiling.301 /// no such ceiling.
302 pub subtitles: Vec<usize>,302 pub subtitles: Vec<usize>,
303+ /// Code every picture as a key frame a decoder may be started from: no
304+ /// frame references another, the file is an intraframe master in the shape
305+ /// of ProRes, and a seek to any frame at all is one decode.
306+ ///
307+ /// Bigger files for that, so it is off for delivery and on for the
308+ /// stand-ins [`crate::proxy`] makes, which exist precisely to be seeked
309+ /// through. The HEVC seats are intra-only whatever this says
310+ /// ([`Enc::open_hevc`]); this is the H.264 pair's switch.
311+ pub intra_only: bool,
312+ /// Write the picture in the space its **source** declares -- no tone map to
313+ /// SDR, no matrix conversion -- and tag the file with it, instead of
314+ /// converting everything into the space the output height implies.
315+ ///
316+ /// For a preview file and nothing else ([`crate::proxy`]): it makes the
317+ /// stand-in a smaller copy of the film rather than a rendition of it, so
318+ /// the screen tone-maps it live with whatever preset the project is set to
319+ /// -- and it takes the per-frame conversion off the *source's* full
320+ /// resolution, which on a 4K HDR film was 48 ms a frame and the whole of a
321+ /// proxy's cost (measured 2026-08-13).
322+ ///
323+ /// A delivery export must leave it off: an mp4 in BT.2020 PQ is a file for
324+ /// this editor to read back, not one to hand anybody.
325+ pub keep_source_colour: bool,
303 }326 }
304 327
305 struct Shared {328 struct Shared {
@@ -390,6 +413,15 @@ pub fn start(
390 part.push(".part");413 part.push(".part");
391 let part = PathBuf::from(part);414 let part = PathBuf::from(part);
392 let spawned = thread::Builder::new().name("export".into()).spawn(move || {415 let spawned = thread::Builder::new().name("export".into()).spawn(move || {
416+ // Every file this export will read, named before a byte of one is.
417+ // These are the project's own sources and can be nothing else: a
418+ // stand-in ([`crate::proxy`]) is a substitution playback makes when it
419+ // opens a span, and nothing here knows such a thing exists. Printed so
420+ // that "the delivery came off the film itself" is a grep rather than a
421+ // belief.
422+ for source in project.sources() {
423+ eprintln!("export source: {}", source.path.display());
424+ }
393 // The rename is the last step and the only one that publishes a file425 // The rename is the last step and the only one that publishes a file
394 // under the name the caller asked for; it stays on the same directory,426 // under the name the caller asked for; it stays on the same directory,
395 // so it is atomic.427 // so it is atomic.
@@ -526,6 +558,20 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
526 format if format.is_av1() => {558 format if format.is_av1() => {
527 HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate)559 HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate)
528 }560 }
561+ // An intra-only H.264 file is a *different seat*, not the same seat with
562+ // a flag on the pictures: asking this one for a key frame every time
563+ // gets I slices that are not IDRs and carry no parameter sets, which is
564+ // a file with one starting point in it however many I pictures it holds
565+ // (measured: a 60-frame hardware proxy, 1 sync point of 60). `None`
566+ // where the plugin is older than that seat, and then the software
567+ // encoder takes the file -- its `gop_size = 1` writes what was asked
568+ // for, slowly, which is the only honest fallback here.
569+ //
570+ // Only H.264 reaches this arm: the two arms above take every HEVC and
571+ // AV1 format, and the HEVC seat is intra-only already.
572+ _ if settings.intra_only => {
573+ HwEncoder::open_intra(meta.width, meta.height, fps_num, fps_den, bitrate)
574+ }
529 _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate),575 _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate),
530 }576 }
531 }577 }
@@ -1735,6 +1781,22 @@ fn run(
1735 settings: &ExportSettings,1781 settings: &ExportSettings,
1736 ) -> crate::Result<()> {1782 ) -> crate::Result<()> {
1737 let total = project.timeline_frames();1783 let total = project.timeline_frames();
1784+ // The two preview switches are the H.264 mp4 pair's alone. Only that
1785+ // container carries a colour of its own back out ([`write_video`] tags it
1786+ // there), so asking any other for a source-space file would write pictures
1787+ // in one space and a header in another; and only that codec's seats honour
1788+ // `intra_only` -- the HEVC pair is intra whatever it says, and an AV1 one
1789+ // would quietly write the long-GOP file it always did.
1790+ if settings.keep_source_colour && settings.format != Format::Mp4 {
1791+ return Err(format!(
1792+ "{} cannot be written in its source's colour space",
1793+ settings.format.name()
1794+ )
1795+ .into());
1796+ }
1797+ if settings.intra_only && settings.format != Format::Mp4 {
1798+ return Err(format!("{} cannot be written intra-only", settings.format.name()).into());
1799+ }
1738 let sources = project.sources();1800 let sources = project.sources();
1739 // The picture's decision first, before a sample of sound is touched: it is1801 // The picture's decision first, before a sample of sound is touched: it is
1740 // the answer that decides what the whole export *is*, it costs one header1802 // the answer that decides what the whole export *is*, it costs one header
@@ -1874,14 +1936,24 @@ fn run(
1874 let tone: Vec<Option<ToneMapper>> = rates1936 let tone: Vec<Option<ToneMapper>> = rates
1875 .iter()1937 .iter()
1876 .map(|(_, color, peak)| match color.transfer {1938 .map(|(_, color, peak)| match color.transfer {
1939+ // A preview file keeps the film's own curve and is tone-mapped when
1940+ // it is *shown* ([`ExportSettings::keep_source_colour`]), which is
1941+ // both cheaper and the only way the preset can still be changed
1942+ // after the stand-in was made.
1943+ _ if settings.keep_source_colour => None,
1877 Transfer::Sdr => None,1944 Transfer::Sdr => None,
1878 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)),1945 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)),
1879 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)),1946 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)),
1880 })1947 })
1881 .collect();1948 .collect();
1882 // ...and the one space they are all written in, the same rule a reader with1949 // ...and the one space they are all written in, the same rule a reader with
1883- // no tags to read would apply to this file's height.1950+ // no tags to read would apply to this file's height -- or, for a preview
1884- let out_color = ColorDescription::output(meta.height);1951+ // file, the source's own, which is what makes every remap below the
1952+ // identity and the file's `colr` box its film's.
1953+ let out_color = match settings.keep_source_colour {
1954+ true => meta.color,
1955+ false => ColorDescription::output(meta.height),
1956+ };
1885 1957
1886 let mut encoder = Enc::open(meta, settings)?;1958 let mut encoder = Enc::open(meta, settings)?;
1887 // What this file is really being written by, for a progress line to name.1959 // What this file is really being written by, for a progress line to name.
@@ -2068,11 +2140,11 @@ fn run(
2068 // graded and placed, so a held frame costs an encode and no decode.2140 // graded and placed, so a held frame costs an encode and no decode.
2069 for _ in 0..repeats {2141 for _ in 0..repeats {
2070 let coded = match &frame {2142 let coded = match &frame {
2071- Frame::Dma(dma) => encoder.encode_dma(dma)?,2143+ Frame::Dma(dma) => encoder.encode_dma(dma, settings.intra_only)?,
2072 Frame::Pixels(..) => {2144 Frame::Pixels(..) => {
2073 let (y, u, v, width, height) =2145 let (y, u, v, width, height) =
2074 placed.expect("a picture with pixels was placed");2146 placed.expect("a picture with pixels was placed");
2075- encoder.encode(y, u, v, width, height)?2147+ encoder.encode(y, u, v, width, height, settings.intra_only)?
2076 }2148 }
2077 };2149 };
2078 if let Some((au, key)) = coded {2150 if let Some((au, key)) = coded {
@@ -2813,6 +2885,12 @@ fn write_video(
2813 )?)) else {2885 )?)) else {
2814 unreachable!("just inserted an mp4 muxer")2886 unreachable!("just inserted an mp4 muxer")
2815 };2887 };
2888+ // A file written in its source's own space says so, rather than
2889+ // claiming the space its height would imply
2890+ // ([`ExportSettings::keep_source_colour`]).
2891+ if settings.keep_source_colour {
2892+ mp4.set_colour(meta.color);
2893+ }
2816 mp42894 mp4
2817 }2895 }
2818 };2896 };
@@ -2946,8 +3024,13 @@ impl Enc {
2946 cfg.framerate = meta.frame_rate as f32;3024 cfg.framerate = meta.frame_rate as f32;
2947 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;3025 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;
2948 // Two seconds between key frames, and no B-frames on either path: the3026 // Two seconds between key frames, and no B-frames on either path: the
2949- // muxer times everything by duration alone, which reordering would break.3027+ // muxer times everything by duration alone, which reordering would
2950- cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32;3028+ // break. A proxy asks for one frame a GOP, which is every frame its own
3029+ // starting point ([`ExportSettings::intra_only`]).
3030+ cfg.gop_size = match settings.intra_only {
3031+ true => 1,
3032+ false => (meta.frame_rate * 2.0).round().max(1.0) as u32,
3033+ };
2951 cfg.bframes = 0;3034 cfg.bframes = 0;
2952 // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same3035 // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same
2953 // bitrate, so Fast is what a fallback should be.3036 // bitrate, so Fast is what a fallback should be.
@@ -3109,6 +3192,7 @@ impl Enc {
3109 v: &[u8],3192 v: &[u8],
3110 width: u32,3193 width: u32,
3111 height: u32,3194 height: u32,
3195+ intra: bool,
3112 ) -> crate::Result<Option<(&[u8], bool)>> {3196 ) -> crate::Result<Option<(&[u8], bool)>> {
3113 match self {3197 match self {
3114 Self::Av1Hw(hw) => {3198 Self::Av1Hw(hw) => {
@@ -3158,9 +3242,13 @@ impl Enc {
3158 // frame -- which is what an intraframe master means.3242 // frame -- which is what an intraframe master means.
3159 Ok(pop_hevc(hevc))3243 Ok(pop_hevc(hevc))
3160 }3244 }
3245+ // A key frame is asked for on every picture where the file is an
3246+ // intraframe one, and the flag says what was asked: the mp4 muxer
3247+ // reads its own sync marks off the IDR slices either way, so this
3248+ // is what a Matroska one would be told.
3161 Self::Hw(hw) => Ok(hw3249 Self::Hw(hw) => Ok(hw
3162- .encode(y, u, v, width, height, false)?3250+ .encode(y, u, v, width, height, intra)?
3163- .map(|au| (au, false))),3251+ .map(|au| (au, intra))),
3164 Self::Sw { encoder, au, .. } => {3252 Self::Sw { encoder, au, .. } => {
3165 let frame = YuvFrame {3253 let frame = YuvFrame {
3166 width: width as usize,3254 width: width as usize,
@@ -3196,9 +3284,16 @@ impl Enc {
3196 /// Same answer as [`Enc::encode`], including which units a decoder may be3284 /// Same answer as [`Enc::encode`], including which units a decoder may be
3197 /// started from, because it is the same encoder -- only the picture took3285 /// started from, because it is the same encoder -- only the picture took
3198 /// another way in.3286 /// another way in.
3199- fn encode_dma(&mut self, dma: &DmaFrame) -> crate::Result<Option<(&[u8], bool)>> {3287+ ///
3288+ /// `intra` therefore carries here too, and not for symmetry's sake: a proxy
3289+ /// of a file already small enough is coded at that file's own size
3290+ /// ([`crate::proxy::size_for`]), which is the one case where an intraframe
3291+ /// export's decoder and encoder agree on a surface and the buffer goes
3292+ /// straight across. An access unit marked as no sync point there would give
3293+ /// a stand-in whose whole reason to exist is that every frame is one.
3294+ fn encode_dma(&mut self, dma: &DmaFrame, intra: bool) -> crate::Result<Option<(&[u8], bool)>> {
3200 match self {3295 match self {
3201- Self::Hw(hw) => Ok(hw.encode_dma(dma, false)?.map(|au| (au, false))),3296+ Self::Hw(hw) => Ok(hw.encode_dma(dma, intra)?.map(|au| (au, intra))),
3202 // Every picture an IDR here, exactly as in [`Enc::encode`].3297 // Every picture an IDR here, exactly as in [`Enc::encode`].
3203 Self::HevcHw(hw) => Ok(hw.encode_dma(dma, true)?.map(|au| (au, true))),3298 Self::HevcHw(hw) => Ok(hw.encode_dma(dma, true)?.map(|au| (au, true))),
3204 // Unreachable through [`Enc::dma_want`], which is the only thing3299 // Unreachable through [`Enc::dma_want`], which is the only thing
crates/engine/src/hw.rsmodified+26 -0
@@ -444,6 +444,10 @@ struct EncPlugin {
444 /// The HEVC seat, missing from an older plugin for the same reason and at444 /// The HEVC seat, missing from an older plugin for the same reason and at
445 /// the same cost: an HEVC export then runs on the software intra encoder.445 /// the same cost: an HEVC export then runs on the software intra encoder.
446 open_hevc: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>,446 open_hevc: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>,
447+ /// The **intra-only** H.264 seat, missing from an older plugin for the same
448+ /// reason and at the same cost: a proxy then runs on the software encoder,
449+ /// which codes one frame a GOP and so writes the same kind of file.
450+ open_intra: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>,
447 frame:451 frame:
448 unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32,452 unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32,
449 /// The zero-copy pair, both optional together: an older plugin exports453 /// The zero-copy pair, both optional together: an older plugin exports
@@ -477,6 +481,7 @@ fn load_enc() -> Option<EncPlugin> {
477 open: *lib.get(b"vh_enc_open\0").ok()?,481 open: *lib.get(b"vh_enc_open\0").ok()?,
478 open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s),482 open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s),
479 open_hevc: lib.get(b"vh_enc_hevc_open\0").ok().map(|s| *s),483 open_hevc: lib.get(b"vh_enc_hevc_open\0").ok().map(|s| *s),
484+ open_intra: lib.get(b"vh_enc_open_intra\0").ok().map(|s| *s),
480 frame: *lib.get(b"vh_enc_frame\0").ok()?,485 frame: *lib.get(b"vh_enc_frame\0").ok()?,
481 dma_geometry: lib.get(b"vh_enc_dma_geometry\0").ok().map(|s| *s),486 dma_geometry: lib.get(b"vh_enc_dma_geometry\0").ok().map(|s| *s),
482 frame_dma: lib.get(b"vh_enc_frame_dma\0").ok().map(|s| *s),487 frame_dma: lib.get(b"vh_enc_frame_dma\0").ok().map(|s| *s),
@@ -518,6 +523,27 @@ impl HwEncoder {
518 )523 )
519 }524 }
520 525
526+ /// The same H.264 seat, **intra-only**: every picture comes back an IDR
527+ /// with its own parameter sets, so every frame of the file is one a decoder
528+ /// may be started from. What [`crate::proxy`] codes a stand-in with.
529+ ///
530+ /// `None` on everything [`HwEncoder::open`] answers `None` to *and* on a
531+ /// plugin built before this seat existed -- and that `None` matters more
532+ /// than the others: the caller must then take the software encoder, which
533+ /// codes one frame a GOP, rather than the ordinary hardware seat, which
534+ /// would write a long-GOP file under a name that promises otherwise.
535+ pub fn open_intra(
536+ width: u32,
537+ height: u32,
538+ fps_num: u32,
539+ fps_den: u32,
540+ bitrate: u64,
541+ ) -> Option<Self> {
542+ let plugin = enc_plugin()?;
543+ let open = plugin.open_intra?;
544+ Self::opened(plugin, open, width, height, fps_num, fps_den, bitrate)
545+ }
546+
521 /// The same, coding AV1 instead. `None` on everything [`HwEncoder::open`]547 /// The same, coding AV1 instead. `None` on everything [`HwEncoder::open`]
522 /// answers `None` to *and* on a plugin or a GPU with no AV1 encoder -- an548 /// answers `None` to *and* on a plugin or a GPU with no AV1 encoder -- an
523 /// AV1 encode entrypoint is recent hardware, so this is the fallback that549 /// AV1 encode entrypoint is recent hardware, so this is the fallback that
crates/engine/src/lib.rsmodified+1 -0
@@ -17,6 +17,7 @@ pub mod limiter;
17 pub mod mux;17 pub mod mux;
18 pub mod playback;18 pub mod playback;
19 pub mod project;19 pub mod project;
20+pub mod proxy;
20 pub mod real_library;21 pub mod real_library;
21 pub mod scale;22 pub mod scale;
22 pub mod scratch;23 pub mod scratch;
crates/engine/src/mux.rsmodified+10 -0
@@ -329,6 +329,16 @@ impl Mp4Muxer {
329 Ok(())329 Ok(())
330 }330 }
331 331
332+ /// Says what this file's samples mean, where that is *not* the rule the
333+ /// height implies -- a picture written in its source's own space rather
334+ /// than converted into the output one ([`crate::proxy`] is why: a stand-in
335+ /// carries the film's colour and lets the screen convert it, once, at
336+ /// preview size). The box is written when the file is finished, so this may
337+ /// be said any time before then.
338+ pub fn set_colour(&mut self, colour: ColorDescription) {
339+ self.colr = colr_nclx(colour);
340+ }
341+
332 /// One coded picture, Annex-B framed. Parameter sets inside it are dropped342 /// One coded picture, Annex-B framed. Parameter sets inside it are dropped
333 /// (they are already in `avcC`); an IDR slice marks the sample as a sync point.343 /// (they are already in `avcC`); an IDR slice marks the sample as a sync point.
334 pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> {344 pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> {
crates/engine/src/playback.rsmodified+83 -4
@@ -11,7 +11,7 @@
11 //! Drift policy stays with the caller -- this type answers "what time is it",11 //! Drift policy stays with the caller -- this type answers "what time is it",
12 //! the renderer decides which frame that means.12 //! the renderer decides which frame that means.
13 13
14-use std::path::Path;14+use std::path::{Path, PathBuf};
15 use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering};15 use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering};
16 use std::sync::mpsc::{Receiver, TryRecvError};16 use std::sync::mpsc::{Receiver, TryRecvError};
17 use std::sync::{Arc, Mutex};17 use std::sync::{Arc, Mutex};
@@ -378,6 +378,16 @@ pub struct PlaybackSession {
378 /// passed ([`Self::drop_late_pictures`]). Off unless a caller says it is378 /// passed ([`Self::drop_late_pictures`]). Off unless a caller says it is
379 /// watching this in real time.379 /// watching this in real time.
380 drop_late: bool,380 drop_late: bool,
381+ /// Whether the picture is decoded from the stand-ins rather than from the
382+ /// films ([`crate::proxy`]). One switch for the whole project, saved with
383+ /// it, and *only* the picture: the sound is always the film's own, and so
384+ /// is everything an export reads.
385+ ///
386+ /// Which sources have a stand-in is not kept here -- it is asked of the
387+ /// cache when a span opens ([`Self::picture_path`]), one `stat` against a
388+ /// file open that already costs milliseconds, so a proxy made (or deleted)
389+ /// mid-session is picked up at the next seek and nothing can go stale.
390+ proxies: bool,
381 }391 }
382 392
383 /// What an edit dirtied -- which half of the pipeline has to be rebuilt for the393 /// What an edit dirtied -- which half of the pipeline has to be rebuilt for the
@@ -493,6 +503,8 @@ impl PlaybackSession {
493 mix: None,503 mix: None,
494 priming: false,504 priming: false,
495 drop_late: false,505 drop_late: false,
506+ // A file just opened is a project nobody has picked stand-ins for.
507+ proxies: false,
496 })508 })
497 }509 }
498 510
@@ -606,6 +618,8 @@ impl PlaybackSession {
606 mix: None,618 mix: None,
607 priming: false,619 priming: false,
608 drop_late: false,620 drop_late: false,
621+ // A file just opened is a project nobody has picked stand-ins for.
622+ proxies: false,
609 })623 })
610 }624 }
611 625
@@ -683,6 +697,8 @@ impl PlaybackSession {
683 mix: None,697 mix: None,
684 priming: false,698 priming: false,
685 drop_late: false,699 drop_late: false,
700+ // A file just opened is a project nobody has picked stand-ins for.
701+ proxies: false,
686 })702 })
687 }703 }
688 704
@@ -977,6 +993,9 @@ impl PlaybackSession {
977 mix: None,993 mix: None,
978 priming: false,994 priming: false,
979 drop_late: false,995 drop_late: false,
996+ // What the file says, and `false` for every dialect before v12:
997+ // a project cut on the films themselves opens on them.
998+ proxies: doc.proxy,
980 };999 };
981 // The scaffolding above opened source 0 from its first frame and the1000 // The scaffolding above opened source 0 from its first frame and the
982 // whole of its audio; this puts both onto the clip the playhead is1001 // whole of its audio; this puts both onto the clip the playhead is
@@ -1228,6 +1247,10 @@ impl PlaybackSession {
1228 // reason: a picked look that vanished on a reload is a look nobody1247 // reason: a picked look that vanished on a reload is a look nobody
1229 // could keep.1248 // could keep.
1230 self.project.tone(),1249 self.project.tone(),
1250+ // ...and whether it is cut on the stand-ins, for the same reason.
1251+ // *Which* files have one is not saved: [`crate::proxy`] finds that
1252+ // out from the film itself, so nothing here can go stale.
1253+ self.proxies,
1231 self.project.limiter(),1254 self.project.limiter(),
1232 playhead,1255 playhead,
1233 )1256 )
@@ -1468,7 +1491,19 @@ impl PlaybackSession {
1468 from: Some((source, in_frame)),1491 from: Some((source, in_frame)),
1469 ..1492 ..
1470 }) => {1493 }) => {
1471- let path = &self.project.sources()[source].path;1494+ // The stand-in where there is one and the switch is on, the
1495+ // film itself otherwise -- the one place the picture's file is
1496+ // decided ([`Self::picture_path`]). The sound is opened
1497+ // elsewhere and is always the film's.
1498+ //
1499+ // It decides for the reuse door below as well, and that is what
1500+ // makes the switch flippable while watching: a worker holding
1501+ // the film is asked for a span of the stand-in, declines on the
1502+ // path it already has ([`Worker::reseek`]), and the seek
1503+ // [`Self::set_proxies`] does becomes a respawn on the other
1504+ // file. Asking the *project* here instead would have left every
1505+ // proxied span opening a worker from scratch.
1506+ let path = self.picture_path(source);
1472 // The file's own frames, which is the only place they exist: a1507 // The file's own frames, which is the only place they exist: a
1473 // clip counts the timeline's ([`Rate`]).1508 // clip counts the timeline's ([`Rate`]).
1474 let start_frame = self.span_rate.source_at(in_frame);1509 let start_frame = self.span_rate.source_at(in_frame);
@@ -1503,7 +1538,7 @@ impl PlaybackSession {
1503 // deferred opener below is then exactly the path it always was.1538 // deferred opener below is then exactly the path it always was.
1504 if let Some((frames, backend)) =1539 if let Some((frames, backend)) =
1505 self.worker1540 self.worker
1506- .reseek(path, start_frame, end_frame, color, canvas(), tone)1541+ .reseek(&path, start_frame, end_frame, color, canvas(), tone)
1507 {1542 {
1508 self.frames = frames;1543 self.frames = frames;
1509 self.backend = backend;1544 self.backend = backend;
@@ -1511,7 +1546,7 @@ impl PlaybackSession {
1511 return;1546 return;
1512 }1547 }
1513 Ok(DecodeSession::open_worker_deferred(1548 Ok(DecodeSession::open_worker_deferred(
1514- &self.project.sources()[source].path,1549+ &path,
1515 start_frame,1550 start_frame,
1516 end_frame,1551 end_frame,
1517 color,1552 color,
@@ -1919,6 +1954,50 @@ impl PlaybackSession {
1919 .map_or(Rate::REAL_TIME, |i| self.rates[i])1954 .map_or(Rate::REAL_TIME, |i| self.rates[i])
1920 }1955 }
1921 1956
1957+ /// Which file this source's **picture** is decoded from: its stand-in when
1958+ /// the project is cut on stand-ins and one has been made for it, and the
1959+ /// film itself in every other case ([`crate::proxy`]).
1960+ ///
1961+ /// One `stat` per span open, against a decoder open that costs milliseconds
1962+ /// -- so a proxy that appeared (or was deleted) since the last seek is
1963+ /// picked up at this one, and no table of attachments exists to disagree
1964+ /// with the cache.
1965+ ///
1966+ /// The sound never comes through here: [`open_audio`] is given the
1967+ /// project's own source path, so a mix is the film's however this answers.
1968+ pub fn picture_path(&self, source: usize) -> PathBuf {
1969+ let path = &self.project.sources()[source].path;
1970+ let Some(proxy) = self.proxies.then(|| crate::proxy::cached(path)).flatten() else {
1971+ return path.clone();
1972+ };
1973+ // Said out loud, once per span opened, because "the picture came off
1974+ // the stand-in and the delivery did not" is a claim somebody has to be
1975+ // able to check: `export` prints the file *it* reads by the same rule.
1976+ eprintln!("picture: proxy {}", proxy.display());
1977+ proxy
1978+ }
1979+
1980+ /// Whether the picture comes off the stand-ins ([`Self::set_proxies`]).
1981+ pub fn proxies(&self) -> bool {
1982+ self.proxies
1983+ }
1984+
1985+ /// Cut on the stand-ins, or on the films themselves. Reseeks, so the very
1986+ /// next picture comes from the other file -- which is what makes this a
1987+ /// switch a person can flip while watching.
1988+ ///
1989+ /// Says nothing about *which* films have one: a source with no stand-in
1990+ /// keeps playing its own pictures either way, and one made while this is on
1991+ /// is picked up at the next seek.
1992+ pub fn set_proxies(&mut self, on: bool) {
1993+ if self.proxies == on {
1994+ return;
1995+ }
1996+ self.proxies = on;
1997+ let now = self.now();
1998+ self.seek(now);
1999+ }
2000+
1922 /// Which source `path` is, canonicalising only if it has to: a source's own2001 /// Which source `path` is, canonicalising only if it has to: a source's own
1923 /// path is canonical ([`Source::new`]), so a caller handing one back from2002 /// path is canonical ([`Source::new`]), so a caller handing one back from
1924 /// [`sources`](Self::sources) -- which is every library row -- hits on the2003 /// [`sources`](Self::sources) -- which is every library row -- hits on the
crates/engine/src/proxy.rsadded+640 -0
@@ -0,0 +1,640 @@
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+
34+use std::path::{Path, PathBuf};
35+use std::time::UNIX_EPOCH;
36+
37+use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta};
38+use crate::export::{ExportHandle, ExportSettings, Format};
39+use crate::project::{Clip, LaneKind, Project, Source, Speed};
40+use 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).
47+pub 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.
66+pub 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.
77+pub 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.
83+const 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.
89+const 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.
94+pub 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.
102+pub 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.
124+pub 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`].
159+fn 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.
186+fn 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`.
222+pub 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.
233+pub struct Job {
234+ out: PathBuf,
235+ /// `None` for a cache hit: there was nothing to run.
236+ handle: Option<ExportHandle>,
237+}
238+
239+impl 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.
295+pub 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.
318+pub 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.
330+fn 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)]
409+mod 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+}
crates/engine/tests/export.rsmodified+266 -1
@@ -6,11 +6,16 @@
6 //! H.264 encode entrypoint, so they are `#[ignore]`d:6 //! H.264 encode entrypoint, so they are `#[ignore]`d:
7 //!7 //!
8 //! ```text8 //! ```text
9-//! cargo build -p engine -p engine-hw --release9+//! cargo build -p engine-hw --release
10 //! LD_LIBRARY_PATH=target/release \10 //! LD_LIBRARY_PATH=target/release \
11 //! cargo test -p engine --release --test export -- --ignored --nocapture --test-threads=111 //! cargo test -p engine --release --test export -- --ignored --nocapture --test-threads=1
12 //! ```12 //! ```
13 //!13 //!
14+//! That build is its own step and stays its own step: `--tests` (or building
15+//! `-p engine` alongside) does **not** rebuild the cdylib, so the plugin beside
16+//! the test binary is whatever was there last time -- a stale one, silently, and
17+//! every hardware claim measured against it is about code nobody edited.
18+//!
14 //! Both env pins are process-wide, hence `--test-threads=1` for the ignored run.19 //! Both env pins are process-wide, hence `--test-threads=1` for the ignored run.
15 20
16 use std::fs::File;21 use std::fs::File;
@@ -859,3 +864,263 @@ fn exports_a_gapped_timeline_as_black_and_silence() {
859 864
860 std::fs::remove_file(&out).unwrap();865 std::fs::remove_file(&out).unwrap();
861 }866 }
867+
868+/// The stand-in a proxy really is, in one pass over the fixture: a picture-only
869+/// file whose *every* frame is a decoder's starting point, playable through the
870+/// ordinary session, and found in the cache the second time it is asked for.
871+///
872+/// Software seat, like every default test here ([`pin_software`]) -- what the
873+/// hardware one buys is speed, and that is the ignored test below.
874+#[test]
875+fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() {
876+ pin_software();
877+ let source = asset("test_av.mp4");
878+ let out = engine::proxy::path_for(&source).expect("a cache directory");
879+ // A proxy left by an earlier run would make this test assert about a file
880+ // it did not write -- and the cache-hit half below would be the only half
881+ // that ran.
882+ let _ = std::fs::remove_file(&out);
883+
884+ let job = engine::proxy::generate(&source).expect("start the proxy");
885+ assert_eq!(job.path(), out, "the job writes where the key says");
886+ let started = Instant::now();
887+ while !job.is_finished() {
888+ assert!(
889+ started.elapsed() < Duration::from_secs(300),
890+ "the proxy did not finish: {:.0}% in",
891+ job.progress() * 100.0
892+ );
893+ std::thread::sleep(Duration::from_millis(20));
894+ }
895+ let made = job
896+ .outcome()
897+ .expect("a finished job has an outcome")
898+ .expect("the proxy");
899+ assert_eq!(made, out);
900+ assert_eq!(job.progress(), 1.0, "finished at full progress");
901+
902+ let (source_meta, _) = engine::demux::Demuxer::open(&source).expect("open the fixture");
903+ let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy");
904+ assert_eq!(
905+ (meta.width, meta.height),
906+ engine::proxy::size_for(&source_meta),
907+ "the proxy is coded at the size the rule picked"
908+ );
909+ assert_eq!(meta.codec, engine::Codec::H264, "proxies are H.264");
910+ assert_eq!(
911+ meta.frame_count, source_meta.frame_count,
912+ "a stand-in as long as the film, or every cut lands elsewhere"
913+ );
914+
915+ // The whole point: every frame its own random-access point, so a seek never
916+ // has to start earlier than it was asked to.
917+ let syncs = engine::demux::sync_points(&made);
918+ assert_eq!(
919+ syncs.len() as u32,
920+ meta.frame_count,
921+ "{} of {} frames are starting points -- the proxy is not intra-only",
922+ syncs.len(),
923+ meta.frame_count
924+ );
925+
926+ // ...and no sound in it at all: the mix is the original's, always.
927+ assert!(
928+ engine::AudioSession::open(&made)
929+ .expect("probe the proxy for sound")
930+ .is_none(),
931+ "a proxy carries no audio track"
932+ );
933+
934+ // It plays through the ordinary door, which is what substitution needs.
935+ let session = PlaybackSession::open(&made).expect("play the proxy");
936+ assert_eq!(session.meta().frame_count, source_meta.frame_count);
937+
938+ // ...and a session on the *film* plays it instead once the switch is on,
939+ // while the film is still the only thing the project names -- which is what
940+ // an export reads and why an export can never come off a stand-in.
941+ let mut session = PlaybackSession::open(&source).expect("open the film");
942+ // The film as the project names it: canonical ([`Source::new`]), which the
943+ // proxy key resolves to as well -- the same file under two names is one
944+ // stand-in.
945+ let film = session.sources()[0].path.clone();
946+ assert_eq!(session.picture_path(0), film, "off: the film itself");
947+ session.set_proxies(true);
948+ assert!(session.proxies());
949+ assert_eq!(session.picture_path(0), made, "on: the stand-in");
950+ assert_eq!(
951+ session.sources()[0].path,
952+ film,
953+ "the project still names the film, and that is what an export reads"
954+ );
955+ // A frame really arrives from it: the switch reseeks, so the picture after
956+ // it is the proxy's.
957+ let started = Instant::now();
958+ while session.try_frame().is_none() {
959+ assert!(
960+ started.elapsed() < Duration::from_secs(10),
961+ "no picture after switching to the stand-in"
962+ );
963+ std::thread::sleep(Duration::from_millis(10));
964+ }
965+ session.set_proxies(false);
966+ assert_eq!(session.picture_path(0), film, "and back again");
967+
968+ // The switch survives a save and a load, and a project written before there
969+ // were stand-ins opens on its films.
970+ let project = Scratch::file("ve_proxy_switch", "edith");
971+ session.set_proxies(true);
972+ session.save_project(&project).expect("save");
973+ let text = std::fs::read_to_string(&project).expect("read the project back");
974+ assert!(text.starts_with("edith 12\n"), "{text}");
975+ assert!(text.contains("\nproxy on\n"), "{text}");
976+ let reopened = PlaybackSession::open_project(&project).expect("load");
977+ assert!(reopened.proxies(), "the switch came back on");
978+ assert_eq!(reopened.picture_path(0), made, "and it is substituting");
979+
980+ // Asked again, it is the file already there: no second encode.
981+ let again = engine::proxy::generate(&source).expect("ask again");
982+ assert!(again.is_finished(), "a cached proxy is done on the spot");
983+ assert_eq!(
984+ again.outcome().expect("cached outcome").expect("cached path"),
985+ out
986+ );
987+ assert_eq!(engine::proxy::cached(&source), Some(out.clone()));
988+
989+ std::fs::remove_file(&out).expect("clean the cache entry up");
990+ assert_eq!(engine::proxy::cached(&source), None);
991+}
992+
993+/// The same file on the **hardware** seat, asking the one question the software
994+/// twin above cannot: is what the GPU wrote really every-frame-a-starting-point?
995+///
996+/// It was not, and that is why this test exists. The plugin's ordinary H.264
997+/// seat, asked for a key frame on every picture, codes I slices that are not
998+/// IDRs and carry no parameter sets: a 60-picture proxy came back with **one**
999+/// sync point in it, and a proxy whose seeks are no better than the film's is
1000+/// no proxy at all. The seat that answers this is `vh_enc_open_intra`.
1001+///
1002+/// ```text
1003+/// cargo build -p engine-hw --release # its own step: `--tests` leaves it stale
1004+/// LD_LIBRARY_PATH=target/release cargo test -p engine --release --test export \
1005+/// -- --ignored --nocapture --test-threads=1 hardware_proxy
1006+/// ```
1007+#[test]
1008+#[ignore = "needs the VA-API plugin"]
1009+fn a_hardware_proxy_is_every_frame_a_starting_point_too() {
1010+ pin_hardware();
1011+ let source = asset("test_av.mp4");
1012+ let out = engine::proxy::path_for(&source).expect("a cache directory");
1013+ let _ = std::fs::remove_file(&out);
1014+ let job = engine::proxy::generate(&source).expect("start the proxy");
1015+ let started = Instant::now();
1016+ while !job.is_finished() {
1017+ assert!(
1018+ started.elapsed() < Duration::from_secs(300),
1019+ "the proxy did not finish"
1020+ );
1021+ std::thread::sleep(Duration::from_millis(20));
1022+ }
1023+ let made = job
1024+ .outcome()
1025+ .expect("a finished job has an outcome")
1026+ .expect("the proxy");
1027+ let seat = job.encoder().unwrap_or_default();
1028+ println!("hardware proxy seat: {seat}");
1029+ // The silent-software trap: without the plugin on the path this measures
1030+ // the fallback and calls it hardware.
1031+ assert!(
1032+ seat.contains("HW encode"),
1033+ "not the hardware seat ({seat}): LD_LIBRARY_PATH must name the plugin"
1034+ );
1035+ let (meta, _) = engine::demux::Demuxer::open(&made).expect("open the proxy");
1036+ let syncs = engine::demux::sync_points(&made);
1037+ println!("{} of {} frames are starting points", syncs.len(), meta.frame_count);
1038+ assert_eq!(
1039+ syncs.len() as u32,
1040+ meta.frame_count,
1041+ "the hardware seat wrote {} starting points in {} frames",
1042+ syncs.len(),
1043+ meta.frame_count
1044+ );
1045+ std::fs::remove_file(&out).expect("clean the cache entry up");
1046+}
1047+
1048+/// A real 4K HEVC film, on the hardware seat: a proxy of it is made **faster
1049+/// than the film plays**, which is the whole promise -- and a cancel stops it
1050+/// dead and leaves nothing behind.
1051+///
1052+/// Measured over a window rather than to the end: the film is two hours and the
1053+/// number wanted is a rate, not a wall time.
1054+///
1055+/// ```text
1056+/// cargo build -p engine-hw --release # its own step: `--tests` leaves it stale
1057+/// LD_LIBRARY_PATH=target/release cargo test -p engine --release --test export \
1058+/// -- --ignored --nocapture --test-threads=1 proxy_of_real_4k
1059+/// ```
1060+#[test]
1061+#[ignore = "needs the VA-API plugin and a real library"]
1062+fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() {
1063+ pin_hardware();
1064+ let Some(film) = engine::real_library::film("hevc_4k_hdr") else {
1065+ return;
1066+ };
1067+ let out = engine::proxy::path_for(&film).expect("a cache directory");
1068+ let _ = std::fs::remove_file(&out);
1069+ let (meta, _) = engine::demux::Demuxer::open(&film).expect("open the film");
1070+ let duration = f64::from(meta.frame_count) / meta.frame_rate;
1071+ println!(
1072+ "film: {}x{} {:.3} fps, {duration:.0}s",
1073+ meta.width, meta.height, meta.frame_rate
1074+ );
1075+
1076+ let job = engine::proxy::generate(&film).expect("start the proxy");
1077+ let window = Duration::from_secs(60);
1078+ let started = Instant::now();
1079+ while started.elapsed() < window && !job.is_finished() {
1080+ std::thread::sleep(Duration::from_millis(200));
1081+ }
1082+ let elapsed = started.elapsed().as_secs_f64();
1083+ let made = f64::from(job.progress()) * duration;
1084+ let seat = job.encoder().unwrap_or_default();
1085+ println!(
1086+ "proxy: {made:.0}s of film in {elapsed:.0}s = {:.2}x realtime, seat {seat}",
1087+ made / elapsed
1088+ );
1089+ // The silent-software trap: a run without the plugin on the path measures
1090+ // the fallback and calls it hardware.
1091+ assert!(
1092+ seat.contains("HW encode"),
1093+ "not the hardware seat ({seat}): LD_LIBRARY_PATH must name the plugin"
1094+ );
1095+ // Twice realtime, not once: the rubric's floor, and the number this seat
1096+ // actually measured (2.35x warm, 3.54x with the page cache hot). A `>= 1.0`
1097+ // here would let a run at 1.2x -- half the speed this shipped at -- pass as
1098+ // green. Cold, the disk is the ceiling instead (~1x on a first pass over an
1099+ // uncached remux), so this wants a film the cache has already seen, which
1100+ // is what a second run of it is.
1101+ assert!(
1102+ made / elapsed >= 2.0,
1103+ "{:.2}x realtime is under the 2x floor this shipped at",
1104+ made / elapsed
1105+ );
1106+
1107+ // Cancel stops the reading, and a proxy that was not finished is not left
1108+ // lying around under the name a finished one would have.
1109+ job.cancel();
1110+ let stopped = Instant::now();
1111+ while !job.is_finished() {
1112+ assert!(
1113+ stopped.elapsed() < Duration::from_secs(30),
1114+ "the proxy did not stop when cancelled"
1115+ );
1116+ std::thread::sleep(Duration::from_millis(50));
1117+ }
1118+ assert!(job.outcome().expect("an outcome").is_err(), "cancelled");
1119+ assert!(
1120+ !out.exists(),
1121+ "a cancelled proxy left {} behind",
1122+ out.display()
1123+ );
1124+ assert!(!part_path(&out).exists(), "a cancelled proxy left its .part");
1125+ assert_eq!(engine::proxy::cached(&film), None);
1126+}
crates/engine/tests/saveload.rsmodified+6 -6
@@ -208,7 +208,7 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_7() {
208 let v2 = dir.join("new.edith");208 let v2 = dir.join("new.edith");
209 loaded.save_project(&v2).expect("save");209 loaded.save_project(&v2).expect("save");
210 let text = std::fs::read_to_string(&v2).expect("read back");210 let text = std::fs::read_to_string(&v2).expect("read back");
211- assert!(text.starts_with("edith 11\n"), "{text}");211+ assert!(text.starts_with("edith 12\n"), "{text}");
212 assert!(212 assert!(
213 text.contains("\nresolution 1280 720\n"),213 text.contains("\nresolution 1280 720\n"),
214 "a project with no resolution of its own is saved at source 0's: {text}"214 "a project with no resolution of its own is saved at source 0's: {text}"
@@ -296,7 +296,7 @@ fn a_version_4_project_holds_more_than_two_lanes() {
296 loaded.save_project(&again).expect("save");296 loaded.save_project(&again).expect("save");
297 assert_eq!(297 assert_eq!(
298 std::fs::read_to_string(&again).expect("read back"),298 std::fs::read_to_string(&again).expect("read back"),
299- "edith 11\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\299+ "edith 12\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
300 video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\300 video 1 0 0 30 0 3 - - fit 1000\naudio 1\n\
301 video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n",301 video 2 40 0 20 0 - - - fit 1000\naudio 2 0 0 30 0 3 - - fit 1000\n",
302 "a four-lane project is written as it was read, three versions on"302 "a four-lane project is written as it was read, three versions on"
@@ -326,7 +326,7 @@ fn a_version_5_project_carries_per_clip_equalizers() {
326 loaded.save_project(&again).expect("save");326 loaded.save_project(&again).expect("save");
327 assert_eq!(327 assert_eq!(
328 std::fs::read_to_string(&again).expect("read back"),328 std::fs::read_to_string(&again).expect("read back"),
329- "edith 11\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\329+ "edith 12\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
330 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\330 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
331 eq 12000.0:6.25:0.5:hs\n\331 eq 12000.0:6.25:0.5:hs\n\
332 video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\332 video 1 0 0 30 0 - 0 - fit 1000\nvideo 1 30 30 60 0 - 1 - fit 1000\n\
@@ -361,7 +361,7 @@ fn a_version_6_project_carries_per_clip_colours() {
361 loaded.save_project(&again).expect("save");361 loaded.save_project(&again).expect("save");
362 assert_eq!(362 assert_eq!(
363 std::fs::read_to_string(&again).expect("read back"),363 std::fs::read_to_string(&again).expect("read back"),
364- "edith 11\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\364+ "edith 12\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
365 eq 80.0:-3.0:0.707:ls\n\365 eq 80.0:-3.0:0.707:ls\n\
366 color 0.1:1.2:0.9:-0.3\n\366 color 0.1:1.2:0.9:-0.3\n\
367 color -0.25:1.0:0.0:0.5\n\367 color -0.25:1.0:0.0:0.5\n\
@@ -411,7 +411,7 @@ fn a_version_7_project_carries_a_resolution_and_fit_policies() {
411 loaded.save_project(&again).expect("save");411 loaded.save_project(&again).expect("save");
412 assert_eq!(412 assert_eq!(
413 std::fs::read_to_string(&again).expect("read back"),413 std::fs::read_to_string(&again).expect("read back"),
414- "edith 11\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\414+ "edith 12\nplayhead 0\nresolution 960 720\nfps 30.0\nsource 0 test_av.mp4\n\
415 video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\415 video 1 0 0 30 0 - - - fill 1000\nvideo 1 30 30 60 0 - - - center 1000\n\
416 audio 1 0 0 60 0 - - - fit 1000\n",416 audio 1 0 0 60 0 - - - fit 1000\n",
417 "a v7 project is written back as the v8 it now is: the same clips, each \417 "a v7 project is written back as the v8 it now is: the same clips, each \
@@ -669,7 +669,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() {
669 669
670 for (text, want) in [670 for (text, want) in [
671 (671 (
672- "edith 12\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n",672+ "edith 13\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - - fit\n",
673 "line 1",673 "line 1",
674 ),674 ),
675 // An eq index the table does not hold, and a band shape there is none.675 // An eq index the table does not hold, and a band shape there is none.
crates/engine/tests/silence.rsmodified+2 -1
@@ -376,13 +376,14 @@ fn scanning_a_clip_and_cutting_what_it_finds() {
376 (1920, 1080),376 (1920, 1080),
377 None,377 None,
378 p.tone(),378 p.tone(),
379+ false,
379 p.limiter(),380 p.limiter(),
380 0,381 0,
381 )382 )
382 .expect("save");383 .expect("save");
383 let text = std::fs::read_to_string(&file).expect("read it back");384 let text = std::fs::read_to_string(&file).expect("read it back");
384 assert!(385 assert!(
385- text.starts_with("edith 11"),386+ text.starts_with("edith 12"),
386 "{:?}",387 "{:?}",
387 &text[..16.min(text.len())]388 &text[..16.min(text.len())]
388 );389 );
crates/engine/tests/subtitles.rsmodified+1 -1
@@ -259,7 +259,7 @@ fn a_project_keeps_its_subtitles_across_a_save() {
259 let project = dir.join("cut.edith");259 let project = dir.join("cut.edith");
260 session.save_project(&project).expect("save");260 session.save_project(&project).expect("save");
261 let text = std::fs::read_to_string(&project).expect("read the project back");261 let text = std::fs::read_to_string(&project).expect("read the project back");
262- assert!(text.starts_with("edith 11\n"), "{text}");262+ assert!(text.starts_with("edith 12\n"), "{text}");
263 assert!(263 assert!(
264 text.contains("\nsubtitle - test_subs.srt\n"),264 text.contains("\nsubtitle - test_subs.srt\n"),
265 "the reference is written relative, and no cue is: {text}"265 "the reference is written relative, and no cue is: {text}"