forge
Explore
Log in

Don't you dare go Hollow

"no picture in it" is a header's answer, not an extension's guess

Browse files at this commit

627d623431bcae85a1f51065c854102d582618aeAhmet Kaan GümüşParent: 2c0dabd
  • fix
    • "no picture in it" is a header's answer, not an extension's guess
Show full message
🐛 fix(engine): "no picture in it" is a header's answer, not an extension's guess

Two residuals of the proxy round, and the doc line that makes a hardware
run measure the code it was meant to.

The quiet answer for a file that is not a film was name-shaped: an
audio-only `.mp4`, `.mkv` or `.mov` is a video container with no video
track in it, so no extension can tell and every one of them still opened,
failed and said "NO PROXY" about a song. Only the header knows, and the
demuxer already knew -- it just said so in prose, which is the one thing
in this engine free to be reworded. `NoVideoTrack` makes it a type: the
two doors that mean *this file carries no picture at all* return it, a
front-end still shows the sentence it always showed, and the proxy takes
it as the same silent `None` a 1080p film gets. A picture in a codec
nothing here decodes is not that class and stays loud.

...and the cap was soft by exactly what it was capping: the sweep aimed
at 20 GB and then two encodes wrote gigabytes on top of it, so the disk
held the cap plus a film per encode (~43 GB worst case). It now sweeps to
`CACHE_CAP - reserve`, where the reserve is what those encodes will
really take -- the file's own bits-per-pixel arithmetic times the 1.25 the
hardware seat overshoots its asked-for rate by -- held to half the cap so
a single 4K feature cannot empty the cache to make room for itself.
`AT_ONCE` moves into the engine beside that arithmetic: how many encodes
run at once *is* how much room the sweep must leave, and two places
holding that number is one place for them to disagree.

The ignored hardware tests now say to build `-p engine-hw --release` as
its own step: `--tests` does not rebuild the cdylib, so the plugin beside
the test binary is whatever was there last time -- and a hardware claim
measured against a stale one is a claim about code nobody edited.

One commit rather than two: both fixes are in `proxy.rs`, in regions a
hunk split cannot separate cleanly (it was tried once and produced a
corrupt intermediate), so each is named here instead.
crates/app/src/layout.rsmodified+5 -5
@@ -38,11 +38,11 @@ pub(crate) const LABEL_MIN_W: f32 = 36.;
3838 /// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade
3939 /// is a second, finer pass over the visible span only, cached like `waves` is.
4040 pub(crate) const WAVE_BPS: u32 = 40;
41-/// How many stand-ins ([`engine::proxy`]) may be in flight at once. Two, not
42-/// one per core: each is a whole film through a decoder and an encoder, and the
43-/// hardware seat they queue on is a single one -- more of them at once is the
44-/// same work done later, with the editor slower while it happens.
45-pub(crate) const PROXIES_AT_ONCE: usize = 2;
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;
4646 /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
4747 /// and a path with a point per pixel is a path per repaint.
4848 pub(crate) const WAVE_COL: f32 = 2.;
crates/engine/src/demux.rsmodified+50 -7
@@ -129,6 +129,40 @@ fn mp4_codec(fourcc: &[u8; 4]) -> Option<Codec> {
129129 .map(|&(codec, ..)| codec)
130130 }
131131
132+/// The one refusal that is an **answer**: this file carries no picture at all
133+/// that this engine reads -- a song in a video container, an audio-only mp4 or
134+/// Matroska, a `.mka` under any name.
135+///
136+/// A type rather than a sentence, because two callers want two different things
137+/// from it. A front-end shows its `Display`, which is the words it always was,
138+/// and refuses the import by them. [`crate::proxy`] wants to tell it from *"this
139+/// file is broken"*: a song is not a film to stand in for and saying "NO PROXY"
140+/// about one is a refusal nobody asked for, while a film that will not open is
141+/// worth a line. Neither could tell them apart by matching on prose, and prose
142+/// is the one thing in this engine that is free to be reworded.
143+///
144+/// A file whose picture is in a codec nothing here decodes is **not** this: it
145+/// has a video track, the refusal names the codec, and that stays loud.
146+#[derive(Debug)]
147+pub struct NoVideoTrack(String);
148+
149+impl std::fmt::Display for NoVideoTrack {
150+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151+ f.write_str(&self.0)
152+ }
153+}
154+
155+impl std::error::Error for NoVideoTrack {}
156+
157+impl NoVideoTrack {
158+ /// Whether `error` is one of these, however deep in a `Box` it is: the
159+ /// question [`crate::proxy`] asks, in one place so no caller downcasts by
160+ /// hand.
161+ pub fn is_it(error: &crate::Error) -> bool {
162+ error.downcast_ref::<Self>().is_some()
163+ }
164+}
165+
132166 #[derive(Debug, Clone, Copy, PartialEq)]
133167 pub struct VideoMeta {
134168 pub width: u32,
@@ -943,10 +977,14 @@ impl MkvDemuxer {
943977 None => format!(
944978 "{codec} video in a Matroska file is not supported — AV1, HEVC, H.264 and VP9 are"
945979 ),
946- },
947- None => "this Matroska file has no video track".to_string(),
948- }
949- .into());
980+ }
981+ .into(),
982+ // No picture in it *at all*, which is a fact about the file
983+ // and not a fault: [`NoVideoTrack`] says why that is a type.
984+ None => crate::Error::from(NoVideoTrack(
985+ "this Matroska file has no video track".to_string(),
986+ )),
987+ });
950988 }
951989 };
952990 // A picture nothing here can put back together is a refusal at the door,
@@ -2372,10 +2410,15 @@ fn mp4_no_video<R>(path: &Path, reader: &Mp4Reader<R>) -> crate::Error {
23722410 None => {
23732411 format!("{kind} video in this mp4 is not supported — H.264, HEVC, VP9 and AV1 are")
23742412 }
2375- },
2376- None => "no H.264, HEVC, VP9 or AV1 video track in file".to_string(),
2413+ }
2414+ .into(),
2415+ // Nothing with a picture in it that this reads -- an audio-only mp4,
2416+ // which is a thing a person really does hand an editor. The Matroska
2417+ // door's own answer, and the same type for the same reason.
2418+ None => crate::Error::from(NoVideoTrack(
2419+ "no H.264, HEVC, VP9 or AV1 video track in file".to_string(),
2420+ )),
23772421 }
2378- .into()
23792422 }
23802423
23812424 /// Bits per luma sample out of a VP9 keyframe's uncompressed header (VP9
crates/engine/src/proxy.rsmodified+159 -14
@@ -34,7 +34,7 @@
3434 use std::path::{Path, PathBuf};
3535 use std::time::UNIX_EPOCH;
3636
37-use crate::demux::{Codec, Demuxer, VideoMeta};
37+use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta};
3838 use crate::export::{ExportHandle, ExportSettings, Format};
3939 use crate::project::{Clip, LaneKind, Project, Source, Speed};
4040 use crate::scale::FitPolicy;
@@ -51,11 +51,37 @@ pub const LONG_EDGE: u32 = 1280;
5151 /// ~11.5 GB at ~1.37 MB per second of film), or a dozen of an ordinary length.
5252 ///
5353 /// A cap is not a nicety here. Proxies are written *without being asked for*,
54-/// on import, two at a time -- so without one the answer to "how much of the
55-/// disk does this take" is "all of it, eventually". Over the cap, the least
56-/// recently used are deleted until it fits ([`sweep`]).
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.
5766 pub const CACHE_CAP: u64 = 20 * 1024 * 1024 * 1024;
5867
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+
5985 /// Bits per pixel per second a proxy is coded at, [`crate::export`]'s own rate
6086 /// rule at three times the number: every frame being an IDR means no frame
6187 /// borrows anything from its neighbours, so the same picture at the inter rate
@@ -114,6 +140,29 @@ pub fn path_for(source: &Path) -> Option<PathBuf> {
114140 Some(dir.join(format!("{:016x}.mp4", crate::demux::fnv1a(&bytes))))
115141 }
116142
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+
117166 /// Deletes least-recently-used stand-ins until the directory holds at most
118167 /// `cap` bytes, and reports what it holds afterwards.
119168 ///
@@ -254,16 +303,26 @@ pub fn generate(source: &Path) -> crate::Result<Job> {
254303 /// cluster walk, so asking `wanted` and then `generate` separately would pay
255304 /// for it twice.
256305 ///
257-/// A song and a still are not films and are answered before that read: neither
258-/// has a picture stream to stand in for, and a demuxer opened on one fails --
259-/// which used to reach a front-end as "no proxy" on a `.wav`, a refusal about
260-/// something nobody had asked for. `Ok(None)` is the true answer, and it is the
261-/// same one a 1080p H.264 film gets.
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.
262318 pub fn generate_if_wanted(source: &Path) -> crate::Result<Option<Job>> {
263319 if crate::is_audio(source) || crate::is_image(source) {
264320 return Ok(None);
265321 }
266- started(source, wanted)
322+ match started(source, wanted) {
323+ Err(e) if NoVideoTrack::is_it(&e) => Ok(None),
324+ other => other,
325+ }
267326 }
268327
269328 /// Both doors: the cache is looked at, the header is read once, and `only_if`
@@ -284,10 +343,11 @@ fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result<Opti
284343 if let Some(dir) = out.parent() {
285344 std::fs::create_dir_all(dir)?;
286345 // Before the write, which is the only thing that makes this directory
287- // bigger: what is already there is brought under the cap first, so the
288- // disk never carries more stand-ins than [`CACHE_CAP`] plus the one
289- // being written.
290- sweep(dir, CACHE_CAP);
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)));
291351 }
292352 // What a killed editor left behind: the export worker deletes its own part
293353 // file when it is cancelled or fails, but nothing can delete it for a
@@ -401,6 +461,31 @@ mod tests {
401461 assert_eq!(size_for(&meta(1, 1, Codec::H264)), (2, 2), "never zero");
402462 }
403463
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+
404489 /// The cap keeps the directory a cache and not a second copy of the
405490 /// library: over it, the least recently used go until it fits, and a
406491 /// half-written one is never taken (it is being written *now*) though its
@@ -448,6 +533,12 @@ mod tests {
448533 ///
449534 /// Real files, because the point is that nothing reads them: a demuxer
450535 /// 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.
451542 #[test]
452543 fn a_song_and_a_still_are_never_stood_in_for() {
453544 let dir = crate::scratch::Scratch::dir("proxy-not-a-film");
@@ -462,6 +553,60 @@ mod tests {
462553 );
463554 assert_eq!(cached(&file), None, "{name} left nothing in the cache");
464555 }
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");
465610 }
466611
467612 /// The staleness rule *is* the name: touch the source and the old proxy is
crates/engine/tests/export.rsmodified+8 -3
@@ -6,11 +6,16 @@
66 //! H.264 encode entrypoint, so they are `#[ignore]`d:
77 //!
88 //! ```text
9-//! cargo build -p engine -p engine-hw --release
9+//! cargo build -p engine-hw --release
1010 //! LD_LIBRARY_PATH=target/release \
1111 //! cargo test -p engine --release --test export -- --ignored --nocapture --test-threads=1
1212 //! ```
1313 //!
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+//!
1419 //! Both env pins are process-wide, hence `--test-threads=1` for the ignored run.
1520
1621 use std::fs::File;
@@ -995,7 +1000,7 @@ fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() {
9951000 /// no proxy at all. The seat that answers this is `vh_enc_open_intra`.
9961001 ///
9971002 /// ```text
998-/// cargo build -p engine -p engine-hw --release
1003+/// cargo build -p engine-hw --release # its own step: `--tests` leaves it stale
9991004 /// LD_LIBRARY_PATH=target/release cargo test -p engine --release --test export \
10001005 /// -- --ignored --nocapture --test-threads=1 hardware_proxy
10011006 /// ```
@@ -1048,7 +1053,7 @@ fn a_hardware_proxy_is_every_frame_a_starting_point_too() {
10481053 /// number wanted is a rate, not a wall time.
10491054 ///
10501055 /// ```text
1051-/// cargo build -p engine -p engine-hw --release
1056+/// cargo build -p engine-hw --release # its own step: `--tests` leaves it stale
10521057 /// LD_LIBRARY_PATH=target/release cargo test -p engine --release --test export \
10531058 /// -- --ignored --nocapture --test-threads=1 proxy_of_real_4k
10541059 /// ```