forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB70849e0Tahinli2 months ago3122 commits

decode.rs591 lines, 19.0 KiBHistoryRawDownload
1//! One ALAC frame: the element walk, the adaptive-Golomb residual decoder, the
2//! adapting LPC predictor and the stereo un-mix.
3//!
4//! Written from the published ALAC format description (element tags and frame
5//! header layout, the Golomb/Rice parameter adaptation with its zero-run mode,
6//! the sign-adapting predictor and the mid/side un-mix). Nothing here is
7//! derived from the reference decoder sources.
8
9use crate::MagicCookie;
10use ec_core::error::{Error, Result};
11
12/// Mean-tracking parameters live in Q9.
13const QBSHIFT: u32 = 9;
14/// `1 << QBSHIFT`, the point where the mean says "the residuals are all zero".
15const QB: u32 = 1 << QBSHIFT;
16const MMULSHIFT: u32 = 2;
17const MDENSHIFT: u32 = QBSHIFT - MMULSHIFT - 1;
18const MOFF: u32 = 1 << (MDENSHIFT - 2);
19const BITOFF: i32 = 24;
20/// Unary prefixes this long are an escape: the value follows raw.
21const MAX_PREFIX: u32 = 9;
22/// Width of the raw value after a zero-run escape.
23const MAX_RUN_BITS: u32 = 16;
24/// A mean this large is clamped rather than allowed to run away.
25const MEAN_CLAMP: u32 = 0xffff;
26
27/// Syntax element tags, three bits at the head of every element.
28const ID_SCE: u32 = 0;
29const ID_CPE: u32 = 1;
30const ID_CCE: u32 = 2;
31const ID_LFE: u32 = 3;
32const ID_DSE: u32 = 4;
33const ID_PCE: u32 = 5;
34const ID_FIL: u32 = 6;
35const ID_END: u32 = 7;
36
37/// Coefficient count the predictor reads as "first-order difference" rather
38/// than as a filter length.
39const ORDER_ADAPT: u32 = 31;
40
41/// An MSB-first bit reader that reads zeroes past the end of its buffer, so a
42/// 32-bit look-ahead near the last byte of a frame is not an error in itself —
43/// running *out* of frame is caught by the element walk instead.
44struct Bits<'a> {
45 data: &'a [u8],
46 pos: usize,
47}
48
49impl<'a> Bits<'a> {
50 fn new(data: &'a [u8]) -> Bits<'a> {
51 Bits { data, pos: 0 }
52 }
53
54 fn end(&self) -> usize {
55 self.data.len() * 8
56 }
57
58 fn at_end(&self) -> bool {
59 self.pos >= self.end()
60 }
61
62 /// The next 32 bits, zero-padded past the buffer.
63 fn peek32(&self) -> u32 {
64 let byte = self.pos >> 3;
65 let off = (self.pos & 7) as u32;
66 let mut v = 0u64;
67 for i in 0..5 {
68 v = (v << 8) | u64::from(self.data.get(byte + i).copied().unwrap_or(0));
69 }
70 (v >> (8 - off)) as u32
71 }
72
73 fn skip(&mut self, n: usize) -> Result<()> {
74 self.pos = self.pos.saturating_add(n);
75 match self.pos > self.end() {
76 true => Err(Error::NeedMore),
77 false => Ok(()),
78 }
79 }
80
81 fn read(&mut self, n: u32) -> Result<u32> {
82 debug_assert!(n <= 32);
83 if n == 0 {
84 return Ok(0);
85 }
86 if self.pos + n as usize > self.end() {
87 return Err(Error::NeedMore);
88 }
89 let v = self.peek32() >> (32 - n);
90 self.pos += n as usize;
91 Ok(v)
92 }
93
94 fn align(&mut self) {
95 self.pos = self.pos.div_ceil(8) * 8;
96 }
97}
98
99/// `floor(log2(x + 3))`, the Rice parameter the mean maps to.
100fn lg3a(x: u32) -> u32 {
101 31 - (x + 3).leading_zeros()
102}
103
104/// One adaptive-Golomb code: a unary prefix of `pre` (worth `pre * m`) and a
105/// remainder of `k` bits, where remainders 0 and 1 share a `k-1`-bit slot. A
106/// prefix of [`MAX_PREFIX`] ones escapes to a raw `maxbits` value.
107fn golomb(bits: &mut Bits<'_>, m: u32, k: u32, maxbits: u32) -> u32 {
108 let stream = bits.peek32();
109 let pre = (!stream).leading_zeros();
110 if pre >= MAX_PREFIX {
111 // The raw value can be up to 32 bits wide (a 24-bit stereo element
112 // codes 25), so it does not fit in the same 32-bit peek as the
113 // prefix: step past the prefix and peek again.
114 bits.pos += MAX_PREFIX as usize;
115 let raw = match maxbits {
116 0 => 0,
117 n => bits.peek32() >> (32 - n),
118 };
119 bits.pos += maxbits as usize;
120 return raw;
121 }
122 bits.pos += pre as usize + 1;
123 let mut result = pre * m;
124 if k > 1 {
125 let v = (stream << (pre + 1)) >> (32 - k);
126 match v >= 2 {
127 true => {
128 result += v - 1;
129 bits.pos += k as usize;
130 }
131 // Zero and one are coded in `k - 1` bits, so only that many were
132 // consumed and the value is zero.
133 false => bits.pos += (k - 1) as usize,
134 }
135 }
136 result
137}
138
139/// Golomb parameters, kept across a channel's residuals because the mean adapts
140/// sample by sample.
141struct Rice {
142 mean: u32,
143 pb: u32,
144 kb: u32,
145 wb: u32,
146}
147
148impl Rice {
149 fn new(cfg: &MagicCookie, pb_factor: u32) -> Rice {
150 let kb = u32::from(cfg.kb).clamp(1, 31);
151 Rice {
152 mean: u32::from(cfg.mb),
153 pb: u32::from(cfg.pb) * pb_factor / 4,
154 kb,
155 wb: (1 << kb) - 1,
156 }
157 }
158
159 /// `count` residuals into `out`, each already un-zigzagged into a signed
160 /// difference.
161 fn decode(&mut self, bits: &mut Bits<'_>, out: &mut [i32], chan_bits: u32) -> Result<()> {
162 let mut zmode = 0u32;
163 let mut c = 0usize;
164 while c < out.len() {
165 if bits.at_end() {
166 return Err(Error::NeedMore);
167 }
168 let k = lg3a(self.mean >> QBSHIFT).min(self.kb);
169 let m = (1u32 << k) - 1;
170 let n = golomb(bits, m, k, chan_bits);
171
172 // Low bit is the sign: 0, -1, 1, -2, 2, ...
173 let ndecode = n.wrapping_add(zmode);
174 let magnitude = ((ndecode as i64 + 1) >> 1) as i32;
175 out[c] = match ndecode & 1 {
176 0 => magnitude,
177 _ => -magnitude,
178 };
179 c += 1;
180
181 // Wrapping because the reference arithmetic is 32-bit unsigned:
182 // an `n` big enough to overflow it is one the clamp below catches.
183 self.mean = self
184 .pb
185 .wrapping_mul(ndecode)
186 .wrapping_add(self.mean)
187 .wrapping_sub(self.pb.wrapping_mul(self.mean) >> QBSHIFT);
188 if n > MEAN_CLAMP {
189 self.mean = MEAN_CLAMP;
190 }
191
192 zmode = 0;
193 if (self.mean << MMULSHIFT) < QB && c < out.len() {
194 zmode = 1;
195 let k = (self.mean.leading_zeros() as i32 - BITOFF
196 + ((self.mean + MOFF) >> MDENSHIFT) as i32)
197 .clamp(0, 31) as u32;
198 let mz = ((1u32 << k) - 1) & self.wb;
199 let run = run_length(bits, mz, k) as usize;
200 if c + run > out.len() {
201 return Err(Error::corrupt("ALAC: a zero run past the end of the frame"));
202 }
203 out[c..c + run].fill(0);
204 c += run;
205 // A run that hit the escape's ceiling is a run that was cut in
206 // half, and the sample after it is not carrying a borrowed one.
207 if run as u32 >= (1 << MAX_RUN_BITS) - 1 {
208 zmode = 0;
209 }
210 self.mean = 0;
211 }
212 }
213 Ok(())
214 }
215}
216
217/// A zero-run length: the same code as [`golomb`] with a 16-bit escape.
218fn run_length(bits: &mut Bits<'_>, m: u32, k: u32) -> u32 {
219 golomb(bits, m, k, MAX_RUN_BITS)
220}
221
222/// Sign of `x` as -1, 0 or 1.
223fn sign(x: i32) -> i32 {
224 (x > 0) as i32 - (x < 0) as i32
225}
226
227/// The LPC predictor, run backwards: residuals in `res`, samples out, with the
228/// coefficients adapting on the sign of each residual exactly as the encoder's
229/// did. `coefs` is scratch — it is mutated as the block is decoded.
230fn predict(
231 res: &[i32],
232 out: &mut [i32],
233 coefs: &mut [i32],
234 chan_bits: u32,
235 den_shift: u32,
236) -> Result<()> {
237 if res.is_empty() {
238 return Ok(());
239 }
240 let n = res.len();
241 let chan_shift = 32 - chan_bits;
242 let clamp = |v: i32| ((v as u32) << chan_shift) as i32 >> chan_shift;
243 let order = coefs.len();
244 out[0] = res[0];
245
246 if order == 0 {
247 out[..n].copy_from_slice(res);
248 return Ok(());
249 }
250 if order as u32 == ORDER_ADAPT {
251 // Not a filter: a plain first-order difference, which is what the
252 // second predictor pass of a "mode != 0" frame undoes.
253 let mut prev = out[0];
254 for j in 1..n {
255 prev = clamp(res[j].wrapping_add(prev));
256 out[j] = prev;
257 }
258 return Ok(());
259 }
260 if order >= n {
261 // Fewer samples than the filter is long: warm-up is the whole block.
262 for j in 1..n {
263 out[j] = clamp(res[j].wrapping_add(out[j - 1]));
264 }
265 return Ok(());
266 }
267
268 // Warm-up: the first `order` samples are plain first-order differences.
269 for j in 1..=order {
270 out[j] = clamp(res[j].wrapping_add(out[j - 1]));
271 }
272
273 let den_half = match den_shift {
274 0 => 0,
275 s => 1i32 << (s - 1),
276 };
277 for j in order..n - 1 {
278 let top = out[j - order];
279 let mut sum = 0i32;
280 for (k, &c) in coefs.iter().enumerate() {
281 sum = sum.wrapping_add(c.wrapping_mul(out[j - k].wrapping_sub(top)));
282 }
283 let del = res[j + 1];
284 let mut del0 = del;
285 let sg = sign(del);
286 let predicted = top.wrapping_add(sum.wrapping_add(den_half) >> den_shift);
287 out[j + 1] = clamp(del.wrapping_add(predicted));
288
289 // The coefficients walk one step towards whatever would have made this
290 // residual smaller, and stop as soon as they have accounted for it.
291 if sg > 0 {
292 for k in (0..order).rev() {
293 let dd = top.wrapping_sub(out[j - k]);
294 let s = sign(dd);
295 coefs[k] -= s;
296 del0 -= ((order - k) as i32).wrapping_mul((s.wrapping_mul(dd)) >> den_shift);
297 if del0 <= 0 {
298 break;
299 }
300 }
301 } else if sg < 0 {
302 for k in (0..order).rev() {
303 let dd = top.wrapping_sub(out[j - k]);
304 let s = sign(dd);
305 coefs[k] += s;
306 del0 -= ((order - k) as i32).wrapping_mul(((-s).wrapping_mul(dd)) >> den_shift);
307 if del0 >= 0 {
308 break;
309 }
310 }
311 }
312 }
313 Ok(())
314}
315
316/// One channel's coded parameters, read straight out of the frame.
317struct ChannelPlan {
318 mode: u32,
319 den_shift: u32,
320 pb_factor: u32,
321 coefs: Vec<i32>,
322}
323
324fn read_plan(bits: &mut Bits<'_>) -> Result<ChannelPlan> {
325 let mode = bits.read(4)?;
326 let den_shift = bits.read(4)?;
327 let pb_factor = bits.read(3)?;
328 let order = bits.read(5)? as usize;
329 let mut coefs = Vec::with_capacity(order);
330 for _ in 0..order {
331 coefs.push(bits.read(16)? as i16 as i32);
332 }
333 Ok(ChannelPlan {
334 mode,
335 den_shift,
336 pb_factor,
337 coefs,
338 })
339}
340
341/// Scratch buffers, kept between frames so a decode costs no allocation.
342#[derive(Debug, Default)]
343pub(crate) struct Scratch {
344 res: Vec<i32>,
345 mix: [Vec<i32>; 2],
346 tmp: Vec<i32>,
347 shift_uv: Vec<u32>,
348}
349
350/// Decode one ALAC frame into `out`, interleaved in the stream's own channel
351/// order, and answer how many samples per channel it held.
352pub(crate) fn frame(
353 cfg: &MagicCookie,
354 scratch: &mut Scratch,
355 data: &[u8],
356 out: &mut Vec<i32>,
357) -> Result<usize> {
358 let channels = usize::from(cfg.channels.max(1));
359 let mut bits = Bits::new(data);
360 let mut written = 0usize;
361 let mut samples = 0usize;
362 out.clear();
363
364 loop {
365 let tag = bits.read(3)?;
366 match tag {
367 ID_SCE | ID_LFE | ID_CPE => {
368 let pair = tag == ID_CPE;
369 let n = element(cfg, scratch, &mut bits, pair)?;
370 if samples == 0 {
371 samples = n;
372 out.resize(n * channels, 0);
373 } else if n != samples {
374 return Err(Error::corrupt(
375 "ALAC: two elements of one frame disagree on length",
376 ));
377 }
378 let width = 1 + usize::from(pair);
379 if written + width > channels {
380 return Err(Error::corrupt("ALAC: more channels than the cookie states"));
381 }
382 for (i, sample) in out.chunks_exact_mut(channels).enumerate().take(samples) {
383 sample[written] = scratch.mix[0][i];
384 if pair {
385 sample[written + 1] = scratch.mix[1][i];
386 }
387 }
388 written += width;
389 if written >= channels {
390 return Ok(samples);
391 }
392 }
393 // Ancillary elements: skipped by their own stated length.
394 ID_DSE => {
395 bits.skip(4)?;
396 let aligned = bits.read(1)? != 0;
397 let mut count = bits.read(8)?;
398 if count == 255 {
399 count += bits.read(8)?;
400 }
401 if aligned {
402 bits.align();
403 }
404 bits.skip(count as usize * 8)?;
405 }
406 ID_FIL => {
407 let mut count = bits.read(4)?;
408 if count == 15 {
409 count += bits.read(8)? - 1;
410 }
411 bits.skip(count as usize * 8)?;
412 }
413 ID_END => {
414 bits.align();
415 return Ok(samples);
416 }
417 ID_CCE | ID_PCE => {
418 return Err(Error::unsupported(
419 "ALAC coupling and program-config elements",
420 "no ALAC encoder writes them and no file has been seen carrying one",
421 ));
422 }
423 _ => return Err(Error::corrupt(format!("ALAC: element tag {tag}"))),
424 }
425 }
426}
427
428/// One SCE/LFE (mono) or CPE (stereo) element into `scratch.mix`.
429fn element(
430 cfg: &MagicCookie,
431 scratch: &mut Scratch,
432 bits: &mut Bits<'_>,
433 pair: bool,
434) -> Result<usize> {
435 let channels = 1 + usize::from(pair);
436 // A 4-bit element instance tag and 12 reserved bits, zero in every stream
437 // measured here (mono and stereo fixtures from the oracle's encoder, whose
438 // predictor plan starts at bit 39 of the frame — 3 tag + these 16 + the 4
439 // flags + the 16 mix bits below).
440 bits.skip(16)?;
441 let partial = bits.read(1)? != 0;
442 let bytes_shifted = bits.read(2)?;
443 let escape = bits.read(1)? != 0;
444 if bytes_shifted == 3 {
445 return Err(Error::corrupt("ALAC: three shifted bytes"));
446 }
447 let shift = bytes_shifted * 8;
448 let samples = match partial {
449 true => (bits.read(16)? << 16 | bits.read(16)?) as usize,
450 false => cfg.frame_length as usize,
451 };
452 if samples == 0 || samples > MAX_FRAME_SAMPLES {
453 return Err(Error::corrupt(format!("ALAC: a {samples}-sample frame")));
454 }
455 let bit_depth = u32::from(cfg.bit_depth);
456 if !(1..=32).contains(&bit_depth) {
457 return Err(Error::corrupt(format!("ALAC: {bit_depth}-bit samples")));
458 }
459 for buf in &mut scratch.mix {
460 buf.clear();
461 buf.resize(samples, 0);
462 }
463 scratch.shift_uv.clear();
464
465 if escape {
466 // Uncompressed: the samples are in the frame verbatim, channels
467 // interleaved, and nothing was mid/side mixed or shifted.
468 let chan_bits = bit_depth;
469 for i in 0..samples {
470 for c in 0..channels {
471 let raw = bits.read(chan_bits)?;
472 scratch.mix[c][i] = ((raw << (32 - chan_bits)) as i32) >> (32 - chan_bits);
473 }
474 }
475 interleave(scratch, samples, channels, 0, 0, 0);
476 return Ok(samples);
477 }
478
479 // The mid/side pair, stated by a mono element too (as zeroes, where it
480 // means nothing) — measured, not assumed: a mono frame's predictor plan
481 // starts 16 bits after its flags, exactly as a stereo frame's does.
482 let mix_bits = bits.read(8)?;
483 let mix_res = bits.read(8)? as i8 as i32;
484 let mut plans = Vec::with_capacity(channels);
485 for _ in 0..channels {
486 plans.push(read_plan(bits)?);
487 }
488
489 // The low bytes of a 24-bit stream ride uncompressed *ahead* of the
490 // residuals in the bitstream but are read back after them.
491 let shift_at = bits.pos;
492 if shift > 0 {
493 bits.skip(shift as usize * samples * channels)?;
494 }
495
496 let chan_bits = bit_depth - shift + (channels as u32 - 1);
497 if chan_bits == 0 || chan_bits > 32 {
498 return Err(Error::corrupt(format!("ALAC: {chan_bits} coded bits")));
499 }
500 scratch.res.clear();
501 scratch.res.resize(samples, 0);
502 scratch.tmp.clear();
503 scratch.tmp.resize(samples, 0);
504 for (c, plan) in plans.iter_mut().enumerate() {
505 let mut rice = Rice::new(cfg, plan.pb_factor);
506 rice.decode(bits, &mut scratch.res, chan_bits)?;
507 match plan.mode {
508 0 => predict(
509 &scratch.res,
510 &mut scratch.mix[c],
511 &mut plan.coefs,
512 chan_bits,
513 plan.den_shift,
514 )?,
515 // Anything else runs the difference pass first and the filter on
516 // top of it.
517 _ => {
518 predict(
519 &scratch.res,
520 &mut scratch.tmp,
521 &mut vec![0; ORDER_ADAPT as usize],
522 chan_bits,
523 0,
524 )?;
525 let tmp = std::mem::take(&mut scratch.tmp);
526 predict(
527 &tmp,
528 &mut scratch.mix[c],
529 &mut plan.coefs,
530 chan_bits,
531 plan.den_shift,
532 )?;
533 scratch.tmp = tmp;
534 }
535 }
536 }
537
538 if shift > 0 {
539 let mut low = Bits::new(bits.data);
540 low.pos = shift_at;
541 for _ in 0..samples * channels {
542 scratch.shift_uv.push(low.read(shift)?);
543 }
544 }
545 interleave(scratch, samples, channels, shift, mix_bits, mix_res);
546 Ok(samples)
547}
548
549/// Un-mix a decoded element in place: the mid/side pair back into left and
550/// right, and the low bytes of a wide stream back onto every sample.
551fn interleave(
552 scratch: &mut Scratch,
553 samples: usize,
554 channels: usize,
555 shift: u32,
556 mix_bits: u32,
557 mix_res: i32,
558) {
559 let shifted = shift > 0 && scratch.shift_uv.len() >= samples * channels;
560 if channels == 1 {
561 for i in 0..samples {
562 let mut v = scratch.mix[0][i];
563 if shifted {
564 v = (v << shift) | scratch.shift_uv[i] as i32;
565 }
566 scratch.mix[0][i] = v;
567 }
568 return;
569 }
570 for i in 0..samples {
571 let u = scratch.mix[0][i];
572 let v = scratch.mix[1][i];
573 let (mut l, mut r) = match mix_res {
574 0 => (u, v),
575 _ => {
576 let l = u.wrapping_add(v).wrapping_sub((mix_res * v) >> mix_bits);
577 (l, l.wrapping_sub(v))
578 }
579 };
580 if shifted {
581 l = (l << shift) | scratch.shift_uv[2 * i] as i32;
582 r = (r << shift) | scratch.shift_uv[2 * i + 1] as i32;
583 }
584 scratch.mix[0][i] = l;
585 scratch.mix[1][i] = r;
586 }
587}
588
589/// The largest frame this accepts, so a corrupt partial-frame length cannot ask
590/// for an allocation the file could not hold. the reference encoder writes 4096.
591const MAX_FRAME_SAMPLES: usize = 1 << 20;