diff --git a/crates/ec-ac3/src/aht.rs b/crates/ec-ac3/src/aht.rs index 325e951a..6d11f16c 100644 --- a/crates/ec-ac3/src/aht.rs +++ b/crates/ec-ac3/src/aht.rs @@ -107,10 +107,10 @@ pub(crate) fn read_channel( let mut next_gain = 0usize; for bin in start..end { let h = hebap[bin]; - let mut zero_bits = false; if h == 0 { - pre = [0.0; AHT_BLOCKS]; - zero_bits = true; + for slot in &mut pre { + *slot = if dither_on { dither.value() } else { 0.0 }; + } } else if h <= 7 { let index = r.read_bits(VQ_BITS[h as usize])? as usize; let table = vq_table(h); @@ -131,13 +131,6 @@ pub(crate) fn read_channel( } } - if zero_bits { - // A zero-bit AHT bin is the same silence AC-3 fills with dither. - for blk in 0..AHT_BLOCKS { - out[blk * COEFFS + bin] = if dither_on { dither.value() } else { 0.0 }; - } - continue; - } // §3.4.5: invert the six-point DCT across blocks. for (blk, slot) in idct6(&pre).into_iter().enumerate() { out[blk * COEFFS + bin] = slot; diff --git a/crates/ec-ac3/src/decode.rs b/crates/ec-ac3/src/decode.rs index e0b09bca..1a2de760 100644 --- a/crates/ec-ac3/src/decode.rs +++ b/crates/ec-ac3/src/decode.rs @@ -12,7 +12,7 @@ use ec_core::{BitReader, Error, Result}; use crate::bitalloc::{self, Allocation, BitAllocParams, Channel, DeltaBa}; use crate::bsi::{Acmod, Bsi}; use crate::exps::{self, Strategy}; -use crate::mantissa::{Dither, Mantissas, scale}; +use crate::mantissa::{Dither, Mantissas, scale, shift}; use crate::transform::{BLOCK_SAMPLES, Imdct}; /// Full-bandwidth channels at most (3/2 mode). @@ -64,7 +64,7 @@ pub(crate) struct Core { pub(crate) ncplbnd: usize, /// Coupling band each sub-band belongs to, after `cplbndstrc` merging. pub(crate) cplband: [usize; 18], - pub(crate) cplco: [[f32; 18]; MAX_FBW], + pub(crate) cplco: [[i32; 18]; MAX_FBW], pub(crate) phsflg: [bool; 18], pub(crate) cplleak: (i32, i32), /// Annex E sends a channel's coupling coordinates in the first block of @@ -118,9 +118,6 @@ pub(crate) struct Core { pub(crate) first_spxco: [bool; MAX_FBW], pub(crate) chinspxatten: [bool; MAX_FBW], pub(crate) spxattencod: [u8; MAX_FBW], - /// The noise source of §3.6.4.2.4, kept apart from the dither source so - /// neither one's sequence depends on the other's use. - pub(crate) spx_noise: Dither, // Adaptive hybrid transform (Annex E §3.4). All false under AC-3. /// Which channels are AHT-coded this frame. pub(crate) aht: [bool; CHANNELS], @@ -152,7 +149,7 @@ impl Core { ncplsubnd: 0, ncplbnd: 0, cplband: [0; 18], - cplco: [[0.0; 18]; MAX_FBW], + cplco: [[0; 18]; MAX_FBW], phsflg: [false; 18], cplleak: (0, 0), first_cplco: [true; MAX_FBW], @@ -190,7 +187,6 @@ impl Core { first_spxco: [true; MAX_FBW], chinspxatten: [false; MAX_FBW], spxattencod: [0; MAX_FBW], - spx_noise: Dither::default(), aht: [false; CHANNELS], aht_read: [false; CHANNELS], aht_mant: vec![0.0; CHANNELS * crate::aht::AHT_BLOCKS * COEFFS], @@ -330,13 +326,8 @@ impl Core { let mstrcplco = r.read_bits(2)? as i32; for bnd in 0..self.ncplbnd { let cplcoexp = r.read_bits(4)? as i32; - let cplcomant = r.read_bits(4)? as f32; - let mant = if cplcoexp == 15 { - cplcomant / 16.0 - } else { - (cplcomant + 16.0) / 32.0 - }; - self.cplco[ch][bnd] = mant * scale((cplcoexp + 3 * mstrcplco).min(24) as u8); + let cplcomant = r.read_bits(4)? as i32; + self.cplco[ch][bnd] = coupling_coord(cplcoexp, cplcomant, mstrcplco); } } if self.acmod == Acmod::Stereo && self.phsflginu && (cplcoe[0] || cplcoe[1]) { @@ -573,11 +564,12 @@ impl Core { for bin in 0..end { let bap = self.bap[ch][bin]; let value = m.read(r, bap)?; - self.coeffs[ch][bin] = if bap == 0 && self.dithflag[ch] && self.dither_on { - self.dither.value() * scale(self.exps[ch][bin]) + let mant = if bap == 0 && self.dithflag[ch] && self.dither_on { + self.dither.mantissa() } else { - value * scale(self.exps[ch][bin]) + value }; + self.coeffs[ch][bin] = shift(mant, self.exps[ch][bin]); } } self.coeffs[ch][end..].fill(0.0); @@ -589,14 +581,12 @@ impl Core { for bin in start..end { let bap = self.bap[CPL][bin]; let value = m.read(r, bap)?; - // The coupling channel always draws dither for its zero-bit - // mantissas, whatever the coupled channels' dithflag says: - // each coupled channel decides later whether to keep it. - self.coeffs[CPL][bin] = if bap == 0 && self.dither_on { - self.dither.value() * scale(self.exps[CPL][bin]) + let mant = if bap == 0 && self.dither_on { + self.dither.mantissa() } else { - value * scale(self.exps[CPL][bin]) + value }; + self.coeffs[CPL][bin] = shift(mant, self.exps[CPL][bin]); } } got_cplchan = true; @@ -608,7 +598,7 @@ impl Core { } else { for bin in 0..7 { let value = m.read(r, self.bap[LFE][bin])?; - self.coeffs[LFE][bin] = value * scale(self.exps[LFE][bin]); + self.coeffs[LFE][bin] = shift(value, self.exps[LFE][bin]); } } self.coeffs[LFE][7..].fill(0.0); @@ -660,22 +650,20 @@ impl Core { } for sbnd in 0..self.ncplsubnd { let bnd = self.cplband[sbnd]; - let mut co = self.cplco[ch][bnd] * 8.0; - // §5.4.3.18: in 2/0 with phase flags, the right channel's - // contribution is inverted for the flagged bands. - if ch == 1 && self.phsflginu && self.phsflg[bnd] { - co = -co; - } + let co = i64::from(self.cplco[ch][bnd]); + let invert = ch == 1 && self.phsflginu && self.phsflg[bnd]; let from = start + sbnd * 12; for bin in from..(from + 12).min(end) { // §7.3.4: a coupled channel without dithflag gets silence where // the coupling channel's mantissa was zero-bit. - let cpl = if self.bap[CPL][bin] == 0 && !self.dithflag[ch] { - 0.0 + let out = if self.bap[CPL][bin] == 0 && !self.dithflag[ch] { + 0 } else { - self.coeffs[CPL][bin] + let cpl = (self.coeffs[CPL][bin] * 8_388_608.0) as i64; + let v = ((cpl * co) >> 23) as i32; + if invert { -v } else { v } }; - self.coeffs[ch][bin] = cpl * co; + self.coeffs[ch][bin] = out as f32 / 8_388_608.0; } } self.coeffs[ch][end..].fill(0.0); @@ -774,6 +762,11 @@ impl Core { } } +pub(crate) fn coupling_coord(exp: i32, mant: i32, master: i32) -> i32 { + let base = if exp == 15 { mant << 22 } else { (mant + 16) << 21 }; + base >> (exp + 3 * master).min(24) +} + /// §7.7.1.2: the 8-bit `dynrng` word as a linear gain. /// /// The three most significant bits are a signed power of two from -4 to 3 with diff --git a/crates/ec-ac3/src/decoder.rs b/crates/ec-ac3/src/decoder.rs index 912c293e..939912e2 100644 --- a/crates/ec-ac3/src/decoder.rs +++ b/crates/ec-ac3/src/decoder.rs @@ -342,7 +342,7 @@ impl Ac3Decoder { ))); } let channels = hdr.nfchans + usize::from(hdr.bsi.lfeon); - let positions = dependent::positions(hdr.chanmap, channels)?; + let positions = dependent::positions(hdr.chanmap, channels, hdr.bsi.acmod, hdr.bsi.lfeon)?; if self.dependents.len() <= slot { self.dependents.push(Core::new()); } diff --git a/crates/ec-ac3/src/dependent.rs b/crates/ec-ac3/src/dependent.rs index 5a503f0a..3078a53a 100644 --- a/crates/ec-ac3/src/dependent.rs +++ b/crates/ec-ac3/src/dependent.rs @@ -28,6 +28,7 @@ use ec_core::{BitReader, ChannelPosition, Error, Result}; +use crate::bsi::Acmod; use crate::eac3::{self, Eac3Bsi, StreamType}; use crate::syncinfo::SYNCWORD; @@ -54,7 +55,7 @@ pub(crate) fn peek(data: &[u8]) -> Option { /// The loudspeaker positions a dependent substream's `channels` coded channels /// fill, in coded order, from its custom channel map (Table E2.5). -pub(crate) fn positions(map: Option, channels: usize) -> Result> { +pub(crate) fn positions(map: Option, channels: usize, acmod: Acmod, lfeon: bool) -> Result> { use ChannelPosition::*; let Some(map) = map else { return Err(Error::unsupported( @@ -99,7 +100,31 @@ pub(crate) fn positions(map: Option, channels: usize) -> Result &'static [u8] { + match (acmod, lfeon) { + (Acmod::DualMono | Acmod::Stereo, false) => &[0, 1], + (Acmod::DualMono | Acmod::Stereo, true) => &[0, 1, 2], + (Acmod::Mono, false) => &[0], + (Acmod::Mono, true) => &[0, 1], + (Acmod::Surround3_0, false) => &[0, 2, 1], + (Acmod::Surround3_0, true) => &[0, 2, 1, 3], + (Acmod::Surround2_1, false) => &[0, 1, 2], + (Acmod::Surround2_1, true) => &[0, 1, 3, 2], + (Acmod::Surround3_1, false) => &[0, 2, 1, 3], + (Acmod::Surround3_1, true) => &[0, 2, 1, 4, 3], + (Acmod::Surround2_2, false) => &[0, 1, 2, 3], + (Acmod::Surround2_2, true) => &[0, 1, 4, 2, 3], + (Acmod::Surround3_2, false) => &[0, 2, 1, 3, 4], + (Acmod::Surround3_2, true) => &[0, 2, 1, 5, 3, 4], + } } /// The Table E2.5 name of the map entry `i` that this build cannot place. @@ -188,26 +213,26 @@ mod tests { #[test] fn map_bits_name_positions_as_ffmpeg_does() { - assert_eq!(positions(Some(0x8000), 1).unwrap(), vec![FrontLeft]); - assert_eq!(positions(Some(0x0400), 2).unwrap(), vec![FrontLeftOfCenter, FrontRightOfCenter]); - assert_eq!(positions(Some(0x0200), 2).unwrap(), vec![BackLeft, BackRight]); - assert_eq!(positions(Some(0x1800), 2).unwrap(), vec![SideLeft, SideRight]); - assert_eq!(positions(Some(0x0001), 1).unwrap(), vec![Lfe]); - assert_eq!(positions(Some(0x8400), 3).unwrap(), vec![FrontLeft, FrontLeftOfCenter, FrontRightOfCenter]); + assert_eq!(positions(Some(0x8000), 1, Acmod::Mono, false).unwrap(), vec![FrontLeft]); + assert_eq!(positions(Some(0x0400), 2, Acmod::Stereo, false).unwrap(), vec![FrontLeftOfCenter, FrontRightOfCenter]); + assert_eq!(positions(Some(0x0200), 2, Acmod::Stereo, false).unwrap(), vec![BackLeft, BackRight]); + assert_eq!(positions(Some(0x1800), 2, Acmod::Stereo, false).unwrap(), vec![SideLeft, SideRight]); + assert_eq!(positions(Some(0x0001), 1, Acmod::Mono, false).unwrap(), vec![Lfe]); + assert_eq!(positions(Some(0x8400), 3, Acmod::Surround2_1, false).unwrap(), vec![FrontLeft, FrontLeftOfCenter, FrontRightOfCenter]); } #[test] fn unnamed_and_missing_maps_are_refused_by_name() { for map in [None, Some(0x0080), Some(0x0040), Some(0x0010), Some(0x0004), Some(0x0002)] { - let err = positions(map, 2).expect_err("refused"); + let err = positions(map, 2, Acmod::Stereo, false).expect_err("refused"); assert!(matches!(err, Error::Unsupported { .. }), "{map:?}: {err}"); } } #[test] fn map_that_disagrees_with_the_channel_count_is_corrupt() { - assert!(matches!(positions(Some(0x1800), 1), Err(Error::Corrupt { .. }))); - assert!(matches!(positions(Some(0x0400), 3), Err(Error::Corrupt { .. }))); + assert!(matches!(positions(Some(0x1800), 1, Acmod::Mono, false), Err(Error::Corrupt { .. }))); + assert!(matches!(positions(Some(0x0400), 3, Acmod::Surround2_1, false), Err(Error::Corrupt { .. }))); } #[test] diff --git a/crates/ec-ac3/src/eac3.rs b/crates/ec-ac3/src/eac3.rs index bfa75c66..d66712ed 100644 --- a/crates/ec-ac3/src/eac3.rs +++ b/crates/ec-ac3/src/eac3.rs @@ -781,7 +781,7 @@ fn parse_block( // §3.6.4.2.1: the blend follows the band's frequency midpoint. let bandsize = core.spxbndsz[bnd] as f32; let nratio = ((spxmant + 0.5 * bandsize) / end - spxblnd).clamp(0.0, 1.0); - core.nblend[ch][bnd] = nratio.sqrt(); + core.nblend[ch][bnd] = (3.0 * nratio).sqrt(); core.sblend[ch][bnd] = (1.0 - nratio).sqrt(); spxmant += bandsize; } @@ -885,14 +885,9 @@ fn parse_block( let mstrcplco = r.read_bits(2)? as i32; for bnd in 0..core.ncplbnd { let cplcoexp = r.read_bits(4)? as i32; - let cplcomant = r.read_bits(4)? as f32; - let mant = if cplcoexp == 15 { - cplcomant / 16.0 - } else { - (cplcomant + 16.0) / 32.0 - }; + let cplcomant = r.read_bits(4)? as i32; core.cplco[ch][bnd] = - mant * crate::mantissa::scale((cplcoexp + 3 * mstrcplco).min(24) as u8); + crate::decode::coupling_coord(cplcoexp, cplcomant, mstrcplco); } } } @@ -1196,11 +1191,8 @@ fn spectral_extension(core: &mut Core, ch: usize) { if spxmant >= COEFFS { break; } - // §E3.6.4.2.4's noise(): a zero-mean unit-variance source the - // standard leaves to the implementation, so it is switched by the - // same option as §7.3.4's dither. let noise = if core.dither_on { - core.spx_noise.unit_variance() + (core.dither.next_word() as i32) as f32 / -2_147_483_648.0 } else { 0.0 }; diff --git a/crates/ec-ac3/src/mantissa.rs b/crates/ec-ac3/src/mantissa.rs index 97d2e558..811945e6 100644 --- a/crates/ec-ac3/src/mantissa.rs +++ b/crates/ec-ac3/src/mantissa.rs @@ -50,27 +50,20 @@ impl Default for Dither { } impl Dither { - /// Next dither value, uniform in ±0.707 (ffmpeg's mantissa scaled by 2^-23). - pub fn value(&mut self) -> f32 { - self.mantissa() as f32 / 8_388_608.0 - } - - /// Next value from a zero-mean, unit-variance source — what Annex E - /// §3.6.4.2.4 calls `noise()`. A uniform distribution on `[-1, 1]` has - /// variance 1/3, so it is scaled by `sqrt(3)`. - pub fn unit_variance(&mut self) -> f32 { - self.mantissa() as f32 / 5_931_008.0 * 1.732_050_8 + pub(crate) fn value(&mut self) -> f32 { + let x = self.next_word() & 0x7f_ffff; + (x as i32 - 0x40_0000) as f32 / 8_388_608.0 } /// ffmpeg's integer dither mantissa: `((x >> 8) * 181 >> 8) - 5931008`. - fn mantissa(&mut self) -> i32 { + pub fn mantissa(&mut self) -> i32 { let x = self.next_word(); let u = ((x >> 8) * 181) >> 8; u as i32 - 5_931_008 } /// `av_lfg_get`: `state[i] = state[i-24] + state[i-55]`, returning the new word. - fn next_word(&mut self) -> u32 { + pub fn next_word(&mut self) -> u32 { let i = self.index & 63; let v = self.state[(i + 40) & 63].wrapping_add(self.state[(i + 9) & 63]); self.state[i] = v; @@ -87,11 +80,11 @@ impl Dither { /// the next channel begins. #[derive(Debug, Clone, Copy, Default)] pub struct Mantissas { - group3: [f32; 3], + group3: [i32; 3], left3: usize, - group5: [f32; 3], + group5: [i32; 3], left5: usize, - group11: [f32; 2], + group11: [i32; 2], left11: usize, } @@ -106,9 +99,9 @@ impl Mantissas { /// `bap == 0` returns 0.0; the caller decides whether that bin gets dither, /// because in the coupled range the decision belongs to the channel rather /// than to the coupling channel the mantissa came from. - pub fn read(&mut self, r: &mut BitReader<'_>, bap: u8) -> Result { + pub fn read(&mut self, r: &mut BitReader<'_>, bap: u8) -> Result { Ok(match bap { - 0 => 0.0, + 0 => 0, 1 => { if self.left3 == 0 { let code = r.read_bits(5)?.min(26); @@ -159,13 +152,16 @@ impl Mantissas { // 6..=15: asymmetric two's complement, decimal point left of // the MSB (§7.3.2). let bits = QNTZTAB[(bap as usize).min(15)]; - let value = r.read_signed(bits)?; - value as f32 / (1u32 << (bits - 1)) as f32 + r.read_signed(bits)? << (24 - bits) } }) } } +pub(crate) fn shift(mantissa: i32, exponent: u8) -> f32 { + (mantissa >> exponent) as f32 / 8_388_608.0 +} + /// `2^-exponent`, the right shift §7.3 applies to every mantissa. pub fn scale(exponent: u8) -> f32 { // Exponents are 0..=24, so a table lookup would buy nothing over the @@ -188,14 +184,10 @@ mod tests { let bytes = w.into_bytes(); let mut r = BitReader::new(&bytes); let mut m = Mantissas::new(); - let got: Vec = (0..3).map(|_| m.read(&mut r, 1).unwrap()).collect(); - assert!((got[0] - 2.0 / 3.0).abs() < 1e-6); - assert!(got[1].abs() < 1e-6); - assert!((got[2] + 2.0 / 3.0).abs() < 1e-6); - let a = m.read(&mut r, 4).unwrap(); - let b = m.read(&mut r, 4).unwrap(); - assert!((a - 10.0 / 11.0).abs() < 1e-6); - assert!((b + 10.0 / 11.0).abs() < 1e-6); + let got: Vec = (0..3).map(|_| m.read(&mut r, 1).unwrap()).collect(); + assert_eq!(got, [5_592_405, 0, -5_592_405]); + assert_eq!(m.read(&mut r, 4).unwrap(), 7_626_007); + assert_eq!(m.read(&mut r, 4).unwrap(), -7_626_007); } #[test] @@ -206,9 +198,9 @@ mod tests { let bytes = w.into_bytes(); let mut r = BitReader::new(&bytes); let mut m = Mantissas::new(); - assert!((m.read(&mut r, 7).unwrap() + 1.0).abs() < 1e-6); - assert!((m.read(&mut r, 7).unwrap() - 31.0 / 32.0).abs() < 1e-6); - assert_eq!(m.read(&mut r, 0).unwrap(), 0.0); + assert_eq!(m.read(&mut r, 7).unwrap(), -(1 << 23)); + assert_eq!(m.read(&mut r, 7).unwrap(), 31 << 18); + assert_eq!(m.read(&mut r, 0).unwrap(), 0); } #[test] diff --git a/crates/ec-ac3/src/tables.rs b/crates/ec-ac3/src/tables.rs index 9e88a860..2ddd7abe 100644 --- a/crates/ec-ac3/src/tables.rs +++ b/crates/ec-ac3/src/tables.rs @@ -155,8 +155,9 @@ pub const QUANT_LEVELS: [u32; 6] = [0, 3, 5, 7, 11, 15]; /// The `k`-th reconstruction level of a `levels`-level symmetric quantizer /// (Tables 7.19-7.23): the uniform midtread set `(2k - (levels-1)) / levels`. -pub fn symmetric_level(levels: u32, k: u32) -> f32 { - (2.0 * k as f32 - (levels as f32 - 1.0)) / levels as f32 +pub fn symmetric_level(levels: u32, k: u32) -> i32 { + let levels = levels as i32; + (2 * k as i32 - (levels - 1)) * (1 << 23) / levels } /// Transform window `w[]`: 256 values used back to back to form the 512-point @@ -216,12 +217,12 @@ mod tests { #[test] fn symmetric_quantizer_matches_printed_tables() { // Tables 7.19-7.23, as printed. - assert!((symmetric_level(3, 0) + 2.0 / 3.0).abs() < 1e-6); - assert!(symmetric_level(3, 1).abs() < 1e-6); - assert!((symmetric_level(5, 3) - 2.0 / 5.0).abs() < 1e-6); - assert!((symmetric_level(7, 6) - 6.0 / 7.0).abs() < 1e-6); - assert!((symmetric_level(11, 0) + 10.0 / 11.0).abs() < 1e-6); - assert!((symmetric_level(15, 14) - 14.0 / 15.0).abs() < 1e-6); + assert_eq!(symmetric_level(3, 0), -5_592_405); + assert_eq!(symmetric_level(3, 1), 0); + assert_eq!(symmetric_level(5, 3), 3_355_443); + assert_eq!(symmetric_level(7, 6), 7_190_235); + assert_eq!(symmetric_level(11, 0), -7_626_007); + assert_eq!(symmetric_level(15, 14), 7_829_367); } #[test] diff --git a/crates/ec-ac3/tests/it/real_library.rs b/crates/ec-ac3/tests/it/real_library.rs index 8bd97ced..3ea1c872 100644 --- a/crates/ec-ac3/tests/it/real_library.rs +++ b/crates/ec-ac3/tests/it/real_library.rs @@ -43,6 +43,17 @@ fn decode(path: &Path) -> (Vec, usize) { if pos + size > data.len() { break; } + let mut end = pos + size; + while end + 6 <= data.len() && data[end] == 0x0B && data[end + 1] == 0x77 && data[end + 5] >> 3 > 10 && data[end + 2] >> 6 == 1 { + let Ok(more) = ec_ac3::frame_size(&data[end..]) else { + break; + }; + if end + more > data.len() { + break; + } + end += more; + } + let size = end - pos; let frame = decoder .decode_frame(&data[pos..pos + size]) .unwrap_or_else(|e| panic!("{}: {e}", path.display()));