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 {
308 pub struct ChannelState {308 pub struct ChannelState {
309 overlap: Vec<f32>,309 overlap: Vec<f32>,
310 prev_shape_kbd: bool,310 prev_shape_kbd: bool,
311- prev_short: bool,
312 }311 }
313 312
314 impl Default for ChannelState {313 impl Default for ChannelState {
@@ -316,7 +315,6 @@ impl Default for ChannelState {
316 ChannelState {315 ChannelState {
317 overlap: vec![0.0; FRAME_LEN],316 overlap: vec![0.0; FRAME_LEN],
318 prev_shape_kbd: false,317 prev_shape_kbd: false,
319- prev_short: false,
320 }318 }
321 }319 }
322 }320 }
@@ -424,7 +422,6 @@ impl FilterBank {
424 }422 }
425 state.overlap.copy_from_slice(&frame[FRAME_LEN..]);423 state.overlap.copy_from_slice(&frame[FRAME_LEN..]);
426 state.prev_shape_kbd = ics.window_shape_kbd;424 state.prev_shape_kbd = ics.window_shape_kbd;
427- state.prev_short = ics.window_sequence.is_short();
428 }425 }
429 }426 }
430 427
@@ -791,6 +788,86 @@ impl BlockDecoder {
791 }788 }
792 }789 }
793 790
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+
794 /// Decodes one `raw_data_block`, returning one PCM plane per channel in871 /// Decodes one `raw_data_block`, returning one PCM plane per channel in
795 /// bitstream element order.872 /// bitstream element order.
796 pub fn raw_data_block(&mut self, r: &mut BitReader<'_>) -> Result<Vec<Vec<f32>>> {873 pub fn raw_data_block(&mut self, r: &mut BitReader<'_>) -> Result<Vec<Vec<f32>>> {
@@ -890,77 +967,7 @@ impl BlockDecoder {
890 pending = None;967 pending = None;
891 }968 }
892 6 => {969 6 => {
893- let mut count = r.read_bits(4)? as u64;970+ self.fill_element(r, &mut out, &mut pending)?;
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;
964 }971 }
965 _ => {972 _ => {
966 // The block ended with no FIL element ever following the973 // The block ended with no FIL element ever following the
crates/ec-aac/src/encode.rsmodified+37 -17
@@ -538,11 +538,11 @@ impl AacEncoder {
538 let mut ms = vec![false; max_sfb];538 let mut ms = vec![false; max_sfb];
539 if *element == Element::Cpe && self.config.mid_side {539 if *element == Element::Cpe && self.config.mid_side {
540 for b in 0..max_sfb {540 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) {
542 ms[b] = true;542 ms[b] = true;
543 }543 }
544 }544 }
545- apply_ms(&mut pair, &ms, swb, max_sfb, short);545+ apply_ms(&mut pair, &ms, swb, max_sfb, seq);
546 }546 }
547 elements.push(ElementPlan {547 elements.push(ElementPlan {
548 element: *element,548 element: *element,
@@ -563,7 +563,7 @@ impl AacEncoder {
563 .map(|plan| {563 .map(|plan| {
564 plan.frames564 plan.frames
565 .iter()565 .iter()
566- .map(|frame| band_profile(frame, swb, max_sfb, short))566+ .map(|frame| band_profile(frame, swb, max_sfb, seq))
567 .collect()567 .collect()
568 })568 })
569 .collect();569 .collect();
@@ -759,14 +759,14 @@ impl AacEncoder {
759 max_sfb,759 max_sfb,
760 b,760 b,
761 floor[b],761 floor[b],
762- || self.band_noise(frame, swb, b, floor[b], windows, short),762+ || self.band_noise(frame, swb, b, floor[b], windows, seq),
763 ) <= target763 ) <= target
764 {764 {
765 let (mut lo, mut hi) = (floor[b], 255);765 let (mut lo, mut hi) = (floor[b], 255);
766 while lo < hi {766 while lo < hi {
767 let mid = lo + (hi - lo + 1) / 2;767 let mid = lo + (hi - lo + 1) / 2;
768 if memo.noise(ch_slot, max_sfb, b, mid, || {768 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)
770 }) <= target {770 }) <= target {
771 lo = mid;771 lo = mid;
772 } else {772 } else {
@@ -848,7 +848,7 @@ impl AacEncoder {
848 if books[b] == 0 {848 if books[b] == 0 {
849 continue;849 continue;
850 }850 }
851- bits += band_bits(&quant, swb, b, books[b], windows, short);851+ bits += band_bits(&quant, swb, b, books[b], windows, seq);
852 let value = prev.map_or(60, |p| (60 + sf[b] - p).clamp(0, 120));852 let value = prev.map_or(60, |p| (60 + sf[b] - p).clamp(0, 120));
853 bits += i32::from(SCALEFACTOR_CODES[value as usize].0);853 bits += i32::from(SCALEFACTOR_CODES[value as usize].0);
854 prev = Some(sf[b]);854 prev = Some(sf[b]);
@@ -871,7 +871,6 @@ impl AacEncoder {
871 books,871 books,
872 quant,872 quant,
873 bits,873 bits,
874- short,
875 }874 }
876 }875 }
877 876
@@ -883,8 +882,9 @@ impl AacEncoder {
883 band: usize,882 band: usize,
884 sf: i32,883 sf: i32,
885 windows: usize,884 windows: usize,
886- short: bool,885+ seq: WindowSequence,
887 ) -> f32 {886 ) -> f32 {
887+ let short = seq == WindowSequence::EightShort;
888 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));888 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
889 let gain = pow_quarter(sf - SF_OFFSET);889 let gain = pow_quarter(sf - SF_OFFSET);
890 let gain_inv = pow_quarter(SF_OFFSET - sf);890 let gain_inv = pow_quarter(SF_OFFSET - sf);
@@ -922,12 +922,18 @@ struct Coded {
922 books: Vec<u8>,922 books: Vec<u8>,
923 quant: Vec<i32>,923 quant: Vec<i32>,
924 bits: i32,924 bits: i32,
925- short: bool,
926 }925 }
927 926
928 /// True when mid/side splits this band's energy more lopsidedly than left/right927 /// True when mid/side splits this band's energy more lopsidedly than left/right
929 /// does, which is when it costs fewer bits.928 /// 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;
931 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));937 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
932 let windows = if short { 8 } else { 1 };938 let windows = if short { 8 } else { 1 };
933 let (mut el, mut er, mut em, mut es) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);939 let (mut el, mut er, mut em, mut es) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
@@ -958,7 +964,13 @@ struct BandProfile {
958 floor: Vec<i32>,964 floor: Vec<i32>,
959 }965 }
960 966
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;
962 let windows = if short { 8 } else { 1 };974 let windows = if short { 8 } else { 1 };
963 let mut peak = vec![0.0f32; max_sfb];975 let mut peak = vec![0.0f32; max_sfb];
964 let mut energy = vec![0.0f32; max_sfb];976 let mut energy = vec![0.0f32; max_sfb];
@@ -1024,7 +1036,14 @@ impl NoiseMemo {
1024 }1036 }
1025 }1037 }
1026 1038
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;
1028 let windows = if short { 8 } else { 1 };1047 let windows = if short { 8 } else { 1 };
1029 for b in 0..max_sfb {1048 for b in 0..max_sfb {
1030 if !ms[b] {1049 if !ms[b] {
@@ -1125,8 +1144,9 @@ fn band_bits(
1125 band: usize,1144 band: usize,
1126 book: u8,1145 book: u8,
1127 windows: usize,1146 windows: usize,
1128- short: bool,1147+ seq: WindowSequence,
1129 ) -> i32 {1148 ) -> i32 {
1149+ let short = seq == WindowSequence::EightShort;
1130 let cb = &CODEBOOKS[usize::from(book) - 1];1150 let cb = &CODEBOOKS[usize::from(book) - 1];
1131 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));1151 let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1]));
1132 let dim = usize::from(cb.dim);1152 let dim = usize::from(cb.dim);
@@ -1218,7 +1238,7 @@ fn write_ics_info(w: &mut BitWriter, c: &Coded) {
1218 };1238 };
1219 w.write_bits(seq, 2);1239 w.write_bits(seq, 2);
1220 w.write_bit(false); // sine window shape1240 w.write_bit(false); // sine window shape
1221- if c.short {1241+ if c.seq == WindowSequence::EightShort {
1222 w.write_bits(c.max_sfb as u32, 4);1242 w.write_bits(c.max_sfb as u32, 4);
1223 w.write_bits(0x7F, 7); // one group of eight windows1243 w.write_bits(0x7F, 7); // one group of eight windows
1224 } else {1244 } else {
@@ -1235,7 +1255,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) {
1235 write_ics_info(w, c);1255 write_ics_info(w, c);
1236 }1256 }
1237 // section_data1257 // section_data
1238- let esc_bits = if c.short { 3 } else { 5 };1258+ let esc_bits = if c.seq == WindowSequence::EightShort { 3 } else { 5 };
1239 let esc = (1u32 << esc_bits) - 1;1259 let esc = (1u32 << esc_bits) - 1;
1240 let mut b = 0usize;1260 let mut b = 0usize;
1241 while b < c.max_sfb {1261 while b < c.max_sfb {
@@ -1267,7 +1287,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) {
1267 w.write_bit(false); // tns_data_present1287 w.write_bit(false); // tns_data_present
1268 w.write_bit(false); // gain_control_data_present1288 w.write_bit(false); // gain_control_data_present
1269 // spectral_data1289 // spectral_data
1270- let windows = if c.short { 8 } else { 1 };1290+ let windows = if c.seq == WindowSequence::EightShort { 8 } else { 1 };
1271 for b in 0..c.max_sfb {1291 for b in 0..c.max_sfb {
1272 let book = c.books[b];1292 let book = c.books[b];
1273 if book == 0 {1293 if book == 0 {
@@ -1277,7 +1297,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) {
1277 let dim = usize::from(cb.dim);1297 let dim = usize::from(cb.dim);
1278 let (lo, hi) = (usize::from(c.swb[b]), usize::from(c.swb[b + 1]));1298 let (lo, hi) = (usize::from(c.swb[b]), usize::from(c.swb[b + 1]));
1279 for win in 0..windows {1299 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 };
1281 let mut k = lo;1301 let mut k = lo;
1282 while k < hi {1302 while k < hi {
1283 let end = (k + dim).min(hi);1303 let end = (k + dim).min(hi);
crates/ec-aac/src/huffman.rsmodified+33 -0
@@ -83,3 +83,36 @@ impl Default for Books {
83 Books::new()83 Books::new()
84 }84 }
85 }85 }
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 @@
8 //! its handling of stale fields, so that the decoded parameters match the8 //! its handling of stale fields, so that the decoded parameters match the
9 //! reference decoder frame for frame.9 //! reference decoder frame for frame.
10 10
11+use crate::huffman::Tree;
11 use crate::ps_huff;12 use crate::ps_huff;
12 use ec_core::{BitReader, Error, Result};13 use ec_core::{BitReader, Error, Result};
13 use std::sync::OnceLock;14 use std::sync::OnceLock;
@@ -93,10 +94,21 @@ impl Default for PsCommon {
93 }94 }
94 }95 }
95 96
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).
97 struct Vlc {99 struct Vlc {
98- codes: Vec<(u32, u32, i32)>,100+ tree: Tree,
99- max_len: u32,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+ }
100 }112 }
101 113
102 /// The ten PS Huffman tables, with canonical codes assigned from the lengths.114 /// The ten PS Huffman tables, with canonical codes assigned from the lengths.
@@ -106,7 +118,7 @@ fn vlcs() -> &'static [Vlc] {
106 ps_huff::TABLES118 ps_huff::TABLES
107 .iter()119 .iter()
108 .zip(ps_huff::OFFSETS)120 .zip(ps_huff::OFFSETS)
109- .map(|(table, offset)| build_codes(table, offset))121+ .map(|(table, offset)| Vlc::new(&build_codes(table, offset)))
110 .collect()122 .collect()
111 })123 })
112 }124 }
@@ -117,36 +129,23 @@ fn vlcs() -> &'static [Vlc] {
117 /// lengths alone do not fix the codes, which is why sorting them canonically129 /// lengths alone do not fix the codes, which is why sorting them canonically
118 /// misreads every fine-IID and ICC frame. Every table in the standard is a130 /// misreads every fine-IID and ICC frame. Every table in the standard is a
119 /// complete prefix code, which the unit tests check.131 /// 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)> {
121 let mut codes = Vec::with_capacity(table.len());133 let mut codes = Vec::with_capacity(table.len());
122 // Position in the code space, in units of 2^-32 (a 64-bit sum: no overflow).134 // Position in the code space, in units of 2^-32 (a 64-bit sum: no overflow).
123 let mut next: u64 = 0;135 let mut next: u64 = 0;
124- let mut max_len = 0;
125 for &(value, len) in table {136 for &(value, len) in table {
126 let len = u32::from(len).clamp(1, 32);137 let len = u32::from(len).clamp(1, 32);
127 let code = (next >> (32 - len)) as u32;138 let code = (next >> (32 - len)) as u32;
128 codes.push((len, code, i32::from(value) + offset));139 codes.push((len, code, i32::from(value) + offset));
129 next += 1u64 << (32 - len);140 next += 1u64 << (32 - len);
130- max_len = max_len.max(len);
131 }141 }
132- Vlc { codes, max_len }142+ codes
133 }143 }
134 144
135 /// Reads one codeword of table `which` and returns its parameter value.145 /// Reads one codeword of table `which` and returns its parameter value.
136 fn read_vlc(r: &mut BitReader<'_>, which: usize) -> Result<i32> {146 fn read_vlc(r: &mut BitReader<'_>, which: usize) -> Result<i32> {
137- let table = &vlcs()[which];147+ let vlc = &vlcs()[which];
138- let mut code: u32 = 0;148+ Ok(vlc.values[vlc.tree.decode(r)?])
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"))
150 }149 }
151 150
152 /// Reads one IID/ICC/IPD/OPD parameter row (FFmpeg's `READ_PAR_DATA`).151 /// Reads one IID/ICC/IPD/OPD parameter row (FFmpeg's `READ_PAR_DATA`).
@@ -458,17 +457,28 @@ mod tests {
458 // length 4) and (value +2, length 4), so they get codes 0000 and 0001,457 // length 4) and (value +2, length 4), so they get codes 0000 and 0001,
459 // not the canonical order a length sort would give.458 // not the canonical order a length sort would give.
460 let v = build_codes(ps_huff::TABLES[HUFF_IID_DF1], ps_huff::OFFSETS[HUFF_IID_DF1]);459 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));460+ assert_eq!(v[0], (4, 0b0000, -2));
462- assert_eq!(v.codes[1], (4, 0b0001, 2));461+ assert_eq!(v[1], (4, 0b0001, 2));
463- assert_eq!(v.codes[2], (3, 0b001, -1));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+ }
464 }474 }
465 475
466 #[test]476 #[test]
467 fn codes_are_prefix_free_and_values_cover_the_range() {477 fn codes_are_prefix_free_and_values_cover_the_range() {
468 for (i, table) in ps_huff::TABLES.iter().enumerate() {478 for (i, table) in ps_huff::TABLES.iter().enumerate() {
469 let v = build_codes(table, ps_huff::OFFSETS[i]);479 let v = build_codes(table, ps_huff::OFFSETS[i]);
470- for (a, &(la, ca, _)) in v.codes.iter().enumerate() {480+ for (a, &(la, ca, _)) in v.iter().enumerate() {
471- for &(lb, cb, _) in v.codes.iter().skip(a + 1) {481+ for &(lb, cb, _) in v.iter().skip(a + 1) {
472 let (short, long, cs, cl) = if la <= lb { (la, lb, ca, cb) } else { (lb, la, cb, ca) };482 let (short, long, cs, cl) = if la <= lb { (la, lb, ca, cb) } else { (lb, la, cb, ca) };
473 assert!(cl >> (long - short) != cs, "table {i} codes collide");483 assert!(cl >> (long - short) != cs, "table {i} codes collide");
474 }484 }
@@ -498,7 +508,7 @@ mod tests {
498 push(&mut bits, 0, 1); // dt = 0 for the envelope508 push(&mut bits, 0, 1); // dt = 0 for the envelope
499 let code_for_zero = {509 let code_for_zero = {
500 let v = build_codes(ps_huff::TABLES[HUFF_IID_DF0], ps_huff::OFFSETS[HUFF_IID_DF0]);510 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")
502 };512 };
503 for _ in 0..10 {513 for _ in 0..10 {
504 push(&mut bits, code_for_zero.1, code_for_zero.0);514 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 {
377 continue;377 continue;
378 }378 }
379 let state = &mut elem.channels[ch];379 let state = &mut elem.channels[ch];
380- let mut low_cur = vec![vec![Complex::ZERO; num_slots]; ANALYSIS_BANDS];380+ let (low_cur, raw) = analyze_plane(state, plane, num_slots);
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- }
405 381
406 let sbr_ch = &data.channels[ch];382 let sbr_ch = &data.channels[ch];
407 let hf = sbr_hf::generate(383 let hf = sbr_hf::generate(
@@ -481,17 +457,7 @@ impl SbrChain {
481 457
482 let kx = (tables.kx as usize).min(ANALYSIS_BANDS);458 let kx = (tables.kx as usize).min(ANALYSIS_BANDS);
483 let k2 = (tables.k2 as usize).min(band_limit);459 let k2 = (tables.k2 as usize).min(band_limit);
484- let mut vs: Vec<[Complex<f64>; SYNTHESIS_BANDS]> = Vec::with_capacity(num_slots);460+ let vs = merge_bands(&raw, &hf, kx, k2, 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- }
495 let out = match (ps_mode && num_slots == PS_SLOTS, data.ps.as_ref()) {461 let out = match (ps_mode && num_slots == PS_SLOTS, data.ps.as_ref()) {
496 (true, Some(ps)) => {462 (true, Some(ps)) => {
497 let (left, right) =463 let (left, right) =
@@ -530,6 +496,62 @@ impl SbrChain {
530 }496 }
531 }497 }
532 498
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+
533 /// Inserts the second output plane a PS element needs, right after its first555 /// Inserts the second output plane a PS element needs, right after its first
534 /// (a copy, which the PS path then overwrites). Returns the element's new556 /// (a copy, which the PS path then overwrites). Returns the element's new
535 /// plane count: 2 when a plane was inserted.557 /// plane count: 2 when a plane was inserted.
crates/ec-aac/src/sbr_payload.rsmodified+68 -32
@@ -15,7 +15,9 @@
15 //! `sbrtables.py` never needed them for the codebook derivation.15 //! `sbrtables.py` never needed them for the codebook derivation.
16 #![allow(dead_code)]16 #![allow(dead_code)]
17 17
18+use crate::huffman::Tree;
18 use crate::ps_data::PsCommon;19 use crate::ps_data::PsCommon;
20+use std::sync::LazyLock;
19 use crate::sbr_bands::{BandTables, freq_tables};21 use crate::sbr_bands::{BandTables, freq_tables};
20 use crate::sbr_tables::*;22 use crate::sbr_tables::*;
21 use ec_core::{BitReader, Error, Result};23 use ec_core::{BitReader, Error, Result};
@@ -165,25 +167,74 @@ pub struct SbrParser {
165 /// `bs_extension_id` of Parametric Stereo.167 /// `bs_extension_id` of Parametric Stereo.
166 const EXTENSION_ID_PS: u32 = 2;168 const EXTENSION_ID_PS: u32 = 2;
167 169
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;
169 match (balance, amp_res != 0, dt) {219 match (balance, amp_res != 0, dt) {
170- (false, false, false) => &ENV15_F,220+ (false, false, false) => &b.env15_f,
171- (false, false, true) => &ENV15_T,221+ (false, false, true) => &b.env15_t,
172- (false, true, false) => &ENV30_F,222+ (false, true, false) => &b.env30_f,
173- (false, true, true) => &ENV30_T,223+ (false, true, true) => &b.env30_t,
174- (true, false, false) => &ENVB15_F,224+ (true, false, false) => &b.envb15_f,
175- (true, false, true) => &ENVB15_T,225+ (true, false, true) => &b.envb15_t,
176- (true, true, false) => &ENVB30_F,226+ (true, true, false) => &b.envb30_f,
177- (true, true, true) => &ENVB30_T,227+ (true, true, true) => &b.envb30_t,
178 }228 }
179 }229 }
180 230
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;
182 match (balance, dt) {233 match (balance, dt) {
183- (false, false) => &NOISE_F,234+ (false, false) => &b.noise_f,
184- (false, true) => &NOISE_T,235+ (false, true) => &b.noise_t,
185- (true, false) => &NOISEB_F,236+ (true, false) => &b.noiseb_f,
186- (true, true) => &NOISEB_T,237+ (true, true) => &b.noiseb_t,
187 }238 }
188 }239 }
189 240
@@ -238,24 +289,9 @@ fn map_prev_env(prev: &[i32], tables: &BandTables, cur_high: bool) -> Vec<i32> {
238 }289 }
239 }290 }
240 291
241-/// Reads one Huffman codeword by walking bit-by-bit until it matches a table292+/// Reads one Huffman codeword and returns its delta.
242-/// entry. Every book here is a complete prefix code (Kraft sum 1, checked in293+fn read_huffman(r: &mut BitReader, book: &Book) -> Result<i32> {
243-/// `sbr_tables`), so a well-formed stream always terminates; a codeword294+ Ok(book.deltas[book.tree.decode(r)?])
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- }
259 }295 }
260 296
261 impl SbrParser {297 impl SbrParser {
crates/ec-mp3/src/decode.rsmodified+38 -15
@@ -2,7 +2,7 @@
2 //! filterbank that turns 576 coefficients back into PCM.2 //! filterbank that turns 576 coefficients back into PCM.
3 3
4 use crate::filterbank::{Imdct, Synthesis, alias_reduce};4 use crate::filterbank::{Imdct, Synthesis, alias_reduce};
5-use crate::header::{ChannelMode, FrameHeader, Version, crc16};5+use crate::header::{ChannelMode, FrameHeader, Layer, Version, crc16};
6 use crate::huffman;6 use crate::huffman;
7 use crate::layer12::Layer12;7 use crate::layer12::Layer12;
8 use crate::tables::{8 use crate::tables::{
@@ -22,6 +22,29 @@ pub struct DecodedFrame {
22 pub samples: Vec<f32>,22 pub samples: Vec<f32>,
23 }23 }
24 24
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+
25 #[derive(Clone, Copy, Debug, Default)]48 #[derive(Clone, Copy, Debug, Default)]
26 struct GranuleInfo {49 struct GranuleInfo {
27 part2_3_length: u32,50 part2_3_length: u32,
@@ -29,7 +52,7 @@ struct GranuleInfo {
29 global_gain: u32,52 global_gain: u32,
30 scalefac_compress: u32,53 scalefac_compress: u32,
31 window_switching: bool,54 window_switching: bool,
32- block_type: u8,55+ block_type: BlockType,
33 mixed_block: bool,56 mixed_block: bool,
34 table_select: [u8; 3],57 table_select: [u8; 3],
35 subblock_gain: [u32; 3],58 subblock_gain: [u32; 3],
@@ -86,7 +109,7 @@ fn parse_side_info(header: &FrameHeader, bytes: &[u8]) -> Result<SideInfo> {
86 )));109 )));
87 }110 }
88 if g.window_switching {111 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)?);
90 g.mixed_block = r.read_bit()?;113 g.mixed_block = r.read_bit()?;
91 for slot in &mut g.table_select[..2] {114 for slot in &mut g.table_select[..2] {
92 *slot = r.read_bits(5)? as u8;115 *slot = r.read_bits(5)? as u8;
@@ -94,13 +117,13 @@ fn parse_side_info(header: &FrameHeader, bytes: &[u8]) -> Result<SideInfo> {
94 for slot in &mut g.subblock_gain {117 for slot in &mut g.subblock_gain {
95 *slot = r.read_bits(3)?;118 *slot = r.read_bits(3)?;
96 }119 }
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 {
98 8121 8
99 } else {122 } else {
100 7123 7
101 };124 };
102 g.region1_count = 20 - g.region0_count;125 g.region1_count = 20 - g.region0_count;
103- if g.block_type == 0 {126+ if g.block_type == BlockType::Normal {
104 return Err(Error::corrupt(127 return Err(Error::corrupt(
105 "mp3: window switching with normal block type",128 "mp3: window switching with normal block type",
106 ));129 ));
@@ -192,7 +215,7 @@ impl Mp3Decode {
192 if frame.len() < frame_len {215 if frame.len() < frame_len {
193 return Err(Error::NeedMore);216 return Err(Error::NeedMore);
194 }217 }
195- if header.layer != 3 {218+ if header.layer != Layer::III {
196 let samples = self.layer12.decode(&header, &frame[..frame_len])?;219 let samples = self.layer12.decode(&header, &frame[..frame_len])?;
197 return Ok(DecodedFrame {220 return Ok(DecodedFrame {
198 sample_rate: header.sample_rate,221 sample_rate: header.sample_rate,
@@ -309,7 +332,7 @@ impl Mp3Decode {
309 ) -> Result<()> {332 ) -> Result<()> {
310 let granule = side.granules[gr][ch];333 let granule = side.granules[gr][ch];
311 let (slen1, slen2) = SLEN[(granule.scalefac_compress & 15) as usize];334 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 {
313 if granule.mixed_block {336 if granule.mixed_block {
314 for sfb in 0..8 {337 for sfb in 0..8 {
315 self.scalefac_l[ch][sfb] = reader.read_bits(slen1)? as u8;338 self.scalefac_l[ch][sfb] = reader.read_bits(slen1)? as u8;
@@ -386,7 +409,7 @@ impl Mp3Decode {
386 slen = [sfc / 3, sfc % 3, 0, 0];409 slen = [sfc / 3, sfc % 3, 0, 0];
387 block_number = 2;410 block_number = 2;
388 }411 }
389- let short = granule.window_switching && granule.block_type == 2;412+ let short = granule.block_type == BlockType::Short;
390 let kind = if !short {413 let kind = if !short {
391 0414 0
392 } else if granule.mixed_block {415 } else if granule.mixed_block {
@@ -427,7 +450,7 @@ impl Mp3Decode {
427 let is = &mut self.is[ch];450 let is = &mut self.is[ch];
428 is.fill(0);451 is.fill(0);
429 let starts = long_starts(header.sample_rate);452 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;
431 let (region1, region2) = if granule.window_switching {454 let (region1, region2) = if granule.window_switching {
432 if short {455 if short {
433 // Three short bands, all three windows: 36 lines at every rate456 // Three short bands, all three windows: 36 lines at every rate
@@ -493,7 +516,7 @@ impl Mp3Decode {
493 let power = power43();516 let power = power43();
494 let xr = &mut self.xr[ch];517 let xr = &mut self.xr[ch];
495 let is = &self.is[ch];518 let is = &self.is[ch];
496- let short = granule.window_switching && granule.block_type == 2;519+ let short = granule.block_type == BlockType::Short;
497 let multiplier = if granule.scalefac_scale { 1.0 } else { 0.5 };520 let multiplier = if granule.scalefac_scale { 1.0 } else { 0.5 };
498 let base = (granule.global_gain as f32 - 210.0) * 0.25;521 let base = (granule.global_gain as f32 - 210.0) * 0.25;
499 let value = |v: i32| -> f32 {522 let value = |v: i32| -> f32 {
@@ -566,7 +589,7 @@ impl Mp3Decode {
566 let ms = joint && header.mode_ext & 2 != 0;589 let ms = joint && header.mode_ext & 2 != 0;
567 let intensity = joint && header.mode_ext & 1 != 0;590 let intensity = joint && header.mode_ext & 1 != 0;
568 let granule = side.granules[gr][0];591 let granule = side.granules[gr][0];
569- let short = granule.window_switching && granule.block_type == 2;592+ let short = granule.block_type == BlockType::Short;
570 // Intensity coding starts at the first band above the right channel's593 // Intensity coding starts at the first band above the right channel's
571 // last non-zero line.594 // last non-zero line.
572 let bound = if intensity {595 let bound = if intensity {
@@ -624,7 +647,7 @@ impl Mp3Decode {
624 channels: usize,647 channels: usize,
625 out: &mut [f32],648 out: &mut [f32],
626 ) {649 ) {
627- let short = granule.window_switching && granule.block_type == 2;650+ let short = granule.block_type == BlockType::Short;
628 let alias_bands = if !short {651 let alias_bands = if !short {
629 32652 32
630 } else if granule.mixed_block {653 } else if granule.mixed_block {
@@ -643,8 +666,8 @@ impl Mp3Decode {
643 if short && !(granule.mixed_block && sb < 2) {666 if short && !(granule.mixed_block && sb < 2) {
644 self.imdct.short(coefficients, &mut block);667 self.imdct.short(coefficients, &mut block);
645 } else {668 } else {
646- let block_type = if short { 0 } else { granule.block_type };669+ let block_type = if short { BlockType::Normal } else { granule.block_type };
647- self.imdct.long(coefficients, block_type, &mut block);670+ self.imdct.long(coefficients, block_type as u8, &mut block);
648 }671 }
649 let overlap = &mut self.overlap[ch][sb];672 let overlap = &mut self.overlap[ch][sb];
650 for t in 0..18 {673 for t in 0..18 {
@@ -736,7 +759,7 @@ impl Mp3Reader {
736 return Err(Error::NeedMore);759 return Err(Error::NeedMore);
737 }760 }
738 let frame = &data[..frame_len];761 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) {
740 self.started = true;763 self.started = true;
741 self.consumed += frame_len;764 self.consumed += frame_len;
742 continue;765 continue;
crates/ec-mp3/src/encode.rsmodified+2 -2
@@ -18,7 +18,7 @@
18 //! makes available.18 //! makes available.
19 19
20 use crate::filterbank::{Analysis, alias_expand};20 use crate::filterbank::{Analysis, alias_expand};
21-use crate::header::{ChannelMode, FrameHeader, Version};21+use crate::header::{ChannelMode, FrameHeader, Layer, Version};
22 use crate::huffman::{self, BitBuf};22 use crate::huffman::{self, BitBuf};
23 use crate::tables::{23 use crate::tables::{
24 MAX_QUANT, SLEN, forward_mdct_long, forward_mdct_short, long_starts, power43, short_starts,24 MAX_QUANT, SLEN, forward_mdct_long, forward_mdct_short, long_starts, power43, short_starts,
@@ -251,7 +251,7 @@ impl Mp3Encode {
251 fn header(&self, bitrate_kbps: u32, padding: bool) -> FrameHeader {251 fn header(&self, bitrate_kbps: u32, padding: bool) -> FrameHeader {
252 FrameHeader {252 FrameHeader {
253 version: self.version,253 version: self.version,
254- layer: 3,254+ layer: Layer::III,
255 crc: false,255 crc: false,
256 bitrate_kbps,256 bitrate_kbps,
257 sample_rate: self.sample_rate,257 sample_rate: self.sample_rate,
crates/ec-mp3/src/header.rsmodified+33 -22
@@ -15,6 +15,17 @@ pub enum Version {
15 Mpeg25,15 Mpeg25,
16 }16 }
17 17
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+
18 /// The channel arrangement a frame declares.29 /// The channel arrangement a frame declares.
19 #[derive(Clone, Copy, Debug, PartialEq, Eq)]30 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
20 pub enum ChannelMode {31 pub enum ChannelMode {
@@ -55,13 +66,13 @@ const BITRATES_L2_V1: [u32; 15] = [
55 /// The bitrate table for a layer of a version: Layer III and Layer II of the66 /// The bitrate table for a layer of a version: Layer III and Layer II of the
56 /// low sampling frequencies share one, the other four combinations each have67 /// low sampling frequencies share one, the other four combinations each have
57 /// their own.68 /// their own.
58-fn bitrate_table(version: Version, layer: u8) -> &'static [u32; 15] {69+fn bitrate_table(version: Version, layer: Layer) -> &'static [u32; 15] {
59 match (version == Version::Mpeg1, layer) {70 match (version == Version::Mpeg1, layer) {
60- (true, 1) => &BITRATES_L1_V1,71+ (true, Layer::I) => &BITRATES_L1_V1,
61- (true, 2) => &BITRATES_L2_V1,72+ (true, Layer::II) => &BITRATES_L2_V1,
62- (true, _) => &BITRATES_V1,73+ (true, Layer::III) => &BITRATES_V1,
63- (false, 1) => &BITRATES_L1_V2,74+ (false, Layer::I) => &BITRATES_L1_V2,
64- (false, _) => &BITRATES_V2,75+ (false, Layer::II | Layer::III) => &BITRATES_V2,
65 }76 }
66 }77 }
67 const RATES_V1: [u32; 3] = [44100, 48000, 32000];78 const RATES_V1: [u32; 3] = [44100, 48000, 32000];
@@ -71,8 +82,8 @@ const RATES_V1: [u32; 3] = [44100, 48000, 32000];
71 pub struct FrameHeader {82 pub struct FrameHeader {
72 /// MPEG generation.83 /// MPEG generation.
73 pub version: Version,84 pub version: Version,
74- /// Layer number, 1..=3.85+ /// The MPEG audio layer.
75- pub layer: u8,86+ pub layer: Layer,
76 /// True when a 16-bit CRC follows the header.87 /// True when a 16-bit CRC follows the header.
77 pub crc: bool,88 pub crc: bool,
78 /// Declared bitrate in kbit/s; 0 means free format.89 /// Declared bitrate in kbit/s; 0 means free format.
@@ -116,9 +127,9 @@ impl FrameHeader {
116 _ => return Err(Error::corrupt("mp3: reserved MPEG version id")),127 _ => return Err(Error::corrupt("mp3: reserved MPEG version id")),
117 };128 };
118 let layer = match (b[1] >> 1) & 3 {129 let layer = match (b[1] >> 1) & 3 {
119- 1 => 3,130+ 1 => Layer::III,
120- 2 => 2,131+ 2 => Layer::II,
121- 3 => 1,132+ 3 => Layer::I,
122 _ => return Err(Error::corrupt("mp3: reserved layer id")),133 _ => return Err(Error::corrupt("mp3: reserved layer id")),
123 };134 };
124 let crc = (b[1] & 1) == 0;135 let crc = (b[1] & 1) == 0;
@@ -166,9 +177,9 @@ impl FrameHeader {
166 Version::Mpeg1 => 3,177 Version::Mpeg1 => 3,
167 };178 };
168 let layer_id = match self.layer {179 let layer_id = match self.layer {
169- 3 => 1,180+ Layer::III => 1,
170- 2 => 2,181+ Layer::II => 2,
171- _ => 3,182+ Layer::I => 3,
172 };183 };
173 let bitrate_index = bitrate_table(self.version, self.layer)184 let bitrate_index = bitrate_table(self.version, self.layer)
174 .iter()185 .iter()
@@ -215,9 +226,9 @@ impl FrameHeader {
215 /// PCM samples per channel produced by this frame.226 /// PCM samples per channel produced by this frame.
216 pub fn samples_per_frame(&self) -> usize {227 pub fn samples_per_frame(&self) -> usize {
217 match self.layer {228 match self.layer {
218- 1 => 384,229+ Layer::I => 384,
219- 2 => 1152,230+ Layer::II => 1152,
220- _ => self.granules() * 576,231+ Layer::III => self.granules() * 576,
221 }232 }
222 }233 }
223 234
@@ -241,10 +252,10 @@ impl FrameHeader {
241 let rate = self.sample_rate as usize;252 let rate = self.sample_rate as usize;
242 let pad = usize::from(self.padding);253 let pad = usize::from(self.padding);
243 Some(match self.layer {254 Some(match self.layer {
244- 1 => (12 * bits / rate + pad) * 4,255+ Layer::I => (12 * bits / rate + pad) * 4,
245- 2 => 144 * bits / rate + pad,256+ Layer::II => 144 * bits / rate + pad,
246- _ if self.version == Version::Mpeg1 => 144 * bits / rate + pad,257+ Layer::III if self.version == Version::Mpeg1 => 144 * bits / rate + pad,
247- _ => 72 * bits / rate + pad,258+ Layer::III => 72 * bits / rate + pad,
248 })259 })
249 }260 }
250 }261 }
@@ -298,7 +309,7 @@ mod tests {
298 let bytes = [0xFF, 0xFB, 0x90, 0x00];309 let bytes = [0xFF, 0xFB, 0x90, 0x00];
299 let h = FrameHeader::parse(&bytes).unwrap();310 let h = FrameHeader::parse(&bytes).unwrap();
300 assert_eq!(h.version, Version::Mpeg1);311 assert_eq!(h.version, Version::Mpeg1);
301- assert_eq!(h.layer, 3);312+ assert_eq!(h.layer, Layer::III);
302 assert_eq!(h.bitrate_kbps, 128);313 assert_eq!(h.bitrate_kbps, 128);
303 assert_eq!(h.sample_rate, 44100);314 assert_eq!(h.sample_rate, 44100);
304 assert_eq!(h.mode, ChannelMode::Stereo);315 assert_eq!(h.mode, ChannelMode::Stereo);
crates/ec-mp3/src/layer12.rsmodified+2 -2
@@ -7,7 +7,7 @@
7 //! copied: `scripts/mp2-tables/measure.py` sets one allocation code at a time and7 //! copied: `scripts/mp2-tables/measure.py` sets one allocation code at a time and
8 //! reads the quantiser size back from the decoded level.8 //! reads the quantiser size back from the decoded level.
9 9
10-use crate::header::{ChannelMode, FrameHeader, Version, crc16_bits};10+use crate::header::{ChannelMode, FrameHeader, Layer, Version, crc16_bits};
11 use crate::window::WINDOW;11 use crate::window::WINDOW;
12 use ec_core::bitio::BitReader;12 use ec_core::bitio::BitReader;
13 use ec_core::error::{Error, Result};13 use ec_core::error::{Error, Result};
@@ -188,7 +188,7 @@ impl Layer12 {
188 let body = &frame[4 + usize::from(header.crc) * 2..];188 let body = &frame[4 + usize::from(header.crc) * 2..];
189 let mut r = BitReader::new(body);189 let mut r = BitReader::new(body);
190 let mut subband = vec![[[0.0f32; 32]; 2]; 36];190 let mut subband = vec![[[0.0f32; 32]; 2]; 36];
191- let slots = if header.layer == 1 {191+ let slots = if header.layer == Layer::I {
192 self.read_layer1(header, frame, &mut r, &mut subband)?;192 self.read_layer1(header, frame, &mut r, &mut subband)?;
193 12193 12
194 } else {194 } else {
crates/ec-mp3/tests/mp2_matrix.rsmodified+11 -10
@@ -10,6 +10,7 @@
10 10
11 use std::path::PathBuf;11 use std::path::PathBuf;
12 12
13+use ec_mp3::header::Layer;
13 use ec_mp3::{FrameHeader, Mp3Reader};14 use ec_mp3::{FrameHeader, Mp3Reader};
14 15
15 fn work_dir() -> PathBuf {16 fn work_dir() -> PathBuf {
@@ -18,8 +19,8 @@ fn work_dir() -> PathBuf {
18 d19 d
19 }20 }
20 21
21-fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec<f32> {22+fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: Layer) -> Vec<f32> {
22- let decoder = if layer == 1 { "mp1float" } else { "mp2float" };23+ let decoder = if layer == Layer::I { "mp1float" } else { "mp2float" };
23 let out = ec_testkit::ffmpeg()24 let out = ec_testkit::ffmpeg()
24 .args(["-v", "error", "-c:a", decoder, "-i"])25 .args(["-v", "error", "-c:a", decoder, "-i"])
25 .arg(path)26 .arg(path)
@@ -40,8 +41,8 @@ fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec<f32>
40 }41 }
41 42
42 /// ffmpeg's fixed-point decoder (the default `mp2`/`mp1`): s16 out.43 /// 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+fn ffmpeg_decode_s16(path: &std::path::Path, channels: usize, layer: Layer) -> Vec<i16> {
44- let decoder = if layer == 1 { "mp1" } else { "mp2" };45+ let decoder = if layer == Layer::I { "mp1" } else { "mp2" };
45 let out = ec_testkit::ffmpeg()46 let out = ec_testkit::ffmpeg()
46 .args(["-v", "error", "-c:a", decoder, "-i"])47 .args(["-v", "error", "-c:a", decoder, "-i"])
47 .arg(path)48 .arg(path)
@@ -192,7 +193,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec<
192 let rnd = |rng: &mut Rng, n: u32| (rng.next() >> 20) as u32 % n.max(1);193 let rnd = |rng: &mut Rng, n: u32| (rng.next() >> 20) as u32 % n.max(1);
193 let (nb_sb, bound);194 let (nb_sb, bound);
194 let rows: Vec<Vec<u32>>;195 let rows: Vec<Vec<u32>>;
195- if h.layer == 1 {196+ if h.layer == Layer::I {
196 nb_sb = 32;197 nb_sb = 32;
197 rows = Vec::new();198 rows = Vec::new();
198 } else {199 } else {
@@ -207,14 +208,14 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec<
207 // allocation codes208 // allocation codes
208 let mut alloc = vec![vec![0u32; nb_sb]; 2];209 let mut alloc = vec![vec![0u32; nb_sb]; 2];
209 let width = |sb: usize| -> u32 {210 let width = |sb: usize| -> u32 {
210- if h.layer == 1 {211+ if h.layer == Layer::I {
211 4212 4
212 } else {213 } else {
213 rows[sb].len().trailing_zeros()214 rows[sb].len().trailing_zeros()
214 }215 }
215 };216 };
216 for sb in 0..nb_sb {217 for sb in 0..nb_sb {
217- let maxcode = if h.layer == 1 {218+ let maxcode = if h.layer == Layer::I {
218 15219 15
219 } else {220 } else {
220 rows[sb].len() as u32221 rows[sb].len() as u32
@@ -247,7 +248,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec<
247 }248 }
248 }249 }
249 let mut scfsi = vec![vec![0u32; nb_sb]; 2];250 let mut scfsi = vec![vec![0u32; nb_sb]; 2];
250- if h.layer == 2 {251+ if h.layer == Layer::II {
251 for sb in 0..nb_sb {252 for sb in 0..nb_sb {
252 for ch in 0..channels {253 for ch in 0..channels {
253 if alloc[ch][sb] != 0 {254 if alloc[ch][sb] != 0 {
@@ -264,7 +265,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec<
264 if alloc[ch][sb] == 0 {265 if alloc[ch][sb] == 0 {
265 continue;266 continue;
266 }267 }
267- let n = if h.layer == 1 {268+ let n = if h.layer == Layer::I {
268 1269 1
269 } else {270 } else {
270 match scfsi[ch][sb] {271 match scfsi[ch][sb] {
@@ -287,7 +288,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec<
287 if a == 0 {288 if a == 0 {
288 continue;289 continue;
289 }290 }
290- if h.layer == 1 {291+ if h.layer == Layer::I {
291 let nb = a + 1;292 let nb = a + 1;
292 w.put(rnd(rng, (1 << nb) - 1), nb);293 w.put(rnd(rng, (1 << nb) - 1), nb);
293 } else {294 } else {