diff --git a/crates/ec-aac/src/decode.rs b/crates/ec-aac/src/decode.rs index 61887a8a..25e061fa 100644 --- a/crates/ec-aac/src/decode.rs +++ b/crates/ec-aac/src/decode.rs @@ -308,7 +308,6 @@ struct Ics { pub struct ChannelState { overlap: Vec, prev_shape_kbd: bool, - prev_short: bool, } impl Default for ChannelState { @@ -316,7 +315,6 @@ impl Default for ChannelState { ChannelState { overlap: vec![0.0; FRAME_LEN], prev_shape_kbd: false, - prev_short: false, } } } @@ -424,7 +422,6 @@ impl FilterBank { } state.overlap.copy_from_slice(&frame[FRAME_LEN..]); state.prev_shape_kbd = ics.window_shape_kbd; - state.prev_short = ics.window_sequence.is_short(); } } @@ -791,6 +788,86 @@ impl BlockDecoder { } } + fn fill_element( + &mut self, + r: &mut BitReader<'_>, + out: &mut Vec>, + pending: &mut Option<(u8, usize, usize, bool)>, + ) -> Result<()> { + let mut count = r.read_bits(4)? as u64; + if count == 15 { + // 15 + esc - 1, written so an escape of 0 cannot underflow. + count = 14 + r.read_bits(8)? as u64; + } + let end_bit = r.bit_position() + count * 8; + // Implicit SBR: no SBR in the config, but this FIL is the first + // to carry an SBR extension right after an element. Arm the + // chain for it; if its payload does not parse, disarm again. + let arming = match self.implicit_core { + Some(core) + if self.sbr.is_none() + && pending.is_some() + && r.bits_remaining() >= 4 + && matches!(r.peek_bits(4)?, 13 | 14) => + { + self.sbr = Some(crate::sbr_chain::SbrChain::new(core * 2)); + true + } + _ => false, + }; + let mut applied = false; + if let (Some(sbr), Some((tag, start, n, is_cpe))) = + (self.sbr.as_mut(), pending.take()) + { + // extension_payload(): bs_extension_type(4), then + // (for SBR) an optional 10-bit CRC, then + // sbr_extension_data() itself. + if r.bits_remaining() >= 4 { + let ext_type = r.peek_bits(4)?; + if ext_type == 13 || ext_type == 14 { + r.skip_bits(4)?; + if ext_type == 14 && r.bits_remaining() >= 10 { + r.skip_bits(10)?; // bs_sbr_crc_bits + } + if let Some(data) = sbr.parse(r, tag, is_cpe) { + if data.ps.is_some() && (arming || self.implicit_on) { + self.implicit_ps = true; + } + sbr.apply_planes(tag, is_cpe, &data, out, start, n)?; + applied = true; + } + } + } + if !applied && !arming { + // No fresh SBR payload this frame (no SBR fill + // element, or one whose extension_type wasn't + // SBR, or a parse failure): §4.6.18 still + // requires doubled-rate reconstruction, using + // the last successfully parsed frame's data. + sbr.apply_last_planes(tag, is_cpe, out, start, n)?; + } + } + if arming { + if applied { + self.implicit_on = true; + self.implicit_core = None; + } else { + // The payload did not parse: this was not SBR after all. + self.sbr = None; + } + } + // Resync to the FIL's declared byte boundary regardless + // of how many bits SBR parsing above actually consumed: + // a parse error or trailing padding must never desync + // the elements that follow. + let now = r.bit_position(); + if now < end_bit { + r.skip_bits(end_bit - now)?; + } + *pending = None; + Ok(()) + } + /// 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>> { @@ -890,77 +967,7 @@ impl BlockDecoder { pending = None; } 6 => { - let mut count = r.read_bits(4)? as u64; - if count == 15 { - // 15 + esc - 1, written so an escape of 0 cannot underflow. - count = 14 + r.read_bits(8)? as u64; - } - let end_bit = r.bit_position() + count * 8; - // Implicit SBR: no SBR in the config, but this FIL is the first - // to carry an SBR extension right after an element. Arm the - // chain for it; if its payload does not parse, disarm again. - let arming = match self.implicit_core { - Some(core) - if self.sbr.is_none() - && pending.is_some() - && r.bits_remaining() >= 4 - && matches!(r.peek_bits(4)?, 13 | 14) => - { - self.sbr = Some(crate::sbr_chain::SbrChain::new(core * 2)); - true - } - _ => false, - }; - let mut applied = false; - if let (Some(sbr), Some((tag, start, n, is_cpe))) = - (self.sbr.as_mut(), pending.take()) - { - // extension_payload(): bs_extension_type(4), then - // (for SBR) an optional 10-bit CRC, then - // sbr_extension_data() itself. - if r.bits_remaining() >= 4 { - let ext_type = r.peek_bits(4)?; - if ext_type == 13 || ext_type == 14 { - r.skip_bits(4)?; - if ext_type == 14 && r.bits_remaining() >= 10 { - r.skip_bits(10)?; // bs_sbr_crc_bits - } - if let Some(data) = sbr.parse(r, tag, is_cpe) { - if data.ps.is_some() && (arming || self.implicit_on) { - self.implicit_ps = true; - } - sbr.apply_planes(tag, is_cpe, &data, &mut out, start, n)?; - applied = true; - } - } - } - if !applied && !arming { - // No fresh SBR payload this frame (no SBR fill - // element, or one whose extension_type wasn't - // SBR, or a parse failure): §4.6.18 still - // requires doubled-rate reconstruction, using - // the last successfully parsed frame's data. - sbr.apply_last_planes(tag, is_cpe, &mut out, start, n)?; - } - } - if arming { - if applied { - self.implicit_on = true; - self.implicit_core = None; - } else { - // The payload did not parse: this was not SBR after all. - self.sbr = None; - } - } - // Resync to the FIL's declared byte boundary regardless - // of how many bits SBR parsing above actually consumed: - // a parse error or trailing padding must never desync - // the elements that follow. - let now = r.bit_position(); - if now < end_bit { - r.skip_bits(end_bit - now)?; - } - pending = None; + self.fill_element(r, &mut out, &mut pending)?; } _ => { // The block ended with no FIL element ever following the diff --git a/crates/ec-aac/src/encode.rs b/crates/ec-aac/src/encode.rs index 9ebfae4b..1bd1e082 100644 --- a/crates/ec-aac/src/encode.rs +++ b/crates/ec-aac/src/encode.rs @@ -538,11 +538,11 @@ impl AacEncoder { 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) { + if ms_wins(&pair[0], &pair[1], swb, b, seq) { ms[b] = true; } } - apply_ms(&mut pair, &ms, swb, max_sfb, short); + apply_ms(&mut pair, &ms, swb, max_sfb, seq); } elements.push(ElementPlan { element: *element, @@ -563,7 +563,7 @@ impl AacEncoder { .map(|plan| { plan.frames .iter() - .map(|frame| band_profile(frame, swb, max_sfb, short)) + .map(|frame| band_profile(frame, swb, max_sfb, seq)) .collect() }) .collect(); @@ -759,14 +759,14 @@ impl AacEncoder { max_sfb, b, floor[b], - || self.band_noise(frame, swb, b, floor[b], windows, short), + || self.band_noise(frame, swb, b, floor[b], windows, seq), ) <= target { let (mut lo, mut hi) = (floor[b], 255); while lo < hi { let mid = lo + (hi - lo + 1) / 2; if memo.noise(ch_slot, max_sfb, b, mid, || { - self.band_noise(frame, swb, b, mid, windows, short) + self.band_noise(frame, swb, b, mid, windows, seq) }) <= target { lo = mid; } else { @@ -848,7 +848,7 @@ impl AacEncoder { if books[b] == 0 { continue; } - bits += band_bits(&quant, swb, b, books[b], windows, short); + bits += band_bits(&quant, swb, b, books[b], windows, seq); 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]); @@ -871,7 +871,6 @@ impl AacEncoder { books, quant, bits, - short, } } @@ -883,8 +882,9 @@ impl AacEncoder { band: usize, sf: i32, windows: usize, - short: bool, + seq: WindowSequence, ) -> f32 { + let short = seq == WindowSequence::EightShort; let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1])); let gain = pow_quarter(sf - SF_OFFSET); let gain_inv = pow_quarter(SF_OFFSET - sf); @@ -922,12 +922,18 @@ struct Coded { 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 { +fn ms_wins( + l: &ChannelFrame, + r: &ChannelFrame, + swb: &[u16], + band: usize, + seq: WindowSequence, +) -> bool { + let short = seq == WindowSequence::EightShort; 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); @@ -958,7 +964,13 @@ struct BandProfile { floor: Vec, } -fn band_profile(frame: &ChannelFrame, swb: &[u16], max_sfb: usize, short: bool) -> BandProfile { +fn band_profile( + frame: &ChannelFrame, + swb: &[u16], + max_sfb: usize, + seq: WindowSequence, +) -> BandProfile { + let short = seq == WindowSequence::EightShort; let windows = if short { 8 } else { 1 }; let mut peak = vec![0.0f32; max_sfb]; let mut energy = vec![0.0f32; max_sfb]; @@ -1024,7 +1036,14 @@ impl NoiseMemo { } } -fn apply_ms(pair: &mut [ChannelFrame], ms: &[bool], swb: &[u16], max_sfb: usize, short: bool) { +fn apply_ms( + pair: &mut [ChannelFrame], + ms: &[bool], + swb: &[u16], + max_sfb: usize, + seq: WindowSequence, +) { + let short = seq == WindowSequence::EightShort; let windows = if short { 8 } else { 1 }; for b in 0..max_sfb { if !ms[b] { @@ -1125,8 +1144,9 @@ fn band_bits( band: usize, book: u8, windows: usize, - short: bool, + seq: WindowSequence, ) -> i32 { + let short = seq == WindowSequence::EightShort; 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); @@ -1218,7 +1238,7 @@ fn write_ics_info(w: &mut BitWriter, c: &Coded) { }; w.write_bits(seq, 2); w.write_bit(false); // sine window shape - if c.short { + if c.seq == WindowSequence::EightShort { w.write_bits(c.max_sfb as u32, 4); w.write_bits(0x7F, 7); // one group of eight windows } else { @@ -1235,7 +1255,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) { write_ics_info(w, c); } // section_data - let esc_bits = if c.short { 3 } else { 5 }; + let esc_bits = if c.seq == WindowSequence::EightShort { 3 } else { 5 }; let esc = (1u32 << esc_bits) - 1; let mut b = 0usize; while b < c.max_sfb { @@ -1267,7 +1287,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) { 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 }; + let windows = if c.seq == WindowSequence::EightShort { 8 } else { 1 }; for b in 0..c.max_sfb { let book = c.books[b]; if book == 0 { @@ -1277,7 +1297,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) { 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 base = if c.seq == WindowSequence::EightShort { win * SHORT_LEN } else { 0 }; let mut k = lo; while k < hi { let end = (k + dim).min(hi); diff --git a/crates/ec-aac/src/huffman.rs b/crates/ec-aac/src/huffman.rs index 4a5f0591..dab34a20 100644 --- a/crates/ec-aac/src/huffman.rs +++ b/crates/ec-aac/src/huffman.rs @@ -83,3 +83,36 @@ impl Default for Books { Books::new() } } + +#[cfg(test)] +pub(crate) fn assert_each_codeword_decodes_to_itself(codes: &[(u8, u32)]) { + let tree = Tree::new(codes); + for (symbol, &(len, code)) in codes.iter().enumerate() { + let mut bytes = [0u8; 8]; + for (i, depth) in (0..len).rev().enumerate() { + if (code >> depth) & 1 == 1 { + bytes[i / 8] |= 0x80 >> (i % 8); + } + } + let mut r = BitReader::new(&bytes); + assert_eq!(tree.decode(&mut r).unwrap(), symbol); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sbr_tables::*; + + #[test] + fn every_sbr_codeword_decodes_to_its_own_symbol() { + let books: [&[(u8, u32, i32)]; 12] = [ + &ENV15_F, &ENV15_T, &ENV30_F, &ENV30_T, &NOISE_F, &NOISE_T, &ENVB15_F, &ENVB15_T, + &ENVB30_F, &ENVB30_T, &NOISEB_F, &NOISEB_T, + ]; + for book in books { + let codes: Vec<(u8, u32)> = book.iter().map(|&(len, code, _)| (len, code)).collect(); + assert_each_codeword_decodes_to_itself(&codes); + } + } +} diff --git a/crates/ec-aac/src/ps_data.rs b/crates/ec-aac/src/ps_data.rs index 81aae92e..35c79a0c 100644 --- a/crates/ec-aac/src/ps_data.rs +++ b/crates/ec-aac/src/ps_data.rs @@ -8,6 +8,7 @@ //! its handling of stale fields, so that the decoded parameters match the //! reference decoder frame for frame. +use crate::huffman::Tree; use crate::ps_huff; use ec_core::{BitReader, Error, Result}; use std::sync::OnceLock; @@ -93,10 +94,21 @@ impl Default for PsCommon { } } -/// One prefix-code table: every codeword as (length, code, parameter value). +/// One prefix-code table: the walkable code tree, and the parameter value of +/// each symbol (the tree's symbol is the codeword's index in the table). struct Vlc { - codes: Vec<(u32, u32, i32)>, - max_len: u32, + tree: Tree, + values: Vec, +} + +impl Vlc { + fn new(codes: &[(u32, u32, i32)]) -> Vlc { + let lens_codes: Vec<(u8, u32)> = codes.iter().map(|&(len, code, _)| (len as u8, code)).collect(); + Vlc { + tree: Tree::new(&lens_codes), + values: codes.iter().map(|&(_, _, value)| value).collect(), + } + } } /// The ten PS Huffman tables, with canonical codes assigned from the lengths. @@ -106,7 +118,7 @@ fn vlcs() -> &'static [Vlc] { ps_huff::TABLES .iter() .zip(ps_huff::OFFSETS) - .map(|(table, offset)| build_codes(table, offset)) + .map(|(table, offset)| Vlc::new(&build_codes(table, offset))) .collect() }) } @@ -117,36 +129,23 @@ fn vlcs() -> &'static [Vlc] { /// lengths alone do not fix the codes, which is why sorting them canonically /// misreads every fine-IID and ICC frame. Every table in the standard is a /// complete prefix code, which the unit tests check. -fn build_codes(table: &[(u8, u8)], offset: i32) -> Vlc { +fn build_codes(table: &[(u8, u8)], offset: i32) -> Vec<(u32, u32, i32)> { let mut codes = Vec::with_capacity(table.len()); // Position in the code space, in units of 2^-32 (a 64-bit sum: no overflow). let mut next: u64 = 0; - let mut max_len = 0; for &(value, len) in table { let len = u32::from(len).clamp(1, 32); let code = (next >> (32 - len)) as u32; codes.push((len, code, i32::from(value) + offset)); next += 1u64 << (32 - len); - max_len = max_len.max(len); } - Vlc { codes, max_len } + codes } /// Reads one codeword of table `which` and returns its parameter value. fn read_vlc(r: &mut BitReader<'_>, which: usize) -> Result { - let table = &vlcs()[which]; - let mut code: u32 = 0; - for len in 1..=table.max_len { - code = (code << 1) | u32::from(r.read_bit()?); - if let Some(&(_, _, value)) = table - .codes - .iter() - .find(|&&(l, c, _)| l == len && c == code) - { - return Ok(value); - } - } - Err(Error::corrupt("ps: no codeword matches the bitstream")) + let vlc = &vlcs()[which]; + Ok(vlc.values[vlc.tree.decode(r)?]) } /// Reads one IID/ICC/IPD/OPD parameter row (FFmpeg's `READ_PAR_DATA`). @@ -458,17 +457,28 @@ mod tests { // length 4) and (value +2, length 4), so they get codes 0000 and 0001, // not the canonical order a length sort would give. let v = build_codes(ps_huff::TABLES[HUFF_IID_DF1], ps_huff::OFFSETS[HUFF_IID_DF1]); - assert_eq!(v.codes[0], (4, 0b0000, -2)); - assert_eq!(v.codes[1], (4, 0b0001, 2)); - assert_eq!(v.codes[2], (3, 0b001, -1)); + assert_eq!(v[0], (4, 0b0000, -2)); + assert_eq!(v[1], (4, 0b0001, 2)); + assert_eq!(v[2], (3, 0b001, -1)); + } + + #[test] + fn every_ps_codeword_decodes_to_its_own_symbol() { + for (i, table) in ps_huff::TABLES.iter().enumerate() { + let codes: Vec<(u8, u32)> = build_codes(table, ps_huff::OFFSETS[i]) + .iter() + .map(|&(len, code, _)| (len as u8, code)) + .collect(); + crate::huffman::assert_each_codeword_decodes_to_itself(&codes); + } } #[test] fn codes_are_prefix_free_and_values_cover_the_range() { for (i, table) in ps_huff::TABLES.iter().enumerate() { let v = build_codes(table, ps_huff::OFFSETS[i]); - for (a, &(la, ca, _)) in v.codes.iter().enumerate() { - for &(lb, cb, _) in v.codes.iter().skip(a + 1) { + for (a, &(la, ca, _)) in v.iter().enumerate() { + for &(lb, cb, _) in v.iter().skip(a + 1) { let (short, long, cs, cl) = if la <= lb { (la, lb, ca, cb) } else { (lb, la, cb, ca) }; assert!(cl >> (long - short) != cs, "table {i} codes collide"); } @@ -498,7 +508,7 @@ mod tests { push(&mut bits, 0, 1); // dt = 0 for the envelope let code_for_zero = { let v = build_codes(ps_huff::TABLES[HUFF_IID_DF0], ps_huff::OFFSETS[HUFF_IID_DF0]); - *v.codes.iter().find(|c| c.2 == 0).expect("zero is a codeword") + *v.iter().find(|c| c.2 == 0).expect("zero is a codeword") }; for _ in 0..10 { push(&mut bits, code_for_zero.1, code_for_zero.0); diff --git a/crates/ec-aac/src/sbr_chain.rs b/crates/ec-aac/src/sbr_chain.rs index 4fcf994f..dd143ed6 100644 --- a/crates/ec-aac/src/sbr_chain.rs +++ b/crates/ec-aac/src/sbr_chain.rs @@ -377,31 +377,7 @@ impl SbrChain { continue; } let state = &mut elem.channels[ch]; - let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS]; - let mut raw = Vec::with_capacity(num_slots); - for slot in 0..num_slots { - let mut chunk = [0f32; ANALYSIS_BANDS]; - chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); - // `plane` is already at the decoder's final output scale - // (`decode::OUTPUT_SCALE`, applied by the core filterbank), - // but the transmitted envelope/noise data is calibrated - // against the core's un-normalized internal PCM domain -- - // undo that scale before analysis so the SBR gain match - // (raw QMF energy vs. the transmitted target) compares - // like against like, and reapply it once below after - // synthesis. Without this the gain step's `target/current` - // ratio is inflated by `1/OUTPUT_SCALE^2` in energy, - // exactly the multi-order-of-magnitude blowup this chain - // used to produce on every real HE-AAC file. - for s in &mut chunk { - *s /= crate::decode::OUTPUT_SCALE; - } - let sub = state.analysis.process_slot(&chunk); - for b in 0..ANALYSIS_BANDS { - low_cur[b][slot] = sub[b]; - } - raw.push(sub); - } + let (low_cur, raw) = analyze_plane(state, plane, num_slots); let sbr_ch = &data.channels[ch]; let hf = sbr_hf::generate( @@ -481,17 +457,7 @@ impl SbrChain { let kx = (tables.kx as usize).min(ANALYSIS_BANDS); let k2 = (tables.k2 as usize).min(band_limit); - let mut vs: Vec<[Complex; SYNTHESIS_BANDS]> = Vec::with_capacity(num_slots); - for slot in 0..num_slots { - let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; - v[0..kx].copy_from_slice(&raw[slot][0..kx]); - for b in kx..k2 { - if b - kx < hf.len() { - v[b] = hf[b - kx][slot]; - } - } - vs.push(v); - } + let vs = merge_bands(&raw, &hf, kx, k2, num_slots); let out = match (ps_mode && num_slots == PS_SLOTS, data.ps.as_ref()) { (true, Some(ps)) => { let (left, right) = @@ -530,6 +496,62 @@ impl SbrChain { } } +type QmfGrid = Vec>>; + +fn analyze_plane( + state: &mut ChannelState, + plane: &[f32], + num_slots: usize, +) -> (QmfGrid, Vec<[Complex; ANALYSIS_BANDS]>) { + let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS]; + let mut raw = Vec::with_capacity(num_slots); + for slot in 0..num_slots { + let mut chunk = [0f32; ANALYSIS_BANDS]; + chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]); + // `plane` is already at the decoder's final output scale + // (`decode::OUTPUT_SCALE`, applied by the core filterbank), + // but the transmitted envelope/noise data is calibrated + // against the core's un-normalized internal PCM domain -- + // undo that scale before analysis so the SBR gain match + // (raw QMF energy vs. the transmitted target) compares + // like against like, and reapply it once below after + // synthesis. Without this the gain step's `target/current` + // ratio is inflated by `1/OUTPUT_SCALE^2` in energy, + // exactly the multi-order-of-magnitude blowup this chain + // used to produce on every real HE-AAC file. + for s in &mut chunk { + *s /= crate::decode::OUTPUT_SCALE; + } + let sub = state.analysis.process_slot(&chunk); + for b in 0..ANALYSIS_BANDS { + low_cur[b][slot] = sub[b]; + } + raw.push(sub); + } + (low_cur, raw) +} + +fn merge_bands( + raw: &[[Complex; ANALYSIS_BANDS]], + hf: &[Vec>], + kx: usize, + k2: usize, + num_slots: usize, +) -> Vec<[Complex; SYNTHESIS_BANDS]> { + let mut vs: Vec<[Complex; SYNTHESIS_BANDS]> = Vec::with_capacity(num_slots); + for slot in 0..num_slots { + let mut v = [Complex::ZERO; SYNTHESIS_BANDS]; + v[0..kx].copy_from_slice(&raw[slot][0..kx]); + for b in kx..k2 { + if b - kx < hf.len() { + v[b] = hf[b - kx][slot]; + } + } + vs.push(v); + } + vs +} + /// Inserts the second output plane a PS element needs, right after its first /// (a copy, which the PS path then overwrites). Returns the element's new /// plane count: 2 when a plane was inserted. diff --git a/crates/ec-aac/src/sbr_payload.rs b/crates/ec-aac/src/sbr_payload.rs index f94180e5..ccca341d 100644 --- a/crates/ec-aac/src/sbr_payload.rs +++ b/crates/ec-aac/src/sbr_payload.rs @@ -15,7 +15,9 @@ //! `sbrtables.py` never needed them for the codebook derivation. #![allow(dead_code)] +use crate::huffman::Tree; use crate::ps_data::PsCommon; +use std::sync::LazyLock; use crate::sbr_bands::{BandTables, freq_tables}; use crate::sbr_tables::*; use ec_core::{BitReader, Error, Result}; @@ -165,25 +167,74 @@ pub struct SbrParser { /// `bs_extension_id` of Parametric Stereo. const EXTENSION_ID_PS: u32 = 2; -fn env_book(dt: bool, balance: bool, amp_res: u8) -> &'static [(u8, u32, i32)] { +/// One codebook as a walkable tree, and the delta value of each symbol. +struct Book { + tree: Tree, + deltas: Vec, +} + +impl Book { + fn new(entries: &[(u8, u32, i32)]) -> Book { + let codes: Vec<(u8, u32)> = entries.iter().map(|&(len, code, _)| (len, code)).collect(); + Book { + tree: Tree::new(&codes), + deltas: entries.iter().map(|&(_, _, delta)| delta).collect(), + } + } +} + +/// The twelve SBR envelope and noise books, built once. +struct SbrBooks { + env15_f: Book, + env15_t: Book, + env30_f: Book, + env30_t: Book, + envb15_f: Book, + envb15_t: Book, + envb30_f: Book, + envb30_t: Book, + noise_f: Book, + noise_t: Book, + noiseb_f: Book, + noiseb_t: Book, +} + +static BOOKS: LazyLock = LazyLock::new(|| SbrBooks { + env15_f: Book::new(&ENV15_F), + env15_t: Book::new(&ENV15_T), + env30_f: Book::new(&ENV30_F), + env30_t: Book::new(&ENV30_T), + envb15_f: Book::new(&ENVB15_F), + envb15_t: Book::new(&ENVB15_T), + envb30_f: Book::new(&ENVB30_F), + envb30_t: Book::new(&ENVB30_T), + noise_f: Book::new(&NOISE_F), + noise_t: Book::new(&NOISE_T), + noiseb_f: Book::new(&NOISEB_F), + noiseb_t: Book::new(&NOISEB_T), +}); + +fn env_book(dt: bool, balance: bool, amp_res: u8) -> &'static Book { + let b = &*BOOKS; match (balance, amp_res != 0, dt) { - (false, false, false) => &ENV15_F, - (false, false, true) => &ENV15_T, - (false, true, false) => &ENV30_F, - (false, true, true) => &ENV30_T, - (true, false, false) => &ENVB15_F, - (true, false, true) => &ENVB15_T, - (true, true, false) => &ENVB30_F, - (true, true, true) => &ENVB30_T, + (false, false, false) => &b.env15_f, + (false, false, true) => &b.env15_t, + (false, true, false) => &b.env30_f, + (false, true, true) => &b.env30_t, + (true, false, false) => &b.envb15_f, + (true, false, true) => &b.envb15_t, + (true, true, false) => &b.envb30_f, + (true, true, true) => &b.envb30_t, } } -fn noise_book(dt: bool, balance: bool) -> &'static [(u8, u32, i32)] { +fn noise_book(dt: bool, balance: bool) -> &'static Book { + let b = &*BOOKS; match (balance, dt) { - (false, false) => &NOISE_F, - (false, true) => &NOISE_T, - (true, false) => &NOISEB_F, - (true, true) => &NOISEB_T, + (false, false) => &b.noise_f, + (false, true) => &b.noise_t, + (true, false) => &b.noiseb_f, + (true, true) => &b.noiseb_t, } } @@ -238,24 +289,9 @@ fn map_prev_env(prev: &[i32], tables: &BandTables, cur_high: bool) -> Vec { } } -/// Reads one Huffman codeword by walking bit-by-bit until it matches a table -/// entry. Every book here is a complete prefix code (Kraft sum 1, checked in -/// `sbr_tables`), so a well-formed stream always terminates; a codeword -/// longer than any entry means truncated or corrupted input, not a panic. -fn read_huffman(r: &mut BitReader, book: &'static [(u8, u32, i32)]) -> Result { - let max_len = book.iter().map(|&(l, _, _)| l).max().unwrap_or(0); - let mut code: u32 = 0; - let mut len: u8 = 0; - loop { - code = (code << 1) | u32::from(r.read_bit()?); - len += 1; - if let Some(&(_, _, delta)) = book.iter().find(|&&(l, c, _)| l == len && c == code) { - return Ok(delta); - } - if len > max_len { - return Err(Error::corrupt("sbr: no codeword matched this bit sequence")); - } - } +/// Reads one Huffman codeword and returns its delta. +fn read_huffman(r: &mut BitReader, book: &Book) -> Result { + Ok(book.deltas[book.tree.decode(r)?]) } impl SbrParser { diff --git a/crates/ec-mp3/src/decode.rs b/crates/ec-mp3/src/decode.rs index 37dd3618..f83dd554 100644 --- a/crates/ec-mp3/src/decode.rs +++ b/crates/ec-mp3/src/decode.rs @@ -2,7 +2,7 @@ //! filterbank that turns 576 coefficients back into PCM. use crate::filterbank::{Imdct, Synthesis, alias_reduce}; -use crate::header::{ChannelMode, FrameHeader, Version, crc16}; +use crate::header::{ChannelMode, FrameHeader, Layer, Version, crc16}; use crate::huffman; use crate::layer12::Layer12; use crate::tables::{ @@ -22,6 +22,29 @@ pub struct DecodedFrame { pub samples: Vec, } +/// `block_type` of a granule with window switching. Normal when the granule +/// does not window-switch. The discriminant indexes the IMDCT window table. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[repr(u8)] +enum BlockType { + #[default] + Normal = 0, + Start = 1, + Short = 2, + Stop = 3, +} + +impl BlockType { + fn from_bits(v: u32) -> BlockType { + match v { + 0 => BlockType::Normal, + 1 => BlockType::Start, + 2 => BlockType::Short, + _ => BlockType::Stop, + } + } +} + #[derive(Clone, Copy, Debug, Default)] struct GranuleInfo { part2_3_length: u32, @@ -29,7 +52,7 @@ struct GranuleInfo { global_gain: u32, scalefac_compress: u32, window_switching: bool, - block_type: u8, + block_type: BlockType, mixed_block: bool, table_select: [u8; 3], subblock_gain: [u32; 3], @@ -86,7 +109,7 @@ fn parse_side_info(header: &FrameHeader, bytes: &[u8]) -> Result { ))); } if g.window_switching { - g.block_type = r.read_bits(2)? as u8; + g.block_type = BlockType::from_bits(r.read_bits(2)?); g.mixed_block = r.read_bit()?; for slot in &mut g.table_select[..2] { *slot = r.read_bits(5)? as u8; @@ -94,13 +117,13 @@ fn parse_side_info(header: &FrameHeader, bytes: &[u8]) -> Result { for slot in &mut g.subblock_gain { *slot = r.read_bits(3)?; } - g.region0_count = if g.block_type == 2 && !g.mixed_block { + g.region0_count = if g.block_type == BlockType::Short && !g.mixed_block { 8 } else { 7 }; g.region1_count = 20 - g.region0_count; - if g.block_type == 0 { + if g.block_type == BlockType::Normal { return Err(Error::corrupt( "mp3: window switching with normal block type", )); @@ -192,7 +215,7 @@ impl Mp3Decode { if frame.len() < frame_len { return Err(Error::NeedMore); } - if header.layer != 3 { + if header.layer != Layer::III { let samples = self.layer12.decode(&header, &frame[..frame_len])?; return Ok(DecodedFrame { sample_rate: header.sample_rate, @@ -309,7 +332,7 @@ impl Mp3Decode { ) -> Result<()> { let granule = side.granules[gr][ch]; let (slen1, slen2) = SLEN[(granule.scalefac_compress & 15) as usize]; - if granule.window_switching && granule.block_type == 2 { + if granule.block_type == BlockType::Short { if granule.mixed_block { for sfb in 0..8 { self.scalefac_l[ch][sfb] = reader.read_bits(slen1)? as u8; @@ -386,7 +409,7 @@ impl Mp3Decode { slen = [sfc / 3, sfc % 3, 0, 0]; block_number = 2; } - let short = granule.window_switching && granule.block_type == 2; + let short = granule.block_type == BlockType::Short; let kind = if !short { 0 } else if granule.mixed_block { @@ -427,7 +450,7 @@ impl Mp3Decode { let is = &mut self.is[ch]; is.fill(0); let starts = long_starts(header.sample_rate); - let short = granule.window_switching && granule.block_type == 2; + let short = granule.block_type == BlockType::Short; let (region1, region2) = if granule.window_switching { if short { // Three short bands, all three windows: 36 lines at every rate @@ -493,7 +516,7 @@ impl Mp3Decode { let power = power43(); let xr = &mut self.xr[ch]; let is = &self.is[ch]; - let short = granule.window_switching && granule.block_type == 2; + let short = granule.block_type == BlockType::Short; let multiplier = if granule.scalefac_scale { 1.0 } else { 0.5 }; let base = (granule.global_gain as f32 - 210.0) * 0.25; let value = |v: i32| -> f32 { @@ -566,7 +589,7 @@ impl Mp3Decode { let ms = joint && header.mode_ext & 2 != 0; let intensity = joint && header.mode_ext & 1 != 0; let granule = side.granules[gr][0]; - let short = granule.window_switching && granule.block_type == 2; + let short = granule.block_type == BlockType::Short; // Intensity coding starts at the first band above the right channel's // last non-zero line. let bound = if intensity { @@ -624,7 +647,7 @@ impl Mp3Decode { channels: usize, out: &mut [f32], ) { - let short = granule.window_switching && granule.block_type == 2; + let short = granule.block_type == BlockType::Short; let alias_bands = if !short { 32 } else if granule.mixed_block { @@ -643,8 +666,8 @@ impl Mp3Decode { if short && !(granule.mixed_block && sb < 2) { self.imdct.short(coefficients, &mut block); } else { - let block_type = if short { 0 } else { granule.block_type }; - self.imdct.long(coefficients, block_type, &mut block); + let block_type = if short { BlockType::Normal } else { granule.block_type }; + self.imdct.long(coefficients, block_type as u8, &mut block); } let overlap = &mut self.overlap[ch][sb]; for t in 0..18 { @@ -736,7 +759,7 @@ impl Mp3Reader { return Err(Error::NeedMore); } let frame = &data[..frame_len]; - if !self.started && header.layer == 3 && is_info_frame(&header, frame) { + if !self.started && header.layer == Layer::III && is_info_frame(&header, frame) { self.started = true; self.consumed += frame_len; continue; diff --git a/crates/ec-mp3/src/encode.rs b/crates/ec-mp3/src/encode.rs index 14502707..4a0a7095 100644 --- a/crates/ec-mp3/src/encode.rs +++ b/crates/ec-mp3/src/encode.rs @@ -18,7 +18,7 @@ //! makes available. use crate::filterbank::{Analysis, alias_expand}; -use crate::header::{ChannelMode, FrameHeader, Version}; +use crate::header::{ChannelMode, FrameHeader, Layer, Version}; use crate::huffman::{self, BitBuf}; use crate::tables::{ MAX_QUANT, SLEN, forward_mdct_long, forward_mdct_short, long_starts, power43, short_starts, @@ -251,7 +251,7 @@ impl Mp3Encode { fn header(&self, bitrate_kbps: u32, padding: bool) -> FrameHeader { FrameHeader { version: self.version, - layer: 3, + layer: Layer::III, crc: false, bitrate_kbps, sample_rate: self.sample_rate, diff --git a/crates/ec-mp3/src/header.rs b/crates/ec-mp3/src/header.rs index 4780da9b..bcb8a493 100644 --- a/crates/ec-mp3/src/header.rs +++ b/crates/ec-mp3/src/header.rs @@ -15,6 +15,17 @@ pub enum Version { Mpeg25, } +/// The MPEG audio layer a frame is coded with. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Layer { + /// Layer I: 384 samples per frame. + I, + /// Layer II: 1152 samples per frame. + II, + /// Layer III: 576 samples per granule, one or two granules per frame. + III, +} + /// The channel arrangement a frame declares. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ChannelMode { @@ -55,13 +66,13 @@ const BITRATES_L2_V1: [u32; 15] = [ /// The bitrate table for a layer of a version: Layer III and Layer II of the /// low sampling frequencies share one, the other four combinations each have /// their own. -fn bitrate_table(version: Version, layer: u8) -> &'static [u32; 15] { +fn bitrate_table(version: Version, layer: Layer) -> &'static [u32; 15] { match (version == Version::Mpeg1, layer) { - (true, 1) => &BITRATES_L1_V1, - (true, 2) => &BITRATES_L2_V1, - (true, _) => &BITRATES_V1, - (false, 1) => &BITRATES_L1_V2, - (false, _) => &BITRATES_V2, + (true, Layer::I) => &BITRATES_L1_V1, + (true, Layer::II) => &BITRATES_L2_V1, + (true, Layer::III) => &BITRATES_V1, + (false, Layer::I) => &BITRATES_L1_V2, + (false, Layer::II | Layer::III) => &BITRATES_V2, } } const RATES_V1: [u32; 3] = [44100, 48000, 32000]; @@ -71,8 +82,8 @@ const RATES_V1: [u32; 3] = [44100, 48000, 32000]; pub struct FrameHeader { /// MPEG generation. pub version: Version, - /// Layer number, 1..=3. - pub layer: u8, + /// The MPEG audio layer. + pub layer: Layer, /// True when a 16-bit CRC follows the header. pub crc: bool, /// Declared bitrate in kbit/s; 0 means free format. @@ -116,9 +127,9 @@ impl FrameHeader { _ => return Err(Error::corrupt("mp3: reserved MPEG version id")), }; let layer = match (b[1] >> 1) & 3 { - 1 => 3, - 2 => 2, - 3 => 1, + 1 => Layer::III, + 2 => Layer::II, + 3 => Layer::I, _ => return Err(Error::corrupt("mp3: reserved layer id")), }; let crc = (b[1] & 1) == 0; @@ -166,9 +177,9 @@ impl FrameHeader { Version::Mpeg1 => 3, }; let layer_id = match self.layer { - 3 => 1, - 2 => 2, - _ => 3, + Layer::III => 1, + Layer::II => 2, + Layer::I => 3, }; let bitrate_index = bitrate_table(self.version, self.layer) .iter() @@ -215,9 +226,9 @@ impl FrameHeader { /// PCM samples per channel produced by this frame. pub fn samples_per_frame(&self) -> usize { match self.layer { - 1 => 384, - 2 => 1152, - _ => self.granules() * 576, + Layer::I => 384, + Layer::II => 1152, + Layer::III => self.granules() * 576, } } @@ -241,10 +252,10 @@ impl FrameHeader { let rate = self.sample_rate as usize; let pad = usize::from(self.padding); Some(match self.layer { - 1 => (12 * bits / rate + pad) * 4, - 2 => 144 * bits / rate + pad, - _ if self.version == Version::Mpeg1 => 144 * bits / rate + pad, - _ => 72 * bits / rate + pad, + Layer::I => (12 * bits / rate + pad) * 4, + Layer::II => 144 * bits / rate + pad, + Layer::III if self.version == Version::Mpeg1 => 144 * bits / rate + pad, + Layer::III => 72 * bits / rate + pad, }) } } @@ -298,7 +309,7 @@ mod tests { let bytes = [0xFF, 0xFB, 0x90, 0x00]; let h = FrameHeader::parse(&bytes).unwrap(); assert_eq!(h.version, Version::Mpeg1); - assert_eq!(h.layer, 3); + assert_eq!(h.layer, Layer::III); assert_eq!(h.bitrate_kbps, 128); assert_eq!(h.sample_rate, 44100); assert_eq!(h.mode, ChannelMode::Stereo); diff --git a/crates/ec-mp3/src/layer12.rs b/crates/ec-mp3/src/layer12.rs index 83407ea2..7679dafd 100644 --- a/crates/ec-mp3/src/layer12.rs +++ b/crates/ec-mp3/src/layer12.rs @@ -7,7 +7,7 @@ //! copied: `scripts/mp2-tables/measure.py` sets one allocation code at a time and //! reads the quantiser size back from the decoded level. -use crate::header::{ChannelMode, FrameHeader, Version, crc16_bits}; +use crate::header::{ChannelMode, FrameHeader, Layer, Version, crc16_bits}; use crate::window::WINDOW; use ec_core::bitio::BitReader; use ec_core::error::{Error, Result}; @@ -188,7 +188,7 @@ impl Layer12 { let body = &frame[4 + usize::from(header.crc) * 2..]; let mut r = BitReader::new(body); let mut subband = vec![[[0.0f32; 32]; 2]; 36]; - let slots = if header.layer == 1 { + let slots = if header.layer == Layer::I { self.read_layer1(header, frame, &mut r, &mut subband)?; 12 } else { diff --git a/crates/ec-mp3/tests/mp2_matrix.rs b/crates/ec-mp3/tests/mp2_matrix.rs index d63f9f49..e3d530be 100644 --- a/crates/ec-mp3/tests/mp2_matrix.rs +++ b/crates/ec-mp3/tests/mp2_matrix.rs @@ -10,6 +10,7 @@ use std::path::PathBuf; +use ec_mp3::header::Layer; use ec_mp3::{FrameHeader, Mp3Reader}; fn work_dir() -> PathBuf { @@ -18,8 +19,8 @@ fn work_dir() -> PathBuf { d } -fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec { - let decoder = if layer == 1 { "mp1float" } else { "mp2float" }; +fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: Layer) -> Vec { + let decoder = if layer == Layer::I { "mp1float" } else { "mp2float" }; let out = ec_testkit::ffmpeg() .args(["-v", "error", "-c:a", decoder, "-i"]) .arg(path) @@ -40,8 +41,8 @@ fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec } /// ffmpeg's fixed-point decoder (the default `mp2`/`mp1`): s16 out. -fn ffmpeg_decode_s16(path: &std::path::Path, channels: usize, layer: u8) -> Vec { - let decoder = if layer == 1 { "mp1" } else { "mp2" }; +fn ffmpeg_decode_s16(path: &std::path::Path, channels: usize, layer: Layer) -> Vec { + let decoder = if layer == Layer::I { "mp1" } else { "mp2" }; let out = ec_testkit::ffmpeg() .args(["-v", "error", "-c:a", decoder, "-i"]) .arg(path) @@ -192,7 +193,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option> 20) as u32 % n.max(1); let (nb_sb, bound); let rows: Vec>; - if h.layer == 1 { + if h.layer == Layer::I { nb_sb = 32; rows = Vec::new(); } else { @@ -207,14 +208,14 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option u32 { - if h.layer == 1 { + if h.layer == Layer::I { 4 } else { rows[sb].len().trailing_zeros() } }; for sb in 0..nb_sb { - let maxcode = if h.layer == 1 { + let maxcode = if h.layer == Layer::I { 15 } else { rows[sb].len() as u32 @@ -247,7 +248,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option Option Option