| 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::eac3; |
| 11 | use crate::syncinfo; |
| 12 | use crate::transform::BLOCK_SAMPLES; |
| 13 | |
| 14 | |
| 15 | const AC3_BLOCKS: usize = 6; |
| 16 | |
| 17 | |
| 18 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 19 | pub enum Downmix { |
| 20 | |
| 21 | #[default] |
| 22 | Native, |
| 23 | |
| 24 | Stereo, |
| 25 | |
| 26 | Mono, |
| 27 | } |
| 28 | |
| 29 | |
| 30 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 31 | pub struct Options { |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | pub drc_scale: f32, |
| 39 | |
| 40 | pub downmix: Downmix, |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | pub dither: bool, |
| 52 | } |
| 53 | |
| 54 | impl Default for Options { |
| 55 | fn default() -> Options { |
| 56 | Options { |
| 57 | drc_scale: 1.0, |
| 58 | downmix: Downmix::Native, |
| 59 | dither: true, |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | |
| 65 | |
| 66 | #[derive(Debug, Clone, PartialEq)] |
| 67 | pub struct FrameInfo { |
| 68 | |
| 69 | pub syntax: Syntax, |
| 70 | |
| 71 | pub sample_rate: u32, |
| 72 | |
| 73 | pub nfchans: usize, |
| 74 | |
| 75 | pub lfeon: bool, |
| 76 | |
| 77 | |
| 78 | |
| 79 | pub dialnorm: u8, |
| 80 | |
| 81 | pub compr: Option<u8>, |
| 82 | |
| 83 | pub center_mix_level: Option<f32>, |
| 84 | |
| 85 | pub surround_mix_level: Option<f32>, |
| 86 | |
| 87 | pub bsmod: u8, |
| 88 | |
| 89 | pub acmod: Acmod, |
| 90 | |
| 91 | pub samples: usize, |
| 92 | } |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | pub struct Ac3Decoder { |
| 99 | core: Core, |
| 100 | params: CodecParameters, |
| 101 | options: Options, |
| 102 | pending: Option<Frame>, |
| 103 | info: Option<FrameInfo>, |
| 104 | |
| 105 | flushed: bool, |
| 106 | } |
| 107 | |
| 108 | impl Default for Ac3Decoder { |
| 109 | fn default() -> Ac3Decoder { |
| 110 | Ac3Decoder::new() |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | impl Ac3Decoder { |
| 115 | |
| 116 | |
| 117 | pub fn new() -> Ac3Decoder { |
| 118 | Ac3Decoder::with_options(Options::default()) |
| 119 | } |
| 120 | |
| 121 | |
| 122 | pub fn with_options(options: Options) -> Ac3Decoder { |
| 123 | Ac3Decoder { |
| 124 | core: Core::new(), |
| 125 | params: CodecParameters::new(CodecId::Ac3), |
| 126 | options, |
| 127 | pending: None, |
| 128 | info: None, |
| 129 | flushed: false, |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | |
| 134 | pub fn options_mut(&mut self) -> &mut Options { |
| 135 | &mut self.options |
| 136 | } |
| 137 | |
| 138 | |
| 139 | pub fn frame_info(&self) -> Option<&FrameInfo> { |
| 140 | self.info.as_ref() |
| 141 | } |
| 142 | |
| 143 | |
| 144 | |
| 145 | |
| 146 | |
| 147 | |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | pub fn decode_frame(&mut self, data: &[u8]) -> Result<AudioFrame> { |
| 157 | let mut samples = Vec::new(); |
| 158 | let (info, consumed) = self.decode_substream(data, &mut samples)?; |
| 159 | reject_tail(&data[consumed..])?; |
| 160 | let layout = self.layout(&info); |
| 161 | let interleaved = self.fold(samples, &info); |
| 162 | let channels = layout.channel_count(); |
| 163 | let count = interleaved.len().checked_div(channels).unwrap_or(0); |
| 164 | self.info = Some(info.clone()); |
| 165 | self.params.media = MediaParameters::Audio(AudioParameters { |
| 166 | sample_rate: info.sample_rate, |
| 167 | layout: layout.clone(), |
| 168 | format: Some(SampleFormat::F32), |
| 169 | bits_per_sample: None, |
| 170 | }); |
| 171 | self.params.codec = match info.syntax { |
| 172 | Syntax::Ac3 => CodecId::Ac3, |
| 173 | Syntax::Eac3 => CodecId::EAc3, |
| 174 | }; |
| 175 | let mut bytes = Vec::with_capacity(interleaved.len() * 4); |
| 176 | for v in &interleaved { |
| 177 | bytes.extend_from_slice(&v.to_le_bytes()); |
| 178 | } |
| 179 | AudioFrame::try_new( |
| 180 | SampleFormat::F32, |
| 181 | false, |
| 182 | layout, |
| 183 | info.sample_rate, |
| 184 | count, |
| 185 | vec![Buf::from_vec(bytes)], |
| 186 | ) |
| 187 | } |
| 188 | |
| 189 | |
| 190 | |
| 191 | fn decode_substream(&mut self, data: &[u8], out: &mut Vec<f32>) -> Result<(FrameInfo, usize)> { |
| 192 | |
| 193 | if data.len() < 6 { |
| 194 | return Err(Error::NeedMore); |
| 195 | } |
| 196 | |
| 197 | |
| 198 | |
| 199 | |
| 200 | let bsid = data[5] >> 3; |
| 201 | let mut r = ec_core::BitReader::new(data); |
| 202 | if bsid <= 10 { |
| 203 | let sync = syncinfo::parse_from(&mut r)?; |
| 204 | let bsi = bsi::parse_from(&mut r)?; |
| 205 | if data.len() < sync.frame_size { |
| 206 | return Err(Error::NeedMore); |
| 207 | } |
| 208 | self.core.drc_scale = self.options.drc_scale; |
| 209 | self.core.dither_on = self.options.dither; |
| 210 | self.core |
| 211 | .start_frame(Syntax::Ac3, sync.fscod as usize, &bsi); |
| 212 | for blk in 0..AC3_BLOCKS { |
| 213 | self.core.block(&mut r, blk, out)?; |
| 214 | } |
| 215 | Ok(( |
| 216 | self.info_from(Syntax::Ac3, sync.sample_rate, &bsi, AC3_BLOCKS), |
| 217 | sync.frame_size, |
| 218 | )) |
| 219 | } else { |
| 220 | let hdr = eac3::bsi::parse_from(&mut r)?; |
| 221 | if data.len() < hdr.frame_size { |
| 222 | return Err(Error::NeedMore); |
| 223 | } |
| 224 | if hdr.strmtyp == eac3::StreamType::Dependent { |
| 225 | return Err(Error::unsupported( |
| 226 | "E-AC-3 dependent substream as the first substream of a packet", |
| 227 | "a dependent substream carries channel extensions for an \ |
| 228 | independent one that has to be decoded first", |
| 229 | )); |
| 230 | } |
| 231 | self.core.drc_scale = self.options.drc_scale; |
| 232 | self.core.dither_on = self.options.dither; |
| 233 | eac3::decode_frame(&mut self.core, &mut r, &hdr, out)?; |
| 234 | Ok(( |
| 235 | self.info_from(Syntax::Eac3, hdr.sample_rate, &hdr.bsi, hdr.nblocks), |
| 236 | hdr.frame_size, |
| 237 | )) |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | fn info_from(&self, syntax: Syntax, sample_rate: u32, bsi: &Bsi, nblocks: usize) -> FrameInfo { |
| 242 | FrameInfo { |
| 243 | syntax, |
| 244 | sample_rate, |
| 245 | nfchans: bsi.nfchans, |
| 246 | lfeon: bsi.lfeon, |
| 247 | dialnorm: bsi.dialnorm, |
| 248 | compr: bsi.compr, |
| 249 | center_mix_level: bsi.cmixlev.map(bsi::center_mix_level), |
| 250 | surround_mix_level: bsi.surmixlev.map(bsi::surround_mix_level), |
| 251 | bsmod: bsi.bsmod, |
| 252 | acmod: bsi.acmod, |
| 253 | samples: nblocks * BLOCK_SAMPLES, |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | |
| 258 | fn native_layout(&self, info: &FrameInfo) -> ChannelLayout { |
| 259 | use ChannelPosition::*; |
| 260 | let mut positions: Vec<ChannelPosition> = match info.acmod { |
| 261 | Acmod::DualMono => vec![FrontLeft, FrontRight], |
| 262 | Acmod::Mono => vec![FrontCenter], |
| 263 | Acmod::Stereo => vec![FrontLeft, FrontRight], |
| 264 | Acmod::Surround3_0 => vec![FrontLeft, FrontRight, FrontCenter], |
| 265 | Acmod::Surround2_1 => vec![FrontLeft, FrontRight, BackCenter], |
| 266 | Acmod::Surround3_1 => vec![FrontLeft, FrontRight, FrontCenter, BackCenter], |
| 267 | Acmod::Surround2_2 => vec![FrontLeft, FrontRight, BackLeft, BackRight], |
| 268 | Acmod::Surround3_2 => vec![FrontLeft, FrontRight, FrontCenter, BackLeft, BackRight], |
| 269 | }; |
| 270 | if info.lfeon { |
| 271 | let fronts = match info.acmod { |
| 272 | Acmod::Mono => 1, |
| 273 | Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => 3, |
| 274 | _ => 2, |
| 275 | }; |
| 276 | positions.insert(fronts.min(positions.len()), Lfe); |
| 277 | } |
| 278 | match positions.len() { |
| 279 | 1 => ChannelLayout::Mono, |
| 280 | 2 => ChannelLayout::Stereo, |
| 281 | _ if positions == ChannelLayout::Surround5_1.positions() => ChannelLayout::Surround5_1, |
| 282 | _ => ChannelLayout::Custom(positions), |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | fn layout(&self, info: &FrameInfo) -> ChannelLayout { |
| 287 | match self.options.downmix { |
| 288 | Downmix::Native => self.native_layout(info), |
| 289 | Downmix::Stereo => ChannelLayout::Stereo, |
| 290 | Downmix::Mono => ChannelLayout::Mono, |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | |
| 295 | fn fold(&self, samples: Vec<f32>, info: &FrameInfo) -> Vec<f32> { |
| 296 | if self.options.downmix == Downmix::Native { |
| 297 | return samples; |
| 298 | } |
| 299 | let layout = self.native_layout(info); |
| 300 | let positions = layout.positions().to_vec(); |
| 301 | let channels = positions.len(); |
| 302 | if channels == 0 { |
| 303 | return samples; |
| 304 | } |
| 305 | let clev = info.center_mix_level.unwrap_or(0.707); |
| 306 | let slev = info.surround_mix_level.unwrap_or(0.707); |
| 307 | |
| 308 | |
| 309 | |
| 310 | let (mut left, mut right) = (Vec::new(), Vec::new()); |
| 311 | for &p in &positions { |
| 312 | let (l, r) = match p { |
| 313 | ChannelPosition::FrontLeft => (1.0, 0.0), |
| 314 | ChannelPosition::FrontRight => (0.0, 1.0), |
| 315 | ChannelPosition::FrontCenter => (clev, clev), |
| 316 | ChannelPosition::BackLeft | ChannelPosition::SideLeft => (slev, 0.0), |
| 317 | ChannelPosition::BackRight | ChannelPosition::SideRight => (0.0, slev), |
| 318 | |
| 319 | ChannelPosition::BackCenter => (0.7 * slev, 0.7 * slev), |
| 320 | |
| 321 | _ => (0.0, 0.0), |
| 322 | }; |
| 323 | left.push(l); |
| 324 | right.push(r); |
| 325 | } |
| 326 | let peak = left |
| 327 | .iter() |
| 328 | .sum::<f32>() |
| 329 | .max(right.iter().sum::<f32>()) |
| 330 | .max(1.0); |
| 331 | let frames = samples.len() / channels; |
| 332 | match self.options.downmix { |
| 333 | Downmix::Stereo => { |
| 334 | let mut out = vec![0.0; frames * 2]; |
| 335 | for f in 0..frames { |
| 336 | let block = &samples[f * channels..(f + 1) * channels]; |
| 337 | let (mut lo, mut ro) = (0.0, 0.0); |
| 338 | for (ch, &v) in block.iter().enumerate() { |
| 339 | lo += v * left[ch]; |
| 340 | ro += v * right[ch]; |
| 341 | } |
| 342 | out[f * 2] = lo / peak; |
| 343 | out[f * 2 + 1] = ro / peak; |
| 344 | } |
| 345 | out |
| 346 | } |
| 347 | _ => { |
| 348 | let mut out = vec![0.0; frames]; |
| 349 | for f in 0..frames { |
| 350 | let block = &samples[f * channels..(f + 1) * channels]; |
| 351 | let mut m = 0.0; |
| 352 | for (ch, &v) in block.iter().enumerate() { |
| 353 | m += v * (left[ch] + right[ch]); |
| 354 | } |
| 355 | out[f] = m / (2.0 * peak); |
| 356 | } |
| 357 | out |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | impl Decoder for Ac3Decoder { |
| 364 | fn codec_parameters(&self) -> &CodecParameters { |
| 365 | &self.params |
| 366 | } |
| 367 | |
| 368 | fn send_packet(&mut self, packet: &Packet) -> Result<()> { |
| 369 | let mut frame = self.decode_frame(&packet.data)?; |
| 370 | frame.pts = packet.pts.map(|ts| Timestamp::new(ts, packet.time_base)); |
| 371 | self.pending = Some(Frame::Audio(frame)); |
| 372 | Ok(()) |
| 373 | } |
| 374 | |
| 375 | fn receive_frame(&mut self) -> Result<Frame> { |
| 376 | match self.pending.take() { |
| 377 | Some(frame) => Ok(frame), |
| 378 | None if self.flushed => Err(Error::Eof), |
| 379 | None => Err(Error::NeedMore), |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | fn flush(&mut self) -> Result<()> { |
| 384 | |
| 385 | |
| 386 | |
| 387 | self.flushed = true; |
| 388 | Ok(()) |
| 389 | } |
| 390 | |
| 391 | fn reset(&mut self) { |
| 392 | self.core.reset(); |
| 393 | self.pending = None; |
| 394 | self.flushed = false; |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | fn reject_tail(tail: &[u8]) -> Result<()> { |
| 407 | |
| 408 | |
| 409 | if tail.len() < 6 || u16::from_be_bytes([tail[0], tail[1]]) != syncinfo::SYNCWORD { |
| 410 | return Ok(()); |
| 411 | } |
| 412 | let named = if tail[5] >> 3 > 10 { |
| 413 | match eac3::parse_from(&mut ec_core::BitReader::new(tail)) { |
| 414 | |
| 415 | |
| 416 | |
| 417 | Ok(hdr) if hdr.strmtyp == eac3::StreamType::Dependent => Some(( |
| 418 | "E-AC-3 dependent substream in the tail of the packet", |
| 419 | "a dependent substream carries channel extensions for an \ |
| 420 | independent one that has to be decoded first", |
| 421 | )), |
| 422 | Ok(_) => Some(( |
| 423 | "a second syncframe in the tail of the packet", |
| 424 | "one packet is one syncframe and the substreams that belong \ |
| 425 | to it; hand frames to the decoder one at a time", |
| 426 | )), |
| 427 | |
| 428 | Err(_) => None, |
| 429 | } |
| 430 | } else { |
| 431 | syncinfo::parse(tail).is_ok().then_some(( |
| 432 | "a second syncframe in the tail of the packet", |
| 433 | "one packet is one syncframe and the substreams that belong \ |
| 434 | to it; hand frames to the decoder one at a time", |
| 435 | )) |
| 436 | }; |
| 437 | match named { |
| 438 | Some((what, why)) => Err(Error::unsupported(what, why)), |
| 439 | None => Ok(()), |
| 440 | } |
| 441 | } |