diff --git a/crates/ec-aac/src/decode.rs b/crates/ec-aac/src/decode.rs index 3400c658..7079dac6 100644 --- a/crates/ec-aac/src/decode.rs +++ b/crates/ec-aac/src/decode.rs @@ -771,6 +771,7 @@ impl BlockDecoder { // extension_payload(): bs_extension_type(4), then // (for SBR) an optional 10-bit CRC, then // sbr_extension_data() itself. + let mut applied = false; if r.bits_remaining() >= 4 { let ext_type = r.peek_bits(4)?; if ext_type == 13 || ext_type == 14 { @@ -780,9 +781,18 @@ impl BlockDecoder { } if let Some(data) = sbr.parse(r, tag, is_cpe) { sbr.apply(tag, &data, &mut out[start..start + n]); + applied = true; } } } + if !applied { + // No fresh SBR payload this frame (no SBR fill + // element, or one whose extension_type wasn't + // SBR, or a parse failure): §4.6.18 still + // requires doubled-rate reconstruction, using + // the last successfully parsed frame's data. + sbr.apply_last(tag, &mut out[start..start + n]); + } } // Resync to the FIL's declared byte boundary regardless // of how many bits SBR parsing above actually consumed: @@ -794,7 +804,17 @@ impl BlockDecoder { } pending = None; } - _ => break, + _ => { + // The block ended with no FIL element ever following the + // last SCE/CPE (no SBR fill at all this frame, not even + // a non-SBR one) -- same "unavailable frame" case as the + // no-fresh-payload branch in id 6 above, so fall back to + // the last known SBR data the same way. + if let (Some(sbr), Some((tag, start, n, _))) = (self.sbr.as_mut(), pending) { + sbr.apply_last(tag, &mut out[start..start + n]); + } + break; + } } } r.align_to_byte(); diff --git a/crates/ec-aac/src/sbr_chain.rs b/crates/ec-aac/src/sbr_chain.rs index 6c8ac5cf..ae4800fc 100644 --- a/crates/ec-aac/src/sbr_chain.rs +++ b/crates/ec-aac/src/sbr_chain.rs @@ -84,6 +84,15 @@ impl ChannelState { struct Element { parser: SbrParser, channels: Vec, + /// The most recently parsed frame's envelope/noise/grid data, held so an + /// access unit whose FIL element carries no fresh SBR payload this frame + /// (an "unavailable" frame, §4.6.18: legal per spec and the decoder must + /// keep reconstructing at the doubled rate using the last known data, + /// not silently fall back to core-only output) can still be + /// SBR-reconstructed instead of leaving that one access unit's plane at + /// half length -- which otherwise permanently shifts every sample after + /// it out of alignment with a reference that stayed at full rate. + last_data: Option, } /// Every configured SBR element in a stream, keyed by @@ -108,6 +117,7 @@ impl SbrChain { let elem = self.elements.entry(tag).or_insert_with(|| Element { parser: SbrParser::new(self.rate), channels: Vec::new(), + last_data: None, }); let data = elem.parser.parse(r, is_cpe).ok()?; let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); @@ -123,6 +133,25 @@ impl SbrChain { /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a /// silent no-op: `planes` is left at its core content. pub fn apply(&mut self, tag: u8, data: &SbrData, planes: &mut [Vec]) { + if let Some(elem) = self.elements.get_mut(&tag) { + elem.last_data = Some(data.clone()); + } + self.apply_data(tag, data, planes); + } + + /// Re-runs the chain for `tag` using the last successfully parsed + /// frame's SBR data, for an access unit whose own FIL element carried no + /// fresh payload this frame. A no-op (planes left at core content, same + /// as [`apply`]'s existing malformed/missing-state fallback) if no prior + /// frame ever parsed successfully for this element. + pub fn apply_last(&mut self, tag: u8, planes: &mut [Vec]) { + let Some(data) = self.elements.get(&tag).and_then(|e| e.last_data.clone()) else { + return; + }; + self.apply_data(tag, &data, planes); + } + + fn apply_data(&mut self, tag: u8, data: &SbrData, planes: &mut [Vec]) { let Some(elem) = self.elements.get_mut(&tag) else { return; }; @@ -220,3 +249,134 @@ impl SbrChain { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::sbr_bands::freq_tables; + use crate::sbr_payload::{SbrHeader, SbrParser}; + + fn tables() -> crate::sbr_bands::BandTables { + freq_tables(44100, 5, 3, 2, 1, 2, 2).unwrap() + } + + fn header() -> SbrHeader { + SbrHeader { + amp_res: 1, + start_freq: 5, + stop_freq: 3, + xover_band: 2, + freq_scale: 2, + alter_scale: 1, + noise_bands: 2, + limiter_bands: 2, + limiter_gains: 3, + interpol_freq: 1, + smoothing_mode: 1, + } + } + + fn one_channel(n_q: usize, n_low: usize) -> SbrChannel { + SbrChannel { + t_env: vec![0, 16], + freq_res: vec![0], + t_noise: vec![0, 16], + e_q: vec![vec![10i32; n_low]], + q_q: vec![vec![2i32; n_q]], + invf_mode: vec![0; n_q], + add_harmonic: None, + } + } + + /// Two adjacent 1024-sample core AUs run through the same `SbrChain` + /// element (as `raw_data_block`'s per-AU calls do) must each double to + /// exactly `2 * ANALYSIS_BANDS * 32` samples with no gap or overlap at + /// the junction: the coverage hole that let a whole access unit's + /// doubling go missing (see `apply_last`) never showed up in the + /// synthetic continuous-stream QMF round trip, since that test never + /// crosses an AU boundary at all. + #[test] + fn two_adjacent_access_units_double_rate_with_no_junction_discontinuity() { + let t = tables(); + let n_low = t.n_low; + let n_q = t.n_q; + let mut chain = SbrChain::new(44100); + let tag = 0u8; + chain.elements.insert( + tag, + Element { + parser: SbrParser::new(44100), + channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)], + last_data: None, + }, + ); + chain + .elements + .get_mut(&tag) + .unwrap() + .parser + .set_for_test(header(), t.clone()); + + let data = SbrData { + coupling: false, + channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)], + }; + + // A steady tone, not silence: silence round-trips trivially (every + // sample is already continuous at 0), which would hide exactly the + // discontinuity this test exists to catch. + let core_au = || -> Vec { (0..1024).map(|i| (i as f32 * 0.1).sin() * 0.2).collect() }; + let mut planes = vec![core_au(), core_au()]; + chain.apply(tag, &data, &mut planes); + + let expected_len = 32 * SYNTHESIS_BANDS; + for (ch, plane) in planes.iter().enumerate() { + assert_eq!( + plane.len(), + expected_len, + "ch{ch} AU1 didn't double to {expected_len} samples" + ); + } + + // Second AU through the SAME chain/state, as consecutive AUs in one + // stream are: this is what exercises the QMF history/HF-chirp/noise + // generator continuity across the junction, not just each AU in + // isolation. + let mut planes2 = vec![core_au(), core_au()]; + chain.apply(tag, &data, &mut planes2); + for (ch, plane) in planes2.iter().enumerate() { + assert_eq!( + plane.len(), + expected_len, + "ch{ch} AU2 didn't double to {expected_len} samples" + ); + } + + // Cumulative length across both AUs is exactly 2x2048, and the + // junction (last sample of AU1 next to the first of AU2) is not a + // discontinuity spike: a dropped/duplicated-AU bug (the one fixed by + // `apply_last`) either changes this total length or opens a silent + // gap, and a QMF history corruption at the boundary spikes the + // derivative right at the join far above the steady-state + // sample-to-sample delta the continuous tone otherwise has. + for ch in 0..2 { + let mut joined = planes[ch].clone(); + joined.extend_from_slice(&planes2[ch]); + assert_eq!(joined.len(), 2 * expected_len); + + let steady_delta = |s: &[f32]| -> f32 { + s.windows(2) + .skip(expected_len / 2) + .take(expected_len / 4) + .map(|w| (w[1] - w[0]).abs()) + .fold(0.0f32, f32::max) + }; + let typical = steady_delta(&joined); + let junction_delta = (joined[expected_len] - joined[expected_len - 1]).abs(); + assert!( + junction_delta <= typical * 4.0 + 1e-6, + "ch{ch} junction delta {junction_delta} far exceeds steady-state delta {typical} -- AU-boundary discontinuity" + ); + } + } +} diff --git a/crates/ec-aac/src/sbr_payload.rs b/crates/ec-aac/src/sbr_payload.rs index 01c28216..aed8ffcb 100644 --- a/crates/ec-aac/src/sbr_payload.rs +++ b/crates/ec-aac/src/sbr_payload.rs @@ -208,6 +208,16 @@ impl SbrParser { self.tables.as_ref() } + /// Test-only seam: installs a header/tables pair without driving a real + /// bitstream, so `sbr_chain`'s own tests can exercise `SbrChain::apply` + /// on synthetic data (the fields this sets are otherwise only reachable + /// through a successful `parse()`). + #[cfg(test)] + pub(crate) fn set_for_test(&mut self, header: SbrHeader, tables: BandTables) { + self.header = Some(header); + self.tables = Some(tables); + } + fn parse_grid(&self, r: &mut BitReader) -> Result { let frame_class = r.read_bits(2)?; match frame_class { diff --git a/crates/ec-aac/tests/sbr_real_library.rs b/crates/ec-aac/tests/sbr_real_library.rs index 13172a5d..1d2e3995 100644 --- a/crates/ec-aac/tests/sbr_real_library.rs +++ b/crates/ec-aac/tests/sbr_real_library.rs @@ -322,6 +322,47 @@ fn highpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec { samples.iter().zip(&low).map(|(a, b)| a - b).collect() } +/// Decisive-experiment diagnostic: correlates consecutive short (`WIN`) +/// windows of `o` against `t` (already coarsely aligned at `oa`/`ob`, e.g. +/// the winning full-file lag from `best_lag_correlation`), searching a small +/// local lag range per window. A per-frame continuity bug (dropped/duplicated +/// samples at access-unit boundaries) shows up as the winning local lag +/// DRIFTING linearly window to window; a bug that is not about concatenation +/// (wrong band mapping, spectral corruption) shows up as a roughly constant +/// lag with low/noisy correlation instead. +fn windowed_lag_drift( + o: &[f32], + t: &[f32], + oa: usize, + ob: usize, + windows: usize, +) -> Vec<(i64, f64)> { + const WIN: usize = 4_096; + const LOCAL_LAG: i64 = 2_000; + let mut out = Vec::with_capacity(windows); + for w in 0..windows { + let base_o = oa + w * WIN; + let base_t = ob + w * WIN; + let mut best = (0i64, -1.0f64, 0.0f64); + for lag in -LOCAL_LAG..=LOCAL_LAG { + let ao = base_o as i64 + lag; + if ao < 0 { + continue; + } + let ao = ao as usize; + if ao + WIN > o.len() || base_t + WIN > t.len() { + continue; + } + let c = correlation(&o[ao..ao + WIN], &t[base_t..base_t + WIN]); + if c.abs() > best.1 { + best = (lag, c.abs(), c); + } + } + out.push((best.0, best.2)); + } + out +} + /// A file discovered under the user's own media directories: its path, which /// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the /// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used @@ -461,6 +502,14 @@ fn sbr_real_library_matches_reference() { c.crossover_hz, c.crossover_hz ); let _ = (&o_low, &t_low); + if std::env::var("EC_AAC_SBR_DRIFT").is_ok() && n >= 4_096 { + let windows = (n / 4_096).min(20); + let drift = windowed_lag_drift(o, t, oa, ob, windows); + println!(" ch{ch} DRIFT (window_idx, local_lag, |corr|):"); + for (w, (l, cr)) in drift.iter().enumerate() { + println!(" w{w}: lag {l} corr {cr:.4}"); + } + } worst_full = worst_full.min(full); worst_low = worst_low.min(low); }