//! Wires the SBR payload parser, HF generator and envelope adjuster into //! one per-element chain the decoder's `raw_data_block` loop drives: parse //! a FIL element's `sbr_extension_data`, run the previous SCE/CPE's core //! PCM through 32-band analysis, generate and adjust the HF region, and //! resynthesize through the 64-band bank to double-rate PCM in place. use crate::sbr_env::{self, AdjustState}; use crate::sbr_hf::{self, ChirpState, HfHistory}; use crate::ps_data::PsCommon; use crate::ps_dsp::{IN_SLOTS, PsEngine, QMF_BANDS}; use crate::sbr_payload::{SbrChannel, SbrData, SbrParser}; use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis}; use ec_core::BitReader; use ec_dsp::Complex; use std::collections::HashMap; /// Envelope-grid "time slots" (§4.6.18.4, `numTimeSlots = 16` for a /// 1024-sample core frame) are half as fine as the QMF slots SBR actually /// runs at (32 per frame): `RATE = 2` converts one to the other. const RATE: i64 = 2; /// Per-channel DSP state an SBR element's reconstruction carries across /// frames: the QMF filterbank pair, the HF generator's LPC history and /// chirp factors, and the noise-floor generator. struct ChannelState { analysis: Analysis, synthesis: Synthesis, hf_hist: HfHistory, chirp: ChirpState, adj: AdjustState, /// §4.6.18.7.6 `tHFAdj`/overlap buffers: the SBR output lags the raw /// analysis by `HF_ADJ` slots, so the previous frame's last `HF_ADJ` /// raw low-band and raw HF slots are kept, plus the already-adjusted HF /// slots past the frame end that a variable-border envelope produced /// (`Y` of slots `32..2*t_E(L_E)`), which lead the next frame's output. low_tail: Vec<[Complex; ANALYSIS_BANDS]>, hf_tail: Vec>>, y_carry: Vec>>, } /// Slots by which the HF adjuster's envelope grid lags the raw QMF frame /// (`tHFAdj` + the 6-slot overlap, §4.6.18.7.6 / Figure 4.32). const HF_ADJ: usize = 6; /// Samples a bypass plane lags its raw analysis by: `HF_ADJ` slots at the doubled rate. const BYPASS_DELAY: usize = HF_ADJ * SYNTHESIS_BANDS; impl ChannelState { fn new(n_q: usize, _seed: u32) -> ChannelState { ChannelState { analysis: Analysis::new(), synthesis: Synthesis::new(), hf_hist: HfHistory::new(ANALYSIS_BANDS), chirp: ChirpState::new(n_q.max(1)), adj: AdjustState::new(), low_tail: vec![[Complex::ZERO; ANALYSIS_BANDS]; HF_ADJ], hf_tail: Vec::new(), y_carry: Vec::new(), } } } /// One SBR element's (SCE or CPE) persistent state. struct Element { parser: SbrParser, channels: Vec, /// The most recently parsed frame's envelope/noise/grid data, held so an /// access unit whose FIL element carries no fresh SBR payload this frame /// (an "unavailable" frame, §4.6.18: legal per spec and the decoder must /// keep reconstructing at the doubled rate using the last known data, /// not silently fall back to core-only output) can still be /// SBR-reconstructed instead of leaving that one access unit's plane at /// half length -- which otherwise permanently shifts every sample after /// it out of alignment with a reference that stayed at full rate. last_data: Option, /// Header of the previous applied frame: a change is the spec's reset. last_header: Option, /// Parametric Stereo reconstruction state (hybrid filter, decorrelator, /// mixing history), used when the element carries PS. ps_engine: PsEngine, } impl Element { fn ensure_channels(&mut self, need: usize, downsampled: bool) { while self.channels.len() < need { let seed = 0x1234_5678u32.wrapping_add(self.channels.len() as u32 * 0x9e37_79b9); let mut channel = ChannelState::new(1, seed); if downsampled { channel.synthesis = Synthesis::downsampled(); } self.channels.push(channel); } } } /// QMF slots per SBR frame: the PS path runs only for the 32-slot frames /// that AAC-LC's 1024-sample frames produce. const PS_SLOTS: usize = 32; /// Every configured SBR element in a stream, keyed by /// `element_instance_tag` (assumed stable frame to frame, as every /// encoder in practice emits it). pub struct SbrChain { rate: u32, downsampled: bool, /// PS is signalled by the config (explicit HE-AACv2). ps_config: bool, // Keyed by (element_instance_tag, is_cpe): SCE/LFE and CPE instance // tags are independent namespaces per §4.4 (an encoder may legally // reuse tag 0 for both an SCE and a CPE in the same access unit), so // a bare `u8` key aliased two distinct elements' QMF/HF/noise state // together whenever that happened -- exactly the case in a 5.1 // stream (SCE + two CPEs). elements: HashMap<(u8, bool), Element>, /// Doubling state of each LFE element, keyed by its instance tag. The LFE /// carries no SBR payload, but its plane still reaches the doubled rate. bypass: HashMap)>, } impl SbrChain { pub fn new(rate: u32) -> SbrChain { SbrChain { rate, downsampled: false, ps_config: false, elements: HashMap::new(), bypass: HashMap::new(), } } pub fn set_downsampled(&mut self, on: bool) { self.downsampled = on; } /// Marks PS as signalled by the config: the element's output is stereo. pub fn set_ps_config(&mut self, on: bool) { self.ps_config = on; for elem in self.elements.values_mut() { elem.parser.set_ps_config(on); } } /// Parses one FIL element's `sbr_extension_data` (the reader /// positioned right past `bs_extension_type`) for element `tag`. pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option { let (ps_config, downsampled) = (self.ps_config, self.downsampled); let elem = self.element(tag, is_cpe); let data = elem.parser.parse(r, is_cpe).ok()?; let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); let ps_out = data.ps.is_some() || (ps_config && !is_cpe); let need = data.channels.len().max(if ps_out { 2 } else { 1 }); elem.ensure_channels(need, downsampled); for ch in &mut elem.channels { if ch.chirp.bands() != n_q { ch.chirp = ChirpState::new(n_q); } } Some(data) } fn element(&mut self, tag: u8, is_cpe: bool) -> &mut Element { let (rate, ps_config) = (self.rate, self.ps_config); self.elements.entry((tag, is_cpe)).or_insert_with(|| { let mut parser = SbrParser::new(rate); parser.set_ps_config(ps_config); Element { parser, channels: Vec::new(), last_data: None, last_header: None, ps_engine: PsEngine::new(), } }) } fn apply_low_only(&mut self, tag: u8, is_cpe: bool, planes: &mut [Vec]) { let dup = !is_cpe && planes.len() == 2; let downsampled = self.downsampled; let elem = self.element(tag, is_cpe); elem.ensure_channels(planes.len(), downsampled); let mut right_synth = if dup { Some(std::mem::take(&mut elem.channels[1].synthesis)) } else { None }; let mut right_plane = None; for (plane, state) in planes.iter_mut().zip(elem.channels.iter_mut()) { if right_plane.is_some() { break; } let num_slots = plane.len() / ANALYSIS_BANDS; let mut raw = Vec::with_capacity(num_slots); for slot in 0..num_slots { let mut chunk = [0f32; ANALYSIS_BANDS]; chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); for s in &mut chunk { *s /= crate::decode::OUTPUT_SCALE; } raw.push(state.analysis.process_slot(&chunk)); } let mut delayed = state.low_tail.clone(); delayed.extend_from_slice(&raw); state.low_tail = delayed[delayed.len() - HF_ADJ..].to_vec(); delayed.truncate(num_slots); let vs: Vec<[Complex; SYNTHESIS_BANDS]> = delayed .iter() .map(|sub| { let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; v[..ANALYSIS_BANDS].copy_from_slice(sub); v }) .collect(); *plane = synth_slots(&mut state.synthesis, &vs); if let Some(rs) = right_synth.as_mut() { right_plane = Some(synth_slots(rs, &vs)); } } if let Some(rs) = right_synth { elem.channels[1].synthesis = rs; } if let Some(right) = right_plane { planes[1] = right; } } /// Doubles the rate of an LFE plane. The standard gives the LFE no SBR /// payload, so its core plane (one frame of `FRAME_LEN` samples) would /// otherwise stay at half length and misalign everything after it. It runs /// through the same 32-band analysis and 64-band synthesis as the SBR /// planes, with the high bands left empty, which is what ffmpeg's output /// does for the LFE channel. pub fn bypass_plane(&mut self, tag: u8, plane: &mut Vec) { let downsampled = self.downsampled; let (state, delay) = self.bypass.entry(tag).or_insert_with(|| { let mut state = ChannelState::new(1, 0); let mut delay = BYPASS_DELAY; if downsampled { state.synthesis = Synthesis::downsampled(); delay /= 2; } (state, vec![0.0; delay]) }); let num_slots = plane.len() / ANALYSIS_BANDS; let mut out = std::mem::take(delay); out.reserve(num_slots * state.synthesis.bands()); for slot in 0..num_slots { let mut chunk = [0f32; ANALYSIS_BANDS]; chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); // Same scale handling as `apply_data`: the QMF pair is calibrated to the // un-normalised core PCM domain. for s in &mut chunk { *s /= crate::decode::OUTPUT_SCALE; } let sub = state.analysis.process_slot(&chunk); let mut slots = [Complex::::ZERO; SYNTHESIS_BANDS]; slots[..ANALYSIS_BANDS].copy_from_slice(&sub); out.extend(synth_slots(&mut state.synthesis, &[slots])); } // The reconstructed planes lag their raw analysis by `HF_ADJ` slots; // hold the bypass output back by the same amount so they line up. let produced = num_slots * state.synthesis.bands(); *plane = out[..produced].to_vec(); *delay = out[produced..].to_vec(); } /// Like [`apply`], for an element whose output lives at `out[start..start + n]` /// inside a whole access unit. A PS element gets its second output /// plane inserted right after its first, so the access unit gains a /// channel. pub fn apply_planes( &mut self, tag: u8, is_cpe: bool, data: &SbrData, out: &mut Vec>, start: usize, n: usize, ) -> crate::Result<()> { let n = expand_for_ps(out, start, n, is_cpe, data.ps.is_some() || self.ps_config); self.apply(tag, is_cpe, data, &mut out[start..start + n]) } /// [`apply_planes`] for the last parsed frame, as [`apply_last`]. pub fn apply_last_planes( &mut self, tag: u8, is_cpe: bool, out: &mut Vec>, start: usize, n: usize, ) -> crate::Result<()> { let has_ps = self .elements .get(&(tag, is_cpe)) .and_then(|e| e.last_data.as_ref()) .is_some_and(|d| d.ps.is_some()) || self.ps_config; let n = expand_for_ps(out, start, n, is_cpe, has_ps); self.apply_last(tag, is_cpe, &mut out[start..start + n]) } /// Runs the chain over `planes` (element `tag`'s already-decoded core /// PCM, one plane per channel), replacing each in place with its /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a /// silent no-op: `planes` is left at its core content. pub fn apply( &mut self, tag: u8, is_cpe: bool, data: &SbrData, planes: &mut [Vec], ) -> crate::Result<()> { if let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) { elem.last_data = Some(data.clone()); } self.apply_data(tag, is_cpe, data, planes) } /// Re-runs the chain for `tag` using the last successfully parsed /// frame's SBR data, for an access unit whose own FIL element carried no /// fresh payload this frame. A no-op (planes left at core content, same /// as [`apply`]'s existing malformed/missing-state fallback) if no prior /// frame ever parsed successfully for this element. pub fn apply_last( &mut self, tag: u8, is_cpe: bool, planes: &mut [Vec], ) -> crate::Result<()> { let Some(data) = self .elements .get(&(tag, is_cpe)) .and_then(|e| e.last_data.clone()) else { self.apply_low_only(tag, is_cpe, planes); return Ok(()); }; self.apply_data(tag, is_cpe, &data, planes) } fn apply_data( &mut self, tag: u8, is_cpe: bool, data: &SbrData, planes: &mut [Vec], ) -> crate::Result<()> { let band_limit = if self.downsampled { ANALYSIS_BANDS } else { SYNTHESIS_BANDS }; let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else { return Ok(()); }; let Some(tables) = elem.parser.tables().cloned() else { return Ok(()); }; let reset = elem.last_header.as_ref() != elem.parser.header(); elem.last_header = elem.parser.header().cloned(); let Some(header) = elem.parser.header().cloned() else { return Ok(()); }; let coupling = data.coupling; // PS: the mono channel is synthesized twice, through its own state and // through channel 1's (the right output), so both stay in step. let ps_mode = !is_cpe && planes.len() >= 2 && data.ps.is_some(); let mut ps_planes: Option<(Vec, Vec)> = None; let dup_mode = !is_cpe && planes.len() >= 2 && data.ps.is_none(); let mut r_synth = if (ps_mode || dup_mode) && elem.channels.len() >= 2 { Some(std::mem::take(&mut elem.channels[1].synthesis)) } else { None }; for (ch, plane) in planes.iter_mut().enumerate() { if ch >= data.channels.len() || ch >= elem.channels.len() { continue; } let num_slots = plane.len() / ANALYSIS_BANDS; if num_slots == 0 { continue; } let state = &mut elem.channels[ch]; let (low_cur, raw) = analyze_plane(state, plane, num_slots); let sbr_ch = &data.channels[ch]; let hf = sbr_hf::generate( &low_cur, &tables, &sbr_ch.invf_mode, &mut state.chirp, &mut state.hf_hist, ); let (env_energy, noise_energy) = sbr_env::dequantize_frame(&data.channels, ch, coupling); // sbr_env::adjust works in QMF-slot units; the parsed borders // are in the coarser envelope-time-slot units (see RATE above). let scaled = SbrChannel { t_env: sbr_ch.t_env.iter().map(|&t| t * RATE).collect(), t_noise: sbr_ch.t_noise.iter().map(|&t| t * RATE).collect(), ..sbr_ch.clone() }; let limiter_table = sbr_hf::limiter_band_table( &tables, &sbr_hf::build_patches(&tables), header.limiter_bands, )?; // Envelope slot i is raw slot i - HF_ADJ: prepend the previous // frame's raw HF tail so the grid (up to 2*t_E(L_E) <= 38) lines // up with the content it was measured on (§4.6.18.7.6). let m_max = hf.len(); if state.hf_tail.len() != m_max || reset { state.hf_tail = vec![vec![Complex::ZERO; HF_ADJ]; m_max]; state.y_carry.clear(); } let mut xh: Vec>> = (0..m_max) .map(|m| { let mut v = state.hf_tail[m].clone(); v.extend_from_slice(&hf[m]); v }) .collect(); for (m, band) in hf.iter().enumerate().take(m_max) { state.hf_tail[m] = band[num_slots.saturating_sub(HF_ADJ)..].to_vec(); } sbr_env::adjust( &mut xh, &tables, &header, &scaled, &env_energy, &noise_energy, &limiter_table, &mut state.adj, reset, ); // Output slot i: low band from the delayed raw analysis, HF from // the previous frame's carried-over adjusted slots first, then // this frame's; slots past the frame end are carried forward. let i_temp = state.y_carry.first().map(Vec::len).unwrap_or(0).min(num_slots); let t_end = (scaled.t_env.last().copied().unwrap_or(0).max(0) as usize).min(xh[0].len()); let mut hf: Vec>> = vec![vec![Complex::ZERO; num_slots]; m_max]; for (m, band) in hf.iter_mut().enumerate().take(m_max) { for (i, slot) in band.iter_mut().enumerate().take(i_temp) { *slot = state.y_carry[m][i]; } for (i, slot) in band.iter_mut().enumerate().take(num_slots).skip(i_temp) { *slot = xh[m][i]; } } state.y_carry = (0..m_max) .map(|m| xh[m][num_slots.min(t_end)..t_end].to_vec()) .collect(); let raw: Vec<[Complex; ANALYSIS_BANDS]> = { let mut d = state.low_tail.clone(); d.extend_from_slice(&raw); state.low_tail = d[d.len() - HF_ADJ..].to_vec(); d.truncate(num_slots); d }; let kx = (tables.kx as usize).min(ANALYSIS_BANDS); let k2 = (tables.k2 as usize).min(band_limit); let vs = merge_bands(&raw, &hf, kx, k2, num_slots); let out = match (ps_mode && num_slots == PS_SLOTS, data.ps.as_ref()) { (true, Some(ps)) => { let (left, right) = render_ps(&mut elem.ps_engine, ps, &vs, &state.low_tail, kx, k2); let left_pcm = synth_slots(&mut state.synthesis, &left); let right_pcm = match r_synth.as_mut() { Some(rs) => synth_slots(rs, &right), None => left_pcm.clone(), }; ps_planes = Some((left_pcm, right_pcm)); Vec::new() } _ if dup_mode => { let left_pcm = synth_slots(&mut state.synthesis, &vs); let right_pcm = match r_synth.as_mut() { Some(rs) => synth_slots(rs, &vs), None => left_pcm.clone(), }; ps_planes = Some((left_pcm, right_pcm)); Vec::new() } _ => synth_slots(&mut state.synthesis, &vs), }; if ps_planes.is_none() { *plane = out; } } if let Some(rs) = r_synth { elem.channels[1].synthesis = rs; } if let Some((left, right)) = ps_planes { planes[0] = left; planes[1] = right; } Ok(()) } } type QmfGrid = Vec>>; fn analyze_plane( state: &mut ChannelState, plane: &[f32], num_slots: usize, ) -> (QmfGrid, Vec<[Complex; ANALYSIS_BANDS]>) { let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS]; let mut raw = Vec::with_capacity(num_slots); for slot in 0..num_slots { let mut chunk = [0f32; ANALYSIS_BANDS]; chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); // `plane` is already at the decoder's final output scale // (`decode::OUTPUT_SCALE`, applied by the core filterbank), // but the transmitted envelope/noise data is calibrated // against the core's un-normalized internal PCM domain -- // undo that scale before analysis so the SBR gain match // (raw QMF energy vs. the transmitted target) compares // like against like, and reapply it once below after // synthesis. Without this the gain step's `target/current` // ratio is inflated by `1/OUTPUT_SCALE^2` in energy, // exactly the multi-order-of-magnitude blowup this chain // used to produce on every real HE-AAC file. for s in &mut chunk { *s /= crate::decode::OUTPUT_SCALE; } let sub = state.analysis.process_slot(&chunk); for b in 0..ANALYSIS_BANDS { low_cur[b][slot] = sub[b]; } raw.push(sub); } (low_cur, raw) } fn merge_bands( raw: &[[Complex; ANALYSIS_BANDS]], hf: &[Vec>], kx: usize, k2: usize, num_slots: usize, ) -> Vec<[Complex; SYNTHESIS_BANDS]> { let mut vs: Vec<[Complex; SYNTHESIS_BANDS]> = Vec::with_capacity(num_slots); for slot in 0..num_slots { let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; v[0..kx].copy_from_slice(&raw[slot][0..kx]); for b in kx..k2 { if b - kx < hf.len() { v[b] = hf[b - kx][slot]; } } vs.push(v); } vs } /// Inserts the second output plane a PS element needs, right after its first /// (a copy, which the PS path then overwrites). Returns the element's new /// plane count: 2 when a plane was inserted. fn expand_for_ps(out: &mut Vec>, start: usize, n: usize, is_cpe: bool, ps: bool) -> usize { if ps && !is_cpe && n == 1 && start < out.len() { let copy = out[start].clone(); out.insert(start + 1, copy); 2 } else { n } } /// Narrows a working-precision QMF sample to the PS engine's single precision. fn narrow32(v: Complex) -> Complex { Complex { re: v.re as f32, im: v.im as f32 } } /// Widens a PS output slab row back to working precision. fn widen(row: &[Complex; QMF_BANDS]) -> [Complex; SYNTHESIS_BANDS] { let mut out = [Complex::ZERO; SYNTHESIS_BANDS]; for (dst, src) in out.iter_mut().zip(row.iter()) { *dst = Complex { re: f64::from(src.re), im: f64::from(src.im) }; } out } /// Runs Parametric Stereo over one frame's synthesis input `vs` (32 slots of /// the mono channel's QMF bands). The hybrid filter reads 6 slots past the /// frame, for the low bands it splits: those come from `low_tail`, the raw /// analysis of the same frame, which holds the slots `vs` cannot. type PlaneVec = Vec<[Complex; SYNTHESIS_BANDS]>; fn render_ps( engine: &mut PsEngine, ps: &PsCommon, vs: &[[Complex; SYNTHESIS_BANDS]], low_tail: &[[Complex; ANALYSIS_BANDS]], kx: usize, top: usize, ) -> (PlaneVec, PlaneVec) { if !ps.start { // No PS header yet: both channels carry the mono signal (FFmpeg's memcpy). return (vs.to_vec(), vs.to_vec()); } let mut x = [[Complex::::new(0.0, 0.0); QMF_BANDS]; IN_SLOTS]; for (j, v) in vs.iter().enumerate().take(IN_SLOTS) { for (dst, src) in x[j].iter_mut().zip(v.iter()) { *dst = narrow32(*src); } } // Only bands below the SBR start hold raw analysis; the hybrid filter // reads lookahead for bands 0..5 only, and those are raw below kx. let lookahead_bands = kx.min(5); for (j, row) in low_tail.iter().enumerate() { let slot = PS_SLOTS + j; if slot >= IN_SLOTS { break; } for (b, sample) in row.iter().enumerate().take(lookahead_bands) { x[slot][b] = narrow32(*sample); } } let (left, right) = engine.apply(ps, &x, top); ( left.iter().map(widen).collect(), right.iter().map(widen).collect(), ) } /// Runs `slots` through a synthesis bank, at the SBR output scale. fn synth_slots(synth: &mut Synthesis, slots: &[[Complex; SYNTHESIS_BANDS]]) -> Vec { let bands = synth.bands(); let mut out = Vec::with_capacity(slots.len() * bands); for v in slots { let mut pcm = synth.process_slot(v); for s in &mut pcm { // The spec 32-analysis/64-synthesis pair (4.6.18.4.1 + // 4.6.18.8.2, literal equations) reads back at half the // core's amplitude; the 2x is the upsampler's gain. *s *= 2.0 * crate::decode::OUTPUT_SCALE; } out.extend_from_slice(&pcm[..bands]); } out } #[cfg(test)] mod tests { use super::*; use crate::sbr_bands::freq_tables; use crate::sbr_payload::{SbrHeader, SbrParser}; fn tables() -> crate::sbr_bands::BandTables { freq_tables(44100, 5, 3, 2, 1, 2, 2).unwrap() } fn header() -> SbrHeader { SbrHeader { amp_res: 1, start_freq: 5, stop_freq: 3, xover_band: 2, freq_scale: 2, alter_scale: 1, noise_bands: 2, limiter_bands: 2, limiter_gains: 3, interpol_freq: 1, smoothing_mode: 1, } } fn one_channel(n_q: usize, n_low: usize) -> SbrChannel { SbrChannel { t_env: vec![0, 16], freq_res: vec![0], t_noise: vec![0, 16], e_q: vec![vec![10i32; n_low]], q_q: vec![vec![2i32; n_q]], invf_mode: vec![0; n_q], add_harmonic: None, df_env: vec![], df_noise: vec![], l_a: -1, amp_res: 1, } } /// Two adjacent 1024-sample core AUs run through the same `SbrChain` /// element (as `raw_data_block`'s per-AU calls do) must each double to /// exactly `2 * ANALYSIS_BANDS * 32` samples with no gap or overlap at /// the junction: the coverage hole that let a whole access unit's /// doubling go missing (see `apply_last`) never showed up in the /// synthetic continuous-stream QMF round trip, since that test never /// crosses an AU boundary at all. #[test] fn two_adjacent_access_units_double_rate_with_no_junction_discontinuity() { let t = tables(); let n_low = t.n_low; let n_q = t.n_q; let mut chain = SbrChain::new(44100); let tag = 0u8; chain.elements.insert( (tag, true), Element { parser: SbrParser::new(44100), channels: vec![ChannelState::new(n_q, 1), ChannelState::new(n_q, 2)], last_data: None, last_header: None, ps_engine: PsEngine::new(), }, ); chain .elements .get_mut(&(tag, true)) .unwrap() .parser .set_for_test(header(), t.clone()); let data = SbrData { coupling: false, channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)], ps: None, }; // A steady tone, not silence: silence round-trips trivially (every // sample is already continuous at 0), which would hide exactly the // discontinuity this test exists to catch. let core_au = || -> Vec { (0..1024).map(|i| (i as f32 * 0.1).sin() * 0.2).collect() }; let mut planes = vec![core_au(), core_au()]; chain.apply(tag, true, &data, &mut planes).unwrap(); let expected_len = 32 * SYNTHESIS_BANDS; for (ch, plane) in planes.iter().enumerate() { assert_eq!( plane.len(), expected_len, "ch{ch} AU1 didn't double to {expected_len} samples" ); } // Second AU through the SAME chain/state, as consecutive AUs in one // stream are: this is what exercises the QMF history/HF-chirp/noise // generator continuity across the junction, not just each AU in // isolation. let mut planes2 = vec![core_au(), core_au()]; chain.apply(tag, true, &data, &mut planes2).unwrap(); for (ch, plane) in planes2.iter().enumerate() { assert_eq!( plane.len(), expected_len, "ch{ch} AU2 didn't double to {expected_len} samples" ); } // Cumulative length across both AUs is exactly 2x2048, and the // junction (last sample of AU1 next to the first of AU2) is not a // discontinuity spike: a dropped/duplicated-AU bug (the one fixed by // `apply_last`) either changes this total length or opens a silent // gap, and a QMF history corruption at the boundary spikes the // derivative right at the join far above the steady-state // sample-to-sample delta the continuous tone otherwise has. for ch in 0..2 { let mut joined = planes[ch].clone(); joined.extend_from_slice(&planes2[ch]); assert_eq!(joined.len(), 2 * expected_len); let steady_delta = |s: &[f32]| -> f32 { s.windows(2) .skip(expected_len / 2) .take(expected_len / 4) .map(|w| (w[1] - w[0]).abs()) .fold(0.0f32, f32::max) }; let typical = steady_delta(&joined); let junction_delta = (joined[expected_len] - joined[expected_len - 1]).abs(); assert!( junction_delta <= typical * 4.0 + 1e-6, "ch{ch} junction delta {junction_delta} far exceeds steady-state delta {typical} -- AU-boundary discontinuity" ); } } /// §4.4: `element_instance_tag` is a namespace per element *type* -- /// an encoder may legally give an SCE and a CPE in the same access /// unit the same tag value (this is exactly what a 5.1 stream with /// SCE+CPE+CPE+LFE does). `SbrChain` used to key its per-element state /// by the bare tag, so the CPE's `parse`/`apply` would silently reuse /// (and corrupt) the SCE's parser/channel state. Keying by `(tag, /// is_cpe)` must keep them fully independent: driving distinct tones /// through an SCE and a same-tagged CPE must not bleed into each /// other's output. #[test] fn an_sce_and_a_same_tagged_cpe_do_not_share_state() { let t = tables(); let n_low = t.n_low; let n_q = t.n_q; let mut chain = SbrChain::new(44100); let tag = 0u8; for is_cpe in [false, true] { let n_ch = if is_cpe { 2 } else { 1 }; chain.elements.insert( (tag, is_cpe), Element { parser: SbrParser::new(44100), channels: (0..n_ch) .map(|i| ChannelState::new(n_q, 10 + i as u32)) .collect(), last_data: None, last_header: None, ps_engine: PsEngine::new(), }, ); chain .elements .get_mut(&(tag, is_cpe)) .unwrap() .parser .set_for_test(header(), t.clone()); } let sce_data = SbrData { coupling: false, channels: vec![one_channel(n_q, n_low)], ps: None, }; let cpe_data = SbrData { coupling: false, channels: vec![one_channel(n_q, n_low), one_channel(n_q, n_low)], ps: None, }; let sce_tone = || -> Vec { (0..1024).map(|i| (i as f32 * 0.05).sin() * 0.2).collect() }; let cpe_tone = || -> Vec { (0..1024).map(|i| (i as f32 * 0.37).sin() * 0.2).collect() }; let mut sce_planes = vec![sce_tone()]; chain.apply(tag, false, &sce_data, &mut sce_planes).unwrap(); let mut cpe_planes = vec![cpe_tone(), cpe_tone()]; chain.apply(tag, true, &cpe_data, &mut cpe_planes).unwrap(); // If state aliased, the CPE call above would have run through (and // mutated) the SCE's Analysis/Synthesis/chirp/noise state instead // of its own -- re-running the SCE with the same input must give // the SAME output as the first call, proving its state was never // touched by the CPE call in between. let mut sce_planes2 = vec![sce_tone()]; chain.apply(tag, false, &sce_data, &mut sce_planes2).unwrap(); // A fresh, never-driven SCE-only chain gives the reference: one AU // through tag/is_cpe=(0,false), nothing else touching its state. let mut reference = SbrChain::new(44100); reference.elements.insert( (tag, false), Element { parser: SbrParser::new(44100), channels: vec![ChannelState::new(n_q, 10)], last_data: None, last_header: None, ps_engine: PsEngine::new(), }, ); reference .elements .get_mut(&(tag, false)) .unwrap() .parser .set_for_test(header(), t.clone()); let mut sce_ref1 = vec![sce_tone()]; reference.apply(tag, false, &sce_data, &mut sce_ref1).unwrap(); let mut sce_ref2 = vec![sce_tone()]; reference.apply(tag, false, &sce_data, &mut sce_ref2).unwrap(); assert_eq!( sce_planes[0], sce_ref1[0], "SCE tag 0's first call already diverges from an isolated reference" ); assert_eq!( sce_planes2[0], sce_ref2[0], "SCE tag 0's state was mutated by the same-tagged CPE's apply() call in between" ); } /// Round-13 stitching verdict (queue item 1): the QMF filterbank pair /// underneath the low band (`0..kx`, `apply_data` copies /// `raw[slot][0..kx]` straight from `Analysis` into `Synthesis`, no /// envelope/HF touch) must give BIT-IDENTICAL output whether its /// `process_slot` calls arrive chunked AU-by-AU (32 slots per call, /// matching a real 1024-sample core frame) or as one continuous run -- /// `Analysis`/`Synthesis`'s own history/overlap-add state carries /// between calls regardless of how the caller groups them, so the /// SAME sample sequence fed either way must produce the SAME output. /// (An earlier version of this test drove it through `SbrChain::apply` /// with one AU-sized `SbrData` grid reused for a 10-AU-long "continuous" /// call; that showed a large divergence, but the divergence was a test /// bug, not a real one: `sbr_env::adjust`'s envelope gain is grid-scoped /// to `ch.t_env`'s own 32-slot range, so a 320-slot call only gain- /// adjusted its first AU's worth and left the other nine raw -- /// `apply_data` is inherently one-AU-per-call by design, so the /// meaningful comparison is at the QMF layer these AU-sized calls sit /// on top of, not by force-feeding it a multi-AU span it was never /// meant to take in one call.) #[test] fn ten_aus_worth_of_qmf_slots_chained_per_au_are_bit_identical_to_one_continuous_pass() { let mut rng = 0x02f6_e2b1_u64; let mut next = || { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; (rng >> 11) as f64 / (1u64 << 53) as f64 - 0.5 }; let all_samples: Vec = (0..10 * 1024).map(|_| next() as f32 * 0.3).collect(); // (a) Per-AU: a fresh 32-slot chunk fed to the SAME persistent // Analysis/Synthesis pair per call, as `apply_data` drives it once // per access unit. let mut analysis_a = Analysis::new(); let mut synthesis_a = Synthesis::new(); let mut per_au_out: Vec = Vec::new(); for au in all_samples.chunks(1024) { for slot in au.as_chunks::().0 { let mut chunk = [0f32; ANALYSIS_BANDS]; chunk.copy_from_slice(slot); let sub = analysis_a.process_slot(&chunk); let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; v[0..ANALYSIS_BANDS].copy_from_slice(&sub); per_au_out.extend(synthesis_a.process_slot(&v)); } } // (b) One continuous pass over the same samples, same bank pair, // just not grouped into per-AU calls. let mut analysis_b = Analysis::new(); let mut synthesis_b = Synthesis::new(); let mut continuous_out: Vec = Vec::new(); for slot in all_samples.as_chunks::().0 { let mut chunk = [0f32; ANALYSIS_BANDS]; chunk.copy_from_slice(slot); let sub = analysis_b.process_slot(&chunk); let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; v[0..ANALYSIS_BANDS].copy_from_slice(&sub); continuous_out.extend(synthesis_b.process_slot(&v)); } assert_eq!(per_au_out.len(), continuous_out.len()); let mut max_diff = 0.0f32; let mut diverging = 0usize; for (a, b) in per_au_out.iter().zip(&continuous_out) { let d = (a - b).abs(); if d != 0.0 { diverging += 1; } max_diff = max_diff.max(d); } let total = per_au_out.len(); println!("stitching check: {diverging}/{total} samples differ, max abs diff {max_diff:e}"); assert!( max_diff < 1e-5, "per-AU chaining and one continuous pass diverge by {max_diff:e} -- a real QMF stitching bug" ); } }