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> {
14981498 pub ts_ns: i64,
14991499 }
15001500
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+
15011530 /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or
15021531 /// `None` for a Matroska file with no sound at all. Header only, and only worth
15031532 /// 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};
8686 /// without a lock, fine enough for any progress bar.
8787 const PROGRESS_SCALE: u32 = 1_000;
8888
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+
89103 /// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
90104 /// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%.
91105 const BITS_PER_PIXEL: f64 = 0.1;
@@ -807,6 +821,48 @@ pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'st
807821 .then(|| video_label(settings.format, hw_seat(meta, settings).is_some()))
808822 }
809823
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+
810866 fn settle(shared: &Shared, result: crate::Result<()>) {
811867 *shared.outcome.lock().unwrap() = Some(result);
812868 // Published last: a caller that sees the flag is guaranteed the outcome.
@@ -848,6 +904,7 @@ fn copy_audio(
848904 meta: &VideoMeta,
849905 kbps: u32,
850906 mkv: bool,
907+ shared: &Shared,
851908 ) -> crate::Result<Option<ExportAudio>> {
852909 // The segments name their source, and the copy carries its packet-rounding
853910 // debt across a source join exactly as across a cut, so a timeline spanning
@@ -872,7 +929,7 @@ fn copy_audio(
872929 // whole comment is about.
873930 let lanes = project.audio_segments_from(0, meta.frame_rate);
874931 let [segments] = &lanes[..] else {
875- return encode_audio(project, meta, kbps, mkv);
932+ return encode_audio(project, meta, kbps, mkv, shared);
876933 };
877934 // ...and the same list names *which* lane those clips sit on, which is the
878935 // only way to ask what has been done to them.
@@ -910,7 +967,7 @@ fn copy_audio(
910967 // such a lane would write it at unity and unlimited, silently.
911968 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
912969 if speeded || equalized(project) || mastered(project) {
913- return encode_audio(project, meta, kbps, mkv);
970+ return encode_audio(project, meta, kbps, mkv, shared);
914971 }
915972 // What is left is a copy the *sources* may still not be able to give: AAC
916973 // inside a Matroska file (readable, but not out of a sample table this walks
@@ -930,7 +987,7 @@ fn copy_audio(
930987 // (they are not in a sample table) and every one of them re-encodes.
931988 opus_pre_skip: None,
932989 })),
933- Err(_) => encode_audio(project, meta, kbps, mkv),
990+ Err(_) => encode_audio(project, meta, kbps, mkv, shared),
934991 }
935992 }
936993
@@ -1150,7 +1207,7 @@ impl CopyPlan {
11501207 done += 1;
11511208 shared
11521209 .progress
1153- .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);
1210+ .store(picture_progress(done, total), Ordering::Relaxed);
11541211 }
11551212 }
11561213 // Everything up to here is still cancellable, exactly as the encoded
@@ -1184,11 +1241,17 @@ fn encode_audio(
11841241 meta: &VideoMeta,
11851242 kbps: u32,
11861243 mkv: bool,
1244+ shared: &Shared,
11871245 ) -> crate::Result<Option<ExportAudio>> {
11881246 let sources = project.audio_sources();
11891247 let segs = project.audio_segments_from(0, meta.frame_rate);
11901248 let eqs = project.audio_eqs_from(0, meta.frame_rate);
11911249 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();
11921255 let Some((audio, chunks)) = AudioSession::open_mixed_streams_master(
11931256 &sources,
11941257 &segs,
@@ -1219,8 +1282,19 @@ fn encode_audio(
12191282 let mut samples: Vec<f32> = Vec::with_capacity(total);
12201283 for chunk in chunks {
12211284 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+ );
12221291 }
12231292 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+ );
12241298
12251299 // Opus where the container carries it and the mix is inside the envelope
12261300 // 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
13671441 // everybody hears in the first frame of a cut. So the first frame is fed in
13681442 // once to warm the encoder, and thrown away again by the pre-skip: exactly
13691443 // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet.
1444+ let coded = std::time::Instant::now();
13701445 let warm = samples.len().min(OPUS_FRAME * 2);
13711446 // ...and one silent frame after the sound, for the same delay seen from the
13721447 // 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
13961471 // sound in a few hundred milliseconds, against a video encode that is
13971472 // minutes). Upgrade path is deleting it, the day this encoder can be
13981473 // trusted at the rate it is asked for.
1474+ let encoded = coded.elapsed().as_secs_f64();
13991475 let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16;
1476+ let measured = std::time::Instant::now();
14001477 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+ );
14011482 Ok((fidelity >= OPUS_MIN_FIDELITY).then_some((packets, pre_skip)))
14021483 }
14031484
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+
14041505 /// The correlation between `samples` and the decode of `packets` with the first
14051506 /// `pre_skip` frames dropped: 1.0 is the same waveform, and this codec's failure
14061507 /// 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
14091510 ///
14101511 /// A packet the decoder refuses is 0.0 and no argument: a track this project
14111512 /// 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.
14121527 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> {
14131564 let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);
14141565 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
1415- let mut drop = pre_skip * 2;
1416- let mut at = 0;
1417- for packet in packets {
1566+ // Where in the mix this window's first decoded sample lands: every packet
1567+ // is [`OPUS_FRAME`] long, and the pre-skip is what the front of the stream
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) {
14181573 let Ok(pcm) = decoder.decode_packet(&packet.bytes) else {
1419- return 0.0;
1574+ return Some(0.0);
14201575 };
14211576 let pcm = &pcm[drop.min(pcm.len())..];
14221577 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+ }
14231583 for (want, got) in samples[at.min(samples.len())..].iter().zip(pcm) {
14241584 let (x, y) = (f64::from(*want), f64::from(*got));
14251585 num += x * y;
14261586 da += x * x;
14271587 db += y * y;
14281588 at += 1;
1589+ counted += 1;
14291590 }
14301591 }
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))
14321593 }
14331594
14341595 fn run(
@@ -1440,16 +1601,29 @@ fn run(
14401601 ) -> crate::Result<()> {
14411602 let total = project.timeline_frames();
14421603 let sources = project.sources();
1443- // Audio first: a track has to be declared when the muxer is created, which
1444- // happens as soon as the first coded picture arrives -- and the Matroska
1445- // muxer wants the packets themselves that early too, because it interleaves
1446- // them into the clusters as it writes. Every video format gets the same
1447- // track: none of them is picture-only any more.
1604+ // The picture's decision first, before a sample of sound is touched: it is
1605+ // the answer that decides what the whole export *is*, it costs one header
1606+ // read per source, and it is what the line on screen has been missing --
1607+ // an export that copies its picture used to say nothing at all for as long
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.
14481621 let audio = copy_audio(
14491622 project,
14501623 meta,
14511624 audio_kbps_of(settings),
14521625 settings.format.is_mkv(),
1626+ shared,
14531627 )?;
14541628 let audio_params = audio.as_ref().map(|track| AudioParams {
14551629 freq_index: track.params.freq_index,
@@ -1473,6 +1647,9 @@ fn run(
14731647 // declared in the header and its blocks are interleaved into the clusters,
14741648 // so the muxer needs the lot before the first picture is written.
14751649 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);
14761653
14771654 // Before an encoder is opened at all: a timeline nobody has touched, whose
14781655 // sources this file can hold as they are, is written by copying their coded
@@ -1480,8 +1657,7 @@ fn run(
14801657 // and the difference between an export bounded by the *edited* spans and one
14811658 // that re-encodes a whole film to change a cut. [`CopyPlan`] states the
14821659 // whole rule; anything at all outside it falls through to the walk below.
1483- if let Some(plan) = CopyPlan::of(project, meta, settings) {
1484- eprintln!("export video: copy (source packets)");
1660+ if let Some(plan) = plan {
14851661 *shared.encoders.lock().unwrap() = Some(format!(
14861662 "copy · {}",
14871663 // The measured codec, exactly as the encoder path below publishes
@@ -1719,7 +1895,7 @@ fn run(
17191895 done += 1;
17201896 shared
17211897 .progress
1722- .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);
1898+ .store(picture_progress(done, total), Ordering::Relaxed);
17231899 }
17241900 done_here += repeats;
17251901 }
@@ -3170,6 +3346,60 @@ mod tests {
31703346 );
31713347 }
31723348
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+
31733403 /// The one rule that keeps a picture from being converted twice: a frame the
31743404 /// tone map has already brought to BT.709 is never handed the 2020 matrix as
31753405 /// well, on either canvas -- and everything else about the remap is
crates/engine/src/playback.rsmodified+10 -0
@@ -914,6 +914,16 @@ impl PlaybackSession {
914914 crate::export::planned_audio(&self.project, format)
915915 }
916916
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+
917927 /// What an export would do about the tracks at `picks` --
918928 /// [`crate::export::planned_subtitles`], asked of the project a front-end is
919929 /// holding, and pure for the same reason. `picks` is any run of rows of