| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 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 | |
| 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 | |
| 29 | Pcm(CodecId), |
| 30 | } |
| 31 | |
| 32 | |
| 33 | pub struct AudioDecoder { |
| 34 | inner: Inner, |
| 35 | codec: CodecId, |
| 36 | channels: usize, |
| 37 | sample_rate: u32, |
| 38 | |
| 39 | |
| 40 | |
| 41 | produced: i64, |
| 42 | |
| 43 | emitted: i64, |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | trim_offset: Option<i64>, |
| 55 | |
| 56 | |
| 57 | |
| 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 | |
| 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 | |
| 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 | |
| 127 | |
| 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 | |
| 161 | pub fn codec(&self) -> CodecId { |
| 162 | self.codec |
| 163 | } |
| 164 | |
| 165 | |
| 166 | pub fn channels(&self) -> usize { |
| 167 | self.channels |
| 168 | } |
| 169 | |
| 170 | |
| 171 | pub fn sample_rate(&self) -> u32 { |
| 172 | self.sample_rate |
| 173 | } |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 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 | |
| 219 | |
| 220 | |
| 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 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 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 | |
| 254 | |
| 255 | self.trim_offset = Some(0); |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | self.produced += raw_frames; |
| 260 | } |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 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 | |
| 282 | |
| 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 | |
| 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 | |
| 298 | |
| 299 | |
| 300 | |
| 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 | |
| 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) => **d = ec_aac::AacDecoder::new(), |
| 325 | Inner::Alac(d) => d.reset(), |
| 326 | Inner::PcmExt(d) => ec_core::Decoder::reset(d.as_mut()), |
| 327 | Inner::AmrNb(d) => ec_core::Decoder::reset(d.as_mut()), |
| 328 | Inner::AmrWb(d) => ec_core::Decoder::reset(d.as_mut()), |
| 329 | Inner::Opus(d) => d.reset(), |
| 330 | Inner::Pcm(_) => {} |
| 331 | } |
| 332 | self.produced = 0; |
| 333 | self.emitted = 0; |
| 334 | self.trim_offset = None; |
| 335 | self.last_granule = None; |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | fn flac_stream_info(data: &[u8]) -> Option<&[u8]> { |
| 348 | if data.len() == 34 { |
| 349 | return Some(data); |
| 350 | } |
| 351 | for at in 0..data.len().saturating_sub(38).min(16) { |
| 352 | let head = &data[at..at + 4]; |
| 353 | let len = u32::from_be_bytes([0, head[1], head[2], head[3]]); |
| 354 | if head[0] & 0x7f == 0 && len == 34 { |
| 355 | return data.get(at + 4..at + 38); |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | |
| 360 | None |
| 361 | } |
| 362 | |
| 363 | |
| 364 | fn is_pcm(codec: CodecId) -> bool { |
| 365 | matches!( |
| 366 | codec, |
| 367 | CodecId::PcmU8 |
| 368 | | CodecId::PcmS16Le |
| 369 | | CodecId::PcmS16Be |
| 370 | | CodecId::PcmS24Le |
| 371 | | CodecId::PcmS32Le |
| 372 | | CodecId::PcmF32Le |
| 373 | ) |
| 374 | } |
| 375 | |
| 376 | |
| 377 | |
| 378 | fn drain(decoder: &mut dyn Decoder, packet: &Packet, out: &mut Vec<f32>) -> Result<()> { |
| 379 | decoder.send_packet(packet)?; |
| 380 | drain_frames(decoder, out) |
| 381 | } |
| 382 | |
| 383 | |
| 384 | fn flush_drain(decoder: &mut dyn Decoder, out: &mut Vec<f32>) -> Result<()> { |
| 385 | decoder.flush()?; |
| 386 | drain_frames(decoder, out) |
| 387 | } |
| 388 | |
| 389 | |
| 390 | fn drain_frames(decoder: &mut dyn Decoder, out: &mut Vec<f32>) -> Result<()> { |
| 391 | loop { |
| 392 | match decoder.receive_frame() { |
| 393 | Ok(Frame::Audio(frame)) => interleave(&frame, out), |
| 394 | Ok(Frame::Video(_)) => { |
| 395 | return Err(Error::corrupt("an audio decoder produced a picture")); |
| 396 | } |
| 397 | Err(e) if e.is_need_more() || e.is_eof() => return Ok(()), |
| 398 | Err(e) => return Err(e), |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | |
| 404 | fn interleave(frame: &ec_core::AudioFrame, out: &mut Vec<f32>) { |
| 405 | let channels = frame.channels().max(1); |
| 406 | let width = frame.format.bytes_per_sample(); |
| 407 | let read = |plane: &[u8], i: usize| -> f32 { |
| 408 | let at = i * width; |
| 409 | let b = &plane[at..at + width]; |
| 410 | match frame.format { |
| 411 | SampleFormat::U8 => (f32::from(b[0]) - 128.0) / 128.0, |
| 412 | SampleFormat::S16 => f32::from(i16::from_ne_bytes([b[0], b[1]])) / 32768.0, |
| 413 | SampleFormat::S32 => i32::from_ne_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2147483648.0, |
| 414 | SampleFormat::F32 => f32::from_ne_bytes([b[0], b[1], b[2], b[3]]), |
| 415 | SampleFormat::F64 => { |
| 416 | f64::from_ne_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) as f32 |
| 417 | } |
| 418 | } |
| 419 | }; |
| 420 | match frame.planar { |
| 421 | false => { |
| 422 | let Some(plane) = frame.data.first() else { |
| 423 | return; |
| 424 | }; |
| 425 | let n = (plane.len() / width).min(frame.samples * channels); |
| 426 | out.extend((0..n).map(|i| read(plane, i))); |
| 427 | } |
| 428 | true => { |
| 429 | for i in 0..frame.samples { |
| 430 | for c in 0..channels { |
| 431 | let Some(plane) = frame.data.get(c) else { |
| 432 | continue; |
| 433 | }; |
| 434 | if (i + 1) * width <= plane.len() { |
| 435 | out.push(read(plane, i)); |
| 436 | } |
| 437 | } |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | |
| 444 | fn pcm(codec: CodecId, data: &[u8], out: &mut Vec<f32>) { |
| 445 | match codec { |
| 446 | CodecId::PcmU8 => out.extend(data.iter().map(|&b| (f32::from(b) - 128.0) / 128.0)), |
| 447 | CodecId::PcmS16Le => out.extend( |
| 448 | data.as_chunks::<2>().0.iter() |
| 449 | .map(|c| f32::from(i16::from_le_bytes([c[0], c[1]])) / 32768.0), |
| 450 | ), |
| 451 | CodecId::PcmS16Be => out.extend( |
| 452 | data.as_chunks::<2>().0.iter() |
| 453 | .map(|c| f32::from(i16::from_be_bytes([c[0], c[1]])) / 32768.0), |
| 454 | ), |
| 455 | |
| 456 | CodecId::PcmS24Le => out.extend(data.as_chunks::<3>().0.iter().map(|c| { |
| 457 | let v = i32::from_le_bytes([0, c[0], c[1], c[2]]); |
| 458 | v as f32 / 2147483648.0 |
| 459 | })), |
| 460 | CodecId::PcmS32Le => out.extend( |
| 461 | data.as_chunks::<4>().0.iter() |
| 462 | .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) as f32 / 2147483648.0), |
| 463 | ), |
| 464 | CodecId::PcmF32Le => out.extend( |
| 465 | data.as_chunks::<4>().0.iter() |
| 466 | .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])), |
| 467 | ), |
| 468 | _ => {} |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | |
| 473 | |
| 474 | |
| 475 | |
| 476 | |
| 477 | |
| 478 | pub fn opus_layout(head: &[u8], channels: usize) -> Result<(usize, usize, Vec<u8>)> { |
| 479 | let channels = channels.max(1); |
| 480 | let family = head.get(18).copied().unwrap_or(0); |
| 481 | if family == 0 || head.len() < 21 { |
| 482 | let coupled = usize::from(channels >= 2); |
| 483 | let mapping: Vec<u8> = (0..channels.min(2) as u8).collect(); |
| 484 | return Ok((channels.min(2) - coupled, coupled, mapping)); |
| 485 | } |
| 486 | let streams = usize::from(head[19]); |
| 487 | let coupled = usize::from(head[20]); |
| 488 | let mapping = head |
| 489 | .get(21..21 + channels) |
| 490 | .ok_or_else(|| { |
| 491 | Error::corrupt(format!( |
| 492 | "an OpusHead claiming {channels} channels with a {}-byte mapping table", |
| 493 | head.len().saturating_sub(21) |
| 494 | )) |
| 495 | })? |
| 496 | .to_vec(); |
| 497 | Ok((streams, coupled, mapping)) |
| 498 | } |
| 499 | |
| 500 | |
| 501 | pub fn opus_pre_skip(head: &[u8]) -> u64 { |
| 502 | match head.get(10..12) { |
| 503 | Some(b) => u64::from(u16::from_le_bytes([b[0], b[1]])), |
| 504 | None => 0, |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | #[cfg(test)] |
| 509 | mod tests { |
| 510 | use super::*; |
| 511 | |
| 512 | #[test] |
| 513 | fn opus_layouts_come_off_the_head_or_are_implied() { |
| 514 | |
| 515 | let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00"; |
| 516 | assert_eq!(opus_layout(head, 2).unwrap(), (1, 1, vec![0, 1])); |
| 517 | assert_eq!(opus_layout(head, 1).unwrap(), (1, 0, vec![0])); |
| 518 | assert_eq!(opus_pre_skip(head), 312); |
| 519 | |
| 520 | |
| 521 | let mut six = head[..18].to_vec(); |
| 522 | six.extend_from_slice(&[1, 4, 2, 0, 4, 1, 2, 3, 5]); |
| 523 | assert_eq!( |
| 524 | opus_layout(&six, 6).unwrap(), |
| 525 | (4, 2, vec![0, 4, 1, 2, 3, 5]) |
| 526 | ); |
| 527 | |
| 528 | assert!(opus_layout(&six[..23], 6).is_err()); |
| 529 | } |
| 530 | |
| 531 | #[test] |
| 532 | fn pcm_reads_every_width_at_full_scale() { |
| 533 | let mut out = Vec::new(); |
| 534 | pcm(CodecId::PcmS16Le, &[0x00, 0x80, 0xff, 0x7f], &mut out); |
| 535 | assert_eq!(out, vec![-1.0, 32767.0 / 32768.0]); |
| 536 | out.clear(); |
| 537 | pcm(CodecId::PcmU8, &[0, 128, 255], &mut out); |
| 538 | assert_eq!(out[0], -1.0); |
| 539 | assert_eq!(out[1], 0.0); |
| 540 | out.clear(); |
| 541 | |
| 542 | pcm(CodecId::PcmS24Le, &[0x00, 0x00, 0x80], &mut out); |
| 543 | assert_eq!(out, vec![-1.0]); |
| 544 | } |
| 545 | } |