forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2cccf17Tahinli3 months ago136 commits

decoder.rs376 lines, 14.1 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 Aac(Box<ec_aac::AacDecoder>),
22 Alac(Box<ec_alac::AlacDecoder>),
23 Opus(Box<ec_opus::MultistreamDecoder>),
24 /// PCM needs no decoder, only a reading of the bytes.
25 Pcm(CodecId),
26}
27
28/// A decoder for one audio stream.
29pub struct AudioDecoder {
30 inner: Inner,
31 codec: CodecId,
32 channels: usize,
33 sample_rate: u32,
34}
35
36impl std::fmt::Debug for AudioDecoder {
37 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 f.debug_struct("AudioDecoder")
39 .field("codec", &self.codec.name())
40 .field("channels", &self.channels)
41 .field("sample_rate", &self.sample_rate)
42 .finish()
43 }
44}
45
46impl AudioDecoder {
47 /// A decoder for the stream `params` describes.
48 pub fn new(params: &CodecParameters) -> Result<AudioDecoder> {
49 let audio = params
50 .audio()
51 .ok_or_else(|| Error::corrupt("a decoder was asked for on a non-audio stream"))?;
52 let channels = audio.layout.channel_count().max(1);
53 let sample_rate = audio.sample_rate;
54 let extradata = params.extradata.as_deref();
55 let inner = match params.codec {
56 CodecId::Flac => {
57 let mut params = params.clone();
58 params.extradata = flac_stream_info(extradata.unwrap_or_default())
59 .map(ec_core::packet::Buf::copy_from_slice);
60 Inner::Flac(Box::new(ec_flac::FlacDecoder::new(params)?))
61 }
62 CodecId::Mp3 => Inner::Mp3(Box::new(ec_mp3::Mp3Decoder::new(params.clone())?)),
63 CodecId::Vorbis => {
64 let data = extradata.ok_or_else(|| {
65 Error::corrupt("a Vorbis stream with no header triplet in its extradata")
66 })?;
67 let headers = ec_ogg::xiph_unlace(data)?;
68 Inner::Vorbis(Box::new(ec_vorbis::VorbisDecoder::new(&headers)?))
69 }
70 CodecId::Ac3 | CodecId::EAc3 => Inner::Ac3(Box::new(ec_ac3::Ac3Decoder::new())),
71 CodecId::Aac => {
72 let decoder = match extradata {
73 Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)?,
74 // ADTS states its own configuration in every frame.
75 None => ec_aac::AacDecoder::new(),
76 };
77 Inner::Aac(Box::new(decoder))
78 }
79 CodecId::Alac => Inner::Alac(Box::new(ec_alac::AlacDecoder::from_parameters(
80 params.clone(),
81 )?)),
82 CodecId::Opus => {
83 let head = extradata.unwrap_or_default();
84 let (streams, coupled, mapping) = opus_layout(head, channels)?;
85 // 48 kHz whatever the container says: it is the only rate Opus
86 // decodes at, and the rate its timestamps are in.
87 Inner::Opus(Box::new(ec_opus::MultistreamDecoder::try_with_rate(
88 48_000, streams, coupled, &mapping,
89 )?))
90 }
91 codec if is_pcm(codec) => Inner::Pcm(codec),
92 codec => {
93 return Err(Error::unsupported(
94 format!("the {} track", codec.name()),
95 match codec.media_type() {
96 ec_core::MediaType::Audio => {
97 "no decoder for it exists in this family (yet)"
98 }
99 _ => "this is an audio probe; picture and subtitles decode elsewhere",
100 },
101 ));
102 }
103 };
104 Ok(AudioDecoder {
105 inner,
106 codec: params.codec,
107 channels,
108 sample_rate: match params.codec {
109 CodecId::Opus => 48_000,
110 _ => sample_rate,
111 },
112 })
113 }
114
115 /// Which codec this is decoding.
116 pub fn codec(&self) -> CodecId {
117 self.codec
118 }
119
120 /// Channels the decoder emits.
121 pub fn channels(&self) -> usize {
122 self.channels
123 }
124
125 /// Rate the decoder emits at.
126 pub fn sample_rate(&self) -> u32 {
127 self.sample_rate
128 }
129
130 /// One packet in, interleaved `f32` out, normalised to -1.0..=1.0.
131 ///
132 /// `out` is cleared first: a packet that decodes to nothing (a header
133 /// packet, a frame the decoder swallowed) leaves it empty rather than
134 /// leaving the caller with the previous packet's audio.
135 pub fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> Result<()> {
136 out.clear();
137 match &mut self.inner {
138 Inner::Flac(d) => drain(d.as_mut(), packet, out)?,
139 Inner::Mp3(d) => drain(d.as_mut(), packet, out)?,
140 Inner::Vorbis(d) => drain(d.as_mut(), packet, out)?,
141 Inner::Ac3(d) => drain(d.as_mut(), packet, out)?,
142 Inner::Aac(d) => {
143 let audio = d.decode(&packet.data, packet.pts)?;
144 self.channels = usize::from(audio.channels).max(1);
145 if audio.sample_rate > 0 {
146 self.sample_rate = audio.sample_rate;
147 }
148 out.extend_from_slice(&audio.samples);
149 }
150 Inner::Alac(d) => {
151 let scale = match d.cookie().sample_format() {
152 SampleFormat::S16 => 1.0 / 32768.0,
153 _ => 1.0 / 2147483648.0,
154 };
155 out.extend(d.decode(&packet.data)?.iter().map(|&s| s as f32 * scale));
156 }
157 Inner::Opus(d) => {
158 let samples = d.decode_packet(&packet.data)?;
159 out.extend_from_slice(&samples);
160 }
161 Inner::Pcm(codec) => pcm(*codec, &packet.data, out),
162 }
163 Ok(())
164 }
165
166 /// Drop everything buffered from before a seek.
167 pub fn reset(&mut self) {
168 match &mut self.inner {
169 Inner::Flac(d) => d.reset(),
170 Inner::Mp3(d) => d.reset(),
171 Inner::Vorbis(d) => d.reset(),
172 Inner::Ac3(d) => d.reset(),
173 Inner::Aac(d) => **d = ec_aac::AacDecoder::new(),
174 Inner::Alac(d) => d.reset(),
175 Inner::Opus(d) => d.reset(),
176 Inner::Pcm(_) => {}
177 }
178 }
179}
180
181/// The bare 34-byte `STREAMINFO` inside whatever a container calls FLAC
182/// extradata.
183///
184/// Three shapes carry the same block: Matroska's `CodecPrivate` is the whole
185/// `fLaC` header chain, mp4's `dfLa` is a version word and then the blocks,
186/// and Ogg's first packet has a `\x7fFLAC` wrapper in front of that. Rather
187/// than encode three offsets, this looks for the one block header that can
188/// only be `STREAMINFO`: type 0, length 34.
189fn flac_stream_info(data: &[u8]) -> Option<&[u8]> {
190 if data.len() == 34 {
191 return Some(data);
192 }
193 for at in 0..data.len().saturating_sub(38).min(16) {
194 let head = &data[at..at + 4];
195 let len = u32::from_be_bytes([0, head[1], head[2], head[3]]);
196 if head[0] & 0x7f == 0 && len == 34 {
197 return data.get(at + 4..at + 38);
198 }
199 }
200 // Nothing recognisable: hand the bytes over as they came and let the
201 // decoder read the frames' own headers instead.
202 None
203}
204
205/// True for the PCM codec ids, which are read rather than decoded.
206fn is_pcm(codec: CodecId) -> bool {
207 matches!(
208 codec,
209 CodecId::PcmU8
210 | CodecId::PcmS16Le
211 | CodecId::PcmS16Be
212 | CodecId::PcmS24Le
213 | CodecId::PcmS32Le
214 | CodecId::PcmF32Le
215 )
216}
217
218/// Push one packet through an [`ec_core::Decoder`] and take every frame it
219/// yields, converted to interleaved `f32`.
220fn drain(decoder: &mut dyn Decoder, packet: &Packet, out: &mut Vec<f32>) -> Result<()> {
221 decoder.send_packet(packet)?;
222 loop {
223 match decoder.receive_frame() {
224 Ok(Frame::Audio(frame)) => interleave(&frame, out),
225 Ok(Frame::Video(_)) => {
226 return Err(Error::corrupt("an audio decoder produced a picture"));
227 }
228 Err(e) if e.is_need_more() || e.is_eof() => return Ok(()),
229 Err(e) => return Err(e),
230 }
231 }
232}
233
234/// One decoded frame appended to `out` as interleaved, normalised `f32`.
235fn interleave(frame: &ec_core::AudioFrame, out: &mut Vec<f32>) {
236 let channels = frame.channels().max(1);
237 let width = frame.format.bytes_per_sample();
238 let read = |plane: &[u8], i: usize| -> f32 {
239 let at = i * width;
240 let b = &plane[at..at + width];
241 match frame.format {
242 SampleFormat::U8 => (f32::from(b[0]) - 128.0) / 128.0,
243 SampleFormat::S16 => f32::from(i16::from_ne_bytes([b[0], b[1]])) / 32768.0,
244 SampleFormat::S32 => i32::from_ne_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2147483648.0,
245 SampleFormat::F32 => f32::from_ne_bytes([b[0], b[1], b[2], b[3]]),
246 SampleFormat::F64 => {
247 f64::from_ne_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) as f32
248 }
249 }
250 };
251 match frame.planar {
252 false => {
253 let Some(plane) = frame.data.first() else {
254 return;
255 };
256 let n = (plane.len() / width).min(frame.samples * channels);
257 out.extend((0..n).map(|i| read(plane, i)));
258 }
259 true => {
260 for i in 0..frame.samples {
261 for c in 0..channels {
262 let Some(plane) = frame.data.get(c) else {
263 continue;
264 };
265 if (i + 1) * width <= plane.len() {
266 out.push(read(plane, i));
267 }
268 }
269 }
270 }
271 }
272}
273
274/// PCM bytes as normalised `f32`.
275fn pcm(codec: CodecId, data: &[u8], out: &mut Vec<f32>) {
276 match codec {
277 CodecId::PcmU8 => out.extend(data.iter().map(|&b| (f32::from(b) - 128.0) / 128.0)),
278 CodecId::PcmS16Le => out.extend(
279 data.chunks_exact(2)
280 .map(|c| f32::from(i16::from_le_bytes([c[0], c[1]])) / 32768.0),
281 ),
282 CodecId::PcmS16Be => out.extend(
283 data.chunks_exact(2)
284 .map(|c| f32::from(i16::from_be_bytes([c[0], c[1]])) / 32768.0),
285 ),
286 // 24-bit is stored packed, little-endian, and sign-extends from bit 23.
287 CodecId::PcmS24Le => out.extend(data.chunks_exact(3).map(|c| {
288 let v = i32::from_le_bytes([0, c[0], c[1], c[2]]);
289 v as f32 / 2147483648.0
290 })),
291 CodecId::PcmS32Le => out.extend(
292 data.chunks_exact(4)
293 .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) as f32 / 2147483648.0),
294 ),
295 CodecId::PcmF32Le => out.extend(
296 data.chunks_exact(4)
297 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])),
298 ),
299 _ => {}
300 }
301}
302
303/// The stream layout of an Opus track, read off its `OpusHead`.
304///
305/// Mapping family 0 is the implied mono/stereo layout the header does not
306/// spell out; families 1 and 255 carry the table. A header too short to hold
307/// one is treated as family 0, which is what a `.opus` file with a truncated
308/// head still plays as.
309pub fn opus_layout(head: &[u8], channels: usize) -> Result<(usize, usize, Vec<u8>)> {
310 let channels = channels.max(1);
311 let family = head.get(18).copied().unwrap_or(0);
312 if family == 0 || head.len() < 21 {
313 let coupled = usize::from(channels >= 2);
314 let mapping: Vec<u8> = (0..channels.min(2) as u8).collect();
315 return Ok((channels.min(2) - coupled, coupled, mapping));
316 }
317 let streams = usize::from(head[19]);
318 let coupled = usize::from(head[20]);
319 let mapping = head
320 .get(21..21 + channels)
321 .ok_or_else(|| {
322 Error::corrupt(format!(
323 "an OpusHead claiming {channels} channels with a {}-byte mapping table",
324 head.len().saturating_sub(21)
325 ))
326 })?
327 .to_vec();
328 Ok((streams, coupled, mapping))
329}
330
331/// The encoder delay an Opus track states in its `OpusHead`, in 48 kHz samples.
332pub fn opus_pre_skip(head: &[u8]) -> u64 {
333 match head.get(10..12) {
334 Some(b) => u64::from(u16::from_le_bytes([b[0], b[1]])),
335 None => 0,
336 }
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342
343 #[test]
344 fn opus_layouts_come_off_the_head_or_are_implied() {
345 // Family 0 stereo: one coupled stream, no table in the header.
346 let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00";
347 assert_eq!(opus_layout(head, 2).unwrap(), (1, 1, vec![0, 1]));
348 assert_eq!(opus_layout(head, 1).unwrap(), (1, 0, vec![0]));
349 assert_eq!(opus_pre_skip(head), 312);
350
351 // Family 1, 5.1: four streams of which two are coupled.
352 let mut six = head[..18].to_vec();
353 six.extend_from_slice(&[1, 4, 2, 0, 4, 1, 2, 3, 5]);
354 assert_eq!(
355 opus_layout(&six, 6).unwrap(),
356 (4, 2, vec![0, 4, 1, 2, 3, 5])
357 );
358 // A table too short for the channel count is named, not guessed at.
359 assert!(opus_layout(&six[..23], 6).is_err());
360 }
361
362 #[test]
363 fn pcm_reads_every_width_at_full_scale() {
364 let mut out = Vec::new();
365 pcm(CodecId::PcmS16Le, &[0x00, 0x80, 0xff, 0x7f], &mut out);
366 assert_eq!(out, vec![-1.0, 32767.0 / 32768.0]);
367 out.clear();
368 pcm(CodecId::PcmU8, &[0, 128, 255], &mut out);
369 assert_eq!(out[0], -1.0);
370 assert_eq!(out[1], 0.0);
371 out.clear();
372 // 24-bit sign-extends: 0x800000 is full-scale negative.
373 pcm(CodecId::PcmS24Le, &[0x00, 0x00, 0x80], &mut out);
374 assert_eq!(out, vec![-1.0]);
375 }
376}