forge
Explore
Log in

Don't you dare go Hollow

The sound of a feature film is measured in a minute, not in half an hour

Browse files at this commit

3fc675351f2b4381bbb62e7fdff9d3e26a21603eAhmet Kaan GümüşParent: c8f62cb
  • fix
    • the sound of a feature film is measured in a minute, not in half an hour
Show full message
⚡ fix(export): the sound of a feature film is measured in a minute, not in half an hour

An mkv export of a two-and-a-half-hour film wrote zero bytes for twenty-one
minutes and then failed its own test's ten-minute cap. All of it was the Opus
fidelity gate: `ruopus` is built here without its `spectrograms` feature, so its
inverse MDCT is an O(n²) DFT with a `sin_cos` per term and decodes at 0.2x real
time. Measured on a two-minute window of a real 4K film (the new
`export_audio_cost` example, and the three `export audio:` lines it reads):

    mix (E-AC-3 5.1 -> stereo)   0.7 s
    Opus encode (opus-rs)        0.3 s
    fidelity decode-back        24.2 s   <- 98.6% of the pass

So the gate now samples: twelve five-second windows spread across the track, a
warm-up per window because CELT predicts across frames, and the *worst* window
is the answer -- which is harsher than the old whole-track sum, where a ruined
minute averaged away against two good hours. What it looks for survives
sampling: OPUS_MAX_KBPS's cliff is a rate the encoder falls off, not a defect of
one bar of music. A window with no sound in it is skipped rather than scored
0.0, which is what a silent timeline used to score before falling back to AAC.

...and the export no longer decides what it is *after* paying for the sound:
CopyPlan is consulted first, so the line on screen says "copy" from the first
second, and the audio pass owns the head of the progress bar instead of leaving
it at zero for as long as it runs.

Beside them, for the card that has been predicting the wrong export in both
directions: `planned_seats` asks the export's own gates what it would open, and
`sync_points` hands a front-end the frames a cut may be placed on.

    cargo test -p engine --release --test video_copy -- --include-ignored
      7 passed in 157.6 s (was: failing the 600 s cap)
crates/engine/examples/export_audio_cost.rsadded+79 -0
@@ -0,0 +1,79 @@
1+//! What the *sound* of a copied export costs, on a window of a real film.
2+//!
3+//! The picture of an untouched Matroska timeline is copied block for block, so
4+//! everything an export of a feature film waits for is in the audio pass. This
5+//! runs that pass over the first `minutes` of a file and prints the engine's own
6+//! stage lines (`export audio: ...`), which is how the per-minute cost of the
7+//! mix, the Opus encode and the fidelity gate are told apart.
8+//!
9+//! ```text
10+//! cargo run --release -p engine --example export_audio_cost -- <film.mkv> [minutes] [out.mkv]
11+//! ```
12+//!
13+//! The output file is overwritten; name a scratch path, never a source.
14+
15+use std::path::PathBuf;
16+use std::time::{Duration, Instant};
17+
18+use engine::PlaybackSession;
19+use engine::export::{ExportSettings, Format};
20+use engine::project::Lane;
21+
22+fn main() {
23+ let mut args = std::env::args_os().skip(1);
24+ let film = PathBuf::from(
25+ args.next()
26+ .expect("usage: export_audio_cost <film.mkv> [minutes] [out.mkv]"),
27+ );
28+ let minutes: f64 = args
29+ .next()
30+ .and_then(|s| s.to_str().and_then(|s| s.parse().ok()))
31+ .unwrap_or(5.0);
32+ let out = args.next().map_or_else(
33+ || PathBuf::from(std::env::temp_dir()).join("ve_export_audio_cost.mkv"),
34+ PathBuf::from,
35+ );
36+
37+ // On a sync point, or the picture is re-encoded and the measurement is of
38+ // the encoder rather than of the sound.
39+ let (_, demuxer) = engine::demux::Demuxer::open(&film).expect("open the film");
40+ let engine::demux::Demuxer::Mkv(mut source) = demuxer else {
41+ panic!("the film is not Matroska");
42+ };
43+
44+ let mut session = PlaybackSession::open(&film).expect("open the film");
45+ let fps = session.meta().frame_rate;
46+ let at = ((minutes * 60.0 * fps) as usize..source.block_count())
47+ .find(|&i| source.is_sync(i))
48+ .expect("a sync point after the mark");
49+ if session.cut_at(at as f64 / fps) {
50+ // Everything after the cut goes; what is left is the window measured.
51+ while session.delete_clip(Lane::V1, 1) {}
52+ }
53+ println!(
54+ "{}: {:.1} min of timeline at {fps:.3} fps -> {}",
55+ film.display(),
56+ session.timeline_duration() / 60.0,
57+ out.display()
58+ );
59+
60+ let settings = ExportSettings {
61+ format: Format::Hevc,
62+ ..Default::default()
63+ };
64+ let started = Instant::now();
65+ let handle = session.export_to_with(&out, &settings);
66+ while !handle.is_finished() {
67+ std::thread::sleep(Duration::from_millis(200));
68+ }
69+ let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
70+ println!(
71+ "export: {:.1} s, {} MB ({})",
72+ started.elapsed().as_secs_f64(),
73+ bytes / 1_000_000,
74+ handle.encoders().unwrap_or_default()
75+ );
76+ if let Some(Err(e)) = handle.result() {
77+ println!("export failed: {e}");
78+ }
79+}
crates/engine/src/demux.rsmodified+29 -0
@@ -1498,6 +1498,35 @@ pub struct CodedBlock<'a> {
1498 pub ts_ns: i64,1498 pub ts_ns: i64,
1499 }1499 }
1500 1500
1501+/// Every block of `path`'s picture track a decoder may be started from, by the
1502+/// block index the whole engine counts a source's frames in -- the frames a cut
1503+/// may be placed on for the export to copy the film instead of coding it again
1504+/// ([`crate::export::planned_seats`] is the same question asked of a whole
1505+/// timeline).
1506+///
1507+/// Empty for anything that is not Matroska, which is exactly the set of files
1508+/// the copy path refuses anyway, and for a file whose clusters cannot be walked.
1509+///
1510+/// Costs that walk, once per file (6.7 s on a 12.9 GB film, then a sidecar read
1511+/// of a few milliseconds -- [`MkvDemuxer::is_sync`]): ask it off a render
1512+/// thread.
1513+pub fn sync_points(path: &Path) -> Vec<u32> {
1514+ if !is_matroska(path) {
1515+ return Vec::new();
1516+ }
1517+ let Ok((_, Demuxer::Mkv(mut demuxer))) = Demuxer::open(path) else {
1518+ return Vec::new();
1519+ };
1520+ // `is_sync` completes the index on its first call, so the count is asked
1521+ // after it: before that it is the open window's, not the file's.
1522+ if !demuxer.is_sync(0) && demuxer.block_count() == 0 {
1523+ return Vec::new();
1524+ }
1525+ (0..demuxer.block_count() as u32)
1526+ .filter(|&i| demuxer.is_sync(i as usize))
1527+ .collect()
1528+}
1529+
1501 /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or1530 /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or
1502 /// `None` for a Matroska file with no sound at all. Header only, and only worth1531 /// `None` for a Matroska file with no sound at all. Header only, and only worth
1503 /// calling once a session has come up silent: a Matroska file's sound is read1532 /// calling once a session has come up silent: a Matroska file's sound is read
crates/engine/src/export.rsmodified+247 -17
@@ -86,6 +86,20 @@ use crate::tonemap::{self, ToneMapper};
86 /// without a lock, fine enough for any progress bar.86 /// without a lock, fine enough for any progress bar.
87 const PROGRESS_SCALE: u32 = 1_000;87 const PROGRESS_SCALE: u32 = 1_000;
88 88
89+/// The head of the bar the *sound* owns, before a picture is written at all.
90+/// The mix is decoded, encoded and measured before the muxer exists ([`run`]
91+/// says why), and on a feature film that is a minute or two in which a bar
92+/// pinned at zero is the only thing on screen -- which reads as an export that
93+/// has hung. Small, because the picture is still nearly all of the work.
94+const AUDIO_BAND: u32 = PROGRESS_SCALE / 20;
95+
96+/// Where the bar stands with `done` of `total` pictures written: the sound's
97+/// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is
98+/// left rather than starting again from zero.
99+fn picture_progress(done: u32, total: u32) -> u32 {
100+ AUDIO_BAND + done.min(total) * (PROGRESS_SCALE - AUDIO_BAND) / total.max(1)
101+}
102+
89 /// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands103 /// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
90 /// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%.104 /// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%.
91 const BITS_PER_PIXEL: f64 = 0.1;105 const BITS_PER_PIXEL: f64 = 0.1;
@@ -807,6 +821,48 @@ pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'st
807 .then(|| video_label(settings.format, hw_seat(meta, settings).is_some()))821 .then(|| video_label(settings.format, hw_seat(meta, settings).is_some()))
808 }822 }
809 823
824+/// What [`start`] would open for *this* timeline: the picture's seat -- or the
825+/// copy that means there is no encoder at all -- and the sound's, asked of the
826+/// very gates the export asks ([`CopyPlan::of`] and [`copy_audio`]'s) rather
827+/// than of the format alone.
828+///
829+/// This exists because the card and the running export used to disagree in both
830+/// directions on the same file: the card named a software HEVC encode for a cut
831+/// the engine copied, and named an AAC copy for a Matroska source whose sound
832+/// no sample table holds and which therefore always re-encodes. A prediction
833+/// that is not the decision is worse than no prediction, because a person plans
834+/// their evening around it.
835+///
836+/// Costs what [`planned_video`] costs (an encoder opened and closed) plus a
837+/// header read per source and, once per file, its cluster walk: ask it off a
838+/// render thread and keep the answer until the timeline or the settings change.
839+pub fn planned_seats(
840+ project: &Project,
841+ meta: &VideoMeta,
842+ settings: &ExportSettings,
843+) -> (Option<&'static str>, &'static str) {
844+ let video = settings.format.has_video().then(|| {
845+ match CopyPlan::of(project, meta, settings).is_some() {
846+ true => "copy (source packets)",
847+ false => video_label(settings.format, hw_seat(meta, settings).is_some()),
848+ }
849+ });
850+ // The half [`audio_label`] cannot know from the format: a copy is a *sample
851+ // table's* packets ([`copy_audio`] hands them to `copy_multi_streams`), and
852+ // a Matroska file has none -- so every mkv source re-encodes, however
853+ // untouched its lane is. Extension only, which is what `is_matroska`
854+ // reads, so this costs nothing beyond what is already open.
855+ let copyable = !forces_encode(project)
856+ && !project
857+ .sources()
858+ .iter()
859+ .any(|source| crate::demux::is_matroska(&source.path));
860+ (
861+ video,
862+ audio_label(project, settings.format, has_sound(project), Some(copyable)),
863+ )
864+}
865+
810 fn settle(shared: &Shared, result: crate::Result<()>) {866 fn settle(shared: &Shared, result: crate::Result<()>) {
811 *shared.outcome.lock().unwrap() = Some(result);867 *shared.outcome.lock().unwrap() = Some(result);
812 // Published last: a caller that sees the flag is guaranteed the outcome.868 // Published last: a caller that sees the flag is guaranteed the outcome.
@@ -848,6 +904,7 @@ fn copy_audio(
848 meta: &VideoMeta,904 meta: &VideoMeta,
849 kbps: u32,905 kbps: u32,
850 mkv: bool,906 mkv: bool,
907+ shared: &Shared,
851 ) -> crate::Result<Option<ExportAudio>> {908 ) -> crate::Result<Option<ExportAudio>> {
852 // The segments name their source, and the copy carries its packet-rounding909 // The segments name their source, and the copy carries its packet-rounding
853 // debt across a source join exactly as across a cut, so a timeline spanning910 // debt across a source join exactly as across a cut, so a timeline spanning
@@ -872,7 +929,7 @@ fn copy_audio(
872 // whole comment is about.929 // whole comment is about.
873 let lanes = project.audio_segments_from(0, meta.frame_rate);930 let lanes = project.audio_segments_from(0, meta.frame_rate);
874 let [segments] = &lanes[..] else {931 let [segments] = &lanes[..] else {
875- return encode_audio(project, meta, kbps, mkv);932+ return encode_audio(project, meta, kbps, mkv, shared);
876 };933 };
877 // ...and the same list names *which* lane those clips sit on, which is the934 // ...and the same list names *which* lane those clips sit on, which is the
878 // only way to ask what has been done to them.935 // only way to ask what has been done to them.
@@ -910,7 +967,7 @@ fn copy_audio(
910 // such a lane would write it at unity and unlimited, silently.967 // such a lane would write it at unity and unlimited, silently.
911 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());968 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
912 if speeded || equalized(project) || mastered(project) {969 if speeded || equalized(project) || mastered(project) {
913- return encode_audio(project, meta, kbps, mkv);970+ return encode_audio(project, meta, kbps, mkv, shared);
914 }971 }
915 // What is left is a copy the *sources* may still not be able to give: AAC972 // What is left is a copy the *sources* may still not be able to give: AAC
916 // inside a Matroska file (readable, but not out of a sample table this walks973 // inside a Matroska file (readable, but not out of a sample table this walks
@@ -930,7 +987,7 @@ fn copy_audio(
930 // (they are not in a sample table) and every one of them re-encodes.987 // (they are not in a sample table) and every one of them re-encodes.
931 opus_pre_skip: None,988 opus_pre_skip: None,
932 })),989 })),
933- Err(_) => encode_audio(project, meta, kbps, mkv),990+ Err(_) => encode_audio(project, meta, kbps, mkv, shared),
934 }991 }
935 }992 }
936 993
@@ -1150,7 +1207,7 @@ impl CopyPlan {
1150 done += 1;1207 done += 1;
1151 shared1208 shared
1152 .progress1209 .progress
1153- .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);1210+ .store(picture_progress(done, total), Ordering::Relaxed);
1154 }1211 }
1155 }1212 }
1156 // Everything up to here is still cancellable, exactly as the encoded1213 // Everything up to here is still cancellable, exactly as the encoded
@@ -1184,11 +1241,17 @@ fn encode_audio(
1184 meta: &VideoMeta,1241 meta: &VideoMeta,
1185 kbps: u32,1242 kbps: u32,
1186 mkv: bool,1243 mkv: bool,
1244+ shared: &Shared,
1187 ) -> crate::Result<Option<ExportAudio>> {1245 ) -> crate::Result<Option<ExportAudio>> {
1188 let sources = project.audio_sources();1246 let sources = project.audio_sources();
1189 let segs = project.audio_segments_from(0, meta.frame_rate);1247 let segs = project.audio_segments_from(0, meta.frame_rate);
1190 let eqs = project.audio_eqs_from(0, meta.frame_rate);1248 let eqs = project.audio_eqs_from(0, meta.frame_rate);
1191 let speeds = project.audio_speeds_from(0, meta.frame_rate);1249 let speeds = project.audio_speeds_from(0, meta.frame_rate);
1250+ // Coarse stage timers, in the same voice as `export video: copy` below: an
1251+ // export of a feature film spends minutes in here before a byte of picture
1252+ // is written, and which minutes went where is the first question asked of a
1253+ // slow export. Three lines an export, so they stay on.
1254+ let mixed = std::time::Instant::now();
1192 let Some((audio, chunks)) = AudioSession::open_mixed_streams_master(1255 let Some((audio, chunks)) = AudioSession::open_mixed_streams_master(
1193 &sources,1256 &sources,
1194 &segs,1257 &segs,
@@ -1219,8 +1282,19 @@ fn encode_audio(
1219 let mut samples: Vec<f32> = Vec::with_capacity(total);1282 let mut samples: Vec<f32> = Vec::with_capacity(total);
1220 for chunk in chunks {1283 for chunk in chunks {
1221 samples.extend(chunk.samples);1284 samples.extend(chunk.samples);
1285+ // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of
1286+ // the three stages and the only one that can be counted as it goes.
1287+ shared.progress.store(
1288+ (samples.len().min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32,
1289+ Ordering::Relaxed,
1290+ );
1222 }1291 }
1223 samples.resize(total, 0.0);1292 samples.resize(total, 0.0);
1293+ eprintln!(
1294+ "export audio: mixed {:.1} s of sound in {:.1} s",
1295+ total as f64 / f64::from(audio.sample_rate.max(1)) / channels as f64,
1296+ mixed.elapsed().as_secs_f64()
1297+ );
1224 1298
1225 // Opus where the container carries it and the mix is inside the envelope1299 // Opus where the container carries it and the mix is inside the envelope
1226 // this encoder was *measured* correct in ([`encode_opus`]): a Matroska file,1300 // this encoder was *measured* correct in ([`encode_opus`]): a Matroska file,
@@ -1367,6 +1441,7 @@ fn encode_opus(samples: &[f32], kbps: u32) -> crate::Result<Option<(Vec<crate::A
1367 // everybody hears in the first frame of a cut. So the first frame is fed in1441 // everybody hears in the first frame of a cut. So the first frame is fed in
1368 // once to warm the encoder, and thrown away again by the pre-skip: exactly1442 // once to warm the encoder, and thrown away again by the pre-skip: exactly
1369 // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet.1443 // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet.
1444+ let coded = std::time::Instant::now();
1370 let warm = samples.len().min(OPUS_FRAME * 2);1445 let warm = samples.len().min(OPUS_FRAME * 2);
1371 // ...and one silent frame after the sound, for the same delay seen from the1446 // ...and one silent frame after the sound, for the same delay seen from the
1372 // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so1447 // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so
@@ -1396,11 +1471,37 @@ fn encode_opus(samples: &[f32], kbps: u32) -> crate::Result<Option<(Vec<crate::A
1396 // sound in a few hundred milliseconds, against a video encode that is1471 // sound in a few hundred milliseconds, against a video encode that is
1397 // minutes). Upgrade path is deleting it, the day this encoder can be1472 // minutes). Upgrade path is deleting it, the day this encoder can be
1398 // trusted at the rate it is asked for.1473 // trusted at the rate it is asked for.
1474+ let encoded = coded.elapsed().as_secs_f64();
1399 let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16;1475 let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16;
1476+ let measured = std::time::Instant::now();
1400 let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip));1477 let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip));
1478+ eprintln!(
1479+ "export audio: Opus encode {encoded:.1} s, fidelity {fidelity:.4} measured in {:.1} s",
1480+ measured.elapsed().as_secs_f64()
1481+ );
1401 Ok((fidelity >= OPUS_MIN_FIDELITY).then_some((packets, pre_skip)))1482 Ok((fidelity >= OPUS_MIN_FIDELITY).then_some((packets, pre_skip)))
1402 }1483 }
1403 1484
1485+/// Packets one sampled window listens to: 5 s at [`OPUS_FRAME`].
1486+const FIDELITY_WINDOW: usize = 250;
1487+
1488+/// How many of them a long track is judged on -- a minute of sound, wherever
1489+/// the track's length puts them, and a constant cost rather than one that grows
1490+/// with the film ([`opus_fidelity`]).
1491+const FIDELITY_WINDOWS: usize = 12;
1492+
1493+/// Packets decoded into a window and thrown away before it is measured. CELT
1494+/// predicts across frames, so a decoder started cold mid-stream is behind its
1495+/// own history for a few frames; 100 ms is far more than it needs and is not
1496+/// worth counting.
1497+const FIDELITY_WARMUP: usize = 5;
1498+
1499+/// How much sound a window must carry before its correlation means anything:
1500+/// mean square per sample. A window of digital silence -- the head of a film,
1501+/// the gap between a feature and its credits -- correlates with nothing, and
1502+/// failing a track for it would send perfectly good sound to AAC.
1503+const FIDELITY_FLOOR: f64 = 1e-9;
1504+
1404 /// The correlation between `samples` and the decode of `packets` with the first1505 /// The correlation between `samples` and the decode of `packets` with the first
1405 /// `pre_skip` frames dropped: 1.0 is the same waveform, and this codec's failure1506 /// `pre_skip` frames dropped: 1.0 is the same waveform, and this codec's failure
1406 /// mode lands near 0.1. Streamed packet by packet -- the decode is never held,1507 /// mode lands near 0.1. Streamed packet by packet -- the decode is never held,
@@ -1409,26 +1510,86 @@ fn encode_opus(samples: &[f32], kbps: u32) -> crate::Result<Option<(Vec<crate::A
1409 ///1510 ///
1410 /// A packet the decoder refuses is 0.0 and no argument: a track this project1511 /// A packet the decoder refuses is 0.0 and no argument: a track this project
1411 /// cannot read is exactly what this is here to catch.1512 /// cannot read is exactly what this is here to catch.
1513+///
1514+/// **Sampled, above a minute of sound, and the worst window is the answer.**
1515+/// This decode is the whole cost of exporting a feature film: `ruopus` runs its
1516+/// inverse MDCT at 0.2x real time here (measured, 24.2 s for 121.5 s of stereo),
1517+/// so judging every packet of a two-and-a-half-hour film costs half an hour
1518+/// before a byte of picture is written -- which is what it did, and what made a
1519+/// copy export that has no encoding to do at all sit at zero for twenty minutes.
1520+/// [`FIDELITY_WINDOWS`] windows spread evenly across the track cost the same
1521+/// minute of decode whatever the film's length, and what they are looking for
1522+/// survives sampling: [`OPUS_MAX_KBPS`]'s cliff is a *rate* the encoder falls
1523+/// off, measured over one-second spans, not a defect of one bar of music. It is
1524+/// also strictly harsher per window than the old whole-track sum, which let a
1525+/// ruined minute average away against two good hours -- the answer here is the
1526+/// worst window, not the mean.
1412 fn opus_fidelity(packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize) -> f64 {1527 fn opus_fidelity(packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize) -> f64 {
1528+ // Short enough to hear all of: every fixture, every unit test, and any
1529+ // track under a minute. There is nothing to sample from.
1530+ let all = FIDELITY_WINDOW * FIDELITY_WINDOWS;
1531+ if packets.len() <= all {
1532+ return window_fidelity(packets, samples, pre_skip, 0, 0, packets.len()).unwrap_or(1.0);
1533+ }
1534+ // Evenly spread, first window at the head: the head is where an encoder's
1535+ // own warm-up would show, and the last starts a window short of the end so
1536+ // no window runs past the packets.
1537+ let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);
1538+ let mut worst: Option<f64> = None;
1539+ for w in 0..FIDELITY_WINDOWS {
1540+ let at = w * step;
1541+ let from = at.saturating_sub(FIDELITY_WARMUP);
1542+ let Some(fidelity) =
1543+ window_fidelity(packets, samples, pre_skip, from, at, at + FIDELITY_WINDOW)
1544+ else {
1545+ continue; // silence: nothing to correlate, and not a failure
1546+ };
1547+ worst = Some(worst.map_or(fidelity, |w: f64| w.min(fidelity)));
1548+ }
1549+ // Every window silent is a silent track, which this codec writes as silence.
1550+ worst.unwrap_or(1.0)
1551+}
1552+
1553+/// [`opus_fidelity`] over `packets[measure..to]`, with `packets[from..measure]`
1554+/// -- the warm-up -- decoded for its state and thrown away. `None` where the
1555+/// source window carries no sound worth correlating ([`FIDELITY_FLOOR`]).
1556+fn window_fidelity(
1557+ packets: &[crate::AacPacket],
1558+ samples: &[f32],
1559+ pre_skip: usize,
1560+ from: usize,
1561+ measure: usize,
1562+ to: usize,
1563+) -> Option<f64> {
1413 let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);1564 let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);
1414 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);1565 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
1415- let mut drop = pre_skip * 2;1566+ // Where in the mix this window's first decoded sample lands: every packet
1416- let mut at = 0;1567+ // is [`OPUS_FRAME`] long, and the pre-skip is what the front of the stream
1417- for packet in packets {1568+ // owes before the first of them is the timeline's frame 0.
1569+ let mut at = (from * OPUS_FRAME * 2).saturating_sub(pre_skip * 2);
1570+ let mut drop = (pre_skip * 2).saturating_sub(from * OPUS_FRAME * 2);
1571+ let mut counted = 0usize;
1572+ for (index, packet) in packets.iter().enumerate().take(to).skip(from) {
1418 let Ok(pcm) = decoder.decode_packet(&packet.bytes) else {1573 let Ok(pcm) = decoder.decode_packet(&packet.bytes) else {
1419- return 0.0;1574+ return Some(0.0);
1420 };1575 };
1421 let pcm = &pcm[drop.min(pcm.len())..];1576 let pcm = &pcm[drop.min(pcm.len())..];
1422 drop = drop.saturating_sub(packet.samples as usize * 2);1577 drop = drop.saturating_sub(packet.samples as usize * 2);
1578+ // The warm-up is decoded for its state and not for its numbers.
1579+ if index < measure {
1580+ at += pcm.len();
1581+ continue;
1582+ }
1423 for (want, got) in samples[at.min(samples.len())..].iter().zip(pcm) {1583 for (want, got) in samples[at.min(samples.len())..].iter().zip(pcm) {
1424 let (x, y) = (f64::from(*want), f64::from(*got));1584 let (x, y) = (f64::from(*want), f64::from(*got));
1425 num += x * y;1585 num += x * y;
1426 da += x * x;1586 da += x * x;
1427 db += y * y;1587 db += y * y;
1428 at += 1;1588 at += 1;
1589+ counted += 1;
1429 }1590 }
1430 }1591 }
1431- num / (da.sqrt() * db.sqrt()).max(1e-12)1592+ (da / counted.max(1) as f64 > FIDELITY_FLOOR).then(|| num / (da.sqrt() * db.sqrt()).max(1e-12))
1432 }1593 }
1433 1594
1434 fn run(1595 fn run(
@@ -1440,16 +1601,29 @@ fn run(
1440 ) -> crate::Result<()> {1601 ) -> crate::Result<()> {
1441 let total = project.timeline_frames();1602 let total = project.timeline_frames();
1442 let sources = project.sources();1603 let sources = project.sources();
1443- // Audio first: a track has to be declared when the muxer is created, which1604+ // The picture's decision first, before a sample of sound is touched: it is
1444- // happens as soon as the first coded picture arrives -- and the Matroska1605+ // the answer that decides what the whole export *is*, it costs one header
1445- // muxer wants the packets themselves that early too, because it interleaves1606+ // read per source, and it is what the line on screen has been missing --
1446- // them into the clusters as it writes. Every video format gets the same1607+ // an export that copies its picture used to say nothing at all for as long
1447- // track: none of them is picture-only any more.1608+ // as its sound took, which on a feature film was minutes. Half a line now,
1609+ // completed by the measured codec once the sound is known below: what is
1610+ // published is never a codec that did not run.
1611+ let plan = CopyPlan::of(project, meta, settings);
1612+ if plan.is_some() {
1613+ eprintln!("export video: copy (source packets)");
1614+ *shared.encoders.lock().unwrap() = Some("copy · working out the sound…".into());
1615+ }
1616+ // ...then the audio: a track has to be declared when the muxer is created,
1617+ // which happens as soon as the first coded picture arrives -- and the
1618+ // Matroska muxer wants the packets themselves that early too, because it
1619+ // interleaves them into the clusters as it writes. Every video format gets
1620+ // the same track: none of them is picture-only any more.
1448 let audio = copy_audio(1621 let audio = copy_audio(
1449 project,1622 project,
1450 meta,1623 meta,
1451 audio_kbps_of(settings),1624 audio_kbps_of(settings),
1452 settings.format.is_mkv(),1625 settings.format.is_mkv(),
1626+ shared,
1453 )?;1627 )?;
1454 let audio_params = audio.as_ref().map(|track| AudioParams {1628 let audio_params = audio.as_ref().map(|track| AudioParams {
1455 freq_index: track.params.freq_index,1629 freq_index: track.params.freq_index,
@@ -1473,6 +1647,9 @@ fn run(
1473 // declared in the header and its blocks are interleaved into the clusters,1647 // declared in the header and its blocks are interleaved into the clusters,
1474 // so the muxer needs the lot before the first picture is written.1648 // so the muxer needs the lot before the first picture is written.
1475 let mut subs = export_subtitles(project, meta, settings);1649 let mut subs = export_subtitles(project, meta, settings);
1650+ // The sound is done, whichever way it went: the bar stands at the head of
1651+ // the picture's own share ([`AUDIO_BAND`]).
1652+ shared.progress.store(AUDIO_BAND, Ordering::Relaxed);
1476 1653
1477 // Before an encoder is opened at all: a timeline nobody has touched, whose1654 // Before an encoder is opened at all: a timeline nobody has touched, whose
1478 // sources this file can hold as they are, is written by copying their coded1655 // sources this file can hold as they are, is written by copying their coded
@@ -1480,8 +1657,7 @@ fn run(
1480 // and the difference between an export bounded by the *edited* spans and one1657 // and the difference between an export bounded by the *edited* spans and one
1481 // that re-encodes a whole film to change a cut. [`CopyPlan`] states the1658 // that re-encodes a whole film to change a cut. [`CopyPlan`] states the
1482 // whole rule; anything at all outside it falls through to the walk below.1659 // whole rule; anything at all outside it falls through to the walk below.
1483- if let Some(plan) = CopyPlan::of(project, meta, settings) {1660+ if let Some(plan) = plan {
1484- eprintln!("export video: copy (source packets)");
1485 *shared.encoders.lock().unwrap() = Some(format!(1661 *shared.encoders.lock().unwrap() = Some(format!(
1486 "copy · {}",1662 "copy · {}",
1487 // The measured codec, exactly as the encoder path below publishes1663 // The measured codec, exactly as the encoder path below publishes
@@ -1719,7 +1895,7 @@ fn run(
1719 done += 1;1895 done += 1;
1720 shared1896 shared
1721 .progress1897 .progress
1722- .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);1898+ .store(picture_progress(done, total), Ordering::Relaxed);
1723 }1899 }
1724 done_here += repeats;1900 done_here += repeats;
1725 }1901 }
@@ -3170,6 +3346,60 @@ mod tests {
3170 );3346 );
3171 }3347 }
3172 3348
3349+ /// The gate on a track too long to listen to whole: it samples, and what it
3350+ /// samples it judges one window at a time. A five-second stretch that is not
3351+ /// the mix fails the whole track -- where the old whole-track sum would have
3352+ /// let it average away against the minutes either side -- and a silent track
3353+ /// is not a failure at all, which is what it used to be scored as (0.0
3354+ /// against a denominator of nothing, and an all-quiet timeline fell back to
3355+ /// AAC for it).
3356+ ///
3357+ /// 61 s of sound: one second past the minute the gate stops listening whole,
3358+ /// which is what puts this on the sampled path at all.
3359+ #[test]
3360+ fn a_long_track_is_judged_by_its_worst_sampled_window() {
3361+ let pcm = two_tones(61);
3362+ let (packets, pre_skip) = encode_opus(&pcm, 96)
3363+ .expect("the encoder opens")
3364+ .expect("and passes its own round trip");
3365+ assert!(
3366+ packets.len() > FIDELITY_WINDOW * FIDELITY_WINDOWS,
3367+ "{} packets is not the sampled path",
3368+ packets.len()
3369+ );
3370+ let pre_skip = usize::from(pre_skip);
3371+ let whole = opus_fidelity(&packets, &pcm, pre_skip);
3372+ assert!(whole >= OPUS_MIN_FIDELITY, "a good track scored {whole:.4}");
3373+
3374+ // One window's worth of the *mix* replaced by its own phase inverse:
3375+ // the packets still decode, they are simply no longer this sound. Placed
3376+ // on a window the gate samples -- window 6 of the twelve, by the same
3377+ // arithmetic the gate spreads them with.
3378+ let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);
3379+ let from = (6 * step * OPUS_FRAME).saturating_sub(pre_skip) * 2;
3380+ let mut ruined = pcm.clone();
3381+ for sample in &mut ruined[from..(from + FIDELITY_WINDOW * OPUS_FRAME * 2).min(pcm.len())] {
3382+ *sample = -*sample;
3383+ }
3384+ let worst = opus_fidelity(&packets, &ruined, pre_skip);
3385+ assert!(
3386+ worst < OPUS_MIN_FIDELITY,
3387+ "five seconds of a long track that is not the mix scored {worst:.4}"
3388+ );
3389+
3390+ // ...and silence is silence: nothing to correlate is not a round trip
3391+ // that failed. Short, because the floor is the same on either path.
3392+ let quiet = vec![0f32; OPUS_RATE as usize * 2 * 2];
3393+ let (packets, pre_skip) = encode_opus(&quiet, 96)
3394+ .expect("the encoder opens")
3395+ .expect("silence is written as Opus, not sent to AAC");
3396+ let fidelity = opus_fidelity(&packets, &quiet, usize::from(pre_skip));
3397+ assert!(
3398+ fidelity >= OPUS_MIN_FIDELITY,
3399+ "a silent track scored {fidelity:.4} and would fall back to AAC"
3400+ );
3401+ }
3402+
3173 /// The one rule that keeps a picture from being converted twice: a frame the3403 /// The one rule that keeps a picture from being converted twice: a frame the
3174 /// tone map has already brought to BT.709 is never handed the 2020 matrix as3404 /// tone map has already brought to BT.709 is never handed the 2020 matrix as
3175 /// well, on either canvas -- and everything else about the remap is3405 /// well, on either canvas -- and everything else about the remap is
crates/engine/src/playback.rsmodified+10 -0
@@ -914,6 +914,16 @@ impl PlaybackSession {
914 crate::export::planned_audio(&self.project, format)914 crate::export::planned_audio(&self.project, format)
915 }915 }
916 916
917+ /// The timeline an export started right now would be run against, owned:
918+ /// what lets a front-end ask [`crate::export::planned_seats`] what that
919+ /// export would open *off* its render thread, which is the only way to ask
920+ /// a question that opens files. The very snapshot
921+ /// [`export_to_with`](Self::export_to_with) hands the worker, so the answer
922+ /// is about the export that would really start.
923+ pub fn export_snapshot(&self) -> (crate::project::Project, VideoMeta) {
924+ (self.project.export_snapshot(), self.meta)
925+ }
926+
917 /// What an export would do about the tracks at `picks` --927 /// What an export would do about the tracks at `picks` --
918 /// [`crate::export::planned_subtitles`], asked of the project a front-end is928 /// [`crate::export::planned_subtitles`], asked of the project a front-end is
919 /// holding, and pure for the same reason. `picks` is any run of rows of929 /// holding, and pure for the same reason. `picks` is any run of rows of