Merge branch 'simplify/s10' into simplify/w2
Browse files at this commit11 changed files +400 -237
- crates/ec-aac/src/decode.rs +81 -74
- crates/ec-aac/src/encode.rs +37 -17
- crates/ec-aac/src/huffman.rs +33 -0
- crates/ec-aac/src/ps_data.rs +37 -27
- crates/ec-aac/src/sbr_chain.rs +58 -36
- crates/ec-aac/src/sbr_payload.rs +68 -32
- crates/ec-mp3/src/decode.rs +38 -15
- crates/ec-mp3/src/encode.rs +2 -2
- crates/ec-mp3/src/header.rs +33 -22
- crates/ec-mp3/src/layer12.rs +2 -2
- crates/ec-mp3/tests/mp2_matrix.rs +11 -10
crates/ec-aac/src/decode.rsmodified+81 -74
| @@ -308,7 +308,6 @@ struct Ics { | ||
| 308 | 308 | pub struct ChannelState { |
| 309 | 309 | overlap: Vec<f32>, |
| 310 | 310 | prev_shape_kbd: bool, |
| 311 | - prev_short: bool, | |
| 312 | 311 | } |
| 313 | 312 | |
| 314 | 313 | impl Default for ChannelState { |
| @@ -316,7 +315,6 @@ impl Default for ChannelState { | ||
| 316 | 315 | ChannelState { |
| 317 | 316 | overlap: vec![0.0; FRAME_LEN], |
| 318 | 317 | prev_shape_kbd: false, |
| 319 | - prev_short: false, | |
| 320 | 318 | } |
| 321 | 319 | } |
| 322 | 320 | } |
| @@ -424,7 +422,6 @@ impl FilterBank { | ||
| 424 | 422 | } |
| 425 | 423 | state.overlap.copy_from_slice(&frame[FRAME_LEN..]); |
| 426 | 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 | 871 | /// Decodes one `raw_data_block`, returning one PCM plane per channel in |
| 795 | 872 | /// bitstream element order. |
| 796 | 873 | pub fn raw_data_block(&mut self, r: &mut BitReader<'_>) -> Result<Vec<Vec<f32>>> { |
| @@ -890,77 +967,7 @@ impl BlockDecoder { | ||
| 890 | 967 | pending = None; |
| 891 | 968 | } |
| 892 | 969 | 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)?; | |
| 964 | 971 | } |
| 965 | 972 | _ => { |
| 966 | 973 | // 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 | 538 | let mut ms = vec![false; max_sfb]; |
| 539 | 539 | if *element == Element::Cpe && self.config.mid_side { |
| 540 | 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 | 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 | 547 | elements.push(ElementPlan { |
| 548 | 548 | element: *element, |
| @@ -563,7 +563,7 @@ impl AacEncoder { | ||
| 563 | 563 | .map(|plan| { |
| 564 | 564 | plan.frames |
| 565 | 565 | .iter() |
| 566 | - .map(|frame| band_profile(frame, swb, max_sfb, short)) | |
| 566 | + .map(|frame| band_profile(frame, swb, max_sfb, seq)) | |
| 567 | 567 | .collect() |
| 568 | 568 | }) |
| 569 | 569 | .collect(); |
| @@ -759,14 +759,14 @@ impl AacEncoder { | ||
| 759 | 759 | max_sfb, |
| 760 | 760 | b, |
| 761 | 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 | 763 | ) <= target |
| 764 | 764 | { |
| 765 | 765 | let (mut lo, mut hi) = (floor[b], 255); |
| 766 | 766 | while lo < hi { |
| 767 | 767 | let mid = lo + (hi - lo + 1) / 2; |
| 768 | 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 | 770 | }) <= target { |
| 771 | 771 | lo = mid; |
| 772 | 772 | } else { |
| @@ -848,7 +848,7 @@ impl AacEncoder { | ||
| 848 | 848 | if books[b] == 0 { |
| 849 | 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 | 852 | let value = prev.map_or(60, |p| (60 + sf[b] - p).clamp(0, 120)); |
| 853 | 853 | bits += i32::from(SCALEFACTOR_CODES[value as usize].0); |
| 854 | 854 | prev = Some(sf[b]); |
| @@ -871,7 +871,6 @@ impl AacEncoder { | ||
| 871 | 871 | books, |
| 872 | 872 | quant, |
| 873 | 873 | bits, |
| 874 | - short, | |
| 875 | 874 | } |
| 876 | 875 | } |
| 877 | 876 | |
| @@ -883,8 +882,9 @@ impl AacEncoder { | ||
| 883 | 882 | band: usize, |
| 884 | 883 | sf: i32, |
| 885 | 884 | windows: usize, |
| 886 | - short: bool, | |
| 885 | + seq: WindowSequence, | |
| 887 | 886 | ) -> f32 { |
| 887 | + let short = seq == WindowSequence::EightShort; | |
| 888 | 888 | let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1])); |
| 889 | 889 | let gain = pow_quarter(sf - SF_OFFSET); |
| 890 | 890 | let gain_inv = pow_quarter(SF_OFFSET - sf); |
| @@ -922,12 +922,18 @@ struct Coded { | ||
| 922 | 922 | books: Vec<u8>, |
| 923 | 923 | quant: Vec<i32>, |
| 924 | 924 | bits: i32, |
| 925 | - short: bool, | |
| 926 | 925 | } |
| 927 | 926 | |
| 928 | 927 | /// True when mid/side splits this band's energy more lopsidedly than left/right |
| 929 | 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 | 937 | let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1])); |
| 932 | 938 | let windows = if short { 8 } else { 1 }; |
| 933 | 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 | 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 | 974 | let windows = if short { 8 } else { 1 }; |
| 963 | 975 | let mut peak = vec![0.0f32; max_sfb]; |
| 964 | 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 | 1047 | let windows = if short { 8 } else { 1 }; |
| 1029 | 1048 | for b in 0..max_sfb { |
| 1030 | 1049 | if !ms[b] { |
| @@ -1125,8 +1144,9 @@ fn band_bits( | ||
| 1125 | 1144 | band: usize, |
| 1126 | 1145 | book: u8, |
| 1127 | 1146 | windows: usize, |
| 1128 | - short: bool, | |
| 1147 | + seq: WindowSequence, | |
| 1129 | 1148 | ) -> i32 { |
| 1149 | + let short = seq == WindowSequence::EightShort; | |
| 1130 | 1150 | let cb = &CODEBOOKS[usize::from(book) - 1]; |
| 1131 | 1151 | let (lo, hi) = (usize::from(swb[band]), usize::from(swb[band + 1])); |
| 1132 | 1152 | let dim = usize::from(cb.dim); |
| @@ -1218,7 +1238,7 @@ fn write_ics_info(w: &mut BitWriter, c: &Coded) { | ||
| 1218 | 1238 | }; |
| 1219 | 1239 | w.write_bits(seq, 2); |
| 1220 | 1240 | w.write_bit(false); // sine window shape |
| 1221 | - if c.short { | |
| 1241 | + if c.seq == WindowSequence::EightShort { | |
| 1222 | 1242 | w.write_bits(c.max_sfb as u32, 4); |
| 1223 | 1243 | w.write_bits(0x7F, 7); // one group of eight windows |
| 1224 | 1244 | } else { |
| @@ -1235,7 +1255,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) { | ||
| 1235 | 1255 | write_ics_info(w, c); |
| 1236 | 1256 | } |
| 1237 | 1257 | // 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 | 1259 | let esc = (1u32 << esc_bits) - 1; |
| 1240 | 1260 | let mut b = 0usize; |
| 1241 | 1261 | while b < c.max_sfb { |
| @@ -1267,7 +1287,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) { | ||
| 1267 | 1287 | w.write_bit(false); // tns_data_present |
| 1268 | 1288 | w.write_bit(false); // gain_control_data_present |
| 1269 | 1289 | // spectral_data |
| 1270 | - let windows = if c.short { 8 } else { 1 }; | |
| 1290 | + let windows = if c.seq == WindowSequence::EightShort { 8 } else { 1 }; | |
| 1271 | 1291 | for b in 0..c.max_sfb { |
| 1272 | 1292 | let book = c.books[b]; |
| 1273 | 1293 | if book == 0 { |
| @@ -1277,7 +1297,7 @@ fn write_ics(w: &mut BitWriter, c: &Coded, own_info: bool) { | ||
| 1277 | 1297 | let dim = usize::from(cb.dim); |
| 1278 | 1298 | let (lo, hi) = (usize::from(c.swb[b]), usize::from(c.swb[b + 1])); |
| 1279 | 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 | 1301 | let mut k = lo; |
| 1282 | 1302 | while k < hi { |
| 1283 | 1303 | let end = (k + dim).min(hi); |
crates/ec-aac/src/huffman.rsmodified+33 -0
| @@ -83,3 +83,36 @@ impl Default for Books { | ||
| 83 | 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 | 8 | //! its handling of stale fields, so that the decoded parameters match the |
| 9 | 9 | //! reference decoder frame for frame. |
| 10 | 10 | |
| 11 | +use crate::huffman::Tree; | |
| 11 | 12 | use crate::ps_huff; |
| 12 | 13 | use ec_core::{BitReader, Error, Result}; |
| 13 | 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 | 99 | 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 | + } | |
| 100 | 112 | } |
| 101 | 113 | |
| 102 | 114 | /// The ten PS Huffman tables, with canonical codes assigned from the lengths. |
| @@ -106,7 +118,7 @@ fn vlcs() -> &'static [Vlc] { | ||
| 106 | 118 | ps_huff::TABLES |
| 107 | 119 | .iter() |
| 108 | 120 | .zip(ps_huff::OFFSETS) |
| 109 | - .map(|(table, offset)| build_codes(table, offset)) | |
| 121 | + .map(|(table, offset)| Vlc::new(&build_codes(table, offset))) | |
| 110 | 122 | .collect() |
| 111 | 123 | }) |
| 112 | 124 | } |
| @@ -117,36 +129,23 @@ fn vlcs() -> &'static [Vlc] { | ||
| 117 | 129 | /// lengths alone do not fix the codes, which is why sorting them canonically |
| 118 | 130 | /// misreads every fine-IID and ICC frame. Every table in the standard is a |
| 119 | 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 | 133 | let mut codes = Vec::with_capacity(table.len()); |
| 122 | 134 | // Position in the code space, in units of 2^-32 (a 64-bit sum: no overflow). |
| 123 | 135 | let mut next: u64 = 0; |
| 124 | - let mut max_len = 0; | |
| 125 | 136 | for &(value, len) in table { |
| 126 | 137 | let len = u32::from(len).clamp(1, 32); |
| 127 | 138 | let code = (next >> (32 - len)) as u32; |
| 128 | 139 | codes.push((len, code, i32::from(value) + offset)); |
| 129 | 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 | 145 | /// Reads one codeword of table `which` and returns its parameter value. |
| 136 | 146 | 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)?]) | |
| 150 | 149 | } |
| 151 | 150 | |
| 152 | 151 | /// Reads one IID/ICC/IPD/OPD parameter row (FFmpeg's `READ_PAR_DATA`). |
| @@ -458,17 +457,28 @@ mod tests { | ||
| 458 | 457 | // length 4) and (value +2, length 4), so they get codes 0000 and 0001, |
| 459 | 458 | // not the canonical order a length sort would give. |
| 460 | 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)); | |
| 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 | + } | |
| 464 | 474 | } |
| 465 | 475 | |
| 466 | 476 | #[test] |
| 467 | 477 | fn codes_are_prefix_free_and_values_cover_the_range() { |
| 468 | 478 | for (i, table) in ps_huff::TABLES.iter().enumerate() { |
| 469 | 479 | 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) { | |
| 472 | 482 | let (short, long, cs, cl) = if la <= lb { (la, lb, ca, cb) } else { (lb, la, cb, ca) }; |
| 473 | 483 | assert!(cl >> (long - short) != cs, "table {i} codes collide"); |
| 474 | 484 | } |
| @@ -498,7 +508,7 @@ mod tests { | ||
| 498 | 508 | push(&mut bits, 0, 1); // dt = 0 for the envelope |
| 499 | 509 | let code_for_zero = { |
| 500 | 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 | 513 | for _ in 0..10 { |
| 504 | 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 | 377 | continue; |
| 378 | 378 | } |
| 379 | 379 | 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); | |
| 405 | 381 | |
| 406 | 382 | let sbr_ch = &data.channels[ch]; |
| 407 | 383 | let hf = sbr_hf::generate( |
| @@ -481,17 +457,7 @@ impl SbrChain { | ||
| 481 | 457 | |
| 482 | 458 | let kx = (tables.kx as usize).min(ANALYSIS_BANDS); |
| 483 | 459 | 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); | |
| 495 | 461 | let out = match (ps_mode && num_slots == PS_SLOTS, data.ps.as_ref()) { |
| 496 | 462 | (true, Some(ps)) => { |
| 497 | 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 | 555 | /// Inserts the second output plane a PS element needs, right after its first |
| 534 | 556 | /// (a copy, which the PS path then overwrites). Returns the element's new |
| 535 | 557 | /// plane count: 2 when a plane was inserted. |
crates/ec-aac/src/sbr_payload.rsmodified+68 -32
| @@ -15,7 +15,9 @@ | ||
| 15 | 15 | //! `sbrtables.py` never needed them for the codebook derivation. |
| 16 | 16 | #![allow(dead_code)] |
| 17 | 17 | |
| 18 | +use crate::huffman::Tree; | |
| 18 | 19 | use crate::ps_data::PsCommon; |
| 20 | +use std::sync::LazyLock; | |
| 19 | 21 | use crate::sbr_bands::{BandTables, freq_tables}; |
| 20 | 22 | use crate::sbr_tables::*; |
| 21 | 23 | use ec_core::{BitReader, Error, Result}; |
| @@ -165,25 +167,74 @@ pub struct SbrParser { | ||
| 165 | 167 | /// `bs_extension_id` of Parametric Stereo. |
| 166 | 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 | 219 | 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, | |
| 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 | 233 | 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, | |
| 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 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)?]) | |
| 259 | 295 | } |
| 260 | 296 | |
| 261 | 297 | impl SbrParser { |
crates/ec-mp3/src/decode.rsmodified+38 -15
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | //! filterbank that turns 576 coefficients back into PCM. |
| 3 | 3 | |
| 4 | 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 | 6 | use crate::huffman; |
| 7 | 7 | use crate::layer12::Layer12; |
| 8 | 8 | use crate::tables::{ |
| @@ -22,6 +22,29 @@ pub struct DecodedFrame { | ||
| 22 | 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 | 48 | #[derive(Clone, Copy, Debug, Default)] |
| 26 | 49 | struct GranuleInfo { |
| 27 | 50 | part2_3_length: u32, |
| @@ -29,7 +52,7 @@ struct GranuleInfo { | ||
| 29 | 52 | global_gain: u32, |
| 30 | 53 | scalefac_compress: u32, |
| 31 | 54 | window_switching: bool, |
| 32 | - block_type: u8, | |
| 55 | + block_type: BlockType, | |
| 33 | 56 | mixed_block: bool, |
| 34 | 57 | table_select: [u8; 3], |
| 35 | 58 | subblock_gain: [u32; 3], |
| @@ -86,7 +109,7 @@ fn parse_side_info(header: &FrameHeader, bytes: &[u8]) -> Result<SideInfo> { | ||
| 86 | 109 | ))); |
| 87 | 110 | } |
| 88 | 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 | 113 | g.mixed_block = r.read_bit()?; |
| 91 | 114 | for slot in &mut g.table_select[..2] { |
| 92 | 115 | *slot = r.read_bits(5)? as u8; |
| @@ -94,13 +117,13 @@ fn parse_side_info(header: &FrameHeader, bytes: &[u8]) -> Result<SideInfo> { | ||
| 94 | 117 | for slot in &mut g.subblock_gain { |
| 95 | 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 | 121 | 8 |
| 99 | 122 | } else { |
| 100 | 123 | 7 |
| 101 | 124 | }; |
| 102 | 125 | g.region1_count = 20 - g.region0_count; |
| 103 | - if g.block_type == 0 { | |
| 126 | + if g.block_type == BlockType::Normal { | |
| 104 | 127 | return Err(Error::corrupt( |
| 105 | 128 | "mp3: window switching with normal block type", |
| 106 | 129 | )); |
| @@ -192,7 +215,7 @@ impl Mp3Decode { | ||
| 192 | 215 | if frame.len() < frame_len { |
| 193 | 216 | return Err(Error::NeedMore); |
| 194 | 217 | } |
| 195 | - if header.layer != 3 { | |
| 218 | + if header.layer != Layer::III { | |
| 196 | 219 | let samples = self.layer12.decode(&header, &frame[..frame_len])?; |
| 197 | 220 | return Ok(DecodedFrame { |
| 198 | 221 | sample_rate: header.sample_rate, |
| @@ -309,7 +332,7 @@ impl Mp3Decode { | ||
| 309 | 332 | ) -> Result<()> { |
| 310 | 333 | let granule = side.granules[gr][ch]; |
| 311 | 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 | 336 | if granule.mixed_block { |
| 314 | 337 | for sfb in 0..8 { |
| 315 | 338 | self.scalefac_l[ch][sfb] = reader.read_bits(slen1)? as u8; |
| @@ -386,7 +409,7 @@ impl Mp3Decode { | ||
| 386 | 409 | slen = [sfc / 3, sfc % 3, 0, 0]; |
| 387 | 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 | 413 | let kind = if !short { |
| 391 | 414 | 0 |
| 392 | 415 | } else if granule.mixed_block { |
| @@ -427,7 +450,7 @@ impl Mp3Decode { | ||
| 427 | 450 | let is = &mut self.is[ch]; |
| 428 | 451 | is.fill(0); |
| 429 | 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 | 454 | let (region1, region2) = if granule.window_switching { |
| 432 | 455 | if short { |
| 433 | 456 | // Three short bands, all three windows: 36 lines at every rate |
| @@ -493,7 +516,7 @@ impl Mp3Decode { | ||
| 493 | 516 | let power = power43(); |
| 494 | 517 | let xr = &mut self.xr[ch]; |
| 495 | 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 | 520 | let multiplier = if granule.scalefac_scale { 1.0 } else { 0.5 }; |
| 498 | 521 | let base = (granule.global_gain as f32 - 210.0) * 0.25; |
| 499 | 522 | let value = |v: i32| -> f32 { |
| @@ -566,7 +589,7 @@ impl Mp3Decode { | ||
| 566 | 589 | let ms = joint && header.mode_ext & 2 != 0; |
| 567 | 590 | let intensity = joint && header.mode_ext & 1 != 0; |
| 568 | 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 | 593 | // Intensity coding starts at the first band above the right channel's |
| 571 | 594 | // last non-zero line. |
| 572 | 595 | let bound = if intensity { |
| @@ -624,7 +647,7 @@ impl Mp3Decode { | ||
| 624 | 647 | channels: usize, |
| 625 | 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 | 651 | let alias_bands = if !short { |
| 629 | 652 | 32 |
| 630 | 653 | } else if granule.mixed_block { |
| @@ -643,8 +666,8 @@ impl Mp3Decode { | ||
| 643 | 666 | if short && !(granule.mixed_block && sb < 2) { |
| 644 | 667 | self.imdct.short(coefficients, &mut block); |
| 645 | 668 | } 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); | |
| 648 | 671 | } |
| 649 | 672 | let overlap = &mut self.overlap[ch][sb]; |
| 650 | 673 | for t in 0..18 { |
| @@ -736,7 +759,7 @@ impl Mp3Reader { | ||
| 736 | 759 | return Err(Error::NeedMore); |
| 737 | 760 | } |
| 738 | 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 | 763 | self.started = true; |
| 741 | 764 | self.consumed += frame_len; |
| 742 | 765 | continue; |
crates/ec-mp3/src/encode.rsmodified+2 -2
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | //! makes available. |
| 19 | 19 | |
| 20 | 20 | use crate::filterbank::{Analysis, alias_expand}; |
| 21 | -use crate::header::{ChannelMode, FrameHeader, Version}; | |
| 21 | +use crate::header::{ChannelMode, FrameHeader, Layer, Version}; | |
| 22 | 22 | use crate::huffman::{self, BitBuf}; |
| 23 | 23 | use crate::tables::{ |
| 24 | 24 | MAX_QUANT, SLEN, forward_mdct_long, forward_mdct_short, long_starts, power43, short_starts, |
| @@ -251,7 +251,7 @@ impl Mp3Encode { | ||
| 251 | 251 | fn header(&self, bitrate_kbps: u32, padding: bool) -> FrameHeader { |
| 252 | 252 | FrameHeader { |
| 253 | 253 | version: self.version, |
| 254 | - layer: 3, | |
| 254 | + layer: Layer::III, | |
| 255 | 255 | crc: false, |
| 256 | 256 | bitrate_kbps, |
| 257 | 257 | sample_rate: self.sample_rate, |
crates/ec-mp3/src/header.rsmodified+33 -22
| @@ -15,6 +15,17 @@ pub enum Version { | ||
| 15 | 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 | 29 | /// The channel arrangement a frame declares. |
| 19 | 30 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 20 | 31 | pub enum ChannelMode { |
| @@ -55,13 +66,13 @@ const BITRATES_L2_V1: [u32; 15] = [ | ||
| 55 | 66 | /// The bitrate table for a layer of a version: Layer III and Layer II of the |
| 56 | 67 | /// low sampling frequencies share one, the other four combinations each have |
| 57 | 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 | 70 | 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, | |
| 65 | 76 | } |
| 66 | 77 | } |
| 67 | 78 | const RATES_V1: [u32; 3] = [44100, 48000, 32000]; |
| @@ -71,8 +82,8 @@ const RATES_V1: [u32; 3] = [44100, 48000, 32000]; | ||
| 71 | 82 | pub struct FrameHeader { |
| 72 | 83 | /// MPEG generation. |
| 73 | 84 | pub version: Version, |
| 74 | - /// Layer number, 1..=3. | |
| 75 | - pub layer: u8, | |
| 85 | + /// The MPEG audio layer. | |
| 86 | + pub layer: Layer, | |
| 76 | 87 | /// True when a 16-bit CRC follows the header. |
| 77 | 88 | pub crc: bool, |
| 78 | 89 | /// Declared bitrate in kbit/s; 0 means free format. |
| @@ -116,9 +127,9 @@ impl FrameHeader { | ||
| 116 | 127 | _ => return Err(Error::corrupt("mp3: reserved MPEG version id")), |
| 117 | 128 | }; |
| 118 | 129 | 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, | |
| 122 | 133 | _ => return Err(Error::corrupt("mp3: reserved layer id")), |
| 123 | 134 | }; |
| 124 | 135 | let crc = (b[1] & 1) == 0; |
| @@ -166,9 +177,9 @@ impl FrameHeader { | ||
| 166 | 177 | Version::Mpeg1 => 3, |
| 167 | 178 | }; |
| 168 | 179 | 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, | |
| 172 | 183 | }; |
| 173 | 184 | let bitrate_index = bitrate_table(self.version, self.layer) |
| 174 | 185 | .iter() |
| @@ -215,9 +226,9 @@ impl FrameHeader { | ||
| 215 | 226 | /// PCM samples per channel produced by this frame. |
| 216 | 227 | pub fn samples_per_frame(&self) -> usize { |
| 217 | 228 | 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, | |
| 221 | 232 | } |
| 222 | 233 | } |
| 223 | 234 | |
| @@ -241,10 +252,10 @@ impl FrameHeader { | ||
| 241 | 252 | let rate = self.sample_rate as usize; |
| 242 | 253 | let pad = usize::from(self.padding); |
| 243 | 254 | 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, | |
| 248 | 259 | }) |
| 249 | 260 | } |
| 250 | 261 | } |
| @@ -298,7 +309,7 @@ mod tests { | ||
| 298 | 309 | let bytes = [0xFF, 0xFB, 0x90, 0x00]; |
| 299 | 310 | let h = FrameHeader::parse(&bytes).unwrap(); |
| 300 | 311 | assert_eq!(h.version, Version::Mpeg1); |
| 301 | - assert_eq!(h.layer, 3); | |
| 312 | + assert_eq!(h.layer, Layer::III); | |
| 302 | 313 | assert_eq!(h.bitrate_kbps, 128); |
| 303 | 314 | assert_eq!(h.sample_rate, 44100); |
| 304 | 315 | assert_eq!(h.mode, ChannelMode::Stereo); |
crates/ec-mp3/src/layer12.rsmodified+2 -2
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | //! copied: `scripts/mp2-tables/measure.py` sets one allocation code at a time and |
| 8 | 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 | 11 | use crate::window::WINDOW; |
| 12 | 12 | use ec_core::bitio::BitReader; |
| 13 | 13 | use ec_core::error::{Error, Result}; |
| @@ -188,7 +188,7 @@ impl Layer12 { | ||
| 188 | 188 | let body = &frame[4 + usize::from(header.crc) * 2..]; |
| 189 | 189 | let mut r = BitReader::new(body); |
| 190 | 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 | 192 | self.read_layer1(header, frame, &mut r, &mut subband)?; |
| 193 | 193 | 12 |
| 194 | 194 | } else { |
crates/ec-mp3/tests/mp2_matrix.rsmodified+11 -10
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | |
| 11 | 11 | use std::path::PathBuf; |
| 12 | 12 | |
| 13 | +use ec_mp3::header::Layer; | |
| 13 | 14 | use ec_mp3::{FrameHeader, Mp3Reader}; |
| 14 | 15 | |
| 15 | 16 | fn work_dir() -> PathBuf { |
| @@ -18,8 +19,8 @@ fn work_dir() -> PathBuf { | ||
| 18 | 19 | d |
| 19 | 20 | } |
| 20 | 21 | |
| 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" }; | |
| 23 | 24 | let out = ec_testkit::ffmpeg() |
| 24 | 25 | .args(["-v", "error", "-c:a", decoder, "-i"]) |
| 25 | 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 | 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 | - 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" }; | |
| 45 | 46 | let out = ec_testkit::ffmpeg() |
| 46 | 47 | .args(["-v", "error", "-c:a", decoder, "-i"]) |
| 47 | 48 | .arg(path) |
| @@ -192,7 +193,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec< | ||
| 192 | 193 | let rnd = |rng: &mut Rng, n: u32| (rng.next() >> 20) as u32 % n.max(1); |
| 193 | 194 | let (nb_sb, bound); |
| 194 | 195 | let rows: Vec<Vec<u32>>; |
| 195 | - if h.layer == 1 { | |
| 196 | + if h.layer == Layer::I { | |
| 196 | 197 | nb_sb = 32; |
| 197 | 198 | rows = Vec::new(); |
| 198 | 199 | } else { |
| @@ -207,14 +208,14 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec< | ||
| 207 | 208 | // allocation codes |
| 208 | 209 | let mut alloc = vec![vec![0u32; nb_sb]; 2]; |
| 209 | 210 | let width = |sb: usize| -> u32 { |
| 210 | - if h.layer == 1 { | |
| 211 | + if h.layer == Layer::I { | |
| 211 | 212 | 4 |
| 212 | 213 | } else { |
| 213 | 214 | rows[sb].len().trailing_zeros() |
| 214 | 215 | } |
| 215 | 216 | }; |
| 216 | 217 | for sb in 0..nb_sb { |
| 217 | - let maxcode = if h.layer == 1 { | |
| 218 | + let maxcode = if h.layer == Layer::I { | |
| 218 | 219 | 15 |
| 219 | 220 | } else { |
| 220 | 221 | 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 | 250 | let mut scfsi = vec![vec![0u32; nb_sb]; 2]; |
| 250 | - if h.layer == 2 { | |
| 251 | + if h.layer == Layer::II { | |
| 251 | 252 | for sb in 0..nb_sb { |
| 252 | 253 | for ch in 0..channels { |
| 253 | 254 | if alloc[ch][sb] != 0 { |
| @@ -264,7 +265,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec< | ||
| 264 | 265 | if alloc[ch][sb] == 0 { |
| 265 | 266 | continue; |
| 266 | 267 | } |
| 267 | - let n = if h.layer == 1 { | |
| 268 | + let n = if h.layer == Layer::I { | |
| 268 | 269 | 1 |
| 269 | 270 | } else { |
| 270 | 271 | match scfsi[ch][sb] { |
| @@ -287,7 +288,7 @@ fn structured_frame(rng: &mut Rng, h: &FrameHeader, density: u32) -> Option<Vec< | ||
| 287 | 288 | if a == 0 { |
| 288 | 289 | continue; |
| 289 | 290 | } |
| 290 | - if h.layer == 1 { | |
| 291 | + if h.layer == Layer::I { | |
| 291 | 292 | let nb = a + 1; |
| 292 | 293 | w.put(rnd(rng, (1 << nb) - 1), nb); |
| 293 | 294 | } else { |