forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

sbr_chain.rs865 lines, 35.5 KiBHistoryRawDownload
1//! Wires the SBR payload parser, HF generator and envelope adjuster into
2//! one per-element chain the decoder's `raw_data_block` loop drives: parse
3//! a FIL element's `sbr_extension_data`, run the previous SCE/CPE's core
4//! 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.
6
7use crate::sbr_env::{self, AdjustState};
8use crate::sbr_hf::{self, ChirpState, HfHistory};
9use crate::sbr_payload::{SbrChannel, SbrData, SbrParser};
10use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis};
11use ec_core::BitReader;
12use ec_dsp::Complex;
13use std::collections::HashMap;
14use std::sync::atomic::{AtomicUsize, Ordering};
15
16/// Debug: dumps parsed grid/header/e_q/q_q values for the first 20 frames
17/// per channel when `EC_AAC_SBR_DEBUG` is set (diagnostic only, gated).
18fn debug_dump(
19 header: &crate::sbr_payload::SbrHeader,
20 tables: &crate::sbr_bands::BandTables,
21 ch: &SbrChannel,
22 ch_idx: usize,
23) {
24 static COUNT: AtomicUsize = AtomicUsize::new(0);
25 let n = COUNT.fetch_add(1, Ordering::Relaxed);
26 if n >= 20 {
27 return;
28 }
29 eprintln!(
30 "SBRDBG frame {n} ch{ch_idx}: amp_res={} kx={} k2={} n_low={} n_high={} n_q={} t_env={:?} freq_res={:?} t_noise={:?} f_high={:?} patches={:?}",
31 header.amp_res,
32 tables.kx,
33 tables.k2,
34 tables.n_low,
35 tables.n_high,
36 tables.n_q,
37 ch.t_env,
38 ch.freq_res,
39 ch.t_noise,
40 tables.f_high,
41 crate::sbr_hf::build_patches(tables),
42 );
43 for (i, row) in ch.e_q.iter().enumerate() {
44 let (mn, mx) = row
45 .iter()
46 .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v)));
47 eprintln!(" e_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len());
48 }
49 for (i, row) in ch.q_q.iter().enumerate() {
50 let (mn, mx) = row
51 .iter()
52 .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v)));
53 eprintln!(" q_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len());
54 }
55}
56
57/// Envelope-grid "time slots" (§4.6.18.4, `numTimeSlots = 16` for a
58/// 1024-sample core frame) are half as fine as the QMF slots SBR actually
59/// runs at (32 per frame): `RATE = 2` converts one to the other.
60const RATE: i64 = 2;
61
62/// Round-20 residual/side-info correlation: one row per (access unit,
63/// channel) `apply_data` actually ran, giving `sbr_real_library.rs`'s
64/// residual-energy grid a side-info table to correlate against without
65/// re-parsing debug text. `frame` is a single counter shared by every
66/// channel `apply_data` touches in one call, so it lines up 1:1 with the
67/// AU-aligned (2048 output samples/AU for a plain 2x stream) blocks the
68/// residual grid uses.
69#[derive(Clone, Debug)]
70pub struct SbrSideInfoRow {
71 pub frame: usize,
72 pub tag: u8,
73 pub ch: usize,
74 /// `"fresh"` for a frame `apply` reached (a real payload this AU),
75 /// `"hold"` for one `apply_last` reached (no fresh payload, reusing the
76 /// last parsed frame's data per §4.6.18).
77 pub source: &'static str,
78 pub coupling: bool,
79 pub amp_res: u8,
80 /// Band-index domain (same units `f_high`/`f_noise` and the residual
81 /// grid's FFT-bucket index share, per `per_band_correlation`'s
82 /// `band_hz = rate/256` measurement) the crossover and high-res/noise
83 /// band boundaries below live in.
84 pub kx: i64,
85 pub k2: i64,
86 pub f_high: Vec<i64>,
87 pub f_noise: Vec<i64>,
88 pub t_env: Vec<i64>,
89 pub freq_res: Vec<u8>,
90 pub invf_mode: Vec<u8>,
91 pub add_harmonic: Option<Vec<u8>>,
92 pub e_q_means: Vec<f64>,
93 pub q_q_means: Vec<f64>,
94 /// Header fields held for the frame's duration (§4.6.18.3.2), added for
95 /// the FMJ-vs-reeln feature-table hunt: `sbr_header()`'s own coding
96 /// choices, not per-envelope grid data.
97 pub freq_scale: u8,
98 pub alter_scale: u8,
99 pub noise_bands: u8,
100 pub limiter_bands: u8,
101 pub limiter_gains: u8,
102 pub interpol_freq: u8,
103 pub smoothing_mode: u8,
104 pub start_freq: u8,
105 pub stop_freq: u8,
106 pub xover_band: u8,
107 /// `t_noise.len() - 1`, i.e. `numNoiseFloors` this frame.
108 pub num_noise: usize,
109 /// One entry per HF patch, each the patch's band count (from
110 /// `sbr_hf::build_patches`), so patch geometry is visible per frame.
111 pub patch_lengths: Vec<usize>,
112 pub df_env: Vec<u8>,
113 pub df_noise: Vec<u8>,
114}
115
116static SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<SbrSideInfoRow>>> =
117 std::sync::OnceLock::new();
118static SIDEINFO_FRAME: AtomicUsize = AtomicUsize::new(0);
119
120/// Diagnostic-only counter: how many `apply_data` calls process-wide ran
121/// with `source == "hold"` (an AU whose FIL carried no fresh SBR payload,
122/// falling back to `apply_last`'s reuse of the last parsed frame). Read via
123/// [`hold_call_count`]; not gated by an env var since incrementing an atomic
124/// is unconditionally cheap, unlike the `EC_AAC_SBR_*_DEBUG` prints nearby.
125static HOLD_CALLS: AtomicUsize = AtomicUsize::new(0);
126
127/// Total `apply_data` calls process-wide where the SBR payload was reused
128/// from a prior frame (`apply_last`) rather than freshly parsed this AU --
129/// diagnostic instrument for `sbr441_family_sample_drift_probe`.
130pub fn hold_call_count() -> usize {
131 HOLD_CALLS.load(Ordering::Relaxed)
132}
133
134fn sideinfo_enabled() -> bool {
135 std::env::var("EC_AAC_SBR_SIDEINFO_DEBUG").is_ok()
136}
137
138/// Round-34 Task 1 diagnostic: per-AU per-QMF-band mean energy at a named
139/// pipeline stage, gated by `EC_AAC_SBR_QMFDUMP`. `start_band` is the
140/// absolute QMF band index `rows[0]` represents (`0` for the core analysis
141/// matrix, `kx` for the HF matrix), so every printed band index lines up
142/// with `build_patches`' target-band units without the reader having to
143/// offset anything by hand.
144fn qmfdump_enabled() -> bool {
145 std::env::var("EC_AAC_SBR_QMFDUMP").is_ok()
146}
147
148fn qmfdump_energies(stage: &str, start_band: usize, rows: &[Vec<Complex<f64>>]) {
149 let means: Vec<f64> = rows
150 .iter()
151 .map(|series| {
152 if series.is_empty() {
153 0.0
154 } else {
155 series
156 .iter()
157 .map(|c| c.re * c.re + c.im * c.im)
158 .sum::<f64>()
159 / series.len() as f64
160 }
161 })
162 .collect();
163 eprintln!("QMFDUMP stage={stage} start_band={start_band} means={means:?}");
164}
165
166/// Drains nothing -- returns a clone of every row logged so far this
167/// process, in call order. Empty unless `EC_AAC_SBR_SIDEINFO_DEBUG` was set
168/// before decoding.
169pub fn sbr_sideinfo_log() -> Vec<SbrSideInfoRow> {
170 let Some(log) = SIDEINFO_LOG.get() else {
171 return Vec::new();
172 };
173 log.lock().map(|l| l.clone()).unwrap_or_default()
174}
175
176/// Per-channel DSP state an SBR element's reconstruction carries across
177/// frames: the QMF filterbank pair, the HF generator's LPC history and
178/// chirp factors, and the noise-floor generator.
179struct ChannelState {
180 analysis: Analysis,
181 synthesis: Synthesis,
182 hf_hist: HfHistory,
183 chirp: ChirpState,
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>>>,
193}
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).
197const HF_ADJ: usize = 6;
198
199impl ChannelState {
200 fn new(n_q: usize, _seed: u32) -> ChannelState {
201 ChannelState {
202 analysis: Analysis::new(),
203 synthesis: Synthesis::new(),
204 hf_hist: HfHistory::new(ANALYSIS_BANDS),
205 chirp: ChirpState::new(n_q.max(1)),
206 adj: AdjustState::new(),
207 low_tail: vec![[Complex::ZERO; ANALYSIS_BANDS]; HF_ADJ],
208 hf_tail: Vec::new(),
209 y_carry: Vec::new(),
210 }
211 }
212}
213
214/// One SBR element's (SCE or CPE) persistent state.
215struct Element {
216 parser: SbrParser,
217 channels: Vec<ChannelState>,
218 /// The most recently parsed frame's envelope/noise/grid data, held so an
219 /// access unit whose FIL element carries no fresh SBR payload this frame
220 /// (an "unavailable" frame, §4.6.18: legal per spec and the decoder must
221 /// keep reconstructing at the doubled rate using the last known data,
222 /// not silently fall back to core-only output) can still be
223 /// SBR-reconstructed instead of leaving that one access unit's plane at
224 /// half length -- which otherwise permanently shifts every sample after
225 /// it out of alignment with a reference that stayed at full rate.
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>,
229}
230
231/// Every configured SBR element in a stream, keyed by
232/// `element_instance_tag` (assumed stable frame to frame, as every
233/// encoder in practice emits it).
234pub struct SbrChain {
235 rate: u32,
236 // Keyed by (element_instance_tag, is_cpe): SCE/LFE and CPE instance
237 // tags are independent namespaces per §4.4 (an encoder may legally
238 // reuse tag 0 for both an SCE and a CPE in the same access unit), so
239 // a bare `u8` key aliased two distinct elements' QMF/HF/noise state
240 // together whenever that happened -- exactly the case in a 5.1
241 // stream (SCE + two CPEs).
242 elements: HashMap<(u8, bool), Element>,
243}
244
245impl SbrChain {
246 pub fn new(rate: u32) -> SbrChain {
247 SbrChain {
248 rate,
249 elements: HashMap::new(),
250 }
251 }
252
253 /// Parses one FIL element's `sbr_extension_data` (the reader
254 /// positioned right past `bs_extension_type`) for element `tag`.
255 pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option<SbrData> {
256 let elem = self.elements.entry((tag, is_cpe)).or_insert_with(|| Element {
257 parser: SbrParser::new(self.rate),
258 channels: Vec::new(),
259 last_data: None,
260 last_header: None,
261 });
262 let data = elem.parser.parse(r, is_cpe).ok()?;
263 let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1);
264 while elem.channels.len() < data.channels.len() {
265 let seed = 0x1234_5678u32.wrapping_add(elem.channels.len() as u32 * 0x9e37_79b9);
266 elem.channels.push(ChannelState::new(n_q, seed));
267 }
268 Some(data)
269 }
270
271 /// Runs the chain over `planes` (element `tag`'s already-decoded core
272 /// PCM, one plane per channel), replacing each in place with its
273 /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a
274 /// silent no-op: `planes` is left at its core content.
275 pub fn apply(&mut self, tag: u8, is_cpe: bool, data: &SbrData, planes: &mut [Vec<f32>]) {
276 if let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) {
277 elem.last_data = Some(data.clone());
278 }
279 self.apply_data(tag, is_cpe, data, planes, "fresh");
280 }
281
282 /// Re-runs the chain for `tag` using the last successfully parsed
283 /// frame's SBR data, for an access unit whose own FIL element carried no
284 /// fresh payload this frame. A no-op (planes left at core content, same
285 /// as [`apply`]'s existing malformed/missing-state fallback) if no prior
286 /// frame ever parsed successfully for this element.
287 pub fn apply_last(&mut self, tag: u8, is_cpe: bool, planes: &mut [Vec<f32>]) {
288 let Some(data) = self
289 .elements
290 .get(&(tag, is_cpe))
291 .and_then(|e| e.last_data.clone())
292 else {
293 return;
294 };
295 self.apply_data(tag, is_cpe, &data, planes, "hold");
296 }
297
298 fn apply_data(
299 &mut self,
300 tag: u8,
301 is_cpe: bool,
302 data: &SbrData,
303 planes: &mut [Vec<f32>],
304 source: &'static str,
305 ) {
306 if source == "hold" {
307 HOLD_CALLS.fetch_add(1, Ordering::Relaxed);
308 }
309 let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else {
310 return;
311 };
312 let Some(tables) = elem.parser.tables().cloned() else {
313 return;
314 };
315 let reset = elem.last_header.as_ref() != elem.parser.header();
316 elem.last_header = elem.parser.header().cloned();
317 let Some(header) = elem.parser.header().cloned() else {
318 return;
319 };
320 let coupling = data.coupling;
321 let sideinfo_on = sideinfo_enabled();
322 let au_frame = if sideinfo_on {
323 SIDEINFO_FRAME.fetch_add(1, Ordering::Relaxed)
324 } else {
325 0
326 };
327 for (ch, plane) in planes.iter_mut().enumerate() {
328 if ch >= data.channels.len() || ch >= elem.channels.len() {
329 continue;
330 }
331 let num_slots = plane.len() / ANALYSIS_BANDS;
332 if num_slots == 0 {
333 continue;
334 }
335 if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() {
336 static N: AtomicUsize = AtomicUsize::new(0);
337 let n = N.fetch_add(1, Ordering::Relaxed);
338 if n < 40 {
339 let rms = (plane.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>()
340 / plane.len().max(1) as f64)
341 .sqrt();
342 eprintln!(
343 "PREQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}",
344 plane.len(),
345 &plane[..8.min(plane.len())]
346 );
347 }
348 }
349 let state = &mut elem.channels[ch];
350 let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS];
351 let mut raw = Vec::with_capacity(num_slots);
352 for slot in 0..num_slots {
353 let mut chunk = [0f32; ANALYSIS_BANDS];
354 chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]);
355 // `plane` is already at the decoder's final output scale
356 // (`decode::OUTPUT_SCALE`, applied by the core filterbank),
357 // but the transmitted envelope/noise data is calibrated
358 // against the core's un-normalized internal PCM domain --
359 // undo that scale before analysis so the SBR gain match
360 // (raw QMF energy vs. the transmitted target) compares
361 // like against like, and reapply it once below after
362 // synthesis. Without this the gain step's `target/current`
363 // ratio is inflated by `1/OUTPUT_SCALE^2` in energy,
364 // exactly the multi-order-of-magnitude blowup this chain
365 // used to produce on every real HE-AAC file.
366 for s in &mut chunk {
367 *s /= crate::decode::OUTPUT_SCALE;
368 }
369 let sub = state.analysis.process_slot(&chunk);
370 for b in 0..ANALYSIS_BANDS {
371 low_cur[b][slot] = sub[b];
372 }
373 raw.push(sub);
374 }
375
376 let sbr_ch = &data.channels[ch];
377 if std::env::var("EC_AAC_SBR_DEBUG").is_ok() {
378 eprintln!("SBRDBG coupling={}", data.coupling);
379 debug_dump(&header, &tables, sbr_ch, ch);
380 }
381 if sideinfo_on {
382 let mean = |rows: &[Vec<i32>]| -> Vec<f64> {
383 rows.iter()
384 .map(|r| {
385 if r.is_empty() {
386 0.0
387 } else {
388 r.iter().map(|&v| f64::from(v)).sum::<f64>() / r.len() as f64
389 }
390 })
391 .collect()
392 };
393 let row = SbrSideInfoRow {
394 frame: au_frame,
395 tag,
396 ch,
397 source,
398 coupling,
399 amp_res: header.amp_res,
400 kx: tables.kx,
401 k2: tables.k2,
402 f_high: tables.f_high.clone(),
403 f_noise: tables.f_noise.clone(),
404 t_env: sbr_ch.t_env.clone(),
405 freq_res: sbr_ch.freq_res.clone(),
406 invf_mode: sbr_ch.invf_mode.clone(),
407 add_harmonic: sbr_ch.add_harmonic.clone(),
408 e_q_means: mean(&sbr_ch.e_q),
409 q_q_means: mean(&sbr_ch.q_q),
410 freq_scale: header.freq_scale,
411 alter_scale: header.alter_scale,
412 noise_bands: header.noise_bands,
413 limiter_bands: header.limiter_bands,
414 limiter_gains: header.limiter_gains,
415 interpol_freq: header.interpol_freq,
416 smoothing_mode: header.smoothing_mode,
417 start_freq: header.start_freq,
418 stop_freq: header.stop_freq,
419 xover_band: header.xover_band,
420 num_noise: sbr_ch.t_noise.len().saturating_sub(1),
421 patch_lengths: sbr_hf::build_patches(&tables).iter().map(|p| p.width).collect(),
422 df_env: sbr_ch.df_env.clone(),
423 df_noise: sbr_ch.df_noise.clone(),
424 };
425 let log = SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new()));
426 if let Ok(mut l) = log.lock() {
427 l.push(row);
428 }
429 }
430 let qmfdump_on = qmfdump_enabled();
431 if qmfdump_on {
432 qmfdump_energies("analysis", 0, &low_cur);
433 }
434 let hf = sbr_hf::generate(
435 &low_cur,
436 &tables,
437 &sbr_ch.invf_mode,
438 &mut state.chirp,
439 &mut state.hf_hist,
440 );
441 if qmfdump_on {
442 qmfdump_energies("post_patch", tables.kx as usize, &hf);
443 }
444 let (env_energy, noise_energy) =
445 sbr_env::dequantize_frame(&data.channels, ch, coupling);
446 // sbr_env::adjust works in QMF-slot units; the parsed borders
447 // are in the coarser envelope-time-slot units (see RATE above).
448 let scaled = SbrChannel {
449 t_env: sbr_ch.t_env.iter().map(|&t| t * RATE).collect(),
450 t_noise: sbr_ch.t_noise.iter().map(|&t| t * RATE).collect(),
451 ..sbr_ch.clone()
452 };
453 let limiter_table = sbr_hf::limiter_band_table(
454 &tables,
455 &sbr_hf::build_patches(&tables),
456 header.limiter_bands,
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, band) in hf.iter().enumerate().take(m_max) {
474 state.hf_tail[m] = band[num_slots.saturating_sub(HF_ADJ)..].to_vec();
475 }
476 sbr_env::adjust(
477 &mut xh,
478 &tables,
479 &header,
480 &scaled,
481 &env_energy,
482 &noise_energy,
483 &limiter_table,
484 &mut state.adj,
485 reset,
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, band) in hf.iter_mut().enumerate().take(m_max) {
494 for (i, slot) in band.iter_mut().enumerate().take(i_temp) {
495 *slot = state.y_carry[m][i];
496 }
497 for (i, slot) in band.iter_mut().enumerate().take(num_slots).skip(i_temp) {
498 *slot = 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 };
511 if qmfdump_on {
512 qmfdump_energies("post_adjust", tables.kx as usize, &hf);
513 }
514
515 let kx = (tables.kx as usize).min(ANALYSIS_BANDS);
516 let k2 = (tables.k2 as usize).min(SYNTHESIS_BANDS);
517 let mut out = Vec::with_capacity(num_slots * SYNTHESIS_BANDS);
518 for slot in 0..num_slots {
519 let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
520 v[0..kx].copy_from_slice(&raw[slot][0..kx]);
521 if std::env::var("EC_AAC_SBR_HF_BYPASS").is_err() {
522 for b in kx..k2 {
523 if b - kx < hf.len() {
524 v[b] = hf[b - kx][slot];
525 }
526 }
527 }
528 let mut pcm = state.synthesis.process_slot(&v);
529 for s in &mut pcm {
530 // The spec 32-analysis/64-synthesis pair (4.6.18.4.1 +
531 // 4.6.18.8.2, literal equations) reads back at half the
532 // core's amplitude; the 2x is the upsampler's gain.
533 *s *= 2.0 * crate::decode::OUTPUT_SCALE;
534 }
535 out.extend_from_slice(&pcm);
536 }
537 if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() {
538 static N: AtomicUsize = AtomicUsize::new(0);
539 let n = N.fetch_add(1, Ordering::Relaxed);
540 if n < 40 {
541 let rms = (out.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>()
542 / out.len().max(1) as f64)
543 .sqrt();
544 eprintln!(
545 "POSTQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}",
546 out.len(),
547 &out[..8.min(out.len())]
548 );
549 }
550 }
551 *plane = out;
552 }
553 }
554}
555
556#[cfg(test)]
557mod tests {
558 use super::*;
559 use crate::sbr_bands::freq_tables;
560 use crate::sbr_payload::{SbrHeader, SbrParser};
561
562 fn tables() -> crate::sbr_bands::BandTables {
563 freq_tables(44100, 5, 3, 2, 1, 2, 2).unwrap()
564 }
565
566 fn header() -> SbrHeader {
567 SbrHeader {
568 amp_res: 1,
569 start_freq: 5,
570 stop_freq: 3,
571 xover_band: 2,
572 freq_scale: 2,
573 alter_scale: 1,
574 noise_bands: 2,
575 limiter_bands: 2,
576 limiter_gains: 3,
577 interpol_freq: 1,
578 smoothing_mode: 1,
579 }
580 }
581
582 fn one_channel(n_q: usize, n_low: usize) -> SbrChannel {
583 SbrChannel {
584 t_env: vec![0, 16],
585 freq_res: vec![0],
586 t_noise: vec![0, 16],
587 e_q: vec![vec![10i32; n_low]],
588 q_q: vec![vec![2i32; n_q]],
589 invf_mode: vec![0; n_q],
590 add_harmonic: None,
591 df_env: vec![],
592 df_noise: vec![],
593 l_a: -1,
594 amp_res: 1,
595 }
596 }
597
598 /// Two adjacent 1024-sample core AUs run through the same `SbrChain`
599 /// element (as `raw_data_block`'s per-AU calls do) must each double to
600 /// exactly `2 * ANALYSIS_BANDS * 32` samples with no gap or overlap at
601 /// the junction: the coverage hole that let a whole access unit's
602 /// doubling go missing (see `apply_last`) never showed up in the
603 /// synthetic continuous-stream QMF round trip, since that test never
604 /// crosses an AU boundary at all.
605 #[test]
606 fn two_adjacent_access_units_double_rate_with_no_junction_discontinuity() {
607 let t = tables();
608 let n_low = t.n_low;
609 let n_q = t.n_q;
610 let mut chain = SbrChain::new(44100);
611 let tag = 0u8;
612 chain.elements.insert(
613 (tag, true),
614 Element {
615 parser: SbrParser::new(44100),
616 channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)],
617 last_data: None,
618 last_header: None,
619 },
620 );
621 chain
622 .elements
623 .get_mut(&(tag, true))
624 .unwrap()
625 .parser
626 .set_for_test(header(), t.clone());
627
628 let data = SbrData {
629 coupling: false,
630 channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)],
631 };
632
633 // A steady tone, not silence: silence round-trips trivially (every
634 // sample is already continuous at 0), which would hide exactly the
635 // discontinuity this test exists to catch.
636 let core_au = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.1).sin() * 0.2).collect() };
637 let mut planes = vec![core_au(), core_au()];
638 chain.apply(tag, true, &data, &mut planes);
639
640 let expected_len = 32 * SYNTHESIS_BANDS;
641 for (ch, plane) in planes.iter().enumerate() {
642 assert_eq!(
643 plane.len(),
644 expected_len,
645 "ch{ch} AU1 didn't double to {expected_len} samples"
646 );
647 }
648
649 // Second AU through the SAME chain/state, as consecutive AUs in one
650 // stream are: this is what exercises the QMF history/HF-chirp/noise
651 // generator continuity across the junction, not just each AU in
652 // isolation.
653 let mut planes2 = vec![core_au(), core_au()];
654 chain.apply(tag, true, &data, &mut planes2);
655 for (ch, plane) in planes2.iter().enumerate() {
656 assert_eq!(
657 plane.len(),
658 expected_len,
659 "ch{ch} AU2 didn't double to {expected_len} samples"
660 );
661 }
662
663 // Cumulative length across both AUs is exactly 2x2048, and the
664 // junction (last sample of AU1 next to the first of AU2) is not a
665 // discontinuity spike: a dropped/duplicated-AU bug (the one fixed by
666 // `apply_last`) either changes this total length or opens a silent
667 // gap, and a QMF history corruption at the boundary spikes the
668 // derivative right at the join far above the steady-state
669 // sample-to-sample delta the continuous tone otherwise has.
670 for ch in 0..2 {
671 let mut joined = planes[ch].clone();
672 joined.extend_from_slice(&planes2[ch]);
673 assert_eq!(joined.len(), 2 * expected_len);
674
675 let steady_delta = |s: &[f32]| -> f32 {
676 s.windows(2)
677 .skip(expected_len / 2)
678 .take(expected_len / 4)
679 .map(|w| (w[1] - w[0]).abs())
680 .fold(0.0f32, f32::max)
681 };
682 let typical = steady_delta(&joined);
683 let junction_delta = (joined[expected_len] - joined[expected_len - 1]).abs();
684 assert!(
685 junction_delta <= typical * 4.0 + 1e-6,
686 "ch{ch} junction delta {junction_delta} far exceeds steady-state delta {typical} -- AU-boundary discontinuity"
687 );
688 }
689 }
690
691 /// §4.4: `element_instance_tag` is a namespace per element *type* --
692 /// an encoder may legally give an SCE and a CPE in the same access
693 /// unit the same tag value (this is exactly what a 5.1 stream with
694 /// SCE+CPE+CPE+LFE does). `SbrChain` used to key its per-element state
695 /// by the bare tag, so the CPE's `parse`/`apply` would silently reuse
696 /// (and corrupt) the SCE's parser/channel state. Keying by `(tag,
697 /// is_cpe)` must keep them fully independent: driving distinct tones
698 /// through an SCE and a same-tagged CPE must not bleed into each
699 /// other's output.
700 #[test]
701 fn an_sce_and_a_same_tagged_cpe_do_not_share_state() {
702 let t = tables();
703 let n_low = t.n_low;
704 let n_q = t.n_q;
705 let mut chain = SbrChain::new(44100);
706 let tag = 0u8;
707
708 for is_cpe in [false, true] {
709 let n_ch = if is_cpe { 2 } else { 1 };
710 chain.elements.insert(
711 (tag, is_cpe),
712 Element {
713 parser: SbrParser::new(44100),
714 channels: (0..n_ch)
715 .map(|i| ChannelState::new(n_q, 10 + i as u32))
716 .collect(),
717 last_data: None,
718 last_header: None,
719 },
720 );
721 chain
722 .elements
723 .get_mut(&(tag, is_cpe))
724 .unwrap()
725 .parser
726 .set_for_test(header(), t.clone());
727 }
728
729 let sce_data = SbrData {
730 coupling: false,
731 channels: vec![one_channel(n_q, n_low)],
732 };
733 let cpe_data = SbrData {
734 coupling: false,
735 channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)],
736 };
737
738 let sce_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.05).sin() * 0.2).collect() };
739 let cpe_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.37).sin() * 0.2).collect() };
740
741 let mut sce_planes = vec![sce_tone()];
742 chain.apply(tag, false, &sce_data, &mut sce_planes);
743 let mut cpe_planes = vec![cpe_tone(), cpe_tone()];
744 chain.apply(tag, true, &cpe_data, &mut cpe_planes);
745
746 // If state aliased, the CPE call above would have run through (and
747 // mutated) the SCE's Analysis/Synthesis/chirp/noise state instead
748 // of its own -- re-running the SCE with the same input must give
749 // the SAME output as the first call, proving its state was never
750 // touched by the CPE call in between.
751 let mut sce_planes2 = vec![sce_tone()];
752 chain.apply(tag, false, &sce_data, &mut sce_planes2);
753
754 // A fresh, never-driven SCE-only chain gives the reference: one AU
755 // through tag/is_cpe=(0,false), nothing else touching its state.
756 let mut reference = SbrChain::new(44100);
757 reference.elements.insert(
758 (tag, false),
759 Element {
760 parser: SbrParser::new(44100),
761 channels: vec![ChannelState::new(n_q, 10)],
762 last_data: None,
763 last_header: None,
764 },
765 );
766 reference
767 .elements
768 .get_mut(&(tag, false))
769 .unwrap()
770 .parser
771 .set_for_test(header(), t.clone());
772 let mut sce_ref1 = vec![sce_tone()];
773 reference.apply(tag, false, &sce_data, &mut sce_ref1);
774 let mut sce_ref2 = vec![sce_tone()];
775 reference.apply(tag, false, &sce_data, &mut sce_ref2);
776
777 assert_eq!(
778 sce_planes[0], sce_ref1[0],
779 "SCE tag 0's first call already diverges from an isolated reference"
780 );
781 assert_eq!(
782 sce_planes2[0], sce_ref2[0],
783 "SCE tag 0's state was mutated by the same-tagged CPE's apply() call in between"
784 );
785 }
786
787 /// Round-13 stitching verdict (queue item 1): the QMF filterbank pair
788 /// underneath the low band (`0..kx`, `apply_data` copies
789 /// `raw[slot][0..kx]` straight from `Analysis` into `Synthesis`, no
790 /// envelope/HF touch) must give BIT-IDENTICAL output whether its
791 /// `process_slot` calls arrive chunked AU-by-AU (32 slots per call,
792 /// matching a real 1024-sample core frame) or as one continuous run --
793 /// `Analysis`/`Synthesis`'s own history/overlap-add state carries
794 /// between calls regardless of how the caller groups them, so the
795 /// SAME sample sequence fed either way must produce the SAME output.
796 /// (An earlier version of this test drove it through `SbrChain::apply`
797 /// with one AU-sized `SbrData` grid reused for a 10-AU-long "continuous"
798 /// call; that showed a large divergence, but the divergence was a test
799 /// bug, not a real one: `sbr_env::adjust`'s envelope gain is grid-scoped
800 /// to `ch.t_env`'s own 32-slot range, so a 320-slot call only gain-
801 /// adjusted its first AU's worth and left the other nine raw --
802 /// `apply_data` is inherently one-AU-per-call by design, so the
803 /// meaningful comparison is at the QMF layer these AU-sized calls sit
804 /// on top of, not by force-feeding it a multi-AU span it was never
805 /// meant to take in one call.)
806 #[test]
807 fn ten_aus_worth_of_qmf_slots_chained_per_au_are_bit_identical_to_one_continuous_pass() {
808 let mut rng = 0x02f6_e2b1_u64;
809 let mut next = || {
810 rng ^= rng << 13;
811 rng ^= rng >> 7;
812 rng ^= rng << 17;
813 (rng >> 11) as f64 / (1u64 << 53) as f64 - 0.5
814 };
815 let all_samples: Vec<f32> = (0..10 * 1024).map(|_| next() as f32 * 0.3).collect();
816
817 // (a) Per-AU: a fresh 32-slot chunk fed to the SAME persistent
818 // Analysis/Synthesis pair per call, as `apply_data` drives it once
819 // per access unit.
820 let mut analysis_a = Analysis::new();
821 let mut synthesis_a = Synthesis::new();
822 let mut per_au_out: Vec<f32> = Vec::new();
823 for au in all_samples.chunks(1024) {
824 for slot in au.chunks_exact(ANALYSIS_BANDS) {
825 let mut chunk = [0f32; ANALYSIS_BANDS];
826 chunk.copy_from_slice(slot);
827 let sub = analysis_a.process_slot(&chunk);
828 let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
829 v[0..ANALYSIS_BANDS].copy_from_slice(&sub);
830 per_au_out.extend(synthesis_a.process_slot(&v));
831 }
832 }
833
834 // (b) One continuous pass over the same samples, same bank pair,
835 // just not grouped into per-AU calls.
836 let mut analysis_b = Analysis::new();
837 let mut synthesis_b = Synthesis::new();
838 let mut continuous_out: Vec<f32> = Vec::new();
839 for slot in all_samples.chunks_exact(ANALYSIS_BANDS) {
840 let mut chunk = [0f32; ANALYSIS_BANDS];
841 chunk.copy_from_slice(slot);
842 let sub = analysis_b.process_slot(&chunk);
843 let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
844 v[0..ANALYSIS_BANDS].copy_from_slice(&sub);
845 continuous_out.extend(synthesis_b.process_slot(&v));
846 }
847
848 assert_eq!(per_au_out.len(), continuous_out.len());
849 let mut max_diff = 0.0f32;
850 let mut diverging = 0usize;
851 for (a, b) in per_au_out.iter().zip(&continuous_out) {
852 let d = (a - b).abs();
853 if d != 0.0 {
854 diverging += 1;
855 }
856 max_diff = max_diff.max(d);
857 }
858 let total = per_au_out.len();
859 println!("stitching check: {diverging}/{total} samples differ, max abs diff {max_diff:e}");
860 assert!(
861 max_diff < 1e-5,
862 "per-AU chaining and one continuous pass diverge by {max_diff:e} -- a real QMF stitching bug"
863 );
864 }
865}