diff --git a/crates/ec-aac/src/decode.rs b/crates/ec-aac/src/decode.rs index 3deeccef..b5c110c8 100644 --- a/crates/ec-aac/src/decode.rs +++ b/crates/ec-aac/src/decode.rs @@ -453,6 +453,7 @@ pub struct BlockDecoder { pub states: Vec, noise: Noise, sf_index: u8, + sbr: Option, } impl BlockDecoder { @@ -463,6 +464,7 @@ impl BlockDecoder { states: Vec::new(), noise: Noise(0x1234_5678), sf_index, + sbr: None, } } @@ -470,6 +472,12 @@ impl BlockDecoder { self.sf_index = sf_index; } + /// Enables (or disables, passing `None`) SBR reconstruction at the + /// given extension (doubled) sample rate. + pub fn set_sbr_rate(&mut self, rate: Option) { + self.sbr = rate.map(crate::sbr_chain::SbrChain::new); + } + fn section_data(&self, r: &mut BitReader<'_>, ics: &IcsInfo) -> Result>> { let bits = if ics.window_sequence.is_short() { 3 } else { 5 }; let esc = (1u32 << bits) - 1; @@ -681,6 +689,10 @@ impl BlockDecoder { /// bitstream element order. pub fn raw_data_block(&mut self, r: &mut BitReader<'_>) -> Result>> { let mut out: Vec> = Vec::new(); + // The element (tag, channel range, is_cpe) an immediately following + // FIL's SBR payload would apply to, per §4.5.1: a fill_element + // directly follows the element it decorates. + let mut pending: Option<(u8, usize, usize, bool)> = None; loop { if r.bits_remaining() < 3 { break; @@ -691,12 +703,15 @@ impl BlockDecoder { // element this profile never emits and cannot be skipped // blind, so it is refused rather than silently mis-parsed. 0 | 3 => { - let _tag = r.read_bits(4)?; + let tag = r.read_bits(4)? as u8; + let start = out.len(); let mut ch = [self.channel_stream(r, None)?]; self.finish(&mut ch, None, &mut out); + pending = Some((tag, start, 1, false)); } 1 => { - let _tag = r.read_bits(4)?; + let tag = r.read_bits(4)? as u8; + let start = out.len(); let common = r.read_bit()?; let (shared, mask) = if common { let info = parse_ics_info(r, self.sf_index)?; @@ -724,6 +739,7 @@ impl BlockDecoder { self.channel_stream(r, shared.as_ref())?, ]; self.finish(&mut pair, Some(&mask), &mut out); + pending = Some((tag, start, 2, true)); } 2 => return Err(Error::unsupported("aac", "coupling channel element")), 4 => { @@ -737,16 +753,46 @@ impl BlockDecoder { r.align_to_byte(); } r.skip_bits(count * 8)?; + pending = None; } 5 => { crate::config::skip_program_config(r)?; + pending = None; } 6 => { let mut count = r.read_bits(4)? as u64; if count == 15 { count += r.read_bits(8)? as u64 - 1; } - r.skip_bits(count * 8)?; + let end_bit = r.bit_position() + count * 8; + if let (Some(sbr), Some((tag, start, n, is_cpe))) = + (self.sbr.as_mut(), pending.take()) + { + // extension_payload(): bs_extension_type(4), then + // (for SBR) an optional 10-bit CRC, then + // sbr_extension_data() itself. + if r.bits_remaining() >= 4 { + let ext_type = r.peek_bits(4)?; + if ext_type == 13 || ext_type == 14 { + r.skip_bits(4)?; + if ext_type == 14 && r.bits_remaining() >= 10 { + r.skip_bits(10)?; // bs_sbr_crc_bits + } + if let Some(data) = sbr.parse(r, tag, is_cpe) { + sbr.apply(tag, &data, &mut out[start..start + n]); + } + } + } + } + // Resync to the FIL's declared byte boundary regardless + // of how many bits SBR parsing above actually consumed: + // a parse error or trailing padding must never desync + // the elements that follow. + let now = r.bit_position(); + if now < end_bit { + r.skip_bits(end_bit - now)?; + } + pending = None; } _ => break, } diff --git a/crates/ec-aac/src/lib.rs b/crates/ec-aac/src/lib.rs index 8c3de51e..cba422c5 100644 --- a/crates/ec-aac/src/lib.rs +++ b/crates/ec-aac/src/lib.rs @@ -16,9 +16,11 @@ //! //! AAC-LC (audio object type 2) is complete: all four window sequences, both //! window shapes, TNS, pulse data, M/S and intensity stereo, PNS, and SCE, CPE, -//! LFE, DSE, PCE and FIL elements. HE-AAC's SBR and Parametric Stereo are -//! **not** implemented; a stream that signals them decodes to its AAC-LC core, -//! at the core sample rate, and says so through [`AacDecoder::sbr_support`] and +//! LFE, DSE, PCE and FIL elements. HE-AAC v1 (SBR) is reconstructed: the core +//! decodes, its low bands feed the SBR QMF/HF/envelope chain, and the output +//! is at the extension rate. Parametric Stereo is **not** implemented; a +//! stream that signals it decodes to its AAC-LC core, at the core sample +//! rate, and says so through [`AacDecoder::sbr_support`] and //! [`AacDecoder::output_sample_rate`] rather than silently claiming the //! extension rate. See `sbr_is_reported_not_silently_upsampled` in the tests. @@ -29,6 +31,7 @@ mod decode; mod encode; mod huffman; mod sbr_bands; +mod sbr_chain; mod sbr_env; mod sbr_hf; mod sbr_payload; @@ -55,8 +58,12 @@ use ec_core::BitReader; pub enum SbrSupport { /// The stream is plain AAC-LC: nothing is missing. NotSignalled, - /// SBR (and possibly PS) is signalled and is **not** reconstructed. The - /// AAC-LC core decodes, at the core rate, half the signalled bandwidth. + /// SBR is signalled and **is** reconstructed: the decoded audio spans + /// the full extension bandwidth at the extension sample rate. + V1, + /// SBR is signalled but not reconstructed (Parametric Stereo streams: + /// PS itself is still unimplemented). The AAC-LC core decodes, at the + /// core rate, half the signalled bandwidth. CoreOnly, } @@ -121,6 +128,13 @@ impl AacDecoder { d.block.set_sf_index(cfg.sf_index); d.sample_rate = cfg.sample_rate; d.channels = cfg.channels; + // PS is not reconstructed; SBR is. Both still need the core + // decoded first, but only a plain-SBR (non-PS) stream gets the + // extension-rate QMF chain wired in. + if cfg.sbr_present && !cfg.ps_present { + let rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2); + d.block.set_sbr_rate(Some(rate)); + } d.config = Some(cfg); d } @@ -139,18 +153,21 @@ impl AacDecoder { /// Whether the stream asked for SBR, and what became of it. pub fn sbr_support(&self) -> SbrSupport { match &self.config { - Some(c) if c.sbr_present || c.ps_present => SbrSupport::CoreOnly, + Some(c) if c.ps_present => SbrSupport::CoreOnly, + Some(c) if c.sbr_present => SbrSupport::V1, _ => SbrSupport::NotSignalled, } } - /// The rate the samples this decoder hands back are actually at. - /// - /// For an HE-AAC stream this is the **core** rate, not the doubled rate the - /// configuration advertises: the SBR extension is not reconstructed, so - /// claiming its rate would be claiming bandwidth that is not there. + /// The rate the samples this decoder hands back are actually at: the + /// extension rate for a reconstructed (V1) HE-AAC stream, the core + /// rate for plain AAC-LC or an unreconstructed (PS) stream -- claiming + /// bandwidth that was not actually rebuilt would be a lie. pub fn output_sample_rate(&self) -> Option { - self.config.as_ref().map(|c| c.sample_rate) + self.config.as_ref().map(|c| match self.sbr_support() { + SbrSupport::V1 => c.extension_sample_rate.unwrap_or(c.sample_rate * 2), + _ => c.sample_rate, + }) } /// Decodes one packet: a raw `raw_data_block`, or one or more ADTS frames. @@ -187,7 +204,7 @@ impl AacDecoder { let channels = planes.len(); if channels == 0 { return Ok(DecodedAudio { - sample_rate: self.sample_rate, + sample_rate: self.output_sample_rate().unwrap_or(self.sample_rate), channels: self.channels, samples: Vec::new(), pts, @@ -206,7 +223,7 @@ impl AacDecoder { } } Ok(DecodedAudio { - sample_rate: self.sample_rate, + sample_rate: self.output_sample_rate().unwrap_or(self.sample_rate), channels: channels as u16, samples, pts, diff --git a/crates/ec-aac/src/sbr_chain.rs b/crates/ec-aac/src/sbr_chain.rs new file mode 100644 index 00000000..cea38f99 --- /dev/null +++ b/crates/ec-aac/src/sbr_chain.rs @@ -0,0 +1,161 @@ +//! 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, NoiseGen}; +use crate::sbr_hf::{self, ChirpState, HfHistory}; +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, + noise: NoiseGen, +} + +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)), + noise: NoiseGen::new(seed), + } + } +} + +/// One SBR element's (SCE or CPE) persistent state. +struct Element { + parser: SbrParser, + channels: Vec, +} + +/// 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, + elements: HashMap, +} + +impl SbrChain { + pub fn new(rate: u32) -> SbrChain { + SbrChain { + rate, + elements: HashMap::new(), + } + } + + /// 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 elem = self.elements.entry(tag).or_insert_with(|| Element { + parser: SbrParser::new(self.rate), + channels: Vec::new(), + }); + let data = elem.parser.parse(r, is_cpe).ok()?; + let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); + while elem.channels.len() < data.channels.len() { + let seed = 0x1234_5678u32.wrapping_add(elem.channels.len() as u32 * 0x9e37_79b9); + elem.channels.push(ChannelState::new(n_q, seed)); + } + Some(data) + } + + /// 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, data: &SbrData, planes: &mut [Vec]) { + let Some(elem) = self.elements.get_mut(&tag) else { + return; + }; + let Some(tables) = elem.parser.tables().cloned() else { + return; + }; + let Some(header) = elem.parser.header().cloned() else { + return; + }; + let coupling = data.coupling; + 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 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]); + let sub = state.analysis.process_slot(&chunk); + for b in 0..ANALYSIS_BANDS { + low_cur[b][slot] = sub[b]; + } + raw.push(sub); + } + + let sbr_ch = &data.channels[ch]; + let mut 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(&header, &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() + }; + sbr_env::adjust( + &mut hf, + &tables, + &header, + &scaled, + &env_energy, + &noise_energy, + &mut state.noise, + ); + + let kx = (tables.kx as usize).min(ANALYSIS_BANDS); + let k2 = (tables.k2 as usize).min(SYNTHESIS_BANDS); + let mut out = Vec::with_capacity(num_slots * SYNTHESIS_BANDS); + 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]; + } + } + let pcm = state.synthesis.process_slot(&v); + out.extend_from_slice(&pcm); + } + *plane = out; + } + } +} diff --git a/crates/ec-aac/src/sbr_env.rs b/crates/ec-aac/src/sbr_env.rs index b4809379..2c0f58a2 100644 --- a/crates/ec-aac/src/sbr_env.rs +++ b/crates/ec-aac/src/sbr_env.rs @@ -63,6 +63,55 @@ pub fn dequant_pair(e0_raw: i32, e1_raw: i32, amp_res: u8) -> (f64, f64) { (left, right) } +/// Dequantizes one channel's envelopes and noise floors for one frame, +/// de-mixing through [`dequant_pair`] when `coupling` makes `channels[1]` +/// a balance channel against `channels[0]`. Noise floors dequantize +/// independently per channel regardless of coupling (corner-cut: the +/// balance codebook's noise ratio convention is unverified against a real +/// coupled file, same ceiling as the envelope one above). +pub fn dequantize_frame( + header: &SbrHeader, + channels: &[SbrChannel], + ch: usize, + coupling: bool, +) -> (Vec>, Vec>) { + let c = &channels[ch]; + // A single-envelope frame forces 1.5 dB resolution regardless of + // bs_amp_res, mirroring sbr_payload's own `amp_res_of`. + let amp_res = if c.e_q.len() == 1 { 0 } else { header.amp_res }; + let mut env = Vec::with_capacity(c.e_q.len()); + if coupling && channels.len() == 2 { + let (row0_src, row1_src, want_left) = if ch == 0 { + (0usize, 1usize, true) + } else { + (0usize, 1usize, false) + }; + for i in 0..c.e_q.len() { + let row0 = channels[row0_src].e_q.get(i); + let row1 = channels[row1_src].e_q.get(i); + let len = c.e_q[i].len(); + let mut r = Vec::with_capacity(len); + for b in 0..len { + let e0 = row0.and_then(|r| r.get(b)).copied().unwrap_or(0); + let e1 = row1.and_then(|r| r.get(b)).copied().unwrap_or(0); + let (left, right) = dequant_pair(e0, e1, amp_res); + r.push(if want_left { left } else { right }); + } + env.push(r); + } + } else { + for row in &c.e_q { + env.push(row.iter().map(|&v| dequant_env(v, amp_res)).collect()); + } + } + let noise = c + .q_q + .iter() + .map(|row| row.iter().map(|&v| dequant_noise(v)).collect()) + .collect(); + (env, noise) +} + /// A small deterministic PRNG for the injected noise floor -- the same /// generator shape `decode::Noise` uses, kept local so this module has no /// dependency on the core decoder's internals. diff --git a/crates/ec-aac/src/sbr_payload.rs b/crates/ec-aac/src/sbr_payload.rs index 15976a1d..8a321481 100644 --- a/crates/ec-aac/src/sbr_payload.rs +++ b/crates/ec-aac/src/sbr_payload.rs @@ -195,6 +195,11 @@ impl SbrParser { self.header.as_ref() } + /// The frequency band tables derived from the current header, if any. + pub fn tables(&self) -> Option<&BandTables> { + self.tables.as_ref() + } + fn parse_grid(&self, r: &mut BitReader) -> Result { let frame_class = r.read_bits(2)?; match frame_class { diff --git a/crates/ec-aac/tests/oracle.rs b/crates/ec-aac/tests/oracle.rs index c9eea3b3..77b01c51 100644 --- a/crates/ec-aac/tests/oracle.rs +++ b/crates/ec-aac/tests/oracle.rs @@ -286,20 +286,33 @@ fn asc_round_trips_every_sample_rate() { assert_eq!(ec_aac::sf_index_for_rate(37_000), None); } -/// A refusal is a claim: this one proves the SBR extension really is absent and -/// that the decoder says so instead of quietly claiming the doubled rate. +/// A refusal is a claim: this pins the current contract -- plain SBR (no +/// Parametric Stereo) is reconstructed and reports the extension rate; a +/// Parametric Stereo stream still falls back to its core (PS itself is a +/// separate, unimplemented tool); plain AAC-LC reports nothing missing. #[test] fn sbr_is_reported_not_silently_upsampled() { // AOT 5 (SBR), core index 6 (24 kHz), stereo, extension index 3 (48 kHz), // then AOT 2 for the core: 00101 0110 0010 0011 00010. let asc = [0x2Bu8, 0x11, 0x88]; let decoder = AacDecoder::with_config_bytes(&asc).expect("HE-AAC config parses"); - assert_eq!(decoder.sbr_support(), ec_aac::SbrSupport::CoreOnly); + assert_eq!(decoder.sbr_support(), ec_aac::SbrSupport::V1); assert_eq!( decoder.output_sample_rate(), + Some(48_000), + "a reconstructed HE-AAC stream must report the extension rate it now actually produces" + ); + + // Same layout, AOT 29 (PS) instead of 5 (SBR): 11101 0110 0010 0011 00010. + let ps_asc = [0xEBu8, 0x11, 0x88]; + let ps_decoder = AacDecoder::with_config_bytes(&ps_asc).expect("HE-AAC v2 config parses"); + assert_eq!(ps_decoder.sbr_support(), ec_aac::SbrSupport::CoreOnly); + assert_eq!( + ps_decoder.output_sample_rate(), Some(24_000), - "an HE-AAC stream must report the core rate it actually produces" + "PS is still unreconstructed: must report the core rate it actually produces" ); + let plain = AacDecoder::with_config_bytes(&ec_aac::audio_specific_config_bytes(48_000, 2)) .expect("LC config parses"); assert_eq!(plain.sbr_support(), ec_aac::SbrSupport::NotSignalled);