1#![warn(rust_2018_idioms)]
9#![forbid(unsafe_code)]
10#![allow(clippy::comparison_chain)]
13#![allow(clippy::excessive_precision)]
14#![allow(clippy::identity_op)]
15#![allow(clippy::manual_range_contains)]
16#![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
47pub struct VorbisDecoder {
49 params: CodecParameters,
51 ident: IdentHeader,
53 codebooks: Vec<VorbisCodebook>,
55 floors: Vec<Box<dyn Floor>>,
57 residues: Vec<Residue>,
59 modes: Vec<Mode>,
61 mappings: Vec<Mapping>,
63 dsp: Dsp,
65 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 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 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 (self.ident.bs0_exp, &mut self.dsp.imdct_short)
102 };
103
104 let n = 1 << bs_exp;
106 let n2 = n >> 1;
107
108 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 floor.read_channel(&mut bs, &self.codebooks)?;
119
120 ch.do_not_decode = floor.is_unused();
121
122 if !ch.do_not_decode {
123 floor.synthesis(bs_exp, &mut ch.floor)?;
127 }
128 else {
129 ch.floor[..n2].fill(0.0);
131 }
132 }
133
134 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 for (submap_idx, submap) in mapping.submaps.iter().enumerate() {
154 let mut residue_channels: BitSet256 = Default::default();
155
156 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 for coupling in mapping.couplings.iter() {
177 debug_assert!(coupling.magnitude_ch != coupling.angle_ch);
178
179 let (magnitude_ch, angle_ch) = if coupling.magnitude_ch < coupling.angle_ch {
181 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 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 for channel in self.dsp.channels.iter_mut() {
217 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 self.buf.clear();
230
231 if let Some(lap_state) = &self.dsp.lapping_state {
235 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 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 self.buf.trim(packet.trim_start() as usize, packet.trim_end() as usize);
260
261 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 if params.codec != CODEC_TYPE_VORBIS {
272 return unsupported_error("vorbis: invalid codec type");
273 }
274
275 let extra_data = match params.extra_data.as_ref() {
277 Some(buf) => buf,
278 _ => return unsupported_error("vorbis: missing extra data"),
279 };
280
281 let mut reader = BufReader::new(extra_data);
283
284 let ident = read_ident_header(&mut reader)?;
286
287 let setup = read_setup(&mut reader, &ident)?;
289
290 let windows = Windows::new(1 << ident.bs0_exp, 1 << ident.bs1_exp);
292
293 let dsp_channels =
295 (0..ident.n_channels).map(|_| DspChannel::new(ident.bs0_exp, ident.bs1_exp)).collect();
296
297 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 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 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
367const VORBIS_PACKET_TYPE_IDENTIFICATION: u8 = 1;
369const VORBIS_PACKET_TYPE_SETUP: u8 = 5;
371
372const VORBIS_HEADER_PACKET_SIGNATURE: &[u8] = b"vorbis";
374
375const VORBIS_VERSION: u32 = 0;
377
378const VORBIS_BLOCKSIZE_MIN: u8 = 6;
380const VORBIS_BLOCKSIZE_MAX: u8 = 13;
382
383fn read_ident_header<B: ReadBytes>(reader: &mut B) -> Result<IdentHeader> {
384 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 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 let version = reader.read_u32()?;
401
402 if version != VORBIS_VERSION {
403 return unsupported_error("vorbis: only vorbis 1 is supported");
404 }
405
406 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 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 let _bitrate_max = reader.read_u32()?;
426 let _bitrate_nom = reader.read_u32()?;
427 let _bitrate_min = reader.read_u32()?;
428
429 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 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 if bs0_exp > bs1_exp {
446 return decode_error("vorbis: blocksize_0 exceeds blocksize_1");
447 }
448
449 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 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 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 let mut bs = BitReaderRtl::new(reader.read_buf_bytes_available_ref());
483
484 let codebooks = read_codebooks(&mut bs)?;
486
487 read_time_domain_transforms(&mut bs)?;
489
490 let floors = read_floors(&mut bs, ident.bs0_exp, ident.bs1_exp, codebooks.len() as u8)?;
492
493 let residues = read_residues(&mut bs, codebooks.len() as u8)?;
495
496 let mappings =
498 read_mappings(&mut bs, ident.n_channels, floors.len() as u8, residues.len() as u8)?;
499
500 let modes = read_modes(&mut bs, mappings.len() as u8)?;
502
503 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 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 let coupling_steps = bs.read_bits_leq32(8)? as u16 + 1;
633
634 couplings.reserve_exact(usize::from(coupling_steps));
636
637 let max_ch = audio_channels - 1;
639
640 let coupling_bits = ilog(u32::from(max_ch));
642 debug_assert!(coupling_bits <= 8);
643
644 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 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 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 let _ = bs.read_bits_leq32(8)?;
687
688 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 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 if window_type != 0 {
724 return decode_error("vorbis: invalid window type for mode");
725 }
726
727 if transform_type != 0 {
729 return decode_error("vorbis: invalid transform type for mode");
730 }
731
732 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
742pub fn map_vorbis_channel(num_channels: u8, ch: usize) -> usize {
747 assert!(ch < usize::from(num_channels));
749
750 let mapped_ch: u8 = match num_channels {
751 1 => [0][ch], 2 => [0, 1][ch], 3 => [0, 2, 1][ch], 4 => [0, 1, 2, 3][ch], 5 => [0, 2, 1, 3, 4][ch], 6 => [0, 2, 1, 4, 5, 3][ch], 7 => [0, 2, 1, 5, 6, 4, 3][ch], 8 => [0, 2, 1, 6, 7, 4, 5, 3][ch], _ => return ch,
760 };
761
762 usize::from(mapped_ch)
763}