forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB1e4e107Tahinli2 months ago2830 commits

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