forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'simplify/s10' into simplify/w2

Browse files at this commit

3f8e1d575d06b0147fde89a2b7f632f28a8e4761Ahmet Kaan GümüşParent: 4bfe6919cca91e
crates/ec-aac/src/decode.rsmodified+81 -74
@@ -308,7 +308,6 @@ struct Ics {
308308 pub struct ChannelState {
309309 overlap: Vec<f32>,
310310 prev_shape_kbd: bool,
311- prev_short: bool,
312311 }
313312
314313 impl Default for ChannelState {
@@ -316,7 +315,6 @@ impl Default for ChannelState {
316315 ChannelState {
317316 overlap: vec![0.0; FRAME_LEN],
318317 prev_shape_kbd: false,
319- prev_short: false,
320318 }
321319 }
322320 }
@@ -424,7 +422,6 @@ impl FilterBank {
424422 }
425423 state.overlap.copy_from_slice(&frame[FRAME_LEN..]);
426424 state.prev_shape_kbd = ics.window_shape_kbd;
427- state.prev_short = ics.window_sequence.is_short();
428425 }
429426 }
430427
@@ -791,6 +788,86 @@ impl BlockDecoder {
791788 }
792789 }
793790
791+ fn fill_element(
792+ &mut self,
793+ r: &mut BitReader<'_>,
794+ out: &mut Vec<Vec<f32>>,
795+ pending: &mut Option<(u8, usize, usize, bool)>,
796+ ) -> Result<()> {
797+ let mut count = r.read_bits(4)? as u64;
798+ if count == 15 {
799+ // 15 + esc - 1, written so an escape of 0 cannot underflow.
800+ count = 14 + r.read_bits(8)? as u64;
801+ }
802+ let end_bit = r.bit_position() + count * 8;
803+ // Implicit SBR: no SBR in the config, but this FIL is the first
804+ // to carry an SBR extension right after an element. Arm the
805+ // chain for it; if its payload does not parse, disarm again.
806+ let arming = match self.implicit_core {
807+ Some(core)
808+ if self.sbr.is_none()
809+ && pending.is_some()
810+ && r.bits_remaining() >= 4
811+ && matches!(r.peek_bits(4)?, 13 | 14) =>
812+ {
813+ self.sbr = Some(crate::sbr_chain::SbrChain::new(core * 2));
814+ true
815+ }
816+ _ => false,
817+ };
818+ let mut applied = false;
819+ if let (Some(sbr), Some((tag, start, n, is_cpe))) =
820+ (self.sbr.as_mut(), pending.take())
821+ {
822+ // extension_payload(): bs_extension_type(4), then
823+ // (for SBR) an optional 10-bit CRC, then
824+ // sbr_extension_data() itself.
825+ if r.bits_remaining() >= 4 {
826+ let ext_type = r.peek_bits(4)?;
827+ if ext_type == 13 || ext_type == 14 {
828+ r.skip_bits(4)?;
829+ if ext_type == 14 && r.bits_remaining() >= 10 {
830+ r.skip_bits(10)?; // bs_sbr_crc_bits
831+ }
832+ if let Some(data) = sbr.parse(r, tag, is_cpe) {
833+ if data.ps.is_some() && (arming || self.implicit_on) {
834+ self.implicit_ps = true;
835+ }
836+ sbr.apply_planes(tag, is_cpe, &data, out, start, n)?;
837+ applied = true;
838+ }
839+ }
840+ }
841+ if !applied && !arming {
842+ // No fresh SBR payload this frame (no SBR fill
843+ // element, or one whose extension_type wasn't
844+ // SBR, or a parse failure): §4.6.18 still
845+ // requires doubled-rate reconstruction, using
846+ // the last successfully parsed frame's data.
847+ sbr.apply_last_planes(tag, is_cpe, out, start, n)?;
848+ }
849+ }
850+ if arming {
851+ if applied {
852+ self.implicit_on = true;
853+ self.implicit_core = None;
854+ } else {
855+ // The payload did not parse: this was not SBR after all.
856+ self.sbr = None;
857+ }
858+ }
859+ // Resync to the FIL's declared byte boundary regardless
860+ // of how many bits SBR parsing above actually consumed:
861+ // a parse error or trailing padding must never desync
862+ // the elements that follow.
863+ let now = r.bit_position();
864+ if now < end_bit {
865+ r.skip_bits(end_bit - now)?;
866+ }
867+ *pending = None;
868+ Ok(())
869+ }
870+
794871 /// Decodes one `raw_data_block`, returning one PCM plane per channel in
795872 /// bitstream element order.
796873 pub fn raw_data_block(&mut self, r: &mut BitReader<'_>) -> Result<Vec<Vec<f32>>> {
@@ -890,77 +967,7 @@ impl BlockDecoder {
890967 pending = None;
891968 }
892969 6 => {
893- let mut count = r.read_bits(4)? as u64;
894- if count == 15 {
895- // 15 + esc - 1, written so an escape of 0 cannot underflow.
896- count = 14 + r.read_bits(8)? as u64;
897- }
898- let end_bit = r.bit_position() + count * 8;
899- // Implicit SBR: no SBR in the config, but this FIL is the first
900- // to carry an SBR extension right after an element. Arm the
901- // chain for it; if its payload does not parse, disarm again.
902- let arming = match self.implicit_core {
903- Some(core)
904- if self.sbr.is_none()
905- && pending.is_some()
906- && r.bits_remaining() >= 4
907- && matches!(r.peek_bits(4)?, 13 | 14) =>
908- {
909- self.sbr = Some(crate::sbr_chain::SbrChain::new(core * 2));
910- true
911- }
912- _ => false,
913- };
914- let mut applied = false;
915- if let (Some(sbr), Some((tag, start, n, is_cpe))) =
916- (self.sbr.as_mut(), pending.take())
917- {
918- // extension_payload(): bs_extension_type(4), then
919- // (for SBR) an optional 10-bit CRC, then
920- // sbr_extension_data() itself.
921- if r.bits_remaining() >= 4 {
922- let ext_type = r.peek_bits(4)?;
923- if ext_type == 13 || ext_type == 14 {
924- r.skip_bits(4)?;
925- if ext_type == 14 && r.bits_remaining() >= 10 {
926- r.skip_bits(10)?; // bs_sbr_crc_bits
927- }
928- if let Some(data) = sbr.parse(r, tag, is_cpe) {
929- if data.ps.is_some() && (arming || self.implicit_on) {
930- self.implicit_ps = true;
931- }
932- sbr.apply_planes(tag, is_cpe, &data, &mut out, start, n)?;
933- applied = true;
934- }
935- }
936- }
937- if !applied && !arming {
938- // No fresh SBR payload this frame (no SBR fill
939- // element, or one whose extension_type wasn't
940- // SBR, or a parse failure): §4.6.18 still
941- // requires doubled-rate reconstruction, using
942- // the last successfully parsed frame's data.
943- sbr.apply_last_planes(tag, is_cpe, &mut out, start, n)?;
944- }
945- }
946- if arming {
947- if applied {
948- self.implicit_on = true;
949- self.implicit_core = None;
950- } else {
951- // The payload did not parse: this was not SBR after all.
952- self.sbr = None;
953- }
954- }
955- // Resync to the FIL's declared byte boundary regardless
956- // of how many bits SBR parsing above actually consumed:
957- // a parse error or trailing padding must never desync
958- // the elements that follow.
959- let now = r.bit_position();
960- if now < end_bit {
961- r.skip_bits(end_bit - now)?;
962- }
963- pending = None;
970+ self.fill_element(r, &mut out, &mut pending)?;
964971 }
965972 _ => {
966973 // The block ended with no FIL element ever following the
crates/ec-aac/src/encode.rsmodified+37 -17
@@ -538,11 +538,11 @@ impl AacEncoder {
538538 let mut ms = vec![false; max_sfb];
539539 if *element == Element::Cpe && self.config.mid_side {
540540 for b in 0..max_sfb {
541- if ms_wins(&pair[0], &pair[1], swb, b, short) {
541+ if ms_wins(&pair[0], &pair[1], swb, b, seq) {
542542 ms[b] = true;
543543 }
544544 }
545- apply_ms(&mut pair, &ms, swb, max_sfb, short);
545+ apply_ms(&mut pair, &ms, swb, max_sfb, seq);
546546 }
547547 elements.push(ElementPlan {
548548 element: *element,
@@ -563,7 +563,7 @@ impl AacEncoder {
563563 .map(|plan| {
564564 plan.frames
565565 .iter()
566- .map(|frame| band_profile(frame, swb, max_sfb, short))
566+ .map(|frame| band_profile(frame, swb, max_sfb, seq))
567567 .collect()
568568 })
569569 .collect();
@@ -759,14 +759,14 @@ impl AacEncoder {
759759 max_sfb,
760760 b,
761761 floor[b],
762- || self.band_noise(frame, swb, b, floor[b], windows, short),
762+ || self.band_noise(frame, swb, b, floor[b], windows, seq),
763763 ) <= target
764764 {
765765 let (mut lo, mut hi) = (floor[b], 255);
766766 while lo < hi {
767767 let mid = lo + (hi - lo + 1) / 2;
768768 if memo.noise(ch_slot, max_sfb, b, mid, || {
769- self.band_noise(frame, swb, b, mid, windows, short)
769+ self.band_noise(frame, swb, b, mid, windows, seq)
770770 }) <= target {
771771 lo = mid;
772772 } else {
@@ -848,7 +848,7 @@ impl AacEncoder {
848848 if books[b] == 0 {
849849 continue;
850850 }
851- bits += band_bits(&quant, swb, b, books[b], windows, short);
851+ bits += band_bits(&quant, swb, b, books[b], windows, seq);
852852 let value = prev.map_or(60, |p| (60 + sf[b] - p).clamp(0, 120));
853853 bits += i32::from(SCALEFACTOR_CODES[value as usize].0);
854854 prev = Some(sf[b]);
@@ -871,7 +871,6 @@ impl AacEncoder {
871871 books,
872872 quant,
873873 bits,
874- short,
875874 }
876875 }
877876
@@ -883,8 +882,9 @@ impl AacEncoder {
883882 band: usize,
884883 sf: i32,
885884 windows: usize,
886- short: bool,
885+ seq: WindowSequence,
887886 ) -> f32 {
887+ let short = seq == WindowSequence::EightShort;
888888 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
889889 let gain = pow_quarter(sf - SF_OFFSET);
890890 let gain_inv = pow_quarter(SF_OFFSET - sf);
@@ -922,12 +922,18 @@ struct Coded {
922922 books: Vec<u8>,
923923 quant: Vec<i32>,
924924 bits: i32,
925- short: bool,
926925 }
927926
928927 /// True when mid/side splits this band's energy more lopsidedly than left/right
929928 /// does, which is when it costs fewer bits.
930-fn ms_wins(l: &ChannelFrame, r: &ChannelFrame, swb: &[u16], band: usize, short: bool) -> bool {
929+fn ms_wins(
930+ l: &ChannelFrame,
931+ r: &ChannelFrame,
932+ swb: &[u16],
933+ band: usize,
934+ seq: WindowSequence,
935+) -> bool {
936+ let short = seq == WindowSequence::EightShort;
931937 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
932938 let windows = if short { 8 } else { 1 };
933939 let (mut el, mut er, mut em, mut es) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
@@ -958,7 +964,13 @@ struct BandProfile {
958964 floor: Vec<i32>,
959965 }
960966
961-fn band_profile(frame: &ChannelFrame, swb: &[u16], max_sfb: usize, short: bool) -> BandProfile {
967+fn band_profile(
968+ frame: &ChannelFrame,
969+ swb: &[u16],
970+ max_sfb: usize,
971+ seq: WindowSequence,
972+) -> BandProfile {
973+ let short = seq == WindowSequence::EightShort;
962974 let windows = if short { 8 } else { 1 };
963975 let mut peak = vec![0.0f32; max_sfb];
964976 let mut energy = vec![0.0f32; max_sfb];
@@ -1024,7 +1036,14 @@ impl NoiseMemo {
10241036 }
10251037 }
10261038
1027-fn apply_ms(pair: &mut [ChannelFrame], ms: &[bool], swb: &[u16], max_sfb: usize, short: bool) {
1039+fn apply_ms(
1040+ pair: &mut [ChannelFrame],
1041+ ms: &[bool],
1042+ swb: &[u16],
1043+ max_sfb: usize,
1044+ seq: WindowSequence,
1045+) {
1046+ let short = seq == WindowSequence::EightShort;
10281047 let windows = if short { 8 } else { 1 };
10291048 for b in 0..max_sfb {
10301049 if !ms[b] {
@@ -1125,8 +1144,9 @@ fn band_bits(
11251144 band: usize,
11261145 book: u8,
11271146 windows: usize,
1128- short: bool,
1147+ seq: WindowSequence,
11291148 ) -> i32 {
1149+ let short = seq == WindowSequence::EightShort;
11301150 let cb = &CODEBOOKS[usize::from(book) - 1];
11311151 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
11321152 let dim = usize::from(cb.dim);
@@ -1218,7 +1238,7 @@ fn write_ics_info(w: &mut BitWriter, c: &Coded) {
12181238 };
12191239 w.write_bits(seq, 2);
12201240 w.write_bit(false); // sine window shape
1221- if c.short {
1241+ if c.seq == WindowSequence::EightShort {
12221242 w.write_bits(c.max_sfb as u32, 4);
12231243 w.write_bits(0x7F, 7); // one group of eight windows
12241244 } else {
@@ -1235,7 +1255,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) {
12351255 write_ics_info(w, c);
12361256 }
12371257 // section_data
1238- let esc_bits = if c.short { 3 } else { 5 };
1258+ let esc_bits = if c.seq == WindowSequence::EightShort { 3 } else { 5 };
12391259 let esc = (1u32 << esc_bits) - 1;
12401260 let mut b = 0usize;
12411261 while b < c.max_sfb {
@@ -1267,7 +1287,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) {
12671287 w.write_bit(false); // tns_data_present
12681288 w.write_bit(false); // gain_control_data_present
12691289 // spectral_data
1270- let windows = if c.short { 8 } else { 1 };
1290+ let windows = if c.seq == WindowSequence::EightShort { 8 } else { 1 };
12711291 for b in 0..c.max_sfb {
12721292 let book = c.books[b];
12731293 if book == 0 {
@@ -1277,7 +1297,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) {
12771297 let dim = usize::from(cb.dim);
12781298 let (lo, hi) = (usize::from(c.swb[b]), usize::from(c.swb[b + 1]));
12791299 for win in 0..windows {
1280- let base = if c.short { win * SHORT_LEN } else { 0 };
1300+ let base = if c.seq == WindowSequence::EightShort { win * SHORT_LEN } else { 0 };
12811301 let mut k = lo;
12821302 while k < hi {
12831303 let end = (k + dim).min(hi);
crates/ec-aac/src/huffman.rsmodified+33 -0
@@ -83,3 +83,36 @@ impl Default for Books {
8383 Books::new()
8484 }
8585 }
86+
87+#[cfg(test)]
88+pub(crate) fn assert_each_codeword_decodes_to_itself(codes: &[(u8, u32)]) {
89+ let tree = Tree::new(codes);
90+ for (symbol, &(len, code)) in codes.iter().enumerate() {
91+ let mut bytes = [0u8; 8];
92+ for (i, depth) in (0..len).rev().enumerate() {
93+ if (code >> depth) & 1 == 1 {
94+ bytes[i / 8] |= 0x80 >> (i % 8);
95+ }
96+ }
97+ let mut r = BitReader::new(&bytes);
98+ assert_eq!(tree.decode(&mut r).unwrap(), symbol);
99+ }
100+}
101+
102+#[cfg(test)]
103+mod tests {
104+ use super::*;
105+ use crate::sbr_tables::*;
106+
107+ #[test]
108+ fn every_sbr_codeword_decodes_to_its_own_symbol() {
109+ let books: [&[(u8, u32, i32)]; 12] = [
110+ &ENV15_F, &ENV15_T, &ENV30_F, &ENV30_T, &NOISE_F, &NOISE_T, &ENVB15_F, &ENVB15_T,
111+ &ENVB30_F, &ENVB30_T, &NOISEB_F, &NOISEB_T,
112+ ];
113+ for book in books {
114+ let codes: Vec<(u8, u32)> = book.iter().map(|&(len, code, _)| (len, code)).collect();
115+ assert_each_codeword_decodes_to_itself(&codes);
116+ }
117+ }
118+}
crates/ec-aac/src/ps_data.rsmodified+37 -27
@@ -8,6 +8,7 @@
88 //! its handling of stale fields, so that the decoded parameters match the
99 //! reference decoder frame for frame.
1010
11+use crate::huffman::Tree;
1112 use crate::ps_huff;
1213 use ec_core::{BitReader, Error, Result};
1314 use std::sync::OnceLock;
@@ -93,10 +94,21 @@ impl Default for PsCommon {
9394 }
9495 }
9596
96-/// One prefix-code table: every codeword as (length, code, parameter value).
97+/// One prefix-code table: the walkable code tree, and the parameter value of
98+/// each symbol (the tree's symbol is the codeword's index in the table).
9799 struct Vlc {
98- codes: Vec<(u32, u32, i32)>,
99- max_len: u32,
100+ tree: Tree,
101+ values: Vec<i32>,
102+}
103+
104+impl Vlc {
105+ fn new(codes: &[(u32, u32, i32)]) -> Vlc {
106+ let lens_codes: Vec<(u8, u32)> = codes.iter().map(|&(len, code, _)| (len as u8, code)).collect();
107+ Vlc {
108+ tree: Tree::new(&lens_codes),
109+ values: codes.iter().map(|&(_, _, value)| value).collect(),
110+ }
111+ }
100112 }
101113
102114 /// The ten PS Huffman tables, with canonical codes assigned from the lengths.
@@ -106,7 +118,7 @@ fn vlcs() -> &'static [Vlc] {
106118 ps_huff::TABLES
107119 .iter()
108120 .zip(ps_huff::OFFSETS)
109- .map(|(table, offset)| build_codes(table, offset))
121+ .map(|(table, offset)| Vlc::new(&build_codes(table, offset)))
110122 .collect()
111123 })
112124 }
@@ -117,36 +129,23 @@ fn vlcs() -> &'static [Vlc] {
117129 /// lengths alone do not fix the codes, which is why sorting them canonically
118130 /// misreads every fine-IID and ICC frame. Every table in the standard is a
119131 /// complete prefix code, which the unit tests check.
120-fn build_codes(table: &[(u8, u8)], offset: i32) -> Vlc {
132+fn build_codes(table: &[(u8, u8)], offset: i32) -> Vec<(u32, u32, i32)> {
121133 let mut codes = Vec::with_capacity(table.len());
122134 // Position in the code space, in units of 2^-32 (a 64-bit sum: no overflow).
123135 let mut next: u64 = 0;
124- let mut max_len = 0;
125136 for &(value, len) in table {
126137 let len = u32::from(len).clamp(1, 32);
127138 let code = (next >> (32 - len)) as u32;
128139 codes.push((len, code, i32::from(value) + offset));
129140 next += 1u64 << (32 - len);
130- max_len = max_len.max(len);
131141 }
132- Vlc { codes, max_len }
142+ codes
133143 }
134144
135145 /// Reads one codeword of table `which` and returns its parameter value.
136146 fn read_vlc(r: &mut BitReader<'_>, which: usize) -> Result<i32> {
137- let table = &vlcs()[which];
138- let mut code: u32 = 0;
139- for len in 1..=table.max_len {
140- code = (code << 1) | u32::from(r.read_bit()?);
141- if let Some(&(_, _, value)) = table
142- .codes
143- .iter()
144- .find(|&&(l, c, _)| l == len && c == code)
145- {
146- return Ok(value);
147- }
148- }
149- Err(Error::corrupt("ps: no codeword matches the bitstream"))
147+ let vlc = &vlcs()[which];
148+ Ok(vlc.values[vlc.tree.decode(r)?])
150149 }
151150
152151 /// Reads one IID/ICC/IPD/OPD parameter row (FFmpeg's `READ_PAR_DATA`).
@@ -458,17 +457,28 @@ mod tests {
458457 // length 4) and (value +2, length 4), so they get codes 0000 and 0001,
459458 // not the canonical order a length sort would give.
460459 let v = build_codes(ps_huff::TABLES[HUFF_IID_DF1], ps_huff::OFFSETS[HUFF_IID_DF1]);
461- assert_eq!(v.codes[0], (4, 0b0000, -2));
462- assert_eq!(v.codes[1], (4, 0b0001, 2));
463- assert_eq!(v.codes[2], (3, 0b001, -1));
460+ assert_eq!(v[0], (4, 0b0000, -2));
461+ assert_eq!(v[1], (4, 0b0001, 2));
462+ assert_eq!(v[2], (3, 0b001, -1));
463+ }
464+
465+ #[test]
466+ fn every_ps_codeword_decodes_to_its_own_symbol() {
467+ for (i, table) in ps_huff::TABLES.iter().enumerate() {
468+ let codes: Vec<(u8, u32)> = build_codes(table, ps_huff::OFFSETS[i])
469+ .iter()
470+ .map(|&(len, code, _)| (len as u8, code))
471+ .collect();
472+ crate::huffman::assert_each_codeword_decodes_to_itself(&codes);
473+ }
464474 }
465475
466476 #[test]
467477 fn codes_are_prefix_free_and_values_cover_the_range() {
468478 for (i, table) in ps_huff::TABLES.iter().enumerate() {
469479 let v = build_codes(table, ps_huff::OFFSETS[i]);
470- for (a, &(la, ca, _)) in v.codes.iter().enumerate() {
471- for &(lb, cb, _) in v.codes.iter().skip(a + 1) {
480+ for (a, &(la, ca, _)) in v.iter().enumerate() {
481+ for &(lb, cb, _) in v.iter().skip(a + 1) {
472482 let (short, long, cs, cl) = if la <= lb { (la, lb, ca, cb) } else { (lb, la, cb, ca) };
473483 assert!(cl >> (long - short) != cs, "table {i} codes collide");
474484 }
@@ -498,7 +508,7 @@ mod tests {
498508 push(&mut bits, 0, 1); // dt = 0 for the envelope
499509 let code_for_zero = {
500510 let v = build_codes(ps_huff::TABLES[HUFF_IID_DF0], ps_huff::OFFSETS[HUFF_IID_DF0]);
501- *v.codes.iter().find(|c| c.2 == 0).expect("zero is a codeword")
511+ *v.iter().find(|c| c.2 == 0).expect("zero is a codeword")
502512 };
503513 for _ in 0..10 {
504514 push(&mut bits, code_for_zero.1, code_for_zero.0);
crates/ec-aac/src/sbr_chain.rsmodified+58 -36
@@ -377,31 +377,7 @@ impl SbrChain {
377377 continue;
378378 }
379379 let state = &mut elem.channels[ch];
380- let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS];
381- let mut raw = Vec::with_capacity(num_slots);
382- for slot in 0..num_slots {
383- let mut chunk = [0f32; ANALYSIS_BANDS];
384- chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]);
385- // `plane` is already at the decoder's final output scale
386- // (`decode::OUTPUT_SCALE`, applied by the core filterbank),
387- // but the transmitted envelope/noise data is calibrated
388- // against the core's un-normalized internal PCM domain --
389- // undo that scale before analysis so the SBR gain match
390- // (raw QMF energy vs. the transmitted target) compares
391- // like against like, and reapply it once below after
392- // synthesis. Without this the gain step's `target/current`
393- // ratio is inflated by `1/OUTPUT_SCALE^2` in energy,
394- // exactly the multi-order-of-magnitude blowup this chain
395- // used to produce on every real HE-AAC file.
396- for s in &mut chunk {
397- *s /= crate::decode::OUTPUT_SCALE;
398- }
399- let sub = state.analysis.process_slot(&chunk);
400- for b in 0..ANALYSIS_BANDS {
401- low_cur[b][slot] = sub[b];
402- }
403- raw.push(sub);
404- }
380+ let (low_cur, raw) = analyze_plane(state, plane, num_slots);
405381
406382 let sbr_ch = &data.channels[ch];
407383 let hf = sbr_hf::generate(
@@ -481,17 +457,7 @@ impl SbrChain {
481457
482458 let kx = (tables.kx as usize).min(ANALYSIS_BANDS);
483459 let k2 = (tables.k2 as usize).min(band_limit);
484- let mut vs: Vec<[Complex<f64>; SYNTHESIS_BANDS]> = Vec::with_capacity(num_slots);
485- for slot in 0..num_slots {
486- let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
487- v[0..kx].copy_from_slice(&raw[slot][0..kx]);
488- for b in kx..k2 {
489- if b - kx < hf.len() {
490- v[b] = hf[b - kx][slot];
491- }
492- }
493- vs.push(v);
494- }
460+ let vs = merge_bands(&raw, &hf, kx, k2, num_slots);
495461 let out = match (ps_mode && num_slots == PS_SLOTS, data.ps.as_ref()) {
496462 (true, Some(ps)) => {
497463 let (left, right) =
@@ -530,6 +496,62 @@ impl SbrChain {
530496 }
531497 }
532498
499+type QmfGrid = Vec<Vec<Complex<f64>>>;
500+
501+fn analyze_plane(
502+ state: &mut ChannelState,
503+ plane: &[f32],
504+ num_slots: usize,
505+) -> (QmfGrid, Vec<[Complex<f64>; ANALYSIS_BANDS]>) {
506+ let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS];
507+ let mut raw = Vec::with_capacity(num_slots);
508+ for slot in 0..num_slots {
509+ let mut chunk = [0f32; ANALYSIS_BANDS];
510+ chunk.copy_from_slice(&plane[slot * ANALYSIS_BANDS..(slot + 1) * ANALYSIS_BANDS]);
511+ // `plane` is already at the decoder's final output scale
512+ // (`decode::OUTPUT_SCALE`, applied by the core filterbank),
513+ // but the transmitted envelope/noise data is calibrated
514+ // against the core's un-normalized internal PCM domain --
515+ // undo that scale before analysis so the SBR gain match
516+ // (raw QMF energy vs. the transmitted target) compares
517+ // like against like, and reapply it once below after
518+ // synthesis. Without this the gain step's `target/current`
519+ // ratio is inflated by `1/OUTPUT_SCALE^2` in energy,
520+ // exactly the multi-order-of-magnitude blowup this chain
521+ // used to produce on every real HE-AAC file.
522+ for s in &mut chunk {
523+ *s /= crate::decode::OUTPUT_SCALE;
524+ }
525+ let sub = state.analysis.process_slot(&chunk);
526+ for b in 0..ANALYSIS_BANDS {
527+ low_cur[b][slot] = sub[b];
528+ }
529+ raw.push(sub);
530+ }
531+ (low_cur, raw)
532+}
533+
534+fn merge_bands(
535+ raw: &[[Complex<f64>; ANALYSIS_BANDS]],
536+ hf: &[Vec<Complex<f64>>],
537+ kx: usize,
538+ k2: usize,
539+ num_slots: usize,
540+) -> Vec<[Complex<f64>; SYNTHESIS_BANDS]> {
541+ let mut vs: Vec<[Complex<f64>; SYNTHESIS_BANDS]> = Vec::with_capacity(num_slots);
542+ for slot in 0..num_slots {
543+ let mut v = [Complex::ZERO; SYNTHESIS_BANDS];
544+ v[0..kx].copy_from_slice(&raw[slot][0..kx]);
545+ for b in kx..k2 {
546+ if b - kx < hf.len() {
547+ v[b] = hf[b - kx][slot];
548+ }
549+ }
550+ vs.push(v);
551+ }
552+ vs
553+}
554+
533555 /// Inserts the second output plane a PS element needs, right after its first
534556 /// (a copy, which the PS path then overwrites). Returns the element's new
535557 /// plane count: 2 when a plane was inserted.
crates/ec-aac/src/sbr_payload.rsmodified+68 -32
@@ -15,7 +15,9 @@
1515 //! `sbrtables.py` never needed them for the codebook derivation.
1616 #![allow(dead_code)]
1717
18+use crate::huffman::Tree;
1819 use crate::ps_data::PsCommon;
20+use std::sync::LazyLock;
1921 use crate::sbr_bands::{BandTables, freq_tables};
2022 use crate::sbr_tables::*;
2123 use ec_core::{BitReader, Error, Result};
@@ -165,25 +167,74 @@ pub struct SbrParser {
165167 /// `bs_extension_id` of Parametric Stereo.
166168 const EXTENSION_ID_PS: u32 = 2;
167169
168-fn env_book(dt: bool, balance: bool, amp_res: u8) -> &'static [(u8, u32, i32)] {
170+/// One codebook as a walkable tree, and the delta value of each symbol.
171+struct Book {
172+ tree: Tree,
173+ deltas: Vec<i32>,
174+}
175+
176+impl Book {
177+ fn new(entries: &[(u8, u32, i32)]) -> Book {
178+ let codes: Vec<(u8, u32)> = entries.iter().map(|&(len, code, _)| (len, code)).collect();
179+ Book {
180+ tree: Tree::new(&codes),
181+ deltas: entries.iter().map(|&(_, _, delta)| delta).collect(),
182+ }
183+ }
184+}
185+
186+/// The twelve SBR envelope and noise books, built once.
187+struct SbrBooks {
188+ env15_f: Book,
189+ env15_t: Book,
190+ env30_f: Book,
191+ env30_t: Book,
192+ envb15_f: Book,
193+ envb15_t: Book,
194+ envb30_f: Book,
195+ envb30_t: Book,
196+ noise_f: Book,
197+ noise_t: Book,
198+ noiseb_f: Book,
199+ noiseb_t: Book,
200+}
201+
202+static BOOKS: LazyLock<SbrBooks> = LazyLock::new(|| SbrBooks {
203+ env15_f: Book::new(&ENV15_F),
204+ env15_t: Book::new(&ENV15_T),
205+ env30_f: Book::new(&ENV30_F),
206+ env30_t: Book::new(&ENV30_T),
207+ envb15_f: Book::new(&ENVB15_F),
208+ envb15_t: Book::new(&ENVB15_T),
209+ envb30_f: Book::new(&ENVB30_F),
210+ envb30_t: Book::new(&ENVB30_T),
211+ noise_f: Book::new(&NOISE_F),
212+ noise_t: Book::new(&NOISE_T),
213+ noiseb_f: Book::new(&NOISEB_F),
214+ noiseb_t: Book::new(&NOISEB_T),
215+});
216+
217+fn env_book(dt: bool, balance: bool, amp_res: u8) -> &'static Book {
218+ let b = &*BOOKS;
169219 match (balance, amp_res != 0, dt) {
170- (false, false, false) => &ENV15_F,
171- (false, false, true) => &ENV15_T,
172- (false, true, false) => &ENV30_F,
173- (false, true, true) => &ENV30_T,
174- (true, false, false) => &ENVB15_F,
175- (true, false, true) => &ENVB15_T,
176- (true, true, false) => &ENVB30_F,
177- (true, true, true) => &ENVB30_T,
220+ (false, false, false) => &b.env15_f,
221+ (false, false, true) => &b.env15_t,
222+ (false, true, false) => &b.env30_f,
223+ (false, true, true) => &b.env30_t,
224+ (true, false, false) => &b.envb15_f,
225+ (true, false, true) => &b.envb15_t,
226+ (true, true, false) => &b.envb30_f,
227+ (true, true, true) => &b.envb30_t,
178228 }
179229 }
180230
181-fn noise_book(dt: bool, balance: bool) -> &'static [(u8, u32, i32)] {
231+fn noise_book(dt: bool, balance: bool) -> &'static Book {
232+ let b = &*BOOKS;
182233 match (balance, dt) {
183- (false, false) => &NOISE_F,
184- (false, true) => &NOISE_T,
185- (true, false) => &NOISEB_F,
186- (true, true) => &NOISEB_T,
234+ (false, false) => &b.noise_f,
235+ (false, true) => &b.noise_t,
236+ (true, false) => &b.noiseb_f,
237+ (true, true) => &b.noiseb_t,
187238 }
188239 }
189240
@@ -238,24 +289,9 @@ fn map_prev_env(prev: &[i32], tables: &BandTables, cur_high: bool) -> Vec<i32> {
238289 }
239290 }
240291
241-/// Reads one Huffman codeword by walking bit-by-bit until it matches a table
242-/// entry. Every book here is a complete prefix code (Kraft sum 1, checked in
243-/// `sbr_tables`), so a well-formed stream always terminates; a codeword
244-/// longer than any entry means truncated or corrupted input, not a panic.
245-fn read_huffman(r: &mut BitReader, book: &'static [(u8, u32, i32)]) -> Result<i32> {
246- let max_len = book.iter().map(|&(l, _, _)| l).max().unwrap_or(0);
247- let mut code: u32 = 0;
248- let mut len: u8 = 0;
249- loop {
250- code = (code << 1) | u32::from(r.read_bit()?);
251- len += 1;
252- if let Some(&(_, _, delta)) = book.iter().find(|&&(l, c, _)| l == len && c == code) {
253- return Ok(delta);
254- }
255- if len > max_len {
256- return Err(Error::corrupt("sbr: no codeword matched this bit sequence"));
257- }
258- }
292+/// Reads one Huffman codeword and returns its delta.
293+fn read_huffman(r: &mut BitReader, book: &Book) -> Result<i32> {
294+ Ok(book.deltas[book.tree.decode(r)?])
259295 }
260296
261297 impl SbrParser {
crates/ec-mp3/src/decode.rsmodified+38 -15
@@ -2,7 +2,7 @@
22 //! filterbank that turns 576 coefficients back into PCM.
33
44 use crate::filterbank::{Imdct, Synthesis, alias_reduce};
5-use crate::header::{ChannelMode, FrameHeader, Version, crc16};
5+use crate::header::{ChannelMode, FrameHeader, Layer, Version, crc16};
66 use crate::huffman;
77 use crate::layer12::Layer12;
88 use crate::tables::{
@@ -22,6 +22,29 @@ pub struct DecodedFrame {
2222 pub samples: Vec<f32>,
2323 }
2424
25+/// `block_type` of a granule with window switching. Normal when the granule
26+/// does not window-switch. The discriminant indexes the IMDCT window table.
27+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28+#[repr(u8)]
29+enum BlockType {
30+ #[default]
31+ Normal = 0,
32+ Start = 1,
33+ Short = 2,
34+ Stop = 3,
35+}
36+
37+impl BlockType {
38+ fn from_bits(v: u32) -> BlockType {
39+ match v {
40+ 0 => BlockType::Normal,
41+ 1 => BlockType::Start,
42+ 2 => BlockType::Short,
43+ _ => BlockType::Stop,
44+ }
45+ }
46+}
47+
2548 #[derive(Clone, Copy, Debug, Default)]
2649 struct GranuleInfo {
2750 part2_3_length: u32,
@@ -29,7 +52,7 @@ struct GranuleInfo {
2952 global_gain: u32,
3053 scalefac_compress: u32,
3154 window_switching: bool,
32- block_type: u8,
55+ block_type: BlockType,
3356 mixed_block: bool,
3457 table_select: [u8; 3],
3558 subblock_gain: [u32; 3],
@@ -86,7 +109,7 @@ fn parse_side_info(header: &FrameHeader, bytes: &[u8]) -> Result<SideInfo> {
86109 )));
87110 }
88111 if g.window_switching {
89- g.block_type = r.read_bits(2)? as u8;
112+ g.block_type = BlockType::from_bits(r.read_bits(2)?);
90113 g.mixed_block = r.read_bit()?;
91114 for slot in &mut g.table_select[..2] {
92115 *slot = r.read_bits(5)? as u8;
@@ -94,13 +117,13 @@ fn parse_side_info(header: &FrameHeader, bytes: &[u8]) -> Result<SideInfo> {
94117 for slot in &mut g.subblock_gain {
95118 *slot = r.read_bits(3)?;
96119 }
97- g.region0_count = if g.block_type == 2 && !g.mixed_block {
120+ g.region0_count = if g.block_type == BlockType::Short && !g.mixed_block {
98121 8
99122 } else {
100123 7
101124 };
102125 g.region1_count = 20 - g.region0_count;
103- if g.block_type == 0 {
126+ if g.block_type == BlockType::Normal {
104127 return Err(Error::corrupt(
105128 "mp3: window switching with normal block type",
106129 ));
@@ -192,7 +215,7 @@ impl Mp3Decode {
192215 if frame.len() < frame_len {
193216 return Err(Error::NeedMore);
194217 }
195- if header.layer != 3 {
218+ if header.layer != Layer::III {
196219 let samples = self.layer12.decode(&header, &frame[..frame_len])?;
197220 return Ok(DecodedFrame {
198221 sample_rate: header.sample_rate,
@@ -309,7 +332,7 @@ impl Mp3Decode {
309332 ) -> Result<()> {
310333 let granule = side.granules[gr][ch];
311334 let (slen1, slen2) = SLEN[(granule.scalefac_compress & 15) as usize];
312- if granule.window_switching && granule.block_type == 2 {
335+ if granule.block_type == BlockType::Short {
313336 if granule.mixed_block {
314337 for sfb in 0..8 {
315338 self.scalefac_l[ch][sfb] = reader.read_bits(slen1)? as u8;
@@ -386,7 +409,7 @@ impl Mp3Decode {
386409 slen = [sfc / 3, sfc % 3, 0, 0];
387410 block_number = 2;
388411 }
389- let short = granule.window_switching && granule.block_type == 2;
412+ let short = granule.block_type == BlockType::Short;
390413 let kind = if !short {
391414 0
392415 } else if granule.mixed_block {
@@ -427,7 +450,7 @@ impl Mp3Decode {
427450 let is = &mut self.is[ch];
428451 is.fill(0);
429452 let starts = long_starts(header.sample_rate);
430- let short = granule.window_switching && granule.block_type == 2;
453+ let short = granule.block_type == BlockType::Short;
431454 let (region1, region2) = if granule.window_switching {
432455 if short {
433456 // Three short bands, all three windows: 36 lines at every rate
@@ -493,7 +516,7 @@ impl Mp3Decode {
493516 let power = power43();
494517 let xr = &mut self.xr[ch];
495518 let is = &self.is[ch];
496- let short = granule.window_switching && granule.block_type == 2;
519+ let short = granule.block_type == BlockType::Short;
497520 let multiplier = if granule.scalefac_scale { 1.0 } else { 0.5 };
498521 let base = (granule.global_gain as f32 - 210.0) * 0.25;
499522 let value = |v: i32| -> f32 {
@@ -566,7 +589,7 @@ impl Mp3Decode {
566589 let ms = joint && header.mode_ext & 2 != 0;
567590 let intensity = joint && header.mode_ext & 1 != 0;
568591 let granule = side.granules[gr][0];
569- let short = granule.window_switching && granule.block_type == 2;
592+ let short = granule.block_type == BlockType::Short;
570593 // Intensity coding starts at the first band above the right channel's
571594 // last non-zero line.
572595 let bound = if intensity {
@@ -624,7 +647,7 @@ impl Mp3Decode {
624647 channels: usize,
625648 out: &mut [f32],
626649 ) {
627- let short = granule.window_switching && granule.block_type == 2;
650+ let short = granule.block_type == BlockType::Short;
628651 let alias_bands = if !short {
629652 32
630653 } else if granule.mixed_block {
@@ -643,8 +666,8 @@ impl Mp3Decode {
643666 if short && !(granule.mixed_block && sb < 2) {
644667 self.imdct.short(coefficients, &mut block);
645668 } else {
646- let block_type = if short { 0 } else { granule.block_type };
647- self.imdct.long(coefficients, block_type, &mut block);
669+ let block_type = if short { BlockType::Normal } else { granule.block_type };
670+ self.imdct.long(coefficients, block_type as u8, &mut block);
648671 }
649672 let overlap = &mut self.overlap[ch][sb];
650673 for t in 0..18 {
@@ -736,7 +759,7 @@ impl Mp3Reader {
736759 return Err(Error::NeedMore);
737760 }
738761 let frame = &data[..frame_len];
739- if !self.started && header.layer == 3 && is_info_frame(&header, frame) {
762+ if !self.started && header.layer == Layer::III && is_info_frame(&header, frame) {
740763 self.started = true;
741764 self.consumed += frame_len;
742765 continue;
crates/ec-mp3/src/encode.rsmodified+2 -2
@@ -18,7 +18,7 @@
1818 //! makes available.
1919
2020 use crate::filterbank::{Analysis, alias_expand};
21-use crate::header::{ChannelMode, FrameHeader, Version};
21+use crate::header::{ChannelMode, FrameHeader, Layer, Version};
2222 use crate::huffman::{self, BitBuf};
2323 use crate::tables::{
2424 MAX_QUANT, SLEN, forward_mdct_long, forward_mdct_short, long_starts, power43, short_starts,
@@ -251,7 +251,7 @@ impl Mp3Encode {
251251 fn header(&self, bitrate_kbps: u32, padding: bool) -> FrameHeader {
252252 FrameHeader {
253253 version: self.version,
254- layer: 3,
254+ layer: Layer::III,
255255 crc: false,
256256 bitrate_kbps,
257257 sample_rate: self.sample_rate,
crates/ec-mp3/src/header.rsmodified+33 -22
@@ -15,6 +15,17 @@ pub enum Version {
1515 Mpeg25,
1616 }
1717
18+/// The MPEG audio layer a frame is coded with.
19+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20+pub enum Layer {
21+ /// Layer I: 384 samples per frame.
22+ I,
23+ /// Layer II: 1152 samples per frame.
24+ II,
25+ /// Layer III: 576 samples per granule, one or two granules per frame.
26+ III,
27+}
28+
1829 /// The channel arrangement a frame declares.
1930 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
2031 pub enum ChannelMode {
@@ -55,13 +66,13 @@ const BITRATES_L2_V1: [u32; 15] = [
5566 /// The bitrate table for a layer of a version: Layer III and Layer II of the
5667 /// low sampling frequencies share one, the other four combinations each have
5768 /// their own.
58-fn bitrate_table(version: Version, layer: u8) -> &'static [u32; 15] {
69+fn bitrate_table(version: Version, layer: Layer) -> &'static [u32; 15] {
5970 match (version == Version::Mpeg1, layer) {
60- (true, 1) => &BITRATES_L1_V1,
61- (true, 2) => &BITRATES_L2_V1,
62- (true, _) => &BITRATES_V1,
63- (false, 1) => &BITRATES_L1_V2,
64- (false, _) => &BITRATES_V2,
71+ (true, Layer::I) => &BITRATES_L1_V1,
72+ (true, Layer::II) => &BITRATES_L2_V1,
73+ (true, Layer::III) => &BITRATES_V1,
74+ (false, Layer::I) => &BITRATES_L1_V2,
75+ (false, Layer::II | Layer::III) => &BITRATES_V2,
6576 }
6677 }
6778 const RATES_V1: [u32; 3] = [44100, 48000, 32000];
@@ -71,8 +82,8 @@ const RATES_V1: [u32; 3] = [44100, 48000, 32000];
7182 pub struct FrameHeader {
7283 /// MPEG generation.
7384 pub version: Version,
74- /// Layer number, 1..=3.
75- pub layer: u8,
85+ /// The MPEG audio layer.
86+ pub layer: Layer,
7687 /// True when a 16-bit CRC follows the header.
7788 pub crc: bool,
7889 /// Declared bitrate in kbit/s; 0 means free format.
@@ -116,9 +127,9 @@ impl FrameHeader {
116127 _ => return Err(Error::corrupt("mp3: reserved MPEG version id")),
117128 };
118129 let layer = match (b[1] >> 1) & 3 {
119- 1 => 3,
120- 2 => 2,
121- 3 => 1,
130+ 1 => Layer::III,
131+ 2 => Layer::II,
132+ 3 => Layer::I,
122133 _ => return Err(Error::corrupt("mp3: reserved layer id")),
123134 };
124135 let crc = (b[1] & 1) == 0;
@@ -166,9 +177,9 @@ impl FrameHeader {
166177 Version::Mpeg1 => 3,
167178 };
168179 let layer_id = match self.layer {
169- 3 => 1,
170- 2 => 2,
171- _ => 3,
180+ Layer::III => 1,
181+ Layer::II => 2,
182+ Layer::I => 3,
172183 };
173184 let bitrate_index = bitrate_table(self.version, self.layer)
174185 .iter()
@@ -215,9 +226,9 @@ impl FrameHeader {
215226 /// PCM samples per channel produced by this frame.
216227 pub fn samples_per_frame(&self) -> usize {
217228 match self.layer {
218- 1 => 384,
219- 2 => 1152,
220- _ => self.granules() * 576,
229+ Layer::I => 384,
230+ Layer::II => 1152,
231+ Layer::III => self.granules() * 576,
221232 }
222233 }
223234
@@ -241,10 +252,10 @@ impl FrameHeader {
241252 let rate = self.sample_rate as usize;
242253 let pad = usize::from(self.padding);
243254 Some(match self.layer {
244- 1 => (12 * bits / rate + pad) * 4,
245- 2 => 144 * bits / rate + pad,
246- _ if self.version == Version::Mpeg1 => 144 * bits / rate + pad,
247- _ => 72 * bits / rate + pad,
255+ Layer::I => (12 * bits / rate + pad) * 4,
256+ Layer::II => 144 * bits / rate + pad,
257+ Layer::III if self.version == Version::Mpeg1 => 144 * bits / rate + pad,
258+ Layer::III => 72 * bits / rate + pad,
248259 })
249260 }
250261 }
@@ -298,7 +309,7 @@ mod tests {
298309 let bytes = [0xFF, 0xFB, 0x90, 0x00];
299310 let h = FrameHeader::parse(&bytes).unwrap();
300311 assert_eq!(h.version, Version::Mpeg1);
301- assert_eq!(h.layer, 3);
312+ assert_eq!(h.layer, Layer::III);
302313 assert_eq!(h.bitrate_kbps, 128);
303314 assert_eq!(h.sample_rate, 44100);
304315 assert_eq!(h.mode, ChannelMode::Stereo);
crates/ec-mp3/src/layer12.rsmodified+2 -2
@@ -7,7 +7,7 @@
77 //! copied: `scripts/mp2-tables/measure.py` sets one allocation code at a time and
88 //! reads the quantiser size back from the decoded level.
99
10-use crate::header::{ChannelMode, FrameHeader, Version, crc16_bits};
10+use crate::header::{ChannelMode, FrameHeader, Layer, Version, crc16_bits};
1111 use crate::window::WINDOW;
1212 use ec_core::bitio::BitReader;
1313 use ec_core::error::{Error, Result};
@@ -188,7 +188,7 @@ impl Layer12 {
188188 let body = &frame[4 + usize::from(header.crc) * 2..];
189189 let mut r = BitReader::new(body);
190190 let mut subband = vec![[[0.0f32; 32]; 2]; 36];
191- let slots = if header.layer == 1 {
191+ let slots = if header.layer == Layer::I {
192192 self.read_layer1(header, frame, &mut r, &mut subband)?;
193193 12
194194 } else {
crates/ec-mp3/tests/mp2_matrix.rsmodified+11 -10
@@ -10,6 +10,7 @@
1010
1111 use std::path::PathBuf;
1212
13+use ec_mp3::header::Layer;
1314 use ec_mp3::{FrameHeader, Mp3Reader};
1415
1516 fn work_dir() -> PathBuf {
@@ -18,8 +19,8 @@ fn work_dir() -> PathBuf {
1819 d
1920 }
2021
21-fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec<f32> {
22- let decoder = if layer == 1 { "mp1float" } else { "mp2float" };
22+fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: Layer) -> Vec<f32> {
23+ let decoder = if layer == Layer::I { "mp1float" } else { "mp2float" };
2324 let out = ec_testkit::ffmpeg()
2425 .args(["-v", "error", "-c:a", decoder, "-i"])
2526 .arg(path)
@@ -40,8 +41,8 @@ fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec<f32>
4041 }
4142
4243 /// ffmpeg's fixed-point decoder (the default `mp2`/`mp1`): s16 out.
43-fn ffmpeg_decode_s16(path: &std::path::Path, channels: usize, layer: u8) -> Vec<i16> {
44- let decoder = if layer == 1 { "mp1" } else { "mp2" };
44+fn ffmpeg_decode_s16(path: &std::path::Path, channels: usize, layer: Layer) -> Vec<i16> {
45+ let decoder = if layer == Layer::I { "mp1" } else { "mp2" };
4546 let out = ec_testkit::ffmpeg()
4647 .args(["-v", "error", "-c:a", decoder, "-i"])
4748 .arg(path)
@@ -192,7 +193,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec<
192193 let rnd = |rng: &mut Rng, n: u32| (rng.next() >> 20) as u32 % n.max(1);
193194 let (nb_sb, bound);
194195 let rows: Vec<Vec<u32>>;
195- if h.layer == 1 {
196+ if h.layer == Layer::I {
196197 nb_sb = 32;
197198 rows = Vec::new();
198199 } else {
@@ -207,14 +208,14 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec<
207208 // allocation codes
208209 let mut alloc = vec![vec![0u32; nb_sb]; 2];
209210 let width = |sb: usize| -> u32 {
210- if h.layer == 1 {
211+ if h.layer == Layer::I {
211212 4
212213 } else {
213214 rows[sb].len().trailing_zeros()
214215 }
215216 };
216217 for sb in 0..nb_sb {
217- let maxcode = if h.layer == 1 {
218+ let maxcode = if h.layer == Layer::I {
218219 15
219220 } else {
220221 rows[sb].len() as u32
@@ -247,7 +248,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec<
247248 }
248249 }
249250 let mut scfsi = vec![vec![0u32; nb_sb]; 2];
250- if h.layer == 2 {
251+ if h.layer == Layer::II {
251252 for sb in 0..nb_sb {
252253 for ch in 0..channels {
253254 if alloc[ch][sb] != 0 {
@@ -264,7 +265,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec<
264265 if alloc[ch][sb] == 0 {
265266 continue;
266267 }
267- let n = if h.layer == 1 {
268+ let n = if h.layer == Layer::I {
268269 1
269270 } else {
270271 match scfsi[ch][sb] {
@@ -287,7 +288,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec<
287288 if a == 0 {
288289 continue;
289290 }
290- if h.layer == 1 {
291+ if h.layer == Layer::I {
291292 let nb = a + 1;
292293 w.put(rnd(rng, (1 << nb) - 1), nb);
293294 } else {