symphonia_codec_alac/
lib.rs

1// Symphonia
2// Copyright (c) 2019-2022 The Project Symphonia Developers.
3//
4// This Source Code Form is subject to the terms of the Mozilla Public
5// License, v. 2.0. If a copy of the MPL was not distributed with this
6// file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
8#![warn(rust_2018_idioms)]
9#![forbid(unsafe_code)]
10// The following lints are allowed in all Symphonia crates. Please see clippy.toml for their
11// justification.
12#![allow(clippy::comparison_chain)]
13#![allow(clippy::excessive_precision)]
14#![allow(clippy::identity_op)]
15#![allow(clippy::manual_range_contains)]
16// Disable to better express the specification.
17#![allow(clippy::collapsible_else_if)]
18
19use std::cmp::min;
20
21use symphonia_core::audio::{
22    AsAudioBufferRef, AudioBuffer, AudioBufferRef, Channels, Signal, SignalSpec,
23};
24use symphonia_core::codecs::{
25    CodecDescriptor, CodecParameters, Decoder, DecoderOptions, FinalizeResult, CODEC_TYPE_ALAC,
26};
27use symphonia_core::errors::{decode_error, unsupported_error, Result};
28use symphonia_core::formats::Packet;
29use symphonia_core::io::{BitReaderLtr, BufReader, FiniteStream, ReadBitsLtr, ReadBytes};
30use symphonia_core::support_codec;
31
32/// Supported ALAC version.
33const ALAC_VERSION: u8 = 0;
34
35/// Single Channel Element (SCE) tag.
36const ALAC_ELEM_TAG_SCE: u32 = 0;
37/// Channel Pair Element (CPE) tag.
38const ALAC_ELEM_TAG_CPE: u32 = 1;
39/// Coupling Channel Element CCE tag.
40const ALAC_ELEM_TAG_CCE: u32 = 2;
41/// LFE Channel Element (LFE) tag.
42const ALAC_ELEM_TAG_LFE: u32 = 3;
43/// Data Stream Element (DSE) tag.
44const ALAC_ELEM_TAG_DSE: u32 = 4;
45/// Program Control Element (PCE) tag.
46const ALAC_ELEM_TAG_PCE: u32 = 5;
47/// Fill Element (FIL) tag.
48const ALAC_ELEM_TAG_FIL: u32 = 6;
49/// Frame End Element (END) tag.
50const ALAC_ELEM_TAG_END: u32 = 7;
51
52/// An ALAC channel layout.
53#[derive(Debug)]
54enum ChannelLayout {
55    /// Centre
56    Mono,
57    /// Front Left, Front Right
58    Stereo,
59    /// Centre, Front Left, Front Right
60    Mpeg3p0B,
61    /// Centre, Front Left, Front Right, Rear Centre
62    Mpeg4p0B,
63    /// Centre, Front Left, Front Right, Side Left, Side Right
64    Mpeg5p0D,
65    /// Centre, Front Left, Front Right, Side Left, Side Right, LFE
66    Mpeg5p1D,
67    /// Centre, Front Left, Front Right, Side Left, Side Right, Rear Centre, LFE
68    Aac6p1,
69    /// Centre, Front Left of Centre, Front Right of Centre, Front Left, Front Right, Side Left,
70    /// Side Right, LFE
71    Mpeg7p1B,
72}
73
74impl ChannelLayout {
75    /// Given the current ALAC channel layout, this function will return a mappings of an ALAC
76    /// channel number (the index into the array) to a Symphonia `AudioBuffer` channel index.
77    fn channel_map(&self) -> [u8; 8] {
78        match self {
79            ChannelLayout::Mono => [0, 0, 0, 0, 0, 0, 0, 0],
80            ChannelLayout::Stereo => [0, 1, 0, 0, 0, 0, 0, 0],
81            ChannelLayout::Mpeg3p0B => [2, 0, 1, 0, 0, 0, 0, 0],
82            ChannelLayout::Mpeg4p0B => [2, 0, 1, 3, 0, 0, 0, 0],
83            ChannelLayout::Mpeg5p0D => [2, 0, 1, 3, 4, 0, 0, 0],
84            ChannelLayout::Mpeg5p1D => [2, 0, 1, 4, 5, 3, 0, 0],
85            ChannelLayout::Aac6p1 => [2, 0, 1, 5, 6, 4, 3, 0],
86            ChannelLayout::Mpeg7p1B => [2, 4, 5, 0, 1, 6, 7, 3],
87        }
88    }
89
90    /// Get a Symphonia channels bitmask from the ALAC channel layout.
91    fn channels(&self) -> Channels {
92        match self {
93            ChannelLayout::Mono => Channels::FRONT_LEFT,
94            ChannelLayout::Stereo => Channels::FRONT_LEFT | Channels::FRONT_RIGHT,
95            ChannelLayout::Mpeg3p0B => {
96                Channels::FRONT_CENTRE | Channels::FRONT_LEFT | Channels::FRONT_RIGHT
97            }
98            ChannelLayout::Mpeg4p0B => {
99                Channels::FRONT_CENTRE
100                    | Channels::FRONT_LEFT
101                    | Channels::FRONT_RIGHT
102                    | Channels::REAR_CENTRE
103            }
104            ChannelLayout::Mpeg5p0D => {
105                Channels::FRONT_CENTRE
106                    | Channels::FRONT_LEFT
107                    | Channels::FRONT_RIGHT
108                    | Channels::SIDE_LEFT
109                    | Channels::SIDE_RIGHT
110            }
111            ChannelLayout::Mpeg5p1D => {
112                Channels::FRONT_CENTRE
113                    | Channels::FRONT_LEFT
114                    | Channels::FRONT_RIGHT
115                    | Channels::SIDE_LEFT
116                    | Channels::SIDE_RIGHT
117                    | Channels::LFE1
118            }
119            ChannelLayout::Aac6p1 => {
120                Channels::FRONT_CENTRE
121                    | Channels::FRONT_LEFT
122                    | Channels::FRONT_RIGHT
123                    | Channels::SIDE_LEFT
124                    | Channels::SIDE_RIGHT
125                    | Channels::REAR_CENTRE
126                    | Channels::LFE1
127            }
128            ChannelLayout::Mpeg7p1B => {
129                Channels::FRONT_CENTRE
130                    | Channels::FRONT_LEFT_CENTRE
131                    | Channels::FRONT_RIGHT_CENTRE
132                    | Channels::FRONT_LEFT
133                    | Channels::FRONT_RIGHT
134                    | Channels::SIDE_LEFT
135                    | Channels::SIDE_RIGHT
136                    | Channels::LFE1
137            }
138        }
139    }
140}
141
142/// The ALAC "magic cookie" or codec specific configuration.
143#[derive(Debug)]
144#[allow(dead_code)]
145struct MagicCookie {
146    frame_length: u32,
147    compatible_version: u8,
148    bit_depth: u8,
149    pb: u8,
150    mb: u8,
151    kb: u8,
152    num_channels: u8,
153    max_run: u16,
154    max_frame_bytes: u32,
155    avg_bit_rate: u32,
156    sample_rate: u32,
157    channel_layout: ChannelLayout,
158}
159
160impl MagicCookie {
161    fn try_read<B: ReadBytes + FiniteStream>(reader: &mut B) -> Result<MagicCookie> {
162        // The magic cookie is either 24 or 48 bytes long.
163        if reader.byte_len() != 24 && reader.byte_len() != 48 {
164            return unsupported_error("alac: invalid magic cookie size");
165        }
166
167        let mut config = MagicCookie {
168            frame_length: reader.read_be_u32()?,
169            compatible_version: reader.read_u8()?,
170            bit_depth: reader.read_u8()?,
171            pb: reader.read_u8()?,
172            mb: reader.read_u8()?,
173            kb: reader.read_u8()?,
174            num_channels: reader.read_u8()?,
175            max_run: reader.read_be_u16()?,
176            max_frame_bytes: reader.read_be_u32()?,
177            avg_bit_rate: reader.read_be_u32()?,
178            sample_rate: reader.read_be_u32()?,
179            channel_layout: ChannelLayout::Mono,
180        };
181
182        // Only support up-to the currently implemented ALAC version.
183        if config.compatible_version > ALAC_VERSION {
184            return unsupported_error("alac: not compatible with alac version 0");
185        }
186
187        // A bit-depth greater than 32 is not allowed.
188        if config.bit_depth > 32 {
189            return decode_error("alac: invalid bit depth");
190        }
191
192        // Only 8 channel layouts exist.
193        // TODO: Support discrete/auxiliary channels.
194        if config.num_channels < 1 || config.num_channels > 8 {
195            return unsupported_error("alac: more than 8 channels");
196        }
197
198        // If the magic cookie is 48 bytes, the channel layout is explictly set, otherwise select a
199        // channel layout from the number of channels.
200        config.channel_layout = if reader.byte_len() == 48 {
201            // The first field is the size of the channel layout info. This should always be 24.
202            if reader.read_be_u32()? != 24 {
203                return decode_error("alac: invalid channel layout info size");
204            }
205
206            // The channel layout info identifier should be the ascii string "chan".
207            if reader.read_quad_bytes()? != *b"chan" {
208                return decode_error("alac: invalid channel layout info id");
209            }
210
211            // The channel layout info version must be 0.
212            if reader.read_be_u32()? != 0 {
213                return decode_error("alac: invalid channel layout info version");
214            }
215
216            // Read the channel layout tag. The numerical value of this tag is defined by the Apple
217            // CoreAudio API.
218            let layout = match reader.read_be_u32()? {
219                // 100 << 16
220                0x64_0001 => ChannelLayout::Mono,
221                // 101 << 16
222                0x65_0002 => ChannelLayout::Stereo,
223                // 113 << 16
224                0x71_0003 => ChannelLayout::Mpeg3p0B,
225                // 116 << 16
226                0x74_0004 => ChannelLayout::Mpeg4p0B,
227                // 120 << 16
228                0x78_0005 => ChannelLayout::Mpeg5p0D,
229                // 124 << 16
230                0x7c_0006 => ChannelLayout::Mpeg5p1D,
231                // 142 << 16
232                0x8e_0007 => ChannelLayout::Aac6p1,
233                // 127 << 16
234                0x7f_0008 => ChannelLayout::Mpeg7p1B,
235                _ => return decode_error("alac: invalid channel layout tag"),
236            };
237
238            // The number of channels stated in the mandatory part of the magic cookie should match
239            // the number of channels implicit to the channel layout.
240            if config.num_channels != layout.channels().count() as u8 {
241                return decode_error(
242                    "alac: the number of channels differs from the channel layout",
243                );
244            }
245
246            // The next two fields are reserved and should be 0.
247            if reader.read_be_u32()? != 0 || reader.read_be_u32()? != 0 {
248                return decode_error("alac: reserved values in channel layout info are not 0");
249            }
250
251            layout
252        }
253        else {
254            // If extra channel information is not provided, use the number of channels to assign
255            // a channel layout.
256            //
257            // TODO: If the number of channels is > 2, then the additional channels are considered
258            // discrete and not part of a channel layout. However, Symphonia does not support
259            // discrete/auxiliary channels so the standard ALAC channel layouts are used for now.
260            match config.num_channels {
261                1 => ChannelLayout::Mono,
262                2 => ChannelLayout::Stereo,
263                3 => ChannelLayout::Mpeg3p0B,
264                4 => ChannelLayout::Mpeg4p0B,
265                5 => ChannelLayout::Mpeg5p0D,
266                6 => ChannelLayout::Mpeg5p1D,
267                7 => ChannelLayout::Aac6p1,
268                8 => ChannelLayout::Mpeg7p1B,
269                _ => return decode_error("alac: unknown channel layout for number of channels"),
270            }
271        };
272
273        Ok(config)
274    }
275}
276
277#[derive(Debug)]
278struct ElementChannel {
279    pred_bits: u32,
280    kb: u32,
281    mb: u32,
282    mode: u32,
283    shift: u32,
284    pb_factor: u32,
285    lpc_order: u32,
286    lpc_coeffs: [i32; 32],
287}
288
289impl ElementChannel {
290    fn try_read<B: ReadBitsLtr>(
291        bs: &mut B,
292        config: &MagicCookie,
293        pred_bits: u8,
294    ) -> Result<ElementChannel> {
295        let mode = bs.read_bits_leq32(4)?;
296        let shift = bs.read_bits_leq32(4)?;
297        let pb_factor = (bs.read_bits_leq32(3)? * u32::from(config.pb)) >> 2;
298        let lpc_order = bs.read_bits_leq32(5)?;
299
300        // Read the predictor coefficients.
301        let mut lpc_coeffs = [0; 32];
302
303        for coeff in &mut lpc_coeffs[..lpc_order as usize] {
304            *coeff = bs.read_bits_leq32_signed(16)?;
305        }
306
307        Ok(ElementChannel {
308            pred_bits: u32::from(pred_bits),
309            kb: u32::from(config.kb),
310            mb: u32::from(config.mb),
311            mode,
312            shift,
313            pb_factor,
314            lpc_order,
315            lpc_coeffs,
316        })
317    }
318
319    fn read_residuals<B: ReadBitsLtr>(&mut self, bs: &mut B, out: &mut [i32]) -> Result<()> {
320        let out_len = out.len();
321
322        let mut mb = self.mb;
323        let mut sign_toggle = 0;
324        let mut zero_run_end = 0;
325
326        for (i, sample) in out.iter_mut().enumerate() {
327            // If the current sample is within a run of zeros, skip to the next sample since the
328            // output is already zeroed.
329            if i < zero_run_end {
330                continue;
331            }
332
333            let k = lg3a(mb);
334            let val = read_rice_code(bs, k.min(self.kb), self.pred_bits)? + sign_toggle;
335
336            *sample = rice_code_to_signed(val);
337
338            if val > 0xffff {
339                mb = 0xffff;
340            }
341            else {
342                // Order is important here.
343                mb -= (self.pb_factor * mb) >> 9;
344                mb += self.pb_factor * val;
345            }
346
347            sign_toggle = 0;
348
349            // In this special case, a run of zeros is signalled.
350            if mb < 128 && i + 1 < out_len {
351                // This subtraction cannot overflow because mb is a u32 and < 128. Therefore, mb
352                // will always have 25 leading zeros.
353                let k = mb.leading_zeros() - 24 + ((mb + 16) >> 6);
354
355                // The decoded rice code indicates the length of the run of zeros.
356                let zeros = read_rice_code(bs, k.min(self.kb), 16)?;
357
358                if zeros < 0xffff {
359                    sign_toggle = 1;
360                }
361
362                mb = 0;
363                zero_run_end = i + 1 + zeros as usize;
364            }
365        }
366        Ok(())
367    }
368
369    fn predict(&mut self, out: &mut [i32]) -> Result<()> {
370        // Modes other than 0 and 15 are invalid.
371        if self.mode > 0 && self.mode < 15 {
372            return decode_error("alac: invalid mode");
373        }
374
375        // An order of 0 indicates no prediction is done (the residuals are the samples).
376        if self.lpc_order == 0 {
377            return Ok(());
378        }
379
380        // Decoding is performed on signed 32-bit numbers, however, the actual predicted samples
381        // have a bit-width of `pred_bits`. Therefore, the top `32 - pred_bits` bits should be
382        // clipped.
383        let num_clip_bits = 32 - self.pred_bits;
384
385        // An order of 31, or a mode of 15, are special cases where the predictor runs twice. The
386        // first-pass uses a first-order prediction. The second pass is then the regular prediction
387        // using the coefficients from the bitstream.
388        if self.lpc_order == 31 || self.mode == 15 {
389            for i in 1..out.len() {
390                out[i] = clip_msbs(out[i].wrapping_add(out[i - 1]), num_clip_bits);
391            }
392        }
393
394        let order = self.lpc_order as usize;
395
396        // Process warm-up samples.
397        for i in 1..1 + order {
398            out[i] = clip_msbs(out[i].wrapping_add(out[i - 1]), num_clip_bits);
399        }
400
401        // Do the prediction.
402        //
403        // TODO: Orders for 4 and 8 are special-cased in the reference decoder. Consider using
404        // optimized versions for those cases like the FLAC decoder does.
405        for i in 1 + order..out.len() {
406            // Value of the output sample before prediction (the residual or difference).
407            let mut res = out[i];
408
409            // Value of the sample preceeding the first past sample.
410            let past0 = out[i - order - 1];
411
412            // Run the FIR filter.
413            let sum = self.lpc_coeffs[..order]
414                .iter()
415                .rev()
416                .zip(&out[i - order..i])
417                .map(|(&coeff, &s)| coeff.wrapping_mul(s - past0))
418                .fold(0i32, |sum, s| sum.wrapping_add(s));
419
420            // Rewrite `1 << (self.shift - 1)` as `(1 << self.shift) >> 1` to prevent overflowing
421            // when shift is 0.
422            let val = (sum + ((1 << self.shift) >> 1)) >> self.shift;
423            out[i] = clip_msbs(out[i].wrapping_add(past0).wrapping_add(val), num_clip_bits);
424
425            // Adjust the coefficients if the initial value of the residual was not 0.
426            if res != 0 {
427                let iter =
428                    self.lpc_coeffs[..order].iter_mut().rev().zip(&out[i - order..i]).enumerate();
429
430                // Note the subtle change in operations and signs for the following two cases.
431                if res > 0 {
432                    // Positive residual case.
433                    for (j, (coeff, &sample)) in iter {
434                        let val = past0 - sample;
435                        let sign = val.signum();
436
437                        *coeff -= sign;
438
439                        res -= (1 + j as i32) * ((sign * val) >> self.shift);
440
441                        if res <= 0 {
442                            break;
443                        }
444                    }
445                }
446                else {
447                    // Negative residual case.
448                    for (j, (coeff, &sample)) in iter {
449                        let val = past0 - sample;
450                        let sign = val.signum();
451
452                        *coeff += sign;
453
454                        res -= (1 + j as i32) * ((-sign * val) >> self.shift);
455
456                        if res >= 0 {
457                            break;
458                        }
459                    }
460                }
461            }
462        }
463
464        Ok(())
465    }
466}
467
468/// Apple Lossless Audio Codec (ALAC) decoder.
469pub struct AlacDecoder {
470    /// Codec paramters.
471    params: CodecParameters,
472    /// A temporary buffer to store the tail bits while decoding an element with a bit-shift > 0. If
473    /// `config.num_channels` > 1, then this buffer must be 2x the frame length.
474    tail_bits: Vec<u16>,
475    /// ALAC codec-specific configuration.
476    config: MagicCookie,
477    /// Output buffer.
478    buf: AudioBuffer<i32>,
479}
480
481impl AlacDecoder {
482    fn decode_inner(&mut self, packet: &Packet) -> Result<()> {
483        let mut bs = BitReaderLtr::new(packet.buf());
484
485        let channel_map = self.config.channel_layout.channel_map();
486        let num_channels = self.config.num_channels as usize;
487        let mut next_channel = 0;
488        let mut num_frames = 0;
489
490        // Fill the audio buffer with silence.
491        self.buf.clear();
492        self.buf.render_silence(None);
493
494        loop {
495            let tag = bs.read_bits_leq32(3)?;
496
497            match tag {
498                ALAC_ELEM_TAG_SCE | ALAC_ELEM_TAG_LFE => {
499                    let out0 = self.buf.chan_mut(channel_map[next_channel] as usize);
500
501                    num_frames =
502                        decode_sce_or_cpe(&self.config, &mut bs, &mut self.tail_bits, out0, None)?;
503
504                    next_channel += 1;
505                }
506                ALAC_ELEM_TAG_CPE => {
507                    // There may only be one channel left in the output buffer, do not attempt to
508                    // decode in this case.
509                    if next_channel + 2 > num_channels {
510                        break;
511                    }
512
513                    let (out0, out1) = self.buf.chan_pair_mut(
514                        channel_map[next_channel + 0] as usize,
515                        channel_map[next_channel + 1] as usize,
516                    );
517
518                    num_frames = decode_sce_or_cpe(
519                        &self.config,
520                        &mut bs,
521                        &mut self.tail_bits,
522                        out0,
523                        Some(out1),
524                    )?;
525
526                    next_channel += 2;
527                }
528                ALAC_ELEM_TAG_DSE => {
529                    let _tag = bs.read_bits_leq32(4)?;
530                    let align_flag = bs.read_bool()?;
531
532                    let count = match bs.read_bits_leq32(8)? {
533                        val @ 0..=254 => val,
534                        val @ 255 => val + bs.read_bits_leq32(8)?,
535                        _ => unreachable!(),
536                    };
537
538                    if align_flag {
539                        bs.realign();
540                    }
541
542                    bs.ignore_bits(8 * count)?;
543                }
544                ALAC_ELEM_TAG_FIL => {
545                    let count = match bs.read_bits_leq32(4)? {
546                        val @ 0..=14 => val,
547                        val @ 15 => val + bs.read_bits_leq32(8)? - 1,
548                        _ => unreachable!(),
549                    };
550
551                    bs.ignore_bits(8 * count)?;
552                }
553                ALAC_ELEM_TAG_CCE | ALAC_ELEM_TAG_PCE => {
554                    // These elements are unsupported in ALAC version 0.
555                    return decode_error("alac: unsupported element");
556                }
557                ALAC_ELEM_TAG_END => break,
558                _ => unreachable!(),
559            }
560
561            // Exit if all channels are decoded.
562            if next_channel >= num_channels {
563                break;
564            }
565        }
566
567        // Truncate the audio buffer to the number of samples of the last element.
568        self.buf.truncate(num_frames);
569
570        // The audio buffer is always signed 32-bit, but the actual bit-depth may be smaller. If
571        // the bit-depth is less-than 32, shift the final samples up.
572        let shift = 32 - self.config.bit_depth;
573
574        if shift > 0 {
575            self.buf.transform(|sample| sample << shift);
576        }
577
578        Ok(())
579    }
580}
581
582impl Decoder for AlacDecoder {
583    fn try_new(params: &CodecParameters, _: &DecoderOptions) -> Result<Self> {
584        // Verify codec type.
585        if params.codec != CODEC_TYPE_ALAC {
586            return unsupported_error("alac: invalid codec type");
587        }
588
589        // Read the config (magic cookie).
590        let config = if let Some(extra_data) = &params.extra_data {
591            MagicCookie::try_read(&mut BufReader::new(extra_data))?
592        }
593        else {
594            return unsupported_error("alac: missing extra data");
595        };
596
597        let spec = SignalSpec::new(config.sample_rate, config.channel_layout.channels());
598        let buf = AudioBuffer::new(u64::from(config.frame_length), spec);
599
600        let max_tail_values = min(2, config.num_channels) as usize * config.frame_length as usize;
601
602        Ok(AlacDecoder { params: params.clone(), tail_bits: vec![0; max_tail_values], buf, config })
603    }
604
605    fn reset(&mut self) {
606        // Nothing to do.
607    }
608
609    fn supported_codecs() -> &'static [CodecDescriptor] {
610        &[support_codec!(CODEC_TYPE_ALAC, "alac", "Apple Lossless Audio Codec")]
611    }
612
613    fn codec_params(&self) -> &CodecParameters {
614        &self.params
615    }
616
617    fn decode(&mut self, packet: &Packet) -> Result<AudioBufferRef<'_>> {
618        if let Err(e) = self.decode_inner(packet) {
619            self.buf.clear();
620            Err(e)
621        }
622        else {
623            Ok(self.buf.as_audio_buffer_ref())
624        }
625    }
626
627    fn finalize(&mut self) -> FinalizeResult {
628        Default::default()
629    }
630
631    fn last_decoded(&self) -> AudioBufferRef<'_> {
632        self.buf.as_audio_buffer_ref()
633    }
634}
635
636/// Reads and decodes a SCE or CPE (if the second output channel not `None`).
637fn decode_sce_or_cpe<B: ReadBitsLtr>(
638    config: &MagicCookie,
639    bs: &mut B,
640    tail_bits: &mut [u16],
641    out0: &mut [i32],
642    mut out1: Option<&mut [i32]>,
643) -> Result<usize> {
644    // If the second output channel is provided, decode as a Channel Pair Element (CPE), otherwise
645    // as a Single Channel Element (SCE).
646    let is_cpe = out1.is_some();
647
648    // Element instance tag.
649    let _elem_instance_tag = bs.read_bits_leq32(4)?;
650
651    // Unused header bits.
652    if bs.read_bits_leq32(12)? != 0 {
653        return decode_error("alac: unused header bits not 0");
654    };
655
656    let is_partial_frame = bs.read_bool()?;
657    let shift = 8 * bs.read_bits_leq32(2)? as u8;
658    let is_uncompressed = bs.read_bool()?;
659
660    // The shift must not be >= 24-bits, or exceed the encoded bit-depth.
661    if shift >= 8 * 3 || shift >= config.bit_depth {
662        return decode_error("alac: invalid shift value");
663    }
664
665    // If this is a partial frame, then read the frame length from the element,
666    // otherwise use the frame length in the configuration.
667    let num_samples =
668        if is_partial_frame { bs.read_bits_leq32(32)? } else { config.frame_length } as usize;
669
670    if !is_uncompressed {
671        // The number of upper sample bits that will be predicted per channel. This may be less-than
672        // the bit-depth if the lower sample bits will be encoded separately. If decoding a CPE,
673        // each channel gets an extra bit allocated to it for mid-side encoding.
674        let pred_bits = config.bit_depth - shift + u8::from(is_cpe);
675
676        let mid_side_shift = bs.read_bits_leq32(8)? as u8;
677        let mid_side_weight = bs.read_bits_leq32_signed(8)?;
678
679        // For SCE elements, the mid-side parameters must (should?) be 0.
680        if !is_cpe && (mid_side_shift != 0 || mid_side_weight != 0) {
681            return decode_error("alac: invalid mixing information for mono channel");
682        }
683
684        // Read the headers for each channel in the element.
685        let mut elem0 = ElementChannel::try_read(bs, config, pred_bits)?;
686        let mut elem1 =
687            if is_cpe { Some(ElementChannel::try_read(bs, config, pred_bits)?) } else { None };
688
689        // If there is a shift, read and save the "tail" bits that will be appended to the predicted
690        // samples.
691        if shift > 0 {
692            let num_tail_values = if is_cpe { 2 } else { 1 } * num_samples;
693
694            for val in &mut tail_bits[..num_tail_values] {
695                *val = bs.read_bits_leq32(u32::from(shift))? as u16;
696            }
697        }
698
699        elem0.read_residuals(bs, &mut out0[..num_samples])?;
700        elem0.predict(&mut out0[..num_samples])?;
701
702        if let Some(out1) = out1.as_mut() {
703            let elem1 = elem1.as_mut().unwrap();
704
705            elem1.read_residuals(bs, &mut out1[..num_samples])?;
706            elem1.predict(&mut out1[..num_samples])?;
707
708            if mid_side_weight != 0 {
709                decorrelate_mid_side(out0, out1, mid_side_weight, mid_side_shift);
710            }
711        }
712
713        // If there is a shift, append the saved "tail" bits to each predicted sample.
714        if shift > 0 {
715            let out0_iter = out0[..num_samples].iter_mut();
716
717            if let Some(out1) = out1.as_mut() {
718                let out1_iter = out1[..num_samples].iter_mut();
719                let tail_iter = tail_bits[..2 * num_samples].chunks_exact(2);
720
721                // For a CPE, the tail bits are interleaved.
722                for ((s0, s1), vals) in out0_iter.zip(out1_iter).zip(tail_iter) {
723                    *s0 = (*s0 << shift) | vals[0] as i32;
724                    *s1 = (*s1 << shift) | vals[1] as i32;
725                }
726            }
727            else {
728                let tail_iter = tail_bits[..num_samples].iter();
729
730                for (s0, &val) in out0_iter.zip(tail_iter) {
731                    *s0 = (*s0 << shift) | val as i32;
732                }
733            }
734        }
735    }
736    else {
737        // Read uncompressed samples directly from the bitstream.
738        if let Some(out1) = out1.as_mut() {
739            // For a CPE, the samples are interleaved.
740            for (s0, s1) in out0[..num_samples].iter_mut().zip(&mut out1[..num_samples]) {
741                *s0 = bs.read_bits_leq32_signed(u32::from(config.bit_depth))?;
742                *s1 = bs.read_bits_leq32_signed(u32::from(config.bit_depth))?;
743            }
744        }
745        else {
746            for s0 in out0[..num_samples].iter_mut() {
747                *s0 = bs.read_bits_leq32_signed(u32::from(config.bit_depth))?;
748            }
749        }
750    }
751
752    Ok(num_samples)
753}
754
755#[inline(always)]
756fn lg3a(val: u32) -> u32 {
757    31 - ((val >> 9) + 3).leading_zeros()
758}
759
760/// Read a rice code from the bitstream.
761#[inline(always)]
762fn read_rice_code<B: ReadBitsLtr>(bs: &mut B, k: u32, kb: u32) -> Result<u32> {
763    let prefix = bs.read_unary_ones_capped(9)?;
764
765    // If the prefix is > 8, the value is read as an arbitrary width unsigned integer.
766    let value = if prefix > 8 {
767        bs.read_bits_leq32(kb)?
768    }
769    else if k > 1 {
770        // The reference decoder specifies prefix to be multiplied by a parameter `m`. The parameter
771        // `m` is always `(1<<k)-1` which is `2^k - 1`. This can be rewritten using a bit-shift.
772        let value = (prefix << k) - prefix;
773
774        // Ideally, we need to read, but not consume, `k` bits here. This is because if the value is
775        // less-than 2 we must only consume `k-1` bits. The bit reader does not support peeking,
776        // therefore, we read the `k-1` top-most bits. If the value is > 0, then the `k`-bit value
777        // would be > 2. In that case, we'll then read the least-significant bit in a second read
778        // operation.
779        let suffix = bs.read_bits_leq32(k - 1)?;
780
781        if suffix > 0 {
782            // Shift suffix left by 1 because it is missing its LSb, and then read the missing bit.
783            value + (suffix << 1) + bs.read_bit()? - 1
784        }
785        else {
786            value
787        }
788    }
789    else if k == 1 {
790        prefix
791    }
792    else {
793        0
794    };
795
796    Ok(value)
797}
798
799/// Converts the unsigned rice code into a signed i32.
800#[inline(always)]
801fn rice_code_to_signed(val: u32) -> i32 {
802    // The last bit of the decoded rice value is the sign-bit. See FLAC decoder for a derivation
803    // of this function.
804    (val >> 1) as i32 ^ -((val & 0x1) as i32)
805}
806
807/// Clips `num` most significant bits from the provided value and returns the result.
808#[inline(always)]
809fn clip_msbs(val: i32, num: u32) -> i32 {
810    (val << num) >> num
811}
812
813/// Decorrelates a mid-side channel pair.
814fn decorrelate_mid_side(out0: &mut [i32], out1: &mut [i32], weight: i32, shift: u8) {
815    assert!(out0.len() == out1.len());
816
817    for (s0, s1) in out0.iter_mut().zip(out1.iter_mut()) {
818        *s0 = *s0 + *s1 - ((*s1 * weight) >> shift);
819        *s1 = *s0 - *s1;
820    }
821}