forge
Explore
Log in

Don't you dare go Hollow

A film in an mkv paints its wave, and a failure says so

Browse files at this commit

ffb310517477a9b3110535fab1badf4bc12d8dcaAhmet Kaan GümüşParent: dea8a27
  • fix
    • a film in an mkv paints its wave, and a failure says so
Show full message
✨ fix(waveform): a film in an mkv paints its wave, and a failure says so

A 5.1 AAC track decodes through rusty_aac, whose IMDCT ran as an 8 MB
cosine matrix -- 88% of decode time and 2x realtime, so a two-hour film
needed an hour of background decode before its lane had anything to
draw. The same file has an N/4-point FFT already, for the encoder: the
IMDCT is a DCT-IV read at an offset, so both directions now share
dsp::dct4. 40x on the fixture, 141 s for the film.

And a decode that fails is no longer a silent file: peaks() errors reach
the lane as Wave::Failed with a band that says "audio unreadable", the
reason goes to the log, and the Matroska opener logs what it swallows.
Cargo.tomlmodified+4 -1
@@ -23,7 +23,10 @@ edition = "2024"
23 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per23 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per
24 # term (the fast path in the same file serves the encoder only),24 # term (the fast path in the same file serves the encoder only),
25 # which is 4x slower than real time for 5.1 and therefore not25 # which is 4x slower than real time for 5.1 and therefore not
26-# playable at all; the patch caches the cosine matrix26+# playable at all; the patch routes the IMDCT through the same
27+# N/4-point FFT the encoder's MDCT already uses (`dsp::dct4`),
28+# 40x the matrix version it started as -- 2 hours of 5.1 for a
29+# waveform in 2.4 minutes rather than an hour
27 # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and30 # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and
28 # refuses any dimension that is not a multiple of the 16-sample31 # refuses any dimension that is not a multiple of the 16-sample
29 # CTB, so 1920x1080 could not be written at all; the patch adds32 # CTB, so 1920x1080 could not be written at all; the patch adds
crates/app/src/main.rsmodified+28 -8
@@ -260,6 +260,10 @@ enum Wave {
260 Loading,260 Loading,
261 /// The file has no audio track. An answer, not a miss.261 /// The file has no audio track. An answer, not a miss.
262 Silent,262 Silent,
263+ /// The decode failed. Drawn as its own mark rather than as [`Self::Silent`]:
264+ /// "this file's sound could not be read" and "this file has no sound" look
265+ /// the same on a lane, and the first is a bug report waiting to happen.
266+ Failed,
263 Peaks(Arc<Vec<(f32, f32)>>),267 Peaks(Arc<Vec<(f32, f32)>>),
264 }268 }
265 269
@@ -2178,9 +2182,8 @@ impl Player {
2178 let (path, stream) = key.clone();2182 let (path, stream) = key.clone();
2179 async move {2183 async move {
2180 engine::waveform::peaks(&path, stream, WAVE_BPS)2184 engine::waveform::peaks(&path, stream, WAVE_BPS)
2181- .ok()2185+ .map(|peaks| peaks.map(|peaks| Arc::new(normalise(peaks))))
2182- .flatten()2186+ .inspect_err(|e| eprintln!("waveform: {}: {e}", path.display()))
2183- .map(|peaks| Arc::new(normalise(peaks)))
2184 }2187 }
2185 });2188 });
2186 cx.spawn(async move |this, cx| {2189 cx.spawn(async move |this, cx| {
@@ -2189,11 +2192,14 @@ impl Player {
2189 this.waves.insert(2192 this.waves.insert(
2190 key,2193 key,
2191 match decoded {2194 match decoded {
2192- Some(peaks) => Wave::Peaks(peaks),2195+ Ok(Some(peaks)) => Wave::Peaks(peaks),
2193- // Either no audio track or a file we could not read2196+ // No audio track: an answer, and not worth asking
2194- // it from; both mean the lane has nothing to draw,2197+ // about again.
2195- // and neither is worth asking about again.2198+ Ok(None) => Wave::Silent,
2196- None => Wave::Silent,2199+ // A file whose sound we could not read is not a
2200+ // silent one, and a lane that drew it as silent is
2201+ // how a broken decode passes for a design choice.
2202+ Err(_) => Wave::Failed,
2197 },2203 },
2198 );2204 );
2199 cx.notify();2205 cx.notify();
@@ -6915,6 +6921,20 @@ impl Player {
6915 .into_any_element(),6921 .into_any_element(),
6916 // No audio track: nothing, never a fake.6922 // No audio track: nothing, never a fake.
6917 Wave::Silent => return None,6923 Wave::Silent => return None,
6924+ // Could not be read: a band that says so in
6925+ // words, because the empty band a silent
6926+ // file draws would claim this file has no
6927+ // sound. The reason itself went to the log.
6928+ Wave::Failed => div()
6929+ .h_full()
6930+ .flex()
6931+ .items_center()
6932+ .justify_center()
6933+ .truncate()
6934+ .text_size(px(9.))
6935+ .text_color(rgb(INK_DIM))
6936+ .child("audio unreadable")
6937+ .into_any_element(),
6918 };6938 };
6919 Some(6939 Some(
6920 div()6940 div()
crates/engine/src/audio.rsmodified+10 -1
@@ -975,9 +975,18 @@ impl Track {
975 if stream > 0 {975 if stream > 0 {
976 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());976 return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into());
977 }977 }
978+ // Logged on the way past: "silent" here covers both a codec nothing
979+ // decodes and a track that genuinely broke, and only the second is a
980+ // bug -- with no trace at all it reaches the user as a lane that
981+ // drew no waveform and nothing else to go on.
978 return Ok(SymTrack::open(path)982 return Ok(SymTrack::open(path)
983+ .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display()))
979 .ok()984 .ok()
980- .filter(|t| t.decoder().is_ok())985+ .filter(|t| {
986+ t.decoder()
987+ .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display()))
988+ .is_ok()
989+ })
981 .map(Self::Sym));990 .map(Self::Sym));
982 }991 }
983 let audio_file = crate::is_audio(path);992 let audio_file = crate::is_audio(path);
crates/engine/src/waveform.rsmodified+39 -4
@@ -15,10 +15,18 @@ use crate::AudioSession;
15 /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always15 /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always
16 /// straddles zero, so silence draws as a flat line.16 /// straddles zero, so silence draws as a flat line.
17 ///17 ///
18-/// Decoding the whole file runs at ~1700x realtime, but it is still linear in18+/// Decoding the whole file runs at ~1700x realtime for an mp4's stereo AAC and
19-/// source length: callers cache the result per source *and stream* — two19+/// ~50x for a film's 5.1 AAC in an mkv (six channels through `rusty_aac`), but
20-/// streams of one file are two different envelopes, and a cache keyed on the20+/// it is linear in source length either way: callers cache the result per source
21-/// path alone would draw the first one under both.21+/// *and stream* — two streams of one file are two different envelopes, and a
22+/// cache keyed on the path alone would draw the first one under both. Memory is
23+/// flat in it, though: chunks are consumed as they arrive and only the buckets
24+/// are kept (2 hours at 10/s is 70k pairs).
25+///
26+/// ponytail: that 50x is 2.4 minutes of background decode for a two-hour film
27+/// before its lane has a waveform. The upgrade path is decoding the source in
28+/// segments on several threads — `open_multi_streams` already takes a window per
29+/// call — and stitching the buckets, which the fold to one envelope makes safe.
22 pub fn peaks(30 pub fn peaks(
23 path: impl AsRef<Path>,31 path: impl AsRef<Path>,
24 stream: usize,32 stream: usize,
@@ -141,6 +149,33 @@ mod tests {
141 assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}");149 assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}");
142 }150 }
143 151
152+ /// The shape the ask came from: a film in an mkv with a 5.1 AAC track,
153+ /// which no symphonia decoder takes (`aac: aac too complex`) and which
154+ /// therefore reaches the lane through `rusty_aac` and the stereo fold. A
155+ /// clip of one draws a waveform like any other -- an envelope that is not
156+ /// flat -- rather than the empty band a silent file makes.
157+ #[test]
158+ fn a_five_one_aac_mkv_draws_an_envelope() {
159+ let peaks = peaks(asset("test_hevc10.mkv"), 0, BPS)
160+ .expect("the 5.1 AAC track decodes")
161+ .expect("test_hevc10.mkv has an audio track");
162+ let want = 2 * BPS as usize; // 2 s of tones
163+ assert!(
164+ peaks.len().abs_diff(want) <= 2,
165+ "{} buckets, want {want} +/-2",
166+ peaks.len()
167+ );
168+ // Six tones, one per channel, folded to stereo: every bucket carries
169+ // signal, and a decode that came out silent (or clipped to a rail) is
170+ // exactly what this refuses.
171+ for (i, &(lo, hi)) in peaks.iter().enumerate() {
172+ assert!(
173+ (0.02..2.0).contains(&(hi - lo)),
174+ "bucket {i} is ({lo}, {hi})"
175+ );
176+ }
177+ }
178+
144 #[test]179 #[test]
145 fn video_only_source_has_no_peaks() {180 fn video_only_source_has_no_peaks() {
146 assert!(181 assert!(
vendor/rusty_aac/src/dsp.rsmodified+87 -49
@@ -35,20 +35,45 @@ pub fn imdct(spec: &[f32]) -> Vec<f32> {
35 if n == 0 {35 if n == 0 {
36 return Vec::new();36 return Vec::new();
37 }37 }
38- // LOCAL PATCH: the AAC block sizes take the cached cosine matrix below --38+ // LOCAL PATCH: O(N log N) instead of the O(N^2) sum below. With `n0 = N/4 +
39- // the same numbers, looked up instead of called for.39+ // 1/2` the kernel is exactly a DCT-IV of length L = N/2 read at `j = i +
40- if let Some(matrix) = imdct_matrix(n) {40+ // L/2` -- the same DCT-IV [`mdct_fast`] already runs as one N/4-point FFT --
41- let mut out = vec![0f32; n];41+ // so the transform is that one call plus a sign-and-mirror walk (DCT-IV is
42- for (i, o) in out.iter_mut().enumerate() {42+ // even about `j = -1/2`, odd about `j = L - 1/2`, and negates every 2L).
43- let row = &matrix[i * half..(i + 1) * half];43+ if half >= 2 && half.is_power_of_two() {
44- let mut acc = 0f32;44+ let owned;
45- for (k, &s) in spec.iter().enumerate() {45+ let tw = match mdct_twiddles(n) {
46- acc += s * row[k];46+ Some(t) => t,
47+ None => {
48+ owned = MdctTwiddles::build(n);
49+ &owned
47 }50 }
48- *o = acc;51+ };
49- }52+ let d = dct4(half, |k| spec[k] as f64, tw);
50- return out;53+ let scale = 2.0 / n as f64;
54+ let (l, l2) = (half, half / 2);
55+ return (0..n)
56+ .map(|i| {
57+ let j = i + l2;
58+ let v = if j < l {
59+ d[j]
60+ } else if j < 2 * l {
61+ -d[2 * l - 1 - j]
62+ } else {
63+ -d[j - 2 * l]
64+ };
65+ (scale * v) as f32
66+ })
67+ .collect();
51 }68 }
69+ imdct_direct(spec)
70+}
71+
72+/// The direct O(N^2) transform [`imdct`] is defined as, kept as the oracle its
73+/// test measures against and as the path for sizes the fast one does not take.
74+fn imdct_direct(spec: &[f32]) -> Vec<f32> {
75+ let half = spec.len();
76+ let n = half * 2;
52 let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/277 let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/2
53 let scale = 2.0 / n as f64;78 let scale = 2.0 / n as f64;
54 let w = 2.0 * PI / n as f64;79 let w = 2.0 * PI / n as f64;
@@ -64,36 +89,6 @@ pub fn imdct(spec: &[f32]) -> Vec<f32> {
64 out89 out
65 }90 }
66 91
67-/// LOCAL PATCH: `(2/N)·cos((2π/N)(i+n0)(k+½))` for every `(i, k)` of one block
68-/// size, built once. The direct transform above spends its whole time in `cos`
69-/// -- ~63 ms for one 1024-coefficient channel, three times slower than real
70-/// time, which is what made a 5.1 stream unplayable. The matrix is 8 MB for the
71-/// long block and 128 kB for the short one, and each output sample becomes a
72-/// dot product a compiler can vectorise.
73-fn imdct_matrix(n: usize) -> Option<&'static [f32]> {
74- static LONG: OnceLock<Vec<f32>> = OnceLock::new();
75- static SHORT: OnceLock<Vec<f32>> = OnceLock::new();
76- fn build(n: usize) -> Vec<f32> {
77- let half = n / 2;
78- let n0 = (n / 2 + 1) as f64 / 2.0;
79- let scale = 2.0 / n as f64;
80- let w = 2.0 * PI / n as f64;
81- let mut m = vec![0f32; n * half];
82- for i in 0..n {
83- let a = w * (i as f64 + n0);
84- for k in 0..half {
85- m[i * half + k] = (scale * (a * (k as f64 + 0.5)).cos()) as f32;
86- }
87- }
88- m
89- }
90- match n {
91- 2048 => Some(LONG.get_or_init(|| build(2048))),
92- 256 => Some(SHORT.get_or_init(|| build(256))),
93- _ => None,
94- }
95-}
96-
97 /// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate92 /// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate
98 /// the IMDCT via perfect reconstruction (and useful for an eventual encoder).93 /// the IMDCT via perfect reconstruction (and useful for an eventual encoder).
99 /// `N` time samples → `N/2` coefficients.94 /// `N` time samples → `N/2` coefficients.
@@ -236,7 +231,7 @@ pub fn mdct_fast(x: &[f32]) -> Vec<f32> {
236 if n < 4 {231 if n < 4 {
237 return mdct(x); // tiny sizes: fall back to the direct oracle232 return mdct(x); // tiny sizes: fall back to the direct oracle
238 }233 }
239- let (l, m) = (n / 2, n / 4);234+ let l = n / 2;
240 let owned;235 let owned;
241 let tw = match mdct_twiddles(n) {236 let tw = match mdct_twiddles(n) {
242 Some(t) => t,237 Some(t) => t,
@@ -254,20 +249,32 @@ pub fn mdct_fast(x: &[f32]) -> Vec<f32> {
254 (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64)249 (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64)
255 }250 }
256 };251 };
257- // Pack + pre-rotate into M complex: v[p] = (y[2p] + i·y[L-1-2p])·e^{-iπ(4p+1)/4L}.252+ // Output scaled ×2: that factor is [`mdct`]'s, not the DCT-IV's.
253+ dct4(l, fold, tw).iter().map(|&v| (2.0 * v) as f32).collect()
254+}
255+
256+/// DCT-IV of length `l`: `out[k] = Σ_j y(j)·cos((π/L)(j+½)(k+½))`, as one
257+/// `L/2`-point complex FFT — pack + pre-rotate `v[p] = (y[2p] + i·y[L-1-2p])
258+/// ·e^{-iπ(4p+1)/4L}`, transform, post-rotate `W = V·e^{-iπp/L}`, and read
259+/// `out[2p] = Re(W)`, `out[L-1-2p] = -Im(W)`.
260+///
261+/// `y` is a closure because the forward MDCT folds its input on the fly and the
262+/// inverse reads a spectrum straight out; `tw` is the block-size table both
263+/// directions share ([`MdctTwiddles`], built for `N = 2L`).
264+fn dct4(l: usize, y: impl Fn(usize) -> f64, tw: &MdctTwiddles) -> Vec<f64> {
265+ let m = l / 2;
258 let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]);266 let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]);
259 for p in 0..m {267 for p in 0..m {
260- let (yr, yi) = (fold(2 * p), fold(l - 1 - 2 * p));268+ let (yr, yi) = (y(2 * p), y(l - 1 - 2 * p));
261 re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p];269 re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p];
262 im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p];270 im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p];
263 }271 }
264 fft(&mut re, &mut im, &tw.fft_c, &tw.fft_s);272 fft(&mut re, &mut im, &tw.fft_c, &tw.fft_s);
265- // Post-rotate W = V·e^{-iπp/L}; X[2p]=Re(W), X[L-1-2p]=-Im(W); output scaled ×2.273+ let mut out = vec![0f64; l];
266- let mut out = vec![0f32; l];
267 for p in 0..m {274 for p in 0..m {
268 let (vr, vi) = (re[p], im[p]);275 let (vr, vi) = (re[p], im[p]);
269- out[2 * p] = (2.0 * (vr * tw.post_c[p] + vi * tw.post_s[p])) as f32;276+ out[2 * p] = vr * tw.post_c[p] + vi * tw.post_s[p];
270- out[l - 1 - 2 * p] = (2.0 * (vr * tw.post_s[p] - vi * tw.post_c[p])) as f32;277+ out[l - 1 - 2 * p] = vr * tw.post_s[p] - vi * tw.post_c[p];
271 }278 }
272 out279 out
273 }280 }
@@ -346,6 +353,37 @@ mod tests {
346 }353 }
347 }354 }
348 355
356+ /// LOCAL PATCH: the fast IMDCT against the direct sum it replaced, at both
357+ /// AAC block sizes plus one the twiddle cache does not hold (512, built on
358+ /// the spot) and one the fast path declines (a 3-coefficient spectrum), on
359+ /// raw and decoder-scale (×32768) input. Every output sample, because the
360+ /// index remap is where a DCT-IV-based inverse goes wrong: a sign or a
361+ /// mirror off by one is silent in the first half and audible in the second.
362+ #[test]
363+ fn imdct_matches_direct() {
364+ for &half in &[3usize, 128, 256, 1024] {
365+ for &scale in &[1.0f32, 32768.0] {
366+ let spec: Vec<f32> = (0..half)
367+ .map(|k| {
368+ scale
369+ * (0.4 * (k as f64 * 0.037).sin() + 0.25 * (k as f64 * 0.011).cos())
370+ as f32
371+ })
372+ .collect();
373+ let (a, b) = (imdct_direct(&spec), imdct(&spec));
374+ let tol = 2e-4 * scale.max(1.0);
375+ for i in 0..half * 2 {
376+ assert!(
377+ (a[i] - b[i]).abs() < tol,
378+ "half={half} scale={scale} i={i}: {} vs {}",
379+ a[i],
380+ b[i]
381+ );
382+ }
383+ }
384+ }
385+ }
386+
349 #[test]387 #[test]
350 fn dequant_matches_spec_curve() {388 fn dequant_matches_spec_curve() {
351 assert_eq!(dequant(0), 0.0);389 assert_eq!(dequant(0), 0.0);