diff --git a/crates/ec-aac/Cargo.toml b/crates/ec-aac/Cargo.toml new file mode 100644 index 00000000..34478983 --- /dev/null +++ b/crates/ec-aac/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "ec-aac" +description = "AAC-LC decoder and encoder: ADTS and AudioSpecificConfig framing, mono through 7.1." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core = { workspace = true } +ec-dsp = { workspace = true } diff --git a/crates/ec-aac/src/config.rs b/crates/ec-aac/src/config.rs new file mode 100644 index 00000000..4b906f19 --- /dev/null +++ b/crates/ec-aac/src/config.rs @@ -0,0 +1,310 @@ +//! AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2) and ADTS (§1.A.2) framing. + +use ec_core::{BitReader, BitWriter, Error, Result}; + +use crate::tables::SAMPLE_RATES; + +/// AAC Low Complexity. +pub const AOT_AAC_LC: u8 = 2; +/// Spectral Band Replication (HE-AAC v1). +pub const AOT_SBR: u8 = 5; +/// Parametric Stereo (HE-AAC v2). +pub const AOT_PS: u8 = 29; + +/// A rate's `samplingFrequencyIndex`, or `None` when AAC cannot carry it. +pub fn sf_index_for_rate(rate: u32) -> Option { + SAMPLE_RATES + .iter() + .position(|&r| r == rate) + .map(|i| i as u8) +} + +/// The rate a `samplingFrequencyIndex` names; 0 for the escape and reserved +/// values. +pub fn sample_rate_for_index(index: u8) -> u32 { + SAMPLE_RATES.get(usize::from(index)).copied().unwrap_or(0) +} + +/// A decoded AudioSpecificConfig. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AudioSpecificConfig { + /// Audio object type; 2 is AAC-LC, the only one this decoder codes. + pub object_type: u8, + pub sample_rate: u32, + pub sf_index: u8, + /// Channels the configuration implies, PCE included. + pub channels: u16, + /// `channelConfiguration`; 0 means the layout came from a PCE. + pub channel_config: u8, + /// True when the config signals SBR, i.e. HE-AAC. + pub sbr_present: bool, + /// True when the config signals Parametric Stereo, i.e. HE-AAC v2. + pub ps_present: bool, + /// The rate SBR would output at, when signalled. + pub extension_sample_rate: Option, +} + +/// Channels implied by `channelConfiguration` (ISO 14496-3 tbl 1.19). +pub fn channels_for_config(config: u8) -> u16 { + match config { + 1..=6 => u16::from(config), + 7 => 8, + _ => 0, + } +} + +fn object_type(r: &mut BitReader<'_>) -> Result { + let t = r.read_bits(5)? as u8; + if t == 31 { + return Ok(32 + r.read_bits(6)? as u8); + } + Ok(t) +} + +fn sampling_frequency(r: &mut BitReader<'_>) -> Result<(u8, u32)> { + let index = r.read_bits(4)? as u8; + if index == 15 { + return Ok((index, r.read_bits(24)?)); + } + Ok((index, sample_rate_for_index(index))) +} + +/// Parses an AudioSpecificConfig, the `esds`/`CodecPrivate` payload. +pub fn parse_audio_specific_config(data: &[u8]) -> Result { + let mut r = BitReader::new(data); + let mut object = object_type(&mut r)?; + let (mut sf_index, mut rate) = sampling_frequency(&mut r)?; + let mut channel_config = r.read_bits(4)? as u8; + let mut sbr = false; + let mut ps = false; + let mut ext_rate = None; + if object == AOT_SBR || object == AOT_PS { + sbr = true; + ps = object == AOT_PS; + let (_, er) = sampling_frequency(&mut r)?; + ext_rate = Some(er); + object = object_type(&mut r)?; + if object == 22 { + let _ext_channel_config = r.read_bits(4)?; + } + } else if object == AOT_AAC_LC { + // GASpecificConfig; the fields matter only for the PCE that may follow. + let _frame_length_flag = r.read_bit()?; + if r.read_bit()? { + let _core_coder_delay = r.read_bits(14)?; + } + let _extension_flag = r.read_bit()?; + if channel_config == 0 { + let pce = parse_program_config(&mut r)?; + channel_config = 0; + sf_index = pce.sf_index; + rate = sample_rate_for_index(pce.sf_index); + return Ok(AudioSpecificConfig { + object_type: object, + sample_rate: rate, + sf_index, + channels: pce.channels, + channel_config, + sbr_present: false, + ps_present: false, + extension_sample_rate: None, + }); + } + // A backward-compatible SBR signal rides in a sync extension at the end. + if r.bits_remaining() >= 16 && r.read_bits(11)? == 0x2B7 { + let ext = object_type(&mut r)?; + if ext == AOT_SBR && r.read_bit()? { + sbr = true; + let (_, er) = sampling_frequency(&mut r)?; + ext_rate = Some(er); + } + } + } + if rate == 0 { + return Err(Error::corrupt("aac: reserved samplingFrequencyIndex")); + } + Ok(AudioSpecificConfig { + object_type: object, + sample_rate: rate, + sf_index, + channels: channels_for_config(channel_config), + channel_config, + sbr_present: sbr, + ps_present: ps, + extension_sample_rate: ext_rate, + }) +} + +/// Serialises the two-byte (plus SBR extension) AudioSpecificConfig. +pub fn write_audio_specific_config(cfg: &AudioSpecificConfig) -> Vec { + let mut w = BitWriter::new(); + w.write_bits(u32::from(cfg.object_type), 5); + w.write_bits(u32::from(cfg.sf_index), 4); + w.write_bits(u32::from(cfg.channel_config), 4); + w.write_bit(false); // frameLengthFlag: 1024 samples + w.write_bit(false); // dependsOnCoreCoder + w.write_bit(false); // extensionFlag + w.align_to_byte(); + w.into_bytes() +} + +/// The AudioSpecificConfig an AAC-LC track of this shape needs. +pub fn audio_specific_config_bytes(sample_rate: u32, channels: u16) -> Vec { + let sf_index = sf_index_for_rate(sample_rate).unwrap_or(3); + write_audio_specific_config(&AudioSpecificConfig { + object_type: AOT_AAC_LC, + sample_rate, + sf_index, + channels, + channel_config: config_for_channels(channels), + sbr_present: false, + ps_present: false, + extension_sample_rate: None, + }) +} + +/// The `channelConfiguration` that carries this many channels. +pub fn config_for_channels(channels: u16) -> u8 { + match channels { + 1..=6 => channels as u8, + 8 => 7, + _ => 0, + } +} + +/// What a program_config_element says about the stream. +#[derive(Clone, Debug, Default)] +pub struct ProgramConfig { + pub sf_index: u8, + pub channels: u16, +} + +/// Parses a program_config_element far enough to count its channels. +pub fn parse_program_config(r: &mut BitReader<'_>) -> Result { + let _tag = r.read_bits(4)?; + let _object_type = r.read_bits(2)?; + let sf_index = r.read_bits(4)? as u8; + let front = r.read_bits(4)? as usize; + let side = r.read_bits(4)? as usize; + let back = r.read_bits(4)? as usize; + let lfe = r.read_bits(2)? as usize; + let assoc = r.read_bits(3)? as usize; + let cc = r.read_bits(4)? as usize; + if r.read_bit()? { + let _mono_mixdown = r.read_bits(4)?; + } + if r.read_bit()? { + let _stereo_mixdown = r.read_bits(4)?; + } + if r.read_bit()? { + let _matrix_mixdown = r.read_bits(3)?; + } + let mut channels = 0u16; + for _ in 0..front + side + back { + channels += if r.read_bit()? { 2 } else { 1 }; + let _tag = r.read_bits(4)?; + } + channels += lfe as u16; + for _ in 0..lfe + assoc { + let _tag = r.read_bits(4)?; + } + for _ in 0..cc { + let _is_ind_sw = r.read_bit()?; + let _tag = r.read_bits(4)?; + } + r.align_to_byte(); + let comment = r.read_bits(8)? as u64; + r.skip_bits(comment * 8)?; + Ok(ProgramConfig { sf_index, channels }) +} + +pub(crate) fn skip_program_config(r: &mut BitReader<'_>) -> Result<()> { + parse_program_config(r).map(|_| ()) +} + +/// An ADTS frame header (§1.A.2.2). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AdtsHeader { + pub object_type: u8, + pub sf_index: u8, + pub sample_rate: u32, + pub channels: u16, + pub channel_config: u8, + /// Whole frame length in bytes, header included. + pub frame_length: usize, + /// Header length in bytes: 7, or 9 when the CRC is present. + pub header_len: usize, + pub raw_blocks: u8, +} + +/// True when `data` opens on an ADTS syncword. +pub fn is_adts(data: &[u8]) -> bool { + data.len() >= 2 && data[0] == 0xFF && data[1] & 0xF6 == 0xF0 +} + +/// Parses one ADTS header. +pub fn parse_adts(data: &[u8]) -> Result { + if data.len() < 7 { + return Err(Error::NeedMore); + } + let mut r = BitReader::new(data); + if r.read_bits(12)? != 0xFFF { + return Err(Error::corrupt("aac: no ADTS syncword")); + } + let _id = r.read_bit()?; + let layer = r.read_bits(2)?; + if layer != 0 { + return Err(Error::corrupt("aac: ADTS layer is not zero")); + } + let protection_absent = r.read_bit()?; + let object_type = r.read_bits(2)? as u8 + 1; + let sf_index = r.read_bits(4)? as u8; + let _private = r.read_bit()?; + let channel_config = r.read_bits(3)? as u8; + let _original = r.read_bit()?; + let _home = r.read_bit()?; + let _copyright_id = r.read_bit()?; + let _copyright_start = r.read_bit()?; + let frame_length = r.read_bits(13)? as usize; + let _fullness = r.read_bits(11)?; + let raw_blocks = r.read_bits(2)? as u8 + 1; + let header_len = if protection_absent { 7 } else { 9 }; + if frame_length < header_len { + return Err(Error::corrupt("aac: ADTS frame shorter than its header")); + } + let sample_rate = sample_rate_for_index(sf_index); + if sample_rate == 0 { + return Err(Error::corrupt("aac: reserved samplingFrequencyIndex")); + } + Ok(AdtsHeader { + object_type, + sf_index, + sample_rate, + channels: channels_for_config(channel_config), + channel_config, + frame_length, + header_len, + raw_blocks, + }) +} + +/// Serialises a 7-byte ADTS header (no CRC). +pub fn write_adts_header(header: &AdtsHeader) -> Vec { + let mut w = BitWriter::with_capacity(7); + w.write_bits(0xFFF, 12); + w.write_bit(false); // MPEG-4 + w.write_bits(0, 2); // layer + w.write_bit(true); // protection absent + w.write_bits(u32::from(header.object_type.saturating_sub(1)), 2); + w.write_bits(u32::from(header.sf_index), 4); + w.write_bit(false); // private + w.write_bits(u32::from(header.channel_config), 3); + w.write_bit(false); // original + w.write_bit(false); // home + w.write_bit(false); // copyright id + w.write_bit(false); // copyright start + w.write_bits(header.frame_length as u32, 13); + w.write_bits(0x7FF, 11); // buffer fullness: variable rate + w.write_bits(u32::from(header.raw_blocks.saturating_sub(1)), 2); + w.into_bytes() +} diff --git a/crates/ec-aac/src/decode.rs b/crates/ec-aac/src/decode.rs new file mode 100644 index 00000000..3deeccef --- /dev/null +++ b/crates/ec-aac/src/decode.rs @@ -0,0 +1,951 @@ +//! `raw_data_block` decoding: ISO/IEC 14496-3 §4.4.2 syntax, §4.6 tools. +//! +//! Band, group and window indices are the domain's own coordinates and address +//! several parallel arrays at once, so the loops here are written over indices +//! rather than iterators. +#![allow(clippy::needless_range_loop)] + +use ec_core::{BitReader, Error, Result}; +use ec_dsp::{Mdct, Window}; + +use crate::huffman::Books; +use crate::tables::{CODEBOOKS, SWB_LONG, SWB_SHORT, TNS_MAX_BANDS_LONG, TNS_MAX_BANDS_SHORT}; + +/// Samples one AAC frame carries per channel. +pub const FRAME_LEN: usize = 1024; +/// Samples one short block carries. +pub const SHORT_LEN: usize = 128; +/// The `sect_cb` value for a band coded as all zeroes. +const ZERO_HCB: u8 = 0; +/// The `sect_cb` value for perceptual noise substitution. +const NOISE_HCB: u8 = 13; +/// Out-of-phase intensity stereo. +const INTENSITY_HCB2: u8 = 14; +/// In-phase intensity stereo. +const INTENSITY_HCB: u8 = 15; +/// `sf` is an exponent in quarter-powers of two around this offset (§4.6.2). +const SF_OFFSET: i32 = 100; +/// The dequantiser works in the standard's own units, where full scale is +/// 2^16; the public API speaks the usual +/-1 float range. Checked against a +/// reference decode in `adts_fixtures_match_ffmpeg_per_channel`, which compares +/// amplitudes and not just shape. +const OUTPUT_SCALE: f32 = 1.0 / 65536.0; +/// The longest TNS filter AAC-LC allows (long blocks; short blocks stop at 7). +const TNS_MAX_ORDER_LONG: usize = 12; +const TNS_MAX_ORDER_SHORT: usize = 7; + +/// The four window sequences of §4.6.11. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum WindowSequence { + OnlyLong, + LongStart, + EightShort, + LongStop, +} + +impl WindowSequence { + fn from_bits(v: u32) -> WindowSequence { + match v { + 1 => WindowSequence::LongStart, + 2 => WindowSequence::EightShort, + 3 => WindowSequence::LongStop, + _ => WindowSequence::OnlyLong, + } + } + + /// True for `EIGHT_SHORT_SEQUENCE`, which changes almost every field width. + pub fn is_short(self) -> bool { + self == WindowSequence::EightShort + } +} + +/// `ics_info` (§4.4.2.1) plus the grouping it implies. +#[derive(Clone, Debug)] +pub struct IcsInfo { + pub window_sequence: WindowSequence, + /// False for the sine window, true for Kaiser-Bessel-derived. + pub window_shape_kbd: bool, + pub max_sfb: usize, + pub num_windows: usize, + pub num_groups: usize, + /// Windows per group, `num_groups` entries. + pub group_len: [usize; 8], + /// Band offsets in force for this window shape, `num_swb + 1` entries. + pub swb: &'static [u16], + /// Highest band a TNS filter may reach at this rate and window length. + pub tns_max_bands: usize, +} + +impl IcsInfo { + fn num_swb(&self) -> usize { + self.swb.len() - 1 + } + + /// First window index of each group. + fn group_start(&self, g: usize) -> usize { + self.group_len[..g].iter().sum() + } +} + +fn parse_ics_info(r: &mut BitReader<'_>, sf_index: u8) -> Result { + let _reserved = r.read_bit()?; + let window_sequence = WindowSequence::from_bits(r.read_bits(2)?); + let window_shape_kbd = r.read_bit()?; + let idx = usize::from(sf_index).min(11); + let (max_sfb, num_windows, num_groups, group_len, swb, tns_max_bands) = + if window_sequence.is_short() { + let max_sfb = r.read_bits(4)? as usize; + let grouping = r.read_bits(7)?; + let mut group_len = [0usize; 8]; + let mut groups = 1; + group_len[0] = 1; + for i in 0..7 { + if (grouping >> (6 - i)) & 1 == 1 { + group_len[groups - 1] += 1; + } else { + group_len[groups] = 1; + groups += 1; + } + } + ( + max_sfb, + 8, + groups, + group_len, + SWB_SHORT[idx], + TNS_MAX_BANDS_SHORT[idx], + ) + } else { + let max_sfb = r.read_bits(6)? as usize; + if r.read_bit()? { + // AAC-LC has no predictor; LTP/main streams are a different profile. + return Err(Error::unsupported( + "aac", + "predictor_data_present: main or LTP profile, not AAC-LC", + )); + } + let mut group_len = [0usize; 8]; + group_len[0] = 1; + ( + max_sfb, + 1, + 1, + group_len, + SWB_LONG[idx], + TNS_MAX_BANDS_LONG[idx], + ) + }; + if max_sfb > swb.len() - 1 { + return Err(Error::corrupt("aac: max_sfb past the band table")); + } + Ok(IcsInfo { + window_sequence, + window_shape_kbd, + max_sfb, + num_windows, + num_groups, + group_len, + swb, + tns_max_bands, + }) +} + +/// One TNS filter as transmitted, already converted to LPC coefficients. +#[derive(Clone, Debug, Default)] +struct TnsFilter { + /// Bands the filter spans, counted down from the top. + length: usize, + order: usize, + /// True when the filter runs from high frequency down. + downward: bool, + lpc: Vec, +} + +#[derive(Clone, Debug, Default)] +struct Tns { + /// Filters per window. + filters: Vec>, +} + +fn parse_tns(r: &mut BitReader<'_>, ics: &IcsInfo) -> Result { + let short = ics.window_sequence.is_short(); + let (n_filt_bits, len_bits, order_bits) = if short { (1, 4, 3) } else { (2, 6, 5) }; + let max_order = if short { + TNS_MAX_ORDER_SHORT + } else { + TNS_MAX_ORDER_LONG + }; + let mut filters = Vec::with_capacity(ics.num_windows); + for _ in 0..ics.num_windows { + let n_filt = r.read_bits(n_filt_bits)? as usize; + let mut coef_res = 0; + if n_filt > 0 { + coef_res = u32::from(r.read_bit()?); + } + let mut win = Vec::with_capacity(n_filt); + for _ in 0..n_filt { + let length = r.read_bits(len_bits)? as usize; + let order = r.read_bits(order_bits)? as usize; + if order == 0 { + win.push(TnsFilter { + length, + ..TnsFilter::default() + }); + continue; + } + // A stream may state a longer filter than the profile allows; the + // extra taps are dropped rather than the frame refused. + let order = order.min(max_order); + let downward = r.read_bit()?; + let compress = u32::from(r.read_bit()?); + let res_bits = coef_res + 3; + let bits = res_bits - compress; + // §4.6.9.3: the transmitted index is a signed fraction of a quarter + // turn, and the two half-step factors keep the mapping symmetric. + let iqfac = ((1 << (res_bits - 1)) as f64 - 0.5) / core::f64::consts::FRAC_PI_2; + let iqfac_m = ((1 << (res_bits - 1)) as f64 + 0.5) / core::f64::consts::FRAC_PI_2; + let mut parcor = Vec::with_capacity(order); + for _ in 0..order { + let raw = r.read_bits(bits)? as i32; + let sign_bit = 1 << (bits - 1); + let value = if raw & sign_bit != 0 { + raw - (1 << bits) + } else { + raw + }; + let scaled = if value >= 0 { + f64::from(value) / iqfac + } else { + f64::from(value) / iqfac_m + }; + parcor.push(scaled.sin()); + } + win.push(TnsFilter { + length, + order, + downward, + lpc: parcor_to_lpc(&parcor), + }); + } + filters.push(win); + } + Ok(Tns { filters }) +} + +/// Reflection coefficients to direct-form LPC (§4.6.9.3), `a[0] == 1`. +fn parcor_to_lpc(parcor: &[f64]) -> Vec { + let mut a = vec![0.0f64; parcor.len() + 1]; + let mut tmp = vec![0.0f64; parcor.len() + 1]; + a[0] = 1.0; + for (m, &k) in parcor.iter().enumerate() { + for i in 1..=m { + tmp[i] = a[i] + k * a[m + 1 - i]; + } + a[1..=m].copy_from_slice(&tmp[1..=m]); + a[m + 1] = k; + } + a.into_iter().map(|v| v as f32).collect() +} + +/// Applies every TNS filter of one window in place (§4.6.9.2). +fn apply_tns(coef: &mut [f32], tns: &Tns, ics: &IcsInfo, window: usize) { + let Some(filters) = tns.filters.get(window) else { + return; + }; + let num_swb = ics.num_swb(); + let mut bottom = num_swb; + for filter in filters { + let top = bottom; + bottom = top.saturating_sub(filter.length); + if filter.order == 0 { + continue; + } + let cap = ics.max_sfb.min(ics.tns_max_bands); + let start = usize::from(ics.swb[bottom.min(cap)]); + let end = usize::from(ics.swb[top.min(cap)]); + if end <= start { + continue; + } + let order = filter.order; + let mut state = vec![0.0f32; order + 1]; + let walk = |i: usize, state: &mut Vec, coef: &mut [f32]| { + let mut y = coef[i]; + for j in 1..=order { + y -= filter.lpc[j] * state[j - 1]; + } + for j in (1..=order).rev() { + state[j] = state[j - 1]; + } + state[0] = y; + coef[i] = y; + }; + if filter.downward { + for i in (start..end).rev() { + walk(i, &mut state, coef); + } + } else { + for i in start..end { + walk(i, &mut state, coef); + } + } + } +} + +/// Per-channel data of one `individual_channel_stream`. +struct Ics { + ics: IcsInfo, + /// `sect_cb` by group and band. + cb: Vec>, + /// Scalefactor, intensity position or noise energy by group and band. + sf: Vec>, + coef: Vec, + tns: Tns, +} + +/// The decoder's per-channel memory: the filterbank overlap and the window +/// shape the next frame's rising edge has to match. +#[derive(Clone, Debug)] +pub struct ChannelState { + overlap: Vec, + prev_shape_kbd: bool, + prev_short: bool, +} + +impl Default for ChannelState { + fn default() -> ChannelState { + ChannelState { + overlap: vec![0.0; FRAME_LEN], + prev_shape_kbd: false, + prev_short: false, + } + } +} + +/// The four windows and two transforms the filterbank needs, built once. +pub struct FilterBank { + long: Mdct, + short: Mdct, + sine_long: Vec, + kbd_long: Vec, + sine_short: Vec, + kbd_short: Vec, + scratch_long: Vec, + scratch_short: Vec, +} + +impl FilterBank { + pub fn new() -> FilterBank { + FilterBank { + long: Mdct::new(2 * FRAME_LEN), + short: Mdct::new(2 * SHORT_LEN), + sine_long: Window::::sine(2 * FRAME_LEN).as_slice().to_vec(), + kbd_long: Window::::kbd(2 * FRAME_LEN, 4.0).as_slice().to_vec(), + sine_short: Window::::sine(2 * SHORT_LEN).as_slice().to_vec(), + kbd_short: Window::::kbd(2 * SHORT_LEN, 6.0).as_slice().to_vec(), + scratch_long: vec![0.0; 2 * FRAME_LEN], + scratch_short: vec![0.0; 2 * SHORT_LEN], + } + } + + fn long_win(&self, kbd: bool) -> &[f32] { + if kbd { &self.kbd_long } else { &self.sine_long } + } + + fn short_win(&self, kbd: bool) -> &[f32] { + if kbd { + &self.kbd_short + } else { + &self.sine_short + } + } + + /// Inverse filterbank and overlap-add for one channel (§4.6.11). + fn synthesize( + &mut self, + spec: &[f32], + ics: &IcsInfo, + state: &mut ChannelState, + out: &mut [f32], + ) { + let mut frame = vec![0.0f32; 2 * FRAME_LEN]; + match ics.window_sequence { + WindowSequence::EightShort => { + for w in 0..8 { + let src = &spec[w * SHORT_LEN..(w + 1) * SHORT_LEN]; + self.short.inverse(src, &mut self.scratch_short); + let rise = self.short_win(if w == 0 { + state.prev_shape_kbd + } else { + ics.window_shape_kbd + }); + let fall = self.short_win(ics.window_shape_kbd); + let base = 448 + w * SHORT_LEN; + for i in 0..SHORT_LEN { + frame[base + i] += self.scratch_short[i] * rise[i]; + frame[base + SHORT_LEN + i] += + self.scratch_short[SHORT_LEN + i] * fall[SHORT_LEN + i]; + } + } + } + seq => { + self.long.inverse(spec, &mut self.scratch_long); + let prev_long = self.long_win(state.prev_shape_kbd); + let prev_short = self.short_win(state.prev_shape_kbd); + let cur_long = self.long_win(ics.window_shape_kbd); + let cur_short = self.short_win(ics.window_shape_kbd); + for i in 0..FRAME_LEN { + let rise = match seq { + // A stop window opens flat: nothing to overlap with the + // short block that preceded it until sample 448. + WindowSequence::LongStop => match i { + 0..448 => 0.0, + 448..576 => prev_short[i - 448], + _ => 1.0, + }, + _ => prev_long[i], + }; + frame[i] = self.scratch_long[i] * rise; + } + for i in 0..FRAME_LEN { + let fall = match seq { + WindowSequence::LongStart => match i { + 0..448 => 1.0, + 448..576 => cur_short[SHORT_LEN + i - 448], + _ => 0.0, + }, + _ => cur_long[FRAME_LEN + i], + }; + frame[FRAME_LEN + i] = self.scratch_long[FRAME_LEN + i] * fall; + } + } + } + for i in 0..FRAME_LEN { + out[i] = (state.overlap[i] + frame[i]) * OUTPUT_SCALE; + } + state.overlap.copy_from_slice(&frame[FRAME_LEN..]); + state.prev_shape_kbd = ics.window_shape_kbd; + state.prev_short = ics.window_sequence.is_short(); + } +} + +impl Default for FilterBank { + fn default() -> FilterBank { + FilterBank::new() + } +} + +/// Deterministic noise source for PNS; the standard leaves the sequence free, +/// only the band energy is normative. +#[derive(Clone, Debug)] +pub struct Noise(u32); + +impl Noise { + fn next(&mut self) -> f32 { + self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (self.0 >> 8) as f32 / (1 << 23) as f32 - 1.0 + } +} + +/// The syntactic and tool state one `raw_data_block` needs. +pub struct BlockDecoder { + pub books: Books, + pub bank: FilterBank, + pub states: Vec, + noise: Noise, + sf_index: u8, +} + +impl BlockDecoder { + pub fn new(sf_index: u8) -> BlockDecoder { + BlockDecoder { + books: Books::new(), + bank: FilterBank::new(), + states: Vec::new(), + noise: Noise(0x1234_5678), + sf_index, + } + } + + pub fn set_sf_index(&mut self, sf_index: u8) { + self.sf_index = sf_index; + } + + 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; + let mut out = Vec::with_capacity(ics.num_groups); + for _ in 0..ics.num_groups { + let mut row = vec![ZERO_HCB; ics.max_sfb]; + let mut k = 0usize; + while k < ics.max_sfb { + let cb = r.read_bits(4)? as u8; + let mut len = 0usize; + loop { + let incr = r.read_bits(bits)?; + len += incr as usize; + if incr != esc { + break; + } + } + if len == 0 || k + len > ics.max_sfb { + return Err(Error::corrupt("aac: section runs past max_sfb")); + } + row[k..k + len].fill(cb); + k += len; + } + out.push(row); + } + Ok(out) + } + + fn scale_factor_data( + &self, + r: &mut BitReader<'_>, + ics: &IcsInfo, + cb: &[Vec], + global_gain: u8, + ) -> Result>> { + let mut scale = i32::from(global_gain); + let mut intensity = 0i32; + let mut noise = i32::from(global_gain) - 90; + let mut noise_pcm = true; + let mut out = Vec::with_capacity(ics.num_groups); + for g in 0..ics.num_groups { + let mut row = vec![0i32; ics.max_sfb]; + for sfb in 0..ics.max_sfb { + row[sfb] = match cb[g][sfb] { + ZERO_HCB => 0, + INTENSITY_HCB | INTENSITY_HCB2 => { + intensity += self.books.scalefactor.decode(r)? as i32 - 60; + intensity + } + NOISE_HCB => { + if noise_pcm { + noise_pcm = false; + noise += r.read_bits(9)? as i32 - 256; + } else { + noise += self.books.scalefactor.decode(r)? as i32 - 60; + } + noise + } + _ => { + scale += self.books.scalefactor.decode(r)? as i32 - 60; + if !(0..=255).contains(&scale) { + return Err(Error::corrupt("aac: scalefactor out of range")); + } + scale + } + }; + } + out.push(row); + } + Ok(out) + } + + /// `spectral_data` (§4.4.2.7) into quantised integers, window-major. + fn spectral_data( + &self, + r: &mut BitReader<'_>, + ics: &IcsInfo, + cb: &[Vec], + quant: &mut [i32], + ) -> Result<()> { + for g in 0..ics.num_groups { + let start = ics.group_start(g); + for sfb in 0..ics.max_sfb { + let book = cb[g][sfb]; + if !(1..=11).contains(&book) { + continue; + } + let spec = &CODEBOOKS[usize::from(book) - 1]; + let tree = &self.books.spectral[usize::from(book) - 1]; + let lo = usize::from(ics.swb[sfb]); + let hi = usize::from(ics.swb[sfb + 1]); + for w in 0..ics.group_len[g] { + let base = if ics.window_sequence.is_short() { + (start + w) * SHORT_LEN + } else { + 0 + }; + let mut k = lo; + while k < hi { + let mut values = [0i32; 4]; + let symbol = tree.decode(r)?; + decode_tuple(spec, symbol, &mut values); + let dim = usize::from(spec.dim); + if spec.unsigned { + for v in values.iter_mut().take(dim) { + if *v != 0 && r.read_bit()? { + *v = -*v; + } + } + } + if spec.esc { + for v in values.iter_mut().take(dim) { + if v.unsigned_abs() == 16 { + let mut n = 0u32; + while r.read_bit()? { + n += 1; + if n > 20 { + return Err(Error::corrupt("aac: escape too long")); + } + } + let magnitude = (1i32 << (n + 4)) | r.read_bits(n + 4)? as i32; + *v = if *v < 0 { -magnitude } else { magnitude }; + } + } + } + for (i, &v) in values.iter().take(dim).enumerate() { + if k + i < hi { + quant[base + k + i] = v; + } + } + k += dim; + } + } + } + } + Ok(()) + } + + /// One `individual_channel_stream` (§4.4.2.4). + fn channel_stream(&mut self, r: &mut BitReader<'_>, shared: Option<&IcsInfo>) -> Result { + let global_gain = r.read_bits(8)? as u8; + let ics = match shared { + Some(info) => info.clone(), + None => parse_ics_info(r, self.sf_index)?, + }; + let cb = self.section_data(r, &ics)?; + let sf = self.scale_factor_data(r, &ics, &cb, global_gain)?; + let mut pulse = None; + if r.read_bit()? { + if ics.window_sequence.is_short() { + return Err(Error::corrupt("aac: pulse data on a short window")); + } + pulse = Some(parse_pulse(r)?); + } + let tns = if r.read_bit()? { + parse_tns(r, &ics)? + } else { + Tns::default() + }; + if r.read_bit()? { + return Err(Error::unsupported("aac", "gain control data: SSR profile")); + } + let mut quant = vec![0i32; FRAME_LEN]; + self.spectral_data(r, &ics, &cb, &mut quant)?; + if let Some(p) = pulse { + apply_pulse(&mut quant, &p, &ics); + } + Ok(Ics { + coef: dequantize(&quant, &ics, &cb, &sf), + ics, + cb, + sf, + tns, + }) + } + + /// Runs the stereo tools, TNS and the filterbank over one element's + /// channels, appending each channel's PCM to `out`. + fn finish(&mut self, chans: &mut [Ics], ms: Option<&MsMask>, out: &mut Vec>) { + if let ([left, right], Some(mask)) = (&mut *chans, ms) { + apply_ms(left, right, mask); + } + if let [left, right] = &mut *chans { + apply_intensity(left, right, ms); + } + for ch in chans.iter_mut() { + fill_noise(ch, &mut self.noise); + let windows = if ch.ics.window_sequence.is_short() { + 8 + } else { + 1 + }; + for w in 0..windows { + let len = if windows == 8 { SHORT_LEN } else { FRAME_LEN }; + apply_tns(&mut ch.coef[w * len..(w + 1) * len], &ch.tns, &ch.ics, w); + } + let mut pcm = vec![0.0f32; FRAME_LEN]; + let index = out.len(); + while self.states.len() <= index { + self.states.push(ChannelState::default()); + } + self.bank + .synthesize(&ch.coef, &ch.ics, &mut self.states[index], &mut pcm); + out.push(pcm); + } + } + + /// Decodes one `raw_data_block`, returning one PCM plane per channel in + /// bitstream element order. + pub fn raw_data_block(&mut self, r: &mut BitReader<'_>) -> Result>> { + let mut out: Vec> = Vec::new(); + loop { + if r.bits_remaining() < 3 { + break; + } + let id = r.read_bits(3)?; + match id { + // SCE and LFE are one channel each; CCE (2) is a coupling + // 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 mut ch = [self.channel_stream(r, None)?]; + self.finish(&mut ch, None, &mut out); + } + 1 => { + let _tag = r.read_bits(4)?; + let common = r.read_bit()?; + let (shared, mask) = if common { + let info = parse_ics_info(r, self.sf_index)?; + let present = r.read_bits(2)?; + let mask = match present { + 0 => MsMask::None, + 1 => { + let mut bits = vec![vec![false; info.max_sfb]; info.num_groups]; + for row in bits.iter_mut() { + for b in row.iter_mut() { + *b = r.read_bit()?; + } + } + MsMask::Some(bits) + } + 2 => MsMask::All, + _ => return Err(Error::corrupt("aac: reserved ms_mask_present")), + }; + (Some(info), mask) + } else { + (None, MsMask::None) + }; + let mut pair = [ + self.channel_stream(r, shared.as_ref())?, + self.channel_stream(r, shared.as_ref())?, + ]; + self.finish(&mut pair, Some(&mask), &mut out); + } + 2 => return Err(Error::unsupported("aac", "coupling channel element")), + 4 => { + let _tag = r.read_bits(4)?; + let align = r.read_bit()?; + let mut count = r.read_bits(8)? as u64; + if count == 255 { + count += r.read_bits(8)? as u64; + } + if align { + r.align_to_byte(); + } + r.skip_bits(count * 8)?; + } + 5 => { + crate::config::skip_program_config(r)?; + } + 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)?; + } + _ => break, + } + } + r.align_to_byte(); + Ok(out) + } +} + +#[derive(Debug)] +enum MsMask { + None, + All, + Some(Vec>), +} + +impl MsMask { + fn used(&self, g: usize, sfb: usize) -> bool { + match self { + MsMask::None => false, + MsMask::All => true, + MsMask::Some(bits) => bits[g][sfb], + } + } +} + +/// The symbol index back into its tuple; the index is the tuple read as digits +/// in base `lav + 1` (unsigned) or `2 * lav + 1` (signed), first coefficient +/// most significant. +fn decode_tuple(cb: &crate::tables::Codebook, symbol: usize, out: &mut [i32; 4]) { + let span = if cb.unsigned { + usize::from(cb.lav) + 1 + } else { + 2 * usize::from(cb.lav) + 1 + }; + let off = if cb.unsigned { 0 } else { i32::from(cb.lav) }; + let dim = usize::from(cb.dim); + let mut rest = symbol; + for i in (0..dim).rev() { + out[i] = (rest % span) as i32 - off; + rest /= span; + } +} + +#[derive(Debug)] +struct Pulse { + start_sfb: usize, + offsets: Vec, + amps: Vec, +} + +fn parse_pulse(r: &mut BitReader<'_>) -> Result { + let count = r.read_bits(2)? as usize + 1; + let start_sfb = r.read_bits(6)? as usize; + let mut offsets = Vec::with_capacity(count); + let mut amps = Vec::with_capacity(count); + for _ in 0..count { + offsets.push(r.read_bits(5)? as usize); + amps.push(r.read_bits(4)? as i32); + } + Ok(Pulse { + start_sfb, + offsets, + amps, + }) +} + +fn apply_pulse(quant: &mut [i32], pulse: &Pulse, ics: &IcsInfo) { + if pulse.start_sfb >= ics.swb.len() { + return; + } + let mut k = usize::from(ics.swb[pulse.start_sfb]); + for (&off, &) in pulse.offsets.iter().zip(&pulse.amps) { + k += off; + if k >= quant.len() { + return; + } + // The pulse grows the magnitude, keeping whatever sign the coefficient + // already had (§4.6.3). + quant[k] += if quant[k] < 0 { -amp } else { amp }; + } +} + +/// `x^(4/3) * 2^((sf - 100) / 4)` per band (§4.6.2), window-major. +fn dequantize(quant: &[i32], ics: &IcsInfo, cb: &[Vec], sf: &[Vec]) -> Vec { + let mut coef = vec![0.0f32; FRAME_LEN]; + let short = ics.window_sequence.is_short(); + for g in 0..ics.num_groups { + let start = ics.group_start(g); + for sfb in 0..ics.max_sfb { + let book = cb[g][sfb]; + if !(1..=11).contains(&book) { + continue; + } + let gain = 2f32.powf((sf[g][sfb] - SF_OFFSET) as f32 * 0.25); + let lo = usize::from(ics.swb[sfb]); + let hi = usize::from(ics.swb[sfb + 1]); + for w in 0..ics.group_len[g] { + let base = if short { (start + w) * SHORT_LEN } else { 0 }; + for k in lo..hi { + let q = quant[base + k]; + if q != 0 { + let mag = (q.unsigned_abs() as f32).powf(4.0 / 3.0) * gain; + coef[base + k] = if q < 0 { -mag } else { mag }; + } + } + } + } + } + coef +} + +/// Mid/side to left/right, for every band the mask marks and no other (§4.6.8.1). +fn apply_ms(left: &mut Ics, right: &mut Ics, mask: &MsMask) { + let ics = &left.ics; + let short = ics.window_sequence.is_short(); + for g in 0..ics.num_groups { + let start = ics.group_start(g); + for sfb in 0..ics.max_sfb { + if !mask.used(g, sfb) || is_intensity(right.cb[g][sfb]) { + continue; + } + let lo = usize::from(ics.swb[sfb]); + let hi = usize::from(ics.swb[sfb + 1]); + for w in 0..ics.group_len[g] { + let base = if short { (start + w) * SHORT_LEN } else { 0 }; + for k in base + lo..base + hi { + let (m, s) = (left.coef[k], right.coef[k]); + left.coef[k] = m + s; + right.coef[k] = m - s; + } + } + } + } +} + +fn is_intensity(cb: u8) -> bool { + cb == INTENSITY_HCB || cb == INTENSITY_HCB2 +} + +/// Intensity stereo: the right channel's marked bands are the left channel's, +/// scaled by `0.5^(is_position / 4)` and signed by the codebook (§4.6.8.2). +fn apply_intensity(left: &mut Ics, right: &mut Ics, ms: Option<&MsMask>) { + let ics = right.ics.clone(); + let short = ics.window_sequence.is_short(); + for g in 0..ics.num_groups { + let start = ics.group_start(g); + for sfb in 0..ics.max_sfb { + let cb = right.cb[g][sfb]; + if !is_intensity(cb) { + continue; + } + let mut sign = if cb == INTENSITY_HCB { 1.0 } else { -1.0 }; + if ms.is_some_and(|m| m.used(g, sfb)) { + sign = -sign; + } + let scale = sign * 0.5f32.powf(0.25 * right.sf[g][sfb] as f32); + let lo = usize::from(ics.swb[sfb]); + let hi = usize::from(ics.swb[sfb + 1]); + for w in 0..ics.group_len[g] { + let base = if short { (start + w) * SHORT_LEN } else { 0 }; + for k in base + lo..base + hi { + right.coef[k] = left.coef[k] * scale; + } + } + } + } +} + +/// Perceptual noise substitution: the band is filled with noise carrying the +/// transmitted energy (§4.6.13). The sequence is free, the energy is not. +fn fill_noise(ch: &mut Ics, rng: &mut Noise) { + let ics = ch.ics.clone(); + let short = ics.window_sequence.is_short(); + for g in 0..ics.num_groups { + let start = ics.group_start(g); + for sfb in 0..ics.max_sfb { + if ch.cb[g][sfb] != NOISE_HCB { + continue; + } + let lo = usize::from(ics.swb[sfb]); + let hi = usize::from(ics.swb[sfb + 1]); + for w in 0..ics.group_len[g] { + let base = if short { (start + w) * SHORT_LEN } else { 0 }; + let mut energy = 0.0f32; + for k in base + lo..base + hi { + let v = rng.next(); + ch.coef[k] = v; + energy += v * v; + } + if energy <= 0.0 { + continue; + } + let target = 2f32.powf(0.25 * ch.sf[g][sfb] as f32); + let scale = target / energy.sqrt(); + for k in base + lo..base + hi { + ch.coef[k] *= scale; + } + } + } + } +} diff --git a/crates/ec-aac/src/encode.rs b/crates/ec-aac/src/encode.rs new file mode 100644 index 00000000..db42c005 --- /dev/null +++ b/crates/ec-aac/src/encode.rs @@ -0,0 +1,1074 @@ +//! AAC-LC encoding: psychoacoustics, window decision, quantisation and the +//! `raw_data_block` writer. +//! +//! The psychoacoustic model is the classic three-stage one, and this is exactly +//! what it does: a 2048-point FFT of the windowed input gives per-band energy; +//! energy is spread across bands with a two-slope spreading function at +//! scalefactor-band resolution; tonality is estimated by each band's spectral +//! flatness (**not** by phase unpredictability, which needs two frames of +//! history for a fraction of a dB); the signal-to-mask ratio runs from 6 dB on +//! noise-like bands to 24 dB on tonal ones. Rate control is the two-loop +//! search of the informative part of ISO/IEC 14496-3: an inner distortion loop +//! choosing each band's scalefactor against its mask, and an outer rate loop +//! over a common offset, against a bit reservoir. +//! +//! The window decision is shared by every channel of a frame, which is what +//! lets a channel pair use `common_window` and therefore mid/side coding. +//! +//! Band, group and window indices are the domain's own coordinates and address +//! several parallel arrays at once, so the loops here are written over indices +//! rather than iterators. +#![allow(clippy::needless_range_loop)] + +use ec_core::{BitWriter, Error, Result}; +use ec_dsp::{Complex, Mdct, RealFft, Window}; + +use crate::config::{AdtsHeader, config_for_channels, sf_index_for_rate}; +use crate::decode::{FRAME_LEN, SHORT_LEN, WindowSequence}; +use crate::tables::{CODEBOOKS, Codebook, SCALEFACTOR_CODES, SWB_LONG, SWB_SHORT}; + +const SF_OFFSET: i32 = 100; +/// The decoder divides by this; the encoder multiplies by it, so a round trip +/// is unity gain. +const INPUT_SCALE: f32 = 65536.0; +/// Quantiser rounding bias of the informative encoder (§4.6.2). +const ROUND_BIAS: f32 = 0.4054; +/// Ceiling on what the reservoir may lend one frame, per channel. +const RESERVOIR_MAX: i32 = 6144; +/// Largest magnitude the escape codebook can carry. +const MAX_QUANT: i32 = 8191; +/// Masking floor relative to the loudest band of the frame, standing in for the +/// absolute threshold of hearing (see [`AacEncoder::psychoacoustics`]). +const ATH_FLOOR: f32 = 1e-7; + +/// Which window shape the encoder asks for. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum WindowShape { + /// Sine window everywhere. + #[default] + Sine, + /// Kaiser-Bessel-derived everywhere: better stop-band rejection, which + /// suits tonal material. + Kbd, +} + +/// Encoder options. +#[derive(Debug, Clone, Copy)] +pub struct AacEncoderConfig { + /// Target bitrate in bits per second, over all channels. + pub bitrate_bps: u32, + /// Window shape policy. + pub window_shape: WindowShape, + /// Emit ADTS framing around each packet instead of a bare `raw_data_block`. + pub adts: bool, + /// Allow mid/side coding on channel pairs. + pub mid_side: bool, + /// Allow the long/short window switch on transients. + pub window_switching: bool, +} + +impl Default for AacEncoderConfig { + fn default() -> AacEncoderConfig { + AacEncoderConfig { + bitrate_bps: 128_000, + window_shape: WindowShape::Sine, + adts: false, + mid_side: true, + window_switching: true, + } + } +} + +/// One encoded access unit. +#[derive(Debug, Clone)] +pub struct EncodedPacket { + pub data: Vec, + /// Presentation time in samples (frame index * 1024). + pub pts: i64, + /// Duration in samples; always one AAC frame. + pub duration: u32, +} + +/// One channel's transform and masking thresholds for a frame. +#[derive(Clone)] +struct ChannelFrame { + /// MDCT coefficients, window-major for short sequences. + coef: Vec, + /// Masking threshold per band. + threshold: Vec, +} + +/// An AAC-LC encoder. +pub struct AacEncoder { + config: AacEncoderConfig, + sample_rate: u32, + sf_index: u8, + channels: usize, + /// Input not yet turned into frames, per channel. + pcm: Vec>, + /// The previous frame's samples, the MDCT block's left half. + prev: Vec>, + seq: WindowSequence, + energy: f32, + mdct_long: Mdct, + mdct_short: Mdct, + fft: RealFft, + sine_long: Vec, + kbd_long: Vec, + sine_short: Vec, + kbd_short: Vec, + queue: std::collections::VecDeque, + frames_out: i64, + reservoir: i32, + flushed: bool, + initialised: bool, +} + +impl AacEncoder { + pub fn new(config: AacEncoderConfig) -> AacEncoder { + AacEncoder { + config, + sample_rate: 0, + sf_index: 3, + channels: 0, + pcm: Vec::new(), + prev: Vec::new(), + seq: WindowSequence::OnlyLong, + energy: 0.0, + mdct_long: Mdct::new(2 * FRAME_LEN), + mdct_short: Mdct::new(2 * SHORT_LEN), + fft: RealFft::new(2 * FRAME_LEN), + sine_long: Window::::sine(2 * FRAME_LEN).as_slice().to_vec(), + kbd_long: Window::::kbd(2 * FRAME_LEN, 4.0).as_slice().to_vec(), + sine_short: Window::::sine(2 * SHORT_LEN).as_slice().to_vec(), + kbd_short: Window::::kbd(2 * SHORT_LEN, 6.0).as_slice().to_vec(), + queue: std::collections::VecDeque::new(), + frames_out: 0, + reservoir: 0, + flushed: false, + initialised: false, + } + } + + /// The stream's sample rate; 0 until the first PCM arrives. + pub fn sample_rate(&self) -> u32 { + self.sample_rate + } + + /// The stream's channel count; 0 until the first PCM arrives. + pub fn channels(&self) -> u16 { + self.channels as u16 + } + + /// The AudioSpecificConfig a container needs for this stream. + pub fn audio_specific_config(&self) -> Vec { + crate::config::audio_specific_config_bytes(self.sample_rate, self.channels as u16) + } + + fn init(&mut self, channels: u16, sample_rate: u32) -> Result<()> { + if self.initialised { + if self.channels != usize::from(channels) || self.sample_rate != sample_rate { + return Err(Error::corrupt("aac: stream parameters changed mid-encode")); + } + return Ok(()); + } + let sf_index = sf_index_for_rate(sample_rate).ok_or_else(|| { + Error::unsupported("aac", format!("{sample_rate} Hz is not an AAC sample rate")) + })?; + if channels == 0 || channels == 7 || channels > 8 { + return Err(Error::unsupported( + "aac", + format!("{channels} channels has no channelConfiguration"), + )); + } + self.sf_index = sf_index; + self.sample_rate = sample_rate; + self.channels = usize::from(channels); + self.pcm = vec![Vec::new(); self.channels]; + self.prev = vec![vec![0.0; FRAME_LEN]; self.channels]; + self.initialised = true; + Ok(()) + } + + /// Appends interleaved PCM. + pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> { + self.init(channels, sample_rate)?; + let n = usize::from(channels); + for (i, sample) in interleaved.iter().enumerate() { + self.pcm[i % n].push(*sample); + } + self.drain_frames(); + Ok(()) + } + + /// Appends planar PCM, one slice per channel. + pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> { + self.init(planes.len() as u16, sample_rate)?; + for (buf, plane) in self.pcm.iter_mut().zip(planes) { + buf.extend_from_slice(plane); + } + self.drain_frames(); + Ok(()) + } + + /// Marks the end of input; the tail is padded to a whole frame. + pub fn finish(&mut self) { + if !self.initialised || self.flushed { + self.flushed = true; + return; + } + self.flushed = true; + let left = self.pcm.iter().map(|c| c.len()).max().unwrap_or(0); + if left > 0 { + // One frame of lookahead is held back for the window decision, and + // the filterbank needs another frame of zeroes to flush its tail. + let pad = left.div_ceil(FRAME_LEN) * FRAME_LEN + 2 * FRAME_LEN; + for c in self.pcm.iter_mut() { + c.resize(pad, 0.0); + } + } + self.drain_frames(); + } + + /// Takes the next encoded packet, or [`Error::Eof`] once drained. + pub fn next_packet(&mut self) -> Result { + self.queue.pop_front().ok_or(Error::Eof) + } + + fn drain_frames(&mut self) { + while self.pcm.iter().all(|c| c.len() >= 2 * FRAME_LEN) { + self.encode_frame(); + } + } + + fn long_window(&self) -> &[f32] { + match self.config.window_shape { + WindowShape::Sine => &self.sine_long, + WindowShape::Kbd => &self.kbd_long, + } + } + + fn short_window(&self) -> &[f32] { + match self.config.window_shape { + WindowShape::Sine => &self.sine_short, + WindowShape::Kbd => &self.kbd_short, + } + } + + fn swb(&self, seq: WindowSequence) -> &'static [u16] { + let idx = usize::from(self.sf_index).min(11); + if seq == WindowSequence::EightShort { + SWB_SHORT[idx] + } else { + SWB_LONG[idx] + } + } + + /// Transform, psychoacoustics, quantisation and bitstream for one frame. + fn encode_frame(&mut self) { + // One window decision for the whole frame: a channel pair can only + // share `ics_info` -- and so only use mid/side -- if it shares its + // window sequence. + let transient = self.config.window_switching && self.frame_transient(); + self.seq = match self.seq { + WindowSequence::LongStart => WindowSequence::EightShort, + WindowSequence::EightShort if transient => WindowSequence::EightShort, + WindowSequence::EightShort => WindowSequence::LongStop, + _ if transient => WindowSequence::LongStart, + _ => WindowSequence::OnlyLong, + }; + let seq = self.seq; + + let mut frames = Vec::with_capacity(self.channels); + for ch in 0..self.channels { + let cur: Vec = self.pcm[ch][..FRAME_LEN] + .iter() + .map(|v| v * INPUT_SCALE) + .collect(); + let mut block = Vec::with_capacity(2 * FRAME_LEN); + block.extend_from_slice(&self.prev[ch]); + block.extend_from_slice(&cur); + self.prev[ch] = cur; + let coef = self.transform(&block, seq); + let threshold = self.psychoacoustics(&block, &coef, seq); + frames.push(ChannelFrame { coef, threshold }); + } + for c in self.pcm.iter_mut() { + c.drain(..FRAME_LEN); + } + + let target = (u64::from(self.config.bitrate_bps) * FRAME_LEN as u64 + / u64::from(self.sample_rate.max(1))) as i32; + let budget = target + + self + .reservoir + .clamp(0, RESERVOIR_MAX * self.channels as i32); + let data = self.write_frame(&frames, seq, budget); + let used = data.len() as i32 * 8; + self.reservoir = + (self.reservoir + target - used).clamp(0, RESERVOIR_MAX * self.channels as i32); + let data = if self.config.adts { + let header = AdtsHeader { + object_type: 2, + sf_index: self.sf_index, + sample_rate: self.sample_rate, + channels: self.channels as u16, + channel_config: config_for_channels(self.channels as u16), + frame_length: data.len() + 7, + header_len: 7, + raw_blocks: 1, + }; + let mut out = crate::config::write_adts_header(&header); + out.extend_from_slice(&data); + out + } else { + data + }; + self.queue.push_back(EncodedPacket { + data, + pts: self.frames_out * FRAME_LEN as i64, + duration: FRAME_LEN as u32, + }); + self.frames_out += 1; + } + + /// An eighth-frame energy jump anywhere in the frame ahead is a transient. + /// + /// The running average is primed by the first frame rather than starting at + /// zero: from zero every opening sample looks like an attack, and the frames + /// that carry a file's first second would all be coded short. + fn frame_transient(&mut self) -> bool { + let mut hit = false; + let primed = self.energy > 0.0; + let mut running = self.energy; + for i in 0..8 { + let mut e = 0.0f32; + for ch in 0..self.channels { + let lo = FRAME_LEN + i * SHORT_LEN; + for v in &self.pcm[ch][lo..lo + SHORT_LEN] { + e += v * v; + } + } + e /= (SHORT_LEN * self.channels) as f32; + if primed && e > running * 8.0 && e > 1e-7 { + hit = true; + } + running = if i == 0 && !primed { + e + } else { + running * 0.7 + e * 0.3 + }; + } + self.energy = running; + hit + } + + fn transform(&mut self, block: &[f32], seq: WindowSequence) -> Vec { + let mut coef = vec![0.0f32; FRAME_LEN]; + if seq == WindowSequence::EightShort { + let win = self.short_window().to_vec(); + for w in 0..8 { + let base = 448 + w * SHORT_LEN; + self.mdct_short.forward_windowed( + &block[base..base + 2 * SHORT_LEN], + &win, + &mut coef[w * SHORT_LEN..(w + 1) * SHORT_LEN], + ); + } + return coef; + } + let long = self.long_window().to_vec(); + let short = self.short_window().to_vec(); + let mut win = vec![1.0f32; 2 * FRAME_LEN]; + match seq { + WindowSequence::LongStart => { + win[..FRAME_LEN].copy_from_slice(&long[..FRAME_LEN]); + win[FRAME_LEN + 448..FRAME_LEN + 576] + .copy_from_slice(&short[SHORT_LEN..2 * SHORT_LEN]); + win[FRAME_LEN + 576..].fill(0.0); + } + WindowSequence::LongStop => { + win[..448].fill(0.0); + win[448..576].copy_from_slice(&short[..SHORT_LEN]); + win[FRAME_LEN..].copy_from_slice(&long[FRAME_LEN..]); + } + _ => win.copy_from_slice(&long), + } + self.mdct_long.forward_windowed(block, &win, &mut coef); + coef + } + + /// Per-band masking thresholds; see the module docs for the model. + fn psychoacoustics(&mut self, block: &[f32], coef: &[f32], seq: WindowSequence) -> Vec { + let swb = self.swb(seq); + let bands = swb.len() - 1; + let windowed: Vec = block + .iter() + .zip(self.sine_long.iter()) + .map(|(v, w)| v * w) + .collect(); + let mut spectrum = vec![ + Complex { + re: 0.0f32, + im: 0.0f32 + }; + FRAME_LEN + 1 + ]; + self.fft.forward(&windowed, &mut spectrum); + let short = seq == WindowSequence::EightShort; + let windows = if short { 8 } else { 1 }; + let mut energy = vec![0.0f32; bands]; + let mut flatness = vec![0.0f32; bands]; + for b in 0..bands { + let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1])); + // Level comes from the MDCT itself, so the threshold and the + // quantisation noise it is compared against are in the same units; + // an FFT-scaled threshold would be a constant factor out, and that + // constant is the difference between masking a band and coding it. + let mut sum = 0.0f64; + let mut n = 0usize; + for w in 0..windows { + let base = if short { w * SHORT_LEN } else { 0 }; + for k in base + lo..base + hi { + sum += f64::from(coef[k]) * f64::from(coef[k]); + n += 1; + } + } + energy[b] = (sum / n.max(1) as f64) as f32; + // Tonality comes from the FFT, which is what it is good for. A short + // block's bands index 128 lines against the FFT's 1024, the same + // eightfold ratio the filterbank uses. + let (flo, fhi) = if short { (lo * 8, hi * 8) } else { (lo, hi) }; + let fhi = fhi.min(FRAME_LEN); + let fn_ = fhi.saturating_sub(flo).max(1); + let mut fsum = 0.0f64; + let mut log_sum = 0.0f64; + for k in flo..fhi { + let p = f64::from(spectrum[k].norm_sqr()) + 1e-9; + fsum += p; + log_sum += p.ln(); + } + let geometric = (log_sum / fn_ as f64).exp(); + flatness[b] = (geometric / (fsum / fn_ as f64).max(1e-30)) as f32; + } + // Two-slope spreading at band resolution: about 10 dB per band upward + // in frequency, 25 dB downward. + let mut spread = energy.clone(); + for b in 1..bands { + spread[b] = spread[b].max(spread[b - 1] * 0.1); + } + for b in (0..bands.saturating_sub(1)).rev() { + spread[b] = spread[b].max(spread[b + 1] * 0.003); + } + // Standing in for the absolute threshold of hearing: nothing this far + // under the loudest band of the frame is audible, and without a floor + // of this kind the spreading function falls away faster than the + // filterbank's own leakage does, so an encoder spends its whole budget + // coding the skirts of a tone at full precision. + let floor = energy.iter().copied().fold(0.0f32, f32::max) * ATH_FLOOR; + (0..bands) + .map(|b| { + // Flat (noise-like) bands mask well, peaky (tonal) ones badly. + let tonality = (1.0 - flatness[b]).clamp(0.0, 1.0); + let smr = 10f32.powf((6.0 + 18.0 * tonality) / 10.0); + (spread[b] / smr).max(floor).max(1e-3) + }) + .collect() + } + + /// Quantises every channel against a shared rate loop and writes the block. + fn write_frame( + &mut self, + frames: &[ChannelFrame], + seq: WindowSequence, + budget: i32, + ) -> Vec { + let layout = element_layout(self.channels); + let swb = self.swb(seq); + let short = seq == WindowSequence::EightShort; + let max_sfb = (swb.len() - 1).min(if short { 15 } else { 51 }); + + // Mid/side per band, decided once: the pair that codes to the more + // lopsided energy split is the one that costs fewer bits. + let mut elements: Vec = Vec::with_capacity(layout.len()); + for (element, chans) in &layout { + let mut pair: Vec = chans.iter().map(|&c| frames[c].clone()).collect(); + let mut ms = vec![false; max_sfb]; + if *element == Element::Cpe && self.config.mid_side { + for b in 0..max_sfb { + if ms_wins(&pair[0], &pair[1], swb, b, short) { + ms[b] = true; + } + } + apply_ms(&mut pair, &ms, swb, max_sfb, short); + } + elements.push(ElementPlan { + element: *element, + frames: pair, + ms, + }); + } + + // Outer rate loop. Bits fall monotonically as the common offset rises, + // so the finest quantisation that fits the budget is a bisection -- + // which also means the psychoacoustic model only has to get the shape + // of the allocation right, not its absolute level. + let cost = |enc: &AacEncoder, offset: i32| -> (i32, Vec) { + let mut coded = Vec::new(); + let mut bits = 10i32; // END element plus byte-alignment slack + for plan in &elements { + bits += 3 + + 4 + + if plan.element == Element::Cpe { + 1 + 2 + max_sfb as i32 + } else { + 0 + }; + for frame in &plan.frames { + let c = enc.quantise(frame, seq, swb, max_sfb, offset); + bits += c.bits; + coded.push(c); + } + } + (bits, coded) + }; + let (mut lo, mut hi) = (-240i32, 240i32); + let (mut bits, mut coded) = cost(self, hi); + if bits > budget { + // Even the coarsest setting overflows: take it and let the + // reservoir absorb the overshoot. + lo = hi; + } else { + while lo < hi { + let mid = lo + (hi - lo) / 2; + let (b, c) = cost(self, mid); + if b <= budget { + hi = mid; + bits = b; + coded = c; + } else { + lo = mid + 1; + } + } + if lo < 240 { + let (b, c) = cost(self, lo); + if b <= budget { + bits = b; + coded = c; + } + } + } + let _ = (lo, bits); + + let mut w = BitWriter::new(); + let mut at = 0usize; + for plan in &elements { + let id = match plan.element { + Element::Sce => 0u32, + Element::Cpe => 1, + Element::Lfe => 3, + }; + w.write_bits(id, 3); + w.write_bits(0, 4); // element_instance_tag + if plan.element == Element::Cpe { + w.write_bit(true); // common_window + write_ics_info(&mut w, &coded[at]); + w.write_bits(1, 2); // ms_mask_present: per band + for b in 0..coded[at].max_sfb { + w.write_bit(plan.ms[b]); + } + write_ics(&mut w, &coded[at], false); + write_ics(&mut w, &coded[at + 1], false); + at += 2; + } else { + write_ics(&mut w, &coded[at], true); + at += 1; + } + } + w.write_bits(7, 3); // END + w.align_to_byte(); + w.into_bytes() + } + + /// Inner distortion loop: the coarsest scalefactor per band whose noise + /// still sits under the mask, then codebook choice and an exact bit count. + /// + /// Only bands that actually code anything carry a scalefactor, and the + /// codebook can only code a delta of +/-60 between consecutive ones. Both + /// facts are settled here rather than at write time -- a scalefactor the + /// bitstream cannot carry would come back at the wrong gain, and chaining + /// the constraint through *silent* bands is what drags a fine scalefactor + /// into the empty top of the spectrum and spends the frame on leakage. + fn quantise( + &self, + frame: &ChannelFrame, + seq: WindowSequence, + swb: &'static [u16], + max_sfb: usize, + offset: i32, + ) -> Coded { + let short = seq == WindowSequence::EightShort; + let windows = if short { 8 } else { 1 }; + let mut sf = vec![0i32; max_sfb]; + let mut floor = vec![0i32; max_sfb]; + let mut zero = vec![true; max_sfb]; + for b in 0..max_sfb { + let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1])); + let mut peak = 0.0f32; + for w in 0..windows { + let base = if short { w * SHORT_LEN } else { 0 }; + for k in base + lo..base + hi { + peak = peak.max(frame.coef[k].abs()); + } + } + if peak < 1e-4 { + continue; + } + // The rate loop scales the whole mask rather than shifting the + // scalefactors: that keeps the noise following the shape the model + // asked for, and lets a band whose signal falls under its own mask + // drop out entirely instead of being coded ever more coarsely. + let target = frame.threshold[b] * 2f32.powf(offset as f32 * 0.5); + let mut energy = 0.0f32; + let mut count = 0usize; + for w in 0..windows { + let base = if short { w * SHORT_LEN } else { 0 }; + for k in base + lo..base + hi { + energy += frame.coef[k] * frame.coef[k]; + count += 1; + } + } + if energy / count.max(1) as f32 <= target { + continue; + } + floor[b] = sf_floor(peak).max(0); + let mut best = floor[b]; + let mut level = best; + while level < 255 { + if self.band_noise(frame, swb, b, level, windows, short) > target { + break; + } + best = level; + level += 1; + } + sf[b] = best.clamp(floor[b], 255); + zero[b] = false; + } + + let mut quant = vec![0i32; FRAME_LEN]; + let mut books = vec![0u8; max_sfb]; + for _ in 0..4 { + let mut settled = true; + let mut prev: Option = None; + for b in 0..max_sfb { + if zero[b] { + continue; + } + let fixed = match prev { + None => sf[b], + Some(p) => sf[b].clamp(p - 60, p + 60).clamp(0, 255), + }; + if fixed != sf[b] { + sf[b] = fixed; + settled = false; + } + prev = Some(sf[b]); + } + for b in 0..max_sfb { + let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1])); + if zero[b] { + books[b] = 0; + for w in 0..windows { + let base = if short { w * SHORT_LEN } else { 0 }; + quant[base + lo..base + hi].fill(0); + } + continue; + } + let mut peak = 0i32; + for w in 0..windows { + let base = if short { w * SHORT_LEN } else { 0 }; + for k in lo..hi { + let q = quantise_one(frame.coef[base + k], sf[b]); + quant[base + k] = q; + peak = peak.max(q.abs()); + } + } + books[b] = codebook_for(peak); + if peak == 0 { + // Nothing survived: the band leaves the delta chain, which + // may free the bands after it to go coarser. + zero[b] = true; + settled = false; + } + } + if settled { + break; + } + } + + let mut bits = 8 + 3; // global_gain plus the three tool flags + let mut prev: Option = None; + for b in 0..max_sfb { + if books[b] == 0 { + continue; + } + bits += band_bits(&quant, swb, b, books[b], windows, short); + let value = prev.map_or(60, |p| (60 + sf[b] - p).clamp(0, 120)); + bits += i32::from(SCALEFACTOR_CODES[value as usize].0); + prev = Some(sf[b]); + } + let mut sections = 0; + let mut b = 0usize; + while b < max_sfb { + let book = books[b]; + while b < max_sfb && books[b] == book { + b += 1; + } + sections += 1; + } + bits += sections * (4 + if short { 3 } else { 5 }); + Coded { + seq, + max_sfb, + swb, + sf, + books, + quant, + bits, + short, + } + } + + /// Quantisation noise energy of one band at a candidate scalefactor. + fn band_noise( + &self, + frame: &ChannelFrame, + swb: &[u16], + band: usize, + sf: i32, + windows: usize, + short: bool, + ) -> f32 { + let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1])); + let gain = 2f32.powf((sf - SF_OFFSET) as f32 * 0.25); + let mut noise = 0.0f32; + let mut count = 0usize; + for w in 0..windows { + let base = if short { w * SHORT_LEN } else { 0 }; + for k in base + lo..base + hi { + let x = frame.coef[k]; + let q = quantise_one(x, sf); + let mut back = (q.unsigned_abs() as f32).powf(4.0 / 3.0) * gain; + if q < 0 { + back = -back; + } + noise += (x - back) * (x - back); + count += 1; + } + } + noise / count.max(1) as f32 + } +} + +struct ElementPlan { + element: Element, + frames: Vec, + ms: Vec, +} + +/// A channel's quantised frame, ready to write. +struct Coded { + seq: WindowSequence, + max_sfb: usize, + swb: &'static [u16], + sf: Vec, + books: Vec, + quant: Vec, + bits: i32, + short: bool, +} + +/// True when mid/side splits this band's energy more lopsidedly than left/right +/// does, which is when it costs fewer bits. +fn ms_wins(l: &ChannelFrame, r: &ChannelFrame, swb: &[u16], band: usize, short: bool) -> bool { + let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1])); + let windows = if short { 8 } else { 1 }; + let (mut el, mut er, mut em, mut es) = (0.0f64, 0.0f64, 0.0f64, 0.0f64); + for w in 0..windows { + let base = if short { w * SHORT_LEN } else { 0 }; + for k in base + lo..base + hi { + let (a, b) = (f64::from(l.coef[k]), f64::from(r.coef[k])); + el += a * a; + er += b * b; + em += (a + b) * (a + b) * 0.25; + es += (a - b) * (a - b) * 0.25; + } + } + let lr = (el.max(er) + 1e-9) / (el.min(er) + 1e-9); + let ms = (em.max(es) + 1e-9) / (em.min(es) + 1e-9); + ms > lr * 1.5 +} + +fn apply_ms(pair: &mut [ChannelFrame], ms: &[bool], swb: &[u16], max_sfb: usize, short: bool) { + let windows = if short { 8 } else { 1 }; + for b in 0..max_sfb { + if !ms[b] { + continue; + } + let (lo, hi) = (usize::from(swb[b]), usize::from(swb[b + 1])); + for w in 0..windows { + let base = if short { w * SHORT_LEN } else { 0 }; + for k in base + lo..base + hi { + let (a, b2) = (pair[0].coef[k], pair[1].coef[k]); + pair[0].coef[k] = (a + b2) * 0.5; + pair[1].coef[k] = (a - b2) * 0.5; + } + } + // The side channel inherits the pair's tighter mask. + let t = pair[0].threshold[b].min(pair[1].threshold[b]); + pair[0].threshold[b] = t; + pair[1].threshold[b] = t; + } +} + +/// The finest scalefactor at which a peak of this size still fits the escape +/// codebook: below it the quantiser saturates, which costs bits *and* adds +/// distortion. +fn sf_floor(peak: f32) -> i32 { + let want = (0.75 * peak.log2() - (MAX_QUANT as f32).log2()) / 0.1875; + SF_OFFSET + want.ceil() as i32 +} + +fn quantise_one(x: f32, sf: i32) -> i32 { + if x == 0.0 { + return 0; + } + let gain = 2f32.powf(-(sf - SF_OFFSET) as f32 * 0.25); + let q = ((x.abs() * gain).powf(0.75) + ROUND_BIAS) as i32; + let q = q.min(MAX_QUANT); + if x < 0.0 { -q } else { q } +} + +/// The cheapest codebook that can carry a peak magnitude. +fn codebook_for(peak: i32) -> u8 { + match peak { + 0 => 0, + 1 => 1, + 2 => 3, + 3..=4 => 5, + 5..=7 => 7, + 8..=12 => 9, + _ => 11, + } +} + +fn band_bits( + quant: &[i32], + swb: &[u16], + band: usize, + book: u8, + windows: usize, + short: bool, +) -> i32 { + let cb = &CODEBOOKS[usize::from(book) - 1]; + let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1])); + let dim = usize::from(cb.dim); + let mut bits = 0i32; + for w in 0..windows { + let base = if short { w * SHORT_LEN } else { 0 }; + let mut k = lo; + while k < hi { + let end = (k + dim).min(hi); + bits += tuple_bits(cb, &quant[base + k..base + end]); + k += dim; + } + } + bits +} + +/// Bits one Huffman tuple costs, sign and escape included. +fn tuple_bits(cb: &Codebook, values: &[i32]) -> i32 { + let mut bits = i32::from(cb.codes[tuple_index(cb, values)].0); + for &v in values { + if cb.unsigned && v != 0 { + bits += 1; + } + if cb.esc && v.unsigned_abs() >= 16 { + let n = escape_order(v.unsigned_abs()); + bits += 2 * n + 5; + } + } + bits +} + +/// The escape's unary length: `value` needs `n + 4` payload bits. +fn escape_order(mag: u32) -> i32 { + (32 - mag.leading_zeros()) as i32 - 5 +} + +/// Tuple to codebook index, clamped into the codebook's range. +fn tuple_index(cb: &Codebook, values: &[i32]) -> usize { + let span = if cb.unsigned { + usize::from(cb.lav) + 1 + } else { + 2 * usize::from(cb.lav) + 1 + }; + let mut idx = 0usize; + for i in 0..usize::from(cb.dim) { + let v = values.get(i).copied().unwrap_or(0); + let digit = if cb.unsigned { + v.unsigned_abs().min(u32::from(cb.lav)) as usize + } else { + (v.clamp(-i32::from(cb.lav), i32::from(cb.lav)) + i32::from(cb.lav)) as usize + }; + idx = idx * span + digit; + } + idx +} + +fn write_tuple(w: &mut BitWriter, cb: &Codebook, values: &[i32]) { + let (len, code) = cb.codes[tuple_index(cb, values)]; + w.write_bits(code, u32::from(len)); + if cb.unsigned { + for &v in values.iter().take(usize::from(cb.dim)) { + if v != 0 { + w.write_bit(v < 0); + } + } + } + if cb.esc { + for &v in values.iter().take(usize::from(cb.dim)) { + let mag = v.unsigned_abs(); + if mag >= 16 { + let n = escape_order(mag) as u32; + for _ in 0..n { + w.write_bit(true); + } + w.write_bit(false); + w.write_bits(mag & ((1 << (n + 4)) - 1), n + 4); + } + } + } +} + +fn write_ics_info(w: &mut BitWriter, c: &Coded) { + w.write_bit(false); // ics_reserved_bit + let seq = match c.seq { + WindowSequence::OnlyLong => 0, + WindowSequence::LongStart => 1, + WindowSequence::EightShort => 2, + WindowSequence::LongStop => 3, + }; + w.write_bits(seq, 2); + w.write_bit(false); // sine window shape + if c.short { + w.write_bits(c.max_sfb as u32, 4); + w.write_bits(0x7F, 7); // one group of eight windows + } else { + w.write_bits(c.max_sfb as u32, 6); + w.write_bit(false); // predictor_data_present + } +} + +fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) { + let first = c.books.iter().position(|&b| b != 0); + let global_gain = first.map_or(100, |b| c.sf[b]).clamp(0, 255) as u32; + w.write_bits(global_gain, 8); + if own_info { + write_ics_info(w, c); + } + // section_data + let esc_bits = if c.short { 3 } else { 5 }; + let esc = (1u32 << esc_bits) - 1; + let mut b = 0usize; + while b < c.max_sfb { + let book = c.books[b]; + let start = b; + while b < c.max_sfb && c.books[b] == book { + b += 1; + } + w.write_bits(u32::from(book), 4); + let mut left = (b - start) as u32; + while left >= esc { + w.write_bits(esc, esc_bits); + left -= esc; + } + w.write_bits(left, esc_bits); + } + // scale_factor_data + let mut prev = global_gain as i32; + for b in 0..c.max_sfb { + if c.books[b] == 0 { + continue; + } + let value = (60 + c.sf[b] - prev).clamp(0, 120) as usize; + let (len, code) = SCALEFACTOR_CODES[value]; + w.write_bits(code, u32::from(len)); + prev += value as i32 - 60; + } + w.write_bit(false); // pulse_data_present + w.write_bit(false); // tns_data_present + w.write_bit(false); // gain_control_data_present + // spectral_data + let windows = if c.short { 8 } else { 1 }; + for b in 0..c.max_sfb { + let book = c.books[b]; + if book == 0 { + continue; + } + let cb = &CODEBOOKS[usize::from(book) - 1]; + let dim = usize::from(cb.dim); + let (lo, hi) = (usize::from(c.swb[b]), usize::from(c.swb[b + 1])); + for win in 0..windows { + let base = if c.short { win * SHORT_LEN } else { 0 }; + let mut k = lo; + while k < hi { + let end = (k + dim).min(hi); + write_tuple(w, cb, &c.quant[base + k..base + end]); + k += dim; + } + } + } +} + +/// Which channel element carries which of the caller's channels. The caller +/// speaks film order (`FL, FR, FC, LFE, BL, BR, SL, SR`); the bitstream wants +/// centre first and LFE last (ISO/IEC 14496-3 tbl 1.19). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Element { + Sce, + Cpe, + Lfe, +} + +fn element_layout(channels: usize) -> Vec<(Element, Vec)> { + match channels { + 1 => vec![(Element::Sce, vec![0])], + 2 => vec![(Element::Cpe, vec![0, 1])], + 3 => vec![(Element::Sce, vec![2]), (Element::Cpe, vec![0, 1])], + 4 => vec![ + (Element::Sce, vec![2]), + (Element::Cpe, vec![0, 1]), + (Element::Sce, vec![3]), + ], + 5 => vec![ + (Element::Sce, vec![2]), + (Element::Cpe, vec![0, 1]), + (Element::Cpe, vec![3, 4]), + ], + 6 => vec![ + (Element::Sce, vec![2]), + (Element::Cpe, vec![0, 1]), + (Element::Cpe, vec![4, 5]), + (Element::Lfe, vec![3]), + ], + 8 => vec![ + (Element::Sce, vec![2]), + (Element::Cpe, vec![0, 1]), + (Element::Cpe, vec![6, 7]), + (Element::Cpe, vec![4, 5]), + (Element::Lfe, vec![3]), + ], + n => (0..n).map(|i| (Element::Sce, vec![i])).collect(), + } +} diff --git a/crates/ec-aac/src/huffman.rs b/crates/ec-aac/src/huffman.rs new file mode 100644 index 00000000..4a5f0591 --- /dev/null +++ b/crates/ec-aac/src/huffman.rs @@ -0,0 +1,85 @@ +//! Prefix-code decoding for the spectral and scalefactor codebooks. +//! +//! Every codebook is a complete prefix code (Kraft sum exactly 1, asserted in +//! the tests), so a binary tree walk is total: no bit pattern falls off the +//! tree, and the only failure a stream can produce is running out of bits. + +use ec_core::{BitReader, Error, Result}; + +/// A codebook as a walkable binary tree. `nodes[i]` holds the two children of +/// node `i`; a non-negative child is another node, a negative one is the leaf +/// `-(index + 1)`. +#[derive(Debug, Clone)] +pub struct Tree { + nodes: Vec<[i32; 2]>, +} + +impl Tree { + /// Builds the tree from `(length, code)` by symbol index. + /// + /// # Panics + /// If two symbols share a prefix, which would mean a corrupt table. + pub fn new(codes: &[(u8, u32)]) -> Tree { + let mut nodes = vec![[0i32; 2]]; + for (symbol, &(len, code)) in codes.iter().enumerate() { + let mut at = 0usize; + for depth in (0..len).rev() { + let bit = ((code >> depth) & 1) as usize; + let last = depth == 0; + if last { + assert_eq!(nodes[at][bit], 0, "codebook prefix collision"); + nodes[at][bit] = -(symbol as i32 + 1); + } else if nodes[at][bit] == 0 { + nodes.push([0i32; 2]); + let next = nodes.len() as i32 - 1; + nodes[at][bit] = next; + at = next as usize; + } else { + at = nodes[at][bit] as usize; + } + } + } + Tree { nodes } + } + + /// Reads one symbol index. + pub fn decode(&self, r: &mut BitReader<'_>) -> Result { + let mut at = 0usize; + loop { + let bit = usize::from(r.read_bit()?); + let next = self.nodes[at][bit]; + if next < 0 { + return Ok((-next - 1) as usize); + } + if next == 0 { + return Err(Error::corrupt("aac: undefined Huffman code")); + } + at = next as usize; + } + } +} + +/// The eleven spectral trees plus the scalefactor tree, built once per decoder. +#[derive(Debug, Clone)] +pub struct Books { + pub spectral: Vec, + pub scalefactor: Tree, +} + +impl Books { + pub fn new() -> Books { + Books { + spectral: crate::tables::CODEBOOKS + .iter() + .map(|cb| Tree::new(cb.codes)) + .collect(), + scalefactor: Tree::new(crate::tables::SCALEFACTOR_CODES), + } + } +} + +impl Default for Books { + fn default() -> Books { + Books::new() + } +} diff --git a/crates/ec-aac/src/lib.rs b/crates/ec-aac/src/lib.rs new file mode 100644 index 00000000..1f007bb4 --- /dev/null +++ b/crates/ec-aac/src/lib.rs @@ -0,0 +1,230 @@ +//! AAC-LC: decoder (mono through 7.1) and encoder, in safe Rust. +//! +//! # Where the tables come from +//! +//! The Huffman codebooks, the scalefactor codebook and the scalefactor-band +//! offsets in [`tables`] were **derived**, not transcribed: `scripts/derive-aac-tables.py` +//! synthesises access units whose spectral payload is a chosen bit string, has a +//! reference decoder decode them, and reads the quantised spectrum back through +//! the inverse MDCT. Walking the binary tree of probes enumerates each codebook +//! in about `2M` frames for `M` codewords. Every table came out with a Kraft +//! sum of exactly 1 and the entry count ISO/IEC 14496-3 prescribes, which is +//! what makes the derivation self-checking rather than a transcription to be +//! trusted. +//! +//! # What is here and what is not +//! +//! 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 +//! [`AacDecoder::output_sample_rate`] rather than silently claiming the +//! extension rate. See `sbr_is_reported_not_silently_upsampled` in the tests. + +#![forbid(unsafe_code)] + +mod config; +mod decode; +mod encode; +mod huffman; +pub mod tables; + +pub use config::{ + AOT_AAC_LC, AOT_PS, AOT_SBR, AdtsHeader, AudioSpecificConfig, ProgramConfig, + audio_specific_config_bytes, channels_for_config, config_for_channels, is_adts, parse_adts, + parse_audio_specific_config, parse_program_config, sample_rate_for_index, sf_index_for_rate, + write_adts_header, write_audio_specific_config, +}; +pub use decode::{FRAME_LEN, WindowSequence}; +pub use ec_core::{Error, Result}; +pub use encode::{AacEncoder, AacEncoderConfig, EncodedPacket, WindowShape}; +pub use tables::SAMPLE_RATES; + +use decode::BlockDecoder; +use ec_core::BitReader; + +/// What this decoder does with a High Efficiency stream. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +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. + CoreOnly, +} + +/// One decoded frame: interleaved `f32` in film channel order. +#[derive(Clone, Debug, Default)] +pub struct DecodedAudio { + pub sample_rate: u32, + pub channels: u16, + /// Interleaved samples, `frames() * channels` of them. + pub samples: Vec, + pub pts: Option, +} + +impl DecodedAudio { + /// Sample frames in this block. + pub fn frames(&self) -> usize { + if self.channels == 0 { + 0 + } else { + self.samples.len() / usize::from(self.channels) + } + } +} + +/// Bitstream element order to the film order `FL, FR, FC, LFE, BL, BR, SL, SR` +/// that every downmix in this family folds (ISO/IEC 14496-3 tbl 1.19: the +/// elements arrive centre first, LFE last). +fn film_order(channels: usize) -> &'static [usize] { + match channels { + 3 => &[1, 2, 0], + 4 => &[1, 2, 0, 3], + 5 => &[1, 2, 0, 3, 4], + 6 => &[1, 2, 0, 5, 3, 4], + 8 => &[1, 2, 0, 7, 5, 6, 3, 4], + _ => &[0, 1, 2, 3, 4, 5, 6, 7], + } +} + +/// An AAC-LC decoder. +pub struct AacDecoder { + block: BlockDecoder, + config: Option, + sample_rate: u32, + channels: u16, +} + +impl AacDecoder { + /// A decoder with no configuration yet: it will take its parameters from + /// the first ADTS header it sees. + pub fn new() -> AacDecoder { + AacDecoder { + block: BlockDecoder::new(3), + config: None, + sample_rate: 0, + channels: 0, + } + } + + /// A decoder configured from a parsed AudioSpecificConfig. + pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder { + let mut d = AacDecoder::new(); + d.block.set_sf_index(cfg.sf_index); + d.sample_rate = cfg.sample_rate; + d.channels = cfg.channels; + d.config = Some(cfg); + d + } + + /// A decoder configured from raw AudioSpecificConfig bytes -- an mp4 + /// `esds` payload or a Matroska `CodecPrivate`. + pub fn with_config_bytes(data: &[u8]) -> Result { + Ok(AacDecoder::with_config(parse_audio_specific_config(data)?)) + } + + /// The configuration this decoder was built with, if any. + pub fn config(&self) -> Option<&AudioSpecificConfig> { + self.config.as_ref() + } + + /// 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, + _ => 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. + pub fn output_sample_rate(&self) -> Option { + self.config.as_ref().map(|c| c.sample_rate) + } + + /// Decodes one packet: a raw `raw_data_block`, or one or more ADTS frames. + pub fn decode(&mut self, packet: &[u8], pts: Option) -> Result { + let mut planes: Vec> = Vec::new(); + if is_adts(packet) { + let mut at = 0usize; + while at + 7 <= packet.len() { + let header = parse_adts(&packet[at..])?; + let end = (at + header.frame_length).min(packet.len()); + let body = &packet[at + header.header_len..end]; + if self.config.is_none() { + self.sample_rate = header.sample_rate; + self.channels = header.channels; + self.block.set_sf_index(header.sf_index); + } + let mut r = BitReader::new(body); + for _ in 0..header.raw_blocks { + let block = self.block.raw_data_block(&mut r)?; + merge(&mut planes, block); + if r.bits_remaining() < 8 { + break; + } + } + if header.frame_length == 0 { + break; + } + at += header.frame_length; + } + } else { + let mut r = BitReader::new(packet); + planes = self.block.raw_data_block(&mut r)?; + } + let channels = planes.len(); + if channels == 0 { + return Ok(DecodedAudio { + sample_rate: self.sample_rate, + channels: self.channels, + samples: Vec::new(), + pts, + }); + } + if self.channels == 0 { + self.channels = channels as u16; + } + let order = film_order(channels); + let frames = planes[0].len(); + let mut samples = vec![0.0f32; frames * channels]; + for (out_ch, &src) in order.iter().take(channels).enumerate() { + let plane = &planes[src.min(channels - 1)]; + for (i, &v) in plane.iter().enumerate() { + samples[i * channels + out_ch] = v; + } + } + Ok(DecodedAudio { + sample_rate: self.sample_rate, + channels: channels as u16, + samples, + pts, + }) + } +} + +/// Appends a block's planes to the packet's, growing the plane count if a later +/// `raw_data_block` carries more channels than an earlier one. +fn merge(planes: &mut Vec>, block: Vec>) { + if planes.is_empty() { + *planes = block; + return; + } + for (i, plane) in block.into_iter().enumerate() { + match planes.get_mut(i) { + Some(dst) => dst.extend_from_slice(&plane), + None => planes.push(plane), + } + } +} + +impl Default for AacDecoder { + fn default() -> AacDecoder { + AacDecoder::new() + } +} diff --git a/crates/ec-aac/src/tables.rs b/crates/ec-aac/src/tables.rs new file mode 100644 index 00000000..02407588 --- /dev/null +++ b/crates/ec-aac/src/tables.rs @@ -0,0 +1,1609 @@ +//! Normative AAC tables (ISO/IEC 14496-3 §4.6.2, §4.6.9, tbl 4.140). +//! +//! Every number here was derived by black-box probing of a reference decoder, +//! not copied from an implementation: `scripts/derive-aac-tables.py` synthesises +//! access units whose spectral payload is a chosen bit string, decodes them, and +//! reads the quantised spectrum back through the inverse MDCT. Each codebook +//! came out with a Kraft sum of exactly 1 and the entry count the standard +//! prescribes, which is what makes the derivation self-checking. +/// Codebook 1: dim 4, lav 1, signed. +static HCB1: [(u8, u32); 81] = [ + (11, 2040), + (9, 497), + (11, 2045), + (10, 1013), + (7, 104), + (10, 1008), + (11, 2039), + (9, 492), + (11, 2037), + (10, 1009), + (7, 114), + (10, 1012), + (7, 116), + (5, 17), + (7, 118), + (9, 491), + (7, 108), + (10, 1014), + (11, 2044), + (9, 481), + (11, 2033), + (9, 496), + (7, 97), + (9, 502), + (11, 2034), + (9, 490), + (11, 2043), + (9, 498), + (7, 105), + (9, 493), + (7, 119), + (5, 23), + (7, 111), + (9, 486), + (7, 100), + (9, 485), + (7, 103), + (5, 21), + (7, 98), + (5, 18), + (1, 0), + (5, 20), + (7, 101), + (5, 22), + (7, 109), + (9, 489), + (7, 99), + (9, 484), + (7, 107), + (5, 19), + (7, 113), + (9, 483), + (7, 112), + (9, 499), + (11, 2046), + (9, 487), + (11, 2035), + (9, 495), + (7, 96), + (9, 494), + (11, 2032), + (9, 482), + (11, 2042), + (10, 1011), + (7, 106), + (9, 488), + (7, 117), + (5, 16), + (7, 115), + (9, 500), + (7, 110), + (10, 1015), + (11, 2038), + (9, 480), + (11, 2041), + (10, 1010), + (7, 102), + (9, 501), + (11, 2047), + (9, 503), + (11, 2036), +]; +/// Codebook 2: dim 4, lav 1, signed. +static HCB2: [(u8, u32); 81] = [ + (9, 499), + (7, 111), + (9, 509), + (8, 235), + (6, 35), + (8, 234), + (9, 503), + (8, 232), + (9, 506), + (8, 242), + (6, 45), + (7, 112), + (6, 32), + (5, 6), + (6, 43), + (7, 110), + (6, 40), + (8, 233), + (9, 505), + (7, 102), + (8, 248), + (8, 231), + (6, 27), + (8, 241), + (9, 500), + (7, 107), + (9, 501), + (8, 236), + (6, 42), + (7, 108), + (6, 44), + (5, 10), + (6, 39), + (7, 103), + (6, 26), + (8, 245), + (6, 36), + (5, 8), + (6, 31), + (5, 9), + (3, 0), + (5, 7), + (6, 29), + (5, 11), + (6, 48), + (8, 239), + (6, 28), + (7, 100), + (6, 30), + (5, 12), + (6, 41), + (8, 243), + (6, 47), + (8, 240), + (9, 508), + (7, 113), + (9, 498), + (8, 244), + (6, 33), + (8, 230), + (8, 247), + (7, 104), + (9, 504), + (8, 238), + (6, 34), + (7, 101), + (6, 49), + (4, 2), + (6, 38), + (8, 237), + (6, 37), + (7, 106), + (9, 507), + (7, 114), + (9, 510), + (7, 105), + (6, 46), + (8, 246), + (9, 511), + (7, 109), + (9, 502), +]; +/// Codebook 3: dim 4, lav 2, unsigned. +static HCB3: [(u8, u32); 81] = [ + (1, 0), + (4, 9), + (8, 239), + (4, 11), + (5, 25), + (8, 240), + (9, 491), + (9, 486), + (10, 1010), + (4, 10), + (6, 53), + (9, 495), + (6, 52), + (6, 55), + (9, 489), + (9, 493), + (9, 487), + (10, 1011), + (9, 494), + (10, 1005), + (13, 8186), + (9, 492), + (9, 498), + (11, 2041), + (11, 2040), + (10, 1016), + (12, 4088), + (4, 8), + (6, 56), + (10, 1014), + (6, 54), + (7, 117), + (10, 1009), + (10, 1003), + (10, 1004), + (12, 4084), + (5, 24), + (7, 118), + (11, 2036), + (6, 57), + (7, 116), + (10, 1007), + (9, 499), + (9, 500), + (11, 2038), + (9, 488), + (10, 1002), + (13, 8188), + (8, 242), + (9, 497), + (12, 4091), + (10, 1013), + (11, 2035), + (12, 4092), + (8, 238), + (10, 1015), + (15, 32766), + (9, 496), + (11, 2037), + (15, 32765), + (13, 8187), + (14, 16378), + (16, 65535), + (8, 241), + (10, 1008), + (14, 16380), + (9, 490), + (10, 1006), + (14, 16379), + (12, 4086), + (12, 4090), + (15, 32764), + (11, 2034), + (12, 4085), + (16, 65534), + (10, 1012), + (11, 2039), + (15, 32763), + (12, 4087), + (12, 4089), + (15, 32762), +]; +/// Codebook 4: dim 4, lav 2, unsigned. +static HCB4: [(u8, u32); 81] = [ + (4, 7), + (5, 22), + (8, 246), + (5, 24), + (4, 8), + (8, 239), + (9, 495), + (8, 243), + (11, 2040), + (5, 25), + (5, 23), + (8, 237), + (5, 21), + (4, 1), + (8, 226), + (8, 240), + (7, 112), + (10, 1008), + (9, 494), + (8, 241), + (11, 2042), + (8, 238), + (8, 228), + (10, 1010), + (11, 2038), + (10, 1007), + (11, 2045), + (4, 5), + (5, 20), + (8, 242), + (4, 9), + (4, 4), + (8, 229), + (8, 244), + (8, 232), + (10, 1012), + (4, 6), + (4, 2), + (8, 231), + (4, 3), + (4, 0), + (7, 107), + (8, 227), + (7, 105), + (9, 499), + (8, 235), + (8, 230), + (10, 1014), + (7, 110), + (7, 106), + (9, 500), + (10, 1004), + (9, 496), + (10, 1017), + (8, 245), + (8, 236), + (11, 2043), + (8, 234), + (7, 111), + (10, 1015), + (11, 2041), + (10, 1011), + (12, 4095), + (8, 233), + (7, 109), + (10, 1016), + (7, 108), + (7, 104), + (9, 501), + (10, 1006), + (9, 498), + (11, 2036), + (11, 2039), + (10, 1009), + (12, 4094), + (10, 1005), + (9, 497), + (11, 2037), + (11, 2046), + (10, 1013), + (11, 2044), +]; +/// Codebook 5: dim 2, lav 4, signed. +static HCB5: [(u8, u32); 81] = [ + (13, 8191), + (12, 4087), + (11, 2036), + (11, 2024), + (10, 1009), + (11, 2030), + (11, 2041), + (12, 4088), + (13, 8189), + (12, 4093), + (11, 2033), + (10, 1000), + (9, 488), + (8, 240), + (9, 492), + (10, 1006), + (11, 2034), + (12, 4090), + (12, 4084), + (10, 1007), + (9, 498), + (8, 232), + (7, 112), + (8, 236), + (9, 496), + (10, 1002), + (11, 2035), + (11, 2027), + (9, 491), + (8, 234), + (5, 26), + (4, 8), + (5, 25), + (8, 238), + (9, 495), + (11, 2029), + (10, 1008), + (8, 242), + (7, 115), + (4, 11), + (1, 0), + (4, 10), + (7, 113), + (8, 243), + (11, 2025), + (11, 2031), + (9, 494), + (8, 239), + (5, 24), + (4, 9), + (5, 27), + (8, 235), + (9, 489), + (11, 2028), + (11, 2038), + (10, 1003), + (9, 499), + (8, 237), + (7, 114), + (8, 233), + (9, 497), + (10, 1005), + (11, 2039), + (12, 4086), + (11, 2032), + (10, 1001), + (9, 493), + (8, 241), + (9, 490), + (10, 1004), + (11, 2040), + (12, 4089), + (13, 8188), + (12, 4092), + (12, 4085), + (11, 2026), + (10, 1011), + (10, 1010), + (11, 2037), + (12, 4091), + (13, 8190), +]; +/// Codebook 6: dim 2, lav 4, signed. +static HCB6: [(u8, u32); 81] = [ + (11, 2046), + (10, 1021), + (9, 497), + (9, 491), + (9, 500), + (9, 490), + (9, 496), + (10, 1020), + (11, 2045), + (10, 1014), + (9, 485), + (8, 234), + (7, 108), + (7, 113), + (7, 104), + (8, 240), + (9, 486), + (10, 1015), + (9, 499), + (8, 239), + (6, 50), + (6, 39), + (6, 40), + (6, 38), + (6, 49), + (8, 235), + (9, 503), + (9, 488), + (7, 111), + (6, 46), + (4, 8), + (4, 4), + (4, 6), + (6, 41), + (7, 107), + (9, 494), + (9, 495), + (7, 114), + (6, 45), + (4, 2), + (4, 0), + (4, 3), + (6, 47), + (7, 115), + (9, 506), + (9, 487), + (7, 110), + (6, 43), + (4, 7), + (4, 1), + (4, 5), + (6, 44), + (7, 109), + (9, 492), + (9, 505), + (8, 238), + (6, 48), + (6, 36), + (6, 42), + (6, 37), + (6, 51), + (8, 236), + (9, 498), + (10, 1016), + (9, 484), + (8, 237), + (7, 106), + (7, 112), + (7, 105), + (7, 116), + (8, 241), + (10, 1018), + (11, 2047), + (10, 1017), + (9, 502), + (9, 493), + (9, 504), + (9, 489), + (9, 501), + (10, 1019), + (11, 2044), +]; +/// Codebook 7: dim 2, lav 7, unsigned. +static HCB7: [(u8, u32); 64] = [ + (1, 0), + (3, 5), + (6, 55), + (7, 116), + (8, 242), + (9, 491), + (10, 1005), + (11, 2039), + (3, 4), + (4, 12), + (6, 53), + (7, 113), + (8, 236), + (8, 238), + (9, 494), + (9, 501), + (6, 54), + (6, 52), + (7, 114), + (8, 234), + (8, 241), + (9, 489), + (9, 499), + (10, 1013), + (7, 115), + (7, 112), + (8, 235), + (8, 240), + (9, 497), + (9, 496), + (10, 1004), + (10, 1018), + (8, 243), + (8, 237), + (9, 488), + (9, 495), + (10, 1007), + (10, 1009), + (10, 1017), + (11, 2043), + (9, 493), + (8, 239), + (9, 490), + (9, 498), + (10, 1011), + (10, 1016), + (11, 2041), + (11, 2044), + (10, 1006), + (9, 492), + (9, 500), + (10, 1012), + (10, 1015), + (11, 2040), + (12, 4093), + (12, 4094), + (11, 2038), + (10, 1008), + (10, 1010), + (10, 1014), + (11, 2042), + (11, 2045), + (12, 4092), + (12, 4095), +]; +/// Codebook 8: dim 2, lav 7, unsigned. +static HCB8: [(u8, u32); 64] = [ + (5, 14), + (4, 5), + (5, 16), + (6, 48), + (7, 111), + (8, 241), + (9, 506), + (10, 1022), + (4, 3), + (3, 0), + (4, 4), + (5, 18), + (6, 44), + (7, 106), + (7, 117), + (8, 248), + (5, 15), + (4, 2), + (4, 6), + (5, 20), + (6, 46), + (7, 105), + (7, 114), + (8, 245), + (6, 47), + (5, 17), + (5, 19), + (6, 42), + (6, 50), + (7, 108), + (8, 236), + (8, 250), + (7, 113), + (6, 43), + (6, 45), + (6, 49), + (7, 109), + (7, 112), + (8, 242), + (9, 505), + (8, 239), + (7, 104), + (6, 51), + (7, 107), + (7, 110), + (8, 238), + (8, 249), + (10, 1020), + (9, 504), + (7, 116), + (7, 115), + (8, 237), + (8, 240), + (8, 246), + (9, 502), + (9, 509), + (10, 1021), + (8, 243), + (8, 244), + (8, 247), + (9, 503), + (9, 507), + (9, 508), + (10, 1023), +]; +/// Codebook 9: dim 2, lav 12, unsigned. +static HCB9: [(u8, u32); 169] = [ + (1, 0), + (3, 5), + (6, 55), + (8, 231), + (9, 478), + (10, 974), + (10, 985), + (11, 1992), + (11, 1997), + (12, 4040), + (12, 4061), + (13, 8164), + (13, 8172), + (3, 4), + (4, 12), + (6, 53), + (7, 114), + (8, 234), + (8, 237), + (9, 482), + (10, 977), + (10, 979), + (10, 992), + (11, 2008), + (12, 4047), + (12, 4053), + (6, 54), + (6, 52), + (7, 113), + (8, 232), + (8, 236), + (9, 481), + (10, 975), + (10, 989), + (10, 987), + (11, 2000), + (12, 4039), + (12, 4052), + (12, 4068), + (8, 230), + (7, 112), + (8, 233), + (9, 477), + (9, 483), + (10, 978), + (10, 988), + (11, 1996), + (11, 1994), + (11, 2014), + (12, 4056), + (12, 4074), + (13, 8155), + (9, 479), + (8, 235), + (9, 476), + (9, 486), + (10, 981), + (10, 990), + (11, 1995), + (11, 2013), + (11, 2012), + (12, 4045), + (12, 4066), + (12, 4071), + (13, 8161), + (10, 976), + (9, 480), + (9, 484), + (10, 982), + (11, 1989), + (11, 2001), + (11, 2011), + (12, 4050), + (11, 2016), + (12, 4057), + (12, 4075), + (13, 8163), + (13, 8169), + (11, 1988), + (9, 485), + (10, 983), + (11, 1990), + (11, 1999), + (11, 2010), + (12, 4043), + (12, 4058), + (12, 4067), + (12, 4073), + (13, 8166), + (13, 8179), + (13, 8183), + (11, 2003), + (10, 984), + (10, 993), + (11, 2004), + (11, 2009), + (12, 4051), + (12, 4062), + (13, 8157), + (13, 8153), + (13, 8162), + (13, 8170), + (13, 8177), + (13, 8182), + (11, 2002), + (10, 980), + (10, 986), + (11, 1991), + (11, 2007), + (11, 2018), + (12, 4046), + (12, 4059), + (13, 8152), + (13, 8174), + (14, 16368), + (13, 8180), + (14, 16370), + (11, 2017), + (10, 991), + (11, 1993), + (11, 2006), + (12, 4042), + (12, 4048), + (12, 4069), + (12, 4070), + (13, 8171), + (13, 8175), + (14, 16371), + (14, 16372), + (14, 16373), + (12, 4064), + (11, 1998), + (11, 2005), + (12, 4038), + (12, 4049), + (12, 4065), + (13, 8160), + (13, 8168), + (13, 8176), + (14, 16369), + (14, 16376), + (14, 16374), + (15, 32764), + (12, 4072), + (11, 2015), + (12, 4041), + (12, 4055), + (12, 4060), + (13, 8156), + (13, 8159), + (13, 8173), + (13, 8181), + (14, 16377), + (14, 16379), + (15, 32765), + (15, 32766), + (13, 8167), + (12, 4044), + (12, 4054), + (12, 4063), + (13, 8158), + (13, 8154), + (13, 8165), + (13, 8178), + (14, 16378), + (14, 16375), + (14, 16380), + (14, 16381), + (15, 32767), +]; +/// Codebook 10: dim 2, lav 12, unsigned. +static HCB10: [(u8, u32); 169] = [ + (6, 34), + (5, 8), + (6, 29), + (6, 38), + (7, 95), + (8, 211), + (9, 463), + (10, 976), + (10, 983), + (10, 1005), + (11, 2032), + (11, 2038), + (12, 4093), + (5, 7), + (4, 0), + (4, 1), + (5, 9), + (6, 32), + (7, 84), + (7, 96), + (8, 213), + (8, 220), + (9, 468), + (10, 973), + (10, 990), + (11, 2023), + (6, 28), + (4, 2), + (5, 6), + (5, 12), + (6, 30), + (6, 40), + (7, 91), + (8, 205), + (8, 217), + (9, 462), + (9, 476), + (10, 985), + (10, 1009), + (6, 37), + (5, 11), + (5, 10), + (5, 13), + (6, 36), + (7, 87), + (7, 97), + (8, 204), + (8, 221), + (9, 460), + (9, 478), + (10, 979), + (10, 999), + (7, 93), + (6, 33), + (6, 31), + (6, 35), + (6, 39), + (7, 89), + (7, 100), + (8, 216), + (8, 223), + (9, 466), + (9, 482), + (10, 989), + (10, 1006), + (8, 209), + (7, 85), + (6, 41), + (7, 86), + (7, 88), + (7, 98), + (8, 206), + (8, 224), + (8, 226), + (9, 474), + (10, 980), + (10, 995), + (11, 2027), + (9, 457), + (7, 94), + (7, 90), + (7, 92), + (7, 99), + (8, 202), + (8, 218), + (9, 455), + (9, 458), + (9, 480), + (10, 987), + (10, 1000), + (11, 2028), + (9, 483), + (8, 210), + (8, 203), + (8, 208), + (8, 215), + (8, 219), + (9, 454), + (9, 469), + (9, 472), + (10, 970), + (10, 986), + (11, 2026), + (11, 2033), + (9, 481), + (8, 212), + (8, 207), + (8, 214), + (8, 222), + (8, 225), + (9, 464), + (9, 470), + (10, 977), + (10, 981), + (10, 1010), + (11, 2030), + (11, 2043), + (10, 1001), + (9, 461), + (9, 456), + (9, 459), + (9, 465), + (9, 471), + (9, 479), + (10, 975), + (10, 992), + (10, 1007), + (11, 2022), + (11, 2040), + (12, 4090), + (10, 1003), + (9, 477), + (9, 467), + (9, 473), + (9, 475), + (10, 978), + (10, 972), + (10, 988), + (10, 1002), + (11, 2029), + (11, 2035), + (11, 2041), + (12, 4089), + (11, 2034), + (10, 974), + (9, 484), + (10, 971), + (10, 984), + (10, 982), + (10, 994), + (10, 997), + (11, 2024), + (11, 2036), + (11, 2037), + (11, 2039), + (12, 4091), + (11, 2042), + (10, 1004), + (10, 991), + (10, 993), + (10, 996), + (10, 998), + (10, 1008), + (11, 2025), + (11, 2031), + (12, 4088), + (12, 4094), + (12, 4092), + (12, 4095), +]; +/// Codebook 11: dim 2, lav 16, unsigned, escape. +static HCB11: [(u8, u32); 289] = [ + (4, 0), + (5, 6), + (6, 25), + (7, 61), + (8, 156), + (8, 198), + (9, 423), + (10, 912), + (10, 962), + (10, 991), + (11, 2022), + (11, 2035), + (12, 4091), + (11, 2028), + (12, 4090), + (12, 4094), + (10, 910), + (5, 5), + (4, 1), + (5, 8), + (6, 20), + (7, 55), + (7, 66), + (8, 146), + (8, 175), + (9, 401), + (9, 421), + (9, 437), + (10, 926), + (10, 960), + (10, 930), + (10, 973), + (11, 2006), + (8, 174), + (6, 23), + (5, 7), + (5, 9), + (6, 24), + (7, 57), + (7, 64), + (8, 142), + (8, 163), + (8, 184), + (9, 409), + (9, 428), + (9, 449), + (10, 945), + (10, 918), + (10, 958), + (10, 970), + (8, 157), + (7, 60), + (6, 21), + (6, 22), + (6, 26), + (7, 59), + (7, 68), + (8, 145), + (8, 165), + (8, 190), + (9, 406), + (9, 430), + (9, 441), + (10, 929), + (10, 913), + (10, 933), + (10, 981), + (8, 148), + (8, 154), + (7, 54), + (7, 56), + (7, 58), + (7, 65), + (8, 140), + (8, 155), + (8, 176), + (8, 195), + (9, 414), + (9, 427), + (9, 444), + (10, 927), + (10, 911), + (10, 937), + (10, 975), + (8, 147), + (8, 191), + (7, 62), + (7, 63), + (7, 67), + (7, 69), + (8, 158), + (8, 167), + (8, 185), + (9, 404), + (9, 418), + (9, 442), + (9, 451), + (10, 934), + (10, 935), + (10, 955), + (10, 980), + (8, 159), + (9, 416), + (8, 143), + (8, 141), + (8, 144), + (8, 152), + (8, 166), + (8, 182), + (8, 196), + (9, 415), + (9, 431), + (9, 447), + (10, 921), + (10, 959), + (10, 948), + (10, 969), + (10, 999), + (8, 168), + (9, 438), + (8, 171), + (8, 164), + (8, 170), + (8, 178), + (8, 194), + (8, 197), + (9, 408), + (9, 420), + (9, 440), + (10, 908), + (10, 932), + (10, 964), + (10, 966), + (10, 989), + (10, 1000), + (8, 173), + (10, 943), + (9, 402), + (8, 189), + (8, 188), + (9, 398), + (9, 407), + (9, 410), + (9, 419), + (9, 433), + (10, 909), + (10, 920), + (10, 951), + (10, 979), + (10, 977), + (10, 987), + (11, 2013), + (8, 180), + (10, 990), + (9, 425), + (9, 411), + (9, 412), + (9, 417), + (9, 426), + (9, 429), + (9, 435), + (10, 907), + (10, 946), + (10, 952), + (10, 974), + (10, 993), + (10, 992), + (11, 2002), + (11, 2021), + (8, 183), + (11, 2019), + (9, 443), + (9, 424), + (9, 422), + (9, 432), + (9, 434), + (9, 439), + (10, 923), + (10, 922), + (10, 954), + (10, 949), + (10, 982), + (11, 2007), + (10, 996), + (11, 2008), + (11, 2026), + (8, 186), + (11, 2024), + (10, 928), + (9, 445), + (9, 436), + (10, 906), + (9, 452), + (10, 914), + (10, 938), + (10, 944), + (10, 956), + (10, 983), + (11, 2004), + (11, 2012), + (11, 2011), + (11, 2005), + (11, 2032), + (8, 193), + (11, 2043), + (10, 968), + (10, 931), + (10, 917), + (10, 925), + (10, 940), + (10, 942), + (10, 965), + (10, 984), + (10, 994), + (10, 998), + (11, 2020), + (11, 2023), + (11, 2016), + (11, 2025), + (11, 2039), + (9, 400), + (11, 2034), + (10, 915), + (9, 446), + (9, 448), + (10, 916), + (10, 919), + (10, 941), + (10, 963), + (10, 961), + (10, 978), + (11, 2010), + (11, 2009), + (11, 2015), + (11, 2027), + (11, 2036), + (11, 2042), + (9, 405), + (11, 2040), + (10, 957), + (10, 924), + (10, 939), + (10, 936), + (10, 947), + (10, 953), + (10, 976), + (10, 995), + (10, 997), + (11, 2018), + (11, 2014), + (11, 2029), + (11, 2033), + (11, 2041), + (11, 2044), + (9, 403), + (12, 4093), + (10, 988), + (10, 950), + (10, 967), + (10, 972), + (10, 971), + (10, 985), + (10, 986), + (11, 2003), + (11, 2017), + (11, 2030), + (11, 2031), + (11, 2037), + (11, 2038), + (12, 4092), + (12, 4095), + (9, 413), + (9, 450), + (8, 181), + (8, 161), + (8, 150), + (8, 151), + (8, 149), + (8, 153), + (8, 160), + (8, 162), + (8, 172), + (8, 169), + (8, 177), + (8, 179), + (8, 187), + (8, 192), + (9, 399), + (5, 4), +]; +/// Scalefactor codebook: index is the coded value, delta = index - 60. +static HCB_SF: [(u8, u32); 121] = [ + (18, 262120), + (18, 262118), + (18, 262119), + (18, 262117), + (19, 524277), + (19, 524273), + (19, 524269), + (19, 524278), + (19, 524270), + (19, 524271), + (19, 524272), + (19, 524284), + (19, 524285), + (19, 524287), + (19, 524286), + (19, 524279), + (19, 524280), + (19, 524283), + (19, 524281), + (18, 262116), + (19, 524282), + (18, 262115), + (17, 131055), + (17, 131056), + (16, 65525), + (17, 131054), + (16, 65522), + (16, 65523), + (16, 65524), + (16, 65521), + (15, 32758), + (15, 32759), + (14, 16377), + (14, 16373), + (14, 16375), + (14, 16371), + (14, 16374), + (14, 16370), + (13, 8183), + (13, 8181), + (12, 4089), + (12, 4087), + (12, 4086), + (11, 2041), + (12, 4084), + (11, 2040), + (10, 1017), + (10, 1015), + (10, 1013), + (9, 504), + (9, 503), + (8, 250), + (8, 248), + (8, 246), + (7, 121), + (6, 58), + (6, 56), + (5, 26), + (4, 11), + (3, 4), + (1, 0), + (4, 10), + (4, 12), + (5, 27), + (6, 57), + (6, 59), + (7, 120), + (7, 122), + (8, 247), + (8, 249), + (9, 502), + (9, 505), + (10, 1012), + (10, 1014), + (10, 1016), + (11, 2037), + (11, 2036), + (11, 2038), + (11, 2039), + (12, 4085), + (12, 4088), + (13, 8180), + (13, 8182), + (13, 8184), + (14, 16376), + (14, 16372), + (16, 65520), + (15, 32756), + (16, 65526), + (15, 32757), + (18, 262114), + (19, 524249), + (19, 524250), + (19, 524251), + (19, 524252), + (19, 524253), + (19, 524254), + (19, 524248), + (19, 524242), + (19, 524243), + (19, 524244), + (19, 524245), + (19, 524246), + (19, 524274), + (19, 524255), + (19, 524263), + (19, 524264), + (19, 524265), + (19, 524266), + (19, 524267), + (19, 524262), + (19, 524256), + (19, 524257), + (19, 524258), + (19, 524259), + (19, 524260), + (19, 524261), + (19, 524247), + (19, 524268), + (19, 524276), + (19, 524275), +]; +/// Scalefactor-band offsets for 1024-line windows, by samplingFrequencyIndex. +pub static SWB_LONG: [&[u16]; 12] = [ + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 108, 120, 132, + 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, + 1024, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 108, 120, 132, + 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, + 1024, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, 112, 124, + 140, 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704, + 744, 784, 824, 864, 904, 944, 984, 1024, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, + 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, + 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 1024, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, + 160, 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, + 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124, + 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124, + 136, 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, + 600, 652, 704, 768, 832, 896, 960, 1024, + ], + &[ + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196, + 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, + 772, 832, 896, 960, 1024, + ], + &[ + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196, + 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, + 772, 832, 896, 960, 1024, + ], + &[ + 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196, + 212, 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, + 772, 832, 896, 960, 1024, + ], + &[ + 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, + 268, 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, + 880, 944, 1024, + ], +]; +/// Scalefactor-band offsets for 128-line windows, by samplingFrequencyIndex. +pub static SWB_SHORT: [&[u16]; 12] = [ + &[0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128], + &[0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128], + &[0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128], + &[0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128], + &[0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128], + &[0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, + ], + &[ + 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, + ], +]; + +/// One spectral codebook's shape. +#[derive(Clone, Copy, Debug)] +pub struct Codebook { + /// Coefficients per Huffman codeword (2 or 4). + pub dim: u8, + /// Largest absolute value the codebook can carry. + pub lav: u8, + /// True when magnitudes are coded and each non-zero one takes a sign bit. + pub unsigned: bool, + /// True for codebook 11, whose magnitude 16 opens an escape sequence. + pub esc: bool, + /// `(length, code)` by tuple index, most-significant bit first. + pub codes: &'static [(u8, u32)], +} + +/// The eleven spectral codebooks, indexed by `sect_cb - 1`. +pub static CODEBOOKS: [Codebook; 11] = [ + Codebook { + dim: 4, + lav: 1, + unsigned: false, + esc: false, + codes: &HCB1, + }, + Codebook { + dim: 4, + lav: 1, + unsigned: false, + esc: false, + codes: &HCB2, + }, + Codebook { + dim: 4, + lav: 2, + unsigned: true, + esc: false, + codes: &HCB3, + }, + Codebook { + dim: 4, + lav: 2, + unsigned: true, + esc: false, + codes: &HCB4, + }, + Codebook { + dim: 2, + lav: 4, + unsigned: false, + esc: false, + codes: &HCB5, + }, + Codebook { + dim: 2, + lav: 4, + unsigned: false, + esc: false, + codes: &HCB6, + }, + Codebook { + dim: 2, + lav: 7, + unsigned: true, + esc: false, + codes: &HCB7, + }, + Codebook { + dim: 2, + lav: 7, + unsigned: true, + esc: false, + codes: &HCB8, + }, + Codebook { + dim: 2, + lav: 12, + unsigned: true, + esc: false, + codes: &HCB9, + }, + Codebook { + dim: 2, + lav: 12, + unsigned: true, + esc: false, + codes: &HCB10, + }, + Codebook { + dim: 2, + lav: 16, + unsigned: true, + esc: true, + codes: &HCB11, + }, +]; + +/// The scalefactor codebook, as a `Codebook`-shaped table of `(length, code)`. +pub static SCALEFACTOR_CODES: &[(u8, u32)] = &HCB_SF; + +/// Sampling frequencies by `samplingFrequencyIndex` (ISO 14496-3 tbl 1.18). +pub static SAMPLE_RATES: [u32; 13] = [ + 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350, +]; + +/// Highest scalefactor band a TNS filter may touch (§4.6.9.1), by +/// samplingFrequencyIndex, for 1024-line windows. Derived the same way as the +/// codebooks: sweeping `max_sfb` against a reference decode and watching where +/// the filter stops being applied. +pub static TNS_MAX_BANDS_LONG: [usize; 13] = [31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39]; + +/// The same limit for 128-line windows. +pub static TNS_MAX_BANDS_SHORT: [usize; 13] = [9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14]; diff --git a/crates/ec-aac/tests/oracle.rs b/crates/ec-aac/tests/oracle.rs new file mode 100644 index 00000000..24a9a7a0 --- /dev/null +++ b/crates/ec-aac/tests/oracle.rs @@ -0,0 +1,458 @@ +//! Decoder and encoder against ffmpeg, on the generated fixtures and on the +//! real library. Every test that needs a fixture or ffmpeg skips loudly when it +//! is absent rather than passing quietly. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_aac::{AacDecoder, AacEncoder, AacEncoderConfig}; + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") +} + +fn have_ffmpeg() -> bool { + Command::new("ffmpeg") + .arg("-version") + .output() + .map(|o| o.status.success()) + .unwrap_or(false) +} + +/// ffmpeg's decode of a file, as planar-by-channel `f32`. +fn ffmpeg_decode(path: &Path, channels: usize) -> Vec> { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) + .output() + .expect("ffmpeg runs"); + assert!( + out.status.success(), + "ffmpeg decode failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + deinterleave(&bytes_to_f32(&out.stdout), channels) +} + +fn bytes_to_f32(bytes: &[u8]) -> Vec { + bytes + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect() +} + +fn deinterleave(samples: &[f32], channels: usize) -> Vec> { + let mut out = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels]; + for (i, &v) in samples.iter().enumerate() { + out[i % channels].push(v); + } + out +} + +/// Our decode of an ADTS file, as planar-by-channel `f32`. +fn our_decode(path: &Path) -> (Vec>, u32) { + let data = std::fs::read(path).expect("fixture readable"); + let mut decoder = AacDecoder::new(); + let mut planes: Vec> = Vec::new(); + let mut rate = 0; + let mut at = 0usize; + while at + 7 <= data.len() { + let header = ec_aac::parse_adts(&data[at..]).expect("adts header"); + let end = (at + header.frame_length).min(data.len()); + let frame = decoder.decode(&data[at..end], None).expect("frame decodes"); + rate = frame.sample_rate; + let ch = usize::from(frame.channels); + if planes.is_empty() { + planes = vec![Vec::new(); ch]; + } + for (i, v) in frame.samples.iter().enumerate() { + planes[i % ch].push(*v); + } + at = end; + } + (planes, rate) +} + +/// Pearson correlation over the overlap of two channels. +fn correlation(a: &[f32], b: &[f32]) -> f64 { + let n = a.len().min(b.len()); + assert!(n > 1024, "not enough overlap to compare: {n} samples"); + let (a, b) = (&a[..n], &b[..n]); + let ma = a.iter().map(|v| f64::from(*v)).sum::() / n as f64; + let mb = b.iter().map(|v| f64::from(*v)).sum::() / n as f64; + let mut num = 0.0; + let mut da = 0.0; + let mut db = 0.0; + for i in 0..n { + let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb); + num += x * y; + da += x * x; + db += y * y; + } + if da == 0.0 || db == 0.0 { + return if da == db { 1.0 } else { 0.0 }; + } + num / (da * db).sqrt() +} + +fn compare(path: &Path) -> Vec { + let (ours, _rate) = our_decode(path); + assert!(!ours.is_empty(), "no channels decoded from {path:?}"); + let theirs = ffmpeg_decode(path, ours.len()); + ours.iter() + .zip(&theirs) + .map(|(a, b)| correlation(a, b)) + .collect() +} + +#[test] +fn adts_fixtures_match_ffmpeg_per_channel() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = fixtures().join("audio"); + let mut checked = 0; + for name in [ + "aac-adts-mono-44100.aac", + "aac-adts-mono-48000.aac", + "aac-adts-stereo-44100.aac", + "aac-adts-stereo-48000.aac", + "aac-adts-5.1-44100.aac", + "aac-adts-5.1-48000.aac", + ] { + let path = dir.join(name); + if !path.exists() { + eprintln!("SKIP {name}: fixture missing"); + continue; + } + let corr = compare(&path); + println!("{name}: {corr:?}"); + for (ch, c) in corr.iter().enumerate() { + assert!( + *c >= 0.999, + "{name} channel {ch} correlation {c:.6} < 0.999" + ); + } + checked += 1; + } + assert!( + checked > 0, + "no AAC fixtures found: run scripts/gen-fixtures.sh" + ); +} + +#[test] +fn mp4_fixtures_match_ffmpeg_per_channel() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = fixtures().join("audio"); + let tmp = std::env::temp_dir().join("ec-aac-mp4-oracle"); + std::fs::create_dir_all(&tmp).expect("temp dir"); + let mut checked = 0; + for name in [ + "aac-mp4-mono-48000.mp4", + "aac-mp4-stereo-48000.mp4", + "aac-mp4-5.1-48000.mp4", + ] { + let path = dir.join(name); + if !path.exists() { + eprintln!("SKIP {name}: fixture missing"); + continue; + } + // The mp4 side of the family is another slice; the elementary stream + // comes out with a stream copy so this test stays about AAC. + let adts = tmp.join(format!("{name}.aac")); + let out = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-i"]) + .arg(&path) + .args(["-c:a", "copy", "-f", "adts"]) + .arg(&adts) + .output() + .expect("ffmpeg runs"); + assert!(out.status.success(), "remux failed for {name}"); + let corr = compare(&adts); + println!("{name}: {corr:?}"); + for (ch, c) in corr.iter().enumerate() { + assert!( + *c >= 0.999, + "{name} channel {ch} correlation {c:.6} < 0.999" + ); + } + checked += 1; + } + assert!(checked > 0, "no AAC-in-mp4 fixtures found"); +} + +/// The contract every downmix in this family folds: FL, FR, FC, LFE, BL, BR. +/// Each channel carries its own tone, mapped explicitly onto the layout, so a +/// wrong element order shows up as the wrong tone on the wrong channel. +#[test] +fn five_one_comes_out_in_film_order() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let tmp = std::env::temp_dir().join("ec-aac-order"); + std::fs::create_dir_all(&tmp).expect("temp dir"); + let src = tmp.join("order.aac"); + // The LFE tone stays low: the reference encoder band-limits that channel, + // and a 1.5 kHz tone would simply not survive the trip. + let tones = [300.0, 700.0, 1100.0, 60.0, 1900.0, 2300.0]; + let mut cmd = Command::new("ffmpeg"); + cmd.args(["-v", "error", "-y"]); + for f in tones { + cmd.args([ + "-f", + "lavfi", + "-i", + &format!("sine=frequency={f}:duration=2:sample_rate=48000"), + ]); + } + let out = cmd + .args([ + "-filter_complex", + "[0:a][1:a][2:a][3:a][4:a][5:a]join=inputs=6:channel_layout=5.1:\ +map=0.0-FL|1.0-FR|2.0-FC|3.0-LFE|4.0-BL|5.0-BR[a]", + "-map", + "[a]", + "-c:a", + "aac", + "-b:a", + "320k", + "-f", + "adts", + ]) + .arg(&src) + .output() + .expect("ffmpeg runs"); + assert!( + out.status.success(), + "tone build failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + let (ours, rate) = our_decode(&src); + assert_eq!(ours.len(), 6, "5.1 decodes to six channels"); + for (ch, plane) in ours.iter().enumerate() { + let peak = dominant_frequency(plane, rate); + let want = tones[ch]; + assert!( + (peak - want).abs() < 40.0, + "channel {ch} peaks at {peak:.0} Hz, expected {want:.0} Hz: \ + the element order was not remapped to FL, FR, FC, LFE, BL, BR" + ); + } +} + +/// Crude DFT peak: enough to tell six well-separated tones apart. +fn dominant_frequency(samples: &[f32], rate: u32) -> f64 { + let n = samples.len().min(16384); + let start = samples.len() / 3; + let seg = &samples[start..start + n.min(samples.len() - start)]; + let mut best = (0.0f64, 0.0f64); + let mut f = 40.0; + while f < 4000.0 { + let w = 2.0 * std::f64::consts::PI * f / f64::from(rate); + let (mut re, mut im) = (0.0, 0.0); + for (i, &v) in seg.iter().enumerate() { + re += f64::from(v) * (w * i as f64).cos(); + im += f64::from(v) * (w * i as f64).sin(); + } + let mag = re * re + im * im; + if mag > best.1 { + best = (f, mag); + } + f += 5.0; + } + best.0 +} + +#[test] +fn asc_round_trips_every_sample_rate() { + for (index, rate) in ec_aac::SAMPLE_RATES.iter().enumerate() { + assert_eq!(ec_aac::sf_index_for_rate(*rate), Some(index as u8)); + assert_eq!(ec_aac::sample_rate_for_index(index as u8), *rate); + for channels in [1u16, 2, 6, 8] { + let bytes = ec_aac::audio_specific_config_bytes(*rate, channels); + let cfg = ec_aac::parse_audio_specific_config(&bytes).expect("asc parses"); + assert_eq!(cfg.sample_rate, *rate, "rate round trip at {rate} Hz"); + assert_eq!(cfg.channels, channels, "channels round trip at {rate} Hz"); + assert_eq!(cfg.object_type, ec_aac::AOT_AAC_LC); + } + } + 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. +#[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.output_sample_rate(), + Some(24_000), + "an HE-AAC stream 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); +} + +/// The incumbent encoder's per-channel correlation on these exact fixtures, +/// measured by running `rusty_aac` 0.5.0 as a black box through the same +/// ffmpeg decode (2026-08-14). This is the bar the replacement has to clear. +const INCUMBENT_BAR: &[(&str, usize, u32, f64)] = &[ + ("mono", 1, 96, 0.9846), + ("stereo", 2, 128, 0.9743), + ("stereo", 2, 192, 0.9864), + ("5.1", 6, 384, 0.9648), + ("5.1", 6, 448, 0.9611), +]; + +fn encode_to_adts(pcm: &[f32], channels: u16, rate: u32, kbps: u32) -> Vec { + let mut enc = AacEncoder::new(AacEncoderConfig { + bitrate_bps: kbps * 1000, + adts: true, + ..Default::default() + }); + enc.push_pcm(pcm, channels, rate).expect("pcm accepted"); + enc.finish(); + let mut out = Vec::new(); + while let Ok(p) = enc.next_packet() { + out.extend_from_slice(&p.data); + } + out +} + +/// Correlation at the encoder's own delay, which is one frame of lookahead. +fn best_correlation(source: &[f32], decoded: &[f32]) -> f64 { + [0usize, ec_aac::FRAME_LEN, 2 * ec_aac::FRAME_LEN] + .into_iter() + .filter(|lag| decoded.len() > *lag + 1024) + .map(|lag| correlation(source, &decoded[lag..])) + .fold(f64::MIN, f64::max) +} + +/// Our encode, through ffmpeg, against the incumbent's own numbers on the same +/// lossless fixtures at the same bitrates. +#[test] +fn encoder_beats_the_incumbent_bar() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = fixtures().join("audio"); + let tmp = std::env::temp_dir().join("ec-aac-bar"); + std::fs::create_dir_all(&tmp).expect("temp dir"); + let mut checked = 0; + for (name, channels, kbps, bar) in INCUMBENT_BAR { + let src = dir.join(format!("flac-{name}-48000.flac")); + if !src.exists() { + eprintln!("SKIP {name}: fixture missing"); + continue; + } + let source = ffmpeg_decode(&src, *channels); + let mut interleaved = Vec::with_capacity(source[0].len() * channels); + for i in 0..source[0].len() { + for plane in &source { + interleaved.push(plane[i]); + } + } + let adts = encode_to_adts(&interleaved, *channels as u16, 48_000, *kbps); + let path = tmp.join(format!("{name}-{kbps}k.aac")); + std::fs::write(&path, &adts).expect("write"); + let rate = adts.len() as f64 * 8.0 * 48_000.0 / source[0].len() as f64 / 1000.0; + let ours = ffmpeg_decode(&path, *channels); + let corr: Vec = source + .iter() + .zip(&ours) + .map(|(a, b)| best_correlation(a, b)) + .collect(); + let worst = corr.iter().copied().fold(f64::MAX, f64::min); + println!( + "enc {name} {kbps}k: {rate:.0} kbps actual, worst channel {worst:.4} \ + (incumbent {bar:.4}) per-channel {corr:?}" + ); + assert!( + rate <= f64::from(*kbps) * 1.12, + "{name} {kbps}k overshot its target: {rate:.0} kbps" + ); + assert!( + worst >= *bar, + "{name} {kbps}k worst channel {worst:.4} is under the incumbent's {bar:.4}" + ); + checked += 1; + } + assert!(checked > 0, "no lossless fixtures found"); +} + +fn tone_pcm(rate: u32, channels: usize, secs: f64) -> Vec { + let frames = (f64::from(rate) * secs) as usize; + let mut pcm = Vec::with_capacity(frames * channels); + for i in 0..frames { + let t = i as f64 / f64::from(rate); + for c in 0..channels { + let f = 220.0 * (c + 1) as f64; + let v = (t * f * std::f64::consts::TAU).sin() * 0.35 + + (t * f * 2.5 * std::f64::consts::TAU).sin() * 0.15; + pcm.push(v as f32); + } + } + pcm +} + +#[test] +fn encoder_output_decodes_in_ffmpeg_without_warnings() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let tmp = std::env::temp_dir().join("ec-aac-enc"); + std::fs::create_dir_all(&tmp).expect("temp dir"); + for (channels, kbps) in [(1u16, 96u32), (2, 128), (2, 192), (6, 384)] { + let rate = 48_000; + let pcm = tone_pcm(rate, usize::from(channels), 1.5); + let adts = encode_to_adts(&pcm, channels, rate, kbps); + assert!(!adts.is_empty(), "{channels}ch encode produced nothing"); + let path = tmp.join(format!("enc-{channels}ch-{kbps}k.aac")); + std::fs::write(&path, &adts).expect("write"); + let out = Command::new("ffmpeg") + .args(["-v", "warning", "-i"]) + .arg(&path) + .args(["-f", "null", "-"]) + .output() + .expect("ffmpeg runs"); + // ffmpeg says this about every ADTS file, its own included: the + // container has no duration field. It is not a complaint about us. + let log = String::from_utf8_lossy(&out.stderr); + let log: String = log + .lines() + .filter(|l| !l.contains("Estimating duration from bitrate")) + .collect::>() + .join("\n"); + assert!( + out.status.success() && log.trim().is_empty(), + "ffmpeg complained about our {channels}ch/{kbps}k ADTS:\n{log}" + ); + // And the sound survives the trip. + let theirs = ffmpeg_decode(&path, usize::from(channels)); + let ours = deinterleave(&pcm, usize::from(channels)); + for (ch, (a, b)) in ours.iter().zip(&theirs).enumerate() { + // The encoder's own frame of lookahead delays the output by one + // frame; line the two up before comparing. + let corr = correlation(a, &b[ec_aac::FRAME_LEN..]); + println!("enc {channels}ch {kbps}k channel {ch}: corr {corr:.4}"); + assert!( + corr >= 0.90, + "{channels}ch/{kbps}k channel {ch} correlation {corr:.4} < 0.90" + ); + } + } +} diff --git a/shims/rusty_aac/src/lib.rs b/shims/rusty_aac/src/lib.rs new file mode 100644 index 00000000..360ac82b --- /dev/null +++ b/shims/rusty_aac/src/lib.rs @@ -0,0 +1,233 @@ +//! The `rusty_aac` 0.5 surface, served by `ec-aac`. +//! +//! Only what edith consumes is here, at the incumbent's signatures: +//! `AacDecoder::with_config_bytes` (audio.rs:1731), `AacEncoder::new` with +//! `AacEncoderConfig` (mux.rs:2116, export.rs:1756) and `sf_index_for_rate` +//! (export.rs:1678). The encoder's tool flags are kept as fields so a caller +//! written against the incumbent still compiles; each one names what it maps to. + +#![forbid(unsafe_code)] + +pub use ec_aac::{ + AdtsHeader, AudioSpecificConfig, SAMPLE_RATES, audio_specific_config_bytes, is_adts, + parse_adts, parse_audio_specific_config, sample_rate_for_index, sf_index_for_rate, + write_adts_header, write_audio_specific_config, +}; + +/// The incumbent's error type: one variant per refusal reason, `Eof` included +/// so `while let Ok(p) = next_packet()` still terminates. +#[derive(Debug)] +pub enum Error { + Eof, + NeedMore, + Invalid(String), + Unsupported(String), +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Eof => write!(f, "end of stream"), + Error::NeedMore => write!(f, "need more data"), + Error::Invalid(m) => write!(f, "invalid: {m}"), + Error::Unsupported(m) => write!(f, "unsupported: {m}"), + } + } +} + +impl std::error::Error for Error {} + +impl Error { + pub fn invalid(msg: impl Into) -> Error { + Error::Invalid(msg.into()) + } + + pub fn unsupported(msg: impl Into) -> Error { + Error::Unsupported(msg.into()) + } +} + +impl From for Error { + fn from(e: ec_aac::Error) -> Error { + match e { + ec_aac::Error::Eof => Error::Eof, + ec_aac::Error::NeedMore => Error::NeedMore, + ec_aac::Error::Unsupported { .. } => Error::Unsupported(e.to_string()), + other => Error::Invalid(other.to_string()), + } + } +} + +pub type Result = std::result::Result; + +/// One decoded frame, interleaved, in film channel order. +#[derive(Clone, Debug, Default)] +pub struct DecodedAudio { + pub sample_rate: u32, + pub channels: u16, + pub samples: Vec, + pub pts: Option, +} + +impl DecodedAudio { + pub fn frames(&self) -> usize { + if self.channels == 0 { + 0 + } else { + self.samples.len() / usize::from(self.channels) + } + } +} + +/// What the decoder does with a High Efficiency stream. +pub use ec_aac::SbrSupport; + +/// An AAC-LC decoder. +pub struct AacDecoder(ec_aac::AacDecoder); + +impl AacDecoder { + pub fn new() -> AacDecoder { + AacDecoder(ec_aac::AacDecoder::new()) + } + + pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder { + AacDecoder(ec_aac::AacDecoder::with_config(cfg)) + } + + pub fn with_config_bytes(data: &[u8]) -> Result { + Ok(AacDecoder(ec_aac::AacDecoder::with_config_bytes(data)?)) + } + + pub fn sbr_support(&self) -> SbrSupport { + self.0.sbr_support() + } + + pub fn output_sample_rate(&self) -> Option { + self.0.output_sample_rate() + } + + pub fn decode(&mut self, packet: &[u8], pts: Option) -> Result { + let d = self.0.decode(packet, pts)?; + Ok(DecodedAudio { + sample_rate: d.sample_rate, + channels: d.channels, + samples: d.samples, + pts: d.pts, + }) + } +} + +impl Default for AacDecoder { + fn default() -> AacDecoder { + AacDecoder::new() + } +} + +/// Window-shape policy. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum WindowShape { + #[default] + Sine, + Kbd, + /// Per-frame dispatch on content tonality; served here as [`WindowShape::Sine`]. + Auto, +} + +/// Encoder options, at the incumbent's field set. +#[derive(Debug, Clone, Copy)] +pub struct AacEncoderConfig { + /// Target bitrate in bits per second. + pub bitrate_bps: u32, + /// Window-shape policy. + pub window_shape: WindowShape, + /// The `Auto` gate's threshold; unused here, `Auto` codes as sine. + pub shape_tonality_pct: f32, + /// Run the psychoacoustic model on short blocks: always on here. + pub short_block_psy: bool, + /// Make the signal-to-mask ratio a function of band tonality: always on here. + pub tonality_smr: bool, + /// Emit TNS on long blocks; not emitted by this encoder (decoding it is + /// complete either way). + pub tns: bool, + /// Level-invariant transient detector: always on here. + pub relative_transients: bool, + /// Perceptual noise substitution; not emitted by this encoder. + pub pns: bool, + /// Intensity stereo; not emitted by this encoder. + pub intensity: bool, + /// Split a pair's bit budget by perceptual demand: always on here, the rate + /// loop is joint over the whole frame. + pub stereo_bit_split: bool, +} + +impl Default for AacEncoderConfig { + fn default() -> AacEncoderConfig { + AacEncoderConfig { + bitrate_bps: 128_000, + window_shape: WindowShape::Sine, + shape_tonality_pct: 0.5, + short_block_psy: true, + tonality_smr: true, + tns: false, + relative_transients: true, + pns: false, + intensity: false, + stereo_bit_split: true, + } + } +} + +/// One encoded raw access unit (a `raw_data_block`, no ADTS framing). +#[derive(Debug, Clone)] +pub struct EncodedPacket { + pub data: Vec, + pub pts: i64, + pub duration: u32, +} + +/// An AAC-LC encoder. +pub struct AacEncoder(ec_aac::AacEncoder); + +impl AacEncoder { + pub fn new(config: AacEncoderConfig) -> AacEncoder { + AacEncoder(ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig { + bitrate_bps: config.bitrate_bps.max(1), + window_shape: match config.window_shape { + WindowShape::Kbd => ec_aac::WindowShape::Kbd, + _ => ec_aac::WindowShape::Sine, + }, + adts: false, + mid_side: true, + window_switching: true, + })) + } + + pub fn sample_rate(&self) -> u32 { + self.0.sample_rate() + } + + pub fn channels(&self) -> u16 { + self.0.channels() + } + + pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> { + Ok(self.0.push_pcm(interleaved, channels, sample_rate)?) + } + + pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> { + Ok(self.0.push_pcm_planar(planes, sample_rate)?) + } + + pub fn finish(&mut self) { + self.0.finish(); + } + + pub fn next_packet(&mut self) -> Result { + let p = self.0.next_packet()?; + Ok(EncodedPacket { + data: p.data, + pts: p.pts, + duration: p.duration, + }) + } +}