forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

sbr_chain.rs1098 lines, 44.4 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::ps_data::PsCommon;
10use crate::ps_dsp::{IN_SLOTS, PsEngine, QMF_BANDS};
11use crate::sbr_payload::{SbrChannel, SbrData, SbrParser};
12use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis};
13use ec_core::BitReader;
14use ec_dsp::Complex;
15use std::collections::HashMap;
16use std::sync::atomic::{AtomicUsize, Ordering};
17
18/// Debug: dumps parsed grid/header/e_q/q_q values for the first 20 frames
19/// per channel when `EC_AAC_SBR_DEBUG` is set (diagnostic only, gated).
20fn debug_dump(
21 header: &crate::sbr_payload::SbrHeader,
22 tables: &crate::sbr_bands::BandTables,
23 ch: &SbrChannel,
24 ch_idx: usize,
25) {
26 static COUNT: AtomicUsize = AtomicUsize::new(0);
27 let n = COUNT.fetch_add(1, Ordering::Relaxed);
28 if n >= 20 {
29 return;
30 }
31 eprintln!(
32 "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={:?}",
33 header.amp_res,
34 tables.kx,
35 tables.k2,
36 tables.n_low,
37 tables.n_high,
38 tables.n_q,
39 ch.t_env,
40 ch.freq_res,
41 ch.t_noise,
42 tables.f_high,
43 crate::sbr_hf::build_patches(tables),
44 );
45 for (i, row) in ch.e_q.iter().enumerate() {
46 let (mn, mx) = row
47 .iter()
48 .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v)));
49 eprintln!(" e_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len());
50 }
51 for (i, row) in ch.q_q.iter().enumerate() {
52 let (mn, mx) = row
53 .iter()
54 .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v)));
55 eprintln!(" q_q[{i}] len={} min={mn} max={mx} row={row:?}", row.len());
56 }
57}
58
59/// Envelope-grid "time slots" (§4.6.18.4, `numTimeSlots = 16` for a
60/// 1024-sample core frame) are half as fine as the QMF slots SBR actually
61/// runs at (32 per frame): `RATE = 2` converts one to the other.
62const RATE: i64 = 2;
63
64/// Round-20 residual/side-info correlation: one row per (access unit,
65/// channel) `apply_data` actually ran, giving `sbr_real_library.rs`'s
66/// residual-energy grid a side-info table to correlate against without
67/// re-parsing debug text. `frame` is a single counter shared by every
68/// channel `apply_data` touches in one call, so it lines up 1:1 with the
69/// AU-aligned (2048 output samples/AU for a plain 2x stream) blocks the
70/// residual grid uses.
71#[derive(Clone, Debug)]
72pub struct SbrSideInfoRow {
73 pub frame: usize,
74 pub tag: u8,
75 pub ch: usize,
76 /// `"fresh"` for a frame `apply` reached (a real payload this AU),
77 /// `"hold"` for one `apply_last` reached (no fresh payload, reusing the
78 /// last parsed frame's data per §4.6.18).
79 pub source: &'static str,
80 pub coupling: bool,
81 pub amp_res: u8,
82 /// Band-index domain (same units `f_high`/`f_noise` and the residual
83 /// grid's FFT-bucket index share, per `per_band_correlation`'s
84 /// `band_hz = rate/256` measurement) the crossover and high-res/noise
85 /// band boundaries below live in.
86 pub kx: i64,
87 pub k2: i64,
88 pub f_high: Vec<i64>,
89 pub f_noise: Vec<i64>,
90 pub t_env: Vec<i64>,
91 pub freq_res: Vec<u8>,
92 pub invf_mode: Vec<u8>,
93 pub add_harmonic: Option<Vec<u8>>,
94 pub e_q_means: Vec<f64>,
95 pub q_q_means: Vec<f64>,
96 /// Header fields held for the frame's duration (§4.6.18.3.2), added for
97 /// the FMJ-vs-reeln feature-table hunt: `sbr_header()`'s own coding
98 /// choices, not per-envelope grid data.
99 pub freq_scale: u8,
100 pub alter_scale: u8,
101 pub noise_bands: u8,
102 pub limiter_bands: u8,
103 pub limiter_gains: u8,
104 pub interpol_freq: u8,
105 pub smoothing_mode: u8,
106 pub start_freq: u8,
107 pub stop_freq: u8,
108 pub xover_band: u8,
109 /// `t_noise.len() - 1`, i.e. `numNoiseFloors` this frame.
110 pub num_noise: usize,
111 /// One entry per HF patch, each the patch's band count (from
112 /// `sbr_hf::build_patches`), so patch geometry is visible per frame.
113 pub patch_lengths: Vec<usize>,
114 pub df_env: Vec<u8>,
115 pub df_noise: Vec<u8>,
116}
117
118static SIDEINFO_LOG: std::sync::OnceLock<std::sync::Mutex<Vec<SbrSideInfoRow>>> =
119 std::sync::OnceLock::new();
120static SIDEINFO_FRAME: AtomicUsize = AtomicUsize::new(0);
121
122/// Diagnostic-only counter: how many `apply_data` calls process-wide ran
123/// with `source == "hold"` (an AU whose FIL carried no fresh SBR payload,
124/// falling back to `apply_last`'s reuse of the last parsed frame). Read via
125/// [`hold_call_count`]; not gated by an env var since incrementing an atomic
126/// is unconditionally cheap, unlike the `EC_AAC_SBR_*_DEBUG` prints nearby.
127static HOLD_CALLS: AtomicUsize = AtomicUsize::new(0);
128
129/// Total `apply_data` calls process-wide where the SBR payload was reused
130/// from a prior frame (`apply_last`) rather than freshly parsed this AU --
131/// diagnostic instrument for `sbr441_family_sample_drift_probe`.
132pub fn hold_call_count() -> usize {
133 HOLD_CALLS.load(Ordering::Relaxed)
134}
135
136fn sideinfo_enabled() -> bool {
137 crate::knobs::sbr_sideinfo_debug()
138}
139
140/// Round-34 Task 1 diagnostic: per-AU per-QMF-band mean energy at a named
141/// pipeline stage, gated by `EC_AAC_SBR_QMFDUMP`. `start_band` is the
142/// absolute QMF band index `rows[0]` represents (`0` for the core analysis
143/// matrix, `kx` for the HF matrix), so every printed band index lines up
144/// with `build_patches`' target-band units without the reader having to
145/// offset anything by hand.
146fn qmfdump_enabled() -> bool {
147 std::env::var("EC_AAC_SBR_QMFDUMP").is_ok()
148}
149
150fn qmfdump_energies(stage: &str, start_band: usize, rows: &[Vec<Complex<f64>>]) {
151 let means: Vec<f64> = rows
152 .iter()
153 .map(|series| {
154 if series.is_empty() {
155 0.0
156 } else {
157 series
158 .iter()
159 .map(|c| c.re * c.re + c.im * c.im)
160 .sum::<f64>()
161 / series.len() as f64
162 }
163 })
164 .collect();
165 eprintln!("QMFDUMP stage={stage} start_band={start_band} means={means:?}");
166}
167
168/// Drains nothing -- returns a clone of every row logged so far this
169/// process, in call order. Empty unless `EC_AAC_SBR_SIDEINFO_DEBUG` was set
170/// before decoding.
171pub fn sbr_sideinfo_log() -> Vec<SbrSideInfoRow> {
172 let Some(log) = SIDEINFO_LOG.get() else {
173 return Vec::new();
174 };
175 log.lock().map(|l| l.clone()).unwrap_or_default()
176}
177
178/// Per-channel DSP state an SBR element's reconstruction carries across
179/// frames: the QMF filterbank pair, the HF generator's LPC history and
180/// chirp factors, and the noise-floor generator.
181struct ChannelState {
182 analysis: Analysis,
183 synthesis: Synthesis,
184 hf_hist: HfHistory,
185 chirp: ChirpState,
186 adj: AdjustState,
187 /// §4.6.18.7.6 `tHFAdj`/overlap buffers: the SBR output lags the raw
188 /// analysis by `HF_ADJ` slots, so the previous frame's last `HF_ADJ`
189 /// raw low-band and raw HF slots are kept, plus the already-adjusted HF
190 /// slots past the frame end that a variable-border envelope produced
191 /// (`Y` of slots `32..2*t_E(L_E)`), which lead the next frame's output.
192 low_tail: Vec<[Complex<f64>; ANALYSIS_BANDS]>,
193 hf_tail: Vec<Vec<Complex<f64>>>,
194 y_carry: Vec<Vec<Complex<f64>>>,
195}
196
197/// Slots by which the HF adjuster's envelope grid lags the raw QMF frame
198/// (`tHFAdj` + the 6-slot overlap, §4.6.18.7.6 / Figure 4.32).
199const HF_ADJ: usize = 6;
200
201/// Samples a bypass plane lags its raw analysis by: `HF_ADJ` slots at the doubled rate.
202const BYPASS_DELAY: usize = HF_ADJ * SYNTHESIS_BANDS;
203
204impl ChannelState {
205 fn new(n_q: usize, _seed: u32) -> ChannelState {
206 ChannelState {
207 analysis: Analysis::new(),
208 synthesis: Synthesis::new(),
209 hf_hist: HfHistory::new(ANALYSIS_BANDS),
210 chirp: ChirpState::new(n_q.max(1)),
211 adj: AdjustState::new(),
212 low_tail: vec![[Complex::ZERO; ANALYSIS_BANDS]; HF_ADJ],
213 hf_tail: Vec::new(),
214 y_carry: Vec::new(),
215 }
216 }
217}
218
219/// One SBR element's (SCE or CPE) persistent state.
220struct Element {
221 parser: SbrParser,
222 channels: Vec<ChannelState>,
223 /// The most recently parsed frame's envelope/noise/grid data, held so an
224 /// access unit whose FIL element carries no fresh SBR payload this frame
225 /// (an "unavailable" frame, §4.6.18: legal per spec and the decoder must
226 /// keep reconstructing at the doubled rate using the last known data,
227 /// not silently fall back to core-only output) can still be
228 /// SBR-reconstructed instead of leaving that one access unit's plane at
229 /// half length -- which otherwise permanently shifts every sample after
230 /// it out of alignment with a reference that stayed at full rate.
231 last_data: Option<SbrData>,
232 /// Header of the previous applied frame: a change is the spec's reset.
233 last_header: Option<crate::sbr_payload::SbrHeader>,
234 /// Parametric Stereo reconstruction state (hybrid filter, decorrelator,
235 /// mixing history), used when the element carries PS.
236 ps_engine: PsEngine,
237}
238
239/// QMF slots per SBR frame: the PS path runs only for the 32-slot frames
240/// that AAC-LC's 1024-sample frames produce.
241const PS_SLOTS: usize = 32;
242
243/// Every configured SBR element in a stream, keyed by
244/// `element_instance_tag` (assumed stable frame to frame, as every
245/// encoder in practice emits it).
246pub struct SbrChain {
247 rate: u32,
248 /// PS is signalled by the config (explicit HE-AACv2).
249 ps_config: bool,
250 // Keyed by (element_instance_tag, is_cpe): SCE/LFE and CPE instance
251 // tags are independent namespaces per §4.4 (an encoder may legally
252 // reuse tag 0 for both an SCE and a CPE in the same access unit), so
253 // a bare `u8` key aliased two distinct elements' QMF/HF/noise state
254 // together whenever that happened -- exactly the case in a 5.1
255 // stream (SCE + two CPEs).
256 elements: HashMap<(u8, bool), Element>,
257 /// Doubling state of each LFE element, keyed by its instance tag. The LFE
258 /// carries no SBR payload, but its plane still reaches the doubled rate.
259 bypass: HashMap<u8, (ChannelState, Vec<f32>)>,
260}
261
262impl SbrChain {
263 pub fn new(rate: u32) -> SbrChain {
264 SbrChain {
265 rate,
266 ps_config: false,
267 elements: HashMap::new(),
268 bypass: HashMap::new(),
269 }
270 }
271
272 /// Marks PS as signalled by the config: the element's output is stereo.
273 pub fn set_ps_config(&mut self, on: bool) {
274 self.ps_config = on;
275 for elem in self.elements.values_mut() {
276 elem.parser.set_ps_config(on);
277 }
278 }
279
280 /// Parses one FIL element's `sbr_extension_data` (the reader
281 /// positioned right past `bs_extension_type`) for element `tag`.
282 pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option<SbrData> {
283 let (rate, ps_config) = (self.rate, self.ps_config);
284 let elem = self.elements.entry((tag, is_cpe)).or_insert_with(|| {
285 let mut parser = SbrParser::new(rate);
286 parser.set_ps_config(ps_config);
287 Element {
288 parser,
289 channels: Vec::new(),
290 last_data: None,
291 last_header: None,
292 ps_engine: PsEngine::new(),
293 }
294 });
295 let data = elem.parser.parse(r, is_cpe).ok()?;
296 let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1);
297 // PS needs a second synthesis state: the right output channel.
298 let need = data.channels.len().max(if data.ps.is_some() { 2 } else { 1 });
299 while elem.channels.len() < need {
300 let seed = 0x1234_5678u32.wrapping_add(elem.channels.len() as u32 * 0x9e37_79b9);
301 elem.channels.push(ChannelState::new(n_q, seed));
302 }
303 Some(data)
304 }
305
306 /// Doubles the rate of an LFE plane. The standard gives the LFE no SBR
307 /// payload, so its core plane (one frame of `FRAME_LEN` samples) would
308 /// otherwise stay at half length and misalign everything after it. It runs
309 /// through the same 32-band analysis and 64-band synthesis as the SBR
310 /// planes, with the high bands left empty, which is what ffmpeg's output
311 /// does for the LFE channel.
312 pub fn bypass_plane(&mut self, tag: u8, plane: &mut Vec<f32>) {
313 let (state, delay) = self
314 .bypass
315 .entry(tag)
316 .or_insert_with(|| (ChannelState::new(1, 0), vec![0.0; BYPASS_DELAY]));
317 let num_slots = plane.len() / ANALYSIS_BANDS;
318 let mut out = std::mem::take(delay);
319 out.reserve(num_slots * SYNTHESIS_BANDS);
320 for slot in 0..num_slots {
321 let mut chunk = [0f32; ANALYSIS_BANDS];
322 chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]);
323 // Same scale handling as `apply_data`: the QMF pair is calibrated to the
324 // un-normalised core PCM domain.
325 for s in &mut chunk {
326 *s /= crate::decode::OUTPUT_SCALE;
327 }
328 let sub = state.analysis.process_slot(&chunk);
329 let mut slots = [Complex::<f64>::ZERO; SYNTHESIS_BANDS];
330 slots[..ANALYSIS_BANDS].copy_from_slice(&sub);
331 out.extend(synth_slots(&mut state.synthesis, &[slots]));
332 }
333 // The reconstructed planes lag their raw analysis by `HF_ADJ` slots;
334 // hold the bypass output back by the same amount so they line up.
335 let produced = num_slots * SYNTHESIS_BANDS;
336 *plane = out[..produced].to_vec();
337 *delay = out[produced..].to_vec();
338 }
339
340 /// Like [`apply`], for an element whose output lives at `out[start..start + n]`
341 /// inside a whole access unit. A PS element gets its second output
342 /// plane inserted right after its first, so the access unit gains a
343 /// channel.
344 pub fn apply_planes(
345 &mut self,
346 tag: u8,
347 is_cpe: bool,
348 data: &SbrData,
349 out: &mut Vec<Vec<f32>>,
350 start: usize,
351 n: usize,
352 ) -> crate::Result<()> {
353 let n = expand_for_ps(out, start, n, is_cpe, data.ps.is_some());
354 self.apply(tag, is_cpe, data, &mut out[start..start + n])
355 }
356
357 /// [`apply_planes`] for the last parsed frame, as [`apply_last`].
358 pub fn apply_last_planes(
359 &mut self,
360 tag: u8,
361 is_cpe: bool,
362 out: &mut Vec<Vec<f32>>,
363 start: usize,
364 n: usize,
365 ) -> crate::Result<()> {
366 let has_ps = self
367 .elements
368 .get(&(tag, is_cpe))
369 .and_then(|e| e.last_data.as_ref())
370 .is_some_and(|d| d.ps.is_some());
371 let n = expand_for_ps(out, start, n, is_cpe, has_ps);
372 self.apply_last(tag, is_cpe, &mut out[start..start + n])
373 }
374
375 /// Runs the chain over `planes` (element `tag`'s already-decoded core
376 /// PCM, one plane per channel), replacing each in place with its
377 /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a
378 /// silent no-op: `planes` is left at its core content.
379 pub fn apply(
380 &mut self,
381 tag: u8,
382 is_cpe: bool,
383 data: &SbrData,
384 planes: &mut [Vec<f32>],
385 ) -> crate::Result<()> {
386 if let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) {
387 elem.last_data = Some(data.clone());
388 }
389 self.apply_data(tag, is_cpe, data, planes, "fresh")
390 }
391
392 /// Re-runs the chain for `tag` using the last successfully parsed
393 /// frame's SBR data, for an access unit whose own FIL element carried no
394 /// fresh payload this frame. A no-op (planes left at core content, same
395 /// as [`apply`]'s existing malformed/missing-state fallback) if no prior
396 /// frame ever parsed successfully for this element.
397 pub fn apply_last(
398 &mut self,
399 tag: u8,
400 is_cpe: bool,
401 planes: &mut [Vec<f32>],
402 ) -> crate::Result<()> {
403 let Some(data) = self
404 .elements
405 .get(&(tag, is_cpe))
406 .and_then(|e| e.last_data.clone())
407 else {
408 return Ok(());
409 };
410 self.apply_data(tag, is_cpe, &data, planes, "hold")
411 }
412
413 fn apply_data(
414 &mut self,
415 tag: u8,
416 is_cpe: bool,
417 data: &SbrData,
418 planes: &mut [Vec<f32>],
419 source: &'static str,
420 ) -> crate::Result<()> {
421 if source == "hold" {
422 HOLD_CALLS.fetch_add(1, Ordering::Relaxed);
423 }
424 let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else {
425 return Ok(());
426 };
427 let Some(tables) = elem.parser.tables().cloned() else {
428 return Ok(());
429 };
430 let reset = elem.last_header.as_ref() != elem.parser.header();
431 elem.last_header = elem.parser.header().cloned();
432 let Some(header) = elem.parser.header().cloned() else {
433 return Ok(());
434 };
435 let coupling = data.coupling;
436 let sideinfo_on = sideinfo_enabled();
437 let au_frame = if sideinfo_on {
438 SIDEINFO_FRAME.fetch_add(1, Ordering::Relaxed)
439 } else {
440 0
441 };
442 // PS: the mono channel is synthesized twice, through its own state and
443 // through channel 1's (the right output), so both stay in step.
444 let ps_mode = !is_cpe && planes.len() >= 2 && data.ps.is_some();
445 let mut ps_planes: Option<(Vec<f32>, Vec<f32>)> = None;
446 let mut r_synth = if ps_mode && elem.channels.len() >= 2 {
447 Some(std::mem::take(&mut elem.channels[1].synthesis))
448 } else {
449 None
450 };
451 for (ch, plane) in planes.iter_mut().enumerate() {
452 if ch >= data.channels.len() || ch >= elem.channels.len() {
453 continue;
454 }
455 let num_slots = plane.len() / ANALYSIS_BANDS;
456 if num_slots == 0 {
457 continue;
458 }
459 if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() {
460 static N: AtomicUsize = AtomicUsize::new(0);
461 let n = N.fetch_add(1, Ordering::Relaxed);
462 if n < 40 {
463 let rms = (plane.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>()
464 / plane.len().max(1) as f64)
465 .sqrt();
466 eprintln!(
467 "PREQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}",
468 plane.len(),
469 &plane[..8.min(plane.len())]
470 );
471 }
472 }
473 let state = &mut elem.channels[ch];
474 let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS];
475 let mut raw = Vec::with_capacity(num_slots);
476 for slot in 0..num_slots {
477 let mut chunk = [0f32; ANALYSIS_BANDS];
478 chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]);
479 // `plane` is already at the decoder's final output scale
480 // (`decode::OUTPUT_SCALE`, applied by the core filterbank),
481 // but the transmitted envelope/noise data is calibrated
482 // against the core's un-normalized internal PCM domain --
483 // undo that scale before analysis so the SBR gain match
484 // (raw QMF energy vs. the transmitted target) compares
485 // like against like, and reapply it once below after
486 // synthesis. Without this the gain step's `target/current`
487 // ratio is inflated by `1/OUTPUT_SCALE^2` in energy,
488 // exactly the multi-order-of-magnitude blowup this chain
489 // used to produce on every real HE-AAC file.
490 for s in &mut chunk {
491 *s /= crate::decode::OUTPUT_SCALE;
492 }
493 let sub = state.analysis.process_slot(&chunk);
494 for b in 0..ANALYSIS_BANDS {
495 low_cur[b][slot] = sub[b];
496 }
497 raw.push(sub);
498 }
499
500 let sbr_ch = &data.channels[ch];
501 if std::env::var("EC_AAC_SBR_DEBUG").is_ok() {
502 eprintln!("SBRDBG coupling={}", data.coupling);
503 debug_dump(&header, &tables, sbr_ch, ch);
504 }
505 if sideinfo_on {
506 let mean = |rows: &[Vec<i32>]| -> Vec<f64> {
507 rows.iter()
508 .map(|r| {
509 if r.is_empty() {
510 0.0
511 } else {
512 r.iter().map(|&v| f64::from(v)).sum::<f64>() / r.len() as f64
513 }
514 })
515 .collect()
516 };
517 let row = SbrSideInfoRow {
518 frame: au_frame,
519 tag,
520 ch,
521 source,
522 coupling,
523 amp_res: header.amp_res,
524 kx: tables.kx,
525 k2: tables.k2,
526 f_high: tables.f_high.clone(),
527 f_noise: tables.f_noise.clone(),
528 t_env: sbr_ch.t_env.clone(),
529 freq_res: sbr_ch.freq_res.clone(),
530 invf_mode: sbr_ch.invf_mode.clone(),
531 add_harmonic: sbr_ch.add_harmonic.clone(),
532 e_q_means: mean(&sbr_ch.e_q),
533 q_q_means: mean(&sbr_ch.q_q),
534 freq_scale: header.freq_scale,
535 alter_scale: header.alter_scale,
536 noise_bands: header.noise_bands,
537 limiter_bands: header.limiter_bands,
538 limiter_gains: header.limiter_gains,
539 interpol_freq: header.interpol_freq,
540 smoothing_mode: header.smoothing_mode,
541 start_freq: header.start_freq,
542 stop_freq: header.stop_freq,
543 xover_band: header.xover_band,
544 num_noise: sbr_ch.t_noise.len().saturating_sub(1),
545 patch_lengths: sbr_hf::build_patches(&tables).iter().map(|p| p.width).collect(),
546 df_env: sbr_ch.df_env.clone(),
547 df_noise: sbr_ch.df_noise.clone(),
548 };
549 let log = SIDEINFO_LOG.get_or_init(|| std::sync::Mutex::new(Vec::new()));
550 if let Ok(mut l) = log.lock() {
551 l.push(row);
552 }
553 }
554 let qmfdump_on = qmfdump_enabled();
555 if qmfdump_on {
556 qmfdump_energies("analysis", 0, &low_cur);
557 }
558 let hf = sbr_hf::generate(
559 &low_cur,
560 &tables,
561 &sbr_ch.invf_mode,
562 &mut state.chirp,
563 &mut state.hf_hist,
564 );
565 if qmfdump_on {
566 qmfdump_energies("post_patch", tables.kx as usize, &hf);
567 }
568 let (env_energy, noise_energy) =
569 sbr_env::dequantize_frame(&data.channels, ch, coupling);
570 // sbr_env::adjust works in QMF-slot units; the parsed borders
571 // are in the coarser envelope-time-slot units (see RATE above).
572 let scaled = SbrChannel {
573 t_env: sbr_ch.t_env.iter().map(|&t| t * RATE).collect(),
574 t_noise: sbr_ch.t_noise.iter().map(|&t| t * RATE).collect(),
575 ..sbr_ch.clone()
576 };
577 let limiter_table = sbr_hf::limiter_band_table(
578 &tables,
579 &sbr_hf::build_patches(&tables),
580 header.limiter_bands,
581 )?;
582 // Envelope slot i is raw slot i - HF_ADJ: prepend the previous
583 // frame's raw HF tail so the grid (up to 2*t_E(L_E) <= 38) lines
584 // up with the content it was measured on (§4.6.18.7.6).
585 let m_max = hf.len();
586 if state.hf_tail.len() != m_max || reset {
587 state.hf_tail = vec![vec![Complex::ZERO; HF_ADJ]; m_max];
588 state.y_carry.clear();
589 }
590 let mut xh: Vec<Vec<Complex<f64>>> = (0..m_max)
591 .map(|m| {
592 let mut v = state.hf_tail[m].clone();
593 v.extend_from_slice(&hf[m]);
594 v
595 })
596 .collect();
597 for (m, band) in hf.iter().enumerate().take(m_max) {
598 state.hf_tail[m] = band[num_slots.saturating_sub(HF_ADJ)..].to_vec();
599 }
600 sbr_env::adjust(
601 &mut xh,
602 &tables,
603 &header,
604 &scaled,
605 &env_energy,
606 &noise_energy,
607 &limiter_table,
608 &mut state.adj,
609 reset,
610 );
611 // Output slot i: low band from the delayed raw analysis, HF from
612 // the previous frame's carried-over adjusted slots first, then
613 // this frame's; slots past the frame end are carried forward.
614 let i_temp = state.y_carry.first().map(Vec::len).unwrap_or(0).min(num_slots);
615 let t_end = (scaled.t_env.last().copied().unwrap_or(0).max(0) as usize).min(xh[0].len());
616 let mut hf: Vec<Vec<Complex<f64>>> = vec![vec![Complex::ZERO; num_slots]; m_max];
617 for (m, band) in hf.iter_mut().enumerate().take(m_max) {
618 for (i, slot) in band.iter_mut().enumerate().take(i_temp) {
619 *slot = state.y_carry[m][i];
620 }
621 for (i, slot) in band.iter_mut().enumerate().take(num_slots).skip(i_temp) {
622 *slot = xh[m][i];
623 }
624 }
625 state.y_carry = (0..m_max)
626 .map(|m| xh[m][num_slots.min(t_end)..t_end].to_vec())
627 .collect();
628 let raw: Vec<[Complex<f64>; ANALYSIS_BANDS]> = {
629 let mut d = state.low_tail.clone();
630 d.extend_from_slice(&raw);
631 state.low_tail = d[d.len() - HF_ADJ..].to_vec();
632 d.truncate(num_slots);
633 d
634 };
635 if qmfdump_on {
636 qmfdump_energies("post_adjust", tables.kx as usize, &hf);
637 }
638
639 let kx = (tables.kx as usize).min(ANALYSIS_BANDS);
640 let k2 = (tables.k2 as usize).min(SYNTHESIS_BANDS);
641 let mut vs: Vec<[Complex<f64>; SYNTHESIS_BANDS]> = Vec::with_capacity(num_slots);
642 for slot in 0..num_slots {
643 let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
644 v[0..kx].copy_from_slice(&raw[slot][0..kx]);
645 if !crate::knobs::sbr_hf_bypass() {
646 for b in kx..k2 {
647 if b - kx < hf.len() {
648 v[b] = hf[b - kx][slot];
649 }
650 }
651 }
652 vs.push(v);
653 }
654 let out = match (ps_mode && num_slots == PS_SLOTS, data.ps.as_ref()) {
655 (true, Some(ps)) => {
656 let (left, right) =
657 render_ps(&mut elem.ps_engine, ps, &vs, &state.low_tail, kx, k2);
658 let left_pcm = synth_slots(&mut state.synthesis, &left);
659 let right_pcm = match r_synth.as_mut() {
660 Some(rs) => synth_slots(rs, &right),
661 None => left_pcm.clone(),
662 };
663 ps_planes = Some((left_pcm, right_pcm));
664 Vec::new()
665 }
666 _ => synth_slots(&mut state.synthesis, &vs),
667 };
668 if std::env::var("EC_AAC_SBR_PREQMF_DUMP").is_ok() {
669 static N: AtomicUsize = AtomicUsize::new(0);
670 let n = N.fetch_add(1, Ordering::Relaxed);
671 if n < 40 {
672 let rms = (out.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>()
673 / out.len().max(1) as f64)
674 .sqrt();
675 eprintln!(
676 "POSTQMF n={n} tag={tag} ch={ch} len={} rms={rms:.6} first8={:?}",
677 out.len(),
678 &out[..8.min(out.len())]
679 );
680 }
681 }
682 if ps_planes.is_none() {
683 *plane = out;
684 }
685 }
686 if let Some(rs) = r_synth {
687 elem.channels[1].synthesis = rs;
688 }
689 if let Some((left, right)) = ps_planes {
690 planes[0] = left;
691 planes[1] = right;
692 }
693 Ok(())
694 }
695}
696
697/// Inserts the second output plane a PS element needs, right after its first
698/// (a copy, which the PS path then overwrites). Returns the element's new
699/// plane count: 2 when a plane was inserted.
700fn expand_for_ps(out: &mut Vec<Vec<f32>>, start: usize, n: usize, is_cpe: bool, ps: bool) -> usize {
701 if ps && !is_cpe && n == 1 && start < out.len() {
702 let copy = out[start].clone();
703 out.insert(start + 1, copy);
704 2
705 } else {
706 n
707 }
708}
709
710/// Narrows a working-precision QMF sample to the PS engine's single precision.
711fn narrow32(v: Complex<f64>) -> Complex<f32> {
712 Complex { re: v.re as f32, im: v.im as f32 }
713}
714
715/// Widens a PS output slab row back to working precision.
716fn widen(row: &[Complex<f32>; QMF_BANDS]) -> [Complex<f64>; SYNTHESIS_BANDS] {
717 let mut out = [Complex::ZERO; SYNTHESIS_BANDS];
718 for (dst, src) in out.iter_mut().zip(row.iter()) {
719 *dst = Complex { re: f64::from(src.re), im: f64::from(src.im) };
720 }
721 out
722}
723
724/// Runs Parametric Stereo over one frame's synthesis input `vs` (32 slots of
725/// the mono channel's QMF bands). The hybrid filter reads 6 slots past the
726/// frame, for the low bands it splits: those come from `low_tail`, the raw
727/// analysis of the same frame, which holds the slots `vs` cannot.
728type PlaneVec = Vec<[Complex<f64>; SYNTHESIS_BANDS]>;
729
730fn render_ps(
731 engine: &mut PsEngine,
732 ps: &PsCommon,
733 vs: &[[Complex<f64>; SYNTHESIS_BANDS]],
734 low_tail: &[[Complex<f64>; ANALYSIS_BANDS]],
735 kx: usize,
736 top: usize,
737) -> (PlaneVec, PlaneVec) {
738 if !ps.start {
739 // No PS header yet: both channels carry the mono signal (FFmpeg's memcpy).
740 return (vs.to_vec(), vs.to_vec());
741 }
742 let mut x = [[Complex::<f32>::new(0.0, 0.0); QMF_BANDS]; IN_SLOTS];
743 for (j, v) in vs.iter().enumerate().take(IN_SLOTS) {
744 for (dst, src) in x[j].iter_mut().zip(v.iter()) {
745 *dst = narrow32(*src);
746 }
747 }
748 // Only bands below the SBR start hold raw analysis; the hybrid filter
749 // reads lookahead for bands 0..5 only, and those are raw below kx.
750 let lookahead_bands = kx.min(5);
751 for (j, row) in low_tail.iter().enumerate() {
752 let slot = PS_SLOTS + j;
753 if slot >= IN_SLOTS {
754 break;
755 }
756 for (b, sample) in row.iter().enumerate().take(lookahead_bands) {
757 x[slot][b] = narrow32(*sample);
758 }
759 }
760 let (left, right) = engine.apply(ps, &x, top);
761 (
762 left.iter().map(widen).collect(),
763 right.iter().map(widen).collect(),
764 )
765}
766
767/// Runs `slots` through a synthesis bank, at the SBR output scale.
768fn synth_slots(synth: &mut Synthesis, slots: &[[Complex<f64>; SYNTHESIS_BANDS]]) -> Vec<f32> {
769 let mut out = Vec::with_capacity(slots.len() * SYNTHESIS_BANDS);
770 for v in slots {
771 let mut pcm = synth.process_slot(v);
772 for s in &mut pcm {
773 // The spec 32-analysis/64-synthesis pair (4.6.18.4.1 +
774 // 4.6.18.8.2, literal equations) reads back at half the
775 // core's amplitude; the 2x is the upsampler's gain.
776 *s *= 2.0 * crate::decode::OUTPUT_SCALE;
777 }
778 out.extend_from_slice(&pcm);
779 }
780 out
781}
782
783#[cfg(test)]
784mod tests {
785 use super::*;
786 use crate::sbr_bands::freq_tables;
787 use crate::sbr_payload::{SbrHeader, SbrParser};
788
789 fn tables() -> crate::sbr_bands::BandTables {
790 freq_tables(44100, 5, 3, 2, 1, 2, 2).unwrap()
791 }
792
793 fn header() -> SbrHeader {
794 SbrHeader {
795 amp_res: 1,
796 start_freq: 5,
797 stop_freq: 3,
798 xover_band: 2,
799 freq_scale: 2,
800 alter_scale: 1,
801 noise_bands: 2,
802 limiter_bands: 2,
803 limiter_gains: 3,
804 interpol_freq: 1,
805 smoothing_mode: 1,
806 }
807 }
808
809 fn one_channel(n_q: usize, n_low: usize) -> SbrChannel {
810 SbrChannel {
811 t_env: vec![0, 16],
812 freq_res: vec![0],
813 t_noise: vec![0, 16],
814 e_q: vec![vec![10i32; n_low]],
815 q_q: vec![vec![2i32; n_q]],
816 invf_mode: vec![0; n_q],
817 add_harmonic: None,
818 df_env: vec![],
819 df_noise: vec![],
820 l_a: -1,
821 amp_res: 1,
822 }
823 }
824
825 /// Two adjacent 1024-sample core AUs run through the same `SbrChain`
826 /// element (as `raw_data_block`'s per-AU calls do) must each double to
827 /// exactly `2 * ANALYSIS_BANDS * 32` samples with no gap or overlap at
828 /// the junction: the coverage hole that let a whole access unit's
829 /// doubling go missing (see `apply_last`) never showed up in the
830 /// synthetic continuous-stream QMF round trip, since that test never
831 /// crosses an AU boundary at all.
832 #[test]
833 fn two_adjacent_access_units_double_rate_with_no_junction_discontinuity() {
834 let t = tables();
835 let n_low = t.n_low;
836 let n_q = t.n_q;
837 let mut chain = SbrChain::new(44100);
838 let tag = 0u8;
839 chain.elements.insert(
840 (tag, true),
841 Element {
842 parser: SbrParser::new(44100),
843 channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)],
844 last_data: None,
845 last_header: None,
846 ps_engine: PsEngine::new(),
847 },
848 );
849 chain
850 .elements
851 .get_mut(&(tag, true))
852 .unwrap()
853 .parser
854 .set_for_test(header(), t.clone());
855
856 let data = SbrData {
857 coupling: false,
858 channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)],
859 ps: None,
860 };
861
862 // A steady tone, not silence: silence round-trips trivially (every
863 // sample is already continuous at 0), which would hide exactly the
864 // discontinuity this test exists to catch.
865 let core_au = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.1).sin() * 0.2).collect() };
866 let mut planes = vec![core_au(), core_au()];
867 chain.apply(tag, true, &data, &mut planes).unwrap();
868
869 let expected_len = 32 * SYNTHESIS_BANDS;
870 for (ch, plane) in planes.iter().enumerate() {
871 assert_eq!(
872 plane.len(),
873 expected_len,
874 "ch{ch} AU1 didn't double to {expected_len} samples"
875 );
876 }
877
878 // Second AU through the SAME chain/state, as consecutive AUs in one
879 // stream are: this is what exercises the QMF history/HF-chirp/noise
880 // generator continuity across the junction, not just each AU in
881 // isolation.
882 let mut planes2 = vec![core_au(), core_au()];
883 chain.apply(tag, true, &data, &mut planes2).unwrap();
884 for (ch, plane) in planes2.iter().enumerate() {
885 assert_eq!(
886 plane.len(),
887 expected_len,
888 "ch{ch} AU2 didn't double to {expected_len} samples"
889 );
890 }
891
892 // Cumulative length across both AUs is exactly 2x2048, and the
893 // junction (last sample of AU1 next to the first of AU2) is not a
894 // discontinuity spike: a dropped/duplicated-AU bug (the one fixed by
895 // `apply_last`) either changes this total length or opens a silent
896 // gap, and a QMF history corruption at the boundary spikes the
897 // derivative right at the join far above the steady-state
898 // sample-to-sample delta the continuous tone otherwise has.
899 for ch in 0..2 {
900 let mut joined = planes[ch].clone();
901 joined.extend_from_slice(&planes2[ch]);
902 assert_eq!(joined.len(), 2 * expected_len);
903
904 let steady_delta = |s: &[f32]| -> f32 {
905 s.windows(2)
906 .skip(expected_len / 2)
907 .take(expected_len / 4)
908 .map(|w| (w[1] - w[0]).abs())
909 .fold(0.0f32, f32::max)
910 };
911 let typical = steady_delta(&joined);
912 let junction_delta = (joined[expected_len] - joined[expected_len - 1]).abs();
913 assert!(
914 junction_delta <= typical * 4.0 + 1e-6,
915 "ch{ch} junction delta {junction_delta} far exceeds steady-state delta {typical} -- AU-boundary discontinuity"
916 );
917 }
918 }
919
920 /// §4.4: `element_instance_tag` is a namespace per element *type* --
921 /// an encoder may legally give an SCE and a CPE in the same access
922 /// unit the same tag value (this is exactly what a 5.1 stream with
923 /// SCE+CPE+CPE+LFE does). `SbrChain` used to key its per-element state
924 /// by the bare tag, so the CPE's `parse`/`apply` would silently reuse
925 /// (and corrupt) the SCE's parser/channel state. Keying by `(tag,
926 /// is_cpe)` must keep them fully independent: driving distinct tones
927 /// through an SCE and a same-tagged CPE must not bleed into each
928 /// other's output.
929 #[test]
930 fn an_sce_and_a_same_tagged_cpe_do_not_share_state() {
931 let t = tables();
932 let n_low = t.n_low;
933 let n_q = t.n_q;
934 let mut chain = SbrChain::new(44100);
935 let tag = 0u8;
936
937 for is_cpe in [false, true] {
938 let n_ch = if is_cpe { 2 } else { 1 };
939 chain.elements.insert(
940 (tag, is_cpe),
941 Element {
942 parser: SbrParser::new(44100),
943 channels: (0..n_ch)
944 .map(|i| ChannelState::new(n_q, 10 + i as u32))
945 .collect(),
946 last_data: None,
947 last_header: None,
948 ps_engine: PsEngine::new(),
949 },
950 );
951 chain
952 .elements
953 .get_mut(&(tag, is_cpe))
954 .unwrap()
955 .parser
956 .set_for_test(header(), t.clone());
957 }
958
959 let sce_data = SbrData {
960 coupling: false,
961 channels: vec![one_channel(n_q, n_low)],
962 ps: None,
963 };
964 let cpe_data = SbrData {
965 coupling: false,
966 channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)],
967 ps: None,
968 };
969
970 let sce_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.05).sin() * 0.2).collect() };
971 let cpe_tone = || -> Vec<f32> { (0..1024).map(|i| (i as f32 * 0.37).sin() * 0.2).collect() };
972
973 let mut sce_planes = vec![sce_tone()];
974 chain.apply(tag, false, &sce_data, &mut sce_planes).unwrap();
975 let mut cpe_planes = vec![cpe_tone(), cpe_tone()];
976 chain.apply(tag, true, &cpe_data, &mut cpe_planes).unwrap();
977
978 // If state aliased, the CPE call above would have run through (and
979 // mutated) the SCE's Analysis/Synthesis/chirp/noise state instead
980 // of its own -- re-running the SCE with the same input must give
981 // the SAME output as the first call, proving its state was never
982 // touched by the CPE call in between.
983 let mut sce_planes2 = vec![sce_tone()];
984 chain.apply(tag, false, &sce_data, &mut sce_planes2).unwrap();
985
986 // A fresh, never-driven SCE-only chain gives the reference: one AU
987 // through tag/is_cpe=(0,false), nothing else touching its state.
988 let mut reference = SbrChain::new(44100);
989 reference.elements.insert(
990 (tag, false),
991 Element {
992 parser: SbrParser::new(44100),
993 channels: vec![ChannelState::new(n_q, 10)],
994 last_data: None,
995 last_header: None,
996 ps_engine: PsEngine::new(),
997 },
998 );
999 reference
1000 .elements
1001 .get_mut(&(tag, false))
1002 .unwrap()
1003 .parser
1004 .set_for_test(header(), t.clone());
1005 let mut sce_ref1 = vec![sce_tone()];
1006 reference.apply(tag, false, &sce_data, &mut sce_ref1).unwrap();
1007 let mut sce_ref2 = vec![sce_tone()];
1008 reference.apply(tag, false, &sce_data, &mut sce_ref2).unwrap();
1009
1010 assert_eq!(
1011 sce_planes[0], sce_ref1[0],
1012 "SCE tag 0's first call already diverges from an isolated reference"
1013 );
1014 assert_eq!(
1015 sce_planes2[0], sce_ref2[0],
1016 "SCE tag 0's state was mutated by the same-tagged CPE's apply() call in between"
1017 );
1018 }
1019
1020 /// Round-13 stitching verdict (queue item 1): the QMF filterbank pair
1021 /// underneath the low band (`0..kx`, `apply_data` copies
1022 /// `raw[slot][0..kx]` straight from `Analysis` into `Synthesis`, no
1023 /// envelope/HF touch) must give BIT-IDENTICAL output whether its
1024 /// `process_slot` calls arrive chunked AU-by-AU (32 slots per call,
1025 /// matching a real 1024-sample core frame) or as one continuous run --
1026 /// `Analysis`/`Synthesis`'s own history/overlap-add state carries
1027 /// between calls regardless of how the caller groups them, so the
1028 /// SAME sample sequence fed either way must produce the SAME output.
1029 /// (An earlier version of this test drove it through `SbrChain::apply`
1030 /// with one AU-sized `SbrData` grid reused for a 10-AU-long "continuous"
1031 /// call; that showed a large divergence, but the divergence was a test
1032 /// bug, not a real one: `sbr_env::adjust`'s envelope gain is grid-scoped
1033 /// to `ch.t_env`'s own 32-slot range, so a 320-slot call only gain-
1034 /// adjusted its first AU's worth and left the other nine raw --
1035 /// `apply_data` is inherently one-AU-per-call by design, so the
1036 /// meaningful comparison is at the QMF layer these AU-sized calls sit
1037 /// on top of, not by force-feeding it a multi-AU span it was never
1038 /// meant to take in one call.)
1039 #[test]
1040 fn ten_aus_worth_of_qmf_slots_chained_per_au_are_bit_identical_to_one_continuous_pass() {
1041 let mut rng = 0x02f6_e2b1_u64;
1042 let mut next = || {
1043 rng ^= rng << 13;
1044 rng ^= rng >> 7;
1045 rng ^= rng << 17;
1046 (rng >> 11) as f64 / (1u64 << 53) as f64 - 0.5
1047 };
1048 let all_samples: Vec<f32> = (0..10 * 1024).map(|_| next() as f32 * 0.3).collect();
1049
1050 // (a) Per-AU: a fresh 32-slot chunk fed to the SAME persistent
1051 // Analysis/Synthesis pair per call, as `apply_data` drives it once
1052 // per access unit.
1053 let mut analysis_a = Analysis::new();
1054 let mut synthesis_a = Synthesis::new();
1055 let mut per_au_out: Vec<f32> = Vec::new();
1056 for au in all_samples.chunks(1024) {
1057 for slot in au.as_chunks::<ANALYSIS_BANDS>().0 {
1058 let mut chunk = [0f32; ANALYSIS_BANDS];
1059 chunk.copy_from_slice(slot);
1060 let sub = analysis_a.process_slot(&chunk);
1061 let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
1062 v[0..ANALYSIS_BANDS].copy_from_slice(&sub);
1063 per_au_out.extend(synthesis_a.process_slot(&v));
1064 }
1065 }
1066
1067 // (b) One continuous pass over the same samples, same bank pair,
1068 // just not grouped into per-AU calls.
1069 let mut analysis_b = Analysis::new();
1070 let mut synthesis_b = Synthesis::new();
1071 let mut continuous_out: Vec<f32> = Vec::new();
1072 for slot in all_samples.as_chunks::<ANALYSIS_BANDS>().0 {
1073 let mut chunk = [0f32; ANALYSIS_BANDS];
1074 chunk.copy_from_slice(slot);
1075 let sub = analysis_b.process_slot(&chunk);
1076 let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
1077 v[0..ANALYSIS_BANDS].copy_from_slice(&sub);
1078 continuous_out.extend(synthesis_b.process_slot(&v));
1079 }
1080
1081 assert_eq!(per_au_out.len(), continuous_out.len());
1082 let mut max_diff = 0.0f32;
1083 let mut diverging = 0usize;
1084 for (a, b) in per_au_out.iter().zip(&continuous_out) {
1085 let d = (a - b).abs();
1086 if d != 0.0 {
1087 diverging += 1;
1088 }
1089 max_diff = max_diff.max(d);
1090 }
1091 let total = per_au_out.len();
1092 println!("stitching check: {diverging}/{total} samples differ, max abs diff {max_diff:e}");
1093 assert!(
1094 max_diff < 1e-5,
1095 "per-AU chaining and one continuous pass diverge by {max_diff:e} -- a real QMF stitching bug"
1096 );
1097 }
1098}