Wire SBR HF gen + envelope adjustment into the decode chain
Browse files at this commit5206266a2fdb25f875362558e09e690cad3fae53Parent: 49f840b- feat
- wire SBR HF gen + envelope adjustment into the decode chain
6 changed files +312 -21
- crates/ec-aac/src/decode.rs +49 -3
- crates/ec-aac/src/lib.rs +31 -14
- crates/ec-aac/src/sbr_chain.rs +161 -0
- crates/ec-aac/src/sbr_env.rs +49 -0
- crates/ec-aac/src/sbr_payload.rs +5 -0
- crates/ec-aac/tests/oracle.rs +17 -4
crates/ec-aac/src/decode.rsmodified+49 -3
| @@ -453,6 +453,7 @@ pub struct BlockDecoder { | |||
| 453 | pub states: Vec<ChannelState>, | 453 | pub states: Vec<ChannelState>, |
| 454 | noise: Noise, | 454 | noise: Noise, |
| 455 | sf_index: u8, | 455 | sf_index: u8, |
| 456 | + sbr: Option<crate::sbr_chain::SbrChain>, | ||
| 456 | } | 457 | } |
| 457 | 458 | ||
| 458 | impl BlockDecoder { | 459 | impl BlockDecoder { |
| @@ -463,6 +464,7 @@ impl BlockDecoder { | |||
| 463 | states: Vec::new(), | 464 | states: Vec::new(), |
| 464 | noise: Noise(0x1234_5678), | 465 | noise: Noise(0x1234_5678), |
| 465 | sf_index, | 466 | sf_index, |
| 467 | + sbr: None, | ||
| 466 | } | 468 | } |
| 467 | } | 469 | } |
| 468 | 470 | ||
| @@ -470,6 +472,12 @@ impl BlockDecoder { | |||
| 470 | self.sf_index = sf_index; | 472 | self.sf_index = sf_index; |
| 471 | } | 473 | } |
| 472 | 474 | ||
| 475 | + /// Enables (or disables, passing `None`) SBR reconstruction at the | ||
| 476 | + /// given extension (doubled) sample rate. | ||
| 477 | + pub fn set_sbr_rate(&mut self, rate: Option<u32>) { | ||
| 478 | + self.sbr = rate.map(crate::sbr_chain::SbrChain::new); | ||
| 479 | + } | ||
| 480 | + | ||
| 473 | fn section_data(&self, r: &mut BitReader<'_>, ics: &IcsInfo) -> Result<Vec<Vec<u8>>> { | 481 | fn section_data(&self, r: &mut BitReader<'_>, ics: &IcsInfo) -> Result<Vec<Vec<u8>>> { |
| 474 | let bits = if ics.window_sequence.is_short() { 3 } else { 5 }; | 482 | let bits = if ics.window_sequence.is_short() { 3 } else { 5 }; |
| 475 | let esc = (1u32 << bits) - 1; | 483 | let esc = (1u32 << bits) - 1; |
| @@ -681,6 +689,10 @@ impl BlockDecoder { | |||
| 681 | /// bitstream element order. | 689 | /// bitstream element order. |
| 682 | pub fn raw_data_block(&mut self, r: &mut BitReader<'_>) -> Result<Vec<Vec<f32>>> { | 690 | pub fn raw_data_block(&mut self, r: &mut BitReader<'_>) -> Result<Vec<Vec<f32>>> { |
| 683 | let mut out: Vec<Vec<f32>> = Vec::new(); | 691 | let mut out: Vec<Vec<f32>> = Vec::new(); |
| 692 | + // The element (tag, channel range, is_cpe) an immediately following | ||
| 693 | + // FIL's SBR payload would apply to, per §4.5.1: a fill_element | ||
| 694 | + // directly follows the element it decorates. | ||
| 695 | + let mut pending: Option<(u8, usize, usize, bool)> = None; | ||
| 684 | loop { | 696 | loop { |
| 685 | if r.bits_remaining() < 3 { | 697 | if r.bits_remaining() < 3 { |
| 686 | break; | 698 | break; |
| @@ -691,12 +703,15 @@ impl BlockDecoder { | |||
| 691 | // element this profile never emits and cannot be skipped | 703 | // element this profile never emits and cannot be skipped |
| 692 | // blind, so it is refused rather than silently mis-parsed. | 704 | // blind, so it is refused rather than silently mis-parsed. |
| 693 | 0 | 3 => { | 705 | 0 | 3 => { |
| 694 | - let _tag = r.read_bits(4)?; | 706 | + let tag = r.read_bits(4)? as u8; |
| 707 | + let start = out.len(); | ||
| 695 | let mut ch = [self.channel_stream(r, None)?]; | 708 | let mut ch = [self.channel_stream(r, None)?]; |
| 696 | self.finish(&mut ch, None, &mut out); | 709 | self.finish(&mut ch, None, &mut out); |
| 710 | + pending = Some((tag, start, 1, false)); | ||
| 697 | } | 711 | } |
| 698 | 1 => { | 712 | 1 => { |
| 699 | - let _tag = r.read_bits(4)?; | 713 | + let tag = r.read_bits(4)? as u8; |
| 714 | + let start = out.len(); | ||
| 700 | let common = r.read_bit()?; | 715 | let common = r.read_bit()?; |
| 701 | let (shared, mask) = if common { | 716 | let (shared, mask) = if common { |
| 702 | let info = parse_ics_info(r, self.sf_index)?; | 717 | let info = parse_ics_info(r, self.sf_index)?; |
| @@ -724,6 +739,7 @@ impl BlockDecoder { | |||
| 724 | self.channel_stream(r, shared.as_ref())?, | 739 | self.channel_stream(r, shared.as_ref())?, |
| 725 | ]; | 740 | ]; |
| 726 | self.finish(&mut pair, Some(&mask), &mut out); | 741 | self.finish(&mut pair, Some(&mask), &mut out); |
| 742 | + pending = Some((tag, start, 2, true)); | ||
| 727 | } | 743 | } |
| 728 | 2 => return Err(Error::unsupported("aac", "coupling channel element")), | 744 | 2 => return Err(Error::unsupported("aac", "coupling channel element")), |
| 729 | 4 => { | 745 | 4 => { |
| @@ -737,16 +753,46 @@ impl BlockDecoder { | |||
| 737 | r.align_to_byte(); | 753 | r.align_to_byte(); |
| 738 | } | 754 | } |
| 739 | r.skip_bits(count * 8)?; | 755 | r.skip_bits(count * 8)?; |
| 756 | + pending = None; | ||
| 740 | } | 757 | } |
| 741 | 5 => { | 758 | 5 => { |
| 742 | crate::config::skip_program_config(r)?; | 759 | crate::config::skip_program_config(r)?; |
| 760 | + pending = None; | ||
| 743 | } | 761 | } |
| 744 | 6 => { | 762 | 6 => { |
| 745 | let mut count = r.read_bits(4)? as u64; | 763 | let mut count = r.read_bits(4)? as u64; |
| 746 | if count == 15 { | 764 | if count == 15 { |
| 747 | count += r.read_bits(8)? as u64 - 1; | 765 | count += r.read_bits(8)? as u64 - 1; |
| 748 | } | 766 | } |
| 749 | - r.skip_bits(count * 8)?; | 767 | + let end_bit = r.bit_position() + count * 8; |
| 768 | + if let (Some(sbr), Some((tag, start, n, is_cpe))) = | ||
| 769 | + (self.sbr.as_mut(), pending.take()) | ||
| 770 | + { | ||
| 771 | + // extension_payload(): bs_extension_type(4), then | ||
| 772 | + // (for SBR) an optional 10-bit CRC, then | ||
| 773 | + // sbr_extension_data() itself. | ||
| 774 | + if r.bits_remaining() >= 4 { | ||
| 775 | + let ext_type = r.peek_bits(4)?; | ||
| 776 | + if ext_type == 13 || ext_type == 14 { | ||
| 777 | + r.skip_bits(4)?; | ||
| 778 | + if ext_type == 14 && r.bits_remaining() >= 10 { | ||
| 779 | + r.skip_bits(10)?; // bs_sbr_crc_bits | ||
| 780 | + } | ||
| 781 | + if let Some(data) = sbr.parse(r, tag, is_cpe) { | ||
| 782 | + sbr.apply(tag, &data, &mut out[start..start + n]); | ||
| 783 | + } | ||
| 784 | + } | ||
| 785 | + } | ||
| 786 | + } | ||
| 787 | + // Resync to the FIL's declared byte boundary regardless | ||
| 788 | + // of how many bits SBR parsing above actually consumed: | ||
| 789 | + // a parse error or trailing padding must never desync | ||
| 790 | + // the elements that follow. | ||
| 791 | + let now = r.bit_position(); | ||
| 792 | + if now < end_bit { | ||
| 793 | + r.skip_bits(end_bit - now)?; | ||
| 794 | + } | ||
| 795 | + pending = None; | ||
| 750 | } | 796 | } |
| 751 | _ => break, | 797 | _ => break, |
| 752 | } | 798 | } |
crates/ec-aac/src/lib.rsmodified+31 -14
| @@ -16,9 +16,11 @@ | |||
| 16 | //! | 16 | //! |
| 17 | //! AAC-LC (audio object type 2) is complete: all four window sequences, both | 17 | //! AAC-LC (audio object type 2) is complete: all four window sequences, both |
| 18 | //! window shapes, TNS, pulse data, M/S and intensity stereo, PNS, and SCE, CPE, | 18 | //! window shapes, TNS, pulse data, M/S and intensity stereo, PNS, and SCE, CPE, |
| 19 | -//! LFE, DSE, PCE and FIL elements. HE-AAC's SBR and Parametric Stereo are | 19 | +//! LFE, DSE, PCE and FIL elements. HE-AAC v1 (SBR) is reconstructed: the core |
| 20 | -//! **not** implemented; a stream that signals them decodes to its AAC-LC core, | 20 | +//! decodes, its low bands feed the SBR QMF/HF/envelope chain, and the output |
| 21 | -//! at the core sample rate, and says so through [`AacDecoder::sbr_support`] and | 21 | +//! is at the extension rate. Parametric Stereo is **not** implemented; a |
| 22 | +//! stream that signals it decodes to its AAC-LC core, at the core sample | ||
| 23 | +//! rate, and says so through [`AacDecoder::sbr_support`] and | ||
| 22 | //! [`AacDecoder::output_sample_rate`] rather than silently claiming the | 24 | //! [`AacDecoder::output_sample_rate`] rather than silently claiming the |
| 23 | //! extension rate. See `sbr_is_reported_not_silently_upsampled` in the tests. | 25 | //! extension rate. See `sbr_is_reported_not_silently_upsampled` in the tests. |
| 24 | 26 | ||
| @@ -29,6 +31,7 @@ mod decode; | |||
| 29 | mod encode; | 31 | mod encode; |
| 30 | mod huffman; | 32 | mod huffman; |
| 31 | mod sbr_bands; | 33 | mod sbr_bands; |
| 34 | +mod sbr_chain; | ||
| 32 | mod sbr_env; | 35 | mod sbr_env; |
| 33 | mod sbr_hf; | 36 | mod sbr_hf; |
| 34 | mod sbr_payload; | 37 | mod sbr_payload; |
| @@ -55,8 +58,12 @@ use ec_core::BitReader; | |||
| 55 | pub enum SbrSupport { | 58 | pub enum SbrSupport { |
| 56 | /// The stream is plain AAC-LC: nothing is missing. | 59 | /// The stream is plain AAC-LC: nothing is missing. |
| 57 | NotSignalled, | 60 | NotSignalled, |
| 58 | - /// SBR (and possibly PS) is signalled and is **not** reconstructed. The | 61 | + /// SBR is signalled and **is** reconstructed: the decoded audio spans |
| 59 | - /// AAC-LC core decodes, at the core rate, half the signalled bandwidth. | 62 | + /// the full extension bandwidth at the extension sample rate. |
| 63 | + V1, | ||
| 64 | + /// SBR is signalled but not reconstructed (Parametric Stereo streams: | ||
| 65 | + /// PS itself is still unimplemented). The AAC-LC core decodes, at the | ||
| 66 | + /// core rate, half the signalled bandwidth. | ||
| 60 | CoreOnly, | 67 | CoreOnly, |
| 61 | } | 68 | } |
| 62 | 69 | ||
| @@ -121,6 +128,13 @@ impl AacDecoder { | |||
| 121 | d.block.set_sf_index(cfg.sf_index); | 128 | d.block.set_sf_index(cfg.sf_index); |
| 122 | d.sample_rate = cfg.sample_rate; | 129 | d.sample_rate = cfg.sample_rate; |
| 123 | d.channels = cfg.channels; | 130 | d.channels = cfg.channels; |
| 131 | + // PS is not reconstructed; SBR is. Both still need the core | ||
| 132 | + // decoded first, but only a plain-SBR (non-PS) stream gets the | ||
| 133 | + // extension-rate QMF chain wired in. | ||
| 134 | + if cfg.sbr_present && !cfg.ps_present { | ||
| 135 | + let rate = cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2); | ||
| 136 | + d.block.set_sbr_rate(Some(rate)); | ||
| 137 | + } | ||
| 124 | d.config = Some(cfg); | 138 | d.config = Some(cfg); |
| 125 | d | 139 | d |
| 126 | } | 140 | } |
| @@ -139,18 +153,21 @@ impl AacDecoder { | |||
| 139 | /// Whether the stream asked for SBR, and what became of it. | 153 | /// Whether the stream asked for SBR, and what became of it. |
| 140 | pub fn sbr_support(&self) -> SbrSupport { | 154 | pub fn sbr_support(&self) -> SbrSupport { |
| 141 | match &self.config { | 155 | match &self.config { |
| 142 | - Some(c) if c.sbr_present || c.ps_present => SbrSupport::CoreOnly, | 156 | + Some(c) if c.ps_present => SbrSupport::CoreOnly, |
| 157 | + Some(c) if c.sbr_present => SbrSupport::V1, | ||
| 143 | _ => SbrSupport::NotSignalled, | 158 | _ => SbrSupport::NotSignalled, |
| 144 | } | 159 | } |
| 145 | } | 160 | } |
| 146 | 161 | ||
| 147 | - /// The rate the samples this decoder hands back are actually at. | 162 | + /// The rate the samples this decoder hands back are actually at: the |
| 148 | - /// | 163 | + /// extension rate for a reconstructed (V1) HE-AAC stream, the core |
| 149 | - /// For an HE-AAC stream this is the **core** rate, not the doubled rate the | 164 | + /// rate for plain AAC-LC or an unreconstructed (PS) stream -- claiming |
| 150 | - /// configuration advertises: the SBR extension is not reconstructed, so | 165 | + /// bandwidth that was not actually rebuilt would be a lie. |
| 151 | - /// claiming its rate would be claiming bandwidth that is not there. | ||
| 152 | pub fn output_sample_rate(&self) -> Option<u32> { | 166 | pub fn output_sample_rate(&self) -> Option<u32> { |
| 153 | - self.config.as_ref().map(|c| c.sample_rate) | 167 | + self.config.as_ref().map(|c| match self.sbr_support() { |
| 168 | + SbrSupport::V1 => c.extension_sample_rate.unwrap_or(c.sample_rate * 2), | ||
| 169 | + _ => c.sample_rate, | ||
| 170 | + }) | ||
| 154 | } | 171 | } |
| 155 | 172 | ||
| 156 | /// Decodes one packet: a raw `raw_data_block`, or one or more ADTS frames. | 173 | /// Decodes one packet: a raw `raw_data_block`, or one or more ADTS frames. |
| @@ -187,7 +204,7 @@ impl AacDecoder { | |||
| 187 | let channels = planes.len(); | 204 | let channels = planes.len(); |
| 188 | if channels == 0 { | 205 | if channels == 0 { |
| 189 | return Ok(DecodedAudio { | 206 | return Ok(DecodedAudio { |
| 190 | - sample_rate: self.sample_rate, | 207 | + sample_rate: self.output_sample_rate().unwrap_or(self.sample_rate), |
| 191 | channels: self.channels, | 208 | channels: self.channels, |
| 192 | samples: Vec::new(), | 209 | samples: Vec::new(), |
| 193 | pts, | 210 | pts, |
| @@ -206,7 +223,7 @@ impl AacDecoder { | |||
| 206 | } | 223 | } |
| 207 | } | 224 | } |
| 208 | Ok(DecodedAudio { | 225 | Ok(DecodedAudio { |
| 209 | - sample_rate: self.sample_rate, | 226 | + sample_rate: self.output_sample_rate().unwrap_or(self.sample_rate), |
| 210 | channels: channels as u16, | 227 | channels: channels as u16, |
| 211 | samples, | 228 | samples, |
| 212 | pts, | 229 | pts, |
crates/ec-aac/src/sbr_chain.rsadded+161 -0
| @@ -0,0 +1,161 @@ | |||
| 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 | + | ||
| 7 | +use crate::sbr_env::{self, NoiseGen}; | ||
| 8 | +use crate::sbr_hf::{self, ChirpState, HfHistory}; | ||
| 9 | +use crate::sbr_payload::{SbrChannel, SbrData, SbrParser}; | ||
| 10 | +use crate::sbr_qmf::{ANALYSIS_BANDS, Analysis, SYNTHESIS_BANDS, Synthesis}; | ||
| 11 | +use ec_core::BitReader; | ||
| 12 | +use ec_dsp::Complex; | ||
| 13 | +use std::collections::HashMap; | ||
| 14 | + | ||
| 15 | +/// Envelope-grid "time slots" (§4.6.18.4, `numTimeSlots = 16` for a | ||
| 16 | +/// 1024-sample core frame) are half as fine as the QMF slots SBR actually | ||
| 17 | +/// runs at (32 per frame): `RATE = 2` converts one to the other. | ||
| 18 | +const RATE: i64 = 2; | ||
| 19 | + | ||
| 20 | +/// Per-channel DSP state an SBR element's reconstruction carries across | ||
| 21 | +/// frames: the QMF filterbank pair, the HF generator's LPC history and | ||
| 22 | +/// chirp factors, and the noise-floor generator. | ||
| 23 | +struct ChannelState { | ||
| 24 | + analysis: Analysis, | ||
| 25 | + synthesis: Synthesis, | ||
| 26 | + hf_hist: HfHistory, | ||
| 27 | + chirp: ChirpState, | ||
| 28 | + noise: NoiseGen, | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +impl ChannelState { | ||
| 32 | + fn new(n_q: usize, seed: u32) -> ChannelState { | ||
| 33 | + ChannelState { | ||
| 34 | + analysis: Analysis::new(), | ||
| 35 | + synthesis: Synthesis::new(), | ||
| 36 | + hf_hist: HfHistory::new(ANALYSIS_BANDS), | ||
| 37 | + chirp: ChirpState::new(n_q.max(1)), | ||
| 38 | + noise: NoiseGen::new(seed), | ||
| 39 | + } | ||
| 40 | + } | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// One SBR element's (SCE or CPE) persistent state. | ||
| 44 | +struct Element { | ||
| 45 | + parser: SbrParser, | ||
| 46 | + channels: Vec<ChannelState>, | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// Every configured SBR element in a stream, keyed by | ||
| 50 | +/// `element_instance_tag` (assumed stable frame to frame, as every | ||
| 51 | +/// encoder in practice emits it). | ||
| 52 | +pub struct SbrChain { | ||
| 53 | + rate: u32, | ||
| 54 | + elements: HashMap<u8, Element>, | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +impl SbrChain { | ||
| 58 | + pub fn new(rate: u32) -> SbrChain { | ||
| 59 | + SbrChain { | ||
| 60 | + rate, | ||
| 61 | + elements: HashMap::new(), | ||
| 62 | + } | ||
| 63 | + } | ||
| 64 | + | ||
| 65 | + /// Parses one FIL element's `sbr_extension_data` (the reader | ||
| 66 | + /// positioned right past `bs_extension_type`) for element `tag`. | ||
| 67 | + pub fn parse(&mut self, r: &mut BitReader<'_>, tag: u8, is_cpe: bool) -> Option<SbrData> { | ||
| 68 | + let elem = self.elements.entry(tag).or_insert_with(|| Element { | ||
| 69 | + parser: SbrParser::new(self.rate), | ||
| 70 | + channels: Vec::new(), | ||
| 71 | + }); | ||
| 72 | + let data = elem.parser.parse(r, is_cpe).ok()?; | ||
| 73 | + let n_q = elem.parser.tables().map(|t| t.n_q).unwrap_or(1); | ||
| 74 | + while elem.channels.len() < data.channels.len() { | ||
| 75 | + let seed = 0x1234_5678u32.wrapping_add(elem.channels.len() as u32 * 0x9e37_79b9); | ||
| 76 | + elem.channels.push(ChannelState::new(n_q, seed)); | ||
| 77 | + } | ||
| 78 | + Some(data) | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + /// Runs the chain over `planes` (element `tag`'s already-decoded core | ||
| 82 | + /// PCM, one plane per channel), replacing each in place with its | ||
| 83 | + /// SBR-reconstructed, double-rate PCM. A malformed/missing state is a | ||
| 84 | + /// silent no-op: `planes` is left at its core content. | ||
| 85 | + pub fn apply(&mut self, tag: u8, data: &SbrData, planes: &mut [Vec<f32>]) { | ||
| 86 | + let Some(elem) = self.elements.get_mut(&tag) else { | ||
| 87 | + return; | ||
| 88 | + }; | ||
| 89 | + let Some(tables) = elem.parser.tables().cloned() else { | ||
| 90 | + return; | ||
| 91 | + }; | ||
| 92 | + let Some(header) = elem.parser.header().cloned() else { | ||
| 93 | + return; | ||
| 94 | + }; | ||
| 95 | + let coupling = data.coupling; | ||
| 96 | + for (ch, plane) in planes.iter_mut().enumerate() { | ||
| 97 | + if ch >= data.channels.len() || ch >= elem.channels.len() { | ||
| 98 | + continue; | ||
| 99 | + } | ||
| 100 | + let num_slots = plane.len() / ANALYSIS_BANDS; | ||
| 101 | + if num_slots == 0 { | ||
| 102 | + continue; | ||
| 103 | + } | ||
| 104 | + let state = &mut elem.channels[ch]; | ||
| 105 | + let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS]; | ||
| 106 | + let mut raw = Vec::with_capacity(num_slots); | ||
| 107 | + for slot in 0..num_slots { | ||
| 108 | + let mut chunk = [0f32; ANALYSIS_BANDS]; | ||
| 109 | + chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); | ||
| 110 | + let sub = state.analysis.process_slot(&chunk); | ||
| 111 | + for b in 0..ANALYSIS_BANDS { | ||
| 112 | + low_cur[b][slot] = sub[b]; | ||
| 113 | + } | ||
| 114 | + raw.push(sub); | ||
| 115 | + } | ||
| 116 | + | ||
| 117 | + let sbr_ch = &data.channels[ch]; | ||
| 118 | + let mut hf = sbr_hf::generate( | ||
| 119 | + &low_cur, | ||
| 120 | + &tables, | ||
| 121 | + &sbr_ch.invf_mode, | ||
| 122 | + &mut state.chirp, | ||
| 123 | + &mut state.hf_hist, | ||
| 124 | + ); | ||
| 125 | + let (env_energy, noise_energy) = | ||
| 126 | + sbr_env::dequantize_frame(&header, &data.channels, ch, coupling); | ||
| 127 | + // sbr_env::adjust works in QMF-slot units; the parsed borders | ||
| 128 | + // are in the coarser envelope-time-slot units (see RATE above). | ||
| 129 | + let scaled = SbrChannel { | ||
| 130 | + t_env: sbr_ch.t_env.iter().map(|&t| t * RATE).collect(), | ||
| 131 | + t_noise: sbr_ch.t_noise.iter().map(|&t| t * RATE).collect(), | ||
| 132 | + ..sbr_ch.clone() | ||
| 133 | + }; | ||
| 134 | + sbr_env::adjust( | ||
| 135 | + &mut hf, | ||
| 136 | + &tables, | ||
| 137 | + &header, | ||
| 138 | + &scaled, | ||
| 139 | + &env_energy, | ||
| 140 | + &noise_energy, | ||
| 141 | + &mut state.noise, | ||
| 142 | + ); | ||
| 143 | + | ||
| 144 | + let kx = (tables.kx as usize).min(ANALYSIS_BANDS); | ||
| 145 | + let k2 = (tables.k2 as usize).min(SYNTHESIS_BANDS); | ||
| 146 | + let mut out = Vec::with_capacity(num_slots * SYNTHESIS_BANDS); | ||
| 147 | + for slot in 0..num_slots { | ||
| 148 | + let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; | ||
| 149 | + v[0..kx].copy_from_slice(&raw[slot][0..kx]); | ||
| 150 | + for b in kx..k2 { | ||
| 151 | + if b - kx < hf.len() { | ||
| 152 | + v[b] = hf[b - kx][slot]; | ||
| 153 | + } | ||
| 154 | + } | ||
| 155 | + let pcm = state.synthesis.process_slot(&v); | ||
| 156 | + out.extend_from_slice(&pcm); | ||
| 157 | + } | ||
| 158 | + *plane = out; | ||
| 159 | + } | ||
| 160 | + } | ||
| 161 | +} | ||
crates/ec-aac/src/sbr_env.rsmodified+49 -0
| @@ -63,6 +63,55 @@ pub fn dequant_pair(e0_raw: i32, e1_raw: i32, amp_res: u8) -> (f64, f64) { | |||
| 63 | (left, right) | 63 | (left, right) |
| 64 | } | 64 | } |
| 65 | 65 | ||
| 66 | +/// Dequantizes one channel's envelopes and noise floors for one frame, | ||
| 67 | +/// de-mixing through [`dequant_pair`] when `coupling` makes `channels[1]` | ||
| 68 | +/// a balance channel against `channels[0]`. Noise floors dequantize | ||
| 69 | +/// independently per channel regardless of coupling (corner-cut: the | ||
| 70 | +/// balance codebook's noise ratio convention is unverified against a real | ||
| 71 | +/// coupled file, same ceiling as the envelope one above). | ||
| 72 | +pub fn dequantize_frame( | ||
| 73 | + header: &SbrHeader, | ||
| 74 | + channels: &[SbrChannel], | ||
| 75 | + ch: usize, | ||
| 76 | + coupling: bool, | ||
| 77 | +) -> (Vec<Vec<f64>>, Vec<Vec<f64>>) { | ||
| 78 | + let c = &channels[ch]; | ||
| 79 | + // A single-envelope frame forces 1.5 dB resolution regardless of | ||
| 80 | + // bs_amp_res, mirroring sbr_payload's own `amp_res_of`. | ||
| 81 | + let amp_res = if c.e_q.len() == 1 { 0 } else { header.amp_res }; | ||
| 82 | + let mut env = Vec::with_capacity(c.e_q.len()); | ||
| 83 | + if coupling && channels.len() == 2 { | ||
| 84 | + let (row0_src, row1_src, want_left) = if ch == 0 { | ||
| 85 | + (0usize, 1usize, true) | ||
| 86 | + } else { | ||
| 87 | + (0usize, 1usize, false) | ||
| 88 | + }; | ||
| 89 | + for i in 0..c.e_q.len() { | ||
| 90 | + let row0 = channels[row0_src].e_q.get(i); | ||
| 91 | + let row1 = channels[row1_src].e_q.get(i); | ||
| 92 | + let len = c.e_q[i].len(); | ||
| 93 | + let mut r = Vec::with_capacity(len); | ||
| 94 | + for b in 0..len { | ||
| 95 | + let e0 = row0.and_then(|r| r.get(b)).copied().unwrap_or(0); | ||
| 96 | + let e1 = row1.and_then(|r| r.get(b)).copied().unwrap_or(0); | ||
| 97 | + let (left, right) = dequant_pair(e0, e1, amp_res); | ||
| 98 | + r.push(if want_left { left } else { right }); | ||
| 99 | + } | ||
| 100 | + env.push(r); | ||
| 101 | + } | ||
| 102 | + } else { | ||
| 103 | + for row in &c.e_q { | ||
| 104 | + env.push(row.iter().map(|&v| dequant_env(v, amp_res)).collect()); | ||
| 105 | + } | ||
| 106 | + } | ||
| 107 | + let noise = c | ||
| 108 | + .q_q | ||
| 109 | + .iter() | ||
| 110 | + .map(|row| row.iter().map(|&v| dequant_noise(v)).collect()) | ||
| 111 | + .collect(); | ||
| 112 | + (env, noise) | ||
| 113 | +} | ||
| 114 | + | ||
| 66 | /// A small deterministic PRNG for the injected noise floor -- the same | 115 | /// A small deterministic PRNG for the injected noise floor -- the same |
| 67 | /// generator shape `decode::Noise` uses, kept local so this module has no | 116 | /// generator shape `decode::Noise` uses, kept local so this module has no |
| 68 | /// dependency on the core decoder's internals. | 117 | /// dependency on the core decoder's internals. |
crates/ec-aac/src/sbr_payload.rsmodified+5 -0
| @@ -195,6 +195,11 @@ impl SbrParser { | |||
| 195 | self.header.as_ref() | 195 | self.header.as_ref() |
| 196 | } | 196 | } |
| 197 | 197 | ||
| 198 | + /// The frequency band tables derived from the current header, if any. | ||
| 199 | + pub fn tables(&self) -> Option<&BandTables> { | ||
| 200 | + self.tables.as_ref() | ||
| 201 | + } | ||
| 202 | + | ||
| 198 | fn parse_grid(&self, r: &mut BitReader) -> Result<Grid> { | 203 | fn parse_grid(&self, r: &mut BitReader) -> Result<Grid> { |
| 199 | let frame_class = r.read_bits(2)?; | 204 | let frame_class = r.read_bits(2)?; |
| 200 | match frame_class { | 205 | match frame_class { |
crates/ec-aac/tests/oracle.rsmodified+17 -4
| @@ -286,20 +286,33 @@ fn asc_round_trips_every_sample_rate() { | |||
| 286 | assert_eq!(ec_aac::sf_index_for_rate(37_000), None); | 286 | assert_eq!(ec_aac::sf_index_for_rate(37_000), None); |
| 287 | } | 287 | } |
| 288 | 288 | ||
| 289 | -/// A refusal is a claim: this one proves the SBR extension really is absent and | 289 | +/// A refusal is a claim: this pins the current contract -- plain SBR (no |
| 290 | -/// that the decoder says so instead of quietly claiming the doubled rate. | 290 | +/// Parametric Stereo) is reconstructed and reports the extension rate; a |
| 291 | +/// Parametric Stereo stream still falls back to its core (PS itself is a | ||
| 292 | +/// separate, unimplemented tool); plain AAC-LC reports nothing missing. | ||
| 291 | #[test] | 293 | #[test] |
| 292 | fn sbr_is_reported_not_silently_upsampled() { | 294 | fn sbr_is_reported_not_silently_upsampled() { |
| 293 | // AOT 5 (SBR), core index 6 (24 kHz), stereo, extension index 3 (48 kHz), | 295 | // AOT 5 (SBR), core index 6 (24 kHz), stereo, extension index 3 (48 kHz), |
| 294 | // then AOT 2 for the core: 00101 0110 0010 0011 00010. | 296 | // then AOT 2 for the core: 00101 0110 0010 0011 00010. |
| 295 | let asc = [0x2Bu8, 0x11, 0x88]; | 297 | let asc = [0x2Bu8, 0x11, 0x88]; |
| 296 | let decoder = AacDecoder::with_config_bytes(&asc).expect("HE-AAC config parses"); | 298 | let decoder = AacDecoder::with_config_bytes(&asc).expect("HE-AAC config parses"); |
| 297 | - assert_eq!(decoder.sbr_support(), ec_aac::SbrSupport::CoreOnly); | 299 | + assert_eq!(decoder.sbr_support(), ec_aac::SbrSupport::V1); |
| 298 | assert_eq!( | 300 | assert_eq!( |
| 299 | decoder.output_sample_rate(), | 301 | decoder.output_sample_rate(), |
| 302 | + Some(48_000), | ||
| 303 | + "a reconstructed HE-AAC stream must report the extension rate it now actually produces" | ||
| 304 | + ); | ||
| 305 | + | ||
| 306 | + // Same layout, AOT 29 (PS) instead of 5 (SBR): 11101 0110 0010 0011 00010. | ||
| 307 | + let ps_asc = [0xEBu8, 0x11, 0x88]; | ||
| 308 | + let ps_decoder = AacDecoder::with_config_bytes(&ps_asc).expect("HE-AAC v2 config parses"); | ||
| 309 | + assert_eq!(ps_decoder.sbr_support(), ec_aac::SbrSupport::CoreOnly); | ||
| 310 | + assert_eq!( | ||
| 311 | + ps_decoder.output_sample_rate(), | ||
| 300 | Some(24_000), | 312 | Some(24_000), |
| 301 | - "an HE-AAC stream must report the core rate it actually produces" | 313 | + "PS is still unreconstructed: must report the core rate it actually produces" |
| 302 | ); | 314 | ); |
| 315 | + | ||
| 303 | let plain = AacDecoder::with_config_bytes(&ec_aac::audio_specific_config_bytes(48_000, 2)) | 316 | let plain = AacDecoder::with_config_bytes(&ec_aac::audio_specific_config_bytes(48_000, 2)) |
| 304 | .expect("LC config parses"); | 317 | .expect("LC config parses"); |
| 305 | assert_eq!(plain.sbr_support(), ec_aac::SbrSupport::NotSignalled); | 318 | assert_eq!(plain.sbr_support(), ec_aac::SbrSupport::NotSignalled); |