forge
Explore
Log in

Don't you dare go Hollow

Spec-structured envelope adjuster (per-subband gains, limiter/boost with S_M and Q_M, V-table noise, sinusoid phases, slot smoothing, l_A/delta, 6-slot tHFAdj alignment, class-correct noise border, coupled noise dequant)

Browse files at this commit

363af1c85c8b4d3f44f927a0f54b9eae55ad46a7Ahmet Kaan GümüşParent: 7cb6000
  • fix
    • spec-structured envelope adjuster (per-subband gains, limiter/boost with S_M and Q_M, V-table noise, sinusoid phases, slot smoothing, l_A/delta, 6-slot tHFAdj alignment, class-correct noise border, coupled noise dequant)
Show full message
fix(aac-sbr): spec-structured envelope adjuster (per-subband gains, limiter/boost with S_M and Q_M, V-table noise, sinusoid phases, slot smoothing, l_A/delta, 6-slot tHFAdj alignment, class-correct noise border, coupled noise dequant)

reeln full 0.9927/0.9918 -> 0.9953/0.9946, above-5k 0.9868/0.9918 -> 0.9985/0.9984, lag 385 -> 1.
crates/ec-aac/src/sbr_chain.rsmodified+74 -11
@@ -4,7 +4,7 @@
4 //! PCM through 32-band analysis, generate and adjust the HF region, and4 //! PCM through 32-band analysis, generate and adjust the HF region, and
5 //! resynthesize through the 64-band bank to double-rate PCM in place.5 //! resynthesize through the 64-band bank to double-rate PCM in place.
6 6
7-use crate::sbr_env::{self, NoiseGen};7+use crate::sbr_env::{self, AdjustState};
8 use crate::sbr_hf::{self, ChirpState, HfHistory};8 use crate::sbr_hf::{self, ChirpState, HfHistory};
9 use crate::sbr_payload::{SbrChannel, SbrData, SbrParser};9 use crate::sbr_payload::{SbrChannel, SbrData, SbrParser};
10 use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis};10 use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis};
@@ -181,17 +181,32 @@ struct ChannelState {
181 synthesis: Synthesis,181 synthesis: Synthesis,
182 hf_hist: HfHistory,182 hf_hist: HfHistory,
183 chirp: ChirpState,183 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>>>,
185 }193 }
186 194
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+
187 impl ChannelState {199 impl ChannelState {
188- fn new(n_q: usize, seed: u32) -> ChannelState {200+ fn new(n_q: usize, _seed: u32) -> ChannelState {
189 ChannelState {201 ChannelState {
190 analysis: Analysis::new(),202 analysis: Analysis::new(),
191 synthesis: Synthesis::new(),203 synthesis: Synthesis::new(),
192 hf_hist: HfHistory::new(ANALYSIS_BANDS),204 hf_hist: HfHistory::new(ANALYSIS_BANDS),
193 chirp: ChirpState::new(n_q.max(1)),205 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(),
195 }210 }
196 }211 }
197 }212 }
@@ -209,6 +224,8 @@ struct Element {
209 /// half length -- which otherwise permanently shifts every sample after224 /// half length -- which otherwise permanently shifts every sample after
210 /// it out of alignment with a reference that stayed at full rate.225 /// it out of alignment with a reference that stayed at full rate.
211 last_data: Option<SbrData>,226 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>,
212 }229 }
213 230
214 /// Every configured SBR element in a stream, keyed by231 /// Every configured SBR element in a stream, keyed by
@@ -240,6 +257,7 @@ impl SbrChain {
240 parser: SbrParser::new(self.rate),257 parser: SbrParser::new(self.rate),
241 channels: Vec::new(),258 channels: Vec::new(),
242 last_data: None,259 last_data: None,
260+ last_header: None,
243 });261 });
244 let data = elem.parser.parse(r, is_cpe).ok()?;262 let data = elem.parser.parse(r, is_cpe).ok()?;
245 let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1);263 let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1);
@@ -294,6 +312,8 @@ impl SbrChain {
294 let Some(tables) = elem.parser.tables().cloned() else {312 let Some(tables) = elem.parser.tables().cloned() else {
295 return;313 return;
296 };314 };
315+ let reset = elem.last_header.as_ref() != elem.parser.header();
316+ elem.last_header = elem.parser.header().cloned();
297 let Some(header) = elem.parser.header().cloned() else {317 let Some(header) = elem.parser.header().cloned() else {
298 return;318 return;
299 };319 };
@@ -411,7 +431,7 @@ impl SbrChain {
411 if qmfdump_on {431 if qmfdump_on {
412 qmfdump_energies("analysis", 0, &low_cur);432 qmfdump_energies("analysis", 0, &low_cur);
413 }433 }
414- let mut hf = sbr_hf::generate(434+ let hf = sbr_hf::generate(
415 &low_cur,435 &low_cur,
416 &tables,436 &tables,
417 &sbr_ch.invf_mode,437 &sbr_ch.invf_mode,
@@ -430,25 +450,64 @@ impl SbrChain {
430 t_noise: sbr_ch.t_noise.iter().map(|&t| t * RATE).collect(),450 t_noise: sbr_ch.t_noise.iter().map(|&t| t * RATE).collect(),
431 ..sbr_ch.clone()451 ..sbr_ch.clone()
432 };452 };
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.
437 let limiter_table = sbr_hf::limiter_band_table(453 let limiter_table = sbr_hf::limiter_band_table(
438 &tables,454 &tables,
439 &sbr_hf::build_patches(&tables),455 &sbr_hf::build_patches(&tables),
440 header.limiter_bands,456 header.limiter_bands,
441 );457 );
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+ }
442 sbr_env::adjust(476 sbr_env::adjust(
443- &mut hf,477+ &mut xh,
444 &tables,478 &tables,
445 &header,479 &header,
446 &scaled,480 &scaled,
447 &env_energy,481 &env_energy,
448 &noise_energy,482 &noise_energy,
449- &mut state.noise,
450 &limiter_table,483 &limiter_table,
484+ &mut state.adj,
485+ reset,
451 );486 );
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+ };
452 if qmfdump_on {511 if qmfdump_on {
453 qmfdump_energies("post_adjust", tables.kx as usize, &hf);512 qmfdump_energies("post_adjust", tables.kx as usize, &hf);
454 }513 }
@@ -528,6 +587,7 @@ mod tests {
528 add_harmonic: None,587 add_harmonic: None,
529 df_env: vec![],588 df_env: vec![],
530 df_noise: vec![],589 df_noise: vec![],
590+ l_a: -1,
531 }591 }
532 }592 }
533 593
@@ -551,6 +611,7 @@ mod tests {
551 parser: SbrParser::new(44100),611 parser: SbrParser::new(44100),
552 channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)],612 channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)],
553 last_data: None,613 last_data: None,
614+ last_header: None,
554 },615 },
555 );616 );
556 chain617 chain
@@ -650,6 +711,7 @@ mod tests {
650 .map(|i| ChannelState::new(n_q, 10 + i as u32))711 .map(|i| ChannelState::new(n_q, 10 + i as u32))
651 .collect(),712 .collect(),
652 last_data: None,713 last_data: None,
714+ last_header: None,
653 },715 },
654 );716 );
655 chain717 chain
@@ -694,6 +756,7 @@ mod tests {
694 parser: SbrParser::new(44100),756 parser: SbrParser::new(44100),
695 channels: vec![ChannelState::new(n_q, 10)],757 channels: vec![ChannelState::new(n_q, 10)],
696 last_data: None,758 last_data: None,
759+ last_header: None,
697 },760 },
698 );761 );
699 reference762 reference
crates/ec-aac/src/sbr_env.rsmodified+396 -936
@@ -1,50 +1,23 @@
1-//! SBR envelope adjustment (ISO/IEC 14496-3 §4.6.18.7): scales the raw HF1+//! SBR envelope adjustment (ISO/IEC 14496-3 §4.6.18.7): dequantisation,
2-//! QMF estimate [`crate::sbr_hf::generate`] produced so each transmitted2+//! mapping, E_curr estimation, gain/limiter/boost calculation and HF
3-//! (envelope, band) cell carries the energy the encoder actually measured,3+//! assembly, written formula-for-formula against §4.6.18.7.2-7.6.
4-//! injects the transmitted noise floor, and adds sinusoids at the bands
5-//! `bs_add_harmonic` flags.
6 //!4 //!
7-//! # Dequantization5+//! 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).
8 //!11 //!
9-//! A plain (non-coupled) envelope's linear energy is `2^(alpha * e_q)`12+//! Slot indexing: `hf[m][i]` is `X_high(k, i + tHFAdj)`, i.e. slot `i` is the
10-//! with `alpha = 1.0` at `bs_amp_res = 1` (3 dB steps) and `0.5` at13+//! one envelope border `2*t_E` counts -- the caller supplies a buffer long
11-//! `bs_amp_res = 0` (1.5 dB steps); the noise floor is `2^(6 - q_q)`14+//! enough for `2*t_E(L_E)` (up to 38 slots: 32 of this frame plus the
12-//! (`NOISE_FLOOR_OFFSET = 6`). A coupled CPE's balance channel (`e_q`'s15+//! 6-slot overlap the variable frame classes may reach into).
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.
44 #![allow(clippy::needless_range_loop)]16 #![allow(clippy::needless_range_loop)]
45 17
46 use crate::sbr_bands::BandTables;18 use crate::sbr_bands::BandTables;
47 use crate::sbr_payload::{SbrChannel, SbrHeader};19 use crate::sbr_payload::{SbrChannel, SbrHeader};
20+use crate::sbr_tables::SBR_NOISE;
48 use ec_dsp::Complex;21 use ec_dsp::Complex;
49 22
50 const NOISE_FLOOR_OFFSET: f64 = 6.0;23 const NOISE_FLOOR_OFFSET: f64 = 6.0;
@@ -57,18 +30,17 @@ fn alpha(amp_res: u8) -> f64 {
57 if amp_res != 0 { 1.0 } else { 0.5 }30 if amp_res != 0 { 1.0 } else { 0.5 }
58 }31 }
59 32
60-/// Plain (non-coupled) envelope dequantization.33+/// Plain (non-coupled) envelope dequantization: `E_Orig = 2^(E_Q * a)`.
34+/// §4.6.18.7.2 carries an extra `* 64` here; it is a pure scale on the
35+/// whole HF region (the gain `sqrt(E_orig/E_curr)` cancels our own QMF
36+/// scale otherwise), and this chain's QMF domain is calibrated without it
37+/// (see `sbr_chain`'s OUTPUT_SCALE handling).
61 pub fn dequant_env(e_q: i32, amp_res: u8) -> f64 {38 pub fn dequant_env(e_q: i32, amp_res: u8) -> f64 {
62 2f64.powf(alpha(amp_res) * f64::from(e_q))39 2f64.powf(alpha(amp_res) * f64::from(e_q))
63 }40 }
64 41
65-/// Plain noise-floor dequantization: `Q_div = 2^(NOISE_FLOOR_OFFSET-q_q)`, a42+/// Plain noise-floor dequantization: `Q_Orig = 2^(NOISE_FLOOR_OFFSET - Q_Q)`,
66-/// ratio relative to the ENVELOPE energy of the same (time, band) cell, not43+/// a ratio against the same cell's envelope energy (§4.6.18.7.2).
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).
72 pub fn dequant_noise(q_q: i32) -> f64 {44 pub fn dequant_noise(q_q: i32) -> f64 {
73 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q_q))45 2f64.powf(NOISE_FLOOR_OFFSET - f64::from(q_q))
74 }46 }
@@ -76,24 +48,11 @@ pub fn dequant_noise(q_q: i32) -> f64 {
76 /// De-mixes a coupled CPE's `(channel 0 raw, balance raw)` pair into48 /// De-mixes a coupled CPE's `(channel 0 raw, balance raw)` pair into
77 /// `(env0, env1)` linear energies (ISO/IEC 14496-3 §4.6.18.7.2,49 /// `(env0, env1)` linear energies (ISO/IEC 14496-3 §4.6.18.7.2,
78 /// `bs_coupling`): `Ecurr = dequant_env(e0_raw, amp_res)`,50 /// `bs_coupling`): `Ecurr = dequant_env(e0_raw, amp_res)`,
79-/// `ratio = 2^(pan - panOffset)` where `pan` is the RAW balance value51+/// `ratio = 2^(pan - panOffset)` where `pan` is the RAW balance value and
80-/// (channels[1]'s `e_q`, not run through `alpha`/`amp_res` scaling) and52+/// `panOffset` is 24 at `bs_amp_res=0` or 12 at `bs_amp_res=1`;
81-/// `panOffset` is 24 at `bs_amp_res=0` (1.5 dB steps) or 12 at53+/// `env0 = 2*Ecurr/(1+ratio)`, `env1 = 2*Ecurr*ratio/(1+ratio)`.
82-/// `bs_amp_res=1` (3 dB steps); `env0 = 2*Ecurr/(1+ratio)`,54+/// `header_amp_res` governs `panOffset` regardless of the single-envelope
83-/// `env1 = 2*Ecurr*ratio/(1+ratio)`. The previous `2*alpha*raw - 12`55+/// override -- the two diverge on single-envelope coupled frames.
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) {56 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);57 let e_curr = dequant_env(e0_raw, env_amp_res);
99 let pan_offset = if header_amp_res != 0 { 12.0 } else { 24.0 };58 let pan_offset = if header_amp_res != 0 { 12.0 } else { 24.0 };
@@ -103,9 +62,18 @@ pub fn dequant_pair(e0_raw: i32, pan_raw: i32, env_amp_res: u8, header_amp_res:
103 (env0, env1)62 (env0, env1)
104 }63 }
105 64
65+/// Coupled noise-floor pair (§4.6.18.7.2): `Q0 = 2^(NOISE_FLOOR_OFFSET - q0 + 1)
66+/// / (1 + 2^(12 - q1))`, `Q1 = Q0 * 2^(12 - q1)`.
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 - f64::from(pan_raw));
70+ let q0 = temp1 / (1.0 + temp2);
71+ (q0, q0 * temp2)
72+}
73+
106 /// Dequantizes one channel's envelopes and noise floors for one frame,74 /// Dequantizes one channel's envelopes and noise floors for one frame,
107-/// de-mixing through [`dequant_pair`] when `coupling` makes `channels[1]`75+/// de-mixing through [`dequant_pair`]/[`dequant_noise_pair`] when
108-/// a balance channel against `channels[0]`.76+/// `coupling` makes `channels[1]` a balance channel against `channels[0]`.
109 pub fn dequantize_frame(77 pub fn dequantize_frame(
110 header: &SbrHeader,78 header: &SbrHeader,
111 channels: &[SbrChannel],79 channels: &[SbrChannel],
@@ -116,188 +84,116 @@ pub fn dequantize_frame(
116 // A single-envelope frame forces 1.5 dB resolution regardless of84 // A single-envelope frame forces 1.5 dB resolution regardless of
117 // bs_amp_res, mirroring sbr_payload's own `amp_res_of`.85 // 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 };86 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());87+ let coupled = coupling && channels.len() == 2;
120- if coupling && channels.len() == 2 {88+ let pick = |pair: (f64, f64)| if ch == 0 { pair.0 } else { pair.1 };
121- for i in 0..c.e_q.len() {89+ let env = if coupled {
122- let row0 = channels[0].e_q.get(i);90+ (0..c.e_q.len())
123- let row1 = channels[1].e_q.get(i);91+ .map(|i| {
124- let len = c.e_q[i].len();92+ (0..c.e_q[i].len())
125- let mut r = Vec::with_capacity(len);93+ .map(|b| {
126- for b in 0..len {94+ let e0 = channels[0].e_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0);
127- let e0 = row0.and_then(|r| r.get(b)).copied().unwrap_or(0);95+ let pan = channels[1].e_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0);
128- let pan = row1.and_then(|r| r.get(b)).copied().unwrap_or(0);96+ pick(dequant_pair(e0, pan, amp_res, header.amp_res))
129- let (env0, env1) = dequant_pair(e0, pan, amp_res, header.amp_res);97+ })
130- r.push(if ch == 0 { env0 } else { env1 });98+ .collect()
131- }99+ })
132- env.push(r);100+ .collect()
133- }
134 } else {101 } else {
135- for row in &c.e_q {102+ c.e_q.iter().map(|row| row.iter().map(|&v| dequant_env(v, amp_res)).collect()).collect()
136- env.push(row.iter().map(|&v| dequant_env(v, amp_res)).collect());103+ };
137- }104+ let noise = if coupled {
138- }105+ (0..c.q_q.len())
139- // corner-cut: noise floors dequantize independently per channel106+ .map(|i| {
140- // regardless of coupling. A mirrored dequant_noise_pair() demix (see107+ (0..c.q_q[i].len())
141- // git history) was tried and measured ZERO effect on the real-file108+ .map(|b| {
142- // ch1 RMS blow-up (identical output to printed precision), so the109+ let q0 = channels[0].q_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0);
143- // energy dequantization below is the live suspect, not this; reverted110+ let pan = channels[1].q_q.get(i).and_then(|r| r.get(b)).copied().unwrap_or(0);
144- // rather than keeping an unverified formula with no measured benefit.111+ pick(dequant_noise_pair(q0, pan))
145- let noise = c112+ })
146- .q_q113+ .collect()
147- .iter()114+ })
148- .map(|row| row.iter().map(|&v| dequant_noise(v)).collect())115+ .collect()
149- .collect();116+ } else {
117+ c.q_q.iter().map(|row| row.iter().map(|&v| dequant_noise(v)).collect()).collect()
118+ };
150 (env, noise)119 (env, noise)
151 }120 }
152 121
153-/// A small deterministic PRNG for the injected noise floor -- the same122+/// Limiter gain ceilings, `bs_limiter_gains` 0..3 (§4.6.18.7.5, Table 4.150):
154-/// generator shape `decode::Noise` uses, kept local so this module has no123+/// -3 dB, 0 dB, +3 dB, off.
155-/// dependency on the core decoder's internals.124+const LIMITER_FACTOR: [f64; 4] = [0.70795, 1.0, 1.41254, 1.0e10];
156-pub struct NoiseGen {125+const GAIN_MAX_CLIP: f64 = 1.0e5;
157- lcg: u32,126+const BOOST_MAX: f64 = 1.584_893_192;
158- // (Round-44, Task 1/2) The last `LOWPASS_TAPS - 1` raw (pre-scale) draws,127+const H_SMOOTH: [f64; 5] = [
159- // oldest first -- `complex_unit` boxcar-averages the current draw against128+ 0.333_333_333_333_33,
160- // these before scaling, so consecutive calls (one QMF slot apart, same129+ 0.301_502_832_395_82,
161- // band -- see `adjust`'s band-outer/slot-inner loop) are correlated130+ 0.218_169_499_062_49,
162- // instead of independent.131+ 0.115_163_834_270_84,
163- history: std::collections::VecDeque<Complex<f64>>,132+ 0.031_830_500_937_51,
133+];
134+const H_SL: usize = 4;
135+const EPS: f64 = 1.192_092_9e-7;
136+
137+/// Per-channel adjuster state carried across frames (§4.6.18.7.6's
138+/// `G_Temp`/`Q_Temp` slot history, `f_IndexNoise`, `f_IndexSine`, the
139+/// previous frame's `S_indexMapped` and its `l_A`).
140+#[derive(Clone, Debug)]
141+pub struct AdjustState {
142+ s_index_prev: Vec<u8>,
143+ /// Gain/noise vectors of the last `H_SL` slots, oldest first.
144+ g_hist: std::collections::VecDeque<Vec<f64>>,
145+ q_hist: std::collections::VecDeque<Vec<f64>>,
146+ index_noise: usize,
147+ index_sine: usize,
148+ /// Previous frame's `l_A == L_E` (the transient envelope continues into
149+ /// this frame's envelope 0 -- `l_Aprev`).
150+ la_prev_at_end: bool,
151+ pub fresh: bool,
164 }152 }
165 153
166-/// (Round-44, Task 1) `sbr_qmf::Synthesis`'s prototype passband is HALF the154+impl AdjustState {
167-/// decimated slot-rate Nyquist a per-slot i.i.d. draw spans (see155+ pub fn new() -> AdjustState {
168-/// `sbr_qmf.rs`'s module doc and `synthesis_energy_gain_for_...` harness):156+ AdjustState {
169-/// an unfiltered draw already survives Synthesis' overlap-add reasonably157+ s_index_prev: Vec::new(),
170-/// (in-band fraction ~0.49 of a 20000-slot excitation, once the harness's own158+ g_hist: std::collections::VecDeque::new(),
171-/// band-index math was corrected -- see round-44 ledger), but a short boxcar159+ q_hist: std::collections::VecDeque::new(),
172-/// across consecutive slots pulls more of that draw's own spectral energy160+ index_noise: 0,
173-/// into the passband without collapsing it into a near-tone (a wider boxcar161+ index_sine: 0,
174-/// keeps raising in-band fraction but concentrates it into the passband's162+ la_prev_at_end: false,
175-/// own DC edge, losing the noise-like spread across the band the acceptance163+ fresh: true,
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),
185 }164 }
186 }165 }
166+}
187 167
188- fn next(&mut self) -> f64 {168+impl Default for AdjustState {
189- self.lcg = self.lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);169+ fn default() -> Self {
190- // (Round-41, Task 2) `self.0 >> 8` keeps 24 bits (range [0, 2^24));170+ Self::new()
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)
240 }171 }
241 }172 }
242 173
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-
264 fn noise_fraction_debug() -> bool {174 fn noise_fraction_debug() -> bool {
265- std::env::var("EC_AAC_SBR_NOISE_FRACTION_DEBUG").is_ok()175+ std::env::var("EC_AAC_SBR_NOISE_FRACTION").is_ok()
266 }176 }
267 177
268-/// `(band, signal_energy_sum, noise_energy_sum)` for every band that178+static NOISE_FRACTION: std::sync::OnceLock<std::sync::Mutex<Vec<(usize, f64, f64)>>> =
269-/// accumulated anything, both sums slot-count-weighted.179+ std::sync::OnceLock::new();
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-}
283 180
284-fn accumulate_noise_fraction(band: usize, slots: usize, signal: f64, noise: f64) {181+/// Diagnostic (`EC_AAC_SBR_NOISE_FRACTION`): per absolute QMF band,
285- if slots == 0 {182+/// bookkept `(band, Σ signal energy·slots, Σ noise energy·slots)`.
286- return;183+pub fn noise_fraction_table() -> Vec<(usize, f64, f64)> {
287- }184+ let mut out: Vec<(usize, f64, f64)> = NOISE_FRACTION
288- let stats = NOISE_FRACTION_STATS.get_or_init(|| std::sync::Mutex::new(vec![(0.0, 0.0); 256]));185+ .get()
289- let mut g = stats.lock().unwrap();186+ .and_then(|m| m.lock().ok())
290- if band >= g.len() {187+ .map(|g| g.clone())
291- g.resize(band + 1, (0.0, 0.0));188+ .unwrap_or_default();
292- }189+ out.sort_by_key(|e| e.0);
293- g[band].0 += signal * slots as f64;190+ out
294- g[band].1 += noise * slots as f64;
295 }191 }
296 192
297-/// Applies envelope adjustment in place to `hf` (`[target band 0-based193+/// Adjusts `hf` (`[m][slot]`, `m = k - kx`) in place: envelope gains,
298-/// from kx][slot]`, as [`crate::sbr_hf::generate`] returns it): gain194+/// noise floor and added sinusoids per §4.6.18.7.3-7.6. `ch.t_env`/`t_noise`
299-/// toward `env_energy`, the transmitted noise floor from `noise_energy`,195+/// are in QMF slots (already ×2). `reset` mirrors the spec's header-reset
300-/// and sinusoids at `ch.add_harmonic`'s flagged high-resolution bands.196+/// flag (smoothing history primed from the first envelope, indices zeroed).
301 #[allow(clippy::too_many_arguments)]197 #[allow(clippy::too_many_arguments)]
302 pub fn adjust(198 pub fn adjust(
303 hf: &mut [Vec<Complex<f64>>],199 hf: &mut [Vec<Complex<f64>>],
@@ -306,549 +202,265 @@ pub fn adjust(
306 ch: &SbrChannel,202 ch: &SbrChannel,
307 env_energy: &[Vec<f64>],203 env_energy: &[Vec<f64>],
308 noise_energy: &[Vec<f64>],204 noise_energy: &[Vec<f64>],
309- rng: &mut NoiseGen,
310 limiter_table: &[i64],205 limiter_table: &[i64],
206+ state: &mut AdjustState,
207+ reset: bool,
311 ) {208 ) {
312 let kx = tables.kx as usize;209 let kx = tables.kx as usize;
313- let n_lim = limiter_table.len().saturating_sub(1).max(1);210+ let m_max = hf.len();
314- // (Round-22 sweep instrumentation, zero cost unset) `EC_AAC_SBR_LIMITER_OFF`211+ let num_env = ch.t_env.len().saturating_sub(1).min(env_energy.len());
315- // forces the "no limit" factor regardless of the transmitted212+ if m_max == 0 || num_env == 0 {
316- // `bs_limiter_gains`, to probe whether the limiter itself is clipping213+ return;
317- // correlation on real content.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+ }
318 let limiter_max = if std::env::var("EC_AAC_SBR_LIMITER_OFF").is_ok() {224 let limiter_max = if std::env::var("EC_AAC_SBR_LIMITER_OFF").is_ok() {
319 LIMITER_FACTOR[3]225 LIMITER_FACTOR[3]
320 } else {226 } else {
321 LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]227 LIMITER_FACTOR[usize::from(header.limiter_gains).min(3)]
322 };228 };
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).
329 let zero_noise = std::env::var("EC_AAC_SBR_NOISE_ZERO").is_ok();229 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`230+ let limdump = std::env::var("EC_AAC_SBR_CELLDUMP").is_ok();
331- // linearly interpolates each envelope's per-band gain toward the NEXT231+ let track_fraction = noise_fraction_debug();
332- // envelope's gain across the current envelope's time slots, instead of232+ let h_sl = if header.smoothing_mode == 0 { H_SL } else { 0 };
333- // holding it flat -- probing whether our constant-per-cell gain shape233+ let l_a = ch.l_a;
334- // (vs. the spec's smoother per-slot shape) is a live suspect.234+ let l_a_prev: i64 = if state.la_prev_at_end { 0 } else { -1 };
335- let gain_lerp = std::env::var("EC_AAC_SBR_GAIN_LERP").is_ok();235+ let n_lim = limiter_table.len().saturating_sub(1);
336- // (Round-43, Task 1) `EC_AAC_SBR_CELLDUMP=band[,band...]` -- comma list236+
337- // of ABSOLUTE QMF band indices (same units as `kx`/`k2`/`f_high`,237+ // §4.6.18.7.2 mapping + §4.6.18.7.3 E_curr + §4.6.18.7.5 gains, per env.
338- // `band_hz = rate/128`, per round-42's fixed test-side mapping) -- dumps238+ let mut gain = vec![vec![0.0f64; m_max]; num_env];
339- // every (envelope, band) cell whose `[lo,hi)` range covers a listed239+ let mut q_m = vec![vec![0.0f64; m_max]; num_env];
340- // band: target/signal_target/noise_here/measured cur/raw+capped gain/240+ let mut s_m = vec![vec![0.0f64; m_max]; num_env];
341- // boost/namp/sinusoid amp, and the actually-injected noise energy that241+ let mut s_index_prev = state.s_index_prev.clone();
342- // frame, to stderr.242+ for e in 0..num_env {
343- let celldump: Vec<usize> = std::env::var("EC_AAC_SBR_CELLDUMP")243+ let (t0, t1) = (ch.t_env[e].max(0) as usize, ch.t_env[e + 1].max(0) as usize);
344- .ok()244+ let high_res = ch.freq_res.get(e).copied().unwrap_or(0) != 0;
345- .map(|s| s.split(',').filter_map(|t| t.trim().parse().ok()).collect())245+ let table: &[i64] = if high_res { &tables.f_high } else { &tables.f_low };
346- .unwrap_or_default();246+ let n_bands = table.len().saturating_sub(1);
347-247+ // E_origMapped
348- // Gain toward the transmitted envelope, per (envelope, band) cell,248+ let mut e_orig = vec![0.0f64; m_max];
349- // limited relative to that cell's own noise floor.249+ for i in 0..n_bands {
350- for (ei, (t0, t1)) in ch.t_env.windows(2).map(|w| (w[0], w[1])).enumerate() {250+ let v = env_energy[e].get(i).copied().unwrap_or(0.0);
351- if ei >= env_energy.len() {251+ for k in table[i]..table[i + 1] {
352- break;252+ let m = k as usize - kx.min(k as usize);
353- }253+ if k as usize >= kx && m < m_max {
354- let high_res = ch.freq_res.get(ei).copied().unwrap_or(0) != 0;254+ e_orig[m] = v;
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;
411 }255 }
412 }256 }
413- let current = if count > 0 { sum / count as f64 } else { 0.0 };257+ }
414- let q = noise_band_for(tables, lo);258+ // Q_mapped: noise floor covering this envelope's start.
415- // `dequant_noise` returns `Q_div = 2^(NOISE_FLOOR_OFFSET-q_q)`, a259+ let nf = usize::from(ch.t_noise.len() > 2 && ch.t_env[e] >= ch.t_noise[1]);
416- // ratio relative to this cell's OWN envelope target -- not an260+ let mut q_mapped = vec![0.0f64; m_max];
417- // absolute energy in the same units as `target` (round-21 Task261+ if let Some(row) = noise_energy.get(nf.min(noise_energy.len().saturating_sub(1))) {
418- // 1/2: a reference-decoder q_q sweep at a FIXED envelope target262+ for i in 0..tables.n_q.min(tables.f_noise.len().saturating_sub(1)) {
419- // showed total output power staying nearly flat as q_q swept its263+ let v = row.get(i).copied().unwrap_or(0.0);
420- // whole range, the signature of `target` being split264+ for k in tables.f_noise[i]..tables.f_noise[i + 1] {
421- // `signal=target/(1+Q_div)`, `noise=target*Q_div/(1+Q_div)`265+ if k as usize >= kx && (k as usize - kx) < m_max {
422- // rather than noise being added independently on top of the full266+ q_mapped[k as usize - kx] = v;
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;
460 }267 }
461- accumulate_noise_fraction(band, slots, signal_target, noise_here);
462 }268 }
463 }269 }
464 }270 }
465- // (Round-43, Task 1) `raw_gain` (pre-cap) is about to be overwritten271+ // S_indexMapped (centre subband of each flagged high-res band, from
466- // in place inside `gains` below; keep an uncapped copy for the272+ // l_A on, or carried over from the previous frame) and S_mapped.
467- // celldump so its "cap applied?" column can compare against it.273+ let mut s_index = vec![0u8; m_max];
468- let raw_gains: Vec<f64> = if celldump.is_empty() {274+ if let Some(flags) = &ch.add_harmonic {
469- Vec::new()275+ for i in 0..tables.f_high.len().saturating_sub(1) {
470- } else {276+ let mid = ((tables.f_high[i] + tables.f_high[i + 1]) >> 1) as usize;
471- gains.clone()277+ if mid < kx || mid - kx >= m_max {
472- };278+ continue;
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;
486- }
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;
498- }
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)
505- } else {
506- 1.0
507 }279 }
508- })280+ let on = flags.get(i).copied().unwrap_or(0) != 0;
509- .collect();281+ s_index[mid - kx] =
510- // (Round-57 audit, ISO/IEC 14496-3 4.6.18.7.5/.7.6) Per-limiter-band282+ u8::from(on && ((e as i64) >= l_a || s_index_prev[mid - kx] == 1));
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 {
518- 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),
524- 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],
532- );
533 }283 }
534 }284 }
535- for b in 0..gains.len() {285+ let mut s_mapped = vec![false; m_max];
536- let j = cell_lim[b];286+ for i in 0..n_bands {
537- gains[b] *= lim_boost[j];287+ let lo = (table[i] as usize).max(kx) - kx;
538- // (Round-42, Task 1 corollary) `cell_noise_here[b]` is already a288+ let hi = ((table[i + 1] as usize).max(kx) - kx).min(m_max);
539- // PER-SAMPLE average energy (same units as `target`/`current` --289+ let any = (lo..hi).any(|m| s_index[m] != 0);
540- // see `raw_gain = sqrt(signal_target / cur)` just above, which290+ for m in lo..hi {
541- // treats both sides as per-sample averages without any width291+ s_mapped[m] = any;
542- // normalization). Dividing by the cell's QMF-band width here292+ }
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 }293 }
552- // (Round-43, Task 1) per-cell diagnostic dump for `EC_AAC_SBR_CELLDUMP`294+ s_index_prev = s_index.clone();
553- // -- printed before the application loop below so it reflects the295+ // E_curr (§4.6.18.7.3), bs_interpol_freq 1 per subband / 0 per band.
554- // gain/noise-amplitude values that loop is about to use; the296+ let mut e_curr = vec![0.0f64; m_max];
555- // actually-injected sample energy (which depends on the RNG draws297+ let slots = (t1.saturating_sub(t0)).max(1) as f64;
556- // that loop consumes) is measured separately and printed right298+ if header.interpol_freq != 0 {
557- // after it, tagged with the same `ei`/band range so the two lines299+ for m in 0..m_max {
558- // pair up by eye.300+ let row = &hf[m];
559- if !celldump.is_empty() {301+ let sum: f64 =
560- for b in 0..table.len().saturating_sub(1) {302+ (t0..t1.min(row.len())).map(|i| row[i].norm_sqr()).sum();
561- let lo = table[b] as usize;303+ e_curr[m] = sum / slots;
562- let hi = table[b + 1] as usize;304+ }
563- if !celldump.iter().any(|&cb| cb >= lo && cb < hi) {305+ } else {
564- continue;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>();
565 }313 }
566- let target = env_energy[ei].get(b).copied().unwrap_or(0.0);314+ let v = sum / (slots * (hi.saturating_sub(lo)).max(1) as f64);
567- let noise_here = cell_noise_here[b];315+ for m in lo..hi {
568- let signal_target = target - noise_here;316+ e_curr[m] = v;
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- }
600- }
601 }317 }
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- );
608 }318 }
609 }319 }
610- // (Round-22 sweep instrumentation) the next envelope's gains, only320+ // Gains, limiter and boost (§4.6.18.7.5), per limiter band.
611- // when `EC_AAC_SBR_GAIN_LERP` is set and the band layouts match --321+ let delta = !((e as i64) == l_a || (e as i64) == l_a_prev);
612- // `hf` in the next envelope's time range is still untouched at this322+ let deltaf = if delta { 1.0 } else { 0.0 };
613- // point (envelopes are processed and applied in time order), so323+ for j in 0..n_lim {
614- // this reads the same raw HF estimate the next iteration would.324+ let lo = (limiter_table[j] as usize).max(kx) - kx;
615- let next_gains: Option<Vec<f64>> =325+ let hi = ((limiter_table[j + 1] as usize).max(kx) - kx).min(m_max);
616- if gain_lerp && ei + 1 < env_energy.len() && ei + 2 < ch.t_env.len() {326+ if lo >= hi {
617- let (t0n, t1n) = (ch.t_env[ei + 1], ch.t_env[ei + 2]);327+ continue;
618- let high_res_n = ch.freq_res.get(ei + 1).copied().unwrap_or(0) != 0;328+ }
619- let table_n: &[i64] = if high_res_n {329+ for m in lo..hi {
620- &tables.f_high330+ let temp = e_orig[m] / (1.0 + q_mapped[m]);
621- } else {331+ q_m[e][m] = (temp * q_mapped[m]).sqrt();
622- &tables.f_low332+ s_m[e][m] = (temp * f64::from(s_index[m])).sqrt();
623- };333+ gain[e][m] = if !s_mapped[m] {
624- if table_n.len() == table.len() {334+ (e_orig[m] / ((1.0 + e_curr[m]) * (1.0 + q_mapped[m] * deltaf))).sqrt()
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 {335 } else {
642- None336+ (e_orig[m] * q_mapped[m] / ((1.0 + e_curr[m]) * (1.0 + q_mapped[m]))).sqrt()
643- }337+ } + f64::MIN_POSITIVE;
644- } else {338+ }
645- None339+ let sum_orig: f64 = (lo..hi).map(|m| e_orig[m]).sum();
646- };340+ let sum_curr: f64 = (lo..hi).map(|m| e_curr[m]).sum();
647- // `bs_interpol_freq` (per-subband linear interpolation of these sfb341+ let g_max = (limiter_max * ((EPS + sum_orig) / (EPS + sum_curr)).sqrt()).min(GAIN_MAX_CLIP);
648- // gains, Sec 4.6.18.7.6) was tried here: a centre-frequency lerp342+ let mut capped = 0usize;
649- // between neighbouring sfbs' flat gain values, applied whenever343+ for m in lo..hi {
650- // `header.interpol_freq != 0`. Measured effect on the real-file344+ let q_max = q_m[e][m] * g_max / gain[e][m];
651- // sweep was NEGATIVE (reeln ch0 full-band 0.972756 -> 0.960561)345+ q_m[e][m] = q_m[e][m].min(q_max);
652- // -- the reference decoder's actual interpolation shape (weighting,346+ if gain[e][m] > g_max {
653- // node placement, or which quantity gets interpolated) differs from347+ capped += 1;
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;
678- }
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- }
706 }348 }
349+ gain[e][m] = gain[e][m].min(g_max);
707 }350 }
708- }351+ let sum_act: f64 = (lo..hi)
709- if !celldump.is_empty() {352+ .map(|m| {
710- for (&band, &(noise_sum, signal_sum, count)) in &celldump_injected {353+ e_curr[m] * gain[e][m] * gain[e][m]
711- let (post_sum, post_count) = celldump_post.get(&band).copied().unwrap_or((0.0, 0));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 {
712 eprintln!(365 eprintln!(
713- "CELLDUMP ei={ei} band={band} actually_injected_noise_energy={:.6e} \366+ "LIMDUMP ei={e} band=[{},{}) limiter_bands={} j={j}/{n_lim} \
714- actual_signal_only_energy={:.6e} post_addition_energy={:.6e} (n={count})",367+ E_orig_mapped={sum_orig:.6e} E_curr={sum_curr:.6e} G_max={g_max:.6} \
715- if count > 0 {368+ capped_cells={capped}/{} E_actual={sum_act:.6e} G_boost={boost:.6}",
716- noise_sum / count as f64369+ limiter_table[j],
717- } else {370+ limiter_table[j + 1],
718- 0.0371+ header.limiter_bands,
719- },372+ hi - lo,
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 );373 );
731 }374 }
732 }375 }
733-376+ if track_fraction {
734- // Sinusoids: one extra tone per flagged high-resolution band,377+ let tab = NOISE_FRACTION.get_or_init(|| std::sync::Mutex::new(Vec::new()));
735- // added after gain so its amplitude is exact regardless of the378+ if let Ok(mut t) = tab.lock() {
736- // cell's measured HF energy.379+ for m in 0..m_max {
737- if let Some(flags) = &ch.add_harmonic {380+ let sig = e_orig[m] / (1.0 + q_mapped[m]) * slots;
738- for (b, &on) in flags.iter().enumerate() {381+ let noi = e_orig[m] * q_mapped[m] / (1.0 + q_mapped[m]) * slots;
739- if on == 0 || b + 1 >= tables.f_high.len() {382+ if let Some(row) = t.iter_mut().find(|r| r.0 == m + kx) {
740- continue;383+ row.1 += sig;
741- }384+ row.2 += noi;
742- let lo = tables.f_high[b] as usize;385+ } else {
743- let hi = tables.f_high[b + 1] as usize;386+ t.push((m + kx, sig, noi));
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);
765 }387 }
766 }388 }
767 }389 }
768 }390 }
769 }391 }
770-392+ state.s_index_prev = s_index_prev;
771- // (Round-21) Noise is now injected inside the envelope-gain loop above,393+ state.la_prev_at_end = l_a == num_env as i64;
772- // per (envelope, band) cell using each cell's own `signal_target`/394+
773- // `noise_here` split -- the noise grid is coarser than the envelope395+ // §4.6.18.7.6 assembly: smoothing over the previous H_SL slots, noise
774- // grid but every envelope cell resolves its own noise band via396+ // from the V table, sinusoids with the (-1)^k phase alternation.
775- // `noise_band_for`/`noise_row`, so this covers the same ground the old397+ if reset || state.g_hist.len() != h_sl {
776- // separate noise-grid pass did, consistently with the gain that was398+ state.g_hist.clear();
777- // computed for the same cell (previously the two were split across399+ state.q_hist.clear();
778- // unrelated unit scales; see the comment at `noise_div` above).400+ for _ in 0..h_sl {
779-}401+ state.g_hist.push_back(gain[0].clone());
780-402+ state.q_hist.push_back(q_m[0].clone());
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 }403 }
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 }404 }
826- gains405+ let phi_sign = if kx & 1 == 1 { -1.0 } else { 1.0 };
827-}406+ let mut g_filt = vec![0.0f64; m_max];
828-407+ let mut q_filt = vec![0.0f64; m_max];
829-/// Finds which limiter band (from [`crate::sbr_hf::limiter_band_table`])408+ for e in 0..num_env {
830-/// a `[lo, hi)` QMF-band cell falls into, by its midpoint.409+ let (t0, t1) = (ch.t_env[e].max(0) as usize, ch.t_env[e + 1].max(0) as usize);
831-fn limiter_band_index(limiter_table: &[i64], lo: usize, hi: usize) -> usize {410+ let transient = (e as i64) == l_a || (e as i64) == l_a_prev;
832- if limiter_table.len() < 2 {411+ for i in t0..t1 {
833- return 0;412+ if h_sl > 0 && !transient {
834- }413+ for m in 0..m_max {
835- let mid = (lo + hi) as i64 / 2;414+ let mut g = gain[e][m] * H_SMOOTH[0];
836- for j in 0..limiter_table.len() - 1 {415+ let mut q = q_m[e][m] * H_SMOOTH[0];
837- if mid < limiter_table[j + 1] {416+ for j in 1..=h_sl {
838- return j;417+ // g_hist is oldest-first; j=1 is the most recent slot.
839- }418+ g += state.g_hist[h_sl - j][m] * H_SMOOTH[j];
840- }419+ q += state.q_hist[h_sl - j][m] * H_SMOOTH[j];
841- limiter_table.len() - 2420+ }
842-}421+ g_filt[m] = g;
843-422+ q_filt[m] = q;
844-fn noise_band_for(tables: &BandTables, low_band: usize) -> usize {423+ }
845- let mut q = 0usize;424+ } else {
846- for i in 0..tables.n_q {425+ g_filt.copy_from_slice(&gain[e]);
847- if (low_band as i64) >= tables.f_noise[i] {426+ q_filt.copy_from_slice(&q_m[e]);
848- q = i;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),
441+ };
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;
448+ }
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);
456+ }
457+ row[i] = y;
458+ p_im = -p_im;
459+ }
460+ state.index_noise = (state.index_noise + m_max) & 0x1ff;
461+ state.index_sine = (state.index_sine + 1) & 3;
849 }462 }
850 }463 }
851- q
852 }464 }
853 465
854 #[cfg(test)]466 #[cfg(test)]
@@ -878,237 +490,85 @@ mod tests {
878 }490 }
879 }491 }
880 492
881- #[test]493+ fn channel(tables: &BandTables, add_harmonic: Option<Vec<u8>>) -> SbrChannel {
882- fn flat_hf_region_reaches_the_stated_envelope_energy() {494+ SbrChannel {
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 {
889 t_env: vec![0, 16],495 t_env: vec![0, 16],
890- freq_res: vec![0],496+ freq_res: vec![1],
891 t_noise: vec![0, 16],497 t_noise: vec![0, 16],
892- e_q: vec![vec![]],498+ e_q: vec![vec![0; tables.n_high]],
893- q_q: vec![vec![]],499+ q_q: vec![vec![0; tables.n_q]],
894 invf_mode: vec![],500 invf_mode: vec![],
895- add_harmonic: None,501+ add_harmonic,
896 df_env: vec![],502 df_env: vec![],
897 df_noise: vec![],503 df_noise: vec![],
898- };504+ l_a: -1,
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- );
939 }505 }
940 }506 }
941 507
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.
950- #[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]508 #[test]
963- fn limiter_stays_finite_on_a_uniformly_starved_band() {509+ fn flat_hf_region_reaches_the_stated_envelope_energy() {
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.
977 let tables = flat_tables();510 let tables = flat_tables();
978- let kx = tables.kx as usize;511+ let (kx, k2) = (tables.kx as usize, tables.k2 as usize);
979- let k2 = tables.k2 as usize;
980 let slots = 16usize;512 let slots = 16usize;
981- let mut hf = vec![vec![Complex::new(1e-9, 0.0); slots]; k2 - kx];513+ let mut hf = vec![vec![Complex::new(0.1, 0.0); slots]; k2 - kx];
982- let ch = SbrChannel {514+ let target = 4.0f64;
983- t_env: vec![0, 16],515+ let env_energy = vec![vec![target; tables.n_high]];
984- freq_res: vec![0],516+ // Q_mapped = 1 (q_q = 6): half the target is noise.
985- t_noise: vec![0, 16],517+ let noise_energy = vec![vec![1.0f64; tables.n_q]];
986- e_q: vec![vec![]],518+ let hdr = header(1, 3);
987- q_q: vec![vec![]],519+ let lim = limiter_band_table(&tables, &build_patches(&tables), hdr.limiter_bands);
988- invf_mode: vec![],520+ let mut st = AdjustState::new();
989- add_harmonic: None,521+ adjust(&mut hf, &tables, &hdr, &channel(&tables, None), &env_energy, &noise_energy, &lim, &mut st, true);
990- df_env: vec![],522+ for m in 0..k2 - kx {
991- df_noise: vec![],523+ let avg: f64 = hf[m].iter().map(|c| c.norm_sqr()).sum::<f64>() / slots as f64;
992- };524+ // signal share exactly target/2 (flat input, G cancels E_curr);
993- let env_energy = vec![vec![1.0e6f64; tables.n_low]];525+ // noise share target/2 in expectation over the V table.
994- // (Round-21) noise_energy is now a Q_div ratio against the cell's526+ assert!((avg - target).abs() / target < 0.4, "m={m}: avg {avg} vs target {target}");
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- }
1022 }527 }
1023 }528 }
1024 529
1025 #[test]530 #[test]
1026- fn a_content_empty_cell_inherits_its_limiter_bands_aggregate_cap() {531+ fn sinusoid_lands_on_the_centre_subband_only_and_mutes_noise_there() {
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.
1033 let tables = flat_tables();532 let tables = flat_tables();
1034- let kx = tables.kx as usize;533+ let (kx, k2) = (tables.kx as usize, tables.k2 as usize);
1035- let k2 = tables.k2 as usize;
1036 let slots = 16usize;534 let slots = 16usize;
1037- let mut hf = vec![vec![Complex::new(0.1, 0.0); slots]; k2 - kx];535+ let mut hf = vec![vec![Complex::ZERO; slots]; k2 - kx];
1038- // Silence the top half of the HF region (the empty target cell).536+ let mut flags = vec![0u8; tables.n_high];
1039- let mid = hf.len() / 2;537+ flags[1] = 1;
1040- for row in &mut hf[mid..] {538+ let env_energy = vec![vec![4.0f64; tables.n_high]];
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]];
1058 let noise_energy = vec![vec![0.0f64; tables.n_q]];539 let noise_energy = vec![vec![0.0f64; tables.n_q]];
1059- let mut rng = NoiseGen::new(1);540+ let hdr = header(1, 1);
1060- let mut h = header(1, 1);541+ let lim = limiter_band_table(&tables, &build_patches(&tables), hdr.limiter_bands);
1061- h.limiter_bands = 0; // single aggregate band spanning the whole HF region542+ let mut st = AdjustState::new();
1062- let lim_table = limiter_band_table(&tables, &build_patches(&tables), h.limiter_bands);543+ adjust(&mut hf, &tables, &hdr, &channel(&tables, Some(flags)), &env_energy, &noise_energy, &lim, &mut st, true);
1063- assert_eq!(lim_table, vec![tables.kx, tables.k2]);544+ let mid = ((tables.f_high[1] + tables.f_high[2]) >> 1) as usize - kx;
1064- adjust(545+ for m in 0..k2 - kx {
1065- &mut hf,546+ let e: f64 = hf[m].iter().map(|c| c.norm_sqr()).sum::<f64>() / slots as f64;
1066- &tables,547+ if m == mid {
1067- &h,548+ // S_M^2 = E_orig/(1+Q) = 4, boost capped at 1.5849^2 at most.
1068- &ch,549+ assert!(e >= 4.0 - 1e-9 && e <= 4.0 * BOOST_MAX * BOOST_MAX + 1e-6, "mid {e}");
1069- &env_energy,550+ // Phase walks 0,90,180,270 degrees per slot.
1070- &noise_energy,551+ assert!((hf[m][0].re - hf[m][0].norm_sqr().sqrt()).abs() < 1e-9 && hf[m][1].re.abs() < 1e-9);
1071- &mut rng,552+ } else {
1072- &lim_table,553+ assert!(e < 1e-9, "m={m}: {e}");
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- );
1084 }554 }
1085 }555 }
1086 }556 }
1087 557
1088 #[test]558 #[test]
1089 fn coupled_balance_round_trips_at_a_centred_ratio() {559 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);560 let (e0, e1) = dequant_pair(10, 12, 1, 1);
1094 let e0_plain = dequant_env(10, 1);561 let e0_plain = dequant_env(10, 1);
1095- assert!(562+ assert!((e0 - e0_plain).abs() < 1e-6 && (e1 - e0_plain).abs() < 1e-6, "{e0} {e1} vs {e0_plain}");
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);563 let (e00, e10) = dequant_pair(10, 24, 0, 0);
1100 let e00_plain = dequant_env(10, 0);564 let e00_plain = dequant_env(10, 0);
1101- assert!(565+ assert!((e00 - e00_plain).abs() < 1e-6 && (e10 - e00_plain).abs() < 1e-6, "{e00} {e10} vs {e00_plain}");
1102- (e00 - e00_plain).abs() < 1e-6 && (e10 - e00_plain).abs() < 1e-6,566+ let (q0, q1) = dequant_noise_pair(3, 12);
1103- "{e00} {e10} vs {e00_plain}"567+ assert!((q0 - dequant_noise(3)).abs() < 1e-9 && (q1 - q0).abs() < 1e-9);
1104- );
1105 }568 }
1106 569
1107 #[test]570 #[test]
1108 fn coupled_balance_shifts_energy_toward_the_channel_with_a_higher_raw_value() {571 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);572 let (e0_low, e1_low) = dequant_pair(10, 0, 1, 1);
1113 let (e0_high, e1_high) = dequant_pair(10, 24, 1, 1);573 let (e0_high, e1_high) = dequant_pair(10, 24, 1, 1);
1114 assert!(e0_low > e1_low, "{e0_low} vs {e1_low}");574 assert!(e0_low > e1_low, "{e0_low} vs {e1_low}");
crates/ec-aac/src/sbr_payload.rsmodified+29 -14
@@ -23,7 +23,7 @@ use ec_core::{BitReader, Error, Result};
23 const NUM_TIME_SLOTS: i64 = 16;23 const NUM_TIME_SLOTS: i64 = 16;
24 24
25 /// `sbr_header()` fields, held across frames: a stream need not repeat it.25 /// `sbr_header()` fields, held across frames: a stream need not repeat it.
26-#[derive(Clone, Debug)]26+#[derive(Clone, Debug, PartialEq, Eq)]
27 pub struct SbrHeader {27 pub struct SbrHeader {
28 pub amp_res: u8,28 pub amp_res: u8,
29 pub start_freq: u8,29 pub start_freq: u8,
@@ -60,6 +60,10 @@ pub struct SbrChannel {
60 pub df_env: Vec<u8>,60 pub df_env: Vec<u8>,
61 /// `bs_df_noise` per noise floor, same convention as `df_env`.61 /// `bs_df_noise` per noise floor, same convention as `df_env`.
62 pub df_noise: Vec<u8>,62 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,
63 }67 }
64 68
65 /// One `sbr_data()` frame: one channel for an SCE, two for a CPE.69 /// One `sbr_data()` frame: one channel for an SCE, two for a CPE.
@@ -79,31 +83,41 @@ struct Grid {
79 freq_res: Vec<u8>,83 freq_res: Vec<u8>,
80 t_env: Vec<i64>,84 t_env: Vec<i64>,
81 t_noise: Vec<i64>,85 t_noise: Vec<i64>,
86+ l_a: i64,
82 }87 }
83 88
84 impl Grid {89 impl Grid {
85- /// `pointer` is `bs_pointer` (0 for FIXFIX, which has no such field --90+ /// `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 is91+ /// Middle noise border and `l_A` per ISO/IEC 14496-3 §4.6.18.3.3,
87- /// `num_env >> 1`). Per ISO/IEC 14496-3 §4.6.18.3.3: `bs_pointer == 0`92+ /// Tables 4.146/4.147 -- they depend on `frame_class` (0 FIXFIX,
88- /// selects `num_env >> 1`, `== 1` selects the last envelope border93+ /// 1 FIXVAR, 2 VARFIX, 3 VARVAR), not on `bs_pointer` alone.
89- /// (`num_env - 1`), otherwise `bs_pointer - 1`.94+ fn new(num_env: usize, freq_res: Vec<u8>, t_env: Vec<i64>, pointer: usize, frame_class: u32) -> Grid {
90- fn new(num_env: usize, freq_res: Vec<u8>, t_env: Vec<i64>, pointer: usize) -> Grid {
91 let num_noise = if num_env == 1 { 1 } else { 2 };95 let num_noise = if num_env == 1 { 1 } else { 2 };
92 let t_noise = if num_noise == 1 {96 let t_noise = if num_noise == 1 {
93 vec![t_env[0], t_env[num_env]]97 vec![t_env[0], t_env[num_env]]
94 } else {98 } else {
95- let middle = match pointer {99+ let middle = match frame_class {
96 0 => num_env >> 1,100 0 => num_env >> 1,
97- 1 => num_env - 1,101+ 1 | 3 => num_env - pointer.saturating_sub(1).max(1),
98- p => p - 1,102+ _ => match pointer {
103+ 0 => 1,
104+ 1 => num_env - 1,
105+ p => p - 1,
106+ },
99 };107 };
100- vec![t_env[0], t_env[middle], t_env[num_env]]108+ vec![t_env[0], t_env[middle.min(num_env)], t_env[num_env]]
109+ };
110+ let l_a = match frame_class {
111+ 1 | 3 if pointer > 0 => num_env as i64 + 1 - pointer as i64,
112+ 2 if pointer > 1 => pointer as i64 - 1,
113+ _ => -1,
101 };114 };
102 Grid {115 Grid {
103 num_env,116 num_env,
104 freq_res,117 freq_res,
105 t_env,118 t_env,
106 t_noise,119 t_noise,
120+ l_a,
107 }121 }
108 }122 }
109 }123 }
@@ -237,7 +251,7 @@ impl SbrParser {
237 let t_env: Vec<i64> = (0..=num_env)251 let t_env: Vec<i64> = (0..=num_env)
238 .map(|i| (i as i64) * NUM_TIME_SLOTS / num_env as i64)252 .map(|i| (i as i64) * NUM_TIME_SLOTS / num_env as i64)
239 .collect();253 .collect();
240- Ok(Grid::new(num_env, vec![fr; num_env], t_env, 0))254+ Ok(Grid::new(num_env, vec![fr; num_env], t_env, 0, 0))
241 }255 }
242 1 | 2 => {256 1 | 2 => {
243 // FIXVAR (1, trailing variable border) / VARFIX (2, leading variable border)257 // FIXVAR (1, trailing variable border) / VARFIX (2, leading variable border)
@@ -285,7 +299,7 @@ impl SbrParser {
285 }299 }
286 t[num_env] = NUM_TIME_SLOTS;300 t[num_env] = NUM_TIME_SLOTS;
287 }301 }
288- Ok(Grid::new(num_env, freq_res, t, pointer))302+ Ok(Grid::new(num_env, freq_res, t, pointer, frame_class))
289 }303 }
290 _ => {304 _ => {
291 // VARVAR305 // VARVAR
@@ -325,7 +339,7 @@ impl SbrParser {
325 if t.windows(2).any(|w| w[0] >= w[1]) {339 if t.windows(2).any(|w| w[0] >= w[1]) {
326 return Err(Error::corrupt("sbr: non-monotone envelope time borders"));340 return Err(Error::corrupt("sbr: non-monotone envelope time borders"));
327 }341 }
328- Ok(Grid::new(num_env, freq_res, t, pointer))342+ Ok(Grid::new(num_env, freq_res, t, pointer, frame_class))
329 }343 }
330 }344 }
331 }345 }
@@ -628,6 +642,7 @@ impl SbrParser {
628 add_harmonic: None,642 add_harmonic: None,
629 df_env: df_env[ch].iter().map(|&b| u8::from(b)).collect(),643 df_env: df_env[ch].iter().map(|&b| u8::from(b)).collect(),
630 df_noise: df_noise[ch].iter().map(|&b| u8::from(b)).collect(),644 df_noise: df_noise[ch].iter().map(|&b| u8::from(b)).collect(),
645+ l_a: grids[ch].l_a,
631 });646 });
632 }647 }
633 648
crates/ec-aac/src/sbr_tables.rsmodified+518 -0
@@ -749,6 +749,524 @@ pub(crate) static NOISEB_F: [(u8, u32, i32); 25] = [
749 (14, 16383, 12),749 (14, 16383, 12),
750 ];750 ];
751 751
752+/// ISO/IEC 14496-3 Table 4.A.88: the 512-entry complex noise sequence
753+/// `V` the envelope adjuster draws from (`f_IndexNoise` wraps at 512), as
754+/// `(re, im)` pairs.
755+pub(crate) static SBR_NOISE: [(f64, f64); 512] = [
756+ (-0.99948153278296, -0.59483417516607),
757+ (0.97113454393991, -0.67528515225647),
758+ (0.14130051758487, -0.95090983575689),
759+ (-0.47005496701697, -0.37340549728647),
760+ (0.80705063769351, 0.29653668284408),
761+ (-0.38981478896926, 0.89572605717087),
762+ (-0.01053049862020, -0.66959058036166),
763+ (-0.91266367957293, -0.11522938140034),
764+ (0.54840422910309, 0.75221367176302),
765+ (0.40009252867955, -0.98929400334421),
766+ (-0.99867974711855, -0.88147068645358),
767+ (-0.95531076805040, 0.90908757154593),
768+ (-0.45725933317144, -0.56716323646760),
769+ (-0.72929675029275, -0.98008272727324),
770+ (0.75622801399036, 0.20950329995549),
771+ (0.07069442601050, -0.78247898470706),
772+ (0.74496252926055, -0.91169004445807),
773+ (-0.96440182703856, -0.94739918296622),
774+ (0.30424629369539, -0.49438267012479),
775+ (0.66565033746925, 0.64652935542491),
776+ (0.91697008020594, 0.17514097332009),
777+ (-0.70774918760427, 0.52548653416543),
778+ (-0.70051415345560, -0.45340028808763),
779+ (-0.99496513054797, -0.90071908066973),
780+ (0.98164490790123, -0.77463155528697),
781+ (-0.54671580548181, -0.02570928536004),
782+ (-0.01689629065389, 0.00287506445732),
783+ (-0.86110349531986, 0.42548583726477),
784+ (-0.98892980586032, -0.87881132267556),
785+ (0.51756627678691, 0.66926784710139),
786+ (-0.99635026409640, -0.58107730574765),
787+ (-0.99969370862163, 0.98369989360250),
788+ (0.55266258627194, 0.59449057465591),
789+ (0.34581177741673, 0.94879421061866),
790+ (0.62664209577999, -0.74402970906471),
791+ (-0.77149701404973, -0.33883658042801),
792+ (-0.91592244254432, 0.03687901376713),
793+ (-0.76285492357887, -0.91371867919124),
794+ (0.79788337195331, -0.93180971199849),
795+ (0.54473080610200, -0.11919206037186),
796+ (-0.85639281671058, 0.42429854760451),
797+ (-0.92882402971423, 0.27871809078609),
798+ (-0.11708371046774, -0.99800843444966),
799+ (0.21356749817493, -0.90716295627033),
800+ (-0.76191692573909, 0.99768118356265),
801+ (0.98111043100884, -0.95854459734407),
802+ (-0.85913269895572, 0.95766566168880),
803+ (-0.93307242253692, 0.49431757696466),
804+ (0.30485754879632, -0.70540034357529),
805+ (0.85289650925190, 0.46766131791044),
806+ (0.91328082618125, -0.99839597361769),
807+ (-0.05890199924154, 0.70741827819497),
808+ (0.28398686150148, 0.34633555702188),
809+ (0.95258164539612, -0.54893416026939),
810+ (-0.78566324168507, -0.75568541079691),
811+ (-0.95789495447877, -0.20423194696966),
812+ (0.82411158711197, 0.96654618432562),
813+ (-0.65185446735885, -0.88734990773289),
814+ (-0.93643603134666, 0.99870790442385),
815+ (0.91427159529618, -0.98290505544444),
816+ (-0.70395684036886, 0.58796798221039),
817+ (0.00563771969365, 0.61768196727244),
818+ (0.89065051931895, 0.52783352697585),
819+ (-0.68683707712762, 0.80806944710339),
820+ (0.72165342518718, -0.69259857349564),
821+ (-0.62928247730667, 0.13627037407335),
822+ (0.29938434065514, -0.46051329682246),
823+ (-0.91781958879280, -0.74012716684186),
824+ (0.99298717043688, 0.40816610075661),
825+ (0.82368298622748, -0.74036047190173),
826+ (-0.98512833386833, -0.99972330709594),
827+ (-0.95915368242257, -0.99237800466040),
828+ (-0.21411126572790, -0.93424819052545),
829+ (-0.68821476106884, -0.26892306315457),
830+ (0.91851997982317, 0.09358228901785),
831+ (-0.96062769559127, 0.36099095133739),
832+ (0.51646184922287, -0.71373332873917),
833+ (0.61130721139669, 0.46950141175917),
834+ (0.47336129371299, -0.27333178296162),
835+ (0.90998308703519, 0.96715662938132),
836+ (0.44844799194357, 0.99211574628306),
837+ (0.66614891079092, 0.96590176169121),
838+ (0.74922239129237, -0.89879858826087),
839+ (-0.99571588506485, 0.52785521494349),
840+ (0.97401082477563, -0.16855870075190),
841+ (0.72683747733879, -0.48060774432251),
842+ (0.95432193457128, 0.68849603408441),
843+ (-0.72962208425191, -0.76608443420917),
844+ (-0.85359479233537, 0.88738125901579),
845+ (-0.81412430338535, -0.97480768049637),
846+ (-0.87930772356786, 0.74748307690436),
847+ (-0.71573331064977, -0.98570608178923),
848+ (0.83524300028228, 0.83702537075163),
849+ (-0.48086065601423, -0.98848504923531),
850+ (0.97139128574778, 0.80093621198236),
851+ (0.51992825347895, 0.80247631400510),
852+ (-0.00848591195325, -0.76670128000486),
853+ (-0.70294374303036, 0.55359910445577),
854+ (-0.95894428168140, -0.43265504344783),
855+ (0.97079252950321, 0.09325857238682),
856+ (-0.92404293670797, 0.85507704027855),
857+ (-0.69506469500450, 0.98633412625459),
858+ (0.26559203620024, 0.73314307966524),
859+ (0.28038443336943, 0.14537913654427),
860+ (-0.74138124825523, 0.99310339807762),
861+ (-0.01752795995444, -0.82616635284178),
862+ (-0.55126773094930, -0.98898543862153),
863+ (0.97960898850996, -0.94021446752851),
864+ (-0.99196309146936, 0.67019017358456),
865+ (-0.67684928085260, 0.12631491649378),
866+ (0.09140039465500, -0.20537731453108),
867+ (-0.71658965751996, -0.97788200391224),
868+ (0.81014640078925, 0.53722648362443),
869+ (0.40616991671205, -0.26469008598449),
870+ (-0.67680188682972, 0.94502052337695),
871+ (0.86849774348749, -0.18333598647899),
872+ (-0.99500381284851, -0.02634122068550),
873+ (0.84329189340667, 0.10406957462213),
874+ (-0.09215968531446, 0.69540012101253),
875+ (0.99956173327206, -0.12358542001404),
876+ (-0.79732779473535, -0.91582524736159),
877+ (0.96349973642406, 0.96640458041000),
878+ (-0.79942778496547, 0.64323902822857),
879+ (-0.11566039853896, 0.28587846253726),
880+ (-0.39922954514662, 0.94129601616966),
881+ (0.99089197565987, -0.92062625581587),
882+ (0.28631285179909, -0.91035047143603),
883+ (-0.83302725605608, -0.67330410892084),
884+ (0.95404443402072, 0.49162765398743),
885+ (-0.06449863579434, 0.03250560813135),
886+ (-0.99575054486311, 0.42389784469507),
887+ (-0.65501142790847, 0.82546114655624),
888+ (-0.81254441908887, -0.51627234660629),
889+ (-0.99646369485481, 0.84490533520752),
890+ (0.00287840603348, 0.64768261158166),
891+ (0.70176989408455, -0.20453028573322),
892+ (0.96361882270190, 0.40706967140989),
893+ (-0.68883758192426, 0.91338958840772),
894+ (-0.34875585502238, 0.71472290693300),
895+ (0.91980081243087, 0.66507455644919),
896+ (-0.99009048343881, 0.85868021604848),
897+ (0.68865791458395, 0.55660316809678),
898+ (-0.99484402129368, -0.20052559254934),
899+ (0.94214511408023, -0.99696425367461),
900+ (-0.67414626793544, 0.49548221180078),
901+ (-0.47339353684664, -0.85904328834047),
902+ (0.14323651387360, -0.94145598222488),
903+ (-0.29268293575672, 0.05759224927952),
904+ (0.43793861458754, -0.78904969892724),
905+ (-0.36345126374441, 0.64874435357162),
906+ (-0.08750604656825, 0.97686944362527),
907+ (-0.96495267812511, -0.53960305946511),
908+ (0.55526940659947, 0.78891523734774),
909+ (0.73538215752630, 0.96452072373404),
910+ (-0.30889773919437, -0.80664389776860),
911+ (0.03574995626194, -0.97325616900959),
912+ (0.98720684660488, 0.48409133691962),
913+ (-0.81689296271203, -0.90827703628298),
914+ (0.67866860118215, 0.81284503870856),
915+ (-0.15808569732583, 0.85279555024382),
916+ (0.80723395114371, -0.24717418514605),
917+ (0.47788757329038, -0.46333147839295),
918+ (0.96367554763201, 0.38486749303242),
919+ (-0.99143875716818, -0.24945277239809),
920+ (0.83081876925833, -0.94780851414763),
921+ (-0.58753191905341, 0.01290772389163),
922+ (0.95538108220960, -0.85557052096538),
923+ (-0.96490920476211, -0.64020970923102),
924+ (-0.97327101028521, 0.12378128133110),
925+ (0.91400366022124, 0.57972471346930),
926+ (-0.99925837363824, 0.71084847864067),
927+ (-0.86875903507313, -0.20291699203564),
928+ (-0.26240034795124, -0.68264554369108),
929+ (-0.24664412953388, -0.87642273115183),
930+ (0.02416275806869, 0.27192914288905),
931+ (0.82068619590515, -0.85087787994476),
932+ (0.88547373760759, -0.89636802901469),
933+ (-0.18173078152226, -0.26152145156800),
934+ (0.09355476558534, 0.54845123045604),
935+ (-0.54668414224090, 0.95980774020221),
936+ (0.37050990604091, -0.59910140383171),
937+ (-0.70373594262891, 0.91227665827081),
938+ (-0.34600785879594, -0.99441426144200),
939+ (-0.68774481731008, -0.30238837956299),
940+ (-0.26843291251234, 0.83115668004362),
941+ (0.49072334613242, -0.45359708737775),
942+ (0.38975993093975, 0.95515358099121),
943+ (-0.97757125224150, 0.05305894580606),
944+ (-0.17325552859616, -0.92770672250494),
945+ (0.99948035025744, 0.58285545563426),
946+ (-0.64946246527458, 0.68645507104960),
947+ (-0.12016920576437, -0.57147322153312),
948+ (-0.58947456517751, -0.34847132454388),
949+ (-0.41815140454465, 0.16276422358861),
950+ (0.99885650204884, 0.11136095490444),
951+ (-0.56649614128386, -0.90494866361587),
952+ (0.94138021032330, 0.35281916733018),
953+ (-0.75725076534641, 0.53650549640587),
954+ (0.20541973692630, -0.94435144369918),
955+ (0.99980371023351, 0.79835913565599),
956+ (0.29078277605775, 0.35393777921520),
957+ (-0.62858772103030, 0.38765693387102),
958+ (0.43440904467688, -0.98546330463232),
959+ (-0.98298583762390, 0.21021524625209),
960+ (0.19513029146934, -0.94239832251867),
961+ (-0.95476662400101, 0.98364554179143),
962+ (0.93379635304810, -0.70881994583682),
963+ (-0.85235410573336, -0.08342347966410),
964+ (-0.86425093011245, -0.45795025029466),
965+ (0.38879779059045, 0.97274429344593),
966+ (0.92045124735495, -0.62433652524220),
967+ (0.89162532251878, 0.54950955570563),
968+ (-0.36834336949252, 0.96458298020975),
969+ (0.93891760988045, -0.89968353740388),
970+ (0.99267657565094, -0.03757034316958),
971+ (-0.94063471614176, 0.41332338538963),
972+ (0.99740224117019, -0.16830494996370),
973+ (-0.35899413170555, -0.46633226649613),
974+ (0.05237237274947, -0.25640361602661),
975+ (0.36703583957424, -0.38653265641875),
976+ (0.91653180367913, -0.30587628726597),
977+ (0.69000803499316, 0.90952171386132),
978+ (-0.38658751133527, 0.99501571208985),
979+ (-0.29250814029851, 0.37444994344615),
980+ (-0.60182204677608, 0.86779651036123),
981+ (-0.97418588163217, 0.96468523666475),
982+ (0.88461574003963, 0.57508405276414),
983+ (0.05198933055162, 0.21269661669964),
984+ (-0.53499621979720, 0.97241553731237),
985+ (-0.49429560226497, 0.98183865291903),
986+ (-0.98935142339139, -0.40249159006933),
987+ (-0.98081380091130, -0.72856895534041),
988+ (-0.27338148835532, 0.99950922447209),
989+ (0.06310802338302, -0.54539587529618),
990+ (-0.20461677199539, -0.14209977628489),
991+ (0.66223843141647, 0.72528579940326),
992+ (-0.84764345483665, 0.02372316801261),
993+ (-0.89039863483811, 0.88866581484602),
994+ (0.95903308477986, 0.76744927173873),
995+ (0.73504123909879, -0.03747203173192),
996+ (-0.31744434966056, -0.36834111883652),
997+ (-0.34110827591623, 0.40211222807691),
998+ (0.47803883714199, -0.39423219786288),
999+ (0.98299195879514, 0.01989791390047),
1000+ (-0.30963073129751, -0.18076720599336),
1001+ (0.99992588229018, -0.26281872094289),
1002+ (-0.93149731080767, -0.98313162570490),
1003+ (0.99923472302773, -0.80142993767554),
1004+ (-0.26024169633417, -0.75999759855752),
1005+ (-0.35712514743563, 0.19298963768574),
1006+ (-0.99899084509530, 0.74645156992493),
1007+ (0.86557171579452, 0.55593866696299),
1008+ (0.33408042438752, 0.86185953874709),
1009+ (0.99010736374716, 0.04602397576623),
1010+ (-0.66694269691195, -0.91643611810148),
1011+ (0.64016792079480, 0.15649530836856),
1012+ (0.99570534804836, 0.45844586038111),
1013+ (-0.63431466947340, 0.21079116459234),
1014+ (-0.07706847005931, -0.89581437101329),
1015+ (0.98590090577724, 0.88241721133981),
1016+ (0.80099335254678, -0.36851896710853),
1017+ (0.78368131392666, 0.45506999802597),
1018+ (0.08707806671691, 0.80938994918745),
1019+ (-0.86811883080712, 0.39347308654705),
1020+ (-0.39466529740375, -0.66809432114456),
1021+ (0.97875325649683, -0.72467840967746),
1022+ (-0.95038560288864, 0.89563219587625),
1023+ (0.17005239424212, 0.54683053962658),
1024+ (-0.76910792026848, -0.96226617549298),
1025+ (0.99743281016846, 0.42697157037567),
1026+ (0.95437383549973, 0.97002324109952),
1027+ (0.99578905365569, -0.54106826257356),
1028+ (0.28058259829990, -0.85361420634036),
1029+ (0.85256524470573, -0.64567607735589),
1030+ (-0.50608540105128, -0.65846015480300),
1031+ (-0.97210735183243, -0.23095213067791),
1032+ (0.95424048234441, -0.99240147091219),
1033+ (-0.96926570524023, 0.73775654896574),
1034+ (0.30872163214726, 0.41514960556126),
1035+ (-0.24523839572639, 0.63206633394807),
1036+ (-0.33813265086024, -0.38661779441897),
1037+ (-0.05826828420146, -0.06940774188029),
1038+ (-0.22898461455054, 0.97054853316316),
1039+ (-0.18509915019881, 0.47565762892084),
1040+ (-0.10488238045009, -0.87769947402394),
1041+ (-0.71886586182037, 0.78030982480538),
1042+ (0.99793873738654, 0.90041310491497),
1043+ (0.57563307626120, -0.91034337352097),
1044+ (0.28909646383717, 0.96307783970534),
1045+ (0.42188998312520, 0.48148651230437),
1046+ (0.93335049681047, -0.43537023883588),
1047+ (-0.97087374418267, 0.86636445711364),
1048+ (0.36722871286923, 0.65291654172961),
1049+ (-0.81093025665696, 0.08778370229363),
1050+ (-0.26240603062237, -0.92774095379098),
1051+ (0.83996497984604, 0.55839849139647),
1052+ (-0.99909615720225, -0.96024605713970),
1053+ (0.74649464155061, 0.12144893606462),
1054+ (-0.74774595569805, -0.26898062008959),
1055+ (0.95781667469567, -0.79047927052628),
1056+ (0.95472308713099, -0.08588776019550),
1057+ (0.48708332746299, 0.99999041579432),
1058+ (0.46332038247497, 0.10964126185063),
1059+ (-0.76497004940162, 0.89210929242238),
1060+ (0.57397389364339, 0.35289703373760),
1061+ (0.75374316974495, 0.96705214651335),
1062+ (-0.59174397685714, -0.89405370422752),
1063+ (0.75087906691890, -0.29612672982396),
1064+ (-0.98607857336230, 0.25034911730023),
1065+ (-0.40761056640505, -0.90045573444695),
1066+ (0.66929266740477, 0.98629493401748),
1067+ (-0.97463695257310, -0.00190223301301),
1068+ (0.90145509409859, 0.99781390365446),
1069+ (-0.87259289048043, 0.99233587353666),
1070+ (-0.91529461447692, -0.15698707534206),
1071+ (-0.03305738840705, -0.37205262859764),
1072+ (0.07223051368337, -0.88805001733626),
1073+ (0.99498012188353, 0.97094358113387),
1074+ (-0.74904939500519, 0.99985483641521),
1075+ (0.04585228574211, 0.99812337444082),
1076+ (-0.89054954257993, -0.31791913188064),
1077+ (-0.83782144651251, 0.97637632547466),
1078+ (0.33454804933804, -0.86231516800408),
1079+ (-0.99707579362824, 0.93237990079441),
1080+ (-0.22827527843994, 0.18874759397997),
1081+ (0.67248046289143, -0.03646211390569),
1082+ (-0.05146538187944, -0.92599700120679),
1083+ (0.99947295749905, 0.93625229707912),
1084+ (0.66951124390363, 0.98905825623893),
1085+ (-0.99602956559179, -0.44654715757688),
1086+ (0.82104905483590, 0.99540741724928),
1087+ (0.99186510988782, 0.72023001312947),
1088+ (-0.65284592392918, 0.52186723253637),
1089+ (0.93885443798188, -0.74895312615259),
1090+ (0.96735248738388, 0.90891816978629),
1091+ (-0.22225968841114, 0.57124029781228),
1092+ (-0.44132783753414, -0.92688840659280),
1093+ (-0.85694974219574, 0.88844532719844),
1094+ (0.91783042091762, -0.46356892383970),
1095+ (0.72556974415690, -0.99899555770747),
1096+ (-0.99711581834508, 0.58211560180426),
1097+ (0.77638976371966, 0.94321834873819),
1098+ (0.07717324253925, 0.58638399856595),
1099+ (-0.56049829194163, 0.82522301569036),
1100+ (0.98398893639988, 0.39467440420569),
1101+ (0.47546946844938, 0.68613044836811),
1102+ (0.65675089314631, 0.18331637134880),
1103+ (0.03273375457980, -0.74933109564108),
1104+ (-0.38684144784738, 0.51337349030406),
1105+ (-0.97346267944545, -0.96549364384098),
1106+ (-0.53282156061942, -0.91423265091354),
1107+ (0.99817310731176, 0.61133572482148),
1108+ (-0.50254500772635, -0.88829338134294),
1109+ (0.01995873238855, 0.85223515096765),
1110+ (0.99930381973804, 0.94578896296649),
1111+ (0.82907767600783, -0.06323442598128),
1112+ (-0.58660709669728, 0.96840773806582),
1113+ (-0.17573736667267, -0.48166920859485),
1114+ (0.83434292401346, -0.13023450646997),
1115+ (0.05946491307025, 0.20511047074866),
1116+ (0.81505484574602, -0.94685947861369),
1117+ (-0.44976380954860, 0.40894572671545),
1118+ (-0.89746474625671, 0.99846578838537),
1119+ (0.39677256130792, -0.74854668609359),
1120+ (-0.07588948563079, 0.74096214084170),
1121+ (0.76343198951445, 0.41746629422634),
1122+ (-0.74490104699626, 0.94725911744610),
1123+ (0.64880119792759, 0.41336660830571),
1124+ (0.62319537462542, -0.93098313552599),
1125+ (0.42215817594807, -0.07712787385208),
1126+ (0.02704554141885, -0.05417518053666),
1127+ (0.80001773566818, 0.91542195141039),
1128+ (-0.79351832348816, -0.36208897989136),
1129+ (0.63872359151636, 0.08128252493444),
1130+ (0.52890520960295, 0.60048872455592),
1131+ (0.74238552914587, 0.04491915291044),
1132+ (0.99096131449250, -0.19451182854402),
1133+ (-0.80412329643109, -0.88513818199457),
1134+ (-0.64612616129736, 0.72198674804544),
1135+ (0.11657770663191, -0.83662833815041),
1136+ (-0.95053182488101, -0.96939905138082),
1137+ (-0.62228872928622, 0.82767262846661),
1138+ (0.03004475787316, -0.99738896333384),
1139+ (-0.97987214341034, 0.36526129686425),
1140+ (-0.99986980746200, -0.36021610299715),
1141+ (0.89110648599879, -0.97894250343044),
1142+ (0.10407960510582, 0.77357793811619),
1143+ (0.95964737821728, -0.35435818285502),
1144+ (0.50843233159162, 0.96107691266205),
1145+ (0.17006334670615, -0.76854025314829),
1146+ (0.25872675063360, 0.99893303933816),
1147+ (-0.01115998681937, 0.98496019742444),
1148+ (-0.79598702973261, 0.97138411318894),
1149+ (-0.99264708948101, -0.99542822402536),
1150+ (-0.99829663752818, 0.01877138824311),
1151+ (-0.70801016548184, 0.33680685948117),
1152+ (-0.70467057786826, 0.93272777501857),
1153+ (0.99846021905254, -0.98725746254433),
1154+ (-0.63364968534650, -0.16473594423746),
1155+ (-0.16258217500792, -0.95939125400802),
1156+ (-0.43645594360633, -0.94805030113284),
1157+ (-0.99848471702976, 0.96245166923809),
1158+ (-0.16796458968998, -0.98987511890470),
1159+ (-0.87979225745213, -0.71725725041680),
1160+ (0.44183099021786, -0.93568974498761),
1161+ (0.93310180125532, -0.99913308068246),
1162+ (-0.93941931782002, -0.56409379640356),
1163+ (-0.88590003188677, 0.47624600491382),
1164+ (0.99971463703691, -0.83889954253462),
1165+ (-0.75376385639978, 0.00814643438625),
1166+ (0.93887685615875, -0.11284528204636),
1167+ (0.85126435782309, 0.52349251543547),
1168+ (0.39701421446381, 0.81779634174316),
1169+ (-0.37024464187437, -0.87071656222959),
1170+ (-0.36024828242896, 0.34655735648287),
1171+ (-0.93388812549209, -0.84476541096429),
1172+ (-0.65298804552119, -0.18439575450921),
1173+ (0.11960319006843, 0.99899346780168),
1174+ (0.94292565553160, 0.83163906518293),
1175+ (0.75081145286948, -0.35533223142265),
1176+ (0.56721979748394, -0.24076836414499),
1177+ (0.46857766746029, -0.30140233457198),
1178+ (0.97312313923635, -0.99548191630031),
1179+ (-0.38299976567017, 0.98516909715427),
1180+ (0.41025800019463, 0.02116736935734),
1181+ (0.09638062008048, 0.04411984381457),
1182+ (-0.85283249275397, 0.91475563922421),
1183+ (0.88866808958124, -0.99735267083226),
1184+ (-0.48202429536989, -0.96805608884164),
1185+ (0.27572582416567, 0.58634753335832),
1186+ (-0.65889129659168, 0.58835634138583),
1187+ (0.98838086953732, 0.99994349600236),
1188+ (-0.20651349620689, 0.54593044066355),
1189+ (-0.62126416356920, -0.59893681700392),
1190+ (0.20320105410437, -0.86879180355289),
1191+ (-0.97790548600584, 0.96290806999242),
1192+ (0.11112534735126, 0.21484763313301),
1193+ (-0.41368337314182, 0.28216837680365),
1194+ (0.24133038992960, 0.51294362630238),
1195+ (-0.66393410674885, -0.08249679629081),
1196+ (-0.53697829178752, -0.97649903936228),
1197+ (-0.97224737889348, 0.22081333579837),
1198+ (0.87392477144549, -0.12796173740361),
1199+ (0.19050361015753, 0.01602615387195),
1200+ (-0.46353441212724, -0.95249041539006),
1201+ (-0.07064096339021, -0.94479803205886),
1202+ (-0.92444085484466, -0.10457590187436),
1203+ (-0.83822593578728, -0.01695043208885),
1204+ (0.75214681811150, -0.99955681042665),
1205+ (-0.42102998829339, 0.99720941999394),
1206+ (-0.72094786237696, -0.35008961934255),
1207+ (0.78843311019251, 0.52851398958271),
1208+ (0.97394027897442, -0.26695944086561),
1209+ (0.99206463477946, -0.57010120849429),
1210+ (0.76789609461795, -0.76519356730966),
1211+ (-0.82002421836409, -0.73530179553767),
1212+ (0.81924990025724, 0.99698425250579),
1213+ (-0.26719850873357, 0.68903369776193),
1214+ (-0.43311260380975, 0.85321815947490),
1215+ (0.99194979673836, 0.91876249766422),
1216+ (-0.80692001248487, -0.32627540663214),
1217+ (0.43080003649976, -0.21919095636638),
1218+ (0.67709491937357, -0.95478075822906),
1219+ (0.56151770568316, -0.70693811747778),
1220+ (0.10831862810749, -0.08628837174592),
1221+ (0.91229417540436, -0.65987351408410),
1222+ (-0.48972893932274, 0.56289246362686),
1223+ (-0.89033658689697, -0.71656563987082),
1224+ (0.65269447475094, 0.65916004833932),
1225+ (0.67439478141121, -0.81684380846796),
1226+ (-0.47770832416973, -0.16789556203025),
1227+ (-0.99715979260878, -0.93565784007648),
1228+ (-0.90889593602546, 0.62034397054380),
1229+ (-0.06618622548177, -0.23812217221359),
1230+ (0.99430266919728, 0.18812555317553),
1231+ (0.97686402381843, -0.28664534366620),
1232+ (0.94813650221268, -0.97506640027128),
1233+ (-0.95434497492853, -0.79607978501983),
1234+ (-0.49104783137150, 0.32895214359663),
1235+ (0.99881175120751, 0.88993983831354),
1236+ (0.50449166760303, -0.85995072408434),
1237+ (0.47162891065108, -0.18680204049569),
1238+ (-0.62081581361840, 0.75000676218956),
1239+ (-0.43867015250812, 0.99998069244322),
1240+ (0.98630563232075, -0.53578899600662),
1241+ (-0.61510362277374, -0.89515019899997),
1242+ (-0.03841517601843, -0.69888815681179),
1243+ (-0.30102157304644, -0.07667808922205),
1244+ (0.41881284182683, 0.02188098922282),
1245+ (-0.86135454941237, 0.98947480909359),
1246+ (0.67226861393788, -0.13494389011014),
1247+ (-0.70737398842068, -0.76547349325992),
1248+ (0.94044946687963, 0.09026201157416),
1249+ (-0.82386352534327, 0.08924768823676),
1250+ (-0.32070666698656, 0.50143421908753),
1251+ (0.57593163224487, -0.98966422921509),
1252+ (-0.36326018419965, 0.07440243123228),
1253+ (0.99979044674350, -0.14130287347405),
1254+ (-0.92366023326932, -0.97979298068180),
1255+ (-0.44607178518598, -0.54233252016394),
1256+ (0.44226800932956, 0.71326756742752),
1257+ (0.03671907158312, 0.63606389366675),
1258+ (0.52175424682195, -0.85396826735705),
1259+ (-0.94701139690956, -0.01826348194255),
1260+ (-0.98759606946049, 0.82288714303073),
1261+ (0.87434794743625, 0.89399495655433),
1262+ (-0.93412041758744, 0.41374052024363),
1263+ (0.96063943315511, 0.93116709541280),
1264+ (0.97534253457837, 0.86150930812689),
1265+ (0.99642466504163, 0.70190043427512),
1266+ (-0.94705089665984, -0.29580042814306),
1267+ (0.91599807087376, -0.98147830385781),
1268+];
1269+
752 #[cfg(test)]1270 #[cfg(test)]
753 mod tests {1271 mod tests {
754 use super::*;1272 use super::*;