diff --git a/kodecs-opus/src/safe/celt/bands.rs b/kodecs-opus/src/safe/celt/bands.rs index 030a7d71..c12bbd1a 100644 --- a/kodecs-opus/src/safe/celt/bands.rs +++ b/kodecs-opus/src/safe/celt/bands.rs @@ -1,16 +1,18 @@ -//! Decoding the normalized spectrum band by band, and restoring its energy, from libopus's -//! celt/bands.c. +//! Coding the normalized spectrum band by band, and measuring and restoring its energy, from +//! libopus's celt/bands.c. //! Copyright (c) 2007-2008 CSIRO, 2007-2009 Xiph.Org Foundation, and 2008-2009 Gregory //! Maxwell. use std::f32::consts::{FRAC_1_SQRT_2, SQRT_2}; +use super::coder::{Coder, Snapshot}; use super::energy::E_MEANS; use super::math; +use super::pitch::inner_prod; use super::rate::{self, Allocation}; use super::tables::{EBANDS, LOG_N}; use super::vq; -use super::{BANDS, SHORT_MDCT_SIZE, SPREAD_AGGRESSIVE}; +use super::{BANDS, SHORT_MDCT_SIZE, SPREAD_AGGRESSIVE, SPREAD_LIGHT, SPREAD_NONE, SPREAD_NORMAL}; use crate::safe::range::{self, BIT_RESOLUTION}; const BITRES: i32 = BIT_RESOLUTION as i32; @@ -20,12 +22,54 @@ const QTHETA_OFFSET_TWOPHASE: i32 = 16; const MAX_BAND: usize = 22 << super::MAX_LM; /// Folding memory per channel: every band but the last, at 20 ms. const MAX_NORM: usize = (EBANDS[BANDS - 1] as usize) << super::MAX_LM; +/// Below this band energy, a stereo band codes as the louder channel alone. +const MIN_STEREO_ENERGY: f32 = 1e-10; /// The bin where band `band` starts, at `m` blocks per frame. fn band_start(band: usize, m: usize) -> usize { m * EBANDS[band] as usize } +/// Each band's amplitude (the square root of its energy) in the `channels` spectra of `freq`, +/// for bands below `end`. +pub(super) fn compute_band_energies( + freq: &[f32], + band_e: &mut [f32; 2 * BANDS], + end: usize, + channels: usize, + lm: usize, +) { + let n = SHORT_MDCT_SIZE << lm; + for c in 0..channels { + for i in 0..end { + let bins = &freq[c * n + band_start(i, 1 << lm)..c * n + band_start(i + 1, 1 << lm)]; + let sum = 1e-27 + inner_prod(bins, bins); + band_e[i + c * BANDS] = math::sqrt(sum); + } + } +} + +/// Scale each band of `freq` below `end` to unit energy, into `x`. +pub(super) fn normalise_bands( + freq: &[f32], + x: &mut [f32], + band_e: &[f32; 2 * BANDS], + end: usize, + channels: usize, + m: usize, +) { + let n = m * SHORT_MDCT_SIZE; + for c in 0..channels { + for i in 0..end { + let g = 1.0 / (1e-27 + band_e[i + c * BANDS]); + let bins = c * n + band_start(i, m)..c * n + band_start(i + 1, m); + for (x, &f) in x[bins.clone()].iter_mut().zip(&freq[bins]) { + *x = f * g; + } + } + } +} + /// Restore each band of the normalized spectrum `x` to the energy `log_e` codes, into /// `freq`, zeroing bins past the band limit and the downsampled bandwidth. #[allow( @@ -65,6 +109,105 @@ pub(super) fn denormalise( freq[bound..n].fill(0.0); } +/// The encoder's spreading decision state, carried between frames. +pub(super) struct Spreading { + /// A recursive average of how peaky the bands are, in Q8. + pub average: i32, + /// A recursive average of the high bands' peakiness, steering the tapset. + pub hf_average: i32, + /// The comb filter tapset chosen from `hf_average`. + pub tapset: usize, +} + +/// Choose how much to spread the pulses of the normalized spectrum `x`, from how peaky its +/// bands are, weighted by `spread_weight`. With `update_hf`, also update the tapset. +#[allow( + clippy::too_many_arguments, + reason = "mirrors libopus's spreading_decision, which the encoder calls once" +)] +pub(super) fn spreading_decision( + x: &[f32], + state: &mut Spreading, + last_decision: usize, + update_hf: bool, + end: usize, + channels: usize, + m: usize, + spread_weight: &[i32; BANDS], +) -> usize { + let n0 = m * SHORT_MDCT_SIZE; + if m * rate::band_width(end - 1) as usize <= 8 { + return SPREAD_NONE; + } + let mut sum = 0; + let mut nb_bands = 0; + let mut hf_sum = 0; + for c in 0..channels { + for i in 0..end { + let n = m * rate::band_width(i) as usize; + if n <= 8 { + continue; + } + let x = &x[c * n0 + band_start(i, m)..][..n]; + // A rough CDF of |x[j]|. + let mut tcount = [0; 3]; + for &v in x { + let x2n = v * v * n as f32; + tcount[0] += i32::from(x2n < 0.25); + tcount[1] += i32::from(x2n < 0.0625); + tcount[2] += i32::from(x2n < 0.015625); + } + // Only the last four bands, 8 kHz and up, steer the tapset. + if i > BANDS - 4 { + hf_sum += udiv(32 * (tcount[1] + tcount[0]), n as i32); + } + let n = n as i32; + let tmp = i32::from(2 * tcount[2] >= n) + i32::from(2 * tcount[1] >= n) + i32::from(2 * tcount[0] >= n); + sum += tmp * spread_weight[i]; + nb_bands += spread_weight[i]; + } + } + + if update_hf { + if hf_sum != 0 { + hf_sum = udiv(hf_sum, channels as i32 * (4 - BANDS as i32 + end as i32)); + } + state.hf_average = (state.hf_average + hf_sum) >> 1; + hf_sum = state.hf_average; + match state.tapset { + 2 => hf_sum += 4, + 0 => hf_sum -= 4, + _ => {} + } + state.tapset = match hf_sum { + 23.. => 2, + 19.. => 1, + _ => 0, + }; + } + assert!(nb_bands > 0, "every coded band has a spreading weight"); + let sum = udiv(sum << 8, nb_bands); + // Recursive averaging. + let sum = (sum + state.average) >> 1; + state.average = sum; + // Hysteresis. + let sum = (3 * sum + (((3 - last_decision as i32) << 7) + 64) + 2) >> 2; + if sum < 80 { + SPREAD_AGGRESSIVE + } else if sum < 256 { + SPREAD_NORMAL + } else if sum < 384 { + SPREAD_LIGHT + } else { + SPREAD_NONE + } +} + +/// libopus's `celt_udiv`: unsigned division of values it treats as unsigned. +fn udiv(n: i32, d: i32) -> i32 { + (n as u32 / d as u32) as i32 +} + /// The stereo spectrum's two channels. pub(super) struct Channels<'a> { pub x: &'a mut [f32], @@ -130,9 +273,14 @@ pub(super) fn anti_collapse( } } -/// The per-frame state shared by every band's decode. +/// The per-frame state shared by every band's coding. struct Ctx<'d, 'a> { - dec: &'d mut range::Decoder<'a>, + coder: Coder<'d, 'a>, + /// The encoder's band amplitudes; none when decoding. + band_e: Option<&'d [f32; 2 * BANDS]>, + /// Whether to reconstruct the decoded spectrum, as the decoder and the encoder's theta + /// search need. + resynth: bool, band: usize, intensity: usize, spread: usize, @@ -140,9 +288,13 @@ struct Ctx<'d, 'a> { remaining_bits: i32, seed: u32, disable_inv: bool, + /// Which way the encoder rounds a stereo angle: down (-1), up (1), or to nearest (0). + theta_round: i32, + /// Keep a mono split from coding noise into a silent half, for transients' first band. + avoid_split_noise: bool, } -/// The decoded split of a band into two halves. +/// The coded split of a band into two halves. struct Split { inv: bool, imid: i32, @@ -172,16 +324,48 @@ fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 } } +/// The weights balancing two channels' normalized distortion: their amplitudes, made a bit +/// more conservative. +fn channel_weights(ex: f32, ey: f32) -> [f32; 2] { + let min_e = math::min(ex, ey); + [ex + min_e / 3.0, ey + min_e / 3.0] +} + +/// Mix `y` into `x` as one channel at the two channels' relative amplitudes. +fn intensity_stereo(x: &mut [f32], y: &[f32], band_e: &[f32; 2 * BANDS], band: usize) { + const EPSILON: f32 = 1e-15; + let left = band_e[band]; + let right = band_e[band + BANDS]; + let norm = EPSILON + math::sqrt(EPSILON + left * left + right * right); + let a1 = left / norm; + let a2 = right / norm; + for (x, &y) in x.iter_mut().zip(y) { + *x = a1 * *x + a2 * y; + } +} + +/// Rotate left and right into mid and side. +fn stereo_split(x: &mut [f32], y: &mut [f32]) { + for (x, y) in x.iter_mut().zip(y.iter_mut()) { + let l = FRAC_1_SQRT_2 * *x; + let r = FRAC_1_SQRT_2 * *y; + *x = l + r; + *y = r - l; + } +} + impl Ctx<'_, '_> { - /// Decode the angle splitting `n` bins between mid and side (or two halves), spending - /// from `b`. + /// Code the angle splitting `n` bins between `x` and `y` (mid and side, or two halves), + /// spending from `b`. Encoding measures it from `x` and `y`, and for stereo leaves them as + /// mid and side. #[allow( clippy::too_many_arguments, reason = "mirrors libopus's compute_theta, shared by mono splits and stereo" )] fn compute_theta( &mut self, - n: usize, + x: &mut [f32], + y: &mut [f32], b: &mut i32, blocks: usize, b0: usize, @@ -189,6 +373,7 @@ impl Ctx<'_, '_> { stereo: bool, fill: &mut u32, ) -> Split { + let n = x.len(); let n_i = n as i32; let pulse_cap = i32::from(LOG_N[self.band]) + lm * (1 << BITRES); let offset = (pulse_cap >> 1) @@ -201,60 +386,113 @@ impl Ctx<'_, '_> { if stereo && self.band >= self.intensity { qn = 1; } - let tell = self.dec.tell_frac() as i32; - let mut itheta = 0; + let encoding = self.coder.encoding(); + // The arctangent of the side over the mid, which with both normalized and orthogonal + // is all it takes to rescale them. + let mut itheta = if encoding { + vq::stereo_itheta(x, y, stereo) >> 16 + } else { + 0 + }; + let tell = self.coder.tell_frac() as i32; let mut inv = false; if qn != 1 { + if encoding { + itheta = self.quantize_theta(itheta, qn, n_i, *b, stereo); + } + // A uniform distribution for the time split, a step for stereo, and a triangle + // for the rest. if stereo && n > 2 { - // A step distribution: probability 3 up to itheta 8192, 1 after. + // Probability 3 up to itheta 8192, 1 after. let p0 = 3; let x0 = qn / 2; let ft = p0 * (x0 + 1) + x0; - let symbol = self.dec.decode(ft as u32); - let fs = symbol.index() as i32; - let x = if fs < (x0 + 1) * p0 { - fs / p0 - } else { - x0 + 1 + (fs - (x0 + 1) * p0) - }; - let (fl, fh) = if x <= x0 { - (p0 * x, p0 * (x + 1)) - } else { - ((x - 1 - x0) + (x0 + 1) * p0, (x - x0) + (x0 + 1) * p0) + let bounds = |x: i32| { + if x <= x0 { + (p0 * x)..(p0 * (x + 1)) + } else { + ((x - 1 - x0) + (x0 + 1) * p0)..((x - x0) + (x0 + 1) * p0) + } }; - symbol.update(fl as u32..fh as u32); - itheta = x; + match &mut self.coder { + Coder::Encode(enc) => { + let bounds = bounds(itheta); + enc.encode(bounds.start as u32..bounds.end as u32, ft as u32); + } + Coder::Decode(dec) => { + let symbol = dec.decode(ft as u32); + let fs = symbol.index() as i32; + itheta = if fs < (x0 + 1) * p0 { + fs / p0 + } else { + x0 + 1 + (fs - (x0 + 1) * p0) + }; + let bounds = bounds(itheta); + symbol.update(bounds.start as u32..bounds.end as u32); + } + } } else if b0 > 1 || stereo { - itheta = self.dec.uint((qn + 1) as u32) as i32; + itheta = self.coder.uint(itheta as u32, (qn + 1) as u32) as i32; } else { - // A triangular distribution. let ft = ((qn >> 1) + 1) * ((qn >> 1) + 1); - let symbol = self.dec.decode(ft as u32); - let fm = symbol.index() as i32; - let (fl, fs); - if fm < (((qn >> 1) * ((qn >> 1) + 1)) >> 1) { - itheta = (math::isqrt32(8 * fm as u32 + 1) as i32 - 1) >> 1; - fs = itheta + 1; - fl = (itheta * (itheta + 1)) >> 1; - } else { - itheta = (2 * (qn + 1) - math::isqrt32(8 * (ft - fm - 1) as u32 + 1) as i32) >> 1; - fs = qn + 1 - itheta; - fl = ft - (((qn + 1 - itheta) * (qn + 2 - itheta)) >> 1); + match &mut self.coder { + Coder::Encode(enc) => { + let (fl, fs) = if itheta <= qn >> 1 { + ((itheta * (itheta + 1)) >> 1, itheta + 1) + } else { + (ft - (((qn + 1 - itheta) * (qn + 2 - itheta)) >> 1), qn + 1 - itheta) + }; + enc.encode(fl as u32..(fl + fs) as u32, ft as u32); + } + Coder::Decode(dec) => { + let symbol = dec.decode(ft as u32); + let fm = symbol.index() as i32; + let (fl, fs); + if fm < (((qn >> 1) * ((qn >> 1) + 1)) >> 1) { + itheta = (math::isqrt32(8 * fm as u32 + 1) as i32 - 1) >> 1; + fs = itheta + 1; + fl = (itheta * (itheta + 1)) >> 1; + } else { + itheta = (2 * (qn + 1) - math::isqrt32(8 * (ft - fm - 1) as u32 + 1) as i32) >> 1; + fs = qn + 1 - itheta; + fl = ft - (((qn + 1 - itheta) * (qn + 2 - itheta)) >> 1); + } + symbol.update(fl as u32..(fl + fs) as u32); + } } - symbol.update(fl as u32..(fl + fs) as u32); } itheta = (itheta as u32 * 16384 / qn as u32) as i32; + if encoding && stereo { + let band_e = self.band_e.expect("encoding has band energies"); + if itheta == 0 { + intensity_stereo(x, y, band_e, self.band); + } else { + stereo_split(x, y); + } + } } else if stereo { - if *b > 2 << BITRES && self.remaining_bits > 2 << BITRES { - inv = self.dec.bit_logp(2); + if encoding { + inv = itheta > 8192 && !self.disable_inv; + if inv { + for y in y.iter_mut() { + *y = -*y; + } + } + let band_e = self.band_e.expect("encoding has band energies"); + intensity_stereo(x, y, band_e, self.band); } + inv = if *b > 2 << BITRES && self.remaining_bits > 2 << BITRES { + self.coder.bit_logp(inv, 2) + } else { + false + }; // Phase inversion is overridden to keep downmixing safe. if self.disable_inv { inv = false; } itheta = 0; } - let qalloc = self.dec.tell_frac() as i32 - tell; + let qalloc = self.coder.tell_frac() as i32 - tell; *b -= qalloc; let (imid, iside, delta); @@ -284,19 +522,46 @@ impl Ctx<'_, '_> { } } - /// Decode one-bin bands, which code only a sign per channel. + /// Quantize the encoder's angle `itheta` (a quarter turn at 16384) to one of `qn + 1` + /// steps, rounding as `theta_round` asks. + fn quantize_theta(&self, itheta: i32, qn: i32, n: i32, b: i32, stereo: bool) -> i32 { + if stereo && self.theta_round != 0 { + // Bias towards itheta 0 and 16384. + let bias = if itheta > 8192 { 32767 / qn } else { -32767 / qn }; + let down = (qn - 1).min(0.max((itheta * qn + bias) >> 14)); + return if self.theta_round < 0 { down } else { down + 1 }; + } + let mut itheta = (itheta * qn + 8192) >> 14; + if !stereo && self.avoid_split_noise && itheta > 0 && itheta < qn { + // If the allocation would inject noise into one half, give that half no energy. + let unquantized = (itheta as u32 * 16384 / qn as u32) as i32; + let imid = i32::from(math::bitexact_cos(unquantized as i16)); + let iside = i32::from(math::bitexact_cos((16384 - unquantized) as i16)); + let delta = frac_mul16((n - 1) << 7, math::bitexact_log2tan(iside, imid)); + if delta > b { + itheta = qn; + } else if delta < -b { + itheta = 0; + } + } + itheta + } + + /// Code one-bin bands, which code only a sign per channel. fn quant_band_n1(&mut self, x: &mut [f32], y: Option<&mut [f32]>, lowband_out: Option<&mut [f32]>) -> u32 { - let mut decode_sign = |sample: &mut f32| { + let mut code_sign = |sample: &mut f32| { let mut sign = 0; if self.remaining_bits >= 1 << BITRES { - sign = self.dec.bits(1); + sign = self.coder.bits(u32::from(*sample < 0.0), 1); self.remaining_bits -= 1 << BITRES; } - *sample = if sign != 0 { -1.0 } else { 1.0 }; + if self.resynth { + *sample = if sign != 0 { -1.0 } else { 1.0 }; + } }; - decode_sign(&mut x[0]); + code_sign(&mut x[0]); if let Some(y) = y { - decode_sign(&mut y[0]); + code_sign(&mut y[0]); } if let Some(out) = lowband_out { out[0] = x[0]; @@ -304,7 +569,7 @@ impl Ctx<'_, '_> { 1 } - /// Decode a mono partition, splitting it in two and recursing while its bits exceed what + /// Code a mono partition, splitting it in two and recursing while its bits exceed what /// one codebook codes. #[allow( clippy::too_many_arguments, @@ -336,7 +601,7 @@ impl Ctx<'_, '_> { fill = (fill & 1) | (fill << 1); } blocks = (blocks + 1) >> 1; - let split = self.compute_theta(n, &mut b, blocks, b0, lm, false, &mut fill); + let split = self.compute_theta(x, y, &mut b, blocks, b0, lm, false, &mut fill); let mid = (1.0 / 32768.0) * split.imid as f32; let side = (1.0 / 32768.0) * split.iside as f32; let itheta = split.itheta; @@ -401,10 +666,16 @@ impl Ctx<'_, '_> { } if q != 0 { let k = rate::get_pulses(q) as usize; - return vq::alg_unquant(x, k, self.spread, blocks, self.dec, gain); + return match &mut self.coder { + Coder::Encode(enc) => vq::alg_quant(x, k, self.spread, blocks, enc, gain, self.resynth), + Coder::Decode(dec) => vq::alg_unquant(x, k, self.spread, blocks, dec, gain), + }; } - // No pulses: fill the band anyway. + // No pulses: fill the band anyway, which only reconstruction needs. + if !self.resynth { + return 0; + } let cm_mask = ((1u64 << blocks) - 1) as u32; fill &= cm_mask; if fill == 0 { @@ -438,7 +709,7 @@ impl Ctx<'_, '_> { cm } - /// Decode a mono band, changing its time-frequency resolution around the partition. + /// Code a mono band, changing its time-frequency resolution around the partition. #[allow( clippy::too_many_arguments, reason = "mirrors libopus's quant_band, shared by mono, mid, and side" @@ -462,6 +733,7 @@ impl Ctx<'_, '_> { let n0 = n; let b0 = blocks; let long_blocks = b0 == 1; + let encoding = self.coder.encoding(); let mut tf_change = self.tf_change; let mut n_b = n / blocks; @@ -472,6 +744,9 @@ impl Ctx<'_, '_> { let recombine = tf_change.max(0) as usize; // Band recombining to increase frequency resolution. for k in 0..recombine { + if encoding { + haar1(x, n >> k, 1 << k); + } if let Some(lowband) = lowband.as_deref_mut() { haar1(lowband, n >> k, 1 << k); } @@ -484,6 +759,9 @@ impl Ctx<'_, '_> { // Increasing the time resolution. let mut time_divide = 0; while n_b & 1 == 0 && tf_change < 0 { + if encoding { + haar1(x, n_b, blocks); + } if let Some(lowband) = lowband.as_deref_mut() { haar1(lowband, n_b, blocks); } @@ -498,12 +776,18 @@ impl Ctx<'_, '_> { // Reorganize the samples in time order instead of frequency order. if b0 > 1 { + if encoding { + deinterleave_hadamard(x, n_b >> recombine, b0 << recombine, long_blocks); + } if let Some(lowband) = lowband.as_deref_mut() { deinterleave_hadamard(lowband, n_b >> recombine, b0 << recombine, long_blocks); } } let mut cm = self.quant_partition(x, b, blocks, lowband, lm, gain, fill); + if !self.resynth { + return cm; + } // Undo the reorganization, back to frequency order. if b0 > 1 { @@ -534,7 +818,7 @@ impl Ctx<'_, '_> { cm & ((1 << blocks) - 1) } - /// Decode a stereo band as mid and side. + /// Code a stereo band as mid and side. #[allow(clippy::too_many_arguments, reason = "mirrors libopus's quant_band_stereo")] fn quant_band_stereo( &mut self, @@ -552,7 +836,17 @@ impl Ctx<'_, '_> { return self.quant_band_n1(x, Some(y), lowband_out); } let orig_fill = fill; - let split = self.compute_theta(n, &mut b, blocks, blocks, lm, true, &mut fill); + if let Some(band_e) = self.band_e { + let (left, right) = (band_e[self.band], band_e[BANDS + self.band]); + if left < MIN_STEREO_ENERGY || right < MIN_STEREO_ENERGY { + if left > right { + y.copy_from_slice(x); + } else { + x.copy_from_slice(y); + } + } + } + let split = self.compute_theta(x, y, &mut b, blocks, blocks, lm, true, &mut fill); let mid = (1.0 / 32768.0) * split.imid as f32; let side = (1.0 / 32768.0) * split.iside as f32; let itheta = split.itheta; @@ -568,27 +862,29 @@ impl Ctx<'_, '_> { mbits -= sbits; let swap = itheta > 8192; self.remaining_bits -= split.qalloc + sbits; + let (x2, y2) = if swap { (&mut *y, &mut *x) } else { (&mut *x, &mut *y) }; let mut sign = 0; if sbits != 0 { - sign = self.dec.bits(1) as i32; + sign = self.coder.bits(u32::from(x2[0] * y2[1] - x2[1] * y2[0] < 0.0), 1) as i32; } let sign = 1 - 2 * sign; - let (x2, y2) = if swap { (&mut *y, &mut *x) } else { (&mut *x, &mut *y) }; // orig_fill folds the side even when itheta 16384 cleared fill's low bits. cm = self.quant_band(x2, mbits, blocks, lowband, lm, lowband_out, 1.0, orig_fill); // N = 2 never splits, so cm is 1 or 0 (a collapsed fold) and needs no mixing. y2[0] = (-sign) as f32 * x2[1]; y2[1] = sign as f32 * x2[0]; - x[0] *= mid; - x[1] *= mid; - y[0] *= side; - y[1] *= side; - let tmp = x[0]; - x[0] = tmp - y[0]; - y[0] += tmp; - let tmp = x[1]; - x[1] = tmp - y[1]; - y[1] += tmp; + if self.resynth { + x[0] *= mid; + x[1] *= mid; + y[0] *= side; + y[1] *= side; + let tmp = x[0]; + x[0] = tmp - y[0]; + y[0] += tmp; + let tmp = x[1]; + x[1] = tmp - y[1]; + y[1] += tmp; + } } else { let mut mbits = 0.max(b.min((b - split.delta) / 2)); let mut sbits = b - mbits; @@ -613,9 +909,11 @@ impl Ctx<'_, '_> { c |= self.quant_band(x, mbits, blocks, lowband, lm, lowband_out, 1.0, fill); cm = c; } - stereo_merge(x, y, mid); + if self.resynth { + stereo_merge(x, y, mid); + } } - if split.inv { + if self.resynth && split.inv { for y in y.iter_mut() { *y = -*y; } @@ -626,7 +924,6 @@ impl Ctx<'_, '_> { /// Rotate mid and side back to left and right, renormalizing both. fn stereo_merge(x: &mut [f32], y: &mut [f32], mid: f32) { - use super::pitch::inner_prod; // The norms of X+Y and X-Y, as |X|^2 + |Y|^2 +/- 2 sum(xy). let xp = inner_prod(y, x); let side = inner_prod(y, y); @@ -650,7 +947,7 @@ fn stereo_merge(x: &mut [f32], y: &mut [f32], mid: f32) { } /// One level of the Haar transform over `n0` bins interleaved by `stride`. -fn haar1(x: &mut [f32], n0: usize, stride: usize) { +pub(super) fn haar1(x: &mut [f32], n0: usize, stride: usize) { for i in 0..stride { for j in 0..n0 >> 1 { let a = stride * 2 * j + i; @@ -712,13 +1009,25 @@ pub(super) struct Coding<'a> { pub disable_inv: bool, } -/// Decode every band's normalized spectrum into `spectrum`, returning each band and -/// channel's collapse mask. +/// Which way the spectrum is coded. +pub(super) enum Direction<'c, 'a> { + Decode(&'c mut range::Decoder<'a>), + /// Encode the spectrum of bands with amplitudes `band_e`; from complexity 8, stereo + /// bands try rounding their angle both ways and keep the less distorted. + Encode { + enc: &'c mut range::Encoder<'a>, + band_e: &'c [f32; 2 * BANDS], + complexity: usize, + }, +} + +/// Code every band's normalized spectrum, decoding into `spectrum` or encoding from it, +/// returning each band and channel's collapse mask. pub(super) fn quant_all_bands( coding: &Coding, alloc: &Allocation, spectrum: Channels, - dec: &mut range::Decoder, + direction: Direction, seed: &mut u32, ) -> [u8; 2 * BANDS] { let Coding { @@ -735,6 +1044,20 @@ pub(super) fn quant_all_bands( let channels = if y_all.is_some() { 2 } else { 1 }; let m = 1 << lm; let blocks = if short_blocks { m } else { 1 }; + let mut dual_stereo = alloc.dual_stereo; + let (coder, band_e, theta_rdo) = match direction { + Direction::Decode(dec) => (Coder::Decode(dec), None, false), + Direction::Encode { + enc, + band_e, + complexity, + } => ( + Coder::Encode(enc), + Some(band_e), + channels == 2 && !dual_stereo && complexity >= 8, + ), + }; + let resynth = band_e.is_none() || theta_rdo; let norm_offset = band_start(start, m); // Folding memory for each channel; the last band needs none. let norm2_offset = band_start(BANDS - 1, m) - norm_offset; @@ -742,11 +1065,12 @@ pub(super) fn quant_all_bands( let mut collapse_masks = [0u8; 2 * BANDS]; let mut lowband_offset = 0; let mut update_lowband = true; - let mut dual_stereo = alloc.dual_stereo; let mut balance = alloc.balance; let coded_bands = alloc.coded_bands; let mut ctx = Ctx { - dec, + coder, + band_e, + resynth, band: start, intensity: alloc.intensity, spread, @@ -754,6 +1078,9 @@ pub(super) fn quant_all_bands( remaining_bits: 0, seed: *seed, disable_inv, + theta_round: 0, + // Avoid injecting noise in the first band of transients. + avoid_split_noise: blocks > 1, }; for i in start..end { @@ -761,7 +1088,7 @@ pub(super) fn quant_all_bands( let last = i == end - 1; let bins = band_start(i, m)..band_start(i + 1, m); let n = bins.len(); - let tell = ctx.dec.tell_frac() as i32; + let tell = ctx.coder.tell_frac() as i32; // How many bits to give this band. if i != start { @@ -776,7 +1103,10 @@ pub(super) fn quant_all_bands( 0 }; - if (band_start(i, m) >= n + band_start(start, m) || i == start + 1) && (update_lowband || lowband_offset == 0) { + if resynth + && (band_start(i, m) >= n + band_start(start, m) || i == start + 1) + && (update_lowband || lowband_offset == 0) + { lowband_offset = i; } if i == start + 1 { @@ -826,9 +1156,11 @@ pub(super) fn quant_all_bands( if dual_stereo && i == alloc.intensity { // Switch off dual stereo to do intensity. dual_stereo = false; - let len = band_start(i, m) - norm_offset; - for j in 0..len { - norm[j] = 0.5 * (norm[j] + norm[norm2_offset + j]); + if resynth { + let len = band_start(i, m) - norm_offset; + for j in 0..len { + norm[j] = 0.5 * (norm[j] + norm[norm2_offset + j]); + } } } @@ -844,21 +1176,81 @@ pub(super) fn quant_all_bands( let lowband_out = (!last).then(|| &mut norm[norm2_offset + out..norm2_offset + out + n]); y_cm = ctx.quant_band(y, b / 2, blocks, low, lm as i32, lowband_out, 1.0, y_cm); } else { - let low = fold_source(&mut lowband_buf, &norm, effective_lowband, n); - let lowband_out = (!last).then(|| &mut norm[out..out + n]); - x_cm = match y_all.as_deref_mut() { - Some(y_all) => ctx.quant_band_stereo( - x, - &mut y_all[bins.clone()], - b, - blocks, - low, - lm as i32, - lowband_out, - x_cm | y_cm, - ), - None => ctx.quant_band(x, b, blocks, low, lm as i32, lowband_out, 1.0, x_cm | y_cm), - }; + match y_all.as_deref_mut() { + Some(y_all) => { + let y = &mut y_all[bins.clone()]; + let fill = x_cm | y_cm; + let stereo = move |ctx: &mut Ctx, norm: &mut [f32; 2 * MAX_NORM], x: &mut [f32], y: &mut [f32]| { + let mut lowband_buf = [0.0f32; MAX_BAND]; + let low = fold_source(&mut lowband_buf, &norm[..], effective_lowband, n); + let lowband_out = (!last).then(|| &mut norm[out..out + n]); + ctx.quant_band_stereo(x, y, b, blocks, low, lm as i32, lowband_out, fill) + }; + x_cm = if theta_rdo && i < alloc.intensity { + // Code the band with its angle rounded down, then up, keeping the + // less distorted. + let band_e = band_e.expect("encoding has band energies"); + let w = channel_weights(band_e[i], band_e[i + BANDS]); + let mut x_save = [0.0f32; MAX_BAND]; + let mut y_save = [0.0f32; MAX_BAND]; + x_save[..n].copy_from_slice(x); + y_save[..n].copy_from_slice(y); + let (x_save, y_save) = (&x_save[..n], &y_save[..n]); + let distortion = + |x: &[f32], y: &[f32]| w[0] * inner_prod(x_save, x) + w[1] * inner_prod(y_save, y); + let enc_save = ctx.coder.encoder().checkpoint(); + let save_bytes = ctx.coder.encoder().range_bytes(); + let ctx_save = (ctx.remaining_bits, ctx.seed); + + ctx.theta_round = -1; + let cm_down = stereo(&mut ctx, &mut norm, x, y); + let dist_down = distortion(x, y); + let enc_down = Snapshot::take(ctx.coder.encoder(), save_bytes); + let ctx_down = (ctx.remaining_bits, ctx.seed); + let mut x_down = [0.0f32; MAX_BAND]; + let mut y_down = [0.0f32; MAX_BAND]; + let mut norm_down = [0.0f32; MAX_BAND]; + x_down[..n].copy_from_slice(x); + y_down[..n].copy_from_slice(y); + if !last { + norm_down[..n].copy_from_slice(&norm[out..out + n]); + } + + ctx.coder.encoder().restore(&enc_save); + (ctx.remaining_bits, ctx.seed) = ctx_save; + x.copy_from_slice(x_save); + y.copy_from_slice(y_save); + // The first pass overwrote the folding data the second band reads. + if i == start + 1 { + special_hybrid_folding(&mut norm, norm2_offset, start, m, dual_stereo); + } + ctx.theta_round = 1; + let cm_up = stereo(&mut ctx, &mut norm, x, y); + let dist_up = distortion(x, y); + + if dist_down >= dist_up { + enc_down.restore(ctx.coder.encoder()); + (ctx.remaining_bits, ctx.seed) = ctx_down; + x.copy_from_slice(&x_down[..n]); + y.copy_from_slice(&y_down[..n]); + if !last { + norm[out..out + n].copy_from_slice(&norm_down[..n]); + } + cm_down + } else { + cm_up + } + } else { + ctx.theta_round = 0; + stereo(&mut ctx, &mut norm, x, y) + }; + } + None => { + let low = fold_source(&mut lowband_buf, &norm, effective_lowband, n); + let lowband_out = (!last).then(|| &mut norm[out..out + n]); + x_cm = ctx.quant_band(x, b, blocks, low, lm as i32, lowband_out, 1.0, x_cm | y_cm); + } + } y_cm = x_cm; } collapse_masks[i * channels] = x_cm as u8; @@ -867,6 +1259,8 @@ pub(super) fn quant_all_bands( // Update the folding position only while there is 1 bit per sample of depth. update_lowband = b > (n as i32) << BITRES; + // Only the first band needs to avoid noise on a split; after it, there is folding. + ctx.avoid_split_noise = false; } *seed = ctx.seed; collapse_masks @@ -898,3 +1292,202 @@ fn special_hybrid_folding(norm: &mut [f32], norm2_offset: usize, start: usize, m norm.copy_within(norm2_offset + 2 * n1 - n2..norm2_offset + n1, norm2_offset + n1); } } + +#[cfg(test)] +mod tests { + use super::super::rate::{Choices, Signal}; + use super::super::SPREAD_NORMAL; + use super::*; + + struct Coded { + masks: [u8; 2 * BANDS], + seed: u32, + range: u32, + spectrum: Vec, + } + + /// Encode a random spectrum's bands, then decode them, returning both sides. + fn code_bands( + channels: usize, + lm: usize, + short_blocks: bool, + bytes: usize, + intensity: usize, + dual_stereo: bool, + ) -> (Coded, Coded) { + let n = SHORT_MDCT_SIZE << lm; + let m = 1 << lm; + let mut seed = (lm * 7 + bytes) as u32; + let mut freq = vec![0.0f32; 2 * n]; + for (i, f) in freq.iter_mut().enumerate() { + seed = math::lcg_rand(seed); + // Correlated channels with a falling spectrum. + *f = math::lcg_sample(seed) * 1000.0 / (1.0 + (i % n) as f32 * 0.05); + } + for i in 0..n { + freq[n + i] = 0.6 * freq[i] + 0.4 * freq[n + i]; + } + let mut band_e = [0.0f32; 2 * BANDS]; + compute_band_energies(&freq, &mut band_e, BANDS, channels, lm); + let mut x = vec![0.0f32; 2 * n]; + normalise_bands(&freq, &mut x, &band_e, BANDS, channels, m); + let tf_res: [i32; BANDS] = std::array::from_fn(|i| { + if short_blocks { + (i % 2) as i32 + } else { + -((i % 2) as i32) + } + }); + let offsets = [0; BANDS]; + let cap = rate::init_caps(lm, channels); + + let mut buf = vec![0u8; bytes]; + let mut enc = range::Encoder::new(&mut buf); + let total = ((bytes as i32 * 8) << BITRES) - enc.tell_frac() as i32 - 1; + let choices = Choices { + prev_coded_bands: 0, + signal_bandwidth: BANDS - 1, + intensity, + dual_stereo, + }; + let alloc = rate::compute_allocation( + 0, + BANDS, + &offsets, + &cap, + 5, + total, + channels, + lm, + Signal::Encode(&mut enc, choices), + ); + let coding = Coding { + start: 0, + end: BANDS, + short_blocks, + spread: SPREAD_NORMAL, + tf_res: &tf_res, + total_bits: (bytes as i32 * 8) << BITRES, + lm, + disable_inv: false, + }; + let mut enc_seed = 1; + let (ex, ey) = x.split_at_mut(n); + let direction = Direction::Encode { + enc: &mut enc, + band_e: &band_e, + complexity: 10, + }; + let spectrum = Channels { + x: ex, + y: (channels == 2).then_some(ey), + }; + let enc_masks = quant_all_bands(&coding, &alloc, spectrum, direction, &mut enc_seed); + let enc_range = enc.range(); + let packet = enc.finish().expect("fits").to_vec(); + + let mut dec = range::Decoder::new(&packet); + let alloc = rate::compute_allocation( + 0, + BANDS, + &offsets, + &cap, + 5, + total, + channels, + lm, + Signal::Decode(&mut dec), + ); + let mut decoded = vec![0.0f32; 2 * n]; + let (dx, dy) = decoded.split_at_mut(n); + let spectrum = Channels { + x: dx, + y: (channels == 2).then_some(dy), + }; + let mut dec_seed = 1; + let dec_masks = quant_all_bands(&coding, &alloc, spectrum, Direction::Decode(&mut dec), &mut dec_seed); + ( + Coded { + masks: enc_masks, + seed: enc_seed, + range: enc_range, + spectrum: x, + }, + Coded { + masks: dec_masks, + seed: dec_seed, + range: dec.range(), + spectrum: decoded, + }, + ) + } + + /// Stereo bands coded with the angle search reconstruct in the encoder exactly as the + /// decoder decodes them, through mid-side, intensity, folding, and time-frequency changes. + #[test] + fn stereo_bands_decode_to_the_encoders_resynthesis() { + for (lm, short_blocks, bytes, intensity) in [ + (3, false, 160, 14), + (3, true, 200, 10), + (2, true, 60, 21), + (1, false, 30, 6), + (0, false, 40, 12), + ] { + let (enc, dec) = code_bands(2, lm, short_blocks, bytes, intensity, false); + assert_eq!(enc.range, dec.range, "lm {lm}"); + assert_eq!(enc.seed, dec.seed, "lm {lm}"); + assert_eq!(enc.masks, dec.masks, "lm {lm}"); + assert_eq!(enc.spectrum, dec.spectrum, "lm {lm}"); + } + } + + /// Mono and dual stereo bands, which the encoder doesn't reconstruct, stay in sync. + #[test] + fn mono_and_dual_stereo_bands_stay_in_sync() { + for (channels, lm, short_blocks, bytes) in [ + (1, 3, false, 100), + (1, 2, true, 50), + (2, 3, false, 160), + (2, 1, true, 80), + ] { + let (enc, dec) = code_bands(channels, lm, short_blocks, bytes, BANDS, true); + assert_eq!(enc.range, dec.range, "{channels} channels, lm {lm}"); + } + } + + /// Peaky spectra, whose bins are mostly near zero, spread less than noise. + #[test] + fn spreading_follows_peakiness() { + let lm = 3; + let m = 1 << lm; + let n = SHORT_MDCT_SIZE << lm; + let weights = [32; BANDS]; + let mut noise = vec![0.0f32; n]; + let mut seed = 5u32; + for x in noise.iter_mut() { + seed = math::lcg_rand(seed); + *x = math::lcg_sample(seed); + } + for i in 0..BANDS { + vq::renormalise(&mut noise[band_start(i, m)..band_start(i + 1, m)], 1.0); + } + let mut peaks = vec![0.0f32; n]; + for i in 0..BANDS { + peaks[band_start(i, m)] = 1.0; + } + let decide = |x: &[f32]| { + let mut state = Spreading { + average: 256, + hf_average: 0, + tapset: 0, + }; + let mut decision = SPREAD_NORMAL; + for _ in 0..8 { + decision = spreading_decision(x, &mut state, decision, true, BANDS, 1, m, &weights); + } + decision + }; + assert_eq!(decide(&noise), SPREAD_AGGRESSIVE); + assert_eq!(decide(&peaks), SPREAD_NONE); + } +} diff --git a/kodecs-opus/src/safe/celt/coder.rs b/kodecs-opus/src/safe/celt/coder.rs new file mode 100644 index 00000000..57e5f007 --- /dev/null +++ b/kodecs-opus/src/safe/celt/coder.rs @@ -0,0 +1,109 @@ +//! A range coder running in either direction, for the steps libopus shares between its +//! encoder and decoder behind an `encode` flag. + +use super::MAX_FRAME_BYTES; +use crate::safe::range; + +/// The range coder of a frame being encoded or decoded. +pub(super) enum Coder<'c, 'a> { + Encode(&'c mut range::Encoder<'a>), + Decode(&'c mut range::Decoder<'a>), +} + +impl<'a> Coder<'_, 'a> { + pub(super) fn encoding(&self) -> bool { + matches!(self, Self::Encode(_)) + } + + /// The encoder, for the encoder's own searches. + /// + /// # Panics + /// + /// When decoding. + pub(super) fn encoder(&mut self) -> &mut range::Encoder<'a> { + match self { + Self::Encode(enc) => enc, + Self::Decode(_) => panic!("only the encoder searches"), + } + } + + pub(super) fn tell_frac(&self) -> u32 { + match self { + Self::Encode(enc) => enc.tell_frac(), + Self::Decode(dec) => dec.tell_frac(), + } + } + + /// Encode `bit`, or decode a bit, whose probability of being set is 2 to the power of + /// `-logp`. + pub(super) fn bit_logp(&mut self, bit: bool, logp: u32) -> bool { + match self { + Self::Encode(enc) => { + enc.bit_logp(bit, logp); + bit + } + Self::Decode(dec) => dec.bit_logp(logp), + } + } + + /// Encode `value`, or decode a value, uniform below `total`. + pub(super) fn uint(&mut self, value: u32, total: u32) -> u32 { + match self { + Self::Encode(enc) => { + enc.uint(value, total); + value + } + Self::Decode(dec) => dec.uint(total), + } + } + + /// Encode `value`, or decode a value, as `count` raw bits. + pub(super) fn bits(&mut self, value: u32, count: u32) -> u32 { + match self { + Self::Encode(enc) => { + enc.bits(value, count); + value + } + Self::Decode(dec) => dec.bits(count), + } + } +} + +/// An encoder's state after a trial encode, with the bytes it wrote, which a second trial +/// from the same start overwrites. +pub(super) struct Snapshot { + checkpoint: range::Checkpoint, + /// The range bytes before the trial, which it left alone. + from: usize, + range: [u8; MAX_FRAME_BYTES], + raw: [u8; MAX_FRAME_BYTES], +} + +impl Snapshot { + /// Save `enc` after a trial that started with `from` range bytes written. + pub(super) fn take(enc: &range::Encoder<'_>, from: usize) -> Self { + let mut range = [0; MAX_FRAME_BYTES]; + let written = &enc.range_written()[from..]; + range[..written.len()].copy_from_slice(written); + let mut raw = [0; MAX_FRAME_BYTES]; + let written = enc.raw_written(); + raw[..written.len()].copy_from_slice(written); + Self { + checkpoint: enc.checkpoint(), + from, + range, + raw, + } + } + + /// Rewind `enc` to the end of the saved trial, rewriting its bytes. + pub(super) fn restore(&self, enc: &mut range::Encoder<'_>) { + enc.restore(&self.checkpoint); + let written = &mut enc.range_written_mut()[self.from..]; + let len = written.len(); + written.copy_from_slice(&self.range[..len]); + let written = enc.raw_written_mut(); + let len = written.len(); + written.copy_from_slice(&self.raw[..len]); + } +} diff --git a/kodecs-opus/src/safe/celt/comb.rs b/kodecs-opus/src/safe/celt/comb.rs new file mode 100644 index 00000000..02dabd8e --- /dev/null +++ b/kodecs-opus/src/safe/celt/comb.rs @@ -0,0 +1,115 @@ +//! The pitch comb filter the encoder's prefilter and the decoder's postfilter share, from +//! libopus's celt/celt.c. +//! Copyright (c) 2007-2008 CSIRO, 2007-2010 Xiph.Org Foundation, and 2008 Gregory Maxwell. + +use super::{COMBFILTER_MINPERIOD, OVERLAP}; + +/// The pitch filter's parameters for one frame. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) struct Filter { + pub period: usize, + pub gain: f32, + pub tapset: usize, +} + +/// The comb filter's taps for each tapset. +const COMB_GAINS: [[f32; 3]; 3] = [ + [0.306_640_63, 0.217_041_02, 0.129_638_67], + [0.463_867_2, 0.268_066_4, 0.0], + [0.799_804_7, 0.100_097_656, 0.0], +]; + +/// Filter `n` samples of `buf` from `at` with a three-tap comb at the pitch period, +/// cross-fading from `old` to `new` over the window's overlap (none without a window). +/// +/// Without `out` it filters in place, so later taps read already filtered samples, as +/// libopus's in-place call does; with it, the result goes there and `buf` is unchanged. +pub(super) fn comb_filter( + buf: &mut [f32], + at: usize, + mut out: Option<&mut [f32]>, + n: usize, + old: Filter, + new: Filter, + window: Option<&[f32; OVERLAP]>, +) { + let in_place = out.is_none(); + let mut write = |buf: &mut [f32], i: usize, value: f32| match out.as_deref_mut() { + Some(out) => out[i] = value, + None => buf[at + i] = value, + }; + if old.gain == 0.0 && new.gain == 0.0 { + if !in_place { + for i in 0..n { + let value = buf[at + i]; + write(buf, i, value); + } + } + return; + } + // A zero gain comes with a zero period, which needs to be at least 2 to read real data. + let t0 = old.period.max(COMBFILTER_MINPERIOD); + let t1 = new.period.max(COMBFILTER_MINPERIOD); + let g00 = old.gain * COMB_GAINS[old.tapset][0]; + let g01 = old.gain * COMB_GAINS[old.tapset][1]; + let g02 = old.gain * COMB_GAINS[old.tapset][2]; + let g10 = new.gain * COMB_GAINS[new.tapset][0]; + let g11 = new.gain * COMB_GAINS[new.tapset][1]; + let g12 = new.gain * COMB_GAINS[new.tapset][2]; + let x = |buf: &[f32], i: usize, back: usize| buf[at + i - back]; + let mut x1 = buf[at + 1 - t1]; + let mut x2 = buf[at - t1]; + let mut x3 = buf[at - t1 - 1]; + let mut x4 = buf[at - t1 - 2]; + // An unchanged filter needs no cross-fade. + let overlap = match window { + Some(_) if old.gain == new.gain && t0 == t1 && old.tapset == new.tapset => 0, + Some(_) => OVERLAP, + None => 0, + }; + let mut i = 0; + if let Some(window) = window { + while i < overlap { + let x0 = buf[at + i + 2 - t1]; + let f = window[i] * window[i]; + let value = buf[at + i] + + (1.0 - f) * g00 * x(buf, i, t0) + + (1.0 - f) * g01 * (buf[at + i + 1 - t0] + x(buf, i, t0 + 1)) + + (1.0 - f) * g02 * (buf[at + i + 2 - t0] + x(buf, i, t0 + 2)) + + f * g10 * x2 + + f * g11 * (x1 + x3) + + f * g12 * (x0 + x4); + write(buf, i, value); + x4 = x3; + x3 = x2; + x2 = x1; + x1 = x0; + i += 1; + } + } + if new.gain == 0.0 { + if !in_place { + for i in overlap..n { + let value = buf[at + i]; + write(buf, i, value); + } + } + return; + } + + // The constant filter, which rereads its history from the current position. + let mut x4 = buf[at + i - t1 - 2]; + let mut x3 = buf[at + i - t1 - 1]; + let mut x2 = buf[at + i - t1]; + let mut x1 = buf[at + i + 1 - t1]; + while i < n { + let x0 = buf[at + i + 2 - t1]; + let value = buf[at + i] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4); + write(buf, i, value); + x4 = x3; + x3 = x2; + x2 = x1; + x1 = x0; + i += 1; + } +} diff --git a/kodecs-opus/src/safe/celt/cwrs.rs b/kodecs-opus/src/safe/celt/cwrs.rs index 319f2858..e8ea216a 100644 --- a/kodecs-opus/src/safe/celt/cwrs.rs +++ b/kodecs-opus/src/safe/celt/cwrs.rs @@ -1,4 +1,4 @@ -//! Decoding PVQ codewords by their combinatorial index, from libopus's celt/cwrs.c. +//! Coding PVQ codewords by their combinatorial index, from libopus's celt/cwrs.c. //! Copyright (c) 2007-2008 CSIRO, 2007-2009 Xiph.Org Foundation, and 2007-2009 Timothy B. //! Terriberry. @@ -47,6 +47,31 @@ fn v(n: usize, k: usize) -> u32 { u(n, k).wrapping_add(u(n, k + 1)) } +/// Encode the codeword `y`, which holds `k` pulses. +pub(super) fn encode_pulses(y: &[i32], k: usize, enc: &mut range::Encoder) { + enc.uint(icwrs(y), v(y.len(), k)); +} + +/// The index of codeword `y` among those of its dimensions and pulses. +fn icwrs(y: &[i32]) -> u32 { + let n = y.len(); + assert!(n >= 2, "a codeword has at least two dimensions"); + let mut j = n - 1; + let mut index = u32::from(y[j] < 0); + let mut k = y[j].unsigned_abs() as usize; + loop { + j -= 1; + index += u(n - j, k); + k += y[j].unsigned_abs() as usize; + if y[j] < 0 { + index += u(n - j, k + 1); + } + if j == 0 { + return index; + } + } +} + /// Decode `y.len()` coordinates holding `k` pulses, returning their squared norm. pub(super) fn decode_pulses(y: &mut [i32], k: usize, dec: &mut range::Decoder) -> f32 { let n = y.len(); @@ -152,7 +177,7 @@ mod tests { } #[test] - fn every_index_decodes_to_a_distinct_codeword_with_k_pulses() { + fn every_index_round_trips_through_a_distinct_codeword_with_k_pulses() { for (n, k) in [(2, 3), (3, 2), (4, 4), (5, 7), (8, 2), (6, 6)] { let mut seen = std::collections::HashSet::new(); for index in 0..v(n, k) { @@ -160,6 +185,7 @@ mod tests { let yy = cwrsi(&mut y, k, index); assert_eq!(y.iter().map(|c| c.unsigned_abs() as usize).sum::(), k); assert_eq!(yy, y.iter().map(|&c| (c * c) as f32).sum::()); + assert_eq!(icwrs(&y), index, "N={n} K={k} encodes back"); assert!(seen.insert(y), "N={n} K={k} index {index} repeats"); } } diff --git a/kodecs-opus/src/safe/celt/decoder.rs b/kodecs-opus/src/safe/celt/decoder.rs index 1e6c2bb4..16dfe4ca 100644 --- a/kodecs-opus/src/safe/celt/decoder.rs +++ b/kodecs-opus/src/safe/celt/decoder.rs @@ -3,17 +3,18 @@ //! Copyright (c) 2007-2008 CSIRO, 2007-2010 Xiph.Org Foundation, and 2008 Gregory Maxwell. use super::bands::{self, Channels, Coding}; +use super::comb::{self, comb_filter}; use super::energy; use super::lpc; use super::math; use super::mdct; use super::pitch; use super::rate; -use super::tables::{EBANDS, PREEMPH, WINDOW}; +use super::tables::{EBANDS, PREEMPH, SPREAD_ICDF, TAPSET_ICDF, TF_SELECT_TABLE, TRIM_ICDF, WINDOW}; use super::vq; use super::{ - BANDS, COMBFILTER_MINPERIOD, DECODE_BUFFER_SIZE, LPC_ORDER, MAX_FRAME, MAX_LM, MAX_PERIOD, OVERLAP, - SHORT_MDCT_SIZE, SPREAD_NORMAL, + BANDS, COMBFILTER_MINPERIOD, DECODE_BUFFER_SIZE, LPC_ORDER, MAX_FRAME, MAX_FRAME_BYTES, MAX_LM, MAX_PERIOD, + OVERLAP, SHORT_MDCT_SIZE, SPREAD_NORMAL, }; use crate::safe::config::SampleRate; use crate::safe::math::CELT_SIG_SCALE; @@ -25,24 +26,9 @@ const BITRES: i32 = BIT_RESOLUTION as i32; const PLC_PITCH_LAG_MAX: usize = 720; /// The shortest pitch lag concealment searches, a 480 Hz pitch. const PLC_PITCH_LAG_MIN: usize = 100; -/// The largest frame a packet carries. -const MAX_FRAME_BYTES: usize = 1275; /// The samples each channel's history holds. const BUFFER: usize = DECODE_BUFFER_SIZE + OVERLAP; -const TRIM_ICDF: [u8; 11] = [126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0]; -const SPREAD_ICDF: [u8; 4] = [25, 23, 2, 0]; -const TAPSET_ICDF: [u8; 3] = [2, 1, 0]; - -/// Time-frequency resolution changes, indexed by LM and then by -/// `4 * transient + 2 * tf_select + per_band_flag`. -const TF_SELECT_TABLE: [[i8; 8]; 4] = [ - [0, -1, 0, -1, 0, -1, 0, -1], - [0, -1, 0, -2, 1, 0, 1, -1], - [0, -2, 0, -3, 2, 0, 1, -1], - [0, -2, 0, -3, 3, 0, 1, -1], -]; - /// How the last frame was produced, which decides how the next loss conceals. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum FrameType { @@ -52,14 +38,6 @@ enum FrameType { PlcPeriodic, } -/// The pitch postfilter's parameters for one frame. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -struct Postfilter { - period: usize, - gain: f32, - tapset: usize, -} - /// A CELT decoder for one or two channels in the standard 48 kHz mode. pub(crate) struct Decoder { channels: usize, @@ -76,8 +54,8 @@ pub(crate) struct Decoder { plc_duration: i32, last_frame_type: FrameType, skip_plc: bool, - postfilter: Postfilter, - postfilter_old: Postfilter, + postfilter: comb::Filter, + postfilter_old: comb::Filter, prefilter_and_fold: bool, preemph_mem: [f32; 2], /// Each channel's output history, then the MDCT overlap. @@ -123,8 +101,8 @@ impl Decoder { plc_duration: 0, last_frame_type: FrameType::None, skip_plc: true, - postfilter: Postfilter::default(), - postfilter_old: Postfilter::default(), + postfilter: comb::Filter::default(), + postfilter_old: comb::Filter::default(), prefilter_and_fold: false, preemph_mem: [0.0; 2], decode_mem: [[0.0; BUFFER]; 2], @@ -146,8 +124,8 @@ impl Decoder { self.plc_duration = 0; self.last_frame_type = FrameType::None; self.skip_plc = true; - self.postfilter = Postfilter::default(); - self.postfilter_old = Postfilter::default(); + self.postfilter = comb::Filter::default(); + self.postfilter_old = comb::Filter::default(); self.prefilter_and_fold = false; self.preemph_mem = [0.0; 2]; self.decode_mem = [[0.0; BUFFER]; 2]; @@ -250,7 +228,7 @@ impl Decoder { dec.skip_to_end(); } - let mut postfilter = Postfilter::default(); + let mut postfilter = comb::Filter::default(); if start == 0 && tell + 16 <= total_bits { if dec.bit_logp(1) { let octave = dec.uint(6); @@ -330,7 +308,17 @@ impl Decoder { }; bits -= anti_collapse_rsv; - let alloc = rate::compute_allocation(start, end, &offsets, &cap, alloc_trim, bits, c, lm, dec); + let alloc = rate::compute_allocation( + start, + end, + &offsets, + &cap, + alloc_trim, + bits, + c, + lm, + rate::Signal::Decode(dec), + ); energy::unquant_fine(start, end, &mut self.old_band_e, &alloc.fine_quant, dec, c); for mem in &mut self.decode_mem[..cc] { @@ -354,7 +342,8 @@ impl Decoder { x, y: (c == 2).then_some(y), }; - let collapse_masks = bands::quant_all_bands(&coding, &alloc, channels, dec, &mut self.rng); + let collapse_masks = + bands::quant_all_bands(&coding, &alloc, channels, bands::Direction::Decode(dec), &mut self.rng); let anti_collapse_on = anti_collapse_rsv > 0 && dec.bits(1) != 0; let bits_left = len * 8 - dec.tell() as i32; @@ -515,7 +504,7 @@ impl Decoder { /// Run the pitch postfilter over the frame's `n` new samples, cross-fading from the old /// parameters to the current ones in the first block and to `next` in the rest. - fn postfilter_frame(&mut self, n: usize, lm: usize, next: Postfilter) { + fn postfilter_frame(&mut self, n: usize, lm: usize, next: comb::Filter) { let out_start = DECODE_BUFFER_SIZE - n; self.postfilter.period = self.postfilter.period.max(COMBFILTER_MINPERIOD); self.postfilter_old.period = self.postfilter_old.period.max(COMBFILTER_MINPERIOD); @@ -552,11 +541,11 @@ impl Decoder { /// re-applies it after the MDCT overlap, and simulate TDAC on the concealed audio so it /// blends with the next frame's MDCT. fn prefilter_and_fold(&mut self, n: usize) { - let old = Postfilter { + let old = comb::Filter { gain: -self.postfilter_old.gain, ..self.postfilter_old }; - let new = Postfilter { + let new = comb::Filter { gain: -self.postfilter.gain, ..self.postfilter }; @@ -836,105 +825,3 @@ fn tf_decode(start: usize, end: usize, transient: bool, lm: usize, dec: &mut ran } tf_res } - -/// The comb filter's taps for each tapset. -const COMB_GAINS: [[f32; 3]; 3] = [ - [0.306_640_63, 0.217_041_02, 0.129_638_67], - [0.463_867_2, 0.268_066_4, 0.0], - [0.799_804_7, 0.100_097_656, 0.0], -]; - -/// Filter `n` samples of `buf` from `at` with a three-tap comb at the pitch period, -/// cross-fading from `old` to `new` over the window's overlap (none without a window). -/// -/// Without `out` it filters in place, so later taps read already filtered samples, as -/// libopus's in-place call does; with it, the result goes there and `buf` is unchanged. -fn comb_filter( - buf: &mut [f32], - at: usize, - mut out: Option<&mut [f32]>, - n: usize, - old: Postfilter, - new: Postfilter, - window: Option<&[f32; OVERLAP]>, -) { - let in_place = out.is_none(); - let mut write = |buf: &mut [f32], i: usize, value: f32| match out.as_deref_mut() { - Some(out) => out[i] = value, - None => buf[at + i] = value, - }; - if old.gain == 0.0 && new.gain == 0.0 { - if !in_place { - for i in 0..n { - let value = buf[at + i]; - write(buf, i, value); - } - } - return; - } - // A zero gain comes with a zero period, which needs to be at least 2 to read real data. - let t0 = old.period.max(COMBFILTER_MINPERIOD); - let t1 = new.period.max(COMBFILTER_MINPERIOD); - let g00 = old.gain * COMB_GAINS[old.tapset][0]; - let g01 = old.gain * COMB_GAINS[old.tapset][1]; - let g02 = old.gain * COMB_GAINS[old.tapset][2]; - let g10 = new.gain * COMB_GAINS[new.tapset][0]; - let g11 = new.gain * COMB_GAINS[new.tapset][1]; - let g12 = new.gain * COMB_GAINS[new.tapset][2]; - let x = |buf: &[f32], i: usize, back: usize| buf[at + i - back]; - let mut x1 = buf[at + 1 - t1]; - let mut x2 = buf[at - t1]; - let mut x3 = buf[at - t1 - 1]; - let mut x4 = buf[at - t1 - 2]; - // An unchanged filter needs no cross-fade. - let overlap = match window { - Some(_) if old.gain == new.gain && t0 == t1 && old.tapset == new.tapset => 0, - Some(_) => OVERLAP, - None => 0, - }; - let mut i = 0; - if let Some(window) = window { - while i < overlap { - let x0 = buf[at + i + 2 - t1]; - let f = window[i] * window[i]; - let value = buf[at + i] - + (1.0 - f) * g00 * x(buf, i, t0) - + (1.0 - f) * g01 * (buf[at + i + 1 - t0] + x(buf, i, t0 + 1)) - + (1.0 - f) * g02 * (buf[at + i + 2 - t0] + x(buf, i, t0 + 2)) - + f * g10 * x2 - + f * g11 * (x1 + x3) - + f * g12 * (x0 + x4); - write(buf, i, value); - x4 = x3; - x3 = x2; - x2 = x1; - x1 = x0; - i += 1; - } - } - if new.gain == 0.0 { - if !in_place { - for i in overlap..n { - let value = buf[at + i]; - write(buf, i, value); - } - } - return; - } - - // The constant filter, which rereads its history from the current position. - let mut x4 = buf[at + i - t1 - 2]; - let mut x3 = buf[at + i - t1 - 1]; - let mut x2 = buf[at + i - t1]; - let mut x1 = buf[at + i + 1 - t1]; - while i < n { - let x0 = buf[at + i + 2 - t1]; - let value = buf[at + i] + g10 * x2 + g11 * (x1 + x3) + g12 * (x0 + x4); - write(buf, i, value); - x4 = x3; - x3 = x2; - x2 = x1; - x1 = x0; - i += 1; - } -} diff --git a/kodecs-opus/src/safe/celt/encoder/analysis.rs b/kodecs-opus/src/safe/celt/encoder/analysis.rs new file mode 100644 index 00000000..29973b22 --- /dev/null +++ b/kodecs-opus/src/safe/celt/encoder/analysis.rs @@ -0,0 +1,916 @@ +//! The encoder's signal analysis: transients, tones, time-frequency resolution, allocation +//! trim, stereo, dynamic allocation, and the VBR target, from libopus's celt/celt_encoder.c. +//! Copyright (c) 2007-2008 CSIRO, 2007-2010 Xiph.Org Foundation, and 2008 Gregory Maxwell. + +use std::f64::consts::PI; + +use super::super::bands::haar1; +use super::super::energy::E_MEANS; +use super::super::math; +use super::super::pitch::inner_prod; +use super::super::rate; +use super::super::tables::{EBANDS, LOG_N, TF_SELECT_TABLE}; +use super::super::{BANDS, MAX_FRAME, OVERLAP}; +use super::{Analysis, BITRES, LEAK_BANDS}; + +/// libopus's `EPSILON` in a float build. +const EPSILON: f32 = 1e-15; + +/// What the time-domain transient detector found. +pub(super) struct Transient { + pub transient: bool, + /// A transient too weak to code as one at low bitrates, which time-frequency resolution + /// handles instead. + pub weak: bool, + /// How strong the transient is, from 0 up to about 1, boosting VBR. + pub tf_estimate: f32, + /// The channel with the strongest transient. + pub tf_chan: usize, +} + +/// Look for transients in each of the `channels` runs of `len` samples in `input`, from the +/// ratio of the frame's energy to the harmonic mean of its masking threshold. +pub(super) fn transient_analysis( + input: &[f32], + len: usize, + channels: usize, + allow_weak_transients: bool, + tone_freq: f32, + toneishness: f32, +) -> Transient { + // 6*64/x, trained on real data to minimize the average error. + const INV_TABLE: [u8; 128] = [ + 255, 255, 156, 110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25, 23, 22, 21, 20, 19, 18, 17, 16, 16, 15, 15, + 14, 13, 13, 12, 12, 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, + ]; + // Forward masking of 6.7 dB/ms, or 3.3 dB/ms at low bitrates, where coding transients + // risks unstable energy and partial collapse. + let forward_decay: f32 = if allow_weak_transients { 0.03125 } else { 0.0625 }; + let len2 = len / 2; + let mut tmp = [0.0f32; MAX_FRAME + OVERLAP]; + let mut mask_metric = 0; + let mut tf_chan = 0; + for c in 0..channels { + // High-pass filter: (1 - 2*z^-1 + z^-2) / (1 - z^-1 + .5*z^-2). + let (mut mem0, mut mem1) = (0.0f32, 0.0f32); + for (t, &x) in tmp.iter_mut().zip(&input[c * len..(c + 1) * len]) { + let y = mem0 + x; + let mem00 = mem0; + mem0 = mem0 - x + 0.5 * mem1; + mem1 = x - mem00; + *t = y; + } + // The first few samples are bad, as the memory starts empty. + tmp[..12].fill(0.0); + + // The post-echo threshold, grouping samples by two. + let mut mean = 0.0f32; + let mut mem0 = 0.0f32; + for i in 0..len2 { + let x2 = tmp[2 * i] * tmp[2 * i] + tmp[2 * i + 1] * tmp[2 * i + 1]; + mean += x2; + mem0 = x2 + (1.0 - forward_decay) * mem0; + tmp[i] = forward_decay * mem0; + } + // The pre-echo threshold, from backward masking of 13.9 dB/ms. + let mut mem0 = 0.0f32; + let mut max_e = 0.0f32; + for t in tmp[..len2].iter_mut().rev() { + mem0 = *t + 0.875 * mem0; + *t = 0.125 * mem0; + max_e = math::max(max_e, 0.125 * mem0); + } + + // The frame energy is the geometric mean of the energy and half the max. + let mean = (f64::from(mean * max_e) * 0.5 * len2 as f64).sqrt() as f32; + let norm = len2 as f32 / (EPSILON + mean); + // The harmonic mean of the threshold over a quarter of the samples, skipping the + // unreliable edges. + let mut unmask = 0; + for &t in tmp[12..len2 - 5].iter().step_by(4) { + let id = f64::from(64.0 * norm * (t + EPSILON)).floor().clamp(0.0, 127.0) as usize; + unmask += i32::from(INV_TABLE[id]); + } + // Compensate for the quarter of the samples and the table's factor of six. + let unmask = 64 * unmask * 4 / (6 * (len2 as i32 - 17)); + if unmask > mask_metric { + tf_chan = c; + mask_metric = unmask; + } + } + let mut transient = mask_metric > 200; + // Don't mistake a partial cycle of a very low tone for a transient. + if toneishness > 0.98 && tone_freq < 0.026 { + transient = false; + mask_metric = 0; + } + let mut weak = false; + if allow_weak_transients && transient && mask_metric < 600 { + transient = false; + weak = true; + } + let tf_max = math::max(0.0, f64::from(27 * mask_metric).sqrt() as f32 - 42.0); + let tf_estimate = f64::from(0.0069f32 * math::min(163.0, tf_max)) - 0.139; + let tf_estimate = (if 0.0 > tf_estimate { 0.0 } else { tf_estimate }).sqrt() as f32; + Transient { + transient, + weak, + tf_estimate, + tf_chan, + } +} + +/// Whether the band energies `new_e` rose suddenly over `old_e`, a transient the time-domain +/// detector missed. +pub(super) fn patch_transient_decision( + new_e: &[f32; 2 * BANDS], + old_e: &[f32; 2 * BANDS], + start: usize, + end: usize, + channels: usize, +) -> bool { + // Spread the old energy aggressively, -6 dB/Bark, to ignore irrelevant bands. + let mut spread_old = [0.0f32; BANDS]; + let old = |i: usize| { + if channels == 1 { + old_e[i] + } else { + math::max(old_e[i], old_e[i + BANDS]) + } + }; + spread_old[start] = old(start); + for i in start + 1..end { + spread_old[i] = math::max(spread_old[i - 1] - 1.0, old(i)); + } + for i in (start..end - 1).rev() { + spread_old[i] = math::max(spread_old[i], spread_old[i + 1] - 1.0); + } + // The mean increase. + let first = start.max(2); + let mut mean_diff = 0.0f32; + for c in 0..channels { + for i in first..end - 1 { + let x1 = math::max(0.0, new_e[i + c * BANDS]); + let x2 = math::max(0.0, spread_old[i]); + mean_diff += math::max(0.0, x1 - x2); + } + } + mean_diff /= (channels * (end - 1 - first)) as f32; + mean_diff > 1.0 +} + +/// A least-squares fit of a two-tap predictor at `delay`, forward and backward, or none when +/// the system is ill-conditioned. +fn tone_lpc(x: &[f32], delay: usize) -> Option<[f32; 2]> { + let len = x.len(); + assert!(len > 2 * delay, "{len} samples for delay {delay}"); + // The correlations of the forward covariance method. + let (mut r00, mut r01, mut r02) = (0.0f32, 0.0f32, 0.0f32); + for i in 0..len - 2 * delay { + r00 += x[i] * x[i]; + r01 += x[i] * x[i + delay]; + r02 += x[i] * x[i + 2 * delay]; + } + let mut edges = 0.0f32; + for i in 0..delay { + edges += x[len + i - 2 * delay] * x[len + i - 2 * delay] - x[i] * x[i]; + } + let r11 = r00 + edges; + let mut edges = 0.0f32; + for i in 0..delay { + edges += x[len + i - delay] * x[len + i - delay] - x[i + delay] * x[i + delay]; + } + let r22 = r11 + edges; + let mut edges = 0.0f32; + for i in 0..delay { + edges += x[len + i - 2 * delay] * x[len + i - delay] - x[i] * x[i + delay]; + } + let r12 = r01 + edges; + // Add the reversed, backward contribution. + let (r00, r01, r11, r02, r12) = (r00 + r22, r01 + r12, 2.0 * r11, 2.0 * r02, r12 + r01); + + // Solve [r00, r01; r01, r11] * lpc = [r02; r12]. + let den = r00 * r11 - r01 * r01; + if den < 0.001 * (r00 * r11) { + return None; + } + let num1 = r02 * r11 - r01 * r12; + let lpc1 = if num1 >= den { + 1.0 + } else if num1 <= -den { + -1.0 + } else { + num1 / den + }; + let num0 = r00 * r12 - r02 * r01; + let lpc0 = if 0.5 * num0 >= den { + 1.999999 + } else if 0.5 * num0 <= -den { + -1.999999 + } else { + num0 / den + }; + Some([lpc0, lpc1]) +} + +/// Detect a pure or nearly pure tone in the `channels` runs of `n` samples in `input`, +/// returning its frequency in radians per sample (or -1) and how pure it is. +pub(super) fn tone_detect(input: &[f32], channels: usize, n: usize) -> (f32, f32) { + let mut x = [0.0f32; MAX_FRAME + OVERLAP]; + let x = &mut x[..n]; + if channels == 2 { + for (i, x) in x.iter_mut().enumerate() { + *x = input[i] + input[i + n]; + } + } else { + x.copy_from_slice(&input[..n]); + } + let mut delay = 1; + let mut lpc = tone_lpc(x, delay); + // When the filter resonates too close to DC, retry downsampled. + while delay <= 48000 / 3000 && lpc.is_none_or(|[lpc0, lpc1]| lpc0 > 1.0 && lpc1 < 0.0) { + delay *= 2; + lpc = tone_lpc(x, delay); + } + match lpc { + // A filter with complex roots, whose squared radius is -lpc[1]. + Some([lpc0, lpc1]) if f64::from(lpc0 * lpc0) + 3.999999 * f64::from(lpc1) < 0.0 => { + ((f64::from(0.5 * lpc0).acos() / delay as f64) as f32, -lpc1) + } + _ => (-1.0, 0.0), + } +} + +/// The L1 norm of `tmp`, biased towards frequency resolution by `lm`. +fn l1_metric(tmp: &[f32], lm: i32, bias: f32) -> f32 { + let mut l1 = 0.0f32; + for &x in tmp { + l1 += x.abs(); + } + l1 + (lm as f32 * bias) * l1 +} + +/// Choose each band's time-frequency resolution change by comparing the L1 norms of its Haar +/// transforms, smoothed by a Viterbi search costing each change `lambda`, into `tf_res`. +/// Returns the table selector. +#[allow( + clippy::too_many_arguments, + reason = "mirrors libopus's tf_analysis, which the encoder calls once" +)] +pub(super) fn tf_analysis( + len: usize, + transient: bool, + tf_res: &mut [i32; BANDS], + lambda: i32, + x: &[f32], + n0: usize, + lm: usize, + tf_estimate: f32, + tf_chan: usize, + importance: &[i32; BANDS], +) -> usize { + let lm_i = lm as i32; + let bias = 0.04 * math::max(-0.25, 0.5 - tf_estimate); + let mut metric = [0i32; BANDS]; + for i in 0..len { + let n = (rate::band_width(i) as usize) << lm; + // Too narrow to split down to LM -1. + let narrow = rate::band_width(i) == 1; + let mut tmp = [0.0f32; 22 << super::super::MAX_LM]; + let tmp = &mut tmp[..n]; + let first = tf_chan * n0 + ((EBANDS[i] as usize) << lm); + tmp.copy_from_slice(&x[first..first + n]); + let mut best_l1 = l1_metric(tmp, if transient { lm_i } else { 0 }, bias); + let mut best_level = 0; + // The -1 case, for transients. + if transient && !narrow { + let mut tmp1 = [0.0f32; 22 << super::super::MAX_LM]; + let tmp1 = &mut tmp1[..n]; + tmp1.copy_from_slice(tmp); + haar1(tmp1, n >> lm, 1 << lm); + let l1 = l1_metric(tmp1, lm_i + 1, bias); + if l1 < best_l1 { + best_l1 = l1; + best_level = -1; + } + } + let levels = lm_i + i32::from(!(transient || narrow)); + for k in 0..levels { + let b = if transient { lm_i - k - 1 } else { k + 1 }; + haar1(tmp, n >> k, 1 << k); + let l1 = l1_metric(tmp, b, bias); + if l1 < best_l1 { + best_l1 = l1; + best_level = k + 1; + } + } + // In Q1, to select the midpoint for narrow bands. + metric[i] = if transient { 2 * best_level } else { -2 * best_level }; + // Bands that can't split to -1 take the halfway point, so as not to bias the decision. + if narrow && (metric[i] == 0 || metric[i] == -2 * lm_i) { + metric[i] -= 1; + } + } + + let row = &TF_SELECT_TABLE[lm]; + let t = 4 * usize::from(transient); + let cost = + |i: usize, sel: usize, res: usize| importance[i] * (metric[i] - 2 * i32::from(row[t + 2 * sel + res])).abs(); + let first_lambda = if transient { 0 } else { lambda }; + // Search for the optimal resolution with each table selector. + let mut selcost = [0; 2]; + for (sel, selcost) in selcost.iter_mut().enumerate() { + let mut cost0 = cost(0, sel, 0); + let mut cost1 = cost(0, sel, 1) + first_lambda; + for i in 1..len { + let curr0 = cost0.min(cost1 + lambda); + let curr1 = (cost0 + lambda).min(cost1); + cost0 = curr0 + cost(i, sel, 0); + cost1 = curr1 + cost(i, sel, 1); + } + *selcost = cost0.min(cost1); + } + // Only transients use the second selector, to be conservative. + let tf_select = usize::from(selcost[1] < selcost[0] && transient); + + // The Viterbi forward pass. + let mut path0 = [0i32; BANDS]; + let mut path1 = [0i32; BANDS]; + let mut cost0 = cost(0, tf_select, 0); + let mut cost1 = cost(0, tf_select, 1) + first_lambda; + for i in 1..len { + let (from0, from1) = (cost0, cost1 + lambda); + let curr0 = if from0 < from1 { + path0[i] = 0; + from0 + } else { + path0[i] = 1; + from1 + }; + let (from0, from1) = (cost0 + lambda, cost1); + let curr1 = if from0 < from1 { + path1[i] = 0; + from0 + } else { + path1[i] = 1; + from1 + }; + cost0 = curr0 + cost(i, tf_select, 0); + cost1 = curr1 + cost(i, tf_select, 1); + } + tf_res[len - 1] = i32::from(cost0 >= cost1); + // The backward pass. + for i in (0..len - 1).rev() { + tf_res[i] = if tf_res[i + 1] == 1 { path1[i + 1] } else { path0[i + 1] }; + } + tf_select +} + +/// Choose the allocation trim, tilting bits towards low or high bands, from the inter-channel +/// correlation and spectral tilt. Updates the stereo saving estimate. +#[allow( + clippy::too_many_arguments, + reason = "mirrors libopus's alloc_trim_analysis, which the encoder calls once" +)] +pub(super) fn alloc_trim_analysis( + x: &[f32], + band_log_e: &[f32; 2 * BANDS], + end: usize, + lm: usize, + channels: usize, + n0: usize, + analysis: Option<&Analysis>, + stereo_saving: &mut f32, + tf_estimate: f32, + intensity: usize, + equiv_rate: i32, +) -> i32 { + // Lower trims help at low bitrates; at higher ones, it's less clear. + let mut trim: f32 = if equiv_rate < 64000 { + 4.0 + } else if equiv_rate < 80000 { + let frac = (equiv_rate - 64000) >> 10; + 4.0 + (1.0 / 16.0) * frac as f32 + } else { + 5.0 + }; + if channels == 2 { + let band = |i: usize| (EBANDS[i] as usize) << lm..(EBANDS[i + 1] as usize) << lm; + let correlation = |i: usize| { + let bins = band(i); + inner_prod(&x[bins.clone()], &x[n0 + bins.start..n0 + bins.end]) + }; + // The inter-channel correlation of the low frequencies. + let mut sum = 0.0f32; + for i in 0..8 { + sum += correlation(i); + } + sum *= 1.0 / 8.0; + sum = math::min(1.0, sum.abs()); + let mut min_xc = sum; + for i in 8..intensity { + min_xc = math::min(min_xc, correlation(i).abs()); + } + min_xc = math::min(1.0, min_xc.abs()); + // Mid-side savings estimated from the low-frequency average and the minimum. + let log_xc = math::log2(1.001 - sum * sum); + let log_xc2 = math::max(0.5 * log_xc, math::log2(1.001 - min_xc * min_xc)); + trim += math::max(-4.0, 0.75 * log_xc); + *stereo_saving = math::min(*stereo_saving + 0.25, -(0.5 * log_xc2)); + } + + // The spectral tilt. + let mut diff = 0.0f32; + for c in 0..channels { + for i in 0..end - 1 { + diff += band_log_e[i + c * BANDS] * (2 + 2 * i as i32 - end as i32) as f32; + } + } + diff /= (channels * (end - 1)) as f32; + trim -= math::max(-2.0, math::min(2.0, (diff + 1.0) / 6.0)); + trim -= 2.0 * tf_estimate; + if let Some(analysis) = analysis { + trim -= math::max(-2.0, math::min(2.0, 2.0 * (analysis.tonality_slope + 0.05))); + } + math::floor_int(0.5 + trim).clamp(0, 10) +} + +/// Whether to code stereo as mid and side, from whether it has a smaller L1 norm than left +/// and right in the bands below 13. +pub(super) fn stereo_analysis(x: &[f32], lm: usize, n0: usize) -> bool { + let mut sum_lr = EPSILON; + let mut sum_ms = EPSILON; + for j in 0..(EBANDS[13] as usize) << lm { + let l = x[j]; + let r = x[n0 + j]; + let m = l + r; + let s = l - r; + sum_lr += l.abs() + r.abs(); + sum_ms += m.abs() + s.abs(); + } + #[allow(clippy::approx_constant, reason = "libopus's literal, which rounds differently")] + let half_sqrt_2 = 0.707107f32; + sum_ms *= half_sqrt_2; + // Bands below 8 need no angles at LM 1 and below. + let thetas = if lm <= 1 { 13 - 8 } else { 13 }; + let bins = i32::from(EBANDS[13]) << (lm + 1); + (bins + thetas) as f32 * sum_ms > bins as f32 * sum_lr +} + +fn median_of_5(x: &[f32]) -> f32 { + let t2 = x[2]; + let (mut t0, mut t1) = if x[0] > x[1] { (x[1], x[0]) } else { (x[0], x[1]) }; + let (mut t3, mut t4) = if x[3] > x[4] { (x[4], x[3]) } else { (x[3], x[4]) }; + if t0 > t3 { + std::mem::swap(&mut t0, &mut t3); + std::mem::swap(&mut t1, &mut t4); + } + if t2 > t1 { + if t1 < t3 { + math::min(t2, t3) + } else { + math::min(t4, t1) + } + } else if t2 < t3 { + math::min(t1, t3) + } else { + math::min(t2, t4) + } +} + +fn median_of_3(x: &[f32]) -> f32 { + let (t0, t1) = if x[0] > x[1] { (x[1], x[0]) } else { (x[0], x[1]) }; + let t2 = x[2]; + if t1 < t2 { + t1 + } else if t0 < t2 { + t2 + } else { + t0 + } +} + +/// What dynamic allocation analysis reads. +pub(super) struct Dynalloc<'a> { + pub band_log_e: &'a [f32; 2 * BANDS], + /// Band energies from the long MDCT, compensated for short blocks. + pub band_log_e2: &'a [f32; 2 * BANDS], + pub old_band_e: &'a [f32; 2 * BANDS], + pub start: usize, + pub end: usize, + pub channels: usize, + pub lsb_depth: u32, + pub transient: bool, + pub vbr: bool, + pub constrained_vbr: bool, + pub lm: usize, + pub effective_bytes: i32, + pub analysis: Option<&'a Analysis>, + pub tone_freq: f32, + pub toneishness: f32, +} + +/// What dynamic allocation analysis decides. +pub(super) struct Boosts { + /// Each band's boost, in boost quanta. + pub offsets: [i32; BANDS], + /// How much each band's resolution matters, for the time-frequency search. + pub importance: [i32; BANDS], + /// How much each band counts towards the spreading decision. + pub spread_weight: [i32; BANDS], + /// The largest band energy above the noise floor. + pub max_depth: f32, + /// The boosts' total, in eighth bits. + pub tot_boost: i32, +} + +/// Boost bands that stand out of a smoothed spectral envelope, where the allocation alone +/// would starve them, and weigh bands for spreading and time-frequency analysis. +pub(super) fn dynalloc_analysis(d: &Dynalloc) -> Boosts { + let &Dynalloc { + band_log_e, + band_log_e2, + old_band_e, + start, + end, + channels, + lsb_depth, + transient, + vbr, + constrained_vbr, + lm, + effective_bytes, + analysis, + tone_freq, + toneishness, + } = d; + let mut boosts = Boosts { + offsets: [0; BANDS], + importance: [0; BANDS], + spread_weight: [0; BANDS], + max_depth: -31.9, + tot_boost: 0, + }; + // The noise floor counts the means, the depth, the band widths, and the preemphasis, + // about the square of the Bark band. + let mut noise_floor = [0.0f32; BANDS]; + for (i, floor) in noise_floor.iter_mut().enumerate().take(end) { + *floor = 0.0625 * f32::from(LOG_N[i]) + 0.5 + (9 - lsb_depth as i32) as f32 - E_MEANS[i] + + 0.0062 * (i + 5) as f32 * (i + 5) as f32; + } + for c in 0..channels { + for i in 0..end { + boosts.max_depth = math::max(boosts.max_depth, band_log_e[c * BANDS + i] - noise_floor[i]); + } + } + + // A simple masking model, to ignore fully masked bands in the spreading decision. + { + let mut mask = [0.0f32; BANDS]; + for i in 0..end { + mask[i] = band_log_e[i] - noise_floor[i]; + } + if channels == 2 { + for i in 0..end { + mask[i] = math::max(mask[i], band_log_e[BANDS + i] - noise_floor[i]); + } + } + let sig = mask; + for i in 1..end { + mask[i] = math::max(mask[i], mask[i - 1] - 2.0); + } + for i in (0..end - 1).rev() { + mask[i] = math::max(mask[i], mask[i + 1] - 3.0); + } + for i in 0..end { + // The mask is never more than 72 dB below the peak, nor below the noise floor. + let smr = sig[i] - math::max(math::max(0.0, boosts.max_depth - 12.0), mask[i]); + let shift = 5.min(0.max(-math::floor_int(0.5 + smr))); + boosts.spread_weight[i] = 32 >> shift; + } + } + + // Keep dynamic allocation from busting the budget: it starts at 24 kb/s for 20 ms frames + // and 96 kb/s for 2.5 ms ones. + if effective_bytes < 30 + 5 * lm as i32 { + boosts.importance[start..end].fill(13); + return boosts; + } + let mut follower = [0.0f32; 2 * BANDS]; + // The last band at least 3 dB above the one before, past which band-limited signals + // would cause trouble. + let mut last = 0; + for c in 0..channels { + let mut e3 = [0.0f32; BANDS]; + e3[..end].copy_from_slice(&band_log_e2[c * BANDS..c * BANDS + end]); + if lm == 0 { + // 2.5 ms frames' first 8 bands have one bin, so take the previous energy too. + for i in 0..8.min(end) { + e3[i] = math::max(band_log_e2[c * BANDS + i], old_band_e[c * BANDS + i]); + } + } + let f = &mut follower[c * BANDS..c * BANDS + BANDS]; + f[0] = e3[0]; + for i in 1..end { + if e3[i] > e3[i - 1] + 0.5 { + last = i; + } + f[i] = math::min(f[i - 1] + 1.5, e3[i]); + } + for i in (0..last).rev() { + f[i] = math::min(f[i], math::min(f[i + 1] + 2.0, e3[i])); + } + // Combine with a median filter so dynamic allocation doesn't trigger needlessly; the + // offset keeps it conservative. + let offset = 1.0; + for i in 2..end - 2 { + f[i] = math::max(f[i], median_of_5(&e3[i - 2..]) - offset); + } + let tmp = median_of_3(&e3[..]) - offset; + f[0] = math::max(f[0], tmp); + f[1] = math::max(f[1], tmp); + let tmp = median_of_3(&e3[end - 3..]) - offset; + f[end - 2] = math::max(f[end - 2], tmp); + f[end - 1] = math::max(f[end - 1], tmp); + for i in 0..end { + f[i] = math::max(f[i], noise_floor[i]); + } + } + if channels == 2 { + for i in start..end { + // Allow 24 dB of cross-talk. + follower[BANDS + i] = math::max(follower[BANDS + i], follower[i] - 4.0); + follower[i] = math::max(follower[i], follower[BANDS + i] - 4.0); + follower[i] = 0.5 + * (math::max(0.0, band_log_e[i] - follower[i]) + + math::max(0.0, band_log_e[BANDS + i] - follower[BANDS + i])); + } + } else { + for i in start..end { + follower[i] = math::max(0.0, band_log_e[i] - follower[i]); + } + } + // No surround masking: its dynamic allocation is zero. + for f in &mut follower[start..end] { + *f = math::max(*f, 0.0); + } + for (importance, &f) in boosts.importance[start..end].iter_mut().zip(&follower[start..end]) { + *importance = math::floor_int(0.5 + 13.0 * math::exp2(math::min(f, 4.0))); + } + // Halve the boost for non-transient CBR and CVBR frames. + if (!vbr || constrained_vbr) && !transient { + for f in &mut follower[start..end] { + *f *= 0.5; + } + } + for (i, f) in follower.iter_mut().enumerate().take(end).skip(start) { + if i < 8 { + *f *= 2.0; + } + if i >= 12 { + *f *= 0.5; + } + } + // Compensate for Opus under-allocating tones. + if toneishness > 0.98 { + let freq_bin = (0.5 + f64::from(tone_freq * 120.0) / PI).floor() as i32; + let band = |i: usize| i32::from(EBANDS[i]); + for (i, f) in follower.iter_mut().enumerate().take(end).skip(start) { + let near = |margin: i32| freq_bin >= band(i) - margin && freq_bin <= band(i + 1) + margin; + if near(0) { + *f += 2.0; + } + if near(1) { + *f += 1.0; + } + if near(2) { + *f += 1.0; + } + if near(3) { + *f += 0.5; + } + } + if freq_bin >= band(end) { + follower[end - 1] += 2.0; + follower[end - 2] += 1.0; + } + } + if let Some(analysis) = analysis { + let leak = start.min(LEAK_BANDS)..end.min(LEAK_BANDS); + for (f, &boost) in follower[leak.clone()].iter_mut().zip(&analysis.leak_boost[leak]) { + *f += (1.0 / 64.0) * f32::from(boost); + } + } + let c = channels as i32; + for (i, &f) in follower.iter().enumerate().take(end).skip(start) { + let f = math::min(f, 4.0); + let width = (c * rate::band_width(i)) << lm; + let (boost, boost_bits) = if width < 6 { + let boost = f as i32; + (boost, (boost * width) << BITRES) + } else if width > 48 { + let boost = (f * 8.0) as i32; + (boost, ((boost * width) << BITRES) / 8) + } else { + let boost = (f * width as f32 / 6.0) as i32; + (boost, (boost * 6) << BITRES) + }; + // Limit CBR and non-transient CVBR boosts to 2/3 of the bits. + if (!vbr || (constrained_vbr && !transient)) + && (boosts.tot_boost + boost_bits) >> BITRES >> 3 > 2 * effective_bytes / 3 + { + let cap = (2 * effective_bytes / 3) << BITRES << 3; + boosts.offsets[i] = cap - boosts.tot_boost; + boosts.tot_boost = cap; + break; + } + boosts.offsets[i] = boost; + boosts.tot_boost += boost_bits; + } + boosts +} + +/// What the VBR target reads. +pub(super) struct Vbr<'a> { + pub analysis: Option<&'a Analysis>, + /// The target before analysis, in eighth bits. + pub base_target: i32, + pub lm: usize, + /// The equivalent bitrate. + pub bitrate: i32, + pub last_coded_bands: usize, + pub channels: usize, + pub intensity: usize, + pub constrained_vbr: bool, + pub stereo_saving: f32, + pub tot_boost: i32, + pub tf_estimate: f32, + pub pitch_change: bool, + pub max_depth: f32, + pub temporal_vbr: f32, +} + +/// The VBR target in eighth bits, from the base target adjusted for activity, stereo savings, +/// dynamic allocation, transients, tonality, depth, and temporal variation. +pub(super) fn compute_vbr(v: &Vbr) -> i32 { + let &Vbr { + analysis, + base_target, + lm, + bitrate, + last_coded_bands, + channels, + intensity, + constrained_vbr, + stereo_saving, + tot_boost, + tf_estimate, + pitch_change, + max_depth, + temporal_vbr, + } = v; + let coded_bands = if last_coded_bands != 0 { last_coded_bands } else { BANDS }; + let mut coded_bins = i32::from(EBANDS[coded_bands]) << lm; + if channels == 2 { + coded_bins += i32::from(EBANDS[intensity.min(coded_bands)]) << lm; + } + let mut target = base_target; + if let Some(analysis) = analysis { + if f64::from(analysis.activity) < 0.4 { + target -= ((coded_bins << BITRES) as f32 * (0.4 - analysis.activity)) as i32; + } + } + // Stereo savings. + if channels == 2 { + let coded_stereo_bands = intensity.min(coded_bands); + let coded_stereo_dof = (i32::from(EBANDS[coded_stereo_bands]) << lm) - coded_stereo_bands as i32; + // The most bits a mono signal could save. + let max_frac = 0.8 * coded_stereo_dof as f32 / coded_bins as f32; + let stereo_saving = math::min(stereo_saving, 1.0); + target -= math::min( + max_frac * target as f32, + (stereo_saving - 0.1) * (coded_stereo_dof << BITRES) as f32, + ) as i32; + } + // Boost for dynamic allocation, less its average. + target += tot_boost - (19 << lm); + // Boost transients, less their average. + let tf_calibration = 0.044f32; + target += ((tf_estimate - tf_calibration) * target as f32) as i32; + // Boost tonality, less its average. + if let Some(analysis) = analysis { + let tonal = math::max(0.0, analysis.tonality - 0.15) - 0.12; + let mut tonal_target = target + ((coded_bins << BITRES) as f32 * 1.2 * tonal) as i32; + if pitch_change { + tonal_target += ((coded_bins << BITRES) as f32 * 0.8) as i32; + } + target = tonal_target; + } + { + let bins = i32::from(EBANDS[BANDS - 2]) << lm; + let floor_depth = ((((channels as i32) * bins) << BITRES) as f32 * max_depth) as i32; + let floor_depth = floor_depth.max(target >> 2); + target = target.min(floor_depth); + } + // Constrained VBR can't hold a higher rate for long, so stay closer to the base. + if constrained_vbr { + target = base_target + (0.67 * (target - base_target) as f32) as i32; + } + if tf_estimate < 0.2 { + let amount = 0.0000031 * (96000 - bitrate).clamp(0, 32000) as f32; + let tvbr_factor = temporal_vbr * amount; + target += (tvbr_factor * target as f32) as i32; + } + // Never more than double the rate. + target.min(2 * base_target) +} + +/// The first threshold `val` falls below, sticking to `prev` within its hysteresis. +pub(super) fn hysteresis_decision(val: i32, thresholds: &[i32], hysteresis: &[i32], prev: usize) -> usize { + let mut i = thresholds.iter().position(|&t| val < t).unwrap_or(thresholds.len()); + if i > prev && val < thresholds[prev] + hysteresis[prev] { + i = prev; + } + if i < prev && val > thresholds[prev - 1] - hysteresis[prev - 1] { + i = prev; + } + i +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn medians_match_sorting() { + let mut seed = 1u32; + for _ in 0..1000 { + let mut x = [0.0f32; 5]; + for x in &mut x { + seed = math::lcg_rand(seed); + *x = (seed >> 28) as f32; + } + let mut sorted = x; + sorted.sort_by(f32::total_cmp); + assert_eq!(median_of_5(&x), sorted[2], "{x:?}"); + let mut sorted3 = [x[0], x[1], x[2]]; + sorted3.sort_by(f32::total_cmp); + assert_eq!(median_of_3(&x), sorted3[1], "{x:?}"); + } + } + + /// A click after silence is a transient; a steady sine is not. + #[test] + fn detects_a_click_but_not_a_tone() { + let len = 960 + OVERLAP; + let mut click = [0.0f32; MAX_FRAME + OVERLAP]; + for (i, x) in click.iter_mut().enumerate().take(len).skip(600) { + *x = 8000.0 * (i as f32 * 0.3).sin(); + } + let found = transient_analysis(&click[..len], len, 1, false, -1.0, 0.0); + assert!(found.transient); + assert!(found.tf_estimate > 0.5, "tf_estimate {}", found.tf_estimate); + + let mut tone = [0.0f32; MAX_FRAME + OVERLAP]; + for (i, x) in tone.iter_mut().enumerate().take(len) { + *x = 8000.0 * (i as f32 * 0.05).sin(); + } + let found = transient_analysis(&tone[..len], len, 1, false, -1.0, 0.0); + assert!(!found.transient); + } + + /// A pure tone's frequency comes back from the predictor's poles. + #[test] + fn finds_a_pure_tone() { + let len = 960 + OVERLAP; + let mut tone = [0.0f32; MAX_FRAME + OVERLAP]; + for (i, x) in tone.iter_mut().enumerate().take(len) { + *x = 1000.0 * (i as f32 * 0.2).cos(); + } + let (freq, toneishness) = tone_detect(&tone[..len], 1, len); + assert!((freq - 0.2).abs() < 1e-3, "freq {freq}"); + assert!(toneishness > 0.99, "toneishness {toneishness}"); + + let mut seed = 7u32; + let mut noise = [0.0f32; MAX_FRAME + OVERLAP]; + for x in noise.iter_mut().take(len) { + seed = math::lcg_rand(seed); + *x = math::lcg_sample(seed); + } + let (_, toneishness) = tone_detect(&noise[..len], 1, len); + assert!(toneishness < 0.5, "toneishness {toneishness}"); + } + + #[test] + fn hysteresis_sticks_near_the_previous_decision() { + let thresholds = [10, 20, 30]; + let hysteresis = [2, 2, 2]; + assert_eq!(hysteresis_decision(15, &thresholds, &hysteresis, 0), 1); + assert_eq!(hysteresis_decision(11, &thresholds, &hysteresis, 0), 0); + assert_eq!(hysteresis_decision(21, &thresholds, &hysteresis, 2), 2); + assert_eq!(hysteresis_decision(17, &thresholds, &hysteresis, 2), 1); + assert_eq!(hysteresis_decision(35, &thresholds, &hysteresis, 1), 3); + } +} diff --git a/kodecs-opus/src/safe/celt/encoder/mod.rs b/kodecs-opus/src/safe/celt/encoder/mod.rs new file mode 100644 index 00000000..cb77df54 --- /dev/null +++ b/kodecs-opus/src/safe/celt/encoder/mod.rs @@ -0,0 +1,1122 @@ +//! The CELT frame encoder, from libopus's celt/celt_encoder.c. +//! Copyright (c) 2007-2008 CSIRO, 2007-2010 Xiph.Org Foundation, and 2008 Gregory Maxwell. + +mod analysis; +mod prefilter; + +use super::bands::{self, Channels, Coding, Spreading}; +use super::comb; +use super::energy; +use super::math; +use super::mdct; +use super::rate; +use super::tables::{PREEMPH, SPREAD_ICDF, TAPSET_ICDF, TF_SELECT_TABLE, TRIM_ICDF}; +use super::{ + BANDS, MAX_FRAME, MAX_FRAME_BYTES, MAX_LM, MAX_PERIOD, OVERLAP, SHORT_MDCT_SIZE, SPREAD_AGGRESSIVE, SPREAD_NONE, + SPREAD_NORMAL, +}; +use crate::safe::config::SampleRate; +use crate::safe::math::CELT_SIG_SCALE; +use crate::safe::range::{self, BIT_RESOLUTION}; +use crate::safe::Error; + +const BITRES: i32 = BIT_RESOLUTION as i32; +/// The bands the tonality analysis reports leakage for. +const LEAK_BANDS: usize = 19; + +/// The Opus layer's tonality analysis of a frame, which steers CELT's decisions. +#[derive(Clone, Debug)] +pub(crate) struct Analysis { + pub tonality: f32, + pub tonality_slope: f32, + pub activity: f32, + /// The last band with signal worth coding. + pub bandwidth: usize, + /// How much of the pitch gain to keep, from 0 to 1. + pub max_pitch_ratio: f32, + /// Each band's boost for leakage from its neighbors, in 1/64 of a log2 step. + pub leak_boost: [u8; LEAK_BANDS], +} + +/// What SILK coded below a hybrid frame's CELT bands. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct SilkInfo { + /// SILK's signal type, 2 for voiced. + pub signal_type: i32, + /// SILK's quantization offset; tonal frames have small ones. + pub offset: i32, +} + +/// The rate the encoder targets. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Bitrate { + /// Fill each frame's buffer. + Max, + /// Bits per second. + Bits(i32), +} + +/// A CELT encoder for one or two channels in the standard 48 kHz mode. +pub(crate) struct Encoder { + channels: usize, + stream_channels: usize, + upsample: usize, + start: usize, + end: usize, + complexity: usize, + bitrate: Bitrate, + vbr: bool, + constrained_vbr: bool, + /// Expected packet loss, in percent. + loss_rate: i32, + /// The input's resolution, in bits. + lsb_depth: u32, + disable_inv: bool, + /// No pitch prefilter. + disable_pf: bool, + /// Code every frame's energy without prediction. + force_intra: bool, + + // Everything below is cleared by a reset. + analysis: Option, + silk_info: SilkInfo, + rng: u32, + spread_decision: usize, + delayed_intra: f32, + spreading: Spreading, + last_coded_bands: usize, + prefilter: comb::Filter, + consec_transient: u32, + preemph_mem: [f32; 2], + vbr_reservoir: i32, + vbr_drift: i32, + vbr_offset: i32, + vbr_count: i32, + overlap_max: f32, + stereo_saving: f32, + intensity: usize, + spec_avg: f32, + /// The last overlap of each channel's pre-emphasized input. + in_mem: [[f32; OVERLAP]; 2], + /// Each channel's input before the prefilter, for its pitch search and history. + prefilter_mem: [[f32; MAX_PERIOD]; 2], + old_band_e: [f32; 2 * BANDS], + old_log_e: [f32; 2 * BANDS], + old_log_e2: [f32; 2 * BANDS], + /// The last frame's fine energy quantization error, which biases the next. + energy_error: [f32; 2 * BANDS], +} + +impl Encoder { + /// An encoder of `channels` channels of input at `rate`. + pub(crate) fn new(rate: SampleRate, channels: usize) -> Result { + if !(1..=2).contains(&channels) { + return Err(Error::BadArg); + } + let upsample = match rate { + SampleRate::Hz48000 => 1, + SampleRate::Hz24000 => 2, + SampleRate::Hz16000 => 3, + SampleRate::Hz12000 => 4, + SampleRate::Hz8000 => 6, + }; + let mut encoder = Self { + channels, + stream_channels: channels, + upsample, + start: 0, + end: BANDS, + complexity: 5, + bitrate: Bitrate::Max, + vbr: false, + constrained_vbr: true, + loss_rate: 0, + lsb_depth: 24, + disable_inv: false, + disable_pf: false, + force_intra: false, + analysis: None, + silk_info: SilkInfo::default(), + rng: 0, + spread_decision: SPREAD_NORMAL, + delayed_intra: 1.0, + spreading: Spreading { + average: 256, + hf_average: 0, + tapset: 0, + }, + last_coded_bands: 0, + prefilter: comb::Filter::default(), + consec_transient: 0, + preemph_mem: [0.0; 2], + vbr_reservoir: 0, + vbr_drift: 0, + vbr_offset: 0, + vbr_count: 0, + overlap_max: 0.0, + stereo_saving: 0.0, + intensity: 0, + spec_avg: 0.0, + in_mem: [[0.0; OVERLAP]; 2], + prefilter_mem: [[0.0; MAX_PERIOD]; 2], + old_band_e: [0.0; 2 * BANDS], + old_log_e: [0.0; 2 * BANDS], + old_log_e2: [0.0; 2 * BANDS], + energy_error: [0.0; 2 * BANDS], + }; + encoder.reset(); + Ok(encoder) + } + + /// Forget all history. + pub(crate) fn reset(&mut self) { + self.analysis = None; + self.silk_info = SilkInfo::default(); + self.rng = 0; + self.spread_decision = SPREAD_NORMAL; + self.delayed_intra = 1.0; + self.spreading = Spreading { + average: 256, + hf_average: 0, + tapset: 0, + }; + self.last_coded_bands = 0; + self.prefilter = comb::Filter::default(); + self.consec_transient = 0; + self.preemph_mem = [0.0; 2]; + self.vbr_reservoir = 0; + self.vbr_drift = 0; + self.vbr_offset = 0; + self.vbr_count = 0; + self.overlap_max = 0.0; + self.stereo_saving = 0.0; + self.intensity = 0; + self.spec_avg = 0.0; + self.in_mem = [[0.0; OVERLAP]; 2]; + self.prefilter_mem = [[0.0; MAX_PERIOD]; 2]; + self.old_band_e = [0.0; 2 * BANDS]; + self.old_log_e = [-28.0; 2 * BANDS]; + self.old_log_e2 = [-28.0; 2 * BANDS]; + self.energy_error = [0.0; 2 * BANDS]; + } + + /// Search harder for better coding, from 0 to 10. + pub(crate) fn set_complexity(&mut self, complexity: usize) { + assert!(complexity <= 10, "complexity {complexity} out of range"); + self.complexity = complexity; + } + + /// Code bands from `start` on, as hybrid frames start above SILK's. + pub(crate) fn set_start_band(&mut self, start: usize) { + assert!(start < BANDS, "start band {start} out of range"); + self.start = start; + } + + /// Code bands below `end`, limiting the bandwidth. + pub(crate) fn set_end_band(&mut self, end: usize) { + // libopus also takes 1 and 2, then reads before its band energies in dynamic allocation. + assert!((3..=BANDS).contains(&end), "end band {end} out of range"); + self.end = end; + } + + /// The channels to code, which can be one for stereo input. + pub(crate) fn set_stream_channels(&mut self, channels: usize) { + assert!((1..=self.channels).contains(&channels), "{channels} stream channels"); + self.stream_channels = channels; + } + + /// Target `bitrate`, above 500 b/s and capped at 750 kb/s per channel. + pub(crate) fn set_bitrate(&mut self, bitrate: Bitrate) { + self.bitrate = match bitrate { + Bitrate::Max => Bitrate::Max, + Bitrate::Bits(bits) => { + assert!(bits > 500, "bitrate {bits} out of range"); + Bitrate::Bits(bits.min(750_000 * self.channels as i32)) + } + }; + } + + pub(crate) fn set_vbr(&mut self, vbr: bool) { + self.vbr = vbr; + } + + /// Keep VBR within a bit reservoir of the bitrate. + pub(crate) fn set_vbr_constraint(&mut self, constrained: bool) { + self.constrained_vbr = constrained; + } + + /// How much of the energy and pitch to predict from earlier frames: none (0), energy + /// only (1), or both (2). + pub(crate) fn set_prediction(&mut self, prediction: u32) { + assert!(prediction <= 2, "prediction {prediction} out of range"); + self.disable_pf = prediction <= 1; + self.force_intra = prediction == 0; + } + + /// The expected packet loss, in percent. + pub(crate) fn set_packet_loss(&mut self, percent: i32) { + assert!((0..=100).contains(&percent), "packet loss {percent}% out of range"); + self.loss_rate = percent; + } + + /// The input's resolution in bits, below which it counts as silence. + pub(crate) fn set_lsb_depth(&mut self, depth: u32) { + assert!((8..=24).contains(&depth), "LSB depth {depth} out of range"); + self.lsb_depth = depth; + } + + /// Never invert a stereo band's phase, keeping downmixes safe. + pub(crate) fn set_phase_inversion_disabled(&mut self, disabled: bool) { + self.disable_inv = disabled; + } + + /// The tonality analysis of the next frame, if any. + pub(crate) fn set_analysis(&mut self, analysis: Option) { + self.analysis = analysis; + } + + /// What SILK coded below the next hybrid frame. + pub(crate) fn set_silk_info(&mut self, info: SilkInfo) { + self.silk_info = info; + } + + /// The range coder's final state after the last frame, which the decoder reproduces. + pub(crate) fn final_range(&self) -> u32 { + self.rng + } + + /// Encode `frame_size` samples per channel of interleaved `pcm` at the input rate into + /// `enc`, after anything already coded there, filling at most its buffer and 1275 + /// bytes. Returns the finished frame. Panics, where libopus asserts, if what `enc` + /// already holds overflows the frame's size cap; Opus only puts a hybrid frame's SILK layer and + /// redundancy signalling there. + pub(crate) fn encode<'a>( + &mut self, + pcm: &[f32], + frame_size: usize, + mut enc: range::Encoder<'a>, + ) -> Result<&'a mut [u8], Error> { + let cc = self.channels; + let c = self.stream_channels; + let ci = c as i32; + let start = self.start; + let end = self.end; + if start >= end { + return Err(Error::BadArg); + } + let hybrid = start != 0; + let upsample = self.upsample; + + let frame_size = frame_size.checked_mul(upsample).ok_or(Error::BadArg)?; + let lm = (0..=MAX_LM) + .find(|&lm| SHORT_MDCT_SIZE << lm == frame_size) + .ok_or(Error::BadArg)?; + if enc.len() < 2 || pcm.len() < cc * frame_size / upsample { + return Err(Error::BadArg); + } + let m = 1 << lm; + let n = m * SHORT_MDCT_SIZE; + if enc.len() > MAX_FRAME_BYTES { + enc.shrink(MAX_FRAME_BYTES); + } + + let tell0_frac = enc.tell_frac() as i32; + let mut tell = enc.tell() as i32; + let nb_filled_bytes = (tell + 4) >> 3; + let mut nb_compressed_bytes = enc.len() as i32; + let vbr_rate; + let mut effective_bytes; + match self.bitrate { + Bitrate::Bits(bitrate) if self.vbr => { + vbr_rate = bitrate_to_bits(bitrate, frame_size) << BITRES; + effective_bytes = vbr_rate >> (3 + BITRES); + } + bitrate => { + vbr_rate = 0; + if let Bitrate::Bits(bitrate) = bitrate { + let mut tmp = bitrate * frame_size as i32; + if tell > 1 { + tmp += tell * 48000; + } + nb_compressed_bytes = 2.max(nb_compressed_bytes.min((tmp + 4 * 48000) / (8 * 48000))); + enc.shrink(nb_compressed_bytes as usize); + } + effective_bytes = nb_compressed_bytes - nb_filled_bytes; + } + } + let mut nb_available_bytes = nb_compressed_bytes - nb_filled_bytes; + let overhead = (40 * ci + 20) * ((400 >> lm) - 50); + let mut equiv_rate = ((nb_compressed_bytes * 8 * 50) << (3 - lm)) - overhead; + if let Bitrate::Bits(bitrate) = self.bitrate { + equiv_rate = equiv_rate.min(bitrate - overhead); + } + + // The most constrained VBR allows, set up front so bust prevention triggers right. + if vbr_rate > 0 && self.constrained_vbr { + let vbr_bound = vbr_rate; + // At least two bytes for an empty encoder, but none for hybrid. + let max_allowed = (if tell == 1 { 2 } else { 0 }) + .max((vbr_rate + vbr_bound - self.vbr_reservoir) >> (BITRES + 3)) + .min(nb_available_bytes); + if max_allowed < nb_available_bytes { + nb_compressed_bytes = nb_filled_bytes + max_allowed; + nb_available_bytes = max_allowed; + enc.shrink(nb_compressed_bytes as usize); + } + } + let mut total_bits = nb_compressed_bytes * 8; + let eff_end = end.min(BANDS); + + // Each channel's overlap from the last frame, then this frame, pre-emphasized. + let stride = n + OVERLAP; + let mut input = [0.0f32; 2 * (MAX_FRAME + OVERLAP)]; + let lead = c * (n - OVERLAP) / upsample; + let mut sample_max = math::max(self.overlap_max, max_abs(&pcm[..lead])); + self.overlap_max = max_abs(&pcm[lead..lead + c * OVERLAP / upsample]); + sample_max = math::max(sample_max, self.overlap_max); + let mut silence = sample_max <= 1.0 / (1u32 << self.lsb_depth) as f32; + if tell == 1 { + enc.bit_logp(silence, 15); + } else { + silence = false; + } + if silence { + // VBR needs no more than the minimum. + if vbr_rate > 0 { + nb_compressed_bytes = nb_compressed_bytes.min(nb_filled_bytes + 2); + effective_bytes = nb_compressed_bytes; + total_bits = nb_compressed_bytes * 8; + nb_available_bytes = 2; + enc.shrink(nb_compressed_bytes as usize); + } + // Pretend the remaining bits were filled with zeros, as the buffer is. + tell = nb_compressed_bytes * 8; + enc.skip_to_end(); + } + for ch in 0..cc { + let need_clip = sample_max > 65536.0; + let channel = &mut input[ch * stride..(ch + 1) * stride]; + preemphasis( + &pcm[ch..], + &mut channel[OVERLAP..], + cc, + upsample, + &mut self.preemph_mem[ch], + need_clip, + ); + channel[..OVERLAP].copy_from_slice(&self.prefilter_mem[ch][MAX_PERIOD - OVERLAP..]); + } + let input = &mut input[..cc * stride]; + + let (tone_freq, mut toneishness) = analysis::tone_detect(input, cc, stride); + let mut transient = false; + let mut weak_transient = false; + let mut tf_estimate = 0.0f32; + let mut tf_chan = 0; + if self.complexity >= 1 { + // Keep fricatives' energy stable at low hybrid bitrates, while still coding real + // transients on vowels (small SILK quantization offsets). + let allow_weak = hybrid && effective_bytes < 15 && self.silk_info.signal_type != 2; + let found = analysis::transient_analysis(input, stride, cc, allow_weak, tone_freq, toneishness); + transient = found.transient; + weak_transient = found.weak; + tf_estimate = found.tf_estimate; + tf_chan = found.tf_chan; + } + toneishness = math::min(toneishness, 1.0 - tf_estimate); + + // The pitch period and gain. + let enabled = + nb_available_bytes > 12 * ci && !hybrid && !silence && tell + 16 <= total_bits && !self.disable_pf; + let prefilter_tapset = self.spreading.tapset; + let pf = self.run_prefilter( + input, + cc, + n, + &prefilter::Settings { + tapset: prefilter_tapset, + enabled, + tf_estimate, + available_bytes: nb_available_bytes, + tone_freq, + toneishness, + }, + ); + #[cfg(feature = "ent-dump")] + eprintln!( + "prefilter: pitch_index={}, gain1={:1.6}, qg={}", + pf.pitch, pf.gain, pf.qg + ); + let pitch_change = (pf.gain > 0.4 || self.prefilter.gain > 0.4) + && self.analysis.as_ref().is_none_or(|a| f64::from(a.tonality) > 0.3) + && (pf.pitch as f64 > 1.26 * self.prefilter.period as f64 + || (pf.pitch as f64) < 0.79 * self.prefilter.period as f64); + if !pf.on { + if !hybrid && tell + 16 <= total_bits { + enc.bit_logp(false, 1); + } + } else { + enc.bit_logp(true, 1); + let pitch = pf.pitch as u32 + 1; + let octave = math::ilog(pitch) - 5; + enc.uint(octave, 6); + enc.bits(pitch - (16 << octave), 4 + octave); + enc.bits(pf.qg as u32, 3); + enc.icdf(prefilter_tapset, &TAPSET_ICDF, 2); + } + + let mut short_blocks = false; + let mut transient_got_disabled = false; + if lm > 0 && enc.tell() as i32 + 3 <= total_bits { + short_blocks = transient; + } else { + transient = false; + transient_got_disabled = true; + } + + let mut freq = [0.0f32; 2 * MAX_FRAME]; + let mut band_e = [0.0f32; 2 * BANDS]; + let mut band_log_e = [0.0f32; 2 * BANDS]; + let mut band_log_e2 = [0.0f32; 2 * BANDS]; + let mdcts = |short_blocks: bool, + freq: &mut [f32; 2 * MAX_FRAME], + band_e: &mut [f32; 2 * BANDS], + log_e: &mut [f32; 2 * BANDS]| { + compute_mdcts(short_blocks, input, freq, c, cc, lm, upsample); + bands::compute_band_energies(freq, band_e, eff_end, c, lm); + energy::amp2log2(eff_end, end, band_e, log_e, c); + }; + // Short blocks have less energy than long ones, by half a log2 step per LM. + let compensate = |log_e: &mut [f32; 2 * BANDS]| { + for ch in 0..c { + for e in &mut log_e[ch * BANDS..ch * BANDS + end] { + *e += 0.5 * lm as f32; + } + } + }; + // From complexity 8, take dynamic allocation's energies from a long MDCT even for + // short blocks. + let second_mdct = short_blocks && self.complexity >= 8; + if second_mdct { + mdcts(false, &mut freq, &mut band_e, &mut band_log_e2); + compensate(&mut band_log_e2); + } + mdcts(short_blocks, &mut freq, &mut band_e, &mut band_log_e); + if cc == 2 && c == 1 { + tf_chan = 0; + } + + // Temporal VBR. + let temporal_vbr = { + let mut follow = -10.0f32; + let mut frame_avg = 0.0f32; + let offset = if short_blocks { 0.5 * lm as f32 } else { 0.0 }; + for i in start..end { + follow = math::max(follow - 1.0, band_log_e[i] - offset); + if c == 2 { + follow = math::max(follow, band_log_e[i + BANDS] - offset); + } + frame_avg += follow; + } + frame_avg /= (end - start) as f32; + let temporal_vbr = math::min(3.0, math::max(-1.5, frame_avg - self.spec_avg)); + self.spec_avg += 0.02 * temporal_vbr; + temporal_vbr + }; + + if !second_mdct { + band_log_e2[..c * BANDS].copy_from_slice(&band_log_e[..c * BANDS]); + } + + // A last chance to catch a transient the time-domain analysis missed. + if lm > 0 + && enc.tell() as i32 + 3 <= total_bits + && !transient + && self.complexity >= 5 + && !hybrid + && analysis::patch_transient_decision(&band_log_e, &self.old_band_e, start, end, c) + { + transient = true; + short_blocks = true; + mdcts(true, &mut freq, &mut band_e, &mut band_log_e); + compensate(&mut band_log_e2); + tf_estimate = 0.2; + } + if lm > 0 && enc.tell() as i32 + 3 <= total_bits { + enc.bit_logp(transient, 3); + } + + // Band normalization. + let mut x = [0.0f32; 2 * MAX_FRAME]; + bands::normalise_bands(&freq, &mut x, &band_e, eff_end, c, m); + + let enable_tf_analysis = effective_bytes >= 15 * ci && !hybrid && self.complexity >= 2 && toneishness < 0.98; + let boosts = analysis::dynalloc_analysis(&analysis::Dynalloc { + band_log_e: &band_log_e, + band_log_e2: &band_log_e2, + old_band_e: &self.old_band_e, + start, + end, + channels: c, + lsb_depth: self.lsb_depth, + transient, + vbr: self.vbr, + constrained_vbr: self.constrained_vbr, + lm, + effective_bytes, + analysis: self.analysis.as_ref(), + tone_freq, + toneishness, + }); + let mut offsets = boosts.offsets; + + let mut tf_res = [0; BANDS]; + let tf_select; + if enable_tf_analysis { + let lambda = 80.max(20480 / effective_bytes + 2); + tf_select = analysis::tf_analysis( + eff_end, + transient, + &mut tf_res, + lambda, + &x, + n, + lm, + tf_estimate, + tf_chan, + &boosts.importance, + ); + for i in eff_end..end { + tf_res[i] = tf_res[eff_end - 1]; + } + } else if hybrid && weak_transient { + // Time-frequency changes on a long window improve time resolution imperfectly, + // which keeps weak transients' energy from collapsing at low bitrates. + tf_res[..end].fill(1); + tf_select = 0; + } else if hybrid && effective_bytes < 15 && self.silk_info.signal_type != 2 { + // Low bitrate hybrid frames get 5 ms time resolution rather than 2.5. + tf_res[..end].fill(0); + tf_select = usize::from(transient); + } else { + tf_res[..end].fill(i32::from(transient)); + tf_select = 0; + } + + // Bias stable energies towards the last frame's quantization error, as a constant + // offset sounds better than fluctuation. + for ch in 0..c { + for i in start..end { + let b = i + ch * BANDS; + if (band_log_e[b] - self.old_band_e[b]).abs() < 2.0 { + band_log_e[b] -= 0.25 * self.energy_error[b]; + } + } + } + let mut error = [0.0f32; 2 * BANDS]; + energy::quant_coarse( + &energy::Coarse { + start, + end, + eff_end, + band_log_e: &band_log_e, + budget: total_bits, + channels: c, + lm, + available_bytes: nb_available_bytes, + force_intra: self.force_intra, + two_pass: self.complexity >= 4, + loss_rate: self.loss_rate, + }, + &mut self.old_band_e, + &mut error, + &mut self.delayed_intra, + &mut enc, + ); + tf_encode(start, end, transient, &mut tf_res, lm, tf_select, &mut enc); + + if enc.tell() as i32 + 4 <= total_bits { + self.spread_decision = if hybrid { + if self.complexity == 0 { + SPREAD_NONE + } else if transient { + SPREAD_NORMAL + } else { + SPREAD_AGGRESSIVE + } + } else if short_blocks || self.complexity < 3 || nb_available_bytes < 10 * ci { + if self.complexity == 0 { + SPREAD_NONE + } else { + SPREAD_NORMAL + } + } else { + bands::spreading_decision( + &x, + &mut self.spreading, + self.spread_decision, + pf.on && !short_blocks, + eff_end, + c, + m, + &boosts.spread_weight, + ) + }; + enc.icdf(self.spread_decision, &SPREAD_ICDF, 5); + } else { + self.spread_decision = SPREAD_NORMAL; + } + + // Dynamic allocation boosts. + let cap = rate::init_caps(lm, c); + let mut dynalloc_logp = 6; + total_bits <<= BITRES; + let mut total_boost = 0; + let mut tell = enc.tell_frac() as i32; + for i in start..end { + let width = (ci * rate::band_width(i)) << lm; + // Six bits a boost, but no more than one bit and no less than an eighth per sample. + let quanta = (width << BITRES).min((6 << BITRES).max(width)); + let mut loop_logp = dynalloc_logp; + let mut boost = 0; + let mut j = 0; + while tell + (loop_logp << BITRES) < total_bits - total_boost && boost < cap[i] { + let flag = j < offsets[i]; + enc.bit_logp(flag, loop_logp as u32); + tell = enc.tell_frac() as i32; + if !flag { + break; + } + boost += quanta; + total_boost += quanta; + loop_logp = 1; + j += 1; + } + // Make further boosts more likely. + if j > 0 { + dynalloc_logp = 2.max(dynalloc_logp - 1); + } + offsets[i] = boost; + } + + let mut dual_stereo = false; + if c == 2 { + const INTENSITY_THRESHOLDS: [i32; BANDS] = [ + 1, 2, 3, 4, 5, 6, 7, 8, 16, 24, 36, 44, 50, 56, 62, 67, 72, 79, 88, 106, 134, + ]; + const INTENSITY_HYSTERESIS: [i32; BANDS] = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 5, 6, 8, 8]; + // 2.5 ms frames always use mid and side, short of a better analysis. + if lm != 0 { + dual_stereo = analysis::stereo_analysis(&x, lm, n); + } + self.intensity = analysis::hysteresis_decision( + equiv_rate / 1000, + &INTENSITY_THRESHOLDS, + &INTENSITY_HYSTERESIS, + self.intensity, + ); + self.intensity = end.min(start.max(self.intensity)); + } + + let mut alloc_trim = 5; + if tell + (6 << BITRES) <= total_bits - total_boost { + if start > 0 { + self.stereo_saving = 0.0; + } else { + alloc_trim = analysis::alloc_trim_analysis( + &x, + &band_log_e, + end, + lm, + c, + n, + self.analysis.as_ref(), + &mut self.stereo_saving, + tf_estimate, + self.intensity, + equiv_rate, + ); + } + enc.icdf(alloc_trim as usize, &TRIM_ICDF, 7); + tell = enc.tell_frac() as i32; + } + + // Never shrink a VBR frame so much that the encoder runs out of bits; the two bytes + // of margin keep the decoder's bust prevention from triggering so far. + let mut min_allowed = ((tell + total_boost + (1 << (BITRES + 3)) - 1) >> (BITRES + 3)) + 2; + // Leave hybrid frames the 37 bits a redundant frame's signalling needs, as a shorter + // packet would desynchronize the range decoder. + if hybrid { + min_allowed = + min_allowed.max((tell0_frac + (37 << BITRES) + total_boost + (1 << (BITRES + 3)) - 1) >> (BITRES + 3)); + } + + if vbr_rate > 0 { + let lm_diff = (MAX_LM - lm) as i32; + // Never more than 510 kb/s, even for short frames, as the allocator can't use it. + nb_compressed_bytes = nb_compressed_bytes.min(MAX_FRAME_BYTES as i32 >> (3 - lm)); + let mut base_target = if hybrid { + 0.max(vbr_rate - ((9 * ci + 4) << BITRES)) + } else { + vbr_rate - ((40 * ci + 20) << BITRES) + }; + if self.constrained_vbr { + base_target += self.vbr_offset >> lm_diff; + } + let mut target = if hybrid { + let mut target = base_target; + // Tonal frames (offset below 100) need more bits than noisy ones. + if self.silk_info.offset < 100 { + target += 12 << BITRES >> (3 - lm); + } + if self.silk_info.offset > 100 { + target -= 18 << BITRES >> (3 - lm); + } + // Boost transients and vowels with large temporal spikes. + target += ((tf_estimate - 0.25) * (50 << BITRES) as f32) as i32; + // Give strong transients enough bits to fold the first two bands rather than + // code noise. + if tf_estimate > 0.7 { + target = target.max(50 << BITRES); + } + target + } else { + analysis::compute_vbr(&analysis::Vbr { + analysis: self.analysis.as_ref(), + base_target, + lm, + bitrate: equiv_rate, + last_coded_bands: self.last_coded_bands, + channels: c, + intensity: self.intensity, + constrained_vbr: self.constrained_vbr, + stereo_saving: self.stereo_saving, + tot_boost: boosts.tot_boost, + tf_estimate, + pitch_change, + max_depth: boosts.max_depth, + temporal_vbr, + }) + }; + // Add the space used so far. + target += tell; + nb_available_bytes = (target + (1 << (BITRES + 2))) >> (BITRES + 3); + nb_available_bytes = min_allowed.max(nb_available_bytes); + nb_available_bytes = nb_compressed_bytes.min(nb_available_bytes); + // How far the frame missed its target. + let mut delta = target - vbr_rate; + target = nb_available_bytes << (BITRES + 3); + // Silence doesn't adjust the drift, which would shoot the rate up after it, but it + // lets the reservoir refill, undershooting the target on mostly silent input. + if silence { + nb_available_bytes = 2; + target = (2 * 8) << BITRES; + delta = 0; + } + let alpha = if self.vbr_count < 970 { + self.vbr_count += 1; + 1.0 / (self.vbr_count + 20) as f32 + } else { + 0.001 + }; + // Bits used beyond the allowance. + if self.constrained_vbr { + self.vbr_reservoir += target - vbr_rate; + } + // The offset that reaches the target. + if self.constrained_vbr { + self.vbr_drift += (alpha * ((delta * (1 << lm_diff)) - self.vbr_offset - self.vbr_drift) as f32) as i32; + self.vbr_offset = -self.vbr_drift; + } + if self.constrained_vbr && self.vbr_reservoir < 0 { + // Under the minimum: raise the rate, unless coding silence. + let adjust = -self.vbr_reservoir / (8 << BITRES); + if !silence { + nb_available_bytes += adjust; + } + self.vbr_reservoir = 0; + } + nb_compressed_bytes = nb_compressed_bytes.min(nb_available_bytes); + // Move the raw bits to the new end. + enc.shrink(nb_compressed_bytes as usize); + } + + // Bit allocation: the packet, less where we are, less a bit of safety. + let mut bits = ((nb_compressed_bytes * 8) << BITRES) - enc.tell_frac() as i32 - 1; + let anti_collapse_rsv = if transient && lm >= 2 && bits >= (lm as i32 + 2) << BITRES { + 1 << BITRES + } else { + 0 + }; + bits -= anti_collapse_rsv; + let mut signal_bandwidth = end - 1; + if let Some(analysis) = &self.analysis { + let min_bandwidth = if equiv_rate < 32000 * ci { + 13 + } else if equiv_rate < 48000 * ci { + 16 + } else if equiv_rate < 60000 * ci { + 18 + } else if equiv_rate < 80000 * ci { + 19 + } else { + 20 + }; + signal_bandwidth = analysis.bandwidth.max(min_bandwidth); + } + let alloc = rate::compute_allocation( + start, + end, + &offsets, + &cap, + alloc_trim, + bits, + c, + lm, + rate::Signal::Encode( + &mut enc, + rate::Choices { + prev_coded_bands: self.last_coded_bands, + signal_bandwidth, + intensity: self.intensity, + dual_stereo, + }, + ), + ); + self.intensity = alloc.intensity; + self.last_coded_bands = if self.last_coded_bands != 0 { + (self.last_coded_bands + 1).min((self.last_coded_bands - 1).max(alloc.coded_bands)) + } else { + alloc.coded_bands + }; + + energy::quant_fine( + start, + end, + &mut self.old_band_e, + &mut error, + &alloc.fine_quant, + &mut enc, + c, + ); + self.energy_error = [0.0; 2 * BANDS]; + + // Residual quantization. + let (x, y) = x[..c * n].split_at_mut(n); + bands::quant_all_bands( + &Coding { + start, + end, + short_blocks, + spread: self.spread_decision, + tf_res: &tf_res, + total_bits: nb_compressed_bytes * (8 << BITRES) - anti_collapse_rsv, + lm, + disable_inv: self.disable_inv, + }, + &alloc, + Channels { + x, + y: (c == 2).then_some(y), + }, + bands::Direction::Encode { + enc: &mut enc, + band_e: &band_e, + complexity: self.complexity, + }, + &mut self.rng, + ); + + if anti_collapse_rsv > 0 { + let anti_collapse_on = self.consec_transient < 2; + enc.bits(u32::from(anti_collapse_on), 1); + } + energy::quant_finalise( + start, + end, + &mut self.old_band_e, + &mut error, + &alloc.fine_quant, + &alloc.fine_priority, + nb_compressed_bytes * 8 - enc.tell() as i32, + &mut enc, + c, + ); + for ch in 0..c { + for i in start..end { + let b = i + ch * BANDS; + self.energy_error[b] = math::max(-0.5, math::min(0.5, error[b])); + } + } + if silence { + self.old_band_e[..c * BANDS].fill(-28.0); + } + self.prefilter = comb::Filter { + period: pf.pitch, + gain: pf.gain, + tapset: prefilter_tapset, + }; + if cc == 2 && c == 1 { + self.old_band_e.copy_within(..BANDS, BANDS); + } + let used = cc * BANDS; + if transient { + for (log_e, &band_e) in self.old_log_e[..used].iter_mut().zip(&self.old_band_e) { + *log_e = math::min(*log_e, band_e); + } + } else { + self.old_log_e2[..used].copy_from_slice(&self.old_log_e[..used]); + self.old_log_e[..used].copy_from_slice(&self.old_band_e[..used]); + } + // In case start or end were to change. + for ch in 0..cc { + for i in (0..start).chain(end..BANDS) { + self.old_band_e[ch * BANDS + i] = 0.0; + self.old_log_e[ch * BANDS + i] = -28.0; + self.old_log_e2[ch * BANDS + i] = -28.0; + } + } + if transient || transient_got_disabled { + self.consec_transient += 1; + } else { + self.consec_transient = 0; + } + self.rng = enc.range(); + // Any room left, only at very high rates, is already zeros. + enc.finish().map_err(|_| Error::Internal) + } +} + +/// The bits a frame of `frame_size` samples at 48 kHz gets at `bitrate`. +fn bitrate_to_bits(bitrate: i32, frame_size: usize) -> i32 { + bitrate * 6 / (6 * 48000 / frame_size as i32) +} + +/// The largest magnitude in `x`. +fn max_abs(x: &[f32]) -> f32 { + let mut max = 0.0f32; + let mut min = 0.0f32; + for &x in x { + max = math::max(max, x); + min = math::min(min, x); + } + math::max(max, -min) +} + +/// Pre-emphasize channel 0 of the `cc` interleaved channels of `pcm` into `out`, scaled to +/// CELT's signal range, inserting zeros to upsample and clipping when `clip`. +fn preemphasis(pcm: &[f32], out: &mut [f32], cc: usize, upsample: usize, mem: &mut f32, clip: bool) { + let n = out.len(); + let mut m = *mem; + let nu = n / upsample; + if upsample != 1 { + out.fill(0.0); + } + for i in 0..nu { + out[i * upsample] = CELT_SIG_SCALE * pcm[cc * i]; + } + if clip { + // Clip to avoid encoding non-portable files. + for i in 0..nu { + out[i * upsample] = math::max(-65536.0, math::min(65536.0, out[i * upsample])); + } + } + for x in out.iter_mut() { + let sample = *x; + *x = sample - m; + m = PREEMPH * sample; + } + *mem = m; +} + +/// Window and transform each of the `cc` channels of `input` into `freq`, as one long MDCT +/// or `2^lm` interleaved short ones, downmixing to `c` channels and scaling for upsampling. +fn compute_mdcts( + short_blocks: bool, + input: &[f32], + freq: &mut [f32; 2 * MAX_FRAME], + c: usize, + cc: usize, + lm: usize, + upsample: usize, +) { + let (blocks, n, shift) = if short_blocks { + (1 << lm, SHORT_MDCT_SIZE, MAX_LM) + } else { + (1, SHORT_MDCT_SIZE << lm, MAX_LM - lm) + }; + let frame = blocks * n; + for ch in 0..cc { + for b in 0..blocks { + mdct::forward( + &input[ch * (frame + OVERLAP) + b * n..], + &mut freq[b + ch * frame..], + shift, + blocks, + ); + } + } + if cc == 2 && c == 1 { + for i in 0..frame { + freq[i] = 0.5 * freq[i] + 0.5 * freq[frame + i]; + } + } + if upsample != 1 { + for ch in 0..c { + let bound = frame / upsample; + let channel = &mut freq[ch * frame..(ch + 1) * frame]; + for f in &mut channel[..bound] { + *f *= upsample as f32; + } + channel[bound..].fill(0.0); + } + } +} + +/// Code each band's time-frequency resolution change in `tf_res`, as changes from the last +/// band, then map them through the selected table. +fn tf_encode( + start: usize, + end: usize, + transient: bool, + tf_res: &mut [i32; BANDS], + lm: usize, + tf_select: usize, + enc: &mut range::Encoder, +) { + let mut budget = enc.len() as u32 * 8; + let mut tell = enc.tell(); + let mut logp = if transient { 2 } else { 4 }; + // Reserve space for the selector. + let tf_select_rsv = lm > 0 && tell + logp < budget; + budget -= u32::from(tf_select_rsv); + let mut curr = 0; + let mut tf_changed = 0; + for tf in &mut tf_res[start..end] { + if tell + logp <= budget { + enc.bit_logp(*tf ^ curr != 0, logp); + tell = enc.tell(); + curr = *tf; + tf_changed |= curr; + } else { + *tf = curr; + } + logp = if transient { 4 } else { 5 }; + } + let row = &TF_SELECT_TABLE[lm]; + let t = 4 * usize::from(transient); + let changed = tf_changed as usize; + // Code the selector only where it makes a difference. + let tf_select = if tf_select_rsv && row[t + changed] != row[t + 2 + changed] { + enc.bit_logp(tf_select != 0, 1); + tf_select + } else { + 0 + }; + for tf in &mut tf_res[start..end] { + *tf = i32::from(row[t + 2 * tf_select + *tf as usize]); + } +} + +#[cfg(test)] +mod tests; diff --git a/kodecs-opus/src/safe/celt/encoder/prefilter.rs b/kodecs-opus/src/safe/celt/encoder/prefilter.rs new file mode 100644 index 00000000..2dfa1755 --- /dev/null +++ b/kodecs-opus/src/safe/celt/encoder/prefilter.rs @@ -0,0 +1,243 @@ +//! The pitch prefilter, a comb filter the decoder's postfilter undoes, from libopus's +//! celt/celt_encoder.c. +//! Copyright (c) 2007-2008 CSIRO, 2007-2010 Xiph.Org Foundation, and 2008 Gregory Maxwell. + +use std::f64::consts::PI; + +use super::super::comb::{comb_filter, Filter}; +use super::super::math; +use super::super::pitch; +use super::super::tables::WINDOW; +use super::super::{COMBFILTER_MINPERIOD, MAX_FRAME, MAX_PERIOD, OVERLAP}; +use super::Encoder; + +// The filter history must hold a whole frame. +const _: () = assert!(MAX_FRAME < MAX_PERIOD); + +/// What the prefilter decided for a frame. +pub(super) struct Prefilter { + /// The comb filter's period, coded when `on`. + pub pitch: usize, + /// The comb filter's gain, zero when off. + pub gain: f32, + /// The coded gain, `gain / 0.09375 - 1`. + pub qg: i32, + pub on: bool, +} + +/// How the prefilter runs on a frame. +pub(super) struct Settings { + pub tapset: usize, + /// Whether the frame has the bits and signal for a prefilter at all. + pub enabled: bool, + pub tf_estimate: f32, + pub available_bytes: i32, + pub tone_freq: f32, + pub toneishness: f32, +} + +impl Encoder { + /// Find the pitch period and gain of the `n` new samples after the overlap in each of + /// the `cc` runs of `n + OVERLAP` samples in `input`, and apply the prefilter to them in + /// place, keeping it only when it helps. + pub(super) fn run_prefilter(&mut self, input: &mut [f32], cc: usize, n: usize, settings: &Settings) -> Prefilter { + let &Settings { + tapset, + enabled, + tf_estimate, + available_bytes, + mut tone_freq, + toneishness, + } = settings; + let stride = n + OVERLAP; + // Each channel's filter history, then the frame. + let mut pre = [[0.0f32; MAX_PERIOD + MAX_FRAME]; 2]; + for c in 0..cc { + pre[c][..MAX_PERIOD].copy_from_slice(&self.prefilter_mem[c]); + pre[c][MAX_PERIOD..MAX_PERIOD + n].copy_from_slice(&input[c * stride + OVERLAP..c * stride + stride]); + } + + let pitch_index; + let mut gain1; + if enabled && toneishness > 0.99 { + // The pitch estimator is unreliable on a single tone, so filter at the tone itself. + // Above 24 kHz, use the postfilter's alias; the threshold is just above pi to spare + // 48 kHz. + #[allow(clippy::approx_constant, reason = "libopus's literals, which round differently")] + if tone_freq >= 3.1416 { + tone_freq = 3.141593 - tone_freq; + } + // Double the pitch until the postfilter can take it. + let mut multiple = 1; + while tone_freq >= multiple as f32 * 0.39 { + multiple += 1; + } + pitch_index = if tone_freq > 0.006148 { + let period = (0.5 + 2.0 * PI * f64::from(multiple) / f64::from(tone_freq)).floor() as usize; + period.min(MAX_PERIOD - 2) + } else { + // A very low tone fares better with the filter's DC response at the shortest + // period. + COMBFILTER_MINPERIOD + }; + gain1 = 0.75; + } else if enabled && self.complexity >= 5 { + let mut pitch_buf = [0.0f32; (MAX_PERIOD + MAX_FRAME) >> 1]; + let pitch_buf = &mut pitch_buf[..(MAX_PERIOD + n) >> 1]; + let channels = [&pre[0][..MAX_PERIOD + n], &pre[1][..MAX_PERIOD + n]]; + pitch::pitch_downsample(&channels[..cc], pitch_buf); + // Skip the last 1.5 octaves of the range, where short-term correlation gives too + // many false positives. + let found = pitch::pitch_search( + &pitch_buf[MAX_PERIOD >> 1..], + pitch_buf, + n, + MAX_PERIOD - 3 * COMBFILTER_MINPERIOD, + ); + let (period, gain) = pitch::remove_doubling( + pitch_buf, + MAX_PERIOD, + COMBFILTER_MINPERIOD, + n, + MAX_PERIOD - found, + self.prefilter.period, + self.prefilter.gain, + ); + pitch_index = period.min(MAX_PERIOD - 2); + gain1 = 0.7 * gain; + if self.loss_rate > 2 { + gain1 *= 0.5; + } + if self.loss_rate > 4 { + gain1 *= 0.5; + } + if self.loss_rate > 8 { + gain1 = 0.0; + } + } else { + gain1 = 0.0; + pitch_index = COMBFILTER_MINPERIOD; + } + if let Some(analysis) = &self.analysis { + gain1 *= analysis.max_pitch_ratio; + } + + // The gain threshold, adjusted for rate and continuity. + let mut pf_threshold = 0.2f32; + if (pitch_index as i32 - self.prefilter.period as i32).abs() * 10 > pitch_index as i32 { + pf_threshold += 0.2; + // Strong transients without continuity get no prefilter at all. + if tf_estimate > 0.98 { + gain1 = 0.0; + } + } + if available_bytes < 25 { + pf_threshold += 0.1; + } + if available_bytes < 35 { + pf_threshold += 0.1; + } + if self.prefilter.gain > 0.4 { + pf_threshold -= 0.1; + } + if self.prefilter.gain > 0.55 { + pf_threshold -= 0.1; + } + pf_threshold = math::max(pf_threshold, 0.2); + let mut qg; + let mut on; + if gain1 < pf_threshold { + gain1 = 0.0; + on = false; + qg = 0; + } else { + if (gain1 - self.prefilter.gain).abs() < 0.1 { + gain1 = self.prefilter.gain; + } + qg = (math::floor_int(0.5 + gain1 * 32.0 / 3.0) - 1).clamp(0, 7); + gain1 = 0.09375 * (qg + 1) as f32; + on = true; + } + + // libopus also filters the first `SHORT_MDCT_SIZE - OVERLAP` samples with the old + // filter alone; the standard mode has none. + self.prefilter.period = self.prefilter.period.max(COMBFILTER_MINPERIOD); + let old = Filter { + gain: -self.prefilter.gain, + ..self.prefilter + }; + let new = Filter { + period: pitch_index, + gain: -gain1, + tapset, + }; + let mut before = [0.0f32; 2]; + let mut after = [0.0f32; 2]; + for c in 0..cc { + let channel = &mut input[c * stride..(c + 1) * stride]; + channel[..OVERLAP].copy_from_slice(&self.in_mem[c]); + for &x in &channel[OVERLAP..] { + before[c] += x.abs(); + } + comb_filter( + &mut pre[c], + MAX_PERIOD, + Some(&mut channel[OVERLAP..]), + n, + old, + new, + Some(&WINDOW), + ); + for &x in &channel[OVERLAP..] { + after[c] += x.abs(); + } + } + + let cancel = if cc == 2 { + let thresh = [ + 0.25 * gain1 * before[0] + 0.01 * before[1], + 0.25 * gain1 * before[1] + 0.01 * before[0], + ]; + // Don't filter if one channel gets significantly worse, or neither gets + // significantly better. + after[0] - before[0] > thresh[0] + || after[1] - before[1] > thresh[1] + || (before[0] - after[0] < thresh[0] && before[1] - after[1] < thresh[1]) + } else { + after[0] > before[0] + }; + if cancel { + // Fade the old filter out over the overlap instead. + let new = Filter { gain: 0.0, ..new }; + for c in 0..cc { + let channel = &mut input[c * stride + OVERLAP..(c + 1) * stride]; + channel.copy_from_slice(&pre[c][MAX_PERIOD..MAX_PERIOD + n]); + comb_filter( + &mut pre[c], + MAX_PERIOD, + Some(&mut channel[..OVERLAP]), + OVERLAP, + old, + new, + Some(&WINDOW), + ); + } + gain1 = 0.0; + on = false; + qg = 0; + } + + for c in 0..cc { + self.in_mem[c].copy_from_slice(&input[c * stride + n..(c + 1) * stride]); + let mem = &mut self.prefilter_mem[c]; + mem.copy_within(n.., 0); + mem[MAX_PERIOD - n..].copy_from_slice(&pre[c][MAX_PERIOD..MAX_PERIOD + n]); + } + Prefilter { + pitch: pitch_index, + gain: gain1, + qg, + on, + } + } +} diff --git a/kodecs-opus/src/safe/celt/encoder/tests.rs b/kodecs-opus/src/safe/celt/encoder/tests.rs new file mode 100644 index 00000000..ad2c53ad --- /dev/null +++ b/kodecs-opus/src/safe/celt/encoder/tests.rs @@ -0,0 +1,295 @@ +use super::*; +use crate::safe::{Decoder, Mapping}; + +/// What a test signal sounds like. +#[derive(Clone, Copy, Debug)] +enum Kind { + /// A sum of tones below 5 kHz, different in each channel. + Tones, + /// White noise through a one-pole low-pass at about 3 kHz. + Noise, +} + +/// Half a second of `kind` in `channels` interleaved channels at 48 kHz, at about -10 dBFS. +fn signal(kind: Kind, channels: usize) -> Vec { + const LEN: usize = 24000; + let mut pcm = vec![0.0f32; LEN * channels]; + let mut seed = 11u32; + let mut lowpass = [0.0f32; 2]; + for i in 0..LEN { + for c in 0..channels { + let t = i as f32 / 48000.0; + pcm[i * channels + c] = match kind { + Kind::Tones => { + let base = 220.0 * (c + 2) as f32; + 0.15 * (std::f32::consts::TAU * base * t).sin() + + 0.1 * (std::f32::consts::TAU * 3.0 * base * t).sin() + + 0.05 * (std::f32::consts::TAU * 4321.0 * t).sin() + } + Kind::Noise => { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + let white = (seed >> 8) as f32 / (1 << 23) as f32 - 1.0; + lowpass[c] = 0.67 * lowpass[c] + 0.33 * white; + 0.6 * lowpass[c] + } + }; + } + } + pcm +} + +/// The signal-to-noise ratio of `decoded` against `original` in dB, at the delay that +/// maximizes it, skipping the first 50 ms while the codec settles. +fn snr(original: &[f32], decoded: &[f32], channels: usize) -> f64 { + const SKIP: usize = 2400; + let frames = original.len() / channels; + (0..=480) + .map(|delay| { + let (mut signal, mut noise) = (0.0f64, 0.0f64); + for i in SKIP..frames - delay { + for c in 0..channels { + let x = f64::from(original[i * channels + c]); + let y = f64::from(decoded[(i + delay) * channels + c]); + signal += x * x; + noise += (x - y) * (x - y); + } + } + 10.0 * (signal / noise).log10() + }) + .fold(f64::NEG_INFINITY, f64::max) +} + +struct RoundTrip { + snr: f64, + /// Each frame's CELT bytes, without the TOC byte. + sizes: Vec, +} + +/// Encode `kind` in single-frame CELT packets of `frame` samples, decode them with the +/// public decoder, and measure the result. +fn round_trip(kind: Kind, channels: usize, frame: usize, bitrate: i32, vbr: bool) -> RoundTrip { + let pcm = signal(kind, channels); + let mut encoder = Encoder::new(SampleRate::Hz48000, channels).expect("valid encoder"); + encoder.set_bitrate(Bitrate::Bits(bitrate)); + encoder.set_vbr(vbr); + encoder.set_complexity(10); + let mapping = Mapping::family0(channels as u8).expect("valid mapping"); + let mut decoder = Decoder::new(48000, &mapping).expect("valid decoder"); + let lm = (0..=MAX_LM) + .find(|&lm| SHORT_MDCT_SIZE << lm == frame) + .expect("a CELT frame size"); + // Fullband CELT-only configurations 28 to 31, one frame. + let toc = ((28 + lm as u8) << 3) | (u8::from(channels == 2) << 2); + + let mut decoded = vec![0.0f32; pcm.len()]; + let mut sizes = Vec::new(); + for (input, output) in pcm + .chunks_exact(frame * channels) + .zip(decoded.chunks_exact_mut(frame * channels)) + { + let mut packet = [0u8; 1 + MAX_FRAME_BYTES]; + packet[0] = toc; + let len = { + let enc = range::Encoder::new(&mut packet[1..]); + encoder.encode(input, frame, enc).expect("encodes").len() + }; + sizes.push(len); + let samples = decoder.decode_float(&packet[..1 + len], output).expect("decodes"); + assert_eq!(samples, frame, "decoded duration"); + } + RoundTrip { + snr: snr(&pcm, &decoded, channels), + sizes, + } +} + +/// Every frame size, channel count, and signal round-trips at high quality, CBR frames fill +/// exactly their bitrate's bytes, and VBR frames average near it. +#[test] +fn frames_round_trip_through_the_decoder() { + for channels in [1, 2] { + for frame in [120, 240, 480, 960] { + for kind in [Kind::Tones, Kind::Noise] { + for vbr in [false, true] { + let bitrate = 64000 * channels as i32; + let result = round_trip(kind, channels, frame, bitrate, vbr); + let label = format!("{kind:?}, {channels} channels, {frame} samples, vbr {vbr}"); + let bytes = (bitrate * frame as i32 / 48000 + 4) / 8; + let mean = result.sizes.iter().sum::() as f64 / result.sizes.len() as f64; + if vbr { + assert!( + (mean - bytes as f64).abs() < 0.25 * bytes as f64, + "{label}: mean {mean} bytes for {bytes}" + ); + } else { + assert!( + result.sizes.iter().all(|&size| size == bytes as usize), + "{label}: {:?}", + result.sizes + ); + } + // CELT codes noise perceptually, folding and filling rather than matching its + // waveform. + let min_snr = match kind { + Kind::Tones => 20.0, + Kind::Noise => 5.0, + }; + assert!(result.snr > min_snr, "{label}: SNR {:.1} dB", result.snr); + } + } + } + } +} + +/// Digital silence codes as the two-byte silence frame in VBR and decodes to silence. +#[test] +fn silence_codes_in_two_bytes() { + let mut encoder = Encoder::new(SampleRate::Hz48000, 2).expect("valid encoder"); + encoder.set_bitrate(Bitrate::Bits(128000)); + encoder.set_vbr(true); + let mut buf = [0u8; 1275]; + let pcm = [0.0f32; 2 * 960]; + for _ in 0..3 { + let enc = range::Encoder::new(&mut buf); + let packet = encoder.encode(&pcm, 960, enc).expect("encodes"); + assert_eq!(packet.len(), 2); + } +} + +/// A pulse train gets a prefilter at its period, or a multiple, with a strong gain. +#[test] +fn prefilter_locks_onto_a_pulse_train() { + const PERIOD: usize = 240; + let mut encoder = Encoder::new(SampleRate::Hz48000, 1).expect("valid encoder"); + encoder.set_complexity(10); + let mut pcm = vec![0.0f32; 960 * 8]; + for (i, x) in pcm.iter_mut().enumerate() { + let phase = i % PERIOD; + *x = if phase < 4 { 0.5 } else { 0.0 } + 0.02 * (i as f32 * 0.37).sin(); + } + for input in pcm.as_chunks::<960>().0 { + let mut buf = [0u8; 160]; + let enc = range::Encoder::new(&mut buf); + encoder.encode(input, 960, enc).expect("encodes"); + } + let filter = encoder.prefilter; + assert!(filter.gain > 0.3, "{filter:?}"); + assert_eq!(filter.period % PERIOD, 0, "{filter:?}"); +} + +/// Stereo input coded as one stream channel decodes to the same mono content in both. +#[test] +fn stereo_input_codes_as_a_mono_stream() { + let pcm = signal(Kind::Tones, 2); + let mut encoder = Encoder::new(SampleRate::Hz48000, 2).expect("valid encoder"); + encoder.set_stream_channels(1); + let mapping = Mapping::family0(2).expect("valid mapping"); + let mut decoder = Decoder::new(48000, &mapping).expect("valid decoder"); + let mut output = [0.0f32; 2 * 960]; + for input in pcm.as_chunks::<{ 2 * 960 }>().0.iter().take(10) { + let mut packet = [0u8; 161]; + packet[0] = 31 << 3; + let enc = range::Encoder::new(&mut packet[1..]); + let len = encoder.encode(input, 960, enc).expect("encodes").len(); + assert_eq!( + decoder.decode_float(&packet[..1 + len], &mut output).expect("decodes"), + 960 + ); + } + let energy: f32 = output.iter().map(|x| x * x).sum(); + assert!(energy > 1.0, "energy {energy}"); + for pair in output.as_chunks::<2>().0 { + assert_eq!(pair[0], pair[1]); + } +} + +/// Input at lower rates upsamples, still filling the frame. +#[test] +fn lower_input_rates_upsample() { + let mut encoder = Encoder::new(SampleRate::Hz16000, 1).expect("valid encoder"); + let pcm: Vec = (0..320).map(|i| 0.3 * (i as f32 * 0.2).sin()).collect(); + let mut buf = [0u8; 80]; + let enc = range::Encoder::new(&mut buf); + assert_eq!(encoder.encode(&pcm, 320, enc).expect("encodes").len(), 80); + let enc = range::Encoder::new(&mut buf); + assert_eq!(encoder.encode(&pcm[..100], 100, enc), Err(Error::BadArg)); +} + +/// Narrow band ranges encode, even above the tonality analysis's leak bands, and reversed +/// ranges or impossible frame sizes are rejected. +#[test] +fn band_ranges_and_bad_arguments() { + let pcm = signal(Kind::Noise, 1); + let pcm = &pcm[..960]; + let mut buf = [0u8; 1275]; + for (start, end) in [(0, 3), (20, 21)] { + let mut encoder = Encoder::new(SampleRate::Hz48000, 1).expect("valid encoder"); + encoder.set_start_band(start); + encoder.set_end_band(end); + encoder.set_analysis(Some(Analysis { + tonality: 0.5, + tonality_slope: 0.0, + activity: 1.0, + bandwidth: 20, + max_pitch_ratio: 1.0, + leak_boost: [64; LEAK_BANDS], + })); + let enc = range::Encoder::new(&mut buf); + encoder.encode(pcm, 960, enc).expect("encodes"); + } + + let mut encoder = Encoder::new(SampleRate::Hz24000, 1).expect("valid encoder"); + let enc = range::Encoder::new(&mut buf); + assert_eq!(encoder.encode(pcm, usize::MAX / 2 + 241, enc), Err(Error::BadArg)); + encoder.set_start_band(17); + encoder.set_end_band(17); + let enc = range::Encoder::new(&mut buf); + assert_eq!(encoder.encode(pcm, 480, enc), Err(Error::BadArg)); +} + +/// At the same rate, quality stays within 3 dB of the c2rust libopus 1.3.1 encoder's CELT +/// mode, which adds its own tonality analysis. +#[test] +fn quality_matches_the_reference_encoder() { + for channels in [1, 2] { + for frame in [480, 960] { + for kind in [Kind::Tones, Kind::Noise] { + let bitrate = 64000 * channels as u32; + let pcm = signal(kind, channels); + let mut reference = + crate::Encoder::new(48000, channels as u8, crate::Application::Audio).expect("valid encoder"); + reference.set_bitrate(bitrate).expect("valid bitrate"); + reference.set_signal(crate::Signal::Music).expect("valid signal"); + let mapping = Mapping::family0(channels as u8).expect("valid mapping"); + let mut decoder = Decoder::new(48000, &mapping).expect("valid decoder"); + let mut decoded = vec![0.0f32; pcm.len()]; + let mut bytes = 0; + for (input, output) in pcm + .chunks_exact(frame * channels) + .zip(decoded.chunks_exact_mut(frame * channels)) + { + let mut packet = [0u8; 1500]; + let len = reference.encode_float(input, &mut packet).expect("encodes"); + assert!(packet[0] >> 3 >= 16, "configuration {} isn't CELT-only", packet[0] >> 3); + bytes += len - 1; + decoder.decode_float(&packet[..len], output).expect("decodes"); + } + let reference_snr = snr(&pcm, &decoded, channels); + let reference_bytes = bytes as f64 / (pcm.len() / channels / frame) as f64; + + let ours = round_trip(kind, channels, frame, bitrate as i32, true); + let our_bytes = ours.sizes.iter().sum::() as f64 / ours.sizes.len() as f64; + let label = format!("{kind:?}, {channels} channels, {frame} samples"); + assert!( + ours.snr > reference_snr - 3.0, + "{label}: SNR {:.1} dB against {reference_snr:.1}", + ours.snr + ); + assert!( + (our_bytes - reference_bytes).abs() < 0.05 * reference_bytes, + "{label}: {our_bytes} bytes against {reference_bytes}" + ); + } + } + } +} diff --git a/kodecs-opus/src/safe/celt/energy.rs b/kodecs-opus/src/safe/celt/energy.rs index 8726703c..e205595d 100644 --- a/kodecs-opus/src/safe/celt/energy.rs +++ b/kodecs-opus/src/safe/celt/energy.rs @@ -1,7 +1,8 @@ -//! Decoding band energies, from libopus's celt/quant_bands.c and celt/laplace.c. +//! Coding band energies, from libopus's celt/quant_bands.c and celt/laplace.c. //! Copyright (c) 2007-2008 CSIRO, 2007-2009 Xiph.Org Foundation, and 2007-2009 Jean-Marc //! Valin. +use super::coder::Snapshot; use super::math; use super::BANDS; use crate::safe::range; @@ -81,6 +82,47 @@ const SMALL_ENERGY_ICDF: [u8; 3] = [2, 1, 0]; const LAPLACE_MINP: u32 = 1; const LAPLACE_NMIN: u32 = 16; +/// The probability of +1 (and of -1) beyond the minimum, given the probability `fs0` of zero. +fn laplace_freq1(fs0: u32, decay: u32) -> u32 { + let ft = 32768 - LAPLACE_MINP * (2 * LAPLACE_NMIN) - fs0; + (ft * (16384 - decay)) >> 15 +} + +/// Encode `value` with the Laplace-like distribution `laplace_decode` reads, clamping it to +/// the largest magnitude the distribution codes. +fn laplace_encode(enc: &mut range::Encoder, value: &mut i32, mut fs: u32, decay: u32) { + let mut fl = 0; + let mut val = *value; + if val != 0 { + let s = -i32::from(val < 0); + val = (val + s) ^ s; + fl = fs; + fs = laplace_freq1(fs, decay); + // Search the decaying part of the distribution. + let mut i = 1; + while fs > 0 && i < val { + fs *= 2; + fl += fs + 2 * LAPLACE_MINP; + fs = (fs * decay) >> 15; + i += 1; + } + if fs == 0 { + // Everything beyond has probability LAPLACE_MINP. + let ndi_max = (32768 - fl + LAPLACE_MINP - 1) as i32; + let ndi_max = (ndi_max - s) >> 1; + let di = (val - i).min(ndi_max - 1); + fl += ((2 * di + 1 + s) as u32) * LAPLACE_MINP; + fs = LAPLACE_MINP.min(32768 - fl); + *value = (i + di + s) ^ s; + } else { + fs += LAPLACE_MINP; + fl += fs & !(s as u32); + } + debug_assert!(fl + fs <= 32768 && fs > 0); + } + enc.encode_bin(fl..fl + fs, 15); +} + /// Decode a value with a Laplace-like distribution: `fs` is the probability of zero and /// `decay` the geometric decay, both in Q15. fn laplace_decode(dec: &mut range::Decoder, mut fs: u32, decay: u32) -> i32 { @@ -91,8 +133,7 @@ fn laplace_decode(dec: &mut range::Decoder, mut fs: u32, decay: u32) -> i32 { if fm >= fs { val += 1; fl = fs; - let ft = 32768 - LAPLACE_MINP * (2 * LAPLACE_NMIN) - fs; - fs = ((ft * (16384 - decay)) >> 15) + LAPLACE_MINP; + fs = laplace_freq1(fs, decay) + LAPLACE_MINP; // Search the decaying part of the distribution. while fs > LAPLACE_MINP && fm >= fl + 2 * fs { fs *= 2; @@ -217,3 +258,369 @@ pub(super) fn unquant_finalise( } } } + +/// How the coarse energy of a frame is coded. +pub(super) struct Coarse<'a> { + pub start: usize, + pub end: usize, + /// One past the last band with real energy. + pub eff_end: usize, + /// Each band's log2 amplitude, relative to its mean. + pub band_log_e: &'a [f32; 2 * BANDS], + /// The frame's size in bits. + pub budget: i32, + pub channels: usize, + pub lm: usize, + pub available_bytes: i32, + pub force_intra: bool, + /// Try intra coding too and keep whichever codes better. + pub two_pass: bool, + /// Expected packet loss, in percent. + pub loss_rate: i32, +} + +/// The squared change in each band's log2 energy since the last frame, capped at 200. +fn loss_distortion(e: &[f32; 2 * BANDS], old: &[f32; 2 * BANDS], start: usize, end: usize, channels: usize) -> f32 { + let mut dist = 0.0f32; + for c in 0..channels { + for i in start..end { + let d = e[i + c * BANDS] - old[i + c * BANDS]; + dist += d * d; + } + } + math::min(200.0, dist) +} + +/// Encode the coarse energy of bands `start..end`, updating `old` to the quantized energy and +/// `error` to what is left for fine quantization. `delayed_intra` tracks how much a lost +/// frame would hurt, which decides when intra coding pays off. +pub(super) fn quant_coarse( + coarse: &Coarse, + old: &mut [f32; 2 * BANDS], + error: &mut [f32; 2 * BANDS], + delayed_intra: &mut f32, + enc: &mut range::Encoder, +) { + let &Coarse { + start, + end, + eff_end, + band_log_e, + budget, + channels, + lm, + available_bytes, + force_intra, + loss_rate, + .. + } = coarse; + let c = channels as i32; + let bands = (end - start) as i32; + let mut two_pass = coarse.two_pass; + let mut intra = + force_intra || (!two_pass && *delayed_intra > (2 * c * bands) as f32 && available_bytes > bands * c); + let intra_bias = (budget as f32 * *delayed_intra * loss_rate as f32 / (c * 512) as f32) as i32; + let new_distortion = loss_distortion(band_log_e, old, start, eff_end, channels); + + if enc.tell() as i32 + 3 > budget { + two_pass = false; + intra = false; + } + + let mut max_decay = 16.0f32; + if end - start > 10 { + max_decay = math::min(max_decay, 0.125 * available_bytes as f32); + } + let start_state = enc.checkpoint(); + let start_bytes = enc.range_bytes(); + let mut old_intra = *old; + let mut error_intra = *error; + let mut badness1 = 0; + if two_pass || intra { + badness1 = quant_coarse_pass(coarse, &mut old_intra, &mut error_intra, true, max_decay, enc); + } + + if !intra { + let tell_intra = enc.tell_frac() as i32; + let intra_state = Snapshot::take(enc, start_bytes); + enc.restore(&start_state); + let badness2 = quant_coarse_pass(coarse, old, error, false, max_decay, enc); + if two_pass + && (badness1 < badness2 || (badness1 == badness2 && enc.tell_frac() as i32 + intra_bias > tell_intra)) + { + intra_state.restore(enc); + *old = old_intra; + *error = error_intra; + intra = true; + } + } else { + *old = old_intra; + *error = error_intra; + } + + *delayed_intra = if intra { + new_distortion + } else { + PRED_COEF[lm] * PRED_COEF[lm] * *delayed_intra + new_distortion + }; +} + +/// One coarse energy encode, intra or predicted from `old`, returning how far the coded +/// values strayed from the wanted ones for lack of bits. +fn quant_coarse_pass( + coarse: &Coarse, + old: &mut [f32; 2 * BANDS], + error: &mut [f32; 2 * BANDS], + intra: bool, + max_decay: f32, + enc: &mut range::Encoder, +) -> i32 { + let &Coarse { + start, + end, + band_log_e, + budget, + channels, + lm, + .. + } = coarse; + if enc.tell() as i32 + 3 <= budget { + enc.bit_logp(intra, 3); + } + let prob_model = &E_PROB_MODEL[lm][usize::from(intra)]; + let (coef, beta) = if intra { + (0.0, BETA_INTRA) + } else { + (PRED_COEF[lm], BETA_COEF[lm]) + }; + let mut badness = 0; + let mut prev = [0.0f32; 2]; + for i in start..end { + for (c, prev) in prev.iter_mut().enumerate().take(channels) { + let band = i + c * BANDS; + let x = band_log_e[band]; + let old_e = math::max(-9.0, old[band]); + let f = x - coef * old_e - *prev; + // Rounding to nearest is really important here. + let mut qi = math::floor_int(0.5 + f); + let decay_bound = math::max(-28.0, old[band]) - max_decay; + // Keep the energy from falling too fast, as for single-bin bands. + if qi < 0 && x < decay_bound { + qi += (decay_bound - x) as i32; + qi = qi.min(0); + } + let qi0 = qi; + // Short of bits for every band's energy, assume something safe. + let tell = enc.tell() as i32; + let bits_left = budget - tell - 3 * channels as i32 * (end - i) as i32; + if i != start && bits_left < 30 { + if bits_left < 24 { + qi = qi.min(1); + } + if bits_left < 16 { + qi = qi.max(-1); + } + } + if budget - tell >= 15 { + let pi = 2 * i.min(20); + laplace_encode( + enc, + &mut qi, + u32::from(prob_model[pi]) << 7, + u32::from(prob_model[pi + 1]) << 6, + ); + } else if budget - tell >= 2 { + qi = qi.clamp(-1, 1); + enc.icdf(((2 * qi) ^ -i32::from(qi < 0)) as usize, &SMALL_ENERGY_ICDF, 2); + } else if budget - tell >= 1 { + qi = qi.min(0); + enc.bit_logp(qi != 0, 1); + } else { + qi = -1; + } + error[band] = f - qi as f32; + badness += (qi0 - qi).abs(); + let q = qi as f32; + old[band] = coef * old_e + *prev + q; + *prev = *prev + q - beta * q; + } + } + badness +} + +/// Encode the fine energy bits `fine_quant` allocates to each band. +pub(super) fn quant_fine( + start: usize, + end: usize, + old: &mut [f32; 2 * BANDS], + error: &mut [f32; 2 * BANDS], + fine_quant: &[i32; BANDS], + enc: &mut range::Encoder, + channels: usize, +) { + for (i, &bits) in fine_quant.iter().enumerate().take(end).skip(start) { + if bits <= 0 { + continue; + } + if enc.tell() as i32 + channels as i32 * bits > enc.len() as i32 * 8 { + continue; + } + let levels = 1 << bits; + for c in 0..channels { + let band = i + c * BANDS; + let q2 = math::floor_int((error[band] + 0.5) * levels as f32).clamp(0, levels - 1); + enc.bits(q2 as u32, bits as u32); + // libopus then scales by a previous quantizer step only its extended precision + // layer has; here it is one. + let offset = (q2 as f32 + 0.5) * (1 << (14 - bits)) as f32 * (1.0 / 16384.0) - 0.5; + old[band] += offset; + error[band] -= offset; + } + } +} + +/// Spend the bits left after the spectrum on one more fine energy bit per band, by priority. +#[allow( + clippy::too_many_arguments, + reason = "mirrors libopus's quant_energy_finalise, which the encoder calls once" +)] +pub(super) fn quant_finalise( + start: usize, + end: usize, + old: &mut [f32; 2 * BANDS], + error: &mut [f32; 2 * BANDS], + fine_quant: &[i32; BANDS], + fine_priority: &[i32; BANDS], + mut bits_left: i32, + enc: &mut range::Encoder, + channels: usize, +) { + for prio in 0..2 { + let mut i = start; + while i < end && bits_left >= channels as i32 { + if fine_quant[i] >= MAX_FINE_BITS || fine_priority[i] != prio { + i += 1; + continue; + } + for c in 0..channels { + let band = i + c * BANDS; + let q2 = u32::from(error[band] >= 0.0); + enc.bits(q2, 1); + let offset = (q2 as f32 - 0.5) * (1 << (14 - fine_quant[i] - 1)) as f32 * (1.0 / 16384.0); + old[band] += offset; + error[band] -= offset; + bits_left -= 1; + } + i += 1; + } + } +} + +/// Convert band amplitudes to log2, relative to each band's mean, with bands from `eff_end` +/// to `end` silent. +pub(super) fn amp2log2( + eff_end: usize, + end: usize, + band_e: &[f32; 2 * BANDS], + band_log_e: &mut [f32; 2 * BANDS], + channels: usize, +) { + for c in 0..channels { + for i in 0..eff_end { + band_log_e[i + c * BANDS] = math::log2(band_e[i + c * BANDS]) - E_MEANS[i]; + } + band_log_e[c * BANDS + eff_end..c * BANDS + end].fill(-14.0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::safe::range; + + /// The decoder reproduces the encoder's quantized energies exactly through coarse, fine, + /// and final quantization, intra or predicted, and they land near the targets. + #[test] + fn quantized_energies_decode_to_the_encoders() { + let mut seed = 3u32; + let mut random = move || { + seed = math::lcg_rand(seed); + (seed >> 8) as f32 / (1 << 23) as f32 - 1.0 + }; + for (channels, lm, force_intra, bytes) in [ + (1, 3, true, 100), + (2, 3, false, 160), + (1, 0, false, 40), + (2, 2, false, 12), + ] { + let mut enc_old = [0.0f32; 2 * BANDS]; + let mut dec_old = [0.0f32; 2 * BANDS]; + let mut delayed_intra = 1.0; + for frame in 0..4 { + let mut target = [0.0f32; 2 * BANDS]; + for t in target.iter_mut() { + *t = 4.0 * random() + frame as f32; + } + let mut buf = vec![0u8; bytes]; + let mut enc = range::Encoder::new(&mut buf); + let mut error = [0.0f32; 2 * BANDS]; + let coarse = Coarse { + start: 0, + end: BANDS, + eff_end: BANDS, + band_log_e: &target, + budget: bytes as i32 * 8, + channels, + lm, + available_bytes: bytes as i32, + force_intra, + two_pass: true, + loss_rate: 0, + }; + quant_coarse(&coarse, &mut enc_old, &mut error, &mut delayed_intra, &mut enc); + let fine_quant: [i32; BANDS] = std::array::from_fn(|i| (i % 3) as i32); + let fine_priority: [i32; BANDS] = std::array::from_fn(|i| (i % 2) as i32); + quant_fine(0, BANDS, &mut enc_old, &mut error, &fine_quant, &mut enc, channels); + let bits_left = bytes as i32 * 8 - enc.tell() as i32; + quant_finalise( + 0, + BANDS, + &mut enc_old, + &mut error, + &fine_quant, + &fine_priority, + bits_left, + &mut enc, + channels, + ); + let packet = enc.finish().expect("fits").to_vec(); + + let mut dec = range::Decoder::new(&packet); + let intra = dec.bit_logp(3); + unquant_coarse(0, BANDS, &mut dec_old, intra, &mut dec, channels, lm); + unquant_fine(0, BANDS, &mut dec_old, &fine_quant, &mut dec, channels); + let bits_left = bytes as i32 * 8 - dec.tell() as i32; + unquant_finalise( + 0, + BANDS, + &mut dec_old, + &fine_quant, + &fine_priority, + bits_left, + &mut dec, + channels, + ); + assert_eq!( + &dec_old[..channels * BANDS], + &enc_old[..channels * BANDS], + "frame {frame}" + ); + if bytes >= 100 { + for (i, (&q, &t)) in enc_old.iter().zip(&target).take(channels * BANDS).enumerate() { + assert!((q - t).abs() <= 0.5 + 1e-4, "band {i}: {q} for {t}"); + } + } + } + } + } +} diff --git a/kodecs-opus/src/safe/celt/fft.rs b/kodecs-opus/src/safe/celt/fft.rs index 50c8e21e..82c120e0 100644 --- a/kodecs-opus/src/safe/celt/fft.rs +++ b/kodecs-opus/src/safe/celt/fft.rs @@ -38,7 +38,6 @@ impl Cpx { pub(super) struct FftState { pub nfft: usize, /// The forward transform's normalization, which only the encoder's MDCT applies. - #[allow(dead_code, reason = "the forward FFT uses this scale")] pub scale: f32, /// How many times this size halves the largest, whose twiddles every size shares; -1 for /// the largest itself. diff --git a/kodecs-opus/src/safe/celt/math.rs b/kodecs-opus/src/safe/celt/math.rs index 970cb277..c70a1ffb 100644 --- a/kodecs-opus/src/safe/celt/math.rs +++ b/kodecs-opus/src/safe/celt/math.rs @@ -57,6 +57,77 @@ pub(in crate::safe) fn exp2(x: f32) -> f32 { f32::from_bits(bits) } +/// libopus's `FLOAT_APPROX` base-2 logarithm: the exponent plus a degree-4 polynomial on the +/// mantissa, normalized into one of eight subranges. +#[allow(clippy::excessive_precision, reason = "libopus's coefficients, verbatim")] +pub(super) fn log2(x: f32) -> f32 { + const X_NORM: [f32; 8] = [ + 1.000000000000000000000000000, + 8.88888895511627197265625e-01, + 8.00000000000000000000000e-01, + 7.27272748947143554687500e-01, + 6.66666686534881591796875e-01, + 6.15384638309478759765625e-01, + 5.71428596973419189453125e-01, + 5.33333361148834228515625e-01, + ]; + const Y_NORM: [f32; 8] = [ + 0.0000000000000000000000000000, + 1.699250042438507080078125e-01, + 3.219280838966369628906250e-01, + 4.594316184520721435546875e-01, + 5.849624872207641601562500e-01, + 7.004396915435791015625000e-01, + 8.073549270629882812500000e-01, + 9.068905711174011230468750e-01, + ]; + const A0: f32 = 8.74628424644470214843750000e-02; + const A1: f32 = 1.357829570770263671875000000000; + const A2: f32 = -6.3897705078125000000000000e-01; + const A3: f32 = 4.01971250772476196289062500e-01; + const A4: f32 = -2.8415444493293762207031250e-01; + let bits = x.to_bits(); + let integer = (bits >> 23) as i32 - 127; + let bits = (bits as i32).wrapping_sub(((integer as u32) << 23) as i32) as u32; + let range = ((bits >> 20) & 0x7) as usize; + let m = f32::from_bits(bits) * X_NORM[range] - 1.0625; + let poly = A0 + m * (A1 + m * (A2 + m * (A3 + m * A4))); + integer as f32 + poly + Y_NORM[range] +} + +/// `atan(x) * 2/pi` for `x` in [0, 1], a degree-15 odd polynomial. +#[allow(clippy::excessive_precision, reason = "libopus's coefficients, verbatim")] +fn atan_norm(x: f32) -> f32 { + const TWO_OVER_PI: f32 = std::f32::consts::FRAC_2_PI; + const A03: f32 = -3.3331659436225891113281250000e-01; + const A05: f32 = 1.99627041816711425781250000000e-01; + const A07: f32 = -1.3976582884788513183593750000e-01; + const A09: f32 = 9.79423448443412780761718750000e-02; + const A11: f32 = -5.7773590087890625000000000000e-02; + const A13: f32 = 2.30401363223791122436523437500e-02; + const A15: f32 = -4.3554059229791164398193359375e-03; + let x_sq = x * x; + TWO_OVER_PI + * (x + x * x_sq * (A03 + x_sq * (A05 + x_sq * (A07 + x_sq * (A09 + x_sq * (A11 + x_sq * (A13 + x_sq * A15))))))) +} + +/// `atan2(y, x) * 2/pi` for nonnegative `y` and `x`, zero when both are tiny. +pub(super) fn atan2p_norm(y: f32, x: f32) -> f32 { + if x * x + y * y < 1e-18 { + return 0.0; + } + if y < x { + atan_norm(y / x) + } else { + 1.0 - atan_norm(x / y) + } +} + +/// `floor(x)` as C evaluates it on a float: in double precision, then truncated to an int. +pub(super) fn floor_int(x: f32) -> i32 { + f64::from(x).floor() as i32 +} + /// Multiply two Q15 values with rounding, as the bit-exact `FRAC_MUL16`. fn frac_mul16(a: i32, b: i32) -> i32 { (16384 + i32::from(a as i16) * i32::from(b as i16)) >> 15 diff --git a/kodecs-opus/src/safe/celt/mdct.rs b/kodecs-opus/src/safe/celt/mdct.rs index 2ae91b21..105c35d6 100644 --- a/kodecs-opus/src/safe/celt/mdct.rs +++ b/kodecs-opus/src/safe/celt/mdct.rs @@ -1,4 +1,5 @@ -//! The inverse MDCT with windowed overlap-add, ported from libopus 1.6.1's celt/mdct.c. +//! The forward MDCT and the inverse with windowed overlap-add, ported from libopus 1.6.1's +//! celt/mdct.c. //! Copyright (c) 2007-2008 CSIRO, 2007-2008 Xiph.Org Foundation. use super::fft::{fft_impl, Cpx}; @@ -70,6 +71,73 @@ pub(super) fn backward(input: &[f32], stride: usize, out: &mut [f32], shift: usi } } +/// Window and transform the `(1920 >> shift) / 2 + OVERLAP` samples of `input` into +/// `(1920 >> shift) / 2` coefficients at `out[0], out[stride], ...`, scaled by `4 / N`, as +/// libopus's `clt_mdct_forward` does. +pub(super) fn forward(input: &[f32], out: &mut [f32], shift: usize, stride: usize) { + let mut n = MAX_N; + let mut trig = &MDCT_TWIDDLES[..]; + for _ in 0..shift { + n >>= 1; + trig = &trig[n..]; + } + let n2 = n >> 1; + let n4 = n >> 2; + let state = &FFT_STATES[shift]; + + // Consider the input as four blocks [a, b, c, d]: window, shuffle, and fold them. + let mut folded = [0.0f32; MAX_N / 2]; + let edge = OVERLAP.div_ceil(4); + for i in 0..n4 { + let x1 = OVERLAP / 2 + 2 * i; + let x2 = n2 - 1 + OVERLAP / 2 - 2 * i; + let (re, im) = if i < edge { + // The real part is -d-cR, the imaginary -b+aR. + let w1 = WINDOW[OVERLAP / 2 + 2 * i]; + let w2 = WINDOW[OVERLAP / 2 - 1 - 2 * i]; + ( + input[x1 + n2] * w2 + input[x2] * w1, + input[x1] * w1 - input[x2 - n2] * w2, + ) + } else if i < n4 - edge { + // The real part is a-bR, the imaginary -c-dR, unwindowed. + (input[x2], input[x1]) + } else { + let k = i - (n4 - edge); + let w1 = WINDOW[2 * k]; + let w2 = WINDOW[OVERLAP - 1 - 2 * k]; + ( + -(input[x1 - n2] * w1) + input[x2] * w2, + input[x1] * w2 + input[x2 + n2] * w1, + ) + }; + folded[2 * i] = re; + folded[2 * i + 1] = im; + } + + // Pre-rotate and scale, in bit-reversed order for the FFT. + let mut scratch = [Cpx::default(); MAX_N / 4]; + for i in 0..n4 { + let (t0, t1) = (trig[i], trig[n4 + i]); + let (re, im) = (folded[2 * i], folded[2 * i + 1]); + let yr = re * t0 - im * t1; + let yi = im * t0 + re * t1; + scratch[state.bitrev[i] as usize] = Cpx { + r: yr * state.scale, + i: yi * state.scale, + }; + } + let scratch = &mut scratch[..n4]; + fft_impl(state, scratch); + + // Post-rotate, writing from both ends. + for (i, value) in scratch.iter().enumerate() { + let (t0, t1) = (trig[i], trig[n4 + i]); + out[2 * stride * i] = value.i * t1 - value.r * t0; + out[stride * (n2 - 1) - 2 * stride * i] = value.r * t1 + value.i * t0; + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/kodecs-opus/src/safe/celt/mod.rs b/kodecs-opus/src/safe/celt/mod.rs index 2c9f8415..96b31e6d 100644 --- a/kodecs-opus/src/safe/celt/mod.rs +++ b/kodecs-opus/src/safe/celt/mod.rs @@ -1,4 +1,5 @@ -//! The CELT decoder and its packet loss concealment, ported from libopus 1.6.1's float build. +//! The CELT encoder, and the decoder with its packet loss concealment, ported from libopus +//! 1.6.1's float build. //! Copyright (c) 2007-2008 CSIRO, 2007-2010 Xiph.Org Foundation, and 2008 Gregory Maxwell. //! //! Only the standard 48 kHz mode with 2.5 ms short blocks exists here, as in libopus without @@ -6,8 +7,15 @@ //! scalar C build without floating-point contraction bit for bit. mod bands; +mod coder; +mod comb; mod cwrs; mod decoder; +#[allow( + dead_code, + reason = "the safe Opus encoder (quest/m1/opus-safe/encoder.md) will drive it" +)] +mod encoder; mod energy; mod fft; mod lpc; @@ -41,8 +49,11 @@ const DECODE_BUFFER_SIZE: usize = 2048; const LPC_ORDER: usize = 24; /// The shortest comb filter period. const COMBFILTER_MINPERIOD: usize = 15; +/// The most bytes an Opus frame codes. +const MAX_FRAME_BYTES: usize = 1275; /// Spreading strength for the folded and quantized spectrum. const SPREAD_NONE: usize = 0; +const SPREAD_LIGHT: usize = 1; const SPREAD_NORMAL: usize = 2; const SPREAD_AGGRESSIVE: usize = 3; diff --git a/kodecs-opus/src/safe/celt/pitch.rs b/kodecs-opus/src/safe/celt/pitch.rs index ed573aaf..ada0e269 100644 --- a/kodecs-opus/src/safe/celt/pitch.rs +++ b/kodecs-opus/src/safe/celt/pitch.rs @@ -1,5 +1,5 @@ -//! Pitch search for packet loss concealment, and the correlation kernels it shares with -//! linear prediction, from libopus's celt/pitch.c and celt/pitch.h. +//! Pitch search for the prefilter and packet loss concealment, and the correlation kernels it +//! shares with linear prediction, from libopus's celt/pitch.c and celt/pitch.h. //! Copyright (c) 2007-2008 CSIRO and 2007-2009 Xiph.Org Foundation. use super::lpc; @@ -242,3 +242,111 @@ pub(super) fn pitch_search(x_lp: &[f32], y: &[f32], len: usize, max_pitch: usize }; (2 * best_pitch[0] as isize - offset) as usize } + +/// The normalized correlation of a lag with energy `yy` against a signal with energy `xx`. +fn compute_pitch_gain(xy: f32, xx: f32, yy: f32) -> f32 { + xy / math::sqrt(1.0 + xx * yy) +} + +/// Refine the pitch period `t0` that `pitch_search` found, checking whether a submultiple +/// of it correlates almost as well, as when the search locked onto a multiple of the true +/// period. `x` holds `max_period` samples of history and then `n` of the frame, all at half +/// rate; periods are at full rate. Returns the period and its gain. +pub(super) fn remove_doubling( + x: &[f32], + max_period: usize, + min_period: usize, + n: usize, + t0: usize, + prev_period: usize, + prev_gain: f32, +) -> (usize, f32) { + const SECOND_CHECK: [usize; 16] = [0, 0, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2]; + let min_period0 = min_period; + let max_period = max_period / 2; + let min_period = min_period / 2; + let prev_period = prev_period / 2; + let n = n / 2; + let t0 = (t0 / 2).min(max_period - 1); + // The frame starts at `base`; `lag(t)` is it delayed by `t`. + let base = max_period; + let frame = &x[base..base + n]; + let lag = |t: usize| &x[base - t..]; + + let xx = inner_prod(frame, frame); + let xy = inner_prod(frame, lag(t0)); + let mut yy_lookup = [0.0f32; super::MAX_PERIOD / 2 + 1]; + yy_lookup[0] = xx; + let mut yy = xx; + for i in 1..=max_period { + yy = yy + x[base - i] * x[base - i] - x[base + n - i] * x[base + n - i]; + yy_lookup[i] = math::max(0.0, yy); + } + let yy = yy_lookup[t0]; + let mut best_xy = xy; + let mut best_yy = yy; + let g0 = compute_pitch_gain(xy, xx, yy); + let mut g = g0; + let mut t = t0; + // Look for any pitch at t0/k. + for (k, &second_check) in SECOND_CHECK.iter().enumerate().skip(2) { + let t1 = (2 * t0 + k) / (2 * k); + if t1 < min_period { + break; + } + // Look for another strong correlation at t1b. + let t1b = if k == 2 { + if t1 + t0 > max_period { + t0 + } else { + t0 + t1 + } + } else { + (2 * second_check * t0 + k) / (2 * k) + }; + let xy = 0.5 * (inner_prod(frame, lag(t1)) + inner_prod(frame, lag(t1b))); + let yy = 0.5 * (yy_lookup[t1] + yy_lookup[t1b]); + let g1 = compute_pitch_gain(xy, xx, yy); + let cont = if t1.abs_diff(prev_period) <= 1 { + prev_gain + } else if t1.abs_diff(prev_period) <= 2 && 5 * k * k < t0 { + 0.5 * prev_gain + } else { + 0.0 + }; + // Bias against very short periods, which short-term correlation fakes. + let thresh = if t1 < 3 * min_period { + math::max(0.4, 0.85 * g0 - cont) + } else if t1 < 2 * min_period { + math::max(0.5, 0.9 * g0 - cont) + } else { + math::max(0.3, 0.7 * g0 - cont) + }; + if g1 > thresh { + best_xy = xy; + best_yy = yy; + t = t1; + g = g1; + } + } + let best_xy = math::max(0.0, best_xy); + let mut pg = if best_yy <= best_xy { + 1.0 + } else { + best_xy / (best_yy + 1.0) + }; + + let xcorr: [f32; 3] = std::array::from_fn(|k| inner_prod(frame, lag(t + k - 1))); + let offset = if xcorr[2] - xcorr[0] > 0.7 * (xcorr[1] - xcorr[0]) { + 1 + } else if xcorr[0] - xcorr[2] > 0.7 * (xcorr[1] - xcorr[2]) { + -1 + } else { + 0 + }; + if pg > g { + pg = g; + } + let period = (2 * t).saturating_add_signed(offset).max(min_period0); + (period, pg) +} diff --git a/kodecs-opus/src/safe/celt/rate.rs b/kodecs-opus/src/safe/celt/rate.rs index 73e555c5..7515d009 100644 --- a/kodecs-opus/src/safe/celt/rate.rs +++ b/kodecs-opus/src/safe/celt/rate.rs @@ -79,7 +79,24 @@ pub(super) fn init_caps(lm: usize, channels: usize) -> [i32; BANDS] { }) } -/// How a frame's bits divide between bands, as decoded. +/// The encoder's choices for the allocation's side information. +pub(super) struct Choices { + /// The previous frame's coded bands, from which skipping takes hysteresis. + pub prev_coded_bands: usize, + /// The last band with signal worth coding. + pub signal_bandwidth: usize, + /// The first band to code with intensity stereo. + pub intensity: usize, + pub dual_stereo: bool, +} + +/// Which way the allocation's skip, intensity, and dual stereo decisions go. +pub(super) enum Signal<'c, 'a> { + Decode(&'c mut range::Decoder<'a>), + Encode(&'c mut range::Encoder<'a>, Choices), +} + +/// How a frame's bits divide between bands, as coded. pub(super) struct Allocation { /// One past the last band coded with PVQ. pub coded_bands: usize, @@ -96,11 +113,11 @@ pub(super) struct Allocation { pub fine_priority: [i32; BANDS], } -/// Interpolate the allocation tables to `total` eighth bits, decoding the skip, intensity, -/// and dual stereo parameters. +/// Interpolate the allocation tables to `total` eighth bits, coding the skip, intensity, and +/// dual stereo parameters. #[allow( clippy::too_many_arguments, - reason = "mirrors libopus's clt_compute_allocation, which the decoder calls once" + reason = "mirrors libopus's clt_compute_allocation, which encoder and decoder call once" )] pub(super) fn compute_allocation( start: usize, @@ -111,7 +128,7 @@ pub(super) fn compute_allocation( total: i32, channels: usize, lm: usize, - dec: &mut range::Decoder, + signal: Signal, ) -> Allocation { let c = channels as i32; let lm_i = lm as i32; @@ -220,7 +237,7 @@ pub(super) fn compute_allocation( channels, lm, } - .run(dec) + .run(signal) } /// The inputs of libopus's `interp_bits2pulses`. @@ -241,7 +258,7 @@ struct Interp<'a> { } impl Interp<'_> { - fn run(self, dec: &mut range::Decoder) -> Allocation { + fn run(self, mut signal: Signal) -> Allocation { let Self { start, end, @@ -322,7 +339,24 @@ impl Interp<'_> { // Only a band above its threshold codes a skip decision; others are force-skipped, // which guarantees bits for the flag. if band_bits >= thresh[j].max(alloc_floor + (1 << BITRES)) { - if dec.bit_logp(1) { + let keep = match &mut signal { + Signal::Decode(dec) => dec.bit_logp(1), + Signal::Encode(enc, choices) => { + // The only choice here the bitstream doesn't dictate: hysteresis keeps + // bands from flickering in and out, short of folding too deep. + let depth_threshold = match coded_bands { + 18.. if j < choices.prev_coded_bands => 7, + 18.. => 9, + _ => 0, + }; + let keep = coded_bands <= start + 2 + || (band_bits > (depth_threshold * band_width) << lm << BITRES >> 4 + && j <= choices.signal_bandwidth); + enc.bit_logp(keep, 1); + keep + } + }; + if keep { break; } // A bit was spent to skip this band. @@ -345,16 +379,28 @@ impl Interp<'_> { coded_bands -= 1; } - let intensity = if intensity_rsv > 0 { - start + dec.uint((coded_bands + 1 - start) as u32) as usize - } else { - 0 + let intensity_total = (coded_bands + 1 - start) as u32; + let intensity = match &mut signal { + _ if intensity_rsv <= 0 => 0, + Signal::Decode(dec) => start + dec.uint(intensity_total) as usize, + Signal::Encode(enc, choices) => { + let intensity = choices.intensity.min(coded_bands); + enc.uint((intensity - start) as u32, intensity_total); + intensity + } }; if intensity <= start { total += dual_stereo_rsv; dual_stereo_rsv = 0; } - let dual_stereo = dual_stereo_rsv > 0 && dec.bit_logp(1); + let dual_stereo = dual_stereo_rsv > 0 + && match &mut signal { + Signal::Decode(dec) => dec.bit_logp(1), + Signal::Encode(enc, choices) => { + enc.bit_logp(choices.dual_stereo, 1); + choices.dual_stereo + } + }; // Allocate the remaining bits. let mut left = total - psum; diff --git a/kodecs-opus/src/safe/celt/tables.rs b/kodecs-opus/src/safe/celt/tables.rs index a88d2236..de32cb93 100644 --- a/kodecs-opus/src/safe/celt/tables.rs +++ b/kodecs-opus/src/safe/celt/tables.rs @@ -195,6 +195,22 @@ pub(super) const CACHE_CAPS: [u8; 168] = [ 198, 187, 187, 175, 140, 66, 40, ]; +/// The inverse CDF of the allocation trim. +pub(super) const TRIM_ICDF: [u8; 11] = [126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0]; +/// The inverse CDF of the spreading decision. +pub(super) const SPREAD_ICDF: [u8; 4] = [25, 23, 2, 0]; +/// The inverse CDF of the comb filter's tapset. +pub(super) const TAPSET_ICDF: [u8; 3] = [2, 1, 0]; + +/// Time-frequency resolution changes, indexed by LM and then by +/// `4 * transient + 2 * tf_select + per_band_flag`. +pub(super) const TF_SELECT_TABLE: [[i8; 8]; 4] = [ + [0, -1, 0, -1, 0, -1, 0, -1], + [0, -1, 0, -2, 1, 0, 1, -1], + [0, -2, 0, -3, 2, 0, 1, -1], + [0, -2, 0, -3, 3, 0, 1, -1], +]; + /// The de-emphasis filter coefficient. pub(super) const PREEMPH: f32 = 0.85000610; diff --git a/kodecs-opus/src/safe/celt/vq.rs b/kodecs-opus/src/safe/celt/vq.rs index fcc6acd3..9191ec7f 100644 --- a/kodecs-opus/src/safe/celt/vq.rs +++ b/kodecs-opus/src/safe/celt/vq.rs @@ -1,12 +1,15 @@ -//! Pyramid vector dequantization and spreading, from libopus's celt/vq.c. +//! Pyramid vector quantization and spreading, from libopus's celt/vq.c. //! Copyright (c) 2007-2008 CSIRO and 2007-2009 Xiph.Org Foundation. use super::cwrs; use super::math; use super::pitch::inner_prod; -use super::{MAX_FRAME, SPREAD_NONE}; +use super::{MAX_LM, SPREAD_NONE}; use crate::safe::range; +/// The widest band a codebook codes, band 20 at 20 ms. +const MAX_N: usize = 22 << MAX_LM; + /// Rotate pairs `stride` apart by the angle whose cosine and sine are `c` and `s`, forward /// then back, as one spreading pass. fn exp_rotation1(x: &mut [f32], stride: usize, c: f32, s: f32) { @@ -92,17 +95,156 @@ pub(super) fn alg_unquant( dec: &mut range::Decoder, gain: f32, ) -> u32 { - let n = x.len(); - let mut iy = [0i32; MAX_FRAME]; - let iy = &mut iy[..n]; + let mut iy = [0i32; MAX_N]; + let iy = &mut iy[..x.len()]; let ryy = cwrs::decode_pulses(iy, k, dec); - // Normalize the integer codeword. + normalise_residual(iy, x, ryy, gain); + exp_rotation(x, -1, b, k, spread); + extract_collapse_mask(iy, b) +} + +/// Encode `x` as its nearest codeword of `k` pulses, returning the collapse mask of its `b` +/// blocks. With `resynth`, `x` becomes the decoded codeword scaled to `gain`, as the decoder +/// sees it. +#[allow( + clippy::too_many_arguments, + reason = "mirrors libopus's alg_quant, which quant_partition calls once" +)] +pub(super) fn alg_quant( + x: &mut [f32], + k: usize, + spread: usize, + b: usize, + enc: &mut range::Encoder, + gain: f32, + resynth: bool, +) -> u32 { + assert!(k > 0 && x.len() > 1, "a codeword needs a pulse and two dimensions"); + let mut iy = [0i32; MAX_N]; + let iy = &mut iy[..x.len()]; + exp_rotation(x, 1, b, k, spread); + let yy = pvq_search(x, iy, k); + let collapse_mask = extract_collapse_mask(iy, b); + cwrs::encode_pulses(iy, k, enc); + if resynth { + normalise_residual(iy, x, yy, gain); + exp_rotation(x, -1, b, k, spread); + } + collapse_mask +} + +/// Scale the integer codeword `iy`, of squared norm `ryy`, into `x` with norm `gain`. +fn normalise_residual(iy: &[i32], x: &mut [f32], ryy: f32, gain: f32) { let g = math::rsqrt(ryy) * gain; - for (x, &y) in x.iter_mut().zip(iy.iter()) { + for (x, &y) in x.iter_mut().zip(iy) { *x = y as f32 * g; } - exp_rotation(x, -1, b, k, spread); - extract_collapse_mask(iy, b) +} + +/// Find the codeword of `k` pulses in `iy` nearest `x` in angle, returning its squared norm. +/// `x` is left holding its absolute values. +fn pvq_search(x: &mut [f32], iy: &mut [i32], k: usize) -> f32 { + const EPSILON: f32 = 1e-15; + let n = x.len(); + let mut y = [0.0f32; MAX_N]; + let mut signx = [false; MAX_N]; + // Get rid of the sign. + for j in 0..n { + signx[j] = x[j] < 0.0; + x[j] = x[j].abs(); + iy[j] = 0; + } + let mut xy = 0.0f32; + let mut yy = 0.0f32; + let mut pulses_left = k as i32; + + // Pre-search by projecting onto the pyramid. + if k > n >> 1 { + let mut sum = 0.0f32; + for &x in &x[..n] { + sum += x; + } + // Written as libopus does so infinities and NaNs (64 approximating infinity) also + // fall back to a single pulse at 0 rather than allocating too many. + if !(sum > EPSILON && sum < 64.0) { + x[0] = 1.0; + x[1..].fill(0.0); + sum = 1.0; + } + // K plus less than one can never yield more than K pulses. + let rcp = (k as f32 + 0.8) * (1.0 / sum); + for j in 0..n { + iy[j] = math::floor_int(rcp * x[j]); + y[j] = iy[j] as f32; + yy += y[j] * y[j]; + xy += x[j] * y[j]; + y[j] *= 2.0; + pulses_left -= iy[j]; + } + } + debug_assert!(pulses_left >= 0); + + // This should never happen, but just in case (as on silence) fill the first bin. + if pulses_left > n as i32 + 3 { + let tmp = pulses_left as f32; + yy += tmp * tmp; + yy += tmp * y[0]; + iy[0] += pulses_left; + pulses_left = 0; + } + + for _ in 0..pulses_left { + // The squared magnitude term gets added anyway, so add it outside the loop. + yy += 1.0; + // Maximize Rxy/sqrt(Ryy), comparing without division; y holds twice each pulse. + let score = |j: usize| { + let rxy = xy + x[j]; + (rxy * rxy, yy + y[j]) + }; + let (mut best_num, mut best_den) = score(0); + let mut best_id = 0; + for j in 1..n { + let (num, den) = score(j); + if best_den * num > den * best_num { + best_den = den; + best_num = num; + best_id = j; + } + } + xy += x[best_id]; + yy += y[best_id]; + y[best_id] += 2.0; + iy[best_id] += 1; + } + + // Put the original sign back. + for (iy, &negative) in iy.iter_mut().zip(&signx) { + if negative { + *iy = -*iy; + } + } + yy +} + +/// The angle between the mid and side of `x` and `y` (or between `x` and `y` themselves when +/// not `stereo`), with a quarter turn at 2^30. +pub(super) fn stereo_itheta(x: &[f32], y: &[f32], stereo: bool) -> i32 { + let (emid, eside) = if stereo { + let mut emid = 0.0f32; + let mut eside = 0.0f32; + for (&x, &y) in x.iter().zip(y) { + let m = x + y; + let s = x - y; + emid += m * m; + eside += s * s; + } + (emid, eside) + } else { + (inner_prod(x, x), inner_prod(y, y)) + }; + let mid = math::sqrt(emid); + let side = math::sqrt(eside); + math::floor_int(0.5 + 65536.0 * 16384.0 * math::atan2p_norm(side, mid)) } /// Scale `x` to norm `gain`. @@ -113,3 +255,77 @@ pub(super) fn renormalise(x: &mut [f32], gain: f32) { *x *= g; } } + +#[cfg(test)] +mod tests { + use super::super::{SPREAD_AGGRESSIVE, SPREAD_LIGHT, SPREAD_NORMAL}; + use super::*; + + /// Encoding finds a codeword of exactly `k` pulses, and decoding it reproduces the + /// encoder's resynthesis and collapse mask bit for bit, across spreads and block counts. + #[test] + fn quantized_vectors_decode_to_the_encoders_resynthesis() { + let mut seed = 1u32; + for &(n, k, blocks) in &[ + (2, 1, 1), + (4, 3, 2), + (8, 5, 1), + (16, 6, 4), + (32, 4, 8), + (96, 2, 2), + (176, 1, 8), + ] { + for spread in [SPREAD_NONE, SPREAD_LIGHT, SPREAD_NORMAL, SPREAD_AGGRESSIVE] { + let mut x = [0.0f32; MAX_N]; + let x = &mut x[..n]; + for x in x.iter_mut() { + seed = math::lcg_rand(seed); + *x = math::lcg_sample(seed); + } + renormalise(x, 1.0); + let original = x.to_vec(); + + let mut iy = [0i32; MAX_N]; + let mut abs = original.clone(); + pvq_search(&mut abs, &mut iy[..n], k); + assert_eq!(iy[..n].iter().map(|y| y.unsigned_abs() as usize).sum::(), k); + + let mut buf = [0u8; 64]; + let mut enc = range::Encoder::new(&mut buf); + let encoded_mask = alg_quant(x, k, spread, blocks, &mut enc, 1.0, true); + let packet = enc.finish().expect("fits").to_vec(); + // The resynthesis points the original's way. + let dot: f32 = x.iter().zip(&original).map(|(a, b)| a * b).sum(); + assert!(dot > 0.0, "n {n} k {k}: correlation {dot}"); + + let mut decoded = [0.0f32; MAX_N]; + let mut dec = range::Decoder::new(&packet); + let decoded_mask = alg_unquant(&mut decoded[..n], k, spread, blocks, &mut dec, 1.0); + assert_eq!(&decoded[..n], &x[..], "n {n} k {k} spread {spread}"); + assert_eq!(decoded_mask, encoded_mask); + } + } + } + + /// A vector that is a codeword of `k` pulses, scaled, searches back to that codeword. + #[test] + fn search_recovers_an_exact_codeword() { + let mut seed = 9u32; + for &(n, k) in &[(2, 1), (5, 4), (8, 8), (16, 3), (64, 5)] { + let mut codeword = [0i32; MAX_N]; + for _ in 0..k { + seed = math::lcg_rand(seed); + let at = (seed >> 16) as usize % n; + codeword[at] += if seed & 1 != 0 { 1 } else { -1 }; + } + let pulses: usize = codeword[..n].iter().map(|y| y.unsigned_abs() as usize).sum(); + let mut x = [0.0f32; MAX_N]; + for (x, &y) in x.iter_mut().zip(&codeword[..n]) { + *x = 0.37 * y as f32; + } + let mut iy = [0i32; MAX_N]; + pvq_search(&mut x[..n], &mut iy[..n], pulses); + assert_eq!(&iy[..n], &codeword[..n], "n {n} k {pulses}"); + } + } +} diff --git a/kodecs-opus/src/safe/range/encoder.rs b/kodecs-opus/src/safe/range/encoder.rs index 9b870246..49f29ff3 100644 --- a/kodecs-opus/src/safe/range/encoder.rs +++ b/kodecs-opus/src/safe/range/encoder.rs @@ -35,6 +35,8 @@ pub(crate) struct Encoder<'a> { impl<'a> Encoder<'a> { /// Start encoding into the given frame buffer. pub(crate) fn new(buf: &'a mut [u8]) -> Self { + #[cfg(feature = "ent-dump")] + eprintln!("ec_enc_init()"); Self { back: buf.len(), buf, @@ -53,6 +55,8 @@ impl<'a> Encoder<'a> { } fn write_front(&mut self, byte: u8) { + #[cfg(feature = "ent-dump")] + eprintln!("ec_write_byte(0x{byte:x} @ 0x{:x})", self.front); if self.front == self.back { self.error.get_or_insert(Error::BufferTooSmall); return; @@ -62,6 +66,8 @@ impl<'a> Encoder<'a> { } fn write_back(&mut self, byte: u8) { + #[cfg(feature = "ent-dump")] + eprintln!("ec_write_byte_at_end(0x{byte:x} @ 0x{:x})", self.buf.len() - self.back); if self.front == self.back { self.error.get_or_insert(Error::BufferTooSmall); return; @@ -96,6 +102,8 @@ impl<'a> Encoder<'a> { /// Encode a symbol with the given cumulative frequency bounds and total. pub(crate) fn encode(&mut self, bounds: Range, total: u32) { + #[cfg(feature = "ent-dump")] + eprintln!("ec_encode({}, {}, {total})", bounds.start, bounds.end); assert!(bounds.start < bounds.end && bounds.end <= total); let unit = self.state.width / total; assert_ne!(unit, 0, "frequency total exceeds the coding interval"); @@ -110,12 +118,25 @@ impl<'a> Encoder<'a> { /// Encode a symbol in a distribution with a power-of-two total frequency. pub(crate) fn encode_bin(&mut self, bounds: Range, bits: u32) { + #[cfg(feature = "ent-dump")] + eprintln!("ec_encode_bin({}, {}, {bits})", bounds.start, bounds.end); assert!(bits < u32::BITS); - self.encode(bounds, 1 << bits); + let total = 1 << bits; + assert!(bounds.start < bounds.end && bounds.end <= total); + let unit = self.state.width >> bits; + if bounds.start > 0 { + self.value += self.state.width - unit * (total - bounds.start); + self.state.width = unit * (bounds.end - bounds.start); + } else { + self.state.width -= unit * (total - bounds.end); + } + self.normalize(); } /// Encode a bit whose probability of being set is 2 to the power of `-logp`. pub(crate) fn bit_logp(&mut self, bit: bool, logp: u32) { + #[cfg(feature = "ent-dump")] + eprintln!("ec_enc_bit_logp({}, {logp})", u8::from(bit)); assert!(logp < u32::BITS); let split = self.state.width >> logp; self.state.width -= split; @@ -127,7 +148,12 @@ impl<'a> Encoder<'a> { } /// Encode from a descending inverse CDF ending in zero, in units of 2 to the power of `-bits`. - pub(crate) fn icdf(&mut self, index: usize, table: &[impl Copy + Into], bits: u32) { + pub(crate) fn icdf>(&mut self, index: usize, table: &[T], bits: u32) { + #[cfg(feature = "ent-dump")] + eprintln!( + "ec_enc_icdf({index}, {:?}, {bits})", + table[..=index].iter().map(|&v| v.into()).collect::>() + ); assert!(bits < u32::BITS); let unit = self.state.width >> bits; assert_ne!(unit, 0, "table precision exceeds the coding interval"); @@ -145,6 +171,8 @@ impl<'a> Encoder<'a> { /// Encode a uniform integer below `total`. pub(crate) fn uint(&mut self, value: u32, total: u32) { + #[cfg(feature = "ent-dump")] + eprintln!("ec_enc_uint({value}, {total})"); assert!(total > 1 && value < total); let raw_bits = ilog(total - 1).saturating_sub(UINT_BITS); let high = value >> raw_bits; @@ -156,6 +184,8 @@ impl<'a> Encoder<'a> { /// Encode between 1 and 25 raw bits at the back of the frame, low bit first. pub(crate) fn bits(&mut self, value: u32, count: u32) { + #[cfg(feature = "ent-dump")] + eprintln!("ec_enc_bits({value}, {count})"); assert!((1..=MAX_RAW_BITS).contains(&count) && value <= low_mask(count)); if self.raw_bits + count > u32::BITS { while self.raw_bits >= SYMBOL_BITS { @@ -171,6 +201,8 @@ impl<'a> Encoder<'a> { /// Overwrite leading bits reserved with a uniform distribution. pub(crate) fn patch_initial_bits(&mut self, value: u8, bits: u32) { + #[cfg(feature = "ent-dump")] + eprintln!("ec_enc_patch_initial_bits({value}, {bits})"); let value = u32::from(value); assert!(bits <= SYMBOL_BITS && value <= low_mask(bits)); let shift = SYMBOL_BITS - bits; @@ -189,6 +221,8 @@ impl<'a> Encoder<'a> { /// Shorten the frame buffer, moving any flushed raw bytes to the new end. pub(crate) fn shrink(&mut self, len: usize) { + #[cfg(feature = "ent-dump")] + eprintln!("ec_enc_shrink({len})"); let raw_bytes = self.buf.len() - self.back; assert!(len >= self.front + raw_bytes && len <= self.buf.len()); self.buf.copy_within(self.back.., len - raw_bytes); @@ -196,6 +230,16 @@ impl<'a> Encoder<'a> { self.back = len - raw_bytes; } + /// Count every bit of the frame as used, as when it codes silence. + pub(crate) fn skip_to_end(&mut self) { + self.state.whole_bits += 8 * self.buf.len() as u32 - self.tell(); + } + + /// The frame size in bytes. + pub(crate) fn len(&self) -> usize { + self.buf.len() + } + /// The number of range bytes already written at the front. pub(crate) fn range_bytes(&self) -> usize { self.front @@ -241,6 +285,16 @@ impl<'a> Encoder<'a> { &mut self.buf[..self.front] } + /// The raw bytes flushed at the back so far. + pub(crate) fn raw_written(&self) -> &[u8] { + &self.buf[self.back..] + } + + /// The raw bytes flushed at the back so far, to restore after a [`Self::restore`]. + pub(crate) fn raw_written_mut(&mut self) -> &mut [u8] { + &mut self.buf[self.back..] + } + /// The current range width, reported as the final range after encoding. pub(crate) fn range(&self) -> u32 { self.state.width @@ -294,6 +348,8 @@ impl<'a> Encoder<'a> { } self.buf[last] |= self.raw as u8; } + #[cfg(feature = "ent-dump")] + eprintln!("ec_enc_done(): {}", hex::encode(&*self.buf)); Ok(self.buf) } } diff --git a/kodecs-opus/src/safe/range/mod.rs b/kodecs-opus/src/safe/range/mod.rs index 3899d395..b043f85e 100644 --- a/kodecs-opus/src/safe/range/mod.rs +++ b/kodecs-opus/src/safe/range/mod.rs @@ -2,14 +2,17 @@ //! Copyright (c) 2001-2011 Timothy B. Terriberry and 2008-2009 Xiph.Org Foundation. mod decoder; -#[allow(dead_code, reason = "the safe encoder will use this range coder")] +#[allow( + dead_code, + reason = "the safe Opus encoder (quest/m1/opus-safe/encoder.md) will drive it" +)] mod encoder; #[cfg(test)] mod tests; pub(crate) use decoder::Decoder; -pub(crate) use encoder::Encoder; +pub(crate) use encoder::{Checkpoint, Encoder}; const SYMBOL_BITS: u32 = u8::BITS; const CODE_TOP: u32 = 1 << (u32::BITS - 1); diff --git a/quest/m1/opus-safe/encoder-celt.md b/quest/m1/opus-safe/encoder-celt.md deleted file mode 100644 index c3b52be9..00000000 --- a/quest/m1/opus-safe/encoder-celt.md +++ /dev/null @@ -1,44 +0,0 @@ -# [L] Port the libopus 1.6.1 CELT encoder to safe Rust - -## Goal - -`kodecs-opus`'s `#![forbid(unsafe_code)]` libopus 1.6.1 module tree includes a -complete, idiomatic safe-Rust port of libopus 1.6.1's float CELT encoder. -Verified in `kodecs-opus` tests over single-frame CELT durations (2.5, 5, 10, -and 20 ms, mono and stereo, VBR and CBR), its encoded packets round-trip -cleanly through `kodecs_opus::Decoder` (already bit-exact to C libopus 1.6.1) -within target bitrate and high audio quality (SNR against input PCM), and its -internal DSP sub-stages match the C 1.6.1 reference logic. Byte-exact -packet-for-packet parity against C libopus 1.6.1's top-level -`opus_encode_float` (which depends on `opus_encoder.c` preprocessing, tonality -analysis, and multi-frame repacketization such as `celt-40ms`) is verified in -[encoder](/quest/m1/opus-safe/encoder.md). - -## Plan - -- Port libopus 1.6.1's non-ML float CELT encode path (`celt/celt_encoder.c` - and the encode paths of `celt/bands.c`, `celt/cwrs.c`, `celt/laplace.c`, - `celt/mdct.c`, `celt/pitch.c`, `celt/quant_bands.c`, `celt/rate.c`, - `celt/vq.c`, `celt/celt_lpc.c`), reusing the range encoder, tables, FFT/MDCT, - and shared helpers already in the safe 1.6.1 module tree. -- Include `ent-dump` instrumentation for the CELT prefilter state and range - encoder (gated behind `#[cfg(feature = "ent-dump")]`) so - [encoder](/quest/m1/opus-safe/encoder.md) preserves the full documented - trace when deleting the c2rust encoder. -- Use owned structs and stack scratch buffers (no per-frame heap allocations) - and preserve scalar C 1.6.1 float evaluation order and `lrintf` - round-to-nearest-even semantics so [encoder](/quest/m1/opus-safe/encoder.md) - can match C 1.6.1 packet for packet once wired to `opus_encoder.c` and - `analysis.c`. -- Verify inside `kodecs-opus` unit tests: - - Round-trip single-frame CELT packets (2.5, 5, 10, 20 ms; mono and stereo; - bandlimited tones and noise; CBR and VBR) through `kodecs_opus::Decoder` - and check decoded SNR, frame duration, and byte budget. - - Unit-test CELT encode leaves (PVQ, coarse/fine energy quantization, - transient detection, pitch/prefilter, stereo folding) directly. - - Defer top-level `opus_encode_float` checks (DC rejection, delay buffer, - default-complexity tonality analysis, bandwidth/bitrate split, and - multi-frame repacketization like `celt-40ms`) to - [encoder](/quest/m1/opus-safe/encoder.md). - -Public API: none. Wire: none. diff --git a/quest/m1/opus-safe/encoder.md b/quest/m1/opus-safe/encoder.md index 2490005b..e05f5a91 100644 --- a/quest/m1/opus-safe/encoder.md +++ b/quest/m1/opus-safe/encoder.md @@ -27,7 +27,10 @@ transpiled `celt/`, `silk/`, `src/`) is deleted, `kodecs-opus` uses workspace `hex` dependency) across all three documented traces (range coder, tonality analysis, and CELT prefilter state) so `--features ent-dump` keeps working without a breaking change, and delete all remaining c2rust files and - `allow(warnings)` suppressions. + `allow(warnings)` suppressions, including the `dead_code` allowances on the + safe CELT and range encoders and `safe::celt::encoder`'s + `quality_matches_the_reference_encoder` test, which compares against the + c2rust encoder. - Update `kodecs-opus/Cargo.toml` (description, `edition.workspace = true`, drop unused c2rust-only dependencies such as `num-complex` and `num-traits` if no longer needed), `kodecs-opus/src/lib.rs`, `kodecs-opus/README.md`, and @@ -48,7 +51,3 @@ transpiled `celt/`, `silk/`, `src/`) is deleted, `kodecs-opus` uses workspace Public API: none (`Encoder`, `Application`, `Signal`, `Error`, and the `ent-dump` feature are preserved; encoded packets advance from libopus 1.3.1 to wire-compatible libopus 1.6.1). Wire: none. - -## Required - -- [Port the libopus 1.6.1 CELT encoder to safe Rust](/quest/m1/opus-safe/encoder-celt.md) - safe CELT 1.6.1 encode path