edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·381.4 MiB·6c331af·Tahinli·11 hours ago·4261 commits
| 1 | //! Syncframe and audio-block decoding: everything between a parsed header and |
| 2 | //! a block of PCM (A/52 §6.1, §7.3-§7.9). |
| 3 | //! |
| 4 | //! One [`Core`] holds the state a syncframe stream carries from block to block |
| 5 | //! and from frame to frame — exponents, coupling coordinates, bit allocation |
| 6 | //! parameters, and the overlap-add tail. The audio block routine parses |
| 7 | //! `audblk()` in bit stream order, because that is the only order in which it |
| 8 | //! can be parsed: the number of bits a mantissa occupies is computed, not sent. |
| 9 | |
| 10 | use ec_core::{BitReader, Error, Result}; |
| 11 | |
| 12 | use crate::bitalloc::{self, Allocation, BitAllocParams, Channel, DeltaBa}; |
| 13 | use crate::bsi::{Acmod, Bsi}; |
| 14 | use crate::exps::{self, Strategy}; |
| 15 | use crate::mantissa::{Dither, Mantissas, scale, shift}; |
| 16 | use crate::transform::{BLOCK_SAMPLES, Imdct}; |
| 17 | |
| 18 | /// Full-bandwidth channels at most (3/2 mode). |
| 19 | pub(crate) const MAX_FBW: usize = 5; |
| 20 | /// Index of the LFE channel in the per-channel arrays. |
| 21 | pub(crate) const LFE: usize = 5; |
| 22 | /// Index of the coupling channel in the per-channel arrays. |
| 23 | pub(crate) const CPL: usize = 6; |
| 24 | /// Coded channels a frame can carry, plus the coupling channel. |
| 25 | pub(crate) const CHANNELS: usize = 7; |
| 26 | /// Coefficients per channel per block. |
| 27 | pub(crate) const COEFFS: usize = 256; |
| 28 | |
| 29 | /// Which syntax the frame is written in. |
| 30 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 31 | pub enum Syntax { |
| 32 | /// AC-3 (`bsid <= 10`), six blocks per frame. |
| 33 | Ac3, |
| 34 | /// Enhanced AC-3 (Annex E, `bsid == 16`), one to six blocks per frame. |
| 35 | Eac3, |
| 36 | } |
| 37 | |
| 38 | /// The decoder state a stream carries across blocks and frames. |
| 39 | pub(crate) struct Core { |
| 40 | pub(crate) syntax: Syntax, |
| 41 | pub(crate) fscod: usize, |
| 42 | pub(crate) acmod: Acmod, |
| 43 | pub(crate) nfchans: usize, |
| 44 | pub(crate) lfeon: bool, |
| 45 | /// Decoded exponents per channel, valid up to that channel's `endmant`. |
| 46 | /// |
| 47 | /// Boxed, with `bap`, `coeffs` and `delay`, because the four are 16896 of |
| 48 | /// `Core`'s 19728 bytes and `Core` sits inline in the `Ac3Decoder` that |
| 49 | /// `Ac3Decoder::new` hands a caller BY VALUE. Indexing and `&mut self.f[ch]` |
| 50 | /// read through the box unchanged. `Stack`: crate::stack_budget. |
| 51 | pub(crate) exps: Box<[[u8; COEFFS]; CHANNELS]>, |
| 52 | /// Bit allocation pointers per channel. |
| 53 | pub(crate) bap: Box<[[u8; COEFFS]; CHANNELS]>, |
| 54 | /// Exponent strategy of the current block per channel. |
| 55 | pub(crate) expstr: [Strategy; CHANNELS], |
| 56 | pub(crate) endmant: [usize; CHANNELS], |
| 57 | pub(crate) strtmant: [usize; CHANNELS], |
| 58 | // Coupling. |
| 59 | pub(crate) cplinu: bool, |
| 60 | pub(crate) chincpl: [bool; MAX_FBW], |
| 61 | pub(crate) phsflginu: bool, |
| 62 | pub(crate) cplbegf: usize, |
| 63 | pub(crate) ncplsubnd: usize, |
| 64 | pub(crate) ncplbnd: usize, |
| 65 | /// Coupling band each sub-band belongs to, after `cplbndstrc` merging. |
| 66 | pub(crate) cplband: [usize; 18], |
| 67 | pub(crate) cplco: [[i32; 18]; MAX_FBW], |
| 68 | pub(crate) phsflg: [bool; 18], |
| 69 | pub(crate) cplleak: (i32, i32), |
| 70 | /// Annex E sends a channel's coupling coordinates in the first block of |
| 71 | /// each coupling run and only when they change after that. |
| 72 | pub(crate) first_cplco: [bool; MAX_FBW], |
| 73 | /// Likewise for the coupling leak initialisation. |
| 74 | pub(crate) first_cplleak: bool, |
| 75 | // Rematrixing. |
| 76 | pub(crate) nrematbnd: usize, |
| 77 | pub(crate) rematflg: [bool; 4], |
| 78 | // Bit allocation. |
| 79 | pub(crate) ba: BitAllocParams, |
| 80 | pub(crate) csnroffst: u8, |
| 81 | pub(crate) fsnroffst: [u8; CHANNELS], |
| 82 | pub(crate) fgaincod: [u8; CHANNELS], |
| 83 | pub(crate) deltba: [DeltaBa; CHANNELS], |
| 84 | pub(crate) deltba_on: [bool; CHANNELS], |
| 85 | // Per-block flags. |
| 86 | pub(crate) blksw: [bool; MAX_FBW], |
| 87 | pub(crate) dithflag: [bool; MAX_FBW], |
| 88 | /// Dynamic range gain for program 1 and, in 1+1 mode, program 2. |
| 89 | pub(crate) dynrng: [f32; 2], |
| 90 | // Output. |
| 91 | pub(crate) coeffs: Box<[[f32; COEFFS]; CHANNELS]>, |
| 92 | pub(crate) delay: Box<[[f32; COEFFS]; MAX_FBW + 1]>, |
| 93 | pub(crate) imdct: Imdct, |
| 94 | pub(crate) dither: Dither, |
| 95 | /// Fraction of the `dynrng` compression to apply (§7.7.1). |
| 96 | pub(crate) drc_scale: f32, |
| 97 | /// Whether zero-bit mantissas get dither (§7.3.4). |
| 98 | pub(crate) dither_on: bool, |
| 99 | // Spectral extension (Annex E §3.6). All unused under AC-3. |
| 100 | pub(crate) spxinu: bool, |
| 101 | pub(crate) chinspx: [bool; MAX_FBW], |
| 102 | /// First and last-plus-one spectral extension sub-band. |
| 103 | pub(crate) spx_begin: usize, |
| 104 | pub(crate) spx_end: usize, |
| 105 | /// Sub-band the copy region starts at. |
| 106 | pub(crate) spxstrtf: usize, |
| 107 | /// Raw `spxbegf`, which the coupling end frequency is derived from. |
| 108 | pub(crate) spxbegf: usize, |
| 109 | pub(crate) spxbndstrc: [bool; 18], |
| 110 | /// Coupling banding structure, kept across blocks for Annex E's "reuse". |
| 111 | pub(crate) cplbndstrc: [bool; 18], |
| 112 | pub(crate) nspxbnds: usize, |
| 113 | pub(crate) spxbndsz: [usize; 18], |
| 114 | pub(crate) spxco: [[f32; 18]; MAX_FBW], |
| 115 | /// Noise and signal blending factors per band. |
| 116 | pub(crate) nblend: [[f32; 18]; MAX_FBW], |
| 117 | pub(crate) sblend: [[f32; 18]; MAX_FBW], |
| 118 | pub(crate) first_spxco: [bool; MAX_FBW], |
| 119 | pub(crate) chinspxatten: [bool; MAX_FBW], |
| 120 | pub(crate) spxattencod: [u8; MAX_FBW], |
| 121 | // Adaptive hybrid transform (Annex E §3.4). All false under AC-3. |
| 122 | /// Which channels are AHT-coded this frame. |
| 123 | pub(crate) aht: [bool; CHANNELS], |
| 124 | /// Whether a channel's whole-frame AHT payload has been read yet. |
| 125 | pub(crate) aht_read: [bool; CHANNELS], |
| 126 | /// Six blocks of mantissas per channel: `[ch][blk * COEFFS + bin]`. |
| 127 | pub(crate) aht_mant: Vec<f32>, |
| 128 | } |
| 129 | |
| 130 | impl Core { |
| 131 | /// A decoder with no history: silence in the overlap-add tail and no |
| 132 | /// coupling, which is the state the standard asks for at a sync point. |
| 133 | pub(crate) fn new() -> Core { |
| 134 | Core { |
| 135 | syntax: Syntax::Ac3, |
| 136 | fscod: 0, |
| 137 | acmod: Acmod::Stereo, |
| 138 | nfchans: 2, |
| 139 | lfeon: false, |
| 140 | exps: Box::new([[0; COEFFS]; CHANNELS]), |
| 141 | bap: Box::new([[0; COEFFS]; CHANNELS]), |
| 142 | expstr: [Strategy::Reuse; CHANNELS], |
| 143 | endmant: [0; CHANNELS], |
| 144 | strtmant: [0; CHANNELS], |
| 145 | cplinu: false, |
| 146 | chincpl: [false; MAX_FBW], |
| 147 | phsflginu: false, |
| 148 | cplbegf: 0, |
| 149 | ncplsubnd: 0, |
| 150 | ncplbnd: 0, |
| 151 | cplband: [0; 18], |
| 152 | cplco: [[0; 18]; MAX_FBW], |
| 153 | phsflg: [false; 18], |
| 154 | cplleak: (0, 0), |
| 155 | first_cplco: [true; MAX_FBW], |
| 156 | first_cplleak: true, |
| 157 | nrematbnd: 0, |
| 158 | rematflg: [false; 4], |
| 159 | ba: BitAllocParams::default(), |
| 160 | csnroffst: 0, |
| 161 | fsnroffst: [0; CHANNELS], |
| 162 | fgaincod: [0; CHANNELS], |
| 163 | deltba: [DeltaBa::default(); CHANNELS], |
| 164 | deltba_on: [false; CHANNELS], |
| 165 | blksw: [false; MAX_FBW], |
| 166 | dithflag: [true; MAX_FBW], |
| 167 | dynrng: [1.0; 2], |
| 168 | coeffs: Box::new([[0.0; COEFFS]; CHANNELS]), |
| 169 | delay: Box::new([[0.0; COEFFS]; MAX_FBW + 1]), |
| 170 | imdct: Imdct::new(), |
| 171 | dither: Dither::default(), |
| 172 | drc_scale: 1.0, |
| 173 | dither_on: true, |
| 174 | spxinu: false, |
| 175 | chinspx: [false; MAX_FBW], |
| 176 | spx_begin: 0, |
| 177 | spx_end: 0, |
| 178 | spxstrtf: 0, |
| 179 | spxbegf: 0, |
| 180 | spxbndstrc: [false; 18], |
| 181 | cplbndstrc: [false; 18], |
| 182 | nspxbnds: 0, |
| 183 | spxbndsz: [0; 18], |
| 184 | spxco: [[0.0; 18]; MAX_FBW], |
| 185 | nblend: [[0.0; 18]; MAX_FBW], |
| 186 | sblend: [[0.0; 18]; MAX_FBW], |
| 187 | first_spxco: [true; MAX_FBW], |
| 188 | chinspxatten: [false; MAX_FBW], |
| 189 | spxattencod: [0; MAX_FBW], |
| 190 | aht: [false; CHANNELS], |
| 191 | aht_read: [false; CHANNELS], |
| 192 | aht_mant: vec![0.0; CHANNELS * crate::aht::AHT_BLOCKS * COEFFS], |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | /// Drop everything a seek invalidates. |
| 197 | pub(crate) fn reset(&mut self) { |
| 198 | for d in self.delay.iter_mut() { |
| 199 | d.fill(0.0); |
| 200 | } |
| 201 | self.cplinu = false; |
| 202 | self.dynrng = [1.0; 2]; |
| 203 | *self.exps = [[0; COEFFS]; CHANNELS]; |
| 204 | } |
| 205 | |
| 206 | /// Adopt a frame header: channel configuration for the blocks that follow. |
| 207 | pub(crate) fn start_frame(&mut self, syntax: Syntax, fscod: usize, bsi: &Bsi) { |
| 208 | self.syntax = syntax; |
| 209 | self.fscod = fscod; |
| 210 | self.acmod = bsi.acmod; |
| 211 | self.nfchans = bsi.nfchans; |
| 212 | self.lfeon = bsi.lfeon; |
| 213 | self.strtmant = [0; CHANNELS]; |
| 214 | self.endmant[LFE] = 7; |
| 215 | self.aht_read = [false; CHANNELS]; |
| 216 | // §7.2.2.6: delta bit allocation starts each syncframe switched off. |
| 217 | self.deltba_on = [false; CHANNELS]; |
| 218 | self.deltba = [DeltaBa::default(); CHANNELS]; |
| 219 | } |
| 220 | |
| 221 | /// One `dynrng` word as the gain this decoder will actually apply, |
| 222 | /// scaled by [`Core::drc_scale`] (§7.7.1 "Partial Compression"). |
| 223 | pub(crate) fn gain(&self, dynrng: u8) -> f32 { |
| 224 | let gain = dynrng_gain(dynrng); |
| 225 | if self.drc_scale == 1.0 { |
| 226 | gain |
| 227 | } else { |
| 228 | gain.powf(self.drc_scale) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | /// Everything after the bit stream has been parsed: decouple, rematrix, |
| 233 | /// apply the dynamic range gain, transform, interleave. |
| 234 | pub(crate) fn finish_block(&mut self, out: &mut Vec<f32>) { |
| 235 | self.decouple(); |
| 236 | self.rematrix(); |
| 237 | self.apply_gain(); |
| 238 | self.transform(out); |
| 239 | } |
| 240 | |
| 241 | /// Coded channels the frame hands out, LFE included. |
| 242 | pub(crate) fn channels(&self) -> usize { |
| 243 | self.nfchans + usize::from(self.lfeon) |
| 244 | } |
| 245 | |
| 246 | /// Decode one `audblk()`, appending `BLOCK_SAMPLES` interleaved samples per |
| 247 | /// channel to `out` in the order [`Core::channel_order`] states. |
| 248 | pub(crate) fn block( |
| 249 | &mut self, |
| 250 | r: &mut BitReader<'_>, |
| 251 | blk: usize, |
| 252 | out: &mut Vec<f32>, |
| 253 | ) -> Result<()> { |
| 254 | self.parse_block(r, blk)?; |
| 255 | self.finish_block(out); |
| 256 | Ok(()) |
| 257 | } |
| 258 | |
| 259 | // ------------------------------------------------------------- parsing -- |
| 260 | |
| 261 | fn parse_block(&mut self, r: &mut BitReader<'_>, blk: usize) -> Result<()> { |
| 262 | let nfchans = self.nfchans; |
| 263 | for ch in 0..nfchans { |
| 264 | self.blksw[ch] = r.read_bit()?; |
| 265 | } |
| 266 | for ch in 0..nfchans { |
| 267 | self.dithflag[ch] = r.read_bit()?; |
| 268 | } |
| 269 | if r.read_bit()? { |
| 270 | self.dynrng[0] = self.gain(r.read_bits(8)? as u8); |
| 271 | } else if blk == 0 { |
| 272 | self.dynrng[0] = 1.0; |
| 273 | } |
| 274 | if self.acmod == Acmod::DualMono { |
| 275 | if r.read_bit()? { |
| 276 | self.dynrng[1] = self.gain(r.read_bits(8)? as u8); |
| 277 | } else if blk == 0 { |
| 278 | self.dynrng[1] = 1.0; |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | // Coupling strategy. |
| 283 | if r.read_bit()? { |
| 284 | self.cplinu = r.read_bit()?; |
| 285 | if self.cplinu { |
| 286 | for ch in 0..nfchans { |
| 287 | self.chincpl[ch] = r.read_bit()?; |
| 288 | } |
| 289 | if self.acmod == Acmod::Stereo { |
| 290 | self.phsflginu = r.read_bit()?; |
| 291 | } |
| 292 | self.cplbegf = r.read_bits(4)? as usize; |
| 293 | let cplendf = r.read_bits(4)? as usize; |
| 294 | if cplendf + 3 <= self.cplbegf { |
| 295 | return Err(Error::corrupt(format!( |
| 296 | "AC-3 coupling: cplbegf {} above cplendf {cplendf}", |
| 297 | self.cplbegf |
| 298 | ))); |
| 299 | } |
| 300 | self.ncplsubnd = 3 + cplendf - self.cplbegf; |
| 301 | self.strtmant[CPL] = 37 + 12 * self.cplbegf; |
| 302 | self.endmant[CPL] = 37 + 12 * (cplendf + 3); |
| 303 | // Sub-bands merge into coupling bands as cplbndstrc says. |
| 304 | self.cplband[0] = 0; |
| 305 | self.ncplbnd = 1; |
| 306 | for sbnd in 1..self.ncplsubnd { |
| 307 | if !r.read_bit()? { |
| 308 | self.ncplbnd += 1; |
| 309 | } |
| 310 | self.cplband[sbnd] = self.ncplbnd - 1; |
| 311 | } |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | // Coupling coordinates. |
| 316 | let mut cplcoe = [false; MAX_FBW]; |
| 317 | if self.cplinu { |
| 318 | for ch in 0..nfchans { |
| 319 | if !self.chincpl[ch] { |
| 320 | continue; |
| 321 | } |
| 322 | cplcoe[ch] = r.read_bit()?; |
| 323 | if !cplcoe[ch] { |
| 324 | continue; |
| 325 | } |
| 326 | let mstrcplco = r.read_bits(2)? as i32; |
| 327 | for bnd in 0..self.ncplbnd { |
| 328 | let cplcoexp = r.read_bits(4)? as i32; |
| 329 | let cplcomant = r.read_bits(4)? as i32; |
| 330 | self.cplco[ch][bnd] = coupling_coord(cplcoexp, cplcomant, mstrcplco); |
| 331 | } |
| 332 | } |
| 333 | if self.acmod == Acmod::Stereo && self.phsflginu && (cplcoe[0] || cplcoe[1]) { |
| 334 | for bnd in 0..self.ncplbnd { |
| 335 | self.phsflg[bnd] = r.read_bit()?; |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | // Rematrixing. |
| 341 | if self.acmod == Acmod::Stereo && r.read_bit()? { |
| 342 | self.nrematbnd = if !self.cplinu || self.cplbegf > 2 { |
| 343 | 4 |
| 344 | } else if self.cplbegf > 0 { |
| 345 | 3 |
| 346 | } else { |
| 347 | 2 |
| 348 | }; |
| 349 | for bnd in 0..self.nrematbnd { |
| 350 | self.rematflg[bnd] = r.read_bit()?; |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | // Exponent strategies and bandwidths. |
| 355 | self.expstr = [Strategy::Reuse; CHANNELS]; |
| 356 | if self.cplinu { |
| 357 | self.expstr[CPL] = Strategy::from_code(r.read_bits(2)?); |
| 358 | } |
| 359 | for ch in 0..nfchans { |
| 360 | self.expstr[ch] = Strategy::from_code(r.read_bits(2)?); |
| 361 | } |
| 362 | if self.lfeon { |
| 363 | self.expstr[LFE] = if r.read_bit()? { |
| 364 | Strategy::D15 |
| 365 | } else { |
| 366 | Strategy::Reuse |
| 367 | }; |
| 368 | } |
| 369 | for ch in 0..nfchans { |
| 370 | if self.expstr[ch] != Strategy::Reuse { |
| 371 | if self.chincpl[ch] && self.cplinu { |
| 372 | self.endmant[ch] = self.strtmant[CPL]; |
| 373 | } else { |
| 374 | let chbwcod = r.read_bits(6)? as usize; |
| 375 | if chbwcod > 60 { |
| 376 | return Err(Error::corrupt(format!( |
| 377 | "AC-3 audblk: chbwcod = {chbwcod} > 60" |
| 378 | ))); |
| 379 | } |
| 380 | self.endmant[ch] = (chbwcod + 12) * 3 + 37; |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | // Exponents. |
| 386 | if self.cplinu && self.expstr[CPL] != Strategy::Reuse { |
| 387 | let absexp = (r.read_bits(4)? << 1) as u8; |
| 388 | let (start, end) = (self.strtmant[CPL], self.endmant[CPL]); |
| 389 | let ngrps = self.expstr[CPL].coupling_groups(start, end); |
| 390 | exps::decode( |
| 391 | r, |
| 392 | self.expstr[CPL], |
| 393 | ngrps, |
| 394 | absexp, |
| 395 | start, |
| 396 | &mut self.exps[CPL], |
| 397 | )?; |
| 398 | } |
| 399 | for ch in 0..nfchans { |
| 400 | if self.expstr[ch] == Strategy::Reuse { |
| 401 | continue; |
| 402 | } |
| 403 | let absexp = r.read_bits(4)? as u8; |
| 404 | self.exps[ch][0] = absexp; |
| 405 | let ngrps = self.expstr[ch].fbw_groups(self.endmant[ch]); |
| 406 | exps::decode(r, self.expstr[ch], ngrps, absexp, 1, &mut self.exps[ch]).map_err( |
| 407 | |e| match e { |
| 408 | Error::Corrupt { context } => Error::corrupt(format!( |
| 409 | "{context} (block {blk}, channel {ch}, {:?}, endmant {})", |
| 410 | self.expstr[ch], self.endmant[ch] |
| 411 | )), |
| 412 | other => other, |
| 413 | }, |
| 414 | )?; |
| 415 | let _gainrng = r.read_bits(2)?; |
| 416 | } |
| 417 | if self.lfeon && self.expstr[LFE] != Strategy::Reuse { |
| 418 | let absexp = r.read_bits(4)? as u8; |
| 419 | self.exps[LFE][0] = absexp; |
| 420 | exps::decode(r, Strategy::D15, 2, absexp, 1, &mut self.exps[LFE])?; |
| 421 | } |
| 422 | |
| 423 | // Bit allocation parameters. |
| 424 | if r.read_bit()? { |
| 425 | self.ba = BitAllocParams { |
| 426 | sdcycod: r.read_bits(2)? as u8, |
| 427 | fdcycod: r.read_bits(2)? as u8, |
| 428 | sgaincod: r.read_bits(2)? as u8, |
| 429 | dbpbcod: r.read_bits(2)? as u8, |
| 430 | floorcod: r.read_bits(3)? as u8, |
| 431 | }; |
| 432 | } else if blk == 0 { |
| 433 | return Err(Error::corrupt( |
| 434 | "AC-3 audblk 0: bit allocation parameters absent, nothing to reuse", |
| 435 | )); |
| 436 | } |
| 437 | if r.read_bit()? { |
| 438 | self.csnroffst = r.read_bits(6)? as u8; |
| 439 | if self.cplinu { |
| 440 | self.fsnroffst[CPL] = r.read_bits(4)? as u8; |
| 441 | self.fgaincod[CPL] = r.read_bits(3)? as u8; |
| 442 | } |
| 443 | for ch in 0..nfchans { |
| 444 | self.fsnroffst[ch] = r.read_bits(4)? as u8; |
| 445 | self.fgaincod[ch] = r.read_bits(3)? as u8; |
| 446 | } |
| 447 | if self.lfeon { |
| 448 | self.fsnroffst[LFE] = r.read_bits(4)? as u8; |
| 449 | self.fgaincod[LFE] = r.read_bits(3)? as u8; |
| 450 | } |
| 451 | } else if blk == 0 { |
| 452 | return Err(Error::corrupt( |
| 453 | "AC-3 audblk 0: SNR offsets absent, nothing to reuse", |
| 454 | )); |
| 455 | } |
| 456 | if self.cplinu && r.read_bit()? { |
| 457 | // §7.2.2.1: fastleak = (cplfleak << 8) + 768, and the same for |
| 458 | // the slow leak — the offset is not optional. |
| 459 | self.cplleak = ( |
| 460 | ((r.read_bits(3)? as i32) << 8) + 768, |
| 461 | ((r.read_bits(3)? as i32) << 8) + 768, |
| 462 | ); |
| 463 | } |
| 464 | |
| 465 | // Delta bit allocation. |
| 466 | if r.read_bit()? { |
| 467 | let mut deltbae = [0u32; CHANNELS]; |
| 468 | if self.cplinu { |
| 469 | deltbae[CPL] = r.read_bits(2)?; |
| 470 | } |
| 471 | for ch in 0..nfchans { |
| 472 | deltbae[ch] = r.read_bits(2)?; |
| 473 | } |
| 474 | let mut order = Vec::with_capacity(CHANNELS); |
| 475 | if self.cplinu { |
| 476 | order.push(CPL); |
| 477 | } |
| 478 | order.extend(0..nfchans); |
| 479 | for ch in order { |
| 480 | match deltbae[ch] { |
| 481 | // Reuse: leave the previous segments in place. |
| 482 | 0 => {} |
| 483 | 1 => { |
| 484 | self.deltba_on[ch] = true; |
| 485 | let nseg = r.read_bits(3)? as usize + 1; |
| 486 | let mut dba = DeltaBa { |
| 487 | nseg, |
| 488 | ..DeltaBa::default() |
| 489 | }; |
| 490 | for seg in 0..nseg { |
| 491 | dba.offset[seg] = r.read_bits(5)? as u8; |
| 492 | dba.length[seg] = r.read_bits(4)? as u8; |
| 493 | dba.delta[seg] = r.read_bits(3)? as u8; |
| 494 | } |
| 495 | self.deltba[ch] = dba; |
| 496 | } |
| 497 | // Off, and reserved treated as off. |
| 498 | _ => self.deltba_on[ch] = false, |
| 499 | } |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | // Dummy data. |
| 504 | if r.read_bit()? { |
| 505 | let skipl = r.read_bits(9)? as u64; |
| 506 | r.skip_bits(skipl * 8)?; |
| 507 | } |
| 508 | |
| 509 | self.allocate(); |
| 510 | self.read_mantissas(r, blk) |
| 511 | } |
| 512 | |
| 513 | /// Run the bit allocation model for every channel of this block. |
| 514 | pub(crate) fn allocate(&mut self) { |
| 515 | // §7.2.2.1.1: an all-zero set of SNR offsets means no bits at all. |
| 516 | let all_zero = (0..self.nfchans).all(|ch| self.fsnroffst[ch] == 0) |
| 517 | && (!self.lfeon || self.fsnroffst[LFE] == 0) |
| 518 | && (!self.cplinu || self.fsnroffst[CPL] == 0); |
| 519 | if self.csnroffst == 0 && all_zero { |
| 520 | for ch in 0..CHANNELS { |
| 521 | self.bap[ch].fill(0); |
| 522 | } |
| 523 | return; |
| 524 | } |
| 525 | let mut channels: Vec<(usize, Channel)> = (0..self.nfchans) |
| 526 | .filter(|&ch| self.endmant[ch] > 0) |
| 527 | .map(|ch| (ch, Channel::Fbw)) |
| 528 | .collect(); |
| 529 | if self.cplinu { |
| 530 | channels.push((CPL, Channel::Coupling { leak: self.cplleak })); |
| 531 | } |
| 532 | if self.lfeon { |
| 533 | channels.push((LFE, Channel::Lfe)); |
| 534 | } |
| 535 | for (ch, kind) in channels { |
| 536 | let snroffset = |
| 537 | (((i32::from(self.csnroffst) - 15) << 4) + i32::from(self.fsnroffst[ch])) << 2; |
| 538 | let alloc = Allocation { |
| 539 | fscod: self.fscod, |
| 540 | params: self.ba, |
| 541 | range: (self.strtmant[ch], self.endmant[ch]), |
| 542 | fgaincod: self.fgaincod[ch], |
| 543 | snroffset, |
| 544 | kind, |
| 545 | dba: self.deltba_on[ch].then_some(&self.deltba[ch]), |
| 546 | high_efficiency: self.aht[ch], |
| 547 | }; |
| 548 | bitalloc::compute(&alloc, &self.exps[ch], &mut self.bap[ch]); |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | /// Unpack every mantissa of the block into [`Core::coeffs`]. |
| 553 | pub(crate) fn read_mantissas(&mut self, r: &mut BitReader<'_>, blk: usize) -> Result<()> { |
| 554 | // §7.3.5: the 3-, 5- and 11-level groups are shared *across* exponent |
| 555 | // sets — a partial group left by one channel is finished by the next. |
| 556 | // One reader per block, not per channel, is the whole of that rule. |
| 557 | let mut m = Mantissas::new(); |
| 558 | let mut got_cplchan = false; |
| 559 | for ch in 0..self.nfchans { |
| 560 | let end = self.endmant[ch]; |
| 561 | if self.aht[ch] { |
| 562 | self.aht_channel(r, ch, (0, end), blk)?; |
| 563 | } else { |
| 564 | for bin in 0..end { |
| 565 | let bap = self.bap[ch][bin]; |
| 566 | let value = m.read(r, bap)?; |
| 567 | let mant = if bap == 0 && self.dithflag[ch] && self.dither_on { |
| 568 | self.dither.mantissa() |
| 569 | } else { |
| 570 | value |
| 571 | }; |
| 572 | self.coeffs[ch][bin] = shift(mant, self.exps[ch][bin]); |
| 573 | } |
| 574 | } |
| 575 | self.coeffs[ch][end..].fill(0.0); |
| 576 | if self.cplinu && self.chincpl[ch] && !got_cplchan { |
| 577 | let (start, end) = (self.strtmant[CPL], self.endmant[CPL]); |
| 578 | if self.aht[CPL] { |
| 579 | self.aht_channel(r, CPL, (start, end), blk)?; |
| 580 | } else { |
| 581 | for bin in start..end { |
| 582 | let bap = self.bap[CPL][bin]; |
| 583 | let value = m.read(r, bap)?; |
| 584 | let mant = if bap == 0 && self.dither_on { |
| 585 | self.dither.mantissa() |
| 586 | } else { |
| 587 | value |
| 588 | }; |
| 589 | self.coeffs[CPL][bin] = shift(mant, self.exps[CPL][bin]); |
| 590 | } |
| 591 | } |
| 592 | got_cplchan = true; |
| 593 | } |
| 594 | } |
| 595 | if self.lfeon { |
| 596 | if self.aht[LFE] { |
| 597 | self.aht_channel(r, LFE, (0, 7), blk)?; |
| 598 | } else { |
| 599 | for bin in 0..7 { |
| 600 | let value = m.read(r, self.bap[LFE][bin])?; |
| 601 | self.coeffs[LFE][bin] = shift(value, self.exps[LFE][bin]); |
| 602 | } |
| 603 | } |
| 604 | self.coeffs[LFE][7..].fill(0.0); |
| 605 | } |
| 606 | Ok(()) |
| 607 | } |
| 608 | |
| 609 | /// One AHT channel: read the whole frame's mantissas on the first block |
| 610 | /// that asks for them, then hand this block its share (§E3.4). |
| 611 | fn aht_channel( |
| 612 | &mut self, |
| 613 | r: &mut BitReader<'_>, |
| 614 | ch: usize, |
| 615 | range: (usize, usize), |
| 616 | blk: usize, |
| 617 | ) -> Result<()> { |
| 618 | let base = ch * crate::aht::AHT_BLOCKS * COEFFS; |
| 619 | if !self.aht_read[ch] { |
| 620 | let frame = &mut self.aht_mant[base..base + crate::aht::AHT_BLOCKS * COEFFS]; |
| 621 | crate::aht::read_channel( |
| 622 | r, |
| 623 | &self.bap[ch], |
| 624 | range, |
| 625 | &mut self.dither, |
| 626 | self.dither_on, |
| 627 | frame, |
| 628 | )?; |
| 629 | self.aht_read[ch] = true; |
| 630 | } |
| 631 | let offset = base + blk * COEFFS; |
| 632 | for bin in range.0..range.1 { |
| 633 | self.coeffs[ch][bin] = self.aht_mant[offset + bin] * scale(self.exps[ch][bin]); |
| 634 | } |
| 635 | Ok(()) |
| 636 | } |
| 637 | |
| 638 | // ------------------------------------------------------------ decoding -- |
| 639 | |
| 640 | /// §7.4.3: rebuild each coupled channel's high bins from the coupling |
| 641 | /// channel, scaled by that channel's coupling coordinates. |
| 642 | pub(crate) fn decouple(&mut self) { |
| 643 | if !self.cplinu { |
| 644 | return; |
| 645 | } |
| 646 | let (start, end) = (self.strtmant[CPL], self.endmant[CPL]); |
| 647 | for ch in 0..self.nfchans { |
| 648 | if !self.chincpl[ch] { |
| 649 | continue; |
| 650 | } |
| 651 | for sbnd in 0..self.ncplsubnd { |
| 652 | let bnd = self.cplband[sbnd]; |
| 653 | let co = i64::from(self.cplco[ch][bnd]); |
| 654 | let invert = ch == 1 && self.phsflginu && self.phsflg[bnd]; |
| 655 | let from = start + sbnd * 12; |
| 656 | for bin in from..(from + 12).min(end) { |
| 657 | // §7.3.4: a coupled channel without dithflag gets silence where |
| 658 | // the coupling channel's mantissa was zero-bit. |
| 659 | let out = if self.bap[CPL][bin] == 0 && !self.dithflag[ch] { |
| 660 | 0 |
| 661 | } else { |
| 662 | let cpl = (self.coeffs[CPL][bin] * 8_388_608.0) as i64; |
| 663 | let v = ((cpl * co) >> 23) as i32; |
| 664 | if invert { -v } else { v } |
| 665 | }; |
| 666 | self.coeffs[ch][bin] = out as f32 / 8_388_608.0; |
| 667 | } |
| 668 | } |
| 669 | self.coeffs[ch][end..].fill(0.0); |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | /// §7.5.4: undo the sum/difference coding of the 2/0 mode. |
| 674 | pub(crate) fn rematrix(&mut self) { |
| 675 | if self.acmod != Acmod::Stereo || self.nrematbnd == 0 { |
| 676 | return; |
| 677 | } |
| 678 | const BANDS: [usize; 4] = [13, 25, 37, 61]; |
| 679 | let limit = if self.cplinu { |
| 680 | self.strtmant[CPL] |
| 681 | } else { |
| 682 | self.endmant[0].min(self.endmant[1]) |
| 683 | }; |
| 684 | for bnd in 0..self.nrematbnd { |
| 685 | if !self.rematflg[bnd] { |
| 686 | continue; |
| 687 | } |
| 688 | let start = BANDS[bnd]; |
| 689 | let end = if bnd + 1 < BANDS.len() { |
| 690 | BANDS[bnd + 1].min(limit) |
| 691 | } else { |
| 692 | limit |
| 693 | }; |
| 694 | for bin in start..end { |
| 695 | let (l, r) = (self.coeffs[0][bin], self.coeffs[1][bin]); |
| 696 | self.coeffs[0][bin] = l + r; |
| 697 | self.coeffs[1][bin] = l - r; |
| 698 | } |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | /// §7.7.1: the dynamic range gain the encoder asked for. |
| 703 | pub(crate) fn apply_gain(&mut self) { |
| 704 | let mut channels: Vec<usize> = (0..self.nfchans).collect(); |
| 705 | if self.lfeon { |
| 706 | channels.push(LFE); |
| 707 | } |
| 708 | for ch in channels { |
| 709 | // In 1+1 mode the two coded channels are separate programs with |
| 710 | // separate gain words; everywhere else one word covers the frame. |
| 711 | let program = usize::from(self.acmod == Acmod::DualMono && ch == 1); |
| 712 | let gain = self.dynrng[program]; |
| 713 | if gain != 1.0 { |
| 714 | for v in &mut self.coeffs[ch] { |
| 715 | *v *= gain; |
| 716 | } |
| 717 | } |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | /// Inverse transform every channel and interleave the result. |
| 722 | pub(crate) fn transform(&mut self, out: &mut Vec<f32>) { |
| 723 | let channels = self.channels(); |
| 724 | let base = out.len(); |
| 725 | out.resize(base + channels * BLOCK_SAMPLES, 0.0); |
| 726 | let mut pcm = [0.0f32; BLOCK_SAMPLES]; |
| 727 | for (slot, ch) in self.channel_order().into_iter().enumerate() { |
| 728 | let short = ch < MAX_FBW && self.blksw[ch]; |
| 729 | let store = if ch == LFE { MAX_FBW } else { ch }; |
| 730 | self.imdct |
| 731 | .block(&self.coeffs[ch], short, &mut self.delay[store], &mut pcm); |
| 732 | for (n, &v) in pcm.iter().enumerate() { |
| 733 | out[base + n * channels + slot] = v; |
| 734 | } |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | /// The order this frame's channels are handed out in: the family's own |
| 739 | /// L, R, C, LFE, Ls, Rs convention, as indices into the coded channels. |
| 740 | pub(crate) fn channel_order(&self) -> Vec<usize> { |
| 741 | let mut order: Vec<usize> = match self.acmod { |
| 742 | // 1+1 and 2/0 are already in order, as is any mode without a |
| 743 | // centre channel; the coded order only differs where C sits. |
| 744 | Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => { |
| 745 | let mut v = vec![0, 2, 1]; |
| 746 | v.extend(3..self.nfchans); |
| 747 | v |
| 748 | } |
| 749 | _ => (0..self.nfchans).collect(), |
| 750 | }; |
| 751 | if self.lfeon { |
| 752 | // The LFE follows the front channels, which is where every layout |
| 753 | // in the family (and in WAVE) puts it. |
| 754 | let fronts = match self.acmod { |
| 755 | Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => 3, |
| 756 | Acmod::Mono => 1, |
| 757 | _ => 2, |
| 758 | }; |
| 759 | order.insert(fronts.min(order.len()), LFE); |
| 760 | } |
| 761 | order |
| 762 | } |
| 763 | } |
| 764 | |
| 765 | pub(crate) fn coupling_coord(exp: i32, mant: i32, master: i32) -> i32 { |
| 766 | let base = if exp == 15 { mant << 22 } else { (mant + 16) << 21 }; |
| 767 | base >> (exp + 3 * master).min(24) |
| 768 | } |
| 769 | |
| 770 | /// §7.7.1.2: the 8-bit `dynrng` word as a linear gain. |
| 771 | /// |
| 772 | /// The three most significant bits are a signed power of two from -4 to 3 with |
| 773 | /// an implicit +1, and the five least significant bits a fraction in `[1/2, 1)`. |
| 774 | /// The all-zero word is unity, which is what a block with no `dynrng` means. |
| 775 | fn dynrng_gain(dynrng: u8) -> f32 { |
| 776 | let exponent = ((dynrng as i8) >> 5) as i32 + 1; |
| 777 | let mantissa = f32::from(32 + (dynrng & 0x1f)) / 64.0; |
| 778 | mantissa * (exponent as f32).exp2() |
| 779 | } |
| 780 | |
| 781 | #[cfg(test)] |
| 782 | mod tests { |
| 783 | use super::*; |
| 784 | |
| 785 | #[test] |
| 786 | fn dynrng_zero_is_unity_and_the_ends_are_plus_minus_24_db() { |
| 787 | assert!((dynrng_gain(0x00) - 1.0).abs() < 1e-6); |
| 788 | // X = 3 (+24.08 dB), Y = 11111 (63/64) => 2^4 * 63/64 = 15.75. |
| 789 | assert!((dynrng_gain(0b011_11111) - 15.75).abs() < 1e-4); |
| 790 | // X = -4 (-18.06 dB), Y = 00000 (1/2) => 2^-3 * 1/2 = 0.0625. |
| 791 | assert!((dynrng_gain(0b100_00000) - 0.0625).abs() < 1e-6); |
| 792 | // X = -1 is the table's "0 dB", but Y always contributes between |
| 793 | // -0.14 and -6.02 dB: 2^0 * 1/2. |
| 794 | assert!((dynrng_gain(0b111_00000) - 0.5).abs() < 1e-6); |
| 795 | } |
| 796 | |
| 797 | #[test] |
| 798 | fn channel_order_puts_centre_second_and_lfe_after_the_fronts() { |
| 799 | let mut core = Core::new(); |
| 800 | core.acmod = Acmod::Surround3_2; |
| 801 | core.nfchans = 5; |
| 802 | core.lfeon = true; |
| 803 | assert_eq!(core.channel_order(), vec![0, 2, 1, LFE, 3, 4]); |
| 804 | core.lfeon = false; |
| 805 | assert_eq!(core.channel_order(), vec![0, 2, 1, 3, 4]); |
| 806 | core.acmod = Acmod::Stereo; |
| 807 | core.nfchans = 2; |
| 808 | assert_eq!(core.channel_order(), vec![0, 1]); |
| 809 | core.acmod = Acmod::Mono; |
| 810 | core.nfchans = 1; |
| 811 | core.lfeon = true; |
| 812 | assert_eq!(core.channel_order(), vec![0, LFE]); |
| 813 | } |
| 814 | } |