Skip to main content

rff_codec_alac/
lib.rs

1//! Apple Lossless (ALAC) audio decoder.
2//!
3//! Decodes ALAC packets (one frame each, as MP4, CAF and Matroska store them)
4//! from the 24-byte `ALACSpecificConfig` magic cookie given as extradata. Bit
5//! depths 16, 20, 24 and 32, 1 to 8 channels. Output is interleaved: s16 for
6//! 16-bit streams, f32 for deeper ones (exact for 20 and 24 bits).
7//!
8//! The arithmetic follows FFmpeg's `alac.c` (adaptive Golomb-Rice residuals,
9//! the adaptive FIR predictor, stereo decorrelation, shifted low bytes), and
10//! channels are reordered from ALAC's layout (C L R ...) to the WAV/FFmpeg
11//! order (L R C LFE ...) the same way.
12//!
13//! A malformed frame is an error for that packet only; the decoder keeps no
14//! state between frames, so the next packet decodes normally.
15
16use rff_codec::{Codec, CodecParams, CodecRegistry, Decoder};
17use rff_core::{AudioFrame, CodecId, Error, Frame, MediaType, Packet, Result, SampleFormat};
18
19/// Register the ALAC decoder into a [`CodecRegistry`].
20pub fn register(registry: &mut CodecRegistry) {
21    registry.register(Codec {
22        id: CodecId::Alac,
23        name: "alac",
24        long_name: "ALAC (Apple Lossless Audio Codec)",
25        media_type: MediaType::Audio,
26        decoder: Some(|| Box::new(AlacDecoder::default())),
27        encoder: None,
28    });
29}
30
31/// The fields of `ALACSpecificConfig` the decoder uses.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub struct AlacConfig {
34    /// Samples per channel in a full frame.
35    pub frame_length: u32,
36    pub bit_depth: u8,
37    /// Rice history multiplier (`pb`, 40 by default).
38    pub pb: u8,
39    /// Initial Rice history (`mb`, 10 by default).
40    pub mb: u8,
41    /// Rice parameter limit (`kb`, 14 by default).
42    pub kb: u8,
43    pub channels: u8,
44    pub sample_rate: u32,
45}
46
47impl AlacConfig {
48    /// Parse the 24-byte config at `b`.
49    fn at(b: &[u8]) -> Option<AlacConfig> {
50        if b.len() < 24 {
51            return None;
52        }
53        let c = AlacConfig {
54            frame_length: u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
55            bit_depth: b[5],
56            pb: b[6],
57            mb: b[7],
58            kb: b[8],
59            channels: b[9],
60            sample_rate: u32::from_be_bytes([b[20], b[21], b[22], b[23]]),
61        };
62        let ok = matches!(c.bit_depth, 16 | 20 | 24 | 32)
63            && (1..=8).contains(&c.channels)
64            && (1..=1 << 20).contains(&c.frame_length)
65            && (1..=32).contains(&c.kb);
66        ok.then_some(c)
67    }
68
69    /// Find the config in a magic cookie, whichever wrapping it arrives in:
70    /// the bare 24 bytes (MP4 `alac` box payload, Matroska CodecPrivate,
71    /// many CAF `kuki`s), the full 36-byte `alac` atom (FFmpeg extradata),
72    /// or a CAF cookie that opens with a `frma` atom before the `alac` atom.
73    pub fn from_cookie(cookie: &[u8]) -> Option<AlacConfig> {
74        // An `alac` atom anywhere in the first few atoms: size, 'alac',
75        // version/flags, then the config.
76        let mut i = 0;
77        while i + 12 <= cookie.len() && i < 64 {
78            if &cookie[i + 4..i + 8] == b"alac" {
79                if let Some(c) = cookie.get(i + 12..).and_then(AlacConfig::at) {
80                    return Some(c);
81                }
82            }
83            let size = u32::from_be_bytes([cookie[i], cookie[i + 1], cookie[i + 2], cookie[i + 3]])
84                as usize;
85            if size < 8 {
86                break;
87            }
88            i += size;
89        }
90        AlacConfig::at(cookie).or_else(|| cookie.get(4..).and_then(AlacConfig::at))
91    }
92}
93
94/// ALAC channel order -> output order (FFmpeg's
95/// `ff_alac_channel_layout_offsets`): element `ch` of a `channels`-channel
96/// stream lands at output index `OFFSETS[channels - 1][ch]`.
97const OFFSETS: [[u8; 8]; 8] = [
98    [0, 0, 0, 0, 0, 0, 0, 0],
99    [0, 1, 0, 0, 0, 0, 0, 0],
100    [2, 0, 1, 0, 0, 0, 0, 0],
101    [2, 0, 1, 3, 0, 0, 0, 0],
102    [2, 0, 1, 3, 4, 0, 0, 0],
103    [2, 0, 1, 4, 5, 3, 0, 0],
104    [2, 0, 1, 4, 5, 6, 3, 0],
105    [2, 6, 7, 0, 1, 4, 5, 3],
106];
107
108/// MSB-first bit reader over a packet. Reads are served from one unaligned
109/// big-endian 64-bit load at the current byte, so any read of up to 32 bits
110/// is a load, a shift and a mask rather than a walk over bytes. Past the end
111/// of the packet it reads zeros.
112struct Bits<'a> {
113    data: &'a [u8],
114    pos: usize, // in bits
115}
116
117impl<'a> Bits<'a> {
118    fn new(data: &'a [u8]) -> Bits<'a> {
119        Bits { data, pos: 0 }
120    }
121
122    fn left(&self) -> isize {
123        (self.data.len() * 8) as isize - self.pos as isize
124    }
125
126    /// The next 57 or more bits, MSB-aligned (zeros past the end).
127    #[inline(always)]
128    fn window(&self) -> u64 {
129        let at = self.pos >> 3;
130        let word = match self.data.get(at..at + 8) {
131            Some(w) => u64::from_be_bytes(w.try_into().unwrap()),
132            None => self.window_tail(at),
133        };
134        word << (self.pos & 7)
135    }
136
137    /// `window` within 8 bytes of the end, zero-padded.
138    #[cold]
139    #[inline(never)]
140    fn window_tail(&self, at: usize) -> u64 {
141        let mut w = [0u8; 8];
142        if let Some(rest) = self.data.get(at..) {
143            w[..rest.len()].copy_from_slice(rest);
144        }
145        u64::from_be_bytes(w)
146    }
147
148    /// The next `n` (0..=32) bits without consuming them.
149    #[inline(always)]
150    fn peek(&self, n: u32) -> u32 {
151        if n == 0 {
152            return 0;
153        }
154        (self.window() >> (64 - n)) as u32
155    }
156
157    /// Read `n` (0..=32) bits; past the end reads zeros.
158    #[inline(always)]
159    fn read(&mut self, n: u32) -> u32 {
160        let v = self.peek(n);
161        self.pos += n as usize;
162        v
163    }
164
165    #[inline(always)]
166    fn skip(&mut self, n: u32) {
167        self.pos += n as usize;
168    }
169
170    fn sbits(&mut self, n: u32) -> i32 {
171        sign_extend(self.read(n) as i32, n)
172    }
173}
174
175/// Sign-extend the low `bits` (0..=32) bits of `v`. Every caller passes a
176/// width in that range (a sample size, a coded width, 16). There is no
177/// test: at 0 and 32 the shift is 0 and `v` comes back unchanged.
178#[inline(always)]
179fn sign_extend(v: i32, bits: u32) -> i32 {
180    debug_assert!(bits <= 32);
181    let s = 32u32.wrapping_sub(bits) & 31;
182    (v << s) >> s
183}
184
185/// One adaptive Golomb-Rice value (FFmpeg's `decode_scalar`): a unary prefix
186/// of at most 9, then either `bps` raw bits (prefix 9) or `k` bits of
187/// remainder. `k` is at least 1 for every caller. Everything but the escape
188/// comes from one window load. Inlined, since it runs once per residual:
189/// as a call it cost 8-11% more instructions over the whole decode.
190#[inline(always)]
191fn decode_scalar(b: &mut Bits, k: u32, bps: u32) -> u32 {
192    let w = b.window();
193    let x = (!w).leading_zeros().min(9);
194    if x > 8 {
195        b.skip(9);
196        return b.read(bps);
197    }
198    if k == 1 {
199        b.skip(x + 1);
200        return x;
201    }
202    // The remainder starts after the prefix and its 0; x + 1 + k <= 9 + 32
203    // bits, inside the window's 57.
204    let extra = ((w << (x + 1)) >> (64 - k)) as u32;
205    let base = (x << k).wrapping_sub(x);
206    if extra > 1 {
207        b.skip(x + 1 + k);
208        base.wrapping_add(extra - 1)
209    } else {
210        b.skip(x + k);
211        base
212    }
213}
214
215fn log2(v: u32) -> u32 {
216    if v == 0 {
217        0
218    } else {
219        31 - v.leading_zeros()
220    }
221}
222
223/// Adaptive Golomb-Rice residuals (FFmpeg's `rice_decompress`).
224fn rice_decompress(
225    b: &mut Bits,
226    out: &mut [i32],
227    bps: u32,
228    history_mult: u32,
229    initial_history: u32,
230    limit: u32,
231) -> Result<()> {
232    let n = out.len();
233    let mut history = initial_history;
234    let mut sign_modifier = 0u32;
235    let mut i = 0;
236    while i < n {
237        if b.left() <= 0 {
238            return Err(Error::invalid("alac: residuals run past the packet"));
239        }
240        let k = log2((history >> 9) + 3).min(limit);
241        let x = decode_scalar(b, k, bps).wrapping_add(sign_modifier);
242        sign_modifier = 0;
243        out[i] = ((x >> 1) as i32) ^ -((x & 1) as i32);
244        if x > 0xffff {
245            history = 0xffff;
246        } else {
247            history = history
248                .wrapping_add(x.wrapping_mul(history_mult))
249                .wrapping_sub(history.wrapping_mul(history_mult) >> 9);
250        }
251        if history < 128 && i + 1 < n {
252            let k = (7 - log2(history) + ((history + 16) >> 6)).min(limit);
253            let block = decode_scalar(b, k, 16) as usize;
254            if block > 0 {
255                if block >= n - i {
256                    return Err(Error::invalid("alac: zero run past the frame"));
257                }
258                out[i + 1..i + 1 + block].fill(0);
259                i += block;
260            }
261            if block <= 0xffff {
262                sign_modifier = 1;
263            }
264            history = 0;
265        }
266        i += 1;
267    }
268    Ok(())
269}
270
271fn sign_only(v: i32) -> i32 {
272    v.signum()
273}
274
275/// The adaptive FIR predictor (FFmpeg's `lpc_prediction`). `coefs` holds the
276/// coefficients in stream order reversed (index `order - 1` was read first),
277/// and is adapted in place. `order == 31` is the fixed first-order mode.
278fn lpc_prediction(
279    err: &[i32],
280    out: &mut [i32],
281    bps: u32,
282    coefs: &mut [i16],
283    order: usize,
284    quant: u32,
285) {
286    let n = err.len();
287    if n == 0 {
288        return;
289    }
290    out[0] = err[0];
291    if n <= 1 {
292        return;
293    }
294    if order == 0 {
295        out[1..n].copy_from_slice(&err[1..n]);
296        return;
297    }
298    if order == 31 {
299        for i in 1..n {
300            out[i] = sign_extend(out[i - 1].wrapping_add(err[i]), bps);
301        }
302        return;
303    }
304    let mut i = 1;
305    while i <= order && i < n {
306        out[i] = sign_extend(out[i - 1].wrapping_add(err[i]), bps);
307        i += 1;
308    }
309    if i >= n {
310        return;
311    }
312    // The common encoder orders get their own copies of the loop, so the
313    // per-sample dot product and adaptation run over a known length.
314    match order {
315        4 => lpc_fixed::<4>(err, out, bps, &mut coefs[..4], quant),
316        8 => lpc_fixed::<8>(err, out, bps, &mut coefs[..8], quant),
317        _ => lpc_adaptive(err, out, bps, &mut coefs[..order], order, quant),
318    }
319}
320
321/// First-order prediction in place: each sample is the previous one plus
322/// its residual.
323fn first_order(buf: &mut [i32], bps: u32) {
324    let Some((first, rest)) = buf.split_first_mut() else {
325        return;
326    };
327    let mut prev = *first;
328    for v in rest {
329        prev = sign_extend(prev.wrapping_add(*v), bps);
330        *v = prev;
331    }
332}
333
334/// `lpc_adaptive` for a fixed order, with the coefficients and the last `N`
335/// outputs held in local arrays for the whole frame. Every sample writes
336/// both (the new output, the adapted coefficients) and the next sample reads
337/// them all back; through memory those reads wait on the stores just made,
338/// and in registers they do not. Same arithmetic, same results.
339#[inline(always)]
340fn lpc_fixed<const N: usize>(
341    err: &[i32],
342    out: &mut [i32],
343    bps: u32,
344    coefs: &mut [i16],
345    quant: u32,
346) {
347    let n = err.len().min(out.len());
348    if n <= N + 1 {
349        return;
350    }
351    let round = 1i64 << (quant - 1);
352    let mut c: [i16; N] = coefs[..N].try_into().unwrap();
353    // `d` is out[i - N - 1]; `past[j]` is out[i - N + j].
354    let mut d = out[0];
355    let mut past: [i32; N] = out[1..=N].try_into().unwrap();
356    for (o, &e) in out[N + 1..n].iter_mut().zip(&err[N + 1..n]) {
357        let mut val: i32 = 0;
358        for j in 0..N {
359            val = val.wrapping_add(past[j].wrapping_sub(d).wrapping_mul(i32::from(c[j])));
360        }
361        let rounded = ((i64::from(val) + round) >> quant) as i32;
362        let y = sign_extend(rounded.wrapping_add(d).wrapping_add(e), bps);
363        *o = y;
364        // The adaptation, split by the residual's sign so each loop's stop
365        // test is a plain compare (the shape symphonia uses). The test runs
366        // after each step, which is the same as before the next one, since
367        // it holds on entry.
368        let mut error_val = e;
369        if e > 0 {
370            for j in 0..N {
371                let v = d.wrapping_sub(past[j]);
372                let sign = sign_only(v);
373                c[j] = c[j].wrapping_sub(sign as i16);
374                error_val = error_val
375                    .wrapping_sub((v.wrapping_mul(sign) >> quant).wrapping_mul(j as i32 + 1));
376                if error_val <= 0 {
377                    break;
378                }
379            }
380        } else if e.wrapping_neg() > 0 {
381            // (Written as a negation, like the original `error * sign > 0`
382            // test, so i32::MIN stops it exactly as there.)
383            for j in 0..N {
384                let v = d.wrapping_sub(past[j]);
385                let sign = sign_only(v);
386                c[j] = c[j].wrapping_add(sign as i16);
387                error_val = error_val
388                    .wrapping_sub((v.wrapping_mul(-sign) >> quant).wrapping_mul(j as i32 + 1));
389                if error_val.wrapping_neg() <= 0 {
390                    break;
391                }
392            }
393        }
394        d = past[0];
395        past.copy_within(1.., 0);
396        past[N - 1] = y;
397    }
398    coefs[..N].copy_from_slice(&c);
399}
400
401/// The adaptive part of `lpc_prediction`, from sample `order + 1` on.
402#[inline(always)]
403fn lpc_adaptive(
404    err: &[i32],
405    out: &mut [i32],
406    bps: u32,
407    coefs: &mut [i16],
408    order: usize,
409    quant: u32,
410) {
411    let n = err.len().min(out.len());
412    let round = 1i64 << (quant - 1);
413    for i in order + 1..n {
414        // `win[0]` is d = out[i - order - 1]; `win[1 + j]` pairs with coefs[j].
415        let (head, tail) = out.split_at_mut(i);
416        let win = &head[i - order - 1..];
417        let d = win[0];
418        let past = &win[1..=order];
419        let val = past.iter().zip(coefs.iter()).fold(0i32, |acc, (&o, &c)| {
420            acc.wrapping_add(o.wrapping_sub(d).wrapping_mul(i32::from(c)))
421        });
422        let rounded = ((i64::from(val) + round) >> quant) as i32;
423        let mut error_val = err[i] as u32;
424        tail[0] = sign_extend(rounded.wrapping_add(d).wrapping_add(error_val as i32), bps);
425        let error_sign = sign_only(error_val as i32);
426        if error_sign != 0 {
427            for (j, (&o, c)) in past.iter().zip(coefs.iter_mut()).enumerate() {
428                if (error_val.wrapping_mul(error_sign as u32) as i32) <= 0 {
429                    break;
430                }
431                let v = d.wrapping_sub(o);
432                let sign = sign_only(v) * error_sign;
433                *c = c.wrapping_sub(sign as i16);
434                error_val = error_val.wrapping_sub(
435                    ((v.wrapping_mul(sign) >> quant) as u32).wrapping_mul(j as u32 + 1),
436                );
437            }
438        }
439    }
440}
441
442/// Decode one ALAC frame into per-channel buffers (output order). Returns
443/// the samples per channel.
444fn decode_frame(
445    cfg: &AlacConfig,
446    data: &[u8],
447    out: &mut [Vec<i32>],
448    extra_buf: &mut Vec<u32>,
449    residual: &mut Vec<i32>,
450) -> Result<usize> {
451    let channels = cfg.channels as usize;
452    let mut b = Bits::new(data);
453    let mut ch = 0usize;
454    let mut nb_samples: Option<usize> = None;
455    // Stop once every channel has decoded: bytes after that (damage, or an
456    // encoder's padding) are not read as more elements.
457    while ch < channels && b.left() >= 3 {
458        let element = b.read(3);
459        if element == 7 {
460            break; // END
461        }
462        // SCE 0, CPE 1, LFE 3. CCE/DSE/PCE/FIL are not used by ALAC encoders.
463        if !matches!(element, 0 | 1 | 3) {
464            return Err(Error::unsupported(format!("alac: element type {element}")));
465        }
466        let elem_ch = if element == 1 { 2 } else { 1 };
467        if ch + elem_ch > channels || OFFSETS[channels - 1][ch] as usize + elem_ch > channels {
468            return Err(Error::invalid("alac: more channel elements than channels"));
469        }
470        let at = OFFSETS[channels - 1][ch] as usize;
471        let n = decode_element(
472            cfg,
473            &mut b,
474            elem_ch,
475            nb_samples,
476            &mut out[at..at + elem_ch],
477            extra_buf,
478            residual,
479        )?;
480        nb_samples = Some(n);
481        ch += elem_ch;
482    }
483    if ch < channels {
484        return Err(Error::invalid("alac: frame ends before every channel"));
485    }
486    Ok(nb_samples.unwrap_or(0))
487}
488
489fn decode_element(
490    cfg: &AlacConfig,
491    b: &mut Bits,
492    channels: usize,
493    expected: Option<usize>,
494    out: &mut [Vec<i32>],
495    extra_buf: &mut Vec<u32>,
496    residual: &mut Vec<i32>,
497) -> Result<usize> {
498    b.skip(4); // element instance tag
499    b.skip(12); // unused
500    let has_size = b.read(1) == 1;
501    let extra_bits = b.read(2) * 8;
502    let sample_size = cfg.bit_depth as u32;
503    let bps = (sample_size + channels as u32 - 1)
504        .checked_sub(extra_bits)
505        .filter(|&v| (1..=32).contains(&v))
506        .ok_or_else(|| Error::invalid("alac: bad shifted-byte count"))?;
507    let is_compressed = b.read(1) == 0;
508    let n = if has_size {
509        b.read(32) as usize
510    } else {
511        cfg.frame_length as usize
512    };
513    if n == 0 || n > cfg.frame_length as usize {
514        return Err(Error::invalid(format!("alac: {n} samples in a frame")));
515    }
516    if expected.is_some_and(|e| e != n) {
517        return Err(Error::invalid("alac: elements disagree on the frame size"));
518    }
519    // Every path below writes all `n` samples of each channel, so a buffer
520    // only needs the right length, not zeroing.
521    for o in out.iter_mut() {
522        o.resize(n, 0);
523    }
524    let mut decorr_shift = 0u32;
525    let mut decorr_left_weight = 0i32;
526    let mut extra = 0u32;
527    if is_compressed {
528        decorr_shift = b.read(8);
529        decorr_left_weight = b.read(8) as i32;
530        if channels == 2 && decorr_left_weight != 0 && decorr_shift > 31 {
531            return Err(Error::invalid("alac: decorrelation shift past 31"));
532        }
533        let mut pred_type = [0u32; 2];
534        let mut quant = [0u32; 2];
535        let mut hist_mult = [0u32; 2];
536        let mut order = [0usize; 2];
537        let mut coefs = [[0i16; 32]; 2];
538        for c in 0..channels {
539            pred_type[c] = b.read(4);
540            quant[c] = b.read(4);
541            hist_mult[c] = b.read(3);
542            order[c] = b.read(5) as usize;
543            if order[c] >= n || quant[c] == 0 {
544                return Err(Error::invalid("alac: bad predictor"));
545            }
546            for i in (0..order[c]).rev() {
547                coefs[c][i] = b.sbits(16) as i16;
548            }
549        }
550        extra = extra_bits;
551        if extra > 0 {
552            if b.left() < (n * channels * extra as usize) as isize {
553                return Err(Error::invalid("alac: shifted bytes run past the packet"));
554            }
555            // Stored sample-major, channel-minor, as they are read.
556            extra_buf.clear();
557            extra_buf.extend((0..n * channels).map(|_| b.read(extra)));
558        }
559        residual.resize(n, 0);
560        for c in 0..channels {
561            let buf = &mut residual[..n];
562            rice_decompress(
563                b,
564                buf,
565                bps,
566                hist_mult[c] * cfg.pb as u32 / 4,
567                cfg.mb as u32,
568                cfg.kb as u32,
569            )?;
570            if pred_type[c] == 15 {
571                first_order(buf, bps);
572            }
573            lpc_prediction(buf, &mut out[c], bps, &mut coefs[c], order[c], quant[c]);
574        }
575    } else {
576        for i in 0..n {
577            for o in out.iter_mut() {
578                o[i] = b.sbits(sample_size);
579            }
580        }
581    }
582    if channels == 2 && decorr_left_weight != 0 {
583        let (l, r) = out.split_at_mut(1);
584        for i in 0..n {
585            let mut a = l[0][i];
586            let mut bb = r[0][i];
587            a = a.wrapping_sub(bb.wrapping_mul(decorr_left_weight) >> decorr_shift);
588            bb = bb.wrapping_add(a);
589            l[0][i] = bb;
590            r[0][i] = a;
591        }
592    }
593    if extra > 0 {
594        for (c, o) in out.iter_mut().enumerate() {
595            for (s, e) in o.iter_mut().zip(extra_buf[c..].iter().step_by(channels)) {
596                *s = ((*s as u32) << extra | e) as i32;
597            }
598        }
599    }
600    Ok(n)
601}
602
603/// Interleave the first `n` samples of each channel into little-endian bytes,
604/// `W` bytes a sample. Mono and stereo get loops of their own, so the common
605/// cases write whole frames without a per-sample channel loop.
606fn interleave<const W: usize>(
607    bufs: &[Vec<i32>],
608    n: usize,
609    conv: impl Fn(i32) -> [u8; W],
610) -> Vec<u8> {
611    let ch = bufs.len();
612    let mut out = vec![0u8; n * ch * W];
613    match bufs {
614        [m] => {
615            for (d, &s) in out.chunks_exact_mut(W).zip(&m[..n]) {
616                d.copy_from_slice(&conv(s));
617            }
618        }
619        [l, r] => {
620            for (d, (&a, &b)) in out.chunks_exact_mut(2 * W).zip(l[..n].iter().zip(&r[..n])) {
621                d[..W].copy_from_slice(&conv(a));
622                d[W..].copy_from_slice(&conv(b));
623            }
624        }
625        _ => {
626            for (i, d) in out.chunks_exact_mut(ch * W).enumerate() {
627                for (b, o) in bufs.iter().zip(d.chunks_exact_mut(W)) {
628                    o.copy_from_slice(&conv(b[i]));
629                }
630            }
631        }
632    }
633    out
634}
635
636#[derive(Default)]
637struct AlacDecoder {
638    config: Option<AlacConfig>,
639    sample_rate: u32,
640    buffers: Vec<Vec<i32>>,
641    /// Shifted low bytes of the element being decoded, reused across frames.
642    extra_buf: Vec<u32>,
643    /// Residuals of the channel being decoded, reused across frames.
644    residual: Vec<i32>,
645    frame: Option<Frame>,
646    eof: bool,
647}
648
649impl Decoder for AlacDecoder {
650    fn configure(&mut self, params: &CodecParams) -> Result<()> {
651        let cfg = AlacConfig::from_cookie(&params.extradata)
652            .ok_or_else(|| Error::invalid("alac: no usable magic cookie in extradata"))?;
653        self.sample_rate = if params.sample_rate > 0 {
654            params.sample_rate
655        } else {
656            cfg.sample_rate
657        };
658        self.buffers = vec![Vec::new(); cfg.channels as usize];
659        self.config = Some(cfg);
660        Ok(())
661    }
662
663    fn send_packet(&mut self, packet: &Packet) -> Result<()> {
664        let cfg = self
665            .config
666            .ok_or_else(|| Error::invalid("alac: not configured"))?;
667        let n = decode_frame(
668            &cfg,
669            &packet.data,
670            &mut self.buffers,
671            &mut self.extra_buf,
672            &mut self.residual,
673        )?;
674        let (format, data) = if cfg.bit_depth == 16 {
675            let data = interleave(&self.buffers, n, |s| (s as i16).to_le_bytes());
676            (SampleFormat::S16, data)
677        } else {
678            // Left-justify to 32 bits (as FFmpeg's s32 output), then scale.
679            // `v as f32` rounds once, and scaling by a power of two is exact,
680            // so this is the same value as rounding `v / 2^31` from f64.
681            let shift = 32 - cfg.bit_depth as u32;
682            let data = interleave(&self.buffers, n, |s| {
683                let v = (s as u32).wrapping_shl(shift) as i32;
684                (v as f32 * (1.0 / 2_147_483_648.0)).to_le_bytes()
685            });
686            (SampleFormat::F32, data)
687        };
688        self.frame = Some(Frame::Audio(AudioFrame {
689            sample_rate: self.sample_rate,
690            channels: cfg.channels as u16,
691            format,
692            planes: vec![data],
693            samples: n,
694            pts: packet.pts,
695        }));
696        Ok(())
697    }
698
699    fn receive_frame(&mut self) -> Result<Frame> {
700        if let Some(f) = self.frame.take() {
701            return Ok(f);
702        }
703        if self.eof {
704            Err(Error::Eof)
705        } else {
706            Err(Error::Again)
707        }
708    }
709
710    fn flush(&mut self) {
711        self.eof = true;
712    }
713}
714
715#[cfg(test)]
716mod tests;