forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

layer12.rs418 lines, 13.5 KiBHistoryRawDownload
1//! Layers I and II (MP1/MP2): bit allocation, scalefactors, requantisation and
2//! the same 32-band polyphase synthesis Layer III uses.
3//!
4//! Layer II's allocation tables (ISO/IEC 11172-3 Tables 3-B.2a..d and the
5//! ISO/IEC 13818-3 low-sampling-frequency table) are normative data, so like
6//! the Layer III tables they were *measured* from an oracle decoder rather than
7//! copied: `scripts/mp2-tables/measure.py` sets one allocation code at a time and
8//! reads the quantiser size back from the decoded level.
9
10use crate::header::{ChannelMode, FrameHeader, Version, crc16_bits};
11use crate::window::WINDOW;
12use ec_core::bitio::BitReader;
13use ec_core::error::{Error, Result};
14
15// Quantiser sizes (number of levels) by allocation code; 0 means "not coded".
16const Q_A: [u32; 16] = [
17 0, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535,
18];
19const Q_B: [u32; 16] = [
20 0, 3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 65535,
21];
22const Q_C: [u32; 8] = [0, 3, 5, 7, 9, 15, 31, 65535];
23const Q_D: [u32; 4] = [0, 3, 5, 65535];
24const Q_E: [u32; 16] = [
25 0, 3, 5, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767,
26];
27const Q_F: [u32; 8] = [0, 3, 5, 9, 15, 31, 63, 127];
28const Q_G: [u32; 16] = [
29 0, 3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383,
30];
31const Q_H: [u32; 4] = [0, 3, 5, 9];
32
33/// One subband's allocation: how many bits the code takes, and what each code means.
34type Row = &'static [u32];
35
36/// The five Layer II allocation tables as `(row, subband count)` runs.
37const TABLES: [&[(&[u32], usize)]; 5] = [
38 // 3-B.2a: 27 bands.
39 &[(&Q_A, 3), (&Q_B, 8), (&Q_C, 12), (&Q_D, 4)],
40 // 3-B.2b: 30 bands.
41 &[(&Q_A, 3), (&Q_B, 8), (&Q_C, 12), (&Q_D, 7)],
42 // 3-B.2c: 8 bands.
43 &[(&Q_E, 2), (&Q_F, 6)],
44 // 3-B.2d: 12 bands.
45 &[(&Q_E, 2), (&Q_F, 10)],
46 // 13818-3 LSF: 30 bands.
47 &[(&Q_G, 4), (&Q_F, 7), (&Q_H, 19)],
48];
49
50/// Which table a Layer II stream uses (ISO/IEC 11172-3 2.4.2.3).
51fn select_table(header: &FrameHeader) -> usize {
52 if header.version != Version::Mpeg1 {
53 return 4;
54 }
55 let ch_bitrate = header.bitrate_kbps / header.channels() as u32;
56 let rate = header.sample_rate;
57 if (rate == 48000 && ch_bitrate >= 56) || (56..=80).contains(&ch_bitrate) {
58 0
59 } else if rate != 48000 && ch_bitrate >= 96 {
60 1
61 } else if rate != 32000 && ch_bitrate <= 48 {
62 2
63 } else {
64 3
65 }
66}
67
68/// Scalefactor multipliers, `2^(1 - i/3)`.
69fn scalefactor(index: u32) -> f32 {
70 (2.0f64).powf(1.0 - f64::from(index) / 3.0) as f32
71}
72
73/// Bits one sample takes for a quantiser of `levels` levels.
74fn sample_bits(levels: u32) -> u32 {
75 match levels {
76 3 => 2,
77 5 => 3,
78 9 => 4,
79 n => 32 - n.leading_zeros(),
80 }
81}
82
83/// `(2v - L + 1) / L`: the requantised value of code `v` out of `L` levels,
84/// before the scalefactor. (The standard's `C * (s + D)` collapses to this.)
85fn level(v: u32, levels: u32) -> f32 {
86 ((2.0 * f64::from(v) - f64::from(levels) + 1.0) / f64::from(levels)) as f32
87}
88
89/// The stateful half of Layer I/II decoding: just the synthesis history.
90#[derive(Debug, Default)]
91pub(crate) struct Layer12 {
92 pub(crate) synthesis: [Synth; 2],
93}
94
95/// Matrixing cosines `cos(pi m (2k+1) / 64)` and the synthesis window `D[i]`.
96struct Tables {
97 cos: [[f64; 32]; 32],
98 window: [f64; 512],
99}
100
101/// The standard's `D[i]` are integers over 65536 (ISO/IEC 11172-3 Table 3-B.3
102/// lists them to nine decimals) and the window measured for Layer III is within
103/// 2e-6 of them, well inside the 7.6e-6 half-step, so rounding recovers the exact
104/// table. Layers I/II run the whole bank in f64 with it, which leaves the
105/// result limited by the f32 output alone.
106fn tables() -> &'static Tables {
107 static T: std::sync::OnceLock<Tables> = std::sync::OnceLock::new();
108 T.get_or_init(|| {
109 let mut t = Tables {
110 cos: [[0.0; 32]; 32],
111 window: [0.0; 512],
112 };
113 for (m, row) in t.cos.iter_mut().enumerate() {
114 for (k, c) in row.iter_mut().enumerate() {
115 *c = (std::f64::consts::PI * (m * (2 * k + 1)) as f64 / 64.0).cos();
116 }
117 }
118 for (o, w) in t.window.iter_mut().zip(WINDOW.iter()) {
119 *o = (f64::from(*w) * 65536.0).round() / 65536.0;
120 }
121 t
122 })
123}
124
125/// One channel's polyphase synthesis: 32 subband samples in, 32 PCM out.
126#[derive(Debug)]
127pub(crate) struct Synth {
128 blocks: Vec<[f64; 64]>,
129 pos: usize,
130}
131
132impl Default for Synth {
133 fn default() -> Synth {
134 Synth {
135 blocks: vec![[0.0; 64]; 16],
136 pos: 0,
137 }
138 }
139}
140
141impl Synth {
142 fn reset(&mut self) {
143 self.blocks.iter_mut().for_each(|b| b.fill(0.0));
144 self.pos = 0;
145 }
146
147 fn slot(&mut self, subband: &[f32; 32], out: &mut [f32]) {
148 let t = tables();
149 let mut g = [0.0f64; 32];
150 for (m, g) in g.iter_mut().enumerate() {
151 *g = subband
152 .iter()
153 .zip(&t.cos[m])
154 .map(|(s, c)| f64::from(*s) * c)
155 .sum();
156 }
157 self.pos = (self.pos + 15) % 16;
158 let v = &mut self.blocks[self.pos];
159 for (b, slot) in v.iter_mut().enumerate() {
160 *slot = match b {
161 0..=15 => g[b + 16],
162 16 => 0.0,
163 17..=47 => -g[48 - b],
164 _ => -g[b - 48],
165 };
166 }
167 for (j, sample) in out.iter_mut().enumerate() {
168 let mut acc = 0.0f64;
169 for i in 0..16 {
170 let b = if i % 2 == 0 { j } else { j + 32 };
171 acc += t.window[j + 32 * i] * self.blocks[(self.pos + i) % 16][b];
172 }
173 *sample = acc as f32;
174 }
175 }
176}
177
178impl Layer12 {
179 pub(crate) fn reset(&mut self) {
180 for s in &mut self.synthesis {
181 s.reset();
182 }
183 }
184
185 /// Decodes one frame of Layer I or II; `frame` is the whole frame, header included.
186 pub(crate) fn decode(&mut self, header: &FrameHeader, frame: &[u8]) -> Result<Vec<f32>> {
187 let channels = header.channels();
188 let body = &frame[4 + usize::from(header.crc) * 2..];
189 let mut r = BitReader::new(body);
190 let mut subband = vec![[[0.0f32; 32]; 2]; 36];
191 let slots = if header.layer == 1 {
192 self.read_layer1(header, frame, &mut r, &mut subband)?;
193 12
194 } else {
195 self.read_layer2(header, frame, &mut r, &mut subband)?;
196 36
197 };
198 let mut out = vec![0.0f32; slots * 32 * channels];
199 let mut pcm = [0.0f32; 32];
200 for (t, slot) in subband.iter().take(slots).enumerate() {
201 for ch in 0..channels {
202 self.synthesis[ch].slot(&slot[ch], &mut pcm);
203 for (j, sample) in pcm.iter().enumerate() {
204 out[(t * 32 + j) * channels + ch] = *sample;
205 }
206 }
207 }
208 Ok(out)
209 }
210
211 fn bound(header: &FrameHeader, limit: usize) -> usize {
212 if header.mode == ChannelMode::JointStereo {
213 (4 + 4 * usize::from(header.mode_ext)).min(limit)
214 } else {
215 limit
216 }
217 }
218
219 fn check_crc(header: &FrameHeader, frame: &[u8], body: &[u8], bits: u64) -> Result<()> {
220 if !header.crc {
221 return Ok(());
222 }
223 let stored = u16::from_be_bytes([frame[4], frame[5]]);
224 let computed = crc16_bits(
225 &[frame[0], frame[1], frame[2], frame[3]],
226 body,
227 bits as usize,
228 );
229 if stored != computed {
230 return Err(Error::corrupt(format!(
231 "mp2: allocation CRC {computed:#06x} != {stored:#06x}"
232 )));
233 }
234 Ok(())
235 }
236
237 fn read_layer1(
238 &mut self,
239 header: &FrameHeader,
240 frame: &[u8],
241 r: &mut BitReader<'_>,
242 out: &mut [[[f32; 32]; 2]],
243 ) -> Result<()> {
244 let channels = header.channels();
245 let bound = Self::bound(header, 32);
246 let mut alloc = [[0u32; 32]; 2];
247 for sb in 0..32 {
248 if sb < bound {
249 for a in alloc.iter_mut().take(channels) {
250 a[sb] = r.read_bits(4)?;
251 }
252 } else {
253 let v = r.read_bits(4)?;
254 alloc[0][sb] = v;
255 alloc[1][sb] = v;
256 }
257 }
258 Self::check_crc(header, frame, &frame[4 + 2..], r.bit_position())?;
259 if alloc.iter().take(channels).flatten().any(|&a| a == 15) {
260 return Err(Error::corrupt("mp1: forbidden allocation code 15"));
261 }
262 let mut sf = [[0.0f32; 32]; 2];
263 for sb in 0..32 {
264 for ch in 0..channels {
265 if alloc[ch][sb] != 0 {
266 sf[ch][sb] = scalefactor(r.read_bits(6)?);
267 }
268 }
269 }
270 for slot in out.iter_mut().take(12) {
271 for sb in 0..32 {
272 if sb < bound {
273 for ch in 0..channels {
274 let a = alloc[ch][sb];
275 if a != 0 {
276 let nb = a + 1;
277 let v = r.read_bits(nb)?;
278 slot[ch][sb] = level(v, (1 << nb) - 1) * sf[ch][sb];
279 }
280 }
281 } else {
282 let a = alloc[0][sb];
283 if a != 0 {
284 let nb = a + 1;
285 let v = r.read_bits(nb)?;
286 let x = level(v, (1 << nb) - 1);
287 for ch in 0..channels {
288 slot[ch][sb] = x * sf[ch][sb];
289 }
290 }
291 }
292 }
293 }
294 Ok(())
295 }
296
297 fn read_layer2(
298 &mut self,
299 header: &FrameHeader,
300 frame: &[u8],
301 r: &mut BitReader<'_>,
302 out: &mut [[[f32; 32]; 2]],
303 ) -> Result<()> {
304 let channels = header.channels();
305 let table = TABLES[select_table(header)];
306 let mut rows: Vec<Row> = Vec::with_capacity(30);
307 for &(row, count) in table {
308 rows.extend(std::iter::repeat_n(row, count));
309 }
310 let sblimit = rows.len();
311 let bound = Self::bound(header, sblimit);
312 // Quantiser levels per band and channel.
313 let mut levels = [[0u32; 30]; 2];
314 for sb in 0..sblimit {
315 let bits = rows[sb].len().trailing_zeros();
316 if sb < bound {
317 for l in levels.iter_mut().take(channels) {
318 l[sb] = rows[sb][r.read_bits(bits)? as usize];
319 }
320 } else {
321 let v = rows[sb][r.read_bits(bits)? as usize];
322 levels[0][sb] = v;
323 levels[1][sb] = v;
324 }
325 }
326 let mut scfsi = [[0u32; 30]; 2];
327 for sb in 0..sblimit {
328 for ch in 0..channels {
329 if levels[ch][sb] != 0 {
330 scfsi[ch][sb] = r.read_bits(2)?;
331 }
332 }
333 }
334 Self::check_crc(header, frame, &frame[4 + 2..], r.bit_position())?;
335 let mut sf = [[[0.0f32; 3]; 30]; 2];
336 for sb in 0..sblimit {
337 for ch in 0..channels {
338 if levels[ch][sb] == 0 {
339 continue;
340 }
341 let mut idx = [0u32; 3];
342 match scfsi[ch][sb] {
343 0 => {
344 for v in &mut idx {
345 *v = r.read_bits(6)?;
346 }
347 }
348 1 => {
349 idx[0] = r.read_bits(6)?;
350 idx[1] = idx[0];
351 idx[2] = r.read_bits(6)?;
352 }
353 2 => {
354 idx = [r.read_bits(6)?; 3];
355 }
356 _ => {
357 idx[0] = r.read_bits(6)?;
358 idx[1] = r.read_bits(6)?;
359 idx[2] = idx[1];
360 }
361 }
362 for (part, i) in idx.iter().enumerate() {
363 sf[ch][sb][part] = scalefactor(*i);
364 }
365 }
366 }
367 for gr in 0..12 {
368 let part = gr / 4;
369 let mut vals = [[[0.0f32; 3]; 30]; 2];
370 for sb in 0..sblimit {
371 if sb < bound {
372 for ch in 0..channels {
373 vals[ch][sb] = read_samples(r, levels[ch][sb])?;
374 }
375 } else {
376 let v = read_samples(r, levels[0][sb])?;
377 vals[0][sb] = v;
378 vals[1][sb] = v;
379 }
380 }
381 for s in 0..3 {
382 for sb in 0..sblimit {
383 for ch in 0..channels {
384 out[gr * 3 + s][ch][sb] = vals[ch][sb][s] * sf[ch][sb][part];
385 }
386 }
387 }
388 }
389 Ok(())
390 }
391}
392
393/// Three consecutive samples of one band: grouped into a single code for the
394/// 3-, 5- and 9-level quantisers, otherwise one code each.
395fn read_samples(r: &mut BitReader<'_>, levels: u32) -> Result<[f32; 3]> {
396 let mut out = [0.0f32; 3];
397 if levels == 0 {
398 return Ok(out);
399 }
400 if matches!(levels, 3 | 5 | 9) {
401 let bits = match levels {
402 3 => 5,
403 5 => 7,
404 _ => 10,
405 };
406 let mut code = r.read_bits(bits)?;
407 for o in &mut out {
408 *o = level(code % levels, levels);
409 code /= levels;
410 }
411 } else {
412 let bits = sample_bits(levels);
413 for o in &mut out {
414 *o = level(r.read_bits(bits)?, levels);
415 }
416 }
417 Ok(out)
418}