forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

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