symphonia_codec_vorbis/
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 symphonia_core::audio::{AsAudioBufferRef, AudioBuffer, AudioBufferRef};
20use symphonia_core::audio::{Signal, SignalSpec};
21use symphonia_core::codecs::{CodecDescriptor, CodecParameters, CODEC_TYPE_VORBIS};
22use symphonia_core::codecs::{Decoder, DecoderOptions, FinalizeResult};
23use symphonia_core::dsp::mdct::Imdct;
24use symphonia_core::errors::{decode_error, unsupported_error, Result};
25use symphonia_core::formats::Packet;
26use symphonia_core::io::{BitReaderRtl, BufReader, FiniteBitStream, ReadBitsRtl, ReadBytes};
27use symphonia_core::support_codec;
28
29use symphonia_utils_xiph::vorbis::*;
30
31use log::{debug, warn};
32
33mod codebook;
34mod common;
35mod dsp;
36mod floor;
37mod residue;
38mod window;
39
40use codebook::VorbisCodebook;
41use common::*;
42use dsp::*;
43use floor::*;
44use residue::*;
45use window::Windows;
46
47/// Vorbis decoder.
48pub struct VorbisDecoder {
49    /// Codec paramters.
50    params: CodecParameters,
51    /// Identity header.
52    ident: IdentHeader,
53    /// Codebooks (max. 256).
54    codebooks: Vec<VorbisCodebook>,
55    /// Floors (max. 64).
56    floors: Vec<Box<dyn Floor>>,
57    /// Residues (max. 64).
58    residues: Vec<Residue>,
59    /// Modes (max. 64).
60    modes: Vec<Mode>,
61    /// Mappings (max. 64).
62    mappings: Vec<Mapping>,
63    /// DSP.
64    dsp: Dsp,
65    /// Output buffer.
66    buf: AudioBuffer<f32>,
67}
68
69impl VorbisDecoder {
70    fn decode_inner(&mut self, packet: &Packet) -> Result<()> {
71        let mut bs = BitReaderRtl::new(packet.buf());
72
73        // Section 4.3.1 - Packet Type, Mode, and Window Decode
74
75        // First bit must be 0 to indicate audio packet.
76        if bs.read_bool()? {
77            return decode_error("vorbis: not an audio packet");
78        }
79
80        let num_modes = self.modes.len() - 1;
81
82        let mode_number = bs.read_bits_leq32(common::ilog(num_modes as u32))? as usize;
83
84        if mode_number >= self.modes.len() {
85            return decode_error("vorbis: invalid packet mode number");
86        }
87
88        let mode = &self.modes[mode_number];
89        let mapping = &self.mappings[usize::from(mode.mapping)];
90
91        let (bs_exp, imdct) = if mode.block_flag {
92            // This packet (block) uses a long window. Do not use the window flags since they may
93            // be wrong.
94            let _prev_window_flag = bs.read_bool()?;
95            let _next_window_flag = bs.read_bool()?;
96
97            (self.ident.bs1_exp, &mut self.dsp.imdct_long)
98        }
99        else {
100            // This packet (block) uses a short window.
101            (self.ident.bs0_exp, &mut self.dsp.imdct_short)
102        };
103
104        // Block, and half-block size
105        let n = 1 << bs_exp;
106        let n2 = n >> 1;
107
108        // Section 4.3.2 - Floor Curve Decode
109
110        // Read the floors from the packet. There is one floor per audio channel. Each mapping will
111        // have one multiplex (submap number) per audio channel. Therefore, iterate over all
112        // muxes in the mapping, and read the floor.
113        for (&submap_num, ch) in mapping.multiplex.iter().zip(&mut self.dsp.channels) {
114            let submap = &mapping.submaps[submap_num as usize];
115            let floor = &mut self.floors[submap.floor as usize];
116
117            // Read the floor from the bitstream.
118            floor.read_channel(&mut bs, &self.codebooks)?;
119
120            ch.do_not_decode = floor.is_unused();
121
122            if !ch.do_not_decode {
123                // Since the same floor can be used by multiple channels and thus overwrite the
124                // data just read from the bitstream, synthesize the floor curve for this channel
125                // now and save it for audio synthesis later.
126                floor.synthesis(bs_exp, &mut ch.floor)?;
127            }
128            else {
129                // If the channel is unused, zero the floor vector.
130                ch.floor[..n2].fill(0.0);
131            }
132        }
133
134        // Section 4.3.3 - Non-zero Vector Propagate
135
136        // If within a pair of coupled channels, one channel has an unused floor (do_not_decode
137        // is true for that channel), but the other channel is used, then both channels must have
138        // do_not_decode unset.
139        for couple in &mapping.couplings {
140            let magnitude_ch_idx = usize::from(couple.magnitude_ch);
141            let angle_ch_idx = usize::from(couple.angle_ch);
142
143            if self.dsp.channels[magnitude_ch_idx].do_not_decode
144                != self.dsp.channels[angle_ch_idx].do_not_decode
145            {
146                self.dsp.channels[magnitude_ch_idx].do_not_decode = false;
147                self.dsp.channels[angle_ch_idx].do_not_decode = false;
148            }
149        }
150
151        // Section 4.3.4 - Residue Decode
152
153        for (submap_idx, submap) in mapping.submaps.iter().enumerate() {
154            let mut residue_channels: BitSet256 = Default::default();
155
156            // Find the channels using this submap.
157            for (c, &ch_submap_idx) in mapping.multiplex.iter().enumerate() {
158                if submap_idx == usize::from(ch_submap_idx) {
159                    residue_channels.set(c)
160                }
161            }
162
163            let residue = &mut self.residues[submap.residue as usize];
164
165            residue.read_residue(
166                &mut bs,
167                bs_exp,
168                &self.codebooks,
169                &residue_channels,
170                &mut self.dsp.channels,
171            )?;
172        }
173
174        // Section 4.3.5 - Inverse Coupling
175
176        for coupling in mapping.couplings.iter() {
177            debug_assert!(coupling.magnitude_ch != coupling.angle_ch);
178
179            // Get mutable reference to each channel in the pair.
180            let (magnitude_ch, angle_ch) = if coupling.magnitude_ch < coupling.angle_ch {
181                // Magnitude channel index < angle channel index.
182                let (a, b) = self.dsp.channels.split_at_mut(coupling.angle_ch as usize);
183                (&mut a[coupling.magnitude_ch as usize], &mut b[0])
184            }
185            else {
186                // Angle channel index < magnitude channel index.
187                let (a, b) = self.dsp.channels.split_at_mut(coupling.magnitude_ch as usize);
188                (&mut b[0], &mut a[coupling.angle_ch as usize])
189            };
190
191            for (m, a) in magnitude_ch.residue[..n2].iter_mut().zip(&mut angle_ch.residue[..n2]) {
192                let (new_m, new_a) = if *m > 0.0 {
193                    if *a > 0.0 {
194                        (*m, *m - *a)
195                    }
196                    else {
197                        (*m + *a, *m)
198                    }
199                }
200                else {
201                    if *a > 0.0 {
202                        (*m, *m + *a)
203                    }
204                    else {
205                        (*m - *a, *m)
206                    }
207                };
208
209                *m = new_m;
210                *a = new_a;
211            }
212        }
213
214        // Section 4.3.6 - Dot Product
215
216        for channel in self.dsp.channels.iter_mut() {
217            // If the channel is marked as do not decode, the floor vector is all 0. Therefore the
218            // dot product will be 0.
219            if channel.do_not_decode {
220                continue;
221            }
222
223            for (f, r) in channel.floor[..n2].iter_mut().zip(&mut channel.residue[..n2]) {
224                *f *= *r;
225            }
226        }
227
228        // Combined Section 4.3.7 and 4.3.8 - Inverse MDCT and Overlap-add (Synthesis)
229        self.buf.clear();
230
231        // Calculate the output length and reserve space in the output buffer. If there was no
232        // previous packet, then return an empty audio buffer since the decoder will need another
233        // packet before being able to produce audio.
234        if let Some(lap_state) = &self.dsp.lapping_state {
235            // The previous block size.
236            let prev_block_n = if lap_state.prev_block_flag {
237                1 << self.ident.bs1_exp
238            }
239            else {
240                1 << self.ident.bs0_exp
241            };
242
243            let render_len = (prev_block_n + n) / 4;
244            self.buf.render_reserved(Some(render_len));
245        }
246
247        // Render all the audio channels.
248        for (i, channel) in self.dsp.channels.iter_mut().enumerate() {
249            channel.synth(
250                mode.block_flag,
251                &self.dsp.lapping_state,
252                &self.dsp.windows,
253                imdct,
254                self.buf.chan_mut(map_vorbis_channel(self.ident.n_channels, i)),
255            );
256        }
257
258        // Trim
259        self.buf.trim(packet.trim_start() as usize, packet.trim_end() as usize);
260
261        // Save the new lapping state.
262        self.dsp.lapping_state = Some(LappingState { prev_block_flag: mode.block_flag });
263
264        Ok(())
265    }
266}
267
268impl Decoder for VorbisDecoder {
269    fn try_new(params: &CodecParameters, _: &DecoderOptions) -> Result<Self> {
270        // This decoder only supports Vorbis.
271        if params.codec != CODEC_TYPE_VORBIS {
272            return unsupported_error("vorbis: invalid codec type");
273        }
274
275        // Get the extra data (mandatory).
276        let extra_data = match params.extra_data.as_ref() {
277            Some(buf) => buf,
278            _ => return unsupported_error("vorbis: missing extra data"),
279        };
280
281        // The extra data contains the identification and setup headers.
282        let mut reader = BufReader::new(extra_data);
283
284        // Read ident header.
285        let ident = read_ident_header(&mut reader)?;
286
287        // Read setup data.
288        let setup = read_setup(&mut reader, &ident)?;
289
290        // Initialize static DSP data.
291        let windows = Windows::new(1 << ident.bs0_exp, 1 << ident.bs1_exp);
292
293        // Initialize dynamic DSP for each channel.
294        let dsp_channels =
295            (0..ident.n_channels).map(|_| DspChannel::new(ident.bs0_exp, ident.bs1_exp)).collect();
296
297        // Map the channels
298        let channels = match vorbis_channels_to_channels(ident.n_channels) {
299            Some(channels) => channels,
300            _ => return unsupported_error("vorbis: unknown channel map (fix me)"),
301        };
302
303        // Initialize the output buffer.
304        let spec = SignalSpec::new(ident.sample_rate, channels);
305
306        let imdct_short = Imdct::new((1 << ident.bs0_exp) >> 1);
307        let imdct_long = Imdct::new((1 << ident.bs1_exp) >> 1);
308
309        // TODO: Should this be half the block size?
310        let duration = 1u64 << ident.bs1_exp;
311
312        let dsp =
313            Dsp { windows, channels: dsp_channels, imdct_short, imdct_long, lapping_state: None };
314
315        Ok(VorbisDecoder {
316            params: params.clone(),
317            ident,
318            codebooks: setup.codebooks,
319            floors: setup.floors,
320            residues: setup.residues,
321            modes: setup.modes,
322            mappings: setup.mappings,
323            dsp,
324            buf: AudioBuffer::new(duration, spec),
325        })
326    }
327
328    fn reset(&mut self) {
329        self.dsp.reset();
330    }
331
332    fn supported_codecs() -> &'static [CodecDescriptor] {
333        &[support_codec!(CODEC_TYPE_VORBIS, "vorbis", "Vorbis")]
334    }
335
336    fn codec_params(&self) -> &CodecParameters {
337        &self.params
338    }
339
340    fn decode(&mut self, packet: &Packet) -> Result<AudioBufferRef<'_>> {
341        if let Err(e) = self.decode_inner(packet) {
342            self.buf.clear();
343            Err(e)
344        }
345        else {
346            Ok(self.buf.as_audio_buffer_ref())
347        }
348    }
349
350    fn finalize(&mut self) -> FinalizeResult {
351        Default::default()
352    }
353
354    fn last_decoded(&self) -> AudioBufferRef<'_> {
355        self.buf.as_audio_buffer_ref()
356    }
357}
358
359#[derive(Debug)]
360struct IdentHeader {
361    n_channels: u8,
362    sample_rate: u32,
363    bs0_exp: u8,
364    bs1_exp: u8,
365}
366
367/// The packet type for an identification header.
368const VORBIS_PACKET_TYPE_IDENTIFICATION: u8 = 1;
369/// The packet type for a setup header.
370const VORBIS_PACKET_TYPE_SETUP: u8 = 5;
371
372/// The common header packet signature.
373const VORBIS_HEADER_PACKET_SIGNATURE: &[u8] = b"vorbis";
374
375/// The Vorbis version supported by this mapper.
376const VORBIS_VERSION: u32 = 0;
377
378/// The minimum block size (64) expressed as a power-of-2 exponent.
379const VORBIS_BLOCKSIZE_MIN: u8 = 6;
380/// The maximum block size (8192) expressed as a power-of-2 exponent.
381const VORBIS_BLOCKSIZE_MAX: u8 = 13;
382
383fn read_ident_header<B: ReadBytes>(reader: &mut B) -> Result<IdentHeader> {
384    // The packet type must be an identification header.
385    let packet_type = reader.read_u8()?;
386
387    if packet_type != VORBIS_PACKET_TYPE_IDENTIFICATION {
388        return decode_error("vorbis: invalid packet type for identification header");
389    }
390
391    // Next, the header packet signature must be correct.
392    let mut packet_sig_buf = [0; 6];
393    reader.read_buf_exact(&mut packet_sig_buf)?;
394
395    if packet_sig_buf != VORBIS_HEADER_PACKET_SIGNATURE {
396        return decode_error("vorbis: invalid header signature");
397    }
398
399    // Next, the Vorbis version must be 0.
400    let version = reader.read_u32()?;
401
402    if version != VORBIS_VERSION {
403        return unsupported_error("vorbis: only vorbis 1 is supported");
404    }
405
406    // Next, the number of channels and sample rate must be non-zero.
407    let n_channels = reader.read_u8()?;
408
409    if n_channels == 0 {
410        return decode_error("vorbis: number of channels cannot be 0");
411    }
412
413    // This is a Symphonia limitation.
414    if n_channels > 32 {
415        return unsupported_error("vorbis: only a maximum of 32 channels are supported");
416    }
417
418    let sample_rate = reader.read_u32()?;
419
420    if sample_rate == 0 {
421        return decode_error("vorbis: sample rate cannot be 0");
422    }
423
424    // Read the bitrate range.
425    let _bitrate_max = reader.read_u32()?;
426    let _bitrate_nom = reader.read_u32()?;
427    let _bitrate_min = reader.read_u32()?;
428
429    // Next, blocksize_0 and blocksize_1 are packed into a single byte.
430    let block_sizes = reader.read_u8()?;
431
432    let bs0_exp = (block_sizes & 0x0f) >> 0;
433    let bs1_exp = (block_sizes & 0xf0) >> 4;
434
435    // The block sizes must not exceed the bounds.
436    if bs0_exp < VORBIS_BLOCKSIZE_MIN || bs0_exp > VORBIS_BLOCKSIZE_MAX {
437        return decode_error("vorbis: blocksize_0 out-of-bounds");
438    }
439
440    if bs1_exp < VORBIS_BLOCKSIZE_MIN || bs1_exp > VORBIS_BLOCKSIZE_MAX {
441        return decode_error("vorbis: blocksize_1 out-of-bounds");
442    }
443
444    // Blocksize_0 must be >= blocksize_1
445    if bs0_exp > bs1_exp {
446        return decode_error("vorbis: blocksize_0 exceeds blocksize_1");
447    }
448
449    // Framing flag must be set.
450    if reader.read_u8()? != 0x1 {
451        return decode_error("vorbis: ident header framing flag unset");
452    }
453
454    Ok(IdentHeader { n_channels, sample_rate, bs0_exp, bs1_exp })
455}
456
457struct Setup {
458    codebooks: Vec<VorbisCodebook>,
459    floors: Vec<Box<dyn Floor>>,
460    residues: Vec<Residue>,
461    mappings: Vec<Mapping>,
462    modes: Vec<Mode>,
463}
464
465fn read_setup(reader: &mut BufReader<'_>, ident: &IdentHeader) -> Result<Setup> {
466    // The packet type must be an setup header.
467    let packet_type = reader.read_u8()?;
468
469    if packet_type != VORBIS_PACKET_TYPE_SETUP {
470        return decode_error("vorbis: invalid packet type for setup header");
471    }
472
473    // Next, the setup packet signature must be correct.
474    let mut packet_sig_buf = [0; 6];
475    reader.read_buf_exact(&mut packet_sig_buf)?;
476
477    if packet_sig_buf != VORBIS_HEADER_PACKET_SIGNATURE {
478        return decode_error("vorbis: invalid setup header signature");
479    }
480
481    // The remaining portion of the setup header packet is read bitwise.
482    let mut bs = BitReaderRtl::new(reader.read_buf_bytes_available_ref());
483
484    // Read codebooks.
485    let codebooks = read_codebooks(&mut bs)?;
486
487    // Read time-domain transforms (placeholders in Vorbis 1).
488    read_time_domain_transforms(&mut bs)?;
489
490    // Read floors.
491    let floors = read_floors(&mut bs, ident.bs0_exp, ident.bs1_exp, codebooks.len() as u8)?;
492
493    // Read residues.
494    let residues = read_residues(&mut bs, codebooks.len() as u8)?;
495
496    // Read channel mappings.
497    let mappings =
498        read_mappings(&mut bs, ident.n_channels, floors.len() as u8, residues.len() as u8)?;
499
500    // Read modes.
501    let modes = read_modes(&mut bs, mappings.len() as u8)?;
502
503    // Framing flag must be set.
504    if !bs.read_bool()? {
505        return decode_error("vorbis: setup header framing flag unset");
506    }
507
508    if bs.bits_left() > 0 {
509        debug!("vorbis: leftover bits in setup head extra data");
510    }
511
512    Ok(Setup { codebooks, floors, residues, mappings, modes })
513}
514
515fn read_codebooks(bs: &mut BitReaderRtl<'_>) -> Result<Vec<VorbisCodebook>> {
516    let count = bs.read_bits_leq32(8)? + 1;
517    (0..count).map(|_| VorbisCodebook::read(bs)).collect()
518}
519
520fn read_time_domain_transforms(bs: &mut BitReaderRtl<'_>) -> Result<()> {
521    let count = bs.read_bits_leq32(6)? + 1;
522
523    for _ in 0..count {
524        // All these values are placeholders and must be 0.
525        if bs.read_bits_leq32(16)? != 0 {
526            return decode_error("vorbis: invalid time domain tranform");
527        }
528    }
529
530    Ok(())
531}
532
533fn read_floors(
534    bs: &mut BitReaderRtl<'_>,
535    bs0_exp: u8,
536    bs1_exp: u8,
537    max_codebook: u8,
538) -> Result<Vec<Box<dyn Floor>>> {
539    let count = bs.read_bits_leq32(6)? + 1;
540    (0..count).map(|_| read_floor(bs, bs0_exp, bs1_exp, max_codebook)).collect()
541}
542
543fn read_floor(
544    bs: &mut BitReaderRtl<'_>,
545    bs0_exp: u8,
546    bs1_exp: u8,
547    max_codebook: u8,
548) -> Result<Box<dyn Floor>> {
549    let floor_type = bs.read_bits_leq32(16)?;
550
551    match floor_type {
552        0 => Floor0::try_read(bs, bs0_exp, bs1_exp, max_codebook),
553        1 => Floor1::try_read(bs, max_codebook),
554        _ => decode_error("vorbis: invalid floor type"),
555    }
556}
557
558fn read_residues(bs: &mut BitReaderRtl<'_>, max_codebook: u8) -> Result<Vec<Residue>> {
559    let count = bs.read_bits_leq32(6)? + 1;
560    (0..count).map(|_| read_residue(bs, max_codebook)).collect()
561}
562
563fn read_residue(bs: &mut BitReaderRtl<'_>, max_codebook: u8) -> Result<Residue> {
564    let residue_type = bs.read_bits_leq32(16)? as u16;
565
566    match residue_type {
567        0..=2 => Residue::try_read(bs, residue_type, max_codebook),
568        _ => decode_error("vorbis: invalid residue type"),
569    }
570}
571
572fn read_mappings(
573    bs: &mut BitReaderRtl<'_>,
574    audio_channels: u8,
575    max_floor: u8,
576    max_residue: u8,
577) -> Result<Vec<Mapping>> {
578    let count = bs.read_bits_leq32(6)? + 1;
579    (0..count).map(|_| read_mapping(bs, audio_channels, max_floor, max_residue)).collect()
580}
581
582fn read_mapping(
583    bs: &mut BitReaderRtl<'_>,
584    audio_channels: u8,
585    max_floor: u8,
586    max_residue: u8,
587) -> Result<Mapping> {
588    let mapping_type = bs.read_bits_leq32(16)?;
589
590    match mapping_type {
591        0 => read_mapping_type0(bs, audio_channels, max_floor, max_residue),
592        _ => decode_error("vorbis: invalid mapping type"),
593    }
594}
595
596fn read_modes(bs: &mut BitReaderRtl<'_>, max_mapping: u8) -> Result<Vec<Mode>> {
597    let count = bs.read_bits_leq32(6)? + 1;
598    (0..count).map(|_| read_mode(bs, max_mapping)).collect()
599}
600
601#[derive(Debug)]
602struct ChannelCouple {
603    magnitude_ch: u8,
604    angle_ch: u8,
605}
606
607#[derive(Debug)]
608struct SubMap {
609    floor: u8,
610    residue: u8,
611}
612
613#[derive(Debug)]
614struct Mapping {
615    couplings: Vec<ChannelCouple>,
616    multiplex: Vec<u8>,
617    submaps: Vec<SubMap>,
618}
619
620fn read_mapping_type0(
621    bs: &mut BitReaderRtl<'_>,
622    audio_channels: u8,
623    max_floor: u8,
624    max_residue: u8,
625) -> Result<Mapping> {
626    let num_submaps = if bs.read_bool()? { bs.read_bits_leq32(4)? as u8 + 1 } else { 1 };
627
628    let mut couplings = Vec::new();
629
630    if bs.read_bool()? {
631        // Number of channel couplings (up-to 256).
632        let coupling_steps = bs.read_bits_leq32(8)? as u16 + 1;
633
634        // Reserve space.
635        couplings.reserve_exact(usize::from(coupling_steps));
636
637        // The maximum channel number.
638        let max_ch = audio_channels - 1;
639
640        // The number of bits to read for the magnitude and angle channel numbers. Never exceeds 8.
641        let coupling_bits = ilog(u32::from(max_ch));
642        debug_assert!(coupling_bits <= 8);
643
644        // Read each channel coupling.
645        for _ in 0..coupling_steps {
646            let magnitude_ch = bs.read_bits_leq32(coupling_bits)? as u8;
647            let angle_ch = bs.read_bits_leq32(coupling_bits)? as u8;
648
649            // Ensure the channels to be coupled are not the same, and that neither channel number
650            // exceeds the maximum channel in the stream.
651            if magnitude_ch == angle_ch || magnitude_ch > max_ch || angle_ch > max_ch {
652                return decode_error("vorbis: invalid channel coupling");
653            }
654
655            couplings.push(ChannelCouple { magnitude_ch, angle_ch });
656        }
657    }
658
659    if bs.read_bits_leq32(2)? != 0 {
660        return decode_error("vorbis: reserved mapping bits non-zero");
661    }
662
663    let mut multiplex = Vec::with_capacity(usize::from(audio_channels));
664
665    // If the number of submaps is > 1 read the multiplex numbers from the bitstream, otherwise
666    // they're all 0.
667    if num_submaps > 1 {
668        for _ in 0..audio_channels {
669            let mux = bs.read_bits_leq32(4)? as u8;
670
671            if mux >= num_submaps {
672                return decode_error("vorbis: invalid channel multiplex");
673            }
674
675            multiplex.push(mux);
676        }
677    }
678    else {
679        multiplex.resize(usize::from(audio_channels), 0);
680    }
681
682    let mut submaps = Vec::with_capacity(usize::from(num_submaps));
683
684    for _ in 0..num_submaps {
685        // Unused.
686        let _ = bs.read_bits_leq32(8)?;
687
688        // The floor to use.
689        let floor = bs.read_bits_leq32(8)? as u8;
690
691        if floor >= max_floor {
692            return decode_error("vorbis: invalid floor for mapping");
693        }
694
695        // The residue to use.
696        let residue = bs.read_bits_leq32(8)? as u8;
697
698        if residue >= max_residue {
699            return decode_error("vorbis: invalid residue for mapping");
700        }
701
702        submaps.push(SubMap { floor, residue });
703    }
704
705    let mapping = Mapping { couplings, multiplex, submaps };
706
707    Ok(mapping)
708}
709
710#[derive(Debug)]
711struct Mode {
712    block_flag: bool,
713    mapping: u8,
714}
715
716fn read_mode(bs: &mut BitReaderRtl<'_>, max_mapping: u8) -> Result<Mode> {
717    let block_flag = bs.read_bool()?;
718    let window_type = bs.read_bits_leq32(16)? as u16;
719    let transform_type = bs.read_bits_leq32(16)? as u16;
720    let mapping = bs.read_bits_leq32(8)? as u8;
721
722    // Only window type 0 is allowed in Vorbis 1 (section 4.2.4).
723    if window_type != 0 {
724        return decode_error("vorbis: invalid window type for mode");
725    }
726
727    // Only transform type 0 is allowed in Vorbis 1 (section 4.2.4).
728    if transform_type != 0 {
729        return decode_error("vorbis: invalid transform type for mode");
730    }
731
732    // Mapping number must be exist.
733    if mapping >= max_mapping {
734        return decode_error("vorbis: invalid mode mapping");
735    }
736
737    let mode = Mode { block_flag, mapping };
738
739    Ok(mode)
740}
741
742/// Map a Vorbis channel index to an audio buffer channel index given the channel map implied by the
743/// total number of channels.
744///
745/// See channel map as defined in section 4.3.9 of the Vorbis I specification.
746pub fn map_vorbis_channel(num_channels: u8, ch: usize) -> usize {
747    // This pre-condition should always be true.
748    assert!(ch < usize::from(num_channels));
749
750    let mapped_ch: u8 = match num_channels {
751        1 => [0][ch],                      // FL
752        2 => [0, 1][ch],                   // FL, FR
753        3 => [0, 2, 1][ch],                // FL, FC, FR
754        4 => [0, 1, 2, 3][ch],             // FL, FR, RL, RR
755        5 => [0, 2, 1, 3, 4][ch],          // FL, FC, FR, RL, RR
756        6 => [0, 2, 1, 4, 5, 3][ch],       // FL, FC, FR, RL, RR, LFE
757        7 => [0, 2, 1, 5, 6, 4, 3][ch],    // FL, FC, FR, SL, SR, RC, LFE
758        8 => [0, 2, 1, 6, 7, 4, 5, 3][ch], // FL, FC, FR, SL, SR, RL, RR, LFE
759        _ => return ch,
760    };
761
762    usize::from(mapped_ch)
763}