Skip to main content

moq_audio/decode/
decoder.rs

1//! Audio decoder front end.
2//!
3//! Mirror of [`encode::Encoder`](crate::encode::Encoder): opens a
4//! [backend](super::backend::Backend) for the catalog codec and trims its
5//! startup delay, producing interleaved `f32` PCM.
6
7use super::Decoded;
8use super::backend;
9use crate::{Error, Layout};
10
11/// Decoder backend selection.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum Backend {
15	/// Prefer a platform decoder, falling back to software.
16	#[default]
17	Auto,
18	/// Require a software backend.
19	Software,
20}
21
22/// Low-level decoder configuration.
23#[derive(Clone, Debug, Default)]
24#[non_exhaustive]
25pub struct Config {
26	/// Backend selection policy.
27	pub backend: Backend,
28}
29
30impl Config {
31	/// Select the available backend automatically.
32	pub fn new() -> Self {
33		Self::default()
34	}
35}
36
37/// Decodes codec packets into interleaved `f32` PCM.
38///
39/// The bring-your-own-payload layer under [`Consumer`](super::Consumer): use it
40/// when the packets don't come from a plain track subscription.
41pub struct Decoder {
42	backend: Box<dyn backend::Backend>,
43	/// Startup delay in native-rate frames, and how much of it is left to trim.
44	delay: usize,
45	delay_remaining: usize,
46}
47
48impl Decoder {
49	/// Build a decoder from a catalog [`AudioConfig`](hang::catalog::AudioConfig).
50	///
51	/// Opus decodes at 48 kHz with the pre-skip and gain its OpusHead
52	/// `description` declares, refusing a malformed head; without a description
53	/// it takes the catalog's channel count and applies neither. PCM uses the
54	/// catalog fields directly and requires an absent `description`. AAC reads
55	/// its AudioSpecificConfig; without one, legacy and LOC packets carry ADTS headers,
56	/// while demuxed CMAF samples remain raw.
57	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	/// The decoder backend name in use, e.g. `"libopus"` or `"symphonia"`.
68	pub fn name(&self) -> &str {
69		self.backend.name()
70	}
71
72	/// The rate the codec decodes at, which may differ from the catalog's.
73	pub fn sample_rate(&self) -> u32 {
74		self.backend.sample_rate()
75	}
76
77	/// The PCM layout the codec decodes to.
78	pub fn layout(&self) -> Layout {
79		self.backend.layout()
80	}
81
82	/// Reset codec history and reapply startup delay for a new discontinuous epoch.
83	pub fn reset(&mut self) -> Result<(), Error> {
84		self.backend.reset()?;
85		self.reapply_delay();
86		Ok(())
87	}
88
89	/// Reapply catalog startup delay for a new playhead epoch without resetting codec prediction.
90	pub(super) fn reapply_delay(&mut self) {
91		self.delay_remaining = self.delay;
92	}
93
94	/// Whether an empty packet now conceals one lost packet.
95	pub(super) fn conceals(&self) -> bool {
96		self.backend.conceals()
97	}
98
99	/// How much startup delay is still to be trimmed, in native-rate frames.
100	///
101	/// Trimmed samples are media the packet covered even though nothing came out of
102	/// it, so a caller tracking where a packet ends has to add back whatever this
103	/// dropped across the call.
104	pub(super) fn delay_remaining(&self) -> usize {
105		self.delay_remaining
106	}
107
108	/// Submit one packet, whose interleaved `f32` PCM [`receive`](Self::receive)
109	/// returns.
110	///
111	/// A codec that pipelines holds a packet's samples past later packets;
112	/// libopus, PCM, and symphonia ready exactly one output per packet at once.
113	/// Call [`flush`](Self::flush) after the last packet for whatever is still held.
114	///
115	/// An empty Opus packet marks one lost packet and conceals as much audio as the
116	/// last packet that decoded held, so a lost 20 ms packet yields 20 ms. It is
117	/// refused with [`Error::Decode`] before any packet has decoded since the last
118	/// [`reset`](Self::reset), since there is no length to conceal. Loss during DTX
119	/// remains classified as DTX, while loss during active audio remains active.
120	pub fn decode(&mut self, packet: &[u8]) -> Result<(), Error> {
121		self.backend.decode(packet)
122	}
123
124	/// Pop the oldest ready output in stream order, with its codec activity and
125	/// any startup delay left trimmed off, or `None` while the codec holds the rest.
126	///
127	/// Call until `None` after each [`decode`](Self::decode) or [`flush`](Self::flush).
128	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	/// Mark the end of input, once the stream has ended or before a boundary its
142	/// output has to respect, so [`receive`](Self::receive) returns every output
143	/// the codec still holds. Packets decoded afterwards start new input.
144	pub fn flush(&mut self) -> Result<(), Error> {
145		self.backend.flush()
146	}
147
148	/// Submit `packet` and take every output it readied.
149	#[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	/// Flush and take every output the codec held.
156	#[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	/// Three consecutive AAC-LC frames of a 440 Hz full-scale sine, mono at
173	/// 44.1 kHz, and the AudioSpecificConfig that opens them. Generated with:
174	///
175	/// ```text
176	/// ffmpeg -f lavfi -i "sine=frequency=440:sample_rate=44100:duration=0.2" -af volume=8 -ac 1 -c:a aac -b:a 32k -f adts sine.aac
177	/// ```
178	///
179	/// then stripping the ADTS header off each frame, since the wire carries raw
180	/// AAC. These are frames 2 to 4, past the encoder's priming. lavfi's sine is
181	/// an eighth of full scale, which is what the volume filter is undoing.
182	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	/// Decodes each byte to one mono sample of its value, and pipelines like a
197	/// platform decoder: it holds every other packet's output and releases it with
198	/// the next, so submissions alternate between readying no output and two.
199	struct Pipelined {
200		held: Option<Decoded>,
201		ready: std::collections::VecDeque<Decoded>,
202	}
203
204	/// Frames of startup delay [`Pipelined`] declares.
205	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	/// Held output comes back in order, the startup delay is trimmed across
268	/// outputs as they emerge rather than as packets arrive, and `flush` returns
269	/// the tail while leaving the decoder usable.
270	#[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		// Three frames of delay take all of the first output and one of the second.
277		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	/// A reset drops held output and reapplies the startup delay to what follows.
289	#[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	/// The published `Decoder` was unwind safe before it boxed a backend; keep it so.
303	#[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		// AAC-LC frames are 1024 samples each, whatever the packet size.
322		for pcm in &decoded {
323			assert_eq!(pcm.len(), 1024);
324		}
325
326		// The first frame is missing the previous frame's overlap, so measure the
327		// last one. ffmpeg decodes this same frame to 0.744 RMS, near the 0.707 of
328		// an ideal full-scale sine.
329		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	/// A packet libopus rejects is that packet's problem, not the
411	/// configuration's. The distinction is what lets a consumer drop the frame and
412	/// keep the subscription instead of ending the stream over one bad packet.
413	#[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		// Not a valid TOC byte sequence: libopus reports OPUS_INVALID_PACKET.
422		assert!(matches!(decoder.decode(&[0xFF; 3]), Err(Error::Decode(_))));
423	}
424
425	/// Real Opus: 20 ms packets of a continuous 440 Hz sine, mono, from libopus
426	/// with its 312-sample lookahead.
427	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	/// A catalog shaped like an import's: the OpusHead input rate as the catalog rate.
441	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	/// The OpusHead input rate is metadata: 44.1 kHz and unknown (0) are valid
453	/// heads, and no input rate changes the 48 kHz clock the packets decode on.
454	#[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			// The pre-skip is 48 kHz samples, trimmed once.
463			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	/// One lost packet conceals one packet's worth of audio, not the 120 ms
475	/// libopus would fill given the whole buffer.
476	#[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		// Nothing decoded yet, so there is no length to conceal.
486		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		// Concealment doesn't change the length: the next loss is the same size.
495		assert_eq!(crate::single(decoder.decode_all(&[]).unwrap()).samples.len(), 960);
496	}
497
498	/// A `Voice` encoder at `bitrate`, and the packets it codes from `frames` of a 440 Hz
499	/// sine at 0.35 RMS followed by `silent` frames of silence.
500	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	/// SILK and hybrid conceal a loss by fading the audio before it, as C libopus does,
523	/// rather than at full scale; a reset leaves nothing to conceal from.
524	#[test]
525	fn opus_conceals_silk_and_hybrid() {
526		// RFC 6716 ยง3.1: TOC configurations 0 to 11 are SILK, 12 to 15 hybrid.
527		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			// Saturated concealment reads about 1.0 RMS.
546			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	/// libopus decodes a SILK or hybrid DTX packet as a loss, playing quiet comfort noise
563	/// rather than the full-scale noise a broken concealment would.
564	#[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			// A reset after loss keeps the gain.
599			decoder.reset().unwrap();
600			let reset = crate::single(decoder.decode_all(&packets[4]).unwrap()).samples;
601			(rms(&last), rms(&reset))
602		};
603
604		// -6.02 dB in Q7.8 halves the amplitude.
605		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	/// A present description is the stream's configuration, so a broken one is
616	/// refused rather than replaced by the catalog's fields.
617	#[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		// Family 1 promising a table that is not there.
627		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	/// Without a description the catalog shapes the stream, which has no pre-skip.
648	#[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}