1use std::time::Duration;
7
8use unsafe_libopus::{
9 OPUS_OK, OPUS_RESET_STATE, OpusDecoder, opus_decode_float, opus_decoder_create, opus_decoder_ctl_impl,
10 opus_decoder_destroy, varargs,
11};
12
13#[cfg(feature = "aac")]
14use symphonia_core::codecs::audio::AudioDecoder;
15
16use super::Decoded;
17#[cfg(feature = "aac")]
18use crate::aac;
19use crate::opus;
20use crate::pcm;
21use crate::{Activity, Error, Format};
22
23const MAX_FRAME_MS: usize = 120;
25
26#[derive(Clone, Debug, Default)]
35#[non_exhaustive]
36pub struct Config {
37 pub format: Format,
39 pub sample_rate: Option<u32>,
42 pub channels: Option<u32>,
45 pub latency_max: Option<Duration>,
56}
57
58impl Config {
59 pub fn new() -> Self {
62 Self::default()
63 }
64}
65
66pub struct Decoder {
71 backend: Backend,
72 sample_rate: u32,
73 channel_count: u32,
74 delay: usize,
75}
76
77enum Backend {
78 Opus(Opus),
79 Pcm {
80 bytes_per_frame: usize,
81 },
82 #[cfg(feature = "aac")]
83 Aac(Box<Aac>),
84}
85
86struct Opus {
87 inner: *mut OpusDecoder,
88 pre_skip_remaining: usize,
89 max_frame_size: usize,
90 in_dtx: bool,
91}
92
93unsafe impl Send for Opus {}
95
96#[cfg(feature = "aac")]
99struct Aac {
100 inner: symphonia_codec_aac::AacDecoder,
101}
102
103impl Decoder {
104 pub fn new(catalog: &hang::catalog::AudioConfig) -> Result<Self, Error> {
110 match &catalog.codec {
111 hang::catalog::AudioCodec::Opus => Self::new_opus(catalog),
112 hang::catalog::AudioCodec::Pcm => Self::new_pcm(catalog),
113 #[cfg(feature = "aac")]
114 hang::catalog::AudioCodec::AAC(aac) => Self::new_aac(catalog, aac.profile),
115 codec => Err(Error::Unsupported(format!("unsupported audio codec: {codec}"))),
116 }
117 }
118
119 fn new_opus(catalog: &hang::catalog::AudioConfig) -> Result<Self, Error> {
120 let (sample_rate, channel_count, pre_skip) = if let Some(desc) = &catalog.description {
121 let mut buf = desc.as_ref();
122 match moq_mux::codec::opus::Config::parse(&mut buf) {
123 Ok(head) => (head.sample_rate, head.channel_count, head.pre_skip),
124 Err(_) => (catalog.sample_rate, catalog.channel_count, 0),
125 }
126 } else {
127 (catalog.sample_rate, catalog.channel_count, 0)
128 };
129
130 opus::validate_rate(sample_rate)?;
131 let channels = opus::validate_channels(channel_count)?;
132
133 let mut err = 0i32;
134 let inner = unsafe { opus_decoder_create(sample_rate as i32, channels, &mut err) };
136 if err != OPUS_OK || inner.is_null() {
137 return Err(opus::error(err, "opus_decoder_create"));
138 }
139
140 let max_frame_size = (sample_rate as usize * MAX_FRAME_MS) / 1000;
141 let pre_skip_remaining = (pre_skip as usize * sample_rate as usize) / 48_000;
142
143 Ok(Self {
144 backend: Backend::Opus(Opus {
145 inner,
146 pre_skip_remaining,
147 max_frame_size,
148 in_dtx: false,
149 }),
150 sample_rate,
151 channel_count,
152 delay: pre_skip_remaining,
153 })
154 }
155
156 #[cfg(feature = "aac")]
165 fn new_aac(catalog: &hang::catalog::AudioConfig, profile: u8) -> Result<Self, Error> {
166 use symphonia_core::codecs::audio::well_known::CODEC_ID_AAC;
167 use symphonia_core::codecs::audio::{AudioCodecParameters, AudioDecoderOptions};
168
169 let description = aac::description(catalog, profile)?;
170
171 let mut params = AudioCodecParameters::new();
172 params
173 .for_codec(CODEC_ID_AAC)
174 .with_extra_data(description.to_vec().into_boxed_slice());
175
176 let inner = symphonia_codec_aac::AacDecoder::try_new(¶ms, &AudioDecoderOptions::default())
177 .map_err(|err| Error::Unsupported(format!("aac decoder: {err}")))?;
178
179 let params = inner.codec_params();
182 let sample_rate = params
183 .sample_rate
184 .ok_or_else(|| Error::Unsupported("aac config declares no sample rate".into()))?;
185 let channel_count = params
186 .channels
187 .as_ref()
188 .map(|channels| channels.count())
189 .ok_or_else(|| Error::Unsupported("aac config declares no channels".into()))?;
190
191 Ok(Self {
192 backend: Backend::Aac(Box::new(Aac { inner })),
193 sample_rate,
194 channel_count: channel_count as u32,
195 delay: 0,
196 })
197 }
198
199 fn new_pcm(catalog: &hang::catalog::AudioConfig) -> Result<Self, Error> {
200 if catalog.sample_rate == 0 {
201 return Err(Error::Unsupported("pcm sample rate must be greater than zero".into()));
202 }
203 if catalog.channel_count == 0 {
204 return Err(Error::Unsupported("pcm channel count must be greater than zero".into()));
205 }
206 if catalog.description.is_some() {
207 return Err(Error::Unsupported("pcm catalog description must be absent".into()));
208 }
209 let bitrate = pcm::bitrate(catalog.sample_rate, catalog.channel_count)?;
210 if catalog.bitrate.is_some_and(|declared| declared != bitrate) {
211 return Err(Error::Unsupported(format!(
212 "pcm catalog bitrate must be {bitrate} bits per second"
213 )));
214 }
215 let bytes_per_frame = pcm::frame_bytes(1, catalog.channel_count)?;
216
217 Ok(Self {
218 backend: Backend::Pcm { bytes_per_frame },
219 sample_rate: catalog.sample_rate,
220 channel_count: catalog.channel_count,
221 delay: 0,
222 })
223 }
224
225 pub fn sample_rate(&self) -> u32 {
227 self.sample_rate
228 }
229
230 pub fn channel_count(&self) -> u32 {
232 self.channel_count
233 }
234
235 pub fn reset(&mut self) -> Result<(), Error> {
237 self.reset_prediction()?;
238 if let Backend::Opus(opus) = &mut self.backend {
239 opus.pre_skip_remaining = self.delay;
240 }
241 Ok(())
242 }
243
244 pub(super) fn reset_prediction(&mut self) -> Result<(), Error> {
246 match &mut self.backend {
247 Backend::Opus(opus) => {
248 let rc = unsafe { opus_decoder_ctl_impl(opus.inner, OPUS_RESET_STATE, varargs![]) };
250 if rc != OPUS_OK {
251 return Err(crate::opus::error(rc, "OPUS_RESET_STATE"));
252 }
253 opus.in_dtx = false;
254 }
255 Backend::Pcm { .. } => {}
256 #[cfg(feature = "aac")]
257 Backend::Aac(aac) => aac.inner.reset(),
258 }
259 Ok(())
260 }
261
262 pub(super) fn delay_remaining(&self) -> usize {
268 match &self.backend {
269 Backend::Opus(opus) => opus.pre_skip_remaining,
270 Backend::Pcm { .. } => 0,
271 #[cfg(feature = "aac")]
272 Backend::Aac(_) => 0,
273 }
274 }
275
276 pub fn decode(&mut self, packet: &[u8]) -> Result<Decoded, Error> {
281 match &mut self.backend {
282 Backend::Opus(opus) => {
283 let mut out = vec![0.0f32; opus.max_frame_size * self.channel_count as usize];
284 let samples = unsafe {
287 opus_decode_float(
288 &mut *opus.inner,
289 packet.as_ptr(),
290 packet.len() as i32,
291 out.as_mut_ptr(),
292 opus.max_frame_size as i32,
293 0,
294 )
295 };
296 if samples < 0 {
297 return Err(crate::opus::decode_error(samples));
298 }
299 out.truncate(samples as usize * self.channel_count as usize);
300 let trim_frames = opus.pre_skip_remaining.min(samples as usize);
301 if trim_frames > 0 {
302 let trim_samples = trim_frames * self.channel_count as usize;
303 out.copy_within(trim_samples.., 0);
304 out.truncate(out.len() - trim_samples);
305 opus.pre_skip_remaining -= trim_frames;
306 }
307 let activity = crate::opus::activity(packet, opus.in_dtx);
308 opus.in_dtx = activity.is_dtx();
309 Ok(Decoded { samples: out, activity })
310 }
311 Backend::Pcm { bytes_per_frame } => {
312 if packet.is_empty() || !packet.len().is_multiple_of(*bytes_per_frame) {
313 return Err(Error::Misaligned {
314 got: packet.len(),
315 expected: packet.len().max(1).next_multiple_of(*bytes_per_frame),
316 });
317 }
318
319 let out = packet
320 .chunks_exact(pcm::BYTES_PER_SAMPLE)
321 .map(|sample| f32::from_le_bytes([sample[0], sample[1], sample[2], sample[3]]))
322 .collect();
323 Ok(Decoded {
324 samples: out,
325 activity: Activity::Active,
326 })
327 }
328 #[cfg(feature = "aac")]
329 Backend::Aac(aac) => {
330 let packet = symphonia_core::packet::PacketRef::new(
334 0,
335 symphonia_core::units::Timestamp::ZERO,
336 symphonia_core::units::Duration::ZERO,
337 packet,
338 );
339
340 let decoded = aac
341 .inner
342 .decode_ref(&packet)
343 .map_err(|err| Error::Decode(format!("aac: {err}")))?;
344
345 let mut out = Vec::new();
346 decoded.copy_to_vec_interleaved(&mut out);
347 Ok(Decoded {
348 samples: out,
349 activity: Activity::Active,
350 })
351 }
352 }
353 }
354}
355
356impl Drop for Opus {
357 fn drop(&mut self) {
358 unsafe { opus_decoder_destroy(self.inner) };
360 }
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 #[cfg(feature = "aac")]
378 const AAC_DESCRIPTION: &[u8] = b"\x12\x08";
379
380 #[cfg(feature = "aac")]
381 const AAC_FRAMES: [&[u8]; 3] = [
382 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",
383 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",
384 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",
385 ];
386
387 #[cfg(feature = "aac")]
388 fn aac_catalog() -> hang::catalog::AudioConfig {
389 let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AAC { profile: 2 }, 44_100, 1);
390 catalog.description = Some(bytes::Bytes::from_static(AAC_DESCRIPTION));
391 catalog
392 }
393
394 #[cfg(feature = "aac")]
395 #[test]
396 fn aac_decodes_a_sine() {
397 let mut decoder = Decoder::new(&aac_catalog()).unwrap();
398 assert_eq!(decoder.sample_rate(), 44_100);
399 assert_eq!(decoder.channel_count(), 1);
400
401 let decoded: Vec<Vec<f32>> = AAC_FRAMES
402 .iter()
403 .map(|frame| decoder.decode(frame).unwrap().samples)
404 .collect();
405
406 for pcm in &decoded {
408 assert_eq!(pcm.len(), 1024);
409 }
410
411 let last = decoded.last().unwrap();
415 let rms = (last.iter().map(|s| s * s).sum::<f32>() / last.len() as f32).sqrt();
416 assert!((0.65..0.8).contains(&rms), "expected a full-scale sine, got {rms} RMS");
417 }
418
419 #[cfg(feature = "aac")]
420 #[test]
421 fn aac_reports_a_truncated_packet_as_decode() {
422 let mut decoder = Decoder::new(&aac_catalog()).unwrap();
423
424 let truncated = &AAC_FRAMES[0][..16];
425 assert!(matches!(decoder.decode(truncated), Err(Error::Decode(_))));
426 }
427
428 #[cfg(feature = "aac")]
429 #[test]
430 fn aac_synthesizes_a_missing_description() {
431 let mut catalog = aac_catalog();
433 catalog.description = None;
434
435 let mut decoder = Decoder::new(&catalog).unwrap();
436 assert_eq!(decoder.sample_rate(), 44_100);
437 assert_eq!(decoder.decode(AAC_FRAMES[0]).unwrap().samples.len(), 1024);
438 }
439
440 #[test]
444 fn opus_reports_a_rejected_packet_as_decode() {
445 let head = moq_mux::codec::opus::Config::new(48_000, 2).encode().unwrap();
446 let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2);
447 catalog.description = Some(head);
448
449 let mut decoder = Decoder::new(&catalog).unwrap();
450
451 assert!(matches!(decoder.decode(&[0xFF; 3]), Err(Error::Decode(_))));
453 }
454
455 #[test]
456 fn pcm_rejects_incomplete_channel_frame() {
457 let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 2);
458 let mut decoder = Decoder::new(&catalog).unwrap();
459
460 assert!(matches!(
461 decoder.decode(&[]),
462 Err(Error::Misaligned { got: 0, expected: 8 })
463 ));
464 assert!(matches!(
465 decoder.decode(&[0; 4]),
466 Err(Error::Misaligned { got: 4, expected: 8 })
467 ));
468 }
469
470 #[test]
471 fn decoder_rejects_unknown_codec() {
472 let catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Unknown("future".into()), 48_000, 2);
473
474 assert!(matches!(Decoder::new(&catalog), Err(Error::Unsupported(_))));
475 }
476
477 #[test]
478 fn pcm_rejects_incorrect_catalog_bitrate() {
479 let mut catalog = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Pcm, 48_000, 2);
480 catalog.bitrate = Some(1);
481
482 assert!(matches!(Decoder::new(&catalog), Err(Error::Unsupported(_))));
483 }
484}