From d60d66b4611daf38926c7f6e0ae3b188d2afbd8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 14:06:13 +0300 Subject: [PATCH] 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.toml | 13 + crates/ec-alac/src/decode.rs | 586 +++++++++++++++++++++++++++++++++ crates/ec-alac/src/lib.rs | 334 +++++++++++++++++++ crates/ec-alac/tests/oracle.rs | 131 ++++++++ 4 files changed, 1064 insertions(+) create mode 100644 crates/ec-alac/Cargo.toml create mode 100644 crates/ec-alac/src/decode.rs create mode 100644 crates/ec-alac/src/lib.rs create mode 100644 crates/ec-alac/tests/oracle.rs diff --git a/crates/ec-alac/Cargo.toml b/crates/ec-alac/Cargo.toml new file mode 100644 index 00000000..e0b30755 --- /dev/null +++ b/crates/ec-alac/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "ec-alac" +description = "Apple Lossless (ALAC) decoder: magic cookie, adaptive-Golomb residuals, LPC predictor, 16 and 24 bit." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core = { workspace = true } + +[dev-dependencies] +ec-mp4 = { workspace = true } diff --git a/crates/ec-alac/src/decode.rs b/crates/ec-alac/src/decode.rs new file mode 100644 index 00000000..f17918b1 --- /dev/null +++ b/crates/ec-alac/src/decode.rs @@ -0,0 +1,586 @@ +//! One ALAC frame: the element walk, the adaptive-Golomb residual decoder, the +//! adapting LPC predictor and the stereo un-mix. +//! +//! Written from the published ALAC format description (element tags and frame +//! header layout, the Golomb/Rice parameter adaptation with its zero-run mode, +//! the sign-adapting predictor and the mid/side un-mix). Nothing here is +//! derived from Apple's decoder sources. + +use crate::MagicCookie; +use ec_core::error::{Error, Result}; + +/// Mean-tracking parameters live in Q9. +const QBSHIFT: u32 = 9; +/// `1 << QBSHIFT`, the point where the mean says "the residuals are all zero". +const QB: u32 = 1 << QBSHIFT; +const MMULSHIFT: u32 = 2; +const MDENSHIFT: u32 = QBSHIFT - MMULSHIFT - 1; +const MOFF: u32 = 1 << (MDENSHIFT - 2); +const BITOFF: i32 = 24; +/// Unary prefixes this long are an escape: the value follows raw. +const MAX_PREFIX: u32 = 9; +/// Width of the raw value after a zero-run escape. +const MAX_RUN_BITS: u32 = 16; +/// A mean this large is clamped rather than allowed to run away. +const MEAN_CLAMP: u32 = 0xffff; + +/// Syntax element tags, three bits at the head of every element. +const ID_SCE: u32 = 0; +const ID_CPE: u32 = 1; +const ID_CCE: u32 = 2; +const ID_LFE: u32 = 3; +const ID_DSE: u32 = 4; +const ID_PCE: u32 = 5; +const ID_FIL: u32 = 6; +const ID_END: u32 = 7; + +/// Coefficient count the predictor reads as "first-order difference" rather +/// than as a filter length. +const ORDER_ADAPT: u32 = 31; + +/// An MSB-first bit reader that reads zeroes past the end of its buffer, so a +/// 32-bit look-ahead near the last byte of a frame is not an error in itself — +/// running *out* of frame is caught by the element walk instead. +struct Bits<'a> { + data: &'a [u8], + pos: usize, +} + +impl<'a> Bits<'a> { + fn new(data: &'a [u8]) -> Bits<'a> { + Bits { data, pos: 0 } + } + + fn end(&self) -> usize { + self.data.len() * 8 + } + + fn at_end(&self) -> bool { + self.pos >= self.end() + } + + /// The next 32 bits, zero-padded past the buffer. + fn peek32(&self) -> u32 { + let byte = self.pos >> 3; + let off = (self.pos & 7) as u32; + let mut v = 0u64; + for i in 0..5 { + v = (v << 8) | u64::from(self.data.get(byte + i).copied().unwrap_or(0)); + } + (v >> (8 - off)) as u32 + } + + fn skip(&mut self, n: usize) -> Result<()> { + self.pos = self.pos.saturating_add(n); + match self.pos > self.end() { + true => Err(Error::NeedMore), + false => Ok(()), + } + } + + fn read(&mut self, n: u32) -> Result { + debug_assert!(n <= 32); + if n == 0 { + return Ok(0); + } + if self.pos + n as usize > self.end() { + return Err(Error::NeedMore); + } + let v = self.peek32() >> (32 - n); + self.pos += n as usize; + Ok(v) + } + + fn align(&mut self) { + self.pos = self.pos.div_ceil(8) * 8; + } +} + +/// `floor(log2(x + 3))`, the Rice parameter the mean maps to. +fn lg3a(x: u32) -> u32 { + 31 - (x + 3).leading_zeros() +} + +/// One adaptive-Golomb code: a unary prefix of `pre` (worth `pre * m`) and a +/// remainder of `k` bits, where remainders 0 and 1 share a `k-1`-bit slot. A +/// prefix of [`MAX_PREFIX`] ones escapes to a raw `maxbits` value. +fn golomb(bits: &mut Bits<'_>, m: u32, k: u32, maxbits: u32) -> u32 { + let stream = bits.peek32(); + let pre = (!stream).leading_zeros(); + if pre >= MAX_PREFIX { + bits.pos += (MAX_PREFIX + maxbits) as usize; + return match maxbits { + 0 => 0, + n => (stream << MAX_PREFIX) >> (32 - n), + }; + } + bits.pos += pre as usize + 1; + let mut result = pre * m; + if k > 1 { + let v = (stream << (pre + 1)) >> (32 - k); + match v >= 2 { + true => { + result += v - 1; + bits.pos += k as usize; + } + // Zero and one are coded in `k - 1` bits, so only that many were + // consumed and the value is zero. + false => bits.pos += (k - 1) as usize, + } + } + result +} + +/// Golomb parameters, kept across a channel's residuals because the mean adapts +/// sample by sample. +struct Rice { + mean: u32, + pb: u32, + kb: u32, + wb: u32, +} + +impl Rice { + fn new(cfg: &MagicCookie, pb_factor: u32) -> Rice { + let kb = u32::from(cfg.kb).clamp(1, 31); + Rice { + mean: u32::from(cfg.mb), + pb: u32::from(cfg.pb) * pb_factor / 4, + kb, + wb: (1 << kb) - 1, + } + } + + /// `count` residuals into `out`, each already un-zigzagged into a signed + /// difference. + fn decode(&mut self, bits: &mut Bits<'_>, out: &mut [i32], chan_bits: u32) -> Result<()> { + let mut zmode = 0u32; + let mut c = 0usize; + while c < out.len() { + if bits.at_end() { + return Err(Error::NeedMore); + } + let k = lg3a(self.mean >> QBSHIFT).min(self.kb); + let m = (1u32 << k) - 1; + let n = golomb(bits, m, k, chan_bits); + + // Low bit is the sign: 0, -1, 1, -2, 2, ... + let ndecode = n.wrapping_add(zmode); + let magnitude = ((ndecode as i64 + 1) >> 1) as i32; + out[c] = match ndecode & 1 { + 0 => magnitude, + _ => -magnitude, + }; + c += 1; + + // Wrapping because the reference arithmetic is 32-bit unsigned: + // an `n` big enough to overflow it is one the clamp below catches. + self.mean = self + .pb + .wrapping_mul(ndecode) + .wrapping_add(self.mean) + .wrapping_sub(self.pb.wrapping_mul(self.mean) >> QBSHIFT); + if n > MEAN_CLAMP { + self.mean = MEAN_CLAMP; + } + + zmode = 0; + if (self.mean << MMULSHIFT) < QB && c < out.len() { + zmode = 1; + let k = (self.mean.leading_zeros() as i32 - BITOFF + + ((self.mean + MOFF) >> MDENSHIFT) as i32) + .clamp(0, 31) as u32; + let mz = ((1u32 << k) - 1) & self.wb; + let run = run_length(bits, mz, k) as usize; + if c + run > out.len() { + return Err(Error::corrupt("ALAC: a zero run past the end of the frame")); + } + out[c..c + run].fill(0); + c += run; + // A run that hit the escape's ceiling is a run that was cut in + // half, and the sample after it is not carrying a borrowed one. + if run as u32 >= (1 << MAX_RUN_BITS) - 1 { + zmode = 0; + } + self.mean = 0; + } + } + Ok(()) + } +} + +/// A zero-run length: the same code as [`golomb`] with a 16-bit escape. +fn run_length(bits: &mut Bits<'_>, m: u32, k: u32) -> u32 { + golomb(bits, m, k, MAX_RUN_BITS) +} + +/// Sign of `x` as -1, 0 or 1. +fn sign(x: i32) -> i32 { + (x > 0) as i32 - (x < 0) as i32 +} + +/// The LPC predictor, run backwards: residuals in `res`, samples out, with the +/// coefficients adapting on the sign of each residual exactly as the encoder's +/// did. `coefs` is scratch — it is mutated as the block is decoded. +fn predict( + res: &[i32], + out: &mut [i32], + coefs: &mut [i32], + chan_bits: u32, + den_shift: u32, +) -> Result<()> { + if res.is_empty() { + return Ok(()); + } + let n = res.len(); + let chan_shift = 32 - chan_bits; + let clamp = |v: i32| ((v as u32) << chan_shift) as i32 >> chan_shift; + let order = coefs.len(); + out[0] = res[0]; + + if order == 0 { + out[..n].copy_from_slice(res); + return Ok(()); + } + if order as u32 == ORDER_ADAPT { + // Not a filter: a plain first-order difference, which is what the + // second predictor pass of a "mode != 0" frame undoes. + let mut prev = out[0]; + for j in 1..n { + prev = clamp(res[j].wrapping_add(prev)); + out[j] = prev; + } + return Ok(()); + } + if order >= n { + // Fewer samples than the filter is long: warm-up is the whole block. + for j in 1..n { + out[j] = clamp(res[j].wrapping_add(out[j - 1])); + } + return Ok(()); + } + + // Warm-up: the first `order` samples are plain first-order differences. + for j in 1..=order { + out[j] = clamp(res[j].wrapping_add(out[j - 1])); + } + + let den_half = match den_shift { + 0 => 0, + s => 1i32 << (s - 1), + }; + for j in order..n - 1 { + let top = out[j - order]; + let mut sum = 0i32; + for (k, &c) in coefs.iter().enumerate() { + sum = sum.wrapping_add(c.wrapping_mul(out[j - k].wrapping_sub(top))); + } + let del = res[j + 1]; + let mut del0 = del; + let sg = sign(del); + let predicted = top.wrapping_add(sum.wrapping_add(den_half) >> den_shift); + out[j + 1] = clamp(del.wrapping_add(predicted)); + + // The coefficients walk one step towards whatever would have made this + // residual smaller, and stop as soon as they have accounted for it. + if sg > 0 { + for k in (0..order).rev() { + let dd = top.wrapping_sub(out[j - k]); + let s = sign(dd); + coefs[k] -= s; + del0 -= ((order - k) as i32).wrapping_mul((s.wrapping_mul(dd)) >> den_shift); + if del0 <= 0 { + break; + } + } + } else if sg < 0 { + for k in (0..order).rev() { + let dd = top.wrapping_sub(out[j - k]); + let s = sign(dd); + coefs[k] += s; + del0 -= ((order - k) as i32).wrapping_mul(((-s).wrapping_mul(dd)) >> den_shift); + if del0 >= 0 { + break; + } + } + } + } + Ok(()) +} + +/// One channel's coded parameters, read straight out of the frame. +struct ChannelPlan { + mode: u32, + den_shift: u32, + pb_factor: u32, + coefs: Vec, +} + +fn read_plan(bits: &mut Bits<'_>) -> Result { + let mode = bits.read(4)?; + let den_shift = bits.read(4)?; + let pb_factor = bits.read(3)?; + let order = bits.read(5)? as usize; + let mut coefs = Vec::with_capacity(order); + for _ in 0..order { + coefs.push(bits.read(16)? as i16 as i32); + } + Ok(ChannelPlan { + mode, + den_shift, + pb_factor, + coefs, + }) +} + +/// Scratch buffers, kept between frames so a decode costs no allocation. +#[derive(Debug, Default)] +pub(crate) struct Scratch { + res: Vec, + mix: [Vec; 2], + tmp: Vec, + shift_uv: Vec, +} + +/// Decode one ALAC frame into `out`, interleaved in the stream's own channel +/// order, and answer how many samples per channel it held. +pub(crate) fn frame( + cfg: &MagicCookie, + scratch: &mut Scratch, + data: &[u8], + out: &mut Vec, +) -> Result { + let channels = usize::from(cfg.channels.max(1)); + let mut bits = Bits::new(data); + let mut written = 0usize; + let mut samples = 0usize; + out.clear(); + + loop { + let tag = bits.read(3)?; + match tag { + ID_SCE | ID_LFE | ID_CPE => { + let pair = tag == ID_CPE; + let n = element(cfg, scratch, &mut bits, pair)?; + if samples == 0 { + samples = n; + out.resize(n * channels, 0); + } else if n != samples { + return Err(Error::corrupt( + "ALAC: two elements of one frame disagree on length", + )); + } + let width = 1 + usize::from(pair); + if written + width > channels { + return Err(Error::corrupt("ALAC: more channels than the cookie states")); + } + for (i, sample) in out.chunks_exact_mut(channels).enumerate().take(samples) { + sample[written] = scratch.mix[0][i]; + if pair { + sample[written + 1] = scratch.mix[1][i]; + } + } + written += width; + if written >= channels { + return Ok(samples); + } + } + // Ancillary elements: skipped by their own stated length. + ID_DSE => { + bits.skip(4)?; + let aligned = bits.read(1)? != 0; + let mut count = bits.read(8)?; + if count == 255 { + count += bits.read(8)?; + } + if aligned { + bits.align(); + } + bits.skip(count as usize * 8)?; + } + ID_FIL => { + let mut count = bits.read(4)?; + if count == 15 { + count += bits.read(8)? - 1; + } + bits.skip(count as usize * 8)?; + } + ID_END => { + bits.align(); + return Ok(samples); + } + ID_CCE | ID_PCE => { + return Err(Error::unsupported( + "ALAC coupling and program-config elements", + "no ALAC encoder writes them and no file has been seen carrying one", + )); + } + _ => return Err(Error::corrupt(format!("ALAC: element tag {tag}"))), + } + } +} + +/// One SCE/LFE (mono) or CPE (stereo) element into `scratch.mix`. +fn element( + cfg: &MagicCookie, + scratch: &mut Scratch, + bits: &mut Bits<'_>, + pair: bool, +) -> Result { + let channels = 1 + usize::from(pair); + // A 4-bit element instance tag and 12 reserved bits, zero in every stream + // measured here (mono and stereo fixtures from ffmpeg's encoder, whose + // predictor plan starts at bit 39 of the frame — 3 tag + these 16 + the 4 + // flags + the 16 mix bits below). + bits.skip(16)?; + let partial = bits.read(1)? != 0; + let bytes_shifted = bits.read(2)?; + let escape = bits.read(1)? != 0; + if bytes_shifted == 3 { + return Err(Error::corrupt("ALAC: three shifted bytes")); + } + let shift = bytes_shifted * 8; + let samples = match partial { + true => (bits.read(16)? << 16 | bits.read(16)?) as usize, + false => cfg.frame_length as usize, + }; + if samples == 0 || samples > MAX_FRAME_SAMPLES { + return Err(Error::corrupt(format!("ALAC: a {samples}-sample frame"))); + } + let bit_depth = u32::from(cfg.bit_depth); + if !(1..=32).contains(&bit_depth) { + return Err(Error::corrupt(format!("ALAC: {bit_depth}-bit samples"))); + } + for buf in &mut scratch.mix { + buf.clear(); + buf.resize(samples, 0); + } + scratch.shift_uv.clear(); + + if escape { + // Uncompressed: the samples are in the frame verbatim, channels + // interleaved, and nothing was mid/side mixed or shifted. + let chan_bits = bit_depth; + for i in 0..samples { + for c in 0..channels { + let raw = bits.read(chan_bits)?; + scratch.mix[c][i] = ((raw << (32 - chan_bits)) as i32) >> (32 - chan_bits); + } + } + interleave(scratch, samples, channels, 0, 0, 0); + return Ok(samples); + } + + // The mid/side pair, stated by a mono element too (as zeroes, where it + // means nothing) — measured, not assumed: a mono frame's predictor plan + // starts 16 bits after its flags, exactly as a stereo frame's does. + let mix_bits = bits.read(8)?; + let mix_res = bits.read(8)? as i8 as i32; + let mut plans = Vec::with_capacity(channels); + for _ in 0..channels { + plans.push(read_plan(bits)?); + } + + // The low bytes of a 24-bit stream ride uncompressed *ahead* of the + // residuals in the bitstream but are read back after them. + let shift_at = bits.pos; + if shift > 0 { + bits.skip(shift as usize * samples * channels)?; + } + + let chan_bits = bit_depth - shift + (channels as u32 - 1); + if chan_bits == 0 || chan_bits > 32 { + return Err(Error::corrupt(format!("ALAC: {chan_bits} coded bits"))); + } + scratch.res.clear(); + scratch.res.resize(samples, 0); + scratch.tmp.clear(); + scratch.tmp.resize(samples, 0); + for (c, plan) in plans.iter_mut().enumerate() { + let mut rice = Rice::new(cfg, plan.pb_factor); + rice.decode(bits, &mut scratch.res, chan_bits)?; + match plan.mode { + 0 => predict( + &scratch.res, + &mut scratch.mix[c], + &mut plan.coefs, + chan_bits, + plan.den_shift, + )?, + // Anything else runs the difference pass first and the filter on + // top of it. + _ => { + predict( + &scratch.res, + &mut scratch.tmp, + &mut vec![0; ORDER_ADAPT as usize], + chan_bits, + 0, + )?; + let tmp = std::mem::take(&mut scratch.tmp); + predict( + &tmp, + &mut scratch.mix[c], + &mut plan.coefs, + chan_bits, + plan.den_shift, + )?; + scratch.tmp = tmp; + } + } + } + + if shift > 0 { + let mut low = Bits::new(bits.data); + low.pos = shift_at; + for _ in 0..samples * channels { + scratch.shift_uv.push(low.read(shift)?); + } + } + interleave(scratch, samples, channels, shift, mix_bits, mix_res); + Ok(samples) +} + +/// Un-mix a decoded element in place: the mid/side pair back into left and +/// right, and the low bytes of a wide stream back onto every sample. +fn interleave( + scratch: &mut Scratch, + samples: usize, + channels: usize, + shift: u32, + mix_bits: u32, + mix_res: i32, +) { + let shifted = shift > 0 && scratch.shift_uv.len() >= samples * channels; + if channels == 1 { + for i in 0..samples { + let mut v = scratch.mix[0][i]; + if shifted { + v = (v << shift) | scratch.shift_uv[i] as i32; + } + scratch.mix[0][i] = v; + } + return; + } + for i in 0..samples { + let u = scratch.mix[0][i]; + let v = scratch.mix[1][i]; + let (mut l, mut r) = match mix_res { + 0 => (u, v), + _ => { + let l = u.wrapping_add(v).wrapping_sub((mix_res * v) >> mix_bits); + (l, l.wrapping_sub(v)) + } + }; + if shifted { + l = (l << shift) | scratch.shift_uv[2 * i] as i32; + r = (r << shift) | scratch.shift_uv[2 * i + 1] as i32; + } + scratch.mix[0][i] = l; + scratch.mix[1][i] = r; + } +} + +/// The largest frame this accepts, so a corrupt partial-frame length cannot ask +/// for an allocation the file could not hold. Apple's encoder writes 4096. +const MAX_FRAME_SAMPLES: usize = 1 << 20; diff --git a/crates/ec-alac/src/lib.rs b/crates/ec-alac/src/lib.rs new file mode 100644 index 00000000..7118dcab --- /dev/null +++ b/crates/ec-alac/src/lib.rs @@ -0,0 +1,334 @@ +//! Apple Lossless (ALAC) decoding for the edith_codecs family. +//! +//! Two ways in: +//! +//! - [`AlacDecoder::decode`], one coded frame in, interleaved samples out, in +//! the layout order the rest of the family uses (FL, FR, FC, LFE, BL, BR for +//! 5.1 — the stream's own order is centre-first). +//! - [`AlacDecoder`] as an [`ec_core::Decoder`], for a container that hands out +//! one ALAC frame per packet, which is how mp4 and Matroska deliver them. +//! +//! The stream describes itself in a *magic cookie* ([`MagicCookie`]) that every +//! container carries as extradata: the frame length, the bit depth and the +//! three Golomb constants the residual coder adapts from. +//! +//! Decode only — edith never writes ALAC, so there is no encoder here and no +//! pretending otherwise. +//! +//! **Clean room.** Written from the published ALAC format description; Apple's +//! decoder sources were not read. Samples are returned shifted into their PCM +//! container the way ffmpeg's decoder returns them (16-bit as `s16`, 24-bit as +//! `s32` with the low 8 bits zero), so raw output compares byte for byte. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod decode; + +use ec_core::error::{Error, Result}; +use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; +use ec_core::packet::{Buf, Packet}; +use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters}; + +/// The `ALACSpecificConfig` every ALAC stream is introduced by: 24 bytes, +/// big-endian, carried as the body of an `alac` box in mp4 and as `CodecPrivate` +/// in Matroska. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MagicCookie { + /// Samples per channel in a full frame (4096 from Apple's encoder). A + /// stream's last frame states its own shorter length. + pub frame_length: u32, + /// Bitstream version the file is compatible with; 0 is the only one. + pub compatible_version: u8, + /// Bits per sample: 16, 20, 24 or 32. + pub bit_depth: u8, + /// Golomb mean update rate. + pub pb: u8, + /// Initial Golomb mean. + pub mb: u8, + /// Ceiling on the Rice parameter. + pub kb: u8, + /// Channels the stream carries. + pub channels: u8, + /// Longest zero run the encoder emits. + pub max_run: u16, + /// Largest coded frame in bytes, `0` when the encoder did not say. + pub max_frame_bytes: u32, + /// Nominal bit rate, `0` when the encoder did not say. + pub avg_bit_rate: u32, + /// Sample rate in Hz. + pub sample_rate: u32, +} + +impl MagicCookie { + /// Parse a cookie from the bytes a container carries. + /// + /// Accepts the three shapes those bytes arrive in: the bare 24-byte config, + /// the config behind a four-byte version/flags word, and the whole `alac` + /// box with its size and type in front (which is what ffmpeg and this + /// family's own mp4 demuxer hand over). + pub fn parse(data: &[u8]) -> Result { + let at = match data { + [_, _, _, _, b'a', b'l', b'a', b'c', ..] if data.len() >= 36 => 12, + _ if data.len() >= 28 && Self::at(data, 0).is_err() => 4, + _ => 0, + }; + Self::at(data, at) + } + + fn at(data: &[u8], at: usize) -> Result { + let c = data + .get(at..at + 24) + .ok_or_else(|| Error::corrupt("ALAC: a magic cookie shorter than 24 bytes"))?; + let be32 = |i: usize| u32::from_be_bytes([c[i], c[i + 1], c[i + 2], c[i + 3]]); + let cookie = MagicCookie { + frame_length: be32(0), + compatible_version: c[4], + bit_depth: c[5], + pb: c[6], + mb: c[7], + kb: c[8], + channels: c[9], + max_run: u16::from_be_bytes([c[10], c[11]]), + max_frame_bytes: be32(12), + avg_bit_rate: be32(16), + sample_rate: be32(20), + }; + // The three fields a decoder cannot proceed on, checked here so a + // mis-sliced cookie is caught at open rather than as garbled audio. + if !(1..=1 << 20).contains(&cookie.frame_length) { + return Err(Error::corrupt(format!( + "ALAC: a {}-sample frame length", + cookie.frame_length + ))); + } + if !(1..=32).contains(&cookie.bit_depth) { + return Err(Error::corrupt(format!( + "ALAC: {}-bit samples", + cookie.bit_depth + ))); + } + if !(1..=8).contains(&cookie.channels) { + return Err(Error::corrupt(format!( + "ALAC: {} channels", + cookie.channels + ))); + } + Ok(cookie) + } + + /// Bits the decoded samples are shifted left by to fill their PCM + /// container, matching [`MagicCookie::sample_format`]. + pub fn container_shift(&self) -> u32 { + match u32::from(self.bit_depth) <= 16 { + true => 16 - u32::from(self.bit_depth), + false => 32 - u32::from(self.bit_depth), + } + } + + /// The sample format decoded audio is delivered in. + pub fn sample_format(&self) -> SampleFormat { + match self.bit_depth <= 16 { + true => SampleFormat::S16, + false => SampleFormat::S32, + } + } +} + +/// Where each output channel sits in the stream's own coded order. +/// +/// ALAC codes centre first (C, L, R, Ls, Rs, LFE for 5.1) because its elements +/// are AAC's; every consumer in this family wants film order (FL, FR, FC, LFE, +/// BL, BR), so the map is applied once, on the way out. +fn film_order(channels: usize) -> &'static [usize] { + match channels { + 3 => &[1, 2, 0], + 4 => &[1, 2, 0, 3], + 5 => &[1, 2, 0, 3, 4], + 6 => &[1, 2, 0, 5, 3, 4], + 7 => &[1, 2, 0, 6, 5, 3, 4], + 8 => &[3, 4, 0, 7, 5, 6, 1, 2], + // Mono and stereo are already in it. + _ => &[0, 1], + } +} + +/// An ALAC decoder for one stream. +#[derive(Debug)] +pub struct AlacDecoder { + cookie: MagicCookie, + params: CodecParameters, + scratch: decode::Scratch, + coded: Vec, + out: Vec, + pending: Option, + drained: bool, +} + +impl AlacDecoder { + /// A decoder for a stream described by `cookie`. + pub fn new(cookie: MagicCookie) -> AlacDecoder { + AlacDecoder { + params: codec_parameters(&cookie), + cookie, + scratch: decode::Scratch::default(), + coded: Vec::new(), + out: Vec::new(), + pending: None, + drained: false, + } + } + + /// A decoder for a stream whose `extradata` is its magic cookie, which is + /// how every container states one. + pub fn from_parameters(params: CodecParameters) -> Result { + let cookie = MagicCookie::parse(params.extradata.as_deref().ok_or_else(|| { + Error::corrupt("ALAC: a track with no magic cookie in its extradata") + })?)?; + let mut decoder = AlacDecoder::new(cookie); + decoder.params.extradata = params.extradata; + Ok(decoder) + } + + /// What the stream said about itself. + pub fn cookie(&self) -> &MagicCookie { + &self.cookie + } + + /// One coded frame in, interleaved samples out in film order, already + /// shifted into their PCM container. + /// + /// The slice is valid until the next call; a caller that keeps it copies. + pub fn decode(&mut self, data: &[u8]) -> Result<&[i32]> { + let channels = usize::from(self.cookie.channels.max(1)); + let samples = decode::frame(&self.cookie, &mut self.scratch, data, &mut self.coded)?; + let shift = self.cookie.container_shift(); + let map = film_order(channels); + self.out.clear(); + self.out.reserve(samples * channels); + for frame in self.coded.chunks_exact(channels).take(samples) { + for &src in &map[..channels] { + self.out.push(frame[src] << shift); + } + } + Ok(&self.out) + } +} + +impl Decoder for AlacDecoder { + fn codec_parameters(&self) -> &CodecParameters { + &self.params + } + + fn send_packet(&mut self, packet: &Packet) -> Result<()> { + self.decode(&packet.data)?; + let channels = usize::from(self.cookie.channels.max(1)); + let format = self.cookie.sample_format(); + let mut bytes = Vec::with_capacity(self.out.len() * format.bytes_per_sample()); + for &s in &self.out { + match format { + SampleFormat::S16 => bytes.extend_from_slice(&(s as i16).to_ne_bytes()), + _ => bytes.extend_from_slice(&s.to_ne_bytes()), + } + } + let mut frame = AudioFrame::try_new( + format, + false, + ChannelLayout::from_count(channels), + self.cookie.sample_rate, + self.out.len() / channels, + vec![Buf::from_vec(bytes)], + )?; + frame.pts = packet + .pts + .map(|ticks| ec_core::timebase::Timestamp::new(ticks, packet.time_base)); + self.pending = Some(frame); + Ok(()) + } + + fn receive_frame(&mut self) -> Result { + match self.pending.take() { + Some(frame) => Ok(Frame::Audio(frame)), + None if self.drained => Err(Error::Eof), + None => Err(Error::NeedMore), + } + } + + fn flush(&mut self) -> Result<()> { + self.drained = true; + Ok(()) + } + + fn reset(&mut self) { + self.pending = None; + self.drained = false; + } +} + +/// Codec parameters for the stream a cookie describes. +pub fn codec_parameters(cookie: &MagicCookie) -> CodecParameters { + let mut params = CodecParameters::new(CodecId::Alac); + params.media = MediaParameters::Audio(AudioParameters { + sample_rate: cookie.sample_rate, + layout: ChannelLayout::from_count(usize::from(cookie.channels.max(1))), + format: Some(cookie.sample_format()), + bits_per_sample: Some(u32::from(cookie.bit_depth)), + }); + params +} + +#[cfg(test)] +mod tests { + use super::*; + + /// ffmpeg's 36-byte `alac` box, a bare 24-byte config and the 28-byte form + /// in between all describe the same stream. + #[test] + fn a_magic_cookie_is_read_in_every_shape_a_container_states_it() { + let config: [u8; 24] = [ + 0, 0, 0x10, 0, // frameLength 4096 + 0, 16, // version 0, 16-bit + 40, 10, 14, // pb, mb, kb + 2, // channels + 0, 255, // maxRun + 0, 0, 0x10, 0, // maxFrameBytes + 0, 0, 0, 0, // avgBitRate + 0, 0, 0xAC, 0x44, // 44100 + ]; + let bare = MagicCookie::parse(&config).expect("bare config"); + assert_eq!(bare.frame_length, 4096); + assert_eq!(bare.bit_depth, 16); + assert_eq!(bare.channels, 2); + assert_eq!(bare.sample_rate, 44100); + assert_eq!(bare.pb, 40); + assert_eq!(bare.mb, 10); + assert_eq!(bare.kb, 14); + + let mut boxed = vec![0, 0, 0, 36, b'a', b'l', b'a', b'c', 0, 0, 0, 0]; + boxed.extend_from_slice(&config); + assert_eq!(MagicCookie::parse(&boxed).expect("boxed"), bare); + + let mut versioned = vec![0, 0, 0, 0]; + versioned.extend_from_slice(&config); + assert_eq!(MagicCookie::parse(&versioned).expect("versioned"), bare); + + // A refusal that names what it refused, rather than decoding noise. + assert!(MagicCookie::parse(&config[..12]).is_err()); + } + + /// The layout map is a permutation for every width, which is the property + /// that keeps a channel from being dropped or doubled on the way out. + #[test] + fn film_order_is_a_permutation_at_every_width() { + for channels in 1..=8usize { + let map = film_order(channels); + let mut seen: Vec = map[..channels].to_vec(); + seen.sort_unstable(); + seen.dedup(); + assert_eq!(seen.len(), channels, "{channels} channels"); + assert!(seen.iter().all(|&c| c < channels), "{channels} channels"); + } + // 5.1: the stream's centre channel is coded first and lands third. + assert_eq!(film_order(6), &[1, 2, 0, 5, 3, 4]); + } +} diff --git a/crates/ec-alac/tests/oracle.rs b/crates/ec-alac/tests/oracle.rs new file mode 100644 index 00000000..88482493 --- /dev/null +++ b/crates/ec-alac/tests/oracle.rs @@ -0,0 +1,131 @@ +//! ALAC is lossless, so the oracle is exact: every fixture must decode to the +//! same bytes ffmpeg's decoder produces, sample for sample, in the same channel +//! order. +//! +//! Fixtures come from `scripts/gen-fixtures.sh`; a missing one skips its row +//! rather than failing, so a checkout without generated fixtures still builds. + +use std::fs::File; +use std::io::BufReader; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_alac::{AlacDecoder, MagicCookie}; +use ec_core::registry::{CodecId, Demuxer}; + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") +} + +/// Every sample of `path`'s ALAC track, interleaved, as this crate decodes it. +fn decode(path: &Path) -> (MagicCookie, Vec) { + let mut demuxer = + ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(path).expect("open"))).expect("mp4"); + let stream = demuxer + .streams() + .iter() + .find(|s| s.params.codec == CodecId::Alac) + .expect("an ALAC track") + .clone(); + let mut decoder = AlacDecoder::from_parameters(stream.params.clone()).expect("cookie"); + let cookie = *decoder.cookie(); + let mut out = Vec::new(); + loop { + match demuxer.next_packet() { + Ok(packet) if packet.stream != stream.index => continue, + Ok(packet) => out.extend_from_slice(decoder.decode(&packet.data).expect("decode")), + Err(e) if e.is_eof() => break, + Err(e) => panic!("{}: {e}", path.display()), + } + } + (cookie, out) +} + +/// ffmpeg's own decode of the same file, in the raw format `fmt` names. +fn ffmpeg(path: &Path, fmt: &str) -> Vec { + let out = Command::new("ffmpeg") + .args(["-nostdin", "-v", "error", "-i"]) + .arg(path) + .args(["-f", fmt, "-"]) + .output() + .expect("ffmpeg"); + assert!( + out.status.success(), + "ffmpeg {}: {}", + path.display(), + String::from_utf8_lossy(&out.stderr) + ); + out.stdout +} + +#[test] +fn every_alac_fixture_decodes_bit_exactly() { + let mut checked = 0; + for name in [ + "alac-mp4-mono-44100.m4a", + "alac-mp4-mono-48000.m4a", + "alac-mp4-stereo-44100.m4a", + "alac-mp4-stereo-48000.m4a", + "alac-mp4-5.1-44100.m4a", + "alac-mp4-5.1-48000.m4a", + "alac24-mp4-stereo-48000.m4a", + "alac24-mp4-5.1-48000.m4a", + ] { + let path = fixtures().join(name); + if !path.exists() { + continue; + } + let (cookie, got) = decode(&path); + let (fmt, width) = match cookie.bit_depth <= 16 { + true => ("s16le", 2), + false => ("s32le", 4), + }; + let want = ffmpeg(&path, fmt); + assert_eq!( + got.len(), + want.len() / width, + "{name}: {} samples decoded, ffmpeg says {}", + got.len(), + want.len() / width + ); + let mine: Vec = got + .iter() + .flat_map(|&s| match width { + 2 => (s as i16).to_le_bytes().to_vec(), + _ => s.to_le_bytes().to_vec(), + }) + .collect(); + let bad = mine + .chunks_exact(width) + .zip(want.chunks_exact(width)) + .position(|(a, b)| a != b); + assert_eq!(bad, None, "{name}: first differing sample"); + checked += 1; + } + assert!(checked > 0, "no ALAC fixtures found — run gen-fixtures.sh"); + eprintln!("alac oracle: {checked} fixtures bit-exact vs ffmpeg"); +} + +/// A truncated frame is an error, not a panic — the fuzz floor in miniature. +#[test] +fn truncated_frames_are_refused_without_panicking() { + let path = fixtures().join("alac-mp4-stereo-44100.m4a"); + if !path.exists() { + return; + } + let mut demuxer = + ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&path).expect("open"))).expect("mp4"); + let stream = demuxer.streams()[0].clone(); + let mut decoder = AlacDecoder::from_parameters(stream.params).expect("cookie"); + let packet = demuxer.next_packet().expect("a packet"); + for len in 0..packet.data.len().min(64) { + let _ = decoder.decode(&packet.data[..len]); + } + // And it still decodes the whole frame afterwards. + assert!( + !decoder + .decode(&packet.data) + .expect("whole frame") + .is_empty() + ); +}