forge
Explore
Log in

Don't you dare go Hollow

The sound gate judges the middle of what it hears, and says which codec it wrote

Browse files at this commit

6b7076f9e74c8dee73e105f79282f4f90eebab15Ahmet Kaan GümüşParent: bea7164
  • fix
    • the sound gate judges the middle of what it hears, and says which codec it wrote
Show full message
🐛 fix(export): the sound gate judges the middle of what it hears, and says which codec it wrote

Two defects the sampled gate's own first run on a real film exposed.

**The statistic was wrong.** A worst-of-windows rule at 0.95 refused a film this
encoder handles perfectly well: forty five-second windows of one mix, encoded at
128 kbps and decoded back, read

    0.803  0.835  0.938  0.940  0.960  0.987  ... median 0.998 ... 0.999

so five of the thirty-nine that carry sound sit under the threshold on a *good*
track -- the same thing OPUS_MAX_KBPS's own table shows, where a span scoring
0.937 at 128 kbps is inside the usable band. What the gate exists to catch is
the opposite shape: a rate the encoder cannot hold ruins the track wherever that
rate is used (0.452/0.697/0.951 at 136 kbps, 0.06 at 256). Half a track cannot
go without the middle of the list moving, so the median separates the two by a
margin no single window can, and a track under a minute is still one window --
median and whole-track correlation are the same number there.

Measured, this film: worst-window 0.8467 (refused, sound written as AAC),
median 0.9982 (taken, written as Opus).

**And the fallback was invisible.** The line the export publishes named "Opus ·
SW encode (opus-rs)" for *every* Matroska encode, because the label it borrowed
predicts from the format and cannot know what the gate decided -- so a track the
gate had just sent to AAC was announced as Opus, on the one path where the
difference is audible. `measured_audio_label` fills in the half a prediction
cannot know.

    cargo test -p engine --release --test video_copy -- --include-ignored
      7 passed in 133.2 s; the film exported in 98.5 s, 27944 MB, Opus
crates/engine/src/export.rsmodified+85 -29
@@ -578,6 +578,31 @@ fn audio_label(
578 }578 }
579 }579 }
580 580
581+/// What the export *did* to the sound, for the line it publishes while it runs:
582+/// [`audio_label`]'s words with the one thing no prediction can know filled in
583+/// -- whether the Opus seat took the track or handed it back
584+/// ([`encode_opus`]'s gate).
585+///
586+/// `sound` is `Some(copied)` for a track and `None` for a file with no sound.
587+/// Naming Opus for *every* Matroska encode is what made that fallback
588+/// invisible: a track the gate refused was written as AAC and the line still
589+/// said Opus, on the one path where the difference is audible.
590+fn measured_audio_label(
591+ project: &Project,
592+ format: Format,
593+ sound: Option<bool>,
594+ opus: bool,
595+) -> &'static str {
596+ match (sound, opus) {
597+ (_, true) => "Opus · SW encode (opus-rs)",
598+ // Encoded, into a container that would have carried Opus, and it is not
599+ // Opus: the fidelity gate sent it to AAC ([`OPUS_MIN_FIDELITY`]), or the
600+ // mix was not the 48 kHz stereo that seat is measured in.
601+ (Some(false), false) if format.is_mkv() => "AAC · SW encode (rusty_aac)",
602+ _ => audio_label(project, format, sound.is_some(), sound),
603+ }
604+}
605+
581 /// What [`start`] would write this timeline's sound with, before one is606 /// What [`start`] would write this timeline's sound with, before one is
582 /// started. Pure: no probe and no file opened, so a card may ask it per repaint.607 /// started. Pure: no probe and no file opened, so a card may ask it per repaint.
583 pub fn planned_audio(project: &Project, format: Format) -> &'static str {608 pub fn planned_audio(project: &Project, format: Format) -> &'static str {
@@ -1511,7 +1536,7 @@ const FIDELITY_FLOOR: f64 = 1e-9;
1511 /// A packet the decoder refuses is 0.0 and no argument: a track this project1536 /// A packet the decoder refuses is 0.0 and no argument: a track this project
1512 /// cannot read is exactly what this is here to catch.1537 /// cannot read is exactly what this is here to catch.
1513 ///1538 ///
1514-/// **Sampled, above a minute of sound, and the worst window is the answer.**1539+/// **Sampled above a minute of sound, and the median window is the answer.**
1515 /// This decode is the whole cost of exporting a feature film: `ruopus` runs its1540 /// 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),1541 /// 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 hour1542 /// so judging every packet of a two-and-a-half-hour film costs half an hour
@@ -1520,10 +1545,27 @@ const FIDELITY_FLOOR: f64 = 1e-9;
1520 /// [`FIDELITY_WINDOWS`] windows spread evenly across the track cost the same1545 /// [`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 for1546 /// 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 falls1547 /// 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 is1548+/// off everywhere that rate is used, not a defect of one bar of music.
1524-/// also strictly harsher per window than the old whole-track sum, which let a1549+///
1525-/// ruined minute average away against two good hours -- the answer here is the1550+/// The **median** and not the worst, and that is measured rather than cautious.
1526-/// worst window, not the mean.1551+/// Forty five-second windows of a real 5.1 film's mix, encoded here at 128 kbps
1552+/// and decoded back, in order:
1553+///
1554+/// ```text
1555+/// 0.803 0.835 0.938 0.940 0.960 0.987 0.994 ... median 0.998 ... 0.999
1556+/// ```
1557+///
1558+/// Five of the thirty-nine that carried sound sit under [`OPUS_MIN_FIDELITY`] on
1559+/// a track that is *good* -- which is the same thing the table in
1560+/// [`OPUS_MAX_KBPS`] shows, where a span scoring 0.937 at 128 kbps is inside the
1561+/// usable band. A worst-window rule at 0.95 therefore refuses films this encoder
1562+/// handles perfectly well, while the failure it exists for is the opposite
1563+/// shape: at 136 kbps the same three measured spans read 0.452, 0.697, 0.951,
1564+/// and at 256 kbps the whole track correlates 0.06. Half a track cannot be
1565+/// ruined without the middle of the list moving, so the median separates the two
1566+/// by a margin no single window can (0.998 against under 0.7) -- and a track
1567+/// under a minute is one window, where median and whole-track correlation are
1568+/// the same number the gate always used.
1527 fn opus_fidelity(packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize) -> f64 {1569 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 any1570 // Short enough to hear all of: every fixture, every unit test, and any
1529 // track under a minute. There is nothing to sample from.1571 // track under a minute. There is nothing to sample from.
@@ -1535,7 +1577,7 @@ fn opus_fidelity(packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize)
1535 // own warm-up would show, and the last starts a window short of the end so1577 // own warm-up would show, and the last starts a window short of the end so
1536 // no window runs past the packets.1578 // no window runs past the packets.
1537 let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);1579 let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);
1538- let mut worst: Option<f64> = None;1580+ let mut scores: Vec<f64> = Vec::with_capacity(FIDELITY_WINDOWS);
1539 for w in 0..FIDELITY_WINDOWS {1581 for w in 0..FIDELITY_WINDOWS {
1540 let at = w * step;1582 let at = w * step;
1541 let from = at.saturating_sub(FIDELITY_WARMUP);1583 let from = at.saturating_sub(FIDELITY_WARMUP);
@@ -1544,10 +1586,14 @@ fn opus_fidelity(packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize)
1544 else {1586 else {
1545 continue; // silence: nothing to correlate, and not a failure1587 continue; // silence: nothing to correlate, and not a failure
1546 };1588 };
1547- worst = Some(worst.map_or(fidelity, |w: f64| w.min(fidelity)));1589+ scores.push(fidelity);
1548 }1590 }
1549 // Every window silent is a silent track, which this codec writes as silence.1591 // Every window silent is a silent track, which this codec writes as silence.
1550- worst.unwrap_or(1.0)1592+ if scores.is_empty() {
1593+ return 1.0;
1594+ }
1595+ scores.sort_by(f64::total_cmp);
1596+ scores[scores.len() / 2]
1551 }1597 }
1552 1598
1553 /// [`opus_fidelity`] over `packets[measure..to]`, with `packets[from..measure]`1599 /// [`opus_fidelity`] over `packets[measure..to]`, with `packets[from..measure]`
@@ -1664,10 +1710,7 @@ fn run(
1664 // it: the mix has been opened by now, so a line that fell back to1710 // it: the mix has been opened by now, so a line that fell back to
1665 // AAC says AAC. Naming the prediction here would make the fallback1711 // AAC says AAC. Naming the prediction here would make the fallback
1666 // invisible on precisely the exports that are over in seconds.1712 // invisible on precisely the exports that are over in seconds.
1667- match opus {1713+ measured_audio_label(project, settings.format, sound, opus)
1668- true => "Opus · SW encode (opus-rs)",
1669- false => audio_label(project, settings.format, sound.is_some(), sound),
1670- }
1671 ));1714 ));
1672 return plan.run(1715 return plan.run(
1673 out,1716 out,
@@ -1723,10 +1766,7 @@ fn run(
1723 *shared.encoders.lock().unwrap() = Some(format!(1766 *shared.encoders.lock().unwrap() = Some(format!(
1724 "{} · {}",1767 "{} · {}",
1725 encoder.label(),1768 encoder.label(),
1726- match opus {1769+ measured_audio_label(project, settings.format, sound, opus)
1727- true => "Opus · SW encode (opus-rs)",
1728- false => audio_label(project, settings.format, sound.is_some(), sound),
1729- }
1730 ));1770 ));
1731 let mut muxer = None;1771 let mut muxer = None;
1732 let mut done = 0u32;1772 let mut done = 0u32;
@@ -3346,18 +3386,19 @@ mod tests {
3346 );3386 );
3347 }3387 }
3348 3388
3349- /// The gate on a track too long to listen to whole: it samples, and what it3389+ /// The gate on a track too long to listen to whole: it samples, and the
3350- /// samples it judges one window at a time. A five-second stretch that is not3390+ /// middle of what it hears is the answer. A track whose sound is *not* what
3351- /// the mix fails the whole track -- where the old whole-track sum would have3391+ /// was encoded fails it; one bad five-second window does not, which is
3352- /// let it average away against the minutes either side -- and a silent track3392+ /// deliberate and measured ([`opus_fidelity`] carries the distribution:
3353- /// is not a failure at all, which is what it used to be scored as (0.03393+ /// five windows of a good film's mix score under 0.95, the lowest 0.803).
3354- /// against a denominator of nothing, and an all-quiet timeline fell back to3394+ /// A silent track is not a failure either, which is what it used to be
3355- /// AAC for it).3395+ /// scored as -- 0.0 against a denominator of nothing, and an all-quiet
3396+ /// timeline fell back to AAC for it.
3356 ///3397 ///
3357 /// 61 s of sound: one second past the minute the gate stops listening whole,3398 /// 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.3399 /// which is what puts this on the sampled path at all.
3359 #[test]3400 #[test]
3360- fn a_long_track_is_judged_by_its_worst_sampled_window() {3401+ fn a_long_track_is_judged_by_the_middle_of_what_it_samples() {
3361 let pcm = two_tones(61);3402 let pcm = two_tones(61);
3362 let (packets, pre_skip) = encode_opus(&pcm, 96)3403 let (packets, pre_skip) = encode_opus(&pcm, 96)
3363 .expect("the encoder opens")3404 .expect("the encoder opens")
@@ -3374,17 +3415,32 @@ mod tests {
3374 // One window's worth of the *mix* replaced by its own phase inverse:3415 // 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. Placed3416 // 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 same3417 // on a window the gate samples -- window 6 of the twelve, by the same
3377- // arithmetic the gate spreads them with.3418+ // arithmetic the gate spreads them with. The track still passes, and
3419+ // that is the measured decision, not an oversight: this codec really
3420+ // does score 0.80 on five seconds of film it otherwise handles at 0.998.
3378 let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);3421 let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);
3379 let from = (6 * step * OPUS_FRAME).saturating_sub(pre_skip) * 2;3422 let from = (6 * step * OPUS_FRAME).saturating_sub(pre_skip) * 2;
3423+ let mut one_bad = pcm.clone();
3424+ for sample in &mut one_bad[from..(from + FIDELITY_WINDOW * OPUS_FRAME * 2).min(pcm.len())] {
3425+ *sample = -*sample;
3426+ }
3427+ let dip = opus_fidelity(&packets, &one_bad, pre_skip);
3428+ assert!(
3429+ dip >= OPUS_MIN_FIDELITY,
3430+ "one ruined window sank the whole track ({dip:.4})"
3431+ );
3432+
3433+ // ...and the shape the gate is actually for, which is what a rate the
3434+ // encoder cannot hold does: the track is not the mix any more, not one
3435+ // window of it. The middle of the list moves with it.
3380 let mut ruined = pcm.clone();3436 let mut ruined = pcm.clone();
3381- for sample in &mut ruined[from..(from + FIDELITY_WINDOW * OPUS_FRAME * 2).min(pcm.len())] {3437+ for sample in &mut ruined[pcm.len() / 4..] {
3382 *sample = -*sample;3438 *sample = -*sample;
3383 }3439 }
3384- let worst = opus_fidelity(&packets, &ruined, pre_skip);3440+ let ruined = opus_fidelity(&packets, &ruined, pre_skip);
3385 assert!(3441 assert!(
3386- worst < OPUS_MIN_FIDELITY,3442+ ruined < OPUS_MIN_FIDELITY,
3387- "five seconds of a long track that is not the mix scored {worst:.4}"3443+ "a track that is no longer the mix scored {ruined:.4}"
3388 );3444 );
3389 3445
3390 // ...and silence is silence: nothing to correlate is not a round trip3446 // ...and silence is silence: nothing to correlate is not a round trip