diff --git a/Cargo.toml b/Cargo.toml index 2fb73a0..93e276b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,7 +23,10 @@ edition = "2024" # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per # term (the fast path in the same file serves the encoder only), # which is 4x slower than real time for 5.1 and therefore not -# playable at all; the patch caches the cosine matrix +# playable at all; the patch routes the IMDCT through the same +# N/4-point FFT the encoder's MDCT already uses (`dsp::dct4`), +# 40x the matrix version it started as -- 2 hours of 5.1 for a +# waveform in 2.4 minutes rather than an hour # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and # refuses any dimension that is not a multiple of the 16-sample # CTB, so 1920x1080 could not be written at all; the patch adds diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 20be25f..a8d971b 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -260,6 +260,10 @@ enum Wave { Loading, /// The file has no audio track. An answer, not a miss. Silent, + /// The decode failed. Drawn as its own mark rather than as [`Self::Silent`]: + /// "this file's sound could not be read" and "this file has no sound" look + /// the same on a lane, and the first is a bug report waiting to happen. + Failed, Peaks(Arc>), } @@ -2178,9 +2182,8 @@ impl Player { let (path, stream) = key.clone(); async move { engine::waveform::peaks(&path, stream, WAVE_BPS) - .ok() - .flatten() - .map(|peaks| Arc::new(normalise(peaks))) + .map(|peaks| peaks.map(|peaks| Arc::new(normalise(peaks)))) + .inspect_err(|e| eprintln!("waveform: {}: {e}", path.display())) } }); cx.spawn(async move |this, cx| { @@ -2189,11 +2192,14 @@ impl Player { this.waves.insert( key, match decoded { - Some(peaks) => Wave::Peaks(peaks), - // Either no audio track or a file we could not read - // it from; both mean the lane has nothing to draw, - // and neither is worth asking about again. - None => Wave::Silent, + Ok(Some(peaks)) => Wave::Peaks(peaks), + // No audio track: an answer, and not worth asking + // about again. + Ok(None) => Wave::Silent, + // A file whose sound we could not read is not a + // silent one, and a lane that drew it as silent is + // how a broken decode passes for a design choice. + Err(_) => Wave::Failed, }, ); cx.notify(); @@ -6915,6 +6921,20 @@ impl Player { .into_any_element(), // No audio track: nothing, never a fake. Wave::Silent => return None, + // Could not be read: a band that says so in + // words, because the empty band a silent + // file draws would claim this file has no + // sound. The reason itself went to the log. + Wave::Failed => div() + .h_full() + .flex() + .items_center() + .justify_center() + .truncate() + .text_size(px(9.)) + .text_color(rgb(INK_DIM)) + .child("audio unreadable") + .into_any_element(), }; Some( div() diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index b958807..d53be99 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -975,9 +975,18 @@ impl Track { if stream > 0 { return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); } + // Logged on the way past: "silent" here covers both a codec nothing + // decodes and a track that genuinely broke, and only the second is a + // bug -- with no trace at all it reaches the user as a lane that + // drew no waveform and nothing else to go on. return Ok(SymTrack::open(path) + .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display())) .ok() - .filter(|t| t.decoder().is_ok()) + .filter(|t| { + t.decoder() + .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display())) + .is_ok() + }) .map(Self::Sym)); } let audio_file = crate::is_audio(path); diff --git a/crates/engine/src/waveform.rs b/crates/engine/src/waveform.rs index 5c23923..14e06aa 100644 --- a/crates/engine/src/waveform.rs +++ b/crates/engine/src/waveform.rs @@ -15,10 +15,18 @@ use crate::AudioSession; /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always /// straddles zero, so silence draws as a flat line. /// -/// Decoding the whole file runs at ~1700x realtime, but it is still linear in -/// source length: callers cache the result per source *and stream* — two -/// streams of one file are two different envelopes, and a cache keyed on the -/// path alone would draw the first one under both. +/// Decoding the whole file runs at ~1700x realtime for an mp4's stereo AAC and +/// ~50x for a film's 5.1 AAC in an mkv (six channels through `rusty_aac`), but +/// it is linear in source length either way: callers cache the result per source +/// *and stream* — two streams of one file are two different envelopes, and a +/// cache keyed on the path alone would draw the first one under both. Memory is +/// flat in it, though: chunks are consumed as they arrive and only the buckets +/// are kept (2 hours at 10/s is 70k pairs). +/// +/// ponytail: that 50x is 2.4 minutes of background decode for a two-hour film +/// before its lane has a waveform. The upgrade path is decoding the source in +/// segments on several threads — `open_multi_streams` already takes a window per +/// call — and stitching the buckets, which the fold to one envelope makes safe. pub fn peaks( path: impl AsRef, stream: usize, @@ -141,6 +149,33 @@ mod tests { assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}"); } + /// The shape the ask came from: a film in an mkv with a 5.1 AAC track, + /// which no symphonia decoder takes (`aac: aac too complex`) and which + /// therefore reaches the lane through `rusty_aac` and the stereo fold. A + /// clip of one draws a waveform like any other -- an envelope that is not + /// flat -- rather than the empty band a silent file makes. + #[test] + fn a_five_one_aac_mkv_draws_an_envelope() { + let peaks = peaks(asset("test_hevc10.mkv"), 0, BPS) + .expect("the 5.1 AAC track decodes") + .expect("test_hevc10.mkv has an audio track"); + let want = 2 * BPS as usize; // 2 s of tones + assert!( + peaks.len().abs_diff(want) <= 2, + "{} buckets, want {want} +/-2", + peaks.len() + ); + // Six tones, one per channel, folded to stereo: every bucket carries + // signal, and a decode that came out silent (or clipped to a rail) is + // exactly what this refuses. + for (i, &(lo, hi)) in peaks.iter().enumerate() { + assert!( + (0.02..2.0).contains(&(hi - lo)), + "bucket {i} is ({lo}, {hi})" + ); + } + } + #[test] fn video_only_source_has_no_peaks() { assert!( diff --git a/vendor/rusty_aac/src/dsp.rs b/vendor/rusty_aac/src/dsp.rs index b35cd4d..b22a28a 100644 --- a/vendor/rusty_aac/src/dsp.rs +++ b/vendor/rusty_aac/src/dsp.rs @@ -35,20 +35,45 @@ pub fn imdct(spec: &[f32]) -> Vec { if n == 0 { return Vec::new(); } - // LOCAL PATCH: the AAC block sizes take the cached cosine matrix below -- - // the same numbers, looked up instead of called for. - if let Some(matrix) = imdct_matrix(n) { - let mut out = vec![0f32; n]; - for (i, o) in out.iter_mut().enumerate() { - let row = &matrix[i * half..(i + 1) * half]; - let mut acc = 0f32; - for (k, &s) in spec.iter().enumerate() { - acc += s * row[k]; + // LOCAL PATCH: O(N log N) instead of the O(N^2) sum below. With `n0 = N/4 + + // 1/2` the kernel is exactly a DCT-IV of length L = N/2 read at `j = i + + // L/2` -- the same DCT-IV [`mdct_fast`] already runs as one N/4-point FFT -- + // so the transform is that one call plus a sign-and-mirror walk (DCT-IV is + // even about `j = -1/2`, odd about `j = L - 1/2`, and negates every 2L). + if half >= 2 && half.is_power_of_two() { + let owned; + let tw = match mdct_twiddles(n) { + Some(t) => t, + None => { + owned = MdctTwiddles::build(n); + &owned } - *o = acc; - } - return out; + }; + let d = dct4(half, |k| spec[k] as f64, tw); + let scale = 2.0 / n as f64; + let (l, l2) = (half, half / 2); + return (0..n) + .map(|i| { + let j = i + l2; + let v = if j < l { + d[j] + } else if j < 2 * l { + -d[2 * l - 1 - j] + } else { + -d[j - 2 * l] + }; + (scale * v) as f32 + }) + .collect(); } + imdct_direct(spec) +} + +/// The direct O(N^2) transform [`imdct`] is defined as, kept as the oracle its +/// test measures against and as the path for sizes the fast one does not take. +fn imdct_direct(spec: &[f32]) -> Vec { + let half = spec.len(); + let n = half * 2; let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/2 let scale = 2.0 / n as f64; let w = 2.0 * PI / n as f64; @@ -64,36 +89,6 @@ pub fn imdct(spec: &[f32]) -> Vec { out } -/// LOCAL PATCH: `(2/N)·cos((2π/N)(i+n0)(k+½))` for every `(i, k)` of one block -/// size, built once. The direct transform above spends its whole time in `cos` -/// -- ~63 ms for one 1024-coefficient channel, three times slower than real -/// time, which is what made a 5.1 stream unplayable. The matrix is 8 MB for the -/// long block and 128 kB for the short one, and each output sample becomes a -/// dot product a compiler can vectorise. -fn imdct_matrix(n: usize) -> Option<&'static [f32]> { - static LONG: OnceLock> = OnceLock::new(); - static SHORT: OnceLock> = OnceLock::new(); - fn build(n: usize) -> Vec { - let half = n / 2; - let n0 = (n / 2 + 1) as f64 / 2.0; - let scale = 2.0 / n as f64; - let w = 2.0 * PI / n as f64; - let mut m = vec![0f32; n * half]; - for i in 0..n { - let a = w * (i as f64 + n0); - for k in 0..half { - m[i * half + k] = (scale * (a * (k as f64 + 0.5)).cos()) as f32; - } - } - m - } - match n { - 2048 => Some(LONG.get_or_init(|| build(2048))), - 256 => Some(SHORT.get_or_init(|| build(256))), - _ => None, - } -} - /// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate /// the IMDCT via perfect reconstruction (and useful for an eventual encoder). /// `N` time samples → `N/2` coefficients. @@ -236,7 +231,7 @@ pub fn mdct_fast(x: &[f32]) -> Vec { if n < 4 { return mdct(x); // tiny sizes: fall back to the direct oracle } - let (l, m) = (n / 2, n / 4); + let l = n / 2; let owned; let tw = match mdct_twiddles(n) { Some(t) => t, @@ -254,20 +249,32 @@ pub fn mdct_fast(x: &[f32]) -> Vec { (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64) } }; - // Pack + pre-rotate into M complex: v[p] = (y[2p] + i·y[L-1-2p])·e^{-iπ(4p+1)/4L}. + // Output scaled ×2: that factor is [`mdct`]'s, not the DCT-IV's. + dct4(l, fold, tw).iter().map(|&v| (2.0 * v) as f32).collect() +} + +/// DCT-IV of length `l`: `out[k] = Σ_j y(j)·cos((π/L)(j+½)(k+½))`, as one +/// `L/2`-point complex FFT — pack + pre-rotate `v[p] = (y[2p] + i·y[L-1-2p]) +/// ·e^{-iπ(4p+1)/4L}`, transform, post-rotate `W = V·e^{-iπp/L}`, and read +/// `out[2p] = Re(W)`, `out[L-1-2p] = -Im(W)`. +/// +/// `y` is a closure because the forward MDCT folds its input on the fly and the +/// inverse reads a spectrum straight out; `tw` is the block-size table both +/// directions share ([`MdctTwiddles`], built for `N = 2L`). +fn dct4(l: usize, y: impl Fn(usize) -> f64, tw: &MdctTwiddles) -> Vec { + let m = l / 2; let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]); for p in 0..m { - let (yr, yi) = (fold(2 * p), fold(l - 1 - 2 * p)); + let (yr, yi) = (y(2 * p), y(l - 1 - 2 * p)); re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p]; im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p]; } fft(&mut re, &mut im, &tw.fft_c, &tw.fft_s); - // Post-rotate W = V·e^{-iπp/L}; X[2p]=Re(W), X[L-1-2p]=-Im(W); output scaled ×2. - let mut out = vec![0f32; l]; + let mut out = vec![0f64; l]; for p in 0..m { let (vr, vi) = (re[p], im[p]); - out[2 * p] = (2.0 * (vr * tw.post_c[p] + vi * tw.post_s[p])) as f32; - out[l - 1 - 2 * p] = (2.0 * (vr * tw.post_s[p] - vi * tw.post_c[p])) as f32; + out[2 * p] = vr * tw.post_c[p] + vi * tw.post_s[p]; + out[l - 1 - 2 * p] = vr * tw.post_s[p] - vi * tw.post_c[p]; } out } @@ -346,6 +353,37 @@ mod tests { } } + /// LOCAL PATCH: the fast IMDCT against the direct sum it replaced, at both + /// AAC block sizes plus one the twiddle cache does not hold (512, built on + /// the spot) and one the fast path declines (a 3-coefficient spectrum), on + /// raw and decoder-scale (×32768) input. Every output sample, because the + /// index remap is where a DCT-IV-based inverse goes wrong: a sign or a + /// mirror off by one is silent in the first half and audible in the second. + #[test] + fn imdct_matches_direct() { + for &half in &[3usize, 128, 256, 1024] { + for &scale in &[1.0f32, 32768.0] { + let spec: Vec = (0..half) + .map(|k| { + scale + * (0.4 * (k as f64 * 0.037).sin() + 0.25 * (k as f64 * 0.011).cos()) + as f32 + }) + .collect(); + let (a, b) = (imdct_direct(&spec), imdct(&spec)); + let tol = 2e-4 * scale.max(1.0); + for i in 0..half * 2 { + assert!( + (a[i] - b[i]).abs() < tol, + "half={half} scale={scale} i={i}: {} vs {}", + a[i], + b[i] + ); + } + } + } + } + #[test] fn dequant_matches_spec_curve() { assert_eq!(dequant(0), 0.0);