forge
Explore
Log in

Don't you dare go Hollow

ALAC decoder, bit-exact against ffmpeg on 16 and 24 bit

Browse files at this commit

d60d66b4611daf38926c7f6e0ae3b188d2afbd8aAhmet Kaan GümüşParent: 5a58bb1
  • feat
    • ALAC decoder, bit-exact against ffmpeg on 16 and 24 bit
Show full message
feat(alac): ALAC decoder, bit-exact against ffmpeg on 16 and 24 bit

Clean-room from the published ALAC format description: magic cookie in
all three shapes a container states it, adaptive-Golomb residuals with
the zero-run mode, the sign-adapting LPC predictor, the mid/side un-mix
and the shifted low bytes of a 24-bit stream. Decode only.

Two things the format description does not spell out were measured
against ffmpeg's own encoder output and are commented where they are
used: a channel element's predictor plan starts 39 bits into the frame
(the mix pair is stated by a mono element too), and the predictor's
history window is out[j-k], not out[j-1-k].

Oracle: 8 fixtures (mono/stereo/5.1, 44.1 and 48 kHz, 16 and 24 bit)
decode byte-for-byte identical to ffmpeg's decoder.
crates/ec-alac/Cargo.tomladded+13 -0
@@ -0,0 +1,13 @@
1+[package]
2+name = "ec-alac"
3+description = "Apple Lossless (ALAC) decoder: magic cookie, adaptive-Golomb residuals, LPC predictor, 16 and 24 bit."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core = { workspace = true }
11+
12+[dev-dependencies]
13+ec-mp4 = { workspace = true }
crates/ec-alac/src/decode.rsadded+586 -0
@@ -0,0 +1,586 @@
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+
9+use crate::MagicCookie;
10+use ec_core::error::{Error, Result};
11+
12+/// Mean-tracking parameters live in Q9.
13+const QBSHIFT: u32 = 9;
14+/// `1 << QBSHIFT`, the point where the mean says "the residuals are all zero".
15+const QB: u32 = 1 << QBSHIFT;
16+const MMULSHIFT: u32 = 2;
17+const MDENSHIFT: u32 = QBSHIFT - MMULSHIFT - 1;
18+const MOFF: u32 = 1 << (MDENSHIFT - 2);
19+const BITOFF: i32 = 24;
20+/// Unary prefixes this long are an escape: the value follows raw.
21+const MAX_PREFIX: u32 = 9;
22+/// Width of the raw value after a zero-run escape.
23+const MAX_RUN_BITS: u32 = 16;
24+/// A mean this large is clamped rather than allowed to run away.
25+const MEAN_CLAMP: u32 = 0xffff;
26+
27+/// Syntax element tags, three bits at the head of every element.
28+const ID_SCE: u32 = 0;
29+const ID_CPE: u32 = 1;
30+const ID_CCE: u32 = 2;
31+const ID_LFE: u32 = 3;
32+const ID_DSE: u32 = 4;
33+const ID_PCE: u32 = 5;
34+const ID_FIL: u32 = 6;
35+const ID_END: u32 = 7;
36+
37+/// Coefficient count the predictor reads as "first-order difference" rather
38+/// than as a filter length.
39+const 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.
44+struct Bits<'a> {
45+ data: &'a [u8],
46+ pos: usize,
47+}
48+
49+impl<'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.
100+fn 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.
107+fn 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.
136+struct Rice {
137+ mean: u32,
138+ pb: u32,
139+ kb: u32,
140+ wb: u32,
141+}
142+
143+impl 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.
213+fn 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.
218+fn 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.
225+fn 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.
312+struct ChannelPlan {
313+ mode: u32,
314+ den_shift: u32,
315+ pb_factor: u32,
316+ coefs: Vec<i32>,
317+}
318+
319+fn 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)]
338+pub(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.
347+pub(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`.
424+fn 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.
546+fn 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.
586+const MAX_FRAME_SAMPLES: usize = 1 << 20;
crates/ec-alac/src/lib.rsadded+334 -0
@@ -0,0 +1,334 @@
1+//! Apple Lossless (ALAC) decoding for the edith_codecs family.
2+//!
3+//! Two ways in:
4+//!
5+//! - [`AlacDecoder::decode`], one coded frame in, interleaved samples out, in
6+//! the layout order the rest of the family uses (FL, FR, FC, LFE, BL, BR for
7+//! 5.1 — the stream's own order is centre-first).
8+//! - [`AlacDecoder`] as an [`ec_core::Decoder`], for a container that hands out
9+//! one ALAC frame per packet, which is how mp4 and Matroska deliver them.
10+//!
11+//! The stream describes itself in a *magic cookie* ([`MagicCookie`]) that every
12+//! container carries as extradata: the frame length, the bit depth and the
13+//! three Golomb constants the residual coder adapts from.
14+//!
15+//! Decode only — edith never writes ALAC, so there is no encoder here and no
16+//! pretending otherwise.
17+//!
18+//! **Clean room.** Written from the published ALAC format description; Apple's
19+//! decoder sources were not read. Samples are returned shifted into their PCM
20+//! container the way ffmpeg's decoder returns them (16-bit as `s16`, 24-bit as
21+//! `s32` with the low 8 bits zero), so raw output compares byte for byte.
22+
23+#![forbid(unsafe_code)]
24+#![warn(missing_docs)]
25+
26+mod decode;
27+
28+use ec_core::error::{Error, Result};
29+use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat};
30+use ec_core::packet::{Buf, Packet};
31+use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters};
32+
33+/// The `ALACSpecificConfig` every ALAC stream is introduced by: 24 bytes,
34+/// big-endian, carried as the body of an `alac` box in mp4 and as `CodecPrivate`
35+/// in Matroska.
36+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37+pub struct MagicCookie {
38+ /// Samples per channel in a full frame (4096 from Apple's encoder). A
39+ /// stream's last frame states its own shorter length.
40+ pub frame_length: u32,
41+ /// Bitstream version the file is compatible with; 0 is the only one.
42+ pub compatible_version: u8,
43+ /// Bits per sample: 16, 20, 24 or 32.
44+ pub bit_depth: u8,
45+ /// Golomb mean update rate.
46+ pub pb: u8,
47+ /// Initial Golomb mean.
48+ pub mb: u8,
49+ /// Ceiling on the Rice parameter.
50+ pub kb: u8,
51+ /// Channels the stream carries.
52+ pub channels: u8,
53+ /// Longest zero run the encoder emits.
54+ pub max_run: u16,
55+ /// Largest coded frame in bytes, `0` when the encoder did not say.
56+ pub max_frame_bytes: u32,
57+ /// Nominal bit rate, `0` when the encoder did not say.
58+ pub avg_bit_rate: u32,
59+ /// Sample rate in Hz.
60+ pub sample_rate: u32,
61+}
62+
63+impl MagicCookie {
64+ /// Parse a cookie from the bytes a container carries.
65+ ///
66+ /// Accepts the three shapes those bytes arrive in: the bare 24-byte config,
67+ /// the config behind a four-byte version/flags word, and the whole `alac`
68+ /// box with its size and type in front (which is what ffmpeg and this
69+ /// family's own mp4 demuxer hand over).
70+ pub fn parse(data: &[u8]) -> Result<MagicCookie> {
71+ let at = match data {
72+ [_, _, _, _, b'a', b'l', b'a', b'c', ..] if data.len() >= 36 => 12,
73+ _ if data.len() >= 28 && Self::at(data, 0).is_err() => 4,
74+ _ => 0,
75+ };
76+ Self::at(data, at)
77+ }
78+
79+ fn at(data: &[u8], at: usize) -> Result<MagicCookie> {
80+ let c = data
81+ .get(at..at + 24)
82+ .ok_or_else(|| Error::corrupt("ALAC: a magic cookie shorter than 24 bytes"))?;
83+ let be32 = |i: usize| u32::from_be_bytes([c[i], c[i + 1], c[i + 2], c[i + 3]]);
84+ let cookie = MagicCookie {
85+ frame_length: be32(0),
86+ compatible_version: c[4],
87+ bit_depth: c[5],
88+ pb: c[6],
89+ mb: c[7],
90+ kb: c[8],
91+ channels: c[9],
92+ max_run: u16::from_be_bytes([c[10], c[11]]),
93+ max_frame_bytes: be32(12),
94+ avg_bit_rate: be32(16),
95+ sample_rate: be32(20),
96+ };
97+ // The three fields a decoder cannot proceed on, checked here so a
98+ // mis-sliced cookie is caught at open rather than as garbled audio.
99+ if !(1..=1 << 20).contains(&cookie.frame_length) {
100+ return Err(Error::corrupt(format!(
101+ "ALAC: a {}-sample frame length",
102+ cookie.frame_length
103+ )));
104+ }
105+ if !(1..=32).contains(&cookie.bit_depth) {
106+ return Err(Error::corrupt(format!(
107+ "ALAC: {}-bit samples",
108+ cookie.bit_depth
109+ )));
110+ }
111+ if !(1..=8).contains(&cookie.channels) {
112+ return Err(Error::corrupt(format!(
113+ "ALAC: {} channels",
114+ cookie.channels
115+ )));
116+ }
117+ Ok(cookie)
118+ }
119+
120+ /// Bits the decoded samples are shifted left by to fill their PCM
121+ /// container, matching [`MagicCookie::sample_format`].
122+ pub fn container_shift(&self) -> u32 {
123+ match u32::from(self.bit_depth) <= 16 {
124+ true => 16 - u32::from(self.bit_depth),
125+ false => 32 - u32::from(self.bit_depth),
126+ }
127+ }
128+
129+ /// The sample format decoded audio is delivered in.
130+ pub fn sample_format(&self) -> SampleFormat {
131+ match self.bit_depth <= 16 {
132+ true => SampleFormat::S16,
133+ false => SampleFormat::S32,
134+ }
135+ }
136+}
137+
138+/// Where each output channel sits in the stream's own coded order.
139+///
140+/// ALAC codes centre first (C, L, R, Ls, Rs, LFE for 5.1) because its elements
141+/// are AAC's; every consumer in this family wants film order (FL, FR, FC, LFE,
142+/// BL, BR), so the map is applied once, on the way out.
143+fn film_order(channels: usize) -> &'static [usize] {
144+ match channels {
145+ 3 => &[1, 2, 0],
146+ 4 => &[1, 2, 0, 3],
147+ 5 => &[1, 2, 0, 3, 4],
148+ 6 => &[1, 2, 0, 5, 3, 4],
149+ 7 => &[1, 2, 0, 6, 5, 3, 4],
150+ 8 => &[3, 4, 0, 7, 5, 6, 1, 2],
151+ // Mono and stereo are already in it.
152+ _ => &[0, 1],
153+ }
154+}
155+
156+/// An ALAC decoder for one stream.
157+#[derive(Debug)]
158+pub struct AlacDecoder {
159+ cookie: MagicCookie,
160+ params: CodecParameters,
161+ scratch: decode::Scratch,
162+ coded: Vec<i32>,
163+ out: Vec<i32>,
164+ pending: Option<AudioFrame>,
165+ drained: bool,
166+}
167+
168+impl AlacDecoder {
169+ /// A decoder for a stream described by `cookie`.
170+ pub fn new(cookie: MagicCookie) -> AlacDecoder {
171+ AlacDecoder {
172+ params: codec_parameters(&cookie),
173+ cookie,
174+ scratch: decode::Scratch::default(),
175+ coded: Vec::new(),
176+ out: Vec::new(),
177+ pending: None,
178+ drained: false,
179+ }
180+ }
181+
182+ /// A decoder for a stream whose `extradata` is its magic cookie, which is
183+ /// how every container states one.
184+ pub fn from_parameters(params: CodecParameters) -> Result<AlacDecoder> {
185+ let cookie = MagicCookie::parse(params.extradata.as_deref().ok_or_else(|| {
186+ Error::corrupt("ALAC: a track with no magic cookie in its extradata")
187+ })?)?;
188+ let mut decoder = AlacDecoder::new(cookie);
189+ decoder.params.extradata = params.extradata;
190+ Ok(decoder)
191+ }
192+
193+ /// What the stream said about itself.
194+ pub fn cookie(&self) -> &MagicCookie {
195+ &self.cookie
196+ }
197+
198+ /// One coded frame in, interleaved samples out in film order, already
199+ /// shifted into their PCM container.
200+ ///
201+ /// The slice is valid until the next call; a caller that keeps it copies.
202+ pub fn decode(&mut self, data: &[u8]) -> Result<&[i32]> {
203+ let channels = usize::from(self.cookie.channels.max(1));
204+ let samples = decode::frame(&self.cookie, &mut self.scratch, data, &mut self.coded)?;
205+ let shift = self.cookie.container_shift();
206+ let map = film_order(channels);
207+ self.out.clear();
208+ self.out.reserve(samples * channels);
209+ for frame in self.coded.chunks_exact(channels).take(samples) {
210+ for &src in &map[..channels] {
211+ self.out.push(frame[src] << shift);
212+ }
213+ }
214+ Ok(&self.out)
215+ }
216+}
217+
218+impl Decoder for AlacDecoder {
219+ fn codec_parameters(&self) -> &CodecParameters {
220+ &self.params
221+ }
222+
223+ fn send_packet(&mut self, packet: &Packet) -> Result<()> {
224+ self.decode(&packet.data)?;
225+ let channels = usize::from(self.cookie.channels.max(1));
226+ let format = self.cookie.sample_format();
227+ let mut bytes = Vec::with_capacity(self.out.len() * format.bytes_per_sample());
228+ for &s in &self.out {
229+ match format {
230+ SampleFormat::S16 => bytes.extend_from_slice(&(s as i16).to_ne_bytes()),
231+ _ => bytes.extend_from_slice(&s.to_ne_bytes()),
232+ }
233+ }
234+ let mut frame = AudioFrame::try_new(
235+ format,
236+ false,
237+ ChannelLayout::from_count(channels),
238+ self.cookie.sample_rate,
239+ self.out.len() / channels,
240+ vec![Buf::from_vec(bytes)],
241+ )?;
242+ frame.pts = packet
243+ .pts
244+ .map(|ticks| ec_core::timebase::Timestamp::new(ticks, packet.time_base));
245+ self.pending = Some(frame);
246+ Ok(())
247+ }
248+
249+ fn receive_frame(&mut self) -> Result<Frame> {
250+ match self.pending.take() {
251+ Some(frame) => Ok(Frame::Audio(frame)),
252+ None if self.drained => Err(Error::Eof),
253+ None => Err(Error::NeedMore),
254+ }
255+ }
256+
257+ fn flush(&mut self) -> Result<()> {
258+ self.drained = true;
259+ Ok(())
260+ }
261+
262+ fn reset(&mut self) {
263+ self.pending = None;
264+ self.drained = false;
265+ }
266+}
267+
268+/// Codec parameters for the stream a cookie describes.
269+pub fn codec_parameters(cookie: &MagicCookie) -> CodecParameters {
270+ let mut params = CodecParameters::new(CodecId::Alac);
271+ params.media = MediaParameters::Audio(AudioParameters {
272+ sample_rate: cookie.sample_rate,
273+ layout: ChannelLayout::from_count(usize::from(cookie.channels.max(1))),
274+ format: Some(cookie.sample_format()),
275+ bits_per_sample: Some(u32::from(cookie.bit_depth)),
276+ });
277+ params
278+}
279+
280+#[cfg(test)]
281+mod tests {
282+ use super::*;
283+
284+ /// ffmpeg's 36-byte `alac` box, a bare 24-byte config and the 28-byte form
285+ /// in between all describe the same stream.
286+ #[test]
287+ fn a_magic_cookie_is_read_in_every_shape_a_container_states_it() {
288+ let config: [u8; 24] = [
289+ 0, 0, 0x10, 0, // frameLength 4096
290+ 0, 16, // version 0, 16-bit
291+ 40, 10, 14, // pb, mb, kb
292+ 2, // channels
293+ 0, 255, // maxRun
294+ 0, 0, 0x10, 0, // maxFrameBytes
295+ 0, 0, 0, 0, // avgBitRate
296+ 0, 0, 0xAC, 0x44, // 44100
297+ ];
298+ let bare = MagicCookie::parse(&config).expect("bare config");
299+ assert_eq!(bare.frame_length, 4096);
300+ assert_eq!(bare.bit_depth, 16);
301+ assert_eq!(bare.channels, 2);
302+ assert_eq!(bare.sample_rate, 44100);
303+ assert_eq!(bare.pb, 40);
304+ assert_eq!(bare.mb, 10);
305+ assert_eq!(bare.kb, 14);
306+
307+ let mut boxed = vec![0, 0, 0, 36, b'a', b'l', b'a', b'c', 0, 0, 0, 0];
308+ boxed.extend_from_slice(&config);
309+ assert_eq!(MagicCookie::parse(&boxed).expect("boxed"), bare);
310+
311+ let mut versioned = vec![0, 0, 0, 0];
312+ versioned.extend_from_slice(&config);
313+ assert_eq!(MagicCookie::parse(&versioned).expect("versioned"), bare);
314+
315+ // A refusal that names what it refused, rather than decoding noise.
316+ assert!(MagicCookie::parse(&config[..12]).is_err());
317+ }
318+
319+ /// The layout map is a permutation for every width, which is the property
320+ /// that keeps a channel from being dropped or doubled on the way out.
321+ #[test]
322+ fn film_order_is_a_permutation_at_every_width() {
323+ for channels in 1..=8usize {
324+ let map = film_order(channels);
325+ let mut seen: Vec<usize> = map[..channels].to_vec();
326+ seen.sort_unstable();
327+ seen.dedup();
328+ assert_eq!(seen.len(), channels, "{channels} channels");
329+ assert!(seen.iter().all(|&c| c < channels), "{channels} channels");
330+ }
331+ // 5.1: the stream's centre channel is coded first and lands third.
332+ assert_eq!(film_order(6), &[1, 2, 0, 5, 3, 4]);
333+ }
334+}
crates/ec-alac/tests/oracle.rsadded+131 -0
@@ -0,0 +1,131 @@
1+//! ALAC is lossless, so the oracle is exact: every fixture must decode to the
2+//! same bytes ffmpeg's decoder produces, sample for sample, in the same channel
3+//! order.
4+//!
5+//! Fixtures come from `scripts/gen-fixtures.sh`; a missing one skips its row
6+//! rather than failing, so a checkout without generated fixtures still builds.
7+
8+use std::fs::File;
9+use std::io::BufReader;
10+use std::path::{Path, PathBuf};
11+use std::process::Command;
12+
13+use ec_alac::{AlacDecoder, MagicCookie};
14+use ec_core::registry::{CodecId, Demuxer};
15+
16+fn fixtures() -> PathBuf {
17+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
18+}
19+
20+/// Every sample of `path`'s ALAC track, interleaved, as this crate decodes it.
21+fn decode(path: &Path) -> (MagicCookie, Vec<i32>) {
22+ let mut demuxer =
23+ ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mp4");
24+ let stream = demuxer
25+ .streams()
26+ .iter()
27+ .find(|s| s.params.codec == CodecId::Alac)
28+ .expect("an ALAC track")
29+ .clone();
30+ let mut decoder = AlacDecoder::from_parameters(stream.params.clone()).expect("cookie");
31+ let cookie = *decoder.cookie();
32+ let mut out = Vec::new();
33+ loop {
34+ match demuxer.next_packet() {
35+ Ok(packet) if packet.stream != stream.index => continue,
36+ Ok(packet) => out.extend_from_slice(decoder.decode(&packet.data).expect("decode")),
37+ Err(e) if e.is_eof() => break,
38+ Err(e) => panic!("{}: {e}", path.display()),
39+ }
40+ }
41+ (cookie, out)
42+}
43+
44+/// ffmpeg's own decode of the same file, in the raw format `fmt` names.
45+fn ffmpeg(path: &Path, fmt: &str) -> Vec<u8> {
46+ let out = Command::new("ffmpeg")
47+ .args(["-nostdin", "-v", "error", "-i"])
48+ .arg(path)
49+ .args(["-f", fmt, "-"])
50+ .output()
51+ .expect("ffmpeg");
52+ assert!(
53+ out.status.success(),
54+ "ffmpeg {}: {}",
55+ path.display(),
56+ String::from_utf8_lossy(&out.stderr)
57+ );
58+ out.stdout
59+}
60+
61+#[test]
62+fn every_alac_fixture_decodes_bit_exactly() {
63+ let mut checked = 0;
64+ for name in [
65+ "alac-mp4-mono-44100.m4a",
66+ "alac-mp4-mono-48000.m4a",
67+ "alac-mp4-stereo-44100.m4a",
68+ "alac-mp4-stereo-48000.m4a",
69+ "alac-mp4-5.1-44100.m4a",
70+ "alac-mp4-5.1-48000.m4a",
71+ "alac24-mp4-stereo-48000.m4a",
72+ "alac24-mp4-5.1-48000.m4a",
73+ ] {
74+ let path = fixtures().join(name);
75+ if !path.exists() {
76+ continue;
77+ }
78+ let (cookie, got) = decode(&path);
79+ let (fmt, width) = match cookie.bit_depth <= 16 {
80+ true => ("s16le", 2),
81+ false => ("s32le", 4),
82+ };
83+ let want = ffmpeg(&path, fmt);
84+ assert_eq!(
85+ got.len(),
86+ want.len() / width,
87+ "{name}: {} samples decoded, ffmpeg says {}",
88+ got.len(),
89+ want.len() / width
90+ );
91+ let mine: Vec<u8> = got
92+ .iter()
93+ .flat_map(|&s| match width {
94+ 2 => (s as i16).to_le_bytes().to_vec(),
95+ _ => s.to_le_bytes().to_vec(),
96+ })
97+ .collect();
98+ let bad = mine
99+ .chunks_exact(width)
100+ .zip(want.chunks_exact(width))
101+ .position(|(a, b)| a != b);
102+ assert_eq!(bad, None, "{name}: first differing sample");
103+ checked += 1;
104+ }
105+ assert!(checked > 0, "no ALAC fixtures found — run gen-fixtures.sh");
106+ eprintln!("alac oracle: {checked} fixtures bit-exact vs ffmpeg");
107+}
108+
109+/// A truncated frame is an error, not a panic — the fuzz floor in miniature.
110+#[test]
111+fn truncated_frames_are_refused_without_panicking() {
112+ let path = fixtures().join("alac-mp4-stereo-44100.m4a");
113+ if !path.exists() {
114+ return;
115+ }
116+ let mut demuxer =
117+ ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&path).expect("open"))).expect("mp4");
118+ let stream = demuxer.streams()[0].clone();
119+ let mut decoder = AlacDecoder::from_parameters(stream.params).expect("cookie");
120+ let packet = demuxer.next_packet().expect("a packet");
121+ for len in 0..packet.data.len().min(64) {
122+ let _ = decoder.decode(&packet.data[..len]);
123+ }
124+ // And it still decodes the whole frame afterwards.
125+ assert!(
126+ !decoder
127+ .decode(&packet.data)
128+ .expect("whole frame")
129+ .is_empty()
130+ );
131+}