| 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 | Opus(Box<ec_opus::MultistreamDecoder>), |
| 25 | |
| 26 | Pcm(CodecId), |
| 27 | } |
| 28 | |
| 29 | |
| 30 | pub struct AudioDecoder { |
| 31 | inner: Inner, |
| 32 | codec: CodecId, |
| 33 | channels: usize, |
| 34 | sample_rate: u32, |
| 35 | |
| 36 | |
| 37 | |
| 38 | produced: i64, |
| 39 | |
| 40 | emitted: i64, |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | trim_offset: Option<i64>, |
| 52 | |
| 53 | |
| 54 | |
| 55 | last_granule: Option<i64>, |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | held: Vec<f32>, |
| 66 | } |
| 67 | |
| 68 | impl 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 | |
| 78 | impl AudioDecoder { |
| 79 | |
| 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 | |
| 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 | |
| 119 | |
| 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 | |
| 154 | pub fn codec(&self) -> CodecId { |
| 155 | self.codec |
| 156 | } |
| 157 | |
| 158 | |
| 159 | pub fn channels(&self) -> usize { |
| 160 | self.channels |
| 161 | } |
| 162 | |
| 163 | |
| 164 | pub fn sample_rate(&self) -> u32 { |
| 165 | self.sample_rate |
| 166 | } |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 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 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 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 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 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 | |
| 241 | |
| 242 | self.trim_offset = Some(0); |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | self.produced += raw_frames; |
| 247 | } |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 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 | |
| 272 | |
| 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 | |
| 284 | |
| 285 | |
| 286 | |
| 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 | |
| 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 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | fn 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 | |
| 343 | |
| 344 | None |
| 345 | } |
| 346 | |
| 347 | |
| 348 | fn 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 | |
| 361 | |
| 362 | fn 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 | |
| 368 | fn flush_drain(decoder: &mut dyn Decoder, out: &mut Vec<f32>) -> Result<()> { |
| 369 | decoder.flush()?; |
| 370 | drain_frames(decoder, out) |
| 371 | } |
| 372 | |
| 373 | |
| 374 | fn 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 | |
| 388 | fn 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 | |
| 428 | fn 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 | |
| 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 | |
| 457 | |
| 458 | |
| 459 | |
| 460 | |
| 461 | |
| 462 | pub 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 | |
| 485 | pub 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)] |
| 493 | mod tests { |
| 494 | use super::*; |
| 495 | |
| 496 | #[test] |
| 497 | fn opus_layouts_come_off_the_head_or_are_implied() { |
| 498 | |
| 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 | |
| 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 | |
| 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 | |
| 526 | pcm(CodecId::PcmS24Le, &[0x00, 0x00, 0x80], &mut out); |
| 527 | assert_eq!(out, vec![-1.0]); |
| 528 | } |
| 529 | } |