SBR frames without a fresh FIL payload now reuse the last envelope
Browse files at this commitf505821694c68f3f159acce4637ea80efaf830c2Parent: 25a65cb- fix
- SBR frames without a fresh FIL payload now reuse the last envelope
4 changed files +240 -1
- crates/ec-aac/src/decode.rs +21 -1
- crates/ec-aac/src/sbr_chain.rs +160 -0
- crates/ec-aac/src/sbr_payload.rs +10 -0
- crates/ec-aac/tests/sbr_real_library.rs +49 -0
crates/ec-aac/src/decode.rsmodified+21 -1
| @@ -771,6 +771,7 @@ impl BlockDecoder { | |||
| 771 | // extension_payload(): bs_extension_type(4), then | 771 | // extension_payload(): bs_extension_type(4), then |
| 772 | // (for SBR) an optional 10-bit CRC, then | 772 | // (for SBR) an optional 10-bit CRC, then |
| 773 | // sbr_extension_data() itself. | 773 | // sbr_extension_data() itself. |
| 774 | + let mut applied = false; | ||
| 774 | if r.bits_remaining() >= 4 { | 775 | if r.bits_remaining() >= 4 { |
| 775 | let ext_type = r.peek_bits(4)?; | 776 | let ext_type = r.peek_bits(4)?; |
| 776 | if ext_type == 13 || ext_type == 14 { | 777 | if ext_type == 13 || ext_type == 14 { |
| @@ -780,9 +781,18 @@ impl BlockDecoder { | |||
| 780 | } | 781 | } |
| 781 | if let Some(data) = sbr.parse(r, tag, is_cpe) { | 782 | if let Some(data) = sbr.parse(r, tag, is_cpe) { |
| 782 | sbr.apply(tag, &data, &mut out[start..start + n]); | 783 | sbr.apply(tag, &data, &mut out[start..start + n]); |
| 784 | + applied = true; | ||
| 783 | } | 785 | } |
| 784 | } | 786 | } |
| 785 | } | 787 | } |
| 788 | + if !applied { | ||
| 789 | + // No fresh SBR payload this frame (no SBR fill | ||
| 790 | + // element, or one whose extension_type wasn't | ||
| 791 | + // SBR, or a parse failure): §4.6.18 still | ||
| 792 | + // requires doubled-rate reconstruction, using | ||
| 793 | + // the last successfully parsed frame's data. | ||
| 794 | + sbr.apply_last(tag, &mut out[start..start + n]); | ||
| 795 | + } | ||
| 786 | } | 796 | } |
| 787 | // Resync to the FIL's declared byte boundary regardless | 797 | // Resync to the FIL's declared byte boundary regardless |
| 788 | // of how many bits SBR parsing above actually consumed: | 798 | // of how many bits SBR parsing above actually consumed: |
| @@ -794,7 +804,17 @@ impl BlockDecoder { | |||
| 794 | } | 804 | } |
| 795 | pending = None; | 805 | pending = None; |
| 796 | } | 806 | } |
| 797 | - _ => break, | 807 | + _ => { |
| 808 | + // The block ended with no FIL element ever following the | ||
| 809 | + // last SCE/CPE (no SBR fill at all this frame, not even | ||
| 810 | + // a non-SBR one) -- same "unavailable frame" case as the | ||
| 811 | + // no-fresh-payload branch in id 6 above, so fall back to | ||
| 812 | + // the last known SBR data the same way. | ||
| 813 | + if let (Some(sbr), Some((tag, start, n, _))) = (self.sbr.as_mut(), pending) { | ||
| 814 | + sbr.apply_last(tag, &mut out[start..start + n]); | ||
| 815 | + } | ||
| 816 | + break; | ||
| 817 | + } | ||
| 798 | } | 818 | } |
| 799 | } | 819 | } |
| 800 | r.align_to_byte(); | 820 | r.align_to_byte(); |
crates/ec-aac/src/sbr_chain.rsmodified+160 -0
| @@ -84,6 +84,15 @@ impl ChannelState { | |||
| 84 | struct Element { | 84 | struct Element { |
| 85 | parser: SbrParser, | 85 | parser: SbrParser, |
| 86 | channels: Vec<ChannelState>, | 86 | channels: Vec<ChannelState>, |
| 87 | + /// The most recently parsed frame's envelope/noise/grid data, held so an | ||
| 88 | + /// access unit whose FIL element carries no fresh SBR payload this frame | ||
| 89 | + /// (an "unavailable" frame, §4.6.18: legal per spec and the decoder must | ||
| 90 | + /// keep reconstructing at the doubled rate using the last known data, | ||
| 91 | + /// not silently fall back to core-only output) can still be | ||
| 92 | + /// SBR-reconstructed instead of leaving that one access unit's plane at | ||
| 93 | + /// half length -- which otherwise permanently shifts every sample after | ||
| 94 | + /// it out of alignment with a reference that stayed at full rate. | ||
| 95 | + last_data: Option<SbrData>, | ||
| 87 | } | 96 | } |
| 88 | 97 | ||
| 89 | /// Every configured SBR element in a stream, keyed by | 98 | /// Every configured SBR element in a stream, keyed by |
| @@ -108,6 +117,7 @@ impl SbrChain { | |||
| 108 | let elem = self.elements.entry(tag).or_insert_with(|| Element { | 117 | let elem = self.elements.entry(tag).or_insert_with(|| Element { |
| 109 | parser: SbrParser::new(self.rate), | 118 | parser: SbrParser::new(self.rate), |
| 110 | channels: Vec::new(), | 119 | channels: Vec::new(), |
| 120 | + last_data: None, | ||
| 111 | }); | 121 | }); |
| 112 | let data = elem.parser.parse(r, is_cpe).ok()?; | 122 | let data = elem.parser.parse(r, is_cpe).ok()?; |
| 113 | let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); | 123 | let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); |
| @@ -123,6 +133,25 @@ impl SbrChain { | |||
| 123 | /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a | 133 | /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a |
| 124 | /// silent no-op: `planes` is left at its core content. | 134 | /// silent no-op: `planes` is left at its core content. |
| 125 | pub fn apply(&mut self, tag: u8, data: &SbrData, planes: &mut [Vec<f32>]) { | 135 | pub fn apply(&mut self, tag: u8, data: &SbrData, planes: &mut [Vec<f32>]) { |
| 136 | + if let Some(elem) = self.elements.get_mut(&tag) { | ||
| 137 | + elem.last_data = Some(data.clone()); | ||
| 138 | + } | ||
| 139 | + self.apply_data(tag, data, planes); | ||
| 140 | + } | ||
| 141 | + | ||
| 142 | + /// Re-runs the chain for `tag` using the last successfully parsed | ||
| 143 | + /// frame's SBR data, for an access unit whose own FIL element carried no | ||
| 144 | + /// fresh payload this frame. A no-op (planes left at core content, same | ||
| 145 | + /// as [`apply`]'s existing malformed/missing-state fallback) if no prior | ||
| 146 | + /// frame ever parsed successfully for this element. | ||
| 147 | + pub fn apply_last(&mut self, tag: u8, planes: &mut [Vec<f32>]) { | ||
| 148 | + let Some(data) = self.elements.get(&tag).and_then(|e| e.last_data.clone()) else { | ||
| 149 | + return; | ||
| 150 | + }; | ||
| 151 | + self.apply_data(tag, &data, planes); | ||
| 152 | + } | ||
| 153 | + | ||
| 154 | + fn apply_data(&mut self, tag: u8, data: &SbrData, planes: &mut [Vec<f32>]) { | ||
| 126 | let Some(elem) = self.elements.get_mut(&tag) else { | 155 | let Some(elem) = self.elements.get_mut(&tag) else { |
| 127 | return; | 156 | return; |
| 128 | }; | 157 | }; |
| @@ -220,3 +249,134 @@ impl SbrChain { | |||
| 220 | } | 249 | } |
| 221 | } | 250 | } |
| 222 | } | 251 | } |
| 252 | + | ||
| 253 | +#[cfg(test)] | ||
| 254 | +mod tests { | ||
| 255 | + use super::*; | ||
| 256 | + use crate::sbr_bands::freq_tables; | ||
| 257 | + use crate::sbr_payload::{SbrHeader, SbrParser}; | ||
| 258 | + | ||
| 259 | + fn tables() -> crate::sbr_bands::BandTables { | ||
| 260 | + freq_tables(44100, 5, 3, 2, 1, 2, 2).unwrap() | ||
| 261 | + } | ||
| 262 | + | ||
| 263 | + fn header() -> SbrHeader { | ||
| 264 | + SbrHeader { | ||
| 265 | + amp_res: 1, | ||
| 266 | + start_freq: 5, | ||
| 267 | + stop_freq: 3, | ||
| 268 | + xover_band: 2, | ||
| 269 | + freq_scale: 2, | ||
| 270 | + alter_scale: 1, | ||
| 271 | + noise_bands: 2, | ||
| 272 | + limiter_bands: 2, | ||
| 273 | + limiter_gains: 3, | ||
| 274 | + interpol_freq: 1, | ||
| 275 | + smoothing_mode: 1, | ||
| 276 | + } | ||
| 277 | + } | ||
| 278 | + | ||
| 279 | + fn one_channel(n_q: usize, n_low: usize) -> SbrChannel { | ||
| 280 | + SbrChannel { | ||
| 281 | + t_env: vec![0, 16], | ||
| 282 | + freq_res: vec![0], | ||
| 283 | + t_noise: vec![0, 16], | ||
| 284 | + e_q: vec![vec![10i32; n_low]], | ||
| 285 | + q_q: vec![vec![2i32; n_q]], | ||
| 286 | + invf_mode: vec![0; n_q], | ||
| 287 | + add_harmonic: None, | ||
| 288 | + } | ||
| 289 | + } | ||
| 290 | + | ||
| 291 | + /// Two adjacent 1024-sample core AUs run through the same `SbrChain` | ||
| 292 | + /// element (as `raw_data_block`'s per-AU calls do) must each double to | ||
| 293 | + /// exactly `2 * ANALYSIS_BANDS * 32` samples with no gap or overlap at | ||
| 294 | + /// the junction: the coverage hole that let a whole access unit's | ||
| 295 | + /// doubling go missing (see `apply_last`) never showed up in the | ||
| 296 | + /// synthetic continuous-stream QMF round trip, since that test never | ||
| 297 | + /// crosses an AU boundary at all. | ||
| 298 | + #[test] | ||
| 299 | + fn two_adjacent_access_units_double_rate_with_no_junction_discontinuity() { | ||
| 300 | + let t = tables(); | ||
| 301 | + let n_low = t.n_low; | ||
| 302 | + let n_q = t.n_q; | ||
| 303 | + let mut chain = SbrChain::new(44100); | ||
| 304 | + let tag = 0u8; | ||
| 305 | + chain.elements.insert( | ||
| 306 | + tag, | ||
| 307 | + Element { | ||
| 308 | + parser: SbrParser::new(44100), | ||
| 309 | + channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)], | ||
| 310 | + last_data: None, | ||
| 311 | + }, | ||
| 312 | + ); | ||
| 313 | + chain | ||
| 314 | + .elements | ||
| 315 | + .get_mut(&tag) | ||
| 316 | + .unwrap() | ||
| 317 | + .parser | ||
| 318 | + .set_for_test(header(), t.clone()); | ||
| 319 | + | ||
| 320 | + let data = SbrData { | ||
| 321 | + coupling: false, | ||
| 322 | + channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)], | ||
| 323 | + }; | ||
| 324 | + | ||
| 325 | + // A steady tone, not silence: silence round-trips trivially (every | ||
| 326 | + // sample is already continuous at 0), which would hide exactly the | ||
| 327 | + // discontinuity this test exists to catch. | ||
| 328 | + let core_au = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.1).sin() * 0.2).collect() }; | ||
| 329 | + let mut planes = vec![core_au(), core_au()]; | ||
| 330 | + chain.apply(tag, &data, &mut planes); | ||
| 331 | + | ||
| 332 | + let expected_len = 32 * SYNTHESIS_BANDS; | ||
| 333 | + for (ch, plane) in planes.iter().enumerate() { | ||
| 334 | + assert_eq!( | ||
| 335 | + plane.len(), | ||
| 336 | + expected_len, | ||
| 337 | + "ch{ch} AU1 didn't double to {expected_len} samples" | ||
| 338 | + ); | ||
| 339 | + } | ||
| 340 | + | ||
| 341 | + // Second AU through the SAME chain/state, as consecutive AUs in one | ||
| 342 | + // stream are: this is what exercises the QMF history/HF-chirp/noise | ||
| 343 | + // generator continuity across the junction, not just each AU in | ||
| 344 | + // isolation. | ||
| 345 | + let mut planes2 = vec![core_au(), core_au()]; | ||
| 346 | + chain.apply(tag, &data, &mut planes2); | ||
| 347 | + for (ch, plane) in planes2.iter().enumerate() { | ||
| 348 | + assert_eq!( | ||
| 349 | + plane.len(), | ||
| 350 | + expected_len, | ||
| 351 | + "ch{ch} AU2 didn't double to {expected_len} samples" | ||
| 352 | + ); | ||
| 353 | + } | ||
| 354 | + | ||
| 355 | + // Cumulative length across both AUs is exactly 2x2048, and the | ||
| 356 | + // junction (last sample of AU1 next to the first of AU2) is not a | ||
| 357 | + // discontinuity spike: a dropped/duplicated-AU bug (the one fixed by | ||
| 358 | + // `apply_last`) either changes this total length or opens a silent | ||
| 359 | + // gap, and a QMF history corruption at the boundary spikes the | ||
| 360 | + // derivative right at the join far above the steady-state | ||
| 361 | + // sample-to-sample delta the continuous tone otherwise has. | ||
| 362 | + for ch in 0..2 { | ||
| 363 | + let mut joined = planes[ch].clone(); | ||
| 364 | + joined.extend_from_slice(&planes2[ch]); | ||
| 365 | + assert_eq!(joined.len(), 2 * expected_len); | ||
| 366 | + | ||
| 367 | + let steady_delta = |s: &[f32]| -> f32 { | ||
| 368 | + s.windows(2) | ||
| 369 | + .skip(expected_len / 2) | ||
| 370 | + .take(expected_len / 4) | ||
| 371 | + .map(|w| (w[1] - w[0]).abs()) | ||
| 372 | + .fold(0.0f32, f32::max) | ||
| 373 | + }; | ||
| 374 | + let typical = steady_delta(&joined); | ||
| 375 | + let junction_delta = (joined[expected_len] - joined[expected_len - 1]).abs(); | ||
| 376 | + assert!( | ||
| 377 | + junction_delta <= typical * 4.0 + 1e-6, | ||
| 378 | + "ch{ch} junction delta {junction_delta} far exceeds steady-state delta {typical} -- AU-boundary discontinuity" | ||
| 379 | + ); | ||
| 380 | + } | ||
| 381 | + } | ||
| 382 | +} | ||
crates/ec-aac/src/sbr_payload.rsmodified+10 -0
| @@ -208,6 +208,16 @@ impl SbrParser { | |||
| 208 | self.tables.as_ref() | 208 | self.tables.as_ref() |
| 209 | } | 209 | } |
| 210 | 210 | ||
| 211 | + /// Test-only seam: installs a header/tables pair without driving a real | ||
| 212 | + /// bitstream, so `sbr_chain`'s own tests can exercise `SbrChain::apply` | ||
| 213 | + /// on synthetic data (the fields this sets are otherwise only reachable | ||
| 214 | + /// through a successful `parse()`). | ||
| 215 | + #[cfg(test)] | ||
| 216 | + pub(crate) fn set_for_test(&mut self, header: SbrHeader, tables: BandTables) { | ||
| 217 | + self.header = Some(header); | ||
| 218 | + self.tables = Some(tables); | ||
| 219 | + } | ||
| 220 | + | ||
| 211 | fn parse_grid(&self, r: &mut BitReader) -> Result<Grid> { | 221 | fn parse_grid(&self, r: &mut BitReader) -> Result<Grid> { |
| 212 | let frame_class = r.read_bits(2)?; | 222 | let frame_class = r.read_bits(2)?; |
| 213 | match frame_class { | 223 | match frame_class { |
crates/ec-aac/tests/sbr_real_library.rsmodified+49 -0
| @@ -322,6 +322,47 @@ fn highpass(samples: &[f32], rate: u32, cutoff_hz: f64) -> Vec<f32> { | |||
| 322 | samples.iter().zip(&low).map(|(a, b)| a - b).collect() | 322 | samples.iter().zip(&low).map(|(a, b)| a - b).collect() |
| 323 | } | 323 | } |
| 324 | 324 | ||
| 325 | +/// Decisive-experiment diagnostic: correlates consecutive short (`WIN`) | ||
| 326 | +/// windows of `o` against `t` (already coarsely aligned at `oa`/`ob`, e.g. | ||
| 327 | +/// the winning full-file lag from `best_lag_correlation`), searching a small | ||
| 328 | +/// local lag range per window. A per-frame continuity bug (dropped/duplicated | ||
| 329 | +/// samples at access-unit boundaries) shows up as the winning local lag | ||
| 330 | +/// DRIFTING linearly window to window; a bug that is not about concatenation | ||
| 331 | +/// (wrong band mapping, spectral corruption) shows up as a roughly constant | ||
| 332 | +/// lag with low/noisy correlation instead. | ||
| 333 | +fn windowed_lag_drift( | ||
| 334 | + o: &[f32], | ||
| 335 | + t: &[f32], | ||
| 336 | + oa: usize, | ||
| 337 | + ob: usize, | ||
| 338 | + windows: usize, | ||
| 339 | +) -> Vec<(i64, f64)> { | ||
| 340 | + const WIN: usize = 4_096; | ||
| 341 | + const LOCAL_LAG: i64 = 2_000; | ||
| 342 | + let mut out = Vec::with_capacity(windows); | ||
| 343 | + for w in 0..windows { | ||
| 344 | + let base_o = oa + w * WIN; | ||
| 345 | + let base_t = ob + w * WIN; | ||
| 346 | + let mut best = (0i64, -1.0f64, 0.0f64); | ||
| 347 | + for lag in -LOCAL_LAG..=LOCAL_LAG { | ||
| 348 | + let ao = base_o as i64 + lag; | ||
| 349 | + if ao < 0 { | ||
| 350 | + continue; | ||
| 351 | + } | ||
| 352 | + let ao = ao as usize; | ||
| 353 | + if ao + WIN > o.len() || base_t + WIN > t.len() { | ||
| 354 | + continue; | ||
| 355 | + } | ||
| 356 | + let c = correlation(&o[ao..ao + WIN], &t[base_t..base_t + WIN]); | ||
| 357 | + if c.abs() > best.1 { | ||
| 358 | + best = (lag, c.abs(), c); | ||
| 359 | + } | ||
| 360 | + } | ||
| 361 | + out.push((best.0, best.2)); | ||
| 362 | + } | ||
| 363 | + out | ||
| 364 | +} | ||
| 365 | + | ||
| 325 | /// A file discovered under the user's own media directories: its path, which | 366 | /// A file discovered under the user's own media directories: its path, which |
| 326 | /// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the | 367 | /// AAC stream in it (0-based among AAC streams only) carries HE-AAC, and the |
| 327 | /// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used | 368 | /// core/SBR crossover an ffprobe/ASC inspection already pinned for it -- used |
| @@ -461,6 +502,14 @@ fn sbr_real_library_matches_reference() { | |||
| 461 | c.crossover_hz, c.crossover_hz | 502 | c.crossover_hz, c.crossover_hz |
| 462 | ); | 503 | ); |
| 463 | let _ = (&o_low, &t_low); | 504 | let _ = (&o_low, &t_low); |
| 505 | + if std::env::var("EC_AAC_SBR_DRIFT").is_ok() && n >= 4_096 { | ||
| 506 | + let windows = (n / 4_096).min(20); | ||
| 507 | + let drift = windowed_lag_drift(o, t, oa, ob, windows); | ||
| 508 | + println!(" ch{ch} DRIFT (window_idx, local_lag, |corr|):"); | ||
| 509 | + for (w, (l, cr)) in drift.iter().enumerate() { | ||
| 510 | + println!(" w{w}: lag {l} corr {cr:.4}"); | ||
| 511 | + } | ||
| 512 | + } | ||
| 464 | worst_full = worst_full.min(full); | 513 | worst_full = worst_full.min(full); |
| 465 | worst_low = worst_low.min(low); | 514 | worst_low = worst_low.min(low); |
| 466 | } | 515 | } |