From e6128afe03fcc16521f29c443e874bd9fba6f446 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 21 Aug 2026 01:32:43 +0300 Subject: [PATCH] fix(aac-sbr): coupled balance raw values count in double steps (centre 6/12), pan offset and alpha from the frame's amp_res; FIXFIX-only single-envelope amp_res override reeln coupled CPE: full-band corr ch0 0.998652 -> 0.999210, ch1 0.996600 -> 0.999176. Adds sbr_residual_locator (per-band complex-STFT corr/level, Parseval-exact) which showed the previous ch1 HF level at 0.35-0.45 of the reference. --- crates/ec-aac/src/sbr_chain.rs | 1 + crates/ec-aac/src/sbr_env.rs | 60 +++++++++++--------- crates/ec-aac/src/sbr_payload.rs | 17 ++++-- crates/ec-aac/tests/sbr_real_library.rs | 73 +++++++++++++++++++++++++ 4 files changed, 119 insertions(+), 32 deletions(-) diff --git a/crates/ec-aac/src/sbr_chain.rs b/crates/ec-aac/src/sbr_chain.rs index b340e57f..44fb7d29 100644 --- a/crates/ec-aac/src/sbr_chain.rs +++ b/crates/ec-aac/src/sbr_chain.rs @@ -591,6 +591,7 @@ mod tests { df_env: vec![], df_noise: vec![], l_a: -1, + amp_res: 1, } } diff --git a/crates/ec-aac/src/sbr_env.rs b/crates/ec-aac/src/sbr_env.rs index db7198a4..9b596820 100644 --- a/crates/ec-aac/src/sbr_env.rs +++ b/crates/ec-aac/src/sbr_env.rs @@ -45,26 +45,28 @@ pub fn dequant_noise(q_q: i32) -> f64 { /// De-mixes a coupled CPE's `(channel 0 raw, balance raw)` pair into /// `(env0, env1)` linear energies (ISO/IEC 14496-3 §4.6.18.7.2, -/// `bs_coupling`): `Ecurr = dequant_env(e0_raw, amp_res)`, -/// `ratio = 2^(pan - panOffset)` where `pan` is the RAW balance value and -/// `panOffset` is 24 at `bs_amp_res=0` or 12 at `bs_amp_res=1`; -/// `env0 = 2*Ecurr/(1+ratio)`, `env1 = 2*Ecurr*ratio/(1+ratio)`. -/// `header_amp_res` governs `panOffset` regardless of the single-envelope -/// override -- the two diverge on single-envelope coupled frames. -pub fn dequant_pair(e0_raw: i32, pan_raw: i32, env_amp_res: u8, header_amp_res: u8) -> (f64, f64) { - let e_curr = dequant_env(e0_raw, env_amp_res); - let pan_offset = if header_amp_res != 0 { 12.0 } else { 24.0 }; - let ratio = 2f64.powf(f64::from(pan_raw) - pan_offset); - let env0 = 2.0 * e_curr / (1.0 + ratio); - let env1 = 2.0 * e_curr * ratio / (1.0 + ratio); - (env0, env1) +/// `bs_coupling`): `E = 2^(a*e0_raw + 7)`, `r = 2^(a*(panOffset - 2*pan))` +/// with `a` = 1 (3 dB) or 0.5 (1.5 dB) and `panOffset` = 12 / 24 for the +/// FRAME's amp_res (the FIXFIX single-envelope override included); +/// `env0 = E/(1+r)`, `env1 = env0*r`. The balance channel's raw values +/// (and its Huffman deltas) count in DOUBLE steps -- `bs_data_env` is one +/// bit narrower than the level field -- so its centre is 6 (3 dB) / 12 +/// (1.5 dB) in raw units; measured on a real coupled stream, where 88% of +/// the raw balance values sit exactly on that centre. +pub fn dequant_pair(e0_raw: i32, pan_raw: i32, amp_res: u8) -> (f64, f64) { + let a = alpha(amp_res); + let pan_offset = if amp_res != 0 { 12.0 } else { 24.0 }; + let ratio = 2f64.powf(a * (pan_offset - 2.0 * f64::from(pan_raw))); + let env0 = 2.0 * dequant_env(e0_raw, amp_res) / (1.0 + ratio); + (env0, env0 * ratio) } /// Coupled noise-floor pair (§4.6.18.7.2): `Q0 = 2^(NOISE_FLOOR_OFFSET - q0 + 1) -/// / (1 + 2^(12 - q1))`, `Q1 = Q0 * 2^(12 - q1)`. +/// / (1 + 2^(12 - 2*q1))`, `Q1 = Q0 * 2^(12 - 2*q1)` -- the raw balance +/// value counts in double steps, as for the envelope. pub fn dequant_noise_pair(q0_raw: i32, pan_raw: i32) -> (f64, f64) { let temp1 = 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q0_raw) + 1.0); - let temp2 = 2f64.powf(12.0 - f64::from(pan_raw)); + let temp2 = 2f64.powf(12.0 - 2.0 * f64::from(pan_raw)); let q0 = temp1 / (1.0 + temp2); (q0, q0 * temp2) } @@ -79,9 +81,7 @@ pub fn dequantize_frame( coupling: bool, ) -> (Vec>, Vec>) { let c = &channels[ch]; - // A single-envelope frame forces 1.5 dB resolution regardless of - // bs_amp_res, mirroring sbr_payload's own `amp_res_of`. - let amp_res = if c.e_q.len() == 1 { 0 } else { header.amp_res }; + let amp_res = c.amp_res; let coupled = coupling && channels.len() == 2; let pick = |pair: (f64, f64)| if ch == 0 { pair.0 } else { pair.1 }; let env = if coupled { @@ -91,7 +91,7 @@ pub fn dequantize_frame( .map(|b| { let e0 = channels[0].e_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0); let pan = channels[1].e_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0); - pick(dequant_pair(e0, pan, amp_res, header.amp_res)) + pick(dequant_pair(e0, pan, amp_res)) }) .collect() }) @@ -500,6 +500,7 @@ mod tests { df_env: vec![], df_noise: vec![], l_a: -1, + amp_res: 1, } } @@ -555,21 +556,26 @@ mod tests { #[test] fn coupled_balance_round_trips_at_a_centred_ratio() { - let (e0, e1) = dequant_pair(10, 12, 1, 1); + let (e0, e1) = dequant_pair(10, 6, 1); let e0_plain = dequant_env(10, 1); assert!((e0 - e0_plain).abs() < 1e-6 && (e1 - e0_plain).abs() < 1e-6, "{e0} {e1} vs {e0_plain}"); - let (e00, e10) = dequant_pair(10, 24, 0, 0); + let (e00, e10) = dequant_pair(10, 12, 0); let e00_plain = dequant_env(10, 0); assert!((e00 - e00_plain).abs() < 1e-6 && (e10 - e00_plain).abs() < 1e-6, "{e00} {e10} vs {e00_plain}"); - let (q0, q1) = dequant_noise_pair(3, 12); + let (q0, q1) = dequant_noise_pair(3, 6); assert!((q0 - dequant_noise(3)).abs() < 1e-9 && (q1 - q0).abs() < 1e-9); } #[test] - fn coupled_balance_shifts_energy_toward_the_channel_with_a_higher_raw_value() { - let (e0_low, e1_low) = dequant_pair(10, 0, 1, 1); - let (e0_high, e1_high) = dequant_pair(10, 24, 1, 1); - assert!(e0_low > e1_low, "{e0_low} vs {e1_low}"); - assert!(e0_high < e1_high, "{e0_high} vs {e1_high}"); + fn coupled_balance_shifts_energy_toward_channel_0_with_a_higher_raw_value() { + let (e0_low, e1_low) = dequant_pair(10, 0, 1); + let (e0_high, e1_high) = dequant_pair(10, 12, 1); + assert!(e0_low < e1_low, "{e0_low} vs {e1_low}"); + assert!(e0_high > e1_high, "{e0_high} vs {e1_high}"); + // One raw balance step is two amp_res steps of ratio: 6 dB at + // amp_res 1, 3 dB at amp_res 0. + let (a0, a1) = dequant_pair(10, 5, 1); + let (b0, b1) = dequant_pair(10, 11, 0); + assert!((a1 / a0 - 4.0).abs() < 1e-9 && (b1 / b0 - 2.0).abs() < 1e-9, "{a0} {a1} {b0} {b1}"); } } diff --git a/crates/ec-aac/src/sbr_payload.rs b/crates/ec-aac/src/sbr_payload.rs index 5dab5008..54850717 100644 --- a/crates/ec-aac/src/sbr_payload.rs +++ b/crates/ec-aac/src/sbr_payload.rs @@ -64,6 +64,9 @@ pub struct SbrChannel { /// at the transient border, `-1` when the frame has none. Gates where /// added sinusoids begin and which envelope skips noise/smoothing. pub l_a: i64, + /// The frame's effective amp_res: `bs_amp_res`, except a FIXFIX frame + /// with a single envelope is forced to 0 (1.5 dB) -- §4.6.18.3.3. + pub amp_res: u8, } /// One `sbr_data()` frame: one channel for an SCE, two for a CPE. @@ -84,6 +87,7 @@ struct Grid { t_env: Vec, t_noise: Vec, l_a: i64, + fixfix: bool, } impl Grid { @@ -118,6 +122,7 @@ impl Grid { t_env, t_noise, l_a, + fixfix: frame_class == 0, } } } @@ -180,9 +185,10 @@ fn raw_env_width(balance: bool, amp_res: u8) -> u32 { const RAW_NOISE_WIDTH: u32 = 5; /// A FIXFIX frame with a single envelope forces the 1.5 dB resolution -/// regardless of `bs_amp_res` (measured by the table-derivation rig). -fn amp_res_of(header_amp_res: u8, num_env: usize) -> u8 { - if num_env == 1 { 0 } else { header_amp_res } +/// regardless of `bs_amp_res` (§4.6.18.3.3); a one-envelope VARFIX/FIXVAR +/// frame keeps the header's value. +fn amp_res_of(header_amp_res: u8, grid: &Grid) -> u8 { + if grid.fixfix && grid.num_env == 1 { 0 } else { header_amp_res } } /// Reads one Huffman codeword by walking bit-by-bit until it matches a table @@ -549,7 +555,7 @@ impl SbrParser { let mut read_env = |this: &mut Self, r: &mut BitReader, ch: usize| -> Result<()> { let balance = is_cpe && coupling && ch == 1; let num_env = grids[ch].num_env; - let amp_res = amp_res_of(header.amp_res, num_env); + let amp_res = amp_res_of(header.amp_res, &grids[ch]); let mut e_q: Vec> = Vec::with_capacity(num_env); for i in 0..num_env { let bands = if grids[ch].freq_res[i] != 0 { @@ -607,7 +613,7 @@ impl SbrParser { for ch in 0..n_channels { let balance = is_cpe && coupling && ch == 1; let num_env = grids[ch].num_env; - let amp_res = amp_res_of(header.amp_res, num_env); + let amp_res = amp_res_of(header.amp_res, &grids[ch]); let e_q = e_q_all[ch].clone(); let q_q = q_q_all[ch].clone(); @@ -643,6 +649,7 @@ impl SbrParser { df_env: df_env[ch].iter().map(|&b| u8::from(b)).collect(), df_noise: df_noise[ch].iter().map(|&b| u8::from(b)).collect(), l_a: grids[ch].l_a, + amp_res, }); } diff --git a/crates/ec-aac/tests/sbr_real_library.rs b/crates/ec-aac/tests/sbr_real_library.rs index c4be655c..08200bdb 100644 --- a/crates/ec-aac/tests/sbr_real_library.rs +++ b/crates/ec-aac/tests/sbr_real_library.rs @@ -4619,3 +4619,76 @@ fn sbr_hf_window_band_probe() { ); } } + +/// Round-59 residual locator: per-2048-sample-window corr at lag 0 (worst +/// windows, with the output frame index) plus a complex-STFT per-band +/// correlation (Parseval: equals the time-domain corr restricted to that +/// band, so it needs no calibration) with an ours-vs-ours self-check column. +#[test] +fn sbr_residual_locator() { + if !have_ffmpeg() { + return; + } + let home = std::env::var("HOME").unwrap(); + let path = PathBuf::from(format!("{home}/Music/reeln.mp4")); + if !path.exists() { + return; + } + let Some((ours, _, rate)) = our_decode(&path, 0) else { return }; + let theirs = ffmpeg_decode(&path, 0, ours.len()); + const W: usize = 2048; + const FFT_LEN: usize = 2048; + const HOP: usize = 1024; + let bins = FFT_LEN / 2 + 1; + let mut rfft = ec_dsp::RealFft::::new(FFT_LEN); + let win = ec_dsp::Window::::sine(FFT_LEN); + for ch in 0..ours.len() { + let n = ours[ch].len().min(theirs[ch].len()); + let (o, t) = (&ours[ch][..n], &theirs[ch][..n]); + let mut wins: Vec<(f64, usize)> = (0..n / W) + .map(|w| (correlation(&o[w * W..(w + 1) * W], &t[w * W..(w + 1) * W]), w)) + .collect(); + wins.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap()); + println!("ch{ch} worst windows (corr, frame): {:?}", &wins[..12]); + let hops = (n - FFT_LEN) / HOP + 1; + let mut spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; + let mut acc = vec![[0.0f64; 3]; bins]; // re(o*conj t), |o|^2, |t|^2 + let mut os = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins]; + for h in 0..hops { + let mut b = o[h * HOP..h * HOP + FFT_LEN].to_vec(); + win.apply(&mut b); + rfft.forward(&b, &mut spec); + os.copy_from_slice(&spec); + let mut b = t[h * HOP..h * HOP + FFT_LEN].to_vec(); + win.apply(&mut b); + rfft.forward(&b, &mut spec); + for k in 0..bins { + let (a, c) = (os[k], spec[k]); + acc[k][0] += f64::from(a.re * c.re + a.im * c.im); + acc[k][1] += f64::from(a.norm_sqr()); + acc[k][2] += f64::from(c.norm_sqr()); + } + } + let hz = f64::from(rate) / FFT_LEN as f64; + let tot: f64 = acc.iter().map(|a| a[1] + a[2]).sum(); + // group into 250 Hz bands up to 8 kHz, then 1 kHz + let mut edges: Vec = (0..=32).map(|i| ((i as f64 * 250.0) / hz) as usize).collect(); + edges.extend((9..=22).map(|i| ((i as f64 * 1000.0) / hz) as usize)); + for e in edges.windows(2) { + let (mut c, mut po, mut pt) = (0.0, 0.0, 0.0); + for k in e[0]..e[1].min(bins) { + c += acc[k][0]; + po += acc[k][1]; + pt += acc[k][2]; + } + println!( + "ch{ch} {:5.0}-{:5.0} Hz corr {:.5} rms ours/ref {:.4} energy share {:.4}", + e[0] as f64 * hz, + e[1] as f64 * hz, + c / (po * pt).sqrt(), + (po / pt).sqrt(), + (po + pt) / tot + ); + } + } +}