| 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 | Aac(Box<ec_aac::AacDecoder>), |
| 22 | Alac(Box<ec_alac::AlacDecoder>), |
| 23 | Opus(Box<ec_opus::MultistreamDecoder>), |
| 24 | |
| 25 | Pcm(CodecId), |
| 26 | } |
| 27 | |
| 28 | |
| 29 | pub struct AudioDecoder { |
| 30 | inner: Inner, |
| 31 | codec: CodecId, |
| 32 | channels: usize, |
| 33 | sample_rate: u32, |
| 34 | |
| 35 | |
| 36 | |
| 37 | produced: i64, |
| 38 | |
| 39 | emitted: i64, |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | trim_offset: Option<i64>, |
| 51 | |
| 52 | |
| 53 | |
| 54 | last_granule: Option<i64>, |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | held: Vec<f32>, |
| 65 | } |
| 66 | |
| 67 | impl std::fmt::Debug for AudioDecoder { |
| 68 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 69 | f.debug_struct("AudioDecoder") |
| 70 | .field("codec", &self.codec.name()) |
| 71 | .field("channels", &self.channels) |
| 72 | .field("sample_rate", &self.sample_rate) |
| 73 | .finish() |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | impl AudioDecoder { |
| 78 | |
| 79 | pub fn new(params: &CodecParameters) -> Result<AudioDecoder> { |
| 80 | let audio = params |
| 81 | .audio() |
| 82 | .ok_or_else(|| Error::corrupt("a decoder was asked for on a non-audio stream"))?; |
| 83 | let channels = audio.layout.channel_count().max(1); |
| 84 | let sample_rate = audio.sample_rate; |
| 85 | let extradata = params.extradata.as_deref(); |
| 86 | let inner = match params.codec { |
| 87 | CodecId::Flac => { |
| 88 | let mut params = params.clone(); |
| 89 | params.extradata = flac_stream_info(extradata.unwrap_or_default()) |
| 90 | .map(ec_core::packet::Buf::copy_from_slice); |
| 91 | Inner::Flac(Box::new(ec_flac::FlacDecoder::new(params)?)) |
| 92 | } |
| 93 | CodecId::Mp3 => Inner::Mp3(Box::new(ec_mp3::Mp3Decoder::new(params.clone())?)), |
| 94 | CodecId::Vorbis => { |
| 95 | let data = extradata.ok_or_else(|| { |
| 96 | Error::corrupt("a Vorbis stream with no header triplet in its extradata") |
| 97 | })?; |
| 98 | let headers = ec_ogg::xiph_unlace(data)?; |
| 99 | Inner::Vorbis(Box::new(ec_vorbis::VorbisDecoder::new(&headers)?)) |
| 100 | } |
| 101 | CodecId::Ac3 | CodecId::EAc3 => Inner::Ac3(Box::new(ec_ac3::Ac3Decoder::new())), |
| 102 | CodecId::Aac => { |
| 103 | let decoder = match extradata { |
| 104 | Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)?, |
| 105 | |
| 106 | None => ec_aac::AacDecoder::new(), |
| 107 | }; |
| 108 | Inner::Aac(Box::new(decoder)) |
| 109 | } |
| 110 | CodecId::Alac => Inner::Alac(Box::new(ec_alac::AlacDecoder::from_parameters( |
| 111 | params.clone(), |
| 112 | )?)), |
| 113 | CodecId::Opus => { |
| 114 | let head = extradata.unwrap_or_default(); |
| 115 | let (streams, coupled, mapping) = opus_layout(head, channels)?; |
| 116 | |
| 117 | |
| 118 | Inner::Opus(Box::new(ec_opus::MultistreamDecoder::try_with_rate( |
| 119 | 48_000, streams, coupled, &mapping, |
| 120 | )?)) |
| 121 | } |
| 122 | codec if is_pcm(codec) => Inner::Pcm(codec), |
| 123 | codec => { |
| 124 | return Err(Error::unsupported( |
| 125 | format!("the {} track", codec.name()), |
| 126 | match codec.media_type() { |
| 127 | ec_core::MediaType::Audio => { |
| 128 | "no decoder for it exists in this family (yet)" |
| 129 | } |
| 130 | _ => "this is an audio probe; picture and subtitles decode elsewhere", |
| 131 | }, |
| 132 | )); |
| 133 | } |
| 134 | }; |
| 135 | Ok(AudioDecoder { |
| 136 | inner, |
| 137 | codec: params.codec, |
| 138 | channels, |
| 139 | sample_rate: match params.codec { |
| 140 | CodecId::Opus => 48_000, |
| 141 | _ => sample_rate, |
| 142 | }, |
| 143 | produced: 0, |
| 144 | emitted: 0, |
| 145 | trim_offset: None, |
| 146 | last_granule: None, |
| 147 | held: Vec::new(), |
| 148 | }) |
| 149 | } |
| 150 | |
| 151 | |
| 152 | pub fn codec(&self) -> CodecId { |
| 153 | self.codec |
| 154 | } |
| 155 | |
| 156 | |
| 157 | pub fn channels(&self) -> usize { |
| 158 | self.channels |
| 159 | } |
| 160 | |
| 161 | |
| 162 | pub fn sample_rate(&self) -> u32 { |
| 163 | self.sample_rate |
| 164 | } |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | pub fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> Result<()> { |
| 172 | out.clear(); |
| 173 | match &mut self.inner { |
| 174 | Inner::Flac(d) => drain(d.as_mut(), packet, out)?, |
| 175 | Inner::Mp3(d) => drain(d.as_mut(), packet, out)?, |
| 176 | Inner::Vorbis(d) => drain(d.as_mut(), packet, out)?, |
| 177 | Inner::Ac3(d) => drain(d.as_mut(), packet, out)?, |
| 178 | Inner::Aac(d) => { |
| 179 | let audio = d.decode(&packet.data, packet.pts)?; |
| 180 | self.channels = usize::from(audio.channels).max(1); |
| 181 | if audio.sample_rate > 0 { |
| 182 | self.sample_rate = audio.sample_rate; |
| 183 | } |
| 184 | out.extend_from_slice(&audio.samples); |
| 185 | } |
| 186 | Inner::Alac(d) => { |
| 187 | let scale = match d.cookie().sample_format() { |
| 188 | SampleFormat::S16 => 1.0 / 32768.0, |
| 189 | _ => 1.0 / 2147483648.0, |
| 190 | }; |
| 191 | out.extend(d.decode(&packet.data)?.iter().map(|&s| s as f32 * scale)); |
| 192 | } |
| 193 | Inner::Opus(d) => { |
| 194 | let samples = d.decode_packet(&packet.data)?; |
| 195 | out.extend_from_slice(&samples); |
| 196 | } |
| 197 | Inner::Pcm(codec) => pcm(*codec, &packet.data, out), |
| 198 | } |
| 199 | self.trim(ec_ogg::granule_of(packet), out); |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | if matches!(self.inner, Inner::Vorbis(_)) { |
| 206 | std::mem::swap(&mut self.held, out); |
| 207 | } |
| 208 | self.emitted += out.len() as i64 / self.channels.max(1) as i64; |
| 209 | Ok(()) |
| 210 | } |
| 211 | |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | fn trim(&mut self, granule: Option<i64>, out: &mut Vec<f32>) { |
| 224 | let channels = self.channels.max(1) as i64; |
| 225 | let raw_frames = out.len() as i64 / channels; |
| 226 | if let Some(granule) = granule { |
| 227 | self.last_granule = Some(granule); |
| 228 | if self.trim_offset.is_none() { |
| 229 | if self.produced == 0 { |
| 230 | let offset = (granule - raw_frames).max(0); |
| 231 | self.trim_offset = Some(offset); |
| 232 | if offset > 0 { |
| 233 | let drop = (offset.min(raw_frames) * channels) as usize; |
| 234 | out.drain(0..drop); |
| 235 | } |
| 236 | } else { |
| 237 | |
| 238 | |
| 239 | self.trim_offset = Some(0); |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 | self.produced += raw_frames; |
| 244 | } |
| 245 | |
| 246 | |
| 247 | |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | pub fn flush(&mut self, out: &mut Vec<f32>) -> Result<()> { |
| 261 | out.clear(); |
| 262 | match &mut self.inner { |
| 263 | Inner::Flac(d) => flush_drain(d.as_mut(), out)?, |
| 264 | Inner::Mp3(d) => flush_drain(d.as_mut(), out)?, |
| 265 | Inner::Vorbis(d) => flush_drain(d.as_mut(), out)?, |
| 266 | Inner::Ac3(d) => flush_drain(d.as_mut(), out)?, |
| 267 | |
| 268 | |
| 269 | Inner::Aac(_) | Inner::Alac(_) | Inner::Opus(_) | Inner::Pcm(_) => {} |
| 270 | } |
| 271 | let channels = self.channels.max(1) as i64; |
| 272 | self.produced += out.len() as i64 / channels; |
| 273 | let mut combined = std::mem::take(&mut self.held); |
| 274 | combined.append(out); |
| 275 | self.trim_tail(&combined, out); |
| 276 | Ok(()) |
| 277 | } |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | fn trim_tail(&mut self, combined: &[f32], out: &mut Vec<f32>) { |
| 284 | let channels = self.channels.max(1) as i64; |
| 285 | let raw_frames = combined.len() as i64 / channels; |
| 286 | let keep = match self.last_granule { |
| 287 | Some(granule) => { |
| 288 | let offset = self.trim_offset.unwrap_or(0); |
| 289 | let target = (granule - offset).max(0); |
| 290 | (target - self.emitted).clamp(0, raw_frames) |
| 291 | } |
| 292 | None => raw_frames, |
| 293 | }; |
| 294 | out.extend_from_slice(&combined[..(keep * channels).max(0) as usize]); |
| 295 | self.emitted += keep; |
| 296 | } |
| 297 | |
| 298 | |
| 299 | pub fn reset(&mut self) { |
| 300 | match &mut self.inner { |
| 301 | Inner::Flac(d) => d.reset(), |
| 302 | Inner::Mp3(d) => d.reset(), |
| 303 | Inner::Vorbis(d) => d.reset(), |
| 304 | Inner::Ac3(d) => d.reset(), |
| 305 | Inner::Aac(d) => **d = ec_aac::AacDecoder::new(), |
| 306 | Inner::Alac(d) => d.reset(), |
| 307 | Inner::Opus(d) => d.reset(), |
| 308 | Inner::Pcm(_) => {} |
| 309 | } |
| 310 | self.held.clear(); |
| 311 | self.produced = 0; |
| 312 | self.emitted = 0; |
| 313 | self.trim_offset = None; |
| 314 | self.last_granule = None; |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | fn flac_stream_info(data: &[u8]) -> Option<&[u8]> { |
| 327 | if data.len() == 34 { |
| 328 | return Some(data); |
| 329 | } |
| 330 | for at in 0..data.len().saturating_sub(38).min(16) { |
| 331 | let head = &data[at..at + 4]; |
| 332 | let len = u32::from_be_bytes([0, head[1], head[2], head[3]]); |
| 333 | if head[0] & 0x7f == 0 && len == 34 { |
| 334 | return data.get(at + 4..at + 38); |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | |
| 339 | None |
| 340 | } |
| 341 | |
| 342 | |
| 343 | fn is_pcm(codec: CodecId) -> bool { |
| 344 | matches!( |
| 345 | codec, |
| 346 | CodecId::PcmU8 |
| 347 | | CodecId::PcmS16Le |
| 348 | | CodecId::PcmS16Be |
| 349 | | CodecId::PcmS24Le |
| 350 | | CodecId::PcmS32Le |
| 351 | | CodecId::PcmF32Le |
| 352 | ) |
| 353 | } |
| 354 | |
| 355 | |
| 356 | |
| 357 | fn drain(decoder: &mut dyn Decoder, packet: &Packet, out: &mut Vec<f32>) -> Result<()> { |
| 358 | decoder.send_packet(packet)?; |
| 359 | drain_frames(decoder, out) |
| 360 | } |
| 361 | |
| 362 | |
| 363 | fn flush_drain(decoder: &mut dyn Decoder, out: &mut Vec<f32>) -> Result<()> { |
| 364 | decoder.flush()?; |
| 365 | drain_frames(decoder, out) |
| 366 | } |
| 367 | |
| 368 | |
| 369 | fn drain_frames(decoder: &mut dyn Decoder, out: &mut Vec<f32>) -> Result<()> { |
| 370 | loop { |
| 371 | match decoder.receive_frame() { |
| 372 | Ok(Frame::Audio(frame)) => interleave(&frame, out), |
| 373 | Ok(Frame::Video(_)) => { |
| 374 | return Err(Error::corrupt("an audio decoder produced a picture")); |
| 375 | } |
| 376 | Err(e) if e.is_need_more() || e.is_eof() => return Ok(()), |
| 377 | Err(e) => return Err(e), |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | |
| 383 | fn interleave(frame: &ec_core::AudioFrame, out: &mut Vec<f32>) { |
| 384 | let channels = frame.channels().max(1); |
| 385 | let width = frame.format.bytes_per_sample(); |
| 386 | let read = |plane: &[u8], i: usize| -> f32 { |
| 387 | let at = i * width; |
| 388 | let b = &plane[at..at + width]; |
| 389 | match frame.format { |
| 390 | SampleFormat::U8 => (f32::from(b[0]) - 128.0) / 128.0, |
| 391 | SampleFormat::S16 => f32::from(i16::from_ne_bytes([b[0], b[1]])) / 32768.0, |
| 392 | SampleFormat::S32 => i32::from_ne_bytes([b[0], b[1], b[2], b[3]]) as f32 / 2147483648.0, |
| 393 | SampleFormat::F32 => f32::from_ne_bytes([b[0], b[1], b[2], b[3]]), |
| 394 | SampleFormat::F64 => { |
| 395 | f64::from_ne_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) as f32 |
| 396 | } |
| 397 | } |
| 398 | }; |
| 399 | match frame.planar { |
| 400 | false => { |
| 401 | let Some(plane) = frame.data.first() else { |
| 402 | return; |
| 403 | }; |
| 404 | let n = (plane.len() / width).min(frame.samples * channels); |
| 405 | out.extend((0..n).map(|i| read(plane, i))); |
| 406 | } |
| 407 | true => { |
| 408 | for i in 0..frame.samples { |
| 409 | for c in 0..channels { |
| 410 | let Some(plane) = frame.data.get(c) else { |
| 411 | continue; |
| 412 | }; |
| 413 | if (i + 1) * width <= plane.len() { |
| 414 | out.push(read(plane, i)); |
| 415 | } |
| 416 | } |
| 417 | } |
| 418 | } |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | |
| 423 | fn pcm(codec: CodecId, data: &[u8], out: &mut Vec<f32>) { |
| 424 | match codec { |
| 425 | CodecId::PcmU8 => out.extend(data.iter().map(|&b| (f32::from(b) - 128.0) / 128.0)), |
| 426 | CodecId::PcmS16Le => out.extend( |
| 427 | data.chunks_exact(2) |
| 428 | .map(|c| f32::from(i16::from_le_bytes([c[0], c[1]])) / 32768.0), |
| 429 | ), |
| 430 | CodecId::PcmS16Be => out.extend( |
| 431 | data.chunks_exact(2) |
| 432 | .map(|c| f32::from(i16::from_be_bytes([c[0], c[1]])) / 32768.0), |
| 433 | ), |
| 434 | |
| 435 | CodecId::PcmS24Le => out.extend(data.chunks_exact(3).map(|c| { |
| 436 | let v = i32::from_le_bytes([0, c[0], c[1], c[2]]); |
| 437 | v as f32 / 2147483648.0 |
| 438 | })), |
| 439 | CodecId::PcmS32Le => out.extend( |
| 440 | data.chunks_exact(4) |
| 441 | .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) as f32 / 2147483648.0), |
| 442 | ), |
| 443 | CodecId::PcmF32Le => out.extend( |
| 444 | data.chunks_exact(4) |
| 445 | .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])), |
| 446 | ), |
| 447 | _ => {} |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | |
| 452 | |
| 453 | |
| 454 | |
| 455 | |
| 456 | |
| 457 | pub fn opus_layout(head: &[u8], channels: usize) -> Result<(usize, usize, Vec<u8>)> { |
| 458 | let channels = channels.max(1); |
| 459 | let family = head.get(18).copied().unwrap_or(0); |
| 460 | if family == 0 || head.len() < 21 { |
| 461 | let coupled = usize::from(channels >= 2); |
| 462 | let mapping: Vec<u8> = (0..channels.min(2) as u8).collect(); |
| 463 | return Ok((channels.min(2) - coupled, coupled, mapping)); |
| 464 | } |
| 465 | let streams = usize::from(head[19]); |
| 466 | let coupled = usize::from(head[20]); |
| 467 | let mapping = head |
| 468 | .get(21..21 + channels) |
| 469 | .ok_or_else(|| { |
| 470 | Error::corrupt(format!( |
| 471 | "an OpusHead claiming {channels} channels with a {}-byte mapping table", |
| 472 | head.len().saturating_sub(21) |
| 473 | )) |
| 474 | })? |
| 475 | .to_vec(); |
| 476 | Ok((streams, coupled, mapping)) |
| 477 | } |
| 478 | |
| 479 | |
| 480 | pub fn opus_pre_skip(head: &[u8]) -> u64 { |
| 481 | match head.get(10..12) { |
| 482 | Some(b) => u64::from(u16::from_le_bytes([b[0], b[1]])), |
| 483 | None => 0, |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | #[cfg(test)] |
| 488 | mod tests { |
| 489 | use super::*; |
| 490 | |
| 491 | #[test] |
| 492 | fn opus_layouts_come_off_the_head_or_are_implied() { |
| 493 | |
| 494 | let head = b"OpusHead\x01\x02\x38\x01\x80\xbb\x00\x00\x00\x00\x00"; |
| 495 | assert_eq!(opus_layout(head, 2).unwrap(), (1, 1, vec![0, 1])); |
| 496 | assert_eq!(opus_layout(head, 1).unwrap(), (1, 0, vec![0])); |
| 497 | assert_eq!(opus_pre_skip(head), 312); |
| 498 | |
| 499 | |
| 500 | let mut six = head[..18].to_vec(); |
| 501 | six.extend_from_slice(&[1, 4, 2, 0, 4, 1, 2, 3, 5]); |
| 502 | assert_eq!( |
| 503 | opus_layout(&six, 6).unwrap(), |
| 504 | (4, 2, vec![0, 4, 1, 2, 3, 5]) |
| 505 | ); |
| 506 | |
| 507 | assert!(opus_layout(&six[..23], 6).is_err()); |
| 508 | } |
| 509 | |
| 510 | #[test] |
| 511 | fn pcm_reads_every_width_at_full_scale() { |
| 512 | let mut out = Vec::new(); |
| 513 | pcm(CodecId::PcmS16Le, &[0x00, 0x80, 0xff, 0x7f], &mut out); |
| 514 | assert_eq!(out, vec![-1.0, 32767.0 / 32768.0]); |
| 515 | out.clear(); |
| 516 | pcm(CodecId::PcmU8, &[0, 128, 255], &mut out); |
| 517 | assert_eq!(out[0], -1.0); |
| 518 | assert_eq!(out[1], 0.0); |
| 519 | out.clear(); |
| 520 | |
| 521 | pcm(CodecId::PcmS24Le, &[0x00, 0x00, 0x80], &mut out); |
| 522 | assert_eq!(out, vec![-1.0]); |
| 523 | } |
| 524 | } |