diff --git a/crates/ec-aac/src/sbr_bands.rs b/crates/ec-aac/src/sbr_bands.rs index 739fe1d2..ef2181a1 100644 --- a/crates/ec-aac/src/sbr_bands.rs +++ b/crates/ec-aac/src/sbr_bands.rs @@ -180,6 +180,10 @@ pub struct BandTables { pub f_noise: Vec, pub kx: i64, pub k2: i64, + /// Master table borders (`k0 = f_master[0]`), needed by the patch builder. + pub f_master: Vec, + /// SBR (output) sample rate, the patch builder's `goalSb` input. + pub rate: u32, } /// `rate` is the SBR rate: twice the AAC-LC core's. @@ -236,6 +240,8 @@ pub fn freq_tables( f_noise, kx, k2, + f_master: master.clone(), + rate, }) } diff --git a/crates/ec-aac/src/sbr_env.rs b/crates/ec-aac/src/sbr_env.rs index 09b0ae8e..9ad3541c 100644 --- a/crates/ec-aac/src/sbr_env.rs +++ b/crates/ec-aac/src/sbr_env.rs @@ -21,6 +21,14 @@ use crate::sbr_tables::SBR_NOISE; use ec_dsp::Complex; const NOISE_FLOOR_OFFSET: f64 = 6.0; +/// corner-cut: this chain's analysis bank (`sbr_qmf::Analysis`, undone by +/// its own `Synthesis`) carries twice the spec bank's subband amplitude, so +/// the transmitted energies need x4 to compare against `|X_high|^2` here. +/// Measured on the real-file per-QMF-band instrument (`EC_AAC_SBR_QMF_WITNESS`, +/// `QMF-BAND` rows): a uniform -6 dB across every HF band with the low +/// band at 0 dB before this factor. Ceiling: none functionally; the upgrade +/// path is normalising `sbr_qmf` to the spec's gain and dropping this. +const ENV_DOMAIN_SCALE: f64 = 4.0; /// Envelope amp-resolution exponent: `2.0` (`bs_amp_res=1`, 3 dB) or `1.0` /// (`bs_amp_res=0`, 1.5 dB) -- expressed as the multiplier on `e_q/2` so @@ -30,13 +38,11 @@ fn alpha(amp_res: u8) -> f64 { if amp_res != 0 { 1.0 } else { 0.5 } } -/// Plain (non-coupled) envelope dequantization: `E_Orig = 2^(E_Q * a)`. -/// §4.6.18.7.2 carries an extra `* 64` here; it is a pure scale on the -/// whole HF region (the gain `sqrt(E_orig/E_curr)` cancels our own QMF -/// scale otherwise), and this chain's QMF domain is calibrated without it -/// (see `sbr_chain`'s OUTPUT_SCALE handling). +/// Plain (non-coupled) envelope dequantization: `E_Orig = 2^(E_Q * a) * 64` +/// (§4.6.18.7.2), times `ENV_DOMAIN_SCALE` to land in this chain's QMF +/// energy domain. pub fn dequant_env(e_q: i32, amp_res: u8) -> f64 { - 2f64.powf(alpha(amp_res) * f64::from(e_q)) + 2f64.powf(alpha(amp_res) * f64::from(e_q)) * 64.0 * ENV_DOMAIN_SCALE } /// Plain noise-floor dequantization: `Q_Orig = 2^(NOISE_FLOOR_OFFSET - Q_Q)`, diff --git a/crates/ec-aac/src/sbr_hf.rs b/crates/ec-aac/src/sbr_hf.rs index 6ec73462..e3d7670a 100644 --- a/crates/ec-aac/src/sbr_hf.rs +++ b/crates/ec-aac/src/sbr_hf.rs @@ -124,45 +124,66 @@ pub struct Patch { pub width: usize, } -/// Builds the patch list filling `[tables.kx, tables.k2)` from bands below -/// `kx`, walking the source pointer down and wrapping it back to `kx` when -/// exhausted. Deterministic: the same tables always produce the same patches. +/// Patch construction, ISO/IEC 14496-3 §4.6.18.6.3 (Figure 4.31): source +/// bands are read downward from `k0 = f_master[0]`, patches end on master +/// borders, `goalSb = round(2048 kHz / fs)` bounds the first patch, and a +/// trailing patch narrower than 3 bands is dropped. pub fn build_patches(tables: &BandTables) -> Vec { - let kx = tables.kx as usize; - let k2 = tables.k2 as usize; - let f_high: Vec = tables.f_high.iter().map(|&b| b as usize).collect(); + let kx = tables.kx; + let k2 = tables.k2; + let fm = &tables.f_master; let mut patches = Vec::new(); - if kx == 0 || k2 <= kx { + if kx <= 0 || k2 <= kx || fm.len() < 2 { return patches; } - let mut msb = kx; // source read pointer, decreasing - let mut sb = kx; // target write pointer, increasing - while sb < k2 { - // Widest run of consecutive f_high intervals starting at `sb` whose - // total width still fits below the current source pointer. - let mut width = 0usize; - let mut probe = sb; + let k0 = fm[0]; + let n_master = fm.len() - 1; + let goal_sb = ((1000i64 << 11) + i64::from(tables.rate >> 1)) / i64::from(tables.rate.max(1)); + let mut k = if goal_sb < k2 { + fm.iter().position(|&b| b >= goal_sb).unwrap_or(n_master) + } else { + n_master + }; + let (mut msb, mut usb) = (k0, kx); + let (mut last_k, mut last_msb) = (usize::MAX, i64::MIN); + let mut sb; + loop { + if k == last_k && msb == last_msb { + break; // construction failed; keep what we have + } + last_k = k; + last_msb = msb; + let mut odd = 0i64; + let mut i = k; loop { - let next_border = f_high.iter().find(|&&b| b > probe).copied(); - let Some(border) = next_border else { break }; - let iv = border - probe; - if width + iv > msb || border > k2 { + sb = fm[i]; + odd = (sb + k0) & 1; + if i == 0 || sb <= k0 - 1 + msb - odd { break; } - width += iv; - probe = border; + i -= 1; + } + let width = (sb - usb).max(0); + if width > 0 { + patches.push(Patch { + source_start: (k0 - odd - width).max(0) as usize, + target_start: usb as usize, + width: width as usize, + }); + usb = sb; + msb = sb; + } else { + msb = kx; } - if width == 0 { - width = (k2 - sb).min(msb.max(1)); + if fm[k] - sb < 3 { + k = n_master; } - let source_start = msb - width.min(msb); - patches.push(Patch { - source_start, - target_start: sb, - width, - }); - sb += width; - msb = if source_start == 0 { kx } else { source_start }; + if sb == k2 || patches.len() > 6 { + break; + } + } + if patches.len() > 1 && patches.last().is_some_and(|p| p.width < 3) { + patches.pop(); } patches } diff --git a/crates/ec-aac/tests/sbr_real_library.rs b/crates/ec-aac/tests/sbr_real_library.rs index 1372e59e..c4be655c 100644 --- a/crates/ec-aac/tests/sbr_real_library.rs +++ b/crates/ec-aac/tests/sbr_real_library.rs @@ -2755,6 +2755,8 @@ fn sbr_real_library_matches_reference() { let high = if n >= 1024 { let oh = highpass(&o[oa..oa + n], rate, c.crossover_hz); let th = highpass(&t[ob..ob + n], rate, c.crossover_hz); + let rms = |v: &[f32]| (v.iter().map(|x| f64::from(*x).powi(2)).sum::() / v.len().max(1) as f64).sqrt(); + println!(" ch{ch} above-crossover RMS ours/ref = {:.4}", rms(&oh) / rms(&th).max(1e-12)); correlation(&oh, &th) } else { 0.0 @@ -3004,6 +3006,25 @@ fn sbr_real_library_matches_reference() { let win = &o[oa..oa + n]; let twin = &t[ob..ob + n]; let (vs_ref, vs_ours, ours_vs_ref) = hf_patch_simulator_qmf(win, twin); + // Per-QMF-band energy ratio and coherence, ours vs reference + // (the envelope-adjuster instrument: a level offset shows as + // a constant dB ratio, a gain-shape defect as per-band dB). + { + let (o_spec, t_spec, _) = qmf_domain_spec(win, twin); + println!(" ch{ch} QMF-BAND ours-vs-REFERENCE (band, ratio_dB, coherence):"); + for band in 0..o_spec.len().min(t_spec.len()).min(48) { + let (mut eo, mut et, mut cr, mut ci) = (0.0f64, 0.0f64, 0.0f64, 0.0f64); + for (a, b) in o_spec[band].iter().zip(&t_spec[band]) { + eo += a.norm_sqr(); + et += b.norm_sqr(); + let c = *a * b.conj(); + cr += c.re; + ci += c.im; + } + let coh = (cr * cr + ci * ci).sqrt() / (eo * et).sqrt().max(1e-30); + println!(" band{band:>3}: {:>7.2} dB coh {coh:.4}", 10.0 * (eo / et.max(1e-30)).log10()); + } + } let mean_in = |rows: &[(usize, f64)], lo: usize, hi: usize| { let vals: Vec = rows .iter()