1use super::Decoded;
8use super::backend;
9use crate::{Error, Layout};
10
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum Backend {
15 #[default]
17 Auto,
18 Software,
20}
21
22#[derive(Clone, Debug, Default)]
24#[non_exhaustive]
25pub struct Config {
26 pub backend: Backend,
28}
29
30impl Config {
31 pub fn new() -> Self {
33 Self::default()
34 }
35}
36
37pub struct Decoder {
42 backend: Box<dyn backend::Backend>,
43 delay: usize,
45 delay_remaining: usize,
46}
47
48impl Decoder {
49 pub fn new(catalog: &hang::catalog::AudioConfig, config: &Config) -> Result<Self, Error> {
58 let backend = backend::open(catalog, config)?;
59 let delay = backend.delay();
60 Ok(Self {
61 backend,
62 delay,
63 delay_remaining: delay,
64 })
65 }
66
67 pub fn name(&self) -> &str {
69 self.backend.name()
70 }
71
72 pub fn sample_rate(&self) -> u32 {
74 self.backend.sample_rate()
75 }
76
77 pub fn layout(&self) -> Layout {
79 self.backend.layout()
80 }
81
82 pub fn reset(&mut self) -> Result<(), Error> {
84 self.backend.reset()?;
85 self.reapply_delay();
86 Ok(())
87 }
88
89 pub(super) fn reapply_delay(&mut self) {
91 self.delay_remaining = self.delay;
92 }
93
94 pub(super) fn conceals(&self) -> bool {
96 self.backend.conceals()
97 }
98
99 pub(super) fn delay_remaining(&self) -> usize {
105 self.delay_remaining
106 }
107
108 pub fn decode(&mut self, packet: &[u8]) -> Result<(), Error> {
121 self.backend.decode(packet)
122 }
123
124 pub fn receive(&mut self) -> Result<Option<Decoded>, Error> {
129 let Some(mut output) = self.backend.receive()? else {
130 return Ok(None);
131 };
132 let channels = self.backend.layout().channels() as usize;
133 let trim = self.delay_remaining.min(output.samples.len() / channels);
134 if trim > 0 {
135 output.samples.drain(..trim * channels);
136 self.delay_remaining -= trim;
137 }
138 Ok(Some(output))
139 }
140
141 pub fn flush(&mut self) -> Result<(), Error> {
145 self.backend.flush()
146 }
147
148 #[cfg(test)]
150 pub(crate) fn decode_all(&mut self, packet: &[u8]) -> Result<Vec<Decoded>, Error> {
151 self.decode(packet)?;
152 self.ready()
153 }
154
155 #[cfg(test)]
157 pub(crate) fn flush_all(&mut self) -> Result<Vec<Decoded>, Error> {
158 self.flush()?;
159 self.ready()
160 }
161
162 #[cfg(test)]
163 fn ready(&mut self) -> Result<Vec<Decoded>, Error> {
164 std::iter::from_fn(|| self.receive().transpose()).collect()
165 }
166}
167
168#[cfg(test)]
169pub(crate) mod tests {
170 use super::*;
171
172 const AAC_DESCRIPTION: &[u8] = b"\x12\x08";
183
184 const AAC_FRAMES: [&[u8]; 3] = [
185 b"\x01\x52\xf2\x8b\x1a\xd7\x8e\x7b\xfd\xa7\xef\xe7\xe3\x55\xd3\x4d\x2f\x55\x2e\x47\x1c\x92\x49\x11\x20\x77\x3f\xbe\x74\xdd\x99\xb3\x7b\xfb\x90\xc9\xf0\x61\x9f\xdc\x0c\x9f\x06\x19\xfd\xe1\x1f\x1f\x00\x67\xf7\x03\x87\xc0\x19\xfd\xc0\xc9\xf0\x07",
186 b"\x01\x1e\x32\x89\xe2\x9d\x6b\x33\xe7\xff\xe2\xfe\xbf\xfa\xff\xe7\x2f\x8b\xd5\xd5\xe7\x5f\x3f\x59\xeb\xf1\xcb\xba\xa5\x5e\x52\x4a\xbd\x8d\x74\x50\x8c\x08\xa8\xa0\xd4\x51\x40\xa1\x86\x5d\x06\xb4\x6c\x32\xe6\x25\x9a\x66\x75\xcd\xf9\xbf\x6f\x83\xb7\x53\x80",
187 b"\x01\x1e\x32\x8a\x22\x7d\x40\x87\x48\xdb\xdf\xff\xf9\x4f\xff\x87\xde\xef\x8b\xeb\x1e\x77\x5d\xfc\x67\x8f\x8c\x77\x8a\xd6\x29\x96\x1f\x29\xe7\x39\xd4\x53\xcf\x3c\xf3\xce\x79\xd4\x27\x9c\xf5\x65\x2a\x9b\xe9\x80\xb7\xba\xa9\xf9\x58\xc7\x3c\x58\x27\x8a\x60\xa1\x57",
188 ];
189
190 fn aac_catalog() -> hang::catalog::AudioConfig {
191 let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AAC { profile: 2 }, 44_100, 1);
192 catalog.description = Some(bytes::Bytes::from_static(AAC_DESCRIPTION));
193 catalog
194 }
195
196 struct Pipelined {
200 held: Option<Decoded>,
201 ready: std::collections::VecDeque<Decoded>,
202 }
203
204 const PIPELINED_DELAY: usize = 3;
206
207 impl backend::Backend for Pipelined {
208 fn decode(&mut self, packet: &[u8]) -> Result<(), Error> {
209 let output = Decoded {
210 samples: packet.iter().map(|&byte| f32::from(byte)).collect(),
211 activity: crate::Activity::Active,
212 };
213 match self.held.take() {
214 Some(held) => self.ready.extend([held, output]),
215 None => self.held = Some(output),
216 }
217 Ok(())
218 }
219
220 fn receive(&mut self) -> Result<Option<Decoded>, Error> {
221 Ok(self.ready.pop_front())
222 }
223
224 fn flush(&mut self) -> Result<(), Error> {
225 self.ready.extend(self.held.take());
226 Ok(())
227 }
228
229 fn reset(&mut self) -> Result<(), Error> {
230 self.held = None;
231 self.ready.clear();
232 Ok(())
233 }
234
235 fn sample_rate(&self) -> u32 {
236 48_000
237 }
238
239 fn layout(&self) -> Layout {
240 Layout::Mono
241 }
242
243 fn delay(&self) -> usize {
244 PIPELINED_DELAY
245 }
246
247 fn name(&self) -> &str {
248 "pipelined"
249 }
250 }
251
252 fn pipelined() -> Decoder {
253 Decoder {
254 backend: Box::new(Pipelined {
255 held: None,
256 ready: Default::default(),
257 }),
258 delay: PIPELINED_DELAY,
259 delay_remaining: PIPELINED_DELAY,
260 }
261 }
262
263 fn samples(outputs: Vec<Decoded>) -> Vec<Vec<f32>> {
264 outputs.into_iter().map(|output| output.samples).collect()
265 }
266
267 #[test]
271 fn held_output_is_trimmed_in_order_and_flushed() {
272 let mut decoder = pipelined();
273 assert!(decoder.decode_all(&[1, 1]).unwrap().is_empty());
274 assert_eq!(decoder.delay_remaining(), PIPELINED_DELAY, "nothing emerged to trim");
275
276 assert_eq!(samples(decoder.decode_all(&[2, 2]).unwrap()), [vec![], vec![2.0]]);
278 assert_eq!(decoder.delay_remaining(), 0);
279
280 assert!(decoder.decode_all(&[3, 3]).unwrap().is_empty());
281 assert_eq!(samples(decoder.flush_all().unwrap()), [vec![3.0, 3.0]]);
282 assert!(decoder.flush_all().unwrap().is_empty());
283
284 assert!(decoder.decode_all(&[4]).unwrap().is_empty());
285 assert_eq!(samples(decoder.decode_all(&[5]).unwrap()), [vec![4.0], vec![5.0]]);
286 }
287
288 #[test]
290 fn reset_drops_held_output() {
291 let mut decoder = pipelined();
292 assert!(decoder.decode_all(&[1; 4]).unwrap().is_empty());
293 assert_eq!(samples(decoder.decode_all(&[2; 4]).unwrap()), [vec![1.0], vec![2.0; 4]]);
294 assert!(decoder.decode_all(&[3; 4]).unwrap().is_empty());
295
296 decoder.reset().unwrap();
297 assert!(decoder.flush_all().unwrap().is_empty());
298 assert!(decoder.decode_all(&[4; 4]).unwrap().is_empty());
299 assert_eq!(samples(decoder.flush_all().unwrap()), [vec![4.0]]);
300 }
301
302 #[test]
304 fn decoder_is_unwind_safe() {
305 fn assert_unwind_safe<T: std::panic::UnwindSafe + std::panic::RefUnwindSafe>() {}
306 assert_unwind_safe::<Decoder>();
307 }
308
309 #[test]
310 fn aac_decodes_a_sine() {
311 let mut decoder = Decoder::new(&aac_catalog(), &Config::default()).unwrap();
312 assert_eq!(decoder.name(), "symphonia");
313 assert_eq!(decoder.sample_rate(), 44_100);
314 assert_eq!(decoder.layout(), Layout::Mono);
315
316 let decoded: Vec<Vec<f32>> = AAC_FRAMES
317 .iter()
318 .map(|frame| crate::single(decoder.decode_all(frame).unwrap()).samples)
319 .collect();
320
321 for pcm in &decoded {
323 assert_eq!(pcm.len(), 1024);
324 }
325
326 let last = decoded.last().unwrap();
330 let rms = (last.iter().map(|s| s * s).sum::<f32>() / last.len() as f32).sqrt();
331 assert!((0.65..0.8).contains(&rms), "expected a full-scale sine, got {rms} RMS");
332 }
333
334 #[test]
335 fn aac_reports_a_truncated_packet_as_decode() {
336 let mut decoder = Decoder::new(&aac_catalog(), &Config::default()).unwrap();
337
338 let truncated = &AAC_FRAMES[0][..16];
339 assert!(matches!(decoder.decode(truncated), Err(Error::Decode(_))));
340 }
341
342 #[test]
343 fn aac_without_a_description_refuses_raw_packets() {
344 let mut catalog = aac_catalog();
345 catalog.description = None;
346
347 let mut decoder = Decoder::new(&catalog, &Config::default()).unwrap();
348 assert_eq!(decoder.sample_rate(), 44_100);
349 assert!(matches!(decoder.decode(AAC_FRAMES[0]), Err(Error::Decode(_))));
350 }
351
352 #[test]
353 fn aac_without_a_description_decodes_adts() {
354 let mut catalog = aac_catalog();
355 catalog.description = None;
356 for crc in [false, true] {
357 let mut adts = Decoder::new(&catalog, &Config::default()).unwrap();
358 let mut raw = Decoder::new(&aac_catalog(), &Config::default()).unwrap();
359 for frame in AAC_FRAMES {
360 let len = frame.len() + if crc { 9 } else { 7 };
361 let mut packet = vec![
362 0xff,
363 if crc { 0xf0 } else { 0xf1 },
364 0x50,
365 0x40 | (len >> 11) as u8,
366 (len >> 3) as u8,
367 ((len & 7) << 5) as u8 | 0x1f,
368 0xfc,
369 ];
370 if crc {
371 packet.extend_from_slice(&[0, 0]);
372 }
373 packet.extend_from_slice(frame);
374 let got = crate::single(adts.decode_all(&packet).unwrap()).samples;
375 let expected = crate::single(raw.decode_all(frame).unwrap()).samples;
376 assert!(got == expected, "ADTS framing changed decoded PCM");
377 for altered in [2, 3, 6] {
378 let mut invalid = packet.clone();
379 invalid[altered] ^= if altered == 2 {
380 4
381 } else if altered == 3 {
382 0xc0
383 } else {
384 1
385 };
386 assert!(matches!(adts.decode(&invalid), Err(Error::Decode(_))));
387 }
388 assert!(matches!(
389 adts.decode(&packet[..packet.len() - 1]),
390 Err(Error::Decode(_))
391 ));
392 }
393 }
394 }
395
396 #[test]
397 fn cmaf_aac_samples_remain_raw_without_a_catalog_description() {
398 let mut catalog = aac_catalog();
399 catalog.description = None;
400 catalog.container = hang::catalog::Container::Cmaf {
401 init: bytes::Bytes::new(),
402 };
403 let mut decoder = Decoder::new(&catalog, &Config::default()).unwrap();
404 assert_eq!(
405 crate::single(decoder.decode_all(AAC_FRAMES[0]).unwrap()).samples.len(),
406 1024
407 );
408 }
409
410 #[test]
414 fn opus_reports_a_rejected_packet_as_decode() {
415 let head = moq_mux::codec::opus::Config::new(48_000, 2).encode().unwrap();
416 let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2);
417 catalog.description = Some(head);
418
419 let mut decoder = Decoder::new(&catalog, &Config::default()).unwrap();
420
421 assert!(matches!(decoder.decode(&[0xFF; 3]), Err(Error::Decode(_))));
423 }
424
425 pub(crate) fn opus_packets(count: usize) -> Vec<bytes::Bytes> {
428 let mut encoder = crate::encode::Encoder::new(&crate::encode::Config::new(48_000, Layout::Mono)).unwrap();
429 let frames = encoder.frame_size();
430 (0..count)
431 .map(|packet| {
432 let pcm: Vec<f32> = (packet * frames..(packet + 1) * frames)
433 .map(|i| (std::f32::consts::TAU * 440.0 * i as f32 / 48_000.0).sin() * 0.5)
434 .collect();
435 crate::single(encoder.encode_all(&pcm).unwrap()).payload
436 })
437 .collect()
438 }
439
440 pub(crate) fn opus_catalog(head: moq_mux::codec::opus::Config) -> hang::catalog::AudioConfig {
442 let mut catalog =
443 hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, head.sample_rate, head.channel_count);
444 catalog.description = Some(head.encode().unwrap());
445 catalog
446 }
447
448 fn rms(samples: &[f32]) -> f32 {
449 (samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32).sqrt()
450 }
451
452 #[test]
455 fn opus_decodes_at_48k_whatever_the_input_rate() {
456 let packets = opus_packets(2);
457 for input_rate in [0, 8_000, 24_000, 44_100, 48_000, 96_000] {
458 let head = moq_mux::codec::opus::Config::new(input_rate, 1).with_pre_skip(312);
459 let mut decoder = Decoder::new(&opus_catalog(head), &Config::default()).unwrap();
460 assert_eq!(decoder.sample_rate(), 48_000, "input rate {input_rate}");
461
462 assert_eq!(
464 crate::single(decoder.decode_all(&packets[0]).unwrap()).samples.len(),
465 960 - 312
466 );
467 assert_eq!(
468 crate::single(decoder.decode_all(&packets[1]).unwrap()).samples.len(),
469 960
470 );
471 }
472 }
473
474 #[test]
477 fn opus_conceals_the_length_of_the_last_packet() {
478 let packets = opus_packets(3);
479 let mut decoder = Decoder::new(
480 &opus_catalog(moq_mux::codec::opus::Config::new(48_000, 1)),
481 &Config::default(),
482 )
483 .unwrap();
484
485 assert!(matches!(decoder.decode(&[]), Err(Error::Decode(_))));
487
488 for packet in &packets {
489 crate::single(decoder.decode_all(packet).unwrap());
490 }
491 assert!(decoder.conceals());
492 assert_eq!(crate::single(decoder.decode_all(&[]).unwrap()).samples.len(), 960);
493
494 assert_eq!(crate::single(decoder.decode_all(&[]).unwrap()).samples.len(), 960);
496 }
497
498 fn voice(bitrate: u64, frames: usize, silent: usize) -> (crate::encode::Encoder, Vec<crate::encode::Encoded>) {
501 let mut encoder = crate::encode::Encoder::new(&crate::encode::Config {
502 kind: Some(crate::encode::Kind::Voice),
503 bitrate: Some(moq_net::bandwidth::Rate::from_bps(bitrate)),
504 ..crate::encode::Config::new(48_000, Layout::Mono)
505 })
506 .unwrap();
507 let size = encoder.frame_size();
508 let packets = (0..frames + silent)
509 .map(|frame| {
510 let pcm: Vec<f32> = (frame * size..(frame + 1) * size)
511 .map(|i| match frame < frames {
512 true => (std::f32::consts::TAU * 440.0 * i as f32 / 48_000.0).sin() * 0.5,
513 false => 0.0,
514 })
515 .collect();
516 crate::single(encoder.encode_all(&pcm).unwrap())
517 })
518 .collect();
519 (encoder, packets)
520 }
521
522 #[test]
525 fn opus_conceals_silk_and_hybrid() {
526 for (bitrate, modes) in [(12_000, 0..12), (32_000, 12..16)] {
528 let (encoder, packets) = voice(bitrate, 10, 0);
529 let mut decoder = Decoder::new(&encoder.catalog(), &Config::default()).unwrap();
530 let mut last = Vec::new();
531 for packet in &packets {
532 assert!(
533 modes.contains(&(packet.payload[0] >> 3)),
534 "{bitrate}: mode {}",
535 packet.payload[0] >> 3
536 );
537 last = crate::single(decoder.decode_all(&packet.payload).unwrap()).samples;
538 }
539 let level = rms(&last);
540 assert!(decoder.conceals());
541
542 let concealed: Vec<f32> = (0..5)
543 .map(|_| rms(&crate::single(decoder.decode_all(&[]).unwrap()).samples))
544 .collect();
545 assert!(
547 concealed.iter().all(|&rms| rms < 1.5 * level),
548 "{bitrate}: {level} then {concealed:?}"
549 );
550 assert!(
551 concealed[0] > 0.2 * level,
552 "{bitrate}: concealed silence, {concealed:?}"
553 );
554 assert!(concealed[4] < 0.5 * concealed[0], "{bitrate}: no fade, {concealed:?}");
555
556 decoder.reset().unwrap();
557 assert!(!decoder.conceals());
558 assert!(matches!(decoder.decode(&[]), Err(Error::Decode(_))));
559 }
560 }
561
562 #[test]
565 fn opus_silk_dtx_is_quiet() {
566 for bitrate in [12_000, 32_000] {
567 let (encoder, packets) = voice(bitrate, 10, 40);
568 let mut decoder = Decoder::new(&encoder.catalog(), &Config::default()).unwrap();
569 let mut dtx = 0;
570 for packet in &packets {
571 let decoded = crate::single(decoder.decode_all(&packet.payload).unwrap());
572 if packet.payload.len() <= 2 {
573 dtx += 1;
574 assert!(decoded.activity.is_dtx());
575 let peak = decoded.samples.iter().fold(0f32, |peak, s| peak.max(s.abs()));
576 assert!(
577 peak < 0.05,
578 "{bitrate}: DTX packet {:?} peaks at {peak}",
579 packet.payload
580 );
581 }
582 }
583 assert!(dtx > 10, "{bitrate}: only {dtx} DTX packets");
584 }
585 }
586
587 #[test]
588 fn opus_applies_the_declared_gain() {
589 let packets = opus_packets(5);
590 let decode = |output_gain: i16| {
591 let mut head = moq_mux::codec::opus::Config::new(48_000, 1);
592 head.output_gain = output_gain;
593 let mut decoder = Decoder::new(&opus_catalog(head), &Config::default()).unwrap();
594 let mut last = Vec::new();
595 for packet in &packets {
596 last = crate::single(decoder.decode_all(packet).unwrap()).samples;
597 }
598 decoder.reset().unwrap();
600 let reset = crate::single(decoder.decode_all(&packets[4]).unwrap()).samples;
601 (rms(&last), rms(&reset))
602 };
603
604 let (plain, plain_reset) = decode(0);
606 let (quiet, quiet_reset) = decode(-1541);
607 assert!((quiet / plain - 0.5).abs() < 0.001, "gain ratio {}", quiet / plain);
608 assert!(
609 (quiet_reset / plain_reset - 0.5).abs() < 0.001,
610 "gain ratio after reset {}",
611 quiet_reset / plain_reset
612 );
613 }
614
615 #[test]
618 fn opus_refuses_a_malformed_description() {
619 let valid = moq_mux::codec::opus::Config::new(48_000, 2).encode().unwrap().to_vec();
620 let mut version = valid.clone();
621 version[8] = 16;
622 let mut channels = valid.clone();
623 channels[9] = 3;
624 let mut signature = valid.clone();
625 signature[0] = b'X';
626 let mut table = valid.clone();
628 table[18] = 1;
629
630 for (name, description) in [
631 ("truncated", valid[..18].to_vec()),
632 ("empty", Vec::new()),
633 ("signature", signature),
634 ("version", version),
635 ("channels", channels),
636 ("table", table),
637 ] {
638 let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2);
639 catalog.description = Some(description.into());
640 assert!(
641 matches!(Decoder::new(&catalog, &Config::default()), Err(Error::Unsupported(_))),
642 "{name}"
643 );
644 }
645 }
646
647 #[test]
649 fn opus_decodes_without_a_description() {
650 let packets = opus_packets(1);
651 let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 24_000, 1);
652 let mut decoder = Decoder::new(&catalog, &Config::default()).unwrap();
653 assert_eq!(decoder.sample_rate(), 48_000);
654 assert_eq!(
655 crate::single(decoder.decode_all(&packets[0]).unwrap()).samples.len(),
656 960
657 );
658
659 let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 6);
660 assert!(matches!(
661 Decoder::new(&catalog, &Config::default()),
662 Err(Error::Unsupported(_))
663 ));
664 }
665
666 #[test]
667 fn pcm_rejects_incomplete_channel_frame() {
668 let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 2);
669 let mut decoder = Decoder::new(&catalog, &Config::default()).unwrap();
670
671 assert!(matches!(
672 decoder.decode(&[]),
673 Err(Error::Misaligned { got: 0, expected: 8 })
674 ));
675 assert!(matches!(
676 decoder.decode(&[0; 4]),
677 Err(Error::Misaligned { got: 4, expected: 8 })
678 ));
679 }
680
681 #[test]
682 fn decoder_rejects_unknown_codec() {
683 let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Unknown("future".into()), 48_000, 2);
684
685 assert!(matches!(
686 Decoder::new(&catalog, &Config::default()),
687 Err(Error::Unsupported(_))
688 ));
689 }
690
691 #[test]
692 fn pcm_rejects_incorrect_catalog_bitrate() {
693 let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 2);
694 catalog.bitrate = Some(1);
695
696 assert!(matches!(
697 Decoder::new(&catalog, &Config::default()),
698 Err(Error::Unsupported(_))
699 ));
700 }
701}