| 1 | |
| 2 | |
| 3 | use ec_core::{ |
| 4 | AudioFrame, AudioParameters, Buf, ChannelLayout, ChannelPosition, CodecId, CodecParameters, |
| 5 | Decoder, Error, Frame, MediaParameters, Packet, Result, SampleFormat, Timestamp, |
| 6 | }; |
| 7 | |
| 8 | use crate::bsi::{self, Acmod, Bsi}; |
| 9 | use crate::decode::{Core, Syntax}; |
| 10 | use crate::dependent; |
| 11 | use crate::eac3; |
| 12 | use crate::syncinfo; |
| 13 | use crate::transform::BLOCK_SAMPLES; |
| 14 | |
| 15 | |
| 16 | const AC3_BLOCKS: usize = 6; |
| 17 | |
| 18 | |
| 19 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 20 | pub enum Downmix { |
| 21 | |
| 22 | #[default] |
| 23 | Native, |
| 24 | |
| 25 | Stereo, |
| 26 | |
| 27 | Mono, |
| 28 | } |
| 29 | |
| 30 | |
| 31 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 32 | pub struct Options { |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | pub drc_scale: f32, |
| 40 | |
| 41 | pub downmix: Downmix, |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | pub dither: bool, |
| 53 | } |
| 54 | |
| 55 | impl Default for Options { |
| 56 | fn default() -> Options { |
| 57 | Options { |
| 58 | drc_scale: 1.0, |
| 59 | downmix: Downmix::Native, |
| 60 | dither: true, |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | |
| 66 | |
| 67 | #[derive(Debug, Clone, PartialEq)] |
| 68 | pub struct FrameInfo { |
| 69 | |
| 70 | pub syntax: Syntax, |
| 71 | |
| 72 | pub sample_rate: u32, |
| 73 | |
| 74 | |
| 75 | pub nfchans: usize, |
| 76 | |
| 77 | pub lfeon: bool, |
| 78 | |
| 79 | |
| 80 | |
| 81 | pub dialnorm: u8, |
| 82 | |
| 83 | pub compr: Option<u8>, |
| 84 | |
| 85 | pub center_mix_level: Option<f32>, |
| 86 | |
| 87 | pub surround_mix_level: Option<f32>, |
| 88 | |
| 89 | pub bsmod: u8, |
| 90 | |
| 91 | pub acmod: Acmod, |
| 92 | |
| 93 | pub samples: usize, |
| 94 | } |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | pub struct Ac3Decoder { |
| 102 | core: Core, |
| 103 | |
| 104 | |
| 105 | dependents: Vec<Core>, |
| 106 | params: CodecParameters, |
| 107 | options: Options, |
| 108 | pending: Option<Frame>, |
| 109 | info: Option<FrameInfo>, |
| 110 | |
| 111 | flushed: bool, |
| 112 | } |
| 113 | |
| 114 | impl Default for Ac3Decoder { |
| 115 | fn default() -> Ac3Decoder { |
| 116 | Ac3Decoder::new() |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | impl Ac3Decoder { |
| 121 | |
| 122 | |
| 123 | pub fn new() -> Ac3Decoder { |
| 124 | Ac3Decoder::with_options(Options::default()) |
| 125 | } |
| 126 | |
| 127 | |
| 128 | pub fn with_options(options: Options) -> Ac3Decoder { |
| 129 | Ac3Decoder { |
| 130 | core: Core::new(), |
| 131 | dependents: Vec::new(), |
| 132 | params: CodecParameters::new(CodecId::Ac3), |
| 133 | options, |
| 134 | pending: None, |
| 135 | info: None, |
| 136 | flushed: false, |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | |
| 141 | pub fn options_mut(&mut self) -> &mut Options { |
| 142 | &mut self.options |
| 143 | } |
| 144 | |
| 145 | |
| 146 | pub fn frame_info(&self) -> Option<&FrameInfo> { |
| 147 | self.info.as_ref() |
| 148 | } |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | pub fn decode_frame(&mut self, data: &[u8]) -> Result<AudioFrame> { |
| 166 | let syncframe = self.decode_syncframe(data)?; |
| 167 | reject_tail(&data[syncframe.consumed..])?; |
| 168 | self.audio_frame(syncframe.info, syncframe.layout, syncframe.interleaved) |
| 169 | } |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | pub fn decode_packet(&mut self, data: &[u8]) -> Result<AudioFrame> { |
| 182 | let mut first = self.decode_syncframe(data)?; |
| 183 | let mut pos = first.consumed; |
| 184 | while begins_syncframe(&data[pos..]) { |
| 185 | let tail = &data[pos..]; |
| 186 | if tail[5] >> 3 > 10 { |
| 187 | let hdr = eac3::parse_from(&mut ec_core::BitReader::new(tail))?; |
| 188 | if hdr.substreamid != 0 { |
| 189 | return Err(Error::unsupported( |
| 190 | "E-AC-3 independent substream of another program in the packet", |
| 191 | "programs 2 and up are not decoded; the packet's first \ |
| 192 | program is the one this decoder produces", |
| 193 | )); |
| 194 | } |
| 195 | } |
| 196 | let next = self.decode_syncframe(tail).map_err(|e| match e { |
| 197 | Error::NeedMore => Error::corrupt("syncframe in the packet tail is truncated"), |
| 198 | other => other, |
| 199 | })?; |
| 200 | if next.layout != first.layout { |
| 201 | return Err(Error::unsupported( |
| 202 | "syncframes with different channel layouts in one packet", |
| 203 | "a packet's frames are concatenated into one frame of one layout", |
| 204 | )); |
| 205 | } |
| 206 | first.interleaved.extend(next.interleaved); |
| 207 | first.info = next.info; |
| 208 | pos += next.consumed; |
| 209 | } |
| 210 | self.audio_frame(first.info, first.layout, first.interleaved) |
| 211 | } |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | fn decode_syncframe(&mut self, data: &[u8]) -> Result<Syncframe> { |
| 217 | let mut samples = Vec::new(); |
| 218 | let (info, consumed) = self.decode_substream(data, &mut samples)?; |
| 219 | let (dependents, consumed) = self.decode_dependents(data, consumed, info.samples)?; |
| 220 | let mut frame = dependent::split(&samples, &self.core_positions(&info)); |
| 221 | for d in dependents { |
| 222 | frame = dependent::merge(frame, d); |
| 223 | } |
| 224 | let positions: Vec<ChannelPosition> = frame.iter().map(|c| c.position).collect(); |
| 225 | let layout = self.layout(&positions); |
| 226 | let interleaved = self.fold(dependent::interleave(&frame), &info, &positions); |
| 227 | Ok(Syncframe { |
| 228 | info, |
| 229 | layout, |
| 230 | interleaved, |
| 231 | consumed, |
| 232 | }) |
| 233 | } |
| 234 | |
| 235 | |
| 236 | |
| 237 | fn audio_frame( |
| 238 | &mut self, |
| 239 | info: FrameInfo, |
| 240 | layout: ChannelLayout, |
| 241 | interleaved: Vec<f32>, |
| 242 | ) -> Result<AudioFrame> { |
| 243 | let channels = layout.channel_count(); |
| 244 | let count = interleaved.len().checked_div(channels).unwrap_or(0); |
| 245 | self.params.media = MediaParameters::Audio(AudioParameters { |
| 246 | sample_rate: info.sample_rate, |
| 247 | layout: layout.clone(), |
| 248 | format: Some(SampleFormat::F32), |
| 249 | bits_per_sample: None, |
| 250 | }); |
| 251 | self.params.codec = match info.syntax { |
| 252 | Syntax::Ac3 => CodecId::Ac3, |
| 253 | Syntax::Eac3 => CodecId::EAc3, |
| 254 | }; |
| 255 | let mut bytes = Vec::with_capacity(interleaved.len() * 4); |
| 256 | for v in &interleaved { |
| 257 | bytes.extend_from_slice(&v.to_le_bytes()); |
| 258 | } |
| 259 | self.info = Some(info.clone()); |
| 260 | AudioFrame::try_new( |
| 261 | SampleFormat::F32, |
| 262 | false, |
| 263 | layout, |
| 264 | info.sample_rate, |
| 265 | count, |
| 266 | vec![Buf::from_vec(bytes)], |
| 267 | ) |
| 268 | } |
| 269 | |
| 270 | |
| 271 | |
| 272 | fn decode_substream(&mut self, data: &[u8], out: &mut Vec<f32>) -> Result<(FrameInfo, usize)> { |
| 273 | |
| 274 | if data.len() < 6 { |
| 275 | return Err(Error::NeedMore); |
| 276 | } |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | let bsid = data[5] >> 3; |
| 282 | let mut r = ec_core::BitReader::new(data); |
| 283 | if bsid <= 10 { |
| 284 | let sync = syncinfo::parse_from(&mut r)?; |
| 285 | let bsi = bsi::parse_from(&mut r)?; |
| 286 | if data.len() < sync.frame_size { |
| 287 | return Err(Error::NeedMore); |
| 288 | } |
| 289 | self.core.drc_scale = self.options.drc_scale; |
| 290 | self.core.dither_on = self.options.dither; |
| 291 | self.core |
| 292 | .start_frame(Syntax::Ac3, sync.fscod as usize, &bsi); |
| 293 | for blk in 0..AC3_BLOCKS { |
| 294 | self.core.block(&mut r, blk, out)?; |
| 295 | } |
| 296 | Ok(( |
| 297 | self.info_from(Syntax::Ac3, sync.sample_rate, &bsi, AC3_BLOCKS), |
| 298 | sync.frame_size, |
| 299 | )) |
| 300 | } else { |
| 301 | let hdr = eac3::bsi::parse_from(&mut r)?; |
| 302 | if data.len() < hdr.frame_size { |
| 303 | return Err(Error::NeedMore); |
| 304 | } |
| 305 | if hdr.strmtyp == eac3::StreamType::Dependent { |
| 306 | return Err(Error::unsupported( |
| 307 | "E-AC-3 dependent substream as the first substream of a packet", |
| 308 | "a dependent substream carries channel extensions for an \ |
| 309 | independent one that has to be decoded first", |
| 310 | )); |
| 311 | } |
| 312 | self.core.drc_scale = self.options.drc_scale; |
| 313 | self.core.dither_on = self.options.dither; |
| 314 | eac3::decode_frame(&mut self.core, &mut r, &hdr, out)?; |
| 315 | Ok(( |
| 316 | self.info_from(Syntax::Eac3, hdr.sample_rate, &hdr.bsi, hdr.nblocks), |
| 317 | hdr.frame_size, |
| 318 | )) |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | fn decode_dependents( |
| 326 | &mut self, |
| 327 | data: &[u8], |
| 328 | mut pos: usize, |
| 329 | frames: usize, |
| 330 | ) -> Result<(Vec<Vec<dependent::Channel>>, usize)> { |
| 331 | let mut found = Vec::new(); |
| 332 | let mut slot = 0; |
| 333 | while let Some(hdr) = dependent::peek(&data[pos..]) { |
| 334 | let body = data |
| 335 | .get(pos..pos + hdr.frame_size) |
| 336 | .ok_or_else(|| Error::corrupt("E-AC-3 dependent substream: truncated"))?; |
| 337 | if hdr.nblocks * BLOCK_SAMPLES != frames { |
| 338 | return Err(Error::corrupt(format!( |
| 339 | "E-AC-3 dependent substream: {} blocks, the independent substream has {}", |
| 340 | hdr.nblocks, |
| 341 | frames / BLOCK_SAMPLES |
| 342 | ))); |
| 343 | } |
| 344 | let channels = hdr.nfchans + usize::from(hdr.bsi.lfeon); |
| 345 | let positions = dependent::positions(hdr.chanmap, channels)?; |
| 346 | if self.dependents.len() <= slot { |
| 347 | self.dependents.push(Core::new()); |
| 348 | } |
| 349 | let (drc_scale, dither) = (self.options.drc_scale, self.options.dither); |
| 350 | let core = &mut self.dependents[slot]; |
| 351 | core.drc_scale = drc_scale; |
| 352 | core.dither_on = dither; |
| 353 | let mut r = ec_core::BitReader::new(body); |
| 354 | let own = eac3::parse_from(&mut r)?; |
| 355 | let mut samples = Vec::new(); |
| 356 | eac3::decode_frame(core, &mut r, &own, &mut samples)?; |
| 357 | found.push(dependent::split(&samples, &positions)); |
| 358 | slot += 1; |
| 359 | pos += hdr.frame_size; |
| 360 | } |
| 361 | Ok((found, pos)) |
| 362 | } |
| 363 | |
| 364 | fn info_from(&self, syntax: Syntax, sample_rate: u32, bsi: &Bsi, nblocks: usize) -> FrameInfo { |
| 365 | FrameInfo { |
| 366 | syntax, |
| 367 | sample_rate, |
| 368 | nfchans: bsi.nfchans, |
| 369 | lfeon: bsi.lfeon, |
| 370 | dialnorm: bsi.dialnorm, |
| 371 | compr: bsi.compr, |
| 372 | center_mix_level: bsi.cmixlev.map(bsi::center_mix_level), |
| 373 | surround_mix_level: bsi.surmixlev.map(bsi::surround_mix_level), |
| 374 | bsmod: bsi.bsmod, |
| 375 | acmod: bsi.acmod, |
| 376 | samples: nblocks * BLOCK_SAMPLES, |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | |
| 381 | |
| 382 | fn core_positions(&self, info: &FrameInfo) -> Vec<ChannelPosition> { |
| 383 | use ChannelPosition::*; |
| 384 | let mut positions: Vec<ChannelPosition> = match info.acmod { |
| 385 | Acmod::DualMono => vec![FrontLeft, FrontRight], |
| 386 | Acmod::Mono => vec![FrontCenter], |
| 387 | Acmod::Stereo => vec![FrontLeft, FrontRight], |
| 388 | Acmod::Surround3_0 => vec![FrontLeft, FrontRight, FrontCenter], |
| 389 | Acmod::Surround2_1 => vec![FrontLeft, FrontRight, BackCenter], |
| 390 | Acmod::Surround3_1 => vec![FrontLeft, FrontRight, FrontCenter, BackCenter], |
| 391 | Acmod::Surround2_2 => vec![FrontLeft, FrontRight, BackLeft, BackRight], |
| 392 | |
| 393 | Acmod::Surround3_2 => vec![FrontLeft, FrontRight, FrontCenter, SideLeft, SideRight], |
| 394 | }; |
| 395 | if info.lfeon { |
| 396 | let fronts = match info.acmod { |
| 397 | Acmod::Mono => 1, |
| 398 | Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => 3, |
| 399 | _ => 2, |
| 400 | }; |
| 401 | positions.insert(fronts.min(positions.len()), Lfe); |
| 402 | } |
| 403 | positions |
| 404 | } |
| 405 | |
| 406 | |
| 407 | fn layout(&self, positions: &[ChannelPosition]) -> ChannelLayout { |
| 408 | match self.options.downmix { |
| 409 | Downmix::Native => layout_of(positions), |
| 410 | Downmix::Stereo => ChannelLayout::Stereo, |
| 411 | Downmix::Mono => ChannelLayout::Mono, |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | |
| 416 | fn fold(&self, samples: Vec<f32>, info: &FrameInfo, positions: &[ChannelPosition]) -> Vec<f32> { |
| 417 | if self.options.downmix == Downmix::Native { |
| 418 | return samples; |
| 419 | } |
| 420 | let channels = positions.len(); |
| 421 | if channels == 0 { |
| 422 | return samples; |
| 423 | } |
| 424 | let clev = info.center_mix_level.unwrap_or(0.707); |
| 425 | let slev = info.surround_mix_level.unwrap_or(0.707); |
| 426 | |
| 427 | |
| 428 | |
| 429 | let (mut left, mut right) = (Vec::new(), Vec::new()); |
| 430 | for &p in positions { |
| 431 | let (l, r) = match p { |
| 432 | ChannelPosition::FrontLeft => (1.0, 0.0), |
| 433 | ChannelPosition::FrontRight => (0.0, 1.0), |
| 434 | ChannelPosition::FrontCenter => (clev, clev), |
| 435 | |
| 436 | |
| 437 | ChannelPosition::FrontLeftOfCenter => (0.707, 0.0), |
| 438 | ChannelPosition::FrontRightOfCenter => (0.0, 0.707), |
| 439 | ChannelPosition::BackLeft | ChannelPosition::SideLeft => (slev, 0.0), |
| 440 | ChannelPosition::BackRight | ChannelPosition::SideRight => (0.0, slev), |
| 441 | |
| 442 | ChannelPosition::BackCenter => (0.7 * slev, 0.7 * slev), |
| 443 | |
| 444 | _ => (0.0, 0.0), |
| 445 | }; |
| 446 | left.push(l); |
| 447 | right.push(r); |
| 448 | } |
| 449 | let peak = left |
| 450 | .iter() |
| 451 | .sum::<f32>() |
| 452 | .max(right.iter().sum::<f32>()) |
| 453 | .max(1.0); |
| 454 | let frames = samples.len() / channels; |
| 455 | match self.options.downmix { |
| 456 | Downmix::Stereo => { |
| 457 | let mut out = vec![0.0; frames * 2]; |
| 458 | for f in 0..frames { |
| 459 | let block = &samples[f * channels..(f + 1) * channels]; |
| 460 | let (mut lo, mut ro) = (0.0, 0.0); |
| 461 | for (ch, &v) in block.iter().enumerate() { |
| 462 | lo += v * left[ch]; |
| 463 | ro += v * right[ch]; |
| 464 | } |
| 465 | out[f * 2] = lo / peak; |
| 466 | out[f * 2 + 1] = ro / peak; |
| 467 | } |
| 468 | out |
| 469 | } |
| 470 | _ => { |
| 471 | let mut out = vec![0.0; frames]; |
| 472 | for f in 0..frames { |
| 473 | let block = &samples[f * channels..(f + 1) * channels]; |
| 474 | let mut m = 0.0; |
| 475 | for (ch, &v) in block.iter().enumerate() { |
| 476 | m += v * (left[ch] + right[ch]); |
| 477 | } |
| 478 | out[f] = m / (2.0 * peak); |
| 479 | } |
| 480 | out |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | impl Decoder for Ac3Decoder { |
| 487 | fn codec_parameters(&self) -> &CodecParameters { |
| 488 | &self.params |
| 489 | } |
| 490 | |
| 491 | fn send_packet(&mut self, packet: &Packet) -> Result<()> { |
| 492 | let mut frame = self.decode_packet(&packet.data)?; |
| 493 | frame.pts = packet.pts.map(|ts| Timestamp::new(ts, packet.time_base)); |
| 494 | self.pending = Some(Frame::Audio(frame)); |
| 495 | Ok(()) |
| 496 | } |
| 497 | |
| 498 | fn receive_frame(&mut self) -> Result<Frame> { |
| 499 | match self.pending.take() { |
| 500 | Some(frame) => Ok(frame), |
| 501 | None if self.flushed => Err(Error::Eof), |
| 502 | None => Err(Error::NeedMore), |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | fn flush(&mut self) -> Result<()> { |
| 507 | |
| 508 | |
| 509 | |
| 510 | self.flushed = true; |
| 511 | Ok(()) |
| 512 | } |
| 513 | |
| 514 | fn reset(&mut self) { |
| 515 | self.core.reset(); |
| 516 | for d in &mut self.dependents { |
| 517 | d.reset(); |
| 518 | } |
| 519 | self.pending = None; |
| 520 | self.flushed = false; |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | |
| 525 | |
| 526 | fn layout_of(positions: &[ChannelPosition]) -> ChannelLayout { |
| 527 | match positions { |
| 528 | [ChannelPosition::FrontCenter] => ChannelLayout::Mono, |
| 529 | [ChannelPosition::FrontLeft, ChannelPosition::FrontRight] => ChannelLayout::Stereo, |
| 530 | _ if positions == ChannelLayout::Surround5_1.positions() => ChannelLayout::Surround5_1, |
| 531 | _ if positions == ChannelLayout::Surround7_1.positions() => ChannelLayout::Surround7_1, |
| 532 | _ => ChannelLayout::Custom(positions.to_vec()), |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | |
| 537 | |
| 538 | |
| 539 | struct Syncframe { |
| 540 | info: FrameInfo, |
| 541 | layout: ChannelLayout, |
| 542 | interleaved: Vec<f32>, |
| 543 | consumed: usize, |
| 544 | } |
| 545 | |
| 546 | |
| 547 | |
| 548 | |
| 549 | |
| 550 | fn begins_syncframe(tail: &[u8]) -> bool { |
| 551 | |
| 552 | |
| 553 | if tail.len() < 6 || u16::from_be_bytes([tail[0], tail[1]]) != syncinfo::SYNCWORD { |
| 554 | return false; |
| 555 | } |
| 556 | if tail[5] >> 3 > 10 { |
| 557 | eac3::parse_from(&mut ec_core::BitReader::new(tail)).is_ok() |
| 558 | } else { |
| 559 | syncinfo::parse(tail).is_ok() |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | |
| 564 | |
| 565 | |
| 566 | |
| 567 | |
| 568 | |
| 569 | fn reject_tail(tail: &[u8]) -> Result<()> { |
| 570 | if begins_syncframe(tail) { |
| 571 | return Err(Error::unsupported( |
| 572 | "a second syncframe in the tail of the packet", |
| 573 | "decode_frame takes one syncframe; decode_packet (and send_packet) \ |
| 574 | walks a packet holding several", |
| 575 | )); |
| 576 | } |
| 577 | Ok(()) |
| 578 | } |