forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust380.6 MiBe18142dTahinli3 hours ago4543 commits

decoder.rs613 lines, 25.0 KiBHistoryRawDownload
1//! One decoder seat for every audio codec the family carries: packets in,
2//! interleaved `f32` out, in film channel order.
3//!
4//! This is the registry half of the probe. A caller that has a stream from
5//! [`crate::Reader`] asks for [`AudioDecoder::new`] and gets either a decoder
6//! or an [`ec_core::Error::Unsupported`] that names the codec *and* why nothing
7//! here decodes it — a refusal string with no capability behind it is a bug,
8//! not a message.
9
10use ec_core::error::{Error, Result};
11use ec_core::frame::{Frame, SampleFormat};
12use ec_core::packet::Packet;
13use ec_core::registry::{CodecId, CodecParameters, Decoder};
14
15/// Which family decoder is doing the work.
16enum Inner {
17 Flac(Box<ec_flac::FlacDecoder>),
18 Mp3(Box<ec_mp3::Mp3Decoder>),
19 Vorbis(Box<ec_vorbis::VorbisDecoder>),
20 Ac3(Box<ec_ac3::Ac3Decoder>),
21 TrueHd(Box<ec_truehd::TrueHdDecoder>),
22 Aac(Box<ec_aac::AacDecoder>),
23 Alac(Box<ec_alac::AlacDecoder>),
24 PcmExt(Box<ec_pcm_ext::PcmExtDecoder>),
25 AmrNb(Box<ec_amr::nb::decoder::AmrNbDecoder>),
26 AmrWb(Box<ec_amr::wb::AmrWbDecoder>),
27 Opus(Box<ec_opus::MultistreamDecoder>),
28 Dts(Box<ec_dts::DtsDecoder>),
29 /// PCM needs no decoder, only a reading of the bytes.
30 Pcm(PcmFormat),
31}
32
33/// The PCM layouts read straight from the packet bytes.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35enum PcmFormat {
36 U8,
37 S16Le,
38 S16Be,
39 S24Le,
40 S24Be,
41 S32Le,
42 S32Be,
43 F32Le,
44}
45
46impl PcmFormat {
47 fn of(codec: CodecId) -> Option<PcmFormat> {
48 Some(match codec {
49 CodecId::PcmU8 => PcmFormat::U8,
50 CodecId::PcmS16Le => PcmFormat::S16Le,
51 CodecId::PcmS16Be => PcmFormat::S16Be,
52 CodecId::PcmS24Le => PcmFormat::S24Le,
53 CodecId::PcmS24Be => PcmFormat::S24Be,
54 CodecId::PcmS32Le => PcmFormat::S32Le,
55 CodecId::PcmS32Be => PcmFormat::S32Be,
56 CodecId::PcmF32Le => PcmFormat::F32Le,
57 _ => return None,
58 })
59 }
60}
61
62/// A decoder for one audio stream.
63pub struct AudioDecoder {
64 inner: Inner,
65 codec: CodecId,
66 channels: usize,
67 sample_rate: u32,
68 /// Raw interleaved frames the decoder has produced so far, before any
69 /// trim — the running clock the front-offset calculation below measures
70 /// against.
71 produced: i64,
72 /// Frames actually handed out to the caller so far.
73 emitted: i64,
74 /// `granule - produced` at the first packet whose granule is known: a
75 /// Vorbis stream's very first pages account for the encoder's pre-roll in
76 /// their granule, so this is the one-time head start (or catch-up) the
77 /// decoder's own count needed to line up with the container's.
78 ///
79 /// This is a front offset only. An *interior* page's granule marks where
80 /// the last packet completed *on that page* ends — not a ceiling every
81 /// later page's cumulative output must stay under, since packets can span
82 /// pages and pages can end mid-packet. Only the first granule (front) and
83 /// the last one (tail, at [`Self::flush`]) are trustworthy trim points.
84 trim_offset: Option<i64>,
85 /// The last granule [`Self::decode`] saw, carried into [`Self::flush`]
86 /// for the terminal packet's own trim: the flush call's packet (the
87 /// reader's synthetic end-of-stream marker) carries no granule of its own.
88 last_granule: Option<i64>,
89}
90
91impl std::fmt::Debug for AudioDecoder {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 f.debug_struct("AudioDecoder")
94 .field("codec", &self.codec.name())
95 .field("channels", &self.channels)
96 .field("sample_rate", &self.sample_rate)
97 .finish()
98 }
99}
100
101impl AudioDecoder {
102 /// A decoder for the stream `params` describes.
103 pub fn new(params: &CodecParameters) -> Result<AudioDecoder> {
104 let audio = params
105 .audio()
106 .ok_or_else(|| Error::corrupt("a decoder was asked for on a non-audio stream"))?;
107 let channels = audio.layout.channel_count().max(1);
108 let sample_rate = audio.sample_rate;
109 let extradata = params.extradata.as_deref();
110 let inner = match params.codec {
111 CodecId::Flac => {
112 let mut params = params.clone();
113 params.extradata = flac_stream_info(extradata.unwrap_or_default())
114 .map(ec_core::packet::Buf::copy_from_slice);
115 Inner::Flac(Box::new(ec_flac::FlacDecoder::new(params)?))
116 }
117 CodecId::Mp3 | CodecId::Mp2 | CodecId::Mp1 => {
118 Inner::Mp3(Box::new(ec_mp3::Mp3Decoder::new(params.clone())?))
119 }
120 CodecId::Vorbis => {
121 let data = extradata.ok_or_else(|| {
122 Error::corrupt("a Vorbis stream with no header triplet in its extradata")
123 })?;
124 let headers = ec_ogg::xiph_unlace(data)?;
125 Inner::Vorbis(Box::new(ec_vorbis::VorbisDecoder::new(&headers)?))
126 }
127 CodecId::Ac3 | CodecId::EAc3 => Inner::Ac3(Box::new(ec_ac3::Ac3Decoder::new())),
128 CodecId::TrueHd => Inner::TrueHd(Box::new(ec_truehd::TrueHdDecoder::new())),
129 CodecId::Aac => {
130 let decoder = match extradata {
131 Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)?,
132 // ADTS states its own configuration in every frame.
133 None => ec_aac::AacDecoder::new(),
134 };
135 Inner::Aac(Box::new(decoder))
136 }
137 CodecId::Alac => Inner::Alac(Box::new(ec_alac::AlacDecoder::from_parameters(
138 params.clone(),
139 )?)),
140 CodecId::AmrNb => Inner::AmrNb(Box::new(
141 ec_amr::nb::decoder::AmrNbDecoder::from_parameters(params.clone())?,
142 )),
143 CodecId::AmrWb => Inner::AmrWb(Box::new(ec_amr::wb::AmrWbDecoder::from_parameters(
144 params.clone(),
145 )?)),
146 CodecId::ImaAdpcmWav
147 | CodecId::MsAdpcm
148 | CodecId::ImaAdpcmQt
149 | CodecId::PcmAlaw
150 | CodecId::PcmMulaw => Inner::PcmExt(Box::new(
151 ec_pcm_ext::PcmExtDecoder::from_parameters(params.clone())?,
152 )),
153 CodecId::Opus => {
154 let head = extradata.unwrap_or_default();
155 let (streams, coupled, mapping) = opus_layout(head, channels)?;
156 // 48 kHz whatever the container says: it is the only rate Opus
157 // decodes at, and the rate its timestamps are in.
158 Inner::Opus(Box::new(ec_opus::MultistreamDecoder::try_with_rate(
159 48_000, streams, coupled, &mapping,
160 )?))
161 }
162 CodecId::Dts => Inner::Dts(Box::new(ec_dts::DtsDecoder::new())),
163 codec => match PcmFormat::of(codec) {
164 Some(format) => Inner::Pcm(format),
165 None => {
166 return Err(Error::unsupported(
167 format!("the {} track", codec.name()),
168 match codec.media_type() {
169 ec_core::MediaType::Audio => {
170 "no decoder for it exists in this family (yet)"
171 }
172 _ => "this is an audio probe; picture and subtitles decode elsewhere",
173 },
174 ));
175 }
176 },
177 };
178 Ok(AudioDecoder {
179 inner,
180 codec: params.codec,
181 channels,
182 sample_rate: match params.codec {
183 CodecId::Opus => 48_000,
184 _ => sample_rate,
185 },
186 produced: 0,
187 emitted: 0,
188 trim_offset: None,
189 last_granule: None,
190 })
191 }
192
193 /// Which codec this is decoding.
194 pub fn codec(&self) -> CodecId {
195 self.codec
196 }
197
198 /// Channels the decoder emits.
199 pub fn channels(&self) -> usize {
200 self.channels
201 }
202
203 /// Rate the decoder emits at.
204 pub fn sample_rate(&self) -> u32 {
205 self.sample_rate
206 }
207
208 /// One packet in, interleaved `f32` out, normalised to -1.0..=1.0.
209 ///
210 /// `out` is cleared first: a packet that decodes to nothing (a header
211 /// packet, a frame the decoder swallowed) leaves it empty rather than
212 /// leaving the caller with the previous packet's audio.
213 pub fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> Result<()> {
214 out.clear();
215 match &mut self.inner {
216 Inner::Flac(d) => drain(d.as_mut(), packet, out)?,
217 Inner::Mp3(d) => drain(d.as_mut(), packet, out)?,
218 Inner::Vorbis(d) => drain(d.as_mut(), packet, out)?,
219 Inner::Ac3(d) => drain(d.as_mut(), packet, out)?,
220 Inner::TrueHd(d) => drain(d.as_mut(), packet, out)?,
221 Inner::Dts(d) => drain(d.as_mut(), packet, out)?,
222 Inner::Aac(d) => {
223 let audio = d.decode(&packet.data, packet.pts)?;
224 self.channels = usize::from(audio.channels).max(1);
225 if audio.sample_rate > 0 {
226 self.sample_rate = audio.sample_rate;
227 }
228 out.extend_from_slice(&audio.samples);
229 }
230 Inner::Alac(d) => {
231 let scale = match d.cookie().sample_format() {
232 SampleFormat::S16 => 1.0 / 32768.0,
233 _ => 1.0 / 2147483648.0,
234 };
235 out.extend(d.decode(&packet.data)?.iter().map(|&s| s as f32 * scale));
236 }
237 Inner::AmrNb(d) => {
238 out.extend(d.decode(&packet.data)?.iter().map(|&s| f32::from(s) / 32768.0));
239 }
240 Inner::AmrWb(d) => {
241 out.extend(d.decode(&packet.data)?.iter().map(|&s| f32::from(s) / 32768.0));
242 }
243 Inner::PcmExt(d) => {
244 out.extend(d.decode(&packet.data)?.iter().map(|&s| f32::from(s) / 32768.0));
245 }
246 Inner::Opus(d) => {
247 let samples = d.decode_packet(&packet.data)?;
248 out.extend_from_slice(&samples);
249 }
250 Inner::Pcm(format) => pcm(*format, &packet.data, out),
251 }
252 // Vorbis trims to its own page granules inside `ec-vorbis`, so its
253 // output is final as it arrives. Every other codec here is trimmed
254 // (or not) by the front and tail rules below.
255 if !matches!(self.inner, Inner::Vorbis(_)) {
256 self.trim(ec_ogg::granule_of(packet), out);
257 }
258 self.emitted += out.len() as i64 / self.channels.max(1) as i64;
259 Ok(())
260 }
261
262 /// The one-off front trim: only the very first packet this decoder ever
263 /// sees can carry a legitimate pre-roll offset (`granule` at real stream
264 /// position zero). Most containers' first *audio* packet carries no
265 /// granule at all — pages tend to end well into the block run — so once
266 /// any later packet is the first to reveal one, that granule is an
267 /// interior page mark, not a front offset: subtracting it from what has
268 /// already been decoded would assign ordinary block-to-block lag to a
269 /// pre-roll that was never there, and can trim away a whole packet's
270 /// worth of real audio. Every later packet passes through untouched — an
271 /// interior page's granule is not a per-page ceiling (see
272 /// [`Self::trim_offset`]); only [`Self::flush`]'s tail trim cuts again.
273 fn trim(&mut self, granule: Option<i64>, out: &mut Vec<f32>) {
274 let channels = self.channels.max(1) as i64;
275 let raw_frames = out.len() as i64 / channels;
276 if let Some(granule) = granule {
277 self.last_granule = Some(granule);
278 if self.trim_offset.is_none() {
279 if self.produced == 0 {
280 let offset = (granule - raw_frames).max(0);
281 self.trim_offset = Some(offset);
282 if offset > 0 {
283 let drop = (offset.min(raw_frames) * channels) as usize;
284 out.drain(0..drop);
285 }
286 } else {
287 // Too late for a real front offset: this stream's first
288 // audio packet already went by with no granule on it.
289 self.trim_offset = Some(0);
290 }
291 }
292 }
293 self.produced += raw_frames;
294 }
295
296 /// Signal end of stream and take whatever the decoder was holding back.
297 ///
298 /// Every codec here that overlaps blocks (Vorbis above all: its terminal
299 /// block's un-overlapped right half is real audio up to the stream's
300 /// final granule, and is otherwise always exactly one hop short) needs
301 /// this told to it once the packets have run out, or the last hop never
302 /// comes out at all. `out` is cleared first, same as [`Self::decode`].
303 ///
304 /// Vorbis is cut to its final granule inside `ec-vorbis` and passes
305 /// through here unchanged; the other codecs' tail is trimmed by
306 /// [`Self::trim_tail`].
307 pub fn flush(&mut self, out: &mut Vec<f32>) -> Result<()> {
308 out.clear();
309 match &mut self.inner {
310 Inner::Flac(d) => flush_drain(d.as_mut(), out)?,
311 Inner::Mp3(d) => flush_drain(d.as_mut(), out)?,
312 Inner::Vorbis(d) => flush_drain(d.as_mut(), out)?,
313 Inner::Ac3(d) => flush_drain(d.as_mut(), out)?,
314 Inner::TrueHd(d) => flush_drain(d.as_mut(), out)?,
315 Inner::Dts(d) => flush_drain(d.as_mut(), out)?,
316 // AAC, ALAC, Opus and PCM decode a packet at a time with nothing
317 // held back across the end of the file.
318 Inner::Aac(_) | Inner::Alac(_) | Inner::PcmExt(_) | Inner::AmrNb(_) | Inner::AmrWb(_) | Inner::Opus(_) | Inner::Pcm(_) => {}
319 }
320 let channels = self.channels.max(1) as i64;
321 if matches!(self.inner, Inner::Vorbis(_)) {
322 // Already cut to the stream's final granule by `ec-vorbis`.
323 self.emitted += out.len() as i64 / channels;
324 return Ok(());
325 }
326 self.produced += out.len() as i64 / channels;
327 let combined = std::mem::take(out);
328 self.trim_tail(&combined, out);
329 Ok(())
330 }
331
332 /// The terminal trim: the stream's last granule minus the front offset
333 /// is the file's true total frame count, so whatever `combined` (the
334 /// flush tail) still has past that is dropped rather than handed to the
335 /// caller.
336 fn trim_tail(&mut self, combined: &[f32], out: &mut Vec<f32>) {
337 let channels = self.channels.max(1) as i64;
338 let raw_frames = combined.len() as i64 / channels;
339 let keep = match self.last_granule {
340 Some(granule) => {
341 let offset = self.trim_offset.unwrap_or(0);
342 let target = (granule - offset).max(0);
343 (target - self.emitted).clamp(0, raw_frames)
344 }
345 None => raw_frames,
346 };
347 out.extend_from_slice(&combined[..(keep * channels).max(0) as usize]);
348 self.emitted += keep;
349 }
350
351 /// Drop everything buffered from before a seek.
352 pub fn reset(&mut self) {
353 match &mut self.inner {
354 Inner::Flac(d) => d.reset(),
355 Inner::Mp3(d) => d.reset(),
356 Inner::Vorbis(d) => d.reset(),
357 Inner::Ac3(d) => d.reset(),
358 Inner::TrueHd(d) => d.reset(),
359 Inner::Dts(d) => ec_core::Decoder::reset(d.as_mut()),
360 Inner::Aac(d) => {
361 **d = match d.config().cloned() {
362 Some(cfg) => ec_aac::AacDecoder::with_config(cfg),
363 None => ec_aac::AacDecoder::new(),
364 }
365 }
366 Inner::Alac(d) => d.reset(),
367 Inner::PcmExt(d) => ec_core::Decoder::reset(d.as_mut()),
368 Inner::AmrNb(d) => ec_core::Decoder::reset(d.as_mut()),
369 Inner::AmrWb(d) => ec_core::Decoder::reset(d.as_mut()),
370 Inner::Opus(d) => d.reset(),
371 Inner::Pcm(_) => {}
372 }
373 self.produced = 0;
374 self.emitted = 0;
375 self.trim_offset = None;
376 self.last_granule = None;
377 }
378}
379
380/// The bare 34-byte `STREAMINFO` inside whatever a container calls FLAC
381/// extradata.
382///
383/// Three shapes carry the same block: Matroska's `CodecPrivate` is the whole
384/// `fLaC` header chain, mp4's `dfLa` is a version word and then the blocks,
385/// and Ogg's first packet has a `\x7fFLAC` wrapper in front of that. Rather
386/// than encode three offsets, this looks for the one block header that can
387/// only be `STREAMINFO`: type 0, length 34.
388fn flac_stream_info(data: &[u8]) -> Option<&[u8]> {
389 if data.len() == 34 {
390 return Some(data);
391 }
392 let last = data.len().checked_sub(38)?;
393 for at in 0..=last.min(16) {
394 let head = &data[at..at + 4];
395 let len = u32::from_be_bytes([0, head[1], head[2], head[3]]);
396 if head[0] & 0x7f == 0 && len == 34 {
397 return data.get(at + 4..at + 38);
398 }
399 }
400 // Nothing recognisable: hand the bytes over as they came and let the
401 // decoder read the frames' own headers instead.
402 None
403}
404
405/// Push one packet through an [`ec_core::Decoder`] and take every frame it
406/// yields, converted to interleaved `f32`.
407fn drain(decoder: &mut dyn Decoder, packet: &Packet, out: &mut Vec<f32>) -> Result<()> {
408 decoder.send_packet(packet)?;
409 drain_frames(decoder, out)
410}
411
412/// [`ec_core::Decoder::flush`], then every frame it releases because of it.
413fn flush_drain(decoder: &mut dyn Decoder, out: &mut Vec<f32>) -> Result<()> {
414 decoder.flush()?;
415 drain_frames(decoder, out)
416}
417
418/// Every frame currently ready, converted to interleaved `f32`.
419fn drain_frames(decoder: &mut dyn Decoder, out: &mut Vec<f32>) -> Result<()> {
420 loop {
421 match decoder.receive_frame() {
422 Ok(Frame::Audio(frame)) => interleave(&frame, out),
423 Ok(Frame::Video(_)) => {
424 return Err(Error::corrupt("an audio decoder produced a picture"));
425 }
426 Err(e) if e.is_need_more() || e.is_eof() => return Ok(()),
427 Err(e) => return Err(e),
428 }
429 }
430}
431
432/// One decoded frame appended to `out` as interleaved, normalised `f32`.
433fn interleave(frame: &ec_core::AudioFrame, out: &mut Vec<f32>) {
434 let channels = frame.channels().max(1);
435 let width = frame.format.bytes_per_sample();
436 let read = |plane: &[u8], i: usize| -> f32 {
437 let at = i * width;
438 let b = &plane[at..at + width];
439 match frame.format {
440 SampleFormat::U8 => (f32::from(b[0]) - 128.0) / 128.0,
441 SampleFormat::S16 => f32::from(i16::from_ne_bytes([b[0], b[1]])) / 32768.0,
442 SampleFormat::S32 => i32::from_ne_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2147483648.0,
443 SampleFormat::F32 => f32::from_ne_bytes([b[0], b[1], b[2], b[3]]),
444 SampleFormat::F64 => {
445 f64::from_ne_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) as f32
446 }
447 }
448 };
449 match frame.planar {
450 false => {
451 let Some(plane) = frame.data.first() else {
452 return;
453 };
454 let n = (plane.len() / width).min(frame.samples * channels);
455 out.extend((0..n).map(|i| read(plane, i)));
456 }
457 true => {
458 for i in 0..frame.samples {
459 for c in 0..channels {
460 let Some(plane) = frame.data.get(c) else {
461 continue;
462 };
463 if (i + 1) * width <= plane.len() {
464 out.push(read(plane, i));
465 }
466 }
467 }
468 }
469 }
470}
471
472/// PCM bytes as normalised `f32`.
473fn pcm(format: PcmFormat, data: &[u8], out: &mut Vec<f32>) {
474 match format {
475 PcmFormat::U8 => out.extend(data.iter().map(|&b| (f32::from(b) - 128.0) / 128.0)),
476 PcmFormat::S16Le => out.extend(
477 data.as_chunks::<2>().0.iter()
478 .map(|c| f32::from(i16::from_le_bytes([c[0], c[1]])) / 32768.0),
479 ),
480 PcmFormat::S16Be => out.extend(
481 data.as_chunks::<2>().0.iter()
482 .map(|c| f32::from(i16::from_be_bytes([c[0], c[1]])) / 32768.0),
483 ),
484 // 24-bit is stored packed, little-endian, and sign-extends from bit 23.
485 PcmFormat::S24Le => out.extend(data.as_chunks::<3>().0.iter().map(|c| {
486 let v = i32::from_le_bytes([0, c[0], c[1], c[2]]);
487 v as f32 / 2147483648.0
488 })),
489 PcmFormat::S24Be => out.extend(data.as_chunks::<3>().0.iter().map(|c| {
490 let v = i32::from_be_bytes([c[0], c[1], c[2], 0]);
491 v as f32 / 2147483648.0
492 })),
493 PcmFormat::S32Le => out.extend(
494 data.as_chunks::<4>().0.iter()
495 .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) as f32 / 2147483648.0),
496 ),
497 PcmFormat::S32Be => out.extend(
498 data.as_chunks::<4>().0.iter()
499 .map(|c| i32::from_be_bytes([c[0], c[1], c[2], c[3]]) as f32 / 2147483648.0),
500 ),
501 PcmFormat::F32Le => out.extend(
502 data.as_chunks::<4>().0.iter()
503 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])),
504 ),
505 }
506}
507
508/// The stream layout of an Opus track, read off its `OpusHead`.
509///
510/// Mapping family 0 is the implied mono/stereo layout the header does not
511/// spell out; families 1 and 255 carry the table. A header too short to hold
512/// one is treated as family 0, which is what a `.opus` file with a truncated
513/// head still plays as.
514pub fn opus_layout(head: &[u8], channels: usize) -> Result<(usize, usize, Vec<u8>)> {
515 let channels = channels.max(1);
516 let family = head.get(18).copied().unwrap_or(0);
517 if family == 0 || head.len() < 21 {
518 let coupled = usize::from(channels >= 2);
519 let mapping: Vec<u8> = (0..channels.min(2) as u8).collect();
520 return Ok((channels.min(2) - coupled, coupled, mapping));
521 }
522 let streams = usize::from(head[19]);
523 let coupled = usize::from(head[20]);
524 let mapping = head
525 .get(21..21 + channels)
526 .ok_or_else(|| {
527 Error::corrupt(format!(
528 "an OpusHead claiming {channels} channels with a {}-byte mapping table",
529 head.len().saturating_sub(21)
530 ))
531 })?
532 .to_vec();
533 Ok((streams, coupled, mapping))
534}
535
536/// The encoder delay an Opus track states in its `OpusHead`, in 48 kHz samples.
537pub fn opus_pre_skip(head: &[u8]) -> u64 {
538 match head.get(10..12) {
539 Some(b) => u64::from(u16::from_le_bytes([b[0], b[1]])),
540 None => 0,
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547
548 #[test]
549 fn opus_layouts_come_off_the_head_or_are_implied() {
550 // Family 0 stereo: one coupled stream, no table in the header.
551 let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00";
552 assert_eq!(opus_layout(head, 2).unwrap(), (1, 1, vec![0, 1]));
553 assert_eq!(opus_layout(head, 1).unwrap(), (1, 0, vec![0]));
554 assert_eq!(opus_pre_skip(head), 312);
555
556 // Family 1, 5.1: four streams of which two are coupled.
557 let mut six = head[..18].to_vec();
558 six.extend_from_slice(&[1, 4, 2, 0, 4, 1, 2, 3, 5]);
559 assert_eq!(
560 opus_layout(&six, 6).unwrap(),
561 (4, 2, vec![0, 4, 1, 2, 3, 5])
562 );
563 // A table too short for the channel count is named, not guessed at.
564 assert!(opus_layout(&six[..23], 6).is_err());
565 }
566
567 #[test]
568 fn raw_aac_still_decodes_after_reset() {
569 let mut enc = ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig::default());
570 let pcm: Vec<f32> = (0..24_000 * 2)
571 .map(|i| ((i / 2) as f32 * 0.05).sin() * 0.3)
572 .collect();
573 enc.push_pcm(&pcm, 2, 24_000).unwrap();
574 enc.finish();
575 let mut params = CodecParameters::new(CodecId::Aac);
576 params.extradata = Some(ec_core::packet::Buf::from_vec(enc.audio_specific_config()));
577 params.media = ec_core::registry::MediaParameters::Audio(ec_core::registry::AudioParameters {
578 sample_rate: 24_000,
579 layout: ec_core::ChannelLayout::from_count(2),
580 ..Default::default()
581 });
582 let packets: Vec<Packet> = std::iter::from_fn(|| enc.next_packet().ok())
583 .map(|p| Packet::new(0, ec_core::TimeBase::new(1, 24_000), p.data))
584 .collect();
585 let mut dec = AudioDecoder::new(&params).unwrap();
586 let mut fresh = AudioDecoder::new(&params).unwrap();
587 let (mut a, mut b) = (Vec::new(), Vec::new());
588 dec.decode(&packets[10], &mut a).unwrap();
589 dec.reset();
590 for p in &packets[20..22] {
591 dec.decode(p, &mut a).unwrap();
592 fresh.decode(p, &mut b).unwrap();
593 assert!(!a.is_empty());
594 assert_eq!(a, b);
595 }
596 assert_eq!(dec.sample_rate(), 24_000);
597 }
598
599 #[test]
600 fn pcm_reads_every_width_at_full_scale() {
601 let mut out = Vec::new();
602 pcm(PcmFormat::S16Le, &[0x00, 0x80, 0xff, 0x7f], &mut out);
603 assert_eq!(out, vec![-1.0, 32767.0 / 32768.0]);
604 out.clear();
605 pcm(PcmFormat::U8, &[0, 128, 255], &mut out);
606 assert_eq!(out[0], -1.0);
607 assert_eq!(out[1], 0.0);
608 out.clear();
609 // 24-bit sign-extends: 0x800000 is full-scale negative.
610 pcm(PcmFormat::S24Le, &[0x00, 0x00, 0x80], &mut out);
611 assert_eq!(out, vec![-1.0]);
612 }
613}