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