From d8db6262615fcd98c2b226b0357869639a98f115 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 12:14:10 +0300 Subject: [PATCH] ec-aac SBR: downsampled SBR (ext rate < 2*core, e.g. al_sbr_sr_48_2_fsaac48 ASC 11 90 56 e5 98) ran the 64-band doubling chain with band tables at the 48 kHz ext rate: ours 2048/AU and band-table errors (no sideinfo rows, ours 1001472 = cap at 489 AUs x 2048 vs ffmpeg 1148 x 1024). ffmpeg (aacsbr_template.c 1147/1683/1418): sbr->sample_rate = 2*core for tables, downsampled = ext_sample_rate < sbr->sample_rate -> 32-band synthesis with the decimated window (ds[n]=c[2n]), 32 output samples/slot. Fix: parser rate always 2*core, SbrChain::set_downsampled, Synthesis::downsampled (N=32, v 640, shift -0.5 matching our analysis phase; python replica of analysis->synth32 corr 0.995 at lag 289 vs 0.9967 for the 64-band pair), k2 clamped to 32, LFE bypass uses the same bank. Also QMF_WINDOW[384] and [512] had the wrong sign vs ffmpeg us/ds tables (ffmpeg flips at 385/513, mirror-symmetric with 128/256; ours at 384/512; table now equals ffmpeg's us and ds to 1e-10), pinned sum updated 81.46300943655164 -> 82.21187106118578. cargo check -p ec-aac --all-targets clean; tests not run --- crates/ec-aac/src/decode.rs | 8 +++ crates/ec-aac/src/lib.rs | 6 +- crates/ec-aac/src/sbr_chain.rs | 47 +++++++++++----- crates/ec-aac/src/sbr_qmf.rs | 86 +++++++++++++++-------------- crates/ec-aac/src/sbr_qmf_window.rs | 6 +- 5 files changed, 92 insertions(+), 61 deletions(-) diff --git a/crates/ec-aac/src/decode.rs b/crates/ec-aac/src/decode.rs index e782f647..c74b4b05 100644 --- a/crates/ec-aac/src/decode.rs +++ b/crates/ec-aac/src/decode.rs @@ -582,6 +582,14 @@ impl BlockDecoder { self.sbr = rate.map(crate::sbr_chain::SbrChain::new); } + /// Marks the SBR output as downsampled: the extension rate is below twice + /// the core rate, so the synthesis stays at 32 bands. + pub fn set_sbr_downsampled(&mut self, on: bool) { + if let Some(sbr) = self.sbr.as_mut() { + sbr.set_downsampled(on); + } + } + /// Marks Parametric Stereo as signalled by the config, for the SBR chain /// (if one is armed): its elements then decode to two channels. pub fn set_sbr_ps(&mut self, on: bool) { diff --git a/crates/ec-aac/src/lib.rs b/crates/ec-aac/src/lib.rs index 106b7426..2a96f88e 100644 --- a/crates/ec-aac/src/lib.rs +++ b/crates/ec-aac/src/lib.rs @@ -144,8 +144,10 @@ impl AacDecoder { // SBR (and Parametric Stereo, for HE-AACv2) is reconstructed: the // core is decoded first, then the extension-rate chain runs on it. if cfg.sbr_present { - let rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2); - d.block.set_sbr_rate(Some(rate)); + let sbr_rate = cfg.sample_rate * 2; + let ext_rate = cfg.extension_sample_rate.unwrap_or(sbr_rate); + d.block.set_sbr_rate(Some(sbr_rate)); + d.block.set_sbr_downsampled(ext_rate < sbr_rate); d.block.set_sbr_ps(cfg.ps_present); } else if !cfg.ps_present { // Plain AAC-LC config: an SBR payload may still follow (implicit signalling). diff --git a/crates/ec-aac/src/sbr_chain.rs b/crates/ec-aac/src/sbr_chain.rs index e2378ebb..d5db41c5 100644 --- a/crates/ec-aac/src/sbr_chain.rs +++ b/crates/ec-aac/src/sbr_chain.rs @@ -237,10 +237,14 @@ struct Element { } impl Element { - fn ensure_channels(&mut self, need: usize) { + 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); - self.channels.push(ChannelState::new(1, seed)); + let mut channel = ChannelState::new(1, seed); + if downsampled { + channel.synthesis = Synthesis::downsampled(); + } + self.channels.push(channel); } } } @@ -254,6 +258,7 @@ const PS_SLOTS: usize = 32; /// 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 @@ -272,6 +277,7 @@ impl SbrChain { pub fn new(rate: u32) -> SbrChain { SbrChain { rate, + downsampled: false, ps_config: false, elements: HashMap::new(), bypass: HashMap::new(), @@ -279,6 +285,10 @@ impl SbrChain { } /// Marks PS as signalled by the config: the element's output is stereo. + pub fn set_downsampled(&mut self, on: bool) { + self.downsampled = on; + } + pub fn set_ps_config(&mut self, on: bool) { self.ps_config = on; for elem in self.elements.values_mut() { @@ -289,13 +299,13 @@ impl SbrChain { /// 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 = self.ps_config; + 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); + elem.ensure_channels(need, downsampled); for ch in &mut elem.channels { if ch.chirp.bands() != n_q { ch.chirp = ChirpState::new(n_q); @@ -321,8 +331,9 @@ impl SbrChain { 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()); + elem.ensure_channels(planes.len(), downsampled); let mut right_synth = if dup { Some(std::mem::take(&mut elem.channels[1].synthesis)) } else { @@ -375,13 +386,19 @@ impl SbrChain { /// 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 (state, delay) = self - .bypass - .entry(tag) - .or_insert_with(|| (ChannelState::new(1, 0), vec![0.0; BYPASS_DELAY])); + 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 * SYNTHESIS_BANDS); + 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]); @@ -397,7 +414,7 @@ impl SbrChain { } // 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 * SYNTHESIS_BANDS; + let produced = num_slots * state.synthesis.bands(); *plane = out[..produced].to_vec(); *delay = out[produced..].to_vec(); } @@ -488,6 +505,7 @@ impl SbrChain { if source == "hold" { HOLD_CALLS.fetch_add(1, Ordering::Relaxed); } + let band_limit = if self.downsampled { ANALYSIS_BANDS } else { SYNTHESIS_BANDS }; let Some(elem) = self.elements.get_mut(&(tag, is_cpe)) else { return Ok(()); }; @@ -705,7 +723,7 @@ impl SbrChain { } let kx = (tables.kx as usize).min(ANALYSIS_BANDS); - let k2 = (tables.k2 as usize).min(SYNTHESIS_BANDS); + let k2 = (tables.k2 as usize).min(band_limit); 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]; @@ -843,7 +861,8 @@ fn render_ps( /// Runs `slots` through a synthesis bank, at the SBR output scale. fn synth_slots(synth: &mut Synthesis, slots: &[[Complex; SYNTHESIS_BANDS]]) -> Vec { - let mut out = Vec::with_capacity(slots.len() * SYNTHESIS_BANDS); + 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 { @@ -852,7 +871,7 @@ fn synth_slots(synth: &mut Synthesis, slots: &[[Complex; SYNTHESIS_BANDS]]) // core's amplitude; the 2x is the upsampler's gain. *s *= 2.0 * crate::decode::OUTPUT_SCALE; } - out.extend_from_slice(&pcm); + out.extend_from_slice(&pcm[..bands]); } out } diff --git a/crates/ec-aac/src/sbr_qmf.rs b/crates/ec-aac/src/sbr_qmf.rs index f3c39e4a..47961884 100644 --- a/crates/ec-aac/src/sbr_qmf.rs +++ b/crates/ec-aac/src/sbr_qmf.rs @@ -218,70 +218,72 @@ impl Default for HfAnalysis { } } -/// The ISO/IEC 14496-3 4.6.18.8.2 64-band complex synthesis QMF bank: -/// complex subband slots in, doubled-rate PCM out, [`SYNTHESIS_BANDS`] -/// output samples per slot. Verified against the literal spec equations at -/// `corr=0.999999` self-consistency (see the module doc). +/// The ISO/IEC 14496-3 4.6.18.8.2 complex synthesis QMF bank: complex subband +/// slots in, PCM out. The 64-band form doubles the rate; the 32-band +/// downsampled form (decimated window, band shift of half a sample like the +/// analysis bank) keeps the core rate. pub struct Synthesis { - /// History buffer `v`, `10 * PROTO_LEN / SYNTHESIS_BANDS * SYNTHESIS_BANDS` - /// = `1280` samples (`4.6.18.8.2`'s own length, not `PROTO_LEN`). - v: [f64; 1280], + bands: usize, + v: Vec, cos_tab: Vec, sin_tab: Vec, } impl Synthesis { - /// A fresh bank with a silent history buffer. pub fn new() -> Synthesis { - let mut cos_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; - let mut sin_tab = vec![0.0f64; SYNTHESIS_BANDS * 128]; - for k in 0..SYNTHESIS_BANDS { - for n in 0..128 { - // phi = pi/128*(k+0.5)*(2n-255) - let phi = std::f64::consts::PI / 128.0 + Synthesis::with_bands(SYNTHESIS_BANDS, 0.0) + } + + pub fn downsampled() -> Synthesis { + Synthesis::with_bands(SYNTHESIS_BANDS / 2, -0.5) + } + + fn with_bands(bands: usize, shift: f64) -> Synthesis { + let len = 2 * bands; + let mut cos_tab = vec![0.0f64; bands * len]; + let mut sin_tab = vec![0.0f64; bands * len]; + for k in 0..bands { + for n in 0..len { + let phi = std::f64::consts::PI / len as f64 * (k as f64 + 0.5) - * (2.0 * n as f64 - 255.0); - cos_tab[k * 128 + n] = phi.cos(); - sin_tab[k * 128 + n] = phi.sin(); + * (2.0 * n as f64 - (2 * len - 1) as f64 + shift); + cos_tab[k * len + n] = phi.cos(); + sin_tab[k * len + n] = phi.sin(); } } Synthesis { - v: [0.0; 1280], + bands, + v: vec![0.0; 10 * len], cos_tab, sin_tab, } } - /// Feeds one slot of [`SYNTHESIS_BANDS`] complex subband samples and - /// returns [`SYNTHESIS_BANDS`] output PCM samples. + pub fn bands(&self) -> usize { + self.bands + } + pub fn process_slot(&mut self, x: &[Complex; SYNTHESIS_BANDS]) -> [f32; SYNTHESIS_BANDS] { - // v[n] = v[n-128] for n=1279..128 (shift), then v[0..128] filled with - // v[n] = Re{ (1/64) sum_k X[k]*exp(j*phi) }, n=0..127. - self.v.copy_within(0..1152, 128); - for n in 0..128 { + let bands = self.bands; + let len = 2 * bands; + self.v.copy_within(0..9 * len, len); + for n in 0..len { let mut re = 0.0f64; - for (k, xk) in x.iter().enumerate() { - let row = k * 128; - // Re{X[k]*exp(j*phi)} = Xre*cos(phi) - Xim*sin(phi) - re += xk.re * self.cos_tab[row + n] - xk.im * self.sin_tab[row + n]; + for (k, xk) in x.iter().take(bands).enumerate() { + let at = k * len + n; + re += xk.re * self.cos_tab[at] - xk.im * self.sin_tab[at]; } self.v[n] = re / SYNTHESIS_BANDS as f64; } - // g[128i+n] = v[256i+n], g[128i+64+n] = v[256i+192+n], i=0..4, n=0..63 - let mut g = [0.0f64; PROTO_LEN]; - for i in 0..5 { - for n in 0..64 { - g[128 * i + n] = self.v[256 * i + n]; - g[128 * i + 64 + n] = self.v[256 * i + 192 + n]; - } - } - // w[n] = g[n]*c[n], n=0..639; y[n] = sum_{k=0}^{9} w[64k+n], n=0..63 + let step = SYNTHESIS_BANDS / bands; let mut out = [0.0f32; SYNTHESIS_BANDS]; - for (n, o) in out.iter_mut().enumerate() { + for (n, o) in out.iter_mut().take(bands).enumerate() { let mut acc = 0.0f64; - for k in 0..10 { - let idx = 64 * k + n; - acc += g[idx] * QMF_WINDOW[idx]; + for i in 0..5 { + let near = self.v[2 * len * i + n]; + let far = self.v[2 * len * i + 3 * bands + n]; + acc += near * QMF_WINDOW[step * (len * i + n)]; + acc += far * QMF_WINDOW[step * (len * i + bands + n)]; } *o = acc as f32; } @@ -470,7 +472,7 @@ mod tests { assert_eq!(QMF_WINDOW.len(), PROTO_LEN); let sum: f64 = QMF_WINDOW.iter().sum(); let sum_sq: f64 = QMF_WINDOW.iter().map(|v| v * v).sum(); - assert!((sum - 81.46300943655164).abs() < 1e-9, "sum={sum}"); + assert!((sum - 82.21187106118578).abs() < 1e-9, "sum={sum}"); assert!((sum_sq - 64.00000000000003).abs() < 1e-9, "sum_sq={sum_sq}"); } diff --git a/crates/ec-aac/src/sbr_qmf_window.rs b/crates/ec-aac/src/sbr_qmf_window.rs index 6a28bc40..1ad74907 100644 --- a/crates/ec-aac/src/sbr_qmf_window.rs +++ b/crates/ec-aac/src/sbr_qmf_window.rs @@ -114,7 +114,7 @@ pub const QMF_WINDOW: [f64; 640] = [ 0.49677082545707, 0.48552530911099, 0.47424532146115, 0.46293080852757, 0.45159965356824, 0.44025537543665, 0.42891199207373, 0.41756968968409, 0.40623176767625, 0.39492117615675, 0.38363500139043, 0.37237955463061, - -0.36115899031355, -0.3499914122931, -0.33887226938665, -0.32781137272105, + 0.36115899031355, -0.3499914122931, -0.33887226938665, -0.32781137272105, -0.31682789136456, -0.30590985751916, -0.29507167170646, -0.28432141891085, -0.27366340405625, -0.26310532994603, -0.25264803095722, -0.24230168845974, -0.23206908706791, -0.22196526964149, -0.21197358538056, -0.20212501768103, @@ -146,7 +146,7 @@ pub const QMF_WINDOW: [f64; 640] = [ 0.02860721736385, 0.02718594296329, 0.02578758475467, 0.02441609920285, 0.02306801692862, 0.02174675502535, 0.02045317933555, 0.01918724313698, 0.01794333813443, 0.01673247129989, 0.01554055533423, 0.01439046660792, - -0.01327182200351, -0.01218499959508, -0.01113155480321, -0.01011502154986, + 0.01327182200351, -0.01218499959508, -0.01113155480321, -0.01011502154986, -0.00913253296085, -0.00817982333726, -0.00726158168517, -0.00637922932685, -0.00553372111088, -0.004722259624, -0.00394011240522, -0.003193377839, -0.00248267236449, -0.00180394725893, -0.00115681355227, -0.00054642808664, @@ -196,7 +196,7 @@ mod tests { argmax = i; } } - assert!((sum - 81.46300943655164).abs() < 1e-9, "sum={sum}"); + assert!((sum - 82.21187106118578).abs() < 1e-9, "sum={sum}"); assert!((sum_sq - 64.00000000000003).abs() < 1e-9, "sum_sq={sum_sq}"); assert!((max - 0.85373856005937).abs() < 1e-12, "max={max}"); assert_eq!(argmax, 320);