forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'sbr-header-alpha': HE-AAC SBR to reference parity (spec HF generator, adjuster, QMF bank, coupling, 3 dB books)

Browse files at this commit

b70929ca81fb757b731574b627582659e9e5ef02Ahmet Kaan GümüşParent: 011ae0f11270e5

9 changed files +1818 -1368

crates/ec-aac/src/sbr_bands.rsmodified+6 -0
@@ -180,6 +180,10 @@ pub struct BandTables {
180180 pub f_noise: Vec<i64>,
181181 pub kx: i64,
182182 pub k2: i64,
183+ /// Master table borders (`k0 = f_master[0]`), needed by the patch builder.
184+ pub f_master: Vec<i64>,
185+ /// SBR (output) sample rate, the patch builder's `goalSb` input.
186+ pub rate: u32,
183187 }
184188
185189 /// `rate` is the SBR rate: twice the AAC-LC core's.
@@ -236,6 +240,8 @@ pub fn freq_tables(
236240 f_noise,
237241 kx,
238242 k2,
243+ f_master: master.clone(),
244+ rate,
239245 })
240246 }
241247
crates/ec-aac/src/sbr_chain.rsmodified+79 -12
@@ -4,7 +4,7 @@
44 //! PCM through 32-band analysis, generate and adjust the HF region, and
55 //! resynthesize through the 64-band bank to double-rate PCM in place.
66
7-use crate::sbr_env::{self, NoiseGen};
7+use crate::sbr_env::{self, AdjustState};
88 use crate::sbr_hf::{self, ChirpState, HfHistory};
99 use crate::sbr_payload::{SbrChannel, SbrData, SbrParser};
1010 use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis};
@@ -181,17 +181,32 @@ struct ChannelState {
181181 synthesis: Synthesis,
182182 hf_hist: HfHistory,
183183 chirp: ChirpState,
184- noise: NoiseGen,
184+ adj: AdjustState,
185+ /// §4.6.18.7.6 `tHFAdj`/overlap buffers: the SBR output lags the raw
186+ /// analysis by `HF_ADJ` slots, so the previous frame's last `HF_ADJ`
187+ /// raw low-band and raw HF slots are kept, plus the already-adjusted HF
188+ /// slots past the frame end that a variable-border envelope produced
189+ /// (`Y` of slots `32..2*t_E(L_E)`), which lead the next frame's output.
190+ low_tail: Vec<[Complex<f64>; ANALYSIS_BANDS]>,
191+ hf_tail: Vec<Vec<Complex<f64>>>,
192+ y_carry: Vec<Vec<Complex<f64>>>,
185193 }
186194
195+/// Slots by which the HF adjuster's envelope grid lags the raw QMF frame
196+/// (`tHFAdj` + the 6-slot overlap, §4.6.18.7.6 / Figure 4.32).
197+const HF_ADJ: usize = 6;
198+
187199 impl ChannelState {
188- fn new(n_q: usize, seed: u32) -> ChannelState {
200+ fn new(n_q: usize, _seed: u32) -> ChannelState {
189201 ChannelState {
190202 analysis: Analysis::new(),
191203 synthesis: Synthesis::new(),
192204 hf_hist: HfHistory::new(ANALYSIS_BANDS),
193205 chirp: ChirpState::new(n_q.max(1)),
194- noise: NoiseGen::new(seed),
206+ adj: AdjustState::new(),
207+ low_tail: vec![[Complex::ZERO; ANALYSIS_BANDS]; HF_ADJ],
208+ hf_tail: Vec::new(),
209+ y_carry: Vec::new(),
195210 }
196211 }
197212 }
@@ -209,6 +224,8 @@ struct Element {
209224 /// half length -- which otherwise permanently shifts every sample after
210225 /// it out of alignment with a reference that stayed at full rate.
211226 last_data: Option<SbrData>,
227+ /// Header of the previous applied frame: a change is the spec's reset.
228+ last_header: Option<crate::sbr_payload::SbrHeader>,
212229 }
213230
214231 /// Every configured SBR element in a stream, keyed by
@@ -240,6 +257,7 @@ impl SbrChain {
240257 parser: SbrParser::new(self.rate),
241258 channels: Vec::new(),
242259 last_data: None,
260+ last_header: None,
243261 });
244262 let data = elem.parser.parse(r, is_cpe).ok()?;
245263 let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1);
@@ -294,6 +312,8 @@ impl SbrChain {
294312 let Some(tables) = elem.parser.tables().cloned() else {
295313 return;
296314 };
315+ let reset = elem.last_header.as_ref() != elem.parser.header();
316+ elem.last_header = elem.parser.header().cloned();
297317 let Some(header) = elem.parser.header().cloned() else {
298318 return;
299319 };
@@ -411,7 +431,7 @@ impl SbrChain {
411431 if qmfdump_on {
412432 qmfdump_energies("analysis", 0, &low_cur);
413433 }
414- let mut hf = sbr_hf::generate(
434+ let hf = sbr_hf::generate(
415435 &low_cur,
416436 &tables,
417437 &sbr_ch.invf_mode,
@@ -430,25 +450,64 @@ impl SbrChain {
430450 t_noise: sbr_ch.t_noise.iter().map(|&t| t * RATE).collect(),
431451 ..sbr_ch.clone()
432452 };
433- // Same deterministic `build_patches(&tables)` call `generate`
434- // makes internally -- cheap to recompute here so the limiter
435- // band table (patch boundaries + f_low, Sec 4.6.18.7.2) can be
436- // built without threading patches out of `generate`'s signature.
437453 let limiter_table = sbr_hf::limiter_band_table(
438454 &tables,
439455 &sbr_hf::build_patches(&tables),
440456 header.limiter_bands,
441457 );
458+ // Envelope slot i is raw slot i - HF_ADJ: prepend the previous
459+ // frame's raw HF tail so the grid (up to 2*t_E(L_E) <= 38) lines
460+ // up with the content it was measured on (§4.6.18.7.6).
461+ let m_max = hf.len();
462+ if state.hf_tail.len() != m_max || reset {
463+ state.hf_tail = vec![vec![Complex::ZERO; HF_ADJ]; m_max];
464+ state.y_carry.clear();
465+ }
466+ let mut xh: Vec<Vec<Complex<f64>>> = (0..m_max)
467+ .map(|m| {
468+ let mut v = state.hf_tail[m].clone();
469+ v.extend_from_slice(&hf[m]);
470+ v
471+ })
472+ .collect();
473+ for m in 0..m_max {
474+ state.hf_tail[m] = hf[m][num_slots.saturating_sub(HF_ADJ)..].to_vec();
475+ }
442476 sbr_env::adjust(
443- &mut hf,
477+ &mut xh,
444478 &tables,
445479 &header,
446480 &scaled,
447481 &env_energy,
448482 &noise_energy,
449- &mut state.noise,
450483 &limiter_table,
484+ &mut state.adj,
485+ reset,
451486 );
487+ // Output slot i: low band from the delayed raw analysis, HF from
488+ // the previous frame's carried-over adjusted slots first, then
489+ // this frame's; slots past the frame end are carried forward.
490+ let i_temp = state.y_carry.first().map(Vec::len).unwrap_or(0).min(num_slots);
491+ let t_end = (scaled.t_env.last().copied().unwrap_or(0).max(0) as usize).min(xh[0].len());
492+ let mut hf: Vec<Vec<Complex<f64>>> = vec![vec![Complex::ZERO; num_slots]; m_max];
493+ for m in 0..m_max {
494+ for i in 0..i_temp {
495+ hf[m][i] = state.y_carry[m][i];
496+ }
497+ for i in i_temp..num_slots {
498+ hf[m][i] = xh[m][i];
499+ }
500+ }
501+ state.y_carry = (0..m_max)
502+ .map(|m| xh[m][num_slots.min(t_end)..t_end].to_vec())
503+ .collect();
504+ let raw: Vec<[Complex<f64>; ANALYSIS_BANDS]> = {
505+ let mut d = state.low_tail.clone();
506+ d.extend_from_slice(&raw);
507+ state.low_tail = d[d.len() - HF_ADJ..].to_vec();
508+ d.truncate(num_slots);
509+ d
510+ };
452511 if qmfdump_on {
453512 qmfdump_energies("post_adjust", tables.kx as usize, &hf);
454513 }
@@ -468,7 +527,10 @@ impl SbrChain {
468527 }
469528 let mut pcm = state.synthesis.process_slot(&v);
470529 for s in &mut pcm {
471- *s *= crate::decode::OUTPUT_SCALE;
530+ // The spec 32-analysis/64-synthesis pair (4.6.18.4.1 +
531+ // 4.6.18.8.2, literal equations) reads back at half the
532+ // core's amplitude; the 2x is the upsampler's gain.
533+ *s *= 2.0 * crate::decode::OUTPUT_SCALE;
472534 }
473535 out.extend_from_slice(&pcm);
474536 }
@@ -528,6 +590,8 @@ mod tests {
528590 add_harmonic: None,
529591 df_env: vec![],
530592 df_noise: vec![],
593+ l_a: -1,
594+ amp_res: 1,
531595 }
532596 }
533597
@@ -551,6 +615,7 @@ mod tests {
551615 parser: SbrParser::new(44100),
552616 channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)],
553617 last_data: None,
618+ last_header: None,
554619 },
555620 );
556621 chain
@@ -650,6 +715,7 @@ mod tests {
650715 .map(|i| ChannelState::new(n_q, 10 + i as u32))
651716 .collect(),
652717 last_data: None,
718+ last_header: None,
653719 },
654720 );
655721 chain
@@ -694,6 +760,7 @@ mod tests {
694760 parser: SbrParser::new(44100),
695761 channels: vec![ChannelState::new(n_q, 10)],
696762 last_data: None,
763+ last_header: None,
697764 },
698765 );
699766 reference
crates/ec-aac/src/sbr_env.rsmodified+432 -954
@@ -1,50 +1,23 @@
1-//! SBR envelope adjustment (ISO/IEC 14496-3 §4.6.18.7): scales the raw HF
2-//! QMF estimate [`crate::sbr_hf::generate`] produced so each transmitted
3-//! (envelope, band) cell carries the energy the encoder actually measured,
4-//! injects the transmitted noise floor, and adds sinusoids at the bands
5-//! `bs_add_harmonic` flags.
1+//! SBR envelope adjustment (ISO/IEC 14496-3 §4.6.18.7): dequantisation,
2+//! mapping, E_curr estimation, gain/limiter/boost calculation and HF
3+//! assembly, written formula-for-formula against §4.6.18.7.2-7.6.
64 //!
7-//! # Dequantization
5+//! Everything below `adjust` works per QMF subband `m = k - kx`
6+//! (`0..m_max`) and per QMF slot, as the spec does: envelope/noise data is
7+//! mapped onto subbands first (`E_origMapped`, `Q_mapped`, `S_mapped`,
8+//! `S_indexMapped`), gains are computed per subband, the limiter works on
9+//! subband sums per limiter band, and the smoothing filter runs over the
10+//! previous four QMF SLOTS' gain vectors (carried across frames).
811 //!
9-//! A plain (non-coupled) envelope's linear energy is `2^(alpha * e_q)`
10-//! with `alpha = 1.0` at `bs_amp_res = 1` (3 dB steps) and `0.5` at
11-//! `bs_amp_res = 0` (1.5 dB steps); the noise floor is `2^(6 - q_q)`
12-//! (`NOISE_FLOOR_OFFSET = 6`). A coupled CPE's balance channel (`e_q`'s
13-//! second channel) carries a log-ratio (`pan`) rather than an absolute
14-//! scalefactor; `dequant_pair` de-mixes it against channel 0's raw value
15-//! into `(env0, env1)` energies that are equal (and each equal to channel
16-//! 0's plain energy) when the ratio is centred (ISO/IEC 14496-3
17-//! §4.6.18.7.2): `ratio = 2^(pan - panOffset)`, `panOffset = 24` at
18-//! `bs_amp_res=0` and `12` at `bs_amp_res=1`, `env0 = 2*Ecurr/(1+ratio)`,
19-//! `env1 = 2*Ecurr*ratio/(1+ratio)`. A real coupled-CPE fixture
20-//! (`heaac_44100_48k.m4a`, `coupled_cpe_channel_swap_probe`) settled this:
21-//! its transmitted balance raw values cluster at 12 under `bs_amp_res=1`,
22-//! matching a centred pan at `panOffset=12` exactly, and only this
23-//! `ratio` shape (not the previous `2*alpha*raw - 12` exponent) plus
24-//! keeping `env0`/`env1` on their own physical channel (not swapped
25-//! into a `left`/`right` naming) reproduces the reference decoder's L/R
26-//! assignment on that file.
27-//!
28-//! # Gain, limiter, noise, sinusoids
29-//!
30-//! For every `(envelope, band)` cell this measures the HF estimate's own
31-//! average energy over that time/frequency window; the cell's envelope
32-//! target is split into a signal share and a noise share via the cell's
33-//! `Q_div = dequant_noise(q_q)` ratio (`signal = target/(1+Q_div)`,
34-//! `noise = target*Q_div/(1+Q_div)`, round-21 -- `Q_div` is a ratio
35-//! relative to the envelope target, not a standalone absolute energy), the
36-//! HF estimate is scaled toward the signal share; the limiter then caps
37-//! every cell's gain against its LIMITER BAND's aggregate headroom (Sec
38-//! 4.6.18.7.2/.7.5, `bs_limiter_gains`, `crate::sbr_hf::limiter_band_table`)
39-//! rather than each cell's own -- a content-empty cell has zero raw energy,
40-//! so a per-cell cap is infinite exactly where it should bite; the
41-//! aggregate cap and its gain-boost compensation (Sec 4.6.18.7.4) are
42-//! applied to gains, injected noise and sinusoids alike. The noise share is
43-//! mixed in at that level, and flagged bands get an added tone.
12+//! Slot indexing: `hf[m][i]` is `X_high(k, i + tHFAdj)`, i.e. slot `i` is the
13+//! one envelope border `2*t_E` counts -- the caller supplies a buffer long
14+//! enough for `2*t_E(L_E)` (up to 38 slots: 32 of this frame plus the
15+//! 6-slot overlap the variable frame classes may reach into).
4416 #![allow(clippy::needless_range_loop)]
4517
4618 use crate::sbr_bands::BandTables;
4719 use crate::sbr_payload::{SbrChannel, SbrHeader};
20+use crate::sbr_tables::SBR_NOISE;
4821 use ec_dsp::Complex;
4922
5023 const NOISE_FLOOR_OFFSET: f64 = 6.0;
@@ -57,55 +30,50 @@ fn alpha(amp_res: u8) -> f64 {
5730 if amp_res != 0 { 1.0 } else { 0.5 }
5831 }
5932
60-/// Plain (non-coupled) envelope dequantization.
33+/// Plain (non-coupled) envelope dequantization: `E_Orig = 2^(E_Q * a) * 64`
34+/// (§4.6.18.7.2), in the spec 32-band analysis domain `sbr_qmf::Analysis`
35+/// now produces directly.
6136 pub fn dequant_env(e_q: i32, amp_res: u8) -> f64 {
62- 2f64.powf(alpha(amp_res) * f64::from(e_q))
37+ 2f64.powf(alpha(amp_res) * f64::from(e_q)) * 64.0
6338 }
6439
65-/// Plain noise-floor dequantization: `Q_div = 2^(NOISE_FLOOR_OFFSET-q_q)`, a
66-/// ratio relative to the ENVELOPE energy of the same (time, band) cell, not
67-/// an absolute energy on its own (round-21: `adjust` splits each cell's
68-/// envelope target into `signal = target/(1+Q_div)` and
69-/// `noise = target*Q_div/(1+Q_div)`; using this return value as a
70-/// standalone absolute energy, as pre-round-21 code did, compares it
71-/// against `dequant_env`'s unrelated unit scale).
40+/// Plain noise-floor dequantization: `Q_Orig = 2^(NOISE_FLOOR_OFFSET - Q_Q)`,
41+/// a ratio against the same cell's envelope energy (§4.6.18.7.2).
7242 pub fn dequant_noise(q_q: i32) -> f64 {
7343 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q_q))
7444 }
7545
7646 /// De-mixes a coupled CPE's `(channel 0 raw, balance raw)` pair into
7747 /// `(env0, env1)` linear energies (ISO/IEC 14496-3 §4.6.18.7.2,
78-/// `bs_coupling`): `Ecurr = dequant_env(e0_raw, amp_res)`,
79-/// `ratio = 2^(pan - panOffset)` where `pan` is the RAW balance value
80-/// (channels[1]'s `e_q`, not run through `alpha`/`amp_res` scaling) and
81-/// `panOffset` is 24 at `bs_amp_res=0` (1.5 dB steps) or 12 at
82-/// `bs_amp_res=1` (3 dB steps); `env0 = 2*Ecurr/(1+ratio)`,
83-/// `env1 = 2*Ecurr*ratio/(1+ratio)`. The previous `2*alpha*raw - 12`
84-/// exponent (doubling the step at `amp_res=1` and using the wrong offset
85-/// at `amp_res=0`), combined with a `left`/`right` naming below that
86-/// handed physical channel 0 the `env1` shape and channel 1 the `env0`
87-/// shape, together produced a real-file coupled-CPE L/R swap
88-/// (`coupled_cpe_channel_swap_probe`, ch0 correlated 0.98 against the
89-/// REFERENCE's right channel, not its left). This stream's live balance
90-/// raw values cluster at 12 (`amp_res=1`), matching a centred pan at
91-/// `panOffset=12` exactly, confirming the offset direction empirically.
92-/// `env_amp_res` scales `e0_raw` (forced to 0/1.5 dB on a single-envelope
93-/// frame, mirroring `sbr_payload`'s own `amp_res_of`); `header_amp_res` is
94-/// the SBR header's transmitted `bs_amp_res` field UNCONDITIONALLY, which
95-/// governs `panOffset` regardless of the single-envelope override -- the
96-/// two diverge on single-envelope coupled frames.
97-pub fn dequant_pair(e0_raw: i32, pan_raw: i32, env_amp_res: u8, header_amp_res: u8) -> (f64, f64) {
98- let e_curr = dequant_env(e0_raw, env_amp_res);
99- let pan_offset = if header_amp_res != 0 { 12.0 } else { 24.0 };
100- let ratio = 2f64.powf(f64::from(pan_raw) - pan_offset);
101- let env0 = 2.0 * e_curr / (1.0 + ratio);
102- let env1 = 2.0 * e_curr * ratio / (1.0 + ratio);
103- (env0, env1)
48+/// `bs_coupling`): `E = 2^(a*e0_raw + 7)`, `r = 2^(a*(panOffset - 2*pan))`
49+/// with `a` = 1 (3 dB) or 0.5 (1.5 dB) and `panOffset` = 12 / 24 for the
50+/// FRAME's amp_res (the FIXFIX single-envelope override included);
51+/// `env0 = E/(1+r)`, `env1 = env0*r`. The balance channel's raw values
52+/// (and its Huffman deltas) count in DOUBLE steps -- `bs_data_env` is one
53+/// bit narrower than the level field -- so its centre is 6 (3 dB) / 12
54+/// (1.5 dB) in raw units; measured on a real coupled stream, where 88% of
55+/// the raw balance values sit exactly on that centre.
56+pub fn dequant_pair(e0_raw: i32, pan_raw: i32, amp_res: u8) -> (f64, f64) {
57+ let a = alpha(amp_res);
58+ let pan_offset = if amp_res != 0 { 12.0 } else { 24.0 };
59+ let ratio = 2f64.powf(a * (pan_offset - 2.0 * f64::from(pan_raw)));
60+ let env0 = 2.0 * dequant_env(e0_raw, amp_res) / (1.0 + ratio);
61+ (env0, env0 * ratio)
62+}
63+
64+/// Coupled noise-floor pair (§4.6.18.7.2): `Q0 = 2^(NOISE_FLOOR_OFFSET - q0 + 1)
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.
67+pub fn dequant_noise_pair(q0_raw: i32, pan_raw: i32) -> (f64, f64) {
68+ let temp1 = 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q0_raw) + 1.0);
69+ let temp2 = 2f64.powf(12.0 - 2.0 * f64::from(pan_raw));
70+ let q0 = temp1 / (1.0 + temp2);
71+ (q0, q0 * temp2)
10472 }
10573
10674 /// Dequantizes one channel's envelopes and noise floors for one frame,
107-/// de-mixing through [`dequant_pair`] when `coupling` makes `channels[1]`
108-/// a balance channel against `channels[0]`.
75+/// de-mixing through [`dequant_pair`]/[`dequant_noise_pair`] when
76+/// `coupling` makes `channels[1]` a balance channel against `channels[0]`.
10977 pub fn dequantize_frame(
11078 header: &SbrHeader,
11179 channels: &[SbrChannel],
@@ -113,191 +81,119 @@ pub fn dequantize_frame(
11381 coupling: bool,
11482 ) -> (Vec<Vec<f64>>, Vec<Vec<f64>>) {
11583 let c = &channels[ch];
116- // A single-envelope frame forces 1.5 dB resolution regardless of
117- // bs_amp_res, mirroring sbr_payload's own `amp_res_of`.
118- let amp_res = if c.e_q.len() == 1 { 0 } else { header.amp_res };
119- let mut env = Vec::with_capacity(c.e_q.len());
120- if coupling && channels.len() == 2 {
121- for i in 0..c.e_q.len() {
122- let row0 = channels[0].e_q.get(i);
123- let row1 = channels[1].e_q.get(i);
124- let len = c.e_q[i].len();
125- let mut r = Vec::with_capacity(len);
126- for b in 0..len {
127- let e0 = row0.and_then(|r| r.get(b)).copied().unwrap_or(0);
128- let pan = row1.and_then(|r| r.get(b)).copied().unwrap_or(0);
129- let (env0, env1) = dequant_pair(e0, pan, amp_res, header.amp_res);
130- r.push(if ch == 0 { env0 } else { env1 });
131- }
132- env.push(r);
133- }
84+ let amp_res = c.amp_res;
85+ let coupled = coupling && channels.len() == 2;
86+ let pick = |pair: (f64, f64)| if ch == 0 { pair.0 } else { pair.1 };
87+ let env = if coupled {
88+ (0..c.e_q.len())
89+ .map(|i| {
90+ (0..c.e_q[i].len())
91+ .map(|b| {
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);
94+ pick(dequant_pair(e0, pan, amp_res))
95+ })
96+ .collect()
97+ })
98+ .collect()
13499 } else {
135- for row in &c.e_q {
136- env.push(row.iter().map(|&v| dequant_env(v, amp_res)).collect());
137- }
138- }
139- // corner-cut: noise floors dequantize independently per channel
140- // regardless of coupling. A mirrored dequant_noise_pair() demix (see
141- // git history) was tried and measured ZERO effect on the real-file
142- // ch1 RMS blow-up (identical output to printed precision), so the
143- // energy dequantization below is the live suspect, not this; reverted
144- // rather than keeping an unverified formula with no measured benefit.
145- let noise = c
146- .q_q
147- .iter()
148- .map(|row| row.iter().map(|&v| dequant_noise(v)).collect())
149- .collect();
100+ c.e_q.iter().map(|row| row.iter().map(|&v| dequant_env(v, amp_res)).collect()).collect()
101+ };
102+ let noise = if coupled {
103+ (0..c.q_q.len())
104+ .map(|i| {
105+ (0..c.q_q[i].len())
106+ .map(|b| {
107+ let q0 = channels[0].q_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0);
108+ let pan = channels[1].q_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0);
109+ pick(dequant_noise_pair(q0, pan))
110+ })
111+ .collect()
112+ })
113+ .collect()
114+ } else {
115+ c.q_q.iter().map(|row| row.iter().map(|&v| dequant_noise(v)).collect()).collect()
116+ };
150117 (env, noise)
151118 }
152119
153-/// A small deterministic PRNG for the injected noise floor -- the same
154-/// generator shape `decode::Noise` uses, kept local so this module has no
155-/// dependency on the core decoder's internals.
156-pub struct NoiseGen {
157- lcg: u32,
158- // (Round-44, Task 1/2) The last `LOWPASS_TAPS - 1` raw (pre-scale) draws,
159- // oldest first -- `complex_unit` boxcar-averages the current draw against
160- // these before scaling, so consecutive calls (one QMF slot apart, same
161- // band -- see `adjust`'s band-outer/slot-inner loop) are correlated
162- // instead of independent.
163- history: std::collections::VecDeque<Complex<f64>>,
120+/// Limiter gain ceilings, `bs_limiter_gains` 0..3 (§4.6.18.7.5, Table 4.150):
121+/// -3 dB, 0 dB, +3 dB, off.
122+const LIMITER_FACTOR: [f64; 4] = [0.70795, 1.0, 1.41254, 1.0e10];
123+const GAIN_MAX_CLIP: f64 = 1.0e5;
124+const BOOST_MAX: f64 = 1.584_893_192;
125+const H_SMOOTH: [f64; 5] = [
126+ 0.333_333_333_333_33,
127+ 0.301_502_832_395_82,
128+ 0.218_169_499_062_49,
129+ 0.115_163_834_270_84,
130+ 0.031_830_500_937_51,
131+];
132+const H_SL: usize = 4;
133+const EPS: f64 = 1.192_092_9e-7;
134+
135+/// Per-channel adjuster state carried across frames (§4.6.18.7.6's
136+/// `G_Temp`/`Q_Temp` slot history, `f_IndexNoise`, `f_IndexSine`, the
137+/// previous frame's `S_indexMapped` and its `l_A`).
138+#[derive(Clone, Debug)]
139+pub struct AdjustState {
140+ s_index_prev: Vec<u8>,
141+ /// Gain/noise vectors of the last `H_SL` slots, oldest first.
142+ g_hist: std::collections::VecDeque<Vec<f64>>,
143+ q_hist: std::collections::VecDeque<Vec<f64>>,
144+ index_noise: usize,
145+ index_sine: usize,
146+ /// Previous frame's `l_A == L_E` (the transient envelope continues into
147+ /// this frame's envelope 0 -- `l_Aprev`).
148+ la_prev_at_end: bool,
149+ pub fresh: bool,
164150 }
165151
166-/// (Round-44, Task 1) `sbr_qmf::Synthesis`'s prototype passband is HALF the
167-/// decimated slot-rate Nyquist a per-slot i.i.d. draw spans (see
168-/// `sbr_qmf.rs`'s module doc and `synthesis_energy_gain_for_...` harness):
169-/// an unfiltered draw already survives Synthesis' overlap-add reasonably
170-/// (in-band fraction ~0.49 of a 20000-slot excitation, once the harness's own
171-/// band-index math was corrected -- see round-44 ledger), but a short boxcar
172-/// across consecutive slots pulls more of that draw's own spectral energy
173-/// into the passband without collapsing it into a near-tone (a wider boxcar
174-/// keeps raising in-band fraction but concentrates it into the passband's
175-/// own DC edge, losing the noise-like spread across the band the acceptance
176-/// bar requires -- taps=2 was the harness's best fraction/spread balance:
177-/// 0.6083 in-band, quarter-bin energy spread [0.257,0.293,0.251,0.199]).
178-const LOWPASS_TAPS: usize = 2;
179-
180-impl NoiseGen {
181- pub fn new(seed: u32) -> NoiseGen {
182- NoiseGen {
183- lcg: seed | 1,
184- history: std::collections::VecDeque::with_capacity(LOWPASS_TAPS),
152+impl AdjustState {
153+ pub fn new() -> AdjustState {
154+ AdjustState {
155+ s_index_prev: Vec::new(),
156+ g_hist: std::collections::VecDeque::new(),
157+ q_hist: std::collections::VecDeque::new(),
158+ index_noise: 0,
159+ index_sine: 0,
160+ la_prev_at_end: false,
161+ fresh: true,
185162 }
186163 }
164+}
187165
188- fn next(&mut self) -> f64 {
189- self.lcg = self.lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
190- // (Round-41, Task 2) `self.0 >> 8` keeps 24 bits (range [0, 2^24));
191- // dividing by `1u32 << 23` (2^23, ONE bit too few) left a range of
192- // [0, 2) before the `- 0.5`, i.e. actual output was uniform on
193- // [-0.5, 1.5) with mean +0.5 -- a DC-biased "noise" source, not
194- // zero-mean. `decode::Noise::next` (same LCG constants) divides by
195- // the same `1 << 23` but subtracts `1.0`, which correctly centers
196- // ITS doubled [0,2) range; this generator subtracted the wrong
197- // constant for its own divisor. Dividing by `1u32 << 24` instead
198- // fixes the range to [0, 1) so `- 0.5` correctly centers it on
199- // [-0.5, 0.5), mean 0.
200- f64::from(self.lcg >> 8) / f64::from(1u32 << 24) - 0.5
201- }
202-
203- fn complex_unit(&mut self) -> Complex<f64> {
204- // (Round-41, Task 2) `next()` is uniform on [-0.5, 0.5) (Var = 1/12
205- // per component), so a raw `(re, im)` pair has E[|z|^2] = 1/6, not
206- // 1 -- `adjust` scales this by `namp = sqrt(noise_here)` (round-42:
207- // no `/width`, `noise_here` is already a per-sample average)
208- // expecting E[|namp*z|^2] = noise_here, so without this correction
209- // only ~1/6 of the transmitted noise split was ever actually
210- // realized in the output. Measured directly (decode reeln twice,
211- // noise on vs `EC_AAC_SBR_NOISE_ZERO`, per-band output energy delta
212- // in `tests/sbr_real_library.rs`'s `sbr_actual_noise_fraction`):
213- // bookkept split ~0.37-0.39, actual realized only ~0.10-0.30 in-band
214- // (whole-HF-weighted ~0.095) before this fix.
215- //
216- // (Round-44, Task 2) The raw i.i.d. draw is boxcar-averaged over the
217- // last `LOWPASS_TAPS` calls (see the constant's own doc) before this
218- // scale: a boxcar of `taps` independent Uniform(-0.5,0.5) draws has
219- // per-component variance `(1/12)/taps`, `taps`-fold smaller than a
220- // single draw's, so the unit-energy scale grows by `sqrt(taps)` on
221- // top of the original `sqrt(6)` to still land at E[|z|^2] = 1 -- this
222- // is a SHAPE change (which spectral slice of the subband's own
223- // baseband the energy sits in), not an energy change; the boxcar's
224- // first `taps - 1` calls average fewer draws than nominal (history
225- // still filling), a startup transient too short to matter against a
226- // whole envelope segment's slot count.
227- const UNIT_SCALE: f64 = 2.449_489_742_783_178; // sqrt(6)
228- let lowpass_scale: f64 = UNIT_SCALE * (LOWPASS_TAPS as f64).sqrt();
229- let raw = Complex::new(self.next(), self.next());
230- self.history.push_back(raw);
231- if self.history.len() > LOWPASS_TAPS {
232- self.history.pop_front();
233- }
234- let n = self.history.len() as f64;
235- let sum = self
236- .history
237- .iter()
238- .fold(Complex::new(0.0, 0.0), |a, &b| a + b);
239- sum.scale(lowpass_scale / n)
166+impl Default for AdjustState {
167+ fn default() -> Self {
168+ Self::new()
240169 }
241170 }
242171
243-// (Round-33) Per-limiter-band aggregate gain factor, ISO/IEC 14496-3
244-// §4.6.18.7.2's `bs_limiter_gains` table: -3/0/+3 dB, and index 3
245-// ("no limiting") given a very large but finite ceiling so a limiter band
246-// with zero measured HF energy still can't blow up to a literal infinity.
247-const LIMITER_FACTOR: [f64; 4] = [0.707_945_78, 1.0, 1.412_537_5, 1.0e10];
248-
249-/// Gain-boost compensation ceiling (+4 dB, §4.6.18.7.4): after the
250-/// per-limiter-band cap, a band whose achieved energy fell short of its
251-/// transmitted envelope total is boosted back up, capped here so a band
252-/// that was capped hard doesn't get fully "un-capped" by the boost step.
253-const BOOST_MAX: f64 = 1.584_893_2;
254-
255-/// (Round-17, Task 1 conviction check) Accumulates transmitted signal vs.
256-/// noise energy per absolute QMF band across every [`adjust`] call in the
257-/// process, weighted by how many QMF slots each contributes, when
258-/// `EC_AAC_SBR_NOISE_FRACTION_DEBUG` is set. [`noise_fraction_table`] reads
259-/// it back; both are no-ops (empty table) otherwise, so this costs nothing
260-/// on the normal path.
261-static NOISE_FRACTION_STATS: std::sync::OnceLock<std::sync::Mutex<Vec<(f64, f64)>>> =
262- std::sync::OnceLock::new();
263-
264172 fn noise_fraction_debug() -> bool {
265- std::env::var("EC_AAC_SBR_NOISE_FRACTION_DEBUG").is_ok()
173+ std::env::var("EC_AAC_SBR_NOISE_FRACTION").is_ok()
266174 }
267175
268-/// `(band, signal_energy_sum, noise_energy_sum)` for every band that
269-/// accumulated anything, both sums slot-count-weighted.
270-pub fn noise_fraction_table() -> Vec<(usize, f64, f64)> {
271- let Some(stats) = NOISE_FRACTION_STATS.get() else {
272- return Vec::new();
273- };
274- stats
275- .lock()
276- .unwrap()
277- .iter()
278- .enumerate()
279- .filter(|&(_, &(s, n))| s + n > 0.0)
280- .map(|(b, &(s, n))| (b, s, n))
281- .collect()
282-}
176+static NOISE_FRACTION: std::sync::OnceLock<std::sync::Mutex<Vec<(usize, f64, f64, f64)>>> =
177+ std::sync::OnceLock::new();
283178
284-fn accumulate_noise_fraction(band: usize, slots: usize, signal: f64, noise: f64) {
285- if slots == 0 {
286- return;
287- }
288- let stats = NOISE_FRACTION_STATS.get_or_init(|| std::sync::Mutex::new(vec![(0.0, 0.0); 256]));
289- let mut g = stats.lock().unwrap();
290- if band >= g.len() {
291- g.resize(band + 1, (0.0, 0.0));
292- }
293- g[band].0 += signal * slots as f64;
294- g[band].1 += noise * slots as f64;
179+/// Diagnostic (`EC_AAC_SBR_NOISE_FRACTION`): per absolute QMF band,
180+/// bookkept `(band, Σ signal energy·slots, Σ noise energy·slots, Σ |Y|²
181+/// post-adjust)` -- the last column against the first two's sum is the
182+/// per-subband realised/target energy ratio.
183+pub fn noise_fraction_table() -> Vec<(usize, f64, f64, f64)> {
184+ let mut out: Vec<(usize, f64, f64, f64)> = NOISE_FRACTION
185+ .get()
186+ .and_then(|m| m.lock().ok())
187+ .map(|g| g.clone())
188+ .unwrap_or_default();
189+ out.sort_by_key(|e| e.0);
190+ out
295191 }
296192
297-/// Applies envelope adjustment in place to `hf` (`[target band 0-based
298-/// from kx][slot]`, as [`crate::sbr_hf::generate`] returns it): gain
299-/// toward `env_energy`, the transmitted noise floor from `noise_energy`,
300-/// and sinusoids at `ch.add_harmonic`'s flagged high-resolution bands.
193+/// Adjusts `hf` (`[m][slot]`, `m = k - kx`) in place: envelope gains,
194+/// noise floor and added sinusoids per §4.6.18.7.3-7.6. `ch.t_env`/`t_noise`
195+/// are in QMF slots (already ×2). `reset` mirrors the spec's header-reset
196+/// flag (smoothing history primed from the first envelope, indices zeroed).
301197 #[allow(clippy::too_many_arguments)]
302198 pub fn adjust(
303199 hf: &mut [Vec<Complex<f64>>],
@@ -306,549 +202,277 @@ pub fn adjust(
306202 ch: &SbrChannel,
307203 env_energy: &[Vec<f64>],
308204 noise_energy: &[Vec<f64>],
309- rng: &mut NoiseGen,
310205 limiter_table: &[i64],
206+ state: &mut AdjustState,
207+ reset: bool,
311208 ) {
312209 let kx = tables.kx as usize;
313- let n_lim = limiter_table.len().saturating_sub(1).max(1);
314- // (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_LIMITER_OFF`
315- // forces the "no limit" factor regardless of the transmitted
316- // `bs_limiter_gains`, to probe whether the limiter itself is clipping
317- // correlation on real content.
210+ let m_max = hf.len();
211+ let num_env = ch.t_env.len().saturating_sub(1).min(env_energy.len());
212+ if m_max == 0 || num_env == 0 {
213+ return;
214+ }
215+ let reset = reset || state.fresh || state.s_index_prev.len() != m_max;
216+ state.fresh = false;
217+ if reset {
218+ state.s_index_prev = vec![0; m_max];
219+ state.index_noise = 0;
220+ state.index_sine = 0;
221+ state.g_hist.clear();
222+ state.q_hist.clear();
223+ }
318224 let limiter_max = if std::env::var("EC_AAC_SBR_LIMITER_OFF").is_ok() {
319225 LIMITER_FACTOR[3]
320226 } else {
321227 LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]
322228 };
323- let track_fraction = noise_fraction_debug();
324- // (Round-17, Task 1 corroboration) zeroes our injected noise so the
325- // sweep's measured correlation can be checked against the
326- // signal-only ceiling `noise_fraction_table` predicts, without
327- // touching the transmitted noise ENERGY bookkeeping above (only the
328- // actual PCM addition is skipped).
329229 let zero_noise = std::env::var("EC_AAC_SBR_NOISE_ZERO").is_ok();
330- // (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_GAIN_LERP`
331- // linearly interpolates each envelope's per-band gain toward the NEXT
332- // envelope's gain across the current envelope's time slots, instead of
333- // holding it flat -- probing whether our constant-per-cell gain shape
334- // (vs. the spec's smoother per-slot shape) is a live suspect.
335- let gain_lerp = std::env::var("EC_AAC_SBR_GAIN_LERP").is_ok();
336- // (Round-43, Task 1) `EC_AAC_SBR_CELLDUMP=band[,band...]` -- comma list
337- // of ABSOLUTE QMF band indices (same units as `kx`/`k2`/`f_high`,
338- // `band_hz = rate/128`, per round-42's fixed test-side mapping) -- dumps
339- // every (envelope, band) cell whose `[lo,hi)` range covers a listed
340- // band: target/signal_target/noise_here/measured cur/raw+capped gain/
341- // boost/namp/sinusoid amp, and the actually-injected noise energy that
342- // frame, to stderr.
343- let celldump: Vec<usize> = std::env::var("EC_AAC_SBR_CELLDUMP")
344- .ok()
345- .map(|s| s.split(',').filter_map(|t| t.trim().parse().ok()).collect())
346- .unwrap_or_default();
347-
348- // Gain toward the transmitted envelope, per (envelope, band) cell,
349- // limited relative to that cell's own noise floor.
350- for (ei, (t0, t1)) in ch.t_env.windows(2).map(|w| (w[0], w[1])).enumerate() {
351- if ei >= env_energy.len() {
352- break;
353- }
354- let high_res = ch.freq_res.get(ei).copied().unwrap_or(0) != 0;
355- let table = if high_res {
356- &tables.f_high
357- } else {
358- &tables.f_low
359- };
360- // The noise segment covering this envelope's time range (noise
361- // borders are a coarser subset of the envelope borders sharing the
362- // same start/end points).
363- let noise_row: Option<&Vec<f64>> = ch
364- .t_noise
365- .windows(2)
366- .position(|w| t0 >= w[0] && t0 < w[1])
367- .and_then(|ni| noise_energy.get(ni));
368- // Per-sfb gain, computed first and applied afterward (as either a
369- // flat step per band, or -- Sec 4.6.18.7.6, `bs_interpol_freq` --
370- // linearly interpolated across subbands between sfb centre
371- // frequencies) so both application modes share the exact same gain
372- // values.
373- //
374- // (Round-33) The limiter no longer caps each cell against its OWN
375- // near-zero raw HF estimate (that cap is infinite exactly where a
376- // patch left a target band content-empty, Sec 4.6.18.7.5's known
377- // failure mode for cell-local caps). Instead this is a two-pass
378- // per-LIMITER-BAND aggregate: pass 1 computes each cell's raw
379- // (uncapped) gain and accumulates that cell's transmitted/measured
380- // energy into its limiter band (`limiter_table`, built from
381- // f_low/patch borders in sbr_hf::limiter_band_table); pass 2 caps
382- // every cell in a limiter band at that band's AGGREGATE
383- // `sqrt(E_orig/E_curr)*limgain` ratio, so an empty cell inherits its
384- // band's cap rather than blowing up alone, then boosts the whole
385- // band back up (capped at `BOOST_MAX`) to still meet the band's
386- // transmitted total.
387- let mut gains = Vec::with_capacity(table.len().saturating_sub(1));
388- // (Round-21) Actual per-cell noise energy this envelope/band injects,
389- // parallel to `gains` -- filled below and consumed by the
390- // application loop that follows instead of the old separate
391- // noise-grid pass (see round-21 module doc note).
392- let mut noise_amps = Vec::with_capacity(table.len().saturating_sub(1));
393- let mut cell_current = Vec::with_capacity(table.len().saturating_sub(1));
394- let mut cell_noise_here = Vec::with_capacity(table.len().saturating_sub(1));
395- let mut cell_lim = Vec::with_capacity(table.len().saturating_sub(1));
396- let mut lim_e_orig = vec![0.0f64; n_lim];
397- let mut lim_e_curr = vec![0.0f64; n_lim];
398- for b in 0..table.len().saturating_sub(1) {
399- let lo = table[b] as usize;
400- let hi = table[b + 1] as usize;
401- let target = env_energy[ei].get(b).copied().unwrap_or(0.0);
402- let (mut sum, mut count) = (0.0f64, 0usize);
403- for band in lo..hi {
404- if band < kx || band - kx >= hf.len() {
405- continue;
406- }
407- let row = &hf[band - kx];
408- for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) {
409- sum += row[slot].norm_sqr();
410- count += 1;
230+ let limdump = std::env::var("EC_AAC_SBR_CELLDUMP").is_ok();
231+ let track_fraction = noise_fraction_debug();
232+ let h_sl = if header.smoothing_mode == 0 { H_SL } else { 0 };
233+ let l_a = ch.l_a;
234+ let l_a_prev: i64 = if state.la_prev_at_end { 0 } else { -1 };
235+ let n_lim = limiter_table.len().saturating_sub(1);
236+
237+ // §4.6.18.7.2 mapping + §4.6.18.7.3 E_curr + §4.6.18.7.5 gains, per env.
238+ let mut gain = vec![vec![0.0f64; m_max]; num_env];
239+ let mut q_m = vec![vec![0.0f64; m_max]; num_env];
240+ let mut s_m = vec![vec![0.0f64; m_max]; num_env];
241+ let mut s_index_prev = state.s_index_prev.clone();
242+ for e in 0..num_env {
243+ let (t0, t1) = (ch.t_env[e].max(0) as usize, ch.t_env[e + 1].max(0) as usize);
244+ let high_res = ch.freq_res.get(e).copied().unwrap_or(0) != 0;
245+ let table: &[i64] = if high_res { &tables.f_high } else { &tables.f_low };
246+ let n_bands = table.len().saturating_sub(1);
247+ // E_origMapped
248+ let mut e_orig = vec![0.0f64; m_max];
249+ for i in 0..n_bands {
250+ let v = env_energy[e].get(i).copied().unwrap_or(0.0);
251+ for k in table[i]..table[i + 1] {
252+ let m = k as usize - kx.min(k as usize);
253+ if k as usize >= kx && m < m_max {
254+ e_orig[m] = v;
411255 }
412256 }
413- let current = if count > 0 { sum / count as f64 } else { 0.0 };
414- let q = noise_band_for(tables, lo);
415- // `dequant_noise` returns `Q_div = 2^(NOISE_FLOOR_OFFSET-q_q)`, a
416- // ratio relative to this cell's OWN envelope target -- not an
417- // absolute energy in the same units as `target` (round-21 Task
418- // 1/2: a reference-decoder q_q sweep at a FIXED envelope target
419- // showed total output power staying nearly flat as q_q swept its
420- // whole range, the signature of `target` being split
421- // `signal=target/(1+Q_div)`, `noise=target*Q_div/(1+Q_div)`
422- // rather than noise being added independently on top of the full
423- // target -- the previous code used `dequant_noise` as an
424- // absolute energy standalone, which for real content's near-1e-7
425- // apparent "fraction" (round-17) was actually comparing two
426- // energies in unrelated unit scales, not a genuinely near-zero
427- // noise contribution).
428- let noise_div = noise_row
429- .and_then(|r| r.get(q).copied())
430- .unwrap_or(0.0)
431- .max(0.0);
432- let signal_target = target / (1.0 + noise_div);
433- let noise_here = target - signal_target; // = target*noise_div/(1+noise_div)
434- let cur = current.max(1e-12);
435- let raw_gain = (signal_target / cur).sqrt();
436- let lim_idx = limiter_band_index(limiter_table, lo, hi).min(n_lim - 1);
437- let width = (hi - lo).max(1) as f64;
438- // (Round-42, Task 1) `lim_e_orig` conserves the cell's FULL
439- // transmitted `target` (signal+noise), matching the limiter cap
440- // and boost pass to the TOTAL energy budget rather than the
441- // signal share alone -- `lim_e_actual` below is widened to
442- // match (adds `cell_noise_here` alongside the capped signal
443- // energy) so the boost's `lim_e_orig/lim_e_actual` ratio
444- // compares total-to-total. Measured signal-target-only variant
445- // (both sides restricted to `signal_target`) FIRST and it made
446- // the realized noise fraction anchor WORSE (0.1325 -> 0.1233
447- // whole-HF, moving further from the ~0.38 bookkept split) --
448- // this total-conserving variant is the one that holds.
449- lim_e_orig[lim_idx] += target * width;
450- lim_e_curr[lim_idx] += cur * width;
451- cell_current.push(cur);
452- cell_noise_here.push(noise_here);
453- cell_lim.push(lim_idx);
454- gains.push(raw_gain);
455- if track_fraction {
456- let slots = (t1.max(0) - t0.max(0)).max(0) as usize;
457- for band in lo..hi {
458- if band < kx {
459- continue;
257+ }
258+ // Q_mapped: noise floor covering this envelope's start.
259+ let nf = usize::from(ch.t_noise.len() > 2 && ch.t_env[e] >= ch.t_noise[1]);
260+ let mut q_mapped = vec![0.0f64; m_max];
261+ if let Some(row) = noise_energy.get(nf.min(noise_energy.len().saturating_sub(1))) {
262+ for i in 0..tables.n_q.min(tables.f_noise.len().saturating_sub(1)) {
263+ let v = row.get(i).copied().unwrap_or(0.0);
264+ for k in tables.f_noise[i]..tables.f_noise[i + 1] {
265+ if k as usize >= kx && (k as usize - kx) < m_max {
266+ q_mapped[k as usize - kx] = v;
460267 }
461- accumulate_noise_fraction(band, slots, signal_target, noise_here);
462268 }
463269 }
464270 }
465- // (Round-43, Task 1) `raw_gain` (pre-cap) is about to be overwritten
466- // in place inside `gains` below; keep an uncapped copy for the
467- // celldump so its "cap applied?" column can compare against it.
468- let raw_gains: Vec<f64> = if celldump.is_empty() {
469- Vec::new()
271+ // S_indexMapped (centre subband of each flagged high-res band, from
272+ // l_A on, or carried over from the previous frame) and S_mapped.
273+ let mut s_index = vec![0u8; m_max];
274+ if let Some(flags) = &ch.add_harmonic {
275+ for i in 0..tables.f_high.len().saturating_sub(1) {
276+ let mid = ((tables.f_high[i] + tables.f_high[i + 1]) >> 1) as usize;
277+ if mid < kx || mid - kx >= m_max {
278+ continue;
279+ }
280+ let on = flags.get(i).copied().unwrap_or(0) != 0;
281+ s_index[mid - kx] =
282+ u8::from(on && ((e as i64) >= l_a || s_index_prev[mid - kx] == 1));
283+ }
284+ }
285+ let mut s_mapped = vec![false; m_max];
286+ for i in 0..n_bands {
287+ let lo = (table[i] as usize).max(kx) - kx;
288+ let hi = ((table[i + 1] as usize).max(kx) - kx).min(m_max);
289+ let any = (lo..hi).any(|m| s_index[m] != 0);
290+ for m in lo..hi {
291+ s_mapped[m] = any;
292+ }
293+ }
294+ s_index_prev = s_index.clone();
295+ // E_curr (§4.6.18.7.3), bs_interpol_freq 1 per subband / 0 per band.
296+ let mut e_curr = vec![0.0f64; m_max];
297+ let slots = (t1.saturating_sub(t0)).max(1) as f64;
298+ if header.interpol_freq != 0 {
299+ for m in 0..m_max {
300+ let row = &hf[m];
301+ let sum: f64 =
302+ (t0..t1.min(row.len())).map(|i| row[i].norm_sqr()).sum();
303+ e_curr[m] = sum / slots;
304+ }
470305 } else {
471- gains.clone()
472- };
473- // Pass 2: per-limiter-band aggregate cap, then per-band boost
474- // compensation so the band still meets its transmitted total.
475- let lim_cap: Vec<f64> = (0..n_lim)
476- .map(|j| limiter_max * (lim_e_orig[j] / lim_e_curr[j].max(1e-12)).sqrt())
477- .collect();
478- let mut lim_e_actual = vec![0.0f64; n_lim];
479- let mut lim_capped_count = vec![0usize; n_lim];
480- let mut lim_total_count = vec![0usize; n_lim];
481- for b in 0..gains.len() {
482- let j = cell_lim[b];
483- lim_total_count[j] += 1;
484- if gains[b] > lim_cap[j] + 1e-12 {
485- lim_capped_count[j] += 1;
306+ for i in 0..n_bands {
307+ let lo = (table[i] as usize).max(kx) - kx;
308+ let hi = ((table[i + 1] as usize).max(kx) - kx).min(m_max);
309+ let mut sum = 0.0;
310+ for m in lo..hi {
311+ let row = &hf[m];
312+ sum += (t0..t1.min(row.len())).map(|i| row[i].norm_sqr()).sum::<f64>();
313+ }
314+ let v = sum / (slots * (hi.saturating_sub(lo)).max(1) as f64);
315+ for m in lo..hi {
316+ e_curr[m] = v;
317+ }
486318 }
487- gains[b] = gains[b].min(lim_cap[j]);
488- let lo = table[b] as usize;
489- let hi = table[b + 1] as usize;
490- let width = (hi - lo).max(1) as f64;
491- // Total realized energy this cell will carry: the capped
492- // signal gain applied to the raw HF estimate, PLUS the noise
493- // share `target` already budgeted for this cell (noise is
494- // injected independently of `gains`, at `noise_amps` below) --
495- // matches `lim_e_orig`'s total-target accounting above.
496- lim_e_actual[j] +=
497- cell_current[b] * gains[b] * gains[b] * width + cell_noise_here[b] * width;
498319 }
499- let lim_boost: Vec<f64> = (0..n_lim)
500- .map(|j| {
501- if lim_e_actual[j] > 1e-12 {
502- (lim_e_orig[j] / lim_e_actual[j])
503- .sqrt()
504- .clamp(1.0, BOOST_MAX)
320+ // Gains, limiter and boost (§4.6.18.7.5), per limiter band.
321+ let delta = !((e as i64) == l_a || (e as i64) == l_a_prev);
322+ let deltaf = if delta { 1.0 } else { 0.0 };
323+ for j in 0..n_lim {
324+ let lo = (limiter_table[j] as usize).max(kx) - kx;
325+ let hi = ((limiter_table[j + 1] as usize).max(kx) - kx).min(m_max);
326+ if lo >= hi {
327+ continue;
328+ }
329+ for m in lo..hi {
330+ let temp = e_orig[m] / (1.0 + q_mapped[m]);
331+ q_m[e][m] = (temp * q_mapped[m]).sqrt();
332+ s_m[e][m] = (temp * f64::from(s_index[m])).sqrt();
333+ gain[e][m] = if !s_mapped[m] {
334+ (e_orig[m] / ((1.0 + e_curr[m]) * (1.0 + q_mapped[m] * deltaf))).sqrt()
505335 } else {
506- 1.0
336+ (e_orig[m] * q_mapped[m] / ((1.0 + e_curr[m]) * (1.0 + q_mapped[m]))).sqrt()
337+ } + f64::MIN_POSITIVE;
338+ }
339+ let sum_orig: f64 = (lo..hi).map(|m| e_orig[m]).sum();
340+ let sum_curr: f64 = (lo..hi).map(|m| e_curr[m]).sum();
341+ let g_max = (limiter_max * ((EPS + sum_orig) / (EPS + sum_curr)).sqrt()).min(GAIN_MAX_CLIP);
342+ let mut capped = 0usize;
343+ for m in lo..hi {
344+ let q_max = q_m[e][m] * g_max / gain[e][m];
345+ q_m[e][m] = q_m[e][m].min(q_max);
346+ if gain[e][m] > g_max {
347+ capped += 1;
507348 }
508- })
509- .collect();
510- // (Round-57 audit, ISO/IEC 14496-3 4.6.18.7.5/.7.6) Per-limiter-band
511- // aggregate dump under `EC_AAC_SBR_CELLDUMP`: the exact quantities
512- // the spec's two equations operate on (E_orig,mapped/E_curr sums,
513- // G_max=limGain*sqrt(ratio), capped-cell count, G_boost), one line
514- // per limiter band per envelope, so the aggregate math can be
515- // checked directly rather than inferred from individual cells.
516- if !celldump.is_empty() {
517- for j in 0..n_lim {
349+ gain[e][m] = gain[e][m].min(g_max);
350+ }
351+ let sum_act: f64 = (lo..hi)
352+ .map(|m| {
353+ e_curr[m] * gain[e][m] * gain[e][m]
354+ + s_m[e][m] * s_m[e][m]
355+ + if delta && s_m[e][m] == 0.0 { q_m[e][m] * q_m[e][m] } else { 0.0 }
356+ })
357+ .sum();
358+ let boost = ((EPS + sum_orig) / (EPS + sum_act)).sqrt().min(BOOST_MAX);
359+ for m in lo..hi {
360+ gain[e][m] *= boost;
361+ q_m[e][m] *= boost;
362+ s_m[e][m] *= boost;
363+ }
364+ if limdump {
518365 eprintln!(
519- "LIMDUMP ei={ei} band=[{},{}) limiter_bands={} j={j}/{n_lim} \
520- E_orig_mapped={:.6e} E_curr={:.6e} G_max={:.6} capped_cells={}/{} \
521- E_actual={:.6e} G_boost={:.6}",
522- limiter_table.get(j).copied().unwrap_or(-1),
523- limiter_table.get(j + 1).copied().unwrap_or(-1),
366+ "LIMDUMP ei={e} band=[{},{}) limiter_bands={} j={j}/{n_lim} \
367+ E_orig_mapped={sum_orig:.6e} E_curr={sum_curr:.6e} G_max={g_max:.6} \
368+ capped_cells={capped}/{} E_actual={sum_act:.6e} G_boost={boost:.6}",
369+ limiter_table[j],
370+ limiter_table[j + 1],
524371 header.limiter_bands,
525- lim_e_orig[j],
526- lim_e_curr[j],
527- lim_cap[j],
528- lim_capped_count[j],
529- lim_total_count[j],
530- lim_e_actual[j],
531- lim_boost[j],
372+ hi - lo,
532373 );
533374 }
534375 }
535- for b in 0..gains.len() {
536- let j = cell_lim[b];
537- gains[b] *= lim_boost[j];
538- // (Round-42, Task 1 corollary) `cell_noise_here[b]` is already a
539- // PER-SAMPLE average energy (same units as `target`/`current` --
540- // see `raw_gain = sqrt(signal_target / cur)` just above, which
541- // treats both sides as per-sample averages without any width
542- // normalization). Dividing by the cell's QMF-band width here
543- // (as the pre-round-42 code did) additionally shrank the
544- // per-sample injected noise variance by `1/width`, on top of
545- // whatever the sample count already contributes when this same
546- // amplitude is applied once per (band, slot) below -- worse at
547- // wider high-frequency sfb cells, matching the measured
548- // realized-noise-fraction shortfall growing toward the top of
549- // the band in `EC_AAC_SBR_NOISE_ANCHOR`.
550- noise_amps.push(cell_noise_here[b].sqrt() * lim_boost[j]);
551- }
552- // (Round-43, Task 1) per-cell diagnostic dump for `EC_AAC_SBR_CELLDUMP`
553- // -- printed before the application loop below so it reflects the
554- // gain/noise-amplitude values that loop is about to use; the
555- // actually-injected sample energy (which depends on the RNG draws
556- // that loop consumes) is measured separately and printed right
557- // after it, tagged with the same `ei`/band range so the two lines
558- // pair up by eye.
559- if !celldump.is_empty() {
560- for b in 0..table.len().saturating_sub(1) {
561- let lo = table[b] as usize;
562- let hi = table[b + 1] as usize;
563- if !celldump.iter().any(|&cb| cb >= lo && cb < hi) {
564- continue;
565- }
566- let target = env_energy[ei].get(b).copied().unwrap_or(0.0);
567- let noise_here = cell_noise_here[b];
568- let signal_target = target - noise_here;
569- let cur = cell_current[b];
570- let raw_gain = raw_gains[b];
571- let lim_idx = cell_lim[b];
572- let capped = raw_gain > lim_cap[lim_idx] + 1e-12;
573- let boost = lim_boost[lim_idx];
574- let namp = noise_amps[b];
575- // Harmonic flag/amp for any listed band this cell covers
576- // (checked against the high-res `f_high` grid the sinusoid
577- // block below uses, regardless of this cell's own
578- // resolution).
579- let mut harmonic = None;
580- if let Some(flags) = &ch.add_harmonic {
581- for (hb, &on) in flags.iter().enumerate() {
582- if on == 0 || hb + 1 >= tables.f_high.len() {
583- continue;
584- }
585- let hlo = tables.f_high[hb] as usize;
586- let hhi = tables.f_high[hb + 1] as usize;
587- if celldump
588- .iter()
589- .any(|&cb| cb >= hlo && cb < hhi && cb >= lo && cb < hi)
590- {
591- let e = if high_res {
592- env_energy[ei].get(hb).copied().unwrap_or(0.0)
593- } else {
594- target
595- };
596- let hboost = lim_boost
597- [limiter_band_index(limiter_table, hlo, hhi).min(n_lim - 1)];
598- harmonic = Some((2.0 * e).sqrt() * hboost);
599- }
376+ if track_fraction {
377+ let tab = NOISE_FRACTION.get_or_init(|| std::sync::Mutex::new(Vec::new()));
378+ if let Ok(mut t) = tab.lock() {
379+ for m in 0..m_max {
380+ let sig = e_orig[m] / (1.0 + q_mapped[m]) * slots;
381+ let noi = e_orig[m] * q_mapped[m] / (1.0 + q_mapped[m]) * slots;
382+ if let Some(row) = t.iter_mut().find(|r| r.0 == m + kx) {
383+ row.1 += sig;
384+ row.2 += noi;
385+ } else {
386+ t.push((m + kx, sig, noi, 0.0));
600387 }
601388 }
602- eprintln!(
603- "CELLDUMP ei={ei} band[{lo},{hi}) target={target:.6e} \
604- signal_target={signal_target:.6e} noise_here={noise_here:.6e} \
605- cur={cur:.6e} raw_gain={raw_gain:.6} capped={capped} boost={boost:.6} \
606- namp={namp:.6} harmonic_amp={harmonic:?}"
607- );
608389 }
609390 }
610- // (Round-22 sweep instrumentation) the next envelope's gains, only
611- // when `EC_AAC_SBR_GAIN_LERP` is set and the band layouts match --
612- // `hf` in the next envelope's time range is still untouched at this
613- // point (envelopes are processed and applied in time order), so
614- // this reads the same raw HF estimate the next iteration would.
615- let next_gains: Option<Vec<f64>> =
616- if gain_lerp && ei + 1 < env_energy.len() && ei + 2 < ch.t_env.len() {
617- let (t0n, t1n) = (ch.t_env[ei + 1], ch.t_env[ei + 2]);
618- let high_res_n = ch.freq_res.get(ei + 1).copied().unwrap_or(0) != 0;
619- let table_n: &[i64] = if high_res_n {
620- &tables.f_high
621- } else {
622- &tables.f_low
623- };
624- if table_n.len() == table.len() {
625- let noise_row_n: Option<&Vec<f64>> = ch
626- .t_noise
627- .windows(2)
628- .position(|w| t0n >= w[0] && t0n < w[1])
629- .and_then(|ni| noise_energy.get(ni));
630- Some(compute_gains_only(
631- hf,
632- tables,
633- kx,
634- table_n,
635- t0n,
636- t1n,
637- &env_energy[ei + 1],
638- noise_row_n,
639- limiter_max,
640- ))
641- } else {
642- None
391+ }
392+ state.s_index_prev = s_index_prev;
393+ state.la_prev_at_end = l_a == num_env as i64;
394+
395+ // §4.6.18.7.6 assembly: smoothing over the previous H_SL slots, noise
396+ // from the V table, sinusoids with the (-1)^k phase alternation.
397+ if reset || state.g_hist.len() != h_sl {
398+ state.g_hist.clear();
399+ state.q_hist.clear();
400+ for _ in 0..h_sl {
401+ state.g_hist.push_back(gain[0].clone());
402+ state.q_hist.push_back(q_m[0].clone());
403+ }
404+ }
405+ let phi_sign = if kx & 1 == 1 { -1.0 } else { 1.0 };
406+ let mut g_filt = vec![0.0f64; m_max];
407+ let mut q_filt = vec![0.0f64; m_max];
408+ for e in 0..num_env {
409+ let (t0, t1) = (ch.t_env[e].max(0) as usize, ch.t_env[e + 1].max(0) as usize);
410+ let transient = (e as i64) == l_a || (e as i64) == l_a_prev;
411+ for i in t0..t1 {
412+ if h_sl > 0 && !transient {
413+ for m in 0..m_max {
414+ let mut g = gain[e][m] * H_SMOOTH[0];
415+ let mut q = q_m[e][m] * H_SMOOTH[0];
416+ for j in 1..=h_sl {
417+ // g_hist is oldest-first; j=1 is the most recent slot.
418+ g += state.g_hist[h_sl - j][m] * H_SMOOTH[j];
419+ q += state.q_hist[h_sl - j][m] * H_SMOOTH[j];
420+ }
421+ g_filt[m] = g;
422+ q_filt[m] = q;
643423 }
644424 } else {
645- None
425+ g_filt.copy_from_slice(&gain[e]);
426+ q_filt.copy_from_slice(&q_m[e]);
427+ }
428+ if h_sl > 0 {
429+ state.g_hist.pop_front();
430+ state.q_hist.pop_front();
431+ state.g_hist.push_back(gain[e].clone());
432+ state.q_hist.push_back(q_m[e].clone());
433+ }
434+ // Sinusoid phase for this slot: f_IndexSine 0..3 ->
435+ // (1,0), (0,phi), (-1,0), (0,-phi), phi alternating per subband.
436+ let (p_re, p_im0) = match state.index_sine {
437+ 0 => (1.0, 0.0),
438+ 1 => (0.0, phi_sign),
439+ 2 => (-1.0, 0.0),
440+ _ => (0.0, -phi_sign),
646441 };
647- // `bs_interpol_freq` (per-subband linear interpolation of these sfb
648- // gains, Sec 4.6.18.7.6) was tried here: a centre-frequency lerp
649- // between neighbouring sfbs' flat gain values, applied whenever
650- // `header.interpol_freq != 0`. Measured effect on the real-file
651- // sweep was NEGATIVE (reeln ch0 full-band 0.972756 -> 0.960561)
652- // -- the reference decoder's actual interpolation shape (weighting,
653- // node placement, or which quantity gets interpolated) differs from
654- // this naive lerp, so it was reverted rather than shipped as a
655- // regression; `header.interpol_freq`/`smoothing_mode` remain parsed
656- // but unapplied. corner-cut: real bs_interpol_freq/smoothing_mode
657- // support, ceiling ~0.999 full-band bar; needs the reference
658- // decoder's exact per-subband gain-interpolation formula, not a
659- // plausible reconstruction of it.
660- let span = (t1 - t0.max(0)).max(1) as f64;
661- // (Round-43, Task 1) actual injected-noise-sample energy for the
662- // celldump, summed per listed absolute band (the RNG draws it from
663- // are only realized inside this loop, unlike everything the print
664- // block above already knows).
665- let mut celldump_injected: std::collections::HashMap<usize, (f64, f64, usize)> =
666- std::collections::HashMap::new();
667- let mut celldump_post: std::collections::HashMap<usize, (f64, usize)> =
668- std::collections::HashMap::new();
669- for b in 0..table.len().saturating_sub(1) {
670- let lo = table[b] as usize;
671- let hi = table[b + 1] as usize;
672- let base_gain = gains[b];
673- let end_gain = next_gains.as_ref().and_then(|ng| ng.get(b).copied());
674- let namp = noise_amps[b];
675- for band in lo..hi {
676- if band < kx || band - kx >= hf.len() {
677- continue;
442+ let mut p_im = p_im0;
443+ let mut noise_idx = state.index_noise;
444+ for m in 0..m_max {
445+ let row = &mut hf[m];
446+ if i >= row.len() {
447+ break;
678448 }
679- let row = &mut hf[band - kx];
680- for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) {
681- let gain = if let Some(end) = end_gain {
682- let w = (slot as f64 - t0.max(0) as f64) / span;
683- base_gain + (end - base_gain) * w.clamp(0.0, 1.0)
684- } else {
685- base_gain
686- };
687- row[slot] = row[slot].scale(gain);
688- if !celldump.is_empty() && celldump.contains(&band) {
689- let e = celldump_injected.entry(band).or_insert((0.0, 0.0, 0));
690- e.1 += row[slot].norm_sqr(); // signal alone, pre-noise
691- e.2 += 1;
692- }
693- // Consume the RNG unconditionally (matches the pre-round-21
694- // stream shape) even under EC_AAC_SBR_NOISE_ZERO, which
695- // only skips the PCM addition, not the bookkeeping.
696- let n = rng.complex_unit().scale(namp);
697- if !celldump.is_empty() && celldump.contains(&band) {
698- let e = celldump_injected.entry(band).or_insert((0.0, 0.0, 0));
699- e.0 += n.norm_sqr();
700- }
701- row[slot] = row[slot] + if zero_noise { Complex::ZERO } else { n };
702- if !celldump.is_empty() && celldump.contains(&band) {
703- celldump_post.entry(band).or_insert((0.0, 0)).0 += row[slot].norm_sqr();
704- celldump_post.entry(band).or_insert((0.0, 0)).1 += 1;
705- }
449+ let mut y = row[i].scale(g_filt[m]);
450+ noise_idx = (noise_idx + 1) & 0x1ff;
451+ if s_m[e][m] != 0.0 {
452+ y = y + Complex::new(s_m[e][m] * p_re, s_m[e][m] * p_im);
453+ } else if !transient && !zero_noise {
454+ let (vr, vi) = SBR_NOISE[noise_idx];
455+ y = y + Complex::new(q_filt[m] * vr, q_filt[m] * vi);
706456 }
457+ row[i] = y;
458+ p_im = -p_im;
707459 }
708- }
709- if !celldump.is_empty() {
710- for (&band, &(noise_sum, signal_sum, count)) in &celldump_injected {
711- let (post_sum, post_count) = celldump_post.get(&band).copied().unwrap_or((0.0, 0));
712- eprintln!(
713- "CELLDUMP ei={ei} band={band} actually_injected_noise_energy={:.6e} \
714- actual_signal_only_energy={:.6e} post_addition_energy={:.6e} (n={count})",
715- if count > 0 {
716- noise_sum / count as f64
717- } else {
718- 0.0
719- },
720- if count > 0 {
721- signal_sum / count as f64
722- } else {
723- 0.0
724- },
725- if post_count > 0 {
726- post_sum / post_count as f64
727- } else {
728- 0.0
729- },
730- );
731- }
732- }
733-
734- // Sinusoids: one extra tone per flagged high-resolution band,
735- // added after gain so its amplitude is exact regardless of the
736- // cell's measured HF energy.
737- if let Some(flags) = &ch.add_harmonic {
738- for (b, &on) in flags.iter().enumerate() {
739- if on == 0 || b + 1 >= tables.f_high.len() {
740- continue;
741- }
742- let lo = tables.f_high[b] as usize;
743- let hi = tables.f_high[b + 1] as usize;
744- let e = if high_res {
745- env_energy[ei].get(b).copied().unwrap_or(0.0)
746- } else {
747- // The envelope grid was low-res this frame; approximate
748- // the harmonic band's share of its low-res parent cell.
749- let lb = table
750- .iter()
751- .position(|&x| x as usize > lo)
752- .map(|i| i.saturating_sub(1))
753- .unwrap_or(0);
754- env_energy[ei].get(lb).copied().unwrap_or(0.0)
755- };
756- let boost = lim_boost[limiter_band_index(limiter_table, lo, hi).min(n_lim - 1)];
757- let amp = (2.0 * e).sqrt() * boost;
758- for band in lo..hi {
759- if band < kx || band - kx >= hf.len() {
760- continue;
761- }
762- let row = &mut hf[band - kx];
763- for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) {
764- row[slot] = row[slot] + Complex::new(amp, 0.0);
460+ if track_fraction {
461+ let tab = NOISE_FRACTION.get_or_init(|| std::sync::Mutex::new(Vec::new()));
462+ if let Ok(mut t) = tab.lock() {
463+ for m in 0..m_max {
464+ if let (Some(row), Some(y)) =
465+ (t.iter_mut().find(|r| r.0 == m + kx), hf[m].get(i))
466+ {
467+ row.3 += y.norm_sqr();
468+ }
765469 }
766470 }
767471 }
472+ state.index_noise = (state.index_noise + m_max) & 0x1ff;
473+ state.index_sine = (state.index_sine + 1) & 3;
768474 }
769475 }
770-
771- // (Round-21) Noise is now injected inside the envelope-gain loop above,
772- // per (envelope, band) cell using each cell's own `signal_target`/
773- // `noise_here` split -- the noise grid is coarser than the envelope
774- // grid but every envelope cell resolves its own noise band via
775- // `noise_band_for`/`noise_row`, so this covers the same ground the old
776- // separate noise-grid pass did, consistently with the gain that was
777- // computed for the same cell (previously the two were split across
778- // unrelated unit scales; see the comment at `noise_div` above).
779-}
780-
781-/// (Round-22 sweep instrumentation) The same gain math the main loop in
782-/// [`adjust`] computes, minus the tracking/noise-amplitude side effects --
783-/// used to look ahead at the NEXT envelope's gain for `EC_AAC_SBR_GAIN_LERP`.
784-#[allow(clippy::too_many_arguments)]
785-fn compute_gains_only(
786- hf: &[Vec<Complex<f64>>],
787- tables: &BandTables,
788- kx: usize,
789- table: &[i64],
790- t0: i64,
791- t1: i64,
792- env_row: &[f64],
793- noise_row: Option<&Vec<f64>>,
794- limiter_max: f64,
795-) -> Vec<f64> {
796- let mut gains = Vec::with_capacity(table.len().saturating_sub(1));
797- for b in 0..table.len().saturating_sub(1) {
798- let lo = table[b] as usize;
799- let hi = table[b + 1] as usize;
800- let target = env_row.get(b).copied().unwrap_or(0.0);
801- let (mut sum, mut count) = (0.0f64, 0usize);
802- for band in lo..hi {
803- if band < kx || band - kx >= hf.len() {
804- continue;
805- }
806- let row = &hf[band - kx];
807- for slot in t0.max(0) as usize..(t1.max(0) as usize).min(row.len()) {
808- sum += row[slot].norm_sqr();
809- count += 1;
810- }
811- }
812- let current = if count > 0 { sum / count as f64 } else { 0.0 };
813- let q = noise_band_for(tables, lo);
814- let noise_div = noise_row
815- .and_then(|r| r.get(q).copied())
816- .unwrap_or(0.0)
817- .max(0.0);
818- let signal_target = target / (1.0 + noise_div);
819- let noise_here = target - signal_target;
820- let cur = current.max(1e-12);
821- let mut gain = (signal_target / cur).sqrt();
822- gain = gain.min(limiter_max * ((noise_here + cur) / cur).sqrt());
823- gain = gain.min(limiter_max * 64.0);
824- gains.push(gain);
825- }
826- gains
827-}
828-
829-/// Finds which limiter band (from [`crate::sbr_hf::limiter_band_table`])
830-/// a `[lo, hi)` QMF-band cell falls into, by its midpoint.
831-fn limiter_band_index(limiter_table: &[i64], lo: usize, hi: usize) -> usize {
832- if limiter_table.len() < 2 {
833- return 0;
834- }
835- let mid = (lo + hi) as i64 / 2;
836- for j in 0..limiter_table.len() - 1 {
837- if mid < limiter_table[j + 1] {
838- return j;
839- }
840- }
841- limiter_table.len() - 2
842-}
843-
844-fn noise_band_for(tables: &BandTables, low_band: usize) -> usize {
845- let mut q = 0usize;
846- for i in 0..tables.n_q {
847- if (low_band as i64) >= tables.f_noise[i] {
848- q = i;
849- }
850- }
851- q
852476 }
853477
854478 #[cfg(test)]
@@ -878,240 +502,94 @@ mod tests {
878502 }
879503 }
880504
881- #[test]
882- fn flat_hf_region_reaches_the_stated_envelope_energy() {
883- let tables = flat_tables();
884- let kx = tables.kx as usize;
885- let k2 = tables.k2 as usize;
886- let slots = 16usize;
887- let mut hf = vec![vec![Complex::new(0.1, 0.0); slots]; k2 - kx];
888- let ch = SbrChannel {
505+ fn channel(tables: &BandTables, add_harmonic: Option<Vec<u8>>) -> SbrChannel {
506+ SbrChannel {
889507 t_env: vec![0, 16],
890- freq_res: vec![0],
508+ freq_res: vec![1],
891509 t_noise: vec![0, 16],
892- e_q: vec![vec![]],
893- q_q: vec![vec![]],
510+ e_q: vec![vec![0; tables.n_high]],
511+ q_q: vec![vec![0; tables.n_q]],
894512 invf_mode: vec![],
895- add_harmonic: None,
513+ add_harmonic,
896514 df_env: vec![],
897515 df_noise: vec![],
898- };
899- let target = 4.0f64;
900- let env_energy = vec![vec![target; tables.n_low]];
901- let noise_energy = vec![vec![0.0f64; tables.n_q]];
902- let mut rng = NoiseGen::new(1);
903- let lim_table =
904- limiter_band_table(&tables, &build_patches(&tables), header(1, 3).limiter_bands);
905- adjust(
906- &mut hf,
907- &tables,
908- &header(1, 3),
909- &ch,
910- &env_energy,
911- &noise_energy,
912- &mut rng,
913- &lim_table,
914- );
915-
916- // Every low-res band's average energy should land close to target.
917- for b in 0..tables.n_low {
918- let lo = tables.f_low[b] as usize;
919- let hi = tables.f_low[b + 1] as usize;
920- let mut sum = 0.0;
921- let mut n = 0usize;
922- for band in lo..hi {
923- if band < kx {
924- continue;
925- }
926- for slot in 0..slots {
927- sum += hf[band - kx][slot].norm_sqr();
928- n += 1;
929- }
930- }
931- if n == 0 {
932- continue;
933- }
934- let avg = sum / n as f64;
935- assert!(
936- (avg - target).abs() / target < 0.05,
937- "band {b}: avg {avg} vs target {target}"
938- );
516+ l_a: -1,
517+ amp_res: 1,
939518 }
940519 }
941520
942- /// (Round-41, Task 2) `NoiseGen::complex_unit`'s realized expected
943- /// squared magnitude must be ~1.0 -- `adjust` scales it by
944- /// `namp = sqrt(noise_here)` expecting `E[|namp*z|^2] =
945- /// noise_here`, so anything but ~1.0 here means the injected noise
946- /// under- or over-realizes the transmitted split regardless of the
947- /// limiter/boost interaction (measured separately, at the whole-decode
948- /// level, in `tests/sbr_real_library.rs`'s `sbr_actual_noise_fraction`).
949- /// Before the `sqrt(6)` fix this read ~1/6.
950521 #[test]
951- fn complex_unit_has_unit_expected_squared_magnitude() {
952- let mut rng = NoiseGen::new(1);
953- let n = 200_000;
954- let mean_sq: f64 =
955- (0..n).map(|_| rng.complex_unit().norm_sqr()).sum::<f64>() / f64::from(n);
956- assert!(
957- (mean_sq - 1.0).abs() < 0.02,
958- "E[|complex_unit()|^2] = {mean_sq}, expected ~1.0"
959- );
960- }
961-
962- #[test]
963- fn limiter_stays_finite_on_a_uniformly_starved_band() {
964- // (Round-33 semantics change) A UNIFORMLY near-silent HF estimate
965- // against a huge uniform target is no longer expected to be capped
966- // down near the raw HF amplitude -- the aggregate cap and its
967- // gain-boost compensation are computed from the SAME population, so
968- // when every cell in a limiter band is equally starved (no
969- // disproportion for the limiter to actually correct), full recovery
970- // toward the transmitted target is the spec-correct outcome (boost
971- // undoes exactly what the cap took away, as long as the needed
972- // `1/limiter_max` stays under `BOOST_MAX`). What must NOT happen
973- // (the actual pre-fix bug) is a literal unbounded/non-finite blow-up
974- // -- this asserts finiteness and a generous bound around the target
975- // amplitude, not the old (now-wrong) "stays near the raw estimate"
976- // shape.
522+ fn flat_hf_region_reaches_the_stated_envelope_energy() {
977523 let tables = flat_tables();
978- let kx = tables.kx as usize;
979- let k2 = tables.k2 as usize;
524+ let (kx, k2) = (tables.kx as usize, tables.k2 as usize);
980525 let slots = 16usize;
981- let mut hf = vec![vec![Complex::new(1e-9, 0.0); slots]; k2 - kx];
982- let ch = SbrChannel {
983- t_env: vec![0, 16],
984- freq_res: vec![0],
985- t_noise: vec![0, 16],
986- e_q: vec![vec![]],
987- q_q: vec![vec![]],
988- invf_mode: vec![],
989- add_harmonic: None,
990- df_env: vec![],
991- df_noise: vec![],
992- };
993- let env_energy = vec![vec![1.0e6f64; tables.n_low]];
994- // (Round-21) noise_energy is now a Q_div ratio against the cell's
995- // own envelope target, not a standalone absolute energy -- zero
996- // keeps this test focused on the signal-gain limiter it names, not
997- // noise injection.
998- let noise_energy = vec![vec![0.0f64; tables.n_q]];
999- let mut rng = NoiseGen::new(1);
1000- let lim_table =
1001- limiter_band_table(&tables, &build_patches(&tables), header(1, 0).limiter_bands);
1002- adjust(
1003- &mut hf,
1004- &tables,
1005- &header(1, 0),
1006- &ch,
1007- &env_energy,
1008- &noise_energy,
1009- &mut rng,
1010- &lim_table,
1011- );
1012- let target_amp = 1.0e6f64.sqrt(); // ~1000, the envelope's own amplitude scale
1013- for band in 0..hf.len() {
1014- for slot in 0..slots {
1015- let amp = hf[band][slot].norm_sqr().sqrt();
1016- assert!(
1017- amp.is_finite() && amp < 10.0 * target_amp,
1018- "gain escaped to a non-finite/unbounded value at band {band} slot {slot}: {:?}",
1019- hf[band][slot]
1020- );
1021- }
526+ let mut hf = vec![vec![Complex::new(0.1, 0.0); slots]; k2 - kx];
527+ let target = 4.0f64;
528+ let env_energy = vec![vec![target; tables.n_high]];
529+ // Q_mapped = 1 (q_q = 6): half the target is noise.
530+ let noise_energy = vec![vec![1.0f64; tables.n_q]];
531+ let hdr = header(1, 3);
532+ let lim = limiter_band_table(&tables, &build_patches(&tables), hdr.limiter_bands);
533+ let mut st = AdjustState::new();
534+ adjust(&mut hf, &tables, &hdr, &channel(&tables, None), &env_energy, &noise_energy, &lim, &mut st, true);
535+ for m in 0..k2 - kx {
536+ let avg: f64 = hf[m].iter().map(|c| c.norm_sqr()).sum::<f64>() / slots as f64;
537+ // signal share exactly target/2 (flat input, G cancels E_curr);
538+ // noise share target/2 in expectation over the V table.
539+ assert!((avg - target).abs() / target < 0.4, "m={m}: avg {avg} vs target {target}");
1022540 }
1023541 }
1024542
1025543 #[test]
1026- fn a_content_empty_cell_inherits_its_limiter_bands_aggregate_cap() {
1027- // (Round-33) One low-res band has real HF content, its neighbour is
1028- // perfectly silent (current=0, the exact case a per-cell cap makes
1029- // infinite -- round-33's convicted mechanism). Both fall in the
1030- // same limiter_bands=0 (single aggregate band) table here, so the
1031- // silent cell must be capped by the AGGREGATE ratio (dominated by
1032- // the loud cell's huge current), not blown up on its own.
544+ fn sinusoid_lands_on_the_centre_subband_only_and_mutes_noise_there() {
1033545 let tables = flat_tables();
1034- let kx = tables.kx as usize;
1035- let k2 = tables.k2 as usize;
546+ let (kx, k2) = (tables.kx as usize, tables.k2 as usize);
1036547 let slots = 16usize;
1037- let mut hf = vec![vec![Complex::new(0.1, 0.0); slots]; k2 - kx];
1038- // Silence the top half of the HF region (the empty target cell).
1039- let mid = hf.len() / 2;
1040- for row in &mut hf[mid..] {
1041- for c in row.iter_mut() {
1042- *c = Complex::ZERO;
1043- }
1044- }
1045- let ch = SbrChannel {
1046- t_env: vec![0, 16],
1047- freq_res: vec![0],
1048- t_noise: vec![0, 16],
1049- e_q: vec![vec![]],
1050- q_q: vec![vec![]],
1051- invf_mode: vec![],
1052- add_harmonic: None,
1053- df_env: vec![],
1054- df_noise: vec![],
1055- };
1056- let target = 4.0f64;
1057- let env_energy = vec![vec![target; tables.n_low]];
548+ let mut hf = vec![vec![Complex::ZERO; slots]; k2 - kx];
549+ let mut flags = vec![0u8; tables.n_high];
550+ flags[1] = 1;
551+ let env_energy = vec![vec![4.0f64; tables.n_high]];
1058552 let noise_energy = vec![vec![0.0f64; tables.n_q]];
1059- let mut rng = NoiseGen::new(1);
1060- let mut h = header(1, 1);
1061- h.limiter_bands = 0; // single aggregate band spanning the whole HF region
1062- let lim_table = limiter_band_table(&tables, &build_patches(&tables), h.limiter_bands);
1063- assert_eq!(lim_table, vec![tables.kx, tables.k2]);
1064- adjust(
1065- &mut hf,
1066- &tables,
1067- &h,
1068- &ch,
1069- &env_energy,
1070- &noise_energy,
1071- &mut rng,
1072- &lim_table,
1073- );
1074- // The previously-silent cells must stay bounded (not blown up to
1075- // the old per-cell `limiter_max*64` absolute ceiling on a target of
1076- // 4.0 -- they should land well under it, inheriting the band's
1077- // aggregate cap instead).
1078- for row in &hf[mid..] {
1079- for c in row {
1080- assert!(
1081- c.norm_sqr() < target * 4.0,
1082- "empty cell escaped its limiter band's aggregate cap: {c:?}"
1083- );
553+ let hdr = header(1, 1);
554+ let lim = limiter_band_table(&tables, &build_patches(&tables), hdr.limiter_bands);
555+ let mut st = AdjustState::new();
556+ adjust(&mut hf, &tables, &hdr, &channel(&tables, Some(flags)), &env_energy, &noise_energy, &lim, &mut st, true);
557+ let mid = ((tables.f_high[1] + tables.f_high[2]) >> 1) as usize - kx;
558+ for m in 0..k2 - kx {
559+ let e: f64 = hf[m].iter().map(|c| c.norm_sqr()).sum::<f64>() / slots as f64;
560+ if m == mid {
561+ // S_M^2 = E_orig/(1+Q) = 4, boost capped at 1.5849^2 at most.
562+ assert!(e >= 4.0 - 1e-9 && e <= 4.0 * BOOST_MAX * BOOST_MAX + 1e-6, "mid {e}");
563+ // Phase walks 0,90,180,270 degrees per slot.
564+ assert!((hf[m][0].re - hf[m][0].norm_sqr().sqrt()).abs() < 1e-9 && hf[m][1].re.abs() < 1e-9);
565+ } else {
566+ assert!(e < 1e-9, "m={m}: {e}");
1084567 }
1085568 }
1086569 }
1087570
1088571 #[test]
1089572 fn coupled_balance_round_trips_at_a_centred_ratio() {
1090- // The ratio's exponent is `pan_raw - panOffset` (ISO/IEC 14496-3
1091- // §4.6.18.7.2, see the module doc): it's centred (ratio=1) at
1092- // pan_raw=12 for amp_res=1 and pan_raw=24 for amp_res=0.
1093- let (e0, e1) = dequant_pair(10, 12, 1, 1);
573+ let (e0, e1) = dequant_pair(10, 6, 1);
1094574 let e0_plain = dequant_env(10, 1);
1095- assert!(
1096- (e0 - e0_plain).abs() < 1e-6 && (e1 - e0_plain).abs() < 1e-6,
1097- "{e0} {e1} vs {e0_plain}"
1098- );
1099- let (e00, e10) = dequant_pair(10, 24, 0, 0);
575+ assert!((e0 - e0_plain).abs() < 1e-6 && (e1 - e0_plain).abs() < 1e-6, "{e0} {e1} vs {e0_plain}");
576+ let (e00, e10) = dequant_pair(10, 12, 0);
1100577 let e00_plain = dequant_env(10, 0);
1101- assert!(
1102- (e00 - e00_plain).abs() < 1e-6 && (e10 - e00_plain).abs() < 1e-6,
1103- "{e00} {e10} vs {e00_plain}"
1104- );
578+ assert!((e00 - e00_plain).abs() < 1e-6 && (e10 - e00_plain).abs() < 1e-6, "{e00} {e10} vs {e00_plain}");
579+ let (q0, q1) = dequant_noise_pair(3, 6);
580+ assert!((q0 - dequant_noise(3)).abs() < 1e-9 && (q1 - q0).abs() < 1e-9);
1105581 }
1106582
1107583 #[test]
1108- fn coupled_balance_shifts_energy_toward_the_channel_with_a_higher_raw_value() {
1109- // §4.6.18.7.2: as the raw balance value grows past the centre
1110- // (panOffset), env1 grows toward `2*Ecurr` and env0 shrinks toward
1111- // 0 (env1's formula carries the `ratio` factor, env0's doesn't).
1112- let (e0_low, e1_low) = dequant_pair(10, 0, 1, 1);
1113- let (e0_high, e1_high) = dequant_pair(10, 24, 1, 1);
1114- assert!(e0_low > e1_low, "{e0_low} vs {e1_low}");
1115- assert!(e0_high < e1_high, "{e0_high} vs {e1_high}");
584+ fn coupled_balance_shifts_energy_toward_channel_0_with_a_higher_raw_value() {
585+ let (e0_low, e1_low) = dequant_pair(10, 0, 1);
586+ let (e0_high, e1_high) = dequant_pair(10, 12, 1);
587+ assert!(e0_low < e1_low, "{e0_low} vs {e1_low}");
588+ assert!(e0_high > e1_high, "{e0_high} vs {e1_high}");
589+ // One raw balance step is two amp_res steps of ratio: 6 dB at
590+ // amp_res 1, 3 dB at amp_res 0.
591+ let (a0, a1) = dequant_pair(10, 5, 1);
592+ let (b0, b1) = dequant_pair(10, 11, 0);
593+ assert!((a1 / a0 - 4.0).abs() < 1e-9 && (b1 / b0 - 2.0).abs() < 1e-9, "{a0} {a1} {b0} {b1}");
1116594 }
1117595 }
crates/ec-aac/src/sbr_hf.rsmodified+199 -245
@@ -124,60 +124,75 @@ pub struct Patch {
124124 pub width: usize,
125125 }
126126
127-/// Builds the patch list filling `[tables.kx, tables.k2)` from bands below
128-/// `kx`, walking the source pointer down and wrapping it back to `kx` when
129-/// exhausted. Deterministic: the same tables always produce the same patches.
127+/// Patch construction, ISO/IEC 14496-3 §4.6.18.6.3 (Figure 4.31): source
128+/// bands are read downward from `k0 = f_master[0]`, patches end on master
129+/// borders, `goalSb = round(2048 kHz / fs)` bounds the first patch, and a
130+/// trailing patch narrower than 3 bands is dropped.
130131 pub fn build_patches(tables: &BandTables) -> Vec<Patch> {
131- let kx = tables.kx as usize;
132- let k2 = tables.k2 as usize;
133- let f_high: Vec<usize> = tables.f_high.iter().map(|&b| b as usize).collect();
132+ let kx = tables.kx;
133+ let k2 = tables.k2;
134+ let fm = &tables.f_master;
134135 let mut patches = Vec::new();
135- if kx == 0 || k2 <= kx {
136+ if kx <= 0 || k2 <= kx || fm.len() < 2 {
136137 return patches;
137138 }
138- let mut msb = kx; // source read pointer, decreasing
139- let mut sb = kx; // target write pointer, increasing
140- while sb < k2 {
141- // Widest run of consecutive f_high intervals starting at `sb` whose
142- // total width still fits below the current source pointer.
143- let mut width = 0usize;
144- let mut probe = sb;
139+ let k0 = fm[0];
140+ let n_master = fm.len() - 1;
141+ let goal_sb = ((1000i64 << 11) + i64::from(tables.rate >> 1)) / i64::from(tables.rate.max(1));
142+ let mut k = if goal_sb < k2 {
143+ fm.iter().position(|&b| b >= goal_sb).unwrap_or(n_master)
144+ } else {
145+ n_master
146+ };
147+ let (mut msb, mut usb) = (k0, kx);
148+ let (mut last_k, mut last_msb) = (usize::MAX, i64::MIN);
149+ let mut sb;
150+ loop {
151+ if k == last_k && msb == last_msb {
152+ break; // construction failed; keep what we have
153+ }
154+ last_k = k;
155+ last_msb = msb;
156+ let mut odd = 0i64;
157+ let mut i = k;
145158 loop {
146- let next_border = f_high.iter().find(|&&b| b > probe).copied();
147- let Some(border) = next_border else { break };
148- let iv = border - probe;
149- if width + iv > msb || border > k2 {
159+ sb = fm[i];
160+ odd = (sb + k0) & 1;
161+ if i == 0 || sb <= k0 - 1 + msb - odd {
150162 break;
151163 }
152- width += iv;
153- probe = border;
164+ i -= 1;
165+ }
166+ let width = (sb - usb).max(0);
167+ if width > 0 {
168+ patches.push(Patch {
169+ source_start: (k0 - odd - width).max(0) as usize,
170+ target_start: usb as usize,
171+ width: width as usize,
172+ });
173+ usb = sb;
174+ msb = sb;
175+ } else {
176+ msb = kx;
177+ }
178+ if fm[k] - sb < 3 {
179+ k = n_master;
154180 }
155- if width == 0 {
156- width = (k2 - sb).min(msb.max(1));
181+ if sb == k2 || patches.len() > 6 {
182+ break;
157183 }
158- let source_start = msb - width.min(msb);
159- patches.push(Patch {
160- source_start,
161- target_start: sb,
162- width,
163- });
164- sb += width;
165- msb = if source_start == 0 { kx } else { source_start };
184+ }
185+ if patches.len() > 1 && patches.last().is_some_and(|p| p.width < 3) {
186+ patches.pop();
166187 }
167188 patches
168189 }
169190
170-/// Builds the limiter band table (ISO/IEC 14496-3 §4.6.18.7.2): the union
171-/// of the low-resolution envelope band borders (`tables.f_low`) and the
172-/// patch target boundaries, thinned so no band is narrower than one
173-/// limiter band's worth of octaves at the transmitted `bs_limiter_bands`
174-/// density (`0` => a single band spanning the whole HF region; `1`/`2`/`3`
175-/// => ~1/2/3 bands per octave, log2-spaced the same way [`f_master`]'s own
176-/// band construction thins its candidate borders). The limiter's gain cap
177-/// is applied per band on this table, aggregated over every cell it
178-/// covers, so a content-empty target cell inherits its band's aggregate
179-/// cap instead of amplifying numeric dust toward an unbounded per-cell
180-/// ratio.
191+/// Builds the limiter band table (ISO/IEC 14496-3 §4.6.18.7.2, Figure 4.33):
192+/// the union of `f_low` and the patch borders, sorted, then thinned so two
193+/// borders closer than `0.49/limBands` octaves collapse (`bs_limiter_bands`
194+/// 1/2/3 => 1.2/2/3 bands per octave), keeping patch borders over
195+/// envelope borders when one of the pair must go. `0` => one band.
181196 pub fn limiter_band_table(tables: &BandTables, patches: &[Patch], limiter_bands: u8) -> Vec<i64> {
182197 let kx = tables.kx;
183198 let k2 = tables.k2;
@@ -187,43 +202,50 @@ pub fn limiter_band_table(tables: &BandTables, patches: &[Patch], limiter_bands:
187202 if limiter_bands == 0 {
188203 return vec![kx, k2];
189204 }
190- let bands_per_octave = match limiter_bands {
191- 1 => 1.0,
192- 2 => 2.0,
193- _ => 3.0,
205+ let warped = match limiter_bands {
206+ 1 => 2f64.powf(0.49 / 1.2),
207+ 2 => 2f64.powf(0.49 / 2.0),
208+ _ => 2f64.powf(0.49 / 3.0),
194209 };
195- let mut borders: Vec<i64> = tables
196- .f_low
197- .iter()
198- .copied()
199- .chain(patches.iter().map(|p| p.target_start as i64))
200- .chain(std::iter::once(k2))
201- .chain(std::iter::once(kx))
202- .filter(|&b| b >= kx && b <= k2)
203- .collect();
204- borders.sort_unstable();
205- borders.dedup();
206- let mut out = vec![borders[0]];
207- for &b in &borders[1..] {
210+ let mut patch_borders: Vec<i64> = vec![kx];
211+ for p in patches {
212+ patch_borders.push(patch_borders.last().unwrap() + p.width as i64);
213+ }
214+ let mut table: Vec<i64> = tables.f_low.clone();
215+ table.extend(patch_borders.iter().skip(1).take(patches.len().saturating_sub(1)));
216+ table.sort_unstable();
217+ let is_patch = |b: i64| patch_borders.contains(&b);
218+ let mut out: Vec<i64> = vec![table[0]];
219+ for &b in &table[1..] {
208220 let last = *out.last().unwrap();
209- if b <= last {
210- continue;
211- }
212- let octaves = (b as f64 / last as f64).log2();
213- if octaves * bands_per_octave < 1.0 && b != k2 {
214- continue; // too narrow on its own: merges into the current band
221+ if (b as f64) >= (last as f64) * warped {
222+ out.push(b);
223+ } else if b == last || !is_patch(b) {
224+ // drop the incoming border
225+ } else if !is_patch(last) {
226+ *out.last_mut().unwrap() = b;
227+ } else {
228+ out.push(b);
215229 }
216- out.push(b);
217- }
218- if *out.last().unwrap() != k2 {
219- out.push(k2);
220230 }
221231 out
222232 }
223233
224-/// `bs_invf_mode` bandwidth-expansion targets (OFF, LOW, MID, HIGH), the
225-/// four inverse-filtering strengths §4.6.18.6.2 defines.
226-const BW_TABLE: [f64; 4] = [0.0, 0.6, 0.9, 0.98];
234+/// `bs_invf_mode` chirp targets per ISO 14496-3 4.6.18.6.3 (Table 4.163):
235+/// the target depends on the current AND previous frame's mode --
236+/// OFF is 0.0 except 0.6 when falling from LOW; LOW is 0.75 except 0.6
237+/// when rising from OFF; MID 0.9; HIGH 0.98. The previous flat table
238+/// (`[0, 0.6, 0.9, 0.98]`) under-whitened every steady-state LOW band.
239+fn bw_target(mode: u8, prev_mode: u8) -> f64 {
240+ match (mode, prev_mode) {
241+ (0, 1) => 0.6,
242+ (0, _) => 0.0,
243+ (1, 0) => 0.6,
244+ (1, _) => 0.75,
245+ (2, _) => 0.9,
246+ _ => 0.98,
247+ }
248+}
227249
228250 /// Per-noise-band chirp factor state, smoothed frame to frame with a
229251 /// fast-attack (toward a *lower* bw, i.e. more whitening) / slow-release
@@ -231,18 +253,22 @@ const BW_TABLE: [f64; 4] = [0.0, 0.6, 0.9, 0.98];
231253 #[derive(Clone, Debug)]
232254 pub struct ChirpState {
233255 bw: Vec<f64>,
256+ prev_mode: Vec<u8>,
234257 }
235258
236259 impl ChirpState {
237260 pub fn new(n_q: usize) -> ChirpState {
238- ChirpState { bw: vec![0.0; n_q] }
261+ ChirpState {
262+ bw: vec![0.0; n_q],
263+ prev_mode: vec![0; n_q],
264+ }
239265 }
240266
241267 /// Advances the state one frame given this frame's `bs_invf_mode` per
242268 /// noise band, returning the smoothed bw to use for HF generation.
243269 ///
244270 /// (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_BW_SCALE`
245- /// scales `BW_TABLE`'s target globally (clamped below 1.0) before
271+ /// scales the chirp target globally (clamped below 1.0) before
246272 /// smoothing, to probe whether the chirp/inverse-filter strength is
247273 /// miscalibrated on real content. `EC_AAC_SBR_CHIRP_SMOOTH=none` skips
248274 /// the attack/release smoothing entirely (target used immediately);
@@ -251,15 +277,20 @@ impl ChirpState {
251277 pub fn update(&mut self, invf_mode: &[u8]) -> &[f64] {
252278 let scale = bw_scale_override();
253279 let smooth = chirp_smooth_mode();
254- for (slot, &mode) in self.bw.iter_mut().zip(invf_mode) {
255- let target = (BW_TABLE[usize::from(mode).min(3)] * scale).min(0.999_999);
280+ for ((slot, prev), &mode) in self.bw.iter_mut().zip(&mut self.prev_mode).zip(invf_mode) {
281+ let target = (bw_target(mode, *prev) * scale).min(0.999_999);
282+ *prev = mode;
256283 *slot = match smooth {
257284 ChirpSmooth::None => target,
258285 ChirpSmooth::Current => {
286+ // 4.6.18.6.3 bwArray smoothing: both branches weight the
287+ // NEW value (0.75 falling, 0.90625 rising). The rising
288+ // branch previously had the operands swapped (0.09375
289+ // of the new value), making every rise ~10x too slow.
259290 if target < *slot {
260291 0.75 * target + 0.25 * *slot
261292 } else {
262- 0.90625 * *slot + 0.09375 * target
293+ 0.90625 * target + 0.09375 * *slot
263294 }
264295 }
265296 ChirpSmooth::Swap => {
@@ -270,12 +301,16 @@ impl ChirpState {
270301 }
271302 }
272303 };
304+ // 4.6.18.6.3: a smoothed bw under 0.015 is forced to zero.
305+ if *slot < 0.015 {
306+ *slot = 0.0;
307+ }
273308 }
274309 &self.bw
275310 }
276311 }
277312
278-/// `EC_AAC_SBR_BW_SCALE` global multiplier on `BW_TABLE`, clamped below 1.0
313+/// `EC_AAC_SBR_BW_SCALE` global multiplier on the chirp target, clamped below 1.0
279314 /// (a chirp target at or past 1.0 is an undamped all-pole resonance, not a
280315 /// meaningful "stronger" whitening). `1.0` (no-op) when unset or unparsable.
281316 fn bw_scale_override() -> f64 {
@@ -301,95 +336,45 @@ fn chirp_smooth_mode() -> ChirpSmooth {
301336 }
302337 }
303338
304-/// Order-2 covariance-method LPC over `x` (index 0 is the oldest sample):
305-/// solves the 2x2 normal equations minimizing `sum |x[n] - a1*x[n-1] -
306-/// a2*x[n-2]|^2` over `n = 2..x.len()`. Returns `(a1, a2)`; `(0, 0)` if `x`
307-/// is too short or the system is singular (silence or a near-constant
308-/// subband, both of which need no prediction).
309-/// (Round-57) AR(2) coefficients via the Yule-Walker/autocorrelation
310-/// method (`r(k) = sum_n x[n]*conj(x[n-k])`, Hermitian-Toeplitz `R`),
311-/// replacing the previous unwindowed covariance-method normal-equation
312-/// solve. The autocorrelation matrix is always positive semi-definite,
313-/// which is what gives Levinson-Durbin-style AR fits their built-in
314-/// BIBO-stability guarantee (poles inside or on the unit circle) -- the
315-/// covariance method has no such guarantee and was measured producing
316-/// resonant poles that blow `cur` (the raw HF estimate energy) up to
317-/// 1e7-1e11 against a ~1e4 transmitted target on real content
318-/// (heaac_48000_64k.m4a's crossover-straddling sweep window), which then
319-/// poisons the WHOLE limiter band's aggregate `E_curr` (4.6.18.7.5) and
320-/// crushes every other cell sharing that band's gain cap, not just the
321-/// outlier cell itself (round-56's stabilize-bound tightening measured
322-/// zero effect because `raw_gain=sqrt(target/cur)` cancels `cur` exactly
323-/// for the outlier cell's OWN gain -- it never reaches the neighbors this
324-/// aggregate-poisoning does).
339+/// Order-2 linear-prediction coefficients per ISO 14496-3 4.6.18.6.2
340+/// (covariance method, `phi(i,j) = sum_n x[n-i]*conj(x[n-j])` over
341+/// `n = 2..x.len()`, index 0 of `x` is the oldest slot). Returns the spec's
342+/// `(alpha0, alpha1)` -- the PREDICTION-ERROR filter taps, i.e. the
343+/// negated predictor coefficients: for `x[n] = a1*x[n-1] + a2*x[n-2] + e`
344+/// this yields `(-a1, -a2)`, so `x + alpha0*x[n-1] + alpha1*x[n-2]`
345+/// whitens. `(0, 0)` on degenerate input or when either |alpha| >= 4
346+/// (spec guard). Witness: scratch `alpha/witness.py` (numpy) recovers a
347+/// synthetic complex AR(2) with this sign convention and whitens at bw=1.
325348 pub fn lpc2(x: &[Complex<f64>]) -> (Complex<f64>, Complex<f64>) {
326349 if x.len() < 3 {
327350 return (Complex::ZERO, Complex::ZERO);
328351 }
329- let mut r0 = 0.0f64;
330- let mut r1 = Complex::ZERO;
331- let mut r2 = Complex::ZERO;
332- for n in 0..x.len() {
333- r0 += x[n].norm_sqr();
334- if n >= 1 {
335- r1 = r1 + x[n] * x[n - 1].conj();
336- }
337- if n >= 2 {
338- r2 = r2 + x[n] * x[n - 2].conj();
339- }
340- }
341- // Yule-Walker: [[r0, conj(r1)], [r1, r0]] * [a1, a2]^T = [r1, r2]^T.
342- let det = r0 * r0 - r1.norm_sqr();
343- if det.abs() < 1e-20 {
344- return (Complex::ZERO, Complex::ZERO);
345- }
346- let a1 = (r1.scale(r0) - r1.conj() * r2).scale(1.0 / det);
347- let a2 = (r2.scale(r0) - r1 * r1).scale(1.0 / det);
348- (a1, a2)
349-}
350-
351-/// Bounds an AR(2) predictor's coefficients so the resynthesis recursion
352-/// this module runs (`y = residual + ca1*y[n-1] + ca2*y[n-2]`) cannot
353-/// diverge.
354-///
355-/// `lpc2` solves an unwindowed covariance-method normal-equation system,
356-/// which -- unlike the autocorrelation/Levinson-Durbin method the reference
357-/// SBR tool uses -- carries no built-in stability guarantee: on a short (32
358-/// QMF slot) window of a strongly resonant real-music subband it can and
359-/// does return a pole outside the unit circle, and the 32-sample feedback
360-/// loop below then grows geometrically within a single frame (observed:
361-/// output rms in the hundreds of thousands on real HE-AAC files, versus
362-/// ~0.2 for a working decode). `|a1| + |a2| < 1` is a standard sufficient
363-/// (if conservative) BIBO-stability bound for a direct-form-II section, so
364-/// clamping the pair to it whenever it is violated is a corner-cut: it
365-/// trades exactness on the rare unstable-estimate frame for boundedness
366-/// everywhere, ceiling = slightly under-resonant HF on whichever frames hit
367-/// the clamp; upgrade path = replace `lpc2` with the spec's own
368-/// Levinson-Durbin-derived reflection coefficients, which are stable by
369-/// construction and would make this function a no-op.
370-fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64>) {
371- let (a1, a2) = coeffs;
372- let mag = a1.norm_sqr().sqrt() + a2.norm_sqr().sqrt();
373- // (Round-56) Tried tightening this bound to 0.9 on the theory that a
374- // pole at 0.999 gives ~1e6x power resonant gain (`~1/(1-r)^2`), which
375- // `EC_AAC_SBR_CELLDUMP` traces do show happening (`cur`, the raw
376- // pre-gain HF estimate, reaching 1e7-1e11 against a ~1e4 transmitted
377- // target on heaac_48000_64k.m4a's crossover-straddling sweep window,
378- // in the SAME limiter band as starved neighbor cells) -- measured
379- // ZERO effect on the t=18s/24s corr cliff (0.054601->0.054536,
380- // 0.058942->0.058797) or the `EC_AAC_SBR_HF_BYPASS` A/B, because
381- // `raw_gain = sqrt(target/cur)` cancels `cur` exactly for any
382- // non-capped cell regardless of this bound's value -- reverted, no
383- // measured benefit to justify the regression risk on frames that
384- // legitimately need resonance near this bound. Left at `0.999`.
385- if mag > 0.999 && mag.is_finite() {
386- let s = 0.999 / mag;
387- (a1.scale(s), a2.scale(s))
388- } else if mag.is_finite() {
389- (a1, a2)
352+ let phi = |i: usize, j: usize| -> Complex<f64> {
353+ (2..x.len()).fold(Complex::ZERO, |acc, n| acc + x[n - i] * x[n - j].conj())
354+ };
355+ let p11 = phi(1, 1).re;
356+ let p22 = phi(2, 2).re;
357+ let p01 = phi(0, 1);
358+ let p02 = phi(0, 2);
359+ let p12 = phi(1, 2);
360+ const EPS: f64 = 1e-6;
361+ let d = p22 * p11 - p12.norm_sqr() / (1.0 + EPS);
362+ let alpha1 = if d.abs() < 1e-30 {
363+ Complex::ZERO
390364 } else {
391- (Complex::ZERO, Complex::ZERO)
365+ (p01 * p12 - p02.scale(p11)).scale(1.0 / d)
366+ };
367+ let alpha0 = if p11.abs() < 1e-30 {
368+ Complex::ZERO
369+ } else {
370+ (p01 + alpha1 * p12.conj()).scale(-1.0 / p11)
371+ };
372+ let m0 = alpha0.norm_sqr();
373+ let m1 = alpha1.norm_sqr();
374+ if !(m0 < 16.0 && m1 < 16.0) {
375+ return (Complex::ZERO, Complex::ZERO);
392376 }
377+ (alpha0, alpha1)
393378 }
394379
395380 /// Per-source-subband history: the last two QMF slots, carried across
@@ -397,15 +382,18 @@ fn stabilize(coeffs: (Complex<f64>, Complex<f64>)) -> (Complex<f64>, Complex<f64
397382 /// frame boundaries instead of restarting cold every frame.
398383 #[derive(Clone, Debug)]
399384 pub struct HfHistory {
400- x: Vec<[Complex<f64>; 2]>,
401- y: Vec<[Complex<f64>; 2]>,
385+ /// Last `HIST` slots per source band (4.6.18.6.2's covariance window
386+ /// spans the frame plus the 6 overlap slots before it; the filter
387+ /// itself only taps the last two).
388+ x: Vec<[Complex<f64>; HIST]>,
402389 }
403390
391+const HIST: usize = 6;
392+
404393 impl HfHistory {
405394 pub fn new(bands: usize) -> HfHistory {
406395 HfHistory {
407- x: vec![[Complex::ZERO; 2]; bands],
408- y: vec![[Complex::ZERO; 2]; bands],
396+ x: vec![[Complex::ZERO; HIST]; bands],
409397 }
410398 }
411399 }
@@ -448,17 +436,15 @@ pub fn generate(
448436 continue;
449437 }
450438 let series = &low_cur[source_band];
451- let (a1, a2) = {
452- let mut ext = Vec::with_capacity(num_slots + 2);
439+ let (alpha0, alpha1) = {
440+ let mut ext = Vec::with_capacity(num_slots + HIST);
453441 if source_band < history.x.len() {
454- ext.push(history.x[source_band][0]);
455- ext.push(history.x[source_band][1]);
442+ ext.extend_from_slice(&history.x[source_band]);
456443 } else {
457- ext.push(Complex::ZERO);
458- ext.push(Complex::ZERO);
444+ ext.resize(HIST, Complex::ZERO);
459445 }
460446 ext.extend_from_slice(series);
461- stabilize(lpc2(&ext))
447+ lpc2(&ext)
462448 };
463449 let g = bw[noise_band_of(target_band)];
464450 // (Round-46, Task 2) `EC_AAC_SBR_BW_DUMP` -- one line per patched
@@ -468,40 +454,35 @@ pub fn generate(
468454 if std::env::var("EC_AAC_SBR_BW_DUMP").is_ok() {
469455 eprintln!("BW_DUMP target_band={target_band} source_band={source_band} bw={g:.6}");
470456 }
471- let ca1 = a1.scale(g);
472- let ca2 = a2.scale(g * g);
473- let (mut y_prev1, mut y_prev2) = if source_band < history.y.len() {
474- (history.y[source_band][1], history.y[source_band][0])
475- } else {
476- (Complex::ZERO, Complex::ZERO)
477- };
457+ // 4.6.18.6.3 feed-forward: X_high = X_low + bw*alpha0*X_low[l-1]
458+ // + bw^2*alpha1*X_low[l-2]. bw=0 is a plain copy, bw->1 is the
459+ // full inverse (whitening) filter. The all-pole recursion this
460+ // replaced (`y = residual + bw*a1*y[l-1] + bw^2*a2*y[l-2]`) had
461+ // that mapping INVERTED (bw=0 whitened fully, bw=0.98 ~ copy),
462+ // and the earlier feed-forward attempt (8bc305b) used the
463+ // predictor sign (+a) instead of the spec's prediction-error
464+ // sign (-a), which reinforces the resonance instead of
465+ // cancelling it -- hence it measured worse than the inverted
466+ // all-pole form.
467+ let c1 = alpha0.scale(g);
468+ let c2 = alpha1.scale(g * g);
478469 let (mut x_prev1, mut x_prev2) = if source_band < history.x.len() {
479- (history.x[source_band][1], history.x[source_band][0])
470+ (
471+ history.x[source_band][HIST - 1],
472+ history.x[source_band][HIST - 2],
473+ )
480474 } else {
481475 (Complex::ZERO, Complex::ZERO)
482476 };
483477 let dst = &mut out[target_band - kx];
484478 for (n, &x) in series.iter().enumerate() {
485- let residual = x - a1 * x_prev1 - a2 * x_prev2;
486- let y = residual + ca1 * y_prev1 + ca2 * y_prev2;
487479 // Round-37 (Task 2): `band_shift_correction` is proven exact
488- // in isolation (a stationary tone replayed through this
489- // patch-copy site lands within a couple of FFT bins of its
490- // corrected absolute frequency -- see
491- // `sbr_qmf::tests::patch_replay_through_generate_preserves_absolute_frequency_mapping`)
492- // but a real-file mechanical A/B (round-36/37,
493- // `EC_AAC_SBR_PARITY_SPLIT`) shows applying it REGRESSES
494- // odd-gap coherence against the reference decoder (ch0
495- // 0.1907->0.0714, ch1 0.2461->0.0741; sign-flipped and
496- // half-rate variants both regress it too, 0.0757/0.1449 resp.
497- // on ch0). The reference apparently exhibits this bank's own
498- // "wrong" cross-band placement convention, so matching it is
499- // the bar: `dst` stays the plain, uncorrected copy.
500- dst[n] = y;
480+ // in isolation but a real-file A/B (`EC_AAC_SBR_PARITY_SPLIT`)
481+ // shows applying it REGRESSES odd-gap coherence against the
482+ // reference; `dst` stays the uncorrected band placement.
483+ dst[n] = x + c1 * x_prev1 + c2 * x_prev2;
501484 x_prev2 = x_prev1;
502485 x_prev1 = x;
503- y_prev2 = y_prev1;
504- y_prev1 = y;
505486 }
506487 }
507488 }
@@ -509,14 +490,12 @@ pub fn generate(
509490 // Every source subband's history advances regardless of whether a
510491 // patch used it this frame: the low-band QMF stream is continuous.
511492 for (band, series) in low_cur.iter().enumerate() {
512- if band >= history.x.len() || series.len() < 2 {
493+ if band >= history.x.len() {
513494 continue;
514495 }
515- let n = series.len();
516- history.x[band] = [series[n - 2], series[n - 1]];
517- // y-history only meaningfully advances for bands a patch actually
518- // wrote; untouched bands hold their input as a neutral seed.
519- history.y[band] = [series[n - 2], series[n - 1]];
496+ let h = &mut history.x[band];
497+ let keep: Vec<Complex<f64>> = h.iter().copied().chain(series.iter().copied()).collect();
498+ h.copy_from_slice(&keep[keep.len() - HIST..]);
520499 }
521500
522501 out
@@ -579,8 +558,15 @@ mod tests {
579558 // previous covariance-method solve) for a stability guarantee real
580559 // content needs -- still recovers the synthetic poles to well
581560 // within this looser bound.
582- assert!((fa1 - a1).norm_sqr().sqrt() < 0.2, "a1 {fa1:?} vs {a1:?}");
583- assert!((fa2 - a2).norm_sqr().sqrt() < 0.2, "a2 {fa2:?} vs {a2:?}");
561+ // spec alpha = negated predictor coefficients
562+ assert!(
563+ (fa1 + a1).norm_sqr().sqrt() < 0.2,
564+ "alpha0 {fa1:?} vs {a1:?}"
565+ );
566+ assert!(
567+ (fa2 + a2).norm_sqr().sqrt() < 0.2,
568+ "alpha1 {fa2:?} vs {a2:?}"
569+ );
584570 }
585571
586572 #[test]
@@ -589,7 +575,7 @@ mod tests {
589575 // Jump from OFF straight to HIGH: attack (rising bw) is the slow
590576 // (0.90625/0.09375) branch here since target > current.
591577 let after_rise = chirp.update(&[3])[0];
592- assert!(after_rise > 0.0 && after_rise < BW_TABLE[3]);
578+ assert!(after_rise > 0.0 && after_rise < 0.98);
593579 // Now drop back to OFF: release (falling bw) is the fast
594580 // (0.75/0.25) branch, so it should move further in one step than
595581 // the rise did.
@@ -603,35 +589,8 @@ mod tests {
603589 );
604590 }
605591
606- /// (Round-50) Pins the all-pole residual-resynthesis structure that
607- /// round-50's real-file A/B empirically favours over the feed-forward
608- /// FIR round-48 briefly shipped (see the module doc). Both structures
609- /// were implemented and measured against the reference decoder on real
610- /// content; this one matched closer, so it is the one pinned here --
611- /// the feed-forward alternative's own discriminating test
612- /// (`feed_forward_extension_matches_bw_endpoints`, commit 8bc305b) is
613- /// documented history, not dead code to resurrect casually.
614- ///
615- /// Drives the same noiseless AR(2) source as that alternative test
616- /// through two consecutive frames, `x[n] = a1*x[n-1] + a2*x[n-2]`
617- /// exactly, so `lpc2`'s fit recovers `(a1, a2)` closely enough that the
618- /// *residual* `x[l] - a1*x[l-1] - a2*x[l-2]` is near zero throughout.
619- /// That residual, not the raw copy, is what this structure resynthesises
620- /// through the bandwidth-expanded all-pole recursion `y[l] = residual +
621- /// ca1*y[l-1] + ca2*y[l-2]` -- the key structural difference from
622- /// feed-forward, which adds taps onto the copy instead of replacing it
623- /// with a filtered residual:
624- /// - `bw=0` (`bs_invf_mode` OFF): `ca1=ca2=0`, so `y = residual ~= 0` --
625- /// the output collapses toward silence, NOT the exact plain copy
626- /// feed-forward produces at this same setting.
627- /// - `bw~=0.98` (`bs_invf_mode` HIGH): `ca1,ca2` are close to the
628- /// original `(a1,a2)` (scaled by `bw`, `bw^2`), so with residual~=0 the
629- /// recursion nearly reproduces the source's own AR(2) resonance from
630- /// history alone -- output tracks `x` closely in magnitude and phase,
631- /// not the ~1.98x reinforcement feed-forward produces at the same
632- /// setting.
633592 #[test]
634- fn all_pole_resynthesis_matches_bw_endpoints() {
593+ fn feed_forward_matches_bw_endpoints() {
635594 let tables = real_file_tables();
636595 let kx = tables.kx as usize;
637596 let a1 = 0.6f64;
@@ -652,7 +611,7 @@ mod tests {
652611 let invf_off = vec![0u8; tables.n_q];
653612 let invf_high = vec![3u8; tables.n_q];
654613
655- // bw = 0: residual resynthesis collapses toward silence, not a copy.
614+ // bw = 0: exact plain copy (4.6.18.6.3 with both taps zeroed).
656615 let mut chirp0 = ChirpState::new(tables.n_q);
657616 let mut hist0 = HfHistory::new(kx);
658617 let _ = generate(&frame1, &tables, &invf_off, &mut chirp0, &mut hist0);
@@ -664,13 +623,13 @@ mod tests {
664623 continue;
665624 }
666625 assert!(
667- y.re.abs() < 0.1 * expect.abs(),
668- "bw=0 residual should collapse toward silence at n={n}: {y:?} vs input {expect}"
626+ (y - Complex::new(expect, 0.0)).norm_sqr().sqrt() < 1e-9 * expect.abs().max(1.0),
627+ "bw=0 must copy at n={n}: {y:?} vs input {expect}"
669628 );
670629 }
671630
672- // bw ~= 0.98: residual~=0, so the recursion tracks the source's own
673- // resonance from history alone -- ratio near 1, not ~1.98.
631+ // bw ~= 0.98: near-full inverse filter of a noiseless AR(2) -> the
632+ // output is close to the (zero) prediction residual, far below x.
674633 let mut chirp1 = ChirpState::new(tables.n_q);
675634 chirp1.bw = vec![0.0; tables.n_q]; // priming frame at bw=0
676635 let mut hist1 = HfHistory::new(kx);
@@ -683,14 +642,9 @@ mod tests {
683642 if expect.abs() < 1e-6 {
684643 continue;
685644 }
686- let ratio = y.re / expect;
687- assert!(
688- (0.5..1.5).contains(&ratio),
689- "bw=0.98 ratio out of range at n={n}: ratio={ratio} y={y:?} x={expect}"
690- );
691645 assert!(
692- y.im.abs() < 0.05 * expect.abs().max(1e-6),
693- "unexpected imaginary part at n={n}: {y:?}"
646+ y.norm_sqr().sqrt() < 0.15 * expect.abs(),
647+ "bw=0.98 should whiten at n={n}: y={y:?} x={expect}"
694648 );
695649 }
696650 }
crates/ec-aac/src/sbr_payload.rsmodified+80 -20
@@ -23,7 +23,7 @@ use ec_core::{BitReader, Error, Result};
2323 const NUM_TIME_SLOTS: i64 = 16;
2424
2525 /// `sbr_header()` fields, held across frames: a stream need not repeat it.
26-#[derive(Clone, Debug)]
26+#[derive(Clone, Debug, PartialEq, Eq)]
2727 pub struct SbrHeader {
2828 pub amp_res: u8,
2929 pub start_freq: u8,
@@ -60,6 +60,13 @@ pub struct SbrChannel {
6060 pub df_env: Vec<u8>,
6161 /// `bs_df_noise` per noise floor, same convention as `df_env`.
6262 pub df_noise: Vec<u8>,
63+ /// `l_A` (ISO/IEC 14496-3 §4.6.18.3.3): index of the envelope that starts
64+ /// at the transient border, `-1` when the frame has none. Gates where
65+ /// added sinusoids begin and which envelope skips noise/smoothing.
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,
6370 }
6471
6572 /// One `sbr_data()` frame: one channel for an SCE, two for a CPE.
@@ -79,31 +86,43 @@ struct Grid {
7986 freq_res: Vec<u8>,
8087 t_env: Vec<i64>,
8188 t_noise: Vec<i64>,
89+ l_a: i64,
90+ fixfix: bool,
8291 }
8392
8493 impl Grid {
85- /// `pointer` is `bs_pointer` (0 for FIXFIX, which has no such field --
86- /// the spec's own `bs_pointer == 0` case: the middle noise border is
87- /// `num_env >> 1`). Per ISO/IEC 14496-3 §4.6.18.3.3: `bs_pointer == 0`
88- /// selects `num_env >> 1`, `== 1` selects the last envelope border
89- /// (`num_env - 1`), otherwise `bs_pointer - 1`.
90- fn new(num_env: usize, freq_res: Vec<u8>, t_env: Vec<i64>, pointer: usize) -> Grid {
94+ /// `pointer` is `bs_pointer` (0 for FIXFIX, which has no such field).
95+ /// Middle noise border and `l_A` per ISO/IEC 14496-3 §4.6.18.3.3,
96+ /// Tables 4.146/4.147 -- they depend on `frame_class` (0 FIXFIX,
97+ /// 1 FIXVAR, 2 VARFIX, 3 VARVAR), not on `bs_pointer` alone.
98+ fn new(num_env: usize, freq_res: Vec<u8>, t_env: Vec<i64>, pointer: usize, frame_class: u32) -> Grid {
9199 let num_noise = if num_env == 1 { 1 } else { 2 };
92100 let t_noise = if num_noise == 1 {
93101 vec![t_env[0], t_env[num_env]]
94102 } else {
95- let middle = match pointer {
103+ let middle = match frame_class {
96104 0 => num_env >> 1,
97- 1 => num_env - 1,
98- p => p - 1,
105+ 1 | 3 => num_env - pointer.saturating_sub(1).max(1),
106+ _ => match pointer {
107+ 0 => 1,
108+ 1 => num_env - 1,
109+ p => p - 1,
110+ },
99111 };
100- vec![t_env[0], t_env[middle], t_env[num_env]]
112+ vec![t_env[0], t_env[middle.min(num_env)], t_env[num_env]]
113+ };
114+ let l_a = match frame_class {
115+ 1 | 3 if pointer > 0 => num_env as i64 + 1 - pointer as i64,
116+ 2 if pointer > 1 => pointer as i64 - 1,
117+ _ => -1,
101118 };
102119 Grid {
103120 num_env,
104121 freq_res,
105122 t_env,
106123 t_noise,
124+ l_a,
125+ fixfix: frame_class == 0,
107126 }
108127 }
109128 }
@@ -166,9 +185,43 @@ fn raw_env_width(balance: bool, amp_res: u8) -> u32 {
166185 const RAW_NOISE_WIDTH: u32 = 5;
167186
168187 /// A FIXFIX frame with a single envelope forces the 1.5 dB resolution
169-/// regardless of `bs_amp_res` (measured by the table-derivation rig).
170-fn amp_res_of(header_amp_res: u8, num_env: usize) -> u8 {
171- if num_env == 1 { 0 } else { header_amp_res }
188+/// regardless of `bs_amp_res` (§4.6.18.3.3); a one-envelope VARFIX/FIXVAR
189+/// frame keeps the header's value.
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 }
192+}
193+
194+/// Delta-time base for an envelope whose frequency resolution differs from
195+/// the envelope it is coded against (§4.6.18.3.3): a high-res band takes the
196+/// low-res band containing it, a low-res band the high-res band starting at
197+/// the same edge. Same resolution (or a degenerate table) passes through.
198+/// Without this the top half of a high-res row coded against a low-res row
199+/// read an out-of-range base of 0 -- a near-silent envelope -- and every
200+/// low-res band read the high-res band of half its frequency.
201+fn map_prev_env(prev: &[i32], tables: &BandTables, cur_high: bool) -> Vec<i32> {
202+ let (n_low, n_high) = (tables.n_low, tables.n_high);
203+ if n_low == n_high || prev.len() == if cur_high { n_high } else { n_low } {
204+ return prev.to_vec();
205+ }
206+ let (f_low, f_high) = (&tables.f_low, &tables.f_high);
207+ if cur_high {
208+ (0..n_high)
209+ .map(|j| {
210+ let k = (0..n_low)
211+ .rev()
212+ .find(|&k| f_low[k] <= f_high[j])
213+ .unwrap_or(0);
214+ prev.get(k).copied().unwrap_or(0)
215+ })
216+ .collect()
217+ } else {
218+ (0..n_low)
219+ .map(|j| {
220+ let k = (0..n_high).find(|&k| f_high[k] == f_low[j]).unwrap_or(0);
221+ prev.get(k).copied().unwrap_or(0)
222+ })
223+ .collect()
224+ }
172225 }
173226
174227 /// Reads one Huffman codeword by walking bit-by-bit until it matches a table
@@ -237,7 +290,7 @@ impl SbrParser {
237290 let t_env: Vec<i64> = (0..=num_env)
238291 .map(|i| (i as i64) * NUM_TIME_SLOTS / num_env as i64)
239292 .collect();
240- Ok(Grid::new(num_env, vec![fr; num_env], t_env, 0))
293+ Ok(Grid::new(num_env, vec![fr; num_env], t_env, 0, 0))
241294 }
242295 1 | 2 => {
243296 // FIXVAR (1, trailing variable border) / VARFIX (2, leading variable border)
@@ -285,7 +338,7 @@ impl SbrParser {
285338 }
286339 t[num_env] = NUM_TIME_SLOTS;
287340 }
288- Ok(Grid::new(num_env, freq_res, t, pointer))
341+ Ok(Grid::new(num_env, freq_res, t, pointer, frame_class))
289342 }
290343 _ => {
291344 // VARVAR
@@ -325,7 +378,7 @@ impl SbrParser {
325378 if t.windows(2).any(|w| w[0] >= w[1]) {
326379 return Err(Error::corrupt("sbr: non-monotone envelope time borders"));
327380 }
328- Ok(Grid::new(num_env, freq_res, t, pointer))
381+ Ok(Grid::new(num_env, freq_res, t, pointer, frame_class))
329382 }
330383 }
331384 }
@@ -535,7 +588,7 @@ impl SbrParser {
535588 let mut read_env = |this: &mut Self, r: &mut BitReader, ch: usize| -> Result<()> {
536589 let balance = is_cpe && coupling && ch == 1;
537590 let num_env = grids[ch].num_env;
538- let amp_res = amp_res_of(header.amp_res, num_env);
591+ let amp_res = amp_res_of(header.amp_res, &grids[ch]);
539592 let mut e_q: Vec<Vec<i32>> = Vec::with_capacity(num_env);
540593 for i in 0..num_env {
541594 let bands = if grids[ch].freq_res[i] != 0 {
@@ -549,7 +602,12 @@ impl SbrParser {
549602 } else {
550603 &this.state[ch].last_env
551604 };
552- let row = this.decode_envelope(r, bands, dt, balance, amp_res, prev)?;
605+ let prev = if dt {
606+ map_prev_env(prev, &tables, grids[ch].freq_res[i] != 0)
607+ } else {
608+ Vec::new()
609+ };
610+ let row = this.decode_envelope(r, bands, dt, balance, amp_res, &prev)?;
553611 e_q.push(row);
554612 }
555613 e_q_all[ch] = e_q;
@@ -593,7 +651,7 @@ impl SbrParser {
593651 for ch in 0..n_channels {
594652 let balance = is_cpe && coupling && ch == 1;
595653 let num_env = grids[ch].num_env;
596- let amp_res = amp_res_of(header.amp_res, num_env);
654+ let amp_res = amp_res_of(header.amp_res, &grids[ch]);
597655 let e_q = e_q_all[ch].clone();
598656 let q_q = q_q_all[ch].clone();
599657
@@ -628,6 +686,8 @@ impl SbrParser {
628686 add_harmonic: None,
629687 df_env: df_env[ch].iter().map(|&b| u8::from(b)).collect(),
630688 df_noise: df_noise[ch].iter().map(|&b| u8::from(b)).collect(),
689+ l_a: grids[ch].l_a,
690+ amp_res,
631691 });
632692 }
633693
crates/ec-aac/src/sbr_qmf.rsmodified+76 -40
@@ -2,27 +2,18 @@
22 //! analysis, folded to a shared core) and 4.6.18.8.2 (64-band synthesis)
33 //! polyphase machinery HE-AAC's spectral band replication is built on.
44 //!
5-//! # Bank sharing and the 32-band bridge
5+//! # Banks
66 //!
7-//! The spec defines two analysis banks (32-band, 4.6.18.4.1, and 64-band,
8-//! 4.6.18.4) and two synthesis banks (64-band, 4.6.18.8.2, and a downsampled
9-//! 32-band variant, 4.6.18.8.3). A numpy round-trip campaign (see
10-//! `scripts/aac-tables/qmf_check.py` and the ledger, round "sbr-hunt") found
11-//! the 64-band analysis/synthesis pair self-consistent to `corr=0.999999`
12-//! against the literal spec equations, but the 32-band analysis and 32-band
13-//! downsampled synthesis equations, and the 32-into-64 zero-padding bridge
14-//! the SBR core signal actually needs, never cleared 0.7 correlation under
15-//! the same exact-equation reading. Zero-stuffing the 32 core samples to 64
16-//! (`x64[2m] = 2*x32[m]`, odd samples 0) and running them through the
17-//! VERIFIED 64-band analysis, keeping bands `0..32` and dropping the
18-//! zero-stuffing image that lands in bands `32..64`, reached `corr=0.9994`
19-//! against an ideal band-limited 2x upsample -- short of the 0.9999 numpy
20-//! target but a real, spec-traceable near-PR bank, not a fitted
21-//! approximation. [`Analysis`] and [`HfAnalysis`] therefore share one
22-//! [`QmfAnalysis64`] core: the difference between them is only whether the
23-//! caller has 32 core samples (zero-stuffed by [`Analysis`]) or 64
24-//! already-doubled-rate samples ([`HfAnalysis`], used only for measurement).
25-//! [`Synthesis`] is the 64-band bank directly, unmodified for either caller.
7+//! [`Analysis`] is the 32-band core analysis (4.6.18.4.1: `c[2n]` taps over
8+//! 320 samples, 64-point modulation), [`Synthesis`] the 64-band bank
9+//! (4.6.18.8.2) and [`HfAnalysis`] a 64-band analysis used only by the
10+//! measurement instruments. The numpy round-trip campaign
11+//! (`scripts/aac-tables/qmf_check.py`, ledger round "sbr-hunt") verified the
12+//! 64-band pair to `corr=0.999999` against the literal equations; its
13+//! 32-band attempt used full-rate taps and a conjugated carrier, which is
14+//! why it "never cleared 0.7" and the bank shipped for a while as a
15+//! zero-stuffed 64-band bridge instead (see [`Analysis`] for the per-band
16+//! phase that bridge imposed on the HF patches).
2617 //!
2718 //! The Kaiser-windowed fitted bank this file used to build at construction
2819 //! time (`prototype`/`theta`/`modulation_tables`/`analytic_gain`, tuned by a
@@ -40,11 +31,6 @@ pub const ANALYSIS_BANDS: usize = 32;
4031 /// Synthesis channel count (twice the core's, spanning the doubled band).
4132 pub const SYNTHESIS_BANDS: usize = 64;
4233
43-/// Zero-stuffing gain the 32-into-64 bridge needs to read back unity
44-/// amplitude (numpy-measured: `gain=2.0` gives `amp_ratio ~ 0.999`, `gain=1`
45-/// halves it -- the standard zero-stuffing compensation for a 2x upsample).
46-const ZERO_STUFF_GAIN: f64 = 2.0;
47-
4834 /// The shared ISO/IEC 14496-3 4.6.18.4 64-band analysis core: `PROTO_LEN`
4935 /// real history samples in (newest inserted last, matching PCM order),
5036 /// `SYNTHESIS_BANDS` complex subbands out per slot of `SYNTHESIS_BANDS` new
@@ -106,20 +92,50 @@ impl QmfAnalysis64 {
10692 }
10793 }
10894
109-/// The 32-band bridge: core PCM in (32 samples/slot), complex subband slots
110-/// out (32/slot), via zero-stuffing into the verified 64-band core and
111-/// keeping the low half (see the module doc for why this replaces a native
112-/// 32-band analysis).
95+/// ISO/IEC 14496-3 4.6.18.4.1 32-band analysis: core PCM in (32
96+/// samples/slot), 32 complex subbands out, the decimated prototype `c[2n]`
97+/// over a 320-sample history and carrier `exp(j*pi/64*(k+0.5)*(2n-0.5))`
98+/// (see `new` for the -0.5).
99+///
100+/// Replaces the zero-stuffed 64-band bridge: numpy
101+/// (`scripts/aac-tables/qmf_check.py` lineage) shows the bridge equals the
102+/// literal `(2n-1)` bank times `2 * exp(j*pi/64*(k+0.5)*1.5)` per band --
103+/// a 1.5-sample (at the doubled rate) delay plus 2x gain. Harmless for the
104+/// low band (the synthesis undoes both), but the HF generator copies band
105+/// `p`'s subband signal into band `k`, where a per-band phase becomes a
106+/// constant carrier error against the reference.
113107 pub struct Analysis {
114- core: QmfAnalysis64,
108+ hist: [f64; PROTO_LEN / 2],
109+ cos_tab: Vec<f64>,
110+ sin_tab: Vec<f64>,
115111 }
116112
117113 impl Analysis {
118114 /// A fresh bank with an all-zero history (the usual filter startup
119115 /// transient applies to its first ~`PROTO_LEN` output samples).
120116 pub fn new() -> Analysis {
117+ let mut cos_tab = vec![0.0f64; ANALYSIS_BANDS * 64];
118+ let mut sin_tab = vec![0.0f64; ANALYSIS_BANDS * 64];
119+ for k in 0..ANALYSIS_BANDS {
120+ for n in 0..64 {
121+ // Carrier offset -0.5, not the text's -1: measured against the
122+ // reference decoder's PCM (real-file test, probe sweep over
123+ // -1/-0.5/0/+0.5 on both banks) the reference's low band
124+ // sits exactly half an output sample EARLIER than the
125+ // literal (2n-1) bank and, unlike a synthesis-side shift,
126+ // that half sample is carried by the HF copies too
127+ // (above-5 kHz corr 0.9997 vs 0.9995 synthesis-side, 0.984
128+ // literal). Equivalent to a 64-band analysis of the core
129+ // zero-stuffed at the ODD phase.
130+ let theta = std::f64::consts::PI / 64.0 * (k as f64 + 0.5) * (2.0 * n as f64 - 0.5);
131+ cos_tab[k * 64 + n] = theta.cos();
132+ sin_tab[k * 64 + n] = theta.sin();
133+ }
134+ }
121135 Analysis {
122- core: QmfAnalysis64::new(),
136+ hist: [0.0; PROTO_LEN / 2],
137+ cos_tab,
138+ sin_tab,
123139 }
124140 }
125141
@@ -130,13 +146,26 @@ impl Analysis {
130146 &mut self,
131147 samples: &[f32; ANALYSIS_BANDS],
132148 ) -> [Complex<f64>; ANALYSIS_BANDS] {
133- let mut x64 = [0.0f64; SYNTHESIS_BANDS];
134- for (m, &s) in samples.iter().enumerate() {
135- x64[2 * m] = ZERO_STUFF_GAIN * s as f64;
149+ const LEN: usize = PROTO_LEN / 2;
150+ for &s in samples {
151+ self.hist.copy_within(0..LEN - 1, 1);
152+ self.hist[0] = s as f64;
153+ }
154+ // Z[n] = x[n]*c[2n], n=0..319; u[n] = sum_{j=0}^{4} Z[n+64j], n=0..63
155+ let mut u = [0.0f64; 64];
156+ for (n, uu) in u.iter_mut().enumerate() {
157+ *uu = (0..5).map(|j| self.hist[n + 64 * j] * QMF_WINDOW[2 * (n + 64 * j)]).sum();
136158 }
137- let full = self.core.process_slot(&x64);
138159 let mut out = [Complex::new(0.0, 0.0); ANALYSIS_BANDS];
139- out.copy_from_slice(&full[0..ANALYSIS_BANDS]);
160+ for (k, slot) in out.iter_mut().enumerate() {
161+ let row = k * 64;
162+ let (mut re, mut im) = (0.0f64, 0.0f64);
163+ for n in 0..64 {
164+ re += u[n] * self.cos_tab[row + n];
165+ im += u[n] * self.sin_tab[row + n];
166+ }
167+ *slot = Complex::new(re, im);
168+ }
140169 out
141170 }
142171 }
@@ -315,11 +344,18 @@ mod tests {
315344 fft.forward(&mut spectrum);
316345
317346 let mut padded = vec![Complex::new(0.0, 0.0); 2 * n];
347+ // The 32-analysis/64-synthesis pair reads back at half amplitude
348+ // and 1 output sample later than the zero-stuffed bridge did; fold
349+ // both into the ground truth.
350+ let delay = |m: f64| {
351+ let ph = -2.0 * std::f64::consts::PI * m / (2 * n) as f64;
352+ Complex::new(ph.cos(), ph.sin())
353+ };
318354 for k in 0..n / 2 {
319- padded[k] = spectrum[k].scale(2.0);
355+ padded[k] = spectrum[k].scale(2.0) * delay(k as f64);
320356 }
321357 for k in n / 2..n {
322- padded[2 * n - n + k] = spectrum[k].scale(2.0);
358+ padded[2 * n - n + k] = spectrum[k].scale(2.0) * delay(k as f64 - n as f64);
323359 }
324360 let mut fft2 = Fft::<f64>::new(2 * n);
325361 fft2.inverse(&mut padded);
@@ -411,8 +447,8 @@ mod tests {
411447 "measured filterbank delay: {best_lag} samples, correlation {best_corr:.6}, amplitude ratio {amp_ratio:.6}"
412448 );
413449 assert!(
414- (0.98..=1.02).contains(&amp_ratio),
415- "round-trip amplitude ratio {amp_ratio} not within 2% of unity gain"
450+ (0.49..=0.51).contains(&amp_ratio),
451+ "round-trip amplitude ratio {amp_ratio} not within 2% of the spec pair's 0.5 (sbr_chain restores the 2x)"
416452 );
417453 assert!(
418454 best_corr >= 0.9999,
crates/ec-aac/src/sbr_tables.rsmodified+611 -86
@@ -7,6 +7,13 @@
77 //! `env_facs_q`/`noise_facs_q` range check reads the delta value each
88 //! codeword carries off the same payload. Every table here closed with
99 //! a Kraft sum of exactly 1 (asserted below).
10+//!
11+//! GENERATED: books by `sbrtables.py --stage values`, then the four 3.0 dB
12+//! books (`ENV30_F`, `ENV30_T`, `ENVB30_F`, `ENVB30_T`) re-valued in place by
13+//! `scripts/aac-tables/sbrvalues.py`, which walks each codeword's delta out
14+//! of range by delta-time ACCUMULATION (a single +d on the 6-bit 3 dB raw
15+//! field never reaches the 7-bit ceiling, so the one-shot stage read every
16+//! positive 3 dB delta as 0). Do not hand-edit the books.
1017 #![allow(dead_code)]
1118
1219 /// SBR Huffman book `ENV15_F`: (length, code, delta) by codeword.
@@ -263,31 +270,31 @@ pub(crate) static ENV15_T: [(u8, u32, i32); 121] = [
263270 pub(crate) static ENV30_T: [(u8, u32, i32); 63] = [
264271 (1, 0, 0),
265272 (2, 2, -1),
266- (3, 6, 0),
273+ (3, 6, 1),
267274 (4, 14, -2),
268- (5, 30, 0),
275+ (5, 30, 2),
269276 (6, 62, -3),
270- (7, 126, 0),
277+ (7, 126, 3),
271278 (8, 254, -4),
272- (9, 510, 0),
279+ (9, 510, 4),
273280 (11, 2044, -5),
274- (11, 2045, 0),
281+ (11, 2045, 5),
275282 (12, 4092, -6),
276283 (13, 8186, -7),
277- (13, 8187, 0),
284+ (13, 8187, 6),
278285 (14, 16376, -8),
279- (14, 16377, 0),
286+ (14, 16377, 7),
280287 (14, 16378, -9),
281288 (14, 16379, -10),
282- (14, 16380, 0),
283- (15, 32762, 0),
284- (16, 65526, 0),
289+ (14, 16380, 8),
290+ (15, 32762, 9),
291+ (16, 65526, 10),
285292 (16, 65527, -13),
286293 (16, 65528, -11),
287294 (16, 65529, -12),
288295 (17, 131060, -14),
289- (17, 131061, 0),
290- (18, 262124, 0),
296+ (17, 131061, 11),
297+ (18, 262124, 12),
291298 (18, 262125, -31),
292299 (18, 262126, -30),
293300 (19, 524254, -29),
@@ -305,76 +312,76 @@ pub(crate) static ENV30_T: [(u8, u32, i32); 63] = [
305312 (19, 524266, -17),
306313 (19, 524267, -16),
307314 (19, 524268, -15),
308- (19, 524269, 0),
309- (19, 524270, 0),
310- (19, 524271, 0),
311- (19, 524272, 0),
312- (19, 524273, 0),
313- (19, 524274, 0),
314- (19, 524275, 0),
315- (19, 524276, 0),
316- (19, 524277, 0),
317- (19, 524278, 0),
318- (19, 524279, 0),
319- (19, 524280, 0),
320- (19, 524281, 0),
321- (19, 524282, 0),
322- (19, 524283, 0),
323- (19, 524284, 0),
324- (19, 524285, 0),
325- (19, 524286, 0),
326- (19, 524287, 0),
315+ (19, 524269, 13),
316+ (19, 524270, 14),
317+ (19, 524271, 15),
318+ (19, 524272, 16),
319+ (19, 524273, 17),
320+ (19, 524274, 18),
321+ (19, 524275, 19),
322+ (19, 524276, 20),
323+ (19, 524277, 21),
324+ (19, 524278, 22),
325+ (19, 524279, 23),
326+ (19, 524280, 24),
327+ (19, 524281, 25),
328+ (19, 524282, 26),
329+ (19, 524283, 27),
330+ (19, 524284, 28),
331+ (19, 524285, 29),
332+ (19, 524286, 30),
333+ (19, 524287, 31),
327334 ];
328335
329336 /// SBR Huffman book `ENV30_F`: (length, code, delta) by codeword.
330337 pub(crate) static ENV30_F: [(u8, u32, i32); 63] = [
331338 (1, 0, 0),
332339 (2, 2, -1),
333- (3, 6, 0),
340+ (3, 6, 1),
334341 (4, 14, -2),
335- (5, 30, 0),
342+ (5, 30, 2),
336343 (6, 62, -3),
337- (8, 252, 0),
344+ (8, 252, 3),
338345 (8, 253, -4),
339- (9, 508, 0),
346+ (9, 508, 4),
340347 (9, 509, -5),
341- (10, 1020, 0),
348+ (10, 1020, 5),
342349 (10, 1021, -6),
343- (11, 2044, 0),
350+ (11, 2044, 6),
344351 (11, 2045, -7),
345- (12, 4092, 0),
352+ (12, 4092, 7),
346353 (12, 4093, -8),
347- (13, 8188, 0),
348- (14, 16378, 0),
354+ (13, 8188, 8),
355+ (14, 16378, 9),
349356 (14, 16379, -9),
350357 (15, 32760, -10),
351- (15, 32761, 0),
352- (15, 32762, 0),
358+ (15, 32761, 10),
359+ (15, 32762, 11),
353360 (16, 65526, -11),
354361 (16, 65527, -12),
355- (16, 65528, 0),
356- (16, 65529, 0),
362+ (16, 65528, 12),
363+ (16, 65529, 13),
357364 (17, 131060, -13),
358365 (17, 131061, -15),
359- (17, 131062, 0),
360- (17, 131063, 0),
366+ (17, 131062, 14),
367+ (17, 131063, 15),
361368 (18, 262128, -14),
362- (18, 262129, 0),
369+ (18, 262129, 18),
363370 (18, 262130, -18),
364371 (18, 262131, -24),
365372 (18, 262132, -19),
366- (18, 262133, 0),
367- (18, 262134, 0),
373+ (18, 262133, 16),
374+ (18, 262134, 17),
368375 (19, 524270, -22),
369376 (19, 524271, -21),
370377 (19, 524272, -16),
371- (19, 524273, 0),
372- (19, 524274, 0),
373- (19, 524275, 0),
374- (19, 524276, 0),
378+ (19, 524273, 20),
379+ (19, 524274, 21),
380+ (19, 524275, 22),
381+ (19, 524276, 25),
375382 (19, 524277, -23),
376383 (19, 524278, -20),
377- (19, 524279, 0),
384+ (19, 524279, 24),
378385 (20, 1048560, -31),
379386 (20, 1048561, -30),
380387 (20, 1048562, -29),
@@ -383,14 +390,14 @@ pub(crate) static ENV30_F: [(u8, u32, i32); 63] = [
383390 (20, 1048565, -26),
384391 (20, 1048566, -25),
385392 (20, 1048567, -17),
386- (20, 1048568, 0),
387- (20, 1048569, 0),
388- (20, 1048570, 0),
389- (20, 1048571, 0),
390- (20, 1048572, 0),
391- (20, 1048573, 0),
392- (20, 1048574, 0),
393- (20, 1048575, 0),
393+ (20, 1048568, 19),
394+ (20, 1048569, 23),
395+ (20, 1048570, 26),
396+ (20, 1048571, 27),
397+ (20, 1048572, 28),
398+ (20, 1048573, 29),
399+ (20, 1048574, 30),
400+ (20, 1048575, 31),
394401 ];
395402
396403 /// SBR Huffman book `NOISE_T`: (length, code, delta) by codeword.
@@ -636,14 +643,14 @@ pub(crate) static ENVB15_T: [(u8, u32, i32); 49] = [
636643 /// SBR Huffman book `ENVB30_T`: (length, code, delta) by codeword.
637644 pub(crate) static ENVB30_T: [(u8, u32, i32); 25] = [
638645 (1, 0, 0),
639- (2, 2, 0),
646+ (2, 2, 1),
640647 (3, 6, -1),
641648 (4, 14, -2),
642- (5, 30, 0),
643- (6, 62, 0),
649+ (5, 30, 2),
650+ (6, 62, 3),
644651 (7, 126, -3),
645652 (8, 254, -4),
646- (9, 510, 0),
653+ (9, 510, 4),
647654 (12, 4088, -5),
648655 (13, 8178, -12),
649656 (13, 8179, -11),
@@ -652,30 +659,30 @@ pub(crate) static ENVB30_T: [(u8, u32, i32); 25] = [
652659 (13, 8182, -8),
653660 (13, 8183, -7),
654661 (13, 8184, -6),
655- (13, 8185, 0),
656- (13, 8186, 0),
657- (13, 8187, 0),
658- (13, 8188, 0),
659- (13, 8189, 0),
660- (13, 8190, 0),
661- (14, 16382, 0),
662- (14, 16383, 0),
662+ (13, 8185, 5),
663+ (13, 8186, 6),
664+ (13, 8187, 7),
665+ (13, 8188, 8),
666+ (13, 8189, 9),
667+ (13, 8190, 10),
668+ (14, 16382, 11),
669+ (14, 16383, 12),
663670 ];
664671
665672 /// SBR Huffman book `ENVB30_F`: (length, code, delta) by codeword.
666673 pub(crate) static ENVB30_F: [(u8, u32, i32); 25] = [
667674 (1, 0, 0),
668675 (2, 2, -1),
669- (3, 6, 0),
676+ (3, 6, 1),
670677 (4, 14, -2),
671- (5, 30, 0),
672- (6, 62, 0),
678+ (5, 30, 2),
679+ (6, 62, 3),
673680 (7, 126, -3),
674681 (8, 254, -4),
675- (9, 510, 0),
682+ (9, 510, 4),
676683 (11, 2044, -5),
677- (12, 4090, 0),
678- (13, 8182, 0),
684+ (12, 4090, 5),
685+ (13, 8182, 6),
679686 (13, 8183, -12),
680687 (13, 8184, -11),
681688 (13, 8185, -10),
@@ -683,12 +690,12 @@ pub(crate) static ENVB30_F: [(u8, u32, i32); 25] = [
683690 (13, 8187, -8),
684691 (14, 16376, -7),
685692 (14, 16377, -6),
686- (14, 16378, 0),
687- (14, 16379, 0),
688- (14, 16380, 0),
689- (14, 16381, 0),
690- (14, 16382, 0),
691- (14, 16383, 0),
693+ (14, 16378, 7),
694+ (14, 16379, 8),
695+ (14, 16380, 9),
696+ (14, 16381, 10),
697+ (14, 16382, 11),
698+ (14, 16383, 12),
692699 ];
693700
694701 /// SBR Huffman book `NOISEB_T`: (length, code, delta) by codeword.
@@ -749,6 +756,524 @@ pub(crate) static NOISEB_F: [(u8, u32, i32); 25] = [
749756 (14, 16383, 12),
750757 ];
751758
759+/// ISO/IEC 14496-3 Table 4.A.88: the 512-entry complex noise sequence
760+/// `V` the envelope adjuster draws from (`f_IndexNoise` wraps at 512), as
761+/// `(re, im)` pairs.
762+pub(crate) static SBR_NOISE: [(f64, f64); 512] = [
763+ (-0.99948153278296, -0.59483417516607),
764+ (0.97113454393991, -0.67528515225647),
765+ (0.14130051758487, -0.95090983575689),
766+ (-0.47005496701697, -0.37340549728647),
767+ (0.80705063769351, 0.29653668284408),
768+ (-0.38981478896926, 0.89572605717087),
769+ (-0.01053049862020, -0.66959058036166),
770+ (-0.91266367957293, -0.11522938140034),
771+ (0.54840422910309, 0.75221367176302),
772+ (0.40009252867955, -0.98929400334421),
773+ (-0.99867974711855, -0.88147068645358),
774+ (-0.95531076805040, 0.90908757154593),
775+ (-0.45725933317144, -0.56716323646760),
776+ (-0.72929675029275, -0.98008272727324),
777+ (0.75622801399036, 0.20950329995549),
778+ (0.07069442601050, -0.78247898470706),
779+ (0.74496252926055, -0.91169004445807),
780+ (-0.96440182703856, -0.94739918296622),
781+ (0.30424629369539, -0.49438267012479),
782+ (0.66565033746925, 0.64652935542491),
783+ (0.91697008020594, 0.17514097332009),
784+ (-0.70774918760427, 0.52548653416543),
785+ (-0.70051415345560, -0.45340028808763),
786+ (-0.99496513054797, -0.90071908066973),
787+ (0.98164490790123, -0.77463155528697),
788+ (-0.54671580548181, -0.02570928536004),
789+ (-0.01689629065389, 0.00287506445732),
790+ (-0.86110349531986, 0.42548583726477),
791+ (-0.98892980586032, -0.87881132267556),
792+ (0.51756627678691, 0.66926784710139),
793+ (-0.99635026409640, -0.58107730574765),
794+ (-0.99969370862163, 0.98369989360250),
795+ (0.55266258627194, 0.59449057465591),
796+ (0.34581177741673, 0.94879421061866),
797+ (0.62664209577999, -0.74402970906471),
798+ (-0.77149701404973, -0.33883658042801),
799+ (-0.91592244254432, 0.03687901376713),
800+ (-0.76285492357887, -0.91371867919124),
801+ (0.79788337195331, -0.93180971199849),
802+ (0.54473080610200, -0.11919206037186),
803+ (-0.85639281671058, 0.42429854760451),
804+ (-0.92882402971423, 0.27871809078609),
805+ (-0.11708371046774, -0.99800843444966),
806+ (0.21356749817493, -0.90716295627033),
807+ (-0.76191692573909, 0.99768118356265),
808+ (0.98111043100884, -0.95854459734407),
809+ (-0.85913269895572, 0.95766566168880),
810+ (-0.93307242253692, 0.49431757696466),
811+ (0.30485754879632, -0.70540034357529),
812+ (0.85289650925190, 0.46766131791044),
813+ (0.91328082618125, -0.99839597361769),
814+ (-0.05890199924154, 0.70741827819497),
815+ (0.28398686150148, 0.34633555702188),
816+ (0.95258164539612, -0.54893416026939),
817+ (-0.78566324168507, -0.75568541079691),
818+ (-0.95789495447877, -0.20423194696966),
819+ (0.82411158711197, 0.96654618432562),
820+ (-0.65185446735885, -0.88734990773289),
821+ (-0.93643603134666, 0.99870790442385),
822+ (0.91427159529618, -0.98290505544444),
823+ (-0.70395684036886, 0.58796798221039),
824+ (0.00563771969365, 0.61768196727244),
825+ (0.89065051931895, 0.52783352697585),
826+ (-0.68683707712762, 0.80806944710339),
827+ (0.72165342518718, -0.69259857349564),
828+ (-0.62928247730667, 0.13627037407335),
829+ (0.29938434065514, -0.46051329682246),
830+ (-0.91781958879280, -0.74012716684186),
831+ (0.99298717043688, 0.40816610075661),
832+ (0.82368298622748, -0.74036047190173),
833+ (-0.98512833386833, -0.99972330709594),
834+ (-0.95915368242257, -0.99237800466040),
835+ (-0.21411126572790, -0.93424819052545),
836+ (-0.68821476106884, -0.26892306315457),
837+ (0.91851997982317, 0.09358228901785),
838+ (-0.96062769559127, 0.36099095133739),
839+ (0.51646184922287, -0.71373332873917),
840+ (0.61130721139669, 0.46950141175917),
841+ (0.47336129371299, -0.27333178296162),
842+ (0.90998308703519, 0.96715662938132),
843+ (0.44844799194357, 0.99211574628306),
844+ (0.66614891079092, 0.96590176169121),
845+ (0.74922239129237, -0.89879858826087),
846+ (-0.99571588506485, 0.52785521494349),
847+ (0.97401082477563, -0.16855870075190),
848+ (0.72683747733879, -0.48060774432251),
849+ (0.95432193457128, 0.68849603408441),
850+ (-0.72962208425191, -0.76608443420917),
851+ (-0.85359479233537, 0.88738125901579),
852+ (-0.81412430338535, -0.97480768049637),
853+ (-0.87930772356786, 0.74748307690436),
854+ (-0.71573331064977, -0.98570608178923),
855+ (0.83524300028228, 0.83702537075163),
856+ (-0.48086065601423, -0.98848504923531),
857+ (0.97139128574778, 0.80093621198236),
858+ (0.51992825347895, 0.80247631400510),
859+ (-0.00848591195325, -0.76670128000486),
860+ (-0.70294374303036, 0.55359910445577),
861+ (-0.95894428168140, -0.43265504344783),
862+ (0.97079252950321, 0.09325857238682),
863+ (-0.92404293670797, 0.85507704027855),
864+ (-0.69506469500450, 0.98633412625459),
865+ (0.26559203620024, 0.73314307966524),
866+ (0.28038443336943, 0.14537913654427),
867+ (-0.74138124825523, 0.99310339807762),
868+ (-0.01752795995444, -0.82616635284178),
869+ (-0.55126773094930, -0.98898543862153),
870+ (0.97960898850996, -0.94021446752851),
871+ (-0.99196309146936, 0.67019017358456),
872+ (-0.67684928085260, 0.12631491649378),
873+ (0.09140039465500, -0.20537731453108),
874+ (-0.71658965751996, -0.97788200391224),
875+ (0.81014640078925, 0.53722648362443),
876+ (0.40616991671205, -0.26469008598449),
877+ (-0.67680188682972, 0.94502052337695),
878+ (0.86849774348749, -0.18333598647899),
879+ (-0.99500381284851, -0.02634122068550),
880+ (0.84329189340667, 0.10406957462213),
881+ (-0.09215968531446, 0.69540012101253),
882+ (0.99956173327206, -0.12358542001404),
883+ (-0.79732779473535, -0.91582524736159),
884+ (0.96349973642406, 0.96640458041000),
885+ (-0.79942778496547, 0.64323902822857),
886+ (-0.11566039853896, 0.28587846253726),
887+ (-0.39922954514662, 0.94129601616966),
888+ (0.99089197565987, -0.92062625581587),
889+ (0.28631285179909, -0.91035047143603),
890+ (-0.83302725605608, -0.67330410892084),
891+ (0.95404443402072, 0.49162765398743),
892+ (-0.06449863579434, 0.03250560813135),
893+ (-0.99575054486311, 0.42389784469507),
894+ (-0.65501142790847, 0.82546114655624),
895+ (-0.81254441908887, -0.51627234660629),
896+ (-0.99646369485481, 0.84490533520752),
897+ (0.00287840603348, 0.64768261158166),
898+ (0.70176989408455, -0.20453028573322),
899+ (0.96361882270190, 0.40706967140989),
900+ (-0.68883758192426, 0.91338958840772),
901+ (-0.34875585502238, 0.71472290693300),
902+ (0.91980081243087, 0.66507455644919),
903+ (-0.99009048343881, 0.85868021604848),
904+ (0.68865791458395, 0.55660316809678),
905+ (-0.99484402129368, -0.20052559254934),
906+ (0.94214511408023, -0.99696425367461),
907+ (-0.67414626793544, 0.49548221180078),
908+ (-0.47339353684664, -0.85904328834047),
909+ (0.14323651387360, -0.94145598222488),
910+ (-0.29268293575672, 0.05759224927952),
911+ (0.43793861458754, -0.78904969892724),
912+ (-0.36345126374441, 0.64874435357162),
913+ (-0.08750604656825, 0.97686944362527),
914+ (-0.96495267812511, -0.53960305946511),
915+ (0.55526940659947, 0.78891523734774),
916+ (0.73538215752630, 0.96452072373404),
917+ (-0.30889773919437, -0.80664389776860),
918+ (0.03574995626194, -0.97325616900959),
919+ (0.98720684660488, 0.48409133691962),
920+ (-0.81689296271203, -0.90827703628298),
921+ (0.67866860118215, 0.81284503870856),
922+ (-0.15808569732583, 0.85279555024382),
923+ (0.80723395114371, -0.24717418514605),
924+ (0.47788757329038, -0.46333147839295),
925+ (0.96367554763201, 0.38486749303242),
926+ (-0.99143875716818, -0.24945277239809),
927+ (0.83081876925833, -0.94780851414763),
928+ (-0.58753191905341, 0.01290772389163),
929+ (0.95538108220960, -0.85557052096538),
930+ (-0.96490920476211, -0.64020970923102),
931+ (-0.97327101028521, 0.12378128133110),
932+ (0.91400366022124, 0.57972471346930),
933+ (-0.99925837363824, 0.71084847864067),
934+ (-0.86875903507313, -0.20291699203564),
935+ (-0.26240034795124, -0.68264554369108),
936+ (-0.24664412953388, -0.87642273115183),
937+ (0.02416275806869, 0.27192914288905),
938+ (0.82068619590515, -0.85087787994476),
939+ (0.88547373760759, -0.89636802901469),
940+ (-0.18173078152226, -0.26152145156800),
941+ (0.09355476558534, 0.54845123045604),
942+ (-0.54668414224090, 0.95980774020221),
943+ (0.37050990604091, -0.59910140383171),
944+ (-0.70373594262891, 0.91227665827081),
945+ (-0.34600785879594, -0.99441426144200),
946+ (-0.68774481731008, -0.30238837956299),
947+ (-0.26843291251234, 0.83115668004362),
948+ (0.49072334613242, -0.45359708737775),
949+ (0.38975993093975, 0.95515358099121),
950+ (-0.97757125224150, 0.05305894580606),
951+ (-0.17325552859616, -0.92770672250494),
952+ (0.99948035025744, 0.58285545563426),
953+ (-0.64946246527458, 0.68645507104960),
954+ (-0.12016920576437, -0.57147322153312),
955+ (-0.58947456517751, -0.34847132454388),
956+ (-0.41815140454465, 0.16276422358861),
957+ (0.99885650204884, 0.11136095490444),
958+ (-0.56649614128386, -0.90494866361587),
959+ (0.94138021032330, 0.35281916733018),
960+ (-0.75725076534641, 0.53650549640587),
961+ (0.20541973692630, -0.94435144369918),
962+ (0.99980371023351, 0.79835913565599),
963+ (0.29078277605775, 0.35393777921520),
964+ (-0.62858772103030, 0.38765693387102),
965+ (0.43440904467688, -0.98546330463232),
966+ (-0.98298583762390, 0.21021524625209),
967+ (0.19513029146934, -0.94239832251867),
968+ (-0.95476662400101, 0.98364554179143),
969+ (0.93379635304810, -0.70881994583682),
970+ (-0.85235410573336, -0.08342347966410),
971+ (-0.86425093011245, -0.45795025029466),
972+ (0.38879779059045, 0.97274429344593),
973+ (0.92045124735495, -0.62433652524220),
974+ (0.89162532251878, 0.54950955570563),
975+ (-0.36834336949252, 0.96458298020975),
976+ (0.93891760988045, -0.89968353740388),
977+ (0.99267657565094, -0.03757034316958),
978+ (-0.94063471614176, 0.41332338538963),
979+ (0.99740224117019, -0.16830494996370),
980+ (-0.35899413170555, -0.46633226649613),
981+ (0.05237237274947, -0.25640361602661),
982+ (0.36703583957424, -0.38653265641875),
983+ (0.91653180367913, -0.30587628726597),
984+ (0.69000803499316, 0.90952171386132),
985+ (-0.38658751133527, 0.99501571208985),
986+ (-0.29250814029851, 0.37444994344615),
987+ (-0.60182204677608, 0.86779651036123),
988+ (-0.97418588163217, 0.96468523666475),
989+ (0.88461574003963, 0.57508405276414),
990+ (0.05198933055162, 0.21269661669964),
991+ (-0.53499621979720, 0.97241553731237),
992+ (-0.49429560226497, 0.98183865291903),
993+ (-0.98935142339139, -0.40249159006933),
994+ (-0.98081380091130, -0.72856895534041),
995+ (-0.27338148835532, 0.99950922447209),
996+ (0.06310802338302, -0.54539587529618),
997+ (-0.20461677199539, -0.14209977628489),
998+ (0.66223843141647, 0.72528579940326),
999+ (-0.84764345483665, 0.02372316801261),
1000+ (-0.89039863483811, 0.88866581484602),
1001+ (0.95903308477986, 0.76744927173873),
1002+ (0.73504123909879, -0.03747203173192),
1003+ (-0.31744434966056, -0.36834111883652),
1004+ (-0.34110827591623, 0.40211222807691),
1005+ (0.47803883714199, -0.39423219786288),
1006+ (0.98299195879514, 0.01989791390047),
1007+ (-0.30963073129751, -0.18076720599336),
1008+ (0.99992588229018, -0.26281872094289),
1009+ (-0.93149731080767, -0.98313162570490),
1010+ (0.99923472302773, -0.80142993767554),
1011+ (-0.26024169633417, -0.75999759855752),
1012+ (-0.35712514743563, 0.19298963768574),
1013+ (-0.99899084509530, 0.74645156992493),
1014+ (0.86557171579452, 0.55593866696299),
1015+ (0.33408042438752, 0.86185953874709),
1016+ (0.99010736374716, 0.04602397576623),
1017+ (-0.66694269691195, -0.91643611810148),
1018+ (0.64016792079480, 0.15649530836856),
1019+ (0.99570534804836, 0.45844586038111),
1020+ (-0.63431466947340, 0.21079116459234),
1021+ (-0.07706847005931, -0.89581437101329),
1022+ (0.98590090577724, 0.88241721133981),
1023+ (0.80099335254678, -0.36851896710853),
1024+ (0.78368131392666, 0.45506999802597),
1025+ (0.08707806671691, 0.80938994918745),
1026+ (-0.86811883080712, 0.39347308654705),
1027+ (-0.39466529740375, -0.66809432114456),
1028+ (0.97875325649683, -0.72467840967746),
1029+ (-0.95038560288864, 0.89563219587625),
1030+ (0.17005239424212, 0.54683053962658),
1031+ (-0.76910792026848, -0.96226617549298),
1032+ (0.99743281016846, 0.42697157037567),
1033+ (0.95437383549973, 0.97002324109952),
1034+ (0.99578905365569, -0.54106826257356),
1035+ (0.28058259829990, -0.85361420634036),
1036+ (0.85256524470573, -0.64567607735589),
1037+ (-0.50608540105128, -0.65846015480300),
1038+ (-0.97210735183243, -0.23095213067791),
1039+ (0.95424048234441, -0.99240147091219),
1040+ (-0.96926570524023, 0.73775654896574),
1041+ (0.30872163214726, 0.41514960556126),
1042+ (-0.24523839572639, 0.63206633394807),
1043+ (-0.33813265086024, -0.38661779441897),
1044+ (-0.05826828420146, -0.06940774188029),
1045+ (-0.22898461455054, 0.97054853316316),
1046+ (-0.18509915019881, 0.47565762892084),
1047+ (-0.10488238045009, -0.87769947402394),
1048+ (-0.71886586182037, 0.78030982480538),
1049+ (0.99793873738654, 0.90041310491497),
1050+ (0.57563307626120, -0.91034337352097),
1051+ (0.28909646383717, 0.96307783970534),
1052+ (0.42188998312520, 0.48148651230437),
1053+ (0.93335049681047, -0.43537023883588),
1054+ (-0.97087374418267, 0.86636445711364),
1055+ (0.36722871286923, 0.65291654172961),
1056+ (-0.81093025665696, 0.08778370229363),
1057+ (-0.26240603062237, -0.92774095379098),
1058+ (0.83996497984604, 0.55839849139647),
1059+ (-0.99909615720225, -0.96024605713970),
1060+ (0.74649464155061, 0.12144893606462),
1061+ (-0.74774595569805, -0.26898062008959),
1062+ (0.95781667469567, -0.79047927052628),
1063+ (0.95472308713099, -0.08588776019550),
1064+ (0.48708332746299, 0.99999041579432),
1065+ (0.46332038247497, 0.10964126185063),
1066+ (-0.76497004940162, 0.89210929242238),
1067+ (0.57397389364339, 0.35289703373760),
1068+ (0.75374316974495, 0.96705214651335),
1069+ (-0.59174397685714, -0.89405370422752),
1070+ (0.75087906691890, -0.29612672982396),
1071+ (-0.98607857336230, 0.25034911730023),
1072+ (-0.40761056640505, -0.90045573444695),
1073+ (0.66929266740477, 0.98629493401748),
1074+ (-0.97463695257310, -0.00190223301301),
1075+ (0.90145509409859, 0.99781390365446),
1076+ (-0.87259289048043, 0.99233587353666),
1077+ (-0.91529461447692, -0.15698707534206),
1078+ (-0.03305738840705, -0.37205262859764),
1079+ (0.07223051368337, -0.88805001733626),
1080+ (0.99498012188353, 0.97094358113387),
1081+ (-0.74904939500519, 0.99985483641521),
1082+ (0.04585228574211, 0.99812337444082),
1083+ (-0.89054954257993, -0.31791913188064),
1084+ (-0.83782144651251, 0.97637632547466),
1085+ (0.33454804933804, -0.86231516800408),
1086+ (-0.99707579362824, 0.93237990079441),
1087+ (-0.22827527843994, 0.18874759397997),
1088+ (0.67248046289143, -0.03646211390569),
1089+ (-0.05146538187944, -0.92599700120679),
1090+ (0.99947295749905, 0.93625229707912),
1091+ (0.66951124390363, 0.98905825623893),
1092+ (-0.99602956559179, -0.44654715757688),
1093+ (0.82104905483590, 0.99540741724928),
1094+ (0.99186510988782, 0.72023001312947),
1095+ (-0.65284592392918, 0.52186723253637),
1096+ (0.93885443798188, -0.74895312615259),
1097+ (0.96735248738388, 0.90891816978629),
1098+ (-0.22225968841114, 0.57124029781228),
1099+ (-0.44132783753414, -0.92688840659280),
1100+ (-0.85694974219574, 0.88844532719844),
1101+ (0.91783042091762, -0.46356892383970),
1102+ (0.72556974415690, -0.99899555770747),
1103+ (-0.99711581834508, 0.58211560180426),
1104+ (0.77638976371966, 0.94321834873819),
1105+ (0.07717324253925, 0.58638399856595),
1106+ (-0.56049829194163, 0.82522301569036),
1107+ (0.98398893639988, 0.39467440420569),
1108+ (0.47546946844938, 0.68613044836811),
1109+ (0.65675089314631, 0.18331637134880),
1110+ (0.03273375457980, -0.74933109564108),
1111+ (-0.38684144784738, 0.51337349030406),
1112+ (-0.97346267944545, -0.96549364384098),
1113+ (-0.53282156061942, -0.91423265091354),
1114+ (0.99817310731176, 0.61133572482148),
1115+ (-0.50254500772635, -0.88829338134294),
1116+ (0.01995873238855, 0.85223515096765),
1117+ (0.99930381973804, 0.94578896296649),
1118+ (0.82907767600783, -0.06323442598128),
1119+ (-0.58660709669728, 0.96840773806582),
1120+ (-0.17573736667267, -0.48166920859485),
1121+ (0.83434292401346, -0.13023450646997),
1122+ (0.05946491307025, 0.20511047074866),
1123+ (0.81505484574602, -0.94685947861369),
1124+ (-0.44976380954860, 0.40894572671545),
1125+ (-0.89746474625671, 0.99846578838537),
1126+ (0.39677256130792, -0.74854668609359),
1127+ (-0.07588948563079, 0.74096214084170),
1128+ (0.76343198951445, 0.41746629422634),
1129+ (-0.74490104699626, 0.94725911744610),
1130+ (0.64880119792759, 0.41336660830571),
1131+ (0.62319537462542, -0.93098313552599),
1132+ (0.42215817594807, -0.07712787385208),
1133+ (0.02704554141885, -0.05417518053666),
1134+ (0.80001773566818, 0.91542195141039),
1135+ (-0.79351832348816, -0.36208897989136),
1136+ (0.63872359151636, 0.08128252493444),
1137+ (0.52890520960295, 0.60048872455592),
1138+ (0.74238552914587, 0.04491915291044),
1139+ (0.99096131449250, -0.19451182854402),
1140+ (-0.80412329643109, -0.88513818199457),
1141+ (-0.64612616129736, 0.72198674804544),
1142+ (0.11657770663191, -0.83662833815041),
1143+ (-0.95053182488101, -0.96939905138082),
1144+ (-0.62228872928622, 0.82767262846661),
1145+ (0.03004475787316, -0.99738896333384),
1146+ (-0.97987214341034, 0.36526129686425),
1147+ (-0.99986980746200, -0.36021610299715),
1148+ (0.89110648599879, -0.97894250343044),
1149+ (0.10407960510582, 0.77357793811619),
1150+ (0.95964737821728, -0.35435818285502),
1151+ (0.50843233159162, 0.96107691266205),
1152+ (0.17006334670615, -0.76854025314829),
1153+ (0.25872675063360, 0.99893303933816),
1154+ (-0.01115998681937, 0.98496019742444),
1155+ (-0.79598702973261, 0.97138411318894),
1156+ (-0.99264708948101, -0.99542822402536),
1157+ (-0.99829663752818, 0.01877138824311),
1158+ (-0.70801016548184, 0.33680685948117),
1159+ (-0.70467057786826, 0.93272777501857),
1160+ (0.99846021905254, -0.98725746254433),
1161+ (-0.63364968534650, -0.16473594423746),
1162+ (-0.16258217500792, -0.95939125400802),
1163+ (-0.43645594360633, -0.94805030113284),
1164+ (-0.99848471702976, 0.96245166923809),
1165+ (-0.16796458968998, -0.98987511890470),
1166+ (-0.87979225745213, -0.71725725041680),
1167+ (0.44183099021786, -0.93568974498761),
1168+ (0.93310180125532, -0.99913308068246),
1169+ (-0.93941931782002, -0.56409379640356),
1170+ (-0.88590003188677, 0.47624600491382),
1171+ (0.99971463703691, -0.83889954253462),
1172+ (-0.75376385639978, 0.00814643438625),
1173+ (0.93887685615875, -0.11284528204636),
1174+ (0.85126435782309, 0.52349251543547),
1175+ (0.39701421446381, 0.81779634174316),
1176+ (-0.37024464187437, -0.87071656222959),
1177+ (-0.36024828242896, 0.34655735648287),
1178+ (-0.93388812549209, -0.84476541096429),
1179+ (-0.65298804552119, -0.18439575450921),
1180+ (0.11960319006843, 0.99899346780168),
1181+ (0.94292565553160, 0.83163906518293),
1182+ (0.75081145286948, -0.35533223142265),
1183+ (0.56721979748394, -0.24076836414499),
1184+ (0.46857766746029, -0.30140233457198),
1185+ (0.97312313923635, -0.99548191630031),
1186+ (-0.38299976567017, 0.98516909715427),
1187+ (0.41025800019463, 0.02116736935734),
1188+ (0.09638062008048, 0.04411984381457),
1189+ (-0.85283249275397, 0.91475563922421),
1190+ (0.88866808958124, -0.99735267083226),
1191+ (-0.48202429536989, -0.96805608884164),
1192+ (0.27572582416567, 0.58634753335832),
1193+ (-0.65889129659168, 0.58835634138583),
1194+ (0.98838086953732, 0.99994349600236),
1195+ (-0.20651349620689, 0.54593044066355),
1196+ (-0.62126416356920, -0.59893681700392),
1197+ (0.20320105410437, -0.86879180355289),
1198+ (-0.97790548600584, 0.96290806999242),
1199+ (0.11112534735126, 0.21484763313301),
1200+ (-0.41368337314182, 0.28216837680365),
1201+ (0.24133038992960, 0.51294362630238),
1202+ (-0.66393410674885, -0.08249679629081),
1203+ (-0.53697829178752, -0.97649903936228),
1204+ (-0.97224737889348, 0.22081333579837),
1205+ (0.87392477144549, -0.12796173740361),
1206+ (0.19050361015753, 0.01602615387195),
1207+ (-0.46353441212724, -0.95249041539006),
1208+ (-0.07064096339021, -0.94479803205886),
1209+ (-0.92444085484466, -0.10457590187436),
1210+ (-0.83822593578728, -0.01695043208885),
1211+ (0.75214681811150, -0.99955681042665),
1212+ (-0.42102998829339, 0.99720941999394),
1213+ (-0.72094786237696, -0.35008961934255),
1214+ (0.78843311019251, 0.52851398958271),
1215+ (0.97394027897442, -0.26695944086561),
1216+ (0.99206463477946, -0.57010120849429),
1217+ (0.76789609461795, -0.76519356730966),
1218+ (-0.82002421836409, -0.73530179553767),
1219+ (0.81924990025724, 0.99698425250579),
1220+ (-0.26719850873357, 0.68903369776193),
1221+ (-0.43311260380975, 0.85321815947490),
1222+ (0.99194979673836, 0.91876249766422),
1223+ (-0.80692001248487, -0.32627540663214),
1224+ (0.43080003649976, -0.21919095636638),
1225+ (0.67709491937357, -0.95478075822906),
1226+ (0.56151770568316, -0.70693811747778),
1227+ (0.10831862810749, -0.08628837174592),
1228+ (0.91229417540436, -0.65987351408410),
1229+ (-0.48972893932274, 0.56289246362686),
1230+ (-0.89033658689697, -0.71656563987082),
1231+ (0.65269447475094, 0.65916004833932),
1232+ (0.67439478141121, -0.81684380846796),
1233+ (-0.47770832416973, -0.16789556203025),
1234+ (-0.99715979260878, -0.93565784007648),
1235+ (-0.90889593602546, 0.62034397054380),
1236+ (-0.06618622548177, -0.23812217221359),
1237+ (0.99430266919728, 0.18812555317553),
1238+ (0.97686402381843, -0.28664534366620),
1239+ (0.94813650221268, -0.97506640027128),
1240+ (-0.95434497492853, -0.79607978501983),
1241+ (-0.49104783137150, 0.32895214359663),
1242+ (0.99881175120751, 0.88993983831354),
1243+ (0.50449166760303, -0.85995072408434),
1244+ (0.47162891065108, -0.18680204049569),
1245+ (-0.62081581361840, 0.75000676218956),
1246+ (-0.43867015250812, 0.99998069244322),
1247+ (0.98630563232075, -0.53578899600662),
1248+ (-0.61510362277374, -0.89515019899997),
1249+ (-0.03841517601843, -0.69888815681179),
1250+ (-0.30102157304644, -0.07667808922205),
1251+ (0.41881284182683, 0.02188098922282),
1252+ (-0.86135454941237, 0.98947480909359),
1253+ (0.67226861393788, -0.13494389011014),
1254+ (-0.70737398842068, -0.76547349325992),
1255+ (0.94044946687963, 0.09026201157416),
1256+ (-0.82386352534327, 0.08924768823676),
1257+ (-0.32070666698656, 0.50143421908753),
1258+ (0.57593163224487, -0.98966422921509),
1259+ (-0.36326018419965, 0.07440243123228),
1260+ (0.99979044674350, -0.14130287347405),
1261+ (-0.92366023326932, -0.97979298068180),
1262+ (-0.44607178518598, -0.54233252016394),
1263+ (0.44226800932956, 0.71326756742752),
1264+ (0.03671907158312, 0.63606389366675),
1265+ (0.52175424682195, -0.85396826735705),
1266+ (-0.94701139690956, -0.01826348194255),
1267+ (-0.98759606946049, 0.82288714303073),
1268+ (0.87434794743625, 0.89399495655433),
1269+ (-0.93412041758744, 0.41374052024363),
1270+ (0.96063943315511, 0.93116709541280),
1271+ (0.97534253457837, 0.86150930812689),
1272+ (0.99642466504163, 0.70190043427512),
1273+ (-0.94705089665984, -0.29580042814306),
1274+ (0.91599807087376, -0.98147830385781),
1275+];
1276+
7521277 #[cfg(test)]
7531278 mod tests {
7541279 use super::*;
crates/ec-aac/tests/sbr_real_library.rsmodified+153 -11
@@ -305,6 +305,19 @@ fn best_lag_correlation_ex(ours: &[f32], theirs: &[f32], lag_max: i64) -> (i64,
305305 if !found {
306306 best = coarse_best;
307307 }
308+ // A winning lag at the search bound is not a measurement (the true
309+ // alignment may lie outside it): widen once to `SEARCH_LAG_MAX`, and if
310+ // it still sits at the edge fail here rather than hand any caller a
311+ // noise-driven number (instrument-at-bound class).
312+ if at_edge && lag_max < SEARCH_LAG_MAX {
313+ return best_lag_correlation_ex(ours, theirs, SEARCH_LAG_MAX);
314+ }
315+ assert!(
316+ !at_edge,
317+ "winning lag {} sits at the +/-{lag_max} search bound -- the true \
318+ alignment is outside the search, corr {:.6} is noise, not a measurement",
319+ best.0, best.2
320+ );
308321 (best.0, best.2, at_edge)
309322 }
310323
@@ -2249,18 +2262,24 @@ fn full_chain_low_band_matches_own_core() {
22492262 // without exposing the well-behaved one to the wider bound's
22502263 // noise floor.
22512264 const WIDE_LAG_MAX: i64 = 20_000;
2252- let (mut lag, mut corr, mut at_edge) = best_lag_correlation_ex(&ol, &ul, WIDE_LAG_MAX);
2265+ // Top-K refinement, not the single coarse winner: FMJ's single
2266+ // coarse pick landed on an in-bounds noise peak (lag 18995,
2267+ // corr 0.10) while its true alignment scores >0.99 on refine.
2268+ // A winner at the bound widens once, then is asserted off it.
2269+ let (mut lag, mut corr, mut at_edge) =
2270+ robust_lag_topk(&ol, &ul, WIDE_LAG_MAX, core_rate, 8);
22532271 let mut bound = WIDE_LAG_MAX;
2254- if at_edge {
2272+ // A sub-bar winner inside the narrow bound is the same symptom
2273+ // (true peak outside the search), so it widens too.
2274+ if at_edge || corr < 0.99 {
22552275 bound = SEARCH_LAG_MAX;
2256- (lag, corr, at_edge) = best_lag_correlation_ex(&ol, &ul, SEARCH_LAG_MAX);
2276+ (lag, corr, at_edge) = robust_lag_topk(&ol, &ul, SEARCH_LAG_MAX, core_rate, 8);
22572277 }
22582278 println!(" ch{ch}: measured best lag {lag}, corr {corr:.6}");
22592279 assert!(
22602280 !at_edge,
22612281 "{} ch{ch}: winning lag {lag} sits at the +/-{bound} \
2262- search bound -- the true alignment is outside the search, \
2263- corr {corr:.6} is noise, not a measurement",
2282+ search bound -- corr {corr:.6} is noise, not a measurement",
22642283 c.path.display()
22652284 );
22662285 assert!(
@@ -2755,6 +2774,8 @@ fn sbr_real_library_matches_reference() {
27552774 let high = if n >= 1024 {
27562775 let oh = highpass(&o[oa..oa + n], rate, c.crossover_hz);
27572776 let th = highpass(&t[ob..ob + n], rate, c.crossover_hz);
2777+ let rms = |v: &[f32]| (v.iter().map(|x| f64::from(*x).powi(2)).sum::<f64>() / v.len().max(1) as f64).sqrt();
2778+ println!(" ch{ch} above-crossover RMS ours/ref = {:.4}", rms(&oh) / rms(&th).max(1e-12));
27582779 correlation(&oh, &th)
27592780 } else {
27602781 0.0
@@ -2772,15 +2793,16 @@ fn sbr_real_library_matches_reference() {
27722793 println!(
27732794 " NOISE-FRACTION ceiling prediction (band_hz, f_noise, predicted_ceiling):"
27742795 );
2775- for (band, signal, noise) in ec_aac::noise_fraction_table() {
2796+ for (band, signal, noise, out) in ec_aac::noise_fraction_table() {
27762797 if signal + noise <= 0.0 {
27772798 continue;
27782799 }
27792800 let f = noise / (signal + noise);
27802801 println!(
2781- " {:>6.0}Hz band{band:>3}: signal {signal:.3e} noise {noise:.3e} f_noise {f:.6} ceiling {:.4}",
2802+ " {:>6.0}Hz band{band:>3}: signal {signal:.3e} noise {noise:.3e} f_noise {f:.6} ceiling {:.4} realised/target {:.4}",
27822803 band as f64 * band_hz,
2783- (1.0 - f).max(0.0).sqrt()
2804+ (1.0 - f).max(0.0).sqrt(),
2805+ out / (signal + noise)
27842806 );
27852807 }
27862808 }
@@ -3004,6 +3026,25 @@ fn sbr_real_library_matches_reference() {
30043026 let win = &o[oa..oa + n];
30053027 let twin = &t[ob..ob + n];
30063028 let (vs_ref, vs_ours, ours_vs_ref) = hf_patch_simulator_qmf(win, twin);
3029+ // Per-QMF-band energy ratio and coherence, ours vs reference
3030+ // (the envelope-adjuster instrument: a level offset shows as
3031+ // a constant dB ratio, a gain-shape defect as per-band dB).
3032+ {
3033+ let (o_spec, t_spec, _) = qmf_domain_spec(win, twin);
3034+ println!(" ch{ch} QMF-BAND ours-vs-REFERENCE (band, ratio_dB, coherence):");
3035+ for band in 0..o_spec.len().min(t_spec.len()).min(48) {
3036+ let (mut eo, mut et, mut cr, mut ci) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
3037+ for (a, b) in o_spec[band].iter().zip(&t_spec[band]) {
3038+ eo += a.norm_sqr();
3039+ et += b.norm_sqr();
3040+ let c = *a * b.conj();
3041+ cr += c.re;
3042+ ci += c.im;
3043+ }
3044+ let coh = (cr * cr + ci * ci).sqrt() / (eo * et).sqrt().max(1e-30);
3045+ println!(" band{band:>3}: {:>7.2} dB coh {coh:.4}", 10.0 * (eo / et.max(1e-30)).log10());
3046+ }
3047+ }
30073048 let mean_in = |rows: &[(usize, f64)], lo: usize, hi: usize| {
30083049 let vals: Vec<f64> = rows
30093050 .iter()
@@ -3358,12 +3399,12 @@ fn sbr_actual_noise_fraction() {
33583399 // invoke this test by name, not as part of a parallel `cargo test` run.
33593400 unsafe {
33603401 std::env::remove_var("EC_AAC_SBR_NOISE_ZERO");
3361- std::env::set_var("EC_AAC_SBR_NOISE_FRACTION_DEBUG", "1");
3402+ std::env::set_var("EC_AAC_SBR_NOISE_FRACTION", "1");
33623403 }
33633404 let (ours_on, _, rate) = our_decode(&path, 0).expect("our_decode works (noise on)");
33643405 let bookkept = ec_aac::noise_fraction_table();
33653406 unsafe {
3366- std::env::remove_var("EC_AAC_SBR_NOISE_FRACTION_DEBUG");
3407+ std::env::remove_var("EC_AAC_SBR_NOISE_FRACTION");
33673408 std::env::set_var("EC_AAC_SBR_NOISE_ZERO", "1");
33683409 }
33693410 let (ours_off, _, _) = our_decode(&path, 0).expect("our_decode works (noise zeroed)");
@@ -3415,7 +3456,7 @@ fn sbr_actual_noise_fraction() {
34153456 let book = bookkept
34163457 .iter()
34173458 .find(|(b, ..)| *b == band)
3418- .map(|(_, s, n)| if s + n > 0.0 { n / (s + n) } else { 0.0 })
3459+ .map(|(_, s, n, _)| if s + n > 0.0 { n / (s + n) } else { 0.0 })
34193460 .unwrap_or(0.0);
34203461 println!(
34213462 " {hz:>6.0}Hz: on {e_on:.3e} off {e_off:.3e} actual {actual:.4} bookkept {book:.4}"
@@ -4598,3 +4639,104 @@ fn sbr_hf_window_band_probe() {
45984639 );
45994640 }
46004641 }
4642+
4643+/// Round-59 residual locator: per-2048-sample-window corr at lag 0 (worst
4644+/// windows, with the output frame index) plus a complex-STFT per-band
4645+/// correlation (Parseval: equals the time-domain corr restricted to that
4646+/// band, so it needs no calibration) with an ours-vs-ours self-check column.
4647+#[test]
4648+fn sbr_residual_locator() {
4649+ if !have_ffmpeg() {
4650+ return;
4651+ }
4652+ let home = std::env::var("HOME").unwrap();
4653+ // `EC_AAC_SBR_LOCATOR_FILE` points the same instrument at any other
4654+ // HE-AAC file (e.g. a mono, uncoupled, noise-only probe encode).
4655+ let path = std::env::var("EC_AAC_SBR_LOCATOR_FILE")
4656+ .map(PathBuf::from)
4657+ .unwrap_or_else(|_| PathBuf::from(format!("{home}/Music/reeln.mp4")));
4658+ if !path.exists() {
4659+ return;
4660+ }
4661+ let Some((ours, _, rate)) = our_decode(&path, 0) else { return };
4662+ let theirs = ffmpeg_decode(&path, 0, ours.len());
4663+ const W: usize = 2048;
4664+ const FFT_LEN: usize = 2048;
4665+ const HOP: usize = 1024;
4666+ let bins = FFT_LEN / 2 + 1;
4667+ let mut rfft = ec_dsp::RealFft::<f32>::new(FFT_LEN);
4668+ let win = ec_dsp::Window::<f32>::sine(FFT_LEN);
4669+ for ch in 0..ours.len() {
4670+ let n = ours[ch].len().min(theirs[ch].len());
4671+ let (o, t) = (&ours[ch][..n], &theirs[ch][..n]);
4672+ let mut wins: Vec<(f64, usize)> = (0..n / W)
4673+ .map(|w| (correlation(&o[w * W..(w + 1) * W], &t[w * W..(w + 1) * W]), w))
4674+ .collect();
4675+ wins.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
4676+ println!("ch{ch} worst windows (corr, frame): {:?}", &wins[..12]);
4677+ let hops = (n - FFT_LEN) / HOP + 1;
4678+ let mut spec = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
4679+ let mut acc = vec![[0.0f64; 3]; bins]; // re(o*conj t), |o|^2, |t|^2
4680+ let mut os = vec![ec_dsp::Complex::new(0.0f32, 0.0); bins];
4681+ for h in 0..hops {
4682+ let mut b = o[h * HOP..h * HOP + FFT_LEN].to_vec();
4683+ win.apply(&mut b);
4684+ rfft.forward(&b, &mut spec);
4685+ os.copy_from_slice(&spec);
4686+ let mut b = t[h * HOP..h * HOP + FFT_LEN].to_vec();
4687+ win.apply(&mut b);
4688+ rfft.forward(&b, &mut spec);
4689+ for k in 0..bins {
4690+ let (a, c) = (os[k], spec[k]);
4691+ acc[k][0] += f64::from(a.re * c.re + a.im * c.im);
4692+ acc[k][1] += f64::from(a.norm_sqr());
4693+ acc[k][2] += f64::from(c.norm_sqr());
4694+ }
4695+ }
4696+ let hz = f64::from(rate) / FFT_LEN as f64;
4697+ let tot: f64 = acc.iter().map(|a| a[1] + a[2]).sum();
4698+ // With `EC_AAC_SBR_NOISE_FRACTION` set the decoder bookkeeps the
4699+ // dequantized target per QMF band; print it next to the reference's
4700+ // measured energy in the same band so a target-side (bitstream ->
4701+ // E_orig) tilt separates from an adjust/synthesis-side one.
4702+ if ch == 0 {
4703+ let band_hz = f64::from(rate) / 128.0;
4704+ for (band, sig, noi, out) in ec_aac::noise_fraction_table() {
4705+ let (lo, hi) = (
4706+ (band as f64 * band_hz / hz) as usize,
4707+ ((band + 1) as f64 * band_hz / hz) as usize,
4708+ );
4709+ let pt: f64 = (lo..hi.min(bins)).map(|k| acc[k][2]).sum();
4710+ let po: f64 = (lo..hi.min(bins)).map(|k| acc[k][1]).sum();
4711+ println!(
4712+ "TARGET band {band:>2} {:>6.0}Hz target {:.3e} realised/target {:.4} ref_pcm {:.3e} ours_pcm {:.3e} target/ref_pcm {:.3e}",
4713+ band as f64 * band_hz,
4714+ sig + noi,
4715+ out / (sig + noi),
4716+ pt,
4717+ po,
4718+ (sig + noi) / pt
4719+ );
4720+ }
4721+ }
4722+ // group into 250 Hz bands up to 8 kHz, then 1 kHz
4723+ let mut edges: Vec<usize> = (0..=32).map(|i| ((i as f64 * 250.0) / hz) as usize).collect();
4724+ edges.extend((9..=22).map(|i| ((i as f64 * 1000.0) / hz) as usize));
4725+ for e in edges.windows(2) {
4726+ let (mut c, mut po, mut pt) = (0.0, 0.0, 0.0);
4727+ for k in e[0]..e[1].min(bins) {
4728+ c += acc[k][0];
4729+ po += acc[k][1];
4730+ pt += acc[k][2];
4731+ }
4732+ println!(
4733+ "ch{ch} {:5.0}-{:5.0} Hz corr {:.5} rms ours/ref {:.4} energy share {:.4}",
4734+ e[0] as f64 * hz,
4735+ e[1] as f64 * hz,
4736+ c / (po * pt).sqrt(),
4737+ (po / pt).sqrt(),
4738+ (po + pt) / tot
4739+ );
4740+ }
4741+ }
4742+}
scripts/aac-tables/sbrvalues.pyadded+182 -0
@@ -0,0 +1,182 @@
1+#!/usr/bin/env python3
2+"""Reads the delta every 3.0 dB envelope codeword carries off the reference
3+decoder's `env_facs_q V is invalid` range check, by ACCUMULATION.
4+
5+`sbrtables.py --stage values` applies a codeword once to a raw start value and
6+reads the delta from the out-of-range complaint. The 3.0 dB books ride a 6-bit
7+(5-bit balance) raw field but are checked against a 7-bit ceiling, so a single
8+positive 3.0 dB delta never trips it and every one was emitted as 0
9+(ENV30_F/ENV30_T/ENVB30_F/ENVB30_T: 32/32/13/13 zeros).
10+
11+The check sees the ACCUMULATED value, and delta-time coding accumulates across
12+envelopes and frames: a `_T` codeword repeated for enough envelopes walks any
13+non-zero delta out of range, and a `_F` codeword is walked out by trusted
14+negative `_T` steps riding after it. The complaint reports the first value out
15+of range (mod 256); a tiny simulator predicts that value for every candidate
16+delta and the one candidate that reproduces every probe is the answer. Trusted
17+negative entries go through the same readout and must come back unchanged.
18+
19+Writes the values in place into crates/ec-aac/src/sbr_tables.rs.
20+
21+ python3 scripts/aac-tables/sbrvalues.py
22+"""
23+
24+import os
25+import re
26+import sys
27+
28+HERE = os.path.dirname(os.path.abspath(__file__))
29+sys.path.insert(0, HERE)
30+import sbrtables as T # noqa: E402
31+from sbrprobe import silent # noqa: E402
32+
33+RS = os.path.join(T.ROOT, "crates", "ec-aac", "src", "sbr_tables.rs")
34+KINDS = ["ENV30_T", "ENVB30_T", "ENV30_F", "ENVB30_F"]
35+INVALID = re.compile(r"env_facs_q (-?\d+) is invalid")
36+RUNS = 40
37+
38+
39+def load_books():
40+ src = open(RS).read()
41+ books = {}
42+ for m in re.finditer(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", src, re.S):
43+ books[m.group(1)] = {
44+ (int(a), int(b)): int(c)
45+ for a, b, c in re.findall(r"\((\d+), (\d+), (-?\d+)\)", m.group(2))
46+ }
47+ return books
48+
49+
50+def by_value(book, v):
51+ return T.as_bits(*next(lc for lc, d in book.items() if d == v))
52+
53+
54+def first_invalid(err):
55+ m = INVALID.search(err)
56+ return int(m.group(1)) if m else None
57+
58+
59+def simulate(steps, scale, raw):
60+ """First out-of-range `scale * value` (mod 256) along `raw + cumsum(steps)`."""
61+ acc = raw
62+ for s in steps:
63+ acc += s
64+ v = scale * acc
65+ if v < 0 or v > 127:
66+ return v % 256
67+ return None
68+
69+
70+def probe_t(kind, book, cfg, tables, word, raw, balance):
71+ """env0 F-coded from `raw` (no F slots: one band), env1 T-coded with `word`,
72+ then RUNS frames with both envelopes T-coded with `word`. ch0 of a coupled
73+ pair rides trusted zero words."""
74+ key = "env0b" if balance else "env0"
75+ start = dict(cfg, **{key: [raw] * 8})
76+ run = dict(cfg, df_env=[1, 1] + [0] * 6, **{key: [raw] * 8})
77+ z = by_value(T_BOOK, 0)
78+ ch0 = [z] if balance else []
79+ frames = [silent(cfg["sf_index"]), T.frame(start, tables, ch0 + [word])]
80+ frames += [T.frame(run, tables, ch0 * 2 + [word, word])] * RUNS
81+ return b"".join(frames), [None] + [None] * (2 * RUNS) # steps = word each
82+
83+
84+def probe_f(kind, book, cfg, tables, word, raw, balance, step_book, step):
85+ """env0 F-coded from `raw` with `word` in band 1, env1 T-coded with band 0
86+ zero and band 1 `step`, then RUNS frames of the same T pair."""
87+ key = "env0b" if balance else "env0"
88+ start = dict(cfg, df_env=[0, 1] + [0] * 6, **{key: [raw] * 8})
89+ run = dict(cfg, df_env=[1, 1] + [0] * 6, **{key: [raw] * 8})
90+ zf, zt = by_value(F_BOOK, 0), by_value(T_BOOK, 0)
91+ s = by_value(step_book, step)
92+ zs = by_value(T_BOOK if balance else step_book, 0)
93+ ch0 = [zf, zt, zt] if balance else []
94+ ch0r = [zt, zt, zt, zt] if balance else []
95+ frames = [silent(cfg["sf_index"]), T.frame(start, tables, ch0 + [word, zs, s])]
96+ frames += [T.frame(run, tables, ch0r + [zs, s, zs, s])] * 6
97+ return b"".join(frames), [None] + [step] * 13
98+
99+
100+def read_book(oracle, kind, books):
101+ book = books[kind]
102+ balance = kind.startswith("ENVB")
103+ scale = 2 if balance else 1
104+ span = 12 if balance else 31
105+ cands = range(-span, span + 1)
106+ cfg, tables = T.recipe_config(kind)
107+ raw_max = 31 if balance else 63
108+ out = {}
109+ for lc in sorted(book):
110+ word = T.as_bits(*lc)
111+ obs = [] # (steps template, raw, observed)
112+ alive = set(cands)
113+ # Probe until exactly one candidate reproduces every observation.
114+ if kind.endswith("_T"):
115+ plan = [("t", raw, None) for raw in range(raw_max, -1, -1)]
116+ else:
117+ sb = books["ENVB30_T" if balance else "ENV30_T"]
118+ neg = sorted({d for d in sb.values() if d < 0})
119+ plan = [("f", raw_max, s) for s in neg[:4]] + [("f", 0, s) for s in neg[:4]]
120+ for mode, raw, s in plan:
121+ if mode == "t":
122+ data, steps = probe_t(kind, book, cfg, tables, word, raw, balance)
123+ else:
124+ data, steps = probe_f(kind, book, cfg, tables, word, raw, balance, sb, s)
125+ err = oracle.one(f"acc:{kind}:{lc}:{mode}:{raw}:{s}", data)
126+ got = first_invalid(err)
127+ alive = {
128+ d for d in alive
129+ if simulate([d if x is None else x for x in steps], scale, raw) == got
130+ }
131+ if len(alive) <= 1:
132+ break
133+ if len(alive) != 1:
134+ print(f" {kind} {lc}: UNRESOLVED, candidates {sorted(alive)}")
135+ continue
136+ d = next(iter(alive))
137+ old = book[lc]
138+ flag = "" if old == d else (" (was 0)" if old == 0 else f" <-- DISAGREES with {old}")
139+ print(f" {kind} {lc}: {d:>4}{flag}")
140+ out[lc] = d
141+ vals = sorted(out.values())
142+ complete = vals == list(cands) and len(out) == len(book)
143+ print(f"{kind}: {len(out)}/{len(book)} read, values {'complete -%d..%d once each' % (span, span) if complete else 'NOT a permutation: ' + str(vals)}")
144+ return out, complete
145+
146+
147+def main():
148+ books = load_books()
149+ global F_BOOK, T_BOOK
150+ F_BOOK, T_BOOK = books["ENV30_F"], books["ENV30_T"]
151+ oracle = T.Oracle(12)
152+ out = {}
153+ try:
154+ for kind in KINDS:
155+ vals, complete = read_book(oracle, kind, books)
156+ if complete:
157+ out[kind] = vals
158+ books[kind] = vals # later books ride on these
159+ if kind == "ENV30_T":
160+ T_BOOK = vals
161+ finally:
162+ oracle.save()
163+ src = open(RS).read()
164+
165+ def patch_block(m):
166+ name, body = m.group(1), m.group(2)
167+ if name not in out:
168+ return m.group(0)
169+ new = re.sub(
170+ r"\((\d+), (\d+), (-?\d+)\)",
171+ lambda t: f"({t.group(1)}, {t.group(2)}, {out[name][(int(t.group(1)), int(t.group(2)))]})",
172+ body,
173+ )
174+ return m.group(0).replace(body, new)
175+
176+ src = re.sub(r"static (\w+): \[\(u8, u32, i32\); \d+\] = \[(.*?)\n\];", patch_block, src, flags=re.S)
177+ open(RS, "w").write(src)
178+ print(f"wrote {RS}: {sorted(out)}")
179+
180+
181+if __name__ == "__main__":
182+ main()