forge
Explore
Log in

Don't you dare go Hollow

Coupled balance raw values count in double steps (centre 6/12), pan offset and alpha from the frame's amp_res

Browse files at this commit

e6128afe03fcc16521f29c443e874bd9fba6f446Ahmet Kaan GümüşParent: b61d50e
  • fix
    • 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
Show full message
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.rsmodified+1 -0
@@ -591,6 +591,7 @@ mod tests {
591 df_env: vec![],591 df_env: vec![],
592 df_noise: vec![],592 df_noise: vec![],
593 l_a: -1,593 l_a: -1,
594+ amp_res: 1,
594 }595 }
595 }596 }
596 597
crates/ec-aac/src/sbr_env.rsmodified+33 -27
@@ -45,26 +45,28 @@ pub fn dequant_noise(q_q: i32) -> f64 {
45 45
46 /// De-mixes a coupled CPE's `(channel 0 raw, balance raw)` pair into46 /// De-mixes a coupled CPE's `(channel 0 raw, balance raw)` pair into
47 /// `(env0, env1)` linear energies (ISO/IEC 14496-3 §4.6.18.7.2,47 /// `(env0, env1)` linear energies (ISO/IEC 14496-3 §4.6.18.7.2,
48-/// `bs_coupling`): `Ecurr = dequant_env(e0_raw, amp_res)`,48+/// `bs_coupling`): `E = 2^(a*e0_raw + 7)`, `r = 2^(a*(panOffset - 2*pan))`
49-/// `ratio = 2^(pan - panOffset)` where `pan` is the RAW balance value and49+/// with `a` = 1 (3 dB) or 0.5 (1.5 dB) and `panOffset` = 12 / 24 for the
50-/// `panOffset` is 24 at `bs_amp_res=0` or 12 at `bs_amp_res=1`;50+/// FRAME's amp_res (the FIXFIX single-envelope override included);
51-/// `env0 = 2*Ecurr/(1+ratio)`, `env1 = 2*Ecurr*ratio/(1+ratio)`.51+/// `env0 = E/(1+r)`, `env1 = env0*r`. The balance channel's raw values
52-/// `header_amp_res` governs `panOffset` regardless of the single-envelope52+/// (and its Huffman deltas) count in DOUBLE steps -- `bs_data_env` is one
53-/// override -- the two diverge on single-envelope coupled frames.53+/// bit narrower than the level field -- so its centre is 6 (3 dB) / 12
54-pub fn dequant_pair(e0_raw: i32, pan_raw: i32, env_amp_res: u8, header_amp_res: u8) -> (f64, f64) {54+/// (1.5 dB) in raw units; measured on a real coupled stream, where 88% of
55- let e_curr = dequant_env(e0_raw, env_amp_res);55+/// the raw balance values sit exactly on that centre.
56- let pan_offset = if header_amp_res != 0 { 12.0 } else { 24.0 };56+pub fn dequant_pair(e0_raw: i32, pan_raw: i32, amp_res: u8) -> (f64, f64) {
57- let ratio = 2f64.powf(f64::from(pan_raw) - pan_offset);57+ let a = alpha(amp_res);
58- let env0 = 2.0 * e_curr / (1.0 + ratio);58+ let pan_offset = if amp_res != 0 { 12.0 } else { 24.0 };
59- let env1 = 2.0 * e_curr * ratio / (1.0 + ratio);59+ let ratio = 2f64.powf(a * (pan_offset - 2.0 * f64::from(pan_raw)));
60- (env0, env1)60+ let env0 = 2.0 * dequant_env(e0_raw, amp_res) / (1.0 + ratio);
61+ (env0, env0 * ratio)
61 }62 }
62 63
63 /// Coupled noise-floor pair (§4.6.18.7.2): `Q0 = 2^(NOISE_FLOOR_OFFSET - q0 + 1)64 /// Coupled noise-floor pair (§4.6.18.7.2): `Q0 = 2^(NOISE_FLOOR_OFFSET - q0 + 1)
64-/// / (1 + 2^(12 - q1))`, `Q1 = Q0 * 2^(12 - q1)`.65+/// / (1 + 2^(12 - 2*q1))`, `Q1 = Q0 * 2^(12 - 2*q1)` -- the raw balance
66+/// value counts in double steps, as for the envelope.
65 pub fn dequant_noise_pair(q0_raw: i32, pan_raw: i32) -> (f64, f64) {67 pub fn dequant_noise_pair(q0_raw: i32, pan_raw: i32) -> (f64, f64) {
66 let temp1 = 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q0_raw) + 1.0);68 let temp1 = 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q0_raw) + 1.0);
67- let temp2 = 2f64.powf(12.0 - f64::from(pan_raw));69+ let temp2 = 2f64.powf(12.0 - 2.0 * f64::from(pan_raw));
68 let q0 = temp1 / (1.0 + temp2);70 let q0 = temp1 / (1.0 + temp2);
69 (q0, q0 * temp2)71 (q0, q0 * temp2)
70 }72 }
@@ -79,9 +81,7 @@ pub fn dequantize_frame(
79 coupling: bool,81 coupling: bool,
80 ) -> (Vec<Vec<f64>>, Vec<Vec<f64>>) {82 ) -> (Vec<Vec<f64>>, Vec<Vec<f64>>) {
81 let c = &channels[ch];83 let c = &channels[ch];
82- // A single-envelope frame forces 1.5 dB resolution regardless of84+ let amp_res = c.amp_res;
83- // bs_amp_res, mirroring sbr_payload's own `amp_res_of`.
84- let amp_res = if c.e_q.len() == 1 { 0 } else { header.amp_res };
85 let coupled = coupling && channels.len() == 2;85 let coupled = coupling && channels.len() == 2;
86 let pick = |pair: (f64, f64)| if ch == 0 { pair.0 } else { pair.1 };86 let pick = |pair: (f64, f64)| if ch == 0 { pair.0 } else { pair.1 };
87 let env = if coupled {87 let env = if coupled {
@@ -91,7 +91,7 @@ pub fn dequantize_frame(
91 .map(|b| {91 .map(|b| {
92 let e0 = channels[0].e_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0);92 let e0 = channels[0].e_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0);
93 let pan = channels[1].e_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0);93 let pan = channels[1].e_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0);
94- pick(dequant_pair(e0, pan, amp_res, header.amp_res))94+ pick(dequant_pair(e0, pan, amp_res))
95 })95 })
96 .collect()96 .collect()
97 })97 })
@@ -500,6 +500,7 @@ mod tests {
500 df_env: vec![],500 df_env: vec![],
501 df_noise: vec![],501 df_noise: vec![],
502 l_a: -1,502 l_a: -1,
503+ amp_res: 1,
503 }504 }
504 }505 }
505 506
@@ -555,21 +556,26 @@ mod tests {
555 556
556 #[test]557 #[test]
557 fn coupled_balance_round_trips_at_a_centred_ratio() {558 fn coupled_balance_round_trips_at_a_centred_ratio() {
558- let (e0, e1) = dequant_pair(10, 12, 1, 1);559+ let (e0, e1) = dequant_pair(10, 6, 1);
559 let e0_plain = dequant_env(10, 1);560 let e0_plain = dequant_env(10, 1);
560 assert!((e0 - e0_plain).abs() < 1e-6 && (e1 - e0_plain).abs() < 1e-6, "{e0} {e1} vs {e0_plain}");561 assert!((e0 - e0_plain).abs() < 1e-6 && (e1 - e0_plain).abs() < 1e-6, "{e0} {e1} vs {e0_plain}");
561- let (e00, e10) = dequant_pair(10, 24, 0, 0);562+ let (e00, e10) = dequant_pair(10, 12, 0);
562 let e00_plain = dequant_env(10, 0);563 let e00_plain = dequant_env(10, 0);
563 assert!((e00 - e00_plain).abs() < 1e-6 && (e10 - e00_plain).abs() < 1e-6, "{e00} {e10} vs {e00_plain}");564 assert!((e00 - e00_plain).abs() < 1e-6 && (e10 - e00_plain).abs() < 1e-6, "{e00} {e10} vs {e00_plain}");
564- let (q0, q1) = dequant_noise_pair(3, 12);565+ let (q0, q1) = dequant_noise_pair(3, 6);
565 assert!((q0 - dequant_noise(3)).abs() < 1e-9 && (q1 - q0).abs() < 1e-9);566 assert!((q0 - dequant_noise(3)).abs() < 1e-9 && (q1 - q0).abs() < 1e-9);
566 }567 }
567 568
568 #[test]569 #[test]
569- fn coupled_balance_shifts_energy_toward_the_channel_with_a_higher_raw_value() {570+ fn coupled_balance_shifts_energy_toward_channel_0_with_a_higher_raw_value() {
570- let (e0_low, e1_low) = dequant_pair(10, 0, 1, 1);571+ let (e0_low, e1_low) = dequant_pair(10, 0, 1);
571- let (e0_high, e1_high) = dequant_pair(10, 24, 1, 1);572+ let (e0_high, e1_high) = dequant_pair(10, 12, 1);
572- assert!(e0_low > e1_low, "{e0_low} vs {e1_low}");573+ assert!(e0_low < e1_low, "{e0_low} vs {e1_low}");
573- assert!(e0_high < e1_high, "{e0_high} vs {e1_high}");574+ assert!(e0_high > e1_high, "{e0_high} vs {e1_high}");
575+ // One raw balance step is two amp_res steps of ratio: 6 dB at
576+ // amp_res 1, 3 dB at amp_res 0.
577+ let (a0, a1) = dequant_pair(10, 5, 1);
578+ let (b0, b1) = dequant_pair(10, 11, 0);
579+ assert!((a1 / a0 - 4.0).abs() < 1e-9 && (b1 / b0 - 2.0).abs() < 1e-9, "{a0} {a1} {b0} {b1}");
574 }580 }
575 }581 }
crates/ec-aac/src/sbr_payload.rsmodified+12 -5
@@ -64,6 +64,9 @@ pub struct SbrChannel {
64 /// at the transient border, `-1` when the frame has none. Gates where64 /// at the transient border, `-1` when the frame has none. Gates where
65 /// added sinusoids begin and which envelope skips noise/smoothing.65 /// added sinusoids begin and which envelope skips noise/smoothing.
66 pub l_a: i64,66 pub l_a: i64,
67+ /// The frame's effective amp_res: `bs_amp_res`, except a FIXFIX frame
68+ /// with a single envelope is forced to 0 (1.5 dB) -- §4.6.18.3.3.
69+ pub amp_res: u8,
67 }70 }
68 71
69 /// One `sbr_data()` frame: one channel for an SCE, two for a CPE.72 /// One `sbr_data()` frame: one channel for an SCE, two for a CPE.
@@ -84,6 +87,7 @@ struct Grid {
84 t_env: Vec<i64>,87 t_env: Vec<i64>,
85 t_noise: Vec<i64>,88 t_noise: Vec<i64>,
86 l_a: i64,89 l_a: i64,
90+ fixfix: bool,
87 }91 }
88 92
89 impl Grid {93 impl Grid {
@@ -118,6 +122,7 @@ impl Grid {
118 t_env,122 t_env,
119 t_noise,123 t_noise,
120 l_a,124 l_a,
125+ fixfix: frame_class == 0,
121 }126 }
122 }127 }
123 }128 }
@@ -180,9 +185,10 @@ fn raw_env_width(balance: bool, amp_res: u8) -> u32 {
180 const RAW_NOISE_WIDTH: u32 = 5;185 const RAW_NOISE_WIDTH: u32 = 5;
181 186
182 /// A FIXFIX frame with a single envelope forces the 1.5 dB resolution187 /// A FIXFIX frame with a single envelope forces the 1.5 dB resolution
183-/// regardless of `bs_amp_res` (measured by the table-derivation rig).188+/// regardless of `bs_amp_res` (§4.6.18.3.3); a one-envelope VARFIX/FIXVAR
184-fn amp_res_of(header_amp_res: u8, num_env: usize) -> u8 {189+/// frame keeps the header's value.
185- if num_env == 1 { 0 } else { header_amp_res }190+fn amp_res_of(header_amp_res: u8, grid: &Grid) -> u8 {
191+ if grid.fixfix && grid.num_env == 1 { 0 } else { header_amp_res }
186 }192 }
187 193
188 /// Reads one Huffman codeword by walking bit-by-bit until it matches a table194 /// Reads one Huffman codeword by walking bit-by-bit until it matches a table
@@ -549,7 +555,7 @@ impl SbrParser {
549 let mut read_env = |this: &mut Self, r: &mut BitReader, ch: usize| -> Result<()> {555 let mut read_env = |this: &mut Self, r: &mut BitReader, ch: usize| -> Result<()> {
550 let balance = is_cpe && coupling && ch == 1;556 let balance = is_cpe && coupling && ch == 1;
551 let num_env = grids[ch].num_env;557 let num_env = grids[ch].num_env;
552- let amp_res = amp_res_of(header.amp_res, num_env);558+ let amp_res = amp_res_of(header.amp_res, &grids[ch]);
553 let mut e_q: Vec<Vec<i32>> = Vec::with_capacity(num_env);559 let mut e_q: Vec<Vec<i32>> = Vec::with_capacity(num_env);
554 for i in 0..num_env {560 for i in 0..num_env {
555 let bands = if grids[ch].freq_res[i] != 0 {561 let bands = if grids[ch].freq_res[i] != 0 {
@@ -607,7 +613,7 @@ impl SbrParser {
607 for ch in 0..n_channels {613 for ch in 0..n_channels {
608 let balance = is_cpe && coupling && ch == 1;614 let balance = is_cpe && coupling && ch == 1;
609 let num_env = grids[ch].num_env;615 let num_env = grids[ch].num_env;
610- let amp_res = amp_res_of(header.amp_res, num_env);616+ let amp_res = amp_res_of(header.amp_res, &grids[ch]);
611 let e_q = e_q_all[ch].clone();617 let e_q = e_q_all[ch].clone();
612 let q_q = q_q_all[ch].clone();618 let q_q = q_q_all[ch].clone();
613 619
@@ -643,6 +649,7 @@ impl SbrParser {
643 df_env: df_env[ch].iter().map(|&b| u8::from(b)).collect(),649 df_env: df_env[ch].iter().map(|&b| u8::from(b)).collect(),
644 df_noise: df_noise[ch].iter().map(|&b| u8::from(b)).collect(),650 df_noise: df_noise[ch].iter().map(|&b| u8::from(b)).collect(),
645 l_a: grids[ch].l_a,651 l_a: grids[ch].l_a,
652+ amp_res,
646 });653 });
647 }654 }
648 655
crates/ec-aac/tests/sbr_real_library.rsmodified+73 -0
@@ -4619,3 +4619,76 @@ fn sbr_hf_window_band_probe() {
4619 );4619 );
4620 }4620 }
4621 }4621 }
4622+
4623+/// Round-59 residual locator: per-2048-sample-window corr at lag 0 (worst
4624+/// windows, with the output frame index) plus a complex-STFT per-band
4625+/// correlation (Parseval: equals the time-domain corr restricted to that
4626+/// band, so it needs no calibration) with an ours-vs-ours self-check column.
4627+#[test]
4628+fn sbr_residual_locator() {
4629+ if !have_ffmpeg() {
4630+ return;
4631+ }
4632+ let home = std::env::var("HOME").unwrap();
4633+ let path = PathBuf::from(format!("{home}/Music/reeln.mp4"));
4634+ if !path.exists() {
4635+ return;
4636+ }
4637+ let Some((ours, _, rate)) = our_decode(&path, 0) else { return };
4638+ let theirs = ffmpeg_decode(&path, 0, ours.len());
4639+ const W: usize = 2048;
4640+ const FFT_LEN: usize = 2048;
4641+ const HOP: usize = 1024;
4642+ let bins = FFT_LEN / 2 + 1;
4643+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
4644+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
4645+ for ch in 0..ours.len() {
4646+ let n = ours[ch].len().min(theirs[ch].len());
4647+ let (o, t) = (&ours[ch][..n], &theirs[ch][..n]);
4648+ let mut wins: Vec<(f64, usize)> = (0..n / W)
4649+ .map(|w| (correlation(&o[w * W..(w + 1) * W], &t[w * W..(w + 1) * W]), w))
4650+ .collect();
4651+ wins.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
4652+ println!("ch{ch} worst windows (corr, frame): {:?}", &wins[..12]);
4653+ let hops = (n - FFT_LEN) / HOP + 1;
4654+ let mut spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
4655+ let mut acc = vec![[0.0f64; 3]; bins]; // re(o*conj t), |o|^2, |t|^2
4656+ let mut os = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
4657+ for h in 0..hops {
4658+ let mut b = o[h * HOP..h * HOP + FFT_LEN].to_vec();
4659+ win.apply(&mut b);
4660+ rfft.forward(&b, &mut spec);
4661+ os.copy_from_slice(&spec);
4662+ let mut b = t[h * HOP..h * HOP + FFT_LEN].to_vec();
4663+ win.apply(&mut b);
4664+ rfft.forward(&b, &mut spec);
4665+ for k in 0..bins {
4666+ let (a, c) = (os[k], spec[k]);
4667+ acc[k][0] += f64::from(a.re * c.re + a.im * c.im);
4668+ acc[k][1] += f64::from(a.norm_sqr());
4669+ acc[k][2] += f64::from(c.norm_sqr());
4670+ }
4671+ }
4672+ let hz = f64::from(rate) / FFT_LEN as f64;
4673+ let tot: f64 = acc.iter().map(|a| a[1] + a[2]).sum();
4674+ // group into 250 Hz bands up to 8 kHz, then 1 kHz
4675+ let mut edges: Vec<usize> = (0..=32).map(|i| ((i as f64 * 250.0) / hz) as usize).collect();
4676+ edges.extend((9..=22).map(|i| ((i as f64 * 1000.0) / hz) as usize));
4677+ for e in edges.windows(2) {
4678+ let (mut c, mut po, mut pt) = (0.0, 0.0, 0.0);
4679+ for k in e[0]..e[1].min(bins) {
4680+ c += acc[k][0];
4681+ po += acc[k][1];
4682+ pt += acc[k][2];
4683+ }
4684+ println!(
4685+ "ch{ch} {:5.0}-{:5.0} Hz corr {:.5} rms ours/ref {:.4} energy share {:.4}",
4686+ e[0] as f64 * hz,
4687+ e[1] as f64 * hz,
4688+ c / (po * pt).sqrt(),
4689+ (po / pt).sqrt(),
4690+ (po + pt) / tot
4691+ );
4692+ }
4693+ }
4694+}